hexsha
stringlengths
40
40
size
int64
19
11.4M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
3
270
max_stars_repo_name
stringlengths
5
110
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
3
270
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
9
max_issues_count
float64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
3
270
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
listlengths
1
9
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
19
11.4M
avg_line_length
float64
1.93
229k
max_line_length
int64
12
688k
alphanum_fraction
float64
0.07
0.99
matches
listlengths
1
10
71a889589946c72e471e442ba344ffbcf31aba91
1,352
cpp
C++
#76_minimum-window-substring/minimum-window-substring.cpp
o-oppang/lets-solve-algorithm
9983a112736ce48bbd309a9af16d1fd68b9420da
[ "MIT" ]
null
null
null
#76_minimum-window-substring/minimum-window-substring.cpp
o-oppang/lets-solve-algorithm
9983a112736ce48bbd309a9af16d1fd68b9420da
[ "MIT" ]
null
null
null
#76_minimum-window-substring/minimum-window-substring.cpp
o-oppang/lets-solve-algorithm
9983a112736ce48bbd309a9af16d1fd68b9420da
[ "MIT" ]
null
null
null
//Input: s = "ADOBECODEBANC", t = "ABC" //Output: "BANC" // while : "ADOBECODEBANC" // ^ ^ ^ ^^^^ class Solution { public: string minWindow(const string s, const string t) { vector<pair<size_t, size_t>> indices; //{first pos, string size} vector<string> remaining; // remaining letters std::size_t found = s.c( t ); while( found != string::npos ) { string str = t; indices.push_back({found, INT_MAX}); remaining.push_back(str); for( auto i = 0; i < remaining.size(); ++i ) { if( remaining[i].size() == 0 ) continue; auto pos = remaining[i].find_first_of( s[found]); if( pos != string::npos ) remaining[i].erase(remaining[i].begin() + pos ); if( remaining[i].size() == 0 ) { indices[i].second = found - indices[i].first + 1; } } found = s.find_first_of( t,found+1 ); } pair<size_t, size_t> minSize = {0, INT_MAX}; for( auto index : indices ) { if(index.second < minSize.second ) minSize = index; } return minSize.second == INT_MAX ? ""s : s.substr(minSize.first, minSize.second); } }; // 265 / 266 test cases passed.
33.8
90
0.492604
[ "vector" ]
71ae5b3a00d38fb63880f5d824e120b8382becb1
23,871
cpp
C++
app/src/main/cpp/filters.cpp
jongwonleee/pinata
f11065f43bddeaaf56548a8942b7f481ce9b9053
[ "Intel", "Apache-2.0" ]
1
2021-01-03T17:50:44.000Z
2021-01-03T17:50:44.000Z
app/src/main/cpp/filters.cpp
jongwonleee/pinata
f11065f43bddeaaf56548a8942b7f481ce9b9053
[ "Intel", "Apache-2.0" ]
null
null
null
app/src/main/cpp/filters.cpp
jongwonleee/pinata
f11065f43bddeaaf56548a8942b7f481ce9b9053
[ "Intel", "Apache-2.0" ]
2
2021-01-03T17:50:46.000Z
2021-01-04T12:58:23.000Z
#include "filters.h" #include <opencv2/imgproc/types_c.h> using namespace std; using namespace cv; extern "C" { void gammaCorrection(Mat &src, Mat &dst) { register int x, y, i; dst = Mat::zeros(src.size(), src.type()); uchar r, g, b; float redAverage = 0; float greenAverage = 0; float blueAverage = 0; Scalar avg = mean(src); redAverage = (float) avg[0]; greenAverage = (float) avg[1]; blueAverage = (float) avg[2]; float gammaRed = log(128.0f / 255) / log(redAverage / 255); float gammaGreen = log(128.0f / 255) / log(greenAverage / 255); float gammaBlue = log(128.0f / 255) / log(blueAverage / 255); int redLut[256]; int greenLut[256]; int blueLut[256]; for (i = 0; i < 256; i++) { redLut[i] = -1; greenLut[i] = -1; blueLut[i] = -1; } for (y = 0; y < src.rows; y++) { for (x = 0; x < src.cols; x++) { r = src.at<Vec3b>(y, x)[0]; g = src.at<Vec3b>(y, x)[1]; b = src.at<Vec3b>(y, x)[2]; if (redLut[r] == -1) redLut[r] = saturate_cast<uchar>(255.0f * powf((r / 255.0f), gammaRed)); dst.at<Vec3b>(y, x)[0] = saturate_cast<uchar>(redLut[r]); if (greenLut[g] == -1) greenLut[g] = saturate_cast<uchar>(255.0f * powf((g / 255.0f), gammaGreen)); dst.at<Vec3b>(y, x)[1] = saturate_cast<uchar>(greenLut[g]); if (blueLut[b] == -1) blueLut[b] = saturate_cast<uchar>(255.0f * powf((b / 255.0f), gammaBlue)); dst.at<Vec3b>(y, x)[2] = saturate_cast<uchar>(blueLut[b]); } } } void applyBW(cv::Mat &src, cv::Mat &dst, int val) { register int x, y; float opacity = val * 0.01f; cvtColor(src, src, CV_BGRA2BGR); dst = Mat::zeros(src.size(), src.type()); uchar grey, r, g, b,bri; for (y = 0; y < src.rows; y++) { for (x = 0; x < src.cols; x++) { r = src.at<Vec3b>(y, x)[0]; g = src.at<Vec3b>(y, x)[1]; b = src.at<Vec3b>(y, x)[2]; grey = (uchar) blackAndWhite(r, g, b); bri = saturate_cast<uchar>((0.6 * r - g * 0.4 - b * 0.4)); dst.at<Vec3b>(y, x)[0] = saturate_cast<uchar>((1 - opacity) * r + opacity * grey + opacity * bri); dst.at<Vec3b>(y, x)[1] = saturate_cast<uchar>((1 - opacity) * g + opacity * grey + opacity * bri); dst.at<Vec3b>(y, x)[2] = saturate_cast<uchar>((1 - opacity) * b + opacity * grey + opacity * bri); } } } void applyNegative(cv::Mat &src, cv::Mat &dst, int val) { register int x, y; float opacity = val * 0.01f; cvtColor(src, src, CV_BGRA2BGR); dst = Mat::zeros(src.size(), src.type()); uchar r, g, b; for (y = 0; y < src.rows; y++) { for (x = 0; x < src.cols; x++) { r = src.at<Vec3b>(y, x)[0]; g = src.at<Vec3b>(y, x)[1]; b = src.at<Vec3b>(y, x)[2]; dst.at<Vec3b>(y, x)[0] = saturate_cast<uchar>(opacity * (255 - r)); dst.at<Vec3b>(y, x)[1] = saturate_cast<uchar>(opacity * (255 - g)); dst.at<Vec3b>(y, x)[2] = saturate_cast<uchar>(opacity * (255 - b)); } } } void applyGreenBoostEffect(cv::Mat &src, cv::Mat &dst, int val) { register int x, y; float opacity = val * 0.01f; cvtColor(src, src, CV_BGRA2BGR); dst = Mat::zeros(src.size(), src.type()); uchar r, g, b,val1; for (y = 0; y < src.rows; y++) { for (x = 0; x < src.cols; x++) { r = src.at<Vec3b>(y, x)[0]; g = src.at<Vec3b>(y, x)[1]; b = src.at<Vec3b>(y, x)[2]; val1 = saturate_cast<uchar>(g*(1+opacity)); if(val1 > 255) { val1 = 255; } dst.at<Vec3b>(y, x)[0] = saturate_cast<uchar>(r); dst.at<Vec3b>(y, x)[1] = saturate_cast<uchar>(val1); dst.at<Vec3b>(y, x)[2] = saturate_cast<uchar>(b); } } } void applyColorBoostEffect(cv::Mat &src, cv::Mat &dst, int val) { register int x, y; float opacity = val * 0.01f; cvtColor(src, src, CV_BGRA2BGR); dst = Mat::zeros(src.size(), src.type()); uchar r, g, b; uchar val1,val2,val3; for (y = 0; y < src.rows; y++) { for (x = 0; x < src.cols; x++) { r = src.at<Vec3b>(y, x)[0]; g = src.at<Vec3b>(y, x)[1]; b = src.at<Vec3b>(y, x)[2]; val1 = saturate_cast<uchar>(r*(1+opacity)); if(val1 > 255) { val1 = 255; } val2 = saturate_cast<uchar>(g*(1+opacity)); if(val2 > 255) { val2 = 255; } val3 = saturate_cast<uchar>(b*(1+opacity)); if(val3 > 255) { val3 = 255; } dst.at<Vec3b>(y, x)[0] = saturate_cast<uchar>(val1); dst.at<Vec3b>(y, x)[1] = saturate_cast<uchar>(val2); dst.at<Vec3b>(y, x)[2] = saturate_cast<uchar>(val3); } } } void applyCyanise(cv::Mat &src, cv::Mat &dst, int val) { register int x, y; float opacity = val * 0.01f; cvtColor(src, src, CV_BGRA2BGR); dst = Mat::zeros(src.size(), src.type()); uchar r, g, b; uchar val2; uchar val3; for (y = 0; y < src.rows; y++) { for (x = 0; x < src.cols; x++) { r = src.at<Vec3b>(y, x)[0]; g = src.at<Vec3b>(y, x)[1]; b = src.at<Vec3b>(y, x)[2]; val2 = saturate_cast<uchar>(g*(1+opacity)); if(val2 > 255) { val2 = 255; } val3 = saturate_cast<uchar>(b*(1+opacity)); if(val3 > 255) { val3 = 255; } dst.at<Vec3b>(y, x)[0] = saturate_cast<uchar>(r); dst.at<Vec3b>(y, x)[1] = saturate_cast<uchar>(val2); dst.at<Vec3b>(y, x)[2] = saturate_cast<uchar>(val3); } } } void applySajuno(cv::Mat &src, cv::Mat &dst, int val) { register int x, y; double op = 0.5 + 0.35 * val / 100.0; cvtColor(src, src, CV_BGRA2BGR); dst = Mat::zeros(src.size(), src.type()); uchar r, g, b; int val1; for (y = 0; y < src.rows; y++) { for (x = 0; x < src.cols; x++) { r = src.at<Vec3b>(y, x)[0]; g = src.at<Vec3b>(y, x)[1]; b = src.at<Vec3b>(y, x)[2]; val1 = saturate_cast<uchar>((op * r - g * 0.4 - b * 0.4)); dst.at<Vec3b>(y, x)[0] = saturate_cast<uchar>(r + val1); dst.at<Vec3b>(y, x)[1] = saturate_cast<uchar>(g + val1); dst.at<Vec3b>(y, x)[2] = saturate_cast<uchar>(b + val1); } } } void applyBoostRedEffect(cv::Mat &src, cv::Mat &dst, int val) { register int x, y; float opacity = val * 0.01f; cvtColor(src, src, CV_BGRA2BGR); dst = Mat::zeros(src.size(), src.type()); uchar r, g, b,val1; for (y = 0; y < src.rows; y++) { for (x = 0; x < src.cols; x++) { r = src.at<Vec3b>(y, x)[0]; g = src.at<Vec3b>(y, x)[1]; b = src.at<Vec3b>(y, x)[2]; val1 = saturate_cast<uchar>(r*(1+opacity)); if(val1 > 255) { val1 = 255; } dst.at<Vec3b>(y, x)[0] = saturate_cast<uchar>(val1); dst.at<Vec3b>(y, x)[1] = saturate_cast<uchar>(g); dst.at<Vec3b>(y, x)[2] = saturate_cast<uchar>(b); } } } void applyManglow(cv::Mat &src, cv::Mat &dst, int val) { register int x, y, i; double opacity = 0.01 * val; double bri_op = 0.4 + 0.0035 * val; cvtColor(src, src, CV_BGRA2BGR); dst = Mat::zeros(src.size(), src.type()); uchar ri, gi, bi, r, g, b, bri; uchar brightnessLut[256], contrastLut[256], lut250[256], lut220[256], lut175[256]; for (i = 0; i < 256; i++) { float pixelf = i / 255.0f; brightnessLut[i] = (uchar) (255 * applyBrightnessToPixelComponent(pixelf, 0.4724f)); contrastLut[i] = (uchar) (255 * applyContrastToPixelComponent(pixelf, 0.3149f)); lut250[i] = multiplyPixelComponents(250, (uchar) i); lut220[i] = multiplyPixelComponents(220, (uchar) i); lut175[i] = multiplyPixelComponents(175, (uchar) i); } for (y = 0; y < src.rows; y++) { for (x = 0; x < src.cols; x++) { ri = src.at<Vec3b>(y, x)[0]; gi = src.at<Vec3b>(y, x)[1]; bi = src.at<Vec3b>(y, x)[2]; bri = saturate_cast<uchar>((bri_op * ri - gi * 0.4 - bi * 0.4)); r = contrastLut[brightnessLut[ri]]; g = contrastLut[brightnessLut[gi]]; b = contrastLut[brightnessLut[bi]]; g = saturate_cast<uchar> ((g * 0.87f) + 33); b = saturate_cast<uchar> ((b * 0.439f) + 143); dst.at<Vec3b>(y, x)[0] = saturate_cast<uchar>((1 - opacity) * ri + opacity * lut250[r] + bri); dst.at<Vec3b>(y, x)[1] = saturate_cast<uchar>((1 - opacity) * gi + opacity * lut220[g] + bri); dst.at<Vec3b>(y, x)[2] = saturate_cast<uchar>((1 - opacity) * bi + opacity * lut175[b] + bri); } } } void applyPalacia(cv::Mat &src, cv::Mat &dst, int val) { int clip = 1 + (int) (val * 0.04); cvtColor(src, src, CV_BGRA2BGR); dst = Mat::zeros(src.size(), src.type()); Mat gamma_mat; gammaCorrection(src, gamma_mat); Mat lab_image; cvtColor(gamma_mat, lab_image, CV_BGR2Lab); vector<Mat> lab_planes(3); split(lab_image, lab_planes); Ptr<CLAHE> clahe = createCLAHE(); clahe->setClipLimit(clip); Mat clahe_mat; clahe->apply(lab_planes[0], clahe_mat); clahe_mat.copyTo(lab_planes[0]); merge(lab_planes, lab_image); cvtColor(lab_image, dst, CV_Lab2BGR); } void applyAnax(cv::Mat &src, cv::Mat &dst, int val) { register int i, j, x, y, tr, tb, tg; double opacity = val / 100.0; cvtColor(src, src, CV_BGRA2BGR); dst = Mat::zeros(src.size(), src.type()); register uchar sepia, red, green, blue; short int overlayLut[256][256]; for (i = 256; i--;) { for (j = 256; j--;) { overlayLut[i][j] = -1; } } for (y = 0; y < src.rows; y++) { for (x = 0; x < src.cols; x++) { HSBColour hsb; float value; red = src.at<Vec3b>(y, x)[0]; green = src.at<Vec3b>(y, x)[1]; blue = src.at<Vec3b>(y, x)[2]; getBrightness(red, green, blue, &value); uchar r = LUTxproRed[red]; uchar g = LUTxproGreen[green]; uchar b = LUTxproBlue[blue]; rgbToHsb(r, g, b, &hsb); hsb.b = value; hsbToRgb(&hsb, &r, &g, &b); if (overlayLut[red][r] == -1) { overlayLut[red][r] = overlayComponents(red, r, 1.0f); } tr = overlayLut[red][r]; if (overlayLut[green][g] == -1) { overlayLut[green][g] = overlayComponents(green, g, 1.0f); } tg = overlayLut[green][g]; if (overlayLut[blue][b] == -1) { overlayLut[blue][b] = overlayComponents(blue, b, 1.0f); } tb = overlayLut[blue][b]; dst.at<Vec3b>(y, x)[2] = saturate_cast<uchar>((1 - opacity) * (src.at<Vec3b>(y, x)[2]) + opacity * tb); dst.at<Vec3b>(y, x)[1] = saturate_cast<uchar>((1 - opacity) * (src.at<Vec3b>(y, x)[1]) + opacity * tg); dst.at<Vec3b>(y, x)[0] = saturate_cast<uchar>((1 - opacity) * (src.at<Vec3b>(y, x)[0]) + opacity * tr); } } } void applySepia(cv::Mat &src, cv::Mat &dst, int val) { register int x, y; double opacity = val / 100.0; cvtColor(src, src, CV_BGRA2BGR); dst = Mat::zeros(src.size(), src.type()); uchar sepia; uchar r, g, b; int bri; for (y = 0; y < src.rows; y++) { for (x = 0; x < src.cols; x++) { r = src.at<Vec3b>(y, x)[0]; g = src.at<Vec3b>(y, x)[1]; b = src.at<Vec3b>(y, x)[2]; sepia = (uchar) sepiaLum(src.at<Vec3b>(y, x)[0], src.at<Vec3b>(y, x)[1], src.at<Vec3b>(y, x)[2]); bri = saturate_cast<uchar>((0.75 * r - g * 0.4 - b * 0.4)); dst.at<Vec3b>(y, x)[0] = saturate_cast<uchar>((1 - opacity) * (src.at<Vec3b>(y, x)[0]) + opacity * LUTsepiaRed[sepia] + bri); dst.at<Vec3b>(y, x)[1] = saturate_cast<uchar>((1 - opacity) * (src.at<Vec3b>(y, x)[1]) + opacity * LUTsepiaGreen[sepia] + bri); dst.at<Vec3b>(y, x)[2] = saturate_cast<uchar>((1 - opacity) * (src.at<Vec3b>(y, x)[2]) + opacity * LUTsepiaBlue[sepia] + bri); } } } void applyBlueBoostEffect(cv::Mat &src, cv::Mat &dst, int val) { register int x, y; float opacity = val * 0.01f; cvtColor(src, src, CV_BGRA2BGR); dst = Mat::zeros(src.size(), src.type()); uchar r, g, b,val1; for (y = 0; y < src.rows; y++) { for (x = 0; x < src.cols; x++) { r = src.at<Vec3b>(y, x)[0]; g = src.at<Vec3b>(y, x)[1]; b = src.at<Vec3b>(y, x)[2]; val1 = saturate_cast<uchar>(b*(1+opacity)); if(val1 > 255) { val1 = 255; } dst.at<Vec3b>(y, x)[0] = saturate_cast<uchar>(r); dst.at<Vec3b>(y, x)[1] = saturate_cast<uchar>(g); dst.at<Vec3b>(y, x)[2] = saturate_cast<uchar>(val1); } } } void applyAnsel(cv::Mat &src, cv::Mat &dst, int val) { register int x, y; double opacity = val / 100.0; cvtColor(src, src, CV_BGRA2BGR); dst = Mat::zeros(src.size(), src.type()); uchar grey, r, g, b, eff; for (y = 0; y < src.rows; y++) { for (x = 0; x < src.cols; x++) { r = src.at<Vec3b>(y, x)[0]; g = src.at<Vec3b>(y, x)[1]; b = src.at<Vec3b>(y, x)[2]; grey = saturate_cast<uchar> blackAndWhite(r, g, b); eff = (uchar) hardLightLayerPixelComponent(grey, grey); dst.at<Vec3b>(y, x)[0] = saturate_cast<uchar>((1 - opacity) * r + opacity * eff); dst.at<Vec3b>(y, x)[1] = saturate_cast<uchar>((1 - opacity) * g + opacity * eff); dst.at<Vec3b>(y, x)[2] = saturate_cast<uchar>((1 - opacity) * b + opacity * eff); } } } void applyHistEq(cv::Mat &src, cv::Mat &dst, int val) { float opacity = 0.01f * val; cvtColor(src, src, CV_BGRA2BGR); dst = Mat::zeros(src.size(), src.type()); vector<Mat> planes(3), planes1(3); split(src, planes); equalizeHist(planes[0], planes1[0]); equalizeHist(planes[1], planes1[1]); equalizeHist(planes[2], planes1[2]); merge(planes1, dst); dst = (1 - opacity) * src + opacity * dst; planes.clear(); planes1.clear(); } void applyThreshold(cv::Mat &src, cv::Mat &dst, int val) { register int x, y; double opacity = val / 100.0; cvtColor(src, src, CV_BGRA2GRAY); dst = Mat::zeros(src.size(), src.type()); int thres = 220 - (int) (opacity * 190); uchar color; for (y = 0; y < src.rows; y++) { for (x = 0; x < src.cols; x++) { if (src.at<uchar>(y, x) < thres) color = 0; else color = 255; dst.at<uchar>(y, x) = saturate_cast<uchar>(color); } } } void applyGrain(cv::Mat &src, cv::Mat &dst, int val) { register int x, y; double opacity = val / 100.0; cvtColor(src, src, CV_BGRA2BGR); dst = src.clone(); time_t t; srand((unsigned) time(&t)); for (y = 0; y < src.rows; y++) { for (x = 0; x < src.cols; x++) { int rval = rand() % 255; if (rand() % 100 < (int) (opacity * 20)) { dst.at<Vec3b>(y, x)[2] = saturate_cast<uchar>( (1 - opacity) * (dst.at<Vec3b>(y, x)[2]) + opacity * rval); dst.at<Vec3b>(y, x)[1] = saturate_cast<uchar>( (1 - opacity) * (dst.at<Vec3b>(y, x)[1]) + opacity * rval); dst.at<Vec3b>(y, x)[0] = saturate_cast<uchar>( (1 - opacity) * (dst.at<Vec3b>(y, x)[0]) + opacity * rval); } } } } void applyCyano(cv::Mat &src, cv::Mat &dst, int val) { register int x, y; double opacity = val / 100.0; cvtColor(src, src, CV_BGRA2BGR); dst = Mat::zeros(src.size(), src.type()); register uchar grey, r, g, b; for (y = 0; y < src.rows; y++) { for (x = 0; x < src.cols; x++) { grey = (uchar) ((src.at<Vec3b>(y, x)[0] * 0.5f) + (src.at<Vec3b>(y, x)[1] * 0.39f) + (src.at<Vec3b>(y, x)[2] * 0.11f)); r = (uchar) ceilComponent(61.0f + grey); g = (uchar) ceilComponent(87.0f + grey); b = (uchar) ceilComponent(136.0f + grey); dst.at<Vec3b>(y, x)[2] = saturate_cast<uchar>((1 - opacity) * (src.at<Vec3b>(y, x)[2]) + opacity * overlayComponents(grey, b, 0.9)); dst.at<Vec3b>(y, x)[1] = saturate_cast<uchar>((1 - opacity) * (src.at<Vec3b>(y, x)[1]) + opacity * overlayComponents(grey, g, 0.9)); dst.at<Vec3b>(y, x)[0] = saturate_cast<uchar>((1 - opacity) * (src.at<Vec3b>(y, x)[0]) + opacity * overlayComponents(grey, r, 0.9)); } } } void applyFade(cv::Mat &src, cv::Mat &dst, int val) { cvtColor(src, src, COLOR_RGB2GRAY); dst = src.clone(); for (int y = 0; y < src.rows; y++) { for (int x = 0; x < src.rows; x++) { Vec3b intensity = src.at<Vec3b>(y, x); uchar blue = intensity.val[0]; uchar green = intensity.val[1]; uchar red = intensity.val[2]; dst.at<Vec3b>(y, x)[0] = saturate_cast<uchar>(blue + 0.5 * val); dst.at<Vec3b>(y, x)[1] = saturate_cast<uchar>(green + 0.5 * val); dst.at<Vec3b>(y, x)[2] = saturate_cast<uchar>(red + 0.5 * val); } } } void applyCartoon(cv::Mat &src, cv::Mat &dst, int val) { double opacity = val / 100.0; Mat srcGray; cvtColor(src, src, CV_BGRA2BGR); cvtColor(src, srcGray, CV_BGR2GRAY); medianBlur(srcGray, srcGray, 7); Size size = src.size(); Mat mask = Mat(size, CV_8U); Mat edges = Mat(size, CV_8U); Laplacian(srcGray, edges, CV_8U, 5); threshold(edges, mask, 80, (int) 255 * opacity, CV_THRESH_BINARY_INV); Size smallSize; smallSize.width = size.width / 4; smallSize.height = size.height / 4; Mat smallImg = Mat(smallSize, CV_8UC3); resize(src, smallImg, smallSize, 0, 0, CV_INTER_LINEAR); Mat tmp = Mat(smallSize, CV_8UC3); int repetitions = 7; for (int i = 0; i < repetitions; i++) { int sizeInt = 9; double sigmaColor = 9; double sigmaSpace = 7; bilateralFilter(smallImg, tmp, sizeInt, sigmaColor, sigmaSpace); bilateralFilter(tmp, smallImg, sizeInt, sigmaColor, sigmaSpace); } resize(smallImg, src, size, 0, 0, CV_INTER_LINEAR); dst = Mat::zeros(src.size(), src.type()); src.copyTo(dst, mask); } void applyPencilSketch(cv::Mat &src, cv::Mat &dst, int val) { cvtColor(src, src, COLOR_BGRA2GRAY); dst = Mat::zeros(src.size(), src.type()); adaptiveThreshold(src, dst, 255, CV_ADAPTIVE_THRESH_MEAN_C, CV_THRESH_BINARY, 9, 2); } void applyEdgify(cv::Mat &src, cv::Mat &dst, int val) { int lowThreshold = val; int ratio = 3; int kernel_size = 3; Mat grey, detected_edges; cvtColor(src, grey, CV_BGR2GRAY); blur(grey, detected_edges, Size(3, 3)); dst.create(grey.size(), grey.type()); Canny(detected_edges, detected_edges, lowThreshold, lowThreshold * ratio, kernel_size); dst = Scalar::all(0); detected_edges.copyTo(dst, detected_edges); } void applyRedBlueEffect(cv::Mat &src, cv::Mat &dst, int val) { register int x, y; float opacity = val * 0.01f; cvtColor(src, src, CV_BGRA2BGR); dst = Mat::zeros(src.size(), src.type()); uchar r, g, b; uchar val1,val3; for (y = 0; y < src.rows; y++) { for (x = 0; x < src.cols; x++) { r = src.at<Vec3b>(y, x)[0]; g = src.at<Vec3b>(y, x)[1]; b = src.at<Vec3b>(y, x)[2]; val1 = saturate_cast<uchar>(r*(1+opacity)); if(val1 > 255) { val1 = 255; } val3 = saturate_cast<uchar>(b*(1+opacity)); if(val3 > 255) { val3 = 255; } dst.at<Vec3b>(y, x)[0] = saturate_cast<uchar>(val1); dst.at<Vec3b>(y, x)[1] = saturate_cast<uchar>(g); dst.at<Vec3b>(y, x)[2] = saturate_cast<uchar>(val3); } } } void applyRedGreenFilter(cv::Mat &src, cv::Mat &dst, int val) { register int x, y; float opacity = val * 0.01f; cvtColor(src, src, CV_BGRA2BGR); dst = Mat::zeros(src.size(), src.type()); uchar r, g, b; uchar val1,val2; for (y = 0; y < src.rows; y++) { for (x = 0; x < src.cols; x++) { r = src.at<Vec3b>(y, x)[0]; g = src.at<Vec3b>(y, x)[1]; b = src.at<Vec3b>(y, x)[2]; val1 = saturate_cast<uchar>(r*(1+opacity)); if(val1 > 255) { val1 = 255; } val2 = saturate_cast<uchar>(g*(1+opacity)); if(val2 > 255) { val2 = 255; } dst.at<Vec3b>(y, x)[0] = saturate_cast<uchar>(val1); dst.at<Vec3b>(y, x)[1] = saturate_cast<uchar>(val2); dst.at<Vec3b>(y, x)[2] = saturate_cast<uchar>(b); } } } void applyWhiteYellowTint(cv::Mat &src, cv::Mat &dst, int val) { register int x, y; double op = 0.5 + 0.1 * val / 100.0; cvtColor(src, src, CV_BGRA2BGR); dst = Mat::zeros(src.size(), src.type()); uchar r, g, b; uchar val1, val2, val3; for (y = 0; y < src.rows; y++) { for (x = 0; x < src.cols; x++) { r = src.at<Vec3b>(y, x)[0]; g = src.at<Vec3b>(y, x)[1]; b = src.at<Vec3b>(y, x)[2]; val1 = saturate_cast<uchar>(r * 1.5 + op); if (val1 > 255) { val1 = 255; } val2 = saturate_cast<uchar>(b * 1.5 + op); if (val2 > 255) { val2 = 255; } val3 = saturate_cast<uchar>(g * 1.5 + op); if (val2 > 255) { val2 = 255; } dst.at<Vec3b>(y, x)[0] = saturate_cast<uchar>(val1); dst.at<Vec3b>(y, x)[1] = saturate_cast<uchar>(val3); dst.at<Vec3b>(y, x)[2] = saturate_cast<uchar>(val2); } } } }
33.108183
98
0.474132
[ "vector" ]
71ba8ac42d966285417a9a68ba8da9066713275f
3,124
cpp
C++
2020/14.cpp
mdelorme/advent_of_code
47142d501055fc0d36989db9b189be7e6756d779
[ "Unlicense" ]
null
null
null
2020/14.cpp
mdelorme/advent_of_code
47142d501055fc0d36989db9b189be7e6756d779
[ "Unlicense" ]
null
null
null
2020/14.cpp
mdelorme/advent_of_code
47142d501055fc0d36989db9b189be7e6756d779
[ "Unlicense" ]
null
null
null
#include <bits/stdc++.h> using BitSet = std::bitset<36>; struct Instruction { std::string mask; uint64_t address; uint64_t value; bool is_mask; }; std::vector<Instruction> instructions; std::map<uint64_t, BitSet> memory_p1; std::map<uint64_t, uint64_t> memory_p2; void apply_value(uint64_t address, uint64_t value, std::string cur_mask) { BitSet b(value); for (int i=0; i < 36; ++i) { if (cur_mask[35-i] == '0') b[i] = false; else if (cur_mask[35-i] == '1') b[i] = true; } memory_p1[address] = b; } void part1() { std::string cur_mask; memory_p1.clear(); for (auto &i: instructions) { if (!i.is_mask) { apply_value(i.address, i.value, cur_mask); } else cur_mask = i.mask; } uint64_t sum = 0; for (auto &[a, v] : memory_p1) sum += v.to_ullong(); std::cout << "Part 1 : " << sum << std::endl; } uint64_t tot_count = 0; uint64_t sum_memory(std::string value, int pos) { if (pos == 36) { BitSet b(value); tot_count++; return b.to_ullong(); } if (value[pos] == 'X') { std::string v1 = value; std::string v2 = value; v1[pos] = '0'; v2[pos] = '1'; return sum_memory(v1, pos+1) + sum_memory(v2, pos+1); } uint64_t res = sum_memory(value, pos+1); return res; } std::string get_address_mask(uint address, std::string mask) { BitSet b(address); std::string res = b.to_string(); for (int i=0; i < 36; ++i) { if (mask[i] != '0') res[i] = mask[i]; } return res; } void parse_addresses(std::vector<uint64_t> &addresses, std::string cur_addr, int pos) { if (pos == 36) { BitSet b(cur_addr); addresses.push_back(b.to_ullong()); return; } if (cur_addr[pos] == 'X') { cur_addr[pos] = '0'; parse_addresses(addresses, cur_addr, pos+1); cur_addr[pos] = '1'; parse_addresses(addresses, cur_addr, pos+1); } else parse_addresses(addresses, cur_addr, pos+1); } void part2() { std::string cur_mask; memory_p2.clear(); for (auto &i: instructions) { if (!i.is_mask) { std::string addr_mask = get_address_mask(i.address, cur_mask); std::vector<uint64_t> addresses; parse_addresses(addresses, addr_mask, 0); for (auto addr: addresses) memory_p2[addr] = i.value; } else cur_mask = i.mask; } // Enumerating memory uint64_t sum = 0; for (auto &[a, v]: memory_p2) { sum += v; } std::cout << "Part 2 : " << sum << std::endl; } int main(int argc, char **argv) { std::ifstream f_in; f_in.open("14.in"); std::regex memory_re("mem\\[([0-9]+)\\] = ([0-9]+)"); while (f_in.good()) { std::string line; Instruction ins; std::getline(f_in, line); std::smatch match; std::regex_match(line, match, memory_re); if (match.empty()) { if (line == "") break; ins.is_mask = true; ins.mask = line.substr(7, 36); } else { ins.address = std::stoi(match[1]); ins.value = std::stoi(match[2]); ins.is_mask = false; } instructions.push_back(ins); } f_in.close(); part1(); part2(); return 0; }
20.966443
87
0.580986
[ "vector" ]
71c5291ee4c36e3dd6e5bd0cfea5979974b38025
2,470
hpp
C++
include/spmdfy/CFG/CFGVisitor.hpp
schwarzschild-radius/spmdfy
9b5543e3446347277f15b9fe2aee3c7f8311bc78
[ "MIT" ]
6
2019-07-26T12:37:32.000Z
2021-03-13T06:18:07.000Z
include/spmdfy/CFG/CFGVisitor.hpp
schwarzschild-radius/spmdfy
9b5543e3446347277f15b9fe2aee3c7f8311bc78
[ "MIT" ]
6
2019-06-19T06:04:01.000Z
2019-08-23T11:12:31.000Z
include/spmdfy/CFG/CFGVisitor.hpp
schwarzschild-radius/spmdfy
9b5543e3446347277f15b9fe2aee3c7f8311bc78
[ "MIT" ]
1
2020-05-28T06:43:12.000Z
2020-05-28T06:43:12.000Z
#ifndef CFGVISITOR_HPP #define CFGVISITOR_HPP #include <spmdfy/CFG/CFG.hpp> #include <vector> namespace spmdfy { namespace cfg { using SpmdTUTy = std::vector<cfg::CFGNode *>; /** * \class CFGVisitor * \ingroup CFG * * \brief A Visitor interface the CFG inspired by clang's ASTVisitors. The * Visitors can be overriden by the inherited nodes. * * */ // FIXME: Why CRTP and Virtual at the same time??? template <typename Derived, typename RetTy> class CFGVisitor { public: #define DISPATCH(NAME) \ return static_cast<Derived *>(this)->Visit##NAME##Node( \ dynamic_cast<NAME##Node *>(node)) #define FALLBACK(NAME) \ virtual RetTy Visit##NAME##Node(NAME##Node *node) { DISPATCH(CFG); } virtual ~CFGVisitor() = default; FALLBACK(Forward); FALLBACK(Backward); FALLBACK(BiDirect); FALLBACK(GlobalVar); FALLBACK(KernelFunc); FALLBACK(Conditional); FALLBACK(IfStmt); FALLBACK(ForStmt); FALLBACK(Reconv); FALLBACK(Internal); FALLBACK(Exit); FALLBACK(ISPCBlock); FALLBACK(ISPCBlockExit); FALLBACK(ISPCGrid); FALLBACK(ISPCGridExit); virtual RetTy Visit(CFGNode *node) { // clang-format off switch (node->getNodeType()) { case CFGNode::Forward: DISPATCH(Forward); case CFGNode::Backward: DISPATCH(Backward); case CFGNode::BiDirect: DISPATCH(BiDirect); case CFGNode::GlobalVar: DISPATCH(GlobalVar); case CFGNode::KernelFunc: DISPATCH(KernelFunc); case CFGNode::Conditional: DISPATCH(Conditional); case CFGNode::IfStmt: DISPATCH(IfStmt); case CFGNode::ForStmt: DISPATCH(ForStmt); case CFGNode::Reconv: DISPATCH(Reconv); case CFGNode::Internal: DISPATCH(Internal); case CFGNode::Exit: DISPATCH(Exit); case CFGNode::ISPCBlock: DISPATCH(ISPCBlock); case CFGNode::ISPCBlockExit: DISPATCH(ISPCBlockExit); case CFGNode::ISPCGrid: DISPATCH(ISPCGrid); case CFGNode::ISPCGridExit: DISPATCH(ISPCGridExit); default: SPMDFY_ERROR("Unknown Node Kind"); } // clang-format on return RetTy(); } virtual RetTy VisitCFGNode(CFGNode *node) { return RetTy(); } }; } // namespace cfg } // namespace spmdfy #endif
30.493827
80
0.609312
[ "vector" ]
71c985b70471c36b2c05237b1bbc116fbcb21b8e
3,392
hpp
C++
src/target/new/type_field_value.hpp
bendyer/kdl
9f3afa71a1df0b2e412a988750c1b9ce61d3c550
[ "MIT" ]
null
null
null
src/target/new/type_field_value.hpp
bendyer/kdl
9f3afa71a1df0b2e412a988750c1b9ce61d3c550
[ "MIT" ]
null
null
null
src/target/new/type_field_value.hpp
bendyer/kdl
9f3afa71a1df0b2e412a988750c1b9ce61d3c550
[ "MIT" ]
null
null
null
// Copyright (c) 2020 Tom Hancocks // // 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. #if !defined(KDL_TYPE_FIELD_VALUE_HPP) #define KDL_TYPE_FIELD_VALUE_HPP #include <vector> #include <optional> #include <tuple> #include <map> #include "parser/lexeme.hpp" #include "target/new/kdl_type.hpp" #include "target/new/binary_type.hpp" #include "target/new/type_template.hpp" namespace kdl { namespace build_target { struct type_field_value { private: lexeme m_base_name; std::optional<kdl_type> m_explicit_type; std::optional<lexeme> m_default_value; std::vector<std::tuple<lexeme, lexeme>> m_symbols; std::vector<lexeme> m_name_extensions; std::optional<std::tuple<lexeme, lexeme>> m_conversion_map; std::vector<type_field_value> m_joined_values; public: type_field_value(const lexeme base_name); auto base_name() const -> lexeme; auto extended_name(const std::map<std::string, lexeme> vars) const -> lexeme; auto set_explicit_type(const kdl_type type) -> void; auto explicit_type() const -> std::optional<kdl::build_target::kdl_type>; auto set_default_value(const lexeme default_value) -> void; auto default_value() const -> std::optional<lexeme>; auto set_symbols(const std::vector<std::tuple<lexeme, lexeme>> symbols) -> void; auto add_symbol(const lexeme symbol, const lexeme value) -> void; auto symbols() const -> std::vector<std::tuple<lexeme, lexeme>>; auto value_for(const lexeme symbol) const -> lexeme; auto set_name_extensions(const std::vector<lexeme> name_extensions) -> void; auto add_name_extension(const lexeme ext) -> void; auto set_conversion_map(const std::tuple<lexeme, lexeme> map) -> void; auto set_conversion_map(const lexeme input, const lexeme output) -> void; auto has_conversion_defined() const -> bool; auto conversion_input() const -> lexeme; auto conversion_output() const -> lexeme; auto join_value(const type_field_value value) -> void; auto joined_value_count() const -> std::size_t; auto joined_value_at(const int i) -> type_field_value; auto joined_value_for(const lexeme symbol) const -> std::optional<std::tuple<int, lexeme>>; }; }}; #endif //KDL_TYPE_FIELD_VALUE_HPP
41.876543
99
0.713443
[ "vector" ]
71cb955a306a1a89c6107556eae7129b91057f62
7,681
hpp
C++
src/private_include/transfer_buffer.hpp
p-groarke/fea_vulkan_compute
e0ffeb74846ed565d7036424e3deddf032d51e05
[ "BSD-3-Clause" ]
null
null
null
src/private_include/transfer_buffer.hpp
p-groarke/fea_vulkan_compute
e0ffeb74846ed565d7036424e3deddf032d51e05
[ "BSD-3-Clause" ]
null
null
null
src/private_include/transfer_buffer.hpp
p-groarke/fea_vulkan_compute
e0ffeb74846ed565d7036424e3deddf032d51e05
[ "BSD-3-Clause" ]
null
null
null
#pragma once #include "private_include/ids.hpp" #include "private_include/raw_buffer.hpp" #include "vkc/vkc.hpp" #include <algorithm> #include <limits> #include <vulkan/vulkan.hpp> namespace fea { namespace vkc { namespace detail { constexpr vk::BufferUsageFlags staging_usage_flags = vk::BufferUsageFlagBits::eTransferSrc | vk::BufferUsageFlagBits::eTransferDst; constexpr vk::MemoryPropertyFlags staging_mem_flags = vk::MemoryPropertyFlagBits::eHostVisible | vk::MemoryPropertyFlagBits::eHostCoherent; constexpr vk::BufferUsageFlags gpu_usage_flags = vk::BufferUsageFlagBits::eTransferDst | vk::BufferUsageFlagBits::eTransferSrc | vk::BufferUsageFlagBits::eStorageBuffer; constexpr vk::MemoryPropertyFlags gpu_mem_flags = vk::MemoryPropertyFlagBits::eDeviceLocal; void make_copy_cmd(const vk::Buffer& src, const vk::Buffer& dst, size_t byte_size, vk::CommandBuffer& cmd_buf) { vk::CommandBufferBeginInfo begin_info{}; cmd_buf.begin(begin_info); vk::BufferCopy copy_region{ 0, 0, byte_size, }; cmd_buf.copyBuffer(src, dst, 1, &copy_region); cmd_buf.end(); } } // namespace detail // This buffer contains 2 raw_buffers. // One cpu-visible staging buffer, and one gpu-only data buffer. // Use this to transfer memory to/from the gpu. struct transfer_buffer { transfer_buffer() = default; // Create a bound transfer_buffer but doesn't allocate memory. transfer_buffer(buffer_ids ids) : _staging_buf( detail::staging_usage_flags, detail::staging_mem_flags) , _gpu_buf(ids, detail::gpu_usage_flags, detail::gpu_mem_flags) { assert(_staging_buf.byte_size() == _gpu_buf.byte_size()); } // Create a bound transfer_buffer and allocate memory. transfer_buffer(const vkc& vkc_inst, buffer_ids gpu_ids, size_t byte_size) : _staging_buf(vkc_inst, byte_size, detail::staging_usage_flags, detail::staging_mem_flags) , _gpu_buf(vkc_inst, gpu_ids, byte_size, detail::gpu_usage_flags, detail::gpu_mem_flags) { assert(_staging_buf.byte_size() == _gpu_buf.byte_size()); } // Move-only transfer_buffer(transfer_buffer&&) = default; transfer_buffer& operator=(transfer_buffer&&) = default; transfer_buffer(const transfer_buffer&) = delete; transfer_buffer& operator=(const transfer_buffer&) = delete; // Operations void clear() { _staging_buf.clear(); _gpu_buf.clear(); assert(_staging_buf.byte_size() == _gpu_buf.byte_size()); } void resize(const vkc& vkc_inst, size_t byte_size) { _staging_buf.resize(vkc_inst, byte_size); _gpu_buf.resize(vkc_inst, byte_size); assert(_staging_buf.byte_size() == _gpu_buf.byte_size()); } void bind(const vkc& vkc_inst, vk::DescriptorSet target_desc_set) { assert(_staging_buf.byte_size() == _gpu_buf.byte_size()); _gpu_buf.bind(vkc_inst, target_desc_set); } void make_push_cmd(vk::CommandBuffer&& cmd_buf) { if (has_push_cmd()) { // Has already been created at correct size. return; } _push_cmd = std::move(cmd_buf); detail::make_copy_cmd( _staging_buf.get(), _gpu_buf.get(), byte_size(), _push_cmd); _push_cmd_byte_size = byte_size(); } void make_pull_cmd(vk::CommandBuffer&& cmd_buf) { if (has_pull_cmd()) { // Has already been created at correct size. return; } _pull_cmd = std::move(cmd_buf); detail::make_copy_cmd( _gpu_buf.get(), _staging_buf.get(), byte_size(), _pull_cmd); _pull_cmd_byte_size = byte_size(); } void push(vkc& vkc_inst, const uint8_t* in_mem) { // Map the buffer memory, so that we can read from it on the CPU. void* mapped_memory = vkc_inst.device().mapMemory( _staging_buf.get_memory(), 0, byte_size()); uint8_t* out_mem = reinterpret_cast<uint8_t*>(mapped_memory); std::copy(in_mem, in_mem + byte_size(), out_mem); // Done writing, so unmap. vkc_inst.device().unmapMemory(_staging_buf.get_memory()); // Now, copy the staging buffer to gpu memory. vk::SubmitInfo submit_info{ {}, nullptr, nullptr, 1, // submit a single command buffer // the command buffer to submit. &_push_cmd, }; vk::Result res = vkc_inst.queue().submit(1, &submit_info, {}); if (res != vk::Result::eSuccess) { fprintf(stderr, "Buffer push submit failed with result : '%d'\n", res); return; } vkc_inst.queue().waitIdle(); } void pull(vkc& vkc_inst, uint8_t* out_mem) { // First, copy the gpu buffer to staging buffer. vk::SubmitInfo submit_info{ {}, nullptr, nullptr, 1, &_pull_cmd, }; vkc_inst.queue().waitIdle(); vk::Result res = vkc_inst.queue().submit(1, &submit_info, {}); if (res != vk::Result::eSuccess) { fprintf(stderr, "Buffer pull submit failed with result : '%d'\n", res); return; } vkc_inst.queue().waitIdle(); // Map the buffer memory, so that we can read from it on the CPU. const void* mapped_memory = vkc_inst.device().mapMemory( _staging_buf.get_memory(), 0, byte_size()); const uint8_t* in_mem = reinterpret_cast<const uint8_t*>(mapped_memory); std::copy(in_mem, in_mem + byte_size(), out_mem); // Done reading, so unmap. vkc_inst.device().unmapMemory(_staging_buf.get_memory()); } // Getters and setters size_t byte_size() const { assert(_staging_buf.byte_size() == _gpu_buf.byte_size()); return _gpu_buf.byte_size(); } size_t capacity() const { assert(_staging_buf.capacity() == _gpu_buf.capacity()); return _gpu_buf.capacity(); } const raw_buffer& staging_buf() const { return _staging_buf; } raw_buffer& staging_buf() { return _staging_buf; } const raw_buffer& gpu_buf() const { return _gpu_buf; } raw_buffer& gpu_buf() { return _gpu_buf; } bool has_push_cmd() const { assert(_staging_buf.byte_size() == _gpu_buf.byte_size()); return _push_cmd != vk::CommandBuffer{} && _push_cmd_byte_size == _staging_buf.byte_size(); } bool has_pull_cmd() const { assert(_staging_buf.byte_size() == _gpu_buf.byte_size()); return _pull_cmd != vk::CommandBuffer{} && _pull_cmd_byte_size == _staging_buf.byte_size(); } private: // The staging buffer, accessible from cpu. raw_buffer _staging_buf; // The actual gpu buffer, not accessible from cpu. raw_buffer _gpu_buf; // The command to copy from staging to gpu. vk::CommandBuffer _push_cmd; // The push command byte_size. // Used to trigger creation of new command when size has changed. size_t _push_cmd_byte_size = 0; // The command to copy from gpu to staging. vk::CommandBuffer _pull_cmd; // The pull command byte_size. // Used to trigger creation of new command when size has changed. size_t _pull_cmd_byte_size = 0; }; // TODO : Allocate and create multiple commands at once, thread. void make_push_cmds(const vkc& vkc_inst, vk::CommandPool command_pool, transfer_buffer& buf) { if (buf.has_push_cmd()) { return; } // We are only creating 1 new command buffer. For now. vk::CommandBufferAllocateInfo alloc_info{ command_pool, vk::CommandBufferLevel::ePrimary, 1, }; std::vector<vk::CommandBuffer> new_buf = vkc_inst.device().allocateCommandBuffers(alloc_info); assert(new_buf.size() == 1); buf.make_push_cmd(std::move(new_buf.back())); } // TODO : Allocate and create multiple commands at once, thread. void make_pull_cmds(const vkc& vkc_inst, vk::CommandPool command_pool, transfer_buffer& buf) { if (buf.has_pull_cmd()) { return; } // We are only creating 1 new command buffer. For now. vk::CommandBufferAllocateInfo alloc_info{ command_pool, vk::CommandBufferLevel::ePrimary, 1, }; std::vector<vk::CommandBuffer> new_buf = vkc_inst.device().allocateCommandBuffers(alloc_info); assert(new_buf.size() == 1); buf.make_pull_cmd(std::move(new_buf.back())); } } // namespace vkc } // namespace fea
27.432143
75
0.719958
[ "vector" ]
71e06be41b3d7618d90d34b25d59d45ed774b17c
4,098
cpp
C++
frameworks/net/interfaces/dmzNetModuleIdentityMap.cpp
dmzgroup/dmz
fc2d9ddcb04ed71f4106b8d33539529807b3dea6
[ "MIT" ]
2
2015-11-05T03:03:43.000Z
2017-05-15T12:55:39.000Z
frameworks/net/interfaces/dmzNetModuleIdentityMap.cpp
dmzgroup/dmz
fc2d9ddcb04ed71f4106b8d33539529807b3dea6
[ "MIT" ]
null
null
null
frameworks/net/interfaces/dmzNetModuleIdentityMap.cpp
dmzgroup/dmz
fc2d9ddcb04ed71f4106b8d33539529807b3dea6
[ "MIT" ]
null
null
null
/*! \class dmz::NetModuleIdentityMap \ingroup Net \brief Provides a mapping between internal and external object identification. \fn dmz::NetModuleIdentityMap *dmz::NetModuleIdentityMap::cast ( const Plugin *PluginPtr, const String &PluginName) \brief Casts Plugin pointer to an NetModuleIdentityMap. \details If the Plugin object implements the NetModuleIdentityMap interface, a pointer to the NetModuleIdentityMap interface of the Plugin is returned. \param[in] PluginPtr Pointer to the Plugin to cast. \param[in] PluginName String containing the name of the desired NetModuleIdentityMap. \return Returns pointer to the NetModuleIdentityMap. Returns NULL if the PluginPtr does not implement the NetModuleIdentityMap interface or the \a PluginName is not empty and not equal to the Plugin's name. \fn dmz::NetModuleIdentityMap::NetModuleIdentityMap (const PluginInfo &Info) \brief Constructor. \fn dmz::NetModuleIdentityMap::~NetModuleIdentityMap () \brief Destructor. \fn dmz::UInt32 dmz::NetModuleIdentityMap::get_site_id () \brief Gets site id for current simulation instance. \fn dmz::UInt32 dmz::NetModuleIdentityMap::get_host_id () \brief Gets host id for current simulation instance. \fn dmz::Boolean dmz::NetModuleIdentityMap::create_site_host_entity ( const Handle ObjectHandle, UInt32 &site, UInt32 &host, UInt32 &entity) \brief Creates a new site/host/entity id and binds it to an object Handle. \param[in] ObjectHandle Handle of object to create new site/host/entity. \param[out] site Id of site. \param[out] host Id of host. \param[out] entity Id of entity. \return Returns dmz::True if a new site/host/entity id was created. \fn dmz::Boolean dmz::NetModuleIdentityMap::store_site_host_entity ( const Handle ObjectHandle, const UInt32 Site, const UInt32 Host, const UInt32 Entity) \brief Binds a site/host/entity to and object Handle. \param[in] ObjectHandle handle of object to bind. \param[in] Site Id of site to bind to object. \param[in] Host Id of host to bind to object. \param[in] Entity Id of entity to bind to object. \return Returns dmz::True if the site/host/entity was successfully bound to the object. \fn dmz::Boolean dmz::NetModuleIdentityMap::lookup_site_host_entity ( const Handle ObjectHandle, UInt32 &site, UInt32 &host, UInt32 &entity) \brief Looks up site/host/entity bound to object Handle. \param[in] ObjectHandle Handle of the object. \param[out] site Id of site. \param[out] host Id of host. \param[out] entity Id of entity. \return Returns dmz::True if a site/host/entity was found for the object. \fn dmz::Boolean dmz::NetModuleIdentityMap::store_name ( const Handle ObjectHandle, const String &Name) \brief Bind name to object. \param[in] ObjectHandle Handle of the object. \param[in] Name String containing the name to bind to the object. \fn dmz::Boolean dmz::NetModuleIdentityMap::lookup_name ( const Handle ObjectHandle, String &name) \brief Looks up name bound to object. \param[in] ObjectHandle Handle of the object. \param[out] name String containing the name bound to the object. \return Returns dmz::True if a name was bound to the object. \fn dmz::Boolean dmz::NetModuleIdentityMap::lookup_handle_from_name ( const String &Name, Handle &handle) \brief Looks up object handle bound to name. \param[in] Name String containing object name. \param[out] handle Handle containing bound object. \return Returns dmz::True if an object was bound to the name. \fn dmz::Boolean dmz::NetModuleIdentityMap::lookup_handle_from_site_host_entity ( const UInt32 Site, const UInt32 Host, const UInt32 Entity, Handle &handle) \brief Looks up object bound to site/host/entity. \param[in] Site Id of the site. \param[in] Host Id of the host. \param[in] Entity Id of the entity. \param[out] handle Handle of the bound object. \return Returns dmz::True if an object was bound to the site/host/entity. \fn dmz::Boolean dmz::NetModuleIdentityMap::remove_object (const Handle ObjectHandle) \brief Remove all bindings to a given object. \param[in] ObjectHandle Handle of object to unbind. \return Returns dmz::True if the object was successfully unbound. */
37.944444
89
0.786481
[ "object" ]
71e1f781b63a6657c7402c3053781492a07ca768
13,394
hh
C++
Detector/Tracker.hh
tassiell/TrackToy
3014e42361673b37c3de65fcd9a53ba94d66bcba
[ "Apache-2.0" ]
null
null
null
Detector/Tracker.hh
tassiell/TrackToy
3014e42361673b37c3de65fcd9a53ba94d66bcba
[ "Apache-2.0" ]
null
null
null
Detector/Tracker.hh
tassiell/TrackToy
3014e42361673b37c3de65fcd9a53ba94d66bcba
[ "Apache-2.0" ]
null
null
null
// // Cylindrical tracker // #ifndef TrackToy_Detector_Tracker_hh #define TrackToy_Detector_Tracker_hh #include "TrackToy/Detector/HollowCylinder.hh" #include "TrackToy/General/TrajUtilities.hh" #include "KinKal/MatEnv/MatDBInfo.hh" #include "TrackToy/General/ELossDistributions.hh" #include "KinKal/General/Vectors.hh" #include "KinKal/Trajectory/Line.hh" #include "KinKal/Detector/StrawXing.hh" #include "KinKal/Detector/StrawMaterial.hh" #include "KinKal/Examples/SimpleWireHit.hh" #include "TRandom3.h" #include "Math/VectorUtil.h" #include <string> #include <vector> #include <iostream> namespace TrackToy { class Tracker { public: enum CellOrientation{azimuthal=0,axial}; Tracker(MatEnv::MatDBInfo const& matdbinfo,std::string const& tfile,TRandom& tr); auto const& cylinder() const { return cyl_; } unsigned nCells() const { return ncells_; } double density() const { return density_;} // gm/mm^3 double driftVelocity() const { return vdrift_; } // mm/ns double propagationVelocity() const { return vprop_; } // mm/ns double driftResolution() const { return sigt_; } // ns double propagationResolution() const { return sigl_; } // ns double cellDensity() const { return cellDensity_;} // N/mm double cellRadius() const { return smat_->strawRadius(); } double rMin() const { return cyl_.rmin(); } double rMax() const { return cyl_.rmax(); } double zMin() const { return cyl_.zmin(); } double zMax() const { return cyl_.zmax(); } double zMid() const { return cyl_.zpos(); } void print(std::ostream& os) const; const KinKal::StrawMaterial* strawMaterial() const { return smat_; } // simulate hit and straw crossings along a particle trajectory. This also updates the trajectory for BField and material effects template<class KTRAJ> void simulateHits(KinKal::BFieldMap const& bfield, KinKal::ParticleTrajectory<KTRAJ>& mctraj, std::vector<std::shared_ptr<KinKal::Hit<KTRAJ>>>& hits, std::vector<std::shared_ptr<KinKal::ElementXing<KTRAJ>>>& xings, std::vector<KinKal::TimeRange>& tinters, double tol) const; private: // helper functions for simulating hits // create a line representing the wire for a time on a particle trajector. This embeds the timing information template <class KTRAJ> KinKal::Line wireLine(KinKal::ParticleTrajectory<KTRAJ> const& mctraj, KinKal::VEC3 wdir, double htime) const; // simulate hit and xing for a particular time on a particle trajectory and add them to the lists template <class KTRAJ> bool simulateHit(KinKal::BFieldMap const& bfield, KinKal::ParticleTrajectory<KTRAJ> const& mctraj, double htime, std::vector<std::shared_ptr<KinKal::Hit<KTRAJ>>>& hits, std::vector<std::shared_ptr<KinKal::ElementXing<KTRAJ>>>& xings ) const; // udpdate the trajectory for material effects template <class KTRAJ> void updateTraj(KinKal::BFieldMap const& bfield, KinKal::ParticleTrajectory<KTRAJ>& mctraj, const KinKal::ElementXing<KTRAJ>* sxing) const; private: HollowCylinder cyl_; // geometric form of the tracker CellOrientation orientation_; // orientation of the cells unsigned ncells_; // number of cells double cellDensity_; // effective linear cell density mm^-1 double minpath_; // minimum path to score hits double density_; // total average density gm/mm^3 KinKal::StrawMaterial* smat_; // straw material double vdrift_; // drift velocity double vprop_; // signal propagation velocity double sigt_; // transverse measurement time resolution sigma double sigl_; // longitudinal measurement time resolution sigma double lrdoca_; // minimum doca to resolve LR ambiguity double hiteff_; // hit efficiency double lowscat_, hiscat_, corefrac_; // factors for non-Gaussian scattering TRandom& tr_; // random number generator }; template<class KTRAJ> void Tracker::simulateHits(KinKal::BFieldMap const& bfield, KinKal::ParticleTrajectory<KTRAJ>& mctraj, std::vector<std::shared_ptr<KinKal::Hit<KTRAJ>>>& hits, std::vector<std::shared_ptr<KinKal::ElementXing<KTRAJ>>>& xings, std::vector<KinKal::TimeRange>& tinters, double tol) const { using KinKal::TimeRange; double tstart = mctraj.back().range().begin(); double speed = mctraj.speed(tstart); double tstep = cellRadius()/speed; // find intersections with tracker TimeRange trange = cylinder().intersect(mctraj,tstart,tstep); while( (!trange.null()) && trange.end() < mctraj.range().end()) { double clen = trange.range()*speed; if(clen > minpath_){ tinters.push_back(trange); unsigned ncells = (unsigned)floor(clen*cellDensity_); double hstep = trange.range()/(ncells+1); double htime = trange.begin()+0.5*hstep; for(unsigned icell=0;icell<ncells;++icell){ // extend the trajectory to this time extendTraj(bfield,mctraj,htime,tol); // create hits and xings for this time bool hashit=simulateHit(bfield,mctraj,htime,hits,xings); // update the trajector for the effect of this material if(hashit){ updateTraj(bfield, mctraj,xings.back().get()); } // update to the next htime += hstep; } } trange = cylinder().intersect(mctraj,trange.end(),tstep); } } template <class KTRAJ> bool Tracker::simulateHit(KinKal::BFieldMap const& bfield, KinKal::ParticleTrajectory<KTRAJ> const& mctraj, double htime, std::vector<std::shared_ptr<KinKal::Hit<KTRAJ>>>& hits, std::vector<std::shared_ptr<KinKal::ElementXing<KTRAJ>>>& xings ) const { using PTCA = KinKal::PiecewiseClosestApproach<KTRAJ,KinKal::Line>; using WIREHIT = KinKal::SimpleWireHit<KTRAJ>; using STRAWXING = KinKal::StrawXing<KTRAJ>; using STRAWXINGPTR = std::shared_ptr<STRAWXING>; using ROOT::Math::VectorUtil::PerpVector; // define the drift and wire directions static const KinKal::VEC3 zdir(0.0,0.0,1.0); KinKal::VEC3 wdir = zdir; if(orientation_ == azimuthal){ auto pos = mctraj.position3(htime); static double pi_over_3 = M_PI/3.0; // generate azimuthal angle WRT the hit double wphi = tr_.Uniform(0.0,pi_over_3); // acceptance test, using a triangular inner hole double rmax = 0.5*cyl_.rmax()/cos(wphi); if(pos.Rho() < rmax)return false; auto rdir = PerpVector(pos,zdir).Unit(); // radial direction auto fdir = zdir.Cross(rdir).Unit(); // azimuthal direction (increasing) wdir = fdir*cos(wphi) + rdir*sin(wphi); // std::cout << "wire rmin " << pos.Rho()*cos(phimax) << std::endl; } // create the line representing this hit's wire. The line embeds the timing information KinKal::Line const& wline = wireLine(mctraj,wdir,htime); // find the TPOCA between the particle trajectory and the wire line KinKal::CAHint tphint(htime,htime); static double tprec(1e-8); // TPOCA precision PTCA tp(mctraj,wline,tphint,tprec); // create the straw xing (regardless of inefficiency) auto xing = std::make_shared<STRAWXING>(tp,*smat_); xings.push_back(xing); // test for inefficiency double eff = tr_.Uniform(0.0,1.0); if(eff < hiteff_){ // check // std::cout << "doca " << tp.doca() << " sensor TOCA " << tp.sensorToca() - fabs(tp.doca())/vdrift_ << " particle TOCA " << tp.particleToca() << " hit time " << htime << std::endl; // define the initial ambiguity; it is the MC true value by default // preset to a null hit KinKal::WireHitState::State ambig(KinKal::WireHitState::null); if(fabs(tp.doca())> lrdoca_){ ambig = tp.doca() < 0 ? KinKal::WireHitState::left : KinKal::WireHitState::right; } KinKal::WireHitState whstate(ambig); double mindoca = std::min(lrdoca_,cellRadius()); // create the hit hits.push_back(std::make_shared<WIREHIT>(bfield, tp, whstate, mindoca, vdrift_, sigt_*sigt_, cellRadius())); } return true; } template <class KTRAJ> KinKal::Line Tracker::wireLine(KinKal::ParticleTrajectory<KTRAJ> const& mctraj, KinKal::VEC3 wdir, double htime) const { // find the position and direction of the particle at this time auto pos = mctraj.position3(htime); auto pdir = mctraj.direction(htime); // drift direction is perp to wire and particle auto ddir = pdir.Cross(wdir).Unit(); // uniform drift distance = uniform impact parameter (random sign) double rdrift = tr_.Uniform(-cellRadius(),cellRadius()); auto wpos = pos + rdrift*ddir; // find the wire ends; this is where the wire crosses the outer envelope double dprop, wlen; if(orientation_ == azimuthal){ double rwire = wpos.Rho(); // radius of the wire position // find crossing of outer cylinder double rmax = std::max(rwire,rMax()); double wdot = -wpos.Dot(wdir); double term = sqrt(wdot*wdot + (rmax*rmax - rwire*rwire)); double d1 = wdot+term; double d2 = wdot-term; wlen = fabs(d1)+fabs(d2); // choose the shortest propagation distance to define the measurement (earliest time) if(fabs(d1) < fabs(d2)){ dprop = fabs(d1); } else { wdir *= -1.0; // points from source to measurement location dprop = fabs(d2); } } else { // wire ends are at zmin and zmax double zmax = zMax() - wpos.Z(); double zmin = zMin() - wpos.Z(); wlen = zmax - zmin; if(fabs(zmax) < fabs(zmin)){ dprop = fabs(zmax); } else { wdir *= -1.0; // points from source to measurement location dprop = fabs(zmin); } } // measurement time includes propagation and drift double mtime = htime + dprop/vprop_ + fabs(rdrift)/vdrift_; // smear measurement time by the resolution mtime = tr_.Gaus(mtime,sigt_); // construct the trajectory for this hit. Note this embeds the timing and location information together auto mpos = wpos + dprop*wdir; // std::cout << "measurement radius " << mpos.Rho() << std::endl; return KinKal::Line(mpos,mtime,wdir*vprop_,wlen); } template <class KTRAJ> void Tracker::updateTraj(KinKal::BFieldMap const& bfield, KinKal::ParticleTrajectory<KTRAJ>& mctraj, const KinKal::ElementXing<KTRAJ>* sxing) const { static unsigned moyalterms_(20); // number of terms in Moyal expansion // simulate energy loss and multiple scattering from this xing auto txing = sxing->crossingTime(); auto const& endpiece = mctraj.nearestPiece(txing); auto endmom = endpiece.momentum4(txing); KinKal::VEC3 momvec = endmom.Vect(); double mom = momvec.R(); auto endpos = endpiece.position4(txing); std::array<double,3> dmom {0.0,0.0,0.0}, momvar {0.0,0.0,0.0}; sxing->materialEffects(mctraj,KinKal::TimeDir::forwards, dmom, momvar); // std::cout << "DMOM " << dmom[0] << std::endl; // note materialEffects returns the normalized energy change MoyalDist edist(MoyalDist::MeanRMS(fabs(dmom[KinKal::MomBasis::momdir_])*mom,sqrt(momvar[KinKal::MomBasis::momdir_])),moyalterms_); // radiation energy loss model BremssLoss bLoss; for(int idir=0;idir<=KinKal::MomBasis::phidir_; idir++) { auto mdir = static_cast<KinKal::MomBasis::Direction>(idir); double momsig = sqrt(momvar[idir]); double ionloss, bremloss, dloss; double dm; double radFrac = sxing->radiationFraction()/10; // convert to cm // only include wall material for now; gas can be added later TODO DeltaRayLoss dLoss(&(sxing->matXings()[0].dmat_), mom,sxing->matXings()[0].plen_/10.0, endpiece.mass()); // generate a random effect given this variance and mean. Note momEffect is scaled to momentum switch( mdir ) { case KinKal::MomBasis::perpdir_: case KinKal::MomBasis::phidir_ : // non-Gaussian scattering tails dm = tr_.Uniform(0.0,1.0) < corefrac_ ? tr_.Gaus(dmom[idir],lowscat_*momsig) : tr_.Gaus(dmom[idir],hiscat_*momsig); dm *= mom; // scale to momentum break; case KinKal::MomBasis::momdir_ : // calculate a smeared energy loss using a Moyal distribution ionloss = edist.sample(tr_.Uniform(0.0,1.0)); bremloss = bLoss.sampleSSPGamma(mom,radFrac); dloss = dLoss.sampleDRL(); // std::cout << "Tracker Ionization eloss = " << ionloss << " Delta eloss " << dloss << " rad eloss " << bremloss << std::endl; dm = std::max(-(ionloss+bremloss+dloss),-mom); // must be positive break; default: throw std::invalid_argument("Invalid direction"); } momvec += endpiece.direction(txing,mdir)*dm; } // std::cout << "startmom " << mom << " endmom " << momvec.R() << std::endl; endmom.SetCoordinates(momvec.X(), momvec.Y(), momvec.Z(),endmom.M()); // generate a new piece and append auto bnom = bfield.fieldVect(endpos.Vect()); // auto bnom = endpiece.bnom(); KTRAJ newend(endpos,endmom,endpiece.charge(),bnom,KinKal::TimeRange(txing,mctraj.range().end())); // mctraj.append(newend); mctraj.append(newend,true); // allow truncation if needed } } #endif
48.883212
190
0.660594
[ "vector", "model" ]
71e2c00d81d86c4b346b8456e1269bc385e2c776
3,170
inl
C++
clove/components/utilities/event/include/Clove/Event/EventManager.inl
mondoo/Clove
3989dc3fea0d886a69005c1e0bb4396501f336f2
[ "MIT" ]
33
2020-01-09T04:57:29.000Z
2021-08-14T08:02:43.000Z
clove/components/utilities/event/include/Clove/Event/EventManager.inl
mondoo/Clove
3989dc3fea0d886a69005c1e0bb4396501f336f2
[ "MIT" ]
234
2019-10-25T06:04:35.000Z
2021-08-18T05:47:41.000Z
clove/components/utilities/event/include/Clove/Event/EventManager.inl
mondoo/Clove
3989dc3fea0d886a69005c1e0bb4396501f336f2
[ "MIT" ]
4
2020-02-11T15:28:42.000Z
2020-09-07T16:22:58.000Z
#include <optional> namespace clove { template<typename EventType> EventManager::EventContainer<EventType>::EventContainer() = default; template<typename EventType> EventManager::EventContainer<EventType>::EventContainer(EventContainer &&other) noexcept = default; template<typename EventType> EventManager::EventContainer<EventType> &EventManager::EventContainer<EventType>::operator=(EventContainer &&other) noexcept = default; template<typename EventType> EventManager::EventContainer<EventType>::~EventContainer() = default; template<typename EventType> EventHandle EventManager::EventContainer<EventType>::addListener(ContainerFunctionType function) { listeners.push_back(function); ListenerId const id{ nextId++ }; listenerIdToIndexMap[id] = listeners.size() - 1; return { id, this }; } template<typename EventType> void EventManager::EventContainer<EventType>::removeListener(ListenerId id) { if(auto iter = listenerIdToIndexMap.find(id); iter != listenerIdToIndexMap.end()) { size_t const index{ iter->second }; size_t const lastIndex{ listeners.size() - 1 }; std::optional<ListenerId> movedEvent; if(index < lastIndex) { for(auto &&idToIndexPair : listenerIdToIndexMap) { if(idToIndexPair.second == lastIndex) { movedEvent = idToIndexPair.first; break; } } listeners[iter->second] = listeners.back(); } listeners.pop_back(); listenerIdToIndexMap.erase(id); if(movedEvent) { listenerIdToIndexMap[*movedEvent] = index; } } } template<typename EventType> typename std::vector<typename EventManager::EventContainer<EventType>::ContainerFunctionType>::iterator EventManager::EventContainer<EventType>::begin() { return listeners.begin(); } template<typename EventType> typename std::vector<typename EventManager::EventContainer<EventType>::ContainerFunctionType>::const_iterator EventManager::EventContainer<EventType>::begin() const { return listeners.begin(); } template<typename EventType> typename std::vector<typename EventManager::EventContainer<EventType>::ContainerFunctionType>::iterator EventManager::EventContainer<EventType>::end() { return listeners.end(); } template<typename EventType> typename std::vector<typename EventManager::EventContainer<EventType>::ContainerFunctionType>::const_iterator EventManager::EventContainer<EventType>::end() const { return listeners.end(); } template<typename EventType> EventManager::EventContainer<EventType> &EventManager::getEventContainer() { const size_t eventId = typeid(EventType).hash_code(); if(containers.find(eventId) == containers.end()) { containers[eventId] = std::make_unique<EventContainer<EventType>>(); } return static_cast<EventContainer<EventType> &>(*containers[eventId]); } }
38.658537
170
0.668139
[ "vector" ]
71e43f0cf1fae5ca545eca376e8507505ba58984
27,538
cpp
C++
src/miner.cpp
tradecraftio/tradecraft
a014fea4d4656df67aef19e379f10322386cf6f8
[ "MIT" ]
10
2019-03-08T04:10:37.000Z
2021-08-20T11:55:14.000Z
src/miner.cpp
tradecraftio/tradecraft
a014fea4d4656df67aef19e379f10322386cf6f8
[ "MIT" ]
69
2018-11-09T20:29:29.000Z
2021-10-05T00:08:36.000Z
src/miner.cpp
tradecraftio/tradecraft
a014fea4d4656df67aef19e379f10322386cf6f8
[ "MIT" ]
7
2019-01-21T06:00:18.000Z
2021-12-19T16:18:00.000Z
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2019 The Bitcoin Core developers // Copyright (c) 2011-2021 The Freicoin Developers // // This program is free software: you can redistribute it and/or modify it under // the terms of version 3 of the GNU Affero General Public License 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 <https://www.gnu.org/licenses/>. #include <miner.h> #include <amount.h> #include <chain.h> #include <chainparams.h> #include <coins.h> #include <consensus/consensus.h> #include <consensus/merkle.h> #include <consensus/tx_verify.h> #include <consensus/validation.h> #include <hash.h> #include <net.h> #include <policy/feerate.h> #include <policy/policy.h> #include <pow.h> #include <primitives/transaction.h> #include <script/standard.h> #include <timedata.h> #include <util/moneystr.h> #include <util/system.h> #include <validationinterface.h> #include <algorithm> #include <queue> #include <utility> int64_t UpdateTime(CBlockHeader* pblock, const Consensus::Params& consensusParams, const CBlockIndex* pindexPrev) { int64_t nOldTime = pblock->nTime; int64_t nNewTime = std::max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime()); if (nOldTime < nNewTime) pblock->nTime = nNewTime; return nNewTime - nOldTime; } BlockAssembler::Options::Options() { blockMinFeeRate = CFeeRate(DEFAULT_BLOCK_MIN_TX_FEE); nBlockMaxWeight = DEFAULT_BLOCK_MAX_WEIGHT; } BlockAssembler::BlockAssembler(const CChainParams& params, const Options& options) : chainparams(params) { blockMinFeeRate = options.blockMinFeeRate; // Limit weight to between 4K and MAX_BLOCK_WEIGHT-4K for sanity: nBlockMaxWeight = std::max<size_t>(4000, std::min<size_t>(MAX_BLOCK_WEIGHT - 4000, options.nBlockMaxWeight)); nMedianTimePast = 0; block_final_state = NO_BLOCK_FINAL_TX; } static BlockAssembler::Options DefaultOptions() { // Block resource limits // If -blockmaxweight is not given, limit to DEFAULT_BLOCK_MAX_WEIGHT BlockAssembler::Options options; options.nBlockMaxWeight = gArgs.GetArg("-blockmaxweight", DEFAULT_BLOCK_MAX_WEIGHT); CAmount n = 0; if (gArgs.IsArgSet("-blockmintxfee") && ParseMoney(gArgs.GetArg("-blockmintxfee", ""), n)) { options.blockMinFeeRate = CFeeRate(n); } else { options.blockMinFeeRate = CFeeRate(DEFAULT_BLOCK_MIN_TX_FEE); } return options; } BlockAssembler::BlockAssembler(const CChainParams& params) : BlockAssembler(params, DefaultOptions()) {} void BlockAssembler::resetBlock() { inBlock.clear(); // Reserve space for coinbase tx nBlockWeight = 4000; nBlockSigOpsCost = 400; fIncludeWitness = false; // These counters do not include coinbase tx nBlockTx = 0; nFees = 0; nMedianTimePast = 0; block_final_state = NO_BLOCK_FINAL_TX; } Optional<int64_t> BlockAssembler::m_last_block_num_txs{nullopt}; Optional<int64_t> BlockAssembler::m_last_block_weight{nullopt}; std::unique_ptr<CBlockTemplate> BlockAssembler::CreateNewBlock(const CScript& scriptPubKeyIn) { int64_t nTimeStart = GetTimeMicros(); resetBlock(); pblocktemplate.reset(new CBlockTemplate()); if(!pblocktemplate.get()) return nullptr; pblock = &pblocktemplate->block; // pointer for convenience // Add dummy coinbase tx as first transaction pblock->vtx.emplace_back(); pblocktemplate->vTxFees.push_back(-1); // updated at end pblocktemplate->vTxSigOpsCost.push_back(-1); // updated at end LOCK2(cs_main, mempool.cs); CBlockIndex* pindexPrev = chainActive.Tip(); assert(pindexPrev != nullptr); nHeight = pindexPrev->nHeight + 1; pblock->nVersion = ComputeBlockVersion(pindexPrev, chainparams.GetConsensus()); // -regtest only: allow overriding block.nVersion with // -blockversion=N to test forking scenarios if (chainparams.MineBlocksOnDemand()) pblock->nVersion = gArgs.GetArg("-blockversion", pblock->nVersion); pblock->nTime = GetAdjustedTime(); nMedianTimePast = pindexPrev->GetMedianTimePast(); nLockTimeCutoff = (STANDARD_LOCKTIME_VERIFY_FLAGS & LOCKTIME_MEDIAN_TIME_PAST) ? nMedianTimePast : pblock->GetBlockTime(); // Check if block-final tx rules are enforced. For the moment this // tracks just whether the soft-fork is active, but by the time we get // to transaction selection it will only be true if there is a // block-final transaction in this block template. if (VersionBitsState(pindexPrev, chainparams.GetConsensus(), Consensus::DEPLOYMENT_FINALTX, versionbitscache) == ThresholdState::ACTIVE) { block_final_state = HAS_BLOCK_FINAL_TX; } // Check if this is the first block for which the block-final rules are // enforced, in which case all we need to do is add the initial // anyone-can-spend output. if ((block_final_state == HAS_BLOCK_FINAL_TX) && (!pindexPrev->pprev || (VersionBitsState(pindexPrev->pprev, chainparams.GetConsensus(), Consensus::DEPLOYMENT_FINALTX, versionbitscache) != ThresholdState::ACTIVE))) { block_final_state = INITIAL_BLOCK_FINAL_TXOUT; } // Otherwise we will need to check if the prior block-final transaction // was a coinbase and if insufficient blocks have occured for it to mature. BlockFinalTxEntry final_tx; if (block_final_state == HAS_BLOCK_FINAL_TX) { final_tx = pcoinsTip->GetFinalTx(); if (final_tx.IsNull()) { // Should never happen return nullptr; } // Fetch the unspent outputs of the last block-final tx. This call // should always return results because the prior block-final // transaction was the last processed transaction (so none of the // outputs could have been spent) or a previously immature coinbase. for (uint32_t n = 0; n < final_tx.size; ++n) { COutPoint prevout(final_tx.hash, n); const auto& coin = pcoinsTip->AccessCoin(prevout); if (coin.IsSpent()) { // Should never happen return nullptr; } // If it was a coinbase, meaning we're in the first 100 blocks after // activation, then we need to make sure it has matured, otherwise // we do nothing at all. if (coin.IsCoinBase() && (nHeight - coin.nHeight < COINBASE_MATURITY)) { // Still maturing. Nothing to do. block_final_state = NO_BLOCK_FINAL_TX; break; } } } // Decide whether to include witness transactions // This is only needed in case the witness softfork activation is reverted // (which would require a very deep reorganization). // Note that the mempool would accept transactions with witness data before // IsWitnessEnabled, but we would only ever mine blocks after IsWitnessEnabled // unless there is a massive block reorganization with the witness softfork // not activated. // TODO: replace this with a call to main to assess validity of a mempool // transaction (which in most cases can be a no-op). fIncludeWitness = IsWitnessEnabled(pindexPrev, chainparams.GetConsensus()); if (block_final_state == HAS_BLOCK_FINAL_TX) initFinalTx(final_tx); int nPackagesSelected = 0; int nDescendantsUpdated = 0; addPackageTxs(nPackagesSelected, nDescendantsUpdated); int64_t nTime1 = GetTimeMicros(); m_last_block_num_txs = nBlockTx; m_last_block_weight = nBlockWeight; // Create coinbase transaction. CMutableTransaction coinbaseTx; coinbaseTx.vin.resize(1); coinbaseTx.vin[0].prevout.SetNull(); coinbaseTx.vout.resize(1); coinbaseTx.vout[0].scriptPubKey = scriptPubKeyIn; coinbaseTx.vout[0].SetReferenceValue(nFees + GetBlockSubsidy(nHeight, chainparams.GetConsensus())); if (block_final_state == INITIAL_BLOCK_FINAL_TXOUT) { CTxOut txout(0, CScript() << OP_TRUE); coinbaseTx.vout.insert(coinbaseTx.vout.begin(), txout); } coinbaseTx.vin[0].scriptSig = CScript() << nHeight << OP_0; // Consensus rule: lock-time of coinbase MUST be median-time-past coinbaseTx.nLockTime = static_cast<uint32_t>(nMedianTimePast); coinbaseTx.lock_height = nHeight; pblock->vtx[0] = MakeTransactionRef(std::move(coinbaseTx)); if (block_final_state == HAS_BLOCK_FINAL_TX) { GenerateCoinbaseCommitment(*pblock, pindexPrev, chainparams.GetConsensus()); } pblocktemplate->vTxFees[0] = -nFees; // The miner needs to know whether the last transaction is a special // transaction, or not. pblocktemplate->has_block_final_tx = (block_final_state == HAS_BLOCK_FINAL_TX); LogPrintf("CreateNewBlock(): block weight: %u txs: %u fees: %ld sigops %d\n", GetBlockWeight(*pblock), nBlockTx, (block_final_state == HAS_BLOCK_FINAL_TX) ? nFees - pblocktemplate->vTxFees.back() : nFees, nBlockSigOpsCost); // Fill in header pblock->hashPrevBlock = pindexPrev->GetBlockHash(); UpdateTime(pblock, chainparams.GetConsensus(), pindexPrev); pblock->nBits = GetNextWorkRequired(pindexPrev, pblock, chainparams.GetConsensus()); pblock->nNonce = 0; pblocktemplate->vTxSigOpsCost[0] = WITNESS_SCALE_FACTOR * GetLegacySigOpCount(*pblock->vtx[0]); // Use of auxiliary proof-of-work is required after merge mining has // activated. Since interfacing with the auxiliary chain is outside of // scope for this code, we generate a minimal auxiliary header. if (VersionBitsState(pindexPrev, chainparams.GetConsensus(), Consensus::DEPLOYMENT_AUXPOW, versionbitscache) == ThresholdState::ACTIVE) { // Setup the block header commitment. pblock->m_aux_pow.m_commit_version = pblock->nVersion; pblock->m_aux_pow.m_commit_hash_merkle_root = BlockTemplateMerkleRoot(*pblock, nullptr); // Setup a fake auxiliary block with a single "transaction" (not an // actual transaction as no valid data precedes the midstate). CSHA256().Midstate(pblock->m_aux_pow.m_midstate_hash.begin(), nullptr, nullptr); pblock->m_aux_pow.m_aux_num_txns = 1; // Set difficulty for the auxiliary proof-of-work. pblock->SetFilteredTime(GetFilteredTimeAux(pindexPrev, chainparams.GetConsensus())); pblock->m_aux_pow.m_commit_bits = GetNextWorkRequiredAux(pindexPrev, *pblock, chainparams.GetConsensus());; // Setup the auxiliary header fields to have reasonable values. pblock->m_aux_pow.m_aux_version = VERSIONBITS_TOP_BITS; pblock->m_aux_pow.m_aux_bits = pblock->m_aux_pow.m_commit_bits; } CValidationState state; if (!TestBlockValidity(state, chainparams, *pblock, pindexPrev, false, false)) { throw std::runtime_error(strprintf("%s: TestBlockValidity failed: %s", __func__, FormatStateMessage(state))); } int64_t nTime2 = GetTimeMicros(); LogPrint(BCLog::BENCH, "CreateNewBlock() packages: %.2fms (%d packages, %d updated descendants), validity: %.2fms (total %.2fms)\n", 0.001 * (nTime1 - nTimeStart), nPackagesSelected, nDescendantsUpdated, 0.001 * (nTime2 - nTime1), 0.001 * (nTime2 - nTimeStart)); return std::move(pblocktemplate); } void BlockAssembler::onlyUnconfirmed(CTxMemPool::setEntries& testSet) { for (CTxMemPool::setEntries::iterator iit = testSet.begin(); iit != testSet.end(); ) { // Only test txs not already in the block if (inBlock.count(*iit)) { testSet.erase(iit++); } else { iit++; } } } bool BlockAssembler::TestPackage(uint64_t packageSize, int64_t packageSigOpsCost) const { // TODO: switch to weight-based accounting for packages instead of vsize-based accounting. if (nBlockWeight + WITNESS_SCALE_FACTOR * packageSize >= nBlockMaxWeight) return false; if (nBlockSigOpsCost + packageSigOpsCost >= MAX_BLOCK_SIGOPS_COST) return false; return true; } // Perform transaction-level checks before adding to block: // - transaction finality (locktime) // - premature witness (in case segwit transactions are added to mempool before // segwit activation) bool BlockAssembler::TestPackageTransactions(const CTxMemPool::setEntries& package) { for (CTxMemPool::txiter it : package) { if (!IsFinalTx(it->GetTx(), nHeight, nLockTimeCutoff)) return false; if (!fIncludeWitness && it->GetTx().HasWitness()) return false; } return true; } void BlockAssembler::AddToBlock(CTxMemPool::txiter iter) { // If we have a block-final transaction, insert just // before the end, so the block-final tx remains last. pblock->vtx.insert(pblock->vtx.end() - (block_final_state == HAS_BLOCK_FINAL_TX), iter->GetSharedTx()); pblocktemplate->vTxFees.insert(pblocktemplate->vTxFees.end() - (block_final_state == HAS_BLOCK_FINAL_TX), iter->GetFee()); pblocktemplate->vTxSigOpsCost.insert(pblocktemplate->vTxSigOpsCost.end() - (block_final_state == HAS_BLOCK_FINAL_TX), iter->GetSigOpCost()); nBlockWeight += iter->GetTxWeight(); ++nBlockTx; nBlockSigOpsCost += iter->GetSigOpCost(); nFees += GetTimeAdjustedValue(iter->GetFee(), nHeight - iter->GetReferenceHeight()); inBlock.insert(iter); bool fPrintPriority = gArgs.GetBoolArg("-printpriority", DEFAULT_PRINTPRIORITY); if (fPrintPriority) { LogPrintf("fee %s txid %s\n", CFeeRate(iter->GetModifiedFee(), iter->GetTxSize()).ToString(), iter->GetTx().GetHash().ToString()); } } int BlockAssembler::UpdatePackagesForAdded(const CTxMemPool::setEntries& alreadyAdded, indexed_modified_transaction_set &mapModifiedTx) { int nDescendantsUpdated = 0; for (CTxMemPool::txiter it : alreadyAdded) { CTxMemPool::setEntries descendants; mempool.CalculateDescendants(it, descendants); // Insert all descendants (not yet in block) into the modified set for (CTxMemPool::txiter desc : descendants) { if (alreadyAdded.count(desc)) continue; ++nDescendantsUpdated; modtxiter mit = mapModifiedTx.find(desc); if (mit == mapModifiedTx.end()) { CTxMemPoolModifiedEntry modEntry(desc); modEntry.nSizeWithAncestors -= it->GetTxSize(); modEntry.nModFeesWithAncestors -= it->GetModifiedFee(); modEntry.nSigOpCostWithAncestors -= it->GetSigOpCost(); mapModifiedTx.insert(modEntry); } else { mapModifiedTx.modify(mit, update_for_parent_inclusion(it)); } } } return nDescendantsUpdated; } // Skip entries in mapTx that are already in a block or are present // in mapModifiedTx (which implies that the mapTx ancestor state is // stale due to ancestor inclusion in the block) // Also skip transactions that we've already failed to add. This can happen if // we consider a transaction in mapModifiedTx and it fails: we can then // potentially consider it again while walking mapTx. It's currently // guaranteed to fail again, but as a belt-and-suspenders check we put it in // failedTx and avoid re-evaluation, since the re-evaluation would be using // cached size/sigops/fee values that are not actually correct. bool BlockAssembler::SkipMapTxEntry(CTxMemPool::txiter it, indexed_modified_transaction_set &mapModifiedTx, CTxMemPool::setEntries &failedTx) { assert (it != mempool.mapTx.end()); return mapModifiedTx.count(it) || inBlock.count(it) || failedTx.count(it); } void BlockAssembler::SortForBlock(const CTxMemPool::setEntries& package, std::vector<CTxMemPool::txiter>& sortedEntries) { // Sort package by ancestor count // If a transaction A depends on transaction B, then A's ancestor count // must be greater than B's. So this is sufficient to validly order the // transactions for block inclusion. sortedEntries.clear(); sortedEntries.insert(sortedEntries.begin(), package.begin(), package.end()); std::sort(sortedEntries.begin(), sortedEntries.end(), CompareTxIterByAncestorCount()); } void BlockAssembler::initFinalTx(const BlockFinalTxEntry& final_tx) { // Block-final transactions are only created after we have reached the final // state of activation. if (block_final_state != HAS_BLOCK_FINAL_TX) { return; } // Create block-final tx CMutableTransaction txFinal; txFinal.nVersion = 2; txFinal.vout.resize(1); txFinal.vout[0].SetReferenceValue(0); txFinal.vout[0].scriptPubKey = CScript() << OP_TRUE; txFinal.nLockTime = static_cast<uint32_t>(nMedianTimePast); txFinal.lock_height = nHeight; // Add all outputs from the prior block-final transaction. We do nothing // here to prevent selected transactions from spending these same outputs // out from underneath us; we depend insted on mempool protections that // prevent such transactions from being considered in the first place. for (uint32_t n = 0; n < final_tx.size; ++n) { COutPoint prevout(final_tx.hash, n); const Coin& coin = pcoinsTip->AccessCoin(prevout); if (IsTriviallySpendable(coin, prevout, MANDATORY_SCRIPT_VERIFY_FLAGS|SCRIPT_VERIFY_WITNESS|SCRIPT_VERIFY_CLEANSTACK)) { txFinal.vin.push_back(CTxIn(prevout, CScript(), CTxIn::SEQUENCE_FINAL)); } else { LogPrintf("WARNING: non-trivial output in block-final transaction record; this should never happen (%s:%n)\n", prevout.hash.ToString(), prevout.n); } } // The previous loop should have found and added at least one input from the // prior block-final transaction, so this check should never pass. The // situation in which it would is if the fork is aborted after lock-in or // activation, a truly abornmal circumstance in which this version of the // client should stop generating blocks anyway. assert(!txFinal.vin.empty()); // Add block-final transaction to block template. pblock->vtx.emplace_back(MakeTransactionRef(std::move(txFinal))); // Record the fees forwarded by the block-final transaction to the coinbase. CAmount nTxFees = pcoinsTip->GetValueIn(*pblock->vtx.back()) - pblock->vtx.back()->GetValueOut(); nTxFees = GetTimeAdjustedValue(nTxFees, nHeight - txFinal.lock_height); pblocktemplate->vTxFees.push_back(nTxFees); nFees += nTxFees; // The block-final transaction contributes to aggregate limits: // the number of sigops is tracked... int64_t nTxSigOpsCost = GetTransactionSigOpCost(*pblock->vtx.back(), *pcoinsTip, STANDARD_SCRIPT_VERIFY_FLAGS); pblocktemplate->vTxSigOpsCost.push_back(nTxSigOpsCost); nBlockSigOpsCost += nTxSigOpsCost; // ...the size is not: nBlockWeight += GetTransactionWeight(*pblock->vtx.back()); } // This transaction selection algorithm orders the mempool based // on feerate of a transaction including all unconfirmed ancestors. // Since we don't remove transactions from the mempool as we select them // for block inclusion, we need an alternate method of updating the feerate // of a transaction with its not-yet-selected ancestors as we go. // This is accomplished by walking the in-mempool descendants of selected // transactions and storing a temporary modified state in mapModifiedTxs. // Each time through the loop, we compare the best transaction in // mapModifiedTxs with the next transaction in the mempool to decide what // transaction package to work on next. void BlockAssembler::addPackageTxs(int &nPackagesSelected, int &nDescendantsUpdated) { // mapModifiedTx will store sorted packages after they are modified // because some of their txs are already in the block indexed_modified_transaction_set mapModifiedTx; // Keep track of entries that failed inclusion, to avoid duplicate work CTxMemPool::setEntries failedTx; // Start by adding all descendants of previously added txs to mapModifiedTx // and modifying them for their already included ancestors UpdatePackagesForAdded(inBlock, mapModifiedTx); CTxMemPool::indexed_transaction_set::index<ancestor_score>::type::iterator mi = mempool.mapTx.get<ancestor_score>().begin(); CTxMemPool::txiter iter; // Limit the number of attempts to add transactions to the block when it is // close to full; this is just a simple heuristic to finish quickly if the // mempool has a lot of entries. const int64_t MAX_CONSECUTIVE_FAILURES = 1000; int64_t nConsecutiveFailed = 0; while (mi != mempool.mapTx.get<ancestor_score>().end() || !mapModifiedTx.empty()) { // First try to find a new transaction in mapTx to evaluate. if (mi != mempool.mapTx.get<ancestor_score>().end() && SkipMapTxEntry(mempool.mapTx.project<0>(mi), mapModifiedTx, failedTx)) { ++mi; continue; } // Now that mi is not stale, determine which transaction to evaluate: // the next entry from mapTx, or the best from mapModifiedTx? bool fUsingModified = false; modtxscoreiter modit = mapModifiedTx.get<ancestor_score>().begin(); if (mi == mempool.mapTx.get<ancestor_score>().end()) { // We're out of entries in mapTx; use the entry from mapModifiedTx iter = modit->iter; fUsingModified = true; } else { // Try to compare the mapTx entry to the mapModifiedTx entry iter = mempool.mapTx.project<0>(mi); if (modit != mapModifiedTx.get<ancestor_score>().end() && CompareTxMemPoolEntryByAncestorFee()(*modit, CTxMemPoolModifiedEntry(iter))) { // The best entry in mapModifiedTx has higher score // than the one from mapTx. // Switch which transaction (package) to consider iter = modit->iter; fUsingModified = true; } else { // Either no entry in mapModifiedTx, or it's worse than mapTx. // Increment mi for the next loop iteration. ++mi; } } // We skip mapTx entries that are inBlock, and mapModifiedTx shouldn't // contain anything that is inBlock. assert(!inBlock.count(iter)); uint64_t packageSize = iter->GetSizeWithAncestors(); CAmount packageFees = iter->GetModFeesWithAncestors(); int64_t packageSigOpsCost = iter->GetSigOpCostWithAncestors(); if (fUsingModified) { packageSize = modit->nSizeWithAncestors; packageFees = modit->nModFeesWithAncestors; packageSigOpsCost = modit->nSigOpCostWithAncestors; } // Ignore demurrage calculations if the refheight age is less than // 1008 blocks (1.5 weeks), to speed up block template construction. // This heuristic has an error of less than 0.1%. if ((iter->GetReferenceHeight() + 1008) < nHeight) { packageFees = GetTimeAdjustedValue(packageFees, nHeight - iter->GetReferenceHeight()); } if (packageFees < blockMinFeeRate.GetFee(packageSize)) { // Everything else we might consider has a lower fee rate return; } if (!TestPackage(packageSize, packageSigOpsCost)) { if (fUsingModified) { // Since we always look at the best entry in mapModifiedTx, // we must erase failed entries so that we can consider the // next best entry on the next loop iteration mapModifiedTx.get<ancestor_score>().erase(modit); failedTx.insert(iter); } ++nConsecutiveFailed; if (nConsecutiveFailed > MAX_CONSECUTIVE_FAILURES && nBlockWeight > nBlockMaxWeight - 4000) { // Give up if we're close to full and haven't succeeded in a while break; } continue; } CTxMemPool::setEntries ancestors; uint64_t nNoLimit = std::numeric_limits<uint64_t>::max(); std::string dummy; mempool.CalculateMemPoolAncestors(*iter, ancestors, nNoLimit, nNoLimit, nNoLimit, nNoLimit, dummy, false); onlyUnconfirmed(ancestors); ancestors.insert(iter); // Test if all tx's are Final if (!TestPackageTransactions(ancestors)) { if (fUsingModified) { mapModifiedTx.get<ancestor_score>().erase(modit); failedTx.insert(iter); } continue; } // This transaction will make it in; reset the failed counter. nConsecutiveFailed = 0; // Package can be added. Sort the entries in a valid order. std::vector<CTxMemPool::txiter> sortedEntries; SortForBlock(ancestors, sortedEntries); for (size_t i=0; i<sortedEntries.size(); ++i) { AddToBlock(sortedEntries[i]); // Erase from the modified set, if present mapModifiedTx.erase(sortedEntries[i]); } ++nPackagesSelected; // Update transactions that depend on each of these nDescendantsUpdated += UpdatePackagesForAdded(ancestors, mapModifiedTx); } } void IncrementExtraNonceAux(CBlock& block, std::vector<unsigned char>& extranonce) { // Update extranonce static uint256 hashPrevBlock; if (hashPrevBlock != block.hashPrevBlock) { extranonce.clear(); hashPrevBlock = block.hashPrevBlock; } else { bool carry = true; for (int i = 0; i < extranonce.size(); ++i) { ++extranonce[i]; if (extranonce[i]) { carry = false; break; } } if (carry) { extranonce.push_back(0); } } block.m_aux_pow.m_midstate_buffer = extranonce; block.m_aux_pow.m_midstate_length = extranonce.size(); } void IncrementExtraNonce(CBlock* pblock, const Consensus::Params& consensusParams, const CBlockIndex* pindexPrev, unsigned int& nExtraNonce, boost::optional<uint256> aux_hash2) { // Update nExtraNonce static uint256 hashPrevBlock; if (hashPrevBlock != pblock->hashPrevBlock) { nExtraNonce = 0; hashPrevBlock = pblock->hashPrevBlock; } ++nExtraNonce; unsigned int nHeight = pindexPrev->nHeight+1; // Height first in coinbase required for block.version=2 CMutableTransaction txCoinbase(*pblock->vtx[0]); txCoinbase.vin[0].scriptSig = (CScript() << nHeight << CScriptNum(nExtraNonce)) + COINBASE_FLAGS; if (aux_hash2) { txCoinbase.vin[0].scriptSig.insert(txCoinbase.vin[0].scriptSig.end(), aux_hash2->begin(), aux_hash2->end()); } assert(txCoinbase.vin[0].scriptSig.size() <= 100); pblock->vtx[0] = MakeTransactionRef(std::move(txCoinbase)); if (GetWitnessCommitment(*pblock, nullptr, nullptr)) { GenerateCoinbaseCommitment(*pblock, pindexPrev, consensusParams); } pblock->hashMerkleRoot = BlockMerkleRoot(*pblock); }
42.76087
266
0.684037
[ "vector" ]
71e4d3c7d88b85f9daf50783c096697b52e9b0b6
1,870
cpp
C++
boardNode.cpp
GregTalotta/cs405_hw2
7c54fdd0873e13ab597ab9a2668f91c2ed2c78a9
[ "MIT" ]
null
null
null
boardNode.cpp
GregTalotta/cs405_hw2
7c54fdd0873e13ab597ab9a2668f91c2ed2c78a9
[ "MIT" ]
null
null
null
boardNode.cpp
GregTalotta/cs405_hw2
7c54fdd0873e13ab597ab9a2668f91c2ed2c78a9
[ "MIT" ]
null
null
null
#include "boardNode.h" using std::rand; using std::vector; std::shared_ptr<BoardNode> BoardNode::getRandomChild() { int pos = rand() % (int)children.size(); return children[pos]; } std::shared_ptr<BoardNode> BoardNode::getBestChild() { std::shared_ptr<BoardNode> best = children[0]; for (int i = 1; i < children.size(); ++i) { if (children[i]->value() > best->value()) { best = children[i]; } } return best; } BoardNode::BoardNode(std::vector<std::vector<char>> nboard, char p) { board = nboard; piece = p; } BoardNode::BoardNode(std::vector<std::vector<char>> nboard, char p, std::shared_ptr<BoardNode> pnode, int posx, int posy) { board = nboard; parent = pnode; piece = p; x = posx; y = posy; } double BoardNode::value() { if (visits == 0) { return 0; } return ((wins + draws) / visits); } char BoardNode::changePiece(char piece) { if (piece == 'x') { return 'o'; } return 'x'; } bool BoardNode::validMove(vector<vector<char>> &playingBoard, int posx, int posy) { return playingBoard[posy][posx] == ' '; } void BoardNode::addLayer(std::shared_ptr<BoardNode> base) { for (int j = 0; j < base->board.size(); ++j) { for (int i = 0; i < base->board.size(); ++i) { if (validMove(board, i, j)) { board[j][i] = changePiece(base->piece); children.push_back(std::make_unique<BoardNode>(BoardNode(board, changePiece(base->piece), base, i, j))); board[j][i] = ' '; } } } } void BoardNode::growTree(int depth) { if (depth == 1) { return; } for (int i = 0; i < children.size(); ++i) { children[i]->addLayer(children[i]); children[i]->growTree(depth - 1); } }
20.777778
121
0.54385
[ "vector" ]
71e7b33e768b94751786c0dcbe8867332249f666
1,543
cpp
C++
CaesarCipher/caesarcipher.cpp
Asyrion/cplusplus
5173b759dc4f34e9be0f49ada079c39946fe7e26
[ "MIT" ]
null
null
null
CaesarCipher/caesarcipher.cpp
Asyrion/cplusplus
5173b759dc4f34e9be0f49ada079c39946fe7e26
[ "MIT" ]
null
null
null
CaesarCipher/caesarcipher.cpp
Asyrion/cplusplus
5173b759dc4f34e9be0f49ada079c39946fe7e26
[ "MIT" ]
1
2019-05-04T18:23:39.000Z
2019-05-04T18:23:39.000Z
#include <string> #include <iostream> #include <algorithm> #include <cctype> class MyTransform { private: int shift; public: MyTransform( int s ) : shift( s ) {} char operator() (char c) { if( isspace(c)) return 0; else { static std::string letters("abcdefghijklmnopqrstuvwxyz"); std::string::size_type found = letters.find(tolower(c)); int shiftedpos = (static_cast<int>(found) + shift) % 26; if(shiftedpos < 0) { shiftedpos = 26 + shiftedpos; } char shifted = letters[shiftedpos]; return shifted; } } }; int main() { std::string input; std::cout << "\t********* CAESAR CIPHER *********\t\n\t\n"; std::cout << "\tWhich text do you want to be encrypted?\n"; // Write to our variable getline(std::cin, input); std::cout << "\t Please enter the key to shift/encrypt with: \n"; int myshift = 0; std::cin >> myshift; std::cout << " Before encryption: " << input << std::endl; std::transform(input.begin(), input.end(), input.begin(), MyTransform(myshift)); std::cout << " After encryption: " << input << std::endl; myshift *= -1; // decrypting again std::transform(input.begin(), input.end(), input.begin(), MyTransform(myshift)); std::cout << " After decryption: " << input << std::endl; return 0; }
27.553571
84
0.515878
[ "transform" ]
71ead71b9ab9037432460863c12107f038aebbe1
1,106
cpp
C++
prompt412/study-0123/1325-hacking.cpp
honux77/algorithm
2ed8cef1fbee7ad96d8f2ae583666d52bd8892ee
[ "MIT" ]
2
2019-02-08T01:23:07.000Z
2020-11-19T12:23:52.000Z
prompt412/study-0123/1325-hacking.cpp
honux77/algorithm
2ed8cef1fbee7ad96d8f2ae583666d52bd8892ee
[ "MIT" ]
null
null
null
prompt412/study-0123/1325-hacking.cpp
honux77/algorithm
2ed8cef1fbee7ad96d8f2ae583666d52bd8892ee
[ "MIT" ]
null
null
null
#include <cstdio> #include <iostream> #include <vector> #include <algorithm> using namespace std; using i64 = long long int; using ii = pair<int, int>; using ii64 = pair<i64, i64>; vector<int> edge[10001]; int vcount = 0; void dfs(int s, vector<bool> &visit) { vcount++; visit[s] = true; for(auto nxt: edge[s]) { if (!visit[nxt]) dfs(nxt, visit); } } int main() { ios_base::sync_with_stdio(false); cin.tie(nullptr); int n, e; cin >> n >> e; for (int i = 0; i < e; i++) { int v1, v2; cin >> v2 >> v1; edge[v1].push_back(v2); } int ans = 0; vector <int> result(n + 1); for(int i = 1; i <= n; i++) { vector<bool> visit(n + 1); vcount = 0; dfs(i, visit); result[i] = vcount; } int maxv = 0; for (int i = 1; i <= n; i++) { //cout << result[i] << "\n"; maxv = max(maxv, result[i]); } for (int i = 1; i <= n; i++) { if (maxv == result[i]) cout << i << " "; } cout << endl; return 0; }
19.068966
42
0.460217
[ "vector" ]
71ee441048145852def3de998bc988c7b1df4a2d
10,710
cpp
C++
src/cpp/state-engine/astro_bodies/Moon.cpp
Dante83/SkyForge
283f30d05012d8570eb98013518977854f845c99
[ "MIT" ]
23
2018-05-08T15:57:32.000Z
2020-11-10T07:14:36.000Z
src/cpp/state-engine/astro_bodies/Moon.cpp
Dante83/SkyForge
283f30d05012d8570eb98013518977854f845c99
[ "MIT" ]
4
2018-06-11T08:58:55.000Z
2019-10-20T08:30:07.000Z
src/cpp/state-engine/astro_bodies/Moon.cpp
Dante83/A-Starry-Sky
283f30d05012d8570eb98013518977854f845c99
[ "MIT" ]
3
2019-06-26T22:41:50.000Z
2020-08-09T09:43:14.000Z
#include "../world_state/AstroTime.h" #include "../Constants.h" #include "AstronomicalBody.h" #include "Moon.h" #include <cmath> // //Constructor // Moon::Moon(AstroTime* astroTimeRef) : AstronomicalBody(astroTimeRef){ // //Default constructor // }; // //Methods // void Moon::updatePosition(double trueObliquityOfEclipticInRads){ double julianCentury = astroTime->julianCentury; double a_1 = check4GreaterThan360(119.75 + 131.849 * julianCentury) * DEG_2_RAD; double a_2 = check4GreaterThan360(53.09 + 479264.29 * julianCentury) * DEG_2_RAD; double a_3 = check4GreaterThan360(313.45 + 481266.484 * julianCentury) * DEG_2_RAD; double e_parameter = 1.0 - julianCentury * (0.002516 + 0.0000074 * julianCentury); double e_parameter_squared = e_parameter * e_parameter; const double D_coeficients[60] = {0.0, 2.0, 2.0, 0.0, 0.0, 0.0, 2.0, 2.0, 2.0, 2.0, 0.0, 1.0, 0.0, 2.0, 0.0, 0.0, 4.0, 0.0, 4.0, 2.0, 2.0, 1.0, 1.0, 2.0, 2.0, 4.0, 2.0, 0.0, 2.0, 2.0, 1.0, 2.0, 0.0, 0.0, 2.0, 2.0, 2.0, 4.0, 0.0, 3.0, 2.0, 4.0, 0.0, 2.0, 2.0, 2.0, 4.0, 0.0, 4.0, 1.0, 2.0, 0.0, 1.0, 3.0, 4.0, 2.0, 0.0, 1.0, 2.0, 2.0}; const double M_coeficients[60] = {0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, -1.0, 0.0, -1.0, 1.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 0.0, 1.0, -1.0, 0.0, 0.0, 0.0, 1.0, 0.0, -1.0, 0.0, -2.0, 1.0, 2.0, -2.0, 0.0, 0.0, -1.0, 0.0, 0.0, 1.0, -1.0, 2.0, 2.0, 1.0, -1.0, 0.0, 0.0, -1.0, 0.0, 1.0, 0.0, 1.0, 0.0, 0.0, -1.0, 2.0, 1.0, 0.0, 0.0}; const double M_prime_coeficients[60] = {1.0, -1.0, 0.0, 2.0, 0.0, 0.0, -2.0, -1.0, 1.0, 0.0, -1.0, 0.0, 1.0, 0.0, 1.0, 1.0, -1.0, 3.0, -2.0, -1.0, 0.0, -1.0, 0.0, 1.0, 2.0, 0.0, -3.0, -2.0, -1.0, -2.0, 1.0, 0.0, 2.0, 0.0, -1.0, 1.0, 0.0, -1.0, 2.0, -1.0, 1.0, -2.0, -1.0, -1.0, -2.0, 0.0, 1.0, 4.0, 0.0, -2.0, 0.0, 2.0, 1.0, -2.0, -3.0, 2.0, 1.0, -1.0, 3.0, -1.0}; const double F_coeficients[60] = {0.0, 0.0, 0.0, 0.0, 0.0, 2.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, -2.0, 2.0, -2.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 2.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, -2.0, 2.0, 0.0, 2.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, -2.0, 0.0, 0.0, 0.0, 0.0, -2.0, -2.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, -2.0}; const double l_sum_coeficients[60] = {6288774.0, 1274027.0, 658314.0, 213618.0, -185116.0, -114332.0, 58793.0, 57066.0, 53322.0, 45758.0, -40923.0, -34720.0, -30383.0, 15327.0, -12528.0, 10980.0, 10675.0, 10034.0, 8548.0, -7888.0, -6766.0, -5163.0, 4987.0, 4036.0, 3994.0, 3861.0, 3665.0, -2689.0, -2602.0, 2390.0, -2348.0, 2236.0, -2120.0, -2069.0, 2048.0, -1773.0, -1595.0, 1215.0, -1110.0, -892.0, -810.0, 759.0, -713.0, -700.0, 691.0, 596.0, 549.0, 537.0, 520.0, -487.0, -399.0, -381.0, 351.0, -340.0, 330.0, 327.0, -323.0, 299.0, 294.0, 0.0}; const double r_sum_coeficients[60] = {-20905355.0, -3699111.0, -2955968.0, -569925.0, 48888.0, -3149.0, 246158.0, -152138.0, -170733.0, -204586.0, -129620.0, 108743.0, 104755.0, 10321.0, 0.0, 79661.0, -34782.0, -23210.0, -21636.0, 24208.0, 30824.0, -8379.0, -16675.0, -12831.0, -10445.0, -11650.0, 14403.0, -7003.0, 0.0, 10056.0, 6322.0, -9884.0, 5751.0, 0.0, -4950.0, 4130.0, 0.0, -3958.0, 0.0, 3258.0, 2616.0, -1897.0, -2117.0, 2354.0, 0.0, 0.0, -1423.0, -1117.0, -1571.0, -1739.0, 0.0, -4421.0, 0.0, 0.0, 0.0, 0.0, 1165.0, 0.0, 0.0, 8752.0}; double sum_l = 0.0; double sum_r = 0.0; //Pre define our variables so we just overwrite their values; double D_coeficient; double M_coeficient; double M_prime_coeficient; double F_coeficient; double l_sum_coeficient; double r_sum_coeficient; double DCoeficientTimesMoonElongation; double MCoeficientTimesSunsElongation; double MPrimeCoeficientTimesMoonsMeanAnomoly; double FCoeficientTimesMoonArgumentOfLatitude; double sumOfTerms; double e_coeficient; double absOfMCoeficient; double sunsMeanAnomoly = sun->meanAnomaly; for(int i=0; i < 60; ++i){ sumOfTerms = check4GreaterThan360(D_coeficients[i] * meanElongation + M_coeficients[i] * sunsMeanAnomoly + M_prime_coeficients[i] * meanAnomaly + F_coeficients[i] * argumentOfLatitude) * DEG_2_RAD; double e_coefficient = 1.0; if(abs(M_coeficients[i]) == 1.0){ e_coefficient = e_parameter; } else if(abs(M_coeficients[i]) == 2.0){ e_coefficient = e_parameter_squared; } sum_l += e_coefficient * l_sum_coeficients[i] * sin(sumOfTerms); sum_r += e_coefficient * r_sum_coeficients[i] * cos(sumOfTerms); } //For B while we're at it :D. As a side note, there are 60 of these, too. const double D_coeficients_2[60] = {0.0, 0.0, 0.0, 2.0, 2.0, 2.0, 2.0, 0.0, 2.0, 0.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 0.0, 4.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 4.0, 4.0, 0.0, 4.0, 2.0, 2.0, 2.0, 2.0, 0.0, 2.0, 2.0, 2.0, 2.0, 4.0, 2.0, 2.0, 0.0, 2.0, 1.0, 1.0, 0.0, 2.0, 1.0, 2.0, 0.0, 4.0, 4.0, 1.0, 4.0, 1.0, 4.0, 2.0}; const double M_coeficients_2[60] = {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, -1.0, 0.0, 0.0, 1.0, -1.0, -1.0, -1.0, 1.0, 0.0, 1.0, 0.0, 1.0, 0.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, -1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 0.0, -1.0, -2.0, 0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0, -1.0, 1.0, 0.0, -1.0, 0.0, 0.0, 0.0, -1.0, -2.0}; const double M_prime_coeficients_2[60] = {0.0, 1.0, 1.0, 0.0, -1.0, -1.0, 0.0, 2.0, 1.0, 2.0, 0.0, -2.0, 1.0, 0.0, -1.0, 0.0, -1.0, -1.0, -1.0, 0.0, 0.0, -1.0, 0.0, 1.0, 1.0, 0.0, 0.0, 3.0, 0.0, -1.0, 1.0, -2.0, 0.0, 2.0, 1.0, -2.0, 3.0, 2.0, -3.0, -1.0, 0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 0.0, -2.0, -1.0, 1.0, -2.0, 2.0, -2.0, -1.0, 1.0, 1.0, -1.0, 0.0, 0.0}; const double F_coeficients_2[60] = {1.0, 1.0, -1.0, -1.0, 1.0, -1.0, 1.0, 1.0, -1.0, -1.0, -1.0, -1.0, 1.0, -1.0, 1.0, 1.0, -1.0, -1.0, -1.0, 1.0, 3.0, 1.0, 1.0, 1.0, -1.0, -1.0, -1.0, 1.0, -1.0, 1.0, -3.0, 1.0, -3.0, -1.0, -1.0, 1.0, -1.0, 1.0, -1.0, 1.0, 1.0, 1.0, 1.0, -1.0, 3.0, -1.0, -1.0, 1.0, -1.0, -1.0, 1.0, -1.0, 1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, 1.0}; const double b_sum_coeficients[60] = {5128122.0, 280602.0, 277693.0, 173237.0, 55413.0, 46271.0, 32573.0, 17198.0, 9266.0, 8822.0, 8216.0, 4324.0, 4200.0, -3359.0, 2463.0, 2211.0, 2065.0, -1870.0, 1828.0, -1794.0, -1749.0, -1565.0, -1491.0, -1475.0, -1410.0, -1344.0, -1335.0, 1107.0, 1021.0, 833.0, 777.0, 671.0, 607.0, 596.0, 491.0, -451.0, 439.0, 422.0, 421.0, -366.0, -351.0, 331.0, 315.0, 302.0, -283.0, -229.0, 223.0, 223.0, -220.0, -220.0, -185.0, 181.0, -177.0, 176.0, 166.0, -164.0, 132.0, -119.0, 115.0, 107}; double sum_b = 0.0; for(int i=0; i < 60; ++i){ sumOfTerms = check4GreaterThan360(D_coeficients_2[i] * meanElongation + M_coeficients_2[i] * sunsMeanAnomoly + M_prime_coeficients_2[i] * meanAnomaly + F_coeficients_2[i] * argumentOfLatitude) * DEG_2_RAD; double e_coefficient = 1.0; if(abs(M_coeficients_2[i]) == 1.0){ e_coefficient = e_parameter; } else if(abs(M_coeficients_2[i]) == 2.0){ e_coefficient = e_parameter_squared; } sum_b += e_coefficient * b_sum_coeficients[i] * sin(sumOfTerms); } //Additional terms sum_l += 3958.0 * sin(a_1) + 1962.0 * sin(meanLongitudeInRads - argumentOfLatitudeInRads) + 318.0 * sin(a_2); sum_b += -2235.0 * sin(meanLongitudeInRads) + 382.0 * sin(a_3) + 175.0 * sin(a_1 - argumentOfLatitudeInRads) + 175.0 * sin(a_1 + argumentOfLatitudeInRads); sum_b += 127.0 * sin(meanLongitudeInRads - meanAnomalyInRads) - 115.0 * sin(meanLongitudeInRads + meanAnomalyInRads); double eclipticalLongitude = (meanLongitude + (sum_l * 0.000001)) * DEG_2_RAD; double eclipticalLatitude = (sum_b * 0.000001) * DEG_2_RAD; distanceFromEarthInMeters = 385000560.0 + sum_r; #define MEAN_LUNAR_DISTANCE_FROM_EARTH 384400000.0 scale = MEAN_LUNAR_DISTANCE_FROM_EARTH / distanceFromEarthInMeters; //From all of the above, we can get our right ascension and declination convertEclipticalLongitudeAndLatitudeToRaAndDec(eclipticalLongitude, eclipticalLatitude, trueObliquityOfEclipticInRads); double geocentricElongationOfTheMoon = acos(cos(eclipticalLatitude) * cos(sun->longitude - eclipticalLongitude)); //Finally,update our moon brightness //From approximation 48.2 and 48.3, in Meeus, page 346 double twoTimesMeanElongationInRads = 2.0 * meanAnomalyInRads; double phiOfMoon = acos(sin(sun->declination) * sin(declination) + cos(sun->declination) * cos(declination) * cos(sun->rightAscension - rightAscension)); double lunarPhaseAngleInRads = atan2(sun->distance2Earth * sin(phiOfMoon), distanceFromEarthInMeters - sun->distance2Earth * cos(phiOfMoon)); //Changing our lunar intensity model over to the one used by A Physically-Based Night Sky Model //by Henrik Jensen et. al. #define AVERAGE_ALBEDO_OF_MOON 0.072 #define RADIUS_OF_THE_MOON_IN_M 1737100.0 #define TWO_THIRDS 0.6666666666666 double illuminationOfMoonCoefficient = TWO_THIRDS * AVERAGE_ALBEDO_OF_MOON * (RADIUS_OF_THE_MOON_IN_M * RADIUS_OF_THE_MOON_IN_M) / (distanceFromEarthInMeters * distanceFromEarthInMeters); double phiOverTwo = 0.5 * lunarPhaseAngleInRads; #define FULL_EARTHSHINE 0.19 earthShineIntensity = abs(0.5 * FULL_EARTHSHINE * (1.0 - sin(phiOverTwo) * tan(phiOverTwo) * log(1.0 / tan(0.5 * phiOverTwo)))); irradianceFromEarth = illuminationOfMoonCoefficient * (earthShineIntensity + sun->irradianceFromEarth) * (1.0 - sin(phiOverTwo) * tan(phiOverTwo) * log(1.0 / tan(0.5 * phiOverTwo))); illuminatedFractionOfMoon = (1.0 + cos(lunarPhaseAngleInRads)) * 0.5; //Update the paralactic angle updateParalacticAngle(); } // //Getters and Setters // void Moon::setMeanLongitude(double inValue){ meanLongitude = check4GreaterThan360(inValue); meanLongitudeInRads = meanLongitude * DEG_2_RAD; } void Moon::setMeanElongation(double inValue){ meanElongation = check4GreaterThan360(inValue); meanElongationInRads = meanElongation * DEG_2_RAD; } void Moon::setMeanAnomaly(double inValue){ meanAnomaly = check4GreaterThan360(inValue); meanAnomalyInRads = meanAnomaly * DEG_2_RAD; } void Moon::setArgumentOfLatitude(double inValue){ argumentOfLatitude = check4GreaterThan360(inValue); argumentOfLatitudeInRads = argumentOfLatitude * DEG_2_RAD; } void Moon::setLongitudeOfTheAscendingNodeOfOrbit(double inValue){ longitudeOfTheAscendingNodeOfOrbit = check4GreaterThan360(inValue); } void Moon::updateParalacticAngle(){ double hourAngle = astroTime->localApparentSiderealTime * DEG_2_RAD - rightAscension; double parallacticAngleDenominator = tan(location->latInRads) * cos(declination) - sin(declination) * cos(hourAngle); parallacticAngle = parallacticAngleDenominator != 0.0 ? sin(hourAngle) / parallacticAngleDenominator : PI_OVER_TWO; }
52.5
209
0.635948
[ "model" ]
71eecfe4020a2156d9d4a51755bf90693ccb5f6e
7,804
hpp
C++
RogueEngine/Source/GLHelper.hpp
silferysky/RogueArcher
3c77696260f773a0b7adb88b991e09bb35069901
[ "FSFAP" ]
1
2019-06-18T20:07:47.000Z
2019-06-18T20:07:47.000Z
RogueEngine/Source/GLHelper.hpp
silferysky/RogueArcher
3c77696260f773a0b7adb88b991e09bb35069901
[ "FSFAP" ]
null
null
null
RogueEngine/Source/GLHelper.hpp
silferysky/RogueArcher
3c77696260f773a0b7adb88b991e09bb35069901
[ "FSFAP" ]
null
null
null
/* Start Header ************************************************************************/ /*! \file GLHelper.hpp \project Exale \author Javier Foo, javier.foo, 440002318 (100%) \par javier.foo\@digipen.edu \date 1 December,2019 \brief This file contains the function definitions for GLHelper All content (C) 2019 DigiPen (SINGAPORE) Corporation, all rights reserved. Reproduction or disclosure of this file or its contents without the prior written consent of DigiPen Institute of Technology is prohibited. */ /* End Header **************************************************************************/ #pragma once #include <glm.hpp> #include <gtc/matrix_transform.hpp> #include <gtc/type_ptr.hpp> #include "WindowHelper.h" #include "Vector2D.h" #include "ShaderManager.h" #define glCheckError() glCheckError_(__FILE__, __LINE__) namespace Rogue { static const float quadVertices[] = { // positions // colors // texture coords 0.5f, 0.5f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, // top right 0.5f, -0.5f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, // bottom right -0.5f, -0.5f, 0.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, // bottom left -0.5f, 0.5f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f, 0.0f, 1.0f // top left }; static void UpdateTextureCoords(const float& xMin, const float& xMax) { float min[] = { xMin }; float max[] = { xMax }; glBufferSubData(GL_ARRAY_BUFFER, 7 * sizeof(float), sizeof(float), max); glBufferSubData(GL_ARRAY_BUFFER, 16 * sizeof(float), sizeof(float), max); glBufferSubData(GL_ARRAY_BUFFER, 25 * sizeof(float), sizeof(float), min); glBufferSubData(GL_ARRAY_BUFFER, 34 * sizeof(float), sizeof(float), min); } static void UpdateTextureCoordsY(const float& yMin, const float& yMax) { float min[] = { yMin }; float max[] = { yMax }; glBufferSubData(GL_ARRAY_BUFFER, 8 * sizeof(float), sizeof(float), max); glBufferSubData(GL_ARRAY_BUFFER, 17 * sizeof(float), sizeof(float), min); glBufferSubData(GL_ARRAY_BUFFER, 26 * sizeof(float), sizeof(float), min); glBufferSubData(GL_ARRAY_BUFFER, 35 * sizeof(float), sizeof(float), max); } static const float frameVertices[] = { // positions // texCoords -1.0f, 1.0f, 0.0f, 1.0f, -1.0f, -1.0f, 0.0f, 0.0f, 1.0f, -1.0f, 1.0f, 0.0f, -1.0f, 1.0f, 0.0f, 1.0f, 1.0f, -1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 1.0f, 1.0f }; static const float lineVertices[] = { // positions // colors 0.5f, 0.5f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, // top right 0.5f, -0.5f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, // bottom right }; static constexpr unsigned int quadIndices[6] = { 0, 1, 3, // first triangle 1, 2, 3 // second triangle }; static void GenerateQuadPrimitive(GLuint& VBO, GLuint& VAO, GLuint& EBO) { // bind the Vertex Array Object first, then bind and set vertex buffer(s), and then configure vertex attributes(s). glGenVertexArrays(1, &VAO); glBindVertexArray(VAO); glGenBuffers(1, &VBO); glBindBuffer(GL_ARRAY_BUFFER, VBO); glBufferData(GL_ARRAY_BUFFER, sizeof(quadVertices), quadVertices, GL_DYNAMIC_DRAW); glGenBuffers(1, &EBO); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(quadIndices), quadIndices, GL_STATIC_DRAW); // position attribute glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 9 * sizeof(float), (const void*)0); glEnableVertexAttribArray(0); // color attribute glVertexAttribPointer(1, 4, GL_FLOAT, GL_FALSE, 9 * sizeof(float), (const void*)(3 * sizeof(float))); glEnableVertexAttribArray(1); // texture coord attribute glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 9 * sizeof(float), (const void*)(7 * sizeof(float))); glEnableVertexAttribArray(2); // normal //glVertexAttribPointer(3, 3, GL_FLOAT, GL_FALSE, 12 * sizeof(float), (const void*)(9 * sizeof(float))); //glEnableVertexAttribArray(3); glBindBuffer(GL_ARRAY_BUFFER, 0); //Reset glBindVertexArray(0); //Reset } static void GenerateLinePrimitive(GLuint& VBO, GLuint& VAO) { // bind the Vertex Array Object first, then bind and set vertex buffer(s), and then configure vertex attributes(s). glGenVertexArrays(1, &VAO); glBindVertexArray(VAO); glGenBuffers(1, &VBO); glBindBuffer(GL_ARRAY_BUFFER, VBO); glBufferData(GL_ARRAY_BUFFER, sizeof(lineVertices), lineVertices, GL_DYNAMIC_DRAW); // position attribute glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 7 * sizeof(float), (const void*)0); glEnableVertexAttribArray(0); // color attribute glVertexAttribPointer(1, 4, GL_FLOAT, GL_FALSE, 7 * sizeof(float), (const void*)(3 * sizeof(float))); glEnableVertexAttribArray(1); glBindBuffer(GL_ARRAY_BUFFER, 0); //Reset glBindVertexArray(0); //Reset } static void GenerateFrameQuad(GLuint& frameVAO, GLuint& frameVBO) { glGenVertexArrays(1, &frameVAO); glGenBuffers(1, &frameVBO); glBindVertexArray(frameVAO); glBindBuffer(GL_ARRAY_BUFFER, frameVBO); glBufferData(GL_ARRAY_BUFFER, sizeof(frameVertices), &frameVertices, GL_STATIC_DRAW); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 4 * sizeof(float), (void*)0); glEnableVertexAttribArray(1); glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 4 * sizeof(float), (void*)(2 * sizeof(float))); glBindBuffer(GL_ARRAY_BUFFER, 0); //Reset glBindVertexArray(0); //Reset } static void GenerateFrameBuffer(GLuint& FBO, GLuint& texColourBuffer, GLuint& RBO, const int& width, const int& height) { glGenFramebuffers(1, &FBO); glBindFramebuffer(GL_FRAMEBUFFER, FBO); // create color attachment texture glGenTextures(1, &texColourBuffer); glBindTexture(GL_TEXTURE_2D, texColourBuffer); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, NULL); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, texColourBuffer, 0); // create a renderbuffer object for depth and stencil attachment glGenRenderbuffers(1, &RBO); glBindRenderbuffer(GL_RENDERBUFFER, RBO); glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH24_STENCIL8, width, height); glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_RENDERBUFFER, RBO); // check if framebuffer is complete if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) std::cout << "Error: Framebuffer is not complete." << std::endl; glBindFramebuffer(GL_FRAMEBUFFER, 0); } static void drawLine(const Vector2D& p1, const Vector2D& p2) { float start[] = { p1.x, p1.y, }; float end[] = { p2.x, p2.y }; glBufferSubData(GL_ARRAY_BUFFER, 0, 2 * sizeof(float), start); glBufferSubData(GL_ARRAY_BUFFER, 7 * sizeof(float), 2 * sizeof(float), end); glDrawArrays(GL_LINES, 0, 2); } static GLenum glCheckError_(const char* file, int line) { GLenum errorCode; while ((errorCode = glGetError()) != GL_NO_ERROR) { std::string error; switch (errorCode) { case GL_INVALID_ENUM: error = "INVALID_ENUM"; break; case GL_INVALID_VALUE: error = "INVALID_VALUE"; break; case GL_INVALID_OPERATION: error = "INVALID_OPERATION"; break; case GL_STACK_OVERFLOW: error = "STACK_OVERFLOW"; break; case GL_STACK_UNDERFLOW: error = "STACK_UNDERFLOW"; break; case GL_OUT_OF_MEMORY: error = "OUT_OF_MEMORY"; break; case GL_INVALID_FRAMEBUFFER_OPERATION: error = "INVALID_FRAMEBUFFER_OPERATION"; break; } std::cout << error << " | " << file << " (" << line << ")" << std::endl; } return errorCode; } }
32.92827
120
0.677217
[ "object" ]
71f82fc97755588fa4e47ec33009a189b61470cc
1,712
cpp
C++
leetcode/problems/medium/1570-dot-product-of-two-sparse-vectors.cpp
wingkwong/competitive-programming
e8bf7aa32e87b3a020b63acac20e740728764649
[ "MIT" ]
18
2020-08-27T05:27:50.000Z
2022-03-08T02:56:48.000Z
leetcode/problems/medium/1570-dot-product-of-two-sparse-vectors.cpp
wingkwong/competitive-programming
e8bf7aa32e87b3a020b63acac20e740728764649
[ "MIT" ]
null
null
null
leetcode/problems/medium/1570-dot-product-of-two-sparse-vectors.cpp
wingkwong/competitive-programming
e8bf7aa32e87b3a020b63acac20e740728764649
[ "MIT" ]
1
2020-10-13T05:23:58.000Z
2020-10-13T05:23:58.000Z
/* Dot Product of Two Sparse Vectors https://leetcode.com/problems/dot-product-of-two-sparse-vectors/ Given two sparse vectors, compute their dot product. Implement class SparseVector: SparseVector(nums) Initializes the object with the vector nums dotProduct(vec) Compute the dot product between the instance of SparseVector and vec A sparse vector is a vector that has mostly zero values, you should store the sparse vector efficiently and compute the dot product between two SparseVector. Follow up: What if only one of the vectors is sparse? Example 1: Input: nums1 = [1,0,0,2,3], nums2 = [0,3,0,4,0] Output: 8 Explanation: v1 = SparseVector(nums1) , v2 = SparseVector(nums2) v1.dotProduct(v2) = 1*0 + 0*3 + 0*0 + 2*4 + 3*0 = 8 Example 2: Input: nums1 = [0,1,0,0,0], nums2 = [0,0,0,0,2] Output: 0 Explanation: v1 = SparseVector(nums1) , v2 = SparseVector(nums2) v1.dotProduct(v2) = 0*0 + 1*0 + 0*0 + 0*0 + 0*2 = 0 Example 3: Input: nums1 = [0,1,0,0,2,0,0], nums2 = [1,0,0,0,3,0,4] Output: 6 Constraints: n == nums1.length == nums2.length 1 <= n <= 10^5 0 <= nums1[i], nums2[i] <= 100 */ class SparseVector { public: map<int, int> m; SparseVector(vector<int> &nums) { for(int i = 0; i < nums.size(); i++) { if(nums[i]) { m[i] = nums[i]; } } } // Return the dotProduct of two sparse vectors int dotProduct(SparseVector& vec) { int res = 0; for(auto x : m) { res += x.second * vec.m[x.first]; } return res; } }; // Your SparseVector object will be instantiated and called as such: // SparseVector v1(nums1); // SparseVector v2(nums2); // int ans = v1.dotProduct(v2);
25.939394
157
0.633178
[ "object", "vector" ]
9f99ff1640f17ca5c2af9bbea9992bd9e5a9c9b7
1,868
hpp
C++
Phoenix3D/Tools/Nirvana/PX2E_ProjTreeItem.hpp
PheonixFoundation/Phoenix3D
bfb2e3757bf61ac461aeeda9216bf8c8fdf76d99
[ "BSL-1.0" ]
36
2016-04-24T01:40:38.000Z
2022-01-18T07:32:26.000Z
Phoenix3D/Tools/Nirvana/PX2E_ProjTreeItem.hpp
PheonixFoundation/Phoenix3D
bfb2e3757bf61ac461aeeda9216bf8c8fdf76d99
[ "BSL-1.0" ]
null
null
null
Phoenix3D/Tools/Nirvana/PX2E_ProjTreeItem.hpp
PheonixFoundation/Phoenix3D
bfb2e3757bf61ac461aeeda9216bf8c8fdf76d99
[ "BSL-1.0" ]
16
2016-06-13T08:43:51.000Z
2020-09-15T13:25:58.000Z
// PX2E_ProjTreeItem.hpp #ifndef PX2E_PROJTREEITEM_HPP #define PX2E_PROJTREEITEM_HPP #include "PX2EditorPre.hpp" #include "PX2Object.hpp" #include "PX2E_ProjTreeDef.hpp" namespace PX2Editor { class ProjTree; class ProjTreeItem { public: enum ItemType { IT_OBJECT, IT_CATALOG, IT_MAX_TYPE }; ProjTreeItem(ProjTree *tree, ProjTreeItem *parent, ItemType type, int iconID, PX2::Object *obj, ProjTreeLevel showLevel, bool isShowHelpNode, const std::string &name = "", bool doInsert = false, wxTreeItemId insertUpID=wxTreeItemId()); virtual ~ProjTreeItem(); void SetTreeLevel(ProjTreeLevel level, bool isShowHelpNode); ProjTreeLevel GetTreeLevel() const { return mTreeLevel; } void SetName(const std::string &name); const std::string &GetName() const { return mName; } void SetObject(PX2::Object *obj) { mObject = obj; } PX2::Object *GetObject() const { return mObject; } int GetIconID() const { return mIconID; } wxTreeItemId GetItemID() const { return mItemID; } ProjTreeItem *GetParent() const { return mParentItem; } ProjTreeItem *AddChild(PX2::Object *obj, int iconID, ProjTreeLevel showLevel, bool isShowHelpNode); ProjTreeItem *InsertChild(wxTreeItemId upID, PX2::Object *obj, int iconID, ProjTreeLevel showLevel, bool isShowHelpNode); void RemoveChild(PX2::Object *obj); void ClearChildren(); ProjTreeItem *GetItem(PX2::Object *obj); ProjTreeItem *GetItem(wxTreeItemId id); public_internal: ProjTreeItem(ProjTree *tree, wxTreeItemId id, ItemType type, int iconID, const std::string &name); std::vector<ProjTreeItem*> mChildItems; protected: ProjTree *mProjTree; ProjTreeItem *mParentItem; ItemType mItemType; int mIconID; PX2::ObjectPtr mObject; std::string mName; wxTreeItemId mItemID; ProjTreeLevel mTreeLevel; bool mIsShowHelpNode; }; } #endif
24.578947
101
0.736081
[ "object", "vector" ]
9f9b446a3bffaa1e4cde4487a1ce8796196b0621
280,124
cpp
C++
emulator/src/devices/video/stvvdp2.cpp
rjw57/tiw-computer
5ef1c79893165b8622d1114d81cd0cded58910f0
[ "MIT" ]
1
2022-01-15T21:38:38.000Z
2022-01-15T21:38:38.000Z
emulator/src/devices/video/stvvdp2.cpp
rjw57/tiw-computer
5ef1c79893165b8622d1114d81cd0cded58910f0
[ "MIT" ]
null
null
null
emulator/src/devices/video/stvvdp2.cpp
rjw57/tiw-computer
5ef1c79893165b8622d1114d81cd0cded58910f0
[ "MIT" ]
null
null
null
// license:LGPL-2.1+ // copyright-holders:David Haywood, Angelo Salese, Olivier Galibert, Mariusz Wojcieszek, R. Belmont /* Sega Saturn VDP2 */ /* the dirty marking stuff and tile decoding will probably be removed in the end anyway as we'll need custom rendering code since mame's drawgfx / tilesytem don't offer everything st-v needs this system seems far too complex to use Mame's tilemap system 4 'scroll' planes (scroll screens) the scroll planes have slightly different capabilities NBG0 NBG1 NBG2 NBG3 2 'rotate' planes RBG0 RBG1 -- other crap EXBG (external) ----------------------------------------------------------------------------------------------------------- Video emulation TODO: -all games: \-priorities (check myfairld,thunt) \-complete windows effects \-mosaic effect \-ODD bit/H/V Counter not yet emulated properly \-Reduction enable bits (zooming limiters) \-Check if there are any remaining video registers that are yet to be macroized & added to the rumble. -batmanfr: \-If you reset the game after the character selection screen,when you get again to it there's garbage floating behind Batman. -elandore: \-(BTANB) priorities at the VS. screen apparently is wrong,but it's like this on the Saturn version too. -hanagumi: \-ending screens have corrupt graphics. (*untested*) -kiwames: \-(fixed) incorrect color emulation for the alpha blended flames on the title screen,it's caused by a schizoid linescroll emulation quirk. \-the VDP1 sprites refresh is too slow,causing the "Draw by request" mode to flicker. Moved back to default ATM. -pblbeach: \-Sprites are offset, because it doesn't clear vdp1 local coordinates set by bios, I guess that they are cleared when some vdp1 register is written (kludged for now) -prikura: \-Attract mode presentation has corrupted graphics in various places,probably caused by incomplete framebuffer data delete. -seabass: \-(fixed) Player sprite is corrupt/missing during movements,caused by incomplete framebuffer switching. -shienryu: \-level 2 background colors on statues, caused by special color calculation usage (per dot); (Saturn games) - scud the disposable assassin: \- when zooming on melee attack background gets pink, color calculation issue? - virtual hydlide: \- transparent pens usage on most vdp1 items should be black instead. \- likewise "press start button" is the other way around, i.e. black pen where it should be transparent instead. Notes of Interest & Unclear features: -the test mode / bios is drawn with layer NBG3; -hanagumi puts a 'RED' dragon logo in tileram (base 0x64000, 4bpp, 8x8 tiles) but its not displayed because its priority value is 0.Left-over? -scrolling is screen display wise,meaning that a scrolling value is masked with the screen resolution size values; -H-Blank bit is INDIPENDENT of the V-Blank bit...trying to fix enable/disable it during V-Blank period causes wrong gameplay speed in Golden Axe:The Duel. -Bitmaps uses transparency pens,examples are: \-elandore's energy bars; \-mausuke's foreground(the one used on the playfield) \-shanhigw's tile-based sprites; The transparency pen table is like this: |------------------|---------------------| | Character count | Transparency code | |------------------|---------------------| | 16 colors |=0x0 (4 bits) | | 256 colors |=0x00 (8 bits) | | 2048 colors |=0x000 (11 bits) | | 32,768 colors |MSB=0 (bit 15) | | 16,770,000 colors|MSB=0 (bit 31) | |------------------|---------------------| In other words,the first three types uses the offset and not the color allocated. -double density interlace setting (LSMD == 3) apparently does a lot of fancy stuff in the graphics sizes. -Debug key list(only if you enable the debug mode on top of this file): \-T: NBG3 layer toggle \-Y: NBG2 layer toggle \-U: NBG1 layer toggle \-I: NBG0 layer toggle \-O: SPRITE toggle \-K: RBG0 layer toggle \-W Decodes the graphics for F4 menu. \-M Stores VDP1 ram contents from a file. \-N Stores VDP1 ram contents into a file. */ #include "emu.h" #include "includes/saturn.h" // FIXME: this is a dependency from devices on MAME #define DEBUG_MODE 0 #define TEST_FUNCTIONS 0 #define POPMESSAGE_DEBUG 0 enum { STV_TRANSPARENCY_NONE, STV_TRANSPARENCY_PEN, STV_TRANSPARENCY_ADD_BLEND, STV_TRANSPARENCY_ALPHA }; #if DEBUG_MODE #define LOG_VDP2 1 #define LOG_ROZ 0 #else #define LOG_VDP2 0 #define LOG_ROZ 0 #endif /* -------------------------------------------------|-----------------------------|------------------------------ | Function | Normal Scroll Screen | Rotation Scroll Screen | | |-----------------------------|-----------------------------|------------------------------ | | NBG0 | NBG1 | NBG2 | NBG3 | RBG0 | RBG1 | -------------------------------------------------|-----------------------------|------------------------------ | Character Colour | 16 colours | 16 colours | 16 colours | 16 colours | 16 colours | 16 colours | | Count | 256 " " | 256 " " | 256 " " | 256 " " | 256 " " | 256 " " | | | 2048 " " | 2048 " " | | | 2048 " " | 2048 " " | | | 32768 " " | 32768 " " | | | 32768 " " | 32768 " " | | | 16770000 " " | | | | 16770000 " " | 16770000 " " | -------------------------------------------------|-----------------------------|------------------------------ | Character Size | 1x1 Cells , 2x2 Cells | -------------------------------------------------|-----------------------------|------------------------------ | Pattern Name | 1 word , 2 words | | Data Size | | -------------------------------------------------|-----------------------------|------------------------------ | Plane Size | 1 H x 1 V 1 Pages ; 2 H x 1 V 1 Pages ; 2 H x 2 V Pages | -------------------------------------------------|-----------------------------|------------------------------ | Plane Count | 4 | 16 | -------------------------------------------------|-----------------------------|------------------------------ | Bitmap Possible | Yes | No | Yes | No | -------------------------------------------------|-----------------------------|------------------------------ | Bitmap Size | 512 x 256 | N/A | 512x256 | N/A | | | 512 x 512 | | 512x512 | | | | 1024 x 256 | | | | | | 1024 x 512 | | | | -------------------------------------------------|-----------------------------|------------------------------ | Scale | 0.25 x - 256 x | None | Any ? | -------------------------------------------------|-----------------------------|------------------------------ | Rotation | No | Yes | -------------------------------------------------|-----------------------------|-----------------------------| | Linescroll | Yes | No | -------------------------------------------------|-----------------------------|------------------------------ | Column Scroll | Yes | No | -------------------------------------------------|-----------------------------|------------------------------ | Mosaic | Yes | Horizontal Only | -------------------------------------------------|-----------------------------|------------------------------ */ /* 180000 - r/w - TVMD - TV Screen Mode bit-> /----15----|----14----|----13----|----12----|----11----|----10----|----09----|----08----\ | DISP | -- | -- | -- | -- | -- | -- | BDCLMD | |----07----|----06----|----05----|----04----|----03----|----02----|----01----|----00----| | LSMD1 | LSMD0 | VRESO1 | VRESO0 | -- | HRESO2 | HRESO1 | HRESO0 | \----------|----------|----------|----------|----------|----------|----------|---------*/ #define STV_VDP2_TVMD (m_vdp2_regs[0x000/2]) #define STV_VDP2_DISP ((STV_VDP2_TVMD & 0x8000) >> 15) #define STV_VDP2_BDCLMD ((STV_VDP2_TVMD & 0x0100) >> 8) #define STV_VDP2_LSMD ((STV_VDP2_TVMD & 0x00c0) >> 6) #define STV_VDP2_VRES ((STV_VDP2_TVMD & 0x0030) >> 4) #define STV_VDP2_HRES ((STV_VDP2_TVMD & 0x0007) >> 0) /* 180002 - r/w - EXTEN - External Signal Enable Register bit-> /----15----|----14----|----13----|----12----|----11----|----10----|----09----|----08----\ | -- | -- | -- | -- | -- | -- | EXLTEN | EXSYEN | |----07----|----06----|----05----|----04----|----03----|----02----|----01----|----00----| | -- | -- | -- | -- | -- | -- | DASEL | EXBGEN | \----------|----------|----------|----------|----------|----------|----------|---------*/ #define STV_VDP2_EXTEN (m_vdp2_regs[0x002/2]) #define STV_VDP2_EXLTEN ((STV_VDP2_EXTEN & 0x0200) >> 9) /* 180004 - r/o - TVSTAT - Screen Status bit-> /----15----|----14----|----13----|----12----|----11----|----10----|----09----|----08----\ | -- | -- | -- | -- | -- | -- | EXLTFG | EXSYFG | |----07----|----06----|----05----|----04----|----03----|----02----|----01----|----00----| | -- | -- | -- | -- | VBLANK | HBLANK | ODD | PAL | \----------|----------|----------|----------|----------|----------|----------|---------*/ /* 180006 - r/w - VRSIZE - VRAM Size bit-> /----15----|----14----|----13----|----12----|----11----|----10----|----09----|----08----\ | VRAMSZ | -- | -- | -- | -- | -- | -- | -- | |----07----|----06----|----05----|----04----|----03----|----02----|----01----|----00----| | -- | -- | -- | -- | VER3 | VER2 | VER1 | VER0 | \----------|----------|----------|----------|----------|----------|----------|---------*/ #define STV_VDP2_VRSIZE (m_vdp2_regs[0x006/2]) #define STV_VDP2_VRAMSZ ((STV_VDP2_VRSIZE & 0x8000) >> 15) /* 180008 - r/o - HCNT - H-Counter bit-> /----15----|----14----|----13----|----12----|----11----|----10----|----09----|----08----\ | -- | -- | -- | -- | -- | -- | HCT9 | HCT8 | |----07----|----06----|----05----|----04----|----03----|----02----|----01----|----00----| | HCT7 | HCT6 | HCT5 | HCT4 | HCT3 | HCT2 | HCT1 | HCT0 | \----------|----------|----------|----------|----------|----------|----------|---------*/ #define STV_VDP2_HCNT (m_vdp2_regs[0x008/2]) /* 18000A - r/o - VCNT - V-Counter bit-> /----15----|----14----|----13----|----12----|----11----|----10----|----09----|----08----\ | -- | -- | -- | -- | -- | -- | VCT9 | VCT8 | |----07----|----06----|----05----|----04----|----03----|----02----|----01----|----00----| | VCT7 | VCT6 | VCT5 | VCT4 | VCT3 | VCT2 | VCT1 | VCT0 | \----------|----------|----------|----------|----------|----------|----------|---------*/ #define STV_VDP2_VCNT (m_vdp2_regs[0x00a/2]) /* 18000C - RESERVED bit-> /----15----|----14----|----13----|----12----|----11----|----10----|----09----|----08----\ | -- | -- | -- | -- | -- | -- | -- | -- | |----07----|----06----|----05----|----04----|----03----|----02----|----01----|----00----| | -- | -- | -- | -- | -- | -- | -- | -- | \----------|----------|----------|----------|----------|----------|----------|---------*/ /* 18000E - r/w - RAMCTL - RAM Control bit-> /----15----|----14----|----13----|----12----|----11----|----10----|----09----|----08----\ | CRKTE | -- | CRMD1 | CRMD0 | -- | -- | VRBMD | VRAMD | |----07----|----06----|----05----|----04----|----03----|----02----|----01----|----00----| | RDBSB11 | RDBSB10 | RDBSB01 | RDBSB00 | RDBSA11 | RDBSA10 | RDBSA01 | RDBSA00 | \----------|----------|----------|----------|----------|----------|----------|---------*/ #define STV_VDP2_RAMCTL (m_vdp2_regs[0x00e/2]) #define STV_VDP2_CRKTE ((STV_VDP2_RAMCTL & 0x8000) >> 15) #define STV_VDP2_CRMD ((STV_VDP2_RAMCTL & 0x3000) >> 12) #define STV_VDP2_RDBSB1 ((STV_VDP2_RAMCTL & 0x00c0) >> 6) #define STV_VDP2_RDBSB0 ((STV_VDP2_RAMCTL & 0x0030) >> 4) #define STV_VDP2_RDBSA1 ((STV_VDP2_RAMCTL & 0x000c) >> 2) #define STV_VDP2_RDBSA0 ((STV_VDP2_RAMCTL & 0x0003) >> 0) /* 180010 - r/w - -CYCA0L - VRAM CYCLE PATTERN (BANK A0) bit-> /----15----|----14----|----13----|----12----|----11----|----10----|----09----|----08----\ | VCP0A03 | VCP0A02 | VCP0A01 | VCP0A00 | VCP1A03 | VCP1A02 | VCP1A01 | VCP1A00 | |----07----|----06----|----05----|----04----|----03----|----02----|----01----|----00----| | VCP2A03 | VCP2A02 | VCP2A01 | VCP2A00 | VCP3A03 | VCP3A02 | VCP3A01 | VCP3A00 | \----------|----------|----------|----------|----------|----------|----------|---------*/ #define STV_VDP2_CYCA0L (m_vdp2_regs[0x010/2]) /* 180012 - r/w - -CYCA0U - VRAM CYCLE PATTERN (BANK A0) bit-> /----15----|----14----|----13----|----12----|----11----|----10----|----09----|----08----\ | VCP4A03 | VCP4A02 | VCP4A01 | VCP4A00 | VCP5A03 | VCP5A02 | VCP5A01 | VCP5A00 | |----07----|----06----|----05----|----04----|----03----|----02----|----01----|----00----| | VCP6A03 | VCP6A02 | VCP6A01 | VCP6A00 | VCP7A03 | VCP7A02 | VCP7A01 | VCP7A00 | \----------|----------|----------|----------|----------|----------|----------|---------*/ #define STV_VDP2_CYCA0U (m_vdp2_regs[0x012/2]) /* 180014 - r/w - -CYCA1L - VRAM CYCLE PATTERN (BANK A1) bit-> /----15----|----14----|----13----|----12----|----11----|----10----|----09----|----08----\ | VCP0A13 | VCP0A12 | VCP0A11 | VCP0A10 | VCP1A13 | VCP1A12 | VCP1A11 | VCP1A10 | |----07----|----06----|----05----|----04----|----03----|----02----|----01----|----00----| | VCP2A13 | VCP2A12 | VCP2A11 | VCP2A10 | VCP3A13 | VCP3A12 | VCP3A11 | VCP3A10 | \----------|----------|----------|----------|----------|----------|----------|---------*/ #define STV_VDP2_CYCA1L (m_vdp2_regs[0x014/2]) /* 180016 - r/w - -CYCA1U - VRAM CYCLE PATTERN (BANK A1) bit-> /----15----|----14----|----13----|----12----|----11----|----10----|----09----|----08----\ | VCP4A13 | VCP4A12 | VCP4A11 | VCP4A10 | VCP5A13 | VCP5A12 | VCP5A11 | VCP5A10 | |----07----|----06----|----05----|----04----|----03----|----02----|----01----|----00----| | VCP6A13 | VCP6A12 | VCP6A11 | VCP6A10 | VCP7A13 | VCP7A12 | VCP7A11 | VCP7A10 | \----------|----------|----------|----------|----------|----------|----------|---------*/ #define STV_VDP2_CYCA1U (m_vdp2_regs[0x016/2]) /* 180018 - r/w - -CYCB0L - VRAM CYCLE PATTERN (BANK B0) bit-> /----15----|----14----|----13----|----12----|----11----|----10----|----09----|----08----\ | VCP0B03 | VCP0B02 | VCP0B01 | VCP0B00 | VCP1B03 | VCP1B02 | VCP1B01 | VCP1B00 | |----07----|----06----|----05----|----04----|----03----|----02----|----01----|----00----| | VCP2B03 | VCP2B02 | VCP2B01 | VCP2B00 | VCP3B03 | VCP3B02 | VCP3B01 | VCP3B00 | \----------|----------|----------|----------|----------|----------|----------|---------*/ #define STV_VDP2_CYCA2L (m_vdp2_regs[0x018/2]) /* 18001A - r/w - -CYCB0U - VRAM CYCLE PATTERN (BANK B0) bit-> /----15----|----14----|----13----|----12----|----11----|----10----|----09----|----08----\ | VCP4B03 | VCP4B02 | VCP4B01 | VCP4B00 | VCP5B03 | VCP5B02 | VCP5B01 | VCP5B00 | |----07----|----06----|----05----|----04----|----03----|----02----|----01----|----00----| | VCP6B03 | VCP6B02 | VCP6B01 | VCP6B00 | VCP7B03 | VCP7B02 | VCP7B01 | VCP7B00 | \----------|----------|----------|----------|----------|----------|----------|---------*/ #define STV_VDP2_CYCA2U (m_vdp2_regs[0x01a/2]) /* 18001C - r/w - -CYCB1L - VRAM CYCLE PATTERN (BANK B1) bit-> /----15----|----14----|----13----|----12----|----11----|----10----|----09----|----08----\ | VCP0B13 | VCP0B12 | VCP0B11 | VCP0B10 | VCP1B13 | VCP1B12 | VCP1B11 | VCP1B10 | |----07----|----06----|----05----|----04----|----03----|----02----|----01----|----00----| | VCP2B13 | VCP2B12 | VCP2B11 | VCP2B10 | VCP3B13 | VCP3B12 | VCP3B11 | VCP3B10 | \----------|----------|----------|----------|----------|----------|----------|---------*/ #define STV_VDP2_CYCA3L (m_vdp2_regs[0x01c/2]) /* 18001E - r/w - -CYCB1U - VRAM CYCLE PATTERN (BANK B1) bit-> /----15----|----14----|----13----|----12----|----11----|----10----|----09----|----08----\ | VCP4B13 | VCP4B12 | VCP4B11 | VCP4B10 | VCP5B13 | VCP5B12 | VCP5B11 | VCP5B10 | |----07----|----06----|----05----|----04----|----03----|----02----|----01----|----00----| | VCP6B13 | VCP6B12 | VCP6B11 | VCP6B10 | VCP7B13 | VCP7B12 | VCP7B11 | VCP7B10 | \----------|----------|----------|----------|----------|----------|----------|---------*/ #define STV_VDP2_CYCA3U (m_vdp2_regs[0x01e/2]) /* 180020 - r/w - BGON - SCREEN DISPLAY ENABLE this register allows each tilemap to be enabled or disabled and also which layers are solid bit-> /----15----|----14----|----13----|----12----|----11----|----10----|----09----|----08----\ | -- | -- | -- | R0TPON | N3TPON | N2TPON | N1TPON | N0TPON | |----07----|----06----|----05----|----04----|----03----|----02----|----01----|----00----| | -- | -- | R1ON | R0ON | N3ON | N2ON | N1ON | N0ON | \----------|----------|----------|----------|----------|----------|----------|---------*/ #define STV_VDP2_BGON (m_vdp2_regs[0x020/2]) // NxOn - Layer Enable Register #define STV_VDP2_xxON ((STV_VDP2_BGON & 0x001f) >> 0) /* to see if anything is enabled */ #define STV_VDP2_N0ON ((STV_VDP2_BGON & 0x0001) >> 0) /* N0On = NBG0 Enable */ #define STV_VDP2_N1ON ((STV_VDP2_BGON & 0x0002) >> 1) /* N1On = NBG1 Enable */ #define STV_VDP2_N2ON ((STV_VDP2_BGON & 0x0004) >> 2) /* N2On = NBG2 Enable */ #define STV_VDP2_N3ON ((STV_VDP2_BGON & 0x0008) >> 3) /* N3On = NBG3 Enable */ #define STV_VDP2_R0ON ((STV_VDP2_BGON & 0x0010) >> 4) /* R0On = RBG0 Enable */ #define STV_VDP2_R1ON ((STV_VDP2_BGON & 0x0020) >> 5) /* R1On = RBG1 Enable */ // NxTPON - Transparency Pen Enable Registers #define STV_VDP2_N0TPON ((STV_VDP2_BGON & 0x0100) >> 8) /* N0TPON = NBG0 Draw Transparent Pen (as solid) /or/ RBG1 Draw Transparent Pen */ #define STV_VDP2_N1TPON ((STV_VDP2_BGON & 0x0200) >> 9) /* N1TPON = NBG1 Draw Transparent Pen (as solid) /or/ EXBG Draw Transparent Pen */ #define STV_VDP2_N2TPON ((STV_VDP2_BGON & 0x0400) >> 10)/* N2TPON = NBG2 Draw Transparent Pen (as solid) */ #define STV_VDP2_N3TPON ((STV_VDP2_BGON & 0x0800) >> 11)/* N3TPON = NBG3 Draw Transparent Pen (as solid) */ #define STV_VDP2_R0TPON ((STV_VDP2_BGON & 0x1000) >> 12)/* R0TPON = RBG0 Draw Transparent Pen (as solid) */ /* 180022 - MZCTL - Mosaic Control bit-> /----15----|----14----|----13----|----12----|----11----|----10----|----09----|----08----\ | -- | -- | -- | -- | -- | -- | -- | -- | |----07----|----06----|----05----|----04----|----03----|----02----|----01----|----00----| | -- | -- | -- | -- | -- | -- | -- | -- | \----------|----------|----------|----------|----------|----------|----------|---------*/ #define STV_VDP2_MZCTL (m_vdp2_regs[0x022/2]) #define STV_VDP2_MZSZV ((STV_VDP2_MZCTL & 0xf000) >> 12) #define STV_VDP2_MZSZH ((STV_VDP2_MZCTL & 0x0f00) >> 8) #define STV_VDP2_R0MZE ((STV_VDP2_MZCTL & 0x0010) >> 4) #define STV_VDP2_N3MZE ((STV_VDP2_MZCTL & 0x0008) >> 3) #define STV_VDP2_N2MZE ((STV_VDP2_MZCTL & 0x0004) >> 2) #define STV_VDP2_N1MZE ((STV_VDP2_MZCTL & 0x0002) >> 1) #define STV_VDP2_N0MZE ((STV_VDP2_MZCTL & 0x0001) >> 0) /*180024 - Special Function Code Select */ #define STV_VDP2_SFSEL (m_vdp2_regs[0x024/2]) /*180026 - Special Function Code */ #define STV_VDP2_SFCODE (m_vdp2_regs[0x026/2]) /* 180028 - CHCTLA - Character Control (NBG0, NBG1) bit-> /----15----|----14----|----13----|----12----|----11----|----10----|----09----|----08----\ | -- | -- | N1CHCN1 | N1CHCN0 | N1BMSZ1 | N1BMSZ0 | N1BMEN | N1CHSZ | |----07----|----06----|----05----|----04----|----03----|----02----|----01----|----00----| | -- | N0CHCN2 | N0CHCN1 | N0CHCN0 | N0BMSZ1 | N0BMSZ0 | N0BMEN | N0CHSZ | \----------|----------|----------|----------|----------|----------|----------|---------*/ #define STV_VDP2_CHCTLA (m_vdp2_regs[0x028/2]) /* -------------------------- NBG0 Character Control Registers -------------------------- */ /* N0CHCNx NBG0 (or RGB1) Colour Depth 000 - 16 Colours 001 - 256 Colours 010 - 2048 Colours 011 - 32768 Colours (RGB5) 100 - 16770000 Colours (RGB8) 101 - invalid 110 - invalid 111 - invalid */ #define STV_VDP2_N0CHCN ((STV_VDP2_CHCTLA & 0x0070) >> 4) /* N0BMSZx - NBG0 Bitmap Size *guessed* 00 - 512 x 256 01 - 512 x 512 10 - 1024 x 256 11 - 1024 x 512 */ #define STV_VDP2_N0BMSZ ((STV_VDP2_CHCTLA & 0x000c) >> 2) /* N0BMEN - NBG0 Bitmap Enable 0 - use cell mode 1 - use bitmap mode */ #define STV_VDP2_N0BMEN ((STV_VDP2_CHCTLA & 0x0002) >> 1) /* N0CHSZ - NBG0 Character (Tile) Size 0 - 1 cell x 1 cell (8x8) 1 - 2 cells x 2 cells (16x16) */ #define STV_VDP2_N0CHSZ ((STV_VDP2_CHCTLA & 0x0001) >> 0) /* -------------------------- NBG1 Character Control Registers -------------------------- */ /* N1CHCNx - NBG1 (or EXB1) Colour Depth 00 - 16 Colours 01 - 256 Colours 10 - 2048 Colours 11 - 32768 Colours (RGB5) */ #define STV_VDP2_N1CHCN ((STV_VDP2_CHCTLA & 0x3000) >> 12) /* N1BMSZx - NBG1 Bitmap Size *guessed* 00 - 512 x 256 01 - 512 x 512 10 - 1024 x 256 11 - 1024 x 512 */ #define STV_VDP2_N1BMSZ ((STV_VDP2_CHCTLA & 0x0c00) >> 10) /* N1BMEN - NBG1 Bitmap Enable 0 - use cell mode 1 - use bitmap mode */ #define STV_VDP2_N1BMEN ((STV_VDP2_CHCTLA & 0x0200) >> 9) /* N1CHSZ - NBG1 Character (Tile) Size 0 - 1 cell x 1 cell (8x8) 1 - 2 cells x 2 cells (16x16) */ #define STV_VDP2_N1CHSZ ((STV_VDP2_CHCTLA & 0x0100) >> 8) /* 18002A - CHCTLB - Character Control (NBG2, NBG1, RBG0) bit-> /----15----|----14----|----13----|----12----|----11----|----10----|----09----|----08----\ | -- | R0CHCN2 | R0CHCN1 | R0CHCN0 | -- | R0BMSZ | R0BMEN | R0CHSZ | |----07----|----06----|----05----|----04----|----03----|----02----|----01----|----00----| | -- | -- | N3CHCN | N3CHSZ | -- | -- | N2CHCN | N2CHSZ | \----------|----------|----------|----------|----------|----------|----------|---------*/ #define STV_VDP2_CHCTLB (m_vdp2_regs[0x02a/2]) /* -------------------------- RBG0 Character Control Registers -------------------------- */ /* R0CHCNx RBG0 Colour Depth 000 - 16 Colours 001 - 256 Colours 010 - 2048 Colours 011 - 32768 Colours (RGB5) 100 - 16770000 Colours (RGB8) 101 - invalid 110 - invalid 111 - invalid */ #define STV_VDP2_R0CHCN ((STV_VDP2_CHCTLB & 0x7000) >> 12) /* R0BMSZx - RBG0 Bitmap Size *guessed* 00 - 512 x 256 01 - 512 x 512 */ #define STV_VDP2_R0BMSZ ((STV_VDP2_CHCTLB & 0x0400) >> 10) /* R0BMEN - RBG0 Bitmap Enable 0 - use cell mode 1 - use bitmap mode */ #define STV_VDP2_R0BMEN ((STV_VDP2_CHCTLB & 0x0200) >> 9) /* R0CHSZ - RBG0 Character (Tile) Size 0 - 1 cell x 1 cell (8x8) 1 - 2 cells x 2 cells (16x16) */ #define STV_VDP2_R0CHSZ ((STV_VDP2_CHCTLB & 0x0100) >> 8) #define STV_VDP2_N3CHCN ((STV_VDP2_CHCTLB & 0x0020) >> 5) #define STV_VDP2_N3CHSZ ((STV_VDP2_CHCTLB & 0x0010) >> 4) #define STV_VDP2_N2CHCN ((STV_VDP2_CHCTLB & 0x0002) >> 1) #define STV_VDP2_N2CHSZ ((STV_VDP2_CHCTLB & 0x0001) >> 0) /* 18002C - BMPNA - Bitmap Palette Number (NBG0, NBG1) bit-> /----15----|----14----|----13----|----12----|----11----|----10----|----09----|----08----\ | -- | -- | -- | -- | -- | -- | -- | -- | |----07----|----06----|----05----|----04----|----03----|----02----|----01----|----00----| | -- | -- | -- | -- | -- | -- | -- | -- | \----------|----------|----------|----------|----------|----------|----------|---------*/ #define STV_VDP2_BMPNA (m_vdp2_regs[0x02c/2]) #define STV_VDP2_N1BMP ((STV_VDP2_BMPNA & 0x0700) >> 8) #define STV_VDP2_N0BMP ((STV_VDP2_BMPNA & 0x0007) >> 0) /* 18002E - Bitmap Palette Number (RBG0) bit-> /----15----|----14----|----13----|----12----|----11----|----10----|----09----|----08----\ | -- | -- | -- | -- | -- | -- | -- | -- | |----07----|----06----|----05----|----04----|----03----|----02----|----01----|----00----| | -- | -- | -- | -- | -- | -- | -- | -- | \----------|----------|----------|----------|----------|----------|----------|---------*/ #define STV_VDP2_BMPNB (m_vdp2_regs[0x02e/2]) #define STV_VDP2_R0BMP ((STV_VDP2_BMPNB & 0x0007) >> 0) /* 180030 - PNCN0 - Pattern Name Control (NBG0) bit-> /----15----|----14----|----13----|----12----|----11----|----10----|----09----|----08----\ | N0PNB | N0CNSM | -- | -- | -- | -- | N0SPR | N0SCC | |----07----|----06----|----05----|----04----|----03----|----02----|----01----|----00----| | N0SPLT6 | N0SPLT5 | N0SPLT4 | N0SPCN4 | N0SPCN3 | N0SPCN2 | N0SPCN1 | N0SPCN0 | \----------|----------|----------|----------|----------|----------|----------|---------*/ #define STV_VDP2_PNCN0 (m_vdp2_regs[0x030/2]) /* Pattern Data Size 0 = 2 bytes 1 = 1 byte */ #define STV_VDP2_N0PNB ((STV_VDP2_PNCN0 & 0x8000) >> 15) /* Character Number Supplement (in 1 byte mode) 0 = Character Number = 10bits + 2bits for flip 1 = Character Number = 12 bits, no flip */ #define STV_VDP2_N0CNSM ((STV_VDP2_PNCN0 & 0x4000) >> 14) /* NBG0 Special Priority Register (in 1 byte mode) */ #define STV_VDP2_N0SPR ((STV_VDP2_PNCN0 & 0x0200) >> 9) /* NBG0 Special Colour Control Register (in 1 byte mode) */ #define STV_VDP2_N0SCC ((STV_VDP2_PNCN0 & 0x0100) >> 8) /* Supplementary Palette Bits (in 1 byte mode) */ #define STV_VDP2_N0SPLT ((STV_VDP2_PNCN0 & 0x00e0) >> 5) /* Supplementary Character Bits (in 1 byte mode) */ #define STV_VDP2_N0SPCN ((STV_VDP2_PNCN0 & 0x001f) >> 0) /* 180032 - Pattern Name Control (NBG1) bit-> /----15----|----14----|----13----|----12----|----11----|----10----|----09----|----08----\ | -- | -- | -- | -- | -- | -- | -- | -- | |----07----|----06----|----05----|----04----|----03----|----02----|----01----|----00----| | -- | -- | -- | -- | -- | -- | -- | -- | \----------|----------|----------|----------|----------|----------|----------|---------*/ #define STV_VDP2_PNCN1 (m_vdp2_regs[0x032/2]) /* Pattern Data Size 0 = 2 bytes 1 = 1 byte */ #define STV_VDP2_N1PNB ((STV_VDP2_PNCN1 & 0x8000) >> 15) /* Character Number Supplement (in 1 byte mode) 0 = Character Number = 10bits + 2bits for flip 1 = Character Number = 12 bits, no flip */ #define STV_VDP2_N1CNSM ((STV_VDP2_PNCN1 & 0x4000) >> 14) /* NBG0 Special Priority Register (in 1 byte mode) */ #define STV_VDP2_N1SPR ((STV_VDP2_PNCN1 & 0x0200) >> 9) /* NBG0 Special Colour Control Register (in 1 byte mode) */ #define STV_VDP2_N1SCC ((STV_VDP2_PNCN1 & 0x0100) >> 8) /* Supplementary Palette Bits (in 1 byte mode) */ #define STV_VDP2_N1SPLT ((STV_VDP2_PNCN1 & 0x00e0) >> 5) /* Supplementary Character Bits (in 1 byte mode) */ #define STV_VDP2_N1SPCN ((STV_VDP2_PNCN1 & 0x001f) >> 0) /* 180034 - Pattern Name Control (NBG2) bit-> /----15----|----14----|----13----|----12----|----11----|----10----|----09----|----08----\ | -- | -- | -- | -- | -- | -- | -- | -- | |----07----|----06----|----05----|----04----|----03----|----02----|----01----|----00----| | -- | -- | -- | -- | -- | -- | -- | -- | \----------|----------|----------|----------|----------|----------|----------|---------*/ #define STV_VDP2_PNCN2 (m_vdp2_regs[0x034/2]) /* Pattern Data Size 0 = 2 bytes 1 = 1 byte */ #define STV_VDP2_N2PNB ((STV_VDP2_PNCN2 & 0x8000) >> 15) /* Character Number Supplement (in 1 byte mode) 0 = Character Number = 10bits + 2bits for flip 1 = Character Number = 12 bits, no flip */ #define STV_VDP2_N2CNSM ((STV_VDP2_PNCN2 & 0x4000) >> 14) /* NBG0 Special Priority Register (in 1 byte mode) */ #define STV_VDP2_N2SPR ((STV_VDP2_PNCN2 & 0x0200) >> 9) /* NBG0 Special Colour Control Register (in 1 byte mode) */ #define STV_VDP2_N2SCC ((STV_VDP2_PNCN2 & 0x0100) >> 8) /* Supplementary Palette Bits (in 1 byte mode) */ #define STV_VDP2_N2SPLT ((STV_VDP2_PNCN2 & 0x00e0) >> 5) /* Supplementary Character Bits (in 1 byte mode) */ #define STV_VDP2_N2SPCN ((STV_VDP2_PNCN2 & 0x001f) >> 0) /* 180036 - Pattern Name Control (NBG3) bit-> /----15----|----14----|----13----|----12----|----11----|----10----|----09----|----08----\ | N3PNB | N3CNSM | -- | -- | -- | -- | N3SPR | N3SCC | |----07----|----06----|----05----|----04----|----03----|----02----|----01----|----00----| | N3SPLT6 | N3SPLT5 | N3SPLT4 | N3SPCN4 | N3SPCN3 | N3SPCN2 | N3SPCN1 | N3SPCN0 | \----------|----------|----------|----------|----------|----------|----------|---------*/ #define STV_VDP2_PNCN3 (m_vdp2_regs[0x036/2]) /* Pattern Data Size 0 = 2 bytes 1 = 1 byte */ #define STV_VDP2_N3PNB ((STV_VDP2_PNCN3 & 0x8000) >> 15) /* Character Number Supplement (in 1 byte mode) 0 = Character Number = 10bits + 2bits for flip 1 = Character Number = 12 bits, no flip */ #define STV_VDP2_N3CNSM ((STV_VDP2_PNCN3 & 0x4000) >> 14) /* NBG0 Special Priority Register (in 1 byte mode) */ #define STV_VDP2_N3SPR ((STV_VDP2_PNCN3 & 0x0200) >> 9) /* NBG0 Special Colour Control Register (in 1 byte mode) */ #define STV_VDP2_N3SCC ((STV_VDP2_PNCN3 & 0x0100) >> 8) /* Supplementary Palette Bits (in 1 byte mode) */ #define STV_VDP2_N3SPLT ((STV_VDP2_PNCN3 & 0x00e0) >> 5) /* Supplementary Character Bits (in 1 byte mode) */ #define STV_VDP2_N3SPCN ((STV_VDP2_PNCN3 & 0x001f) >> 0) /* 180038 - Pattern Name Control (RBG0) bit-> /----15----|----14----|----13----|----12----|----11----|----10----|----09----|----08----\ | -- | -- | -- | -- | -- | -- | -- | -- | |----07----|----06----|----05----|----04----|----03----|----02----|----01----|----00----| | -- | -- | -- | -- | -- | -- | -- | -- | \----------|----------|----------|----------|----------|----------|----------|---------*/ #define STV_VDP2_PNCR (m_vdp2_regs[0x038/2]) /* Pattern Data Size 0 = 2 bytes 1 = 1 byte */ #define STV_VDP2_R0PNB ((STV_VDP2_PNCR & 0x8000) >> 15) /* Character Number Supplement (in 1 byte mode) 0 = Character Number = 10bits + 2bits for flip 1 = Character Number = 12 bits, no flip */ #define STV_VDP2_R0CNSM ((STV_VDP2_PNCR & 0x4000) >> 14) /* NBG0 Special Priority Register (in 1 byte mode) */ #define STV_VDP2_R0SPR ((STV_VDP2_PNCR & 0x0200) >> 9) /* NBG0 Special Colour Control Register (in 1 byte mode) */ #define STV_VDP2_R0SCC ((STV_VDP2_PNCR & 0x0100) >> 8) /* Supplementary Palette Bits (in 1 byte mode) */ #define STV_VDP2_R0SPLT ((STV_VDP2_PNCR & 0x00e0) >> 5) /* Supplementary Character Bits (in 1 byte mode) */ #define STV_VDP2_R0SPCN ((STV_VDP2_PNCR & 0x001f) >> 0) /* 18003A - PLSZ - Plane Size bit-> /----15----|----14----|----13----|----12----|----11----|----10----|----09----|----08----\ | -- | -- | -- | -- | -- | -- | -- | -- | |----07----|----06----|----05----|----04----|----03----|----02----|----01----|----00----| | N3PLSZ1 | N3PLSZ0 | -- | -- | N1PLSZ1 | N1PLSZ0 | N0PLSZ1 | N0PLSZ0 | \----------|----------|----------|----------|----------|----------|----------|---------*/ #define STV_VDP2_PLSZ (m_vdp2_regs[0x03a/2]) /* NBG0 Plane Size 00 1H Page x 1V Page 01 2H Pages x 1V Page 10 invalid 11 2H Pages x 2V Pages */ #define STV_VDP2_RBOVR ((STV_VDP2_PLSZ & 0xc000) >> 14) #define STV_VDP2_RBPLSZ ((STV_VDP2_PLSZ & 0x3000) >> 12) #define STV_VDP2_RAOVR ((STV_VDP2_PLSZ & 0x0c00) >> 10) #define STV_VDP2_RAPLSZ ((STV_VDP2_PLSZ & 0x0300) >> 8) #define STV_VDP2_N3PLSZ ((STV_VDP2_PLSZ & 0x00c0) >> 6) #define STV_VDP2_N2PLSZ ((STV_VDP2_PLSZ & 0x0030) >> 4) #define STV_VDP2_N1PLSZ ((STV_VDP2_PLSZ & 0x000c) >> 2) #define STV_VDP2_N0PLSZ ((STV_VDP2_PLSZ & 0x0003) >> 0) /* 18003C - MPOFN - Map Offset (NBG0, NBG1, NBG2, NBG3) bit-> /----15----|----14----|----13----|----12----|----11----|----10----|----09----|----08----\ | -- | N3MP8 | N3MP7 | N3MP6 | -- | N2MP8 | N2MP7 | N2MP6 | |----07----|----06----|----05----|----04----|----03----|----02----|----01----|----00----| | -- | N1MP8 | N1MP7 | N1MP6 | -- | N0MP8 | N0MP7 | N0MP6 | \----------|----------|----------|----------|----------|----------|----------|---------*/ #define STV_VDP2_MPOFN_ (m_vdp2_regs[0x03c/2]) /* Higher 3 bits of the map offset for each layer */ #define STV_VDP2_N3MP_ ((STV_VDP2_MPOFN_ & 0x3000) >> 12) #define STV_VDP2_N2MP_ ((STV_VDP2_MPOFN_ & 0x0300) >> 8) #define STV_VDP2_N1MP_ ((STV_VDP2_MPOFN_ & 0x0030) >> 4) #define STV_VDP2_N0MP_ ((STV_VDP2_MPOFN_ & 0x0003) >> 0) /* 18003E - Map Offset (Rotation Parameter A,B) bit-> /----15----|----14----|----13----|----12----|----11----|----10----|----09----|----08----\ | -- | -- | -- | -- | -- | -- | -- | -- | |----07----|----06----|----05----|----04----|----03----|----02----|----01----|----00----| | -- | -- | -- | -- | -- | -- | -- | -- | \----------|----------|----------|----------|----------|----------|----------|---------*/ #define STV_VDP2_MPOFR_ (m_vdp2_regs[0x03e/2]) #define STV_VDP2_RBMP_ ((STV_VDP2_MPOFR_ & 0x0030) >> 4) #define STV_VDP2_RAMP_ ((STV_VDP2_MPOFR_ & 0x0003) >> 0) /* 180040 - MPABN0 - Map (NBG0, Plane A,B) bit-> /----15----|----14----|----13----|----12----|----11----|----10----|----09----|----08----\ | -- | -- | N0MPB5 | N0MPB4 | N0MPB3 | N0MPB2 | N0MPB1 | N0MPB0 | |----07----|----06----|----05----|----04----|----03----|----02----|----01----|----00----| | -- | -- | N0MPA5 | N0MPA4 | N0MPA3 | N0MPA2 | N0MPA1 | N0MPA0 | \----------|----------|----------|----------|----------|----------|----------|---------*/ #define STV_VDP2_MPABN0 (m_vdp2_regs[0x040/2]) /* N0MPB5 = lower 6 bits of Map Address of Plane B of Tilemap NBG0 */ #define STV_VDP2_N0MPB ((STV_VDP2_MPABN0 & 0x3f00) >> 8) /* N0MPA5 = lower 6 bits of Map Address of Plane A of Tilemap NBG0 */ #define STV_VDP2_N0MPA ((STV_VDP2_MPABN0 & 0x003f) >> 0) /* 180042 - MPCDN0 - (NBG0, Plane C,D) bit-> /----15----|----14----|----13----|----12----|----11----|----10----|----09----|----08----\ | -- | -- | N0MPD5 | N0MPD4 | N0MPD3 | N0MPD2 | N0MPD1 | N0MPD0 | |----07----|----06----|----05----|----04----|----03----|----02----|----01----|----00----| | -- | -- | N0MPC5 | N0MPC4 | N0MPC3 | N0MPC2 | N0MPC1 | N0MPC0 | \----------|----------|----------|----------|----------|----------|----------|---------*/ #define STV_VDP2_MPCDN0 (m_vdp2_regs[0x042/2]) /* N0MPB5 = lower 6 bits of Map Address of Plane D of Tilemap NBG0 */ #define STV_VDP2_N0MPD ((STV_VDP2_MPCDN0 & 0x3f00) >> 8) /* N0MPA5 = lower 6 bits of Map Address of Plane C of Tilemap NBG0 */ #define STV_VDP2_N0MPC ((STV_VDP2_MPCDN0 & 0x003f) >> 0) /* 180044 - Map (NBG1, Plane A,B) bit-> /----15----|----14----|----13----|----12----|----11----|----10----|----09----|----08----\ | -- | -- | -- | -- | -- | -- | -- | -- | |----07----|----06----|----05----|----04----|----03----|----02----|----01----|----00----| | -- | -- | -- | -- | -- | -- | -- | -- | \----------|----------|----------|----------|----------|----------|----------|---------*/ #define STV_VDP2_MPABN1 (m_vdp2_regs[0x044/2]) /* N0MPB5 = lower 6 bits of Map Address of Plane B of Tilemap NBG1 */ #define STV_VDP2_N1MPB ((STV_VDP2_MPABN1 & 0x3f00) >> 8) /* N0MPA5 = lower 6 bits of Map Address of Plane A of Tilemap NBG1 */ #define STV_VDP2_N1MPA ((STV_VDP2_MPABN1 & 0x003f) >> 0) /* 180046 - Map (NBG1, Plane C,D) bit-> /----15----|----14----|----13----|----12----|----11----|----10----|----09----|----08----\ | -- | -- | -- | -- | -- | -- | -- | -- | |----07----|----06----|----05----|----04----|----03----|----02----|----01----|----00----| | -- | -- | -- | -- | -- | -- | -- | -- | \----------|----------|----------|----------|----------|----------|----------|---------*/ #define STV_VDP2_MPCDN1 (m_vdp2_regs[0x046/2]) /* N0MPB5 = lower 6 bits of Map Address of Plane D of Tilemap NBG0 */ #define STV_VDP2_N1MPD ((STV_VDP2_MPCDN1 & 0x3f00) >> 8) /* N0MPA5 = lower 6 bits of Map Address of Plane C of Tilemap NBG0 */ #define STV_VDP2_N1MPC ((STV_VDP2_MPCDN1 & 0x003f) >> 0) /* 180048 - Map (NBG2, Plane A,B) bit-> /----15----|----14----|----13----|----12----|----11----|----10----|----09----|----08----\ | -- | -- | -- | -- | -- | -- | -- | -- | |----07----|----06----|----05----|----04----|----03----|----02----|----01----|----00----| | -- | -- | -- | -- | -- | -- | -- | -- | \----------|----------|----------|----------|----------|----------|----------|---------*/ #define STV_VDP2_MPABN2 (m_vdp2_regs[0x048/2]) /* N0MPB5 = lower 6 bits of Map Address of Plane B of Tilemap NBG2 */ #define STV_VDP2_N2MPB ((STV_VDP2_MPABN2 & 0x3f00) >> 8) /* N0MPA5 = lower 6 bits of Map Address of Plane A of Tilemap NBG2 */ #define STV_VDP2_N2MPA ((STV_VDP2_MPABN2 & 0x003f) >> 0) /* 18004a - Map (NBG2, Plane C,D) bit-> /----15----|----14----|----13----|----12----|----11----|----10----|----09----|----08----\ | -- | -- | -- | -- | -- | -- | -- | -- | |----07----|----06----|----05----|----04----|----03----|----02----|----01----|----00----| | -- | -- | -- | -- | -- | -- | -- | -- | \----------|----------|----------|----------|----------|----------|----------|---------*/ #define STV_VDP2_MPCDN2 (m_vdp2_regs[0x04a/2]) /* N0MPB5 = lower 6 bits of Map Address of Plane D of Tilemap NBG2 */ #define STV_VDP2_N2MPD ((STV_VDP2_MPCDN2 & 0x3f00) >> 8) /* N0MPA5 = lower 6 bits of Map Address of Plane C of Tilemap NBG2 */ #define STV_VDP2_N2MPC ((STV_VDP2_MPCDN2 & 0x003f) >> 0) /* 18004c - Map (NBG3, Plane A,B) bit-> /----15----|----14----|----13----|----12----|----11----|----10----|----09----|----08----\ | -- | -- | -- | -- | -- | -- | -- | -- | |----07----|----06----|----05----|----04----|----03----|----02----|----01----|----00----| | -- | -- | -- | -- | -- | -- | -- | -- | \----------|----------|----------|----------|----------|----------|----------|---------*/ #define STV_VDP2_MPABN3 (m_vdp2_regs[0x04c/2]) /* N0MPB5 = lower 6 bits of Map Address of Plane B of Tilemap NBG1 */ #define STV_VDP2_N3MPB ((STV_VDP2_MPABN3 & 0x3f00) >> 8) /* N0MPA5 = lower 6 bits of Map Address of Plane A of Tilemap NBG1 */ #define STV_VDP2_N3MPA ((STV_VDP2_MPABN3 & 0x003f) >> 0) /* 18004e - Map (NBG3, Plane C,D) bit-> /----15----|----14----|----13----|----12----|----11----|----10----|----09----|----08----\ | -- | -- | -- | -- | -- | -- | -- | -- | |----07----|----06----|----05----|----04----|----03----|----02----|----01----|----00----| | -- | -- | -- | -- | -- | -- | -- | -- | \----------|----------|----------|----------|----------|----------|----------|---------*/ #define STV_VDP2_MPCDN3 (m_vdp2_regs[0x04e/2]) /* N0MPB5 = lower 6 bits of Map Address of Plane B of Tilemap NBG0 */ #define STV_VDP2_N3MPD ((STV_VDP2_MPCDN3 & 0x3f00) >> 8) /* N0MPA5 = lower 6 bits of Map Address of Plane A of Tilemap NBG0 */ #define STV_VDP2_N3MPC ((STV_VDP2_MPCDN3 & 0x003f) >> 0) /* 180050 - Map (Rotation Parameter A, Plane A,B) bit-> /----15----|----14----|----13----|----12----|----11----|----10----|----09----|----08----\ | -- | -- | -- | -- | -- | -- | -- | -- | |----07----|----06----|----05----|----04----|----03----|----02----|----01----|----00----| | -- | -- | -- | -- | -- | -- | -- | -- | \----------|----------|----------|----------|----------|----------|----------|---------*/ #define STV_VDP2_MPABRA (m_vdp2_regs[0x050/2]) /* R0MPB5 = lower 6 bits of Map Address of Plane B of Tilemap RBG0 */ #define STV_VDP2_RAMPB ((STV_VDP2_MPABRA & 0x3f00) >> 8) /* R0MPA5 = lower 6 bits of Map Address of Plane A of Tilemap RBG0 */ #define STV_VDP2_RAMPA ((STV_VDP2_MPABRA & 0x003f) >> 0) /* 180052 - Map (Rotation Parameter A, Plane C,D) bit-> /----15----|----14----|----13----|----12----|----11----|----10----|----09----|----08----\ | -- | -- | -- | -- | -- | -- | -- | -- | |----07----|----06----|----05----|----04----|----03----|----02----|----01----|----00----| | -- | -- | -- | -- | -- | -- | -- | -- | \----------|----------|----------|----------|----------|----------|----------|---------*/ #define STV_VDP2_MPCDRA (m_vdp2_regs[0x052/2]) /* R0MPB5 = lower 6 bits of Map Address of Plane D of Tilemap RBG0 */ #define STV_VDP2_RAMPD ((STV_VDP2_MPCDRA & 0x3f00) >> 8) /* R0MPA5 = lower 6 bits of Map Address of Plane C of Tilemap RBG0 */ #define STV_VDP2_RAMPC ((STV_VDP2_MPCDRA & 0x003f) >> 0) /* 180054 - Map (Rotation Parameter A, Plane E,F) bit-> /----15----|----14----|----13----|----12----|----11----|----10----|----09----|----08----\ | -- | -- | -- | -- | -- | -- | -- | -- | |----07----|----06----|----05----|----04----|----03----|----02----|----01----|----00----| | -- | -- | -- | -- | -- | -- | -- | -- | \----------|----------|----------|----------|----------|----------|----------|---------*/ #define STV_VDP2_MPEFRA (m_vdp2_regs[0x054/2]) /* R0MPB5 = lower 6 bits of Map Address of Plane F of Tilemap RBG0 */ #define STV_VDP2_RAMPF ((STV_VDP2_MPEFRA & 0x3f00) >> 8) /* R0MPA5 = lower 6 bits of Map Address of Plane E of Tilemap RBG0 */ #define STV_VDP2_RAMPE ((STV_VDP2_MPEFRA & 0x003f) >> 0) /* 180056 - Map (Rotation Parameter A, Plane G,H) bit-> /----15----|----14----|----13----|----12----|----11----|----10----|----09----|----08----\ | -- | -- | -- | -- | -- | -- | -- | -- | |----07----|----06----|----05----|----04----|----03----|----02----|----01----|----00----| | -- | -- | -- | -- | -- | -- | -- | -- | \----------|----------|----------|----------|----------|----------|----------|---------*/ #define STV_VDP2_MPGHRA (m_vdp2_regs[0x056/2]) /* R0MPB5 = lower 6 bits of Map Address of Plane H of Tilemap RBG0 */ #define STV_VDP2_RAMPH ((STV_VDP2_MPGHRA & 0x3f00) >> 8) /* R0MPA5 = lower 6 bits of Map Address of Plane G of Tilemap RBG0 */ #define STV_VDP2_RAMPG ((STV_VDP2_MPGHRA & 0x003f) >> 0) /* 180058 - Map (Rotation Parameter A, Plane I,J) bit-> /----15----|----14----|----13----|----12----|----11----|----10----|----09----|----08----\ | -- | -- | -- | -- | -- | -- | -- | -- | |----07----|----06----|----05----|----04----|----03----|----02----|----01----|----00----| | -- | -- | -- | -- | -- | -- | -- | -- | \----------|----------|----------|----------|----------|----------|----------|---------*/ #define STV_VDP2_MPIJRA (m_vdp2_regs[0x058/2]) /* R0MPB5 = lower 6 bits of Map Address of Plane J of Tilemap RBG0 */ #define STV_VDP2_RAMPJ ((STV_VDP2_MPIJRA & 0x3f00) >> 8) /* R0MPA5 = lower 6 bits of Map Address of Plane I of Tilemap RBG0 */ #define STV_VDP2_RAMPI ((STV_VDP2_MPIJRA & 0x003f) >> 0) /* 18005a - Map (Rotation Parameter A, Plane K,L) bit-> /----15----|----14----|----13----|----12----|----11----|----10----|----09----|----08----\ | -- | -- | -- | -- | -- | -- | -- | -- | |----07----|----06----|----05----|----04----|----03----|----02----|----01----|----00----| | -- | -- | -- | -- | -- | -- | -- | -- | \----------|----------|----------|----------|----------|----------|----------|---------*/ #define STV_VDP2_MPKLRA (m_vdp2_regs[0x05a/2]) /* R0MPB5 = lower 6 bits of Map Address of Plane L of Tilemap RBG0 */ #define STV_VDP2_RAMPL ((STV_VDP2_MPKLRA & 0x3f00) >> 8) /* R0MPA5 = lower 6 bits of Map Address of Plane K of Tilemap RBG0 */ #define STV_VDP2_RAMPK ((STV_VDP2_MPKLRA & 0x003f) >> 0) /* 18005c - Map (Rotation Parameter A, Plane M,N) bit-> /----15----|----14----|----13----|----12----|----11----|----10----|----09----|----08----\ | -- | -- | -- | -- | -- | -- | -- | -- | |----07----|----06----|----05----|----04----|----03----|----02----|----01----|----00----| | -- | -- | -- | -- | -- | -- | -- | -- | \----------|----------|----------|----------|----------|----------|----------|---------*/ #define STV_VDP2_MPMNRA (m_vdp2_regs[0x05c/2]) /* R0MPB5 = lower 6 bits of Map Address of Plane N of Tilemap RBG0 */ #define STV_VDP2_RAMPN ((STV_VDP2_MPMNRA & 0x3f00) >> 8) /* R0MPA5 = lower 6 bits of Map Address of Plane M of Tilemap RBG0 */ #define STV_VDP2_RAMPM ((STV_VDP2_MPMNRA & 0x003f) >> 0) /* 18005e - Map (Rotation Parameter A, Plane O,P) bit-> /----15----|----14----|----13----|----12----|----11----|----10----|----09----|----08----\ | -- | -- | -- | -- | -- | -- | -- | -- | |----07----|----06----|----05----|----04----|----03----|----02----|----01----|----00----| | -- | -- | -- | -- | -- | -- | -- | -- | \----------|----------|----------|----------|----------|----------|----------|---------*/ #define STV_VDP2_MPOPRA (m_vdp2_regs[0x05e/2]) /* R0MPB5 = lower 6 bits of Map Address of Plane P of Tilemap RBG0 */ #define STV_VDP2_RAMPP ((STV_VDP2_MPOPRA & 0x3f00) >> 8) /* R0MPA5 = lower 6 bits of Map Address of Plane O of Tilemap RBG0 */ #define STV_VDP2_RAMPO ((STV_VDP2_MPOPRA & 0x003f) >> 0) /* 180060 - Map (Rotation Parameter B, Plane A,B) bit-> /----15----|----14----|----13----|----12----|----11----|----10----|----09----|----08----\ | -- | -- | -- | -- | -- | -- | -- | -- | |----07----|----06----|----05----|----04----|----03----|----02----|----01----|----00----| | -- | -- | -- | -- | -- | -- | -- | -- | \----------|----------|----------|----------|----------|----------|----------|---------*/ #define STV_VDP2_MPABRB (m_vdp2_regs[0x060/2]) /* R0MPB5 = lower 6 bits of Map Address of Plane B of Tilemap RBG0 */ #define STV_VDP2_RBMPB ((STV_VDP2_MPABRB & 0x3f00) >> 8) /* R0MPA5 = lower 6 bits of Map Address of Plane A of Tilemap RBG0 */ #define STV_VDP2_RBMPA ((STV_VDP2_MPABRB & 0x003f) >> 0) /* 180062 - Map (Rotation Parameter B, Plane C,D) bit-> /----15----|----14----|----13----|----12----|----11----|----10----|----09----|----08----\ | -- | -- | -- | -- | -- | -- | -- | -- | |----07----|----06----|----05----|----04----|----03----|----02----|----01----|----00----| | -- | -- | -- | -- | -- | -- | -- | -- | \----------|----------|----------|----------|----------|----------|----------|---------*/ #define STV_VDP2_MPCDRB (m_vdp2_regs[0x062/2]) /* R0MPD5 = lower 6 bits of Map Address of Plane D of Tilemap RBG0 */ #define STV_VDP2_RBMPD ((STV_VDP2_MPCDRB & 0x3f00) >> 8) /* R0MPc5 = lower 6 bits of Map Address of Plane C of Tilemap RBG0 */ #define STV_VDP2_RBMPC ((STV_VDP2_MPCDRB & 0x003f) >> 0) /* 180064 - Map (Rotation Parameter B, Plane E,F) bit-> /----15----|----14----|----13----|----12----|----11----|----10----|----09----|----08----\ | -- | -- | -- | -- | -- | -- | -- | -- | |----07----|----06----|----05----|----04----|----03----|----02----|----01----|----00----| | -- | -- | -- | -- | -- | -- | -- | -- | \----------|----------|----------|----------|----------|----------|----------|---------*/ #define STV_VDP2_MPEFRB (m_vdp2_regs[0x064/2]) /* R0MPF5 = lower 6 bits of Map Address of Plane F of Tilemap RBG0 */ #define STV_VDP2_RBMPF ((STV_VDP2_MPEFRB & 0x3f00) >> 8) /* R0MPE5 = lower 6 bits of Map Address of Plane E of Tilemap RBG0 */ #define STV_VDP2_RBMPE ((STV_VDP2_MPEFRB & 0x003f) >> 0) /* 180066 - Map (Rotation Parameter B, Plane G,H) bit-> /----15----|----14----|----13----|----12----|----11----|----10----|----09----|----08----\ | -- | -- | -- | -- | -- | -- | -- | -- | |----07----|----06----|----05----|----04----|----03----|----02----|----01----|----00----| | -- | -- | -- | -- | -- | -- | -- | -- | \----------|----------|----------|----------|----------|----------|----------|---------*/ #define STV_VDP2_MPGHRB (m_vdp2_regs[0x066/2]) /* R0MPH5 = lower 6 bits of Map Address of Plane H of Tilemap RBG0 */ #define STV_VDP2_RBMPH ((STV_VDP2_MPGHRB & 0x3f00) >> 8) /* R0MPG5 = lower 6 bits of Map Address of Plane G of Tilemap RBG0 */ #define STV_VDP2_RBMPG ((STV_VDP2_MPGHRB & 0x003f) >> 0) /* 180068 - Map (Rotation Parameter B, Plane I,J) bit-> /----15----|----14----|----13----|----12----|----11----|----10----|----09----|----08----\ | -- | -- | -- | -- | -- | -- | -- | -- | |----07----|----06----|----05----|----04----|----03----|----02----|----01----|----00----| | -- | -- | -- | -- | -- | -- | -- | -- | \----------|----------|----------|----------|----------|----------|----------|---------*/ #define STV_VDP2_MPIJRB (m_vdp2_regs[0x068/2]) /* R0MPJ5 = lower 6 bits of Map Address of Plane J of Tilemap RBG0 */ #define STV_VDP2_RBMPJ ((STV_VDP2_MPIJRB & 0x3f00) >> 8) /* R0MPI5 = lower 6 bits of Map Address of Plane E of Tilemap RBG0 */ #define STV_VDP2_RBMPI ((STV_VDP2_MPIJRB & 0x003f) >> 0) /* 18006a - Map (Rotation Parameter B, Plane K,L) bit-> /----15----|----14----|----13----|----12----|----11----|----10----|----09----|----08----\ | -- | -- | -- | -- | -- | -- | -- | -- | |----07----|----06----|----05----|----04----|----03----|----02----|----01----|----00----| | -- | -- | -- | -- | -- | -- | -- | -- | \----------|----------|----------|----------|----------|----------|----------|---------*/ #define STV_VDP2_MPKLRB (m_vdp2_regs[0x06a/2]) /* R0MPL5 = lower 6 bits of Map Address of Plane L of Tilemap RBG0 */ #define STV_VDP2_RBMPL ((STV_VDP2_MPKLRB & 0x3f00) >> 8) /* R0MPK5 = lower 6 bits of Map Address of Plane K of Tilemap RBG0 */ #define STV_VDP2_RBMPK ((STV_VDP2_MPKLRB & 0x003f) >> 0) /* 18006c - Map (Rotation Parameter B, Plane M,N) bit-> /----15----|----14----|----13----|----12----|----11----|----10----|----09----|----08----\ | -- | -- | -- | -- | -- | -- | -- | -- | |----07----|----06----|----05----|----04----|----03----|----02----|----01----|----00----| | -- | -- | -- | -- | -- | -- | -- | -- | \----------|----------|----------|----------|----------|----------|----------|---------*/ #define STV_VDP2_MPMNRB (m_vdp2_regs[0x06c/2]) /* R0MPN5 = lower 6 bits of Map Address of Plane N of Tilemap RBG0 */ #define STV_VDP2_RBMPN ((STV_VDP2_MPMNRB & 0x3f00) >> 8) /* R0MPM5 = lower 6 bits of Map Address of Plane M of Tilemap RBG0 */ #define STV_VDP2_RBMPM ((STV_VDP2_MPMNRB & 0x003f) >> 0) /* 18006e - Map (Rotation Parameter B, Plane O,P) bit-> /----15----|----14----|----13----|----12----|----11----|----10----|----09----|----08----\ | -- | -- | -- | -- | -- | -- | -- | -- | |----07----|----06----|----05----|----04----|----03----|----02----|----01----|----00----| | -- | -- | -- | -- | -- | -- | -- | -- | \----------|----------|----------|----------|----------|----------|----------|---------*/ #define STV_VDP2_MPOPRB (m_vdp2_regs[0x06e/2]) /* R0MPP5 = lower 6 bits of Map Address of Plane P of Tilemap RBG0 */ #define STV_VDP2_RBMPP ((STV_VDP2_MPOPRB & 0x3f00) >> 8) /* R0MPO5 = lower 6 bits of Map Address of Plane O of Tilemap RBG0 */ #define STV_VDP2_RBMPO ((STV_VDP2_MPOPRB & 0x003f) >> 0) /* 180070 - SCXIN0 - Screen Scroll (NBG0, Horizontal Integer Part) bit-> /----15----|----14----|----13----|----12----|----11----|----10----|----09----|----08----\ | -- | -- | -- | -- | -- | -- | -- | -- | |----07----|----06----|----05----|----04----|----03----|----02----|----01----|----00----| | -- | -- | -- | -- | -- | -- | -- | -- | \----------|----------|----------|----------|----------|----------|----------|---------*/ #define STV_VDP2_SCXIN0 (m_vdp2_regs[0x070/2]) /* 180072 - Screen Scroll (NBG0, Horizontal Fractional Part) bit-> /----15----|----14----|----13----|----12----|----11----|----10----|----09----|----08----\ | -- | -- | -- | -- | -- | -- | -- | -- | |----07----|----06----|----05----|----04----|----03----|----02----|----01----|----00----| | -- | -- | -- | -- | -- | -- | -- | -- | \----------|----------|----------|----------|----------|----------|----------|---------*/ #define STV_VDP2_SCXDN0 (m_vdp2_regs[0x072/2]) /* 180074 - SCYIN0 - Screen Scroll (NBG0, Vertical Integer Part) bit-> /----15----|----14----|----13----|----12----|----11----|----10----|----09----|----08----\ | -- | -- | -- | -- | -- | -- | -- | -- | |----07----|----06----|----05----|----04----|----03----|----02----|----01----|----00----| | -- | -- | -- | -- | -- | -- | -- | -- | \----------|----------|----------|----------|----------|----------|----------|---------*/ #define STV_VDP2_SCYIN0 (m_vdp2_regs[0x074/2]) /* 180076 - Screen Scroll (NBG0, Vertical Fractional Part) bit-> /----15----|----14----|----13----|----12----|----11----|----10----|----09----|----08----\ | -- | -- | -- | -- | -- | -- | -- | -- | |----07----|----06----|----05----|----04----|----03----|----02----|----01----|----00----| | -- | -- | -- | -- | -- | -- | -- | -- | \----------|----------|----------|----------|----------|----------|----------|---------*/ #define STV_VDP2_SCYDN0 (m_vdp2_regs[0x076/2]) /* 180078 - Coordinate Inc (NBG0, Horizontal Integer Part) bit-> /----15----|----14----|----13----|----12----|----11----|----10----|----09----|----08----\ | -- | -- | -- | -- | -- | -- | -- | -- | |----07----|----06----|----05----|----04----|----03----|----02----|----01----|----00----| | -- | -- | -- | -- | -- | -- | -- | -- | \----------|----------|----------|----------|----------|----------|----------|---------*/ #define STV_VDP2_ZMXIN0 (m_vdp2_regs[0x078/2]) #define STV_VDP2_N0ZMXI ((STV_VDP2_ZMXIN0 & 0x0007) >> 0) /* 18007a - Coordinate Inc (NBG0, Horizontal Fractional Part) bit-> /----15----|----14----|----13----|----12----|----11----|----10----|----09----|----08----\ | -- | -- | -- | -- | -- | -- | -- | -- | |----07----|----06----|----05----|----04----|----03----|----02----|----01----|----00----| | -- | -- | -- | -- | -- | -- | -- | -- | \----------|----------|----------|----------|----------|----------|----------|---------*/ #define STV_VDP2_ZMXDN0 (m_vdp2_regs[0x07a/2]) #define STV_VDP2_N0ZMXD ((STV_VDP2_ZMXDN0 >> 8)& 0xff) #define STV_VDP2_ZMXN0 (((STV_VDP2_N0ZMXI<<16) | (STV_VDP2_N0ZMXD<<8)) & 0x0007ff00) /* 18007c - Coordinate Inc (NBG0, Vertical Integer Part) bit-> /----15----|----14----|----13----|----12----|----11----|----10----|----09----|----08----\ | -- | -- | -- | -- | -- | -- | -- | -- | |----07----|----06----|----05----|----04----|----03----|----02----|----01----|----00----| | -- | -- | -- | -- | -- | -- | -- | -- | \----------|----------|----------|----------|----------|----------|----------|---------*/ #define STV_VDP2_ZMYIN0 (m_vdp2_regs[0x07c/2]) #define STV_VDP2_N0ZMYI ((STV_VDP2_ZMYIN0 & 0x0007) >> 0) /* 18007e - Coordinate Inc (NBG0, Vertical Fractional Part) bit-> /----15----|----14----|----13----|----12----|----11----|----10----|----09----|----08----\ | -- | -- | -- | -- | -- | -- | -- | -- | |----07----|----06----|----05----|----04----|----03----|----02----|----01----|----00----| | -- | -- | -- | -- | -- | -- | -- | -- | \----------|----------|----------|----------|----------|----------|----------|---------*/ #define STV_VDP2_ZMYDN0 (m_vdp2_regs[0x07e/2]) #define STV_VDP2_N0ZMYD ((STV_VDP2_ZMYDN0 >> 8)& 0xff) #define STV_VDP2_ZMYN0 (((STV_VDP2_N0ZMYI<<16) | (STV_VDP2_N0ZMYD<<8)) & 0x0007ff00) /* 180080 - SCXIN1 - Screen Scroll (NBG1, Horizontal Integer Part) bit-> /----15----|----14----|----13----|----12----|----11----|----10----|----09----|----08----\ | -- | -- | -- | -- | -- | -- | -- | -- | |----07----|----06----|----05----|----04----|----03----|----02----|----01----|----00----| | -- | -- | -- | -- | -- | -- | -- | -- | \----------|----------|----------|----------|----------|----------|----------|---------*/ #define STV_VDP2_SCXIN1 (m_vdp2_regs[0x080/2]) /* 180082 - Screen Scroll (NBG1, Horizontal Fractional Part) bit-> /----15----|----14----|----13----|----12----|----11----|----10----|----09----|----08----\ | -- | -- | -- | -- | -- | -- | -- | -- | |----07----|----06----|----05----|----04----|----03----|----02----|----01----|----00----| | -- | -- | -- | -- | -- | -- | -- | -- | \----------|----------|----------|----------|----------|----------|----------|---------*/ #define STV_VDP2_SCXDN1 (m_vdp2_regs[0x082/2]) /* 180084 - SCYIN1 - Screen Scroll (NBG1, Vertical Integer Part) bit-> /----15----|----14----|----13----|----12----|----11----|----10----|----09----|----08----\ | -- | -- | -- | -- | -- | -- | -- | -- | |----07----|----06----|----05----|----04----|----03----|----02----|----01----|----00----| | -- | -- | -- | -- | -- | -- | -- | -- | \----------|----------|----------|----------|----------|----------|----------|---------*/ #define STV_VDP2_SCYIN1 (m_vdp2_regs[0x084/2]) /* 180086 - Screen Scroll (NBG1, Vertical Fractional Part) bit-> /----15----|----14----|----13----|----12----|----11----|----10----|----09----|----08----\ | -- | -- | -- | -- | -- | -- | -- | -- | |----07----|----06----|----05----|----04----|----03----|----02----|----01----|----00----| | -- | -- | -- | -- | -- | -- | -- | -- | \----------|----------|----------|----------|----------|----------|----------|---------*/ #define STV_VDP2_SCYDN1 (m_vdp2_regs[0x086/2]) /* 180088 - Coordinate Inc (NBG1, Horizontal Integer Part) bit-> /----15----|----14----|----13----|----12----|----11----|----10----|----09----|----08----\ | -- | -- | -- | -- | -- | -- | -- | -- | |----07----|----06----|----05----|----04----|----03----|----02----|----01----|----00----| | -- | -- | -- | -- | -- | -- | -- | -- | \----------|----------|----------|----------|----------|----------|----------|---------*/ #define STV_VDP2_ZMXIN1 (m_vdp2_regs[0x088/2]) #define STV_VDP2_N1ZMXI ((STV_VDP2_ZMXIN1 & 0x0007) >> 0) /* 18008a - Coordinate Inc (NBG1, Horizontal Fractional Part) bit-> /----15----|----14----|----13----|----12----|----11----|----10----|----09----|----08----\ | -- | -- | -- | -- | -- | -- | -- | -- | |----07----|----06----|----05----|----04----|----03----|----02----|----01----|----00----| | -- | -- | -- | -- | -- | -- | -- | -- | \----------|----------|----------|----------|----------|----------|----------|---------*/ #define STV_VDP2_ZMXDN1 (m_vdp2_regs[0x08a/2]) #define STV_VDP2_N1ZMXD ((STV_VDP2_ZMXDN1 >> 8)& 0xff) #define STV_VDP2_ZMXN1 (((STV_VDP2_N1ZMXI<<16) | (STV_VDP2_N1ZMXD<<8)) & 0x0007ff00) /* 18008c - Coordinate Inc (NBG1, Vertical Integer Part) bit-> /----15----|----14----|----13----|----12----|----11----|----10----|----09----|----08----\ | -- | -- | -- | -- | -- | -- | -- | -- | |----07----|----06----|----05----|----04----|----03----|----02----|----01----|----00----| | -- | -- | -- | -- | -- | -- | -- | -- | \----------|----------|----------|----------|----------|----------|----------|---------*/ #define STV_VDP2_ZMYIN1 (m_vdp2_regs[0x08c/2]) #define STV_VDP2_N1ZMYI ((STV_VDP2_ZMYIN1 & 0x0007) >> 0) /* 18008e - Coordinate Inc (NBG1, Vertical Fractional Part) bit-> /----15----|----14----|----13----|----12----|----11----|----10----|----09----|----08----\ | -- | -- | -- | -- | -- | -- | -- | -- | |----07----|----06----|----05----|----04----|----03----|----02----|----01----|----00----| | -- | -- | -- | -- | -- | -- | -- | -- | \----------|----------|----------|----------|----------|----------|----------|---------*/ #define STV_VDP2_ZMYDN1 (m_vdp2_regs[0x08e/2]) #define STV_VDP2_N1ZMYD ((STV_VDP2_ZMYDN1 >> 8)& 0xff) #define STV_VDP2_ZMYN1 (((STV_VDP2_N1ZMYI<<16) | (STV_VDP2_N1ZMYD<<8)) & 0x007ff00) /* 180090 - SCXN2 - Screen Scroll (NBG2, Horizontal) bit-> /----15----|----14----|----13----|----12----|----11----|----10----|----09----|----08----\ | -- | -- | -- | -- | -- | -- | -- | -- | |----07----|----06----|----05----|----04----|----03----|----02----|----01----|----00----| | -- | -- | -- | -- | -- | -- | -- | -- | \----------|----------|----------|----------|----------|----------|----------|---------*/ #define STV_VDP2_SCXN2 (m_vdp2_regs[0x090/2]) /* 180092 - SCYN2 - Screen Scroll (NBG2, Vertical) bit-> /----15----|----14----|----13----|----12----|----11----|----10----|----09----|----08----\ | -- | -- | -- | -- | -- | -- | -- | -- | |----07----|----06----|----05----|----04----|----03----|----02----|----01----|----00----| | -- | -- | -- | -- | -- | -- | -- | -- | \----------|----------|----------|----------|----------|----------|----------|---------*/ #define STV_VDP2_SCYN2 (m_vdp2_regs[0x092/2]) /* 180094 - SCXN3 - Screen Scroll (NBG3, Horizontal) bit-> /----15----|----14----|----13----|----12----|----11----|----10----|----09----|----08----\ | -- | -- | -- | -- | -- | -- | -- | -- | |----07----|----06----|----05----|----04----|----03----|----02----|----01----|----00----| | -- | -- | -- | -- | -- | -- | -- | -- | \----------|----------|----------|----------|----------|----------|----------|---------*/ #define STV_VDP2_SCXN3 (m_vdp2_regs[0x094/2]) /* 180096 - SCYN3 - Screen Scroll (NBG3, Vertical) bit-> /----15----|----14----|----13----|----12----|----11----|----10----|----09----|----08----\ | -- | -- | -- | -- | -- | -- | -- | -- | |----07----|----06----|----05----|----04----|----03----|----02----|----01----|----00----| | -- | -- | -- | -- | -- | -- | -- | -- | \----------|----------|----------|----------|----------|----------|----------|---------*/ #define STV_VDP2_SCYN3 (m_vdp2_regs[0x096/2]) /* 180098 - Reduction Enable bit-> /----15----|----14----|----13----|----12----|----11----|----10----|----09----|----08----\ | -- | -- | -- | -- | -- | -- | N1ZMQT | N1ZMHF | |----07----|----06----|----05----|----04----|----03----|----02----|----01----|----00----| | -- | -- | -- | -- | -- | -- | N0ZMQT | N0ZMHF | \----------|----------|----------|----------|----------|----------|----------|---------*/ #define STV_VDP2_ZMCTL (m_vdp2_regs[0x098/2]) #define STV_VDP2_N1ZMQT ((STV_VDP2_ZMCTL & 0x0200) >> 9) #define STV_VDP2_N1ZMHF ((STV_VDP2_ZMCTL & 0x0100) >> 8) #define STV_VDP2_N0ZMQT ((STV_VDP2_ZMCTL & 0x0002) >> 1) #define STV_VDP2_N0ZMHF ((STV_VDP2_ZMCTL & 0x0001) >> 0) /* 18009a - Line and Vertical Cell Scroll Control (NBG0, NBG1) bit-> /----15----|----14----|----13----|----12----|----11----|----10----|----09----|----08----\ | -- | -- | -- | -- | -- | -- | -- | -- | |----07----|----06----|----05----|----04----|----03----|----02----|----01----|----00----| | -- | -- | -- | -- | -- | -- | -- | -- | \----------|----------|----------|----------|----------|----------|----------|---------*/ #define STV_VDP2_SCRCTL (m_vdp2_regs[0x09a/2]) #define STV_VDP2_N1LSS ((STV_VDP2_SCRCTL & 0x3000) >> 12) #define STV_VDP2_N1LZMX ((STV_VDP2_SCRCTL & 0x0800) >> 11) #define STV_VDP2_N1LSCY ((STV_VDP2_SCRCTL & 0x0400) >> 10) #define STV_VDP2_N1LSCX ((STV_VDP2_SCRCTL & 0x0200) >> 9) #define STV_VDP2_N1VCSC ((STV_VDP2_SCRCTL & 0x0100) >> 8) #define STV_VDP2_N0LSS ((STV_VDP2_SCRCTL & 0x0030) >> 4) #define STV_VDP2_N0LZMX ((STV_VDP2_SCRCTL & 0x0008) >> 3) #define STV_VDP2_N0LSCY ((STV_VDP2_SCRCTL & 0x0004) >> 2) #define STV_VDP2_N0LSCX ((STV_VDP2_SCRCTL & 0x0002) >> 1) #define STV_VDP2_N0VCSC ((STV_VDP2_SCRCTL & 0x0001) >> 0) /* 18009c - Vertical Cell Table Address (NBG0, NBG1) bit-> /----15----|----14----|----13----|----12----|----11----|----10----|----09----|----08----\ | -- | -- | -- | -- | -- | -- | -- | -- | |----07----|----06----|----05----|----04----|----03----|----02----|----01----|----00----| | -- | -- | -- | -- | -- | -- | -- | -- | \----------|----------|----------|----------|----------|----------|----------|---------*/ #define STV_VDP2_VCSTAU (m_vdp2_regs[0x09c/2] & 7) /* 18009e - Vertical Cell Table Address (NBG0, NBG1) bit-> /----15----|----14----|----13----|----12----|----11----|----10----|----09----|----08----\ | -- | -- | -- | -- | -- | -- | -- | -- | |----07----|----06----|----05----|----04----|----03----|----02----|----01----|----00----| | -- | -- | -- | -- | -- | -- | -- | -- | \----------|----------|----------|----------|----------|----------|----------|---------*/ #define STV_VDP2_VCSTAL (m_vdp2_regs[0x09e/2]) /* 1800a0 - LSTA0U - Line Scroll Table Address (NBG0) bit-> /----15----|----14----|----13----|----12----|----11----|----10----|----09----|----08----\ | -- | -- | -- | -- | -- | -- | -- | -- | |----07----|----06----|----05----|----04----|----03----|----02----|----01----|----00----| | -- | -- | -- | -- | -- | -- | -- | -- | \----------|----------|----------|----------|----------|----------|----------|---------*/ /*bit 2 unused when VRAM = 4 Mbits*/ #define STV_VDP2_LSTA0U (m_vdp2_regs[0x0a0/2] & 7) /* 1800a2 - LSTA0L - Line Scroll Table Address (NBG0) bit-> /----15----|----14----|----13----|----12----|----11----|----10----|----09----|----08----\ | -- | -- | -- | -- | -- | -- | -- | -- | |----07----|----06----|----05----|----04----|----03----|----02----|----01----|----00----| | -- | -- | -- | -- | -- | -- | -- | -- | \----------|----------|----------|----------|----------|----------|----------|---------*/ #define STV_VDP2_LSTA0L (m_vdp2_regs[0x0a2/2]) /* 1800a4 - LSTA1U - Line Scroll Table Address (NBG1) bit-> /----15----|----14----|----13----|----12----|----11----|----10----|----09----|----08----\ | -- | -- | -- | -- | -- | -- | -- | -- | |----07----|----06----|----05----|----04----|----03----|----02----|----01----|----00----| | -- | -- | -- | -- | -- | -- | -- | -- | \----------|----------|----------|----------|----------|----------|----------|---------*/ /*bit 2 unused when VRAM = 4 Mbits*/ #define STV_VDP2_LSTA1U (m_vdp2_regs[0x0a4/2] & 7) /* 1800a6 - LSTA1L - Line Scroll Table Address (NBG1) bit-> /----15----|----14----|----13----|----12----|----11----|----10----|----09----|----08----\ | -- | -- | -- | -- | -- | -- | -- | -- | |----07----|----06----|----05----|----04----|----03----|----02----|----01----|----00----| | -- | -- | -- | -- | -- | -- | -- | -- | \----------|----------|----------|----------|----------|----------|----------|---------*/ #define STV_VDP2_LSTA1L (m_vdp2_regs[0x0a6/2]) /* 1800a8 - LCTAU - Line Colour Screen Table Address bit-> /----15----|----14----|----13----|----12----|----11----|----10----|----09----|----08----\ | -- | -- | -- | -- | -- | -- | -- | -- | |----07----|----06----|----05----|----04----|----03----|----02----|----01----|----00----| | -- | -- | -- | -- | -- | -- | -- | -- | \----------|----------|----------|----------|----------|----------|----------|---------*/ #define STV_VDP2_LCTAU (m_vdp2_regs[0x0a8/2]) #define STV_VDP2_LCCLMD ((STV_VDP2_LCTAU & 0x8000) >> 15) /* 1800aa - LCTAL - Line Colour Screen Table Address bit-> /----15----|----14----|----13----|----12----|----11----|----10----|----09----|----08----\ | -- | -- | -- | -- | -- | -- | -- | -- | |----07----|----06----|----05----|----04----|----03----|----02----|----01----|----00----| | -- | -- | -- | -- | -- | -- | -- | -- | \----------|----------|----------|----------|----------|----------|----------|---------*/ #define STV_VDP2_LCTAL (m_vdp2_regs[0x0aa/2]) #define STV_VDP2_LCTA (((STV_VDP2_LCTAU & 0x0007) << 16) | (STV_VDP2_LCTAL & 0xffff)) /* 1800ac - Back Screen Table Address bit-> /----15----|----14----|----13----|----12----|----11----|----10----|----09----|----08----\ | BKCLMD | -- | -- | -- | -- | -- | -- | -- | |----07----|----06----|----05----|----04----|----03----|----02----|----01----|----00----| | -- | -- | -- | -- | -- | BKTA18 | BKTA17 | BKTA16 | \----------|----------|----------|----------|----------|----------|----------|---------*/ #define STV_VDP2_BKTAU (m_vdp2_regs[0x0ac/2]) #define STV_VDP2_BKCLMD ((STV_VDP2_BKTAU & 0x8000) >> 15) /* 1800ae - Back Screen Table Address bit-> /----15----|----14----|----13----|----12----|----11----|----10----|----09----|----08----\ | BKTA15 | BKTA14 | BKTA13 | BKTA12 | BKTA11 | BKTA10 | BKTA9 | BKTA8 | |----07----|----06----|----05----|----04----|----03----|----02----|----01----|----00----| | BKTA7 | BKTA7 | BKTA6 | BKTA5 | BKTA4 | BKTA3 | BKTA2 | BKTA0 | \----------|----------|----------|----------|----------|----------|----------|---------*/ #define STV_VDP2_BKTAL (m_vdp2_regs[0x0ae/2]) #define STV_VDP2_BKTA (((STV_VDP2_BKTAU & 0x0007) << 16) | (STV_VDP2_BKTAL & 0xffff)) /* 1800b0 - RPMD - Rotation Parameter Mode bit-> /----15----|----14----|----13----|----12----|----11----|----10----|----09----|----08----\ | -- | -- | -- | -- | -- | -- | -- | -- | |----07----|----06----|----05----|----04----|----03----|----02----|----01----|----00----| | -- | -- | -- | -- | -- | -- | -- | -- | \----------|----------|----------|----------|----------|----------|----------|---------*/ #define STV_VDP2_RPMD ((m_vdp2_regs[0x0b0/2]) & 0x0003) /* 1800b2 - RPRCTL - Rotation Parameter Read Control bit-> /----15----|----14----|----13----|----12----|----11----|----10----|----09----|----08----\ | -- | -- | -- | -- | -- | RBKASTRE | RBYSTRE | RBXSTRE | |----07----|----06----|----05----|----04----|----03----|----02----|----01----|----00----| | -- | -- | -- | -- | -- | RAKASTRE | RAYSTRE | RBXSTRE | \----------|----------|----------|----------|----------|----------|----------|---------*/ #define STV_VDP2_RPRCTL (m_vdp2_regs[0x0b2/2]) #define STV_VDP2_RBKASTRE ((STV_VDP2_RPRCTL & 0x0400) >> 10) #define STV_VDP2_RBYSTRE ((STV_VDP2_RPRCTL & 0x0200) >> 9) #define STV_VDP2_RBXSTRE ((STV_VDP2_RPRCTL & 0x0100) >> 8) #define STV_VDP2_RAKASTRE ((STV_VDP2_RPRCTL & 0x0004) >> 2) #define STV_VDP2_RAYSTRE ((STV_VDP2_RPRCTL & 0x0002) >> 1) #define STV_VDP2_RAXSTRE ((STV_VDP2_RPRCTL & 0x0001) >> 0) /* 1800b4 - KTCTL - Coefficient Table Control bit-> /----15----|----14----|----13----|----12----|----11----|----10----|----09----|----08----\ | -- | -- | -- | RBKLCE | RBKMD1 | RBKMD0 | RBKDBS | RBKTE | |----07----|----06----|----05----|----04----|----03----|----02----|----01----|----00----| | -- | -- | -- | RAKLCE | RAKMD1 | RAKMD0 | RAKDBS | RAKTE | \----------|----------|----------|----------|----------|----------|----------|---------*/ #define STV_VDP2_KTCTL (m_vdp2_regs[0x0b4/2]) #define STV_VDP2_RBKLCE ((STV_VDP2_KTCTL & 0x1000) >> 12) #define STV_VDP2_RBKMD ((STV_VDP2_KTCTL & 0x0c00) >> 10) #define STV_VDP2_RBKDBS ((STV_VDP2_KTCTL & 0x0200) >> 9) #define STV_VDP2_RBKTE ((STV_VDP2_KTCTL & 0x0100) >> 8) #define STV_VDP2_RAKLCE ((STV_VDP2_KTCTL & 0x0010) >> 4) #define STV_VDP2_RAKMD ((STV_VDP2_KTCTL & 0x000c) >> 2) #define STV_VDP2_RAKDBS ((STV_VDP2_KTCTL & 0x0002) >> 1) #define STV_VDP2_RAKTE ((STV_VDP2_KTCTL & 0x0001) >> 0) /* 1800b6 - KTAOF - Coefficient Table Address Offset (Rotation Parameter A,B) bit-> /----15----|----14----|----13----|----12----|----11----|----10----|----09----|----08----\ | -- | -- | -- | -- | -- | RBKTAOS2 | RBKTAOS1 | RBKTAOS0 | |----07----|----06----|----05----|----04----|----03----|----02----|----01----|----00----| | -- | -- | -- | -- | -- | RAKTAOS2 | RAKTAOS1 | RAKTAOS0 | \----------|----------|----------|----------|----------|----------|----------|---------*/ #define STV_VDP2_KTAOF (m_vdp2_regs[0x0b6/2]) #define STV_VDP2_RBKTAOS ((STV_VDP2_KTAOF & 0x0700) >> 8) #define STV_VDP2_RAKTAOS ((STV_VDP2_KTAOF & 0x0007) >> 0) /* 1800b8 - OVPNRA - Screen Over Pattern Name (Rotation Parameter A) bit-> /----15----|----14----|----13----|----12----|----11----|----10----|----09----|----08----\ | -- | -- | -- | -- | -- | -- | -- | -- | |----07----|----06----|----05----|----04----|----03----|----02----|----01----|----00----| | -- | -- | -- | -- | -- | -- | -- | -- | \----------|----------|----------|----------|----------|----------|----------|---------*/ #define STV_VDP2_OVPNRA (m_vdp2_regs[0x0b8/2]) /* 1800ba - Screen Over Pattern Name (Rotation Parameter B) bit-> /----15----|----14----|----13----|----12----|----11----|----10----|----09----|----08----\ | -- | -- | -- | -- | -- | -- | -- | -- | |----07----|----06----|----05----|----04----|----03----|----02----|----01----|----00----| | -- | -- | -- | -- | -- | -- | -- | -- | \----------|----------|----------|----------|----------|----------|----------|---------*/ #define STV_VDP2_OVPNRB (m_vdp2_regs[0x0ba/2]) /* 1800bc - RPTAU - Rotation Parameter Table Address (Rotation Parameter A,B) bit-> /----15----|----14----|----13----|----12----|----11----|----10----|----09----|----08----\ | -- | -- | -- | -- | -- | -- | -- | -- | |----07----|----06----|----05----|----04----|----03----|----02----|----01----|----00----| | -- | -- | -- | -- | -- | RPTA18 | RPTA17 | RPTA16 | \----------|----------|----------|----------|----------|----------|----------|---------*/ #define STV_VDP2_RPTAU (m_vdp2_regs[0x0bc/2] & 7) /* 1800be - RPTAL - Rotation Parameter Table Address (Rotation Parameter A,B) bit-> /----15----|----14----|----13----|----12----|----11----|----10----|----09----|----08----\ | RPTA15 | RPTA14 | RPTA13 | RPTA12 | RPTA11 | RPTA10 | RPTA9 | RPTA8 | |----07----|----06----|----05----|----04----|----03----|----02----|----01----|----00----| | RPTA7 | RPTA6 | RPTA5 | RPTA4 | RPTA3 | RPTA2 | RPTA1 | -- | \----------|----------|----------|----------|----------|----------|----------|---------*/ #define STV_VDP2_RPTAL (m_vdp2_regs[0x0be/2] & 0x0000ffff) /* 1800c0 - Window Position (W0, Horizontal Start Point) bit-> /----15----|----14----|----13----|----12----|----11----|----10----|----09----|----08----\ | -- | -- | -- | -- | -- | -- | -- | -- | |----07----|----06----|----05----|----04----|----03----|----02----|----01----|----00----| | -- | -- | -- | -- | -- | -- | -- | -- | \----------|----------|----------|----------|----------|----------|----------|---------*/ #define STV_VDP2_WPSX0 (m_vdp2_regs[0x0c0/2]) #define STV_VDP2_W0SX ((STV_VDP2_WPSX0 & 0x03ff) >> 0) /* 1800c2 - Window Position (W0, Vertical Start Point) bit-> /----15----|----14----|----13----|----12----|----11----|----10----|----09----|----08----\ | -- | -- | -- | -- | -- | -- | -- | -- | |----07----|----06----|----05----|----04----|----03----|----02----|----01----|----00----| | -- | -- | -- | -- | -- | -- | -- | -- | \----------|----------|----------|----------|----------|----------|----------|---------*/ #define STV_VDP2_WPSY0 (m_vdp2_regs[0x0c2/2]) #define STV_VDP2_W0SY ((STV_VDP2_WPSY0 & 0x03ff) >> 0) /* 1800c4 - Window Position (W0, Horizontal End Point) bit-> /----15----|----14----|----13----|----12----|----11----|----10----|----09----|----08----\ | -- | -- | -- | -- | -- | -- | -- | -- | |----07----|----06----|----05----|----04----|----03----|----02----|----01----|----00----| | -- | -- | -- | -- | -- | -- | -- | -- | \----------|----------|----------|----------|----------|----------|----------|---------*/ #define STV_VDP2_WPEX0 (m_vdp2_regs[0x0c4/2]) #define STV_VDP2_W0EX ((STV_VDP2_WPEX0 & 0x03ff) >> 0) /* 1800c6 - Window Position (W0, Vertical End Point) bit-> /----15----|----14----|----13----|----12----|----11----|----10----|----09----|----08----\ | -- | -- | -- | -- | -- | -- | -- | -- | |----07----|----06----|----05----|----04----|----03----|----02----|----01----|----00----| | -- | -- | -- | -- | -- | -- | -- | -- | \----------|----------|----------|----------|----------|----------|----------|---------*/ #define STV_VDP2_WPEY0 (m_vdp2_regs[0x0c6/2]) #define STV_VDP2_W0EY ((STV_VDP2_WPEY0 & 0x03ff) >> 0) /* 1800c8 - Window Position (W1, Horizontal Start Point) bit-> /----15----|----14----|----13----|----12----|----11----|----10----|----09----|----08----\ | -- | -- | -- | -- | -- | -- | -- | -- | |----07----|----06----|----05----|----04----|----03----|----02----|----01----|----00----| | -- | -- | -- | -- | -- | -- | -- | -- | \----------|----------|----------|----------|----------|----------|----------|---------*/ #define STV_VDP2_WPSX1 (m_vdp2_regs[0x0c8/2]) #define STV_VDP2_W1SX ((STV_VDP2_WPSX1 & 0x03ff) >> 0) /* 1800ca - Window Position (W1, Vertical Start Point) bit-> /----15----|----14----|----13----|----12----|----11----|----10----|----09----|----08----\ | -- | -- | -- | -- | -- | -- | -- | -- | |----07----|----06----|----05----|----04----|----03----|----02----|----01----|----00----| | -- | -- | -- | -- | -- | -- | -- | -- | \----------|----------|----------|----------|----------|----------|----------|---------*/ #define STV_VDP2_WPSY1 (m_vdp2_regs[0x0ca/2]) #define STV_VDP2_W1SY ((STV_VDP2_WPSY1 & 0x03ff) >> 0) /* 1800cc - Window Position (W1, Horizontal End Point) bit-> /----15----|----14----|----13----|----12----|----11----|----10----|----09----|----08----\ | -- | -- | -- | -- | -- | -- | -- | -- | |----07----|----06----|----05----|----04----|----03----|----02----|----01----|----00----| | -- | -- | -- | -- | -- | -- | -- | -- | \----------|----------|----------|----------|----------|----------|----------|---------*/ #define STV_VDP2_WPEX1 (m_vdp2_regs[0x0cc/2]) #define STV_VDP2_W1EX ((STV_VDP2_WPEX1 & 0x03ff) >> 0) /* 1800ce - Window Position (W1, Vertical End Point) bit-> /----15----|----14----|----13----|----12----|----11----|----10----|----09----|----08----\ | -- | -- | -- | -- | -- | -- | -- | -- | |----07----|----06----|----05----|----04----|----03----|----02----|----01----|----00----| | -- | -- | -- | -- | -- | -- | -- | -- | \----------|----------|----------|----------|----------|----------|----------|---------*/ #define STV_VDP2_WPEY1 (m_vdp2_regs[0x0ce/2]) #define STV_VDP2_W1EY ((STV_VDP2_WPEY1 & 0x03ff) >> 0) /* 1800d0 - Window Control (NBG0, NBG1) bit-> /----15----|----14----|----13----|----12----|----11----|----10----|----09----|----08----\ | -- | -- | -- | -- | -- | -- | -- | -- | |----07----|----06----|----05----|----04----|----03----|----02----|----01----|----00----| | -- | -- | -- | -- | -- | -- | -- | -- | \----------|----------|----------|----------|----------|----------|----------|---------*/ #define STV_VDP2_WCTLA (m_vdp2_regs[0x0d0/2]) #define STV_VDP2_N1LOG ((STV_VDP2_WCTLA & 0x8000) >> 15) #define STV_VDP2_N1SWE ((STV_VDP2_WCTLA & 0x2000) >> 13) #define STV_VDP2_N1SWA ((STV_VDP2_WCTLA & 0x1000) >> 12) #define STV_VDP2_N1W1E ((STV_VDP2_WCTLA & 0x0800) >> 11) #define STV_VDP2_N1W1A ((STV_VDP2_WCTLA & 0x0400) >> 10) #define STV_VDP2_N1W0E ((STV_VDP2_WCTLA & 0x0200) >> 9) #define STV_VDP2_N1W0A ((STV_VDP2_WCTLA & 0x0100) >> 8) #define STV_VDP2_N0LOG ((STV_VDP2_WCTLA & 0x0080) >> 7) #define STV_VDP2_N0SWE ((STV_VDP2_WCTLA & 0x0020) >> 5) #define STV_VDP2_N0SWA ((STV_VDP2_WCTLA & 0x0010) >> 4) #define STV_VDP2_N0W1E ((STV_VDP2_WCTLA & 0x0008) >> 3) #define STV_VDP2_N0W1A ((STV_VDP2_WCTLA & 0x0004) >> 2) #define STV_VDP2_N0W0E ((STV_VDP2_WCTLA & 0x0002) >> 1) #define STV_VDP2_N0W0A ((STV_VDP2_WCTLA & 0x0001) >> 0) /* 1800d2 - Window Control (NBG2, NBG3) bit-> /----15----|----14----|----13----|----12----|----11----|----10----|----09----|----08----\ | -- | -- | -- | -- | -- | -- | -- | -- | |----07----|----06----|----05----|----04----|----03----|----02----|----01----|----00----| | -- | -- | -- | -- | -- | -- | -- | -- | \----------|----------|----------|----------|----------|----------|----------|---------*/ #define STV_VDP2_WCTLB (m_vdp2_regs[0x0d2/2]) #define STV_VDP2_N3LOG ((STV_VDP2_WCTLB & 0x8000) >> 15) #define STV_VDP2_N3SWE ((STV_VDP2_WCTLB & 0x2000) >> 13) #define STV_VDP2_N3SWA ((STV_VDP2_WCTLB & 0x1000) >> 12) #define STV_VDP2_N3W1E ((STV_VDP2_WCTLB & 0x0800) >> 11) #define STV_VDP2_N3W1A ((STV_VDP2_WCTLB & 0x0400) >> 10) #define STV_VDP2_N3W0E ((STV_VDP2_WCTLB & 0x0200) >> 9) #define STV_VDP2_N3W0A ((STV_VDP2_WCTLB & 0x0100) >> 8) #define STV_VDP2_N2LOG ((STV_VDP2_WCTLB & 0x0080) >> 7) #define STV_VDP2_N2SWE ((STV_VDP2_WCTLB & 0x0020) >> 5) #define STV_VDP2_N2SWA ((STV_VDP2_WCTLB & 0x0010) >> 4) #define STV_VDP2_N2W1E ((STV_VDP2_WCTLB & 0x0008) >> 3) #define STV_VDP2_N2W1A ((STV_VDP2_WCTLB & 0x0004) >> 2) #define STV_VDP2_N2W0E ((STV_VDP2_WCTLB & 0x0002) >> 1) #define STV_VDP2_N2W0A ((STV_VDP2_WCTLB & 0x0001) >> 0) /* 1800d4 - Window Control (RBG0, Sprite) bit-> /----15----|----14----|----13----|----12----|----11----|----10----|----09----|----08----\ | -- | -- | -- | -- | -- | -- | -- | -- | |----07----|----06----|----05----|----04----|----03----|----02----|----01----|----00----| | -- | -- | -- | -- | -- | -- | -- | -- | \----------|----------|----------|----------|----------|----------|----------|---------*/ #define STV_VDP2_WCTLC (m_vdp2_regs[0x0d4/2]) #define STV_VDP2_SPLOG ((STV_VDP2_WCTLC & 0x8000) >> 15) #define STV_VDP2_SPSWE ((STV_VDP2_WCTLC & 0x2000) >> 13) #define STV_VDP2_SPSWA ((STV_VDP2_WCTLC & 0x1000) >> 12) #define STV_VDP2_SPW1E ((STV_VDP2_WCTLC & 0x0800) >> 11) #define STV_VDP2_SPW1A ((STV_VDP2_WCTLC & 0x0400) >> 10) #define STV_VDP2_SPW0E ((STV_VDP2_WCTLC & 0x0200) >> 9) #define STV_VDP2_SPW0A ((STV_VDP2_WCTLC & 0x0100) >> 8) #define STV_VDP2_R0LOG ((STV_VDP2_WCTLC & 0x0080) >> 7) #define STV_VDP2_R0SWE ((STV_VDP2_WCTLC & 0x0020) >> 5) #define STV_VDP2_R0SWA ((STV_VDP2_WCTLC & 0x0010) >> 4) #define STV_VDP2_R0W1E ((STV_VDP2_WCTLC & 0x0008) >> 3) #define STV_VDP2_R0W1A ((STV_VDP2_WCTLC & 0x0004) >> 2) #define STV_VDP2_R0W0E ((STV_VDP2_WCTLC & 0x0002) >> 1) #define STV_VDP2_R0W0A ((STV_VDP2_WCTLC & 0x0001) >> 0) /* 1800d6 - Window Control (Parameter Window, Colour Calc. Window) bit-> /----15----|----14----|----13----|----12----|----11----|----10----|----09----|----08----\ | -- | -- | -- | -- | -- | -- | -- | -- | |----07----|----06----|----05----|----04----|----03----|----02----|----01----|----00----| | -- | -- | -- | -- | -- | -- | -- | -- | \----------|----------|----------|----------|----------|----------|----------|---------*/ #define STV_VDP2_WCTLD (m_vdp2_regs[0x0d6/2]) #define STV_VDP2_CCLOG ((STV_VDP2_WCTLD & 0x8000) >> 15) #define STV_VDP2_CCSWE ((STV_VDP2_WCTLD & 0x2000) >> 13) #define STV_VDP2_CCSWA ((STV_VDP2_WCTLD & 0x1000) >> 12) #define STV_VDP2_CCW1E ((STV_VDP2_WCTLD & 0x0800) >> 11) #define STV_VDP2_CCW1A ((STV_VDP2_WCTLD & 0x0400) >> 10) #define STV_VDP2_CCW0E ((STV_VDP2_WCTLD & 0x0200) >> 9) #define STV_VDP2_CCW0A ((STV_VDP2_WCTLD & 0x0100) >> 8) #define STV_VDP2_RPLOG ((STV_VDP2_WCTLD & 0x0080) >> 7) #define STV_VDP2_RPW1E ((STV_VDP2_WCTLD & 0x0008) >> 3) #define STV_VDP2_RPW1A ((STV_VDP2_WCTLD & 0x0004) >> 2) #define STV_VDP2_RPW0E ((STV_VDP2_WCTLD & 0x0002) >> 1) #define STV_VDP2_RPW0A ((STV_VDP2_WCTLD & 0x0001) >> 0) /* 1800d8 - Line Window Table Address (W0) bit-> /----15----|----14----|----13----|----12----|----11----|----10----|----09----|----08----\ | -- | -- | -- | -- | -- | -- | -- | -- | |----07----|----06----|----05----|----04----|----03----|----02----|----01----|----00----| | -- | -- | -- | -- | -- | -- | -- | -- | \----------|----------|----------|----------|----------|----------|----------|---------*/ #define STV_VDP2_LWTA0U (m_vdp2_regs[0x0d8/2]) #define STV_VDP2_W0LWE ((STV_VDP2_LWTA0U & 0x8000) >> 15) /* 1800da - Line Window Table Address (W0) bit-> /----15----|----14----|----13----|----12----|----11----|----10----|----09----|----08----\ | -- | -- | -- | -- | -- | -- | -- | -- | |----07----|----06----|----05----|----04----|----03----|----02----|----01----|----00----| | -- | -- | -- | -- | -- | -- | -- | -- | \----------|----------|----------|----------|----------|----------|----------|---------*/ #define STV_VDP2_LWTA0L (m_vdp2_regs[0x0da/2]) /* bit 19 isn't used when VRAM = 4 Mbit */ #define STV_VDP2_W0LWTA (((STV_VDP2_LWTA0U & 0x0007) << 16) | (STV_VDP2_LWTA0L & 0xfffe)) /* 1800dc - Line Window Table Address (W1) bit-> /----15----|----14----|----13----|----12----|----11----|----10----|----09----|----08----\ | -- | -- | -- | -- | -- | -- | -- | -- | |----07----|----06----|----05----|----04----|----03----|----02----|----01----|----00----| | -- | -- | -- | -- | -- | -- | -- | -- | \----------|----------|----------|----------|----------|----------|----------|---------*/ #define STV_VDP2_LWTA1U (m_vdp2_regs[0x0dc/2]) #define STV_VDP2_W1LWE ((STV_VDP2_LWTA1U & 0x8000) >> 15) /* 1800de - Line Window Table Address (W1) bit-> /----15----|----14----|----13----|----12----|----11----|----10----|----09----|----08----\ | -- | -- | -- | -- | -- | -- | -- | -- | |----07----|----06----|----05----|----04----|----03----|----02----|----01----|----00----| | -- | -- | -- | -- | -- | -- | -- | -- | \----------|----------|----------|----------|----------|----------|----------|---------*/ #define STV_VDP2_LWTA1L (m_vdp2_regs[0x0de/2]) /* bit 19 isn't used when VRAM = 4 Mbit */ #define STV_VDP2_W1LWTA (((STV_VDP2_LWTA1U & 0x0007) << 16) | (STV_VDP2_LWTA1L & 0xfffe)) /* 1800e0 - Sprite Control bit-> /----15----|----14----|----13----|----12----|----11----|----10----|----09----|----08----\ | -- | -- | SPCCCS1 | SPCCCS0 | -- | SPCCN2 | SPCCN1 | SPCCN0 | |----07----|----06----|----05----|----04----|----03----|----02----|----01----|----00----| | -- | -- | SPCLMD | SPWINEN | SPTYPE3 | SPTYPE2 | SPTYPE1 | SPTYPE0 | \----------|----------|----------|----------|----------|----------|----------|---------*/ #define STV_VDP2_SPCTL (m_vdp2_regs[0xe0/2]) #define STV_VDP2_SPCCCS ((STV_VDP2_SPCTL & 0x3000) >> 12) #define STV_VDP2_SPCCN ((STV_VDP2_SPCTL & 0x700) >> 8) #define STV_VDP2_SPCLMD ((STV_VDP2_SPCTL & 0x20) >> 5) #define STV_VDP2_SPWINEN ((STV_VDP2_SPCTL & 0x10) >> 4) #define STV_VDP2_SPTYPE (STV_VDP2_SPCTL & 0xf) /* 1800e2 - Shadow Control bit-> /----15----|----14----|----13----|----12----|----11----|----10----|----09----|----08----\ | -- | -- | -- | -- | -- | -- | -- | -- | |----07----|----06----|----05----|----04----|----03----|----02----|----01----|----00----| | -- | -- | -- | -- | -- | -- | -- | -- | \----------|----------|----------|----------|----------|----------|----------|---------*/ #define STV_VDP2_SDCTL (m_vdp2_regs[0x0e2/2]) /* 1800e4 - CRAOFA - Colour Ram Address Offset (NBG0 - NBG3) bit-> /----15----|----14----|----13----|----12----|----11----|----10----|----09----|----08----\ | -- | N0CAOS2 | N3CAOS1 | N3CAOS0 | -- | N2CAOS2 | N2CAOS1 | N2CAOS0 | |----07----|----06----|----05----|----04----|----03----|----02----|----01----|----00----| | -- | N1CAOS2 | N1CAOS1 | N1CAOS0 | -- | N0CAOS2 | N0CAOS1 | N0CAOS0 | \----------|----------|----------|----------|----------|----------|----------|---------*/ #define STV_VDP2_CRAOFA (m_vdp2_regs[0x0e4/2]) /* NxCAOS = */ #define STV_VDP2_N0CAOS ((STV_VDP2_CRAOFA & 0x0007) >> 0) #define STV_VDP2_N1CAOS ((STV_VDP2_CRAOFA & 0x0070) >> 4) #define STV_VDP2_N2CAOS ((STV_VDP2_CRAOFA & 0x0700) >> 8) #define STV_VDP2_N3CAOS ((STV_VDP2_CRAOFA & 0x7000) >> 12) /* 1800e6 - Colour Ram Address Offset (RBG0, SPRITE) bit-> /----15----|----14----|----13----|----12----|----11----|----10----|----09----|----08----\ | -- | -- | -- | -- | -- | -- | -- | -- | |----07----|----06----|----05----|----04----|----03----|----02----|----01----|----00----| | -- | -- | -- | -- | -- | -- | -- | -- | \----------|----------|----------|----------|----------|----------|----------|---------*/ #define STV_VDP2_CRAOFB (m_vdp2_regs[0x0e6/2]) #define STV_VDP2_R0CAOS ((STV_VDP2_CRAOFB & 0x0007) >> 0) #define STV_VDP2_SPCAOS ((STV_VDP2_CRAOFB & 0x0070) >> 4) /* 1800e8 - LNCLEN - Line Colour Screen Enable bit-> /----15----|----14----|----13----|----12----|----11----|----10----|----09----|----08----\ | -- | -- | -- | -- | -- | -- | -- | -- | |----07----|----06----|----05----|----04----|----03----|----02----|----01----|----00----| | -- | -- | SPLCEN | R0LCEN | N3LCEN | N2LCEN | N1LCEN | N0LCEN | \----------|----------|----------|----------|----------|----------|----------|---------*/ #define STV_VDP2_LNCLEN (m_vdp2_regs[0x0e8/2]) #define STV_VDP2_SPLCEN ((STV_VDP2_LNCLEN & 0x0020) >> 5) #define STV_VDP2_R0LCEN ((STV_VDP2_LNCLEN & 0x0010) >> 4) #define STV_VDP2_N3LCEN ((STV_VDP2_LNCLEN & 0x0008) >> 3) #define STV_VDP2_N2LCEN ((STV_VDP2_LNCLEN & 0x0004) >> 2) #define STV_VDP2_N1LCEN ((STV_VDP2_LNCLEN & 0x0002) >> 1) #define STV_VDP2_N0LCEN ((STV_VDP2_LNCLEN & 0x0001) >> 0) /* 1800ea - Special Priority Mode bit-> /----15----|----14----|----13----|----12----|----11----|----10----|----09----|----08----\ | -- | -- | -- | -- | -- | -- | -- | -- | |----07----|----06----|----05----|----04----|----03----|----02----|----01----|----00----| | -- | -- | -- | -- | -- | -- | -- | -- | \----------|----------|----------|----------|----------|----------|----------|---------*/ #define STV_VDP2_SFPRMD (m_vdp2_regs[0x0ea/2]) /* 1800ec - Colour Calculation Control bit-> /----15----|----14----|----13----|----12----|----11----|----10----|----09----|----08----\ | BOKEN | BOKN2 | BOKN1 | BOKN0 | -- | EXCCEN | CCRTMD | CCMD | |----07----|----06----|----05----|----04----|----03----|----02----|----01----|----00----| | -- | SPCCEN | LCCCEN | R0CCEN | N3CCEN | N2CCEN | N1CCEN | N0CCEN | \----------|----------|----------|----------|----------|----------|----------|---------*/ #define STV_VDP2_CCCR (m_vdp2_regs[0x0ec/2]) #define STV_VDP2_CCMD ((STV_VDP2_CCCR & 0x100) >> 8) #define STV_VDP2_SPCCEN ((STV_VDP2_CCCR & 0x40) >> 6) #define STV_VDP2_LCCCEN ((STV_VDP2_CCCR & 0x20) >> 5) #define STV_VDP2_R0CCEN ((STV_VDP2_CCCR & 0x10) >> 4) #define STV_VDP2_N3CCEN ((STV_VDP2_CCCR & 0x8) >> 3) #define STV_VDP2_N2CCEN ((STV_VDP2_CCCR & 0x4) >> 2) #define STV_VDP2_N1CCEN ((STV_VDP2_CCCR & 0x2) >> 1) #define STV_VDP2_N0CCEN ((STV_VDP2_CCCR & 0x1) >> 0) /* 1800ee - Special Colour Calculation Mode bit-> /----15----|----14----|----13----|----12----|----11----|----10----|----09----|----08----\ | -- | -- | -- | -- | -- | -- | -- | -- | |----07----|----06----|----05----|----04----|----03----|----02----|----01----|----00----| | -- | -- | -- | -- | -- | -- | -- | -- | \----------|----------|----------|----------|----------|----------|----------|---------*/ #define STV_VDP2_SFCCMD (m_vdp2_regs[0x0ee/2]) /* 1800f0 - Priority Number (Sprite 0,1) bit-> /----15----|----14----|----13----|----12----|----11----|----10----|----09----|----08----\ | -- | -- | -- | -- | -- | S1PRIN2 | S1PRIN1 | S1PRIN0 | |----07----|----06----|----05----|----04----|----03----|----02----|----01----|----00----| | -- | -- | -- | -- | -- | S0PRIN2 | S0PRIN1 | S0PRIN0 | \----------|----------|----------|----------|----------|----------|----------|---------*/ #define STV_VDP2_PRISA (m_vdp2_regs[0x0f0/2]) #define STV_VDP2_S1PRIN ((STV_VDP2_PRISA & 0x0700) >> 8) #define STV_VDP2_S0PRIN ((STV_VDP2_PRISA & 0x0007) >> 0) /* 1800f2 - Priority Number (Sprite 2,3) bit-> /----15----|----14----|----13----|----12----|----11----|----10----|----09----|----08----\ | -- | -- | -- | -- | -- | S3PRIN2 | S3PRIN1 | S3PRIN0 | |----07----|----06----|----05----|----04----|----03----|----02----|----01----|----00----| | -- | -- | -- | -- | -- | S2PRIN2 | S2PRIN1 | S2PRIN0 | \----------|----------|----------|----------|----------|----------|----------|---------*/ #define STV_VDP2_PRISB (m_vdp2_regs[0x0f2/2]) #define STV_VDP2_S3PRIN ((STV_VDP2_PRISB & 0x0700) >> 8) #define STV_VDP2_S2PRIN ((STV_VDP2_PRISB & 0x0007) >> 0) /* 1800f4 - Priority Number (Sprite 4,5) bit-> /----15----|----14----|----13----|----12----|----11----|----10----|----09----|----08----\ | -- | -- | -- | -- | -- | S5PRIN2 | S5PRIN1 | S5PRIN0 | |----07----|----06----|----05----|----04----|----03----|----02----|----01----|----00----| | -- | -- | -- | -- | -- | S4PRIN2 | S4PRIN1 | S4PRIN0 | \----------|----------|----------|----------|----------|----------|----------|---------*/ #define STV_VDP2_PRISC (m_vdp2_regs[0x0f4/2]) #define STV_VDP2_S5PRIN ((STV_VDP2_PRISC & 0x0700) >> 8) #define STV_VDP2_S4PRIN ((STV_VDP2_PRISC & 0x0007) >> 0) /* 1800f6 - Priority Number (Sprite 6,7) bit-> /----15----|----14----|----13----|----12----|----11----|----10----|----09----|----08----\ | -- | -- | -- | -- | -- | S7PRIN2 | S7PRIN1 | S7PRIN0 | |----07----|----06----|----05----|----04----|----03----|----02----|----01----|----00----| | -- | -- | -- | -- | -- | S6PRIN2 | S6PRIN1 | S6PRIN0 | \----------|----------|----------|----------|----------|----------|----------|---------*/ #define STV_VDP2_PRISD (m_vdp2_regs[0x0f6/2]) #define STV_VDP2_S7PRIN ((STV_VDP2_PRISD & 0x0700) >> 8) #define STV_VDP2_S6PRIN ((STV_VDP2_PRISD & 0x0007) >> 0) /* 1800f8 - PRINA - Priority Number (NBG 0,1) bit-> /----15----|----14----|----13----|----12----|----11----|----10----|----09----|----08----\ | -- | -- | -- | -- | -- | -- | -- | -- | |----07----|----06----|----05----|----04----|----03----|----02----|----01----|----00----| | -- | -- | -- | -- | -- | -- | -- | -- | \----------|----------|----------|----------|----------|----------|----------|---------*/ #define STV_VDP2_PRINA (m_vdp2_regs[0x0f8/2]) #define STV_VDP2_N1PRIN ((STV_VDP2_PRINA & 0x0700) >> 8) #define STV_VDP2_N0PRIN ((STV_VDP2_PRINA & 0x0007) >> 0) /* 1800fa - PRINB - Priority Number (NBG 2,3) bit-> /----15----|----14----|----13----|----12----|----11----|----10----|----09----|----08----\ | -- | -- | -- | -- | -- | -- | -- | -- | |----07----|----06----|----05----|----04----|----03----|----02----|----01----|----00----| | -- | -- | -- | -- | -- | -- | -- | -- | \----------|----------|----------|----------|----------|----------|----------|---------*/ #define STV_VDP2_PRINB (m_vdp2_regs[0x0fa/2]) #define STV_VDP2_N3PRIN ((STV_VDP2_PRINB & 0x0700) >> 8) #define STV_VDP2_N2PRIN ((STV_VDP2_PRINB & 0x0007) >> 0) /* 1800fc - Priority Number (RBG0) bit-> /----15----|----14----|----13----|----12----|----11----|----10----|----09----|----08----\ | -- | -- | -- | -- | -- | -- | -- | -- | |----07----|----06----|----05----|----04----|----03----|----02----|----01----|----00----| | -- | -- | -- | -- | -- | -- | -- | -- | \----------|----------|----------|----------|----------|----------|----------|---------*/ #define STV_VDP2_PRIR (m_vdp2_regs[0x0fc/2]) #define STV_VDP2_R0PRIN ((STV_VDP2_PRIR & 0x0007) >> 0) /* 1800fe - Reserved bit-> /----15----|----14----|----13----|----12----|----11----|----10----|----09----|----08----\ | -- | -- | -- | -- | -- | -- | -- | -- | |----07----|----06----|----05----|----04----|----03----|----02----|----01----|----00----| | -- | -- | -- | -- | -- | -- | -- | -- | \----------|----------|----------|----------|----------|----------|----------|---------*/ /* 180100 - Colour Calculation Ratio (Sprite 0,1) bit-> /----15----|----14----|----13----|----12----|----11----|----10----|----09----|----08----\ | -- | -- | -- | S1CCRT4 | S1CCRT3 | S1CCRT2 | S1CCRT1 | S1CCRT0 | |----07----|----06----|----05----|----04----|----03----|----02----|----01----|----00----| | -- | -- | -- | S0CCRT4 | S0CCRT3 | S0CCRT2 | S0CCRT1 | S0CCRT0 | \----------|----------|----------|----------|----------|----------|----------|---------*/ #define STV_VDP2_CCRSA (m_vdp2_regs[0x100/2]) #define STV_VDP2_S1CCRT ((STV_VDP2_CCRSA & 0x1f00) >> 8) #define STV_VDP2_S0CCRT ((STV_VDP2_CCRSA & 0x001f) >> 0) /* 180102 - Colour Calculation Ratio (Sprite 2,3) bit-> /----15----|----14----|----13----|----12----|----11----|----10----|----09----|----08----\ | -- | -- | -- | S3CCRT4 | S3CCRT3 | S3CCRT2 | S3CCRT1 | S3CCRT0 | |----07----|----06----|----05----|----04----|----03----|----02----|----01----|----00----| | -- | -- | -- | S2CCRT4 | S2CCRT3 | S2CCRT2 | S2CCRT1 | S2CCRT0 | \----------|----------|----------|----------|----------|----------|----------|---------*/ #define STV_VDP2_CCRSB (m_vdp2_regs[0x102/2]) #define STV_VDP2_S3CCRT ((STV_VDP2_CCRSB & 0x1f00) >> 8) #define STV_VDP2_S2CCRT ((STV_VDP2_CCRSB & 0x001f) >> 0) /* 180104 - Colour Calculation Ratio (Sprite 4,5) bit-> /----15----|----14----|----13----|----12----|----11----|----10----|----09----|----08----\ | -- | -- | -- | S5CCRT4 | S5CCRT3 | S5CCRT2 | S5CCRT1 | S5CCRT0 | |----07----|----06----|----05----|----04----|----03----|----02----|----01----|----00----| | -- | -- | -- | S4CCRT4 | S4CCRT3 | S4CCRT2 | S4CCRT1 | S4CCRT0 | \----------|----------|----------|----------|----------|----------|----------|---------*/ #define STV_VDP2_CCRSC (m_vdp2_regs[0x104/2]) #define STV_VDP2_S5CCRT ((STV_VDP2_CCRSC & 0x1f00) >> 8) #define STV_VDP2_S4CCRT ((STV_VDP2_CCRSC & 0x001f) >> 0) /* 180106 - Colour Calculation Ratio (Sprite 6,7) bit-> /----15----|----14----|----13----|----12----|----11----|----10----|----09----|----08----\ | -- | -- | -- | S7CCRT4 | S7CCRT3 | S7CCRT2 | S7CCRT1 | S7CCRT0 | |----07----|----06----|----05----|----04----|----03----|----02----|----01----|----00----| | -- | -- | -- | S6CCRT4 | S6CCRT3 | S6CCRT2 | S6CCRT1 | S6CCRT0 | \----------|----------|----------|----------|----------|----------|----------|---------*/ #define STV_VDP2_CCRSD (m_vdp2_regs[0x106/2]) #define STV_VDP2_S7CCRT ((STV_VDP2_CCRSD & 0x1f00) >> 8) #define STV_VDP2_S6CCRT ((STV_VDP2_CCRSD & 0x001f) >> 0) /* 180108 - Colour Calculation Ratio (NBG 0,1) bit-> /----15----|----14----|----13----|----12----|----11----|----10----|----09----|----08----\ | -- | -- | -- | N1CCRT4 | N1CCRT3 | N1CCRT2 | N1CCRT1 | N1CCRT0 | |----07----|----06----|----05----|----04----|----03----|----02----|----01----|----00----| | -- | -- | -- | N0CCRT4 | N0CCRT3 | N0CCRT2 | N0CCRT1 | N0CCRT0 | \----------|----------|----------|----------|----------|----------|----------|---------*/ #define STV_VDP2_CCRNA (m_vdp2_regs[0x108/2]) #define STV_VDP2_N1CCRT ((STV_VDP2_CCRNA & 0x1f00) >> 8) #define STV_VDP2_N0CCRT (STV_VDP2_CCRNA & 0x1f) /* 18010a - Colour Calculation Ratio (NBG 2,3) bit-> /----15----|----14----|----13----|----12----|----11----|----10----|----09----|----08----\ | -- | -- | -- | N3CCRT4 | N3CCRT3 | N3CCRT2 | N3CCRT1 | N3CCRT0 | |----07----|----06----|----05----|----04----|----03----|----02----|----01----|----00----| | -- | -- | -- | N2CCRT4 | N2CCRT3 | N2CCRT2 | N2CCRT1 | N2CCRT0 | \----------|----------|----------|----------|----------|----------|----------|---------*/ #define STV_VDP2_CCRNB (m_vdp2_regs[0x10a/2]) #define STV_VDP2_N3CCRT ((STV_VDP2_CCRNB & 0x1f00) >> 8) #define STV_VDP2_N2CCRT (STV_VDP2_CCRNB & 0x1f) /* 18010c - Colour Calculation Ratio (RBG 0) bit-> /----15----|----14----|----13----|----12----|----11----|----10----|----09----|----08----\ | -- | -- | -- | -- | -- | -- | -- | -- | |----07----|----06----|----05----|----04----|----03----|----02----|----01----|----00----| | -- | -- | -- | -- | -- | -- | -- | -- | \----------|----------|----------|----------|----------|----------|----------|---------*/ #define STV_VDP2_CCRR (m_vdp2_regs[0x10c/2]) #define STV_VDP2_R0CCRT (STV_VDP2_CCRR & 0x1f) /* 18010e - Colour Calculation Ratio (Line Colour Screen, Back Colour Screen) bit-> /----15----|----14----|----13----|----12----|----11----|----10----|----09----|----08----\ | -- | -- | -- | -- | -- | -- | -- | -- | |----07----|----06----|----05----|----04----|----03----|----02----|----01----|----00----| | -- | -- | -- | -- | -- | -- | -- | -- | \----------|----------|----------|----------|----------|----------|----------|---------*/ #define STV_VDP2_CCRLB (m_vdp2_regs[0x10e/2]) /* 180110 - Colour Offset Enable bit-> /----15----|----14----|----13----|----12----|----11----|----10----|----09----|----08----\ | -- | -- | -- | -- | -- | -- | -- | -- | |----07----|----06----|----05----|----04----|----03----|----02----|----01----|----00----| | -- | -- | -- | -- | -- | -- | -- | -- | \----------|----------|----------|----------|----------|----------|----------|---------*/ #define STV_VDP2_CLOFEN (m_vdp2_regs[0x110/2]) #define STV_VDP2_N0COEN ((STV_VDP2_CLOFEN & 0x01) >> 0) #define STV_VDP2_N1COEN ((STV_VDP2_CLOFEN & 0x02) >> 1) #define STV_VDP2_N2COEN ((STV_VDP2_CLOFEN & 0x04) >> 2) #define STV_VDP2_N3COEN ((STV_VDP2_CLOFEN & 0x08) >> 3) #define STV_VDP2_R0COEN ((STV_VDP2_CLOFEN & 0x10) >> 4) #define STV_VDP2_BKCOEN ((STV_VDP2_CLOFEN & 0x20) >> 5) #define STV_VDP2_SPCOEN ((STV_VDP2_CLOFEN & 0x40) >> 6) /* 180112 - Colour Offset Select bit-> /----15----|----14----|----13----|----12----|----11----|----10----|----09----|----08----\ | -- | -- | -- | -- | -- | -- | -- | -- | |----07----|----06----|----05----|----04----|----03----|----02----|----01----|----00----| | -- | -- | -- | -- | -- | -- | -- | -- | \----------|----------|----------|----------|----------|----------|----------|---------*/ #define STV_VDP2_CLOFSL (m_vdp2_regs[0x112/2]) #define STV_VDP2_N0COSL ((STV_VDP2_CLOFSL & 0x01) >> 0) #define STV_VDP2_N1COSL ((STV_VDP2_CLOFSL & 0x02) >> 1) #define STV_VDP2_N2COSL ((STV_VDP2_CLOFSL & 0x04) >> 2) #define STV_VDP2_N3COSL ((STV_VDP2_CLOFSL & 0x08) >> 3) #define STV_VDP2_R0COSL ((STV_VDP2_CLOFSL & 0x10) >> 4) #define STV_VDP2_BKCOSL ((STV_VDP2_CLOFSL & 0x20) >> 5) #define STV_VDP2_SPCOSL ((STV_VDP2_CLOFSL & 0x40) >> 6) /* 180114 - Colour Offset A (Red) bit-> /----15----|----14----|----13----|----12----|----11----|----10----|----09----|----08----\ | -- | -- | -- | -- | -- | -- | -- | -- | |----07----|----06----|----05----|----04----|----03----|----02----|----01----|----00----| | -- | -- | -- | -- | -- | -- | -- | -- | \----------|----------|----------|----------|----------|----------|----------|---------*/ #define STV_VDP2_COAR (m_vdp2_regs[0x114/2]) /* 180116 - Colour Offset A (Green) bit-> /----15----|----14----|----13----|----12----|----11----|----10----|----09----|----08----\ | -- | -- | -- | -- | -- | -- | -- | -- | |----07----|----06----|----05----|----04----|----03----|----02----|----01----|----00----| | -- | -- | -- | -- | -- | -- | -- | -- | \----------|----------|----------|----------|----------|----------|----------|---------*/ #define STV_VDP2_COAG (m_vdp2_regs[0x116/2]) /* 180118 - Colour Offset A (Blue) bit-> /----15----|----14----|----13----|----12----|----11----|----10----|----09----|----08----\ | -- | -- | -- | -- | -- | -- | -- | -- | |----07----|----06----|----05----|----04----|----03----|----02----|----01----|----00----| | -- | -- | -- | -- | -- | -- | -- | -- | \----------|----------|----------|----------|----------|----------|----------|---------*/ #define STV_VDP2_COAB (m_vdp2_regs[0x118/2]) /* 18011a - Colour Offset B (Red) bit-> /----15----|----14----|----13----|----12----|----11----|----10----|----09----|----08----\ | -- | -- | -- | -- | -- | -- | -- | -- | |----07----|----06----|----05----|----04----|----03----|----02----|----01----|----00----| | -- | -- | -- | -- | -- | -- | -- | -- | \----------|----------|----------|----------|----------|----------|----------|---------*/ #define STV_VDP2_COBR (m_vdp2_regs[0x11a/2]) /* 18011c - Colour Offset B (Green) bit-> /----15----|----14----|----13----|----12----|----11----|----10----|----09----|----08----\ | -- | -- | -- | -- | -- | -- | -- | -- | |----07----|----06----|----05----|----04----|----03----|----02----|----01----|----00----| | -- | -- | -- | -- | -- | -- | -- | -- | \----------|----------|----------|----------|----------|----------|----------|---------*/ #define STV_VDP2_COBG (m_vdp2_regs[0x11c/2]) /* 18011e - Colour Offset B (Blue) bit-> /----15----|----14----|----13----|----12----|----11----|----10----|----09----|----08----\ | -- | -- | -- | -- | -- | -- | -- | -- | |----07----|----06----|----05----|----04----|----03----|----02----|----01----|----00----| | -- | -- | -- | -- | -- | -- | -- | -- | \----------|----------|----------|----------|----------|----------|----------|---------*/ #define STV_VDP2_COBB (m_vdp2_regs[0x11e/2]) #define STV_VDP2_RBG_ROTATION_PARAMETER_A 1 #define STV_VDP2_RBG_ROTATION_PARAMETER_B 2 #define mul_fixed32( a, b ) mul_32x32_shift( a, b, 16 ) void saturn_state::stv_vdp2_fill_rotation_parameter_table( uint8_t rot_parameter ) { uint32_t address; address = (((STV_VDP2_RPTAU << 16) | STV_VDP2_RPTAL) << 1); if ( rot_parameter == 1 ) { address &= ~0x00000080; } else if ( rot_parameter == 2 ) { address |= 0x00000080; } stv_current_rotation_parameter_table.xst = (m_vdp2_vram[address/4] & 0x1fffffc0) | ((m_vdp2_vram[address/4] & 0x10000000) ? 0xe0000000 : 0x00000000 ); stv_current_rotation_parameter_table.yst = (m_vdp2_vram[address/4 + 1] & 0x1fffffc0) | ((m_vdp2_vram[address/4 + 1] & 0x10000000) ? 0xe0000000 : 0x00000000 ); stv_current_rotation_parameter_table.zst = (m_vdp2_vram[address/4 + 2] & 0x1fffffc0) | ((m_vdp2_vram[address/4 + 2] & 0x10000000) ? 0xe0000000 : 0x00000000 ); stv_current_rotation_parameter_table.dxst = (m_vdp2_vram[address/4 + 3] & 0x0007ffc0) | ((m_vdp2_vram[address/4 + 3] & 0x00040000) ? 0xfff80000 : 0x00000000 ); stv_current_rotation_parameter_table.dyst = (m_vdp2_vram[address/4 + 4] & 0x0007ffc0) | ((m_vdp2_vram[address/4 + 4] & 0x00040000) ? 0xfff80000 : 0x00000000 ); stv_current_rotation_parameter_table.dx = (m_vdp2_vram[address/4 + 5] & 0x0007ffc0) | ((m_vdp2_vram[address/4 + 5] & 0x00040000) ? 0xfff80000 : 0x00000000 ); stv_current_rotation_parameter_table.dy = (m_vdp2_vram[address/4 + 6] & 0x0007ffc0) | ((m_vdp2_vram[address/4 + 6] & 0x00040000) ? 0xfff80000 : 0x00000000 ); stv_current_rotation_parameter_table.A = (m_vdp2_vram[address/4 + 7] & 0x000fffc0) | ((m_vdp2_vram[address/4 + 7] & 0x00080000) ? 0xfff00000 : 0x00000000 ); stv_current_rotation_parameter_table.B = (m_vdp2_vram[address/4 + 8] & 0x000fffc0) | ((m_vdp2_vram[address/4 + 8] & 0x00080000) ? 0xfff00000 : 0x00000000 ); stv_current_rotation_parameter_table.C = (m_vdp2_vram[address/4 + 9] & 0x000fffc0) | ((m_vdp2_vram[address/4 + 9] & 0x00080000) ? 0xfff00000 : 0x00000000 ); stv_current_rotation_parameter_table.D = (m_vdp2_vram[address/4 + 10] & 0x000fffc0) | ((m_vdp2_vram[address/4 + 10] & 0x00080000) ? 0xfff00000 : 0x00000000 ); stv_current_rotation_parameter_table.E = (m_vdp2_vram[address/4 + 11] & 0x000fffc0) | ((m_vdp2_vram[address/4 + 11] & 0x00080000) ? 0xfff00000 : 0x00000000 ); stv_current_rotation_parameter_table.F = (m_vdp2_vram[address/4 + 12] & 0x000fffc0) | ((m_vdp2_vram[address/4 + 12] & 0x00080000) ? 0xfff00000 : 0x00000000 ); stv_current_rotation_parameter_table.px = (m_vdp2_vram[address/4 + 13] & 0x3fff0000) | ((m_vdp2_vram[address/4 + 13] & 0x30000000) ? 0xc0000000 : 0x00000000 ); stv_current_rotation_parameter_table.py = (m_vdp2_vram[address/4 + 13] & 0x00003fff) << 16; if ( stv_current_rotation_parameter_table.py & 0x20000000 ) stv_current_rotation_parameter_table.py |= 0xc0000000; stv_current_rotation_parameter_table.pz = (m_vdp2_vram[address/4 + 14] & 0x3fff0000) | ((m_vdp2_vram[address/4 + 14] & 0x20000000) ? 0xc0000000 : 0x00000000 ); stv_current_rotation_parameter_table.cx = (m_vdp2_vram[address/4 + 15] & 0x3fff0000) | ((m_vdp2_vram[address/4 + 15] & 0x20000000) ? 0xc0000000 : 0x00000000 ); stv_current_rotation_parameter_table.cy = (m_vdp2_vram[address/4 + 15] & 0x00003fff) << 16; if ( stv_current_rotation_parameter_table.cy & 0x20000000 ) stv_current_rotation_parameter_table.cy |= 0xc0000000; stv_current_rotation_parameter_table.cz = (m_vdp2_vram[address/4 + 16] & 0x3fff0000) | ((m_vdp2_vram[address/4 + 16] & 0x20000000) ? 0xc0000000 : 0x00000000 ); stv_current_rotation_parameter_table.mx = (m_vdp2_vram[address/4 + 17] & 0x3fffffc0) | ((m_vdp2_vram[address/4 + 17] & 0x20000000) ? 0xc0000000 : 0x00000000 ); stv_current_rotation_parameter_table.my = (m_vdp2_vram[address/4 + 18] & 0x3fffffc0) | ((m_vdp2_vram[address/4 + 18] & 0x20000000) ? 0xc0000000 : 0x00000000 ); stv_current_rotation_parameter_table.kx = (m_vdp2_vram[address/4 + 19] & 0x00ffffff) | ((m_vdp2_vram[address/4 + 19] & 0x00800000) ? 0xff000000 : 0x00000000 ); stv_current_rotation_parameter_table.ky = (m_vdp2_vram[address/4 + 20] & 0x00ffffff) | ((m_vdp2_vram[address/4 + 20] & 0x00800000) ? 0xff000000 : 0x00000000 ); stv_current_rotation_parameter_table.kast = (m_vdp2_vram[address/4 + 21] & 0xffffffc0); stv_current_rotation_parameter_table.dkast= (m_vdp2_vram[address/4 + 22] & 0x03ffffc0) | ((m_vdp2_vram[address/4 + 22] & 0x02000000) ? 0xfc000000 : 0x00000000 ); stv_current_rotation_parameter_table.dkax = (m_vdp2_vram[address/4 + 23] & 0x03ffffc0) | ((m_vdp2_vram[address/4 + 23] & 0x02000000) ? 0xfc000000 : 0x00000000 ); // check rotation parameter read control, override if specific bits are disabled // (Batman Forever The Riddler stage relies on this) switch(rot_parameter) { case 1: if(!STV_VDP2_RAXSTRE) stv_current_rotation_parameter_table.xst = 0; if(!STV_VDP2_RAYSTRE) stv_current_rotation_parameter_table.yst = 0; if(!STV_VDP2_RAKASTRE) stv_current_rotation_parameter_table.dkax = 0; break; case 2: if(!STV_VDP2_RBXSTRE) stv_current_rotation_parameter_table.xst = 0; if(!STV_VDP2_RBYSTRE) stv_current_rotation_parameter_table.yst = 0; if(!STV_VDP2_RBKASTRE) stv_current_rotation_parameter_table.dkax = 0; break; } #define RP stv_current_rotation_parameter_table if(LOG_ROZ == 1) logerror( "Rotation parameter table (%d)\n", rot_parameter ); if(LOG_ROZ == 1) logerror( "xst = %x, yst = %x, zst = %x\n", RP.xst, RP.yst, RP.zst ); if(LOG_ROZ == 1) logerror( "dxst = %x, dyst = %x\n", RP.dxst, RP.dyst ); if(LOG_ROZ == 1) logerror( "dx = %x, dy = %x\n", RP.dx, RP.dy ); if(LOG_ROZ == 1) logerror( "A = %x, B = %x, C = %x, D = %x, E = %x, F = %x\n", RP.A, RP.B, RP.C, RP.D, RP.E, RP.F ); if(LOG_ROZ == 1) logerror( "px = %x, py = %x, pz = %x\n", RP.px, RP.py, RP.pz ); if(LOG_ROZ == 1) logerror( "cx = %x, cy = %x, cz = %x\n", RP.cx, RP.cy, RP.cz ); if(LOG_ROZ == 1) logerror( "mx = %x, my = %x\n", RP.mx, RP.my ); if(LOG_ROZ == 1) logerror( "kx = %x, ky = %x\n", RP.kx, RP.ky ); if(LOG_ROZ == 1) logerror( "kast = %x, dkast = %x, dkax = %x\n", RP.kast, RP.dkast, RP.dkax ); /*Attempt to show on screen the rotation table*/ #if 0 if(LOG_ROZ == 2) { if(machine().input().code_pressed_once(JOYCODE_Y_UP_SWITCH)) m_vdpdebug_roz++; if(machine().input().code_pressed_once(JOYCODE_Y_DOWN_SWITCH)) m_vdpdebug_roz--; if(m_vdpdebug_roz > 10) m_vdpdebug_roz = 10; switch(m_vdpdebug_roz) { case 0: popmessage( "Rotation parameter Table (%d)", rot_parameter ); break; case 1: popmessage( "xst = %x, yst = %x, zst = %x", RP.xst, RP.yst, RP.zst ); break; case 2: popmessage( "dxst = %x, dyst = %x", RP.dxst, RP.dyst ); break; case 3: popmessage( "dx = %x, dy = %x", RP.dx, RP.dy ); break; case 4: popmessage( "A = %x, B = %x, C = %x, D = %x, E = %x, F = %x", RP.A, RP.B, RP.C, RP.D, RP.E, RP.F ); break; case 5: popmessage( "px = %x, py = %x, pz = %x", RP.px, RP.py, RP.pz ); break; case 6: popmessage( "cx = %x, cy = %x, cz = %x", RP.cx, RP.cy, RP.cz ); break; case 7: popmessage( "mx = %x, my = %x", RP.mx, RP.my ); break; case 8: popmessage( "kx = %x, ky = %x", RP.kx, RP.ky ); break; case 9: popmessage( "kast = %x, dkast = %x, dkax = %x", RP.kast, RP.dkast, RP.dkax ); break; case 10: break; } } #endif } /* check if RGB layer has rotation applied */ uint8_t saturn_state::stv_vdp2_is_rotation_applied(void) { #define _FIXED_1 (0x00010000) #define _FIXED_0 (0x00000000) if ( RP.A == _FIXED_1 && RP.B == _FIXED_0 && RP.C == _FIXED_0 && RP.D == _FIXED_0 && RP.E == _FIXED_1 && RP.F == _FIXED_0 && RP.dxst == _FIXED_0 && RP.dyst == _FIXED_1 && RP.dx == _FIXED_1 && RP.dy == _FIXED_0 && RP.kx == _FIXED_1 && RP.ky == _FIXED_1 ) { return 0; } else { return 1; } } uint8_t saturn_state::stv_vdp2_are_map_registers_equal(void) { int i; for ( i = 1; i < stv2_current_tilemap.map_count; i++ ) { if ( stv2_current_tilemap.map_offset[i] != stv2_current_tilemap.map_offset[0] ) { return 0; } } return 1; } void saturn_state::stv_vdp2_check_fade_control_for_layer( void ) { if ( stv2_current_tilemap.fade_control & 1 ) { if ( stv2_current_tilemap.fade_control & 2 ) { if ((STV_VDP2_COBR & 0x1ff) == 0 && (STV_VDP2_COBG & 0x1ff) == 0 && (STV_VDP2_COBB & 0x1ff) == 0 ) { stv2_current_tilemap.fade_control = 0; } } else { if ((STV_VDP2_COAR & 0x1ff) == 0 && (STV_VDP2_COAG & 0x1ff) == 0 && (STV_VDP2_COAB & 0x1ff) == 0 ) { stv2_current_tilemap.fade_control = 0; } } } } #define STV_VDP2_CP_NBG0_PNMDR 0x0 #define STV_VDP2_CP_NBG1_PNMDR 0x1 #define STV_VDP2_CP_NBG2_PNMDR 0x2 #define STV_VDP2_CP_NBG3_PNMDR 0x3 #define STV_VDP2_CP_NBG0_CPDR 0x4 #define STV_VDP2_CP_NBG1_CPDR 0x5 #define STV_VDP2_CP_NBG2_CPDR 0x6 #define STV_VDP2_CP_NBG3_CPDR 0x7 uint8_t saturn_state::stv_vdp2_check_vram_cycle_pattern_registers( uint8_t access_command_pnmdr, uint8_t access_command_cpdr, uint8_t bitmap_enable ) { int i; uint8_t access_command_ok = 0; uint16_t cp_regs[8]; cp_regs[0] = STV_VDP2_CYCA0L; cp_regs[1] = STV_VDP2_CYCA0U; cp_regs[2] = STV_VDP2_CYCA1L; cp_regs[3] = STV_VDP2_CYCA1U; cp_regs[4] = STV_VDP2_CYCA2L; cp_regs[5] = STV_VDP2_CYCA2U; cp_regs[6] = STV_VDP2_CYCA3L; cp_regs[7] = STV_VDP2_CYCA3U; if ( bitmap_enable ) access_command_ok = 1; for ( i = 0; i < 8; i++ ) { if ( ((cp_regs[i] >> 12) & 0xf) == access_command_pnmdr ) { access_command_ok |= 1; } if ( ((cp_regs[i] >> 12) & 0xf) == access_command_cpdr ) { access_command_ok |= 2; } if ( ((cp_regs[i] >> 8) & 0xf) == access_command_pnmdr ) { access_command_ok |= 1; } if ( ((cp_regs[i] >> 8) & 0xf) == access_command_cpdr ) { access_command_ok |= 2; } if ( ((cp_regs[i] >> 4) & 0xf) == access_command_pnmdr ) { access_command_ok |= 1; } if ( ((cp_regs[i] >> 4) & 0xf) == access_command_cpdr ) { access_command_ok |= 2; } if ( ((cp_regs[i] >> 0) & 0xf) == access_command_pnmdr ) { access_command_ok |= 1; } if ( ((cp_regs[i] >> 0) & 0xf) == access_command_cpdr ) { access_command_ok |= 2; } } return access_command_ok == 3 ? 1 : 0; } static inline uint32_t stv_add_blend(uint32_t a, uint32_t b) { rgb_t rb = (a & 0xff00ff) + (b & 0xff00ff); rgb_t g = (a & 0x00ff00) + (b & 0x00ff00); return rgb_t((rb & 0x1000000) ? 0xff : rb.r(), (g & 0x0010000) ? 0xff : g.g(), (rb & 0x0000100) ? 0xff : rb.b() ); } void saturn_state::stv_vdp2_compute_color_offset( int *r, int *g, int *b, int cor ) { if ( cor == 0 ) { *r = (STV_VDP2_COAR & 0x100) ? (*r - (0x100 - (STV_VDP2_COAR & 0xff))) : ((STV_VDP2_COAR & 0xff) + *r); *g = (STV_VDP2_COAG & 0x100) ? (*g - (0x100 - (STV_VDP2_COAG & 0xff))) : ((STV_VDP2_COAG & 0xff) + *g); *b = (STV_VDP2_COAB & 0x100) ? (*b - (0x100 - (STV_VDP2_COAB & 0xff))) : ((STV_VDP2_COAB & 0xff) + *b); } else { *r = (STV_VDP2_COBR & 0x100) ? (*r - (0xff - (STV_VDP2_COBR & 0xff))) : ((STV_VDP2_COBR & 0xff) + *r); *g = (STV_VDP2_COBG & 0x100) ? (*g - (0xff - (STV_VDP2_COBG & 0xff))) : ((STV_VDP2_COBG & 0xff) + *g); *b = (STV_VDP2_COBB & 0x100) ? (*b - (0xff - (STV_VDP2_COBB & 0xff))) : ((STV_VDP2_COBB & 0xff) + *b); } if(*r < 0) { *r = 0; } if(*r > 0xff) { *r = 0xff; } if(*g < 0) { *g = 0; } if(*g > 0xff) { *g = 0xff; } if(*b < 0) { *b = 0; } if(*b > 0xff) { *b = 0xff; } } void saturn_state::stv_vdp2_compute_color_offset_UINT32(rgb_t *rgb, int cor) { int _r = rgb->r(); int _g = rgb->g(); int _b = rgb->b(); if ( cor == 0 ) { _r = (STV_VDP2_COAR & 0x100) ? (_r - (0x100 - (STV_VDP2_COAR & 0xff))) : ((STV_VDP2_COAR & 0xff) + _r); _g = (STV_VDP2_COAG & 0x100) ? (_g - (0x100 - (STV_VDP2_COAG & 0xff))) : ((STV_VDP2_COAG & 0xff) + _g); _b = (STV_VDP2_COAB & 0x100) ? (_b - (0x100 - (STV_VDP2_COAB & 0xff))) : ((STV_VDP2_COAB & 0xff) + _b); } else { _r = (STV_VDP2_COBR & 0x100) ? (_r - (0xff - (STV_VDP2_COBR & 0xff))) : ((STV_VDP2_COBR & 0xff) + _r); _g = (STV_VDP2_COBG & 0x100) ? (_g - (0xff - (STV_VDP2_COBG & 0xff))) : ((STV_VDP2_COBG & 0xff) + _g); _b = (STV_VDP2_COBB & 0x100) ? (_b - (0xff - (STV_VDP2_COBB & 0xff))) : ((STV_VDP2_COBB & 0xff) + _b); } if(_r < 0) { _r = 0; } if(_r > 0xff) { _r = 0xff; } if(_g < 0) { _g = 0; } if(_g > 0xff) { _g = 0xff; } if(_b < 0) { _b = 0; } if(_b > 0xff) { _b = 0xff; } *rgb = rgb_t(_r, _g, _b); } void saturn_state::stv_vdp2_drawgfxzoom( bitmap_rgb32 &dest_bmp,const rectangle &clip,gfx_element *gfx, uint32_t code,uint32_t color,int flipx,int flipy,int sx,int sy, int transparency,int transparent_color,int scalex, int scaley, int sprite_screen_width, int sprite_screen_height, int alpha) { rectangle myclip; if (!scalex || !scaley) return; if (gfx->has_pen_usage() && transparency == STV_TRANSPARENCY_PEN) { int transmask; transmask = 1 << (transparent_color & 0xff); if ((gfx->pen_usage(code) & ~transmask) == 0) /* character is totally transparent, no need to draw */ return; else if ((gfx->pen_usage(code) & transmask) == 0) /* character is totally opaque, can disable transparency */ transparency = STV_TRANSPARENCY_NONE; } /* scalex and scaley are 16.16 fixed point numbers 1<<15 : shrink to 50% 1<<16 : uniform scale 1<<17 : double to 200% */ /* KW 991012 -- Added code to force clip to bitmap boundary */ myclip = clip; myclip &= dest_bmp.cliprect(); if( gfx ) { const pen_t *pal = &m_palette->pen(gfx->colorbase() + gfx->granularity() * (color % gfx->colors())); const uint8_t *source_base = gfx->get_data(code % gfx->elements()); //int sprite_screen_height = (scaley*gfx->height()+0x8000)>>16; //int sprite_screen_width = (scalex*gfx->width()+0x8000)>>16; if (sprite_screen_width && sprite_screen_height) { /* compute sprite increment per screen pixel */ //int dx = (gfx->width()<<16)/sprite_screen_width; //int dy = (gfx->height()<<16)/sprite_screen_height; int dx = stv2_current_tilemap.incx; int dy = stv2_current_tilemap.incy; int ex = sx+sprite_screen_width; int ey = sy+sprite_screen_height; int x_index_base; int y_index; if( flipx ) { x_index_base = (sprite_screen_width-1)*dx; dx = -dx; } else { x_index_base = 0; } if( flipy ) { y_index = (sprite_screen_height-1)*dy; dy = -dy; } else { y_index = 0; } if( sx < myclip.min_x) { /* clip left */ int pixels = myclip.min_x-sx; sx += pixels; x_index_base += pixels*dx; } if( sy < myclip.min_y ) { /* clip top */ int pixels = myclip.min_y-sy; sy += pixels; y_index += pixels*dy; } /* NS 980211 - fixed incorrect clipping */ if( ex > myclip.max_x+1 ) { /* clip right */ int pixels = ex-myclip.max_x-1; ex -= pixels; } if( ey > myclip.max_y+1 ) { /* clip bottom */ int pixels = ey-myclip.max_y-1; ey -= pixels; } if( ex>sx ) { /* skip if inner loop doesn't draw anything */ int y; /* case 0: STV_TRANSPARENCY_NONE */ if (transparency == STV_TRANSPARENCY_NONE) { for( y=sy; y<ey; y++ ) { const uint8_t *source = source_base + (y_index>>16) * gfx->rowbytes(); uint32_t *dest = &dest_bmp.pix32(y); int x, x_index = x_index_base; for( x=sx; x<ex; x++ ) { if(stv_vdp2_window_process(x,y)) dest[x] = pal[source[x_index>>16]]; x_index += dx; } y_index += dy; } } /* case 1: STV_TRANSPARENCY_PEN */ else if (transparency == STV_TRANSPARENCY_PEN) { for( y=sy; y<ey; y++ ) { const uint8_t *source = source_base + (y_index>>16) * gfx->rowbytes(); uint32_t *dest = &dest_bmp.pix32(y); int x, x_index = x_index_base; for( x=sx; x<ex; x++ ) { if(stv_vdp2_window_process(x,y)) { int c = source[x_index>>16]; if( c != transparent_color ) dest[x] = pal[c]; } x_index += dx; } y_index += dy; } } /* case 6: STV_TRANSPARENCY_ALPHA */ else if (transparency == STV_TRANSPARENCY_ALPHA) { for( y=sy; y<ey; y++ ) { const uint8_t *source = source_base + (y_index>>16) * gfx->rowbytes(); uint32_t *dest = &dest_bmp.pix32(y); int x, x_index = x_index_base; for( x=sx; x<ex; x++ ) { if(stv_vdp2_window_process(x,y)) { int c = source[x_index>>16]; if( c != transparent_color ) dest[x] = alpha_blend_r32(dest[x], pal[c], alpha); } x_index += dx; } y_index += dy; } } /* case : STV_TRANSPARENCY_ADD_BLEND */ else if (transparency == STV_TRANSPARENCY_ADD_BLEND ) { for( y=sy; y<ey; y++ ) { const uint8_t *source = source_base + (y_index>>16) * gfx->rowbytes(); uint32_t *dest = &dest_bmp.pix32(y); int x, x_index = x_index_base; for( x=sx; x<ex; x++ ) { if(stv_vdp2_window_process(x,y)) { int c = source[x_index>>16]; if( c != transparent_color ) dest[x] = stv_add_blend(dest[x],pal[c]); } x_index += dx; } y_index += dy; } } } } } } void saturn_state::stv_vdp2_drawgfxzoom_rgb555( bitmap_rgb32 &dest_bmp,const rectangle &clip, uint32_t code,uint32_t color,int flipx,int flipy,int sx,int sy, int transparency,int transparent_color,int scalex, int scaley, int sprite_screen_width, int sprite_screen_height, int alpha) { rectangle myclip; uint8_t* gfxdata; gfxdata = m_vdp2.gfx_decode.get() + code * 0x20; if(stv2_current_tilemap.window_control.enabled[0] || stv2_current_tilemap.window_control.enabled[1]) popmessage("Window Enabled for RGB555 Zoom"); if (!scalex || !scaley) return; #if 0 if (gfx->has_pen_usage() && transparency == STV_TRANSPARENCY_PEN) { int transmask = 0; transmask = 1 << (transparent_color & 0xff); if ((gfx->pen_usage(code) & ~transmask) == 0) /* character is totally transparent, no need to draw */ return; else if ((gfx->pen_usage(code) & transmask) == 0) /* character is totally opaque, can disable transparency */ transparency = STV_TRANSPARENCY_NONE; } #endif /* scalex and scaley are 16.16 fixed point numbers 1<<15 : shrink to 50% 1<<16 : uniform scale 1<<17 : double to 200% */ /* KW 991012 -- Added code to force clip to bitmap boundary */ myclip = clip; myclip &= dest_bmp.cliprect(); // if( gfx ) { // const uint8_t *source_base = gfx->get_data(code % gfx->elements()); //int sprite_screen_height = (scaley*gfx->height()+0x8000)>>16; //int sprite_screen_width = (scalex*gfx->width()+0x8000)>>16; if (sprite_screen_width && sprite_screen_height) { /* compute sprite increment per screen pixel */ //int dx = (gfx->width()<<16)/sprite_screen_width; //int dy = (gfx->height()<<16)/sprite_screen_height; int dx = stv2_current_tilemap.incx; int dy = stv2_current_tilemap.incy; int ex = sx+sprite_screen_width; int ey = sy+sprite_screen_height; int x_index_base; int y_index; if( flipx ) { x_index_base = (sprite_screen_width-1)*dx; dx = -dx; } else { x_index_base = 0; } if( flipy ) { y_index = (sprite_screen_height-1)*dy; dy = -dy; } else { y_index = 0; } if( sx < myclip.min_x) { /* clip left */ int pixels = myclip.min_x-sx; sx += pixels; x_index_base += pixels*dx; } if( sy < myclip.min_y ) { /* clip top */ int pixels = myclip.min_y-sy; sy += pixels; y_index += pixels*dy; } /* NS 980211 - fixed incorrect clipping */ if( ex > myclip.max_x+1 ) { /* clip right */ int pixels = ex-myclip.max_x-1; ex -= pixels; } if( ey > myclip.max_y+1 ) { /* clip bottom */ int pixels = ey-myclip.max_y-1; ey -= pixels; } if( ex>sx ) { /* skip if inner loop doesn't draw anything */ int y; /* case 0: STV_TRANSPARENCY_NONE */ if (transparency == STV_TRANSPARENCY_NONE) { for( y=sy; y<ey; y++ ) { const uint8_t *source = gfxdata + (y_index>>16)*16; uint32_t *dest = &dest_bmp.pix32(y); int r,g,b,data; int x, x_index = x_index_base; for( x=sx; x<ex; x++ ) { data = (source[(x_index>>16)*2] << 8) | source[(x_index>>16)*2+1]; b = pal5bit((data & 0x7c00) >> 10); g = pal5bit((data & 0x03e0) >> 5); r = pal5bit( data & 0x001f); if(stv2_current_tilemap.fade_control & 1) stv_vdp2_compute_color_offset(&r,&g,&b,stv2_current_tilemap.fade_control & 2); dest[x] = rgb_t(r, g, b); x_index += dx; } y_index += dy; } } /* case 1: STV_TRANSPARENCY_PEN */ if (transparency == STV_TRANSPARENCY_PEN) { for( y=sy; y<ey; y++ ) { const uint8_t *source = gfxdata + (y_index>>16)*16; uint32_t *dest = &dest_bmp.pix32(y); int r,g,b,data; int x, x_index = x_index_base; for( x=sx; x<ex; x++ ) { data = (source[(x_index>>16)*2] << 8) | source[(x_index>>16)*2+1]; b = pal5bit((data & 0x7c00) >> 10); g = pal5bit((data & 0x03e0) >> 5); r = pal5bit( data & 0x001f); if(stv2_current_tilemap.fade_control & 1) stv_vdp2_compute_color_offset(&r,&g,&b,stv2_current_tilemap.fade_control & 2); if( data ) dest[x] = rgb_t(r, g, b); x_index += dx; } y_index += dy; } } /* case 6: STV_TRANSPARENCY_ALPHA */ if (transparency == STV_TRANSPARENCY_ALPHA) { for( y=sy; y<ey; y++ ) { const uint8_t *source = gfxdata + (y_index>>16)*16; uint32_t *dest = &dest_bmp.pix32(y); int r,g,b,data; int x, x_index = x_index_base; for( x=sx; x<ex; x++ ) { data = (source[(x_index>>16)*2] << 8) | source[(x_index>>16)*2+1]; b = pal5bit((data & 0x7c00) >> 10); g = pal5bit((data & 0x03e0) >> 5); r = pal5bit( data & 0x001f); if(stv2_current_tilemap.fade_control & 1) stv_vdp2_compute_color_offset(&r,&g,&b,stv2_current_tilemap.fade_control & 2); if( data ) dest[x] = alpha_blend_r32(dest[x], rgb_t(r, g, b), alpha); x_index += dx; } y_index += dy; } } /* case : STV_TRANSPARENCY_ADD_BLEND */ if (transparency == STV_TRANSPARENCY_ADD_BLEND ) { for( y=sy; y<ey; y++ ) { const uint8_t *source = gfxdata + (y_index>>16)*16; uint32_t *dest = &dest_bmp.pix32(y); int r,g,b,data; int x, x_index = x_index_base; for( x=sx; x<ex; x++ ) { data = (source[(x_index*2+0)>>16]<<0)|(source[(x_index*2+1)>>16]<<8); b = pal5bit((data & 0x7c00) >> 10); g = pal5bit((data & 0x03e0) >> 5); r = pal5bit( data & 0x001f); if(stv2_current_tilemap.fade_control & 1) stv_vdp2_compute_color_offset(&r,&g,&b,stv2_current_tilemap.fade_control & 2); if( data ) dest[x] = stv_add_blend(dest[x], rgb_t(r, g, b)); x_index += dx; } y_index += dy; } } } } } } void saturn_state::stv_vdp2_drawgfx_rgb555( bitmap_rgb32 &dest_bmp, const rectangle &clip, uint32_t code, int flipx, int flipy, int sx, int sy, int transparency, int alpha) { rectangle myclip; uint8_t* gfxdata; int sprite_screen_width, sprite_screen_height; gfxdata = m_vdp2.gfx_decode.get() + code * 0x20; sprite_screen_width = sprite_screen_height = 8; if(stv2_current_tilemap.window_control.enabled[0] || stv2_current_tilemap.window_control.enabled[1]) popmessage("Window Enabled for RGB555 tiles"); /* KW 991012 -- Added code to force clip to bitmap boundary */ myclip = clip; myclip &= dest_bmp.cliprect(); { int dx = stv2_current_tilemap.incx; int dy = stv2_current_tilemap.incy; int ex = sx+sprite_screen_width; int ey = sy+sprite_screen_height; int x_index_base; int y_index; if( flipx ) { x_index_base = (sprite_screen_width-1)*dx; dx = -dx; } else { x_index_base = 0; } if( flipy ) { y_index = (sprite_screen_height-1)*dy; dy = -dy; } else { y_index = 0; } if( sx < myclip.min_x) { /* clip left */ int pixels = myclip.min_x-sx; sx += pixels; x_index_base += pixels*dx; } if( sy < myclip.min_y ) { /* clip top */ int pixels = myclip.min_y-sy; sy += pixels; y_index += pixels*dy; } /* NS 980211 - fixed incorrect clipping */ if( ex > myclip.max_x+1 ) { /* clip right */ int pixels = ex-myclip.max_x-1; ex -= pixels; } if( ey > myclip.max_y+1 ) { /* clip bottom */ int pixels = ey-myclip.max_y-1; ey -= pixels; } if( ex>sx ) { /* skip if inner loop doesn't draw anything */ int y; for( y=sy; y<ey; y++ ) { const uint8_t *source = gfxdata + (y_index>>16)*16; uint32_t *dest = &dest_bmp.pix32(y); uint16_t data; int x, x_index = x_index_base; for( x=sx; x<ex; x++ ) { int r,g,b; data = (source[(x_index>>16)*2] << 8) | source[(x_index>>16)*2+1]; if ((data & 0x8000) || (transparency == STV_TRANSPARENCY_NONE)) { b = pal5bit((data & 0x7c00) >> 10); g = pal5bit((data & 0x03e0) >> 5); r = pal5bit( data & 0x001f); if(stv2_current_tilemap.fade_control & 1) stv_vdp2_compute_color_offset(&r,&g,&b,stv2_current_tilemap.fade_control & 2); if ( transparency == STV_TRANSPARENCY_ALPHA ) dest[x] = alpha_blend_r32( dest[x], rgb_t(r, g, b), alpha ); else dest[x] = rgb_t(r, g, b); } x_index += dx; } y_index += dy; } } } } void saturn_state::stv_vdp2_drawgfx_rgb888( bitmap_rgb32 &dest_bmp, const rectangle &clip, uint32_t code, int flipx, int flipy, int sx, int sy, int transparency, int alpha) { rectangle myclip; uint8_t* gfxdata; int sprite_screen_width, sprite_screen_height; gfxdata = m_vdp2.gfx_decode.get() + code * 0x20; sprite_screen_width = sprite_screen_height = 8; if(stv2_current_tilemap.window_control.enabled[0] || stv2_current_tilemap.window_control.enabled[1]) popmessage("Window Enabled for RGB888 tiles"); /* KW 991012 -- Added code to force clip to bitmap boundary */ myclip = clip; myclip &= dest_bmp.cliprect(); { int dx = stv2_current_tilemap.incx; int dy = stv2_current_tilemap.incy; int ex = sx+sprite_screen_width; int ey = sy+sprite_screen_height; int x_index_base; int y_index; if( flipx ) { x_index_base = (sprite_screen_width-1)*dx; dx = -dx; } else { x_index_base = 0; } if( flipy ) { y_index = (sprite_screen_height-1)*dy; dy = -dy; } else { y_index = 0; } if( sx < myclip.min_x) { /* clip left */ int pixels = myclip.min_x-sx; sx += pixels; x_index_base += pixels*dx; } if( sy < myclip.min_y ) { /* clip top */ int pixels = myclip.min_y-sy; sy += pixels; y_index += pixels*dy; } /* NS 980211 - fixed incorrect clipping */ if( ex > myclip.max_x+1 ) { /* clip right */ int pixels = ex-myclip.max_x-1; ex -= pixels; } if( ey > myclip.max_y+1 ) { /* clip bottom */ int pixels = ey-myclip.max_y-1; ey -= pixels; } if( ex>sx ) { /* skip if inner loop doesn't draw anything */ int y; for( y=sy; y<ey; y++ ) { const uint8_t *source = gfxdata + (y_index>>16)*32; uint32_t *dest = &dest_bmp.pix32(y); uint32_t data; int x, x_index = x_index_base; for( x=sx; x<ex; x++ ) { int r,g,b; data = (source[(x_index>>16)*4+0] << 24) | (source[(x_index>>16)*4+1] << 16) | (source[(x_index>>16)*4+2] << 8) | (source[(x_index>>16)*4+3] << 0); if ((data & 0x80000000) || (transparency == STV_TRANSPARENCY_NONE)) { b = (data & 0xff0000) >> 16; g = (data & 0x00ff00) >> 8; r = (data & 0x0000ff); if(stv2_current_tilemap.fade_control & 1) stv_vdp2_compute_color_offset(&r,&g,&b,stv2_current_tilemap.fade_control & 2); if ( transparency == STV_TRANSPARENCY_ALPHA ) dest[x] = alpha_blend_r32( dest[x], rgb_t(r, g, b), alpha ); else dest[x] = rgb_t(r, g, b); } x_index += dx; } y_index += dy; } } } } void saturn_state::stv_vdp2_drawgfx_alpha(bitmap_rgb32 &dest_bmp,const rectangle &clip,gfx_element *gfx, uint32_t code,uint32_t color, int flipx,int flipy,int offsx,int offsy, int transparent_color, int alpha) { const pen_t *pal = &m_palette->pen(gfx->colorbase() + gfx->granularity() * (color % gfx->colors())); const uint8_t *source_base = gfx->get_data(code % gfx->elements()); int x_index_base, y_index, sx, sy, ex, ey; int xinc, yinc; xinc = flipx ? -1 : 1; yinc = flipy ? -1 : 1; x_index_base = flipx ? gfx->width()-1 : 0; y_index = flipy ? gfx->height()-1 : 0; /* start coordinates */ sx = offsx; sy = offsy; /* end coordinates */ ex = sx + gfx->width(); ey = sy + gfx->height(); /* clip left */ if (sx < clip.min_x) { int pixels = clip.min_x-sx; sx += pixels; x_index_base += xinc*pixels; } /* clip top */ if (sy < clip.min_y) { int pixels = clip.min_y-sy; sy += pixels; y_index += yinc*pixels; } /* clip right */ if (ex > clip.max_x+1) { ex = clip.max_x+1; } /* clip bottom */ if (ey > clip.max_y+1) { ey = clip.max_y+1; } /* skip if inner loop doesn't draw anything */ if (ex > sx) { int x, y; { for (y = sy; y < ey; y++) { const uint8_t *source = source_base + y_index*gfx->rowbytes(); uint32_t *dest = &dest_bmp.pix32(y); int x_index = x_index_base; for (x = sx; x < ex; x++) { if(stv_vdp2_window_process(x,y)) { int c = (source[x_index]); if (c != transparent_color) dest[x] = alpha_blend_r32( dest[x], pal[c], alpha );; } x_index += xinc; } y_index += yinc; } } } } void saturn_state::stv_vdp2_drawgfx_transpen(bitmap_rgb32 &dest_bmp,const rectangle &clip,gfx_element *gfx, uint32_t code,uint32_t color, int flipx,int flipy,int offsx,int offsy, int transparent_color) { const pen_t *pal = &m_palette->pen(gfx->colorbase() + gfx->granularity() * (color % gfx->colors())); const uint8_t *source_base = gfx->get_data(code % gfx->elements()); int x_index_base, y_index, sx, sy, ex, ey; int xinc, yinc; xinc = flipx ? -1 : 1; yinc = flipy ? -1 : 1; x_index_base = flipx ? gfx->width()-1 : 0; y_index = flipy ? gfx->height()-1 : 0; /* start coordinates */ sx = offsx; sy = offsy; /* end coordinates */ ex = sx + gfx->width(); ey = sy + gfx->height(); /* clip left */ if (sx < clip.min_x) { int pixels = clip.min_x-sx; sx += pixels; x_index_base += xinc*pixels; } /* clip top */ if (sy < clip.min_y) { int pixels = clip.min_y-sy; sy += pixels; y_index += yinc*pixels; } /* clip right */ if (ex > clip.max_x+1) { ex = clip.max_x+1; } /* clip bottom */ if (ey > clip.max_y+1) { ey = clip.max_y+1; } /* skip if inner loop doesn't draw anything */ if (ex > sx) { int x, y; { for (y = sy; y < ey; y++) { const uint8_t *source = source_base + y_index*gfx->rowbytes(); uint32_t *dest = &dest_bmp.pix32(y); int x_index = x_index_base; for (x = sx; x < ex; x++) { if(stv_vdp2_window_process(x,y)) { int c = (source[x_index]); if (c != transparent_color) dest[x] = pal[c]; } x_index += xinc; } y_index += yinc; } } } } void saturn_state::draw_4bpp_bitmap(bitmap_rgb32 &bitmap, const rectangle &cliprect) { int xsize, ysize, xsize_mask, ysize_mask; int xsrc,ysrc,xdst,ydst; int src_offs; uint8_t* vram = m_vdp2.gfx_decode.get(); uint32_t map_offset = stv2_current_tilemap.bitmap_map * 0x20000; int scrollx = stv2_current_tilemap.scrollx; int scrolly = stv2_current_tilemap.scrolly; uint16_t dot_data; uint16_t pal_bank; xsize = (stv2_current_tilemap.bitmap_size & 2) ? 1024 : 512; ysize = (stv2_current_tilemap.bitmap_size & 1) ? 512 : 256; xsize_mask = (stv2_current_tilemap.linescroll_enable) ? 1024 : xsize; ysize_mask = (stv2_current_tilemap.vertical_linescroll_enable) ? 512 : ysize; pal_bank = stv2_current_tilemap.bitmap_palette_number; pal_bank+= stv2_current_tilemap.colour_ram_address_offset; pal_bank&= 7; pal_bank<<=8; if(stv2_current_tilemap.fade_control & 1) pal_bank += ((stv2_current_tilemap.fade_control & 2) ? (2*2048) : (2048)); for(ydst=cliprect.min_y;ydst<=cliprect.max_y;ydst++) { for(xdst=cliprect.min_x;xdst<=cliprect.max_x;xdst++) { if(!stv_vdp2_window_process(xdst,ydst)) continue; xsrc = (xdst + scrollx) & (xsize_mask-1); ysrc = (ydst + scrolly) & (ysize_mask-1); src_offs = (xsrc + (ysrc*xsize)); src_offs/= 2; src_offs += map_offset; src_offs &= 0x7ffff; dot_data = vram[src_offs] >> ((xsrc & 1) ? 0 : 4); dot_data&= 0xf; if ((dot_data != 0) || (stv2_current_tilemap.transparency == STV_TRANSPARENCY_NONE)) { dot_data += pal_bank; if ( stv2_current_tilemap.colour_calculation_enabled == 0 ) bitmap.pix32(ydst, xdst) = m_palette->pen(dot_data); else bitmap.pix32(ydst, xdst) = alpha_blend_r32(bitmap.pix32(ydst, xdst), m_palette->pen(dot_data), stv2_current_tilemap.alpha); } } } } void saturn_state::draw_8bpp_bitmap(bitmap_rgb32 &bitmap, const rectangle &cliprect) { int xsize, ysize, xsize_mask, ysize_mask; int xsrc,ysrc,xdst,ydst; int src_offs; uint8_t* vram = m_vdp2.gfx_decode.get(); uint32_t map_offset = stv2_current_tilemap.bitmap_map * 0x20000; int scrollx = stv2_current_tilemap.scrollx; int scrolly = stv2_current_tilemap.scrolly; uint16_t dot_data; uint16_t pal_bank; int xf, yf; xsize = (stv2_current_tilemap.bitmap_size & 2) ? 1024 : 512; ysize = (stv2_current_tilemap.bitmap_size & 1) ? 512 : 256; xsize_mask = (stv2_current_tilemap.linescroll_enable) ? 1024 : xsize; ysize_mask = (stv2_current_tilemap.vertical_linescroll_enable) ? 512 : ysize; pal_bank = stv2_current_tilemap.bitmap_palette_number; pal_bank+= stv2_current_tilemap.colour_ram_address_offset; pal_bank&= 7; pal_bank<<=8; if(stv2_current_tilemap.fade_control & 1) pal_bank += ((stv2_current_tilemap.fade_control & 2) ? (2*2048) : (2048)); for(ydst=cliprect.min_y;ydst<=cliprect.max_y;ydst++) { for(xdst=cliprect.min_x;xdst<=cliprect.max_x;xdst++) { if(!stv_vdp2_window_process(xdst,ydst)) continue; xf = stv2_current_tilemap.incx * xdst; xf>>=16; yf = stv2_current_tilemap.incy * ydst; yf>>=16; xsrc = (xf + scrollx) & (xsize_mask-1); ysrc = (yf + scrolly) & (ysize_mask-1); src_offs = (xsrc + (ysrc*xsize)); src_offs += map_offset; src_offs &= 0x7ffff; dot_data = vram[src_offs]; if ((dot_data != 0) || (stv2_current_tilemap.transparency == STV_TRANSPARENCY_NONE)) { dot_data += pal_bank; if ( stv2_current_tilemap.colour_calculation_enabled == 0 ) bitmap.pix32(ydst, xdst) = m_palette->pen(dot_data); else bitmap.pix32(ydst, xdst) = alpha_blend_r32(bitmap.pix32(ydst, xdst), m_palette->pen(dot_data), stv2_current_tilemap.alpha); } } } } void saturn_state::draw_11bpp_bitmap(bitmap_rgb32 &bitmap, const rectangle &cliprect) { int xsize, ysize, xsize_mask, ysize_mask; int xsrc,ysrc,xdst,ydst; int src_offs; uint8_t* vram = m_vdp2.gfx_decode.get(); uint32_t map_offset = stv2_current_tilemap.bitmap_map * 0x20000; int scrollx = stv2_current_tilemap.scrollx; int scrolly = stv2_current_tilemap.scrolly; uint16_t dot_data; uint16_t pal_bank; int xf, yf; xsize = (stv2_current_tilemap.bitmap_size & 2) ? 1024 : 512; ysize = (stv2_current_tilemap.bitmap_size & 1) ? 512 : 256; xsize_mask = (stv2_current_tilemap.linescroll_enable) ? 1024 : xsize; ysize_mask = (stv2_current_tilemap.vertical_linescroll_enable) ? 512 : ysize; pal_bank = 0; if(stv2_current_tilemap.fade_control & 1) pal_bank = ((stv2_current_tilemap.fade_control & 2) ? (2*2048) : (2048)); for(ydst=cliprect.min_y;ydst<=cliprect.max_y;ydst++) { for(xdst=cliprect.min_x;xdst<=cliprect.max_x;xdst++) { if(!stv_vdp2_window_process(xdst,ydst)) continue; xf = stv2_current_tilemap.incx * xdst; xf>>=16; yf = stv2_current_tilemap.incy * ydst; yf>>=16; xsrc = (xf + scrollx) & (xsize_mask-1); ysrc = (yf + scrolly) & (ysize_mask-1); src_offs = (xsrc + (ysrc*xsize)); src_offs *= 2; src_offs += map_offset; src_offs &= 0x7ffff; dot_data = ((vram[src_offs]<<8)|(vram[src_offs+1]<<0)) & 0x7ff; if ((dot_data != 0) || (stv2_current_tilemap.transparency == STV_TRANSPARENCY_NONE)) { dot_data += pal_bank; if ( stv2_current_tilemap.colour_calculation_enabled == 0 ) bitmap.pix32(ydst, xdst) = m_palette->pen(dot_data); else bitmap.pix32(ydst, xdst) = alpha_blend_r32(bitmap.pix32(ydst, xdst), m_palette->pen(dot_data), stv2_current_tilemap.alpha); } } } } void saturn_state::draw_rgb15_bitmap(bitmap_rgb32 &bitmap, const rectangle &cliprect) { int xsize, ysize, xsize_mask, ysize_mask; int xsrc,ysrc,xdst,ydst; int src_offs; uint8_t* vram = m_vdp2.gfx_decode.get(); uint32_t map_offset = stv2_current_tilemap.bitmap_map * 0x20000; int scrollx = stv2_current_tilemap.scrollx; int scrolly = stv2_current_tilemap.scrolly; int r,g,b; uint16_t dot_data; int xf, yf; xsize = (stv2_current_tilemap.bitmap_size & 2) ? 1024 : 512; ysize = (stv2_current_tilemap.bitmap_size & 1) ? 512 : 256; xsize_mask = (stv2_current_tilemap.linescroll_enable) ? 1024 : xsize; ysize_mask = (stv2_current_tilemap.vertical_linescroll_enable) ? 512 : ysize; for(ydst=cliprect.min_y;ydst<=cliprect.max_y;ydst++) { for(xdst=cliprect.min_x;xdst<=cliprect.max_x;xdst++) { if(!stv_vdp2_window_process(xdst,ydst)) continue; xf = stv2_current_tilemap.incx * xdst; xf>>=16; yf = stv2_current_tilemap.incy * ydst; yf>>=16; xsrc = (xf + scrollx) & (xsize_mask-1); ysrc = (yf + scrolly) & (ysize_mask-1); src_offs = (xsrc + (ysrc*xsize)); src_offs *= 2; src_offs += map_offset; src_offs &= 0x7ffff; dot_data =(vram[src_offs]<<8)|(vram[src_offs+1]<<0); if ((dot_data & 0x8000) || (stv2_current_tilemap.transparency == STV_TRANSPARENCY_NONE)) { b = pal5bit((dot_data & 0x7c00) >> 10); g = pal5bit((dot_data & 0x03e0) >> 5); r = pal5bit((dot_data & 0x001f) >> 0); if(stv2_current_tilemap.fade_control & 1) stv_vdp2_compute_color_offset(&r,&g,&b,stv2_current_tilemap.fade_control & 2); if ( stv2_current_tilemap.colour_calculation_enabled == 0 ) bitmap.pix32(ydst, xdst) = rgb_t(r, g, b); else bitmap.pix32(ydst, xdst) = alpha_blend_r32( bitmap.pix32(ydst, xdst), rgb_t(r, g, b), stv2_current_tilemap.alpha ); } } } } void saturn_state::draw_rgb32_bitmap(bitmap_rgb32 &bitmap, const rectangle &cliprect) { int xsize, ysize, xsize_mask, ysize_mask; int xsrc,ysrc,xdst,ydst; int src_offs; uint8_t* vram = m_vdp2.gfx_decode.get(); uint32_t map_offset = stv2_current_tilemap.bitmap_map * 0x20000; int scrollx = stv2_current_tilemap.scrollx; int scrolly = stv2_current_tilemap.scrolly; int r,g,b; uint32_t dot_data; int xf, yf; xsize = (stv2_current_tilemap.bitmap_size & 2) ? 1024 : 512; ysize = (stv2_current_tilemap.bitmap_size & 1) ? 512 : 256; xsize_mask = (stv2_current_tilemap.linescroll_enable) ? 1024 : xsize; ysize_mask = (stv2_current_tilemap.vertical_linescroll_enable) ? 512 : ysize; for(ydst=cliprect.min_y;ydst<=cliprect.max_y;ydst++) { for(xdst=cliprect.min_x;xdst<=cliprect.max_x;xdst++) { if(!stv_vdp2_window_process(xdst,ydst)) continue; xf = stv2_current_tilemap.incx * xdst; xf>>=16; yf = stv2_current_tilemap.incy * ydst; yf>>=16; xsrc = (xf + scrollx) & (xsize_mask-1); ysrc = (yf + scrolly) & (ysize_mask-1); src_offs = (xsrc + (ysrc*xsize)); src_offs *= 4; src_offs += map_offset; src_offs &= 0x7ffff; dot_data = (vram[src_offs+0]<<24)|(vram[src_offs+1]<<16)|(vram[src_offs+2]<<8)|(vram[src_offs+3]<<0); if ((dot_data & 0x80000000) || (stv2_current_tilemap.transparency == STV_TRANSPARENCY_NONE)) { b = ((dot_data & 0x00ff0000) >> 16); g = ((dot_data & 0x0000ff00) >> 8); r = ((dot_data & 0x000000ff) >> 0); if(stv2_current_tilemap.fade_control & 1) stv_vdp2_compute_color_offset(&r,&g,&b,stv2_current_tilemap.fade_control & 2); if ( stv2_current_tilemap.colour_calculation_enabled == 0 ) bitmap.pix32(ydst, xdst) = rgb_t(r, g, b); else bitmap.pix32(ydst, xdst) = alpha_blend_r32( bitmap.pix32(ydst, xdst), rgb_t(r, g, b), stv2_current_tilemap.alpha ); } } } } void saturn_state::stv_vdp2_draw_basic_bitmap(bitmap_rgb32 &bitmap, const rectangle &cliprect) { if (!stv2_current_tilemap.enabled) return; /* new bitmap code, supposed to rewrite the old one. Not supposed to be clean, but EFFICIENT! */ if(stv2_current_tilemap.incx == 0x10000 && stv2_current_tilemap.incy == 0x10000) { switch(stv2_current_tilemap.colour_depth) { case 0: draw_4bpp_bitmap(bitmap,cliprect); return; case 1: draw_8bpp_bitmap(bitmap,cliprect); return; case 2: draw_11bpp_bitmap(bitmap, cliprect); return; case 3: draw_rgb15_bitmap(bitmap,cliprect); return; case 4: draw_rgb32_bitmap(bitmap,cliprect); return; } /* intentional fall-through*/ popmessage("%d %s %s %s",stv2_current_tilemap.colour_depth, stv2_current_tilemap.transparency == STV_TRANSPARENCY_NONE ? "no trans" : "trans", stv2_current_tilemap.colour_calculation_enabled ? "cc" : "no cc", (stv2_current_tilemap.incx == 0x10000 && stv2_current_tilemap.incy == 0x10000) ? "no zoom" : "zoom"); } else { switch(stv2_current_tilemap.colour_depth) { // case 0: draw_4bpp_bitmap(bitmap,cliprect); return; case 1: draw_8bpp_bitmap(bitmap,cliprect); return; // case 2: draw_11bpp_bitmap(bitmap, cliprect); return; case 3: draw_rgb15_bitmap(bitmap,cliprect); return; case 4: draw_rgb32_bitmap(bitmap,cliprect); return; } /* intentional fall-through*/ popmessage("%d %s %s %s",stv2_current_tilemap.colour_depth, stv2_current_tilemap.transparency == STV_TRANSPARENCY_NONE ? "no trans" : "trans", stv2_current_tilemap.colour_calculation_enabled ? "cc" : "no cc", (stv2_current_tilemap.incx == 0x10000 && stv2_current_tilemap.incy == 0x10000) ? "no zoom" : "zoom"); } } /*--------------------------------------------------------------------------- | Plane Size | Pattern Name Data Size | Character Size | Map Bits / Address | ----------------------------------------------------------------------------| | | | 1 H x 1 V | bits 6-0 * 0x02000 | | | 1 word |-------------------------------------| | | | 2 H x 2 V | bits 8-0 * 0x00800 | | 1 H x 1 V ---------------------------------------------------------------| | | | 1 H x 1 V | bits 5-0 * 0x04000 | | | 2 words |-------------------------------------| | | | 2 H x 2 V | bits 7-0 * 0x01000 | ----------------------------------------------------------------------------- | | | 1 H x 1 V | bits 6-1 * 0x04000 | | | 1 word |-------------------------------------| | | | 2 H x 2 V | bits 8-1 * 0x01000 | | 2 H x 1 V ---------------------------------------------------------------| | | | 1 H x 1 V | bits 5-1 * 0x08000 | | | 2 words |-------------------------------------| | | | 2 H x 2 V | bits 7-1 * 0x02000 | ----------------------------------------------------------------------------- | | | 1 H x 1 V | bits 6-2 * 0x08000 | | | 1 word |-------------------------------------| | | | 2 H x 2 V | bits 8-2 * 0x02000 | | 2 H x 2 V ---------------------------------------------------------------| | | | 1 H x 1 V | bits 5-2 * 0x10000 | | | 2 words |-------------------------------------| | | | 2 H x 2 V | bits 7-2 * 0x04000 | --the-highest-bit-is-ignored-if-vram-is-only-4mbits------------------------*/ /* 4.2 Sega's Cell / Character Pattern / Page / Plane / Map system, aka a rather annoying thing that makes optimizations hard (this is only for the normal tilemaps at the moment, i haven't even thought about the ROZ ones) Tiles: Cells are 8x8 gfx stored in video ram, they can be of various colour depths Character Patterns can be 8x8 or 16x16 (1 hcell x 1 vcell or 2 hcell x 2 vcell) (a 16x16 character pattern is 4 8x8 cells put together) A page is made up of 64x64 cells, thats 64x64 character patterns in 8x8 mode or 32x32 character patterns in 16x16 mode. 64 * 8 = 512 (0x200) 32 * 16 = 512 (0x200) A page is _always_ 512 (0x200) pixels in each direction in 1 word mode a 32*16 x 32*16 page is 0x0800 bytes in 1 word mode a 64*8 x 64*8 page is 0x2000 bytes in 2 word mode a 32*16 x 32*16 page is 0x1000 bytes in 2 word mode a 64*8 x 64*8 page is 0x4000 bytes either 1, 2 or 4 pages make each plane depending on the plane size register (per tilemap) therefore each plane is either 64 * 8 * 1 x 64 * 8 * 1 (512 x 512) 64 * 8 * 2 x 64 * 8 * 1 (1024 x 512) 64 * 8 * 2 x 64 * 8 * 2 (1024 x 1024) 32 * 16 * 1 x 32 * 16 * 1 (512 x 512) 32 * 16 * 2 x 32 * 16 * 1 (1024 x 512) 32 * 16 * 2 x 32 * 16 * 2 (1024 x 1024) map is always enabled? map is a 2x2 arrangement of planes, all 4 of the planes can be the same. */ void saturn_state::stv_vdp2_get_map_page( int x, int y, int *_map, int *_page ) { int page = 0; int map; if ( stv2_current_tilemap.map_count == 4 ) { if ( stv2_current_tilemap.tile_size == 0 ) { if ( stv2_current_tilemap.plane_size & 1 ) { page = ((x >> 6) & 1); map = (x >> 7) & 1; } else { map = (x >> 6) & 1; } if ( stv2_current_tilemap.plane_size & 2 ) { page |= ((y >> (6-1)) & 2); map |= ((y >> (7-1)) & 2); } else { map |= ((y >> (6-1)) & 2); } } else { if ( stv2_current_tilemap.plane_size & 1 ) { page = ((x >> 5) & 1); map = (x >> 6) & 1; } else { map = (x >> 5) & 1; } if ( stv2_current_tilemap.plane_size & 2 ) { page |= ((y >> (5 - 1)) & 2); map |= ((y >> (6-1)) & 2); } else { map |= ((y >> (5-1)) & 2); } } } else //16 { if ( stv2_current_tilemap.tile_size == 0 ) { if ( stv2_current_tilemap.plane_size & 1 ) { page = ((x >> 6) & 1); map = (x >> 7) & 3; } else { map = (x >> 6) & 3; } if ( stv2_current_tilemap.plane_size & 2 ) { page |= ((y >> (6-1)) & 2); map |= ((y >> (7-2)) & 12); } else { map |= ((y >> (6-2)) & 12); } } else { if ( stv2_current_tilemap.plane_size & 1 ) { page = ((x >> 5) & 1); map = (x >> 6) & 3; } else { map = (x >> 5) & 3; } if ( stv2_current_tilemap.plane_size & 2 ) { page |= ((y >> (5 - 1)) & 2); map |= ((y >> (6-2)) & 12); } else { map |= ((y >> (5-2)) & 12); } } } *_page = page; *_map = map; } void saturn_state::stv_vdp2_draw_basic_tilemap(bitmap_rgb32 &bitmap, const rectangle &cliprect) { /* hopefully this is easier to follow than it is efficient .. */ /* I call character patterns tiles .. even if they represent up to 4 tiles */ /* Page variables */ int pgtiles_x, pgpixels_x; int pgtiles_y, pgpixels_y; int pgsize_bytes, pgsize_dwords; /* Plane Variables */ int pltiles_x, plpixels_x; int pltiles_y, plpixels_y; int plsize_bytes/*, plsize_dwords*/; /* Map Variables */ int mptiles_x, mppixels_x; int mptiles_y, mppixels_y; int mpsize_bytes, mpsize_dwords; /* work Variables */ int i, x, y; int base[16]; int scalex,scaley; int tilesizex, tilesizey; int drawypos, drawxpos; int tilecodemin = 0x10000000, tilecodemax = 0; if ( stv2_current_tilemap.incx == 0 || stv2_current_tilemap.incy == 0 ) return; if ( stv2_current_tilemap.colour_calculation_enabled == 1 ) { if ( STV_VDP2_CCMD ) { stv2_current_tilemap.transparency = STV_TRANSPARENCY_ADD_BLEND; } else { stv2_current_tilemap.transparency = STV_TRANSPARENCY_ALPHA; } } scalex = s32(s64(0x100000000U) / s64(stv2_current_tilemap.incx)); scaley = s32(s64(0x100000000U) / s64(stv2_current_tilemap.incy)); tilesizex = scalex * 8; tilesizey = scaley * 8; drawypos = drawxpos = 0; /* Calculate the Number of tiles for x / y directions of each page (actually these will be the same */ /* (2-stv2_current_tilemap.tile_size) << 5) */ pgtiles_x = ((2-stv2_current_tilemap.tile_size) << 5); // 64 (8x8 mode) or 32 (16x16 mode) pgtiles_y = ((2-stv2_current_tilemap.tile_size) << 5); // 64 (8x8 mode) or 32 (16x16 mode) /* Calculate the Page Size in BYTES */ /* 64 * 64 * (1 * 2) = 0x2000 bytes 32 * 32 * (1 * 2) = 0x0800 bytes 64 * 64 * (2 * 2) = 0x4000 bytes 32 * 32 * (2 * 2) = 0x1000 bytes */ pgsize_bytes = (pgtiles_x * pgtiles_y) * ((2-stv2_current_tilemap.pattern_data_size)*2); /*--------------------------------------------------------------------------- | Plane Size | Pattern Name Data Size | Character Size | Map Bits / Address | ----------------------------------------------------------------------------| | | | 1 H x 1 V | bits 6-0 * 0x02000 | | | 1 word |-------------------------------------| | | | 2 H x 2 V | bits 8-0 * 0x00800 | | 1 H x 1 V ---------------------------------------------------------------| | | | 1 H x 1 V | bits 5-0 * 0x04000 | | | 2 words |-------------------------------------| | | | 2 H x 2 V | bits 7-0 * 0x01000 | ---------------------------------------------------------------------------*/ /* Page Dimensions are always 0x200 pixes (512x512) */ pgpixels_x = 0x200; pgpixels_y = 0x200; /* Work out the Plane Size in tiles and Plane Dimensions (pixels) */ switch (stv2_current_tilemap.plane_size & 3) { case 0: // 1 page * 1 page pltiles_x = pgtiles_x; plpixels_x = pgpixels_x; pltiles_y = pgtiles_y; plpixels_y = pgpixels_y; break; case 1: // 2 pages * 1 page pltiles_x = pgtiles_x * 2; plpixels_x = pgpixels_x * 2; pltiles_y = pgtiles_y; plpixels_y = pgpixels_y; break; case 3: // 2 pages * 2 pages pltiles_x = pgtiles_x * 2; plpixels_x = pgpixels_x * 2; pltiles_y = pgtiles_y * 2; plpixels_y = pgpixels_y * 2; break; default: // illegal pltiles_x = pgtiles_x; plpixels_x = pgpixels_x; pltiles_y = pgtiles_y * 2; plpixels_y = pgpixels_y * 2; break; } /* Plane Size in BYTES */ /* still the same as before (64 * 1) * (64 * 1) * (1 * 2) = 0x02000 bytes (32 * 1) * (32 * 1) * (1 * 2) = 0x00800 bytes (64 * 1) * (64 * 1) * (2 * 2) = 0x04000 bytes (32 * 1) * (32 * 1) * (2 * 2) = 0x01000 bytes changed (64 * 2) * (64 * 1) * (1 * 2) = 0x04000 bytes (32 * 2) * (32 * 1) * (1 * 2) = 0x01000 bytes (64 * 2) * (64 * 1) * (2 * 2) = 0x08000 bytes (32 * 2) * (32 * 1) * (2 * 2) = 0x02000 bytes changed (64 * 2) * (64 * 1) * (1 * 2) = 0x08000 bytes (32 * 2) * (32 * 1) * (1 * 2) = 0x02000 bytes (64 * 2) * (64 * 1) * (2 * 2) = 0x10000 bytes (32 * 2) * (32 * 1) * (2 * 2) = 0x04000 bytes */ plsize_bytes = (pltiles_x * pltiles_y) * ((2-stv2_current_tilemap.pattern_data_size)*2); /*--------------------------------------------------------------------------- | Plane Size | Pattern Name Data Size | Character Size | Map Bits / Address | ----------------------------------------------------------------------------- | 1 H x 1 V see above, nothing has changed | ----------------------------------------------------------------------------- | | | 1 H x 1 V | bits 6-1 * 0x04000 | | | 1 word |-------------------------------------| | | | 2 H x 2 V | bits 8-1 * 0x01000 | | 2 H x 1 V ---------------------------------------------------------------| | | | 1 H x 1 V | bits 5-1 * 0x08000 | | | 2 words |-------------------------------------| | | | 2 H x 2 V | bits 7-1 * 0x02000 | ----------------------------------------------------------------------------- | | | 1 H x 1 V | bits 6-2 * 0x08000 | | | 1 word |-------------------------------------| | | | 2 H x 2 V | bits 8-2 * 0x02000 | | 2 H x 2 V ---------------------------------------------------------------| | | | 1 H x 1 V | bits 5-2 * 0x10000 | | | 2 words |-------------------------------------| | | | 2 H x 2 V | bits 7-2 * 0x04000 | --the-highest-bit-is-ignored-if-vram-is-only-4mbits------------------------*/ /* Work out the Map Sizes in tiles, Map Dimensions */ /* maps are always enabled? */ if ( stv2_current_tilemap.map_count == 4 ) { mptiles_x = pltiles_x * 2; mptiles_y = pltiles_y * 2; mppixels_x = plpixels_x * 2; mppixels_y = plpixels_y * 2; } else { mptiles_x = pltiles_x * 4; mptiles_y = pltiles_y * 4; mppixels_x = plpixels_x * 4; mppixels_y = plpixels_y * 4; } /* Map Size in BYTES */ mpsize_bytes = (mptiles_x * mptiles_y) * ((2-stv2_current_tilemap.pattern_data_size)*2); /*----------------------------------------------------------------------------------------------------------- | | | 1 H x 1 V | bits 6-1 (upper mask 0x07f) (0x1ff >> 2) * 0x04000 | | | 1 word |---------------------------------------------------------------------| | | | 2 H x 2 V | bits 8-1 (upper mask 0x1ff) (0x1ff >> 0) * 0x01000 | | 2 H x 1 V -----------------------------------------------------------------------------------------------| | | | 1 H x 1 V | bits 5-1 (upper mask 0x03f) (0x1ff >> 3) * 0x08000 | | | 2 words |---------------------------------------------------------------------| | | | 2 H x 2 V | bits 7-1 (upper mask 0x0ff) (0x1ff >> 1) * 0x02000 | ------------------------------------------------------------------------------------------------------------- lower mask = ~stv2_current_tilemap.plane_size -----------------------------------------------------------------------------------------------------------*/ /* Precalculate bases from MAP registers */ for (i = 0; i < stv2_current_tilemap.map_count; i++) { static const int shifttable[4] = {0,1,2,2}; int uppermask, uppermaskshift; uppermaskshift = (1-stv2_current_tilemap.pattern_data_size) | ((1-stv2_current_tilemap.tile_size)<<1); uppermask = 0x1ff >> uppermaskshift; base[i] = ((stv2_current_tilemap.map_offset[i] & uppermask) >> shifttable[stv2_current_tilemap.plane_size]) * plsize_bytes; base[i] &= 0x7ffff; /* shienryu needs this for the text layer, is there a problem elsewhere or is it just right without the ram cart */ base[i] = base[i] / 4; // convert bytes to DWORDS } /* other bits */ //stv2_current_tilemap.trans_enabled = stv2_current_tilemap.trans_enabled ? STV_TRANSPARENCY_NONE : STV_TRANSPARENCY_PEN; stv2_current_tilemap.scrollx &= mppixels_x-1; stv2_current_tilemap.scrolly &= mppixels_y-1; pgsize_dwords = pgsize_bytes /4; //plsize_dwords = plsize_bytes /4; mpsize_dwords = mpsize_bytes /4; // if (stv2_current_tilemap.layer_name==3) popmessage ("well this is a bit %08x", stv2_current_tilemap.map_offset[0]); // if (stv2_current_tilemap.layer_name==3) popmessage ("well this is a bit %08x %08x %08x %08x", stv2_current_tilemap.plane_size, pgtiles_x, pltiles_x, mptiles_x); if (!stv2_current_tilemap.enabled) return; // stop right now if its disabled ... /* most things we need (or don't need) to work out are now worked out */ for (y = 0; y<mptiles_y; y++) { int ypageoffs; int page, map, newbase, offs, data; int tilecode, flipyx, pal, gfx = 0; map = 0 ; page = 0 ; if ( y == 0 ) { int drawyposinc = tilesizey*(stv2_current_tilemap.tile_size ? 2 : 1); drawypos = -(stv2_current_tilemap.scrolly*scaley); while( ((drawypos + drawyposinc) >> 16) < cliprect.min_y ) { drawypos += drawyposinc; y++; } mptiles_y += y; } else { drawypos += tilesizey*(stv2_current_tilemap.tile_size ? 2 : 1); } if ((drawypos >> 16) > cliprect.max_y) break; ypageoffs = y & (pgtiles_y-1); for (x = 0; x<mptiles_x; x++) { int xpageoffs; int tilecodespacing = 1; if ( x == 0 ) { int drawxposinc = tilesizex*(stv2_current_tilemap.tile_size ? 2 : 1); drawxpos = -(stv2_current_tilemap.scrollx*scalex); while( ((drawxpos + drawxposinc) >> 16) < cliprect.min_x ) { drawxpos += drawxposinc; x++; } mptiles_x += x; } else { drawxpos+=tilesizex*(stv2_current_tilemap.tile_size ? 2 : 1); } if ( (drawxpos >> 16) > cliprect.max_x ) break; xpageoffs = x & (pgtiles_x-1); stv_vdp2_get_map_page(x,y,&map,&page); newbase = base[map] + page * pgsize_dwords; offs = (ypageoffs * pgtiles_x) + xpageoffs; /* GET THE TILE INFO ... */ /* 1 word per tile mode with supplement bits */ if (stv2_current_tilemap.pattern_data_size ==1) { data = m_vdp2_vram[newbase + offs/2]; data = (offs&1) ? (data & 0x0000ffff) : ((data & 0xffff0000) >> 16); /* Supplement Mode 12 bits, no flip */ if (stv2_current_tilemap.character_number_supplement == 1) { /* no flip */ flipyx = 0; /* 8x8 */ if (stv2_current_tilemap.tile_size==0) tilecode = (data & 0x0fff) + ( (stv2_current_tilemap.supplementary_character_bits&0x1c) << 10); /* 16x16 */ else tilecode = ((data & 0x0fff) << 2) + (stv2_current_tilemap.supplementary_character_bits&0x03) + ((stv2_current_tilemap.supplementary_character_bits&0x10) << 10); } /* Supplement Mode 10 bits, with flip */ else { /* flip bits */ flipyx = (data & 0x0c00) >> 10; /* 8x8 */ if (stv2_current_tilemap.tile_size==0) tilecode = (data & 0x03ff) + ( (stv2_current_tilemap.supplementary_character_bits) << 10); /* 16x16 */ else tilecode = ((data & 0x03ff) <<2) + (stv2_current_tilemap.supplementary_character_bits&0x03) + ((stv2_current_tilemap.supplementary_character_bits&0x1c) << 10); } /*>16cols*/ if (stv2_current_tilemap.colour_depth != 0) pal = ((data & 0x7000)>>8); /*16 cols*/ else pal = ((data & 0xf000)>>12) +( (stv2_current_tilemap.supplementary_palette_bits) << 4); } /* 2 words per tile, no supplement bits */ else { data = m_vdp2_vram[newbase + offs]; tilecode = (data & 0x00007fff); pal = (data & 0x007f0000)>>16; // specialc = (data & 0x10000000)>>28; flipyx = (data & 0xc0000000)>>30; } /* WE'VE GOT THE TILE INFO ... */ if ( tilecode < tilecodemin ) tilecodemin = tilecode; if ( tilecode > tilecodemax ) tilecodemax = tilecode; /* DECODE ANY TILES WE NEED TO DECODE */ pal += stv2_current_tilemap.colour_ram_address_offset<< 4; // bios uses this .. /*Enable fading bit*/ if(stv2_current_tilemap.fade_control & 1) { /*Select fading bit*/ pal += ((stv2_current_tilemap.fade_control & 2) ? (0x100) : (0x80)); } if (stv2_current_tilemap.colour_depth == 1) { gfx = 2; pal = pal >>4; tilecode &=0x7fff; if (tilecode == 0x7fff) tilecode--; /* prevents crash but unsure what should happen; wrapping? */ tilecodespacing = 2; } else if (stv2_current_tilemap.colour_depth == 0) { gfx = 0; tilecode &=0x7fff; tilecodespacing = 1; } /* TILES ARE NOW DECODED */ if(!STV_VDP2_VRAMSZ) tilecode &= 0x3fff; /* DRAW! */ if(stv2_current_tilemap.incx != 0x10000 || stv2_current_tilemap.incy != 0x10000 || stv2_current_tilemap.transparency == STV_TRANSPARENCY_ADD_BLEND ) { #define SCR_TILESIZE_X (((drawxpos + tilesizex) >> 16) - (drawxpos >> 16)) #define SCR_TILESIZE_X1(startx) (((drawxpos + (startx) + tilesizex) >> 16) - ((drawxpos + (startx))>>16)) #define SCR_TILESIZE_Y (((drawypos + tilesizey) >> 16) - (drawypos >> 16)) #define SCR_TILESIZE_Y1(starty) (((drawypos + (starty) + tilesizey) >> 16) - ((drawypos + (starty))>>16)) if (stv2_current_tilemap.tile_size==1) { if ( stv2_current_tilemap.colour_depth == 4 ) { popmessage("Unsupported tilemap gfx zoom color depth = 4, tile size = 1, contact MAMEdev"); } else if ( stv2_current_tilemap.colour_depth == 3 ) { /* RGB555 */ stv_vdp2_drawgfxzoom_rgb555(bitmap,cliprect,tilecode+(0+(flipyx&1)+(flipyx&2))*tilecodespacing,pal,flipyx&1,flipyx&2,drawxpos >> 16, drawypos >> 16,stv2_current_tilemap.transparency,0,scalex,scaley,SCR_TILESIZE_X, SCR_TILESIZE_Y,stv2_current_tilemap.alpha); stv_vdp2_drawgfxzoom_rgb555(bitmap,cliprect,tilecode+(1-(flipyx&1)+(flipyx&2))*tilecodespacing,pal,flipyx&1,flipyx&2,(drawxpos+tilesizex) >> 16,drawypos >> 16,stv2_current_tilemap.transparency,0,scalex,scaley,SCR_TILESIZE_X1(tilesizex), SCR_TILESIZE_Y,stv2_current_tilemap.alpha); stv_vdp2_drawgfxzoom_rgb555(bitmap,cliprect,tilecode+(2+(flipyx&1)-(flipyx&2))*tilecodespacing,pal,flipyx&1,flipyx&2,drawxpos >> 16,(drawypos+tilesizey) >> 16,stv2_current_tilemap.transparency,0,scalex,scaley,SCR_TILESIZE_X, SCR_TILESIZE_Y1(tilesizey),stv2_current_tilemap.alpha); stv_vdp2_drawgfxzoom_rgb555(bitmap,cliprect,tilecode+(3-(flipyx&1)-(flipyx&2))*tilecodespacing,pal,flipyx&1,flipyx&2,(drawxpos+tilesizex)>> 16,(drawypos+tilesizey) >> 16,stv2_current_tilemap.transparency,0,scalex,scaley,SCR_TILESIZE_X1(tilesizex), SCR_TILESIZE_Y1(tilesizey),stv2_current_tilemap.alpha); } else { /* normal */ stv_vdp2_drawgfxzoom(bitmap,cliprect,m_gfxdecode->gfx(gfx),tilecode+(0+(flipyx&1)+(flipyx&2))*tilecodespacing,pal,flipyx&1,flipyx&2,drawxpos >> 16, drawypos >> 16,stv2_current_tilemap.transparency,0,scalex,scaley,SCR_TILESIZE_X, SCR_TILESIZE_Y,stv2_current_tilemap.alpha); stv_vdp2_drawgfxzoom(bitmap,cliprect,m_gfxdecode->gfx(gfx),tilecode+(1-(flipyx&1)+(flipyx&2))*tilecodespacing,pal,flipyx&1,flipyx&2,(drawxpos+tilesizex) >> 16,drawypos >> 16,stv2_current_tilemap.transparency,0,scalex,scaley,SCR_TILESIZE_X1(tilesizex), SCR_TILESIZE_Y,stv2_current_tilemap.alpha); stv_vdp2_drawgfxzoom(bitmap,cliprect,m_gfxdecode->gfx(gfx),tilecode+(2+(flipyx&1)-(flipyx&2))*tilecodespacing,pal,flipyx&1,flipyx&2,drawxpos >> 16,(drawypos+tilesizey) >> 16,stv2_current_tilemap.transparency,0,scalex,scaley,SCR_TILESIZE_X, SCR_TILESIZE_Y1(tilesizey),stv2_current_tilemap.alpha); stv_vdp2_drawgfxzoom(bitmap,cliprect,m_gfxdecode->gfx(gfx),tilecode+(3-(flipyx&1)-(flipyx&2))*tilecodespacing,pal,flipyx&1,flipyx&2,(drawxpos+tilesizex)>> 16,(drawypos+tilesizey) >> 16,stv2_current_tilemap.transparency,0,scalex,scaley,SCR_TILESIZE_X1(tilesizex), SCR_TILESIZE_Y1(tilesizey),stv2_current_tilemap.alpha); } } else { if ( stv2_current_tilemap.colour_depth == 4 ) popmessage("Unsupported tilemap gfx zoom color depth = 4, tile size = 0, contact MAMEdev"); else if ( stv2_current_tilemap.colour_depth == 3) { stv_vdp2_drawgfxzoom_rgb555(bitmap,cliprect,tilecode,pal,flipyx&1,flipyx&2, drawxpos >> 16, drawypos >> 16,stv2_current_tilemap.transparency,0,scalex,scaley,SCR_TILESIZE_X,SCR_TILESIZE_Y,stv2_current_tilemap.alpha); } else stv_vdp2_drawgfxzoom(bitmap,cliprect,m_gfxdecode->gfx(gfx),tilecode,pal,flipyx&1,flipyx&2, drawxpos >> 16, drawypos >> 16,stv2_current_tilemap.transparency,0,scalex,scaley,SCR_TILESIZE_X,SCR_TILESIZE_Y,stv2_current_tilemap.alpha); } } else { int olddrawxpos, olddrawypos; olddrawxpos = drawxpos; drawxpos >>= 16; olddrawypos = drawypos; drawypos >>= 16; if (stv2_current_tilemap.tile_size==1) { if ( stv2_current_tilemap.colour_depth == 4 ) { /* normal */ stv_vdp2_drawgfx_rgb888(bitmap,cliprect,tilecode+(0+(flipyx&1)+(flipyx&2))*4,flipyx&1,flipyx&2,drawxpos, drawypos,stv2_current_tilemap.transparency,stv2_current_tilemap.alpha); stv_vdp2_drawgfx_rgb888(bitmap,cliprect,tilecode+(1-(flipyx&1)+(flipyx&2))*4,flipyx&1,flipyx&2,drawxpos+8,drawypos,stv2_current_tilemap.transparency,stv2_current_tilemap.alpha); stv_vdp2_drawgfx_rgb888(bitmap,cliprect,tilecode+(2+(flipyx&1)-(flipyx&2))*4,flipyx&1,flipyx&2,drawxpos,drawypos+8,stv2_current_tilemap.transparency,stv2_current_tilemap.alpha); stv_vdp2_drawgfx_rgb888(bitmap,cliprect,tilecode+(3-(flipyx&1)-(flipyx&2))*4,flipyx&1,flipyx&2,drawxpos+8,drawypos+8,stv2_current_tilemap.transparency,stv2_current_tilemap.alpha); } else if ( stv2_current_tilemap.colour_depth == 3 ) { /* normal */ stv_vdp2_drawgfx_rgb555(bitmap,cliprect,tilecode+(0+(flipyx&1)+(flipyx&2))*4,flipyx&1,flipyx&2,drawxpos, drawypos,stv2_current_tilemap.transparency,stv2_current_tilemap.alpha); stv_vdp2_drawgfx_rgb555(bitmap,cliprect,tilecode+(1-(flipyx&1)+(flipyx&2))*4,flipyx&1,flipyx&2,drawxpos+8,drawypos,stv2_current_tilemap.transparency,stv2_current_tilemap.alpha); stv_vdp2_drawgfx_rgb555(bitmap,cliprect,tilecode+(2+(flipyx&1)-(flipyx&2))*4,flipyx&1,flipyx&2,drawxpos,drawypos+8,stv2_current_tilemap.transparency,stv2_current_tilemap.alpha); stv_vdp2_drawgfx_rgb555(bitmap,cliprect,tilecode+(3-(flipyx&1)-(flipyx&2))*4,flipyx&1,flipyx&2,drawxpos+8,drawypos+8,stv2_current_tilemap.transparency,stv2_current_tilemap.alpha); } else if (stv2_current_tilemap.transparency == STV_TRANSPARENCY_ALPHA) { /* alpha */ stv_vdp2_drawgfx_alpha(bitmap,cliprect,m_gfxdecode->gfx(gfx),tilecode+(0+(flipyx&1)+(flipyx&2))*tilecodespacing,pal,flipyx&1,flipyx&2,drawxpos, drawypos,0,stv2_current_tilemap.alpha); stv_vdp2_drawgfx_alpha(bitmap,cliprect,m_gfxdecode->gfx(gfx),tilecode+(1-(flipyx&1)+(flipyx&2))*tilecodespacing,pal,flipyx&1,flipyx&2,drawxpos+8,drawypos,0,stv2_current_tilemap.alpha); stv_vdp2_drawgfx_alpha(bitmap,cliprect,m_gfxdecode->gfx(gfx),tilecode+(2+(flipyx&1)-(flipyx&2))*tilecodespacing,pal,flipyx&1,flipyx&2,drawxpos,drawypos+8,0,stv2_current_tilemap.alpha); stv_vdp2_drawgfx_alpha(bitmap,cliprect,m_gfxdecode->gfx(gfx),tilecode+(3-(flipyx&1)-(flipyx&2))*tilecodespacing,pal,flipyx&1,flipyx&2,drawxpos+8,drawypos+8,0,stv2_current_tilemap.alpha); } else { /* normal */ stv_vdp2_drawgfx_transpen(bitmap,cliprect,m_gfxdecode->gfx(gfx),tilecode+(0+(flipyx&1)+(flipyx&2))*tilecodespacing,pal,flipyx&1,flipyx&2,drawxpos, drawypos,(stv2_current_tilemap.transparency==STV_TRANSPARENCY_PEN)?0:-1); stv_vdp2_drawgfx_transpen(bitmap,cliprect,m_gfxdecode->gfx(gfx),tilecode+(1-(flipyx&1)+(flipyx&2))*tilecodespacing,pal,flipyx&1,flipyx&2,drawxpos+8,drawypos,(stv2_current_tilemap.transparency==STV_TRANSPARENCY_PEN)?0:-1); stv_vdp2_drawgfx_transpen(bitmap,cliprect,m_gfxdecode->gfx(gfx),tilecode+(2+(flipyx&1)-(flipyx&2))*tilecodespacing,pal,flipyx&1,flipyx&2,drawxpos,drawypos+8,(stv2_current_tilemap.transparency==STV_TRANSPARENCY_PEN)?0:-1); stv_vdp2_drawgfx_transpen(bitmap,cliprect,m_gfxdecode->gfx(gfx),tilecode+(3-(flipyx&1)-(flipyx&2))*tilecodespacing,pal,flipyx&1,flipyx&2,drawxpos+8,drawypos+8,(stv2_current_tilemap.transparency==STV_TRANSPARENCY_PEN)?0:-1); } } else { if ( stv2_current_tilemap.colour_depth == 4) { stv_vdp2_drawgfx_rgb888(bitmap,cliprect,tilecode,flipyx&1,flipyx&2,drawxpos,drawypos,stv2_current_tilemap.transparency,stv2_current_tilemap.alpha); } else if ( stv2_current_tilemap.colour_depth == 3) { stv_vdp2_drawgfx_rgb555(bitmap,cliprect,tilecode,flipyx&1,flipyx&2,drawxpos,drawypos,stv2_current_tilemap.transparency,stv2_current_tilemap.alpha); } else { if (stv2_current_tilemap.transparency == STV_TRANSPARENCY_ALPHA) stv_vdp2_drawgfx_alpha(bitmap,cliprect,m_gfxdecode->gfx(gfx),tilecode,pal,flipyx&1,flipyx&2, drawxpos, drawypos,0,stv2_current_tilemap.alpha); else stv_vdp2_drawgfx_transpen(bitmap,cliprect,m_gfxdecode->gfx(gfx),tilecode,pal,flipyx&1,flipyx&2, drawxpos, drawypos,(stv2_current_tilemap.transparency==STV_TRANSPARENCY_PEN)?0:-1); } } drawxpos = olddrawxpos; drawypos = olddrawypos; } /* DRAWN?! */ } } if ( stv2_current_tilemap.layer_name & 0x80 ) { static const int shifttable[4] = {0,1,2,2}; int uppermask, uppermaskshift; int mapsize; uppermaskshift = (1-stv2_current_tilemap.pattern_data_size) | ((1-stv2_current_tilemap.tile_size)<<1); uppermask = 0x1ff >> uppermaskshift; if ( LOG_VDP2 ) { logerror( "Layer RBG%d, size %d x %d\n", stv2_current_tilemap.layer_name & 0x7f, cliprect.max_x + 1, cliprect.max_y + 1 ); logerror( "Tiles: min %08X, max %08X\n", tilecodemin, tilecodemax ); logerror( "MAP size in dwords %08X\n", mpsize_dwords ); for (i = 0; i < stv2_current_tilemap.map_count; i++) { logerror( "Map register %d: base %08X\n", stv2_current_tilemap.map_offset[i], base[i] ); } } // store map information stv_vdp2_layer_data_placement.map_offset_min = 0x7fffffff; stv_vdp2_layer_data_placement.map_offset_max = 0x00000000; for (i = 0; i < stv2_current_tilemap.map_count; i++) { if ( base[i] < stv_vdp2_layer_data_placement.map_offset_min ) stv_vdp2_layer_data_placement.map_offset_min = base[i]; if ( base[i] > stv_vdp2_layer_data_placement.map_offset_max ) stv_vdp2_layer_data_placement.map_offset_max = base[i]; } mapsize = ((1 & uppermask) >> shifttable[stv2_current_tilemap.plane_size]) * plsize_bytes - ((0 & uppermask) >> shifttable[stv2_current_tilemap.plane_size]) * plsize_bytes; mapsize /= 4; stv_vdp2_layer_data_placement.map_offset_max += mapsize; stv_vdp2_layer_data_placement.tile_offset_min = tilecodemin * 0x20 / 4; stv_vdp2_layer_data_placement.tile_offset_max = (tilecodemax + 1) * 0x20 / 4; } } #define STV_VDP2_READ_VERTICAL_LINESCROLL( _val, _address ) \ { \ _val = m_vdp2_vram[ _address ]; \ _val &= 0x07ffff00; \ if ( _val & 0x04000000 ) _val |= 0xf8000000; \ } void saturn_state::stv_vdp2_check_tilemap_with_linescroll(bitmap_rgb32 &bitmap, const rectangle &cliprect) { rectangle mycliprect; int cur_line = cliprect.min_y; int address; int active_functions = 0; int32_t scroll_values[3], prev_scroll_values[3]; int i; int scroll_values_equal; int lines; int16_t main_scrollx, main_scrolly; // int32_t incx; int linescroll_enable, vertical_linescroll_enable, linezoom_enable; int vertical_linescroll_index = -1; // read original scroll values main_scrollx = stv2_current_tilemap.scrollx; main_scrolly = stv2_current_tilemap.scrolly; // incx = stv2_current_tilemap.incx; // prepare linescroll flags linescroll_enable = stv2_current_tilemap.linescroll_enable; // stv2_current_tilemap.linescroll_enable = 0; vertical_linescroll_enable = stv2_current_tilemap.vertical_linescroll_enable; // stv2_current_tilemap.vertical_linescroll_enable = 0; linezoom_enable = stv2_current_tilemap.linezoom_enable; // stv2_current_tilemap.linezoom_enable = 0; // prepare working clipping rectangle memcpy( &mycliprect, &cliprect, sizeof(rectangle) ); // calculate the number of active functions if ( linescroll_enable ) active_functions++; if ( vertical_linescroll_enable ) { vertical_linescroll_index = active_functions; active_functions++; } if ( linezoom_enable ) active_functions++; // address of data table address = stv2_current_tilemap.linescroll_table_address + active_functions*4*cliprect.min_y; // get the first scroll values for ( i = 0; i < active_functions; i++ ) { if ( i == vertical_linescroll_index ) { STV_VDP2_READ_VERTICAL_LINESCROLL( prev_scroll_values[i], (address / 4) + i ); prev_scroll_values[i] -= (cur_line * stv2_current_tilemap.incy); } else { prev_scroll_values[i] = m_vdp2_vram[ (address / 4) + i ]; } } while( cur_line <= cliprect.max_y ) { lines = 0; do { // update address address += active_functions*4; // update lines count lines += stv2_current_tilemap.linescroll_interval; // get scroll values for ( i = 0; i < active_functions; i++ ) { if ( i == vertical_linescroll_index ) { STV_VDP2_READ_VERTICAL_LINESCROLL( scroll_values[i], (address/4) + i ); scroll_values[i] -= (cur_line + lines) * stv2_current_tilemap.incy; } else { scroll_values[i] = m_vdp2_vram[ (address / 4) + i ]; } } // compare scroll values scroll_values_equal = 1; for ( i = 0; i < active_functions; i++ ) { scroll_values_equal &= (scroll_values[i] == prev_scroll_values[i]); } } while( scroll_values_equal && ((cur_line + lines) <= cliprect.max_y) ); // determined how many lines can be drawn // prepare clipping rectangle mycliprect.min_y = cur_line; mycliprect.max_y = cur_line + lines - 1; // prepare scroll values i = 0; // linescroll if ( linescroll_enable ) { prev_scroll_values[i] &= 0x07ffff00; if ( prev_scroll_values[i] & 0x04000000 ) prev_scroll_values[i] |= 0xf8000000; stv2_current_tilemap.scrollx = main_scrollx + (prev_scroll_values[i] >> 16); i++; } // vertical line scroll if ( vertical_linescroll_enable ) { stv2_current_tilemap.scrolly = main_scrolly + (prev_scroll_values[i] >> 16); i++; } // linezooom if ( linezoom_enable ) { prev_scroll_values[i] &= 0x0007ff00; if ( prev_scroll_values[i] & 0x00040000 ) prev_scroll_values[i] |= 0xfff80000; stv2_current_tilemap.incx = prev_scroll_values[i]; i++; } // if ( LOG_VDP2 ) logerror( "Linescroll: y < %d, %d >, scrollx = %d, scrolly = %d, incx = %f\n", mycliprect.min_y, mycliprect.max_y, stv2_current_tilemap.scrollx, stv2_current_tilemap.scrolly, (float)stv2_current_tilemap.incx/65536.0 ); // render current tilemap portion if (stv2_current_tilemap.bitmap_enable) // this layer is a bitmap { stv_vdp2_draw_basic_bitmap(bitmap, mycliprect); } else { //stv_vdp2_apply_window_on_layer(mycliprect); stv_vdp2_draw_basic_tilemap(bitmap, mycliprect); } // update parameters for next iteration memcpy( prev_scroll_values, scroll_values, sizeof(scroll_values)); cur_line += lines; } } void saturn_state::stv_vdp2_draw_line(bitmap_rgb32 &bitmap, const rectangle &cliprect) { int x,y; uint8_t* gfxdata = m_vdp2.gfx_decode.get(); uint32_t base_offs,base_mask; uint32_t pix; uint8_t interlace; interlace = (STV_VDP2_LSMD == 3)+1; { base_mask = STV_VDP2_VRAMSZ ? 0x7ffff : 0x3ffff; for(y=cliprect.min_y;y<=cliprect.max_y;y++) { base_offs = (STV_VDP2_LCTA & base_mask) << 1; if(STV_VDP2_LCCLMD) base_offs += (y / interlace) << 1; for(x=cliprect.min_x;x<=cliprect.max_x;x++) { uint16_t pen; pen = (gfxdata[base_offs+0]<<8)|gfxdata[base_offs+1]; pix = bitmap.pix32(y, x); bitmap.pix32(y, x) = stv_add_blend(m_palette->pen(pen & 0x7ff),pix); } } } } void saturn_state::stv_vdp2_draw_mosaic(bitmap_rgb32 &bitmap, const rectangle &cliprect, uint8_t is_roz) { int x,y,xi,yi; uint8_t h_size,v_size; uint32_t pix; h_size = STV_VDP2_MZSZH+1; v_size = STV_VDP2_MZSZV+1; if(is_roz) v_size = 1; if(h_size == 1 && v_size == 1) return; // don't bother if(STV_VDP2_LSMD == 3) v_size <<= 1; for(y=cliprect.min_y;y<=cliprect.max_y;y+=v_size) { for(x=cliprect.min_x;x<=cliprect.max_x;x+=h_size) { pix = bitmap.pix32(y, x); for(yi=0;yi<v_size;yi++) for(xi=0;xi<h_size;xi++) bitmap.pix32(y+yi, x+xi) = pix; } } } void saturn_state::stv_vdp2_check_tilemap(bitmap_rgb32 &bitmap, const rectangle &cliprect) { /* the idea is here we check the tilemap capabilities / whats enabled and call an appropriate tilemap drawing routine, or at the very list throw up a few errors if the tilemaps want to do something we don't support yet */ // int window_applied = 0; rectangle mycliprect = cliprect; if ( stv2_current_tilemap.linescroll_enable || stv2_current_tilemap.vertical_linescroll_enable || stv2_current_tilemap.linezoom_enable ) { stv_vdp2_check_tilemap_with_linescroll(bitmap, cliprect); return; } if (stv2_current_tilemap.bitmap_enable) // this layer is a bitmap { stv_vdp2_draw_basic_bitmap(bitmap, mycliprect); } else { //stv_vdp2_apply_window_on_layer(mycliprect); stv_vdp2_draw_basic_tilemap(bitmap, mycliprect); } /* post-processing functions (TODO: needs layer bitmaps to be individual planes to work correctly) */ if(stv2_current_tilemap.line_screen_enabled && TEST_FUNCTIONS) stv_vdp2_draw_line(bitmap,cliprect); if(stv2_current_tilemap.mosaic_screen_enabled && TEST_FUNCTIONS) stv_vdp2_draw_mosaic(bitmap,cliprect,stv2_current_tilemap.layer_name & 0x80); { if(stv2_current_tilemap.colour_depth == 2 && !stv2_current_tilemap.bitmap_enable) popmessage("2048 color mode used on a non-bitmap plane"); // if(STV_VDP2_SCXDN0 || STV_VDP2_SCXDN1 || STV_VDP2_SCYDN0 || STV_VDP2_SCYDN1) // popmessage("Fractional part scrolling write, contact MAMEdev"); /* Pukunpa */ //if(STV_VDP2_SPWINEN) // popmessage("Sprite Window enabled"); /* Capcom Collection Dai 2 - Choh Makaimura (Duh!) */ if(STV_VDP2_MZCTL & 0x1f && POPMESSAGE_DEBUG) popmessage("Mosaic control enabled = %04x\n",STV_VDP2_MZCTL); /* Bio Hazard bit 1 */ /* Airs Adventure 0x3e */ /* Bakuretsu Hunter */ if(STV_VDP2_LNCLEN & ~2 && POPMESSAGE_DEBUG) popmessage("Line Colour screen enabled %04x %08x, contact MAMEdev",STV_VDP2_LNCLEN,STV_VDP2_LCTAU<<16|STV_VDP2_LCTAL); /* Bio Hazard 0x400 = extended color calculation enabled */ /* Advanced World War 0x200 = color calculation ratio mode */ /* Whizz = 0x8100 */ /* Dark Saviour = 0x9051 on save select screen (the one with a Saturn in the background) */ if(STV_VDP2_CCCR & 0x6000) popmessage("Gradation enabled %04x, contact MAMEdev",STV_VDP2_CCCR); /* Advanced VG, Shining Force III */ if(STV_VDP2_SFCCMD && POPMESSAGE_DEBUG) popmessage("Special Color Calculation enable %04x, contact MAMEdev",STV_VDP2_SFCCMD); /* Cleopatra Fortune Transparent Shadow */ /* Pretty Fighter X Back & Transparent Shadow*/ //if(STV_VDP2_SDCTL & 0x0120) // popmessage("%s shadow select bit enabled, contact MAMEdev",STV_VDP2_SDCTL & 0x100 ? "Transparent" : "Back"); /* Langrisser III bit 3 normal, bit 1 during battle field */ /* Metal Slug bit 0 during gameplay */ /* Bug! Sega Away Logo onward 0x470 */ /* Command & Conquer 0x0004 0xc000 */ if(STV_VDP2_SFSEL & ~0x47f) popmessage("Special Function Code Select enable %04x %04x, contact MAMEdev",STV_VDP2_SFSEL,STV_VDP2_SFCODE); /* Albert Odyssey Gaiden 0x0001 */ /* Asuka 120% (doesn't make sense?) 0x0101 */ /* Slam n Jam 96 0x0003 */ if(STV_VDP2_ZMCTL & 0x0200) popmessage("Reduction enable %04x, contact MAMEdev",STV_VDP2_ZMCTL); /* Burning Rangers and friends FMV, J.League Pro Soccer Club Wo Tsukurou!! backgrounds */ if(STV_VDP2_SCRCTL & 0x0101 && POPMESSAGE_DEBUG) popmessage("Vertical cell scroll enable %04x, contact MAMEdev",STV_VDP2_SCRCTL); /* Magical Drop III 0x200 -> color calculation window */ /* Ide Yousuke Meijin No Shin Jissen Mahjong 0x0303 */ /* Decathlete 0x088 */ /* Sexy Parodius 0x2300 */ // if(STV_VDP2_WCTLD & 0x2000) // popmessage("Special window enabled %04x, contact MAMEdev",STV_VDP2_WCTLD); /* Shining Force III, After Burner 2 (doesn't make a proper use tho?) */ /* Layer Section */ //if(STV_VDP2_W0LWE || STV_VDP2_W1LWE) // popmessage("Line Window %s %08x enabled, contact MAMEdev",STV_VDP2_W0LWE ? "0" : "1",STV_VDP2_W0LWTA); /* Akumajou Dracula, bits 2-4 */ /* Arcana Strikes bit 5 */ /* Choh Makai Mura 0x0055 */ /* Sega Rally 0x0155 */ /* Find Love 0x4400 */ /* Dragon Ball Z 0x3800 - 0x2c00 */ /* Assault Suit Leynos 2 0x0200*/ /* Bug! 0x8800 */ /* Wonder 3 0x0018 */ if(STV_VDP2_SFPRMD & ~0xff7f) popmessage("Special Priority Mode enabled %04x, contact MAMEdev",STV_VDP2_SFPRMD); } } void saturn_state::stv_vdp2_copy_roz_bitmap(bitmap_rgb32 &bitmap, bitmap_rgb32 &roz_bitmap, const rectangle &cliprect, int iRP, int planesizex, int planesizey, int planerenderedsizex, int planerenderedsizey) { int32_t xsp, ysp, xp, yp, dx, dy, x, y, xs, ys, dxs, dys; int32_t vcnt, hcnt; int32_t kx, ky; int8_t use_coeff_table, coeff_table_mode, coeff_table_size, coeff_table_shift; int8_t screen_over_process; uint8_t vcnt_shift, hcnt_shift; uint8_t coeff_msb; uint32_t *coeff_table_base, coeff_table_offset; int32_t coeff_table_val; uint32_t address; uint32_t *line; rgb_t pix; //uint32_t coeff_line_color_screen_data; int32_t clipxmask = 0, clipymask = 0; vcnt_shift = ((STV_VDP2_LSMD & 3) == 3); hcnt_shift = ((STV_VDP2_HRES & 2) == 2); planesizex--; planesizey--; planerenderedsizex--; planerenderedsizey--; kx = RP.kx; ky = RP.ky; use_coeff_table = coeff_table_mode = coeff_table_size = coeff_table_shift = 0; coeff_table_offset = 0; coeff_table_val = 0; coeff_table_base = nullptr; if ( LOG_ROZ == 1 ) logerror( "Rendering RBG with parameter %s\n", iRP == 1 ? "A" : "B" ); if ( LOG_ROZ == 1 ) logerror( "RPMD (parameter mode) = %x\n", STV_VDP2_RPMD ); if ( LOG_ROZ == 1 ) logerror( "RPRCTL (parameter read control) = %04x\n", STV_VDP2_RPRCTL ); if ( LOG_ROZ == 1 ) logerror( "KTCTL (coefficient table control) = %04x\n", STV_VDP2_KTCTL ); if ( LOG_ROZ == 1 ) logerror( "KTAOF (coefficient table address offset) = %04x\n", STV_VDP2_KTAOF ); if ( LOG_ROZ == 1 ) logerror( "RAOVR (screen-over process) = %x\n", STV_VDP2_RAOVR ); if ( iRP == 1 ) { use_coeff_table = STV_VDP2_RAKTE; if ( use_coeff_table == 1 ) { coeff_table_mode = STV_VDP2_RAKMD; coeff_table_size = STV_VDP2_RAKDBS; coeff_table_offset = STV_VDP2_RAKTAOS; } screen_over_process = STV_VDP2_RAOVR; } else { use_coeff_table = STV_VDP2_RBKTE; if ( use_coeff_table == 1 ) { coeff_table_mode = STV_VDP2_RBKMD; coeff_table_size = STV_VDP2_RBKDBS; coeff_table_offset = STV_VDP2_RBKTAOS; } screen_over_process = STV_VDP2_RBOVR; } if ( use_coeff_table ) { if ( STV_VDP2_CRKTE == 0 ) { coeff_table_base = m_vdp2_vram.get(); } else { coeff_table_base = m_vdp2_cram.get(); } if ( coeff_table_size == 0 ) { coeff_table_offset = (coeff_table_offset & 0x0003) * 0x40000; coeff_table_shift = 2; } else { coeff_table_offset = (coeff_table_offset & 0x0007) * 0x20000; coeff_table_shift = 1; } } if ( stv2_current_tilemap.colour_calculation_enabled == 1 ) { if ( STV_VDP2_CCMD ) { stv2_current_tilemap.transparency = STV_TRANSPARENCY_ADD_BLEND; } else { stv2_current_tilemap.transparency = STV_TRANSPARENCY_ALPHA; } } /* clipping */ switch( screen_over_process ) { case 0: /* repeated */ clipxmask = clipymask = 0; break; case 1: /* screen over pattern, not supported */ clipxmask = clipymask = 0; break; case 2: /* outside display area, scroll screen is transparent */ clipxmask = ~planesizex; clipymask = ~planesizey; break; case 3: /* display area is 512x512, outside is transparent */ clipxmask = ~511; clipymask = ~511; break; } //dx = (RP.A * RP.dx) + (RP.B * RP.dy); //dy = (RP.D * RP.dx) + (RP.E * RP.dy); dx = mul_fixed32( RP.A, RP.dx ) + mul_fixed32( RP.B, RP.dy ); dy = mul_fixed32( RP.D, RP.dx ) + mul_fixed32( RP.E, RP.dy ); //xp = RP.A * ( RP.px - RP.cx ) + RP.B * ( RP.py - RP.cy ) + RP.C * ( RP.pz - RP.cz ) + RP.cx + RP.mx; //yp = RP.D * ( RP.px - RP.cx ) + RP.E * ( RP.py - RP.cy ) + RP.F * ( RP.pz - RP.cz ) + RP.cy + RP.my; xp = mul_fixed32( RP.A, RP.px - RP.cx ) + mul_fixed32( RP.B, RP.py - RP.cy ) + mul_fixed32( RP.C, RP.pz - RP.cz ) + RP.cx + RP.mx; yp = mul_fixed32( RP.D, RP.px - RP.cx ) + mul_fixed32( RP.E, RP.py - RP.cy ) + mul_fixed32( RP.F, RP.pz - RP.cz ) + RP.cy + RP.my; for (vcnt = cliprect.min_y; vcnt <= cliprect.max_y; vcnt++ ) { /*xsp = RP.A * ( ( RP.xst + RP.dxst * (vcnt << 16) ) - RP.px ) + RP.B * ( ( RP.yst + RP.dyst * (vcnt << 16) ) - RP.py ) + RP.C * ( RP.zst - RP.pz); ysp = RP.D * ( ( RP.xst + RP.dxst * (vcnt << 16) ) - RP.px ) + RP.E * ( ( RP.yst + RP.dyst * (vcnt << 16) ) - RP.py ) + RP.F * ( RP.zst - RP.pz );*/ xsp = mul_fixed32( RP.A, RP.xst + mul_fixed32( RP.dxst, vcnt << (16 - vcnt_shift)) - RP.px ) + mul_fixed32( RP.B, RP.yst + mul_fixed32( RP.dyst, vcnt << (16 - vcnt_shift)) - RP.py ) + mul_fixed32( RP.C, RP.zst - RP.pz ); ysp = mul_fixed32( RP.D, RP.xst + mul_fixed32( RP.dxst, vcnt << (16 - vcnt_shift)) - RP.px ) + mul_fixed32( RP.E, RP.yst + mul_fixed32( RP.dyst, vcnt << (16 - vcnt_shift)) - RP.py ) + mul_fixed32( RP.F, RP.zst - RP.pz ); //xp = RP.A * ( RP.px - RP.cx ) + RP.B * ( RP.py - RP.cy ) + RP.C * ( RP.pz - RP.cz ) + RP.cx + RP.mx; //yp = RP.D * ( RP.px - RP.cx ) + RP.E * ( RP.py - RP.cy ) + RP.F * ( RP.pz - RP.cz ) + RP.cy + RP.my; //dx = (RP.A * RP.dx) + (RP.B * RP.dy); //dy = (RP.D * RP.dx) + (RP.E * RP.dy); line = &bitmap.pix32(vcnt); // TODO: nuke this spaghetti code if ( !use_coeff_table || RP.dkax == 0 ) { if ( use_coeff_table ) { switch( coeff_table_size ) { case 0: address = coeff_table_offset + ((RP.kast + RP.dkast*(vcnt>>vcnt_shift)) >> 16) * 4; coeff_table_val = coeff_table_base[ address / 4 ]; //coeff_line_color_screen_data = (coeff_table_val & 0x7f000000) >> 24; coeff_msb = (coeff_table_val & 0x80000000) > 0; if ( coeff_table_val & 0x00800000 ) { coeff_table_val |= 0xff000000; } else { coeff_table_val &= 0x007fffff; } break; case 1: address = coeff_table_offset + ((RP.kast + RP.dkast*(vcnt>>vcnt_shift)) >> 16) * 2; coeff_table_val = coeff_table_base[ address / 4 ]; if ( (address & 2) == 0 ) { coeff_table_val >>= 16; } coeff_table_val &= 0xffff; //coeff_line_color_screen_data = 0; coeff_msb = (coeff_table_val & 0x8000) > 0; if ( coeff_table_val & 0x4000 ) { coeff_table_val |= 0xffff8000; } else { coeff_table_val &= 0x3fff; } coeff_table_val <<= 6; /* to form 16.16 fixed point val */ break; default: coeff_msb = 1; break; } if ( coeff_msb ) continue; switch( coeff_table_mode ) { case 0: kx = ky = coeff_table_val; break; case 1: kx = coeff_table_val; break; case 2: ky = coeff_table_val; break; case 3: xp = coeff_table_val; break; } } //x = RP.kx * ( xsp + dx * (hcnt << 16)) + xp; //y = RP.ky * ( ysp + dy * (hcnt << 16)) + yp; xs = mul_fixed32( kx, xsp ) + xp; ys = mul_fixed32( ky, ysp ) + yp; dxs = mul_fixed32( kx, mul_fixed32( dx, 1 << (16-hcnt_shift))); dys = mul_fixed32( ky, mul_fixed32( dy, 1 << (16-hcnt_shift))); for (hcnt = cliprect.min_x; hcnt <= cliprect.max_x; xs+=dxs, ys+=dys, hcnt++ ) { x = xs >> 16; y = ys >> 16; if ( x & clipxmask || y & clipymask ) continue; if ( stv2_current_tilemap.roz_mode3 == true ) { if( stv_vdp2_roz_mode3_window(hcnt, vcnt, iRP-1) == false ) continue; } pix = roz_bitmap.pix32(y & planerenderedsizey, x & planerenderedsizex); switch( stv2_current_tilemap.transparency ) { case STV_TRANSPARENCY_PEN: if (pix & 0xffffff) { if(stv2_current_tilemap.fade_control & 1) stv_vdp2_compute_color_offset_UINT32(&pix,stv2_current_tilemap.fade_control & 2); line[hcnt] = pix; } break; case STV_TRANSPARENCY_NONE: if(stv2_current_tilemap.fade_control & 1) stv_vdp2_compute_color_offset_UINT32(&pix,stv2_current_tilemap.fade_control & 2); line[hcnt] = pix; break; case STV_TRANSPARENCY_ALPHA: if (pix & 0xffffff) { if(stv2_current_tilemap.fade_control & 1) stv_vdp2_compute_color_offset_UINT32(&pix,stv2_current_tilemap.fade_control & 2); line[hcnt] = alpha_blend_r32( line[hcnt], pix, stv2_current_tilemap.alpha ); } break; case STV_TRANSPARENCY_ADD_BLEND: if (pix & 0xffffff) { if(stv2_current_tilemap.fade_control & 1) stv_vdp2_compute_color_offset_UINT32(&pix,stv2_current_tilemap.fade_control & 2); line[hcnt] = stv_add_blend( line[hcnt], pix ); } break; } } } else { for (hcnt = cliprect.min_x; hcnt <= cliprect.max_x; hcnt++ ) { switch( coeff_table_size ) { case 0: address = coeff_table_offset + ((RP.kast + RP.dkast*(vcnt>>vcnt_shift) + RP.dkax*hcnt) >> 16) * 4; coeff_table_val = coeff_table_base[ address / 4 ]; //coeff_line_color_screen_data = (coeff_table_val & 0x7f000000) >> 24; coeff_msb = (coeff_table_val & 0x80000000) > 0; if ( coeff_table_val & 0x00800000 ) { coeff_table_val |= 0xff000000; } else { coeff_table_val &= 0x007fffff; } break; case 1: address = coeff_table_offset + ((RP.kast + RP.dkast*(vcnt>>vcnt_shift) + RP.dkax*hcnt) >> 16) * 2; coeff_table_val = coeff_table_base[ address / 4 ]; if ( (address & 2) == 0 ) { coeff_table_val >>= 16; } coeff_table_val &= 0xffff; //coeff_line_color_screen_data = 0; coeff_msb = (coeff_table_val & 0x8000) > 0; if ( coeff_table_val & 0x4000 ) { coeff_table_val |= 0xffff8000; } else { coeff_table_val &= 0x3fff; } coeff_table_val <<= 6; /* to form 16.16 fixed point val */ break; default: coeff_msb = 1; break; } if ( coeff_msb ) continue; switch( coeff_table_mode ) { case 0: kx = ky = coeff_table_val; break; case 1: kx = coeff_table_val; break; case 2: ky = coeff_table_val; break; case 3: xp = coeff_table_val; break; } //x = RP.kx * ( xsp + dx * (hcnt << 16)) + xp; //y = RP.ky * ( ysp + dy * (hcnt << 16)) + yp; x = mul_fixed32( kx, xsp + mul_fixed32( dx, (hcnt>>hcnt_shift) << 16 ) ) + xp; y = mul_fixed32( ky, ysp + mul_fixed32( dy, (hcnt>>hcnt_shift) << 16 ) ) + yp; x >>= 16; y >>= 16; if ( x & clipxmask || y & clipymask ) continue; pix = roz_bitmap.pix32(y & planerenderedsizey, x & planerenderedsizex); switch( stv2_current_tilemap.transparency ) { case STV_TRANSPARENCY_PEN: if (pix & 0xffffff) { if(stv2_current_tilemap.fade_control & 1) stv_vdp2_compute_color_offset_UINT32(&pix,stv2_current_tilemap.fade_control & 2); line[hcnt] = pix; } break; case STV_TRANSPARENCY_NONE: if(stv2_current_tilemap.fade_control & 1) stv_vdp2_compute_color_offset_UINT32(&pix,stv2_current_tilemap.fade_control & 2); line[hcnt] = pix; break; case STV_TRANSPARENCY_ALPHA: if (pix & 0xffffff) { if(stv2_current_tilemap.fade_control & 1) stv_vdp2_compute_color_offset_UINT32(&pix,stv2_current_tilemap.fade_control & 2); line[hcnt] = alpha_blend_r32( line[hcnt], pix, stv2_current_tilemap.alpha ); } break; case STV_TRANSPARENCY_ADD_BLEND: if (pix & 0xffffff) { if(stv2_current_tilemap.fade_control & 1) stv_vdp2_compute_color_offset_UINT32(&pix,stv2_current_tilemap.fade_control & 2); line[hcnt] = stv_add_blend( line[hcnt], pix ); } break; } } } } } bool saturn_state::stv_vdp2_roz_mode3_window(int x, int y, int rot_parameter) { int s_x=0,e_x=0,s_y=0,e_y=0; int w0_pix, w1_pix; uint8_t logic = STV_VDP2_RPLOG; uint8_t w0_enable = STV_VDP2_RPW0E; uint8_t w1_enable = STV_VDP2_RPW1E; uint8_t w0_area = STV_VDP2_RPW0A; uint8_t w1_area = STV_VDP2_RPW1A; if (w0_enable == 0 && w1_enable == 0) return rot_parameter ^ 1; stv_vdp2_get_window0_coordinates(&s_x, &e_x, &s_y, &e_y); w0_pix = get_roz_mode3_window_pixel(s_x,e_x,s_y,e_y,x,y,w0_enable, w0_area); stv_vdp2_get_window1_coordinates(&s_x, &e_x, &s_y, &e_y); w1_pix = get_roz_mode3_window_pixel(s_x,e_x,s_y,e_y,x,y,w1_enable, w1_area); return (logic & 1 ? (w0_pix | w1_pix) : (w0_pix & w1_pix)) ^ rot_parameter; } int saturn_state::get_roz_mode3_window_pixel(int s_x,int e_x,int s_y,int e_y,int x, int y,uint8_t winenable, uint8_t winarea) { int res; res = 1; if(winenable) { if(winarea) res = (y >= s_y && y <= e_y && x >= s_x && x <= e_x); else res = (y >= s_y && y <= e_y && x >= s_x && x <= e_x) ^ 1; } return res; } void saturn_state::stv_vdp2_draw_NBG0(bitmap_rgb32 &bitmap, const rectangle &cliprect) { uint32_t base_mask; base_mask = STV_VDP2_VRAMSZ ? 0x7ffff : 0x3ffff; /* Colours : 16, 256, 2048, 32768, 16770000 Char Size : 1x1 cells, 2x2 cells Pattern Data Size : 1 word, 2 words Plane Layouts : 1 x 1, 2 x 1, 2 x 2 Planes : 4 Bitmap : Possible Bitmap Sizes : 512 x 256, 512 x 512, 1024 x 256, 1024 x 512 Scale : 0.25 x - 256 x Rotation : No Linescroll : Yes Column Scroll : Yes Mosaic : Yes */ stv2_current_tilemap.enabled = STV_VDP2_N0ON | STV_VDP2_R1ON; // if (!stv2_current_tilemap.enabled) return; // stop right now if its disabled ... //stv2_current_tilemap.trans_enabled = STV_VDP2_N0TPON; if ( STV_VDP2_N0CCEN ) { stv2_current_tilemap.colour_calculation_enabled = 1; stv2_current_tilemap.alpha = ((uint16_t)(0x1f-STV_VDP2_N0CCRT)*0xff)/0x1f; } else { stv2_current_tilemap.colour_calculation_enabled = 0; } if ( STV_VDP2_N0TPON == 0 ) { stv2_current_tilemap.transparency = STV_TRANSPARENCY_PEN; } else { stv2_current_tilemap.transparency = STV_TRANSPARENCY_NONE; } stv2_current_tilemap.colour_depth = STV_VDP2_N0CHCN; stv2_current_tilemap.tile_size = STV_VDP2_N0CHSZ; stv2_current_tilemap.bitmap_enable = STV_VDP2_N0BMEN; stv2_current_tilemap.bitmap_size = STV_VDP2_N0BMSZ; stv2_current_tilemap.bitmap_palette_number = STV_VDP2_N0BMP; stv2_current_tilemap.bitmap_map = STV_VDP2_N0MP_; stv2_current_tilemap.map_offset[0] = STV_VDP2_N0MPA | (STV_VDP2_N0MP_ << 6); stv2_current_tilemap.map_offset[1] = STV_VDP2_N0MPB | (STV_VDP2_N0MP_ << 6); stv2_current_tilemap.map_offset[2] = STV_VDP2_N0MPC | (STV_VDP2_N0MP_ << 6); stv2_current_tilemap.map_offset[3] = STV_VDP2_N0MPD | (STV_VDP2_N0MP_ << 6); stv2_current_tilemap.map_count = 4; stv2_current_tilemap.pattern_data_size = STV_VDP2_N0PNB; stv2_current_tilemap.character_number_supplement = STV_VDP2_N0CNSM; stv2_current_tilemap.special_priority_register = STV_VDP2_N0SPR; stv2_current_tilemap.special_colour_control_register = STV_VDP2_PNCN0; stv2_current_tilemap.supplementary_palette_bits = STV_VDP2_N0SPLT; stv2_current_tilemap.supplementary_character_bits = STV_VDP2_N0SPCN; stv2_current_tilemap.scrollx = STV_VDP2_SCXIN0; stv2_current_tilemap.scrolly = STV_VDP2_SCYIN0; stv2_current_tilemap.incx = STV_VDP2_ZMXN0; stv2_current_tilemap.incy = STV_VDP2_ZMYN0; stv2_current_tilemap.linescroll_enable = STV_VDP2_N0LSCX; stv2_current_tilemap.linescroll_interval = (((STV_VDP2_LSMD & 3) == 2) ? (2) : (1)) << (STV_VDP2_N0LSS); stv2_current_tilemap.linescroll_table_address = (((STV_VDP2_LSTA0U << 16) | STV_VDP2_LSTA0L) & base_mask) * 2; stv2_current_tilemap.vertical_linescroll_enable = STV_VDP2_N0LSCY; stv2_current_tilemap.linezoom_enable = STV_VDP2_N0LZMX; stv2_current_tilemap.plane_size = (STV_VDP2_R1ON) ? STV_VDP2_RBPLSZ : STV_VDP2_N0PLSZ; stv2_current_tilemap.colour_ram_address_offset = STV_VDP2_N0CAOS; stv2_current_tilemap.fade_control = (STV_VDP2_N0COEN * 1) | (STV_VDP2_N0COSL * 2); stv_vdp2_check_fade_control_for_layer(); stv2_current_tilemap.window_control.logic = STV_VDP2_N0LOG; stv2_current_tilemap.window_control.enabled[0] = STV_VDP2_N0W0E; stv2_current_tilemap.window_control.enabled[1] = STV_VDP2_N0W1E; // stv2_current_tilemap.window_control.? = STV_VDP2_N0SWE; stv2_current_tilemap.window_control.area[0] = STV_VDP2_N0W0A; stv2_current_tilemap.window_control.area[1] = STV_VDP2_N0W1A; // stv2_current_tilemap.window_control.? = STV_VDP2_N0SWA; stv2_current_tilemap.line_screen_enabled = STV_VDP2_N0LCEN; stv2_current_tilemap.mosaic_screen_enabled = STV_VDP2_N0MZE; stv2_current_tilemap.layer_name=(STV_VDP2_R1ON) ? 0x81 : 0; if ( stv2_current_tilemap.enabled && (!(STV_VDP2_R1ON))) /* TODO: check cycle pattern for RBG1 */ { stv2_current_tilemap.enabled = stv_vdp2_check_vram_cycle_pattern_registers( STV_VDP2_CP_NBG0_PNMDR, STV_VDP2_CP_NBG0_CPDR, stv2_current_tilemap.bitmap_enable ); } if(STV_VDP2_R1ON) stv_vdp2_draw_rotation_screen(bitmap, cliprect, 2 ); else stv_vdp2_check_tilemap(bitmap, cliprect); } void saturn_state::stv_vdp2_draw_NBG1(bitmap_rgb32 &bitmap, const rectangle &cliprect) { uint32_t base_mask; base_mask = STV_VDP2_VRAMSZ ? 0x7ffff : 0x3ffff; /* Colours : 16, 256, 2048, 32768 Char Size : 1x1 cells, 2x2 cells Pattern Data Size : 1 word, 2 words Plane Layouts : 1 x 1, 2 x 1, 2 x 2 Planes : 4 Bitmap : Possible Bitmap Sizes : 512 x 256, 512 x 512, 1024 x 256, 1024 x 512 Scale : 0.25 x - 256 x Rotation : No Linescroll : Yes Column Scroll : Yes Mosaic : Yes */ stv2_current_tilemap.enabled = STV_VDP2_N1ON; // if (!stv2_current_tilemap.enabled) return; // stop right now if its disabled ... //stv2_current_tilemap.trans_enabled = STV_VDP2_N1TPON; if ( STV_VDP2_N1CCEN ) { stv2_current_tilemap.colour_calculation_enabled = 1; stv2_current_tilemap.alpha = ((uint16_t)(0x1f-STV_VDP2_N1CCRT)*0xff)/0x1f; } else { stv2_current_tilemap.colour_calculation_enabled = 0; } if ( STV_VDP2_N1TPON == 0 ) { stv2_current_tilemap.transparency = STV_TRANSPARENCY_PEN; } else { stv2_current_tilemap.transparency = STV_TRANSPARENCY_NONE; } stv2_current_tilemap.colour_depth = STV_VDP2_N1CHCN; stv2_current_tilemap.tile_size = STV_VDP2_N1CHSZ; stv2_current_tilemap.bitmap_enable = STV_VDP2_N1BMEN; stv2_current_tilemap.bitmap_size = STV_VDP2_N1BMSZ; stv2_current_tilemap.bitmap_palette_number = STV_VDP2_N1BMP; stv2_current_tilemap.bitmap_map = STV_VDP2_N1MP_; stv2_current_tilemap.map_offset[0] = STV_VDP2_N1MPA | (STV_VDP2_N1MP_ << 6); stv2_current_tilemap.map_offset[1] = STV_VDP2_N1MPB | (STV_VDP2_N1MP_ << 6); stv2_current_tilemap.map_offset[2] = STV_VDP2_N1MPC | (STV_VDP2_N1MP_ << 6); stv2_current_tilemap.map_offset[3] = STV_VDP2_N1MPD | (STV_VDP2_N1MP_ << 6); stv2_current_tilemap.map_count = 4; stv2_current_tilemap.pattern_data_size = STV_VDP2_N1PNB; stv2_current_tilemap.character_number_supplement = STV_VDP2_N1CNSM; stv2_current_tilemap.special_priority_register = STV_VDP2_N1SPR; stv2_current_tilemap.special_colour_control_register = STV_VDP2_PNCN1; stv2_current_tilemap.supplementary_palette_bits = STV_VDP2_N1SPLT; stv2_current_tilemap.supplementary_character_bits = STV_VDP2_N1SPCN; stv2_current_tilemap.scrollx = STV_VDP2_SCXIN1; stv2_current_tilemap.scrolly = STV_VDP2_SCYIN1; stv2_current_tilemap.incx = STV_VDP2_ZMXN1; stv2_current_tilemap.incy = STV_VDP2_ZMYN1; stv2_current_tilemap.linescroll_enable = STV_VDP2_N1LSCX; stv2_current_tilemap.linescroll_interval = (((STV_VDP2_LSMD & 3) == 2) ? (2) : (1)) << (STV_VDP2_N1LSS); stv2_current_tilemap.linescroll_table_address = (((STV_VDP2_LSTA1U << 16) | STV_VDP2_LSTA1L) & base_mask) * 2; stv2_current_tilemap.vertical_linescroll_enable = STV_VDP2_N1LSCY; stv2_current_tilemap.linezoom_enable = STV_VDP2_N1LZMX; stv2_current_tilemap.plane_size = STV_VDP2_N1PLSZ; stv2_current_tilemap.colour_ram_address_offset = STV_VDP2_N1CAOS; stv2_current_tilemap.fade_control = (STV_VDP2_N1COEN * 1) | (STV_VDP2_N1COSL * 2); stv_vdp2_check_fade_control_for_layer(); stv2_current_tilemap.window_control.logic = STV_VDP2_N1LOG; stv2_current_tilemap.window_control.enabled[0] = STV_VDP2_N1W0E; stv2_current_tilemap.window_control.enabled[1] = STV_VDP2_N1W1E; // stv2_current_tilemap.window_control.? = STV_VDP2_N1SWE; stv2_current_tilemap.window_control.area[0] = STV_VDP2_N1W0A; stv2_current_tilemap.window_control.area[1] = STV_VDP2_N1W1A; // stv2_current_tilemap.window_control.? = STV_VDP2_N1SWA; stv2_current_tilemap.line_screen_enabled = STV_VDP2_N1LCEN; stv2_current_tilemap.mosaic_screen_enabled = STV_VDP2_N1MZE; stv2_current_tilemap.layer_name=1; if ( stv2_current_tilemap.enabled ) { stv2_current_tilemap.enabled = stv_vdp2_check_vram_cycle_pattern_registers( STV_VDP2_CP_NBG1_PNMDR, STV_VDP2_CP_NBG1_CPDR, stv2_current_tilemap.bitmap_enable ); } stv_vdp2_check_tilemap(bitmap, cliprect); } void saturn_state::stv_vdp2_draw_NBG2(bitmap_rgb32 &bitmap, const rectangle &cliprect) { /* NBG2 is the first of the 2 more basic tilemaps, it has exactly the same capabilities as NBG3 Colours : 16, 256 Char Size : 1x1 cells, 2x2 cells Pattern Data Size : 1 word, 2 words Plane Layouts : 1 x 1, 2 x 1, 2 x 2 Planes : 4 Bitmap : No Bitmap Sizes : N/A Scale : No Rotation : No Linescroll : No Column Scroll : No Mosaic : Yes */ stv2_current_tilemap.enabled = STV_VDP2_N2ON; /* these modes for N0 disable this layer */ if (STV_VDP2_N0CHCN == 0x03) stv2_current_tilemap.enabled = 0; if (STV_VDP2_N0CHCN == 0x04) stv2_current_tilemap.enabled = 0; // if (!stv2_current_tilemap.enabled) return; // stop right now if its disabled ... //stv2_current_tilemap.trans_enabled = STV_VDP2_N2TPON; if ( STV_VDP2_N2CCEN ) { stv2_current_tilemap.colour_calculation_enabled = 1; stv2_current_tilemap.alpha = ((uint16_t)(0x1f-STV_VDP2_N2CCRT)*0xff)/0x1f; } else { stv2_current_tilemap.colour_calculation_enabled = 0; } if ( STV_VDP2_N2TPON == 0 ) { stv2_current_tilemap.transparency = STV_TRANSPARENCY_PEN; } else { stv2_current_tilemap.transparency = STV_TRANSPARENCY_NONE; } stv2_current_tilemap.colour_depth = STV_VDP2_N2CHCN; stv2_current_tilemap.tile_size = STV_VDP2_N2CHSZ; /* this layer can't be a bitmap,so ignore these registers*/ stv2_current_tilemap.bitmap_enable = 0; stv2_current_tilemap.bitmap_size = 0; stv2_current_tilemap.bitmap_palette_number = 0; stv2_current_tilemap.bitmap_map = 0; stv2_current_tilemap.map_offset[0] = STV_VDP2_N2MPA | (STV_VDP2_N2MP_ << 6); stv2_current_tilemap.map_offset[1] = STV_VDP2_N2MPB | (STV_VDP2_N2MP_ << 6); stv2_current_tilemap.map_offset[2] = STV_VDP2_N2MPC | (STV_VDP2_N2MP_ << 6); stv2_current_tilemap.map_offset[3] = STV_VDP2_N2MPD | (STV_VDP2_N2MP_ << 6); stv2_current_tilemap.map_count = 4; stv2_current_tilemap.pattern_data_size = STV_VDP2_N2PNB; stv2_current_tilemap.character_number_supplement = STV_VDP2_N2CNSM; stv2_current_tilemap.special_priority_register = STV_VDP2_N2SPR; stv2_current_tilemap.special_colour_control_register = STV_VDP2_PNCN2; stv2_current_tilemap.supplementary_palette_bits = STV_VDP2_N2SPLT; stv2_current_tilemap.supplementary_character_bits = STV_VDP2_N2SPCN; stv2_current_tilemap.scrollx = STV_VDP2_SCXN2; stv2_current_tilemap.scrolly = STV_VDP2_SCYN2; /*This layer can't be scaled*/ stv2_current_tilemap.incx = 0x10000; stv2_current_tilemap.incy = 0x10000; stv2_current_tilemap.linescroll_enable = 0; stv2_current_tilemap.linescroll_interval = 0; stv2_current_tilemap.linescroll_table_address = 0; stv2_current_tilemap.vertical_linescroll_enable = 0; stv2_current_tilemap.linezoom_enable = 0; stv2_current_tilemap.colour_ram_address_offset = STV_VDP2_N2CAOS; stv2_current_tilemap.fade_control = (STV_VDP2_N2COEN * 1) | (STV_VDP2_N2COSL * 2); stv_vdp2_check_fade_control_for_layer(); stv2_current_tilemap.window_control.logic = STV_VDP2_N2LOG; stv2_current_tilemap.window_control.enabled[0] = STV_VDP2_N2W0E; stv2_current_tilemap.window_control.enabled[1] = STV_VDP2_N2W1E; // stv2_current_tilemap.window_control.? = STV_VDP2_N2SWE; stv2_current_tilemap.window_control.area[0] = STV_VDP2_N2W0A; stv2_current_tilemap.window_control.area[1] = STV_VDP2_N2W1A; // stv2_current_tilemap.window_control.? = STV_VDP2_N2SWA; stv2_current_tilemap.line_screen_enabled = STV_VDP2_N2LCEN; stv2_current_tilemap.mosaic_screen_enabled = STV_VDP2_N2MZE; stv2_current_tilemap.layer_name=2; stv2_current_tilemap.plane_size = STV_VDP2_N2PLSZ; if ( stv2_current_tilemap.enabled ) { stv2_current_tilemap.enabled = stv_vdp2_check_vram_cycle_pattern_registers( STV_VDP2_CP_NBG2_PNMDR, STV_VDP2_CP_NBG2_CPDR, stv2_current_tilemap.bitmap_enable ); } stv_vdp2_check_tilemap(bitmap, cliprect); } void saturn_state::stv_vdp2_draw_NBG3(bitmap_rgb32 &bitmap, const rectangle &cliprect) { /* NBG3 is the second of the 2 more basic tilemaps, it has exactly the same capabilities as NBG2 Colours : 16, 256 Char Size : 1x1 cells, 2x2 cells Pattern Data Size : 1 word, 2 words Plane Layouts : 1 x 1, 2 x 1, 2 x 2 Planes : 4 Bitmap : No Bitmap Sizes : N/A Scale : No Rotation : No Linescroll : No Column Scroll : No Mosaic : Yes */ stv2_current_tilemap.enabled = STV_VDP2_N3ON; // if (!stv2_current_tilemap.enabled) return; // stop right now if its disabled ... /* these modes for N1 disable this layer */ if (STV_VDP2_N1CHCN == 0x03) stv2_current_tilemap.enabled = 0; if (STV_VDP2_N1CHCN == 0x04) stv2_current_tilemap.enabled = 0; //stv2_current_tilemap.trans_enabled = STV_VDP2_N3TPON; if ( STV_VDP2_N3CCEN ) { stv2_current_tilemap.colour_calculation_enabled = 1; stv2_current_tilemap.alpha = ((uint16_t)(0x1f-STV_VDP2_N3CCRT)*0xff)/0x1f; } else { stv2_current_tilemap.colour_calculation_enabled = 0; } if ( STV_VDP2_N3TPON == 0 ) { stv2_current_tilemap.transparency = STV_TRANSPARENCY_PEN; } else { stv2_current_tilemap.transparency = STV_TRANSPARENCY_NONE; } stv2_current_tilemap.colour_depth = STV_VDP2_N3CHCN; stv2_current_tilemap.tile_size = STV_VDP2_N3CHSZ; /* this layer can't be a bitmap,so ignore these registers*/ stv2_current_tilemap.bitmap_enable = 0; stv2_current_tilemap.bitmap_size = 0; stv2_current_tilemap.bitmap_palette_number = 0; stv2_current_tilemap.bitmap_map = 0; stv2_current_tilemap.map_offset[0] = STV_VDP2_N3MPA | (STV_VDP2_N3MP_ << 6); stv2_current_tilemap.map_offset[1] = STV_VDP2_N3MPB | (STV_VDP2_N3MP_ << 6); stv2_current_tilemap.map_offset[2] = STV_VDP2_N3MPC | (STV_VDP2_N3MP_ << 6); stv2_current_tilemap.map_offset[3] = STV_VDP2_N3MPD | (STV_VDP2_N3MP_ << 6); stv2_current_tilemap.map_count = 4; stv2_current_tilemap.pattern_data_size = STV_VDP2_N3PNB; stv2_current_tilemap.character_number_supplement = STV_VDP2_N3CNSM; stv2_current_tilemap.special_priority_register = STV_VDP2_N3SPR; stv2_current_tilemap.special_colour_control_register = STV_VDP2_N3SCC; stv2_current_tilemap.supplementary_palette_bits = STV_VDP2_N3SPLT; stv2_current_tilemap.supplementary_character_bits = STV_VDP2_N3SPCN; stv2_current_tilemap.scrollx = STV_VDP2_SCXN3; stv2_current_tilemap.scrolly = STV_VDP2_SCYN3; /*This layer can't be scaled*/ stv2_current_tilemap.incx = 0x10000; stv2_current_tilemap.incy = 0x10000; stv2_current_tilemap.linescroll_enable = 0; stv2_current_tilemap.linescroll_interval = 0; stv2_current_tilemap.linescroll_table_address = 0; stv2_current_tilemap.vertical_linescroll_enable = 0; stv2_current_tilemap.linezoom_enable = 0; stv2_current_tilemap.colour_ram_address_offset = STV_VDP2_N3CAOS; stv2_current_tilemap.fade_control = (STV_VDP2_N3COEN * 1) | (STV_VDP2_N3COSL * 2); stv_vdp2_check_fade_control_for_layer(); stv2_current_tilemap.window_control.logic = STV_VDP2_N3LOG; stv2_current_tilemap.window_control.enabled[0] = STV_VDP2_N3W0E; stv2_current_tilemap.window_control.enabled[1] = STV_VDP2_N3W1E; // stv2_current_tilemap.window_control.? = STV_VDP2_N3SWE; stv2_current_tilemap.window_control.area[0] = STV_VDP2_N3W0A; stv2_current_tilemap.window_control.area[1] = STV_VDP2_N3W1A; // stv2_current_tilemap.window_control.? = STV_VDP2_N3SWA; stv2_current_tilemap.line_screen_enabled = STV_VDP2_N3LCEN; stv2_current_tilemap.mosaic_screen_enabled = STV_VDP2_N3MZE; stv2_current_tilemap.layer_name=3; stv2_current_tilemap.plane_size = STV_VDP2_N3PLSZ; if ( stv2_current_tilemap.enabled ) { stv2_current_tilemap.enabled = stv_vdp2_check_vram_cycle_pattern_registers( STV_VDP2_CP_NBG3_PNMDR, STV_VDP2_CP_NBG3_CPDR, stv2_current_tilemap.bitmap_enable ); } stv_vdp2_check_tilemap(bitmap, cliprect); } void saturn_state::stv_vdp2_draw_rotation_screen(bitmap_rgb32 &bitmap, const rectangle &cliprect, int iRP) { rectangle roz_clip_rect, mycliprect; int planesizex = 0, planesizey = 0; int planerenderedsizex, planerenderedsizey; uint8_t colour_calculation_enabled; uint8_t fade_control; if ( iRP == 1) { stv2_current_tilemap.bitmap_map = STV_VDP2_RAMP_; stv2_current_tilemap.map_offset[0] = STV_VDP2_RAMPA | (STV_VDP2_RAMP_ << 6); stv2_current_tilemap.map_offset[1] = STV_VDP2_RAMPB | (STV_VDP2_RAMP_ << 6); stv2_current_tilemap.map_offset[2] = STV_VDP2_RAMPC | (STV_VDP2_RAMP_ << 6); stv2_current_tilemap.map_offset[3] = STV_VDP2_RAMPD | (STV_VDP2_RAMP_ << 6); stv2_current_tilemap.map_offset[4] = STV_VDP2_RAMPE | (STV_VDP2_RAMP_ << 6); stv2_current_tilemap.map_offset[5] = STV_VDP2_RAMPF | (STV_VDP2_RAMP_ << 6); stv2_current_tilemap.map_offset[6] = STV_VDP2_RAMPG | (STV_VDP2_RAMP_ << 6); stv2_current_tilemap.map_offset[7] = STV_VDP2_RAMPH | (STV_VDP2_RAMP_ << 6); stv2_current_tilemap.map_offset[8] = STV_VDP2_RAMPI | (STV_VDP2_RAMP_ << 6); stv2_current_tilemap.map_offset[9] = STV_VDP2_RAMPJ | (STV_VDP2_RAMP_ << 6); stv2_current_tilemap.map_offset[10] = STV_VDP2_RAMPK | (STV_VDP2_RAMP_ << 6); stv2_current_tilemap.map_offset[11] = STV_VDP2_RAMPL | (STV_VDP2_RAMP_ << 6); stv2_current_tilemap.map_offset[12] = STV_VDP2_RAMPM | (STV_VDP2_RAMP_ << 6); stv2_current_tilemap.map_offset[13] = STV_VDP2_RAMPN | (STV_VDP2_RAMP_ << 6); stv2_current_tilemap.map_offset[14] = STV_VDP2_RAMPO | (STV_VDP2_RAMP_ << 6); stv2_current_tilemap.map_offset[15] = STV_VDP2_RAMPP | (STV_VDP2_RAMP_ << 6); stv2_current_tilemap.map_count = 16; } else { stv2_current_tilemap.bitmap_map = STV_VDP2_RBMP_; stv2_current_tilemap.map_offset[0] = STV_VDP2_RBMPA | (STV_VDP2_RBMP_ << 6); stv2_current_tilemap.map_offset[1] = STV_VDP2_RBMPB | (STV_VDP2_RBMP_ << 6); stv2_current_tilemap.map_offset[2] = STV_VDP2_RBMPC | (STV_VDP2_RBMP_ << 6); stv2_current_tilemap.map_offset[3] = STV_VDP2_RBMPD | (STV_VDP2_RBMP_ << 6); stv2_current_tilemap.map_offset[4] = STV_VDP2_RBMPE | (STV_VDP2_RBMP_ << 6); stv2_current_tilemap.map_offset[5] = STV_VDP2_RBMPF | (STV_VDP2_RBMP_ << 6); stv2_current_tilemap.map_offset[6] = STV_VDP2_RBMPG | (STV_VDP2_RBMP_ << 6); stv2_current_tilemap.map_offset[7] = STV_VDP2_RBMPH | (STV_VDP2_RBMP_ << 6); stv2_current_tilemap.map_offset[8] = STV_VDP2_RBMPI | (STV_VDP2_RBMP_ << 6); stv2_current_tilemap.map_offset[9] = STV_VDP2_RBMPJ | (STV_VDP2_RBMP_ << 6); stv2_current_tilemap.map_offset[10] = STV_VDP2_RBMPK | (STV_VDP2_RBMP_ << 6); stv2_current_tilemap.map_offset[11] = STV_VDP2_RBMPL | (STV_VDP2_RBMP_ << 6); stv2_current_tilemap.map_offset[12] = STV_VDP2_RBMPM | (STV_VDP2_RBMP_ << 6); stv2_current_tilemap.map_offset[13] = STV_VDP2_RBMPN | (STV_VDP2_RBMP_ << 6); stv2_current_tilemap.map_offset[14] = STV_VDP2_RBMPO | (STV_VDP2_RBMP_ << 6); stv2_current_tilemap.map_offset[15] = STV_VDP2_RBMPP | (STV_VDP2_RBMP_ << 6); stv2_current_tilemap.map_count = 16; } stv_vdp2_fill_rotation_parameter_table(iRP); if ( iRP == 1 ) { stv2_current_tilemap.plane_size = STV_VDP2_RAPLSZ; } else { stv2_current_tilemap.plane_size = STV_VDP2_RBPLSZ; } if (stv2_current_tilemap.bitmap_enable) { switch (stv2_current_tilemap.bitmap_size) { case 0: planesizex=512; planesizey=256; break; case 1: planesizex=512; planesizey=512; break; case 2: planesizex=1024; planesizey=256; break; case 3: planesizex=1024; planesizey=512; break; } } else { switch( stv2_current_tilemap.plane_size ) { case 0: planesizex = planesizey = 2048; break; case 1: planesizex = 4096; planesizey = 2048; break; case 2: planesizex = 0; planesizey = 0; break; case 3: planesizex = planesizey = 4096; break; } } if ( stv_vdp2_is_rotation_applied() == 0 ) { stv2_current_tilemap.scrollx = stv_current_rotation_parameter_table.mx >> 16; stv2_current_tilemap.scrolly = stv_current_rotation_parameter_table.my >> 16; stv_vdp2_check_tilemap(bitmap,cliprect); } else { if ( !m_vdp2.roz_bitmap[iRP-1].valid() ) m_vdp2.roz_bitmap[iRP-1].allocate(4096, 4096); roz_clip_rect.min_x = roz_clip_rect.min_y = 0; if ( (iRP == 1 && STV_VDP2_RAOVR == 3) || (iRP == 2 && STV_VDP2_RBOVR == 3) ) { roz_clip_rect.max_x = roz_clip_rect.max_y = 511; planerenderedsizex = planerenderedsizey = 512; } else if (stv_vdp2_are_map_registers_equal() && !stv2_current_tilemap.bitmap_enable) { roz_clip_rect.max_x = (planesizex / 4) - 1; roz_clip_rect.max_y = (planesizey / 4) - 1; planerenderedsizex = planesizex / 4; planerenderedsizey = planesizey / 4; } else { roz_clip_rect.max_x = planesizex - 1; roz_clip_rect.max_y = planesizey - 1; planerenderedsizex = planesizex; planerenderedsizey = planesizey; } colour_calculation_enabled = stv2_current_tilemap.colour_calculation_enabled; stv2_current_tilemap.colour_calculation_enabled = 0; // window_control = stv2_current_tilemap.window_control; // stv2_current_tilemap.window_control = 0; fade_control = stv2_current_tilemap.fade_control; stv2_current_tilemap.fade_control = 0; g_profiler.start(PROFILER_USER1); if ( LOG_VDP2 ) logerror( "Checking for cached RBG bitmap, cache_dirty = %d, memcmp() = %d\n", stv_rbg_cache_data.is_cache_dirty, memcmp(&stv_rbg_cache_data.layer_data[iRP-1],&stv2_current_tilemap,sizeof(stv2_current_tilemap))); if ( (stv_rbg_cache_data.is_cache_dirty & iRP) || memcmp(&stv_rbg_cache_data.layer_data[iRP-1],&stv2_current_tilemap,sizeof(stv2_current_tilemap)) != 0 ) { m_vdp2.roz_bitmap[iRP-1].fill(m_palette->black_pen(), roz_clip_rect ); stv_vdp2_check_tilemap(m_vdp2.roz_bitmap[iRP-1], roz_clip_rect); // prepare cache data stv_rbg_cache_data.watch_vdp2_vram_writes |= iRP; stv_rbg_cache_data.is_cache_dirty &= ~iRP; memcpy(&stv_rbg_cache_data.layer_data[iRP-1], &stv2_current_tilemap, sizeof(stv2_current_tilemap)); stv_rbg_cache_data.map_offset_min[iRP-1] = stv_vdp2_layer_data_placement.map_offset_min; stv_rbg_cache_data.map_offset_max[iRP-1] = stv_vdp2_layer_data_placement.map_offset_max; stv_rbg_cache_data.tile_offset_min[iRP-1] = stv_vdp2_layer_data_placement.tile_offset_min; stv_rbg_cache_data.tile_offset_max[iRP-1] = stv_vdp2_layer_data_placement.tile_offset_max; if ( LOG_VDP2 ) logerror( "Cache watch: map = %06X - %06X, tile = %06X - %06X\n", stv_rbg_cache_data.map_offset_min[iRP-1], stv_rbg_cache_data.map_offset_max[iRP-1], stv_rbg_cache_data.tile_offset_min[iRP-1], stv_rbg_cache_data.tile_offset_max[iRP-1] ); } g_profiler.stop(); stv2_current_tilemap.colour_calculation_enabled = colour_calculation_enabled; if ( colour_calculation_enabled ) { stv2_current_tilemap.transparency = STV_TRANSPARENCY_ALPHA; } mycliprect = cliprect; /* TODO: remove me. */ if ( stv2_current_tilemap.window_control.enabled[0] || stv2_current_tilemap.window_control.enabled[1] ) { //popmessage("Window control for RBG"); stv_vdp2_apply_window_on_layer(mycliprect); stv2_current_tilemap.window_control.enabled[0] = 0; stv2_current_tilemap.window_control.enabled[1] = 0; } stv2_current_tilemap.fade_control = fade_control; g_profiler.start(PROFILER_USER2); stv_vdp2_copy_roz_bitmap(bitmap, m_vdp2.roz_bitmap[iRP-1], mycliprect, iRP, planesizex, planesizey, planerenderedsizex, planerenderedsizey ); g_profiler.stop(); } } void saturn_state::stv_vdp2_draw_RBG0(bitmap_rgb32 &bitmap, const rectangle &cliprect) { /* Colours : 16, 256, 2048, 32768, 16770000 Char Size : 1x1 cells, 2x2 cells Pattern Data Size : 1 word, 2 words Plane Layouts : 1 x 1, 2 x 1, 2 x 2 Planes : 4 Bitmap : Possible Bitmap Sizes : 512 x 256, 512 x 512, 1024 x 256, 1024 x 512 Scale : 0.25 x - 256 x Rotation : Yes Linescroll : Yes Column Scroll : Yes Mosaic : Yes */ stv2_current_tilemap.enabled = STV_VDP2_R0ON; // if (!stv2_current_tilemap.enabled) return; // stop right now if its disabled ... //stv2_current_tilemap.trans_enabled = STV_VDP2_R0TPON; if ( STV_VDP2_R0CCEN ) { stv2_current_tilemap.colour_calculation_enabled = 1; stv2_current_tilemap.alpha = ((uint16_t)(0x1f-STV_VDP2_R0CCRT)*0xff)/0x1f; } else { stv2_current_tilemap.colour_calculation_enabled = 0; } if ( STV_VDP2_R0TPON == 0 ) { stv2_current_tilemap.transparency = STV_TRANSPARENCY_PEN; } else { stv2_current_tilemap.transparency = STV_TRANSPARENCY_NONE; } stv2_current_tilemap.colour_depth = STV_VDP2_R0CHCN; stv2_current_tilemap.tile_size = STV_VDP2_R0CHSZ; stv2_current_tilemap.bitmap_enable = STV_VDP2_R0BMEN; stv2_current_tilemap.bitmap_size = STV_VDP2_R0BMSZ; stv2_current_tilemap.bitmap_palette_number = STV_VDP2_R0BMP; stv2_current_tilemap.pattern_data_size = STV_VDP2_R0PNB; stv2_current_tilemap.character_number_supplement = STV_VDP2_R0CNSM; stv2_current_tilemap.special_priority_register = STV_VDP2_R0SPR; stv2_current_tilemap.special_colour_control_register = STV_VDP2_R0SCC; stv2_current_tilemap.supplementary_palette_bits = STV_VDP2_R0SPLT; stv2_current_tilemap.supplementary_character_bits = STV_VDP2_R0SPCN; stv2_current_tilemap.colour_ram_address_offset = STV_VDP2_R0CAOS; stv2_current_tilemap.fade_control = (STV_VDP2_R0COEN * 1) | (STV_VDP2_R0COSL * 2); stv_vdp2_check_fade_control_for_layer(); stv2_current_tilemap.window_control.logic = STV_VDP2_R0LOG; stv2_current_tilemap.window_control.enabled[0] = STV_VDP2_R0W0E; stv2_current_tilemap.window_control.enabled[1] = STV_VDP2_R0W1E; // stv2_current_tilemap.window_control.? = STV_VDP2_R0SWE; stv2_current_tilemap.window_control.area[0] = STV_VDP2_R0W0A; stv2_current_tilemap.window_control.area[1] = STV_VDP2_R0W1A; // stv2_current_tilemap.window_control.? = STV_VDP2_R0SWA; stv2_current_tilemap.scrollx = 0; stv2_current_tilemap.scrolly = 0; stv2_current_tilemap.incx = 0x10000; stv2_current_tilemap.incy = 0x10000; stv2_current_tilemap.linescroll_enable = 0; stv2_current_tilemap.linescroll_interval = 0; stv2_current_tilemap.linescroll_table_address = 0; stv2_current_tilemap.vertical_linescroll_enable = 0; stv2_current_tilemap.linezoom_enable = 0; stv2_current_tilemap.line_screen_enabled = STV_VDP2_R0LCEN; stv2_current_tilemap.mosaic_screen_enabled = STV_VDP2_R0MZE; /*Use 0x80 as a normal/rotate switch*/ stv2_current_tilemap.layer_name=0x80; if ( !stv2_current_tilemap.enabled ) return; switch(STV_VDP2_RPMD) { case 0://Rotation Parameter A stv2_current_tilemap.roz_mode3 = false; stv_vdp2_draw_rotation_screen(bitmap, cliprect, 1 ); break; case 1://Rotation Parameter B //case 2: stv2_current_tilemap.roz_mode3 = false; stv_vdp2_draw_rotation_screen(bitmap, cliprect, 2 ); break; case 2://Rotation Parameter A & B CKTE stv2_current_tilemap.roz_mode3 = false; stv_vdp2_draw_rotation_screen(bitmap, cliprect, 2 ); stv_vdp2_draw_rotation_screen(bitmap, cliprect, 1 ); break; case 3://Rotation Parameter A & B Window stv2_current_tilemap.roz_mode3 = true; stv_vdp2_draw_rotation_screen(bitmap, cliprect, 2 ); stv_vdp2_draw_rotation_screen(bitmap, cliprect, 1 ); break; } } void saturn_state::stv_vdp2_draw_back(bitmap_rgb32 &bitmap, const rectangle &cliprect) { int x,y; uint8_t* gfxdata = m_vdp2.gfx_decode.get(); uint32_t base_offs,base_mask; uint8_t interlace; interlace = (STV_VDP2_LSMD == 3)+1; // popmessage("Back screen %08x %08x %08x",STV_VDP2_BDCLMD,STV_VDP2_BKCLMD,STV_VDP2_BKTA); /* draw black if BDCLMD and DISP are cleared */ if(!(STV_VDP2_BDCLMD) && !(STV_VDP2_DISP)) bitmap.fill(m_palette->black_pen(), cliprect); else { base_mask = STV_VDP2_VRAMSZ ? 0x7ffff : 0x3ffff; for(y=cliprect.min_y;y<=cliprect.max_y;y++) { base_offs = ((STV_VDP2_BKTA ) & base_mask) << 1; if(STV_VDP2_BKCLMD) base_offs += ((y / interlace) << 1); for(x=cliprect.min_x;x<=cliprect.max_x;x++) { int r,g,b; uint16_t dot; dot = (gfxdata[base_offs+0]<<8)|gfxdata[base_offs+1]; b = pal5bit((dot & 0x7c00) >> 10); g = pal5bit((dot & 0x03e0) >> 5); r = pal5bit( dot & 0x001f); if(STV_VDP2_BKCOEN) stv_vdp2_compute_color_offset( &r, &g, &b, STV_VDP2_BKCOSL ); bitmap.pix32(y, x) = rgb_t(r, g, b); } } } } READ32_MEMBER ( saturn_state::saturn_vdp2_vram_r ) { return m_vdp2_vram[offset]; } WRITE32_MEMBER ( saturn_state::saturn_vdp2_vram_w ) { uint8_t* gfxdata = m_vdp2.gfx_decode.get(); COMBINE_DATA(&m_vdp2_vram[offset]); data = m_vdp2_vram[offset]; /* put in gfx region for easy decoding */ gfxdata[offset*4+0] = (data & 0xff000000) >> 24; gfxdata[offset*4+1] = (data & 0x00ff0000) >> 16; gfxdata[offset*4+2] = (data & 0x0000ff00) >> 8; gfxdata[offset*4+3] = (data & 0x000000ff) >> 0; m_gfxdecode->gfx(0)->mark_dirty(offset/8); m_gfxdecode->gfx(1)->mark_dirty(offset/8); m_gfxdecode->gfx(2)->mark_dirty(offset/8); m_gfxdecode->gfx(3)->mark_dirty(offset/8); /* 8-bit tiles overlap, so this affects the previous one as well */ if (offset/8 != 0) { m_gfxdecode->gfx(2)->mark_dirty(offset/8 - 1); m_gfxdecode->gfx(3)->mark_dirty(offset/8 - 1); } if ( stv_rbg_cache_data.watch_vdp2_vram_writes ) { if ( stv_rbg_cache_data.watch_vdp2_vram_writes & STV_VDP2_RBG_ROTATION_PARAMETER_A ) { if ( (offset >= stv_rbg_cache_data.map_offset_min[0] && offset < stv_rbg_cache_data.map_offset_max[0]) || (offset >= stv_rbg_cache_data.tile_offset_min[0] && offset < stv_rbg_cache_data.tile_offset_max[0]) ) { if ( LOG_VDP2 ) logerror( "RBG Cache: dirtying for RP = 1, write at offset = %06X\n", offset ); stv_rbg_cache_data.is_cache_dirty |= STV_VDP2_RBG_ROTATION_PARAMETER_A; stv_rbg_cache_data.watch_vdp2_vram_writes &= ~STV_VDP2_RBG_ROTATION_PARAMETER_A; } } if ( stv_rbg_cache_data.watch_vdp2_vram_writes & STV_VDP2_RBG_ROTATION_PARAMETER_B ) { if ( (offset >= stv_rbg_cache_data.map_offset_min[1] && offset < stv_rbg_cache_data.map_offset_max[1]) || (offset >= stv_rbg_cache_data.tile_offset_min[1] && offset < stv_rbg_cache_data.tile_offset_max[1]) ) { if ( LOG_VDP2 ) logerror( "RBG Cache: dirtying for RP = 2, write at offset = %06X\n", offset ); stv_rbg_cache_data.is_cache_dirty |= STV_VDP2_RBG_ROTATION_PARAMETER_B; stv_rbg_cache_data.watch_vdp2_vram_writes &= ~STV_VDP2_RBG_ROTATION_PARAMETER_B; } } } } READ16_MEMBER ( saturn_state::saturn_vdp2_regs_r ) { switch(offset) { case 0x002/2: { /* latch h/v signals through HV latch*/ if(!STV_VDP2_EXLTEN) { if(!machine().side_effects_disabled()) { m_vdp2.h_count = get_hcounter(); m_vdp2.v_count = get_vcounter(); /* latch flag */ m_vdp2.exltfg |= 1; } } break; } case 0x004/2: { /*Screen Status Register*/ /*VBLANK HBLANK ODD PAL */ m_vdp2_regs[offset] = (m_vdp2.exltfg<<9) | (m_vdp2.exsyfg<<8) | (get_vblank() << 3) | (get_hblank() << 2) | (get_odd_bit() << 1) | (m_vdp2.pal << 0); /* vblank bit is always 1 if DISP bit is disabled */ if(!STV_VDP2_DISP) m_vdp2_regs[offset] |= 1 << 3; /* HV latches clears if this register is read */ if(!machine().side_effects_disabled()) { m_vdp2.exltfg &= ~1; m_vdp2.exsyfg &= ~1; } break; } case 0x006/2: { m_vdp2_regs[offset] = (STV_VDP2_VRAMSZ << 15) | ((0 << 0) & 0xf); // VDP2 version /* Games basically r/w the entire VDP2 register area when this is tripped. (example: Silhouette Mirage) Disable log for the time being. */ //if(!machine().side_effects_disabled()) // printf("Warning: VDP2 version read\n"); break; } /* HCNT */ case 0x008/2: { m_vdp2_regs[offset] = (m_vdp2.h_count); break; } /* VCNT */ case 0x00a/2: { m_vdp2_regs[offset] = (m_vdp2.v_count); break; } default: //if(!machine().side_effects_disabled()) // printf("VDP2: read from register %08x %08x\n",offset*4,mem_mask); break; } return m_vdp2_regs[offset]; } READ32_MEMBER ( saturn_state::saturn_vdp2_cram_r ) { offset &= (0xfff) >> (2); return m_vdp2_cram[offset]; } WRITE32_MEMBER ( saturn_state::saturn_vdp2_cram_w ) { int r,g,b; uint8_t cmode0; cmode0 = (STV_VDP2_CRMD & 3) == 0; offset &= (0xfff) >> (2); COMBINE_DATA(&m_vdp2_cram[offset]); switch( STV_VDP2_CRMD ) { /*Mode 2/3*/ case 2: case 3: { //offset &= (0xfff) >> 2; b = ((m_vdp2_cram[offset] & 0x00ff0000) >> 16); g = ((m_vdp2_cram[offset] & 0x0000ff00) >> 8); r = ((m_vdp2_cram[offset] & 0x000000ff) >> 0); m_palette->set_pen_color(offset,rgb_t(r,g,b)); m_palette->set_pen_color(offset^0x400,rgb_t(r,g,b)); } break; /*Mode 0*/ case 0: case 1: { offset &= (0xfff) >> (cmode0+2); b = ((m_vdp2_cram[offset] & 0x00007c00) >> 10); g = ((m_vdp2_cram[offset] & 0x000003e0) >> 5); r = ((m_vdp2_cram[offset] & 0x0000001f) >> 0); m_palette->set_pen_color((offset*2)+1,pal5bit(r),pal5bit(g),pal5bit(b)); if(cmode0) m_palette->set_pen_color(((offset*2)+1)^0x400,pal5bit(r),pal5bit(g),pal5bit(b)); b = ((m_vdp2_cram[offset] & 0x7c000000) >> 26); g = ((m_vdp2_cram[offset] & 0x03e00000) >> 21); r = ((m_vdp2_cram[offset] & 0x001f0000) >> 16); m_palette->set_pen_color(offset*2,pal5bit(r),pal5bit(g),pal5bit(b)); if(cmode0) m_palette->set_pen_color((offset*2)^0x400,pal5bit(r),pal5bit(g),pal5bit(b)); } break; } } void saturn_state::refresh_palette_data( void ) { int r,g,b; int c_i; uint8_t bank; switch( STV_VDP2_CRMD ) { case 2: case 3: { for(c_i=0;c_i<0x400;c_i++) { b = ((m_vdp2_cram[c_i] & 0x00ff0000) >> 16); g = ((m_vdp2_cram[c_i] & 0x0000ff00) >> 8); r = ((m_vdp2_cram[c_i] & 0x000000ff) >> 0); m_palette->set_pen_color(c_i,rgb_t(r,g,b)); m_palette->set_pen_color(c_i+0x400,rgb_t(r,g,b)); } } break; case 0: { for(bank=0;bank<2;bank++) { for(c_i=0;c_i<0x400;c_i++) { b = ((m_vdp2_cram[c_i] & 0x00007c00) >> 10); g = ((m_vdp2_cram[c_i] & 0x000003e0) >> 5); r = ((m_vdp2_cram[c_i] & 0x0000001f) >> 0); m_palette->set_pen_color((c_i*2)+1+bank*0x400,pal5bit(r),pal5bit(g),pal5bit(b)); b = ((m_vdp2_cram[c_i] & 0x7c000000) >> 26); g = ((m_vdp2_cram[c_i] & 0x03e00000) >> 21); r = ((m_vdp2_cram[c_i] & 0x001f0000) >> 16); m_palette->set_pen_color(c_i*2+bank*0x400,pal5bit(r),pal5bit(g),pal5bit(b)); } } } break; case 1: { for(c_i=0;c_i<0x800;c_i++) { b = ((m_vdp2_cram[c_i] & 0x00007c00) >> 10); g = ((m_vdp2_cram[c_i] & 0x000003e0) >> 5); r = ((m_vdp2_cram[c_i] & 0x0000001f) >> 0); m_palette->set_pen_color((c_i*2)+1,pal5bit(r),pal5bit(g),pal5bit(b)); b = ((m_vdp2_cram[c_i] & 0x7c000000) >> 26); g = ((m_vdp2_cram[c_i] & 0x03e00000) >> 21); r = ((m_vdp2_cram[c_i] & 0x001f0000) >> 16); m_palette->set_pen_color(c_i*2,pal5bit(r),pal5bit(g),pal5bit(b)); } } break; } } WRITE16_MEMBER ( saturn_state::saturn_vdp2_regs_w ) { COMBINE_DATA(&m_vdp2_regs[offset]); if(m_vdp2.old_crmd != STV_VDP2_CRMD) { m_vdp2.old_crmd = STV_VDP2_CRMD; refresh_palette_data(); } if(m_vdp2.old_tvmd != STV_VDP2_TVMD) { m_vdp2.old_tvmd = STV_VDP2_TVMD; stv_vdp2_dynamic_res_change(); } if(STV_VDP2_VRAMSZ) printf("VDP2 sets up 8 Mbit VRAM!\n"); } int saturn_state::get_hblank_duration( void ) { int res; res = (STV_VDP2_HRES & 1) ? 455 : 427; /* double pump horizontal max res */ if(STV_VDP2_HRES & 2) res<<=1; return res; } /*some vblank lines measurements (according to Charles MacDonald)*/ /* TODO: interlace mode "eats" one line, should be 262.5 */ int saturn_state::get_vblank_duration( void ) { int res; res = (m_vdp2.pal) ? 313 : 263; /* compensate for interlacing */ if((STV_VDP2_LSMD & 3) == 3) res<<=1; if(STV_VDP2_HRES & 4) res = (STV_VDP2_HRES & 1) ? 561 : 525; //Hi-Vision / 31kHz Monitor return res; } int saturn_state::get_pixel_clock( void ) { int res,divider; res = (m_vdp2.dotsel ? MASTER_CLOCK_352 : MASTER_CLOCK_320).value(); /* TODO: divider is ALWAYS 8, this thing is just to over-compensate for MAME framework faults ... */ divider = 8; if(STV_VDP2_HRES & 2) divider>>=1; if((STV_VDP2_LSMD & 3) == 3) divider>>=1; if(STV_VDP2_HRES & 4) //TODO divider>>=1; return res/divider; } /* TODO: hblank position and hblank firing doesn't really match HW behaviour. */ uint8_t saturn_state::get_hblank( void ) { const rectangle &visarea = m_screen->visible_area(); int cur_h = m_screen->hpos(); if (cur_h > visarea.max_x) //TODO return 1; return 0; } uint8_t saturn_state::get_vblank( void ) { int cur_v,vblank; cur_v = m_screen->vpos(); vblank = get_vblank_start_position() * get_ystep_count(); if (cur_v >= vblank) return 1; return 0; } uint8_t saturn_state::get_odd_bit( void ) { if(STV_VDP2_HRES & 4) //exclusive monitor mode makes this bit to be always 1 return 1; // TODO: seabass explicitly wants this bit to be 0 when screen is disabled from bios to game transition. // But the documentation claims that "non-interlaced" mode is always 1. // grdforce tests this bit to be 1 from title screen to gameplay, ditto for finlarch/sasissu/magzun. // Assume documentation is wrong and actually always flip this bit. return m_vdp2.odd;//m_screen->frame_number() & 1; } int saturn_state::get_vblank_start_position( void ) { // TODO: test says that second setting happens at 241, might need further investigation ... // also first one happens at 240, but needs mods in SMPC otherwise we get 2 credits at startup in shanhigw and sokyugrt // (i.e. make a special screen device that handles this for us) const int d_vres[4] = { 224, 240, 256, 256 }; int vres_mask; int vblank_line; vres_mask = (m_vdp2.pal << 1)|1; //PAL uses mask 3, NTSC uses mask 1 vblank_line = d_vres[STV_VDP2_VRES & vres_mask]; return vblank_line; } int saturn_state::get_ystep_count( void ) { int max_y = m_screen->height(); int y_step; y_step = 2; if((max_y == 263 && m_vdp2.pal == 0) || (max_y == 313 && m_vdp2.pal == 1)) y_step = 1; return y_step; } /* TODO: these needs to be checked via HW tests! */ int saturn_state::get_hcounter( void ) { int hcount; hcount = m_screen->hpos(); switch(STV_VDP2_HRES & 6) { /* Normal */ case 0: hcount &= 0x1ff; hcount <<= 1; break; /* Hi-Res */ case 2: hcount &= 0x3ff; break; /* Exclusive Normal*/ case 4: hcount &= 0x1ff; break; /* Exclusive Hi-Res */ case 6: hcount >>= 1; hcount &= 0x1ff; break; } return hcount; } int saturn_state::get_vcounter( void ) { int vcount; vcount = m_screen->vpos(); /* Exclusive Monitor */ if(STV_VDP2_HRES & 4) return vcount & 0x3ff; /* Double Density Interlace */ if((STV_VDP2_LSMD & 3) == 3) return (vcount & ~1) | (m_screen->frame_number() & 1); /* docs says << 1, but according to HW tests it's a typo. */ assert((vcount & 0x1ff) < ARRAY_LENGTH(true_vcount)); return (true_vcount[vcount & 0x1ff][STV_VDP2_VRES]); // Non-interlace } void saturn_state::stv_vdp2_state_save_postload( void ) { uint8_t *gfxdata = m_vdp2.gfx_decode.get(); int offset; uint32_t data; for ( offset = 0; offset < 0x100000/4; offset++ ) { data = m_vdp2_vram[offset]; /* put in gfx region for easy decoding */ gfxdata[offset*4+0] = (data & 0xff000000) >> 24; gfxdata[offset*4+1] = (data & 0x00ff0000) >> 16; gfxdata[offset*4+2] = (data & 0x0000ff00) >> 8; gfxdata[offset*4+3] = (data & 0x000000ff) >> 0; m_gfxdecode->gfx(0)->mark_dirty(offset/8); m_gfxdecode->gfx(1)->mark_dirty(offset/8); m_gfxdecode->gfx(2)->mark_dirty(offset/8); m_gfxdecode->gfx(3)->mark_dirty(offset/8); /* 8-bit tiles overlap, so this affects the previous one as well */ if (offset/8 != 0) { m_gfxdecode->gfx(2)->mark_dirty(offset/8 - 1); m_gfxdecode->gfx(3)->mark_dirty(offset/8 - 1); } } memset( &stv_rbg_cache_data, 0, sizeof(stv_rbg_cache_data)); stv_rbg_cache_data.is_cache_dirty = 3; memset( &stv_vdp2_layer_data_placement, 0, sizeof(stv_vdp2_layer_data_placement)); refresh_palette_data(); } void saturn_state::stv_vdp2_exit ( void ) { m_vdp2.roz_bitmap[0].reset(); m_vdp2.roz_bitmap[1].reset(); } int saturn_state::stv_vdp2_start ( void ) { machine().add_notifier(MACHINE_NOTIFY_EXIT, machine_notify_delegate(&saturn_state::stv_vdp2_exit, this)); m_vdp2_regs = make_unique_clear<uint16_t[]>(0x040000/2 ); m_vdp2_vram = make_unique_clear<uint32_t[]>(0x100000/4 ); m_vdp2_cram = make_unique_clear<uint32_t[]>(0x080000/4 ); m_vdp2.gfx_decode = std::make_unique<uint8_t[]>(0x100000 ); // m_gfxdecode->gfx(0)->granularity()=4; // m_gfxdecode->gfx(1)->granularity()=4; memset( &stv_rbg_cache_data, 0, sizeof(stv_rbg_cache_data)); stv_rbg_cache_data.is_cache_dirty = 3; memset( &stv_vdp2_layer_data_placement, 0, sizeof(stv_vdp2_layer_data_placement)); save_pointer(NAME(m_vdp2_regs.get()), 0x040000/2); save_pointer(NAME(m_vdp2_vram.get()), 0x100000/4); save_pointer(NAME(m_vdp2_cram.get()), 0x080000/4); machine().save().register_postload(save_prepost_delegate(FUNC(saturn_state::stv_vdp2_state_save_postload), this)); return 0; } /* maybe we should move this to video/stv.c */ VIDEO_START_MEMBER(saturn_state,stv_vdp2) { int i; m_screen->register_screen_bitmap(m_tmpbitmap); stv_vdp2_start(); stv_vdp1_start(); m_vdpdebug_roz = 0; m_gfxdecode->gfx(0)->set_source(m_vdp2.gfx_decode.get()); m_gfxdecode->gfx(1)->set_source(m_vdp2.gfx_decode.get()); m_gfxdecode->gfx(2)->set_source(m_vdp2.gfx_decode.get()); m_gfxdecode->gfx(3)->set_source(m_vdp2.gfx_decode.get()); /* calc V counter offsets */ /* 224 mode */ for(i=0;i<263;i++) { true_vcount[i][0] = i; if(i>0xec) true_vcount[i][0]+=0xf9; } for(i=0;i<263;i++) { true_vcount[i][1] = i; if(i>0xf5) true_vcount[i][1]+=0xf9; } /* 256 mode, todo */ for(i=0;i<263;i++) { true_vcount[i][2] = i; true_vcount[i][3] = i; } } void saturn_state::stv_vdp2_dynamic_res_change( void ) { const int d_vres[4] = { 224, 240, 256, 256 }; const int d_hres[4] = { 320, 352, 640, 704 }; int horz_res,vert_res; int vres_mask; // reset odd bit if a dynamic resolution change occurs, seabass ST-V cares! m_vdp2.odd = 1; vres_mask = (m_vdp2.pal << 1)|1; //PAL uses mask 3, NTSC uses mask 1 vert_res = d_vres[STV_VDP2_VRES & vres_mask]; if((STV_VDP2_VRES & 3) == 3) popmessage("Illegal VRES MODE, contact MAMEdev"); /*Double-density interlace mode,doubles the vertical res*/ if((STV_VDP2_LSMD & 3) == 3) { vert_res*=2; } horz_res = d_hres[STV_VDP2_HRES & 3]; /*Exclusive modes,they sets the Vertical Resolution without considering the VRES register.*/ if(STV_VDP2_HRES & 4) vert_res = 480; { int vblank_period,hblank_period; attoseconds_t refresh; rectangle visarea(0, horz_res-1, 0, vert_res-1); vblank_period = get_vblank_duration(); hblank_period = get_hblank_duration(); refresh = HZ_TO_ATTOSECONDS(get_pixel_clock()) * (hblank_period) * vblank_period; //printf("%d %d %d %d\n",horz_res,vert_res,horz_res+hblank_period,vblank_period); m_screen->configure(hblank_period, vblank_period, visarea, refresh ); } // m_screen->set_visible_area(0*8, horz_res-1,0*8, vert_res-1); } /*This is for calculating the rgb brightness*/ /*TODO: Optimize this...*/ void saturn_state::stv_vdp2_fade_effects( void ) { /* Note:We have to use temporary storages because palette_get_color must use variables setted with unsigned int8 */ int16_t t_r,t_g,t_b; uint8_t r,g,b; rgb_t color; int i; //popmessage("%04x %04x",STV_VDP2_CLOFEN,STV_VDP2_CLOFSL); for(i=0;i<2048;i++) { /*Fade A*/ color = m_palette->pen_color(i); t_r = (STV_VDP2_COAR & 0x100) ? (color.r() - (0x100 - (STV_VDP2_COAR & 0xff))) : ((STV_VDP2_COAR & 0xff) + color.r()); t_g = (STV_VDP2_COAG & 0x100) ? (color.g() - (0x100 - (STV_VDP2_COAG & 0xff))) : ((STV_VDP2_COAG & 0xff) + color.g()); t_b = (STV_VDP2_COAB & 0x100) ? (color.b() - (0x100 - (STV_VDP2_COAB & 0xff))) : ((STV_VDP2_COAB & 0xff) + color.b()); if(t_r < 0) { t_r = 0; } if(t_r > 0xff) { t_r = 0xff; } if(t_g < 0) { t_g = 0; } if(t_g > 0xff) { t_g = 0xff; } if(t_b < 0) { t_b = 0; } if(t_b > 0xff) { t_b = 0xff; } r = t_r; g = t_g; b = t_b; m_palette->set_pen_color(i+(2048*1),rgb_t(r,g,b)); /*Fade B*/ color = m_palette->pen_color(i); t_r = (STV_VDP2_COBR & 0x100) ? (color.r() - (0xff - (STV_VDP2_COBR & 0xff))) : ((STV_VDP2_COBR & 0xff) + color.r()); t_g = (STV_VDP2_COBG & 0x100) ? (color.g() - (0xff - (STV_VDP2_COBG & 0xff))) : ((STV_VDP2_COBG & 0xff) + color.g()); t_b = (STV_VDP2_COBB & 0x100) ? (color.b() - (0xff - (STV_VDP2_COBB & 0xff))) : ((STV_VDP2_COBB & 0xff) + color.b()); if(t_r < 0) { t_r = 0; } if(t_r > 0xff) { t_r = 0xff; } if(t_g < 0) { t_g = 0; } if(t_g > 0xff) { t_g = 0xff; } if(t_b < 0) { t_b = 0; } if(t_b > 0xff) { t_b = 0xff; } r = t_r; g = t_g; b = t_b; m_palette->set_pen_color(i+(2048*2),rgb_t(r,g,b)); } //popmessage("%04x %04x %04x %04x %04x %04x",STV_VDP2_COAR,STV_VDP2_COAG,STV_VDP2_COAB,STV_VDP2_COBR,STV_VDP2_COBG,STV_VDP2_COBB); } void saturn_state::stv_vdp2_get_window0_coordinates(int *s_x, int *e_x, int *s_y, int *e_y) { /*W0*/ switch(STV_VDP2_LSMD & 3) { case 0: case 1: case 2: *s_y = ((STV_VDP2_W0SY & 0x3ff) >> 0); *e_y = ((STV_VDP2_W0EY & 0x3ff) >> 0); break; case 3: *s_y = ((STV_VDP2_W0SY & 0x7ff) >> 0); *e_y = ((STV_VDP2_W0EY & 0x7ff) >> 0); break; } switch(STV_VDP2_HRES & 6) { /*Normal*/ case 0: *s_x = ((STV_VDP2_W0SX & 0x3fe) >> 1); *e_x = ((STV_VDP2_W0EX & 0x3fe) >> 1); break; /*Hi-Res*/ case 2: *s_x = ((STV_VDP2_W0SX & 0x3ff) >> 0); *e_x = ((STV_VDP2_W0EX & 0x3ff) >> 0); break; /*Exclusive Normal*/ case 4: *s_x = ((STV_VDP2_W0SX & 0x1ff) >> 0); *e_x = ((STV_VDP2_W0EX & 0x1ff) >> 0); *s_y = ((STV_VDP2_W0SY & 0x3ff) >> 0); *e_y = ((STV_VDP2_W0EY & 0x3ff) >> 0); break; /*Exclusive Hi-Res*/ case 6: *s_x = ((STV_VDP2_W0SX & 0x1ff) << 1); *e_x = ((STV_VDP2_W0EX & 0x1ff) << 1); *s_y = ((STV_VDP2_W0SY & 0x3ff) >> 0); *e_y = ((STV_VDP2_W0EY & 0x3ff) >> 0); break; } } void saturn_state::stv_vdp2_get_window1_coordinates(int *s_x, int *e_x, int *s_y, int *e_y) { /*W1*/ switch(STV_VDP2_LSMD & 3) { case 0: case 1: case 2: *s_y = ((STV_VDP2_W1SY & 0x3ff) >> 0); *e_y = ((STV_VDP2_W1EY & 0x3ff) >> 0); break; case 3: *s_y = ((STV_VDP2_W1SY & 0x7ff) >> 0); *e_y = ((STV_VDP2_W1EY & 0x7ff) >> 0); break; } switch(STV_VDP2_HRES & 6) { /*Normal*/ case 0: *s_x = ((STV_VDP2_W1SX & 0x3fe) >> 1); *e_x = ((STV_VDP2_W1EX & 0x3fe) >> 1); break; /*Hi-Res*/ case 2: *s_x = ((STV_VDP2_W1SX & 0x3ff) >> 0); *e_x = ((STV_VDP2_W1EX & 0x3ff) >> 0); break; /*Exclusive Normal*/ case 4: *s_x = ((STV_VDP2_W1SX & 0x1ff) >> 0); *e_x = ((STV_VDP2_W1EX & 0x1ff) >> 0); *s_y = ((STV_VDP2_W1SY & 0x3ff) >> 0); *e_y = ((STV_VDP2_W1EY & 0x3ff) >> 0); break; /*Exclusive Hi-Res*/ case 6: *s_x = ((STV_VDP2_W1SX & 0x1ff) << 1); *e_x = ((STV_VDP2_W1EX & 0x1ff) << 1); *s_y = ((STV_VDP2_W1SY & 0x3ff) >> 0); *e_y = ((STV_VDP2_W1EY & 0x3ff) >> 0); break; } } int saturn_state::get_window_pixel(int s_x,int e_x,int s_y,int e_y,int x, int y,uint8_t win_num) { int res; res = 1; if(stv2_current_tilemap.window_control.enabled[win_num]) { if(stv2_current_tilemap.window_control.area[win_num]) res = (y >= s_y && y <= e_y && x >= s_x && x <= e_x); else res = (y >= s_y && y <= e_y && x >= s_x && x <= e_x) ^ 1; } return res; } inline int saturn_state::stv_vdp2_window_process(int x,int y) { int s_x=0,e_x=0,s_y=0,e_y=0; int w0_pix, w1_pix; if (stv2_current_tilemap.window_control.enabled[0] == 0 && stv2_current_tilemap.window_control.enabled[1] == 0) return 1; stv_vdp2_get_window0_coordinates(&s_x, &e_x, &s_y, &e_y); w0_pix = get_window_pixel(s_x,e_x,s_y,e_y,x,y,0); stv_vdp2_get_window1_coordinates(&s_x, &e_x, &s_y, &e_y); w1_pix = get_window_pixel(s_x,e_x,s_y,e_y,x,y,1); return stv2_current_tilemap.window_control.logic & 1 ? (w0_pix | w1_pix) : (w0_pix & w1_pix); } /* TODO: remove this crap. */ int saturn_state::stv_vdp2_apply_window_on_layer(rectangle &cliprect) { int s_x=0,e_x=0,s_y=0,e_y=0; if ( stv2_current_tilemap.window_control.enabled[0] && (!stv2_current_tilemap.window_control.area[0])) { /* w0, transparent outside supported */ stv_vdp2_get_window0_coordinates(&s_x, &e_x, &s_y, &e_y); if ( s_x > cliprect.min_x ) cliprect.min_x = s_x; if ( e_x < cliprect.max_x ) cliprect.max_x = e_x; if ( s_y > cliprect.min_y ) cliprect.min_y = s_y; if ( e_y < cliprect.max_y ) cliprect.max_y = e_y; return 1; } else if ( stv2_current_tilemap.window_control.enabled[1] && (!stv2_current_tilemap.window_control.area[1]) ) { /* w1, transparent outside supported */ stv_vdp2_get_window1_coordinates(&s_x, &e_x, &s_y, &e_y); if ( s_x > cliprect.min_x ) cliprect.min_x = s_x; if ( e_x < cliprect.max_x ) cliprect.max_x = e_x; if ( s_y > cliprect.min_y ) cliprect.min_y = s_y; if ( e_y < cliprect.max_y ) cliprect.max_y = e_y; return 1; } else { return 0; } } void saturn_state::draw_sprites(bitmap_rgb32 &bitmap, const rectangle &cliprect, uint8_t pri) { int x,y,r,g,b; int i; uint16_t pix; uint16_t *framebuffer_line; uint32_t *bitmap_line, *bitmap_line2 = nullptr; uint8_t interlace_framebuffer; uint8_t double_x; static const uint16_t sprite_colormask_table[] = { 0x07ff, 0x07ff, 0x07ff, 0x07ff, 0x03ff, 0x07ff, 0x03ff, 0x01ff, 0x007f, 0x003f, 0x003f, 0x003f, 0x00ff, 0x00ff, 0x00ff, 0x00ff }; static const uint16_t priority_shift_table[] = { 14, 13, 14, 13, 13, 12, 12, 12, 7, 7, 6, 0, 7, 7, 6, 0 }; static const uint16_t priority_mask_table[] = { 3, 7, 1, 3, 3, 7, 7, 7, 1, 1, 3, 0, 1, 1, 3, 0 }; static const uint16_t ccrr_shift_table[] = { 11, 11, 11, 11, 10, 11, 10, 9, 0, 6, 0, 6, 0, 6, 0, 6 }; static const uint16_t ccrr_mask_table[] = { 7, 3, 7, 3, 7, 1, 3, 7, 0, 1, 0, 3, 0, 1, 0, 3 }; static const uint16_t shadow_mask_table[] = { 0, 0, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0x8000, 0, 0, 0, 0, 0, 0, 0, 0 }; uint16_t alpha_enabled; int sprite_type; int sprite_colormask; int color_offset_pal; int sprite_shadow; uint16_t sprite_priority_shift, sprite_priority_mask, sprite_ccrr_shift, sprite_ccrr_mask; uint8_t priority; uint8_t ccr = 0; uint8_t sprite_priorities[8]; uint8_t sprite_ccr[8]; int sprite_color_mode = STV_VDP2_SPCLMD; if ( (stv_sprite_priorities_usage_valid == 1) && (stv_sprite_priorities_used[pri] == 0) ) return; sprite_priorities[0] = STV_VDP2_S0PRIN; sprite_priorities[1] = STV_VDP2_S1PRIN; sprite_priorities[2] = STV_VDP2_S2PRIN; sprite_priorities[3] = STV_VDP2_S3PRIN; sprite_priorities[4] = STV_VDP2_S4PRIN; sprite_priorities[5] = STV_VDP2_S5PRIN; sprite_priorities[6] = STV_VDP2_S6PRIN; sprite_priorities[7] = STV_VDP2_S7PRIN; sprite_ccr[0] = STV_VDP2_S0CCRT; sprite_ccr[1] = STV_VDP2_S1CCRT; sprite_ccr[2] = STV_VDP2_S2CCRT; sprite_ccr[3] = STV_VDP2_S3CCRT; sprite_ccr[4] = STV_VDP2_S4CCRT; sprite_ccr[5] = STV_VDP2_S5CCRT; sprite_ccr[6] = STV_VDP2_S6CCRT; sprite_ccr[7] = STV_VDP2_S7CCRT; sprite_type = STV_VDP2_SPTYPE; sprite_colormask = sprite_colormask_table[sprite_type]; sprite_priority_shift = priority_shift_table[sprite_type]; sprite_priority_mask = priority_mask_table[sprite_type]; sprite_ccrr_shift = ccrr_shift_table[sprite_type]; sprite_ccrr_mask = ccrr_mask_table[sprite_type]; sprite_shadow = shadow_mask_table[sprite_type]; for ( i = 0; i < (sprite_priority_mask+1); i++ ) if ( sprite_priorities[i] == pri ) break; if ( i == (sprite_priority_mask+1) ) return; /* color offset (RGB brightness) */ color_offset_pal = 0; if ( STV_VDP2_SPCOEN ) { if ( STV_VDP2_SPCOSL == 0 ) { color_offset_pal = 2048; } else { color_offset_pal = 2048*2; } } /* color calculation (alpha blending)*/ if ( STV_VDP2_SPCCEN ) { alpha_enabled = 0; switch( STV_VDP2_SPCCCS ) { case 0x0: if ( pri <= STV_VDP2_SPCCN ) alpha_enabled = 1; break; case 0x1: if ( pri == STV_VDP2_SPCCN ) alpha_enabled = 1; break; case 0x2: if ( pri >= STV_VDP2_SPCCN ) alpha_enabled = 1; break; case 0x3: alpha_enabled = 2; sprite_shadow = 0; break; } } else { alpha_enabled = 0; } /* framebuffer interlace */ if ( (STV_VDP2_LSMD == 3) && m_vdp1.framebuffer_double_interlace == 0 ) interlace_framebuffer = 1; else interlace_framebuffer = 0; /*Guess:Some games needs that the horizontal sprite size to be doubled (TODO: understand the proper settings,it might not work like this)*/ if(STV_VDP1_TVM == 0 && STV_VDP2_HRES & 2) // astrass & findlove double_x = 1; else double_x = 0; /* window control */ stv2_current_tilemap.window_control.logic = STV_VDP2_SPLOG; stv2_current_tilemap.window_control.enabled[0] = STV_VDP2_SPW0E; stv2_current_tilemap.window_control.enabled[1] = STV_VDP2_SPW1E; // stv2_current_tilemap.window_control.? = STV_VDP2_SPSWE; stv2_current_tilemap.window_control.area[0] = STV_VDP2_SPW0A; stv2_current_tilemap.window_control.area[1] = STV_VDP2_SPW1A; // stv2_current_tilemap.window_control.? = STV_VDP2_SPSWA; // stv_vdp2_apply_window_on_layer(mycliprect); if (interlace_framebuffer == 0 && double_x == 0 ) { if ( alpha_enabled == 0 ) { for ( y = cliprect.min_y; y <= cliprect.max_y; y++ ) { if ( stv_sprite_priorities_usage_valid ) if (stv_sprite_priorities_in_fb_line[y][pri] == 0) continue; framebuffer_line = m_vdp1.framebuffer_display_lines[y]; bitmap_line = &bitmap.pix32(y); for ( x = cliprect.min_x; x <= cliprect.max_x; x++ ) { if(!stv_vdp2_window_process(x,y)) continue; pix = framebuffer_line[x]; if ( (pix & 0x8000) && sprite_color_mode) { if ( sprite_priorities[0] != pri ) { stv_sprite_priorities_used[sprite_priorities[0]] = 1; stv_sprite_priorities_in_fb_line[y][sprite_priorities[0]] = 1; continue; }; if(STV_VDP2_SPWINEN && pix == 0x8000) /* Pukunpa */ continue; b = pal5bit((pix & 0x7c00) >> 10); g = pal5bit((pix & 0x03e0) >> 5); r = pal5bit( pix & 0x001f); if ( color_offset_pal ) { stv_vdp2_compute_color_offset( &r, &g, &b, STV_VDP2_SPCOSL ); } bitmap_line[x] = rgb_t(r, g, b); } else { priority = sprite_priorities[(pix >> sprite_priority_shift) & sprite_priority_mask]; if ( priority != pri ) { stv_sprite_priorities_used[priority] = 1; stv_sprite_priorities_in_fb_line[y][priority] = 1; continue; }; { pix &= sprite_colormask; if ( pix == (sprite_colormask - 1) ) { /*shadow - in reality, we should check from what layer pixel beneath comes...*/ if ( STV_VDP2_SDCTL & 0x3f ) { rgb_t p = bitmap_line[x]; bitmap_line[x] = rgb_t(p.r() >> 1, p.g() >> 1, p.b() >> 1); } /* note that when shadows are disabled, "shadow" palette entries are not drawn */ } else if ( pix ) { pix += (STV_VDP2_SPCAOS << 8); pix &= 0x7ff; pix += color_offset_pal; bitmap_line[x] = m_palette->pen( pix ); } } /* TODO: I don't think this one makes much logic ... (1) */ if ( pix & sprite_shadow ) { if ( pix & ~sprite_shadow ) { rgb_t p = bitmap_line[x]; bitmap_line[x] = rgb_t(p.r() >> 1, p.g() >> 1, p.b() >> 1); } } } } } } else //alpha_enabled == 1 { for ( y = cliprect.min_y; y <= cliprect.max_y; y++ ) { if ( stv_sprite_priorities_usage_valid ) if (stv_sprite_priorities_in_fb_line[y][pri] == 0) continue; framebuffer_line = m_vdp1.framebuffer_display_lines[y]; bitmap_line = &bitmap.pix32(y); for ( x = cliprect.min_x; x <= cliprect.max_x; x++ ) { if(!stv_vdp2_window_process(x,y)) continue; pix = framebuffer_line[x]; if ( (pix & 0x8000) && sprite_color_mode) { if ( sprite_priorities[0] != pri ) { stv_sprite_priorities_used[sprite_priorities[0]] = 1; stv_sprite_priorities_in_fb_line[y][sprite_priorities[0]] = 1; continue; }; b = pal5bit((pix & 0x7c00) >> 10); g = pal5bit((pix & 0x03e0) >> 5); r = pal5bit( pix & 0x001f); if ( color_offset_pal ) { stv_vdp2_compute_color_offset( &r, &g, &b, STV_VDP2_SPCOSL ); } ccr = sprite_ccr[0]; if ( STV_VDP2_CCMD ) { bitmap_line[x] = stv_add_blend( bitmap_line[x], rgb_t(r, g, b)); } else { bitmap_line[x] = alpha_blend_r32( bitmap_line[x], rgb_t(r, g ,b), ((uint16_t)(0x1f-ccr)*0xff)/0x1f); } } else { priority = sprite_priorities[(pix >> sprite_priority_shift) & sprite_priority_mask]; if ( priority != pri ) { stv_sprite_priorities_used[priority] = 1; stv_sprite_priorities_in_fb_line[y][priority] = 1; continue; }; ccr = sprite_ccr[ (pix >> sprite_ccrr_shift) & sprite_ccrr_mask ]; if ( alpha_enabled == 2 ) { if ( ( pix & 0x8000 ) == 0 ) { ccr = 0; } } { pix &= sprite_colormask; if ( pix == (sprite_colormask - 1) ) { /*shadow - in reality, we should check from what layer pixel beneath comes...*/ if ( STV_VDP2_SDCTL & 0x3f ) { rgb_t p = bitmap_line[x]; bitmap_line[x] = rgb_t(p.r() >> 1, p.g() >> 1, p.b() >> 1); } /* note that when shadows are disabled, "shadow" palette entries are not drawn */ } else if ( pix ) { pix += (STV_VDP2_SPCAOS << 8); pix &= 0x7ff; pix += color_offset_pal; if ( ccr > 0 ) { if ( STV_VDP2_CCMD ) { bitmap_line[x] = stv_add_blend( bitmap_line[x], m_palette->pen(pix) ); } else { bitmap_line[x] = alpha_blend_r32( bitmap_line[x], m_palette->pen(pix), ((uint16_t)(0x1f-ccr)*0xff)/0x1f ); } } else bitmap_line[x] = m_palette->pen(pix); } } /* TODO: (1) */ if ( pix & sprite_shadow ) { if ( pix & ~sprite_shadow ) { rgb_t p = bitmap_line[x]; bitmap_line[x] = rgb_t(p.r() >> 1, p.g() >> 1, p.b() >> 1); } } } } } } } else { for ( y = cliprect.min_y; y <= cliprect.max_y / (interlace_framebuffer+1); y++ ) { if ( stv_sprite_priorities_usage_valid ) if (stv_sprite_priorities_in_fb_line[y][pri] == 0) continue; framebuffer_line = m_vdp1.framebuffer_display_lines[y]; if ( interlace_framebuffer == 0 ) { bitmap_line = &bitmap.pix32(y); } else { bitmap_line = &bitmap.pix32(2*y); bitmap_line2 = &bitmap.pix32(2*y + 1); } for ( x = cliprect.min_x; x <= cliprect.max_x /(double_x+1) ; x++ ) { if(!stv_vdp2_window_process(x,y)) continue; pix = framebuffer_line[x]; if ( (pix & 0x8000) && sprite_color_mode) { if ( sprite_priorities[0] != pri ) { stv_sprite_priorities_used[sprite_priorities[0]] = 1; stv_sprite_priorities_in_fb_line[y][sprite_priorities[0]] = 1; continue; }; b = pal5bit((pix & 0x7c00) >> 10); g = pal5bit((pix & 0x03e0) >> 5); r = pal5bit( pix & 0x001f); if ( color_offset_pal ) { stv_vdp2_compute_color_offset( &r, &g, &b, STV_VDP2_SPCOSL ); } if ( alpha_enabled == 0 ) { if(double_x) { bitmap_line[x*2] = rgb_t(r, g, b); if ( interlace_framebuffer == 1 ) bitmap_line2[x*2] = rgb_t(r, g, b); bitmap_line[x*2+1] = rgb_t(r, g, b); if ( interlace_framebuffer == 1 ) bitmap_line2[x*2+1] = rgb_t(r, g, b); } else { bitmap_line[x] = rgb_t(r, g, b); if ( interlace_framebuffer == 1 ) bitmap_line2[x] = rgb_t(r, g, b); } } else // alpha_blend == 1 { ccr = sprite_ccr[0]; if ( STV_VDP2_CCMD ) { if(double_x) { bitmap_line[x*2] = stv_add_blend( bitmap_line[x*2], rgb_t(r, g, b) ); if ( interlace_framebuffer == 1 ) bitmap_line2[x*2] = stv_add_blend( bitmap_line2[x*2], rgb_t(r, g, b) ); bitmap_line[x*2+1] = stv_add_blend( bitmap_line[x*2+1], rgb_t(r, g, b) ); if ( interlace_framebuffer == 1 ) bitmap_line2[x*2+1] = stv_add_blend( bitmap_line2[x*2+1], rgb_t(r, g, b) ); } else { bitmap_line[x] = stv_add_blend( bitmap_line[x], rgb_t(r, g, b) ); if ( interlace_framebuffer == 1 ) bitmap_line2[x] = stv_add_blend( bitmap_line2[x], rgb_t(r, g, b) ); } } else { if(double_x) { bitmap_line[x*2] = alpha_blend_r32( bitmap_line[x*2], rgb_t(r, g, b), ((uint16_t)(0x1f-ccr)*0xff)/0x1f ); if ( interlace_framebuffer == 1 ) bitmap_line2[x*2] = alpha_blend_r32( bitmap_line2[x*2], rgb_t(r, g, b), ((uint16_t)(0x1f-ccr)*0xff)/0x1f ); bitmap_line[x*2+1] = alpha_blend_r32( bitmap_line[x*2+1], rgb_t(r, g, b), ((uint16_t)(0x1f-ccr)*0xff)/0x1f ); if ( interlace_framebuffer == 1 ) bitmap_line2[x*2+1] = alpha_blend_r32( bitmap_line2[x*2+1], rgb_t(r, g, b), ((uint16_t)(0x1f-ccr)*0xff)/0x1f); } else { bitmap_line[x] = alpha_blend_r32( bitmap_line[x], rgb_t(r, g, b), ((uint16_t)(0x1f-ccr)*0xff)/0x1f); if ( interlace_framebuffer == 1 ) bitmap_line2[x] = alpha_blend_r32( bitmap_line2[x], rgb_t(r, g, b), ((uint16_t)(0x1f-ccr)*0xff)/0x1f); } } } } else { priority = sprite_priorities[(pix >> sprite_priority_shift) & sprite_priority_mask]; if ( priority != pri ) { stv_sprite_priorities_used[priority] = 1; stv_sprite_priorities_in_fb_line[y][priority] = 1; continue; }; if ( alpha_enabled ) ccr = sprite_ccr[ (pix >> sprite_ccrr_shift) & sprite_ccrr_mask ]; if ( alpha_enabled == 2 ) { if ( ( pix & 0x8000 ) == 0 ) { ccr = 0; } } { pix &= sprite_colormask; if ( pix == (sprite_colormask - 1) ) { /*shadow - in reality, we should check from what layer pixel beneath comes...*/ if ( STV_VDP2_SDCTL & 0x3f ) { rgb_t p = bitmap_line[x]; if(double_x) { p = bitmap_line[x*2]; bitmap_line[x*2] = rgb_t(p.r() >> 1, p.g() >> 1, p.b() >> 1); p = bitmap_line[x*2+1]; bitmap_line[x*2+1] = rgb_t(p.r() >> 1, p.g() >> 1, p.b() >> 1); } else bitmap_line[x] = rgb_t(p.r() >> 1, p.g() >> 1, p.b() >> 1); } /* note that when shadows are disabled, "shadow" palette entries are not drawn */ } else if ( pix ) { pix += (STV_VDP2_SPCAOS << 8); pix &= 0x7ff; pix += color_offset_pal; if ( alpha_enabled == 0 ) { if(double_x) { bitmap_line[x*2] = m_palette->pen( pix ); if ( interlace_framebuffer == 1 ) bitmap_line2[x*2] = m_palette->pen( pix ); bitmap_line[x*2+1] = m_palette->pen( pix ); if ( interlace_framebuffer == 1 ) bitmap_line2[x*2+1] = m_palette->pen( pix ); } else { bitmap_line[x] = m_palette->pen( pix ); if ( interlace_framebuffer == 1 ) bitmap_line2[x] = m_palette->pen( pix ); } } else // alpha_blend == 1 { if ( STV_VDP2_CCMD ) { if(double_x) { bitmap_line[x*2] = stv_add_blend( bitmap_line[x*2], m_palette->pen(pix) ); if ( interlace_framebuffer == 1 ) bitmap_line2[x*2] = stv_add_blend( bitmap_line2[x], m_palette->pen(pix) ); bitmap_line[x*2+1] = stv_add_blend( bitmap_line[x*2+1], m_palette->pen(pix) ); if ( interlace_framebuffer == 1 ) bitmap_line2[x*2+1] = stv_add_blend( bitmap_line2[x], m_palette->pen(pix) ); } else { bitmap_line[x] = stv_add_blend( bitmap_line[x], m_palette->pen(pix) ); if ( interlace_framebuffer == 1 ) bitmap_line2[x] = stv_add_blend( bitmap_line2[x], m_palette->pen(pix) ); } } else { if(double_x) { bitmap_line[x*2] = alpha_blend_r32( bitmap_line[x*2], m_palette->pen(pix), ((uint16_t)(0x1f-ccr)*0xff)/0x1f ); if ( interlace_framebuffer == 1 ) bitmap_line2[x*2] = alpha_blend_r32( bitmap_line2[x], m_palette->pen(pix), ((uint16_t)(0x1f-ccr)*0xff)/0x1f ); bitmap_line[x*2+1] = alpha_blend_r32( bitmap_line[x*2+1], m_palette->pen(pix), ((uint16_t)(0x1f-ccr)*0xff)/0x1f ); if ( interlace_framebuffer == 1 ) bitmap_line2[x*2+1] = alpha_blend_r32( bitmap_line2[x], m_palette->pen(pix), ((uint16_t)(0x1f-ccr)*0xff)/0x1f ); } else { bitmap_line[x] = alpha_blend_r32( bitmap_line[x], m_palette->pen(pix), ((uint16_t)(0x1f-ccr)*0xff)/0x1f ); if ( interlace_framebuffer == 1 ) bitmap_line2[x] = alpha_blend_r32( bitmap_line2[x], m_palette->pen(pix), ((uint16_t)(0x1f-ccr)*0xff)/0x1f ); } } } } } /* TODO: (1) */ if ( pix & sprite_shadow ) { if ( pix & ~sprite_shadow ) { rgb_t p = bitmap_line[x]; if(double_x) { p = bitmap_line[x*2]; bitmap_line[x*2] = rgb_t(p.r() >> 1, p.g() >> 1, p.b() >> 1); p = bitmap_line[x*2+1]; bitmap_line[x*2+1] = rgb_t(p.r() >> 1, p.g() >> 1, p.b() >> 1); } else bitmap_line[x] = rgb_t(p.r() >> 1, p.g() >> 1, p.b() >> 1); } } } } } } stv_sprite_priorities_usage_valid = 1; } uint32_t saturn_state::screen_update_stv_vdp2(screen_device &screen, bitmap_rgb32 &bitmap, const rectangle &cliprect) { stv_vdp2_fade_effects(); stv_vdp2_draw_back(m_tmpbitmap,cliprect); if(STV_VDP2_DISP) { uint8_t pri; stv_sprite_priorities_usage_valid = 0; memset(stv_sprite_priorities_used, 0, sizeof(stv_sprite_priorities_used)); memset(stv_sprite_priorities_in_fb_line, 0, sizeof(stv_sprite_priorities_in_fb_line)); /*If a plane has a priority value of zero it isn't shown at all.*/ for(pri=1;pri<8;pri++) { if(pri==STV_VDP2_N3PRIN) { stv_vdp2_draw_NBG3(m_tmpbitmap,cliprect); } if(pri==STV_VDP2_N2PRIN) { stv_vdp2_draw_NBG2(m_tmpbitmap,cliprect); } if(pri==STV_VDP2_N1PRIN) { stv_vdp2_draw_NBG1(m_tmpbitmap,cliprect); } if(pri==STV_VDP2_N0PRIN) { stv_vdp2_draw_NBG0(m_tmpbitmap,cliprect); } if(pri==STV_VDP2_R0PRIN) { stv_vdp2_draw_RBG0(m_tmpbitmap,cliprect); } { draw_sprites(m_tmpbitmap,cliprect,pri); } } } copybitmap(bitmap, m_tmpbitmap, 0, 0, 0, 0, cliprect); #if 0 /* Do NOT remove me, used to test video code performance. */ if(machine().input().code_pressed(KEYCODE_Q)) { popmessage("Halt CPUs"); m_maincpu->set_input_line(INPUT_LINE_HALT, ASSERT_LINE); m_slave->set_input_line(INPUT_LINE_HALT, ASSERT_LINE); m_audiocpu->set_input_line(INPUT_LINE_HALT, ASSERT_LINE); } #endif return 0; }
39.655153
324
0.51851
[ "render", "solid" ]
9f9f01951937b860618edab2efdc3664d98ef2b8
25,116
cpp
C++
src/flexui/Style/StyleParse.cpp
franciscod/flexui
9af2c32a8ac3fe7127a9dd6927abe8b1945237c4
[ "MIT" ]
null
null
null
src/flexui/Style/StyleParse.cpp
franciscod/flexui
9af2c32a8ac3fe7127a9dd6927abe8b1945237c4
[ "MIT" ]
null
null
null
src/flexui/Style/StyleParse.cpp
franciscod/flexui
9af2c32a8ac3fe7127a9dd6927abe8b1945237c4
[ "MIT" ]
null
null
null
#include "flexui/Style/StyleParse.hpp" #include "flexui/Style/NamedColors.hpp" #include "flexui/Style/StyleSheet.hpp" /// Eventually we want to move away from std::string. /// We'll have slices of the original buffer /// moving around instead of copying all the time (substrs) namespace flexui { /// Check if the character is a valid start for a CSS identifier inline bool isIdentStart(char c) { return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c == '-') || (c == '_'); } /// Check if the character is valid for a CSS identifier inline bool isIdent(char c) { return isIdentStart(c) || (c >= '0' && c <= '9'); } /// Check if the character is a CSS nesting operator inline bool isNestingOperator(char c) { return c == '>' || c == '+' || c == '~'; } /// Check if the character is a CSS selector marker inline bool isSelectorMarker(char c) { return c == '*' || c == '#' || c == '.' || c == ':'; } /// Check if the character is a valid decimal digit bool isNumeric(char c) { return c >= '0' && c <= '9'; } /// Check if the character is a valid hex digit bool isHex(char c) { return (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F') || isNumeric(c); } /// Converts a hex digit to its decimal representation unsigned char hexToDec(unsigned char c) { if (c >= '0' && c <= '9') return c - '0'; if (c >= 'a' && c <= 'f') return c - 'a' + 10; if (c >= 'A' && c <= 'F') return c - 'A' + 10; return 0; } /// Converts a two digit hex to its decimal representation unsigned char hexToDec(unsigned char l, unsigned char r) { return 16 * hexToDec(l) + hexToDec(r); } /// Converts decimal colors to StyleColor StyleColor buildColor(unsigned char r, unsigned char g, unsigned char b, unsigned char a) { // AABBGGRR return ((uint32_t)(a) << 24) | ((uint32_t)(b) << 16) | ((uint32_t)(g) << 8) | ((uint32_t)(r)); } /// Advances pos until there is no more whitespace void consumeWhiteSpace(const std::string& input, size_t& pos) { while (pos < input.size() && std::isspace(input[pos])) pos++; } /// Parses a single CSS identifier from pos std::string parseIdentifier(const std::string& input, size_t& pos) { std::string result; while (pos < input.size() && isIdent(input[pos])) { result.push_back(input[pos]); pos++; } return result; } // Removes all spaces and transforms to lowercase std::string sanitize(const std::string& input) { std::string result; for (const char& c : input) if (!std::isspace(c)) result.push_back(std::tolower(c)); return result; } bool ParseSingleStyleSelector(const std::string& input, StyleSelector& selector, StyleParseResult& parseResult) { selector = { }; selector.rule = nullptr; selector.specificity = 0; selector.order = 0; size_t pos = 0; StyleSelectorRelationship next_rel = StyleSelectorRelationship::NONE; while (pos < input.size()) { consumeWhiteSpace(input, pos); if (pos >= input.size()) break; // no more char chr = input[pos]; bool marker = isSelectorMarker(chr); if (isIdentStart(chr) || marker) { if (marker) pos++; // skip marker StyleIdentifierType type; bool is_wildcard = false; switch (chr) { case '#': type = StyleIdentifierType::ID; break; default: type = StyleIdentifierType::TAG; break; case '.': type = StyleIdentifierType::CLASS; break; case '*': type = StyleIdentifierType::TAG; is_wildcard = true; break; case ':': std::string pseudo = parseIdentifier(input, pos); StylePseudoStates state; switch (HashStr(pseudo.c_str())) { case HashStr("hover"): state = StylePseudoStates::HOVER; break; case HashStr("disabled"): state = StylePseudoStates::DISABLED; break; case HashStr("checked"): state = StylePseudoStates::CHECKED; break; case HashStr("active"): state = StylePseudoStates::ACTIVE; break; case HashStr("focus"): state = StylePseudoStates::FOCUS; break; default: parseResult.warnings.emplace_back("Unsupported pseudo state '" + pseudo + "'"); return false; } // elem:pseudo if (next_rel == StyleSelectorRelationship::NONE && selector.parts.size() > 0) { selector.parts.back().pseudo_states |= state; } // :pseudo // elem > :pseudo else { // create wildcard tag StyleSelectorPart part = { }; part.identifier.type = StyleIdentifierType::TAG; part.identifier.text = "*"; part.identifier.computeHash(); part.prev_relationship = StyleSelectorRelationship::NONE; part.pseudo_states = state; selector.parts.emplace_back(part); } if (input[pos] == ' ') // check for space next_rel = StyleSelectorRelationship::DESCENDANT; else next_rel = StyleSelectorRelationship::NONE; continue; // skip the rest } StyleSelectorPart part = { }; part.identifier.type = type; part.identifier.text = is_wildcard ? "*" : parseIdentifier(input, pos); part.identifier.computeHash(); part.prev_relationship = next_rel; part.pseudo_states = StylePseudoStates::NONE; // OE_LOG_DEBUG("(selector type " << std::to_string((int)part.identifier.type) << ")" << part.identifier.text); selector.parts.emplace_back(part); if (input[pos] == ' ') // check for space next_rel = StyleSelectorRelationship::DESCENDANT; else next_rel = StyleSelectorRelationship::NONE; } else if (isNestingOperator(chr)) { pos++; // skip operator switch (chr) { case '>': next_rel = StyleSelectorRelationship::CHILD; break; case '+': next_rel = StyleSelectorRelationship::ADJACENT_SIBLING; break; case '~': next_rel = StyleSelectorRelationship::GENERAL_SIBLING; break; } // OE_LOG_DEBUG("(nesting op)" << chr); } else { parseResult.errors.emplace_back("Unexpected character '" + std::string(1, chr) + "'"); return false; } } if (selector.parts.size() > 0) { selector.computeSpecificity(); return true; } else { return false; } } bool ParseStyleSelectors(const std::string& input, std::vector<StyleSelector>& selectors, StyleParseResult& parseResult) { bool any = false; size_t pos = 0; while (pos < input.size()) { size_t selector_end = input.find(",", pos); if (selector_end == std::string::npos) selector_end = input.size(); std::string single_selector = input.substr(pos, selector_end - pos); StyleSelector selector; if (ParseSingleStyleSelector(single_selector, selector, parseResult)) { selectors.emplace_back(selector); any = true; } pos = selector_end + 1; } return any; } bool parseNumber(const std::string& input, int& pos, StyleNumber& output, StyleParseResult& parseResult) { bool valid = false; bool negative = false; bool mantissa = false; int mantissa_place = 1; float value = 0; while (pos < input.size()) { char chr = input[pos]; if (chr == '-') { if (pos == 0) { negative = true; } else { parseResult.warnings.emplace_back("Unexpected '-'"); return false; // unexpected - } } else if (chr == '.') { if (mantissa) { parseResult.warnings.emplace_back("Unexpected '.'"); return false; // unexpected . } mantissa = true; } else if (isNumeric(chr)) { int num = chr - '0'; if (!mantissa) { // whole part value = value * 10 + num; } else { // decimal part value = value + (float)num / powf(10, (float)mantissa_place++); } valid = true; } else { break; // unexpected character (probably a unit) } pos++; } output = negative ? -value : value; return valid; } bool parseLength(const std::string& input, StyleLength& output, StyleParseResult& parseResult) { int pos = 0; if (parseNumber(input, pos, output.number, parseResult)) { // number parsed if (pos < input.size()) { // more to read, must be a unit if (input[pos] == '%') { output.unit = StyleLengthUnit::PERCENT; } else if (pos + 1 < input.size() && input[pos] == 'p' && input[pos + 1] == 'x') { output.unit = StyleLengthUnit::PIXELS; } else { // invalid unit parseResult.warnings.emplace_back("Unexpected character '" + std::string(1, input[pos]) + "' parsing length"); return false; // unexpected character } } else { // by default pixels output.unit = StyleLengthUnit::PIXELS; } output.set_auto = false; return true; } else if (input.size() >= 4) { // check if auto if (input[0] == 'a' && input[1] == 'u' && input[2] == 't' && input[3] == 'o') { output.set_auto = true; return true; } } return false; } bool parseColor(const std::string& input, StyleColor& output, StyleParseResult& parseResult) { if (input.size() < 2) return false; if (input[0] == '#') { // hex color // #RGB if (input.size() == 4) { if (isHex(input[1]) && isHex(input[2]) && isHex(input[3])) { output = buildColor( hexToDec(input[1], input[1]), hexToDec(input[2], input[2]), hexToDec(input[3], input[3]), (unsigned char)0xFF ); return true; } else { parseResult.warnings.emplace_back("Invalid #RGB hex value"); return false; // invalid hex } } // #RRGGBB else if (input.size() == 7) { if (isHex(input[1]) && isHex(input[2]) && isHex(input[3]) && isHex(input[4]) && isHex(input[5]) && isHex(input[6])) { output = buildColor( hexToDec(input[1], input[2]), hexToDec(input[3], input[4]), hexToDec(input[5], input[6]), (unsigned char)0xFF ); return true; } else { parseResult.warnings.emplace_back("Invalid #RRGGBB hex value"); return false; // invalid hex } } else { parseResult.warnings.emplace_back("Invalid size for hex number (" + std::to_string(input.size()) + ")"); return false; // invalid size for hex number } } else if (input.find("rgb") == 0 && input.size() > 5) { // rgb/a color bool has_alpha = input[3] == 'a'; int num_components = has_alpha ? 4 : 3; int pos = has_alpha ? 5 : 4; float components[4]; for (int i = 0; i < num_components; i++) { if (parseNumber(input, pos, components[i], parseResult)) { if (pos < input.size()) { if (input[pos] == '%') { pos++; // skip % } if (input[pos] == ',') { pos++; // skip , // next component if (i + 1 >= num_components) { parseResult.warnings.emplace_back("Too many components for rgb/a"); return false; // too many components } } else if (input[pos] == ')') { // check if matched all components if (i + 1 < num_components) { parseResult.warnings.emplace_back("Too few components for rgb/a"); return false; // too few components } output = buildColor( (unsigned char)components[0], (unsigned char)components[1], (unsigned char)components[2], has_alpha ? (unsigned char)((float)components[3] * 255.0f) : 0xFF ); return true; } } else { parseResult.warnings.emplace_back("Incomplete rgb/a color"); return false; } } else { parseResult.warnings.emplace_back("Could not parse component number " + std::to_string(i) + " of rgb/a color"); return false; } } return false; } else { // try to match predefined colors // See https://www.w3.org/TR/css-color-3/#svg-color auto it = NAMED_COLORS.find(input); if (it != NAMED_COLORS.end()) { output = (*it).second; return true; } else { parseResult.warnings.emplace_back("Named color '" + input + "' not found"); return false; } } parseResult.warnings.emplace_back("Expected color definition"); return false; } bool parseString(const std::string& input, StyleValue::String& output, StyleParseResult& parseResult) { if (input.size() < 2) // must have at least two quotes return false; bool _single = input[0] == '"' || input[input.size() - 1] == '"'; bool _double = input[0] == '\'' || input[input.size() - 1] == '\''; if (!_single && !_double) return false; output.length = (int8_t)(input.size() - 2 + 1); // -2 quotes + 1 \0 output.data = (char*)malloc(output.length); if (!output.data) return false; // malloc failed memcpy(output.data, input.data() + 1, input.size() - 2); output.data[output.length - 1] = '\0'; return true; } bool ParseStyleProperty(const std::string& name, const std::string& raw_value, StyleRule& rule, StyleParseResult& parseResult) { using ID = StylePropertyID; StyleProperty prop = { }; std::string value = sanitize(raw_value); int dummy = 0; // for parseNumber switch (HashStr(sanitize(name).c_str())) { #define PARSE_PROP(func, prop_name, prop_id, prop_key) \ case HashStr(prop_name): \ if (func(value, prop.value.prop_key, parseResult)) { \ prop.id = prop_id; \ rule.properties.emplace_back(prop); \ return true; \ } \ break; #define LENGTH_PROPERTY(prop_name, prop_id) PARSE_PROP(parseLength, prop_name, prop_id, length); #define COLOR_PROPERTY(prop_name, prop_id) PARSE_PROP(parseColor, prop_name, prop_id, color); #define STRING_PROPERTY(prop_name, prop_id) \ case HashStr(prop_name): \ if (parseString(raw_value, prop.value.string, parseResult)) { \ prop.id = prop_id; \ rule.properties.emplace_back(prop); \ return true; \ } \ break; #define NUMBER_PROPERTY(prop_name, prop_id) \ case HashStr(prop_name): \ if (parseNumber(value, dummy, prop.value.number, parseResult)) { \ prop.id = prop_id; \ rule.properties.emplace_back(prop); \ return true; \ } \ break; #define PARSE_ENUM_START(prop_name, prop_id) \ case HashStr(prop_name): \ prop.id = prop_id; \ switch (HashStr(value.c_str())) { #define PARSE_ENUM_ENTRY(key, a, b) \ case HashStr(a): prop.value.key = b; break; \ #define PARSE_ENUM_END() \ default: \ return false; /* no match */ \ } \ rule.properties.emplace_back(prop); \ return true; /// ----------------------- /// ----------------------- /// ----------------------- LENGTH_PROPERTY("width", ID::WIDTH); LENGTH_PROPERTY("height", ID::HEIGHT); LENGTH_PROPERTY("min-width", ID::MIN_WIDTH); LENGTH_PROPERTY("min-height", ID::MIN_HEIGHT); LENGTH_PROPERTY("max-width", ID::MAX_WIDTH); LENGTH_PROPERTY("max-height", ID::MAX_HEIGHT); LENGTH_PROPERTY("margin-left", ID::MARGIN_LEFT); LENGTH_PROPERTY("margin-top", ID::MARGIN_TOP); LENGTH_PROPERTY("margin-right", ID::MARGIN_RIGHT); LENGTH_PROPERTY("margin-bottom", ID::MARGIN_BOTTOM); LENGTH_PROPERTY("padding-left", ID::PADDING_LEFT); LENGTH_PROPERTY("padding-top", ID::PADDING_TOP); LENGTH_PROPERTY("padding-right", ID::PADDING_RIGHT); LENGTH_PROPERTY("padding-bottom", ID::PADDING_BOTTOM); COLOR_PROPERTY("border-color", ID::BORDER_COLOR); LENGTH_PROPERTY("border-top-left-radius", ID::BORDER_TOP_LEFT_RADIUS); LENGTH_PROPERTY("border-top-right-radius", ID::BORDER_TOP_RIGHT_RADIUS); LENGTH_PROPERTY("border-bottom-left-radius", ID::BORDER_BOTTOM_LEFT_RADIUS); LENGTH_PROPERTY("border-bottom-right-radius", ID::BORDER_BOTTOM_RIGHT_RADIUS); LENGTH_PROPERTY("border-left-width", ID::BORDER_LEFT_WIDTH); LENGTH_PROPERTY("border-top-width", ID::BORDER_TOP_WIDTH); LENGTH_PROPERTY("border-right-width", ID::BORDER_RIGHT_WIDTH); LENGTH_PROPERTY("border-bottom-width", ID::BORDER_BOTTOM_WIDTH); NUMBER_PROPERTY("flex-grow", ID::FLEX_GROW); NUMBER_PROPERTY("flex-shrink", ID::FLEX_SHRINK); LENGTH_PROPERTY("flex-basis", ID::FLEX_BASIS); PARSE_ENUM_START("flex-direction", ID::FLEX_DIRECTION); PARSE_ENUM_ENTRY(direction, "row", FlexDirection::ROW); PARSE_ENUM_ENTRY(direction, "column", FlexDirection::COLUMN); PARSE_ENUM_ENTRY(direction, "row-reverse", FlexDirection::ROW_REVERSE); PARSE_ENUM_ENTRY(direction, "column-reverse", FlexDirection::COLUMN_REVERSE); PARSE_ENUM_END(); PARSE_ENUM_START("flex-wrap", ID::FLEX_WRAP); PARSE_ENUM_ENTRY(wrap, "nowrap", FlexWrap::NOWRAP); PARSE_ENUM_ENTRY(wrap, "wrap", FlexWrap::WRAP); PARSE_ENUM_ENTRY(wrap, "wrap-reverse", FlexWrap::WRAP_REVERSE); PARSE_ENUM_END(); #define ALIGN_ENUM_ENTRIES() \ PARSE_ENUM_ENTRY(align, "auto", Align::AUTO); \ PARSE_ENUM_ENTRY(align, "flex-start", Align::FLEX_START); \ PARSE_ENUM_ENTRY(align, "center", Align::CENTER); \ PARSE_ENUM_ENTRY(align, "flex-end", Align::FLEX_END); \ PARSE_ENUM_ENTRY(align, "stretch", Align::STRETCH); \ PARSE_ENUM_ENTRY(align, "baseline", Align::BASELINE); \ PARSE_ENUM_ENTRY(align, "space-between", Align::SPACE_BETWEEN); \ PARSE_ENUM_ENTRY(align, "space-around", Align::SPACE_AROUND); PARSE_ENUM_START("align-self", ID::ALIGN_SELF); ALIGN_ENUM_ENTRIES(); PARSE_ENUM_END(); PARSE_ENUM_START("align-items", ID::ALIGN_ITEMS); ALIGN_ENUM_ENTRIES(); PARSE_ENUM_END(); PARSE_ENUM_START("align-content", ID::ALIGN_CONTENT); ALIGN_ENUM_ENTRIES(); PARSE_ENUM_END(); PARSE_ENUM_START("justify-content", ID::JUSTIFY_CONTENT); PARSE_ENUM_ENTRY(justify, "flex-start", Justify::FLEX_START); PARSE_ENUM_ENTRY(justify, "center", Justify::CENTER); PARSE_ENUM_ENTRY(justify, "flex-end", Justify::FLEX_END); PARSE_ENUM_ENTRY(justify, "space-between", Justify::SPACE_BETWEEN); PARSE_ENUM_ENTRY(justify, "space-around", Justify::SPACE_AROUND); PARSE_ENUM_ENTRY(justify, "space-evenly", Justify::SPACE_EVENLY); PARSE_ENUM_END(); PARSE_ENUM_START("position", ID::POSITION); PARSE_ENUM_ENTRY(position, "relative", Position::RELATIVE); PARSE_ENUM_ENTRY(position, "absolute", Position::ABSOLUTE); PARSE_ENUM_END(); LENGTH_PROPERTY("left", ID::LEFT); LENGTH_PROPERTY("top", ID::TOP); LENGTH_PROPERTY("right", ID::RIGHT); LENGTH_PROPERTY("bottom", ID::BOTTOM); COLOR_PROPERTY("color", ID::COLOR); COLOR_PROPERTY("background-color", ID::BACKGROUND_COLOR); PARSE_ENUM_START("overflow", ID::OVERFLOW); PARSE_ENUM_ENTRY(overflow, "visible", Overflow::VISIBLE); PARSE_ENUM_ENTRY(overflow, "hidden", Overflow::HIDDEN); PARSE_ENUM_ENTRY(overflow, "scroll", Overflow::SCROLL); PARSE_ENUM_END(); PARSE_ENUM_START("display", ID::DISPLAY); PARSE_ENUM_ENTRY(display, "flex", Display::FLEX); PARSE_ENUM_ENTRY(display, "none", Display::NONE); PARSE_ENUM_END(); STRING_PROPERTY("font-family", ID::FONT_FAMILY); LENGTH_PROPERTY("font-size", ID::FONT_SIZE); PARSE_ENUM_START("white-space", ID::WHITE_SPACE); PARSE_ENUM_ENTRY(whiteSpace, "normal", WhiteSpace::NORMAL); PARSE_ENUM_ENTRY(whiteSpace, "nowrap", WhiteSpace::NOWRAP); PARSE_ENUM_END(); PARSE_ENUM_START("cursor", ID::CURSOR); PARSE_ENUM_ENTRY(cursor, "auto", StyleCursor::AUTO); PARSE_ENUM_ENTRY(cursor, "default", StyleCursor::DEFAULT); PARSE_ENUM_ENTRY(cursor, "none", StyleCursor::NONE); PARSE_ENUM_ENTRY(cursor, "help", StyleCursor::HELP); PARSE_ENUM_ENTRY(cursor, "pointer", StyleCursor::POINTER); PARSE_ENUM_ENTRY(cursor, "progress", StyleCursor::PROGRESS); PARSE_ENUM_ENTRY(cursor, "wait", StyleCursor::WAIT); PARSE_ENUM_ENTRY(cursor, "crosshair", StyleCursor::CROSSHAIR); PARSE_ENUM_ENTRY(cursor, "text", StyleCursor::TEXT); PARSE_ENUM_ENTRY(cursor, "move", StyleCursor::MOVE); PARSE_ENUM_ENTRY(cursor, "not-allowed", StyleCursor::NOT_ALLOWED); PARSE_ENUM_ENTRY(cursor, "all-scroll", StyleCursor::ALL_SCROLL); PARSE_ENUM_ENTRY(cursor, "col-resize", StyleCursor::COL_RESIZE); PARSE_ENUM_ENTRY(cursor, "row-resize", StyleCursor::ROW_RESIZE); PARSE_ENUM_END(); // shorthands #define FOUR_LENGTH_SHORTHAND(prop_name, a, b, c, d) \ case HashStr(prop_name): \ if (parseLength(value, prop.value.length, parseResult)) { \ prop.id = a; \ rule.properties.emplace_back(prop); \ prop.id = b; \ rule.properties.emplace_back(prop); \ prop.id = c; \ rule.properties.emplace_back(prop); \ prop.id = d; \ rule.properties.emplace_back(prop); \ return true; \ } \ break; FOUR_LENGTH_SHORTHAND( "border-radius", ID::BORDER_TOP_LEFT_RADIUS, ID::BORDER_TOP_RIGHT_RADIUS, ID::BORDER_BOTTOM_LEFT_RADIUS, ID::BORDER_BOTTOM_RIGHT_RADIUS ) FOUR_LENGTH_SHORTHAND( "border-width", ID::BORDER_LEFT_WIDTH, ID::BORDER_TOP_WIDTH, ID::BORDER_RIGHT_WIDTH, ID::BORDER_BOTTOM_WIDTH ) FOUR_LENGTH_SHORTHAND( "margin", ID::MARGIN_LEFT, ID::MARGIN_TOP, ID::MARGIN_RIGHT, ID::MARGIN_BOTTOM ) FOUR_LENGTH_SHORTHAND( "padding", ID::PADDING_LEFT, ID::PADDING_TOP, ID::PADDING_RIGHT, ID::PADDING_BOTTOM ) // TODO: flex shorthand default: parseResult.warnings.emplace_back("Property '" + name + "' is not supported"); break; } return false; } // strip comments and consecutive spaces std::string sanitizeSource(const std::string& input, StyleParseResult& parseResult) { std::string result; bool before_whitespace = false; bool inside_comment = false; for (int i = 0; i < input.size(); i++) { char chr = input[i]; // check if next is closing comment if (chr == '*' && i + 1 < input.size() && input[i + 1] == '/') { i += 2; inside_comment = false; } else if (inside_comment) { // ignore character } else if (std::isspace(chr)) { if (!before_whitespace) { result.push_back(' '); before_whitespace = true; } } // check if next is opening comment else if (chr == '/' && i + 1 < input.size() && input[i + 1] == '*') { i += 2; inside_comment = true; } else { result.push_back(chr); before_whitespace = false; } } if (inside_comment) { parseResult.errors.emplace_back("Expected comment ending but found EOF"); } return result; } bool parseRule(const std::string& source, StyleRule& rule, StyleParseResult& parseResult) { rule.properties.clear(); size_t pos = 0; do { consumeWhiteSpace(source, pos); if (pos >= source.size()) break; // done if (isIdentStart(source[pos])) { // name std::string name = parseIdentifier(source, pos); consumeWhiteSpace(source, pos); if (source[pos] == ':') { pos++; // skip : } else { parseResult.errors.emplace_back("Expected ':'"); return false; } // value // TODO: allow for ; and } inside quotes consumeWhiteSpace(source, pos); auto value_end = source.find_first_of(";}", pos); if (value_end == std::string::npos) value_end = source.size() - 1; // to the end // go back to the first non-space size_t last_non_space = value_end - 1; while (last_non_space > pos && std::isspace(source[last_non_space])) last_non_space--; std::string value = source.substr(pos, last_non_space - pos + 1); pos = value_end + 1; // OE_LOG_DEBUG(" (property)" << name << ":" << value); // parse property ParseStyleProperty(name, value, rule, parseResult); } else if (source[pos] == '}') { pos++; // skip } break; // stop } else { parseResult.errors.emplace_back("Expected identifier but found '" + std::string(1, source[pos]) + "'"); // try to skip to the next property pos = source.find_first_of(";}", pos); if (pos == std::string::npos) return false; // EOF if (source[pos] == ';') pos++; // skip ; else // source[pos] == '}' return rule.properties.size() > 0; } } while (pos < source.size()); return rule.properties.size() > 0; } StyleSheet* ParseStyleSheet(const std::string& raw_source, StyleParseResult& parseResult) { parseResult.errors.clear(); parseResult.warnings.clear(); StyleSheet* sheet = new StyleSheet(); std::string source = sanitizeSource(raw_source, parseResult); size_t pos = 0; while (pos < source.size()) { size_t block_start = source.find("{", pos); if (block_start == std::string::npos) break; // no more blocks size_t block_end = source.find("}", block_start); if (block_end == std::string::npos) { parseResult.errors.emplace_back("Expected block ending but found EOF"); break; } std::string selectors_str = source.substr(pos, block_start - pos); std::string properties_str = source.substr(block_start + 1, block_end - block_start - 1); std::vector<StyleSelector> selectors; if (ParseStyleSelectors(selectors_str, selectors, parseResult)) { StyleRule rule = { }; if (parseRule(properties_str, rule, parseResult)) { if (rule.properties.size() > 0) { // only add if not empty int rule_ref = sheet->addRule(rule); // connect selectors for (StyleSelector& selector : selectors) { selector.computeSpecificity(); sheet->addSelector(selector, rule_ref); } } } } pos = block_end + 1; } return sheet; } }
30.296743
127
0.63784
[ "vector" ]
9fa1a50704c804086b8f0ffffef32bc4859e5362
4,259
cpp
C++
src/astar.cpp
verri/uatcn
bcf8125a4e82eef1953107a573f912962330efb7
[ "MIT" ]
null
null
null
src/astar.cpp
verri/uatcn
bcf8125a4e82eef1953107a573f912962330efb7
[ "MIT" ]
null
null
null
src/astar.cpp
verri/uatcn
bcf8125a4e82eef1953107a573f912962330efb7
[ "MIT" ]
null
null
null
#include "astar.hpp" #include "uat/agent.hpp" #include <algorithm> #include <cmath> #include <limits> #include <random> #include <unordered_map> #include <variant> #include <boost/functional/hash.hpp> #include <cool/compose.hpp> #include <uat/permit.hpp> using namespace uat; struct score_t { value_t g = std::numeric_limits<value_t>::infinity(); value_t f = std::numeric_limits<value_t>::infinity(); }; template <typename T, typename Cmp> class heap { public: heap(Cmp cmp) : cmp_(std::move(cmp)) {} auto push(T value) { for (auto& v : values_) if (v.first == value) v.second = false; values_.push_back({std::move(value), true}); std::push_heap(values_.begin(), values_.end(), [&](const auto& x, const auto& y) { return cmp_(x.first, y.first); }); } auto pop() -> std::pair<T, bool> { while (values_.size() > 1) { std::pop_heap(values_.begin(), values_.end(), [&](const auto& x, const auto& y) { return cmp_(x.first, y.first); }); auto current = std::move(values_.back()); values_.pop_back(); if (current.second) return current; } auto value = std::move(values_.back()); values_.pop_back(); return value; } auto empty() const { return values_.empty(); } private: std::vector<std::pair<T, bool>> values_; Cmp cmp_; }; struct step { permit first; permit second; auto operator==(const step& other) const { return first == other.first && second == other.second; } }; namespace std { template <> struct hash<step> { auto operator()(const step& s) const noexcept -> size_t { size_t seed = 0; boost::hash_combine(seed, std::hash<permit>{}(s.first)); boost::hash_combine(seed, std::hash<permit>{}(s.second)); return seed; } }; } // namespace std auto astar(const region& from, const region& to, uint_t tstart, value_t bid_max_value, permit_public_status_fn& status, int seed) -> std::vector<uat::permit> { using namespace uat::permit_public_status; if (std::holds_alternative<unavailable>(status(from, tstart))) return {}; std::mt19937 gen(seed); const auto h = [to, bid_max_value](const region& s, uint_t t) -> value_t { return 2 * s.heuristic_distance(to) * bid_max_value; }; const auto cost = [&](const permit& s) { return std::visit( cool::compose{[&](unavailable) { return std::numeric_limits<value_t>::infinity(); }, [&](owned) -> value_t { return 0; }, [&](available status) { return status.min_value > bid_max_value ? std::numeric_limits<value_t>::infinity() : bid_max_value; }}, status(s.location(), s.time())); }; std::unordered_map<step, step> came_from; std::unordered_map<step, score_t> score; const step first = {{from, tstart}, {from, tstart}}; score[first] = {0, h(from, tstart)}; const auto cmp = [&score](const step& a, const step& b) { return score[a].f > score[b].f; }; heap<step, decltype(cmp)> open(cmp); open.push(first); const auto try_path = [&](const step& current, step next) { const auto d = cost(next.first) + cost(next.second); if (std::isinf(d)) return; const auto tentative = score[current].g + d; const auto hnext = h(next.second.location(), next.second.time()); if (tentative < score[next].g) { came_from[next] = current; score[next] = {tentative, tentative + hnext}; open.push(std::move(next)); } }; while (!open.empty()) { const auto [current, valid] = open.pop(); if (!valid) continue; if (current.second.location() == to) { std::vector<permit> path; auto s = current; for (; s.second.location() != from; s = came_from.at(s)) { path.push_back(s.second); path.push_back(s.first); } path.push_back(s.second); return path; } // XXX: should we keep forbiding staying still? // try_path(current, {current.location(), current.time() + 1}); auto nei = current.second.location().adjacent_regions(); std::shuffle(nei.begin(), nei.end(), gen); for (auto nslot : nei) try_path(current, {{current.second.location(), current.second.time() + 1}, {std::move(nslot), current.second.time() + 1}}); } return {}; }
27.301282
129
0.619864
[ "vector" ]
9fa2c286576983c01222b7fb57e3ef0da89a03bb
6,932
hpp
C++
include/GlobalNamespace/EnvironmentEffectsFilterPresetDropdown.hpp
darknight1050/BeatSaber-Quest-Codegen
a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032
[ "Unlicense" ]
null
null
null
include/GlobalNamespace/EnvironmentEffectsFilterPresetDropdown.hpp
darknight1050/BeatSaber-Quest-Codegen
a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032
[ "Unlicense" ]
null
null
null
include/GlobalNamespace/EnvironmentEffectsFilterPresetDropdown.hpp
darknight1050/BeatSaber-Quest-Codegen
a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032
[ "Unlicense" ]
null
null
null
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "extern/beatsaber-hook/shared/utils/typedefs.h" // Including type: UnityEngine.MonoBehaviour #include "UnityEngine/MonoBehaviour.hpp" // Including type: EnvironmentEffectsFilterPreset #include "GlobalNamespace/EnvironmentEffectsFilterPreset.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp" #include "extern/beatsaber-hook/shared/utils/utils.h" // Completed includes // Begin forward declares // Forward declaring namespace: GlobalNamespace namespace GlobalNamespace { } // Forward declaring namespace: HMUI namespace HMUI { // Forward declaring type: SimpleTextDropdown class SimpleTextDropdown; // Forward declaring type: DropdownWithTableView class DropdownWithTableView; } // Forward declaring namespace: System namespace System { // Forward declaring type: Action`1<T> template<typename T> class Action_1; // Forward declaring type: Tuple`2<T1, T2> template<typename T1, typename T2> class Tuple_2; } // Forward declaring namespace: System::Collections::Generic namespace System::Collections::Generic { // Forward declaring type: IReadOnlyList`1<T> template<typename T> class IReadOnlyList_1; } // Completed forward declares // Type namespace: namespace GlobalNamespace { // Size: 0x30 #pragma pack(push, 1) // Autogenerated type: EnvironmentEffectsFilterPresetDropdown class EnvironmentEffectsFilterPresetDropdown : public UnityEngine::MonoBehaviour { public: // Nested type: GlobalNamespace::EnvironmentEffectsFilterPresetDropdown::$$c class $$c; // private HMUI.SimpleTextDropdown _simpleTextDropdown // Size: 0x8 // Offset: 0x18 HMUI::SimpleTextDropdown* simpleTextDropdown; // Field size check static_assert(sizeof(HMUI::SimpleTextDropdown*) == 0x8); // [CompilerGeneratedAttribute] Offset: 0xE241C8 // private System.Action`1<System.Int32> didSelectCellWithIdxEvent // Size: 0x8 // Offset: 0x20 System::Action_1<int>* didSelectCellWithIdxEvent; // Field size check static_assert(sizeof(System::Action_1<int>*) == 0x8); // private System.Collections.Generic.IReadOnlyList`1<System.Tuple`2<EnvironmentEffectsFilterPreset,System.String>> _lightReductionAmountData // Size: 0x8 // Offset: 0x28 System::Collections::Generic::IReadOnlyList_1<System::Tuple_2<GlobalNamespace::EnvironmentEffectsFilterPreset, ::Il2CppString*>*>* lightReductionAmountData; // Field size check static_assert(sizeof(System::Collections::Generic::IReadOnlyList_1<System::Tuple_2<GlobalNamespace::EnvironmentEffectsFilterPreset, ::Il2CppString*>*>*) == 0x8); // Creating value type constructor for type: EnvironmentEffectsFilterPresetDropdown EnvironmentEffectsFilterPresetDropdown(HMUI::SimpleTextDropdown* simpleTextDropdown_ = {}, System::Action_1<int>* didSelectCellWithIdxEvent_ = {}, System::Collections::Generic::IReadOnlyList_1<System::Tuple_2<GlobalNamespace::EnvironmentEffectsFilterPreset, ::Il2CppString*>*>* lightReductionAmountData_ = {}) noexcept : simpleTextDropdown{simpleTextDropdown_}, didSelectCellWithIdxEvent{didSelectCellWithIdxEvent_}, lightReductionAmountData{lightReductionAmountData_} {} // Deleting conversion operator: operator System::IntPtr constexpr operator System::IntPtr() const noexcept = delete; // public System.Void add_didSelectCellWithIdxEvent(System.Action`1<System.Int32> value) // Offset: 0x10BF0E8 void add_didSelectCellWithIdxEvent(System::Action_1<int>* value); // public System.Void remove_didSelectCellWithIdxEvent(System.Action`1<System.Int32> value) // Offset: 0x10BF18C void remove_didSelectCellWithIdxEvent(System::Action_1<int>* value); // private System.Collections.Generic.IReadOnlyList`1<System.Tuple`2<EnvironmentEffectsFilterPreset,System.String>> get_lightReductionAmountData() // Offset: 0x10BF230 System::Collections::Generic::IReadOnlyList_1<System::Tuple_2<GlobalNamespace::EnvironmentEffectsFilterPreset, ::Il2CppString*>*>* get_lightReductionAmountData(); // protected System.Void Start() // Offset: 0x10BF32C void Start(); // protected System.Void OnDestroy() // Offset: 0x10BF4AC void OnDestroy(); // public EnvironmentEffectsFilterPreset GetLightsReductionAmount() // Offset: 0x10BF588 GlobalNamespace::EnvironmentEffectsFilterPreset GetLightsReductionAmount(); // public System.Void SelectCellWithLightReductionAmount(EnvironmentEffectsFilterPreset environmentEffectsFilterPreset) // Offset: 0x10BF65C void SelectCellWithLightReductionAmount(GlobalNamespace::EnvironmentEffectsFilterPreset environmentEffectsFilterPreset); // private System.Int32 GetIdxForLightReductionAmount(EnvironmentEffectsFilterPreset environmentEffectsFilterPreset) // Offset: 0x10BF698 int GetIdxForLightReductionAmount(GlobalNamespace::EnvironmentEffectsFilterPreset environmentEffectsFilterPreset); // private System.Void HandleSimpleTextDropdownDidSelectCellWithIdx(HMUI.DropdownWithTableView dropdownWithTableView, System.Int32 idx) // Offset: 0x10BF890 void HandleSimpleTextDropdownDidSelectCellWithIdx(HMUI::DropdownWithTableView* dropdownWithTableView, int idx); // public System.Void .ctor() // Offset: 0x10BF904 // Implemented from: UnityEngine.MonoBehaviour // Base method: System.Void MonoBehaviour::.ctor() // Base method: System.Void Behaviour::.ctor() // Base method: System.Void Component::.ctor() // Base method: System.Void Object::.ctor() // Base method: System.Void Object::.ctor() template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary> static EnvironmentEffectsFilterPresetDropdown* New_ctor() { static auto ___internal__logger = ::Logger::get().WithContext("GlobalNamespace::EnvironmentEffectsFilterPresetDropdown::.ctor"); return THROW_UNLESS((::il2cpp_utils::New<EnvironmentEffectsFilterPresetDropdown*, creationType>())); } }; // EnvironmentEffectsFilterPresetDropdown #pragma pack(pop) static check_size<sizeof(EnvironmentEffectsFilterPresetDropdown), 40 + sizeof(System::Collections::Generic::IReadOnlyList_1<System::Tuple_2<GlobalNamespace::EnvironmentEffectsFilterPreset, ::Il2CppString*>*>*)> __GlobalNamespace_EnvironmentEffectsFilterPresetDropdownSizeCheck; static_assert(sizeof(EnvironmentEffectsFilterPresetDropdown) == 0x30); } DEFINE_IL2CPP_ARG_TYPE(GlobalNamespace::EnvironmentEffectsFilterPresetDropdown*, "", "EnvironmentEffectsFilterPresetDropdown");
57.289256
476
0.763849
[ "object" ]
9fa40106cce23b1419b5bade6e7b975061ea2c0c
19,341
cpp
C++
base/cluster/mgmt/cluscfg/basecluster/test/baseclustertest.cpp
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
base/cluster/mgmt/cluscfg/basecluster/test/baseclustertest.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
base/cluster/mgmt/cluscfg/basecluster/test/baseclustertest.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
////////////////////////////////////////////////////////////////////////////// // // Copyright (c) 1999-2000 Microsoft Corporation // // Module Name: // BaseClusterTest.cpp // // Description: // Main file for the test harness executable. // Initializes tracing, parses command line and actually call the // BaseClusCfg functions. // // Documentation: // No documention for the test harness. // // Maintained By: // Vij Vasu (Vvasu) 08-MAR-2000 // ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// // Include Files ////////////////////////////////////////////////////////////////////////////// #include "pch.h" #include <stdio.h> #include <objbase.h> #include <limits.h> #include <initguid.h> #include "guids.h" #include "CClusCfgCallback.h" // Show help for this executable. void ShowUsage() { wprintf( L"\nThe syntax of this command is:\n" ); wprintf( L"\nBaseClusterTest.exe [computer-name] {<options>}\n" ); wprintf( L"\n<options> =\n" ); wprintf( L" /FORM NAME= cluster-name DOMAIN= account-domain ACCOUNT= clussvc-account\n" ); wprintf( L" PASSWORD= account-password IPADDR= ip-address(hex)\n" ); wprintf( L" SUBNET= ip-subnet-mask(hex) NICNAME= ip-nic-name\n\n" ); wprintf( L" /JOIN NAME= cluster-name DOMAIN= account-domain ACCOUNT= clussvc-account\n" ); wprintf( L" PASSWORD= account-password\n\n" ); wprintf( L" /CLEANUP\n" ); wprintf( L"\nNotes:\n" ); wprintf( L"- A space is required after an '=' sign.\n" ); wprintf( L"- The order for the parameters has to be the same as shown above.\n" ); } // Create the BaseCluster component. HRESULT HrInitComponent( COSERVERINFO * pcoServerInfoPtrIn , CSmartIfacePtr< IClusCfgBaseCluster > & rspClusCfgBaseClusterIn ) { HRESULT hr = S_OK; do { MULTI_QI mqiInterfaces[] = { { &IID_IClusCfgBaseCluster, NULL, S_OK }, { &IID_IClusCfgInitialize, NULL, S_OK } }; // // Create and initialize the BaseClusterAction component // hr = CoCreateInstanceEx( CLSID_ClusCfgBaseCluster , NULL , CLSCTX_LOCAL_SERVER , pcoServerInfoPtrIn , sizeof( mqiInterfaces ) / sizeof( mqiInterfaces[0] ) , mqiInterfaces ); // Store the retrieved pointers in smart pointers for safe release. rspClusCfgBaseClusterIn.Attach( reinterpret_cast< IClusCfgBaseCluster * >( mqiInterfaces[0].pItf ) ); CSmartIfacePtr< IClusCfgInitialize > spClusCfgInitialize; spClusCfgInitialize.Attach( reinterpret_cast< IClusCfgInitialize * >( mqiInterfaces[1].pItf ) ); // Check if CoCreateInstanceEx() worked. if ( FAILED( hr ) && ( hr != CO_S_NOTALLINTERFACES ) ) { wprintf( L"Could not create the BaseCluster component. Error %#08x.\n", hr ); break; } // if: CoCreateInstanceEx() failed // Check if we got the pointer to the IClusCfgBaseCluster interface. hr = mqiInterfaces[0].hr; if ( FAILED( hr ) ) { // We cannot do anything without this pointer - bail. wprintf( L"Could not get the IClusCfgBaseCluster pointer. Error %#08x.\n", hr ); break; } // if: we could not get a pointer to the IClusCfgBaseCluster interface // // Check if we got a pointer to the IClusCfgInitialize interface hr = mqiInterfaces[1].hr; if ( hr == S_OK ) { // We got the pointer - initialize the component. IUnknown * punk = NULL; IClusCfgCallback * pccb = NULL; hr = CClusCfgCallback::S_HrCreateInstance( &punk ); if ( FAILED( hr ) ) { wprintf( L"Could not initalize callback component. Error %#08x.\n", hr ); break; } hr = punk->QueryInterface< IClusCfgCallback >( &pccb ); punk->Release( ); if ( FAILED( hr ) ) { wprintf( L"Could not find IClusCfgCallback on CClusCfgCallback object. Error %#08x.\n", hr ); break; } hr = spClusCfgInitialize->Initialize( pccb, LOCALE_SYSTEM_DEFAULT ); if ( pccb != NULL ) { pccb->Release(); } // if: we created a callback, release it. if ( FAILED( hr ) ) { if ( hr == HRESULT_FROM_WIN32( ERROR_ACCESS_DENIED ) ) { wprintf( L"Access was denied trying to initialize the BaseCluster component. This may be because remote callbacks are not supported. However, configuration will proceed.\n" ); hr = ERROR_SUCCESS; } // if: the error was ERROR_ACCESS_DENIED else { wprintf( L"Could not initialize the BaseCluster component. Error %#08x occurred. Configuration will be aborted.\n", hr ); break; } // else: some other error occurred. } // if: something went wrong during initialization } // if: we got a pointer to the IClusCfgInitialize interface else { wprintf( L"The BaseCluster component does not provide notifications.\n" ); if ( hr != E_NOINTERFACE ) { break; } // if: the interface is supported, but something else went wrong. // // If the interface is not support, that is ok. It just means that // initialization is not required. // hr = S_OK; } // if: we did not get a pointer to the IClusCfgInitialize interface } while( false ); return hr; } HRESULT HrFormCluster( int argc , WCHAR *argv[] , CSmartIfacePtr< IClusCfgBaseCluster > & rspClusCfgBaseClusterIn ) { HRESULT hr = S_OK; bool fSyntaxError = false; do { if ( argc != 16 ) { wprintf( L"FORM: Incorrect number of parameters.\n" ); fSyntaxError = true; hr = E_INVALIDARG; break; } wprintf( L"Trying to form a cluster...\n"); // Cluster name. if ( ClRtlStrICmp( argv[2], L"NAME=" ) != 0 ) { wprintf( L"Expected 'NAME='. Got '%s'.\n", argv[2] ); fSyntaxError = true; hr = E_INVALIDARG; break; } WCHAR * pszClusterName = argv[3]; wprintf( L" Cluster Name = '%s'\n", pszClusterName ); // Cluster account domain if ( ClRtlStrICmp( argv[4], L"DOMAIN=" ) != 0 ) { wprintf( L"Expected 'DOMAIN='. Got '%s'.\n", argv[4] ); fSyntaxError = true; hr = E_INVALIDARG; break; } WCHAR * pszClusterAccountDomain = argv[5]; wprintf( L" Cluster Account Domain = '%s'\n", pszClusterAccountDomain ); // Cluster account name. if ( ClRtlStrICmp( argv[6], L"ACCOUNT=" ) != 0 ) { wprintf( L"Expected 'ACCOUNT='. Got '%s'.\n", argv[6] ); fSyntaxError = true; hr = E_INVALIDARG; break; } WCHAR * pszClusterAccountName = argv[7]; wprintf( L" Cluster Account Name = '%s'\n", pszClusterAccountName ); // Cluster account password. if ( ClRtlStrICmp( argv[8], L"PASSWORD=" ) != 0 ) { wprintf( L"Expected 'PASSWORD='. Got '%s'.\n", argv[8] ); fSyntaxError = true; hr = E_INVALIDARG; break; } WCHAR * pszClusterAccountPwd = argv[9]; wprintf( L" Cluster Account Password = '%s'\n", pszClusterAccountPwd ); // Cluster IP address. if ( ClRtlStrICmp( argv[10], L"IPADDR=" ) != 0 ) { wprintf( L"Expected 'IPADDR='. Got '%s'.\n", argv[10] ); fSyntaxError = true; hr = E_INVALIDARG; break; } WCHAR * pTemp; ULONG ulClusterIPAddress = wcstoul( argv[11], &pTemp, 16 ); if ( ( ( argv[11] + wcslen( argv[11] ) ) != pTemp ) || ( ulClusterIPAddress == ULONG_MAX ) ) { wprintf( L"Could not convert '%s' to an IP address.\n", argv[11] ); fSyntaxError = true; hr = E_INVALIDARG; break; } wprintf( L" Cluster IP Address = %d.%d.%d.%d\n" , ( ulClusterIPAddress & 0xFF000000 ) >> 24 , ( ulClusterIPAddress & 0x00FF0000 ) >> 16 , ( ulClusterIPAddress & 0x0000FF00 ) >> 8 , ( ulClusterIPAddress & 0x000000FF ) ); // Cluster IP subnet mask. if ( ClRtlStrICmp( argv[12], L"SUBNET=" ) != 0 ) { wprintf( L"Expected 'SUBNET='. Got '%s'.\n", argv[12] ); fSyntaxError = true; hr = E_INVALIDARG; break; } ULONG ulClusterIPSubnetMask = wcstoul( argv[13], &pTemp, 16 ); if ( ( ( argv[13] + wcslen( argv[13] ) ) != pTemp ) || ( ulClusterIPAddress == ULONG_MAX ) ) { wprintf( L"Could not convert '%s' to a subnet mask.\n", argv[13] ); fSyntaxError = true; hr = E_INVALIDARG; break; } wprintf( L" Cluster IP subnet mask = %d.%d.%d.%d\n" , ( ulClusterIPSubnetMask & 0xFF000000 ) >> 24 , ( ulClusterIPSubnetMask & 0x00FF0000 ) >> 16 , ( ulClusterIPSubnetMask & 0x0000FF00 ) >> 8 , ( ulClusterIPSubnetMask & 0x000000FF ) ); // Cluster IP NIC name. if ( ClRtlStrICmp( argv[14], L"NICNAME=" ) != 0 ) { wprintf( L"Expected 'NICNAME='. Got '%s'.\n", argv[14] ); fSyntaxError = true; hr = E_INVALIDARG; break; } WCHAR * pszClusterIPNetwork = argv[15]; wprintf( L" Name of the NIC for the cluster IP address = '%s'\n", pszClusterIPNetwork ); // Indicate that a cluster should be formed when Commit() is called. hr = rspClusCfgBaseClusterIn->SetCreate( pszClusterName , pszClusterAccountName , pszClusterAccountPwd , pszClusterAccountDomain , ulClusterIPAddress , ulClusterIPSubnetMask , pszClusterIPNetwork ); if ( FAILED( hr ) ) { wprintf( L"Error %#08x occurred trying to set cluster form parameters.\n", hr ); break; } // if: SetCreate() failed. // Initiate a cluster create operation. hr = rspClusCfgBaseClusterIn->Commit(); if ( hr != S_OK ) { wprintf( L"Error %#08x occurred trying to create the cluster.\n", hr ); break; } // if: Commit() failed. wprintf( L"Cluster successfully created.\n" ); } while( false ); if ( fSyntaxError ) { ShowUsage(); } return hr; } HRESULT HrJoinCluster( int argc , WCHAR *argv[] , CSmartIfacePtr< IClusCfgBaseCluster > & rspClusCfgBaseClusterIn ) { HRESULT hr = S_OK; bool fSyntaxError = false; do { if ( argc != 10 ) { wprintf( L"JOIN: Incorrect number of parameters.\n" ); fSyntaxError = true; hr = E_INVALIDARG; break; } wprintf( L"Trying to join a cluster...\n"); // Cluster name. if ( ClRtlStrICmp( argv[2], L"NAME=" ) != 0 ) { wprintf( L"Expected 'NAME='. Got '%s'.\n", argv[2] ); fSyntaxError = true; hr = E_INVALIDARG; break; } WCHAR * pszClusterName = argv[3]; wprintf( L" Cluster Name = '%s'\n", pszClusterName ); // Cluster account domain if ( ClRtlStrICmp( argv[4], L"DOMAIN=" ) != 0 ) { wprintf( L"Expected 'DOMAIN='. Got '%s'.\n", argv[4] ); fSyntaxError = true; hr = E_INVALIDARG; break; } WCHAR * pszClusterAccountDomain = argv[5]; wprintf( L" Cluster Account Domain = '%s'\n", pszClusterAccountDomain ); // Cluster account name. if ( ClRtlStrICmp( argv[6], L"ACCOUNT=" ) != 0 ) { wprintf( L"Expected 'ACCOUNT='. Got '%s'.\n", argv[6] ); fSyntaxError = true; hr = E_INVALIDARG; break; } WCHAR * pszClusterAccountName = argv[7]; wprintf( L" Cluster Account Name = '%s'\n", pszClusterAccountName ); // Cluster account password. if ( ClRtlStrICmp( argv[8], L"PASSWORD=" ) != 0 ) { wprintf( L"Expected 'PASSWORD='. Got '%s'.\n", argv[8] ); fSyntaxError = true; hr = E_INVALIDARG; break; } WCHAR * pszClusterAccountPwd = argv[9]; wprintf( L" Cluster Account Password = '%s'\n", pszClusterAccountPwd ); // Indicate that a cluster should be joined when Commit() is called. hr = rspClusCfgBaseClusterIn->SetAdd( pszClusterName , pszClusterAccountName , pszClusterAccountPwd , pszClusterAccountDomain ); if ( FAILED( hr ) ) { wprintf( L"Error %#08x occurred trying to set cluster join parameters.\n", hr ); break; } // if: SetAdd() failed. // Initiate cluster join. hr = rspClusCfgBaseClusterIn->Commit(); if ( hr != S_OK ) { wprintf( L"Error %#08x occurred trying to join the cluster.\n", hr ); break; } // if: Commit() failed. wprintf( L"Cluster join successful.\n" ); } while( false ); if ( fSyntaxError ) { ShowUsage(); } return hr; } HRESULT HrCleanupNode( int argc , WCHAR *argv[] , CSmartIfacePtr< IClusCfgBaseCluster > & rspClusCfgBaseClusterIn ) { HRESULT hr = S_OK; bool fSyntaxError = false; do { if ( argc != 2 ) { wprintf( L"CLEANUP: Incorrect number of parameters.\n" ); fSyntaxError = true; hr = E_INVALIDARG; break; } wprintf( L"Trying to cleanup node...\n"); // Indicate that the node should be cleaned up when Commit() is called. hr = rspClusCfgBaseClusterIn->SetCleanup(); if ( FAILED( hr ) ) { wprintf( L"Error %#08x occurred trying to set node cleanup parameters.\n", hr ); break; } // if: SetCleanup() failed. // Initiate node cleanup. hr = rspClusCfgBaseClusterIn->Commit(); if ( hr != S_OK ) { wprintf( L"Error %#08x occurred trying to clean up the node.\n", hr ); break; } // if: Commit() failed. wprintf( L"Node successfully cleaned up.\n" ); } while( false ); if ( fSyntaxError ) { ShowUsage(); } return hr; } // The main function for this program. int __cdecl wmain( int argc, WCHAR *argv[] ) { HRESULT hr = S_OK; // Initialize COM CoInitializeEx( 0, COINIT_MULTITHREADED ); wprintf( L"\n" ); do { COSERVERINFO coServerInfo; COAUTHINFO coAuthInfo; COSERVERINFO * pcoServerInfoPtr = NULL; WCHAR ** pArgList = argv; int nArgc = argc; CSmartIfacePtr< IClusCfgBaseCluster > spClusCfgBaseCluster; if ( nArgc <= 1 ) { ShowUsage(); break; } // Check if a computer name is specified. if ( *pArgList[1] != '/' ) { coAuthInfo.dwAuthnSvc = RPC_C_AUTHN_WINNT; coAuthInfo.dwAuthzSvc = RPC_C_AUTHZ_NONE; coAuthInfo.pwszServerPrincName = NULL; coAuthInfo.dwAuthnLevel = RPC_C_AUTHN_LEVEL_PKT_PRIVACY; coAuthInfo.dwImpersonationLevel = RPC_C_IMP_LEVEL_IMPERSONATE; coAuthInfo.pAuthIdentityData = NULL; coAuthInfo.dwCapabilities = EOAC_NONE; coServerInfo.dwReserved1 = 0; coServerInfo.pwszName = pArgList[1]; coServerInfo.pAuthInfo = &coAuthInfo; coServerInfo.dwReserved2 = 0; pcoServerInfoPtr = &coServerInfo; wprintf( L"Attempting cluster configuration on computer '%s'.\n", pArgList[1] ); // Consume the arguments ++pArgList; --nArgc; } else { wprintf( L"Attempting cluster configuration on this computer.\n" ); } // Initialize the BaseCluster component. hr = HrInitComponent( pcoServerInfoPtr, spClusCfgBaseCluster ); if ( FAILED( hr ) ) { wprintf( L"HrInitComponent() failed. Cannot configure cluster. Error %#08x.\n", hr ); break; } // Parse the command line for options if ( ClRtlStrICmp( pArgList[1], L"/FORM" ) == 0 ) { hr = HrFormCluster( nArgc, pArgList, spClusCfgBaseCluster ); if ( FAILED( hr ) ) { wprintf( L"HrFormCluster() failed. Cannot form cluster. Error %#08x.\n", hr ); break; } } // if: form else if ( ClRtlStrICmp( pArgList[1], L"/JOIN" ) == 0 ) { hr = HrJoinCluster( nArgc, pArgList, spClusCfgBaseCluster ); if ( FAILED( hr ) ) { wprintf( L"HrJoinCluster() failed. Cannot join cluster. Error %#08x.\n", hr ); break; } } // else if: join else if ( ClRtlStrICmp( pArgList[1], L"/CLEANUP" ) == 0 ) { hr = HrCleanupNode( nArgc, pArgList, spClusCfgBaseCluster ); if ( FAILED( hr ) ) { wprintf( L"HrFormCluster() failed. Cannot clean up node. Error %#08x.\n", hr ); break; } } // else if: cleanup else { wprintf( L"Invalid option '%s'.\n", pArgList[1] ); ShowUsage(); } // else: invalid option } while( false ); // dummy do-while loop to avoid gotos. CoUninitialize(); return hr; }
31.34684
196
0.498268
[ "object" ]
9faf82fb7db34485496bf5554ec3378fc33a492c
7,472
hpp
C++
implementations/Vulkan/command_list.hpp
rsayers/abstract-gpu
48176fcb88bde7d56de662c9e49d3d0e562819e1
[ "MIT" ]
41
2016-03-25T18:14:37.000Z
2022-01-20T11:16:52.000Z
implementations/Vulkan/command_list.hpp
rsayers/abstract-gpu
48176fcb88bde7d56de662c9e49d3d0e562819e1
[ "MIT" ]
4
2016-05-05T22:08:01.000Z
2021-12-10T13:06:55.000Z
implementations/Vulkan/command_list.hpp
rsayers/abstract-gpu
48176fcb88bde7d56de662c9e49d3d0e562819e1
[ "MIT" ]
9
2016-05-23T01:51:25.000Z
2021-08-21T15:32:37.000Z
#ifndef AGPU_COMMAND_LIST_HPP #define AGPU_COMMAND_LIST_HPP #include "device.hpp" namespace AgpuVulkan { class AVkCommandList : public agpu::command_list { public: AVkCommandList(const agpu::device_ref &device); ~AVkCommandList(); static agpu::command_list_ref create(const agpu::device_ref &device, agpu_command_list_type type, const agpu::command_allocator_ref &allocator, const agpu::pipeline_state_ref &initial_pipeline_state); virtual agpu_error setShaderSignature(const agpu::shader_signature_ref &signature) override; virtual agpu_error setViewport(agpu_int x, agpu_int y, agpu_int w, agpu_int h) override; virtual agpu_error setScissor(agpu_int x, agpu_int y, agpu_int w, agpu_int h) override; virtual agpu_error usePipelineState(const agpu::pipeline_state_ref &pipeline) override; virtual agpu_error useVertexBinding(const agpu::vertex_binding_ref &vertex_binding) override; virtual agpu_error useIndexBuffer(const agpu::buffer_ref &index_buffer) override; virtual agpu_error useIndexBufferAt(const agpu::buffer_ref &index_buffer, agpu_size offset, agpu_size index_size) override; virtual agpu_error useDrawIndirectBuffer(const agpu::buffer_ref &draw_buffer) override; virtual agpu_error useComputeDispatchIndirectBuffer(const agpu::buffer_ref &dispatch_buffer) override; virtual agpu_error useShaderResources(const agpu::shader_resource_binding_ref &binding) override; virtual agpu_error useShaderResourcesInSlot(const agpu::shader_resource_binding_ref & binding, agpu_uint slot) override; virtual agpu_error useComputeShaderResources(const agpu::shader_resource_binding_ref &binding) override; virtual agpu_error useComputeShaderResourcesInSlot(const agpu::shader_resource_binding_ref & binding, agpu_uint slot) override; virtual agpu_error pushConstants (agpu_uint offset, agpu_uint size, agpu_pointer values) override; virtual agpu_error drawArrays(agpu_uint vertex_count, agpu_uint instance_count, agpu_uint first_vertex, agpu_uint base_instance) override; virtual agpu_error drawArraysIndirect(agpu_size offset, agpu_size drawcount) override; virtual agpu_error drawElements(agpu_uint index_count, agpu_uint instance_count, agpu_uint first_index, agpu_int base_vertex, agpu_uint base_instance) override; virtual agpu_error drawElementsIndirect(agpu_size offset, agpu_size drawcount) override; virtual agpu_error dispatchCompute ( agpu_uint group_count_x, agpu_uint group_count_y, agpu_uint group_count_z ) override; virtual agpu_error dispatchComputeIndirect ( agpu_size offset ) override; virtual agpu_error setStencilReference(agpu_uint reference) override; virtual agpu_error executeBundle(const agpu::command_list_ref &bundle) override; virtual agpu_error close() override; virtual agpu_error reset(const agpu::command_allocator_ref &allocator, const agpu::pipeline_state_ref &initial_pipeline_state) override; virtual agpu_error resetBundle (const agpu::command_allocator_ref &allocator, const agpu::pipeline_state_ref &initial_pipeline_state, agpu_inheritance_info* inheritance_info ) override; virtual agpu_error beginRenderPass(const agpu::renderpass_ref &renderpass, const agpu::framebuffer_ref &framebuffer, agpu_bool secondaryContent) override; virtual agpu_error endRenderPass() override; virtual agpu_error resolveFramebuffer(const agpu::framebuffer_ref &destFramebuffer, const agpu::framebuffer_ref &sourceFramebuffer) override; virtual agpu_error resolveTexture (const agpu::texture_ref &sourceTexture, agpu_uint sourceLevel, agpu_uint sourceLayer, const agpu::texture_ref &destTexture, agpu_uint destLevel, agpu_uint destLayer, agpu_uint levelCount, agpu_uint layerCount, agpu_texture_aspect aspect ) override; virtual agpu_error memoryBarrier(agpu_pipeline_stage_flags source_stage, agpu_pipeline_stage_flags dest_stage, agpu_access_flags source_accesses, agpu_access_flags dest_accesses) override; virtual agpu_error bufferMemoryBarrier(const agpu::buffer_ref & buffer, agpu_pipeline_stage_flags source_stage, agpu_pipeline_stage_flags dest_stage, agpu_access_flags source_accesses, agpu_access_flags dest_accesses, agpu_size offset, agpu_size size) override; virtual agpu_error textureMemoryBarrier(const agpu::texture_ref & texture, agpu_pipeline_stage_flags source_stage, agpu_pipeline_stage_flags dest_stage, agpu_access_flags source_accesses, agpu_access_flags dest_accesses, agpu_texture_usage_mode_mask old_usage, agpu_texture_usage_mode_mask new_usage, agpu_texture_subresource_range* subresource_range) override; virtual agpu_error pushBufferTransitionBarrier(const agpu::buffer_ref & buffer, agpu_buffer_usage_mask old_usage, agpu_buffer_usage_mask new_usage) override; virtual agpu_error pushTextureTransitionBarrier(const agpu::texture_ref & texture, agpu_texture_usage_mode_mask old_usage, agpu_texture_usage_mode_mask new_usage, agpu_texture_subresource_range* subresource_range) override; virtual agpu_error popBufferTransitionBarrier() override; virtual agpu_error popTextureTransitionBarrier() override; virtual agpu_error copyBuffer(const agpu::buffer_ref & source_buffer, agpu_size source_offset, const agpu::buffer_ref & dest_buffer, agpu_size dest_offset, agpu_size copy_size) override; virtual agpu_error copyBufferToTexture(const agpu::buffer_ref & buffer, const agpu::texture_ref & texture, agpu_buffer_image_copy_region* copy_region) override; virtual agpu_error copyTextureToBuffer(const agpu::texture_ref & texture, const agpu::buffer_ref & buffer, agpu_buffer_image_copy_region* copy_region) override; virtual agpu_error copyTexture(const agpu::texture_ref & source_texture, const agpu::texture_ref & dest_texture, agpu_image_copy_region* copy_region) override; void addWaitSemaphore(VkSemaphore semaphore, VkPipelineStageFlags dstStageMask); void addSignalSemaphore(VkSemaphore semaphore); agpu::device_ref device; agpu::command_allocator_ref allocator; agpu_command_list_type type; agpu_uint queueFamilyIndex; VkCommandBuffer commandBuffer; std::vector<VkSemaphore> waitSemaphores; std::vector<VkPipelineStageFlags> waitSemaphoresDstStageMask; std::vector<VkSemaphore> signalSemaphores; private: void resetState(); agpu_error transitionImageUsageMode(VkImage image, agpu_texture_usage_mode_mask allowedUsages, agpu_texture_usage_mode_mask sourceUsage, agpu_texture_usage_mode_mask destUsage, VkImageSubresourceRange range); agpu_error transitionBufferUsageMode(VkBuffer buffer, agpu_buffer_usage_mask oldUsageMode, agpu_buffer_usage_mask newUsageMode); agpu::framebuffer_ref currentFramebuffer; agpu_bool isClosed; agpu_bool isSecondaryContent; agpu::buffer_ref drawIndirectBuffer; agpu::buffer_ref computeDispatchIndirectBuffer; agpu::shader_signature_ref shaderSignature; struct BufferTransitionDesc { agpu::buffer_ref buffer; agpu_buffer_usage_mask oldUsage; agpu_buffer_usage_mask newUsage; }; struct TextureTransitionDesc { agpu::texture_ref texture; agpu_texture_usage_mode_mask oldUsage; agpu_texture_usage_mode_mask newUsage; VkImageSubresourceRange subresourceRange; }; std::vector<BufferTransitionDesc> bufferTransitionStack; std::vector<TextureTransitionDesc> textureTransitionStack; }; } // End of namespace AgpuVulkan #endif //AGPU_COMMAND_LIST_HPP
67.927273
365
0.82682
[ "vector" ]
9fb1363f863d07aa861b0b2930263be734e47736
18,554
hpp
C++
dakota-6.3.0.Windows.x86/include/ExternalEvaluator.hpp
seakers/ExtUtils
b0186098063c39bd410d9decc2a765f24d631b25
[ "BSD-2-Clause" ]
null
null
null
dakota-6.3.0.Windows.x86/include/ExternalEvaluator.hpp
seakers/ExtUtils
b0186098063c39bd410d9decc2a765f24d631b25
[ "BSD-2-Clause" ]
null
null
null
dakota-6.3.0.Windows.x86/include/ExternalEvaluator.hpp
seakers/ExtUtils
b0186098063c39bd410d9decc2a765f24d631b25
[ "BSD-2-Clause" ]
1
2022-03-18T14:13:14.000Z
2022-03-18T14:13:14.000Z
/* ================================================================================ PROJECT: John Eddy's Genetic Algorithms (JEGA) CONTENTS: Definition of class ExternalEvaluator. NOTES: See notes under Class Definition section of this file. PROGRAMMERS: John Eddy (jpeddy@sandia.gov) (JE) ORGANIZATION: Sandia National Laboratories COPYRIGHT: See the LICENSE file in the top level JEGA directory. VERSION: 2.1.0 CHANGES: Thu Nov 09 14:54:09 2006 - Original Version (JE) ================================================================================ */ /* ================================================================================ Document This File ================================================================================ */ /** \file * \brief Contains the definition of the ExternalEvaluator class. */ /* ================================================================================ Prevent Multiple Inclusions ================================================================================ */ #ifndef JEGA_FRONTEND_CONFIGFILE_EXTERNALEVALUATOR_HPP #define JEGA_FRONTEND_CONFIGFILE_EXTERNALEVALUATOR_HPP /* ================================================================================ Includes ================================================================================ */ // JEGAConfig.hpp should be the first include in all JEGA files. #include <../Utilities/include/JEGAConfig.hpp> #include <GeneticAlgorithmEvaluator.hpp> #include <../Utilities/include/JEGATypes.hpp> /* ================================================================================ Pre-Namespace Forward Declares ================================================================================ */ /* ================================================================================ Namespace Aliases ================================================================================ */ /* ================================================================================ Begin Namespace ================================================================================ */ namespace JEGA { namespace Algorithms { /* ================================================================================ In-Namespace Forward Declares ================================================================================ */ class ExternalEvaluator; /* ================================================================================ In-Namespace File Scope Typedefs ================================================================================ */ /* ================================================================================ Class Definition ================================================================================ */ /** * \brief This evaluator operates by calling an external program and reading * results in from a text file. * * The executable can be anything that can be called via the command line such * as an actual assembly, a script or batch file, etc. The command line will * include two arguments. The first is the name of the file from which the * design variable values can be read. The second is the name of the file that * this evaluator will look for in order to read in the results of the * evaluation. The following is an example of such a command line string. * * \verbatim myevaler.exe params3.in results3.out \endverbatim * * The design variables will be written as floating point values, 1 per line * in the params file. The results must be written in the same fashion. The * objective function values must be written followed by constraint values if * there are any. These must be written in the order in which the objectives * and constraints were described to the DesignTarget. * * If JEGA has been built in thread safe mode, this operator will respect the * concurrency as defined and implemented in the base class. * * The name of the executable, the pattern by which to create parameter file * names, and the pattern by which to create response file names are extracted * from the parameter database using the strings "method.jega.exe_name", * "method.jega.out_file_pat", and "method.jega.in_file_pat" respectively. * The number of concurrent evaluations to run is extracted using the string * "method.jega.eval_concurrency". The first 3 are all extracted as strings. * The concurrency is extracted as a size type variable. If the output file * pattern and input file pattern are not supplied, then the default values as * defined by DEFAULT_OUT_PATTERN and DEFAULT_IN_PATTERN are used. If the * executable name is not supplied, then a warning is issued. If a name is not * supplied by the time an evaluation is requested, then a fatal error occurs. * There is no default for this. If a concurrency value is not supplied, then * the default value as defined by DEFAULT_EVAL_CONCUR is used. These are * required in addition to any requirements of the base class. */ class JEGA_SL_IEDECL ExternalEvaluator : public GeneticAlgorithmEvaluator { /* ============================================================================ Class Scope Typedefs ============================================================================ */ public: protected: private: /* ============================================================================ Member Data Declarations ============================================================================ */ public: /// The default number of generations over which to track the metric. static const std::string DEFAULT_OUT_PATTERN; /// The default percent change in the metric being sought. static const std::string DEFAULT_IN_PATTERN; private: /// The name of the executable program to be run for evaluations. std::string _exeName; /// The pattern by which parameter file names are written. /** * These are the files into which design variables get written to be * read in by analysis code. */ std::string _outPattern; /// The pattern by which response file names are written. /** * These are the files into which objective function and constraint * values get written to be read back in by this evaluator. */ std::string _inPattern; std::size_t _evalNum; /// The mutext that protects the _evalNum variable in threadsafe mode. EDDY_DECLARE_MUTABLE_MUTEX(_currEvalMutex) /* ============================================================================ Mutators ============================================================================ */ public: /// Allows mutation of the executable name known by this evaluator. /** * This method issues a verbose level log entry to inform of the new * executable name. * * \param exeName The new name of the program to run for evaluations. */ void SetExecutableName( const std::string& exeName ); /// Allows mutation of the output file name pattern. /** * This method issues a verbose level log entry to inform of the new * pattern. * * \param outPattern The new pattern by which output parameter files * are named. */ void SetOutputFilenamePattern( const std::string& outPattern ); /// Allows mutation of the input file name pattern. /** * This method issues a verbose level log entry to inform of the new * pattern. * * \param inPattern The new pattern by which input response files * are named. */ void SetInputFilenamePattern( const std::string& inPattern ); protected: private: /* ============================================================================ Accessors ============================================================================ */ public: /// Allows access to the name of the executable used by this evaluator. /** * \return The current executable name used in creating command lines * for performing executions. */ inline const std::string& GetExecutableName( ) const; /// Allows access to the parameter output file name pattern. /** * \return The pattern used to create parameter output file names. */ inline const std::string& GetOutputFilenamePattern( ) const; /// Allows access to the response input file name pattern. /** * \return The pattern used to create response input file names. */ inline const std::string& GetInputFilenamePattern( ) const; protected: private: /* ============================================================================ Public Methods ============================================================================ */ public: /// Returns the proper name of this operator. /** * \return The string "external". */ static const std::string& Name( ); /// Returns a full description of what this operator does and how. /** * The returned text is: * \verbatim \endverbatim. * * \return A description of the operation of this operator. */ static const std::string& Description( ); /** * \brief Returns a new instance of this operator class for use by * \a algorithm. * * \param algorithm The GA for which the new evaluator is to be used. * \return A new, default instance of a ExternalEvaluator. */ static GeneticAlgorithmOperator* Create( JEGA::Algorithms::GeneticAlgorithm& algorithm ); /* ============================================================================ Subclass Visible Methods ============================================================================ */ protected: /** * \brief Creates a new output file name whereby all #'s in * \a _outPattern are replaced by the number \a lbRepl. * * \param lbRepl The number to put in place of all #'s in the returned * output file name. * \return The filename resulting from replacing all #'s in * \a _outPattern by \a lbRepl. */ std::string GetOutputFilename( std::size_t lbRepl ) const; /** * \brief Creates a new input file name whereby all #'s in * \a _inPattern are replaced by the number \a lbRepl. * * \param lbRepl The number to put in place of all #'s in the returned * input file name. * \return The filename resulting from replacing all #'s in * \a _inPattern by \a lbRepl. */ std::string GetInputFilename( std::size_t lbRepl ) const; /* ============================================================================ Subclass Overridable Methods ============================================================================ */ public: /// Does evaluation of each Design in \a group. /** * This method is overridden only to do some sanity checking with the * names of the input files and output files in the case of a >1 * evaluation concurrency. If the concurrency is >1, then the names * must have wildcards. After the check, the base class implementation * is invoked. * * \param group The group containing the Designs to be evaluated. * \return True if all Designs evaluate successfully and false * otherwise. */ virtual bool Evaluate( JEGA::Utilities::DesignGroup& group ); /** * \brief Overridden to perform evaluation of the Design provided. * * This is the method from which an evaluation is performed. This * method will issue a call to the external evaluation program and * read in the results. * * \param des The design to be evaluted. * \return true if the Design is successfully evaluated and the results * read in and false otherwise. */ virtual bool Evaluate( JEGA::Utilities::Design& des ); ///** // * \brief Overridden to perform evaluation of the Design provided in // * the supplied EvaluationJob. // * // * This is the method from which an evaluation is performed. This // * method will issue a call to the external evaluation program and // * read in the results. // * // * \param evalJob The object containing the information needed to // * perform the evaluation of a Design. // * \return true if the Design is successfully evaluated and the results // * read in and false otherwise. // */ //virtual //bool //Evaluate( // EvaluationJob& evalJob // ); /// Returns the proper name of this operator. /** * \return See Name(). */ virtual std::string GetName( ) const; /// Returns a full description of what this operator does and how. /** * \return See Description(). */ virtual std::string GetDescription( ) const; /** * \brief Creates and returns a pointer to an exact duplicate of this * operator. * * \param algorithm The GA for which the clone is being created. * \return A clone of this operator. */ virtual GeneticAlgorithmOperator* Clone( JEGA::Algorithms::GeneticAlgorithm& algorithm ) const; /// Retrieves specific parameters using Get...FromDB methods. /** * This method is used to extract needed information for this * operator. It does so using the "Get...FromDB" class * of methods from the GeneticAlgorithmOperator base class. * * This version extracts the output file name pattern, input file name * pattern, and the name of the executable to call. * * \param db The database of parameters from which the configuration * information can be retrieved. * \return true if the extraction completed successfully and false * otherwise. */ virtual bool PollForParameters( const JEGA::Utilities::ParameterDatabase& db ); protected: private: /* ============================================================================ Private Methods ============================================================================ */ private: /** * \brief Replaces all occurances of the supplied character in the * supplied string with a string representation of the supplied * value. * * \param of The character to replace. * \param in The string in which to do the replacing. * \param with The number to put in place of all \a of's. */ static std::string ReplaceAllOccurrances( char of, const std::string& in, eddy::utilities::uint64_t with ); /* ============================================================================ Structors ============================================================================ */ public: /// Constructs a ExternalEvaluator for use by \a algorithm. /** * If you use this constructor, it will be necessary for you to supply * an evaluation functor via the SetEvaluationFunctor method prior to * use. * * \param algorithm The GA for which this evaluator is being * constructed. */ ExternalEvaluator( JEGA::Algorithms::GeneticAlgorithm& algorithm ); /// Copy constructs an ExternalEvaluator. /** * \param copy The instance from which properties should be copied into * this. */ ExternalEvaluator( const ExternalEvaluator& copy ); /// Copy constructs an ExternalEvaluator for use by \a algorithm. /** * \param copy The instance from which properties should be copied into * this. * \param algorithm The GA for which this evaluator is being * constructed. */ ExternalEvaluator( const ExternalEvaluator& copy, JEGA::Algorithms::GeneticAlgorithm& algorithm ); }; // class ExternalEvaluator /* ================================================================================ End Namespace ================================================================================ */ } // namespace Algorithms } // namespace JEGA /* ================================================================================ Include Inlined Functions File ================================================================================ */ #include "inline/ExternalEvaluator.hpp.inl" /* ================================================================================ End of Multiple Inclusion Check ================================================================================ */ #endif // JEGA_FRONTEND_CONFIGFILE_EXTERNALEVALUATOR_HPP
29.450794
81
0.476285
[ "object" ]
9fb8b73d30dcd34c572a12b190694996c40d6146
10,957
cpp
C++
PhotoSynthViewer/src/GPUBillboardSet.cpp
dddExperiments/PhotoSynthToolkit
4f81577ca347c30c9c142bad2e6edc278e38a4ca
[ "Unlicense", "MIT" ]
17
2015-02-10T17:44:42.000Z
2021-07-13T01:07:37.000Z
PhotoSynthViewer/src/GPUBillboardSet.cpp
Acidburn0zzz/PhotoSynthToolkit
4f81577ca347c30c9c142bad2e6edc278e38a4ca
[ "Unlicense", "MIT" ]
null
null
null
PhotoSynthViewer/src/GPUBillboardSet.cpp
Acidburn0zzz/PhotoSynthToolkit
4f81577ca347c30c9c142bad2e6edc278e38a4ca
[ "Unlicense", "MIT" ]
11
2015-01-15T04:21:40.000Z
2017-06-12T09:24:47.000Z
/* Copyright (c) 2010 ASTRE Henri (http://www.visual-experiments.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 "GPUBillboardSet.h" #include <OgreHardwareBufferManager.h> #include <OgreHardwareVertexBuffer.h> #include <OgreRoot.h> const Ogre::String GPUBillboardSet::mMovableType("GPUBillboardSet"); GPUBillboardSet::GPUBillboardSet(const Ogre::String& name, const std::vector<PhotoSynth::Vertex>& vertices, bool useGeometryShader, Ogre::Vector2& billboardSize) { mBBRadius = 1.0f; mBillboardSize = billboardSize; setBillboards(vertices, useGeometryShader); } GPUBillboardSet::~GPUBillboardSet() { OGRE_DELETE mRenderOp.vertexData; } void GPUBillboardSet::setBillboards(const std::vector<PhotoSynth::Vertex>& vertices, bool useGeometryShader) { if (mRenderOp.vertexData) OGRE_DELETE mRenderOp.vertexData; if (useGeometryShader) createVertexDataForVertexAndGeometryShaders(vertices); else createVertexDataForVertexShaderOnly(vertices); // Update bounding box and sphere updateBoundingBoxAndSphereFromBillboards(vertices); // Update billboard size setBillboardSize(mBillboardSize); } void GPUBillboardSet::createVertexDataForVertexAndGeometryShaders(const std::vector<PhotoSynth::Vertex>& vertices) { // Setup render operation mRenderOp.operationType = Ogre::RenderOperation::OT_POINT_LIST; mRenderOp.vertexData = OGRE_NEW Ogre::VertexData(); mRenderOp.vertexData->vertexCount = vertices.size(); mRenderOp.vertexData->vertexStart = 0; mRenderOp.useIndexes = false; mRenderOp.indexData = 0; // Vertex format declaration unsigned short sourceBufferIdx = 0; Ogre::VertexDeclaration* decl = mRenderOp.vertexData->vertexDeclaration; size_t currOffset = 0; decl->addElement(sourceBufferIdx, currOffset, Ogre::VET_FLOAT3, Ogre::VES_POSITION); currOffset += Ogre::VertexElement::getTypeSize(Ogre::VET_FLOAT3); decl->addElement(sourceBufferIdx, currOffset, Ogre::VET_COLOUR, Ogre::VES_DIFFUSE); currOffset += Ogre::VertexElement::getTypeSize(Ogre::VET_COLOUR); // Create vertex buffer Ogre::HardwareVertexBufferSharedPtr vbuf = Ogre::HardwareBufferManager::getSingleton().createVertexBuffer( decl->getVertexSize(sourceBufferIdx), mRenderOp.vertexData->vertexCount, Ogre::HardwareBuffer::HBU_STATIC_WRITE_ONLY); // Bind vertex buffer Ogre::VertexBufferBinding* bind = mRenderOp.vertexData->vertexBufferBinding; bind->setBinding(sourceBufferIdx, vbuf); // Fill vertex buffer (see http://www.ogre3d.org/docs/manual/manual_59.html#SEC287) Ogre::RenderSystem* renderSystem = Ogre::Root::getSingletonPtr()->getRenderSystem(); unsigned char* pVert = static_cast<unsigned char*>(vbuf->lock(Ogre::HardwareBuffer::HBL_DISCARD)); Ogre::Real* pReal; Ogre::RGBA* pRGBA; Ogre::VertexDeclaration::VertexElementList elems = decl->findElementsBySource(sourceBufferIdx); Ogre::VertexDeclaration::VertexElementList::iterator itr; for (unsigned int i=0; i<vertices.size(); ++i ) { const PhotoSynth::Vertex& vertex = vertices[i]; for (itr=elems.begin(); itr!=elems.end(); ++itr) { Ogre::VertexElement& elem = *itr; if (elem.getSemantic() == Ogre::VES_POSITION) { elem.baseVertexPointerToElement(pVert, &pReal); *pReal = vertex.position.x; *pReal++; *pReal = vertex.position.y; *pReal++; *pReal = vertex.position.z; *pReal++; } else if (elem.getSemantic() == Ogre::VES_DIFFUSE) { elem.baseVertexPointerToElement(pVert, &pRGBA); renderSystem->convertColourValue(vertex.color, pRGBA); } } // Go to next vertex pVert += vbuf->getVertexSize(); } vbuf->unlock(); // Set material this->setMaterial("GPUBillboardWithGS"); } void GPUBillboardSet::createVertexDataForVertexShaderOnly(const std::vector<PhotoSynth::Vertex>& vertices) { // Setup render operation mRenderOp.operationType = Ogre::RenderOperation::OT_TRIANGLE_LIST; mRenderOp.vertexData = OGRE_NEW Ogre::VertexData(); mRenderOp.vertexData->vertexCount = vertices.size() * 4; mRenderOp.vertexData->vertexStart = 0; mRenderOp.useIndexes = true; mRenderOp.indexData = OGRE_NEW Ogre::IndexData(); mRenderOp.indexData->indexCount = vertices.size() * 6; mRenderOp.indexData->indexStart = 0; // Vertex format declaration unsigned short sourceBufferIdx = 0; Ogre::VertexDeclaration* decl = mRenderOp.vertexData->vertexDeclaration; size_t currOffset = 0; decl->addElement(sourceBufferIdx, currOffset, Ogre::VET_FLOAT3, Ogre::VES_POSITION); currOffset += Ogre::VertexElement::getTypeSize(Ogre::VET_FLOAT3); decl->addElement(sourceBufferIdx, currOffset, Ogre::VET_COLOUR, Ogre::VES_DIFFUSE); currOffset += Ogre::VertexElement::getTypeSize(Ogre::VET_COLOUR); decl->addElement(sourceBufferIdx, currOffset, Ogre::VET_FLOAT2, Ogre::VES_TEXTURE_COORDINATES, 0); currOffset += Ogre::VertexElement::getTypeSize(Ogre::VET_FLOAT2); // Create vertex buffer Ogre::HardwareVertexBufferSharedPtr vbuf = Ogre::HardwareBufferManager::getSingleton().createVertexBuffer( decl->getVertexSize(sourceBufferIdx), mRenderOp.vertexData->vertexCount, Ogre::HardwareBuffer::HBU_STATIC_WRITE_ONLY); // Bind vertex buffer Ogre::VertexBufferBinding* bind = mRenderOp.vertexData->vertexBufferBinding; bind->setBinding(sourceBufferIdx, vbuf); // Fill vertex buffer (see http://www.ogre3d.org/docs/manual/manual_59.html#SEC287) Ogre::RenderSystem* renderSystem = Ogre::Root::getSingletonPtr()->getRenderSystem(); unsigned char* pVert = static_cast<unsigned char*>(vbuf->lock(Ogre::HardwareBuffer::HBL_DISCARD)); Ogre::Real* pReal; Ogre::RGBA* pRGBA; Ogre::VertexDeclaration::VertexElementList elems = decl->findElementsBySource(sourceBufferIdx); Ogre::VertexDeclaration::VertexElementList::iterator itr; const Ogre::Vector2 uvs[4] = { Ogre::Vector2( -1.f, 1.f ), Ogre::Vector2( -1.f, -1.f ), Ogre::Vector2( 1.f, -1.f ), Ogre::Vector2( 1.f, 1.f ) }; for (unsigned int i=0; i<vertices.size(); ++i ) { const PhotoSynth::Vertex& vertex = vertices[i]; for ( unsigned int j=0; j<4; j++ ) { for (itr=elems.begin(); itr!=elems.end(); ++itr) { Ogre::VertexElement& elem = *itr; if (elem.getSemantic() == Ogre::VES_POSITION) { elem.baseVertexPointerToElement(pVert, &pReal); *pReal = vertex.position.x; *pReal++; *pReal = vertex.position.y; *pReal++; *pReal = vertex.position.z; *pReal++; } else if (elem.getSemantic() == Ogre::VES_DIFFUSE) { elem.baseVertexPointerToElement(pVert, &pRGBA); renderSystem->convertColourValue(vertex.color, pRGBA); } else if (elem.getSemantic() == Ogre::VES_TEXTURE_COORDINATES && elem.getIndex() == 0) { elem.baseVertexPointerToElement(pVert, &pReal); *pReal = uvs[j].x; *pReal++; *pReal = uvs[j].y; *pReal++; } } // Go to next vertex pVert += vbuf->getVertexSize(); } } vbuf->unlock(); // Create index buffer if (mRenderOp.indexData->indexCount>=65536) { Ogre::HardwareIndexBufferSharedPtr ibuf = Ogre::HardwareBufferManager::getSingleton().createIndexBuffer( Ogre::HardwareIndexBuffer::IT_32BIT, mRenderOp.indexData->indexCount, Ogre::HardwareBuffer::HBU_STATIC_WRITE_ONLY, false); mRenderOp.indexData->indexBuffer = ibuf; Ogre::uint32* indices = static_cast<Ogre::uint32*>(ibuf->lock( Ogre::HardwareBuffer::HBL_DISCARD)); Ogre::uint32 indexFirstVertex = 0; const Ogre::uint32 inds[6] = { 0, 1, 2, 3, 0, 2 }; for (unsigned int i=0; i<vertices.size(); ++i) { for (unsigned int j=0; j<6; ++j) { *indices = indexFirstVertex + inds[j]; indices++; } indexFirstVertex +=4; } ibuf->unlock(); } else { Ogre::HardwareIndexBufferSharedPtr ibuf = Ogre::HardwareBufferManager::getSingleton().createIndexBuffer( Ogre::HardwareIndexBuffer::IT_16BIT, mRenderOp.indexData->indexCount, Ogre::HardwareBuffer::HBU_STATIC_WRITE_ONLY, false); mRenderOp.indexData->indexBuffer = ibuf; Ogre::uint16* indices = static_cast<Ogre::uint16*>( ibuf->lock( Ogre::HardwareBuffer::HBL_DISCARD ) ); Ogre::uint32 indexFirstVertex = 0; const Ogre::uint16 inds[6] = { 0, 1, 2, 3, 0, 2 }; for ( unsigned int i=0; i<vertices.size(); ++i ) { for ( unsigned int j=0; j<6; ++j ) { *indices = indexFirstVertex + inds[j]; indices++; } indexFirstVertex +=4; } ibuf->unlock(); } // Set material this->setMaterial("GPUBillboard"); } void GPUBillboardSet::updateBoundingBoxAndSphereFromBillboards(const std::vector<PhotoSynth::Vertex>& vertices) { Ogre::AxisAlignedBox box = calculateBillboardsBoundingBox(vertices); setBoundingBox(box); Ogre::Vector3 vmax = box.getMaximum(); Ogre::Vector3 vmin = box.getMinimum(); Ogre::Real sqLen = std::max(vmax.squaredLength(), vmin.squaredLength()); mBBRadius = Ogre::Math::Sqrt(sqLen); } Ogre::AxisAlignedBox GPUBillboardSet::calculateBillboardsBoundingBox(const std::vector<PhotoSynth::Vertex>& vertices) { Ogre::AxisAlignedBox box; for (std::size_t i=0; i<vertices.size(); ++i) box.merge(vertices[i].position); return box; } Ogre::Real GPUBillboardSet::getSquaredViewDepth(const Ogre::Camera* cam) const { Ogre::Vector3 min, max, mid, dist; min = mBox.getMinimum(); max = mBox.getMaximum(); mid = ((max - min) * 0.5) + min; dist = cam->getDerivedPosition() - mid; return dist.squaredLength(); } const Ogre::String& GPUBillboardSet::getMovableType(void) const { return mMovableType; } void GPUBillboardSet::setBillboardSize(Ogre::Vector2 size) { // The billboard size is stored as custom parameter #0 of this renderable. // In "Vertex shader only" mode, the parameter is used by the vertex program, // In "Vertex+Geometry shader" mode, it is used by the geometry program. setCustomParameter(0, Ogre::Vector4(size.x, size.y, 0.f, 0.f)); mBillboardSize = size; } Ogre::Vector2 GPUBillboardSet::getBillboardSize() const { return mBillboardSize; } Ogre::Real GPUBillboardSet::getBoundingRadius() const { return mBBRadius; }
35.92459
161
0.731861
[ "geometry", "render", "vector" ]
9fba8e0f85f5528b9ca7cfeb12a7b23bb2a9b109
5,130
hh
C++
RAVL2/3D/Mesh/HEMesh.hh
isuhao/ravl2
317e0ae1cb51e320b877c3bad6a362447b5e52ec
[ "BSD-Source-Code" ]
null
null
null
RAVL2/3D/Mesh/HEMesh.hh
isuhao/ravl2
317e0ae1cb51e320b877c3bad6a362447b5e52ec
[ "BSD-Source-Code" ]
null
null
null
RAVL2/3D/Mesh/HEMesh.hh
isuhao/ravl2
317e0ae1cb51e320b877c3bad6a362447b5e52ec
[ "BSD-Source-Code" ]
null
null
null
// This file is part of RAVL, Recognition And Vision Library // Copyright (C) 2002, University of Surrey // This code may be redistributed under the terms of the GNU Lesser // General Public License (LGPL). See the lgpl.licence file for details or // see http://www.gnu.org/copyleft/lesser.html // file-header-ends-here #ifndef RAVL3D_HEMESH_HEADER #define RAVL3D_HEMESH_HEADER 1 //! rcsid="$Id: HEMesh.hh 5240 2005-12-06 17:16:50Z plugger $" //! lib=Ravl3D //! author="Charles Galambos" //! docentry="Ravl.API.3D.Half Edge Mesh" //! date="24/4/2002" //! file="Ravl/3D/Mesh/HEMesh.hh" #include "Ravl/3D/HEMeshFace.hh" #include "Ravl/3D/HEMeshVertex.hh" #include "Ravl/3D/HEMeshEdge.hh" #include "Ravl/3D/HEMeshFaceIter.hh" #include "Ravl/3D/HEMeshVertexIter.hh" #include "Ravl/RefCounter.hh" #include "Ravl/DList.hh" #include "Ravl/IntrDList.hh" #include "Ravl/SArray1d.hh" #include "Ravl/Hash.hh" #include "Ravl/Tuple2.hh" namespace Ravl3DN { using namespace RavlN; class HEMeshC; class TriMeshC; //! userlevel=Develop //: Half Edge Mesh Body class HEMeshBodyC : public RCBodyVC { public: HEMeshBodyC() {} //: Default constructor. // Creates an empty mesh. HEMeshBodyC(const TriMeshC &mesh); //: Construct from a TriMesh ~HEMeshBodyC(); //: Destructor. HEMeshVertexC InsertVertex(const Vector3dC &position,const Vector3dC &norm) { HEMeshVertexC vert(position,norm); vertices.InsLast(vert.Body()); return vert; } //: Insert a new vertex into the mesh. HEMeshVertexC InsertVertex(const VertexC &vert) { HEMeshVertexC nvert(vert); vertices.InsLast(nvert.Body()); return nvert; } //: Insert a new vertex into the mesh. HEMeshVertexC InsertVertexOnEdge(HEMeshEdgeC edge); //: Insert a vertex on an edge. HEMeshFaceC InsertFace(const SArray1dC<HEMeshVertexC> &vertices,HashC<Tuple2C<HEMeshVertexC,HEMeshVertexC> , HEMeshEdgeC> &edgeTab); //: Insert face defined by vertices. UIntT NoFaces() const { return faces.Size(); } //: Get the number of faces. UIntT NoVertices() const { return vertices.Size(); } //: Get the number of vertices. TriMeshC TriMesh() const; //: Build a TriMesh from this mesh. bool CheckMesh(bool canBeOpen = false) const; //: Check mesh structure is consistant. // Returns false if an inconsistancy is found. protected: IntrDListC<HEMeshFaceBodyC> faces; // List of faces in the mesh. IntrDListC<HEMeshVertexBodyC> vertices; // List of vertices. friend class HEMeshC; }; //! userlevel=Normal //: Half Edge Mesh // Reference counted handle to mesh. class HEMeshC : public RCHandleC<HEMeshBodyC> { public: HEMeshC() {} //: Default constructor. HEMeshC(bool) : RCHandleC<HEMeshBodyC>(*new HEMeshBodyC()) {} //: Constructor. HEMeshC(const TriMeshC &mesh) : RCHandleC<HEMeshBodyC>(*new HEMeshBodyC(mesh)) {} //: Construct from a TriMesh HEMeshVertexC InsertVertex(const Vector3dC &position,const Vector3dC &norm) { return Body().InsertVertex(position,norm); } //: Insert a new vertex into the mesh. HEMeshVertexC InsertVertex(const VertexC &vert) { return Body().InsertVertex(vert); } //: Insert a new vertex into the mesh. HEMeshVertexC InsertVertexOnEdge(HEMeshEdgeC edge) { return Body().InsertVertexOnEdge(edge); } //: Insert a vertex on an edge. HEMeshFaceC InsertFace(const SArray1dC<HEMeshVertexC> &vertices,HashC<Tuple2C<HEMeshVertexC,HEMeshVertexC> , HEMeshEdgeC> &edgeTab) { return Body().InsertFace(vertices,edgeTab); } //: Insert face defined by vertices. UIntT NoFaces() const { return Body().NoFaces(); } //: Get the number of faces. UIntT NoVertices() const { return Body().NoVertices(); } //: Get the number of vertices. TriMeshC TriMesh() const; //: Build a TriMesh from this mesh. bool CheckMesh(bool canBeOpen = false) const { return Body().CheckMesh(canBeOpen); } //: Check mesh structure is consistant. // Returns false if an inconsistancy is found. HEMeshFaceIterC Faces() { return HEMeshFaceIterC(Body().faces); } //: List of faces in the mesh. // Use to create HEMeshFaceIterC. HEMeshVertexIterC Vertices() { return HEMeshVertexIterC(Body().vertices); } //: List of vertices. // Use to create HEMeshVertexIterC. HEMeshFaceC FirstFace() { return HEMeshFaceC(Body().faces.First()); } //: Get the first face in the mesh. // Note: The mesh must NOT be empty. HEMeshVertexC FirstVertex() { return HEMeshVertexC(Body().vertices.First()); } //: Get the first vertex in the mesh. // Note: The mesh must NOT be empty. }; BinOStreamC &operator<<(BinOStreamC &strm,const HEMeshC &obj); //: Write to binary stream. // NOT IMPLEMENTED. BinIStreamC &operator>>(BinIStreamC &strm,HEMeshC &obj); //: Read from binary stream. // NOT IMPLEMENTED. } #endif
28.032787
136
0.666277
[ "mesh", "3d" ]
9fbe2c86075bc0fdeedf9dc5991ecf60930bd2e2
8,074
cc
C++
pdns-recursor-4.0.6/unix_utility.cc
hankai17/test
8f38d999a7c6a92eac94b4d9dc8e444619d2144f
[ "MIT" ]
7
2017-07-16T15:09:26.000Z
2021-09-01T02:13:15.000Z
pdns-recursor-4.0.6/unix_utility.cc
hankai17/test
8f38d999a7c6a92eac94b4d9dc8e444619d2144f
[ "MIT" ]
null
null
null
pdns-recursor-4.0.6/unix_utility.cc
hankai17/test
8f38d999a7c6a92eac94b4d9dc8e444619d2144f
[ "MIT" ]
3
2017-09-13T09:54:49.000Z
2019-03-18T01:29:15.000Z
/* PowerDNS Versatile Database Driven Nameserver Copyright (C) 2002 - 2011 PowerDNS.COM BV This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation Additionally, the license of this program contains a special exception which allows to distribute the program in binary form when it is linked against OpenSSL. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "utility.hh" #include <cstring> #include <fcntl.h> #include <unistd.h> #include <stdlib.h> #include "pdnsexception.hh" #include "logger.hh" #include "misc.hh" #include <pwd.h> #include <grp.h> #include <sys/types.h> #include <sys/select.h> #ifdef NEED_INET_NTOP_PROTO extern "C" { const char *inet_ntop(int af, const void *src, char *dst, size_t cnt); } #endif #include "namespaces.hh" // Connects to socket with timeout int Utility::timed_connect( Utility::sock_t sock, const sockaddr *addr, Utility::socklen_t sockaddr_size, int timeout_sec, int timeout_usec ) { fd_set set; struct timeval timeout; int ret; timeout.tv_sec = timeout_sec; timeout.tv_usec = timeout_usec; FD_ZERO(&set); FD_SET(sock, &set); setNonBlocking(sock); if ((ret = connect (sock, addr, sockaddr_size)) < 0) { if (errno != EINPROGRESS) return ret; } ret = select(sock + 1, NULL, &set, NULL, &timeout); setBlocking(sock); return ret; } void Utility::setBindAny(int af, sock_t sock) { const int one = 1; (void) one; // avoids 'unused var' warning on systems that have none of the defines checked below #ifdef IP_FREEBIND if (setsockopt(sock, IPPROTO_IP, IP_FREEBIND, &one, sizeof(one)) < 0) theL()<<Logger::Warning<<"Warning: IP_FREEBIND setsockopt failed: "<<strerror(errno)<<endl; #endif #ifdef IP_BINDANY if (af == AF_INET) if (setsockopt(sock, IPPROTO_IP, IP_BINDANY, &one, sizeof(one)) < 0) theL()<<Logger::Warning<<"Warning: IP_BINDANY setsockopt failed: "<<strerror(errno)<<endl; #endif #ifdef IPV6_BINDANY if (af == AF_INET6) if (setsockopt(sock, IPPROTO_IPV6, IPV6_BINDANY, &one, sizeof(one)) < 0) theL()<<Logger::Warning<<"Warning: IPV6_BINDANY setsockopt failed: "<<strerror(errno)<<endl; #endif #ifdef SO_BINDANY if (setsockopt(sock, SOL_SOCKET, SO_BINDANY, &one, sizeof(one)) < 0) theL()<<Logger::Warning<<"Warning: SO_BINDANY setsockopt failed: "<<strerror(errno)<<endl; #endif } const char *Utility::inet_ntop(int af, const char *src, char *dst, size_t size) { return ::inet_ntop(af,src,dst,size); } unsigned int Utility::sleep(unsigned int sec) { return ::sleep(sec); } void Utility::usleep(unsigned long usec) { struct timespec ts; ts.tv_sec = usec / 1000000; ts.tv_nsec = (usec % 1000000) * 1000; // POSIX.1 recommends using nanosleep instead of usleep ::nanosleep(&ts, NULL); } // Drops the program's group privileges. void Utility::dropGroupPrivs( int uid, int gid ) { if(gid) { if(setgid(gid)<0) { theL()<<Logger::Critical<<"Unable to set effective group id to "<<gid<<": "<<stringerror()<<endl; exit(1); } else theL()<<Logger::Info<<"Set effective group id to "<<gid<<endl; struct passwd *pw=getpwuid(uid); if(!pw) { theL()<<Logger::Warning<<"Unable to determine user name for uid "<<uid<<endl; if (setgroups(0, NULL)<0) { theL()<<Logger::Critical<<"Unable to drop supplementary gids: "<<stringerror()<<endl; exit(1); } } else { if (initgroups(pw->pw_name, gid)<0) { theL()<<Logger::Critical<<"Unable to set supplementary groups: "<<stringerror()<<endl; exit(1); } } } } // Drops the program's user privileges. void Utility::dropUserPrivs( int uid ) { if(uid) { if(setuid(uid)<0) { theL()<<Logger::Critical<<"Unable to set effective user id to "<<uid<<": "<<stringerror()<<endl; exit(1); } else theL()<<Logger::Info<<"Set effective user id to "<<uid<<endl; } } // Returns the current process id. Utility::pid_t Utility::getpid( void ) { return ::getpid(); } // Returns the current time. int Utility::gettimeofday( struct timeval *tv, void *tz ) { return ::gettimeofday(tv,0); } // Retrieves a gid using a groupname. int Utility::makeGidNumeric(const string &group) { int newgid; if(!(newgid=atoi(group.c_str()))) { errno=0; struct group *gr=getgrnam(group.c_str()); if(!gr) { theL()<<Logger::Critical<<"Unable to look up gid of group '"<<group<<"': "<< (errno ? strerror(errno) : "not found") <<endl; exit(1); } newgid=gr->gr_gid; } return newgid; } // Retrieves an uid using a username. int Utility::makeUidNumeric(const string &username) { int newuid; if(!(newuid=atoi(username.c_str()))) { struct passwd *pw=getpwnam(username.c_str()); if(!pw) { theL()<<Logger::Critical<<"Unable to look up uid of user '"<<username<<"': "<< (errno ? strerror(errno) : "not found") <<endl; exit(1); } newuid=pw->pw_uid; } return newuid; } // Returns a random number. long int Utility::random( void ) { return rand(); } // Sets the random seed. void Utility::srandom( unsigned int seed ) { ::srandom(seed); } // Writes a vector. int Utility::writev(int socket, const iovec *vector, size_t count ) { return ::writev(socket,vector,count); } /* this is cut and pasted from dietlibc, gratefully copied! */ static int isleap(int year) { /* every fourth year is a leap year except for century years that are * not divisible by 400. */ return (!(year%4) && ((year%100) || !(year%400))); } time_t Utility::timegm(struct tm *const t) { const static short spm[13] = /* days per month -- nonleap! */ { 0, (31), (31+28), (31+28+31), (31+28+31+30), (31+28+31+30+31), (31+28+31+30+31+30), (31+28+31+30+31+30+31), (31+28+31+30+31+30+31+31), (31+28+31+30+31+30+31+31+30), (31+28+31+30+31+30+31+31+30+31), (31+28+31+30+31+30+31+31+30+31+30), (31+28+31+30+31+30+31+31+30+31+30+31), }; time_t day; time_t i; time_t years = t->tm_year - 70; if (t->tm_sec>60) { t->tm_min += t->tm_sec/60; t->tm_sec%=60; } if (t->tm_min>60) { t->tm_hour += t->tm_min/60; t->tm_min%=60; } if (t->tm_hour>60) { t->tm_mday += t->tm_hour/60; t->tm_hour%=60; } if (t->tm_mon>11) { t->tm_year += t->tm_mon/12; t->tm_mon%=12; } while (t->tm_mday>spm[1+t->tm_mon]) { if (t->tm_mon==1 && isleap(t->tm_year+1900)) { if (t->tm_mon==31+29) break; --t->tm_mday; } t->tm_mday-=spm[t->tm_mon]; ++t->tm_mon; if (t->tm_mon>11) { t->tm_mon=0; ++t->tm_year; } } if (t->tm_year < 70) return (time_t) -1; /* Days since 1970 is 365 * number of years + number of leap years since 1970 */ day = years * 365 + (years + 1) / 4; /* After 2100 we have to subtract 3 leap years for every 400 years This is not intuitive. Most mktime implementations do not support dates after 2059, anyway, so we might leave this out for its bloat. */ if ((years -= 131) >= 0) { years /= 100; day -= (years >> 2) * 3 + 1; if ((years &= 3) == 3) years--; day -= years; } day += t->tm_yday = spm [t->tm_mon] + t->tm_mday-1 + ( isleap (t->tm_year+1900) & (t->tm_mon > 1) ); /* day is now the number of days since 'Jan 1 1970' */ i = 7; t->tm_wday = (day + 4) % i; /* Sunday=0, Monday=1, ..., Saturday=6 */ i = 24; day *= i; i = 60; return ((day + t->tm_hour) * i + t->tm_min) * i + t->tm_sec; }
26.214286
132
0.632276
[ "vector" ]
9fc0c6a047493456d67e154818c53988cad076cc
477
cpp
C++
189 rotate-array/c/main.v2.cpp
o-jules/LeetCode-Problems
e8b31d0dd93f6e49e385ef35689e51f6935cd7cb
[ "MIT" ]
null
null
null
189 rotate-array/c/main.v2.cpp
o-jules/LeetCode-Problems
e8b31d0dd93f6e49e385ef35689e51f6935cd7cb
[ "MIT" ]
null
null
null
189 rotate-array/c/main.v2.cpp
o-jules/LeetCode-Problems
e8b31d0dd93f6e49e385ef35689e51f6935cd7cb
[ "MIT" ]
null
null
null
/** * Leetcode 最优解示例 * * 时间复杂度O(n) * 空间复杂度O(1) * */ void reverse(vector<int>& nums, int start, int end) { int temp; while (start < end) { temp = nums[start]; nums[start] = nums[end]; nums[end] = temp; start++; end--; } } void rotate(vector<int>& nums, int k) { int lenth = nums.size(); if(lenth <= 1) { eturn; } k=k%lenth; reverse(nums, 0, lenth - k - 1); reverse(nums, lenth - k, lenth - 1); reverse(nums, 0, lenth - 1); }
15.387097
53
0.536688
[ "vector" ]
9fc422329736f5109c2b08b1f642e14b88fee179
14,880
cpp
C++
src/TestSuite.cpp
krnflake/deeplearn
51d517b882f16c0b3361baa1f79233fa2e1c517c
[ "MIT" ]
19
2016-02-10T10:30:36.000Z
2022-01-23T03:09:38.000Z
src/TestSuite.cpp
krnflake/deeplearn
51d517b882f16c0b3361baa1f79233fa2e1c517c
[ "MIT" ]
null
null
null
src/TestSuite.cpp
krnflake/deeplearn
51d517b882f16c0b3361baa1f79233fa2e1c517c
[ "MIT" ]
3
2016-06-09T09:04:42.000Z
2022-01-23T03:09:38.000Z
#include <libgen.h> #include <iostream> #include <vector> #include <memory> #include <ctime> #include "ocl/Device.h" #include "ocl/Utils.h" #include "utils/Mnist.h" #include "nn/NN.h" #include "utils/OpenCL.h" #include "common/Common.h" using namespace std; using namespace nn; #define RANDOM_SIZES true #define NUM_REPETITIONS 1 #define RunTest(name, do_cpu, do_gpu) \ start = clock(); \ for (int i = 0; i < NUM_REPETITIONS; i++) { \ do_cpu; \ } \ cpu_time = (clock() - start) / (double)CLOCKS_PER_SEC; \ start = clock(); \ for (int i = 0; i < NUM_REPETITIONS; i++) { \ do_gpu; \ } \ nn::GPUContext::device->AwaitJobCompletion(); \ gpu_time = (clock() - start) / (double)CLOCKS_PER_SEC; \ printf("%50s CPU: %.6fs GPU: %.6fs %10.2fx Speedup\n", \ name, cpu_time / NUM_REPETITIONS, gpu_time / NUM_REPETITIONS, \ (cpu_time / gpu_time)); // Needed for the benchmarks. clock_t start; double cpu_time, gpu_time; // Input sizes. size_t small_1; size_t small_2; size_t large; inline size_t RandBetween(size_t min, size_t max) { return rand() % (max-min + 1) + min; } void RunBasicTensorTests() { // Basic shape test. Shape s({15, 30, 45}); Assert(s.TotalElementCount() == 15 * 30 * 45); Assert(s.rank() == 3); Assert(s.ElementShape() == Shape({30, 45})); Assert(s.ElementShape().rank() == 2); // Basic shape and size tests. CPUTensor h_tensor({10, 10, 10}, RandomInitializer()); GPUTensor g_tensor = h_tensor.ToGPU(); CPUTensor h_row({10}, RandomInitializer()); GPUTensor g_row = h_row.ToGPU(); Assert(h_tensor.shape() == Shape({10, 10, 10})); Assert(h_tensor.shape() == g_tensor.shape()); Assert(h_tensor.size() == 1000); Assert(h_tensor.size() == g_tensor.size()); // Copy and assignment operator tests. CPUTensor h_tensor_copy(h_tensor); GPUTensor g_tensor_copy(g_tensor); Assert(h_tensor_copy == h_tensor); Assert(g_tensor_copy.ToHost() == g_tensor.ToHost()); h_tensor_copy = h_row; g_tensor_copy = g_row; Assert(h_tensor_copy == h_row); Assert(g_tensor_copy.ToHost() == g_row.ToHost()); // Sub-tensor access tests. Assert(h_tensor[0].shape() == Shape({10, 10}) && g_tensor[0].shape() == Shape({10, 10})); Assert(h_tensor[0][9].shape() == Shape({10}) && g_tensor[0][9].shape() == Shape({10})); Assert(h_tensor[9].size() == 100 && g_tensor[9].size() == 100); Assert(h_tensor[9][0].size() == 10 && g_tensor[9][0].size() == 10); Assert(h_tensor[5] == g_tensor[5].ToHost()); h_tensor[5].Clear(); g_tensor[5].Clear(); Assert(h_tensor == g_tensor.ToHost()); h_tensor[0][4] = h_row; g_tensor[0][4] = g_row; Assert(h_tensor[0][4] == h_row); Assert(h_tensor == g_tensor.ToHost()); } void RunTensorArithmeticTests() { CPUTensor h_x({large}, RandomInitializer()), h_y({large}, RandomInitializer()); GPUTensor g_x = h_x.ToGPU(), g_y = h_y.ToGPU(); CPUTensor h_output({large}); GPUTensor g_output({large}); // Addition RunTest("Tensor addition", add(h_x, h_y, h_output), add(g_x, g_y, g_output)); Check(h_output == g_output.ToHost(), "Tensor addition test failed"); Check(h_x + h_y == (g_x + g_y).ToHost(), "Tensor addition test failed"); // Subtraction RunTest("Tensor subtraction", sub(h_x, h_y, h_output), sub(g_x, g_y, g_output)); Check(h_output == g_output.ToHost(), "Tensor subtraction test failed"); Check(h_x - h_y == (g_x - g_y).ToHost(), "Tensor subtraction test failed"); // Multiplication RunTest("Tensor multiplication", mul(h_x, h_y, h_output), mul(g_x, g_y, g_output)); Check(h_output == g_output.ToHost(), "Tensor multiplication test failed"); Check(h_x * h_y == (g_x * g_y).ToHost(), "Tensor multiplication test failed"); // Division RunTest("Tensor division", div(h_x, h_y, h_output), div(g_x, g_y, g_output)); Check(h_output == g_output.ToHost(), "Tensor divison test failed"); Check(h_x / h_y == (g_x / g_y).ToHost(), "Tensor division test failed"); // Exp RunTest("Elementwise exp()", exp(h_x, h_output), exp(g_x, g_output)); Check(h_output == g_output.ToHost(), "Elementwise exp() test failed"); // Log // Initialize input tensors with large values to avoid NaNs. for (auto& f : h_x) f = 10 + rand() % 100; g_x = h_x.ToGPU(); RunTest("Elementwise log()", log(h_x, h_output), log(g_x, g_output)); Check(h_output == g_output.ToHost(), "Elementwise log() test failed"); } void RunLinearAlgebraTests() { CPUTensor h_matrix({small_2, small_1}, RandomInitializer()), h_vector1({small_1}, RandomInitializer()), h_vector2({small_2}, RandomInitializer()), h_vector3({large}, RandomInitializer()), h_vector4({large}, RandomInitializer()); GPUTensor g_matrix = h_matrix.ToGPU(), g_vector1 = h_vector1.ToGPU(), g_vector2 = h_vector2.ToGPU(), g_vector3 = h_vector3.ToGPU(), g_vector4 = h_vector4.ToGPU(); CPUTensor h_output1({small_1}), h_output2({small_2}), h_output3({small_1, small_2}); GPUTensor g_output1({small_1}), g_output2({small_2}), g_output3({small_1, small_2}); float cpu_result, gpu_result; // Matrix-vector multiplication RunTest("Matrix-vector multiplication", matvecmul(h_matrix, h_vector1, h_output2), matvecmul(g_matrix, g_vector1, g_output2)); Check(h_output2 == g_output2.ToHost(), "Matrix-vector multiplication test failed"); // Transposed matrix-vector multiplication RunTest("Transposed matrix-vector multiplication", transposed_matvecmul(h_matrix, h_vector2, h_output1), transposed_matvecmul(g_matrix, g_vector2, g_output1)); Check(h_output1 == g_output1.ToHost(), "Transposed matrix-vector multiplication test failed"); // Vector dot product RunTest("Vector-vector multiplication", cpu_result = vecmul(h_vector3, h_vector4), gpu_result = vecmul(g_vector3, g_vector4)); Check(floatEq(cpu_result, gpu_result), "Vector-vector multiplication test failed"); // Transposed Vector product RunTest("Transposed vector-vector multiplication", transposed_vecmul(h_vector1, h_vector2, h_output3), transposed_vecmul(g_vector1, g_vector2, g_output3)); Check(h_output3 == g_output3.ToHost(), "Transposed vector-vector multiplication test failed"); } void RunConvolutionTests() { // We need smaller input sizes if built without optimization... #if DEBUG size_t num_features=2, num_channels=2, width=33, height=33; #else size_t num_features=64, num_channels=64, width=32, height=32; #endif CPUTensor h_image({num_channels, height, width}, RandomInitializer()), h_kernel({num_features, num_channels, 7, 7}, RandomInitializer()); GPUTensor g_image = h_image.ToGPU(), g_kernel = h_kernel.ToGPU(); CPUTensor h_image2({num_features, height, width}); GPUTensor g_image2({num_features, height, width}); // Convolution RunTest("Convolution", convolution(h_image, h_kernel, h_image2), convolution(g_image, g_kernel, g_image2)); Check(h_image2 == g_image2.ToHost(), "Convolution test failed"); // Cross-correlation RunTest("Cross-correlation", cross_correlation(h_image2, h_kernel, h_image), cross_correlation(g_image2, g_kernel, g_image)); Check(h_image == g_image.ToHost(), "Cross-correlation test failed"); h_image = CPUTensor({num_channels, height, width}, RandomInitializer(0, 0.1)); h_image2 = CPUTensor({num_features, height, width}, RandomInitializer(0, 0.1)); g_image = h_image.ToGPU(); g_image2 = h_image2.ToGPU(); // Convolution gradients RunTest("Convolution gradients", convolution_kernel_gradients(h_image, h_image2, h_kernel), convolution_kernel_gradients(g_image, g_image2, g_kernel)); Check(h_kernel == g_kernel.ToHost(), "Convolution kernel gradient test failed"); } void RunActivationTests() { CPUTensor h_input({large}, RandomInitializer()), h_output({large}); GPUTensor g_input = h_input.ToGPU(), g_output({large}); // Sigmoid RunTest("Sigmoid activation", sigmoid(h_input, h_output), sigmoid(g_input, g_output)); Check(h_output == g_output.ToHost(), "Sigmoid test failed"); // ReLU RunTest("ReLU activation", relu(h_input, h_output), relu(g_input, g_output)); Check(h_output == g_output.ToHost(), "Sigmoid test failed"); } void RunLossFunctionTests() { CPUTensor h_input1({large}, RandomInitializer()), h_input2({large}, RandomInitializer()); GPUTensor g_input1 = h_input1.ToGPU(), g_input2 = h_input2.ToGPU(); float cpu_result, gpu_result; // Mean squared error RunTest("Mean squared error calculation", cpu_result = mse(h_input1, h_input2), gpu_result = mse(g_input1, g_input2)); Check(floatEq(cpu_result, gpu_result), "MSE test failed"); } void RunLayerTests() { // // Tensor setup const CPUTensor* cpu_result_tensor; const GPUTensor* gpu_result_tensor; // Convolution dimensions. #if DEBUG size_t num_features=16, num_channels=16, width=32, height=32; #else size_t num_features=64, num_channels=64, width=64, height=64; #endif CPUTensor h_dense_layer_weights({small_2, small_1}, RandomInitializer()); GPUTensor g_dense_layer_weights = h_dense_layer_weights.ToGPU(); CPUTensor h_bias_layer_weights({large}, RandomInitializer()); GPUTensor g_bias_layer_weights = h_bias_layer_weights.ToGPU(); CPUTensor h_convolution_layer_weights({num_features, num_channels, 5, 5}, RandomInitializer()); GPUTensor g_convolution_layer_weights = h_convolution_layer_weights.ToGPU(); CPUTensor h_dense_layer_input({small_1}, RandomInitializer(0, 0.1)), h_dense_layer_gradients({small_2}, RandomInitializer(0, 0.1)); GPUTensor g_dense_layer_input = h_dense_layer_input.ToGPU(), g_dense_layer_gradiensts = h_dense_layer_gradients.ToGPU(); CPUTensor h_bias_layer_input({large}, RandomInitializer()), h_bias_layer_gradients({large}, RandomInitializer()); GPUTensor g_bias_layer_input = h_bias_layer_input.ToGPU(), g_bias_layer_gradiensts = h_bias_layer_gradients.ToGPU(); CPUTensor h_image1({num_channels, height, width}, RandomInitializer(0, 0.1)); GPUTensor g_image1 = h_image1.ToGPU(); CPUTensor h_image2({num_features, height, width}, RandomInitializer(0, 0.1)); GPUTensor g_image2 = h_image2.ToGPU(); CPUTensor h_image3({num_features, height/2, width/2}, RandomInitializer(0, 0.1)); GPUTensor g_image3 = h_image3.ToGPU(); // // Instantiate layers. DenseLayer<CPUTensor> h_dense(h_dense_layer_weights); DenseLayer<GPUTensor> g_dense(g_dense_layer_weights); BiasLayer<CPUTensor> h_bias(h_bias_layer_weights); BiasLayer<GPUTensor> g_bias(g_bias_layer_weights); ConvolutionLayer<CPUTensor> h_convolution({num_channels, height, width}, h_convolution_layer_weights); ConvolutionLayer<GPUTensor> g_convolution({num_channels, height, width}, g_convolution_layer_weights); MaxPool2DLayer<CPUTensor> h_maxpool({num_features, height, width}, 2, 2); MaxPool2DLayer<GPUTensor> g_maxpool({num_features, height, width}, 2, 2); // // Run tests RunTest("Fully connected layer (Forward)", cpu_result_tensor = &h_dense.Forward(h_dense_layer_input), gpu_result_tensor = &g_dense.Forward(g_dense_layer_input)); Check((*cpu_result_tensor) == gpu_result_tensor->ToHost(), "Dense layer test failed"); RunTest("Fully connected layer (Backward)", cpu_result_tensor = &h_dense.Backward(h_dense_layer_gradients), gpu_result_tensor = &g_dense.Backward(g_dense_layer_gradiensts)); Check((*cpu_result_tensor) == gpu_result_tensor->ToHost(), "Dense layer test failed"); Check(h_dense.CurrentGradients() == g_dense.CurrentGradients().ToHost(), "Dense layer test failed"); RunTest("Bias layer (Forward)", cpu_result_tensor = &h_bias.Forward(h_bias_layer_input), gpu_result_tensor = &g_bias.Forward(g_bias_layer_input)); Check((*cpu_result_tensor) == gpu_result_tensor->ToHost(), "Bias layer test failed"); RunTest("Bias layer (Backward)", cpu_result_tensor = &h_bias.Backward(h_bias_layer_gradients), gpu_result_tensor = &g_bias.Backward(g_bias_layer_gradiensts)); Check((*cpu_result_tensor) == gpu_result_tensor->ToHost(), "Bias layer test failed"); RunTest("Convolution layer (Forward)", cpu_result_tensor = &h_convolution.Forward(h_image1), gpu_result_tensor = &g_convolution.Forward(g_image1)); Check((*cpu_result_tensor) == gpu_result_tensor->ToHost(), "Convolution layer test failed"); RunTest("Convolution layer (Backward)", cpu_result_tensor = &h_convolution.Backward(h_image2), gpu_result_tensor = &g_convolution.Backward(g_image2)); Check((*cpu_result_tensor) == gpu_result_tensor->ToHost(), "Convolution layer test failed"); Check(h_convolution.CurrentGradients() == g_convolution.CurrentGradients().ToHost(), "Convolution layer test failed"); RunTest("2D Max-pooling layer (Forward)", cpu_result_tensor = &h_maxpool.Forward(h_image2), gpu_result_tensor = &g_maxpool.Forward(g_image2)); Check((*cpu_result_tensor) == gpu_result_tensor->ToHost(), "2D Max-pooling layer test failed"); RunTest("2D Max-pooling layer (Backward)", cpu_result_tensor = &h_maxpool.Backward(h_image3), gpu_result_tensor = &g_maxpool.Backward(g_image3)); Check((*cpu_result_tensor) == gpu_result_tensor->ToHost(), "2D Max-pooling layer test failed"); } int main(int argc, char** argv) { srand(time(0)); Check(InitOpenCL(), "Failed to initialize OpenCL context"); #if RANDOM_SIZES small_1 = RandBetween(1, 10000); small_2 = RandBetween(1, 10000); large = RandBetween(1, 500000); #else small_1 = 444; small_2 = 888; large = 98765; #endif cout << "Test dimensions: small_1=" << small_1 << ", small_2=" << small_2 << ", large=" << large << endl << endl; // Basic tensor tests don't run any benchmarks. RunBasicTensorTests(); cout << " RESULTS" << endl << endl; RunTensorArithmeticTests(); cout << endl; RunLinearAlgebraTests(); cout << endl; RunConvolutionTests(); cout << endl; RunActivationTests(); cout << endl; RunLossFunctionTests(); cout << endl; RunLayerTests(); cout << endl; cout << "\n ALL TESTS PASSED" << endl; return 0; }
40.655738
177
0.671505
[ "shape", "vector" ]
9fca152086a5e6fca15113e083f8b0004df54a4b
26,301
cpp
C++
Engine/Source/Runtime/Engine/Private/GlobalShader.cpp
PopCap/GameIdea
201e1df50b2bc99afc079ce326aa0a44b178a391
[ "BSD-2-Clause" ]
null
null
null
Engine/Source/Runtime/Engine/Private/GlobalShader.cpp
PopCap/GameIdea
201e1df50b2bc99afc079ce326aa0a44b178a391
[ "BSD-2-Clause" ]
2
2015-06-21T17:38:11.000Z
2015-06-22T20:54:42.000Z
Engine/Source/Runtime/Engine/Private/GlobalShader.cpp
PopCap/GameIdea
201e1df50b2bc99afc079ce326aa0a44b178a391
[ "BSD-2-Clause" ]
null
null
null
// Copyright 1998-2015 Epic Games, Inc. All Rights Reserved. /*============================================================================= GlobalShader.cpp: Global shader implementation. =============================================================================*/ #include "EnginePrivate.h" #include "GlobalShader.h" #include "StaticBoundShaderState.h" #include "ShaderCompiler.h" #include "DerivedDataCacheInterface.h" #include "ShaderDerivedDataVersion.h" #include "TargetPlatform.h" /** The global shader map. */ TShaderMap<FGlobalShaderType>* GGlobalShaderMap[SP_NumPlatforms]; IMPLEMENT_SHADER_TYPE(,FNULLPS,TEXT("NullPixelShader"),TEXT("Main"),SF_Pixel); /** Used to identify the global shader map in compile queues. */ const int32 GlobalShaderMapId = 0; FGlobalShaderMapId::FGlobalShaderMapId(EShaderPlatform Platform) { TArray<FShaderType*> ShaderTypes; for (TLinkedList<FShaderType*>::TIterator ShaderTypeIt(FShaderType::GetTypeList()); ShaderTypeIt; ShaderTypeIt.Next()) { FGlobalShaderType* GlobalShaderType = ShaderTypeIt->GetGlobalShaderType(); if (GlobalShaderType && GlobalShaderType->ShouldCache(Platform)) { ShaderTypes.Add(GlobalShaderType); } } ShaderTypes.Sort(FCompareShaderTypes()); for (int32 TypeIndex = 0; TypeIndex < ShaderTypes.Num(); TypeIndex++) { FShaderTypeDependency Dependency; Dependency.ShaderType = ShaderTypes[TypeIndex]; Dependency.SourceHash = ShaderTypes[TypeIndex]->GetSourceHash(); ShaderTypeDependencies.Add(Dependency); } } void FGlobalShaderMapId::AppendKeyString(FString& KeyString) const { TMap<const TCHAR*,FCachedUniformBufferDeclaration> ReferencedUniformBuffers; for (int32 ShaderIndex = 0; ShaderIndex < ShaderTypeDependencies.Num(); ShaderIndex++) { KeyString += TEXT("_"); const FShaderTypeDependency& ShaderTypeDependency = ShaderTypeDependencies[ShaderIndex]; KeyString += ShaderTypeDependency.ShaderType->GetName(); // Add the type's source hash so that we can invalidate cached shaders when .usf changes are made KeyString += ShaderTypeDependency.SourceHash.ToString(); // Add the serialization history to the key string so that we can detect changes to global shader serialization without a corresponding .usf change ShaderTypeDependency.ShaderType->GetSerializationHistory().AppendKeyString(KeyString); const TMap<const TCHAR*,FCachedUniformBufferDeclaration>& ReferencedUniformBufferStructsCache = ShaderTypeDependency.ShaderType->GetReferencedUniformBufferStructsCache(); // Gather referenced uniform buffers for (TMap<const TCHAR*,FCachedUniformBufferDeclaration>::TConstIterator It(ReferencedUniformBufferStructsCache); It; ++It) { ReferencedUniformBuffers.Add(It.Key(), It.Value()); } } { TArray<uint8> TempData; FSerializationHistory SerializationHistory; FMemoryWriter Ar(TempData, true); FShaderSaveArchive SaveArchive(Ar, SerializationHistory); // Save uniform buffer member info so we can detect when layout has changed SerializeUniformBufferInfo(SaveArchive, ReferencedUniformBuffers); SerializationHistory.AppendKeyString(KeyString); } } void FGlobalShaderType::BeginCompileShader(EShaderPlatform Platform, TArray<FShaderCompileJob*>& NewJobs) { FShaderCompileJob* NewJob = new FShaderCompileJob(GlobalShaderMapId, NULL, this); FShaderCompilerEnvironment& ShaderEnvironment = NewJob->Input.Environment; UE_LOG(LogShaders, Verbose, TEXT(" %s"), GetName()); // Allow the shader type to modify the compile environment. SetupCompileEnvironment(Platform, ShaderEnvironment); static FString GlobalName(TEXT("Global")); // Compile the shader environment passed in with the shader type's source code. ::GlobalBeginCompileShader( GlobalName, NULL, this, GetShaderFilename(), GetFunctionName(), FShaderTarget(GetFrequency(),Platform), NewJob, NewJobs ); } FShader* FGlobalShaderType::FinishCompileShader(const FShaderCompileJob& CurrentJob) { if (CurrentJob.bSucceeded) { FShaderType* SpecificType = CurrentJob.ShaderType->LimitShaderResourceToThisType() ? CurrentJob.ShaderType : NULL; // Reuse an existing resource with the same key or create a new one based on the compile output // This allows FShaders to share compiled bytecode and RHI shader references FShaderResource* Resource = FShaderResource::FindOrCreateShaderResource(CurrentJob.Output, SpecificType); check(Resource); // Find a shader with the same key in memory FShader* Shader = CurrentJob.ShaderType->FindShaderById(FShaderId(GGlobalShaderMapHash, NULL, CurrentJob.ShaderType, CurrentJob.Input.Target)); // There was no shader with the same key so create a new one with the compile output, which will bind shader parameters if (!Shader) { Shader = (*ConstructCompiledRef)(CompiledShaderInitializerType(this, CurrentJob.Output, Resource, GGlobalShaderMapHash, NULL)); CurrentJob.Output.ParameterMap.VerifyBindingsAreComplete(GetName(), (EShaderFrequency)CurrentJob.Output.Target.Frequency, CurrentJob.VFType); } return Shader; } else { return NULL; } } FGlobalShader::FGlobalShader(const ShaderMetaType::CompiledShaderInitializerType& Initializer) : FShader(Initializer) { } void BackupGlobalShaderMap(FGlobalShaderBackupData& OutGlobalShaderBackup) { for (int32 i = (int32)ERHIFeatureLevel::ES2; i < (int32)ERHIFeatureLevel::Num; ++i) { EShaderPlatform ShaderPlatform = GetFeatureLevelShaderPlatform((ERHIFeatureLevel::Type)i); if (ShaderPlatform < EShaderPlatform::SP_NumPlatforms && GGlobalShaderMap[ShaderPlatform] != nullptr) { TArray<uint8>* ShaderData = new TArray<uint8>(); FMemoryWriter Ar(*ShaderData); GGlobalShaderMap[ShaderPlatform]->SerializeInline(Ar, true, true); GGlobalShaderMap[ShaderPlatform]->Empty(); OutGlobalShaderBackup.FeatureLevelShaderData[i] = ShaderData; } } // Remove cached references to global shaders for (TLinkedList<FGlobalBoundShaderStateResource*>::TIterator It(FGlobalBoundShaderStateResource::GetGlobalBoundShaderStateList()); It; It.Next()) { BeginUpdateResourceRHI(*It); } } void RestoreGlobalShaderMap(const FGlobalShaderBackupData& GlobalShaderBackup) { for (int32 i = (int32)ERHIFeatureLevel::ES2; i < (int32)ERHIFeatureLevel::Num; ++i) { EShaderPlatform ShaderPlatform = GetFeatureLevelShaderPlatform((ERHIFeatureLevel::Type)i); if (GlobalShaderBackup.FeatureLevelShaderData[i] != nullptr && ShaderPlatform < EShaderPlatform::SP_NumPlatforms && GGlobalShaderMap[ShaderPlatform] != nullptr) { FMemoryReader Ar(*GlobalShaderBackup.FeatureLevelShaderData[i]); GGlobalShaderMap[ShaderPlatform]->SerializeInline(Ar, true, true); } } } /** * Makes sure all global shaders are loaded and/or compiled for the passed in platform. * Note: if compilation is needed, this only kicks off the compile. * * @param Platform Platform to verify global shaders for */ void VerifyGlobalShaders(EShaderPlatform Platform, bool bLoadedFromCacheFile) { check(IsInGameThread()); check(!FPlatformProperties::IsServerOnly()); check(GGlobalShaderMap[Platform]); UE_LOG(LogShaders, Log, TEXT("Verifying Global Shaders for %s"), *LegacyShaderPlatformToShaderFormat(Platform).ToString()); // Ensure that the global shader map contains all global shader types. TShaderMap<FGlobalShaderType>* GlobalShaderMap = GetGlobalShaderMap(Platform); const bool bEmptyMap = GlobalShaderMap->IsEmpty(); if (bEmptyMap) { UE_LOG(LogShaders, Warning, TEXT(" Empty global shader map, recompiling all global shaders")); } TArray<FShaderCompileJob*> GlobalShaderJobs; for(TLinkedList<FShaderType*>::TIterator ShaderTypeIt(FShaderType::GetTypeList());ShaderTypeIt;ShaderTypeIt.Next()) { FGlobalShaderType* GlobalShaderType = ShaderTypeIt->GetGlobalShaderType(); if(GlobalShaderType && GlobalShaderType->ShouldCache(Platform)) { if(!GlobalShaderMap->HasShader(GlobalShaderType)) { bool bErrorOnMissing = bLoadedFromCacheFile; if (FPlatformProperties::RequiresCookedData()) { // We require all shaders to exist on cooked platforms because we can't compile them. bErrorOnMissing = true; } if (bErrorOnMissing) { UE_LOG(LogShaders, Fatal,TEXT("Missing global shader %s, Please make sure cooking was successful."), GlobalShaderType->GetName()); } if (!bEmptyMap) { UE_LOG(LogShaders, Warning, TEXT(" %s"), GlobalShaderType->GetName()); } // Compile this global shader type. GlobalShaderType->BeginCompileShader(Platform, GlobalShaderJobs); } } } if (GlobalShaderJobs.Num() > 0) { GShaderCompilingManager->AddJobs(GlobalShaderJobs, true, true); const bool bAllowAsynchronousGlobalShaderCompiling = // OpenGL requires that global shader maps are compiled before attaching // primitives to the scene as it must be able to find FNULLPS. // TODO_OPENGL: Allow shaders to be compiled asynchronously. !IsOpenGLPlatform(GMaxRHIShaderPlatform) && GShaderCompilingManager->AllowAsynchronousShaderCompiling(); if (!bAllowAsynchronousGlobalShaderCompiling) { TArray<int32> ShaderMapIds; ShaderMapIds.Add(GlobalShaderMapId); GShaderCompilingManager->FinishCompilation(TEXT("Global"), ShaderMapIds); } } } /** Serializes the global shader map to an archive. */ void SerializeGlobalShaders(FArchive& Ar, TShaderMap<FGlobalShaderType>* GlobalShaderMap) { check(IsInGameThread()); // Serialize the global shader map binary file tag. static const uint32 ReferenceTag = 0x47534D42; if (Ar.IsLoading()) { // Initialize Tag to 0 as it won't be written to if the serialize fails (ie the global shader cache file is empty) uint32 Tag = 0; Ar << Tag; checkf(Tag == ReferenceTag, TEXT("Global shader map binary file is missing GSMB tag.")); } else { uint32 Tag = ReferenceTag; Ar << Tag; } // Serialize the global shaders. GlobalShaderMap->SerializeInline(Ar, true, false); } FString GetGlobalShaderCacheFilename(EShaderPlatform Platform) { return FString(TEXT("Engine")) / TEXT("GlobalShaderCache-") + LegacyShaderPlatformToShaderFormat(Platform).ToString() + TEXT(".bin"); } /** Saves the global shader map as a file for the target platform. */ FString SaveGlobalShaderFile(EShaderPlatform Platform, FString SavePath) { TShaderMap<FGlobalShaderType>* GlobalShaderMap = GetGlobalShaderMap(Platform); // Wait until all global shaders are compiled if (GShaderCompilingManager) { GShaderCompilingManager->ProcessAsyncResults(false, true); } TArray<uint8> GlobalShaderData; FMemoryWriter MemoryWriter(GlobalShaderData); SerializeGlobalShaders(MemoryWriter, GlobalShaderMap); // make the final name FString FullPath = SavePath / GetGlobalShaderCacheFilename(Platform); if (!FFileHelper::SaveArrayToFile(GlobalShaderData, *FullPath)) { UE_LOG(LogMaterial, Fatal, TEXT("Could not save global shader file to '%s'"), *FullPath); } return FullPath; } FString GetGlobalShaderMapDDCKey() { return FString(GLOBALSHADERMAP_DERIVEDDATA_VER); } FString GetMaterialShaderMapDDCKey() { return FString(MATERIALSHADERMAP_DERIVEDDATA_VER); } /** Creates a string key for the derived data cache entry for the global shader map. */ FString GetGlobalShaderMapKeyString(const FGlobalShaderMapId& ShaderMapId, EShaderPlatform Platform) { FName Format = LegacyShaderPlatformToShaderFormat(Platform); FString ShaderMapKeyString = Format.ToString() + TEXT("_") + FString(FString::FromInt(GetTargetPlatformManagerRef().ShaderFormatVersion(Format))) + TEXT("_"); ShaderMapAppendKeyString(Platform, ShaderMapKeyString); ShaderMapId.AppendKeyString(ShaderMapKeyString); return FDerivedDataCacheInterface::BuildCacheKey(TEXT("GSM"), GLOBALSHADERMAP_DERIVEDDATA_VER, *ShaderMapKeyString); } /** Saves the platform's shader map to the DDC. */ void SaveGlobalShaderMapToDerivedDataCache(EShaderPlatform Platform) { TArray<uint8> SaveData; FMemoryWriter Ar(SaveData, true); SerializeGlobalShaders(Ar, GGlobalShaderMap[Platform]); FGlobalShaderMapId ShaderMapId(Platform); GetDerivedDataCacheRef().Put(*GetGlobalShaderMapKeyString(ShaderMapId, Platform), SaveData); } TShaderMap<FGlobalShaderType>* GetGlobalShaderMap(EShaderPlatform Platform, bool bRefreshShaderMap) { DECLARE_SCOPE_CYCLE_COUNTER(TEXT("GetGlobalShaderMap"), STAT_GetGlobalShaderMap, STATGROUP_LoadTime); // No global shaders needed on dedicated server if (FPlatformProperties::IsServerOnly()) { if (!GGlobalShaderMap[Platform]) { GGlobalShaderMap[Platform] = new TShaderMap<FGlobalShaderType>(); return GGlobalShaderMap[Platform]; } return NULL; } if (bRefreshShaderMap) { // delete the current global shader map delete GGlobalShaderMap[Platform]; GGlobalShaderMap[Platform] = NULL; // make sure we look for updated shader source files FlushShaderFileCache(); } // If the global shader map hasn't been created yet, create it. if(!GGlobalShaderMap[Platform]) { // GetGlobalShaderMap is called the first time during startup in the main thread. check(IsInGameThread()); FScopedSlowTask SlowTask(70); // verify that all shader source files are intact SlowTask.EnterProgressFrame(20); VerifyShaderSourceFiles(); GGlobalShaderMap[Platform] = new TShaderMap<FGlobalShaderType>(); bool bLoadedFromCacheFile = false; // Try to load the global shaders from a local cache file if it exists // This method is used exclusively with cooked content, since the DDC is not present if (FPlatformProperties::RequiresCookedData()) { SlowTask.EnterProgressFrame(50); TArray<uint8> GlobalShaderData; FString GlobalShaderCacheFilename = FPaths::GetRelativePathToRoot() / GetGlobalShaderCacheFilename(Platform); FPaths::MakeStandardFilename(GlobalShaderCacheFilename); bLoadedFromCacheFile = FFileHelper::LoadFileToArray(GlobalShaderData, *GlobalShaderCacheFilename, FILEREAD_Silent); if (!bLoadedFromCacheFile) { // Handle this gracefully and exit. FString SandboxPath = IFileManager::Get().ConvertToAbsolutePathForExternalAppForWrite(*GlobalShaderCacheFilename); // This can be too early to localize in some situations. const FText Message = FText::Format(NSLOCTEXT("Engine", "GlobalShaderCacheFileMissing", "The global shader cache file '{0}' is missing.\n\nYour application is built to load COOKED content. No COOKED content was found; This usually means you did not cook content for this build.\nIt also may indicate missing cooked data for a shader platform(e.g., OpenGL under Windows): Make sure your platform's packaging settings include this Targeted RHI.\n\nAlternatively build and run the UNCOOKED version instead."), FText::FromString( SandboxPath ) ); if (FPlatformProperties::SupportsWindowedMode()) { UE_LOG(LogMaterial, Error, TEXT("%s"), *Message.ToString()); FMessageDialog::Open(EAppMsgType::Ok, Message); FPlatformMisc::RequestExit(false); return NULL; } else { UE_LOG(LogMaterial, Fatal, TEXT("%s"), *Message.ToString()); } } FMemoryReader MemoryReader(GlobalShaderData); SerializeGlobalShaders(MemoryReader, GGlobalShaderMap[Platform]); } // Uncooked platform else { FGlobalShaderMapId ShaderMapId(Platform); TArray<uint8> CachedData; SlowTask.EnterProgressFrame(40); const FString DataKey = GetGlobalShaderMapKeyString(ShaderMapId, Platform); // Find the shader map in the derived data cache SlowTask.EnterProgressFrame(10); if (GetDerivedDataCacheRef().GetSynchronous(*DataKey, CachedData)) { FMemoryReader Ar(CachedData, true); // Deserialize from the cached data SerializeGlobalShaders(Ar, GGlobalShaderMap[Platform]); } } // If any shaders weren't loaded, compile them now. VerifyGlobalShaders(Platform, bLoadedFromCacheFile); extern int32 GCreateShadersOnLoad; if (GCreateShadersOnLoad && Platform == GMaxRHIShaderPlatform) { for (TMap<FShaderType*, TRefCountPtr<FShader> >::TConstIterator ShaderIt(GGlobalShaderMap[Platform]->GetShaders()); ShaderIt; ++ShaderIt) { FShader* Shader = ShaderIt.Value(); if (Shader) { Shader->BeginInitializeResources(); } } } } return GGlobalShaderMap[Platform]; } bool IsGlobalShaderMapComplete(const TCHAR* TypeNameSubstring) { for (int32 i = 0; i < SP_NumPlatforms; ++i) { EShaderPlatform Platform = (EShaderPlatform)i; TShaderMap<FGlobalShaderType>* GlobalShaderMap = GGlobalShaderMap[Platform]; if (GlobalShaderMap) { for (TLinkedList<FShaderType*>::TIterator ShaderTypeIt(FShaderType::GetTypeList()); ShaderTypeIt; ShaderTypeIt.Next()) { FGlobalShaderType* GlobalShaderType = ShaderTypeIt->GetGlobalShaderType(); if (GlobalShaderType && (TypeNameSubstring == nullptr || (FPlatformString::Strstr(GlobalShaderType->GetName(), TypeNameSubstring) != nullptr)) && GlobalShaderType->ShouldCache(Platform)) { if (!GlobalShaderMap->HasShader(GlobalShaderType)) { return false; } } } } } return true; } /** * Forces a recompile of the global shaders. */ void RecompileGlobalShaders() { if( !FPlatformProperties::RequiresCookedData() ) { // Flush pending accesses to the existing global shaders. FlushRenderingCommands(); UMaterialInterface::IterateOverActiveFeatureLevels([&](ERHIFeatureLevel::Type InFeatureLevel) { auto ShaderPlatform = GShaderPlatformForFeatureLevel[InFeatureLevel]; GetGlobalShaderMap(ShaderPlatform)->Empty(); VerifyGlobalShaders(ShaderPlatform, false); }); GShaderCompilingManager->ProcessAsyncResults(false, true); //invalidate global bound shader states so they will be created with the new shaders the next time they are set (in SetGlobalBoundShaderState) for(TLinkedList<FGlobalBoundShaderStateResource*>::TIterator It(FGlobalBoundShaderStateResource::GetGlobalBoundShaderStateList());It;It.Next()) { BeginUpdateResourceRHI(*It); } } } bool RecompileChangedShadersForPlatform( const FString& PlatformName ) { // figure out what shader platforms to recompile ITargetPlatformManagerModule* TPM = GetTargetPlatformManager(); ITargetPlatform* TargetPlatform = TPM->FindTargetPlatform(PlatformName); if (TargetPlatform == NULL) { UE_LOG(LogShaders, Display, TEXT("Failed to find target platform module for %s"), *PlatformName); return false; } TArray<FName> DesiredShaderFormats; TargetPlatform->GetAllTargetedShaderFormats(DesiredShaderFormats); // figure out which shaders are out of date TArray<FShaderType*> OutdatedShaderTypes; TArray<const FVertexFactoryType*> OutdatedFactoryTypes; // Pick up new changes to shader files FlushShaderFileCache(); FShaderType::GetOutdatedTypes(OutdatedShaderTypes, OutdatedFactoryTypes); UE_LOG(LogShaders, Display, TEXT("We found %d out of date shader types, and %d out of date VF types!"), OutdatedShaderTypes.Num(), OutdatedFactoryTypes.Num()); for (int32 FormatIndex = 0; FormatIndex < DesiredShaderFormats.Num(); FormatIndex++) { // get the shader platform enum const EShaderPlatform ShaderPlatform = ShaderFormatToLegacyShaderPlatform(DesiredShaderFormats[FormatIndex]); // Only compile for the desired platform if requested // Kick off global shader recompiles BeginRecompileGlobalShaders(OutdatedShaderTypes, ShaderPlatform); // Block on global shaders FinishRecompileGlobalShaders(); #if WITH_EDITOR // we only want to actually compile mesh shaders if we have out of date ones if (OutdatedShaderTypes.Num() || OutdatedFactoryTypes.Num()) { for (TObjectIterator<UMaterialInterface> It; It; ++It) { (*It)->ClearCachedCookedPlatformData(TargetPlatform); } } #endif } if (OutdatedFactoryTypes.Num() || OutdatedShaderTypes.Num()) { return true; } return false; } void RecompileShadersForRemote( const FString& PlatformName, EShaderPlatform ShaderPlatformToCompile, const FString& OutputDirectory, const TArray<FString>& MaterialsToLoad, const TArray<uint8>& SerializedShaderResources, TArray<uint8>* MeshMaterialMaps, TArray<FString>* ModifiedFiles, bool bCompileChangedShaders ) { // figure out what shader platforms to recompile ITargetPlatformManagerModule* TPM = GetTargetPlatformManager(); ITargetPlatform* TargetPlatform = TPM->FindTargetPlatform(PlatformName); if (TargetPlatform == NULL) { UE_LOG(LogShaders, Display, TEXT("Failed to find target platform module for %s"), *PlatformName); return; } TArray<FName> DesiredShaderFormats; TargetPlatform->GetAllTargetedShaderFormats(DesiredShaderFormats); UE_LOG(LogShaders, Display, TEXT("Loading %d materials..."), MaterialsToLoad.Num()); // make sure all materials the client has loaded will be processed TArray<UMaterialInterface*> MaterialsToCompile; for (int32 Index = 0; Index < MaterialsToLoad.Num(); Index++) { UE_LOG(LogShaders, Display, TEXT(" --> %s"), *MaterialsToLoad[Index]); MaterialsToCompile.Add(LoadObject<UMaterialInterface>(NULL, *MaterialsToLoad[Index])); } UE_LOG(LogShaders, Display, TEXT(" Done!")) // figure out which shaders are out of date TArray<FShaderType*> OutdatedShaderTypes; TArray<const FVertexFactoryType*> OutdatedFactoryTypes; // Pick up new changes to shader files FlushShaderFileCache(); if( bCompileChangedShaders ) { FShaderType::GetOutdatedTypes( OutdatedShaderTypes, OutdatedFactoryTypes ); UE_LOG( LogShaders, Display, TEXT( "We found %d out of date shader types, and %d out of date VF types!" ), OutdatedShaderTypes.Num(), OutdatedFactoryTypes.Num() ); } { for (int32 FormatIndex = 0; FormatIndex < DesiredShaderFormats.Num(); FormatIndex++) { // get the shader platform enum const EShaderPlatform ShaderPlatform = ShaderFormatToLegacyShaderPlatform(DesiredShaderFormats[FormatIndex]); // Only compile for the desired platform if requested if (ShaderPlatform == ShaderPlatformToCompile || ShaderPlatformToCompile == SP_NumPlatforms) { if( bCompileChangedShaders ) { // Kick off global shader recompiles BeginRecompileGlobalShaders( OutdatedShaderTypes, ShaderPlatform ); // Block on global shaders FinishRecompileGlobalShaders(); } // we only want to actually compile mesh shaders if a client directly requested it, and there's actually some work to do if (MeshMaterialMaps != NULL && (OutdatedShaderTypes.Num() || OutdatedFactoryTypes.Num() || bCompileChangedShaders == false)) { TMap<FString, TArray<TRefCountPtr<FMaterialShaderMap> > > CompiledShaderMaps; UMaterial::CompileMaterialsForRemoteRecompile(MaterialsToCompile, ShaderPlatform, CompiledShaderMaps); // write the shader compilation info to memory, converting fnames to strings FMemoryWriter MemWriter(*MeshMaterialMaps, true); FNameAsStringProxyArchive Ar(MemWriter); // pull the serialized resource ids into an array of resources TArray<FShaderResourceId> ClientResourceIds; FMemoryReader MemReader(SerializedShaderResources, true); MemReader << ClientResourceIds; // save out the shader map to the byte array FMaterialShaderMap::SaveForRemoteRecompile(Ar, CompiledShaderMaps, ClientResourceIds); } // save it out so the client can get it (and it's up to date next time) FString GlobalShaderFilename = SaveGlobalShaderFile(ShaderPlatform, OutputDirectory); // add this to the list of files to tell the other end about if (ModifiedFiles) { // need to put it in non-sandbox terms FString SandboxPath(GlobalShaderFilename); check(SandboxPath.StartsWith(OutputDirectory)); SandboxPath.ReplaceInline(*OutputDirectory, TEXT("../../../")); FPaths::NormalizeFilename(SandboxPath); ModifiedFiles->Add(SandboxPath); } } } } } void BeginRecompileGlobalShaders(const TArray<FShaderType*>& OutdatedShaderTypes, EShaderPlatform ShaderPlatform) { if( !FPlatformProperties::RequiresCookedData() ) { // Flush pending accesses to the existing global shaders. FlushRenderingCommands(); TShaderMap<FGlobalShaderType>* GlobalShaderMap = GetGlobalShaderMap(ShaderPlatform); for (int32 TypeIndex = 0; TypeIndex < OutdatedShaderTypes.Num(); TypeIndex++) { FGlobalShaderType* CurrentGlobalShaderType = OutdatedShaderTypes[TypeIndex]->GetGlobalShaderType(); if (CurrentGlobalShaderType) { UE_LOG(LogShaders, Log, TEXT("Flushing Global Shader %s"), CurrentGlobalShaderType->GetName()); GlobalShaderMap->RemoveShaderType(CurrentGlobalShaderType); //invalidate global bound shader states so they will be created with the new shaders the next time they are set (in SetGlobalBoundShaderState) for(TLinkedList<FGlobalBoundShaderStateResource*>::TIterator It(FGlobalBoundShaderStateResource::GetGlobalBoundShaderStateList());It;It.Next()) { BeginUpdateResourceRHI(*It); } } } VerifyGlobalShaders(ShaderPlatform, false); } } void FinishRecompileGlobalShaders() { // Block until global shaders have been compiled and processed GShaderCompilingManager->ProcessAsyncResults(false, true); } void ProcessCompiledGlobalShaders(const TArray<FShaderCompileJob*>& CompilationResults) { UE_LOG(LogShaders, Warning, TEXT("Compiled %u global shaders"), CompilationResults.Num()); TArray<EShaderPlatform> ShaderPlatformsProcessed; for (int32 ResultIndex = 0; ResultIndex < CompilationResults.Num(); ResultIndex++) { const FShaderCompileJob& CurrentJob = *CompilationResults[ResultIndex]; FGlobalShaderType* GlobalShaderType = CurrentJob.ShaderType->GetGlobalShaderType(); check(GlobalShaderType); FShader* Shader = GlobalShaderType->FinishCompileShader(CurrentJob); if (Shader) { // Add the new global shader instance to the global shader map. EShaderPlatform Platform = (EShaderPlatform)CurrentJob.Input.Target.Platform; GGlobalShaderMap[Platform]->AddShader(GlobalShaderType,Shader); ShaderPlatformsProcessed.AddUnique(Platform); } else { UE_LOG(LogShaders, Fatal,TEXT("Failed to compile global shader %s. Enable 'r.ShaderDevelopmentMode' in ConsoleVariables.ini for retries."), GlobalShaderType->GetName()); } } for (int32 PlatformIndex = 0; PlatformIndex < ShaderPlatformsProcessed.Num(); PlatformIndex++) { // Save the global shader map for any platforms that were recompiled SaveGlobalShaderMapToDerivedDataCache(ShaderPlatformsProcessed[PlatformIndex]); } }
35.638211
546
0.761758
[ "mesh" ]
9fcda0fc4c953f6aa03bdf4640846bbd32b88425
1,652
cpp
C++
Python/Interfacing_C_C++_Fortran/Pybind11/Stats/src/bindings/statistics_bind.cpp
Gjacquenot/training-material
16b29962bf5683f97a1072d961dd9f31e7468b8d
[ "CC-BY-4.0" ]
115
2015-03-23T13:34:42.000Z
2022-03-21T00:27:21.000Z
Python/Interfacing_C_C++_Fortran/Pybind11/Stats/src/bindings/statistics_bind.cpp
Gjacquenot/training-material
16b29962bf5683f97a1072d961dd9f31e7468b8d
[ "CC-BY-4.0" ]
56
2015-02-25T15:04:26.000Z
2022-01-03T07:42:48.000Z
Python/Interfacing_C_C++_Fortran/Pybind11/Stats/src/bindings/statistics_bind.cpp
Gjacquenot/training-material
16b29962bf5683f97a1072d961dd9f31e7468b8d
[ "CC-BY-4.0" ]
59
2015-11-26T11:44:51.000Z
2022-03-21T00:27:22.000Z
#include <pybind11/pybind11.h> #include <pybind11/numpy.h> #include <statistics.h> namespace py = pybind11; Statistics compute_stats(py::array_t<double> data) { Statistics stats; auto data_info = data.request(); ssize_t n = 1; for (const auto& size: data_info.shape) n *= size; for (ssize_t i = 0; i < n; ++i) stats.add(((double*) data_info.ptr)[i]); return stats; } PYBIND11_MODULE(stats, m) { m.doc() = "module defining Statistics class"; m.def("compute_stats", &compute_stats, "return statistics over numpy array"); py::class_<Statistics>(m, "Statistics") .def(py::init<>(), "initialize an anonymous Statistics object") .def(py::init<const std::string&>(), "initialize a named Statistics object") .def("name", &Statistics::name, "return the name of the Statistics object") .def("n", &Statistics::n, "return the number of data items") .def("add", (void (Statistics::*)(const double)) &Statistics::add, "add a floating point value to the statistics") .def("add", (void (Statistics::*)(const std::string&)) &Statistics::add, "add a string representation of a value to the statistics") .def("sum", &Statistics::sum, "return the sum of the values") .def("min", &Statistics::min, "return the minimum value") .def("max", &Statistics::max, "return the maximum value") .def("mean", &Statistics::mean, "return the mean value") .def("stddev", &Statistics::stddev, "return the standard deviation") .def("nr_missing", &Statistics::nr_missing, "return the number of missing values"); }
44.648649
91
0.635593
[ "object", "shape" ]
9fce98318117db48d56451cb939866c7891fe694
2,351
cpp
C++
uhk/acm5468.cpp
Hyyyyyyyyyy/acm
d7101755b2c2868d51bb056f094e024d0333b56f
[ "MIT" ]
null
null
null
uhk/acm5468.cpp
Hyyyyyyyyyy/acm
d7101755b2c2868d51bb056f094e024d0333b56f
[ "MIT" ]
null
null
null
uhk/acm5468.cpp
Hyyyyyyyyyy/acm
d7101755b2c2868d51bb056f094e024d0333b56f
[ "MIT" ]
null
null
null
#include <cstdio> #include <cstring> #include <algorithm> #include <cmath> #include <vector> using namespace std; typedef long long ll; const int INF = 2147483640; const int maxn = 100000; bool check[maxn + 10]; int prime[maxn + 10]; int mu[maxn + 10]; vector<int> factors[maxn + 10]; vector<int> G[maxn + 10]; void Moblus() { memset(check, false, sizeof(check)); mu[1] = 1; int tot = 0; for(int i = 2; i <= maxn; i++) { if(!check[i]) { prime[tot++] = i; mu[i] = -1; } for(int j = 0; j < tot; j++) { if(i * prime[j] > maxn) break; check[i * prime[j]] = true; if(i % prime[j] == 0) { mu[i * prime[j]] = 0; break; } else { mu[i * prime[j]] = -mu[i]; } } } for(int i = 2; i <= maxn; i++) if(mu[i]) { for(int j = i; j <= maxn; j += i) { factors[j].push_back(i); } } } //???? < tot int val[maxn+10]; int cnt[maxn], sz[maxn], ans[maxn]; void dfs(int u, int fa) { sz[u] = 1; vector<int>pre; for(int i = 0; i < factors[val[u]].size(); i++) { int d = factors[val[u]][i]; pre.push_back(cnt[d]); cnt[d]++; } for(int i = 0; i < G[u].size(); i++) { int v = G[u][i]; if(v == fa) continue; dfs(v, u); sz[u] += sz[v]; } ans[u] = sz[u]; for(int i = 0; i < factors[val[u]].size(); i++) { int d = factors[val[u]][i]; int c = cnt[d] - pre[i]; if(c) ans[u] += mu[d] * c; } } int main() { int i, j, k, u, n, m, cas = 1, a, b; Moblus(); while(scanf("%d", &n) != EOF) { for(i = 0; i <= n; i++) G[i].clear(); for(m = 1; m <= n-1; m++) { scanf("%d %d", &a, &b); G[a].push_back(b); G[b].push_back(a); } for(i = 1; i <= n; i++) { scanf("%d", &val[i]); } memset(cnt, 0, sizeof(cnt)); dfs(1, 0); printf("Case #%d:", cas++); for(i = 1; i <= n; i++) printf(" %d", ans[i]); printf("\n"); } return 0; }
21.768519
51
0.374309
[ "vector" ]
9fd0d0f80353d4b0e7cc4d37f05c2140f01df776
2,827
cpp
C++
src/xtd.core/src/xtd/io/drive_info.cpp
BaderEddineOuaich/xtd
6f28634c7949a541d183879d2de18d824ec3c8b1
[ "MIT" ]
1
2022-02-25T16:53:06.000Z
2022-02-25T16:53:06.000Z
src/xtd.core/src/xtd/io/drive_info.cpp
leanid/xtd
2e1ea6537218788ca08901faf8915d4100990b53
[ "MIT" ]
null
null
null
src/xtd.core/src/xtd/io/drive_info.cpp
leanid/xtd
2e1ea6537218788ca08901faf8915d4100990b53
[ "MIT" ]
null
null
null
#include "../../../include/xtd/io/drive_info.h" #include "../../../include/xtd/io/io_exception.h" #include "../../../include/xtd/argument_exception.h" #define __XTD_CORE_NATIVE_LIBRARY__ #include <xtd/native/drive.h> #undef __XTD_CORE_NATIVE_LIBRARY__ using namespace std; using namespace xtd; using namespace io; const drive_info drive_info::empty; drive_info::drive_info(const ustring& drive_name) : drive_name_(drive_name) { if (drive_name.empty()) throw argument_exception(csf_); auto drives = native::drive::get_drives(); if (find(drives.begin(), drives.end(), drive_name) == drives.end()) throw argument_exception(csf_); } size_t drive_info::available_free_space() const { size_t free_bytes = 0, total_number_of_bytes = 0, total_number_of_free_bytes = 0; if (!native::drive::get_available_free_space(drive_name_, free_bytes, total_number_of_bytes, total_number_of_free_bytes)) throw io_exception(csf_); return free_bytes; } ustring drive_info::drive_format() const { string volume_name, file_system_name; if (!native::drive::get_volume_information(drive_name_, volume_name, file_system_name)) throw io_exception(csf_); return file_system_name; } drive_type drive_info::drive_type() const { int32_t drive_type = native::drive::get_drive_type(drive_name_); return static_cast<xtd::io::drive_type>(drive_type); } bool drive_info::is_ready() const noexcept { string volume_name, file_system_name; return native::drive::get_volume_information(drive_name_, volume_name, file_system_name); } ustring drive_info::name() const noexcept { return drive_name_; } directory_info drive_info::root_directory() const noexcept { return directory_info(drive_name_); } size_t drive_info::total_free_space() const { size_t free_bytes = 0, total_number_of_bytes = 0, total_number_of_free_bytes = 0; if (!native::drive::get_available_free_space(drive_name_, free_bytes, total_number_of_bytes, total_number_of_free_bytes)) throw io_exception(csf_); return total_number_of_free_bytes; } size_t drive_info::total_size() const { size_t free_bytes = 0, total_number_of_bytes = 0, total_number_of_free_bytes = 0; if (!native::drive::get_available_free_space(drive_name_, free_bytes, total_number_of_bytes, total_number_of_free_bytes)) throw io_exception(csf_); return total_number_of_bytes; } ustring drive_info::volume_label() const { string volume_name, file_system_name; if (!native::drive::get_volume_information(drive_name_, volume_name, file_system_name)) throw io_exception(csf_); return volume_name; } vector<drive_info> drive_info::get_drives() noexcept { vector<drive_info> drives; for (auto drive : native::drive::get_drives()) drives.emplace_back(drive_info(drive)); return drives; } xtd::ustring drive_info::to_string() const noexcept { return drive_name_; }
36.24359
149
0.780686
[ "vector" ]
9fd834060d6ad27a8c1e999b61b953f688962294
417
cpp
C++
src/PauseState.cpp
mikaelmello/story-based-rpg
bc73c24ad0e41512c3e980ca3aad0fc5738af2f2
[ "Zlib" ]
null
null
null
src/PauseState.cpp
mikaelmello/story-based-rpg
bc73c24ad0e41512c3e980ca3aad0fc5738af2f2
[ "Zlib" ]
null
null
null
src/PauseState.cpp
mikaelmello/story-based-rpg
bc73c24ad0e41512c3e980ca3aad0fc5738af2f2
[ "Zlib" ]
null
null
null
#include "PauseState.hpp" PauseState::PauseState(){} PauseState::~PauseState() {} void PauseState::Update(float dt) { if (quitRequested || popRequested) { return; } UpdateArray(dt); } void PauseState::Start() { LoadAssets(); StartArray(); started = true; } void PauseState::Pause() {} void PauseState::Resume() {} void PauseState::LoadAssets() {} void PauseState::Render() { RenderArray(); }
14.892857
44
0.664269
[ "render" ]
9fde253c96a9c710790af49f3e2914fa01923788
640
cpp
C++
K Closest Points to Origin.cpp
Subhash3/Algorithms-For-Software-Developers
2e0ac4f51d379a2b10a40fca7fa82a8501d3db94
[ "BSD-2-Clause" ]
2
2021-10-01T04:20:04.000Z
2021-10-01T04:20:06.000Z
K Closest Points to Origin.cpp
Subhash3/Algorithms-For-Software-Developers
2e0ac4f51d379a2b10a40fca7fa82a8501d3db94
[ "BSD-2-Clause" ]
1
2021-10-01T18:00:09.000Z
2021-10-01T18:00:09.000Z
K Closest Points to Origin.cpp
Subhash3/Algorithms-For-Software-Developers
2e0ac4f51d379a2b10a40fca7fa82a8501d3db94
[ "BSD-2-Clause" ]
8
2021-10-01T04:20:38.000Z
2022-03-19T17:05:05.000Z
class Solution { public: vector<vector<int>> kClosest(vector<vector<int>>& points, int k) { vector<vector<int>> ans; if(points.size()==0)return ans; priority_queue<pair<int,pair<int,int>>> pq; for(int i=0;i<points.size();i++) { int dist=points[i][0]*points[i][0]+points[i][1]*points[i][1]; pq.push({dist,{points[i][0],points[i][1]}}); if(pq.size()>k) pq.pop(); } while(!pq.empty()) { ans.push_back({pq.top().second.first,pq.top().second.second}); pq.pop(); } return ans; } };
29.090909
74
0.484375
[ "vector" ]
9fe38fadd25fa2cd6e6da8709be098ed3195fd5b
889
cpp
C++
coding-problems/questions/Length Summation/Length Summation.cpp
Avash027/software-engineering-interview-prep
e50ff19b0d3846e679d7c0af74ce2956999524cb
[ "MIT" ]
null
null
null
coding-problems/questions/Length Summation/Length Summation.cpp
Avash027/software-engineering-interview-prep
e50ff19b0d3846e679d7c0af74ce2956999524cb
[ "MIT" ]
null
null
null
coding-problems/questions/Length Summation/Length Summation.cpp
Avash027/software-engineering-interview-prep
e50ff19b0d3846e679d7c0af74ce2956999524cb
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; long long sum_of_good_segments(vector<long long> a , long long k , int n) { int left_boundary = 0 , right_boundary = 0; long long sum_of_segment = 0LL , sum_of_length_of_segments = 0; while (right_boundary < n) { sum_of_segment += a[right_boundary++]; while (sum_of_segment > k) {// It is not a good segment so we try to reduce its size sum_of_segment -= a[left_boundary]; left_boundary++; } long long lenght_of_segment = right_boundary - left_boundary; sum_of_length_of_segments += (lenght_of_segment * (lenght_of_segment + 1)) / 2; } return sum_of_length_of_segments; } int main() { int n; long long k; cin >> n >> k; if (n == 0 || k == 0) { cout << 0 << "\n"; return 0; } vector<long long> a(n); for (auto&e : a) cin >> e; cout << sum_of_good_segments(a, k, n) << "\n"; return 0; }
16.773585
86
0.646794
[ "vector" ]
9fe6aec24a0cf90222895b6423da8256e33957cd
11,411
cpp
C++
moses/moses/SearchCubePruning.cpp
anshsarkar/TailBench
25845756aee9a892229c25b681051591c94daafd
[ "MIT" ]
3
2018-01-25T00:51:56.000Z
2022-01-07T15:09:38.000Z
moses/moses/SearchCubePruning.cpp
anshsarkar/TailBench
25845756aee9a892229c25b681051591c94daafd
[ "MIT" ]
1
2021-11-25T18:08:22.000Z
2021-11-25T18:08:22.000Z
moses/moses/SearchCubePruning.cpp
anshsarkar/TailBench
25845756aee9a892229c25b681051591c94daafd
[ "MIT" ]
3
2018-06-08T08:36:27.000Z
2021-12-26T20:36:16.000Z
#include "Manager.h" #include "Util.h" #include "SearchCubePruning.h" #include "StaticData.h" #include "InputType.h" #include "TranslationOptionCollection.h" using namespace std; namespace Moses { class BitmapContainerOrderer { public: bool operator()(const BitmapContainer* A, const BitmapContainer* B) const { if (B->Empty()) { if (A->Empty()) { return A < B; } return false; } if (A->Empty()) { return true; } // Compare the top hypothesis of each bitmap container using the TotalScore, which includes future cost const float scoreA = A->Top()->GetHypothesis()->GetTotalScore(); const float scoreB = B->Top()->GetHypothesis()->GetTotalScore(); if (scoreA < scoreB) { return true; } else if (scoreA > scoreB) { return false; } else { return A < B; } } }; SearchCubePruning::SearchCubePruning(Manager& manager, const InputType &source, const TranslationOptionCollection &transOptColl) :Search(manager) ,m_source(source) ,m_hypoStackColl(source.GetSize() + 1) ,m_initialTargetPhrase(source.m_initialTargetPhrase) ,m_start(clock()) ,m_transOptColl(transOptColl) { const StaticData &staticData = StaticData::Instance(); /* constraint search not implemented in cube pruning long sentenceID = source.GetTranslationId(); m_constraint = staticData.GetConstrainingPhrase(sentenceID); */ std::vector < HypothesisStackCubePruning >::iterator iterStack; for (size_t ind = 0 ; ind < m_hypoStackColl.size() ; ++ind) { HypothesisStackCubePruning *sourceHypoColl = new HypothesisStackCubePruning(m_manager); sourceHypoColl->SetMaxHypoStackSize(staticData.GetMaxHypoStackSize()); sourceHypoColl->SetBeamWidth(staticData.GetBeamWidth()); m_hypoStackColl[ind] = sourceHypoColl; } } SearchCubePruning::~SearchCubePruning() { RemoveAllInColl(m_hypoStackColl); } /** * Main decoder loop that translates a sentence by expanding * hypotheses stack by stack, until the end of the sentence. */ void SearchCubePruning::ProcessSentence() { const StaticData &staticData = StaticData::Instance(); // initial seed hypothesis: nothing translated, no words produced Hypothesis *hypo = Hypothesis::Create(m_manager,m_source, m_initialTargetPhrase); HypothesisStackCubePruning &firstStack = *static_cast<HypothesisStackCubePruning*>(m_hypoStackColl.front()); firstStack.AddInitial(hypo); // Call this here because the loop below starts at the second stack. firstStack.CleanupArcList(); CreateForwardTodos(firstStack); const size_t PopLimit = StaticData::Instance().GetCubePruningPopLimit(); VERBOSE(3,"Cube Pruning pop limit is " << PopLimit << std::endl) const size_t Diversity = StaticData::Instance().GetCubePruningDiversity(); VERBOSE(3,"Cube Pruning diversity is " << Diversity << std::endl) // go through each stack size_t stackNo = 1; std::vector < HypothesisStack* >::iterator iterStack; for (iterStack = ++m_hypoStackColl.begin() ; iterStack != m_hypoStackColl.end() ; ++iterStack) { // check if decoding ran out of time double _elapsed_time = GetUserTime(); if (_elapsed_time > staticData.GetTimeoutThreshold()) { VERBOSE(1,"Decoding is out of time (" << _elapsed_time << "," << staticData.GetTimeoutThreshold() << ")" << std::endl); return; } HypothesisStackCubePruning &sourceHypoColl = *static_cast<HypothesisStackCubePruning*>(*iterStack); // priority queue which has a single entry for each bitmap container, sorted by score of top hyp std::priority_queue< BitmapContainer*, std::vector< BitmapContainer* >, BitmapContainerOrderer> BCQueue; _BMType::const_iterator bmIter; const _BMType &accessor = sourceHypoColl.GetBitmapAccessor(); for(bmIter = accessor.begin(); bmIter != accessor.end(); ++bmIter) { bmIter->second->InitializeEdges(); BCQueue.push(bmIter->second); // old algorithm // bmIter->second->EnsureMinStackHyps(PopLimit); } // main search loop, pop k best hyps for (size_t numpops = 1; numpops <= PopLimit && !BCQueue.empty(); numpops++) { BitmapContainer *bc = BCQueue.top(); BCQueue.pop(); bc->ProcessBestHypothesis(); if (!bc->Empty()) BCQueue.push(bc); } // ensure diversity, a minimum number of inserted hyps for each bitmap container; // NOTE: diversity doesn't ensure they aren't pruned at some later point if (Diversity > 0) { for(bmIter = accessor.begin(); bmIter != accessor.end(); ++bmIter) { bmIter->second->EnsureMinStackHyps(Diversity); } } // the stack is pruned before processing (lazy pruning): VERBOSE(3,"processing hypothesis from next stack"); // VERBOSE("processing next stack at "); sourceHypoColl.PruneToSize(staticData.GetMaxHypoStackSize()); VERBOSE(3,std::endl); sourceHypoColl.CleanupArcList(); CreateForwardTodos(sourceHypoColl); stackNo++; } //PrintBitmapContainerGraph(); // some more logging IFVERBOSE(2) { m_manager.GetSentenceStats().SetTimeTotal( clock()-m_start ); } VERBOSE(2, m_manager.GetSentenceStats()); } void SearchCubePruning::CreateForwardTodos(HypothesisStackCubePruning &stack) { const _BMType &bitmapAccessor = stack.GetBitmapAccessor(); _BMType::const_iterator iterAccessor; size_t size = m_source.GetSize(); stack.AddHypothesesToBitmapContainers(); for (iterAccessor = bitmapAccessor.begin() ; iterAccessor != bitmapAccessor.end() ; ++iterAccessor) { const WordsBitmap &bitmap = iterAccessor->first; BitmapContainer &bitmapContainer = *iterAccessor->second; if (bitmapContainer.GetHypothesesSize() == 0) { // no hypothese to expand. don't bother doing it continue; } // Sort the hypotheses inside the Bitmap Container as they are being used by now. bitmapContainer.SortHypotheses(); // check bitamp and range doesn't overlap size_t startPos, endPos; for (startPos = 0 ; startPos < size ; startPos++) { if (bitmap.GetValue(startPos)) continue; // not yet covered WordsRange applyRange(startPos, startPos); if (CheckDistortion(bitmap, applyRange)) { // apply range CreateForwardTodos(bitmap, applyRange, bitmapContainer); } size_t maxSize = size - startPos; size_t maxSizePhrase = StaticData::Instance().GetMaxPhraseLength(); maxSize = std::min(maxSize, maxSizePhrase); for (endPos = startPos+1; endPos < startPos + maxSize; endPos++) { if (bitmap.GetValue(endPos)) break; WordsRange applyRange(startPos, endPos); if (CheckDistortion(bitmap, applyRange)) { // apply range CreateForwardTodos(bitmap, applyRange, bitmapContainer); } } } } } void SearchCubePruning::CreateForwardTodos(const WordsBitmap &bitmap, const WordsRange &range, BitmapContainer &bitmapContainer) { WordsBitmap newBitmap = bitmap; newBitmap.SetValue(range.GetStartPos(), range.GetEndPos(), true); size_t numCovered = newBitmap.GetNumWordsCovered(); const TranslationOptionList &transOptList = m_transOptColl.GetTranslationOptionList(range); const SquareMatrix &futureScore = m_transOptColl.GetFutureScore(); if (transOptList.size() > 0) { HypothesisStackCubePruning &newStack = *static_cast<HypothesisStackCubePruning*>(m_hypoStackColl[numCovered]); newStack.SetBitmapAccessor(newBitmap, newStack, range, bitmapContainer, futureScore, transOptList); } } bool SearchCubePruning::CheckDistortion(const WordsBitmap &hypoBitmap, const WordsRange &range) const { // since we check for reordering limits, its good to have that limit handy int maxDistortion = StaticData::Instance().GetMaxDistortion(); // if there are reordering limits, make sure it is not violated // the coverage bitmap is handy here (and the position of the first gap) const size_t hypoFirstGapPos = hypoBitmap.GetFirstGapPos() , startPos = range.GetStartPos() , endPos = range.GetEndPos(); // if reordering constraints are used (--monotone-at-punctuation or xml), check if passes all if (! m_source.GetReorderingConstraint().Check( hypoBitmap, startPos, endPos ) ) { return false; } // no limit of reordering: no problem if (maxDistortion < 0) { return true; } bool leftMostEdge = (hypoFirstGapPos == startPos); // any length extension is okay if starting at left-most edge if (leftMostEdge) { return true; } // starting somewhere other than left-most edge, use caution // the basic idea is this: we would like to translate a phrase starting // from a position further right than the left-most open gap. The // distortion penalty for the following phrase will be computed relative // to the ending position of the current extension, so we ask now what // its maximum value will be (which will always be the value of the // hypothesis starting at the left-most edge). If this vlaue is than // the distortion limit, we don't allow this extension to be made. WordsRange bestNextExtension(hypoFirstGapPos, hypoFirstGapPos); int required_distortion = m_source.ComputeDistortionDistance(range, bestNextExtension); if (required_distortion > maxDistortion) { return false; } return true; } /** * Find best hypothesis on the last stack. * This is the end point of the best translation, which can be traced back from here */ const Hypothesis *SearchCubePruning::GetBestHypothesis() const { // const HypothesisStackCubePruning &hypoColl = m_hypoStackColl.back(); const HypothesisStack &hypoColl = *m_hypoStackColl.back(); return hypoColl.GetBestHypothesis(); } /** * Logging of hypothesis stack sizes */ void SearchCubePruning::OutputHypoStackSize() { std::vector < HypothesisStack* >::const_iterator iterStack = m_hypoStackColl.begin(); TRACE_ERR( "Stack sizes: " << (int)(*iterStack)->size()); for (++iterStack; iterStack != m_hypoStackColl.end() ; ++iterStack) { TRACE_ERR( ", " << (int)(*iterStack)->size()); } TRACE_ERR( endl); } void SearchCubePruning::PrintBitmapContainerGraph() { HypothesisStackCubePruning &lastStack = *static_cast<HypothesisStackCubePruning*>(m_hypoStackColl.back()); const _BMType &bitmapAccessor = lastStack.GetBitmapAccessor(); _BMType::const_iterator iterAccessor; for (iterAccessor = bitmapAccessor.begin(); iterAccessor != bitmapAccessor.end(); ++iterAccessor) { cerr << iterAccessor->first << endl; //BitmapContainer &container = *iterAccessor->second; } } /** * Logging of hypothesis stack contents * \param stack number of stack to be reported, report all stacks if 0 */ void SearchCubePruning::OutputHypoStack(int stack) { if (stack >= 0) { TRACE_ERR( "Stack " << stack << ": " << endl << m_hypoStackColl[stack] << endl); } else { // all stacks int i = 0; vector < HypothesisStack* >::iterator iterStack; for (iterStack = m_hypoStackColl.begin() ; iterStack != m_hypoStackColl.end() ; ++iterStack) { HypothesisStackCubePruning &hypoColl = *static_cast<HypothesisStackCubePruning*>(*iterStack); TRACE_ERR( "Stack " << i++ << ": " << endl << hypoColl << endl); } } } const std::vector < HypothesisStack* >& SearchCubePruning::GetHypothesisStacks() const { return m_hypoStackColl; } }
34.578788
128
0.703882
[ "vector" ]
9fe97b7b0016431596ca1de2476850a82ca1c881
2,621
cpp
C++
src/uarc_colld/src/SendScheduleSubsystem.cpp
timercrack/uarc
c9a840c9c4cc2c89dc4714781c9be67be59f8ac0
[ "Apache-2.0" ]
1
2016-09-04T23:53:45.000Z
2016-09-04T23:53:45.000Z
src/uarc_colld/src/SendScheduleSubsystem.cpp
timercrack/uarc
c9a840c9c4cc2c89dc4714781c9be67be59f8ac0
[ "Apache-2.0" ]
null
null
null
src/uarc_colld/src/SendScheduleSubsystem.cpp
timercrack/uarc
c9a840c9c4cc2c89dc4714781c9be67be59f8ac0
[ "Apache-2.0" ]
3
2016-02-22T07:57:46.000Z
2021-09-06T02:49:20.000Z
/* * SendScheduleSubsystem.cpp * * Created on: 2015-5-23 * Author: root */ #include "SendScheduleSubsystem.h" SendScheduleSubsystem::SendScheduleSubsystem(): _stopped(true), _thread(){ // TODO Auto-generated constructor stub } SendScheduleSubsystem::~SendScheduleSubsystem() { // TODO Auto-generated destructor stub } void SendScheduleSubsystem::initialize(Poco::Util::Application & self) { // TODO 初始化rtdbms对象 std::string rtdbms_ip = self.config().getString("RedisDB.Base.IPAddr", "127.0.0.1"); int rtdbms_port = self.config().getInt("RedisDB.Base.Port", 6379); _rtdbms = new CRtDbMs(rtdbms_ip,rtdbms_port); } void SendScheduleSubsystem::uninitialize() { delete _rtdbms; _rtdbms = NULL; } void SendScheduleSubsystem::Start() { poco_assert (_stopped); _stopped = false; _thread.start(*this); UARCCollServer::GetLogger().information("启动下发配比计划子系统[%s]!", std::string(name())); } const char *SendScheduleSubsystem::name() const { return "SendScheduleSubsystem"; } void SendScheduleSubsystem::run() { // TODO 注册回调,监视内存数据库是否有控制命令下发 bool bRegistCallback = false; bRegistCallback = _rtdbms->setDevScheduleCallback(ScheduleCmdTaskRun); //配比计划回调 if (bRegistCallback) { UARCCollServer::GetLogger().information("注册配比计划下发回调成功!"); } else { UARCCollServer::GetLogger().error("注册配比计划下发回调失败!"); } // TODO 阻塞等待 _rtdbms->start(); } void SendScheduleSubsystem::Stop() { if (!_stopped) { _rtdbms->stop(); _stopped = true; _thread.join(); } UARCCollServer::GetLogger().information("停止配比计划下发子系统[%s]!", std::string(name())); } bool ScheduleCmdTaskRun(const ScheduleInfoData& scheduleTask) { // TODO 将控制命令下发至采集终端处理 bool bSend; DataItem dataItem; std::vector<DataItem> dataItems; dataItem.itemId = scheduleTask.itemId; dataItem.termId = scheduleTask.termId; dataItem.value = scheduleTask.scheduleVal; dataItem.time = scheduleTask.scheduleTime; // TODO 填充数据添加到下发任务集合中 dataItems.push_back(dataItem); bSend = send(scheduleTask.deviceId,SEND_SCHEDULECMD_TYPE,dataItems); if(bSend) { UARCCollServer::GetLogger().information("下发配比计划(termId:%d itemId:%d scheduleVal:%f scheduleTime:%d)至终端设备(deviceId:%d)成功!", scheduleTask.termId,scheduleTask.itemId,scheduleTask.scheduleVal,scheduleTask.scheduleTime,scheduleTask.deviceId); return true; } else { UARCCollServer::GetLogger().information("下发配比计划(termId:%d itemId:%d scheduleVal:%f scheduleTime:%d)至终端设备(deviceId:%d)失败!", scheduleTask.termId,scheduleTask.itemId,scheduleTask.scheduleVal,scheduleTask.scheduleTime,scheduleTask.deviceId); return false; } return true; }
24.045872
124
0.737123
[ "vector" ]
9feaf446e0088d1bcb129e8c2a05492e10b62a61
2,904
hpp
C++
Testbed/Tests/MotorJoint.hpp
minium2/Box2D
620af0b776a4773736233f0eb3cfdbb2bd84cf26
[ "Zlib" ]
23
2015-01-17T00:20:37.000Z
2020-05-24T07:45:43.000Z
Testbed/Tests/MotorJoint.hpp
minium2/Box2D
620af0b776a4773736233f0eb3cfdbb2bd84cf26
[ "Zlib" ]
null
null
null
Testbed/Tests/MotorJoint.hpp
minium2/Box2D
620af0b776a4773736233f0eb3cfdbb2bd84cf26
[ "Zlib" ]
14
2015-01-14T09:14:25.000Z
2022-02-10T17:27:14.000Z
/* * Copyright (c) 2006-2012 Erin Catto http://www.box2d.org * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would be * appreciated but is not required. * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * 3. This notice may not be removed or altered from any source distribution. */ #ifndef MOTOR_JOINT_HPP #define MOTOR_JOINT_HPP /// This test shows how to use a motor joint. A motor joint /// can be used to animate a dynamic body. With finite motor forces /// the body can be blocked by collision with other bodies. class MotorJoint : public Test { public: MotorJoint() { b2::Body* ground = NULL; { b2::BodyDef bd; ground = m_world->CreateBody(&bd); b2::EdgeShape shape; shape.Set(b2::Vec2(-20.0f, 0.0f), b2::Vec2(20.0f, 0.0f)); b2::FixtureDef fd; fd.shape = &shape; ground->CreateFixture(&fd); } // Define motorized body { b2::BodyDef bd; bd.type = b2::dynamicBody; bd.position.Set(0.0f, 8.0f); b2::Body* body = m_world->CreateBody(&bd); b2::PolygonShape shape; shape.SetAsBox(2.0f, 0.5f); b2::FixtureDef fd; fd.shape = &shape; fd.friction = 0.6f; fd.density = 2.0f; body->CreateFixture(&fd); b2::MotorJointDef mjd; mjd.Initialize(ground, body); mjd.maxForce = 1000.0f; mjd.maxTorque = 1000.0f; m_joint = (b2::MotorJoint*)m_world->CreateJoint(&mjd); } m_go = false; m_time = 0.0f; } void Keyboard(int key) { switch (key) { case GLFW_KEY_S: m_go = !m_go; break; } } void Step(Settings* settings) { if (m_go && settings->hz > 0.0f) { m_time += 1.0f / settings->hz; } b2::Vec2 linearOffset; linearOffset.x = 6.0f * std::sin(2.0f * m_time); linearOffset.y = 8.0f + 4.0f * std::sin(1.0f * m_time); b2::float32 angularOffset = 4.0f * m_time; m_joint->SetLinearOffset(linearOffset); m_joint->SetAngularOffset(angularOffset); g_debugDraw.DrawPoint(linearOffset, 4.0f, b2::Color(0.9f, 0.9f, 0.9f)); Test::Step(settings); g_debugDraw.DrawString(5, m_textLine, "Keys: (s) pause"); m_textLine += 15; } static Test* Create() { return new MotorJoint; } b2::MotorJoint* m_joint; b2::float32 m_time; bool m_go; }; #endif
25.252174
77
0.65668
[ "shape" ]
b001dd3e203fecda1af3d93c68d0a447dd6e15d8
11,171
cpp
C++
src/mhd.cpp
matu3ba/simpaSRG
a38ef23973e15053414c7c8b4cdf61c09aa26bf1
[ "MIT" ]
1
2022-03-03T15:33:07.000Z
2022-03-03T15:33:07.000Z
src/mhd.cpp
matu3ba/simpaSRG
a38ef23973e15053414c7c8b4cdf61c09aa26bf1
[ "MIT" ]
null
null
null
src/mhd.cpp
matu3ba/simpaSRG
a38ef23973e15053414c7c8b4cdf61c09aa26bf1
[ "MIT" ]
null
null
null
//FILE mhd.cpp #include "mhd.h" #include <boost/algorithm/string.hpp> #include <iterator> //for copy iterator //ostream writes random ^M on carriage return, which invalidates up number conversion //C FILE API was used to read/write files due to this behavior std::ostream &operator << (std::ostream &os, const ST_Mhd &mhd) { os << mhd.sObjectType.first << "=" << mhd.sObjectType.second << "\n" << mhd.uchNDims.first << "=" << (mhd.uchNDims).second << "\n" << mhd.v_uiDimSize.first << "="; for (auto& i : mhd.v_uiDimSize.second) os << i << " "; os << "\n"; os << mhd.v_dElementSize.first << "="; for (auto& i : mhd.v_dElementSize.second) os << i << " "; os << "\n"; os << mhd.sElementType.first << "=" << mhd.sElementType.second << "\n" << mhd.v_uiOffset.first << "="; for (auto& i : mhd.v_uiOffset.second) os << i << " "; os << "\n" << mhd.sElementDataFile.first << "=" << mhd.sElementDataFile.second << "\n"; return os; } Return checkPath(const std::filesystem::path &mhdpath, std::string extension) { if (!is_regular_file(mhdpath)) { return Return::invalidpath2; } if ( (mhdpath.has_stem() == false) || (mhdpath.has_extension() == false) ) { return Return::invalidpath3; } if ( mhdpath.extension() != extension ) { return Return::invalidpath4; } if ( mhdpath.parent_path().filename() != "data" ) { return Return::invalidpath5; } return Return::ok; } Return getFileContent(const std::filesystem::path &mhdpath, std::vector<std::string> & vec_mhd) { Return status = Return::ok; status = checkPath(mhdpath, ".mhd"); if ( status != Return::ok ) return status; std::ifstream in(mhdpath.c_str()); if (!in) { std::cerr << "cannot open file: " << mhdpath.string() << "\n"; return Return::mhd_inputfile; } std::string str; while(std::getline(in, str)) { str.erase(std::remove(str.begin(), str.end(), '\n'), str.end()); str.erase(std::remove(str.begin(), str.end(), '\r'), str.end()); vec_mhd.push_back(str); } in.close(); return Return::ok; } // read MhdFile in path to struct Mhd and return sizes of 3D Cube Return readMhdFile(const std::filesystem::path &path, ST_Mhd &Mhd, Int3 &sizes) { const size_t max_len = 100; std::vector<std::string> spl_line; std::string stmp; std::vector<std::string> vec_mhd; Return status = Return::ok; status = getFileContent(path, vec_mhd); if ( status != Return::ok ) return returnPrint(status); int32_t i = 0; if( vec_mhd[i].compare(0, Mhd.sObjectType.first.length(), Mhd.sObjectType.first) != 0 ) { return returnPrint(Return::mhd_invalid_format); } else { //std::cout << vec_mhd[i].substr(Mhd.sObjectType.first.length()+1, max_len) << "\n"; // we dont want the '=' in the string stmp = vec_mhd[i].substr(Mhd.sObjectType.first.length()+1, max_len); Mhd.sObjectType.second = stmp; } ++i; if( vec_mhd[i].compare(0, Mhd.uchNDims.first.length(), Mhd.uchNDims.first) != 0 ) { return returnPrint(Return::mhd_invalid_mhdfile1); } else { stmp = vec_mhd[i].substr(Mhd.uchNDims.first.length()+1, max_len); //base means hex etc values Mhd.uchNDims.second = static_cast<uint16_t>(std::stoul(stmp,nullptr,0)); } ++i; if( vec_mhd[i].compare(0, Mhd.v_uiDimSize.first.length(), Mhd.v_uiDimSize.first) != 0 ) { return returnPrint(Return::mhd_invalid_mhdfile2); } else { stmp = vec_mhd[i].substr(Mhd.v_uiDimSize.first.length()+1, max_len); boost::split(spl_line, stmp, boost::is_any_of(" ")); for (auto& el: spl_line) { //std::cout << el << "\n"; if (el.length() > 0 && el != " ") //x" "" " may result in " " or emptystring Mhd.v_uiDimSize.second.push_back( static_cast<uint64_t>(std::stoul(el,nullptr,0)) ); } if ( Mhd.v_uiDimSize.second.size() < 3 ) //less than 3 dimensions return returnPrint(Return::mhd_dimensionlower3); } ++i; if( vec_mhd[i].compare(0, Mhd.v_dElementSize.first.length(), Mhd.v_dElementSize.first) != 0 ) { return returnPrint(Return::mhd_invalid_mhdfile3); } else { stmp = vec_mhd[i].substr(Mhd.v_dElementSize.first.length()+1, max_len); boost::split(spl_line, stmp, boost::is_any_of(" ")); for (auto& el: spl_line) { //std::cout << el << "\n"; if (el.length() > 0 && el != " ") //x" "" " may result in " " or emptystring Mhd.v_dElementSize.second.push_back( std::stod(el,nullptr) ); //base means hex etc values } } ++i; if( vec_mhd[i].compare(0, Mhd.sElementType.first.length(), Mhd.sElementType.first) != 0 ) { return returnPrint(Return::mhd_invalid_mhdfile4); } else { // we dont want the '=' in the string stmp = vec_mhd[i].substr(Mhd.sElementType.first.length()+1, max_len); Mhd.sElementType.second = stmp; } ++i; if( vec_mhd[i].compare(0, Mhd.v_uiOffset.first.length(), Mhd.v_uiOffset.first) != 0 ) { return returnPrint(Return::mhd_invalid_mhdfile5); } else { stmp = vec_mhd[i].substr(Mhd.v_uiOffset.first.length()+1, max_len); boost::split(spl_line, stmp, boost::is_any_of(" ")); for (auto& el: spl_line) { //std::cout << el << "\n"; if (el.length() > 0 && el != " ") //x" "" " may result in " " or emptystring Mhd.v_uiOffset.second.push_back( static_cast<uint64_t>(std::stoul(el,nullptr,0)) ); } } ++i; if( vec_mhd[i].compare(0, Mhd.v_uiRotation.first.length(), Mhd.v_uiRotation.first) != 0 ) { //FALLTHROUGH (no field Rotation) } else { // we dont want the '=' in the string stmp = vec_mhd[i].substr(Mhd.v_uiRotation.first.length()+1, max_len); boost::split(spl_line, stmp, boost::is_any_of(" ")); for (auto& el: spl_line) { //std::cout << el << "\n"; if (el.length() > 0 && el != " ") //x" "" " may result in " " or emptystring Mhd.v_uiRotation.second.push_back( static_cast<uint64_t>(std::stoul(el,nullptr,0)) ); } ++i; } if( vec_mhd[i].compare(0, Mhd.sElementDataFile.first.length(), Mhd.sElementDataFile.first) != 0 ) { return returnPrint(Return::mhd_invalid_mhdfile6); } else { // we dont want the '=' in the string stmp = vec_mhd[i].substr(Mhd.sElementDataFile.first.length()+1, max_len); Mhd.sElementDataFile.second = stmp; } ++i; sizes.x = Mhd.v_uiDimSize.second[0]; sizes.y = Mhd.v_uiDimSize.second[1]; sizes.z = Mhd.v_uiDimSize.second[2]; return Return::ok; } // write MhdFile to path from struct Mhd // REMARK carriage return as ^M are appended on strings Return writeMhdFile(const std::filesystem::path &path, ST_Mhd &Mhd) { std::FILE * mhdfile; mhdfile = std::fopen(path.c_str(), "wb"); //binary mode would be .write() if (mhdfile == NULL) { std::cerr << "cannot write file: " << path << "\n"; return returnPrint(Return::mhd_outputfile); } //std::cout << Mhd.sObjectType.first + "=" + Mhd.sObjectType.second << "\n" // << Mhd.uchNDims.first + "=" << std::to_string((Mhd.uchNDims).second) + "\n"; std::string s1 = Mhd.sObjectType.first + "=" + Mhd.sObjectType.second + "\n"; s1.append ( Mhd.uchNDims.first + "=" ); s1.append ( std::to_string((Mhd.uchNDims).second) + "\n" ); s1.append ( Mhd.v_uiDimSize.first + "=" ); for (uint32_t i=0; i<Mhd.v_uiDimSize.second.size(); ++i) { if ( i == Mhd.v_uiDimSize.second.size()-1 ) s1.append ( std::to_string(Mhd.v_uiDimSize.second[i]) ); else s1.append ( std::to_string(Mhd.v_uiDimSize.second[i]) + " " ); } s1.append ( "\n" ); s1.append ( Mhd.v_dElementSize.first + "=" ); for (uint32_t i=0; i<Mhd.v_dElementSize.second.size(); ++i) { if ( i == Mhd.v_dElementSize.second.size()-1 ) s1.append ( std::to_string(Mhd.v_dElementSize.second[i]) ); else s1.append ( std::to_string(Mhd.v_dElementSize.second[i]) + " " ); } s1.append ( "\n" ); s1.append ( Mhd.sElementType.first + "=" + Mhd.sElementType.second + "\n" ); s1.append ( Mhd.v_uiOffset.first + "=" ); for (uint32_t i=0; i<Mhd.v_uiOffset.second.size(); ++i) { if ( i == Mhd.v_uiOffset.second.size()-1 ) s1.append ( std::to_string(Mhd.v_uiOffset.second[i]) ); else s1.append ( std::to_string(Mhd.v_uiOffset.second[i]) + " " ); } s1.append ( "\n" ); //OPTIONAL Rotation field exists if (Mhd.v_uiRotation.second.size() > 0) { s1.append ( Mhd.v_uiRotation.first + "=" ); for (uint32_t i=0; i<Mhd.v_uiRotation.second.size(); ++i) { if ( i == Mhd.v_uiRotation.second.size()-1 ) s1.append ( std::to_string(Mhd.v_uiRotation.second[i]) ); else s1.append ( std::to_string(Mhd.v_uiRotation.second[i]) + " " ); } s1.append ( "\n" ); } s1.append( Mhd.sElementDataFile.first + "=" + Mhd.sElementDataFile.second + "\n" ); //std::cout << s1 ; //std::cout << s1.c_str(); std::fwrite(s1.data(),sizeof(char),s1.length(),mhdfile); std::fclose(mhdfile); return Return::ok; } Return checkValidity(std::vector<unsigned char> &Cube_data, ST_Mhd &Mhd) { uint64_t size = Mhd.v_uiDimSize.second[0] * Mhd.v_uiDimSize.second[1] * Mhd.v_uiDimSize.second[2]; if(Cube_data.size() != size) { std::cerr << "mhd size: " << size << " raw size: " << Cube_data.size() << "\n"; return returnPrint(Return::mhd_size_unequal); } return Return::ok; } // RawFile belongs to Mhd header and is defined by Mhd.sElementDataFile // Cube_data contains the RawData as 3D Cube Return readRawFile(const std::filesystem::path &datafolder, std::vector<unsigned char> &Cube_data, ST_Mhd &Mhd) { std::filesystem::path imgpath = datafolder; imgpath /= Mhd.sElementDataFile.second; Return status = Return::ok; status = checkPath(imgpath, ".img"); if ( status != Return::ok ) { std::cerr << "invalid file path: " << imgpath << "\n"; return returnPrint(Return::raw_inputfile); } //std::cout << "imgpath: " << imgpath << "\n"; std::FILE * rawfile; rawfile = std::fopen(imgpath.c_str(), "rb"); if (rawfile == NULL) { std::cerr << "cannot open file: " << Mhd.sElementDataFile.second << "\n"; return returnPrint(Return::raw_inputfile); } std::size_t res = std::fread(Cube_data.data(),sizeof(unsigned char),Cube_data.size(),rawfile); if (res == 0) std::cerr << "nothing was read\n"; //std::cout << res << " voxels(1B) read\n"; std::fclose(rawfile); return Return::ok; } // RawFile belongs to Mhd header and is defined by Mhd.sElementDataFile // Cube_data contains the RawData as cube Return writeRawFile(const std::filesystem::path &datafolder, std::vector<unsigned char> &Cube_data, ST_Mhd &Mhd) { std::filesystem::path imgpath = datafolder; imgpath /= Mhd.sElementDataFile.second; std::FILE * rawfile; rawfile = std::fopen(imgpath.c_str(), "wb"); if (rawfile == NULL) { std::cerr << "cannot write file: " << imgpath.string() << "\n"; return returnPrint(Return::raw_outputfile); } std::size_t res = std::fwrite(Cube_data.data(),sizeof(unsigned char),Cube_data.size(),rawfile); if (res == 0) std::cerr << "nothing was written\n"; //std::cout << res << " voxels(1B) written\n"; std::fclose(rawfile); return Return::ok; }
39.473498
101
0.625369
[ "vector", "3d" ]
b005c0f903ab4014ce31e083dd8cbdf8f12a1506
14,061
hpp
C++
iOS/G3MiOSSDK/Commons/Rendererers/PlanetRenderer.hpp
restjohn/g3m
608657fd6f0e2898bd963d15136ff085b499e97e
[ "BSD-2-Clause" ]
null
null
null
iOS/G3MiOSSDK/Commons/Rendererers/PlanetRenderer.hpp
restjohn/g3m
608657fd6f0e2898bd963d15136ff085b499e97e
[ "BSD-2-Clause" ]
null
null
null
iOS/G3MiOSSDK/Commons/Rendererers/PlanetRenderer.hpp
restjohn/g3m
608657fd6f0e2898bd963d15136ff085b499e97e
[ "BSD-2-Clause" ]
null
null
null
// // PlanetRenderer.hpp // G3MiOSSDK // // Created by Agustin Trujillo Pino on 12/06/12. // Copyright (c) 2012 __MyCompanyName__. All rights reserved. // #ifndef G3MiOSSDK_PlanetRenderer #define G3MiOSSDK_PlanetRenderer class Tile; class TileTessellator; class LayerSet; class VisibleSectorListenerEntry; class VisibleSectorListener; class ElevationDataProvider; class LayerTilesRenderParameters; class TerrainTouchListener; class ChangedInfoListener; class TileRenderingListener; #include "IStringBuilder.hpp" #include "DefaultRenderer.hpp" #include "Sector.hpp" #include "Tile.hpp" #include "Camera.hpp" #include "LayerSet.hpp" #include "ITileVisitor.hpp" #include "SurfaceElevationProvider.hpp" #include "ChangedListener.hpp" #include "TouchEvent.hpp" class EllipsoidShape; class TilesStatistics { private: long _tilesProcessed; long _tilesVisible; long _tilesRendered; static const int _maxLOD = 128; int _tilesProcessedByLevel[_maxLOD]; int _tilesVisibleByLevel[_maxLOD]; int _tilesRenderedByLevel[_maxLOD]; int _buildersStartsInFrame; double _visibleLowerLatitudeDegrees; double _visibleLowerLongitudeDegrees; double _visibleUpperLatitudeDegrees; double _visibleUpperLongitudeDegrees; public: TilesStatistics() { clear(); } ~TilesStatistics() { } void clear() { _tilesProcessed = 0; _tilesVisible = 0; _tilesRendered = 0; _buildersStartsInFrame = 0; const IMathUtils* mu = IMathUtils::instance(); _visibleLowerLatitudeDegrees = mu->maxDouble(); _visibleLowerLongitudeDegrees = mu->maxDouble(); _visibleUpperLatitudeDegrees = mu->minDouble(); _visibleUpperLongitudeDegrees = mu->minDouble(); for (int i = 0; i < _maxLOD; i++) { _tilesProcessedByLevel[i] = 0; _tilesVisibleByLevel[i] = 0; _tilesRenderedByLevel[i] = 0; } } int getBuildersStartsInFrame() const { return _buildersStartsInFrame; } void computeBuilderStartInFrame() { _buildersStartsInFrame++; } void computeTileProcessed(Tile* tile) { _tilesProcessed++; const int level = tile->_level; _tilesProcessedByLevel[level] = _tilesProcessedByLevel[level] + 1; } void computeVisibleTile(Tile* tile) { _tilesVisible++; const int level = tile->_level; _tilesVisibleByLevel[level] = _tilesVisibleByLevel[level] + 1; } void computeRenderedSector(Tile* tile) { const Sector sector = tile->_sector; const double lowerLatitudeDegrees = sector._lower._latitude._degrees; const double lowerLongitudeDegrees = sector._lower._longitude._degrees; const double upperLatitudeDegrees = sector._upper._latitude._degrees; const double upperLongitudeDegrees = sector._upper._longitude._degrees; if (lowerLatitudeDegrees < _visibleLowerLatitudeDegrees) { _visibleLowerLatitudeDegrees = lowerLatitudeDegrees; } if (upperLatitudeDegrees < _visibleLowerLatitudeDegrees) { _visibleLowerLatitudeDegrees = upperLatitudeDegrees; } if (lowerLatitudeDegrees >_visibleUpperLatitudeDegrees) { _visibleUpperLatitudeDegrees = lowerLatitudeDegrees; } if (upperLatitudeDegrees > _visibleUpperLatitudeDegrees) { _visibleUpperLatitudeDegrees = upperLatitudeDegrees; } if (lowerLongitudeDegrees < _visibleLowerLongitudeDegrees) { _visibleLowerLongitudeDegrees = lowerLongitudeDegrees; } if (upperLongitudeDegrees < _visibleLowerLongitudeDegrees) { _visibleLowerLongitudeDegrees = upperLongitudeDegrees; } if (lowerLongitudeDegrees > _visibleUpperLongitudeDegrees) { _visibleUpperLongitudeDegrees = lowerLongitudeDegrees; } if (upperLongitudeDegrees > _visibleUpperLongitudeDegrees) { _visibleUpperLongitudeDegrees = upperLongitudeDegrees; } } void computeTileRenderered(Tile* tile) { _tilesRendered++; const int level = tile->_level; _tilesRenderedByLevel[level] = _tilesRenderedByLevel[level] + 1; computeRenderedSector(tile); } Sector* updateVisibleSector(Sector* visibleSector) const { if ((visibleSector == NULL) || (visibleSector->_lower._latitude._degrees != _visibleLowerLatitudeDegrees) || (visibleSector->_lower._longitude._degrees != _visibleLowerLongitudeDegrees) || (visibleSector->_upper._latitude._degrees != _visibleUpperLatitudeDegrees) || (visibleSector->_upper._longitude._degrees != _visibleUpperLongitudeDegrees) ) { delete visibleSector; if ((_visibleLowerLatitudeDegrees > _visibleUpperLatitudeDegrees) || (_visibleLowerLongitudeDegrees > _visibleUpperLongitudeDegrees)) { return NULL; } return new Sector(Geodetic2D::fromDegrees(_visibleLowerLatitudeDegrees, _visibleLowerLongitudeDegrees), Geodetic2D::fromDegrees(_visibleUpperLatitudeDegrees, _visibleUpperLongitudeDegrees)); } return visibleSector; } static std::string asLogString(const int m[], const int nMax) { bool first = true; IStringBuilder* isb = IStringBuilder::newStringBuilder(); for(int i = 0; i < nMax; i++) { const int level = i; const int counter = m[i]; if (counter != 0) { if (first) { first = false; } else { isb->addString(","); } isb->addInt(level); isb->addString(":"); isb->addInt(counter); } } std::string s = isb->getString(); delete isb; return s; } void log(const ILogger* logger) const { logger->logInfo("Tiles processed:%d (%s), visible:%d (%s), rendered:%d (%s).", _tilesProcessed, asLogString(_tilesProcessedByLevel, _maxLOD).c_str(), _tilesVisible, asLogString(_tilesVisibleByLevel, _maxLOD).c_str(), _tilesRendered, asLogString(_tilesRenderedByLevel, _maxLOD).c_str()); } }; class PlanetRenderer: public DefaultRenderer, ChangedListener, ChangedInfoListener, SurfaceElevationProvider { private: TileTessellator* _tessellator; ElevationDataProvider* _elevationDataProvider; bool _ownsElevationDataProvider; TileTexturizer* _texturizer; LayerSet* _layerSet; const TilesRenderParameters* _tilesRenderParameters; const bool _showStatistics; const bool _logTilesPetitions; ITileVisitor* _tileVisitor = NULL; TileRenderingListener* _tileRenderingListener; std::vector<const Tile*>* _tilesStartedRendering; std::vector<std::string>* _tilesStoppedRendering; TilesStatistics _statistics; #ifdef C_CODE const Camera* _lastCamera; #endif #ifdef JAVA_CODE private Camera _lastCamera; #endif std::vector<Tile*> _firstLevelTiles; bool _firstLevelTilesJustCreated; bool _allFirstLevelTilesAreTextureSolved; ITimer* _lastSplitTimer; // timer to start every time a tile get splitted into subtiles void clearFirstLevelTiles(); void createFirstLevelTiles(const G3MContext* context); void createFirstLevelTiles(std::vector<Tile*>& firstLevelTiles, Tile* tile, int firstLevel) const; void sortTiles(std::vector<Tile*>& firstLevelTiles) const; bool _firstRender; void pruneFirstLevelTiles(); Sector* _lastVisibleSector; std::vector<VisibleSectorListenerEntry*> _visibleSectorListeners; void visitTilesTouchesWith(const Sector& sector, const int topLevel, const int maxLevel); void visitSubTilesTouchesWith(std::vector<Layer*> layers, Tile* tile, const Sector& sectorToVisit, const int topLevel, const int maxLevel); long long _tileDownloadPriority; float _verticalExaggeration; bool _recreateTilesPending; GLState* _glState; void updateGLState(const G3MRenderContext* rc); SurfaceElevationProvider_Tree _elevationListenersTree; bool _renderTileMeshes; Sector* _renderedSector; // bool _validLayerTilesRenderParameters; bool _layerTilesRenderParametersDirty; #ifdef C_CODE const LayerTilesRenderParameters* _layerTilesRenderParameters; #endif #ifdef JAVA_CODE private LayerTilesRenderParameters _layerTilesRenderParameters; #endif std::vector<std::string> _errors; const LayerTilesRenderParameters* getLayerTilesRenderParameters(); std::vector<TerrainTouchListener*> _terrainTouchListeners; TouchEventType _touchEventTypeOfTerrainTouchListener; std::vector<Tile*> _toVisit; std::vector<Tile*> _toVisitInNextIteration; public: PlanetRenderer(TileTessellator* tessellator, ElevationDataProvider* elevationDataProvider, bool ownsElevationDataProvider, float verticalExaggeration, TileTexturizer* texturizer, LayerSet* layerSet, const TilesRenderParameters* tilesRenderParameters, bool showStatistics, long long tileDownloadPriority, const Sector& renderedSector, const bool renderTileMeshes, const bool logTilesPetitions, TileRenderingListener* tileRenderingListener, ChangedRendererInfoListener* changedInfoListener, TouchEventType touchEventTypeOfTerrainTouchListener); ~PlanetRenderer(); void initialize(const G3MContext* context); void render(const G3MRenderContext* rc, GLState* glState); bool onTouchEvent(const G3MEventContext* ec, const TouchEvent* touchEvent); void onResizeViewportEvent(const G3MEventContext* ec, int width, int height) { } RenderState getRenderState(const G3MRenderContext* rc); void acceptTileVisitor(ITileVisitor* tileVisitor, const Sector& sector, const int topLevel, const int maxLevel) { _tileVisitor = tileVisitor; visitTilesTouchesWith(sector, topLevel, maxLevel); } void start(const G3MRenderContext* rc) { _firstRender = true; } void stop(const G3MRenderContext* rc) { _firstRender = false; } void onPause(const G3MContext* context) { recreateTiles(); } void setEnable(bool enable) { #ifdef C_CODE DefaultRenderer::setEnable(enable); #endif #ifdef JAVA_CODE super.setEnable(enable); #endif if (!enable) { pruneFirstLevelTiles(); } } void changed(); void recreateTiles(); /** Answer the visible-sector, it can be null if globe was not yet rendered. */ const Sector* getVisibleSector() const { return _lastVisibleSector; } /** Add a listener for notification of visible-sector changes. @param stabilizationInterval How many time the visible-sector has to be settled (without changes) before triggering the event. Useful for avoid process while the camera is being moved (as in animations). If stabilizationInterval is zero, the event is triggered immediately. */ void addVisibleSectorListener(VisibleSectorListener* listener, const TimeInterval& stabilizationInterval); /** Add a listener for notification of visible-sector changes. The event is triggered immediately without waiting for the visible-sector get settled. */ void addVisibleSectorListener(VisibleSectorListener* listener) { addVisibleSectorListener(listener, TimeInterval::zero()); } /** * Set the download-priority used by Tiles (for downloading textures). * * @param tileDownloadPriority: new value for download priority of textures */ void setTileDownloadPriority(long long tileDownloadPriority) { _tileDownloadPriority = tileDownloadPriority; } /** * Return the current value for the download priority of textures * * @return _tileDownloadPriority: long */ long long getTileDownloadPriority() const { return _tileDownloadPriority; } /** * @see Renderer#isPlanetRenderer() */ bool isPlanetRenderer() { return true; } SurfaceElevationProvider* getSurfaceElevationProvider() { return (_elevationDataProvider == NULL) ? NULL : this; } PlanetRenderer* getPlanetRenderer() { return this; } void addListener(const Angle& latitude, const Angle& longitude, SurfaceElevationListener* listener); void addListener(const Geodetic2D& position, SurfaceElevationListener* listener); bool removeListener(SurfaceElevationListener* listener); void sectorElevationChanged(ElevationData* elevationData) const; const Sector* getRenderedSector() const { return _renderedSector; } bool setRenderedSector(const Sector& sector); void addTerrainTouchListener(TerrainTouchListener* listener); void setElevationDataProvider(ElevationDataProvider* elevationDataProvider, bool owned); void setVerticalExaggeration(float verticalExaggeration); ElevationDataProvider* getElevationDataProvider() const { return _elevationDataProvider; } void setRenderTileMeshes(bool renderTileMeshes) { _renderTileMeshes = renderTileMeshes; } bool getRenderTileMeshes() const { return _renderTileMeshes; } void changedInfo(const std::vector<std::string>& info) { if (_changedInfoListener != NULL) { _changedInfoListener->changedRendererInfo(_rendererIdentifier, info); } } float getVerticalExaggeration() const { return _verticalExaggeration; } }; #endif
29.539916
278
0.681815
[ "render", "vector" ]
b008fa21067058c6c0f6810d94233d966f88d5de
8,246
cpp
C++
HookDll/Hook/InventorySack_AddItem.cpp
MartinRohrbach/iagd
f6aa8880b82eab575544b66cd2a9b2a5160683c9
[ "MIT" ]
null
null
null
HookDll/Hook/InventorySack_AddItem.cpp
MartinRohrbach/iagd
f6aa8880b82eab575544b66cd2a9b2a5160683c9
[ "MIT" ]
null
null
null
HookDll/Hook/InventorySack_AddItem.cpp
MartinRohrbach/iagd
f6aa8880b82eab575544b66cd2a9b2a5160683c9
[ "MIT" ]
null
null
null
#include "stdafx.h" #include <set> #include <stdio.h> #include <stdlib.h> #include "MessageType.h" #include <detours.h> #include "InventorySack_AddItem.h" #include "Exports.h" #define STASH_1 0 #define STASH_2 1 #define STASH_3 2 #define STASH_4 3 #define STASH_5 4 #define STASH_PRIVATE 1000 HANDLE InventorySack_AddItem::m_hEvent; DataQueue* InventorySack_AddItem::m_dataQueue; InventorySack_AddItem::GameEngine_GetTransferSack InventorySack_AddItem::dll_GameEngine_GetTransferSack; InventorySack_AddItem::GameEngine_SetTransferOpen InventorySack_AddItem::dll_GameEngine_SetTransferOpen; InventorySack_AddItem::GameInfo_GameInfo_Param InventorySack_AddItem::dll_GameInfo_GameInfo_Param; InventorySack_AddItem::GameInfo_GameInfo InventorySack_AddItem::dll_GameInfo_GameInfo; InventorySack_AddItem::GameInfo_SetHardcore InventorySack_AddItem::dll_GameInfo_SetHardcore; InventorySack_AddItem::GameInfo_GetHardcore InventorySack_AddItem::dll_GameInfo_GetHardcore; InventorySack_AddItem::GameEngine_GetGameInfo InventorySack_AddItem::dll_GameEngine_GetGameInfo; InventorySack_AddItem::InventorySack_Sort InventorySack_AddItem::dll_InventorySack_Sort; GetPrivateStash InventorySack_AddItem::privateStashHook; InventorySack_AddItem::InventorySack_InventorySack InventorySack_AddItem::dll_InventorySack_InventorySack; InventorySack_AddItem::InventorySack_InventorySackParam InventorySack_AddItem::dll_InventorySack_InventorySackParam; int InventorySack_AddItem::m_isHardcore; void* InventorySack_AddItem::m_gameEngine = NULL; // Check if this sack is the Nth transfer sack // Zero indexed, so 3 == stash 4 bool InventorySack_AddItem::IsTransferStash(void* stash, int idx) { if (m_gameEngine != NULL) { // class GAME::InventorySack * GAME::GameEngine::GetTransferSack(int) if (dll_GameEngine_GetTransferSack != NULL) { return dll_GameEngine_GetTransferSack(m_gameEngine, idx) == stash; } } return false; } void InventorySack_AddItem::EnableHook() { dll_GameEngine_GetTransferSack = (GameEngine_GetTransferSack)GetProcAddress(::GetModuleHandle("Game.dll"), GET_TRANSFER_SACK); DetourTransactionBegin(); DetourUpdateThread(GetCurrentThread()); DetourAttach((PVOID*)&dll_GameEngine_GetTransferSack, Hooked_GameEngine_GetTransferSack); DetourTransactionCommit(); dll_GameEngine_SetTransferOpen = (GameEngine_SetTransferOpen)GetProcAddress(::GetModuleHandle("Game.dll"), SET_TRANSFER_OPEN); if (dll_GameEngine_SetTransferOpen != NULL) { DetourTransactionBegin(); DetourUpdateThread(GetCurrentThread()); DetourAttach((PVOID*)&dll_GameEngine_SetTransferOpen, Hooked_GameEngine_SetTransferOpen); DetourTransactionCommit(); } else { DataItemPtr item(new DataItem(TYPE_ERROR_HOOKING_TRANSFER_STASH, 0, 0)); m_dataQueue->push(item); SetEvent(m_hEvent); } // GameInfo:: dll_GameInfo_GameInfo_Param = (GameInfo_GameInfo_Param)GetProcAddress(::GetModuleHandle("Engine.dll"), GAMEINFO_CONSTRUCTOR_ARGS); DetourTransactionBegin(); DetourUpdateThread(GetCurrentThread()); DetourAttach((PVOID*)&dll_GameInfo_GameInfo_Param, Hooked_GameInfo_GameInfo_Param); DetourTransactionCommit(); dll_GameInfo_GameInfo = (GameInfo_GameInfo)GetProcAddress(::GetModuleHandle("Engine.dll"), GAMEINFO_CONSTRUCTOR); DetourTransactionBegin(); DetourUpdateThread(GetCurrentThread()); DetourAttach((PVOID*)&dll_GameInfo_GameInfo, Hooked_GameInfo_GameInfo); DetourTransactionCommit(); dll_GameInfo_SetHardcore = (GameInfo_SetHardcore)GetProcAddress(::GetModuleHandle("Engine.dll"), SET_IS_HARDCORE); DetourTransactionBegin(); DetourUpdateThread(GetCurrentThread()); DetourAttach((PVOID*)&dll_GameInfo_SetHardcore, Hooked_GameInfo_SetHardcore); DetourTransactionCommit(); privateStashHook.EnableHook(); dll_InventorySack_Sort = (InventorySack_Sort)GetProcAddress(::GetModuleHandle("Game.dll"), SORT_INVENTORY); DetourTransactionBegin(); DetourUpdateThread(GetCurrentThread()); DetourAttach((PVOID*)&dll_InventorySack_Sort, Hooked_InventorySack_Sort); DetourTransactionCommit(); // bool GAME::GameInfo::GetHardcore(void) dll_GameInfo_GetHardcore = (GameInfo_GetHardcore)GetProcAddress(::GetModuleHandle("Engine.dll"), GET_HARDCORE); // class GAME::GameInfo * GAME::Engine::GetGameInfo(void) dll_GameEngine_GetGameInfo = (GameEngine_GetGameInfo)GetProcAddress(::GetModuleHandle("Engine.dll"), GET_GAME_INFO); } InventorySack_AddItem::InventorySack_AddItem(DataQueue* dataQueue, HANDLE hEvent) { InventorySack_AddItem::m_dataQueue = dataQueue; InventorySack_AddItem::m_hEvent = hEvent; privateStashHook = GetPrivateStash(dataQueue, hEvent); m_isHardcore = -1; } InventorySack_AddItem::InventorySack_AddItem() { InventorySack_AddItem::m_hEvent = NULL; m_isHardcore = -1; } void InventorySack_AddItem::DisableHook() { DetourTransactionBegin(); DetourUpdateThread(GetCurrentThread()); DetourDetach((PVOID*)&dll_GameEngine_GetTransferSack, Hooked_GameEngine_GetTransferSack); DetourDetach((PVOID*)&dll_GameEngine_SetTransferOpen, Hooked_GameEngine_SetTransferOpen); DetourDetach((PVOID*)&dll_GameInfo_GameInfo_Param, Hooked_GameInfo_GameInfo_Param); DetourDetach((PVOID*)&dll_GameInfo_GameInfo, Hooked_GameInfo_GameInfo); DetourDetach((PVOID*)&dll_GameInfo_SetHardcore, Hooked_GameInfo_SetHardcore); DetourDetach((PVOID*)&dll_InventorySack_Sort, Hooked_InventorySack_Sort); DetourTransactionCommit(); privateStashHook.DisableHook(); } void __fastcall InventorySack_AddItem::Hooked_GameEngine_SetTransferOpen(void* This , bool isOpen) { dll_GameEngine_SetTransferOpen(This, isOpen); m_gameEngine = This; char b[1]; b[0] = (isOpen ? 1 : 0); DataItemPtr item(new DataItem(TYPE_OPEN_CLOSE_TRANSFER_STASH, 1, (char*)b)); m_dataQueue->push(item); SetEvent(m_hEvent); } int InventorySack_AddItem::GetStashIndex(void* stash) { if (stash == privateStashHook.GetPrivateStashInventorySack()) return STASH_PRIVATE; else if (IsTransferStash(stash, STASH_1)) return STASH_1; else if (IsTransferStash(stash, STASH_2)) return STASH_2; else if (IsTransferStash(stash, STASH_3)) return STASH_3; else if (IsTransferStash(stash, STASH_4)) return STASH_4; else if (IsTransferStash(stash, STASH_5)) return STASH_5; return -1; } // Since were creating from an existing object we'll need to call Get() on isHardcore and ModLabel void* __fastcall InventorySack_AddItem::Hooked_GameInfo_GameInfo_Param(void* This , void* info) { void* result = dll_GameInfo_GameInfo_Param(This, info); bool isHardcore = dll_GameInfo_GetHardcore(This); DataItemPtr dataEvent(new DataItem(TYPE_GameInfo_IsHardcore_via_init, sizeof(isHardcore), (char*)&isHardcore)); m_dataQueue->push(dataEvent); SetEvent(m_hEvent); m_isHardcore = isHardcore ? 1 : 0; return result; } void* __fastcall InventorySack_AddItem::Hooked_GameInfo_GameInfo(void* This ) { void* result = dll_GameInfo_GameInfo(This); DataItemPtr dataEvent(new DataItem(TYPE_GameInfo_IsHardcore_via_init_2, 0, 0)); m_dataQueue->push(dataEvent); SetEvent(m_hEvent); return result; } //void GAME::GameInfo::SetHardcore(bool) void* __fastcall InventorySack_AddItem::Hooked_GameInfo_SetHardcore(void* This , bool isHardcore) { DataItemPtr dataEvent(new DataItem(TYPE_GameInfo_IsHardcore, sizeof(isHardcore), (char*)&isHardcore)); m_dataQueue->push(dataEvent); SetEvent(m_hEvent); m_isHardcore = isHardcore ? 1 : 0; return dll_GameInfo_SetHardcore(This, isHardcore); } // When stash 3 is sorted, IA no longer knows where items are placed bool __fastcall InventorySack_AddItem::Hooked_InventorySack_Sort(void* This , unsigned int unknown) { if (IsTransferStash(This, 2)) { // TODO: This is now dynamic.... DataItemPtr dataEvent(new DataItem(TYPE_InventorySack_Sort, 0, 0)); m_dataQueue->push(dataEvent); SetEvent(m_hEvent); } return dll_InventorySack_Sort(This, unknown); } int* __fastcall InventorySack_AddItem::Hooked_GameEngine_GetTransferSack(void* This , int idx ) { if (idx == STASH_PRIVATE || idx == STASH_1 || idx == STASH_2 || idx == STASH_3 || idx == STASH_4 || idx == STASH_5) { DataItemPtr dataEvent(new DataItem(TYPE_RequestRestrictedSack, sizeof(idx), (char*)&idx)); m_dataQueue->push(dataEvent); SetEvent(m_hEvent); } int* result = dll_GameEngine_GetTransferSack(This, idx); return result; }
36.977578
131
0.809362
[ "object" ]
b00fcffea670094e92479b26fa5b1f0067724394
1,119
cpp
C++
ccpca/cpca_wrap.cpp
takanori-fujiwara/ccpca
e2a2f57ca5d9ada00bf91892f7f5c4fa570d6110
[ "BSD-3-Clause" ]
14
2019-07-16T03:29:29.000Z
2022-02-19T14:59:11.000Z
ccpca/cpca_wrap.cpp
takanori-fujiwara/ccpca
e2a2f57ca5d9ada00bf91892f7f5c4fa570d6110
[ "BSD-3-Clause" ]
null
null
null
ccpca/cpca_wrap.cpp
takanori-fujiwara/ccpca
e2a2f57ca5d9ada00bf91892f7f5c4fa570d6110
[ "BSD-3-Clause" ]
7
2019-07-16T03:35:58.000Z
2022-01-30T05:41:07.000Z
#include "cpca.hpp" #include <pybind11/eigen.h> #include <pybind11/functional.h> #include <pybind11/pybind11.h> #include <pybind11/stl.h> namespace py = pybind11; PYBIND11_MODULE(cpca_cpp, m) { m.doc() = "cPCA wrapped with pybind11"; py::class_<CPCA>(m, "CPCA") .def(py::init<Eigen::Index const, bool const>()) .def("initialize", &CPCA::initialize) .def("fit", &CPCA::fit) .def("transform", &CPCA::transform) // .def("fit_transform", &CPCA::fitTransform) .def("best_alpha", &CPCA::bestAlpha) .def("update_components", &CPCA::updateComponents) .def("best_alpha", &CPCA::bestAlpha) .def("logspace", &CPCA::logspace) .def("get_components", &CPCA::getComponents) .def("get_component", &CPCA::getComponent) .def("get_eigenvalues", &CPCA::getEigenvalues) .def("get_eigenvalue", &CPCA::getEigenvalue) .def("get_loadings", &CPCA::getLoadings) .def("get_loading", &CPCA::getLoading) .def("get_current_fg", &CPCA::getCurrentFg) .def("get_best_alpha", &CPCA::getBestAlpha) .def("get_reports", &CPCA::getReports); }
34.96875
56
0.647006
[ "transform" ]
b0117278bc5834e2bb1fb01ab4b51ca94df2cd16
3,546
hpp
C++
libs/ml/include/ml/ops/divide.hpp
ejfitzgerald/ledger
01d1802220329aa348daaf4abfd502c6cc0d9f44
[ "Apache-2.0" ]
null
null
null
libs/ml/include/ml/ops/divide.hpp
ejfitzgerald/ledger
01d1802220329aa348daaf4abfd502c6cc0d9f44
[ "Apache-2.0" ]
null
null
null
libs/ml/include/ml/ops/divide.hpp
ejfitzgerald/ledger
01d1802220329aa348daaf4abfd502c6cc0d9f44
[ "Apache-2.0" ]
2
2019-11-13T10:55:24.000Z
2019-11-13T11:37:09.000Z
#pragma once //------------------------------------------------------------------------------ // // Copyright 2018-2019 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 "math/fundamental_operators.hpp" #include "ml/ops/ops.hpp" namespace fetch { namespace ml { namespace ops { template <class T> class Divide : public fetch::ml::Ops<T> { public: using ArrayType = T; using SizeType = typename ArrayType::SizeType; using ArrayPtrType = std::shared_ptr<ArrayType>; using VecTensorType = typename Ops<T>::VecTensorType; using DataType = typename T::Type; Divide() = default; virtual ~Divide() = default; /** * elementwise division * @param inputs left & right inputs to Divide * @return */ virtual void Forward(VecTensorType const &inputs, ArrayType &output) { assert(inputs.size() == 2); assert(inputs.at(0).get().shape() == output.shape()); if (inputs.at(1).get().size() > 1) { // array / array fetch::math::Divide(inputs.at(0).get(), inputs.at(1).get(), output); } else { // array / scalar fetch::math::Divide(inputs.at(0).get(), *(inputs.at(1).get().cbegin()), output); } } /** * f'(a)=(1/b)*err * f'(b)=-(a/(b^2))*err */ virtual std::vector<ArrayType> Backward(VecTensorType const &inputs, ArrayType const & error_signal) { ArrayType return_signal_1(inputs.at(0).get().shape()); ArrayType return_signal_2(inputs.at(1).get().shape()); auto a_it = inputs.at(0).get().cbegin(); auto b_it = inputs.at(1).get().cbegin(); auto err_it = error_signal.cbegin(); auto r_1_it = return_signal_1.begin(); auto r_2_it = return_signal_2.begin(); if (inputs.at(0).get().shape() == inputs.at(1).get().shape()) { // array / array same shape while (a_it.is_valid()) { *r_1_it = (*err_it) / (*b_it); *r_2_it = -((*err_it) * (*a_it)) / ((*b_it) * (*b_it)); ++a_it; ++b_it; ++err_it; ++r_1_it; ++r_2_it; } } else if (inputs.at(1).get().size() == 1) { // array / scalar while (a_it.is_valid()) { *r_1_it = (*err_it) / (*b_it); *r_2_it += -((*err_it) * (*a_it)) / ((*b_it) * (*b_it)); ++a_it; ++err_it; ++r_1_it; } } else { // array / array different shape // TODO (#1380) Write backpropagation for array array division of different shapes throw std::runtime_error("array array division of different shapes is not yet handled"); } return {return_signal_1, return_signal_2}; } virtual std::vector<SizeType> ComputeOutputShape(VecTensorType const &inputs) const { return inputs.front().get().shape(); } static constexpr char const *DESCRIPTOR = "Divide"; }; } // namespace ops } // namespace ml } // namespace fetch
29.55
94
0.573886
[ "shape", "vector" ]
b015a5ae5bc1fa09506772a66e375a7ae4a6ca7e
3,871
cpp
C++
application/src/UISystem.cpp
ChaosPaladin/l2mapconv-public
3d2c8074b0e6a9541dfdc55360bc7958f628cc39
[ "MIT" ]
42
2020-10-31T12:44:52.000Z
2022-03-06T08:27:24.000Z
application/src/UISystem.cpp
ChaosPaladin/l2mapconv-public
3d2c8074b0e6a9541dfdc55360bc7958f628cc39
[ "MIT" ]
10
2020-11-19T00:06:24.000Z
2021-12-20T18:54:47.000Z
application/src/UISystem.cpp
ChaosPaladin/l2mapconv-public
3d2c8074b0e6a9541dfdc55360bc7958f628cc39
[ "MIT" ]
28
2020-09-21T12:59:13.000Z
2022-03-12T04:53:37.000Z
#include "pch.h" #include "UISystem.h" UISystem::UISystem(UIContext &ui_context, WindowContext &window_context, RenderingContext &rendering_context) : m_ui_context{ui_context}, m_window_context{window_context}, m_rendering_context{rendering_context} { ASSERT(m_window_context.window_handle != nullptr, "App", "Window must be initialized"); IMGUI_CHECKVERSION(); ImGui::CreateContext(); ImGui_ImplGlfw_InitForOpenGL(m_window_context.window_handle, true); ImGui_ImplOpenGL3_Init(); ImGui::StyleColorsDark(); // Default rendering settings. m_ui_context.rendering.culling = true; m_ui_context.rendering.terrain = true; m_ui_context.rendering.static_meshes = true; m_ui_context.rendering.csg = true; m_ui_context.rendering.exported_geodata = true; // Default geodata settings. m_ui_context.geodata.set_defaults(); } UISystem::~UISystem() { ImGui_ImplOpenGL3_Shutdown(); ImGui_ImplGlfw_Shutdown(); ImGui::DestroyContext(); } void UISystem::frame_begin(Timestep frame_time) { ImGui_ImplOpenGL3_NewFrame(); ImGui_ImplGlfw_NewFrame(); ImGui::NewFrame(); rendering_window(frame_time); geodata_window(); } void UISystem::frame_end(Timestep /*frame_time*/) { ImGui::Render(); ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData()); } void UISystem::rendering_window(Timestep frame_time) const { if (m_window_context.keyboard.m) { m_ui_context.rendering.wireframe = !m_ui_context.rendering.wireframe; } const auto &camera_position = m_rendering_context.camera.position(); ImGui::Begin("Rendering", nullptr, ImGuiWindowFlags_AlwaysAutoResize); ImGui::Text("CPU frame time: %f", frame_time.seconds()); ImGui::Text("Draws: %d", m_ui_context.rendering.draws); ImGui::Text("Camera"); ImGui::Text("\tx: %d", static_cast<int>(camera_position.x)); ImGui::Text("\ty: %d", static_cast<int>(camera_position.y)); ImGui::Text("\tz: %d", static_cast<int>(camera_position.z)); ImGui::Checkbox("Culling", &m_ui_context.rendering.culling); ImGui::Checkbox("Wireframe", &m_ui_context.rendering.wireframe); ImGui::Checkbox("Passable", &m_ui_context.rendering.passable); ImGui::Checkbox("Terrain", &m_ui_context.rendering.terrain); ImGui::Checkbox("Static Meshes", &m_ui_context.rendering.static_meshes); ImGui::Checkbox("CSG", &m_ui_context.rendering.csg); ImGui::Checkbox("Bounding Boxes", &m_ui_context.rendering.bounding_boxes); ImGui::Checkbox("Imported Geodata", &m_ui_context.rendering.imported_geodata); ImGui::Checkbox("Exported Geodata", &m_ui_context.rendering.exported_geodata); ImGui::End(); } void UISystem::geodata_window() const { ImGui::Begin("Geodata", nullptr, ImGuiWindowFlags_AlwaysAutoResize); ImGui::PushItemWidth(50); ImGui::InputFloat("Cell Size", &m_ui_context.geodata.cell_size); ImGui::InputFloat("Cell Height", &m_ui_context.geodata.cell_height); ImGui::InputFloat("Walkable Height", &m_ui_context.geodata.walkable_height); ImGui::InputFloat("Wall Angle", &m_ui_context.geodata.wall_angle); ImGui::InputFloat("Walkable Angle", &m_ui_context.geodata.walkable_angle); ImGui::InputFloat("Min Walkable Climb", &m_ui_context.geodata.min_walkable_climb); ImGui::InputFloat("Max Walkable Climb", &m_ui_context.geodata.max_walkable_climb); if (ImGui::Button("Reset")) { m_ui_context.geodata.set_defaults(); ASSERT(m_ui_context.geodata.build_handler, "App", "Geodata build handler must be defined"); m_ui_context.geodata.build_handler(); } ImGui::SameLine(); if (ImGui::Button("Build")) { ASSERT(m_ui_context.geodata.build_handler, "App", "Geodata build handler must be defined"); m_ui_context.geodata.build_handler(); } ImGui::SameLine(); ImGui::Checkbox("Export", &m_ui_context.geodata.export_); ImGui::End(); }
33.95614
80
0.734694
[ "render" ]
b021890427ae0531fa77759b7d56c715bfca8124
2,222
cpp
C++
src/main.cpp
sstsai/llell
7722e1460964fb008406d480fde017a66b1f387d
[ "BSL-1.0" ]
null
null
null
src/main.cpp
sstsai/llell
7722e1460964fb008406d480fde017a66b1f387d
[ "BSL-1.0" ]
null
null
null
src/main.cpp
sstsai/llell
7722e1460964fb008406d480fde017a66b1f387d
[ "BSL-1.0" ]
null
null
null
#include "filedialog.h" #include "image.h" #include "imgui_.h" #include "glfw.h" #include "opengl.h" #include "co.h" #include <glbinding/glbinding.h> int main(int, char *av[]) { auto main_win = glfw::make_window(1280, 720, "Main", nullptr, nullptr, glfw::attrib::context_version_major{3}, glfw::attrib::context_version_minor{2}, glfw::attrib::opengl_profile{ glfw::attrib::opengl_profiles::core}, glfw::attrib::opengl_forward_compat{true}) .value(); glfwMakeContextCurrent(main_win.get()); glbinding::initialize(glfwGetProcAddress); using namespace imgui; auto imgui_ctx = glfw_opengl(main_win.get()); gl::glClearColor(.7f, .3f, .5f, 1.f); auto url = std::array<char, 256>(); auto texture = opengl::texture(); while (!glfwWindowShouldClose(main_win.get())) { gl::glClear(gl::GL_COLOR_BUFFER_BIT); imgui_ctx.render([&]() { ImGui::GetBackgroundDrawList(ImGui::GetMainViewport()) ->AddImage((void *)(intptr_t)(gl::GLuint)texture.get(), ImGui::GetMainViewport()->WorkPos, ImVec2(ImGui::GetMainViewport()->WorkPos.x + ImGui::GetMainViewport()->WorkSize.x, ImGui::GetMainViewport()->WorkPos.y + ImGui::GetMainViewport()->WorkSize.y)); ImGui::InputText("url", url.data(), url.size()); if (ImGui::Button("open")) { auto img = image::get(std::string_view(url.data())); if (img) { gl::glBindTexture(gl::GL_TEXTURE_2D, (gl::GLuint)texture.get()); image::glimage(boost::gil::view(*img)); } } static bool show = false; if (show) { ImGui::ShowDemoWindow(&show); ImPlot::ShowDemoWindow(&show); } }); glfwPollEvents(); } }
40.4
80
0.489199
[ "render" ]
b026a11247ad6ed5148d431dcae71b308a2d210f
2,047
cpp
C++
src/poe/searchmanager.cpp
azais-corentin/StillSane
5cafa1aad4964d042879ee14d80ddef71bd9f8e4
[ "MIT" ]
1
2022-03-15T18:07:37.000Z
2022-03-15T18:07:37.000Z
src/poe/searchmanager.cpp
azais-corentin/StillSane
5cafa1aad4964d042879ee14d80ddef71bd9f8e4
[ "MIT" ]
null
null
null
src/poe/searchmanager.cpp
azais-corentin/StillSane
5cafa1aad4964d042879ee14d80ddef71bd9f8e4
[ "MIT" ]
1
2022-03-20T16:09:28.000Z
2022-03-20T16:09:28.000Z
#include "searchmanager.hh" #include "api/constants.hh" #include "api/trade.hh" namespace StillSane::Poe { SearchManager::SearchManager(QObject* parent) : QObject(parent) {} SearchManager::~SearchManager() { qDeleteAll(mTradeApis); } void SearchManager::setCookies(const QString& POESESSID) { mPOESESSID = POESESSID; Network::AccessManager::setPOESESSID(POESESSID); } void SearchManager::addSearch(const QString& id, const QString& league, const QString& name, bool enabled) { // Create a new live Trade Api::Trade* trade = new Api::Trade{}; trade->setId(id); trade->setName(name); trade->setLeague(league); trade->setEnabled(enabled); // Add it to the vector mTradeApis.push_back(trade); // Connect signals and start the live search connectToTradeApi(trade); if (enabled) trade->openLiveSearch(); emit searchAdded(); } bool SearchManager::editSearch(const QString& id, const QString& name) { auto it = std::find_if(mTradeApis.begin(), mTradeApis.end(), [&id](Api::Trade* trade) { return trade->getId() == id; }); if (it != mTradeApis.end()) { (*it)->setName(name); return true; } return false; } bool SearchManager::editSearch(const QString& id, const bool& enabled) { auto it = std::find_if(mTradeApis.begin(), mTradeApis.end(), [&id](Api::Trade* trade) { return trade->getId() == id; }); if (it != mTradeApis.end()) { (*it)->setEnabled(enabled); return true; } return false; } QVector<Api::Trade*>& SearchManager::getSearches() { return mTradeApis; } void SearchManager::connectToTradeApi(Api::Trade* trade) { connect(trade, &Api::Trade::itemReceived, [&](const Api::TradeItem&) { /*onItemReceived(trade, item);*/ }); } void SearchManager::onItemReceived(size_t index, const Api::TradeItem& item) { qDebug() << "trade[" << index << "] result:" << item.text; } } // namespace StillSane::Poe
25.271605
84
0.629702
[ "vector" ]
b033b5abc1e2fc848e4e3ef006916fa9d7d29eb5
617
hpp
C++
include/bencode/decoder/decoder.hpp
vt4a2h/bencode
fbca367d38dfc291fc1f55eae54b08fb574a5107
[ "MIT" ]
2
2022-01-04T20:22:20.000Z
2022-01-05T07:40:19.000Z
include/bencode/decoder/decoder.hpp
vt4a2h/bencode
fbca367d38dfc291fc1f55eae54b08fb574a5107
[ "MIT" ]
null
null
null
include/bencode/decoder/decoder.hpp
vt4a2h/bencode
fbca367d38dfc291fc1f55eae54b08fb574a5107
[ "MIT" ]
null
null
null
// // MIT License // // Copyright (c) 2022-present Vitaly Fanaskov // // bencode -- A simple library for decoding bencoded data // Project home: https://github.com/vt4a2h/bencode // // See LICENSE file for the further details. // #pragma once #include <bencode/element/element.hpp> #include <bencode/result/expected.hpp> #include <bencode/element/types.hpp> namespace bencode { //! Decode \p input. //! \note \p input is a view. Object it refers to should live long enough. //! \return vector of elements or \p DecodingError. [[nodiscard]] Expected<Elements> decode(std::string_view input); } // namespace bencode
24.68
74
0.724473
[ "object", "vector" ]
b041c2190ffc2351c6ec9ffaca87354cfba35730
5,222
cpp
C++
test/src/Digest_00.cpp
ahfakt/StreamSecurity
65af4565489ea5f5e8b382c3b55dd7f22988d866
[ "MIT" ]
null
null
null
test/src/Digest_00.cpp
ahfakt/StreamSecurity
65af4565489ea5f5e8b382c3b55dd7f22988d866
[ "MIT" ]
null
null
null
test/src/Digest_00.cpp
ahfakt/StreamSecurity
65af4565489ea5f5e8b382c3b55dd7f22988d866
[ "MIT" ]
null
null
null
#include <cassert> #include <Stream/File.h> #include <Stream/Buffer.h> #include <StreamSecurity/Digest.h> #include <openssl/rand.h> #include <openssl/err.h> #include "Util.h" #define Expect1(x) if (1 != x) throw std::runtime_error(ERR_error_string(ERR_peek_last_error(), nullptr)) std::vector<std::byte> testOutputHash(std::string const& fileName, EVP_MD const* md, int length, int maxChunkLength) { std::vector<std::byte> outputData = StreamTest::Util::GetRandomBytes<std::chrono::minutes>(length); IO::File io(fileName, IO::File::Mode::W); Stream::FileOutput file; Stream::BufferOutput buffer(io.getBlockSize()); Stream::Security::DigestOutput digestOutput(md); io << file << buffer << digestOutput; StreamTest::Util::WriteRandomChunks(digestOutput, outputData, std::uniform_int_distribution<int> {1, maxChunkLength}); auto outputDigest = digestOutput.getOutputDigest(); assert(Stream::Security::Digest::Matches(outputDigest, Stream::Security::Digest::Compute(outputData.data(), outputData.size(), md))); return outputDigest; } std::vector<std::byte> testOutputHMAC(std::string const& fileName, EVP_MD const* md, Stream::Security::Key const& key, int length, int maxChunkLength) { std::vector<std::byte> outputData = StreamTest::Util::GetRandomBytes<std::chrono::minutes>(length); IO::File io(fileName, IO::File::Mode::W); Stream::FileOutput file; Stream::BufferOutput buffer(io.getBlockSize()); Stream::Security::DigestOutput digestOutput(md, key); io << file << buffer << digestOutput; StreamTest::Util::WriteRandomChunks(digestOutput, outputData, std::uniform_int_distribution<int> {1, maxChunkLength}); auto outputDigest = digestOutput.getOutputDigest(); assert(Stream::Security::Digest::Matches(outputDigest, Stream::Security::Digest::Compute(outputData.data(), outputData.size(), md, key))); return outputDigest; } std::vector<std::byte> testInputHash(std::string const& fileName, EVP_MD const* md, int length, int maxChunkLength) { std::vector<std::byte> inputData; inputData.resize(length); IO::File io(fileName, IO::File::Mode::R); Stream::FileInput file; Stream::BufferInput buffer(io.getBlockSize()); Stream::Security::DigestInput digestInput(md); io >> file >> buffer >> digestInput; StreamTest::Util::ReadRandomChunks(digestInput, inputData, std::uniform_int_distribution<int> {1, maxChunkLength}); auto inputDigest = digestInput.getInputDigest(); assert(Stream::Security::Digest::Matches(inputDigest, Stream::Security::Digest::Compute(inputData.data(), inputData.size(), md))); return inputDigest; } std::vector<std::byte> testInputHMAC(std::string const& fileName, EVP_MD const* md, Stream::Security::Key const& key, int length, int maxChunkLength) { std::vector<std::byte> inputData; inputData.resize(length); IO::File io(fileName, IO::File::Mode::R); Stream::FileInput file; Stream::BufferInput buffer(io.getBlockSize()); Stream::Security::DigestInput digestInput(md, key); io >> file >> buffer >> digestInput; StreamTest::Util::ReadRandomChunks(digestInput, inputData, std::uniform_int_distribution<int> {1, maxChunkLength}); auto inputDigest = digestInput.getInputDigest(); assert(Stream::Security::Digest::Matches(inputDigest, Stream::Security::Digest::Compute(inputData.data(), inputData.size(), md, key))); return inputDigest; } void testHash(std::string const& fileName, EVP_MD const* md, int length, int maxChunkLength) { auto outputDigest = testOutputHash(fileName, md, length, maxChunkLength); auto inputDigest = testInputHash(fileName, md, length, maxChunkLength); assert(Stream::Security::Digest::Matches(outputDigest, inputDigest)); } void testHMAC(std::string const& fileName, EVP_MD const* md, Stream::Security::Key const& key, int length, int maxChunkLength) { auto outputHMAC = testOutputHMAC(fileName, md, key, length, maxChunkLength); auto inputHMAC = testInputHMAC(fileName, md, key, length, maxChunkLength); assert(Stream::Security::Digest::Matches(outputHMAC, inputHMAC)); } void testCMAC(std::string const& fileName, Stream::Security::Key const& key, int length, int maxChunkLength) { auto outputCMAC = testOutputHMAC(fileName, nullptr, key, length, maxChunkLength); auto inputCMAC = testInputHMAC(fileName, nullptr, key, length, maxChunkLength); assert(Stream::Security::Digest::Matches(outputCMAC, inputCMAC)); } int main() { std::random_device rd; std::mt19937 gen(rd()); int length = 1024*64; int maxChunkLength = 256; length += std::uniform_int_distribution<int>{1, 5}(gen); testHash("sha256.hash", EVP_sha256(), length, maxChunkLength); int hKeyLength = EVP_MD_size(EVP_sha256()); Stream::Security::SecureMemory hKeyRaw(new unsigned char[hKeyLength], hKeyLength); Expect1(RAND_priv_bytes(hKeyRaw.get(), hKeyLength)); Stream::Security::Key const hkey(hKeyRaw); testHMAC("sha256.hmac", EVP_sha256(), hkey, length, maxChunkLength); int cKeyLength = EVP_CIPHER_key_length(EVP_aes_256_cbc()); Stream::Security::SecureMemory cKeyRaw(new unsigned char[cKeyLength], cKeyLength); Expect1(RAND_priv_bytes(hKeyRaw.get(), cKeyLength)); Stream::Security::Key const ckey(cKeyRaw, EVP_aes_256_cbc()); testCMAC("sha256.cmac", ckey, length, maxChunkLength); return 0; }
36.774648
127
0.750862
[ "vector" ]
b047b1f86af2a6ab2583a6a443d0edc11a4b0d71
1,403
cpp
C++
src/signedDistance.cpp
AntonKrug/raymarcher
dd51fd9181e9430525c96bade1444347a6c37902
[ "MIT" ]
null
null
null
src/signedDistance.cpp
AntonKrug/raymarcher
dd51fd9181e9430525c96bade1444347a6c37902
[ "MIT" ]
null
null
null
src/signedDistance.cpp
AntonKrug/raymarcher
dd51fd9181e9430525c96bade1444347a6c37902
[ "MIT" ]
null
null
null
// // Created by anton.krug@gmail.com on 27/12/21. // License: MIT // #include "signedDistance.h" namespace signedDistance { float box(vector point, vector size) { vector distance = point.abs() - size; float externalDistance = distance.max(0.0f).length(); float internalDistance = helper::minf(0.0f, helper::maxf(distance.x, distance.y, distance.z)); return externalDistance + internalDistance; } float mhcpLogoCylinder(vector point) { point.z += helper::clamp(point.z, 0.0f, -0.35f); // hardcoded line segment distance float distance = point.length() - 1.8f; // make it into capsule by using the sphere calculation return helper::maxf(distance, -point.z - 0.25f, point.z); // flatten ends with planes to make a cylinder } float capsule(vector point, vector a, vector b, const float radius) { vector ab = b - a; vector ap = point - a; float percentage = helper::clamp(ap.dotProduct(ab) / ab.dotProduct(), 0.0f, 1.0f); vector close = a + ab * percentage; return (close - point).length() - radius; } float capsuleDelta(vector point, vector a, vector ab, const float radius) { vector ap = point - a; float percentage = helper::clamp(ap.dotProduct(ab) / ab.dotProduct(), 0.0f, 1.0f); vector close = a + ab * percentage; return (close - point).length() - radius; } };
29.229167
117
0.642195
[ "vector" ]
b0487559ab5216a2da562918309c13b7d18c44d2
15,236
cpp
C++
Source/Editor/Editor.tests.cpp
JPMMaia/H
c99b03e38b3d7ef1f9c048e13cf9156a5697ad7b
[ "MIT" ]
null
null
null
Source/Editor/Editor.tests.cpp
JPMMaia/H
c99b03e38b3d7ef1f9c048e13cf9156a5697ad7b
[ "MIT" ]
null
null
null
Source/Editor/Editor.tests.cpp
JPMMaia/H
c99b03e38b3d7ef1f9c048e13cf9156a5697ad7b
[ "MIT" ]
null
null
null
#define CATCH_CONFIG_MAIN #define CATCH_CONFIG_ENABLE_ALL_STRINGMAKERS #include <catch2/catch.hpp> import h.core; import h.editor; namespace h::editor { TEST_CASE("Create code format segment") { Code_format_segment const format_segment = create_code_format_segment("${return_type} ${function_name}(${function_parameters});", {}, {}); REQUIRE(format_segment.types.size() == 6); REQUIRE(format_segment.keywords.size() == 3); REQUIRE(format_segment.strings.size() == 3); REQUIRE(format_segment.types[0] == Code_format_segment::Type::Keyword); CHECK(format_segment.keywords[0] == Code_format_keyword::Return_type); REQUIRE(format_segment.types[1] == Code_format_segment::Type::String); CHECK(format_segment.strings[0] == " "); REQUIRE(format_segment.types[2] == Code_format_segment::Type::Keyword); CHECK(format_segment.keywords[1] == Code_format_keyword::Function_name); REQUIRE(format_segment.types[3] == Code_format_segment::Type::String); CHECK(format_segment.strings[1] == "("); REQUIRE(format_segment.types[4] == Code_format_segment::Type::Keyword); CHECK(format_segment.keywords[2] == Code_format_keyword::Function_parameters); REQUIRE(format_segment.types[5] == Code_format_segment::Type::String); CHECK(format_segment.strings[2] == ");"); } TEST_CASE("Create type reference template") { Code_format_segment const format = create_code_format_segment( "${type_name}", {}, {} ); HTML_template const actual = create_template( "h_type_reference", format, {}, {} ); char const* const expected = "<template id=\"h_type_reference\">" "<slot name=\"type_name\"></slot>" "</template>"; CHECK(actual.value == expected); } TEST_CASE("Create function parameters template with style 0") { Code_format_segment const format = create_code_format_segment("${parameter_type} ${parameter_name}", {}, {}); HTML_template const actual = create_template( "h_function_parameter", format, {}, {} ); char const* const expected = "<template id=\"h_function_parameter\">" "<h_type_reference><span slot=\"type_name\"><slot name=\"type\"></slot></span></h_type_reference>" " " "<slot name=\"name\"></slot>" "</template>"; CHECK(actual.value == expected); } TEST_CASE("Create function parameters template with style 1") { Code_format_segment const format = create_code_format_segment("${parameter_name}: ${parameter_type}", {}, {}); HTML_template const actual = create_template( "h_function_parameter", format, {}, {} ); char const* const expected = "<template id=\"h_function_parameter\">" "<slot name=\"name\"></slot>" ": " "<h_type_reference><span slot=\"type_name\"><slot name=\"type\"></slot></span></h_type_reference>" "</template>"; CHECK(actual.value == expected); } TEST_CASE("Create function declaration template with style 0") { Code_format_segment const format = create_code_format_segment("${return_type} ${function_name}(${function_parameters})", {}, {}); HTML_template const actual = create_template( "h_function_declaration", format, {}, {} ); char const* const expected = "<template id=\"h_function_declaration\">" "<h_type_reference><span slot=\"type_name\"><slot name=\"return_type\"></slot></span></h_type_reference>" " " "<slot name=\"name\"></slot>" "(" "<slot name=\"parameters\"></slot>" ")" "</template>"; CHECK(actual.value == expected); } TEST_CASE("Create function declaration template with style 1") { Code_format_segment const format = create_code_format_segment("function ${function_name}(${function_parameters}) -> ${return_type}", {}, {}); HTML_template const actual = create_template( "h_function_declaration", format, {}, {} ); char const* const expected = "<template id=\"h_function_declaration\">" "function" " " "<slot name=\"name\"></slot>" "(" "<slot name=\"parameters\"></slot>" ")" " -> " "<h_type_reference><span slot=\"type_name\"><slot name=\"return_type\"></slot></span></h_type_reference>" "</template>"; CHECK(actual.value == expected); } h::Function_declaration create_function_declaration() { std::pmr::vector<Type_reference> parameter_types { Type_reference{.data = Fundamental_type::Int32}, Type_reference{.data = Fundamental_type::Int32}, }; std::pmr::vector<std::uint64_t> parameter_ids { 0, 1 }; std::pmr::vector<std::pmr::string> parameter_names { "lhs", "rhs" }; return h::Function_declaration { .name = "add", .return_type = Type_reference{.data = Fundamental_type::Int32}, .parameter_types = std::move(parameter_types), .parameter_ids = std::move(parameter_ids), .parameter_names = std::move(parameter_names), .linkage = Linkage::External }; } TEST_CASE("Create function declaration template instance") { h::Function_declaration const function_declaration = create_function_declaration(); Fundamental_type_name_map const fundamental_type_name_map = create_default_fundamental_type_name_map( {} ); Function_format_options const options { .parameter_separator = ", " }; HTML_template_instance const actual = create_function_declaration_instance( function_declaration, fundamental_type_name_map, options, {}, {} ); char const* const expected = "<h_function_declaration>" "<span slot=\"name\">add</span>" "<span slot=\"return_type\">Int32</span>" "<span slot=\"parameters\">" "<h_function_parameter>" "<span slot=\"type\">Int32</span>" "<span slot=\"name\">lhs</span>" "</h_function_parameter>" ", " "<h_function_parameter>" "<span slot=\"type\">Int32</span>" "<span slot=\"name\">rhs</span>" "</h_function_parameter>" "</span>" "</h_function_declaration>"; CHECK(actual.value == expected); } TEST_CASE("Create constant expression template with style 0") { Code_format_segment const format = create_code_format_segment("${constant_type}${constant_value}", {}, {}); HTML_template const actual = create_template( "h_constant_expression", format, {}, {} ); char const* const expected = "<template id=\"h_constant_expression\">" "<h_type_reference><span slot=\"type_name\"><slot name=\"type\"></slot></span></h_type_reference>" "<slot name=\"value\"></slot>" "</template>"; CHECK(actual.value == expected); } TEST_CASE("Create constant expression template instance") { h::Constant_expression const expression = { .type = Fundamental_type::Float16, .data = "0.5" }; Fundamental_type_name_map const fundamental_type_name_map = create_default_fundamental_type_name_map( {} ); HTML_template_instance const actual = create_constant_expression_instance( expression, fundamental_type_name_map, {}, {} ); char const* const expected = "<h_constant_expression>" "<span slot=\"type\">Float16</span>" "<span slot=\"value\">0.5</span>" "</h_constant_expression>"; CHECK(actual.value == expected); } TEST_CASE("Create return expression template with style 0") { Code_format_segment const format = create_code_format_segment("return ${expression}", {}, {}); HTML_template const actual = create_template( "h_return_expression", format, {}, {} ); char const* const expected = "<template id=\"h_return_expression\">" "return " "<h_expression><slot name=\"expression\"></slot></h_expression>" "</template>"; CHECK(actual.value == expected); } TEST_CASE("Create variable expression template with style 0") { Code_format_segment const format = create_code_format_segment("${variable_name}", {}, {}); HTML_template const actual = create_template( "h_variable_expression", format, {}, {} ); char const* const expected = "<template id=\"h_variable_expression\">" "<slot name=\"type\"></slot>" "<slot name=\"id\"></slot>" "<slot name=\"temporary\"></slot>" "</template>"; CHECK(actual.value == expected); } TEST_CASE("Create function argument variable expression template instance") { h::Variable_expression const expression { .type = Variable_expression_type::Function_argument, .id = 1 }; Fundamental_type_name_map const fundamental_type_name_map = create_default_fundamental_type_name_map( {} ); HTML_template_instance const actual = create_variable_expression_instance( expression, std::nullopt, fundamental_type_name_map, {}, {} ); char const* const expected = "<h_variable_expression>" "<span slot=\"type\">function_argument</span>" "<span slot=\"id\">1</span>" "</h_variable_expression>"; CHECK(actual.value == expected); } TEST_CASE("Create temporary variable expression template instance") { HTML_template_instance const temporary_expression { .value = "<temporary_expression></temporary_expression>" }; h::Variable_expression const expression { .type = Variable_expression_type::Temporary, .id = 1 }; Fundamental_type_name_map const fundamental_type_name_map = create_default_fundamental_type_name_map( {} ); HTML_template_instance const actual = create_variable_expression_instance( expression, temporary_expression, fundamental_type_name_map, {}, {} ); char const* const expected = "<h_variable_expression>" "<span slot=\"type\">temporary</span>" "<span slot=\"id\">1</span>" "<span slot=\"temporary\">" "<temporary_expression></temporary_expression>" "</span>" "</h_variable_expression>"; CHECK(actual.value == expected); } TEST_CASE("Create statement expression template with style 0") { Code_format_segment const format = create_code_format_segment("${statement};", {}, {}); HTML_template const actual = create_template( "h_statement", format, {}, {} ); char const* const expected = "<template id=\"h_statement\">" "<slot name=\"id\"></slot>" "<slot name=\"name\"></slot>" "<slot name=\"expression\"></slot>" ";" "</template>"; CHECK(actual.value == expected); } namespace { h::Statement create_statement() { std::pmr::vector<h::Expression> expressions { { h::Expression{ .data = h::Binary_expression{ .left_hand_side = h::Variable_expression{ .type = h::Variable_expression_type::Function_argument, .id = 0 }, .right_hand_side = h::Variable_expression{ .type = h::Variable_expression_type::Function_argument, .id = 1 }, .operation = h::Binary_operation::Add } }, h::Expression{ .data = h::Return_expression{ .variable = h::Variable_expression{ .type = h::Variable_expression_type::Temporary, .id = 0 }, } } } }; return h::Statement { .id = 0, .name = "var_0", .expressions = std::move(expressions) }; } } TEST_CASE("Create statement template instance") { h::Statement const statement = create_statement(); Fundamental_type_name_map const fundamental_type_name_map = create_default_fundamental_type_name_map( {} ); HTML_template_instance const actual = create_statement_instance( statement, fundamental_type_name_map, {}, {} ); char const* const expected = "<h_statement>" "<span slot=\"id\">0</span>" "<span slot=\"name\">var_0</span>" "<span slot=\"expression\">" "<h_return_expression>" "<span slot=\"expression\">" "<h_binary_expression>" "<span slot=\"left_hand_side\">" "<h_variable_expression>" "<span slot=\"type\">function_argument</span>" "<span slot=\"id\">0</span>" "</h_variable_expression>" "</span>" "<span slot=\"right_hand_side\">" "<h_variable_expression>" "<span slot=\"type\">function_argument</span>" "<span slot=\"id\">1</span>" "</h_variable_expression>" "</span>" "<span slot=\"operation\">add</span>" "</h_binary_expression>" "</span>" "</h_return_expression>" "</span>" "</h_statement>"; CHECK(actual.value == expected); } }
31.414433
149
0.530454
[ "vector" ]
b04ae2566f205b6680008c4474edafc6a5402c82
1,608
cpp
C++
core/test/lib/libledger-test/MemPreferencesBackend.cpp
Manny27nyc/lib-ledger-core
fc9d762b83fc2b269d072b662065747a64ab2816
[ "MIT" ]
92
2016-11-13T01:28:34.000Z
2022-03-25T01:11:37.000Z
core/test/lib/libledger-test/MemPreferencesBackend.cpp
Manny27nyc/lib-ledger-core
fc9d762b83fc2b269d072b662065747a64ab2816
[ "MIT" ]
242
2016-11-28T11:13:09.000Z
2022-03-04T13:02:53.000Z
core/test/lib/libledger-test/MemPreferencesBackend.cpp
Manny27nyc/lib-ledger-core
fc9d762b83fc2b269d072b662065747a64ab2816
[ "MIT" ]
91
2017-06-20T10:35:28.000Z
2022-03-09T14:15:40.000Z
#include <MemPreferencesBackend.hpp> #include "utils/optional.hpp" namespace ledger { namespace core { namespace test { MemPreferencesBackend::~MemPreferencesBackend() {} std::experimental::optional<std::vector<uint8_t>> MemPreferencesBackend::get(const std::vector<uint8_t> & key) { if (_data.find(key) != _data.end()) return _data.at(key); return optional<std::vector<uint8_t>>(); } bool MemPreferencesBackend::commit(const std::vector<api::PreferencesChange> & changes) { for(const auto& change: changes) { _data[change.key] = change.value; } return true; } void MemPreferencesBackend::setEncryption(const std::shared_ptr<api::RandomNumberGenerator> & rng, const std::string & password) { } void MemPreferencesBackend::unsetEncryption() { } bool MemPreferencesBackend::resetEncryption(const std::shared_ptr<api::RandomNumberGenerator> & rng, const std::string & oldPassword, const std::string & newPassword) { return true; } std::string MemPreferencesBackend::getEncryptionSalt() { return ""; } void MemPreferencesBackend::clear() { _data.clear(); } } } }
29.777778
179
0.501866
[ "vector" ]
b04fd42c0954a1143c7e822d2e059ff4a2d503d9
2,440
cc
C++
test/run_tests.cc
t-dillon/tdoku
1668b02258c58b0647713d78e09a8ab101e13bd1
[ "BSD-2-Clause" ]
100
2019-07-01T20:16:33.000Z
2022-03-27T10:36:48.000Z
test/run_tests.cc
doc22940/tdoku
63d190a9090d9dc8e613e48e4770c635a5b7e3c3
[ "BSD-2-Clause" ]
7
2019-12-18T09:07:58.000Z
2022-03-13T19:39:46.000Z
test/run_tests.cc
doc22940/tdoku
63d190a9090d9dc8e613e48e4770c635a5b7e3c3
[ "BSD-2-Clause" ]
14
2019-06-18T05:47:28.000Z
2022-03-05T08:58:05.000Z
#include "../src/all_solvers.h" #include "../src/bitutil.h" #include <chrono> #include <cstdlib> #include <cstring> #include <fstream> #include <iostream> #include <memory> #include <sstream> #include <vector> using namespace std; void Run(const string &testdata_filename, const Solver &solver, bool verbose) { ifstream file; file.open(testdata_filename); if (file.fail()) { cout << "Error opening " << testdata_filename << endl; exit(1); } string line; bool fail = false; while (getline(file, line)) { stringstream ss(line); string puzzle, expect_str, solution; getline(ss, puzzle, ':'); getline(ss, expect_str, ':'); int expect = stoi(expect_str); if (expect > 0 && !solver.ReturnsCount()) expect = 1; if (expect > 1 && !solver.ReturnsFullCount()) expect = 2; char output[82]{}; size_t backtracks; size_t count = solver.Solve(puzzle.c_str(), 100000, output, &backtracks); bool this_fail = count != expect; if (this_fail || verbose) { cout << (this_fail ? "FAIL: " : "") << solver.Id() << "\n" << " puzzle: " << puzzle << "\n" << " expected: " << expect << "\n" << " observed: " << count << endl; } if (!this_fail && expect_str == "1" && solver.ReturnsSolution()) { getline(ss, solution, ':'); solver.Solve(puzzle.c_str(), 1, output, &backtracks); this_fail = strncmp(solution.c_str(), output, 81) != 0; if (this_fail || verbose) { cout << (this_fail ? "FAIL: " : "") << solver.Id() << "\n" << " puzzle: " << puzzle << "\n" << " expected: " << solution << "\n" << " observed: " << output << endl; } } fail |= this_fail; } file.close(); if (!fail) cout << "PASS: " << solver.Id() << endl; } int main(int argc, char **argv) { bool verbose = false; string testdata_filename = "test/test_puzzles"; for (int i = 1; i < argc; i++) { if (strcmp(argv[i], "-v") == 0) { verbose = true; } else { testdata_filename = argv[1]; } } auto solvers = GetAllSolvers(); for (auto &solver : solvers) { Run(testdata_filename, solver, verbose); } }
31.282051
81
0.504918
[ "vector" ]
b053897c167b135a91ee1a05d9b775920df1341c
1,056
cpp
C++
src/value.cpp
akhleung/vole
358bd7a84d245e89b3ae47d369c19b3fff2f8a75
[ "MIT" ]
null
null
null
src/value.cpp
akhleung/vole
358bd7a84d245e89b3ae47d369c19b3fff2f8a75
[ "MIT" ]
null
null
null
src/value.cpp
akhleung/vole
358bd7a84d245e89b3ae47d369c19b3fff2f8a75
[ "MIT" ]
null
null
null
#include "value.hpp" namespace Vole { Value::Content::Content() { } Value::Content::Content(bool b) : boolean(b) { } Value::Content::Content(double d) : number(d) { } Value::Content::Content(Symbol s) : symbol(s) { } Value::Content::Content(String s) : string(s) { } Value::Content::Content(Vector v) : vector(v) { } Value::Content::Content(Function f) : function(f) { } Value::Content::Content(char c) : color(c) { } Value::Value() : type(UNDEFINED) { } Value::Value(bool b) : type(BOOLEAN), content(b) { } Value::Value(double d) : type(NUMBER), content(d) { } Value::Value(Symbol s) : type(SYMBOL), content(s) { } Value::Value(String s) : type(STRING), content(s) { } Value::Value(Vector v) : type(VECTOR), content(v) { } Value::Value(Function f) : type(FUNCTION), content(f) { } Value::Value(char c) : type(COLOR), content(c) { } Value::operator bool() { return !((type == BOOLEAN) && !content.boolean); } }
39.111111
59
0.5625
[ "vector" ]
b063aee643b7cceda304761e0d0ed035ef0c25e5
33,510
cpp
C++
sources/Service/TexServiceImplementation.cpp
palchukovsky/TunnelEx
ec645271ab8b79225e378345ff108795110c57de
[ "Apache-2.0" ]
null
null
null
sources/Service/TexServiceImplementation.cpp
palchukovsky/TunnelEx
ec645271ab8b79225e378345ff108795110c57de
[ "Apache-2.0" ]
null
null
null
sources/Service/TexServiceImplementation.cpp
palchukovsky/TunnelEx
ec645271ab8b79225e378345ff108795110c57de
[ "Apache-2.0" ]
null
null
null
/************************************************************************** * Created: 2008/02/17 5:31 * Author: Eugene V. Palchukovsky * E-mail: eugene@palchukovsky.com * ------------------------------------------------------------------- * Project: TunnelEx * URL: http://tunnelex.net **************************************************************************/ #include "Prec.h" #include "TexServiceImplementation.hpp" #include "Licensing.hpp" #include "ServiceControl/Configuration.hpp" #include "Legacy/LegacySupporter.hpp" #include "Modules/Upnp/Client.hpp" #include "ServiceFilesSecurity.hpp" #include "Core/Server.hpp" #include "Core/SslCertificatesStorage.hpp" #include "Core/LicenseState.hpp" #include "Core/Rule.hpp" #include "Core/Log.hpp" #include "Core/Exceptions.hpp" namespace fs = boost::filesystem; namespace ps = boost::posix_time; using namespace TunnelEx; using namespace TunnelEx::Helpers; using namespace TunnelEx::Helpers::Crypto; ////////////////////////////////////////////////////////////////////////// class TexServiceImplementation::Implementation : private boost::noncopyable { public: Implementation() : m_stateRevision(0), m_ruleSetRevision(0), m_licenseKeyRevision(0), m_licenseKeyRevisionTimeDiff(0), m_logSize(0), m_errorCount(0), m_warnCount(0), m_isStarted(0), m_startTime(time(0)) { //...// } ~Implementation() throw() { //...// } void LoadRules() { std::wifstream rulesFile(m_rulesFilePath.c_str(), std::ios::binary | std::ios::in); if (!rulesFile) { Log::GetInstance().AppendDebug( "Could not find rule set file \"%1%\".", ConvertString<String>(m_rulesFilePath.c_str()).GetCStr()); SetRuleSet(std::auto_ptr<RuleSet>(new RuleSet)); return; } std::wostringstream rulesXml; rulesXml << rulesFile.rdbuf(); if (!rulesXml.str().empty()) { try { SetRuleSet( std::auto_ptr<RuleSet>(new RuleSet(rulesXml.str().c_str()))); } catch (const TunnelEx::XmlDoesNotMatchException &) { // rules xml file has wrong version std::auto_ptr<RuleSet> ruleSet(new RuleSet); LegacySupporter().MigrateCurrentRuleSet(*ruleSet); SetRuleSet(ruleSet); } } else { SetRuleSet(std::auto_ptr<RuleSet>(new RuleSet)); } } void SaveRules() const { try { const fs::wpath rulesFilePath(m_rulesFilePath); fs::create_directories(rulesFilePath.branch_path()); { std::wofstream rulesFile( rulesFilePath.string().c_str(), std::ios::binary | std::ios::out | std::ios::trunc); if (rulesFile) { WString rulesXml; m_ruleSet->GetXml(rulesXml); rulesFile << rulesXml.GetCStr(); } else { Format message("Could not open rule set file \"%1%\"."); message % ConvertString<String>(m_rulesFilePath.c_str()).GetCStr(); Log::GetInstance().AppendFatalError(message.str().c_str()); } } if (ServiceConfiguration::GetConfigurationFileDir() == rulesFilePath.branch_path()) { ServiceFilesSecurity::Set(rulesFilePath.branch_path()); } } catch (const boost::filesystem::filesystem_error &ex) { Format message("Could not create directory for rule set file: \"%1%\"."); message % ex.what(); Log::GetInstance().AppendSystemError(message.str().c_str()); } } ServiceConfiguration & GetConfiguration() { if (!m_conf.get()) { m_conf = LoadConfiguration(); } return *m_conf; } SslCertificatesStorage & GetSslCertificatesStorage() { if (!m_sslCertificatesStorage.get()) { std::vector<unsigned char> key; GetSslStorageKey(key); m_sslCertificatesStorage.reset( new SslCertificatesStorage( GetConfiguration().GetCertificatesStoragePath().c_str(), &key[0], key.size())); } return *m_sslCertificatesStorage; } std::auto_ptr<ServiceConfiguration> LoadConfiguration() { std::auto_ptr<ServiceConfiguration> result; try { result.reset(new ServiceConfiguration); } catch (const ServiceConfiguration::ConfigurationNotFoundException &) { result = ServiceConfiguration::GetDefault(); } catch (const ServiceConfiguration::ConfigurationHasInvalidFormatException &) { result.reset( new ServiceConfiguration( LegacySupporter().MigrateCurrentServiceConfiguration())); } catch (const ServiceConfiguration::ConfigurationException &) { //...// } if (result->IsChanged()) { const bool saveResult = result->Save(); assert(saveResult); if (saveResult && !ServiceConfiguration::IsTestMode()) { ServiceFilesSecurity::Set(ServiceConfiguration::GetConfigurationFileDir()); } } return result; } bool TruncateLog( const ServiceConfiguration &configuration, uintmax_t &previousLogSize) const { const std::wstring logPath = configuration.GetLogPath(); previousLogSize = 0; try { if (fs::exists(logPath)) { previousLogSize = fs::file_size(logPath); if (previousLogSize > configuration.GetMaxLogSize()) { std::ofstream f(logPath.c_str(), std::ios::trunc); return true; } } } catch (const fs::filesystem_error&) { //...// } return false; } template<class RuleSet> bool UpdateRulesState(RuleSet &ruleSet) const { const size_t ruleSetSize = ruleSet.GetSize(); bool hasChanges = false; for (size_t i = 0; i < ruleSetSize; ++i) { const bool isEnabled = Server::GetInstance().IsRuleEnabled(ruleSet[i].GetUuid()); if (isEnabled != ruleSet[i].IsEnabled()) { assert(!isEnabled); ruleSet[i].Enable(isEnabled); hasChanges = true; } } return hasChanges; } //! Normally this operation required only be the active rules license restriction. void UpdateRulesState() { std::auto_ptr<RuleSet> rulesPtr(new RuleSet(*m_ruleSet)); bool hasChanges = false; if (UpdateRulesState(rulesPtr->GetServices())) { hasChanges = true; } if (UpdateRulesState(rulesPtr->GetTunnels())) { hasChanges = true; } if (hasChanges) { SetRuleSet(rulesPtr); SaveRules(); } } void SetRuleSet(std::auto_ptr<RuleSet> newRuleSet) throw() { m_ruleSet = newRuleSet; UpdateLastRuleSetRevision(); } void UpdateLastRuleSetRevision() { Interlocked::Increment(&m_ruleSetRevision); Interlocked::Increment(&m_stateRevision); } void UpdateLastLicenseKeyModificationTime() { const auto diff = m_licenseKeyRevisionTimeDiff; const long newDiff = long(Licensing::ServiceKeyRequest::LocalStorage::GetDbFileModificationTime() - m_startTime); if ( diff != newDiff && Interlocked::CompareExchange( m_licenseKeyRevisionTimeDiff, newDiff, diff) == diff) { Interlocked::Increment(&m_licenseKeyRevision); Interlocked::Increment(&m_stateRevision); } } template<class RuleSet> bool EnableRule( RuleSet &ruleSet, const std::wstring &uuid, bool wasEnabled, bool &changed) const { const size_t size = ruleSet.GetSize(); for (size_t i = 0; i < size; ++i) { typename RuleSet::ItemType &rule = ruleSet[i]; if (rule.GetUuid() == uuid.c_str()) { if (rule.IsEnabled() != wasEnabled) { rule.Enable(wasEnabled); if ( Server::GetInstance().IsStarted() && !Server::GetInstance().UpdateRule(rule)) { Format message( "The rule \"%1%\" has been updated, but some errors has been occurred."); message % ConvertString<String>(rule.GetUuid()).GetCStr(); Log::GetInstance().AppendWarn(message.str()); } changed = true; } else { changed = false; } return true; } } changed = false; return false; } template<class RuleSet> bool DeleteRule(RuleSet &ruleSet, const std::wstring &uuid) const { const size_t size = ruleSet.GetSize(); for (size_t i = 0; i < size; ++i) { if (ruleSet[i].GetUuid() == uuid.c_str()) { ruleSet.Remove(i); return true; } } return false; } template<class RuleSet> void UpdateRules(const RuleSet &ruleSetWithNew, RuleSet &ruleSet) { const size_t size = ruleSetWithNew.GetSize(); for (unsigned int i = 0; i < size; ++i) { const typename RuleSet::ItemType &newRule = ruleSetWithNew[i]; const WString &u = newRule.GetUuid(); const size_t currentRulesNumb = ruleSet.GetSize(); bool wasFound = false; for (size_t j = 0; j < currentRulesNumb; ++j) { if (ruleSet[j].GetUuid() == u) { ruleSet[j] = newRule; wasFound = true; break; } } if (!wasFound) { ruleSet.Append(newRule); } if ( Server::GetInstance().IsStarted() && !Server::GetInstance().UpdateRule(newRule)) { Format message( "The rule \"%1%\" has been updated, but some errors has been occurred."); message % ConvertString<String>(u).GetCStr(); Log::GetInstance().AppendWarn(message.str()); } } } void GetSslStorageKey(std::vector<unsigned char> &result) { /* <)g<D}GhTFXOByZneW8zJA`53u(Ddk6P&Mh!,G8oRra{g]UrGgi%bRl{=P$u,'^@Iln4QkW;vK/ length: 75 */ std::vector<unsigned char> key; key.resize(27); key[26] = '('; key.resize(51); key[50] = 'i'; key[0] = '<'; key[22] = '`'; key[18] = '8'; key[32] = '&'; key[33] = 'M'; key[17] = 'W'; key[8] = 'T'; key[4] = 'D'; key[38] = '8'; key[34] = 'h'; key.resize(55); key[54] = 'l'; key.resize(57); key[56] = '='; key[2] = 'g'; key[15] = 'n'; key.resize(58); key[57] = 'P'; key.resize(64); key[63] = '@'; key[7] = 'h'; key[14] = 'Z'; key.resize(72); key[71] = ';'; key[55] = '{'; key[39] = 'o'; key[40] = 'R'; key.resize(75); key[74] = '/'; key[16] = 'e'; key[36] = ','; key[12] = 'B'; key[24] = '3'; key[23] = '5'; key[11] = 'O'; key[30] = '6'; key[6] = 'G'; key[20] = 'J'; key[1] = ')'; key[60] = ','; key[25] = 'u'; key[62] = '^'; key[44] = 'g'; key[29] = 'k'; key[51] = '%'; key[5] = '}'; key[47] = 'r'; key[49] = 'g'; key[67] = '4'; key[21] = 'A'; key[65] = 'l'; key[41] = 'r'; key[52] = 'b'; key[68] = 'Q'; key[43] = '{'; key[19] = 'z'; key[27] = 'D'; key[10] = 'X'; key[46] = 'U'; key[31] = 'P'; key[45] = ']'; key[69] = 'k'; key[3] = '<'; key[70] = 'W'; key[35] = '!'; key[72] = 'v'; key[58] = '$'; key[13] = 'y'; key[59] = 'u'; key[61] = '\''; key[48] = 'G'; key[64] = 'I'; key[42] = 'a'; key[9] = 'F'; key[53] = 'R'; key[73] = 'K'; key[66] = 'n'; key[37] = 'G'; key[28] = 'd'; key.swap(result); } public: std::auto_ptr<RuleSet> m_ruleSet; volatile long m_stateRevision; volatile long m_ruleSetRevision; volatile long m_licenseKeyRevision; volatile long m_licenseKeyRevisionTimeDiff; volatile long m_logSize; volatile long m_errorCount; volatile long m_warnCount; volatile long m_isStarted; const time_t m_startTime; std::wstring m_rulesFilePath; std::wstring m_logFilePath; boost::mutex m_mutex; std::auto_ptr<ServiceConfiguration> m_conf; std::auto_ptr<SslCertificatesStorage> m_sslCertificatesStorage; }; ////////////////////////////////////////////////////////////////////////// TexServiceImplementation::TexServiceImplementation(boost::optional<LogLevel> forcedLogLevel) : m_pimpl(new Implementation) { ServiceConfiguration &conf = m_pimpl->GetConfiguration(); uintmax_t previousLogSize; const bool logWasTruncated = m_pimpl->TruncateLog(conf, previousLogSize); Log::GetInstance().AttachFile(conf.GetLogPath()); # if !defined(DEV_VER) if (!forcedLogLevel && conf.GetLogLevel() == TunnelEx::LOG_LEVEL_DEBUG) { conf.SetLogLevel(TunnelEx::LOG_LEVEL_INFO); conf.Save(); } # endif Log::GetInstance().SetMinimumRegistrationLevel(forcedLogLevel ? *forcedLogLevel : conf.GetLogLevel()); Log::GetInstance().AppendForced( TunnelEx::LOG_LEVEL_INFO, "Started " TUNNELEX_NAME " " TUNNELEX_VERSION_FULL TUNNELEX_BUILD_IDENTITY_ADD); if (logWasTruncated) { Log::GetInstance().AppendInfo( (Format("Log was truncated, previous size - %1% bytes.") % previousLogSize).str()); } m_pimpl->m_rulesFilePath = conf.GetRulesPath(); m_pimpl->m_logFilePath = conf.GetLogPath(); m_pimpl->LoadRules(); if (conf.IsServerStarted()) { Start(); } } TexServiceImplementation::~TexServiceImplementation() { LogTracking("TexServiceImplementation", "~TexServiceImplementation", __FILE__, __LINE__); } bool TexServiceImplementation::Start() { LogTracking("TexServiceImplementation", "StartServer", __FILE__, __LINE__); if (!Server::GetInstance().IsStarted()) { boost::mutex::scoped_lock lock(m_pimpl->m_mutex); if (!Server::GetInstance().IsStarted()) { try { Server::GetInstance().Start( *m_pimpl->m_ruleSet, m_pimpl->GetSslCertificatesStorage()); } catch (const ::TunnelEx::LocalException &ex) { Format message("Could not start the server: \"%1%\"."); message % ConvertString<String>(ex.GetWhat()).GetCStr(); Log::GetInstance().AppendFatalError(message.str()); } } } const bool isStarted = Server::GetInstance().IsStarted(); if (isStarted) { m_pimpl->UpdateRulesState(); } return isStarted; } bool TexServiceImplementation::Stop() { LogTracking("TexServiceImplementation", "StopServer", __FILE__, __LINE__); if (Server::GetInstance().IsStarted()) { boost::mutex::scoped_lock lock(m_pimpl->m_mutex); if (Server::GetInstance().IsStarted()) { try { Server::GetInstance().Stop(); } catch (const ::TunnelEx::LocalException &ex) { Format message("Could not stop the server: \"%1%\"."); message % ConvertString<String>(ex.GetWhat()).GetCStr(); Log::GetInstance().AppendFatalError(message.str()); } } } return !Server::GetInstance().IsStarted(); } bool TexServiceImplementation::IsStarted() const { return Server::GetInstance().IsStarted(); } void TexServiceImplementation::GetRuleSet(std::string &result) const { WString buffer; try { boost::mutex::scoped_lock lock(m_pimpl->m_mutex); m_pimpl->m_ruleSet->GetXml(buffer); } catch (const TunnelEx::LocalException &ex) { Format message("Could not serialize rules list into XML: \"%1%\"."); message % ConvertString<String>(ex.GetWhat()).GetCStr(); Log::GetInstance().AppendFatalError(message.str()); } result = ConvertString<String>(buffer).GetCStr(); } //! @todo: make exception-safe void TexServiceImplementation::UpdateRules(const std::wstring &xml) { try { RuleSet ruleSet(xml.c_str()); boost::mutex::scoped_lock lock(m_pimpl->m_mutex); m_pimpl->UpdateRules(ruleSet.GetServices(), m_pimpl->m_ruleSet->GetServices()); m_pimpl->UpdateRules(ruleSet.GetTunnels(), m_pimpl->m_ruleSet->GetTunnels()); m_pimpl->SaveRules(); m_pimpl->UpdateLastRuleSetRevision(); } catch (const ::TunnelEx::LocalException &ex) { Format message("Could not update rules: %1%."); message % ConvertString<String>(ex.GetWhat()).GetCStr(); Log::GetInstance().AppendError(message.str()); m_pimpl->UpdateRulesState(); return; } } void TexServiceImplementation::EnableRules( const std::list<std::wstring> &uuids, bool isEnabled) { try { bool wasChanged = false; const std::list<std::wstring>::const_iterator end = uuids.end(); boost::mutex::scoped_lock lock(m_pimpl->m_mutex); foreach (const std::wstring &u, uuids) { bool wasChangedNow = false; m_pimpl->EnableRule(m_pimpl->m_ruleSet->GetServices(), u, isEnabled, wasChangedNow) || m_pimpl->EnableRule(m_pimpl->m_ruleSet->GetTunnels(), u, isEnabled, wasChangedNow); if (wasChangedNow) { wasChanged = true; } } if (wasChanged) { m_pimpl->SaveRules(); m_pimpl->UpdateLastRuleSetRevision(); } } catch (const ::TunnelEx::LocalException &ex) { Format message("Could not enable rules: %1%."); message % ConvertString<String>(ex.GetWhat()).GetCStr(); Log::GetInstance().AppendError(message.str()); m_pimpl->UpdateRulesState(); return; } } //! @todo: make exception-safe void TexServiceImplementation::DeleteRules(const std::list<std::wstring> &uuids) { bool wasFound = false; boost::mutex::scoped_lock lock(m_pimpl->m_mutex); foreach (const std::wstring &u, uuids) { if (Server::GetInstance().IsStarted()) { Server::GetInstance().DeleteRule(u.c_str()); } if ( m_pimpl->DeleteRule(m_pimpl->m_ruleSet->GetServices(), u) || m_pimpl->DeleteRule(m_pimpl->m_ruleSet->GetTunnels(), u)) { wasFound = true; } } if (wasFound) { m_pimpl->SaveRules(); m_pimpl->UpdateLastRuleSetRevision(); } } void TexServiceImplementation::SaveRunningState() const { LogTracking("TexServiceImplementation", "SaveServerState", __FILE__, __LINE__); ServiceConfiguration &conf = m_pimpl->GetConfiguration(); try { conf.SetServerStarted(Server::GetInstance().IsStarted()); conf.Save(); } catch (const ServiceConfiguration::ConfigurationException &) { Log::GetInstance().AppendFatalError( "Could not save server state into service configuration file."); } } LogLevel TexServiceImplementation::GetLogLevel() const { return m_pimpl->GetConfiguration().GetLogLevel(); } void TexServiceImplementation::SetLogLevel(LogLevel level) { ServiceConfiguration &conf = m_pimpl->GetConfiguration(); try { conf.SetLogLevel(level); Log::GetInstance().SetMinimumRegistrationLevel(conf.GetLogLevel()); conf.Save(); } catch (const ServiceConfiguration::ConfigurationException &) { Log::GetInstance().AppendFatalError( "Could not save server state into service configuration file."); } } void TexServiceImplementation::GetNetworkAdapters( std::list<texs__NetworkAdapterInfo> &result) const { std::list<texs__NetworkAdapterInfo> adapters; { texs__NetworkAdapterInfo all; all.id = "all"; all.name = "All available locally"; all.ipAddress = "*"; adapters.push_back(all); } { texs__NetworkAdapterInfo loopback; loopback.id = "loopback"; loopback.name = "Loopback"; loopback.ipAddress = "127.0.0.1"; adapters.push_back(loopback); } std::vector<unsigned char> adaptersInfo(sizeof(IP_ADAPTER_INFO)); ULONG adaptersInfoBufferLen = ULONG(adaptersInfo.size()); if ( GetAdaptersInfo( reinterpret_cast<PIP_ADAPTER_INFO>(&adaptersInfo[0]), &adaptersInfoBufferLen) == ERROR_BUFFER_OVERFLOW) { adaptersInfo.resize(adaptersInfoBufferLen); } if ( GetAdaptersInfo( reinterpret_cast<PIP_ADAPTER_INFO>(&adaptersInfo[0]), &adaptersInfoBufferLen) == NO_ERROR) { PIP_ADAPTER_INFO adapter = reinterpret_cast<PIP_ADAPTER_INFO>(&adaptersInfo[0]); while (adapter) { std::string ipAddress = adapter->IpAddressList.IpAddress.String; const bool isIpValid = !ipAddress.empty() && ipAddress != "0.0.0.0"; switch (adapter->Type) { default: if (!isIpValid) { break; } case MIB_IF_TYPE_ETHERNET: case MIB_IF_TYPE_PPP: case IF_TYPE_IEEE80211: case IF_TYPE_IEEE80212: case IF_TYPE_FASTETHER: case IF_TYPE_FASTETHER_FX: { texs__NetworkAdapterInfo info; info.id = adapter->AdapterName; info.name = adapter->Description; if (isIpValid) { info.ipAddress.swap(ipAddress); } adapters.push_back(info); } break; } adapter = adapter->Next; } } adapters.swap(result); } void TexServiceImplementation::GetLastLogRecords( unsigned int recordsNumber, std::list<texs__LogRecord> &destination) const { std::ifstream log(m_pimpl->m_logFilePath.c_str(), std::ios::in | std::ios::binary); log.seekg(-1, std::ios::end); unsigned int passedLines = 0; bool isContentStarted = false; for (std::streamsize i = 1; ; log.seekg(-(++i), std::ios::end)) { if (!log) { log.clear(); log.seekg(-(i - 1), std::ios::end); break; } char c; log.get(c); if (c == '\n') { if (isContentStarted && ++passedLines >= recordsNumber) { break; } } else if (!isContentStarted) { isContentStarted = true; } } const unsigned short bufferStep # ifdef _DEBUG = 10; # else = 512; # endif // _DEBUG std::vector<char> buffer(bufferStep, 0); size_t pos = 0; boost::regex recordExp( "(\\d{4,4}\\-[a-z]{3,3}\\-\\d{2,2}\\s\\d{2,2}:\\d{2,2}:\\d{2,2}.\\d{6,6})\\s+([a-z]+(\\s[a-z]+)?):\\s([^\\r\\n]*)[\\r\\n\\t\\s]*", boost::regex::perl | boost::regex::icase); while (!log.getline(&buffer[pos], std::streamsize(buffer.size() - pos)).eof()) { if (log.fail()) { pos = buffer.size() - 1; buffer.resize(buffer.size() + bufferStep); log.clear(log.rdstate() & ~std::ios::failbit); } else { pos = 0; boost::cmatch what; if (boost::regex_match(&buffer[0], what, recordExp)) { texs__LogRecord record; record.time = what[1]; record.level = Log::GetInstance().ResolveLevel(what[2].str().c_str()); record.message = what[4]; destination.push_back(record); } } } } bool TexServiceImplementation::Migrate() { LegacySupporter().MigrateAllAndSave(); m_pimpl->LoadRules(); return true; } long TexServiceImplementation::HitHeart() const { bool isNewRevision = false; { const auto newLogSize = Log::GetInstance().GetSize(); if (newLogSize != m_pimpl->m_logSize) { const auto logSize = m_pimpl->m_logSize; if ( Interlocked::CompareExchange(m_pimpl->m_logSize, newLogSize, logSize) == logSize) { Interlocked::CompareExchange( m_pimpl->m_warnCount, Log::GetInstance().GetWarnCount(), m_pimpl->m_warnCount); Interlocked::CompareExchange( m_pimpl->m_errorCount, Log::GetInstance().GetErrorCount(), m_pimpl->m_errorCount); Interlocked::Increment(&m_pimpl->m_stateRevision); isNewRevision = true; } } } { const long newIsStarted = Server::GetInstance().IsStarted() ? 1 : 0; if (m_pimpl->m_isStarted != newIsStarted) { const auto isStarted = m_pimpl->m_isStarted; if ( Interlocked::CompareExchange( m_pimpl->m_isStarted, newIsStarted, isStarted) == isStarted && !isNewRevision) { Interlocked::Increment(&m_pimpl->m_stateRevision); } } } return m_pimpl->m_stateRevision; } void TexServiceImplementation::CheckState(texs__ServiceState &result) const { result.rev = HitHeart(); result.errorCount = m_pimpl->m_errorCount; result.warnCount = m_pimpl->m_warnCount; result.logSize = m_pimpl->m_logSize; result.ruleSetRev = m_pimpl->m_ruleSetRevision; result.licKeyRev = m_pimpl->m_licenseKeyRevision; result.isStarted = m_pimpl->m_isStarted != 0; } void TexServiceImplementation::GenerateLicenseKeyRequest( const std::string &license, std::string &request, std::string &privateKey) const { Licensing::ServiceKeyRequest::RequestGeneration::Generate( license, request, privateKey, boost::any()); } std::string TexServiceImplementation::GetTrialLicense() const { return Licensing::ServiceKeyRequest::LocalStorage::GetTrialLicense(); } std::string TexServiceImplementation::GetLicenseKey() const { return Licensing::ServiceKeyRequest::LocalStorage::GetLicenseKey(boost::any()); } void TexServiceImplementation::RegisterLicenseError( TunnelEx::Licensing::Client client, const std::string &license, const std::string &time, const std::string &point, const std::string &error) { TunnelEx::LicenseState::GetInstance().RegisterError(client, license, time, point, error); } std::string TexServiceImplementation::GetLicenseKeyLocalAsymmetricPrivateKey() const { return Licensing::ServiceKeyRequest::LocalStorage::GetLocalAsymmetricPrivateKey(boost::any()); } void TexServiceImplementation::SetLicenseKey( const std::string &licenseKey, const std::string &privateKey) { Licensing::ServiceKeyRequest::LocalStorage::StoreLicenseKey( licenseKey, privateKey); m_pimpl->UpdateLastLicenseKeyModificationTime(); } void TexServiceImplementation::GetProperties(std::vector<unsigned char> &result) { using namespace Licensing; typedef boost::int8_t Result; typedef boost::int32_t ValSize; typedef boost::int32_t Id; std::vector<unsigned char> notEncryptedBuffer; notEncryptedBuffer.resize(sizeof(Result)); WorkstationPropertyValues props; if (ExeLicense::WorkstationPropertiesLocal::Get(props, boost::any())) { reinterpret_cast<Result &>(*&notEncryptedBuffer[0]) = Result(true); foreach (const WorkstationPropertyValues::value_type &prop, props) { size_t i = notEncryptedBuffer.size(); notEncryptedBuffer.resize( notEncryptedBuffer.size() + sizeof(Id) + sizeof(ValSize) + prop.second.size()); reinterpret_cast<Id &>(*&notEncryptedBuffer[i]) = Id(prop.first); i += sizeof(Id); reinterpret_cast<ValSize &>(*&notEncryptedBuffer[i]) = ValSize(prop.second.size()); i += sizeof(ValSize); memcpy(&notEncryptedBuffer[i], prop.second.c_str(), prop.second.size()); assert(i + prop.second.size() == notEncryptedBuffer.size()); } } else { reinterpret_cast<Result &>(*&notEncryptedBuffer[0]) = Result(false); } std::vector<unsigned char> encryptedBuffer(notEncryptedBuffer.size()); std::vector<unsigned char>::iterator i = encryptedBuffer.begin(); std::vector<unsigned char> key; LocalComunicationPolicy::GetEncryptingKey(key); size_t token = 0; foreach (char ch, notEncryptedBuffer) { ch ^= key[token++ % key.size()]; *i = ch; ++i; } encryptedBuffer.swap(result); } bool TexServiceImplementation::GetUpnpStatus( std::string &externalIp, std::string &localIp) const { try { Mods::Upnp::Client upnpc; std::string externalIpTmp = upnpc.GetExternalIpAddress(); std::string localIpTmp = upnpc.GetLocalIpAddress(); externalIpTmp.swap(externalIp); localIpTmp.swap(localIp); return true; } catch (const ::TunnelEx::Mods::Upnp::Client::DeviceNotExistException &) { //...// } catch (const ::TunnelEx::LocalException &ex) { Log::GetInstance() .AppendError(ConvertString<String>(ex.GetWhat()).GetCStr()); } return false; } void TexServiceImplementation::GetSslCertificate( const std::wstring &id, texs__SslCertificateInfo &result) const { try { const AutoPtr<const X509Shared> certificate = m_pimpl->GetSslCertificatesStorage().GetCertificate(id.c_str()); texs__SslCertificateInfo certificateInfo; certificateInfo.id = id; certificateInfo.keySize = certificate->GetPublicKey().GetSize(); certificateInfo.isPrivate = m_pimpl->GetSslCertificatesStorage().IsPrivateCertificate(id.c_str()); certificateInfo.serial = certificate->GetSerialNumber(); certificateInfo.validAfterTimeUtc = certificate->GetValidAfterTimeUtc(); certificateInfo.validBeforeTimeUtc = certificate->GetValidBeforeTimeUtc(); certificateInfo.subjectCommonName = certificate->GetSubjectCommonName(); certificateInfo.issuerCommonName = certificate->GetIssuerCommonName(); certificateInfo.subjectOrganization = certificate->GetSubjectOrganization(); certificateInfo.subjectOrganizationUnit = certificate->GetSubjectOrganizationUnit(); certificateInfo.subjectCity = certificate->GetSubjectCity(); certificateInfo.subjectStateOrProvince = certificate->GetSubjectStateOrProvince(); certificateInfo.subjectCountry = certificate->GetSubjectCountry(); certificate->Print(certificateInfo.fullInfo); certificateInfo.certificate = certificate->Export(); result = certificateInfo; } catch (const TunnelEx::LocalException &ex) { Format message("Could not get SSL certificate %1%: %2%."); message % ConvertString<String>(id.c_str()).GetCStr(); message % ConvertString<String>(ex.GetWhat()).GetCStr(); Log::GetInstance().AppendError(message.str()); result = texs__SslCertificateInfo(); } catch (const TunnelEx::Helpers::Crypto::Exception &ex) { Format message("Could not get SSL certificate info: %1%."); message % ex.what(); Log::GetInstance().AppendError(message.str()); } } void TexServiceImplementation::GetSslCertificates( std::list<texs__SslCertificateShortInfo> &result) const { try { for ( ; ; ) { std::list<texs__SslCertificateShortInfo> certificates; const AutoPtr<const SslCertificateIdCollection> ids = m_pimpl->GetSslCertificatesStorage().GetInstalledIds(); try { for (size_t i = 0; i < ids->GetSize(); ++i) { const WString &id = (*ids)[i]; try { const AutoPtr<const X509Shared> certificate = m_pimpl->GetSslCertificatesStorage().GetCertificate(id); texs__SslCertificateShortInfo certificateInfo; certificateInfo.id = id.GetCStr(); certificateInfo.isPrivate = m_pimpl ->GetSslCertificatesStorage() .IsPrivateCertificate(id); certificateInfo.validBeforeTimeUtc = certificate->GetValidBeforeTimeUtc(); certificateInfo.subjectCommonName = certificate->GetSubjectCommonName(); certificateInfo.issuerCommonName = certificate->GetIssuerCommonName(); certificates.push_back(certificateInfo); } catch (const TunnelEx::Helpers::Crypto::Exception &ex) { Format message("Could not get info for SSL certificate %1%: %2%."); message % ConvertString<String>(id).GetCStr(); message % ex.what(); Log::GetInstance().AppendError(message.str()); } } } catch (const NotFoundException &) { Log::GetInstance().AppendDebug("SSL certificates list has been changed, reloading..."); continue; } certificates.swap(result); return; } } catch (const TunnelEx::LocalException &ex) { Format message("Could not get SSL certificates list: %1%."); message % ConvertString<String>(ex.GetWhat()).GetCStr(); Log::GetInstance().AppendError(message.str()); std::list<texs__SslCertificateShortInfo>().swap(result); } } void TexServiceImplementation::DeleteSslCertificates(const std::list<std::wstring> &ids) { SslCertificateIdCollection idsForStorage(ids.size()); foreach (const std::wstring &id, ids) { idsForStorage.Append(id.c_str()); } try { m_pimpl->GetSslCertificatesStorage().Delete(idsForStorage); } catch (const TunnelEx::LocalException &ex) { Format message("Could not delete SSL certificates: %1%."); message % ConvertString<String>(ex.GetWhat()).GetCStr(); Log::GetInstance().AppendError(message.str()); } } void TexServiceImplementation::ImportSslCertificateX509( const std::vector<unsigned char> &certificate, const std::string &privateKeyStr, std::wstring &error) { Log::GetInstance().AppendDebug("Importing SSL certificate..."); std::auto_ptr<PrivateKey> privateKey; if (!privateKeyStr.empty()) { Log::GetInstance().AppendDebug("Importing SSL certificate private key..."); try { privateKey.reset(new PrivateKey(privateKeyStr)); Log::GetInstance().AppendDebug("SSL certificate private key successfully parsed..."); } catch (const TunnelEx::Helpers::Crypto::Exception &ex) { Log::GetInstance().AppendDebug( "Failed to parse SSL certificate private key: %1%.", ex.what()); error = L"Could not parse the private key. Please check the file format."; return; } } std::auto_ptr<X509Shared> x509; Log::GetInstance().AppendDebug("Importing X.509 SSL certificate..."); try { if (privateKey.get()) { x509.reset(new X509Private(&certificate[0], certificate.size(), *privateKey)); } else { x509.reset(new X509Shared(&certificate[0], certificate.size())); } Log::GetInstance().AppendDebug("X.509 SSL certificate successfully parsed..."); } catch (const TunnelEx::Helpers::Crypto::Exception &ex) { Log::GetInstance().AppendDebug( "Failed to parse X.509: %1%.", ex.what()); error = L"Could not parse the X.509 SSL certificate. Please check the file format."; return; } assert(x509.get() != 0 || privateKey.get() == 0); try { Log::GetInstance().AppendDebug("Installing public SSL certificate..."); if (privateKey.get()) { m_pimpl->GetSslCertificatesStorage().Insert( *boost::polymorphic_downcast<X509Private *>(x509.get())); } else { m_pimpl->GetSslCertificatesStorage().Insert(*x509); } } catch (const TunnelEx::Helpers::Crypto::Exception &ex) { Format message("Could not install SSL certificate: %1%."); message % ex.what(); Log::GetInstance().AppendDebug(message.str()); error = ConvertString<WString>(message.str().c_str()).GetCStr(); } catch (const TunnelEx::LocalException &ex) { Format message("Could not import and install SSL certificate: %1%."); message % ConvertString<String>(ex.GetWhat()).GetCStr(); Log::GetInstance().AppendError(message.str()); } } void TexServiceImplementation::ImportSslCertificatePkcs12( const std::vector<unsigned char> &certificate, const std::string &password, std::wstring &error) { Log::GetInstance().AppendDebug("Importing PKCS12..."); std::auto_ptr<Pkcs12> pkcs12; try { pkcs12.reset(new Pkcs12(&certificate[0], certificate.size())); } catch (const TunnelEx::Helpers::Crypto::Exception &ex) { Log::GetInstance().AppendDebug("Failed to parse PKCS12: %1%.", ex.what()); error = L"Could not parse SSL certificate. Please check the file format."; return; } assert(pkcs12.get() != 0); std::auto_ptr<const X509Private> x509; try { Log::GetInstance().AppendDebug("Checking SSL certificate password..."); x509 = pkcs12->GetCertificate(password); } catch (const TunnelEx::Helpers::Crypto::Exception &ex) { Log::GetInstance().AppendDebug( "Failed to check SSL certificate (%1%)...", ex.what()); error = L"Could not parse SSL certificate." L" Please check the file format and password."; return; } assert(x509.get() != 0); Log::GetInstance().AppendDebug("Installing private SSL certificate..."); try { m_pimpl->GetSslCertificatesStorage().Insert(*x509); } catch (const TunnelEx::Helpers::Crypto::Exception &ex) { Format message("Could not install SSL certificate: %1%."); message % ex.what(); Log::GetInstance().AppendDebug(message.str()); error = ConvertString<WString>(message.str().c_str()).GetCStr(); } catch (const TunnelEx::LocalException &ex) { Format message("Could not import and install SSL certificate: %1%."); message % ConvertString<String>(ex.GetWhat()).GetCStr(); Log::GetInstance().AppendError(message.str()); } }
31.763033
132
0.682751
[ "vector" ]
b06a4d32abeec83e6a7b87d108570a6cc417bbec
2,887
cpp
C++
source/globjects/source/ProgramPipeline.cpp
citron0xa9/globjects
53a1de45f3c177fbd805610f274d3ffb1b97843a
[ "MIT" ]
null
null
null
source/globjects/source/ProgramPipeline.cpp
citron0xa9/globjects
53a1de45f3c177fbd805610f274d3ffb1b97843a
[ "MIT" ]
null
null
null
source/globjects/source/ProgramPipeline.cpp
citron0xa9/globjects
53a1de45f3c177fbd805610f274d3ffb1b97843a
[ "MIT" ]
2
2020-10-01T04:10:51.000Z
2021-07-01T07:45:45.000Z
#include <globjects/ProgramPipeline.h> #include <glbinding/gl/enum.h> #include <glbinding/gl/boolean.h> #include <glbinding/gl/functions.h> #include <globjects/Program.h> #include <globjects/ObjectVisitor.h> #include <globjects/Resource.h> namespace globjects { ProgramPipeline::ProgramPipeline() : Object(std::unique_ptr<IDResource>(new ProgramPipelineResource())) , m_dirty(true) { } ProgramPipeline::~ProgramPipeline() { if (0 == id()) { for (auto & program : m_programs) program->deregisterListener(this); } else { for (auto program : std::set<Program *>(m_programs)) releaseProgram(program); } } void ProgramPipeline::accept(ObjectVisitor & visitor) { visitor.visitProgramPipeline(this); } void ProgramPipeline::use() const { if (m_dirty) { for (const Program * program : m_programs) { program->link(); } const_cast<ProgramPipeline *>(this)->m_dirty = false; checkUseStatus(); } gl::glUseProgram(0); gl::glBindProgramPipeline(id()); } void ProgramPipeline::release() { gl::glBindProgramPipeline(0); } void ProgramPipeline::useStages(Program * program, gl::UseProgramStageMask stages) { program->setParameter(gl::GL_PROGRAM_SEPARABLE, gl::GL_TRUE); program->registerListener(this); m_programs.emplace(program); program->link(); gl::glUseProgramStages(id(), stages, program->id()); invalidate(); } void ProgramPipeline::releaseStages(gl::UseProgramStageMask stages) { gl::glUseProgramStages(id(), stages, 0); invalidate(); } void ProgramPipeline::releaseProgram(Program * program) { program->deregisterListener(this); m_programs.erase(program); invalidate(); } void ProgramPipeline::notifyChanged(const Changeable * /*sender*/) { invalidate(); } bool ProgramPipeline::isValid() const { return get(gl::GL_VALIDATE_STATUS) == 1; } void ProgramPipeline::validate() const { gl::glValidateProgramPipeline(id()); } void ProgramPipeline::invalidate() { m_dirty = true; } bool ProgramPipeline::checkUseStatus() const { validate(); if (!isValid()) { critical() << "Use error:" << std::endl << infoLog(); return false; } return true; } gl::GLint ProgramPipeline::get(const gl::GLenum pname) const { gl::GLint value = 0; gl::glGetProgramPipelineiv(id(), pname, &value); return value; } std::string ProgramPipeline::infoLog() const { gl::GLint length = get(gl::GL_INFO_LOG_LENGTH); if (length == 0) return std::string(); std::vector<char> log(length); gl::glGetProgramPipelineInfoLog(id(), length, &length, log.data()); return std::string(log.data(), length); } gl::GLenum ProgramPipeline::objectType() const { return gl::GL_PROGRAM_PIPELINE; } } // namespace globjects
18.272152
82
0.659508
[ "object", "vector" ]
b07950755c76329d5380ea86a0d895470f229a19
970
cpp
C++
LCA.cpp
imran123509/graph-concept-
4fde73cc4ac41f5b3b639b5204627618e85a3016
[ "MIT" ]
null
null
null
LCA.cpp
imran123509/graph-concept-
4fde73cc4ac41f5b3b639b5204627618e85a3016
[ "MIT" ]
null
null
null
LCA.cpp
imran123509/graph-concept-
4fde73cc4ac41f5b3b639b5204627618e85a3016
[ "MIT" ]
null
null
null
#include<bits/stdc++.h> using namespace std; const int N=1e5+5; //lowest common ancestor vector<int> graph[N]; int parent[N]; // storing the parent of all node void dfs(int vertex, int par=-1){ parent[vertex]=par; for(int child : graph[vertex]){ if(child==par) continue; dfs(child, vertex); } } // storing the path vector<int> path(int vertex){ vector<int> ans; while(vertex !=-1){ ans.push_back(vertex); vertex=parent[vertex]; } reverse(ans.begin(), ans.end()); return ans; } int main(){ int n; cin>>n; for(int i=0; i<n-1; i++){ int x, y; cin>>x>>y; graph[x].push_back(y); graph[y].push_back(x); } dfs(1); int x, y; cin>>x>>y; vector<int> path_x=path(x); vector<int> path_y=path(y); int minlen=min(path_x.size(), path_y.size()); int lca=-1; for(int i=0; i<minlen; i++){ if(path_x[i]==path_y[i]){ lca=path_x[i]; } } cout<<lca<<endl; } /* 13 1 2 1 3 1 13 2 5 5 6 5 7 5 8 8 12 3 4 4 9 4 10 10 11 */
14.477612
48
0.597938
[ "vector" ]
b0842cc27c7b7cf75ea0f51e7b0efc4d59acd67a
1,194
cpp
C++
binarysearch.io/easy/Sorting-Mail.cpp
wingkwong/competitive-programming
e8bf7aa32e87b3a020b63acac20e740728764649
[ "MIT" ]
18
2020-08-27T05:27:50.000Z
2022-03-08T02:56:48.000Z
binarysearch.io/easy/Sorting-Mail.cpp
wingkwong/competitive-programming
e8bf7aa32e87b3a020b63acac20e740728764649
[ "MIT" ]
null
null
null
binarysearch.io/easy/Sorting-Mail.cpp
wingkwong/competitive-programming
e8bf7aa32e87b3a020b63acac20e740728764649
[ "MIT" ]
1
2020-10-13T05:23:58.000Z
2020-10-13T05:23:58.000Z
/* Sorting Mail https://binarysearch.io/problems/Sorting-Mail You are given a list of mailboxes. Each mailbox is a list of strings, where each string is either "junk", "personal", "work". Go through each mailbox in round robin order starting from the first one, filtering out junk, to form a single pile and return the pile. Example 1 Input mailboxes = [ ["work", "personal"], ["junk", "personal", "junk"], ["work"] ] Output ["work", "work", "personal", "personal"] Explanation In order and without filtering, we'd have work -> junk -> work -> personal -> personal -> junk, and since we filter out junk we get work -> work -> personal -> personal. */ #include "solution.hpp" using namespace std; class Solution { public: vector<string> solve(vector<vector<string>>& mailboxes) { vector<string> ans; int mx=-1; for(auto mailbox:mailboxes){ mx=max(mx,(int)mailbox.size()); } for(int i=0;i<mx;i++){ for(auto mailbox: mailboxes){ if(i<mailbox.size()&&mailbox[i]!="junk"){ ans.push_back(mailbox[i]); } } } return ans; } };
26.533333
262
0.599665
[ "vector" ]
b086fd1679108d2b144f8b97244f2eb989c9b382
3,660
cpp
C++
src/LuaState.cpp
guwere/luapath
d782070ec8f04eef9161baeb2db9f5dcc87a008b
[ "MIT" ]
3
2015-08-05T00:00:11.000Z
2016-06-30T08:35:12.000Z
src/LuaState.cpp
guwere/luapath
d782070ec8f04eef9161baeb2db9f5dcc87a008b
[ "MIT" ]
null
null
null
src/LuaState.cpp
guwere/luapath
d782070ec8f04eef9161baeb2db9f5dcc87a008b
[ "MIT" ]
null
null
null
#include <iomanip> #include "luapath/LuaState.hpp" #include "luapath/LuaTypes.hpp" #include "luapath/exceptions.hpp" #include <lua.hpp> using std::cout; using std::endl; using std::setw; using std::string; namespace luapath{ LuaState::LuaState() :m_L(luaL_newstate()), loaded(false) { } LuaState::~LuaState() { close(); } void LuaState::close() { loaded = false; if (m_L) lua_close(m_L); m_L = nullptr; } void LuaState::loadString(const std::string& str) { int err = luaL_dostring(m_L, str.c_str()); if (err) { string errorStr(lua_tostring(m_L, -1)); close(); throw lua_state_exception(errorStr); } loaded = true; } void LuaState::loadFile(const string& filepath) { int err = luaL_dofile(m_L, filepath.c_str()); if (err) { string errorStr(lua_tostring(m_L, -1)); close(); throw lua_state_exception(errorStr); } loaded = true; } bool LuaState::isLoaded() const { return loaded; } Value LuaState::getGlobalValue(const string &fieldName) { lua_getglobal(m_L, fieldName.c_str()); int t = lua_type(m_L, -1); switch (t) { case LUA_TSTRING: return Value(Value::Type::STRING, lua_tostring(m_L, -1)); case LUA_TBOOLEAN: return Value(Value::Type::BOOL, lua_toboolean(m_L, -1) ? true : false); case LUA_TNUMBER: return Value(Value::Type::NUMBER, (float)lua_tonumber(m_L, -1)); case LUA_TNIL: throw path_lookup_exception(string("The search field - ").append(fieldName).append(" - could not be found")); default: throw type_mismatch_exception("The type of the result value is not one of : string, number or boolean"); } } Table LuaState::getGlobalTable(const string &tableName) { lua_getglobal(m_L, tableName.c_str()); int t = lua_type(m_L, -1); switch (t) { case LUA_TTABLE:{ Key key(tableName); Table root(key); getTableContents(root, -1); return root; } case LUA_TNIL: throw path_lookup_exception(string("The search field - ").append(tableName).append(" - could not be found")); default: throw type_mismatch_exception("The type of the result value is not a table"); } } void LuaState::getTableContents(Table &currTable, int tableIndex) { lua_pushnil(m_L); tableIndex--; try { while (lua_next(m_L, tableIndex) != 0) { Key key = getKey(-2); Value value = getValue(-1); if (value.type == Value::Type::TABLE) { currTable.nestedSet.emplace(std::make_pair(key, Table(key))); getTableContents(currTable.nestedSet.at(key), -1); } else { currTable.leafSet.emplace(std::make_pair(key, value)); } lua_pop(m_L, 1); } } catch (std::exception &e){ cout << "error: " << e.what() << endl; } } Key LuaState::getKey(int index) { int keyType = lua_type(m_L,index); switch (keyType) { case LUA_TSTRING: return Key(lua_tostring(m_L, index)); case LUA_TNUMBER: return Key(lua_tointeger(m_L, index)); default: throw type_mismatch_exception("Construction of a Key not possible from a stack value that is not either NUMBER or STRING"); } } Value LuaState::getValue(int index) { int valueType = lua_type(m_L, index); switch (valueType) { case LUA_TSTRING: return Value(Value::Type::STRING, lua_tostring(m_L, index)); case LUA_TBOOLEAN: return Value(Value::Type::BOOL, lua_toboolean(m_L, -1) ? true : false); case LUA_TNUMBER: return Value(Value::Type::NUMBER, (float)lua_tonumber(m_L, -1)); case LUA_TTABLE: //we still need to represent a table in a Value object because // later it will help with the traversal of the Table object return Value(Value::Type::TABLE, "->"); default: throw type_mismatch_exception("Construction of a Key not possible from a stack value that is not either NUMBER, STRING, BOOL or TABLE"); } } }
21.529412
138
0.698361
[ "object" ]
b08c0100270b982a4b65a7e84c7e1c9bac8fe402
32,043
hpp
C++
src/stan/variational/advi.hpp
stephensrmmartin/stan
e95c7bc9814792204ae8d900a1b47dfd17d88c0b
[ "CC-BY-3.0", "BSD-3-Clause" ]
null
null
null
src/stan/variational/advi.hpp
stephensrmmartin/stan
e95c7bc9814792204ae8d900a1b47dfd17d88c0b
[ "CC-BY-3.0", "BSD-3-Clause" ]
null
null
null
src/stan/variational/advi.hpp
stephensrmmartin/stan
e95c7bc9814792204ae8d900a1b47dfd17d88c0b
[ "CC-BY-3.0", "BSD-3-Clause" ]
null
null
null
#ifndef STAN_VARIATIONAL_ADVI_HPP #define STAN_VARIATIONAL_ADVI_HPP #include <stan/math.hpp> #include <stan/analyze/mcmc/autocovariance.hpp> #include <stan/analyze/mcmc/compute_effective_sample_size.hpp> #include <stan/analyze/mcmc/compute_potential_scale_reduction.hpp> #include <stan/analyze/mcmc/estimate_gpd_params.hpp> #include <stan/callbacks/logger.hpp> #include <stan/callbacks/writer.hpp> #include <stan/callbacks/stream_writer.hpp> #include <stan/io/dump.hpp> #include <stan/services/error_codes.hpp> #include <stan/variational/print_progress.hpp> #include <stan/variational/families/normal_fullrank.hpp> #include <stan/variational/families/normal_meanfield.hpp> #include <stan/variational/families/normal_lowrank.hpp> #include <boost/circular_buffer.hpp> #include <boost/lexical_cast.hpp> #include <algorithm> #include <chrono> #include <limits> #include <numeric> #include <ostream> #include <queue> #include <string> #include <vector> #include <cmath> namespace stan { namespace variational { /** * Automatic Differentiation Variational Inference * * Implements "black box" variational inference using stochastic gradient * ascent to maximize the Evidence Lower Bound for a given model * and variational family. This base class encapsulates the mean-field, * low-rank, and full-rank variational posterior classes. * * @tparam Model class of model * @tparam Q class of variational distribution * @tparam BaseRNG class of random number generator */ template <class Model, class Q, class BaseRNG> class advi_base { public: /** * Constructor * * @param[in] m stan model * @param[in] cont_params initialization of continuous parameters * @param[in,out] rng random number generator * @param[in] n_monte_carlo_grad number of samples for gradient computation * @param[in] n_monte_carlo_elbo number of samples for ELBO computation * @param[in] n_posterior_samples number of samples to draw from posterior * @throw std::runtime_error if n_monte_carlo_grad is not positive * @throw std::runtime_error if n_monte_carlo_elbo is not positive * @throw std::runtime_error if n_posterior_samples is not positive */ advi_base(Model& m, Eigen::VectorXd& cont_params, BaseRNG& rng, int n_monte_carlo_grad, int n_monte_carlo_elbo, int n_posterior_samples) : model_(m), cont_params_(cont_params), rng_(rng), n_monte_carlo_grad_(n_monte_carlo_grad), n_monte_carlo_elbo_(n_monte_carlo_elbo), n_posterior_samples_(n_posterior_samples) { static const char* function = "stan::variational::advi"; math::check_positive(function, "Number of Monte Carlo samples for gradients", n_monte_carlo_grad_); math::check_positive(function, "Number of Monte Carlo samples for ELBO", n_monte_carlo_elbo_); math::check_positive(function, "Number of posterior samples for output", n_posterior_samples_); } /** * Calculates the Evidence Lower BOund (ELBO) by sampling from * the variational distribution and then evaluating the log joint, * adjusted by the entropy term of the variational distribution. * * @param[in] variational variational approximation at which to evaluate * the ELBO. * @param logger logger for messages * @return the evidence lower bound. * @throw std::domain_error If, after n_monte_carlo_elbo_ number of draws * from the variational distribution all give non-finite log joint * evaluations. This means that the model is severely ill conditioned or * that the variational distribution has somehow collapsed. */ double calc_ELBO(const Q& variational, callbacks::logger& logger) const { static const char* function = "stan::variational::advi::calc_ELBO"; double elbo = 0.0; int dim = variational.dimension(); Eigen::VectorXd zeta(dim); int n_dropped_evaluations = 0; for (int i = 0; i < n_monte_carlo_elbo_;) { variational.sample(rng_, zeta); try { std::stringstream ss; double log_prob = model_.template log_prob<false, true>(zeta, &ss); if (ss.str().length() > 0) logger.info(ss); stan::math::check_finite(function, "log_prob", log_prob); elbo += log_prob; ++i; } catch (const std::domain_error& e) { ++n_dropped_evaluations; if (n_dropped_evaluations >= n_monte_carlo_elbo_) { const char* name = "The number of dropped evaluations"; const char* msg1 = "has reached its maximum amount ("; const char* msg2 = "). Your model may be either severely " "ill-conditioned or misspecified."; stan::math::throw_domain_error(function, name, n_monte_carlo_elbo_, msg1, msg2); } } } elbo /= n_monte_carlo_elbo_; elbo += variational.entropy(); return elbo; } /** * Calculates the "black box" gradient of the ELBO. * * @param[in] variational variational approximation at which to evaluate * the ELBO. * @param[out] elbo_grad gradient of ELBO with respect to variational * approximation. * @param logger logger for messages */ void calc_ELBO_grad(const Q& variational, Q& elbo_grad, callbacks::logger& logger) const { static const char* function = "stan::variational::advi::calc_ELBO_grad"; stan::math::check_size_match( function, "Dimension of elbo_grad", elbo_grad.dimension(), "Dimension of variational q", variational.dimension()); stan::math::check_size_match( function, "Dimension of variational q", variational.dimension(), "Dimension of variables in model", cont_params_.size()); variational.calc_grad(elbo_grad, model_, cont_params_, n_monte_carlo_grad_, rng_, logger); } /** * Heuristic grid search to adapt eta to the scale of the problem. * * @param[in] variational initial variational distribution. * @param[in] adapt_iterations number of iterations to spend doing stochastic * gradient ascent at each proposed eta value. * @param[in,out] logger logger for messages * @return adapted (tuned) value of eta via heuristic grid search * @throw std::domain_error If either (a) the initial ELBO cannot be * computed at the initial variational distribution, (b) all step-size * proposals in eta_sequence fail. */ double adapt_eta(Q& variational, int adapt_iterations, callbacks::logger& logger) const { static const char* function = "stan::variational::advi::adapt_eta"; stan::math::check_positive(function, "Number of adaptation iterations", adapt_iterations); logger.info("Begin eta adaptation."); // Sequence of eta values to try during adaptation const int eta_sequence_size = 5; double eta_sequence[eta_sequence_size] = {100, 10, 1, 0.1, 0.01}; // Initialize ELBO tracking variables double elbo = -std::numeric_limits<double>::max(); double elbo_best = -std::numeric_limits<double>::max(); double elbo_init; try { elbo_init = calc_ELBO(variational, logger); } catch (const std::domain_error& e) { const char* name = "Cannot compute ELBO using the initial " "variational distribution."; const char* msg1 = "Your model may be either " "severely ill-conditioned or misspecified."; stan::math::throw_domain_error(function, name, "", msg1); } // Variational family to store gradients Q elbo_grad = init_variational(model_.num_params_r()); // Adaptive step-size sequence Q history_grad_squared = init_variational(model_.num_params_r()); double tau = 1.0; double pre_factor = 0.9; double post_factor = 0.1; double eta_best = 0.0; double eta; double eta_scaled; bool do_more_tuning = true; int eta_sequence_index = 0; while (do_more_tuning) { // Try next eta eta = eta_sequence[eta_sequence_index]; int print_progress_m; for (int iter_tune = 1; iter_tune <= adapt_iterations; ++iter_tune) { print_progress_m = eta_sequence_index * adapt_iterations + iter_tune; variational ::print_progress(print_progress_m, 0, adapt_iterations * eta_sequence_size, adapt_iterations, true, "", "", logger); // (ROBUST) Compute gradient of ELBO. It's OK if it diverges. // We'll try a smaller eta. try { calc_ELBO_grad(variational, elbo_grad, logger); } catch (const std::domain_error& e) { elbo_grad.set_to_zero(); } // Update step-size if (iter_tune == 1) { history_grad_squared += elbo_grad.square(); } else { history_grad_squared = pre_factor * history_grad_squared + post_factor * elbo_grad.square(); } eta_scaled = eta / sqrt(static_cast<double>(iter_tune)); // Stochastic gradient update variational += eta_scaled * elbo_grad / (tau + history_grad_squared.sqrt()); } // (ROBUST) Compute ELBO. It's OK if it has diverged. try { elbo = calc_ELBO(variational, logger); } catch (const std::domain_error& e) { elbo = -std::numeric_limits<double>::max(); } // Check if: // (1) ELBO at current eta is worse than the best ELBO // (2) the best ELBO hasn't gotten worse than the initial ELBO if (elbo < elbo_best && elbo_best > elbo_init) { std::stringstream ss; ss << "Success!" << " Found best value [eta = " << eta_best << "]"; if (eta_sequence_index < eta_sequence_size - 1) ss << (" earlier than expected."); else ss << "."; logger.info(ss); logger.info(""); do_more_tuning = false; } else { if (eta_sequence_index < eta_sequence_size - 1) { // Reset elbo_best = elbo; eta_best = eta; } else { // No more eta values to try, so use current eta if it // didn't diverge or fail if it did diverge if (elbo > elbo_init) { std::stringstream ss; ss << "Success!" << " Found best value [eta = " << eta_best << "]."; logger.info(ss); logger.info(""); eta_best = eta; do_more_tuning = false; } else { const char* name = "All proposed step-sizes"; const char* msg1 = "failed. Your model may be either " "severely ill-conditioned or misspecified."; stan::math::throw_domain_error(function, name, "", msg1); } } // Reset history_grad_squared.set_to_zero(); } ++eta_sequence_index; variational = init_variational(cont_params_); } return eta_best; } /** * Run Robust Variational Inference. * A. Dhaka et al., 2020 * * @param[in] eta eta parameter of stepsize sequence * @param[in] adapt_engaged boolean flag for eta adaptation * @param[in] adapt_iterations number of iterations for eta adaptation * @param[in] max_iterations max number of iterations to run algorithm * @param[in] eval_window Interval to calculate termination conditions * @param[in] window_size Proportion of eval_window samples to calculate * Rhat for termination condition * @param[in] rhat_cut Rhat termination criteria * @param[in] mcse_cut MCSE termination criteria * @param[in] ess_cut effective sample size termination criteria * @param[in] num_chains Number of VI chains to run * @param[in,out] logger logger for messages * @param[in,out] parameter_writer writer for parameters * (typically to file) * @param[in,out] diagnostic_writer writer for diagnostic information */ int run(double eta, bool adapt_engaged, int adapt_iterations, int max_iterations, int eval_window, double window_size, double rhat_cut, double mcse_cut, double ess_cut, int num_chains, callbacks::logger& logger, callbacks::writer& parameter_writer, callbacks::writer& diagnostic_writer) const { diagnostic_writer("iter,time_in_seconds,ELBO"); // Initialize variational approximation Q variational = init_variational(cont_params_); std::stringstream ss; if (adapt_engaged) { eta = adapt_eta(variational, adapt_iterations, logger); parameter_writer("Stepsize adaptation complete."); ss << "eta = " << eta << " "; parameter_writer(ss.str()); } /////////////////// double khat, ess, mcse, max_rhat, rhat, eta_scaled; int T0 = max_iterations - 1; const int dim = variational.dimension(); const int n_approx_params = variational.num_approx_params(); std::vector<Q> variational_obj_vec; std::vector<Q> elbo_grad_vec; std::vector<Q> elbo_grad_square_vec; // for each chain, save variational parameter values on matrix // of dim (n_params, n_iters) typedef Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> histMat; std::vector<histMat> hist_vector; hist_vector.reserve(num_chains); variational_obj_vec.reserve(num_chains); elbo_grad_vec.reserve(num_chains); elbo_grad_square_vec.reserve(num_chains); for(int i = 0; i < num_chains; i++){ hist_vector.push_back(histMat(n_approx_params, max_iterations)); variational_obj_vec.push_back(init_variational(cont_params_)); elbo_grad_vec.push_back(init_variational(dim)); elbo_grad_square_vec.push_back(init_variational(dim)); } for (int n_iter = 0; n_iter < max_iterations; n_iter++){ eta_scaled = eta / sqrt(static_cast<double>(n_iter + 1)); for (int n_chain = 0; n_chain < num_chains; n_chain++){ calc_ELBO_grad(variational_obj_vec[n_chain], elbo_grad_vec[n_chain], logger); if (n_iter == 0) { elbo_grad_square_vec[n_chain] += elbo_grad_vec[n_chain].square(); } else { elbo_grad_square_vec[n_chain] = 0.9 * elbo_grad_square_vec[n_chain] + 0.1 * elbo_grad_vec[n_chain].square(); } variational_obj_vec[n_chain] += eta_scaled * elbo_grad_vec[n_chain] / (1.0 + elbo_grad_square_vec[n_chain].sqrt()); hist_vector[n_chain].col(n_iter) = variational_obj_vec[n_chain].return_approx_params(); } if ((n_iter % eval_window == 0 && n_iter > 0) || n_iter == max_iterations - 1){ max_rhat = std::numeric_limits<double>::lowest(); for(int k = 0; k < n_approx_params; k++) { std::vector<const double*> hist_ptrs; std::vector<size_t> chain_length; const int split_point = n_iter * (1.0 - window_size); // iteration index to start calculating rhat // so Rhat should be calculated for iters [split_point, n_iter] if(num_chains == 1){ // use split rhat chain_length.assign(2, static_cast<size_t>((n_iter - split_point + 1) / 2)); hist_ptrs.push_back(hist_vector[0].row(k).data() + split_point); hist_ptrs.push_back(hist_ptrs[0] + chain_length[0]); } else{ for(int i = 0; i < num_chains; i++){ //chain_length.push_back(static_cast<size_t>(n_iter * window_size)); //hist_ptrs.push_back(hist_vector[i].row(k).data()); // multi-chain split rhat (split each chain into 2) chain_length.insert(chain_length.end(), 2, static_cast<size_t>((n_iter - split_point + 1) / 2)); hist_ptrs.push_back(hist_vector[i].row(k).data() + split_point); hist_ptrs.push_back(hist_vector[i].row(k).data() + split_point + chain_length[0]); } } rhat = stan::analyze::compute_potential_scale_reduction(hist_ptrs, chain_length); max_rhat = std::max<double>(max_rhat, rhat); } if (max_rhat < rhat_cut) { T0 = n_iter; ss << "Preliminary iterations terminated by rhat condition at iteration # " << T0 << " with max reported Rhat value of " << max_rhat << "\n"; break; } } } bool khat_failed = false; for(int k = 0; k < num_chains; k++){ Eigen::VectorXd lw_vec(n_posterior_samples_); lr(variational_obj_vec[k], lw_vec); double sigma, max_lw; int n_tail; if(n_posterior_samples_ < 225) { n_tail = int(lw_vec.size() * 0.2); } else{ n_tail = 3 * sqrt(lw_vec.size()); // if more than 225 samples 3 * sqrt(lw_vec.size()) } max_lw = lw_vec.maxCoeff(); lw_vec = lw_vec.array() - max_lw; lw_vec = lw_vec.array().exp() - std::exp(lw_vec(n_tail)); lw_vec = lw_vec.head(n_tail); stan::analyze::gpdfit(lw_vec, khat, sigma); ss << "Chain " << k << " khat: " << khat << "\n"; if(khat > 1.0) { khat_failed = true; break; } } if (khat_failed || max_rhat > rhat_cut) { logger.warn("Optimization may have not converged"); ss << " max_rhat: " << max_rhat << " rhat_cut: " << rhat_cut << "\n"; // avarage parameters from the last eval_window param iterations for(int i = 0; i < num_chains; i++){ variational_obj_vec[i].set_approx_params( hist_vector[i].block(0, T0 - eval_window + 1, n_approx_params, eval_window).rowwise().mean()); } } else { ss << "Start secondary iteration at step #: " << T0 << "\n"; for(int n_post_iter = T0; n_post_iter < max_iterations; n_post_iter++){ eta_scaled = eta / sqrt(static_cast<double>(n_post_iter + 1)); for (int n_chain = 0; n_chain < num_chains; n_chain++){ calc_ELBO_grad(variational_obj_vec[n_chain], elbo_grad_vec[n_chain], logger); elbo_grad_square_vec[n_chain] = 0.9 * elbo_grad_square_vec[n_chain] + 0.1 * elbo_grad_vec[n_chain].square(); variational_obj_vec[n_chain] += eta_scaled * elbo_grad_vec[n_chain] / elbo_grad_square_vec[n_chain].sqrt(); hist_vector[n_chain].col(n_post_iter) = variational_obj_vec[n_chain].return_approx_params(); } if ((n_post_iter - T0) % eval_window == 0 && (n_post_iter - T0) > 0) { double min_ess = std::numeric_limits<double>::infinity(), max_mcse = std::numeric_limits<double>::lowest(); for(int k = 0; k < n_approx_params; k++){ std::vector<const double*> hist_ptrs; std::vector<size_t> chain_length; if(num_chains == 1){ // split chain calculation chain_length.assign(2, static_cast<size_t>((n_post_iter - T0 + 1) / 2)); hist_ptrs.push_back(hist_vector[0].row(k).data() + T0); hist_ptrs.push_back(hist_ptrs[0] + chain_length[0]); } else { for(int i = 0; i < num_chains; i++){ chain_length.push_back(static_cast<size_t>(n_post_iter - T0 + 1)); hist_ptrs.push_back(hist_vector[i].row(k).data() + T0); } } double ess, mcse; ESS_MCSE(ess, mcse, hist_ptrs, chain_length); min_ess = std::min<double>(min_ess, ess); max_mcse = std::max<double>(max_mcse, mcse); } if(max_mcse < mcse_cut && min_ess > ess_cut){ ss << "Second iteration break condition reached at iteration # " << n_post_iter << "\n"; ss << "min ESS: " << min_ess << " max MCSE: " << max_mcse << "\n"; for(int i = 0; i < num_chains; i++){ variational_obj_vec[i].set_approx_params( hist_vector[i].block(0, T0, n_approx_params, n_post_iter - T0 + 1).rowwise().mean()); } break; } } } } variational.set_to_zero(); for(int i = 0; i < num_chains; i++){ variational += 1.0 / num_chains * variational_obj_vec[i]; } ss << "Finished optimization" << "\n"; for(int i = 0; i < num_chains; i++){ ss << "Chain " << i << " mean:\n" << variational_obj_vec[i].mean() << "\n"; } ss << "----\nQ variational:\n" << variational.mean() << "\n----\n"; ss << "Num of Model params: " << dim << "\n"; ss << "Num of Approx params: " << n_approx_params << "\n"; logger.info(ss); /////////////////// // Write posterior mean of variational approximations. cont_params_ = variational.mean(); std::vector<double> cont_vector(cont_params_.size()); for (int i = 0; i < cont_params_.size(); ++i) cont_vector.at(i) = cont_params_(i); std::vector<int> disc_vector; std::vector<double> values; /*std::stringstream msg; model_.write_array(rng_, cont_vector, disc_vector, values, true, true, &msg); if (msg.str().length() > 0) logger.info(msg); // The first row of lp_, log_p, log_g, and chain_id. values.insert(values.begin(), {0, 0, 0, -1}); parameter_writer(values);*/ // Draw more from posterior and write on subsequent lines logger.info(""); std::stringstream ss2; ss2 << "Drawing a sample of size " << n_posterior_samples_ << " from the approximate posterior... "; logger.info(ss2); double log_p = 0; double log_g = 0; // Draw posterior sample. log_g is the log normal densities. Eigen::VectorXd chain_params(cont_params_.size()); for (int n = 0; n < n_posterior_samples_; ++n) { for (int k = 0; k < num_chains; k++){ chain_params = variational_obj_vec[k].mean(); variational_obj_vec[k].sample_log_g(rng_, chain_params, log_g); for (int i = 0; i < chain_params.size(); ++i) { cont_vector.at(i) = chain_params(i); } std::stringstream msg2; model_.write_array(rng_, cont_vector, disc_vector, values, true, true, &msg2); // log_p: Log probability in the unconstrained space log_p = model_.template log_prob<false, true>(chain_params, &msg2); if (msg2.str().length() > 0) logger.info(msg2); // Write lp__, log_p, log_g, and chain_id. values.insert(values.begin(), {0.0, log_p, log_g, static_cast<double>(k)}); parameter_writer(values); } } logger.info("COMPLETED."); return stan::services::error_codes::OK; } /** * RVI Diagnostics: Calculates log importance weights * * @param[in] variational_obj variational family object * @param[in, out] weight_vector An Eigen * dynamic vector of weights, sorted in descending order */ void lr(const Q& variational_obj, Eigen::VectorXd& weight_vector) const { // Need to check the vector is empty weight_vector.resize(n_posterior_samples_); double log_p, log_g; std::stringstream msg2; Eigen::VectorXd draws(variational_obj.dimension()); // Draw posterior sample. log_g is the log normal densities. for (int n = 0; n < n_posterior_samples_; ++n) { variational_obj.sample_log_g(rng_, draws, log_g); // log_p: Log probability in the unconstrained space log_p = model_.template log_prob<false, true>(draws, &msg2); weight_vector(n) = log_p - log_g; } // sort descending order std::sort(weight_vector.data(), weight_vector.data() + weight_vector.size(), std::greater<double>()); } /** * RVI Diagnostics * Estimate the Effective Sample Size and Monte Carlo Standard Error of posterior samples where * MCSE = sqrt( var(parmas) / ess) * @param[in] samples An Eigen::VectorXd containing posterior samples @TODO rewrite from here * @param[in] ess If specified, will be used as effective sample size instead * of calling compute_effective_sample_size() * * @return Calculated MCSE */ static double ESS_MCSE(double &ess, double &mcse, const std::vector<const double*> draws, const std::vector<size_t> sizes) { int num_chains = sizes.size(); size_t num_draws = sizes[0]; for (int chain = 1; chain < num_chains; ++chain) { num_draws = std::min(num_draws, sizes[chain]); } if (num_draws < 4) { ess = std::numeric_limits<double>::quiet_NaN(); mcse = std::numeric_limits<double>::quiet_NaN(); return std::numeric_limits<double>::quiet_NaN(); } // check if chains are constant; all equal to first draw's value bool are_all_const = false; Eigen::VectorXd init_draw = Eigen::VectorXd::Zero(num_chains); for (int chain_idx = 0; chain_idx < num_chains; chain_idx++) { Eigen::Map<const Eigen::Matrix<double, Eigen::Dynamic, 1>> draw( draws[chain_idx], sizes[chain_idx]); for (int n = 0; n < num_draws; n++) { if (!std::isfinite(draw(n))) { ess = std::numeric_limits<double>::quiet_NaN(); mcse = std::numeric_limits<double>::quiet_NaN(); return std::numeric_limits<double>::quiet_NaN(); } } init_draw(chain_idx) = draw(0); if (draw.isApproxToConstant(draw(0))) { are_all_const |= true; } } if (are_all_const) { // If all chains are constant then return NaN // if they all equal the same constant value if (init_draw.isApproxToConstant(init_draw(0))) { ess = std::numeric_limits<double>::quiet_NaN();; mcse = std::numeric_limits<double>::quiet_NaN(); return std::numeric_limits<double>::quiet_NaN(); } } Eigen::Matrix<Eigen::VectorXd, Eigen::Dynamic, 1> acov(num_chains); Eigen::VectorXd chain_mean(num_chains); Eigen::VectorXd chain_sq_mean(num_chains); Eigen::VectorXd chain_var(num_chains); for (int chain = 0; chain < num_chains; ++chain) { Eigen::Map<const Eigen::Matrix<double, Eigen::Dynamic, 1>> draw( draws[chain], sizes[chain]); stan::analyze::autocovariance<double>(draw, acov(chain)); chain_mean(chain) = draw.mean(); chain_sq_mean(chain) = draw.array().square().mean(); chain_var(chain) = acov(chain)(0) * num_draws / (num_draws - 1); } double mean_var = chain_var.mean(); double var_plus = mean_var * (num_draws - 1) / num_draws; if (num_chains > 1) var_plus += math::variance(chain_mean); Eigen::VectorXd rho_hat_s(num_draws); rho_hat_s.setZero(); Eigen::VectorXd acov_s(num_chains); for (int chain = 0; chain < num_chains; ++chain) acov_s(chain) = acov(chain)(1); double rho_hat_even = 1.0; rho_hat_s(0) = rho_hat_even; double rho_hat_odd = 1 - (mean_var - acov_s.mean()) / var_plus; rho_hat_s(1) = rho_hat_odd; // Convert raw autocovariance estimators into Geyer's initial // positive sequence. Loop only until num_draws - 4 to // leave the last pair of autocorrelations as a bias term that // reduces variance in the case of antithetical chains. size_t s = 1; while (s < (num_draws - 4) && (rho_hat_even + rho_hat_odd) > 0) { for (int chain = 0; chain < num_chains; ++chain) acov_s(chain) = acov(chain)(s + 1); rho_hat_even = 1 - (mean_var - acov_s.mean()) / var_plus; for (int chain = 0; chain < num_chains; ++chain) acov_s(chain) = acov(chain)(s + 2); rho_hat_odd = 1 - (mean_var - acov_s.mean()) / var_plus; if ((rho_hat_even + rho_hat_odd) >= 0) { rho_hat_s(s + 1) = rho_hat_even; rho_hat_s(s + 2) = rho_hat_odd; } s += 2; } int max_s = s; // this is used in the improved estimate, which reduces variance // in antithetic case -- see tau_hat below if (rho_hat_even > 0) rho_hat_s(max_s + 1) = rho_hat_even; // Convert Geyer's initial positive sequence into an initial // monotone sequence for (int s = 1; s <= max_s - 3; s += 2) { if (rho_hat_s(s + 1) + rho_hat_s(s + 2) > rho_hat_s(s - 1) + rho_hat_s(s)) { rho_hat_s(s + 1) = (rho_hat_s(s - 1) + rho_hat_s(s)) / 2; rho_hat_s(s + 2) = rho_hat_s(s + 1); } } double num_total_draws = num_chains * num_draws; // Geyer's truncated estimator for the asymptotic variance // Improved estimate reduces variance in antithetic case double tau_hat = -1 + 2 * rho_hat_s.head(max_s).sum() + rho_hat_s(max_s + 1); double ess_val = num_total_draws / tau_hat; ess = ess_val; mcse = std::sqrt((chain_sq_mean.mean() - chain_mean.mean() * chain_mean.mean())/ess_val); return 0; } protected: Model& model_; Eigen::VectorXd& cont_params_; BaseRNG& rng_; int n_monte_carlo_grad_; int n_monte_carlo_elbo_; int n_posterior_samples_; private: virtual Q init_variational(Eigen::VectorXd& cont_params) const = 0; virtual Q init_variational(size_t dimension) const = 0; }; /** * The ADVI implementation used for meanfield and full-rank approximations. * * @tparam Model Class of model * @tparam Q Class of variational distribution, either mean-field or low-rank. * @tparam BaseRNG Class of random number generator */ template <class Model, class Q, class BaseRNG> class advi : public advi_base<Model, Q, BaseRNG> { public: advi(Model& m, Eigen::VectorXd& cont_params, BaseRNG& rng, int n_monte_carlo_grad, int n_monte_carlo_elbo, int n_posterior_samples) : advi_base<Model, Q, BaseRNG>(m, cont_params, rng, n_monte_carlo_grad, n_monte_carlo_elbo, n_posterior_samples) {} private: Q init_variational(Eigen::VectorXd& cont_params) const { return Q(cont_params); } Q init_variational(size_t dimension) const { return Q(dimension); } }; /** * The ADVI implementation used only for low-rank approximations. * * @tparam Model Class of model. * @tparam BaseRNG Class of random number generator. */ template <class Model, class BaseRNG> class advi_lowrank : public advi_base<Model, stan::variational::normal_lowrank, BaseRNG> { public: /** * Constructor * * @param[in] m stan model * @param[in] cont_params initialization of continuous parameters * @param[in,out] rng random number generator * @param[in] rank rank of approximation * @param[in] n_monte_carlo_grad number of samples for gradient computation * @param[in] n_monte_carlo_elbo number of samples for ELBO computation * @param[in] eval_elbo evaluate ELBO at every "eval_elbo" iters * @param[in] n_posterior_samples number of samples to draw from posterior * @throw std::runtime_error if n_monte_carlo_grad is not positive * @throw std::runtime_error if n_monte_carlo_elbo is not positive * @throw std::runtime_error if eval_elbo is not positive * @throw std::runtime_error if n_posterior_samples is not positive */ advi_lowrank(Model& m, Eigen::VectorXd& cont_params, BaseRNG& rng, size_t rank, int n_monte_carlo_grad, int n_monte_carlo_elbo, int n_posterior_samples) : advi_base<Model, stan::variational::normal_lowrank, BaseRNG>( m, cont_params, rng, n_monte_carlo_grad, n_monte_carlo_elbo, n_posterior_samples), rank_(rank) { static const char* function = "stan::variational::advi_lowrank"; math::check_positive(function, "Approximation rank", rank_); } protected: size_t rank_; private: stan::variational::normal_lowrank init_variational( Eigen::VectorXd& cont_params) const { return stan::variational::normal_lowrank(cont_params, rank_); } stan::variational::normal_lowrank init_variational(size_t dimension) const { return stan::variational::normal_lowrank(dimension, rank_); } }; } // namespace variational } // namespace stan #endif
39.461823
123
0.633461
[ "object", "vector", "model" ]
b08ed886982d9928557035449b9ef6113bf9296f
2,803
hpp
C++
OcularCore/include/Scene/SceneLoader/SceneObjectLoader.hpp
ssell/OcularEngine
c80cc4fcdb7dd7ce48d3af330bd33d05312076b1
[ "Apache-2.0" ]
8
2017-01-27T01:06:06.000Z
2020-11-05T20:23:19.000Z
OcularCore/include/Scene/SceneLoader/SceneObjectLoader.hpp
ssell/OcularEngine
c80cc4fcdb7dd7ce48d3af330bd33d05312076b1
[ "Apache-2.0" ]
39
2016-06-03T02:00:36.000Z
2017-03-19T17:47:39.000Z
OcularCore/include/Scene/SceneLoader/SceneObjectLoader.hpp
ssell/OcularEngine
c80cc4fcdb7dd7ce48d3af330bd33d05312076b1
[ "Apache-2.0" ]
4
2019-05-22T09:13:36.000Z
2020-12-01T03:17:45.000Z
/** * Copyright 2014-2017 Steven T Sell (ssell@vertexfragment.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. */ #pragma once #ifndef __H__OCULAR_CORE_SCENE_OBJECT_LOADER__H__ #define __H__OCULAR_CORE_SCENE_OBJECT_LOADER__H__ #include "FileIO/File.hpp" //------------------------------------------------------------------------------------------ /** * \addtogroup Ocular * @{ */ namespace Ocular { /** * \addtogroup Core * @{ */ namespace Core { class SceneObject; struct Node_Internal; /** * \class SceneObjectLoader * \brief Handles the loading of .opre files (Ocular Predefined Scene Object) * * Loads .opre files as instances of SceneObjects. * * As a SceneObject is not a Resource, this loader is a standalone class separate from the standard * loader/saver pattern found within the Resource subsystem. */ class SceneObjectLoader { public: /** * Attempts to the load the SceneObject from the specified .opre file. * * \param[in] file * * \return The new SceneObject. The object is already owned by the primary SceneManager (OcularScene), * and as such should not be manually destroyed. Returns NULL if failed to load. */ static SceneObject* Load(File const& file); /** * Attempts to the load the SceneObject from the provided node. * \note This is generally for internal use only by other loaders (ie SceneLoader) * * \param[in] node * * \return The new SceneObject. The object is already owned by the primary SceneManager (OcularScene), * and as such should not be manually destroyed. Returns NULL if failed to load. */ static SceneObject* Load(Node_Internal* node); protected: static bool IsValidFile(File const& file); private: }; } /** * @} End of Doxygen Groups */ } /** * @} End of Doxygen Groups */ //------------------------------------------------------------------------------------------ #endif
30.802198
114
0.570817
[ "object" ]
b09db865bd60c394e525aa77ada91750c6931d54
2,131
cc
C++
xdl/ps-plus/ps-plus/common/file_system/none_file_system.cc
Ru-Xiang/x-deeplearning
04cc0497150920c64b06bb8c314ef89977a3427a
[ "Apache-2.0" ]
4,071
2018-12-13T04:17:38.000Z
2022-03-30T03:29:35.000Z
xdl/ps-plus/ps-plus/common/file_system/none_file_system.cc
laozhuang727/x-deeplearning
781545783a4e2bbbda48fc64318fb2c6d8bbb3cc
[ "Apache-2.0" ]
359
2018-12-21T01:14:57.000Z
2022-02-15T07:18:02.000Z
xdl/ps-plus/ps-plus/common/file_system/none_file_system.cc
laozhuang727/x-deeplearning
781545783a4e2bbbda48fc64318fb2c6d8bbb3cc
[ "Apache-2.0" ]
1,054
2018-12-20T09:57:42.000Z
2022-03-29T07:16:53.000Z
/* Copyright (C) 2016-2018 Alibaba Group Holding 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 "ps-plus/common/file_system.h" namespace ps { class NoneFileSystem : public FileSystem { public: class NoneReadStream : public ReadStream { public: virtual ~NoneReadStream() {Close();} virtual int64_t ReadSimple(void* buf, size_t size) override { return 0; } protected: virtual void CloseInternal() override { } }; class NoneWriteStream : public WriteStream { public: virtual ~NoneWriteStream() {Close();} virtual int64_t WriteSimple(const void* buf, size_t size) override { return 0; } virtual void Flush() override { } protected: virtual void CloseInternal() { } }; virtual Status OpenReadStream(const std::string& name, ReadStream** result) override { return Status::NotFound("not found"); } virtual Status OpenWriteStream(const std::string& name, WriteStream** result, bool append = false) override { *result = new NoneWriteStream; return Status::Ok(); } virtual Status Mkdir(const std::string& name) override { return Status::Ok(); } virtual Status ListDirectory(const std::string& name, std::vector<std::string>* results) override { return Status::Ok(); } virtual Status Remove(const std::string& name) override { return Status::Ok(); } virtual Status Rename(const std::string& src_name, const std::string& dst_name) override { return Status::Ok(); } }; PLUGIN_REGISTER(FileSystem, none, NoneFileSystem); }
28.039474
111
0.68184
[ "vector" ]
b0ab8fbf8140634bbcf4dddae8ff8af985216cc9
3,274
cpp
C++
src/base/src/shapes.cpp
N4G170/generic
29c8be184b1420b811e2a3db087f9bd6b76ed8bf
[ "MIT" ]
null
null
null
src/base/src/shapes.cpp
N4G170/generic
29c8be184b1420b811e2a3db087f9bd6b76ed8bf
[ "MIT" ]
null
null
null
src/base/src/shapes.cpp
N4G170/generic
29c8be184b1420b811e2a3db087f9bd6b76ed8bf
[ "MIT" ]
null
null
null
#include "shapes.hpp" #include "SDL.h" void DrawCircunference(SDL_Renderer* renderer, int centre_x, int centre_y, int radius, SDL_Colour colour) { SDL_SetRenderDrawColor( renderer, colour.r, colour.g, colour.b, colour.a ); //draw circunference int cos45 = static_cast<int>(SquareRoot(2)/2 * radius); int squared_radius = radius * radius; for (int x = 0; x <= cos45; ++x) { int y = static_cast<int>(SquareRoot((double)squared_radius - x * x));//if + makes vegeta head vein SDL_RenderDrawPoint(renderer, x + centre_x, y + centre_y); SDL_RenderDrawPoint(renderer, x + centre_x, -y + centre_y); SDL_RenderDrawPoint(renderer, -x + centre_x, y + centre_y); SDL_RenderDrawPoint(renderer, -x + centre_x, -y + centre_y); SDL_RenderDrawPoint(renderer, y + centre_x, x + centre_y); SDL_RenderDrawPoint(renderer, y + centre_x, -x + centre_y); SDL_RenderDrawPoint(renderer, -y + centre_x, x + centre_y); SDL_RenderDrawPoint(renderer, -y + centre_x, -x + centre_y); } } void DrawCircle(SDL_Renderer* renderer, int centre_x, int centre_y, int radius, SDL_Colour border_colour, SDL_Colour fill_colour) { // //draw circunference // DrawCircunference(renderer, centre_x, centre_y, radius, border_colour); SDL_SetRenderDrawColor( renderer, fill_colour.r, fill_colour.g, fill_colour.b, fill_colour.a ); //fill circle int diagonal = radius * 2;//inner square diagonal int side = diagonal / SquareRoot(2);//inner square side int half_side = side / 2; int squared_radius = radius * radius; SDL_Rect square{ centre_x - half_side, centre_y - half_side, side, side }; SDL_RenderFillRect(renderer, &square); for(int x = -half_side; x <= half_side; ++x) { for(int y = half_side; y <= radius; ++y) { if(x*x + y*y <= squared_radius) { SDL_RenderDrawPoint(renderer, x + centre_x, y + centre_y); SDL_RenderDrawPoint(renderer, x + centre_x, -y + centre_y); SDL_RenderDrawPoint(renderer, y + centre_x, x + centre_y); SDL_RenderDrawPoint(renderer, -y + centre_x, x + centre_y); } } } //draw circunference - at the end to be able to render a border with another color DrawCircunference(renderer, centre_x, centre_y, radius, border_colour); } void GenerateCircunferenceFirstOctantSDLPoints(int radius, std::vector<SDL_Point>& points) { //draw circunference int cos45 = static_cast<int>(SquareRoot(2)/2 * radius); int squared_radius = radius * radius; for (int x = 0; x <= cos45; ++x) points.push_back( {x, -(static_cast<int>(SquareRoot((double)squared_radius - x * x))) });//O1 } void GenerateCircleFirstOctantSDLPoints(int radius, std::vector<SDL_Point>& points) { GenerateCircunferenceFirstOctantSDLPoints(radius, points); //fill circle int squared_radius = radius * radius; int cos45 = static_cast<int>(SquareRoot(2)/2 * radius); for(int x = 0; x <= radius; ++x) { for(int y = 0; y <= cos45 && y <= x; ++y) { if(x*x + y*y <= squared_radius) { points.push_back({x, -y});//O1 } } } }
36.786517
129
0.63653
[ "render", "vector" ]
b0b9fd67d63bbb9d001d0a81b9b02343c2fb9bd5
1,037
cpp
C++
src/AdventOfCode2017/Day05-MazeOfTrampolines/Day05-MazeOfTrampolines.cpp
dbartok/advent-of-code-cpp
c8c2df7a21980f8f3e42128f7bc5df8288f18490
[ "MIT" ]
null
null
null
src/AdventOfCode2017/Day05-MazeOfTrampolines/Day05-MazeOfTrampolines.cpp
dbartok/advent-of-code-cpp
c8c2df7a21980f8f3e42128f7bc5df8288f18490
[ "MIT" ]
null
null
null
src/AdventOfCode2017/Day05-MazeOfTrampolines/Day05-MazeOfTrampolines.cpp
dbartok/advent-of-code-cpp
c8c2df7a21980f8f3e42128f7bc5df8288f18490
[ "MIT" ]
null
null
null
#include "Day05-MazeOfTrampolines.h" #include <AdventOfCodeCommon/DisableLibraryWarningsMacros.h> __BEGIN_LIBRARIES_DISABLE_WARNINGS #include <functional> __END_LIBRARIES_DISABLE_WARNINGS namespace AdventOfCode { namespace Year2017 { namespace Day05 { unsigned stepsWithInstructionModifierFunc(std::vector<int> instructions, std::function<void(int&)> modifierFunc) { int position = 0; unsigned steps = 0; while (position >= 0 && position < instructions.size()) { int newPosition = position + instructions[position]; modifierFunc(instructions[position]); position = newPosition; ++steps; } return steps; } unsigned stepsInstructionsIncreasing(const std::vector<int>& instructions) { return stepsWithInstructionModifierFunc(instructions, [](int& i) noexcept { ++i; }); } unsigned stepsInstructionsIncreasingDecreasing(const std::vector<int>& instructions) { return stepsWithInstructionModifierFunc(instructions, [](int& i) noexcept { i >= 3 ? --i : ++i; }); } } } }
23.044444
112
0.726133
[ "vector" ]
b0c1ee02491661a78abf8812447d0df9bd0d16fc
3,210
hpp
C++
include/aluminum/utils/locked_resource_pool.hpp
shjwudp/Aluminum
046c209adc160522ee557ad5022fe372b738d38a
[ "Apache-2.0" ]
48
2018-09-28T22:09:25.000Z
2021-11-18T05:24:53.000Z
include/aluminum/utils/locked_resource_pool.hpp
PrisdxMeany/Aluminum
49dbbde15ea2202eb0fe246da73ccf39df59e2e2
[ "Apache-2.0" ]
51
2018-09-26T21:03:50.000Z
2021-11-12T18:21:12.000Z
include/aluminum/utils/locked_resource_pool.hpp
PrisdxMeany/Aluminum
49dbbde15ea2202eb0fe246da73ccf39df59e2e2
[ "Apache-2.0" ]
19
2018-09-14T23:01:53.000Z
2021-08-12T04:13:18.000Z
//////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2018, Lawrence Livermore National Security, LLC. Produced at the // Lawrence Livermore National Laboratory in collaboration with University of // Illinois Urbana-Champaign. // // Written by the LBANN Research Team (N. Dryden, N. Maruyama, et al.) listed in // the CONTRIBUTORS file. <lbann-dev@llnl.gov> // // LLNL-CODE-756777. // All rights reserved. // // This file is part of Aluminum GPU-aware Communication Library. For details, see // http://software.llnl.gov/Aluminum or https://github.com/LLNL/Aluminum. // // Licensed under the Apache License, Version 2.0 (the "Licensee"); 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. //////////////////////////////////////////////////////////////////////////////// #pragma once #include <Al_config.hpp> #include <stddef.h> #include <mutex> #include <vector> namespace Al { namespace internal { /** * Provides thread-safe access to a set of identical resources. * * These resources could be things like a fixed-size chunk of memory. * * ResourceAllocator must provide allocate and deallocate methods to * create and destroy (resp.) the managed resource (T). * * LockedResourcePool will guarantee that each instance of the * ResourceAllocator will be accessed by only a single thread at a * time. If additional locking is necessary for correctness, the * ResourceAllocator must provide it. */ template <typename T, typename ResourceAllocator> class LockedResourcePool { public: /** Initialize the resource pool. */ LockedResourcePool(){}; ~LockedResourcePool() { clear(); } /** Preallocate this many instances of the resource. */ void preallocate(size_t prealloc) { for (size_t i = 0; i < prealloc; ++i) { resources.push_back(allocator.allocate()); } } /** Get one instance of the resource. */ T get() { std::lock_guard<std::mutex> lg(lock); if (resources.empty()) { return allocator.allocate(); } else { T resource = resources.back(); resources.pop_back(); return resource; } } /** Return an instance of the resource to the pool. */ void release(T resource) { std::lock_guard<std::mutex> lg(lock); resources.push_back(resource); } /** Clear all instances left in the pool. */ void clear() { std::lock_guard<std::mutex> lg(lock); for (auto&& resource : resources) { allocator.deallocate(resource); } resources.clear(); } private: /** Protects access to allocator and resource. */ std::mutex lock; /** Allocator for the resource. */ ResourceAllocator allocator; /** Currently available resources. */ std::vector<T> resources; }; } // namespace internal } // namespace Al
30
82
0.663863
[ "vector" ]
37d4877c6264b109f4e625cd61be57cad7cc6da3
60,487
cxx
C++
inetsrv/iis/iisrearc/iisplus/ulw3/isapi_handler.cxx
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
inetsrv/iis/iisrearc/iisplus/ulw3/isapi_handler.cxx
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
inetsrv/iis/iisrearc/iisplus/ulw3/isapi_handler.cxx
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
/*++ Copyright (c) 1999 Microsoft Corporation Module Name : isapi_handler.cxx Abstract: Handle ISAPI extension requests Author: Taylor Weiss (TaylorW) 27-Jan-2000 Environment: Win32 - User Mode Project: ULW3.DLL --*/ #include <initguid.h> #include "precomp.hxx" #include "isapi_handler.h" #include <wmrgexp.h> #include <iisextp.h> #include <errno.h> HMODULE W3_ISAPI_HANDLER::sm_hIsapiModule; PFN_ISAPI_TERM_MODULE W3_ISAPI_HANDLER::sm_pfnTermIsapiModule; PFN_ISAPI_PROCESS_REQUEST W3_ISAPI_HANDLER::sm_pfnProcessIsapiRequest; PFN_ISAPI_PROCESS_COMPLETION W3_ISAPI_HANDLER::sm_pfnProcessIsapiCompletion; W3_INPROC_ISAPI_HASH * W3_ISAPI_HANDLER::sm_pInprocIsapiHash; CRITICAL_SECTION W3_ISAPI_HANDLER::sm_csInprocHashLock; CRITICAL_SECTION W3_ISAPI_HANDLER::sm_csBigHurkinWamRegLock; WAM_PROCESS_MANAGER * W3_ISAPI_HANDLER::sm_pWamProcessManager; BOOL W3_ISAPI_HANDLER::sm_fWamActive; CHAR W3_ISAPI_HANDLER::sm_szInstanceId[SIZE_CLSID_STRING]; BOOL sg_Initialized = FALSE; /*********************************************************************** Local Declarations ***********************************************************************/ VOID AddFiltersToMultiSz( IN const MB & mb, IN LPCWSTR szFilterPath, IN OUT MULTISZ * pmsz ); VOID AddAllFiltersToMultiSz( IN const MB & mb, IN OUT MULTISZ * pmsz ); /*********************************************************************** Module Definitions ***********************************************************************/ CONTEXT_STATUS W3_ISAPI_HANDLER::DoWork( VOID ) /*++ Routine Description: Main ISAPI handler routine Return Value: CONTEXT_STATUS_PENDING if async pending, else CONTEXT_STATUS_CONTINUE --*/ { W3_CONTEXT *pW3Context = QueryW3Context(); DBG_ASSERT( pW3Context != NULL ); HRESULT hr; BOOL fComplete = FALSE; W3_REQUEST *pRequest = pW3Context->QueryRequest(); W3_METADATA *pMetaData = pW3Context->QueryUrlContext()->QueryMetaData(); // // Preload entity if needed // hr = pRequest->PreloadEntityBody( pW3Context, &fComplete ); // // If we cannot read the request entity, we will assume it is the // client's fault // if ( FAILED( hr ) ) { if ( hr == HRESULT_FROM_WIN32( ERROR_NOT_ENOUGH_MEMORY ) ) { pW3Context->SetErrorStatus( hr ); pW3Context->QueryResponse()->SetStatus( HttpStatusServerError ); } else if ( hr == HRESULT_FROM_WIN32( ERROR_CONNECTION_INVALID ) ) { pW3Context->QueryResponse()->SetStatus( HttpStatusEntityTooLarge ); } else { pW3Context->SetErrorStatus( hr ); pW3Context->QueryResponse()->SetStatus( HttpStatusBadRequest ); } return CONTEXT_STATUS_CONTINUE; } if ( !fComplete ) { // // Async read pending. Just bail // return CONTEXT_STATUS_PENDING; } // // If we've already exceeded the maximum allowed entity, we // need to fail. // if ( pW3Context->QueryMainContext()->QueryEntityReadSoFar() > pMetaData->QueryMaxRequestEntityAllowed() ) { pW3Context->QueryResponse()->SetStatus( HttpStatusEntityTooLarge ); return CONTEXT_STATUS_CONTINUE; } _fEntityBodyPreloadComplete = TRUE; _State = ISAPI_STATE_INITIALIZING; return IsapiDoWork( pW3Context ); } CONTEXT_STATUS W3_ISAPI_HANDLER::IsapiDoWork( W3_CONTEXT * pW3Context ) /*++ Routine Description: Called to execute an ISAPI. This routine must be called only after we have preloaded entity for the request Arguments: pW3Context - Context for this request Return Value: CONTEXT_STATUS_PENDING if async pending, else CONTEXT_STATUS_CONTINUE --*/ { DWORD dwHseResult; HRESULT hr = NOERROR; HANDLE hOopToken; URL_CONTEXT * pUrlContext; BOOL fIsVrToken; DWORD dwWamSubError = 0; HTTP_SUB_ERROR httpSubError; // // We must have preloaded entity by the time this is called // DBG_ASSERT( _State == ISAPI_STATE_INITIALIZING ); DBG_ASSERT( _fEntityBodyPreloadComplete ); DBG_ASSERT( sm_pfnProcessIsapiRequest ); DBG_ASSERT( sm_pfnProcessIsapiCompletion ); DBG_REQUIRE( ( pUrlContext = pW3Context->QueryUrlContext() ) != NULL ); IF_DEBUG( ISAPI ) { DBGPRINTF(( DBG_CONTEXT, "IsapiDoWork called for new request.\r\n" )); } // // Initialize the ISAPI_CORE_DATA and ISAPI_CORE_INTERFACE // for this request // if ( FAILED( hr = InitCoreData( &fIsVrToken ) ) ) { goto ErrorExit; } DBG_ASSERT( _pCoreData ); // // If the gateway image is not enabled, then we should fail the // request with a 404. // if ( g_pW3Server->QueryIsIsapiImageEnabled( _pCoreData->szGatewayImage ) == FALSE ) { _State = ISAPI_STATE_FAILED; DBGPRINTF(( DBG_CONTEXT, "ISAPI image disabled: %S.\r\n", _pCoreData->szGatewayImage )); pW3Context->SetErrorStatus( ERROR_ACCESS_DISABLED_BY_POLICY ); pW3Context->QueryResponse()->SetStatus( HttpStatusNotFound, Http404DeniedByPolicy ); hr = pW3Context->SendResponse( W3_FLAG_ASYNC ); if ( SUCCEEDED( hr ) ) { return CONTEXT_STATUS_PENDING; } else { return CONTEXT_STATUS_CONTINUE; } } _pIsapiRequest = new (pW3Context) ISAPI_REQUEST( pW3Context, _pCoreData->fIsOop ); if ( _pIsapiRequest == NULL ) { hr = E_OUTOFMEMORY; goto ErrorExit; } if ( FAILED( hr = _pIsapiRequest->Create() ) ) { goto ErrorExit; } // // If the request should run OOP, get the WAM process and // duplicate the impersonation token // if ( _pCoreData->fIsOop ) { DBG_ASSERT( sm_pWamProcessManager ); DBG_ASSERT( _pCoreData->szWamClsid[0] != L'\0' ); hr = sm_pWamProcessManager->GetWamProcess( (LPCWSTR)&_pCoreData->szWamClsid, _pCoreData->szApplMdPathW, &dwWamSubError, &_pWamProcess, sm_szInstanceId ); if ( FAILED( hr ) ) { goto ErrorExit; } // // We have to modify the token that we're passing to // the OOP process. // if( ( fIsVrToken && !pW3Context->QueryVrToken()->QueryOOPToken() ) || ( !fIsVrToken && !pW3Context->QueryUserContext()->QueryIsCachedToken() ) || ( !fIsVrToken && !pW3Context->QueryUserContext()->QueryCachedToken()->QueryOOPToken() ) ) { hr = GrantWpgAccessToToken( _pCoreData->hToken ); if ( FAILED( hr ) ) { goto ErrorExit; } hr = AddWpgToTokenDefaultDacl( _pCoreData->hToken ); if ( FAILED( hr ) ) { goto ErrorExit; } } if ( DuplicateHandle( GetCurrentProcess(), _pCoreData->hToken, _pWamProcess->QueryProcess(), &hOopToken, 0, FALSE, DUPLICATE_SAME_ACCESS ) ) { _pCoreData->hToken = hOopToken; } else { hr = HRESULT_FROM_WIN32( GetLastError() ); // // CODEWORK - If the target process has exited, then // DuplicateHandle fails with ERROR_ACCESS_DENIED. This // will confuse our error handling logic because it'll // thing that we really got this error attempting to // process the request. // // For the time being, we'll detect this error and let // it call into ProcessRequest. If the process really // has exited, this will cause the WAM_PROCESS cleanup // code to recover everything. // // In the future, we should consider waiting on the // process handle to detect steady-state crashes of // OOP hosts so that we don't have to discover the // problem only when something trys to talk to the // process. // // Another thing to consider is that we could trigger // the crash recovery directly and call GetWamProcess // again to get a new process. This would make the // crash completely transparent to the client, which // would be an improvement over the current solution // (and IIS 4 and 5) which usually waits until a client // request fails before recovering. // _pCoreData->hToken = NULL; if ( hr != HRESULT_FROM_WIN32( ERROR_ACCESS_DENIED ) ) { goto ErrorExit; } } } // // Handle the request // _State = ISAPI_STATE_PENDING; // // Temporarily up the thread threshold since we don't know when the // ISAPI will return // ThreadPoolSetInfo( ThreadPoolIncMaxPoolThreads, 0 ); if ( !_pCoreData->fIsOop ) { IF_DEBUG( ISAPI ) { DBGPRINTF(( DBG_CONTEXT, "Processing ISAPI_REQUEST %p OOP.\r\n", _pIsapiRequest )); } hr = sm_pfnProcessIsapiRequest( _pIsapiRequest, _pCoreData, &dwHseResult ); } else { hr = _pWamProcess->ProcessRequest( _pIsapiRequest, _pCoreData, &dwHseResult ); } // // Back down the count since the ISAPI has returned // ThreadPoolSetInfo( ThreadPoolDecMaxPoolThreads, 0 ); if ( FAILED( hr ) ) { _State = ISAPI_STATE_FAILED; goto ErrorExit; } // // Determine whether the extension was synchronous or pending. // We need to do this before releasing our reference on the // ISAPI_REQUEST since the final release will check the state // to determine if an additional completion is necessary. // // In either case, we should just return with the appropriate // return code after setting the state. // if ( dwHseResult != HSE_STATUS_PENDING && _pCoreData->fIsOop == FALSE ) { _State = ISAPI_STATE_DONE; // // This had better be the final release... // LONG Refs = _pIsapiRequest->Release(); // // Make /W3 happy on a free build... // if ( Refs != 0 ) { DBG_ASSERT( Refs == 0 ); } return CONTEXT_STATUS_CONTINUE; } // // This may or may not be the final release... // _pIsapiRequest->Release(); return CONTEXT_STATUS_PENDING; ErrorExit: DBG_ASSERT( FAILED( hr ) ); // // Spew on failure. // if ( FAILED( hr ) ) { DBGPRINTF(( DBG_CONTEXT, "Attempt to process ISAPI request failed. Error 0x%08x.\r\n", hr )); } // // Set the error status now. // pW3Context->SetErrorStatus( hr ); // // If we've failed, and the state is ISAPI_STATE_INITIALIZING, then // we never made the call out to the extension. It's therefore // safe to handle the error and advance the state machine. // // It's also safe to advance the state machine in the special case // error where the attempt to call the extension results in // ERROR_ACCESS_DENIED. // if ( _State == ISAPI_STATE_INITIALIZING || hr == HRESULT_FROM_WIN32( ERROR_ACCESS_DENIED) ) { // // Setting the state to ISAPI_STATE_DONE will cause the // next completion to advance the state machine. // _State = ISAPI_STATE_DONE; // // The _pWamProcess and _pCoreData members are cleaned up // by the destructor. We don't need to worry about them. // We also don't need to worry about any tokens that we // are using. The tokens local to this process are owned // by W3_USER_CONTEXT; any duplicates for OOP are the // responsibility of the dllhost process (if it still // exists). // // We do need to clean up the _pIsapiRequest if we've // created it. This had better well be the final release. // if ( _pIsapiRequest ) { _pIsapiRequest->Release(); } // // Set the HTTP status and send it asynchronously. // This will ultimately trigger the completion that // advances the state machine. // if ( hr == HRESULT_FROM_WIN32( ERROR_ACCESS_DENIED ) ) { pW3Context->QueryResponse()->SetStatus( HttpStatusUnauthorized, Http401Resource ); } else { pW3Context->QueryResponse()->SetStatus( HttpStatusServerError ); if ( dwWamSubError != 0 ) { httpSubError.dwStringId = dwWamSubError; pW3Context->QueryResponse()->SetSubError( &httpSubError ); } } hr = pW3Context->SendResponse( W3_FLAG_ASYNC ); if ( SUCCEEDED( hr ) ) { return CONTEXT_STATUS_PENDING; } // // Ouch - couldn't send the error page... // _State = ISAPI_STATE_FAILED; return CONTEXT_STATUS_CONTINUE; } // // If we get here, then an error has occured during or after // our call into the extension. Because it's possible for an // OOP call to fail after entering the extension, we can't // generally know our state. // // Because of this, we'll assume that the extension has // outstanding references to the ISAPI_REQUEST on its behalf. // We'll set the state to ISAPI_STATE_PENDING and let the // destructor on the ISAPI_REQUEST trigger the final // completion. // // Also, we'll set the error status, just in case the extension // didn't get a response off before it failed. // pW3Context->QueryResponse()->SetStatus( HttpStatusServerError ); _State = ISAPI_STATE_FAILED; // // This may or may not be the final release on the ISAPI_REQUEST. // // It had better be non-NULL if we got past ISAPI_STATE_INITIALIZING. // DBG_ASSERT( _pIsapiRequest ); _pIsapiRequest->Release(); return CONTEXT_STATUS_PENDING; } CONTEXT_STATUS W3_ISAPI_HANDLER::OnCompletion( DWORD cbCompletion, DWORD dwCompletionStatus ) /*++ Routine Description: ISAPI async completion handler. Arguments: cbCompletion - Number of bytes in an async completion dwCompletionStatus - Error status of a completion Return Value: CONTEXT_STATUS_PENDING if async pending, else CONTEXT_STATUS_CONTINUE --*/ { HRESULT hr; W3_CONTEXT * pW3Context; pW3Context = QueryW3Context(); DBG_ASSERT( pW3Context != NULL ); // // Is this completion for the entity body preload? If so note the // number of bytes and start handling the ISAPI request // if ( !_fEntityBodyPreloadComplete ) { BOOL fComplete = FALSE; // // This completion is for entity body preload // W3_REQUEST *pRequest = pW3Context->QueryRequest(); hr = pRequest->PreloadCompletion(pW3Context, cbCompletion, dwCompletionStatus, &fComplete); // // If we cannot read the request entity, we will assume it is the // client's fault // if ( FAILED( hr ) ) { if ( hr == HRESULT_FROM_WIN32( ERROR_CONNECTION_INVALID ) ) { pW3Context->QueryResponse()->SetStatus( HttpStatusEntityTooLarge ); } else { pW3Context->SetErrorStatus( hr ); pW3Context->QueryResponse()->SetStatus( HttpStatusBadRequest ); } return CONTEXT_STATUS_CONTINUE; } if (!fComplete) { return CONTEXT_STATUS_PENDING; } _fEntityBodyPreloadComplete = TRUE; _State = ISAPI_STATE_INITIALIZING; // // Finally we can call the ISAPI // return IsapiDoWork( pW3Context ); } DBG_ASSERT( _fEntityBodyPreloadComplete ); return IsapiOnCompletion( cbCompletion, dwCompletionStatus ); } CONTEXT_STATUS W3_ISAPI_HANDLER::IsapiOnCompletion( DWORD cbCompletion, DWORD dwCompletionStatus ) /*++ Routine Description: Funnels a completion to an ISAPI Arguments: cbCompletion - Bytes of completion dwCompletionStatus - Win32 Error status of completion Return Value: CONTEXT_STATUS_PENDING if async pending, else CONTEXT_STATUS_CONTINUE --*/ { DWORD64 IsapiContext; HRESULT hr = NO_ERROR; // // If the state is ISAPI_STATE_DONE, then we should // advance the state machine now. // if ( _State == ISAPI_STATE_DONE || _State == ISAPI_STATE_FAILED ) { return CONTEXT_STATUS_CONTINUE; } // // If we get here, then this completion should be passed // along to the extension. // DBG_ASSERT( _pCoreData ); DBG_ASSERT( _pIsapiRequest ); IsapiContext = _pIsapiRequest->QueryIsapiContext(); DBG_ASSERT( IsapiContext != 0 ); // // Process the completion. // _pIsapiRequest->AddRef(); // // Temporarily up the thread threshold since we don't know when the // ISAPI will return // ThreadPoolSetInfo( ThreadPoolIncMaxPoolThreads, 0 ); if ( !_pCoreData->fIsOop ) { // // Need to reset the ISAPI context in case the extension // does another async operation before the below call returns // _pIsapiRequest->ResetIsapiContext(); hr = sm_pfnProcessIsapiCompletion( IsapiContext, cbCompletion, dwCompletionStatus ); } else { DBG_ASSERT( _pWamProcess ); // // _pWamProcess->ProcessCompletion depends on the ISAPI // context, so it will make the Reset call. // hr = _pWamProcess->ProcessCompletion( _pIsapiRequest, IsapiContext, cbCompletion, dwCompletionStatus ); } // // Back down the count since the ISAPI has returned // ThreadPoolSetInfo( ThreadPoolDecMaxPoolThreads, 0 ); _pIsapiRequest->Release(); return CONTEXT_STATUS_PENDING; } HRESULT W3_ISAPI_HANDLER::InitCoreData( BOOL * pfIsVrToken ) /*++ Routine Description: Initializes the ISAPI_CORE_DATA for a request Arguments: None Return Value: HRESULT --*/ { HRESULT hr = NO_ERROR; W3_CONTEXT * pW3Context; URL_CONTEXT * pUrlContext; W3_URL_INFO * pUrlInfo; W3_METADATA * pMetadata; W3_REQUEST * pRequest = NULL; LPCSTR szContentLength = NULL; STRU stru; STRU * pstru = NULL; BOOL fRequestIsScript = FALSE; BOOL fUsePathInfo; DWORD dwAppType = APP_INPROC; DBG_REQUIRE( ( pW3Context = QueryW3Context() ) != NULL ); DBG_REQUIRE( ( pRequest = pW3Context->QueryRequest() ) != NULL ); DBG_REQUIRE( ( pUrlContext = pW3Context->QueryUrlContext() ) != NULL ); DBG_REQUIRE( ( pUrlInfo = pUrlContext->QueryUrlInfo() ) != NULL ); DBG_REQUIRE( ( pMetadata = pUrlContext->QueryMetaData() ) != NULL ); // // Check for script // if ( QueryScriptMapEntry() ) { fRequestIsScript = TRUE; } // // Populate data directly into the inline core data. // Assume everything is inproc. In the case of an // OOP request, the SerializeCoreDataForOop function // will take care of any needed changes. // _pCoreData = &_InlineCoreData; // // Structure size information // _pCoreData->cbSize = sizeof(ISAPI_CORE_DATA); // // WAM information - Always set to inproc for w3wp.exe // _pCoreData->szWamClsid[0] = L'\0'; _pCoreData->fIsOop = FALSE; // // Secure request? // _pCoreData->fSecure = pRequest->IsSecureRequest(); // // Client HTTP version // _pCoreData->dwVersionMajor = pRequest->QueryVersion().MajorVersion; _pCoreData->dwVersionMinor = pRequest->QueryVersion().MinorVersion; // // Site instance ID // _pCoreData->dwInstanceId = pRequest->QuerySiteId(); // // Request content-length // if ( pRequest->IsChunkedRequest() ) { _pCoreData->dwContentLength = (DWORD) -1; } else { szContentLength = pRequest->GetHeader( HttpHeaderContentLength ); if ( szContentLength != NULL ) { errno = 0; _pCoreData->dwContentLength = strtoul( szContentLength, NULL, 10 ); // // Check for overflow // if ( ( _pCoreData->dwContentLength == ULONG_MAX || _pCoreData->dwContentLength == 0 ) && errno == ERANGE ) { hr = HRESULT_FROM_WIN32( ERROR_ARITHMETIC_OVERFLOW ); goto ErrorExit; } } else { _pCoreData->dwContentLength = 0; } } // // Client authentication information // _pCoreData->hToken = pW3Context->QueryImpersonationToken( pfIsVrToken ); _pCoreData->pSid = pW3Context->QueryUserContext()->QuerySid(); // // Request ID // _pCoreData->RequestId = pRequest->QueryRequestId(); // // Gateway image // // There are 3 cases to consider: // // 1) If this is a DAV request, then use DAV image // 2) If this is script mapped, use script executable // 3) Else use URL physical path // if ( _fIsDavRequest ) { pstru = &_strDavIsapiImage; } else if ( fRequestIsScript ) { pstru = QueryScriptMapEntry()->QueryExecutable(); } else { pstru = pUrlContext->QueryPhysicalPath(); } DBG_ASSERT( pstru ); _pCoreData->szGatewayImage = pstru->QueryStr(); _pCoreData->cbGatewayImage = pstru->QueryCB() + sizeof(WCHAR); pstru = NULL; // // Get the app type. // if ( sm_fWamActive ) { dwAppType = pMetadata->QueryAppIsolated(); if ( dwAppType == APP_ISOLATED || dwAppType == APP_POOL ) { if ( IsInprocIsapi( _pCoreData->szGatewayImage ) ) { dwAppType = APP_INPROC; } } } // // Physical Path - Not Needed? Just set it to an empty string for now. // hr = _PhysicalPath.Copy( "" ); if ( FAILED( hr ) ) { goto ErrorExit; } _pCoreData->szPhysicalPath = _PhysicalPath.QueryStr(); _pCoreData->cbPhysicalPath = _PhysicalPath.QueryCB() + sizeof(CHAR); // // Path info // // 1) If this is a DAV request, PATH_INFO is the URL // 2) If this is a script, and AllowPathInfoForScriptMappings is // FALSE, then PATH_INFO is the URL. // 3) Else, we use the "real" PATH_INFO // // We will set a flag indicating whether we are using the URL or // the "real" data, so that we can be efficient about deriving // PATH_TRANSLATED. // fUsePathInfo = TRUE; if ( _fIsDavRequest ) { hr = pRequest->GetUrl( &stru ); fUsePathInfo = FALSE; } else if ( fRequestIsScript ) { if ( pW3Context->QuerySite()->QueryAllowPathInfoForScriptMappings() ) { hr = stru.Copy( *pUrlInfo->QueryPathInfo() ); } else { hr = pRequest->GetUrl( &stru ); fUsePathInfo = FALSE; } } else { hr = stru.Copy( *pUrlInfo->QueryPathInfo() ); } if ( FAILED( hr ) ) { goto ErrorExit; } hr = _PathInfo.CopyW( stru.QueryStr(), stru.QueryCCH() ); if ( FAILED( hr ) ) { goto ErrorExit; } _pCoreData->szPathInfo = _PathInfo.QueryStr(); _pCoreData->cbPathInfo = _PathInfo.QueryCB() + sizeof(CHAR); // // Method // hr = pRequest->GetVerbString( &_Method ); if (FAILED( hr ) ) { goto ErrorExit; } _pCoreData->szMethod = _Method.QueryStr(); _pCoreData->cbMethod = _Method.QueryCB() + sizeof(CHAR); // // Query string // hr = pRequest->GetQueryStringA( &_QueryString ); if (FAILED( hr ) ) { goto ErrorExit; } _pCoreData->szQueryString = _QueryString.QueryStr(); _pCoreData->cbQueryString = _QueryString.QueryCB() + sizeof(CHAR); // // Path translated (and we'll do the UNICODE version while we're at it) // hr = pUrlInfo->GetPathTranslated( pW3Context, fUsePathInfo, &_PathTranslatedW ); if ( FAILED( hr ) ) { goto ErrorExit; } hr = _PathTranslated.CopyW( _PathTranslatedW.QueryStr(), _PathTranslatedW.QueryCCH() ); if ( FAILED( hr ) ) { goto ErrorExit; } _pCoreData->szPathTranslated = _PathTranslated.QueryStr(); _pCoreData->cbPathTranslated = _PathTranslated.QueryCB() + sizeof(CHAR); _pCoreData->szPathTranslatedW = _PathTranslatedW.QueryStr(); _pCoreData->cbPathTranslatedW = _PathTranslatedW.QueryCB() + sizeof(WCHAR); // // Content type // _pCoreData->szContentType = (LPSTR)pRequest->GetHeader( HttpHeaderContentType ); if ( !_pCoreData->szContentType ) { _pCoreData->szContentType = CONTENT_TYPE_PLACEHOLDER; } _pCoreData->cbContentType = (DWORD)strlen( _pCoreData->szContentType ) + sizeof(CHAR); // // Connection // _pCoreData->szConnection = (LPSTR)pRequest->GetHeader( HttpHeaderConnection ); if ( !_pCoreData->szConnection ) { _pCoreData->szConnection = CONNECTION_PLACEHOLDER; } _pCoreData->cbConnection = (DWORD)strlen( _pCoreData->szConnection ) + sizeof(CHAR); // // UserAgent // _pCoreData->szUserAgent = (LPSTR)pRequest->GetHeader( HttpHeaderUserAgent ); if ( !_pCoreData->szUserAgent ) { _pCoreData->szUserAgent = USER_AGENT_PLACEHOLDER; } _pCoreData->cbUserAgent = (DWORD)strlen( _pCoreData->szUserAgent ) + sizeof(CHAR); // // Cookie // _pCoreData->szCookie = (LPSTR)pRequest->GetHeader( HttpHeaderCookie ); if ( !_pCoreData->szCookie ) { _pCoreData->szCookie = COOKIE_PLACEHOLDER; } _pCoreData->cbCookie = (DWORD)strlen( _pCoreData->szCookie ) + sizeof(CHAR); // // Appl MD path // hr = GetServerVariableApplMdPath( pW3Context, &_ApplMdPath ); if( FAILED(hr) ) { goto ErrorExit; } _pCoreData->szApplMdPath = _ApplMdPath.QueryStr(); _pCoreData->cbApplMdPath = _ApplMdPath.QueryCB() + sizeof(CHAR); // // szApplMdPathW is only populated in // the OOF case. // _pCoreData->szApplMdPathW = NULL; _pCoreData->cbApplMdPathW = 0; // // Entity data // pW3Context->QueryAlreadyAvailableEntity( &_pCoreData->pAvailableEntity, &_pCoreData->cbAvailableEntity ); // // Keep alive // _pCoreData->fAllowKeepAlive = pMetadata->QueryKeepAliveEnabled(); // // If this is an OOP request, then we need to serialize the core data // if ( dwAppType == APP_ISOLATED || dwAppType == APP_POOL ) { hr = SerializeCoreDataForOop( dwAppType ); if ( FAILED( hr ) ) { goto ErrorExit; } } DBG_ASSERT( SUCCEEDED( hr ) ); return hr; ErrorExit: DBG_ASSERT( FAILED( hr ) ); _pCoreData = NULL; return hr; } HRESULT W3_ISAPI_HANDLER::SerializeCoreDataForOop( DWORD dwAppType ) { W3_CONTEXT * pW3Context; URL_CONTEXT * pUrlContext; W3_URL_INFO * pUrlInfo; W3_METADATA * pMetadata; STRU * pstru; DWORD cbNeeded; BYTE * pCursor; ISAPI_CORE_DATA * pSerialized; HRESULT hr = NO_ERROR; // // Caution. This code must be kept in sync // with the FixupCoreData function in w3isapi.dll // DBG_ASSERT( sm_fWamActive ); DBG_ASSERT( dwAppType == APP_ISOLATED || dwAppType == APP_POOL ); DBG_REQUIRE( ( pW3Context = QueryW3Context() ) != NULL ); DBG_REQUIRE( ( pUrlContext = pW3Context->QueryUrlContext() ) != NULL ); DBG_REQUIRE( ( pUrlInfo = pUrlContext->QueryUrlInfo() ) != NULL ); DBG_REQUIRE( ( pMetadata = pUrlContext->QueryMetaData() ) != NULL ); // // Set the WAM information and NULL out the pSid dude // if ( dwAppType == APP_ISOLATED ) { pstru = pMetadata->QueryWamClsId(); DBG_ASSERT( pstru ); if ( pstru == NULL ) { hr = HRESULT_FROM_WIN32( ERROR_PATH_NOT_FOUND ); goto ErrorExit; } wcsncpy( _pCoreData->szWamClsid, pstru->QueryStr(), SIZE_CLSID_STRING ); _pCoreData->szWamClsid[SIZE_CLSID_STRING-1] = L'\0'; } else { wcsncpy( _pCoreData->szWamClsid, POOL_WAM_CLSID, SIZE_CLSID_STRING ); _pCoreData->szWamClsid[SIZE_CLSID_STRING-1] = L'\0'; } _pCoreData->fIsOop = TRUE; _pCoreData->pSid = NULL; // // ApplMdPathW // hr = GetServerVariableApplMdPathW( pW3Context, &_ApplMdPathW ); if ( FAILED( hr ) ) { goto ErrorExit; } _pCoreData->szApplMdPathW = _ApplMdPathW.QueryStr(); _pCoreData->cbApplMdPathW = _ApplMdPathW.QueryCB() + sizeof(WCHAR); // // Calculate the size needed for the core data and // set up the buffer to contain it. // cbNeeded = sizeof(ISAPI_CORE_DATA); cbNeeded += _pCoreData->cbGatewayImage; cbNeeded += _pCoreData->cbPhysicalPath; cbNeeded += _pCoreData->cbPathInfo; cbNeeded += _pCoreData->cbMethod; cbNeeded += _pCoreData->cbQueryString; cbNeeded += _pCoreData->cbPathTranslated; cbNeeded += _pCoreData->cbContentType; cbNeeded += _pCoreData->cbConnection; cbNeeded += _pCoreData->cbUserAgent; cbNeeded += _pCoreData->cbCookie; cbNeeded += _pCoreData->cbApplMdPath; cbNeeded += _pCoreData->cbApplMdPathW; cbNeeded += _pCoreData->cbPathTranslatedW; cbNeeded += _pCoreData->cbAvailableEntity; hr = _buffCoreData.Resize( cbNeeded ); if ( FAILED( hr ) ) { goto ErrorExit; } // // Copy the core data into the buffer // pSerialized = (ISAPI_CORE_DATA*)_buffCoreData.QueryPtr(); pCursor = (BYTE*)pSerialized; CopyMemory( pCursor, _pCoreData, sizeof(ISAPI_CORE_DATA) ); pSerialized->cbSize = cbNeeded; pCursor += sizeof(ISAPI_CORE_DATA); // // Add gateway image // pSerialized->szGatewayImage = (LPWSTR)pCursor; CopyMemory( pSerialized->szGatewayImage, _pCoreData->szGatewayImage, _pCoreData->cbGatewayImage ); pCursor += _pCoreData->cbGatewayImage; // // Add ApplMdPathW // pSerialized->szApplMdPathW = (LPWSTR)pCursor; CopyMemory( pSerialized->szApplMdPathW, _pCoreData->szApplMdPathW, _pCoreData->cbApplMdPathW ); pCursor += _pCoreData->cbApplMdPathW; // // Add PathTranslatedW // pSerialized->szPathTranslatedW = (LPWSTR)pCursor; CopyMemory( pSerialized->szPathTranslatedW, _pCoreData->szPathTranslatedW, _pCoreData->cbPathTranslatedW ); pCursor += _pCoreData->cbPathTranslatedW; // // Add physical path // pSerialized->szPhysicalPath = (LPSTR)pCursor; CopyMemory( pSerialized->szPhysicalPath, _pCoreData->szPhysicalPath, _pCoreData->cbPhysicalPath ); pCursor += _pCoreData->cbPhysicalPath; // // Add path info // pSerialized->szPathInfo = (LPSTR)pCursor; CopyMemory( pSerialized->szPathInfo, _pCoreData->szPathInfo, _pCoreData->cbPathInfo ); pCursor += _pCoreData->cbPathInfo; // // Add method // pSerialized->szMethod = (LPSTR)pCursor; CopyMemory( pSerialized->szMethod, _pCoreData->szMethod, _pCoreData->cbMethod ); pCursor += _pCoreData->cbMethod; // // Add query string // pSerialized->szQueryString = (LPSTR)pCursor; CopyMemory( pSerialized->szQueryString, _pCoreData->szQueryString, _pCoreData->cbQueryString ); pCursor += _pCoreData->cbQueryString; // // Add path translated // pSerialized->szPathTranslated = (LPSTR)pCursor; CopyMemory( pSerialized->szPathTranslated, _pCoreData->szPathTranslated, _pCoreData->cbPathTranslated ); pCursor += _pCoreData->cbPathTranslated; // // Add content type // pSerialized->szContentType = (LPSTR)pCursor; CopyMemory( pSerialized->szContentType, _pCoreData->szContentType, _pCoreData->cbContentType ); pCursor += _pCoreData->cbContentType; // // Add connection // pSerialized->szConnection = (LPSTR)pCursor; CopyMemory( pSerialized->szConnection, _pCoreData->szConnection, _pCoreData->cbConnection ); pCursor += _pCoreData->cbConnection; // // Add user agent // pSerialized->szUserAgent = (LPSTR)pCursor; CopyMemory( pSerialized->szUserAgent, _pCoreData->szUserAgent, _pCoreData->cbUserAgent ); pCursor += _pCoreData->cbUserAgent; // // Add cookie // pSerialized->szCookie = (LPSTR)pCursor; CopyMemory( pSerialized->szCookie, _pCoreData->szCookie, _pCoreData->cbCookie ); pCursor += _pCoreData->cbCookie; // // Add ApplMdPath // pSerialized->szApplMdPath = (LPSTR)pCursor; CopyMemory( pSerialized->szApplMdPath, _pCoreData->szApplMdPath, _pCoreData->cbApplMdPath ); pCursor += _pCoreData->cbApplMdPath; // // Add entity data // if ( _pCoreData->cbAvailableEntity ) { pSerialized->pAvailableEntity = (LPWSTR)pCursor; CopyMemory( pSerialized->pAvailableEntity, _pCoreData->pAvailableEntity, _pCoreData->cbAvailableEntity ); } // // Point _pCoreData at the new buffer and we're done // _pCoreData = pSerialized; DBG_ASSERT( SUCCEEDED( hr ) ); return hr; ErrorExit: DBG_ASSERT( FAILED( hr ) ); return hr; } HRESULT W3_ISAPI_HANDLER::DuplicateWamProcessHandleForLocalUse( HANDLE hWamProcessHandle, HANDLE * phLocalHandle ) /*++ Routine Description: Duplicates a handle defined in a WAM process to a local handle useful in the IIS core Arguments: hWamProcessHandle - The value of the handle from the WAM process phLocalHandle - Upon successful return, the handle useable in the core process Return Value: HRESULT --*/ { HANDLE hWamProcess; HRESULT hr = NOERROR; DBG_ASSERT( _pWamProcess ); DBG_REQUIRE( ( hWamProcess = _pWamProcess->QueryProcess() ) != NULL ); if ( !DuplicateHandle( hWamProcess, hWamProcessHandle, GetCurrentProcess(), phLocalHandle, 0, FALSE, DUPLICATE_SAME_ACCESS ) ) { hr = HRESULT_FROM_WIN32( GetLastError() ); } return hr; } HRESULT W3_ISAPI_HANDLER::MarshalAsyncReadBuffer( DWORD64 pWamExecInfo, LPBYTE pBuffer, DWORD cbBuffer ) /*++ Routine Description: Pushes a buffer into a WAM process. This function is called to copy a local read buffer into the WAM process just prior to notifying the I/O completion function of an OOP extension. Arguments: pWamExecInfo - A WAM_EXEC_INFO pointer that identifies the request to the OOP host. pBuffer - The buffer to copy cbBuffer - The amount of data in pBuffer Return Value: HRESULT --*/ { DBG_ASSERT( sm_fWamActive ); DBG_ASSERT( _pWamProcess ); return _pWamProcess->MarshalAsyncReadBuffer( pWamExecInfo, pBuffer, cbBuffer ); } VOID W3_ISAPI_HANDLER::IsapiRequestFinished( VOID ) /*++ Routine Description: This function is called by the destructor for the ISAPI_REQUEST associated with this request. If the current state of the W3_ISAPI_HANDLER is ISAPI_STATE_PENDING, then it will advance the core state machine. Arguments: None Return Value: None --*/ { W3_CONTEXT * pW3Context = QueryW3Context(); HRESULT hr = NO_ERROR; DBG_ASSERT( pW3Context ); if ( _State == ISAPI_STATE_FAILED ) { if ( pW3Context->QueryResponseSent() == FALSE ) { // // The ISAPI didn't send a response, we need to send // it now. If our send is successful, we should return // immediately. // hr = pW3Context->SendResponse( W3_FLAG_ASYNC ); if ( SUCCEEDED( hr ) ) { return; } else { pW3Context->SetErrorStatus( hr ); } } // // Since we didn't end up sending a response, we need // to set the status to pending. This will result in // the below code triggering a completion to clean up // the state machine. // _State = ISAPI_STATE_PENDING; } if ( _State == ISAPI_STATE_PENDING ) { RestartCoreStateMachine(); } } VOID W3_ISAPI_HANDLER::RestartCoreStateMachine( VOID ) /*++ Routine Description: Advances the core state machine by setting state to ISAPI_STATE_DONE and triggering an I/O completion. Note that this function is only expected to be called if the object state is ISAPI_STATE_PENDING. Arguments: None Return Value: None --*/ { W3_CONTEXT * pW3Context = QueryW3Context(); DBG_ASSERT( pW3Context ); DBG_ASSERT( _State == ISAPI_STATE_PENDING ); // // Need to set state to ISAPI_STATE_DONE so that the // resulting completion does the advance for us. // _State = ISAPI_STATE_DONE; // // If this is the main request, then we can resume the state // machine on the ISAPIs thread. Therefore no need to marshall // to another thread. If it is not the main request, the we // don't want to risk doing a long running operation (i.e. the // completion of the parent request) on the ISAPI thread // if ( pW3Context == pW3Context->QueryMainContext() ) { W3_MAIN_CONTEXT::OnPostedCompletion( NO_ERROR, 0, (OVERLAPPED*) pW3Context->QueryMainContext() ); } else { POST_MAIN_COMPLETION( pW3Context->QueryMainContext() ); } } //static HRESULT W3_ISAPI_HANDLER::Initialize( VOID ) /*++ Routine Description: Initializes W3_ISAPI_HANDLER Arguments: None Return Value: HRESULT --*/ { HRESULT hr = NOERROR; DBGPRINTF(( DBG_CONTEXT, "W3_ISAPI_HANDLER::Initialize()\n" )); // // For debugging purposes, create a unique instance ID for this // instance of the handler. // #ifdef DBG UUID uuid; RPC_STATUS rpcStatus; unsigned char * szRpcString; rpcStatus = UuidCreate( &uuid ); if ( (rpcStatus != RPC_S_OK) && (rpcStatus != RPC_S_UUID_LOCAL_ONLY) ) { SetLastError( rpcStatus ); goto error_exit; } rpcStatus = UuidToStringA( &uuid, &szRpcString ); if ( rpcStatus != RPC_S_OK ) { SetLastError( ERROR_NOT_ENOUGH_MEMORY ); goto error_exit; } strncpy( sm_szInstanceId, (LPSTR)szRpcString, SIZE_CLSID_STRING ); sm_szInstanceId[SIZE_CLSID_STRING - 1] = '\0'; RpcStringFreeA( &szRpcString ); DBGPRINTF(( DBG_CONTEXT, "W3_ISAPI_HANDLER initialized instance %s.\r\n", sm_szInstanceId )); #else sm_szInstanceId[0] = '\0'; #endif _DBG PFN_ISAPI_INIT_MODULE pfnInit = NULL; sm_hIsapiModule = LoadLibrary( ISAPI_MODULE_NAME ); if( sm_hIsapiModule == NULL ) { hr = HRESULT_FROM_WIN32( GetLastError() ); goto error_exit; } sm_pfnTermIsapiModule = (PFN_ISAPI_TERM_MODULE)GetProcAddress( sm_hIsapiModule, ISAPI_TERM_MODULE ); sm_pfnProcessIsapiRequest = (PFN_ISAPI_PROCESS_REQUEST)GetProcAddress( sm_hIsapiModule, ISAPI_PROCESS_REQUEST ); sm_pfnProcessIsapiCompletion = (PFN_ISAPI_PROCESS_COMPLETION)GetProcAddress( sm_hIsapiModule, ISAPI_PROCESS_COMPLETION ); if( !sm_pfnTermIsapiModule || !sm_pfnProcessIsapiRequest || !sm_pfnProcessIsapiCompletion ) { hr = E_FAIL; goto error_exit; } pfnInit = (PFN_ISAPI_INIT_MODULE)GetProcAddress( sm_hIsapiModule, ISAPI_INIT_MODULE ); if( !pfnInit ) { hr = E_FAIL; goto error_exit; } hr = pfnInit( NULL, sm_szInstanceId, GetCurrentProcessId() ); if( FAILED(hr) ) { goto error_exit; } DBG_REQUIRE( ISAPI_REQUEST::InitClass() ); sm_pInprocIsapiHash = NULL; // // If we're running in backward compatibility mode, initialize // the WAM process manager and inprocess ISAPI app list // if ( g_pW3Server->QueryInBackwardCompatibilityMode() ) { WCHAR szIsapiModule[MAX_PATH]; // // Store away the full path to the loaded ISAPI module // so that we can pass it to OOP processes so that they // know how to load it // if ( GetModuleFileNameW( GetModuleHandleW( ISAPI_MODULE_NAME ), szIsapiModule, MAX_PATH ) == 0 ) { hr = HRESULT_FROM_WIN32( GetLastError() ); goto error_exit; } DBG_ASSERT( szIsapiModule[0] != '\0' ); // // Initialize the WAM_PROCESS_MANAGER // sm_pWamProcessManager = new WAM_PROCESS_MANAGER( szIsapiModule ); if ( !sm_pWamProcessManager ) { goto error_exit; } hr = sm_pWamProcessManager->Create(); if ( FAILED( hr ) ) { sm_pWamProcessManager->Release(); sm_pWamProcessManager = NULL; goto error_exit; } // // Hook up wamreg // hr = WamReg_RegisterSinkNotify( W3SVC_WamRegSink ); if ( FAILED( hr ) ) { goto error_exit; } INITIALIZE_CRITICAL_SECTION( &sm_csInprocHashLock ); UpdateInprocIsapiHash(); INITIALIZE_CRITICAL_SECTION( &sm_csBigHurkinWamRegLock ); sm_fWamActive = TRUE; } else { sm_pWamProcessManager = NULL; sm_fWamActive = FALSE; } sg_Initialized = TRUE; return hr; error_exit: DBGPRINTF(( DBG_CONTEXT, "W3_ISAPI_HANDLER::Initialize() Error=%08x\n", hr )); if ( sm_hIsapiModule ) { FreeLibrary( sm_hIsapiModule ); sm_hIsapiModule = NULL; } sm_pfnTermIsapiModule = NULL; return hr; } //static VOID W3_ISAPI_HANDLER::Terminate( VOID ) /*++ Routine Description: Terminates W3_ISAPI_HANDLER Arguments: None Return Value: None --*/ { DBGPRINTF(( DBG_CONTEXT, "W3_ISAPI_HANDLER::Terminate()\n" )); sg_Initialized = FALSE; DBG_ASSERT( sm_pfnTermIsapiModule ); DBG_ASSERT( sm_hIsapiModule ); if( sm_pfnTermIsapiModule ) { sm_pfnTermIsapiModule(); sm_pfnTermIsapiModule = NULL; } if( sm_hIsapiModule ) { FreeLibrary( sm_hIsapiModule ); sm_hIsapiModule = NULL; } if ( sm_pInprocIsapiHash ) { delete sm_pInprocIsapiHash; } if ( sm_fWamActive ) { // // Disconnect wamreg // WamReg_UnRegisterSinkNotify(); if ( sm_pWamProcessManager ) { sm_pWamProcessManager->Shutdown(); sm_pWamProcessManager->Release(); sm_pWamProcessManager = NULL; } DeleteCriticalSection( &sm_csInprocHashLock ); DeleteCriticalSection( &sm_csBigHurkinWamRegLock ); } ISAPI_REQUEST::CleanupClass(); } // static HRESULT W3_ISAPI_HANDLER::W3SVC_WamRegSink( LPCSTR szAppPath, const DWORD dwCommand, DWORD * pdwResult ) { HRESULT hr = NOERROR; WAM_PROCESS * pWamProcess = NULL; WAM_APP_INFO * pWamAppInfo = NULL; DWORD dwWamSubError = 0; BOOL fIsLoaded = FALSE; // // Scary monsters live in the land where this function // is allowed to run willy nilly // LockWamReg(); DBG_ASSERT( szAppPath ); DBG_ASSERT( sm_pWamProcessManager ); DBGPRINTF(( DBG_CONTEXT, "WAM_PROCESS_MANAGER received a Sink Notify on MD path %S, cmd = %d.\r\n", (LPCWSTR)szAppPath, dwCommand )); *pdwResult = APPSTATUS_UnLoaded; switch ( dwCommand ) { case APPCMD_UNLOAD: case APPCMD_DELETE: case APPCMD_CHANGETOINPROC: case APPCMD_CHANGETOOUTPROC: // // Unload the specified wam process. // // Note that we're casting the incoming app path to // UNICODE. This is because wamreg would normally // convert the MD path (which is nativly UNICODE) to // MBCS in IIS 5.x. It's smart enough to know that // for 6.0 we want to work directly with UNICODE. // hr = sm_pWamProcessManager->GetWamProcessInfo( reinterpret_cast<LPCWSTR>(szAppPath), &pWamAppInfo, &fIsLoaded ); if ( FAILED( hr ) ) { goto Done; } DBG_ASSERT( pWamAppInfo ); // // If the app has not been loaded by the WAM_PROCESS_MANAGER // then there is nothing more to do. // if ( fIsLoaded == FALSE ) { break; } hr = sm_pWamProcessManager->GetWamProcess( pWamAppInfo->_szClsid, pWamAppInfo->_szAppPath, &dwWamSubError, &pWamProcess, sm_szInstanceId ); if ( FAILED( hr ) ) { // // Hey, this app was loaded just a moment ago! // DBG_ASSERT( FALSE ); goto Done; } DBG_ASSERT( pWamProcess ); hr = pWamProcess->Unload( 0 ); if ( FAILED( hr ) ) { goto Done; } break; case APPCMD_GETSTATUS: hr = sm_pWamProcessManager->GetWamProcessInfo( reinterpret_cast<LPCWSTR>(szAppPath), &pWamAppInfo, &fIsLoaded ); if ( SUCCEEDED( hr ) ) { if ( fIsLoaded ) { *pdwResult = APPSTATUS_Running; } else { *pdwResult = APPSTATUS_Stopped; } } break; } Done: UnlockWamReg(); if ( pWamAppInfo ) { pWamAppInfo->Release(); pWamAppInfo = NULL; } if ( pWamProcess ) { pWamProcess->Release(); pWamProcess = NULL; } if ( FAILED( hr ) ) { *pdwResult = APPSTATUS_Error; } return hr; } // static HRESULT W3_ISAPI_HANDLER::UpdateInprocIsapiHash( VOID ) /*++ Routine Description: Updates the table of InProcessIsapiApps Arguments: None Return Value: HRESULT --*/ { MB mb( g_pW3Server->QueryMDObject() ); W3_INPROC_ISAPI_HASH * pNewTable = NULL; W3_INPROC_ISAPI_HASH * pOldTable = NULL; DWORD i; LPWSTR psz; HRESULT hr = NOERROR; LK_RETCODE lkr = LK_SUCCESS; // // Allocate a new table and populate it. // pNewTable = new W3_INPROC_ISAPI_HASH; if ( !pNewTable ) { hr = HRESULT_FROM_WIN32( ERROR_NOT_ENOUGH_MEMORY ); goto ErrorExit; } if ( !mb.Open( L"/LM/W3SVC/" ) ) { hr = HRESULT_FROM_WIN32(GetLastError()); goto ErrorExit; } if ( !mb.GetMultisz( L"", MD_IN_PROCESS_ISAPI_APPS, IIS_MD_UT_SERVER, &pNewTable->_mszImages) ) { hr = HRESULT_FROM_WIN32(GetLastError()); mb.Close(); goto ErrorExit; } // // Merge ISAPI filter images into the list // AddAllFiltersToMultiSz( mb, &pNewTable->_mszImages ); mb.Close(); // // Now that we have a complete list, add them to the // hash table. // for ( i = 0, psz = (LPWSTR)pNewTable->_mszImages.First(); psz != NULL; i++, psz = (LPWSTR)pNewTable->_mszImages.Next( psz ) ) { W3_INPROC_ISAPI * pNewRecord; // // Allocate a new W3_INPROC_ISAPI object and add // it to the table // pNewRecord = new W3_INPROC_ISAPI; if ( !pNewRecord ) { hr = HRESULT_FROM_WIN32( ERROR_NOT_ENOUGH_MEMORY ); goto ErrorExit; } hr = pNewRecord->Create( psz ); if ( FAILED( hr ) ) { pNewRecord->DereferenceInprocIsapi(); pNewRecord = NULL; goto ErrorExit; } lkr = pNewTable->InsertRecord( pNewRecord, TRUE ); pNewRecord->DereferenceInprocIsapi(); pNewRecord = NULL; if ( lkr != LK_SUCCESS && lkr != LK_KEY_EXISTS ) { hr = E_FAIL; goto ErrorExit; } } // // Now swap in the new table and delete the old one // EnterCriticalSection( &sm_csInprocHashLock ); pOldTable = sm_pInprocIsapiHash; sm_pInprocIsapiHash = pNewTable; LeaveCriticalSection( &sm_csInprocHashLock ); if ( pOldTable ) { delete pOldTable; } DBG_ASSERT( SUCCEEDED( hr ) ); return hr; ErrorExit: DBG_ASSERT( FAILED( hr ) ); if ( pNewTable ) { delete pNewTable; }; return hr; } VOID AddFiltersToMultiSz( IN const MB & mb, IN LPCWSTR szFilterPath, IN OUT MULTISZ * pmsz ) /*++ Description: Add the ISAPI filters at the specified metabase path to pmsz. Called by AddAllFiltersToMultiSz. Arguments: mb metabase key open to /LM/W3SVC szFilterPath path of /Filters key relative to /LM/W3SVC pmsz multisz containing the in proc dlls Return: Nothing - failure cases ignored. --*/ { WCHAR szKeyName[MAX_PATH + 1]; STRU strFilterPath; STRU strFullKeyName; INT pchFilterPath = (INT)wcslen( szFilterPath ); if ( FAILED( strFullKeyName.Copy( szFilterPath ) ) ) { return; } DWORD i = 0; if( SUCCEEDED( strFullKeyName.Append( L"/", 1 ) ) ) { while ( const_cast<MB &>(mb).EnumObjects( szFilterPath, szKeyName, i++ ) ) { if( SUCCEEDED( strFullKeyName.Append( szKeyName ) ) ) { if( const_cast<MB &>(mb).GetStr( strFullKeyName.QueryStr(), MD_FILTER_IMAGE_PATH, IIS_MD_UT_SERVER, &strFilterPath ) ) { pmsz->Append( strFilterPath ); } } strFullKeyName.SetLen( pchFilterPath + 1 ); } } } VOID AddAllFiltersToMultiSz( IN const MB & mb, IN OUT MULTISZ * pmsz ) /*++ Description: This is designed to prevent ISAPI extension/filter combination dlls from running out of process. Add the base set of filters defined for the service to pmsz. Iterate through the sites and add the filters defined for each site. Arguments: mb metabase key open to /LM/W3SVC pmsz multisz containing the in proc dlls Return: Nothing - failure cases ignored. --*/ { WCHAR szKeyName[MAX_PATH + 1]; STRU strFullKeyName; DWORD i = 0; DWORD dwInstanceId = 0; if ( FAILED( strFullKeyName.Copy( L"/" ) ) ) { return; } AddFiltersToMultiSz( mb, L"/Filters", pmsz ); while ( const_cast<MB &>(mb).EnumObjects( L"", szKeyName, i++ ) ) { dwInstanceId = _wtoi( szKeyName ); if( 0 != dwInstanceId ) { // This is a site. if( SUCCEEDED( strFullKeyName.Append( szKeyName ) ) && SUCCEEDED( strFullKeyName.Append( L"/Filters" ) ) ) { AddFiltersToMultiSz( mb, strFullKeyName.QueryStr(), pmsz ); } strFullKeyName.SetLen( 1 ); } } } HRESULT W3_ISAPI_HANDLER::SetupUlCachedResponse( W3_CONTEXT * pW3Context, HTTP_CACHE_POLICY *pCachePolicy ) /*++ Routine Description: Setup a response to be cached by UL. Arguments: pW3Context - Context pCachePolicy - Cache policy to be filled in if caching desired Return Value: HRESULT --*/ { STACK_STRU( strFlushUrl, MAX_PATH ); HRESULT hr; DWORD dwTTL = 0; if ( pW3Context == NULL ) { DBG_ASSERT( FALSE ); return HRESULT_FROM_WIN32( ERROR_INVALID_PARAMETER ); } // // Find out if caching is enabled for this isapi request // if (!_pIsapiRequest->QueryCacheResponse()) { return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); } W3_RESPONSE *pResponse = pW3Context->QueryResponse(); LPCSTR pszExpires = pResponse->GetHeader( HttpHeaderExpires ); if ( pszExpires != NULL ) { LARGE_INTEGER liExpireTime; LARGE_INTEGER liCurrentTime; if ( !StringTimeToFileTime( pszExpires, &liExpireTime ) ) { return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); } GetSystemTimeAsFileTime( (FILETIME *)&liCurrentTime ); if ( liExpireTime.QuadPart <= liCurrentTime.QuadPart ) { return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); } dwTTL = ( liExpireTime.QuadPart - liCurrentTime.QuadPart ) / 10000000; } // // Get the exact URL used to flush UL cache // hr = pW3Context->QueryMainContext()->QueryRequest()->GetOriginalFullUrl( &strFlushUrl ); if ( FAILED( hr ) ) { return hr; } // // Setup UL cache response token // DBG_ASSERT( g_pW3Server->QueryUlCache() != NULL ); hr = g_pW3Server->QueryUlCache()->SetupUlCachedResponse( pW3Context, strFlushUrl, FALSE, NULL ); if ( SUCCEEDED( hr ) ) { if (pszExpires == NULL) { pCachePolicy->Policy = HttpCachePolicyUserInvalidates; } else { pCachePolicy->Policy = HttpCachePolicyTimeToLive; pCachePolicy->SecondsToLive = dwTTL; } } return hr; }
24.321271
102
0.539008
[ "object" ]
37d8d3d9d5febd518ac9c9d7674f9e7aaed846e4
3,525
hpp
C++
firmware/src/PeripheralDrivers/CanIO.hpp
sprenger120/remote_control_device
c375ab12683c10fd2918ea8345bcb06a5d78b978
[ "MIT" ]
1
2021-01-27T12:23:43.000Z
2021-01-27T12:23:43.000Z
firmware/src/PeripheralDrivers/CanIO.hpp
sprenger120/remote_control_device
c375ab12683c10fd2918ea8345bcb06a5d78b978
[ "MIT" ]
null
null
null
firmware/src/PeripheralDrivers/CanIO.hpp
sprenger120/remote_control_device
c375ab12683c10fd2918ea8345bcb06a5d78b978
[ "MIT" ]
null
null
null
#pragma once #include "Wrapper/Task.hpp" #include <queue.h> extern "C" { #include <canfestival/can.h> } #include <stm32f3xx_hal.h> /** * @brief Processes incoming and outgoing data from the can perihperal * Dispatches data to canfestival stack * */ namespace remote_control_device { class Logging; class Canopen; class CanIO { public: /** * @brief Initializes queues and registers can peripheral hooks * * @param task Task handle to use for internal processes * @param hCan can perihperal handle for internal processes */ static constexpr uint16_t StackSize = 300; CanIO(CAN_HandleTypeDef &hCan, Logging &log); virtual ~CanIO(); /** * @brief Set the Canopen Instance object * Both classes depend on another but canIO only needs * it after everything is brought up * * @param inst */ virtual void setCanopenInstance(Canopen& inst) { _canopen = &inst; } CanIO(const CanIO &) = delete; CanIO(CanIO &&) = delete; CanIO &operator=(const CanIO &) = delete; CanIO &operator=(CanIO &&) = delete; /** * @brief Sends TX frames, dispatches RX frames to canfestival, handles errors * * @param flags what event happened */ virtual void dispatch(uint32_t flags); static constexpr uint8_t NOTIFY_ATTEMPT_TX = 1 << 0; static constexpr uint8_t NOTIFY_RX_PENDING = 1 << 1; static constexpr uint8_t NOTIFY_ERROR = 1 << 2; static constexpr uint8_t NOTIFY_OVERLOAD = 1 << 3; static void retrieveMessageFromISR(CanIO &canio, CAN_HandleTypeDef *hcan, uint32_t mailboxNmbr); /** * @brief Retturns true if bus communication works as intendet * * @return true * @return false */ virtual bool isBusOK(); /** * @brief Adds a can frame to the TX queue * */ virtual void canSend(Message *); static void _canSend(Message*); /** * @brief Used for canfestival initialisation as calling canDispatch in Statemachine task * consumes too much stack that is usually not used there. * * @param m */ virtual void addRXMessage(Message &m); /** * @brief Queue size for TX and RX queue * increase when overload errors start appearing * */ static constexpr UBaseType_t QUEUES_SIZE = 16; /** * @brief How long a canSend call should wait for a slot in the TX queue * increase for high bus load * */ static constexpr TickType_t QUEUE_WAITTIME = pdMS_TO_TICKS(10); // Some functions to mock in tests static void testing_TxFailed() {}; static void testing_RxAttempt() {}; static void testing_Overload() {}; static void testing_Error() {}; private: CAN_HandleTypeDef &_can; Logging &_log; wrapper::Task _task; Canopen* _canopen{nullptr}; static CanIO *_instance; QueueHandle_t _rxQueue, _txQueue; bool _busOK = true; /* Hooks and support functions */ static void cbTxMailboxCompleteISR(CAN_HandleTypeDef *hcan); static void cbRxMsgPending0ISR(CAN_HandleTypeDef *hcan); static void cbRxMsgPending1ISR(CAN_HandleTypeDef *hcan); static void cbErrorISR(CAN_HandleTypeDef *hcan); static void cbOverloadISR(CAN_HandleTypeDef *hcan); /** * @brief Notifys canIO task about 'flag'. Attempts deferred processing * * @param flag */ static void finishCallback(uint32_t flag); static void taskMain(void* parameter); }; } // namespace remote_control_device
26.503759
100
0.666099
[ "object" ]
37def5788989ed3a672bf8fecf06a3eb5cebbca2
861
cpp
C++
Miscellaneous/InterviewBit/Array/SetZeroes.cpp
chirag-singhal/-Data-Structures-and-Algorithms
9f01b5cc0f382ed59bcd74444a0be1c3aa6cd1a3
[ "MIT" ]
24
2021-02-09T17:59:54.000Z
2022-03-11T07:30:38.000Z
Miscellaneous/InterviewBit/Array/SetZeroes.cpp
chirag-singhal/-Data-Structures-and-Algorithms
9f01b5cc0f382ed59bcd74444a0be1c3aa6cd1a3
[ "MIT" ]
null
null
null
Miscellaneous/InterviewBit/Array/SetZeroes.cpp
chirag-singhal/-Data-Structures-and-Algorithms
9f01b5cc0f382ed59bcd74444a0be1c3aa6cd1a3
[ "MIT" ]
3
2021-06-22T03:09:49.000Z
2022-03-09T18:25:14.000Z
#include <bits/stdc++.h> void setZeroes(std::vector<std::vector<int> > &A) { // Do not write main() function. // Do not read input, instead use the arguments to the function. // Do not print the output, instead return values as specified // Still have a doubt. Checkout www.interviewbit.com/pages/sample_codes/ for more details int n = A.size(); int m = A[0].size(); std::map<int, int> map; for(int i = 0; i < n; i++) { bool found = 0; for(int j = 0; j < m; j++) { if(A[i][j] == 0) { map[j] = 1; found = 1; } } for(int j = 0; found && j < m; j++) A[i][j] = 0; } for(int i = 0; i < m; i++) { if(map[i] == 1) { for(int j = 0; j < n; j++) { A[j][i] = 0; } } } }
28.7
93
0.440186
[ "vector" ]
37e4aa8018b9ab79298504891ff52da55f3813a0
14,798
cpp
C++
Final/Navigation.cpp
pts211/CS4096
6156d567ccdac9e422bb5f476093323f32f73ed8
[ "Apache-2.0" ]
2
2018-07-08T08:36:50.000Z
2021-03-10T08:38:06.000Z
Navigation/Navigation.cpp
pts211/CS4096
6156d567ccdac9e422bb5f476093323f32f73ed8
[ "Apache-2.0" ]
null
null
null
Navigation/Navigation.cpp
pts211/CS4096
6156d567ccdac9e422bb5f476093323f32f73ed8
[ "Apache-2.0" ]
null
null
null
#include "Navigation.h" #include <fstream> #include <queue> #include <math.h> // #include <iostream> // #include <string> // #include <cstring> // #include <dirent.h> using namespace std; double Node::DNE = 1000000.0; double Node::LARGE_NUM = 1000.0; // const int edge = 80; // const int red = 110; // const int green = 110; // const int blue = 170; const int STRAIGHT = 32768; const int REG_SPEED = 200; const int TURN_SPEED = 150; Navigation::Navigation(const char* filename, bool test) { roomba.start(); roomba.powerOn(); roomba.getSensors(Sensor::ALL); startTime = clock(); testMode = test; inputNodes(filename); sleep(2); if(allNodes.size() > 1) //keep in mind, the output path doesn't include the source { cout << "from " << allNodes[0].name << " to " << allNodes[allNodes.size()-1].name << endl; travelFromSourceToSink(&allNodes[0], &allNodes[allNodes.size()-1]); // travelFromSourceToSink(walkToStartingNode(), &allNodes[allNodes.size()-1]); } } void Navigation::inputNodes(const char* filename) { ifstream in; string inStr; int numNeighbors; int neighbor; int weight; int direction; in.open(filename); if(in.good()){ //if the file was successfully opened cout << "is good" << endl; in >> inStr; //read the number of nodes numNodes = atoi(inStr.c_str()); //change the string we read to an int cout << "num nodes " << numNodes << endl; for(int i = 0; i < numNodes; i++) { //loop for each node we have in >> inStr; //read the name of a node Node n(inStr, Node::DNE); //create a new node with nonexistant g value n.parent = NULL; allNodes.push_back(n); //put that node in the list of all nodes } for(int i = 0; i < numNodes; i++) { //loop for each node we have in >> inStr; //read the number of neighbors a node has numNeighbors = atoi(inStr.c_str()); for(int j = 0; j < numNeighbors; j++) { //loop for each neighbor of a node in >> inStr; neighbor = atoi(inStr.c_str()); //read the nodes neighbor in >> inStr; weight = atoi(inStr.c_str()); in >> inStr; direction = atoi(inStr.c_str()); // allNodes[i].info[j] = make_tuple(&allNodes[neighbor], weight, direction); allNodes[i].neighbors.push_back(&allNodes[neighbor]); //store the node in the list of neighbors // in >> inStr; //read the neighbors weight allNodes[i].weights.push_back(weight); //assign the weight switch(direction) { //assign the direction we need to go in to reach the neighbor case 1: allNodes[i].allDirections.push_back(NORTH); break; case 2: allNodes[i].allDirections.push_back(SOUTH); break; case 3: allNodes[i].allDirections.push_back(EAST); break; case 4: allNodes[i].allDirections.push_back(WEST); break; } } } } } bool Navigation::travelFromSourceToSink(Node* source, Node* sink) { vector<Node*> path = findPath(source, sink); //should be (current, sink) with current starting at source //#ifdef DEBUG outputPath(path); //#endif cout << "size: " << path.size() << endl; walkPath(path); return true; } Node* Navigation::getNode(int index) { return &allNodes[index]; } vector<Node*> Navigation::dbgReconstructPath(Node* source, Node* sink) { vector<Node*> path; #ifdef TEST return reconstructPath(source, sink); #else cout << "This function is only for testing." << endl; #endif return path; } vector<Node*> Navigation::dbgFindPath(Node* source, Node* sink) { vector<Node*> path; #ifdef TEST return findPath(source, sink); #else cout << "This function is only for testing." << endl; #endif return path; } void Navigation::rotate(int degrees) { double degreesRotated = 0; int16_t speed = 50; // roomba.getSensors(Sensor::ALL).getAngle(); cout << "\t\t\t\t\t\t\t\t\t\tTURNING " << degrees << " DEGREES" << endl; cout << "\t\t\t\t\tSTOP DRIVE" << endl; roomba.drive(0,0); // roomba.getSensors(Sensor::ALL); roomba.getSensor().getAngle(); if(degrees < 0) { roomba.drive(speed, -1); while((degreesRotated > degrees + 5) || (degreesRotated < degrees - 5)) { // degreesRotated -= roomba.getSensors(Sensor::ALL).getAngle(); if(roomba.getSensors(Sensor::ALL)) { degreesRotated += roomba.getSensor().getAngle(); //cout << "Degrees Rotated: " << degreesRotated << endl; // cout << "getAngle: " << roomba.getSensor().getAngle(); //usleep(50000); } } } else { roomba.drive(speed, 1); while((degreesRotated < degrees -5) || (degreesRotated > degrees + 5)) { // degreesRotated += roomba.getSensors(Sensor::ALL).getAngle(); if(roomba.getSensors(Sensor::ALL)) { //cout << "Degrees Rotated: " << degreesRotated << endl; degreesRotated -= roomba.getSensor().getAngle(); //usleep(50000); } } } roomba.drive(0, 0); } Node* Navigation::walkToStartingNode() { while(1) { cam.output(); // sleep(2); moveForwardUntilSignOrBlockage(); if(!getFloorSign().empty()) for(int i = 0; i < allNodes.size() - 1; i++) if(getFloorSign() == allNodes[i].name) return &allNodes[i]; if(getPathIsBlocked()) { rotate(180); } } } void Navigation::moveForwardUntilSignOrBlockage() { // roomba.getSensors(Sensor::ALL); cout << "Percent Power: " << (float)roomba.getSensor().getCharge() / (float)roomba.getSensor().getCapacity() << endl; cout << "moveForwardUntilSignOrBlockage" << endl; cout << "\t\t\t\t\tDRIVING STRAIGHT" << endl; roomba.drive(REG_SPEED, STRAIGHT); // cout << "start cam check loop" << endl; cam.update(); while(getFloorSign().empty() && !getPathIsBlocked()) { // cout << "about to update" << endl; cam.update(); //cam.output(); cout << "[" << getPathIsBlocked() << ", " << getFloorSign() << ", " << cam.getslope() << "]" << endl; // cout << "updated" << endl; if((cam.getslope() != cam.getslope())) //if the value is NaN { cout << "\t\t\t\t\tSTOP DRIVE" << endl; roomba.drive(0,0); // cout << "NAN" << endl; } else { if(cam.getslope() < -.4) { //arbitrary tolerances. slope will be 0 if we are going straight cout << "\t\t\t\t\tTURNING TO THE RIGHT" << endl; roomba.drive(TURN_SPEED, -1500); while(cam.getslope() < -.1 && getFloorSign().empty()) { // rotate(5); cam.update(); //cam.output(); cout << "[" << getPathIsBlocked() << ", " << getFloorSign() << ", " << cam.getslope() << "]" << endl; } cout << "\t\t\t\t\tDRIVING STRAIGHT" << endl; roomba.drive(REG_SPEED, STRAIGHT); } else if(cam.getslope() > .4) { cout << "\t\t\t\t\tTURNING TO THE LEFT" << endl; roomba.drive(TURN_SPEED, 1500); while(cam.getslope() > .1 && getFloorSign().empty()) { // rotate(-5); cam.update(); //cam.output(); cout << "[" << getPathIsBlocked() << ", " << getFloorSign() << ", " << cam.getslope() << "]" << endl; } cout << "\t\t\t\t\tDRIVING STRAIGHT" << endl; roomba.drive(REG_SPEED, STRAIGHT); } } } if(!getFloorSign().empty()) { cout << "got a floor sign" << endl; cout << "[" << getPathIsBlocked() << ", " << getFloorSign() << ", " << cam.getslope() << "]" << endl; //move forward just a bit more so we're on top of it. cout << "\t\t\t\t\tDRIVING STRAIGHT" << endl; roomba.drive(REG_SPEED, STRAIGHT); //temp arbitrary numbers // while(!getFloorSign().empty()) // { // cout << "[" << getPathIsBlocked() << ", " << getFloorSign() << ", " << cam.getslope() << "]" << endl; // } sleep(3.5); } cout << "end moveForwardUntilSignOrBlockage" << endl; } void Navigation::walkPath(vector<Node*> path) { cout << "walkPath(path)" << endl; //walk the walk using roomba commands if(path.empty()) return; //assume we're on node path[0] and turn towards path[1]. for(size_t i=1; i<path.size(); ++i) { string nodeGoal = path[i]->name; cout << "about to move forward" << endl; moveForwardUntilSignOrBlockage(); if(getPathIsBlocked()) { cout << "Path is blocked. Turning around." << endl; rotate(180); //turn around //move towards last intersection moveForwardUntilSignOrBlockage(); //ASSUMING NO BLOCKAGE HERE //update weights where blockage exists incrementWeight(path[i-1], path[i]); //we turned around, so switch direction we traveled switch(path[i]->directionTraveled) { case NORTH: path[i-1]->directionTraveled = SOUTH; break; case SOUTH: path[i-1]->directionTraveled = NORTH; break; case EAST: path[i-1]->directionTraveled = WEST; break; case WEST: path[i-1]->directionTraveled = EAST; break; } path = findPath(path[i-1], path[path.size()-1]); turnAtIntersection(path, 0); walkPath(path); } else // else if(!getFloorSign().empty()) { turnAtIntersection(path, i); cam.update(); // if(getFloorSign() == path[path.size()-1]->name) // { // arrived = true; // } // else // { // } } } cout << "\t\t\t\t\tSTOP DRIVE" << endl; roomba.drive(0,0); } void Navigation::turnAtIntersection(vector<Node*> path, int currentNode) { cout << "turnAtIntersection" << endl; switch(path[currentNode]->directionTraveled) { case NORTH: switch(path[currentNode+1]->directionTraveled) { case NORTH: break; case SOUTH: rotate(180); break; case EAST: rotate(-90); break; case WEST: rotate(90); break; } break; case SOUTH: switch(path[currentNode+1]->directionTraveled) { case NORTH: rotate(180); break; case SOUTH: break; case EAST: rotate(90); break; case WEST: rotate(-90); break; } break; case EAST: switch(path[currentNode+1]->directionTraveled) { case NORTH: rotate(90); break; case SOUTH: rotate(-90); break; case EAST: break; case WEST: rotate(180); break; } break; case WEST: switch(path[currentNode+1]->directionTraveled) { case NORTH: rotate(-90); break; case SOUTH: rotate(90); break; case EAST: rotate(180); break; case WEST: break; } break; } } vector<Node*> Navigation::findPath(Node* source, Node* sink) { cout << "findPath" << endl; for(size_t i=0; i<allNodes.size(); ++i) { allNodes[i].g_score = Node::DNE; allNodes[i].parent = NULL; } source->g_score = 0.0; //The set of tentative Nodes that need to be evaluated, starting with sink queue<Node*> openSet; openSet.push(source); //while openset is not empty while(!openSet.empty()) { //cout << "loop openSet.size() :: " << openSet.size() << endl; Node* current = openSet.front(); // cout << current->name << endl; openSet.pop(); //for each neighbor in current->neighbors //cout << "neighbors.size() :: " << current->neighbors.size() << endl; for(size_t i=0; i<current->neighbors.size(); ++i) { Node* neighbor = current->neighbors[i]; if(neighbor == NULL) continue; double tempScore = current->g_score + current->weights[i]; //if neighbor not yet evaluated or better score if(neighbor->g_score == Node::DNE || tempScore < neighbor->g_score) { //if neighbor not yet evaluated if(neighbor->g_score == Node::DNE) //add neighbor to openset openSet.push(neighbor); //came_from[neighbor] = current neighbor->parent = current; //set the direction we will travel neighbor->directionTraveled = current->allDirections[i]; //g_score[neighbor] = tentative_g_score neighbor->g_score= tempScore; } } } cout << "find path returning" << endl; return reconstructPath(source, sink); } vector<Node*> Navigation::reconstructPath(Node* source, Node* sink) { Node* current = sink; vector<Node*> path; while(current->parent != NULL) { path.insert(path.begin(), current); current = current->parent; } path.insert(path.begin(), source); cout << "reconstructPath returning" << endl; return path; } void Navigation::incrementWeight(Node* n1, Node* n2) { for(size_t i=0; i<n1->neighbors.size(); ++i) { if(n1->neighbors[i] == n2) { n1->weights[i] += Node::LARGE_NUM; break; } } for(size_t i=0; i<n2->neighbors.size(); ++i) { if(n2->neighbors[i] == n1) { n2->weights[i] += Node::LARGE_NUM; break; } } } string Navigation::getFloorSign() { if(testMode) { return _getFloorSign(); } else { return cam.getfloorsign(); } } string Navigation::_getFloorSign() { double firstTurn = 11.61; double timePassed = ((double)clock() - (double)startTime)/CLOCKS_PER_SEC; cout << "timePassed: " << timePassed << endl; if (timePassed < firstTurn) { return ""; } else if (timePassed < firstTurn + .09) { return "testA"; } else if (timePassed < firstTurn + 7) { return ""; } else if (timePassed < firstTurn + 7.09) { return "testB"; } return ""; } bool Navigation::getPathIsBlocked() { if(testMode) { return _getPathIsBlocked(); } else { return cam.getpathisblocked(); } } bool Navigation::_getPathIsBlocked() { double timePassed = ((double)clock() - (double)startTime)/CLOCKS_PER_SEC; if (timePassed < 10) { return false; } else if (timePassed < 12) { return false; } else { return false; } return false; } void Navigation::outputPath(const vector<Node*>& path) { cout << endl << "start path" << endl; for(size_t i=0; i<path.size(); ++i) { cout << "\t" << path[i]->name << endl; } cout << "end path\n" << endl; } void Navigation::outputAllNodes() { for(size_t i=0; i<allNodes.size(); ++i) { cout << allNodes[i].name << " " << allNodes[i].neighbors.size() << endl; } }
25.602076
119
0.567104
[ "vector" ]
37e4bf50ecb182ec9d75319ec50931c90c0ee9f0
5,680
cxx
C++
hxisgd/tasks/hxisgdsff/.doInstrum.cxx
honsys/legacy
c8662e0df68e8169ec6550d1c0c11f3cdc8bfda8
[ "MIT" ]
null
null
null
hxisgd/tasks/hxisgdsff/.doInstrum.cxx
honsys/legacy
c8662e0df68e8169ec6550d1c0c11f3cdc8bfda8
[ "MIT" ]
null
null
null
hxisgd/tasks/hxisgdsff/.doInstrum.cxx
honsys/legacy
c8662e0df68e8169ec6550d1c0c11f3cdc8bfda8
[ "MIT" ]
null
null
null
#if !defined(DOINSTRUM_C) #define DOINSTRUM_C /** \file Implementaion of the doWork function for the Astro-H FITS b-table 'blob slicer' to help process First Fits Files. This derives from James Peachey's "ahdemo" Build 0.0 example. \author David B. Hon \date Feb-Mar-Apr 2012 */ /// all includes needed and local function declarations -- namespace ahhxisgd /// note some of these funcs. may move into the ahfits or ahgen namespaces /// and associated libs... // Local includes. #include "ahhxisgd.h" AHHXISGD_H(doinstrum) #include "ahsgd/ahSGDtyps.h" AHSGDTYPS_H(doinstrum) #include "ahhxi/ahHXItyps.h" AHHXITYPS_H(doinstrum) #include "ahtlm/ahBits.h" AHBITS_H(doinstrum) #include "ahtlm/ahSlice.h" AHSLICE_H(doinstrum) #include "ahtlm/ahTLM.h" AHTLM_H(doinstrum) #include "ahtlm/ahTLMIO.h" AHTLMIO_H(doinstrum) #include "ahtlm/ahTLMinfoCache.h" AHTLMINFOCACHE_H(doinstrum) #include <sys/types.h> #include <sys/stat.h> #include <stdio.h> #include <stdlib.h> #include <ctype.h> // isdigit, ispunct, isspace, etc. #include <cstring> #include <stdexcept> #include <string> #include <utility> #include <iostream> #include <sstream> #include <map> #include <vector> using namespace ahtlm; using namespace ahhxi; using namespace ahsgd; using namespace ahfits; using namespace ahgen; using namespace ahlog; using namespace std; namespace { const string cvsId = "$Name: $ $Id: doInstrum.cxx,v 1.8 2012/07/18 16:41:21 dhon Exp $"; } namespace ahhxisgd { int creatIOpaths(vector< string >& paths) { int np = (int)paths.size(); if( np <= 0 ) { paths.push_back("./input"); paths.push_back("./output"); paths.push_back("./expected_output"); np = (int)paths.size(); } mode_t m= 0775, m0 = umask(0); // preserve orig. umask... for( int i = 0; i < np; ++i ) { string& filename = paths[i]; AH_INFO(ahlog::LOW) << " :: " << filename << endl; mkdir(filename.c_str(), m); } umask(m0); return np; } int creatIOpaths(string& input, string& output, string& expect) { vector< string > paths; if( input == "" ) input = "./input"; if( output == "" ) output = "./output"; if( expect == "" ) expect = "./expected_output"; paths.push_back(input); paths.push_back(output); paths.push_back(expect); return creatIOpaths(paths); } int writeTextFile(const string& content, const string& filename) { string path = filename; size_t slashpos = path.rfind("/"); if( string::npos != slashpos ) { // slash in filename -- be sure path exists path = path.substr(0, slashpos); vector< string > paths; paths.push_back(path); creatIOpaths(paths); } AH_INFO(ahlog::LOW) << " writing " << filename << endl; FILE* fp = fopen(filename.c_str(), "w"); fprintf(fp, "%s", content.c_str()); fclose(fp); return (int)content.length(); } int doInstrum(InstrumWork& input, InstrumWork& output, int* checkpoint) { AH_INFO(ahlog::LOW) << __PRETTY_FUNCTION__ << " instrument input : " << input.name << ", output: " << output.name << endl; // "HXI"; // or "SGD"; if( input.name != output.name ) { AH_INFO(ahlog::LOW) << __PRETTY_FUNCTION__ << " must be congruent instrument for inpout and output processing ... " <<endl; if( checkpoint ) *checkpoint = -1; return -1; } string instrum = input.name; AH_INFO(ahlog::LOW) << __PRETTY_FUNCTION__ << " inHdu == " << input.hduIdx << ", inRow: " << input.rowIdx << endl; AH_INFO(ahlog::LOW) << __PRETTY_FUNCTION__ << " outHdu == " << output.hduIdx << ", outRow: " << output.rowIdx << endl; // check the current extension hdu setting for the input.file and output.file AhFitsFilePtrs vector<string> in_extnames, out_extnames; int inhdus = getHDUnames(input.file, in_extnames); for( int i = 0; i < inhdus; ++i ) { AH_INFO(ahlog::LOW) << __PRETTY_FUNCTION__ << " extension HDU name " << i << ": " << in_extnames[i] << endl; } int outhdus = getHDUnames(output.file, out_extnames); for( int i = 0; i < outhdus; ++i ) { AH_INFO(ahlog::LOW) << __PRETTY_FUNCTION__ << " extension HDU name " << i << ": " << out_extnames[i] << endl; } vector<string> incol_names, outcol_names; map<string, int> incol_hash, outcol_hash; int incolcnt = getAllColNamesAndNums(input.file, incol_names, incol_hash, input.hduIdx); for( int i = 0; i < incolcnt; ++i ) { string& name = incol_names[i]; int colnum = incol_hash[name]; AH_INFO(ahlog::LOW) << __PRETTY_FUNCTION__ << " input column name and number: " << name << " ==> " << colnum << endl; } int outcolcnt = getAllColNamesAndNums(output.file, outcol_names, outcol_hash, output.hduIdx); for( int i = 0; i < outcolcnt; ++i ) { string& name = outcol_names[i]; int colnum = outcol_hash[name]; AH_INFO(ahlog::LOW) << __PRETTY_FUNCTION__ << " output column name and number: " << name << " ==> " << colnum << endl; } if( "HXI" == instrum ) { doHXIwork(input.file, output.file); if( checkpoint ) *checkpoint = -1; } else if( "SGD" == instrum ) { doSGDwork(input.file, output.file); if( checkpoint ) *checkpoint = -1; } else { AH_INFO(ahlog::LOW) << __PRETTY_FUNCTION__ << " only support Astro-H HXI or SGD ..." << endl; if( checkpoint ) *checkpoint = -1; return -1; } if( ! checkpoint ) return 0; (*checkpoint)--; AH_INFO(ahlog::LOW) << __PRETTY_FUNCTION__ << " checkpoint: " << *checkpoint << endl; return *checkpoint; } // end doInstrum } // end namespace ahhxisgd #endif // DOINSTRUM_C
32.457143
151
0.632746
[ "vector" ]
37ecaab7b1404cc3bc9e848b5d37032a5d0e501a
1,607
hpp
C++
include/x86/codegen.hpp
martinogden/mer
33b4b39b1604ce0708b0d3d1c809b95683a2f4cb
[ "Unlicense" ]
2
2019-11-17T22:54:16.000Z
2020-08-07T20:53:25.000Z
include/x86/codegen.hpp
martinogden/mer
33b4b39b1604ce0708b0d3d1c809b95683a2f4cb
[ "Unlicense" ]
null
null
null
include/x86/codegen.hpp
martinogden/mer
33b4b39b1604ce0708b0d3d1c809b95683a2f4cb
[ "Unlicense" ]
null
null
null
#pragma once #include <string> #include <vector> #include "generator.hpp" #include "inst/inst.hpp" #include "regalloc/regalloc.hpp" #include "x86/asm.hpp" #include "set.hpp" // Emit MACH-O x86-64 asm for OS X class X86CodeGen { private: std::vector<Reg> callee_saved_regs; std::vector<Reg> caller_saved_regs; uint num_spilled; const InstFun& fun; const Alloc& alloc; std::vector<X86Asm> as; void prologue(); void epilogue(); void emitLabel(const std::string& label); void emit(X86Asm::OpCode opcode); void emit(X86Asm::OpCode opcode, const Operand& dst); void emit(X86Asm::OpCode opcode, const Operand& dst, const Operand& src); void visit(const Inst& inst); void visitLabel(const Operand& op); void visitSub(const Operand& dst, const Operand& src1, const Operand& src2); void visitDiv(const Operand& dst, const Operand& src1, const Operand& src2); void visitMod(const Operand& dst, const Operand& src1, const Operand& src2); void visitMov(const Operand& dst, const Operand& src); void visitJmp(const Operand& op); void visitRet(const Operand& op); void visitEnter(); void visitCall(const Operand& dst, const Operand& name, const Operand& src); void visitArg(const Operand& i, const Operand& op); void visitBinary(Inst::OpCode opcode, const Operand& dst, const Operand& src1, const Operand& src2); void visitCJmp(Inst::OpCode opcode, const Operand& operand, const Operand& t, const Operand& f); Operand getDst(const Operand& dst); void storeDst(const Operand& dst); uint getNumSlots(uint n); public: X86CodeGen(const InstFun& fun, const Alloc& alloc); X86Fun run(); };
30.903846
101
0.738643
[ "vector" ]
37ed1eccfe6d4129747eb225ccb3ea8123ae62b0
9,009
cpp
C++
src/linux_parser.cpp
freire-l/CppND-System-Monitor
921032fca54f2742be9c92d5113ecbbe1c173d0c
[ "MIT" ]
null
null
null
src/linux_parser.cpp
freire-l/CppND-System-Monitor
921032fca54f2742be9c92d5113ecbbe1c173d0c
[ "MIT" ]
null
null
null
src/linux_parser.cpp
freire-l/CppND-System-Monitor
921032fca54f2742be9c92d5113ecbbe1c173d0c
[ "MIT" ]
null
null
null
#include <dirent.h> #include <unistd.h> #include <sstream> #include <string> #include <vector> #include <unordered_map> #include <iostream> #include "linux_parser.h" using std::stof; using std::string; using std::to_string; using std::vector; string LinuxParser::str_check(string my_string){ if(my_string!="") return my_string; else return "0"; } // DONE: An example of how to read data from the filesystem string LinuxParser::OperatingSystem() { string line; string key; string value; std::ifstream filestream(kOSPath); if (filestream.is_open()) { while (std::getline(filestream, line)) { std::replace(line.begin(), line.end(), ' ', '_'); std::replace(line.begin(), line.end(), '=', ' '); std::replace(line.begin(), line.end(), '"', ' '); std::istringstream linestream(line); while (linestream >> key >> value) { if (key == "PRETTY_NAME") { std::replace(value.begin(), value.end(), '_', ' '); return value; } } } } return value; } // DONE: An example of how to read data from the filesystem string LinuxParser::Kernel() { string os, kernel, version; string line; std::ifstream stream(kProcDirectory + kVersionFilename); if (stream.is_open()) { std::getline(stream, line); std::istringstream linestream(line); linestream >> os >> version >> kernel; } return kernel; } //*BONUS: Update this to use std::filesystem vector<int> LinuxParser::Pids() { vector<int> pids; DIR* directory = opendir(kProcDirectory.c_str()); struct dirent* file; while ((file = readdir(directory)) != nullptr) { // Is this a directory? if (file->d_type == DT_DIR) { // Is every character of the name a digit? string filename(file->d_name); if (std::all_of(filename.begin(), filename.end(), isdigit)) { int pid = stoi(str_check(filename)); pids.push_back(pid); } } } closedir(directory); return pids; } // TODO: Read and return the system memory utilization float LinuxParser::MemoryUtilization() { string line; string key, value, unit; float mem_tot, mem_free; std::unordered_map <string, int> umap; //read the first 4 lines, and fill the unordered map with the labels and values int i = 3; std::ifstream filestream(kProcDirectory+kMeminfoFilename); if (filestream.is_open()) { while (i>=0) { std::getline(filestream, line); std::replace(line.begin(), line.end(), ':', ' '); std::istringstream linestream(line); linestream >> key >> value >> unit; umap[key] =stoi(str_check(value)); i--; } } mem_tot = float(umap.at("MemTotal")); mem_free = float(umap.at("MemFree")); return ((mem_tot-mem_free)/mem_tot); } // TODO: Read and return the system uptime long LinuxParser::UpTime() { string uptime, idle; string line; std::ifstream stream(kProcDirectory + kUptimeFilename); if (stream.is_open()) { std::getline(stream, line); std::istringstream linestream(line); linestream >> uptime >> idle; return stol(str_check(uptime)); } return 0; } // TODO: Read and return the number of jiffies for the system long LinuxParser::Jiffies() { return 0; } // TODO: Read and return the number of active jiffies for a PID // REMOVE: [[maybe_unused]] once you define the function long LinuxParser::ActiveJiffies(int pid) { string line; vector <string> parse; string value; std::ifstream stream(kProcDirectory +to_string(pid) + kStatFilename); if (stream.is_open()) { while(std::getline(stream, line)){ std::istringstream linestream(line); //fill out the vector with values parsed from the line while (linestream >> value) { parse.push_back(value); } return stol(str_check(parse[13]))+stol(str_check(parse[14]))+stol(str_check(parse[15]))+stol(str_check(parse[16])); } } return 0; } // TODO: Read and return the number of active jiffies for the system long LinuxParser::ActiveJiffies() { return 0; } // TODO: Read and return the number of idle jiffies for the system long LinuxParser::IdleJiffies() { return 0; } // TODO: Read and return CPU utilization //Function that parses the first line of /proc/stat, and returns a vector with all its corresponding fields vector<string> LinuxParser::CpuUtilization() { string name, user, nice, system, idle, iowait, irq, softirq, steal, guest, guest_nice; string line; std::ifstream stream(kProcDirectory + kStatFilename); if (stream.is_open()) { std::getline(stream, line); std::istringstream linestream(line); linestream >> name >> user >> nice >> system >> idle >> iowait >> irq >> softirq >> steal >> guest >> guest_nice; } vector<string> cpu_info{name, user, nice, system, idle, iowait, irq, softirq, steal, guest, guest_nice}; return cpu_info; } // TODO: Read and return the total number of processes int LinuxParser::TotalProcesses() { string line; string key, value; std::ifstream stream(kProcDirectory + kStatFilename); if (stream.is_open()) { while(std::getline(stream, line)){ std::istringstream linestream(line); linestream >> key >> value; if(key == "processes") return stoi(str_check(value)); } } return 0; } // TODO: Read and return the number of running processes int LinuxParser::RunningProcesses() { string line; string key, value; std::ifstream stream(kProcDirectory + kStatFilename); if (stream.is_open()) { while(std::getline(stream, line)){ std::istringstream linestream(line); linestream >> key >> value; if(key == "procs_running") return stoi(str_check(value)); } } return 0; } // TODO: Read and return the command associated with a process // REMOVE: [[maybe_unused]] once you define the function string LinuxParser::Command(int pid) { string line; unsigned int char_limit = 40; string key, id1; std::ifstream stream(kProcDirectory +to_string(pid) + kCmdlineFilename); if (stream.is_open()) { std::getline(stream, line); if (line.size()>char_limit) return (line.substr(0,char_limit)+"..."); else return line; //return the whole line } return string(); } // TODO: Read and return the memory used by a process // REMOVE: [[maybe_unused]] once you define the function string LinuxParser::Ram(int pid) { string line; string key, id1; std::ifstream stream(kProcDirectory +to_string(pid) + kStatusFilename); if (stream.is_open()) { while(std::getline(stream, line)){ std::istringstream linestream(line); //get tag and memory linestream >> key >> id1; //if(key == "VmSize:") //Using VmData instead of VmSize in order to display pysical RAM, as kindly suggested by a reviewer and can be seen here https://man7.org/linux/man-pages/man5/proc.5.html if(key == "VmData:") return id1; } } return string(); } // TODO: Read and return the user ID associated with a process // REMOVE: [[maybe_unused]] once you define the function string LinuxParser::Uid(int pid) { string line; string key, id1; std::ifstream stream(kProcDirectory +to_string(pid) + kStatusFilename); if (stream.is_open()) { while(std::getline(stream, line)){ std::istringstream linestream(line); //get tag and id linestream >> key >> id1; if(key == "Uid:") return id1; } } return string(); } // TODO: Read and return the user associated with a process // REMOVE: [[maybe_unused]] once you define the function string LinuxParser::User(string uid) { string line; string name, x, key; std::ifstream filestream(kPasswordPath); if (filestream.is_open()){ while (std::getline(filestream, line)) { //clean name std::replace(line.begin(), line.end(), ':', ' '); std::istringstream linestream(line); linestream >> name >> x >> key; if(key == uid){ return name; } } } return string(); } // TODO: Read and return the uptime of a process // REMOVE: [[maybe_unused]] once you define the function long LinuxParser::UpTime(int pid) { string line; vector <string> parse; string value; long up_time_sys; long time_pid_start; std::ifstream stream(kProcDirectory +to_string(pid) + kStatFilename); if (stream.is_open()) { while(std::getline(stream, line)){ std::istringstream linestream(line); //parse all tokens while (linestream >> value) { parse.push_back(value); } //return only the uptime up_time_sys = LinuxParser::UpTime(); time_pid_start = (stol(str_check(parse[21]))/sysconf(_SC_CLK_TCK)); return up_time_sys - time_pid_start; } } return 0; }
27.805556
178
0.634699
[ "vector" ]
37eee36b876688e6a5537b83a1c5fa01cf7a637b
10,962
cpp
C++
Flux++/src/xcb_renderer.cpp
Glinrens-corner/Fluxpp
ea64b56d2922a0ab2a946c6a75ceb5633c5ec943
[ "MIT" ]
2
2021-03-25T05:50:17.000Z
2021-04-06T12:53:18.000Z
Flux++/src/xcb_renderer.cpp
Glinrens-corner/Fluxpp
ea64b56d2922a0ab2a946c6a75ceb5633c5ec943
[ "MIT" ]
1
2021-03-09T00:03:56.000Z
2021-03-09T00:03:56.000Z
Flux++/src/xcb_renderer.cpp
Glinrens-corner/Fluxpp
ea64b56d2922a0ab2a946c6a75ceb5633c5ec943
[ "MIT" ]
1
2021-04-05T13:10:55.000Z
2021-04-05T13:10:55.000Z
#include "backend/xcb_renderer.hpp" #include <xcb/render.h> #include <xcb/xcb_image.h> #include <hb.h> #include <hb-ft.h> #include <thread> #include <stdexcept> #include <chrono> #include <cassert> #include <fstream> #include <iostream> #include <algorithm> #include <stack> #include "widget.hpp" #include "gui_event.hpp" namespace { FT_Library ft_library; } namespace fluxpp { namespace backend{ namespace xcb { using events::Coordinate; using widgets::Size; using path_stack_t = std::stack< std::pair<std::size_t,uuid_t>,std::vector<std::pair<std::size_t,uuid_t> > > ; class PositionStack{ PositionStack(){ this->stack_.push(Coordinate{0,0}); }; void push(Coordinate coord){ this->stack_.push(this->stack_.top() +coord) ;}; const Coordinate& top()const{ return this->stack_.top();}; void pop(){ this->stack_.pop();}; private: std::stack<Coordinate, std::vector<Coordinate>> stack_{}; }; namespace detail { bool query_render_extension(xcb_connection_t *connection ){ const xcb_query_extension_reply_t * render_extension = xcb_get_extension_data(connection, &xcb_render_id); return static_cast<bool>(render_extension); }; }; XCBWindowRenderer XCBWindowRenderer::create(xcb_connection_t * connection, Size size) { xcb_screen_t* screen = xcb_setup_roots_iterator( xcb_get_setup(connection)).data; if (detail::query_render_extension( connection) ){ }else { throw std::exception(); }; if(FT_Init_FreeType(&ft_library)){ throw std::runtime_error("could not initiate freetype"); }; xcb_window_t win = xcb_generate_id(connection); uint32_t mask=XCB_CW_BACK_PIXEL | XCB_CW_EVENT_MASK; uint32_t values[2]; values[0] = screen->white_pixel; values[1]= XCB_EVENT_MASK_EXPOSURE |XCB_EVENT_MASK_BUTTON_PRESS |XCB_EVENT_MASK_STRUCTURE_NOTIFY; xcb_create_window( connection, XCB_COPY_FROM_PARENT, win, screen->root, 0, 0, size.width, size.height, 10, XCB_WINDOW_CLASS_INPUT_OUTPUT, screen->root_visual, mask, values); const uint32_t config_values [] = {200,100 }; xcb_configure_window( connection, win, XCB_CONFIG_WINDOW_X |XCB_CONFIG_WINDOW_Y, config_values) ; xcb_map_window(connection, win); xcb_flush(connection); return {win,screen,connection , size}; }; XCBWindowRenderer::~XCBWindowRenderer(){ }; void XCBWindowRenderer::render(std::map<uuid_t,std::unique_ptr<DrawCommandBase>>& commands , uuid_t window_uuid){ path_stack_t path_stack{}; path_stack.push({0,window_uuid}); uint8_t* bitmap = new uint8_t[this->size_.width * this->size_.height*4]; this->clear(bitmap,this->size_ ); while(path_stack.size()>=1){ auto [child_pos, uuid] = path_stack.top( ); DrawCommandBase* next_item = commands.at(uuid).get(); switch (next_item->command_type()){ case CommandType::node: { auto command = dynamic_cast<NodeCommand*>(next_item); if ( command->children_.size()> child_pos){ path_stack.push({0,command->children_[child_pos]}); } else { path_stack.pop(); path_stack.top().first+=1; } }; break; case CommandType::window_node: { auto command = dynamic_cast<WindowNodeCommand*>(next_item); assert(path_stack.size() == 1); if ( command->children_.size()> child_pos){ path_stack.push({0,command->children_[child_pos]}); } else { path_stack.pop(); } }; break; case CommandType::draw_color: this->render_command( dynamic_cast<DrawColorCommand*>(next_item), bitmap, this->size_); path_stack.pop(); path_stack.top().first+=1; break; case CommandType::draw_text: this->render_command( dynamic_cast<DrawTextCommand*>(next_item), bitmap, this->size_); path_stack.pop(); path_stack.top().first+=1; break; default: throw std::runtime_error( "unknown type"); }; }; xcb_image_t* image =xcb_image_create_native( this->connection_, this->size_.width, this->size_.height, XCB_IMAGE_FORMAT_Z_PIXMAP, this->screen_->root_depth, bitmap, this->size_.width * this->size_.height*4, bitmap ); if(!image ) throw std::runtime_error("couldn't create image"); xcb_pixmap_t framebuffer= xcb_generate_id(this->connection_); xcb_create_pixmap( this->connection_, this->screen_->root_depth, framebuffer, this->window_, this->size_.width, this->size_.height); xcb_gcontext_t pixcontext = xcb_generate_id(this->connection_); uint32_t pixmask = XCB_GC_FOREGROUND|XCB_GC_BACKGROUND; uint32_t pixvalue[2]; pixvalue[0] = this->screen_->black_pixel; pixvalue[1] = this->screen_->white_pixel; xcb_create_gc( this->connection_, pixcontext, this->window_, pixmask, pixvalue); xcb_image_put(this->connection_, this->window_, pixcontext,image, 0,0,0); xcb_image_destroy(image); xcb_free_gc(this->connection_, pixcontext); xcb_map_window(this->connection_, this->window_); }; void XCBWindowRenderer::clear(uint8_t *bitmap , widgets::Size size){ for (int i=0; i<size.width*size.height*4; i++){ *(bitmap+i)=0xff; } ; }; void XCBWindowRenderer::render_command(DrawColorCommand* command,uint8_t* bitmap, widgets::Size size){ auto color =command->color_; for(int i=0; i<size.width*size.height*4; i+=4 ){ auto ptr = bitmap+i; ptr[0] = color.blue; ptr[1] = color.green; ptr[2] = color.red; }; }; namespace detail{ void draw_glyph( uint8_t * bitmap,Size bmsize, FT_Face face, std::size_t bmstart_x, std::size_t bmstart_y ) { if (not face->glyph->format==FT_GLYPH_FORMAT_BITMAP){ }; FT_Render_Glyph(face->glyph, FT_RENDER_MODE_NORMAL); auto glyphbm = &face->glyph->bitmap; std::size_t render_width = std::min<unsigned long>(glyphbm->width, bmsize.width - bmstart_y ); std::size_t render_height = std::min<unsigned long>(glyphbm->rows, bmsize.height - bmstart_x ); for ( int i = 0; i<render_height;i++){ auto gl_rowptr = glyphbm->buffer + i*glyphbm->pitch; auto bm_rowptr = bitmap + (i+bmstart_y) *4*bmsize.width; for (int j = 0; j<render_width; j++){ (bm_rowptr+4*(j+bmstart_x))[0] = *(gl_rowptr+j); (bm_rowptr+4*(j+bmstart_x))[1] =*(gl_rowptr+j); (bm_rowptr+4*(j+bmstart_x))[2] =*(gl_rowptr+j); (bm_rowptr+4*(j+bmstart_x))[3] = 0xff; }; }; }; }; void XCBWindowRenderer::render_command(DrawTextCommand* command,uint8_t* bitmap, widgets::Size bitmap_size){ FT_Face ft_face; FT_Error ft_error; ft_error = FT_New_Face( ft_library, "/usr/share/fonts/truetype/LiberationSansNarrow-Regular.ttf", 0, &ft_face); if( ft_error){ return ; }; const char* text = "asdfg"; hb_buffer_t *buf = hb_buffer_create(); if (! hb_buffer_allocation_successful( buf)) { throw std::runtime_error( "buffer creation failed"); }; hb_buffer_add_utf8(buf, text, -1, 0,-1 ); FT_Set_Char_Size(ft_face,0,32*64,96,96); hb_font_t * hb_font; hb_font = hb_ft_font_create(ft_face, nullptr); hb_buffer_set_direction(buf, HB_DIRECTION_LTR); hb_buffer_set_script(buf, HB_SCRIPT_LATIN); hb_buffer_set_language(buf, hb_language_from_string("en",-1)); if (not hb_shape_full(hb_font,buf,nullptr, 0, nullptr)){ throw std::runtime_error( "shaping failed" ); }; unsigned int glyph_count; hb_glyph_info_t *glyph_info = hb_buffer_get_glyph_infos( buf, &glyph_count); hb_glyph_position_t* glyph_pos = hb_buffer_get_glyph_positions( buf, &glyph_count); std::size_t cursor_x = 0; std::size_t cursor_y = 16; for(unsigned int iglyph = 0; iglyph< glyph_count; iglyph++){ hb_codepoint_t glyphid = glyph_info[iglyph].codepoint; if(FT_Load_Glyph(ft_face, glyph_info[iglyph].codepoint, FT_LOAD_DEFAULT)) { throw std::runtime_error("failed to load glyph"); }; detail::draw_glyph( bitmap, bitmap_size, ft_face, cursor_x+glyph_pos[iglyph].x_offset, cursor_y+glyph_pos[iglyph].y_offset ); cursor_x += glyph_pos[iglyph].x_advance/64; cursor_y += glyph_pos[iglyph].y_advance/64; }; }; XCBRenderer::XCBRenderer(){ int screen_num; this->connection_ = xcb_connect(nullptr, &screen_num ); }; bool XCBRenderer::handle_events(RenderTree* render_tree) { this->commands_.update_commands( render_tree->get_synchronous_interface().extract_draw_commands() ); this->render(); xcb_flush(this->connection_ ); xcb_generic_event_t * event; while( (event = xcb_wait_for_event(this->connection_))){ switch(event->response_type & ~0x80){ case XCB_EXPOSE:{ auto expose_event = reinterpret_cast<xcb_expose_event_t *>( event); this->commands_.update_commands( render_tree->get_synchronous_interface().extract_draw_commands() ); this->render(); xcb_flush(this->connection_ ); break; }; case XCB_BUTTON_PRESS:{ auto button_event = reinterpret_cast<xcb_button_press_event_t *>( event); render_tree->get_synchronous_interface() .dispatch_event(events::ButtonPressEvent{ button_event->sequence, Coordinate{.x=button_event->event_x, .y=button_event->event_y}, button_event->state, button_event->detail }); this->commands_.update_commands( render_tree->get_synchronous_interface().extract_draw_commands() ); this->render(); break; }; case XCB_CONFIGURE_NOTIFY:{ auto configure_notify_event =reinterpret_cast<xcb_configure_notify_event_t *>( event); if (configure_notify_event->x != 200){ const uint32_t config_values [] = {200,100 }; xcb_configure_window( this->connection_, this->window_renderer_->window(), XCB_CONFIG_WINDOW_X |XCB_CONFIG_WINDOW_Y, config_values) ; }; break; }; default:{ break; }; }; free(event); }; return true; }; void XCBRenderer::render(){ if (not this->window_renderer_) { this->window_renderer_ = std::make_unique<XCBWindowRenderer>( XCBWindowRenderer::create(this->connection_,Size{100,200})); }; auto root_command = [&](){ auto const& [key, root_command] = *this->commands_.commands().find( this->commands_.root_uuid() ); assert(root_command->command_type() == CommandType::root_node); return dynamic_cast<RootNodeCommand*>( root_command.get() );}(); assert(root_command->children_.size() == 1); this->window_renderer_->render(this->commands_.commands(), root_command->children_[0]); }; void XCBRenderer::update_commands( std::map<uuid_t,std::unique_ptr<DrawCommandBase>>* commands , uuid_t root){ }; XCBRenderer::~XCBRenderer(){ xcb_disconnect( this->connection_); }; }// xcb }//backend }// fluxpp
28.472727
125
0.672231
[ "render", "vector" ]
37f2cd09293f55c1546a2f556e8c96afff572f38
568
cc
C++
test/sample/traits.cc
czfshine/NSTL-1
5395a2bb4a4ecbfd6929c1f05bfa8f7fe2ab848e
[ "MIT" ]
1
2017-10-20T16:46:47.000Z
2017-10-20T16:46:47.000Z
test/sample/traits.cc
czfshine/NSTL-1
5395a2bb4a4ecbfd6929c1f05bfa8f7fe2ab848e
[ "MIT" ]
null
null
null
test/sample/traits.cc
czfshine/NSTL-1
5395a2bb4a4ecbfd6929c1f05bfa8f7fe2ab848e
[ "MIT" ]
1
2018-04-08T12:41:45.000Z
2018-04-08T12:41:45.000Z
// // Created by czfshine on 2017/10/20. // #include "gtest/gtest.h" #include <vector> #include "nstl_type_traits.h" namespace { /** * 编写一个函数,接受一个vector对象,返回一个指针,指向vector的第三个元素,没有就为NULL * @return */ template <class T > typename NSTLSPACE::iterator_traits<typename T::iterator>::value_type * a(T& xs){ if(xs.size()>=3){ return &(xs[2]); }else{ return nullptr; } } TEST(SAMPLE,TRAITS){ std::vector<int> xs={1,2,3,5,6}; auto b=a(xs); EXPECT_EQ(* b,3); } }
20.285714
87
0.544014
[ "vector" ]
37f8ad751989d7d7dc5900d45c2e0c748e0963cf
2,349
hpp
C++
src/tl.hpp
yurivict/oink
c1259fea042a6bfc76d0506a88384d4e93d651b4
[ "Apache-2.0" ]
null
null
null
src/tl.hpp
yurivict/oink
c1259fea042a6bfc76d0506a88384d4e93d651b4
[ "Apache-2.0" ]
null
null
null
src/tl.hpp
yurivict/oink
c1259fea042a6bfc76d0506a88384d4e93d651b4
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2020 Tom van Dijk * * 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 TL_HPP #define TL_HPP #include "oink.hpp" #include "solver.hpp" namespace pg { class TLSolver : public Solver { public: TLSolver(Oink *oink, Game *game); virtual ~TLSolver(); virtual void run(); protected: int iterations = 0; int dominions = 0; int tangles = 0; int steps = 0; std::vector<int*> tout; // for each tangle std::vector<int> *tin; // for each normal vertex std::vector<int*> tv; // the tangle (vertex-strategy pairs) std::vector<int> tpr; // priority of a tangle std::vector<unsigned int> tescs; // number of escapes of a tangle uintqueue Q; // main queue when attracting vertices int *str; // stores currently assigned strategy of each vertex unsigned int *escs; // stores remaining escapes of each vertex uintqueue pea_state; // v,i,... uintqueue pea_S; // S unsigned int* pea_vidx; // rindex bitset pea_root; // root int pea_curidx; // index std::vector<int> tangle; // stores the new tangle uintqueue tangleto; // stores the vertices the tangle can escape to bitset escapes; // which escapes we considered bitset R; // remaining region (in tl) bitset Z; // current region (in tl) bitset G; // the unsolved game bitset S; // solved vertices (in queue Q) bitset V; // heads 1 bitset W; // heads 2 bitset Even; // accumulate even regions bitset Odd; // accumulate odd regions inline void attractVertices(const int pl, int v, bitset &R, bitset &Z); bool attractTangle(const int t, const int pl, bitset &Z, int maxpr); inline void attractTangles(const int pl, int v, bitset &Z, int maxpr); bool tl(void); bool extractTangles(int i, bitset &R, int *str); }; } #endif
29
75
0.675181
[ "vector" ]
37fd68b4b69caa0eebd2ee54f27da64e1c3c4530
5,586
cpp
C++
src/fd-half/src/example-asym-series-calculate.cpp
semenak94/OpenFFD
60ceedc803acb56f63b7da166233e1d0c64037ac
[ "MIT" ]
null
null
null
src/fd-half/src/example-asym-series-calculate.cpp
semenak94/OpenFFD
60ceedc803acb56f63b7da166233e1d0c64037ac
[ "MIT" ]
23
2017-10-24T22:12:01.000Z
2018-01-24T00:11:34.000Z
src/fd-half/src/example-asym-series-calculate.cpp
semenak94/OpenFFD
60ceedc803acb56f63b7da166233e1d0c64037ac
[ "MIT" ]
null
null
null
#include "Common.h" #include "FdIndex.h" #include "AsymptoticSeries.h" #include "ZetaFunction.h" #include <iostream> TEST_CASE("calculate") { setPreciseOutput(); SECTION("m_3half") { INFO("Вычисление значения функции ФД индекса k = -3/2 при x >= x_min"); BmpReal I_x_44 = asympt_series::calculate(fdsf::index::M3_HALF, 44); std::cout << "k = -1.5 I(44) = " << I_x_44 << std::endl; BmpReal I_x_52 = asympt_series::calculate(fdsf::index::M3_HALF, 52); std::cout << "k = -1.5 I(52) = " << I_x_52 << std::endl; } SECTION("m_half") { INFO("Вычисление значения функции ФД индекса k = -1/2 при x >= x_min"); BmpReal I_x_min = asympt_series::calculate(fdsf::index::M1_HALF, 39); std::cout << "k = -0.5 I(39) = " << I_x_min << std::endl; } SECTION("half") { INFO("Вычисление значения функции ФД индекса k = 1/2 при x >= x_min"); BmpReal I_x_min = asympt_series::calculate(fdsf::index::P1_HALF, 35); std::cout << "k = 0.5 I(35) = " << I_x_min << std::endl; } SECTION("3half") { INFO("Вычисление значения функции ФД индекса k = 3/2 при x >= x_min"); BmpReal I_x_min = asympt_series::calculate(fdsf::index::P3_HALF, 33); std::cout << "k = 1.5 I(33) = " << I_x_min << std::endl; } SECTION("5half") { INFO("Вычисление значения функции ФД индекса k = 5/2 при x >= x_min"); BmpReal I_x_min = asympt_series::calculate(fdsf::index::P5_HALF, 30); std::cout << "k = 2.5 I(30) = " << I_x_min << std::endl; } SECTION("7half") { INFO("Вычисление значения функции ФД индекса k = 7/2 при x >= x_min"); BmpReal I_x_min = asympt_series::calculate(fdsf::index::P7_HALF, 29); std::cout << "k = 3.5 I(29) = " << I_x_min << std::endl; } } TEST_CASE("zeta") { for (size_t n = 2; n <= 24; n += 2) { std::cout << n / 2 << " "<< zetaFunction(n) << std::endl; } } namespace { /* * Проверка точности asymptotic и квадратурами в точках 30, 35, 40, 45, 50, 55, 60 */ void checkAccuracy(BmpReal k, const std::vector<BmpReal>& expected) { std::cout << "k = " << k << std::endl; const std::vector<BmpReal> REPER_DOTS = { 30, 35, 40, 45, 50 }; for (size_t i = 0; i < REPER_DOTS.size(); ++i) { BmpReal I_0 = asympt_series::calculate(k, REPER_DOTS[i]); std::cout << "x = " << REPER_DOTS[i] << ": " << I_0 / expected[i] - 1 << std::endl; } } } /* * k = -1.5 * x = 30: 6.03628e-13 * x = 35: 8.43769e-15 * x = 40: 6.66134e-15 * x = 45: 2.88658e-15 * x = 50: 1.11022e-15 * k = -0.5 * x = 30: 9.76996e-15 * x = 35: 1.22125e-15 * x = 40: 1.11022e-16 * x = 45: 0 * x = 50: 2.22045e-16 * k = 0.5 * x = 30: 2.22045e-16 * x = 35: 4.44089e-16 * x = 40: 0 * x = 45: 3.33067e-16 * x = 50: 0 * k = 1.5 * x = 30: 0 * x = 35: 2.22045e-16 * x = 40: 2.22045e-16 * x = 45: 3.33067e-16 * x = 50: 2.22045e-16 * k = 2.5 * x = 30: 0 * x = 35: 2.22045e-16 * x = 40: 8.88178e-16 * x = 45: 7.77156e-16 * x = 50: 4.44089e-16 * k = 3.5 * x = 30: 1.11022e-16 * x = 35: 1.11022e-16 * x = 40: 2.22045e-16 * x = 45: 2.22045e-16 * x = 50: 6.66134e-16 */ TEST_CASE("accuracy") { SECTION("m3half") { const std::vector<BmpReal> EXPECTED = { -0.3656546825930124, -0.33840502628678043, -0.31647315842739643, -0.2983249512504522, -0.28298285818087593, //-0.2697902993693615, //-0.2582876225442183, }; checkAccuracy(fdsf::index::M3_HALF, EXPECTED); } SECTION("m1half") { const std::vector<BmpReal> EXPECTED = { 10.949421304406611, 11.828173306266192, 12.645850688497948, 13.413677426392377, 14.139805291011026, //14.830377690490632, //15.490161585182172, }; checkAccuracy(fdsf::index::M1_HALF, EXPECTED); } SECTION("half") { const std::vector<BmpReal> EXPECTED = { 109.69481833726648, 138.1809826590245, 168.78492259470102, 201.3687766466349, 235.81861512588432, //272.0382110490754, //309.9448732700438, }; checkAccuracy(fdsf::index::P1_HALF, EXPECTED); } SECTION("3half") { const std::vector<BmpReal> EXPECTED = { 1985.311377746039, 2913.472994172872, 4063.3178052469952, 5450.194657595623, 7088.5129602482975, //8991.89716209947, //11173.302913885145, }; checkAccuracy(fdsf::index::P3_HALF, EXPECTED); } SECTION("5half") { const std::vector<BmpReal> EXPECTED = { 42929.25758509994, 73324.08962290642, 116689.92101913081, 175894.7978015514, 253992.56857700663, //354212.155521165, //479948.5008429282, }; checkAccuracy(fdsf::index::P5_HALF, EXPECTED); } SECTION("7half") { const std::vector<BmpReal> EXPECTED = { 1014417.2017425145, 2014719.380775691, 3656385.9176885653, 6191224.971004079, 9922878.385070581, //15209976.546367215, //22469120.83856069, }; checkAccuracy(fdsf::index::P7_HALF, EXPECTED); } }
31.738636
95
0.524347
[ "vector" ]
37ffb88462b4002bc9b57cb9c4bc555e69f28f58
5,840
cpp
C++
04/main.cpp
zv0n/advent_of_code_2020
f730794ff75e95286e55df8ebbb4a514d67b93e8
[ "Unlicense" ]
null
null
null
04/main.cpp
zv0n/advent_of_code_2020
f730794ff75e95286e55df8ebbb4a514d67b93e8
[ "Unlicense" ]
null
null
null
04/main.cpp
zv0n/advent_of_code_2020
f730794ff75e95286e55df8ebbb4a514d67b93e8
[ "Unlicense" ]
1
2020-12-20T16:35:13.000Z
2020-12-20T16:35:13.000Z
#include <fstream> #include <iostream> #include <sstream> #include <vector> class Passport { public: void setBirthYear( int year ) { birth_year = year; } void setIssueYear( int year ) { issue_year = year; } void setExpirationYear( int year ) { expiration_year = year; } void setHeight( const std::string &input ) { height = input; } void setHairColor( const std::string &input ) { hair_color = input; } void setEyeColor( const std::string &input ) { eye_color = input; } void setPassportID( const std::string &id ) { passport_id = id; } void setCountryID( const std::string &id ) { country_id = id; } int getBirthYear() const { return birth_year; } int getIssueYear() const { return issue_year; } int getExpirationYear() const { return expiration_year; } const std::string &getHeight() const { return height; } const std::string &getHairColor() const { return hair_color; } const std::string &getEyeColor() const { return eye_color; } const std::string &getPassportID() const { return passport_id; } const std::string &getCountryID() const { return country_id; } private: int birth_year = -1; int issue_year = -1; int expiration_year = -1; std::string height = ""; std::string hair_color = ""; std::string eye_color = ""; std::string passport_id = ""; std::string country_id = ""; }; // all validations could've been done here, but oh well std::vector<Passport> getPassports( std::ifstream &file ) { std::vector<Passport> ret{}; std::string str; ret.emplace_back(); while ( std::getline( file, str ) ) { if ( str.empty() || str == "\n" ) { ret.emplace_back(); continue; } std::stringstream ss( str ); while ( ss >> str ) { auto key = str.substr( 0, 3 ); auto value = str.substr( 4 ); if ( key == "byr" ) ret.back().setBirthYear( std::stoi( value ) ); else if ( key == "iyr" ) ret.back().setIssueYear( std::stoi( value ) ); else if ( key == "eyr" ) ret.back().setExpirationYear( std::stoi( value ) ); else if ( key == "hgt" ) ret.back().setHeight( value ); else if ( key == "hcl" ) ret.back().setHairColor( value ); else if ( key == "ecl" ) ret.back().setEyeColor( value ); else if ( key == "pid" ) ret.back().setPassportID( value ); else if ( key == "cid" ) ret.back().setCountryID( value ); } } return ret; } bool hasAllValues( const Passport &passport ) { bool valid = true; valid &= passport.getBirthYear() != -1; valid &= passport.getIssueYear() != -1; valid &= passport.getExpirationYear() != -1; valid &= !passport.getHeight().empty(); valid &= !passport.getHairColor().empty(); valid &= !passport.getEyeColor().empty(); valid &= !passport.getPassportID().empty(); return valid; } int allValues( const std::vector<Passport> &passports ) { int count = 0; for ( auto &passport : passports ) { if ( hasAllValues( passport ) ) count++; } return count; } bool validHeight( const std::string &height ) { int height_value = -1; std::string height_unit = ""; std::stringstream ss( height ); ss >> height_value; ss >> height_unit; if ( height_value == -1 || ( height_unit != "cm" && height_unit != "in" ) ) return false; if ( height_unit == "cm" ) return height_value >= 150 && height_value <= 193; return height_value >= 59 && height_value <= 76; } bool validHex( const std::string &hex ) { if ( hex.length() > 7 || hex.length() < 7 ) return false; bool valid = true; valid &= hex[0] == '#'; for ( int i = 1; i < 7; i++ ) { valid &= std::isdigit( hex[i] ) || ( hex[i] >= 'a' && hex[i] <= 'f' ); } return valid; } bool validEye( const std::string &eye ) { return eye == "amb" || eye == "blu" || eye == "brn" || eye == "gry" || eye == "grn" || eye == "hzl" || eye == "oth"; } bool validPID( const std::string &pid ) { if ( pid.length() < 9 || pid.length() > 9 ) return false; bool valid = true; for ( int i = 0; i < 9; i++ ) { valid &= std::isdigit( pid[i] ); } return valid; } int validValues( const std::vector<Passport> &passports ) { int count = 0; for ( auto &passport : passports ) { if ( !hasAllValues( passport ) ) continue; bool valid = true; valid &= passport.getBirthYear() >= 1920 && passport.getBirthYear() <= 2002; valid &= passport.getIssueYear() >= 2010 && passport.getIssueYear() <= 2020; valid &= passport.getExpirationYear() >= 2020 && passport.getExpirationYear() <= 2030; valid &= validHeight( passport.getHeight() ); valid &= validHex( passport.getHairColor() ); valid &= validEye( passport.getEyeColor() ); valid &= validPID( passport.getPassportID() ); if ( valid ) count++; } return count; } int main() { std::ifstream input_file( "input" ); auto passports = getPassports( input_file ); auto res = allValues( passports ); std::cout << "There are \033[93;1m" << res << "\033[0m passports with all required values" << std::endl; res = validValues( passports ); std::cout << "There are \033[93;1m" << res << "\033[0m actually valid passports" << std::endl; }
29.948718
79
0.537842
[ "vector" ]
53052a4581ea31ae2caa9dfa466d01fb27f2ede5
1,075
cpp
C++
Level-1/13. Stack and Queues/5. Largest_Area_Histogram.cpp
anubhvshrma18/PepCoding
1d5ebd43e768ad923bf007c8dd584e217df1f017
[ "Apache-2.0" ]
22
2021-06-02T04:25:55.000Z
2022-01-30T06:25:07.000Z
Level-1/13. Stack and Queues/5. Largest_Area_Histogram.cpp
amitdubey6261/PepCoding
1d5ebd43e768ad923bf007c8dd584e217df1f017
[ "Apache-2.0" ]
2
2021-10-17T19:26:10.000Z
2022-01-14T18:18:12.000Z
Level-1/13. Stack and Queues/5. Largest_Area_Histogram.cpp
amitdubey6261/PepCoding
1d5ebd43e768ad923bf007c8dd584e217df1f017
[ "Apache-2.0" ]
8
2021-07-21T09:55:15.000Z
2022-01-31T10:32:51.000Z
#include <bits/stdc++.h> using namespace std; vector<int> nextSmalleronleft(int *arr,int n){ vector<int> v(n); stack<int> st; st.push(0); v[0]=-1; for(int i=1;i<n;i++){ while(st.size()>0 && arr[st.top()]>=arr[i]){ st.pop(); } if(st.size()==0){ v[i]=-1; } else{ v[i]=st.top(); } st.push(i); } return v; } vector<int> nextSmalleronright(int *arr,int n){ vector<int> v(n); stack<int> st; st.push(n-1); v[n-1]=n; for(int i=n-2;i>=0;i--){ while(st.size()>0 && arr[st.top()]>=arr[i]){ st.pop(); } if(st.size()==0){ v[i]=n; } else{ v[i]=st.top(); } st.push(i); } return v; } void largestAreaHistogram(int *arr,int n){ vector<int> nsl=nextSmalleronleft(arr,n); vector<int> nsr=nextSmalleronright(arr,n); int mxarea=INT_MIN; for(int i=0;i<n;i++){ int width=nsr[i]-nsl[i]-1; int area=width*arr[i]; mxarea=max(mxarea,area); } cout << mxarea << endl; } int main(){ int n; cin >> n; int arr[n]; for(int i=0;i<n;i++){ cin >> arr[i]; } // infixEval(s); largestAreaHistogram(arr,n); return 0; }
14.144737
47
0.55814
[ "vector" ]
53055d9de7b26dacc06006a8a0b4050ff1eeecc3
2,835
cpp
C++
src/levels/level1.cpp
TomSavas/ScrewGeometry
396a6302220de2fcd7f9a947b5c5a508c28ded69
[ "MIT" ]
null
null
null
src/levels/level1.cpp
TomSavas/ScrewGeometry
396a6302220de2fcd7f9a947b5c5a508c28ded69
[ "MIT" ]
null
null
null
src/levels/level1.cpp
TomSavas/ScrewGeometry
396a6302220de2fcd7f9a947b5c5a508c28ded69
[ "MIT" ]
null
null
null
#include "levels/level1.h" #include <utility> #include "OBJ_Loader.h" #include "components/model.h" #include "components/transform.h" Level1::~Level1() { } void Level1::Load() { /* objl::Loader loader; loader.LoadFile("../assets/models/cube.obj"); Model cubeModel(loader.LoadedMeshes[0]); DrawableGameObject *ground = new DrawableGameObject("ground", *this); ground->GetComponent<Transform>()->position.y = -0.5f; ground->GetComponent<Transform>()->scale = glm::vec3(10, 0.01f, 10); ground->AddComponent<Model>(cubeModel); objects.insert(std::make_pair(ground->Name(), ground)); DrawableGameObject *closeRightCube = new DrawableGameObject("closeRightCube", *this); closeRightCube->GetComponent<Transform>()->position = glm::vec3(2, 0, 0); closeRightCube->GetComponent<Transform>()->scale = glm::vec3(.25f); closeRightCube->AddComponent<Model>(cubeModel); objects.insert(std::make_pair(closeRightCube->Name(), closeRightCube)); DrawableGameObject *closeLeftCube = new DrawableGameObject("closeLeftCube", *this); closeLeftCube->GetComponent<Transform>()->position = glm::vec3(-2, 0, 0); closeLeftCube->GetComponent<Transform>()->scale = glm::vec3(.25f); closeLeftCube->AddComponent<Model>(cubeModel); objects.insert(std::make_pair(closeLeftCube->Name(), closeLeftCube)); DrawableGameObject *farRightCube = new DrawableGameObject("farRightCube", *this); farRightCube->GetComponent<Transform>()->position = glm::vec3(2, 0, -2); farRightCube->GetComponent<Transform>()->scale = glm::vec3(.25f); farRightCube->AddComponent<Model>(cubeModel); objects.insert(std::make_pair(farRightCube->Name(), farRightCube)); DrawableGameObject *farLeftCube = new DrawableGameObject("farLeftCube", *this); farLeftCube->GetComponent<Transform>()->position = glm::vec3(-2, 0, -2); farLeftCube->GetComponent<Transform>()->scale = glm::vec3(.25f); farLeftCube->AddComponent<Model>(cubeModel); objects.insert(std::make_pair(farLeftCube->Name(), farLeftCube)); DrawableGameObject *furtherLeftCube = new DrawableGameObject("furtherLeftCube", *this); furtherLeftCube->GetComponent<Transform>()->position = glm::vec3(-2, 0, -4); furtherLeftCube->GetComponent<Transform>()->scale = glm::vec3(.25f); furtherLeftCube->AddComponent<Model>(cubeModel); objects.insert(std::make_pair(furtherLeftCube->Name(), furtherLeftCube)); DrawableGameObject *furthestLeftCube = new DrawableGameObject("furthestLeftCube", *this); furthestLeftCube->GetComponent<Transform>()->position = glm::vec3(-2, 0, -10); furthestLeftCube->GetComponent<Transform>()->scale = glm::vec3(.25f); furthestLeftCube->AddComponent<Model>(cubeModel); objects.insert(std::make_pair(furthestLeftCube->Name(), furthestLeftCube)); */ }
42.954545
93
0.716049
[ "model", "transform" ]
5307d63ff3c22286d5319742cce0f4da63a21a8c
3,674
cc
C++
engine/convertor/worker.cc
YaoPu2021/galileo
0ebee2052bf78205f93f8cbbe0e2884095dd7af7
[ "Apache-2.0" ]
115
2021-09-09T03:01:58.000Z
2022-03-30T10:46:26.000Z
engine/convertor/worker.cc
Hacky-DH/galileo
e4d5021f0287dc879730dfa287b9a056f152f712
[ "Apache-2.0" ]
1
2021-12-09T07:34:41.000Z
2021-12-20T06:24:27.000Z
engine/convertor/worker.cc
Hacky-DH/galileo
e4d5021f0287dc879730dfa287b9a056f152f712
[ "Apache-2.0" ]
28
2021-09-10T08:47:20.000Z
2022-03-17T07:29:26.000Z
// Copyright 2020 JD.com, Inc. Galileo Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ============================================================================== #include "worker.h" #include <unistd.h> #include <cmath> #include "converter.h" #include "utils/buffer.h" #include "utils/string_util.h" #include "utils/task_thread_pool.h" #include "common/macro.h" #include "convertor/file_manager.h" #include "convertor/transform_help.h" #include "glog/logging.h" namespace galileo { namespace convertor { void Worker::Init(galileo::utils::TaskThreadPool* task_thread_pool, Converter* converter) noexcept { converter_ = converter; task_thread_pool->AddTask([this, converter]() { while (1) { size_t idx = this->AllocNextId(); if (idx >= converter_->file_manager_.GetFileNum()) { success_ = true; break; } if (unlikely(!converter_->file_manager_.read(idx, this))) { LOG(ERROR) << "parse file error:" << idx; break; } } }); } bool Worker::operator()(const char* line, size_t len) { if (G_ToolConfig.coordinate_cpu > 0) { usleep(G_ToolConfig.coordinate_cpu); } const char* field_split = G_ToolConfig.field_separator.c_str(); const char* array_split = G_ToolConfig.array_separator.c_str(); assert(1 == strlen(field_split)); assert(1 == strlen(array_split)); char f_split = field_split[0]; char a_split = array_split[0]; std::vector<std::vector<char*>> fields; TransformHelp::SplitLine((char*)line, len, f_split, a_split, fields); return this->ParseRecord(fields); } bool Worker::WriteRecord(int slice_id, Record& record) { SliceBuffer& slice = converter_->slices_[slice_id]; FileManager* file_manager = &converter_->file_manager_; std::lock_guard<std::mutex> auto_lock(slice.locker); size_t avail = slice.buffer.avail(); size_t fix_size = record.fix_fields.size(); size_t vary_size = record.vary_fields.size(); size_t vary_state_size = record.vary_state.size(); size_t record_size = fix_size + vary_state_size + vary_size; if (avail < record_size + 8) { file_manager->WriteSlice(slice_id, slice.buffer.buffer(), slice.buffer.size()); slice.buffer.clear(); } assert(slice.buffer.avail() >= record_size + 8); if (slice.buffer.avail() < record_size + 8) { LOG(ERROR) << " not enough space for write record"; return false; } if (unlikely(!slice.buffer.write((char*)&record_size, sizeof(uint16_t)))) { LOG(ERROR) << " write record_size value fail!"; return false; } if (unlikely(!slice.buffer.write(record.fix_fields.buffer(), fix_size))) { LOG(ERROR) << " write record fix field content fail!"; return false; } if (unlikely( !slice.buffer.write(record.vary_state.buffer(), vary_state_size))) { LOG(ERROR) << " write record fix field content fail!"; return false; } if (unlikely(!slice.buffer.write(record.vary_fields.buffer(), vary_size))) { LOG(ERROR) << " write record vary field content fail!"; return false; } return true; } } // namespace convertor } // namespace galileo
34.018519
81
0.671475
[ "vector" ]
530c29b6059cfccb779afb0ad4fc1870959c1ee6
16,507
cpp
C++
dbms/src/Functions/tests/gtest_from_unixtime.cpp
solotzg/tiflash
66f45c76692e941bc845c01349ea89de0f2cc210
[ "Apache-2.0" ]
85
2022-03-25T09:03:16.000Z
2022-03-25T09:45:03.000Z
dbms/src/Functions/tests/gtest_from_unixtime.cpp
solotzg/tiflash
66f45c76692e941bc845c01349ea89de0f2cc210
[ "Apache-2.0" ]
7
2022-03-25T08:59:10.000Z
2022-03-25T09:40:13.000Z
dbms/src/Functions/tests/gtest_from_unixtime.cpp
solotzg/tiflash
66f45c76692e941bc845c01349ea89de0f2cc210
[ "Apache-2.0" ]
11
2022-03-25T09:15:36.000Z
2022-03-25T09:45:07.000Z
// Copyright 2022 PingCAP, Ltd. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <Columns/ColumnConst.h> #include <Common/Exception.h> #include <Functions/FunctionsDateTime.h> #include <Interpreters/Context.h> #include <TestUtils/FunctionTestUtils.h> #include <TestUtils/TiFlashTestBasic.h> #include <string> #include <vector> namespace DB { namespace tests { class TestFromUnixTime : public DB::tests::FunctionTest { protected: String func_name = "fromUnixTime"; }; TEST_F(TestFromUnixTime, TestInputPattern) try { /// set timezone to UTC context.getTimezoneInfo().resetByTimezoneName("UTC"); std::vector<String> decimal_20_0_data{"-1", "0", "1602328271", "2147483647", "2147483648"}; InferredDataVector<MyDateTime> decimal_20_0_date_time_result{ MyDateTime(0, 0, 0, 0, 0, 0, 0).toPackedUInt(), MyDateTime(1970, 1, 1, 0, 0, 0, 0).toPackedUInt(), MyDateTime(2020, 10, 10, 11, 11, 11, 0).toPackedUInt(), MyDateTime(2038, 1, 19, 3, 14, 7, 0).toPackedUInt(), MyDateTime(2038, 1, 19, 3, 14, 8, 0).toPackedUInt(), }; /// currently, the second argument of from_unixtime can only be constant String format_data = "%Y-%m-%d %H:%i:%s.%f"; std::vector<String> decimal_20_0_string_result{"0000-00-00 00:00:00.000000", "1970-01-01 00:00:00.000000", "2020-10-10 11:11:11.000000", "2038-01-19 03:14:07.000000", "2038-01-19 03:14:08.000000"}; std::vector<Int32> null_map{1, 0, 0, 0, 1}; std::vector<Int32> null_map_for_nullable_vector_input{1, 0, 1, 0, 1}; ColumnsWithTypeAndName first_const_arguments = { /// constant createConstColumn<Decimal128>(std::make_tuple(20, 0), 5, decimal_20_0_data[1]), /// nullable(not null constant) createConstColumn<Nullable<Decimal128>>(std::make_tuple(20, 0), 5, decimal_20_0_data[1]), /// nullable(null constant) createConstColumn<Nullable<Decimal128>>(std::make_tuple(20, 0), 5, {}, "", 0), /// onlyNull constant createConstColumn<Nullable<Null>>(5, {})}; ColumnsWithTypeAndName second_const_arguments = { createConstColumn<String>(5, format_data), createConstColumn<Nullable<String>>(5, format_data), createConstColumn<Nullable<String>>(5, {}), createConstColumn<Nullable<Null>>(5, {})}; auto null_datetime_result = createConstColumn<Nullable<MyDateTime>>(5, {}); auto not_null_datetime_result = createConstColumn<Nullable<MyDateTime>>(5, decimal_20_0_date_time_result[1]); auto only_null_result = createConstColumn<Nullable<Null>>(5, {}); /// case 1 func(const) for (auto & col : first_const_arguments) { auto result_col = null_datetime_result; if (col.type->onlyNull()) result_col = only_null_result; else if (!col.column->isNullAt(0)) result_col = not_null_datetime_result; ASSERT_COLUMN_EQ(result_col, executeFunction(func_name, col)); } /// case 2 func(const, const) auto null_string_result = createConstColumn<Nullable<String>>(5, {}); auto not_null_string_result = createConstColumn<Nullable<String>>(5, decimal_20_0_string_result[1]); for (auto & col1 : first_const_arguments) { for (auto & col2 : second_const_arguments) { auto result_col = null_string_result; if (col1.type->onlyNull() || col2.type->onlyNull()) result_col = only_null_result; else if (!col1.column->isNullAt(0) && !col2.column->isNullAt(0)) result_col = not_null_string_result; ASSERT_COLUMN_EQ(result_col, executeFunction(func_name, col1, col2)); } } /// case 3, func(vector) ASSERT_COLUMN_EQ(createNullableColumn<MyDateTime>(decimal_20_0_date_time_result, null_map), executeFunction(func_name, createColumn<Decimal128>(std::make_tuple(20, 0), decimal_20_0_data))); /// case 4, func(vector, const) auto not_all_null_string_result_vector = createNullableColumn<String>(decimal_20_0_string_result, null_map); for (auto & format_col : second_const_arguments) { auto result_col = null_string_result; if (format_col.type->onlyNull()) result_col = only_null_result; else if (!format_col.column->isNullAt(0)) result_col = not_all_null_string_result_vector; ASSERT_COLUMN_EQ(result_col, executeFunction(func_name, createColumn<Decimal128>(std::make_tuple(20, 0), decimal_20_0_data), format_col)); } /// case 5, func(nullable(vector)) ASSERT_COLUMN_EQ(createNullableColumn<MyDateTime>(decimal_20_0_date_time_result, null_map_for_nullable_vector_input), executeFunction(func_name, createNullableColumn<Decimal128>(std::make_tuple(20, 0), decimal_20_0_data, null_map_for_nullable_vector_input))); /// case 6, func(nullable(vector), const) not_all_null_string_result_vector = createNullableColumn<String>(decimal_20_0_string_result, null_map_for_nullable_vector_input); for (auto & format_col : second_const_arguments) { auto result_col = null_string_result; if (format_col.type->onlyNull()) result_col = only_null_result; else if (!format_col.column->isNullAt(0)) result_col = not_all_null_string_result_vector; ASSERT_COLUMN_EQ(result_col, executeFunction(func_name, createNullableColumn<Decimal128>(std::make_tuple(20, 0), decimal_20_0_data, null_map_for_nullable_vector_input), format_col)); } } CATCH TEST_F(TestFromUnixTime, TestInputType) try { /// set timezone to UTC context.getTimezoneInfo().resetByTimezoneName("UTC"); std::vector<String> decimal_20_3_data{"-1.000", "0.123", "1602328271.124", "2147483647.123", "2147483648.123"}; InferredDataVector<MyDateTime> decimal_20_3_date_time_result{ MyDateTime(0, 0, 0, 0, 0, 0, 0).toPackedUInt(), MyDateTime(1970, 1, 1, 0, 0, 0, 123000).toPackedUInt(), MyDateTime(2020, 10, 10, 11, 11, 11, 124000).toPackedUInt(), MyDateTime(2038, 1, 19, 3, 14, 7, 123000).toPackedUInt(), MyDateTime(2038, 1, 19, 3, 14, 8, 123000).toPackedUInt(), }; String format_data = "%Y-%m-%d %H:%i:%s.%f"; std::vector<String> decimal_20_3_string_result{"0000-00-00 00:00:00.000000", "1970-01-01 00:00:00.123000", "2020-10-10 11:11:11.124000", "2038-01-19 03:14:07.123000", "2038-01-19 03:14:08.123000"}; std::vector<Int32> null_map{1, 0, 0, 0, 1}; ASSERT_COLUMN_EQ(createNullableColumn<MyDateTime>(std::make_tuple(3), decimal_20_3_date_time_result, null_map), executeFunction(func_name, createColumn<Decimal128>(std::make_tuple(20, 3), decimal_20_3_data))); ASSERT_COLUMN_EQ(createNullableColumn<String>(decimal_20_3_string_result, null_map), executeFunction(func_name, createColumn<Decimal128>(std::make_tuple(20, 3), decimal_20_3_data), createConstColumn<String>(5, format_data))); std::vector<String> decimal_20_6_data{"-1.000000", "0.123456", "1602328271.123456", "2147483647.123456", "2147483648.123456"}; InferredDataVector<MyDateTime> decimal_20_6_date_time_result{ MyDateTime(0, 0, 0, 0, 0, 0, 0).toPackedUInt(), MyDateTime(1970, 1, 1, 0, 0, 0, 123456).toPackedUInt(), MyDateTime(2020, 10, 10, 11, 11, 11, 123456).toPackedUInt(), MyDateTime(2038, 1, 19, 3, 14, 7, 123456).toPackedUInt(), MyDateTime(2038, 1, 19, 3, 14, 8, 123456).toPackedUInt(), }; std::vector<String> decimal_20_6_string_result{"0000-00-00 00:00:00.000000", "1970-01-01 00:00:00.123456", "2020-10-10 11:11:11.123456", "2038-01-19 03:14:07.123456", "2038-01-19 03:14:08.123456"}; ASSERT_COLUMN_EQ(createNullableColumn<MyDateTime>(std::make_tuple(6), decimal_20_6_date_time_result, null_map), executeFunction(func_name, createColumn<Decimal128>(std::make_tuple(20, 6), decimal_20_6_data))); ASSERT_COLUMN_EQ(createNullableColumn<String>(decimal_20_6_string_result, null_map), executeFunction(func_name, createColumn<Decimal128>(std::make_tuple(20, 6), decimal_20_6_data), createConstColumn<String>(5, format_data))); ASSERT_COLUMN_EQ(createNullableColumn<MyDateTime>(std::make_tuple(6), decimal_20_6_date_time_result, null_map), executeFunction(func_name, createColumn<Decimal256>(std::make_tuple(40, 6), decimal_20_6_data))); ASSERT_COLUMN_EQ(createNullableColumn<String>(decimal_20_6_string_result, null_map), executeFunction(func_name, createColumn<Decimal256>(std::make_tuple(40, 6), decimal_20_6_data), createConstColumn<String>(5, format_data))); std::vector<String> decimal_18_0_data{"-1", "0", "1602328271", "2147483647", "2147483648"}; InferredDataVector<MyDateTime> decimal_18_0_date_time_result{ MyDateTime(0, 0, 0, 0, 0, 0, 0).toPackedUInt(), MyDateTime(1970, 1, 1, 0, 0, 0, 0).toPackedUInt(), MyDateTime(2020, 10, 10, 11, 11, 11, 0).toPackedUInt(), MyDateTime(2038, 1, 19, 3, 14, 7, 0).toPackedUInt(), MyDateTime(2038, 1, 19, 3, 14, 8, 0).toPackedUInt(), }; std::vector<String> decimal_18_0_string_result{"0000-00-00 00:00:00.000000", "1970-01-01 00:00:00.000000", "2020-10-10 11:11:11.000000", "2038-01-19 03:14:07.000000", "2038-01-19 03:14:08.000000"}; ASSERT_COLUMN_EQ(createNullableColumn<MyDateTime>(std::make_tuple(0), decimal_18_0_date_time_result, null_map), executeFunction(func_name, createColumn<Decimal64>(std::make_tuple(18, 0), decimal_18_0_data))); ASSERT_COLUMN_EQ(createNullableColumn<String>(decimal_18_0_string_result, null_map), executeFunction(func_name, createColumn<Decimal64>(std::make_tuple(18, 0), decimal_18_0_data), createConstColumn<String>(5, format_data))); std::vector<String> decimal_8_0_data{"-1", "0", "16023282", "21474836"}; InferredDataVector<MyDateTime> decimal_8_0_date_time_result{ MyDateTime(0, 0, 0, 0, 0, 0, 0).toPackedUInt(), MyDateTime(1970, 1, 1, 0, 0, 0, 0).toPackedUInt(), MyDateTime(1970, 7, 5, 10, 54, 42, 0).toPackedUInt(), MyDateTime(1970, 9, 6, 13, 13, 56, 0).toPackedUInt(), }; std::vector<String> decimal_8_0_string_result{"0000-00-00 00:00:00.000000", "1970-01-01 00:00:00.000000", "1970-07-05 10:54:42.000000", "1970-09-06 13:13:56.000000"}; ASSERT_COLUMN_EQ(createNullableColumn<MyDateTime>(std::make_tuple(0), decimal_8_0_date_time_result, null_map), executeFunction(func_name, createColumn<Decimal32>(std::make_tuple(8, 0), decimal_8_0_data))); ASSERT_COLUMN_EQ(createNullableColumn<String>(decimal_8_0_string_result, null_map), executeFunction(func_name, createColumn<Decimal32>(std::make_tuple(8, 0), decimal_8_0_data), createConstColumn<String>(5, format_data))); } CATCH TEST_F(TestFromUnixTime, TestTimezone) try { context.getTimezoneInfo().resetByTimezoneName("Asia/Shanghai"); std::vector<String> decimal_20_0_data{"-1", "0", "640115999", "640116000", "653414400", "653418000", "2147483647", "2147483648"}; InferredDataVector<MyDateTime> decimal_20_0_date_time_result{ MyDateTime(0, 0, 0, 0, 0, 0, 0).toPackedUInt(), MyDateTime(1970, 1, 1, 8, 0, 0, 0).toPackedUInt(), MyDateTime(1990, 4, 15, 1, 59, 59, 0).toPackedUInt(), MyDateTime(1990, 4, 15, 3, 0, 0, 0).toPackedUInt(), MyDateTime(1990, 9, 16, 1, 0, 0, 0).toPackedUInt(), MyDateTime(1990, 9, 16, 1, 0, 0, 0).toPackedUInt(), MyDateTime(2038, 1, 19, 11, 14, 7, 0).toPackedUInt(), MyDateTime(2038, 1, 19, 11, 14, 8, 0).toPackedUInt(), }; /// currently, the second argument of from_unixtime can only be constant String format_data = "%Y-%m-%d %H:%i:%s.%f"; std::vector<String> decimal_20_0_string_result{ "0000-00-00 00:00:00.000000", "1970-01-01 08:00:00.000000", "1990-04-15 01:59:59.000000", "1990-04-15 03:00:00.000000", "1990-09-16 01:00:00.000000", "1990-09-16 01:00:00.000000", "2038-01-19 11:14:07.000000", "2038-01-19 11:14:08.000000"}; std::vector<Int32> null_map{1, 0, 0, 0, 0, 0, 0, 1}; ASSERT_COLUMN_EQ(createNullableColumn<MyDateTime>(std::make_tuple(0), decimal_20_0_date_time_result, null_map), executeFunction(func_name, createColumn<Decimal128>(std::make_tuple(20, 0), decimal_20_0_data))); ASSERT_COLUMN_EQ(createNullableColumn<String>(decimal_20_0_string_result, null_map), executeFunction(func_name, createColumn<Decimal128>(std::make_tuple(20, 0), decimal_20_0_data), createConstColumn<String>(5, format_data))); context.getTimezoneInfo().resetByTimezoneOffset(28800); decimal_20_0_date_time_result[3] = MyDateTime(1990, 4, 15, 2, 0, 0, 0).toPackedUInt(); decimal_20_0_string_result[3] = "1990-04-15 02:00:00.000000"; decimal_20_0_date_time_result[4] = MyDateTime(1990, 9, 16, 0, 0, 0, 0).toPackedUInt(); decimal_20_0_string_result[4] = "1990-09-16 00:00:00.000000"; ASSERT_COLUMN_EQ(createNullableColumn<MyDateTime>(std::make_tuple(0), decimal_20_0_date_time_result, null_map), executeFunction(func_name, createColumn<Decimal128>(std::make_tuple(20, 0), decimal_20_0_data))); ASSERT_COLUMN_EQ(createNullableColumn<String>(decimal_20_0_string_result, null_map), executeFunction(func_name, createColumn<Decimal128>(std::make_tuple(20, 0), decimal_20_0_data), createConstColumn<String>(5, format_data))); context.getTimezoneInfo().resetByTimezoneName("America/Santiago"); decimal_20_0_data = {"-1", "0", "1648951200", "1648954800", "1662263999", "1662264000", "2147483647", "2147483648"}; decimal_20_0_date_time_result = { MyDateTime(0, 0, 0, 0, 0, 0, 0).toPackedUInt(), MyDateTime(1969, 12, 31, 21, 0, 0, 0).toPackedUInt(), MyDateTime(2022, 4, 2, 23, 0, 0, 0).toPackedUInt(), MyDateTime(2022, 4, 2, 23, 0, 0, 0).toPackedUInt(), MyDateTime(2022, 9, 3, 23, 59, 59, 0).toPackedUInt(), MyDateTime(2022, 9, 4, 1, 0, 0, 0).toPackedUInt(), MyDateTime(2038, 1, 19, 0, 14, 7, 0).toPackedUInt(), MyDateTime(2038, 1, 19, 0, 14, 8, 0).toPackedUInt(), }; decimal_20_0_string_result = { "0000-00-00 00:00:00.000000", "1969-12-31 21:00:00.000000", "2022-04-02 23:00:00.000000", "2022-04-02 23:00:00.000000", "2022-09-03 23:59:59.000000", "2022-09-04 01:00:00.000000", "2038-01-19 00:14:07.000000", "2038-01-19 00:14:08.000000"}; ASSERT_COLUMN_EQ(createNullableColumn<MyDateTime>(std::make_tuple(0), decimal_20_0_date_time_result, null_map), executeFunction(func_name, createColumn<Decimal128>(std::make_tuple(20, 0), decimal_20_0_data))); ASSERT_COLUMN_EQ(createNullableColumn<String>(decimal_20_0_string_result, null_map), executeFunction(func_name, createColumn<Decimal128>(std::make_tuple(20, 0), decimal_20_0_data), createConstColumn<String>(5, format_data))); context.getTimezoneInfo().resetByTimezoneOffset(-10800); decimal_20_0_date_time_result[3] = MyDateTime(2022, 4, 3, 0, 0, 0, 0).toPackedUInt(); decimal_20_0_string_result[3] = "2022-04-03 00:00:00.000000"; decimal_20_0_date_time_result[4] = MyDateTime(2022, 9, 4, 0, 59, 59, 0).toPackedUInt(); decimal_20_0_string_result[4] = "2022-09-04 00:59:59.000000"; ASSERT_COLUMN_EQ(createNullableColumn<MyDateTime>(std::make_tuple(0), decimal_20_0_date_time_result, null_map), executeFunction(func_name, createColumn<Decimal128>(std::make_tuple(20, 0), decimal_20_0_data))); ASSERT_COLUMN_EQ(createNullableColumn<String>(decimal_20_0_string_result, null_map), executeFunction(func_name, createColumn<Decimal128>(std::make_tuple(20, 0), decimal_20_0_data), createConstColumn<String>(5, format_data))); } CATCH } // namespace tests } // namespace DB
58.743772
201
0.68789
[ "vector" ]
53105c8739299f1900b7bfd9a64a49371d23ed1f
13,816
cpp
C++
FireRender.Max.Plugin/plugin/light/FireRenderIES_General.cpp
Vsevolod1983/RadeonProRenderMaxPlugin
d5393fd04e45dd2c77c8b17fac4e10b20df55285
[ "Apache-2.0" ]
6
2020-05-24T12:00:43.000Z
2021-07-13T06:22:49.000Z
FireRender.Max.Plugin/plugin/light/FireRenderIES_General.cpp
Vsevolod1983/RadeonProRenderMaxPlugin
d5393fd04e45dd2c77c8b17fac4e10b20df55285
[ "Apache-2.0" ]
4
2020-09-17T17:05:38.000Z
2021-06-23T14:29:14.000Z
FireRender.Max.Plugin/plugin/light/FireRenderIES_General.cpp
Vsevolod1983/RadeonProRenderMaxPlugin
d5393fd04e45dd2c77c8b17fac4e10b20df55285
[ "Apache-2.0" ]
8
2020-05-15T08:29:17.000Z
2021-07-14T08:38:07.000Z
/********************************************************************** Copyright 2020 Advanced Micro Devices, 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. ********************************************************************/ #include <array> #include <functional> #include "FireRenderIESLight.h" #include "FireRenderIES_Profiles.h" #include "IESLight/IESprocessor.h" #include "maxscript/maxscript.h" #include "FireRenderIES_General.h" #include "maxscript/util/listener.h" FIRERENDER_NAMESPACE_BEGIN wchar_t* IESErrorCodeToMessage(IESProcessor::ErrorCode errorCode); namespace { bool ProfileIsValid(const wchar_t* profilePath, IESProcessor::ErrorCode& parseRes) { IESProcessor processor; IESProcessor::IESLightData lightData; parseRes = processor.Parse(lightData, profilePath); if (parseRes == IESProcessor::ErrorCode::SUCCESS) { return true; } return false; } void ShowInvalidProfileWarning(IESProcessor::ErrorCode parseRes) { std::basic_string<TCHAR> failReason; failReason = _T("Failed to import IES light source: "); failReason += IESErrorCodeToMessage(parseRes); GetCOREInterface()->Log()->LogEntry(SYSLOG_ERROR, NO_DIALOG, _M("Warning Title"), failReason.c_str()); std::wstring scriptToExecute = L"print \"" + failReason + L"\"\n" L"actionMan.executeAction 0 \"40472\""; // command to show maxscript window - found in maxscript discussion // (the_listener->lvw->CreateViewWindow command from cpp interface doesn't seem to be working correctly) // http://www.gritengine.com/maxscript_html/interface_actionman.htm BOOL success = ExecuteMAXScriptScript(scriptToExecute.c_str() ); FCHECK(success); // TODO: Incorrect use of FCHECK()? It's intended for RPR calls } } const int IES_General::DialogId = IDD_FIRERENDER_IES_LIGHT_GENERAL; const TCHAR* IES_General::PanelName = _T("General"); bool IES_General::InitializePage(TimeValue time) { // Import button m_importButton.Capture(m_panel, IDC_FIRERENDER_IES_LIGHT_IMPORT); m_importButton.SetType(CustButType::CBT_PUSH); m_importButton.SetButtonDownNotify(true); // Delete current profile button m_deleteCurrentButton.Capture(m_panel, IDC_FIRERENDER_IES_LIGHT_DELETE_PROFILE); m_deleteCurrentButton.SetType(CustButType::CBT_PUSH); m_deleteCurrentButton.SetButtonDownNotify(true); // Profiles combo box m_profilesComboBox.Capture(m_panel, IDC_FIRERENDER_IES_LIGHT_PROFILE); UpdateProfiles(time); // Enabled parameter m_enabledControl.Capture(m_panel, IDC_FIRERENDER_IES_LIGHT_ENABLED); m_enabledControl.SetCheck(m_parent->GetEnabled(time)); // Targeted parameter m_targetedControl.Capture(m_panel, IDC_FIRERENDER_IES_LIGHT_TARGETED); m_targetedControl.SetCheck(m_parent->GetTargeted(time)); // Target distance parameter m_targetDistanceControl.Capture(m_panel, IDC_FIRERENDER_IES_LIGHT_TARGET_DISTANCE, IDC_FIRERENDER_IES_LIGHT_TARGET_DISTANCE_S); m_targetDistanceControl.Bind(EDITTYPE_FLOAT); MaxSpinner& targetDistanceSpinner = m_targetDistanceControl.GetSpinner(); targetDistanceSpinner.SetSettings<FireRenderIESLight::TargetDistanceSettings>(); m_targetDistanceControl.GetSpinner().SetValue(m_parent->GetTargetDistance(time)); // Area width parameter m_areaWidthControl.Capture(m_panel, IDC_FIRERENDER_IES_LIGHT_AREA_WIDTH, IDC_FIRERENDER_IES_LIGHT_AREA_WIDTH_S); m_areaWidthControl.Bind(EDITTYPE_FLOAT); MaxSpinner& areaWidthSpinner = m_areaWidthControl.GetSpinner(); areaWidthSpinner.SetSettings<FireRenderIESLight::AreaWidthSettings>(); areaWidthSpinner.SetValue(m_parent->GetAreaWidth(time)); // Rotation X parameter m_RotateX.Capture(m_panel, IDC_FIRERENDER_IES_LIGHT_ROTATION_X, IDC_FIRERENDER_IES_LIGHT_ROTATION_X_S); m_RotateX.Bind(EDITTYPE_FLOAT); MaxSpinner& spinnerRotateX = m_RotateX.GetSpinner(); spinnerRotateX.SetSettings<FireRenderIESLight::LightRotateSettings>(); spinnerRotateX.SetValue(m_parent->GetRotationX(time)); // Rotation Y parameter m_RotateY.Capture(m_panel, IDC_FIRERENDER_IES_LIGHT_ROTATION_Y, IDC_FIRERENDER_IES_LIGHT_ROTATION_Y_S); m_RotateY.Bind(EDITTYPE_FLOAT); MaxSpinner& spinnerRotateY = m_RotateY.GetSpinner(); spinnerRotateY.SetSettings<FireRenderIESLight::LightRotateSettings>(); spinnerRotateY.SetValue(m_parent->GetRotationY(time)); // Rotation Z parameter m_RotateZ.Capture(m_panel, IDC_FIRERENDER_IES_LIGHT_ROTATION_Z, IDC_FIRERENDER_IES_LIGHT_ROTATION_Z_S); m_RotateZ.Bind(EDITTYPE_FLOAT); MaxSpinner& spinnerRotateZ = m_RotateZ.GetSpinner(); spinnerRotateZ.SetSettings<FireRenderIESLight::LightRotateSettings>(); spinnerRotateZ.SetValue(m_parent->GetRotationZ(time)); return true; } void IES_General::UninitializePage() { m_importButton.Release(); m_profilesComboBox.Release(); m_enabledControl.Release(); m_targetedControl.Release(); m_targetDistanceControl.Release(); m_areaWidthControl.Release(); } bool IES_General::HandleControlCommand(TimeValue t, WORD code, WORD controlId) { if (code == BN_CLICKED) { switch (controlId) { case IDC_FIRERENDER_IES_LIGHT_ENABLED: return UpdateEnabledParam(t); case IDC_FIRERENDER_IES_LIGHT_TARGETED: return UpdateTargetedParam(t); } } if (code == BN_BUTTONUP) { switch (controlId) { case IDC_FIRERENDER_IES_LIGHT_IMPORT: if(m_importButton.CursorIsOver()) ImportProfile(); return false; case IDC_FIRERENDER_IES_LIGHT_DELETE_PROFILE: if (m_deleteCurrentButton.CursorIsOver()) DeleteSelectedProfile(t); return true; } } if (code == CBN_SELCHANGE && controlId == IDC_FIRERENDER_IES_LIGHT_PROFILE) { int index = m_profilesComboBox.GetSelectedIndex(); // Nothing is selected if (index != -1) { std::wstring profileName = m_profilesComboBox.GetItemText(index); std::wstring profilePath = FireRenderIES_Profiles::ProfileNameToPath(profileName.c_str()); IESProcessor::ErrorCode parseRes; if (!ProfileIsValid(profilePath.c_str(), parseRes)) { ShowInvalidProfileWarning(parseRes); if (m_parent->ProfileIsSelected(t)) { const TCHAR* activeProfile = m_parent->GetActiveProfile(t); m_profilesComboBox.SetSelected(activeProfile); } else { m_profilesComboBox.SetSelected(-1); } return false; } } bool profileIsActivated = ActivateSelectedProfile(t); UpdateDeleteProfileButtonState(); return profileIsActivated; } return false; } bool IES_General::OnEditChange(TimeValue t, int editId, HWND editHWND) { switch (editId) { case IDC_FIRERENDER_IES_LIGHT_AREA_WIDTH: return UpdateAreaWidthParam(t); case IDC_FIRERENDER_IES_LIGHT_TARGET_DISTANCE: return UpdateTargetDistanceParam(t); case IDC_FIRERENDER_IES_LIGHT_ROTATION_X: return UpdateRotationXParam(t); case IDC_FIRERENDER_IES_LIGHT_ROTATION_Y: return UpdateRotationYParam(t); case IDC_FIRERENDER_IES_LIGHT_ROTATION_Z: return UpdateRotationZParam(t); } return false; } bool IES_General::OnSpinnerChange(TimeValue t, ISpinnerControl* spinner, WORD controlId, bool isDragging) { switch (controlId) { case IDC_FIRERENDER_IES_LIGHT_AREA_WIDTH_S: return UpdateAreaWidthParam(t); case IDC_FIRERENDER_IES_LIGHT_TARGET_DISTANCE_S: return UpdateTargetDistanceParam(t); case IDC_FIRERENDER_IES_LIGHT_ROTATION_X_S: return UpdateRotationXParam(t); case IDC_FIRERENDER_IES_LIGHT_ROTATION_Y_S: return UpdateRotationYParam(t); case IDC_FIRERENDER_IES_LIGHT_ROTATION_Z_S: return UpdateRotationZParam(t); } return false; } const TCHAR* IES_General::GetAcceptMessage(WORD controlId) const { switch (controlId) { case IDC_FIRERENDER_IES_LIGHT_PROFILE: case IDC_FIRERENDER_IES_LIGHT_DELETE_PROFILE: return _T("IES light: change profile"); case IDC_FIRERENDER_IES_LIGHT_ENABLED: return _T("IES light: change enabled parameter"); case IDC_FIRERENDER_IES_LIGHT_TARGETED: return _T("IES light: change targeted parameter"); case IDC_FIRERENDER_IES_LIGHT_TARGET_DISTANCE: case IDC_FIRERENDER_IES_LIGHT_TARGET_DISTANCE_S: return _T("IES light: move target object"); case IDC_FIRERENDER_IES_LIGHT_AREA_WIDTH: case IDC_FIRERENDER_IES_LIGHT_AREA_WIDTH_S: return _T("IES light: change area width"); case IDC_FIRERENDER_IES_LIGHT_ROTATION_X: case IDC_FIRERENDER_IES_LIGHT_ROTATION_X_S: case IDC_FIRERENDER_IES_LIGHT_ROTATION_Y: case IDC_FIRERENDER_IES_LIGHT_ROTATION_Y_S: case IDC_FIRERENDER_IES_LIGHT_ROTATION_Z: case IDC_FIRERENDER_IES_LIGHT_ROTATION_Z_S: return _T("IES light: change light source rotation"); } FASSERT(false); return IES_Panel::GetAcceptMessage(controlId); } void IES_General::UpdateUI(TimeValue t) { if (!IsInitialized()) { return; } m_enabledControl.SetCheck(m_parent->GetEnabled(t)); bool targeted = m_parent->GetTargeted(t); m_targetedControl.SetCheck(targeted); if (targeted) { m_targetDistanceControl.Enable(); } else { m_targetDistanceControl.Disable(); } m_targetDistanceControl.GetSpinner().SetValue(m_parent->GetTargetDistance(t)); m_areaWidthControl.GetSpinner().SetValue(m_parent->GetAreaWidth(t)); int activeIndex = -1; if (m_parent->ProfileIsSelected(t)) { const TCHAR* activeProfile = m_parent->GetActiveProfile(t); // Compute active profile index in the combo box by it's name bool profileFound = m_profilesComboBox.ForEachItem([&](int index, const std::basic_string<TCHAR>& text) { if (_tcscmp(text.c_str(), activeProfile) == 0) { // Active profile is found, break the loop activeIndex = index; return true; } // Keep searching return false; }); FASSERT(profileFound); } m_profilesComboBox.SetSelected(activeIndex); UpdateDeleteProfileButtonState(); } void IES_General::Enable() { using namespace ies_panel_utils; EnableControls<true>( m_importButton, m_deleteCurrentButton, m_profilesComboBox, m_enabledControl, m_targetedControl, m_targetDistanceControl, m_areaWidthControl); } void IES_General::Disable() { using namespace ies_panel_utils; EnableControls<false>( m_importButton, m_deleteCurrentButton, m_profilesComboBox, m_enabledControl, m_targetedControl, m_targetDistanceControl, m_areaWidthControl); } bool IES_General::UpdateEnabledParam(TimeValue t) { return m_parent->SetEnabled(m_enabledControl.IsChecked(), t); } bool IES_General::UpdateTargetedParam(TimeValue t) { return m_parent->SetTargeted(m_targetedControl.IsChecked(), t); } bool IES_General::UpdateTargetDistanceParam(TimeValue t) { return m_parent->SetTargetDistance(m_targetDistanceControl.GetValue<float>(), t); } bool IES_General::UpdateAreaWidthParam(TimeValue t) { return m_parent->SetAreaWidth(m_areaWidthControl.GetValue<float>(), t); } bool IES_General::UpdateRotationXParam(TimeValue t) { return m_parent->SetRotationX(m_RotateX.GetValue<float>(), t); } bool IES_General::UpdateRotationYParam(TimeValue t) { return m_parent->SetRotationY(m_RotateY.GetValue<float>(), t); } bool IES_General::UpdateRotationZParam(TimeValue t) { return m_parent->SetRotationZ(m_RotateZ.GetValue<float>(), t); } void IES_General::ImportProfile() { std::wstring filename; size_t nameOffset; if (FireRenderIES_Profiles::GetIESFileName(filename, &nameOffset)) { const wchar_t* pathAndName = filename.c_str(); const wchar_t* name = pathAndName + nameOffset; if (FireRenderIES_Profiles::CopyIES_File(filename.c_str(), nameOffset)) { IESProcessor::ErrorCode parseRes; if (!ProfileIsValid(pathAndName, parseRes)) { ShowInvalidProfileWarning(parseRes); } else { m_profilesComboBox.AddItem(name); UpdateDeleteProfileButtonState(); } } } } bool IES_General::ActivateSelectedProfile(TimeValue t) { int index = m_profilesComboBox.GetSelectedIndex(); // Nothing is selected if (index == -1) { m_parent->SetActiveProfile(_T(""), t); return false; } return m_parent->SetActiveProfile(m_profilesComboBox.GetItemText(index).c_str(), t); } bool IES_General::DeleteSelectedProfile(TimeValue t) { int selIdx = m_profilesComboBox.GetSelectedIndex(); // Nothing is selected if (selIdx < 0) { return false; } std::wstring itemText = m_profilesComboBox.GetItemText(selIdx); std::wstring profilesDir = FireRenderIES_Profiles::GetIESProfilesDirectory(); std::wstring path = profilesDir + itemText; if (FileExists(path.c_str()) && !DeleteFile(path.c_str())) { MessageBox( GetCOREInterface()->GetMAXHWnd(), _T("Failed to delete the file"), _T("Error"), MB_ICONERROR); return false; } m_profilesComboBox.DeleteItem(selIdx); m_profilesComboBox.SetSelected(-1); bool profileChanged = ActivateSelectedProfile(t); UpdateDeleteProfileButtonState(); return profileChanged; } void IES_General::UpdateProfiles(TimeValue time) { const TCHAR* activeProfile = m_parent->GetActiveProfile(time); int activeIndex = -1; FireRenderIES_Profiles::ForEachProfile([&](const TCHAR* filename) { int addIndex = m_profilesComboBox.AddItem(filename); if (activeIndex < 0 && _tcscmp(filename, activeProfile) == 0) { activeIndex = addIndex; } }); m_profilesComboBox.SetSelected(activeIndex); UpdateDeleteProfileButtonState(); } void IES_General::UpdateDeleteProfileButtonState() { if (m_profilesComboBox.GetSelectedIndex() < 0) { m_deleteCurrentButton.Disable(); } else { m_deleteCurrentButton.Enable(); } } FIRERENDER_NAMESPACE_END
26.216319
106
0.768746
[ "object" ]
5313094f18213424ca88377521d0f087992be01e
671
hpp
C++
include/RasterPolygonBase.hpp
mh0fm4/RasTL
96b072fe4080dfc13d7fd9064e5e0f9ff1c4f394
[ "MIT" ]
null
null
null
include/RasterPolygonBase.hpp
mh0fm4/RasTL
96b072fe4080dfc13d7fd9064e5e0f9ff1c4f394
[ "MIT" ]
null
null
null
include/RasterPolygonBase.hpp
mh0fm4/RasTL
96b072fe4080dfc13d7fd9064e5e0f9ff1c4f394
[ "MIT" ]
null
null
null
#ifndef RTL_RASTER_POLYGON_BASE_HPP #define RTL_RASTER_POLYGON_BASE_HPP #include <cassert> #include "Geometry.hpp" #include "Canvas.hpp" #include "RasterBase.hpp" namespace rastl { template<typename CanvasType> class RasterPolygonBase: RasterBase<CanvasType> { public: using Coordinate_t = typename CanvasType::Coordinate_t; using Entry_t = typename CanvasType::Entry_t; using Index_t = typename CanvasType::Index_t; using Polygon_t = Polygon<Coordinate_t>; using PolygonList_t = List<Polygon_t>; static void checkPolygon(const Polygon_t& polygon) { assert(1 < polygon.size()); } }; } // namespace rastl #endif // RTL_RASTER_POLYGON_BASE_HPP
20.333333
57
0.766021
[ "geometry" ]
5315a49315a79ccd19d16defb3c071bd8f91a103
2,307
cpp
C++
src/CADAssembler/CADCreoUtils/TestQcr.cpp
lefevre-fraser/openmeta-mms
08f3115e76498df1f8d70641d71f5c52cab4ce5f
[ "MIT" ]
null
null
null
src/CADAssembler/CADCreoUtils/TestQcr.cpp
lefevre-fraser/openmeta-mms
08f3115e76498df1f8d70641d71f5c52cab4ce5f
[ "MIT" ]
null
null
null
src/CADAssembler/CADCreoUtils/TestQcr.cpp
lefevre-fraser/openmeta-mms
08f3115e76498df1f8d70641d71f5c52cab4ce5f
[ "MIT" ]
null
null
null
/*--------------------------------------------------------------------*\ Pro/TOOLKIT includes \*--------------------------------------------------------------------*/ #include <ProToolkit.h> #include <ProObjects.h> #include <ProMdl.h> /*--------------------------------------------------------------------*\ Application includes \*--------------------------------------------------------------------*/ #include "TestError.h" #include "UtilString.h" /*====================================================================*\ FUNCTION : TestQcrName() PURPOSE : Generate a name for an output QCR file. \*====================================================================*/ char *ProTestQcrName( ProMdl *model, /* Input - model */ char filext[], /* Input - file extension */ char filename[]) /* Output - file name */ { ProError status; char model_name[30], model_type[10]; char *ProUtilModelnameGet(ProMdl*,char*,char*); /*--------------------------------------------------------------------*\ Get the current model \*--------------------------------------------------------------------*/ if(model == NULL) { status = ProMdlCurrentGet(model); /* No error check so this code can be used out of mode */ TEST_CALL_REPORT("ProMdlCurrentGet()", "ProTestQcrName()", status, status != PRO_TK_NO_ERROR); } /*--------------------------------------------------------------------*\ If there is still no model (so no current mode), use the name "nomodel". \*--------------------------------------------------------------------*/ if(model == NULL) ProUtilstrcpy(filename,"nomodel"); else { /*--------------------------------------------------------------------*\ Use the name of the current model as the file name. \*--------------------------------------------------------------------*/ ProUtilModelnameGet(model, model_name, model_type); ProUtilstrcpy(filename,(const char *)model_name); } /*--------------------------------------------------------------------*\ Add the file extension. \*--------------------------------------------------------------------*/ ProUtilstrcat(filename,(const char *)filext); return(filename); }
36.619048
73
0.350672
[ "model" ]
53178dc9d1b875aa6da51cf73e7e30f011a4db6c
12,061
hpp
C++
source/LibFgBase/src/FgBounds.hpp
maamountki/FaceGenBaseLibrary
0c647920e913354028ed09fff3293555e84d2b94
[ "MIT" ]
null
null
null
source/LibFgBase/src/FgBounds.hpp
maamountki/FaceGenBaseLibrary
0c647920e913354028ed09fff3293555e84d2b94
[ "MIT" ]
null
null
null
source/LibFgBase/src/FgBounds.hpp
maamountki/FaceGenBaseLibrary
0c647920e913354028ed09fff3293555e84d2b94
[ "MIT" ]
null
null
null
// // Copyright (c) 2015 Singular Inversions Inc. (facegen.com) // Use, modification and distribution is subject to the MIT License, // see accompanying file LICENSE.txt or facegen.com/base_library_license.txt // // Authors: Andrew Beatty // Created: Sept. 28, 2009 // // min/max bounds of n-D data structures, and operations on bounds. // // * bounds matrices (or vectors) always have 2 columns: [min,max] // * min values are always treated as inclusive // * max values are documented as either inclusive or exclusive // #ifndef FGBOUNDS_HPP #define FGBOUNDS_HPP #include "FgStdLibs.hpp" #include "FgMatrixC.hpp" #include "FgMatrixV.hpp" template<typename T> inline void fgSetIfGreater(T & max,T val) {max = (val > max) ? val : max; } template<typename T> inline void fgSetIfLess(T & min,T val) {min = (val < min) ? val : min; } template<typename T> FgMatrixC<T,1,2> fgBounds(const std::vector<T> & data) { FGASSERT(data.size() > 0); FgMatrixC<T,1,2> ret(data[0]); for (size_t ii=1; ii<data.size(); ++ii) { fgSetIfLess (ret[0],data[ii]); fgSetIfGreater (ret[1],data[ii]); } return ret; } // Returns inclusive bounds of vectors: template<typename T,uint dim> FgMatrixC<T,dim,2> fgBounds(const std::vector<FgMatrixC<T,dim,1> > & data) { FGASSERT(data.size() > 0); FgMatrixC<T,dim,2> ret; ret.setSubMat(data[0],0,0); ret.setSubMat(data[0],0,1); for (size_t ii=1; ii<data.size(); ++ii) { for (uint dd=0; dd<dim; ++dd) { fgSetIfLess (ret.cr(0,dd),data[ii][dd]); fgSetIfGreater (ret.cr(1,dd),data[ii][dd]); } } return ret; } // Returns combined bounds of two bounds (inclusive or exclusive): template<typename T,uint dim> FgMatrixC<T,dim,2> fgBounds(const FgMatrixC<T,dim,2> & b1,const FgMatrixC<T,dim,2> & b2) { FgMatrixC<T,dim,2> ret(b1); for (uint dd=0; dd<dim; ++dd) { fgSetIfLess (ret.cr(0,dd),b2.cr(0,dd)); fgSetIfGreater (ret.cr(1,dd),b2.cr(1,dd)); } return ret; } // Returns inclusive bounds of all elements of the given matrix: template<typename T,uint nrows,uint ncols> FgMatrixC<T,1,2> fgBounds(const FgMatrixC<T,nrows,ncols> & mat) { FGASSERT(mat.numElems() > 0); FgMatrixC<T,1,2> ret(mat[0]); for (uint ii=0; ii<mat.numElems(); ++ii) { fgSetIfLess (ret[0],mat[ii]); fgSetIfGreater (ret[1],mat[ii]); } return ret; } // Returns inclusive bounds of all elements of 'mat': template<typename T> inline FgMatrixC<T,1,2> fgBounds(const FgMatrixV<T> & mat) {return fgBounds(mat.dataVec()); } // Returns inclusive bounds of 3 column vectors: template<typename T,uint dim> FgMatrixC<T,dim,2> fgBounds( const FgMatrixC<T,dim,1> & v0, const FgMatrixC<T,dim,1> & v1, const FgMatrixC<T,dim,1> & v2) { FgMatrixC<T,dim,2> ret; for (uint dd=0; dd<dim; ++dd) { ret.cr(0,dd) = ret.cr(1,dd) = v0[dd]; fgSetIfLess(ret.cr(0,dd),v1[dd]); fgSetIfLess(ret.cr(0,dd),v2[dd]); fgSetIfGreater(ret.cr(1,dd),v1[dd]); fgSetIfGreater(ret.cr(1,dd),v2[dd]); } return ret; } template<typename T,uint nrows,uint ncols> FgMatrixC<T,nrows,1> fgMaxColwise(const FgMatrixC<T,nrows,ncols> & mat) { FgMatrixC<T,nrows,1> ret(mat.colVec(0)); for (uint row=0; row<nrows; ++row) for (uint col=1; col<ncols; ++col) fgSetIfGreater(ret[row],mat.cr(col,row)); return ret; } template<typename T,uint nrows,uint ncols> T fgMaxElem(const FgMatrixC<T,nrows,ncols> & mat) { T ret(mat[0]); size_t sz = mat.size(); for (size_t ii=1; ii<sz; ++ii) fgSetIfGreater(ret,mat[ii]); return ret; } template<typename T,uint nrows,uint ncols> T fgMinElem(const FgMatrixC<T,nrows,ncols> & mat) { T ret(mat[0]); size_t sz = mat.size(); for (size_t ii=1; ii<sz; ++ii) fgSetIfLess(ret,mat[ii]); return ret; } template<typename T,uint nrows,uint ncols> uint fgMaxIdx(const FgMatrixC<T,nrows,ncols> & mat) { uint idx(0); for (uint ii=1; ii<mat.numElems(); ++ii) if (mat[ii] > mat[idx]) idx = ii; return idx; } template<typename T,uint nrows,uint ncols> uint fgMinIdx(const FgMatrixC<T,nrows,ncols> & mat) { uint idx(0); for (uint ii=1; ii<mat.numElems(); ++ii) if (mat[ii] < mat[idx]) idx = ii; return idx; } template<typename T,uint nrows,uint ncols> FgVect2UI fgMaxCrd(const FgMatrixC<T,nrows,ncols> & mat) { FgVect2UI crd; T max = std::numeric_limits<T>::min(); for (uint rr=0; rr<nrows; ++rr) { for (uint cc=0; cc<ncols; ++cc) { if (mat.rc(rr,cc) > max) { max = mat.rc(rr,cc); crd = FgVect2UI(rr,cc); } } } return crd; } template<typename T> FgVect2UI fgMaxCrd(const FgMatrixV<T> & mat) { FgVect2UI crd; T max = std::numeric_limits<T>::min(); for (uint rr=0; rr<mat.nrows; ++rr) { for (uint cc=0; cc<mat.ncols; ++cc) { if (mat.rc(rr,cc) > max) { max = mat.rc(rr,cc); crd = FgVect2UI(rr,cc); } } } return crd; } // Element-wise max: template<class T,uint nrows,uint ncols> FgMatrixC<T,nrows,ncols> fgMax( const FgMatrixC<T,nrows,ncols> & m1, const FgMatrixC<T,nrows,ncols> & m2) { FgMatrixC<T,nrows,ncols> ret; for (uint ii=0; ii<nrows*ncols; ++ii) ret[ii] = fgMax(m1[ii],m2[ii]); return ret; } template<typename T> inline T fgMaxElem(const FgMatrixV<T> & mat) {return fgMax(mat.dataVec()); } template<typename T,uint nrows> FgMatrixC<T,nrows,1> fgDims(const std::vector<FgMatrixC<T,nrows,1> > & vec) { FgMatrixC<T,nrows,2> bounds = fgBounds(vec); return (bounds.colVec(1)-bounds.colVec(0)); } template<typename T,uint dim> bool fgBoundsIntersect( const FgMatrixC<T,dim,2> & bnds1, const FgMatrixC<T,dim,2> & bnds2) { FgMatrixC<T,dim,2> tmp; for (uint dd=0; dd<dim; ++dd) { tmp.cr(0,dd) = std::max(bnds1.cr(0,dd),bnds2.cr(0,dd)); tmp.cr(1,dd) = std::min(bnds1.cr(1,dd),bnds2.cr(1,dd)); if (tmp.cr(0,dd) > tmp.cr(1,dd)) return false; } return true; } template<typename T,uint dim> bool fgBoundsIntersect( const FgMatrixC<T,dim,2> & bnds1, const FgMatrixC<T,dim,2> & bnds2, FgMatrixC<T,dim,2> & retval) // Not assigned if bounds do not intersect { FgMatrixC<T,dim,2> tmp; for (uint dd=0; dd<dim; ++dd) { tmp.cr(0,dd) = std::max(bnds1.cr(0,dd),bnds2.cr(0,dd)); tmp.cr(1,dd) = std::min(bnds1.cr(1,dd),bnds2.cr(1,dd)); if (tmp.cr(0,dd) > tmp.cr(1,dd)) return false; } retval = tmp; return true; } // The returned bounds will have negative volume if the bounds do not intersect: template<typename T,uint dim> FgMatrixC<T,dim,2> fgBoundsIntersection( const FgMatrixC<T,dim,2> & b1, const FgMatrixC<T,dim,2> & b2) { FgMatrixC<T,dim,2> ret(b1); for (uint dd=0; dd<dim; ++dd) { fgSetIfGreater(ret.cr(0,dd),b2.cr(0,dd)); fgSetIfLess(ret.cr(1,dd),b2.cr(1,dd)); } return ret; } template<typename T,uint dim> bool fgBoundsIncludes( const FgMatrixC<T,dim,2> & inclusiveBounds, const FgMatrixC<T,dim,1> & point) { for (uint dd=0; dd<dim; ++dd) { if ((inclusiveBounds.cr(1,dd) < point[dd]) || (inclusiveBounds.cr(0,dd) > point[dd])) return false; } return true; } template<typename T,uint dim> bool fgBoundsIncludes(FgMatrixC<uint,dim,1> dims,FgMatrixC<T,dim,1> pnt) { for (uint dd=0; dd<dim; ++dd) { if (pnt[dd] < 0) return false; // We can now safely cast T to uint since it's >= 0 (and one hopes smaller than 2Gig): if (uint(pnt[dd]) >= dims[dd]) return false; } return true; } template<uint dim> FgMatrixC<uint,dim,2> fgRangeToBounds(FgMatrixC<uint,dim,1> range) { FGASSERT(fgMinElem(range) > 0); return fgJoinHoriz(FgMatrixC<uint,dim,1>(0),range-FgMatrixC<uint,dim,1>(1)); } template<typename T,uint dim> FgMatrixC<T,dim,1> fgBoundsCentre(const std::vector<FgMatrixC<T,dim,1> > & verts) { FgMatrixC<T,dim,2> bounds = fgBounds(verts); return (bounds.colVector[0] + bounds.colVec(1)) * 0.5; } // Returns true if (upper > lower) for all dims: template<typename T,uint dim> bool fgBoundsNonempty(FgMatrixC<T,dim,2> bounds) { bool ret = true; for (uint dd=0; dd<dim; ++dd) ret = ret && (bounds.rc(dd,1)>bounds.rc(dd,0)); return ret; } // Returns true if (upper >= lower) for all dims: template<typename T,uint dim> bool fgBoundsValid(FgMatrixC<T,dim,2> bounds) { bool ret = true; for (uint dd=0; dd<dim; ++dd) ret = ret && (bounds.rc(dd,1)>=bounds.rc(dd,0)); return ret; } // Return a cube bounding box around the given verts whose centre is the centre of the // rectangular bounding box and whose dimension is that of the largest axis bounding dimension, // optionally scaled by 'padRatio': template<typename T,uint dim> FgMatrixC<T,dim,2> // First column is lower bound corner of cube, second is upper fgCubeBounds(const vector<FgMatrixC<T,dim,1> > & verts,T padRatio=1) { FgMatrixC<T,dim,2> ret; FgMatrixC<T,dim,2> bounds = fgBounds(verts); FgMatrixC<T,dim,1> lo = bounds.colVec(0), hi = bounds.colVec(1), centre = (lo + hi) * T(0.5); T hsize = fgMaxElem(hi - lo) * 0.5f * padRatio; ret = fgJoinHoriz(centre-FgMatrixC<T,dim,1>(hsize),centre+FgMatrixC<T,dim,1>(hsize)); return ret; } // Convert bounds from inclusive upper to exclusive upper: template<class T,uint nrows> FgMatrixC<T,nrows,2> fgInclToExcl(FgMatrixC<T,nrows,2> boundsInclusiveUpper) { FgMatrixC<T,nrows,2> ret; for (uint rr=0; rr<nrows; ++rr) { ret.rc(rr,0) = boundsInclusiveUpper.rc(rr,0); ret.rc(rr,1) = boundsInclusiveUpper.rc(rr,1) + T(1); } return ret; } // Clipping functions below are all inclusive bounds since exclusive bounds do not explicitly provide the // value to clip to: template<typename T> inline T fgClip(T val,T lo,T hi) {return val < lo ? lo : (val > hi ? hi : val); } template<typename T> inline T fgClipLo(T val,T lo) {return (val < lo) ? lo : val; } template<typename T> inline T fgClipHi(T val,T hi) {return (val > hi) ? hi : val; } template<class T,uint nrows> FgMatrixC<T,nrows,1> fgClipElems(const FgMatrixC<T,nrows,1> & vals,T lo,T hi) { FgMatrixC<T,nrows,1> ret(vals); for (uint ii=0; ii<nrows; ++ii) ret[ii] = fgClip(vals[ii],lo,hi); return ret; } template<class T,uint nrows> FgMatrixC<T,nrows,1> fgClipElems(const FgMatrixC<T,nrows,1> & vals,T lo,FgMatrixC<T,nrows,1> hi) { FgMatrixC<T,nrows,1> ret(vals); for (uint ii=0; ii<nrows; ++ii) ret[ii] = fgClip(vals[ii],lo,hi[ii]); return ret; } template<typename T,uint nrows,uint ncols> FgMatrixC<T,nrows,ncols> fgClipElemsLo(FgMatrixC<T,nrows,ncols> m,T lo) { FgMatrixC<T,nrows,ncols> ret; for (uint ii=0; ii<nrows*ncols; ++ii) ret.m[ii] = (m[ii] < lo) ? lo : m[ii]; return ret; } template<class T,uint dim> FgMatrixC<T,dim,1> fgClipToBounds(const FgMatrixC<T,dim,1> & pos,const FgMatrixC<T,dim,2> & boundsInclusive) { FgMatrixC<T,dim,1> ret; for (uint ii=0; ii<dim; ++ii) ret[ii] = fgClip(pos[ii],boundsInclusive.rc(ii,0),boundsInclusive.rc(ii,1)); return ret; } // Clip to [0,hiInclBound] with change from signed to unsigned: template<uint nrows,uint ncols> FgMatrixC<uint,nrows,ncols> fgClipElemsZeroHi(FgMatrixC<int,nrows,ncols> m,uint hiInclBound) { FgMatrixC<uint,nrows,ncols> ret; for (uint ii=0; ii<nrows*ncols; ++ii) { int v = m[ii]; uint vu = uint(v); ret[ii] = v < 0 ? 0U : (vu > hiInclBound ? hiInclBound : vu); } return ret; } #endif
26.802222
105
0.612387
[ "vector" ]
531e7844618723810e512663ae0473af2be33dae
1,671
hpp
C++
components/scream/src/physics/shoc/shoc_diag_second_moments_lbycond_impl.hpp
ambrad/scream
52da60f65e870b8a3994bdbf4a6022fdcac7cab5
[ "BSD-3-Clause" ]
22
2018-12-12T17:44:55.000Z
2022-03-11T03:47:38.000Z
components/scream/src/physics/shoc/shoc_diag_second_moments_lbycond_impl.hpp
ambrad/scream
52da60f65e870b8a3994bdbf4a6022fdcac7cab5
[ "BSD-3-Clause" ]
1,440
2018-07-10T16:49:55.000Z
2022-03-31T22:41:25.000Z
components/scream/src/physics/shoc/shoc_diag_second_moments_lbycond_impl.hpp
ambrad/scream
52da60f65e870b8a3994bdbf4a6022fdcac7cab5
[ "BSD-3-Clause" ]
24
2018-11-12T15:43:53.000Z
2022-03-30T18:10:52.000Z
#ifndef SHOC_DIAG_SECOND_MOMENTS_LBYCOND_IMPL_HPP #define SHOC_DIAG_SECOND_MOMENTS_LBYCOND_IMPL_HPP #include "shoc_functions.hpp" // for ETI only but harmless for GPU namespace scream { namespace shoc { template<typename S, typename D> KOKKOS_FUNCTION void Functions<S,D> ::shoc_diag_second_moments_lbycond( const Scalar& wthl_sfc, const Scalar& wqw_sfc, const Scalar& uw_sfc, const Scalar& vw_sfc, const Scalar& ustar2, const Scalar& wstar, Scalar& wthl_sec, Scalar& wqw_sec, Scalar& uw_sec, Scalar& vw_sec, Scalar& wtke_sec, Scalar& thl_sec, Scalar& qw_sec, Scalar& qwthl_sec) { // Purpose of this subroutine is to diagnose the lower // boundary condition for the second order moments needed // for the SHOC parameterization. // The thermodymnamic, tracer, and momentum fluxes are set // to the surface fluxes for the host model, while the // thermodynamic variances and covariances are computed // according to that of Andre et al. 1978. const Scalar ufmin = 0.01; auto uf = std::sqrt(ustar2+sp(0.3)*wstar*wstar); uf = ekat::impl::max<Scalar>(ufmin,uf); // Diagnose thermodynamics variances and covariances thl_sec = sp(0.4)*sp(1.8)*((wthl_sfc/uf)*(wthl_sfc/uf)); qw_sec = sp(0.4)*sp(1.8)*((wqw_sfc/uf)*(wqw_sfc/uf)); qwthl_sec = sp(0.2)*sp(1.8)*(wthl_sfc/uf)*(wqw_sfc/uf); // Vertical fluxes of heat and moisture, simply // use the surface fluxes given by host model wthl_sec = wthl_sfc; wqw_sec = wqw_sfc; uw_sec = uw_sfc; vw_sec = vw_sfc; auto max_val = ekat::impl::max<Scalar>(sqrt(ustar2),ufmin); wtke_sec = max_val*max_val*max_val; } } // namespace shoc } // namespace scream #endif
34.102041
94
0.722322
[ "model" ]
531f3f14261ef08317c4bfde9a0c2aa0adf45408
1,445
cpp
C++
nodes/Fun.cpp
Gabriel29/Sparrow-CImporter
31ebb895bd998273c8722cfb7be6094b81d557ef
[ "MIT" ]
null
null
null
nodes/Fun.cpp
Gabriel29/Sparrow-CImporter
31ebb895bd998273c8722cfb7be6094b81d557ef
[ "MIT" ]
null
null
null
nodes/Fun.cpp
Gabriel29/Sparrow-CImporter
31ebb895bd998273c8722cfb7be6094b81d557ef
[ "MIT" ]
null
null
null
#include "Fun.hpp" #include "FunParam.hpp" #include "Type.hpp" #include "utils.hpp" using namespace cimporter; Fun::Fun(CXCursor cursor) : Decl(cursor) { _name = getCursorName(_cursor); } void Fun::parseDecl() { auto cursorType = clang_getCursorType(_cursor); auto retType = clang_getResultType(cursorType); _retType = std::make_shared<Type>(retType); _retType->parseType(); if(clang_Cursor_getNumArguments(_cursor) > 0) { clang_visitChildren(_cursor, [] (CXCursor cursor, CXCursor parent, CXClientData clientData) -> CXChildVisitResult { CXCursorKind cursorKind = clang_getCursorKind(cursor); if (cursorKind == CXCursor_ParmDecl) { Fun* f = reinterpret_cast<Fun*>(clientData); auto funParam = std::make_shared<FunParam>(cursor); funParam->parseDecl(); f->_paramList.push_back(funParam); } return CXChildVisit_Continue; }, this); } } const std::vector<std::shared_ptr<FunParam>>& Fun::getParamList() const { return _paramList; } const std::shared_ptr<Type> Fun::getRetType() const { return _retType; } void Fun::addToList(std::shared_ptr<FunParam> node) { _paramList.push_back(node); } void Fun::SetType(std::shared_ptr<Type> retType) { _retType = retType; }
24.913793
93
0.611073
[ "vector" ]
53208d297e150c2338eae1a2f7549e0f572a1b91
419
hpp
C++
include/ast/rootNode.hpp
EthanSK/C-to-MIPS-Compiler
a736901053ec1a2ad009bf33f588b4ce5293317c
[ "MIT" ]
6
2019-05-21T09:42:10.000Z
2021-03-22T04:34:20.000Z
include/ast/rootNode.hpp
EthanSK/C-to-MIPS-Compiler
a736901053ec1a2ad009bf33f588b4ce5293317c
[ "MIT" ]
null
null
null
include/ast/rootNode.hpp
EthanSK/C-to-MIPS-Compiler
a736901053ec1a2ad009bf33f588b4ce5293317c
[ "MIT" ]
1
2019-06-25T22:35:24.000Z
2019-06-25T22:35:24.000Z
#ifndef rootNode_hpp #define rootNode_hpp #include "statement.hpp" class RootNode : public Statement { public: RootNode(StatementPtr tree); void generatePython(std::ostream &os, PythonContext &context, int scopeDepth = 0) const override; void generateIL(std::vector<Instr> &instrs, ILContext &context, std::string destReg) const override; protected: void printC(std::ostream &os) const override; }; #endif
23.277778
103
0.75895
[ "vector" ]
53249d7c2e5eadb08803edabd17b5134e5de9f34
5,217
cpp
C++
codes/data structures/seg_tree.cpp
chessbot108/solved-problems
0945be829a8ea9f0d5896c89331460d70d076691
[ "MIT" ]
2
2021-03-07T03:34:02.000Z
2021-03-09T01:22:21.000Z
codes/data structures/seg_tree.cpp
chessbot108/solved-problems
0945be829a8ea9f0d5896c89331460d70d076691
[ "MIT" ]
1
2021-03-27T15:01:23.000Z
2021-03-27T15:55:34.000Z
codes/data structures/seg_tree.cpp
chessbot108/solved-problems
0945be829a8ea9f0d5896c89331460d70d076691
[ "MIT" ]
1
2021-03-27T05:02:33.000Z
2021-03-27T05:02:33.000Z
#include <iostream> #include <cstdio> #include <cstring> #include <cstdlib> #include <ctime> #include <cmath> #include <cassert> #include <algorithm> #include <vector> #include <string> #include <map> #include <set> #include <sstream> #include <list> #include <unordered_map> #include <unordered_set> #include <functional> #define max_v 1100 #define int_max 0x3f3f3f3f #define cont continue #define byte_max 0x3f #define pow_2(n) (1 << n) using namespace std; void setIO(const string& file_name){ freopen((file_name+".in").c_str(), "r", stdin); freopen((file_name+".out").c_str(), "w+", stdout); } inline int LG_pow2(int n){ return pow_2((int)ceil(log2(n))); } long long sub[max_v*2], sum[max_v*2], add_s[max_v * 2]; class seg_tree{ int t[max_v * 2]; //min int d[max_v * 2]; //max int add[max_v * 2]; int n, s; int Q_min(int l, int r, int k, int L, int R){ //l and r are the query, k is the index, L and R are k's interval //printf("%d %d %d %d %d %d\n", l+1, r+1, k, L+1, R+1, (int)(l <= L && R <= r)); if(R <= l || r <= L) return int_max; if(l <= L && R <= r) return t[k] + add[k]; int mid = (L + R) / 2, lc = k*2 + 1, rc = k*2 + 2; return add[k] + min(Q_min(l, r, lc, L, mid), Q_min(l, r, rc, mid, R)); } int Q_max(int l, int r, int k, int L, int R){ //l and r are the query, k is the index, L and R are k's interval printf("%d %d %d %d %d %d\n", l+1, r+1, k, L+1, R+1, (int)(l <= L && R <= r)); if(R <= l || r <= L) return -int_max; if(l <= L && R <= r) return d[k] + add[k]; int mid = (L + R) / 2, lc = k*2 + 1, rc = k*2 + 2; return add[k] + max(Q_max(l, r, lc, L, mid), Q_max(l, r, rc, mid, R)); } long long Q_s(int l, int r, int k, int L, int R){ printf("%d %d %d %d %d %d\n", l+1, r+1, k, L+1, R+1, (int)(l <= L && R <= r)); if(R <= l || r <= L) return 0; if(l <= L && R <= r) return add_s[k] + sum[k]; int mid = (L + R) / 2, lc = k*2 + 1, rc = k*2 + 2; return add_s[k] + Q_s(l, r, lc, L, mid) + Q_s(l, r, rc, mid, R); } void A(int l, int r, int k, int L, int R, int val){ if(R <= L || R <= l || r <= L) return; int lc = k*2 + 1, rc = k*2 + 2; int mid = (L + R) / 2; if(l <= L && R <= r){ add[k] += val; add_s[k] += (long long)val * sub[k]; }else{ A(l, r, lc, L, mid, val); A(l, r, rc, mid, R, val); t[k] = min(t[lc] + add[lc], t[rc] + add[rc]); d[k] = max(d[lc] + add[lc], d[rc] + add[rc]); sum[k] = sum[lc] + sum[rc] + add_s[lc] + add_s[rc]; } } public: seg_tree(int* arr, int s){ n = LG_pow2(s); this->s = s; memset(t, byte_max, sizeof(t)); memset(add, 0, sizeof(add)); memset(add_s, 0, sizeof(add_s)); memset(d, 0x8f, sizeof(d)); memset(sum, 0, sizeof(sum)); memset(sub, 0, sizeof(sub)); for(int i = n - 1; i < n + s - 1; i++){ t[i] = arr[i - (n - 1)]; d[i] = arr[i - (n - 1)]; sub[i] = 1; sum[i] = (long long)arr[i - (n - 1)]; } for(int i = n - 2; i >= 0; i--){ t[i] = min(t[i*2 + 1], t[i*2 + 2]); d[i] = max(d[i*2 + 1], d[i*2 + 2]); sum[i] = sum[i*2 + 1] + sum[i*2 + 2]; sub[i] = sub[i*2 + 1] + sub[i*2 + 2]; } } long long query_sum(int l, int r){ return Q_s(l, r, 0, 0, n); } int query_min(int l, int r){ return Q_min(l, r, 0, 0, n); } int query_max(int l, int r){ return Q_max(l, r, 0, 0, n); } void udpate(int k, int i){ //k is the index, i is the new value t[n + k - 1] = i; sum[n + k - 1] = (long long)i; k += n - 1; while(k){ k = (k - 1) / 2; int lc = k*2 + 1, rc = k*2 + 2; t[k] = min(t[lc] + add[lc], t[rc] + add[rc]); d[k] = max(d[lc] + add[lc], d[rc] + add[rc]); sum[k] = sum[lc] + sum[rc] + add_s[lc] + add_s[rc]; } } void range_udpate(int l, int r, int val){ //add val to all the values between [l, r) A(l, r, 0, 0, n, val); } void print_leaves(){ for(int i = n - 1; i< n - 1 + s; i++) printf("%d ", t[i]); puts(""); } void print_all(){ for(int i = 0; i<n*2; i++) printf("%d ", t[i]); puts(""); } }; int a[max_v]; int main(){ int n; scanf("%d", &n); for(int i = 0; i<n; i++){ scanf("%d", &a[i]); } seg_tree S(a, n); int x; while(true){ scanf("%d", &x); if(x == -1) break; else if(x == 1){ int l, r; scanf("%d%d", &l, &r); l--; r--; printf("%d\n", S.query_min(l, r)); }else if(x == 2){ int i, k; scanf("%d%d", &i, &k); i--; S.udpate(i, k); }else if(x == 3){ int l, r, k; scanf("%d%d%d", &l, &r, &k); l--; r--; S.range_udpate(l, r, k); }else if(x == 4){ S.print_leaves(); }else if(x == 5){ S.print_all(); }else if(x == 6){ int a, b; scanf("%d%d", &a, &b); a--, b--; printf("%lld\n", S.query_sum(a, b)); }else if(x == 7){ int a, b; scanf("%d%d", &a, &b); a--, b--; printf("%d\n", S.query_max(a, b)); } } return 0; }
24.608491
113
0.450642
[ "vector" ]
53274a44ef713be3171640b039fd92207f37ba3e
5,875
cpp
C++
Courses/101 - Advanced Algorithms and Complexity/week1_flows_in_networks/airline_crews/airline_crews.cpp
aKhfagy/Data-Structures-and-Algorithms-Specialization
3f5582f10c55e108add47292fa40e0eda6910e2d
[ "CC0-1.0" ]
1
2021-01-25T09:56:15.000Z
2021-01-25T09:56:15.000Z
Courses/101 - Advanced Algorithms and Complexity/week1_flows_in_networks/airline_crews/airline_crews.cpp
aKhfagy/data-structures-algorithms
3f5582f10c55e108add47292fa40e0eda6910e2d
[ "CC0-1.0" ]
null
null
null
Courses/101 - Advanced Algorithms and Complexity/week1_flows_in_networks/airline_crews/airline_crews.cpp
aKhfagy/data-structures-algorithms
3f5582f10c55e108add47292fa40e0eda6910e2d
[ "CC0-1.0" ]
null
null
null
#include <iostream> #include <vector> #include <algorithm> #include <memory> #include <queue> #include <limits> using std::vector; using std::cin; using std::cout; using std::queue; using std::numeric_limits; /* class MaxMatching { public: void Solve() { vector<vector<bool>> adj_matrix = ReadData(); vector<int> matching = FindMatching(adj_matrix); WriteResponse(matching); } private: vector<vector<bool>> ReadData() { int num_left, num_right; cin >> num_left >> num_right; vector<vector<bool>> adj_matrix(num_left, vector<bool>(num_right)); for (int i = 0; i < num_left; ++i) for (int j = 0; j < num_right; ++j) { int bit; cin >> bit; adj_matrix[i][j] = (bit == 1); } return adj_matrix; } void WriteResponse(const vector<int>& matching) { for (int i = 0; i < matching.size(); ++i) { if (i > 0) cout << " "; if (matching[i] == -1) cout << "-1"; else cout << (matching[i] + 1); } cout << "\n"; } vector<int> FindMatching(const vector<vector<bool>>& adj_matrix) { // Replace this code with an algorithm that finds the maximum // matching correctly in all cases. int num_left = adj_matrix.size(); int num_right = adj_matrix[0].size(); vector<int> matching(num_left, -1); vector<bool> busy_right(num_right, false); for (int i = 0; i < num_left; ++i) for (int j = 0; j < num_right; ++j) if (matching[i] == -1 && !busy_right[j] && adj_matrix[i][j]) { matching[i] = j; busy_right[j] = true; } return matching; } }; */ /* This class implements a bit unusual scheme for storing edges of the graph, * in order to retrieve the backward edge for a given edge quickly. */ class FlowGraph { public: struct Edge { int from, to, capacity, flow; }; private: /* List of all - forward and backward - edges */ vector<Edge> edges; /* These adjacency lists store only indices of edges in the edges list */ vector<vector<size_t> > graph; const size_t flights; public: explicit FlowGraph(size_t n, size_t f): graph(n), flights(f) {} void add_edge(int from, int to, int capacity) { /* Note that we first append a forward edge and then a backward edge, * so all forward edges are stored at even indices (starting from 0), * whereas backward edges are stored at odd indices in the list edges */ Edge forward_edge = {from, to, capacity, 0}; Edge backward_edge = {to, from, 0, 0}; graph[from].push_back(edges.size()); edges.push_back(forward_edge); graph[to].push_back(edges.size()); edges.push_back(backward_edge); } size_t get_flights() const { return flights; } size_t size() const { return graph.size(); } const vector<size_t>& get_ids(int from) const { return graph[from]; } const Edge& get_edge(size_t id) const { return edges[id]; } void add_flow(size_t id, int flow) { /* To get a backward edge for a true forward edge (i.e id is even), we should get id + 1 * due to the described above scheme. On the other hand, when we have to get a "backward" * edge for a backward edge (i.e. get a forward edge for backward - id is odd), id - 1 * should be taken. * * It turns out that id ^ 1 works for both cases. Think this through! */ edges[id].flow += flow; edges[id ^ 1].flow -= flow; } }; FlowGraph read_data() { int n, m; cin >> n >> m; FlowGraph graph(n + m + 2, n); for(int i = 0; i < n; ++i) graph.add_edge(0, i + 1, 1); for (int i = 1; i <= n; ++i) for(int j = 0; j < m; ++j) { bool flag; cin >> flag; if(flag) graph.add_edge(i, n + j + 1, 1); } for(int i = n + 1; i <= m + n; ++i) graph.add_edge(i, n + m + 1, 1); return graph; } void display_result(const FlowGraph& graph) { int flights = graph.get_flights(); for(int i = 1; i <= flights; ++i) { int crew = -1; // the default answer for(size_t id : graph.get_ids(i)) { const FlowGraph::Edge &e = graph.get_edge(id); if(e.flow == 1) { crew = e.to - flights; break; } } cout << crew << " \n"[i == flights]; } } vector <int> compute_Gf(const FlowGraph& graph, int s, int t) { // This function performs BFS vector<int> parent(graph.size(), -1); queue<int> frontire; frontire.push(s); while (!frontire.empty()) { int node = frontire.front(); frontire.pop(); for (auto id : graph.get_ids(node)) { const FlowGraph::Edge& e = graph.get_edge(id); if (parent[e.to] == -1 && e.capacity > e.flow && e.to != s) { parent[e.to] = id; frontire.push(e.to); } } } return parent; } void max_flow(FlowGraph& graph, int from, int to) { vector<int> parent; do { int min = numeric_limits<int>::max(); parent = compute_Gf(graph, from, to); if(parent[to] != -1) { for (int u = parent[to]; u != -1; u = parent[graph.get_edge(u).from]) min = std::min(min, graph.get_edge(u).capacity - graph.get_edge(u).flow); for (int u = parent[to]; u != -1; u = parent[graph.get_edge(u).from]) graph.add_flow(u, min); } } while(parent[to] != -1); } void solve() { FlowGraph graph = read_data(); max_flow(graph, 0, graph.size() - 1); display_result(graph); } int main() { std::ios_base::sync_with_stdio(false); solve(); return 0; }
26.345291
97
0.548766
[ "vector" ]
5329c73bddaad278094af917e224a1587f777058
2,652
cpp
C++
src/nighthaunt/MyrmournBanshees.cpp
rweyrauch/AoSSimulator
d2bfbbe0fab904cc543f1a01e62e0b82cf67c27b
[ "MIT" ]
5
2019-02-01T01:41:19.000Z
2021-06-17T02:16:13.000Z
src/nighthaunt/MyrmournBanshees.cpp
rweyrauch/AoSSimulator
d2bfbbe0fab904cc543f1a01e62e0b82cf67c27b
[ "MIT" ]
2
2020-01-14T16:57:42.000Z
2021-04-01T00:53:18.000Z
src/nighthaunt/MyrmournBanshees.cpp
rweyrauch/AoSSimulator
d2bfbbe0fab904cc543f1a01e62e0b82cf67c27b
[ "MIT" ]
1
2019-03-02T20:03:51.000Z
2019-03-02T20:03:51.000Z
/* * Warhammer Age of Sigmar battle simulator. * * Copyright (C) 2020 by Rick Weyrauch - rpweyrauch@gmail.com * * This code is licensed under the MIT license (MIT) (http://opensource.org/licenses/MIT) */ #include <UnitFactory.h> #include "nighthaunt/MyrmournBanshees.h" #include "NighthauntPrivate.h" namespace Nighthaunt { static const int g_basesize = 32; static const int g_wounds = 1; static const int g_minUnitSize = 4; static const int g_maxUnitSize = 8; static const int g_pointsPerBlock = 75; static const int g_pointsMaxUnitSize = 150; bool MyrmournBanshees::s_registered = false; Unit *MyrmournBanshees::Create(const ParameterList &parameters) { auto procession = (Procession) GetEnumParam("Procession", parameters, g_processions[0]); int numModels = GetIntParam("Models", parameters, g_minUnitSize); return new MyrmournBanshees(procession, numModels, ComputePoints(parameters)); } int MyrmournBanshees::ComputePoints(const ParameterList& parameters) { int numModels = GetIntParam("Models", parameters, g_minUnitSize); auto points = numModels / g_minUnitSize * g_pointsPerBlock; if (numModels == g_maxUnitSize) { points = g_pointsMaxUnitSize; } return points; } void MyrmournBanshees::Init() { if (!s_registered) { static FactoryMethod factoryMethod = { MyrmournBanshees::Create, Nighthaunt::ValueToString, Nighthaunt::EnumStringToInt, MyrmournBanshees::ComputePoints, { EnumParameter("Procession", g_processions[0], g_processions), IntegerParameter("Models", g_minUnitSize, g_minUnitSize, g_maxUnitSize, g_minUnitSize), }, DEATH, {NIGHTHAUNT} }; s_registered = UnitFactory::Register("Myrmourn Banshees", factoryMethod); } } MyrmournBanshees::MyrmournBanshees(Procession procession, int numModels, int points) : Nighthaunt(procession, "Myrmourn Banshees", 8, g_wounds, 10, 4, true, points), m_dagger(Weapon::Type::Melee, "Chill Dagger", 1, 1, 4, 3, -2, RAND_D3) { m_keywords = {DEATH, MALIGNANT, NIGHTHAUNT, SUMMONABLE, MYRMOURN_BANSHEES}; m_weapons = {&m_dagger}; for (auto i = 0; i < numModels; i++) { auto model = new Model(g_basesize, wounds()); model->addMeleeWeapon(&m_dagger); addModel(model); } } } // namespace Nighthaunt
37.885714
115
0.62368
[ "model" ]
532ecabb372d7d02e6fe45c43854aba4d1d681be
4,682
cpp
C++
src/dmdump_module/dmdump_module.cpp
brinkqiang/dmdump
791c7d511c9797182ea73d56d9e81346a24cb2f3
[ "MIT" ]
1
2018-10-25T08:33:37.000Z
2018-10-25T08:33:37.000Z
src/dmdump_module/dmdump_module.cpp
brinkqiang/dmdump
791c7d511c9797182ea73d56d9e81346a24cb2f3
[ "MIT" ]
null
null
null
src/dmdump_module/dmdump_module.cpp
brinkqiang/dmdump
791c7d511c9797182ea73d56d9e81346a24cb2f3
[ "MIT" ]
null
null
null
// Copyright (c) 2018 brinkqiang (brink.qiang@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 "dmdump.h" #include <memory> #include <array> #include <iostream> #include <stdio.h> #include "dmstrtk.hpp" #include "dmutil.h" #ifdef WIN32 #define popen _popen #define pclose _pclose #include <windows.h> #include <tlhelp32.h> #include <stdio.h> #endif #define BUFFER_SIZE 256 std::string DMExecute(const char* cmd) { std::string result; std::shared_ptr<FILE> pipe(popen(cmd, "r"), pclose); if (!pipe) return result; while (!feof(pipe.get())) { char szBuf[BUFFER_SIZE+1] = {0}; if (fgets(szBuf, BUFFER_SIZE, pipe.get()) != nullptr) { result += szBuf; } } return result; } #ifdef WIN32 std::vector<uint64_t> DMGetProcessList(const std::string& strName) { std::vector<uint64_t> vecList; HANDLE procSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); if (procSnap == INVALID_HANDLE_VALUE) { return vecList; } PROCESSENTRY32 procEntry = { 0 }; procEntry.dwSize = sizeof(PROCESSENTRY32); BOOL bRet = Process32First(procSnap, &procEntry); while (bRet) { std::string strExeFile = procEntry.szExeFile; if (strExeFile == strName) { vecList.push_back(procEntry.th32ProcessID); } //printf("PID: %d (%s) \n", procEntry.th32ProcessID, procEntry.szExeFile); bRet = Process32Next(procSnap, &procEntry); } CloseHandle(procSnap); return vecList; } bool DMGenDumpFile(const std::string& strName, bool bWin32) { std::vector<uint64_t> vecList = DMGetProcessList(strName); std::string strTime = DMFormatDateTime(time(0), "%Y-%m-%d-%H-%M-%S"); for (int i=0; i < vecList.size(); ++i) { char cmd[256] = { 0 }; if (bWin32) { sprintf(cmd, "procdump.exe -ma %d %s_%d_%s.dmp", (int)vecList[i], strName.c_str(), (int)vecList[i], strTime.c_str()); } else { sprintf(cmd, "procdump.exe -64 -ma %d %s_%d_%s.dmp", (int)vecList[i], strName.c_str(), (int)vecList[i], strTime.c_str()); } std::cout << cmd << std::endl; std::string strData = DMExecute(cmd); std::cout << strData << std::endl;; } return true; } #else std::vector<uint64_t> DMGetProcessList(const std::string& strName) { std::vector<uint64_t> vecList; char cmd[256] = { 0 }; sprintf(cmd, "pidof %s", strName.c_str()); std::string data = DMExecute(cmd); strtk::std_string::token_list_type token_list; std::vector<std::string> vecData; const std::string delimiters("\t\r\n "); strtk::parse(data, delimiters, vecData); for (int i=0; i < static_cast<int>(vecData.size()); ++i) { if (vecData[i].empty()) { continue; } vecList.push_back(atoll(vecData[i].c_str())); } return vecList; } bool DMGenDumpFile(const std::string& strName, bool bWin32) { std::vector<uint64_t> vecList = DMGetProcessList(strName); for (int i = 0; i < vecList.size(); ++i) { char cmd[256] = { 0 }; sprintf(cmd, "pstree -p %d", (int)vecList[i]); std::string data = DMExecute(cmd); std::cout << data; char cmd2[256] = { 0 }; sprintf(cmd2, "gcore -o %s.core %d", strName.c_str(), (int)vecList[i]); std::string data2 = DMExecute(cmd2); std::cout << data2; char cmd3[256] = { 0 }; sprintf(cmd3, "%s.core.%d", strName.c_str(), (int)vecList[i]); std::cout << cmd3 << std::endl; } return true; } #endif
28.204819
133
0.629859
[ "vector" ]
5330af95806d461bba83ecaf41f94798e967c8b9
697
cpp
C++
codechef-div-3-rated-contest-2021-division-2-unrated/CHEFPAT.cpp
JorgeKtch/codechef-solutions
e9e7a223386dd899801686623226f2d963dce0cd
[ "MIT" ]
2
2021-01-27T20:27:51.000Z
2021-02-07T10:04:36.000Z
codechef-div-3-rated-contest-2021-division-2-unrated/CHEFPAT.cpp
JorgeKtch/codechef-solutions
e9e7a223386dd899801686623226f2d963dce0cd
[ "MIT" ]
null
null
null
codechef-div-3-rated-contest-2021-division-2-unrated/CHEFPAT.cpp
JorgeKtch/codechef-solutions
e9e7a223386dd899801686623226f2d963dce0cd
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; int main() { int t; cin >> t; for(int c=0; c<t; c++){ int n; cin >> n; int ai, max_ai=1001; map<int, vector<int>> m; for(int i=0; i<n; i++){ cin >> ai; if(ai>max_ai) max_ai = ai; m[ai].push_back(i+1); } map<int, int> pos_time; int pos = 1; for(int illness=max_ai; illness>=1; illness--){ for(int i=0; i<m[illness].size(); i++){ pos_time[m[illness][i]] = pos; pos++; } } for(int i=1; i<=n; i++){ cout << pos_time[i] << " "; } cout << "\n"; } return 0; }
24.034483
55
0.408895
[ "vector" ]
5341205cb2c58033899e389c59afdeb3c780427c
332
cpp
C++
CodeInterviews-SwordOffer/Offer57-Two-Sum/solution1.cpp
loyio/leetcode
366393c29a434a621592ef6674a45795a3086184
[ "CC0-1.0" ]
null
null
null
CodeInterviews-SwordOffer/Offer57-Two-Sum/solution1.cpp
loyio/leetcode
366393c29a434a621592ef6674a45795a3086184
[ "CC0-1.0" ]
null
null
null
CodeInterviews-SwordOffer/Offer57-Two-Sum/solution1.cpp
loyio/leetcode
366393c29a434a621592ef6674a45795a3086184
[ "CC0-1.0" ]
2
2022-01-25T05:31:31.000Z
2022-02-26T07:22:23.000Z
class Solution { public: vector<int> twoSum(vector<int>& nums, int target) { int i = 0, j = nums.size()-1; while(i < j){ int s = nums[i] + nums[j]; if(s < target) i++; else if(s > target) j--; else return {nums[i], nums[j]}; } return {}; } };
23.714286
55
0.427711
[ "vector" ]
53434e9d3227fc4f7e944dd7c9f19fab97f2a5a0
722
cpp
C++
src/Tests/TypeSystem/LabelTypeTest.cpp
pawel-jarosz/nastya-lisp
813a58523b741e00c8c27980fe658b546e9ff38c
[ "MIT" ]
1
2021-03-12T13:39:17.000Z
2021-03-12T13:39:17.000Z
src/Tests/TypeSystem/LabelTypeTest.cpp
pawel-jarosz/nastya-lisp
813a58523b741e00c8c27980fe658b546e9ff38c
[ "MIT" ]
null
null
null
src/Tests/TypeSystem/LabelTypeTest.cpp
pawel-jarosz/nastya-lisp
813a58523b741e00c8c27980fe658b546e9ff38c
[ "MIT" ]
null
null
null
// // Created by caedus on 20.02.2021. // #include <memory> #include <vector> #include <gtest/gtest.h> #include "TypeSystem/Types/LabelObject.hpp" namespace nastya::typesystem { TEST(LabelTypeTest, testConstructor) { std::string test_case = "dummy_label"; LabelObject object(test_case); EXPECT_EQ(object.getValue(), test_case); EXPECT_EQ(object.getType(), ObjectType::Label); EXPECT_EQ(object.info(), "Label => " + test_case); std::unique_ptr<LabelObject> cloned(dynamic_cast<LabelObject*>(object.clone())); EXPECT_EQ(object.getType(), cloned->getType()); EXPECT_EQ(object.getValue(), cloned->getValue()); EXPECT_FALSE(object.isComparable()); } } // namespace nastya::typesystem
25.785714
84
0.706371
[ "object", "vector" ]
5344927d3c7bb98c5bc71321e8c15ac8cb1b0544
17,422
cpp
C++
src/discover/moviedetail.cpp
keshavbhatt/moviesquare
4b2d4e8042702a271eda7707dd2c0a1fa3edd696
[ "MIT" ]
4
2020-10-03T07:20:07.000Z
2021-02-27T22:54:17.000Z
src/discover/moviedetail.cpp
keshavbhatt/moviesquare
4b2d4e8042702a271eda7707dd2c0a1fa3edd696
[ "MIT" ]
null
null
null
src/discover/moviedetail.cpp
keshavbhatt/moviesquare
4b2d4e8042702a271eda7707dd2c0a1fa3edd696
[ "MIT" ]
1
2020-10-03T10:59:57.000Z
2020-10-03T10:59:57.000Z
#include "moviedetail.h" #include "ui_moviedetail.h" #include <QJsonDocument> #include <QJsonArray> #include <QJsonObject> #include <QDesktopServices> MovieDetail::MovieDetail(QWidget *parent, double movieId, QString key, QString lang, QStandardItemModel *langModel) : QWidget(parent), ui(new Ui::MovieDetail) { ui->setupUi(this); this->movieId = movieId; this->key = key; this->lang = lang; this->langModel = langModel; // to convert iso_639_1 language code to language names. _loader = new WaitingSpinnerWidget(this,true,true); _loader->setRoundness(70.0); _loader->setMinimumTrailOpacity(15.0); _loader->setTrailFadePercentage(70.0); _loader->setNumberOfLines(10); _loader->setLineLength(8); _loader->setLineWidth(2); _loader->setInnerRadius(2); _loader->setRevolutionsPerSecond(3); _loader->setColor(QColor("#1e90ff")); circularProgressBar = new CircularProgessBar(); circularProgressBar->setSizePolicy(QSizePolicy::MinimumExpanding,QSizePolicy::Maximum); circularProgressBar->setArcPenBrush(QBrush("#336B95")); circularProgressBar->setCircleBrush(QBrush("#31363B"),QBrush("#31363B")); QFont f; f.setFamily(f.defaultFamily()); f.setPixelSize(11); f.setBold(true); circularProgressBar->setTextProperty(QColor("#C0C0C0"),f); circularProgressBar->setMinimumSize(QSize(90,90)); ui->ratiingLayout->insertWidget(0,circularProgressBar); circularProgressBar->setText("-"); circularProgressBar->setProgressValue(0.0); ui->upperWidget->installEventFilter(this); loadMovie(); creditRetry = 3; } QString MovieDetail::getLangByCode(QString iso_639_1) { QString langName; for (int i = 0; i < langModel->rowCount(); ++i) { QStandardItem* lpItemLang = langModel->item(i); QString szLang = lpItemLang->data().toString(); if(szLang==iso_639_1){ langName = lpItemLang->text(); break; } } return langName; } void MovieDetail::closeEvent(QCloseEvent *event) { QString path = utils::returnPath("discover/backdrop/"); QDir d(path); d.removeRecursively(); QWidget::closeEvent(event); } void MovieDetail::loadMovie() { QString url = QString("https://api.themoviedb.org/3/movie/%1?api_key=%2").arg(movieId).arg(key)+"&language="+lang; Request *_request = new Request(this); connect(_request,&Request::requestStarted,[=]() { _loader->start(); }); // qDebug()<<"MOVIE DETAILS: "<<url; connect(_request,&Request::requestFinished,[=](QString reply) { loadCredits(); // we are loading creadits after loading moview details ui->results->clear(); //load to view loadMovieToView(reply); _loader->stop(); setCursor(Qt::ArrowCursor); }); connect(_request,&Request::downloadError,[=](QString errorString) { _loader->stop(); showError(errorString); }); setCursor(Qt::WaitCursor); _request->get(url); } void MovieDetail::loadCredits() { qDebug()<<"LOADING CREDITS"; QString url = QString("https://api.themoviedb.org/3/movie/%1/credits?api_key=%2").arg(movieId).arg(key); Request *_request = new Request(this); connect(_request,&Request::requestStarted,[=]() { _loader->start(); }); connect(_request,&Request::requestFinished,[=](QString reply) { ui->results->clear(); //load to view loadCastToView(reply); _loader->stop(); setCursor(Qt::ArrowCursor); }); connect(_request,&Request::downloadError,[=](QString errorString) { _loader->stop(); if(creditRetry>0){ _request->clearCache(url); loadCredits(); creditRetry--; qDebug()<<"RELODING CREDIT FOR MOVIE"<<movieId<<", ON NETWORK FAIL"<<creditRetry; _request->deleteLater(); return; } showError(errorString); }); setCursor(Qt::BusyCursor); currentCreditUrl = url; _request->get(url); } void MovieDetail::loadMovieToView(QString reply) { //qDebug()<<"REPLY : "<<reply; QJsonDocument jsonResponse = QJsonDocument::fromJson(reply.toUtf8()); QJsonObject jsonObj = jsonResponse.object(); QJsonArray jsonGenreArray = jsonObj["genres"].toArray(); QJsonArray jsonPCArray = jsonObj["production_companies"].toArray(); QJsonArray jsonProduction_companiesArray = jsonObj["production_companies"].toArray(); QJsonArray jsonPConArray = jsonObj["production_countries"].toArray(); QString pcStr; foreach(QJsonValue pcObj,jsonPCArray){ pcStr.append(", "+pcObj.toObject().value("name").toString()); } QString pconStr; foreach(QJsonValue pconObj,jsonPConArray){ pconStr.append(", "+pconObj.toObject().value("name").toString()); } QString genreStr; foreach(QJsonValue genreObj,jsonGenreArray){ genreStr.append(", "+genreObj.toObject().value("name").toString()); } QString proCompStr; foreach(QJsonValue proComObj,jsonProduction_companiesArray){ proCompStr.append(proComObj.toObject().value("name").toString()); } QString backdrop_path = "https://image.tmdb.org/t/p/w500"+jsonObj.value("backdrop_path").toString(); QString title = jsonObj.value("title").toString(); QString status = jsonObj.value("status").toString(); QString tagline = jsonObj.value("tagline").toString(); QString release_date = jsonObj.value("release_date").toString(); QString poster_path = "https://image.tmdb.org/t/p/w300" + jsonObj.value("poster_path").toString(); double vote = jsonObj.value("vote_average").toDouble(); QString overview = jsonObj.value("overview").toString(); double runtime = jsonObj.value("runtime").toDouble(); QString imdb_id = jsonObj.value("imdb_id").toString(); QTime time = QTime::fromMSecsSinceStartOfDay(runtime*60*1000); QString original_language = jsonObj.value("original_language").toString(); QString langName = getLangByCode(original_language); QString meta = QString(langName.isEmpty()?"":langName+" | ")+ QString(release_date.isEmpty()?"":release_date+" | ")+ QString(genreStr.remove(0,1).isEmpty()?"":genreStr+" | ")+ QString(time.toString("hh:mm:ss").isEmpty()?"":time.toString("hh:mm:ss")); QDate date =QDate::fromString(release_date,Qt::ISODate); ui->title->setText(title.toUpper()+" ("+QString::number(date.year())+")"); if(tagline.isEmpty() || tagline.isNull()){ ui->tagline->hide(); } ui->tagline->setText(tagline); ui->meta->setText(meta); ui->summary->setText("<b>Summary:</b> "+overview); ui->status->setText("<b>Status:</b> "+status+QString(pcStr.isEmpty()?"":"<br><br><b>" "Production:</b> "+pcStr.remove(0,1)) +QString(pconStr.isEmpty()?"":"<br><br><b>" "Country:</b> "+pconStr.remove(0,1))); double ratio = 120.0/187.0; double height = 350.0; double width = ratio * height; ui->poster->setFixedSize(width,height); QString net_cache_path = QStandardPaths::writableLocation(QStandardPaths::CacheLocation); QNetworkDiskCache *diskCache = new QNetworkDiskCache(0); diskCache->setCacheDirectory(net_cache_path); ui->poster->setRemotePixmap(poster_path,diskCache); if(imdb_id.isEmpty()==false){ connect(ui->imdb,&controlButton::clicked,[=](){ QDesktopServices::openUrl(QUrl("https://www.imdb.com/title/"+imdb_id)); }); }else{ ui->imdb->hide(); } RemotePixmapLabel *bp = new RemotePixmapLabel(this); bp->hide(); connect(bp,&RemotePixmapLabel::pixmapLoaded,[=](QByteArray data) { QPixmap pixmap; pixmap.loadFromData(data); if(pixmap.isNull()==false){ backdropPix = pixmap; ui->upperWidget->repaint(); ui->upperWidget->update(); } }); QNetworkDiskCache *diskCache2 = new QNetworkDiskCache(0); diskCache->setCacheDirectory(net_cache_path); bp->setRemotePixmap(backdrop_path,diskCache2); double vote_average = vote * 100.0; qreal tmpValue = vote_average/10.0; QString text = QString::number(tmpValue/10.0,'f',1); circularProgressBar->setProgressValue(tmpValue); circularProgressBar->setText(text); ui->scrollAreaWidgetContents->setMinimumWidth(ui->scrollAreaWidgetContents->minimumSizeHint().width()); } bool MovieDetail::eventFilter(QObject *obj, QEvent *event) { if(obj== ui->upperWidget && event->type() ==QEvent::Paint && !backdropPix.isNull()){ QPainter paint(ui->upperWidget); int widWidth = this->ui->upperWidget->width(); int widHeight = this->ui->upperWidget->height(); QPixmap _backdropPix = backdropPix.scaled(widWidth, widHeight, Qt::KeepAspectRatioByExpanding,Qt::SmoothTransformation); QPoint centerOfWidget = ui->upperWidget->rect().center(); QRect rectOfPixmap = _backdropPix.rect(); rectOfPixmap.moveCenter(centerOfWidget); QRect boundingRect = rectOfPixmap; paint.drawPixmap(rectOfPixmap.topLeft(), _backdropPix); QColor darker = currentTheme.darker(200); int r,g,b; r = darker.red(); g = darker.green(); b = darker.blue(); paint.fillRect(QRectF(boundingRect.x()-5,boundingRect.y()-5,boundingRect.width()+10,boundingRect.height()+10), QBrush(QColor(r,g,b,180))); } return QWidget::eventFilter(obj,event); } void MovieDetail::loadCastToView(QString reply) { QJsonDocument jsonResponse = QJsonDocument::fromJson(reply.toUtf8()); QJsonObject jsonCast = jsonResponse.object(); QJsonArray jsonArrayCast = jsonCast["cast"].toArray(); QJsonArray jsonArrayCrew = jsonCast["crew"].toArray(); QJsonObject tmpObj; // check for error and retry if(jsonCast.isEmpty()){ Request *_request = new Request(this); if(creditRetry>0){ _request->clearCache(currentCreditUrl); loadCredits(); creditRetry--; qDebug()<<"RELODING CREDIT FOR MOVIE"<<movieId<<creditRetry; _request->deleteLater(); return; } } QString directors,producers,authors,screenplay; int limit = jsonArrayCast.count(); if(limit > 20){ limit = 20; } for(int x = 0;x < limit ; x++) { tmpObj = jsonArrayCast.at(x).toObject(); QString posterUrl = tmpObj.value("profile_path").toString(); if(posterUrl.isEmpty()|| posterUrl.isNull()){ posterUrl = "qrc:///icons/others/default-cover.png"; } Item *track_widget = new Item(ui->results,true); track_widget->adjustForPeoples(); track_widget->setContentsMargins(0,0,0,0); track_widget->setStyleSheet("QWidget#"+track_widget->objectName()+"{background-color: transparent;}"); QString name = tmpObj.value("name").toString(); QString character = tmpObj.value("character").toString(); double id = tmpObj.value("id").toDouble(); track_widget->setMovieId(id); // set data track_widget->setTitle(name,character); track_widget->setReleaseDate(character); track_widget->setPoster("https://image.tmdb.org/t/p/w200"+posterUrl); connect(track_widget,&Item::showMoviesBy,[=](double artistId){ emit showMoviesBy(artistId); on_close_clicked(); }); //add widget QListWidgetItem* item = new QListWidgetItem(ui->results); item->setSizeHint(track_widget->minimumSizeHint()); ui->results->setItemWidget(item,track_widget); ui->results->setMinimumHeight(track_widget->height()+6); ui->results->addItem(item); } for(int x = 0;x < jsonArrayCrew.count();x++) { tmpObj = jsonArrayCrew.at(x).toObject(); QString job = tmpObj.value("job").toString(); if(job == "Director"){ directors.append("<br>"+tmpObj.value("name").toString()); } if(job == "Producer"){ producers.append("<br>"+tmpObj.value("name").toString()); } if(job == "Author"){ authors.append("<br>"+tmpObj.value("name").toString()); } if(job == "Screenplay"){ screenplay.append("<br>"+tmpObj.value("name").toString()); } } if(producers.isEmpty()==false){ QLabel *producer = new QLabel(this); ui->crew->addWidget(producer); ui->crew->setAlignment(producer,Qt::AlignTop); producer->setStyleSheet("background:transparent"); producer->setText("<b>Producers:</b><br>"+producers); } if(directors.isEmpty()==false){ QLabel *director = new QLabel(this); ui->crew->addWidget(director); ui->crew->setAlignment(director,Qt::AlignTop); director->setStyleSheet("background:transparent"); director->setText("<b>Directors:</b><br>"+directors); } if(authors.isEmpty()==false){ QLabel *author = new QLabel(this); ui->crew->addWidget(author); ui->crew->setAlignment(author,Qt::AlignTop); author->setStyleSheet("background:transparent"); author->setText("<b>Author:</b><br>"+authors); } if(screenplay.isEmpty()==false){ QLabel *screenplayLab = new QLabel(this); ui->crew->addWidget(screenplayLab); ui->crew->setAlignment(screenplayLab,Qt::AlignTop); screenplayLab->setStyleSheet("background:transparent"); screenplayLab->setText("<b>Screenplay:</b><br>"+screenplay); } //check for error and retry if(ui->results->count() < 1){ Request *_request = new Request(this); if(creditRetry>0){ _request->clearCache(currentCreditUrl); loadCredits(); creditRetry--; qDebug()<<"RELODING CREDIT FOR MOVIE"<<movieId<<", LIST FOUND EMPTY"<<creditRetry; _request->deleteLater(); return; } } QApplication::processEvents(); } void MovieDetail::showError(QString message) { //init error _error = new Error(this); _error->setAttribute(Qt::WA_DeleteOnClose); _error->setWindowTitle(QApplication::applicationName()+" | Error dialog"); _error->setWindowFlags(Qt::Dialog); _error->setWindowModality(Qt::NonModal); _error->setError("An Error ocurred while processing your request!", message); _error->show(); } MovieDetail::~MovieDetail() { delete _error; delete _loader; delete ui; } void MovieDetail::on_close_clicked() { QGraphicsOpacityEffect *eff = new QGraphicsOpacityEffect(this); this->setGraphicsEffect(eff); QPropertyAnimation *a = new QPropertyAnimation(eff,"opacity"); a->setDuration(300); a->setStartValue(1); a->setEndValue(0); a->setEasingCurve(QEasingCurve::Linear); connect(a,&QPropertyAnimation::finished,[=](){ this->close(); }); a->start(QPropertyAnimation::DeleteWhenStopped); } void MovieDetail::setWidgetTheme(QColor rgb) { currentTheme = rgb; QColor lighter = rgb.lighter(160); QString r = QString::number(lighter.red()); QString g = QString::number(lighter.green()); QString b = QString::number(lighter.blue()); circularProgressBar->setArcPenBrush(QBrush(lighter)); ui->results->setStyleSheet("background-color:transparent;" "border:none;" "QListWidget#results{" "border-image: url(:/icons/others/trending-bg.png);" "}"); this->setStyleSheet( "QScrollBar:horizontal{" "background-color: transparent;" "border-color:none;" "border:none;" "height: 16px;" "margin:0px;" "}" "QScrollBar::handle:horizontal {" "background-color: rgba("+r+", "+g+", "+b+",160);" "min-width: 20px;" "border-radius:2px;" "margin:4px 2px 4px 2px;" "}" "QScrollBar::add-line:horizontal{" " background:none;" " width:0px;" " subcontrol-position:bottom;" " subcontrol-origin:margin;" "}" "QScrollBar::sub-line:horizontal{" " background:none;" " width:0px;" " subcontrol-position:top;" " subcontrol-origin:margin;" "}"); //style lines foreach (QFrame *frame, this->findChildren<QFrame*>()) { if(frame->objectName().contains("styled_line")) frame->setStyleSheet("QFrame#"+frame->objectName()+"{border-color:rgba("+r+", "+g+", "+b+",120)}"); } } void MovieDetail::closeRequested() { on_close_clicked(); } void MovieDetail::on_search_clicked() { emit search(ui->title->text().remove("(").remove(")")); }
36.070393
146
0.610033
[ "object" ]
c728fa052a5d6f2ce57abd52f101e846cf5d67b0
47,738
cc
C++
base/debug/activity_tracker.cc
google-ar/chromium
2441c86a5fd975f09a6c30cddb57dfb7fc239699
[ "Apache-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
777
2017-08-29T15:15:32.000Z
2022-03-21T05:29:41.000Z
base/debug/activity_tracker.cc
harrymarkovskiy/WebARonARCore
2441c86a5fd975f09a6c30cddb57dfb7fc239699
[ "Apache-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
66
2017-08-30T18:31:18.000Z
2021-08-02T10:59:35.000Z
base/debug/activity_tracker.cc
harrymarkovskiy/WebARonARCore
2441c86a5fd975f09a6c30cddb57dfb7fc239699
[ "Apache-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
123
2017-08-30T01:19:34.000Z
2022-03-17T22:55:31.000Z
// Copyright 2016 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/debug/activity_tracker.h" #include <algorithm> #include <limits> #include <utility> #include "base/debug/stack_trace.h" #include "base/files/file.h" #include "base/files/file_path.h" #include "base/files/memory_mapped_file.h" #include "base/logging.h" #include "base/memory/ptr_util.h" #include "base/metrics/field_trial.h" #include "base/metrics/histogram_macros.h" #include "base/pending_task.h" #include "base/process/process.h" #include "base/process/process_handle.h" #include "base/stl_util.h" #include "base/strings/string_util.h" #include "base/threading/platform_thread.h" namespace base { namespace debug { namespace { // A number that identifies the memory as having been initialized. It's // arbitrary but happens to be the first 4 bytes of SHA1(ThreadActivityTracker). // A version number is added on so that major structure changes won't try to // read an older version (since the cookie won't match). const uint32_t kHeaderCookie = 0xC0029B24UL + 2; // v2 // The minimum depth a stack should support. const int kMinStackDepth = 2; // The amount of memory set aside for holding arbitrary user data (key/value // pairs) globally or associated with ActivityData entries. const size_t kUserDataSize = 1024; // bytes const size_t kGlobalDataSize = 4096; // bytes const size_t kMaxUserDataNameLength = static_cast<size_t>(std::numeric_limits<uint8_t>::max()); union ThreadRef { int64_t as_id; #if defined(OS_WIN) // On Windows, the handle itself is often a pseudo-handle with a common // value meaning "this thread" and so the thread-id is used. The former // can be converted to a thread-id with a system call. PlatformThreadId as_tid; #elif defined(OS_POSIX) // On Posix, the handle is always a unique identifier so no conversion // needs to be done. However, it's value is officially opaque so there // is no one correct way to convert it to a numerical identifier. PlatformThreadHandle::Handle as_handle; #endif }; // Determines the previous aligned index. size_t RoundDownToAlignment(size_t index, size_t alignment) { return index & (0 - alignment); } // Determines the next aligned index. size_t RoundUpToAlignment(size_t index, size_t alignment) { return (index + (alignment - 1)) & (0 - alignment); } } // namespace // It doesn't matter what is contained in this (though it will be all zeros) // as only the address of it is important. const ActivityData kNullActivityData = {}; ActivityData ActivityData::ForThread(const PlatformThreadHandle& handle) { ThreadRef thread_ref; thread_ref.as_id = 0; // Zero the union in case other is smaller. #if defined(OS_WIN) thread_ref.as_tid = ::GetThreadId(handle.platform_handle()); #elif defined(OS_POSIX) thread_ref.as_handle = handle.platform_handle(); #endif return ForThread(thread_ref.as_id); } ActivityTrackerMemoryAllocator::ActivityTrackerMemoryAllocator( PersistentMemoryAllocator* allocator, uint32_t object_type, uint32_t object_free_type, size_t object_size, size_t cache_size, bool make_iterable) : allocator_(allocator), object_type_(object_type), object_free_type_(object_free_type), object_size_(object_size), cache_size_(cache_size), make_iterable_(make_iterable), iterator_(allocator), cache_values_(new Reference[cache_size]), cache_used_(0) { DCHECK(allocator); } ActivityTrackerMemoryAllocator::~ActivityTrackerMemoryAllocator() {} ActivityTrackerMemoryAllocator::Reference ActivityTrackerMemoryAllocator::GetObjectReference() { // First see if there is a cached value that can be returned. This is much // faster than searching the memory system for free blocks. while (cache_used_ > 0) { Reference cached = cache_values_[--cache_used_]; // Change the type of the cached object to the proper type and return it. // If the type-change fails that means another thread has taken this from // under us (via the search below) so ignore it and keep trying. if (allocator_->ChangeType(cached, object_type_, object_free_type_)) return cached; } // Fetch the next "free" object from persistent memory. Rather than restart // the iterator at the head each time and likely waste time going again // through objects that aren't relevant, the iterator continues from where // it last left off and is only reset when the end is reached. If the // returned reference matches |last|, then it has wrapped without finding // anything. const Reference last = iterator_.GetLast(); while (true) { uint32_t type; Reference found = iterator_.GetNext(&type); if (found && type == object_free_type_) { // Found a free object. Change it to the proper type and return it. If // the type-change fails that means another thread has taken this from // under us so ignore it and keep trying. if (allocator_->ChangeType(found, object_type_, object_free_type_)) return found; } if (found == last) { // Wrapped. No desired object was found. break; } if (!found) { // Reached end; start over at the beginning. iterator_.Reset(); } } // No free block was found so instead allocate a new one. Reference allocated = allocator_->Allocate(object_size_, object_type_); if (allocated && make_iterable_) allocator_->MakeIterable(allocated); return allocated; } void ActivityTrackerMemoryAllocator::ReleaseObjectReference(Reference ref) { // Zero the memory so that it is ready for immediate use if needed later. char* mem_base = allocator_->GetAsArray<char>( ref, object_type_, PersistentMemoryAllocator::kSizeAny); DCHECK(mem_base); memset(mem_base, 0, object_size_); // Mark object as free. bool success = allocator_->ChangeType(ref, object_free_type_, object_type_); DCHECK(success); // Add this reference to our "free" cache if there is space. If not, the type // has still been changed to indicate that it is free so this (or another) // thread can find it, albeit more slowly, using the iteration method above. if (cache_used_ < cache_size_) cache_values_[cache_used_++] = ref; } // static void Activity::FillFrom(Activity* activity, const void* program_counter, const void* origin, Type type, const ActivityData& data) { activity->time_internal = base::TimeTicks::Now().ToInternalValue(); activity->calling_address = reinterpret_cast<uintptr_t>(program_counter); activity->origin_address = reinterpret_cast<uintptr_t>(origin); activity->activity_type = type; activity->data = data; #if defined(SYZYASAN) // Create a stacktrace from the current location and get the addresses. StackTrace stack_trace; size_t stack_depth; const void* const* stack_addrs = stack_trace.Addresses(&stack_depth); // Copy the stack addresses, ignoring the first one (here). size_t i; for (i = 1; i < stack_depth && i < kActivityCallStackSize; ++i) { activity->call_stack[i - 1] = reinterpret_cast<uintptr_t>(stack_addrs[i]); } activity->call_stack[i - 1] = 0; #else activity->call_stack[0] = 0; #endif } ActivityUserData::TypedValue::TypedValue() {} ActivityUserData::TypedValue::TypedValue(const TypedValue& other) = default; ActivityUserData::TypedValue::~TypedValue() {} StringPiece ActivityUserData::TypedValue::Get() const { DCHECK_EQ(RAW_VALUE, type_); return long_value_; } StringPiece ActivityUserData::TypedValue::GetString() const { DCHECK_EQ(STRING_VALUE, type_); return long_value_; } bool ActivityUserData::TypedValue::GetBool() const { DCHECK_EQ(BOOL_VALUE, type_); return short_value_ != 0; } char ActivityUserData::TypedValue::GetChar() const { DCHECK_EQ(CHAR_VALUE, type_); return static_cast<char>(short_value_); } int64_t ActivityUserData::TypedValue::GetInt() const { DCHECK_EQ(SIGNED_VALUE, type_); return static_cast<int64_t>(short_value_); } uint64_t ActivityUserData::TypedValue::GetUint() const { DCHECK_EQ(UNSIGNED_VALUE, type_); return static_cast<uint64_t>(short_value_); } StringPiece ActivityUserData::TypedValue::GetReference() const { DCHECK_EQ(RAW_VALUE_REFERENCE, type_); return ref_value_; } StringPiece ActivityUserData::TypedValue::GetStringReference() const { DCHECK_EQ(STRING_VALUE_REFERENCE, type_); return ref_value_; } ActivityUserData::ValueInfo::ValueInfo() {} ActivityUserData::ValueInfo::ValueInfo(ValueInfo&&) = default; ActivityUserData::ValueInfo::~ValueInfo() {} std::atomic<uint32_t> ActivityUserData::next_id_; ActivityUserData::ActivityUserData(void* memory, size_t size) : memory_(reinterpret_cast<char*>(memory)), available_(RoundDownToAlignment(size, kMemoryAlignment)), id_(reinterpret_cast<std::atomic<uint32_t>*>(memory)) { // It's possible that no user data is being stored. if (!memory_) return; DCHECK_LT(kMemoryAlignment, available_); if (id_->load(std::memory_order_relaxed) == 0) { // Generate a new ID and store it in the first 32-bit word of memory_. // |id_| must be non-zero for non-sink instances. uint32_t id; while ((id = next_id_.fetch_add(1, std::memory_order_relaxed)) == 0) ; id_->store(id, std::memory_order_relaxed); DCHECK_NE(0U, id_->load(std::memory_order_relaxed)); } memory_ += kMemoryAlignment; available_ -= kMemoryAlignment; // If there is already data present, load that. This allows the same class // to be used for analysis through snapshots. ImportExistingData(); } ActivityUserData::~ActivityUserData() {} void ActivityUserData::Set(StringPiece name, ValueType type, const void* memory, size_t size) { DCHECK(thread_checker_.CalledOnValidThread()); DCHECK_GE(std::numeric_limits<uint8_t>::max(), name.length()); size = std::min(std::numeric_limits<uint16_t>::max() - (kMemoryAlignment - 1), size); // It's possible that no user data is being stored. if (!memory_) return; // The storage of a name is limited so use that limit during lookup. if (name.length() > kMaxUserDataNameLength) name.set(name.data(), kMaxUserDataNameLength); ValueInfo* info; auto existing = values_.find(name); if (existing != values_.end()) { info = &existing->second; } else { // The name size is limited to what can be held in a single byte but // because there are not alignment constraints on strings, it's set tight // against the header. Its extent (the reserved space, even if it's not // all used) is calculated so that, when pressed against the header, the // following field will be aligned properly. size_t name_size = name.length(); size_t name_extent = RoundUpToAlignment(sizeof(Header) + name_size, kMemoryAlignment) - sizeof(Header); size_t value_extent = RoundUpToAlignment(size, kMemoryAlignment); // The "base size" is the size of the header and (padded) string key. Stop // now if there's not room enough for even this. size_t base_size = sizeof(Header) + name_extent; if (base_size > available_) return; // The "full size" is the size for storing the entire value. size_t full_size = std::min(base_size + value_extent, available_); // If the value is actually a single byte, see if it can be stuffed at the // end of the name extent rather than wasting kMemoryAlignment bytes. if (size == 1 && name_extent > name_size) { full_size = base_size; --name_extent; --base_size; } // Truncate the stored size to the amount of available memory. Stop now if // there's not any room for even part of the value. size = std::min(full_size - base_size, size); if (size == 0) return; // Allocate a chunk of memory. Header* header = reinterpret_cast<Header*>(memory_); memory_ += full_size; available_ -= full_size; // Datafill the header and name records. Memory must be zeroed. The |type| // is written last, atomically, to release all the other values. DCHECK_EQ(END_OF_VALUES, header->type.load(std::memory_order_relaxed)); DCHECK_EQ(0, header->value_size.load(std::memory_order_relaxed)); header->name_size = static_cast<uint8_t>(name_size); header->record_size = full_size; char* name_memory = reinterpret_cast<char*>(header) + sizeof(Header); void* value_memory = reinterpret_cast<char*>(header) + sizeof(Header) + name_extent; memcpy(name_memory, name.data(), name_size); header->type.store(type, std::memory_order_release); // Create an entry in |values_| so that this field can be found and changed // later on without having to allocate new entries. StringPiece persistent_name(name_memory, name_size); auto inserted = values_.insert(std::make_pair(persistent_name, ValueInfo())); DCHECK(inserted.second); // True if inserted, false if existed. info = &inserted.first->second; info->name = persistent_name; info->memory = value_memory; info->size_ptr = &header->value_size; info->extent = full_size - sizeof(Header) - name_extent; info->type = type; } // Copy the value data to storage. The |size| is written last, atomically, to // release the copied data. Until then, a parallel reader will just ignore // records with a zero size. DCHECK_EQ(type, info->type); size = std::min(size, info->extent); info->size_ptr->store(0, std::memory_order_seq_cst); memcpy(info->memory, memory, size); info->size_ptr->store(size, std::memory_order_release); } void ActivityUserData::SetReference(StringPiece name, ValueType type, const void* memory, size_t size) { ReferenceRecord rec; rec.address = reinterpret_cast<uintptr_t>(memory); rec.size = size; Set(name, type, &rec, sizeof(rec)); } void ActivityUserData::ImportExistingData() const { while (available_ > sizeof(Header)) { Header* header = reinterpret_cast<Header*>(memory_); ValueType type = static_cast<ValueType>(header->type.load(std::memory_order_acquire)); if (type == END_OF_VALUES) return; if (header->record_size > available_) return; size_t value_offset = RoundUpToAlignment(sizeof(Header) + header->name_size, kMemoryAlignment); if (header->record_size == value_offset && header->value_size.load(std::memory_order_relaxed) == 1) { value_offset -= 1; } if (value_offset + header->value_size > header->record_size) return; ValueInfo info; info.name = StringPiece(memory_ + sizeof(Header), header->name_size); info.type = type; info.memory = memory_ + value_offset; info.size_ptr = &header->value_size; info.extent = header->record_size - value_offset; StringPiece key(info.name); values_.insert(std::make_pair(key, std::move(info))); memory_ += header->record_size; available_ -= header->record_size; } } bool ActivityUserData::CreateSnapshot(Snapshot* output_snapshot) const { DCHECK(output_snapshot); DCHECK(output_snapshot->empty()); // Find any new data that may have been added by an active instance of this // class that is adding records. ImportExistingData(); for (const auto& entry : values_) { TypedValue value; value.type_ = entry.second.type; DCHECK_GE(entry.second.extent, entry.second.size_ptr->load(std::memory_order_relaxed)); switch (entry.second.type) { case RAW_VALUE: case STRING_VALUE: value.long_value_ = std::string(reinterpret_cast<char*>(entry.second.memory), entry.second.size_ptr->load(std::memory_order_relaxed)); break; case RAW_VALUE_REFERENCE: case STRING_VALUE_REFERENCE: { ReferenceRecord* ref = reinterpret_cast<ReferenceRecord*>(entry.second.memory); value.ref_value_ = StringPiece( reinterpret_cast<char*>(static_cast<uintptr_t>(ref->address)), static_cast<size_t>(ref->size)); } break; case BOOL_VALUE: case CHAR_VALUE: value.short_value_ = *reinterpret_cast<char*>(entry.second.memory); break; case SIGNED_VALUE: case UNSIGNED_VALUE: value.short_value_ = *reinterpret_cast<uint64_t*>(entry.second.memory); break; case END_OF_VALUES: // Included for completeness purposes. NOTREACHED(); } auto inserted = output_snapshot->insert( std::make_pair(entry.second.name.as_string(), std::move(value))); DCHECK(inserted.second); // True if inserted, false if existed. } return true; } const void* ActivityUserData::GetBaseAddress() { // The |memory_| pointer advances as elements are written but the |id_| // value is always at the start of the block so just return that. return id_; } // This information is kept for every thread that is tracked. It is filled // the very first time the thread is seen. All fields must be of exact sizes // so there is no issue moving between 32 and 64-bit builds. struct ThreadActivityTracker::Header { // Expected size for 32/64-bit check. static constexpr size_t kExpectedInstanceSize = 80; // This unique number indicates a valid initialization of the memory. std::atomic<uint32_t> cookie; // The number of Activity slots (spaces that can hold an Activity) that // immediately follow this structure in memory. uint32_t stack_slots; // The process-id and thread-id (thread_ref.as_id) to which this data belongs. // These identifiers are not guaranteed to mean anything but are unique, in // combination, among all active trackers. It would be nice to always have // the process_id be a 64-bit value but the necessity of having it atomic // (for the memory barriers it provides) limits it to the natural word size // of the machine. #ifdef ARCH_CPU_64_BITS std::atomic<int64_t> process_id; #else std::atomic<int32_t> process_id; int32_t process_id_padding; #endif ThreadRef thread_ref; // The start-time and start-ticks when the data was created. Each activity // record has a |time_internal| value that can be converted to a "wall time" // with these two values. int64_t start_time; int64_t start_ticks; // The current depth of the stack. This may be greater than the number of // slots. If the depth exceeds the number of slots, the newest entries // won't be recorded. std::atomic<uint32_t> current_depth; // A memory location used to indicate if changes have been made to the stack // that would invalidate an in-progress read of its contents. The active // tracker will zero the value whenever something gets popped from the // stack. A monitoring tracker can write a non-zero value here, copy the // stack contents, and read the value to know, if it is still non-zero, that // the contents didn't change while being copied. This can handle concurrent // snapshot operations only if each snapshot writes a different bit (which // is not the current implementation so no parallel snapshots allowed). std::atomic<uint32_t> stack_unchanged; // The name of the thread (up to a maximum length). Dynamic-length names // are not practical since the memory has to come from the same persistent // allocator that holds this structure and to which this object has no // reference. char thread_name[32]; }; ThreadActivityTracker::Snapshot::Snapshot() {} ThreadActivityTracker::Snapshot::~Snapshot() {} ThreadActivityTracker::ScopedActivity::ScopedActivity( ThreadActivityTracker* tracker, const void* program_counter, const void* origin, Activity::Type type, const ActivityData& data) : tracker_(tracker) { if (tracker_) activity_id_ = tracker_->PushActivity(program_counter, origin, type, data); } ThreadActivityTracker::ScopedActivity::~ScopedActivity() { if (tracker_) tracker_->PopActivity(activity_id_); } void ThreadActivityTracker::ScopedActivity::ChangeTypeAndData( Activity::Type type, const ActivityData& data) { if (tracker_) tracker_->ChangeActivity(activity_id_, type, data); } ThreadActivityTracker::ThreadActivityTracker(void* base, size_t size) : header_(static_cast<Header*>(base)), stack_(reinterpret_cast<Activity*>(reinterpret_cast<char*>(base) + sizeof(Header))), stack_slots_( static_cast<uint32_t>((size - sizeof(Header)) / sizeof(Activity))) { DCHECK(thread_checker_.CalledOnValidThread()); // Verify the parameters but fail gracefully if they're not valid so that // production code based on external inputs will not crash. IsValid() will // return false in this case. if (!base || // Ensure there is enough space for the header and at least a few records. size < sizeof(Header) + kMinStackDepth * sizeof(Activity) || // Ensure that the |stack_slots_| calculation didn't overflow. (size - sizeof(Header)) / sizeof(Activity) > std::numeric_limits<uint32_t>::max()) { NOTREACHED(); return; } // Ensure that the thread reference doesn't exceed the size of the ID number. // This won't compile at the global scope because Header is a private struct. static_assert( sizeof(header_->thread_ref) == sizeof(header_->thread_ref.as_id), "PlatformThreadHandle::Handle is too big to hold in 64-bit ID"); // Ensure that the alignment of Activity.data is properly aligned to a // 64-bit boundary so there are no interoperability-issues across cpu // architectures. static_assert(offsetof(Activity, data) % sizeof(uint64_t) == 0, "ActivityData.data is not 64-bit aligned"); // Provided memory should either be completely initialized or all zeros. if (header_->cookie.load(std::memory_order_relaxed) == 0) { // This is a new file. Double-check other fields and then initialize. DCHECK_EQ(0, header_->process_id.load(std::memory_order_relaxed)); DCHECK_EQ(0, header_->thread_ref.as_id); DCHECK_EQ(0, header_->start_time); DCHECK_EQ(0, header_->start_ticks); DCHECK_EQ(0U, header_->stack_slots); DCHECK_EQ(0U, header_->current_depth.load(std::memory_order_relaxed)); DCHECK_EQ(0U, header_->stack_unchanged.load(std::memory_order_relaxed)); DCHECK_EQ(0, stack_[0].time_internal); DCHECK_EQ(0U, stack_[0].origin_address); DCHECK_EQ(0U, stack_[0].call_stack[0]); DCHECK_EQ(0U, stack_[0].data.task.sequence_id); #if defined(OS_WIN) header_->thread_ref.as_tid = PlatformThread::CurrentId(); #elif defined(OS_POSIX) header_->thread_ref.as_handle = PlatformThread::CurrentHandle().platform_handle(); #endif header_->process_id.store(GetCurrentProcId(), std::memory_order_relaxed); header_->start_time = base::Time::Now().ToInternalValue(); header_->start_ticks = base::TimeTicks::Now().ToInternalValue(); header_->stack_slots = stack_slots_; strlcpy(header_->thread_name, PlatformThread::GetName(), sizeof(header_->thread_name)); // This is done last so as to guarantee that everything above is "released" // by the time this value gets written. header_->cookie.store(kHeaderCookie, std::memory_order_release); valid_ = true; DCHECK(IsValid()); } else { // This is a file with existing data. Perform basic consistency checks. valid_ = true; valid_ = IsValid(); } } ThreadActivityTracker::~ThreadActivityTracker() {} ThreadActivityTracker::ActivityId ThreadActivityTracker::PushActivity( const void* program_counter, const void* origin, Activity::Type type, const ActivityData& data) { // A thread-checker creates a lock to check the thread-id which means // re-entry into this code if lock acquisitions are being tracked. DCHECK(type == Activity::ACT_LOCK_ACQUIRE || thread_checker_.CalledOnValidThread()); // Get the current depth of the stack. No access to other memory guarded // by this variable is done here so a "relaxed" load is acceptable. uint32_t depth = header_->current_depth.load(std::memory_order_relaxed); // Handle the case where the stack depth has exceeded the storage capacity. // Extra entries will be lost leaving only the base of the stack. if (depth >= stack_slots_) { // Since no other threads modify the data, no compare/exchange is needed. // Since no other memory is being modified, a "relaxed" store is acceptable. header_->current_depth.store(depth + 1, std::memory_order_relaxed); return depth; } // Get a pointer to the next activity and load it. No atomicity is required // here because the memory is known only to this thread. It will be made // known to other threads once the depth is incremented. Activity::FillFrom(&stack_[depth], program_counter, origin, type, data); // Save the incremented depth. Because this guards |activity| memory filled // above that may be read by another thread once the recorded depth changes, // a "release" store is required. header_->current_depth.store(depth + 1, std::memory_order_release); // The current depth is used as the activity ID because it simply identifies // an entry. Once an entry is pop'd, it's okay to reuse the ID. return depth; } void ThreadActivityTracker::ChangeActivity(ActivityId id, Activity::Type type, const ActivityData& data) { DCHECK(thread_checker_.CalledOnValidThread()); DCHECK(type != Activity::ACT_NULL || &data != &kNullActivityData); DCHECK_LT(id, header_->current_depth.load(std::memory_order_acquire)); // Update the information if it is being recorded (i.e. within slot limit). if (id < stack_slots_) { Activity* activity = &stack_[id]; if (type != Activity::ACT_NULL) { DCHECK_EQ(activity->activity_type & Activity::ACT_CATEGORY_MASK, type & Activity::ACT_CATEGORY_MASK); activity->activity_type = type; } if (&data != &kNullActivityData) activity->data = data; } } void ThreadActivityTracker::PopActivity(ActivityId id) { // Do an atomic decrement of the depth. No changes to stack entries guarded // by this variable are done here so a "relaxed" operation is acceptable. // |depth| will receive the value BEFORE it was modified which means the // return value must also be decremented. The slot will be "free" after // this call but since only a single thread can access this object, the // data will remain valid until this method returns or calls outside. uint32_t depth = header_->current_depth.fetch_sub(1, std::memory_order_relaxed) - 1; // Validate that everything is running correctly. DCHECK_EQ(id, depth); // A thread-checker creates a lock to check the thread-id which means // re-entry into this code if lock acquisitions are being tracked. DCHECK(stack_[depth].activity_type == Activity::ACT_LOCK_ACQUIRE || thread_checker_.CalledOnValidThread()); // The stack has shrunk meaning that some other thread trying to copy the // contents for reporting purposes could get bad data. That thread would // have written a non-zero value into |stack_unchanged|; clearing it here // will let that thread detect that something did change. This needs to // happen after the atomic |depth| operation above so a "release" store // is required. header_->stack_unchanged.store(0, std::memory_order_release); } std::unique_ptr<ActivityUserData> ThreadActivityTracker::GetUserData( ActivityId id, ActivityTrackerMemoryAllocator* allocator) { // User-data is only stored for activities actually held in the stack. if (id < stack_slots_) { // Don't allow user data for lock acquisition as recursion may occur. if (stack_[id].activity_type == Activity::ACT_LOCK_ACQUIRE) { NOTREACHED(); return MakeUnique<ActivityUserData>(nullptr, 0); } // Get (or reuse) a block of memory and create a real UserData object // on it. PersistentMemoryAllocator::Reference ref = allocator->GetObjectReference(); void* memory = allocator->GetAsArray<char>(ref, PersistentMemoryAllocator::kSizeAny); if (memory) { std::unique_ptr<ActivityUserData> user_data = MakeUnique<ActivityUserData>(memory, kUserDataSize); stack_[id].user_data_ref = ref; stack_[id].user_data_id = user_data->id(); return user_data; } } // Return a dummy object that will still accept (but ignore) Set() calls. return MakeUnique<ActivityUserData>(nullptr, 0); } bool ThreadActivityTracker::HasUserData(ActivityId id) { // User-data is only stored for activities actually held in the stack. return (id < stack_slots_ && stack_[id].user_data_ref); } void ThreadActivityTracker::ReleaseUserData( ActivityId id, ActivityTrackerMemoryAllocator* allocator) { // User-data is only stored for activities actually held in the stack. if (id < stack_slots_ && stack_[id].user_data_ref) { allocator->ReleaseObjectReference(stack_[id].user_data_ref); stack_[id].user_data_ref = 0; } } bool ThreadActivityTracker::IsValid() const { if (header_->cookie.load(std::memory_order_acquire) != kHeaderCookie || header_->process_id.load(std::memory_order_relaxed) == 0 || header_->thread_ref.as_id == 0 || header_->start_time == 0 || header_->start_ticks == 0 || header_->stack_slots != stack_slots_ || header_->thread_name[sizeof(header_->thread_name) - 1] != '\0') { return false; } return valid_; } bool ThreadActivityTracker::CreateSnapshot(Snapshot* output_snapshot) const { DCHECK(output_snapshot); // There is no "called on valid thread" check for this method as it can be // called from other threads or even other processes. It is also the reason // why atomic operations must be used in certain places above. // It's possible for the data to change while reading it in such a way that it // invalidates the read. Make several attempts but don't try forever. const int kMaxAttempts = 10; uint32_t depth; // Stop here if the data isn't valid. if (!IsValid()) return false; // Allocate the maximum size for the stack so it doesn't have to be done // during the time-sensitive snapshot operation. It is shrunk once the // actual size is known. output_snapshot->activity_stack.reserve(stack_slots_); for (int attempt = 0; attempt < kMaxAttempts; ++attempt) { // Remember the process and thread IDs to ensure they aren't replaced // during the snapshot operation. Use "acquire" to ensure that all the // non-atomic fields of the structure are valid (at least at the current // moment in time). const int64_t starting_process_id = header_->process_id.load(std::memory_order_acquire); const int64_t starting_thread_id = header_->thread_ref.as_id; // Write a non-zero value to |stack_unchanged| so it's possible to detect // at the end that nothing has changed since copying the data began. A // "cst" operation is required to ensure it occurs before everything else. // Using "cst" memory ordering is relatively expensive but this is only // done during analysis so doesn't directly affect the worker threads. header_->stack_unchanged.store(1, std::memory_order_seq_cst); // Fetching the current depth also "acquires" the contents of the stack. depth = header_->current_depth.load(std::memory_order_acquire); uint32_t count = std::min(depth, stack_slots_); output_snapshot->activity_stack.resize(count); if (count > 0) { // Copy the existing contents. Memcpy is used for speed. memcpy(&output_snapshot->activity_stack[0], stack_, count * sizeof(Activity)); } // Retry if something changed during the copy. A "cst" operation ensures // it must happen after all the above operations. if (!header_->stack_unchanged.load(std::memory_order_seq_cst)) continue; // Stack copied. Record it's full depth. output_snapshot->activity_stack_depth = depth; // TODO(bcwhite): Snapshot other things here. // Get the general thread information. Loading of "process_id" is guaranteed // to be last so that it's possible to detect below if any content has // changed while reading it. It's technically possible for a thread to end, // have its data cleared, a new thread get created with the same IDs, and // it perform an action which starts tracking all in the time since the // ID reads above but the chance is so unlikely that it's not worth the // effort and complexity of protecting against it (perhaps with an // "unchanged" field like is done for the stack). output_snapshot->thread_name = std::string(header_->thread_name, sizeof(header_->thread_name) - 1); output_snapshot->thread_id = header_->thread_ref.as_id; output_snapshot->process_id = header_->process_id.load(std::memory_order_seq_cst); // All characters of the thread-name buffer were copied so as to not break // if the trailing NUL were missing. Now limit the length if the actual // name is shorter. output_snapshot->thread_name.resize( strlen(output_snapshot->thread_name.c_str())); // If the process or thread ID has changed then the tracker has exited and // the memory reused by a new one. Try again. if (output_snapshot->process_id != starting_process_id || output_snapshot->thread_id != starting_thread_id) { continue; } // Only successful if the data is still valid once everything is done since // it's possible for the thread to end somewhere in the middle and all its // values become garbage. if (!IsValid()) return false; // Change all the timestamps in the activities from "ticks" to "wall" time. const Time start_time = Time::FromInternalValue(header_->start_time); const int64_t start_ticks = header_->start_ticks; for (Activity& activity : output_snapshot->activity_stack) { activity.time_internal = (start_time + TimeDelta::FromInternalValue(activity.time_internal - start_ticks)) .ToInternalValue(); } // Success! return true; } // Too many attempts. return false; } // static size_t ThreadActivityTracker::SizeForStackDepth(int stack_depth) { return static_cast<size_t>(stack_depth) * sizeof(Activity) + sizeof(Header); } GlobalActivityTracker* GlobalActivityTracker::g_tracker_ = nullptr; GlobalActivityTracker::ScopedThreadActivity::ScopedThreadActivity( const void* program_counter, const void* origin, Activity::Type type, const ActivityData& data, bool lock_allowed) : ThreadActivityTracker::ScopedActivity(GetOrCreateTracker(lock_allowed), program_counter, origin, type, data) {} GlobalActivityTracker::ScopedThreadActivity::~ScopedThreadActivity() { if (tracker_ && tracker_->HasUserData(activity_id_)) { GlobalActivityTracker* global = GlobalActivityTracker::Get(); AutoLock lock(global->user_data_allocator_lock_); tracker_->ReleaseUserData(activity_id_, &global->user_data_allocator_); } } ActivityUserData& GlobalActivityTracker::ScopedThreadActivity::user_data() { if (!user_data_) { if (tracker_) { GlobalActivityTracker* global = GlobalActivityTracker::Get(); AutoLock lock(global->user_data_allocator_lock_); user_data_ = tracker_->GetUserData(activity_id_, &global->user_data_allocator_); } else { user_data_ = MakeUnique<ActivityUserData>(nullptr, 0); } } return *user_data_; } GlobalActivityTracker::ManagedActivityTracker::ManagedActivityTracker( PersistentMemoryAllocator::Reference mem_reference, void* base, size_t size) : ThreadActivityTracker(base, size), mem_reference_(mem_reference), mem_base_(base) {} GlobalActivityTracker::ManagedActivityTracker::~ManagedActivityTracker() { // The global |g_tracker_| must point to the owner of this class since all // objects of this type must be destructed before |g_tracker_| can be changed // (something that only occurs in tests). DCHECK(g_tracker_); g_tracker_->ReturnTrackerMemory(this); } void GlobalActivityTracker::CreateWithAllocator( std::unique_ptr<PersistentMemoryAllocator> allocator, int stack_depth) { // There's no need to do anything with the result. It is self-managing. GlobalActivityTracker* global_tracker = new GlobalActivityTracker(std::move(allocator), stack_depth); // Create a tracker for this thread since it is known. global_tracker->CreateTrackerForCurrentThread(); } #if !defined(OS_NACL) // static void GlobalActivityTracker::CreateWithFile(const FilePath& file_path, size_t size, uint64_t id, StringPiece name, int stack_depth) { DCHECK(!file_path.empty()); DCHECK_GE(static_cast<uint64_t>(std::numeric_limits<int64_t>::max()), size); // Create and map the file into memory and make it globally available. std::unique_ptr<MemoryMappedFile> mapped_file(new MemoryMappedFile()); bool success = mapped_file->Initialize(File(file_path, File::FLAG_CREATE_ALWAYS | File::FLAG_READ | File::FLAG_WRITE | File::FLAG_SHARE_DELETE), {0, static_cast<int64_t>(size)}, MemoryMappedFile::READ_WRITE_EXTEND); DCHECK(success); CreateWithAllocator(MakeUnique<FilePersistentMemoryAllocator>( std::move(mapped_file), size, id, name, false), stack_depth); } #endif // !defined(OS_NACL) // static void GlobalActivityTracker::CreateWithLocalMemory(size_t size, uint64_t id, StringPiece name, int stack_depth) { CreateWithAllocator( MakeUnique<LocalPersistentMemoryAllocator>(size, id, name), stack_depth); } ThreadActivityTracker* GlobalActivityTracker::CreateTrackerForCurrentThread() { DCHECK(!this_thread_tracker_.Get()); PersistentMemoryAllocator::Reference mem_reference; { base::AutoLock autolock(thread_tracker_allocator_lock_); mem_reference = thread_tracker_allocator_.GetObjectReference(); } if (!mem_reference) { // Failure. This shouldn't happen. But be graceful if it does, probably // because the underlying allocator wasn't given enough memory to satisfy // to all possible requests. NOTREACHED(); // Report the thread-count at which the allocator was full so that the // failure can be seen and underlying memory resized appropriately. UMA_HISTOGRAM_COUNTS_1000( "ActivityTracker.ThreadTrackers.MemLimitTrackerCount", thread_tracker_count_.load(std::memory_order_relaxed)); // Return null, just as if tracking wasn't enabled. return nullptr; } // Convert the memory block found above into an actual memory address. // Doing the conversion as a Header object enacts the 32/64-bit size // consistency checks which would not otherwise be done. Unfortunately, // some older compilers and MSVC don't have standard-conforming definitions // of std::atomic which cause it not to be plain-old-data. Don't check on // those platforms assuming that the checks on other platforms will be // sufficient. // TODO(bcwhite): Review this after major compiler releases. DCHECK(mem_reference); void* mem_base; #if 0 // TODO(bcwhite): Update this for new GetAsObject functionality. mem_base = allocator_->GetAsObject<ThreadActivityTracker::Header>( mem_reference, kTypeIdActivityTracker); #else mem_base = allocator_->GetAsArray<char>(mem_reference, kTypeIdActivityTracker, PersistentMemoryAllocator::kSizeAny); #endif DCHECK(mem_base); DCHECK_LE(stack_memory_size_, allocator_->GetAllocSize(mem_reference)); // Create a tracker with the acquired memory and set it as the tracker // for this particular thread in thread-local-storage. ManagedActivityTracker* tracker = new ManagedActivityTracker(mem_reference, mem_base, stack_memory_size_); DCHECK(tracker->IsValid()); this_thread_tracker_.Set(tracker); int old_count = thread_tracker_count_.fetch_add(1, std::memory_order_relaxed); UMA_HISTOGRAM_ENUMERATION("ActivityTracker.ThreadTrackers.Count", old_count + 1, kMaxThreadCount); return tracker; } void GlobalActivityTracker::ReleaseTrackerForCurrentThreadForTesting() { ThreadActivityTracker* tracker = reinterpret_cast<ThreadActivityTracker*>(this_thread_tracker_.Get()); if (tracker) delete tracker; } void GlobalActivityTracker::RecordLogMessage(StringPiece message) { // Allocate at least one extra byte so the string is NUL terminated. All // memory returned by the allocator is guaranteed to be zeroed. PersistentMemoryAllocator::Reference ref = allocator_->Allocate(message.size() + 1, kTypeIdGlobalLogMessage); char* memory = allocator_->GetAsArray<char>(ref, kTypeIdGlobalLogMessage, message.size() + 1); if (memory) { memcpy(memory, message.data(), message.size()); allocator_->MakeIterable(ref); } } GlobalActivityTracker::GlobalActivityTracker( std::unique_ptr<PersistentMemoryAllocator> allocator, int stack_depth) : allocator_(std::move(allocator)), stack_memory_size_(ThreadActivityTracker::SizeForStackDepth(stack_depth)), this_thread_tracker_(&OnTLSDestroy), thread_tracker_count_(0), thread_tracker_allocator_(allocator_.get(), kTypeIdActivityTracker, kTypeIdActivityTrackerFree, stack_memory_size_, kCachedThreadMemories, /*make_iterable=*/true), user_data_allocator_(allocator_.get(), kTypeIdUserDataRecord, kTypeIdUserDataRecordFree, kUserDataSize, kCachedUserDataMemories, /*make_iterable=*/false), user_data_( allocator_->GetAsArray<char>( allocator_->Allocate(kGlobalDataSize, kTypeIdGlobalDataRecord), kTypeIdGlobalDataRecord, PersistentMemoryAllocator::kSizeAny), kGlobalDataSize) { // Ensure the passed memory is valid and empty (iterator finds nothing). uint32_t type; DCHECK(!PersistentMemoryAllocator::Iterator(allocator_.get()).GetNext(&type)); // Ensure that there is no other global object and then make this one such. DCHECK(!g_tracker_); g_tracker_ = this; // The global user-data record must be iterable in order to be found by an // analyzer. allocator_->MakeIterable(allocator_->GetAsReference( user_data_.GetBaseAddress(), kTypeIdGlobalDataRecord)); } GlobalActivityTracker::~GlobalActivityTracker() { DCHECK_EQ(g_tracker_, this); DCHECK_EQ(0, thread_tracker_count_.load(std::memory_order_relaxed)); g_tracker_ = nullptr; } void GlobalActivityTracker::ReturnTrackerMemory( ManagedActivityTracker* tracker) { PersistentMemoryAllocator::Reference mem_reference = tracker->mem_reference_; void* mem_base = tracker->mem_base_; DCHECK(mem_reference); DCHECK(mem_base); // Remove the destructed tracker from the set of known ones. DCHECK_LE(1, thread_tracker_count_.load(std::memory_order_relaxed)); thread_tracker_count_.fetch_sub(1, std::memory_order_relaxed); // Release this memory for re-use at a later time. base::AutoLock autolock(thread_tracker_allocator_lock_); thread_tracker_allocator_.ReleaseObjectReference(mem_reference); } // static void GlobalActivityTracker::OnTLSDestroy(void* value) { delete reinterpret_cast<ManagedActivityTracker*>(value); } ScopedActivity::ScopedActivity(const void* program_counter, uint8_t action, uint32_t id, int32_t info) : GlobalActivityTracker::ScopedThreadActivity( program_counter, nullptr, static_cast<Activity::Type>(Activity::ACT_GENERIC | action), ActivityData::ForGeneric(id, info), /*lock_allowed=*/true), id_(id) { // The action must not affect the category bits of the activity type. DCHECK_EQ(0, action & Activity::ACT_CATEGORY_MASK); } void ScopedActivity::ChangeAction(uint8_t action) { DCHECK_EQ(0, action & Activity::ACT_CATEGORY_MASK); ChangeTypeAndData(static_cast<Activity::Type>(Activity::ACT_GENERIC | action), kNullActivityData); } void ScopedActivity::ChangeInfo(int32_t info) { ChangeTypeAndData(Activity::ACT_NULL, ActivityData::ForGeneric(id_, info)); } void ScopedActivity::ChangeActionAndInfo(uint8_t action, int32_t info) { DCHECK_EQ(0, action & Activity::ACT_CATEGORY_MASK); ChangeTypeAndData(static_cast<Activity::Type>(Activity::ACT_GENERIC | action), ActivityData::ForGeneric(id_, info)); } ScopedTaskRunActivity::ScopedTaskRunActivity( const void* program_counter, const base::PendingTask& task) : GlobalActivityTracker::ScopedThreadActivity( program_counter, task.posted_from.program_counter(), Activity::ACT_TASK_RUN, ActivityData::ForTask(task.sequence_num), /*lock_allowed=*/true) {} ScopedLockAcquireActivity::ScopedLockAcquireActivity( const void* program_counter, const base::internal::LockImpl* lock) : GlobalActivityTracker::ScopedThreadActivity( program_counter, nullptr, Activity::ACT_LOCK_ACQUIRE, ActivityData::ForLock(lock), /*lock_allowed=*/false) {} ScopedEventWaitActivity::ScopedEventWaitActivity( const void* program_counter, const base::WaitableEvent* event) : GlobalActivityTracker::ScopedThreadActivity( program_counter, nullptr, Activity::ACT_EVENT_WAIT, ActivityData::ForEvent(event), /*lock_allowed=*/true) {} ScopedThreadJoinActivity::ScopedThreadJoinActivity( const void* program_counter, const base::PlatformThreadHandle* thread) : GlobalActivityTracker::ScopedThreadActivity( program_counter, nullptr, Activity::ACT_THREAD_JOIN, ActivityData::ForThread(*thread), /*lock_allowed=*/true) {} #if !defined(OS_NACL) && !defined(OS_IOS) ScopedProcessWaitActivity::ScopedProcessWaitActivity( const void* program_counter, const base::Process* process) : GlobalActivityTracker::ScopedThreadActivity( program_counter, nullptr, Activity::ACT_PROCESS_WAIT, ActivityData::ForProcess(process->Pid()), /*lock_allowed=*/true) {} #endif } // namespace debug } // namespace base
39.129508
80
0.69938
[ "object" ]
c72a2fc9eb72fc0f0a7f66072940f8ef7bc8a643
6,858
cpp
C++
tgmm-paper/src/cellDivisionDiscriminationWithTemporalWindow/matlabCode/cellDivAnnotatorGUI/readTGMM_XMLoutput/readTGMM_XMLoutput/readXMLmixtureGaussians.cpp
msphan/tgmm-docker
bc417f4199801df9386817eba467026167320127
[ "Apache-2.0" ]
null
null
null
tgmm-paper/src/cellDivisionDiscriminationWithTemporalWindow/matlabCode/cellDivAnnotatorGUI/readTGMM_XMLoutput/readTGMM_XMLoutput/readXMLmixtureGaussians.cpp
msphan/tgmm-docker
bc417f4199801df9386817eba467026167320127
[ "Apache-2.0" ]
null
null
null
tgmm-paper/src/cellDivisionDiscriminationWithTemporalWindow/matlabCode/cellDivAnnotatorGUI/readTGMM_XMLoutput/readTGMM_XMLoutput/readXMLmixtureGaussians.cpp
msphan/tgmm-docker
bc417f4199801df9386817eba467026167320127
[ "Apache-2.0" ]
null
null
null
//wrapper to readXMLGaussianMixtureModel #include "mex.h" #include <vector> #include <iostream> #include <fstream> #include <string> #include <map> #include "GaussianMixtureModel.h" #include "external/xmlParser2/svlStrUtils.h" #include "external/xmlParser2/xmlParser.h" using namespace std; void mexFunction(int nlhs, mxArray *plhs[],int nrhs, const mxArray *prhs[]) { char *input_buf; if (nrhs!=1 || nlhs>1) mexErrMsgTxt("The number of input and/or output arguments os wrong."); /* input must be a string */ if ( mxIsChar(prhs[0]) != 1) mexErrMsgTxt("Input must be a string."); /* copy the string data from prhs[0] into a C string input_ buf. */ input_buf = mxArrayToString(prhs[0]); //check if file exists ifstream inCheck(input_buf); if(!inCheck.is_open()) mexErrMsgTxt("Requested file does not exist"); inCheck.close(); mexPrintf("Reading initial solution from xml file %s\n",input_buf); XMLNode xMainNode=XMLNode::openFileHelper(input_buf,"document"); vector<GaussianMixtureModel*> stack; //read stack int n=xMainNode.nChildNode("GaussianMixtureModel"); for(int ii=0;ii<n;ii++) stack.push_back(new GaussianMixtureModel(xMainNode,ii)); mexPrintf("Read %d mixtures in XML file\n",(int)(stack.size())); //allocate memory and prepare struct to return const int nfields=18;//it has to match fieldnames const char *fieldnames[]={"m","id","dims","scale","nu","beta","alpha","W","nuPrior","betaPrior","alphaPrior","mPrior","WPrior","sigmaDistPrior","splitScore","lineage","parent","svIdx"}; /* pointers to field names */ /* create a Nx1 struct matrix for output */ plhs[0] = mxCreateStructMatrix(stack.size(), 1, nfields, fieldnames); const size_t vecSize=sizeof(double)*dimsImage; const size_t matrixSize=sizeof(double)*dimsImage*dimsImage; double *ptr; for(unsigned int ii=0;ii<stack.size();ii++) { GaussianMixtureModel *GM=stack[ii]; //set m mxArray *field_value_0=mxCreateDoubleMatrix(1,dimsImage,mxREAL); ptr=mxGetPr(field_value_0); //for(int jj=0;jj<dimsImage;jj++) ptr[jj]=GM->m_k(jj); memcpy(ptr,GM->m_k.data(),vecSize); mxSetFieldByNumber(plhs[0],ii,0,field_value_0);//field number is 0-indexed //set id mxArray *field_value_1=mxCreateDoubleMatrix(1,1,mxREAL); *mxGetPr(field_value_1) = GM->id; mxSetFieldByNumber(plhs[0],ii,1,field_value_1);//field number is 0-indexed //set dims mxArray *field_value_2=mxCreateDoubleMatrix(1,1,mxREAL); *mxGetPr(field_value_2) = dimsImage; mxSetFieldByNumber(plhs[0],ii,2,field_value_2);//field number is 0-indexed //set scale mxArray *field_value_3=mxCreateDoubleMatrix(1,dimsImage,mxREAL); ptr=mxGetPr(field_value_3); for(int jj=0;jj<dimsImage;jj++) ptr[jj]=GaussianMixtureModel::scale[jj]; mxSetFieldByNumber(plhs[0],ii,3,field_value_3);//field number is 0-indexed //set nu mxArray *field_value_4=mxCreateDoubleMatrix(1,1,mxREAL); *mxGetPr(field_value_4) = GM->nu_k; mxSetFieldByNumber(plhs[0],ii,4,field_value_4);//field number is 0-indexed //set beta mxArray *field_value_5=mxCreateDoubleMatrix(1,1,mxREAL); *mxGetPr(field_value_5) = GM->beta_k; mxSetFieldByNumber(plhs[0],ii,5,field_value_5);//field number is 0-indexed //set alpha mxArray *field_value_6=mxCreateDoubleMatrix(1,1,mxREAL); *mxGetPr(field_value_6) = GM->alpha_k; mxSetFieldByNumber(plhs[0],ii,6,field_value_6);//field number is 0-indexed //set W mxArray *field_value_7=mxCreateDoubleMatrix(dimsImage,dimsImage,mxREAL); ptr=mxGetPr(field_value_7); memcpy(ptr,GM->W_k.data(),matrixSize); mxSetFieldByNumber(plhs[0],ii,7,field_value_7);//field number is 0-indexed //set nuPrior mxArray *field_value_8=mxCreateDoubleMatrix(1,1,mxREAL); *mxGetPr(field_value_8) = GM->nu_o; mxSetFieldByNumber(plhs[0],ii,8,field_value_8);//field number is 0-indexed //set betaPrio mxArray *field_value_9=mxCreateDoubleMatrix(1,1,mxREAL); *mxGetPr(field_value_9) = GM->beta_o; mxSetFieldByNumber(plhs[0],ii,9,field_value_9);//field number is 0-indexed //set alphaPrior mxArray *field_value_10=mxCreateDoubleMatrix(1,1,mxREAL); *mxGetPr(field_value_10) = GM->alpha_o; mxSetFieldByNumber(plhs[0],ii,10,field_value_10);//field number is 0-indexed //set mPrior mxArray *field_value_11=mxCreateDoubleMatrix(1,dimsImage,mxREAL); ptr=mxGetPr(field_value_11); //for(int jj=0;jj<dimsImage;jj++) ptr[jj]=GM->m_o(jj); memcpy(ptr,GM->m_o.data(),vecSize); mxSetFieldByNumber(plhs[0],ii,11,field_value_11);//field number is 0-indexed //set WPrior mxArray *field_value_12=mxCreateDoubleMatrix(dimsImage,dimsImage,mxREAL); ptr=mxGetPr(field_value_12); memcpy(ptr,GM->W_o.data(),matrixSize); mxSetFieldByNumber(plhs[0],ii,12,field_value_12);//field number is 0-indexed //set sigma dist split score mxArray *field_value_13=mxCreateDoubleMatrix(1,1,mxREAL); *mxGetPr(field_value_13) = GM->sigmaDist_o; mxSetFieldByNumber(plhs[0],ii,13,field_value_13);//field number is 0-indexed //set split score mxArray *field_value_14=mxCreateDoubleMatrix(1,1,mxREAL); *mxGetPr(field_value_14) = GM->splitScore; mxSetFieldByNumber(plhs[0],ii,14,field_value_14);//field number is 0-indexed //set lineage mxArray *field_value_15=mxCreateDoubleMatrix(1,1,mxREAL); *mxGetPr(field_value_15) = GM->lineageId; mxSetFieldByNumber(plhs[0],ii,15,field_value_15);//field number is 0-indexed //set parent mxArray *field_value_16=mxCreateDoubleMatrix(1,1,mxREAL); *mxGetPr(field_value_16) = GM->parentId; mxSetFieldByNumber(plhs[0],ii,16,field_value_16);//field number is 0-indexed //set supervoxel idx mxArray *field_value_17=mxCreateDoubleMatrix(1,GM->supervoxelIdx.size(), mxREAL); ptr=mxGetPr(field_value_17); for(size_t aa = 0; aa < GM->supervoxelIdx.size(); aa++) ptr[aa] = GM->supervoxelIdx[aa]; mxSetFieldByNumber(plhs[0],ii,17,field_value_17);//field number is 0-indexed } //release memory mxFree(input_buf); for(int ii=0;ii<n;ii++) delete stack[ii]; stack.clear(); return; }
38.1
225
0.645523
[ "vector" ]
c73d1c0940577044be5f17430c9a60b70b41c675
21,628
hpp
C++
ThirdParty-mod/java2cpp/android/widget/TabHost.hpp
kakashidinho/HQEngine
8125b290afa7c62db6cc6eac14e964d8138c7fd0
[ "MIT" ]
1
2019-04-03T01:53:28.000Z
2019-04-03T01:53:28.000Z
ThirdParty-mod/java2cpp/android/widget/TabHost.hpp
kakashidinho/HQEngine
8125b290afa7c62db6cc6eac14e964d8138c7fd0
[ "MIT" ]
null
null
null
ThirdParty-mod/java2cpp/android/widget/TabHost.hpp
kakashidinho/HQEngine
8125b290afa7c62db6cc6eac14e964d8138c7fd0
[ "MIT" ]
null
null
null
/*================================================================================ code generated by: java2cpp author: Zoran Angelov, mailto://baldzar@gmail.com class: android.widget.TabHost ================================================================================*/ #ifndef J2CPP_INCLUDE_IMPLEMENTATION #ifndef J2CPP_ANDROID_WIDGET_TABHOST_HPP_DECL #define J2CPP_ANDROID_WIDGET_TABHOST_HPP_DECL namespace j2cpp { namespace java { namespace lang { class Object; } } } namespace j2cpp { namespace java { namespace lang { class CharSequence; } } } namespace j2cpp { namespace java { namespace lang { class String; } } } namespace j2cpp { namespace android { namespace app { class LocalActivityManager; } } } namespace j2cpp { namespace android { namespace graphics { namespace drawable { class Drawable; } } } } namespace j2cpp { namespace android { namespace content { class Intent; } } } namespace j2cpp { namespace android { namespace content { class Context; } } } namespace j2cpp { namespace android { namespace view { class View; } } } namespace j2cpp { namespace android { namespace view { namespace ViewTreeObserver_ { class OnTouchModeChangeListener; } } } } namespace j2cpp { namespace android { namespace view { class KeyEvent; } } } namespace j2cpp { namespace android { namespace widget { namespace TabHost_ { class TabContentFactory; } } } } namespace j2cpp { namespace android { namespace widget { namespace TabHost_ { class TabSpec; } } } } namespace j2cpp { namespace android { namespace widget { class TabWidget; } } } namespace j2cpp { namespace android { namespace widget { namespace TabHost_ { class OnTabChangeListener; } } } } namespace j2cpp { namespace android { namespace widget { class FrameLayout; } } } namespace j2cpp { namespace android { namespace util { class AttributeSet; } } } #include <android/app/LocalActivityManager.hpp> #include <android/content/Context.hpp> #include <android/content/Intent.hpp> #include <android/graphics/drawable/Drawable.hpp> #include <android/util/AttributeSet.hpp> #include <android/view/KeyEvent.hpp> #include <android/view/View.hpp> #include <android/view/ViewTreeObserver.hpp> #include <android/widget/FrameLayout.hpp> #include <android/widget/TabHost.hpp> #include <android/widget/TabWidget.hpp> #include <java/lang/CharSequence.hpp> #include <java/lang/Object.hpp> #include <java/lang/String.hpp> namespace j2cpp { namespace android { namespace widget { class TabHost; namespace TabHost_ { class TabContentFactory; class TabContentFactory : public object<TabContentFactory> { public: J2CPP_DECLARE_CLASS J2CPP_DECLARE_METHOD(0) explicit TabContentFactory(jobject jobj) : object<TabContentFactory>(jobj) { } operator local_ref<java::lang::Object>() const; local_ref< android::view::View > createTabContent(local_ref< java::lang::String > const&); }; //class TabContentFactory class TabSpec; class TabSpec : public object<TabSpec> { public: J2CPP_DECLARE_CLASS J2CPP_DECLARE_METHOD(0) J2CPP_DECLARE_METHOD(1) J2CPP_DECLARE_METHOD(2) J2CPP_DECLARE_METHOD(3) J2CPP_DECLARE_METHOD(4) J2CPP_DECLARE_METHOD(5) J2CPP_DECLARE_METHOD(6) J2CPP_DECLARE_METHOD(7) J2CPP_DECLARE_FIELD(0) explicit TabSpec(jobject jobj) : object<TabSpec>(jobj) { } operator local_ref<java::lang::Object>() const; local_ref< android::widget::TabHost_::TabSpec > setIndicator(local_ref< java::lang::CharSequence > const&); local_ref< android::widget::TabHost_::TabSpec > setIndicator(local_ref< java::lang::CharSequence > const&, local_ref< android::graphics::drawable::Drawable > const&); local_ref< android::widget::TabHost_::TabSpec > setIndicator(local_ref< android::view::View > const&); local_ref< android::widget::TabHost_::TabSpec > setContent(jint); local_ref< android::widget::TabHost_::TabSpec > setContent(local_ref< android::widget::TabHost_::TabContentFactory > const&); local_ref< android::widget::TabHost_::TabSpec > setContent(local_ref< android::content::Intent > const&); local_ref< java::lang::String > getTag(); }; //class TabSpec class OnTabChangeListener; class OnTabChangeListener : public object<OnTabChangeListener> { public: J2CPP_DECLARE_CLASS J2CPP_DECLARE_METHOD(0) explicit OnTabChangeListener(jobject jobj) : object<OnTabChangeListener>(jobj) { } operator local_ref<java::lang::Object>() const; void onTabChanged(local_ref< java::lang::String > const&); }; //class OnTabChangeListener } //namespace TabHost_ class TabHost : public object<TabHost> { public: J2CPP_DECLARE_CLASS J2CPP_DECLARE_METHOD(0) J2CPP_DECLARE_METHOD(1) J2CPP_DECLARE_METHOD(2) J2CPP_DECLARE_METHOD(3) J2CPP_DECLARE_METHOD(4) J2CPP_DECLARE_METHOD(5) J2CPP_DECLARE_METHOD(6) J2CPP_DECLARE_METHOD(7) J2CPP_DECLARE_METHOD(8) J2CPP_DECLARE_METHOD(9) J2CPP_DECLARE_METHOD(10) J2CPP_DECLARE_METHOD(11) J2CPP_DECLARE_METHOD(12) J2CPP_DECLARE_METHOD(13) J2CPP_DECLARE_METHOD(14) J2CPP_DECLARE_METHOD(15) J2CPP_DECLARE_METHOD(16) J2CPP_DECLARE_METHOD(17) J2CPP_DECLARE_METHOD(18) J2CPP_DECLARE_METHOD(19) J2CPP_DECLARE_METHOD(20) typedef TabHost_::TabContentFactory TabContentFactory; typedef TabHost_::TabSpec TabSpec; typedef TabHost_::OnTabChangeListener OnTabChangeListener; explicit TabHost(jobject jobj) : object<TabHost>(jobj) { } operator local_ref<android::widget::FrameLayout>() const; operator local_ref<android::view::ViewTreeObserver_::OnTouchModeChangeListener>() const; TabHost(local_ref< android::content::Context > const&); TabHost(local_ref< android::content::Context > const&, local_ref< android::util::AttributeSet > const&); local_ref< android::widget::TabHost_::TabSpec > newTabSpec(local_ref< java::lang::String > const&); void setup(); void setup(local_ref< android::app::LocalActivityManager > const&); void onTouchModeChanged(jboolean); void addTab(local_ref< android::widget::TabHost_::TabSpec > const&); void clearAllTabs(); local_ref< android::widget::TabWidget > getTabWidget(); jint getCurrentTab(); local_ref< java::lang::String > getCurrentTabTag(); local_ref< android::view::View > getCurrentTabView(); local_ref< android::view::View > getCurrentView(); void setCurrentTabByTag(local_ref< java::lang::String > const&); local_ref< android::widget::FrameLayout > getTabContentView(); jboolean dispatchKeyEvent(local_ref< android::view::KeyEvent > const&); void dispatchWindowFocusChanged(jboolean); void setCurrentTab(jint); void setOnTabChangedListener(local_ref< android::widget::TabHost_::OnTabChangeListener > const&); }; //class TabHost } //namespace widget } //namespace android } //namespace j2cpp #endif //J2CPP_ANDROID_WIDGET_TABHOST_HPP_DECL #else //J2CPP_INCLUDE_IMPLEMENTATION #ifndef J2CPP_ANDROID_WIDGET_TABHOST_HPP_IMPL #define J2CPP_ANDROID_WIDGET_TABHOST_HPP_IMPL namespace j2cpp { android::widget::TabHost_::TabContentFactory::operator local_ref<java::lang::Object>() const { return local_ref<java::lang::Object>(get_jobject()); } local_ref< android::view::View > android::widget::TabHost_::TabContentFactory::createTabContent(local_ref< java::lang::String > const &a0) { return call_method< android::widget::TabHost_::TabContentFactory::J2CPP_CLASS_NAME, android::widget::TabHost_::TabContentFactory::J2CPP_METHOD_NAME(0), android::widget::TabHost_::TabContentFactory::J2CPP_METHOD_SIGNATURE(0), local_ref< android::view::View > >(get_jobject(), a0); } J2CPP_DEFINE_CLASS(android::widget::TabHost_::TabContentFactory,"android/widget/TabHost$TabContentFactory") J2CPP_DEFINE_METHOD(android::widget::TabHost_::TabContentFactory,0,"createTabContent","(Ljava/lang/String;)Landroid/view/View;") android::widget::TabHost_::TabSpec::operator local_ref<java::lang::Object>() const { return local_ref<java::lang::Object>(get_jobject()); } local_ref< android::widget::TabHost_::TabSpec > android::widget::TabHost_::TabSpec::setIndicator(local_ref< java::lang::CharSequence > const &a0) { return call_method< android::widget::TabHost_::TabSpec::J2CPP_CLASS_NAME, android::widget::TabHost_::TabSpec::J2CPP_METHOD_NAME(1), android::widget::TabHost_::TabSpec::J2CPP_METHOD_SIGNATURE(1), local_ref< android::widget::TabHost_::TabSpec > >(get_jobject(), a0); } local_ref< android::widget::TabHost_::TabSpec > android::widget::TabHost_::TabSpec::setIndicator(local_ref< java::lang::CharSequence > const &a0, local_ref< android::graphics::drawable::Drawable > const &a1) { return call_method< android::widget::TabHost_::TabSpec::J2CPP_CLASS_NAME, android::widget::TabHost_::TabSpec::J2CPP_METHOD_NAME(2), android::widget::TabHost_::TabSpec::J2CPP_METHOD_SIGNATURE(2), local_ref< android::widget::TabHost_::TabSpec > >(get_jobject(), a0, a1); } local_ref< android::widget::TabHost_::TabSpec > android::widget::TabHost_::TabSpec::setIndicator(local_ref< android::view::View > const &a0) { return call_method< android::widget::TabHost_::TabSpec::J2CPP_CLASS_NAME, android::widget::TabHost_::TabSpec::J2CPP_METHOD_NAME(3), android::widget::TabHost_::TabSpec::J2CPP_METHOD_SIGNATURE(3), local_ref< android::widget::TabHost_::TabSpec > >(get_jobject(), a0); } local_ref< android::widget::TabHost_::TabSpec > android::widget::TabHost_::TabSpec::setContent(jint a0) { return call_method< android::widget::TabHost_::TabSpec::J2CPP_CLASS_NAME, android::widget::TabHost_::TabSpec::J2CPP_METHOD_NAME(4), android::widget::TabHost_::TabSpec::J2CPP_METHOD_SIGNATURE(4), local_ref< android::widget::TabHost_::TabSpec > >(get_jobject(), a0); } local_ref< android::widget::TabHost_::TabSpec > android::widget::TabHost_::TabSpec::setContent(local_ref< android::widget::TabHost_::TabContentFactory > const &a0) { return call_method< android::widget::TabHost_::TabSpec::J2CPP_CLASS_NAME, android::widget::TabHost_::TabSpec::J2CPP_METHOD_NAME(5), android::widget::TabHost_::TabSpec::J2CPP_METHOD_SIGNATURE(5), local_ref< android::widget::TabHost_::TabSpec > >(get_jobject(), a0); } local_ref< android::widget::TabHost_::TabSpec > android::widget::TabHost_::TabSpec::setContent(local_ref< android::content::Intent > const &a0) { return call_method< android::widget::TabHost_::TabSpec::J2CPP_CLASS_NAME, android::widget::TabHost_::TabSpec::J2CPP_METHOD_NAME(6), android::widget::TabHost_::TabSpec::J2CPP_METHOD_SIGNATURE(6), local_ref< android::widget::TabHost_::TabSpec > >(get_jobject(), a0); } local_ref< java::lang::String > android::widget::TabHost_::TabSpec::getTag() { return call_method< android::widget::TabHost_::TabSpec::J2CPP_CLASS_NAME, android::widget::TabHost_::TabSpec::J2CPP_METHOD_NAME(7), android::widget::TabHost_::TabSpec::J2CPP_METHOD_SIGNATURE(7), local_ref< java::lang::String > >(get_jobject()); } J2CPP_DEFINE_CLASS(android::widget::TabHost_::TabSpec,"android/widget/TabHost$TabSpec") J2CPP_DEFINE_METHOD(android::widget::TabHost_::TabSpec,0,"<init>","(Landroid/widget/TabHost;)V") J2CPP_DEFINE_METHOD(android::widget::TabHost_::TabSpec,1,"setIndicator","(Ljava/lang/CharSequence;)Landroid/widget/TabHost$TabSpec;") J2CPP_DEFINE_METHOD(android::widget::TabHost_::TabSpec,2,"setIndicator","(Ljava/lang/CharSequence;Landroid/graphics/drawable/Drawable;)Landroid/widget/TabHost$TabSpec;") J2CPP_DEFINE_METHOD(android::widget::TabHost_::TabSpec,3,"setIndicator","(Landroid/view/View;)Landroid/widget/TabHost$TabSpec;") J2CPP_DEFINE_METHOD(android::widget::TabHost_::TabSpec,4,"setContent","(I)Landroid/widget/TabHost$TabSpec;") J2CPP_DEFINE_METHOD(android::widget::TabHost_::TabSpec,5,"setContent","(Landroid/widget/TabHost$TabContentFactory;)Landroid/widget/TabHost$TabSpec;") J2CPP_DEFINE_METHOD(android::widget::TabHost_::TabSpec,6,"setContent","(Landroid/content/Intent;)Landroid/widget/TabHost$TabSpec;") J2CPP_DEFINE_METHOD(android::widget::TabHost_::TabSpec,7,"getTag","()Ljava/lang/String;") J2CPP_DEFINE_FIELD(android::widget::TabHost_::TabSpec,0,"this$0","Landroid/widget/TabHost;") android::widget::TabHost_::OnTabChangeListener::operator local_ref<java::lang::Object>() const { return local_ref<java::lang::Object>(get_jobject()); } void android::widget::TabHost_::OnTabChangeListener::onTabChanged(local_ref< java::lang::String > const &a0) { return call_method< android::widget::TabHost_::OnTabChangeListener::J2CPP_CLASS_NAME, android::widget::TabHost_::OnTabChangeListener::J2CPP_METHOD_NAME(0), android::widget::TabHost_::OnTabChangeListener::J2CPP_METHOD_SIGNATURE(0), void >(get_jobject(), a0); } J2CPP_DEFINE_CLASS(android::widget::TabHost_::OnTabChangeListener,"android/widget/TabHost$OnTabChangeListener") J2CPP_DEFINE_METHOD(android::widget::TabHost_::OnTabChangeListener,0,"onTabChanged","(Ljava/lang/String;)V") android::widget::TabHost::operator local_ref<android::widget::FrameLayout>() const { return local_ref<android::widget::FrameLayout>(get_jobject()); } android::widget::TabHost::operator local_ref<android::view::ViewTreeObserver_::OnTouchModeChangeListener>() const { return local_ref<android::view::ViewTreeObserver_::OnTouchModeChangeListener>(get_jobject()); } android::widget::TabHost::TabHost(local_ref< android::content::Context > const &a0) : object<android::widget::TabHost>( call_new_object< android::widget::TabHost::J2CPP_CLASS_NAME, android::widget::TabHost::J2CPP_METHOD_NAME(0), android::widget::TabHost::J2CPP_METHOD_SIGNATURE(0) >(a0) ) { } android::widget::TabHost::TabHost(local_ref< android::content::Context > const &a0, local_ref< android::util::AttributeSet > const &a1) : object<android::widget::TabHost>( call_new_object< android::widget::TabHost::J2CPP_CLASS_NAME, android::widget::TabHost::J2CPP_METHOD_NAME(1), android::widget::TabHost::J2CPP_METHOD_SIGNATURE(1) >(a0, a1) ) { } local_ref< android::widget::TabHost_::TabSpec > android::widget::TabHost::newTabSpec(local_ref< java::lang::String > const &a0) { return call_method< android::widget::TabHost::J2CPP_CLASS_NAME, android::widget::TabHost::J2CPP_METHOD_NAME(2), android::widget::TabHost::J2CPP_METHOD_SIGNATURE(2), local_ref< android::widget::TabHost_::TabSpec > >(get_jobject(), a0); } void android::widget::TabHost::setup() { return call_method< android::widget::TabHost::J2CPP_CLASS_NAME, android::widget::TabHost::J2CPP_METHOD_NAME(3), android::widget::TabHost::J2CPP_METHOD_SIGNATURE(3), void >(get_jobject()); } void android::widget::TabHost::setup(local_ref< android::app::LocalActivityManager > const &a0) { return call_method< android::widget::TabHost::J2CPP_CLASS_NAME, android::widget::TabHost::J2CPP_METHOD_NAME(4), android::widget::TabHost::J2CPP_METHOD_SIGNATURE(4), void >(get_jobject(), a0); } void android::widget::TabHost::onTouchModeChanged(jboolean a0) { return call_method< android::widget::TabHost::J2CPP_CLASS_NAME, android::widget::TabHost::J2CPP_METHOD_NAME(7), android::widget::TabHost::J2CPP_METHOD_SIGNATURE(7), void >(get_jobject(), a0); } void android::widget::TabHost::addTab(local_ref< android::widget::TabHost_::TabSpec > const &a0) { return call_method< android::widget::TabHost::J2CPP_CLASS_NAME, android::widget::TabHost::J2CPP_METHOD_NAME(8), android::widget::TabHost::J2CPP_METHOD_SIGNATURE(8), void >(get_jobject(), a0); } void android::widget::TabHost::clearAllTabs() { return call_method< android::widget::TabHost::J2CPP_CLASS_NAME, android::widget::TabHost::J2CPP_METHOD_NAME(9), android::widget::TabHost::J2CPP_METHOD_SIGNATURE(9), void >(get_jobject()); } local_ref< android::widget::TabWidget > android::widget::TabHost::getTabWidget() { return call_method< android::widget::TabHost::J2CPP_CLASS_NAME, android::widget::TabHost::J2CPP_METHOD_NAME(10), android::widget::TabHost::J2CPP_METHOD_SIGNATURE(10), local_ref< android::widget::TabWidget > >(get_jobject()); } jint android::widget::TabHost::getCurrentTab() { return call_method< android::widget::TabHost::J2CPP_CLASS_NAME, android::widget::TabHost::J2CPP_METHOD_NAME(11), android::widget::TabHost::J2CPP_METHOD_SIGNATURE(11), jint >(get_jobject()); } local_ref< java::lang::String > android::widget::TabHost::getCurrentTabTag() { return call_method< android::widget::TabHost::J2CPP_CLASS_NAME, android::widget::TabHost::J2CPP_METHOD_NAME(12), android::widget::TabHost::J2CPP_METHOD_SIGNATURE(12), local_ref< java::lang::String > >(get_jobject()); } local_ref< android::view::View > android::widget::TabHost::getCurrentTabView() { return call_method< android::widget::TabHost::J2CPP_CLASS_NAME, android::widget::TabHost::J2CPP_METHOD_NAME(13), android::widget::TabHost::J2CPP_METHOD_SIGNATURE(13), local_ref< android::view::View > >(get_jobject()); } local_ref< android::view::View > android::widget::TabHost::getCurrentView() { return call_method< android::widget::TabHost::J2CPP_CLASS_NAME, android::widget::TabHost::J2CPP_METHOD_NAME(14), android::widget::TabHost::J2CPP_METHOD_SIGNATURE(14), local_ref< android::view::View > >(get_jobject()); } void android::widget::TabHost::setCurrentTabByTag(local_ref< java::lang::String > const &a0) { return call_method< android::widget::TabHost::J2CPP_CLASS_NAME, android::widget::TabHost::J2CPP_METHOD_NAME(15), android::widget::TabHost::J2CPP_METHOD_SIGNATURE(15), void >(get_jobject(), a0); } local_ref< android::widget::FrameLayout > android::widget::TabHost::getTabContentView() { return call_method< android::widget::TabHost::J2CPP_CLASS_NAME, android::widget::TabHost::J2CPP_METHOD_NAME(16), android::widget::TabHost::J2CPP_METHOD_SIGNATURE(16), local_ref< android::widget::FrameLayout > >(get_jobject()); } jboolean android::widget::TabHost::dispatchKeyEvent(local_ref< android::view::KeyEvent > const &a0) { return call_method< android::widget::TabHost::J2CPP_CLASS_NAME, android::widget::TabHost::J2CPP_METHOD_NAME(17), android::widget::TabHost::J2CPP_METHOD_SIGNATURE(17), jboolean >(get_jobject(), a0); } void android::widget::TabHost::dispatchWindowFocusChanged(jboolean a0) { return call_method< android::widget::TabHost::J2CPP_CLASS_NAME, android::widget::TabHost::J2CPP_METHOD_NAME(18), android::widget::TabHost::J2CPP_METHOD_SIGNATURE(18), void >(get_jobject(), a0); } void android::widget::TabHost::setCurrentTab(jint a0) { return call_method< android::widget::TabHost::J2CPP_CLASS_NAME, android::widget::TabHost::J2CPP_METHOD_NAME(19), android::widget::TabHost::J2CPP_METHOD_SIGNATURE(19), void >(get_jobject(), a0); } void android::widget::TabHost::setOnTabChangedListener(local_ref< android::widget::TabHost_::OnTabChangeListener > const &a0) { return call_method< android::widget::TabHost::J2CPP_CLASS_NAME, android::widget::TabHost::J2CPP_METHOD_NAME(20), android::widget::TabHost::J2CPP_METHOD_SIGNATURE(20), void >(get_jobject(), a0); } J2CPP_DEFINE_CLASS(android::widget::TabHost,"android/widget/TabHost") J2CPP_DEFINE_METHOD(android::widget::TabHost,0,"<init>","(Landroid/content/Context;)V") J2CPP_DEFINE_METHOD(android::widget::TabHost,1,"<init>","(Landroid/content/Context;Landroid/util/AttributeSet;)V") J2CPP_DEFINE_METHOD(android::widget::TabHost,2,"newTabSpec","(Ljava/lang/String;)Landroid/widget/TabHost$TabSpec;") J2CPP_DEFINE_METHOD(android::widget::TabHost,3,"setup","()V") J2CPP_DEFINE_METHOD(android::widget::TabHost,4,"setup","(Landroid/app/LocalActivityManager;)V") J2CPP_DEFINE_METHOD(android::widget::TabHost,5,"onAttachedToWindow","()V") J2CPP_DEFINE_METHOD(android::widget::TabHost,6,"onDetachedFromWindow","()V") J2CPP_DEFINE_METHOD(android::widget::TabHost,7,"onTouchModeChanged","(Z)V") J2CPP_DEFINE_METHOD(android::widget::TabHost,8,"addTab","(Landroid/widget/TabHost$TabSpec;)V") J2CPP_DEFINE_METHOD(android::widget::TabHost,9,"clearAllTabs","()V") J2CPP_DEFINE_METHOD(android::widget::TabHost,10,"getTabWidget","()Landroid/widget/TabWidget;") J2CPP_DEFINE_METHOD(android::widget::TabHost,11,"getCurrentTab","()I") J2CPP_DEFINE_METHOD(android::widget::TabHost,12,"getCurrentTabTag","()Ljava/lang/String;") J2CPP_DEFINE_METHOD(android::widget::TabHost,13,"getCurrentTabView","()Landroid/view/View;") J2CPP_DEFINE_METHOD(android::widget::TabHost,14,"getCurrentView","()Landroid/view/View;") J2CPP_DEFINE_METHOD(android::widget::TabHost,15,"setCurrentTabByTag","(Ljava/lang/String;)V") J2CPP_DEFINE_METHOD(android::widget::TabHost,16,"getTabContentView","()Landroid/widget/FrameLayout;") J2CPP_DEFINE_METHOD(android::widget::TabHost,17,"dispatchKeyEvent","(Landroid/view/KeyEvent;)Z") J2CPP_DEFINE_METHOD(android::widget::TabHost,18,"dispatchWindowFocusChanged","(Z)V") J2CPP_DEFINE_METHOD(android::widget::TabHost,19,"setCurrentTab","(I)V") J2CPP_DEFINE_METHOD(android::widget::TabHost,20,"setOnTabChangedListener","(Landroid/widget/TabHost$OnTabChangeListener;)V") } //namespace j2cpp #endif //J2CPP_ANDROID_WIDGET_TABHOST_HPP_IMPL #endif //J2CPP_INCLUDE_IMPLEMENTATION
37.09777
208
0.734048
[ "object" ]
c73dae9cab8135665c46623c7806019eb978955e
4,066
cpp
C++
rtx/core/geometry/standard.cpp
musyoku/chainer-gqn-playground
657bb931d2c531ff8f078fcb1686bbf1999afa7f
[ "MIT" ]
28
2018-09-06T18:08:28.000Z
2021-12-19T13:30:41.000Z
rtx/core/geometry/standard.cpp
musyoku/chainer-gqn-playground
657bb931d2c531ff8f078fcb1686bbf1999afa7f
[ "MIT" ]
3
2019-03-01T02:50:15.000Z
2019-06-25T08:12:21.000Z
rtx/core/geometry/standard.cpp
musyoku/chainer-gqn-playground
657bb931d2c531ff8f078fcb1686bbf1999afa7f
[ "MIT" ]
8
2018-10-26T12:05:52.000Z
2019-09-04T05:14:24.000Z
#include "standard.h" #include "../header/enum.h" #include "../header/glm.h" #include <cassert> #include <cfloat> #include <iostream> namespace rtx { namespace py = pybind11; StandardGeometry::StandardGeometry() : Geometry() { } StandardGeometry::StandardGeometry( py::array_t<int, py::array::c_style> face_vertex_indeces, py::array_t<float, py::array::c_style> vertices) : Geometry() { init(face_vertex_indeces, vertices, BVH_DEFAULT_TRIANGLES_PER_NODE); } StandardGeometry::StandardGeometry( py::array_t<int, py::array::c_style> face_vertex_indeces, py::array_t<float, py::array::c_style> vertices, int bvh_max_triangles_per_node) : Geometry() { init(face_vertex_indeces, vertices, bvh_max_triangles_per_node); } void StandardGeometry::init( py::array_t<int, py::array::c_style> np_face_vertex_indeces, py::array_t<float, py::array::c_style> np_vertices, int bvh_max_triangles_per_node) { if (np_face_vertex_indeces.ndim() != 2) { throw std::runtime_error("(num_np_face_vertex_indeces.ndim() != 2) -> false"); } if (np_vertices.ndim() != 2) { throw std::runtime_error("(num_np_vertices.ndim() != 2) -> false"); } _bvh_max_triangles_per_node = bvh_max_triangles_per_node; int num_faces = np_face_vertex_indeces.shape(0); int num_vertices = np_vertices.shape(0); int ndim_vertex = np_vertices.shape(1); if (ndim_vertex != 3 && ndim_vertex != 4) { throw std::runtime_error("(ndim_vertex != 3 && ndim_vertex != 4) -> false"); } auto faces = np_face_vertex_indeces.mutable_unchecked<2>(); auto vertices = np_vertices.mutable_unchecked<2>(); for (int n = 0; n < num_faces; n++) { _face_vertex_indices_array.emplace_back(glm::vec3i(faces(n, 0), faces(n, 1), faces(n, 2))); } for (int n = 0; n < num_vertices; n++) { if (ndim_vertex == 3) { _vertex_array.emplace_back(glm::vec4f(vertices(n, 0), vertices(n, 1), vertices(n, 2), 1.0f)); } else { _vertex_array.emplace_back(glm::vec4f(vertices(n, 0), vertices(n, 1), vertices(n, 2), vertices(n, 3))); } } } void StandardGeometry::add_face(glm::vec3i face) { _face_vertex_indices_array.emplace_back(face); } void StandardGeometry::add_vertex(glm::vec3f vertex) { _vertex_array.emplace_back(glm::vec4f(vertex.x, vertex.y, vertex.z, 1.0f)); } void StandardGeometry::set_bvh_max_triangles_per_node(int bvh_max_triangles_per_node) { _bvh_max_triangles_per_node = bvh_max_triangles_per_node; } int StandardGeometry::type() const { return RTXGeometryTypeStandard; } int StandardGeometry::num_faces() const { return _face_vertex_indices_array.size(); } int StandardGeometry::num_vertices() const { return _vertex_array.size(); } void StandardGeometry::serialize_vertices(rtx::array<rtxVertex>& buffer, int array_offset) const { for (unsigned int j = 0; j < _vertex_array.size(); j++) { auto& vertex = _vertex_array[j]; buffer[j + array_offset] = { vertex.x, vertex.y, vertex.z, vertex.w }; } } void StandardGeometry::serialize_faces(rtx::array<rtxFaceVertexIndex>& buffer, int array_offset) const { for (unsigned int j = 0; j < _face_vertex_indices_array.size(); j++) { auto& face = _face_vertex_indices_array[j]; buffer[j + array_offset] = { face[0], face[1], face[2], -1 }; } } std::shared_ptr<Geometry> StandardGeometry::transoform(glm::mat4& transformation_matrix) const { auto geometry = std::make_shared<StandardGeometry>(); geometry->_bvh_max_triangles_per_node = _bvh_max_triangles_per_node; geometry->_face_vertex_indices_array = _face_vertex_indices_array; geometry->_vertex_array.resize(_vertex_array.size()); for (unsigned int index = 0; index < _vertex_array.size(); index++) { auto& vertex = _vertex_array[index]; geometry->_vertex_array.at(index) = transformation_matrix * vertex; } return geometry; } int StandardGeometry::bvh_max_triangles_per_node() const { return _bvh_max_triangles_per_node; } }
35.356522
115
0.697737
[ "geometry", "shape" ]