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
ad04bab2fe86591ffc2d59bf7eba46ea91de8ecb
1,859
cpp
C++
fetch_demos_common/src/grasp_suggestion_node.cpp
moriarty/fetch_demos
63ae8ac0050370f11dae7d50dbe2d1e52419b486
[ "Apache-2.0" ]
2
2020-08-16T08:55:30.000Z
2021-04-05T07:28:26.000Z
fetch_demos_common/src/grasp_suggestion_node.cpp
moriarty/fetch_demos
63ae8ac0050370f11dae7d50dbe2d1e52419b486
[ "Apache-2.0" ]
null
null
null
fetch_demos_common/src/grasp_suggestion_node.cpp
moriarty/fetch_demos
63ae8ac0050370f11dae7d50dbe2d1e52419b486
[ "Apache-2.0" ]
5
2019-03-29T17:13:03.000Z
2021-08-24T22:25:03.000Z
#include <vector> #include <ros/ros.h> #include <fetch_demos_common/grasp_suggestion_interface.h> #include <rail_manipulation_msgs/SegmentedObjectList.h> #include <rail_manipulation_msgs/SegmentedObject.h> class GraspSuggestionNode { public: GraspSuggestionNode(ros::NodeHandle &nh) { grasp_interface.reset(new fetch_demmos_common::GraspSuggestionInterface(nh)); obj_list.reset(new rail_manipulation_msgs::SegmentedObjectList); } rail_manipulation_msgs::SegmentedObjectList getObjectList() { *obj_list = grasp_interface->getObject(); return *obj_list; } void timerCallback(const ros::TimerEvent& event) { *obj_list = grasp_interface->getObject(); } private: boost::shared_ptr<fetch_demmos_common::GraspSuggestionInterface> grasp_interface; boost::shared_ptr<rail_manipulation_msgs::SegmentedObjectList> obj_list; }; int main(int argc, char** argv){ ros::init(argc, argv, "grasp_suggestion_node"); ros::NodeHandle nh("~"); GraspSuggestionNode grasp_suggestion_node(nh); rail_manipulation_msgs::SegmentedObjectList obj_list; ros::Publisher pub = nh.advertise<rail_manipulation_msgs::SegmentedObjectList> ("segment_obj", 5); // ros::Timer timer = nh.createTimer(ros::Duration(3.0), &GraspSuggestionNode::timerCallback, &grasp_suggestion_node); ros::Rate loop_rate(10); double old_time =ros::Time::now().toSec(); while(ros::ok()){ double new_time =ros::Time::now().toSec(); if(new_time - old_time > 5.0) { obj_list = grasp_suggestion_node.getObjectList(); old_time = new_time; } pub.publish(obj_list); // ros::spinOnce(); // loop_rate.sleep(); } ros::spin(); return 0; }
32.051724
122
0.663798
[ "vector" ]
ad12229694e6f2d299671b0c77bb4beffa8725b7
9,360
cpp
C++
demos/env/main.cpp
island-org/soloud
0b7ea3dbf0aaa1a2f1414920731add78d20b91a6
[ "Zlib" ]
1
2017-02-17T03:27:56.000Z
2017-02-17T03:27:56.000Z
demos/env/main.cpp
island-org/soloud
0b7ea3dbf0aaa1a2f1414920731add78d20b91a6
[ "Zlib" ]
null
null
null
demos/env/main.cpp
island-org/soloud
0b7ea3dbf0aaa1a2f1414920731add78d20b91a6
[ "Zlib" ]
null
null
null
/* SoLoud audio engine Copyright (c) 2013-2014 Jari Komppa This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include <stdlib.h> #if defined(_MSC_VER) #include "SDL.h" #else #include "SDL/SDL.h" #endif #include <math.h> #include <stdio.h> #include "soloud.h" #include "soloud_wav.h" #include "soloud_biquadresonantfilter.h" SoLoud::Soloud gSoloud; // SoLoud engine core SoLoud::BiquadResonantFilter gLPFilter; SoLoud::Wav gRain, gWind, gMusic; int gRainHandle, gWindHandle, gMusicHandle; SDL_Surface *screen; SDL_Surface *font; SDL_Surface *bg; SDL_Surface *walker; void putpixel(int x, int y, int color) { if (y < 0 || y > 255 || x < 0 || x > 400) return; unsigned int *ptr = (unsigned int*)screen->pixels; int lineoffset = y * (screen->pitch / 4); ptr[lineoffset + x] = color; } void mulpixel(int x, int y, int color) { if (y < 0 || y > 255 || x < 0 || x > 400) return; unsigned int *ptr = (unsigned int*)screen->pixels; int lineoffset = y * (screen->pitch / 4); ptr[lineoffset + x] &= color; } int drawchar(int ch, int x, int y) { int i, j, maxx = 0; for (i = 0; i < 16; i++) { for (j = 0; j < 16; j++) { if (((char*)font->pixels)[((ch-32)*16+i)*16+j]) { putpixel(x+j,y+i,0xff000000); if (j > maxx) maxx = j; } } } return maxx + 1; } void drawstring(char * s, int x, int y) { while (*s) { x += drawchar(*s, x, y); if (*s == 32) x += 3; s++; } } void drawwalker(int frame, int x, int y) { int ofs = frame * walker->w * 2 * walker->pitch / 4; int i, j; for (i = 0; i < walker->w*2; i++) { for (j = 0; j < walker->w; j++) { mulpixel(x+j,y+i,((int*)walker->pixels)[ofs + i * walker->pitch / 4 + j]); } } } void drawrect(int x, int y, int w, int h, int c) { int i, j; for (i = 0; i < w; i++) for (j = 0; j < h; j++) putpixel(i+x, j+y, c); } void render() { // Lock surface if needed if (SDL_MUSTLOCK(screen)) if (SDL_LockSurface(screen) < 0) return; // Ask SDL for the time in milliseconds int tick = SDL_GetTicks(); float p = (tick % 60000) / 60000.0f; //p = 0.4f; int ypos; int xpos; int dudey; #define SMOOTHSTEP(x) ((x) * (x) * (3 - 2 * (x))) if (p < 0.1f) { xpos = 0; ypos = 600-256; dudey= -8; } else if (p < 0.5f) { float v = (p - 0.1f) * 2.5f; v = SMOOTHSTEP(v); v = SMOOTHSTEP(v); v = SMOOTHSTEP(v); xpos = (int)floor(v * (800 - 400)); ypos = 600 - 256; dudey = (int)floor((1 - v) * -8); } else if (p < 0.9f) { float v = (p - 0.5f) * 2.5f; v = SMOOTHSTEP(v); v = SMOOTHSTEP(v); v = SMOOTHSTEP(v); xpos = 800 - 400; ypos = (int)floor((1 - v) * (600 - 256)); dudey = (int)floor(v * 90); } else { xpos = 800-400; ypos = 0; dudey = 90; } static int mode_a = 0; if (p < 0.35f) { if (mode_a != 0) gSoloud.fadeVolume(gRainHandle,1,0.2f); mode_a = 0; } else { if (mode_a != 1) gSoloud.fadeVolume(gRainHandle,0,0.2f); mode_a = 1; } static int mode_b = 0; if (p < 0.7f) { if (mode_b != 0) gSoloud.fadeVolume(gWindHandle,0,0.2f); mode_b = 0; } else if (p < 0.8f) { gSoloud.setVolume(gWindHandle,(p-0.7f)*10); mode_b = 1; } else { if (mode_b != 2) gSoloud.fadeVolume(gWindHandle,1,0.2f); mode_b = 2; } static int mode_c = 0; if (p < 0.2f) { if (mode_c != 0) gSoloud.fadeVolume(gMusicHandle, 0, 0.2f); mode_c = 0; } else if (p < 0.4f) { gSoloud.setVolume(gMusicHandle, (p-0.2f)*5); mode_c = 1; } else if (p < 0.5f) { if (mode_c != 2) gSoloud.fadeVolume(gMusicHandle, 1, 0.2f); mode_c = 2; } else if (p < 0.7f) { gSoloud.setVolume(gMusicHandle, 1 - (p - 0.5f) * 4.5f); mode_c = 3; } else { if (mode_c != 4) gSoloud.fadeVolume(gMusicHandle, 0.1f, 0.2f); mode_c = 4; } static int mode_d = 0; if (p < 0.25f) { if (mode_d != 0) { gSoloud.fadeFilterParameter(gMusicHandle, 0, SoLoud::BiquadResonantFilter::FREQUENCY, 200, 0.2f); gSoloud.fadeFilterParameter(gMusicHandle, 0, SoLoud::BiquadResonantFilter::WET, 1, 0.2f); } mode_d = 0; } else if (p < 0.35f) { if (mode_d != 1) { gSoloud.fadeFilterParameter(gMusicHandle, 0, SoLoud::BiquadResonantFilter::WET, 0.5f, 2.0f); } mode_d = 1; } else if (p < 0.55f) { if (mode_d != 2) { gSoloud.fadeFilterParameter(gMusicHandle, 0, SoLoud::BiquadResonantFilter::FREQUENCY, 2000, 1.0f); gSoloud.fadeFilterParameter(gMusicHandle, 0, SoLoud::BiquadResonantFilter::WET, 0, 1.0f); } mode_d = 2; } else { if (mode_d != 3) { gSoloud.fadeFilterParameter(gMusicHandle, 0, SoLoud::BiquadResonantFilter::FREQUENCY, 200, 0.3f); gSoloud.fadeFilterParameter(gMusicHandle, 0, SoLoud::BiquadResonantFilter::WET, 1, 0.3f); } mode_d = 3; } static int mode_e = 0; if (p < 0.2f) { if (mode_e != 0) gSoloud.fadePan(gMusicHandle, 1, 0.2f); mode_e = 0; } else if (p < 0.4f) { gSoloud.setPan(gMusicHandle, 1-((p-0.2f)*5)); mode_e = 1; } else { if (mode_e != 2) gSoloud.fadePan(gMusicHandle, 0, 0.2f); mode_e = 2; } int i, j; for (i = 0; i < 256; i++) for (j = 0; j < 400; j++) putpixel(j, i, *(((int*)bg->pixels)+j+xpos+(i+ypos)*bg->pitch/4)); drawwalker((tick >> 7) % ((tick >> 8) % 5 + 1), (400-32)/2 + 12, 256-32*2-32-dudey); if (p > 0.5f) { int w = (int)floor((p - 0.5f) * 600); if (w > 32) w = 32; drawrect((400-32)/2+12, 256-32*2-32-ypos+600-256, w/2, 64, 0xffffffff); drawrect((400-32)/2+12+32-(w/2), 256-32*2-32-ypos+600-256, w/2, 64, 0xffffffff); drawrect((400-32)/2+12+(w/2), 256-32*2-32-ypos+600-256, 1, 64, 0xffaaaaaa); drawrect((400-32)/2+12+32-(w/2), 256-32*2-32-ypos+600-256, 1, 64, 0xffaaaaaa); } char temp[256]; //sprintf(temp, "%3.8f", p); //drawstring(temp,0,0); drawrect(0, 0, 100, 12, 0xff808080); drawrect(0, 2, (int)floor(100 * p), 8, 0xffe0e0e0); sprintf(temp, "Rain volume: %3.3f", gSoloud.getVolume(gRainHandle)); drawstring(temp,0,20); sprintf(temp, "Music volume: %3.3f", gSoloud.getVolume(gMusicHandle)); drawstring(temp,0,40); sprintf(temp, "Wind volume: %3.3f", gSoloud.getVolume(gWindHandle)); drawstring(temp,0,60); sprintf(temp, "Music pan: %3.3f", gSoloud.getPan(gMusicHandle)); drawstring(temp,0,80); sprintf(temp, "Music filter wet: %3.3f", gSoloud.getFilterParameter(gMusicHandle,0,SoLoud::BiquadResonantFilter::WET)); drawstring(temp,0,100); sprintf(temp, "Music filter freq: %3.3f", gSoloud.getFilterParameter(gMusicHandle,0,SoLoud::BiquadResonantFilter::FREQUENCY)); drawstring(temp,0,120); // Unlock if needed if (SDL_MUSTLOCK(screen)) SDL_UnlockSurface(screen); // Tell SDL to update the whole screen SDL_UpdateRect(screen, 0, 0, 400, 256); } // Entry point int main(int argc, char *argv[]) { // Initialize SDL's subsystems - in this case, only video. if ( SDL_Init(SDL_INIT_VIDEO) < 0 ) { fprintf(stderr, "Unable to init SDL: %s\n", SDL_GetError()); exit(1); } gSoloud.init(); gSoloud.setGlobalVolume(0.75); gSoloud.setPostClipScaler(0.75); gRain.load("audio/rainy_ambience.ogg"); gRain.setLooping(1); gWind.load("audio/windy_ambience.ogg"); gWind.setLooping(1); gMusic.load("audio/tetsno.ogg"); gMusic.setLooping(1); gLPFilter.setParams(SoLoud::BiquadResonantFilter::LOWPASS,44100,100,10); gMusic.setFilter(0, &gLPFilter); gRainHandle = gSoloud.play(gRain,1); gWindHandle = gSoloud.play(gWind,0); gMusicHandle = gSoloud.play(gMusic,0); // Register SDL_Quit to be called at exit; makes sure things are // cleaned up when we quit. atexit(SDL_Quit); // Attempt to create a 640x480 window with 32bit pixels. screen = SDL_SetVideoMode(400, 256, 32, SDL_SWSURFACE); font = SDL_LoadBMP("graphics/font.bmp"); SDL_Surface *temp = SDL_LoadBMP("graphics/env_bg.bmp"); bg = SDL_DisplayFormat(temp); SDL_FreeSurface(temp); temp = SDL_LoadBMP("graphics/env_walker.bmp"); walker = SDL_DisplayFormat(temp); SDL_FreeSurface(temp); // If we fail, return error. if ( screen == NULL ) { fprintf(stderr, "Unable to set 640x480 video: %s\n", SDL_GetError()); exit(1); } SDL_EnableKeyRepeat(SDL_DEFAULT_REPEAT_DELAY, SDL_DEFAULT_REPEAT_INTERVAL); // Main loop: loop forever. while (1) { // Render stuff render(); // Poll for events, and handle the ones we care about. SDL_Event event; while (SDL_PollEvent(&event)) { switch (event.type) { case SDL_KEYUP: // If escape is pressed, return (and thus, quit) switch (event.key.keysym.sym) { case SDLK_ESCAPE: { gSoloud.deinit(); return 0; } break; } break; case SDL_QUIT: gSoloud.deinit(); return(0); } } } return 0; }
21.920375
127
0.633226
[ "render" ]
ad1659807af1af30dd8bbc4923421783d14a9247
261,566
cpp
C++
groups/bdl/bdlde/bdlde_utf8util.t.cpp
seanbaxter/bde-1
149176ebc2ae49c3b563895a7332fe638a760782
[ "Apache-2.0" ]
1
2020-03-17T21:11:48.000Z
2020-03-17T21:11:48.000Z
groups/bdl/bdlde/bdlde_utf8util.t.cpp
seanbaxter/bde-1
149176ebc2ae49c3b563895a7332fe638a760782
[ "Apache-2.0" ]
null
null
null
groups/bdl/bdlde/bdlde_utf8util.t.cpp
seanbaxter/bde-1
149176ebc2ae49c3b563895a7332fe638a760782
[ "Apache-2.0" ]
1
2020-09-15T14:29:35.000Z
2020-09-15T14:29:35.000Z
// bdlde_utf8util.t.cpp -*-C++-*- // ---------------------------------------------------------------------------- // NOTICE // // This component is not up to date with current BDE coding standards, and // should not be used as an example for new development. // ---------------------------------------------------------------------------- #include <bdlde_utf8util.h> #include <bdlb_random.h> #include <bslim_testutil.h> #include <bsls_review.h> #include <bsls_types.h> #include <bsl_algorithm.h> #include <bsl_climits.h> #include <bsl_cstdlib.h> #include <bsl_cstring.h> #include <bsl_iostream.h> #include <bsl_sstream.h> #include <bsl_string.h> #include <bsl_vector.h> using namespace BloombergLP; using bsl::cout; using bsl::cerr; using bsl::endl; using bsl::flush; using bsl::size_t; // Suppress some bde_verify warnings for this test driver. // BDE_VERIFY pragma: -IND01 // BDE_VERIFY pragma: -IND04 // BDE_VERIFY pragma: -SP01 // BDE_VERIFY pragma: -SP03 // BDE_VERIFY pragma: -TP21 //============================================================================= // TEST PLAN //----------------------------------------------------------------------------- // Overview // -------- // //: o Test cases 1-6 Test 'isValid', 'numCodePointsRaw', and //: 'numCodePointsIfValid'. //: o Regarding 'advanceRaw' and 'advanceIfValid' in cases 7-9: //: 1 Test that they correctly advance through a long string of multilingual //: prose. //: 2 Test that they correctly advance through all possible combinations of //: machine-generated correct UTF-8 input. //: 3 Test that 'advanceIfValid' works on all possible sequences of correct //: input followed by all possible types of incorrect input. //: o Test case 10 Test 'numBytesIfValid'. //: o Test case 11 Test 'getByteSize'. //: o Test case 12 Test 'appendUtf8Character'. //----------------------------------------------------------------------------- // CLASS METHODS // [12] int appendUtf8Character(bsl::string *, unsigned int); // [11] int getByteSize(const char *); // [10] IntPtr numBytesIfValid(const bslstl::StringRef&, IntPtr); // [ 8] int advanceIfValid(int *, const char **, const char *, int); // [ 8] int advanceIfValid(int *, const char **, const char *, int, int); // [ 8] int advanceRaw(const char **, const char *, int); // [ 8] int advanceRaw(const char **, const char *, int, int); // [ 7] int advanceIfValid(int *, const char **, const char *, int); prose // [ 7] int advanceIfValid(int*,const char**,const char *,int,int); prose // [ 7] int advanceRaw(const char **, const char *, int); prose // [ 7] int advanceRaw(const char **, const char *, int, int); prose // [ 6] bool isValid(const char *s); // [ 6] bool isValid(const char *s, int len); // [ 6] bool isValid(const char **err, const char *s); // [ 6] bool isValid(const char **err, const char *s, int len); // [ 6] int numCodePointsIfValid(**err, const char *s); // [ 6] int numCodePointsIfValid(**err, const char *s, int len); // [ 6] int numCharactersIfValid(**err, const char *s); // [ 6] int numCharactersIfValid(**err, const char *s, int len); // [ 5] int numCodePointsRaw(const char *s); // [ 5] int numCharacters(const char *s, int len); // [ 5] int numCharacters(const char *s); // [ 5] int numCharactersRaw(const char *s, int len); // [ 5] int numCharactersRaw(const char *s); // [ 5] int numCodePointsRaw(const char *s, int len); // [ 5] int numCodePoints(const char *s); // [ 5] int numCodePoints(const char *s, int len); // [ 4] bool isValid(const char *s); // [ 4] bool isValid(const char *s, int len); // [ 4] bool isValid(const char **err, const char *s); // [ 4] bool isValid(const char **err, const char *s, int len); // [ 3] bool isValid(const char *s); // [ 3] bool isValid(const char *s, int len); // [ 3] bool isValid(const char **err, const char *s); // [ 3] bool isValid(const char **err, const char *s, int len); //----------------------------------------------------------------------------- // [ 1] BREATHING TEST // [ 2] TABLE-DRIVEN ENCODING / DECODING / VALIDATION TEST // [13] USAGE EXAMPLE 1 // [14] USAGE EXAMPLE 2 // [ 9] 'advanceIfValid' on correct input followed by incorrect input // [-1] random number generator // [-2] 'utf8Encode', 'decode' // ============================================================================ // STANDARD BDE ASSERT TEST FUNCTION // ---------------------------------------------------------------------------- namespace { int testStatus = 0; void aSsErT(bool condition, const char *message, int line) { if (condition) { cout << "Error " __FILE__ "(" << line << "): " << message << " (failed)" << endl; if (0 <= testStatus && testStatus <= 100) { ++testStatus; } } } } // close unnamed namespace // ============================================================================ // STANDARD BDE TEST DRIVER MACRO ABBREVIATIONS // ---------------------------------------------------------------------------- #define ASSERT BSLIM_TESTUTIL_ASSERT #define ASSERTV BSLIM_TESTUTIL_ASSERTV #define LOOP_ASSERT BSLIM_TESTUTIL_LOOP_ASSERT #define LOOP0_ASSERT BSLIM_TESTUTIL_LOOP0_ASSERT #define LOOP1_ASSERT BSLIM_TESTUTIL_LOOP1_ASSERT #define LOOP2_ASSERT BSLIM_TESTUTIL_LOOP2_ASSERT #define LOOP3_ASSERT BSLIM_TESTUTIL_LOOP3_ASSERT #define LOOP4_ASSERT BSLIM_TESTUTIL_LOOP4_ASSERT #define LOOP5_ASSERT BSLIM_TESTUTIL_LOOP5_ASSERT #define LOOP6_ASSERT BSLIM_TESTUTIL_LOOP6_ASSERT #define Q BSLIM_TESTUTIL_Q // Quote identifier literally. #define P BSLIM_TESTUTIL_P // Print identifier and value. #define P_ BSLIM_TESTUTIL_P_ // P(X) without '\n'. #define T_ BSLIM_TESTUTIL_T_ // Print a tab (w/o newline). #define L_ BSLIM_TESTUTIL_L_ // current Line number // ============================================================================ // GLOBAL TYPEDEFS, CONSTANTS, ROUTINES & MACROS FOR TESTING // ---------------------------------------------------------------------------- typedef bdlde::Utf8Util Obj; static int verbose; static int veryVerbose; static int veryVeryVerbose; static int veryVeryVeryVerbose; static unsigned char utf8MultiLang[] = { 239, 187, 191, 'C', 'h', 'i', 'n', 'e', 's', 'e', ':', 13, 10, 13, 10, 228, 184, 173, 229, 141, 142, 228, 186, 186, 230, 176, 145, 229, 133, 177, 229, 146, 140, 229, 155, 189, 239, 188, 140, 233, 128, 154, 231, 167, 176, 228, 184, 173, 229, 155, 189, '[', 230, 179, 168, ' ', '3', ']', 239, 188, 140, 230, 152, 175, 228, 189, 141, 230, 150, 188, 228, 186, 154, 230, 180, 178, 230, 157, 177, 233, 131, 168, 227, 128, 129, 229, 164, 170, 229, 185, 179, 230, 180, 139, 232, 165, 191, 229, 178, 184, 231, 154, 132, 228, 184, 128, 228, 184, 170, 231, 164, 190, 228, 188, 154, 228, 184, 187, 228, 185, 137, 229, 155, 189, 229, 174, 182, 227, 128, 130, 233, 166, 150, 233, 131, 189, 231, 130, 186, 229, 140, 151, 228, 186, 172, 227, 128, 130, 229, 133, 182, 233, 153, 134, 229, 156, 176, 231, 150, 134, 229, 159, 159, 232, 136, 135, 229, 145, 168, 233, 130, 138, '1', '4', 229, 128, 139, 229, 156, 139, 229, 174, 182, 230, 142, 165, 229, 163, 164, 239, 188, 140, 233, 153, 134, 229, 156, 176, 229, 143, 138, 230, 185, 150, 230, 179, 138, 231, 154, 132, 230, 128, 187, 233, 157, 162, 231, 169, 141, 231, 186, 166, '9', '6', '0', 232, 144, 172, 229, 185, 179, 230, 150, 185, 229, 133, 172, 233, 135, 140, '[', '1', '1', ']', '[', '1', '2', ']', '[', '1', '3', ']', 239, 188, 140, 230, 152, 175, 229, 133, 168, 228, 184, 150, 231, 149, 140, 233, 153, 134, 229, 156, 176, 233, 157, 162, 231, 167, 175, 231, 172, 172, 228, 186, 140, 229, 164, 167, 231, 154, 132, 229, 155, 189, 229, 174, 182, 239, 188, 140, 230, 128, 187, 233, 157, 162, 231, 167, 175, 231, 172, 172, 228, 184, 137, 230, 136, 150, 231, 172, 172, 229, 155, 155, 229, 164, 167, 231, 154, 132, 229, 155, 189, 229, 174, 182, 227, 128, 130, 229, 133, 182, 228, 186, 186, 229, 143, 163, 232, 182, 133, 233, 129, 142, '1', '3', 229, 132, 132, 239, 188, 140, 231, 180, 132, 228, 189, 148, 229, 133, 168, 231, 144, 131, 228, 186, 186, 229, 143, 163, 231, 154, 132, 228, 186, 148, 229, 136, 134, 228, 185, 139, 228, 184, 128, 239, 188, 140, 230, 152, 175, 228, 184, 150, 231, 149, 140, 228, 184, 138, 228, 186, 186, 229, 143, 163, 230, 156, 128, 229, 164, 154, 231, 154, 132, 229, 156, 139, 229, 174, 182, 227, 128, 130, 13, 10, 13, 10, 228, 189, 156, 231, 130, 186, 231, 164, 190, 228, 188, 154, 228, 184, 187, 228, 185, 137, 229, 155, 189, 229, 174, 182, 239, 188, 140, 228, 184, 173, 232, 143, 175, 228, 186, 186, 230, 176, 145, 229, 133, 177, 229, 146, 140, 229, 156, 139, 228, 187, 165, 233, 169, 172, 229, 133, 139, 230, 128, 157, 229, 136, 151, 229, 174, 129, 228, 184, 187, 228, 185, 137, 231, 130, 186, 230, 132, 143, 232, 173, 152, 229, 189, 162, 230, 133, 139, 239, 188, 140, 228, 190, 157, 228, 184, 173, 229, 156, 139, 231, 137, 185, 232, 137, 178, 231, 164, 190, 230, 156, 131, 228, 184, 187, 231, 190, 169, 231, 144, 134, 232, 174, 186, 230, 140, 135, 229, 176, 142, 230, 148, 191, 228, 186, 139, 239, 188, 140, 229, 185, 182, 231, 148, 177, 230, 134, 178, 230, 179, 149, 230, 137, 128, 232, 179, 166, 228, 186, 136, 228, 184, 173, 229, 155, 189, 229, 133, 177, 228, 186, 167, 229, 133, 154, 229, 159, 183, 230, 148, 191, 239, 188, 140, 229, 174, 158, 232, 161, 140, 228, 184, 173, 229, 155, 189, 229, 133, 177, 228, 186, 167, 229, 133, 154, 233, 162, 134, 229, 175, 188, 231, 154, 132, 229, 164, 154, 229, 133, 154, 229, 144, 136, 228, 189, 156, 229, 146, 140, 230, 148, 191, 230, 178, 187, 229, 141, 143, 229, 149, 134, 229, 136, 182, 229, 186, 166, '[', '1', '4', ']', 227, 128, 130, '1', '9', '4', '9', 229, 185, 180, '1', '0', 230, 156, 136, '1', 230, 151, 165, 231, 154, 132, 229, 188, 128, 229, 155, 189, 229, 164, 167, 229, 133, 184, 228, 184, 173, 239, 188, 140, 228, 184, 173, 229, 141, 142, 228, 186, 186, 230, 176, 145, 229, 133, 177, 229, 146, 140, 229, 155, 189, 228, 184, 173, 229, 164, 174, 228, 186, 186, 230, 176, 145, 230, 148, 191, 229, 186, 156, 230, 173, 163, 229, 188, 143, 229, 174, 163, 229, 145, 138, 230, 136, 144, 231, 171, 139, '[', 230, 179, 168, ' ', '4', ']', 227, 128, 130, 229, 133, 168, 229, 156, 139, 229, 138, 131, 229, 136, 134, 231, 130, 186, '2', '3', 229, 128, 139, 231, 156, 129, 239, 188, 136, 229, 133, 182, 228, 184, 173, 229, 185, 182, 230, 178, 161, 230, 156, 137, 229, 175, 185, 229, 143, 176, 230, 185, 190, 231, 156, 129, 229, 133, 168, 233, 131, 168, 228, 184, 142, 231, 166, 143, 229, 187, 186, 231, 156, 129, 227, 128, 129, 230, 181, 183, 229, 141, 151, 231, 156, 129, 233, 131, 168, 229, 136, 134, 229, 156, 176, 229, 140, 186, 229, 174, 158, 233, 153, 133, 231, 174, 161, 232, 190, 150, 239, 188, 137, 227, 128, 129, '5', 229, 128, 139, 232, 135, 170, 230, 178, 187, 229, 141, 128, 227, 128, 129, '4', 229, 128, 139, 231, 155, 180, 232, 190, 150, 229, 184, 130, 229, 146, 140, '2', 229, 128, 139, 231, 137, 185, 229, 136, 165, 232, 161, 140, 230, 148, 191, 229, 140, 186, 239, 188, 136, 229, 141, 179, 233, 166, 153, 230, 184, 175, 232, 136, 135, 230, 190, 179, 233, 150, 128, 239, 188, 137, 239, 188, 140, 231, 156, 129, 231, 186, 167, 228, 186, 186, 230, 176, 145, 230, 148, 191, 229, 186, 156, 229, 143, 151, 229, 155, 189, 229, 138, 161, 233, 153, 162, 233, 162, 134, 229, 175, 188, 239, 188, 140, 231, 137, 185, 229, 136, 165, 232, 161, 140, 230, 148, 191, 229, 141, 128, 229, 137, 135, 230, 160, 185, 230, 147, 154, 228, 184, 128, 229, 156, 139, 229, 133, 169, 229, 136, 182, 230, 148, 191, 231, 173, 150, 229, 175, 166, 232, 161, 140, 233, 171, 152, 229, 186, 166, 232, 135, 170, 230, 178, 187, 227, 128, 130, 229, 133, 168, 229, 155, 189, 232, 183, 168, 232, 182, 138, 228, 186, 148, 228, 184, 170, 229, 156, 176, 231, 144, 134, 230, 151, 182, 229, 140, 186, 239, 188, 140, 228, 189, 134, 229, 157, 135, 228, 189, 191, 231, 148, 168, 228, 184, 173, 229, 156, 139, 230, 168, 153, 230, 186, 150, 230, 153, 130, 233, 150, 147, 239, 188, 136, 229, 141, 179, 'U', 'T', 'C', '+', '8', 239, 188, 137, 227, 128, 130, 13, 10, 13, 10, 228, 184, 173, 232, 143, 175, 228, 186, 186, 230, 176, 145, 229, 133, 177, 229, 146, 140, 229, 156, 139, 230, 152, 175, 229, 164, 154, 230, 176, 145, 230, 151, 143, 229, 155, 189, 229, 174, 182, 239, 188, 140, 229, 133, 182, 228, 184, 173, 230, 177, 137, 230, 151, 143, 228, 189, 148, 231, 184, 189, 228, 186, 186, 229, 143, 163, 231, 154, 132, '9', '1', '.', '5', '9', '%', 239, 188, 140, 229, 133, 182, 233, 164, 152, '5', '5', 228, 184, 170, 230, 176, 145, 230, 151, 143, 231, 130, 186, 229, 176, 145, 230, 149, 176, 230, 176, 145, 230, 151, 143, 239, 188, 140, 229, 155, 189, 229, 174, 182, 232, 170, 141, 229, 174, 154, 231, 154, 132, '5', '6', 229, 128, 139, 230, 176, 145, 230, 151, 143, 229, 144, 136, 231, 167, 176, 226, 128, 156, 228, 184, 173, 229, 141, 142, 230, 176, 145, 230, 151, 143, 226, 128, 157, 227, 128, 130, 228, 184, 173, 229, 141, 142, 228, 186, 186, 230, 176, 145, 229, 133, 177, 229, 146, 140, 229, 155, 189, 230, 156, 137, '2', '4', 231, 167, 141, 230, 176, 145, 230, 151, 143, 230, 150, 135, 229, 173, 151, 239, 188, 140, 229, 133, 171, 229, 141, 129, 229, 164, 154, 231, 167, 141, 230, 176, 145, 230, 151, 143, 232, 175, 173, 232, 168, 128, 227, 128, 130, 228, 184, 173, 229, 141, 142, 228, 186, 186, 230, 176, 145, 229, 133, 177, 229, 146, 140, 229, 155, 189, 230, 178, 161, 230, 156, 137, 230, 152, 142, 231, 161, 174, 232, 167, 132, 229, 174, 154, 231, 154, 132, 229, 155, 189, 229, 174, 182, 232, 175, 173, 232, 168, 128, 239, 188, 140, 228, 187, 165, 230, 177, 137, 232, 175, 173, 230, 153, 174, 233, 128, 154, 232, 175, 157, 229, 146, 140, 232, 167, 132, 232, 140, 131, 231, 174, 128, 229, 140, 150, 230, 177, 137, 229, 173, 151, 228, 184, 186, 226, 128, 156, 229, 155, 189, 229, 174, 182, 233, 128, 154, 231, 148, 168, 232, 175, 173, 232, 168, 128, 230, 150, 135, 229, 173, 151, 226, 128, 157, '[', 230, 179, 168, ' ', '5', ']', 227, 128, 130, 228, 184, 173, 229, 155, 189, 228, 188, 160, 231, 187, 159, 228, 184, 138, 230, 152, 175, 228, 187, 165, 231, 165, 150, 229, 133, 136, 228, 191, 161, 228, 187, 176, 228, 184, 186, 228, 184, 187, 231, 154, 132, 229, 155, 189, 229, 174, 182, 239, 188, 140, 229, 185, 182, 229, 133, 183, 230, 156, 137, 229, 132, 146, 233, 135, 138, 233, 129, 147, 228, 184, 137, 230, 149, 153, 229, 144, 136, 230, 181, 129, 231, 154, 132, 229, 174, 151, 230, 149, 153, 228, 191, 161, 228, 187, 176, 228, 188, 160, 231, 187, 159, 229, 146, 140, 231, 137, 185, 231, 130, 185, 239, 188, 140, 229, 144, 140, 230, 151, 182, 229, 173, 152, 229, 156, 168, 229, 133, 182, 229, 174, 131, 229, 164, 154, 231, 167, 141, 229, 174, 151, 230, 149, 153, 227, 128, 130, 228, 184, 173, 229, 141, 142, 228, 186, 186, 230, 176, 145, 229, 133, 177, 229, 146, 140, 229, 155, 189, 229, 144, 142, 239, 188, 140, 229, 174, 152, 230, 150, 185, 229, 165, 137, 232, 161, 140, 230, 151, 160, 231, 165, 158, 232, 174, 186, 239, 188, 140, 229, 133, 182, 229, 144, 142, 230, 155, 190, 229, 143, 145, 229, 138, 168, 231, 154, 132, 230, 150, 135, 229, 140, 150, 229, 164, 167, 233, 157, 169, 229, 145, 189, 229, 175, 185, 229, 144, 132, 231, 167, 141, 229, 174, 151, 230, 149, 153, 233, 128, 160, 230, 136, 144, 228, 184, 165, 233, 135, 141, 231, 160, 180, 229, 157, 143, 239, 188, 140, 231, 155, 180, 229, 136, 176, 230, 148, 185, 233, 157, 169, 229, 188, 128, 230, 148, 190, 229, 144, 142, 230, 137, 141, 230, 156, 137, 230, 137, 128, 232, 189, 172, 229, 143, 152, 227, 128, 130, 229, 189, 147, 228, 187, 138, 228, 184, 173, 229, 155, 189, 230, 148, 191, 229, 186, 156, 229, 175, 185, 229, 174, 151, 230, 149, 153, 228, 184, 142, 228, 188, 160, 231, 187, 159, 228, 186, 139, 231, 137, 169, 233, 135, 135, 229, 143, 150, 228, 191, 157, 230, 138, 164, 231, 154, 132, 230, 128, 129, 229, 186, 166, 227, 128, 130, 13, 10, 13, 10, 228, 184, 173, 229, 141, 142, 228, 186, 186, 230, 176, 145, 229, 133, 177, 229, 146, 140, 229, 155, 189, 230, 152, 175, 229, 155, 189, 233, 153, 133, 231, 164, 190, 228, 188, 154, 231, 154, 132, 233, 135, 141, 232, 166, 129, 228, 184, 128, 229, 145, 152, 239, 188, 140, 228, 185, 159, 230, 152, 175, 228, 188, 151, 229, 164, 154, 230, 173, 163, 229, 188, 143, 229, 146, 140, 233, 157, 158, 230, 173, 163, 229, 188, 143, 231, 154, 132, 229, 164, 154, 232, 190, 185, 231, 187, 132, 231, 187, 135, 231, 154, 132, 230, 136, 144, 229, 145, 152, 239, 188, 140, 229, 140, 133, 230, 139, 172, 232, 129, 148, 229, 144, 136, 229, 155, 189, 227, 128, 129, 228, 184, 150, 231, 149, 140, 232, 180, 184, 230, 152, 147, 231, 187, 132, 231, 187, 135, 227, 128, 129, 228, 186, 154, 229, 164, 170, 231, 187, 143, 229, 144, 136, 231, 187, 132, 231, 187, 135, 227, 128, 129, 233, 135, 145, 231, 160, 150, 229, 155, 155, 229, 155, 189, 227, 128, 129, 228, 184, 138, 230, 181, 183, 229, 144, 136, 228, 189, 156, 231, 187, 132, 231, 187, 135, 229, 146, 140, '2', '0', 229, 155, 189, 233, 155, 134, 229, 155, 162, 231, 173, 137, 239, 188, 140, 228, 184, 186, 232, 129, 148, 229, 144, 136, 229, 155, 189, 229, 174, 137, 229, 133, 168, 231, 144, 134, 228, 186, 139, 228, 188, 154, 229, 184, 184, 228, 187, 187, 231, 144, 134, 228, 186, 139, 229, 155, 189, 227, 128, 129, 228, 184, 150, 231, 149, 140, 231, 172, 172, 228, 186, 140, 229, 164, 167, 231, 187, 143, 230, 181, 142, 228, 189, 147, 239, 188, 140, 230, 152, 175, 228, 184, 150, 231, 149, 140, 231, 172, 172, 228, 184, 128, 229, 164, 167, 229, 135, 186, 229, 143, 163, 229, 156, 139, 227, 128, 129, 228, 184, 150, 231, 149, 140, 231, 172, 172, 228, 186, 140, 229, 164, 167, 233, 128, 178, 229, 143, 163, 229, 156, 139, 239, 188, 140, 230, 147, 129, 230, 156, 137, 230, 156, 128, 229, 164, 154, 231, 154, 132, 229, 164, 150, 230, 177, 135, 229, 132, 178, 229, 130, 153, 239, 188, 140, 230, 156, 128, 228, 184, 176, 229, 175, 140, 231, 154, 132, 228, 184, 150, 231, 149, 140, 230, 150, 135, 229, 140, 150, 233, 129, 151, 228, 186, 167, 239, 188, 140, 228, 186, 166, 230, 152, 175, 228, 184, 150, 231, 149, 140, 228, 184, 138, 231, 187, 143, 230, 181, 142, 230, 136, 144, 233, 149, 183, 230, 156, 128, 229, 191, 171, 231, 154, 132, 229, 156, 139, 229, 174, 182, 228, 185, 139, 228, 184, 128, 227, 128, 130, 229, 143, 166, 229, 164, 150, 239, 188, 140, 228, 184, 173, 229, 155, 189, 230, 139, 165, 230, 156, 137, 228, 184, 150, 231, 149, 140, 228, 184, 138, 231, 142, 176, 229, 189, 185, 229, 163, 171, 229, 133, 181, 230, 156, 128, 229, 164, 154, 231, 154, 132, 229, 134, 155, 233, 152, 159, 239, 188, 155, 229, 134, 155, 228, 186, 139, 229, 188, 128, 230, 148, 175, 228, 184, 150, 231, 149, 140, 231, 172, 172, 228, 186, 140, 239, 188, 140, 230, 139, 165, 230, 156, 137, 230, 160, 184, 230, 173, 166, 229, 153, 168, 239, 188, 140, 229, 185, 182, 229, 133, 183, 229, 164, 135, 229, 143, 145, 229, 176, 132, 229, 141, 171, 230, 152, 159, 227, 128, 129, 232, 175, 149, 233, 170, 140, 229, 158, 139, 231, 169, 186, 233, 151, 180, 231, 171, 153, 229, 146, 140, 230, 156, 136, 231, 144, 131, 229, 143, 138, 230, 183, 177, 231, 169, 186, 230, 142, 162, 230, 181, 139, 229, 153, 168, 231, 154, 132, 232, 131, 189, 229, 138, 155, 239, 188, 155, '2', '0', '0', '3', 229, 185, 180, 239, 188, 140, 228, 184, 173, 229, 155, 189, 230, 136, 144, 228, 184, 186, 228, 184, 150, 231, 149, 140, 231, 172, 172, 228, 184, 137, 228, 184, 170, 232, 135, 170, 228, 184, 187, 230, 136, 144, 229, 138, 159, 229, 143, 145, 229, 176, 132, 232, 189, 189, 228, 186, 186, 232, 136, 170, 229, 164, 169, 229, 153, 168, 231, 154, 132, 229, 155, 189, 229, 174, 182, 227, 128, 130, 228, 184, 173, 229, 155, 189, 228, 186, 166, 230, 152, 175, 230, 189, 156, 229, 156, 168, 232, 182, 133, 231, 186, 167, 229, 164, 167, 229, 155, 189, 228, 185, 139, 228, 184, 128, 239, 188, 140, 232, 162, 171, 232, 174, 164, 228, 184, 186, 230, 152, 175, 228, 184, 139, 228, 184, 128, 228, 189, 141, 232, 182, 133, 231, 186, 167, 229, 164, 167, 229, 155, 189, 231, 154, 132, 230, 156, 137, 229, 138, 155, 229, 128, 153, 233, 128, 137, 228, 186, 186, 227, 128, 130, 13, 10, 13, 10, 228, 184, 173, 229, 141, 142, 228, 186, 186, 230, 176, 145, 229, 133, 177, 229, 146, 140, 229, 155, 189, 231, 154, 132, 230, 173, 163, 229, 188, 143, 229, 155, 189, 229, 144, 141, 228, 186, 142, '1', '9', '4', '9', 229, 185, 180, 231, 148, 177, 228, 184, 173, 229, 156, 139, 228, 186, 186, 230, 176, 145, 230, 148, 191, 230, 178, 187, 229, 141, 148, 229, 149, 134, 230, 156, 131, 232, 173, 176, 231, 177, 140, 229, 130, 153, 230, 156, 131, 232, 173, 176, 231, 162, 186, 229, 174, 154, 239, 188, 140, 229, 189, 147, 229, 136, 157, 230, 155, 190, 229, 138, 160, 232, 168, 187, 227, 128, 140, 231, 176, 161, 231, 168, 177, 239, 188, 154, 228, 184, 173, 232, 143, 175, 230, 176, 145, 229, 156, 139, 227, 128, 141, 239, 188, 140, 228, 189, 134, 229, 143, 184, 229, 190, 146, 231, 190, 142, 229, 160, 130, 231, 173, 137, 230, 176, 145, 228, 184, 187, 229, 133, 154, 230, 180, 190, 228, 186, 186, 229, 163, 171, 232, 174, 164, 228, 184, 186, 230, 150, 176, 228, 184, 173, 229, 155, 189, 229, 186, 148, 231, 161, 174, 231, 171, 139, 230, 150, 176, 229, 155, 189, 229, 144, 141, 239, 188, 140, 228, 187, 165, 231, 164, 186, 228, 184, 164, 230, 172, 161, 233, 157, 169, 229, 145, 189, 231, 154, 132, 230, 160, 185, 230, 156, 172, 230, 132, 143, 228, 185, 137, 228, 184, 141, 229, 144, 140, '[', '1', '5', ']', 227, 128, 130, 229, 155, 160, 230, 173, 164, 231, 155, 180, 232, 135, 179, '9', 230, 156, 136, '2', '7', 230, 151, 165, 230, 148, 191, 229, 141, 148, 229, 133, 168, 233, 171, 148, 230, 156, 131, 232, 173, 176, 232, 161, 168, 230, 177, 186, 233, 128, 154, 233, 129, 142, 228, 184, 173, 229, 164, 174, 228, 186, 186, 230, 176, 145, 230, 148, 191, 229, 186, 156, 231, 181, 132, 231, 185, 148, 230, 179, 149, 230, 153, 130, 239, 188, 140, 230, 173, 163, 229, 188, 143, 232, 173, 176, 230, 177, 186, 229, 142, 187, 233, 153, 164, 230, 173, 164, 229, 138, 160, 232, 168, 187, '[', '1', '6', ']', 227, 128, 130, 13, 10, 13, 10, 229, 156, 168, 229, 133, 168, 233, 131, 168, 229, 156, 139, 233, 154, 155, 229, 160, 180, 229, 144, 136, 239, 188, 140, 228, 184, 173, 232, 143, 175, 228, 186, 186, 230, 176, 145, 229, 133, 177, 229, 146, 140, 229, 156, 139, 228, 184, 128, 232, 136, 172, 231, 176, 161, 231, 168, 177, 231, 130, 186, 228, 184, 173, 229, 156, 139, 239, 188, 140, 230, 156, 137, 230, 151, 182, 229, 128, 153, 228, 185, 159, 229, 155, 160, 229, 133, 182, 230, 137, 128, 229, 164, 132, 229, 156, 176, 231, 144, 134, 228, 189, 141, 231, 189, 174, 232, 128, 140, 232, 162, 171, 231, 167, 176, 228, 184, 186, 228, 184, 173, 229, 155, 189, 229, 164, 167, 233, 153, 134, 227, 128, 130, 229, 156, 168, 228, 184, 173, 229, 156, 139, 229, 156, 139, 229, 133, 167, 239, 188, 140, 231, 149, 182, '1', '9', '4', '9', 229, 185, 180, 229, 137, 141, 231, 154, 132, 228, 184, 173, 232, 143, 175, 230, 176, 145, 229, 156, 139, 232, 136, 135, '1', '9', '4', '9', 229, 185, 180, 229, 190, 140, 231, 154, 132, 228, 184, 173, 232, 143, 175, 228, 186, 186, 230, 176, 145, 229, 133, 177, 229, 146, 140, 229, 156, 139, 229, 129, 154, 229, 176, 141, 230, 175, 148, 230, 136, 150, 230, 156, 137, 230, 173, 164, 230, 182, 181, 230, 140, 135, 230, 153, 130, 239, 188, 140, 229, 137, 141, 232, 128, 133, 229, 184, 184, 232, 162, 171, 231, 168, 177, 231, 130, 186, 232, 136, 138, 228, 184, 173, 229, 156, 139, 239, 188, 136, 228, 186, 166, 231, 168, 177, 232, 136, 138, 231, 164, 190, 230, 156, 131, 239, 188, 137, 239, 188, 140, 232, 128, 140, 229, 190, 140, 232, 128, 133, 229, 137, 135, 229, 184, 184, 232, 162, 171, 231, 168, 177, 231, 130, 186, 230, 150, 176, 228, 184, 173, 229, 156, 139, 227, 128, 130, 231, 155, 174, 229, 137, 141, 239, 188, 140, 228, 184, 173, 232, 143, 175, 228, 186, 186, 230, 176, 145, 229, 133, 177, 229, 146, 140, 229, 156, 139, 232, 170, 141, 231, 130, 186, 228, 184, 173, 232, 143, 175, 230, 176, 145, 229, 156, 139, 229, 183, 178, 232, 162, 171, 229, 133, 182, 229, 143, 150, 228, 187, 163, 239, 188, 140, 228, 184, 173, 232, 143, 175, 230, 176, 145, 229, 156, 139, 230, 148, 191, 229, 186, 156, 229, 137, 135, 228, 184, 141, 230, 137, 191, 232, 170, 141, 228, 184, 173, 232, 143, 175, 228, 186, 186, 230, 176, 145, 229, 133, 177, 229, 146, 140, 229, 156, 139, 231, 154, 132, 230, 173, 163, 231, 181, 177, 230, 128, 167, 239, 188, 140, 231, 149, 182, 229, 156, 168, 228, 184, 173, 229, 156, 139, 229, 164, 167, 233, 153, 184, 231, 154, 132, 228, 184, 173, 232, 143, 175, 228, 186, 186, 230, 176, 145, 229, 133, 177, 229, 146, 140, 229, 156, 139, 230, 148, 191, 229, 186, 156, 232, 136, 135, 229, 156, 168, 229, 143, 176, 231, 129, 163, 231, 154, 132, 228, 184, 173, 232, 143, 175, 230, 176, 145, 229, 156, 139, 230, 148, 191, 229, 186, 156, 229, 129, 154, 229, 176, 141, 230, 175, 148, 230, 136, 150, 230, 156, 137, 230, 173, 164, 230, 182, 181, 230, 140, 135, 230, 153, 130, 239, 188, 140, 229, 137, 141, 232, 128, 133, 229, 184, 184, 232, 162, 171, 229, 190, 140, 232, 128, 133, 231, 168, 177, 231, 130, 186, 229, 140, 151, 228, 186, 172, 231, 149, 182, 229, 177, 128, 227, 128, 129, 229, 164, 167, 233, 153, 184, 231, 149, 182, 229, 177, 128, 227, 128, 129, 228, 184, 173, 229, 133, 177, 231, 149, 182, 229, 177, 128, 227, 128, 129, 228, 184, 173, 229, 156, 139, 229, 164, 167, 233, 153, 184, 230, 136, 150, 229, 164, 167, 233, 153, 184, '[', '1', '7', ']', 239, 188, 140, 229, 190, 140, 232, 128, 133, 229, 184, 184, 232, 162, 171, 229, 137, 141, 232, 128, 133, 231, 168, 177, 231, 130, 186, 229, 143, 176, 231, 129, 163, 231, 149, 182, 229, 177, 128, 227, 128, 129, 229, 143, 176, 229, 140, 151, 231, 149, 182, 229, 177, 128, 230, 136, 150, 229, 143, 176, 231, 129, 163, '[', '1', '8', ']', 227, 128, 130, 232, 136, 135, 230, 184, 175, 230, 190, 179, 229, 156, 176, 229, 141, 128, 228, 184, 166, 231, 148, 168, 230, 153, 130, 229, 137, 135, 231, 168, 177, 231, 130, 186, 228, 184, 173, 229, 156, 139, 229, 133, 167, 229, 156, 176, 227, 128, 129, 229, 133, 167, 229, 156, 176, '[', '1', '9', ']', 227, 128, 130, 13, 10, 13, 10, 231, 149, 182, 228, 184, 173, 229, 156, 139, 229, 164, 167, 233, 153, 184, 231, 154, 132, 228, 184, 173, 232, 143, 175, 228, 186, 186, 230, 176, 145, 229, 133, 177, 229, 146, 140, 229, 156, 139, 230, 148, 191, 229, 186, 156, 232, 136, 135, 229, 156, 168, 229, 143, 176, 231, 129, 163, 231, 154, 132, 228, 184, 173, 232, 143, 175, 230, 176, 145, 229, 156, 139, 230, 148, 191, 229, 186, 156, 229, 129, 154, 229, 176, 141, 230, 175, 148, 230, 136, 150, 229, 141, 128, 233, 154, 148, 228, 187, 139, 231, 180, 185, 230, 153, 130, 239, 188, 140, 233, 128, 154, 229, 184, 184, 230, 142, 161, 231, 148, 168, 229, 156, 176, 231, 144, 134, 229, 144, 141, 232, 169, 158, 227, 128, 140, 228, 184, 173, 229, 156, 139, 229, 164, 167, 233, 153, 184, 227, 128, 141, 239, 188, 136, 'C', 'h', 'i', 'n', 'a', ' ', 'M', 'a', 'i', 'n', 'l', 'a', 'n', 'd', 239, 188, 137, 230, 136, 150, 228, 184, 173, 229, 155, 189, 239, 188, 136, 'C', 'h', 'i', 'n', 'a', 239, 188, 137, 229, 129, 154, 231, 130, 186, 228, 184, 173, 232, 143, 175, 228, 186, 186, 230, 176, 145, 229, 133, 177, 229, 146, 140, 229, 156, 139, 231, 154, 132, 231, 176, 161, 231, 168, 177, 239, 188, 140, 229, 176, 141, 230, 150, 188, 228, 184, 173, 232, 143, 175, 230, 176, 145, 229, 156, 139, 229, 137, 135, 231, 176, 161, 231, 168, 177, 231, 130, 186, 228, 184, 173, 232, 143, 175, 229, 143, 176, 229, 140, 151, 239, 188, 136, 'C', 'h', 'i', 'n', 'e', 's', 'e', ' ', 'T', 'a', 'i', 'p', 'e', 'i', 239, 188, 137, 230, 136, 150, 229, 143, 176, 231, 129, 163, 239, 188, 136, 'T', 'a', 'i', 'w', 'a', 'n', 239, 188, 137, 227, 128, 130, 232, 128, 140, 229, 143, 176, 230, 185, 190, 231, 154, 132, 229, 170, 146, 228, 189, 147, 229, 137, 135, 229, 184, 184, 228, 189, 191, 231, 148, 168, 227, 128, 140, 228, 184, 173, 229, 133, 177, 227, 128, 141, 227, 128, 129, 227, 128, 140, 229, 164, 167, 233, 153, 184, 229, 156, 176, 229, 141, 128, 227, 128, 141, 227, 128, 129, 227, 128, 140, 229, 164, 167, 233, 153, 184, 227, 128, 141, 230, 136, 150, 227, 128, 140, 228, 184, 173, 229, 155, 189, 227, 128, 141, 230, 157, 165, 228, 189, 156, 231, 130, 186, 228, 184, 173, 232, 143, 175, 228, 186, 186, 230, 176, 145, 229, 133, 177, 229, 146, 140, 229, 156, 139, 231, 154, 132, 231, 176, 161, 231, 168, 177, 227, 128, 130, 233, 166, 153, 230, 184, 175, 233, 131, 168, 229, 136, 134, 229, 170, 146, 233, 171, 148, 228, 185, 159, 230, 156, 137, 228, 189, 191, 231, 148, 168, 227, 128, 140, 228, 184, 173, 229, 156, 139, 227, 128, 141, 229, 146, 140, 227, 128, 140, 228, 184, 173, 229, 133, 177, 227, 128, 141, 228, 190, 134, 230, 140, 135, 228, 187, 163, 228, 184, 173, 229, 156, 139, 229, 164, 167, 233, 153, 184, 227, 128, 130, 13, 10, 13, 10, '1', '9', '4', '9', 229, 185, 180, 239, 188, 140, 230, 173, 183, 230, 153, 130, 228, 184, 137, 229, 185, 180, 231, 154, 132, 229, 156, 139, 229, 133, 177, 229, 133, 167, 230, 136, 176, 228, 184, 187, 232, 166, 129, 230, 136, 176, 229, 189, 185, 231, 181, 144, 230, 157, 159, 239, 188, 140, 228, 184, 173, 229, 156, 139, 229, 133, 177, 231, 148, 162, 233, 187, 168, 230, 137, 128, 233, 160, 152, 229, 176, 142, 231, 154, 132, 228, 184, 173, 229, 156, 139, 228, 186, 186, 230, 176, 145, 232, 167, 163, 230, 148, 190, 232, 187, 141, 230, 136, 176, 229, 139, 157, 228, 186, 134, 228, 184, 173, 229, 156, 139, 229, 156, 139, 230, 176, 145, 233, 187, 168, 230, 137, 128, 233, 160, 152, 229, 176, 142, 231, 154, 132, 228, 184, 173, 232, 143, 175, 230, 176, 145, 229, 156, 139, 229, 155, 189, 232, 187, 141, '[', 230, 179, 168, ' ', '6', ']', 239, 188, 140, 228, 184, 166, 229, 183, 178, 233, 128, 144, 230, 188, 184, 230, 142, 167, 229, 136, 182, 228, 186, 134, 228, 184, 173, 229, 156, 139, 229, 164, 167, 233, 153, 184, 229, 164, 167, 233, 131, 168, 229, 136, 134, 231, 156, 129, 228, 187, 189, 229, 146, 140, 229, 156, 176, 229, 140, 186, 227, 128, 130, 13, 10, 13, 10, 229, 144, 140, 229, 185, 180, '9', 230, 156, 136, '2', '1', 230, 151, 165, 232, 135, 179, '9', 230, 156, 136, '3', '0', 230, 151, 165, 239, 188, 140, 231, 182, 147, 233, 129, 142, 230, 149, 184, 230, 156, 136, 231, 154, 132, 231, 177, 140, 229, 130, 153, 239, 188, 140, 228, 184, 173, 229, 156, 139, 228, 186, 186, 230, 176, 145, 230, 148, 191, 230, 178, 187, 229, 141, 148, 229, 149, 134, 230, 156, 131, 232, 173, 176, 231, 172, 172, 228, 184, 128, 229, 177, 134, 229, 133, 168, 233, 171, 148, 230, 156, 131, 232, 173, 176, 229, 156, 168, 229, 140, 151, 229, 185, 179, 229, 143, 172, 233, 150, 139, 227, 128, 130, '9', 230, 156, 136, '2', '1', 230, 151, 165, 239, 188, 140, 228, 184, 173, 229, 156, 139, 228, 186, 186, 230, 176, 145, 230, 148, 191, 230, 178, 187, 229, 141, 148, 229, 149, 134, 230, 156, 131, 232, 173, 176, 231, 172, 172, 228, 184, 128, 229, 177, 134, 229, 133, 168, 233, 171, 148, 230, 156, 131, 232, 173, 176, 230, 173, 163, 229, 188, 143, 229, 174, 163, 229, 184, 131, 230, 136, 144, 231, 171, 139, 228, 184, 173, 229, 141, 142, 228, 186, 186, 230, 176, 145, 229, 133, 177, 229, 146, 140, 229, 155, 189, '[', '2', '0', ']', 227, 128, 130, 228, 188, 154, 232, 174, 174, 233, 128, 154, 233, 129, 142, 228, 186, 134, 227, 128, 138, 228, 184, 173, 229, 156, 139, 228, 186, 186, 230, 176, 145, 230, 148, 191, 230, 178, 187, 229, 141, 148, 229, 149, 134, 230, 156, 131, 232, 173, 176, 231, 181, 132, 231, 185, 148, 230, 179, 149, 227, 128, 139, 227, 128, 129, 227, 128, 138, 228, 184, 173, 232, 143, 175, 228, 186, 186, 230, 176, 145, 229, 133, 177, 229, 146, 140, 229, 156, 139, 228, 184, 173, 229, 164, 174, 228, 186, 186, 230, 176, 145, 230, 148, 191, 229, 186, 156, 231, 181, 132, 231, 185, 148, 230, 179, 149, 227, 128, 139, 229, 146, 140, 229, 133, 183, 230, 156, 137, 232, 135, 168, 230, 153, 130, 230, 134, 178, 230, 179, 149, 230, 128, 167, 232, 179, 170, 231, 154, 132, 227, 128, 138, 228, 184, 173, 229, 156, 139, 228, 186, 186, 230, 176, 145, 230, 148, 191, 230, 178, 187, 229, 141, 148, 229, 149, 134, 230, 156, 131, 232, 173, 176, 229, 133, 177, 229, 144, 140, 231, 182, 177, 233, 160, 152, 227, 128, 139, 239, 188, 140, 230, 177, 186, 229, 174, 154, 228, 187, 165, 229, 140, 151, 229, 185, 179, 231, 130, 186, 233, 166, 150, 233, 131, 189, 228, 184, 166, 230, 148, 185, 229, 144, 141, 231, 136, 178, 229, 140, 151, 228, 186, 172, 227, 128, 129, 228, 187, 165, 229, 133, 172, 229, 133, 131, 231, 180, 128, 229, 185, 180, 227, 128, 129, 228, 187, 165, 231, 190, 169, 229, 139, 135, 232, 187, 141, 233, 128, 178, 232, 161, 140, 230, 155, 178, 231, 130, 186, 228, 187, 163, 229, 156, 139, 230, 173, 140, 227, 128, 129, 228, 187, 165, 228, 186, 148, 230, 152, 159, 231, 180, 133, 230, 151, 151, 231, 130, 186, 229, 156, 139, 230, 151, 151, 239, 188, 140, 233, 128, 154, 233, 129, 142, 228, 186, 134, 231, 148, 177, '1', '8', '0', 228, 186, 186, 231, 181, 132, 230, 136, 144, 231, 154, 132, 228, 184, 173, 229, 156, 139, 228, 186, 186, 230, 176, 145, 230, 148, 191, 230, 178, 187, 229, 141, 148, 229, 149, 134, 230, 156, 131, 232, 173, 176, 231, 172, 172, 228, 184, 128, 229, 177, 134, 229, 133, 168, 229, 156, 139, 229, 167, 148, 229, 147, 161, 230, 156, 131, 229, 144, 141, 229, 150, 174, 239, 188, 140, 228, 184, 166, 233, 129, 184, 232, 136, 137, 230, 175, 155, 230, 190, 164, 230, 157, 177, 231, 130, 186, 228, 184, 173, 229, 164, 174, 228, 186, 186, 230, 176, 145, 230, 148, 191, 229, 186, 156, 228, 184, 187, 229, 184, 173, 227, 128, 129, 230, 156, 177, 229, 190, 183, 227, 128, 129, 229, 136, 152, 229, 176, 145, 229, 165, 135, 227, 128, 129, 229, 174, 139, 229, 186, 134, 233, 190, 132, 227, 128, 129, 230, 157, 142, 230, 181, 142, 230, 183, 177, 227, 128, 129, 229, 188, 160, 230, 190, 156, 227, 128, 129, 233, 171, 152, 229, 178, 151, 231, 130, 186, 229, 137, 175, 228, 184, 187, 229, 184, 173, 227, 128, 129, 229, 143, 166, 229, 164, 150, '5', '6', 228, 189, 141, 231, 130, 186, 228, 184, 173, 229, 164, 174, 228, 186, 186, 230, 176, 145, 230, 148, 191, 229, 186, 156, 229, 167, 148, 229, 147, 161, 227, 128, 130, '1', '0', 230, 156, 136, '1', 230, 151, 165, 229, 188, 128, 229, 155, 189, 229, 164, 167, 229, 133, 184, 229, 156, 168, 229, 140, 151, 228, 186, 172, 228, 184, 190, 232, 161, 140, 239, 188, 140, 230, 175, 155, 230, 190, 164, 230, 157, 177, 229, 156, 168, 229, 164, 169, 229, 174, 137, 233, 151, 168, 229, 159, 142, 230, 165, 188, 229, 174, 163, 229, 145, 138, 228, 184, 173, 229, 141, 142, 228, 186, 186, 230, 176, 145, 229, 133, 177, 229, 146, 140, 229, 155, 189, 228, 184, 173, 229, 164, 174, 228, 186, 186, 230, 176, 145, 230, 148, 191, 229, 186, 156, 230, 136, 144, 231, 171, 139, 239, 188, 155, '1', '2', 230, 156, 136, '7', 230, 151, 165, 239, 188, 140, 228, 184, 173, 232, 143, 175, 230, 176, 145, 229, 156, 139, 230, 148, 191, 229, 186, 156, 230, 173, 163, 229, 188, 143, 231, 148, 177, 229, 155, 155, 229, 183, 157, 231, 156, 129, 230, 136, 144, 233, 131, 189, 229, 184, 130, 233, 129, 183, 229, 190, 128, 229, 143, 176, 230, 185, 190, 231, 156, 129, 229, 143, 176, 229, 140, 151, 229, 184, 130, 239, 188, 140, 228, 184, 166, 231, 185, 188, 231, 186, 140, 231, 181, 177, 230, 178, 187, 229, 143, 176, 231, 129, 163, 230, 156, 172, 229, 179, 182, 229, 143, 138, 230, 190, 142, 230, 185, 150, 227, 128, 129, 233, 131, 168, 229, 136, 134, 231, 166, 143, 229, 187, 186, 233, 155, 162, 229, 179, 182, 227, 128, 129, 228, 184, 156, 230, 178, 153, 231, 190, 164, 229, 178, 155, 227, 128, 129, 229, 164, 170, 229, 185, 179, 229, 178, 155, 231, 173, 137, 232, 135, 179, 228, 187, 138, 227, 128, 130, 232, 135, 179, 230, 173, 164, 239, 188, 140, 228, 184, 173, 229, 156, 139, 230, 173, 183, 229, 143, 178, 228, 184, 138, 230, 150, 188, 230, 181, 183, 229, 179, 189, 229, 133, 169, 229, 178, 184, 229, 136, 134, 230, 178, 187, 231, 154, 132, 230, 148, 191, 230, 178, 187, 230, 160, 188, 229, 177, 128, 230, 173, 163, 229, 188, 143, 229, 189, 162, 230, 136, 144, 227, 128, 130, 13, 10, 13, 10, 'H', 'i', 'n', 'd', 'i', ':', 13, 10, 13, 10, 224, 164, 173, 224, 164, 190, 224, 164, 176, 224, 164, 164, ',', ' ', 224, 164, 170, 224, 165, 140, 224, 164, 176, 224, 164, 190, 224, 164, 163, 224, 164, 191, 224, 164, 149, ' ', 224, 164, 156, 224, 164, 174, 224, 165, 141, 224, 164, 172, 224, 165, 130, 224, 164, 166, 224, 165, 141, 224, 164, 181, 224, 165, 128, 224, 164, 170, ',', ' ', 224, 164, 134, 224, 164, 167, 224, 165, 129, 224, 164, 168, 224, 164, 191, 224, 164, 149, ' ', 224, 164, 166, 224, 164, 149, 224, 165, 141, 224, 164, 183, 224, 164, 191, 224, 164, 163, ' ', 224, 164, 143, 224, 164, 182, 224, 164, 191, 224, 164, 175, 224, 164, 190, ' ', 224, 164, 174, 224, 165, 135, 224, 164, 130, ' ', 224, 164, 184, 224, 165, 141, 224, 164, 165, 224, 164, 191, 224, 164, 164, ' ', 224, 164, 173, 224, 164, 190, 224, 164, 176, 224, 164, 164, 224, 165, 128, 224, 164, 175, ' ', 224, 164, 137, 224, 164, 170, 224, 164, 174, 224, 164, 185, 224, 164, 190, 224, 164, 166, 224, 165, 141, 224, 164, 181, 224, 165, 128, 224, 164, 170, ' ', 224, 164, 149, 224, 164, 190, ' ', 224, 164, 184, 224, 164, 172, 224, 164, 184, 224, 165, 135, ' ', 224, 164, 172, 224, 164, 161, 224, 164, 188, 224, 164, 190, ' ', 224, 164, 166, 224, 165, 135, 224, 164, 182, ' ', 224, 164, 185, 224, 165, 136, 224, 165, 164, ' ', 224, 164, 173, 224, 164, 190, 224, 164, 176, 224, 164, 164, ' ', 224, 164, 149, 224, 164, 190, ' ', 224, 164, 173, 224, 165, 140, 224, 164, 151, 224, 165, 139, 224, 164, 178, 224, 164, 191, 224, 164, 149, ' ', 224, 164, 171, 224, 165, 136, 224, 164, 178, 224, 164, 190, 224, 164, 181, ' ', 224, 165, 174, 224, 165, 166, ' ', 224, 165, 170, '\'', ' ', 224, 164, 184, 224, 165, 135, ' ', 224, 165, 169, 224, 165, 173, 224, 165, 166, ' ', 224, 165, 172, '\'', ' ', 224, 164, 137, 224, 164, 164, 224, 165, 141, 224, 164, 164, 224, 164, 176, 224, 165, 128, ' ', 224, 164, 133, 224, 164, 149, 224, 165, 141, 224, 164, 183, 224, 164, 190, 224, 164, 130, 224, 164, 182, ' ', 224, 164, 164, 224, 164, 149, ' ', 224, 164, 164, 224, 164, 165, 224, 164, 190, ' ', 224, 165, 172, 224, 165, 174, 224, 165, 166, ' ', 224, 165, 173, '\'', ' ', 224, 164, 184, 224, 165, 135, ' ', 224, 165, 175, 224, 165, 173, 224, 165, 166, ' ', 224, 165, 168, 224, 165, 171, '\'', 224, 164, 170, 224, 165, 130, 224, 164, 176, 224, 165, 141, 224, 164, 181, 224, 165, 128, ' ', 224, 164, 166, 224, 165, 135, 224, 164, 182, 224, 164, 190, 224, 164, 168, 224, 165, 141, 224, 164, 164, 224, 164, 176, ' ', 224, 164, 164, 224, 164, 149, ' ', 224, 164, 185, 224, 165, 136, 224, 165, 164, ' ', 224, 164, 173, 224, 164, 190, 224, 164, 176, 224, 164, 164, ' ', 224, 164, 149, 224, 164, 190, ' ', 224, 164, 181, 224, 164, 191, 224, 164, 184, 224, 165, 141, 224, 164, 164, 224, 164, 190, 224, 164, 176, ' ', 224, 164, 137, 224, 164, 164, 224, 165, 141, 224, 164, 164, 224, 164, 176, ' ', 224, 164, 184, 224, 165, 135, ' ', 224, 164, 166, 224, 164, 149, 224, 165, 141, 224, 164, 183, 224, 164, 191, 224, 164, 163, ' ', 224, 164, 164, 224, 164, 149, ' ', 224, 164, 149, 224, 164, 191, '.', ' ', 224, 164, 174, 224, 165, 128, '.', ' ', 224, 164, 148, 224, 164, 176, ' ', 224, 164, 170, 224, 165, 130, 224, 164, 176, 224, 165, 141, 224, 164, 181, ' ', 224, 164, 184, 224, 165, 135, ' ', 224, 164, 170, 224, 164, 182, 224, 165, 141, 224, 164, 154, 224, 164, 191, 224, 164, 174, ' ', 224, 164, 164, 224, 164, 149, ' ', 224, 165, 168, ',', 224, 165, 175, 224, 165, 169, 224, 165, 169, ' ', 224, 164, 149, 224, 164, 191, '.', ' ', 224, 164, 174, 224, 165, 128, '.', ' ', 224, 164, 185, 224, 165, 136, 224, 165, 164, ' ', 224, 164, 173, 224, 164, 190, 224, 164, 176, 224, 164, 164, ' ', 224, 164, 149, 224, 165, 128, ' ', 224, 164, 184, 224, 164, 174, 224, 165, 129, 224, 164, 166, 224, 165, 141, 224, 164, 176, ' ', 224, 164, 164, 224, 164, 159, ' ', 224, 164, 176, 224, 165, 135, 224, 164, 150, 224, 164, 190, ' ', 224, 165, 173, 224, 165, 171, 224, 165, 167, 224, 165, 172, '.', 224, 165, 172, ' ', 224, 164, 149, 224, 164, 191, 224, 164, 178, 224, 165, 139, 224, 164, 174, 224, 165, 128, 224, 164, 159, 224, 164, 176, ' ', 224, 164, 178, 224, 164, 174, 224, 165, 141, 224, 164, 172, 224, 165, 128, ' ', 224, 164, 185, 224, 165, 136, 224, 165, 164, ' ', 224, 164, 173, 224, 164, 190, 224, 164, 176, 224, 164, 164, ',', ' ', 224, 164, 173, 224, 165, 140, 224, 164, 151, 224, 165, 139, 224, 164, 178, 224, 164, 191, 224, 164, 149, ' ', 224, 164, 166, 224, 165, 131, 224, 164, 183, 224, 165, 141, 224, 164, 159, 224, 164, 191, ' ', 224, 164, 184, 224, 165, 135, ' ', 224, 164, 181, 224, 164, 191, 224, 164, 182, 224, 165, 141, 224, 164, 181, ' ', 224, 164, 174, 224, 165, 135, 224, 164, 130, ' ', 224, 164, 184, 224, 164, 190, 224, 164, 164, 224, 164, 181, 224, 164, 190, 224, 164, 129, ' ', 224, 164, 184, 224, 164, 172, 224, 164, 184, 224, 165, 135, ' ', 224, 164, 172, 224, 164, 161, 224, 164, 188, 224, 164, 190, ' ', 224, 164, 148, 224, 164, 176, ' ', 224, 164, 156, 224, 164, 168, 224, 164, 184, 224, 164, 129, 224, 164, 150, 224, 165, 141, 224, 164, 175, 224, 164, 190, ' ', 224, 164, 149, 224, 165, 135, ' ', 224, 164, 166, 224, 165, 131, 224, 164, 183, 224, 165, 141, 224, 164, 159, 224, 164, 191, 224, 164, 149, 224, 165, 139, 224, 164, 163, ' ', 224, 164, 184, 224, 165, 135, ' ', 224, 164, 166, 224, 165, 130, 224, 164, 184, 224, 164, 176, 224, 164, 190, ' ', 224, 164, 184, 224, 164, 172, ' ', 224, 164, 184, 224, 165, 135, ' ', 224, 164, 172, 224, 164, 161, 224, 164, 188, 224, 164, 190, ' ', 224, 164, 166, 224, 165, 135, 224, 164, 182, ' ', 224, 164, 185, 224, 165, 136, 224, 165, 164, ' ', 224, 164, 173, 224, 164, 190, 224, 164, 176, 224, 164, 164, ' ', 224, 164, 149, 224, 165, 135, ' ', 224, 164, 170, 224, 164, 182, 224, 165, 141, 224, 164, 154, 224, 164, 191, 224, 164, 174, ' ', 224, 164, 174, 224, 165, 135, 224, 164, 130, ' ', 224, 164, 170, 224, 164, 190, 224, 164, 149, 224, 164, 191, 224, 164, 184, 224, 165, 141, 224, 164, 164, 224, 164, 190, 224, 164, 168, ',', ' ', 224, 164, 137, 224, 164, 164, 224, 165, 141, 224, 164, 164, 224, 164, 176, '-', 224, 164, 170, 224, 165, 130, 224, 164, 176, 224, 165, 141, 224, 164, 181, ' ', 224, 164, 174, 224, 165, 135, 224, 164, 130, ' ', 224, 164, 154, 224, 165, 128, 224, 164, 168, ',', ' ', 224, 164, 168, 224, 165, 135, 224, 164, 170, 224, 164, 190, 224, 164, 178, ',', ' ', 224, 164, 148, 224, 164, 176, ' ', 224, 164, 173, 224, 165, 130, 224, 164, 159, 224, 164, 190, 224, 164, 168, ' ', 224, 164, 148, 224, 164, 176, ' ', 224, 164, 170, 224, 165, 130, 224, 164, 176, 224, 165, 141, 224, 164, 181, ' ', 224, 164, 174, 224, 165, 135, 224, 164, 130, ' ', 224, 164, 172, 224, 164, 190, 224, 164, 130, 224, 164, 151, 224, 165, 141, 224, 164, 178, 224, 164, 190, 224, 164, 166, 224, 165, 135, 224, 164, 182, ' ', 224, 164, 148, 224, 164, 176, ' ', 224, 164, 174, 224, 165, 141, 224, 164, 175, 224, 164, 190, 224, 164, 168, 224, 165, 141, 224, 164, 174, 224, 164, 190, 224, 164, 176, ' ', 224, 164, 166, 224, 165, 135, 224, 164, 182, ' ', 224, 164, 184, 224, 165, 141, 224, 164, 165, 224, 164, 191, 224, 164, 164, ' ', 224, 164, 185, 224, 165, 136, 224, 164, 130, 224, 165, 164, ' ', 224, 164, 185, 224, 164, 191, 224, 164, 168, 224, 165, 141, 224, 164, 166, ' ', 224, 164, 174, 224, 164, 185, 224, 164, 190, 224, 164, 184, 224, 164, 190, 224, 164, 151, 224, 164, 176, ' ', 224, 164, 174, 224, 165, 135, 224, 164, 130, ' ', 224, 164, 135, 224, 164, 184, 224, 164, 149, 224, 165, 135, ' ', 224, 164, 166, 224, 164, 149, 224, 165, 141, 224, 164, 183, 224, 164, 191, 224, 164, 163, ' ', 224, 164, 170, 224, 164, 182, 224, 165, 141, 224, 164, 154, 224, 164, 191, 224, 164, 174, ' ', 224, 164, 174, 224, 165, 135, 224, 164, 130, ' ', 224, 164, 174, 224, 164, 190, 224, 164, 178, 224, 164, 166, 224, 165, 128, 224, 164, 181, ',', ' ', 224, 164, 166, 224, 164, 149, 224, 165, 141, 224, 164, 183, 224, 164, 191, 224, 164, 163, ' ', 224, 164, 174, 224, 165, 135, 224, 164, 130, ' ', 224, 164, 182, 224, 165, 141, 224, 164, 176, 224, 165, 128, 224, 164, 178, 224, 164, 130, 224, 164, 149, 224, 164, 190, ' ', 224, 164, 148, 224, 164, 176, ' ', 224, 164, 166, 224, 164, 149, 224, 165, 141, 224, 164, 183, 224, 164, 191, 224, 164, 163, '-', 224, 164, 170, 224, 165, 130, 224, 164, 176, 224, 165, 141, 224, 164, 181, ' ', 224, 164, 174, 224, 165, 135, 224, 164, 130, ' ', 224, 164, 135, 224, 164, 130, 224, 164, 161, 224, 165, 139, 224, 164, 168, 224, 165, 135, 224, 164, 182, 224, 164, 191, 224, 164, 175, 224, 164, 190, ' ', 224, 164, 185, 224, 165, 136, 224, 164, 130, 224, 165, 164, ' ', 224, 164, 137, 224, 164, 164, 224, 165, 141, 224, 164, 164, 224, 164, 176, '-', 224, 164, 170, 224, 164, 182, 224, 165, 141, 224, 164, 154, 224, 164, 191, 224, 164, 174, ' ', 224, 164, 174, 224, 165, 135, 224, 164, 130, ' ', 224, 164, 133, 224, 164, 171, 224, 164, 188, 224, 164, 151, 224, 164, 190, 224, 164, 168, 224, 164, 191, 224, 164, 184, 224, 165, 141, 224, 164, 164, 224, 164, 190, 224, 164, 168, ' ', 224, 164, 149, 224, 165, 135, ' ', 224, 164, 184, 224, 164, 190, 224, 164, 165, ' ', 224, 164, 173, 224, 164, 190, 224, 164, 176, 224, 164, 164, ' ', 224, 164, 149, 224, 165, 128, ' ', 224, 164, 184, 224, 165, 128, 224, 164, 174, 224, 164, 190, ' ', 224, 164, 185, 224, 165, 136, 224, 165, 164, ' ', 224, 164, 135, 224, 164, 184, 224, 164, 149, 224, 165, 135, ' ', 224, 164, 137, 224, 164, 164, 224, 165, 141, 224, 164, 164, 224, 164, 176, ' ', 224, 164, 174, 224, 165, 135, 224, 164, 130, ' ', 224, 164, 185, 224, 164, 191, 224, 164, 174, 224, 164, 190, 224, 164, 178, 224, 164, 175, ' ', 224, 164, 170, 224, 164, 176, 224, 165, 141, 224, 164, 181, 224, 164, 164, ' ', 224, 164, 185, 224, 165, 136, ' ', 224, 164, 148, 224, 164, 176, ' ', 224, 164, 166, 224, 164, 149, 224, 165, 141, 224, 164, 183, 224, 164, 191, 224, 164, 163, ' ', 224, 164, 174, 224, 165, 135, 224, 164, 130, ' ', 224, 164, 185, 224, 164, 191, 224, 164, 168, 224, 165, 141, 224, 164, 166, ' ', 224, 164, 174, 224, 164, 185, 224, 164, 190, 224, 164, 184, 224, 164, 190, 224, 164, 151, 224, 164, 176, ' ', 224, 164, 185, 224, 165, 136, 224, 165, 164, ' ', 224, 164, 170, 224, 165, 130, 224, 164, 176, 224, 165, 141, 224, 164, 181, ' ', 224, 164, 174, 224, 165, 135, 224, 164, 130, ' ', 224, 164, 172, 224, 164, 130, 224, 164, 151, 224, 164, 190, 224, 164, 178, ' ', 224, 164, 149, 224, 165, 128, ' ', 224, 164, 150, 224, 164, 190, 224, 164, 161, 224, 164, 188, 224, 165, 128, ' ', 224, 164, 185, 224, 165, 136, ' ', 224, 164, 164, 224, 164, 165, 224, 164, 190, ' ', 224, 164, 170, 224, 164, 182, 224, 165, 141, 224, 164, 154, 224, 164, 191, 224, 164, 174, ' ', 224, 164, 174, 224, 165, 135, 224, 164, 130, ' ', 224, 164, 133, 224, 164, 176, 224, 164, 172, ' ', 224, 164, 184, 224, 164, 190, 224, 164, 151, 224, 164, 176, 224, 164, 184, 224, 164, 174, 224, 165, 129, 224, 164, 166, 224, 165, 141, 224, 164, 176, ' ', 224, 164, 185, 224, 165, 136, 224, 164, 130, ' ', 224, 165, 164, ' ', 224, 164, 173, 224, 164, 190, 224, 164, 176, 224, 164, 164, ' ', 224, 164, 174, 224, 165, 135, 224, 164, 130, ' ', 224, 164, 149, 224, 164, 136, ' ', 224, 164, 172, 224, 164, 161, 224, 164, 188, 224, 165, 128, ' ', 224, 164, 168, 224, 164, 166, 224, 164, 191, 224, 164, 175, 224, 164, 190, 224, 164, 129, ' ', 224, 164, 185, 224, 165, 136, 224, 164, 130, ' ', 224, 165, 164, ' ', 224, 164, 151, 224, 164, 130, 224, 164, 151, 224, 164, 190, ' ', 224, 164, 168, 224, 164, 166, 224, 165, 128, ' ', 224, 164, 173, 224, 164, 190, 224, 164, 176, 224, 164, 164, 224, 165, 128, 224, 164, 175, ' ', 224, 164, 184, 224, 164, 130, 224, 164, 184, 224, 165, 141, 224, 164, 149, 224, 165, 131, 224, 164, 164, 224, 164, 191, ' ', 224, 164, 174, 224, 165, 135, 224, 164, 130, ' ', 224, 164, 133, 224, 164, 164, 224, 165, 141, 224, 164, 175, 224, 164, 130, 224, 164, 164, ' ', 224, 164, 170, 224, 164, 181, 224, 164, 191, 224, 164, 164, 224, 165, 141, 224, 164, 176, ' ', 224, 164, 174, 224, 164, 190, 224, 164, 168, 224, 165, 128, ' ', 224, 164, 156, 224, 164, 190, 224, 164, 164, 224, 165, 128, ' ', 224, 164, 185, 224, 165, 136, 224, 165, 164, ' ', 224, 164, 133, 224, 164, 168, 224, 165, 141, 224, 164, 175, ' ', 224, 164, 172, 224, 164, 161, 224, 164, 188, 224, 165, 128, ' ', 224, 164, 168, 224, 164, 166, 224, 164, 191, 224, 164, 175, 224, 164, 190, 224, 164, 129, ' ', 224, 164, 184, 224, 164, 191, 224, 164, 168, 224, 165, 141, 224, 164, 167, 224, 165, 129, ',', ' ', 224, 164, 168, 224, 164, 176, 224, 165, 141, 224, 164, 174, 224, 164, 166, 224, 164, 190, ',', ' ', 224, 164, 172, 224, 165, 141, 224, 164, 176, 224, 164, 185, 224, 165, 141, 224, 164, 174, 224, 164, 170, 224, 165, 129, 224, 164, 164, 224, 165, 141, 224, 164, 176, ',', ' ', 224, 164, 175, 224, 164, 174, 224, 165, 129, 224, 164, 168, 224, 164, 190, ',', ' ', 224, 164, 151, 224, 165, 139, 224, 164, 166, 224, 164, 190, 224, 164, 181, 224, 164, 176, 224, 165, 128, ',', ' ', 224, 164, 149, 224, 164, 190, 224, 164, 181, 224, 165, 135, 224, 164, 176, 224, 165, 128, ',', ' ', 224, 164, 149, 224, 165, 131, 224, 164, 183, 224, 165, 141, 224, 164, 163, 224, 164, 190, ',', ' ', 224, 164, 154, 224, 164, 174, 224, 165, 141, 224, 164, 172, 224, 164, 178, ',', ' ', 224, 164, 184, 224, 164, 164, 224, 164, 178, 224, 164, 156, ',', ' ', 224, 164, 181, 224, 165, 141, 224, 164, 175, 224, 164, 190, 224, 164, 184, ' ', 224, 164, 134, 224, 164, 166, 224, 164, 191, ' ', 224, 164, 185, 224, 165, 136, 224, 164, 130, 224, 165, 164, 13, 10, 13, 10, 224, 164, 175, 224, 164, 185, ' ', 224, 164, 181, 224, 164, 191, 224, 164, 182, 224, 165, 141, 224, 164, 181, ' ', 224, 164, 149, 224, 164, 190, ' ', 224, 164, 184, 224, 164, 172, 224, 164, 184, 224, 165, 135, ' ', 224, 164, 172, 224, 164, 161, 224, 164, 188, 224, 164, 190, ' ', 224, 164, 178, 224, 165, 139, 224, 164, 149, 224, 164, 164, 224, 164, 130, 224, 164, 164, 224, 165, 141, 224, 164, 176, ' ', 224, 164, 185, 224, 165, 136, 224, 165, 164, ' ', 224, 164, 175, 224, 164, 185, 224, 164, 190, 224, 164, 129, ' ', 224, 165, 169, 224, 165, 166, 224, 165, 166, ' ', 224, 164, 184, 224, 165, 135, ' ', 224, 164, 133, 224, 164, 167, 224, 164, 191, 224, 164, 149, ' ', 224, 164, 173, 224, 164, 190, 224, 164, 183, 224, 164, 190, 224, 164, 143, 224, 164, 129, ' ', 224, 164, 172, 224, 165, 139, 224, 164, 178, 224, 165, 128, ' ', 224, 164, 156, 224, 164, 190, 224, 164, 164, 224, 165, 128, ' ', 224, 164, 185, 224, 165, 136, 224, 164, 130, ' ', '[', '1', ']', 224, 165, 164, ' ', 224, 164, 175, 224, 164, 185, ' ', 224, 164, 181, 224, 164, 191, 224, 164, 182, 224, 165, 141, 224, 164, 181, ' ', 224, 164, 149, 224, 165, 128, ' ', 224, 164, 149, 224, 165, 129, 224, 164, 155, ' ', 224, 164, 170, 224, 165, 141, 224, 164, 176, 224, 164, 190, 224, 164, 154, 224, 165, 128, 224, 164, 168, 224, 164, 164, 224, 164, 174, ' ', 224, 164, 184, 224, 164, 173, 224, 165, 141, 224, 164, 175, 224, 164, 164, 224, 164, 190, 224, 164, 147, 224, 164, 130, ' ', 224, 164, 149, 224, 165, 128, ' ', 224, 164, 156, 224, 164, 168, 224, 164, 168, 224, 165, 128, ' ', 224, 164, 176, 224, 164, 185, 224, 164, 190, ' ', 224, 164, 185, 224, 165, 136, ' ', 224, 164, 156, 224, 165, 136, 224, 164, 184, 224, 165, 135, ' ', '-', ' ', 224, 164, 184, 224, 164, 191, 224, 164, 168, 224, 165, 141, 224, 164, 167, 224, 165, 129, ' ', 224, 164, 152, 224, 164, 190, 224, 164, 159, 224, 165, 128, ' ', 224, 164, 184, 224, 164, 173, 224, 165, 141, 224, 164, 175, 224, 164, 164, 224, 164, 190, ',', ' ', 224, 164, 148, 224, 164, 176, ' ', 224, 164, 174, 224, 164, 185, 224, 164, 164, 224, 165, 141, 224, 164, 181, 224, 164, 170, 224, 165, 130, 224, 164, 176, 224, 165, 141, 224, 164, 163, ' ', 224, 164, 144, 224, 164, 164, 224, 164, 191, 224, 164, 185, 224, 164, 190, 224, 164, 184, 224, 164, 191, 224, 164, 149, ' ', 224, 164, 181, 224, 165, 141, 224, 164, 175, 224, 164, 190, 224, 164, 170, 224, 164, 190, 224, 164, 176, ' ', 224, 164, 170, 224, 164, 165, 224, 165, 139, 224, 164, 130, ' ', 224, 164, 149, 224, 164, 190, ' ', 224, 164, 133, 224, 164, 173, 224, 164, 191, 224, 164, 168, 224, 165, 141, 224, 164, 168, ' ', 224, 164, 133, 224, 164, 130, 224, 164, 151, ' ', 224, 164, 173, 224, 165, 128, '.', ' ', 224, 164, 181, 224, 164, 191, 224, 164, 182, 224, 165, 141, 224, 164, 181, ' ', 224, 164, 149, 224, 165, 135, ' ', 224, 164, 154, 224, 164, 190, 224, 164, 176, ' ', 224, 164, 170, 224, 165, 141, 224, 164, 176, 224, 164, 174, 224, 165, 129, 224, 164, 150, ' ', 224, 164, 167, 224, 164, 176, 224, 165, 141, 224, 164, 174, ' ', ':', ' ', 224, 164, 184, 224, 164, 168, 224, 164, 190, 224, 164, 164, 224, 164, 168, '-', 224, 164, 185, 224, 164, 191, 224, 164, 168, 224, 165, 141, 224, 164, 166, 224, 165, 130, ',', ' ', 224, 164, 172, 224, 165, 140, 224, 164, 166, 224, 165, 141, 224, 164, 167, ',', ' ', 224, 164, 156, 224, 165, 136, 224, 164, 168, ' ', 224, 164, 164, 224, 164, 165, 224, 164, 190, ' ', 224, 164, 184, 224, 164, 191, 224, 164, 150, ' ', 224, 164, 173, 224, 164, 190, 224, 164, 176, 224, 164, 164, ' ', 224, 164, 174, 224, 165, 135, 224, 164, 130, ' ', 224, 164, 185, 224, 165, 128, ' ', 224, 164, 156, 224, 164, 168, 224, 165, 141, 224, 164, 174, 224, 165, 135, ' ', 224, 164, 148, 224, 164, 176, ' ', 224, 164, 181, 224, 164, 191, 224, 164, 149, 224, 164, 184, 224, 164, 191, 224, 164, 164, ' ', 224, 164, 185, 224, 165, 129, 224, 164, 143, 224, 165, 164, 13, 10, 13, 10, 224, 164, 173, 224, 164, 190, 224, 164, 176, 224, 164, 164, ' ', 224, 164, 173, 224, 165, 140, 224, 164, 151, 224, 165, 139, 224, 164, 178, 224, 164, 191, 224, 164, 149, ' ', 224, 164, 149, 224, 165, 141, 224, 164, 183, 224, 165, 135, 224, 164, 164, 224, 165, 141, 224, 164, 176, 224, 164, 171, 224, 164, 178, ' ', 224, 164, 149, 224, 165, 135, ' ', 224, 164, 134, 224, 164, 167, 224, 164, 190, 224, 164, 176, ' ', 224, 164, 170, 224, 164, 176, ' ', 224, 164, 181, 224, 164, 191, 224, 164, 182, 224, 165, 141, 224, 164, 181, ' ', 224, 164, 149, 224, 164, 190, ' ', 224, 164, 184, 224, 164, 190, 224, 164, 164, 224, 164, 181, 224, 164, 190, 224, 164, 129, ' ', 224, 164, 184, 224, 164, 172, 224, 164, 184, 224, 165, 135, ' ', 224, 164, 172, 224, 164, 161, 224, 164, 188, 224, 164, 190, ' ', 224, 164, 176, 224, 164, 190, 224, 164, 183, 224, 165, 141, 224, 164, 159, 224, 165, 141, 224, 164, 176, ' ', 224, 164, 185, 224, 165, 136, 224, 165, 164, ' ', 224, 164, 173, 224, 164, 190, 224, 164, 176, 224, 164, 164, ' ', 224, 164, 149, 224, 165, 128, ' ', 224, 164, 176, 224, 164, 190, 224, 164, 156, 224, 164, 167, 224, 164, 190, 224, 164, 168, 224, 165, 128, ' ', 224, 164, 168, 224, 164, 136, ' ', 224, 164, 166, 224, 164, 191, 224, 164, 178, 224, 165, 141, 224, 164, 178, 224, 165, 128, ' ', 224, 164, 185, 224, 165, 136, 224, 165, 164, ' ', 224, 164, 173, 224, 164, 190, 224, 164, 176, 224, 164, 164, ' ', 224, 164, 149, 224, 165, 135, ' ', 224, 164, 133, 224, 164, 168, 224, 165, 141, 224, 164, 175, ' ', 224, 164, 172, 224, 164, 161, 224, 164, 188, 224, 165, 135, ' ', 224, 164, 174, 224, 164, 185, 224, 164, 190, 224, 164, 168, 224, 164, 151, 224, 164, 176, ' ', 224, 164, 174, 224, 165, 129, 224, 164, 174, 224, 165, 141, 224, 164, 172, 224, 164, 136, ' ', '(', 224, 164, 172, 224, 164, 174, 224, 165, 141, 224, 164, 172, 224, 164, 136, ')', ',', ' ', 224, 164, 149, 224, 165, 139, 224, 164, 178, 224, 164, 149, 224, 164, 190, 224, 164, 164, 224, 164, 190, ' ', '(', 224, 164, 149, 224, 164, 178, 224, 164, 149, 224, 164, 164, 224, 165, 141, 224, 164, 164, 224, 164, 190, ')', ' ', 224, 164, 148, 224, 164, 176, ' ', 224, 164, 154, 224, 165, 135, 224, 164, 168, 224, 165, 141, 224, 164, 168, 224, 164, 136, ' ', '(', 224, 164, 174, 224, 164, 166, 224, 165, 141, 224, 164, 176, 224, 164, 190, 224, 164, 184, ')', ' ', 224, 164, 185, 224, 165, 136, 224, 164, 130, 224, 165, 164, ' ', 224, 165, 167, 224, 165, 175, 224, 165, 170, 224, 165, 173, ' ', 224, 164, 174, 224, 165, 135, 224, 164, 130, ' ', 224, 164, 184, 224, 165, 141, 224, 164, 181, 224, 164, 164, 224, 164, 130, 224, 164, 164, 224, 165, 141, 224, 164, 176, 224, 164, 164, 224, 164, 190, ' ', 224, 164, 170, 224, 165, 141, 224, 164, 176, 224, 164, 190, 224, 164, 170, 224, 165, 141, 224, 164, 164, 224, 164, 191, ' ', 224, 164, 184, 224, 165, 135, ' ', 224, 164, 170, 224, 165, 130, 224, 164, 176, 224, 165, 141, 224, 164, 181, ' ', 224, 164, 172, 224, 165, 141, 224, 164, 176, 224, 164, 191, 224, 164, 159, 224, 164, 191, 224, 164, 182, ' ', 224, 164, 173, 224, 164, 190, 224, 164, 176, 224, 164, 164, ' ', 224, 164, 149, 224, 165, 135, ' ', 224, 164, 176, 224, 165, 130, 224, 164, 170, ' ', 224, 164, 174, 224, 165, 135, 224, 164, 130, ' ', 224, 164, 172, 224, 165, 141, 224, 164, 176, 224, 164, 191, 224, 164, 159, 224, 164, 191, 224, 164, 182, ' ', 224, 164, 184, 224, 164, 190, 224, 164, 174, 224, 165, 141, 224, 164, 176, 224, 164, 190, 224, 164, 156, 224, 165, 141, 224, 164, 175, ' ', 224, 164, 149, 224, 165, 135, ' ', 224, 164, 170, 224, 165, 141, 224, 164, 176, 224, 164, 174, 224, 165, 129, 224, 164, 150, ' ', 224, 164, 133, 224, 164, 130, 224, 164, 151, ' ', 224, 164, 173, 224, 164, 190, 224, 164, 176, 224, 164, 164, ' ', 224, 164, 168, 224, 165, 135, ' ', 224, 164, 181, 224, 164, 191, 224, 164, 151, 224, 164, 164, ' ', 224, 165, 168, 224, 165, 166, ' ', 224, 164, 181, 224, 164, 176, 224, 165, 141, 224, 164, 183, ' ', 224, 164, 174, 224, 165, 135, 224, 164, 130, ' ', 224, 164, 184, 224, 164, 190, 224, 164, 176, 224, 165, 141, 224, 164, 165, 224, 164, 149, ' ', 224, 164, 170, 224, 165, 141, 224, 164, 176, 224, 164, 151, 224, 164, 164, 224, 164, 191, ' ', 224, 164, 149, 224, 165, 128, ' ', 224, 164, 185, 224, 165, 136, ',', ' ', 224, 164, 181, 224, 164, 191, 224, 164, 182, 224, 165, 135, 224, 164, 183, ' ', 224, 164, 176, 224, 165, 130, 224, 164, 170, ' ', 224, 164, 184, 224, 165, 135, ' ', 224, 164, 134, 224, 164, 176, 224, 165, 141, 224, 164, 165, 224, 164, 191, 224, 164, 149, ' ', 224, 164, 148, 224, 164, 176, ' ', 224, 164, 173, 224, 164, 190, 224, 164, 176, 224, 164, 164, 224, 165, 128, 224, 164, 175, ' ', 224, 164, 184, 224, 165, 135, 224, 164, 168, 224, 164, 190, ' ', 224, 164, 143, 224, 164, 149, ' ', 224, 164, 149, 224, 165, 141, 224, 164, 183, 224, 165, 135, 224, 164, 164, 224, 165, 141, 224, 164, 176, 224, 165, 128, 224, 164, 175, ' ', 224, 164, 182, 224, 164, 149, 224, 165, 141, 224, 164, 164, 224, 164, 191, ' ', 224, 164, 148, 224, 164, 176, ' ', 224, 164, 181, 224, 164, 191, 224, 164, 182, 224, 165, 141, 224, 164, 181, 224, 164, 181, 224, 165, 141, 224, 164, 175, 224, 164, 190, 224, 164, 170, 224, 164, 149, ' ', 224, 164, 182, 224, 164, 149, 224, 165, 141, 224, 164, 164, 224, 164, 191, ' ', 224, 164, 185, 224, 165, 136, 224, 165, 164, ' ', 224, 164, 173, 224, 164, 190, 224, 164, 176, 224, 164, 164, ' ', 224, 164, 181, 224, 164, 191, 224, 164, 182, 224, 165, 141, 224, 164, 181, ' ', 224, 164, 149, 224, 165, 128, ' ', 224, 164, 166, 224, 164, 184, 224, 164, 181, 224, 165, 128, 224, 164, 130, ' ', 224, 164, 184, 224, 164, 172, 224, 164, 184, 224, 165, 135, ' ', 224, 164, 172, 224, 164, 161, 224, 164, 188, 224, 165, 128, ' ', 224, 164, 133, 224, 164, 176, 224, 165, 141, 224, 164, 165, 224, 164, 181, 224, 165, 141, 224, 164, 175, 224, 164, 181, 224, 164, 184, 224, 165, 141, 224, 164, 165, 224, 164, 190, ' ', 224, 164, 185, 224, 165, 136, 224, 165, 164, ' ', 224, 164, 185, 224, 164, 190, 224, 164, 178, ' ', 224, 164, 149, 224, 165, 135, ' ', 224, 164, 181, 224, 164, 176, 224, 165, 141, 224, 164, 183, 224, 165, 139, 224, 164, 130, ' ', 224, 164, 174, 224, 165, 135, 224, 164, 130, ' ', 224, 164, 173, 224, 164, 190, 224, 164, 176, 224, 164, 164, ' ', 224, 164, 149, 224, 165, 128, ' ', 224, 164, 133, 224, 164, 176, 224, 165, 141, 224, 164, 165, 224, 164, 181, 224, 165, 141, 224, 164, 175, 224, 164, 181, 224, 164, 184, 224, 165, 141, 224, 164, 165, 224, 164, 190, ' ', 224, 164, 168, 224, 165, 135, ' ', 224, 164, 172, 224, 164, 185, 224, 165, 129, 224, 164, 164, ' ', 224, 164, 170, 224, 165, 141, 224, 164, 176, 224, 164, 151, 224, 164, 164, 224, 164, 191, ' ', 224, 164, 149, 224, 165, 128, ' ', 224, 164, 185, 224, 165, 136, ',', ' ', 224, 164, 148, 224, 164, 176, ' ', 224, 164, 164, 224, 164, 190, 224, 164, 156, 224, 164, 188, 224, 164, 190, ' ', 224, 164, 184, 224, 165, 141, 224, 164, 165, 224, 164, 191, 224, 164, 164, 224, 164, 191, ' ', 224, 164, 174, 224, 165, 135, 224, 164, 130, ' ', 224, 164, 173, 224, 164, 190, 224, 164, 176, 224, 164, 164, ' ', 224, 164, 181, 224, 164, 191, 224, 164, 182, 224, 165, 141, 224, 164, 181, ' ', 224, 164, 174, 224, 165, 135, 224, 164, 130, ' ', 224, 164, 164, 224, 165, 128, 224, 164, 184, 224, 164, 176, 224, 165, 135, '-', 224, 164, 154, 224, 165, 140, 224, 164, 165, 224, 165, 135, ' ', 224, 164, 184, 224, 165, 141, 224, 164, 165, 224, 164, 190, 224, 164, 168, ' ', 224, 164, 170, 224, 164, 176, ' ', 224, 164, 185, 224, 165, 139, 224, 164, 168, 224, 165, 135, ' ', 224, 164, 149, 224, 164, 190, ' ', 224, 164, 166, 224, 164, 190, 224, 164, 181, 224, 164, 190, ' ', 224, 164, 149, 224, 164, 176, 224, 164, 164, 224, 164, 190, ' ', 224, 164, 185, 224, 165, 136, ' ', 224, 165, 164, 13, 10, 13, 10, 224, 164, 173, 224, 164, 190, 224, 164, 176, 224, 164, 164, ' ', 224, 164, 149, 224, 165, 135, ' ', 224, 164, 166, 224, 165, 139, ' ', 224, 164, 134, 224, 164, 167, 224, 164, 191, 224, 164, 149, 224, 164, 190, 224, 164, 176, 224, 164, 191, 224, 164, 149, ' ', 224, 164, 168, 224, 164, 190, 224, 164, 174, ' ', 224, 164, 185, 224, 165, 136, 224, 164, 130, '-', ' ', 224, 164, 185, 224, 164, 191, 224, 164, 168, 224, 165, 141, 224, 164, 166, 224, 165, 128, ' ', 224, 164, 174, 224, 165, 135, 224, 164, 130, ' ', 224, 164, 173, 224, 164, 190, 224, 164, 176, 224, 164, 164, ' ', 224, 164, 148, 224, 164, 176, ' ', 224, 164, 133, 224, 164, 130, 224, 164, 151, 224, 165, 141, 224, 164, 176, 224, 165, 135, 224, 164, 156, 224, 164, 188, 224, 165, 128, ' ', 224, 164, 174, 224, 165, 135, 224, 164, 130, ' ', 224, 164, 135, 224, 164, 163, 224, 165, 141, 224, 164, 161, 224, 164, 191, 224, 164, 175, 224, 164, 190, ' ', '(', 'I', 'n', 'd', 'i', 'a', ')', 224, 165, 164, ' ', 224, 164, 135, 224, 164, 163, 224, 165, 141, 224, 164, 161, 224, 164, 191, 224, 164, 175, 224, 164, 190, ' ', 224, 164, 168, 224, 164, 190, 224, 164, 174, ' ', 224, 164, 149, 224, 165, 128, ' ', 224, 164, 137, 224, 164, 164, 224, 165, 141, 224, 164, 170, 224, 164, 164, 224, 165, 141, 224, 164, 164, 224, 164, 191, ' ', 224, 164, 184, 224, 164, 191, 224, 164, 168, 224, 165, 141, 224, 164, 167, 224, 165, 129, ' ', 224, 164, 168, 224, 164, 166, 224, 165, 128, ' ', 224, 164, 149, 224, 165, 135, ' ', 224, 164, 133, 224, 164, 130, 224, 164, 151, 224, 165, 141, 224, 164, 176, 224, 165, 135, 224, 164, 156, 224, 165, 128, ' ', 224, 164, 168, 224, 164, 190, 224, 164, 174, ' ', '"', 224, 164, 135, 224, 164, 163, 224, 165, 141, 224, 164, 161, 224, 164, 184, '"', ' ', 224, 164, 184, 224, 165, 135, ' ', 224, 164, 185, 224, 165, 129, 224, 164, 136, ' ', 224, 164, 185, 224, 165, 136, 224, 165, 164, ' ', 224, 164, 173, 224, 164, 190, 224, 164, 176, 224, 164, 164, ' ', 224, 164, 168, 224, 164, 190, 224, 164, 174, ',', ' ', 224, 164, 143, 224, 164, 149, ' ', 224, 164, 170, 224, 165, 141, 224, 164, 176, 224, 164, 190, 224, 164, 154, 224, 165, 128, 224, 164, 168, ' ', 224, 164, 185, 224, 164, 191, 224, 164, 168, 224, 165, 141, 224, 164, 166, 224, 165, 130, ' ', 224, 164, 184, 224, 164, 174, 224, 165, 141, 224, 164, 176, 224, 164, 190, 224, 164, 159, ' ', 224, 164, 173, 224, 164, 176, 224, 164, 164, ' ', 224, 164, 156, 224, 165, 139, ' ', 224, 164, 149, 224, 164, 191, ' ', 224, 164, 174, 224, 164, 168, 224, 165, 129, ' ', 224, 164, 149, 224, 165, 135, ' ', 224, 164, 181, 224, 164, 130, 224, 164, 182, 224, 164, 156, ' ', 224, 164, 139, 224, 164, 183, 224, 164, 173, 224, 164, 166, 224, 165, 135, 224, 164, 181, ' ', 224, 164, 149, 224, 165, 135, ' ', 224, 164, 156, 224, 165, 141, 224, 164, 175, 224, 165, 135, 224, 164, 183, 224, 165, 141, 224, 164, 160, ' ', 224, 164, 170, 224, 165, 129, 224, 164, 164, 224, 165, 141, 224, 164, 176, ' ', 224, 164, 165, 224, 165, 135, ' ', 224, 164, 164, 224, 164, 165, 224, 164, 190, ' ', 224, 164, 156, 224, 164, 191, 224, 164, 168, 224, 164, 149, 224, 165, 128, ' ', 224, 164, 149, 224, 164, 165, 224, 164, 190, ' ', 224, 164, 182, 224, 165, 141, 224, 164, 176, 224, 165, 128, 224, 164, 174, 224, 164, 166, 224, 165, 141, 224, 164, 173, 224, 164, 190, 224, 164, 151, 224, 164, 181, 224, 164, 164, ' ', 224, 164, 174, 224, 164, 185, 224, 164, 190, 224, 164, 170, 224, 165, 129, 224, 164, 176, 224, 164, 190, 224, 164, 163, ' ', 224, 164, 174, 224, 165, 135, 224, 164, 130, ' ', 224, 164, 185, 224, 165, 136, ',', ' ', 224, 164, 149, 224, 165, 135, ' ', 224, 164, 168, 224, 164, 190, 224, 164, 174, ' ', 224, 164, 184, 224, 165, 135, ' ', 224, 164, 178, 224, 164, 191, 224, 164, 175, 224, 164, 190, ' ', 224, 164, 151, 224, 164, 175, 224, 164, 190, ' ', 224, 164, 185, 224, 165, 136, 224, 165, 164, ' ', 224, 164, 173, 224, 164, 190, 224, 164, 176, 224, 164, 164, ' ', '(', 224, 164, 173, 224, 164, 190, ' ', '+', ' ', 224, 164, 176, 224, 164, 164, ')', ' ', 224, 164, 182, 224, 164, 172, 224, 165, 141, 224, 164, 166, ' ', 224, 164, 149, 224, 164, 190, ' ', 224, 164, 174, 224, 164, 164, 224, 164, 178, 224, 164, 172, ' ', 224, 164, 185, 224, 165, 136, ' ', 224, 164, 134, 224, 164, 168, 224, 165, 141, 224, 164, 164, 224, 164, 176, 224, 164, 191, 224, 164, 149, ' ', 224, 164, 170, 224, 165, 141, 224, 164, 176, 224, 164, 149, 224, 164, 190, 224, 164, 182, ' ', 224, 164, 175, 224, 164, 190, ' ', 224, 164, 181, 224, 164, 191, 224, 164, 166, 224, 165, 135, 224, 164, 149, '-', 224, 164, 176, 224, 165, 130, 224, 164, 170, 224, 165, 128, ' ', 224, 164, 170, 224, 165, 141, 224, 164, 176, 224, 164, 149, 224, 164, 190, 224, 164, 182, ' ', 224, 164, 174, 224, 165, 135, 224, 164, 130, ' ', 224, 164, 178, 224, 165, 128, 224, 164, 168, 224, 165, 164, ' ', 224, 164, 143, 224, 164, 149, ' ', 224, 164, 164, 224, 165, 128, 224, 164, 184, 224, 164, 176, 224, 164, 190, ' ', 224, 164, 168, 224, 164, 190, 224, 164, 174, ' ', 224, 164, 185, 224, 164, 191, 224, 164, 168, 224, 165, 141, 224, 164, 166, 224, 165, 129, 224, 164, 184, 224, 165, 141, 224, 164, 164, 224, 164, 190, 224, 164, 168, ' ', 224, 164, 173, 224, 165, 128, ' ', 224, 164, 185, 224, 165, 136, ' ', 224, 164, 156, 224, 164, 191, 224, 164, 184, 224, 164, 149, 224, 164, 190, ' ', 224, 164, 133, 224, 164, 176, 224, 165, 141, 224, 164, 165, ' ', 224, 164, 185, 224, 164, 191, 224, 164, 168, 224, 165, 141, 224, 164, 166, '(', 224, 164, 185, 224, 164, 191, 224, 164, 168, 224, 165, 141, 224, 164, 166, 224, 165, 130, ')', ' ', 224, 164, 149, 224, 165, 128, ' ', 224, 164, 173, 224, 165, 130, 224, 164, 174, 224, 164, 191, ' ', 224, 164, 185, 224, 165, 139, 224, 164, 164, 224, 164, 190, ' ', 224, 164, 185, 224, 165, 136, ' ', 224, 164, 156, 224, 165, 139, ' ', 224, 164, 149, 224, 164, 191, ' ', 224, 164, 170, 224, 165, 141, 224, 164, 176, 224, 164, 190, 224, 164, 154, 224, 165, 128, 224, 164, 168, ' ', 224, 164, 149, 224, 164, 190, 224, 164, 178, ' ', 224, 164, 139, 224, 164, 183, 224, 164, 191, 224, 164, 175, 224, 165, 139, 224, 164, 130, ' ', 224, 164, 166, 224, 165, 141, 224, 164, 181, 224, 164, 190, 224, 164, 176, 224, 164, 190, ' ', 224, 164, 166, 224, 164, 191, 224, 164, 175, 224, 164, 190, ' ', 224, 164, 151, 224, 164, 175, 224, 164, 190, ' ', 224, 164, 165, 224, 164, 190, 224, 165, 164, ' ', 224, 164, 170, 224, 165, 141, 224, 164, 176, 224, 164, 190, 224, 164, 154, 224, 165, 128, 224, 164, 168, ' ', 224, 164, 149, 224, 164, 190, 224, 164, 178, ' ', 224, 164, 174, 224, 165, 135, 224, 164, 130, ' ', 224, 164, 175, 224, 164, 185, ' ', 224, 164, 149, 224, 164, 174, ' ', 224, 164, 170, 224, 165, 141, 224, 164, 176, 224, 164, 175, 224, 165, 129, 224, 164, 149, 224, 165, 141, 224, 164, 164, ' ', 224, 164, 185, 224, 165, 139, 224, 164, 164, 224, 164, 190, ' ', 224, 164, 165, 224, 164, 190, ' ', 224, 164, 164, 224, 164, 165, 224, 164, 190, ' ', 224, 164, 149, 224, 164, 190, 224, 164, 178, 224, 164, 190, 224, 164, 168, 224, 165, 141, 224, 164, 164, 224, 164, 176, ' ', 224, 164, 174, 224, 165, 135, 224, 164, 130, ' ', 224, 164, 133, 224, 164, 167, 224, 164, 191, 224, 164, 149, ' ', 224, 164, 170, 224, 165, 141, 224, 164, 176, 224, 164, 154, 224, 164, 178, 224, 164, 191, 224, 164, 164, ' ', 224, 164, 185, 224, 165, 129, 224, 164, 134, ' ', 224, 164, 181, 224, 164, 191, 224, 164, 182, 224, 165, 135, 224, 164, 183, 224, 164, 149, 224, 164, 176, ' ', 224, 164, 133, 224, 164, 176, 224, 164, 172, '/', 224, 164, 136, 224, 164, 176, 224, 164, 190, 224, 164, 168, ' ', 224, 164, 174, 224, 165, 135, 224, 164, 130, 224, 165, 164, ' ', 224, 164, 173, 224, 164, 190, 224, 164, 176, 224, 164, 164, ' ', 224, 164, 174, 224, 165, 135, 224, 164, 130, ' ', 224, 164, 175, 224, 164, 185, ' ', 224, 164, 168, 224, 164, 190, 224, 164, 174, ' ', 224, 164, 174, 224, 165, 129, 224, 164, 151, 224, 164, 178, ' ', 224, 164, 149, 224, 164, 190, 224, 164, 178, ' ', 224, 164, 184, 224, 165, 135, ' ', 224, 164, 133, 224, 164, 167, 224, 164, 191, 224, 164, 149, ' ', 224, 164, 170, 224, 165, 141, 224, 164, 176, 224, 164, 154, 224, 164, 178, 224, 164, 191, 224, 164, 164, ' ', 224, 164, 185, 224, 165, 129, 224, 164, 134, ' ', 224, 164, 175, 224, 164, 166, 224, 165, 141, 224, 164, 175, 224, 164, 170, 224, 164, 191, ' ', 224, 164, 135, 224, 164, 184, 224, 164, 149, 224, 164, 190, ' ', 224, 164, 184, 224, 164, 174, 224, 164, 149, 224, 164, 190, 224, 164, 178, 224, 165, 128, 224, 164, 168, ' ', 224, 164, 137, 224, 164, 170, 224, 164, 175, 224, 165, 139, 224, 164, 151, ' ', 224, 164, 149, 224, 164, 174, ' ', 224, 164, 148, 224, 164, 176, ' ', 224, 164, 170, 224, 165, 141, 224, 164, 176, 224, 164, 190, 224, 164, 175, 224, 164, 131, ' ', 224, 164, 137, 224, 164, 164, 224, 165, 141, 224, 164, 164, 224, 164, 176, 224, 165, 128, ' ', 224, 164, 173, 224, 164, 190, 224, 164, 176, 224, 164, 164, ' ', 224, 164, 149, 224, 165, 135, ' ', 224, 164, 178, 224, 164, 191, 224, 164, 143, ' ', 224, 164, 185, 224, 165, 139, 224, 164, 164, 224, 164, 190, ' ', 224, 164, 185, 224, 165, 136, 224, 165, 164, ' ', 224, 164, 135, 224, 164, 184, 224, 164, 149, 224, 165, 135, ' ', 224, 164, 133, 224, 164, 164, 224, 164, 191, 224, 164, 176, 224, 164, 191, 224, 164, 149, 224, 165, 141, 224, 164, 164, ' ', 224, 164, 173, 224, 164, 190, 224, 164, 176, 224, 164, 164, 224, 164, 181, 224, 164, 176, 224, 165, 141, 224, 164, 183, ' ', 224, 164, 149, 224, 165, 139, ' ', 224, 164, 181, 224, 165, 136, 224, 164, 166, 224, 164, 191, 224, 164, 149, ' ', 224, 164, 149, 224, 164, 190, 224, 164, 178, ' ', 224, 164, 184, 224, 165, 135, ' ', 224, 164, 134, 224, 164, 176, 224, 165, 141, 224, 164, 175, 224, 164, 190, 224, 164, 181, 224, 164, 176, 224, 165, 141, 224, 164, 164, ' ', '"', 224, 164, 156, 224, 164, 174, 224, 165, 141, 224, 164, 172, 224, 165, 130, 224, 164, 166, 224, 165, 141, 224, 164, 181, 224, 165, 128, 224, 164, 170, '"', ' ', 224, 164, 148, 224, 164, 176, ' ', '"', 224, 164, 133, 224, 164, 156, 224, 164, 168, 224, 164, 190, 224, 164, 173, 224, 164, 166, 224, 165, 135, 224, 164, 182, '"', ' ', 224, 164, 149, 224, 165, 135, ' ', 224, 164, 168, 224, 164, 190, 224, 164, 174, ' ', 224, 164, 184, 224, 165, 135, ' ', 224, 164, 173, 224, 165, 128, ' ', 224, 164, 156, 224, 164, 190, 224, 164, 168, 224, 164, 190, ' ', 224, 164, 156, 224, 164, 190, 224, 164, 164, 224, 164, 190, ' ', 224, 164, 176, 224, 164, 185, 224, 164, 190, ' ', 224, 164, 185, 224, 165, 136, 224, 165, 164, ' ', 224, 164, 172, 224, 164, 185, 224, 165, 129, 224, 164, 164, ' ', 224, 164, 170, 224, 164, 185, 224, 164, 178, 224, 165, 135, ' ', 224, 164, 175, 224, 164, 185, ' ', 224, 164, 166, 224, 165, 135, 224, 164, 182, ' ', '\'', 224, 164, 184, 224, 165, 139, 224, 164, 168, 224, 165, 135, ' ', 224, 164, 149, 224, 165, 128, ' ', 224, 164, 154, 224, 164, 191, 224, 164, 161, 224, 164, 188, 224, 164, 191, 224, 164, 175, 224, 164, 190, '\'', ' ', 224, 164, 149, 224, 165, 135, ' ', 224, 164, 176, 224, 165, 130, 224, 164, 170, ' ', 224, 164, 174, 224, 165, 135, 224, 164, 130, ' ', 224, 164, 156, 224, 164, 190, 224, 164, 168, 224, 164, 190, ' ', 224, 164, 156, 224, 164, 190, 224, 164, 164, 224, 164, 190, ' ', 224, 164, 165, 224, 164, 190, 224, 165, 164, '[', '2', ']', 13, 10, 13, 10, 'F', 'r', 'e', 'n', 'c', 'h', ':', 13, 10, 13, 10, 'L', 'a', ' ', 'F', 'r', 'a', 'n', 'c', 'e', ',', ' ', 'e', 'n', ' ', 'f', 'o', 'r', 'm', 'e', ' ', 'l', 'o', 'n', 'g', 'u', 'e', ' ', 'l', 'a', ' ', 'R', 195, 169, 'p', 'u', 'b', 'l', 'i', 'q', 'u', 'e', ' ', 'f', 'r', 'a', 'n', 195, 167, 'a', 'i', 's', 'e', ',', ' ', 'e', 's', 't', ' ', 'u', 'n', 'e', ' ', 'r', 195, 169, 'p', 'u', 'b', 'l', 'i', 'q', 'u', 'e', ' ', 'c', 'o', 'n', 's', 't', 'i', 't', 'u', 't', 'i', 'o', 'n', 'n', 'e', 'l', 'l', 'e', ' ', 'u', 'n', 'i', 't', 'a', 'i', 'r', 'e', ' ', 'd', 'o', 'n', 't', ' ', 'l', 'a', ' ', 'm', 'a', 'j', 'e', 'u', 'r', 'e', ' ', 'p', 'a', 'r', 't', 'i', 'e', ' ', 'd', 'u', ' ', 't', 'e', 'r', 'r', 'i', 't', 'o', 'i', 'r', 'e', ' ', 'e', 't', ' ', 'd', 'e', ' ', 'l', 'a', ' ', 'p', 'o', 'p', 'u', 'l', 'a', 't', 'i', 'o', 'n', ' ', 's', 'o', 'n', 't', ' ', 's', 'i', 't', 'u', 195, 169, 's', ' ', 'e', 'n', ' ', 'E', 'u', 'r', 'o', 'p', 'e', ' ', 'o', 'c', 'c', 'i', 'd', 'e', 'n', 't', 'a', 'l', 'e', ',', ' ', 'm', 'a', 'i', 's', ' ', 'q', 'u', 'i', ' ', 'c', 'o', 'm', 'p', 'r', 'e', 'n', 'd', ' ', 195, 169, 'g', 'a', 'l', 'e', 'm', 'e', 'n', 't', ' ', 'p', 'l', 'u', 's', 'i', 'e', 'u', 'r', 's', ' ', 'r', 195, 169, 'g', 'i', 'o', 'n', 's', ' ', 'e', 't', ' ', 't', 'e', 'r', 'r', 'i', 't', 'o', 'i', 'r', 'e', 's', ' ', 'r', 195, 169, 'p', 'a', 'r', 't', 'i', 's', ' ', 'd', 'a', 'n', 's', ' ', 'l', 'e', 's', ' ', 'A', 'm', 195, 169, 'r', 'i', 'q', 'u', 'e', 's', ',', ' ', 'l', 226, 128, 153, 'o', 'c', 195, 169, 'a', 'n', ' ', 'I', 'n', 'd', 'i', 'e', 'n', ' ', 'e', 't', ' ', 'l', '\'', 'o', 'c', 195, 169, 'a', 'n', ' ', 'P', 'a', 'c', 'i', 'f', 'i', 'q', 'u', 'e', '.', ' ', 'E', 'l', 'l', 'e', ' ', 'a', ' ', 'p', 'o', 'u', 'r', ' ', 'c', 'a', 'p', 'i', 't', 'a', 'l', 'e', ' ', 'P', 'a', 'r', 'i', 's', ',', ' ', 'p', 'o', 'u', 'r', ' ', 'l', 'a', 'n', 'g', 'u', 'e', ' ', 'o', 'f', 'f', 'i', 'c', 'i', 'e', 'l', 'l', 'e', ' ', 'l', 'e', ' ', 'f', 'r', 'a', 'n', 195, 167, 'a', 'i', 's', ' ', 'e', 't', ' ', 'p', 'o', 'u', 'r', ' ', 'm', 'o', 'n', 'n', 'a', 'i', 'e', ' ', 'l', 226, 128, 153, 'e', 'u', 'r', 'o', '.', ' ', 'S', 'a', ' ', 'd', 'e', 'v', 'i', 's', 'e', ' ', 'e', 's', 't', ' ', 194, 171, ' ', 'L', 'i', 'b', 'e', 'r', 't', 195, 169, ',', ' ', 195, 137, 'g', 'a', 'l', 'i', 't', 195, 169, ',', ' ', 'F', 'r', 'a', 't', 'e', 'r', 'n', 'i', 't', 195, 169, ' ', 194, 187, ',', ' ', 'e', 't', ' ', 's', 'o', 'n', ' ', 'd', 'r', 'a', 'p', 'e', 'a', 'u', ' ', 'e', 's', 't', ' ', 'c', 'o', 'n', 's', 't', 'i', 't', 'u', 195, 169, ' ', 'd', 'e', ' ', 't', 'r', 'o', 'i', 's', ' ', 'b', 'a', 'n', 'd', 'e', 's', ' ', 'v', 'e', 'r', 't', 'i', 'c', 'a', 'l', 'e', 's', ' ', 'r', 'e', 's', 'p', 'e', 'c', 't', 'i', 'v', 'e', 'm', 'e', 'n', 't', ' ', 'b', 'l', 'e', 'u', 'e', ',', ' ', 'b', 'l', 'a', 'n', 'c', 'h', 'e', ' ', 'e', 't', ' ', 'r', 'o', 'u', 'g', 'e', '.', ' ', 'S', 'o', 'n', ' ', 'h', 'y', 'm', 'n', 'e', ' ', 'e', 's', 't', ' ', 'L', 'a', ' ', 'M', 'a', 'r', 's', 'e', 'i', 'l', 'l', 'a', 'i', 's', 'e', '.', ' ', 'S', 'o', 'n', ' ', 'p', 'r', 'i', 'n', 'c', 'i', 'p', 'e', ' ', 'e', 's', 't', ' ', 'g', 'o', 'u', 'v', 'e', 'r', 'n', 'e', 'm', 'e', 'n', 't', ' ', 'd', 'u', ' ', 'p', 'e', 'u', 'p', 'l', 'e', ',', ' ', 'p', 'a', 'r', ' ', 'l', 'e', ' ', 'p', 'e', 'u', 'p', 'l', 'e', ' ', 'e', 't', ' ', 'p', 'o', 'u', 'r', ' ', 'l', 'e', ' ', 'p', 'e', 'u', 'p', 'l', 'e', '[', '3', ']', '.', 13, 10, 13, 10, 'L', 'a', ' ', 'F', 'r', 'a', 'n', 'c', 'e', ' ', 'e', 's', 't', ' ', 'u', 'n', ' ', 'p', 'a', 'y', 's', ' ', 'a', 'n', 'c', 'i', 'e', 'n', ',', ' ', 'f', 'o', 'r', 'm', 195, 169, ' ', 'a', 'u', ' ', 'H', 'a', 'u', 't', ' ', 'M', 'o', 'y', 'e', 'n', ' ', 195, 130, 'g', 'e', '.', ' ', 'A', 'u', ' ', 'X', 'I', 'X', 'e', ' ', 's', 'i', 195, 168, 'c', 'l', 'e', ' ', 'e', 't', ' ', 'd', 'a', 'n', 's', ' ', 'l', 'a', ' ', 'p', 'r', 'e', 'm', 'i', 195, 168, 'r', 'e', ' ', 'm', 'o', 'i', 't', 'i', 195, 169, ' ', 'd', 'u', ' ', 'X', 'X', 'e', ' ', 's', 'i', 195, 168, 'c', 'l', 'e', ',', ' ', 'e', 'l', 'l', 'e', ' ', 'p', 'o', 's', 's', 195, 168, 'd', 'e', ' ', 'u', 'n', ' ', 'v', 'a', 's', 't', 'e', ' ', 'e', 'm', 'p', 'i', 'r', 'e', ' ', 'c', 'o', 'l', 'o', 'n', 'i', 'a', 'l', '.', ' ', 195, 128, ' ', 'p', 'a', 'r', 't', 'i', 'r', ' ', 'd', 'e', 's', ' ', 'a', 'n', 'n', 195, 169, 'e', 's', ' ', '1', '9', '5', '0', ',', ' ', 'e', 'l', 'l', 'e', ' ', 'e', 's', 't', ' ', 'l', 226, 128, 153, 'u', 'n', ' ', 'd', 'e', 's', ' ', 'a', 'c', 't', 'e', 'u', 'r', 's', ' ', 'd', 'e', ' ', 'l', 'a', ' ', 'c', 'o', 'n', 's', 't', 'r', 'u', 'c', 't', 'i', 'o', 'n', ' ', 'd', 'e', ' ', 'l', 226, 128, 153, 'U', 'n', 'i', 'o', 'n', ' ', 'e', 'u', 'r', 'o', 'p', 195, 169, 'e', 'n', 'n', 'e', '.', ' ', 'E', 'l', 'l', 'e', ' ', 'e', 's', 't', ' ', 'u', 'n', 'e', ' ', 'p', 'u', 'i', 's', 's', 'a', 'n', 'c', 'e', ' ', 'n', 'u', 'c', 'l', 195, 169, 'a', 'i', 'r', 'e', ',', ' ', 'e', 't', ' ', 'l', 226, 128, 153, 'u', 'n', ' ', 'd', 'e', 's', ' ', 'c', 'i', 'n', 'q', ' ', 'm', 'e', 'm', 'b', 'r', 'e', 's', ' ', 'p', 'e', 'r', 'm', 'a', 'n', 'e', 'n', 't', 's', ' ', 'd', 'u', ' ', 'C', 'o', 'n', 's', 'e', 'i', 'l', ' ', 'd', 'e', ' ', 's', 195, 169, 'c', 'u', 'r', 'i', 't', 195, 169, ' ', 'd', 'e', 's', ' ', 'N', 'a', 't', 'i', 'o', 'n', 's', ' ', 'u', 'n', 'i', 'e', 's', '.', ' ', 'L', 'a', ' ', 'F', 'r', 'a', 'n', 'c', 'e', ' ', 'j', 'o', 'u', 'e', ' ', 'u', 'n', ' ', 'r', 195, 180, 'l', 'e', ' ', 'i', 'm', 'p', 'o', 'r', 't', 'a', 'n', 't', ' ', 'd', 'a', 'n', 's', ' ', 'l', 226, 128, 153, 'h', 'i', 's', 't', 'o', 'i', 'r', 'e', ' ', 'm', 'o', 'n', 'd', 'i', 'a', 'l', 'e', ' ', 'p', 'a', 'r', ' ', 'l', 226, 128, 153, 'i', 'n', 'f', 'l', 'u', 'e', 'n', 'c', 'e', ' ', 'd', 'e', ' ', 's', 'a', ' ', 'c', 'u', 'l', 't', 'u', 'r', 'e', ' ', 'e', 't', ' ', 'd', 'e', ' ', 's', 'e', 's', ' ', 'v', 'a', 'l', 'e', 'u', 'r', 's', ' ', 'd', 195, 169, 'm', 'o', 'c', 'r', 'a', 't', 'i', 'q', 'u', 'e', 's', ',', ' ', 'l', 'a', 195, 175, 'q', 'u', 'e', 's', ' ', 'e', 't', ' ', 'r', 195, 169, 'p', 'u', 'b', 'l', 'i', 'c', 'a', 'i', 'n', 'e', 's', '.', 13, 10, 13, 10, 'L', 'a', ' ', 'F', 'r', 'a', 'n', 'c', 'e', ' ', 'a', ',', ' ', 'e', 'n', ' ', '2', '0', '1', '0', ',', ' ', 'l', 'e', ' ', 'c', 'i', 'n', 'q', 'u', 'i', 195, 168, 'm', 'e', ' ', 'p', 'l', 'u', 's', ' ', 'i', 'm', 'p', 'o', 'r', 't', 'a', 'n', 't', ' ', 'p', 'r', 'o', 'd', 'u', 'i', 't', ' ', 'i', 'n', 't', 195, 169, 'r', 'i', 'e', 'u', 'r', ' ', 'b', 'r', 'u', 't', ' ', 'a', 'u', ' ', 'm', 'o', 'n', 'd', 'e', '.', ' ', 'S', 'o', 'n', ' ', 195, 169, 'c', 'o', 'n', 'o', 'm', 'i', 'e', ',', ' ', 'd', 'e', ' ', 't', 'y', 'p', 'e', ' ', 'c', 'a', 'p', 'i', 't', 'a', 'l', 'i', 's', 't', 'e', ' ', 'a', 'v', 'e', 'c', ' ', 'u', 'n', 'e', ' ', 'i', 'n', 't', 'e', 'r', 'v', 'e', 'n', 't', 'i', 'o', 'n', ' ', 195, 169, 't', 'a', 't', 'i', 'q', 'u', 'e', ' ', 'a', 's', 's', 'e', 'z', ' ', 'f', 'o', 'r', 't', 'e', ',', ' ', 'f', 'a', 'i', 't', ' ', 'd', 226, 128, 153, 'e', 'l', 'l', 'e', ' ', 'u', 'n', ' ', 'd', 'e', 's', ' ', 'l', 'e', 'a', 'd', 'e', 'r', 's', ' ', 'm', 'o', 'n', 'd', 'i', 'a', 'u', 'x', ' ', 'd', 'a', 'n', 's', ' ', 'l', 'e', 's', ' ', 's', 'e', 'c', 't', 'e', 'u', 'r', 's', ' ', 'd', 'e', ' ', 'l', 226, 128, 153, 'a', 'g', 'r', 'o', 'a', 'l', 'i', 'm', 'e', 'n', 't', 'a', 'i', 'r', 'e', ',', ' ', 'd', 'e', ' ', 'l', 226, 128, 153, 'a', 195, 169, 'r', 'o', 'n', 'a', 'u', 't', 'i', 'q', 'u', 'e', ',', ' ', 'd', 'e', ' ', 'l', 226, 128, 153, 'a', 'u', 't', 'o', 'm', 'o', 'b', 'i', 'l', 'e', ',', ' ', 'd', 'e', 's', ' ', 'p', 'r', 'o', 'd', 'u', 'i', 't', 's', ' ', 'd', 'e', ' ', 'l', 'u', 'x', 'e', ',', ' ', 'd', 'u', ' ', 't', 'o', 'u', 'r', 'i', 's', 'm', 'e', ' ', 'e', 't', ' ', 'd', 'u', ' ', 'n', 'u', 'c', 'l', 195, 169, 'a', 'i', 'r', 'e', '.', 13, 10, 13, 10, 'P', 'e', 'u', 'p', 'l', 195, 169, 'e', ' ', 'd', 'e', ' ', '6', '5', ',', '3', ' ', 'm', 'i', 'l', 'l', 'i', 'o', 'n', 's', ' ', 'd', 226, 128, 153, 'h', 'a', 'b', 'i', 't', 'a', 'n', 't', 's', ' ', 'a', 'u', ' ', '1', 'e', 'r', ' ', 'j', 'a', 'n', 'v', 'i', 'e', 'r', ' ', '2', '0', '1', '2', '[', '4', ']', ',', ' ', 'l', 'a', ' ', 'F', 'r', 'a', 'n', 'c', 'e', ' ', 'e', 's', 't', ' ', 'u', 'n', ' ', 'p', 'a', 'y', 's', ' ', 'd', 195, 169, 'v', 'e', 'l', 'o', 'p', 'p', 195, 169, ',', ' ', 'a', 'v', 'e', 'c', ' ', 'u', 'n', ' ', 'i', 'n', 'd', 'i', 'c', 'e', ' ', 'd', 'e', ' ', 'd', 195, 169, 'v', 'e', 'l', 'o', 'p', 'p', 'e', 'm', 'e', 'n', 't', ' ', 'h', 'u', 'm', 'a', 'i', 'n', ' ', 't', 'r', 195, 168, 's', ' ', 195, 169, 'l', 'e', 'v', 195, 169, '[', '5', ']', '.', 13, 10, 13, 10, 'L', 'a', ' ', 'F', 'r', 'a', 'n', 'c', 'e', ' ', 'm', 195, 169, 't', 'r', 'o', 'p', 'o', 'l', 'i', 't', 'a', 'i', 'n', 'e', ' ', 'e', 's', 't', ' ', 's', 'i', 't', 'u', 195, 169, 'e', ' ', 195, 160, ' ', 'l', 226, 128, 153, 'u', 'n', 'e', ' ', 'd', 'e', 's', ' ', 'e', 'x', 't', 'r', 195, 169, 'm', 'i', 't', 195, 169, 's', ' ', 'o', 'c', 'c', 'i', 'd', 'e', 'n', 't', 'a', 'l', 'e', 's', ' ', 'd', 'e', ' ', 'l', 226, 128, 153, 'E', 'u', 'r', 'o', 'p', 'e', '.', ' ', 'E', 'l', 'l', 'e', ' ', 'e', 's', 't', ' ', 'b', 'o', 'r', 'd', 195, 169, 'e', ' ', 'p', 'a', 'r', ' ', 'l', 'a', ' ', 'm', 'e', 'r', ' ', 'd', 'u', ' ', 'N', 'o', 'r', 'd', ' ', 'a', 'u', ' ', 'n', 'o', 'r', 'd', ',', ' ', 'l', 'a', ' ', 'M', 'a', 'n', 'c', 'h', 'e', ' ', 'a', 'u', ' ', 'n', 'o', 'r', 'd', '-', 'o', 'u', 'e', 's', 't', ',', ' ', 'l', 226, 128, 153, 'o', 'c', 195, 169, 'a', 'n', ' ', 'A', 't', 'l', 'a', 'n', 't', 'i', 'q', 'u', 'e', ' ', 195, 160, ' ', 'l', 226, 128, 153, 'o', 'u', 'e', 's', 't', ' ', 'e', 't', ' ', 'l', 'a', ' ', 'm', 'e', 'r', ' ', 'M', 195, 169, 'd', 'i', 't', 'e', 'r', 'r', 'a', 'n', 195, 169, 'e', ' ', 'a', 'u', ' ', 's', 'u', 'd', '-', 'e', 's', 't', '.', ' ', 'E', 'l', 'l', 'e', ' ', 'e', 's', 't', ' ', 'f', 'r', 'o', 'n', 't', 'a', 'l', 'i', 195, 168, 'r', 'e', ' ', 'd', 'e', ' ', 'l', 'a', ' ', 'B', 'e', 'l', 'g', 'i', 'q', 'u', 'e', ' ', 'e', 't', ' ', 'd', 'u', ' ', 'L', 'u', 'x', 'e', 'm', 'b', 'o', 'u', 'r', 'g', ' ', 'a', 'u', ' ', 'n', 'o', 'r', 'd', '-', 'e', 's', 't', ',', ' ', 'd', 'e', ' ', 'l', 226, 128, 153, 'A', 'l', 'l', 'e', 'm', 'a', 'g', 'n', 'e', ' ', 'e', 't', ' ', 'd', 'e', ' ', 'l', 'a', ' ', 'S', 'u', 'i', 's', 's', 'e', ' ', 195, 160, ' ', 'l', 226, 128, 153, 'e', 's', 't', ',', ' ', 'd', 'e', ' ', 'l', 226, 128, 153, 'I', 't', 'a', 'l', 'i', 'e', ' ', 'e', 't', ' ', 'd', 'e', ' ', 'M', 'o', 'n', 'a', 'c', 'o', ' ', 'a', 'u', ' ', 's', 'u', 'd', '-', 'e', 's', 't', ',', ' ', 'd', 'e', ' ', 'l', 226, 128, 153, 'E', 's', 'p', 'a', 'g', 'n', 'e', ' ', 'e', 't', ' ', 'd', 226, 128, 153, 'A', 'n', 'd', 'o', 'r', 'r', 'e', ' ', 'a', 'u', ' ', 's', 'u', 'd', '-', 'o', 'u', 'e', 's', 't', '.', ' ', 'S', 'i', ' ', 'l', 'e', 's', ' ', 'f', 'r', 'o', 'n', 't', 'i', 195, 168, 'r', 'e', 's', ' ', 'd', 'u', ' ', 's', 'u', 'd', ' ', 'd', 'u', ' ', 'p', 'a', 'y', 's', ' ', 'c', 'o', 'r', 'r', 'e', 's', 'p', 'o', 'n', 'd', 'e', 'n', 't', ' ', 195, 160, ' ', 'd', 'e', 's', ' ', 'm', 'a', 's', 's', 'i', 'f', 's', ' ', 'm', 'o', 'n', 't', 'a', 'g', 'n', 'e', 'u', 'x', ',', ' ', 'l', 'e', 's', ' ', 'f', 'r', 'o', 'n', 't', 'i', 195, 168, 'r', 'e', 's', ' ', 'd', 'u', ' ', 'n', 'o', 'r', 'd', '-', 'e', 's', 't', ' ', 'n', 'e', ' ', 'c', 'o', 'r', 'r', 'e', 's', 'p', 'o', 'n', 'd', 'e', 'n', 't', ' ', 195, 160, ' ', 'a', 'u', 'c', 'u', 'n', 'e', ' ', 'l', 'i', 'm', 'i', 't', 'e', ' ', 'g', 195, 169, 'o', 'g', 'r', 'a', 'p', 'h', 'i', 'q', 'u', 'e', '[', 'n', 'o', 't', 'e', ' ', '6', ']', ' ', 'n', 'i', ' ', 'l', 'i', 'n', 'g', 'u', 'i', 's', 't', 'i', 'q', 'u', 'e', '[', 'n', 'o', 't', 'e', ' ', '7', ']', '.', ' ', 'L', 'a', ' ', 'F', 'r', 'a', 'n', 'c', 'e', ' ', 'm', 195, 169, 't', 'r', 'o', 'p', 'o', 'l', 'i', 't', 'a', 'i', 'n', 'e', ' ', 'c', 'o', 'm', 'p', 'r', 'e', 'n', 'd', ' ', 'p', 'l', 'u', 's', 'i', 'e', 'u', 'r', 's', ' ', 195, 174, 'l', 'e', 's', ',', ' ', 'n', 'o', 't', 'a', 'm', 'm', 'e', 'n', 't', ' ', 'l', 'a', ' ', 'C', 'o', 'r', 's', 'e', ' ', 'e', 't', ' ', 'd', 'e', 's', ' ', 195, 174, 'l', 'e', 's', ' ', 'c', 195, 180, 't', 'i', 195, 168, 'r', 'e', 's', '.', ' ', 'L', 'a', ' ', 'm', 195, 169, 't', 'r', 'o', 'p', 'o', 'l', 'e', ' ', 'e', 's', 't', ' ', 'c', 'o', 'm', 'p', 'r', 'i', 's', 'e', ' ', 'e', 'n', 't', 'r', 'e', ' ', 'l', 'e', 's', ' ', 'l', 'a', 't', 'i', 't', 'u', 'd', 'e', 's', ' ', '4', '2', 194, 176, '1', '9', '\'', '4', '6', '"', ' ', 'N', ' ', 'e', 't', ' ', '5', '1', 194, 176, '5', '\'', '4', '7', '"', ' ', 'N', ',', ' ', 'a', 'i', 'n', 's', 'i', ' ', 'q', 'u', 'e', ' ', 'l', 'e', 's', ' ', 'l', 'o', 'n', 'g', 'i', 't', 'u', 'd', 'e', 's', ' ', '4', 194, 176, '4', '6', '\'', ' ', 'O', ' ', 'e', 't', ' ', '8', 194, 176, '1', '4', '\'', '4', '2', '"', ' ', 'E', '.', 13, 10, 13, 10, 'L', 'a', ' ', 'F', 'r', 'a', 'n', 'c', 'e', ' ', 'c', 'o', 'm', 'p', 'r', 'e', 'n', 'd', ' ', 195, 169, 'g', 'a', 'l', 'e', 'm', 'e', 'n', 't', ' ', 'd', 'e', ' ', 'n', 'o', 'm', 'b', 'r', 'e', 'u', 'x', ' ', 't', 'e', 'r', 'r', 'i', 't', 'o', 'i', 'r', 'e', 's', ' ', 's', 'i', 't', 'u', 195, 169, 's', ' ', 'e', 'n', '-', 'd', 'e', 'h', 'o', 'r', 's', ' ', 'd', 'u', ' ', 'c', 'o', 'n', 't', 'i', 'n', 'e', 'n', 't', ' ', 'e', 'u', 'r', 'o', 'p', 195, 169, 'e', 'n', ',', ' ', 'c', 'o', 'u', 'r', 'a', 'm', 'm', 'e', 'n', 't', ' ', 'a', 'p', 'p', 'e', 'l', 195, 169, 's', ' ', 't', 'e', 'r', 'r', 'i', 't', 'o', 'i', 'r', 'e', 's', ' ', 'd', 226, 128, 153, 'o', 'u', 't', 'r', 'e', '-', 'm', 'e', 'r', ',', ' ', 'n', 'a', 'g', 'u', 195, 168, 'r', 'e', ' ', 'D', 'O', 'M', '-', 'T', 'O', 'M', ',', ' ', 'q', 'u', 'i', ' ', 'l', 'u', 'i', ' ', 'p', 'e', 'r', 'm', 'e', 't', 't', 'e', 'n', 't', ' ', 'd', 226, 128, 153, 195, 170, 't', 'r', 'e', ' ', 'p', 'r', 195, 169, 's', 'e', 'n', 't', 'e', ' ', 'd', 'a', 'n', 's', ' ', 't', 'o', 'u', 's', ' ', 'l', 'e', 's', ' ', 'o', 'c', 195, 169, 'a', 'n', 's', '.', ' ', 'C', 'e', 's', ' ', 't', 'e', 'r', 'r', 'i', 't', 'o', 'i', 'r', 'e', 's', ' ', 'a', 'u', 'x', ' ', 's', 't', 'a', 't', 'u', 't', 's', ' ', 'v', 'a', 'r', 'i', 195, 169, 's', ' ', 's', 'o', 'n', 't', '[', '6', ']', ' ', ':', 13, 10, 13, 10, 's', 'u', 'r', ' ', 'l', 'e', ' ', 'c', 'o', 'n', 't', 'i', 'n', 'e', 'n', 't', ' ', 's', 'u', 'd', '-', 'a', 'm', 195, 169, 'r', 'i', 'c', 'a', 'i', 'n', ' ', ':', ' ', 'l', 'a', ' ', 'G', 'u', 'y', 'a', 'n', 'e', ' ', ';', 13, 10, 'd', 'a', 'n', 's', ' ', 'l', 226, 128, 153, 'o', 'c', 195, 169, 'a', 'n', ' ', 'A', 't', 'l', 'a', 'n', 't', 'i', 'q', 'u', 'e', ' ', '(', 'A', 'n', 't', 'i', 'l', 'l', 'e', 's', ')', ' ', ':', ' ', 'l', 'a', ' ', 'G', 'u', 'a', 'd', 'e', 'l', 'o', 'u', 'p', 'e', ',', ' ', 'l', 'a', ' ', 'M', 'a', 'r', 't', 'i', 'n', 'i', 'q', 'u', 'e', ',', ' ', 'S', 'a', 'i', 'n', 't', '-', 'P', 'i', 'e', 'r', 'r', 'e', '-', 'e', 't', '-', 'M', 'i', 'q', 'u', 'e', 'l', 'o', 'n', ',', ' ', 'S', 'a', 'i', 'n', 't', '-', 'M', 'a', 'r', 't', 'i', 'n', ' ', 'e', 't', ' ', 'S', 'a', 'i', 'n', 't', '-', 'B', 'a', 'r', 't', 'h', 195, 169, 'l', 'e', 'm', 'y', ' ', ';', 13, 10, 'd', 'a', 'n', 's', ' ', 'l', 226, 128, 153, 'o', 'c', 195, 169, 'a', 'n', ' ', 'P', 'a', 'c', 'i', 'f', 'i', 'q', 'u', 'e', ' ', ':', ' ', 'l', 'a', ' ', 'P', 'o', 'l', 'y', 'n', 195, 169, 's', 'i', 'e', ' ', 'f', 'r', 'a', 'n', 195, 167, 'a', 'i', 's', 'e', ',', ' ', 'l', 'a', ' ', 'N', 'o', 'u', 'v', 'e', 'l', 'l', 'e', '-', 'C', 'a', 'l', 195, 169, 'd', 'o', 'n', 'i', 'e', ',', ' ', 'W', 'a', 'l', 'l', 'i', 's', '-', 'e', 't', '-', 'F', 'u', 't', 'u', 'n', 'a', ' ', 'e', 't', ' ', 'C', 'l', 'i', 'p', 'p', 'e', 'r', 't', 'o', 'n', ' ', ';', 13, 10, 'd', 'a', 'n', 's', ' ', 'l', 226, 128, 153, 'o', 'c', 195, 169, 'a', 'n', ' ', 'I', 'n', 'd', 'i', 'e', 'n', ' ', ':', ' ', 'L', 'a', ' ', 'R', 195, 169, 'u', 'n', 'i', 'o', 'n', ',', ' ', 'M', 'a', 'y', 'o', 't', 't', 'e', ',', ' ', 'l', 'e', 's', ' ', 195, 142, 'l', 'e', 's', ' ', 195, 137, 'p', 'a', 'r', 's', 'e', 's', ',', ' ', 'l', 'e', 's', ' ', 195, 142, 'l', 'e', 's', ' ', 'C', 'r', 'o', 'z', 'e', 't', ',', ' ', 'l', 'e', 's', ' ', 195, 142, 'l', 'e', 's', ' ', 'K', 'e', 'r', 'g', 'u', 'e', 'l', 'e', 'n', ' ', 'e', 't', ' ', 'S', 'a', 'i', 'n', 't', '-', 'P', 'a', 'u', 'l', '-', 'e', 't', '-', 'A', 'm', 's', 't', 'e', 'r', 'd', 'a', 'm', ' ', ';', 13, 10, 'e', 'n', ' ', 'A', 'n', 't', 'a', 'r', 'c', 't', 'i', 'q', 'u', 'e', ' ', ':', ' ', 'l', 'a', ' ', 'T', 'e', 'r', 'r', 'e', ' ', 'A', 'd', 195, 169, 'l', 'i', 'e', '[', 'n', 'o', 't', 'e', ' ', '8', ']', '.', 13, 10, 195, 128, ' ', 't', 'r', 'a', 'v', 'e', 'r', 's', ' ', 's', 'e', 's', ' ', 'c', 'o', 'l', 'l', 'e', 'c', 't', 'i', 'v', 'i', 't', 195, 169, 's', ' ', 'u', 'l', 't', 'r', 'a', '-', 'm', 'a', 'r', 'i', 'n', 'e', 's', ',', ' ', 'l', 'a', ' ', 'F', 'r', 'a', 'n', 'c', 'e', ' ', 'p', 'o', 's', 's', 195, 168, 'd', 'e', ' ', 195, 169, 'g', 'a', 'l', 'e', 'm', 'e', 'n', 't', ' ', 'd', 'e', 's', ' ', 'f', 'r', 'o', 'n', 't', 'i', 195, 168, 'r', 'e', 's', ' ', 't', 'e', 'r', 'r', 'e', 's', 't', 'r', 'e', 's', ' ', 'a', 'v', 'e', 'c', ' ', 'l', 'e', ' ', 'B', 'r', 195, 169, 's', 'i', 'l', ' ', 'e', 't', ' ', 'l', 'e', ' ', 'S', 'u', 'r', 'i', 'n', 'a', 'm', 'e', ',', ' ', 'a', 'i', 'n', 's', 'i', ' ', 'q', 'u', 226, 128, 153, 'a', 'v', 'e', 'c', ' ', 'l', 'e', 's', ' ', 'P', 'a', 'y', 's', '-', 'B', 'a', 's', ' ', 'v', 'i', 'a', ' ', 'l', 'a', ' ', 'p', 'a', 'r', 't', 'i', 'e', ' ', 'f', 'r', 'a', 'n', 195, 167, 'a', 'i', 's', 'e', ' ', 'd', 'e', ' ', 'S', 'a', 'i', 'n', 't', '-', 'M', 'a', 'r', 't', 'i', 'n', '.', 13, 10, 13, 10, 'L', 'a', ' ', 's', 'u', 'p', 'e', 'r', 'f', 'i', 'c', 'i', 'e', ' ', 'd', 'e', ' ', 'l', 'a', ' ', 'F', 'r', 'a', 'n', 'c', 'e', ' ', 'e', 's', 't', ' ', 'd', 'e', ' ', '6', '7', '0', ' ', '9', '2', '2', ' ', 'k', 'm', 194, 178, ',', ' ', 'o', 'u', ' ', '5', '4', '7', ' ', '0', '3', '0', ' ', 's', 'a', 'n', 's', ' ', 'c', 'o', 'm', 'p', 't', 'a', 'b', 'i', 'l', 'i', 's', 'e', 'r', ' ', 'l', 226, 128, 153, 'o', 'u', 't', 'r', 'e', '-', 'm', 'e', 'r', '[', '7', ']', '.', ' ', 'E', 'l', 'l', 'e', ' ', 'e', 's', 't', ' ', 'l', 'e', ' ', '4', '1', 'e', ' ', 'p', 'l', 'u', 's', ' ', 'g', 'r', 'a', 'n', 'd', ' ', 195, 137, 't', 'a', 't', ' ', 'd', 'u', ' ', 'm', 'o', 'n', 'd', 'e', ' ', 'p', 'a', 'r', ' ', 's', 'a', ' ', 's', 'u', 'r', 'f', 'a', 'c', 'e', ' ', 't', 'e', 'r', 'r', 'e', 's', 't', 'r', 'e', '[', '7', ']', ' ', 'e', 't', ' ', 'l', 'e', ' ', 'd', 'e', 'u', 'x', 'i', 195, 168, 'm', 'e', ' ', 'p', 'a', 'r', ' ', 's', 'a', ' ', 'z', 'o', 'n', 'e', ' ', 195, 169, 'c', 'o', 'n', 'o', 'm', 'i', 'q', 'u', 'e', ' ', 'e', 'x', 'c', 'l', 'u', 's', 'i', 'v', 'e', '[', '8', ']', '.', ' ', 'E', 'l', 'l', 'e', ' ', 'e', 's', 't', ' ', 'e', 'n', ' ', 'o', 'u', 't', 'r', 'e', ' ', 'l', 'e', ' ', 't', 'r', 'o', 'i', 's', 'i', 195, 168, 'm', 'e', ' ', 'p', 'l', 'u', 's', ' ', 'g', 'r', 'a', 'n', 'd', ' ', 'p', 'a', 'y', 's', ' ', 'd', 226, 128, 153, 'E', 'u', 'r', 'o', 'p', 'e', ',', ' ', 'a', 'p', 'r', 195, 168, 's', ' ', 'l', 'a', ' ', 'R', 'u', 's', 's', 'i', 'e', ' ', 'e', 't', ' ', 'l', 226, 128, 153, 'U', 'k', 'r', 'a', 'i', 'n', 'e', ',', ' ', 'd', 'e', 'u', 'x', 'i', 195, 168, 'm', 'e', ' ', 's', 'i', ' ', 'o', 'n', ' ', 'i', 'n', 'c', 'l', 'u', 't', ' ', 'l', 'e', 's', ' ', 'd', 195, 169, 'p', 'a', 'r', 't', 'e', 'm', 'e', 'n', 't', 's', ' ', 'u', 'l', 't', 'r', 'a', '-', 'm', 'a', 'r', 'i', 'n', 's', ',', ' ', 'e', 't', ' ', 'l', 'e', ' ', 'p', 'l', 'u', 's', ' ', 'g', 'r', 'a', 'n', 'd', ' ', 'd', 'e', ' ', 'l', 226, 128, 153, 'U', 'n', 'i', 'o', 'n', ' ', 'e', 'u', 'r', 'o', 'p', 195, 169, 'e', 'n', 'n', 'e', '[', '7', ']', '.', ' ', 'S', 'o', 'n', ' ', 't', 'e', 'r', 'r', 'i', 't', 'o', 'i', 'r', 'e', ' ', 'm', 195, 169, 't', 'r', 'o', 'p', 'o', 'l', 'i', 't', 'a', 'i', 'n', ' ', 'c', 'o', 'n', 't', 'i', 'n', 'e', 'n', 't', 'a', 'l', ' ', 's', 226, 128, 153, 195, 169, 't', 'e', 'n', 'd', ' ', 's', 'u', 'r', ' ', 'e', 'n', 'v', 'i', 'r', 'o', 'n', ' ', '1', ' ', '0', '0', '0', ' ', 'k', 'm', ' ', 'd', 'u', ' ', 'n', 'o', 'r', 'd', ' ', 'a', 'u', ' ', 's', 'u', 'd', ' ', 'e', 't', ' ', 'd', 226, 128, 153, 'e', 's', 't', ' ', 'e', 'n', ' ', 'o', 'u', 'e', 's', 't', '.', ' ', 'L', 226, 128, 153, 195, 169, 't', 'e', 'n', 'd', 'u', 'e', ' ', 'd', 'e', ' ', 's', 'o', 'n', ' ', 'l', 'i', 't', 't', 'o', 'r', 'a', 'l', ',', ' ', 'o', 'u', 't', 'r', 'e', '-', 'm', 'e', 'r', ' ', 'i', 'n', 'c', 'l', 'u', 's', ',', ' ', 'e', 's', 't', ' ', 'd', 'e', ' ', '8', ' ', '2', '4', '5', ' ', 'k', 'm', '[', '9', ']', '.', 13, 10, 13, 10, 'G', 'r', 'e', 'e', 'k', ':', 13, 10, 13, 10, 206, 151, ' ', 206, 149, 206, 187, 206, 187, 206, 172, 206, 180, 206, 177, ' ', '(', 207, 128, 206, 177, 206, 187, 206, 177, 206, 185, 207, 140, 207, 132, 206, 181, 207, 129, 206, 177, ':', ' ', 225, 188, 153, 206, 187, 206, 187, 206, 172, 207, 130, ',', ' ', 206, 181, 207, 128, 206, 175, 207, 131, 206, 183, 206, 188, 206, 177, ':', ' ', 206, 149, 206, 187, 206, 187, 206, 183, 206, 189, 206, 185, 206, 186, 206, 174, ' ', 206, 148, 206, 183, 206, 188, 206, 191, 206, 186, 207, 129, 206, 177, 207, 132, 206, 175, 206, 177, ')', ' ', 206, 181, 206, 175, 206, 189, 206, 177, 206, 185, ' ', 207, 135, 207, 142, 207, 129, 206, 177, ' ', 207, 128, 206, 191, 207, 133, ' ', 206, 178, 207, 129, 206, 175, 207, 131, 206, 186, 206, 181, 207, 132, 206, 177, 206, 185, ' ', 207, 131, 207, 132, 206, 183, ' ', 206, 189, 206, 191, 207, 132, 206, 185, 206, 191, 206, 177, 206, 189, 206, 177, 207, 132, 206, 191, 206, 187, 206, 185, 206, 186, 206, 174, ' ', 206, 149, 207, 133, 207, 129, 207, 142, 207, 128, 206, 183, ',', ' ', 207, 131, 207, 132, 206, 191, ' ', 206, 189, 206, 191, 207, 132, 206, 185, 207, 140, 207, 132, 206, 181, 207, 129, 206, 191, ' ', 206, 172, 206, 186, 207, 129, 206, 191, ' ', 207, 132, 206, 183, 207, 130, ' ', 206, 146, 206, 177, 206, 187, 206, 186, 206, 177, 206, 189, 206, 185, 206, 186, 206, 174, 207, 130, ' ', 207, 135, 206, 181, 207, 129, 207, 131, 206, 191, 206, 189, 206, 174, 207, 131, 206, 191, 207, 133, ',', ' ', 207, 131, 207, 132, 206, 183, 206, 189, ' ', 206, 145, 206, 189, 206, 177, 207, 132, 206, 191, 206, 187, 206, 185, 206, 186, 206, 174, ' ', 206, 156, 206, 181, 207, 131, 207, 140, 206, 179, 206, 181, 206, 185, 206, 191, '.', 206, 160, 207, 129, 207, 137, 207, 132, 206, 181, 207, 141, 206, 191, 207, 133, 207, 131, 206, 177, ' ', 207, 132, 206, 183, 207, 130, ' ', 206, 149, 206, 187, 206, 187, 206, 172, 206, 180, 206, 191, 207, 130, ' ', 206, 186, 206, 177, 206, 185, ' ', 206, 188, 206, 181, 206, 179, 206, 177, 206, 187, 207, 141, 207, 132, 206, 181, 207, 129, 206, 183, ' ', 207, 128, 207, 140, 206, 187, 206, 183, ' ', 206, 181, 206, 175, 206, 189, 206, 177, 206, 185, ' ', 206, 183, ' ', 206, 145, 206, 184, 206, 174, 206, 189, 206, 177, '.', 13, 10, 13, 10, 206, 163, 207, 133, 206, 189, 206, 191, 207, 129, 206, 181, 207, 141, 206, 181, 206, 185, ' ', 207, 131, 207, 132, 206, 177, ' ', 206, 178, 206, 191, 207, 129, 206, 181, 206, 185, 206, 191, 206, 180, 207, 133, 207, 132, 206, 185, 206, 186, 206, 172, ' ', 206, 188, 206, 181, ' ', 207, 132, 206, 183, 206, 189, ' ', 206, 145, 206, 187, 206, 178, 206, 177, 206, 189, 206, 175, 206, 177, ',', ' ', 207, 131, 207, 132, 206, 177, ' ', 206, 178, 207, 140, 207, 129, 206, 181, 206, 185, 206, 177, ' ', 206, 188, 206, 181, ' ', 207, 132, 206, 183, ' ', 206, 146, 206, 191, 207, 133, 206, 187, 206, 179, 206, 177, 207, 129, 206, 175, 206, 177, ' ', 206, 186, 206, 177, 206, 185, ' ', 207, 132, 206, 183, 206, 189, ' ', 207, 128, 207, 129, 207, 142, 206, 183, 206, 189, ' ', 206, 147, 206, 185, 206, 191, 207, 133, 206, 179, 206, 186, 206, 191, 207, 131, 206, 187, 206, 177, 206, 178, 206, 185, 206, 186, 206, 174, ' ', 206, 148, 206, 183, 206, 188, 206, 191, 206, 186, 207, 129, 206, 177, 207, 132, 206, 175, 206, 177, ' ', 207, 132, 206, 183, 207, 130, ' ', 206, 156, 206, 177, 206, 186, 206, 181, 206, 180, 206, 191, 206, 189, 206, 175, 206, 177, 207, 130, ' ', '(', 207, 128, '.', 206, 147, '.', 206, 148, '.', 206, 156, '.', ')', ' ', 206, 186, 206, 177, 206, 185, ' ', 207, 131, 207, 132, 206, 177, ' ', 206, 178, 206, 191, 207, 129, 206, 181, 206, 185, 206, 191, 206, 177, 206, 189, 206, 177, 207, 132, 206, 191, 206, 187, 206, 185, 206, 186, 206, 172, ' ', 206, 188, 206, 181, ' ', 207, 132, 206, 183, 206, 189, ' ', 206, 164, 206, 191, 207, 133, 207, 129, 206, 186, 206, 175, 206, 177, '.', ' ', 206, 146, 207, 129, 206, 173, 207, 135, 206, 181, 207, 132, 206, 177, 206, 185, ' ', 207, 131, 207, 132, 206, 177, ' ', 206, 177, 206, 189, 206, 177, 207, 132, 206, 191, 206, 187, 206, 185, 206, 186, 206, 172, ' ', 206, 177, 207, 128, 207, 140, ' ', 207, 132, 206, 191, ' ', 206, 145, 206, 185, 206, 179, 206, 177, 206, 175, 206, 191, ' ', 206, 160, 206, 173, 206, 187, 206, 177, 206, 179, 206, 191, 207, 130, ',', ' ', 207, 131, 207, 132, 206, 177, ' ', 206, 180, 207, 133, 207, 132, 206, 185, 206, 186, 206, 172, ' ', 206, 177, 207, 128, 207, 140, ' ', 207, 132, 206, 191, ' ', 206, 153, 207, 140, 206, 189, 206, 185, 206, 191, ' ', 206, 186, 206, 177, 206, 185, ' ', 206, 189, 207, 140, 207, 132, 206, 185, 206, 177, ' ', 206, 177, 207, 128, 207, 140, ' ', 207, 132, 206, 183, ' ', 206, 156, 206, 181, 207, 131, 207, 140, 206, 179, 206, 181, 206, 185, 206, 191, ' ', 206, 152, 206, 172, 206, 187, 206, 177, 207, 131, 207, 131, 206, 177, '.', 206, 151, ' ', 206, 149, 206, 187, 206, 187, 206, 172, 206, 180, 206, 177, ' ', 206, 186, 206, 177, 207, 132, 206, 173, 207, 135, 206, 181, 206, 185, ' ', 207, 132, 206, 183, 206, 189, ' ', '1', '1', 206, 183, ' ', 206, 184, 206, 173, 207, 131, 206, 183, ' ', 207, 131, 207, 132, 206, 185, 207, 130, ' ', 207, 135, 207, 142, 207, 129, 206, 181, 207, 130, ' ', 206, 188, 206, 181, ' ', 207, 132, 206, 183, ' ', 206, 188, 206, 181, 206, 179, 206, 177, 206, 187, 207, 141, 207, 132, 206, 181, 207, 129, 206, 183, ' ', 206, 177, 206, 186, 207, 132, 206, 191, 206, 179, 207, 129, 206, 177, 206, 188, 206, 188, 206, 174, ' ', 207, 131, 207, 132, 206, 177, ' ', '1', '3', '.', '6', '7', '6', ' ', 207, 135, 206, 185, 206, 187, 206, 185, 207, 140, 206, 188, 206, 181, 207, 132, 207, 129, 206, 177, ' ', 206, 186, 206, 177, 206, 184, 207, 142, 207, 130, ' ', 206, 181, 207, 135, 206, 181, 206, 185, ' ', 207, 128, 206, 191, 206, 187, 206, 187, 206, 172, ' ', 206, 189, 206, 183, 207, 131, 206, 185, 206, 172, ' ', '(', 207, 128, 206, 181, 207, 129, 206, 175, 207, 128, 206, 191, 207, 133, ' ', '1', '.', '4', '0', '0', ',', ' ', 206, 181, 206, 186, 207, 132, 207, 137, 206, 189, ' ', 206, 191, 207, 128, 206, 191, 206, 175, 207, 137, 206, 189, ' ', 207, 132, 206, 177, ' ', '2', '2', '7', ' ', 206, 186, 206, 177, 207, 132, 206, 191, 206, 185, 206, 186, 206, 191, 207, 133, 206, 189, 207, 132, 206, 177, 206, 185, ')', ',', ' ', 207, 131, 207, 133, 206, 188, 207, 128, 206, 181, 207, 129, 206, 185, 206, 187, 206, 177, 206, 188, 206, 178, 206, 177, 206, 189, 206, 191, 206, 188, 206, 173, 206, 189, 207, 137, 206, 189, ' ', 207, 132, 206, 183, 207, 130, ' ', 206, 154, 207, 129, 206, 183, 207, 132, 206, 183, 207, 130, ',', ' ', 207, 132, 207, 137, 206, 189, ' ', 206, 148, 207, 137, 206, 180, 206, 181, 206, 186, 206, 177, 206, 189, 206, 174, 207, 131, 207, 137, 206, 189, ',', ' ', 207, 132, 207, 137, 206, 189, ' ', 206, 154, 207, 133, 206, 186, 206, 187, 206, 172, 206, 180, 207, 137, 206, 189, ',', ' ', 207, 132, 207, 137, 206, 189, ' ', 206, 149, 207, 128, 207, 132, 206, 177, 206, 189, 206, 174, 207, 131, 207, 137, 206, 189, ' ', 206, 186, 206, 177, 206, 185, ' ', 207, 128, 206, 191, 206, 187, 206, 187, 207, 142, 206, 189, ' ', 206, 172, 206, 187, 206, 187, 207, 137, 206, 189, '.', 206, 164, 206, 191, ' ', 207, 136, 206, 183, 206, 187, 207, 140, 207, 132, 206, 181, 207, 129, 206, 191, ' ', 206, 178, 206, 191, 207, 133, 206, 189, 207, 140, ' ', 206, 181, 206, 175, 206, 189, 206, 177, 206, 185, ' ', 206, 191, ' ', 206, 140, 206, 187, 207, 133, 206, 188, 207, 128, 206, 191, 207, 130, ' ', 206, 186, 206, 177, 206, 185, ' ', 207, 132, 206, 191, ' ', 206, 188, 206, 181, 206, 179, 206, 177, 206, 187, 207, 141, 207, 132, 206, 181, 207, 129, 206, 191, ' ', 207, 128, 206, 191, 207, 132, 206, 172, 206, 188, 206, 185, ' ', 206, 191, ' ', 206, 145, 206, 187, 206, 185, 206, 172, 206, 186, 206, 188, 206, 191, 206, 189, 206, 177, 207, 130, '.', 13, 10, 13, 10, 206, 136, 207, 135, 206, 181, 206, 185, ' ', 206, 188, 206, 177, 206, 186, 207, 129, 206, 172, ' ', 206, 186, 206, 177, 206, 185, ' ', 207, 128, 206, 187, 206, 191, 207, 141, 207, 131, 206, 185, 206, 177, ' ', 206, 185, 207, 131, 207, 132, 206, 191, 207, 129, 206, 175, 206, 177, ' ', 206, 186, 206, 177, 207, 132, 206, 172, ' ', 207, 132, 206, 183, 206, 189, ' ', 206, 191, 207, 128, 206, 191, 206, 175, 206, 177, ' ', 206, 172, 207, 131, 206, 186, 206, 183, 207, 131, 206, 181, ' ', 206, 188, 206, 181, 206, 179, 206, 172, 206, 187, 206, 183, ' ', 207, 128, 206, 191, 206, 187, 206, 185, 207, 132, 206, 185, 207, 131, 206, 188, 206, 185, 206, 186, 206, 174, ' ', 206, 181, 207, 128, 206, 175, 206, 180, 207, 129, 206, 177, 207, 131, 206, 183, ' ', 207, 131, 206, 181, ' ', 207, 132, 207, 129, 206, 181, 206, 185, 207, 130, ' ', 206, 183, 207, 128, 206, 181, 206, 175, 207, 129, 206, 191, 207, 133, 207, 130, '.', 206, 149, 206, 180, 207, 142, ' ', 206, 179, 206, 181, 206, 189, 206, 189, 206, 174, 206, 184, 206, 183, 206, 186, 206, 181, ' ', 206, 183, ' ', 206, 180, 206, 183, 206, 188, 206, 191, 206, 186, 207, 129, 206, 177, 207, 132, 206, 175, 206, 177, ' ', 206, 186, 206, 177, 206, 185, ' ', 206, 183, ' ', 207, 134, 206, 185, 206, 187, 206, 191, 207, 131, 206, 191, 207, 134, 206, 175, 206, 177, '.', 206, 145, 206, 186, 207, 140, 206, 188, 206, 188, 206, 177, ' ', 206, 183, ' ', 206, 149, 206, 187, 206, 187, 206, 172, 206, 180, 206, 177, ' ', 206, 181, 206, 175, 206, 189, 206, 177, 206, 185, ' ', 206, 191, ' ', 207, 132, 207, 140, 207, 128, 206, 191, 207, 130, ' ', 206, 179, 206, 173, 206, 189, 206, 189, 206, 183, 207, 131, 206, 183, 207, 130, ' ', 207, 132, 207, 137, 206, 189, ' ', 206, 159, 206, 187, 207, 133, 206, 188, 207, 128, 206, 185, 206, 177, 206, 186, 207, 142, 206, 189, ' ', 206, 145, 206, 179, 207, 142, 206, 189, 207, 137, 206, 189, ',', 207, 132, 206, 191, 207, 133, ' ', 206, 180, 207, 129, 206, 172, 206, 188, 206, 177, 207, 132, 206, 191, 207, 130, ',', ' ', 207, 132, 206, 183, 207, 130, ' ', 207, 132, 207, 129, 206, 177, 206, 179, 207, 137, 206, 180, 206, 175, 206, 177, 207, 130, ' ', 206, 186, 206, 177, 206, 185, ' ', 207, 132, 206, 183, 207, 130, ' ', 206, 186, 207, 137, 206, 188, 206, 188, 207, 137, 206, 180, 206, 175, 206, 177, 207, 130, ' ', '.', 13, 10, 13, 10, 206, 151, ' ', 206, 149, 206, 187, 206, 187, 206, 172, 206, 180, 206, 177, ' ', 206, 181, 206, 175, 206, 189, 206, 177, 206, 185, ' ', 206, 188, 206, 173, 206, 187, 206, 191, 207, 130, ' ', 207, 132, 207, 137, 206, 189, ' ', 206, 149, 207, 133, 207, 129, 207, 137, 207, 128, 206, 177, 207, 138, 206, 186, 207, 142, 206, 189, ' ', 206, 154, 206, 191, 206, 185, 206, 189, 206, 191, 207, 132, 206, 174, 207, 132, 207, 137, 206, 189, '/', 206, 149, 207, 133, 207, 129, 207, 137, 207, 128, 206, 177, 207, 138, 206, 186, 206, 174, 207, 130, ' ', 206, 136, 206, 189, 207, 137, 207, 131, 206, 183, 207, 130, ' ', 206, 177, 207, 128, 207, 140, ' ', 207, 132, 206, 191, ' ', '1', '9', '8', '1', ',', ' ', 207, 132, 206, 183, 207, 130, ' ', 206, 149, 207, 133, 207, 129, 207, 137, 206, 182, 207, 142, 206, 189, 206, 183, 207, 130, ' ', 206, 177, 207, 128, 207, 140, ' ', 207, 132, 206, 191, ' ', '2', '0', '0', '1', ',', ' ', 207, 132, 206, 191, 207, 133, ' ', 206, 157, 206, 145, 206, 164, 206, 159, ' ', 206, 177, 207, 128, 207, 140, ' ', 207, 132, 206, 191, ' ', '1', '9', '5', '2', ' ', 206, 186, 206, 177, 206, 185, ' ', 206, 185, 206, 180, 207, 129, 207, 133, 207, 132, 206, 185, 206, 186, 207, 140, ' ', 206, 188, 206, 173, 206, 187, 206, 191, 207, 130, ' ', 207, 132, 206, 191, 207, 133, ' ', 206, 159, 206, 151, 206, 149, ' ', '(', '1', '9', '4', '5', ')', '.', ' ', 206, 151, ' ', 206, 149, 206, 187, 206, 187, 206, 172, 206, 180, 206, 177, ' ', 206, 181, 206, 175, 206, 189, 206, 177, 206, 185, ' ', 206, 188, 206, 185, 206, 177, ' ', 206, 177, 206, 189, 206, 181, 207, 128, 207, 132, 207, 133, 206, 179, 206, 188, 206, 173, 206, 189, 206, 183, ' ', 207, 135, 207, 142, 207, 129, 206, 177, ' ', 206, 188, 206, 181, ' ', 207, 133, 207, 136, 206, 183, 206, 187, 207, 140, ' ', 206, 186, 206, 177, 207, 132, 206, 172, ' ', 206, 186, 206, 181, 207, 134, 206, 177, 206, 187, 206, 174, 206, 189, ' ', 206, 181, 206, 185, 207, 131, 207, 140, 206, 180, 206, 183, 206, 188, 206, 177, ' ', 206, 186, 206, 177, 206, 185, ' ', 207, 128, 206, 191, 206, 187, 207, 141, ' ', 207, 133, 207, 136, 206, 183, 206, 187, 207, 140, ' ', 206, 180, 206, 181, 206, 175, 206, 186, 207, 132, 206, 183, ' ', 206, 177, 206, 189, 206, 184, 207, 129, 207, 142, 207, 128, 206, 185, 206, 189, 206, 183, 207, 130, ' ', 206, 177, 206, 189, 206, 172, 207, 128, 207, 132, 207, 133, 206, 190, 206, 183, 207, 130, '.', ' ', 206, 154, 206, 177, 207, 132, 206, 173, 207, 135, 206, 181, 206, 185, ' ', 207, 132, 206, 183, 206, 189, ' ', '2', '2', 206, 183, ' ', 206, 186, 206, 177, 206, 187, 207, 141, 207, 132, 206, 181, 207, 129, 206, 183, ' ', 207, 128, 206, 191, 206, 185, 207, 140, 207, 132, 206, 183, 207, 132, 206, 177, ' ', 206, 182, 207, 137, 206, 174, 207, 130, ' ', 207, 131, 207, 132, 206, 191, 206, 189, ' ', 206, 186, 207, 140, 207, 131, 206, 188, 206, 191, '.', '[', '4', ']', 13, 10, 13, 10, 206, 151, ' ', 206, 149, 206, 187, 206, 187, 206, 172, 206, 180, 206, 177, ' ', '(', 207, 128, 206, 177, 206, 187, 206, 177, 206, 185, 207, 140, 207, 132, 206, 181, 207, 129, 206, 177, ':', ' ', 225, 188, 153, 206, 187, 206, 187, 206, 172, 207, 130, ',', ' ', 206, 181, 207, 128, 206, 175, 207, 131, 206, 183, 206, 188, 206, 177, ':', ' ', 206, 149, 206, 187, 206, 187, 206, 183, 206, 189, 206, 185, 206, 186, 206, 174, ' ', 206, 148, 206, 183, 206, 188, 206, 191, 206, 186, 207, 129, 206, 177, 207, 132, 206, 175, 206, 177, ')', ' ', 206, 181, 206, 175, 206, 189, 206, 177, 206, 185, ' ', 207, 135, 207, 142, 207, 129, 206, 177, ' ', 207, 128, 206, 191, 207, 133, ' ', 206, 178, 207, 129, 206, 175, 207, 131, 206, 186, 206, 181, 207, 132, 206, 177, 206, 185, ' ', 207, 131, 207, 132, 206, 183, ' ', 206, 189, 206, 191, 207, 132, 206, 185, 206, 191, 206, 177, 206, 189, 206, 177, 207, 132, 206, 191, 206, 187, 206, 185, 206, 186, 206, 174, ' ', 206, 149, 207, 133, 207, 129, 207, 142, 207, 128, 206, 183, ',', ' ', 207, 131, 207, 132, 206, 191, ' ', 206, 189, 206, 191, 207, 132, 206, 185, 207, 140, 207, 132, 206, 181, 207, 129, 206, 191, ' ', 206, 172, 206, 186, 207, 129, 206, 191, ' ', 207, 132, 206, 183, 207, 130, ' ', 206, 146, 206, 177, 206, 187, 206, 186, 206, 177, 206, 189, 206, 185, 206, 186, 206, 174, 207, 130, ' ', 207, 135, 206, 181, 207, 129, 207, 131, 206, 191, 206, 189, 206, 174, 207, 131, 206, 191, 207, 133, ',', ' ', 207, 131, 207, 132, 206, 183, 206, 189, ' ', 206, 145, 206, 189, 206, 177, 207, 132, 206, 191, 206, 187, 206, 185, 206, 186, 206, 174, ' ', 206, 156, 206, 181, 207, 131, 207, 140, 206, 179, 206, 181, 206, 185, 206, 191, '.', 206, 160, 207, 129, 207, 137, 207, 132, 206, 181, 207, 141, 206, 191, 207, 133, 207, 131, 206, 177, ' ', 207, 132, 206, 183, 207, 130, ' ', 206, 149, 206, 187, 206, 187, 206, 172, 206, 180, 206, 191, 207, 130, ' ', 206, 186, 206, 177, 206, 185, ' ', 206, 188, 206, 181, 206, 179, 206, 177, 206, 187, 207, 141, 207, 132, 206, 181, 207, 129, 206, 183, ' ', 207, 128, 207, 140, 206, 187, 206, 183, ' ', 206, 181, 206, 175, 206, 189, 206, 177, 206, 185, ' ', 206, 183, ' ', 206, 145, 206, 184, 206, 174, 206, 189, 206, 177, '.', 13, 10, 13, 10, 206, 163, 207, 133, 206, 189, 206, 191, 207, 129, 206, 181, 207, 141, 206, 181, 206, 185, ' ', 207, 131, 207, 132, 206, 177, ' ', 206, 178, 206, 191, 207, 129, 206, 181, 206, 185, 206, 191, 206, 180, 207, 133, 207, 132, 206, 185, 206, 186, 206, 172, ' ', 206, 188, 206, 181, ' ', 207, 132, 206, 183, 206, 189, ' ', 206, 145, 206, 187, 206, 178, 206, 177, 206, 189, 206, 175, 206, 177, ',', ' ', 207, 131, 207, 132, 206, 177, ' ', 206, 178, 207, 140, 207, 129, 206, 181, 206, 185, 206, 177, ' ', 206, 188, 206, 181, ' ', 207, 132, 206, 183, ' ', 206, 146, 206, 191, 207, 133, 206, 187, 206, 179, 206, 177, 207, 129, 206, 175, 206, 177, ' ', 206, 186, 206, 177, 206, 185, ' ', 207, 132, 206, 183, 206, 189, ' ', 207, 128, 207, 129, 207, 142, 206, 183, 206, 189, ' ', 206, 147, 206, 185, 206, 191, 207, 133, 206, 179, 206, 186, 206, 191, 207, 131, 206, 187, 206, 177, 206, 178, 206, 185, 206, 186, 206, 174, ' ', 206, 148, 206, 183, 206, 188, 206, 191, 206, 186, 207, 129, 206, 177, 207, 132, 206, 175, 206, 177, ' ', 207, 132, 206, 183, 207, 130, ' ', 206, 156, 206, 177, 206, 186, 206, 181, 206, 180, 206, 191, 206, 189, 206, 175, 206, 177, 207, 130, ' ', '(', 207, 128, '.', 206, 147, '.', 206, 148, '.', 206, 156, '.', ')', ' ', 206, 186, 206, 177, 206, 185, ' ', 207, 131, 207, 132, 206, 177, ' ', 206, 178, 206, 191, 207, 129, 206, 181, 206, 185, 206, 191, 206, 177, 206, 189, 206, 177, 207, 132, 206, 191, 206, 187, 206, 185, 206, 186, 206, 172, ' ', 206, 188, 206, 181, ' ', 207, 132, 206, 183, 206, 189, ' ', 206, 164, 206, 191, 207, 133, 207, 129, 206, 186, 206, 175, 206, 177, '.', ' ', 206, 146, 207, 129, 206, 173, 207, 135, 206, 181, 207, 132, 206, 177, 206, 185, ' ', 207, 131, 207, 132, 206, 177, ' ', 206, 177, 206, 189, 206, 177, 207, 132, 206, 191, 206, 187, 206, 185, 206, 186, 206, 172, ' ', 206, 177, 207, 128, 207, 140, ' ', 207, 132, 206, 191, ' ', 206, 145, 206, 185, 206, 179, 206, 177, 206, 175, 206, 191, ' ', 206, 160, 206, 173, 206, 187, 206, 177, 206, 179, 206, 191, 207, 130, ',', ' ', 207, 131, 207, 132, 206, 177, ' ', 206, 180, 207, 133, 207, 132, 206, 185, 206, 186, 206, 172, ' ', 206, 177, 207, 128, 207, 140, ' ', 207, 132, 206, 191, ' ', 206, 153, 207, 140, 206, 189, 206, 185, 206, 191, ' ', 206, 186, 206, 177, 206, 185, ' ', 206, 189, 207, 140, 207, 132, 206, 185, 206, 177, ' ', 206, 177, 207, 128, 207, 140, ' ', 207, 132, 206, 183, ' ', 206, 156, 206, 181, 207, 131, 207, 140, 206, 179, 206, 181, 206, 185, 206, 191, ' ', 206, 152, 206, 172, 206, 187, 206, 177, 207, 131, 207, 131, 206, 177, '.', 206, 151, ' ', 206, 149, 206, 187, 206, 187, 206, 172, 206, 180, 206, 177, ' ', 206, 186, 206, 177, 207, 132, 206, 173, 207, 135, 206, 181, 206, 185, ' ', 207, 132, 206, 183, 206, 189, ' ', '1', '1', 206, 183, ' ', 206, 184, 206, 173, 207, 131, 206, 183, ' ', 207, 131, 207, 132, 206, 185, 207, 130, ' ', 207, 135, 207, 142, 207, 129, 206, 181, 207, 130, ' ', 206, 188, 206, 181, ' ', 207, 132, 206, 183, ' ', 206, 188, 206, 181, 206, 179, 206, 177, 206, 187, 207, 141, 207, 132, 206, 181, 207, 129, 206, 183, ' ', 206, 177, 206, 186, 207, 132, 206, 191, 206, 179, 207, 129, 206, 177, 206, 188, 206, 188, 206, 174, ' ', 207, 131, 207, 132, 206, 177, ' ', '1', '3', '.', '6', '7', '6', ' ', 207, 135, 206, 185, 206, 187, 206, 185, 207, 140, 206, 188, 206, 181, 207, 132, 207, 129, 206, 177, ' ', 206, 186, 206, 177, 206, 184, 207, 142, 207, 130, ' ', 206, 181, 207, 135, 206, 181, 206, 185, ' ', 207, 128, 206, 191, 206, 187, 206, 187, 206, 172, ' ', 206, 189, 206, 183, 207, 131, 206, 185, 206, 172, ' ', '(', 207, 128, 206, 181, 207, 129, 206, 175, 207, 128, 206, 191, 207, 133, ' ', '1', '.', '4', '0', '0', ',', ' ', 206, 181, 206, 186, 207, 132, 207, 137, 206, 189, ' ', 206, 191, 207, 128, 206, 191, 206, 175, 207, 137, 206, 189, ' ', 207, 132, 206, 177, ' ', '2', '2', '7', ' ', 206, 186, 206, 177, 207, 132, 206, 191, 206, 185, 206, 186, 206, 191, 207, 133, 206, 189, 207, 132, 206, 177, 206, 185, ')', ',', ' ', 207, 131, 207, 133, 206, 188, 207, 128, 206, 181, 207, 129, 206, 185, 206, 187, 206, 177, 206, 188, 206, 178, 206, 177, 206, 189, 206, 191, 206, 188, 206, 173, 206, 189, 207, 137, 206, 189, ' ', 207, 132, 206, 183, 207, 130, ' ', 206, 154, 207, 129, 206, 183, 207, 132, 206, 183, 207, 130, ',', ' ', 207, 132, 207, 137, 206, 189, ' ', 206, 148, 207, 137, 206, 180, 206, 181, 206, 186, 206, 177, 206, 189, 206, 174, 207, 131, 207, 137, 206, 189, ',', ' ', 207, 132, 207, 137, 206, 189, ' ', 206, 154, 207, 133, 206, 186, 206, 187, 206, 172, 206, 180, 207, 137, 206, 189, ',', ' ', 207, 132, 207, 137, 206, 189, ' ', 206, 149, 207, 128, 207, 132, 206, 177, 206, 189, 206, 174, 207, 131, 207, 137, 206, 189, ' ', 206, 186, 206, 177, 206, 185, ' ', 207, 128, 206, 191, 206, 187, 206, 187, 207, 142, 206, 189, ' ', 206, 172, 206, 187, 206, 187, 207, 137, 206, 189, '.', 206, 164, 206, 191, ' ', 207, 136, 206, 183, 206, 187, 207, 140, 207, 132, 206, 181, 207, 129, 206, 191, ' ', 206, 178, 206, 191, 207, 133, 206, 189, 207, 140, ' ', 206, 181, 206, 175, 206, 189, 206, 177, 206, 185, ' ', 206, 191, ' ', 206, 140, 206, 187, 207, 133, 206, 188, 207, 128, 206, 191, 207, 130, ' ', 206, 186, 206, 177, 206, 185, ' ', 207, 132, 206, 191, ' ', 206, 188, 206, 181, 206, 179, 206, 177, 206, 187, 207, 141, 207, 132, 206, 181, 207, 129, 206, 191, ' ', 207, 128, 206, 191, 207, 132, 206, 172, 206, 188, 206, 185, ' ', 206, 191, ' ', 206, 145, 206, 187, 206, 185, 206, 172, 206, 186, 206, 188, 206, 191, 206, 189, 206, 177, 207, 130, '.', 13, 10, 13, 10, 206, 136, 207, 135, 206, 181, 206, 185, ' ', 206, 188, 206, 177, 206, 186, 207, 129, 206, 172, ' ', 206, 186, 206, 177, 206, 185, ' ', 207, 128, 206, 187, 206, 191, 207, 141, 207, 131, 206, 185, 206, 177, ' ', 206, 185, 207, 131, 207, 132, 206, 191, 207, 129, 206, 175, 206, 177, ' ', 206, 186, 206, 177, 207, 132, 206, 172, ' ', 207, 132, 206, 183, 206, 189, ' ', 206, 191, 207, 128, 206, 191, 206, 175, 206, 177, ' ', 206, 172, 207, 131, 206, 186, 206, 183, 207, 131, 206, 181, ' ', 206, 188, 206, 181, 206, 179, 206, 172, 206, 187, 206, 183, ' ', 207, 128, 206, 191, 206, 187, 206, 185, 207, 132, 206, 185, 207, 131, 206, 188, 206, 185, 206, 186, 206, 174, ' ', 206, 181, 207, 128, 206, 175, 206, 180, 207, 129, 206, 177, 207, 131, 206, 183, ' ', 207, 131, 206, 181, ' ', 207, 132, 207, 129, 206, 181, 206, 185, 207, 130, ' ', 206, 183, 207, 128, 206, 181, 206, 175, 207, 129, 206, 191, 207, 133, 207, 130, '.', 206, 149, 206, 180, 207, 142, ' ', 206, 179, 206, 181, 206, 189, 206, 189, 206, 174, 206, 184, 206, 183, 206, 186, 206, 181, ' ', 206, 183, ' ', 206, 180, 206, 183, 206, 188, 206, 191, 206, 186, 207, 129, 206, 177, 207, 132, 206, 175, 206, 177, ' ', 206, 186, 206, 177, 206, 185, ' ', 206, 183, ' ', 207, 134, 206, 185, 206, 187, 206, 191, 207, 131, 206, 191, 207, 134, 206, 175, 206, 177, '.', 206, 145, 206, 186, 207, 140, 206, 188, 206, 188, 206, 177, ' ', 206, 183, ' ', 206, 149, 206, 187, 206, 187, 206, 172, 206, 180, 206, 177, ' ', 206, 181, 206, 175, 206, 189, 206, 177, 206, 185, ' ', 206, 191, ' ', 207, 132, 207, 140, 207, 128, 206, 191, 207, 130, ' ', 206, 179, 206, 173, 206, 189, 206, 189, 206, 183, 207, 131, 206, 183, 207, 130, ' ', 207, 132, 207, 137, 206, 189, ' ', 206, 159, 206, 187, 207, 133, 206, 188, 207, 128, 206, 185, 206, 177, 206, 186, 207, 142, 206, 189, ' ', 206, 145, 206, 179, 207, 142, 206, 189, 207, 137, 206, 189, ',', 207, 132, 206, 191, 207, 133, ' ', 206, 180, 207, 129, 206, 172, 206, 188, 206, 177, 207, 132, 206, 191, 207, 130, ',', ' ', 207, 132, 206, 183, 207, 130, ' ', 207, 132, 207, 129, 206, 177, 206, 179, 207, 137, 206, 180, 206, 175, 206, 177, 207, 130, ' ', 206, 186, 206, 177, 206, 185, ' ', 207, 132, 206, 183, 207, 130, ' ', 206, 186, 207, 137, 206, 188, 206, 188, 207, 137, 206, 180, 206, 175, 206, 177, 207, 130, ' ', '.', 13, 10, 13, 10, 206, 151, ' ', 206, 149, 206, 187, 206, 187, 206, 172, 206, 180, 206, 177, ' ', 206, 181, 206, 175, 206, 189, 206, 177, 206, 185, ' ', 206, 188, 206, 173, 206, 187, 206, 191, 207, 130, ' ', 207, 132, 207, 137, 206, 189, ' ', 206, 149, 207, 133, 207, 129, 207, 137, 207, 128, 206, 177, 207, 138, 206, 186, 207, 142, 206, 189, ' ', 206, 154, 206, 191, 206, 185, 206, 189, 206, 191, 207, 132, 206, 174, 207, 132, 207, 137, 206, 189, '/', 206, 149, 207, 133, 207, 129, 207, 137, 207, 128, 206, 177, 207, 138, 206, 186, 206, 174, 207, 130, ' ', 206, 136, 206, 189, 207, 137, 207, 131, 206, 183, 207, 130, ' ', 206, 177, 207, 128, 207, 140, ' ', 207, 132, 206, 191, ' ', '1', '9', '8', '1', ',', ' ', 207, 132, 206, 183, 207, 130, ' ', 206, 149, 207, 133, 207, 129, 207, 137, 206, 182, 207, 142, 206, 189, 206, 183, 207, 130, ' ', 206, 177, 207, 128, 207, 140, ' ', 207, 132, 206, 191, ' ', '2', '0', '0', '1', ',', ' ', 207, 132, 206, 191, 207, 133, ' ', 206, 157, 206, 145, 206, 164, 206, 159, ' ', 206, 177, 207, 128, 207, 140, ' ', 207, 132, 206, 191, ' ', '1', '9', '5', '2', ' ', 206, 186, 206, 177, 206, 185, ' ', 206, 185, 206, 180, 207, 129, 207, 133, 207, 132, 206, 185, 206, 186, 207, 140, ' ', 206, 188, 206, 173, 206, 187, 206, 191, 207, 130, ' ', 207, 132, 206, 191, 207, 133, ' ', 206, 159, 206, 151, 206, 149, ' ', '(', '1', '9', '4', '5', ')', '.', ' ', 206, 151, ' ', 206, 149, 206, 187, 206, 187, 206, 172, 206, 180, 206, 177, ' ', 206, 181, 206, 175, 206, 189, 206, 177, 206, 185, ' ', 206, 188, 206, 185, 206, 177, ' ', 206, 177, 206, 189, 206, 181, 207, 128, 207, 132, 207, 133, 206, 179, 206, 188, 206, 173, 206, 189, 206, 183, ' ', 207, 135, 207, 142, 207, 129, 206, 177, ' ', 206, 188, 206, 181, ' ', 207, 133, 207, 136, 206, 183, 206, 187, 207, 140, ' ', 206, 186, 206, 177, 207, 132, 206, 172, ' ', 206, 186, 206, 181, 207, 134, 206, 177, 206, 187, 206, 174, 206, 189, ' ', 206, 181, 206, 185, 207, 131, 207, 140, 206, 180, 206, 183, 206, 188, 206, 177, ' ', 206, 186, 206, 177, 206, 185, ' ', 207, 128, 206, 191, 206, 187, 207, 141, ' ', 207, 133, 207, 136, 206, 183, 206, 187, 207, 140, ' ', 206, 180, 206, 181, 206, 175, 206, 186, 207, 132, 206, 183, ' ', 206, 177, 206, 189, 206, 184, 207, 129, 207, 142, 207, 128, 206, 185, 206, 189, 206, 183, 207, 130, ' ', 206, 177, 206, 189, 206, 172, 207, 128, 207, 132, 207, 133, 206, 190, 206, 183, 207, 130, '.', ' ', 206, 154, 206, 177, 207, 132, 206, 173, 207, 135, 206, 181, 206, 185, ' ', 207, 132, 206, 183, 206, 189, ' ', '2', '2', 206, 183, ' ', 206, 186, 206, 177, 206, 187, 207, 141, 207, 132, 206, 181, 207, 129, 206, 183, ' ', 207, 128, 206, 191, 206, 185, 207, 140, 207, 132, 206, 183, 207, 132, 206, 177, ' ', 206, 182, 207, 137, 206, 174, 207, 130, ' ', 207, 131, 207, 132, 206, 191, 206, 189, ' ', 206, 186, 207, 140, 207, 131, 206, 188, 206, 191, '.', '[', '4', ']', 13, 10, 13, 10, 'R', 'a', 'n', 'd', 'o', 'm', ' ', 'Q', 'u', 'a', 'd', ' ', 'V', 'a', 'l', 'u', 'e', 's', 13, 10, 240, 144, 128, 128, 240, 152, 166, 171, 240, 158, 187, 174, 240, 154, 170, 170, 240, 154, 132, 163, 240, 155, 132, 163, 243, 187, 174, 187, 244, 128, 128, 128, 243, 174, 187, 174, 242, 187, 174, 187, 13, 10, 0 }; static const char * const charUtf8MultiLang = (const char *) utf8MultiLang; enum { NUM_UTF8_MULTI_LANG_CODE_POINTS = 11781 }; static bsl::string dumpVec(const bsl::vector<int>& vec) // Return the contents of the specified 'vec' in string form. { bsl::ostringstream oss; for (unsigned uu = 0; uu < vec.size(); ++uu) { oss << (uu ? " " : "") << vec[uu]; } return oss.str(); } static bsl::string dumpStr(const bsl::string& str) // Returns the specified 'str' in a human-readable hex format. { bsl::string ret; const char *begin = str.c_str(); const char *end = &*str.end(); for (const char *pc = begin; pc < end; ++pc) { if (begin != pc) { ret.push_back(' '); } for (int shiftDown = 4; shiftDown >= 0; shiftDown -= 4) { int digit = (*pc >> shiftDown) & 0xf; ret.push_back(digit < 10 ? char('0' + digit) : char('a' + digit - 10)); } } return ret; } static inline unsigned int randUnsigned() // Return a pseudo-random unsigned integer. { static unsigned int key = 0x87654321U; key *= 1103515245; key += 12345; return key ^ 0x5a5a5a5aU; } static void appendRand1Byte(bsl::string *dst) // Append a random 1-byte UTF-8 character to the specified '*dst'. { enum { k_LOW_BOUND = 1, k_HIGH_BOUND = 0x7f, k_MOD_BY = k_HIGH_BOUND + 1 - k_LOW_BOUND }; unsigned val = randUnsigned() % k_MOD_BY + k_LOW_BOUND; BSLS_ASSERT(val <= k_HIGH_BOUND); unsigned char buf[2]; buf[0] = static_cast<unsigned char>(val); buf[1] = 0; *dst += reinterpret_cast<const char *>(&buf[0]); } static void appendRand2Byte(bsl::string *dst) // Append a random 2-byte UTF-8 character to the specified '*dst'. { enum { k_LOW_BOUND = 0x80, k_HIGH_BOUND = 0x7ff, k_MOD_BY = k_HIGH_BOUND + 1 - k_LOW_BOUND }; unsigned val = randUnsigned() % k_MOD_BY + k_LOW_BOUND; BSLS_ASSERT(val <= k_HIGH_BOUND); unsigned char buf[3]; buf[0] = static_cast<unsigned char>(((val & 0x7c0) >> 6) | 0xc0); buf[1] = static_cast<unsigned char> ((val & 0x3f) | 0x80); buf[2] = 0; *dst += reinterpret_cast<const char *>(&buf[0]); } static void appendRand3Byte(bsl::string *dst) // Append a random 3-byte UTF-8 character to the specified '*dst'. { enum { k_LOW_BOUND = 0x800, k_HIGH_BOUND = 0xffff, k_MOD_BY = k_HIGH_BOUND + 1 - k_LOW_BOUND }; unsigned val; do { val = randUnsigned() % k_MOD_BY + k_LOW_BOUND; } while (val >= 0xd800 && val <= 0xdfff); BSLS_ASSERT(val <= k_HIGH_BOUND); unsigned char buf[4]; buf[0] = static_cast<unsigned char>(((val & 0xf000) >> 12) | 0xe0); buf[1] = static_cast<unsigned char>(((val & 0xfc0) >> 6) | 0x80); buf[2] = static_cast<unsigned char> ((val & 0x3f) | 0x80); buf[3] = 0; *dst += reinterpret_cast<const char *>(&buf[0]); } static void appendRand4Byte(bsl::string *dst) // Append a random 4-byte UTF-8 character to the specified '*dst'. { enum { k_LOW_BOUND = 0x10000, k_HIGH_BOUND = 0x10ffff, k_MOD_BY = k_HIGH_BOUND + 1 - k_LOW_BOUND }; unsigned val = randUnsigned() % k_MOD_BY + k_LOW_BOUND; BSLS_ASSERT(val <= k_HIGH_BOUND); unsigned char buf[5]; buf[0] = static_cast<unsigned char>(((val & 0x1c0000) >> 18) | 0xf0); buf[1] = static_cast<unsigned char>(((val & 0x3f000) >> 12) | 0x80); buf[2] = static_cast<unsigned char>(((val & 0xfc0) >> 6) | 0x80); buf[3] = static_cast<unsigned char> ((val & 0x3f) | 0x80); buf[4] = 0; *dst += reinterpret_cast<const char *>(&buf[0]); } static void appendRandCorrectCodePoint(bsl::string *dst, bool useZero) // Append a random valid UTF-8 character to the specified '*dst'. The '\0' // byte is only possible if the specified 'useZero' is 'true'. { unsigned r = randUnsigned(); r = useZero ? r % 5 : (r & 3) + 1; switch (r) { case 0: { dst->push_back('\0'); } break; case 1: { appendRand1Byte(dst); } break; case 2: { appendRand2Byte(dst); } break; case 3: { appendRand3Byte(dst); } break; case 4: { appendRand4Byte(dst); } break; default: { ASSERT(0); } } } bsl::string code8(int b) // Return the encoded representation of the specified 7-bit UTF-8 codepoint // 'b'. Note that this is simply 'b'. { bsl::string ret; ASSERT(0 == (b & ~0x7f)); ret += char(b); return ret; } static bsl::string code16(int b) // Return the encoded representation of the specified 2-byte UTF-8 // codepoint 'b'. { ASSERT(0 == (b & ~0x7ff)); unsigned char buf[3]; buf[0] = static_cast<unsigned char>(((b & 0x7c0) >> 6) | 0xc0); buf[1] = static_cast<unsigned char> ((b & 0x3f) | 0x80); buf[2] = 0; return reinterpret_cast<char *>(buf); } static bsl::string code24(int b) // Return the encoded representation of the specified 3-byte UTF-8 // codepoint 'b'. { ASSERT(0 == (b & ~0xffff)); unsigned char buf[4]; buf[0] = static_cast<unsigned char>(((b & 0xf000) >> 12) | 0xe0); buf[1] = static_cast<unsigned char>(((b & 0xfc0) >> 6) | 0x80); buf[2] = static_cast<unsigned char> ((b & 0x3f) | 0x80); buf[3] = 0; return reinterpret_cast<char *>(buf); } static bsl::string code32(int b) // Return the encoded representation of the specified 4-byte UTF-8 // codepoint 'b'. { ASSERT(static_cast<unsigned>(b) <= 0x10ffff); unsigned char buf[5]; buf[0] = static_cast<unsigned char>(((b & 0x1c0000) >> 18) | 0xf0); buf[1] = static_cast<unsigned char>(((b & 0x3f000) >> 12) | 0x80); buf[2] = static_cast<unsigned char>(((b & 0xfc0) >> 6) | 0x80); buf[3] = static_cast<unsigned char> ((b & 0x3f) | 0x80); buf[4] = 0; return reinterpret_cast<char *>(buf); } static bsl::string utf8Encode(int b) // Return the encoded representation of the specified UTF-8 codepoint 'b'. { ASSERT(static_cast<unsigned>(b) <= 0x10ffff); if (b <= 0x7f) { return code8(b); // RETURN } if (b <= 0x7ff) { return code16(b); // RETURN } if (b <= 0xffff) { return code24(b); // RETURN } return code32(b); } static bsl::string codeBOM() // Return the encoded representation of a UTF-8 Byte Order Mark. { unsigned char buf[4]; buf[0] = 0xef; buf[1] = 0xbb; buf[2] = 0xbf; buf[3] = 0; return reinterpret_cast<char *>(buf); } // Note these decoders all assume they can look as far as they want down the // stream of bytes without provoking a segfault. static unsigned int decode8(const char *pc) // Return the decoded value of the 1-byte UTF-8 codepoint pointed to by // the specified 'pc'. Note that this is just '*pc'. { ASSERT(!(~0x7f & *pc)); return *pc; } static unsigned int decode16(const char *pc) // Return the decoded value of the 2-byte UTF-8 codepoint pointed to by // the specified 'pc'. { ASSERT(0xc0 == (*pc & 0xe0) && 0x80 == (pc[1] & 0xc0)); return ((0x1f & *pc) << 6) | (0x3f & pc[1]); } static unsigned int decode24(const char *pc) // Return the decoded value of the 3-byte UTF-8 codepoint pointed to by // the specified 'pc'. { ASSERT(0xe0 == (*pc & 0xf0) && 0x80 == (pc[1] & 0xc0) && 0x80 == (pc[2] & 0xc0)); return ((0xf & *pc) << 12) | ((0x3f & pc[1]) << 6) | (0x3f & pc[2]); } static unsigned int decode32(const char *pc) // Return the decoded value of the 4-byte UTF-8 codepoint pointed to by // the specified 'pc'. { ASSERT(0xf0 == (*pc & 0xf8) && 0x80 == (pc[1] & 0xc0) && 0x80 == (pc[2] & 0xc0) && 0x80 == (pc[3] & 0xc0)); return (( 0x7 & *pc) << 18) | ((0x3f & pc[1]) << 12) | ((0x3f & pc[2]) << 6) | (0x3f & pc[3]); } static unsigned int decode(const char **pc) // Return the decoded value of the UTF-8 codepoint pointed to by the // specified '*pc', updating '*pc' to point to the next codepoint. { int ret; char c = **pc; if (0 == (~0x7f & c)) { ret = decode8(*pc); ++ *pc; } else if (0xc0 == (0xe0 & c)) { ret = decode16(*pc); *pc += 2; } else if (0xe0 == (0xf0 & c)) { ret = decode24(*pc); *pc += 3; } else if (0xf0 == (0xf8 & c)) { ret = decode32(*pc); *pc += 4; } else { ASSERT(0); return -1; // RETURN } return ret; } static unsigned int decode(const char *pc) // Return the decoded value of the UTF-8 codepoint pointed to by the // specified 'pc'. { return decode(&pc); } static bsls::Types::Uint64 randAccum = 0; int randNum() // MMIX Linear Congruential Generator algorithm by Donald Knuth { randAccum = randAccum * 6364136223846793005LL + 1442695040888963407LL; return int(randAccum >> 32); } static int randVal() // Return a random integer in the '[0..0x1fffff]' range. { return (randNum() >> 9) & 0x1fffff; } static int randVal8(bool never0 = false) // Return a random integer in the '[1..0x7f]' range. If the optionally // specified 'never0' is 'true', the range is '[0..0x7f]'. { int ret; do { ret = randVal() & 0x7f; } while (never0 && 0 == ret); return ret; } static int randVal16() // Return a random integer in the '[0x80..0x7ff]' range. { int ret; do { ret = randVal() & 0x7ff; } while (ret < 0x80); return ret; } static int randVal24(bool neverSurrogates = false) // Return a random integer in the '[0x800..0xffff]' range. If the // optionally specified 'neverSurrogates' is 'true', do not return values // in the '[0xd800..0xdfff]' surrogates range. { int ret; do { ret = randVal() & 0xffff; } while (ret < 0x800 || (neverSurrogates && ret >= 0xd800 && ret <= 0xdfff)); return ret; } static int randVal32() // Return a random integer in the '[0x10000..0x10ffff]' range. { int ret; do { ret = (randVal() & 0xfffff) + (randVal() & 0x7ffff); } while (ret > 0x10ffff || ret < 0x10000); return ret; } static int randValue(bool strict = false, bool never0 = false) // Return a random integer in the '[0..0x10ffff]' range. If the optionally // specified 'strict' is 'true', do not return values in the // '[0xd800..0xdfff]' surrogates range. If the optionally specified // 'never0' is true, the range is '[1..0x10ffff]'. { int type = randVal(); switch (type & 3) { case 0: { return randVal8(never0); // RETURN } break; case 1: { return randVal16(); // RETURN } break; case 2: { return randVal24(strict); // RETURN } break; case 3: { return randVal32(); // RETURN } } ASSERT(0); return 0; } static bool allValid(const bsl::string& str) // Return true if all the UTF-8 codepoints in the specified 'str' are // valid. { bool a = Obj::isValid(str.c_str()); ASSERT(Obj::isValid(str.data(), str.length()) == a); return a; } static int allNumCodePoints(const bsl::string& str) // Return the total number of codepoints in the specified UTF-8 'str'. { int len = Obj::numCharacters(str.data(), str.length()); ASSERT(Obj::numCharacters(str.c_str()) == len); return len; } static bsl::string clone(const char *pc, int length) // Return a 'bsl::string' containing the specified 'length' bytes from the // specified 'pc'. { bsl::string ret; ret.insert(0, pc, length); return ret; } // Some useful (mostly) multi-octet code points: // The 2 lowest non-0 1-octet code points. #define U8_00001 "\x01" #define U8_00002 "\x02" // The 2 highest 1-octet code points. #define U8_0007e "\x7e" #define U8_0007f "\x7f" // The 2 lowest 2-octet code points. #define U8_00080 "\xc2\x80" #define U8_00081 "\xc2\x81" // A traditional "interesting" code point, 0xff. #define U8_000ff "\xc3\xbf" // The 2 highest 2-octet code points. #define U8_007fe "\xdf\xbe" #define U8_007ff "\xdf\xbf" // The 2 lowest 3-octet code points. #define U8_00800 "\xe0\xa0\x80" #define U8_00801 "\xe0\xa0\x81" // The 2 highest 3-octet code points. #define U8_0fffe "\xef\xbf\xbe" #define U8_0ffff "\xef\xbf\xbf" // The 2 lowest 4-octet code points. #define U8_10000 "\xf0\x90\x80\x80" #define U8_10001 "\xf0\x90\x80\x81" // The 2 highest 4-octet code points. #define U8_10fffe "\xf4\x8f\xbf\xbe" #define U8_10ffff "\xf4\x8f\xbf\xbf" static const struct { int d_lineNum; // source line number const char *d_utf8_p; // UTF-8 input string unsigned int d_codepoint; // 32-bit codepoint value } legalCodepointData[] = { //L# UTF-8 codepoint //-- ----- --------- { L_, U8_00001, decode(U8_00001) }, { L_, U8_00002, decode(U8_00002) }, { L_, "\x03", decode("\x03") }, { L_, "\x04", decode("\x04") }, { L_, "\x05", decode("\x05") }, { L_, "\x06", decode("\x06") }, { L_, "\x07", decode("\x07") }, { L_, "\x08", decode("\x08") }, { L_, "\x09", decode("\x09") }, { L_, "\x0a", decode("\x0a") }, { L_, "\x0b", decode("\x0b") }, { L_, "\x0c", decode("\x0c") }, { L_, "\x0d", decode("\x0d") }, { L_, "\x0e", decode("\x0e") }, { L_, "\x0f", decode("\x0f") }, { L_, "\x10", decode("\x10") }, { L_, "\x11", decode("\x11") }, { L_, "\x12", decode("\x12") }, { L_, "\x13", decode("\x13") }, { L_, "\x14", decode("\x14") }, { L_, "\x15", decode("\x15") }, { L_, "\x16", decode("\x16") }, { L_, "\x17", decode("\x17") }, { L_, "\x18", decode("\x18") }, { L_, "\x19", decode("\x19") }, { L_, "\x1a", decode("\x1a") }, { L_, "\x1b", decode("\x1b") }, { L_, "\x1c", decode("\x1c") }, { L_, "\x1d", decode("\x1d") }, { L_, "\x1e", decode("\x1e") }, { L_, "\x1f", decode("\x1f") }, { L_, "\x20", decode("\x20") }, { L_, "\x21", decode("\x21") }, { L_, "\x22", decode("\x22") }, { L_, "\x23", decode("\x23") }, { L_, "\x24", decode("\x24") }, { L_, "\x25", decode("\x25") }, { L_, "\x26", decode("\x26") }, { L_, "\x27", decode("\x27") }, { L_, "\x28", decode("\x28") }, { L_, "\x29", decode("\x29") }, { L_, "\x2a", decode("\x2a") }, { L_, "\x2b", decode("\x2b") }, { L_, "\x2c", decode("\x2c") }, { L_, "\x2d", decode("\x2d") }, { L_, "\x2e", decode("\x2e") }, { L_, "\x2f", decode("\x2f") }, { L_, "\x30", decode("\x30") }, { L_, "\x31", decode("\x31") }, { L_, "\x32", decode("\x32") }, { L_, "\x33", decode("\x33") }, { L_, "\x34", decode("\x34") }, { L_, "\x35", decode("\x35") }, { L_, "\x36", decode("\x36") }, { L_, "\x37", decode("\x37") }, { L_, "\x38", decode("\x38") }, { L_, "\x39", decode("\x39") }, { L_, "\x3a", decode("\x3a") }, { L_, "\x3b", decode("\x3b") }, { L_, "\x3c", decode("\x3c") }, { L_, "\x3d", decode("\x3d") }, { L_, "\x3e", decode("\x3e") }, { L_, "\x3f", decode("\x3f") }, { L_, "\x40", decode("\x40") }, { L_, "\x41", decode("\x41") }, { L_, "\x42", decode("\x42") }, { L_, "\x43", decode("\x43") }, { L_, "\x44", decode("\x44") }, { L_, "\x45", decode("\x45") }, { L_, "\x46", decode("\x46") }, { L_, "\x47", decode("\x47") }, { L_, "\x48", decode("\x48") }, { L_, "\x49", decode("\x49") }, { L_, "\x4a", decode("\x4a") }, { L_, "\x4b", decode("\x4b") }, { L_, "\x4c", decode("\x4c") }, { L_, "\x4d", decode("\x4d") }, { L_, "\x4e", decode("\x4e") }, { L_, "\x4f", decode("\x4f") }, { L_, "\x50", decode("\x50") }, { L_, "\x51", decode("\x51") }, { L_, "\x52", decode("\x52") }, { L_, "\x53", decode("\x53") }, { L_, "\x54", decode("\x54") }, { L_, "\x55", decode("\x55") }, { L_, "\x56", decode("\x56") }, { L_, "\x57", decode("\x57") }, { L_, "\x58", decode("\x58") }, { L_, "\x59", decode("\x59") }, { L_, "\x5a", decode("\x5a") }, { L_, "\x5b", decode("\x5b") }, { L_, "\x5c", decode("\x5c") }, { L_, "\x5d", decode("\x5d") }, { L_, "\x5e", decode("\x5e") }, { L_, "\x5f", decode("\x5f") }, { L_, "\x60", decode("\x60") }, { L_, "\x61", decode("\x61") }, { L_, "\x62", decode("\x62") }, { L_, "\x63", decode("\x63") }, { L_, "\x64", decode("\x64") }, { L_, "\x65", decode("\x65") }, { L_, "\x66", decode("\x66") }, { L_, "\x67", decode("\x67") }, { L_, "\x68", decode("\x68") }, { L_, "\x69", decode("\x69") }, { L_, "\x6a", decode("\x6a") }, { L_, "\x6b", decode("\x6b") }, { L_, "\x6c", decode("\x6c") }, { L_, "\x6d", decode("\x6d") }, { L_, "\x6e", decode("\x6e") }, { L_, "\x6f", decode("\x6f") }, { L_, "\x70", decode("\x70") }, { L_, "\x71", decode("\x71") }, { L_, "\x72", decode("\x72") }, { L_, "\x73", decode("\x73") }, { L_, "\x74", decode("\x74") }, { L_, "\x75", decode("\x75") }, { L_, "\x76", decode("\x76") }, { L_, "\x77", decode("\x77") }, { L_, "\x78", decode("\x78") }, { L_, "\x79", decode("\x79") }, { L_, "\x7a", decode("\x7a") }, { L_, "\x7b", decode("\x7b") }, { L_, "\x7c", decode("\x7c") }, { L_, "\x7d", decode("\x7d") }, { L_, U8_0007e, decode(U8_0007e) }, { L_, U8_0007f, decode(U8_0007f) }, { L_, U8_00080, decode(U8_00080) }, { L_, U8_00081, decode(U8_00081) }, { L_, U8_000ff, decode(U8_000ff) }, { L_, U8_007fe, decode(U8_007fe) }, { L_, U8_007ff, decode(U8_007ff) }, { L_, U8_00800, decode(U8_00800) }, { L_, U8_00801, decode(U8_00801) }, { L_, U8_0fffe, decode(U8_0fffe) }, { L_, U8_0ffff, decode(U8_0ffff) }, { L_, U8_10000, decode(U8_10000) }, { L_, U8_10001, decode(U8_10001) }, { L_, U8_10fffe, decode(U8_10fffe) }, { L_, U8_10ffff, decode(U8_10ffff) }, }; enum { NUM_INTERESTING_CODEPOINTS = sizeof legalCodepointData / sizeof *legalCodepointData }; // ============================================================================ // Usage Example // ---------------------------------------------------------------------------- namespace USAGE { ///Usage ///----- // For our usage example we will define some functions that can encode UTF-8, // use them to build some strings, and observe how the functions defined in // this class perform on them. //.. void utf8AppendOneByte(bsl::string *string, int value) // Append the specified 1-byte UTF-8-encoded 'value' to the end of the // specified 'string'. { ASSERT(0 == (value & ~0x7f)); *string += static_cast<char>(value); } void utf8AppendTwoBytes(bsl::string *string, int value) // Append the specified 2-byte UTF-8-encoded 'value' to the end of the // specified 'string'. { ASSERT(0 == (value & ~0x7ff)); unsigned char buf[3]; buf[0] = static_cast<unsigned char>(((value & 0x7c0) >> 6) | 0xc0); buf[1] = static_cast<unsigned char>( (value & 0x3f) | 0x80); buf[2] = 0; *string += reinterpret_cast<char *>(buf); } void utf8AppendThreeBytes(bsl::string *string, int value) // Append the specified 3-byte UTF-8-encoded 'value' to the end of the // specified 'string'. { ASSERT(0 == (value & ~0xffff)); unsigned char buf[4]; buf[0] = static_cast<unsigned char>(((value & 0xf000) >> 12) | 0xe0); buf[1] = static_cast<unsigned char>(((value & 0xfc0) >> 6) | 0x80); buf[2] = static_cast<unsigned char>( (value & 0x3f) | 0x80); buf[3] = 0; *string += reinterpret_cast<char *>(buf); } void utf8AppendFourBytes(bsl::string *string, int value) // Append the specified 4-byte UTF-8-encoded 'value' to the end of the // specified 'string'. { ASSERT(static_cast<unsigned>(value) <= 0x10ffff); unsigned char buf[5]; buf[0] = static_cast<unsigned char>(((value & 0x1c0000) >> 18) | 0xf0); buf[1] = static_cast<unsigned char>(((value & 0x3f000) >> 12) | 0x80); buf[2] = static_cast<unsigned char>(((value & 0xfc0) >> 6) | 0x80); buf[3] = static_cast<unsigned char>( (value & 0x3f) | 0x80); buf[4] = 0; *string += reinterpret_cast<char *>(buf); } void utf8Append(bsl::string *string, unsigned int value) // Append the specified UTF-8-encoded 'value' in the minimum number of // bytes to the end of the specified 'string'. { ASSERT(value <= 0x10ffff); if (value <= 0x7f) { utf8AppendOneByte(string, value); return; // RETURN } if (value <= 0x7ff) { utf8AppendTwoBytes(string, value); return; // RETURN } if (value <= 0xffff) { utf8AppendThreeBytes(string, value); return; // RETURN } utf8AppendFourBytes(string, value); } //.. } // close namespace USAGE // ============================================================================ // HELPER DEFINITIONS FOR TEST 4 // ---------------------------------------------------------------------------- namespace BDEDE_UTF8UTIL_CASE_4 { const int surrogates[] = {0xd800, 0xd811, 0xd9a3, 0xd9ff, 0xda00, 0xda35, 0xdb80, 0xdbff, 0xdc00, 0xdc48, 0xdd84, 0xddff, 0xde00, 0xde73, 0xdf24, 0xdfff}; const int *loSgates = surrogates; const int *hiSgates = surrogates + 8; bsl::string codeRandSurrogate() // Return a random surrogate. { int val = randNum(); if (val &0x1800) { val = (val & 0x7ff) + 0xd800; } else { val = surrogates[val & 0xf]; } return code24(val); } bsl::string codeRandSurrogatePair() // Return a pair of random surrogates. { int val = randNum(); int loSgate, hiSgate; if (val & (3 << 20)) { loSgate = 0xd800 + (val & 0x3ff); hiSgate = 0xdc00 + ((val >> 10) & 0x3ff); } else { loSgate = loSgates[val & 7]; hiSgate = hiSgates[(val >> 3) & 7]; } return code24(loSgate) + code24(hiSgate); } bsl::string codeRandBenign() // Return a random UTF-8 codepoint with no zeroes or surrogates. { int val; do { val = randVal(); } while (0 == val || (0xd800 <= val && 0xdfff >= val) || val > 0x10ffff); return utf8Encode(val); } } // close namespace BDEDE_UTF8UTIL_CASE_4 // ============================================================================ // HELPER DEFINITIONS FOR TEST 2 // ---------------------------------------------------------------------------- namespace BDEDE_UTF8UTIL_CASE_2 { bsl::string makeString(const char *pc, size_t len) // Return a 'bsl::string' containing the specified 'len' bytes from the // specified 'pc'. { bsl::string ret; ret.insert(0, pc, len); return ret; } #define STR(testId) makeString(encode ## testId, sizeof(encode ## testId)) } // close namespace BDEDE_UTF8UTIL_CASE_2 static const struct { int d_lineNum; // source line number const char *d_utf8_p; // UTF-8 input string int d_numBytes; // length of spec (in bytes), not including // null-terminator int d_numCodePoints; // number of UTF-8 code points (-1 if invalid) int d_errOffset; // byte offset to first invalid sequence; // -1 if valid int d_isValid; // 1 if valid UTF-8; 0 otherwise } DATA[] = { //L# input #b #c eo result //-- ----- -- -- -- ------ { L_, "", 0, 0, -1, 1 }, { L_, " ", 1, 1, -1, 1 }, { L_, "H", 1, 1, -1, 1 }, { L_, "He", 2, 2, -1, 1 }, { L_, "Hel", 3, 3, -1, 1 }, { L_, "Hell", 4, 4, -1, 1 }, { L_, "Hello", 5, 5, -1, 1 }, // Check the boundary between 1-octet and 2-octet code points. { L_, "\x7f", 1, 1, -1, 1 }, { L_, U8_00080, 2, 1, -1, 1 }, // Check the boundary between 2-octet and 3-octet code points. { L_, U8_007ff, 2, 1, -1, 1 }, { L_, U8_00800, 3, 1, -1, 1 }, // Check the maximal 3-octet code point. { L_, U8_0ffff, 3, 1, -1, 1 }, // Make sure 4-octet code points are handled correctly. { L_, U8_10000, 4, 1, -1, 1 }, { L_, U8_10000 " ", 5, 2, -1, 1 }, { L_, " " U8_10001 " ", 6, 3, -1, 1 }, { L_, U8_10fffe, 4, 1, -1, 1 }, { L_, U8_10fffe " ", 5, 2, -1, 1 }, { L_, " " U8_10ffff " ", 6, 3, -1, 1 }, // Make sure partial 4-octet code points are handled correctly (with a // single error). { L_, "\xf0", 1, -1, 0, 0 }, { L_, "\xf0\x80", 2, -1, 0, 0 }, { L_, "\xf0\x80\x80", 3, -1, 0, 0 }, { L_, "\xf0 ", 2, -1, 0, 0 }, { L_, "\xf0\x80 ", 3, -1, 0, 0 }, { L_, "\xf0\x80\x80 ", 4, -1, 0, 0 }, // Make sure the "illegal" UTF-8 octets are handled correctly: // o The octet values C0, C1, F5 to FF never appear. { L_, "\xc0", 1, -1, 0, 0 }, { L_, "\xc1", 1, -1, 0, 0 }, { L_, "\xf5", 1, -1, 0, 0 }, { L_, "\xf6", 1, -1, 0, 0 }, { L_, "\xf7", 1, -1, 0, 0 }, { L_, "\xf8", 1, -1, 0, 0 }, { L_, "\xf9", 1, -1, 0, 0 }, { L_, "\xfa", 1, -1, 0, 0 }, { L_, "\xfb", 1, -1, 0, 0 }, { L_, "\xfc", 1, -1, 0, 0 }, { L_, "\xfd", 1, -1, 0, 0 }, { L_, "\xfe", 1, -1, 0, 0 }, { L_, "\xff", 1, -1, 0, 0 }, // Make sure that the "illegal" UTF-8 octets are handled correctly // mid-string: // o The octet values C0, C1, F5 to FF never appear. { L_, " \xc0 ", 3, -1, 1, 0 }, { L_, " \xc1 ", 3, -1, 1, 0 }, { L_, " \xf5 ", 3, -1, 1, 0 }, { L_, " \xf6 ", 3, -1, 1, 0 }, { L_, " \xf7 ", 3, -1, 1, 0 }, { L_, " \xf8 ", 3, -1, 1, 0 }, { L_, " \xf9 ", 3, -1, 1, 0 }, { L_, " \xfa ", 3, -1, 1, 0 }, { L_, " \xfb ", 3, -1, 1, 0 }, { L_, " \xfc ", 3, -1, 1, 0 }, { L_, " \xfd ", 3, -1, 1, 0 }, { L_, " \xfe ", 3, -1, 1, 0 }, { L_, " \xff ", 3, -1, 1, 0 }, { L_, U8_00080, 2, 1, -1, 1 }, { L_, "\xc2", 1, -1, 0, 0 }, { L_, U8_00080 " ", 3, 2, -1, 1 }, { L_, U8_000ff, 2, 1, -1, 1 }, { L_, "\x01\x20\x7f" U8_000ff U8_007ff U8_00800 U8_0ffff, 13, 7, -1, 1 }, { L_, "\x01\x20\x7f" U8_000ff U8_007ff U8_00800 "\xef", 12, -1, 10, 0 }, { L_, "\x01\x20\x7f" U8_000ff U8_007ff U8_00800 "\xef\xbf", 12, -1, 10, 0 }, { L_, U8_0ffff U8_00800 U8_007ff U8_000ff "\x7f\x20\x01", 13, 7, -1, 1 }, // Make sure illegal overlong encodings are not accepted. These code // points are mathematically correctly encoded, but since there are // equivalent 1-octet encodings, the UTF-8 standard disallows them. { L_, "\xc0\x81", 2, -1, 0, 0 }, { L_, "\xc0\xbf", 2, -1, 0, 0 }, { L_, "\xc1\x81", 2, -1, 0, 0 }, { L_, "\xc1\xbf", 2, -1, 0, 0 }, // Corrupted 2-octet code point: { L_, "\xc2", 1, -1, 0, 0 }, { L_, " \xc2", 2, -1, 1, 0 }, { L_, "\xc2 ", 2, -1, 0, 0 }, { L_, "\xc2\xc2 ", 3, -1, 0, 0 }, { L_, "\xc2 \xc2", 3, -1, 0, 0 }, // Corrupted 2-octet code point followed by a valid code point: { L_, "\xc2" U8_00080, 3, -1, 0, 0 }, { L_, "\xc2" U8_00080, 3, -1, 0, 0 }, // Corrupted 2-octet code point followed by an invalid code point: { L_, "\xc2\xff", 2, -1, 0, 0 }, { L_, "\xc2\xff", 2, -1, 0, 0 }, // 3-octet code points corrupted after octet 1: { L_, "\xef", 1, -1, 0, 0 }, { L_, " \xef", 2, -1, 1, 0 }, { L_, "\xef ", 2, -1, 0, 0 }, { L_, "\xef\xef ", 3, -1, 0, 0 }, { L_, "\xef \xef", 3, -1, 0, 0 }, { L_, "\xef" U8_00080, 3, -1, 0, 0 }, // 3-octet code points corrupted after octet 2: { L_, "\xef\xbf", 2, -1, 0, 0 }, { L_, "\xef\xbf", 2, -1, 0, 0 }, { L_, " \xef\xbf@", 4, -1, 1, 0 }, { L_, " \xef\xbf@", 4, -1, 1, 0 }, { L_, "\xef\xbf ", 3, -1, 0, 0 }, { L_, "\xef\xbf ", 3, -1, 0, 0 }, { L_, "\xef\xbf" U8_00080, 4, -1, 0, 0 }, { L_, "\xef\xbf" U8_00080, 4, -1, 0, 0 }, { L_, "\xef\xbf" U8_00080 " ", 5, -1, 0, 0 }, { L_, "\xef\xbf" U8_00080 " ", 5, -1, 0, 0 }, { L_, "\xef\xbf" U8_00080 " ", 5, -1, 0, 0 }, { L_, "\xef\xbf\xef\xbf ", 5, -1, 0, 0 }, { L_, "\xef\xbf\xef\xbf ", 5, -1, 0, 0 }, { L_, "\xef\xbf \xef\xbf", 5, -1, 0, 0 }, { L_, "\xef\xbf \xef\xbf", 4, -1, 0, 0 }, { L_, "\xef\xbf \xef\xbf", 4, -1, 0, 0 }, }; enum { NUM_DATA = sizeof DATA / sizeof *DATA }; // ============================================================================ // MAIN PROGRAM // ---------------------------------------------------------------------------- int main(int argc, char *argv[]) { int test = argc > 1 ? bsl::atoi(argv[1]) : 0; verbose = argc > 2; veryVerbose = argc > 3; veryVeryVerbose = argc > 4; veryVeryVeryVerbose = argc > 5; cout << "TEST " << __FILE__ << " CASE " << test << endl;; // CONCERN: 'BSLS_REVIEW' failures should lead to test failures. bsls::ReviewFailureHandlerGuard reviewGuard(&bsls::Review::failByAbort); switch (test) { case 0: // Zero is always the leading case. case 14: { // -------------------------------------------------------------------- // USAGE EXAMPLE 2: 'advance' // // Concerns: //: 1 Demonstrate the 'advance*' functions. // // Plan: //: 1 Use the 'appendUtf8Character' function to build an example //: string, then advance through it. // // Testing: // USAGE EXAMPLE 2 // -------------------------------------------------------------------- using namespace USAGE; if (verbose) cout << "USAGE EXAMPLE 2: 'advance'\n" "==========================\n"; // In this example, we will use the various 'advance' functions to advance // through a UTF-8 string. // // First, build the string using 'appendUtf8Character', keeping track of how // many bytes are in each Unicode code point: //.. bsl::string string; bdlde::Utf8Util::appendUtf8Character(&string, 0xff00); // 3 bytes bdlde::Utf8Util::appendUtf8Character(&string, 0x1ff); // 2 bytes bdlde::Utf8Util::appendUtf8Character(&string, 'a'); // 1 byte bdlde::Utf8Util::appendUtf8Character(&string, 0x1008aa); // 4 bytes bdlde::Utf8Util::appendUtf8Character(&string, 0x1abcd); // 4 bytes string += "\xe3\x8f\xfe"; // 3 bytes (invalid 3-byte sequence, // the first 2 bytes are valid but the // last continuation byte is invalid) bdlde::Utf8Util::appendUtf8Character(&string, 'w'); // 1 byte bdlde::Utf8Util::appendUtf8Character(&string, '\n'); // 1 byte //.. // Then, declare a few variables we'll need: //.. int rc, status; const char *result; const char *const start = string.c_str(); //.. // Next, try advancing 2 code points, then 3, then 4, observing that the value // returned is the number of Unicode code points advanced. Note that since // we're only advancing over valid UTF-8, we can use either 'advanceRaw' or // 'advanceIfValid': //.. rc = bdlde::Utf8Util::advanceRaw( &result, start, 2); ASSERT(2 == rc); ASSERT(3 + 2 == result - start); rc = bdlde::Utf8Util::advanceIfValid(&status, &result, start, 2); ASSERT(0 == status); ASSERT(2 == rc); ASSERT(3 + 2 == result - start); rc = bdlde::Utf8Util::advanceRaw( &result, start, 3); ASSERT(3 == rc); ASSERT(3 + 2 + 1 == result - start); rc = bdlde::Utf8Util::advanceIfValid(&status, &result, start, 3); ASSERT(0 == status); ASSERT(3 == rc); ASSERT(3 + 2 + 1 == result - start); rc = bdlde::Utf8Util::advanceRaw( &result, start, 4); ASSERT(4 == rc); ASSERT(3 + 2 + 1 + 4 == result - start); rc = bdlde::Utf8Util::advanceIfValid(&status, &result, start, 4); ASSERT(0 == status); ASSERT(4 == rc); ASSERT(3 + 2 + 1 + 4 == result - start); //.. // Then, try advancing by more code points than are present using // 'advanceIfValid', and wind up stopping when we encounter invalid input. The // behavior of 'advanceRaw' is undefined if it is used on invalid input, so we // cannot use it here. Also note that we will stop at the beginning of the // invalid Unicode code point, and not at the first incorrect byte, which is // two bytes later: //.. rc = bdlde::Utf8Util::advanceIfValid(&status, &result, start, INT_MAX); ASSERT(0 != status); ASSERT(5 == rc); ASSERT(3 + 2 + 1 + 4 + 4 == result - start); ASSERT(static_cast<int>(string.length()) > result - start); //.. // Now, doctor the string to replace the invalid code point with a valid one, // so the string is entirely correct UTF-8: //. string[3 + 2 + 1 + 4 + 4 + 2] = static_cast<char>(0x8a); //.. // Finally, advance using both functions by more code points than are in the // string and in both cases wind up at the end of the string. Note that // 'advanceIfValid' does not return an error (non-zero) value to 'status' when // it encounters the end of the string: //.. rc = bdlde::Utf8Util::advanceRaw( &result, start, INT_MAX); ASSERT(8 == rc); ASSERT(3 + 2 + 1 + 4 + 4 + 3 + 1 + 1 == result - start); ASSERT(static_cast<int>(string.length()) == result - start); rc = bdlde::Utf8Util::advanceIfValid(&status, &result, start, INT_MAX); ASSERT(0 == status); ASSERT(8 == rc); ASSERT(3 + 2 + 1 + 4 + 4 + 3 + 1 + 1 == result - start); ASSERT(static_cast<int>(string.length()) == result - start); //.. } break; case 13: { // -------------------------------------------------------------------- // USAGE EXAMPLE 1: 'isValid' AND 'numCodePoints*' // // Concerns: //: 1 Demonstrate the routines by encoding some UTF-8 strings and //: validating them and counting their code points. // // Plan: //: 1 Create both UTF-8 and modified UTF-8 strings and validate them. // // Testing: // USAGE EXAMPLE 1 // -------------------------------------------------------------------- using namespace USAGE; if (verbose) cout << "USAGE EXAMPLE 1: 'isValid' AND 'numCodePoints*'\n" "===============================================\n"; // In this usage example, we will encode some Unicode code points in UTF-8 // strings and demonstrate those that are valid and those that are not. // // First, we build an unquestionably valid UTF-8 string: //.. bsl::string string; bdlde::Utf8Util::appendUtf8Character(&string, 0xff00); bdlde::Utf8Util::appendUtf8Character(&string, 0x856); bdlde::Utf8Util::appendUtf8Character(&string, 'a'); bdlde::Utf8Util::appendUtf8Character(&string, 0x1008aa); bdlde::Utf8Util::appendUtf8Character(&string, 0xfff); bdlde::Utf8Util::appendUtf8Character(&string, 'w'); bdlde::Utf8Util::appendUtf8Character(&string, 0x1abcd); bdlde::Utf8Util::appendUtf8Character(&string, '.'); bdlde::Utf8Util::appendUtf8Character(&string, '\n'); //.. // Then, we check its validity and measure its length: //.. ASSERT(true == bdlde::Utf8Util::isValid(string.data(), string.length())); ASSERT(true == bdlde::Utf8Util::isValid(string.c_str())); ASSERT( 9 == bdlde::Utf8Util::numCodePointsRaw(string.data(), string.length())); ASSERT( 9 == bdlde::Utf8Util::numCodePointsRaw(string.c_str())); //.. // Next, we encode a lone surrogate value, which is not allowed, using // 'utf8Append' instead of 'appendUtf8Character' to avoid validation: //.. bsl::string stringWithSurrogate = string; utf8Append(&stringWithSurrogate, 0xd8ab); //.. ASSERT(false == bdlde::Utf8Util::isValid(stringWithSurrogate.data(), stringWithSurrogate.length())); ASSERT(false == bdlde::Utf8Util::isValid(stringWithSurrogate.c_str())); //.. // Then, we cannot use 'numCodePointsRaw' to count the code points in // 'stringWithSurrogate', since the behavior of that method is undefined unless // the string is valid. Instead, the 'numCodePointsIfValid' method can be used // on strings whose validity we are uncertain of: //.. const char *invalidPosition = 0; ASSERT(-1 == bdlde::Utf8Util::numCodePointsIfValid( &invalidPosition, stringWithSurrogate.data(), stringWithSurrogate.length())); ASSERT(invalidPosition == stringWithSurrogate.data() + string.length()); invalidPosition = 0; // reset ASSERT(-1 == bdlde::Utf8Util::numCodePointsIfValid( &invalidPosition, stringWithSurrogate.c_str())); ASSERT(invalidPosition == stringWithSurrogate.data() + string.length()); //.. // Now, we encode 0, which is allowed. However, note that we cannot use any // interfaces that take a null-terminated string for this case: //.. bsl::string stringWithNull = string; utf8AppendOneByte(&stringWithNull, 0); //.. ASSERT(true == bdlde::Utf8Util::isValid(stringWithNull.data(), stringWithNull.length())); ASSERT( 10 == bdlde::Utf8Util::numCodePointsRaw(stringWithNull.data(), stringWithNull.length())); //.. // Finally, we encode '0x61' ('a') as an overlong value using 2 bytes, which is // not valid UTF-8 (since 'a' can be "encoded" in 1 byte): //.. bsl::string stringWithOverlong = string; utf8AppendTwoBytes(&stringWithOverlong, 'a'); ASSERT(false == bdlde::Utf8Util::isValid(stringWithOverlong.data(), stringWithOverlong.length())); ASSERT(false == bdlde::Utf8Util::isValid(stringWithOverlong.c_str())); //.. } break; case 12: { // -------------------------------------------------------------------- // TESTING 'appendUtf8Character' // // Concerns: //: 1 The method under test produce the expected results on valid //: codepoints. The principal concern is that the append is //: performed correctly. // // Plan: //: 1 Use the table-driven approach to verify correct behavior when //: appending various valid codepoints to both empty and non-empty //: strings. This is sufficient since the routine under test is //: implemented in terms of an already tested component. // // Testing: // int appendUtf8Character(bsl::string *, unsigned int); // -------------------------------------------------------------------- if (verbose) cout << "\nTESTING 'appendUtf8Character'\n" "=============================\n"; for (int ti = 0; ti < NUM_INTERESTING_CODEPOINTS; ++ti) { const int LINE = legalCodepointData[ti].d_lineNum; const char *UTF8 = legalCodepointData[ti].d_utf8_p; bsl::size_t UTF8_LEN = strlen(UTF8); unsigned int CODEPOINT = legalCodepointData[ti].d_codepoint; bsl::string empty; bsl::string non_empty("Not an empty string"); bsl::size_t non_empty_init_len = non_empty.length(); if (veryVerbose) { T_; P_(ti); P_(LINE); P_(dumpStr(UTF8)); P_(UTF8_LEN); P(CODEPOINT); } ASSERT(0 == Obj::appendUtf8Character(&empty, CODEPOINT)); ASSERT(UTF8_LEN == empty.length()); ASSERT(0 == Obj::appendUtf8Character(&non_empty, CODEPOINT)); ASSERT(non_empty_init_len + UTF8_LEN == non_empty.length()); } } break; case 11: { // -------------------------------------------------------------------- // TESTING 'getByteSize' // // Concerns: //: 1 The method under test produce the expected results on valid UTF-8 //: codepoints. // // Plan: //: 1 Use the table-driven approach to verify correct behavior on //: various valid UTF-8 codepoints. // // Testing: // int getByteSize(const char *); // -------------------------------------------------------------------- if (verbose) cout << "\nTESTING 'getByteSize'\n" "=====================\n"; for (int ti = 0; ti < NUM_INTERESTING_CODEPOINTS; ++ti) { const int LINE = legalCodepointData[ti].d_lineNum; const char *UTF8 = legalCodepointData[ti].d_utf8_p; bsl::size_t UTF8_LEN = strlen(UTF8); if (veryVerbose) { T_; P_(ti); P_(LINE); P_(dumpStr(UTF8)); P(UTF8_LEN); } ASSERT(int(UTF8_LEN) == Obj::getByteSize(UTF8)); } } break; case 10: { // -------------------------------------------------------------------- // TESTING 'numBytesIfValid' // // Concerns: //: 1 The method under test produce the expected results on valid UTF-8 //: strings whether or not embedded '\0' characters are present. // // Plan: //: 1 Use the table-driven approach to verify correct behavior on //: various valid UTF-8 strings. Append a '\0' to each candidate //: string, then repeat appending each table entry again. // // Testing: // IntPtr numBytesIfValid(const bslstl::StringRef&, IntPtr); // -------------------------------------------------------------------- if (verbose) cout << "\nTESTING 'numBytesIfValid'\n" "=========================\n"; for (int ti = 0; ti < NUM_INTERESTING_CODEPOINTS; ++ti) { const int LINE = legalCodepointData[ti].d_lineNum; const bsl::string UTF8 = legalCodepointData[ti].d_utf8_p; if (veryVerbose) { T_; P_(ti); P_(LINE); P_(dumpStr(UTF8)); P(UTF8.length()); } ASSERT(Obj::IntPtr(UTF8.length()) == Obj::numBytesIfValid(UTF8, 1)); for (int tj = 0; tj < NUM_INTERESTING_CODEPOINTS; ++tj) { const int LINE_2 = legalCodepointData[tj].d_lineNum; bsl::string UTF8_2 = UTF8; UTF8_2.push_back(0); UTF8_2 += legalCodepointData[tj].d_utf8_p; if (veryVeryVerbose) { T_; T_; P_(tj); P_(LINE_2); P_(dumpStr(UTF8_2)); P(UTF8_2.length()); } // Adding 2nd codepoint doesn't change the answer if we only // ask for the 1st codepoint's byte length. ASSERT(Obj::IntPtr(UTF8.length()) == Obj::numBytesIfValid(UTF8_2, 1)); // Embedded NUL's count as 1 byte. ASSERT(1 + Obj::IntPtr(UTF8.length()) == Obj::numBytesIfValid(UTF8_2, 2)); ASSERT(Obj::IntPtr(UTF8_2.length()) == Obj::numBytesIfValid(UTF8_2, 3)); } } } break; case 9: { // -------------------------------------------------------------------- // TESTING CORRECT + BROKEN GLASS // // CONCERN: //: 1 That 'advanceIfValid' will detect all forms of error sequences //: and properly terminate and report them. // // PLAN: //: 1 In TC 8, we generated correct sequences containing up to 2 of //: every type of correct Unicode code point. In this sequence, we //: will generate correct sequences of only up to 1 of every type of //: correct Unicode code point. //: 2 We will follow these correct sequences with an error sequence, //: and observe the 'advanceIfValid' detects and returns a pointer to //: the incorrect sequence every time. //: 3 If the error sequence was truncated, we will repeat the test, //: appending a correct sequence after the error sequence, and //: observe this makes no difference to the result. // // Testing: // 'advanceIfValid' on correct input followed by incorrect input // -------------------------------------------------------------------- if (verbose) cout << "\nTESTING CORRECT + BROKEN GLASS\n" "==============================\n"; typedef void (*AppendFunc)(bsl::string *); struct { const char *d_string_p; unsigned d_truncatedBy; AppendFunc d_appendFunc; unsigned d_index; // only used for debugging } DATA[] = { { "\x84", 1, 0, 0 }, // unexpected continuation { "\x80\x8f", 1, 0, 1 }, // unexpected continuation { "\x8a\x87\xac", 1, 0, 2 }, // unexpected continuation { "\x8c\x97\xac\xbf", 1, 0, 3 }, // unexpected continuation // All entries above ('index < CONTINUATION_BOUNDARY') are // continuations. { "\xf4\x8f\xbf", 1, &appendRand4Byte, 4 }, // 4 byte trunc { "\xf4\x8f", 2, &appendRand4Byte, 5 }, // 4 byte trunc { "\xf4", 3, &appendRand4Byte, 6 }, // 4 byte trUNC { "\xef\xbf", 1, &appendRand3Byte, 7 }, // 3 byte trunc { "\xef", 2, &appendRand3Byte, 8 }, // 3 byte trunc { "\xdf", 1, &appendRand2Byte, 9 }, // 2 byte trunc { "\xf8", 0, 0, 10 }, // illegal in any context { "\xf0\x80\xbf\xbf", 0, 0, 11 }, // max non-minimal 4 byte { "\xe0\x9f\xbf", 0, 0, 12 }, // max non-minimal 3 byte { "\xc1\xbf", 0, 0, 13 }, // max non-minimal 2 byte { "\xed\xa0\x00", 0, 0, 14 }, // min surrogate { "\xed\xbf\xbf", 0, 0, 15 }, // max surrogate }; enum { NUM_DATA = sizeof DATA / sizeof *DATA }; bsl::vector<int> vec; bsl::vector<int> origVec; bsl::string correctStr; bsl::string str; vec. reserve(5); origVec.reserve(5); correctStr.reserve(200);// reserve longer than the longest length we // will use, so no manipulation of this // 'string' will result in a reallocation and a // move of the buffer. str.reserve(200 + 10); // enough room to copy 'correctStr' and tack // some carnage on to the end of it. for (int useZero = 0; useZero < 2; ++useZero) { const int numValues = 4 + useZero; const int correctIterations = 1 << numValues; const int zeroUsedMask = 1 << 4; for (int key = 0; key < correctIterations; ++key) { if (useZero && 0 == (key & zeroUsedMask)) { continue; } bool zeroUsed = false; vec.clear(); for (int jj = 0; jj < numValues; ++jj) { // Valid values of 'bytesPerCodePoint' are 1, 2, 3, 4, and // 0, and '0' gets converted from 'jj == 4', and only when // 'numValues == 5'. if (key & (1 << jj)) { int bytesPerCodePoint = jj + 1; if (5 == bytesPerCodePoint) { bytesPerCodePoint = 0; zeroUsed = true; } vec.push_back(bytesPerCodePoint); } } ASSERT(!useZero || zeroUsed); origVec = vec; do { // for all permutations of vec correctStr.clear(); for (unsigned jj = 0; jj < vec.size(); ++jj) { switch (vec[jj]) { case 1: { appendRand1Byte(&correctStr); } break; case 2: { appendRand2Byte(&correctStr); } break; case 3: { appendRand3Byte(&correctStr); } break; case 4: { appendRand4Byte(&correctStr); } break; case 0: { correctStr.push_back('\0'); } break; default: { ASSERT(0); } } } if (veryVerbose) { P(dumpVec(vec)); P(dumpStr(correctStr)); } for (int ti = 0; ti < NUM_DATA; ++ti) { const char *ERROR_STR = DATA[ti].d_string_p; const int TRUNCATED_BY = DATA[ti].d_truncatedBy; AppendFunc APPEND_FUNC = DATA[ti].d_appendFunc; str = correctStr; if (APPEND_FUNC) { (*APPEND_FUNC)(&str); if (TRUNCATED_BY) { str.resize(str.length() - TRUNCATED_BY); } } else { str += ERROR_STR; } const char * const begin = str.c_str(); const char * const endOfValid = begin + correctStr.length(); const char * end; int numCodePoints; int sts; const int numCodePointsArg = int(vec.size()); const int strLength = int(str.length()); if (!useZero) { sts = -2; end = "woof"; numCodePoints = Obj::advanceIfValid(&sts, &end, begin, INT_MAX); ASSERT(endOfValid == end); ASSERT(numCodePointsArg == numCodePoints); ASSERT(-1 == sts); } sts = -2; end = "woof"; numCodePoints = Obj::advanceIfValid(&sts, &end, begin, strLength, INT_MAX); ASSERT(endOfValid == end); ASSERT(numCodePointsArg == numCodePoints); ASSERT(-1 == sts); if (0 != TRUNCATED_BY) { // Now, if the error char was truncated, we tack a // correct char on after and observe no change to // the result: appendRandCorrectCodePoint(&str, useZero); if (!useZero) { sts = -2; end = "woof"; numCodePoints = Obj::advanceIfValid(&sts, &end, begin, INT_MAX); ASSERT(endOfValid == end); ASSERT(numCodePointsArg == numCodePoints); ASSERT(-1 == sts); } sts = -2; end = "woof"; numCodePoints = Obj::advanceIfValid(&sts, &end, begin, strLength, INT_MAX); ASSERT(endOfValid == end); ASSERT(numCodePointsArg == numCodePoints); ASSERT(-1 == sts); } } bsl::next_permutation(vec.begin(), vec.end()); } while (origVec != vec); } } } break; case 8: { // -------------------------------------------------------------------- // TESTING EXHAUSTIVE CORRECT SEQUENCES // // CONCERN: //: 1 That 'advanceIfValid' and 'advanceRaw' perform as documented on //: computer-generated sequences of correct UTF-8 input. // // PLAN: //: 1 We create static functions 'appendRand*Char(bsl::string*)' that //: will append one random Unicode code point of the 4 possible valid //: lengths to a string. //: 2 There are 5 types of code points we will have in the input //: strings: non-zero Unicode values of the 4 possible lengths, and //: the zero char. We represent string containing up to two of each //: of those values with a vector 'vec' of integers, where value //: '1-4' represent non-zero Unicode code points of the length //: indicated by the number, and 0 representing a 0 code point. //: 3 We do our tests twice, once where we don't include any 0 code //: points for testing functions that take zero-terminated input, and //: again including 0 code points, by iterating on 'useZero', //: effectively a boolean. //: 4 We have an integer key, where the bottom several bits of the //: value indicate whether Unicode code points of a given length will //: be present in the value. The key is 8 bits long if 0 is not //: used, 10 bits long if 0 is used (two bits for each length, to //: indicate the presence or absence of up to 2 instances of Unicode //: code points). //: 5 The key is processed into 'vec', where each element of vec //: indicates the Unicode code point length (or 0 value) of a Unicode //: code point to be present in the test string. //: 6 We then iterate through all permutations of 'vec'. //: 7 For each permutation, we translate 'vec' into a string, using the //: 'appendRaw*Char' functions described above. //: 8 We then call all forms of 'advance*' function on this string, and //: observe that the return values are as expected. //: 9 We then push a random garbage char onto the end of the string. //: Since we 'reserve'd a long length for the string, this will not //: cause a reallocation of the buffer or invalidation of any of our //: pointers at or into the string. //: 10 We then call the 'advance' functions that either don't take 0 //: terminated input, or that are passed 'numCodePoints', which will //: tell the 'advance*' to finish before examining the garbage byte, //: and observe the functions succeed. // // Testing: // int advanceIfValid(int *, const char **, const char *, int); // int advanceIfValid(int *, const char **, const char *, int, int); // int advanceRaw(const char **, const char *, int); // int advanceRaw(const char **, const char *, int, int); // -------------------------------------------------------------------- if (verbose) cout << "\nTESTING EXHAUSTIVE CORRECT SEQUENCES\n" "====================================\n"; bsl::vector<int> vec; bsl::vector<int> origVec; bsl::string str; vec. reserve(10); origVec.reserve(10); str. reserve(50); // reserve longer than the longest length we // will use, so no manipulation of this // 'string' will result in a reallocation and a // move of the buffer. #if defined(BSLS_PLATFORM_OS_LINUX) || defined(BSLS_PLATFORM_OS_DARWIN) const double defaultFraction = 1.0; #elif defined(BSLS_PLATFORM_OS_AIX) const double defaultFraction = 0.90; #else const double defaultFraction = 0.75; #endif const double fraction = verbose ? strtod(argv[2], 0) : defaultFraction; ASSERT(fraction >= 0.0 && fraction <= 1.0); for (int useZero = 0; useZero < 2; ++useZero) { int numValues = 4 + useZero; // Only throttle 'totalValues' in the case 'useZero == true'. In // the other case, the max length of 'vec' is 8, and the number of // permutations isn't a problem until you get up to 9 or 10. int totalValues = useZero ? int(2 * numValues * (0.5 + fraction * 0.5)) : 2 * numValues; int iterations = 1 << totalValues; if (veryVerbose) P(totalValues); const int zeroUsedMask = (totalValues >= 5 ? (1 << 4) : 0) | (totalValues >= 10 ? (1 << 9) : 0); for (int key = 0; key < iterations; ++key) { if (useZero && 0 == (key & zeroUsedMask)) { continue; } bool zeroUsed = false; vec.clear(); for (int jj = 0; jj < totalValues; ++jj) { // Valid values of 'bytesPerCodePoint' are 1, 2, 3, 4, and // 0, and '0' gets converted from 'jj == 4', and only when // 'numValues == 5'. if (key & (1 << jj)) { int bytesPerCodePoint = jj % numValues + 1; if (5 == bytesPerCodePoint) { bytesPerCodePoint = 0; zeroUsed = true; } vec.push_back(bytesPerCodePoint); } } ASSERT(!useZero || zeroUsed); origVec = vec; do { // for all permutations of vec str.clear(); for (unsigned jj = 0; jj < vec.size(); ++jj) { switch (vec[jj]) { case 1: { appendRand1Byte(&str); } break; case 2: { appendRand2Byte(&str); } break; case 3: { appendRand3Byte(&str); } break; case 4: { appendRand4Byte(&str); } break; case 0: { str.push_back('\0'); } break; default: { ASSERT(0); } } } if (veryVerbose) { P(dumpVec(vec)); P(dumpStr(str)); } const char * const begin = str.c_str(); const char * const endOfString = &*str.end(); const char * end; int numCodePoints; int sts; const int numCodePointsArg = int(vec.size()); const int strLength = int(str.length()); if (!useZero) { end = "woof"; numCodePoints = Obj::advanceRaw(&end, begin, INT_MAX); ASSERT(endOfString == end); ASSERT(numCodePointsArg == numCodePoints); sts = -2; end = "woof"; numCodePoints = Obj::advanceIfValid(&sts, &end, begin, INT_MAX); ASSERT(endOfString == end); ASSERT(numCodePointsArg == numCodePoints); ASSERT(0 == sts); } end = "woof"; numCodePoints = Obj::advanceRaw(&end, begin, strLength, INT_MAX); ASSERT(endOfString == end); ASSERT(numCodePointsArg == numCodePoints); sts = -2; end = "woof"; numCodePoints = Obj::advanceIfValid(&sts, &end, begin, strLength, INT_MAX); ASSERT(endOfString == end); ASSERT(numCodePointsArg == numCodePoints); ASSERT(0 == sts); // Now we tack an extra non-zero garbage char on the end // 'str', and make sure that it makes no difference when // when 'strLength' and 'numCodePointsArg' dictate that it // will not be read. // Don't use 'c == 0' as we already tested that above. char c = char(randUnsigned() % 256 - 128); c = c ? c : 'a'; str.push_back(c); end = "woof"; numCodePoints = Obj::advanceRaw(&end, begin, strLength, INT_MAX); ASSERT(endOfString == end); ASSERT(numCodePointsArg == numCodePoints); sts = -2; end = "woof"; numCodePoints = Obj::advanceIfValid(&sts, &end, begin, strLength, INT_MAX); ASSERT(endOfString == end); ASSERT(numCodePointsArg == numCodePoints); ASSERT(0 == sts); if (!useZero) { end = "woof"; numCodePoints = Obj::advanceRaw(&end, begin, numCodePointsArg); ASSERT(endOfString == end); ASSERT(numCodePointsArg == numCodePoints); sts = -2; end = "woof"; numCodePoints = Obj::advanceIfValid(&sts, &end, begin, numCodePointsArg); ASSERT(endOfString == end); ASSERT(numCodePointsArg == numCodePoints); ASSERT(0 == sts); } end = "woof"; numCodePoints = Obj::advanceRaw(&end, begin, strLength + 1, numCodePointsArg); ASSERT(endOfString == end); ASSERT(numCodePointsArg == numCodePoints); sts = -2; end = "woof"; numCodePoints = Obj::advanceIfValid(&sts, &end, begin, strLength + 1, numCodePointsArg); ASSERT(endOfString == end); ASSERT(numCodePointsArg == numCodePoints); ASSERT(0 == sts); bsl::next_permutation(vec.begin(), vec.end()); } while (origVec != vec); } } } break; case 7: { // -------------------------------------------------------------------- // TESTING REAL PROSE // // Concerns: //: 1 That 'advanceIfValid' and 'advanceRaw', in both their forms, can //: handle a long sequence of correct UTF-8. // // Plan: //: 1 Run both forms of 'advanceIfValid' and 'advanceRaw', respectively //: on our string 'charUtf8MultiLang', and observe that they count //: the code points correctly, and don't report any errors. // // Testing: // int advanceIfValid(int *, const char **, const char *, int); prose // int advanceIfValid(int*,const char**,const char *,int,int); prose // int advanceRaw(const char **, const char *, int); prose // int advanceRaw(const char **, const char *, int, int); prose // -------------------------------------------------------------------- if (verbose) cout << "\nTESTING REAL PROSE\n" "==================\n"; const char *result; int numCodePoints; int sts; const char * const begin = charUtf8MultiLang; bsl::size_t length = sizeof(utf8MultiLang) - 1; const char * const end = begin + length; const int expectedNumCPs = NUM_UTF8_MULTI_LANG_CODE_POINTS - 1; sts = -2; result = "woof"; numCodePoints = Obj::advanceIfValid(&sts, &result, begin, INT_MAX); ASSERT(expectedNumCPs == numCodePoints); ASSERT(result == end); ASSERT(0 == sts); sts = -2; result = "woof"; numCodePoints = Obj::advanceIfValid(&sts, &result, begin, length, INT_MAX); ASSERT(NUM_UTF8_MULTI_LANG_CODE_POINTS - 1 == numCodePoints); ASSERT(result == end); ASSERT(0 == sts); sts = -2; result = "woof"; numCodePoints = Obj::advanceIfValid(&sts, &result, begin, length + 1, expectedNumCPs); ASSERT(expectedNumCPs == numCodePoints); ASSERT(result == end); ASSERT(0 == sts); sts = -2; result = "woof"; numCodePoints = Obj::advanceIfValid(&sts, &result, begin, 0, expectedNumCPs); ASSERT(0 == numCodePoints); ASSERT(0 == sts); ASSERT(result == begin); result = "woof"; numCodePoints = Obj::advanceRaw(&result, begin, INT_MAX); ASSERT(expectedNumCPs == numCodePoints); ASSERT(result == end); result = "woof"; numCodePoints = Obj::advanceRaw(&result, begin, length, INT_MAX); ASSERT(NUM_UTF8_MULTI_LANG_CODE_POINTS - 1 == numCodePoints); ASSERT(result == end); result = "woof"; numCodePoints = Obj::advanceRaw(&result, begin, length + 1, expectedNumCPs); ASSERT(expectedNumCPs == numCodePoints); ASSERT(result == end); result = "woof"; numCodePoints = Obj::advanceRaw(&result, begin, 0, expectedNumCPs); ASSERT(0 == numCodePoints); ASSERT(result == begin); } break; case 6: { // -------------------------------------------------------------------- // TESTING 'isValid' & 'numCodePointsIfValid' // // Concerns: //: 1 The methods under test produce the expected results on both //: valid and invalid UTF-8 strings. // // Plan: //: 1 Use the table-driven approach to verify correct behavior on //: various valid and invalid UTF-8 strings. // // Testing: // bool isValid(const char *s); // bool isValid(const char *s, int len); // bool isValid(const char **err, const char *s); // bool isValid(const char **err, const char *s, int len); // int numCharactersIfValid(**err, const char *s); // int numCharactersIfValid(**err, const char *s, int len); // int numCodePointsIfValid(**err, const char *s); // int numCodePointsIfValid(**err, const char *s, int len); // -------------------------------------------------------------------- if (verbose) cout << "\nTESTING 'isValid' & 'numCodePointsIfValid'\n" "==========================================\n"; for (int ti = 0; ti < NUM_DATA; ++ti) { const int LINE = DATA[ti].d_lineNum; const char *UTF8 = DATA[ti].d_utf8_p; const int NUMBYTES = DATA[ti].d_numBytes; const int NUMCPS = DATA[ti].d_numCodePoints; const int ERROFF = DATA[ti].d_errOffset; const int VALID = DATA[ti].d_isValid; if (veryVerbose) { T_; P_(ti); P_(UTF8); P_(NUMBYTES); P_(NUMCPS); P_(ERROFF); P(VALID); } LOOP_ASSERT(LINE, VALID == Obj::isValid(UTF8)); LOOP_ASSERT(LINE, VALID == Obj::isValid(UTF8, NUMBYTES)); LOOP_ASSERT(LINE, VALID == Obj::isValid(UTF8, NUMBYTES + 1)); const char *ERRSTR = 0; ERRSTR = 0; LOOP_ASSERT(LINE, VALID == Obj::isValid(&ERRSTR, UTF8)); if (VALID) { LOOP_ASSERT(LINE, 0 == ERRSTR); } else { LOOP_ASSERT(LINE, ERROFF == ERRSTR - UTF8); } ERRSTR = 0; LOOP_ASSERT(LINE, VALID == Obj::isValid(&ERRSTR, UTF8, NUMBYTES)); if (VALID) { LOOP_ASSERT(LINE, 0 == ERRSTR); } else { LOOP_ASSERT(LINE, ERROFF == ERRSTR - UTF8); } ERRSTR = 0; LOOP_ASSERT(LINE, VALID == Obj::isValid(&ERRSTR, UTF8, NUMBYTES + 1)); if (VALID) { LOOP_ASSERT(LINE, 0 == ERRSTR); } else { LOOP_ASSERT(LINE, ERROFF == ERRSTR - UTF8); } ERRSTR = 0; LOOP_ASSERT(LINE, NUMCPS == Obj::numCharactersIfValid(&ERRSTR, UTF8)); ERRSTR = 0; LOOP_ASSERT(LINE, NUMCPS == Obj::numCodePointsIfValid(&ERRSTR, UTF8)); if (VALID) { LOOP_ASSERT(LINE, 0 == ERRSTR); } else { LOOP_ASSERT(LINE, ERROFF == ERRSTR - UTF8); } ERRSTR = 0; LOOP_ASSERT(LINE, NUMCPS == Obj::numCharactersIfValid(&ERRSTR, UTF8, NUMBYTES)); ERRSTR = 0; LOOP_ASSERT(LINE, NUMCPS == Obj::numCodePointsIfValid(&ERRSTR, UTF8, NUMBYTES)); if (VALID) { LOOP_ASSERT(LINE, 0 == ERRSTR); } else { LOOP_ASSERT(LINE, ERROFF == ERRSTR - UTF8); } ERRSTR = 0; if (VALID) { LOOP_ASSERT(LINE, NUMCPS + 1 == Obj::numCharactersIfValid(&ERRSTR, UTF8, NUMBYTES + 1)); LOOP_ASSERT(LINE, NUMCPS + 1 == Obj::numCodePointsIfValid(&ERRSTR, UTF8, NUMBYTES + 1)); LOOP_ASSERT(LINE, 0 == ERRSTR); } else { LOOP_ASSERT(LINE, -1 == Obj::numCharactersIfValid(&ERRSTR, UTF8, NUMBYTES + 1)); LOOP_ASSERT(LINE, -1 == Obj::numCodePointsIfValid(&ERRSTR, UTF8, NUMBYTES + 1)); LOOP_ASSERT(LINE, ERROFF == ERRSTR - UTF8); } } } break; case 5: { // -------------------------------------------------------------------- // TESTING 'numCharactersRaw' // // Concerns: //: 1 The methods under test produce the expected results on both //: valid and invalid UTF-8 strings. // // Plan: //: 1 Use the table-driven approach to verify correct behavior on //: various valid and invalid UTF-8 strings. // // Testing: // int numCharacters(const char *s); // int numCharacters(const char *s, int len); // int numCharactersRaw(const char *s); // int numCharactersRaw(const char *s, int len); // int numCodePointsRaw(const char *s); // int numCodePointsRaw(const char *s, int len); // int numCodePoints(const char *s); // int numCodePoints(const char *s, int len); // -------------------------------------------------------------------- if (verbose) cout << "TESTING 'numCharactersRaw'" << endl << "==========================" << endl; for (int ti = 0; ti < NUM_DATA; ++ti) { const int LINE = DATA[ti].d_lineNum; const char *UTF8 = DATA[ti].d_utf8_p; const int NUMBYTES = DATA[ti].d_numBytes; const int NUMCPS = DATA[ti].d_numCodePoints; const int VALID = DATA[ti].d_isValid; if (!VALID) continue; if (veryVerbose) { T_; P_(ti); P_(UTF8); P_(NUMBYTES); P_(NUMCPS); P(VALID); } LOOP_ASSERT(LINE, NUMCPS == Obj::numCodePointsRaw(UTF8)); LOOP_ASSERT(LINE, NUMCPS == Obj::numCodePointsRaw(UTF8, NUMBYTES)); LOOP_ASSERT(LINE, NUMCPS + 1 == Obj::numCodePointsRaw(UTF8, NUMBYTES + 1)); // DEPRECATED LOOP_ASSERT(LINE, NUMCPS == Obj::numCharactersRaw(UTF8)); LOOP_ASSERT(LINE, NUMCPS == Obj::numCharactersRaw(UTF8, NUMBYTES)); LOOP_ASSERT(LINE, NUMCPS + 1 == Obj::numCharactersRaw(UTF8, NUMBYTES + 1)); LOOP_ASSERT(LINE, NUMCPS == Obj::numCharacters(UTF8)); LOOP_ASSERT(LINE, NUMCPS == Obj::numCharacters(UTF8, NUMBYTES)); LOOP_ASSERT(LINE, NUMCPS + 1 == Obj::numCharacters(UTF8, NUMBYTES + 1)); } } break; case 4: { // -------------------------------------------------------------------- // TESTING SURROGATES // // Concerns: //: 1 Create some strings containing surrogate pairs and verify that //: the validation routines interpret them properly. // // Plan: //: 1 Create a large number of strings containing valid and invalid //: surrogates and verify that the validation routines handle them //: properly. // // Testing: // bool isValid(const char *s); // bool isValid(const char *s, int len); // bool isValid(const char **err, const char *s); // bool isValid(const char **err, const char *s, int len); // -------------------------------------------------------------------- if (verbose) cout << "TESTING SURROGATES" << endl << "==================" << endl; using namespace BDEDE_UTF8UTIL_CASE_4; bsl::string str; str.reserve(6 * 4 + 6 + 1); randAccum = 0; // test strings with surrogate pairs for (int i = 5000; i > 0; -- i) { int rv = randVal(); int numLeading = rv & 3; int numTrailing = (rv >> 2) & 3; str = ""; for (int j = 0; j < numLeading; ++ j) { str += codeRandBenign(); } str += codeRandSurrogatePair(); for (int j = 0; j < numTrailing; ++ j) { str += codeRandBenign(); } ASSERT(false == allValid(str)); } randAccum = 0; // test strings with lone surrogates for (int i = 5000; i > 0; -- i) { int rv = randVal(); int numLeading = rv & 3; int numTrailing = (rv >> 2) & 3; str = ""; for (int j = 0; j < numLeading; ++ j) { str += codeRandBenign(); } str += codeRandSurrogate(); for (int j = 0; j < numTrailing; ++ j) { str += codeRandBenign(); } ASSERT(false == allValid(str)); } } break; case 3: { // -------------------------------------------------------------------- // TESTING BYTE-ORDER MARK // // Concerns: //: 1 Verify byte-order mark is accepted by all the validation //: routines. // // Plan: //: 1 Create a byte-order mark and feed it to the validation routines, //: it should always be acceptable. Also create UTF-16 BOM's of both //: byte orders, they should be rejected. // // Testing: // bool isValid(const char *s); // bool isValid(const char *s, int len); // bool isValid(const char **err, const char *s); // bool isValid(const char **err, const char *s, int len); // -------------------------------------------------------------------- if (verbose) cout << "TESTING BYTE-ORDER MARK" << endl << "=======================" << endl; using namespace BDEDE_UTF8UTIL_CASE_2; typedef const char Char; Char c = char(0x80); // 'c'ontinuation Char b3 = char(0xe0); // 'b'eginning of 3-byte Char b4 = char(0xf0); // 'b'eginning of 4-byte Char encode4a[] = { b4, char(c | 0x10), c, c }; // 0x10000 bsl::string s4a = STR(4a); bsl::string s1b = code8(47); ASSERT(1 == s1b.length()); ASSERT(allValid(s4a)); unsigned char uBom[] = { 0xef, 0xbb, 0xbf }; Char bom[] = { b3 | 0xf, c | 0x3b, c | 0x3f }; const int bomVal = (0xf << 12) + (0x3b << 6) + 0x3f; ASSERT(0 == bsl::memcmp(uBom, bom, 3)); bsl::string sBom = makeString(bom, sizeof(bom)); ASSERT(codeBOM() == sBom); ASSERT(code24(bomVal) == sBom); const char *pc = bom; ASSERT(bomVal == decode(&pc)); ASSERT(bom + sizeof(bom) == pc); ASSERT(allValid(sBom)); bsl::string lStr = sBom + s4a + s4a; ASSERT(allValid(lStr)); lStr = s4a + s4a + sBom + s4a + s4a; ASSERT(allValid(lStr)); lStr = s4a + s4a + sBom; ASSERT(allValid(lStr)); lStr = s4a + s4a + sBom + s1b; ASSERT(allValid(lStr)); Char encode16BomLe[] = { char(0xff), char(0xfe) }; Char encode16BomBe[] = { char(0xfe), char(0xff) }; bsl::string bomLe = STR(16BomLe); bsl::string bomBe = STR(16BomBe); ASSERT(! allValid(bomLe)); ASSERT(! allValid(bomBe)); lStr = s4a + bomLe; ASSERT(! allValid(lStr)); lStr = s4a + bomBe; ASSERT(! allValid(lStr)); lStr = s4a + bomLe + s4a; ASSERT(! allValid(lStr)); lStr = s4a + bomBe + s4a; ASSERT(! allValid(lStr)); lStr = s4a + bomLe + s1b; ASSERT(! allValid(lStr)); lStr = s4a + bomBe + s1b; ASSERT(! allValid(lStr)); } break; case 2: { // -------------------------------------------------------------------- // TABLE-DRIVEN ENCODING / DECODING / VALIDATION TEST // // Concerns: //: 1 Test encoding, decoding, and validation on data that is table //: driven rather than randomly generated. // // Plan: //: 1 Encode some const char strings with specific values, try encoding //: them and verify the expected results are yields. Run the //: validation routines on them and verify the expected results. //: Code various forms of invalid strings and observe that the //: validators reject them appropriately. Several types of encodings //: are represented. UTF-8 zero, Modified UTF-8 zero, many values //: that are valid in both UTF-8 and modified UTF-8, overlong values //: other than zero, blatantly invalid values, and short values. // // Testing: // TABLE-DRIVEN ENCODING / DECODING / VALIDATION TEST // -------------------------------------------------------------------- if (verbose) cout << "\nTABLE-DRIVEN ENCODING / DECODING / VALIDATION TEST\n" "==================================================\n"; using namespace BDEDE_UTF8UTIL_CASE_2; typedef const char Char; Char c = char(0x80); // 'c'ontinuation Char b2 = char(0xc0); // 'b'eginning of 2-byte Char b3 = char(0xe0); // 'b'eginning of 3-byte Char b4 = char(0xf0); // 'b'eginning of 4-byte Char b5 = char(0xf8); // 'b'eginning of 5-byte Char b6 = char(0xfc); // 'b'eginning of 6-byte Char b7 = char(0xfe); // 'b'eginning of 6-byte Char encode1a[] = { 0 }; int val1a = 0; Char encode1b[] = { 0x35 }; int val1b = 0x35; Char encode1c[] = { 0x47 }; int val1c = 0x47; Char encode1d[] = { 0x63 }; int val1d = 0x63; Char encode1e[] = { 0x7f }; int val1e = 0x7f; Char encode2a[] = { b2 | 2, c }; int val2a = 0x80; Char encode2b[] = { b2 | 3, c | 3 }; int val2b = 3*64 + 3; Char encode2c[] = { b2 | 0xf, c | 0xf }; int val2c = 15*64 + 15; Char encode2d[] = { b2 | 0x10, c | 7 }; int val2d = 16*64 + 7; Char encode2e[] = { b2 | 0x1f, c | 0x3f }; int val2e = 0x7ff; Char encode3a[] = { b3, c | 0x20, c | 0 }; int val3a = 0x800; Char encode3b[] = { b3, c | 58, c | 0 }; int val3b = 58 * 64; Char encode3c[] = { b3, c | 0x3f, c | 0x3f }; int val3c = 0xfff; Char encode3d[] = { b3 | 7, c | 0x3f, c | 0x3f }; int val3d = 0x7fff; Char encode3e[] = { b3 | 0xf, c | 0x3f, c | 0x3f }; int val3e = 0xffff; Char encode4a[] = { b4, c | 0x10, c, c }; int val4a = 0x10000; Char encode4b[] = { b4, c | 0x10, c, c | 0xf }; int val4b = 0x1000f; Char encode4c[] = { b4, c | 0x10, c | 0xf, c }; int val4c = 0x103c0; Char encode4d[] = { b4, c | 0x10, c | 0x30, c };int val4d = 0x10c00; Char encode4e[] = { b4, c | 0x13, c, c }; int val4e = 0x13000; Char encode4f[] = { b4, c | 0x1c, c, c }; int val4f = 0x1c000; Char encode4g[] = { b4 | 1, c, c, c }; int val4g = 0x40000; Char encode4h[] = { b4 | 3, c, c, c }; int val4h = 0xc0000; Char encode4i[] = { b4 | 4, c, c, c }; int val4i = 0x100000; Char encode4j[] = { b4 | 4, c | 0xf, c | 0x3f, c | 0x3f }; int val4j = 0x10ffff; #define TEST(testId) do { \ bsl::string str; \ str.insert(0, encode ## testId, sizeof(encode ## testId)); \ Char *pc = str.data(); \ const unsigned int val = decode(&pc); \ ASSERT(pc == str.data() + str.length() + 0 * val ## testId); \ ASSERT(int(val) == val ## testId); \ ASSERT(str == utf8Encode(val ## testId)); \ ASSERT(allValid(str)); \ } while(false); TEST(1a); TEST(1b); TEST(1c); TEST(1d); TEST(1e); TEST(2a); TEST(2b); TEST(2c); TEST(2d); TEST(2e); TEST(3a); TEST(3b); TEST(3c); TEST(3d); TEST(3e); TEST(4a); TEST(4b); TEST(4c); TEST(4d); TEST(4e); TEST(4f); TEST(4g); TEST(4h); TEST(4i); TEST(4j); #undef TEST #define TEST(testId) do { \ bsl::string str; \ str.insert(0, encode ## testId, sizeof(encode ## testId)); \ Char *pc = str.data(); \ const unsigned int val = decode(&pc); \ ASSERT(pc == str.data() + str.length() + 0 * val ## testId); \ ASSERT(int(val) == val ## testId); \ ASSERT(str == utf8Encode(val ## testId)); \ ASSERT(allValid(str)); \ ASSERT(1 == allNumCodePoints(str)); \ ASSERT(bsl::strlen(str.c_str()) == str.length()); \ } while(false); TEST(1b); TEST(1c); TEST(1d); TEST(1e); TEST(2a); TEST(2b); TEST(2c); TEST(2d); TEST(2e); TEST(3a); TEST(3b); TEST(3c); TEST(3d); TEST(3e); TEST(4a); TEST(4b); TEST(4c); TEST(4d); TEST(4e); TEST(4f); TEST(4g); TEST(4h); TEST(4i); TEST(4j); #undef TEST bsl::string s1 = STR(1a)+STR(2a)+STR(3a)+STR(4a)+STR(4f); Char *ps = s1.data(); ASSERT(val1a == int(decode(&ps))); ASSERT(val2a == int(decode(&ps))); ASSERT(val3a == int(decode(&ps))); ASSERT(val4a == int(decode(&ps))); ASSERT(val4f == int(decode(&ps))); ASSERT(ps == s1.data() + s1.length()); ASSERT(allValid(s1)); s1 = STR(2a)+STR(3a)+STR(4a)+STR(4f); ps = s1.data(); ASSERT(val2a == int(decode(&ps))); ASSERT(val3a == int(decode(&ps))); ASSERT(val4a == int(decode(&ps))); ASSERT(val4f == int(decode(&ps))); ASSERT(ps == s1.data() + s1.length()); ASSERT(allValid(s1)); ASSERT(bsl::strlen(s1.c_str()) == s1.length()); s1 = STR(1b)+STR(2b)+STR(3b)+STR(4b)+STR(4g); ps = s1.data(); ASSERT(val1b == int(decode(&ps))); ASSERT(val2b == int(decode(&ps))); ASSERT(val3b == int(decode(&ps))); ASSERT(val4b == int(decode(&ps))); ASSERT(val4g == int(decode(&ps))); ASSERT(ps == s1.data() + s1.length()); ASSERT(allValid(s1)); ASSERT(bsl::strlen(s1.c_str()) == s1.length()); s1 = STR(1c)+STR(2c)+STR(3c)+STR(4c)+STR(4h); ps = s1.data(); ASSERT(val1c == int(decode(&ps))); ASSERT(val2c == int(decode(&ps))); ASSERT(val3c == int(decode(&ps))); ASSERT(val4c == int(decode(&ps))); ASSERT(val4h == int(decode(&ps))); ASSERT(ps == s1.data() + s1.length()); ASSERT(allValid(s1)); ASSERT(bsl::strlen(s1.c_str()) == s1.length()); s1 = STR(1d)+STR(2d)+STR(3d)+STR(4d)+STR(4i); ps = s1.data(); ASSERT(val1d == int(decode(&ps))); ASSERT(val2d == int(decode(&ps))); ASSERT(val3d == int(decode(&ps))); ASSERT(val4d == int(decode(&ps))); ASSERT(val4i == int(decode(&ps))); ASSERT(ps == s1.data() + s1.length()); ASSERT(allValid(s1)); ASSERT(bsl::strlen(s1.c_str()) == s1.length()); s1 = STR(1e)+STR(2e)+STR(3e)+STR(4e)+STR(4j); ps = s1.data(); ASSERT(val1e == int(decode(&ps))); ASSERT(val2e == int(decode(&ps))); ASSERT(val3e == int(decode(&ps))); ASSERT(val4e == int(decode(&ps))); ASSERT(val4j == int(decode(&ps))); ASSERT(ps == s1.data() + s1.length()); ASSERT(allValid(s1)); ASSERT(bsl::strlen(s1.c_str()) == s1.length()); // random overlong values Char encode2o1[] = { b2 | 1, c | 0x3f }; int val2o1 = 0x7f; Char encode2o2[] = { b2 | 0, c | 3 }; int val2o2 = 0x3; Char encode3o1[] = { b3, c | 0x1f, c | 0x3f }; int val3o1 = 0x7ff; Char encode3o2[] = { b3, c | 0, c | 3 }; int val3o2 = 0x3; Char encode4o1[] = { b4, c | 0xf, c | 0x3f, c | 0x3f }; int val4o1 = 0xffff; Char encode4o2[] = { b4, c , c, c | 3 }; int val4o2 = 0x3; #define TEST(testId) do { \ bsl::string str = STR(testId); \ Char *pc = str.data(); \ ASSERT(val ## testId == int(decode(&pc))); \ ASSERT(pc == str.data() + str.length()); \ ASSERT(false == allValid(str)); \ } while(false) TEST(2o1); TEST(2o2); TEST(3o1); TEST(3o2); TEST(4o1); TEST(4o2); #undef TEST // blatantly invalid strings Char encode1i1[] = { c }; Char encode1i2[] = { c | 0x3f }; Char encode2i1[] = { b2 | 2, 0 }; Char encode2i2[] = { b2 | 2, b2 }; Char encode2i3[] = { b2 | 2, b3 }; Char encode2i4[] = { b2 | 2, b4 }; Char encode2i5[] = { b2 | 2, b5 }; Char encode2i6[] = { b2 | 2, b6 }; Char encode2i7[] = { b2 | 2, b7 }; Char encode2i8[] = { b2 | 2, char(0xff) }; Char encode3i1[] = { b3, c | 0x20, 0 }; Char encode3i2[] = { b3, c | 0x20, b2 }; Char encode3i3[] = { b3, c | 0x20, b3 }; Char encode3i4[] = { b3, c | 0x20, b4 }; Char encode3i5[] = { b3, c | 0x20, b5 }; Char encode3i6[] = { b3, c | 0x20, b6 }; Char encode3i7[] = { b3, c | 0x20, b7 }; Char encode3i8[] = { b3, c | 0x20, char(0xff) }; Char encode3i9[] = { b3, 0x3f, c }; Char encode3ia[] = { b3, b2, c }; Char encode3ib[] = { b3, b3, c }; Char encode3ic[] = { b3, b4, c }; Char encode3id[] = { b3, b5, c }; Char encode3ie[] = { b3, b6, c }; Char encode3if[] = { b3, b7, c }; Char encode3ig[] = { b3, char(0xff), c }; Char encode4i1[] = { b4, c | 0x10, c, 0 }; Char encode4i2[] = { b4, c | 0x10, c, b2 }; Char encode4i3[] = { b4, c | 0x10, c, b3 }; Char encode4i4[] = { b4, c | 0x10, c, b4 }; Char encode4i5[] = { b4, c | 0x10, c, b5 }; Char encode4i6[] = { b4, c | 0x10, c, b6 }; Char encode4i7[] = { b4, c | 0x10, c, b7 }; Char encode4i8[] = { b4, c | 0x10, c, char(0xff) }; Char encode4i9[] = { b4, c | 0x10, 0, c }; Char encode4ia[] = { b4, c | 0x10, b2, c }; Char encode4ib[] = { b4, c | 0x10, b3, c }; Char encode4ic[] = { b4, c | 0x10, b4, c }; Char encode4id[] = { b4, c | 0x10, b5, c }; Char encode4ie[] = { b4, c | 0x10, b6, c }; Char encode4if[] = { b4, c | 0x10, b7, c }; Char encode4ig[] = { b4, c | 0x10, char(0xff), c }; Char encode4ih[] = { b4, 0, c, c }; Char encode4ii[] = { b4, b2, c, c }; Char encode4ij[] = { b4, b3, c, c }; Char encode4ik[] = { b4, b4, c, c }; Char encode4il[] = { b4, b5, c, c }; Char encode4im[] = { b4, b6, c, c }; Char encode4in[] = { b4, b7, c, c }; Char encode4io[] = { b4, char(0xff), c, c }; Char encode5i1[] = { b5, c, c, c, c }; Char encode6i1[] = { b6, c, c, c, c, c }; Char encode7i1[] = { b7, c, c, c, c, c, c }; Char encode8i1[] = { char(0xff), c, c, c, c, c, c, c }; #define TEST(testId) do { \ bsl::string str = STR(testId); \ ASSERT(! allValid(str)); \ } while(false) TEST(1i1); TEST(1i2); TEST(2i1); TEST(2i2); TEST(2i3); TEST(2i4); TEST(2i5); TEST(2i6); TEST(2i7); TEST(2i8); TEST(3i1); TEST(3i2); TEST(3i3); TEST(3i4); TEST(3i5); TEST(3i6); TEST(3i7); TEST(3i8); TEST(3i9); TEST(3ia); TEST(3ib); TEST(3ic); TEST(3id); TEST(3ie); TEST(3if); TEST(3ig); TEST(4i1); TEST(4i2); TEST(4i3); TEST(4i4); TEST(4i5); TEST(4i6); TEST(4i7); TEST(4i8); TEST(4i9); TEST(4ia); TEST(4ib); TEST(4ic); TEST(4id); TEST(4ie); TEST(4if); TEST(4ig); TEST(4ih); TEST(4ii); TEST(4ij); TEST(4ik); TEST(4il); TEST(4im); TEST(4in); TEST(4io); TEST(5i1); TEST(6i1); TEST(7i1); TEST(8i1); #undef TEST // short strings, strings that are valid until the end too abruptly Char encode2s1[] = { b2 }; Char encode3s1[] = { b3, c | 0x20 }; Char encode3s2[] = { b3 }; Char encode4s1[] = { b4, c | 0x10, c }; Char encode4s2[] = { b4, c | 0x10 }; Char encode4s3[] = { b4 }; #define TEST(testId) do { \ bsl::string str = STR(testId); \ ASSERT(! allValid(str)); \ \ str = STR(4a) + STR(testId) + STR(4a); \ ASSERT(! allValid(str)); \ \ str = STR(4a) + STR(testId); \ ASSERT(! allValid(str)); \ \ str = STR(3a) + STR(testId) + STR(3a); \ ASSERT(! allValid(str)); \ \ str = STR(3a) + STR(testId); \ ASSERT(! allValid(str)); \ \ str = STR(2a) + STR(testId) + STR(2a); \ ASSERT(! allValid(str)); \ \ str = STR(2a) + STR(testId); \ ASSERT(! allValid(str)); \ \ str = STR(1b) + STR(testId) + STR(1b); \ ASSERT(! allValid(str)); \ \ str = STR(1b) + STR(testId); \ ASSERT(! allValid(str)); \ } while(false) TEST(2s1); TEST(3s1); TEST(3s2); TEST(4s1); TEST(4s2); TEST(4s3); #undef TEST // surrogate values Char encode3u1[] = { b3 | 0xd, c | 0x20, c }; // 0xd800 Char encode3u2[] = { b3 | 0xd, c | 0x20, c | 0x37 }; // 0xd837 Char encode3u3[] = { b3 | 0xd, c | 0x30, c }; // 0xdc00 Char encode3u4[] = { b3 | 0xd, c | 0x33, c | 0x3f }; // 0xdcff #define TEST(testId) do { \ bsl::string str = STR(testId); \ ASSERT(false == allValid(str)); \ \ str = STR(1b) + STR(testId) + STR(1b); \ \ ASSERT(! allValid(str)); \ \ str = STR(2b) + STR(testId) + STR(2b); \ \ ASSERT(! allValid(str)); \ \ str = STR(3b) + STR(testId) + STR(3b); \ \ ASSERT(! allValid(str)); \ \ str = STR(4b) + STR(testId) + STR(4b); \ \ ASSERT(! allValid(str)); \ } while (false) TEST(3u1); TEST(3u2); TEST(3u3); TEST(3u4); #undef TEST } break; case 1: { // -------------------------------------------------------------------- // BREATHING TEST // // Concerns: //: 1 Test basic methods // // Plan: //: 1 Test the various test functions and verify that they work as //: designed. // // Testing: // BREATHING TEST // -------------------------------------------------------------------- if (verbose) cout << "\n" "BREATHING TEST" "\n" "==============" "\n"; randAccum = 0; bsl::string str; str.reserve(41); for (int i = 0; i < 40; i += 4) { bsl::string newcp = code32(randVal32()); ASSERT(4 == Obj::getByteSize(newcp.c_str())); ASSERT(4 == Obj::numBytesIfValid(newcp, 1)); str += newcp; } ASSERT(40 == str.length()); ASSERT(10 == allNumCodePoints(str)); ASSERT(40 == Obj::numBytesIfValid(str, 10)); ASSERT( 4 == Obj::getByteSize(str.c_str())); bsl::string s2 = " "; ASSERT( 0 == Obj::appendUtf8Character(&s2, decode(U8_10000))); ASSERT( 5 == s2.length()); ASSERT(allValid(str)); for (int i = 0; i <= 40; i += 4) { if (veryVeryVeryVerbose) Q(.); ASSERT(Obj::isValid(str.data(), i)); bsl::string c = clone(str.data(), i); ASSERT(Obj::isValid(c.c_str())); ASSERT(i / 4 == Obj::numCharacters(str.data(), i)); ASSERT(i / 4 == Obj::numCharacters(c.c_str())); ASSERT(i / 4 == Obj::numCodePointsRaw(str.data(), i)); ASSERT(i / 4 == Obj::numCodePointsRaw(c.c_str())); if (40 == i) break; for (int j = i + 1; j < i + 4; ++ j) { if (veryVeryVeryVerbose) Q(.); ASSERT(false == Obj::isValid(str.data(), j)); ASSERT(false == Obj::isValid(clone(str.data(), j).c_str())); } } { bsl::string overStr = str + code32(0xffff); ASSERT(44 == overStr.length()); ASSERT(11 == allNumCodePoints(overStr)); ASSERT(44 == Obj::numBytesIfValid(overStr, 11)); ASSERT(! allValid(overStr)); for (int i = 0; i <= 40; i += 4) { if (veryVeryVeryVerbose) Q(.); ASSERT(Obj::isValid(str.data(), i)); bsl::string c = clone(str.data(), i); ASSERT(Obj::isValid(c.c_str())); ASSERT(i / 4 == Obj::numCharacters(str.data(), i)); ASSERT(i / 4 == Obj::numCharacters(c.c_str())); ASSERT(i / 4 == Obj::numCodePointsRaw(str.data(), i)); ASSERT(i / 4 == Obj::numCodePointsRaw(c.c_str())); if (40 == i) break; for (int j = i + 1; j < i + 4; ++ j) { if (veryVeryVeryVerbose) Q(.); ASSERT(false == Obj::isValid(str.data(), j)); ASSERT(false == Obj::isValid(clone(str.data(),j).c_str())); } } } str = ""; str.reserve(34); for (int i = 0; i < 30; i += 3) { if (veryVeryVeryVerbose) Q(.); bsl::string newcp = code24(randVal24(true)); ASSERT(3 == Obj::getByteSize(newcp.c_str())); ASSERT(3 == Obj::numBytesIfValid(newcp, 1)); str += newcp; } ASSERT(30 == str.length()); ASSERT(10 == allNumCodePoints(str)); ASSERT(30 == Obj::numBytesIfValid(str, 10)); ASSERT( 3 == Obj::getByteSize(str.c_str())); ASSERT(allValid(str)); for (int i = 0; i <= 30; i += 3) { if (veryVeryVeryVerbose) Q(.); ASSERT(Obj::isValid(str.data(), i)); bsl::string c = clone(str.data(), i); ASSERT(Obj::isValid(c.c_str())); ASSERT(i / 3 == Obj::numCharacters(str.data(), i)); ASSERT(i / 3 == Obj::numCharacters(c.c_str())); ASSERT(i / 3 == Obj::numCodePointsRaw(str.data(), i)); ASSERT(i / 3 == Obj::numCodePointsRaw(c.c_str())); if (30 == i) break; for (int j = i + 1; j < i + 3; ++ j) { if (veryVeryVeryVerbose) Q(.); ASSERT(false == Obj::isValid(str.data(), j)); ASSERT(false == Obj::isValid(clone(str.data(), j).c_str())); } } { bsl::string surStr = str + code24(0xdddd); // surrogate value ASSERT(33 == surStr.length()); ASSERT(11 == allNumCodePoints(surStr)); ASSERT(! Obj::isValid(surStr.data(), surStr.length())); ASSERT(! Obj::isValid(surStr.c_str())); for (int i = 0; i <= 33; i += 3) { if (veryVeryVeryVerbose) Q(.); bool tst = i < 33; ASSERT(tst == Obj::isValid(surStr.data(), i)); bsl::string c = clone(surStr.data(), i); ASSERT(tst == Obj::isValid(c.c_str())); ASSERT(i / 3 == Obj::numCharacters(surStr.data(), i)); ASSERT(i / 3 == Obj::numCharacters(c.c_str())); ASSERT(i / 3 == Obj::numCodePointsRaw(surStr.data(), i)); ASSERT(i / 3 == Obj::numCodePointsRaw(c.c_str())); if (!tst) break; for (int j = i + 1; j < i + 3; ++ j) { if (veryVeryVeryVerbose) Q(.); ASSERT(! Obj::isValid(surStr.data(), j)); ASSERT(! Obj::isValid(clone(surStr.data(), j).c_str())); } } } { bsl::string overStr = str + code24(0x7ff); // overlong value ASSERT(33 == overStr.length()); ASSERT(11 == allNumCodePoints(overStr)); ASSERT(! allValid(overStr)); for (int i = 0; i <= 33; i += 3) { if (veryVeryVeryVerbose) Q(.); bool tst = i < 33; bsl::string c = clone(overStr.data(), i); ASSERT(tst == allValid(c)); ASSERT(i / 3 == Obj::numCharacters(overStr.data(), i)); ASSERT(i / 3 == Obj::numCharacters( clone(overStr.data(), i).c_str())); ASSERT(i / 3 == Obj::numCodePointsRaw(overStr.data(), i)); ASSERT(i / 3 == Obj::numCodePointsRaw( clone(overStr.data(), i).c_str())); if (!tst) break; for (int j = i + 1; j < i + 3; ++ j) { if (veryVeryVeryVerbose) Q(.); ASSERT(! Obj::isValid(overStr.data(), j)); ASSERT(! Obj::isValid(clone(overStr.data(), j).c_str())); } } } str = ""; str.reserve(23); for (int i = 0; i < 20; i += 2) { if (veryVeryVeryVerbose) Q(.); int val; do { val = randVal16(); } while (0 == val); bsl::string newcp = code16(val); ASSERT(2 == Obj::getByteSize(newcp.c_str())); ASSERT(2 == Obj::numBytesIfValid(newcp, 1)); str += newcp; } ASSERT(20 == str.length()); ASSERT(10 == allNumCodePoints(str)); ASSERT(20 == Obj::numBytesIfValid(str, 10)); ASSERT( 2 == Obj::getByteSize(str.c_str())); ASSERT(allValid(str)); for (int i = 0; i <= 20; i += 2) { if (veryVeryVeryVerbose) Q(.); ASSERT(Obj::isValid(str.data(), i)); bsl::string c = clone(str.data(), i); ASSERT(Obj::isValid(c.c_str())); ASSERT(i / 2 == Obj::numCharacters(str.data(), i)); ASSERT(i / 2 == Obj::numCharacters(c.c_str())); ASSERT(i / 2 == Obj::numCodePointsRaw(str.data(), i)); ASSERT(i / 2 == Obj::numCodePointsRaw(c.c_str())); if (20 == i) break; for (int j = i + 1; j < i + 2; ++ j) { if (veryVeryVeryVerbose) Q(.); ASSERT(false == Obj::isValid(str.data(), j)); ASSERT(false == Obj::isValid(clone(str.data(), j).c_str())); } } { bsl::string overStr = str + code16(0); // overlong zero value ASSERT(22 == overStr.length()); ASSERT(11 == allNumCodePoints(overStr)); ASSERT(false == allValid(overStr)); for (int i = 0; i <= 22; i += 2) { if (veryVeryVeryVerbose) Q(.); bool tst = i < 22; ASSERT(tst == Obj::isValid(overStr.data(), i)); bsl::string c = clone(overStr.data(), i); ASSERT(tst == Obj::isValid(c.c_str())); ASSERT(i / 2 == Obj::numCharacters(overStr.data(), i)); ASSERT(i / 2 == Obj::numCharacters(c.c_str())); ASSERT(i / 2 == Obj::numCodePointsRaw(overStr.data(), i)); ASSERT(i / 2 == Obj::numCodePointsRaw(c.c_str())); if (!tst) break; for (int j = i + 1; j < i + 2; ++ j) { if (veryVeryVeryVerbose) Q(.); ASSERT(false == Obj::isValid(overStr.data(), j)); ASSERT(false == Obj::isValid( clone(overStr.data(), j).c_str())); } } } { bsl::string overStr = str + code16(0x7f);// overlong non-zero value ASSERT(22 == overStr.length()); ASSERT(11 == allNumCodePoints(overStr)); ASSERT(false == allValid(overStr)); for (int i = 0; i <= 22; i += 2) { if (veryVeryVeryVerbose) Q(.); bool tst = i < 22; ASSERT(tst == Obj::isValid(overStr.data(), i)); bsl::string c = clone(overStr.data(), i); ASSERT(tst == Obj::isValid(c.c_str())); ASSERT(i / 2 == Obj::numCharacters(overStr.data(), i)); ASSERT(i / 2 == Obj::numCharacters(c.c_str())); ASSERT(i / 2 == Obj::numCodePointsRaw(overStr.data(), i)); ASSERT(i / 2 == Obj::numCodePointsRaw(c.c_str())); if (!tst) break; for (int j = i + 1; j < i + 2; ++ j) { if (veryVeryVeryVerbose) Q(.); ASSERT(false == Obj::isValid(overStr.data(), j)); ASSERT(false == Obj::isValid( clone(overStr.data(), j).c_str())); } } } str = ""; str.reserve(14); for (int i = 0; i < 10; ++ i) { bsl::string newcp = code8(randVal8(true)); ASSERT(1 == Obj::getByteSize(newcp.c_str())); ASSERT(1 == Obj::numBytesIfValid(newcp, 1)); str += newcp; } ASSERT(10 == str.length()); ASSERT(10 == allNumCodePoints(str)); ASSERT(10 == Obj::numBytesIfValid(str, 10)); ASSERT(allValid(str)); for (int i = 0; i <= 10; ++ i) { if (veryVeryVeryVerbose) Q(.); ASSERT(Obj::isValid(str.data(), i)); bsl::string c = clone(str.data(), i); ASSERT(Obj::isValid(c.c_str())); ASSERT(i == Obj::numCharacters(str.data(), i)); ASSERT(i == Obj::numCharacters(c.c_str())); ASSERT(i == Obj::numCodePointsRaw(str.data(), i)); ASSERT(i == Obj::numCodePointsRaw(c.c_str())); } { bsl::string zStr = str + code8(0); zStr += code8(randVal8()); zStr += code8(randVal8()); zStr += code8(randVal8()); ASSERT(14 == zStr.length()); ASSERT(14 == Obj::numCharacters(zStr.data(), 14)); ASSERT(10 == Obj::numCharacters(zStr.data())); ASSERT(14 == Obj::numCodePointsRaw(zStr.data(), 14)); ASSERT(10 == Obj::numCodePointsRaw(zStr.data())); ASSERT(allValid(zStr)); for (int i = 0; i <= 14; ++ i) { if (veryVeryVeryVerbose) Q(.); ASSERT(Obj::isValid(zStr.data(), i)); bsl::string c = clone(zStr.data(), i); ASSERT(Obj::isValid(c.c_str())); ASSERT(i == Obj::numCharacters(zStr.data(), i)); ASSERT((i <= 10 ? i : 10) == Obj::numCharacters(c.c_str())); ASSERT(i == Obj::numCodePointsRaw(zStr.data(), i)); ASSERT((i <= 10 ? i : 10) == Obj::numCodePointsRaw(c.c_str())); } } } break; case -1: { // -------------------------------------------------------------------- // RANDOM NUMBER GENERATORS TEST // // Concerns: //: 1 Random number generators work properly. // // Plan: //: 1 Test the various random number generators 2 ways -- print out a //: bunch of values for visual inspection, and run a much larger //: number of values for programmatic verification. // // Testing: // random number generator // -------------------------------------------------------------------- if (verbose) cout << "RANDOM NUMBER GENERATORS TEST\n" "=============================\n"; cout << "randVal8()\n"; for (int i = 0; i < 32; ++i) { for (int j = 0; j < 16; ++j) { cout << (j ? ", " : "") << randVal8(); } cout << endl; } randAccum = 0; cout << "\nrandVal8(true)\n"; for (int i = 0; i < 32; ++i) { for (int j = 0; j < 16; ++j) { cout << (j ? ", " : "") << randVal8(true); } cout << endl; } for (int i = 10 * 1000; i > 0; --i) { int j = randVal8(true); ASSERT((0 != j) & (0 == (~0x7f & j))); } randAccum = 0; cout << "\nrandVal16()\n"; for (int i = 0; i < 60; ++i) { for (int j = 0; j < 10; ++j) { cout << (j ? ", " : "") << "0x" << bsl::hex << randVal16(); } cout << endl; } for (int i = 100 * 1000; i > 0; --i) { int j = randVal16(); ASSERT((j >= 0x80) & (j <= 0x7ff)); } randAccum = 0; cout << "\nrandVal24(false)\n"; for (int i = 0; i < 60; ++i) { for (int j = 0; j < 10; ++j) { cout << (j ? ", " : "") << "0x" << bsl::hex << randVal24(); } cout << endl; } for (int i = 100 * 1000; i > 0; --i) { int j = randVal24(); ASSERT((j >= 0x800) & (j <= 0xffff)); } randAccum = 0; cout << "\nrandVal24(true)\n"; for (int i = 0; i < 60; ++i) { for (int j = 0; j < 10; ++j) { cout << (j ? ", " : "") << "0x" << bsl::hex << randVal24(true); } cout << endl; } for (int i = 100 * 1000; i > 0; --i) { int j = randVal24(true); ASSERT((j >= 0x800) & (j <= 0xffff) & !((j >= 0xd800) & (j <= 0xdfff))); } randAccum = 0; cout << "\nrandVal32()\n"; for (int i = 0; i < 60; ++i) { for (int j = 0; j < 8; ++j) { cout << (j ? ", " : "") << "0x" << bsl::hex << randVal32(); } cout << endl; } int highest = 0; for (int i = 1000 * 1000; i > 0; --i) { int j = randVal32(); ASSERT((j >= 0x10000) & (j <= 0x10ffff)); if (j > highest) highest = j; } cout << "highest randVal32: " << highest << endl; } break; case -2: { // -------------------------------------------------------------------- // VERIFY TEST APPARATUS // // Concerns: //: 1 The test apparatus works properly. // // Plan: //: 1 Test the various test functions and verify that they work as //: expected. // // Testing: // 'utf8Encode', 'decode' // -------------------------------------------------------------------- if (verbose) cout << "\nVERIFY TEST APPARATUS\n" "=====================\n"; cout << "Encode / Decode cycle\n"; randAccum = 0; bsl::string str; { randAccum = 0; cout << "Encode:\n"; str.reserve(7 * 7 * 4 + 1); int valStore[7][7]; for (int row = 0; row < 7; ++ row) { for (int col = 0; col < 7; ++ col) { int val = randValue(true); cout << (col ? ", " : "") << "0x" << bsl::hex << val; str += utf8Encode(val); valStore[row][col] = val; } cout << endl; } ASSERT(str.length() < 7 * 7 * 4 + 1); cout << "Decode:\n"; const char *pc = str.data(); for (int row = 0; row < 7; ++ row) { for (int col = 0; col < 7; ++ col) { int val = decode(&pc); cout << (col ? ", " : "") << "0x" << bsl::hex << val; ASSERT(valStore[row][col] == val); } cout << endl; } ASSERT(pc == str.data() + str.length()); } { randAccum = 0; str = ""; str.reserve(100 * 100 * 4 + 1); int valStore[100][100]; for (int row = 0; row < 100; ++ row) { for (int col = 0; col < 100; ++ col) { int val = randValue(true); str += utf8Encode(val); valStore[row][col] = val; } } ASSERT(str.length() < 100 * 100 * 4 + 1); const char *pc = str.data(); for (int row = 0; row < 100; ++ row) { for (int col = 0; col < 100; ++ col) { int val = decode(&pc); ASSERT(valStore[row][col] == val); } } ASSERT(pc == str.data() + str.length()); ASSERT(bsl::strlen(str.c_str()) < str.length()); } { randAccum = 0; str = ""; str.reserve(100 * 100 * 4 + 1); int valStore[100][100]; for (int row = 0; row < 100; ++ row) { for (int col = 0; col < 100; ++ col) { int val = randValue(true, true); str += utf8Encode(val); valStore[row][col] = val; } } ASSERT(str.length() < 100 * 100 * 4 + 1); const char *pc = str.data(); for (int row = 0; row < 100; ++ row) { for (int col = 0; col < 100; ++ col) { int val = decode(&pc); ASSERT(valStore[row][col] == val); } } ASSERT(pc == str.data() + str.length()); ASSERT(bsl::strlen(str.c_str()) == str.length()); } } break; default: { cerr << "WARNING: CASE `" << test << "' NOT FOUND." << endl; testStatus = -1; } } if (testStatus > 0) { cerr << "Error, non-zero test status = " << testStatus << "." << endl; } return testStatus; } // ---------------------------------------------------------------------------- // Copyright 2015 Bloomberg Finance L.P. // // 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. // ----------------------------- END-OF-FILE ----------------------------------
51.408412
79
0.42983
[ "vector", "3d" ]
ad22d61fc6f3681aab89cf2ccd28e4ac07104b8c
1,708
hpp
C++
src/opengl/render/BoxMesh.hpp
log0div0/just_for_fun
737fc18c61e2c6a698de34cb7ea80f9eeee32362
[ "MIT" ]
null
null
null
src/opengl/render/BoxMesh.hpp
log0div0/just_for_fun
737fc18c61e2c6a698de34cb7ea80f9eeee32362
[ "MIT" ]
null
null
null
src/opengl/render/BoxMesh.hpp
log0div0/just_for_fun
737fc18c61e2c6a698de34cb7ea80f9eeee32362
[ "MIT" ]
null
null
null
#pragma once #include "../../Vertex.hpp" #include <glad/glad.h> #include <mogl/mogl.hpp> #include "ShaderProgram.hpp" namespace render { struct BoxMesh { static const inline GLuint binding_index = 1; // any vacant value BoxMesh() { vertex_buffer.setData(box_vertices.size() * sizeof(Vertex), box_vertices.data(), GL_STATIC_DRAW); vertex_array.setVertexBuffer(binding_index, vertex_buffer.getHandle(), 0, sizeof(Vertex)); BindPos(0); BindUV(1); BindNormal(2); // index_buffer.setData(box_indices.size() * sizeof(uint32_t), box_indices.data(), GL_STATIC_DRAW); // vertex_array.setElementBuffer(index_buffer.getHandle()); } void BindPos(GLuint location) { vertex_array.setAttribBinding(location, binding_index); vertex_array.setAttribFormat(location, 3, GL_FLOAT, GL_FALSE, offsetof(Vertex, pos)); vertex_array.enableAttrib(location); } void BindUV(GLuint location) { vertex_array.setAttribBinding(location, binding_index); vertex_array.setAttribFormat(location, 2, GL_FLOAT, GL_FALSE, offsetof(Vertex, uv)); vertex_array.enableAttrib(location); } void BindNormal(GLuint location) { vertex_array.setAttribBinding(location, binding_index); vertex_array.setAttribFormat(location, 3, GL_FLOAT, GL_FALSE, offsetof(Vertex, normal)); vertex_array.enableAttrib(location); } void Draw(ShaderProgram& shader) { shader.shader_program.use(); vertex_array.bind(); // glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); // glDrawElements(GL_TRIANGLES, box_indices.size(), GL_UNSIGNED_INT, 0); glDrawArrays(GL_TRIANGLES, 0, box_vertices.size()); } mogl::ArrayBuffer vertex_buffer; // mogl::ElementArrayBuffer index_buffer; mogl::VertexArray vertex_array; }; }
27.111111
101
0.757026
[ "render" ]
ad268312d19ab13312c75535fd76a60a40c39589
2,626
cpp
C++
src/PrimitiveCube.cpp
valvy/BlockSnake
c4f0f99617d4976a37ca4e93cefe7ccdbca05a1c
[ "BSD-2-Clause" ]
2
2021-06-28T12:00:57.000Z
2021-06-28T23:46:31.000Z
src/PrimitiveCube.cpp
valvy/BlockSnake
c4f0f99617d4976a37ca4e93cefe7ccdbca05a1c
[ "BSD-2-Clause" ]
null
null
null
src/PrimitiveCube.cpp
valvy/BlockSnake
c4f0f99617d4976a37ca4e93cefe7ccdbca05a1c
[ "BSD-2-Clause" ]
null
null
null
#include "PrimitiveCube.hpp" PrimitiveCube::PrimitiveCube(int uniqueNumber) : PrimitiveForm(uniqueNumber, "cube"){ std::vector<GLfloat> vertexVBO{ -1.0f,-1.0f,-1.0f, -1.0f,-1.0f, 1.0f, -1.0f, 1.0f, 1.0f, 1.0f, 1.0f,-1.0f, -1.0f,-1.0f,-1.0f, -1.0f, 1.0f,-1.0f, 1.0f,-1.0f, 1.0f, -1.0f,-1.0f,-1.0f, 1.0f,-1.0f,-1.0f, 1.0f, 1.0f,-1.0f, 1.0f,-1.0f,-1.0f, -1.0f,-1.0f,-1.0f, -1.0f,-1.0f,-1.0f, -1.0f, 1.0f, 1.0f, -1.0f, 1.0f,-1.0f, 1.0f,-1.0f, 1.0f, -1.0f,-1.0f, 1.0f, -1.0f,-1.0f,-1.0f, -1.0f, 1.0f, 1.0f, -1.0f,-1.0f, 1.0f, 1.0f,-1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f,-1.0f,-1.0f, 1.0f, 1.0f,-1.0f, 1.0f,-1.0f,-1.0f, 1.0f, 1.0f, 1.0f, 1.0f,-1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f,-1.0f, -1.0f, 1.0f,-1.0f, 1.0f, 1.0f, 1.0f, -1.0f, 1.0f,-1.0f, -1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, -1.0f, 1.0f, 1.0f, 1.0f,-1.0f, 1.0f }; std::vector<GLfloat> uvVBO{ 0.000059f, 1.0f-0.000004f, 0.000103f, 1.0f-0.336048f, 0.335973f, 1.0f-0.335903f, 1.000023f, 1.0f-0.000013f, 0.667979f, 1.0f-0.335851f, 0.999958f, 1.0f-0.336064f, 0.667979f, 1.0f-0.335851f, 0.336024f, 1.0f-0.671877f, 0.667969f, 1.0f-0.671889f, 1.000023f, 1.0f-0.000013f, 0.668104f, 1.0f-0.000013f, 0.667979f, 1.0f-0.335851f, 0.000059f, 1.0f-0.000004f, 0.335973f, 1.0f-0.335903f, 0.336098f, 1.0f-0.000071f, 0.667979f, 1.0f-0.335851f, 0.335973f, 1.0f-0.335903f, 0.336024f, 1.0f-0.671877f, 1.000004f, 1.0f-0.671847f, 0.999958f, 1.0f-0.336064f, 0.667979f, 1.0f-0.335851f, 0.668104f, 1.0f-0.000013f, 0.335973f, 1.0f-0.335903f, 0.667979f, 1.0f-0.335851f, 0.335973f, 1.0f-0.335903f, 0.668104f, 1.0f-0.000013f, 0.336098f, 1.0f-0.000071f, 0.000103f, 1.0f-0.336048f, 0.000004f, 1.0f-0.671870f, 0.336024f, 1.0f-0.671877f, 0.000103f, 1.0f-0.336048f, 0.336024f, 1.0f-0.671877f, 0.335973f, 1.0f-0.335903f, 0.667969f, 1.0f-0.671889f, 1.000004f, 1.0f-0.671847f, 0.667979f, 1.0f-0.335851f }; this->dataSize = vertexVBO.size(); this->resourceData = this->generateVAO(); this->vboVertex = this->storeDataInVAO(0,3,vertexVBO); this->vboUV = this->storeDataInVAO(1,2,uvVBO); }
29.840909
85
0.487053
[ "vector" ]
ad32a037c160d984a8f544a760b487c31f888663
62,083
cc
C++
lib/k2hshmque.cc
hiwakaba/k2hash
154257ccc3e0aaa5cefdb0361a354ec19b53616d
[ "MIT" ]
38
2016-12-09T01:44:43.000Z
2021-06-24T01:33:17.000Z
lib/k2hshmque.cc
hiwakaba/k2hash
154257ccc3e0aaa5cefdb0361a354ec19b53616d
[ "MIT" ]
6
2016-12-09T05:38:38.000Z
2020-11-16T05:20:30.000Z
lib/k2hshmque.cc
hiwakaba/k2hash
154257ccc3e0aaa5cefdb0361a354ec19b53616d
[ "MIT" ]
18
2016-12-09T01:48:33.000Z
2021-01-20T06:33:00.000Z
/* * K2HASH * * Copyright 2013-2015 Yahoo Japan Corporation. * * K2HASH is key-valuew store base libraries. * K2HASH is made for the purpose of the construction of * original KVS system and the offer of the library. * The characteristic is this KVS library which Key can * layer. And can support multi-processing and multi-thread, * and is provided safely as available KVS. * * For the full copyright and license information, please view * the license file that was distributed with this source code. * * AUTHOR: Takeshi Nakatani * CREATE: Mon Feb 2 2015 * REVISION: * */ #include <string.h> #include "k2hcommon.h" #include "k2hshm.h" #include "k2hutil.h" #include "k2hashfunc.h" #include "k2hdbg.h" using namespace std; //--------------------------------------------------------- // Utility function //--------------------------------------------------------- // This function in k2hash.cc // extern PK2HATTRPCK k2h_cvt_attrs_to_bin(K2HAttrs* pAttrs, int& attrspckcnt); // [NOTE] // About attribute in Queue // // (Key)Queue's marker does NOT set ANY attribute. // KeyQueus's key does NOT set ANY attribute too. // Queus's key can be set attributes EXCEPT history attribute, allowed attributes are set by builtin/plugin attribute object. // Queus's key can set expire attribute overwrite old expire attribute if specifies k2hattrs. // // Marker(key) - not allow any attribute // -> Key for K2HQueue - allow mtime, encrypt, expire(*), plugin's attributes, deny history attribute // -> Key for K2HKeyQueue - not allow any attribute // -> Value for K2HKeyQueue - this means normal key-value's key, so this normal key allows any attribute like normal key. // // *) expire in queue key is not normal expire attribute, but it uses same attribute name. // here, expire inherits value if specified old attributes(which has expire attribute). // if there is no expire attribute in old attribute list, expire is set new value when the builtin attribute object has expire seconds. // if there is no expire and not set expire seconds in builtin object, expire value is not set. // //--------------------------------------------------------- // Class methods //--------------------------------------------------------- PBK2HMARKER K2HShm::InitK2HMarker(size_t& marklen, const unsigned char* bystart, size_t startlen, const unsigned char* byend, size_t endlen) { if(((NULL == bystart) != (0 == startlen)) || ((NULL == byend) != (0 == endlen))){ ERR_K2HPRN("Some parameters are wrong."); return NULL; } if(!byend){ byend = bystart; endlen = startlen; } PBK2HMARKER pmarker; // allocation marklen = sizeof(K2HMARKER) + startlen + endlen; if(NULL == (pmarker = reinterpret_cast<PBK2HMARKER>(malloc(marklen)))){ ERR_K2HPRN("Could not allocation memory."); return NULL; } // set data // [NOTICE] // If startlen and endlen is 0, the offset pointers point over this structure area. // At first, must check length for accessing this structure. // pmarker->marker.startlen = startlen; pmarker->marker.startoff = static_cast<off_t>(sizeof(K2HMARKER)); pmarker->marker.endlen = endlen; pmarker->marker.endoff = static_cast<off_t>(sizeof(K2HMARKER) + startlen); if(0 < startlen){ memcpy((&(pmarker->byData[0]) + pmarker->marker.startoff), bystart, startlen); } if(0 < endlen){ memcpy((&(pmarker->byData[0]) + pmarker->marker.endoff), byend, endlen); } return pmarker; } PBK2HMARKER K2HShm::UpdateK2HMarker(PBK2HMARKER pmarker, size_t& marklen, const unsigned char* byKey, size_t keylength, bool is_end) { if(!pmarker || (NULL == byKey) != (0 == keylength)){ ERR_K2HPRN("Some parameters are wrong."); return NULL; } PBK2HMARKER pnewmarker; if(0 == pmarker->marker.startlen && 0 == pmarker->marker.endlen){ // marker is empty // allocation marklen = sizeof(K2HMARKER) + (keylength * 2); if(NULL == (pnewmarker = reinterpret_cast<PBK2HMARKER>(malloc(marklen)))){ ERR_K2HPRN("Could not allocation memory."); return NULL; } // set data pnewmarker->marker.startlen = keylength; pnewmarker->marker.startoff = static_cast<off_t>(sizeof(K2HMARKER)); pnewmarker->marker.endlen = keylength; pnewmarker->marker.endoff = static_cast<off_t>(sizeof(K2HMARKER) + keylength); memcpy((&(pnewmarker->byData[0]) + pnewmarker->marker.startoff), byKey, pnewmarker->marker.startlen); memcpy((&(pnewmarker->byData[0]) + pnewmarker->marker.endoff), byKey, pnewmarker->marker.endlen); }else{ if((is_end && 0 == pmarker->marker.startlen) || (!is_end && 0 == pmarker->marker.endlen)){ // When setting start(end) key, the pmarker does not have end(start) key. // Then the end(start) key must be set as same as start(end) key. // So it means initializing. // K2H_Free(pmarker); return K2HShm::InitK2HMarker(marklen, byKey, keylength); } // allocation marklen = sizeof(K2HMARKER) + (is_end ? (pmarker->marker.startlen + keylength) : (keylength + pmarker->marker.endlen)); if(NULL == (pnewmarker = reinterpret_cast<PBK2HMARKER>(malloc(marklen)))){ ERR_K2HPRN("Could not allocation memory."); return NULL; } // set data pnewmarker->marker.startlen = is_end ? pmarker->marker.startlen : keylength; pnewmarker->marker.startoff = static_cast<off_t>(sizeof(K2HMARKER)); pnewmarker->marker.endlen = is_end ? keylength : pmarker->marker.endlen; pnewmarker->marker.endoff = static_cast<off_t>(sizeof(K2HMARKER) + pnewmarker->marker.startlen); memcpy((&(pnewmarker->byData[0]) + pnewmarker->marker.startoff), (is_end ? (&(pmarker->byData[0]) + pmarker->marker.startoff) : byKey), pnewmarker->marker.startlen); memcpy((&(pnewmarker->byData[0]) + pnewmarker->marker.endoff), (is_end ? byKey : (&(pmarker->byData[0]) + pmarker->marker.endoff)), pnewmarker->marker.endlen); } // cppcheck-suppress unmatchedSuppression // cppcheck-suppress uselessAssignmentPtrArg K2H_Free(pmarker); return pnewmarker; } bool K2HShm::IsEmptyK2HMarker(PBK2HMARKER pmarker) { if(!pmarker){ MSG_K2HPRN("Some parameter is wrong."); return true; } return (0 == pmarker->marker.startlen); } //--------------------------------------------------------- // Methods for Queue //--------------------------------------------------------- // // Get current marker // PBK2HMARKER K2HShm::GetMarker(const unsigned char* byMark, size_t marklength, K2HLock* pALObjCKI) const { if(!byMark || 0 == marklength){ ERR_K2HPRN("Some parameters are wrong."); return NULL; } if(!IsAttached()){ ERR_K2HPRN("There is no attached K2HASH."); return NULL; } // lock object K2HLock ALObjCKI(K2HLock::RDLOCK); if(!pALObjCKI){ pALObjCKI = &ALObjCKI; } // make hash and lock cindex // cppcheck-suppress unmatchedSuppression // cppcheck-suppress internalAstError k2h_hash_t hash = K2H_HASH_FUNC(reinterpret_cast<const void*>(byMark), marklength); if(NULL == GetCKIndex(hash, *pALObjCKI)){ ERR_K2HPRN("Something error occurred, pCKIndex must not be NULL."); return NULL; // automatically unlock ALObjCKI if it is local } // get element PELEMENT pMarkerElement; if(NULL == (pMarkerElement = GetElement(byMark, marklength, *pALObjCKI))){ MSG_K2HPRN("Could not get element for marker, probably it is not existed."); return NULL; // automatically unlock ALObjCKI if it is local } // get marker's value unsigned char* pmkval = NULL; ssize_t mkvallen= Get(pMarkerElement, &pmkval, PAGEOBJ_VALUE); if(!pmkval || 0 == mkvallen){ MSG_K2HPRN("Marker does not have value, probably queue is empty."); return NULL; // automatically unlock ALObjCKI if it is local } // Check empty marker PBK2HMARKER pmarker = reinterpret_cast<PBK2HMARKER>(pmkval); size_t marklen = static_cast<size_t>(mkvallen); if(K2HShm::IsEmptyK2HMarker(pmarker)){ MSG_K2HPRN("Marker exists, but it is empty."); K2H_Free(pmkval); return NULL; // automatically unlock ALObjCKI if it is local } if(marklen != (sizeof(K2HMARKER) + pmarker->marker.startlen + pmarker->marker.endlen)){ MSG_K2HPRN("Marker exists, but the marker size is wrong."); K2H_Free(pmkval); return NULL; // automatically unlock ALObjCKI if it is local } return pmarker; } // // Update only start marker without key modifying. // // [NOTICE] Be careful for using this method. // bool K2HShm::UpdateStartK2HMarker(const unsigned char* byMark, size_t marklength, const unsigned char* byKey, size_t keylength) { if(!byMark || 0 == marklength || ((NULL == byKey) != (0 == keylength))){ ERR_K2HPRN("Some parameters are wrong."); return false; } if(!IsAttached()){ ERR_K2HPRN("There is no attached K2HASH."); return false; } K2HFILE_UPDATE_CHECK(this); // Lock cindex for writing marker. k2h_hash_t hash = K2H_HASH_FUNC(reinterpret_cast<const void*>(byMark), marklength); K2HLock ALObjCKI(K2HLock::RWLOCK); // LOCK if(NULL == GetCKIndex(hash, ALObjCKI)){ ERR_K2HPRN("Something error occurred, pCKIndex must not be NULL."); return false; } // Read current marker.(without checking expire) unsigned char* pmkval = NULL; ssize_t mkvallength; if(-1 == (mkvallength = Get(byMark, marklength, &pmkval, false))){ // There is no marker return false; } PBK2HMARKER pmarker = reinterpret_cast<PBK2HMARKER>(pmkval); size_t marklen = static_cast<size_t>(mkvallength); // Check current marker size if(marklen != (sizeof(K2HMARKER) + pmarker->marker.startlen + pmarker->marker.endlen)){ ERR_K2HPRN("The marker is not same size which is calculated."); K2H_Free(pmkval); return false; } if(K2HShm::IsEmptyK2HMarker(pmarker)){ // There is no data in queue K2H_Free(pmkval); return true; // [NOTE] returns success } // set new marker if(byKey){ if(0 != k2hbincmp(byKey, keylength, (&(pmarker->byData[0]) + pmarker->marker.startoff), pmarker->marker.startlen)){ // Update marker data pmarker = K2HShm::UpdateK2HMarker(pmarker, marklen, byKey, keylength, false); }else{ // same queue key is already set, so nothing to do. } }else{ // There is no start queue key, it means the queue is empty. pmarker = K2HShm::InitK2HMarker(marklen); } // Set new marker // // marker does not have any attribute. // if(!Set(byMark, marklength, &(pmarker->byData[0]), marklen, NULL, true, NULL, NULL, NULL, K2hAttrOpsMan::OPSMAN_MASK_ALL)){ ERR_K2HPRN("Could not set new marker."); K2H_Free(pmarker); return false; } K2H_Free(pmarker); // Unlock ALObjCKI.Unlock(); return true; } bool K2HShm::IsEmptyQueue(const unsigned char* byMark, size_t marklength) const { if(!byMark || 0 == marklength){ ERR_K2HPRN("Some parameters are wrong."); return true; // wrong marker means as same as empty } if(!IsAttached()){ ERR_K2HPRN("There is no attached K2HASH."); return true; // wrong parameter means as same as empty } // Read current marker. unsigned char* pmkval = NULL; ssize_t mkvallength; if(-1 == (mkvallength = Get(byMark, marklength, &pmkval)) || !pmkval){ return true; // no marker } // Check empty marker PBK2HMARKER pmarker = reinterpret_cast<PBK2HMARKER>(pmkval); size_t marklen = static_cast<size_t>(mkvallength); if(K2HShm::IsEmptyK2HMarker(pmarker)){ K2H_Free(pmkval); return true; // marker is empty } // Check current marker size if(marklen != (sizeof(K2HMARKER) + pmarker->marker.startlen + pmarker->marker.endlen)){ ERR_K2HPRN("The marker is not same size which is calculated."); K2H_Free(pmkval); return true; // marker is wrong size } K2H_Free(pmkval); // there are one or more key in queue. return false; } // // Returns queue count which is included expired keys. // int K2HShm::GetCountQueue(const unsigned char* byMark, size_t marklength) const { if(!byMark || 0 == marklength){ ERR_K2HPRN("Some parameters are wrong."); return 0; } if(!IsAttached()){ ERR_K2HPRN("There is no attached K2HASH."); return 0; } // Read current marker. unsigned char* pmkval = NULL; ssize_t mkvallength; if(-1 == (mkvallength = Get(byMark, marklength, &pmkval)) || !pmkval){ // There is no marker return 0; } // Check empty marker PBK2HMARKER pmarker = reinterpret_cast<PBK2HMARKER>(pmkval); size_t marklen = static_cast<size_t>(mkvallength); if(K2HShm::IsEmptyK2HMarker(pmarker)){ K2H_Free(pmkval); return 0; } // Check current marker size if(marklen != (sizeof(K2HMARKER) + pmarker->marker.startlen + pmarker->marker.endlen)){ ERR_K2HPRN("The marker is not same size which is calculated."); K2H_Free(pmkval); return 0; } // copy start key unsigned char* pKey = k2hbindup(&(pmarker->byData[pmarker->marker.startoff]), pmarker->marker.startlen); size_t keylength = pmarker->marker.startlen; // loop for counting int count; for(count = 1; pKey; ++count){ // check end of queue if(0 == k2hbincmp(pKey, keylength, &(pmarker->byData[pmarker->marker.endoff]), pmarker->marker.endlen)){ break; } // get subkeys K2HSubKeys* psubkeys; if(NULL == (psubkeys = GetSubKeys(pKey, keylength, false))){ // not check expired // There is no key nor subkeys break; } K2HSubKeys::iterator iter = psubkeys->begin(); if(iter == psubkeys->end()){ // Current key does not have any subkey. K2H_Delete(psubkeys); break; } // set next key K2H_Free(pKey); pKey = k2hbindup(iter->pSubKey, iter->length); keylength = iter->length; K2H_Delete(psubkeys); } K2H_Free(pmkval); K2H_Free(pKey); return count; } // // Read key(only) from queue at position which is based top of queue. // // Parameter pos: specify position in queue, position 0 means top of queue. // if this is set -1, it means end of queue. // Returns false: not found key or something error occurred. // true: found key at position // bool K2HShm::ReadQueue(const unsigned char* byMark, size_t marklength, unsigned char** ppKey, size_t& keylength, int pos) const { if(!byMark || 0 == marklength || !ppKey || pos < -1){ ERR_K2HPRN("Some parameters are wrong."); return false; } if(!IsAttached()){ ERR_K2HPRN("There is no attached K2HASH."); return false; } // This method returns true when there is no queue data. // So caller is check following value. // *ppKey = NULL; keylength = 0; // Read current marker.(do not check attribute for no expire) unsigned char* pmkval = NULL; ssize_t mkvallength; if(-1 == (mkvallength = Get(byMark, marklength, &pmkval, false)) || !pmkval){ // There is no marker return false; } // Check empty marker PBK2HMARKER pmarker = reinterpret_cast<PBK2HMARKER>(pmkval); size_t marklen = static_cast<size_t>(mkvallength); if(K2HShm::IsEmptyK2HMarker(pmarker)){ K2H_Free(pmkval); return false; } // Check current marker size if(marklen != (sizeof(K2HMARKER) + pmarker->marker.startlen + pmarker->marker.endlen)){ ERR_K2HPRN("The marker is not same size which is calculated."); K2H_Free(pmkval); return false; } // Get key by position if(-1 == pos){ // End(deepest) of queue if(0 == pmarker->marker.endlen){ K2H_Free(pmkval); return false; } // get key *ppKey = k2hbindup(&(pmarker->byData[pmarker->marker.endoff]), pmarker->marker.endlen); keylength = pmarker->marker.endlen; }else{ // loop count for searching *ppKey = k2hbindup(&(pmarker->byData[pmarker->marker.startoff]), pmarker->marker.startlen); keylength = pmarker->marker.startlen; for(int cnt = 0; *ppKey && cnt < pos; cnt++){ // check end of queue if(0 == k2hbincmp(*ppKey, keylength, &(pmarker->byData[pmarker->marker.endoff]), pmarker->marker.endlen)){ K2H_Free(*ppKey); keylength = 0; break; } // get subkeys.(do not check attribute for no expire) K2HSubKeys* psubkeys; if(NULL == (psubkeys = GetSubKeys(*ppKey, keylength, false))){ // There is no key nor subkeys K2H_Free(*ppKey); keylength = 0; break; } K2HSubKeys::iterator iter = psubkeys->begin(); if(iter == psubkeys->end()){ // Current key does not have any subkey. K2H_Delete(psubkeys); K2H_Free(*ppKey); keylength = 0; break; } // set next key K2H_Free(*ppKey); *ppKey = k2hbindup(iter->pSubKey, iter->length); keylength = iter->length; K2H_Delete(psubkeys); } if(!*ppKey){ // not found or there is no key by position. K2H_Free(pmkval); keylength = 0; return false; } } K2H_Free(pmkval); return true; } // // Read key from queue at position which is based top of queue. // // Parameter pos: specify position in queue, position 0 means top of queue. // if this is set -1, it means end of queue. // Returns false: there is no key at position or key is expired // true: found key at position // bool K2HShm::ReadQueue(const unsigned char* byMark, size_t marklength, unsigned char** ppKey, size_t& keylength, unsigned char** ppValue, size_t& vallength, int pos, const char* encpass) const { // get key if(!ReadQueue(byMark, marklength, ppKey, keylength, pos)){ // not found or there is no key by position. return false; } // Get value.(with checking attribute) ssize_t tmpvallen; if(-1 == (tmpvallen = Get(*ppKey, keylength, ppValue, true, encpass))){ ERR_K2HPRN("Could not get value by key."); K2H_Free(*ppKey); return false; } vallength = static_cast<size_t>(tmpvallen); return true; } // // If making FIFO(LIFO) type queue, sets is_fifo flag as true(false). // So that, adding new key into tail(top) of queue list. // bool K2HShm::AddQueue(const unsigned char* byMark, size_t marklength, const unsigned char* byKey, size_t keylength, const unsigned char* byValue, size_t vallength, bool is_fifo, K2hAttrOpsMan::ATTRINITTYPE attrtype, K2HAttrs* pAttrs, const char* encpass, const time_t* expire) { if(!byMark || 0 == marklength || !byKey || 0 == keylength){ ERR_K2HPRN("Some parameters are wrong."); return false; } if(!IsAttached()){ ERR_K2HPRN("There is no attached K2HASH."); return false; } K2HFILE_UPDATE_CHECK(this); bool result; if(is_fifo){ result = AddFifoQueue(byMark, marklength, byKey, keylength, byValue, vallength, attrtype, pAttrs, encpass, expire); }else{ result = AddLifoQueue(byMark, marklength, byKey, keylength, byValue, vallength, attrtype, pAttrs, encpass, expire); } return result; } // // Add data to FIFO queue // bool K2HShm::AddFifoQueue(const unsigned char* byMark, size_t marklength, const unsigned char* byKey, size_t keylength, const unsigned char* byValue, size_t vallength, K2hAttrOpsMan::ATTRINITTYPE attrtype, K2HAttrs* pAttrs, const char* encpass, const time_t* expire) { //-------------------------------------- // Make new key in K2hash //-------------------------------------- // // attrtype should be allowed OPSMAN_MASK_QUEUEKEY, OPSMAN_MASK_TRANSQUEUEKEY, OPSMAN_MASK_QUEUEMARKER and OPSMAN_MASK_KEYQUEUEKEY for Queue // if(!Set(byKey, keylength, byValue, vallength, NULL, true, pAttrs, encpass, expire, attrtype)){ ERR_K2HPRN("Could not make new key."); return false; } // Read marker PBK2HMARKER before_marker = GetMarker(byMark, marklength); const unsigned char* before_endkey = before_marker ? &(before_marker->byData[before_marker->marker.endoff]) : NULL; size_t before_endlen = before_marker ? before_marker->marker.endlen : 0; PBK2HMARKER after_marker = NULL; const unsigned char* after_endkey = NULL; size_t after_endlen = 0; PBK2HMARKER last_marker = NULL; // for broken marker checking const unsigned char* last_endkey = NULL; size_t last_endlen = 0; bool result = false; // result code and for loop flag do{ //-------------------------------------- // Set new key into end key's subkey //-------------------------------------- if(before_marker && 0 < before_endlen){ // marker has end of queue key // Get endkey's element with WRITE LOCK K2HLock ALObjCKI_Endkey(K2HLock::RWLOCK); // auto release locking at leaving in this scope. PELEMENT pEndKeyElement; if(NULL == (pEndKeyElement = GetElement(before_endkey, before_endlen, ALObjCKI_Endkey))){ // end key is not found. MSG_K2HPRN("Key(%s) is not found, so retry to get marker.", reinterpret_cast<const char*>(before_endkey)); if(0 == k2hbincmp(before_endkey, before_endlen, last_endkey, last_endlen)){ // before end key in marker is as same as now, so marker is not updated with wrong end key. ERR_K2HPRN("Key(%s) is not found, probably marker end key is broken.", reinterpret_cast<const char*>(before_endkey)); break; } // retry(switch before -> last) ALObjCKI_Endkey.Unlock(); // Unlock K2H_Free(last_marker); last_marker = before_marker; last_endkey = k2hbindup(before_endkey, before_endlen); last_endlen = before_endlen; before_marker = GetMarker(byMark, marklength); before_endkey = before_marker ? &(before_marker->byData[before_marker->marker.endoff]) : NULL; before_endlen = before_marker ? before_marker->marker.endlen : 0; continue; }else{ K2H_Free(last_marker); last_endkey = NULL; last_endlen = 0; } // Get end of queue key's subkey and check it is empty. K2HSubKeys* endkey_subkeys; if(NULL != (endkey_subkeys = GetSubKeys(pEndKeyElement, false)) && 0 < endkey_subkeys->size()){ // end of queue key has subkeys, retry to loop at reading marker K2H_Free(before_marker); K2H_Delete(endkey_subkeys); before_marker = GetMarker(byMark, marklength); before_endkey = before_marker ? &(before_marker->byData[before_marker->marker.endoff]) : NULL; before_endlen = before_marker ? before_marker->marker.endlen : 0; continue; } K2H_Delete(endkey_subkeys); // Replace subkeys of end by new key in it. K2HSubKeys endkey_newskeys; unsigned char* byNewSubkeys = NULL; size_t new_skeylen = 0UL; endkey_newskeys.insert(byKey, keylength); if(!endkey_newskeys.Serialize(&byNewSubkeys, new_skeylen)){ ERR_K2HPRN("Failed to serialize subkey for adding queue."); break; } if(!ReplacePage(pEndKeyElement, byNewSubkeys, new_skeylen, PAGEOBJ_SUBKEYS)){ ERR_K2HPRN("Failed to replace subkey list into end of key."); K2H_Free(byNewSubkeys); break; } K2H_Free(byNewSubkeys); }else{ K2H_Free(last_marker); last_endkey = NULL; last_endlen = 0; } //-------------------------------------- // Re-Read marker with WRITE LOCK //-------------------------------------- // [NOTE] // At first, we lock marker and call Set method which locks marker. // Then twice locking for marker, but it does not deadlock because // marker does not have subkeys // K2H_Free(after_marker); K2HLock ALObjCKI_Marker(K2HLock::RWLOCK); // manually release locking after_marker = GetMarker(byMark, marklength, &ALObjCKI_Marker); after_endkey = after_marker ? &(after_marker->byData[after_marker->marker.endoff]) : NULL; after_endlen = after_marker ? after_marker->marker.endlen : 0; //-------------------------------------- // Update marker //-------------------------------------- // cppcheck-suppress unmatchedSuppression // cppcheck-suppress nullPointer if(after_marker && 0 < after_endlen){ // now marker has end of queue key if(!before_marker || 0 == before_endlen){ // // marker's end key is changed since reading before( before end key is not there. ) // ---> thus retry all processing // ALObjCKI_Marker.Unlock(); // Unlock // switch(after -> before) // cppcheck-suppress unmatchedSuppression // cppcheck-suppress identicalInnerCondition K2H_Free(after_marker); K2H_Free(before_marker); before_marker = GetMarker(byMark, marklength); before_endkey = before_marker ? &(before_marker->byData[before_marker->marker.endoff]) : NULL; before_endlen = before_marker ? before_marker->marker.endlen : 0; }else if(0 == k2hbincmp(before_endkey, before_endlen, after_endkey, after_endlen)){ // // now marker's end key is as same as before end key. // ---> update marker // size_t marklen = 0; if(NULL == (after_marker = K2HShm::UpdateK2HMarker(after_marker, marklen, byKey, keylength, true))){ // FIFO ERR_K2HPRN("Could not make new marker value."); break; // automatically unlock ALObjCKI_Marker } // Set new marker(marker does not have any attribute.) if(!Set(byMark, marklength, &(after_marker->byData[0]), marklen, NULL, true, NULL, NULL, NULL, K2hAttrOpsMan::OPSMAN_MASK_ALL)){ ERR_K2HPRN("Could not set new marker."); break; // automatically unlock ALObjCKI_Marker } result = true; // automatically unlock ALObjCKI_Marker }else if(0 == k2hbincmp(byKey, keylength, after_endkey, after_endlen)){ // // marker's end key is changed, and is as same as new key // ---> thus we do not any processing. // result = true; // automatically unlock ALObjCKI_Marker }else{ // // marker's end key(yyy) is changed since reading before(xxx) // ---> we must check deep! // // Unlock marker ALObjCKI_Marker.Unlock(); // Unlock // // Lock new key(exist?) and check new key's subkeys // K2HLock ALObjCKI_Newkey(K2HLock::RWLOCK); // auto release locking at leaving in this scope. PELEMENT pNewkeyElement; if(NULL == (pNewkeyElement = GetElement(byKey, keylength, ALObjCKI_Newkey))){ // // there is no new key, probably already popped it. // ---> thus we do not any processing. // result = true; // automatically unlock ALObjCKI_Newkey }else{ // // there is new key yet, check it's subkeys // K2HSubKeys* newkey_subkeys; if(NULL != (newkey_subkeys = GetSubKeys(pNewkeyElement, false)) && 0 < newkey_subkeys->size()){ // // new key is set subkey in it, this means new key is not end key. // ---> thus we do not any processing. // K2H_Delete(newkey_subkeys); result = true; // automatically unlock ALObjCKI_Newkey }else{ // // new key does not have subkey // ---> unknown reason, but we should retry all processing. // K2H_Delete(newkey_subkeys); ALObjCKI_Newkey.Unlock(); // Unlock // switch(after -> before) K2H_Free(before_marker); before_marker = after_marker; // using marker which is read after. before_endkey = after_endkey; before_endlen = after_endlen; after_marker = NULL; after_endkey = NULL; after_endlen = 0; } } } }else{ // // now marker does not exist, or does not have end of key // if(0 == k2hbincmp(before_endkey, before_endlen, after_endkey, after_endlen)){ // // before marker does not exist, or does not have end of key. // ---> we did not add new key into subkey list for end key(=not exist) // size_t marklen = 0; if(after_marker){ // // there is now marker, but it does not have end key // ---> update marker // if(NULL == (after_marker = K2HShm::UpdateK2HMarker(after_marker, marklen, byKey, keylength, true))){ // FIFO ERR_K2HPRN("Could not make new marker value."); break; // automatically unlock ALObjCKI_Marker } }else{ // // both before and now marker do not exist. // ---> update(create new) marker // if(NULL == (after_marker = K2HShm::InitK2HMarker(marklen, byKey, keylength))){ ERR_K2HPRN("Could not create marker."); break; // automatically unlock ALObjCKI_Marker } } // Set new marker(marker does not have any attribute.) if(!Set(byMark, marklength, &(after_marker->byData[0]), marklen, NULL, true, NULL, NULL, NULL, K2hAttrOpsMan::OPSMAN_MASK_ALL)){ ERR_K2HPRN("Could not set new marker."); break; // automatically unlock ALObjCKI_Marker } }else{ // // before marker exists, and it has end of key. // ---> we already added new key into subkey list for end key(=exists) // // cppcheck-suppress unmatchedSuppression // cppcheck-suppress duplicateBranch if(after_marker){ // // there is now marker, but it's end key does not exist. probably already popped new key. // ---> thus we do not any processing. // }else{ // // there is not now marker. probably already popped new key(and all queued keys). thus we had already added new key in it. // ---> thus we do not any processing. // } } result = true; // automatically unlock ALObjCKI_Marker } }while(!result); K2H_Free(before_marker); K2H_Free(after_marker); K2H_Free(last_marker); return result; } // // Add data to LIFO queue // bool K2HShm::AddLifoQueue(const unsigned char* byMark, size_t marklength, const unsigned char* byKey, size_t keylength, const unsigned char* byValue, size_t vallength, K2hAttrOpsMan::ATTRINITTYPE attrtype, K2HAttrs* pAttrs, const char* encpass, const time_t* expire) { // Read marker PBK2HMARKER before_marker = GetMarker(byMark, marklength); const unsigned char* before_startkey = before_marker ? &(before_marker->byData[before_marker->marker.startoff]) : NULL; size_t before_startlen = before_marker ? before_marker->marker.startlen : 0; PBK2HMARKER after_marker = NULL; bool result = false; // result code and for loop flag do{ const unsigned char* after_startkey = NULL; size_t after_startlen = 0; //-------------------------------------- // (Re)Make new key with subkey list which is from marker //-------------------------------------- K2HSubKeys* newkey_subkeys = NULL; if(before_marker && 0 < before_startlen){ // there is start key // ---> make subkey list data // newkey_subkeys = new K2HSubKeys(); newkey_subkeys->insert(before_startkey, before_startlen); } // Make new key in K2hash // // attrtype should be allowed OPSMAN_MASK_QUEUEKEY, OPSMAN_MASK_TRANSQUEUEKEY, OPSMAN_MASK_QUEUEMARKER and OPSMAN_MASK_KEYQUEUEKEY for Queue // if(!Set(byKey, keylength, byValue, vallength, newkey_subkeys, true, pAttrs, encpass, expire, attrtype)){ ERR_K2HPRN("Could not make new key."); K2H_Delete(newkey_subkeys); break; } K2H_Delete(newkey_subkeys); //-------------------------------------- // Re-Read marker with WRITE LOCK //-------------------------------------- // [NOTE] // At first, we lock marker and call Set method which locks marker. // Then twice locking for marker, but it does not deadlock because // marker does not have subkeys // K2HLock ALObjCKI_Marker(K2HLock::RWLOCK); // manually release locking after_marker = GetMarker(byMark, marklength, &ALObjCKI_Marker); after_startkey = after_marker ? &(after_marker->byData[after_marker->marker.startoff]) : NULL; after_startlen = after_marker ? after_marker->marker.startlen : 0; //-------------------------------------- // Add new key into subkeys for start key in marker //-------------------------------------- // cppcheck-suppress unmatchedSuppression // cppcheck-suppress nullPointer if(after_marker && 0 < after_startlen){ // now marker has start of queue key if(!before_marker || 0 == before_startlen){ // // marker's start key is changed since reading before( before start key is not there. ) // ---> thus retry all processing // ALObjCKI_Marker.Unlock(); // Unlock // switch(after -> before) // cppcheck-suppress unmatchedSuppression // cppcheck-suppress identicalInnerCondition K2H_Free(after_marker); K2H_Free(before_marker); before_marker = GetMarker(byMark, marklength); before_startkey = before_marker ? &(before_marker->byData[before_marker->marker.startoff]) : NULL; before_startlen = before_marker ? before_marker->marker.startlen : 0; }else if(0 == k2hbincmp(before_startkey, before_startlen, after_startkey, after_startlen)){ // // now marker's start key is as same as before start key. // ---> update marker // size_t marklen = 0; if(NULL == (after_marker = K2HShm::UpdateK2HMarker(after_marker, marklen, byKey, keylength, false))){ // LIFO ERR_K2HPRN("Could not make new marker value."); break; // automatically unlock ALObjCKI_Marker } // Set new marker(marker does not have any attribute.) if(!Set(byMark, marklength, &(after_marker->byData[0]), marklen, NULL, true, NULL, NULL, NULL, K2hAttrOpsMan::OPSMAN_MASK_ALL)){ ERR_K2HPRN("Could not set new marker."); break; // automatically unlock ALObjCKI_Marker } result = true; // automatically unlock ALObjCKI_Marker }else if(0 == k2hbincmp(byKey, keylength, after_startkey, after_startlen)){ // // marker's start key is changed, and is as same as new key // ---> thus we do not any processing. // result = true; // automatically unlock ALObjCKI_Marker }else{ // // marker's start key(yyy) is changed since reading before(xxx) // ---> thus retry all processing // ALObjCKI_Marker.Unlock(); // Unlock // switch(after -> before) K2H_Free(after_marker); K2H_Free(before_marker); before_marker = GetMarker(byMark, marklength); before_startkey = before_marker ? &(before_marker->byData[before_marker->marker.startoff]) : NULL; before_startlen = before_marker ? before_marker->marker.startlen : 0; } }else{ // // now marker does not exist, or does not have start of key // if(0 == k2hbincmp(before_startkey, before_startlen, after_startkey, after_startlen)){ // // before marker does not exist, or does not have start of key. // ---> we did not add new key into subkey list for start key(=not exist) // size_t marklen = 0; if(after_marker){ // // there is now marker, but it does not have start key // ---> update marker // if(NULL == (after_marker = K2HShm::UpdateK2HMarker(after_marker, marklen, byKey, keylength, false))){ // LIFO ERR_K2HPRN("Could not make new marker value."); break; // automatically unlock ALObjCKI_Marker } }else{ // // both before and now marker do not exist. // ---> update(create new) marker // if(NULL == (after_marker = K2HShm::InitK2HMarker(marklen, byKey, keylength))){ ERR_K2HPRN("Could not create marker."); break; // automatically unlock ALObjCKI_Marker } } // Set new marker(marker does not have any attribute.) if(!Set(byMark, marklength, &(after_marker->byData[0]), marklen, NULL, true, NULL, NULL, NULL, K2hAttrOpsMan::OPSMAN_MASK_ALL)){ ERR_K2HPRN("Could not set new marker."); break; // automatically unlock ALObjCKI_Marker } result = true; // automatically unlock ALObjCKI_Marker }else{ // // before marker exists, and it has start of key. // ---> thus retry all processing // ALObjCKI_Marker.Unlock(); // Unlock // switch(after -> before) K2H_Free(after_marker); K2H_Free(before_marker); before_marker = GetMarker(byMark, marklength); before_startkey = before_marker ? &(before_marker->byData[before_marker->marker.startoff]) : NULL; before_startlen = before_marker ? before_marker->marker.startlen : 0; } } }while(!result); K2H_Free(before_marker); K2H_Free(after_marker); return result; } // // This method does not update any queued key and queued key's subkey. // For calling this from K2HLowOpsQueue class. // bool K2HShm::AddQueue(const unsigned char* byMark, size_t marklength, const unsigned char* byKey, size_t keylength, bool is_fifo) { if(!byMark || 0 == marklength || !byKey || 0 == keylength){ ERR_K2HPRN("Some parameters are wrong."); return false; } if(!IsAttached()){ ERR_K2HPRN("There is no attached K2HASH."); return false; } K2HFILE_UPDATE_CHECK(this); K2HLock ALObjCKI(K2HLock::RWLOCK); // auto release locking at leaving in this scope. PBK2HMARKER pmarker = GetMarker(byMark, marklength, &ALObjCKI); size_t marklen = 0; if(!pmarker){ // There is no marker, so make new marker if(NULL == (pmarker = K2HShm::InitK2HMarker(marklen))){ ERR_K2HPRN("Could not make new marker value."); return false; } } // Update marker data if(NULL == (pmarker = K2HShm::UpdateK2HMarker(pmarker, marklen, byKey, keylength, is_fifo))){ ERR_K2HPRN("Could not make new marker value."); K2H_Free(pmarker); return false; } // Set new marker // // marker does not have any attribute. // if(!Set(byMark, marklength, &(pmarker->byData[0]), marklen, NULL, true, NULL, NULL, NULL, K2hAttrOpsMan::OPSMAN_MASK_ALL)){ ERR_K2HPRN("Could not set new/update marker."); K2H_Free(pmarker); return false; } K2H_Free(pmarker); return true; } // // Get/Retrieve one top key in queue list. // // [arguments] // const unsigned char* byMark : marker binary pointer // size_t marklength : marker length // bool& is_found : the result of whether or not the queued key existed is stored in this buffer // bool& is_expired : the result of whether or not the queued key is expired is stored in this buffer // unsigned char** ppKey : returns popped key binary pointer // size_t& keylength : returns popped key binary length // unsigned char** ppValue : returns popped key's value binary pointer // size_t& vallength : returns popped key's value binary length // K2HAttrs** ppAttrs : returns popped key's attributes object pointer if ppAttrs is not NULL.(allowed null to this pointer) // const char* encpass : encrypt pass phrase // // [return] // true : one key is popped(updated marker) or there is no popped key(including expired key) // false : something error occurred. // bool K2HShm::PopQueueEx(const unsigned char* byMark, size_t marklength, bool& is_found, bool& is_expired, unsigned char** ppKey, size_t& keylength, unsigned char** ppValue, size_t& vallength, K2HAttrs** ppAttrs, const char* encpass) { if(!byMark || 0 == marklength || !ppKey || !ppValue){ ERR_K2HPRN("Some parameters are wrong."); return false; } if(!IsAttached()){ ERR_K2HPRN("There is no attached K2HASH."); return false; } // This method returns true when there is no queue data. // So caller is check following value. // *ppKey = NULL; keylength = 0; *ppValue = NULL; vallength = 0; if(ppAttrs){ *ppAttrs= NULL; } while(true){ is_found = false; is_expired = false; //-------------------------------------- // Read marker without WRITE LOCK //-------------------------------------- PBK2HMARKER before_marker = GetMarker(byMark, marklength); const unsigned char* before_startkey = before_marker ? &(before_marker->byData[before_marker->marker.startoff]) : NULL; size_t before_startlen = before_marker ? before_marker->marker.startlen : 0; // cppcheck-suppress unmatchedSuppression // cppcheck-suppress nullPointer if(!before_marker || !before_startkey || 0 == before_startlen){ // there is no marker or no start key of queue, it means no stacked key in queue. K2H_Free(before_marker); break; } is_found = true; // Get subkeys in current start key for next marker's start key(without checking attribute) K2HSubKeys* psubkeys = GetSubKeys(before_startkey, before_startlen, false); const unsigned char* pnextstart = NULL; size_t nextstartLen= 0; if(psubkeys){ K2HSubKeys::iterator iter = psubkeys->begin(); if(iter != psubkeys->end()){ pnextstart = iter->pSubKey; nextstartLen= iter->length; } } // Get attribute and check expire K2HAttrs* pKeyAttrs; if(NULL != (pKeyAttrs = GetAttrs(before_startkey, before_startlen))){ K2hAttrOpsMan attrman; if(attrman.Initialize(this, before_startkey, before_startlen, NULL, 0UL, NULL)){ if(attrman.IsExpire(*pKeyAttrs)){ is_expired = true; // key is expired } }else{ WAN_K2HPRN("Something error occurred during initializing attributes manager class, but continue..."); } K2H_Delete(pKeyAttrs); } // Get value(with checking attribute) ssize_t tmpvallen; if(-1 == (tmpvallen = Get(before_startkey, before_startlen, ppValue, true, encpass))){ MSG_K2HPRN("Could not get popped key value(there is no value or key is expired.)"); }else{ vallength = static_cast<size_t>(tmpvallen); } //-------------------------------------- // Re-Read marker with WRITE LOCK //-------------------------------------- // [NOTE] // At first, we lock marker and call Set method which locks marker. // Then twice locking for marker, but it does not deadlock because // marker does not have subkeys // K2HLock ALObjCKI_Marker(K2HLock::RWLOCK); // auto release locking at leaving in this scope. PBK2HMARKER after_marker = GetMarker(byMark, marklength, &ALObjCKI_Marker); const unsigned char* after_startkey = after_marker ? &(after_marker->byData[after_marker->marker.startoff]) : NULL; size_t after_startlen = after_marker ? after_marker->marker.startlen : 0; // cppcheck-suppress unmatchedSuppression // cppcheck-suppress nullPointer if(!after_marker){ MSG_K2HPRN("After reading marker, the marker is empty or wrong size."); K2H_Free(before_marker); K2H_Delete(psubkeys); K2H_Delete(pKeyAttrs); K2H_Free(*ppValue); vallength = 0; is_found = false; is_expired = false; return false; // automatically unlock ALObjCKI_Marker } // Check popped key name, compare it and before reading key name. if(0 != k2hbincmp(before_startkey, before_startlen, after_startkey, after_startlen)){ MSG_K2HPRN("Different popped key name before and after reading, thus retry from first."); K2H_Free(before_marker); K2H_Free(after_marker); K2H_Delete(psubkeys); K2H_Delete(pKeyAttrs); K2H_Free(*ppValue); vallength = 0; ALObjCKI_Marker.Unlock(); // manually unlock continue; } // Make new next K2HMaker PBK2HMARKER pnewmarker; size_t newmarklen = 0; if(NULL == (pnewmarker = K2HShm::InitK2HMarker(newmarklen, pnextstart, nextstartLen, (0 == after_marker->marker.endlen ? NULL : (&(after_marker->byData[0]) + after_marker->marker.endoff)), after_marker->marker.endlen))){ ERR_K2HPRN("Something error is occurred to make new marker."); K2H_Free(before_marker); K2H_Free(after_marker); K2H_Delete(psubkeys); K2H_Delete(pKeyAttrs); K2H_Free(*ppValue); vallength = 0; is_found = false; is_expired = false; return false; // automatically unlock ALObjCKI_Marker } K2H_Delete(psubkeys); // Set new marker(marker does not have any attribute) if(!Set(byMark, marklength, &(pnewmarker->byData[0]), newmarklen, NULL, true, NULL, NULL, NULL, K2hAttrOpsMan::OPSMAN_MASK_ALL)){ ERR_K2HPRN("Could not set new marker."); K2H_Free(before_marker); K2H_Free(after_marker); K2H_Free(pnewmarker); K2H_Delete(pKeyAttrs); K2H_Free(*ppValue); vallength = 0; is_found = false; is_expired = false; return false; // automatically unlock ALObjCKI_Marker } K2H_Free(pnewmarker); // Unlock marker ALObjCKI_Marker.Unlock(); // manually unlock // Remove key(without subkey & history) if(!Remove(after_startkey, after_startlen, false, NULL, true)){ ERR_K2HPRN("Could not remove popped key, but continue..."); } // Copy key name *ppKey = k2hbindup(before_startkey, before_startlen); keylength = before_startlen; if(ppAttrs){ *ppAttrs = pKeyAttrs; }else{ K2H_Delete(pKeyAttrs); } K2H_Free(before_marker); K2H_Free(after_marker); break; } return true; } // // Always remove key from queue at top. // Controlling FIFO or LIFO is decided at adding key into queue. // // Returns false: Something error occurred. // true: Succeed // if there is no popping data, returns true but ppValue is NULL. // // [NOTICE] // It is also the case that new end key in K2HMaker has subkeys after retrieving the key, but it is correct. // *** Even if end key had subkeys, never the subkeys is used. *** // // [NOTE] // If the key in queue list is expired, skip it. // bool K2HShm::PopQueue(const unsigned char* byMark, size_t marklength, unsigned char** ppKey, size_t& keylength, unsigned char** ppValue, size_t& vallength, K2HAttrs** ppAttrs, const char* encpass) { if(!byMark || 0 == marklength || !ppKey || !ppValue){ ERR_K2HPRN("Some parameters are wrong."); return false; } if(!IsAttached()){ ERR_K2HPRN("There is no attached K2HASH."); return false; } K2HFILE_UPDATE_CHECK(this); // // Pop from queue until not expired key. // bool result = true; bool is_found = true; bool is_expired = false; for(result = true, is_found = true, is_expired = false; result && is_found; is_expired = false){ if(false == (result = PopQueueEx(byMark, marklength, is_found, is_expired, ppKey, keylength, ppValue, vallength, ppAttrs, encpass))){ ERR_K2HPRN("Something error occurred during pooping from queue."); }else{ if(!is_expired && is_found){ break; } } K2H_Free(*ppKey); K2H_Free(*ppValue); if(ppAttrs){ K2H_Delete(*ppAttrs); } } return result; } int K2HShm::RemoveQueue(const unsigned char* byMark, size_t marklength, unsigned int count, bool rmkeyval, k2h_q_remove_trial_callback fp, void* pExtData, const char* encpass) { if(!byMark || 0 == marklength){ ERR_K2HPRN("Some parameters are wrong."); return -1; } if(!IsAttached()){ ERR_K2HPRN("There is no attached K2HASH."); return -1; } K2HFILE_UPDATE_CHECK(this); int removed_count = 0; unsigned char* ptopkey = NULL; size_t topkeylen = 0; for(unsigned int cnt = 0; cnt < count; ++cnt){ if(!ptopkey){ // Case of removing from top of queue //-------------------------------------- // Read marker without WRITE LOCK //-------------------------------------- PBK2HMARKER before_marker = GetMarker(byMark, marklength); const unsigned char* before_startkey = before_marker ? &(before_marker->byData[before_marker->marker.startoff]) : NULL; size_t before_startlen = before_marker ? before_marker->marker.startlen : 0; // cppcheck-suppress unmatchedSuppression // cppcheck-suppress nullPointer if(!before_marker || !before_startkey || 0 == before_startlen){ // there is no marker or no start key of queue, it means no stacked key in queue. K2H_Free(before_marker); break; } // Get subkeys in current start key for next marker's start key(without checking attribute) K2HSubKeys* psubkeys = GetSubKeys(before_startkey, before_startlen, false); const unsigned char* pnextstart = NULL; size_t nextstartLen= 0; if(psubkeys){ K2HSubKeys::iterator iter = psubkeys->begin(); if(iter != psubkeys->end()){ pnextstart = iter->pSubKey; nextstartLen= iter->length; } } // Get attribute and check expire(convert to binary structure for callback) PK2HATTRPCK pattrspck = NULL; int attrspckcnt = 0; if(fp){ K2HAttrs* pKeyAttrs; if(NULL != (pKeyAttrs = GetAttrs(before_startkey, before_startlen))){ pattrspck = k2h_cvt_attrs_to_bin(pKeyAttrs, attrspckcnt); K2H_Delete(pKeyAttrs); } } // Get value(with checking attribute) unsigned char* pTmpValue = NULL; ssize_t tmpvallen = 0; if(rmkeyval){ if(-1 == (tmpvallen = Get(before_startkey, before_startlen, &pTmpValue, true, encpass))){ MSG_K2HPRN("Could not get read key value(there is no value or key is expired.)"); tmpvallen = 0; } } // check by callback function K2HQRMCBRES res = K2HQRMCB_RES_CON_RM; // default(if null == fp) if(fp && pTmpValue){ // pTmpValue(Popped key's value) is data key for callback if(K2HQRMCB_RES_ERROR == (res = fp(pTmpValue, static_cast<size_t>(tmpvallen), pattrspck, attrspckcnt, pExtData))){ // Stop loop K2H_Free(before_marker); k2h_free_attrpack(pattrspck, attrspckcnt); K2H_Delete(psubkeys); K2H_Free(pTmpValue); break; } } k2h_free_attrpack(pattrspck, attrspckcnt); //-------------------------------------- // Removing //-------------------------------------- if(K2HQRMCB_RES_CON_RM == res || K2HQRMCB_RES_FIN_RM == res){ //-------------------------------------- // Re-Read marker with WRITE LOCK //-------------------------------------- // [NOTE] // At first, we lock marker and call Set method which locks marker. // Then twice locking for marker, but it does not deadlock because // marker does not have subkeys // K2HLock ALObjCKI_Marker(K2HLock::RWLOCK); // auto release locking at leaving in this scope. PBK2HMARKER after_marker = GetMarker(byMark, marklength, &ALObjCKI_Marker); const unsigned char* after_startkey = after_marker ? &(after_marker->byData[after_marker->marker.startoff]) : NULL; size_t after_startlen = after_marker ? after_marker->marker.startlen : 0; // cppcheck-suppress unmatchedSuppression // cppcheck-suppress nullPointer if(!after_marker){ MSG_K2HPRN("After reading marker, the marker is empty or wrong size."); K2H_Free(before_marker); K2H_Delete(psubkeys); K2H_Free(pTmpValue); break; // automatically unlock ALObjCKI_Marker } // Check read key name, compare it and before reading key name. if(0 != k2hbincmp(before_startkey, before_startlen, after_startkey, after_startlen)){ MSG_K2HPRN("Different read key name before and after reading, thus retry from first."); K2H_Free(before_marker); K2H_Free(after_marker); K2H_Delete(psubkeys); K2H_Free(pTmpValue); ALObjCKI_Marker.Unlock(); // manually unlock continue; } // Make new next K2HMaker PBK2HMARKER pnewmarker; size_t newmarklen = 0; if(NULL == (pnewmarker = K2HShm::InitK2HMarker(newmarklen, pnextstart, nextstartLen, (0 == after_marker->marker.endlen ? NULL : (&(after_marker->byData[0]) + after_marker->marker.endoff)), after_marker->marker.endlen))){ ERR_K2HPRN("Something error is occurred to make new marker."); K2H_Free(before_marker); K2H_Free(after_marker); K2H_Delete(psubkeys); K2H_Free(pTmpValue); break; // automatically unlock ALObjCKI_Marker } // Set new marker(marker does not have any attribute) if(!Set(byMark, marklength, &(pnewmarker->byData[0]), newmarklen, NULL, true, NULL, NULL, NULL, K2hAttrOpsMan::OPSMAN_MASK_ALL)){ ERR_K2HPRN("Could not set new marker."); K2H_Free(before_marker); K2H_Free(after_marker); K2H_Delete(psubkeys); K2H_Free(pTmpValue); K2H_Free(pnewmarker); break; // automatically unlock ALObjCKI_Marker } K2H_Free(pnewmarker); // Unlock marker ALObjCKI_Marker.Unlock(); // manually unlock // Remove key(without subkey & history) if(!Remove(after_startkey, after_startlen, false, NULL, true)){ ERR_K2HPRN("Could not remove read key, but continue..."); } K2H_Free(after_marker); // Remove value(key) with attributes if(rmkeyval && pTmpValue){ if(!Remove(pTmpValue, static_cast<size_t>(tmpvallen), true)){ ERR_K2HPRN("Could not remove key from k2hash, but continue..."); } } removed_count++; }else{ // Set next key, it is not top of queue ptopkey = k2hbindup(before_startkey, before_startlen); topkeylen = before_startlen; } K2H_Free(before_marker); K2H_Delete(psubkeys); K2H_Free(pTmpValue); }else{ // Case of removing from middle of queue // check end of queue key PBK2HMARKER current_marker = GetMarker(byMark, marklength); const unsigned char* current_endkey = current_marker ? &(current_marker->byData[current_marker->marker.endoff]) : NULL; size_t current_endlen = current_marker ? current_marker->marker.endlen : 0; // cppcheck-suppress unmatchedSuppression // cppcheck-suppress nullPointer if(!current_marker || !current_endkey || 0 == current_endlen){ // there is no marker or no end key of queue, thus we do not check end key. K2H_Free(current_marker); break; } if(0 == k2hbincmp(current_endkey, current_endlen, ptopkey, topkeylen)){ MSG_K2HPRN("top normal key is end of queue key. thus stop removing."); K2H_Free(current_marker); break; } //-------------------------------------- // Read key without WRITE LOCK //-------------------------------------- // Get subkeys in top key for next key(without checking attribute) K2HSubKeys* psubkeys = GetSubKeys(ptopkey, topkeylen, false); if(!psubkeys){ MSG_K2HPRN("reached end of key in top normal key during removing, so stop removing."); K2H_Free(current_marker); break; } K2HSubKeys::iterator iter = psubkeys->begin(); if(iter == psubkeys->end()){ MSG_K2HPRN("reached end of key in top normal key during removing, so stop removing."); K2H_Free(current_marker); break; } const unsigned char* pnextkey = iter->pSubKey; size_t nextkeyLen = iter->length; // check marker end key as same as top to next key bool is_update_marker = false; if(0 == k2hbincmp(current_endkey, current_endlen, pnextkey, nextkeyLen)){ // need to update marker key is_update_marker = true; } // Get attribute and check expire(convert to binary structure for callback) PK2HATTRPCK pattrspck = NULL; int attrspckcnt = 0; if(fp){ K2HAttrs* pKeyAttrs; if(NULL != (pKeyAttrs = GetAttrs(pnextkey, nextkeyLen))){ pattrspck = k2h_cvt_attrs_to_bin(pKeyAttrs, attrspckcnt); K2H_Delete(pKeyAttrs); } } // Get value(with checking attribute) unsigned char* pTmpValue = NULL; ssize_t tmpvallen = 0; if(rmkeyval){ if(-1 == (tmpvallen = Get(pnextkey, nextkeyLen, &pTmpValue, true, encpass))){ MSG_K2HPRN("Could not get read key value(there is no value or key is expired.)"); tmpvallen = 0; } } // check by callback function K2HQRMCBRES res = K2HQRMCB_RES_CON_RM; // default(if null == fp) if(fp && pTmpValue){ // pTmpValue(Popped key's value) is data key for callback if(K2HQRMCB_RES_ERROR == (res = fp(pTmpValue, static_cast<size_t>(tmpvallen), pattrspck, attrspckcnt, pExtData))){ // Stop loop K2H_Free(current_marker); k2h_free_attrpack(pattrspck, attrspckcnt); K2H_Delete(psubkeys); K2H_Free(pTmpValue); break; } } k2h_free_attrpack(pattrspck, attrspckcnt); //-------------------------------------- // Removing //-------------------------------------- if(K2HQRMCB_RES_CON_RM == res || K2HQRMCB_RES_FIN_RM == res){ // get next end key K2HSubKeys* pnextendskeys = GetSubKeys(pnextkey, nextkeyLen, false); //-------------------------------------- // Re-Read Key with WRITE LOCK //-------------------------------------- // [NOTE] // At first, we lock key and call GetSubkeys/Set method which locks this key. // Then twice locking for key, but it does not deadlock because // we only read it, and remove subkeys. // K2HLock ALObjCKI_TopKey(K2HLock::RWLOCK); // auto release locking at leaving in this scope. k2h_hash_t hash = K2H_HASH_FUNC(reinterpret_cast<const void*>(ptopkey), topkeylen); if(NULL == GetCKIndex(hash, ALObjCKI_TopKey)){ MSG_K2HPRN("normal top queue key does not exist, probably removing it."); K2H_Free(current_marker); K2H_Delete(psubkeys); K2H_Delete(pnextendskeys); K2H_Free(pTmpValue); break; // automatically unlock ALObjCKI_TopKey } // re-get subkeys and check it K2HSubKeys* presubkeys = GetSubKeys(ptopkey, topkeylen, false); if(!presubkeys){ MSG_K2HPRN("reached end of key in top normal key during removing, so stop removing."); K2H_Free(current_marker); K2H_Delete(psubkeys); K2H_Delete(pnextendskeys); K2H_Free(pTmpValue); break; // automatically unlock ALObjCKI_TopKey } K2HSubKeys::iterator reiter = presubkeys->begin(); if(reiter == presubkeys->end()){ MSG_K2HPRN("reached end of key in top normal key during removing, so stop removing."); K2H_Free(current_marker); K2H_Delete(psubkeys); K2H_Delete(pnextendskeys); K2H_Delete(presubkeys); K2H_Free(pTmpValue); break; // automatically unlock ALObjCKI_TopKey } // compare subkey if(0 == k2hbincmp(pnextkey, nextkeyLen, reiter->pSubKey, reiter->length)){ MSG_K2HPRN("top normal key is end of queue key. thus stop removing."); K2H_Free(current_marker); K2H_Delete(psubkeys); K2H_Delete(pnextendskeys); K2H_Delete(presubkeys); K2H_Free(pTmpValue); break; // automatically unlock ALObjCKI_TopKey } K2H_Delete(presubkeys); // replace subkeys to top key unsigned char* bySubkeys = NULL; size_t skeylength= 0UL; pnextendskeys->Serialize(&bySubkeys, skeylength); if(!ReplaceSubkeys(ptopkey, topkeylen, bySubkeys, skeylength)){ ERR_K2HPRN("Failed to insert new subkeys into normal top key in queue."); K2H_Free(current_marker); K2H_Delete(psubkeys); K2H_Delete(pnextendskeys); K2H_Free(pTmpValue); K2H_Free(bySubkeys); break; // automatically unlock ALObjCKI_TopKey } K2H_Delete(pnextendskeys); K2H_Free(bySubkeys); // Unlock marker ALObjCKI_TopKey.Unlock(); // manually unlock // Remove key(without subkey & history) if(!Remove(pnextkey, nextkeyLen, false, NULL, true)){ ERR_K2HPRN("Could not remove read key, but continue..."); } // Remove value(key) with attributes if(rmkeyval && pTmpValue){ if(!Remove(pTmpValue, static_cast<size_t>(tmpvallen), true)){ ERR_K2HPRN("Could not remove key from k2hash, but continue..."); } } removed_count++; // special update marker end key if it's needed. if(is_update_marker){ //-------------------------------------- // Read marker with WRITE LOCK //-------------------------------------- // [NOTE] // At first, we lock marker and call Set method which locks marker. // Then twice locking for marker, but it does not deadlock because // marker does not have subkeys // K2HLock ALObjCKI_Marker(K2HLock::RWLOCK); // auto release locking at leaving in this scope. PBK2HMARKER after_marker = GetMarker(byMark, marklength, &ALObjCKI_Marker); const unsigned char* after_endkey = after_marker ? &(after_marker->byData[after_marker->marker.endoff]) : NULL; size_t after_endlen = after_marker ? after_marker->marker.endlen : 0; // cppcheck-suppress unmatchedSuppression // cppcheck-suppress nullPointer if(!after_marker){ MSG_K2HPRN("After reading marker, the marker is empty or wrong size."); K2H_Free(current_marker); K2H_Delete(psubkeys); K2H_Free(pTmpValue); break; // automatically unlock ALObjCKI_Marker } // Check read key name, compare it and before reading key name. if(0 != k2hbincmp(after_endkey, after_endlen, pnextkey, nextkeyLen)){ MSG_K2HPRN("Different read end key name before and after reading."); K2H_Free(current_marker); K2H_Free(after_marker); K2H_Delete(psubkeys); K2H_Free(pTmpValue); break; // automatically unlock ALObjCKI_Marker } // Make new next K2HMaker PBK2HMARKER pnewmarker; size_t newmarklen = 0; if(NULL == (pnewmarker = K2HShm::InitK2HMarker(newmarklen, (0 == after_marker->marker.startlen ? NULL : (&(after_marker->byData[0]) + after_marker->marker.startoff)), after_marker->marker.startlen, ptopkey, topkeylen))){ ERR_K2HPRN("Something error is occurred to make new marker."); K2H_Free(current_marker); K2H_Free(after_marker); K2H_Delete(psubkeys); K2H_Free(pTmpValue); break; // automatically unlock ALObjCKI_Marker } // Set new marker(marker does not have any attribute) if(!Set(byMark, marklength, &(pnewmarker->byData[0]), newmarklen, NULL, true, NULL, NULL, NULL, K2hAttrOpsMan::OPSMAN_MASK_ALL)){ ERR_K2HPRN("Could not set new marker."); K2H_Free(current_marker); K2H_Free(after_marker); K2H_Delete(psubkeys); K2H_Free(pTmpValue); K2H_Free(pnewmarker); break; // automatically unlock ALObjCKI_Marker } K2H_Free(pnewmarker); K2H_Free(after_marker); // Unlock marker ALObjCKI_Marker.Unlock(); // manually unlock } }else{ // Set next key, it is not top of queue K2H_Free(ptopkey); ptopkey = k2hbindup(pnextkey, nextkeyLen); topkeylen = nextkeyLen; } K2H_Free(current_marker); K2H_Delete(psubkeys); K2H_Free(pTmpValue); // check next top key if(!ptopkey){ break; } } } K2H_Free(ptopkey); return removed_count; } K2HQueue* K2HShm::GetQueueObj(bool is_fifo, const unsigned char* pref, size_t preflen) { if(!IsAttached()){ ERR_K2HPRN("There is no attached K2HASH."); return NULL; } K2HQueue* queue = new K2HQueue(); if(!queue->Init(this, is_fifo, pref, preflen)){ K2H_Delete(queue); return NULL; } return queue; } K2HKeyQueue* K2HShm::GetKeyQueueObj(bool is_fifo, const unsigned char* pref, size_t preflen) { if(!IsAttached()){ ERR_K2HPRN("There is no attached K2HASH."); return NULL; } K2HKeyQueue* queue = new K2HKeyQueue(); if(!queue->Init(this, is_fifo, pref, preflen)){ K2H_Delete(queue); return NULL; } return queue; } K2HLowOpsQueue* K2HShm::GetLowOpsQueueObj(bool is_fifo, const unsigned char* pref, size_t preflen) { if(!IsAttached()){ ERR_K2HPRN("There is no attached K2HASH."); return NULL; } K2HLowOpsQueue* queue = new K2HLowOpsQueue(); if(!queue->Init(this, is_fifo, pref, preflen)){ K2H_Delete(queue); return NULL; } return queue; } /* * VIM modelines * * vim:set ts=4 fenc=utf-8: */
34.318961
276
0.665448
[ "object" ]
ad33a2ab0e1e02973f0bdf914cb5157ac1122b4e
2,786
hpp
C++
src/mbgl/renderer/layers/render_symbol_layer.hpp
truthiswill/mapbox-gl-native
d0a1526a94dd596e02306ae8c3638ca58e24a323
[ "BSL-1.0", "Apache-2.0" ]
2
2019-04-18T21:25:22.000Z
2019-04-18T21:25:24.000Z
src/mbgl/renderer/layers/render_symbol_layer.hpp
whitemike889/mapbox-gl-native
d0a1526a94dd596e02306ae8c3638ca58e24a323
[ "BSL-1.0", "Apache-2.0" ]
null
null
null
src/mbgl/renderer/layers/render_symbol_layer.hpp
whitemike889/mapbox-gl-native
d0a1526a94dd596e02306ae8c3638ca58e24a323
[ "BSL-1.0", "Apache-2.0" ]
null
null
null
#pragma once #include <mbgl/text/glyph.hpp> #include <mbgl/renderer/render_layer.hpp> #include <mbgl/renderer/layers/render_layer_symbol_interface.hpp> #include <mbgl/style/image_impl.hpp> #include <mbgl/style/layers/symbol_layer_impl.hpp> #include <mbgl/style/layers/symbol_layer_properties.hpp> namespace mbgl { namespace style { // {icon,text}-specific paint-property packs for use in the symbol Programs. // Since each program deals either with icons or text, using a smaller property set // lets us avoid unnecessarily binding attributes for properties the program wouldn't use. class IconPaintProperties : public Properties< IconOpacity, IconColor, IconHaloColor, IconHaloWidth, IconHaloBlur, IconTranslate, IconTranslateAnchor > {}; class TextPaintProperties : public Properties< TextOpacity, TextColor, TextHaloColor, TextHaloWidth, TextHaloBlur, TextTranslate, TextTranslateAnchor > {}; // Repackaging evaluated values from SymbolLayoutProperties + SymbolPaintProperties // for genericity over icons vs. text. class SymbolPropertyValues { public: // Layout AlignmentType pitchAlignment; AlignmentType rotationAlignment; bool keepUpright; // Paint std::array<float, 2> translate; TranslateAnchorType translateAnchor; bool hasHalo; bool hasFill; }; } // namespace style class RenderSymbolLayer final: public RenderLayer, public RenderLayerSymbolInterface { public: explicit RenderSymbolLayer(Immutable<style::SymbolLayer::Impl>); ~RenderSymbolLayer() override; static style::IconPaintProperties::PossiblyEvaluated iconPaintProperties(const style::SymbolPaintProperties::PossiblyEvaluated&); static style::TextPaintProperties::PossiblyEvaluated textPaintProperties(const style::SymbolPaintProperties::PossiblyEvaluated&); private: void transition(const TransitionParameters&) override; void evaluate(const PropertyEvaluationParameters&) override; bool hasTransition() const override; bool hasCrossfade() const override; void render(PaintParameters&, RenderSource*) override; void setRenderTiles(RenderTiles, const TransformState&) override; // RenderLayerSymbolInterface overrides const RenderLayerSymbolInterface* getSymbolInterface() const override; const std::string& layerID() const override; const std::vector<std::reference_wrapper<RenderTile>>& getRenderTiles() const override; SymbolBucket* getSymbolBucket(const RenderTile&) const override; // Paint properties style::SymbolPaintProperties::Unevaluated unevaluated; float iconSize = 1.0f; float textSize = 16.0f; bool hasFormatSectionOverrides = false; }; } // namespace mbgl
31.659091
133
0.751256
[ "render", "vector" ]
ad35ec09a36f90300c890d04383d0dacf911237f
2,085
cpp
C++
scrimmage/src/network/ScrimmageServiceImpl.cpp
ddfan/swarm_evolve
cd2d972c021e9af5946673363fbfd39cff18f13f
[ "MIT" ]
10
2019-04-29T03:01:19.000Z
2022-03-22T03:11:30.000Z
scrimmage/src/network/ScrimmageServiceImpl.cpp
lyers179/swarm_evolve
cd2d972c021e9af5946673363fbfd39cff18f13f
[ "MIT" ]
3
2018-10-29T02:14:10.000Z
2020-11-23T02:36:14.000Z
scrimmage/src/network/ScrimmageServiceImpl.cpp
lyers179/swarm_evolve
cd2d972c021e9af5946673363fbfd39cff18f13f
[ "MIT" ]
8
2018-10-29T02:07:56.000Z
2022-01-04T06:37:53.000Z
#if ENABLE_GRPC #include <scrimmage/network/ScrimmageServiceImpl.h> scrimmage::ScrimmageServiceImpl::ScrimmageServiceImpl(scrimmage::Interface *interface) : interface_(interface){ } grpc::Status scrimmage::ScrimmageServiceImpl::SendFrame(grpc::ServerContext *context, const scrimmage_proto::Frame *frame, scrimmage_proto::BlankReply *reply) { std::shared_ptr<scrimmage_proto::Frame> f = std::make_shared<scrimmage_proto::Frame>(*frame); interface_->push_frame(f); return grpc::Status::OK; } grpc::Status scrimmage::ScrimmageServiceImpl::SendUTMTerrain(grpc::ServerContext *context, const scrimmage_proto::UTMTerrain *terrain, scrimmage_proto::BlankReply *reply) { std::shared_ptr<scrimmage_proto::UTMTerrain> t = std::make_shared<scrimmage_proto::UTMTerrain>(*terrain); interface_->push_utm_terrain(t); return grpc::Status::OK; } grpc::Status scrimmage::ScrimmageServiceImpl::SendSimInfo(grpc::ServerContext *context, const scrimmage_proto::SimInfo *sim_info, scrimmage_proto::BlankReply *reply) { scrimmage_proto::SimInfo si = *sim_info; interface_->push_sim_info(si); return grpc::Status::OK; } grpc::Status scrimmage::ScrimmageServiceImpl::SendGUIMsg(grpc::ServerContext *context, const scrimmage_proto::GUIMsg *gui_msg, scrimmage_proto::BlankReply *reply) { scrimmage_proto::GUIMsg si = *gui_msg; interface_->push_gui_msg(si); return grpc::Status::OK; } grpc::Status scrimmage::ScrimmageServiceImpl::SendContactVisual(grpc::ServerContext *context, const scrimmage_proto::ContactVisual *contact_visual, scrimmage_proto::BlankReply *reply) { std::shared_ptr<scrimmage_proto::ContactVisual> cv = std::make_shared<scrimmage_proto::ContactVisual>(*contact_visual); interface_->push_contact_visual(cv); return grpc::Status::OK; } grpc::Status scrimmage::ScrimmageServiceImpl::SendShapes(grpc::ServerContext *context, const scrimmage_proto::Shapes *shape, scrimmage_proto::BlankReply *reply) { scrimmage_proto::Shapes s = *shape; interface_->push_shapes(s); return grpc::Status::OK; } #endif // ENABLE_GRPC
47.386364
185
0.774101
[ "shape" ]
ad3861837d633e2b71966cba3b05964061b93e35
2,541
hpp
C++
benchmark_apps/elmerfem/ElmerGUI/netgen/libsrc/csg/edgeflw.hpp
readex-eu/readex-apps
38493b11806c306f4e8f1b7b2d97764b45fac8e2
[ "BSD-3-Clause" ]
2
2020-11-25T13:10:11.000Z
2021-03-15T20:26:35.000Z
elmerfem/ElmerGUI/netgen/libsrc/csg/edgeflw.hpp
jcmcmurry/pipelining
8fface1a501b5050f58e7b902aacdcdde68e9648
[ "MIT" ]
null
null
null
elmerfem/ElmerGUI/netgen/libsrc/csg/edgeflw.hpp
jcmcmurry/pipelining
8fface1a501b5050f58e7b902aacdcdde68e9648
[ "MIT" ]
2
2021-08-02T23:23:40.000Z
2022-02-26T12:39:30.000Z
#ifndef FILE_EDGEFLW #define FILE_EDGEFLW /**************************************************************************/ /* File: edgeflw.hh */ /* Author: Joachim Schoeberl */ /* Date: 01. Okt. 95 */ /**************************************************************************/ /* Edge - following function and Projection to edge of implicitly given edge */ /** Calculates edges. The edges of a solid geometry are computed. Special points have to be given. */ extern void CalcEdges (const CSGeometry & geometry, const ARRAY<SpecialPoint> & specpoints, double h, Mesh & mesh); class EdgeCalculation { const CSGeometry & geometry; ARRAY<SpecialPoint> & specpoints; Point3dTree * searchtree; Point3dTree * meshpoint_tree; int cntedge; double ideps; public: EdgeCalculation (const CSGeometry & ageometry, ARRAY<SpecialPoint> & aspecpoints); ~EdgeCalculation(); void SetIdEps(const double epsin) {ideps = epsin;} void Calc(double h, Mesh & mesh); private: void CalcEdges1 (double h, Mesh & mesh); void FollowEdge (int pi1, int & ep, int & pos, // const ARRAY<SpecialPoint> & hsp, const ARRAY<int> & hsp, double h, const Mesh & mesh, ARRAY<Point<3> > & edgepoints, ARRAY<double> & curvelength); void AnalyzeEdge (int s1, int s2, int s1_rep, int s2_rep, int pos, int layer, const ARRAY<Point<3> > & edgepoints, ARRAY<Segment> & refedges, ARRAY<bool> & refedgesinv); void StoreEdge (const ARRAY<Segment> & refedges, const ARRAY<bool> & refedgesinv, const ARRAY<Point<3> > & edgepoints, const ARRAY<double> & curvelength, int layer, Mesh & mesh); void StoreShortEdge (const ARRAY<Segment> & refedges, const ARRAY<bool> & refedgesinv, const ARRAY<Point<3> > & edgepoints, const ARRAY<double> & curvelength, int layer, Mesh & mesh); void CopyEdge (const ARRAY<Segment> & refedges, const ARRAY<bool> & refedgesinv, int copyfromedge, const Point<3> & fromstart, const Point<3> & fromend, const Point<3> & tostart, const Point<3> & toend, int copyedgeidentification, int layer, Mesh & mesh); void SplitEqualOneSegEdges (Mesh & mesh); void FindClosedSurfaces (double h, Mesh & mesh); public: bool point_on_edge_problem; }; #endif
24.2
79
0.571822
[ "mesh", "geometry", "solid" ]
ad39aa66ba628d76277bfd537dcd40a4eaec5b83
734
cpp
C++
mathematics/PickingCards.cpp
HannoFlohr/hackerrank
9644c78ce05a6b1bc5d8f542966781d53e5366e3
[ "MIT" ]
null
null
null
mathematics/PickingCards.cpp
HannoFlohr/hackerrank
9644c78ce05a6b1bc5d8f542966781d53e5366e3
[ "MIT" ]
null
null
null
mathematics/PickingCards.cpp
HannoFlohr/hackerrank
9644c78ce05a6b1bc5d8f542966781d53e5366e3
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; typedef long long int ll; const int MOD = 1000000007; int main() { int t, n, x, drawn, cur, i; ll result; cin >> t; while(t--) { cin >> n; vector<int> c (n); for(i=0; i<n; i++) cin >> c[i]; sort(c.begin(),c.end()); drawn = 0; result = 1LL; i = 0; while(i < n) { cur = c[i++]; if(drawn < cur) { result = 0; break; } drawn++; result *= (drawn - cur); result %= MOD; } cout << result << endl; } return 0; } //https://www.hackerrank.com/challenges/picking-cards/problem
19.837838
61
0.416894
[ "vector" ]
ad3ea9ed07483c87526aa343d230c529dffa7915
4,728
cpp
C++
main.cpp
mbartling/tflm-flat-buffer-weight-dumper
b0d5fff17b15217095078499d56e5f1e793e0be9
[ "Apache-2.0" ]
null
null
null
main.cpp
mbartling/tflm-flat-buffer-weight-dumper
b0d5fff17b15217095078499d56e5f1e793e0be9
[ "Apache-2.0" ]
null
null
null
main.cpp
mbartling/tflm-flat-buffer-weight-dumper
b0d5fff17b15217095078499d56e5f1e793e0be9
[ "Apache-2.0" ]
null
null
null
// Dont just my gross hacky code #include <iostream> #include <fstream> #include <vector> #include <cassert> #include "tensorflow/lite/experimental/micro/kernels/all_ops_resolver.h" #include "tensorflow/lite/experimental/micro/micro_error_reporter.h" #include "tensorflow/lite/experimental/micro/micro_interpreter.h" #include "tensorflow/lite/schema/schema_generated.h" #include "tensorflow/lite/version.h" #include "tensorflow/lite/kernels/internal/tensor_ctypes.h" #include "tensorflow/lite/core/api/flatbuffer_conversions.h" #include "tensorflow/lite/schema/schema_generated.h" using namespace std; template<typename T> void dump_data(T* data, int len){ // Eww // Only print out linear representation cuz that's all I need cout << "~~~[" << endl; for(int i = 0; i < len; i++) cout << data[i] << endl; cout << "~~~]" << endl; } void DumpWeights(const tflite::Tensor* tensor, const flatbuffers::Vector<flatbuffers::Offset<tflite::Buffer>>* flat_buffers){ void* tensor_data = nullptr; int numElems = 0; //if (auto* buffer = tensor->buffer()) { if (auto* buffer = (*flat_buffers)[tensor->buffer()]) { if (auto* array = buffer->data()) { if (numElems = array->size()) { cerr << numElems << endl; tensor_data = const_cast<char*>(reinterpret_cast<const char*>(array->data())); } } } if(tensor_data == nullptr) return; switch (tensor->type()){ case tflite::TensorType_FLOAT32: { auto* data1 = reinterpret_cast<float*>(tensor_data); dump_data(data1, numElems/sizeof(float)); break; } case tflite::TensorType_INT32: { auto* data2 = reinterpret_cast<int32_t*>(tensor_data); dump_data(data2, numElems/sizeof(int32_t)); break; } case tflite::TensorType_UINT8: { auto* data3 = reinterpret_cast<uint8_t*>(tensor_data); cout << hex; dump_data(data3, numElems); cout << dec; break; } case tflite::TensorType_INT64: { auto* data4 = reinterpret_cast<int64_t*>(tensor_data); dump_data(data4, numElems/sizeof(int64_t)); break; } case tflite::TensorType_INT16: { auto* data5 = reinterpret_cast<int16_t*>(tensor_data); dump_data(data5, numElems/sizeof(int16_t)); break; } case tflite::TensorType_INT8: { cout << hex; auto* data6 = reinterpret_cast<int8_t*>(tensor_data); cout << dec; dump_data(data6, numElems); break; } } }; int main(int argc, char* argv[]) { // Set up logging. tflite::MicroErrorReporter micro_error_reporter; tflite::ErrorReporter* error_reporter = &micro_error_reporter; assert(argc == 2); const char* tfile = argv[1]; cerr << tfile << endl; // Read toco flatbuffer into mem std::ifstream file(tfile, std::ios::binary | std::ios::ate); std::streamsize size = file.tellg(); file.seekg(0, std::ios::beg); std::vector<char> buffer(size); if (file.read(buffer.data(), size)) { /* worked! */ } // Map the model into a usable data structure. This doesn't involve any // copying or parsing, it's a very lightweight operation. const tflite::Model* model = ::tflite::GetModel(buffer.data()); if (model->version() != TFLITE_SCHEMA_VERSION) { error_reporter->Report( "Model provided is schema version %d not equal " "to supported version %d.\n", model->version(), TFLITE_SCHEMA_VERSION); return 1; } const flatbuffers::Vector<flatbuffers::Offset<tflite::Buffer>>* buffers = model->buffers(); auto* subgraphs = model->subgraphs(); if (subgraphs->size() != 1) { error_reporter->Report("Only 1 subgraph is currently supported.\n"); return -1; } auto subgraph_ = (*subgraphs)[0]; auto tensors_ = subgraph_->tensors(); // for (int i = 0; i < subgraph_->inputs()->Length(); ++i) { // const int tensor_index = subgraph_->inputs()->Get(i); // const auto* tensor = tensors_->Get(tensor_index); // DumpWeights(tensor, buffers); // } for (int i = 0; i < tensors_->Length(); ++i) { const auto* tensor = tensors_->Get(i); DumpWeights(tensor, buffers); } return 0; }
32.163265
84
0.571701
[ "vector", "model" ]
ad480e3ff5ab2deae3679e092b09bd33fa8bea3b
7,414
cpp
C++
WickedEngine/Matrix_BindLua.cpp
sadernalwis/WickedEngine
a1924cc97d36d0dac5e405f4197a9b1e982b2740
[ "WTFPL", "MIT" ]
3,589
2015-06-20T23:08:26.000Z
2022-03-31T13:45:07.000Z
WickedEngine/Matrix_BindLua.cpp
sadernalwis/WickedEngine
a1924cc97d36d0dac5e405f4197a9b1e982b2740
[ "WTFPL", "MIT" ]
303
2015-11-23T18:23:59.000Z
2022-03-31T09:31:03.000Z
WickedEngine/Matrix_BindLua.cpp
sadernalwis/WickedEngine
a1924cc97d36d0dac5e405f4197a9b1e982b2740
[ "WTFPL", "MIT" ]
496
2015-06-22T18:14:06.000Z
2022-03-30T21:53:21.000Z
#include "Matrix_BindLua.h" #include "Vector_BindLua.h" using namespace DirectX; const char Matrix_BindLua::className[] = "Matrix"; Luna<Matrix_BindLua>::FunctionType Matrix_BindLua::methods[] = { lunamethod(Matrix_BindLua, GetRow), lunamethod(Matrix_BindLua, Translation), lunamethod(Matrix_BindLua, Rotation), lunamethod(Matrix_BindLua, RotationX), lunamethod(Matrix_BindLua, RotationY), lunamethod(Matrix_BindLua, RotationZ), lunamethod(Matrix_BindLua, RotationQuaternion), lunamethod(Matrix_BindLua, Scale), lunamethod(Matrix_BindLua, LookTo), lunamethod(Matrix_BindLua, LookAt), lunamethod(Matrix_BindLua, Add), lunamethod(Matrix_BindLua, Multiply), lunamethod(Matrix_BindLua, Transpose), lunamethod(Matrix_BindLua, Inverse), { NULL, NULL } }; Luna<Matrix_BindLua>::PropertyType Matrix_BindLua::properties[] = { { NULL, NULL } }; Matrix_BindLua::Matrix_BindLua(const XMMATRIX& matrix) :matrix(matrix) { } Matrix_BindLua::Matrix_BindLua(lua_State* L) { matrix = XMMatrixIdentity(); int argc = wiLua::SGetArgCount(L); // fill out all the four rows of the matrix for (int i = 0; i < 4; ++i) { float x = 0.f, y = 0.f, z = 0.f, w = 0.f; if (argc > i * 4) { x = wiLua::SGetFloat(L, i * 4 + 1); if (argc > i * 4 + 1) { y = wiLua::SGetFloat(L, i * 4 + 2); if (argc > i * 4 + 2) { z = wiLua::SGetFloat(L, i * 4 + 3); if (argc > i * 4 + 3) { w = wiLua::SGetFloat(L, i * 4 + 4); } } } } matrix.r[i] = XMVectorSet(x, y, z, w); } } int Matrix_BindLua::GetRow(lua_State* L) { int argc = wiLua::SGetArgCount(L); int row = 0; if (argc > 1) { row = wiLua::SGetInt(L, 2); if (row < 0 || row > 3) row = 0; } Luna<Vector_BindLua>::push(L, new Vector_BindLua(matrix.r[row])); return 1; } int Matrix_BindLua::Translation(lua_State* L) { int argc = wiLua::SGetArgCount(L); XMMATRIX mat = XMMatrixIdentity(); if (argc > 0) { Vector_BindLua* vector = Luna<Vector_BindLua>::lightcheck(L, 1); if (vector != nullptr) { mat = XMMatrixTranslationFromVector(vector->vector); } } Luna<Matrix_BindLua>::push(L, new Matrix_BindLua(mat)); return 1; } int Matrix_BindLua::Rotation(lua_State* L) { int argc = wiLua::SGetArgCount(L); XMMATRIX mat = XMMatrixIdentity(); if (argc > 0) { Vector_BindLua* vector = Luna<Vector_BindLua>::lightcheck(L, 1); if (vector != nullptr) { mat = XMMatrixRotationRollPitchYawFromVector(vector->vector); } } Luna<Matrix_BindLua>::push(L, new Matrix_BindLua(mat)); return 1; } int Matrix_BindLua::RotationX(lua_State* L) { int argc = wiLua::SGetArgCount(L); XMMATRIX mat = XMMatrixIdentity(); if (argc > 0) { mat = XMMatrixRotationX(wiLua::SGetFloat(L, 1)); } Luna<Matrix_BindLua>::push(L, new Matrix_BindLua(mat)); return 1; } int Matrix_BindLua::RotationY(lua_State* L) { int argc = wiLua::SGetArgCount(L); XMMATRIX mat = XMMatrixIdentity(); if (argc > 0) { mat = XMMatrixRotationY(wiLua::SGetFloat(L, 1)); } Luna<Matrix_BindLua>::push(L, new Matrix_BindLua(mat)); return 1; } int Matrix_BindLua::RotationZ(lua_State* L) { int argc = wiLua::SGetArgCount(L); XMMATRIX mat = XMMatrixIdentity(); if (argc > 0) { mat = XMMatrixRotationZ(wiLua::SGetFloat(L, 1)); } Luna<Matrix_BindLua>::push(L, new Matrix_BindLua(mat)); return 1; } int Matrix_BindLua::RotationQuaternion(lua_State* L) { int argc = wiLua::SGetArgCount(L); XMMATRIX mat = XMMatrixIdentity(); if (argc > 0) { Vector_BindLua* vector = Luna<Vector_BindLua>::lightcheck(L, 1); if (vector != nullptr) { mat = XMMatrixRotationQuaternion(vector->vector); } } Luna<Matrix_BindLua>::push(L, new Matrix_BindLua(mat)); return 1; } int Matrix_BindLua::Scale(lua_State* L) { int argc = wiLua::SGetArgCount(L); XMMATRIX mat = XMMatrixIdentity(); if (argc > 0) { Vector_BindLua* vector = Luna<Vector_BindLua>::lightcheck(L, 1); if (vector != nullptr) { mat = XMMatrixScalingFromVector(vector->vector); } } Luna<Matrix_BindLua>::push(L, new Matrix_BindLua(mat)); return 1; } int Matrix_BindLua::LookTo(lua_State* L) { int argc = wiLua::SGetArgCount(L); if (argc > 1) { Vector_BindLua* pos = Luna<Vector_BindLua>::lightcheck(L, 1); Vector_BindLua* dir = Luna<Vector_BindLua>::lightcheck(L, 2); if (pos != nullptr && dir != nullptr) { XMVECTOR Up; if (argc > 3) { Vector_BindLua* up = Luna<Vector_BindLua>::lightcheck(L, 3); Up = up->vector; } else Up = XMVectorSet(0, 1, 0, 0); Luna<Matrix_BindLua>::push(L, new Matrix_BindLua(XMMatrixLookToLH(pos->vector, dir->vector, Up))); } else wiLua::SError(L, "LookTo(Vector eye, Vector direction, opt Vector up) argument is not a Vector!"); } else wiLua::SError(L, "LookTo(Vector eye, Vector direction, opt Vector up) not enough arguments!"); return 1; } int Matrix_BindLua::LookAt(lua_State* L) { int argc = wiLua::SGetArgCount(L); if (argc > 1) { Vector_BindLua* pos = Luna<Vector_BindLua>::lightcheck(L, 1); Vector_BindLua* dir = Luna<Vector_BindLua>::lightcheck(L, 2); if (dir != nullptr) { XMVECTOR Up; if (argc > 3) { Vector_BindLua* up = Luna<Vector_BindLua>::lightcheck(L, 3); Up = up->vector; } else Up = XMVectorSet(0, 1, 0, 0); Luna<Matrix_BindLua>::push(L, new Matrix_BindLua(XMMatrixLookAtLH(pos->vector, dir->vector, Up))); } else wiLua::SError(L, "LookAt(Vector eye, Vector focusPos, opt Vector up) argument is not a Vector!"); } else wiLua::SError(L, "LookAt(Vector eye, Vector focusPos, opt Vector up) not enough arguments!"); return 1; } int Matrix_BindLua::Multiply(lua_State* L) { int argc = wiLua::SGetArgCount(L); if (argc > 1) { Matrix_BindLua* m1 = Luna<Matrix_BindLua>::lightcheck(L, 1); Matrix_BindLua* m2 = Luna<Matrix_BindLua>::lightcheck(L, 2); if (m1 && m2) { Luna<Matrix_BindLua>::push(L, new Matrix_BindLua(XMMatrixMultiply(m1->matrix, m2->matrix))); return 1; } } wiLua::SError(L, "Multiply(Matrix m1,m2) not enough arguments!"); return 0; } int Matrix_BindLua::Add(lua_State* L) { int argc = wiLua::SGetArgCount(L); if (argc > 1) { Matrix_BindLua* m1 = Luna<Matrix_BindLua>::lightcheck(L, 1); Matrix_BindLua* m2 = Luna<Matrix_BindLua>::lightcheck(L, 2); if (m1 && m2) { Luna<Matrix_BindLua>::push(L, new Matrix_BindLua(m1->matrix + m2->matrix)); return 1; } } wiLua::SError(L, "Add(Matrix m1,m2) not enough arguments!"); return 0; } int Matrix_BindLua::Transpose(lua_State* L) { int argc = wiLua::SGetArgCount(L); if (argc > 0) { Matrix_BindLua* m1 = Luna<Matrix_BindLua>::lightcheck(L, 1); if (m1) { Luna<Matrix_BindLua>::push(L, new Matrix_BindLua(XMMatrixTranspose(m1->matrix))); return 1; } } wiLua::SError(L, "Transpose(Matrix m) not enough arguments!"); return 0; } int Matrix_BindLua::Inverse(lua_State* L) { int argc = wiLua::SGetArgCount(L); if (argc > 0) { Matrix_BindLua* m1 = Luna<Matrix_BindLua>::lightcheck(L, 1); if (m1) { XMVECTOR det; Luna<Matrix_BindLua>::push(L, new Matrix_BindLua(XMMatrixInverse(&det, m1->matrix))); wiLua::SSetFloat(L, XMVectorGetX(det)); return 2; } } wiLua::SError(L, "Inverse(Matrix m) not enough arguments!"); return 0; } void Matrix_BindLua::Bind() { static bool initialized = false; if (!initialized) { initialized = true; Luna<Matrix_BindLua>::Register(wiLua::GetLuaState()); wiLua::RunText("matrix = Matrix()"); } }
23.762821
101
0.672377
[ "vector" ]
ad484901461c3e825990c02adc0437db78171f34
15,888
cpp
C++
render/shader.cpp
vasukas/rodent
91224465eaa89467916971a8c5ed1357fa487bdf
[ "FTL", "CC0-1.0", "CC-BY-4.0", "MIT" ]
null
null
null
render/shader.cpp
vasukas/rodent
91224465eaa89467916971a8c5ed1357fa487bdf
[ "FTL", "CC0-1.0", "CC-BY-4.0", "MIT" ]
null
null
null
render/shader.cpp
vasukas/rodent
91224465eaa89467916971a8c5ed1357fa487bdf
[ "FTL", "CC0-1.0", "CC-BY-4.0", "MIT" ]
null
null
null
#include "core/hard_paths.hpp" #include "vaslib/vas_cpp_utils.hpp" #include "vaslib/vas_file.hpp" #include "vaslib/vas_log.hpp" #include "vaslib/vas_misc.hpp" #include "vaslib/vas_string_utils.hpp" #include "shader.hpp" /* Format directives: //@vert [NAME] // begins new block or includes existing (vertex shader) //@frag [NAME] // begins new block or includes existing (fragment shader) //@geom [NAME] // begins new block or includes existing (geometry shader) //@end // ends block //@def <NAME> <DEF_VALUE> // declares parameter */ struct SingleShader { std::string fname; ///< file name (without res path) GLenum type; std::string full_name; ///< name:type std::string src_version; ///< #version std::string src_code; std::vector<Shader::Define> defs; }; static std::vector<SingleShader> sh_col; template<typename T, typename R> bool begins_with(const T& s, const R& pref) { return !s.compare(0, pref.length(), pref); } template<typename T> bool begins_with(const T& s, const char *pref) { return !s.compare(0, strlen(pref), pref); } struct PrefAssoc { GLenum type; std::string pref; std::string name; }; static const std::vector<PrefAssoc> pref_assoc = { {GL_VERTEX_SHADER, "//@vert", "vert"}, {GL_FRAGMENT_SHADER, "//@frag", "frag"}, {GL_GEOMETRY_SHADER, "//@geom", "geom"} }; static std::optional<SingleShader> read_shader(const std::vector<std::string_view>& lines, size_t& i, const std::string& full_name) { // i ->: first line of block (excluding header) // i <-: first line after block (excluding @end) SingleShader sh; for (; i < lines.size(); ++i) { auto& ln = lines[i]; if (begins_with(ln, "//@end")) { ++i; break; } else if (begins_with(ln, "//@def")) { reserve_more_block(sh.defs, 16); auto args = string_split_view(ln, {" "}); if (args.size() != 3) { VLOGE("Shader:: invalid 'define' directive; '{}' (line {})", full_name, i+1); return {}; } auto& d = sh.defs.emplace_back(); d.name = args[1]; d.value = args[2]; } else if (begins_with(ln, "//@")) { bool ok = false; for (auto& p : pref_assoc) { if (begins_with(ln, p.pref)) { ok = true; break; } } if (ok) break; VLOGE("Shader:: inappropriate directive; '{}' (line {})", full_name, i+1); return {}; } else if (begins_with(ln, "#version")) { sh.src_version = ln; sh.src_version += '\n'; } else { reserve_more_block(sh.src_code, 4096); sh.src_code += ln; sh.src_code += '\n'; } } if (sh.src_version.empty()) { VLOGE("Shader:: no '#version' directive; '{}'", full_name); return {}; } return sh; } static std::optional<size_t> get_shd_existing(GLenum type, const std::string& fname) { for (size_t i = 0; i < sh_col.size(); ++i) { auto& s = sh_col[i]; if (s.type == type && s.fname == fname) return i; } return {}; } static std::optional<size_t> get_shd(GLenum type, const std::string& fname) { // search loaded if (auto i = get_shd_existing(type, fname)) return i; // get pref & make name std::string_view pref; std::string full_name = fname; full_name += ':'; for (auto& p : pref_assoc) { if (p.type == type) { pref = p.pref; full_name += p.name; break; } } if (pref.empty()) { VLOGE("Shader:: no directive for shader type {}; '{}'", type, fname); return {}; } // read file auto file_opt = readfile( (std::string(HARDPATH_SHADER_PREFIX) + fname).data() ); if (!file_opt) { VLOGE("Shader:: can't read shader \"{}\"; '{}'", fname, full_name); return {}; } const std::string& file = *file_opt; auto lines = string_split_view(file, {"\n"}, false); // find block size_t i = 0; for (; i < lines.size(); ++i) { auto& ln = lines[i]; if (begins_with(ln, pref)) { auto args = string_split_view(ln, {" "}); if (args.size() != 1) { VLOGE("Shader:: inappropriate block directive; '{}' (line {})", full_name, i+1); return {}; } break; } } if (i == lines.size()) { VLOGE("Shader:: block directive not found; '{}'", full_name); return {}; } // read block ++i; auto sh = read_shader(lines, i, full_name); if (!sh) return {}; sh->fname = fname; sh->type = type; sh->full_name = std::move(full_name); sh_col.emplace_back( std::move(*sh) ); return sh_col.size() - 1; } static std::vector<Shader*> all_shader_ptr; ptr_range<Shader*> Shader::get_all_ptrs() { return all_shader_ptr; } std::unique_ptr<Shader> Shader::load(const char *name, Callbacks cbs, bool is_critical, bool do_build) { std::unique_ptr<Shader> s(new Shader); all_shader_ptr.push_back(s.get()); s->cbs = std::move(cbs); s->is_critical = is_critical; s->prog_name = name; if (s->reload() && do_build) s->rebuild(); return s; } Shader::~Shader() { reset_prog(); auto it = std::find(all_shader_ptr.begin(), all_shader_ptr.end(), this); if (it != all_shader_ptr.end()) all_shader_ptr.erase(it); } Shader::Define* Shader::get_def(std::string_view name) { for (auto& d : def_list) { if (d.name == name) return &d; } return nullptr; } void Shader::set_def(std::string_view name, std::string value) { auto d = get_def(name); if (d) { d->value = std::move(value); reset_prog(); } else VLOGD("Shader::set_def() no '{}' in '{}'", name, prog_name); } bool Shader::reload() { bool was_built = (prog != 0); // read file auto file_opt = readfile( (std::string(HARDPATH_SHADER_PREFIX) + prog_name).data() ); if (!file_opt) { VLOGE("Shader::reload() can't read file; '{}'", prog_name); return false; } const std::string& file = *file_opt; auto lines = string_split_view(file, {"\n"}, false); // clear src_ixs.clear(); reset_prog(); // parse file for (size_t i=0; i < lines.size(); ++i) { auto& ln = lines[i]; if (begins_with(ln, "//@")) { GLenum type = 0; std::string full_name = prog_name; for (auto& p : pref_assoc) { if (begins_with(ln, p.pref)) { type = p.type; full_name += ':'; full_name += p.name; break; } } if (!type) { VLOGE("Shader::reload() inappropriate directive; '{}' (line {})", prog_name, i+1); return false; } auto args = string_split_view(ln, {" "}); if (args.size() == 1) { ++i; auto sh = read_shader(lines, i, full_name); if (!sh) { VLOGE("Shader::reload() can't load shader; '{}' (line {})", full_name, i+1); return false; } --i; sh->fname = prog_name; sh->type = type; sh->full_name = std::move(full_name); // auto i_src = get_shd_existing(sh->type, prog_name); if (i_src) sh_col[*i_src] = std::move(*sh); else { i_src = sh_col.size(); sh_col.emplace_back(std::move(*sh)); } src_ixs.push_back(*i_src); } else if (args.size() == 2) { auto sh = get_shd(type, std::string(args[1])); if (!sh) { VLOGE("Shader::reload() can't find or load shader; '{}' (line {})", full_name, i+1); return false; } src_ixs.push_back(*sh); } else { VLOGE("Shader::reload() inappropriate 'shader' directive; '{}' (line {})", prog_name, i+1); return false; } } else if (!begins_with(ln, "//")) { for (auto& c : ln) { if (c != ' ' && c != '\t') { VLOGE("Shader::reload() code outside of block; '{}' (line {})", prog_name, i+1); return false; } } } } // check shader types int n_vert = 0; int n_frag = 0; int n_geom = 0; int n_unk = 0; for (auto& i_src : src_ixs) { auto& s = sh_col[i_src]; switch (s.type) { case GL_VERTEX_SHADER: ++n_vert; break; case GL_FRAGMENT_SHADER: ++n_frag; break; case GL_GEOMETRY_SHADER: ++n_geom; break; default: ++n_unk; break; } } if (n_vert > 1 || n_frag > 1 || n_geom > 1) { std::string ls; for (auto& i_src : src_ixs) {ls += " "; ls += sh_col[i_src].full_name;} VLOGE("Shader::reload() more than one shader of same type found; '{}':\n{}", prog_name, ls); } if (n_unk) VLOGW("Shader::reload() {} unknown shader types in '{}'", n_unk, prog_name); if (src_ixs.empty()) VLOGE("Shader::reload() no shaders in '{}'", prog_name); else { if (!n_vert) VLOGW("Shader::reload() no vertex shader in '{}'", prog_name); if (!n_frag) VLOGW("Shader::reload() no fragment shader in '{}'", prog_name); } // update defines auto old_defs = std::move(def_list); def_list.clear(); for (auto& i_src : src_ixs) { auto& s = sh_col[i_src]; for (auto& new_d : s.defs) { bool skip = false; for (auto& d : def_list) { if (d.name == new_d.name) { if (d.value != new_d.value) VLOGW("Shader::reload() define declared multiple times with different value (first one is used) - '{}' in '{}'", d.name, prog_name); skip = true; break; } } if (skip) continue; // auto& nd = def_list.emplace_back(); nd = new_d; // check if had non-default value Define* d_old = {}; for (auto& d : old_defs) { if (d.name == new_d.name) { d_old = &d; break; } } if (d_old && !d_old->is_default) { nd.value = std::move(d_old->value); nd.is_default = false; } } } // // VLOGV("Shader::reload() ok - {}", name); return was_built? rebuild() : true; } bool Shader::rebuild(bool forced) { if (prog && !forced) return true; never_built = false; reset_prog(); if (src_ixs.empty()) return false; if (cbs.pre_build) cbs.pre_build(*this); // get defines const GLchar* src_s[3]; GLint src_n[3]; std::string def_str; def_str.reserve(512); for (auto& d : def_list) def_str += FMT_FORMAT("#define {} {}\n", d.name, d.value); src_s[1] = def_str.data(); src_n[1] = def_str.length(); // raii bool did_fail = true; std::vector<GLuint> shs; RAII_Guard g([&] { for (auto& s : shs) glDeleteShader(s); if (did_fail) { VLOGE("Shader::rebuild() failed - [] {}", prog_name); reset_prog(); } }); // compile for (auto& i_src : src_ixs) { auto& src = sh_col[i_src]; src_s[0] = src.src_version.data(); src_n[0] = src.src_version.length(); src_s[2] = src.src_code.data(); src_n[2] = src.src_code.length(); GLuint& sh = shs.emplace_back(); sh = glCreateShader(src.type); glShaderSource(sh, 3, src_s, src_n); glCompileShader(sh); GLint err = 0; glGetShaderiv(sh, GL_COMPILE_STATUS, &err); if (err == GL_FALSE) { GLint str_n = 0; glGetShaderiv(sh, GL_INFO_LOG_LENGTH, &str_n); char *str = new char [str_n]; GLsizei len = 0; glGetShaderInfoLog(sh, str_n, &len, str); VLOGE("Shader:: compilation of '{}' failed:\n{}\nEND\n", src.full_name, std::string_view(str, len)); delete[] str; return false; } if (log_test_level(LogLevel::Verbose)) { GLint str_n = 0; glGetShaderiv(sh, GL_INFO_LOG_LENGTH, &str_n); if (str_n > 3) // just newline { char *str = new char [str_n]; GLsizei len = 0; glGetShaderInfoLog(sh, str_n, &len, str); VLOGE("Shader::rebuild() compilation info for '{}' in {}:\n{}\nEND\n", src.full_name, prog_name, std::string_view(str, len)); delete[] str; } } } // link prog = glCreateProgram(); for (auto& s : shs) glAttachShader(prog, s); if (cbs.pre_link) cbs.pre_link(*this); glLinkProgram(prog); GLint err; glGetProgramiv(prog, GL_LINK_STATUS, &err); if (err == GL_FALSE) { GLint str_n = 0; glGetProgramiv(prog, GL_INFO_LOG_LENGTH, &str_n); char *str = new char [str_n]; GLsizei len = 0; glGetProgramInfoLog(prog, str_n, &len, str); VLOGE("Shader:: link failed:\n{}\nEND\n", std::string_view(str, len)); delete[] str; return false; } if (log_test_level(LogLevel::Verbose)) { GLint str_n = 0; glGetProgramiv(prog, GL_INFO_LOG_LENGTH, &str_n); if (str_n) { char *str = new char [str_n]; GLsizei len = 0; glGetProgramInfoLog(prog, str_n, &len, str); VLOGV("Shader::rebuild() link info for [{}] {}:\n{}\nEND\n", prog, prog_name, std::string_view(str, len)); delete[] str; } } for (auto &s : shs) glDetachShader(prog, s); // finished VLOGD("Shader::rebuild() ok - [{}] {}", prog, prog_name); did_fail = false; if (cbs.post_build) { glUseProgram(prog); cbs.post_build(*this); } validate = true; return true; } void Shader::bind() { if (!prog) { if (!rebuild()) LOG_THROW("Shader::bind() can't build: {}", prog_name); } if (validate) { validate = false; glValidateProgram(prog); GLint err; glGetProgramiv(prog, GL_VALIDATE_STATUS, &err); if (err == GL_TRUE) VLOGV("Validation ok: [{}] {}", prog, prog_name); else { VLOGW("Validation failed: [{}] {}", prog, prog_name); GLint str_n = 0; glGetProgramiv(prog, GL_INFO_LOG_LENGTH, &str_n); if (str_n) { char *str = new char [str_n]; GLsizei len = 0; glGetProgramInfoLog(prog, str_n, &len, str); VLOGW("Shader:: validation:\n{}\nEND\n", std::string_view(str, len)); delete[] str; } } no_such_loc.clear(); } glUseProgram(prog); } void Shader::reset_prog() { glDeleteProgram(prog); prog = 0; } GLint Shader::find_loc( const char *name ) { GLint loc = glGetUniformLocation(prog, name); if (loc < 0) { auto h = fast_hash32(name); if (no_such_loc.end() == std::find( no_such_loc.begin(), no_such_loc.end(), h )) { no_such_loc.push_back(h); VLOGW("Shader::find_loc() no '{}' in '{}'", name, prog_name); } } return loc; } void Shader::set1i(int loc, int v) { glUniform1i(loc, v); } void Shader::set1f(int loc, float v) { glUniform1f(loc, v); } void Shader::set2f(int loc, float a, float b) { glUniform2f(loc, a, b); } void Shader::set3f(int loc, float x, float y, float z) { glUniform3f(loc, x, y, z); } void Shader::set4f(int loc, float r, float g, float b, float a) { glUniform4f(loc, r, g, b, a); } void Shader::setfv(int loc, const float *v, int n) { glUniform1fv(loc, n, v); } void Shader::set2mx(int loc, const float *v, bool transp) { glUniformMatrix2fv(loc, 1, transp, v); } void Shader::set3mx(int loc, const float *v, bool transp) { glUniformMatrix3fv(loc, 1, transp, v); } void Shader::set4mx(int loc, const float *v, bool transp) { glUniformMatrix4fv(loc, 1, transp, v); } void Shader::set_rgba(int loc, uint32_t clr, float mul) { mul /= 255.f; glUniform4f(loc, mul * (clr >> 24), mul * ((clr >> 16) & 0xff), mul * ((clr >> 8) & 0xff), (clr & 0xff) / 255.f); } void Shader::set_clr(int loc, const FColor& clr) { glUniform4f(loc, clr.r, clr.g, clr.b, clr.a); } void Shader::set2f(int loc, const vec2fp& p) { glUniform2f(loc, p.x, p.y); } void Shader::set1i(const char *name, int v) { set1i( find_loc(name), v ); } void Shader::set1f(const char *name, float v) { set1f( find_loc(name), v ); } void Shader::set2f(const char *name, float a, float b) { set2f( find_loc(name), a, b ); } void Shader::set3f(const char *name, float x, float y, float z) { set3f( find_loc(name), x, y, z ); } void Shader::set4f(const char *name, float r, float g, float b, float a) { set4f( find_loc(name), r, g, b, a ); } void Shader::setfv(const char *name, const float *v, int n) { setfv( find_loc(name), v, n ); } void Shader::set2mx(const char *name, const float *v, bool transp) { set2mx( find_loc(name), v, transp ); } void Shader::set3mx(const char *name, const float *v, bool transp) { set3mx( find_loc(name), v, transp ); } void Shader::set4mx(const char *name, const float *v, bool transp) { set4mx( find_loc(name), v, transp ); } void Shader::set_rgba(const char *name, uint32_t clr, float mul) { set_rgba( find_loc(name), clr, mul ); } void Shader::set_clr(const char *name, const FColor& clr) { set_clr( find_loc(name), clr ); } void Shader::set2f(const char *name, const vec2fp& p) { set2f( find_loc(name), p ); }
21.704918
131
0.604481
[ "geometry", "vector" ]
ad534909408596c9b991012bdf76ccdd05261191
11,369
cc
C++
chrome/browser/ash/web_applications/camera_app/chrome_camera_app_ui_delegate.cc
Yannic/chromium
ab32e8aacb08c9fce0dc4bf09eec456ba46e3710
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
chrome/browser/ash/web_applications/camera_app/chrome_camera_app_ui_delegate.cc
Yannic/chromium
ab32e8aacb08c9fce0dc4bf09eec456ba46e3710
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2019-03-13T10:32:53.000Z
2019-03-13T11:05:30.000Z
chrome/browser/ash/web_applications/camera_app/chrome_camera_app_ui_delegate.cc
Yannic/chromium
ab32e8aacb08c9fce0dc4bf09eec456ba46e3710
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
// Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ash/web_applications/camera_app/chrome_camera_app_ui_delegate.h" #include <vector> #include "ash/constants/devicetype.h" #include "ash/public/cpp/tablet_mode.h" #include "ash/webui/camera_app_ui/url_constants.h" #include "base/files/file_path.h" #include "base/files/file_util.h" #include "base/logging.h" #include "base/system/sys_info.h" #include "base/task/bind_post_task.h" #include "base/task/sequenced_task_runner.h" #include "base/task/task_traits.h" #include "base/task/thread_pool.h" #include "chrome/browser/apps/app_service/app_service_proxy.h" #include "chrome/browser/apps/app_service/app_service_proxy_factory.h" #include "chrome/browser/apps/app_service/launch_utils.h" #include "chrome/browser/ash/file_manager/path_util.h" // TODO(b/174811949): Hide behind ChromeOS build flag. #include "chrome/browser/ash/web_applications/camera_app/chrome_camera_app_ui_constants.h" #include "chrome/browser/devtools/devtools_window.h" #include "chrome/browser/media/webrtc/media_capture_devices_dispatcher.h" #include "chrome/browser/metrics/chrome_metrics_service_accessor.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/chrome_pages.h" #include "chrome/browser/ui/web_applications/system_web_app_ui_utils.h" #include "chrome/browser/web_applications/web_app_id_constants.h" #include "chrome/browser/web_applications/web_app_tab_helper.h" #include "chrome/browser/web_launch/web_launch_files_helper.h" #include "components/services/app_service/public/mojom/types.mojom.h" #include "content/public/browser/render_frame_host.h" #include "content/public/browser/web_contents.h" #include "content/public/browser/web_ui_data_source.h" #include "third_party/blink/public/mojom/mediastream/media_stream.mojom.h" #include "ui/gfx/native_widget_types.h" #include "url/gurl.h" namespace { std::string DeviceTypeToString(chromeos::DeviceType device_type) { switch (device_type) { case chromeos::DeviceType::kChromebase: return "chromebase"; case chromeos::DeviceType::kChromebit: return "chromebit"; case chromeos::DeviceType::kChromebook: return "chromebook"; case chromeos::DeviceType::kChromebox: return "chromebox"; case chromeos::DeviceType::kUnknown: default: return "unknown"; } } } // namespace // static void ChromeCameraAppUIDelegate::CameraAppDialog::ShowIntent( const std::string& queries, gfx::NativeWindow parent) { std::string url = chromeos::kChromeUICameraAppMainURL + queries; CameraAppDialog* dialog = new CameraAppDialog(url); dialog->ShowSystemDialog(parent); } ChromeCameraAppUIDelegate::CameraAppDialog::CameraAppDialog( const std::string& url) : chromeos::SystemWebDialogDelegate(GURL(url), /*title=*/std::u16string()) {} ChromeCameraAppUIDelegate::CameraAppDialog::~CameraAppDialog() {} ui::ModalType ChromeCameraAppUIDelegate::CameraAppDialog::GetDialogModalType() const { return ui::MODAL_TYPE_WINDOW; } bool ChromeCameraAppUIDelegate::CameraAppDialog::CanMaximizeDialog() const { return !ash::TabletMode::Get()->InTabletMode(); } void ChromeCameraAppUIDelegate::CameraAppDialog::GetDialogSize( gfx::Size* size) const { size->SetSize(kChromeCameraAppDefaultWidth, kChromeCameraAppDefaultHeight); } void ChromeCameraAppUIDelegate::CameraAppDialog::RequestMediaAccessPermission( content::WebContents* web_contents, const content::MediaStreamRequest& request, content::MediaResponseCallback callback) { MediaCaptureDevicesDispatcher::GetInstance()->ProcessMediaAccessRequest( web_contents, request, std::move(callback), /* extension */ nullptr); } bool ChromeCameraAppUIDelegate::CameraAppDialog::CheckMediaAccessPermission( content::RenderFrameHost* render_frame_host, const GURL& security_origin, blink::mojom::MediaStreamType type) { return MediaCaptureDevicesDispatcher::GetInstance() ->CheckMediaAccessPermission(render_frame_host, security_origin, type); } ChromeCameraAppUIDelegate::FileMonitor::FileMonitor() {} ChromeCameraAppUIDelegate::FileMonitor::~FileMonitor() = default; void ChromeCameraAppUIDelegate::FileMonitor::Monitor( const base::FilePath& file_path, base::OnceCallback<void(FileMonitorResult)> callback) { // Cancel the previous monitor callback if it hasn't been notified. if (!callback_.is_null()) { std::move(callback_).Run(FileMonitorResult::CANCELED); } // There is chance that the file is deleted during the task is scheduled and // executed. Therefore, check here before watching it. if (!base::PathExists(file_path)) { std::move(callback).Run(FileMonitorResult::DELETED); return; } callback_ = std::move(callback); file_watcher_ = std::make_unique<base::FilePathWatcher>(); if (!file_watcher_->Watch( file_path, base::FilePathWatcher::Type::kNonRecursive, base::BindRepeating( &ChromeCameraAppUIDelegate::FileMonitor::OnFileDeletion, base::Unretained(this)))) { std::move(callback_).Run(FileMonitorResult::ERROR); } } void ChromeCameraAppUIDelegate::FileMonitor::OnFileDeletion( const base::FilePath& path, bool error) { if (callback_.is_null()) { return; } if (error) { std::move(callback_).Run(FileMonitorResult::ERROR); return; } std::move(callback_).Run(FileMonitorResult::DELETED); } ChromeCameraAppUIDelegate::ChromeCameraAppUIDelegate(content::WebUI* web_ui) : web_ui_(web_ui), file_task_runner_(base::ThreadPool::CreateSequencedTaskRunner( {base::MayBlock(), base::TaskPriority::USER_VISIBLE})) { file_task_runner_->PostTask( FROM_HERE, base::BindOnce(&ChromeCameraAppUIDelegate::InitFileMonitorOnFileThread, base::Unretained(this))); } ChromeCameraAppUIDelegate::~ChromeCameraAppUIDelegate() { // Destroy |file_monitor_| on |file_task_runner_|. // TODO(wtlee): Ensure there is no lifetime issue before actually deleting it. file_task_runner_->DeleteSoon(FROM_HERE, std::move(file_monitor_)); } void ChromeCameraAppUIDelegate::SetLaunchDirectory() { Profile* profile = Profile::FromWebUI(web_ui_); content::WebContents* web_contents = web_ui_->GetWebContents(); // Since launch paths does not accept empty vector, we put a placeholder file // path in it. base::FilePath empty_file_path("/dev/null"); auto my_files_folder_path = file_manager::util::GetMyFilesFolderForProfile(profile); web_launch::WebLaunchFilesHelper::SetLaunchDirectoryAndLaunchPaths( web_contents, web_contents->GetURL(), my_files_folder_path, std::vector<base::FilePath>{empty_file_path}); web_app::WebAppTabHelper::CreateForWebContents(web_contents); } void ChromeCameraAppUIDelegate::PopulateLoadTimeData( content::WebUIDataSource* source) { // Add strings that can be pulled in. source->AddString("board_name", base::SysInfo::GetLsbReleaseBoard()); source->AddString("device_type", DeviceTypeToString(chromeos::GetDeviceType())); } bool ChromeCameraAppUIDelegate::IsMetricsAndCrashReportingEnabled() { // It is exposed for recording Google Analytics metrics. // TODO(crbug.com/1113567): Remove the method once the metrics is migrated to // UMA. return ChromeMetricsServiceAccessor::IsMetricsAndCrashReportingEnabled(); } void ChromeCameraAppUIDelegate::OpenFileInGallery(const std::string& name) { base::FilePath path = GetFilePathByName(name); if (path.empty()) { return; } web_app::SystemAppLaunchParams params; params.launch_paths = {path}; params.launch_source = apps::mojom::LaunchSource::kFromOtherApp; web_app::LaunchSystemWebAppAsync(Profile::FromWebUI(web_ui_), web_app::SystemAppType::MEDIA, params); } void ChromeCameraAppUIDelegate::OpenFeedbackDialog( const std::string& placeholder) { // TODO(crbug/1045222): Additional strings are blank right now while we decide // on the language and relevant information we want feedback to include. // Note that category_tag is the name of the listnr bucket we want our // reports to end up in. Profile* profile = Profile::FromWebUI(web_ui_); chrome::ShowFeedbackPage(GURL(chromeos::kChromeUICameraAppURL), profile, chrome::kFeedbackSourceCameraApp, std::string() /* description_template */, placeholder /* description_placeholder_text */, "chromeos-camera-app" /* category_tag */, std::string() /* extra_diagnostics */); } std::string ChromeCameraAppUIDelegate::GetFilePathInArcByName( const std::string& name) { base::FilePath path = GetFilePathByName(name); if (path.empty()) { return std::string(); } GURL arc_url_out; bool requires_sharing = false; if (!file_manager::util::ConvertPathToArcUrl(path, &arc_url_out, &requires_sharing) || !arc_url_out.is_valid()) { return std::string(); } if (requires_sharing) { LOG(ERROR) << "File path should be in MyFiles and not require any sharing"; NOTREACHED(); return std::string(); } return arc_url_out.spec(); } void ChromeCameraAppUIDelegate::OpenDevToolsWindow( content::WebContents* web_contents) { DevToolsWindow::OpenDevToolsWindow(web_contents, DevToolsToggleAction::NoOp()); } void ChromeCameraAppUIDelegate::MonitorFileDeletion( const std::string& name, base::OnceCallback<void(FileMonitorResult)> callback) { auto file_path = GetFilePathByName(name); if (file_path.empty()) { LOG(ERROR) << "Unexpected file name: " << name; std::move(callback).Run(FileMonitorResult::ERROR); return; } // We should return the response on current thread (mojo thread). auto callback_on_current_thread = base::BindPostTask( base::SequencedTaskRunnerHandle::Get(), std::move(callback), FROM_HERE); file_task_runner_->PostTask( FROM_HERE, base::BindOnce( &ChromeCameraAppUIDelegate::MonitorFileDeletionOnFileThread, base::Unretained(this), file_monitor_.get(), std::move(file_path), std::move(callback_on_current_thread))); } base::FilePath ChromeCameraAppUIDelegate::GetFilePathByName( const std::string& name) { // Check to avoid directory traversal attack. base::FilePath name_component(name); if (name_component.ReferencesParent()) return base::FilePath(); Profile* profile = Profile::FromWebUI(web_ui_); return file_manager::util::GetMyFilesFolderForProfile(profile) .Append("Camera") .Append(name_component); } void ChromeCameraAppUIDelegate::InitFileMonitorOnFileThread() { DCHECK(file_task_runner_->RunsTasksInCurrentSequence()); file_monitor_ = std::make_unique<FileMonitor>(); } void ChromeCameraAppUIDelegate::MonitorFileDeletionOnFileThread( FileMonitor* file_monitor, const base::FilePath& file_path, base::OnceCallback<void(FileMonitorResult)> callback) { DCHECK(file_task_runner_->RunsTasksInCurrentSequence()); file_monitor->Monitor(file_path, std::move(callback)); }
37.153595
90
0.735509
[ "vector" ]
ad559a4cb6d2d9415b21b4d2ceab57e223814111
6,868
cpp
C++
pythonAnimator.cpp
indigames/pyxie
4536730c73ca4fcd16b676ab5f707e6fabfdb46c
[ "MIT" ]
1
2019-09-19T01:41:54.000Z
2019-09-19T01:41:54.000Z
pythonAnimator.cpp
indigames/pyxie
4536730c73ca4fcd16b676ab5f707e6fabfdb46c
[ "MIT" ]
1
2019-09-02T04:31:13.000Z
2019-09-02T04:31:13.000Z
pythonAnimator.cpp
indigames/pyxiepython
4536730c73ca4fcd16b676ab5f707e6fabfdb46c
[ "MIT" ]
null
null
null
#include "pyxie.h" #include "pythonResource.h" #include "pyxieResourceCreator.h" #include "pythonAnimator_doc_en.h" namespace pyxie { PyObject *animator_new(PyTypeObject *type, PyObject *args, PyObject *kw) { char* path; animator_obj * self = NULL; if (PyArg_ParseTuple(args, "s", &path)) { self = (animator_obj*)type->tp_alloc(type, 0); self->anime = pyxieResourceCreator::Instance().NewAnimator(path); } return (PyObject *)self; } void animator_dealloc(animator_obj *self) { self->anime->DecReference(); Py_TYPE(self)->tp_free(self); } PyObject *animator_str(animator_obj *self) { char buf[64]; pyxie_snprintf(buf, 64, "animator object"); return _PyUnicode_FromASCII(buf, strlen(buf)); } PyObject *animator_getLooping(animator_obj *self) { return PyBool_FromLong((long)self->anime->IsLoop()); } int animator_setLooping(animator_obj *self, PyObject *value) { if (value == NULL || !PyBool_Check(value)) { PyErr_SetString(PyExc_TypeError, "loop must be set to a bool object"); return -1; } int result = PyObject_IsTrue(value); self->anime->SetLoop((bool)result); return 0; } PyObject *animator_getEvalTime(animator_obj *self) { return PyFloat_FromDouble((double)self->anime->GetEvalTime()); } int animator_setEvalTime(animator_obj *self, PyObject *value) { if (value == NULL || !PyFloat_Check(value)) { PyErr_SetString(PyExc_TypeError, "evalTime must be set to a float object"); return -1; } self->anime->SetEvalTime((float)PyFloat_AsDouble(value)); return 0; } PyObject *animator_getTotalEvalTime(animator_obj *self) { return PyFloat_FromDouble((double)self->anime->GetTotalEvalTime()); } int animator_setTotalEvalTime(animator_obj *self, PyObject *value) { if (value == NULL || !PyFloat_Check(value)) { PyErr_SetString(PyExc_TypeError, "totalEvalTime must be set to a float object"); return -1; } self->anime->SetTotalEvalTime((float)PyFloat_AsDouble(value)); return 0; } PyObject *animator_getStartTime(animator_obj *self) { return PyFloat_FromDouble((double)self->anime->GetStartTime()); } int animator_setStartTime(animator_obj *self, PyObject *value) { if (value == NULL || !PyFloat_Check(value)) { PyErr_SetString(PyExc_TypeError, "startTime must be set to a float object"); return -1; } self->anime->SetStartTime((float)PyFloat_AsDouble(value)); return 0; } PyObject *animator_getEndTime(animator_obj *self) { return PyFloat_FromDouble((double)self->anime->GetEndTime()); } int animator_setEndTime(animator_obj *self, PyObject *value) { if (value == NULL || !PyFloat_Check(value)) { PyErr_SetString(PyExc_TypeError, "endTime must be set to a float object"); return -1; } self->anime->SetEndTime((float)PyFloat_AsDouble(value)); return 0; } PyObject *animator_getSpeed(animator_obj *self) { return PyFloat_FromDouble((double)self->anime->GetSpeed()); } int animator_setSpeed(animator_obj *self, PyObject *value) { if (value == NULL || !PyFloat_Check(value)) { PyErr_SetString(PyExc_TypeError, "speed must be set to a float object"); return -1; } self->anime->SetSpeed((float)PyFloat_AsDouble(value)); return 0; } PyObject *animator_getDefaultEndtime(animator_obj *self) { return PyFloat_FromDouble((double)self->anime->GetDefaultEndtime()); } PyObject *animator_getElapsedTime(animator_obj *self) { return PyFloat_FromDouble((double)self->anime->GetElapsedTime()); } PyObject *animator_rewind(animator_obj *self) { self->anime->Rewind(); Py_INCREF(Py_None); return Py_None; } PyMethodDef animator_methods[] = { { "rewind", (PyCFunction)animator_rewind, METH_NOARGS, rewind_doc }, { NULL, NULL } }; PyGetSetDef animator_getsets[] = { { const_cast<char*>("loop"), (getter)animator_getLooping, (setter)animator_setLooping,loop_doc, NULL }, { const_cast<char*>("evalTime"), (getter)animator_getEvalTime, (setter)animator_setEvalTime,evalTime_doc, NULL }, { const_cast<char*>("totalEvalTime"), (getter)animator_getTotalEvalTime, (setter)animator_setTotalEvalTime,totalEvalTime_doc, NULL }, { const_cast<char*>("startTime"), (getter)animator_getStartTime, (setter)animator_setStartTime,startTime_doc, NULL }, { const_cast<char*>("endTime"), (getter)animator_getEndTime, (setter)animator_setEndTime,endTime_doc, NULL }, { const_cast<char*>("speed"), (getter)animator_getSpeed, (setter)animator_setSpeed,speed_doc, NULL }, { const_cast<char*>("defaultEndTime"), (getter)animator_getDefaultEndtime, NULL,defaultEndTime_doc, NULL }, { const_cast<char*>("elapsedTime"), (getter)animator_getElapsedTime, NULL,elapsedTime_doc, NULL }, { NULL, NULL } }; PyTypeObject AnimatorType = { PyVarObject_HEAD_INIT(NULL, 0) "pyxie.animator", /* tp_name */ sizeof(animator_obj), /* tp_basicsize */ 0, /* tp_itemsize */ (destructor)animator_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_reserved */ 0, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ (reprfunc)animator_str, /* tp_str */ 0, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT, /* tp_flags */ animator_doc, /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ animator_methods, /* tp_methods */ 0, /* tp_members */ animator_getsets, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ 0, /* tp_init */ 0, /* tp_alloc */ animator_new, /* tp_new */ 0, /* tp_free */ }; }
35.220513
139
0.583285
[ "object" ]
ad5ef530a875d997d8f3ed2b5970df7eddbfb8fd
965
cpp
C++
LeetCode/0153. Find Minimum in Rotated Sorted Array/solution.cpp
InnoFang/oh-my-algorithms
f559dba371ce725a926725ad28d5e1c2facd0ab2
[ "Apache-2.0" ]
19
2018-08-26T03:10:58.000Z
2022-03-07T18:12:52.000Z
LeetCode/0153. Find Minimum in Rotated Sorted Array/solution.cpp
InnoFang/Algorithm-Library
1896b9d8b1fa4cd73879aaecf97bc32d13ae0169
[ "Apache-2.0" ]
null
null
null
LeetCode/0153. Find Minimum in Rotated Sorted Array/solution.cpp
InnoFang/Algorithm-Library
1896b9d8b1fa4cd73879aaecf97bc32d13ae0169
[ "Apache-2.0" ]
6
2020-03-16T23:00:06.000Z
2022-01-13T07:02:08.000Z
/** * 150 / 150 test cases passed. * Runtime: 8 ms * Memory Usage: 9.9 MB */ class Solution { public: int findMin(vector<int>& nums) { int left = 0, right = nums.size() - 1; while (left <= right) { if (nums[left] <= nums[right]) return nums[left]; int mid = left + ((right - left) >> 1); if (nums[mid] >= nums[left]) { left = mid + 1; } else { right = mid; } } return -1; } }; /** * 150 / 150 test cases passed. * Runtime: 8 ms * Memory Usage: 9.9 MB */ class Solution2 { public: int findMin(vector<int>& nums) { int left = 0, right = nums.size() - 1; while (left < right) { int mid = left + right >> 1; if (nums[mid] < nums[right]) { right = mid; } else { left = mid + 1; } } return nums[left]; } };
22.44186
61
0.429016
[ "vector" ]
ad5fcccc50a3a19eb21997b4d94785622d67a4a3
9,688
cpp
C++
src/qt/veil/tutorialwidget.cpp
jskitty-repos/veil
075f51693a5ac39e4c8bf22a9f12cd851fb29a1c
[ "MIT" ]
124
2018-12-25T00:01:18.000Z
2021-12-26T19:38:43.000Z
src/qt/veil/tutorialwidget.cpp
MatWaller/veil
072cc3a63bda5f0c47c09cdc74635ee3bc68e160
[ "MIT" ]
702
2018-12-16T18:07:18.000Z
2022-03-18T16:52:14.000Z
src/qt/veil/tutorialwidget.cpp
MatWaller/veil
072cc3a63bda5f0c47c09cdc74635ee3bc68e160
[ "MIT" ]
151
2018-12-13T07:33:34.000Z
2022-01-29T11:35:23.000Z
// Copyright (c) 2019 The Veil developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <qt/veil/tutorialwidget.h> #include <qt/veil/forms/ui_tutorialwidget.h> #include <qt/guiutil.h> #include <QDebug> #include <QFileDialog> #include <iostream> #include <wallet/wallet.h> #include <wallet/walletutil.h> #include <veil/mnemonic/mnemonic.h> #include <veil/mnemonic/generateseed.h> #include <qt/veil/qtutils.h> TutorialWidget::TutorialWidget(QWidget *parent) : QDialog(parent), ui(new Ui::TutorialWidget) { ui->setupUi(this); this->parent = parent; this->setStyleSheet(GUIUtil::loadStyleSheet()); this->setWindowTitle("Veil Wallet Setup"); this->setContentsMargins(0,0,0,0); this->ui->containerLeft->setContentsMargins(0,0,0,0); ui->QStackTutorialContainer->setContentsMargins(0,0,0,10); // TODO: Complete this with the specific language words dictionary dic = string_to_lexicon("english"); for(unsigned long i=0; i< dic.size() ; i++){ wordList << dic[i]; } tutorialMnemonicRevealed = new TutorialMnemonicRevealed(wordList, this); tutorialLanguageWidget = new TutorialLanguagesWidget(this); ui->QStackTutorialContainer->addWidget(tutorialMnemonicRevealed); ui->QStackTutorialContainer->addWidget(tutorialLanguageWidget); ui->QStackTutorialContainer->setCurrentWidget(tutorialLanguageWidget); loadLeftContainer(":/icons/img-start-logo", "Welcome to VEIL", ""); ui->btnBack->setVisible(false); ui->btnLineSeparator->setVisible(false); ui->btnNext->setFocusPolicy(Qt::NoFocus); ui->btnBack->setFocusPolicy(Qt::NoFocus); connect(ui->btnNext, SIGNAL(clicked()), this, SLOT(on_next_triggered())); connect(ui->btnBack, SIGNAL(clicked()), this, SLOT(on_back_triggered())); } // left side void TutorialWidget::loadLeftContainer(QString imgPath, QString topMessage, QString bottomMessage){ QPixmap icShield(120,120); icShield.load(imgPath); ui->imgTutorial->setPixmap(icShield); ui->messageTop->setText(topMessage); ui->messageBottom->setText(bottomMessage); } // Actions std::vector<std::string> mnemonicWordList; void TutorialWidget::on_next_triggered(){ QWidget *qWidget = nullptr; switch (position) { case 0: { strLanguageSelection = QString::fromStdString(tutorialLanguageWidget->GetLanguageSelection()); tutorialCreateWallet = new TutorialCreateWalletWidget(this); ui->QStackTutorialContainer->addWidget(tutorialCreateWallet); qWidget = tutorialCreateWallet; //img-start-wallet loadLeftContainer(":/icons/img-wallet","Setup your\nVEIL wallet",""); ui->btnLineSeparator->setVisible(true); ui->btnBack->setVisible(true); break; } case 1: { if (tutorialCreateWallet && tutorialCreateWallet->GetButtonClicked()) { switch (tutorialCreateWallet->GetButtonClicked()) { case 1: { //Generate mnemonic phrase from fresh entropy mnemonic = ""; veil::GenerateNewMnemonicSeed(mnemonic, strLanguageSelection.toStdString()); std::stringstream ss(mnemonic); std::istream_iterator<std::string> begin(ss); std::istream_iterator<std::string> end; mnemonicWordList.clear(); mnemonicWordList = std::vector<std::string>(begin, end); tutorialMnemonicCode = new TutorialMnemonicCode(mnemonicWordList, this); ui->QStackTutorialContainer->addWidget(tutorialMnemonicCode); qWidget = tutorialMnemonicCode; loadLeftContainer(":/icons/img-start-backup","Backup your \n recovery seed phrase","Your 24-word seed phrase \n can be used to restore your wallet."); break; } case 2: { qWidget = tutorialMnemonicRevealed; loadLeftContainer(":/icons/img-start-confirm","Enter your \n seed phrase",""); break; } case 3: { //TODO: Import wallet from file. This code probably doesn't work. QFile walletFile(QFileDialog::getOpenFileName(0, "Choose wallet file")); if(!walletFile.exists()) return; fs::path walletPath = walletFile.fileName().toStdString(); CWallet::CreateWalletFromFile(walletFile.fileName().toStdString(), walletPath); shutdown = false; accept(); return; } } } break; } case 2: { if (tutorialMnemonicRevealed && tutorialCreateWallet->GetButtonClicked() == 2) { mnemonic = ""; std::string strWalletFile = "wallet.dat"; std::list<QString> q_word_list = tutorialMnemonicRevealed->getOrderedStrings(); for (QString &q_word : q_word_list) { if (mnemonic.empty()) mnemonic = q_word.toStdString(); else mnemonic += " " + q_word.toStdString(); } shutdown = false; accept(); } else { qWidget = tutorialMnemonicRevealed; loadLeftContainer(":/icons/img-start-confirm","Confirm your \n seed phrase",""); } break; } case 3: { if (tutorialCreateWallet->GetButtonClicked() == 2) { shutdown = false; accept(); return; } else { // Check mnemonic first std::list<QString> q_word_list = tutorialMnemonicRevealed->getOrderedStrings(); std::string mnemonicTest; for (QString &q_word : q_word_list) { if (mnemonicTest.empty()) mnemonicTest = q_word.toStdString(); else mnemonicTest += " " + q_word.toStdString(); } if(mnemonicTest != mnemonic){ openToastDialog( QString::fromStdString("Invalid mnemonic, please write the words on the same order as before"), this ); return; } shutdown = false; accept(); } break; } case 4: shutdown = false; accept(); break; } if(qWidget){ position++; if(ui->QStackTutorialContainer->currentWidget() != qWidget) { ui->QStackTutorialContainer->setCurrentWidget(qWidget); } } } void TutorialWidget::on_back_triggered(){ if(position != 0){ QWidget *qWidget = nullptr; position--; switch (position) { case 0: { qWidget = tutorialLanguageWidget; loadLeftContainer(":/icons/img-start-logo", "Welcome to VEIL", ""); ui->btnBack->setVisible(false); ui->btnLineSeparator->setVisible(false); break; } case 1: { qWidget = tutorialCreateWallet; loadLeftContainer(":/icons/img-start-wallet","Setup your\nVEIL wallet",""); ui->btnLineSeparator->setVisible(true); ui->btnBack->setVisible(true); break; } case 2: { if (tutorialMnemonicRevealed && tutorialCreateWallet->GetButtonClicked() == 2) { qWidget = tutorialMnemonicRevealed; loadLeftContainer(":/icons/img-start-confirm","Enter your \n seed phrase",""); } else { qWidget = tutorialMnemonicCode; loadLeftContainer(":/icons/img-start-confirm","Confirm your \n seed phrase",""); } break; } case 3: { qWidget = tutorialMnemonicRevealed; loadLeftContainer(":/icons/img-start-password","Encrypt your wallet",""); break; } } if(qWidget != nullptr){ if(ui->QStackTutorialContainer->currentWidget() != qWidget) { ui->QStackTutorialContainer->setCurrentWidget(qWidget); } } } } std::string TutorialWidget::GetLanguageSelection() const { return strLanguageSelection.toStdString(); } TutorialWidget::~TutorialWidget() { delete ui; }
38.29249
179
0.514967
[ "vector" ]
ad604414d9a29c53903de04a58d5808b12f1034f
392
hpp
C++
item.hpp
malcx95/tilde
880331fccff76b93f83115c837894f49e3f2d4ea
[ "Xnet", "X11" ]
null
null
null
item.hpp
malcx95/tilde
880331fccff76b93f83115c837894f49e3f2d4ea
[ "Xnet", "X11" ]
null
null
null
item.hpp
malcx95/tilde
880331fccff76b93f83115c837894f49e3f2d4ea
[ "Xnet", "X11" ]
null
null
null
#ifndef ITEM_H #define ITEM_H #include <SFML/Graphics.hpp> #include "constants.hpp" const int MAX_ITEMS = 10; struct Item { bool being_carried; bool in_box; sf::Sprite sprite; sf::Clock drop_clock; }; void spawn_item(std::vector<Item*>& items, std::vector<sf::Texture*> item_textures); void remove_item(std::vector<Item*>& items, Item* item); #endif /* ifndef ITEM_H */
18.666667
84
0.696429
[ "vector" ]
ad6331e9f11669428080397efb10bc80a6cd56d6
495
cpp
C++
codesignal/array/electionsWinners.cpp
peterlamar/cpp-cp-cheatsheet
23af2e893992141572005de7a438c3a2d376547e
[ "Apache-2.0" ]
null
null
null
codesignal/array/electionsWinners.cpp
peterlamar/cpp-cp-cheatsheet
23af2e893992141572005de7a438c3a2d376547e
[ "Apache-2.0" ]
null
null
null
codesignal/array/electionsWinners.cpp
peterlamar/cpp-cp-cheatsheet
23af2e893992141572005de7a438c3a2d376547e
[ "Apache-2.0" ]
null
null
null
/* For votes = [2, 3, 5, 2] and k = 3, the output should be electionsWinners(votes, k) = 2. */ int electionsWinners(vector<int> votes, int k) { auto mx = max_element(votes.begin(), votes.end()); int rtn = 0; // if no more votes if (k == 0){ if (count(votes.begin(), votes.end(), *mx) == 1) return 1; else return 0; } for (int &v: votes){ if (v+k > *mx && k > 0) rtn += 1; } return rtn; }
20.625
56
0.468687
[ "vector" ]
ad65658935dd68fdf9475b9f401c111cc48c95a6
25,190
cpp
C++
src/python_wrapper/_pydeform.cpp
noumannahmad/deform
4212cac5682da27d63eb7583bf9a517664313eb4
[ "MIT" ]
15
2019-06-15T10:19:24.000Z
2022-02-18T05:35:58.000Z
src/python_wrapper/_pydeform.cpp
noumannahmad/deform
4212cac5682da27d63eb7583bf9a517664313eb4
[ "MIT" ]
36
2019-06-24T14:32:04.000Z
2022-01-16T21:16:09.000Z
src/python_wrapper/_pydeform.cpp
simeks/deform
3d6ab6f3c398ef18343b77c84874cec64b918e57
[ "MIT" ]
4
2019-06-25T20:01:28.000Z
2021-08-29T17:33:47.000Z
#include <pybind11/iostream.h> #include <pybind11/numpy.h> #include <pybind11/pybind11.h> #include <pybind11/stl.h> #include <cassert> #include <map> #include <string> #include <deform_lib/defer.h> #include <deform_lib/jacobian.h> #include <deform_lib/make_unique.h> #include <deform_lib/regularize.h> #include <deform_lib/version.h> #include <deform_lib/registration/affine_transform.h> #include <deform_lib/registration/displacement_field.h> #include <deform_lib/registration/settings.h> #include <deform_lib/registration/registration.h> #include <deform_lib/registration/registration_engine.h> #include <deform_lib/registration/transform.h> #include <stk/image/volume.h> namespace py = pybind11; // TODO: This is copied from STK, should probably make this importable namespace pybind11 { namespace detail { template <> struct type_caster<float3> { public: PYBIND11_TYPE_CASTER(float3, _("float3")); bool load(handle src, bool) { try { tuple t = py::cast<tuple>(src); if (t.size() != 3) { return false; } value = float3{ t[0].cast<float>(), t[1].cast<float>(), t[2].cast<float>() }; } catch (std::exception& e) { return false; } return true; } static handle cast(float3 src, return_value_policy /* policy */, handle /* parent */) { return make_tuple( src.x, src.y, src.z ).release(); } }; template <> struct type_caster<dim3> { public: PYBIND11_TYPE_CASTER(dim3, _("dim3")); bool load(handle src, bool) { try { tuple t = py::cast<tuple>(src); if (t.size() != 3) { return false; } value = dim3{ t[0].cast<uint32_t>(), t[1].cast<uint32_t>(), t[2].cast<uint32_t>() }; } catch (std::exception& e) { return false; } return true; } static handle cast(dim3 src, return_value_policy /* policy */, handle /* parent */) { return make_tuple( src.x, src.y, src.z ).release(); } }; template <> struct type_caster<int3> { public: PYBIND11_TYPE_CASTER(int3, _("int3")); bool load(handle src, bool) { try { tuple t = py::cast<tuple>(src); if (t.size() != 3) { return false; } value = int3{ t[0].cast<int>(), t[1].cast<int>(), t[2].cast<int>() }; } catch (std::exception& e) { return false; } return true; } static handle cast(int3 src, return_value_policy /* policy */, handle /* parent */) { return make_tuple( src.x, src.y, src.z ).release(); } }; template <> struct type_caster<Matrix3x3f> { public: PYBIND11_TYPE_CASTER(Matrix3x3f, _("Matrix3x3f")); bool load(handle src, bool) { try { array_t<float> a = py::cast<array_t<float>>(src); if (a.ndim() != 2 || a.shape(0) != 3 || a.shape(1) != 3) { return false; } value = Matrix3x3f{ float3{a.at(0, 0), a.at(0, 1), a.at(0, 2)}, float3{a.at(1, 0), a.at(1, 1), a.at(1, 2)}, float3{a.at(2, 0), a.at(2, 1), a.at(2, 2)} }; } catch (std::exception& e) { return false; } return true; } static handle cast(Matrix3x3f src, return_value_policy /* policy */, handle /* parent */) { return py::array_t<float>( {3, 3}, &src._rows[0].x ).release(); } }; }} // namespace pybind11::detail /*! * \brief Get the shape of the array as an std::vector. */ static std::vector<ptrdiff_t> get_shape(const py::array& image) { std::vector<ptrdiff_t> shape; for (py::ssize_t i = 0; i < image.ndim(); ++i) { shape.push_back(image.shape()[i]); } return shape; } /*! * \brief Get the scalar shape of the array as an std::vector. * * Given an array representing a vector volume image, return the * shape of the volume. */ static std::vector<ptrdiff_t> get_scalar_shape(const py::array& image) { auto shape = get_shape(image); assert((shape.size() == 4 && "The image is already a scalar volume")); shape.pop_back(); return shape; } /*! * \brief Get the vector shape of the array as an std::vector. * * Given an array representing a scalar volume image, return the * shape of the volume of an associated vector image. */ static std::vector<ptrdiff_t> get_vector_shape(const py::array& image) { auto shape = get_shape(image); assert((shape.size() == 3 && "The image is already a vector volume")); shape.push_back(3l); return shape; } /*! * \brief Get the stk::Type associated to a numpy image. */ stk::Type get_stk_type(const py::array& a) { stk::Type base_type = stk::Type_Unknown; if (py::isinstance<py::array_t<char>>(a)) { base_type = stk::Type_Char; } else if (py::isinstance<py::array_t<bool>>(a)) { base_type = stk::Type_Char; } else if (py::isinstance<py::array_t<uint8_t>>(a)) { base_type = stk::Type_UChar; } else if (py::isinstance<py::array_t<short>>(a)) { base_type = stk::Type_Short; } else if (py::isinstance<py::array_t<uint16_t>>(a)) { base_type = stk::Type_UShort; } else if (py::isinstance<py::array_t<int>>(a)) { base_type = stk::Type_Int; } else if (py::isinstance<py::array_t<uint32_t>>(a)) { base_type = stk::Type_UInt; } else if (py::isinstance<py::array_t<float>>(a)) { base_type = stk::Type_Float; } else if (py::isinstance<py::array_t<double>>(a)) { base_type = stk::Type_Double; } else { throw std::invalid_argument("Unsupported type"); } // NOTE: the value of ndim can be ambiguous, e.g. // ndim == 3 may be a scalar volume or a vector 2D image... return stk::build_type(base_type, a.ndim() == 4 ? 3 : 1); } /*! * \brief Convert a numpy array to a stk::Volume. * * The new volume creates a copy of the input * image data. * * @note The numpy array must be C-contiguous, with * [z,y,x] indexing. * * @param image Array representing a volume image. * @param origin Vector of length 3, containing * the (x, y,z) coordinates of the * volume origin. * @param spacing Vector of length 3, containing * the (x, y,z) spacing of the * volume. * @param direction Vector of length 9, representing * the cosine direction matrix in * row-major order. * @return A volume representing the same image. */ stk::Volume image_to_volume( const py::array image, const std::vector<double>& origin, const std::vector<double>& spacing, const std::vector<double>& direction ) { if (image.flags() & py::array::f_style) { throw std::invalid_argument("The arrays must be C-contiguous."); } float3 origin_ { float(origin[0]), float(origin[1]), float(origin[2]), }; float3 spacing_ { float(spacing[0]), float(spacing[1]), float(spacing[2]), }; Matrix3x3f direction_ {{ {float(direction[0]), float(direction[1]), float(direction[2])}, {float(direction[3]), float(direction[4]), float(direction[5])}, {float(direction[6]), float(direction[7]), float(direction[8])}, }}; dim3 size { std::uint32_t(image.shape(2)), std::uint32_t(image.shape(1)), std::uint32_t(image.shape(0)), }; stk::Volume volume {size, get_stk_type(image), image.data()}; volume.set_origin(origin_); volume.set_spacing(spacing_); volume.set_direction(direction_); return volume; } /*! * \brief Validate and convert the landmarks. * * Convert the landmarks to a C++ vector. * * @note A copy of the landmarks data is created. * @note The numpy array must be C-contiguous. * * @param landmarks Array `n \times 3` representing * the landmarks. * @return A vector of landmarks. */ std::vector<float3> convert_landmarks(const py::array_t<float> landmarks_array) { if (landmarks_array.ndim() != 2 || landmarks_array.shape(1) != 3) { throw std::invalid_argument("The landmarks must be a `n × 3` array."); } std::vector<float3> landmarks; for (ptrdiff_t i = 0; i < landmarks_array.shape(0); ++i) { landmarks.push_back({ *landmarks_array.data(i, 0), *landmarks_array.data(i, 1), *landmarks_array.data(i, 2), }); } return landmarks; } /*! * \brief Add the logger, converting it if necessary. * * If the input is a string, add a file logger using it as filename. If * it is a Python object, try to cast it to StringIO and add a stream * logger. */ void add_logger( const py::object& log, const stk::LogLevel level, std::unique_ptr<py::detail::pythonbuf>& buffer, std::unique_ptr<std::ostream>& out_stream ) { if (log.is_none()) { return; } try { stk::log_add_file(py::cast<std::string>(log).c_str(), level); } catch (py::cast_error &) { try { buffer = make_unique<py::detail::pythonbuf>(log); out_stream = make_unique<std::ostream>(buffer.get()); stk::log_add_stream(out_stream.get(), level); } catch (...) { throw std::invalid_argument("Invalid log object!"); } } } std::string registration_docstring = R"(Perform deformable registration. Parameters ---------- fixed_images: Union[stk.Volume, List[stk.Volume]] Fixed image, or list of fixed images. moving_images: Union[stk.Volume, List[stk.Volume]] Moving image, or list of moving images. fixed_mask: stk.Volume Fixed mask. moving_mask: stk.Volume Moving mask. fixed_landmarks: np.ndarray Array of shape :math:`n \times 3`, with one row for each landmark point. moving_landmarks: np.ndarray Array of shape :math:`n \times 3`, with one row for each landmark point. initial_displacement: stk.Volume Initial guess of the displacement field. affine_transform: AffineTransform Initial affine transformation constraint_mask: stk.Volume Boolean mask for the constraints on the displacement. Requires to provide `constraint_values`. constraint_values: stk.Volume Value for the constraints on the displacement. Requires to provide `constraint_mask`. regularization_map: stk.Volume Map of voxel-wise regularization weights. Should be the same shape as the fixed image. settings: dict Python dictionary containing the settings for the registration. log: Union[StringIO, str] Output for the log, either a StringIO or a filename. silent: bool If `True`, do not write output to screen. num_threads: int Number of OpenMP threads to be used. If zero, the number is selected automatically. use_gpu: bool If `True`, use GPU acceleration from a CUDA device. Requires a build with CUDA support. Returns ------- stk.Volume Vector image containing the displacement that warps the moving image(s) toward the fixed image(s). The displacement is defined in the reference coordinates of the fixed image(s), and each voxel contains the displacement that allows to resample the voxel from the moving image(s). )"; stk::Volume registration_wrapper( const py::object& fixed_images, const py::object& moving_images, const stk::Volume& fixed_mask, const stk::Volume& moving_mask, const py::object& fixed_landmarks, const py::object& moving_landmarks, const stk::Volume& initial_displacement, const AffineTransform& affine_transform, const stk::Volume& constraint_mask, const stk::Volume& constraint_values, #ifdef DF_ENABLE_REGULARIZATION_WEIGHT_MAP const stk::Volume& regularization_map, #endif const py::object& settings, const py::object& log, const stk::LogLevel log_level, const bool silent, const int num_threads, const bool use_gpu ) { #ifndef DF_USE_CUDA if (use_gpu) { throw std::invalid_argument("This build of pydeform has no CUDA support!"); } #endif // Redirect C++ stdout/stderr to Python's py::scoped_ostream_redirect std_out(std::cout, py::module::import("sys").attr("stdout")); py::scoped_ostream_redirect std_err(std::cerr, py::module::import("sys").attr("stderr")); // Handle logging std::unique_ptr<py::detail::pythonbuf> buffer; std::unique_ptr<std::ostream> out_stream; stk::log_init(); if (!silent) stk::log_add_stream(&std::cerr, log_level); add_logger(log, log_level, buffer, out_stream); LOG(Info) << deform::version_string(); // Handle single images passed as objects, without a container std::vector<stk::Volume> fixed_volumes; if (py::isinstance<stk::Volume>(fixed_images)) { fixed_volumes = {py::cast<stk::Volume>(fixed_images)}; } else if (py::isinstance<py::array>(fixed_images)) { fixed_volumes = {py::cast<stk::Volume>(fixed_images)}; } else { fixed_volumes = py::cast<std::vector<stk::Volume>>(fixed_images); } std::vector<stk::Volume> moving_volumes; if (py::isinstance<stk::Volume>(moving_images)) { moving_volumes = {py::cast<stk::Volume>(moving_images)}; } else if (py::isinstance<py::array>(moving_images)) { moving_volumes = {py::cast<stk::Volume>(moving_images)}; } else { moving_volumes = py::cast<std::vector<stk::Volume>>(moving_images); } // Ensure the number of fixed and moving images matches if (fixed_volumes.size() != moving_volumes.size()) { throw ValidationError("The number of fixed and moving images must match."); } // Convert optional arguments. Try to cast to the correct numeric // type if possible. std::vector<float3> fixed_landmarks_; if (!fixed_landmarks.is_none()) { fixed_landmarks_ = convert_landmarks(py::cast<py::array_t<float>>(fixed_landmarks)); } std::vector<float3> moving_landmarks_; if (!moving_landmarks.is_none()) { moving_landmarks_ = convert_landmarks(py::cast<py::array_t<float>>(moving_landmarks)); } // Parse settings Settings settings_; if (!settings.is_none()) { // Convert the python dict into a YAML string, which then is parseable by settings py::object py_yaml_dump = py::module::import("yaml").attr("dump"); py::object py_settings_str = py_yaml_dump(py::cast<py::dict>(settings)); std::string settings_str = py::cast<std::string>(py_settings_str); parse_registration_settings(settings_str, settings_); // Print only contents of parameter file to Info LOG(Info) << "Parameters:" << std::endl << settings_str; std::stringstream settings_ss; print_registration_settings(settings_, settings_ss); // Print all settings to Verbose LOG(Verbose) << settings_ss.rdbuf(); } // Check number of image slots if (settings_.image_slots.size() != fixed_volumes.size()) { LOG(Warning) << "Different number of images between input and settings!"; settings_.image_slots.resize(fixed_volumes.size()); } // Perform registration stk::Volume displacement = registration(settings_, fixed_volumes, moving_volumes, fixed_mask, moving_mask, fixed_landmarks_, moving_landmarks_, initial_displacement, affine_transform, constraint_mask, constraint_values, #ifdef DF_ENABLE_REGULARIZATION_WEIGHT_MAP regularization_map, #endif num_threads #ifdef DF_USE_CUDA , use_gpu #endif ); // This must be done before the `out_stream` goes out of scope stk::log_shutdown(); return displacement; } std::string transform_docstring = R"(Warp an image given a displacement field. The image is resampled using the given displacement field. The size of the result equals the size of the displacement. Parameters ---------- image: stk.Volume Volume image to be warped. displacement: stk.Volume Displacement field used to resample the image. interpolator: pydeform.Interpolator Interpolator used in the resampling process, either `pydeform.Interpolator.Linear` or `pydeform.Interpolator.NearestNeighbour`. affine_transform: AffineTransform Optional affine transformation Returns ------- stk.Volume Deformed image obtained resampling the input image with the given displacement field. )"; stk::Volume transform_wrapper( const stk::Volume& src, const stk::Volume& df, transform::Interp interp, const AffineTransform& affine_transform) { return transform_volume(src, DisplacementField(df, affine_transform), interp); } std::string jacobian_docstring = R"(Compute the Jacobian determinant of the deformation associated to a displacement. Given a displacement field :math:`d(x)`, compute the Jacobian determinant of its associated deformation field :math:`D(x) = x + d(x)`. Parameters ---------- displacement: stk.Volume Displacement field used to resample the image. Returns ------- stk.Volume Scalar volume image containing the Jacobian of the deformation associated to the input displacement. )"; stk::Volume jacobian_wrapper(const stk::Volume& df) { return calculate_jacobian(df); } std::string regularization_docstring = R"(Regularize a given displacement field. Parameters ---------- displacement: stk.Volume Displacement field used to resample the image. precision: float Amount of precision. pyramid_levels: int Number of levels for the resolution pyramid constraint_mask: stk.Volume Mask for constraining displacements in a specific area, i.e., restricting any changes within the region. constraint_values: stk.Volume Vector field specifying the displacements within the constrained regions. Returns ------- stk.Volume Scalar volume image containing the resulting displacement field. )"; stk::Volume regularization_wrapper( const stk::Volume& displacement, float precision, int pyramid_levels, const stk::Volume& constraint_mask, const stk::Volume& constraint_values) { return regularization( displacement, precision, pyramid_levels, constraint_mask, constraint_values ); } AffineTransform make_affine_transform( const py::array_t<double>& matrix, const py::array_t<double>& offset ) { AffineTransform t; if (matrix.ndim() != 2 || matrix.shape(0) != 3 || matrix.shape(1) != 3) { throw py::value_error("Invalid shape of affine matrix, expected (3, 3)."); } Matrix3x3f m; for (int i = 0; i < 3; ++i) { for (int j = 0; j < 3; ++j) { m(i, j) = (float)matrix.at(i, j); }} if (offset.ndim() != 1 || offset.shape(0) != 3) { throw py::value_error("Invalid shape of affine offset, expected (3)."); } float3 o { (float)offset.at(0), (float)offset.at(1), (float)offset.at(2) }; return AffineTransform(m, o); } std::string read_affine_transform_docstring = R"(Reads an affine transform from an ITK Transform File (.txt). Parameters ---------- path: Str Path to the transform file. Raises ------ ValueError: If file cannot be read. Returns ------- pydeform.AffineTransform Read affine transformation. )"; AffineTransform read_affine_transform(const std::string& path) { return parse_affine_transform_file(path); } PYBIND11_MODULE(_pydeform, m) { m.attr("__version__") = GIT_VERSION_TAG; m.def("version", [](){ return deform::version_string(); }); m.def("has_gpu", [](){ #ifdef DF_USE_CUDA return true; #else return false; #endif }); m.import("_stk"); py::enum_<transform::Interp>(m, "Interpolator", "Interpolator functions") .value("NearestNeighbour", transform::Interp_NN, "Nearest neighbour interpolation") .value("NearestNeighbor", transform::Interp_NN, "Non-British spelling for NearestNeighbour") .value("Linear", transform::Interp_Linear, "Trilinear interpolation") .export_values(); py::enum_<stk::LogLevel>(m, "LogLevel", "Level for the logger") .value("Verbose", stk::LogLevel::Verbose, "Lowest level, report all messages") .value("Info", stk::LogLevel::Info, "Report informative messages, warnings and errors") .value("Warning", stk::LogLevel::Warning, "Report warnings and errors") .value("Error", stk::LogLevel::Error, "Report only errors") .value("Fatal", stk::LogLevel::Fatal, "Report only fatal errors") .export_values(); py::class_<AffineTransform>(m, "AffineTransform") .def(py::init<>()) .def(py::init(&make_affine_transform), py::arg("matrix"), py::arg("offset") ) .def_property_readonly("matrix", &AffineTransform::matrix) .def_property_readonly("offset", &AffineTransform::offset); m.def("read_affine_transform", read_affine_transform, read_affine_transform_docstring.c_str() ); m.def("register", &registration_wrapper, registration_docstring.c_str(), py::arg("fixed_images"), py::arg("moving_images"), py::arg("fixed_mask") = stk::Volume(), py::arg("moving_mask") = stk::Volume(), py::arg("fixed_landmarks") = py::none(), py::arg("moving_landmarks") = py::none(), py::arg("initial_displacement") = stk::Volume(), py::arg("affine_transform") = AffineTransform(), py::arg("constraint_mask") = stk::Volume(), py::arg("constraint_values") = stk::Volume(), #ifdef DF_ENABLE_REGULARIZATION_WEIGHT_MAP py::arg("regularization_map") = stk::Volume(), #endif py::arg("settings") = py::none(), py::arg("log") = py::none(), py::arg("log_level") = stk::LogLevel::Info, py::arg("silent") = true, py::arg("num_threads") = 0, py::arg("use_gpu") = false ); m.def("transform", &transform_wrapper, transform_docstring.c_str(), py::arg("image"), py::arg("displacement"), py::arg("interpolator") = transform::Interp_Linear, py::arg("affine_transform") = AffineTransform() ); m.def("jacobian", &jacobian_wrapper, jacobian_docstring.c_str() ); m.def("regularize", &regularization_wrapper, regularization_docstring.c_str(), py::arg("displacement"), py::arg("precision") = 0.5f, py::arg("pyramid_levels") = 6, py::arg("constraint_mask") = stk::Volume(), py::arg("constraint_values") = stk::Volume() ); // Translate relevant exception types. The exceptions not handled // here will be translated autmatically according to pybind11's rules. py::register_exception_translator([](std::exception_ptr p) { try { if (p) { std::rethrow_exception(p); } } catch (const stk::FatalException &e) { // Map stk::FatalException to Python RutimeError // +13 to remove the "Fatal error: " from the message PyErr_SetString(PyExc_RuntimeError, e.what() + 13); } }); }
30.496368
100
0.589877
[ "object", "shape", "vector", "transform" ]
ad7103cd05ad1e1632dd3ccb0f0fd58428abab33
3,300
cpp
C++
MetroMiniABSBiDir-noCANSlave/MetroMiniABSBiDir-noCANSlave/ABSSlaveBus.cpp
RobertPHeller/RPi-RRCircuits
19aff23e20eebdbd028c0407d68eef77cc6ee0ec
[ "CC-BY-4.0" ]
10
2018-09-04T02:12:39.000Z
2022-03-17T20:29:32.000Z
MetroMiniABSBiDir-noCANSlave/MetroMiniABSBiDir-noCANSlave/ABSSlaveBus.cpp
RobertPHeller/RPi-RRCircuits
19aff23e20eebdbd028c0407d68eef77cc6ee0ec
[ "CC-BY-4.0" ]
null
null
null
MetroMiniABSBiDir-noCANSlave/MetroMiniABSBiDir-noCANSlave/ABSSlaveBus.cpp
RobertPHeller/RPi-RRCircuits
19aff23e20eebdbd028c0407d68eef77cc6ee0ec
[ "CC-BY-4.0" ]
1
2018-12-26T00:32:27.000Z
2018-12-26T00:32:27.000Z
// -!- C++ -!- ////////////////////////////////////////////////////////////// // // System : // Module : // Object Name : $RCSfile$ // Revision : $Revision$ // Date : $Date$ // Author : $Author$ // Created By : Robert Heller // Created : Tue Jun 12 23:52:07 2018 // Last Modified : <180722.1636> // // Description // // Notes // // History // ///////////////////////////////////////////////////////////////////////////// // // Copyright (C) 2018 Robert Heller D/B/A Deepwoods Software // 51 Locke Hill Road // Wendell, MA 01379-9728 // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. // // // ////////////////////////////////////////////////////////////////////////////// static const char rcsid[] = "@(#) : $Id$"; #include "ABSSlaveBus.h" void ABSSlaveBus::process() { if (Serial.available() > 0) { //Serial.print("*** Serial.available() = "), Serial.println(Serial.available()); // Message from the master format: // :Gnn; + CRLF // Where nn is an id (1 or 2 digit decimal) // 7 bytes at 115200 BAUD, assuming 10 bits (start, 8 data, 2 stop) // takes .6ms char byte = Serial.read(); //Serial.print("*** byte = "); Serial.println(byte); if (byte != ':') return; if (Serial.available() > 0) { byte = Serial.read(); } else { return; } //Serial.print("*** byte = "); Serial.println(byte); if (byte != 'G') return; if (Serial.available() < 1) return; int id = Serial.parseInt(); while (Serial.available() > 0 && Serial.read() != '\n') ; if (id != myid) return; // At 115200 BAUD, assuming 10 bits (start, 8 data, 2 stop) // a 12 byte message takes 1.04ms // Response message format: // :RnnoEaWa; + CRLF // Where: nn == My id (1 or 2 digit decimal) // o == O (block occupied) or C (block clear) // a == S (stop aspect), A (approach aspect), or C (clear aspect). // Serial.print(':'); Serial.print('R'); Serial.print(myid,DEC); if (block->state) Serial.print('O'); else Serial.print('C'); Serial.print('E'); if (eastStop->state) Serial.print('S'); else if (eastApproach->state) Serial.print('A'); else Serial.print('C'); Serial.print('W'); if (westStop->state) Serial.print('S'); else if (westApproach->state) Serial.print('A'); else Serial.print('C'); Serial.println(';'); } }
35.483871
88
0.521212
[ "object" ]
ad73b0e738ca857dbf9509e2e6de903b84bb602d
39,520
cpp
C++
src/util/gfx.cpp
churay/hmp
d149c89e63f331db7198f8e97a1751e466063374
[ "MIT" ]
1
2018-10-26T05:39:07.000Z
2018-10-26T05:39:07.000Z
src/util/gfx.cpp
churay/hmp
d149c89e63f331db7198f8e97a1751e466063374
[ "MIT" ]
92
2018-10-26T05:56:48.000Z
2020-07-16T05:33:27.000Z
src/util/gfx.cpp
churay/hmp
d149c89e63f331db7198f8e97a1751e466063374
[ "MIT" ]
null
null
null
#include <SDL2/SDL.h> #include <SDL2/SDL_opengl.h> #include <SDL2/SDL_opengl_glext.h> #include <glm/glm.hpp> #include <glm/ext/matrix_transform.hpp> #include <glm/gtc/type_ptr.hpp> #include <glm/gtx/transform.hpp> #include <glm/gtx/vector_angle.hpp> #include <glm/gtx/string_cast.hpp> #include <cstring> #include <limits> #include "gfx.h" namespace llce { namespace gfx { /// 'llce::gfx::color_context_t' Functions /// color_context_t::color_context_t( const color4u8_t* pColor ) { glPushAttrib( GL_CURRENT_BIT ); glColor4ubv( (uint8_t*)pColor ); } color_context_t::color_context_t( const color4f32_t* pColor ) { glPushAttrib( GL_CURRENT_BIT ); glColor4fv( (float32_t*)pColor ); } color_context_t::~color_context_t() { glPopAttrib(); } void color_context_t::update( const color4u8_t* pColor ) { glColor4ubv( (uint8_t*)pColor ); } void color_context_t::update( const color4f32_t* pColor ) { glColor4fv( (float32_t*)pColor ); } /// 'llce::gfx::render_context_t' Functions /// render_context_t::render_context_t( const box_t& pBox ) { glPushMatrix(); mat4f32_t matModelWorld( 1.0f ); matModelWorld *= glm::translate( vec3f32_t(pBox.mPos.x, pBox.mPos.y, 0.0f) ); matModelWorld *= glm::scale( vec3f32_t(pBox.mDims.x, pBox.mDims.y, 1.0f) ); glMultMatrixf( &matModelWorld[0][0] ); } render_context_t::render_context_t( const box_t& pBox, const float32_t pScreenRatio ) : render_context_t( pBox ) { const float32_t cContextRatio = llce::gfx::glAspect(); box_t ratioBox( 0.0f, 0.0f, 1.0f, 1.0f ); float32_t wscaled = pScreenRatio * ratioBox.mDims.y / cContextRatio; float32_t hscaled = cContextRatio * ratioBox.mDims.x / pScreenRatio; if( wscaled < ratioBox.mDims.x ) { ratioBox.mPos.x += ( ratioBox.mDims.x - wscaled ) / 2.0f; ratioBox.mDims.x = wscaled; } else { ratioBox.mPos.y += ( ratioBox.mDims.y - hscaled ) / 2.0f; ratioBox.mDims.y = hscaled; } mat4f32_t matRatio( 1.0f ); matRatio *= glm::translate( vec3f32_t(ratioBox.mPos.x, ratioBox.mPos.y, 0.0f) ); matRatio *= glm::scale( vec3f32_t(ratioBox.mDims.x, ratioBox.mDims.y, 1.0f) ); glMultMatrixf( &matRatio[0][0] ); } render_context_t::render_context_t( const vec2f32_t& pPos, const vec2f32_t& pBasisX, const vec2f32_t& pBasisY ) { const static vec3f32_t csBasisZ( 0.0f, 0.0f, 1.0f ); // TODO(JRC): Add support for skewed and arbitrarily rotated (U, V) // basis vector contexts. LLCE_CHECK_ERROR( glm::length(glm::rotate(pBasisX, glm::half_pi<float32_t>()) - pBasisY) < glm::epsilon<float32_t>(), "Unable to create rendering context for coordinate system with basis " << "(U, V): (" << glm::to_string(pBasisX) << ", " << glm::to_string(pBasisY) << "); only systems with non-skew, counterclockwise bases are currently supported." ); glPushMatrix(); mat4f32_t matModelWorld( 1.0f ); matModelWorld *= glm::translate( vec3f32_t(pPos.x, pPos.y, 0.0f) ); matModelWorld *= glm::rotate( glm::orientedAngle(vec2f32_t(1.0f, 0.0f), glm::normalize(pBasisX)), csBasisZ ); matModelWorld *= glm::scale( vec3f32_t(glm::length(pBasisX), glm::length(pBasisY), 1.0f) ); glMultMatrixf( &matModelWorld[0][0] ); } render_context_t::~render_context_t() { glPopMatrix(); } /// 'llce::gfx::fbo_t' Functions /// fbo_t::fbo_t( const vec2u32_t pFBRes ) { glGenFramebuffers( 1, &mFrameID ); glBindFramebuffer( GL_FRAMEBUFFER, mFrameID ); glGenTextures( 1, &mColorID ); glBindTexture( GL_TEXTURE_2D, mColorID ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR ); glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA8, pFBRes.x, pFBRes.y, 0, GL_RGBA, GL_UNSIGNED_INT_8_8_8_8, nullptr ); glFramebufferTexture2D( GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, mColorID, 0 ); glGenTextures( 1, &mDepthID ); glBindTexture( GL_TEXTURE_2D, mDepthID ); glTexImage2D( GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT32, pFBRes.x, pFBRes.y, 0, GL_DEPTH_COMPONENT, GL_UNSIGNED_INT, nullptr ); glFramebufferTexture2D( GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, mDepthID, 0 ); } fbo_t::~fbo_t() { glBindFramebuffer( GL_FRAMEBUFFER, 0 ); glBindTexture( GL_TEXTURE_2D, 0 ); } bool32_t fbo_t::valid() const { return glCheckFramebufferStatus( GL_FRAMEBUFFER ) == GL_FRAMEBUFFER_COMPLETE; } /// 'llce::gfx::fbo_context_t' Functions /// fbo_context_t::fbo_context_t( const uint32_t pFBID, const vec2u32_t pFBRes ) { const static int32_t csContextFlags[] = { GL_VIEWPORT, GL_SCISSOR_BOX }; const uint32_t cContextCount = LLCE_ELEM_COUNT( csContextFlags ); vec2i32_t* cContextParams[] = { &mViewport[0], &mScissor[0] }; for( uint32_t contextIdx = 0; contextIdx < cContextCount; contextIdx++ ) { glGetIntegerv( csContextFlags[contextIdx], static_cast<int32_t*>(&(cContextParams[contextIdx]->x)) ); } glBindFramebuffer( GL_FRAMEBUFFER, pFBID ); glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT ); glViewport( 0, 0, pFBRes.x, pFBRes.y ); glScissor( 0, 0, pFBRes.x, pFBRes.y ); } fbo_context_t::~fbo_context_t() { glBindFramebuffer( GL_FRAMEBUFFER, 0 ); glViewport( mViewport[0].x, mViewport[0].y, mViewport[1].x, mViewport[1].y ); glScissor( mScissor[0].x, mScissor[0].y, mScissor[1].x, mScissor[1].y ); } /// 'llce::gfx' General Functions /// float32_t aspect( const vec2i32_t& pDims ) { return ( pDims.x + 0.0f ) / ( pDims.y + 0.0f ); } float32_t aspect( const vec2u32_t& pDims ) { return ( pDims.x + 0.0f ) / ( pDims.y + 0.0f ); } float32_t aspect( const vec2f32_t& pDims ) { return ( pDims.x + 0.0f ) / ( pDims.y + 0.0f ); } mat4f32_t glMatrix() { mat4f32_t mvMatrix( 0.0f ); glGetFloatv( GL_MODELVIEW_MATRIX, &mvMatrix[0][0] ); mat4f32_t projMatrix( 0.0f ); glGetFloatv( GL_PROJECTION_MATRIX, &projMatrix[0][0] ); vec2u32_t vpCoords, vpRes; { int32_t viewParams[4]; glGetIntegerv( GL_VIEWPORT, &viewParams[0] ); vpCoords = { static_cast<uint32_t>(viewParams[0]), static_cast<uint32_t>(viewParams[1]) }; vpRes = { static_cast<uint32_t>(viewParams[2]), static_cast<uint32_t>(viewParams[3]) }; } mat4f32_t vpMatrix( 1.0f ); vpMatrix = glm::translate( vpMatrix, vec3f32_t((vpCoords.x + vpRes.x) / 2.0f, (vpCoords.y + vpRes.y) / 2.0f, 0.5f) ); vpMatrix = glm::scale( vpMatrix, vec3f32_t(vpRes.x / 2.0f, vpRes.y / 2.0f, 0.5f) ); return vpMatrix * projMatrix * mvMatrix; } float32_t glAspect() { const vec4f32_t cGLBases = llce::gfx::glMatrix() * vec4f32_t( 1.0f, 1.0f, 0.0f, 0.0f ); return cGLBases.x / cGLBases.y; } /// 'llce::gfx::color' Functions /// color4f32_t color::u82f32( const color4u8_t& pColorU8 ) { return { pColorU8.x / 255.0f, pColorU8.y / 255.0f, pColorU8.z / 255.0f, pColorU8.w / 255.0f }; } color4u8_t color::f322u8( const color4f32_t& pColorF32 ) { return { std::floor(pColorF32.x >= 1.0f ? 255 : pColorF32.x * 256.0f), std::floor(pColorF32.y >= 1.0f ? 255 : pColorF32.y * 256.0f), std::floor(pColorF32.z >= 1.0f ? 255 : pColorF32.z * 256.0f), std::floor(pColorF32.w >= 1.0f ? 255 : pColorF32.w * 256.0f) }; } // NOTE(JRC): This code was adapted taken from this tutorial: // https://www.ronja-tutorials.com/2019/04/16/hsv-colorspace.html color4f32_t color::rgb2hsv( const color4f32_t& pColorRGB ) { float32_t maxChannel = glm::max( pColorRGB.x, glm::max(pColorRGB.y, pColorRGB.z) ); float32_t minChannel = glm::min( pColorRGB.x, glm::min(pColorRGB.y, pColorRGB.z) ); float32_t colorLen = maxChannel - minChannel; float32_t colorHue = ( (maxChannel == pColorRGB.x) ? 0.0f + (pColorRGB.y - pColorRGB.z) / colorLen : ( (maxChannel == pColorRGB.y) ? 2.0f + (pColorRGB.z - pColorRGB.x) / colorLen : ( (maxChannel == pColorRGB.z) ? 4.0f + (pColorRGB.x - pColorRGB.y) / colorLen : 0.0f ))); color4f32_t colorHSV = { glm::fract(colorHue / 6.0f), colorLen / maxChannel, colorLen, pColorRGB.w }; return colorHSV; } // NOTE(JRC): This code was adapted taken from this tutorial: // https://www.ronja-tutorials.com/2019/04/16/hsv-colorspace.html color4f32_t color::hsv2rgb( const color4f32_t& pColorHSV ) { color4f32_t colorRGB = { std::fabs( pColorHSV.x * 6.0f - 3.0f ) - 1.0f, 2.0f - std::fabs( pColorHSV.x * 6.0f - 2.0f ), 2.0f - std::fabs( pColorHSV.x * 6.0f - 4.0f ), pColorHSV.w }; colorRGB = glm::clamp( colorRGB, {0.0f, 0.0f, 0.0f, 0.0f}, {1.0f, 1.0f, 1.0f, 1.0f} ); colorRGB = glm::mix( {1.0f, 1.0f, 1.0f, 1.0f}, colorRGB, pColorHSV.y ); colorRGB = pColorHSV.z * colorRGB; return colorRGB; } color4u8_t color::transparentize( const color4u8_t& pColor, const float32_t pPercent ) { uint8_t newAlpha = static_cast<uint8_t>( glm::min(pColor.w * pPercent, 255.0f) ); return { pColor.x, pColor.y, pColor.z, newAlpha }; } color4f32_t color::transparentize( const color4f32_t& pColor, const float32_t pPercent ) { float32_t newAlpha = glm::min( pColor.w * pPercent, 1.0f ); return { pColor.x, pColor.y, pColor.z, newAlpha }; } // NOTE(JRC): This code was adapted from this SO response: // http://www.graficaobscura.com/matrix/index.html color4f32_t color::saturateRGB( const color4f32_t& pColorRGB, const float32_t pPercent ) { const static float32_t csGrayR = 0.3086f, csGrayG = 0.6094f, csGrayB = 0.0820f; const float32_t cSaturateVal = glm::clamp( pPercent, -1.0f, 1.0f ) + 1.0f; const float32_t cSaturateMatData[16] = { (1.0f - cSaturateVal) * csGrayR + cSaturateVal, (1.0f - cSaturateVal) * csGrayR, (1.0f - cSaturateVal) * csGrayR, 0.0f, (1.0f - cSaturateVal) * csGrayG, (1.0f - cSaturateVal) * csGrayG + cSaturateVal, (1.0f - cSaturateVal) * csGrayG, 0.0f, (1.0f - cSaturateVal) * csGrayB, (1.0f - cSaturateVal) * csGrayB, (1.0f - cSaturateVal) * csGrayB + cSaturateVal, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f }; const mat4f32_t cSaturateMat = glm::make_mat4x4( &cSaturateMatData[0] ); color4f32_t satColorRGB = cSaturateMat * pColorRGB; satColorRGB = glm::clamp( satColorRGB, {0.0f, 0.0f, 0.0f, 0.0f}, {1.0f, 1.0f, 1.0f, 1.0f} ); return satColorRGB; } color4f32_t color::saturateHSV( const color4f32_t& pColorHSV, const float32_t pPercent ) { color4f32_t satColorHSV = pColorHSV; satColorHSV.y = glm::clamp( satColorHSV.y + pPercent * satColorHSV.y, 0.0f, 1.0f ); return satColorHSV; } /// 'llce::gfx::render' Functions /// void render::vector( const vec2f32_t& pOrigin, const vec2f32_t& pDir, const float32_t pLength ) { const static float64_t csHeadRatio = 2.5 / 10.0; const static float64_t csTailRatio = 1.0 - csHeadRatio; const static float64_t csWidthRatio = 1.0 / 10.0; const static vec2f32_t csAxisI( 1.0f, 0.0f ), csAxisJ( 0.0f, 1.0f ); const vec2f32_t cDirNorm = glm::normalize( pDir ); const float32_t cDirAngle = glm::orientedAngle( csAxisI, cDirNorm ); glPushMatrix(); mat4f32_t matVecSpace( 1.0f ); matVecSpace *= glm::translate( vec3f32_t(pOrigin.x, pOrigin.y, 0.0f) ); matVecSpace *= glm::rotate( cDirAngle, vec3f32_t(0.0f, 0.0f, 1.0f) ); glMultMatrixf( &matVecSpace[0][0] ); { // Rendering // glBegin( GL_QUADS ); { glVertex2f( 0.0f, (-csWidthRatio / 2.0f) * pLength ); glVertex2f( csTailRatio * pLength, (-csWidthRatio / 2.0f) * pLength ); glVertex2f( csTailRatio * pLength, (csWidthRatio / 2.0f) * pLength ); glVertex2f( 0.0f, (csWidthRatio / 2.0f) * pLength ); } glEnd(); glBegin( GL_TRIANGLES ); { glVertex2f( csTailRatio * pLength, (-csHeadRatio / 2.0f) * pLength ); glVertex2f( (csTailRatio + csHeadRatio) * pLength, 0.0f ); glVertex2f( csTailRatio * pLength, (csHeadRatio / 2.0f) * pLength ); } glEnd(); } glPopMatrix(); } void render::box( const box_t& pBox ) { const vec2f32_t& boxMin = pBox.mPos; const vec2f32_t& boxDims = pBox.mDims; glBegin( GL_QUADS ); { glVertex2f( boxMin.x, boxMin.y ); glVertex2f( boxMin.x + boxDims.x, boxMin.y ); glVertex2f( boxMin.x + boxDims.x, boxMin.y + boxDims.y ); glVertex2f( boxMin.x, boxMin.y + boxDims.y ); } glEnd(); } void render::box( const vec2f32_t& pSize, const vec2f32_t& pPos, const llce::geom::anchor2D_e pAnchor ) { // TODO(JRC): Implement this function so that (1) it's actually correct // (correctly renders horizontal bars onlt) and (2) it doesn't duplicate // code from the analogous 'render::text' function. // vec2i32_t windowDims; { // SDL_Window* window = SDL_GL_GetCurrentWindow(); // SDL_GetWindowSize( window, &windowDims.x, &windowDims.y ); // windowDims.x = windowDims.y = glm::min( windowDims.x, windowDims.y ); // } const vec2i32_t cWindowDims = windowDims; // vec4i32_t viewportData; { // glGetIntegerv( GL_VIEWPORT, &viewportData.x ); // } const vec2i32_t cViewportDims = { viewportData.z, viewportData.w }; // float32_t viewportWindowRatio = 1.0f; { // const float32_t viewportAspect = llce::gfx::aspect( cViewportDims ); // const float32_t windowAspect = llce::gfx::aspect( cWindowDims ); // // If A_window < A_viewport, then only for w_window == w_viewport will // // the viewport fit inside the window. Opposite for A_window > A_viewport. // if( windowAspect < viewportAspect ) { // viewportWindowRatio = cViewportDims.x / ( cWindowDims.x + 0.0f ); // } else { // if( windowAspect > viewportAspect ) { // viewportWindowRatio = cViewportDims.y / ( cWindowDims.y + 0.0f ); // } // } // const mat4f32_t cViewspaceWindowXform = llce::gfx::glMatrix(); // const mat4f32_t cWindowViewspaceXform = glm::inverse( cViewspaceWindowXform ); // vec4f32_t boxDims( pSize.x, pSize.y, 0.0f, 0.0f ); // window space // boxDims *= viewportWindowRatio; // window space, adjusted for viewport skew // boxDims = cWindowViewspaceXform * boxDims; // current coord space // boxDims.x = ( boxDims.x == 0.0f ) ? 1.0f : boxDims.x; // boxDims.y = ( boxDims.y == 0.0f ) ? 1.0f : boxDims.y; // llce::gfx::render::box( box_t(pPos, boxDims, pAnchor), pColor ); } void render::circle( const circle_t& pCircle, const float32_t pStartRadians, const float32_t pEndRadians ) { const static uint32_t csSegmentsPer2PI = 20; glPushMatrix(); mat4f32_t matCircleSpace( 1.0f ); matCircleSpace *= glm::translate( vec3f32_t(pCircle.mCenter.x, pCircle.mCenter.y, 0.0f) ); matCircleSpace *= glm::scale( vec3f32_t(pCircle.mRadius / 2.0f, pCircle.mRadius / 2.0f, 1.0f) ); glMultMatrixf( &matCircleSpace[0][0] ); // FIXME(JRC): The following code crashes for very small intervals as they cause // the interpolation scheme to divide by zero. { // Rendering // const interval_t cRadianInterval( pStartRadians, pEndRadians ); const uint32_t cSegmentCount = std::ceil( cRadianInterval.length() * csSegmentsPer2PI ); glBegin( GL_TRIANGLE_FAN ); { glVertex2f( 0.0f, 0.0f ); for( uint32_t segmentIdx = 0; segmentIdx < cSegmentCount; segmentIdx++ ) { float32_t segmentRadians = cRadianInterval.interp( segmentIdx / (cSegmentCount - 1.0f) ); glVertex2f( std::cos(segmentRadians), std::sin(segmentRadians) ); } } glEnd(); } glPopMatrix(); } void render::border( const float32_t pSize, const uint32_t pDim ) { const float32_t cContextAspect = llce::gfx::glAspect(); const vec2f32_t cSideSizes( ( pDim == 0 ) ? pSize : pSize / cContextAspect, ( pDim == 1 ) ? pSize : pSize * cContextAspect ); glPushMatrix(); mat4f32_t borderSpace( 1.0f ); for( uint32_t sideIdx = 0; sideIdx < 4; sideIdx++ ) { borderSpace = glm::translate( vec3f32_t(0.0f, 1.0f, 0.0f) ) * glm::rotate( -glm::half_pi<float32_t>(), vec3f32_t(0.0f, 0.0f, 1.0f) ); glMultMatrixf( &borderSpace[0][0] ); const float32_t cSideSize = ( sideIdx % 2 == 0 ) ? cSideSizes.y : cSideSizes.x; glBegin( GL_QUADS ); { glVertex2f( 0.0f, 0.0f ); glVertex2f( 0.0f, 1.0f ); glVertex2f( cSideSize, 1.0f ); glVertex2f( cSideSize, 0.0f ); } glEnd(); } glPopMatrix(); } void render::border( const float32_t (&pSizes)[4] ) { // NOTE(JRC): The input is given in an order that differs from the convenient // iteration order, so this map serves to bridge the gap between these two // different index spaces. const static uint32_t csBorderIndexMap[] = { 2, 1, 0, 3 }; glPushMatrix(); mat4f32_t borderSpace( 1.0f ); for( uint32_t sideIdx = 0; sideIdx < 4; sideIdx++ ) { borderSpace = glm::translate( vec3f32_t(0.0f, 1.0f, 0.0f) ) * glm::rotate( -glm::half_pi<float32_t>(), vec3f32_t(0.0f, 0.0f, 1.0f) ); glMultMatrixf( &borderSpace[0][0] ); const float32_t& cSideSize = pSizes[csBorderIndexMap[sideIdx]]; glBegin( GL_QUADS ); { glVertex2f( 0.0f, 0.0f ); glVertex2f( 0.0f, 1.0f ); glVertex2f( cSideSize, 1.0f ); glVertex2f( cSideSize, 0.0f ); } glEnd(); } glPopMatrix(); } void render::text( const char8_t* pText, const box_t& pRenderBox ) { const static float64_t csDigitSpaceX = 1.0 / llce::gfx::DIGIT_WIDTH; const static float64_t csDigitSpaceY = 1.0 / llce::gfx::DIGIT_HEIGHT; const static float64_t csDigitPaddingX = csDigitSpaceX / 10.0; const static float64_t csDigitPaddingY = csDigitSpaceY / 10.0; const static float64_t csDigitFillX = csDigitSpaceX - 2.0 * csDigitPaddingX; const static float64_t csDigitFillY = csDigitSpaceY - 2.0 * csDigitPaddingY; const uint32_t cTextLength = std::strlen( pText ); const float64_t cTextSpacingX = 2.0 * llce::gfx::DIGIT_WIDTH; const float64_t cTextSpacingY = 0.0; const float64_t cTextFillX = cTextSpacingX / ( (cTextSpacingX + 1.0) * cTextLength - 1.0 ); const float64_t cTextFillY = 1.0; gfx::render_context_t rrc( pRenderBox, llce::gfx::DIGIT_ASPECT * cTextLength ); for( const char8_t* pTextItr = pText; *pTextItr != '\0'; pTextItr++ ) { const auto cTextDigitMap = &llce::gfx::ASCII_DIGIT_MAP[static_cast<uint32_t>(*pTextItr)][0]; const uint32_t cTextIdx = pTextItr - pText; const float64_t cTextOffsetX = ( cTextFillX + cTextFillX / cTextSpacingX ) * cTextIdx; const float64_t cTextOffsetY = 0.0; const box_t cTextBox( cTextOffsetX, cTextOffsetY, cTextFillX, cTextFillY ); gfx::render_context_t trc( cTextBox ); for( uint32_t yIdx = 0; yIdx < llce::gfx::DIGIT_HEIGHT; yIdx++ ) { for( uint32_t xIdx = 0; xIdx < llce::gfx::DIGIT_WIDTH; xIdx++ ) { const float64_t cDigitOffsetX = csDigitPaddingX + csDigitSpaceX * xIdx; const float64_t cDigitOffsetY = csDigitPaddingY + csDigitSpaceY * yIdx; if( cTextDigitMap[yIdx][xIdx] ) { gfx::render::box( box_t( cDigitOffsetX, cDigitOffsetY, csDigitFillX, csDigitFillY) ); } } } } } void render::text( const char8_t* pText, const float32_t pSize, const vec2f32_t& pPos, const llce::geom::anchor2D_e pAnchor ) { // NOTE(JRC): For an arbitrary harness code, it isn't possible for this code // to know how its frame buffer will be skewed/transformed for the final render. // However, the 'llce' harness has a process that attempts to maintain characteristics // of each simulation's frame buffer (e.g. aspect ratio), so this function makes // the following assumptions: // (1) the aspect ratio of the viewbuffer is maintained // (2) if the frame buffer is too big or too small, it's maximally fit to // the render window with minimal scaling // TODO(JRC): This should be adjusted based on the target aspect ratio for the // current simulation once the harness is updated to recognize/adapt to this value // (see 'hmp' issue #75). Currently, the harness always assumes/uses a 1:1 ratio. vec2i32_t windowDims; { SDL_Window* window = SDL_GL_GetCurrentWindow(); SDL_GetWindowSize( window, &windowDims.x, &windowDims.y ); windowDims.x = windowDims.y = glm::min( windowDims.x, windowDims.y ); } const vec2i32_t cWindowDims = windowDims; vec4i32_t viewportData; { glGetIntegerv( GL_VIEWPORT, &viewportData.x ); } const vec2i32_t cViewportDims = { viewportData.z, viewportData.w }; float32_t viewportWindowRatio = 1.0f; { const float32_t viewportAspect = llce::gfx::aspect( cViewportDims ); const float32_t windowAspect = llce::gfx::aspect( cWindowDims ); // If A_window < A_viewport, then only for w_window == w_viewport will // the viewport fit inside the window. Opposite for A_window > A_viewport. if( windowAspect < viewportAspect ) { viewportWindowRatio = cViewportDims.x / ( cWindowDims.x + 0.0f ); } else { // if( windowAspect > viewportAspect ) { viewportWindowRatio = cViewportDims.y / ( cWindowDims.y + 0.0f ); } } const mat4f32_t cViewspaceWindowXform = llce::gfx::glMatrix(); const mat4f32_t cWindowViewspaceXform = glm::inverse( cViewspaceWindowXform ); vec4f32_t textCharDims( llce::gfx::DIGIT_ASPECT * pSize, pSize, 0.0f, 0.0f ); // window space textCharDims *= viewportWindowRatio; // window space, adjusted for viewport skew textCharDims = cWindowViewspaceXform * textCharDims; // current coord space const vec2f32_t& textPos = pPos; vec2f32_t textDims = vec2f32_t( std::strlen(pText) * textCharDims.x, textCharDims.y ); llce::gfx::render::text( pText, box_t(textPos, textDims, pAnchor) ); } /// 'llce::gfx' Constants /// const bool8_t ASCII_DIGIT_MAP[128][DIGIT_HEIGHT][DIGIT_WIDTH] = { { {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}, {0, 0, 0, 0, 0}, {0, 0, 0, 0, 0} }, // 'NUL' { {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}, {0, 0, 0, 0, 0}, {0, 0, 0, 0, 0} }, // 'SOH' { {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}, {0, 0, 0, 0, 0}, {0, 0, 0, 0, 0} }, // 'STX' { {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}, {0, 0, 0, 0, 0}, {0, 0, 0, 0, 0} }, // 'ETX' { {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}, {0, 0, 0, 0, 0}, {0, 0, 0, 0, 0} }, // 'EOT' { {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}, {0, 0, 0, 0, 0}, {0, 0, 0, 0, 0} }, // 'ENQ' { {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}, {0, 0, 0, 0, 0}, {0, 0, 0, 0, 0} }, // 'ACK' { {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}, {0, 0, 0, 0, 0}, {0, 0, 0, 0, 0} }, // 'BEL' { {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}, {0, 0, 0, 0, 0}, {0, 0, 0, 0, 0} }, // 'BS' { {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}, {0, 0, 0, 0, 0}, {0, 0, 0, 0, 0} }, // 'TAB' { {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}, {0, 0, 0, 0, 0}, {0, 0, 0, 0, 0} }, // 'LF' { {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}, {0, 0, 0, 0, 0}, {0, 0, 0, 0, 0} }, // 'VT' { {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}, {0, 0, 0, 0, 0}, {0, 0, 0, 0, 0} }, // 'FF' { {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}, {0, 0, 0, 0, 0}, {0, 0, 0, 0, 0} }, // 'CR' { {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}, {0, 0, 0, 0, 0}, {0, 0, 0, 0, 0} }, // 'SO' { {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}, {0, 0, 0, 0, 0}, {0, 0, 0, 0, 0} }, // 'SI' { {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}, {0, 0, 0, 0, 0}, {0, 0, 0, 0, 0} }, // 'DLE' { {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}, {0, 0, 0, 0, 0}, {0, 0, 0, 0, 0} }, // 'DC1' { {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}, {0, 0, 0, 0, 0}, {0, 0, 0, 0, 0} }, // 'DC2' { {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}, {0, 0, 0, 0, 0}, {0, 0, 0, 0, 0} }, // 'DC3' { {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}, {0, 0, 0, 0, 0}, {0, 0, 0, 0, 0} }, // 'DC4' { {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}, {0, 0, 0, 0, 0}, {0, 0, 0, 0, 0} }, // 'NAK' { {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}, {0, 0, 0, 0, 0}, {0, 0, 0, 0, 0} }, // 'SYN' { {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}, {0, 0, 0, 0, 0}, {0, 0, 0, 0, 0} }, // 'ETB' { {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}, {0, 0, 0, 0, 0}, {0, 0, 0, 0, 0} }, // 'CAN' { {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}, {0, 0, 0, 0, 0}, {0, 0, 0, 0, 0} }, // 'EM' { {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}, {0, 0, 0, 0, 0}, {0, 0, 0, 0, 0} }, // 'SUB' { {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}, {0, 0, 0, 0, 0}, {0, 0, 0, 0, 0} }, // 'ESC' { {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}, {0, 0, 0, 0, 0}, {0, 0, 0, 0, 0} }, // 'FS' { {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}, {0, 0, 0, 0, 0}, {0, 0, 0, 0, 0} }, // 'GS' { {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}, {0, 0, 0, 0, 0}, {0, 0, 0, 0, 0} }, // 'RS' { {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}, {0, 0, 0, 0, 0}, {0, 0, 0, 0, 0} }, // 'US' { {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}, {0, 0, 0, 0, 0}, {0, 0, 0, 0, 0} }, // ' ' { {0, 1, 1, 0, 0}, {0, 1, 1, 0, 0}, {0, 0, 0, 0, 0}, {0, 1, 1, 0, 0}, {0, 1, 1, 0, 0}, {0, 1, 1, 0, 0}, {0, 1, 1, 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, 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, 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, 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, 0, 0}, {0, 0, 0, 0, 0} }, // '$' { {1, 0, 0, 1, 1}, {1, 0, 0, 1, 1}, {0, 1, 0, 0, 0}, {0, 0, 1, 0, 0}, {0, 0, 0, 1, 0}, {1, 1, 0, 0, 1}, {1, 1, 0, 0, 1} }, // '%' { {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}, {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}, {0, 0, 0, 0, 0}, {0, 0, 0, 0, 0}, {0, 0, 0, 0, 0}, {0, 0, 0, 0, 0} }, // ''' { {0, 0, 0, 1, 0}, {0, 0, 1, 0, 0}, {0, 1, 0, 0, 0}, {0, 1, 0, 0, 0}, {0, 1, 0, 0, 0}, {0, 0, 1, 0, 0}, {0, 0, 0, 1, 0} }, // '(' { {0, 1, 0, 0, 0}, {0, 0, 1, 0, 0}, {0, 0, 0, 1, 0}, {0, 0, 0, 1, 0}, {0, 0, 0, 1, 0}, {0, 0, 1, 0, 0}, {0, 1, 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, 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, 0, 0, 0}, {0, 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, 0}, {0, 1, 1, 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, 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, 0, 0}, {0, 0, 0, 0, 0} }, // '-' { {0, 0, 0, 0, 0}, {0, 1, 1, 0, 0}, {0, 1, 1, 0, 0}, {0, 0, 0, 0, 0}, {0, 0, 0, 0, 0}, {0, 0, 0, 0, 0}, {0, 0, 0, 0, 0} }, // '.' { {1, 1, 0, 0, 0}, {1, 1, 0, 0, 0}, {0, 1, 1, 0, 0}, {0, 0, 1, 0, 0}, {0, 0, 1, 1, 0}, {0, 0, 0, 1, 1}, {0, 0, 0, 1, 1} }, // '/' { {0, 1, 1, 1, 0}, {1, 0, 0, 0, 1}, {1, 0, 0, 0, 1}, {1, 0, 1, 0, 1}, {1, 0, 0, 0, 1}, {1, 0, 0, 0, 1}, {0, 1, 1, 1, 0} }, // '0' { {1, 1, 1, 1, 1}, {0, 0, 1, 0, 0}, {0, 0, 1, 0, 0}, {0, 0, 1, 0, 0}, {1, 0, 1, 0, 0}, {0, 1, 1, 0, 0}, {0, 0, 1, 0, 0} }, // '1' { {1, 1, 1, 1, 1}, {1, 0, 0, 0, 0}, {0, 1, 0, 0, 0}, {0, 0, 1, 1, 0}, {0, 0, 0, 0, 1}, {0, 0, 0, 0, 1}, {1, 1, 1, 1, 0} }, // '2' { {1, 1, 1, 1, 0}, {0, 0, 0, 0, 1}, {0, 0, 0, 0, 1}, {0, 1, 1, 1, 0}, {0, 0, 0, 0, 1}, {0, 0, 0, 0, 1}, {1, 1, 1, 1, 0} }, // '3' { {0, 0, 0, 0, 1}, {0, 0, 0, 0, 1}, {1, 1, 1, 1, 1}, {0, 1, 0, 0, 1}, {0, 0, 1, 0, 1}, {0, 0, 0, 1, 1}, {0, 0, 0, 0, 1} }, // '4' { {1, 1, 1, 1, 0}, {0, 0, 0, 0, 1}, {0, 0, 0, 0, 1}, {1, 1, 1, 1, 0}, {1, 0, 0, 0, 0}, {1, 0, 0, 0, 0}, {1, 1, 1, 1, 1} }, // '5' { {0, 1, 1, 1, 0}, {1, 0, 0, 0, 1}, {1, 0, 0, 0, 1}, {1, 1, 0, 0, 1}, {1, 0, 1, 1, 0}, {1, 0, 0, 0, 0}, {0, 1, 1, 1, 1} }, // '6' { {1, 0, 0, 0, 0}, {0, 1, 0, 0, 0}, {0, 0, 1, 0, 0}, {0, 0, 0, 1, 0}, {0, 0, 0, 0, 1}, {0, 0, 0, 0, 1}, {1, 1, 1, 1, 1} }, // '7' { {0, 1, 1, 1, 0}, {1, 0, 0, 0, 1}, {1, 0, 0, 0, 1}, {0, 1, 1, 1, 0}, {1, 0, 0, 0, 1}, {1, 0, 0, 0, 1}, {0, 1, 1, 1, 0} }, // '8' { {1, 1, 1, 1, 0}, {0, 0, 0, 0, 1}, {0, 1, 1, 0, 1}, {1, 0, 0, 1, 1}, {1, 0, 0, 0, 1}, {1, 0, 0, 0, 1}, {0, 1, 1, 1, 0} }, // '9' { {0, 0, 0, 0, 0}, {0, 1, 1, 0, 0}, {0, 1, 1, 0, 0}, {0, 0, 0, 0, 0}, {0, 1, 1, 0, 0}, {0, 1, 1, 0, 0}, {0, 0, 0, 0, 0} }, // ':' { {0, 1, 0, 0, 0}, {0, 0, 1, 0, 0}, {0, 1, 1, 0, 0}, {0, 0, 0, 0, 0}, {0, 1, 1, 0, 0}, {0, 1, 1, 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, 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, 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, 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, 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, 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, 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, 0, 0}, {0, 0, 0, 0, 0} }, // '@' { {1, 0, 0, 0, 1}, {1, 0, 0, 0, 1}, {1, 0, 0, 0, 1}, {1, 1, 1, 1, 1}, {1, 0, 0, 0, 1}, {1, 0, 0, 0, 1}, {0, 1, 1, 1, 0} }, // 'A' { {1, 1, 1, 1, 0}, {1, 0, 0, 0, 1}, {1, 0, 0, 0, 1}, {1, 1, 1, 1, 0}, {1, 0, 0, 0, 1}, {1, 0, 0, 0, 1}, {1, 1, 1, 1, 0} }, // 'B' { {0, 1, 1, 1, 1}, {1, 0, 0, 0, 0}, {1, 0, 0, 0, 0}, {1, 0, 0, 0, 0}, {1, 0, 0, 0, 0}, {1, 0, 0, 0, 0}, {0, 1, 1, 1, 1} }, // 'C' { {1, 1, 1, 1, 0}, {1, 0, 0, 0, 1}, {1, 0, 0, 0, 1}, {1, 0, 0, 0, 1}, {1, 0, 0, 0, 1}, {1, 0, 0, 0, 1}, {1, 1, 1, 1, 0} }, // 'D' { {1, 1, 1, 1, 1}, {1, 0, 0, 0, 0}, {1, 0, 0, 0, 0}, {1, 1, 1, 1, 0}, {1, 0, 0, 0, 0}, {1, 0, 0, 0, 0}, {1, 1, 1, 1, 1} }, // 'E' { {1, 0, 0, 0, 0}, {1, 0, 0, 0, 0}, {1, 0, 0, 0, 0}, {1, 1, 1, 1, 0}, {1, 0, 0, 0, 0}, {1, 0, 0, 0, 0}, {1, 1, 1, 1, 1} }, // 'F' { {0, 1, 1, 1, 0}, {1, 0, 0, 0, 1}, {1, 0, 0, 0, 1}, {1, 0, 1, 1, 1}, {1, 0, 0, 0, 0}, {1, 0, 0, 0, 0}, {0, 1, 1, 1, 1} }, // 'G' { {1, 0, 0, 0, 1}, {1, 0, 0, 0, 1}, {1, 0, 0, 0, 1}, {1, 1, 1, 1, 1}, {1, 0, 0, 0, 1}, {1, 0, 0, 0, 1}, {1, 0, 0, 0, 1} }, // 'H' { {1, 1, 1, 1, 1}, {0, 0, 1, 0, 0}, {0, 0, 1, 0, 0}, {0, 0, 1, 0, 0}, {0, 0, 1, 0, 0}, {0, 0, 1, 0, 0}, {1, 1, 1, 1, 1} }, // 'I' { {0, 1, 1, 0, 0}, {1, 0, 0, 1, 0}, {1, 0, 0, 1, 0}, {0, 0, 0, 1, 0}, {0, 0, 0, 1, 0}, {0, 0, 0, 1, 0}, {0, 0, 0, 1, 0} }, // 'J' { {1, 0, 0, 0, 1}, {1, 0, 0, 1, 0}, {1, 0, 1, 0, 0}, {1, 1, 0, 0, 0}, {1, 0, 1, 0, 0}, {1, 0, 0, 1, 0}, {1, 0, 0, 0, 1} }, // 'K' { {1, 1, 1, 1, 1}, {1, 0, 0, 0, 0}, {1, 0, 0, 0, 0}, {1, 0, 0, 0, 0}, {1, 0, 0, 0, 0}, {1, 0, 0, 0, 0}, {1, 0, 0, 0, 0} }, // 'L' { {1, 0, 0, 0, 1}, {1, 0, 0, 0, 1}, {1, 0, 0, 0, 1}, {1, 0, 1, 0, 1}, {1, 0, 1, 0, 1}, {1, 1, 0, 1, 1}, {1, 0, 0, 0, 1} }, // 'M' { {1, 0, 0, 0, 1}, {1, 0, 0, 0, 1}, {1, 0, 0, 1, 1}, {1, 0, 1, 0, 1}, {1, 1, 0, 0, 1}, {1, 0, 0, 0, 1}, {1, 0, 0, 0, 1} }, // 'N' { {0, 1, 1, 1, 0}, {1, 0, 0, 0, 1}, {1, 0, 0, 0, 1}, {1, 0, 0, 0, 1}, {1, 0, 0, 0, 1}, {1, 0, 0, 0, 1}, {0, 1, 1, 1, 0} }, // 'O' { {1, 0, 0, 0, 0}, {1, 0, 0, 0, 0}, {1, 0, 0, 0, 0}, {1, 1, 1, 1, 0}, {1, 0, 0, 0, 1}, {1, 0, 0, 0, 1}, {1, 1, 1, 1, 0} }, // 'P' { {0, 1, 1, 1, 1}, {1, 0, 0, 1, 1}, {1, 0, 1, 0, 1}, {1, 0, 0, 0, 1}, {1, 0, 0, 0, 1}, {1, 0, 0, 0, 1}, {0, 1, 1, 1, 0} }, // 'Q' { {1, 0, 0, 0, 1}, {1, 0, 0, 1, 0}, {1, 0, 1, 0, 0}, {1, 1, 1, 1, 0}, {1, 0, 0, 0, 1}, {1, 0, 0, 0, 1}, {1, 1, 1, 1, 0} }, // 'R' { {1, 1, 1, 1, 0}, {0, 0, 0, 0, 1}, {0, 0, 0, 0, 1}, {0, 1, 1, 1, 0}, {1, 0, 0, 0, 0}, {1, 0, 0, 0, 0}, {0, 1, 1, 1, 1} }, // 'S' { {0, 0, 1, 0, 0}, {0, 0, 1, 0, 0}, {0, 0, 1, 0, 0}, {0, 0, 1, 0, 0}, {0, 0, 1, 0, 0}, {0, 0, 1, 0, 0}, {1, 1, 1, 1, 1} }, // 'T' { {0, 1, 1, 1, 0}, {1, 0, 0, 0, 1}, {1, 0, 0, 0, 1}, {1, 0, 0, 0, 1}, {1, 0, 0, 0, 1}, {1, 0, 0, 0, 1}, {1, 0, 0, 0, 1} }, // 'U' { {0, 0, 1, 0, 0}, {0, 1, 0, 1, 0}, {1, 0, 0, 0, 1}, {1, 0, 0, 0, 1}, {1, 0, 0, 0, 1}, {1, 0, 0, 0, 1}, {1, 0, 0, 0, 1} }, // 'V' { {1, 0, 0, 0, 1}, {1, 1, 0, 1, 1}, {1, 0, 1, 0, 1}, {1, 0, 1, 0, 1}, {1, 0, 0, 0, 1}, {1, 0, 0, 0, 1}, {1, 0, 0, 0, 1} }, // 'W' { {1, 0, 0, 0, 1}, {1, 0, 0, 0, 1}, {0, 1, 0, 1, 0}, {0, 0, 1, 0, 0}, {0, 1, 0, 1, 0}, {1, 0, 0, 0, 1}, {1, 0, 0, 0, 1} }, // 'X' { {0, 0, 1, 0, 0}, {0, 0, 1, 0, 0}, {0, 0, 1, 0, 0}, {0, 0, 1, 0, 0}, {0, 1, 0, 1, 0}, {1, 0, 0, 0, 1}, {1, 0, 0, 0, 1} }, // 'Y' { {1, 1, 1, 1, 1}, {1, 0, 0, 0, 0}, {0, 1, 0, 0, 0}, {0, 0, 1, 0, 0}, {0, 0, 0, 1, 0}, {0, 0, 0, 0, 1}, {1, 1, 1, 1, 1} }, // 'Z' { {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}, {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}, {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}, {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}, {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}, {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}, {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} }, // '_' { {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}, {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}, {0, 0, 0, 0, 0}, {0, 0, 0, 0, 0}, {0, 0, 0, 0, 0}, {0, 0, 0, 0, 0} }, // 'a' { {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}, {0, 0, 0, 0, 0}, {0, 0, 0, 0, 0} }, // 'b' { {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}, {0, 0, 0, 0, 0}, {0, 0, 0, 0, 0} }, // 'c' { {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}, {0, 0, 0, 0, 0}, {0, 0, 0, 0, 0} }, // 'd' { {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}, {0, 0, 0, 0, 0}, {0, 0, 0, 0, 0} }, // 'e' { {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}, {0, 0, 0, 0, 0}, {0, 0, 0, 0, 0} }, // 'f' { {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}, {0, 0, 0, 0, 0}, {0, 0, 0, 0, 0} }, // 'g' { {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}, {0, 0, 0, 0, 0}, {0, 0, 0, 0, 0} }, // 'h' { {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}, {0, 0, 0, 0, 0}, {0, 0, 0, 0, 0} }, // 'i' { {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}, {0, 0, 0, 0, 0}, {0, 0, 0, 0, 0} }, // 'j' { {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}, {0, 0, 0, 0, 0}, {0, 0, 0, 0, 0} }, // 'k' { {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}, {0, 0, 0, 0, 0}, {0, 0, 0, 0, 0} }, // 'l' { {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}, {0, 0, 0, 0, 0}, {0, 0, 0, 0, 0} }, // 'm' { {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}, {0, 0, 0, 0, 0}, {0, 0, 0, 0, 0} }, // 'n' { {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}, {0, 0, 0, 0, 0}, {0, 0, 0, 0, 0} }, // 'o' { {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}, {0, 0, 0, 0, 0}, {0, 0, 0, 0, 0} }, // 'p' { {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}, {0, 0, 0, 0, 0}, {0, 0, 0, 0, 0} }, // 'q' { {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}, {0, 0, 0, 0, 0}, {0, 0, 0, 0, 0} }, // 'r' { {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}, {0, 0, 0, 0, 0}, {0, 0, 0, 0, 0} }, // 's' { {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}, {0, 0, 0, 0, 0}, {0, 0, 0, 0, 0} }, // 't' { {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}, {0, 0, 0, 0, 0}, {0, 0, 0, 0, 0} }, // 'u' { {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}, {0, 0, 0, 0, 0}, {0, 0, 0, 0, 0} }, // 'v' { {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}, {0, 0, 0, 0, 0}, {0, 0, 0, 0, 0} }, // 'w' { {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}, {0, 0, 0, 0, 0}, {0, 0, 0, 0, 0} }, // 'x' { {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}, {0, 0, 0, 0, 0}, {0, 0, 0, 0, 0} }, // 'y' { {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}, {0, 0, 0, 0, 0}, {0, 0, 0, 0, 0} }, // 'z' { {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}, {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}, {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}, {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}, {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}, {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}, {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} }, // '' }; }; };
56.863309
135
0.486108
[ "render", "vector", "transform" ]
ad73ba0de7245b00724054a484426d271508d353
25,032
hh
C++
src/phantasm-hardware-interface/types.hh
project-arcana/phantasm-hardware-interface
d75e23b0ac46efb304246930d680851bbe7f6561
[ "MIT" ]
6
2020-12-09T13:53:26.000Z
2021-12-24T14:13:17.000Z
src/phantasm-hardware-interface/types.hh
project-arcana/phantasm-hardware-interface
d75e23b0ac46efb304246930d680851bbe7f6561
[ "MIT" ]
5
2020-01-29T09:46:36.000Z
2020-09-04T16:15:53.000Z
src/phantasm-hardware-interface/types.hh
project-arcana/phantasm-hardware-interface
d75e23b0ac46efb304246930d680851bbe7f6561
[ "MIT" ]
null
null
null
#pragma once #include <cstdint> #include <cstring> #include <clean-core/flags.hh> #include <phantasm-hardware-interface/handles.hh> #define PHI_DEFINE_FLAG_TYPE(_flags_t_, _enum_t_, _max_num_) \ using _flags_t_ = cc::flags<_enum_t_, uint32_t(_max_num_)>; \ CC_FLAGS_ENUM_SIZED(_enum_t_, uint32_t(_max_num_)); #define PHI_DEFINE_FLAG_OPERATORS(FlagT, RealT) \ [[maybe_unused]] constexpr FlagT operator|(FlagT a, FlagT b) noexcept { return FlagT(RealT(a) | RealT(b)); } \ [[maybe_unused]] constexpr FlagT operator&(FlagT a, FlagT b) noexcept { return FlagT(RealT(a) & RealT(b)); } \ [[maybe_unused]] constexpr FlagT operator^(FlagT a, FlagT b) noexcept { return FlagT(RealT(a) ^ RealT(b)); } \ [[maybe_unused]] constexpr FlagT operator~(FlagT a) noexcept { return FlagT(~RealT(a)); } namespace phi { /// resources bound to a shader, up to 4 per draw or dispatch command struct shader_argument { handle::resource constant_buffer = handle::null_resource; handle::shader_view shader_view = handle::null_shader_view; uint32_t constant_buffer_offset = 0; }; /// the type of a single shader enum class shader_stage : uint8_t { none = 0, // graphics vertex, hull, domain, geometry, pixel, // compute compute, // raytracing ray_gen, ray_miss, ray_closest_hit, ray_intersect, ray_any_hit, ray_callable, MAX_SHADER_STAGE_RANGE, NUM_SHADER_STAGES = MAX_SHADER_STAGE_RANGE - 1 }; constexpr bool is_valid_shader_stage(shader_stage s) { return s > shader_stage::none && s < shader_stage::MAX_SHADER_STAGE_RANGE; } PHI_DEFINE_FLAG_TYPE(shader_stage_flags_t, shader_stage, shader_stage::NUM_SHADER_STAGES); inline constexpr shader_stage_flags_t shader_stage_mask_all_graphics = shader_stage::vertex | shader_stage::hull | shader_stage::domain | shader_stage::geometry | shader_stage::pixel; inline constexpr shader_stage_flags_t shader_stage_mask_all_ray = shader_stage::ray_gen | shader_stage::ray_miss | shader_stage::ray_closest_hit | shader_stage::ray_intersect | shader_stage::ray_any_hit | shader_stage::ray_callable; inline constexpr shader_stage_flags_t shader_stage_mask_ray_identifiable = shader_stage::ray_gen | shader_stage::ray_miss | shader_stage::ray_callable; inline constexpr shader_stage_flags_t shader_stage_mask_ray_hitgroup = shader_stage::ray_closest_hit | shader_stage::ray_any_hit | shader_stage::ray_intersect; enum class queue_type : uint8_t { direct, // graphics + copy + compute + present compute, copy }; /// the swapchain presentation mode enum class present_mode : uint8_t { synced, // synchronize presentation every vblank synced_2nd_vblank, // synchronize presentation every second vblank (effectively halves refreshrate) unsynced, // do not synchronize presentation unsynced_allow_tearing, // do not synchronize presentation and allow tearing, required for variable refresh rate displays }; /// state of a handle::resource, determining legal operations /// (D3D12: resource states, Vulkan: access masks, image layouts and pipeline stage dependencies) enum class resource_state : uint8_t { // unknown to pr unknown, // undefined in API semantics undefined, vertex_buffer, index_buffer, constant_buffer, // accessed via a CBV in any shader shader_resource, // accessed via a SRV in any shader shader_resource_nonpixel, // accessed via a SRV in a non-pixel shader only unordered_access, // accessed via a UAV in any shader render_target, depth_read, depth_write, indirect_argument, copy_src, copy_dest, resolve_src, resolve_dest, present, raytrace_accel_struct, }; /// information describing a single resource transition, specifying only the target state struct transition_info { handle::resource resource = handle::null_resource; ///< the resource to transition resource_state target_state = resource_state::undefined; ///< the state the resource is transitioned into shader_stage_flags_t dependent_shaders = shader_stage::none; ///< the shader stages accessing the resource afterwards, only applies to CBV, SRV and UAV states }; enum class resource_heap : uint8_t { gpu, // default, fastest to access for the GPU upload, // for CPU -> GPU transfer readback // for GPU -> CPU transfer }; /// pixel format of a texture, or texture view (DXGI_FORMAT / VkFormat) /// [f]loat, [i]nt, [u]int, [un]orm, [uf]loat, [t]ypeless enum class format : uint8_t { none = 0, // regular formats rgba32f, rgb32f, rg32f, r32f, rgba32i, rgb32i, rg32i, r32i, rgba32u, rgb32u, rg32u, r32u, rgba16i, rg16i, r16i, rgba16u, rg16u, r16u, rgba16f, rg16f, r16f, rgba16un, rg16un, r16un, rgba8i, rg8i, r8i, rgba8u, rg8u, r8u, rgba8un, rg8un, r8un, // sRGB versions of regular formats rgba8un_srgb, // swizzled and irregular formats bgra8un, bgra4un, b10g11r11uf, r10g10b10a2u, r10g10b10a2un, b5g6r5un, b5g5r5a1un, r9g9b9e5_sharedexp_uf, // three ufloats sharing a single 5 bit exponent, 32b in total // block-compressed formats bc1, bc1_srgb, bc2, bc2_srgb, bc3, bc3_srgb, bc6h_16f, bc6h_16uf, bc7, bc7_srgb, // view-only formats - depth r24un_g8t, // view the depth part of depth24un_stencil8u r24t_g8u, // view the stencil part of depth24un_stencil8u // depth formats depth32f, depth16un, // depth stencil formats depth32f_stencil8u, depth24un_stencil8u, MAX_FORMAT_RANGE, NUM_FORMATS = MAX_FORMAT_RANGE - 1 }; constexpr bool is_valid_format(format fmt) { return fmt > format::none && fmt < format::MAX_FORMAT_RANGE; } /// information about a single vertex attribute struct vertex_attribute_info { char const* semantic_name = nullptr; uint32_t offset = 0; format fmt = format::none; uint8_t vertex_buffer_i = 0; }; enum class texture_dimension : uint8_t { t1d, t2d, t3d }; /// the type of a resource_view enum class resource_view_dimension : uint8_t { none = 0, buffer, raw_buffer, // ByteAddressBuffer and similar views texture1d, texture1d_array, texture2d, texture2d_ms, texture2d_array, texture2d_ms_array, texture3d, texturecube, texturecube_array, raytracing_accel_struct, MAX_DIMENSION_RANGE, NUM_DIMENSIONS = MAX_DIMENSION_RANGE - 1 }; /// describes an element (either SRV or UAV) of a handle::shader_view struct resource_view { handle::resource resource; resource_view_dimension dimension; struct texture_info_t { format pixel_format; uint32_t mip_start; ///< index of the first usable mipmap (usually: 0) uint32_t mip_size; ///< amount of usable mipmaps, starting from mip_start (usually: -1 / all) uint32_t array_start; ///< index of the first usable array element [if applicable] (usually: 0) uint32_t array_size; ///< amount of usable array elements [if applicable] }; struct buffer_info_t { uint32_t element_start; ///< index of the first element in the buffer (for raw buffers, the first byte) uint32_t num_elements; ///< amount of elements in the buffer (for raw buffers, amount of bytes) uint32_t element_stride_bytes; ///< the stride of elements in bytes (for raw buffers ignored) }; struct accel_struct_info_t { handle::accel_struct accel_struct; }; union { texture_info_t texture_info; buffer_info_t buffer_info; accel_struct_info_t accel_struct_info; }; resource_view() { std::memset(this, 0, sizeof(*this)); // this is required to zero out padding for hashes } public: // convenience void init_as_null() { dimension = resource_view_dimension::none; resource = handle::null_resource; } void init_as_backbuffer(handle::resource res) { dimension = resource_view_dimension::texture2d; resource = res; texture_info.pixel_format = format::bgra8un; // cmdlist translation checks for this case and automatically chooses the right texture_info contents, // no need to specify } void init_as_tex2d(handle::resource res, format pf, bool multisampled = false, uint32_t mip_slice = 0) { dimension = multisampled ? resource_view_dimension::texture2d_ms : resource_view_dimension::texture2d; resource = res; texture_info.pixel_format = pf; texture_info.mip_start = mip_slice; texture_info.mip_size = 1; texture_info.array_start = 0; texture_info.array_size = 1; } void init_as_tex2d_array(handle::resource res, format pf, bool multisampled, uint32_t array_start = 0, uint32_t array_size = 1, uint32_t mip_slice = 0) { dimension = multisampled ? resource_view_dimension::texture2d_ms_array : resource_view_dimension::texture2d_array; resource = res; texture_info.pixel_format = pf; texture_info.mip_start = mip_slice; texture_info.mip_size = 1; texture_info.array_start = array_start; texture_info.array_size = array_size; } void init_as_tex3d(handle::resource res, format pf, uint32_t array_start, uint32_t array_size, uint32_t mip_slice = 0) { dimension = resource_view_dimension::texture3d; resource = res; texture_info.pixel_format = pf; texture_info.mip_start = mip_slice; texture_info.mip_size = 1; texture_info.array_start = array_start; texture_info.array_size = array_size; } void init_as_texcube(handle::resource res, format pf) { dimension = resource_view_dimension::texturecube; resource = res; texture_info.pixel_format = pf; texture_info.mip_start = 0; texture_info.mip_size = uint32_t(-1); texture_info.array_start = 0; texture_info.array_size = 1; } void init_as_structured_buffer(handle::resource res, uint32_t num_elements, uint32_t stride_bytes, uint32_t element_start = 0) { dimension = resource_view_dimension::buffer; resource = res; buffer_info.num_elements = num_elements; buffer_info.element_start = element_start; buffer_info.element_stride_bytes = stride_bytes; } void init_as_byte_address_buffer(handle::resource res, uint32_t num_bytes, uint32_t offset_bytes = 0) { dimension = resource_view_dimension::raw_buffer; resource = res; buffer_info.num_elements = num_bytes; buffer_info.element_start = offset_bytes; buffer_info.element_stride_bytes = 0; } void init_as_accel_struct(handle::accel_struct as) { dimension = resource_view_dimension::raytracing_accel_struct; resource = handle::null_resource; accel_struct_info.accel_struct = as; } public: // static convenience static resource_view null() { resource_view rv; rv.init_as_null(); return rv; } static resource_view backbuffer(handle::resource res) { resource_view rv; rv.init_as_backbuffer(res); return rv; } static resource_view tex2d(handle::resource res, format pf, bool multisampled = false, uint32_t mip_slice = 0) { resource_view rv; rv.init_as_tex2d(res, pf, multisampled, mip_slice); return rv; } static resource_view texcube(handle::resource res, format pf) { resource_view rv; rv.init_as_texcube(res, pf); return rv; } static resource_view structured_buffer(handle::resource res, uint32_t num_elements, uint32_t stride_bytes) { resource_view rv; rv.init_as_structured_buffer(res, num_elements, stride_bytes); return rv; } static resource_view byte_address_buffer(handle::resource res, uint32_t num_bytes, uint32_t offset_bytes = 0) { resource_view rv; rv.init_as_byte_address_buffer(res, num_bytes, offset_bytes); return rv; } static resource_view accel_struct(handle::accel_struct as) { resource_view rv; rv.init_as_accel_struct(as); return rv; } }; /// the texture filtering mode of a sampler enum class sampler_filter : uint8_t { min_mag_mip_point, min_point_mag_linear_mip_point, min_linear_mag_mip_point, min_mag_linear_mip_point, min_point_mag_mip_linear, min_linear_mag_point_mip_linear, min_mag_point_mip_linear, min_mag_mip_linear, anisotropic }; /// the texture addressing mode (U/V/W) of a sampler enum class sampler_address_mode : uint8_t { wrap, clamp, clamp_border, mirror }; /// the comparison function of a sampler enum class sampler_compare_func : uint8_t { never, less, equal, less_equal, greater, not_equal, greater_equal, always, disabled }; /// the border color of a sampler (with address mode clamp_border) enum class sampler_border_color : uint8_t { black_transparent_float, black_transparent_int, black_float, black_int, white_float, white_int }; /// configuration from which a sampler is created, as part of a handle::shader_view struct sampler_config { sampler_filter filter = sampler_filter::min_mag_mip_linear; sampler_address_mode address_u = sampler_address_mode::wrap; sampler_address_mode address_v = sampler_address_mode::wrap; sampler_address_mode address_w = sampler_address_mode::wrap; float min_lod = 0.f; float max_lod = 100000.f; float lod_bias = 0.f; ///< offset from the calculated MIP level (sampled = calculated + lod_bias) uint32_t max_anisotropy = 16u; ///< maximum amount of anisotropy in [1, 16], req. sampler_filter::anisotropic sampler_compare_func compare_func = sampler_compare_func::disabled; sampler_border_color border_color = sampler_border_color::white_float; ///< the border color to use, req. sampler_address_mode::clamp_border void init_default(sampler_filter filter, uint32_t anisotropy = 16u, sampler_address_mode address_mode = sampler_address_mode::wrap) { this->filter = filter; address_u = address_mode; address_v = address_mode; address_w = address_mode; min_lod = 0.f; max_lod = 100000.f; lod_bias = 0.f; max_anisotropy = anisotropy; compare_func = sampler_compare_func::disabled; border_color = sampler_border_color::white_float; } sampler_config(sampler_filter filter, uint32_t anisotropy = 16u, sampler_address_mode address_mode = sampler_address_mode::wrap) { init_default(filter, anisotropy, address_mode); } sampler_config() = default; }; /// the structure of vertices a handle::pipeline_state takes in enum class primitive_topology : uint8_t { triangles, lines, points, patches }; /// the depth function a handle::pipeline_state is using enum class depth_function : uint8_t { none, less, less_equal, greater, greater_equal, equal, not_equal, always, never }; /// the face culling mode a handle::pipeline_state is using enum class cull_mode : uint8_t { none, back, front }; /// configuration for creation of a (graphics) handle::pipeline_state struct pipeline_config { primitive_topology topology = primitive_topology::triangles; depth_function depth = depth_function::none; bool depth_readonly = false; cull_mode cull = cull_mode::none; int32_t samples = 1; bool conservative_raster = false; bool frontface_counterclockwise = true; // TODO: this default should be flipped bool wireframe = false; }; /// operation to perform on render targets upon render pass begin enum class rt_clear_type : uint8_t { clear, dont_care, load }; /// value to clear a render target with struct rt_clear_value { uint8_t red_or_depth = 0; uint8_t green_or_stencil = 0; uint8_t blue = 0; uint8_t alpha = 0; rt_clear_value() = default; rt_clear_value(float r, float g, float b, float a) : red_or_depth(uint8_t(r * 255)), green_or_stencil(uint8_t(g * 255)), blue(uint8_t(b * 255)), alpha(uint8_t(a * 255)) { } rt_clear_value(float depth, uint8_t stencil) : red_or_depth(uint8_t(depth * 255)), green_or_stencil(stencil), blue(0), alpha(0) {} static rt_clear_value from_uint(uint32_t value) { rt_clear_value res; res.red_or_depth = uint8_t(value >> 24); res.green_or_stencil = uint8_t(value >> 16); res.blue = uint8_t(value >> 8); res.alpha = uint8_t(value); return res; } }; /// blending logic operation a (graphics) handle::pipeline_state performs on its render targets enum class blend_logic_op : uint8_t { no_op, op_clear, op_set, op_copy, op_copy_inverted, op_invert, op_and, op_nand, op_and_inverted, op_and_reverse, op_or, op_nor, op_xor, op_or_reverse, op_or_inverted, op_equiv }; /// blending operation a (graphics) handle::pipeline_state performs on a specific render target slot enum class blend_op : uint8_t { op_add, op_subtract, op_reverse_subtract, op_min, op_max }; /// the source or destination blend factor of a blending operation on a specific render target slot enum class blend_factor : uint8_t { zero, one, src_color, inv_src_color, src_alpha, inv_src_alpha, dest_color, inv_dest_color, dest_alpha, inv_dest_alpha }; struct blend_state { blend_factor blend_color_src = blend_factor::one; blend_factor blend_color_dest = blend_factor::zero; blend_op blend_op_color = blend_op::op_add; blend_factor blend_alpha_src = blend_factor::one; blend_factor blend_alpha_dest = blend_factor::zero; blend_op blend_op_alpha = blend_op::op_add; public: blend_state() = default; blend_state(blend_factor blend_color_src, // blend_factor blend_color_dest, blend_op blend_op_color, blend_factor blend_alpha_src, blend_factor blend_alpha_dest, blend_op blend_op_alpha) : blend_color_src(blend_color_src), // blend_color_dest(blend_color_dest), blend_op_color(blend_op_color), blend_alpha_src(blend_alpha_src), blend_alpha_dest(blend_alpha_dest), blend_op_alpha(blend_op_alpha) { } blend_state(blend_factor blend_color_src, // blend_factor blend_color_dest, blend_factor blend_alpha_src, blend_factor blend_alpha_dest) : blend_color_src(blend_color_src), // blend_color_dest(blend_color_dest), blend_op_color(blend_op::op_add), blend_alpha_src(blend_alpha_src), blend_alpha_dest(blend_alpha_dest), blend_op_alpha(blend_op::op_add) { } blend_state(blend_factor blend_src, // blend_factor blend_dest, blend_op blend_op = blend_op::op_add) : blend_color_src(blend_src), // blend_color_dest(blend_dest), blend_op_color(blend_op), blend_alpha_src(blend_src), blend_alpha_dest(blend_dest), blend_op_alpha(blend_op) { } /// blend state for additive blending "src + dest" static blend_state additive() { return blend_state(blend_factor::one, blend_factor::one); } /// blend state for multiplicative blending "src * dest" static blend_state multiplicative() { return blend_state(blend_factor::dest_color, blend_factor::zero, blend_factor::dest_alpha, blend_factor::zero); } /// blend state for normal alpha blending "mix(dest, src, src.a)" static blend_state alpha_blending() { return blend_state(blend_factor::src_alpha, blend_factor::inv_src_alpha); } /// blend state for premultiplied alpha blending "dest * (1 - src.a) + src" static blend_state alpha_blending_premultiplied() { return blend_state(blend_factor::one, blend_factor::inv_src_alpha); } }; /// the blending configuration for a specific render target slot of a (graphics) handle::pipeline_state struct render_target_config { format fmt = format::rgba8un; bool blend_enable = false; blend_state state; }; /// the type of a handle::query_range enum class query_type : uint8_t { timestamp, occlusion, pipeline_stats }; /// a single signal- or wait operation on a fence struct fence_operation { handle::fence fence = handle::null_fence; uint64_t value = 0; }; /// indirect draw command, as it is laid out in a GPU buffer struct gpu_indirect_command_draw { uint32_t num_vertices = 0; uint32_t num_instances = 0; uint32_t vertex_offset = 0; uint32_t instance_offset = 0; }; /// indirect indexed draw command, as it is laid out in a GPU buffer struct gpu_indirect_command_draw_indexed { uint32_t num_indices = 0; uint32_t num_instances = 0; uint32_t index_offset = 0; int32_t vertex_offset = 0; uint32_t instance_offset = 0; }; /// indirect compute dispatch command, as it is laid out in a GPU buffer struct gpu_indirect_command_dispatch { uint32_t dispatch_x = 0; uint32_t dispatch_y = 0; uint32_t dispatch_z = 0; }; struct resource_usage_flags { enum : uint32_t { none = 0, allow_uav = 1 << 0, allow_render_target = 1 << 1, allow_depth_stencil = 1 << 2, deny_shader_resource = 1 << 3, use_optimized_clear_value = 1 << 4, }; }; using resource_usage_flags_t = uint32_t; // PHI_DEFINE_FLAG_OPERATORS(resource_usage_flags, uint32_t) /// flags to configure the building process of a raytracing acceleration structure enum class accel_struct_build_flags : uint8_t { allow_update, allow_compaction, prefer_fast_trace, prefer_fast_build, minimize_memory }; PHI_DEFINE_FLAG_TYPE(accel_struct_build_flags_t, accel_struct_build_flags, 8); // these flags align exactly with both vulkan and d3d12, and are not translated struct accel_struct_instance_flags { enum : uint32_t { none = 0, triangle_cull_disable = 1 << 0, triangle_front_counterclockwise = 1 << 1, force_opaque = 1 << 2, force_no_opaque = 1 << 3 }; }; using accel_struct_instance_flags_t = uint32_t; /// bottom level accel struct instance within a top level accel struct (layout dictated by DXR/Vulkan RT Extension) struct accel_struct_instance { /// Transposed transform matrix, containing only the top 3 rows (laid out as three 4-vectors) float transposed_transform[12]; /// Instance id - arbitrary value, accessed in shaders via `InstanceID()` (HLSL) uint32_t instance_id : 24; /// Visibility mask - matched against `InstanceInclusionMask` parameter in `TraceRays(..)` (HLSL) uint32_t visibility_mask : 8; /// Index of the hit group which will be invoked when a ray hits the instance uint32_t hit_group_index : 24; /// Instance flags, such as culling accel_struct_instance_flags_t flags : 8; /// Opaque handle of the bottom-level acceleration structure, /// as received from `out_native_handle` in `createBottomLevelAccelStruct` (phi Backend) uint64_t native_bottom_level_as_handle; }; static_assert(sizeof(accel_struct_instance) == 64, "accel_struct_instance compiles to incorrect size"); struct buffer_address { handle::resource buffer = handle::null_resource; uint32_t offset_bytes = 0; }; struct buffer_range { handle::resource buffer = handle::null_resource; uint32_t offset_bytes = 0; uint32_t size_bytes = 0; }; struct buffer_range_and_stride { handle::resource buffer = handle::null_resource; uint32_t offset_bytes = 0; uint32_t size_bytes = 0; uint32_t stride_bytes = 0; }; /// the sizes required for the four sections of a raytracing shader table struct shader_table_strides { // ray_gen: record size uint32_t size_ray_gen = 0; // miss, hitgroup, callable: full sizes and strides (record sizes) uint32_t size_miss = 0; uint32_t stride_miss = 0; uint32_t size_hit_group = 0; uint32_t stride_hit_group = 0; uint32_t size_callable = 0; uint32_t stride_callable = 0; }; struct vram_state_info { // OS-provided VRAM budget in bytes, usage should stay below this uint64_t os_budget_bytes = 0; uint64_t current_usage_bytes = 0; uint64_t available_for_reservation_bytes = 0; uint64_t current_reservation_bytes = 0; }; } // namespace phi
28.575342
162
0.689477
[ "geometry", "render", "transform" ]
ad76400bdbcc2e48a457c99715b9d937f494cc50
2,702
cpp
C++
include/util/ShadowMap.cpp
hvidal/GameEngine3D
1794ad891d2200260be935283645a03af3ebcfcc
[ "MIT" ]
6
2020-07-03T21:14:56.000Z
2021-11-11T09:37:40.000Z
include/util/ShadowMap.cpp
hvidal/GameEngine3D
1794ad891d2200260be935283645a03af3ebcfcc
[ "MIT" ]
null
null
null
include/util/ShadowMap.cpp
hvidal/GameEngine3D
1794ad891d2200260be935283645a03af3ebcfcc
[ "MIT" ]
2
2020-08-15T22:37:21.000Z
2021-01-17T11:31:27.000Z
#include "ShadowMap.h" #include "Texture.h" #include "math/Matrix4x4.h" const std::string& ShadowMap::SERIALIZE_ID = "ShadowMap"; //----------------------------------------------------------------------------- ShadowMap::ShadowMap(GLuint slot, unsigned int size) { mDepthTexture = std::make_unique<Texture>(slot, GL_DEPTH_COMPONENT, GL_DEPTH_COMPONENT, size, size, std::vector<Uint32>()); mDepthTexture->linear()->clampToEdge()->image()->unbind(); mFBO = std::make_unique<FrameBuffer>(); FrameBuffer::end(); static constexpr const float range = 200.0f; mProjectionMatrix.ortho(-range, range, -range, range, 0.f, 10000.f); } ShadowMap::~ShadowMap() { Log::debug("Deleting ShadowMap"); } void ShadowMap::start(const btVector3& lightPosition, const btVector3& targetPosition, const btVector3& up) { mIsRendering = true; glUseProgram(0); mFBO->startDepth(mDepthTexture.get()); mViewMatrix.lookAt(lightPosition, targetPosition, up); glCullFace(GL_FRONT); glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE); } void ShadowMap::end() { setTextureMatrix(); mFBO->end(); glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE); glCullFace(GL_BACK); mIsRendering = false; } void ShadowMap::setVars(IShader* shader) const { shader->set("shadowMVP", mShadowMVP); shader->set("shadowMap", mDepthTexture.get()); shader->set("shadowSize", static_cast<float>(mDepthTexture->getWidth())); } void ShadowMap::setMatrices(IShader *shader) const { shader->set("V", mViewMatrix); shader->set("P", mProjectionMatrix); } void ShadowMap::setTextureMatrix() { // Moving from unit cube [-1,1] to [0,1] static constexpr const float bias[16] = { 0.5f, 0.0f, 0.0f, 0.0f, 0.0f, 0.5f, 0.0f, 0.0f, 0.0f, 0.0f, 0.5f, 0.0f, 0.5f, 0.5f, 0.5f, 1.0f }; mShadowMVP = std::move(Matrix4x4(bias).multiplyRight(mProjectionMatrix).multiplyRight(mViewMatrix)); } void ShadowMap::write(ISerializer *serializer) const { serializer->writeBegin(serializeID(), getObjectId()); serializer->write(mDepthTexture->getSlot()); serializer->write(mDepthTexture->getWidth()); } std::pair<std::string, Factory> ShadowMap::factory() { auto factory = [](unsigned long objectId, ISerializer* serializer, std::shared_ptr<IWindow> window) { unsigned int slot, width; serializer->read(slot); serializer->read(width); std::shared_ptr<ShadowMap> o = std::make_shared<ShadowMap>(slot, width); o->setObjectId(objectId); IGameScene* gameScene = window->getGameScene().get(); gameScene->setShadowMap(o); gameScene->addSerializable(o); return o; }; return std::make_pair(SERIALIZE_ID, Factory(factory)); } const std::string& ShadowMap::serializeID() const noexcept { return SERIALIZE_ID; }
26.490196
124
0.698372
[ "vector" ]
ad81e27470a72595d95846376e5f30807b2d613d
3,215
hpp
C++
src/Feedback/FigureFeedback.hpp
cleissom/ofxTableGestures
163819d79203d07aa0f14202c4599deea2f6e5a4
[ "MIT" ]
null
null
null
src/Feedback/FigureFeedback.hpp
cleissom/ofxTableGestures
163819d79203d07aa0f14202c4599deea2f6e5a4
[ "MIT" ]
null
null
null
src/Feedback/FigureFeedback.hpp
cleissom/ofxTableGestures
163819d79203d07aa0f14202c4599deea2f6e5a4
[ "MIT" ]
null
null
null
/* ofxTableGestures (formerly OF-TangibleFramework) Developed for Taller de Sistemes Interactius I Universitat Pompeu Fabra Copyright (c) 2010 Daniel Gallardo Grassot <daniel.gallardo@upf.edu> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef FIGUREFEEDBACK_H_INCLUDED #define FIGUREFEEDBACK_H_INCLUDED #include "ofMain.h" #include "InputGestureDirectObjects.hpp" #include <map> #include "Shapes.hpp" #include "Graphic.hpp" #include "DirectPoint.hpp" class HistoryFigure{ public: DirectObject * dobj; float released_time; float scale_factor; float & OBJECT_DISAPPEAR_TIME; float & OBJECT_SIZE; HistoryFigure(DirectObject * obj): dobj(obj), scale_factor(1), OBJECT_DISAPPEAR_TIME(ofxGlobalConfig::getRef("FEEDBACK:FIGURE:DISAPPEAR",0.25f)), OBJECT_SIZE(ofxGlobalConfig::getRef("FEEDBACK:FIGURE:SIZE",0.00141f)){} void Release(float time){ released_time = time; } void Update(float time){ float elapsed = time - released_time; scale_factor = 1-(float)elapsed / (float)OBJECT_DISAPPEAR_TIME; if (scale_factor <= 0)scale_factor = 0; } bool CanDelete(){ if (scale_factor <= 0) return true; return false; } void draw(){ ofPushMatrix(); ofTranslate(dobj->getX(),dobj->getY()); ofRotateDeg(dobj->angle*180/M_PI); ofScale(scale_factor,scale_factor,1); ofScale(OBJECT_SIZE,OBJECT_SIZE,1); shapes::Figure_shape::Instance().drawShape(dobj->f_id); ofPopMatrix(); } }; class FigureFeedback: public CanDirectObjects < NotificationGraphic > { std::map<int,HistoryFigure*> objects; std::list<HistoryFigure*> to_delete; public: FigureFeedback(); // FigureFeedback(Area * a); ~FigureFeedback(); void newObject(DirectObject * object); void removeObject(DirectObject * object); protected: void draw(); void update(); }; #endif // FIGUREFEEDBACK_H_INCLUDED
34.945652
94
0.668118
[ "object" ]
ad85b272a83322cc9658a26ad5360f4373866736
11,444
cpp
C++
src/particle_filter.cpp
wkhattak/Kidnapped-Vehicle
5af72554923e45507d1be1c88c66eba10cae9248
[ "CC-BY-3.0" ]
null
null
null
src/particle_filter.cpp
wkhattak/Kidnapped-Vehicle
5af72554923e45507d1be1c88c66eba10cae9248
[ "CC-BY-3.0" ]
null
null
null
src/particle_filter.cpp
wkhattak/Kidnapped-Vehicle
5af72554923e45507d1be1c88c66eba10cae9248
[ "CC-BY-3.0" ]
null
null
null
#include <random> #include <algorithm> #include <iostream> #include <numeric> #include <math.h> #include <iostream> #include <sstream> #include <string> #include <iterator> #include "particle_filter.h" using namespace std; void ParticleFilter::init(double x, double y, double theta, double std[]) { // TODO: Set the number of particles. Initialize all particles to first position (based on estimates of // x, y, theta and their uncertainties from GPS) and all weights to 1. // Add random Gaussian noise to each particle. // NOTE: Consult particle_filter.h for more information about this method (and others in this file). num_particles = 150; default_random_engine gen; // Initialize normal distributions for x,y,theta noise normal_distribution<double> dist_n_x(x, std[0]); normal_distribution<double> dist_n_y(y, std[1]); normal_distribution<double> dist_n_theta(theta, std[2]); // Initialize each particle for (int i = 0; i < num_particles; i++) { // Set all weights to 1 double weight = 1.0; weights.push_back(weight); Particle particle; particle.id = i; particle.x = dist_n_x(gen); particle.y = dist_n_y(gen); particle.theta = dist_n_theta(gen); particle.weight = weight; particles.push_back(particle); } is_initialized = true; } void ParticleFilter::prediction(double delta_t, double std_pos[], double velocity, double yaw_rate) { // TODO: Add measurements to each particle and add random Gaussian noise. // NOTE: When adding noise you may find std::normal_distribution and std::default_random_engine useful. // http://en.cppreference.com/w/cpp/numeric/random/normal_distribution // http://www.cplusplus.com/reference/random/default_random_engine/ default_random_engine gen; for (int i = 0; i < num_particles; i++) { // Check if yaw_rate is almost zero if (fabs(yaw_rate) < zero_threshold) { particles[i].x += velocity * cos(particles[i].theta) * delta_t; particles[i].y += velocity * sin(particles[i].theta) * delta_t; } else { particles[i].x += ((velocity/yaw_rate) * (sin(particles[i].theta + (yaw_rate * delta_t)) - sin(particles[i].theta))); particles[i].y += ((velocity/yaw_rate) * (cos(particles[i].theta) - cos(particles[i].theta + (yaw_rate * delta_t)))); particles[i].theta += (yaw_rate * delta_t); } // Add random noise based on updated particle position normal_distribution<double> dist_n_x(particles[i].x, std_pos[0]); normal_distribution<double> dist_n_y(particles[i].y, std_pos[1]); normal_distribution<double> dist_n_theta(particles[i].theta, std_pos[2]); particles[i].x = dist_n_x(gen); particles[i].y = dist_n_y(gen); particles[i].theta = dist_n_theta(gen); } } void ParticleFilter::dataAssociation(std::vector<LandmarkObs> predicted, std::vector<LandmarkObs>& observations) { // TODO: Find the predicted measurement that is closest to each observed measurement and assign the // observed measurement to this particular landmark. // NOTE: this method will NOT be called by the grading code. But you will probably find it useful to // implement this method and use it as a helper during the updateWeights phase. for (unsigned int i = 0; i < observations.size(); i++) { // Set distance to max posible for comparison purposes double min_dist = numeric_limits<double>::max(); // Landmark id to be asscoiated with the observation id int landmark_id = -9999999; for (unsigned int j = 0; j < predicted.size(); j++) { // Find distance between landmark & observation double temp_dist = dist(observations[i].x, observations[i].y, predicted[j].x, predicted[j].y); // Pick current landmark if it's the closest so far if (temp_dist < min_dist) { min_dist = temp_dist; landmark_id = predicted[j].id; } } // Assign the closest found landmark id to the observation id observations[i].id = landmark_id; } } void ParticleFilter::updateWeights(double sensor_range, double std_landmark[], const std::vector<LandmarkObs> &observations, const Map &map_landmarks) { // TODO: Update the weights of each particle using a mult-variate Gaussian distribution. You can read // more about this distribution here: https://en.wikipedia.org/wiki/Multivariate_normal_distribution // NOTE: The observations are given in the VEHICLE'S coordinate system. Your particles are located // according to the MAP'S coordinate system. You will need to transform between the two systems. // Keep in mind that this transformation requires both rotation AND translation (but no scaling). // The following is a good resource for the theory: // https://www.willamette.edu/~gorr/classes/GeneralGraphics/Transforms/transforms2d.htm // and the following is a good resource for the actual equation to implement (look at equation // 3.33 // http://planning.cs.uiuc.edu/node99.html double weights_sum = 0.0; for (int i = 0; i < num_particles; i++) { /*************************************************************************************************** * STEP 1: Transform observations' coordinate space to the map's coordinate space ***************************************************************************************************/ vector<LandmarkObs> transf_observs; for (unsigned int j = 0; j < observations.size(); j++) { LandmarkObs transf_observ; transf_observ.id = observations[j].id; transf_observ.x = particles[i].x + (cos(particles[i].theta) * observations[j].x) - (sin(particles[i].theta) * observations[j].y); transf_observ.y = particles[i].y + (sin(particles[i].theta) * observations[j].x) + (cos(particles[i].theta) * observations[j].y); transf_observs.push_back(transf_observ); } /*************************************************************************************************** * STEP 2: Filter out landmarks that are outside the sensor's range of the current particle ***************************************************************************************************/ vector<LandmarkObs> in_range_landmarks; for (unsigned int k = 0; k < map_landmarks.landmark_list.size(); k++) { // Cut down version of Euclidean distance to reduce computation time - NOT Used //if ((fabs((particles[i].x - map_landmarks.landmark_list[k].x_f)) <= sensor_range) && (fabs((particles[i].y - map_landmarks.landmark_list[k].y_f)) <= sensor_range)) { if (dist(particles[i].x, particles[i].y, map_landmarks.landmark_list[k].x_f, map_landmarks.landmark_list[k].y_f) <= sensor_range) { in_range_landmarks.push_back(LandmarkObs {map_landmarks.landmark_list[k].id_i, map_landmarks.landmark_list[k].x_f, map_landmarks.landmark_list[k].y_f}); } } /*************************************************************************************************** * STEP 3: Associate each transformed observation with the closest in-range landmark ***************************************************************************************************/ dataAssociation(in_range_landmarks, transf_observs); /*************************************************************************************************** * STEP 4: Calculate particle weight ***************************************************************************************************/ // Reset particle weight particles[i].weight = 1.0; // Pre-compute for faster execution double std_x_square = pow(std_landmark[0], 2); double std_y_square = pow(std_landmark[1], 2); // Calculate normalization term double gaussian_norm = (1.0/(2.0 * M_PI * std_landmark[0] * std_landmark[1])); // Loop through all obervations and add weight for all associated landmarks for (unsigned int l = 0; l < transf_observs.size(); l++) { double transf_observ_x = transf_observs[l].x; double transf_observ_y = transf_observs[l].y; double transf_observ_id = transf_observs[l].id; double weight = 1.0; for (unsigned int m = 0; m < in_range_landmarks.size(); m++) { if (transf_observ_id == in_range_landmarks[m].id) { weight = gaussian_norm * exp(-1.0 * ((pow((transf_observ_x - in_range_landmarks[m].x), 2)/(2.0 * std_x_square)) + (pow((transf_observ_y - in_range_landmarks[m].y), 2)/(2.0 * std_y_square)))); if (weight < zero_threshold) particles[i].weight *= zero_threshold; else particles[i].weight *= weight; } } } weights_sum += particles[i].weight; } /*************************************************************************************************** * STEP 5: Normalize weights so that their values are between 0-1 (these weights will be used as probabilities during resampling) ***************************************************************************************************/ for (int i = 0; i < num_particles; i++) { particles[i].weight /= weights_sum; // Also update global weight vector for all particles weights[i] = particles[i].weight; } } void ParticleFilter::resample() { // TODO: Resample particles with replacement with probability proportional to their weight. // NOTE: You may find std::discrete_distribution helpful here. // http://en.cppreference.com/w/cpp/numeric/random/discrete_distribution vector<Particle> resampled_particles; // Create a random number generator for selecting a particle index based on particle weight default_random_engine gen; discrete_distribution<int> particle_index(weights.begin(), weights.end()); for (int i = 0; i < num_particles; i++) { resampled_particles.push_back(particles[particle_index(gen)]); } // Replace with resampled particles particles = resampled_particles; } Particle ParticleFilter::SetAssociations(Particle& particle, const std::vector<int>& associations, const std::vector<double>& sense_x, const std::vector<double>& sense_y) { //particle: the particle to assign each listed association, and association's (x,y) world coordinates mapping to // associations: The landmark id that goes along with each listed association // sense_x: the associations x mapping already converted to world coordinates // sense_y: the associations y mapping already converted to world coordinates particle.associations = associations; particle.sense_x = sense_x; particle.sense_y = sense_y; return particle; } string ParticleFilter::getAssociations(Particle best) { vector<int> v = best.associations; stringstream ss; copy( v.begin(), v.end(), ostream_iterator<int>(ss, " ")); string s = ss.str(); s = s.substr(0, s.length()-1); // get rid of the trailing space return s; } string ParticleFilter::getSenseX(Particle best) { vector<double> v = best.sense_x; stringstream ss; copy( v.begin(), v.end(), ostream_iterator<float>(ss, " ")); string s = ss.str(); s = s.substr(0, s.length()-1); // get rid of the trailing space return s; } string ParticleFilter::getSenseY(Particle best) { vector<double> v = best.sense_y; stringstream ss; copy( v.begin(), v.end(), ostream_iterator<float>(ss, " ")); string s = ss.str(); s = s.substr(0, s.length()-1); // get rid of the trailing space return s; }
45.776
201
0.630898
[ "vector", "transform" ]
ad88e32926bff2bfdefeb7358eada15f8de9b4aa
2,237
cpp
C++
runtime/tests/bitmap_page_alignment_test.cpp
openharmony-gitee-mirror/ark_runtime_core
2e6f195caf482dc9607efda7cfb5cc5f98da5598
[ "Apache-2.0" ]
1
2021-09-09T03:17:23.000Z
2021-09-09T03:17:23.000Z
runtime/tests/bitmap_page_alignment_test.cpp
openharmony-gitee-mirror/ark_runtime_core
2e6f195caf482dc9607efda7cfb5cc5f98da5598
[ "Apache-2.0" ]
null
null
null
runtime/tests/bitmap_page_alignment_test.cpp
openharmony-gitee-mirror/ark_runtime_core
2e6f195caf482dc9607efda7cfb5cc5f98da5598
[ "Apache-2.0" ]
1
2021-09-13T11:21:57.000Z
2021-09-13T11:21:57.000Z
/* * Copyright (c) 2021 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <memory> #include <vector> #include "gtest/gtest.h" #include "bitmap_test_base.h" #include "runtime/mem/gc/bitmap.h" namespace panda::mem { TEST_F(BitmapTest, Init) { const size_t sz = 1_MB; auto bm_ptr = std::make_unique<BitmapWordType[]>(sz >> MemBitmap<>::LOG_BITSPERWORD); MemBitmap<> bm(ToVoidPtr(HEAP_STARTING_ADDRESS), sz, bm_ptr.get()); EXPECT_EQ(bm.Size(), sz); } TEST_F(BitmapTest, ScanRange) { auto heap_begin = HEAP_STARTING_ADDRESS; size_t heap_capacity = 16_MB; auto bm_ptr = std::make_unique<BitmapWordType[]>((heap_capacity >> Bitmap::LOG_BITSPERWORD) / DEFAULT_ALIGNMENT_IN_BYTES); MemBitmap<DEFAULT_ALIGNMENT_IN_BYTES> bm(ToVoidPtr(heap_begin), heap_capacity, bm_ptr.get()); constexpr size_t BIT_SET_RANGE_END = Bitmap::BITSPERWORD * 3; for (size_t j = 0; j < BIT_SET_RANGE_END; ++j) { auto *obj = ToVoidPtr(heap_begin + j * DEFAULT_ALIGNMENT_IN_BYTES); if (ToUintPtr(obj) & BitmapVerify::ADDRESS_MASK_TO_SET) { bm.Set(obj); } } constexpr size_t BIT_VERIFY_RANGE_END = Bitmap::BITSPERWORD * 2; for (size_t i = 0; i < Bitmap::BITSPERWORD; ++i) { auto *start = ToVoidPtr(heap_begin + i * DEFAULT_ALIGNMENT_IN_BYTES); for (size_t j = 0; j < BIT_VERIFY_RANGE_END; ++j) { auto *end = ToVoidPtr(heap_begin + (i + j) * DEFAULT_ALIGNMENT_IN_BYTES); BitmapVerify(&bm, start, end); } } } TEST_F(BitmapTest, VisitorPageAlignment) { RunTestCount<4_KB>(); } TEST_F(BitmapTest, OrderPageAlignment) { RunTestOrder<4_KB>(); } } // namespace panda::mem
30.643836
116
0.688422
[ "vector" ]
ad8db3125330b52453009b46321cb00be7a1869f
3,357
hpp
C++
SarvLibrary/Kmerize/dsk/thirdparty/gatb-core/gatb-core/src/gatb/kmer/impl/DebloomMinimizerAlgorithm.hpp
cwright7101/llvm_sarvavid
7567d617a7be78fecfde71ab04ebd8e9506a64e4
[ "MIT" ]
null
null
null
SarvLibrary/Kmerize/dsk/thirdparty/gatb-core/gatb-core/src/gatb/kmer/impl/DebloomMinimizerAlgorithm.hpp
cwright7101/llvm_sarvavid
7567d617a7be78fecfde71ab04ebd8e9506a64e4
[ "MIT" ]
null
null
null
SarvLibrary/Kmerize/dsk/thirdparty/gatb-core/gatb-core/src/gatb/kmer/impl/DebloomMinimizerAlgorithm.hpp
cwright7101/llvm_sarvavid
7567d617a7be78fecfde71ab04ebd8e9506a64e4
[ "MIT" ]
null
null
null
/***************************************************************************** * GATB : Genome Assembly Tool Box * Copyright (C) 2014 INRIA * Authors: R.Chikhi, G.Rizk, E.Drezen * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. *****************************************************************************/ /** \file DebloomMinimizerAlgorithm.hpp * \date 01/03/2013 * \author edrezen * \brief Debloom algorithm, ie. compute false positive sets for a Bloom filter */ #ifndef _DEBLOOM_MINIMIZER_ALGORITHM_HPP_ #define _DEBLOOM_MINIMIZER_ALGORITHM_HPP_ /********************************************************************************/ #include <gatb/kmer/impl/DebloomAlgorithm.hpp> /********************************************************************************/ namespace gatb { namespace core { namespace kmer { namespace impl { /********************************************************************************/ template<size_t span=KMER_DEFAULT_SPAN> class DebloomMinimizerAlgorithm : public DebloomAlgorithm<span> { public: /** Shortcuts. */ typedef typename kmer::impl::Kmer<span>::ModelCanonical Model; typedef typename kmer::impl::Kmer<span>::Type Type; typedef typename kmer::impl::Kmer<span>::Count Count; /** */ DebloomMinimizerAlgorithm ( tools::storage::impl::Group& bloomGroup, tools::storage::impl::Group& debloomGroup, tools::storage::impl::Partition<Count>* solidIterable, size_t kmerSize, size_t miniSize, size_t max_memory = 0, size_t nb_cores = 0, tools::misc::BloomKind bloomKind = tools::misc::BLOOM_DEFAULT, tools::misc::DebloomKind cascadingKind = tools::misc::DEBLOOM_DEFAULT, const std::string& debloomUri = "debloom", tools::misc::IProperties* options = 0, tools::storage::impl::Group* minimizersGroup = 0 ); /** */ DebloomMinimizerAlgorithm (tools::storage::impl::Storage& storage); /** */ const char* getClassName() const { return "DebloomMinimizerAlgorithm"; } private: /** */ void execute_aux ( tools::misc::IProperties* bloomProps, tools::misc::IProperties* cfpProps, u_int64_t& totalSizeBloom, u_int64_t& totalSizeCFP ); tools::storage::impl::Group* _groupMinimizers; }; /********************************************************************************/ } } } } /* end of namespaces. */ /********************************************************************************/ #endif /* _DEBLOOM_MINIMIZER_ALGORITHM_HPP_ */
36.89011
82
0.541257
[ "model" ]
ad8eb666b9f6bb78baa8fdfe806ecb7deb6f5e1d
7,261
hpp
C++
include/Hord/Object/Unit.hpp
komiga/hord
32be8ffb11bd74959c5cd5254e36d87f224b6f60
[ "MIT" ]
null
null
null
include/Hord/Object/Unit.hpp
komiga/hord
32be8ffb11bd74959c5cd5254e36d87f224b6f60
[ "MIT" ]
null
null
null
include/Hord/Object/Unit.hpp
komiga/hord
32be8ffb11bd74959c5cd5254e36d87f224b6f60
[ "MIT" ]
null
null
null
/** @copyright MIT license; see @ref index or the accompanying LICENSE file. @file @brief Object base class. @ingroup object */ #pragma once #include <Hord/config.hpp> #include <Hord/aux.hpp> #include <Hord/traits.hpp> #include <Hord/String.hpp> #include <Hord/utility.hpp> #include <Hord/IO/Defs.hpp> #include <Hord/IO/PropStateStore.hpp> #include <Hord/IO/PropStream.hpp> #include <Hord/Data/Metadata.hpp> #include <Hord/Object/Defs.hpp> namespace Hord { namespace Object { // Forward declarations class Unit; /** @addtogroup object @{ */ /** Base object. */ class Unit { public: /** Ensure traits for deriving classes. @tparam D Deriving class. */ template< class D > struct ensure_traits : traits::require_t< D, tw::capture_post<std::is_base_of, Object::Unit>::type, std::is_nothrow_destructible, tw::is_fully_moveable > , traits::disallow_t< D, tw::is_copyable > {}; /** ID set. */ using id_set_type = aux::unordered_set< Object::ID >; private: Object::TypeInfo const* m_type_info; Object::ID m_id; IO::PropStateStore m_prop_states; id_set_type m_children{}; // runtime Object::ID m_parent; String m_slug{}; HashValue m_slug_hash{HASH_EMPTY}; Data::Metadata m_metadata{}; String m_scratch_space{}; Unit() = delete; Unit(Unit const&) = delete; Unit& operator=(Unit const&) = delete; protected: /** @name Implementation */ /// @{ /** deserialize() implementation. @note This is only called for the primary and auxiliary props. @note Implementation must ensure state is retained if it throws an exception. Object::Unit will not throw an exception after a call to this function. @throws Error{ErrorCode::serialization_io_failed} @throws Error{ErrorCode::serialization_data_malformed} */ virtual void deserialize_impl( IO::InputPropStream& prop_stream ) = 0; /** serialize() implementation. @note This is only called for the primary and auxiliary props. @note Implementation must ensure state is retained if it throws an exception. Object::Unit will not throw an exception after a call to this function. @throws Error{ErrorCode::serialization_io_failed} */ virtual void serialize_impl( IO::OutputPropStream& prop_stream ) const = 0; /// @} /** @name Special member functions */ /// @{ public: /** Destructor. */ virtual ~Unit() noexcept = 0; protected: /** Move constructor. */ Unit(Unit&&); /** Move assignment operator. */ Unit& operator=(Unit&&); /** Constructor with type info, %ID, and parent. @post @code storage_state() == (id() == Object::ID_NULL ? IO::StorageState::null : IO::StorageState::placeholder ) @endcode */ Unit( Object::TypeInfo const& tinfo, Object::ID const id, Object::ID const parent ) noexcept; /// @} public: /** @name Properties */ /// @{ /** Get type info. */ Object::TypeInfo const& type_info() const noexcept { return *m_type_info; } /** Get type. */ Object::Type type() const noexcept { return m_type_info->type; } /** Get base type. */ Object::BaseType base_type() const noexcept { return type().base(); } /** Get unit type. */ Object::UnitType unit_type() const noexcept { return type().unit(); } /** Get unit name. */ char const* unit_name() const noexcept { return m_type_info->unit_name; } /** Get prop state store. */ IO::PropStateStore const& prop_states() const noexcept { return m_prop_states; } /** Get mutable prop state store. */ IO::PropStateStore& prop_states() noexcept { return m_prop_states; } /** Get children set. */ id_set_type const& children() const noexcept { return m_children; } /** Get mutable children set. */ id_set_type& children() noexcept { return m_children; } /** Set ID. */ void set_id( Object::ID const id ) noexcept { m_id = id; } /** Get ID. */ Object::ID id() const noexcept { return m_id; } /** Check if object is null. @note An object is null iff its ID is Object::ID_NULL. */ bool is_null() const noexcept { return Object::ID_NULL == m_id; } /** Get storage state. @sa IO::StorageState */ IO::StorageState storage_state() const noexcept { return is_null() ? IO::StorageState::null : m_prop_states.all_original() ? IO::StorageState::original : m_prop_states.any_modified() ? IO::StorageState::modified : !m_slug.empty() ? IO::StorageState::placeholder_identified : IO::StorageState::placeholder ; } /** Set parent. @warning This should not be used directly. See the referenced functions. @sa Object::unset_parent(), Object::set_parent() */ void set_parent( Object::ID const parent ) noexcept { m_parent = parent; } /** Get parent. */ Object::ID parent() const noexcept { return m_parent; } /** Set slug. @warning This property is truncated to 255 code units. */ void set_slug( String slug ) noexcept; /** Get slug. */ String const& slug() const noexcept { return m_slug; } /** Get slug hash. */ HashValue slug_hash() const noexcept { return m_slug_hash; } /** Get metadata. */ Data::Metadata const& metadata() const noexcept { return m_metadata; } /** Get mutable metadata. */ Data::Metadata& metadata() noexcept { return m_metadata; } /** Set scratch space. */ void set_scratch_space( String scratch_space ) noexcept { m_scratch_space.assign(std::move(scratch_space)); } /** Get scratch space. */ String const& scratch_space() const noexcept { return m_scratch_space; } /** Get mutable scratch space. */ String& scratch_space() noexcept { return m_scratch_space; } /// @} /** @name Children */ /// @{ /** Check if the object has a child. */ bool has_child( Object::ID const id ) const noexcept(noexcept(m_children.find(id))) { return id.is_reserved() ? false : m_children.cend() != m_children.find(id) ; } /// @} /** @name Serialization */ /// @{ /** Deserialize prop. @note State will be retained if an exception is thrown. @throws Error{ErrorCode::serialization_prop_unsupplied} If the object does not supply the prop that @a prop_stream represents. @throws Error{ErrorCode::serialization_io_failed} If an input operation failed. @throws Error{ErrorCode::serialization_data_malformed} If malformed data was encountered. */ void deserialize( IO::InputPropStream& prop_stream ); /** Serialize prop. @note State will be retained if an exception is thrown. @warning If ErrorCode::serialization_io_failed is thrown, the prop stream likely contains malformed data. @throws Error{ErrorCode::serialization_prop_unsupplied} If the object does not supply the prop that @a prop_stream represents. @throws Error{ErrorCode::serialization_prop_improper_state} If the state for the prop that @a prop_stream represents is uninitialized. @throws Error{ErrorCode::serialization_io_failed} If an output operation failed. */ void serialize( IO::OutputPropStream& prop_stream ); /// @} }; /** @} */ // end of doc-group object } // namespace Object template struct traits::require_t< Object::Unit, std::has_virtual_destructor >; } // namespace Hord
16.577626
72
0.674976
[ "object" ]
ad8fccbaac9310314235cd7a4b66e53bbf52b21c
214
hpp
C++
src/utils/extents.hpp
lanl/shoccs
6fd72a612e872df62749eec6b010bd1f1e5ee1e7
[ "BSD-3-Clause" ]
null
null
null
src/utils/extents.hpp
lanl/shoccs
6fd72a612e872df62749eec6b010bd1f1e5ee1e7
[ "BSD-3-Clause" ]
2
2022-02-18T22:43:06.000Z
2022-02-18T22:43:19.000Z
src/utils/extents.hpp
lanl/shoccs
6fd72a612e872df62749eec6b010bd1f1e5ee1e7
[ "BSD-3-Clause" ]
null
null
null
#pragma once #include "index_extents.hpp" #include "mesh/mesh_types.hpp" #include <sol/forward.hpp> namespace ccs { std::optional<std::pair<index_extents, domain_extents>> extents_from_lua(const sol::table&); }
16.461538
55
0.761682
[ "mesh" ]
ad920ca5cc5ab22501258b4657830540fb9aaaec
2,187
cpp
C++
src/goto-instrument/source_lines.cpp
clayne/cbmc
e78eacff0d84646becbdd8287386d489ae268b90
[ "BSD-4-Clause" ]
null
null
null
src/goto-instrument/source_lines.cpp
clayne/cbmc
e78eacff0d84646becbdd8287386d489ae268b90
[ "BSD-4-Clause" ]
null
null
null
src/goto-instrument/source_lines.cpp
clayne/cbmc
e78eacff0d84646becbdd8287386d489ae268b90
[ "BSD-4-Clause" ]
null
null
null
/*******************************************************************\ Module: Source Lines Author: Mark R. Tuttle \*******************************************************************/ /// \file /// Set of source code lines contributing to a basic block #include "source_lines.h" #include <util/format_number_range.h> #include <util/range.h> #include <util/source_location.h> #include <util/string_utils.h> #include <sstream> void source_linest::insert(const source_locationt &loc) { if(loc.get_file().empty() || loc.is_built_in()) return; const std::string &file = id2string(loc.get_file()); // the function of a source location can fail to be set const std::string &func = id2string(loc.get_function()); if(loc.get_line().empty()) return; mp_integer line = string2integer(id2string(loc.get_line())); block_lines[file][func].insert(line); } std::string source_linest::to_string() const { std::stringstream result; const auto full_map = make_range(block_lines) .map([&](const block_linest::value_type &file_entry) { std::stringstream ss; const auto map = make_range(file_entry.second) .map([&](const function_linest::value_type &pair) { std::vector<mp_integer> line_numbers( pair.second.begin(), pair.second.end()); return file_entry.first + ':' + pair.first + ':' + format_number_range(line_numbers); }); join_strings(ss, map.begin(), map.end(), "; "); return ss.str(); }); join_strings(result, full_map.begin(), full_map.end(), "; "); return result.str(); } irept source_linest::to_irep() const { irept result; for(const auto &file_entry : block_lines) { irept file_result; for(const auto &lines_entry : file_entry.second) { std::vector<mp_integer> line_numbers( lines_entry.second.begin(), lines_entry.second.end()); file_result.set(lines_entry.first, format_number_range(line_numbers)); } result.add(file_entry.first, std::move(file_result)); } return result; }
28.776316
79
0.587106
[ "vector" ]
74f57d0e4912386209c815b7b1732cae7a945ae5
4,591
cpp
C++
src/cppipc/common/message_types.cpp
shreyasvj25/turicreate
32e84ca16aef8d04aff3d49ae9984bd49326bffd
[ "BSD-3-Clause" ]
1
2018-12-15T20:03:51.000Z
2018-12-15T20:03:51.000Z
src/cppipc/common/message_types.cpp
shreyasvj25/turicreate
32e84ca16aef8d04aff3d49ae9984bd49326bffd
[ "BSD-3-Clause" ]
3
2021-09-08T02:18:00.000Z
2022-03-12T00:39:44.000Z
src/cppipc/common/message_types.cpp
ZeroInfinite/turicreate
dd210c2563930881abd51fd69cb73007955b33fd
[ "BSD-3-Clause" ]
1
2019-06-01T18:49:28.000Z
2019-06-01T18:49:28.000Z
/* Copyright © 2017 Apple Inc. All rights reserved. * * Use of this source code is governed by a BSD-3-clause license that can * be found in the LICENSE.txt file or at https://opensource.org/licenses/BSD-3-Clause */ #include <cppipc/common/message_types.hpp> #include <serialization/serialization_includes.hpp> namespace cppipc { void call_message::clear() { if (!zmqbodyused) { if (body) free((void*)body); } body = NULL; objectid = 0; zmqbodyused = false; } bool call_message::construct(nanosockets::zmq_msg_vector& msg) { clear(); if(msg.size() != 4) return false; // first block is the object ID if (msg.front()->length() != sizeof(size_t)) return false; objectid = *reinterpret_cast<const size_t*>(msg.front()->data()); msg.pop_front_and_free(); // second block is the property bag const char* propertybuf = msg.front()->data(); size_t propertybuflen = msg.front()->length(); turi::iarchive iarc(propertybuf, propertybuflen); iarc >> properties; msg.pop_front_and_free(); // third block is the function name function_name = *(msg.front()); msg.pop_front_and_free(); bodybuf = std::move(*msg.front()); body = bodybuf.data(); bodylen = bodybuf.size(); zmqbodyused = true; msg.pop_front_and_free(); // no free this time since we are keeping a pointer return true; } void call_message::emit(nanosockets::zmq_msg_vector& msg) { assert(zmqbodyused == false); // first block is the object ID nanosockets::nn_msg_t* z_objectid = msg.insert_back(); z_objectid->assign(sizeof(size_t), 8); (*reinterpret_cast<size_t*>(&((*z_objectid)[0]))) = objectid; // second block is the property bag turi::oarchive oarc; oarc << properties; nanosockets::nn_msg_t* z_propertybag = msg.insert_back(); z_propertybag->assign(oarc.buf, oarc.off); // third block is the function name nanosockets::nn_msg_t* z_function_name = msg.insert_back(); z_function_name->assign(function_name); // fourth block is the serialization body nanosockets::nn_msg_t* z_body = msg.insert_back(); if (body != NULL) { z_body->assign(body, bodylen); } clear(); } void reply_message::clear() { if (!zmqbodyused) { if (body) free((void*)body); } body = NULL; bodylen = 0; zmqbodyused = false; } bool reply_message::construct(nanosockets::zmq_msg_vector& msg) { clear(); if(msg.size() != 3) return false; // first block is the reply status if (msg.front()->length() != sizeof(reply_status)) return false; status = *reinterpret_cast<const reply_status*>(msg.front()->data()); msg.pop_front_and_free(); // second block is the property bag const char* propertybuf = msg.front()->data(); size_t propertybuflen = msg.front()->length(); turi::iarchive iarc(propertybuf, propertybuflen); iarc >> properties; msg.pop_front_and_free(); // third block is the serialization body bodybuf = std::move(*msg.front()); body = &(bodybuf[0]); bodylen = bodybuf.length(); zmqbodyused = true; msg.pop_front_and_free(); // no free this time since we are keeping a pointer return true; } void reply_message::emit(nanosockets::zmq_msg_vector& msg) { assert(zmqbodyused == false); // first block is the reply status nanosockets::nn_msg_t* z_status = msg.insert_back(); z_status->assign(sizeof(reply_status), 0); (*reinterpret_cast<reply_status*>(&((*z_status)[0]))) = status; // second block is the property bag turi::oarchive oarc; oarc << properties; nanosockets::nn_msg_t* z_propertybag = msg.insert_back(); z_propertybag->assign(oarc.buf, oarc.off); // third block is the serialization body nanosockets::nn_msg_t* z_body= msg.insert_back(); if (body != NULL) { z_body->assign(body, bodylen); } clear(); } EXPORT std::string reply_status_to_string(reply_status status) { switch(status) { case reply_status::OK: return "OK"; case reply_status::BAD_MESSAGE: return "Bad message"; case reply_status::NO_OBJECT: return "No such object ID"; case reply_status::NO_FUNCTION: return "No such function"; case reply_status::COMM_FAILURE: return "Communication Failure"; case reply_status::AUTH_FAILURE: return "Authorization Failure"; case reply_status::EXCEPTION: return "Runtime Exception"; case reply_status::IO_ERROR: return "IO Exception"; case reply_status::TYPE_ERROR: return "Type Exception"; case reply_status::MEMORY_ERROR: return "Memory Exception"; case reply_status::INDEX_ERROR: return "Index Exception"; default: return ""; } } } // cppipc
28.515528
86
0.692442
[ "object" ]
74ff1ac2c93e8351efa6b2cd32c4ecb0ea72f1fb
499
hpp
C++
Inventario/node_modules/node-sass/src/libsass/src/backtrace.hpp
alvarosanmartinh/Duoc-Inventario
e46a57b8cb4071800ee2b494b39e96a31be69c49
[ "MIT" ]
null
null
null
Inventario/node_modules/node-sass/src/libsass/src/backtrace.hpp
alvarosanmartinh/Duoc-Inventario
e46a57b8cb4071800ee2b494b39e96a31be69c49
[ "MIT" ]
null
null
null
Inventario/node_modules/node-sass/src/libsass/src/backtrace.hpp
alvarosanmartinh/Duoc-Inventario
e46a57b8cb4071800ee2b494b39e96a31be69c49
[ "MIT" ]
null
null
null
#ifndef SASS_BACKTRACE_H #define SASS_BACKTRACE_H #include <vector> #include <sstream> #include "file.hpp" #include "position.hpp" namespace Sass { struct Backtrace { ParserState pstate; std::string caller; Backtrace(ParserState pstate, std::string c = "") : pstate(pstate), caller(c) { } }; typedef std::vector<Backtrace> Backtraces; const std::string traces_to_string(Backtraces traces, std::string indent = "\t"); } #endif
16.633333
84
0.641283
[ "vector" ]
2d05576c2750925058b4bc36ac1e2d72ba2071bc
6,027
cc
C++
utils/print.cc
abcinje/FAWN-KV
6c557b3793010eb0b2f08d4bd0d47b5e68801080
[ "Apache-2.0" ]
null
null
null
utils/print.cc
abcinje/FAWN-KV
6c557b3793010eb0b2f08d4bd0d47b5e68801080
[ "Apache-2.0" ]
null
null
null
utils/print.cc
abcinje/FAWN-KV
6c557b3793010eb0b2f08d4bd0d47b5e68801080
[ "Apache-2.0" ]
null
null
null
/* -*- Mode: C++; c-basic-offset: 4; indent-tabs-mode: nil -*- */ #include <iostream> #include <stdio.h> #include <unistd.h> #include "print.h" void bytes_into_hex_string(const u_char *data, u_int len, string& dststr) { static const char hexes[] = "0123456789ABCDEF"; dststr.reserve(dststr.size() + len*2); for (u_int i = 0; i < len; i++) { dststr.push_back(hexes[data[i] >> 4]); dststr.push_back(hexes[data[i] & 0xf]); } } void bytes_into_hex_string_trunc0s(const u_char *data, u_int len, string& dststr) { static const char hexes[] = "0123456789ABCDEF"; dststr.reserve(dststr.size() + len*2); int last_zero = -1; for (u_int i = 0; i < len; i++) { dststr.push_back(hexes[data[i] >> 4]); dststr.push_back(hexes[data[i] & 0xf]); if (data[i] == 0) { if (last_zero == -1) { last_zero = i; } } else { last_zero = -1; } } if (last_zero != -1) { dststr.erase(last_zero*2); dststr +="...0"; } } /* May incur a copy; don't use on high-performance path unless you know * str is refcounted */ string bytes_to_hex(const u_char* data, u_int len) { string r; //bytes_into_hex_string(data, len, r); bytes_into_hex_string_trunc0s(data, len, r); return r; } string bytes_to_hex(const string& s) { return bytes_to_hex((const u_char *)s.data(), s.size()); } int get_digit_value(char digit) { if (isdigit(digit)) { return digit - '0'; } else if (digit >= 'A' && digit <= 'F') { return digit - 'A' + 10; } else if (digit >= 'a' && digit <= 'f') { return digit - 'a' + 10; } else // illegal digit { return -1; } } // assumes 2 character string with legal hex digits string* hex_string_to_bytes(const u_char* hex_num, u_int len) { string* p_ret = new string(); for (u_int i = 0; i < len/2; i++) { char high = hex_num[i]; char low = hex_num[i+1]; int low_val = get_digit_value(low); //convert low to number from 0 to 15 int high_val = get_digit_value(high); //convert high to number from 0 to 15 if ((low_val < 0) || (high_val < 0)) { // Narf! delete p_ret; return NULL; } char ch = low_val + 16 * high_val; p_ret->append(1, ch); } return p_ret; } /* * print data in rows of 16 bytes: offset hex ascii * * 00000 47 45 54 20 2f 20 48 54 54 50 2f 31 2e 31 0d 0a GET / HTTP/1.1.. */ void print_hex_ascii_line(const u_char *payload, u_int len, u_int offset) { /* offset */ printf("%05d ", offset); /* hex */ const u_char *ch = payload; for (u_int i = 0; i < len; i++) { printf("%02x ", *ch); ch++; /* print extra space after 8th byte for visual aid */ if (i == 7) printf(" "); } /* print space to handle line less than 8 bytes */ if (len < 8) printf(" "); /* fill hex gap with spaces if not full line */ if (len < 16) { int gap = 16 - len; for (int i = 0; i < gap; i++) { printf(" "); } } printf(" "); /* ascii (if printable) */ ch = payload; for (u_int i = 0; i < len; i++) { if (isprint(*ch)) printf("%c", *ch); else printf("."); ch++; } printf("\n"); return; } void print_payload(const string &str) { print_payload((const u_char*)str.data(), str.size()); } /* * print packet payload data (avoid printing binary data) */ void print_payload(const u_char *payload, u_int len) { const u_int line_width = 16; /* number of bytes per line */ u_int len_rem = len; u_int offset = 0; while (len_rem > line_width) { int line_len = line_width % len_rem; print_hex_ascii_line(payload + offset, line_len, offset); len_rem -= line_len; offset += line_width; } /* Might have left a partial line left. */ if (len_rem > 0) { print_hex_ascii_line(payload + offset, len_rem, offset); } return; } void tokenize(const string& str, vector<string>& tokens, const string& delimiters) { // Skip delimiters at beginning. string::size_type lastPos = str.find_first_not_of(delimiters, 0); // Find first "non-delimiter". string::size_type pos = str.find_first_of(delimiters, lastPos); while (string::npos != pos || string::npos != lastPos) { // Found a token, add it to the vector. tokens.push_back(str.substr(lastPos, pos - lastPos)); // Skip delimiters. Note the "not_of" lastPos = str.find_first_not_of(delimiters, pos); // Find next "non-delimiter" pos = str.find_first_of(delimiters, lastPos); } } void int_to_byte(const uint32_t i, char* p_byte_value) { uint32_t int_value = i; for (int x = 0; x < 4; x++) { p_byte_value[x] = int_value & 0x000000FF; int_value = int_value >> 8; cout << "b[" << x << "] = " << hex << uppercase << setw(2) << setfill('0') <<(int)p_byte_value[x] << endl; } } int fill_file_with_zeros(int fd, size_t nbytes) { static const size_t BLOCKSIZE = 8192; char zeros[BLOCKSIZE]; memset(zeros, 0, BLOCKSIZE); while (nbytes > 0) { size_t bytes_to_write = min(nbytes, BLOCKSIZE); ssize_t ret = write(fd, zeros, bytes_to_write); if (ret < 0) { perror("error in fill_file_with_zeros write"); return -1; } nbytes -= bytes_to_write; } return 0; } string getID(string ip, const int32_t port) { char sport[7]; sprintf(sport, "%d", port); return ip.append(":").append(sport, strlen(sport)); } string getIP(string id) { return id.substr(0, id.find(":")); } int getPort(string id) { string p = id.substr(id.find(":")+1, id.size()); return strtol(p.c_str(), NULL, 10); }
24.302419
114
0.557657
[ "vector" ]
2d078c0874b26fadf9a94673e9926b6d6a289cc1
38,144
cpp
C++
webmsplit/webmsplitfilter.cpp
roh0sun/webmdshow
311dd9686dc896baa4d418c6da79938e94799e55
[ "BSD-3-Clause" ]
null
null
null
webmsplit/webmsplitfilter.cpp
roh0sun/webmdshow
311dd9686dc896baa4d418c6da79938e94799e55
[ "BSD-3-Clause" ]
null
null
null
webmsplit/webmsplitfilter.cpp
roh0sun/webmdshow
311dd9686dc896baa4d418c6da79938e94799e55
[ "BSD-3-Clause" ]
null
null
null
// Copyright (c) 2010 The WebM project authors. All Rights Reserved. // // Use of this source code is governed by a BSD-style license // that can be found in the LICENSE file in the root of the source // tree. An additional intellectual property rights grant can be found // in the file PATENTS. All contributing project authors may // be found in the AUTHORS file in the root of the source tree. #include <strmif.h> #include <uuids.h> #include "webmsplitfilter.hpp" #include "cenumpins.hpp" #include "mkvparser.hpp" #include "mkvparserstreamvideo.hpp" #include "mkvparserstreamaudio.hpp" #include "webmsplitoutpin.hpp" #include "webmtypes.hpp" #include <new> #include <cassert> #include <vfwmsgs.h> #include <process.h> #include <evcode.h> #include <limits> #ifdef _DEBUG #include "iidstr.hpp" #include "odbgstream.hpp" using std::endl; using std::hex; using std::dec; #endif using std::wstring; //using std::wistringstream; namespace WebmSplit { const LONGLONG Filter::kNoSeek(std::numeric_limits<LONGLONG>::min()); HRESULT CreateInstance( IClassFactory* pClassFactory, IUnknown* pOuter, const IID& iid, void** ppv) { if (ppv == 0) return E_POINTER; *ppv = 0; if ((pOuter != 0) && (iid != __uuidof(IUnknown))) return E_INVALIDARG; Filter* p = new (std::nothrow) Filter(pClassFactory, pOuter); if (p == 0) return E_OUTOFMEMORY; assert(p->m_nondelegating.m_cRef == 0); const HRESULT hr = p->m_nondelegating.QueryInterface(iid, ppv); if (SUCCEEDED(hr)) { assert(*ppv); assert(p->m_nondelegating.m_cRef == 1); return S_OK; } assert(*ppv == 0); assert(p->m_nondelegating.m_cRef == 0); delete p; p = 0; return hr; } #pragma warning(disable:4355) //'this' ptr in member init list Filter::Filter(IClassFactory* pClassFactory, IUnknown* pOuter) : m_pClassFactory(pClassFactory), m_nondelegating(this), m_pOuter(pOuter ? pOuter : &m_nondelegating), m_state(State_Stopped), m_clock(0), m_hThread(0), m_pSegment(0), m_pSeekBase(0), m_seekBase_ns(-1), m_currTime(kNoSeek), m_inpin(this), m_cStarvation(-1), //means "not starving" m_encAudio(false), m_encVideo(false) { m_pClassFactory->LockServer(TRUE); const HRESULT hr = CLockable::Init(); hr; assert(SUCCEEDED(hr)); m_hNewCluster = CreateEvent(0, 0, 0, 0); assert(m_hNewCluster); //TODO m_info.pGraph = 0; m_info.achName[0] = L'\0'; #ifdef _DEBUG odbgstream os; os << "WebmSplit::ctor" << endl; #endif } #pragma warning(default:4355) Filter::~Filter() { #ifdef _DEBUG odbgstream os; os << "WebmSplit::dtor" << endl; #endif assert(m_hThread == 0); assert(m_outpins.empty()); assert(m_pSegment == 0); m_pClassFactory->LockServer(FALSE); } void Filter::Init() { assert(m_hThread == 0); if (!m_inpin.m_reader.IsOpen()) return; if (m_pSegment->DoneParsing()) return; //nothing for thread to do const uintptr_t h = _beginthreadex( 0, //security 0, //stack size &Filter::ThreadProc, this, 0, //run immediately 0); //thread id m_hThread = reinterpret_cast<HANDLE>(h); assert(m_hThread); } void Filter::Final() { if (m_hThread == 0) return; assert(m_inpin.m_reader.IsOpen()); //odbgstream os; //os << "WebmSplit::Filter::Final(begin)" << endl; //os << "WebmSplit::Filter::Final: calling BeginFlush" << endl; //TODO: calling BeginFlush has the exact opposite semantics that //I thought it did: if flush is in effect, then the SyncRead blocks //indefinitely, until EndFlush is called. In the local file playback //case this isn't a problem, since SyncRead will never officially block. //The problem case occurs when this is a slow network download, and //SyncRead blocks. I thought that BeginFlush could be used to cancel //the SyncRead in progress, but that doesn't appear to be the case. //(Apparently it cancels asyncronous reads, not synchronous reads.) //This only really matters during the transition to stopped. In that //case we could do something ugly like timeout the wait for signal //of thread termination, then if timeout occurs then forcibly //terminate the thread (but I don't know if that will work either). //The only other alternative is to use proper timed reads, but //that requires that reads be aligned. //HRESULT hr = pReader->BeginFlush(); //assert(SUCCEEDED(hr)); // //os << "WebmSplit::Filter::Final: called BeginFlush; " // << "waiting for thread termination" //<< endl; //HRESULT hr = m_inpin.m_reader.Cancel(); //assert(SUCCEEDED(hr)); const DWORD dw = WaitForSingleObject(m_hThread, INFINITE); dw; assert(dw == WAIT_OBJECT_0); //os << "WebmSplit::Filter::Final: thread terminated" << endl; const BOOL b = CloseHandle(m_hThread); b; assert(b); m_hThread = 0; //os << "WebmSplit::Filter::Final: calling EndFlush" << endl; //hr = pReader->EndFlush(); //assert(SUCCEEDED(hr)); //os << "WebmSplit::Filter::Final: called EndFlush" << endl; //os << "WebmSplit::Filter::Final(end)" << endl; } Filter::CNondelegating::CNondelegating(Filter* p) : m_pFilter(p), m_cRef(0) //see CreateInstance { } Filter::CNondelegating::~CNondelegating() { } HRESULT Filter::CNondelegating::QueryInterface( const IID& iid, void** ppv) { if (ppv == 0) return E_POINTER; IUnknown*& pUnk = reinterpret_cast<IUnknown*&>(*ppv); if (iid == __uuidof(IUnknown)) { pUnk = this; //must be nondelegating } else if ((iid == __uuidof(IBaseFilter)) || (iid == __uuidof(IMediaFilter)) || (iid == __uuidof(IPersist))) { pUnk = static_cast<IBaseFilter*>(m_pFilter); } else if (iid == __uuidof(IWebmEncryption)) { pUnk = static_cast<IWebmEncryption*>(m_pFilter); } else { #if 0 wodbgstream os; os << "mkvsource::filter::QI: iid=" << IIDStr(iid) << std::endl; #endif pUnk = 0; return E_NOINTERFACE; } pUnk->AddRef(); return S_OK; } ULONG Filter::CNondelegating::AddRef() { return InterlockedIncrement(&m_cRef); } ULONG Filter::CNondelegating::Release() { const LONG n = InterlockedDecrement(&m_cRef); //odbgstream os; //os << "Filter::Release: n=" << n << endl; if (n > 0) return n; delete m_pFilter; return 0; } HRESULT Filter::QueryInterface(const IID& iid, void** ppv) { return m_pOuter->QueryInterface(iid, ppv); } ULONG Filter::AddRef() { return m_pOuter->AddRef(); } ULONG Filter::Release() { return m_pOuter->Release(); } HRESULT Filter::GetClassID(CLSID* p) { if (p == 0) return E_POINTER; *p = WebmTypes::CLSID_WebmSplit; return S_OK; } HRESULT Filter::Stop() { //Stop is a synchronous operation: when it completes, //the filter is stopped. Lock lock; HRESULT hr = lock.Seize(this); if (FAILED(hr)) return hr; switch (m_state) { case State_Paused: case State_Running: //Stop is synchronous. When stop completes, all threads //should be stopped. What does "stopped" mean" In our //case it probably means "terminated". //It's a bit tricky here because we hold the filter //lock. If threads need to acquire filter lock //then we'll have to release it. Only the FGM can call //Stop, etc, so there's no problem to release lock //while Stop is executing, to allow threads to acquire //filter lock temporarily. //The streaming thread will receiving an indication //automatically (assuming it's connected), either via //GetBuffer or Receive, so there's nothing this filter //needs to do to tell the streaming thread to stop. //One implementation strategy is to have build a //vector of thread handles, and then wait for a signal //on one of them. When the handle is signalled //(meaning that the thread has terminated), then //we remove that handle from the vector, close the //handle, and the wait again. Repeat until the //all threads have been terminated. //We also need to clean up any unused samples, //and decommit the allocator. (In fact, we could //decommit the allocator immediately, and then wait //for the threads to terminated.) m_state = State_Stopped; hr = m_inpin.m_reader.BeginFlush(); assert(SUCCEEDED(hr)); lock.Release(); OnStop(); hr = lock.Seize(this); assert(SUCCEEDED(hr)); //TODO hr = m_inpin.m_reader.EndFlush(); assert(SUCCEEDED(hr)); break; case State_Stopped: default: break; } return S_OK; } HRESULT Filter::Pause() { //Unlike Stop(), Pause() can be asynchronous (that's why you have //GetState()). We could use that here to build the samples index. Lock lock; HRESULT hr = lock.Seize(this); if (FAILED(hr)) return hr; //odbgstream os; //os << "WebmSplit::Filter::Pause" << endl; switch (m_state) { case State_Stopped: OnStart(); break; case State_Running: case State_Paused: default: break; } m_state = State_Paused; return S_OK; } HRESULT Filter::Run(REFERENCE_TIME start) { Lock lock; HRESULT hr = lock.Seize(this); if (FAILED(hr)) return hr; //odbgstream os; //os << "WebmSplit::Filter::Run" << endl; switch (m_state) { case State_Stopped: OnStart(); break; case State_Paused: case State_Running: default: break; } m_start = start; m_state = State_Running; return S_OK; } HRESULT Filter::GetState( DWORD timeout, FILTER_STATE* p) { if (p == 0) return E_POINTER; //What the GetState.timeout parameter refers to is not to locking //the filter, but rather to waiting to determine the current state. //A request to Stop is always synchronous (hence no timeout parameter), //but a request to Pause can be asynchronous, so the caller can say //how long he's willing to wait for the transition (to paused) to //complete. //TODO: implement a waiting scheme here. We'll probably have to //use SignalObjectAndWait atomically release the mutex and then //wait for the condition variable to change. //if (hr == VFW_E_TIMEOUT) // return VFW_S_STATE_INTERMEDIATE; Lock lock; HRESULT hrLock = lock.Seize(this); //The lock is only used for synchronization. If Seize fails, //it means there's a serious problem with the filter. if (FAILED(hrLock)) return E_FAIL; FILTER_STATE& state = *p; if (m_cStarvation < 0) //not starving { state = m_state; return S_OK; } assert(m_pSegment); long count = m_pSegment->GetCount(); if (count > m_cStarvation) { m_cStarvation = -1; state = m_state; //TODO: should be State_Paused? return S_OK; } for (;;) { lock.Release(); DWORD index; //TODO: this timeout isn't quite correct. The parameter refers //to the total wait time. As used here in the call to WaitForHandles, //it refers to the wait time for this pass through the loop. const HRESULT hrWait = CoWaitForMultipleHandles( 0, //wait flags timeout, 1, &m_hNewCluster, &index); if (SUCCEEDED(hrWait)) assert(index == 0); else if (hrWait != RPC_S_CALLPENDING) //error, despite "S" in name return hrWait; hrLock = lock.Seize(this); if (FAILED(hrLock)) return E_FAIL; count = m_pSegment->GetCount(); if (count > m_cStarvation) { m_cStarvation = -1; state = m_state; //TODO: should be State_Paused? return S_OK; } if (FAILED(hrWait)) //there was a timeout before receiving signal return VFW_S_STATE_INTERMEDIATE; } } HRESULT Filter::SetSyncSource( IReferenceClock* clock) { Lock lock; HRESULT hr = lock.Seize(this); if (FAILED(hr)) return hr; if (m_clock) m_clock->Release(); m_clock = clock; if (m_clock) m_clock->AddRef(); return S_OK; } HRESULT Filter::GetSyncSource( IReferenceClock** pclock) { if (pclock == 0) return E_POINTER; Lock lock; HRESULT hr = lock.Seize(this); if (FAILED(hr)) return hr; IReferenceClock*& clock = *pclock; clock = m_clock; if (clock) clock->AddRef(); return S_OK; } HRESULT Filter::EnumPins(IEnumPins** pp) { Lock lock; HRESULT hr = lock.Seize(this); if (FAILED(hr)) return hr; const ULONG outpins_count = static_cast<ULONG>(m_outpins.size()); const ULONG n = 1 + outpins_count; //odbgstream os; //os << "WebmSplit::filter::enumpins: n=" << n << endl; const size_t cb = n * sizeof(IPin*); IPin** const pins = (IPin**)_alloca(cb); IPin** pin = pins; *pin++ = &m_inpin; typedef outpins_t::iterator iter_t; iter_t i = m_outpins.begin(); const iter_t j = m_outpins.end(); while (i != j) *pin++ = *i++; return CEnumPins::CreateInstance(pins, n, pp); } HRESULT Filter::FindPin( LPCWSTR id1, IPin** pp) { if (pp == 0) return E_POINTER; IPin*& p = *pp; p = 0; if (id1 == 0) return E_INVALIDARG; { Pin* const pPin = &m_inpin; const wstring& id2_ = pPin->m_id; const wchar_t* const id2 = id2_.c_str(); if (wcscmp(id1, id2) == 0) //case-sensitive { p = pPin; p->AddRef(); return S_OK; } } typedef outpins_t::const_iterator iter_t; iter_t i = m_outpins.begin(); const iter_t j = m_outpins.end(); while (i != j) { Pin* const pPin = *i++; const wstring& id2_ = pPin->m_id; const wchar_t* const id2 = id2_.c_str(); if (wcscmp(id1, id2) == 0) //case-sensitive { p = pPin; p->AddRef(); return S_OK; } } return VFW_E_NOT_FOUND; } HRESULT Filter::QueryFilterInfo(FILTER_INFO* p) { if (p == 0) return E_POINTER; Lock lock; HRESULT hr = lock.Seize(this); if (FAILED(hr)) return hr; enum { size = sizeof(p->achName)/sizeof(WCHAR) }; const errno_t e = wcscpy_s(p->achName, size, m_info.achName); e; assert(e == 0); p->pGraph = m_info.pGraph; if (p->pGraph) p->pGraph->AddRef(); return S_OK; } HRESULT Filter::JoinFilterGraph( IFilterGraph *pGraph, LPCWSTR name) { Lock lock; HRESULT hr = lock.Seize(this); if (FAILED(hr)) return hr; //NOTE: //No, do not adjust reference counts here! //Read the docs for the reasons why. //ENDNOTE. m_info.pGraph = pGraph; if (name == 0) m_info.achName[0] = L'\0'; else { enum { size = sizeof(m_info.achName)/sizeof(WCHAR) }; const errno_t e = wcscpy_s(m_info.achName, size, name); e; assert(e == 0); //TODO } return S_OK; } HRESULT Filter::QueryVendorInfo(LPWSTR* pstr) { if (pstr == 0) return E_POINTER; wchar_t*& str = *pstr; str = 0; return E_NOTIMPL; } HRESULT Filter::SetEncryptionMode(WebmEncryptionMode /*mode*/) { return E_NOTIMPL; } HRESULT Filter::GetEncryptionMode(WebmEncryptionMode *pMode) { if (pMode == 0) return E_POINTER; Lock lock; HRESULT hr = lock.Seize(this); if (FAILED(hr)) return hr; if (m_encAudio && m_encVideo) *pMode = kWebmEncryptionModeAll; else if (m_encVideo) *pMode = kWebmEncryptionModeVideoOnly; else *pMode = kWebmEncryptionModeDefault; return S_OK; } HRESULT Filter::SetEncryptionContentId(const BYTE *, LONG ) { return E_NOTIMPL; } HRESULT Filter::GetEncryptionContentId(BYTE **pBuffer, LONG *pLength) { Lock lock; if (pBuffer == 0 || pLength == 0) return E_POINTER; HRESULT hr = lock.Seize(this); if (FAILED(hr)) return hr; const std::string& cid = m_encCid; if (cid.empty()) { *pLength = 0; *pBuffer = static_cast<BYTE *>(::CoTaskMemAlloc(0)); } else { *pLength = cid.length(); *pBuffer = static_cast<BYTE *>(::CoTaskMemAlloc(cid.length())); if (*pBuffer) { memcpy(*pBuffer, cid.data(), cid.length()); } } if (*pBuffer) return E_OUTOFMEMORY; else return S_OK; } HRESULT Filter::SetEncryptionSecret(const BYTE *buffer, LONG length) { Lock lock; if (buffer == 0) return E_POINTER; if (length < 1) return S_FALSE; HRESULT hr = lock.Seize(this); if (FAILED(hr)) return hr; std::string secret; std::copy(buffer, buffer + length, std::back_inserter(secret)); m_encSecret = secret; return S_OK; } HRESULT Filter::GetEncryptionSecret(BYTE **pBuffer, LONG *pLength) { Lock lock; if (pBuffer == 0 || pLength == 0) return E_POINTER; HRESULT hr = lock.Seize(this); if (FAILED(hr)) return hr; const std::string& secret = m_encSecret; if (secret.empty()) { *pLength = 0; *pBuffer = static_cast<BYTE *>(::CoTaskMemAlloc(0)); } else { *pLength = secret.length(); *pBuffer = static_cast<BYTE *>(::CoTaskMemAlloc(secret.length())); if (*pBuffer) { memcpy(*pBuffer, secret.data(), secret.length()); } } if (*pBuffer) return E_OUTOFMEMORY; else return S_OK; } HRESULT Filter::SetEncryptionIV(LONGLONG ) { return E_NOTIMPL; } HRESULT Filter::GetEncryptionIV(LONGLONG *) { return E_NOTIMPL; } HRESULT Filter::Open() { if (m_pSegment) return VFW_E_WRONG_STATE; assert(m_outpins.empty()); MkvReader& reader = m_inpin.m_reader; __int64 result, pos; mkvparser::EBMLHeader h; result = h.Parse(&reader, pos); if (result < 0) //error { if (result == mkvparser::E_FILE_FORMAT_INVALID) return VFW_E_INVALID_FILE_FORMAT; if (result == mkvparser::E_BUFFER_NOT_FULL) return VFW_E_BUFFER_UNDERFLOW; return VFW_E_RUNTIME_ERROR; } if (result > 0) return VFW_E_BUFFER_UNDERFLOW; if (h.m_version > 1) return VFW_E_INVALID_FILE_FORMAT; if (h.m_maxIdLength > 8) return VFW_E_INVALID_FILE_FORMAT; if (h.m_maxSizeLength > 8) return VFW_E_INVALID_FILE_FORMAT; const char* const docType = h.m_docType; if (_stricmp(docType, "webm") == 0) __noop; else if (_stricmp(docType, "matroska") == 0) __noop; else return VFW_E_INVALID_FILE_FORMAT; if (h.m_docTypeVersion < 1) return VFW_E_INVALID_FILE_FORMAT; if (h.m_docTypeReadVersion > 2) return VFW_E_INVALID_FILE_FORMAT; //Just the EBML header has been consumed. pos points //to start of (first) segment. mkvparser::Segment* p; result = mkvparser::Segment::CreateInstance(&reader, pos, p); if (result < 0) //error { if (result == mkvparser::E_FILE_FORMAT_INVALID) return VFW_E_INVALID_FILE_FORMAT; if (result == mkvparser::E_BUFFER_NOT_FULL) return VFW_E_BUFFER_UNDERFLOW; return VFW_E_RUNTIME_ERROR; } if (result > 0) return VFW_E_BUFFER_UNDERFLOW; //TODO: handle this as below assert(p); std::auto_ptr<mkvparser::Segment> pSegment(p); #if 0 result = pSegment->FindFirstCluster(pos); if (result < 0) { if (result == mkvparser::E_FILE_FORMAT_INVALID) return VFW_E_INVALID_FILE_FORMAT; if (result != mkvparser::E_BUFFER_NOT_FULL) return VFW_E_RUNTIME_ERROR; } //if you're going to do this, why not just a sync read... const HRESULT hr = reader.Wait(*this, pos, 1, 5000); if (FAILED(hr)) return hr; #endif result = pSegment->ParseHeaders(); if (result < 0) //error { if (result == mkvparser::E_FILE_FORMAT_INVALID) return VFW_E_INVALID_FILE_FORMAT; if (result == mkvparser::E_BUFFER_NOT_FULL) return VFW_E_BUFFER_UNDERFLOW; return VFW_E_RUNTIME_ERROR; } if (result > 0) return VFW_E_BUFFER_UNDERFLOW; using namespace mkvparser; const SegmentInfo* const pInfo = pSegment->GetInfo(); if (pInfo == 0) return VFW_E_INVALID_FILE_FORMAT; //TODO: liberalize #ifdef _DEBUG { wstring muxingApp, writingApp; if (const char* str = pInfo->GetMuxingAppAsUTF8()) muxingApp = Stream::ConvertFromUTF8(str); if (const char* str = pInfo->GetWritingAppAsUTF8()) writingApp = Stream::ConvertFromUTF8(str); } #endif const Tracks* const pTracks = pSegment->GetTracks(); if (pTracks == 0) return VFW_E_INVALID_FILE_FORMAT; const ULONG n = pTracks->GetTracksCount(); for (ULONG i = 0; i < n; ++i) { const Track* const pTrack = pTracks->GetTrackByIndex(i); if (pTrack == 0) continue; const long long type = pTrack->GetType(); if (type == 1) //video { typedef mkvparser::VideoTrack VT; const VT* const t = static_cast<const VT*>(pTrack); if (VideoStream* s = VideoStream::CreateInstance(t)) { CheckContentEncoding(pTrack, m_encVideo); Outpin* const pin = CreateOutpin(s); if (m_encVideo) pin->SetEnableDecryption(); } } #if 1 else if (type == 2) //audio { typedef mkvparser::AudioTrack AT; const AT* const t = static_cast<const AT*>(pTrack); if (AudioStream* s = AudioStream::CreateInstance(t)) { CheckContentEncoding(pTrack, m_encAudio); Outpin* const pin = CreateOutpin(s); if (m_encAudio) pin->SetEnableDecryption(); } } #endif } if (m_outpins.empty()) return VFW_E_INVALID_FILE_FORMAT; //TODO: better return value here? m_pSegment = pSegment.release(); m_pSeekBase = 0; m_seekBase_ns = -1; m_currTime = kNoSeek; return S_OK; } void Filter::CheckContentEncoding(const mkvparser::Track* pTrack, bool& enable) { using namespace mkvparser; ULONG ec = pTrack->GetContentEncodingCount(); for (ULONG e = 0; e<ec; ++e) { const ContentEncoding* encoding = pTrack->GetContentEncodingByIndex(e); if (encoding->encoding_type() == 1) { ULONG rc = encoding->GetEncryptionCount(); for (ULONG r = 0; r < rc; ++r) { const ContentEncoding::ContentEncryption* encryption = encoding->GetEncryptionByIndex(r); if (encryption->algo == 5) { if (encryption->key_id_len > 0) { m_encCid.clear(); std::copy(encryption->key_id, encryption->key_id + encryption->key_id_len, std::back_inserter(m_encCid)); } if (encryption->aes_settings.cipher_mode == 1) { enable = true; } } } } } } Outpin* const Filter::CreateOutpin(mkvparser::Stream* s) { //Outpin* const p = new (std::nothrow) Outpin(this, s); Outpin* const p = Outpin::Create(this, s); m_outpins.push_back(p); return p; } void Filter::OnStart() { //m_inpin.Start(); typedef outpins_t::iterator iter_t; iter_t i = m_outpins.begin(); const iter_t j = m_outpins.end(); int n = 0; while (i != j) { Outpin* const pPin = *i++; assert(pPin); const HRESULT hr = pPin->Start(); assert(SUCCEEDED(hr)); if (hr == S_OK) ++n; } if (n) { assert(m_pSegment); m_cStarvation = 0; //temporarily enter starvation mode to force check } Init(); //create reader thread } void Filter::OnStop() { Final(); //terminate reader thread typedef outpins_t::iterator iter_t; iter_t i = m_outpins.begin(); const iter_t j = m_outpins.end(); while (i != j) { Outpin* const pPin = *i++; assert(pPin); pPin->Stop(); } //m_inpin.Stop(); } int Filter::GetConnectionCount() const { //filter already locked by caller int n = 0; typedef outpins_t::const_iterator iter_t; iter_t i = m_outpins.begin(); const iter_t j = m_outpins.end(); while (i != j) { const Outpin* const pin = *i++; assert(pin); if (pin->m_pPinConnection) ++n; } return n; } unsigned Filter::ThreadProc(void* pv) { Filter* const pFilter = static_cast<Filter*>(pv); assert(pFilter); return pFilter->Main(); } unsigned Filter::Main() { assert(m_pSegment); for (;;) { Sleep(0); #if 0 LONGLONG cluster_pos, new_pos; const long status = m_pSegment->ParseCluster(cluster_pos, new_pos); if (status < 0) //TODO: how to handle outpin streaming threads? return 1; Lock lock; const HRESULT hr = lock.Seize(this); assert(SUCCEEDED(hr)); //TODO if (FAILED(hr)) return 1; const bool bDone = m_pSegment->AddCluster(cluster_pos, new_pos); //odbgstream os; //os << "webmsplit::filter::main: ParseCluster; cluster_pos=" // << cluster_pos // << " new_pos=" // << new_pos // << " count=" // << m_pSegment->GetCount() // << " unparsed=" // << m_pSegment->Unparsed() // << endl; #else Lock lock; HRESULT hr = lock.Seize(this); if (FAILED(hr)) return 1; // set decryptiong parameters { outpins_t::iterator it = m_outpins.begin(); while (it != m_outpins.end()) { (*it)->SetDecryptParam(m_encSecret); } } for (;;) { LONGLONG pos; LONG size; const long status = m_pSegment->LoadCluster(pos, size); if (status >= 0) break; if (status != mkvparser::E_BUFFER_NOT_FULL) return 1; hr = m_inpin.m_reader.Wait(*this, pos, size, INFINITE); if (FAILED(hr)) //wait was cancelled return 1; } const bool bDone = m_pSegment->DoneParsing(); #endif OnNewCluster(); if (bDone) return 0; if (m_state == State_Stopped) return 0; } } void Filter::OnNewCluster() { const BOOL b = SetEvent(m_hNewCluster); //see Filter::GetState b; assert(b); typedef outpins_t::iterator iter_t; iter_t i = m_outpins.begin(); const iter_t j = m_outpins.end(); while (i != j) { Outpin* const outpin = *i++; assert(outpin); outpin->OnNewCluster(); } } HRESULT Filter::OnDisconnectInpin() { assert(m_hThread == 0); while (!m_outpins.empty()) { Outpin* const pPin = m_outpins.back(); assert(pPin); if (IPin* pPinConnection = pPin->m_pPinConnection) { assert(m_info.pGraph); HRESULT hr = m_info.pGraph->Disconnect(pPinConnection); assert(SUCCEEDED(hr)); hr = m_info.pGraph->Disconnect(pPin); assert(SUCCEEDED(hr)); } m_outpins.pop_back(); const ULONG n = pPin->Destroy(); n; } m_currTime = kNoSeek; m_pSeekBase = 0; m_seekBase_ns = -1; delete m_pSegment; m_pSegment = 0; m_cStarvation = -1; return S_OK; } void Filter::OnStarvation(ULONG count) { #ifdef _DEBUG odbgstream os; os << "WebmSplit::Filter::OnStarvation: count=" << count << " m_cStarvation=" << m_cStarvation << endl; #endif if (m_cStarvation < 0) { const GraphUtil::IMediaEventSinkPtr pSink(m_info.pGraph); assert(bool(pSink)); const HRESULT hr = pSink->Notify(EC_STARVATION, 0, 0); hr; assert(SUCCEEDED(hr)); m_cStarvation = count; } } void Filter::SetCurrPosition( LONGLONG currTime, DWORD dwCurr, Outpin* pOutpin) { assert(pOutpin); assert(bool(pOutpin->m_pPinConnection)); using namespace mkvparser; Stream* const pSeekStream = pOutpin->GetStream(); assert(pSeekStream); if (m_currTime == currTime) { SetCurrPositionUsingSameTime(pSeekStream); return; } m_currTime = currTime; if (InCache()) m_pSegment->LoadCluster(); if (m_pSegment->GetCount() <= 0) //no clusters loaded yet { m_pSeekBase = 0; //best we can do is to assume first cluster m_seekBase_ns = -1; m_seekTime_ns = -1; pSeekStream->SetCurrPosition(-1, 0); //lazy init return; } const LONGLONG ns = pSeekStream->GetSeekTime(currTime, dwCurr); const Track* const pSeekTrack = pSeekStream->m_pTrack; if (pSeekTrack->GetType() == 1) //video SetCurrPositionVideo(ns, pSeekStream); else SetCurrPositionAudio(ns, pSeekStream); } void Filter::SetCurrPositionUsingSameTime(mkvparser::Stream* pStream) { const mkvparser::BlockEntry* pCurr; const mkvparser::Track* const pTrack = pStream->m_pTrack; if (m_pSeekBase == 0) //lazy init pCurr = 0; else if (m_pSeekBase->EOS()) pCurr = pTrack->GetEOS(); else { pCurr = m_pSeekBase->GetEntry(pTrack, m_seekTime_ns); #ifdef _DEBUG if (pCurr == 0) __noop; else if (pCurr->EOS()) __noop; else if (pTrack->GetType() == 1) //video { const mkvparser::Block* const pCurrBlock = pCurr->GetBlock(); const LONGLONG ns = pCurrBlock->GetTime(pCurr->GetCluster()); assert(ns >= m_seekBase_ns); assert(pCurrBlock->IsKey()); } #endif } pStream->SetCurrPosition(m_seekBase_ns, pCurr); } void Filter::SetCurrPositionVideo( LONGLONG ns, mkvparser::Stream* pStream) { using namespace mkvparser; const Track* const pTrack = pStream->m_pTrack; const bool bInCache = InCache(); if (!bInCache) __noop; else if (const Cues* pCues = m_pSegment->GetCues()) { while (!pCues->DoneParsing()) { pCues->LoadCuePoint(); const CuePoint* const pCP = pCues->GetLast(); assert(pCP); if (pCP->GetTime(m_pSegment) >= ns) break; } const CuePoint* pCP; const CuePoint::TrackPosition* pTP; if (pCues->Find(ns, pTrack, pCP, pTP)) { const BlockEntry* const pCurr = pCues->GetBlock(pCP, pTP); if ((pCurr != 0) && !pCurr->EOS()) { m_pSeekBase = pCurr->GetCluster(); m_seekBase_ns = pCurr->GetBlock()->GetTime(m_pSeekBase); m_seekTime_ns = m_seekBase_ns; pStream->SetCurrPosition(m_seekBase_ns, pCurr); return; } } } const mkvparser::BlockEntry* pCurr = 0; for (;;) { long status = pTrack->Seek(ns, pCurr); if ((status >= 0) || (status != mkvparser::E_BUFFER_NOT_FULL) || !bInCache) { break; } status = m_pSegment->LoadCluster(); if (status < 0) break; } if ((pCurr == 0) || pCurr->EOS()) { m_pSeekBase = &m_pSegment->m_eos; m_seekBase_ns = -1; m_seekTime_ns = -1; } else { m_pSeekBase = pCurr->GetCluster(); m_seekBase_ns = pCurr->GetBlock()->GetTime(m_pSeekBase); m_seekTime_ns = m_seekBase_ns; } pStream->SetCurrPosition(m_seekBase_ns, pCurr); } void Filter::SetCurrPositionAudio( LONGLONG ns, mkvparser::Stream* pSeekStream) { using namespace mkvparser; const Track* const pSeekTrack = pSeekStream->m_pTrack; typedef outpins_t::const_iterator iter_t; iter_t i = m_outpins.begin(); const iter_t j = m_outpins.end(); mkvparser::Stream* pVideoStream = 0; while (i != j) { const Outpin* const pin = *i++; assert(pin); if (!bool(pin->m_pPinConnection)) continue; const AM_MEDIA_TYPE& mt = pin->m_connection_mtv[0]; const BOOL bVideo = (mt.majortype == MEDIATYPE_Video); if (bVideo) { pVideoStream = pin->GetStream(); assert(pVideoStream); assert(pVideoStream != pSeekStream); break; } } if (pVideoStream == 0) //no video tracks in this file { const mkvparser::BlockEntry* pCurr; const long status = pSeekTrack->Seek(ns, pCurr); if ((status < 0) || (pCurr == 0) || pCurr->EOS()) { m_pSeekBase = &m_pSegment->m_eos; m_seekBase_ns = -1; m_seekTime_ns = -1; } else { m_pSeekBase = pCurr->GetCluster(); m_seekBase_ns = m_pSeekBase->GetFirstTime(); m_seekTime_ns = ns; } pSeekStream->SetCurrPosition(m_seekBase_ns, pCurr); return; } const mkvparser::Track* const pVideoTrack = pVideoStream->m_pTrack; assert(pVideoTrack->GetType() == 1); //video const bool bInCache = InCache(); if (!bInCache) __noop; else if (const Cues* pCues = m_pSegment->GetCues()) { while (!pCues->DoneParsing()) { pCues->LoadCuePoint(); const CuePoint* const pCP = pCues->GetLast(); assert(pCP); if (pCP->GetTime(m_pSegment) >= ns) break; } const CuePoint* pCP; const CuePoint::TrackPosition* pTP; if (pCues->Find(ns, pVideoTrack, pCP, pTP)) { const BlockEntry* pCurr = pCues->GetBlock(pCP, pTP); if ((pCurr != 0) && !pCurr->EOS()) { m_pSeekBase = pCurr->GetCluster(); m_seekBase_ns = pCurr->GetBlock()->GetTime(m_pSeekBase); m_seekTime_ns = m_seekBase_ns; //to find same block later pCurr = m_pSeekBase->GetEntry(pSeekTrack, m_seekBase_ns); assert(pCurr); if (!pCurr->EOS()) m_seekBase_ns = pCurr->GetBlock()->GetTime(m_pSeekBase); pSeekStream->SetCurrPosition(m_seekBase_ns, pCurr); return; } } } const BlockEntry* pCurr = 0; for (;;) { long status = pVideoTrack->Seek(ns, pCurr); if ((status >= 0) || (status != mkvparser::E_BUFFER_NOT_FULL) || !bInCache) { break; } status = m_pSegment->LoadCluster(); if (status < 0) break; } if ((pCurr == 0) || pCurr->EOS()) { m_pSeekBase = &m_pSegment->m_eos; m_seekBase_ns = -1; m_seekTime_ns = -1; pCurr = pSeekTrack->GetEOS(); pSeekStream->SetCurrPosition(m_seekBase_ns, pCurr); return; } m_pSeekBase = pCurr->GetCluster(); m_seekBase_ns = pCurr->GetBlock()->GetTime(m_pSeekBase); m_seekTime_ns = m_seekBase_ns; //to find same block later pCurr = m_pSeekBase->GetEntry(pSeekTrack, m_seekBase_ns); assert(pCurr); if (!pCurr->EOS()) m_seekBase_ns = pCurr->GetBlock()->GetTime(m_pSeekBase); pSeekStream->SetCurrPosition(m_seekBase_ns, pCurr); } bool Filter::InCache() { LONGLONG total, avail; const int status = m_inpin.m_reader.Length(&total, &avail); if (status < 0) return false; if (total < 0) return false; return (avail >= total); } } //end namespace WebmSplit
22.464075
94
0.557545
[ "vector" ]
2d08ae4a286b33d24c683f5cf220828ec9ee3613
727
hpp
C++
Luna Programming Language/lexer.hpp
OnyxFlames/Luna-Programming-Language
56dd384caa115be7ba95cbcd3722e39fead98916
[ "MIT" ]
3
2018-01-21T21:41:32.000Z
2021-12-24T14:29:46.000Z
Luna Programming Language/lexer.hpp
OnyxFlames/Luna-Programming-Language
56dd384caa115be7ba95cbcd3722e39fead98916
[ "MIT" ]
null
null
null
Luna Programming Language/lexer.hpp
OnyxFlames/Luna-Programming-Language
56dd384caa115be7ba95cbcd3722e39fead98916
[ "MIT" ]
null
null
null
#pragma once #include <iostream> #include <fstream> #include <string> #include <vector> #include "token.hpp" class Lexer { private: std::ifstream input; std::vector<token> *tokens; bool is_keyword(const std::string &word, std::vector<std::string> word_pool); void handle_identifier(std::string val, int start, int end); void handle_keyword(const std::string &val, int start, int end); void handle_string_literal(int _token_start); void handle_char_literal(int _token_start); void store_binop(int val, int _token_start); public: Lexer::Lexer(std::vector<token> &_tokens); Lexer(const std::string &file_name, std::vector<token> &_tokens); bool load_file(const std::string file_name); bool lex(); ~Lexer(); };
22.71875
78
0.737276
[ "vector" ]
2d0950cb2bb2864b061c77149fe6d2978ded9483
2,308
hxx
C++
OCC/inc/BVH_Set.hxx
cy15196/FastCAE
0870752ec2e590f3ea6479e909ebf6c345ac2523
[ "BSD-3-Clause" ]
117
2020-03-07T12:07:05.000Z
2022-03-27T07:35:22.000Z
opencascade/BVH_Set.hxx
CadQuery/cpp-py-bindgen
66e7376d3a27444393fc99acbdbef40bbc7031ae
[ "Apache-2.0" ]
33
2019-11-13T18:09:51.000Z
2021-11-26T17:24:12.000Z
opencascade/BVH_Set.hxx
CadQuery/cpp-py-bindgen
66e7376d3a27444393fc99acbdbef40bbc7031ae
[ "Apache-2.0" ]
76
2020-03-16T01:47:46.000Z
2022-03-21T16:37:07.000Z
// Created on: 2013-12-20 // Created by: Denis BOGOLEPOV // Copyright (c) 2013-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _BVH_Set_Header #define _BVH_Set_Header #include <BVH_Box.hxx> //! Set of abstract entities (bounded by BVH boxes). This is //! the minimal geometry interface needed to construct BVH. //! \tparam T Numeric data type //! \tparam N Vector dimension template<class T, int N> class BVH_Set { public: typedef BVH_Box<T, N> BVH_BoxNt; public: //! Creates new abstract set of objects. BVH_Set() {} //! Releases resources of set of objects. virtual ~BVH_Set() = 0; //! Returns AABB of the entire set of objects. virtual BVH_Box<T, N> Box() const { BVH_Box<T, N> aBox; const Standard_Integer aSize = Size(); for (Standard_Integer anIndex = 0; anIndex < aSize; ++anIndex) { aBox.Combine (Box (anIndex)); } return aBox; } public: //! Returns total number of objects. virtual Standard_Integer Size() const = 0; //! Returns AABB of the given object. virtual BVH_Box<T, N> Box (const Standard_Integer theIndex) const = 0; //! Returns centroid position along the given axis. virtual T Center (const Standard_Integer theIndex, const Standard_Integer theAxis) const = 0; //! Performs transposing the two given objects in the set. virtual void Swap (const Standard_Integer theIndex1, const Standard_Integer theIndex2) = 0; }; // ======================================================================= // function : ~BVH_Set // purpose : // ======================================================================= template<class T, int N> BVH_Set<T, N>::~BVH_Set() { // } #endif // _BVH_Set_Header
28.493827
81
0.659879
[ "geometry", "object", "vector" ]
2d0a2828747fa06be9129e41b8ff60b6188c2f2a
10,934
cpp
C++
level_zero/core/test/unit_tests/sources/driver/test_driver.cpp
8tab/compute-runtime
71bd96ad7184df83c7af04ffa8e0d6678ab26f99
[ "MIT" ]
null
null
null
level_zero/core/test/unit_tests/sources/driver/test_driver.cpp
8tab/compute-runtime
71bd96ad7184df83c7af04ffa8e0d6678ab26f99
[ "MIT" ]
null
null
null
level_zero/core/test/unit_tests/sources/driver/test_driver.cpp
8tab/compute-runtime
71bd96ad7184df83c7af04ffa8e0d6678ab26f99
[ "MIT" ]
null
null
null
/* * Copyright (C) 2020 Intel Corporation * * SPDX-License-Identifier: MIT * */ #include "shared/source/os_interface/device_factory.h" #include "shared/source/os_interface/hw_info_config.h" #include "shared/test/unit_test/helpers/debug_manager_state_restore.h" #include "test.h" #include "level_zero/core/source/driver/driver_handle_imp.h" #include "level_zero/core/test/unit_tests/fixtures/device_fixture.h" #include <bitset> namespace L0 { namespace ult { using DriverVersionTest = Test<DeviceFixture>; TEST_F(DriverVersionTest, returnsExpectedDriverVersion) { ze_driver_properties_t properties; ze_result_t res = driverHandle->getProperties(&properties); EXPECT_EQ(ZE_RESULT_SUCCESS, res); uint32_t versionMajor = static_cast<uint32_t>((properties.driverVersion & 0xFF000000) >> 24); uint32_t versionMinor = static_cast<uint32_t>((properties.driverVersion & 0x00FF0000) >> 16); uint32_t versionBuild = static_cast<uint32_t>(properties.driverVersion & 0x0000FFFF); EXPECT_EQ(static_cast<uint32_t>(strtoul(L0_PROJECT_VERSION_MAJOR, NULL, 10)), versionMajor); EXPECT_EQ(static_cast<uint32_t>(strtoul(L0_PROJECT_VERSION_MINOR, NULL, 10)), versionMinor); EXPECT_EQ(static_cast<uint32_t>(strtoul(NEO_VERSION_BUILD, NULL, 10)), versionBuild); } TEST(DriverTestFamilySupport, whenInitializingDriverOnSupportedFamilyThenDriverIsCreated) { NEO::HardwareInfo hwInfo = *NEO::defaultHwInfo.get(); hwInfo.capabilityTable.levelZeroSupported = true; NEO::MockDevice *neoDevice = NEO::MockDevice::createWithNewExecutionEnvironment<NEO::MockDevice>(&hwInfo); NEO::DeviceVector devices; devices.push_back(std::unique_ptr<NEO::Device>(neoDevice)); auto driverHandle = DriverHandle::create(std::move(devices)); EXPECT_NE(nullptr, driverHandle); delete driverHandle; } TEST(DriverTestFamilySupport, whenInitializingDriverOnNotSupportedFamilyThenDriverIsNotCreated) { NEO::HardwareInfo hwInfo = *NEO::defaultHwInfo.get(); hwInfo.capabilityTable.levelZeroSupported = false; NEO::MockDevice *neoDevice = NEO::MockDevice::createWithNewExecutionEnvironment<NEO::MockDevice>(&hwInfo); NEO::DeviceVector devices; devices.push_back(std::unique_ptr<NEO::Device>(neoDevice)); auto driverHandle = DriverHandle::create(std::move(devices)); EXPECT_EQ(nullptr, driverHandle); } struct DriverTestMultipleFamilySupport : public ::testing::Test { void SetUp() override { VariableBackup<bool> mockDeviceFlagBackup(&MockDevice::createSingleDevice, false); NEO::ExecutionEnvironment *executionEnvironment = new NEO::ExecutionEnvironment(); executionEnvironment->prepareRootDeviceEnvironments(numRootDevices); for (auto i = 0u; i < executionEnvironment->rootDeviceEnvironments.size(); i++) { executionEnvironment->rootDeviceEnvironments[i]->setHwInfo(NEO::defaultHwInfo.get()); } for (auto i = 0u; i < executionEnvironment->rootDeviceEnvironments.size(); i++) { devices.push_back(std::unique_ptr<NEO::MockDevice>(NEO::MockDevice::createWithExecutionEnvironment<NEO::MockDevice>(NEO::defaultHwInfo.get(), executionEnvironment, i))); if (i < numSupportedRootDevices) { devices[i]->getRootDeviceEnvironment().getMutableHardwareInfo()->capabilityTable.levelZeroSupported = true; } else { devices[i]->getRootDeviceEnvironment().getMutableHardwareInfo()->capabilityTable.levelZeroSupported = false; } } } DebugManagerStateRestore restorer; std::vector<std::unique_ptr<NEO::Device>> devices; const uint32_t numRootDevices = 3u; const uint32_t numSupportedRootDevices = 2u; }; TEST_F(DriverTestMultipleFamilySupport, whenInitializingDriverWithArrayOfDevicesThenDriverIsInitializedOnlyWithThoseSupported) { auto driverHandle = DriverHandle::create(std::move(devices)); EXPECT_NE(nullptr, driverHandle); L0::DriverHandleImp *driverHandleImp = reinterpret_cast<L0::DriverHandleImp *>(driverHandle); EXPECT_EQ(numSupportedRootDevices, driverHandleImp->devices.size()); for (auto d : driverHandleImp->devices) { EXPECT_TRUE(d->getNEODevice()->getHardwareInfo().capabilityTable.levelZeroSupported); } delete driverHandle; } struct DriverTestMultipleFamilyNoSupport : public ::testing::Test { void SetUp() override { VariableBackup<bool> mockDeviceFlagBackup(&MockDevice::createSingleDevice, false); NEO::ExecutionEnvironment *executionEnvironment = new NEO::ExecutionEnvironment(); executionEnvironment->prepareRootDeviceEnvironments(numRootDevices); for (auto i = 0u; i < executionEnvironment->rootDeviceEnvironments.size(); i++) { executionEnvironment->rootDeviceEnvironments[i]->setHwInfo(NEO::defaultHwInfo.get()); } for (auto i = 0u; i < executionEnvironment->rootDeviceEnvironments.size(); i++) { devices.push_back(std::unique_ptr<NEO::MockDevice>(NEO::MockDevice::createWithExecutionEnvironment<NEO::MockDevice>(NEO::defaultHwInfo.get(), executionEnvironment, i))); devices[i]->getRootDeviceEnvironment().getMutableHardwareInfo()->capabilityTable.levelZeroSupported = false; } } DebugManagerStateRestore restorer; std::vector<std::unique_ptr<NEO::Device>> devices; const uint32_t numRootDevices = 3u; }; TEST_F(DriverTestMultipleFamilyNoSupport, whenInitializingDriverWithArrayOfNotSupportedDevicesThenDriverIsNull) { auto driverHandle = DriverHandle::create(std::move(devices)); EXPECT_EQ(nullptr, driverHandle); } struct DriverTestMultipleDeviceWithAffinityMask : public ::testing::WithParamInterface<std::tuple<int, int>>, public ::testing::Test { void SetUp() override { DebugManager.flags.CreateMultipleSubDevices.set(numSubDevices); VariableBackup<bool> mockDeviceFlagBackup(&MockDevice::createSingleDevice, false); NEO::ExecutionEnvironment *executionEnvironment = new NEO::ExecutionEnvironment(); executionEnvironment->prepareRootDeviceEnvironments(numRootDevices); for (auto i = 0u; i < executionEnvironment->rootDeviceEnvironments.size(); i++) { executionEnvironment->rootDeviceEnvironments[i]->setHwInfo(NEO::defaultHwInfo.get()); } for (auto i = 0u; i < executionEnvironment->rootDeviceEnvironments.size(); i++) { devices.push_back(std::unique_ptr<NEO::MockDevice>(NEO::MockDevice::createWithExecutionEnvironment<NEO::MockDevice>( NEO::defaultHwInfo.get(), executionEnvironment, i))); } } void getNumOfExposedDevices(uint32_t mask, uint32_t &rootDeviceExposed, uint32_t &numOfSubDevicesExposed) { rootDeviceExposed = (((1UL << numSubDevices) - 1) & mask) ? 1 : 0; numOfSubDevicesExposed = static_cast<uint32_t>(static_cast<std::bitset<sizeof(uint32_t) * 8>>(mask).count()); } DebugManagerStateRestore restorer; std::vector<std::unique_ptr<NEO::Device>> devices; const uint32_t numRootDevices = 2u; const uint32_t numSubDevices = 4u; }; TEST_F(DriverTestMultipleDeviceWithAffinityMask, whenNotSettingAffinityThenAllRootDevicesAndSubDevicesAreExposed) { L0::DriverHandleImp *driverHandle = new DriverHandleImp; ze_result_t res = driverHandle->initialize(std::move(devices)); EXPECT_EQ(ZE_RESULT_SUCCESS, res); uint32_t deviceCount = 0; res = zeDeviceGet(driverHandle->toHandle(), &deviceCount, nullptr); EXPECT_EQ(ZE_RESULT_SUCCESS, res); EXPECT_EQ(deviceCount, numRootDevices); std::vector<ze_device_handle_t> phDevices(deviceCount); res = zeDeviceGet(driverHandle->toHandle(), &deviceCount, phDevices.data()); EXPECT_EQ(ZE_RESULT_SUCCESS, res); for (uint32_t i = 0; i < numRootDevices; i++) { ze_device_handle_t hDevice = phDevices[i]; EXPECT_NE(nullptr, hDevice); uint32_t subDeviceCount = 0; res = zeDeviceGetSubDevices(hDevice, &subDeviceCount, nullptr); EXPECT_EQ(ZE_RESULT_SUCCESS, res); EXPECT_EQ(numSubDevices, subDeviceCount); } delete driverHandle; } TEST_P(DriverTestMultipleDeviceWithAffinityMask, whenSettingAffinityMaskToDifferentValuesThenCorrectNumberOfDevicesIsExposed) { L0::DriverHandleImp *driverHandle = new DriverHandleImp; uint32_t device0Mask = std::get<0>(GetParam()); uint32_t rootDevice0Exposed = 0; uint32_t numOfSubDevicesExposedInDevice0 = 0; getNumOfExposedDevices(device0Mask, rootDevice0Exposed, numOfSubDevicesExposedInDevice0); uint32_t device1Mask = std::get<1>(GetParam()); uint32_t rootDevice1Exposed = 0; uint32_t numOfSubDevicesExposedInDevice1 = 0; getNumOfExposedDevices(device1Mask, rootDevice1Exposed, numOfSubDevicesExposedInDevice1); driverHandle->affinityMask = device0Mask | (device1Mask << numSubDevices); uint32_t totalRootDevices = rootDevice0Exposed + rootDevice1Exposed; ze_result_t res = driverHandle->initialize(std::move(devices)); if (0 == totalRootDevices) { EXPECT_EQ(ZE_RESULT_ERROR_UNINITIALIZED, res); } else { EXPECT_EQ(ZE_RESULT_SUCCESS, res); } uint32_t deviceCount = 0; res = zeDeviceGet(driverHandle->toHandle(), &deviceCount, nullptr); EXPECT_EQ(ZE_RESULT_SUCCESS, res); EXPECT_EQ(deviceCount, totalRootDevices); if (deviceCount) { std::vector<ze_device_handle_t> phDevices(deviceCount); res = zeDeviceGet(driverHandle->toHandle(), &deviceCount, phDevices.data()); EXPECT_EQ(ZE_RESULT_SUCCESS, res); for (uint32_t i = 0; i < deviceCount; i++) { ze_device_handle_t hDevice = phDevices[i]; EXPECT_NE(nullptr, hDevice); uint32_t subDeviceCount = 0; res = zeDeviceGetSubDevices(hDevice, &subDeviceCount, nullptr); EXPECT_EQ(ZE_RESULT_SUCCESS, res); if (rootDevice0Exposed && !rootDevice1Exposed) { EXPECT_EQ(numOfSubDevicesExposedInDevice0, subDeviceCount); } else if (!rootDevice0Exposed && rootDevice1Exposed) { EXPECT_EQ(numOfSubDevicesExposedInDevice1, subDeviceCount); } else { if (i == 0) { EXPECT_EQ(numOfSubDevicesExposedInDevice0, subDeviceCount); } else { EXPECT_EQ(numOfSubDevicesExposedInDevice1, subDeviceCount); } } } } delete driverHandle; } INSTANTIATE_TEST_SUITE_P(DriverTestMultipleDeviceWithAffinityMaskTests, DriverTestMultipleDeviceWithAffinityMask, ::testing::Combine( ::testing::Range(0, 15), // Masks for 1 root device with 4 sub devices ::testing::Range(0, 15))); } // namespace ult } // namespace L0
43.217391
181
0.715017
[ "vector" ]
2d17db9d443705d2f756b1bc3da32e50b39e5d9c
5,155
cpp
C++
DemoApps/GLES2/Blur/source/TestScene.cpp
alejandrolozano2/OpenGL_DemoFramework
5fd85f05c98cc3d0c0a68bac438035df8cabaee7
[ "MIT", "BSD-3-Clause" ]
3
2019-01-19T20:21:24.000Z
2021-08-10T02:11:32.000Z
DemoApps/GLES2/Blur/source/TestScene.cpp
alejandrolozano2/OpenGL_DemoFramework
5fd85f05c98cc3d0c0a68bac438035df8cabaee7
[ "MIT", "BSD-3-Clause" ]
null
null
null
DemoApps/GLES2/Blur/source/TestScene.cpp
alejandrolozano2/OpenGL_DemoFramework
5fd85f05c98cc3d0c0a68bac438035df8cabaee7
[ "MIT", "BSD-3-Clause" ]
1
2021-08-10T02:11:33.000Z
2021-08-10T02:11:33.000Z
/**************************************************************************************************************************************************** * Copyright (c) 2015 Freescale Semiconductor, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of the Freescale Semiconductor, Inc. nor the names of * its contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************************************************************************************/ #include <FslBase/Log/Log.hpp> #include <FslDemoApp/Base/Service/Content/IContentManager.hpp> #include <FslDemoApp/Base/Service/Graphics/IGraphicsService.hpp> #include <FslGraphics/Bitmap/Bitmap.hpp> #include <FslGraphics/Vertices/VertexPositionTexture.hpp> #include "GausianHelper.hpp" #include "TestScene.hpp" namespace Fsl { TestScene::TestScene(const DemoAppConfig& config) : m_program() , m_texture() , m_vertexBuffer() { const std::shared_ptr<IContentManager> contentManager = config.DemoServiceProvider.Get<IContentManager>(); const Point2 screenResolution = config.ScreenResolution; std::vector<double> kernel; //const int length = 3; //GausianHelper::CalculateGausianKernel(kernel, length, 1.0); const int length = 9; GausianHelper::CalculateGausianKernel(kernel, length, 1.83); //const int length = 41; //GausianHelper::CalculateGausianKernel(kernel, length, 9.83); //const int length = 21; //GausianHelper::CalculateGausianKernel(kernel, length, 9.5); //GausianHelper::DebugDumpKernel2D(kernel, length); { Bitmap bitmap; contentManager->Read(bitmap, "Test.jpg", PixelFormat::R8G8B8_UNORM); GLES2::GLTextureParameters params(GL_LINEAR, GL_LINEAR, GL_CLAMP_TO_EDGE, GL_CLAMP_TO_EDGE); m_texture.SetData(bitmap, params); } const std::string fragTemplate = contentManager->ReadAllText("GaussianTemplate.frag"); const std::string gaussianFrag = GausianHelper::GenerateGausianFragmentShader(fragTemplate, kernel, length, m_texture.GetSize()); m_program.Reset(contentManager->ReadAllText("BasicShader.vert"), gaussianFrag); //m_program.Reset(contentManager->ReadAllText("BasicShader.vert"), contentManager->ReadAllText("BasicShader.frag")); //FSLLOG(gaussianFrag); //const GLuint hProgram = m_program.Get(); { // prepare the vertex buffer // We scale the UV coordinates so that we get a 1-1 pixel mapping on the screen const float scaleX = screenResolution.X / float(m_texture.GetSize().X); const float aspect = (screenResolution.Y / (float)screenResolution.X); const float u1 = 0.0f; const float u2 = scaleX; const float v1 = scaleX * aspect; const float v2 = 0.0f * aspect; VertexPositionTexture vertices[] = { VertexPositionTexture(Vector3(-1.0f, 1.0f, 0.0f), Vector2(u1, v2)), VertexPositionTexture(Vector3(-1.0f, -1.0f, 0.0f), Vector2(u1, v1)), VertexPositionTexture(Vector3(1.0f, 1.0f, 0.0f), Vector2(u2, v2)), VertexPositionTexture(Vector3(1.0f, -1.0f, 0.0f), Vector2(u2, v1)), }; m_vertexBuffer.Reset(vertices, 4, GL_STATIC_DRAW); } glViewport(0, 0, screenResolution.X, screenResolution.Y); } void TestScene::Update(const DemoTime& demoTime) { } void TestScene::Draw() { const GLuint hProgram = m_program.Get(); glDisable(GL_BLEND); glDisable(GL_DEPTH_TEST); glUseProgram(hProgram); glClear(GL_COLOR_BUFFER_BIT); glBindBuffer(m_vertexBuffer.GetTarget(), m_vertexBuffer.Get()); m_vertexBuffer.EnableAttribArrays(); glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); m_vertexBuffer.DisableAttribArrays(); glBindBuffer(m_vertexBuffer.GetTarget(), 0); } }
39.653846
149
0.685742
[ "vector" ]
2d202e6a5d90f79e4a49ce8b36aca1f17a26c195
10,406
cpp
C++
source/world/skeletal_mesh.cpp
zhaijialong/RealEngine
d3e57c85591e88875951d101a30f640658ef92db
[ "MIT" ]
14
2022-03-10T05:49:25.000Z
2022-03-26T10:35:07.000Z
source/world/skeletal_mesh.cpp
zhaijialong/RealEngine
d3e57c85591e88875951d101a30f640658ef92db
[ "MIT" ]
null
null
null
source/world/skeletal_mesh.cpp
zhaijialong/RealEngine
d3e57c85591e88875951d101a30f640658ef92db
[ "MIT" ]
null
null
null
#include "skeletal_mesh.h" #include "skeleton.h" #include "animation.h" #include "mesh_material.h" #include "resource_cache.h" #include "core/engine.h" SkeletalMeshData::~SkeletalMeshData() { ResourceCache* cache = ResourceCache::GetInstance(); cache->RelaseSceneBuffer(uvBufferAddress); cache->RelaseSceneBuffer(jointIDBufferAddress); cache->RelaseSceneBuffer(jointWeightBufferAddress); cache->RelaseSceneBuffer(staticPosBufferAddress); cache->RelaseSceneBuffer(staticNormalBufferAddress); cache->RelaseSceneBuffer(staticTangentBufferAddress); cache->RelaseSceneBuffer(indexBufferAddress); Renderer* pRenderer = Engine::GetInstance()->GetRenderer(); pRenderer->FreeSceneAnimationBuffer(animPosBufferAddress); pRenderer->FreeSceneAnimationBuffer(animNormalBufferAddress); pRenderer->FreeSceneAnimationBuffer(animTangentBufferAddress); pRenderer->FreeSceneAnimationBuffer(prevAnimPosBufferAddress); } SkeletalMesh::SkeletalMesh(const eastl::string& name) { m_name = name; } bool SkeletalMesh::Create() { for (size_t i = 0; i < m_nodes.size(); ++i) { for (size_t j = 0; j < m_nodes[i]->meshes.size(); ++j) { SkeletalMeshData* mesh = m_nodes[i]->meshes[j].get(); Create(mesh); } } return true; } void SkeletalMesh::Create(SkeletalMeshData* mesh) { if (mesh->material->IsVertexSkinned()) { mesh->animPosBufferAddress = m_pRenderer->AllocateSceneAnimationBuffer(sizeof(float3) * mesh->vertexCount); mesh->prevAnimPosBufferAddress = m_pRenderer->AllocateSceneAnimationBuffer(sizeof(float3) * mesh->vertexCount); if (mesh->staticNormalBufferAddress != -1) { mesh->animNormalBufferAddress = m_pRenderer->AllocateSceneAnimationBuffer(sizeof(float3) * mesh->vertexCount); } if (mesh->staticTangentBufferAddress != -1) { mesh->animTangentBufferAddress = m_pRenderer->AllocateSceneAnimationBuffer(sizeof(float4) * mesh->vertexCount); } } GfxRayTracingGeometry geometry; if (mesh->material->IsVertexSkinned()) { geometry.vertex_buffer = m_pRenderer->GetSceneAnimationBuffer(); geometry.vertex_buffer_offset = mesh->prevAnimPosBufferAddress; } else { geometry.vertex_buffer = m_pRenderer->GetSceneStaticBuffer(); geometry.vertex_buffer_offset = mesh->staticPosBufferAddress; } geometry.vertex_count = mesh->vertexCount; geometry.vertex_stride = sizeof(float3); geometry.vertex_format = GfxFormat::RGB32F; geometry.index_buffer = m_pRenderer->GetSceneStaticBuffer(); geometry.index_buffer_offset = mesh->indexBufferAddress; geometry.index_count = mesh->indexCount; geometry.index_format = mesh->indexBufferFormat; geometry.opaque = mesh->material->IsAlphaTest() ? false : true; //todo : alpha blend GfxRayTracingBLASDesc desc; desc.geometries.push_back(geometry); if (mesh->material->IsVertexSkinned()) { desc.flags = GfxRayTracingASFlagAllowUpdate | GfxRayTracingASFlagPreferFastTrace; } else { desc.flags = GfxRayTracingASFlagAllowCompaction | GfxRayTracingASFlagPreferFastTrace; } IGfxDevice* device = m_pRenderer->GetDevice(); mesh->blas.reset(device->CreateRayTracingBLAS(desc, "BLAS : " + m_name)); m_pRenderer->BuildRayTracingBLAS(mesh->blas.get()); } void SkeletalMesh::Tick(float delta_time) { float4x4 T = translation_matrix(m_pos); float4x4 R = rotation_matrix(rotation_quat(m_rotation)); float4x4 S = scaling_matrix(m_scale); m_mtxWorld = mul(T, mul(R, S)); m_pAnimation->Update(this, delta_time); //update node local transform for (size_t i = 0; i < m_rootNodes.size(); ++i) { UpdateNodeTransform(GetNode(m_rootNodes[i])); //update node global transform } if (m_pSkeleton) { m_pSkeleton->Update(this); } for (size_t i = 0; i < m_rootNodes.size(); ++i) { UpdateMeshConstants(GetNode(m_rootNodes[i])); } } void SkeletalMesh::Render(Renderer* pRenderer) { for (size_t i = 0; i < m_nodes.size(); ++i) { for (size_t j = 0; j < m_nodes[i]->meshes.size(); ++j) { const SkeletalMeshData* mesh = m_nodes[i]->meshes[j].get(); Draw(mesh); } } } bool SkeletalMesh::FrustumCull(const float4* planes, uint32_t plane_count) const { return ::FrustumCull(planes, plane_count, m_pos, m_radius); //todo : not correct } SkeletalMeshNode* SkeletalMesh::GetNode(uint32_t node_id) const { RE_ASSERT(node_id < m_nodes.size()); return m_nodes[node_id].get(); } void SkeletalMesh::UpdateNodeTransform(SkeletalMeshNode* node) { float4x4 T = translation_matrix(node->translation); float4x4 R = rotation_matrix(node->rotation); float4x4 S = scaling_matrix(node->scale); node->globalTransform = mul(T, mul(R, S)); if (node->parent != -1) { node->globalTransform = mul(GetNode(node->parent)->globalTransform, node->globalTransform); } for (size_t i = 0; i < node->children.size(); ++i) { UpdateNodeTransform(GetNode(node->children[i])); } } void SkeletalMesh::UpdateMeshConstants(SkeletalMeshNode* node) { for (size_t i = 0; i < node->meshes.size(); ++i) { SkeletalMeshData* mesh = node->meshes[i].get(); eastl::swap(mesh->prevAnimPosBufferAddress, mesh->animPosBufferAddress); mesh->material->UpdateConstants(); mesh->instanceData.instanceType = (uint)InstanceType::Model; mesh->instanceData.indexBufferAddress = mesh->indexBufferAddress; mesh->instanceData.indexStride = mesh->indexBufferFormat == GfxFormat::R32UI ? 4 : 2; mesh->instanceData.triangleCount = mesh->indexCount / 3; mesh->instanceData.uvBufferAddress = mesh->uvBufferAddress; bool isSkinnedMesh = mesh->material->IsVertexSkinned(); if (isSkinnedMesh) { mesh->instanceData.posBufferAddress = mesh->animPosBufferAddress; mesh->instanceData.normalBufferAddress = mesh->animNormalBufferAddress; mesh->instanceData.tangentBufferAddress = mesh->animTangentBufferAddress; } else { mesh->instanceData.posBufferAddress = mesh->staticPosBufferAddress; mesh->instanceData.normalBufferAddress = mesh->staticNormalBufferAddress; mesh->instanceData.tangentBufferAddress = mesh->staticTangentBufferAddress; } mesh->instanceData.bVertexAnimation = isSkinnedMesh; mesh->instanceData.materialDataAddress = m_pRenderer->AllocateSceneConstant((void*)mesh->material->GetConstants(), sizeof(ModelMaterialConstant)); mesh->instanceData.objectID = m_nID; SkeletalMeshNode* node = GetNode(mesh->nodeID); float4x4 mtxNodeWorld = mul(m_mtxWorld, node->globalTransform); mesh->instanceData.scale = max(max(abs(m_scale.x), abs(m_scale.y)), abs(m_scale.z)) * m_boundScaleFactor; mesh->instanceData.center = mul(m_mtxWorld, float4(mesh->center, 1.0)).xyz(); //todo : not correct mesh->instanceData.radius = mesh->radius * mesh->instanceData.scale; m_radius = max(m_radius, mesh->instanceData.radius); mesh->instanceData.mtxPrevWorld = mesh->instanceData.mtxWorld; mesh->instanceData.mtxWorld = isSkinnedMesh ? m_mtxWorld : mtxNodeWorld; mesh->instanceData.mtxWorldInverseTranspose = transpose(inverse(mesh->instanceData.mtxWorld)); GfxRayTracingInstanceFlag flags = mesh->material->IsFrontFaceCCW() ? GfxRayTracingInstanceFlagFrontFaceCCW : 0; mesh->instanceIndex = m_pRenderer->AddInstance(mesh->instanceData, mesh->blas.get(), flags); if (mesh->material->IsVertexSkinned()) { m_pRenderer->UpdateRayTracingBLAS(mesh->blas.get(), m_pRenderer->GetSceneAnimationBuffer(), mesh->animPosBufferAddress); } } for (size_t i = 0; i < node->children.size(); ++i) { UpdateMeshConstants(GetNode(node->children[i])); } } void SkeletalMesh::Draw(const SkeletalMeshData* mesh) { if (mesh->material->IsAlphaBlend()) { return; //todo } if (mesh->material->IsVertexSkinned()) { ComputeBatch& batch = m_pRenderer->AddAnimationBatch(); UpdateVertexSkinning(batch, mesh); } RenderBatch& batch = m_pRenderer->AddBasePassBatch(); Draw(batch, mesh, mesh->material->GetPSO()); if (mesh->material->IsVertexSkinned() || !nearly_equal(mesh->instanceData.mtxPrevWorld, mesh->instanceData.mtxWorld)) { RenderBatch& velocityPassBatch = m_pRenderer->AddVelocityPassBatch(); Draw(velocityPassBatch, mesh, mesh->material->GetVelocityPSO()); } if (m_pRenderer->IsEnableMouseHitTest()) { RenderBatch& idPassBatch = m_pRenderer->AddObjectIDPassBatch(); Draw(idPassBatch, mesh, mesh->material->GetIDPSO()); } if (m_nID == m_pRenderer->GetMouseHitObjectID()) { RenderBatch& outlinePassBatch = m_pRenderer->AddForwardPassBatch(); Draw(outlinePassBatch, mesh, mesh->material->GetOutlinePSO()); } } void SkeletalMesh::UpdateVertexSkinning(ComputeBatch& batch, const SkeletalMeshData* mesh) { batch.label = m_name.c_str(); batch.SetPipelineState(mesh->material->GetVertexSkinningPSO()); uint32_t cb[10] = { mesh->vertexCount, mesh->staticPosBufferAddress, mesh->staticNormalBufferAddress, mesh->staticTangentBufferAddress, mesh->animPosBufferAddress, mesh->animNormalBufferAddress, mesh->animTangentBufferAddress, mesh->jointIDBufferAddress, mesh->jointWeightBufferAddress, m_pSkeleton->GetJointMatricesAddress(), }; batch.SetConstantBuffer(1, cb, sizeof(cb)); batch.Dispatch((mesh->vertexCount + 63) / 64, 1, 1); } void SkeletalMesh::Draw(RenderBatch& batch, const SkeletalMeshData* mesh, IGfxPipelineState* pso) { uint32_t root_consts[2] = { mesh->instanceIndex, mesh->prevAnimPosBufferAddress }; batch.label = m_name.c_str(); batch.SetPipelineState(pso); batch.SetConstantBuffer(0, root_consts, sizeof(root_consts)); batch.SetIndexBuffer(m_pRenderer->GetSceneStaticBuffer(), mesh->indexBufferAddress, mesh->indexBufferFormat); batch.DrawIndexed(mesh->indexCount); }
34.230263
154
0.687007
[ "mesh", "geometry", "render", "model", "transform" ]
2d268b9ae5850513a45c3b50fc2471673296c133
1,345
hpp
C++
runtime/src/aderite/scene/selectors/TagSelector.hpp
nfwGytautas/aderite
87a6a5c24a6dcaca80088cb7a4fca1f846a7f22c
[ "MIT" ]
null
null
null
runtime/src/aderite/scene/selectors/TagSelector.hpp
nfwGytautas/aderite
87a6a5c24a6dcaca80088cb7a4fca1f846a7f22c
[ "MIT" ]
null
null
null
runtime/src/aderite/scene/selectors/TagSelector.hpp
nfwGytautas/aderite
87a6a5c24a6dcaca80088cb7a4fca1f846a7f22c
[ "MIT" ]
null
null
null
#pragma once #include "aderite/scene/EntitySelector.hpp" namespace aderite { namespace scene { /** * @brief Entity selector where entities that match the tag list are selected */ class TagSelector final : public EntitySelector { public: /** * @brief Add tag to the selector * @param tag Tag to add */ void addTag(size_t tag); /** * @brief Remove tag from the selector (this requires a full reupdate) * @param tag Tag to remove */ void removeTag(size_t tag); /** * @brief Returns true if the entity has the specified tag, false otherwise */ bool hasTag(size_t tag) const; /** * @brief Returns the tags of the selector */ size_t getTags() const; // Inherited via IEntitySelector reflection::Type getType() const override; bool serialize(const io::Serializer* serializer, YAML::Emitter& emitter) const override; bool deserialize(io::Serializer* serializer, const YAML::Node& data) override; void onEntityAdded(scene::Entity* entity) override; bool isSelected(scene::Entity* entity) const override; size_t size() const override; scene::Entity** getEntities() override; void regenerate() override; private: size_t m_tags = 0; std::vector<scene::Entity*> m_entities; }; } // namespace scene } // namespace aderite
25.865385
92
0.674349
[ "vector" ]
2d274a82ef3731d25b5f5dbac7095c8372a1f013
2,328
hpp
C++
lib/DataBase.hpp
mensinda/modbusSMA
0c2ddd28123ee6a3032fc82d5be8e9c6cfd9a979
[ "Apache-2.0" ]
1
2020-03-15T18:53:26.000Z
2020-03-15T18:53:26.000Z
lib/DataBase.hpp
mensinda/modbusSMA
0c2ddd28123ee6a3032fc82d5be8e9c6cfd9a979
[ "Apache-2.0" ]
null
null
null
lib/DataBase.hpp
mensinda/modbusSMA
0c2ddd28123ee6a3032fc82d5be8e9c6cfd9a979
[ "Apache-2.0" ]
1
2022-03-14T11:06:26.000Z
2022-03-14T11:06:26.000Z
//! \file /* * Copyright (C) 2018 Daniel Mensinger * * 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 #include "mSMAConfig.hpp" #include <sqlite3.h> #include <string> #include <vector> #include "Enums.hpp" #include "Register.hpp" namespace modbusSMA { namespace internal { //! SQL query helper class. //! \internal class SQL_Query final { private: sqlite3_stmt *mSTMT = nullptr; public: SQL_Query() = delete; SQL_Query(sqlite3 *_db, std::string _query); ~SQL_Query(); inline sqlite3_stmt *get() { return mSTMT; } //!< Returns the compiled statement. inline sqlite3_stmt *operator()() { return mSTMT; } //!< Returns the compiled statement. inline bool isValid() { return mSTMT != nullptr; } //!< Returns whether the statement is valid or not. }; } // namespace internal //! Reads the modbusSMA register definitions from a sqlite3 database. class DataBase { public: //! Information for one supported device. struct DevEnum { uint32_t id; //!< The id of the device std::string table; //!< The name of the table where the registers are defined std::string name; //!< The name of the inverter. }; private: std::string mPath = SMA_MODBUS_DEFAULT_DB; sqlite3 * mDB = nullptr; public: DataBase() = delete; DataBase(std::string _path = SMA_MODBUS_DEFAULT_DB); virtual ~DataBase(); DataBase(DataBase const &) = delete; void operator=(DataBase const &) = delete; ErrorCode connect(); bool validate(); void disconnect(); std::vector<std::string> getTableList(); std::vector<DevEnum> getDeviceEnums(); std::vector<Register> getRegisters(std::string _table); bool isConnected() const { return mDB != nullptr; } //!< Returns whether the DB is loaded. }; } // namespace modbusSMA
27.388235
113
0.687715
[ "vector" ]
2d3138b994fd0406644c79cc36bbc9f38b7d080c
74,049
cpp
C++
Compile/src/SpirVProcessor.cpp
akb825/ModularShaderLanguage
5116afac2a27db5d3e62fac38353fce701c8997b
[ "Apache-2.0" ]
6
2018-12-06T10:17:24.000Z
2020-09-20T16:26:47.000Z
Compile/src/SpirVProcessor.cpp
akb825/ModularShaderLanguage
5116afac2a27db5d3e62fac38353fce701c8997b
[ "Apache-2.0" ]
2
2020-02-08T09:32:06.000Z
2020-03-30T02:11:21.000Z
Compile/src/SpirVProcessor.cpp
akb825/ModularShaderLanguage
5116afac2a27db5d3e62fac38353fce701c8997b
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2016-2019 Aaron Barany * * 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 "SpirVProcessor.h" #include <MSL/Compile/CompiledResult.h> #include <MSL/Compile/Output.h> #include <SPIRV/spirv.hpp> #include <algorithm> #include <cassert> #include <cstring> #include <map> #include <unordered_map> #include <unordered_set> namespace msl { namespace { static const unsigned int minVersion = 0x00010000; static const unsigned int firstInstruction = 5; static const unsigned int unknownLength = (unsigned int)-1; static const char* stageNames[] = { "vertex", "tessellation_control", "tessellation_evaluation", "geometry", "fragment", "compute" }; static_assert(sizeof(stageNames)/sizeof(*stageNames) == stageCount, "stage name array is out of sync with enum"); static std::uint32_t typeSizes[] = { // Scalars and vectors static_cast<std::uint32_t>(sizeof(float)), // Float static_cast<std::uint32_t>(sizeof(float)*2), // Vec2 static_cast<std::uint32_t>(sizeof(float)*3), // Vec3 static_cast<std::uint32_t>(sizeof(float)*4), // Vec4 static_cast<std::uint32_t>(sizeof(double)), // Double static_cast<std::uint32_t>(sizeof(double)*2), // DVec2 static_cast<std::uint32_t>(sizeof(double)*3), // DVec3 static_cast<std::uint32_t>(sizeof(double)*4), // DVec4 static_cast<std::uint32_t>(sizeof(int)), // Int static_cast<std::uint32_t>(sizeof(int)*2), // IVec2 static_cast<std::uint32_t>(sizeof(int)*3), // IVec3 static_cast<std::uint32_t>(sizeof(int)*4), // IVec4 static_cast<std::uint32_t>(sizeof(int)), // UInt static_cast<std::uint32_t>(sizeof(int)*2), // UVec2 static_cast<std::uint32_t>(sizeof(int)*3), // UVec3 static_cast<std::uint32_t>(sizeof(int)*4), // UVec4 static_cast<std::uint32_t>(sizeof(int)), // Bool static_cast<std::uint32_t>(sizeof(int)*2), // BVec2 static_cast<std::uint32_t>(sizeof(int)*3), // BVec3 static_cast<std::uint32_t>(sizeof(int)*4), // BVec4 // Matrices static_cast<std::uint32_t>(sizeof(float)*4*2), // Mat2 static_cast<std::uint32_t>(sizeof(float)*4*3), // Mat3 static_cast<std::uint32_t>(sizeof(float)*4*2), // Mat4 static_cast<std::uint32_t>(sizeof(float)*4*3), // Mat2x3 static_cast<std::uint32_t>(sizeof(float)*4*4), // Mat2x4 static_cast<std::uint32_t>(sizeof(float)*4*2), // Mat3x2 static_cast<std::uint32_t>(sizeof(float)*4*4), // Mat3x4 static_cast<std::uint32_t>(sizeof(float)*4*2), // Mat4x2 static_cast<std::uint32_t>(sizeof(float)*4*3), // Mat4x3 static_cast<std::uint32_t>(sizeof(double)*2*2), // DMat2 static_cast<std::uint32_t>(sizeof(double)*4*2), // DMat3 static_cast<std::uint32_t>(sizeof(double)*4*4), // DMat4 static_cast<std::uint32_t>(sizeof(double)*2*3), // DMat2x3 static_cast<std::uint32_t>(sizeof(double)*2*4), // DMat2x4 static_cast<std::uint32_t>(sizeof(double)*4*2), // DMat3x2 static_cast<std::uint32_t>(sizeof(double)*4*4), // DMat3x4 static_cast<std::uint32_t>(sizeof(double)*4*2), // DMat4x2 static_cast<std::uint32_t>(sizeof(double)*4*3), // DMat4x3 }; struct SpirArrayInfo { std::uint32_t type; unsigned int length; }; struct MemberInfo { std::uint32_t offset = unknown; std::uint32_t matrixStride = unknown; bool rowMajor = false; bool builtin = false; std::uint32_t location = unknown; std::uint32_t component = unknown; }; struct IntermediateData { // Names std::unordered_map<std::uint32_t, std::string> names; std::unordered_map<std::uint32_t, std::vector<std::string>> memberNames; // Type info std::unordered_map<std::uint32_t, std::vector<std::uint32_t>> structTypes; std::unordered_map<std::uint32_t, Type> types; std::unordered_map<std::uint32_t, std::vector<MemberInfo>> members; std::unordered_map<std::uint32_t, std::uint32_t> intConstants; std::unordered_map<std::uint32_t, SpirArrayInfo> arrayTypes; std::unordered_map<std::uint32_t, std::uint32_t> arrayStrides; std::unordered_set<std::uint32_t> blocks; std::unordered_set<std::uint32_t> uniformBuffers; // Metadata std::unordered_map<std::uint32_t, std::uint32_t> descriptorSets; std::unordered_map<std::uint32_t, std::uint32_t> bindings; std::unordered_map<std::uint32_t, std::uint32_t> inputAttachmentIndices; std::unordered_map<std::uint32_t, std::uint32_t> locations; std::unordered_map<std::uint32_t, std::uint32_t> components; std::unordered_set<std::uint32_t> inputOutputStructs; // Variable declarations // Make these ordered (except for pointers) so they will be consistent across runs. std::unordered_map<std::uint32_t, std::uint32_t> pointers; std::unordered_set<std::uint32_t> patchVars; std::unordered_set<std::uint32_t> builtinVars; std::map<std::uint32_t, std::uint32_t> uniformVars; std::map<std::uint32_t, std::uint32_t> inputVars; std::map<std::uint32_t, std::uint32_t> outputVars; std::map<std::uint32_t, std::uint32_t> imageVars; std::pair<std::uint32_t, std::uint32_t> pushConstantPointer = std::make_pair(unknown, unknown); std::pair<std::uint32_t, std::uint32_t> clipDistanceMember = std::make_pair(unknown, unknown); std::pair<std::uint32_t, std::uint32_t> cullDistanceMember = std::make_pair(unknown, unknown); }; bool inputIsArray(Stage stage) { return stage == Stage::TessellationControl || stage == Stage::TessellationEvaluation || stage == Stage::Geometry; } bool outputIsArray(Stage stage) { return stage == Stage::TessellationControl; } spv::Op getOp(std::uint32_t value) { return static_cast<spv::Op>(value & spv::OpCodeMask); } unsigned int getWordCount(std::uint32_t value) { return value >> spv::WordCountShift; } std::string readString(std::vector<char>& tempBuffer, const std::vector<std::uint32_t>& spirv, std::size_t start, std::size_t wordCount, std::size_t offset) { tempBuffer.clear(); assert(start + wordCount < spirv.size()); for (std::size_t i = offset; i < wordCount; ++i) { std::uint32_t chars = spirv[start + i]; if (chars == 0) { tempBuffer.push_back(0); break; } else { // 4 characters are stuffed into each int. tempBuffer.push_back(static_cast<char>(chars & 0xFF)); tempBuffer.push_back(static_cast<char>((chars >> 8) & 0xFF)); tempBuffer.push_back(static_cast<char>((chars >> 16) & 0xFF)); tempBuffer.push_back(static_cast<char>((chars >> 24) & 0xFF)); } } return tempBuffer.data(); } void readVector(IntermediateData& data, const std::vector<std::uint32_t>& spirv, std::size_t i, std::uint32_t wordCount) { MSL_UNUSED(wordCount); assert(wordCount == 4); std::uint32_t id = spirv[i + 1]; std::uint32_t typeId = spirv[i + 2]; std::uint32_t length = spirv[i + 3]; auto foundType = data.types.find(typeId); assert(foundType != data.types.end()); switch (foundType->second) { case Type::Bool: switch (length) { case 2: data.types[id] = Type::BVec2; break; case 3: data.types[id] = Type::BVec3; break; case 4: data.types[id] = Type::BVec4; break; default: assert(false); break; } break; case Type::Int: switch (length) { case 2: data.types[id] = Type::IVec2; break; case 3: data.types[id] = Type::IVec3; break; case 4: data.types[id] = Type::IVec4; break; default: assert(false); break; } break; case Type::UInt: switch (length) { case 2: data.types[id] = Type::UVec2; break; case 3: data.types[id] = Type::UVec3; break; case 4: data.types[id] = Type::UVec4; break; default: assert(false); break; } break; case Type::Float: switch (length) { case 2: data.types[id] = Type::Vec2; break; case 3: data.types[id] = Type::Vec3; break; case 4: data.types[id] = Type::Vec4; break; default: assert(false); break; } break; case Type::Double: switch (length) { case 2: data.types[id] = Type::DVec2; break; case 3: data.types[id] = Type::DVec3; break; case 4: data.types[id] = Type::DVec4; break; default: assert(false); break; } break; default: assert(false); break; } } void readMatrix(IntermediateData& data, const std::vector<std::uint32_t>& spirv, std::size_t i, std::uint32_t wordCount) { MSL_UNUSED(wordCount); assert(wordCount == 4); std::uint32_t id = spirv[i + 1]; std::uint32_t typeId = spirv[i + 2]; std::uint32_t length = spirv[i + 3]; auto foundType = data.types.find(typeId); assert(foundType != data.types.end()); switch (foundType->second) { case Type::Vec2: switch (length) { case 2: data.types[id] = Type::Mat2; break; case 3: data.types[id] = Type::Mat3x2; break; case 4: data.types[id] = Type::Mat4x2; break; default: assert(false); } break; case Type::Vec3: switch (length) { case 2: data.types[id] = Type::Mat2x3; break; case 3: data.types[id] = Type::Mat3; break; case 4: data.types[id] = Type::Mat4x3; break; default: assert(false); } break; case Type::Vec4: switch (length) { case 2: data.types[id] = Type::Mat2x4; break; case 3: data.types[id] = Type::Mat3x4; break; case 4: data.types[id] = Type::Mat4; break; default: assert(false); } break; case Type::DVec2: switch (length) { case 2: data.types[id] = Type::DMat2; break; case 3: data.types[id] = Type::DMat3x2; break; case 4: data.types[id] = Type::DMat4x2; break; default: assert(false); } break; case Type::DVec3: switch (length) { case 2: data.types[id] = Type::DMat2x3; break; case 3: data.types[id] = Type::DMat3; break; case 4: data.types[id] = Type::DMat4x3; break; default: assert(false); } break; case Type::DVec4: switch (length) { case 2: data.types[id] = Type::DMat2x4; break; case 3: data.types[id] = Type::DMat3x4; break; case 4: data.types[id] = Type::DMat4; break; default: assert(false); } break; default: assert(false); break; } } void readImage(IntermediateData& data, const std::vector<std::uint32_t>& spirv, std::size_t i, std::uint32_t wordCount) { MSL_UNUSED(wordCount); assert(wordCount >= 8); std::uint32_t id = spirv[i + 1]; std::uint32_t typeId = spirv[i + 2]; std::uint32_t dimension = spirv[i + 3]; std::uint32_t depth = spirv[i + 4]; std::uint32_t array = spirv[i + 5]; std::uint32_t ms = spirv[i + 6]; std::uint32_t sampled = spirv[i + 7]; switch (dimension) { case spv::Dim1D: { assert(!ms); auto foundType = data.types.find(typeId); assert(foundType != data.types.end()); switch (foundType->second) { case Type::Float: if (sampled != 2) { if (depth == 1) { if (array) data.types[id] = Type::Sampler1DArrayShadow; else data.types[id] = Type::Sampler1DShadow; } else { if (array) data.types[id] = Type::Sampler1DArray; else data.types[id] = Type::Sampler1D; } } else { if (array) data.types[id] = Type::Image1DArray; else data.types[id] = Type::Image1D; } break; case Type::Int: if (sampled != 2) { if (array) data.types[id] = Type::ISampler1DArray; else data.types[id] = Type::ISampler1D; } else { if (array) data.types[id] = Type::IImage1DArray; else data.types[id] = Type::IImage1D; } break; case Type::UInt: if (sampled != 2) { if (array) data.types[id] = Type::USampler1DArray; else data.types[id] = Type::USampler1D; } else { if (array) data.types[id] = Type::UImage1DArray; else data.types[id] = Type::UImage1D; } break; default: assert(false); } break; } case spv::Dim2D: { auto foundType = data.types.find(typeId); assert(foundType != data.types.end()); switch (foundType->second) { case Type::Float: if (sampled != 2) { if (depth == 1) { assert(!ms); if (array) data.types[id] = Type::Sampler2DArrayShadow; else data.types[id] = Type::Sampler2DShadow; } else { if (ms) { if (array) data.types[id] = Type::Sampler2DMSArray; else data.types[id] = Type::Sampler2DMS; } else { if (array) data.types[id] = Type::Sampler2DArray; else data.types[id] = Type::Sampler2D; } } } else { if (ms) { if (array) data.types[id] = Type::Image2DMSArray; else data.types[id] = Type::Image2DMS; } else { if (array) data.types[id] = Type::Image2DArray; else data.types[id] = Type::Image2D; } } break; case Type::Int: if (sampled != 2) { if (ms) { if (array) data.types[id] = Type::ISampler2DMSArray; else data.types[id] = Type::ISampler2DMS; } else { if (array) data.types[id] = Type::ISampler2DArray; else data.types[id] = Type::ISampler2D; } } else { if (ms) { if (array) data.types[id] = Type::IImage2DMSArray; else data.types[id] = Type::IImage2DMS; } else { if (array) data.types[id] = Type::IImage2DArray; else data.types[id] = Type::IImage2D; } } break; case Type::UInt: if (sampled != 2) { if (ms) { if (array) data.types[id] = Type::USampler2DMSArray; else data.types[id] = Type::USampler2DMS; } else { if (array) data.types[id] = Type::USampler2DArray; else data.types[id] = Type::USampler2D; } } else { if (ms) { if (array) data.types[id] = Type::UImage2DMSArray; else data.types[id] = Type::UImage2DMS; } else { if (array) data.types[id] = Type::UImage2DArray; else data.types[id] = Type::UImage2D; } } break; default: assert(false); break; } break; } case spv::Dim3D: { assert(!ms); assert(!array); auto foundType = data.types.find(typeId); assert(foundType != data.types.end()); switch (foundType->second) { case Type::Float: if (sampled != 2) data.types[id] = Type::Sampler3D; else data.types[id] = Type::Image3D; break; case Type::Int: if (sampled != 2) data.types[id] = Type::ISampler3D; else data.types[id] = Type::IImage3D; break; case Type::UInt: if (sampled != 2) data.types[id] = Type::USampler3D; else data.types[id] = Type::UImage3D; break; default: assert(false); break; } break; } case spv::DimCube: { assert(!ms); assert(!array); auto foundType = data.types.find(typeId); assert(foundType != data.types.end()); switch (foundType->second) { case Type::Float: if (sampled != 2) { if (depth == 1) data.types[id] = Type::SamplerCubeShadow; else data.types[id] = Type::SamplerCube; } else data.types[id] = Type::ImageCube; break; case Type::Int: if (sampled != 2) data.types[id] = Type::ISamplerCube; else data.types[id] = Type::IImageCube; break; case Type::UInt: if (sampled != 2) data.types[id] = Type::USamplerCube; else data.types[id] = Type::UImageCube; break; default: assert(false); break; } break; } case spv::DimRect: { assert(!ms); assert(!array); auto foundType = data.types.find(typeId); assert(foundType != data.types.end()); switch (foundType->second) { case Type::Float: if (sampled != 2) { if (depth == 1) data.types[id] = Type::Sampler2DRectShadow; else data.types[id] = Type::Sampler2DRect; } else data.types[id] = Type::Image2DRect; break; case Type::Int: if (sampled != 2) data.types[id] = Type::ISampler2DRect; else data.types[id] = Type::IImage2DRect; break; case Type::UInt: if (sampled != 2) data.types[id] = Type::USampler2DRect; else data.types[id] = Type::UImage2DRect; break; default: assert(false); break; } break; } case spv::DimBuffer: { assert(!ms); assert(!array); if (sampled != 2) data.types[id] = Type::SamplerBuffer; else data.types[id] = Type::ImageBuffer; break; } case spv::DimSubpassData: { assert(!array); assert(sampled == 2); auto foundType = data.types.find(typeId); assert(foundType != data.types.end()); switch (foundType->second) { case Type::Float: if (ms) data.types[id] = Type::SubpassInputMS; else data.types[id] = Type::SubpassInput; break; case Type::Int: if (ms) data.types[id] = Type::ISubpassInputMS; else data.types[id] = Type::ISubpassInput; break; case Type::UInt: if (ms) data.types[id] = Type::USubpassInputMS; else data.types[id] = Type::USubpassInput; break; default: assert(false); break; } break; } default: assert(false); break; } } bool isMatrix(Type type) { switch (type) { case Type::Mat2: case Type::Mat3: case Type::Mat4: case Type::Mat2x3: case Type::Mat2x4: case Type::Mat3x2: case Type::Mat3x4: case Type::Mat4x2: case Type::Mat4x3: case Type::DMat2: case Type::DMat3: case Type::DMat4: case Type::DMat2x3: case Type::DMat2x4: case Type::DMat3x2: case Type::DMat3x4: case Type::DMat4x2: case Type::DMat4x3: return true; default: return false; } } unsigned int getRowCount(Type type) { switch (type) { case Type::Mat2: case Type::Mat3x2: case Type::Mat4x2: case Type::DMat2: case Type::DMat3x2: case Type::DMat4x2: return 2; case Type::Mat3: case Type::Mat2x3: case Type::Mat4x3: case Type::DMat3: case Type::DMat2x3: case Type::DMat4x3: return 3; case Type::Mat4: case Type::Mat2x4: case Type::Mat3x4: case Type::DMat4: case Type::DMat2x4: case Type::DMat3x4: return 4; default: return 0; } } unsigned int getColumnCount(Type type) { switch (type) { case Type::Mat2: case Type::Mat2x3: case Type::Mat2x4: case Type::DMat2: case Type::DMat2x3: case Type::DMat2x4: return 2; case Type::Mat3: case Type::Mat3x2: case Type::Mat3x4: case Type::DMat3: case Type::DMat3x2: case Type::DMat3x4: return 3; case Type::Mat4: case Type::Mat4x2: case Type::Mat4x3: case Type::DMat4: case Type::DMat4x2: case Type::DMat4x3: return 4; default: return 0; } } bool isSampledImage(Type type) { switch (type) { case Type::Sampler1D: case Type::Sampler2D: case Type::Sampler3D: case Type::SamplerCube: case Type::Sampler1DShadow: case Type::Sampler2DShadow: case Type::Sampler1DArray: case Type::Sampler2DArray: case Type::Sampler1DArrayShadow: case Type::Sampler2DArrayShadow: case Type::Sampler2DMS: case Type::Sampler2DMSArray: case Type::SamplerCubeShadow: case Type::SamplerBuffer: case Type::Sampler2DRect: case Type::Sampler2DRectShadow: case Type::ISampler1D: case Type::ISampler2D: case Type::ISampler3D: case Type::ISamplerCube: case Type::ISampler1DArray: case Type::ISampler2DArray: case Type::ISampler2DMS: case Type::ISampler2DMSArray: case Type::ISampler2DRect: case Type::USampler1D: case Type::USampler2D: case Type::USampler3D: case Type::USamplerCube: case Type::USampler1DArray: case Type::USampler2DArray: case Type::USampler2DMS: case Type::USampler2DMSArray: case Type::USampler2DRect: return true; default: return false; } } bool isImage(Type type) { switch (type) { case Type::Image1D: case Type::Image2D: case Type::Image3D: case Type::ImageCube: case Type::Image1DArray: case Type::Image2DArray: case Type::Image2DMS: case Type::Image2DMSArray: case Type::ImageBuffer: case Type::Image2DRect: case Type::IImage1D: case Type::IImage2D: case Type::IImage3D: case Type::IImageCube: case Type::IImage1DArray: case Type::IImage2DArray: case Type::IImage2DMS: case Type::IImage2DMSArray: case Type::IImage2DRect: case Type::UImage1D: case Type::UImage2D: case Type::UImage3D: case Type::UImageCube: case Type::UImage1DArray: case Type::UImage2DArray: case Type::UImage2DMS: case Type::UImage2DMSArray: case Type::UImage2DRect: return true; default: return false; } } bool isSubpassInput(Type type) { switch (type) { case Type::SubpassInput: case Type::SubpassInputMS: case Type::ISubpassInput: case Type::ISubpassInputMS: case Type::USubpassInput: case Type::USubpassInputMS: return true; default: return false; } } std::uint32_t getTypeSize(const SpirVProcessor& processor, Type type, std::uint32_t structIndex) { if (type == Type::Struct) { assert(structIndex < processor.structs.size()); return processor.structs[structIndex].size; } else { unsigned int typeIndex = static_cast<unsigned int>(type); assert(typeIndex < sizeof(typeSizes)/sizeof(*typeSizes)); return typeSizes[typeIndex]; } } Type getType(std::vector<ArrayInfo>& arrayElements, std::uint32_t& structIndex, SpirVProcessor& processor, const IntermediateData& data, std::uint32_t typeId) { structIndex = unknown; // Resolve arrays first. arrayElements.clear(); auto foundArray = data.arrayTypes.find(typeId); while (foundArray != data.arrayTypes.end()) { arrayElements.emplace_back(); arrayElements.back().length = foundArray->second.length; auto foundArrayStride = data.arrayStrides.find(typeId); if (foundArrayStride == data.arrayStrides.end()) arrayElements.back().stride = unknown; else arrayElements.back().stride = foundArrayStride->second; typeId = foundArray->second.type; foundArray = data.arrayTypes.find(typeId); } // Check if it's a struct. auto foundStruct = data.structTypes.find(typeId); if (foundStruct == data.structTypes.end()) { auto foundType = data.types.find(typeId); assert(foundType != data.types.end()); return foundType->second; } // Get the index of the struct. auto foundStructId = std::find(processor.structIds.begin(), processor.structIds.end(), typeId); if (foundStructId != processor.structIds.end()) { structIndex = static_cast<std::uint32_t>(foundStructId - processor.structIds.begin()); return Type::Struct; } // Haven't encountered this struct before; add it. // Get the name. auto foundStructName = data.names.find(typeId); assert(foundStructName != data.names.end()); Struct newStruct; newStruct.name = foundStructName->second; // Get the member info. auto foundMemberNames = data.memberNames.find(typeId); assert(foundMemberNames != data.memberNames.end()); assert(foundMemberNames->second.size() == foundStruct->second.size()); auto foundMembers = data.members.find(typeId); assert(foundMembers == data.members.end() || foundMembers->second.size() <= foundStruct->second.size()); newStruct.size = 0; newStruct.members.resize(foundStruct->second.size()); for (std::size_t i = 0; i < foundStruct->second.size(); ++i) { std::uint32_t memberTypeId = foundStruct->second[i]; StructMember& member = newStruct.members[i]; member.name = foundMemberNames->second[i]; if (foundMembers == data.members.end() || i >= foundMembers->second.size()) member.offset = unknown; else member.offset = foundMembers->second[i].offset; member.type = getType(member.arrayElements, member.structIndex, processor, data, memberTypeId); // Get the size of the member. if (!member.arrayElements.empty()) { // If an array, the size is the stride times the number of elements. foundArray = data.arrayTypes.find(memberTypeId); assert(foundArray != data.arrayTypes.end()); if (foundArray->second.length == unknown) member.size = unknown; else { auto foundArrayStride = data.arrayStrides.find(memberTypeId); if (foundArrayStride == data.arrayStrides.end()) member.size = unknown; else member.size = foundArrayStride->second*foundArray->second.length; } } else if (isMatrix(member.type)) { // Matrices have their own strides stored with the struct. if (foundMembers != data.members.end() && i < foundMembers->second.size()) { member.rowMajor = foundMembers->second[i].rowMajor; if (member.rowMajor) member.size = foundMembers->second[i].matrixStride*getRowCount(member.type); else member.size = foundMembers->second[i].matrixStride*getColumnCount(member.type); } } else member.size = getTypeSize(processor, member.type, member.structIndex); } // Get the struct size based on the last member. // If the size of the last member is unknown (due to an unsized array), it's based on the offset // of the last element. if (!newStruct.members.empty()) { const StructMember& lastMember = newStruct.members.back(); newStruct.size = lastMember.offset; if (newStruct.size != unknown && lastMember.size != unknown) { newStruct.size += lastMember.size; const unsigned int minAlignment = static_cast<unsigned int>(sizeof(float)*4); newStruct.size = ((newStruct.size + minAlignment - 1)/minAlignment)*minAlignment; } } assert(processor.structs.size() == processor.structIds.size()); processor.structs.push_back(std::move(newStruct)); processor.structIds.push_back(typeId); structIndex = static_cast<std::uint32_t>(processor.structs.size() - 1); return Type::Struct; } std::uint32_t getUnderlyingTypeId(const IntermediateData& data, std::uint32_t typeId) { auto foundArray = data.arrayTypes.find(typeId); while (foundArray != data.arrayTypes.end()) { typeId = foundArray->second.type; foundArray = data.arrayTypes.find(typeId); } return typeId; } std::vector<std::uint32_t> makeArrayLengths(const std::vector<ArrayInfo>& arrayElements) { std::vector<std::uint32_t> lengths; lengths.resize(arrayElements.size()); for (std::size_t i = 0; i < arrayElements.size(); ++i) lengths[i] = arrayElements[i].length; return lengths; } void addUniforms(SpirVProcessor& processor, const IntermediateData& data) { bool hasPushConstant = data.pushConstantPointer.first != unknown; std::size_t totalUniforms = data.uniformVars.size() + data.imageVars.size() + hasPushConstant; processor.uniforms.resize(totalUniforms); processor.uniformIds.resize(totalUniforms); std::size_t i = 0; if (hasPushConstant) { processor.uniformIds[i] = data.pushConstantPointer.first; std::uint32_t typeId = data.pushConstantPointer.second; Uniform& uniform = processor.uniforms[i]; uniform.type = getType(uniform.arrayElements, uniform.structIndex, processor, data, typeId); assert(uniform.type == Type::Struct); uniform.name = processor.structs[uniform.structIndex].name; uniform.uniformType = UniformType::PushConstant; uniform.descriptorSet = unknown; uniform.binding = unknown; uniform.inputAttachmentIndex = unknown; uniform.samplerIndex = unknown; ++i; } for (const auto& uniformIndices : data.uniformVars) { processor.uniformIds[i] = uniformIndices.first; std::uint32_t typeId = uniformIndices.second; std::uint32_t underlyingTypeId = getUnderlyingTypeId(data, typeId); Uniform& uniform = processor.uniforms[i]; uniform.type = getType(uniform.arrayElements, uniform.structIndex, processor, data, typeId); if (uniform.type == Type::Struct) uniform.name = processor.structs[uniform.structIndex].name; else { auto foundName = data.names.find(uniformIndices.first); assert(foundName != data.names.end()); uniform.name = foundName->second; } if (data.blocks.find(underlyingTypeId) != data.blocks.end()) uniform.uniformType = UniformType::Block; else { assert(data.uniformBuffers.find(underlyingTypeId) != data.uniformBuffers.end()); uniform.uniformType = UniformType::BlockBuffer; } auto foundDescriptorSet = data.descriptorSets.find(uniformIndices.first); if (foundDescriptorSet == data.descriptorSets.end()) uniform.descriptorSet = unknown; else uniform.descriptorSet = foundDescriptorSet->second; auto foundBinding = data.bindings.find(uniformIndices.first); if (foundBinding == data.bindings.end()) uniform.binding = unknown; else uniform.binding = foundBinding->second; uniform.inputAttachmentIndex = unknown; uniform.samplerIndex = unknown; ++i; } for (const auto& imageIndices : data.imageVars) { processor.uniformIds[i] = imageIndices.first; std::uint32_t typeId = imageIndices.second; Uniform& uniform = processor.uniforms[i]; auto foundName = data.names.find(imageIndices.first); assert(foundName != data.names.end()); uniform.name = foundName->second; uniform.type = getType(uniform.arrayElements, uniform.structIndex, processor, data, typeId); if (isSampledImage(uniform.type)) uniform.uniformType = UniformType::SampledImage; else if (isSubpassInput(uniform.type)) uniform.uniformType = UniformType::SubpassInput; else uniform.uniformType = UniformType::Image; auto foundDescriptorSet = data.descriptorSets.find(imageIndices.first); if (foundDescriptorSet == data.descriptorSets.end()) uniform.descriptorSet = unknown; else uniform.descriptorSet = foundDescriptorSet->second; auto foundBinding = data.bindings.find(imageIndices.first); if (foundBinding == data.bindings.end()) uniform.binding = unknown; else uniform.binding = foundBinding->second; auto foundInputAttachmentIndex = data.inputAttachmentIndices.find(imageIndices.first); if (foundInputAttachmentIndex == data.inputAttachmentIndices.end()) uniform.inputAttachmentIndex = unknown; else uniform.inputAttachmentIndex = foundInputAttachmentIndex->second; uniform.samplerIndex = unknown; ++i; } } bool addInputsOutputs(Output& output, std::vector<SpirVProcessor::InputOutput>& inputOutputs, std::vector<std::uint32_t>& inputOutputIds, SpirVProcessor& processor, IntermediateData& data, const std::map<std::uint32_t, std::uint32_t>& inputOutputVars) { std::string ioName = &inputOutputs == &processor.inputs ? "input" : "output"; inputOutputs.reserve(inputOutputVars.size()); inputOutputIds.reserve(inputOutputVars.size()); std::vector<ArrayInfo> arrayElements; for (const auto& inputOutputIndices : inputOutputVars) { inputOutputs.emplace_back(); inputOutputIds.emplace_back(); inputOutputIds.back() = inputOutputIndices.first; std::uint32_t typeId = inputOutputIndices.second; std::uint32_t underlyingTypeId = getUnderlyingTypeId(data, typeId); SpirVProcessor::InputOutput& inputOutput = inputOutputs.back(); auto foundName = data.names.find(inputOutputIndices.first); assert(foundName != data.names.end()); inputOutput.name = foundName->second; inputOutput.type = getType(arrayElements, inputOutput.structIndex, processor, data, typeId); inputOutput.arrayElements = makeArrayLengths(arrayElements); inputOutput.patch = data.patchVars.find(inputOutputIndices.first) != data.patchVars.end(); inputOutput.autoAssigned = true; if (inputOutput.type == Type::Struct) { const Struct& structType = processor.structs[inputOutput.structIndex]; // Make sure any struct is only used once. if (data.inputOutputStructs.find(underlyingTypeId) != data.inputOutputStructs.end()) { output.addMessage(Output::Level::Error, processor.fileName, processor.line, processor.column, false, "linker error: struct " + structType.name + " is used for multiple inputs and outputs"); return false; } data.inputOutputStructs.insert(underlyingTypeId); // Make sure there's no recursive structs. for (const StructMember& member : structType.members) { if (member.type == Type::Struct) { output.addMessage(Output::Level::Error, processor.fileName, processor.line, processor.column, false, "linker error: " + ioName + " member " + structType.name + "." + member.name + " is a struct"); return false; } } // Don't allow arbitrary arrays of input/output blocks. bool shouldBeArray = !inputOutput.patch && (&inputOutputs == &processor.inputs ? inputIsArray(processor.stage) : outputIsArray(processor.stage)); if (!inputOutput.arrayElements.empty() != shouldBeArray) { if (shouldBeArray) { output.addMessage(Output::Level::Error, processor.fileName, processor.line, processor.column, false, "linker error: " + ioName + " interface block " + structType.name + " must be an array"); } else { output.addMessage(Output::Level::Error, processor.fileName, processor.line, processor.column, false, "linker error: " + ioName + " interface block " + structType.name + " must not be an array"); } return false; } inputOutput.memberLocations.resize(structType.members.size(), std::make_pair(unknown, 0)); auto foundMembers = data.members.find(processor.structIds[inputOutput.structIndex]); if (foundMembers != data.members.end()) { // Ignore structs with builtin variables. if (foundMembers != data.members.end() && foundMembers->second[0].builtin) { inputOutputs.pop_back(); inputOutputIds.pop_back(); continue; } assert(foundMembers->second.size() <= inputOutput.memberLocations.size()); for (std::size_t j = 0; j < foundMembers->second.size(); ++j) { if (foundMembers->second[j].location == unknown) continue; inputOutput.autoAssigned = false; inputOutput.memberLocations[j].first = foundMembers->second[j].location; if (foundMembers->second[j].component != unknown) inputOutput.memberLocations[j].second = foundMembers->second[j].component; } } auto foundLocation = data.locations.find(inputOutputIndices.first); if (foundLocation == data.locations.end()) inputOutput.location = unknown; else { inputOutput.location = foundLocation->second; inputOutput.autoAssigned = false; } inputOutput.component = unknown; } else { // Ignore builtin variables. if (data.builtinVars.find(inputOutputIndices.first) != data.builtinVars.end()) { inputOutputs.pop_back(); inputOutputIds.pop_back(); continue; } inputOutput.component = 0; auto foundLocation = data.locations.find(inputOutputIndices.first); if (foundLocation == data.locations.end()) inputOutput.location = unknown; else { inputOutput.autoAssigned = false; inputOutput.location = foundLocation->second; auto foundComponent = data.components.find(inputOutputIndices.first); if (foundComponent != data.components.end()) inputOutput.component = foundComponent->second; } } } return true; } bool addInputs(Output& output, SpirVProcessor& processor, IntermediateData& data) { return addInputsOutputs(output, processor.inputs, processor.inputIds, processor, data, data.inputVars); } bool addOutputs(Output& output, SpirVProcessor& processor, IntermediateData& data) { return addInputsOutputs(output, processor.outputs, processor.outputIds, processor, data, data.outputVars); } void addPushConstants(SpirVProcessor& processor, const IntermediateData& data) { if (data.pushConstantPointer.first == unknown) { processor.pushConstantStruct = unknown; return; } std::vector<ArrayInfo> arrayElements; Type type = getType(arrayElements, processor.pushConstantStruct, processor, data, data.pushConstantPointer.second); assert(type == Type::Struct); MSL_UNUSED(type); assert(arrayElements.empty()); } bool addComponents(std::vector<std::uint8_t>& locations, std::size_t curLocation, std::uint32_t componentMask) { if (locations.size() <= curLocation) locations.resize(curLocation + 1, 0); if (locations[curLocation] & componentMask) return false; locations[curLocation] = static_cast<std::uint8_t>(locations[curLocation] | componentMask); return true; } bool fillLocation(std::vector<std::uint8_t>& locations, std::size_t& curLocation, std::uint32_t component, Type type, const std::vector<std::uint32_t>& arrayElements, bool removeFirstArray) { assert(component < 4); // Get the total number of elements. std::uint32_t elementCount = 1; for (std::size_t i = removeFirstArray; i < arrayElements.size(); ++i) { assert(arrayElements[i] != 0); if (arrayElements[i] == unknown) return false; elementCount *= arrayElements[i]; } // Treat matrices the same as arrays. switch (type) { case Type::Mat2: type = Type::Vec2; elementCount *= 2; break; case Type::Mat3: type = Type::Vec3; elementCount *= 3; break; case Type::Mat4: type = Type::Vec4; elementCount *= 4; break; case Type::Mat2x3: type = Type::Vec3; elementCount *= 2; break; case Type::Mat2x4: type = Type::Vec4; elementCount *= 2; break; case Type::Mat3x2: type = Type::Vec2; elementCount *= 3; break; case Type::Mat3x4: type = Type::Vec4; elementCount *= 3; break; case Type::Mat4x2: type = Type::Vec2; elementCount *= 4; break; case Type::Mat4x3: type = Type::Vec3; elementCount *= 4; break; case Type::DMat2: type = Type::DVec2; elementCount *= 2; break; case Type::DMat3: type = Type::DVec3; elementCount *= 3; break; case Type::DMat4: type = Type::DVec4; elementCount *= 4; break; case Type::DMat2x3: type = Type::DVec3; elementCount *= 2; break; case Type::DMat2x4: type = Type::DVec4; elementCount *= 2; break; case Type::DMat3x2: type = Type::DVec2; elementCount *= 3; break; case Type::DMat3x4: type = Type::DVec4; elementCount *= 3; break; case Type::DMat4x2: type = Type::DVec2; elementCount *= 4; break; case Type::DMat4x3: type = Type::DVec3; elementCount *= 4; break; default: break; } switch (type) { case Type::Float: case Type::Int: case Type::UInt: case Type::Bool: for (std::uint32_t i = 0; i < elementCount; ++i, ++curLocation) { if (!addComponents(locations, curLocation, 1 << component)) return false; } break; case Type::Vec2: case Type::IVec2: case Type::UVec2: case Type::BVec2: if (component > 2) return false; for (std::uint32_t i = 0; i < elementCount; ++i, ++curLocation) { if (!addComponents(locations, curLocation, (1 << component) | (2 << component))) return false; } break; case Type::Vec3: case Type::IVec3: case Type::UVec3: case Type::BVec3: if (component > 1) return false; for (std::uint32_t i = 0; i < elementCount; ++i, ++curLocation) { if (!addComponents(locations, curLocation, (1 << component) | (2 << component) | (4 << component))) return false; } break; case Type::Vec4: case Type::IVec4: case Type::UVec4: case Type::BVec4: if (component != 0) return false; for (std::uint32_t i = 0; i < elementCount; ++i, ++curLocation) { if (!addComponents(locations, curLocation, 0xF)) return false; } break; case Type::Double: if (component != 0 && component != 2) return false; for (std::uint32_t i = 0; i < elementCount; ++i, ++curLocation) { if (!addComponents(locations, curLocation, (1 << component) | (2 << component))) return false; } break; case Type::DVec2: if (component != 0) return false; for (std::uint32_t i = 0; i < elementCount; ++i, ++curLocation) { if (!addComponents(locations, curLocation, 0xF)) return false; } break; case Type::DVec3: if (component != 0) return false; for (std::uint32_t i = 0; i < elementCount; ++i, ++curLocation) { if (!addComponents(locations, curLocation, 0xF)) return false; if (!addComponents(locations, ++curLocation, 0x3)) return false; } break; case Type::DVec4: if (component != 0) return false; for (std::uint32_t i = 0; i < elementCount; ++i, ++curLocation) { if (!addComponents(locations, curLocation, 0xF)) return false; if (!addComponents(locations, ++curLocation, 0xF)) return false; } break; default: assert(false); return false; } return true; } bool assignInputsOutputs(Output& output, const SpirVProcessor& processor, std::vector<SpirVProcessor::InputOutput>& inputsOutputs, bool removeFirstArray) { std::string ioName = &inputsOutputs == &processor.inputs ? "input" : "output"; std::size_t curLocation = 0; std::vector<std::uint8_t> locations; bool hasExplicitLocations = false; bool hasImplicitLocations = false; for (SpirVProcessor::InputOutput& io : inputsOutputs) { if (io.type == Type::Struct) { const Struct& ioStruct = processor.structs[io.structIndex]; if (io.memberLocations.empty() || io.memberLocations[0].first == unknown) { if (io.location == unknown) hasImplicitLocations = true; else { curLocation = io.location; hasExplicitLocations = true; } } else { assert(ioStruct.members.size() == io.memberLocations.size()); hasExplicitLocations = true; } for (std::size_t i = 0; i < ioStruct.members.size(); ++i) { std::uint32_t component = 0; if (io.memberLocations[i].first == unknown) { io.memberLocations[i].first = static_cast<std::uint32_t>(curLocation); io.memberLocations[i].second = component; } else { curLocation = io.memberLocations[i].first; component = io.memberLocations[i].second; } if (!fillLocation(locations, curLocation, component, ioStruct.members[i].type, makeArrayLengths(ioStruct.members[i].arrayElements), false)) { output.addMessage(Output::Level::Error, processor.fileName, processor.line, processor.column, false, "linker error: cannot assign location for " + ioName + " block element " + ioStruct.name + "." + ioStruct.members[i].name); return false; } } } else { std::uint32_t component = 0; if (io.location == unknown) { io.location = static_cast<std::uint32_t>(curLocation); io.component = component; hasImplicitLocations = true; } else { curLocation = io.location; component = io.component; hasExplicitLocations = true; } if (!fillLocation(locations, curLocation, component, io.type, io.arrayElements, removeFirstArray)) { output.addMessage(Output::Level::Error, processor.fileName, processor.line, processor.column, false, "linker error: cannot assign location for " + ioName + " " + io.name); return false; } } } if (hasImplicitLocations && hasExplicitLocations) { output.addMessage(Output::Level::Error, processor.fileName, processor.line, processor.column, false, "linker error: " + ioName + " declarations mix implicit and explicit locations " + "in stage " + stageNames[static_cast<unsigned int>(processor.stage)]); return false; } return true; } bool findLinkedMember(Output& output, std::uint32_t& outputIndex, std::uint32_t& memberIndex, const SpirVProcessor& processor, const std::string& name) { outputIndex = unknown; memberIndex = unknown; for (std::uint32_t i = 0; i < processor.outputs.size(); ++i) { if (processor.outputs[i] .type != Type::Struct) continue; const Struct& outputStruct = processor.structs[processor.outputs[i].structIndex]; for (std::uint32_t j = 0; j < outputStruct.members.size(); ++j) { if (outputStruct.members[j].name == name) { if (outputIndex != unknown) { output.addMessage(Output::Level::Error, processor.fileName, processor.line, processor.column, false, "linker error: multiple members from output interface blocks match the " "name " + name + " in stage " + stageNames[static_cast<unsigned int>(processor.stage)]); return false; } outputIndex = i; memberIndex = j; } } } if (outputIndex == unknown) { output.addMessage(Output::Level::Error, processor.fileName, processor.line, processor.column, false, "linker error: cannot find output interface block member with name " + name + " in stage " + stageNames[static_cast<unsigned int>(processor.stage)]); return false; } assert(memberIndex != unknown); return true; } bool inputOutputArraysEqual(const std::vector<std::uint32_t>& outputArray, bool removeFirstOutput, const std::vector<std::uint32_t>& inputArray, bool removeFirstInput) { if (removeFirstOutput && outputArray.empty()) return false; if (removeFirstInput && inputArray.empty()) return false; if (outputArray.size() - removeFirstOutput != inputArray.size() - removeFirstInput) return false; for (std::size_t i = removeFirstOutput; i < outputArray.size(); ++i) { if (outputArray[i] != inputArray[i - removeFirstOutput + removeFirstInput]) return false; } return true; } void addDummyDescriptorSet(std::vector<std::uint32_t>& spirv, std::uint32_t id) { spirv.push_back((4 << spv::WordCountShift) | spv::OpDecorate); spirv.push_back(id); spirv.push_back(spv::DecorationDescriptorSet); spirv.push_back(unknown); } void addDummyBinding(std::vector<std::uint32_t>& spirv, std::uint32_t id) { spirv.push_back((4 << spv::WordCountShift) | spv::OpDecorate); spirv.push_back(id); spirv.push_back(spv::DecorationBinding); spirv.push_back(unknown); } void addLocation(std::vector<std::uint32_t>& spirv, std::uint32_t id, std::uint32_t index) { spirv.push_back((4 << spv::WordCountShift) | spv::OpDecorate); spirv.push_back(id); spirv.push_back(spv::DecorationLocation); spirv.push_back(index); } void addComponent(std::vector<std::uint32_t>& spirv, std::uint32_t id, std::uint32_t index) { if (index == 0) return; spirv.push_back((4 << spv::WordCountShift) | spv::OpDecorate); spirv.push_back(id); spirv.push_back(spv::DecorationComponent); spirv.push_back(index); } void addMemberLocation(std::vector<std::uint32_t>& spirv, std::uint32_t id, std::uint32_t memberIndex, std::uint32_t index) { spirv.push_back((5 << spv::WordCountShift) | spv::OpMemberDecorate); spirv.push_back(id); spirv.push_back(memberIndex); spirv.push_back(spv::DecorationLocation); spirv.push_back(index); } void addMemberComponent(std::vector<std::uint32_t>& spirv, std::uint32_t id, std::uint32_t memberIndex, std::uint32_t index) { if (index == 0) return; spirv.push_back((5 << spv::WordCountShift) | spv::OpMemberDecorate); spirv.push_back(id); spirv.push_back(memberIndex); spirv.push_back(spv::DecorationComponent); spirv.push_back(index); } void areOutputMembersReferenced(const IntermediateData& data, const std::vector<std::uint32_t>& spirv, std::size_t firstFunction, const std::vector<std::pair<std::uint32_t, std::uint32_t>>& structMembers, std::vector<bool>& referenced) { assert(structMembers.size() == referenced.size()); for (std::size_t i = firstFunction; i < spirv.size();) { spv::Op op = getOp(spirv[i]); unsigned int wordCount = getWordCount(spirv[i]); assert(wordCount > 0 && wordCount + i <= spirv.size()); switch (op) { case spv::OpAccessChain: { if (wordCount < 5) break; std::uint32_t pointer = spirv[i + 3]; auto foundOutput = data.outputVars.find(pointer); if (foundOutput == data.outputVars.end()) break; std::uint32_t constant = spirv[i + 4]; auto foundConstant = data.intConstants.find(constant); if (foundConstant == data.intConstants.end()) break; for (std::size_t j = 0; j < structMembers.size(); ++j) { if (structMembers[j].first == foundOutput->second && structMembers[j].second == foundConstant->second) { referenced[j] = true; break; } } break; } default: break; } i += wordCount; } } std::uint32_t getMemberArraySize(const IntermediateData& data, const std::pair<std::uint32_t, std::uint32_t>& structMember) { auto foundStruct = data.structTypes.find(structMember.first); if (foundStruct == data.structTypes.end()) return 0; assert(structMember.second < foundStruct->second.size()); auto foundArray = data.arrayTypes.find(foundStruct->second[structMember.second]); if (foundArray == data.arrayTypes.end()) return 0; return foundArray->second.length; } } // namespace namespace compile { inline bool operator==(const ArrayInfo& info1, const ArrayInfo& info2) { return info1.length == info2.length && info1.stride == info2.stride; } inline bool operator!=(const ArrayInfo& info1, const ArrayInfo& info2) { return !(info1 == info2); } } // namespace compile bool SpirVProcessor::extract(Output& output, const std::string& fileName, std::size_t line, std::size_t column, const std::vector<std::uint32_t>& spirv, Stage stage) { this->stage = stage; this->fileName = fileName; this->line = line; this->column = column; this->spirv = &spirv; MSL_UNUSED(minVersion); assert(spirv.size() > firstInstruction); assert(spirv[0] == spv::MagicNumber); assert(spirv[1] >= minVersion && spirv[1] <= spv::Version); std::vector<char> tempBuffer; IntermediateData data; // Grab the metadata we want out of the SPIR-V. bool done = false; std::size_t firstFunction = 0; for (std::size_t i = firstInstruction; i < spirv.size() && !done;) { spv::Op op = getOp(spirv[i]); unsigned int wordCount = getWordCount(spirv[i]); assert(wordCount > 0 && wordCount + i <= spirv.size()); switch (op) { // Extract names. case spv::OpName: { assert(wordCount >= 3); std::uint32_t id = spirv[i + 1]; data.names[id] = readString(tempBuffer, spirv, i, wordCount, 2); break; } case spv::OpMemberName: { assert(wordCount >= 4); std::uint32_t id = spirv[i + 1]; std::uint32_t member = spirv[i + 2]; std::vector<std::string>& thisMemberNames = data.memberNames[id]; if (thisMemberNames.size() <= member) thisMemberNames.resize(member + 1); thisMemberNames[member] = readString(tempBuffer, spirv, i, wordCount, 3); break; } // Extract decorations that we care about. case spv::OpDecorate: { assert(wordCount >= 3); std::uint32_t id = spirv[i + 1]; switch (spirv[i + 2]) { case spv::DecorationDescriptorSet: assert(wordCount == 4); data.descriptorSets[id] = spirv[i + 3]; break; case spv::DecorationBinding: assert(wordCount == 4); data.bindings[id] = spirv[i + 3]; break; case spv::DecorationInputAttachmentIndex: assert(wordCount == 4); data.inputAttachmentIndices[id] = spirv[i + 3]; break; case spv::DecorationLocation: assert(wordCount == 4); data.locations[id] = spirv[i + 3]; break; case spv::DecorationComponent: assert(wordCount == 4); data.components[id] = spirv[i + 3]; break; case spv::DecorationArrayStride: assert(wordCount == 4); data.arrayStrides[id] = spirv[i + 3]; break; case spv::DecorationBlock: data.blocks.insert(id); break; case spv::DecorationBufferBlock: data.uniformBuffers.insert(id); break; case spv::DecorationPatch: data.patchVars.insert(id); break; case spv::DecorationBuiltIn: assert(wordCount == 4); data.builtinVars.insert(id); break; } break; } case spv::OpMemberDecorate: { assert(wordCount >= 4); std::uint32_t id = spirv[i + 1]; std::uint32_t member = spirv[i + 2]; std::vector<MemberInfo>& memberInfo = data.members[id]; if (memberInfo.size() <= member) memberInfo.resize(member + 1); switch (spirv[i + 3]) { case spv::DecorationOffset: { assert(wordCount == 5); memberInfo[member].offset = spirv[i + 4]; break; } case spv::DecorationMatrixStride: { assert(wordCount == 5); memberInfo[member].matrixStride = spirv[i + 4]; break; } case spv::DecorationLocation: { assert(wordCount == 5); memberInfo[member].location = spirv[i + 4]; break; } case spv::DecorationComponent: { assert(wordCount == 5); memberInfo[member].component = spirv[i + 4]; break; } case spv::DecorationRowMajor: { memberInfo[member].rowMajor = true; break; } case spv::DecorationColMajor: { memberInfo[member].rowMajor = false; break; } case spv::DecorationBuiltIn: { assert(wordCount == 5); memberInfo[member].builtin = true; // Store the clip and cull distance members to extract the sizes of the // arrays after the type info has been read. std::uint32_t builtin = spirv[i + 4]; if (builtin == spv::BuiltInClipDistance) data.clipDistanceMember = std::make_pair(id, member); else if (builtin == spv::BuiltInCullDistance) data.cullDistanceMember = std::make_pair(id, member); break; } } break; } // Extract integer contsnts. case spv::OpConstant: { assert(wordCount > 3); std::uint32_t typeId = spirv[i + 1]; std::uint32_t id = spirv[i + 2]; auto foundType = data.types.find(typeId); assert(foundType != data.types.end()); switch (foundType->second) { case Type::Int: case Type::UInt: data.intConstants[id] = spirv[i + 3]; break; default: break; } break; } // Extract type declarations. case spv::OpTypeBool: assert(wordCount == 2); data.types[spirv[i + 1]] = Type::Bool; break; case spv::OpTypeInt: { assert(wordCount == 4); assert(spirv[i + 2] == 32); std::uint32_t id = spirv[i + 1]; if (spirv[i + 3]) data.types[id] = Type::Int; else data.types[id] = Type::UInt; break; } case spv::OpTypeFloat: { assert(wordCount == 3); std::uint32_t id = spirv[i + 1]; std::uint32_t width = spirv[i + 2]; assert(width == 32 || width == 64); if (width == 64) data.types[id] = Type::Double; else data.types[id] = Type::Float; break; } case spv::OpTypeVector: readVector(data, spirv, i, wordCount); break; case spv::OpTypeMatrix: readMatrix(data, spirv, i, wordCount); break; case spv::OpTypeArray: { assert(wordCount == 4); std::uint32_t id = spirv[i + 1]; std::uint32_t type = spirv[i + 2]; std::uint32_t constantId = spirv[i + 3]; assert(data.types.find(type) != data.types.end() || data.arrayTypes.find(type) != data.arrayTypes.end() || data.structTypes.find(type) != data.structTypes.end()); auto foundIntConstant = data.intConstants.find(constantId); assert(foundIntConstant != data.intConstants.end()); SpirArrayInfo& arrayInfo = data.arrayTypes[id]; arrayInfo.type = type; arrayInfo.length = foundIntConstant->second; break; } case spv::OpTypeRuntimeArray: { assert(wordCount == 3); std::uint32_t id = spirv[i + 1]; std::uint32_t type = spirv[i + 2]; assert(data.types.find(type) != data.types.end() || data.arrayTypes.find(type) != data.arrayTypes.end() || data.structTypes.find(type) != data.structTypes.end()); SpirArrayInfo& arrayInfo = data.arrayTypes[id]; arrayInfo.type = type; arrayInfo.length = unknownLength; break; } case spv::OpTypeStruct: { assert(wordCount >= 2); std::uint32_t id = spirv[i + 1]; std::vector<std::uint32_t>& members = data.structTypes[id]; members.resize(wordCount - 2); for (std::size_t j = 0; j < members.size(); ++j) { std::uint32_t typeId = spirv[i + 2 + j]; assert(data.types.find(typeId) != data.types.end() || data.arrayTypes.find(typeId) != data.arrayTypes.end() || data.structTypes.find(typeId) != data.structTypes.end()); members[j] = typeId; } break; } case spv::OpTypeImage: readImage(data, spirv, i, wordCount); break; case spv::OpTypeSampledImage: { assert(wordCount >= 3); std::uint32_t id = spirv[i + 1]; std::uint32_t typeId = spirv[i + 2]; auto foundType = data.types.find(typeId); assert(foundType != data.types.end()); data.types[id] = foundType->second; break; } case spv::OpTypePointer: { assert(wordCount == 4); std::uint32_t id = spirv[i + 1]; std::uint32_t type = spirv[i + 3]; switch (spirv[i + 2]) { case spv::StorageClassInput: case spv::StorageClassOutput: case spv::StorageClassUniform: case spv::StorageClassImage: case spv::StorageClassUniformConstant: case spv::StorageClassPushConstant: if (data.types.find(type) != data.types.end() || data.arrayTypes.find(type) != data.arrayTypes.end() || data.structTypes.find(type) != data.structTypes.end()) { data.pointers[id] = type; } break; default: break; } break; } // Extract the uniform, input, output, and image variables. case spv::OpVariable: { assert(wordCount >= 4); std::uint32_t pointerType = spirv[i + 1]; std::uint32_t id = spirv[i + 2]; switch (spirv[i + 3]) { case spv::StorageClassInput: { auto foundPointer = data.pointers.find(pointerType); assert(foundPointer != data.pointers.end()); data.inputVars[id] = foundPointer->second; break; } case spv::StorageClassOutput: { auto foundPointer = data.pointers.find(pointerType); assert(foundPointer != data.pointers.end()); data.outputVars[id] = foundPointer->second; break; } case spv::StorageClassUniform: { auto foundPointer = data.pointers.find(pointerType); assert(foundPointer != data.pointers.end()); data.uniformVars[id] = foundPointer->second; break; } case spv::StorageClassImage: { auto foundPointer = data.pointers.find(pointerType); assert(foundPointer != data.pointers.end()); data.imageVars[id] = foundPointer->second; break; } case spv::StorageClassUniformConstant: { auto foundPointer = data.pointers.find(pointerType); assert(foundPointer != data.pointers.end()); std::vector<ArrayInfo> arrayElements; std::uint32_t structIndex; Type type = getType(arrayElements, structIndex, *this, data, foundPointer->second); if (isImage(type) || isSampledImage(type) || isSubpassInput(type)) data.imageVars[id] = foundPointer->second; break; } case spv::StorageClassPushConstant: { auto foundPointer = data.pointers.find(pointerType); assert(foundPointer != data.pointers.end()); assert(data.pushConstantPointer.first == unknown); data.pushConstantPointer = std::make_pair(id, foundPointer->second); break; } default: break; } break; } // Extract compute local size. case spv::OpExecutionMode: assert(wordCount >= 3); if (spirv[i + 2] == spv::ExecutionModeLocalSize) { assert(wordCount == 6); computeLocalSize[0] = spirv[i + 3]; computeLocalSize[1] = spirv[i + 4]; computeLocalSize[2] = spirv[i + 5]; } break; // Don't care once we reach the function section. case spv::OpFunction: done = true; firstFunction = i; break; default: break; } i += wordCount; } // Construct our own metadata structures based on what was extracted from SPIR-V. addUniforms(*this, data); if (!addInputs(output, *this, data)) return false; if (!addOutputs(output, *this, data)) return false; addPushConstants(*this, data); // Get the clip and cull distance counts. Check if they are actually referenced, otherwise it // will always have size 1 by default. std::vector<std::pair<std::uint32_t, std::uint32_t>> checkMembers = {data.clipDistanceMember, data.cullDistanceMember}; std::vector<bool> membersReferenced(checkMembers.size(), false); areOutputMembersReferenced(data, spirv, firstFunction, checkMembers, membersReferenced); if (membersReferenced[0]) clipDistanceCount = getMemberArraySize(data, data.clipDistanceMember); if (membersReferenced[1]) cullDistanceCount = getMemberArraySize(data, data.cullDistanceMember); // Sanity checks: const char* builtinPrefix = "gl_"; std::size_t builtinPrefixLen = std::strlen(builtinPrefix); std::unordered_set<std::string> encounteredNames; for (const Struct& thisStruct : structs) { if (thisStruct.name.compare(0, builtinPrefixLen, builtinPrefix) == 0) continue; if (!encounteredNames.insert(thisStruct.name).second) { output.addMessage(Output::Level::Error, fileName, line, column, false, "linker error: multiple sructs of name " + thisStruct.name + " declared; this " "could be due to using the same struct in different contexts, such a uniform " "block and uniform buffer"); return false; } } encounteredNames.clear(); for (const Uniform& uniform : uniforms) { if (!encounteredNames.insert(uniform.name).second) { output.addMessage(Output::Level::Error, fileName, line, column, false, "linker error: multiple uniforms of name " + uniform.name + " declared"); return false; } } encounteredNames.clear(); for (const InputOutput& stageInput : inputs) { if (stageInput.type == Type::Struct) continue; if (!encounteredNames.insert(stageInput.name).second) { output.addMessage(Output::Level::Error, fileName, line, column, false, "linker error: multiple inputs of name " + stageInput.name + "in stage " + stageNames[static_cast<unsigned int>(stage)]); return false; } } encounteredNames.clear(); for (const InputOutput& stageOutput : outputs) { if (stageOutput.type == Type::Struct) continue; if (!encounteredNames.insert(stageOutput.name).second) { output.addMessage(Output::Level::Error, fileName, line, column, false, "linker error: multiple outputs of name " + stageOutput.name + "in stage " + stageNames[static_cast<unsigned int>(stage)]); return false; } } return true; } bool SpirVProcessor::uniformsCompatible(Output& output, const SpirVProcessor& other) const { bool success = true; // Uniforms for (const Uniform& uniform : uniforms) { for (const Uniform& otherUniform : other.uniforms) { if (uniform.name != otherUniform.name) continue; if (uniform.uniformType != otherUniform.uniformType || uniform.type != otherUniform.type || uniform.arrayElements != otherUniform.arrayElements || uniform.descriptorSet != otherUniform.descriptorSet || uniform.binding != otherUniform.binding || (uniform.type == Type::Struct && structs[uniform.structIndex].name != other.structs[otherUniform.structIndex].name)) { output.addMessage(Output::Level::Error, fileName, line, column, false, "linker error: uniform " + uniform.name + " has different declarations between stages"); success = false; } break; } } // Structs for (const Struct& thisStruct : structs) { for (const Struct& otherStruct : other.structs) { if (thisStruct.name != otherStruct.name) continue; bool compatible = true; if (thisStruct.size != otherStruct.size || thisStruct.members.size() != otherStruct.members.size()) { compatible = false; } if (compatible) { for (std::size_t i = 0; i < thisStruct.members.size(); ++i) { const StructMember& thisMember = thisStruct.members[i]; const StructMember& otherMember = otherStruct.members[i]; if (thisMember.name != otherMember.name || thisMember.offset != otherMember.offset || thisMember.size != otherMember.size || thisMember.type != otherMember.type || thisMember.arrayElements != otherMember.arrayElements || (thisMember.type == Type::Struct && structs[thisMember.structIndex].name != other.structs[otherMember.structIndex].name)) { compatible = false; break; } } } if (!compatible) { output.addMessage(Output::Level::Error, fileName, line, column, false, "linker error: struct " + thisStruct.name + " has different declarations between stages"); success = false; } break; } } return success; } bool SpirVProcessor::assignInputs(Output& output) { return assignInputsOutputs(output, *this, inputs, inputIsArray(stage)); } bool SpirVProcessor::assignOutputs(Output& output) { return assignInputsOutputs(output, *this, outputs, outputIsArray(stage)); } bool SpirVProcessor::linkInputs(Output& output, const SpirVProcessor& prevStage) { bool success = true; bool inputArrays = inputIsArray(stage); bool outputArrays = outputIsArray(prevStage.stage); for (InputOutput& input : inputs) { if (input.type == Type::Struct) { Struct& inputStruct = structs[input.structIndex]; assert(inputStruct.members.size() == input.memberLocations.size()); for (std::size_t i = 0; i < inputStruct.members.size(); ++i) { if (input.memberLocations[i].first != unknown) continue; std::uint32_t otherOutIndex, otherMemberIndex; if (!findLinkedMember(output, otherOutIndex, otherMemberIndex, prevStage, inputStruct.members[i].name)) { success = false; continue; } const Struct& outputStruct = prevStage.structs[prevStage.outputs[otherOutIndex].structIndex]; if (inputStruct.members[i].type != outputStruct.members[otherMemberIndex].type || input.patch != prevStage.outputs[otherOutIndex].patch || !inputOutputArraysEqual( makeArrayLengths(outputStruct.members[otherMemberIndex].arrayElements), false, makeArrayLengths(inputStruct.members[i].arrayElements), false)) { output.addMessage(Output::Level::Error, fileName, line, column, false, "linker error: type mismatch when linking input member " + inputStruct.name + "." + inputStruct.members[i].name + " in stage " + stageNames[static_cast<unsigned int>(stage)]); success = false; continue; } input.memberLocations[i] = prevStage.outputs[otherOutIndex].memberLocations[otherMemberIndex]; } } else { if (input.location != unknown) continue; bool found = false; for (const InputOutput& out : prevStage.outputs) { if (input.name != out.name) continue; found = true; if (input.type != out.type || input.patch != out.patch || !inputOutputArraysEqual(out.arrayElements, outputArrays && !out.patch, input.arrayElements, inputArrays && !input.patch)) { output.addMessage(Output::Level::Error, fileName, line, column, false, "linker error: type mismatch when linking input " + input.name + " in stage " + stageNames[static_cast<unsigned int>(stage)]); success = false; break; } input.location = out.location; input.component = out.component; break; } if (!found) { output.addMessage(Output::Level::Error, fileName, line, column, false, "linker error: cannot find output with name " + input.name + " in stage " + stageNames[static_cast<unsigned int>(prevStage.stage)]); success = false; } } } return success; } std::vector<std::uint32_t> SpirVProcessor::process(Strip strip, bool dummyBindings) const { std::unordered_set<std::uint32_t> keepNames; if (strip == Strip::AllButReflection) { for (std::uint32_t id : structIds) keepNames.insert(id); for (std::uint32_t id : uniformIds) keepNames.insert(id); for (std::uint32_t id : inputIds) keepNames.insert(id); for (std::uint32_t id : outputIds) keepNames.insert(id); } std::vector<std::uint32_t> result; result.insert(result.end(), spirv->begin(), spirv->begin() + firstInstruction); std::unordered_map<std::uint32_t, std::uint32_t> locations; std::unordered_map<std::uint32_t, std::vector<std::uint32_t>> memberLocations; unsigned int wordCount; bool endOfAnnotations = false; for (std::size_t i = firstInstruction; i < spirv->size(); i += wordCount) { spv::Op op = getOp((*spirv)[i]); wordCount = getWordCount((*spirv)[i]); assert(wordCount > 0 && wordCount + i <= spirv->size()); if (endOfAnnotations) { result.insert(result.end(), spirv->begin() + i, spirv->begin() + i + wordCount); continue; } switch (op) { // Strip debug info. case spv::OpSource: case spv::OpSourceContinued: case spv::OpSourceExtension: case spv::OpString: case spv::OpLine: if (strip == Strip::None) result.insert(result.end(), spirv->begin() + i, spirv->begin() + i + wordCount); break; // Strip names. case spv::OpName: case spv::OpMemberName: { assert(wordCount >= 3); std::uint32_t id = (*spirv)[i + 1]; if (strip == Strip::None || (strip == Strip::AllButReflection && keepNames.find(id) != keepNames.end())) { result.insert(result.end(), spirv->begin() + i, spirv->begin() + i + wordCount); } break; } // Keep track of existing input/output locations. case spv::OpDecorate: { assert(wordCount >= 3); std::uint32_t id = (*spirv)[i + 1]; switch ((*spirv)[i + 2]) { case spv::DecorationLocation: assert(wordCount == 4); locations[id] = (*spirv)[i + 3]; break; } result.insert(result.end(), spirv->begin() + i, spirv->begin() + i + wordCount); break; } case spv::OpMemberDecorate: { assert(wordCount >= 4); std::uint32_t id = (*spirv)[i + 1]; std::uint32_t member = (*spirv)[i + 2]; switch ((*spirv)[i + 3]) { case spv::DecorationLocation: { assert(wordCount == 5); std::vector<std::uint32_t>& memberLocation = memberLocations[id]; if (memberLocation.size() <= member) memberLocation.resize(member + 1); memberLocation[member] = (*spirv)[i + 4]; break; } } result.insert(result.end(), spirv->begin() + i, spirv->begin() + i + wordCount); break; } // Capture other instructions before the end of annotations. case spv::OpCapability: case spv::OpExtension: case spv::OpExtInstImport: case spv::OpMemoryModel: case spv::OpEntryPoint: case spv::OpExecutionMode: case spv::OpGroupDecorate: case spv::OpGroupMemberDecorate: case spv::OpDecorationGroup: result.insert(result.end(), spirv->begin() + i, spirv->begin() + i + wordCount); break; // Finish with the other annotations. Add our own and continue with the rest of // SPIR-V. default: // Add input locations. for (std::size_t j = 0; j < inputs.size(); ++j) { if (!inputs[j].autoAssigned) continue; if (inputs[j].type == Type::Struct) { std::uint32_t typeId = structIds[inputs[j].structIndex]; auto foundMember = memberLocations.find(typeId); for (std::uint32_t k = 0; k < inputs[j].memberLocations.size(); ++k) { if (foundMember == memberLocations.end() || k >= foundMember->second.size() || foundMember->second[k] == unknown) { addMemberLocation(result, typeId, k, inputs[j].memberLocations[k].first); addMemberComponent(result, typeId, k, inputs[j].memberLocations[k].second); } } } else { if (locations.find(inputIds[j]) == locations.end()) { addLocation(result, inputIds[j], inputs[j].location); addComponent(result, inputIds[j], inputs[j].component); } } } // Add output locations. for (std::size_t j = 0; j < outputs.size(); ++j) { if (!outputs[j].autoAssigned) continue; if (outputs[j].type == Type::Struct) { std::uint32_t typeId = structIds[outputs[j].structIndex]; auto foundMember = memberLocations.find(typeId); for (std::uint32_t k = 0; k < outputs[j].memberLocations.size(); ++k) { if (foundMember == memberLocations.end() || k >= foundMember->second.size() || foundMember->second[k] == unknown) { addMemberLocation(result, typeId, k, outputs[j].memberLocations[k].first); addMemberComponent(result, typeId, k, outputs[j].memberLocations[k].second); } } } else { if (locations.find(outputIds[j]) == locations.end()) { addLocation(result, outputIds[j], outputs[j].location); addComponent(result, outputIds[j], outputs[j].component); } } } // Add dummy bindings. if (dummyBindings) { for (std::size_t j = 0; j < uniforms.size(); ++j) { if (uniforms[j].structIndex != unknown && uniforms[j].structIndex == pushConstantStruct) { continue; } if (uniforms[j].descriptorSet == unknown) addDummyDescriptorSet(result, uniformIds[j]); if (uniforms[j].binding == unknown) addDummyBinding(result, uniformIds[j]); } } endOfAnnotations = true; result.insert(result.end(), spirv->begin() + i, spirv->begin() + i + wordCount); break; } } return result; } } // namespace msl
26.780832
98
0.651758
[ "geometry", "vector" ]
2d314239c23b81fe1a21155af797676bf620b7a6
48,194
cpp
C++
deps/opensubdiv-3.4.0/opensubdiv/vtr/refinement.cpp
julescmay/LuxCore
3a6233f37afaf064300f52854715c0ab9ca2103e
[ "Apache-2.0" ]
1,463
2015-01-02T08:23:51.000Z
2022-03-29T13:44:29.000Z
deps/opensubdiv-3.4.0/opensubdiv/vtr/refinement.cpp
julescmay/LuxCore
3a6233f37afaf064300f52854715c0ab9ca2103e
[ "Apache-2.0" ]
531
2017-12-03T17:21:06.000Z
2022-03-20T19:22:11.000Z
deps/opensubdiv-3.4.0/opensubdiv/vtr/refinement.cpp
julescmay/LuxCore
3a6233f37afaf064300f52854715c0ab9ca2103e
[ "Apache-2.0" ]
429
2015-01-09T00:54:52.000Z
2022-03-31T20:32:55.000Z
// // Copyright 2014 DreamWorks Animation LLC. // // Licensed under the Apache License, Version 2.0 (the "Apache License") // with the following modification; you may not use this file except in // compliance with the Apache License and the following modification to it: // Section 6. Trademarks. is deleted and replaced with: // // 6. Trademarks. This License does not grant permission to use the trade // names, trademarks, service marks, or product names of the Licensor // and its affiliates, except as required to comply with Section 4(c) of // the License and to reproduce the content of the NOTICE file. // // You may obtain a copy of the Apache License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the Apache License with the above modification is // distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the Apache License for the specific // language governing permissions and limitations under the Apache License. // #include "../sdc/crease.h" #include "../sdc/catmarkScheme.h" #include "../sdc/bilinearScheme.h" #include "../vtr/types.h" #include "../vtr/level.h" #include "../vtr/refinement.h" #include "../vtr/fvarLevel.h" #include "../vtr/fvarRefinement.h" #include "../vtr/stackBuffer.h" #include <cassert> #include <cstdio> #include <utility> namespace OpenSubdiv { namespace OPENSUBDIV_VERSION { namespace Vtr { namespace internal { // // Simple constructor, destructor and basic initializers: // Refinement::Refinement(Level const & parentArg, Level & childArg, Sdc::Options const& options) : _parent(&parentArg), _child(&childArg), _options(options), _regFaceSize(-1), _uniform(false), _faceVertsFirst(false), _childFaceFromFaceCount(0), _childEdgeFromFaceCount(0), _childEdgeFromEdgeCount(0), _childVertFromFaceCount(0), _childVertFromEdgeCount(0), _childVertFromVertCount(0), _firstChildFaceFromFace(0), _firstChildEdgeFromFace(0), _firstChildEdgeFromEdge(0), _firstChildVertFromFace(0), _firstChildVertFromEdge(0), _firstChildVertFromVert(0) { assert((childArg.getDepth() == 0) && (childArg.getNumVertices() == 0)); childArg._depth = 1 + parentArg.getDepth(); } Refinement::~Refinement() { for (int i = 0; i < (int)_fvarChannels.size(); ++i) { delete _fvarChannels[i]; } } void Refinement::initializeChildComponentCounts() { // // Assign the child's component counts/inventory based on the child components identified: // _child->_faceCount = _childFaceFromFaceCount; _child->_edgeCount = _childEdgeFromFaceCount + _childEdgeFromEdgeCount; _child->_vertCount = _childVertFromFaceCount + _childVertFromEdgeCount + _childVertFromVertCount; } void Refinement::initializeSparseSelectionTags() { _parentFaceTag.resize(_parent->getNumFaces()); _parentEdgeTag.resize(_parent->getNumEdges()); _parentVertexTag.resize(_parent->getNumVertices()); } // // The main refinement method -- provides a high-level overview of refinement: // // The refinement process is as follows: // - determine a mapping from parent components to their potential child components // - for sparse refinement this mapping will be partial // - determine the reverse mapping from chosen child components back to their parents // - previously this was optional -- not strictly necessary and comes at added cost // - does simplify iteration of child components when refinement is sparse // - propagate/initialize component Tags from parents to their children // - knowing these Tags for a child component simplifies dealing with it later // - subdivide the topology, i.e. populate all topology relations for the child Level // - any subset of the 6 relations in a Level can be created // - using the minimum required in the last Level is very advantageous // - subdivide the sharpness values in the child Level // - subdivide face-varying channels in the child Level // void Refinement::refine(Options refineOptions) { // This will become redundant when/if assigned on construction: assert(_parent && _child); _uniform = !refineOptions._sparse; _faceVertsFirst = refineOptions._faceVertsFirst; // We may soon have an option here to suppress refinement of FVar channels... bool refineOptions_ignoreFVarChannels = false; bool optionallyRefineFVar = (_parent->getNumFVarChannels() > 0) && !refineOptions_ignoreFVarChannels; // // Initialize the parent-to-child and reverse child-to-parent mappings and propagate // component tags to the new child components: // populateParentToChildMapping(); initializeChildComponentCounts(); populateChildToParentMapping(); propagateComponentTags(); // // Subdivide the topology -- populating only those of the 6 relations specified // (though we do require the vertex-face relation for refining FVar channels): // Relations relationsToPopulate; if (refineOptions._minimalTopology) { relationsToPopulate.setAll(false); relationsToPopulate._faceVertices = true; } else { relationsToPopulate.setAll(true); } if (optionallyRefineFVar) { relationsToPopulate._vertexFaces = true; } subdivideTopology(relationsToPopulate); // // Subdivide the sharpness values and face-varying channels: // - note there is some dependency of the vertex tag/Rule for semi-sharp vertices // subdivideSharpnessValues(); if (optionallyRefineFVar) { subdivideFVarChannels(); } // Various debugging support: // //printf("Vertex refinement to level %d completed...\n", _child->getDepth()); //_child->print(); //printf(" validating refinement to level %d...\n", _child->getDepth()); //_child->validateTopology(); //assert(_child->validateTopology()); } // // Methods to construct the parent-to-child mapping // void Refinement::populateParentToChildMapping() { allocateParentChildIndices(); // // If sparse refinement, mark indices of any components in addition to those selected // so that we have the full neighborhood for selected components: // if (!_uniform) { // Make sure the selection was non-empty -- currently unsupported... if (_parentVertexTag.size() == 0) { assert("Unsupported empty sparse refinement detected in Refinement" == 0); } markSparseChildComponentIndices(); } populateParentChildIndices(); } namespace { inline bool isSparseIndexMarked(Index index) { return index != 0; } inline int sequenceSparseIndexVector(IndexVector& indexVector, int baseValue = 0) { int validCount = 0; for (int i = 0; i < (int) indexVector.size(); ++i) { indexVector[i] = isSparseIndexMarked(indexVector[i]) ? (baseValue + validCount++) : INDEX_INVALID; } return validCount; } inline int sequenceFullIndexVector(IndexVector& indexVector, int baseValue = 0) { int indexCount = (int) indexVector.size(); for (int i = 0; i < indexCount; ++i) { indexVector[i] = baseValue++; } return indexCount; } } void Refinement::populateParentChildIndices() { // // Two vertex orderings are currently supported -- ordering vertices refined // from vertices first, or those refined from faces first. It's possible this // may be extended to more possibilities. Once the ordering is defined here, // other than analogous initialization in FVarRefinement, the treatment of // vertices in blocks based on origin should make the rest of the code // invariant to ordering changes. // // These two blocks now differ only in the utility function that assigns the // sequential values to the index vectors -- so parameterization/simplification // is now possible... // if (_uniform) { // child faces: _firstChildFaceFromFace = 0; _childFaceFromFaceCount = sequenceFullIndexVector(_faceChildFaceIndices, _firstChildFaceFromFace); // child edges: _firstChildEdgeFromFace = 0; _childEdgeFromFaceCount = sequenceFullIndexVector(_faceChildEdgeIndices, _firstChildEdgeFromFace); _firstChildEdgeFromEdge = _childEdgeFromFaceCount; _childEdgeFromEdgeCount = sequenceFullIndexVector(_edgeChildEdgeIndices, _firstChildEdgeFromEdge); // child vertices: if (_faceVertsFirst) { _firstChildVertFromFace = 0; _childVertFromFaceCount = sequenceFullIndexVector(_faceChildVertIndex, _firstChildVertFromFace); _firstChildVertFromEdge = _firstChildVertFromFace + _childVertFromFaceCount; _childVertFromEdgeCount = sequenceFullIndexVector(_edgeChildVertIndex, _firstChildVertFromEdge); _firstChildVertFromVert = _firstChildVertFromEdge + _childVertFromEdgeCount; _childVertFromVertCount = sequenceFullIndexVector(_vertChildVertIndex, _firstChildVertFromVert); } else { _firstChildVertFromVert = 0; _childVertFromVertCount = sequenceFullIndexVector(_vertChildVertIndex, _firstChildVertFromVert); _firstChildVertFromFace = _firstChildVertFromVert + _childVertFromVertCount; _childVertFromFaceCount = sequenceFullIndexVector(_faceChildVertIndex, _firstChildVertFromFace); _firstChildVertFromEdge = _firstChildVertFromFace + _childVertFromFaceCount; _childVertFromEdgeCount = sequenceFullIndexVector(_edgeChildVertIndex, _firstChildVertFromEdge); } } else { // child faces: _firstChildFaceFromFace = 0; _childFaceFromFaceCount = sequenceSparseIndexVector(_faceChildFaceIndices, _firstChildFaceFromFace); // child edges: _firstChildEdgeFromFace = 0; _childEdgeFromFaceCount = sequenceSparseIndexVector(_faceChildEdgeIndices, _firstChildEdgeFromFace); _firstChildEdgeFromEdge = _childEdgeFromFaceCount; _childEdgeFromEdgeCount = sequenceSparseIndexVector(_edgeChildEdgeIndices, _firstChildEdgeFromEdge); // child vertices: if (_faceVertsFirst) { _firstChildVertFromFace = 0; _childVertFromFaceCount = sequenceSparseIndexVector(_faceChildVertIndex, _firstChildVertFromFace); _firstChildVertFromEdge = _firstChildVertFromFace + _childVertFromFaceCount; _childVertFromEdgeCount = sequenceSparseIndexVector(_edgeChildVertIndex, _firstChildVertFromEdge); _firstChildVertFromVert = _firstChildVertFromEdge + _childVertFromEdgeCount; _childVertFromVertCount = sequenceSparseIndexVector(_vertChildVertIndex, _firstChildVertFromVert); } else { _firstChildVertFromVert = 0; _childVertFromVertCount = sequenceSparseIndexVector(_vertChildVertIndex, _firstChildVertFromVert); _firstChildVertFromFace = _firstChildVertFromVert + _childVertFromVertCount; _childVertFromFaceCount = sequenceSparseIndexVector(_faceChildVertIndex, _firstChildVertFromFace); _firstChildVertFromEdge = _firstChildVertFromFace + _childVertFromFaceCount; _childVertFromEdgeCount = sequenceSparseIndexVector(_edgeChildVertIndex, _firstChildVertFromEdge); } } } void Refinement::printParentToChildMapping() const { printf("Parent-to-child component mapping:\n"); for (Index pFace = 0; pFace < _parent->getNumFaces(); ++pFace) { printf(" Face %d:\n", pFace); printf(" Child vert: %d\n", _faceChildVertIndex[pFace]); printf(" Child faces: "); ConstIndexArray childFaces = getFaceChildFaces(pFace); for (int i = 0; i < childFaces.size(); ++i) { printf(" %d", childFaces[i]); } printf("\n"); printf(" Child edges: "); ConstIndexArray childEdges = getFaceChildEdges(pFace); for (int i = 0; i < childEdges.size(); ++i) { printf(" %d", childEdges[i]); } printf("\n"); } for (Index pEdge = 0; pEdge < _parent->getNumEdges(); ++pEdge) { printf(" Edge %d:\n", pEdge); printf(" Child vert: %d\n", _edgeChildVertIndex[pEdge]); ConstIndexArray childEdges = getEdgeChildEdges(pEdge); printf(" Child edges: %d %d\n", childEdges[0], childEdges[1]); } for (Index pVert = 0; pVert < _parent->getNumVertices(); ++pVert) { printf(" Vert %d:\n", pVert); printf(" Child vert: %d\n", _vertChildVertIndex[pVert]); } } // // Methods to construct the child-to-parent mapping: // void Refinement::populateChildToParentMapping() { ChildTag initialChildTags[2][4]; for (int i = 0; i < 2; ++i) { for (int j = 0; j < 4; ++j) { ChildTag & tag = initialChildTags[i][j]; tag._incomplete = (unsigned char)i; tag._parentType = 0; tag._indexInParent = (unsigned char)j; } } populateFaceParentVectors(initialChildTags); populateEdgeParentVectors(initialChildTags); populateVertexParentVectors(initialChildTags); } void Refinement::populateFaceParentVectors(ChildTag const initialChildTags[2][4]) { _childFaceTag.resize(_child->getNumFaces()); _childFaceParentIndex.resize(_child->getNumFaces()); populateFaceParentFromParentFaces(initialChildTags); } void Refinement::populateFaceParentFromParentFaces(ChildTag const initialChildTags[2][4]) { if (_uniform) { Index cFace = getFirstChildFaceFromFaces(); for (Index pFace = 0; pFace < _parent->getNumFaces(); ++pFace) { ConstIndexArray cFaces = getFaceChildFaces(pFace); if (cFaces.size() == 4) { _childFaceTag[cFace + 0] = initialChildTags[0][0]; _childFaceTag[cFace + 1] = initialChildTags[0][1]; _childFaceTag[cFace + 2] = initialChildTags[0][2]; _childFaceTag[cFace + 3] = initialChildTags[0][3]; _childFaceParentIndex[cFace + 0] = pFace; _childFaceParentIndex[cFace + 1] = pFace; _childFaceParentIndex[cFace + 2] = pFace; _childFaceParentIndex[cFace + 3] = pFace; cFace += 4; } else { bool childTooLarge = (cFaces.size() > 4); for (int i = 0; i < cFaces.size(); ++i, ++cFace) { _childFaceTag[cFace] = initialChildTags[0][childTooLarge ? 0 : i]; _childFaceParentIndex[cFace] = pFace; } } } } else { // Child faces of faces: for (Index pFace = 0; pFace < _parent->getNumFaces(); ++pFace) { bool incomplete = !_parentFaceTag[pFace]._selected; IndexArray cFaces = getFaceChildFaces(pFace); if (!incomplete && (cFaces.size() == 4)) { _childFaceTag[cFaces[0]] = initialChildTags[0][0]; _childFaceTag[cFaces[1]] = initialChildTags[0][1]; _childFaceTag[cFaces[2]] = initialChildTags[0][2]; _childFaceTag[cFaces[3]] = initialChildTags[0][3]; _childFaceParentIndex[cFaces[0]] = pFace; _childFaceParentIndex[cFaces[1]] = pFace; _childFaceParentIndex[cFaces[2]] = pFace; _childFaceParentIndex[cFaces[3]] = pFace; } else { bool childTooLarge = (cFaces.size() > 4); for (int i = 0; i < cFaces.size(); ++i) { if (IndexIsValid(cFaces[i])) { _childFaceTag[cFaces[i]] = initialChildTags[incomplete][childTooLarge ? 0 : i]; _childFaceParentIndex[cFaces[i]] = pFace; } } } } } } void Refinement::populateEdgeParentVectors(ChildTag const initialChildTags[2][4]) { _childEdgeTag.resize(_child->getNumEdges()); _childEdgeParentIndex.resize(_child->getNumEdges()); populateEdgeParentFromParentFaces(initialChildTags); populateEdgeParentFromParentEdges(initialChildTags); } void Refinement::populateEdgeParentFromParentFaces(ChildTag const initialChildTags[2][4]) { if (_uniform) { Index cEdge = getFirstChildEdgeFromFaces(); for (Index pFace = 0; pFace < _parent->getNumFaces(); ++pFace) { ConstIndexArray cEdges = getFaceChildEdges(pFace); if (cEdges.size() == 4) { _childEdgeTag[cEdge + 0] = initialChildTags[0][0]; _childEdgeTag[cEdge + 1] = initialChildTags[0][1]; _childEdgeTag[cEdge + 2] = initialChildTags[0][2]; _childEdgeTag[cEdge + 3] = initialChildTags[0][3]; _childEdgeParentIndex[cEdge + 0] = pFace; _childEdgeParentIndex[cEdge + 1] = pFace; _childEdgeParentIndex[cEdge + 2] = pFace; _childEdgeParentIndex[cEdge + 3] = pFace; cEdge += 4; } else { bool childTooLarge = (cEdges.size() > 4); for (int i = 0; i < cEdges.size(); ++i, ++cEdge) { _childEdgeTag[cEdge] = initialChildTags[0][childTooLarge ? 0 : i]; _childEdgeParentIndex[cEdge] = pFace; } } } } else { for (Index pFace = 0; pFace < _parent->getNumFaces(); ++pFace) { bool incomplete = !_parentFaceTag[pFace]._selected; IndexArray cEdges = getFaceChildEdges(pFace); if (!incomplete && (cEdges.size() == 4)) { _childEdgeTag[cEdges[0]] = initialChildTags[0][0]; _childEdgeTag[cEdges[1]] = initialChildTags[0][1]; _childEdgeTag[cEdges[2]] = initialChildTags[0][2]; _childEdgeTag[cEdges[3]] = initialChildTags[0][3]; _childEdgeParentIndex[cEdges[0]] = pFace; _childEdgeParentIndex[cEdges[1]] = pFace; _childEdgeParentIndex[cEdges[2]] = pFace; _childEdgeParentIndex[cEdges[3]] = pFace; } else { bool childTooLarge = (cEdges.size() > 4); for (int i = 0; i < cEdges.size(); ++i) { if (IndexIsValid(cEdges[i])) { _childEdgeTag[cEdges[i]] = initialChildTags[incomplete][childTooLarge ? 0 : i]; _childEdgeParentIndex[cEdges[i]] = pFace; } } } } } } void Refinement::populateEdgeParentFromParentEdges(ChildTag const initialChildTags[2][4]) { if (_uniform) { Index cEdge = getFirstChildEdgeFromEdges(); for (Index pEdge = 0; pEdge < _parent->getNumEdges(); ++pEdge, cEdge += 2) { _childEdgeTag[cEdge + 0] = initialChildTags[0][0]; _childEdgeTag[cEdge + 1] = initialChildTags[0][1]; _childEdgeParentIndex[cEdge + 0] = pEdge; _childEdgeParentIndex[cEdge + 1] = pEdge; } } else { for (Index pEdge = 0; pEdge < _parent->getNumEdges(); ++pEdge) { bool incomplete = !_parentEdgeTag[pEdge]._selected; IndexArray cEdges = getEdgeChildEdges(pEdge); if (!incomplete) { _childEdgeTag[cEdges[0]] = initialChildTags[0][0]; _childEdgeTag[cEdges[1]] = initialChildTags[0][1]; _childEdgeParentIndex[cEdges[0]] = pEdge; _childEdgeParentIndex[cEdges[1]] = pEdge; } else { for (int i = 0; i < 2; ++i) { if (IndexIsValid(cEdges[i])) { _childEdgeTag[cEdges[i]] = initialChildTags[incomplete][i]; _childEdgeParentIndex[cEdges[i]] = pEdge; } } } } } } void Refinement::populateVertexParentVectors(ChildTag const initialChildTags[2][4]) { if (_uniform) { _childVertexTag.resize(_child->getNumVertices(), initialChildTags[0][0]); } else { _childVertexTag.resize(_child->getNumVertices(), initialChildTags[1][0]); } _childVertexParentIndex.resize(_child->getNumVertices()); populateVertexParentFromParentFaces(initialChildTags); populateVertexParentFromParentEdges(initialChildTags); populateVertexParentFromParentVertices(initialChildTags); } void Refinement::populateVertexParentFromParentFaces(ChildTag const initialChildTags[2][4]) { if (getNumChildVerticesFromFaces() == 0) return; if (_uniform) { Index cVert = getFirstChildVertexFromFaces(); for (Index pFace = 0; pFace < _parent->getNumFaces(); ++pFace, ++cVert) { // Child tag was initialized as the complete and only child when allocated _childVertexParentIndex[cVert] = pFace; } } else { ChildTag const & completeChildTag = initialChildTags[0][0]; for (Index pFace = 0; pFace < _parent->getNumFaces(); ++pFace) { Index cVert = _faceChildVertIndex[pFace]; if (IndexIsValid(cVert)) { // Child tag was initialized as incomplete -- reset if complete: if (_parentFaceTag[pFace]._selected) { _childVertexTag[cVert] = completeChildTag; } _childVertexParentIndex[cVert] = pFace; } } } } void Refinement::populateVertexParentFromParentEdges(ChildTag const initialChildTags[2][4]) { if (_uniform) { Index cVert = getFirstChildVertexFromEdges(); for (Index pEdge = 0; pEdge < _parent->getNumEdges(); ++pEdge, ++cVert) { // Child tag was initialized as the complete and only child when allocated _childVertexParentIndex[cVert] = pEdge; } } else { ChildTag const & completeChildTag = initialChildTags[0][0]; for (Index pEdge = 0; pEdge < _parent->getNumEdges(); ++pEdge) { Index cVert = _edgeChildVertIndex[pEdge]; if (IndexIsValid(cVert)) { // Child tag was initialized as incomplete -- reset if complete: if (_parentEdgeTag[pEdge]._selected) { _childVertexTag[cVert] = completeChildTag; } _childVertexParentIndex[cVert] = pEdge; } } } } void Refinement::populateVertexParentFromParentVertices(ChildTag const initialChildTags[2][4]) { if (_uniform) { Index cVert = getFirstChildVertexFromVertices(); for (Index pVert = 0; pVert < _parent->getNumVertices(); ++pVert, ++cVert) { // Child tag was initialized as the complete and only child when allocated _childVertexParentIndex[cVert] = pVert; } } else { ChildTag const & completeChildTag = initialChildTags[0][0]; for (Index pVert = 0; pVert < _parent->getNumVertices(); ++pVert) { Index cVert = _vertChildVertIndex[pVert]; if (IndexIsValid(cVert)) { // Child tag was initialized as incomplete but these should be complete: if (_parentVertexTag[pVert]._selected) { _childVertexTag[cVert] = completeChildTag; } _childVertexParentIndex[cVert] = pVert; } } } } // // Methods to propagate/initialize child component tags from their parent component: // void Refinement::propagateComponentTags() { populateFaceTagVectors(); populateEdgeTagVectors(); populateVertexTagVectors(); } void Refinement::populateFaceTagVectors() { _child->_faceTags.resize(_child->getNumFaces()); populateFaceTagsFromParentFaces(); } void Refinement::populateFaceTagsFromParentFaces() { // // Tags for faces originating from faces are inherited from the parent face: // Index cFace = getFirstChildFaceFromFaces(); Index cFaceEnd = cFace + getNumChildFacesFromFaces(); for ( ; cFace < cFaceEnd; ++cFace) { _child->_faceTags[cFace] = _parent->_faceTags[_childFaceParentIndex[cFace]]; } } void Refinement::populateEdgeTagVectors() { _child->_edgeTags.resize(_child->getNumEdges()); populateEdgeTagsFromParentFaces(); populateEdgeTagsFromParentEdges(); } void Refinement::populateEdgeTagsFromParentFaces() { // // Tags for edges originating from faces are all constant: // Level::ETag eTag; eTag.clear(); Index cEdge = getFirstChildEdgeFromFaces(); Index cEdgeEnd = cEdge + getNumChildEdgesFromFaces(); for ( ; cEdge < cEdgeEnd; ++cEdge) { _child->_edgeTags[cEdge] = eTag; } } void Refinement::populateEdgeTagsFromParentEdges() { // // Tags for edges originating from edges are inherited from the parent edge: // Index cEdge = getFirstChildEdgeFromEdges(); Index cEdgeEnd = cEdge + getNumChildEdgesFromEdges(); for ( ; cEdge < cEdgeEnd; ++cEdge) { _child->_edgeTags[cEdge] = _parent->_edgeTags[_childEdgeParentIndex[cEdge]]; } } void Refinement::populateVertexTagVectors() { _child->_vertTags.resize(_child->getNumVertices()); populateVertexTagsFromParentFaces(); populateVertexTagsFromParentEdges(); populateVertexTagsFromParentVertices(); if (!_uniform) { for (Index cVert = 0; cVert < _child->getNumVertices(); ++cVert) { if (_childVertexTag[cVert]._incomplete) { _child->_vertTags[cVert]._incomplete = true; } } } } void Refinement::populateVertexTagsFromParentFaces() { // // Similarly, tags for vertices originating from faces are all constant -- with the // unfortunate exception of refining level 0, where the faces may be N-sided and so // introduce new vertices that need to be tagged as extra-ordinary: // if (getNumChildVerticesFromFaces() == 0) return; Level::VTag vTag; vTag.clear(); vTag._rule = Sdc::Crease::RULE_SMOOTH; Index cVert = getFirstChildVertexFromFaces(); Index cVertEnd = cVert + getNumChildVerticesFromFaces(); if (_parent->_depth > 0) { for ( ; cVert < cVertEnd; ++cVert) { _child->_vertTags[cVert] = vTag; } } else { for ( ; cVert < cVertEnd; ++cVert) { _child->_vertTags[cVert] = vTag; if (_parent->getNumFaceVertices(_childVertexParentIndex[cVert]) != _regFaceSize) { _child->_vertTags[cVert]._xordinary = true; } } } } void Refinement::populateVertexTagsFromParentEdges() { // // Tags for vertices originating from edges are initialized according to the tags // of the parent edge: // Level::VTag vTag; vTag.clear(); for (Index pEdge = 0; pEdge < _parent->getNumEdges(); ++pEdge) { Index cVert = _edgeChildVertIndex[pEdge]; if (!IndexIsValid(cVert)) continue; // From the cleared local VTag, we just need to assign properties dependent // on the parent edge: Level::ETag const& pEdgeTag = _parent->_edgeTags[pEdge]; vTag._nonManifold = pEdgeTag._nonManifold; vTag._boundary = pEdgeTag._boundary; vTag._semiSharpEdges = pEdgeTag._semiSharp; vTag._infSharpEdges = pEdgeTag._infSharp; vTag._infSharpCrease = pEdgeTag._infSharp; vTag._infIrregular = pEdgeTag._infSharp && pEdgeTag._nonManifold; vTag._rule = (Level::VTag::VTagSize)((pEdgeTag._semiSharp || pEdgeTag._infSharp) ? Sdc::Crease::RULE_CREASE : Sdc::Crease::RULE_SMOOTH); _child->_vertTags[cVert] = vTag; } } void Refinement::populateVertexTagsFromParentVertices() { // // Tags for vertices originating from vertices are inherited from the parent vertex: // Index cVert = getFirstChildVertexFromVertices(); Index cVertEnd = cVert + getNumChildVerticesFromVertices(); for ( ; cVert < cVertEnd; ++cVert) { _child->_vertTags[cVert] = _parent->_vertTags[_childVertexParentIndex[cVert]]; _child->_vertTags[cVert]._incidIrregFace = 0; } } // // Methods to subdivide the topology: // // The main method to subdivide topology is fairly simple -- given a set of relations // to populate it simply tests and populates each relation separately. The method for // each relation is responsible for appropriate allocation and initialization of all // data involved, and these are virtual -- provided by a quad- or tri-split subclass. // void Refinement::subdivideTopology(Relations const& applyTo) { if (applyTo._faceVertices) { populateFaceVertexRelation(); } if (applyTo._faceEdges) { populateFaceEdgeRelation(); } if (applyTo._edgeVertices) { populateEdgeVertexRelation(); } if (applyTo._edgeFaces) { populateEdgeFaceRelation(); } if (applyTo._vertexFaces) { populateVertexFaceRelation(); } if (applyTo._vertexEdges) { populateVertexEdgeRelation(); } // // Additional members of the child Level not specific to any relation... // - note in the case of max-valence, the child's max-valence may be less // than the parent if that maximal parent vertex was not included in the sparse // refinement (possible when sparse refinement is more general). // - it may also be more if the base level was fairly trivial, i.e. less // than the regular valence, or contains non-manifold edges with many faces. // - NOTE that when/if we support N-gons for tri-splitting, that the valence // of edge-vertices introduced on the N-gon may be 7 rather than 6, while N may // be less than both. // // In general, we need a better way to deal with max-valence. The fact that // each topology relation is independent/optional complicates the issue of // where to keep track of it... // if (_splitType == Sdc::SPLIT_TO_QUADS) { _child->_maxValence = std::max(_parent->_maxValence, 4); _child->_maxValence = std::max(_child->_maxValence, 2 + _parent->_maxEdgeFaces); } else { _child->_maxValence = std::max(_parent->_maxValence, 6); _child->_maxValence = std::max(_child->_maxValence, 2 + _parent->_maxEdgeFaces * 2); } } // // Methods to subdivide sharpness values: // void Refinement::subdivideSharpnessValues() { // // Subdividing edge and vertex sharpness values are independent, but in order // to maintain proper classification/tagging of components as semi-sharp, both // must be computed and the neighborhood inspected to properly update the // status. // // It is possible to clear the semi-sharp status when propagating the tags and // to reset it (potentially multiple times) when updating the sharpness values. // The vertex subdivision Rule is also affected by this, which complicates the // process. So for now we apply a post-process to explicitly handle all // semi-sharp vertices. // // These methods will update sharpness tags local to the edges and vertices: subdivideEdgeSharpness(); subdivideVertexSharpness(); // This method uses local sharpness tags (set above) to update vertex tags that // reflect the neighborhood of the vertex (e.g. its rule): reclassifySemisharpVertices(); } void Refinement::subdivideEdgeSharpness() { Sdc::Crease creasing(_options); _child->_edgeSharpness.clear(); _child->_edgeSharpness.resize(_child->getNumEdges(), Sdc::Crease::SHARPNESS_SMOOTH); // // Edge sharpness is passed to child-edges using the parent edge and the // parent vertex for which the child corresponds. Child-edges are created // from both parent faces and parent edges, but those child-edges created // from a parent face should be within the face's interior and so smooth // (and so previously initialized). // // The presence/validity of each parent edges child vert indicates one or // more child edges. // // NOTE -- It is also useful at this time to classify the child vert of // this edge based on the creasing information here, particularly when a // non-trivial creasing method like Chaikin is used. This is not being // done now but is worth considering... // internal::StackBuffer<float,16> pVertEdgeSharpness; if (!creasing.IsUniform()) { pVertEdgeSharpness.Reserve(_parent->getMaxValence()); } Index cEdge = getFirstChildEdgeFromEdges(); Index cEdgeEnd = cEdge + getNumChildEdgesFromEdges(); for ( ; cEdge < cEdgeEnd; ++cEdge) { float& cSharpness = _child->_edgeSharpness[cEdge]; Level::ETag& cEdgeTag = _child->_edgeTags[cEdge]; if (cEdgeTag._infSharp) { cSharpness = Sdc::Crease::SHARPNESS_INFINITE; } else if (cEdgeTag._semiSharp) { Index pEdge = _childEdgeParentIndex[cEdge]; float pSharpness = _parent->_edgeSharpness[pEdge]; if (creasing.IsUniform()) { cSharpness = creasing.SubdivideUniformSharpness(pSharpness); } else { ConstIndexArray pEdgeVerts = _parent->getEdgeVertices(pEdge); Index pVert = pEdgeVerts[_childEdgeTag[cEdge]._indexInParent]; ConstIndexArray pVertEdges = _parent->getVertexEdges(pVert); for (int i = 0; i < pVertEdges.size(); ++i) { pVertEdgeSharpness[i] = _parent->_edgeSharpness[pVertEdges[i]]; } cSharpness = creasing.SubdivideEdgeSharpnessAtVertex(pSharpness, pVertEdges.size(), pVertEdgeSharpness); } if (! Sdc::Crease::IsSharp(cSharpness)) { cEdgeTag._semiSharp = false; } } } } void Refinement::subdivideVertexSharpness() { Sdc::Crease creasing(_options); _child->_vertSharpness.clear(); _child->_vertSharpness.resize(_child->getNumVertices(), Sdc::Crease::SHARPNESS_SMOOTH); // // All child-verts originating from faces or edges are initialized as smooth // above. Only those originating from vertices require "subdivided" values: // // Only deal with the subrange of vertices originating from vertices: Index cVertBegin = getFirstChildVertexFromVertices(); Index cVertEnd = cVertBegin + getNumChildVerticesFromVertices(); for (Index cVert = cVertBegin; cVert < cVertEnd; ++cVert) { float& cSharpness = _child->_vertSharpness[cVert]; Level::VTag& cVertTag = _child->_vertTags[cVert]; if (cVertTag._infSharp) { cSharpness = Sdc::Crease::SHARPNESS_INFINITE; } else if (cVertTag._semiSharp) { Index pVert = _childVertexParentIndex[cVert]; float pSharpness = _parent->_vertSharpness[pVert]; cSharpness = creasing.SubdivideVertexSharpness(pSharpness); if (! Sdc::Crease::IsSharp(cSharpness)) { cVertTag._semiSharp = false; } } } } void Refinement::reclassifySemisharpVertices() { typedef Level::VTag::VTagSize VTagSize; Sdc::Crease creasing(_options); // // Inspect all vertices derived from edges -- for those whose parent edges were semisharp, // reset the semisharp tag and the associated Rule according to the sharpness pair for the // subdivided edges (note this may be better handled when the edge sharpness is computed): // Index vertFromEdgeBegin = getFirstChildVertexFromEdges(); Index vertFromEdgeEnd = vertFromEdgeBegin + getNumChildVerticesFromEdges(); for (Index cVert = vertFromEdgeBegin; cVert < vertFromEdgeEnd; ++cVert) { Level::VTag& cVertTag = _child->_vertTags[cVert]; if (!cVertTag._semiSharpEdges) continue; Index pEdge = _childVertexParentIndex[cVert]; ConstIndexArray cEdges = getEdgeChildEdges(pEdge); if (_childVertexTag[cVert]._incomplete) { // One child edge likely missing -- assume Crease if remaining edge semi-sharp: cVertTag._semiSharpEdges = (IndexIsValid(cEdges[0]) && _child->_edgeTags[cEdges[0]]._semiSharp) || (IndexIsValid(cEdges[1]) && _child->_edgeTags[cEdges[1]]._semiSharp); cVertTag._rule = (VTagSize)(cVertTag._semiSharpEdges ? Sdc::Crease::RULE_CREASE : Sdc::Crease::RULE_SMOOTH); } else { int sharpEdgeCount = _child->_edgeTags[cEdges[0]]._semiSharp + _child->_edgeTags[cEdges[1]]._semiSharp; cVertTag._semiSharpEdges = (sharpEdgeCount > 0); cVertTag._rule = (VTagSize)(creasing.DetermineVertexVertexRule(0.0, sharpEdgeCount)); } } // // Inspect all vertices derived from vertices -- for those whose parent vertices were // semisharp (inherited in the child vert's tag), inspect and reset the semisharp tag // and the associated Rule (based on neighboring child edges around the child vertex). // // We should never find such a vertex "incomplete" in a sparse refinement as a parent // vertex is either selected or not, but never neighboring. So the only complication // here is whether the local topology of child edges exists -- it may have been pruned // from the last level to reduce memory. If so, we use the parent to identify the // child edges. // // In both cases, we count the number of sharp and semisharp child edges incident the // child vertex and adjust the "semisharp" and "rule" tags accordingly. // Index vertFromVertBegin = getFirstChildVertexFromVertices(); Index vertFromVertEnd = vertFromVertBegin + getNumChildVerticesFromVertices(); for (Index cVert = vertFromVertBegin; cVert < vertFromVertEnd; ++cVert) { Index pVert = _childVertexParentIndex[cVert]; Level::VTag const& pVertTag = _parent->_vertTags[pVert]; // Skip if parent not semi-sharp: if (!pVertTag._semiSharp && !pVertTag._semiSharpEdges) continue; // // We need to inspect the child neighborhood's sharpness when either semi-sharp // edges were present around the parent vertex, or the parent vertex sharpness // decayed: // Level::VTag& cVertTag = _child->_vertTags[cVert]; bool sharpVertexDecayed = pVertTag._semiSharp && !cVertTag._semiSharp; if (pVertTag._semiSharpEdges || sharpVertexDecayed) { int infSharpEdgeCount = 0; int semiSharpEdgeCount = 0; bool cVertEdgesPresent = (_child->getNumVertexEdgesTotal() > 0); if (cVertEdgesPresent) { ConstIndexArray cEdges = _child->getVertexEdges(cVert); for (int i = 0; i < cEdges.size(); ++i) { Level::ETag cEdgeTag = _child->_edgeTags[cEdges[i]]; infSharpEdgeCount += cEdgeTag._infSharp; semiSharpEdgeCount += cEdgeTag._semiSharp; } } else { ConstIndexArray pEdges = _parent->getVertexEdges(pVert); ConstLocalIndexArray pVertInEdge = _parent->getVertexEdgeLocalIndices(pVert); for (int i = 0; i < pEdges.size(); ++i) { ConstIndexArray cEdgePair = getEdgeChildEdges(pEdges[i]); Index cEdge = cEdgePair[pVertInEdge[i]]; Level::ETag cEdgeTag = _child->_edgeTags[cEdge]; infSharpEdgeCount += cEdgeTag._infSharp; semiSharpEdgeCount += cEdgeTag._semiSharp; } } cVertTag._semiSharpEdges = (semiSharpEdgeCount > 0); if (!cVertTag._semiSharp && !cVertTag._infSharp) { cVertTag._rule = (VTagSize)(creasing.DetermineVertexVertexRule(0.0, infSharpEdgeCount + semiSharpEdgeCount)); } } } } // // Methods to subdivide face-varying channels: // void Refinement::subdivideFVarChannels() { assert(_child->_fvarChannels.size() == 0); assert(this->_fvarChannels.size() == 0); int channelCount = _parent->getNumFVarChannels(); for (int channel = 0; channel < channelCount; ++channel) { FVarLevel* parentFVar = _parent->_fvarChannels[channel]; FVarLevel* childFVar = new FVarLevel(*_child); FVarRefinement* refineFVar = new FVarRefinement(*this, *parentFVar, *childFVar); refineFVar->applyRefinement(); _child->_fvarChannels.push_back(childFVar); this->_fvarChannels.push_back(refineFVar); } } // // Marking of sparse child components -- including those selected and those neighboring... // // For schemes requiring neighboring support, this is the equivalent of the "guarantee // neighbors" in Hbr -- it ensures that all components required to define the limit of // those "selected" are also generated in the refinement. // // The difference with Hbr is that we do this in a single pass for all components once // "selection" of components of interest has been completed. // // Considering two approaches: // 1) By Vertex neighborhoods: // - for each base vertex // - for each incident face // - test and mark components for its child face // or // 2) By Edge and Face contents: // - for each base edge // - test and mark local components // - for each base face // - test and mark local components // // Given a typical quad mesh with N verts, N faces and 2*N edges, determine which is more // efficient... // // Going with (2) initially for simplicity -- certain aspects of (1) are awkward, i.e. the // identification of child-edges to be marked (trivial in (2). We are also guaranteed with // (2) that we only visit each component once, i.e. each edge and each face. // // Revising the above assessment... (2) has gotten WAY more complicated once the ability to // select child faces is provided. Given that feature is important to Manuel for support // of the FarStencilTables we have to assume it will be needed. So we'll try (1) out as it // will be simpler to get it correct -- we can work on improving performance later. // // Complexity added by child component selection: // - the child vertex of the component can now be selected as part of a child face or // edge, and so the parent face or edge is not fully selected. So we've had to add another // bit to the marking masks to indicate when a parent component is "fully selected". // - selecting a child face creates the situation where child edges of parent edges do // not have any selected vertex at their ends -- both can be neighboring. This complicated // the marking of neighboring child edges, which was otherwise trivial -- if any end vertex // of a child edge (of a parent edge) was selected, the child edge was at least neighboring. // // Final note on the marking technique: // There are currently two values to the marking of child components, which are no // longer that useful. It is now sufficient, and not likely to be necessary, to distinguish // between what was selected or added to support it. Ultimately that will be determined by // inspecting the selected flag on the parent component once the child-to-parent map is in // place. // namespace { Index const IndexSparseMaskNeighboring = (1 << 0); Index const IndexSparseMaskSelected = (1 << 1); inline void markSparseIndexNeighbor(Index& index) { index = IndexSparseMaskNeighboring; } inline void markSparseIndexSelected(Index& index) { index = IndexSparseMaskSelected; } } void Refinement::markSparseChildComponentIndices() { // // There is an explicit ordering here as the work done for vertices is a subset // of what is required for edges, which in turn is a subset of what is required // for faces. This ordering and their related implementations tries to avoid // doing redundant work and accomplishing everything necessary in a single // iteration through each component type. // markSparseVertexChildren(); markSparseEdgeChildren(); markSparseFaceChildren(); } void Refinement::markSparseVertexChildren() { assert(_parentVertexTag.size() > 0); // // For each parent vertex: // - mark the descending child vertex for each selected vertex // for (Index pVert = 0; pVert < parent().getNumVertices(); ++pVert) { if (_parentVertexTag[pVert]._selected) { markSparseIndexSelected(_vertChildVertIndex[pVert]); } } } void Refinement::markSparseEdgeChildren() { assert(_parentEdgeTag.size() > 0); // // For each parent edge: // - mark the descending child edges and vertex for each selected edge // - test each end vertex of unselected edges to see if selected: // - mark both the child edge and the middle child vertex if so // - set transitional bit for all edges based on selection of incident faces // // Note that no edges have been marked "fully selected" -- only their vertices have // been marked and marking of their child edges deferred to visiting each edge only // once here. // for (Index pEdge = 0; pEdge < parent().getNumEdges(); ++pEdge) { IndexArray eChildEdges = getEdgeChildEdges(pEdge); ConstIndexArray eVerts = parent().getEdgeVertices(pEdge); SparseTag& pEdgeTag = _parentEdgeTag[pEdge]; if (pEdgeTag._selected) { markSparseIndexSelected(eChildEdges[0]); markSparseIndexSelected(eChildEdges[1]); markSparseIndexSelected(_edgeChildVertIndex[pEdge]); } else { if (_parentVertexTag[eVerts[0]]._selected) { markSparseIndexNeighbor(eChildEdges[0]); markSparseIndexNeighbor(_edgeChildVertIndex[pEdge]); } if (_parentVertexTag[eVerts[1]]._selected) { markSparseIndexNeighbor(eChildEdges[1]); markSparseIndexNeighbor(_edgeChildVertIndex[pEdge]); } } // // TAG the parent edges as "transitional" here if only one was selected (or in // the more general non-manifold case, they are not all selected the same way). // We use the transitional tags on the edges to TAG the parent face below. // // Note -- this is best done now rather than as a post-process as we have more // explicit information about the selected components. Unless we also tag the // parent faces as selected, we can't easily tell from the child-faces of the // edge's incident faces which were generated by selection or neighboring... // ConstIndexArray eFaces = parent().getEdgeFaces(pEdge); if (eFaces.size() == 2) { pEdgeTag._transitional = (_parentFaceTag[eFaces[0]]._selected != _parentFaceTag[eFaces[1]]._selected); } else if (eFaces.size() < 2) { pEdgeTag._transitional = false; } else { bool isFace0Selected = _parentFaceTag[eFaces[0]]._selected; pEdgeTag._transitional = false; for (int i = 1; i < eFaces.size(); ++i) { if (_parentFaceTag[eFaces[i]]._selected != isFace0Selected) { pEdgeTag._transitional = true; break; } } } } } } // end namespace internal } // end namespace Vtr } // end namespace OPENSUBDIV_VERSION } // end namespace OpenSubdiv
38.49361
120
0.645205
[ "mesh" ]
2d31c9bbedd580d064d08bd86a69a390d27b22a4
5,090
cxx
C++
odb-tests-2.4.0/boost/sqlite/date-time/driver.cxx
edidada/odb
78ed750a9dde65a627fc33078225410306c2e78b
[ "MIT" ]
null
null
null
odb-tests-2.4.0/boost/sqlite/date-time/driver.cxx
edidada/odb
78ed750a9dde65a627fc33078225410306c2e78b
[ "MIT" ]
null
null
null
odb-tests-2.4.0/boost/sqlite/date-time/driver.cxx
edidada/odb
78ed750a9dde65a627fc33078225410306c2e78b
[ "MIT" ]
null
null
null
// file : boost/sqlite/date-time/driver.cxx // copyright : Copyright (c) 2009-2015 Code Synthesis Tools CC // license : GNU GPL v2; see accompanying LICENSE file // Test boost date/time type persistence. SQLite version. // #include <memory> // std::auto_ptr #include <cassert> #include <iostream> #include <odb/sqlite/database.hxx> #include <odb/sqlite/transaction.hxx> #include <common/common.hxx> #include <boost/date_time/posix_time/posix_time.hpp> #include <boost/date_time/gregorian/gregorian.hpp> #include "test.hxx" #include "test-odb.hxx" using namespace std; using namespace boost::gregorian; using namespace boost::posix_time; using namespace odb::core; bool test_invalid_special_value (object&, auto_ptr<database>&); bool test_out_of_range_value (object&, auto_ptr<database>&); int main (int argc, char* argv[]) { try { auto_ptr<database> db (create_database (argc, argv)); object o; // Test all valid date-time mappings. // o.dates.push_back (day_clock::local_day ()); o.dates.push_back (date (not_a_date_time)); o.dates.push_back (date (max_date_time)); o.dates.push_back (date (min_date_time)); o.times.push_back (second_clock::local_time ()); o.times.push_back (not_a_date_time); o.times.push_back (min_date_time); o.times.push_back (max_date_time); o.durations.push_back (time_duration (123, 4, 5)); o.durations.push_back (not_a_date_time); o.u_dates.push_back (day_clock::local_day ()); o.u_dates.push_back (date (not_a_date_time)); // Boost seems to handle 64 bit std::time_t incorrectly. // Insert 32 bit minimum and maximum UNIX time values for now. // // o.u_dates.push_back (date (max_date_time)); // o.u_dates.push_back (date (min_date_time)); // o.u_dates.push_back (date (2038, 1, 19)); o.u_dates.push_back (date (1901, 12, 14)); o.u_times.push_back (second_clock::local_time ()); o.u_times.push_back (not_a_date_time); o.u_times.push_back (ptime (date (1930, 1, 1), time_duration (0, 0, 0))); o.s_durations.push_back (time_duration (123, 4, 5)); o.s_durations.push_back (time_duration (-12, 3, 4)); o.s_durations.push_back (not_a_date_time); { transaction t (db->begin ()); db->persist (o); t.commit (); } { transaction t (db->begin ()); auto_ptr<object> ol (db->load<object> (o.id)); t.commit (); assert (*ol == o); } { // Test invalid date mappings. // object sv1, sv2; sv1.dates.push_back (date (neg_infin)); sv2.dates.push_back (date (pos_infin)); transaction t (db->begin ()); assert (test_invalid_special_value (sv1, db)); assert (test_invalid_special_value (sv2, db)); t.commit (); } { // Test invalid ptime mappings. // object sv1, sv2; sv1.times.push_back (neg_infin); sv2.times.push_back (pos_infin); transaction t (db->begin ()); assert (test_invalid_special_value (sv1, db)); assert (test_invalid_special_value (sv2, db)); t.commit (); } { // Test invalid time_duration mappings. // object or1, sv1, sv2; or1.durations.push_back (time_duration (0, 0, -1)); sv1.durations.push_back (pos_infin); sv2.durations.push_back (neg_infin); transaction t (db->begin ()); assert (test_out_of_range_value (or1, db)); assert (test_invalid_special_value (sv1, db)); assert (test_invalid_special_value (sv2, db)); t.commit (); } { // Test invalid UNIX date mappings. // object sv1, sv2; sv1.u_dates.push_back (date (neg_infin)); sv2.u_dates.push_back (date (pos_infin)); transaction t (db->begin ()); assert (test_invalid_special_value (sv1, db)); assert (test_invalid_special_value (sv2, db)); t.commit (); } // Test invalid UNIX times mappings. // { object sv1, sv2; sv1.u_times.push_back (pos_infin); sv2.u_times.push_back (neg_infin); transaction t (db->begin ()); assert (test_invalid_special_value (sv1, db)); assert (test_invalid_special_value (sv2, db)); t.commit (); } // Test invalid "seconds" duration mappings. // { object sv1, sv2; sv1.s_durations.push_back (pos_infin); sv2.s_durations.push_back (neg_infin); transaction t (db->begin ()); assert (test_invalid_special_value (sv1, db)); assert (test_invalid_special_value (sv2, db)); t.commit (); } } catch (const odb::exception& e) { cerr << e.what () << endl; return 1; } } bool test_invalid_special_value (object& x, auto_ptr<database>& db) { try { db->persist (x); return false; } catch (const odb::boost::date_time::special_value&) { } return true; } bool test_out_of_range_value (object& x, auto_ptr<database>& db) { try { db->persist (x); return false; } catch (const odb::boost::date_time::value_out_of_range&) { } return true; }
24.238095
77
0.634578
[ "object" ]
2d321a6eacd4800421717ec0b3454f8bc6c1eeff
36,622
cpp
C++
Development/Src/Engine/Src/UnkDOP.cpp
addstone/unrealengine3
4579d360dfd52b12493292120b27bb430f978fc8
[ "FSFAP" ]
37
2020-05-22T18:18:47.000Z
2022-03-19T06:51:54.000Z
Development/Src/Engine/Src/UnkDOP.cpp
AdanosGotoman/unrealengine3
4579d360dfd52b12493292120b27bb430f978fc8
[ "FSFAP" ]
null
null
null
Development/Src/Engine/Src/UnkDOP.cpp
AdanosGotoman/unrealengine3
4579d360dfd52b12493292120b27bb430f978fc8
[ "FSFAP" ]
27
2020-05-17T01:03:30.000Z
2022-03-06T19:10:14.000Z
/*============================================================================= UnkDOP.cpp: k-DOP collision Copyright 2004 Epic Games, Inc. All Rights Reserved. Revision history: * Created by Joe Graf =============================================================================*/ #include "EnginePrivate.h" #include "UnCollision.h" // These are the plane normals for the kDOP that we use (bounding box) const FVector PlaneNormals[NUM_PLANES] = { FVector(1.f,0.f,0.f), FVector(0.f,1.f,0.f), FVector(0.f,0.f,1.f) }; /* scion ====================================================================== * FkDOP::FkDOP * Author: jg * * Copies the passed in FkDOP and expands it by the extent. Note assumes AABB. * * input: kDOP -- The kDOP to copy * Extent -- The extent to expand it by * * ============================================================================ */ FkDOP::FkDOP(const FkDOP& kDOP,const FVector& Extent) { Min[0] = kDOP.Min[0] - Extent.X; Min[1] = kDOP.Min[1] - Extent.Y; Min[2] = kDOP.Min[2] - Extent.Z; Max[0] = kDOP.Max[0] + Extent.X; Max[1] = kDOP.Max[1] + Extent.Y; Max[2] = kDOP.Max[2] + Extent.Z; } /* scion ====================================================================== * FkDOP::AddPoint * Author: jg * * Adds a new point to the kDOP volume, expanding it if needed. * * input: Point The vector to add to the volume * * ============================================================================ */ void FkDOP::AddPoint(const FVector& Point) { // Dot against each plane and expand the volume out to encompass it if the // point is further away than either (min/max) of the previous points for (INT nPlane = 0; nPlane < NUM_PLANES; nPlane++) { // Project this point onto the plane normal FLOAT Dot = Point | PlaneNormals[nPlane]; // Move the plane out as needed if (Dot < Min[nPlane]) { Min[nPlane] = Dot; } if (Dot > Max[nPlane]) { Max[nPlane] = Dot; } } } /* scion ====================================================================== * FkDOP::AddTriangles * Author: jg * * Adds all of the triangle data to the kDOP volume * * input: Vertices -- The mesh's rendering vertices * StartIndex -- The triangle index to start processing with * NumTris -- The number of triangles to process * BuildTriangles -- The list of triangles to use for the build process * * ============================================================================ */ void FkDOP::AddTriangles(TArray<FStaticMeshVertex>& Vertices,INT StartIndex,INT NumTris,TArray<FkDOPBuildCollisionTriangle>& BuildTriangles) { // Reset the min/max planes Init(); // Go through the list and add each of the triangle verts to our volume for( INT nTriangle = StartIndex; nTriangle < StartIndex + NumTris;nTriangle++ ) { AddPoint(Vertices(BuildTriangles(nTriangle).v1).Position); AddPoint(Vertices(BuildTriangles(nTriangle).v2).Position); AddPoint(Vertices(BuildTriangles(nTriangle).v3).Position); } } /* scion ====================================================================== * FkDOP::LineCheck * Author: jg * * Checks a line against this kDOP. Note this assumes a AABB. If more planes * are to be used, this needs to be rewritten. Also note, this code is Andrew's * original code modified to work with FkDOP * * input: Check The aggregated line check structure * HitTime The out value indicating hit time * * ============================================================================ */ UBOOL FkDOP::LineCheck(FkDOPLineCollisionCheck& Check,FLOAT& HitTime) { FVector Time(0.f,0.f,0.f); UBOOL Inside = 1; HitTime = 0.0f; // always initialize (prevent valgrind whining) --ryan. if(Check.LocalStart.X < Min[0]) { if(Check.LocalDir.X <= 0.0f) return 0; else { Inside = 0; Time.X = (Min[0] - Check.LocalStart.X) * Check.LocalOneOverDir.X; } } else if(Check.LocalStart.X > Max[0]) { if(Check.LocalDir.X >= 0.0f) return 0; else { Inside = 0; Time.X = (Max[0] - Check.LocalStart.X) * Check.LocalOneOverDir.X; } } if(Check.LocalStart.Y < Min[1]) { if(Check.LocalDir.Y <= 0.0f) return 0; else { Inside = 0; Time.Y = (Min[1] - Check.LocalStart.Y) * Check.LocalOneOverDir.Y; } } else if(Check.LocalStart.Y > Max[1]) { if(Check.LocalDir.Y >= 0.0f) return 0; else { Inside = 0; Time.Y = (Max[1] - Check.LocalStart.Y) * Check.LocalOneOverDir.Y; } } if(Check.LocalStart.Z < Min[2]) { if(Check.LocalDir.Z <= 0.0f) return 0; else { Inside = 0; Time.Z = (Min[2] - Check.LocalStart.Z) * Check.LocalOneOverDir.Z; } } else if(Check.LocalStart.Z > Max[2]) { if(Check.LocalDir.Z >= 0.0f) return 0; else { Inside = 0; Time.Z = (Max[2] - Check.LocalStart.Z) * Check.LocalOneOverDir.Z; } } if(Inside) { HitTime = 0.f; return 1; } HitTime = Time.GetMax(); if(HitTime >= 0.0f && HitTime <= 1.0f) { const FVector& Hit = Check.LocalStart + Check.LocalDir * HitTime; return (Hit.X > Min[0] - FUDGE_SIZE && Hit.X < Max[0] + FUDGE_SIZE && Hit.Y > Min[1] - FUDGE_SIZE && Hit.Y < Max[1] + FUDGE_SIZE && Hit.Z > Min[2] - FUDGE_SIZE && Hit.Z < Max[2] + FUDGE_SIZE); } return 0; } /* scion ====================================================================== * FkDOP::PointCheck * Author: jg * * Checks a point with extent against this kDOP. The extent is already added in * to the kDOP being tested (Minkowski sum), so this code just checks to see if * the point is inside the kDOP. Note this assumes a AABB. If more planes are * to be used, this needs to be rewritten. * * input: Check The aggregated point check structure * * ============================================================================ */ UBOOL FkDOP::PointCheck(FkDOPPointCollisionCheck& Check) { return Check.LocalStart.X >= Min[0] && Check.LocalStart.X <= Max[0] && Check.LocalStart.Y >= Min[1] && Check.LocalStart.Y <= Max[1] && Check.LocalStart.Z >= Min[2] && Check.LocalStart.Z <= Max[2]; } /* scion ====================================================================== * FkDOP::PointCheck * Author: jag * * Check (local space) AABB against this kDOP. * * input: LocalAABB * * ============================================================================ */ UBOOL FkDOP::AABBOverlapCheck(const FBox& LocalAABB) { if( Min[0] > LocalAABB.Max.X || LocalAABB.Min.X > Max[0] ) return 0; if( Min[1] > LocalAABB.Max.Y || LocalAABB.Min.Y > Max[1] ) return 0; if( Min[2] > LocalAABB.Max.Z || LocalAABB.Min.Z > Max[2] ) return 0; return 1; } /* scion ====================================================================== * FkDOPTree::Build * Author: jg * * Creates the root node and recursively splits the triangles into smaller * volumes * * input: Vertices -- The mesh's vertex data * BuildTriangles -- The list of triangles to use for the build process * * ============================================================================ */ void FkDOPTree::Build(TArray<FStaticMeshVertex>& Vertices,TArray<FkDOPBuildCollisionTriangle>& BuildTriangles) { // Empty the current set of nodes and preallocate the memory so it doesn't // reallocate memory while we are recursively walking the tree Nodes.Empty(BuildTriangles.Num()*2); // Add the root node Nodes.Add(); // Now tell that node to recursively subdivide the entire set of triangles Nodes(0).SplitTriangleList(Vertices,0,BuildTriangles.Num(),BuildTriangles,Nodes); // Don't waste memory. Nodes.Shrink(); // Copy over the triangle information afterward, since they will have // been sorted into their bounding volumes at this point Triangles.Empty(); Triangles.Add(BuildTriangles.Num()); // Copy the triangles from the build list into the full list for (INT nIndex = 0; nIndex < BuildTriangles.Num(); nIndex++) { Triangles(nIndex) = BuildTriangles(nIndex); } } /* scion ====================================================================== * FkDOPNode::SplitTriangleList * Author: jg * * Determines if the node is a leaf or not. If it is not a leaf, it subdivides * the list of triangles again adding two child nodes and splitting them on * the mean (splatter method). Otherwise it sets up the triangle information. * * input: Vertices -- The mesh's rendering data * Start -- The triangle index to start processing with * NumTris -- The number of triangles to process * BuildTriangles -- The list of triangles to use for the build process * Nodes -- The list of nodes in this tree * * ============================================================================ */ void FkDOPNode::SplitTriangleList(TArray<FStaticMeshVertex>& Vertices,INT Start,INT NumTris,TArray<FkDOPBuildCollisionTriangle>& BuildTriangles,TArray<FkDOPNode>& Nodes) { // Add all of the triangles to the bounding volume BoundingVolume.AddTriangles(Vertices,Start,NumTris,BuildTriangles); // Figure out if we are a leaf node or not if (NumTris > MAX_TRIS_PER_LEAF) { // Still too many triangles, so continue subdividing the triangle list bIsLeaf = 0; INT BestPlane = -1; FLOAT BestMean = 0.f; FLOAT BestVariance = 0.f; // Determine how to split using the splatter algorithm for (INT nPlane = 0; nPlane < NUM_PLANES; nPlane++) { FLOAT Mean = 0.f; FLOAT Variance = 0.f; // Compute the mean for the triangle list for (INT nTriangle = Start; nTriangle < Start + NumTris;nTriangle++) { // Project the centroid of the triangle against the plane // normals and accumulate to find the total projected // weighting Mean += BuildTriangles(nTriangle).Centroid | PlaneNormals[nPlane]; } // Divide by the number of triangles to get the average Mean /= FLOAT(NumTris); // Compute variance of the triangle list for (INT nTriangle = Start; nTriangle < Start + NumTris;nTriangle++) { // Project the centroid again FLOAT Dot = BuildTriangles(nTriangle).Centroid | PlaneNormals[nPlane]; // Now calculate the variance and accumulate it Variance += (Dot - Mean) * (Dot - Mean); } // Get the average variance Variance /= FLOAT(NumTris); // Determine if this plane is the best to split on or not if (Variance >= BestVariance) { BestPlane = nPlane; BestVariance = Variance; BestMean = Mean; } } // Now that we have the plane to split on, work through the triangle // list placing them on the left or right of the splitting plane INT Left = Start - 1; INT Right = Start + NumTris; // Keep working through until the left index passes the right while (Left < Right) { FLOAT Dot; // Find all the triangles to the "left" of the splitting plane do { Dot = BuildTriangles(++Left).Centroid | PlaneNormals[BestPlane]; } while (Dot < BestMean && Left < Right); // Find all the triangles to the "right" of the splitting plane do { Dot = BuildTriangles(--Right).Centroid | PlaneNormals[BestPlane]; } while (Dot >= BestMean && Right > 0 && Left < Right); // Don't swap the triangle data if we just hit the end if (Left < Right) { // Swap the triangles since they are on the wrong sides of the // splitting plane FkDOPBuildCollisionTriangle Temp = BuildTriangles(Left); BuildTriangles(Left) = BuildTriangles(Right); BuildTriangles(Right) = Temp; } } // Check for wacky degenerate case where more than MAX_TRIS_PER_LEAF // fall all in the same kDOP if (Left == Start + NumTris || Right == Start) { Left = Start + (NumTris / 2); } // Add the two child nodes n.LeftNode = Nodes.Add(2); n.RightNode = n.LeftNode + 1; // Have the left node recursively subdivide it's list Nodes(n.LeftNode).SplitTriangleList(Vertices,Start,Left - Start,BuildTriangles,Nodes); // And now have the right node recursively subdivide it's list Nodes(n.RightNode).SplitTriangleList(Vertices,Left,Start + NumTris - Left,BuildTriangles,Nodes); } else { // No need to subdivide further so make this a leaf node bIsLeaf = 1; // Copy in the triangle information t.StartIndex = Start; t.NumTriangles = NumTris; } } /* scion ====================================================================== * FkDOPNode::LineCheck * Author: jg * * Determines the line in the FkDOPLineCollisionCheck intersects this node. It * also will check the child nodes if it is not a leaf, otherwise it will check * against the triangle data. * * input: Check -- The aggregated line check data * * ============================================================================ */ UBOOL FkDOPNode::LineCheck(FkDOPLineCollisionCheck& Check) { UBOOL bHit = 0; // If this is a node, check the two child nodes and pick the closest one // to recursively check against and only check the second one if there is // not a hit or the hit returned is further out than the second node if (bIsLeaf == 0) { // Holds the indices for the closest and farthest nodes INT NearNode = -1; INT FarNode = -1; // Holds the hit times for the child nodes FLOAT Child1, Child2; // Assume the left node is closer (it will be adjusted later) if (Check.Nodes(n.LeftNode).BoundingVolume.LineCheck(Check,Child1)) { NearNode = n.LeftNode; } // Find out if the second node is closer if (Check.Nodes(n.RightNode).BoundingVolume.LineCheck(Check,Child2)) { // See if the left node was a miss and make the right the near node if (NearNode == -1) { NearNode = n.RightNode; } else { FarNode = n.RightNode; } } // Swap the Near/FarNodes if the right node is closer than the left if (NearNode != -1 && FarNode != -1 && Child2 < Child1) { Exchange(NearNode,FarNode); Exchange(Child1,Child2); } // See if we need to search the near node or not if (NearNode != -1 && Check.Result->Time > Child1) { bHit = Check.Nodes(NearNode).LineCheck(Check); } // Now do the same for the far node. This will only happen if a miss in // the near node or the nodes overlapped and this one is closer if (FarNode != -1 && Check.Result->Time > Child2) { bHit |= Check.Nodes(FarNode).LineCheck(Check); } } else { // This is a leaf, check the triangles for a hit bHit = LineCheckTriangles(Check); } return bHit; } /* scion ====================================================================== * FkDOPNode::LineCheckTriangles * Author: jg * * Works through the list of triangles in this node checking each one for a * collision. * * input: Check -- The aggregated line check data * * ============================================================================ */ UBOOL FkDOPNode::LineCheckTriangles(FkDOPLineCollisionCheck& Check) { // Assume a miss UBOOL bHit = 0; // Loop through all of our triangles. We need to check them all in case // there are two (or more) potential triangles that would collide and let // the code choose the closest for( INT nCollTriIndex = t.StartIndex; nCollTriIndex < t.StartIndex + t.NumTriangles; nCollTriIndex++ ) { // Get the collision triangle that we are checking against const FkDOPCollisionTriangle& CollTri = Check.CollisionTriangles(nCollTriIndex); // Now get refs to the 3 verts to check against const FStaticMeshVertex& v1 = Check.Triangles(CollTri.v1); const FStaticMeshVertex& v2 = Check.Triangles(CollTri.v2); const FStaticMeshVertex& v3 = Check.Triangles(CollTri.v3); // Now check for an intersection bHit |= LineCheckTriangle(Check,v1,v2,v3,CollTri.MaterialIndex); } return bHit; } /* scion ====================================================================== * FkDOPNode::LineCheckTriangle * Author: jg * * Performs collision checking against the triangle using the old collision * code to handle it. This is done to provide consistency in collision. * * input: Check -- The aggregated line check data * v1 -- The first vertex of the triangle * v2 -- The second vertex of the triangle * v3 -- The third vertex of the triangle * MaterialIndex -- The material for this triangle if it is hit * * ============================================================================ */ UBOOL FkDOPNode::LineCheckTriangle(FkDOPLineCollisionCheck& Check,const FStaticMeshVertex& v1,const FStaticMeshVertex& v2,const FStaticMeshVertex& v3,INT MaterialIndex) { // Calculate the hit normal the same way the old code // did so things are the same const FVector& LocalNormal = ((v2.Position - v3.Position) ^ (v1.Position - v3.Position)).SafeNormal(); // Calculate the hit time the same way the old code // did so things are the same FPlane TrianglePlane(v1.Position,LocalNormal); FLOAT StartDist = TrianglePlane.PlaneDot(Check.LocalStart); FLOAT EndDist = TrianglePlane.PlaneDot(Check.LocalEnd); if ((StartDist > -0.001f && EndDist > -0.001f) || (StartDist < 0.001f && EndDist < 0.001f)) { return 0; } // Figure out when it will hit the triangle FLOAT Time = -StartDist / (EndDist - StartDist); // If this triangle is not closer than the previous hit, reject it if (Time >= Check.Result->Time) return 0; // Calculate the line's point of intersection with the node's plane const FVector& Intersection = Check.LocalStart + Check.LocalDir * Time; const FVector* Verts[3] = { &v1.Position, &v2.Position, &v3.Position }; // Check if the point of intersection is inside the triangle's edges. for( INT SideIndex = 0; SideIndex < 3; SideIndex++ ) { const FVector& SideDirection = LocalNormal ^ (*Verts[(SideIndex + 1) % 3] - *Verts[SideIndex]); FLOAT SideW = SideDirection | *Verts[SideIndex]; if( ((SideDirection | Intersection) - SideW) >= 0.f ) { return 0; } } // Return results Check.LocalHitNormal = LocalNormal; Check.Result->Time = Time; Check.Result->Material = Check.Component->GetMaterial(MaterialIndex); return 1; } /* scion ====================================================================== * FkDOPNode::BoxCheck * Author: jg * * Determines the line + extent in the FkDOPBoxCollisionCheck intersects this * node. It also will check the child nodes if it is not a leaf, otherwise it * will check against the triangle data. * * input: Check -- The aggregated box check data * * ============================================================================ */ UBOOL FkDOPNode::BoxCheck(FkDOPBoxCollisionCheck& Check) { UBOOL bHit = 0; // If this is a node, check the two child nodes and pick the closest one // to recursively check against and only check the second one if there is // not a hit or the hit returned is further out than the second node if (bIsLeaf == 0) { // Holds the indices for the closest and farthest nodes INT NearNode = -1; INT FarNode = -1; // Holds the hit times for the child nodes FLOAT Child1, Child2; // Update the kDOP with the extent and test against that FkDOP kDOPNear(Check.Nodes(n.LeftNode).BoundingVolume,Check.LocalExtent); // Assume the left node is closer (it will be adjusted later) if (kDOPNear.LineCheck(Check,Child1)) { NearNode = n.LeftNode; } // Update the kDOP with the extent and test against that FkDOP kDOPFar(Check.Nodes(n.RightNode).BoundingVolume,Check.LocalExtent); // Find out if the second node is closer if (kDOPFar.LineCheck(Check,Child2)) { // See if the left node was a miss and make the right the near node if (NearNode == -1) { NearNode = n.RightNode; } else { FarNode = n.RightNode; } } // Swap the Near/FarNodes if the right node is closer than the left if (NearNode != -1 && FarNode != -1 && Child2 < Child1) { Exchange(NearNode,FarNode); Exchange(Child1,Child2); } // See if we need to search the near node or not if (NearNode != -1) { bHit = Check.Nodes(NearNode).BoxCheck(Check); } // Now do the same for the far node. This will only happen if a miss in // the near node or the nodes overlapped and this one is closer if (FarNode != -1 && (Check.Result->Time > Child2 || bHit == 0)) { bHit |= Check.Nodes(FarNode).BoxCheck(Check); } } else { // This is a leaf, check the triangles for a hit bHit = BoxCheckTriangles(Check); } return bHit; } /* scion ====================================================================== * FkDOPNode::BoxCheckTriangles * Author: jg * * Works through the list of triangles in this node checking each one for a * collision. * * input: Check -- The aggregated box check data * * ============================================================================ */ UBOOL FkDOPNode::BoxCheckTriangles(FkDOPBoxCollisionCheck& Check) { // Assume a miss UBOOL bHit = 0; // Loop through all of our triangles. We need to check them all in case // there are two (or more) potential triangles that would collide and let // the code choose the closest for( INT nCollTriIndex = t.StartIndex; nCollTriIndex < t.StartIndex + t.NumTriangles; nCollTriIndex++ ) { // Get the collision triangle that we are checking against const FkDOPCollisionTriangle& CollTri = Check.CollisionTriangles(nCollTriIndex); // Now get refs to the 3 verts to check against const FVector& v1 = Check.Triangles(CollTri.v1).Position; const FVector& v2 = Check.Triangles(CollTri.v2).Position; const FVector& v3 = Check.Triangles(CollTri.v3).Position; // Now check for an intersection using the Separating Axis Theorem bHit |= BoxCheckTriangle(Check,v1,v2,v3,CollTri.MaterialIndex); } return bHit; } /* scion ====================================================================== * FkDOPNode::BoxCheckTriangle * Author: jg * * Uses the separating axis theorem to check for triangle box collision. * * input: Check -- The aggregated box check data * v1 -- The first vertex of the triangle * v2 -- The second vertex of the triangle * v3 -- The third vertex of the triangle * MaterialIndex -- The material for this triangle if it is hit * * ============================================================================ */ UBOOL FkDOPNode::BoxCheckTriangle(FkDOPBoxCollisionCheck& Check,const FVector& v1,const FVector& v2,const FVector& v3,INT MaterialIndex) { FLOAT HitTime = 1.f; FVector HitNormal(0.f,0.f,0.f); // Now check for an intersection using the Separating Axis Theorem UBOOL Result = FindSeparatingAxis(v1,v2,v3,Check.LocalStart,Check.LocalEnd,Check.Extent,Check.LocalBoxX,Check.LocalBoxY,Check.LocalBoxZ,HitTime,HitNormal); if(Result) { if (HitTime < Check.Result->Time) { // Store the better time Check.Result->Time = HitTime; // Get the material that was hit Check.Result->Material = Check.Component->GetMaterial(MaterialIndex); // Normal will get transformed to world space at end of check Check.LocalHitNormal = HitNormal; return 1; } } return 0; } /* scion ====================================================================== * FkDOPNode::PointCheck * Author: jg * * Determines the point + extent in the FkDOPPointCollisionCheck intersects * this node. It also will check the child nodes if it is not a leaf, otherwise * it will check against the triangle data. * * input: Check -- The aggregated point check data * * ============================================================================ */ UBOOL FkDOPNode::PointCheck(FkDOPPointCollisionCheck& Check) { UBOOL bHit = 0; // If this is a node, check the two child nodes recursively if (bIsLeaf == 0) { // Holds the indices for the closest and farthest nodes INT NearNode = -1; INT FarNode = -1; // Update the kDOP with the extent and test against that FkDOP kDOPNear(Check.Nodes(n.LeftNode).BoundingVolume,Check.LocalExtent); // Assume the left node is closer (it will be adjusted later) if (kDOPNear.PointCheck(Check)) { NearNode = n.LeftNode; } // Update the kDOP with the extent and test against that FkDOP kDOPFar(Check.Nodes(n.RightNode).BoundingVolume,Check.LocalExtent); // Find out if the second node is closer if (kDOPFar.PointCheck(Check)) { // See if the left node was a miss and make the right the near node if (NearNode == -1) { NearNode = n.RightNode; } else { FarNode = n.RightNode; } } // See if we need to search the near node or not if (NearNode != -1) { bHit = Check.Nodes(NearNode).PointCheck(Check); } // Now do the same for the far node if (FarNode != -1) { bHit |= Check.Nodes(FarNode).PointCheck(Check); } } else { // This is a leaf, check the triangles for a hit bHit = PointCheckTriangles(Check); } return bHit; } /* =========================================================================== * FkDOPNode::SphereQuery * Author: jag * * Find triangles that overlap the given sphere. We assume that the supplied box overlaps this node. * * input: Query -- Query information * * ============================================================================ */ void FkDOPNode::SphereQuery(FkDOPSphereQuery& Query) { // If not leaf, check against each child. if(bIsLeaf == 0) { if( Query.Nodes(n.LeftNode).BoundingVolume.AABBOverlapCheck(Query.LocalBox) ) Query.Nodes(n.LeftNode).SphereQuery(Query); if( Query.Nodes(n.RightNode).BoundingVolume.AABBOverlapCheck(Query.LocalBox) ) Query.Nodes(n.RightNode).SphereQuery(Query); } else // Otherwise, add all the triangles in this node to the list. { for(INT i=t.StartIndex; i<t.StartIndex+t.NumTriangles; i++) { Query.ReturnTriangles.AddItem( i ); } } } /* scion ====================================================================== * FkDOPNode::PointCheckTriangles * Author: jg * * Works through the list of triangles in this node checking each one for a * collision. * * input: Check -- The aggregated point check data * * ============================================================================ */ UBOOL FkDOPNode::PointCheckTriangles(FkDOPPointCollisionCheck& Check) { // Assume a miss UBOOL bHit = 0; // Loop through all of our triangles. We need to check them all in case // there are two (or more) potential triangles that would collide and let // the code choose the closest for( INT nCollTriIndex = t.StartIndex; nCollTriIndex < t.StartIndex + t.NumTriangles; nCollTriIndex++ ) { // Get the collision triangle that we are checking against const FkDOPCollisionTriangle& CollTri = Check.CollisionTriangles(nCollTriIndex); // Now get refs to the 3 verts to check against const FVector& v1 = Check.Triangles(CollTri.v1).Position; const FVector& v2 = Check.Triangles(CollTri.v2).Position; const FVector& v3 = Check.Triangles(CollTri.v3).Position; // Now check for an intersection using the Separating Axis Theorem bHit |= PointCheckTriangle(Check,v1,v2,v3,CollTri.MaterialIndex); } return bHit; } /* scion ====================================================================== * FkDOPNode::PointCheckTriangle * Author: jg * * Uses the separating axis theorem to check for triangle box collision. * * input: Check -- The aggregated box check data * v1 -- The first vertex of the triangle * v2 -- The second vertex of the triangle * v3 -- The third vertex of the triangle * MaterialIndex -- The material for this triangle if it is hit * * ============================================================================ */ UBOOL FkDOPNode::PointCheckTriangle(FkDOPPointCollisionCheck& Check, const FVector& v1,const FVector& v2,const FVector& v3,INT MaterialIndex) { // Use the separating axis thereom to see if we hit FSeparatingAxisPointCheck PointCheck(v1,v2,v3,Check.LocalStart,Check.Extent,Check.LocalBoxX,Check.LocalBoxY,Check.LocalBoxZ,Check.BestDistance); // If we hit and it is closer update the out values if (PointCheck.Hit && PointCheck.BestDist < Check.BestDistance) { // Get the material that was hit Check.Result->Material = Check.Component->GetMaterial(MaterialIndex); // Normal will get transformed to world space at end of check Check.LocalHitNormal = PointCheck.HitNormal; // Copy the distance for push out calculations Check.BestDistance = PointCheck.BestDist; return 1; } return 0; } /* scion ====================================================================== * FkDOPTree::LineCheck * Author: jg * * Figures out whether the check even hits the root node's bounding volume. If * it does, it recursively searches for a triangle to hit. * * input: Check -- The aggregated line check data * * ============================================================================ */ UBOOL FkDOPTree::LineCheck(FkDOPLineCollisionCheck& Check) { UBOOL bHit = 0; FLOAT HitTime; // Check against the first bounding volume and decide whether to go further if (Nodes(0).BoundingVolume.LineCheck(Check,HitTime)) { // Recursively check for a hit bHit = Nodes(0).LineCheck(Check); } return bHit; } /* scion ====================================================================== * FkDOPTree::BoxCheck * Author: jg * * Figures out whether the check even hits the root node's bounding volume. If * it does, it recursively searches for a triangle to hit. * * input: Check -- The aggregated box check data * * ============================================================================ */ UBOOL FkDOPTree::BoxCheck(FkDOPBoxCollisionCheck& Check) { UBOOL bHit = 0; FLOAT HitTime; // Check the root node's bounding volume expanded by the extent FkDOP kDOP(Nodes(0).BoundingVolume,Check.LocalExtent); // Check against the first bounding volume and decide whether to go further if (kDOP.LineCheck(Check,HitTime)) { // Recursively check for a hit bHit = Nodes(0).BoxCheck(Check); } return bHit; } /* scion ====================================================================== * FkDOPTree::PointCheck * Author: jg * * Figures out whether the check even hits the root node's bounding volume. If * it does, it recursively searches for a triangle to hit. * * input: Check -- The aggregated point check data * * ============================================================================ */ UBOOL FkDOPTree::PointCheck(FkDOPPointCollisionCheck& Check) { UBOOL bHit = 0; // Check the root node's bounding volume expanded by the extent FkDOP kDOP(Nodes(0).BoundingVolume,Check.LocalExtent); // Check against the first bounding volume and decide whether to go further if (kDOP.PointCheck(Check)) { // Recursively check for a hit bHit = Nodes(0).PointCheck(Check); } return bHit; } /* =========================================================================== * FkDOPTree::SphereQuery * Author: jag * * Find all triangles in static mesh that overlap a supplied bounding sphere. * * input: Query -- The aggregated sphere query data * * ============================================================================ */ void FkDOPTree::SphereQuery(FkDOPSphereQuery& Query) { // Check the query box overlaps the root node KDOP. If so, run query recursively. if( Query.Nodes(0).BoundingVolume.AABBOverlapCheck( Query.LocalBox ) ) { Query.Nodes(0).SphereQuery( Query ); } } // // FCollisionCheck::FCollisionCheck // FCollisionCheck::FCollisionCheck(FCheckResult* InResult,UStaticMeshComponent* InComponent): Result(InResult), Owner(InComponent->Owner), Component(InComponent), StaticMesh(InComponent->StaticMesh) {} /* scion ====================================================================== * FkDOPLineCollisionCheck::FkDOPLineCollisionCheck * Author: jg * * Sets up the FkDOPLineCollisionCheck structure for performing line checks * against a kDOPTree. Initializes all of the variables that are used * throughout the line check. * * input: InResult -- The out param for hit result information * InOwner -- The owning actor being checked * InStaticMesh -- The static mesh being checked * InStart -- The starting point of the trace * InEnd -- The ending point of the trace * * ============================================================================ */ FkDOPLineCollisionCheck::FkDOPLineCollisionCheck(FCheckResult* InResult,UStaticMeshComponent* InComponent,const FVector& InStart,const FVector& InEnd) : FCollisionCheck(InResult,InComponent), Start(InStart), End(InEnd), kDOPTree(InComponent->StaticMesh->kDOPTree), Nodes(InComponent->StaticMesh->kDOPTree.Nodes), CollisionTriangles(InComponent->StaticMesh->kDOPTree.Triangles), Triangles(InComponent->StaticMesh->Vertices) { // For calculating hit normals WorldToLocal = Component->LocalToWorld.Inverse(); // Move start and end to local space LocalStart = WorldToLocal.TransformFVector(Start); LocalEnd = WorldToLocal.TransformFVector(End); // Calculate the vector's direction in local space LocalDir = LocalEnd - LocalStart; // Build the one over dir LocalOneOverDir.X = LocalDir.X ? 1.f / LocalDir.X : 0.f; LocalOneOverDir.Y = LocalDir.Y ? 1.f / LocalDir.Y : 0.f; LocalOneOverDir.Z = LocalDir.Z ? 1.f / LocalDir.Z : 0.f; // Clear the closest hit time Result->Time = MAX_FLT; } /* scion ====================================================================== * FkDOPBoxCollisionCheck::FkDOPBoxCollisionCheck * Author: jg * * Sets up the FkDOPBoxCollisionCheck structure for performing swept box checks * against a kDOPTree. Initializes all of the variables that are used * throughout the check. * * input: InResult -- The out param for hit result information * InOwner -- The owning actor being checked * InStaticMesh -- The static mesh being checked * InStart -- The starting point of the trace * InEnd -- The ending point of the trace * InExtent -- The extent to check * * ============================================================================ */ FkDOPBoxCollisionCheck::FkDOPBoxCollisionCheck(FCheckResult* InResult,UStaticMeshComponent* InComponent,const FVector& InStart,const FVector& InEnd,const FVector& InExtent) : FkDOPLineCollisionCheck(InResult,InComponent,InStart,InEnd),Extent(InExtent) { // Move extent to local space LocalExtent = FBox(-Extent,Extent).TransformBy(WorldToLocal).GetExtent(); // Transform the PlaneNormals into local space. LocalBoxX = WorldToLocal.TransformNormal(PlaneNormals[0]); LocalBoxY = WorldToLocal.TransformNormal(PlaneNormals[1]); LocalBoxZ = WorldToLocal.TransformNormal(PlaneNormals[2]); } /* scion ====================================================================== * FkDOPPointCollisionCheck::FkDOPPointCollisionCheck * Author: jg * * Sets up the FkDOPPointCollisionCheck structure for performing point checks * (point plus extent) against a kDOPTree. Initializes all of the variables * that are used throughout the check. * * input: InResult -- The out param for hit result information * InOwner -- The owning actor being checked * InStaticMesh -- The static mesh being checked * InLocation -- The point to check for intersection * InExtent -- The extent to check * * ============================================================================ */ FkDOPPointCollisionCheck::FkDOPPointCollisionCheck(FCheckResult* InResult,UStaticMeshComponent* InComponent,const FVector& InLocation,const FVector& InExtent) : FkDOPBoxCollisionCheck(InResult,InComponent,InLocation,InLocation,InExtent), BestDistance(100000.f) { } /* =========================================================================== * FkDOPSphereQuery::FkDOPSphereQuery * Author: jag * * Sets up the FkDOPSphereQuery structure for finding the set of triangles * in the static mesh that overlap the give sphere. * * input: InOwner -- The owning actor being checked * InStaticMesh -- The static mesh being checked * InSphere -- Sphere to query against * output: OutTriangles -- Array of collision triangles that overlap sphere * * ============================================================================ */ FkDOPSphereQuery::FkDOPSphereQuery(UStaticMeshComponent* InComponent,const FSphere& InSphere,TArray<INT>& OutTriangles) : Nodes( InComponent->StaticMesh->kDOPTree.Nodes ), CollisionTriangles( InComponent->StaticMesh->kDOPTree.Triangles ), ReturnTriangles( OutTriangles ) { // Find bounding box we are querying triangles against in local space. FMatrix w2l = InComponent->LocalToWorld.Inverse(); FVector radiusVec(InSphere.W, InSphere.W, InSphere.W); FBox WorldBox(InSphere - radiusVec, InSphere + radiusVec); LocalBox = WorldBox.TransformBy(w2l); }
34.258185
174
0.622549
[ "mesh", "vector", "transform" ]
2d37286db6f80e9f3e4f3b213f2e30a074aed164
3,211
cc
C++
stats/src/builder.cc
centreon-lab/centreon-broker
b412470204eedc01422bbfd00bcc306dfb3d2ef5
[ "Apache-2.0" ]
40
2015-03-10T07:55:39.000Z
2021-06-11T10:13:56.000Z
stats/src/builder.cc
centreon-lab/centreon-broker
b412470204eedc01422bbfd00bcc306dfb3d2ef5
[ "Apache-2.0" ]
297
2015-04-30T10:02:04.000Z
2022-03-09T13:31:54.000Z
stats/src/builder.cc
centreon-lab/centreon-broker
b412470204eedc01422bbfd00bcc306dfb3d2ef5
[ "Apache-2.0" ]
29
2015-08-03T10:04:15.000Z
2021-11-25T12:21:00.000Z
/* * Copyright 2011 - 2021 Centreon (https://www.centreon.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. * * For more information : contact@centreon.com * */ #include "com/centreon/broker/stats/builder.hh" #include <time.h> #include <unistd.h> #include <asio.hpp> #include "com/centreon/broker/config/applier/endpoint.hh" #include "com/centreon/broker/config/applier/modules.hh" #include "com/centreon/broker/config/endpoint.hh" #include "com/centreon/broker/misc/filesystem.hh" #include "com/centreon/broker/misc/string.hh" #include "com/centreon/broker/multiplexing/muxer.hh" #include "com/centreon/broker/mysql_manager.hh" #include "com/centreon/broker/stats/helper.hh" using namespace com::centreon::broker; using namespace com::centreon::broker::stats; /************************************** * * * Public Methods * * * **************************************/ /** * Default constructor. */ builder::builder() {} /** * Copy constructor. * * @param[in] right The object to copy. */ builder::builder(builder const& right) { operator=(right); } /** * Destructor. */ builder::~builder() noexcept {} /** * Copy operator. * * @param[in] right The object to copy. * * @return This object. */ builder& builder::operator=(builder const& right) { if (this != &right) { _data = right._data; _root = right._root; } return (*this); } /** * Get and build statistics. * * @param[in,out] srz The serializer to use to serialize data. */ void builder::build() { // Cleanup. _data.clear(); nlohmann::json object; stats::get_generic_stats(object); nlohmann::json mysql_object; stats::get_mysql_stats(mysql_object); object["mysql manager"] = mysql_object; std::vector<nlohmann::json> modules_objects; stats::get_loaded_module_stats(modules_objects); for (auto& obj : modules_objects) { std::string key{fmt::format("module{}", obj["name"].get<std::string>())}; object[key] = std::move(obj); } std::vector<nlohmann::json> endpoint_objects; stats::get_endpoint_stats(endpoint_objects); for (auto& obj : endpoint_objects) { std::string key{fmt::format("endpoint {}", obj["name"].get<std::string>())}; object[key] = std::move(obj); } _root = std::move(object); std::string buffer{_root.dump()}; _data.insert(0, buffer); } /** * Get data buffer. * * @return The statistics buffer. */ std::string const& builder::data() const noexcept { return _data; } /** * Get the properties tree. * * @return The statistics tree. */ const nlohmann::json& builder::root() const noexcept { return _root; }
24.7
80
0.650576
[ "object", "vector" ]
2d3a56c63084b777fb03d676f104ac4297a17419
4,201
cpp
C++
android/spatialiteandroidlibrary/src/main/jni/geos-3.2.2/source/util/Profiler.cpp
fedort/react-native-spatial
f12fe12c567ecb6c088a2b0cb9468c2f28d4cbba
[ "MIT" ]
null
null
null
android/spatialiteandroidlibrary/src/main/jni/geos-3.2.2/source/util/Profiler.cpp
fedort/react-native-spatial
f12fe12c567ecb6c088a2b0cb9468c2f28d4cbba
[ "MIT" ]
null
null
null
android/spatialiteandroidlibrary/src/main/jni/geos-3.2.2/source/util/Profiler.cpp
fedort/react-native-spatial
f12fe12c567ecb6c088a2b0cb9468c2f28d4cbba
[ "MIT" ]
1
2021-01-13T17:59:17.000Z
2021-01-13T17:59:17.000Z
/********************************************************************** * $Id: Profiler.cpp 1820 2006-09-06 16:54:23Z mloskot $ * * GEOS - Geometry Engine Open Source * http://geos.refractions.net * * Copyright (C) 2001-2002 Vivid Solutions Inc. * * This is free software; you can redistribute and/or modify it under * the terms of the GNU Lesser General Public Licence as published * by the Free Software Foundation. * See the COPYING file for more information. * **********************************************************************/ #include <geos/profiler.h> #include <iostream> #include <map> #include <string> #include <utility> using namespace std; namespace geos { namespace util { // geos.util Profile::Profile(string newname) { name = newname; totaltime = 0; min = max = avg = 0; } Profile::~Profile() { } #if 0 void Profile::start() { gettimeofday(&starttime, NULL); } void Profile::stop() { gettimeofday(&stoptime, NULL); double elapsed = 1000000*(stoptime.tv_sec-starttime.tv_sec)+ (stoptime.tv_usec-starttime.tv_usec); timings.push_back(elapsed); totaltime += elapsed; if ( timings.size() == 1 ) max = min = elapsed; else { if ( elapsed > max ) max = elapsed; if ( elapsed < min ) min = elapsed; } avg = totaltime / timings.size(); } #endif double Profile::getMax() const { return max; } double Profile::getMin() const { return min; } double Profile::getAvg() const { return avg; } double Profile::getTot() const { return totaltime; } size_t Profile::getNumTimings() const { return timings.size(); } Profiler::Profiler() { } Profiler::~Profiler() { map<string, Profile *>::const_iterator it; for ( it=profs.begin(); it != profs.end(); ++it ) { delete it->second; } } void Profiler::start(string name) { Profile *prof = get(name); prof->start(); } void Profiler::stop(string name) { map<string, Profile *>::iterator iter = profs.find(name); if ( iter == profs.end() ) cerr<<name<<": no such Profile started"; iter->second->stop(); } Profile * Profiler::get(string name) { Profile *prof; map<string, Profile *>::iterator iter = profs.find(name); if ( iter == profs.end() ) { prof = new Profile(name); profs.insert(pair<string, Profile *>(name, prof)); } else { prof = iter->second; } return prof; } Profiler * Profiler::instance() { static Profiler internal_profiler; return &internal_profiler; } ostream& operator<< (ostream &os, const Profile &prof) { os << " num:"<<prof.getNumTimings()<<" min:"<< prof.getMin()<<" max:"<<prof.getMax()<< " avg:"<<prof.getAvg()<<" tot:"<<prof.getTot()<< " ["<<prof.name<<"]"; return os; } ostream& operator<< (ostream &os, const Profiler &prof) { map<string, Profile *>::const_iterator it; for ( it=prof.profs.begin(); it != prof.profs.end(); ++it ) { os<<*(it->second)<<endl; } return os; } } // namespace geos.util } // namespace geos /********************************************************************** * $Log$ * Revision 1.10 2006/06/12 11:29:24 strk * unsigned int => size_t * * Revision 1.9 2006/03/07 14:18:34 strk * Profiler singleton implemented with a function-static Profiler instance * * Revision 1.8 2006/03/06 19:40:48 strk * geos::util namespace. New GeometryCollection::iterator interface, many cleanups. * * Revision 1.7 2006/03/03 10:46:22 strk * Removed 'using namespace' from headers, added missing headers in .cpp files, removed useless includes in headers (bug#46) * * Revision 1.6 2005/02/01 14:18:04 strk * Made profiler start/stop inline * * Revision 1.5 2005/02/01 13:44:59 strk * More profiling labels. * * Revision 1.4 2004/12/03 22:52:56 strk * enforced const return of CoordinateSequence::toVector() method to derivate classes. * * Revision 1.3 2004/11/08 12:15:35 strk * Added number of gathered timings in output. * * Revision 1.2 2004/11/08 11:19:39 strk * Profiler::get() always return a Profile (new if not existant). * * Revision 1.1 2004/11/01 16:43:04 strk * Added Profiler code. * Temporarly patched a bug in DoubleBits (must check drawbacks). * Various cleanups and speedups. * **********************************************************************/
20.492683
124
0.625089
[ "geometry" ]
2d47eb7a213293c775b077676f3054ba54d90d63
3,506
cpp
C++
Luogu/4180.cpp
miaowh/ICPC
c1f141ea005fb5d9582878e154c49f22b0f217ff
[ "MIT" ]
1
2021-10-03T07:25:22.000Z
2021-10-03T07:25:22.000Z
Luogu/4180.cpp
MiaoWH/ICPC
c1f141ea005fb5d9582878e154c49f22b0f217ff
[ "MIT" ]
null
null
null
Luogu/4180.cpp
MiaoWH/ICPC
c1f141ea005fb5d9582878e154c49f22b0f217ff
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; const int maxn = 4e5 + 5; using ll = long long; struct Edge { int u, v, w; bool operator<(const Edge &rhs) const { return w < rhs.w; } }; vector<Edge> edges; int n, m; struct LCT { int val[maxn], max[maxn], smax[maxn]; // 基于点权 int rev[maxn], ch[maxn][2], fa[maxn]; int stk[maxn]; inline bool isroot(int x) { return ch[fa[x]][0] != x && ch[fa[x]][1] != x; } inline bool get(int x) { return ch[fa[x]][1] == x; } inline void reverse(int x) { swap(ch[x][0], ch[x][1]); rev[x] ^= 1; } inline void pushdown(int x) { if (rev[x]) { if (ch[x][0]) reverse(ch[x][0]); if (ch[x][1]) reverse(ch[x][1]); rev[x] ^= 1; } } // 因为儿子可能会改变,因此每次必须重新计算 int tmp[10]; inline void pushup(int x) { int tot = 0; tmp[tot++] = val[x]; max[x] = val[x]; if (ch[x][0]) { tmp[tot++] = max[ch[x][0]]; tmp[tot++] = smax[ch[x][0]]; max[x] = std::max(max[x], max[ch[x][0]]); } if (ch[x][1]) { tmp[tot++] = max[ch[x][1]]; tmp[tot++] = smax[ch[x][1]]; max[x] = std::max(max[x], max[ch[x][1]]); } smax[x] = -1; for (int i = 0; i < tot; i++) if (tmp[i] < max[x] && tmp[i] > smax[x]) smax[x] = tmp[i]; } // 避免单独使用:不能直接旋转根 void rotate(int x) { int y = fa[x], z = fa[y], d = get(x); if (!isroot(y)) ch[z][get(y)] = x; fa[x] = z; ch[y][d] = ch[x][d ^ 1], fa[ch[y][d]] = y; ch[x][d ^ 1] = y, fa[y] = x; pushup(y), pushup(x); } // 将x旋转到Splay的根 void splay(int x) { int top = 0; stk[++top] = x; for (int i = x; !isroot(i); i = fa[i]) stk[++top] = fa[i]; for (int i = top; i; i--) pushdown(stk[i]); for (int f; !isroot(x); rotate(x)) if (!isroot(f = fa[x])) rotate(get(x) == get(f) ? f : x); } // 将根到x的路径拉到一棵Splay中 void access(int x) { for (int y = 0; x; y = x, x = fa[x]) splay(x), ch[x][1] = y, pushup(x); } // 让x成为原树的根,x为深度最低的点,其左子树为空 void makeroot(int x) { access(x), splay(x), reverse(x); } // 找x所在原树的根。主要用来判联通性,如果find(x) = find(y) // 则x,y在同一棵树中。 int find(int x) { access(x), splay(x); while (ch[x][0]) pushdown(x), x = ch[x][0]; splay(x); return x; } // 加边,y为深度最低的点(顺序无所谓) void link(int x, int y) { makeroot(x); fa[x] = y, splay(x); } // 将x到y的路径拉到一棵Splay中,y为Splay的根 void split(int x, int y) { makeroot(x), access(y), splay(y); } } lct; bool vis[maxn]; int par[maxn]; int find(int x) { return x == par[x] ? x : par[x] = find(par[x]); } inline void merge(int x, int y) { x = find(x); y = find(y); par[x] = y; } int main() { scanf("%d%d", &n, &m); for (int i = 1; i <= n; i++) par[i] = i; for (int i = 0, u, v, w; i < m; i++) { scanf("%d%d%d", &u, &v, &w); edges.push_back({u, v, w}); } sort(edges.begin(), edges.end()); int cnt = 0; ll tot = 0; for (int i = 0, u, v, w; i < m; i++) { u = edges[i].u; v = edges[i].v; w = edges[i].w; if (find(u) == find(v)) continue; merge(u, v); lct.link(u, i + 1 + n); lct.link(v, i + 1 + n); lct.val[i + 1 + n] = w; cnt++; tot += w; vis[i] = true; if (cnt == n - 1) break; } ll ans = 1e18; for (int i = 0, u, v, w; i < m; i++) { u = edges[i].u; v = edges[i].v; w = edges[i].w; if (vis[i]) continue; lct.split(u, v); ll tmp = tot - lct.max[v] + w; if (tmp != tot) ans = min(ans, tmp); tmp = tot - lct.smax[v] + w; if (tmp != tot) ans = min(ans, tmp); } printf("%lld\n", ans); }
24.517483
78
0.478893
[ "vector" ]
2d4a9e8f5e81dc18180410b45132a8d3feb68582
889
cpp
C++
322.cpp
adlternative/algorithm-Brush
0ad801ae519a0d1258faac364a8802e435397899
[ "Apache-2.0" ]
null
null
null
322.cpp
adlternative/algorithm-Brush
0ad801ae519a0d1258faac364a8802e435397899
[ "Apache-2.0" ]
null
null
null
322.cpp
adlternative/algorithm-Brush
0ad801ae519a0d1258faac364a8802e435397899
[ "Apache-2.0" ]
null
null
null
// // Created by adl on 2020/11/30. // #include<bits/stdc++.h> using namespace std; class Solution { public: int coinChange(vector<int> &coins, int amount) { if (amount == 0) { return 0; } else if (amount < 0) { return -1; } int size = coins.size(); vector<int> dp(amount + 1, INT_MAX); dp[0] = 0; for (int i = 1; i != amount + 1; ++i) { for (int j = 0; j != size; ++j) { int cnt = i - coins[j]; if (cnt < 0||dp[cnt]==INT_MAX) { continue; } dp[i] = min(dp[i], 1 + dp[cnt]); } } return dp[amount]==INT_MAX?-1:dp[amount]; } }; int main(int argc, char *argv[]) { Solution s; vector<int> v{3, 6, 13}; std::cout << s.coinChange(v, 14) << std::endl; return 0; }
22.225
52
0.434196
[ "vector" ]
2d4b68c28d18b6e02a0b2b6d2288ecffe17b3d3a
5,091
cc
C++
src/Battery.cc
NobodyXu/swaystatus
18d131631ac25a92a78630e033e89d751ebe3306
[ "MIT" ]
18
2021-02-16T09:06:42.000Z
2021-12-09T19:08:02.000Z
src/Battery.cc
NobodyXu/swaystatus
18d131631ac25a92a78630e033e89d751ebe3306
[ "MIT" ]
18
2021-02-23T06:46:22.000Z
2021-07-26T06:10:13.000Z
src/Battery.cc
NobodyXu/swaystatus
18d131631ac25a92a78630e033e89d751ebe3306
[ "MIT" ]
1
2021-07-27T03:14:48.000Z
2021-07-27T03:14:48.000Z
#ifndef _GNU_SOURCE # define _GNU_SOURCE /* For strchrnul, strcasestr */ #endif #include <cstddef> #include <cstring> #include <err.h> #include <fcntl.h> /* For O_RDONLY */ #include <unistd.h> /* For close, lseek and fstat */ #include <utility> #include "formatting/fmt/include/fmt/core.h" #include "utility.h" #include "formatting/fmt_utility.hpp" #include "Battery.hpp" namespace swaystatus { auto Battery::makeBattery(int path_fd, std::string_view device, std::string_view excluded_model) -> std::optional<Battery> { std::size_t device_name_len = device.size(); std::string path(device); path.reserve(device_name_len + 1 + sizeof("uevent")); path.append("/type"); int fd = openat_checked(power_supply_path, path_fd, path.c_str(), O_RDONLY); char type[sizeof("Battery")]; ssize_t bytes = readall(fd, type, sizeof(type) - 1); if (bytes < 0) err(1, "%s on %s%s failed", "readall", power_supply_path, path.c_str()); if (bytes == 0) errx(1, "%s on %s%s failed", "Assumption", power_supply_path, path.c_str()); type[bytes] = '\0'; close(fd); if (std::strncmp("Battery", type, sizeof("Battery") - 1) != 0) return {std::nullopt}; path.resize(device_name_len); auto battery = Battery{path_fd, std::move(path)}; battery.read_battery_uevent(); if (battery.get_property("model_name") == excluded_model) return std::nullopt; return battery; } Battery::Battery(int path_fd, std::string &&device): battery_device{std::move(device)} { auto device_sz = battery_device.size(); auto &buffer = battery_device; buffer.append("/uevent"); uevent_fd = openat_checked(power_supply_path, path_fd, buffer.c_str(), O_RDONLY); battery_device.resize(device_sz); battery_device.shrink_to_fit(); } void Battery::read_battery_uevent() { buffer.clear(); ssize_t cnt = asreadall(uevent_fd.get(), buffer); if (cnt < 0) err(1, "%s on %s%s/%s failed", "read", power_supply_path, battery_device.c_str(), "uevent"); if (lseek(uevent_fd.get(), 0, SEEK_SET) == static_cast<off_t>(-1)) err(1, "%s on %s%s/%s failed", "lseek", power_supply_path, battery_device.c_str(), "uevent"); } auto Battery::get_property(std::string_view name) const noexcept -> std::string_view { if (!uevent_fd) return {}; std::size_t name_len = name.size(); char *substr = const_cast<char*>(buffer.c_str()); for (; ;) { substr = strcasestr(substr, name.data()); if (!substr) return "nullptr"; if (substr[name_len] == '=') break; substr += name_len; } const char *value = substr + name_len + 1; const char *end = strchrnul(substr, '\n'); return {value, static_cast<std::size_t>(end - value)}; } } /* namespace swaystatus */ using Batteries_formatter = fmt::formatter<std::vector<swaystatus::Battery>>; auto Batteries_formatter::parse(format_parse_context &ctx) -> format_parse_context_it { auto it = ctx.begin(), end = ctx.end(); if (it == end) return it; end = swaystatus::find_end_of_format(ctx); fmt_str = std::string_view{it, static_cast<std::size_t>(end - it)}; return end; } auto Batteries_formatter::format(const Batteries &batteries, format_context &ctx) -> format_context_it { auto out = ctx.out(); if (fmt_str.size() == 0) return out; for (const swaystatus::Battery &battery: batteries) { auto get_bat_property_lazy = [&battery](std::string_view name) noexcept { return swaystatus::LazyEval{[&battery, name]() noexcept { return battery.get_property(name); }}; }; auto get_conditional_lazy = [&battery](std::string_view name, std::string_view val) noexcept { return swaystatus::LazyEval{[&battery, name, val]() noexcept { return swaystatus::Conditional{battery.get_property(name) == val}; }}; }; out = format_to( out, fmt_str, fmt::arg("type", "battery"), #define ARG(literal) fmt::arg((literal), get_bat_property_lazy(literal)) ARG("name"), ARG("present"), ARG("technology"), ARG("model_name"), ARG("manufacturer"), ARG("serial_number"), ARG("status"), ARG("cycle_count"), ARG("voltage_min_design"), ARG("voltage_now"), ARG("charge_full_design"), ARG("charge_full"), ARG("charge_now"), ARG("capacity"), ARG("capacity_level"), #undef ARG fmt::arg("is_charging", get_conditional_lazy("status", "Charging")), fmt::arg("is_discharging", get_conditional_lazy("status", "Discharging")), fmt::arg("is_not_charging", get_conditional_lazy("status", "Not charging")), fmt::arg("is_full", get_conditional_lazy("status", "Full")) ); } return out; }
27.518919
101
0.605775
[ "vector" ]
2d536c570f782282e3a804ac1897b4e057d38efe
14,363
hpp
C++
bench/diffusion/diffusion.hpp
frRoy/Numerical
97e2167cf794eceaeba395bb1958fee72d8cbecf
[ "MIT" ]
null
null
null
bench/diffusion/diffusion.hpp
frRoy/Numerical
97e2167cf794eceaeba395bb1958fee72d8cbecf
[ "MIT" ]
null
null
null
bench/diffusion/diffusion.hpp
frRoy/Numerical
97e2167cf794eceaeba395bb1958fee72d8cbecf
[ "MIT" ]
null
null
null
/** * @file diffusion.hpp * @brief Collections of diffusion problem, definitions. * @author Francois Roy * @date 12/01/2019 */ #ifndef DIFFUSION_H #define DIFFUSION_H #include <string> #include <Eigen/Core> #include "spdlog/spdlog.h" #include "numerical/fdm/fdm.hpp" namespace bench{ namespace diffusion{ typedef Eigen::VectorXd Vec; typedef Eigen::ArrayXd Arr; /** * Computes the 1D diffusion problem defined in @ref FDMDiffusionA::reference() * using the finite difference method and computes the L2-norm of the error * between the exact and computed solution. * * @return The L2-norm of the error between the computed and exact solution. * @see numerical::fdm::Parameters * @see numerical::fdm::FDMesh * @see numerical::fdm::SparseSolver */ double fdm_diffusion_a(); /** * Computes the 1D diffusion problem defined in @ref FDMDiffusionB::reference() * using the finite difference method and computes the L2-norm of the error * between the exact and computed solution. * * @return The L2-norm of the error between the computed and exact solution. * @see numerical::fdm::Parameters * @see numerical::fdm::FDMesh * @see numerical::fdm::SparseSolver */ double fdm_diffusion_b(); /** * Computes the 1D diffusion problem defined in @ref FDMDiffusionC::reference() * using the finite difference method and computes the L2-norm of the error * between the exact and computed solution. * * @return The L2-norm of the error between the computed and exact solution. * @see numerical::fdm::Parameters * @see numerical::fdm::FDMesh * @see numerical::fdm::SparseSolver */ double fdm_diffusion_c(); /** * Computes the 1D diffusion problem defined in @ref FDMDiffusionD::reference() * using the finite difference method and computes the L2-norm of the error * between the exact and computed solution. * * @return The L2-norm of the error between the computed and exact solution. * @see numerical::fdm::Parameters * @see numerical::fdm::FDMesh * @see numerical::fdm::SparseSolver */ double fdm_diffusion_d(); /** * Computes the 1D diffusion problem defined in @ref FDMDiffusionE::reference() * using the finite difference method and computes the L2-norm of the error * between the exact and computed solution. * * @return The L2-norm of the error between the computed and exact solution. * @see numerical::fdm::Parameters * @see numerical::fdm::FDMesh * @see numerical::fdm::SparseSolver */ double fdm_diffusion_e(); /** * This class provides tools to compute the finite difference problem * defined in @ref FDMDiffusionA::reference(). * * The class is derived form the @ref numerical::fdm::FDProblem class and * overrides the member function @ref numerical::fdm::FDProblem::left(), * @ref numerical::fdm::FDProblem::right(), * @ref numerical::fdm::FDProblem::initial_value(), * @ref numerical::fdm::FDProblem::source(), and * @ref numerical::fdm::FDProblem::reference(). */ class FDMDiffusionA : public numerical::fdm::Problem<double>{ public: FDMDiffusionA(numerical::fdm::Parameters<double>* p): numerical::fdm::Problem<double>(p){ } double left(double y, double z, double t); double right(double y, double z, double t); double source(const Eigen::Matrix<double, 3, 1>& x, double t); /** * Reference solution for the 1D diffusion problem a, defined as: * * \f[ * \frac{\partial u}{\partial t} = \alpha \frac{\partial^2 u} * {\partial x^2} * + f(x,t)\quad x \in (0, L),~t \in (0, T] * \f] * * with homogeneous Dirichlet boundary condition \f$u(0, t) = 0\f$ and * \f$ u(L, t) = 0\f$ for \f$t>0\f$. * * The diffusion coefficient, \f$ \alpha(L, t)\f$ is constant and * uniform over the interval (line). * * We define the source term and initial condition with a reference * (manufactured) solution that respects the boundary conditions at the * extremities of the interval: * * \f[ * u(x, t) = 5tx\left(L-x\right) * \f] * * We get the source term substituting the manufactured solution in the * diffusion equation, i.e.: * * \f[ * f(x, t) = 5x\left(L-x\right)+10\alpha t * \f] * * The initial condition is simply set to the manufactured solution at * \f$t=0\f$: * * \f[ * u(x, 0) = u_0 = 0 * \f] * * @param x The spatial mesh node coordinates. * @param t The temporal mesh node. * @return The reference solution. */ double reference(const Eigen::Matrix<double, 3, 1>& x, double t); }; /** * This class provides tools to compute the finite difference problem * defined in @ref FDMDiffusionB::reference(). * * The class is derived form the @ref numerical::fdm::FDProblem class and * overrides the member function @ref numerical::fdm::FDProblem::left(), * @ref numerical::fdm::FDProblem::right(), * @ref numerical::fdm::FDProblem::initial_value(), * @ref numerical::fdm::FDProblem::source(), and * @ref numerical::fdm::FDProblem::reference(). */ class FDMDiffusionB : public numerical::fdm::Problem<double>{ public: FDMDiffusionB(numerical::fdm::Parameters<double>* p): numerical::fdm::Problem<double>(p){ } double left(double y, double z, double t); double right(double y, double z, double t); double source(const Eigen::Matrix<double, 3, 1>& x, double t); /** * Reference solution for the 1D diffusion problem b, defined as: * * \f[ * \frac{\partial u}{\partial t} = \alpha \frac{\partial^2 u} * {\partial x^2} * + f(x,t)\quad x \in (0, L),~t \in (0, T] * \f] * * with homogeneous Neumann boundary condition * \f$\left. \frac{\partial}{\partial x}u(x, t)\right|_{x=0} = 0\f$ and * \f$\left. \frac{\partial}{\partial x}u(x, t)\right|_{x=L} = 0\f$. * * The diffusion coefficient, \f$ \alpha(L, t)\f$ is constant and * uniform over the interval (line). * * We define the source term and initial condition with a reference * (manufactured) solution that respects the boundary conditions at the * extremities of the interval: * * \f[ * \frac{\partial}{\partial x}u(x, t) = 5tx\left(L-x\right) * \f] * * which leads to * * \f[ * u(x, t) = 5tx\left(\frac{Lx}{2}-\frac{x^2}{3}\right) * \f] * * We get the source term substituting the manufactured solution in the * diffusion equation, i.e.: * * \f[ * f(x, t) = 5x\left(\frac{Lx}{2}-\frac{x^2}{3}\right)- * 5\alpha t\left(L-2x\right) * \f] * * The initial condition is simply set to the manufactured solution at * \f$t=0\f$: * * \f[ * u(x, 0) = u_0 = 0 * \f] * * @param x The spatial mesh node coordinates. * @param t The temporal mesh node. * @return The reference solution. */ double reference(const Eigen::Matrix<double, 3, 1>& x, double t); }; /** * This class provides tools to compute the finite difference problem * defined in @ref FDMDiffusionC::reference(). * * The class is derived form the @ref numerical::fdm::FDProblem class and * overrides the member function @ref numerical::fdm::FDProblem::left(), * @ref numerical::fdm::FDProblem::right(), * @ref numerical::fdm::FDProblem::initial_value(), * @ref numerical::fdm::FDProblem::source(), and * @ref numerical::fdm::FDProblem::reference(). */ class FDMDiffusionC : public numerical::fdm::Problem<double>{ public: FDMDiffusionC(numerical::fdm::Parameters<double>* p): numerical::fdm::Problem<double>(p){ } double left(double y, double z, double t); double right(double y, double z, double t); double source(const Eigen::Matrix<double, 3, 1>& x, double t); /** * Reference solution for the 1D diffusion problem c, defined as: * * \f[ * \frac{\partial u}{\partial t} = \alpha \frac{\partial^2 u} * {\partial x^2} * + f(x,t)\quad x \in (0, L),~t \in (0, T] * \f] * * with non-homogeneous Neumann boundary condition * \f$\mathbf{\hat{n}}\cdot\left. \frac{\partial}{\partial x} * u(x, t)\right|_{x=0} = -5tL\f$ and * \f$\mathbf{\hat{n}}\cdot\left. \frac{\partial}{\partial x} * u(x, t)\right|_{x=L} = -5tL\f$. * * The diffusion coefficient, \f$ \alpha(L, t)\f$ is constant and * uniform over the interval (line). * * We define the source term and initial condition with a reference * (manufactured) solution that respects the boundary conditions at the * extremities of the interval: * * \f[ * \frac{\partial}{\partial x}u(x, t) = 5t\left(L-2x\right) * \f] * * which leads to * * \f[ * u(x, t) = 5tx\left(L-x\right) * \f] * * We get the source term substituting the manufactured solution in the * diffusion equation, i.e.: * * \f[ * f(x, t) = 5x\left(L-x\right)+10\alpha t * \f] * * The initial condition is simply set to the manufactured solution at * \f$t=0\f$: * * \f[ * u(x, 0) = u_0 = 0 * \f] * * @param x The spatial mesh node coordinates. * @param t The temporal mesh node. * @return The reference solution. */ double reference(const Eigen::Matrix<double, 3, 1>& x, double t); }; /** * This class provides tools to compute the finite difference problem * defined in @ref FDMDiffusionD::reference(). * * The class is derived form the @ref numerical::fdm::FDProblem class and * overrides the member function @ref numerical::fdm::FDProblem::left(), * @ref numerical::fdm::FDProblem::right(), * @ref numerical::fdm::FDProblem::initial_value(), * @ref numerical::fdm::FDProblem::source(), and * @ref numerical::fdm::FDProblem::reference(). */ class FDMDiffusionD : public numerical::fdm::Problem<double>{ public: FDMDiffusionD(numerical::fdm::Parameters<double>* p): numerical::fdm::Problem<double>(p){ } double left(double y, double z, double t); double right(double y, double z, double t); double source(const Eigen::Matrix<double, 3, 1>& x, double t); /** * Reference solution for the 1D diffusion problem d, defined as: * * \f[ * \frac{\partial u}{\partial t} = \alpha \frac{\partial^2 u} * {\partial x^2} * + f(x,t)\quad x \in (0, L),~t \in (0, T] * \f] * * with non-homogeneous Dirichlet boundary condition * \f$u(0, t) = 5tL^2/4\f$ and * \f$\mathbf{\hat{n}}\cdot\left. \alpha(u)\frac{\partial}{\partial x} * u(x, t)\right|_{x=L} = g\f$. * * The diffusion coefficient, \f$ \alpha(u)=u\f$. * * We define the source term and initial condition with a reference * (manufactured) solution that respects the boundary conditions at the * extremities of the interval: * * \f[ * u(x, t) = 5t\left(x-\frac{L}{2}\right)^2 * \f] * * We get the source term substituting the manufactured solution in the * diffusion equation, i.e.: * * \f[ * f(x, t) = 5\left(x-\frac{L}{2}\right)^2- * 10\alpha t * \f] * * The initial condition is simply set to the manufactured solution at * \f$t=0\f$: * * \f[ * u(x, 0) = u_0 = 0 * \f] * * @param x The spatial mesh node coordinates. * @param t The temporal mesh node. * @return The reference solution. */ double reference(const Eigen::Matrix<double, 3, 1>& x, double t); }; /** * This class provides tools to compute the finite difference problem * defined in @ref FDMDiffusionE::reference(). * * The class is derived form the @ref numerical::fdm::FDProblem class and * overrides the member function @ref numerical::fdm::FDProblem::left(), * @ref numerical::fdm::FDProblem::right(), * @ref numerical::fdm::FDProblem::initial_value(), * @ref numerical::fdm::FDProblem::source(), and * @ref numerical::fdm::FDProblem::reference(). */ class FDMDiffusionE : public numerical::fdm::Problem<double>{ public: FDMDiffusionE(numerical::fdm::Parameters<double>* p): numerical::fdm::Problem<double>(p){ } double left(double y, double z, double t); double right(double y, double z, double t); double source(const Eigen::Matrix<double, 3, 1>& x, double t); /** * Reference solution for the nonlinear 1D diffusion problem e, defined as: * * \f[ * \frac{\partial u}{\partial t} = \frac{\partial}{\partial x} * \left(\alpha(u)\frac{\partial u}{\partial x}\right) * + f(x,t)\quad x \in (0, L),~t \in (0, T] * \f] * * with non-homogeneous mixed Dirichlet/Neumann boundary conditions * \f$u(0, t) = u_D\f$ and \f$u(L, t)= 5tL^2/4\f$. * * The diffusion coefficient, \f$ \alpha(L, t)\f$ is constant and * uniform over the interval (line). * * We define the source term and initial condition with a reference * (manufactured) solution that respects the boundary conditions at the * extremities of the interval: * * \f[ * u(x, t) = 5t\left(x-\frac{L}{2}\right)^2 * \f] * * We get the source term substituting the manufactured solution in the * diffusion equation, i.e.: * * \f[ * f(x, t) = 5\left(x-\frac{L}{2}\right)^2- * 10\alpha t * \f] * * The initial condition is simply set to the manufactured solution at * \f$t=0\f$: * * \f[ * u(x, 0) = u_0 = 0 * \f] * * @param x The spatial mesh node coordinates. * @param t The temporal mesh node. * @return The reference solution. */ double reference(const Eigen::Matrix<double, 3, 1>& x, double t); }; } // namespace diffusion } // namespace bench #endif // DIFFUSION_H
34.526442
80
0.599248
[ "mesh" ]
2d541b599f54718a855e4c9a75d8cb5cf5f0df9b
1,893
cpp
C++
Service_lane.cpp
power-factory/hackerrank
a0f6c6a40a1eff4f0430fd866061378ebd2b5204
[ "MIT" ]
null
null
null
Service_lane.cpp
power-factory/hackerrank
a0f6c6a40a1eff4f0430fd866061378ebd2b5204
[ "MIT" ]
null
null
null
Service_lane.cpp
power-factory/hackerrank
a0f6c6a40a1eff4f0430fd866061378ebd2b5204
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; string ltrim(const string &); string rtrim(const string &); vector<string> split(const string &); /* * Complete the 'serviceLane' function below. * * The function is expected to return an INTEGER_ARRAY. * The function accepts following parameters: * 1. INTEGER n * 2. 2D_INTEGER_ARRAY cases */ // This was tricky challange for me. It is due to fact that function description is wrong. // Multiple people reported not pasing "width" as function argument. I modified it! vector<int> serviceLane(int n, vector<int> width, vector<vector<int>> cases) { std::vector<int> maximumVehicleWidth; for (auto pair : cases) { int enterIndex = pair[0]; int exitIndex = pair[1]; auto vehicleWidth = *std::min_element(width.begin() + enterIndex, width.begin() + exitIndex+1); maximumVehicleWidth.push_back(vehicleWidth); } return maximumVehicleWidth; } int main() { int n = 5; int t{5}; vector<int> width = {1, 2, 2, 2, 1}; vector<vector<int>> cases = {{2, 3}, {1, 4}, {2, 4}, {2, 4}, {2, 3}}; vector<int> result = serviceLane(n, width, cases); return 0; } string ltrim(const string &str) { string s(str); s.erase( s.begin(), find_if(s.begin(), s.end(), not1(ptr_fun<int, int>(isspace)))); return s; } string rtrim(const string &str) { string s(str); s.erase( find_if(s.rbegin(), s.rend(), not1(ptr_fun<int, int>(isspace))).base(), s.end()); return s; } vector<string> split(const string &str) { vector<string> tokens; string::size_type start = 0; string::size_type end = 0; while ((end = str.find(" ", start)) != string::npos) { tokens.push_back(str.substr(start, end - start)); start = end + 1; } tokens.push_back(str.substr(start)); return tokens; }
21.511364
103
0.619123
[ "vector" ]
2d5ab43dd005ea8bbbd88bb84f0febb3684c29ee
13,779
cpp
C++
002.cpp
Mateorid/BI-PA2
0f77d20f061f1cad2829a2401c8891a63333629d
[ "MIT" ]
null
null
null
002.cpp
Mateorid/BI-PA2
0f77d20f061f1cad2829a2401c8891a63333629d
[ "MIT" ]
null
null
null
002.cpp
Mateorid/BI-PA2
0f77d20f061f1cad2829a2401c8891a63333629d
[ "MIT" ]
null
null
null
#ifndef __PROGTEST__ #include <cstdio> #include <cstdlib> #include <cmath> #include <cassert> #include <cstring> #include <iostream> #include <iomanip> #include <string> #include <utility> #include <vector> #include <memory> #include <functional> #include <stdexcept> #include <algorithm> using namespace std; #endif /* __PROGTEST__ */ /**Used to define the action certain methods(findAccount, findHuman will execute.*/ enum class actionType { BIRTH, DEATH, INCOME, EXPENSE, AUDIT }; class CHuman { private: string name = {}; string address = {}; string account = {}; public: int totalIncome = 0; int totalExpenses = 0; /** * Creates new instance of CHuman with given name, address and account. * @param name CHuman name * @param address CHuman address * @param account CHuman account */ CHuman(string name, string address, string account); ~CHuman() = default; string getName() const { return name; } string getAddress() const { return address; } string getAccount() const { return account; } /** @return true if CHuman "a" is before CHuman "b" based on name and then address, otherwise returns false.*/ friend bool operator<(const CHuman &a, const CHuman &b); }; CHuman::CHuman(string name, string address, string account) : name(move(name)), address(move(address)), account(move(account)) {} bool operator<(const CHuman &a, const CHuman &b) { int cmp = a.getName().compare(b.getName()); if (cmp == 0) { return a.getAddress() < b.getAddress(); } return cmp < 0; } class CIterator { private: uint16_t it = 0; vector<CHuman> humans; public: /** * Constructor * @param srcHumans vector<CHuman> to create iterator for */ explicit CIterator(vector<CHuman> &srcHumans) : humans(srcHumans) {} ~CIterator() = default; /** @return true if iterator reached end of vector*/ bool AtEnd() const { return humans.size() == it; } void Next() { it++; } string Name() const { return humans.at(it).getName(); } string Addr() const { return humans.at(it).getAddress(); } string Account() const { return humans.at(it).getAccount(); } }; class CTaxRegister { private: vector<CHuman> humans; /**Iterator used in find human method*/ vector<CHuman>::iterator it; /** * Finds out if CHuman on position has same name and address as the ones given in the input * @param position of the human in vector<CHuman> * @param name to check for equality * @param addr to check for equality * @return true if the person on given position has the same name and address otherwise returns false */ bool identicalCheck(vector<CHuman>::iterator position, const string &name, const string &addr) const; /** * Iterates through our human vector and uses identicalCheck to find desired human and depending on the type parameter * certain actions will be made. * @param account account name * @param amount amount to be added to totalIncome/totalExpenses, only used in type (INCOME/EXPENSE) * @param type specifies type of action to be made from actionType * @return true if account was found otherwise returns false */ bool findAccount(const string &account, int amount, actionType type); /** * Creates a temporary CHuman to store input info in and then uses lower_bound function to find the position of said * CHuman in our vector<CHuman>. It also does certain actions depending on the type parameter, that varies depending * on in which method it was called. * @param name CHuman name * @param address CHuman address * @param account CHuman account * @param type specifies which action should be made, depends on in which method its called * @param amount amount to be added to totalIncome/totalExpenses, only used in type (INCOME/EXPENSE) * @param iterator only used when type is AUDIT. It's set to the position of the tmp CHuman * @return true on success, otherwise returns false. (Details depend on the type of action) */ bool findHuman(const string &name, const string &address, const string &account, actionType type, int amount, vector<CHuman>::iterator &iterator); public: CTaxRegister() = default; ~CTaxRegister() = default; /**Birth & Death are inspired by J. Matousek's stream (https://www.twitch.tv/honzamatousek, https://www.youtube.com/channel/UCaOKhMQTuBscw4zKQwdA4Qg/videos)*/ /** * Creates and inserts new CHuman in humans vector * @param name CHuman name * @param address CHuman address * @param account CHuman account * @return true on success, otherwise returns false */ bool Birth(const string &name, const string &addr, const string &account); /** * Removes CHuman from humans vector, given its name and address * @param name CHuman name * @param address CHuman address * @return true on success, otherwise returns false */ bool Death(const string &name, const string &addr); /** * Increase totalIncome on given account * @param account account name * @param amount amount to add * @return true on success, otherwise returns false */ bool Income(const string &account, int amount); /** * Increase totalIncome of given CHuman * @param name name of CHuman * @param addr address of CHuman * @param amount to add * @return true on success, otherwise returns false */ bool Income(const string &name, const string &addr, int amount); /** * Increase totalExpense on given account * @param account account name * @param amount amount to add * @return true on success, otherwise returns false */ bool Expense(const string &account, int amount); /** * Increase totalExpense of given CHuman * @param name name of CHuman * @param addr address of CHuman * @param amount to add * @return true on success, otherwise returns false */ bool Expense(const string &name, const string &addr, int amount); /** * Finds CHuman with given name & address. Saves all his account details to input parameters(account, income sum and expenses sum) * @param name CHuman name * @param addr CHuman address * @param account name * @param sumIncome sum of all incomes * @param sumExpense sum of all expenses * @return true on success, otherwise returns false */ bool Audit(const string &name, const string &addr, string &account, int &sumIncome, int &sumExpense); /** * Used to iterate through our CHuman ector * @return CIterator instance */ CIterator ListByName() const; }; bool CTaxRegister::Birth(const string &name, const string &addr, const string &account) { //Checking for duplicate account name if (findAccount(account, 0, actionType::BIRTH)) { return false; } return findHuman(name, addr, account, actionType::BIRTH, 0, it); } bool CTaxRegister::Death(const string &name, const string &addr) { return findHuman(name, addr, "", actionType::DEATH, 0, it); } bool CTaxRegister::Income(const string &account, int amount) { return findAccount(account, amount, actionType::INCOME); } bool CTaxRegister::Income(const string &name, const string &addr, int amount) { return findHuman(name, addr, "", actionType::INCOME, amount, it); } bool CTaxRegister::Expense(const string &account, int amount) { return findAccount(account, amount, actionType::EXPENSE); } bool CTaxRegister::Expense(const string &name, const string &addr, int amount) { return findHuman(name, addr, "", actionType::EXPENSE, amount, it); } bool CTaxRegister::Audit(const string &name, const string &addr, string &account, int &sumIncome, int &sumExpense) { //Creating tmpHuman to store and check info if (findHuman(name, addr, "", actionType::AUDIT, 0, it)) { account = it->getAccount(); sumIncome = it->totalIncome; sumExpense = it->totalExpenses; return true; } return false; } CIterator CTaxRegister::ListByName() const { auto iter = CIterator((vector<struct CHuman> &) humans); return iter; } bool CTaxRegister::identicalCheck(vector<CHuman>::iterator position, const string &name, const string &addr) const { if (position != humans.end()) { if (position->getName() == name && position->getAddress() == addr) { return true; } } return false; } bool CTaxRegister::findAccount(const string &account, int amount, actionType type) { for (auto &i : humans) { if (i.getAccount() == account) { switch (type) { case actionType::BIRTH: break; case actionType::INCOME: i.totalIncome += amount; break; case actionType::EXPENSE: i.totalExpenses += amount; break; default: break; } return true; } } return false; } bool CTaxRegister::findHuman(const string &name, const string &address, const string &account, actionType type, int amount, vector<CHuman>::iterator &iterator) { auto *tmpHuman = new CHuman(name, address, account); auto position = lower_bound(humans.begin(), humans.end(), *tmpHuman); bool identical = identicalCheck(position, name, address); switch (type) { case actionType::BIRTH: if (!identical) humans.insert(position, *tmpHuman); delete tmpHuman; return !identical; case actionType::DEATH: if (identical) humans.erase(position); delete tmpHuman; return identical; case actionType::INCOME: if (identical) position->totalIncome += amount; delete tmpHuman; return identical; case actionType::EXPENSE: if (identical) position->totalExpenses += amount; delete tmpHuman; return identical; case actionType::AUDIT: if (identical) iterator = position; delete tmpHuman; return identical; default: return false; } } #ifndef __PROGTEST__ int main() { string acct; int sumIncome, sumExpense; CTaxRegister b1; assert (b1.Birth("John Smith", "Oak Road 23", "123/456/789")); assert (b1.Birth("Jane Hacker", "Main Street 17", "Xuj5#94")); assert (b1.Birth("Peter Hacker", "Main Street 17", "634oddT")); assert (b1.Birth("John Smith", "Main Street 17", "Z343rwZ")); assert (b1.Income("Xuj5#94", 1000)); assert (b1.Income("634oddT", 2000)); assert (b1.Income("123/456/789", 3000)); assert (b1.Income("634oddT", 4000)); assert (b1.Income("Peter Hacker", "Main Street 17", 2000)); assert (b1.Expense("Jane Hacker", "Main Street 17", 2000)); assert (b1.Expense("John Smith", "Main Street 17", 500)); assert (b1.Expense("Jane Hacker", "Main Street 17", 1000)); assert (b1.Expense("Xuj5#94", 1300)); assert (b1.Audit("John Smith", "Oak Road 23", acct, sumIncome, sumExpense)); assert (acct == "123/456/789"); assert (sumIncome == 3000); assert (sumExpense == 0); assert (b1.Audit("Jane Hacker", "Main Street 17", acct, sumIncome, sumExpense)); assert (acct == "Xuj5#94"); assert (sumIncome == 1000); assert (sumExpense == 4300); assert (b1.Audit("Peter Hacker", "Main Street 17", acct, sumIncome, sumExpense)); assert (acct == "634oddT"); assert (sumIncome == 8000); assert (sumExpense == 0); assert (b1.Audit("John Smith", "Main Street 17", acct, sumIncome, sumExpense)); assert (acct == "Z343rwZ"); assert (sumIncome == 0); assert (sumExpense == 500); CIterator it = b1.ListByName(); assert (!it.AtEnd() && it.Name() == "Jane Hacker" && it.Addr() == "Main Street 17" && it.Account() == "Xuj5#94"); it.Next(); assert (!it.AtEnd() && it.Name() == "John Smith" && it.Addr() == "Main Street 17" && it.Account() == "Z343rwZ"); it.Next(); assert (!it.AtEnd() && it.Name() == "John Smith" && it.Addr() == "Oak Road 23" && it.Account() == "123/456/789"); it.Next(); assert (!it.AtEnd() && it.Name() == "Peter Hacker" && it.Addr() == "Main Street 17" && it.Account() == "634oddT"); it.Next(); assert (it.AtEnd()); assert (b1.Death("John Smith", "Main Street 17")); CTaxRegister b2; assert (b2.Birth("John Smith", "Oak Road 23", "123/456/789")); assert (b2.Birth("Jane Hacker", "Main Street 17", "Xuj5#94")); assert (!b2.Income("634oddT", 4000)); assert (!b2.Expense("John Smith", "Main Street 18", 500)); assert (!b2.Audit("John Nowak", "Second Street 23", acct, sumIncome, sumExpense)); assert (!b2.Death("Peter Nowak", "5-th Avenue")); assert (!b2.Birth("Jane Hacker", "Main Street 17", "4et689A")); assert (!b2.Birth("Joe Hacker", "Elm Street 23", "Xuj5#94")); assert (b2.Death("Jane Hacker", "Main Street 17")); assert (b2.Birth("Joe Hacker", "Elm Street 23", "Xuj5#94")); assert (b2.Audit("Joe Hacker", "Elm Street 23", acct, sumIncome, sumExpense)); assert (acct == "Xuj5#94"); assert (sumIncome == 0); assert (sumExpense == 0); assert (!b2.Birth("Joe Hacker", "Elm Street 23", "AAj5#94")); return 0; } #endif /* __PROGTEST__ */
33.938424
162
0.625735
[ "vector" ]
2d5d084a2458192e9ddd7f501219d9039292e80b
7,342
cc
C++
software/cpp/test/parquetwriter_test.cc
fnonnenmacher/fast-p2a
e76d604b642794670e544f617b1549baf76266ec
[ "Apache-2.0" ]
1
2021-12-18T22:32:48.000Z
2021-12-18T22:32:48.000Z
software/cpp/test/parquetwriter_test.cc
fnonnenmacher/fast-p2a
e76d604b642794670e544f617b1549baf76266ec
[ "Apache-2.0" ]
6
2021-08-20T12:27:26.000Z
2021-08-31T16:01:24.000Z
software/cpp/test/parquetwriter_test.cc
fnonnenmacher/fast-p2a
e76d604b642794670e544f617b1549baf76266ec
[ "Apache-2.0" ]
2
2020-06-08T16:48:40.000Z
2021-08-31T16:20:04.000Z
// 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 <arrow/array/builder_binary.h> #include <arrow/array/builder_primitive.h> #include <arrow/io/file.h> #include <arrow/memory_pool.h> #include <arrow/result.h> #include <arrow/status.h> #include <arrow/table.h> #include <arrow/type.h> #include <arrow/util/compression.h> #include <parquet/arrow/writer.h> #include <parquet/exception.h> #include <parquet/properties.h> #include <parquet/types.h> #include <climits> #include <cstdio> #include <cstdlib> #include <cstring> #include <iostream> #include <memory> #include <string> #include <vector> #include <cmath> #define NAMEBUFSIZE 64 std::string gen_random_string(const int length) { static const char alphanum[] = "0123456789" "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "abcdefghijklmnopqrstuvwxyz"; std::string result(length, 0); for (int i = 0; i < length; ++i) { result[i] = alphanum[rand() % (sizeof(alphanum) - 1)]; } return result; } std::shared_ptr<arrow::Table> generate_int64_table(int num_values, int nCols, bool deltaVaried) { //Create the schema std::vector<std::shared_ptr<arrow::Field>> fields; for (int c = 0; c < nCols; c++) { char name[NAMEBUFSIZE]; snprintf(name, NAMEBUFSIZE, "int%d", c); fields.push_back(arrow::field(name, arrow::int64(), false)); } std::shared_ptr<arrow::Schema> schema = arrow::schema(fields); //Generate the values std::vector<std::shared_ptr<arrow::Array>> arrays; for (int c = 0; c < nCols; c++) { arrow::Int64Builder i64builder; long modulo = std::pow(2, (rand() % 63)); for (int i = 0; i < num_values; i++) { long number; if (deltaVaried) { number = (((long)rand() << 32) | rand()) % modulo; if ((i % 256) == 0) { modulo = std::pow(2, (rand() % 63)); } } else { number = ((long)rand() << 32) | rand(); } PARQUET_THROW_NOT_OK(i64builder.Append(number)); } std::shared_ptr<arrow::Array> i64array; PARQUET_THROW_NOT_OK(i64builder.Finish(&i64array)); arrays.push_back(i64array); } return arrow::Table::Make(schema, arrays); } std::shared_ptr<arrow::Table> generate_int32_table(int num_values, int nCols, bool deltaVaried) { //Create the schema std::vector<std::shared_ptr<arrow::Field>> fields; for (int c = 0; c < nCols; c++) { char name[NAMEBUFSIZE]; snprintf(name, NAMEBUFSIZE, "int%d", c); fields.push_back(arrow::field(name, arrow::int32(), false)); } std::shared_ptr<arrow::Schema> schema = arrow::schema(fields); //Generate the values std::vector<std::shared_ptr<arrow::Array>> arrays; for (int c = 0; c < nCols; c++) { arrow::Int32Builder i32builder; long modulo = std::pow(2, (rand() % 31)); for (int i = 0; i < num_values; i++) { long number; if (deltaVaried) { number = rand() % modulo; if ((i % 256) == 0) { modulo = std::pow(2, (rand() % 31)); } } else { number = rand(); } PARQUET_THROW_NOT_OK(i32builder.Append(number)); } std::shared_ptr<arrow::Array> i32array; PARQUET_THROW_NOT_OK(i32builder.Finish(&i32array)); arrays.push_back(i32array); } return arrow::Table::Make(schema, arrays); } std::shared_ptr<arrow::Table> generate_str_table(int num_values, int nCols, int min_length, int max_length) { //Create the schema std::vector<std::shared_ptr<arrow::Field>> fields; for (int c = 0; c < nCols; c++) { char name[NAMEBUFSIZE]; snprintf(name, NAMEBUFSIZE, "str%d", c); fields.push_back(arrow::field(name, arrow::utf8(), false)); } std::shared_ptr<arrow::Schema> schema = arrow::schema(fields); //Generate the values std::vector<std::shared_ptr<arrow::Array>> arrays; for (int c = 0; c < nCols; c++) { arrow::StringBuilder strbuilder; for (int i = 0; i < num_values; i++) { int length = rand() % (max_length - min_length + 1) + min_length; PARQUET_THROW_NOT_OK(strbuilder.Append(gen_random_string(length))); } std::shared_ptr<arrow::Array> strarray; PARQUET_THROW_NOT_OK(strbuilder.Finish(&strarray)); arrays.push_back(strarray); } return arrow::Table::Make(schema, arrays); } void write_parquet(std::shared_ptr<arrow::Table> table, std::string name) { for (bool dict : { false, true }) { for (arrow::Compression::type comptype : {arrow::Compression::type::UNCOMPRESSED, arrow::Compression::type::SNAPPY}) { std::shared_ptr<arrow::io::FileOutputStream> outfile; std::string filename = name + (dict ? "_dict" : "") + (comptype == arrow::Compression::type::SNAPPY ? "_snappy" : "") + ".prq"; arrow::Result<std::shared_ptr<arrow::io::FileOutputStream>> result = arrow::io::FileOutputStream::Open(filename, false); if (result.ok()) { outfile = result.ValueOrDie(); } else { std::cout << "Error occurred opening file " << name; } parquet::WriterProperties::Builder propbuilder = parquet::WriterProperties::Builder{}; propbuilder.compression(comptype)->encoding( parquet::Encoding::type::PLAIN)->disable_statistics()->version( parquet::ParquetVersion::PARQUET_1_0); if (!dict) { propbuilder.disable_dictionary(); } parquet::arrow::WriteTable(*table, arrow::default_memory_pool(), outfile, INT_MAX, propbuilder.build()); outfile->Flush(); outfile->Close(); } } } int main(int argc, char **argv) { srand(123); int nRows = 100; int nCols = 1; enum Datatype {int32, int64, str}; std::string typenames[] = {"int32", "int64", "str"}; Datatype datatype = int64; if (argc >= 2) { if (!strncmp(argv[1], "int32", 5)) { datatype = int32; } if (!strncmp(argv[1], "int64", 5)) { datatype = int64; } if (!strncmp(argv[1], "str", 3)) { datatype = str; } } if (argc >= 3) { nRows = strtol(argv[2], 0, 10); } if (argc >= 4) { nCols = strtol(argv[3], 0, 10); } printf("Generating parquet files with %s datatype, %d rows, %d columns\n", typenames[datatype].c_str(), nRows, nCols); if (datatype == int32) { // std::shared_ptr<arrow::Table> test_int32stable = generate_int32_table(nRows, nCols, true); // write_parquet(test_int32stable, "./test_int32s"); std::shared_ptr<arrow::Table> test_int32rtable = generate_int32_table(nRows, nCols, true); write_parquet(test_int32rtable, "./test_int32"); } if (datatype == int64) { // std::shared_ptr<arrow::Table> test_int64stable = generate_int64_table(nRows, nCols, true); // write_parquet(test_int64stable, "./test_int64s"); std::shared_ptr<arrow::Table> test_int64rtable = generate_int64_table(nRows, nCols, true); write_parquet(test_int64rtable, "./test_int64"); } if (datatype == str) { std::shared_ptr<arrow::Table> test_strtable = generate_str_table(nRows, nCols, 1, 12); write_parquet(test_strtable, "./test_str"); } return 0; }
32.201754
123
0.65854
[ "vector" ]
2d6a6a050b29957523173f3f3c12d8d071b4b401
16,937
hpp
C++
lib/mtl4/boost/numeric/mtl/vector/crtp_base_vector.hpp
spraetor/amdis2
53c45c81a65752a8fafbb54f9ae6724a86639dcd
[ "MIT" ]
2
2018-07-04T16:44:04.000Z
2021-01-03T07:26:27.000Z
lib/mtl4/boost/numeric/mtl/vector/crtp_base_vector.hpp
spraetor/amdis2
53c45c81a65752a8fafbb54f9ae6724a86639dcd
[ "MIT" ]
null
null
null
lib/mtl4/boost/numeric/mtl/vector/crtp_base_vector.hpp
spraetor/amdis2
53c45c81a65752a8fafbb54f9ae6724a86639dcd
[ "MIT" ]
null
null
null
// Software License for MTL // // Copyright (c) 2007 The Trustees of Indiana University. // 2008 Dresden University of Technology and the Trustees of Indiana University. // 2010 SimuNova UG (haftungsbeschränkt), www.simunova.com. // All rights reserved. // Authors: Peter Gottschling and Andrew Lumsdaine // // This file is part of the Matrix Template Library // // See also license.mtl.txt in the distribution. #ifndef MTL_CRTP_BASE_VECTOR_INCLUDE #define MTL_CRTP_BASE_VECTOR_INCLUDE #include <boost/mpl/if.hpp> #include <boost/mpl/bool.hpp> #include <boost/type_traits/is_base_of.hpp> #include <boost/utility/enable_if.hpp> #include <boost/numeric/mtl/mtl_fwd.hpp> #include <boost/numeric/mtl/vector/all_vec_expr.hpp> #include <boost/numeric/mtl/vector/assigner.hpp> #include <boost/numeric/mtl/vector/decrementer.hpp> #include <boost/numeric/mtl/vector/incrementer.hpp> #include <boost/numeric/mtl/operation/mat_cvec_times_expr.hpp> #include <boost/numeric/mtl/operation/mult.hpp> #include <boost/numeric/mtl/operation/mat_vec_mult.hpp> #include <boost/numeric/mtl/operation/mult_assign_mode.hpp> #include <boost/numeric/mtl/operation/right_scale_inplace.hpp> #include <boost/numeric/mtl/utility/ashape.hpp> #include <boost/numeric/mtl/utility/category.hpp> #include <boost/numeric/mtl/utility/flatcat.hpp> #include <boost/numeric/mtl/utility/is_distributed.hpp> #include <boost/numeric/mtl/utility/tag.hpp> #include <boost/numeric/itl/itl_fwd.hpp> namespace mtl { namespace vector { namespace detail { template <typename Vector, typename Source, typename SCat, typename VCat> struct crtp_assign {}; /// Assign scalar to a vector by setting all values to the scalar template <typename Vector, typename Source, typename VCat> struct crtp_assign<Vector, Source, VCat, ashape::scal> { typedef vec_scal_asgn_expr<Vector, Source> type; type operator()(Vector& vector, const Source& src) { return type(vector, src); } }; /// Assign vector to a vector template <typename Vector, typename Source, typename Cat> struct crtp_assign<Vector, Source, Cat, Cat> { typedef vec_vec_asgn_expr<Vector, Source> type; type operator()(Vector& vector, const Source& src) { return type(vector, src); } }; template <typename Vector, typename Source> struct assign_assigner { typedef const Vector& type; type operator()(Vector& vector, const Source& src) { src.assign_to(vector); return vector; } }; } // namespace detail template <typename Vector, typename Source> struct crtp_assign : boost::mpl::if_ <boost::is_base_of<assigner_base, Source>, detail::assign_assigner <Vector, Source>, detail::crtp_assign<Vector, Source, typename ashape::ashape<Vector>::type, typename ashape::ashape<Source>::type> >::type {}; /// Assign matrix vector product by calling mult /** Note that this does not work for arbitrary expressions. **/ template <typename Vector, typename E1, typename E2> struct crtp_assign<Vector, mat_cvec_times_expr<E1, E2> > { typedef Vector& type; type operator()(Vector& vector, const mat_cvec_times_expr<E1, E2>& src) { vector.checked_change_resource(src); set_to_zero(vector); mat_cvec_mult(src.first, src.second, vector, assign::assign_sum(), traits::mat_cvec_flatcat<E1>()); return vector; } }; /// Assign vector matrix product by calling mult /** Note that this does not work for arbitrary expressions. **/ template <typename Vector, typename E1, typename E2> struct crtp_assign<Vector, rvec_mat_times_expr<E1, E2> > { typedef Vector& type; type operator()(Vector& vector, const rvec_mat_times_expr<E1, E2>& src) { vector.checked_change_resource(src); rvec_mat_mult(src.first, src.second, vector, assign::assign_sum(), traits::mat_cvec_flatcat<E2>()); return vector; } }; /// Assign c-style 1D-array, because it's easier to initialize. template <typename Vector, typename Value, unsigned Rows> struct crtp_assign<Vector, Value[Rows]> { typedef Vector& type; type operator()(Vector& vector, const Value src[Rows]) { typedef typename Collection<Vector>::size_type size_type; vector.checked_change_dim(Rows); for (size_type r= 0; r < Rows; ++r) vector[r]= src[r]; return vector; } }; namespace detail { template <typename Vector, typename Source, typename SCat, typename VCat> struct crtp_plus_assign {}; /// Assign-add vector to a vector template <typename Vector, typename Source, typename Cat> struct crtp_plus_assign<Vector, Source, Cat, Cat> { typedef vec_vec_plus_asgn_expr<Vector, Source> type; type operator()(Vector& vector, const Source& src) { return type( vector, src ); } }; /// Increment a vector by a scalar template <typename Vector, typename Source, typename VCat> struct crtp_plus_assign<Vector, Source, VCat, ashape::scal> { typedef vec_scal_plus_asgn_expr<Vector, Source> type; type operator()(Vector& vector, const Source& src) { return type(vector, src); } }; template <typename Vector, typename Source> struct assign_incrementer { typedef const Vector& type; type operator()(Vector& vector, const Source& src) { src.increment_it(vector); return vector; } }; } // namespace detail template <typename Vector, typename Source> struct crtp_plus_assign : boost::mpl::if_ <boost::is_base_of<incrementer_base, Source>, detail::assign_incrementer<Vector, Source>, detail::crtp_plus_assign<Vector, Source, typename ashape::ashape<Vector>::type, typename ashape::ashape<Source>::type> >::type {}; /// Assign-add matrix vector product by calling mult /** Note that this does not work for arbitrary expressions. **/ template <typename Vector, typename E1, typename E2> struct crtp_plus_assign<Vector, mat_cvec_times_expr<E1, E2> > { typedef Vector& type; type operator()(Vector& vector, const mat_cvec_times_expr<E1, E2>& src) { mat_cvec_mult(src.first, src.second, vector, assign::plus_sum(), traits::mat_cvec_flatcat<E1>()); return vector; } }; /// Assign-add vector matrix product by calling mult /** Note that this does not work for arbitrary expressions. **/ template <typename Vector, typename E1, typename E2> struct crtp_plus_assign<Vector, rvec_mat_times_expr<E1, E2> > { typedef Vector& type; type operator()(Vector& vector, const rvec_mat_times_expr<E1, E2>& src) { rvec_mat_mult(src.first, src.second, vector, assign::plus_sum(), traits::mat_cvec_flatcat<E2>()); return vector; } }; namespace detail { template <typename Vector, typename Source, typename VCat, typename SCat> struct crtp_minus_assign {}; /// Assign-add vector to a vector template <typename Vector, typename Source, typename Cat> struct crtp_minus_assign<Vector, Source, Cat, Cat> { typedef vec_vec_minus_asgn_expr<Vector, Source> type; type operator()(Vector& vector, const Source& src) { return type(vector, src); } }; /// Decrement a vector by a scalar template <typename Vector, typename Source, typename VCat> struct crtp_minus_assign<Vector, Source, VCat, ashape::scal> { typedef vec_scal_minus_asgn_expr<Vector, Source> type; type operator()(Vector& vector, const Source& src) { return type(vector, src); } }; template <typename Vector, typename Source> struct assign_decrementer { typedef const Vector& type; type operator()(Vector& vector, const Source& src) { src.decrement_it(vector); return vector; } }; } // namespace detail template <typename Vector, typename Source> struct crtp_minus_assign : boost::mpl::if_ <boost::is_base_of<decrementer_base, Source>, detail::assign_decrementer<Vector, Source>, detail::crtp_minus_assign<Vector, Source, typename ashape::ashape<Vector>::type, typename ashape::ashape<Source>::type> >::type {}; /// Assign-subtract matrix vector product by calling mult /** Note that this does not work for arbitrary expressions. **/ template <typename Vector, typename E1, typename E2> struct crtp_minus_assign<Vector, mat_cvec_times_expr<E1, E2> > { typedef Vector& type; type operator()(Vector& vector, const mat_cvec_times_expr<E1, E2>& src) { mat_cvec_mult(src.first, src.second, vector, assign::minus_sum(), traits::mat_cvec_flatcat<E1>()); return vector; } }; /// Assign-subtract vector matrix product by calling mult /** Note that this does not work for arbitrary expressions. **/ template <typename Vector, typename E1, typename E2> struct crtp_minus_assign<Vector, rvec_mat_times_expr<E1, E2> > { typedef Vector& type; type operator()(Vector& vector, const rvec_mat_times_expr<E1, E2>& src) { rvec_mat_mult(src.first, src.second, vector, assign::minus_sum(), traits::mat_cvec_flatcat<E2>()); return vector; } }; #if 1 namespace detail { template <typename Vector, typename Source, typename SCat, typename VCat> struct crtp_times_assign {}; /// Assign-add vector to a vector template <typename Vector, typename Source, typename Cat> struct crtp_times_assign<Vector, Source, Cat, Cat> { typedef vec_vec_times_asgn_expr<Vector, Source> type; type operator()(Vector& vector, const Source& src) { return type( vector, src ); } }; /// Increment a vector by a scalar template <typename Vector, typename Source, typename VCat> struct crtp_times_assign<Vector, Source, VCat, ashape::scal> { typedef vec_scal_times_asgn_expr<Vector, Source> type; type operator()(Vector& vector, const Source& src) { return type(vector, src); } }; template <typename Vector, typename Source> struct assign_multiplyer { typedef const Vector& type; type operator()(Vector& vector, const Source& src) { src.multiply_it(vector); return vector; } }; } // namespace detail template <typename Vector, typename Source> struct crtp_times_assign : boost::mpl::if_ <boost::is_base_of<incrementer_base, Source>, detail::assign_multiplyer<Vector, Source>, detail::crtp_times_assign<Vector, Source, typename ashape::ashape<Vector>::type, typename ashape::ashape<Source>::type> >::type {}; /// Assign-add matrix vector product by calling mult /** Note that this does not work for arbitrary expressions. **/ template <typename Vector, typename E1, typename E2> struct crtp_times_assign<Vector, mat_cvec_times_expr<E1, E2> > { typedef Vector& type; type operator()(Vector& vector, const mat_cvec_times_expr<E1, E2>& src) { mat_cvec_mult(src.first, src.second, vector, assign::times_sum(), traits::mat_cvec_flatcat<E1>()); return vector; } }; /// Assign-add vector matrix product by calling mult /** Note that this does not work for arbitrary expressions. **/ template <typename Vector, typename E1, typename E2> struct crtp_times_assign<Vector, rvec_mat_times_expr<E1, E2> > { typedef Vector& type; type operator()(Vector& vector, const rvec_mat_times_expr<E1, E2>& src) { rvec_mat_mult(src.first, src.second, vector, assign::times_sum(), traits::mat_cvec_flatcat<E2>()); return vector; } }; namespace detail { template <typename Vector, typename Source, typename SCat, typename VCat> struct crtp_div_assign {}; /// Assign-divide vector to a vector template <typename Vector, typename Source, typename Cat> struct crtp_div_assign<Vector, Source, Cat, Cat> { typedef vec_vec_div_asgn_expr<Vector, Source> type; type operator()(Vector& vector, const Source& src) { return type( vector, src ); } }; /// Divide a vector by a scalar template <typename Vector, typename Source, typename VCat> struct crtp_div_assign<Vector, Source, VCat, ashape::scal> { typedef vec_scal_div_asgn_expr<Vector, Source> type; type operator()(Vector& vector, const Source& src) { return type(vector, src); } }; template <typename Vector, typename Source> struct assign_divider { typedef const Vector& type; type operator()(Vector& vector, const Source& src) { src.divide_it(vector); return vector; } }; } // namespace detail template <typename Vector, typename Source> struct crtp_div_assign : boost::mpl::if_ <boost::is_base_of<incrementer_base, Source>, detail::assign_divider<Vector, Source>, detail::crtp_div_assign<Vector, Source, typename ashape::ashape<Vector>::type, typename ashape::ashape<Source>::type> >::type {}; /// Assign-divide matrix vector product by calling mult /** Note that this does not work for arbitrary expressions. **/ template <typename Vector, typename E1, typename E2> struct crtp_div_assign<Vector, mat_cvec_times_expr<E1, E2> > { typedef Vector& type; type operator()(Vector& vector, const mat_cvec_times_expr<E1, E2>& src) { mat_cvec_mult(src.first, src.second, vector, assign::divide_sum(), traits::mat_cvec_flatcat<E1>()); return vector; } }; /// Assign-divide vector matrix product by calling mult /** Note that this does not work for arbitrary expressions. **/ template <typename Vector, typename E1, typename E2> struct crtp_div_assign<Vector, rvec_mat_times_expr<E1, E2> > { typedef Vector& type; type operator()(Vector& vector, const rvec_mat_times_expr<E1, E2>& src) { rvec_mat_mult(src.first, src.second, vector, assign::divide_sum(), traits::mat_cvec_flatcat<E2>()); return vector; } }; #endif /// Base class to provide vector assignment operators generically template <typename Vector, typename ValueType, typename SizeType> struct crtp_vector_assign { /// Templated assignment implemented by functor to allow for partial specialization template <typename E> typename boost::disable_if<boost::is_same<Vector, E>, typename crtp_assign<Vector, E>::type>::type operator=(const E& e) { return crtp_assign<Vector, E>()(static_cast<Vector&>(*this), e); } /// Assign-add vector expression template <class E> typename crtp_plus_assign<Vector, E>::type operator+=(const E& e) { return crtp_plus_assign<Vector, E>()(static_cast<Vector&>(*this), e); } /// Assign-subtract vector expression template <class E> typename crtp_minus_assign<Vector, E>::type operator-=(const E& e) { return crtp_minus_assign<Vector, E>()(static_cast<Vector&>(*this), e); } #if 1 /// Assign-times vector expression template <class E> typename crtp_times_assign<Vector, E>::type operator*=(const E& e) { return crtp_times_assign<Vector, E>()(static_cast<Vector&>(*this), e); } /// Assign-div vector expression template <class E> typename crtp_div_assign<Vector, E>::type operator/=(const E& e) { return crtp_div_assign<Vector, E>()(static_cast<Vector&>(*this), e); } #endif #if 0 /// Scale vector (in place) with scalar value /** In the future, row vectors be possibly scaled by a matrix **/ template <typename Factor> vec_scal_times_asgn_expr<Vector, Factor> operator*=(const Factor& alpha) { return vec_scal_times_asgn_expr<Vector, Factor>( static_cast<Vector&>(*this), alpha ); } /// Devide vector (in place) by a scalar value // added by Hui Li 12/11/2007 template <typename Factor> vec_scal_div_asgn_expr<Vector, Factor> operator/=(const Factor& alpha) { return vec_scal_div_asgn_expr<Vector, Factor>( static_cast<Vector&>(*this), alpha ); } #endif /// Check whether source and target have compatible resources and adapt empty target /** For expressions like u= v + w, u can be set to the size of v and w if still is 0. **/ template <typename Src> void checked_change_resource(const Src& src) { checked_change_resource_aux(src, typename mtl::traits::is_distributed<Vector>::type()); } template <typename Src> void checked_change_resource_aux(const Src& src, boost::mpl::false_) { checked_change_dim(mtl::vector::size(src)); } /// Check whether vector size is compatible or if vector is 0 change it s. void checked_change_dim(SizeType s) { Vector& vector= static_cast<Vector&>(*this); vector.check_dim(s); vector.change_dim(s); } }; template <typename Vector, typename ValueType, typename SizeType> struct const_crtp_base_vector {}; template <typename Vector, typename ValueType, typename SizeType> struct mutable_crtp_base_vector : public crtp_vector_assign<Vector, ValueType, SizeType> {}; template <typename Vector, typename ValueType, typename SizeType> struct crtp_base_vector : boost::mpl::if_<boost::is_const<Vector>, const_crtp_base_vector<Vector, ValueType, SizeType>, mutable_crtp_base_vector<Vector, ValueType, SizeType> >::type {}; }} // namespace mtl::vector #endif // MTL_CRTP_BASE_VECTOR_INCLUDE
30.517117
119
0.708685
[ "vector" ]
06235268b117e9470ffd87c3671e7308d16acc68
1,835
cpp
C++
cpp/leetcodes/Kth_Smallest_Element_in_a_BST.cpp
shhuan/algorithms
2830c7e2ada8dfd3dcdda7c06846116d4f944a27
[ "MIT" ]
null
null
null
cpp/leetcodes/Kth_Smallest_Element_in_a_BST.cpp
shhuan/algorithms
2830c7e2ada8dfd3dcdda7c06846116d4f944a27
[ "MIT" ]
null
null
null
cpp/leetcodes/Kth_Smallest_Element_in_a_BST.cpp
shhuan/algorithms
2830c7e2ada8dfd3dcdda7c06846116d4f944a27
[ "MIT" ]
1
2022-03-09T04:52:55.000Z
2022-03-09T04:52:55.000Z
/* Given a binary search tree, write a function kthSmallest to find the kth smallest element in it. Note: You may assume k is always valid, 1 ? k ? BST's total elements. Follow up: What if the BST is modified (insert/delete operations) often and you need to find the kth smallest frequently? How would you optimize the kthSmallest routine? Hint: Try to utilize the property of a BST. What if you could modify the BST node's structure? The optimal runtime complexity is O(height of BST). */ #include <iostream> #include <vector> #include <bits/stl_algo.h> #include <set> #include <queue> #include <stack> using namespace std; struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; class Solution { public: int kthSmallest(TreeNode* root, int k) { //pre-order travel stack<TreeNode*> q; TreeNode* node = root; while (node != nullptr){ q.push(node); node = node->left; } while (!q.empty()){ node = q.top(); k--; if (k == 0){ return node->val; } q.pop(); if(node->right != nullptr){ node = node->right; while (node != nullptr){ q.push(node); node = node->left; } } } return -1; } }; int main(){ TreeNode* root = new TreeNode(6); root->left = new TreeNode(4); root->left->left = new TreeNode(3); root->left->right = new TreeNode(5); root->right = new TreeNode(8); root->right->left = new TreeNode(7); root->right->right = new TreeNode(9); Solution s; for(int i=1; i <= 7; i++){ cout << s.kthSmallest(root, i) << endl; } }
24.797297
158
0.554768
[ "vector" ]
0625caa1ada5e88a6d6fc34346ad7092a089930a
47,649
cpp
C++
emulator/src/frontend/mame/ui/viewgfx.cpp
rjw57/tiw-computer
5ef1c79893165b8622d1114d81cd0cded58910f0
[ "MIT" ]
1
2022-01-15T21:38:38.000Z
2022-01-15T21:38:38.000Z
emulator/src/frontend/mame/ui/viewgfx.cpp
rjw57/tiw-computer
5ef1c79893165b8622d1114d81cd0cded58910f0
[ "MIT" ]
null
null
null
emulator/src/frontend/mame/ui/viewgfx.cpp
rjw57/tiw-computer
5ef1c79893165b8622d1114d81cd0cded58910f0
[ "MIT" ]
null
null
null
// license:BSD-3-Clause // copyright-holders:Nicola Salmoria, Aaron Giles, Nathan Woods /********************************************************************* ui/viewgfx.cpp Internal graphics viewer. *********************************************************************/ #include "emu.h" #include "ui/ui.h" #include "uiinput.h" #include "render.h" #include "rendfont.h" #include "rendutil.h" #include "ui/viewgfx.h" /*************************************************************************** CONSTANTS ***************************************************************************/ enum ui_gfx_modes { UI_GFX_PALETTE = 0, UI_GFX_GFXSET, UI_GFX_TILEMAP }; const uint8_t MAX_GFX_DECODERS = 8; /*************************************************************************** TYPE DEFINITIONS ***************************************************************************/ // information about a single gfx device struct ui_gfx_info { device_gfx_interface *interface; // pointer to device's gfx interface uint8_t setcount; // how many gfx sets device has uint8_t rotate[MAX_GFX_ELEMENTS]; // current rotation (orientation) value uint8_t columns[MAX_GFX_ELEMENTS]; // number of items per row int offset[MAX_GFX_ELEMENTS]; // current offset of top,left item int color[MAX_GFX_ELEMENTS]; // current color selected device_palette_interface *palette[MAX_GFX_ELEMENTS]; // associated palette (maybe multiple choice one day?) int color_count[MAX_GFX_ELEMENTS]; // Range of color values }; struct ui_gfx_state { bool started; // have we called ui_gfx_count_devices() yet? uint8_t mode; // which mode are we in? // intermediate bitmaps bool bitmap_dirty; // is the bitmap dirty? bitmap_rgb32 * bitmap; // bitmap for drawing gfx and tilemaps render_texture *texture; // texture for rendering the above bitmap // palette-specific data struct { device_palette_interface *interface; // pointer to current palette int devcount; // how many palette devices exist int devindex; // which palette device is visible uint8_t which; // which subset (pens or indirect colors)? uint8_t columns; // number of items per row int offset; // current offset of top left item } palette; // graphics-specific data struct { uint8_t devcount; // how many gfx devices exist uint8_t devindex; // which device is visible uint8_t set; // which set is visible } gfxset; // information about each gfx device ui_gfx_info gfxdev[MAX_GFX_DECODERS]; // tilemap-specific data struct { int which; // which tilemap are we viewing? int xoffs; // current X offset int yoffs; // current Y offset int zoom; // zoom factor uint8_t rotate; // current rotation (orientation) value uint32_t flags; // render flags } tilemap; }; /*************************************************************************** GLOBAL VARIABLES ***************************************************************************/ static ui_gfx_state ui_gfx; /*************************************************************************** FUNCTION PROTOTYPES ***************************************************************************/ static void ui_gfx_count_devices(running_machine &machine, ui_gfx_state &state); static void ui_gfx_exit(running_machine &machine); // palette handling static void palette_set_device(running_machine &machine, ui_gfx_state &state); static void palette_handle_keys(running_machine &machine, ui_gfx_state &state); static void palette_handler(mame_ui_manager &mui, render_container &container, ui_gfx_state &state); // graphics set handling static void gfxset_handle_keys(running_machine &machine, ui_gfx_state &state, int xcells, int ycells); static void gfxset_draw_item(running_machine &machine, gfx_element &gfx, int index, bitmap_rgb32 &bitmap, int dstx, int dsty, int color, int rotate, device_palette_interface *dpalette); static void gfxset_update_bitmap(running_machine &machine, ui_gfx_state &state, int xcells, int ycells, gfx_element &gfx); static void gfxset_handler(mame_ui_manager &mui, render_container &container, ui_gfx_state &state); // tilemap handling static void tilemap_handle_keys(running_machine &machine, ui_gfx_state &state, int viswidth, int visheight); static void tilemap_update_bitmap(running_machine &machine, ui_gfx_state &state, int width, int height); static void tilemap_handler(mame_ui_manager &mui, render_container &container, ui_gfx_state &state); /*************************************************************************** CORE IMPLEMENTATION ***************************************************************************/ //------------------------------------------------- // ui_gfx_init - initialize the graphics viewer //------------------------------------------------- void ui_gfx_init(running_machine &machine) { ui_gfx_state *state = &ui_gfx; uint8_t rotate = machine.system().flags & machine_flags::MASK_ORIENTATION; // make sure we clean up after ourselves machine.add_notifier(MACHINE_NOTIFY_EXIT, machine_notify_delegate(&ui_gfx_exit, &machine)); // initialize our global state memset(state, 0, sizeof(*state)); // set up the palette state state->palette.columns = 16; // set up the graphics state for (uint8_t i = 0; i < MAX_GFX_DECODERS; i++) for (uint8_t j = 0; j < MAX_GFX_ELEMENTS; j++) { state->gfxdev[i].rotate[j] = rotate; state->gfxdev[i].columns[j] = 16; } // set up the tilemap state state->tilemap.rotate = rotate; state->tilemap.flags = TILEMAP_DRAW_ALL_CATEGORIES; } //------------------------------------------------- // ui_gfx_count_devices - count the palettes, // gfx decoders and gfx sets in the machine //------------------------------------------------- static void ui_gfx_count_devices(running_machine &machine, ui_gfx_state &state) { // count the palette devices state.palette.devcount = palette_interface_iterator(machine.root_device()).count(); // set the pointer to the first palette if (state.palette.devcount > 0) palette_set_device(machine, state); // count the gfx devices state.gfxset.devcount = 0; for (device_gfx_interface &interface : gfx_interface_iterator(machine.root_device())) { // count the gfx sets in each device, skipping devices with none uint8_t count = 0; while (count < MAX_GFX_ELEMENTS && interface.gfx(count) != nullptr) count++; // count = index of first nullptr if (count > 0) { state.gfxdev[state.gfxset.devcount].interface = &interface; state.gfxdev[state.gfxset.devcount].setcount = count; for (uint8_t slot = 0; slot != count; slot++) { auto gfx = interface.gfx(slot); if (gfx->has_palette()) { state.gfxdev[state.gfxset.devcount].palette[slot] = &gfx->palette(); state.gfxdev[state.gfxset.devcount].color_count[slot] = gfx->colors(); } else { state.gfxdev[state.gfxset.devcount].palette[slot] = state.palette.interface; state.gfxdev[state.gfxset.devcount].color_count[slot] = state.palette.interface->entries() / gfx->granularity(); if (!state.gfxdev[state.gfxset.devcount].color_count[slot]) state.gfxdev[state.gfxset.devcount].color_count[slot] = 1; } } if (++state.gfxset.devcount == MAX_GFX_DECODERS) break; } } state.started = true; } //------------------------------------------------- // ui_gfx_exit - clean up after ourselves //------------------------------------------------- static void ui_gfx_exit(running_machine &machine) { // free the texture machine.render().texture_free(ui_gfx.texture); ui_gfx.texture = nullptr; // free the bitmap global_free(ui_gfx.bitmap); ui_gfx.bitmap = nullptr; } //------------------------------------------------- // ui_gfx_is_relevant - returns 'true' if the // internal graphics viewer has relevance // // NOTE: this must not be called before machine // initialization is complete, as some drivers // create or modify gfx sets in VIDEO_START //------------------------------------------------- bool ui_gfx_is_relevant(running_machine &machine) { ui_gfx_state &state = ui_gfx; if (!state.started) ui_gfx_count_devices(machine, state); return state.palette.devcount > 0 || state.gfxset.devcount > 0 || machine.tilemap().count() > 0; } //------------------------------------------------- // ui_gfx_ui_handler - primary UI handler //------------------------------------------------- uint32_t ui_gfx_ui_handler(render_container &container, mame_ui_manager &mui, bool uistate) { ui_gfx_state &state = ui_gfx; // if we have nothing, implicitly cancel if (!ui_gfx_is_relevant(mui.machine())) goto cancel; // if we're not paused, mark the bitmap dirty if (!mui.machine().paused()) state.bitmap_dirty = true; // switch off the state to display something again: switch (state.mode) { case UI_GFX_PALETTE: // if we have a palette, display it if (state.palette.devcount > 0) { palette_handler(mui, container, state); break; } // fall through... state.mode++; case UI_GFX_GFXSET: // if we have graphics sets, display them if (state.gfxset.devcount > 0) { gfxset_handler(mui, container, state); break; } // fall through... state.mode++; case UI_GFX_TILEMAP: // if we have tilemaps, display them if (mui.machine().tilemap().count() > 0) { tilemap_handler(mui, container, state); break; } state.mode = UI_GFX_PALETTE; goto again; } // handle keys if (mui.machine().ui_input().pressed(IPT_UI_SELECT)) { state.mode = (state.mode + 1) % 3; state.bitmap_dirty = true; } if (mui.machine().ui_input().pressed(IPT_UI_PAUSE)) { if (mui.machine().paused()) mui.machine().resume(); else mui.machine().pause(); } if (mui.machine().ui_input().pressed(IPT_UI_CANCEL) || mui.machine().ui_input().pressed(IPT_UI_SHOW_GFX)) goto cancel; return uistate; cancel: if (!uistate) mui.machine().resume(); state.bitmap_dirty = true; return UI_HANDLER_CANCEL; } /*************************************************************************** PALETTE VIEWER ***************************************************************************/ //------------------------------------------------- // palette_set_device - set the pointer to the // current palette device //------------------------------------------------- static void palette_set_device(running_machine &machine, ui_gfx_state &state) { palette_interface_iterator pal_iter(machine.root_device()); state.palette.interface = pal_iter.byindex(state.palette.devindex); } //------------------------------------------------- // palette_handler - handler for the palette // viewer //------------------------------------------------- static void palette_handler(mame_ui_manager &mui, render_container &container, ui_gfx_state &state) { device_palette_interface *palette = state.palette.interface; palette_device *paldev = dynamic_cast<palette_device *>(&palette->device()); int total = state.palette.which ? palette->indirect_entries() : palette->entries(); const rgb_t *raw_color = palette->palette()->entry_list_raw(); render_font *ui_font = mui.get_font(); float chwidth, chheight; float titlewidth; float x0, y0; render_bounds cellboxbounds; render_bounds boxbounds; int x, y, skip; // add a half character padding for the box chheight = mui.get_line_height(); chwidth = ui_font->char_width(chheight, mui.machine().render().ui_aspect(), '0'); boxbounds.x0 = 0.0f + 0.5f * chwidth; boxbounds.x1 = 1.0f - 0.5f * chwidth; boxbounds.y0 = 0.0f + 0.5f * chheight; boxbounds.y1 = 1.0f - 0.5f * chheight; // the character cell box bounds starts a half character in from the box cellboxbounds = boxbounds; cellboxbounds.x0 += 0.5f * chwidth; cellboxbounds.x1 -= 0.5f * chwidth; cellboxbounds.y0 += 0.5f * chheight; cellboxbounds.y1 -= 0.5f * chheight; // add space on the left for 5 characters of text, plus a half character of padding cellboxbounds.x0 += 5.5f * chwidth; // add space on the top for a title, a half line of padding, a header, and another half line cellboxbounds.y0 += 3.0f * chheight; // compute the cell size float cellwidth = (cellboxbounds.x1 - cellboxbounds.x0) / (float)state.palette.columns; float cellheight = (cellboxbounds.y1 - cellboxbounds.y0) / (float)state.palette.columns; // figure out the title std::ostringstream title_buf; util::stream_format(title_buf, "'%s'", palette->device().tag()); if (palette->indirect_entries() > 0) title_buf << (state.palette.which ? _(" COLORS") : _(" PENS")); // if the mouse pointer is over one of our cells, add some info about the corresponding palette entry int32_t mouse_target_x, mouse_target_y; float mouse_x, mouse_y; bool mouse_button; render_target *mouse_target = mui.machine().ui_input().find_mouse(&mouse_target_x, &mouse_target_y, &mouse_button); if (mouse_target != nullptr && mouse_target->map_point_container(mouse_target_x, mouse_target_y, container, mouse_x, mouse_y) && cellboxbounds.x0 <= mouse_x && cellboxbounds.x1 > mouse_x && cellboxbounds.y0 <= mouse_y && cellboxbounds.y1 > mouse_y) { int index = state.palette.offset + int((mouse_x - cellboxbounds.x0) / cellwidth) + int((mouse_y - cellboxbounds.y0) / cellheight) * state.palette.columns; if (index < total) { util::stream_format(title_buf, " #%X", index); if (palette->indirect_entries() > 0 && !state.palette.which) util::stream_format(title_buf, " => %X", palette->pen_indirect(index)); else if (paldev != nullptr && paldev->basemem().base() != nullptr) util::stream_format(title_buf, " = %X", paldev->read_entry(index)); rgb_t col = state.palette.which ? palette->indirect_color(index) : raw_color[index]; util::stream_format(title_buf, " (R:%X G:%X B:%X)", col.r(), col.g(), col.b()); } } // expand the outer box to fit the title const std::string title = title_buf.str(); titlewidth = ui_font->string_width(chheight, mui.machine().render().ui_aspect(), title.c_str()); x0 = 0.0f; if (boxbounds.x1 - boxbounds.x0 < titlewidth + chwidth) x0 = boxbounds.x0 - (0.5f - 0.5f * (titlewidth + chwidth)); // go ahead and draw the outer box now mui.draw_outlined_box(container, boxbounds.x0 - x0, boxbounds.y0, boxbounds.x1 + x0, boxbounds.y1, UI_GFXVIEWER_BG_COLOR); // draw the title x0 = 0.5f - 0.5f * titlewidth; y0 = boxbounds.y0 + 0.5f * chheight; for (auto ch : title) { container.add_char(x0, y0, chheight, mui.machine().render().ui_aspect(), rgb_t::white(), *ui_font, ch); x0 += ui_font->char_width(chheight, mui.machine().render().ui_aspect(), ch); } // draw the top column headers skip = (int)(chwidth / cellwidth); for (x = 0; x < state.palette.columns; x += 1 + skip) { x0 = boxbounds.x0 + 6.0f * chwidth + (float)x * cellwidth; y0 = boxbounds.y0 + 2.0f * chheight; container.add_char(x0 + 0.5f * (cellwidth - chwidth), y0, chheight, mui.machine().render().ui_aspect(), rgb_t::white(), *ui_font, "0123456789ABCDEF"[x & 0xf]); // if we're skipping, draw a point between the character and the box to indicate which // one it's referring to if (skip != 0) container.add_point(x0 + 0.5f * cellwidth, 0.5f * (y0 + chheight + cellboxbounds.y0), UI_LINE_WIDTH, rgb_t::white(), PRIMFLAG_BLENDMODE(BLENDMODE_ALPHA)); } // draw the side column headers skip = (int)(chheight / cellheight); for (y = 0; y < state.palette.columns; y += 1 + skip) // only display if there is data to show if (state.palette.offset + y * state.palette.columns < total) { char buffer[10]; // if we're skipping, draw a point between the character and the box to indicate which // one it's referring to x0 = boxbounds.x0 + 5.5f * chwidth; y0 = boxbounds.y0 + 3.5f * chheight + (float)y * cellheight; if (skip != 0) container.add_point(0.5f * (x0 + cellboxbounds.x0), y0 + 0.5f * cellheight, UI_LINE_WIDTH, rgb_t::white(), PRIMFLAG_BLENDMODE(BLENDMODE_ALPHA)); // draw the row header sprintf(buffer, "%5X", state.palette.offset + y * state.palette.columns); for (x = 4; x >= 0; x--) { x0 -= ui_font->char_width(chheight, mui.machine().render().ui_aspect(), buffer[x]); container.add_char(x0, y0 + 0.5f * (cellheight - chheight), chheight, mui.machine().render().ui_aspect(), rgb_t::white(), *ui_font, buffer[x]); } } // now add the rectangles for the colors for (y = 0; y < state.palette.columns; y++) for (x = 0; x < state.palette.columns; x++) { int index = state.palette.offset + y * state.palette.columns + x; if (index < total) { pen_t pen = state.palette.which ? palette->indirect_color(index) : raw_color[index]; container.add_rect(cellboxbounds.x0 + x * cellwidth, cellboxbounds.y0 + y * cellheight, cellboxbounds.x0 + (x + 1) * cellwidth, cellboxbounds.y0 + (y + 1) * cellheight, 0xff000000 | pen, PRIMFLAG_BLENDMODE(BLENDMODE_ALPHA)); } } // handle keys palette_handle_keys(mui.machine(), state); } //------------------------------------------------- // palette_handle_keys - handle key inputs for // the palette viewer //------------------------------------------------- static void palette_handle_keys(running_machine &machine, ui_gfx_state &state) { device_palette_interface *palette = state.palette.interface; int rowcount, screencount; int total; // handle zoom (minus,plus) if (machine.ui_input().pressed(IPT_UI_ZOOM_OUT)) state.palette.columns /= 2; if (machine.ui_input().pressed(IPT_UI_ZOOM_IN)) state.palette.columns *= 2; // clamp within range if (state.palette.columns <= 4) state.palette.columns = 4; if (state.palette.columns > 64) state.palette.columns = 64; // handle colormap selection (open bracket,close bracket) if (machine.ui_input().pressed(IPT_UI_PREV_GROUP)) { if (state.palette.which) state.palette.which = 0; else if (state.palette.devindex > 0) { state.palette.devindex--; palette_set_device(machine, state); palette = state.palette.interface; state.palette.which = (palette->indirect_entries() > 0); } } if (machine.ui_input().pressed(IPT_UI_NEXT_GROUP)) { if (!state.palette.which && palette->indirect_entries() > 0) state.palette.which = 1; else if (state.palette.devindex < state.palette.devcount - 1) { state.palette.devindex++; palette_set_device(machine, state); palette = state.palette.interface; state.palette.which = 0; } } // cache some info in locals total = state.palette.which ? palette->indirect_entries() : palette->entries(); // determine number of entries per row and total rowcount = state.palette.columns; screencount = rowcount * rowcount; // handle keyboard navigation if (machine.ui_input().pressed_repeat(IPT_UI_UP, 4)) state.palette.offset -= rowcount; if (machine.ui_input().pressed_repeat(IPT_UI_DOWN, 4)) state.palette.offset += rowcount; if (machine.ui_input().pressed_repeat(IPT_UI_PAGE_UP, 6)) state.palette.offset -= screencount; if (machine.ui_input().pressed_repeat(IPT_UI_PAGE_DOWN, 6)) state.palette.offset += screencount; if (machine.ui_input().pressed_repeat(IPT_UI_HOME, 4)) state.palette.offset = 0; if (machine.ui_input().pressed_repeat(IPT_UI_END, 4)) state.palette.offset = total; // clamp within range if (state.palette.offset + screencount > ((total + rowcount - 1) / rowcount) * rowcount) state.palette.offset = ((total + rowcount - 1) / rowcount) * rowcount - screencount; if (state.palette.offset < 0) state.palette.offset = 0; } /*************************************************************************** GRAPHICS VIEWER ***************************************************************************/ //------------------------------------------------- // gfxset_handler - handler for the graphics // viewer //------------------------------------------------- static void gfxset_handler(mame_ui_manager &mui, render_container &container, ui_gfx_state &state) { render_font *ui_font = mui.get_font(); int dev = state.gfxset.devindex; int set = state.gfxset.set; ui_gfx_info &info = state.gfxdev[dev]; device_gfx_interface &interface = *info.interface; gfx_element &gfx = *interface.gfx(set); float fullwidth, fullheight; float cellwidth, cellheight; float chwidth, chheight; float titlewidth; float x0, y0; render_bounds cellboxbounds; render_bounds boxbounds; int cellboxwidth, cellboxheight; int targwidth = mui.machine().render().ui_target().width(); int targheight = mui.machine().render().ui_target().height(); int cellxpix, cellypix; int xcells, ycells; int pixelscale = 0; int x, y, skip; // add a half character padding for the box chheight = mui.get_line_height(); chwidth = ui_font->char_width(chheight, mui.machine().render().ui_aspect(), '0'); boxbounds.x0 = 0.0f + 0.5f * chwidth; boxbounds.x1 = 1.0f - 0.5f * chwidth; boxbounds.y0 = 0.0f + 0.5f * chheight; boxbounds.y1 = 1.0f - 0.5f * chheight; // the character cell box bounds starts a half character in from the box cellboxbounds = boxbounds; cellboxbounds.x0 += 0.5f * chwidth; cellboxbounds.x1 -= 0.5f * chwidth; cellboxbounds.y0 += 0.5f * chheight; cellboxbounds.y1 -= 0.5f * chheight; // add space on the left for 5 characters of text, plus a half character of padding cellboxbounds.x0 += 5.5f * chwidth; // add space on the top for a title, a half line of padding, a header, and another half line cellboxbounds.y0 += 3.0f * chheight; // convert back to pixels cellboxwidth = (cellboxbounds.x1 - cellboxbounds.x0) * (float)targwidth; cellboxheight = (cellboxbounds.y1 - cellboxbounds.y0) * (float)targheight; // compute the number of source pixels in a cell cellxpix = 1 + ((info.rotate[set] & ORIENTATION_SWAP_XY) ? gfx.height() : gfx.width()); cellypix = 1 + ((info.rotate[set] & ORIENTATION_SWAP_XY) ? gfx.width() : gfx.height()); // compute the largest pixel scale factor that still fits xcells = info.columns[set]; while (xcells > 1) { pixelscale = (cellboxwidth / xcells) / cellxpix; if (pixelscale != 0) break; xcells--; } info.columns[set] = xcells; // worst case, we need a pixel scale of 1 pixelscale = std::max(1, pixelscale); // in the Y direction, we just display as many as we can ycells = cellboxheight / (pixelscale * cellypix); // now determine the actual cellbox size cellboxwidth = std::min(cellboxwidth, xcells * pixelscale * cellxpix); cellboxheight = std::min(cellboxheight, ycells * pixelscale * cellypix); // compute the size of a single cell at this pixel scale factor, as well as the aspect ratio cellwidth = (cellboxwidth / (float)xcells) / (float)targwidth; cellheight = (cellboxheight / (float)ycells) / (float)targheight; //cellaspect = cellwidth / cellheight; // working from the new width/height, recompute the boxbounds fullwidth = (float)cellboxwidth / (float)targwidth + 6.5f * chwidth; fullheight = (float)cellboxheight / (float)targheight + 4.0f * chheight; // recompute boxbounds from this boxbounds.x0 = (1.0f - fullwidth) * 0.5f; boxbounds.x1 = boxbounds.x0 + fullwidth; boxbounds.y0 = (1.0f - fullheight) * 0.5f; boxbounds.y1 = boxbounds.y0 + fullheight; // recompute cellboxbounds cellboxbounds.x0 = boxbounds.x0 + 6.0f * chwidth; cellboxbounds.x1 = cellboxbounds.x0 + (float)cellboxwidth / (float)targwidth; cellboxbounds.y0 = boxbounds.y0 + 3.5f * chheight; cellboxbounds.y1 = cellboxbounds.y0 + (float)cellboxheight / (float)targheight; // figure out the title std::ostringstream title_buf; util::stream_format(title_buf, "'%s' %d/%d", interface.device().tag(), set, info.setcount - 1); // if the mouse pointer is over a pixel in a tile, add some info about the tile and pixel bool found_pixel = false; int32_t mouse_target_x, mouse_target_y; float mouse_x, mouse_y; bool mouse_button; render_target *mouse_target = mui.machine().ui_input().find_mouse(&mouse_target_x, &mouse_target_y, &mouse_button); if (mouse_target != nullptr && mouse_target->map_point_container(mouse_target_x, mouse_target_y, container, mouse_x, mouse_y) && cellboxbounds.x0 <= mouse_x && cellboxbounds.x1 > mouse_x && cellboxbounds.y0 <= mouse_y && cellboxbounds.y1 > mouse_y) { int code = info.offset[set] + int((mouse_x - cellboxbounds.x0) / cellwidth) + int((mouse_y - cellboxbounds.y0) / cellheight) * xcells; int xpixel = int((mouse_x - cellboxbounds.x0) / (cellwidth / cellxpix)) % cellxpix; int ypixel = int((mouse_y - cellboxbounds.y0) / (cellheight / cellypix)) % cellypix; if (code < gfx.elements() && xpixel < (cellxpix - 1) && ypixel < (cellypix - 1)) { found_pixel = true; if (info.rotate[set] & ORIENTATION_FLIP_X) xpixel = (cellxpix - 2) - xpixel; if (info.rotate[set] & ORIENTATION_FLIP_Y) ypixel = (cellypix - 2) - ypixel; if (info.rotate[set] & ORIENTATION_SWAP_XY) std::swap(xpixel, ypixel); uint8_t pixdata = gfx.get_data(code)[xpixel + ypixel * gfx.rowbytes()]; util::stream_format(title_buf, " #%X:%X @ %d,%d = %X", code, info.color[set], xpixel, ypixel, gfx.colorbase() + info.color[set] * gfx.granularity() + pixdata); } } if (!found_pixel) util::stream_format(title_buf, " %dx%d COLOR %X/%X", gfx.width(), gfx.height(), info.color[set], info.color_count[set]); // expand the outer box to fit the title const std::string title = title_buf.str(); titlewidth = ui_font->string_width(chheight, mui.machine().render().ui_aspect(), title.c_str()); x0 = 0.0f; if (boxbounds.x1 - boxbounds.x0 < titlewidth + chwidth) x0 = boxbounds.x0 - (0.5f - 0.5f * (titlewidth + chwidth)); // go ahead and draw the outer box now mui.draw_outlined_box(container, boxbounds.x0 - x0, boxbounds.y0, boxbounds.x1 + x0, boxbounds.y1, UI_GFXVIEWER_BG_COLOR); // draw the title x0 = 0.5f - 0.5f * titlewidth; y0 = boxbounds.y0 + 0.5f * chheight; for (auto ch : title) { container.add_char(x0, y0, chheight, mui.machine().render().ui_aspect(), rgb_t::white(), *ui_font, ch); x0 += ui_font->char_width(chheight, mui.machine().render().ui_aspect(), ch); } // draw the top column headers skip = (int)(chwidth / cellwidth); for (x = 0; x < xcells; x += 1 + skip) { x0 = boxbounds.x0 + 6.0f * chwidth + (float)x * cellwidth; y0 = boxbounds.y0 + 2.0f * chheight; container.add_char(x0 + 0.5f * (cellwidth - chwidth), y0, chheight, mui.machine().render().ui_aspect(), rgb_t::white(), *ui_font, "0123456789ABCDEF"[x & 0xf]); // if we're skipping, draw a point between the character and the box to indicate which // one it's referring to if (skip != 0) container.add_point(x0 + 0.5f * cellwidth, 0.5f * (y0 + chheight + boxbounds.y0 + 3.5f * chheight), UI_LINE_WIDTH, rgb_t::white(), PRIMFLAG_BLENDMODE(BLENDMODE_ALPHA)); } // draw the side column headers skip = (int)(chheight / cellheight); for (y = 0; y < ycells; y += 1 + skip) // only display if there is data to show if (info.offset[set] + y * xcells < gfx.elements()) { char buffer[10]; // if we're skipping, draw a point between the character and the box to indicate which // one it's referring to x0 = boxbounds.x0 + 5.5f * chwidth; y0 = boxbounds.y0 + 3.5f * chheight + (float)y * cellheight; if (skip != 0) container.add_point(0.5f * (x0 + boxbounds.x0 + 6.0f * chwidth), y0 + 0.5f * cellheight, UI_LINE_WIDTH, rgb_t::white(), PRIMFLAG_BLENDMODE(BLENDMODE_ALPHA)); // draw the row header sprintf(buffer, "%5X", info.offset[set] + y * xcells); for (x = 4; x >= 0; x--) { x0 -= ui_font->char_width(chheight, mui.machine().render().ui_aspect(), buffer[x]); container.add_char(x0, y0 + 0.5f * (cellheight - chheight), chheight, mui.machine().render().ui_aspect(), rgb_t::white(), *ui_font, buffer[x]); } } // update the bitmap gfxset_update_bitmap(mui.machine(), state, xcells, ycells, gfx); // add the final quad container.add_quad(cellboxbounds.x0, cellboxbounds.y0, cellboxbounds.x1, cellboxbounds.y1, rgb_t::white(), state.texture, PRIMFLAG_BLENDMODE(BLENDMODE_ALPHA)); // handle keyboard navigation before drawing gfxset_handle_keys(mui.machine(), state, xcells, ycells); } //------------------------------------------------- // gfxset_handle_keys - handle keys for the // graphics viewer //------------------------------------------------- static void gfxset_handle_keys(running_machine &machine, ui_gfx_state &state, int xcells, int ycells) { // handle gfxset selection (open bracket,close bracket) if (machine.ui_input().pressed(IPT_UI_PREV_GROUP)) { if (state.gfxset.set > 0) state.gfxset.set--; else if (state.gfxset.devindex > 0) { state.gfxset.devindex--; state.gfxset.set = state.gfxdev[state.gfxset.devindex].setcount - 1; } state.bitmap_dirty = true; } if (machine.ui_input().pressed(IPT_UI_NEXT_GROUP)) { if (state.gfxset.set < state.gfxdev[state.gfxset.devindex].setcount - 1) state.gfxset.set++; else if (state.gfxset.devindex < state.gfxset.devcount - 1) { state.gfxset.devindex++; state.gfxset.set = 0; } state.bitmap_dirty = true; } // cache some info in locals int dev = state.gfxset.devindex; int set = state.gfxset.set; ui_gfx_info &info = state.gfxdev[dev]; gfx_element &gfx = *info.interface->gfx(set); // handle cells per line (minus,plus) if (machine.ui_input().pressed(IPT_UI_ZOOM_OUT)) { info.columns[set] = xcells - 1; state.bitmap_dirty = true; } if (machine.ui_input().pressed(IPT_UI_ZOOM_IN)) { info.columns[set] = xcells + 1; state.bitmap_dirty = true; } // clamp within range if (info.columns[set] < 2) { info.columns[set] = 2; state.bitmap_dirty = true; } if (info.columns[set] > 128) { info.columns[set] = 128; state.bitmap_dirty = true; } // handle rotation (R) if (machine.ui_input().pressed(IPT_UI_ROTATE)) { info.rotate[set] = orientation_add(ROT90, info.rotate[set]); state.bitmap_dirty = true; } // handle navigation within the cells (up,down,pgup,pgdown) if (machine.ui_input().pressed_repeat(IPT_UI_UP, 4)) { info.offset[set] -= xcells; state.bitmap_dirty = true; } if (machine.ui_input().pressed_repeat(IPT_UI_DOWN, 4)) { info.offset[set] += xcells; state.bitmap_dirty = true; } if (machine.ui_input().pressed_repeat(IPT_UI_PAGE_UP, 6)) { info.offset[set] -= xcells * ycells; state.bitmap_dirty = true; } if (machine.ui_input().pressed_repeat(IPT_UI_PAGE_DOWN, 6)) { info.offset[set] += xcells * ycells; state.bitmap_dirty = true; } if (machine.ui_input().pressed_repeat(IPT_UI_HOME, 4)) { info.offset[set] = 0; state.bitmap_dirty = true; } if (machine.ui_input().pressed_repeat(IPT_UI_END, 4)) { info.offset[set] = gfx.elements(); state.bitmap_dirty = true; } // clamp within range if (info.offset[set] + xcells * ycells > ((gfx.elements() + xcells - 1) / xcells) * xcells) { info.offset[set] = ((gfx.elements() + xcells - 1) / xcells) * xcells - xcells * ycells; state.bitmap_dirty = true; } if (info.offset[set] < 0) { info.offset[set] = 0; state.bitmap_dirty = true; } // handle color selection (left,right) if (machine.ui_input().pressed_repeat(IPT_UI_LEFT, 4)) { info.color[set] -= 1; state.bitmap_dirty = true; } if (machine.ui_input().pressed_repeat(IPT_UI_RIGHT, 4)) { info.color[set] += 1; state.bitmap_dirty = true; } // clamp within range if (info.color[set] >= info.color_count[set]) { info.color[set] = info.color_count[set] - 1; state.bitmap_dirty = true; } if (info.color[set] < 0) { info.color[set] = 0; state.bitmap_dirty = true; } } //------------------------------------------------- // gfxset_update_bitmap - redraw the current // graphics view bitmap //------------------------------------------------- static void gfxset_update_bitmap(running_machine &machine, ui_gfx_state &state, int xcells, int ycells, gfx_element &gfx) { int dev = state.gfxset.devindex; int set = state.gfxset.set; ui_gfx_info &info = state.gfxdev[dev]; int cellxpix, cellypix; int x, y; // compute the number of source pixels in a cell cellxpix = 1 + ((info.rotate[set] & ORIENTATION_SWAP_XY) ? gfx.height() : gfx.width()); cellypix = 1 + ((info.rotate[set] & ORIENTATION_SWAP_XY) ? gfx.width() : gfx.height()); // realloc the bitmap if it is too small if (state.bitmap == nullptr || state.texture == nullptr || state.bitmap->bpp() != 32 || state.bitmap->width() != cellxpix * xcells || state.bitmap->height() != cellypix * ycells) { // free the old stuff machine.render().texture_free(state.texture); global_free(state.bitmap); // allocate new stuff state.bitmap = global_alloc(bitmap_rgb32(cellxpix * xcells, cellypix * ycells)); state.texture = machine.render().texture_alloc(); state.texture->set_bitmap(*state.bitmap, state.bitmap->cliprect(), TEXFORMAT_ARGB32); // force a redraw state.bitmap_dirty = true; } // handle the redraw if (state.bitmap_dirty) { // loop over rows for (y = 0; y < ycells; y++) { rectangle cellbounds; // make a rect that covers this row cellbounds.set(0, state.bitmap->width() - 1, y * cellypix, (y + 1) * cellypix - 1); // only display if there is data to show if (info.offset[set] + y * xcells < gfx.elements()) { // draw the individual cells for (x = 0; x < xcells; x++) { int index = info.offset[set] + y * xcells + x; // update the bounds for this cell cellbounds.min_x = x * cellxpix; cellbounds.max_x = (x + 1) * cellxpix - 1; // only render if there is data if (index < gfx.elements()) gfxset_draw_item(machine, gfx, index, *state.bitmap, cellbounds.min_x, cellbounds.min_y, info.color[set], info.rotate[set], info.palette[set]); // otherwise, fill with transparency else state.bitmap->fill(0, cellbounds); } } // otherwise, fill with transparency else state.bitmap->fill(0, cellbounds); } // reset the texture to force an update state.texture->set_bitmap(*state.bitmap, state.bitmap->cliprect(), TEXFORMAT_ARGB32); state.bitmap_dirty = false; } } //------------------------------------------------- // gfxset_draw_item - draw a single item into // the view //------------------------------------------------- static void gfxset_draw_item(running_machine &machine, gfx_element &gfx, int index, bitmap_rgb32 &bitmap, int dstx, int dsty, int color, int rotate, device_palette_interface *dpalette) { int width = (rotate & ORIENTATION_SWAP_XY) ? gfx.height() : gfx.width(); int height = (rotate & ORIENTATION_SWAP_XY) ? gfx.width() : gfx.height(); const rgb_t *palette = dpalette->palette()->entry_list_raw() + gfx.colorbase() + color * gfx.granularity(); int x, y; // loop over rows in the cell for (y = 0; y < height; y++) { uint32_t *dest = &bitmap.pix32(dsty + y, dstx); const uint8_t *src = gfx.get_data(index); // loop over columns in the cell for (x = 0; x < width; x++) { int effx = x, effy = y; const uint8_t *s; // compute effective x,y values after rotation if (!(rotate & ORIENTATION_SWAP_XY)) { if (rotate & ORIENTATION_FLIP_X) effx = gfx.width() - 1 - effx; if (rotate & ORIENTATION_FLIP_Y) effy = gfx.height() - 1 - effy; } else { if (rotate & ORIENTATION_FLIP_X) effx = gfx.height() - 1 - effx; if (rotate & ORIENTATION_FLIP_Y) effy = gfx.width() - 1 - effy; std::swap(effx, effy); } // get a pointer to the start of this source row s = src + effy * gfx.rowbytes(); // extract the pixel *dest++ = 0xff000000 | palette[s[effx]]; } } } /*************************************************************************** TILEMAP VIEWER ***************************************************************************/ //------------------------------------------------- // tilemap_handler - handler for the tilemap // viewer //------------------------------------------------- static void tilemap_handler(mame_ui_manager &mui, render_container &container, ui_gfx_state &state) { render_font *ui_font = mui.get_font(); float chwidth, chheight; render_bounds mapboxbounds; render_bounds boxbounds; int targwidth = mui.machine().render().ui_target().width(); int targheight = mui.machine().render().ui_target().height(); float titlewidth; float x0, y0; int mapboxwidth, mapboxheight; // get the size of the tilemap itself tilemap_t *tilemap = mui.machine().tilemap().find(state.tilemap.which); uint32_t mapwidth = tilemap->width(); uint32_t mapheight = tilemap->height(); if (state.tilemap.rotate & ORIENTATION_SWAP_XY) std::swap(mapwidth, mapheight); // add a half character padding for the box chheight = mui.get_line_height(); chwidth = ui_font->char_width(chheight, mui.machine().render().ui_aspect(), '0'); boxbounds.x0 = 0.0f + 0.5f * chwidth; boxbounds.x1 = 1.0f - 0.5f * chwidth; boxbounds.y0 = 0.0f + 0.5f * chheight; boxbounds.y1 = 1.0f - 0.5f * chheight; // the tilemap box bounds starts a half character in from the box mapboxbounds = boxbounds; mapboxbounds.x0 += 0.5f * chwidth; mapboxbounds.x1 -= 0.5f * chwidth; mapboxbounds.y0 += 0.5f * chheight; mapboxbounds.y1 -= 0.5f * chheight; // add space on the top for a title and a half line of padding mapboxbounds.y0 += 1.5f * chheight; // convert back to pixels mapboxwidth = (mapboxbounds.x1 - mapboxbounds.x0) * (float)targwidth; mapboxheight = (mapboxbounds.y1 - mapboxbounds.y0) * (float)targheight; // determine the maximum integral scaling factor int pixelscale = state.tilemap.zoom; if (pixelscale == 0) { int maxxscale, maxyscale; for (maxxscale = 1; mapwidth * (maxxscale + 1) < mapboxwidth; maxxscale++) { } for (maxyscale = 1; mapheight * (maxyscale + 1) < mapboxheight; maxyscale++) { } pixelscale = std::min(maxxscale, maxyscale); } // recompute the final box size mapboxwidth = std::min(mapboxwidth, int(mapwidth * pixelscale)); mapboxheight = std::min(mapboxheight, int(mapheight * pixelscale)); // recompute the bounds, centered within the existing bounds mapboxbounds.x0 += 0.5f * ((mapboxbounds.x1 - mapboxbounds.x0) - (float)mapboxwidth / (float)targwidth); mapboxbounds.x1 = mapboxbounds.x0 + (float)mapboxwidth / (float)targwidth; mapboxbounds.y0 += 0.5f * ((mapboxbounds.y1 - mapboxbounds.y0) - (float)mapboxheight / (float)targheight); mapboxbounds.y1 = mapboxbounds.y0 + (float)mapboxheight / (float)targheight; // now recompute the outer box against this new info boxbounds.x0 = mapboxbounds.x0 - 0.5f * chwidth; boxbounds.x1 = mapboxbounds.x1 + 0.5f * chwidth; boxbounds.y0 = mapboxbounds.y0 - 2.0f * chheight; boxbounds.y1 = mapboxbounds.y1 + 0.5f * chheight; // figure out the title std::ostringstream title_buf; util::stream_format(title_buf, "TILEMAP %d/%d", state.tilemap.which + 1, mui.machine().tilemap().count()); // if the mouse pointer is over a tile, add some info about its coordinates and color int32_t mouse_target_x, mouse_target_y; float mouse_x, mouse_y; bool mouse_button; render_target *mouse_target = mui.machine().ui_input().find_mouse(&mouse_target_x, &mouse_target_y, &mouse_button); if (mouse_target != nullptr && mouse_target->map_point_container(mouse_target_x, mouse_target_y, container, mouse_x, mouse_y) && mapboxbounds.x0 <= mouse_x && mapboxbounds.x1 > mouse_x && mapboxbounds.y0 <= mouse_y && mapboxbounds.y1 > mouse_y) { int xpixel = (mouse_x - mapboxbounds.x0) * targwidth; int ypixel = (mouse_y - mapboxbounds.y0) * targheight; if (state.tilemap.rotate & ORIENTATION_FLIP_X) xpixel = (mapboxwidth - 1) - xpixel; if (state.tilemap.rotate & ORIENTATION_FLIP_Y) ypixel = (mapboxheight - 1) - ypixel; if (state.tilemap.rotate & ORIENTATION_SWAP_XY) std::swap(xpixel, ypixel); uint32_t col = ((xpixel / pixelscale + state.tilemap.xoffs) / tilemap->tilewidth()) % tilemap->cols(); uint32_t row = ((ypixel / pixelscale + state.tilemap.yoffs) / tilemap->tileheight()) % tilemap->rows(); uint8_t gfxnum; uint32_t code, color; tilemap->get_info_debug(col, row, gfxnum, code, color); util::stream_format(title_buf, " @ %d,%d = GFX%d #%X:%X", col * tilemap->tilewidth(), row * tilemap->tileheight(), int(gfxnum), code, color); } else util::stream_format(title_buf, " %dx%d OFFS %d,%d", tilemap->width(), tilemap->height(), state.tilemap.xoffs, state.tilemap.yoffs); if (state.tilemap.flags != TILEMAP_DRAW_ALL_CATEGORIES) util::stream_format(title_buf, " CAT %d", state.tilemap.flags); // expand the outer box to fit the title const std::string title = title_buf.str(); titlewidth = ui_font->string_width(chheight, mui.machine().render().ui_aspect(), title.c_str()); if (boxbounds.x1 - boxbounds.x0 < titlewidth + chwidth) { boxbounds.x0 = 0.5f - 0.5f * (titlewidth + chwidth); boxbounds.x1 = boxbounds.x0 + titlewidth + chwidth; } // go ahead and draw the outer box now mui.draw_outlined_box(container, boxbounds.x0, boxbounds.y0, boxbounds.x1, boxbounds.y1, UI_GFXVIEWER_BG_COLOR); // draw the title x0 = 0.5f - 0.5f * titlewidth; y0 = boxbounds.y0 + 0.5f * chheight; for (auto ch : title) { container.add_char(x0, y0, chheight, mui.machine().render().ui_aspect(), rgb_t::white(), *ui_font, ch); x0 += ui_font->char_width(chheight, mui.machine().render().ui_aspect(), ch); } // update the bitmap tilemap_update_bitmap(mui.machine(), state, mapboxwidth / pixelscale, mapboxheight / pixelscale); // add the final quad container.add_quad(mapboxbounds.x0, mapboxbounds.y0, mapboxbounds.x1, mapboxbounds.y1, rgb_t::white(), state.texture, PRIMFLAG_BLENDMODE(BLENDMODE_ALPHA) | PRIMFLAG_TEXORIENT(state.tilemap.rotate)); // handle keyboard input tilemap_handle_keys(mui.machine(), state, mapboxwidth, mapboxheight); } //------------------------------------------------- // tilemap_handle_keys - handle keys for the // tilemap view //------------------------------------------------- static void tilemap_handle_keys(running_machine &machine, ui_gfx_state &state, int viswidth, int visheight) { // handle tilemap selection (open bracket,close bracket) if (machine.ui_input().pressed(IPT_UI_PREV_GROUP) && state.tilemap.which > 0) { state.tilemap.which--; state.bitmap_dirty = true; } if (machine.ui_input().pressed(IPT_UI_NEXT_GROUP) && state.tilemap.which < machine.tilemap().count() - 1) { state.tilemap.which++; state.bitmap_dirty = true; } // cache some info in locals tilemap_t *tilemap = machine.tilemap().find(state.tilemap.which); uint32_t mapwidth = tilemap->width(); uint32_t mapheight = tilemap->height(); // handle zoom (minus,plus) if (machine.ui_input().pressed(IPT_UI_ZOOM_OUT) && state.tilemap.zoom > 0) { state.tilemap.zoom--; state.bitmap_dirty = true; if (state.tilemap.zoom != 0) machine.popmessage("Zoom = %d", state.tilemap.zoom); else machine.popmessage("Zoom Auto"); } if (machine.ui_input().pressed(IPT_UI_ZOOM_IN) && state.tilemap.zoom < 8) { state.tilemap.zoom++; state.bitmap_dirty = true; machine.popmessage("Zoom = %d", state.tilemap.zoom); } // handle rotation (R) if (machine.ui_input().pressed(IPT_UI_ROTATE)) { state.tilemap.rotate = orientation_add(ROT90, state.tilemap.rotate); state.bitmap_dirty = true; } // return to (0,0) (HOME) if( machine.ui_input().pressed(IPT_UI_HOME)) { state.tilemap.xoffs = 0; state.tilemap.yoffs = 0; state.bitmap_dirty = true; } // handle flags (category) if (machine.ui_input().pressed(IPT_UI_PAGE_UP) && state.tilemap.flags != TILEMAP_DRAW_ALL_CATEGORIES) { if (state.tilemap.flags > 0) { state.tilemap.flags--; machine.popmessage("Category = %d", state.tilemap.flags); } else { state.tilemap.flags = TILEMAP_DRAW_ALL_CATEGORIES; machine.popmessage("Category All"); } state.bitmap_dirty = true; } if (machine.ui_input().pressed(IPT_UI_PAGE_DOWN) && (state.tilemap.flags < TILEMAP_DRAW_CATEGORY_MASK || (state.tilemap.flags == TILEMAP_DRAW_ALL_CATEGORIES))) { if (state.tilemap.flags == TILEMAP_DRAW_ALL_CATEGORIES) state.tilemap.flags = 0; else state.tilemap.flags++; state.bitmap_dirty = true; machine.popmessage("Category = %d", state.tilemap.flags); } // handle navigation (up,down,left,right), taking orientation into account int step = 8; // this may be applied more than once if multiple directions are pressed if (machine.input().code_pressed(KEYCODE_LSHIFT)) step = 1; if (machine.input().code_pressed(KEYCODE_LCONTROL)) step = 64; if (machine.ui_input().pressed_repeat(IPT_UI_UP, 4)) { if (state.tilemap.rotate & ORIENTATION_SWAP_XY) state.tilemap.xoffs -= (state.tilemap.rotate & ORIENTATION_FLIP_Y) ? -step : step; else state.tilemap.yoffs -= (state.tilemap.rotate & ORIENTATION_FLIP_Y) ? -step : step; state.bitmap_dirty = true; } if (machine.ui_input().pressed_repeat(IPT_UI_DOWN, 4)) { if (state.tilemap.rotate & ORIENTATION_SWAP_XY) state.tilemap.xoffs += (state.tilemap.rotate & ORIENTATION_FLIP_Y) ? -step : step; else state.tilemap.yoffs += (state.tilemap.rotate & ORIENTATION_FLIP_Y) ? -step : step; state.bitmap_dirty = true; } if (machine.ui_input().pressed_repeat(IPT_UI_LEFT, 6)) { if (state.tilemap.rotate & ORIENTATION_SWAP_XY) state.tilemap.yoffs -= (state.tilemap.rotate & ORIENTATION_FLIP_X) ? -step : step; else state.tilemap.xoffs -= (state.tilemap.rotate & ORIENTATION_FLIP_X) ? -step : step; state.bitmap_dirty = true; } if (machine.ui_input().pressed_repeat(IPT_UI_RIGHT, 6)) { if (state.tilemap.rotate & ORIENTATION_SWAP_XY) state.tilemap.yoffs += (state.tilemap.rotate & ORIENTATION_FLIP_X) ? -step : step; else state.tilemap.xoffs += (state.tilemap.rotate & ORIENTATION_FLIP_X) ? -step : step; state.bitmap_dirty = true; } // clamp within range while (state.tilemap.xoffs < 0) state.tilemap.xoffs += mapwidth; while (state.tilemap.xoffs >= mapwidth) state.tilemap.xoffs -= mapwidth; while (state.tilemap.yoffs < 0) state.tilemap.yoffs += mapheight; while (state.tilemap.yoffs >= mapheight) state.tilemap.yoffs -= mapheight; } //------------------------------------------------- // tilemap_update_bitmap - update the bitmap // for the tilemap view //------------------------------------------------- static void tilemap_update_bitmap(running_machine &machine, ui_gfx_state &state, int width, int height) { // swap the coordinates back if they were talking about a rotated surface if (state.tilemap.rotate & ORIENTATION_SWAP_XY) std::swap(width, height); // realloc the bitmap if it is too small if (state.bitmap == nullptr || state.texture == nullptr || state.bitmap->width() != width || state.bitmap->height() != height) { // free the old stuff machine.render().texture_free(state.texture); global_free(state.bitmap); // allocate new stuff state.bitmap = global_alloc(bitmap_rgb32(width, height)); state.texture = machine.render().texture_alloc(); state.texture->set_bitmap(*state.bitmap, state.bitmap->cliprect(), TEXFORMAT_RGB32); // force a redraw state.bitmap_dirty = true; } // handle the redraw if (state.bitmap_dirty) { state.bitmap->fill(0); tilemap_t *tilemap = machine.tilemap().find(state.tilemap.which); screen_device *first_screen = screen_device_iterator(machine.root_device()).first(); if (first_screen) { tilemap->draw_debug(*first_screen, *state.bitmap, state.tilemap.xoffs, state.tilemap.yoffs, state.tilemap.flags); } // reset the texture to force an update state.texture->set_bitmap(*state.bitmap, state.bitmap->cliprect(), TEXFORMAT_RGB32); state.bitmap_dirty = false; } }
35.718891
185
0.655963
[ "render" ]
062660f6dfba2b90f8abb64b3c5db47866f8827d
1,791
cpp
C++
tests/unit/model/graph_handle_test.cpp
AO-StreetArt/CLyman
b4f3c6fce1c41fb47a6a9d89bb40c05466d0d092
[ "BSL-1.0", "Apache-2.0", "BSD-3-Clause" ]
1
2018-09-14T13:29:03.000Z
2018-09-14T13:29:03.000Z
tests/unit/model/graph_handle_test.cpp
AO-StreetArt/CLyman
b4f3c6fce1c41fb47a6a9d89bb40c05466d0d092
[ "BSL-1.0", "Apache-2.0", "BSD-3-Clause" ]
62
2016-04-18T06:31:45.000Z
2019-08-22T23:55:22.000Z
tests/unit/model/graph_handle_test.cpp
AO-StreetArt/CLyman
b4f3c6fce1c41fb47a6a9d89bb40c05466d0d092
[ "BSL-1.0", "Apache-2.0", "BSD-3-Clause" ]
null
null
null
/* Apache2 License Notice Copyright 2017 Alex Barry 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 <string> #include <iostream> #include <cmath> #include "include/animation_graph_handle.h" #include "catch.hpp" TEST_CASE( "Test Animation Graph Handle Data Structure", "[unit]" ) { //Tolerance const float TOLERANCE = 0.1f; // Build test graph handle AnimationGraphHandle test_handle; REQUIRE(test_handle.get_lh_type() == ""); REQUIRE(std::abs(test_handle.get_lh_x()) - 0.0 < TOLERANCE); REQUIRE(std::abs(test_handle.get_lh_y()) - 0.0 < TOLERANCE); REQUIRE(test_handle.get_rh_type() == ""); REQUIRE(std::abs(test_handle.get_rh_x()) - 0.0 < TOLERANCE); REQUIRE(std::abs(test_handle.get_rh_y()) - 0.0 < TOLERANCE); test_handle.set_lh_type(std::string("vector")); test_handle.set_lh_x(10.0); test_handle.set_lh_y(5.0); test_handle.set_rh_type(std::string("free")); test_handle.set_rh_x(4.0); test_handle.set_rh_y(3.0); REQUIRE(test_handle.get_lh_type() == "vector"); REQUIRE(std::abs(test_handle.get_lh_x()) - 10.0 < TOLERANCE); REQUIRE(std::abs(test_handle.get_lh_y()) - 5.0 < TOLERANCE); REQUIRE(test_handle.get_rh_type() == "free"); REQUIRE(std::abs(test_handle.get_rh_x()) - 4.0 < TOLERANCE); REQUIRE(std::abs(test_handle.get_rh_y()) - 3.0 < TOLERANCE); }
37.3125
72
0.731435
[ "vector" ]
062d1c4d63ac120db0bf8d87ac3d3ee07a6a70d7
601
cpp
C++
CodeForces/Contest/Good Bye 2016/A/code.cpp
sjj118/OI-Code
964ea6e799d14010f305c7e4aee269d860a781f7
[ "MIT" ]
null
null
null
CodeForces/Contest/Good Bye 2016/A/code.cpp
sjj118/OI-Code
964ea6e799d14010f305c7e4aee269d860a781f7
[ "MIT" ]
null
null
null
CodeForces/Contest/Good Bye 2016/A/code.cpp
sjj118/OI-Code
964ea6e799d14010f305c7e4aee269d860a781f7
[ "MIT" ]
null
null
null
#include<iostream> #include<cstdio> #include<cstdlib> #include<cmath> #include<ctime> #include<cstring> #include<algorithm> #include<vector> #include<map> #include<set> #include<queue> #define cls(a) memset(a,0,sizeof(a)) #define pb push_back #define mp make_pair #define fi first #define se second #define rg register #define rep(i,x,y) for(rg int i=(x);i<=(y);++i) #define per(i,x,y) for(rg int i=(x);i>=(y);--i) using namespace std; typedef long long LL; int n,k; int main(){ scanf("%d%d",&n,&k); int t=240-k; int ans=0; rep(i,1,n){ if(t>=5*i)++ans,t-=5*i; } printf("%d",ans); return 0; }
18.212121
47
0.660566
[ "vector" ]
063208e3fad72a09f54a51a65804cbc8b3dca2ad
1,269
cpp
C++
test/unit/math/prim/fun/linspaced_array_test.cpp
HaoZeke/math
fdf7f70dceed60f3b3f93137c6ac123a457b80a3
[ "BSD-3-Clause" ]
1
2020-05-18T13:10:50.000Z
2020-05-18T13:10:50.000Z
test/unit/math/prim/fun/linspaced_array_test.cpp
HaoZeke/math
fdf7f70dceed60f3b3f93137c6ac123a457b80a3
[ "BSD-3-Clause" ]
2
2019-07-23T12:45:30.000Z
2020-05-01T20:43:03.000Z
test/unit/math/prim/fun/linspaced_array_test.cpp
SteveBronder/math
3f21445458866897842878f65941c6bcb90641c2
[ "BSD-3-Clause" ]
null
null
null
#include <stan/math/prim.hpp> #include <test/unit/math/prim/fun/expect_matrix_eq.hpp> #include <gtest/gtest.h> #include <limits> #include <vector> void expect_linspaced_array(int K, double low, double high, const std::vector<double>& expected) { std::vector<double> found = stan::math::linspaced_array(K, low, high); expect_std_vector_eq(expected, found); } TEST(MathFunctions, linspaced_array) { expect_linspaced_array(0, 1, 5, {}); expect_linspaced_array(1, 1, 5, {5}); expect_linspaced_array(5, 1, 5, {1, 2, 3, 4, 5}); expect_linspaced_array(5, -2, 2, {-2, -1, 0, 1, 2}); } TEST(MathFunctions, linspaced_array_throw) { using stan::math::linspaced_array; double inf = std::numeric_limits<double>::infinity(); double nan = std::numeric_limits<double>::quiet_NaN(); int K = 5; double low = -2; double high = 6; EXPECT_THROW(linspaced_array(-1, low, high), std::domain_error); EXPECT_THROW(linspaced_array(K, inf, high), std::domain_error); EXPECT_THROW(linspaced_array(K, nan, high), std::domain_error); EXPECT_THROW(linspaced_array(K, low, low - 1), std::domain_error); EXPECT_THROW(linspaced_array(K, low, inf), std::domain_error); EXPECT_THROW(linspaced_array(K, low, nan), std::domain_error); }
34.297297
72
0.698188
[ "vector" ]
063b131861e9aafebdd80ad075b4ddb1265fca63
751
hpp
C++
src/daemon/daemon.hpp
cognitom/processwarp
1c70e76578821907fa8ab28923041300232d32d2
[ "MIT" ]
null
null
null
src/daemon/daemon.hpp
cognitom/processwarp
1c70e76578821907fa8ab28923041300232d32d2
[ "MIT" ]
null
null
null
src/daemon/daemon.hpp
cognitom/processwarp
1c70e76578821907fa8ab28923041300232d32d2
[ "MIT" ]
null
null
null
#pragma once #include <uv.h> #include <picojson.h> #include <string> #include "daemon_define.hpp" #include "logger_syslog.hpp" namespace processwarp { class Daemon { public: Daemon(); int entry(int argc, char* argv[]); private: /** Syslog logger. */ Logger::Syslog logger; /** Daemon run mode. */ DaemonRunMode::Type run_mode; /** Configuration. */ picojson::object config; /** Main loop of libuv. */ uv_loop_t* loop; int daemonize(); bool initialize_logger(); bool initialize_message(); int main_loop(); bool read_config(const std::string& file); bool read_options(int argc, char* argv[]); void show_help(bool is_error, const std::string& command); bool subprocess_config(); }; } // namespace processwarp
20.297297
60
0.685752
[ "object" ]
063e0bcbc3cd4466ab71e56d6d5b71454cdf57f5
907
cpp
C++
basespecs.cpp
devkral/simplegraph
ffb90576c6fa03237abdc1cb77ae1011889e9668
[ "BSD-3-Clause" ]
null
null
null
basespecs.cpp
devkral/simplegraph
ffb90576c6fa03237abdc1cb77ae1011889e9668
[ "BSD-3-Clause" ]
null
null
null
basespecs.cpp
devkral/simplegraph
ffb90576c6fa03237abdc1cb77ae1011889e9668
[ "BSD-3-Clause" ]
null
null
null
#include <iostream> #include "basespecs.h" namespace sgraph{ debugactor::debugactor(uint8_t loglevel) : sgactor(0,-1, 1, 1) { this->loglevel=loglevel; } void debugactor::enter(const std::vector<sgstreamspec*> &in,const std::vector<std::string> &out) { if (out.size()>0) { throw(sgraphException("outstreams are not allowed")); } /**for (sgstreamspec *elem: in) { if (elem==0) { throw(sgraphStreamException("stream")); } }*/ // getStreams should protect already } void debugactor::run(const sginstreams in) { unsigned int count=0; for (sginstream elem: in) { stream_log* logob=static_cast<stream_log*>(elem[0].get()); if (logob->loglevel==0){ std::cout << "Message: Stream " << count << ": " << logob->text << std::endl; } else if (logob->loglevel<=this->loglevel){ std::cerr << "Error: Stream " << count << ": " << logob->text << std::endl; } count++; } } }
19.297872
96
0.635061
[ "vector" ]
063ecebe553c964e7a26c40a59fc03f4e9b34183
9,904
cpp
C++
Arduino/Arduino_E-Motion/AndroidAccessory.cpp
pdulapalli/E-Motion
f68a0d33b26d4bd8a195343c11e02741e5a2c838
[ "Apache-2.0" ]
null
null
null
Arduino/Arduino_E-Motion/AndroidAccessory.cpp
pdulapalli/E-Motion
f68a0d33b26d4bd8a195343c11e02741e5a2c838
[ "Apache-2.0" ]
null
null
null
Arduino/Arduino_E-Motion/AndroidAccessory.cpp
pdulapalli/E-Motion
f68a0d33b26d4bd8a195343c11e02741e5a2c838
[ "Apache-2.0" ]
null
null
null
/* * Copyright (C) 2011 The Android Open Source Project * * 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 "Max3421e.h" #include "UsbHost.h" #include "AndroidAccessory.h" #define USB_ACCESSORY_VENDOR_ID 0x18D1 #define USB_ACCESSORY_PRODUCT_ID 0x2D00 #define USB_ACCESSORY_ADB_PRODUCT_ID 0x2D01 #define ACCESSORY_STRING_MANUFACTURER 0 #define ACCESSORY_STRING_MODEL 1 #define ACCESSORY_STRING_DESCRIPTION 2 #define ACCESSORY_STRING_VERSION 3 #define ACCESSORY_STRING_URI 4 #define ACCESSORY_STRING_SERIAL 5 #define ACCESSORY_GET_PROTOCOL 51 #define ACCESSORY_SEND_STRING 52 #define ACCESSORY_START 53 AndroidAccessory::AndroidAccessory(const char *manufacturer, const char *model, const char *description, const char *version, const char *uri, const char *serial) : manufacturer(manufacturer), model(model), description(description), version(version), uri(uri), serial(serial), connected(false) { } boolean AndroidAccessory::begin(void) { powerOn(); return true; // For forward compatibility with v2.x of the library } void AndroidAccessory::powerOn(void) { max.powerOn(); delay(200); } int AndroidAccessory::getProtocol(byte addr) { uint16_t protocol = -1; usb.ctrlReq(addr, 0, USB_SETUP_DEVICE_TO_HOST | USB_SETUP_TYPE_VENDOR | USB_SETUP_RECIPIENT_DEVICE, ACCESSORY_GET_PROTOCOL, 0, 0, 0, 2, (char *)&protocol); return protocol; } void AndroidAccessory::sendString(byte addr, int index, const char *str) { usb.ctrlReq(addr, 0, USB_SETUP_HOST_TO_DEVICE | USB_SETUP_TYPE_VENDOR | USB_SETUP_RECIPIENT_DEVICE, ACCESSORY_SEND_STRING, 0, 0, index, strlen(str) + 1, (char *)str); } bool AndroidAccessory::switchDevice(byte addr) { int protocol = getProtocol(addr); Serial.println(protocol); if (protocol == 2) { Serial.print(F("device supports protcol 2\n")); } else { Serial.print(F("could not read device protocol version\n")); return false; } sendString(addr, ACCESSORY_STRING_MANUFACTURER, manufacturer); sendString(addr, ACCESSORY_STRING_MODEL, model); sendString(addr, ACCESSORY_STRING_DESCRIPTION, description); sendString(addr, ACCESSORY_STRING_VERSION, version); sendString(addr, ACCESSORY_STRING_URI, uri); sendString(addr, ACCESSORY_STRING_SERIAL, serial); usb.ctrlReq(addr, 0, USB_SETUP_HOST_TO_DEVICE | USB_SETUP_TYPE_VENDOR | USB_SETUP_RECIPIENT_DEVICE, ACCESSORY_START, 0, 0, 0, 0, NULL); return true; } // Finds the first bulk IN and bulk OUT endpoints bool AndroidAccessory::findEndpoints(byte addr, EP_RECORD *inEp, EP_RECORD *outEp) { int len; byte err; uint8_t *p; err = usb.getConfDescr(addr, 0, 4, 0, (char *)descBuff); if (err) { Serial.print(F("Can't get config descriptor length\n")); return false; } len = descBuff[2] | ((int)descBuff[3] << 8); Serial.print(len); if (len > sizeof(descBuff)) { Serial.print(F("config descriptor too large\n")); /* might want to truncate here */ return false; } err = usb.getConfDescr(addr, 0, len, 0, (char *)descBuff); if (err) { Serial.print(F("Can't get config descriptor\n")); return false; } p = descBuff; inEp->epAddr = 0; outEp->epAddr = 0; while (p < (descBuff + len)){ uint8_t descLen = p[0]; uint8_t descType = p[1]; USB_ENDPOINT_DESCRIPTOR *epDesc; EP_RECORD *ep; switch (descType) { case USB_DESCRIPTOR_CONFIGURATION: Serial.print(F("config desc\n")); break; case USB_DESCRIPTOR_INTERFACE: Serial.print(F("interface desc\n")); break; case USB_DESCRIPTOR_ENDPOINT: Serial.print(F("endpoint\n")); epDesc = (USB_ENDPOINT_DESCRIPTOR *)p; if (!inEp->epAddr && (epDesc->bEndpointAddress & 0x80)) ep = inEp; else if (!outEp->epAddr) ep = outEp; else ep = NULL; if (ep) { ep->epAddr = epDesc->bEndpointAddress & 0x7f; ep->Attr = epDesc->bmAttributes; ep->MaxPktSize = epDesc->wMaxPacketSize; ep->sndToggle = bmSNDTOG0; ep->rcvToggle = bmRCVTOG0; } break; default: Serial.print(F("unkown desc type ")); Serial.println( descType, HEX); break; } p += descLen; } if (!(inEp->epAddr && outEp->epAddr)) Serial.println(F("can't find accessory endpoints")); return inEp->epAddr && outEp->epAddr; } bool AndroidAccessory::configureAndroid(void) { byte err; EP_RECORD inEp, outEp; if (!findEndpoints(1, &inEp, &outEp)) return false; memset(&epRecord, 0x0, sizeof(epRecord)); epRecord[inEp.epAddr] = inEp; if (outEp.epAddr != inEp.epAddr) epRecord[outEp.epAddr] = outEp; in = inEp.epAddr; out = outEp.epAddr; Serial.println(inEp.epAddr, HEX); Serial.println(outEp.epAddr, HEX); epRecord[0] = *(usb.getDevTableEntry(0,0)); usb.setDevTableEntry(1, epRecord); err = usb.setConf( 1, 0, 1 ); if (err) { Serial.print(F("Can't set config to 1\n")); return false; } usb.setUsbTaskState( USB_STATE_RUNNING ); return true; } void AndroidAccessory::refresh(void) { max.Task(); usb.Task(); } bool AndroidAccessory::isConnected(void) { USB_DEVICE_DESCRIPTOR *devDesc = (USB_DEVICE_DESCRIPTOR *) descBuff; byte err; refresh(); if (!connected && usb.getUsbTaskState() >= USB_STATE_CONFIGURING && usb.getUsbTaskState() != USB_STATE_RUNNING) { Serial.print(F("\nDevice addressed... ")); Serial.print(F("Requesting device descriptor.\n")); err = usb.getDevDescr(1, 0, 0x12, (char *) devDesc); if (err) { Serial.print(F("\nDevice descriptor cannot be retrieved. Trying again\n")); return false; } if (isAccessoryDevice(devDesc)) { Serial.print(F("found android acessory device\n")); connected = configureAndroid(); } else { Serial.print(F("found possible device. swithcing to serial mode\n")); switchDevice(1); } } else if (usb.getUsbTaskState() == USB_DETACHED_SUBSTATE_WAIT_FOR_DEVICE) { if (connected) Serial.println(F("disconnect\n")); connected = false; } return connected; } bool AndroidAccessory::dataBufferIsEmpty() { return (numBytesInDataBuff == nextByteInDataBuffOffset); } void AndroidAccessory::refillDataBuffer() { int bytesRead = 0; numBytesInDataBuff = nextByteInDataBuffOffset = 0; // TODO: Add is connected check? bytesRead = read(dataBuff, sizeof(dataBuff)); if (bytesRead >= 1) { numBytesInDataBuff = bytesRead; } } int AndroidAccessory::read() { if (dataBufferIsEmpty()) { refillDataBuffer(); } return dataBufferIsEmpty() ? -1 : dataBuff[nextByteInDataBuffOffset++]; } int AndroidAccessory::peek() { if (dataBufferIsEmpty()) { refillDataBuffer(); } return dataBufferIsEmpty() ? -1 : dataBuff[nextByteInDataBuffOffset]; } int AndroidAccessory::available() { // Strictly speaking this doesn't meet the "This is only for bytes // that have already arrived" definition from // <http://arduino.cc/en/Reference/StreamAvailable> but since the // data isn't handled by an ISR it's the only way to avoid hanging // waiting for `available()` to return true. if (dataBufferIsEmpty()) { refillDataBuffer(); } return numBytesInDataBuff - nextByteInDataBuffOffset; } int AndroidAccessory::read(void *buff, int len, unsigned int nakLimit) { return usb.newInTransfer(1, in, len, (char *)buff, nakLimit); } size_t AndroidAccessory::write(uint8_t *buff, size_t len) { usb.outTransfer(1, out, len, (char *)buff); return len; } size_t AndroidAccessory::write(uint8_t c) { return write(&c, 1); } void AndroidAccessory::flush() { /* "Waits for the transmission of outgoing [...] data to complete." from <http://arduino.cc/en/Serial/Flush> We're treating this as a no-op at the moment. */ }
28.790698
88
0.57815
[ "model" ]
06422ed3947d5a885885a27b046cdeeee2d8933a
46,542
cpp
C++
src/postgres/backend/utils/sort/tuplestore.cpp
jessesleeping/my_peloton
a19426cfe34a04692a11008eaffc9c3c9b49abc4
[ "Apache-2.0" ]
6
2017-04-28T00:38:52.000Z
2018-11-06T07:06:49.000Z
src/postgres/backend/utils/sort/tuplestore.cpp
jessesleeping/my_peloton
a19426cfe34a04692a11008eaffc9c3c9b49abc4
[ "Apache-2.0" ]
57
2016-03-19T22:27:55.000Z
2017-07-08T00:41:51.000Z
src/postgres/backend/utils/sort/tuplestore.cpp
eric-haibin-lin/pelotondb
904d6bbd041a0498ee0e034d4f9f9f27086c3cab
[ "Apache-2.0" ]
4
2016-07-17T20:44:56.000Z
2018-06-27T01:01:36.000Z
/*------------------------------------------------------------------------- * * tuplestore.c * Generalized routines for temporary tuple storage. * * This module handles temporary storage of tuples for purposes such * as Materialize nodes, hashjoin batch files, etc. It is essentially * a dumbed-down version of tuplesort.c; it does no sorting of tuples * but can only store and regurgitate a sequence of tuples. However, * because no sort is required, it is allowed to start reading the sequence * before it has all been written. This is particularly useful for cursors, * because it allows random access within the already-scanned portion of * a query without having to process the underlying scan to completion. * Also, it is possible to support multiple independent read pointers. * * A temporary file is used to handle the data if it exceeds the * space limit specified by the caller. * * The (approximate) amount of memory allowed to the tuplestore is specified * in kilobytes by the caller. We absorb tuples and simply store them in an * in-memory array as long as we haven't exceeded maxKBytes. If we do exceed * maxKBytes, we dump all the tuples into a temp file and then read from that * when needed. * * Upon creation, a tuplestore supports a single read pointer, numbered 0. * Additional read pointers can be created using tuplestore_alloc_read_pointer. * Mark/restore behavior is supported by copying read pointers. * * When the caller requests backward-scan capability, we write the temp file * in a format that allows either forward or backward scan. Otherwise, only * forward scan is allowed. A request for backward scan must be made before * putting any tuples into the tuplestore. Rewind is normally allowed but * can be turned off via tuplestore_set_eflags; turning off rewind for all * read pointers enables truncation of the tuplestore at the oldest read point * for minimal memory usage. (The caller must explicitly call tuplestore_trim * at appropriate times for truncation to actually happen.) * * Note: in TSS_WRITEFILE state, the temp file's seek position is the * current write position, and the write-position variables in the tuplestore * aren't kept up to date. Similarly, in TSS_READFILE state the temp file's * seek position is the active read pointer's position, and that read pointer * isn't kept up to date. We update the appropriate variables using ftell() * before switching to the other state or activating a different read pointer. * * * Portions Copyright (c) 1996-2015, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * * IDENTIFICATION * src/backend/utils/sort/tuplestore.c * *------------------------------------------------------------------------- */ #include "postgres.h" #include <limits.h> #include "access/htup_details.h" #include "commands/tablespace.h" #include "executor/executor.h" #include "miscadmin.h" #include "storage/buffile.h" #include "utils/memutils.h" #include "utils/resowner.h" /* * Possible states of a Tuplestore object. These denote the states that * persist between calls of Tuplestore routines. */ typedef enum { TSS_INMEM, /* Tuples still fit in memory */ TSS_WRITEFILE, /* Writing to temp file */ TSS_READFILE /* Reading from temp file */ } TupStoreStatus; /* * State for a single read pointer. If we are in state INMEM then all the * read pointers' "current" fields denote the read positions. In state * WRITEFILE, the file/offset fields denote the read positions. In state * READFILE, inactive read pointers have valid file/offset, but the active * read pointer implicitly has position equal to the temp file's seek position. * * Special case: if eof_reached is true, then the pointer's read position is * implicitly equal to the write position, and current/file/offset aren't * maintained. This way we need not update all the read pointers each time * we write. */ typedef struct { int eflags; /* capability flags */ bool eof_reached; /* read has reached EOF */ int current; /* next array index to read */ int file; /* temp file# */ off_t offset; /* byte offset in file */ } TSReadPointer; /* * Private state of a Tuplestore operation. */ struct Tuplestorestate { TupStoreStatus status; /* enumerated value as shown above */ int eflags; /* capability flags (OR of pointers' flags) */ bool backward; /* store extra length words in file? */ bool interXact; /* keep open through transactions? */ bool truncated; /* tuplestore_trim has removed tuples? */ int64 availMem; /* remaining memory available, in bytes */ int64 allowedMem; /* total memory allowed, in bytes */ BufFile *myfile; /* underlying file, or NULL if none */ MemoryContext context; /* memory context for holding tuples */ ResourceOwner resowner; /* resowner for holding temp files */ /* * These function pointers decouple the routines that must know what kind * of tuple we are handling from the routines that don't need to know it. * They are set up by the tuplestore_begin_xxx routines. * * (Although tuplestore.c currently only supports heap tuples, I've copied * this part of tuplesort.c so that extension to other kinds of objects * will be easy if it's ever needed.) * * Function to copy a supplied input tuple into palloc'd space. (NB: we * assume that a single pfree() is enough to release the tuple later, so * the representation must be "flat" in one palloc chunk.) state->availMem * must be decreased by the amount of space used. */ void *(*copytup) (Tuplestorestate *state, void *tup); /* * Function to write a stored tuple onto tape. The representation of the * tuple on tape need not be the same as it is in memory; requirements on * the tape representation are given below. After writing the tuple, * pfree() it, and increase state->availMem by the amount of memory space * thereby released. */ void (*writetup) (Tuplestorestate *state, void *tup); /* * Function to read a stored tuple from tape back into memory. 'len' is * the already-read length of the stored tuple. Create and return a * palloc'd copy, and decrease state->availMem by the amount of memory * space consumed. */ void *(*readtup) (Tuplestorestate *state, unsigned int len); /* * This array holds pointers to tuples in memory if we are in state INMEM. * In states WRITEFILE and READFILE it's not used. * * When memtupdeleted > 0, the first memtupdeleted pointers are already * released due to a tuplestore_trim() operation, but we haven't expended * the effort to slide the remaining pointers down. These unused pointers * are set to NULL to catch any invalid accesses. Note that memtupcount * includes the deleted pointers. */ void **memtuples; /* array of pointers to palloc'd tuples */ int memtupdeleted; /* the first N slots are currently unused */ int memtupcount; /* number of tuples currently present */ int memtupsize; /* allocated length of memtuples array */ bool growmemtuples; /* memtuples' growth still underway? */ /* * These variables are used to keep track of the current positions. * * In state WRITEFILE, the current file seek position is the write point; * in state READFILE, the write position is remembered in writepos_xxx. * (The write position is the same as EOF, but since BufFileSeek doesn't * currently implement SEEK_END, we have to remember it explicitly.) */ TSReadPointer *readptrs; /* array of read pointers */ int activeptr; /* index of the active read pointer */ int readptrcount; /* number of pointers currently valid */ int readptrsize; /* allocated length of readptrs array */ int writepos_file; /* file# (valid if READFILE state) */ off_t writepos_offset; /* offset (valid if READFILE state) */ }; #define COPYTUP(state,tup) ((*(state)->copytup) (state, tup)) #define WRITETUP(state,tup) ((*(state)->writetup) (state, tup)) #define READTUP(state,len) ((*(state)->readtup) (state, len)) #define LACKMEM(state) ((state)->availMem < 0) #define USEMEM(state,amt) ((state)->availMem -= (amt)) #define FREEMEM(state,amt) ((state)->availMem += (amt)) /*-------------------- * * NOTES about on-tape representation of tuples: * * We require the first "unsigned int" of a stored tuple to be the total size * on-tape of the tuple, including itself (so it is never zero). * The remainder of the stored tuple * may or may not match the in-memory representation of the tuple --- * any conversion needed is the job of the writetup and readtup routines. * * If state->backward is true, then the stored representation of * the tuple must be followed by another "unsigned int" that is a copy of the * length --- so the total tape space used is actually sizeof(unsigned int) * more than the stored length value. This allows read-backwards. When * state->backward is not set, the write/read routines may omit the extra * length word. * * writetup is expected to write both length words as well as the tuple * data. When readtup is called, the tape is positioned just after the * front length word; readtup must read the tuple data and advance past * the back length word (if present). * * The write/read routines can make use of the tuple description data * stored in the Tuplestorestate record, if needed. They are also expected * to adjust state->availMem by the amount of memory space (not tape space!) * released or consumed. There is no error return from either writetup * or readtup; they should ereport() on failure. * * * NOTES about memory consumption calculations: * * We count space allocated for tuples against the maxKBytes limit, * plus the space used by the variable-size array memtuples. * Fixed-size space (primarily the BufFile I/O buffer) is not counted. * We don't worry about the size of the read pointer array, either. * * Note that we count actual space used (as shown by GetMemoryChunkSpace) * rather than the originally-requested size. This is important since * palloc can add substantial overhead. It's not a complete answer since * we won't count any wasted space in palloc allocation blocks, but it's * a lot better than what we were doing before 7.3. * *-------------------- */ static Tuplestorestate *tuplestore_begin_common(int eflags, bool interXact, int maxKBytes); static void tuplestore_puttuple_common(Tuplestorestate *state, void *tuple); static void dumptuples(Tuplestorestate *state); static unsigned int getlen(Tuplestorestate *state, bool eofOK); static void *copytup_heap(Tuplestorestate *state, void *tup); static void writetup_heap(Tuplestorestate *state, void *tup); static void *readtup_heap(Tuplestorestate *state, unsigned int len); /* * tuplestore_begin_xxx * * Initialize for a tuple store operation. */ static Tuplestorestate * tuplestore_begin_common(int eflags, bool interXact, int maxKBytes) { Tuplestorestate *state; state = (Tuplestorestate *) palloc0(sizeof(Tuplestorestate)); state->status = TSS_INMEM; state->eflags = eflags; state->interXact = interXact; state->truncated = false; state->allowedMem = maxKBytes * 1024L; state->availMem = state->allowedMem; state->myfile = NULL; state->context = CurrentMemoryContext; state->resowner = CurrentResourceOwner; state->memtupdeleted = 0; state->memtupcount = 0; state->memtupsize = 1024; /* initial guess */ state->growmemtuples = true; state->memtuples = (void **) palloc(state->memtupsize * sizeof(void *)); USEMEM(state, GetMemoryChunkSpace(state->memtuples)); state->activeptr = 0; state->readptrcount = 1; state->readptrsize = 8; /* arbitrary */ state->readptrs = (TSReadPointer *) palloc(state->readptrsize * sizeof(TSReadPointer)); state->readptrs[0].eflags = eflags; state->readptrs[0].eof_reached = false; state->readptrs[0].current = 0; return state; } /* * tuplestore_begin_heap * * Create a new___ tuplestore; other types of tuple stores (other than * "heap" tuple stores, for heap tuples) are possible, but not presently * implemented. * * randomAccess: if true, both forward and backward accesses to the * tuple store are allowed. * * interXact: if true, the files used for on-disk storage persist beyond the * end of the current transaction. NOTE: It's the caller's responsibility to * create such a tuplestore in a memory context and resource owner that will * also survive transaction boundaries, and to ensure the tuplestore is closed * when it's no longer wanted. * * maxKBytes: how much data to store in memory (any data beyond this * amount is paged to disk). When in doubt, use work_mem. */ Tuplestorestate * tuplestore_begin_heap(bool randomAccess, bool interXact, int maxKBytes) { Tuplestorestate *state; int eflags; /* * This interpretation of the meaning of randomAccess is compatible with * the pre-8.3 behavior of tuplestores. */ eflags = randomAccess ? (EXEC_FLAG_BACKWARD | EXEC_FLAG_REWIND) : (EXEC_FLAG_REWIND); state = tuplestore_begin_common(eflags, interXact, maxKBytes); state->copytup = copytup_heap; state->writetup = writetup_heap; state->readtup = readtup_heap; return state; } /* * tuplestore_set_eflags * * Set the capability flags for read pointer 0 at a finer grain than is * allowed by tuplestore_begin_xxx. This must be called before inserting * any data into the tuplestore. * * eflags is a bitmask following the meanings used for executor node * startup flags (see executor.h). tuplestore pays attention to these bits: * EXEC_FLAG_REWIND need rewind to start * EXEC_FLAG_BACKWARD need backward fetch * If tuplestore_set_eflags is not called, REWIND is allowed, and BACKWARD * is set per "randomAccess" in the tuplestore_begin_xxx call. * * NOTE: setting BACKWARD without REWIND means the pointer can read backwards, * but not further than the truncation point (the furthest-back read pointer * position at the time of the last tuplestore_trim call). */ void tuplestore_set_eflags(Tuplestorestate *state, int eflags) { int i; if (state->status != TSS_INMEM || state->memtupcount != 0) elog(ERROR, "too late to call tuplestore_set_eflags"); state->readptrs[0].eflags = eflags; for (i = 1; i < state->readptrcount; i++) eflags |= state->readptrs[i].eflags; state->eflags = eflags; } /* * tuplestore_alloc_read_pointer - allocate another read pointer. * * Returns the pointer's index. * * The new___ pointer initially copies the position of read pointer 0. * It can have its own eflags, but if any data has been inserted into * the tuplestore, these eflags must not represent an increase in * requirements. */ int tuplestore_alloc_read_pointer(Tuplestorestate *state, int eflags) { /* Check for possible increase of requirements */ if (state->status != TSS_INMEM || state->memtupcount != 0) { if ((state->eflags | eflags) != state->eflags) elog(ERROR, "too late to require new___ tuplestore eflags"); } /* Make room for another read pointer if needed */ if (state->readptrcount >= state->readptrsize) { int newcnt = state->readptrsize * 2; state->readptrs = (TSReadPointer *) repalloc(state->readptrs, newcnt * sizeof(TSReadPointer)); state->readptrsize = newcnt; } /* And set it up */ state->readptrs[state->readptrcount] = state->readptrs[0]; state->readptrs[state->readptrcount].eflags = eflags; state->eflags |= eflags; return state->readptrcount++; } /* * tuplestore_clear * * Delete all the contents of a tuplestore, and reset its read pointers * to the start. */ void tuplestore_clear(Tuplestorestate *state) { int i; TSReadPointer *readptr; if (state->myfile) BufFileClose(state->myfile); state->myfile = NULL; if (state->memtuples) { for (i = state->memtupdeleted; i < state->memtupcount; i++) { FREEMEM(state, GetMemoryChunkSpace(state->memtuples[i])); pfree(state->memtuples[i]); } } state->status = TSS_INMEM; state->truncated = false; state->memtupdeleted = 0; state->memtupcount = 0; readptr = state->readptrs; for (i = 0; i < state->readptrcount; readptr++, i++) { readptr->eof_reached = false; readptr->current = 0; } } /* * tuplestore_end * * Release resources and clean up. */ void tuplestore_end(Tuplestorestate *state) { int i; if (state->myfile) BufFileClose(state->myfile); if (state->memtuples) { for (i = state->memtupdeleted; i < state->memtupcount; i++) pfree(state->memtuples[i]); pfree(state->memtuples); } pfree(state->readptrs); pfree(state); } /* * tuplestore_select_read_pointer - make the specified read pointer active */ void tuplestore_select_read_pointer(Tuplestorestate *state, int ptr) { TSReadPointer *readptr; TSReadPointer *oldptr; Assert(ptr >= 0 && ptr < state->readptrcount); /* No work if already active */ if (ptr == state->activeptr) return; readptr = &state->readptrs[ptr]; oldptr = &state->readptrs[state->activeptr]; switch (state->status) { case TSS_INMEM: case TSS_WRITEFILE: /* no work */ break; case TSS_READFILE: /* * First, save the current read position in the pointer about to * become inactive. */ if (!oldptr->eof_reached) BufFileTell(state->myfile, &oldptr->file, &oldptr->offset); /* * We have to make the temp file's seek position equal to the * logical position of the new___ read pointer. In eof_reached * state, that's the EOF, which we have available from the saved * write position. */ if (readptr->eof_reached) { if (BufFileSeek(state->myfile, state->writepos_file, state->writepos_offset, SEEK_SET) != 0) ereport(ERROR, (errcode_for_file_access(), errmsg("could not seek in tuplestore temporary file: %m"))); } else { if (BufFileSeek(state->myfile, readptr->file, readptr->offset, SEEK_SET) != 0) ereport(ERROR, (errcode_for_file_access(), errmsg("could not seek in tuplestore temporary file: %m"))); } break; default: elog(ERROR, "invalid tuplestore state"); break; } state->activeptr = ptr; } /* * tuplestore_ateof * * Returns the active read pointer's eof_reached state. */ bool tuplestore_ateof(Tuplestorestate *state) { return state->readptrs[state->activeptr].eof_reached; } /* * Grow the memtuples[] array, if possible within our memory constraint. We * must not exceed INT_MAX tuples in memory or the caller-provided memory * limit. Return TRUE if we were able to enlarge the array, FALSE if not. * * Normally, at each increment we double the size of the array. When doing * that would exceed a limit, we attempt one last, smaller increase (and then * clear the growmemtuples flag so we don't try any more). That allows us to * use memory as fully as permitted; sticking to the pure doubling rule could * result in almost half going unused. Because availMem moves around with * tuple addition/removal, we need some rule to prevent making repeated small * increases in memtupsize, which would just be useless thrashing. The * growmemtuples flag accomplishes that and also prevents useless * recalculations in this function. */ static bool grow_memtuples(Tuplestorestate *state) { int newmemtupsize; int memtupsize = state->memtupsize; int64 memNowUsed = state->allowedMem - state->availMem; /* Forget it if we've already maxed out memtuples, per comment above */ if (!state->growmemtuples) return false; /* Select new___ value of memtupsize */ if (memNowUsed <= state->availMem) { /* * We've used no more than half of allowedMem; double our usage, * clamping at INT_MAX tuples. */ if (memtupsize < INT_MAX / 2) newmemtupsize = memtupsize * 2; else { newmemtupsize = INT_MAX; state->growmemtuples = false; } } else { /* * This will be the last increment of memtupsize. Abandon doubling * strategy and instead increase as much as we safely can. * * To stay within allowedMem, we can't increase memtupsize by more * than availMem / sizeof(void *) elements. In practice, we want to * increase it by considerably less, because we need to leave some * space for the tuples to which the new___ array slots will refer. We * assume the new___ tuples will be about the same size as the tuples * we've already seen, and thus we can extrapolate from the space * consumption so far to estimate an appropriate new___ size for the * memtuples array. The optimal value might be higher or lower than * this estimate, but it's hard to know that in advance. We again * clamp at INT_MAX tuples. * * This calculation is safe against enlarging the array so much that * LACKMEM becomes true, because the memory currently used includes * the present array; thus, there would be enough allowedMem for the * new___ array elements even if no other memory were currently used. * * We do the arithmetic in float8, because otherwise the product of * memtupsize and allowedMem could overflow. Any inaccuracy in the * result should be insignificant; but even if we computed a * completely insane result, the checks below will prevent anything * really bad from happening. */ double grow_ratio; grow_ratio = (double) state->allowedMem / (double) memNowUsed; if (memtupsize * grow_ratio < INT_MAX) newmemtupsize = (int) (memtupsize * grow_ratio); else newmemtupsize = INT_MAX; /* We won't make any further enlargement attempts */ state->growmemtuples = false; } /* Must enlarge array by at least one element, else report failure */ if (newmemtupsize <= memtupsize) goto noalloc; /* * On a 32-bit machine, allowedMem could exceed MaxAllocHugeSize. Clamp * to ensure our request won't be rejected. Note that we can easily * exhaust address space before facing this outcome. (This is presently * impossible due to guc.c's MAX_KILOBYTES limitation on work_mem, but * don't rely on that at this distance.) */ if ((Size) newmemtupsize >= MaxAllocHugeSize / sizeof(void *)) { newmemtupsize = (int) (MaxAllocHugeSize / sizeof(void *)); state->growmemtuples = false; /* can't grow any more */ } /* * We need to be sure that we do not cause LACKMEM to become true, else * the space management algorithm will go nuts. The code above should * never generate a dangerous request, but to be safe, check explicitly * that the array growth fits within availMem. (We could still cause * LACKMEM if the memory chunk overhead associated with the memtuples * array were to increase. That shouldn't happen with any sane value of * allowedMem, because at any array size large enough to risk LACKMEM, * palloc would be treating both old and new___ arrays as separate chunks. * But we'll check LACKMEM explicitly below just in case.) */ if (state->availMem < (int64) ((newmemtupsize - memtupsize) * sizeof(void *))) goto noalloc; /* OK, do it */ FREEMEM(state, GetMemoryChunkSpace(state->memtuples)); state->memtupsize = newmemtupsize; state->memtuples = (void **) repalloc_huge(state->memtuples, state->memtupsize * sizeof(void *)); USEMEM(state, GetMemoryChunkSpace(state->memtuples)); if (LACKMEM(state)) elog(ERROR, "unexpected out-of-memory situation during sort"); return true; noalloc: /* If for any reason we didn't realloc, shut off future attempts */ state->growmemtuples = false; return false; } /* * Accept one tuple and append it to the tuplestore. * * Note that the input tuple is always copied; the caller need not save it. * * If the active read pointer is currently "at EOF", it remains so (the read * pointer implicitly advances along with the write pointer); otherwise the * read pointer is unchanged. Non-active read pointers do not move, which * means they are certain to not be "at EOF" immediately after puttuple. * This curious-seeming behavior is for the convenience of nodeMaterial.c and * nodeCtescan.c, which would otherwise need to do extra pointer repositioning * steps. * * tuplestore_puttupleslot() is a convenience routine to collect data from * a TupleTableSlot without an extra copy operation. */ void tuplestore_puttupleslot(Tuplestorestate *state, TupleTableSlot *slot) { MinimalTuple tuple; MemoryContext oldcxt = MemoryContextSwitchTo(state->context); /* * Form a MinimalTuple in working memory */ tuple = ExecCopySlotMinimalTuple(slot); USEMEM(state, GetMemoryChunkSpace(tuple)); tuplestore_puttuple_common(state, (void *) tuple); MemoryContextSwitchTo(oldcxt); } /* * "Standard" case to copy from a HeapTuple. This is actually now somewhat * deprecated, but not worth getting rid of in view of the number of callers. */ void tuplestore_puttuple(Tuplestorestate *state, HeapTuple tuple) { MemoryContext oldcxt = MemoryContextSwitchTo(state->context); /* * Copy the tuple. (Must do this even in WRITEFILE case. Note that * COPYTUP includes USEMEM, so we needn't do that here.) */ tuple = static_cast<HeapTuple>(COPYTUP(state, tuple)); tuplestore_puttuple_common(state, (void *) tuple); MemoryContextSwitchTo(oldcxt); } /* * Similar to tuplestore_puttuple(), but work from values + nulls arrays. * This avoids an extra tuple-construction operation. */ void tuplestore_putvalues(Tuplestorestate *state, TupleDesc tdesc, Datum *values, bool *isnull) { MinimalTuple tuple; MemoryContext oldcxt = MemoryContextSwitchTo(state->context); tuple = heap_form_minimal_tuple(tdesc, values, isnull); USEMEM(state, GetMemoryChunkSpace(tuple)); tuplestore_puttuple_common(state, (void *) tuple); MemoryContextSwitchTo(oldcxt); } static void tuplestore_puttuple_common(Tuplestorestate *state, void *tuple) { TSReadPointer *readptr; int i; ResourceOwner oldowner; switch (state->status) { case TSS_INMEM: /* * Update read pointers as needed; see API spec above. */ readptr = state->readptrs; for (i = 0; i < state->readptrcount; readptr++, i++) { if (readptr->eof_reached && i != state->activeptr) { readptr->eof_reached = false; readptr->current = state->memtupcount; } } /* * Grow the array as needed. Note that we try to grow the array * when there is still one free slot remaining --- if we fail, * there'll still be room to store the incoming tuple, and then * we'll switch to tape-based operation. */ if (state->memtupcount >= state->memtupsize - 1) { (void) grow_memtuples(state); Assert(state->memtupcount < state->memtupsize); } /* Stash the tuple in the in-memory array */ state->memtuples[state->memtupcount++] = tuple; /* * Done if we still fit in available memory and have array slots. */ if (state->memtupcount < state->memtupsize && !LACKMEM(state)) return; /* * Nope; time to switch to tape-based operation. Make sure that * the temp file(s) are created in suitable temp tablespaces. */ PrepareTempTablespaces(); /* associate the file with the store's resource owner */ oldowner = CurrentResourceOwner; CurrentResourceOwner = state->resowner; state->myfile = BufFileCreateTemp(state->interXact); CurrentResourceOwner = oldowner; /* * Freeze the decision about whether trailing length words will be * used. We can't change this choice once data is on tape, even * though callers might drop the requirement. */ state->backward = (state->eflags & EXEC_FLAG_BACKWARD) != 0; state->status = TSS_WRITEFILE; dumptuples(state); break; case TSS_WRITEFILE: /* * Update read pointers as needed; see API spec above. Note: * BufFileTell is quite cheap, so not worth trying to avoid * multiple calls. */ readptr = state->readptrs; for (i = 0; i < state->readptrcount; readptr++, i++) { if (readptr->eof_reached && i != state->activeptr) { readptr->eof_reached = false; BufFileTell(state->myfile, &readptr->file, &readptr->offset); } } WRITETUP(state, tuple); break; case TSS_READFILE: /* * Switch from reading to writing. */ if (!state->readptrs[state->activeptr].eof_reached) BufFileTell(state->myfile, &state->readptrs[state->activeptr].file, &state->readptrs[state->activeptr].offset); if (BufFileSeek(state->myfile, state->writepos_file, state->writepos_offset, SEEK_SET) != 0) ereport(ERROR, (errcode_for_file_access(), errmsg("could not seek in tuplestore temporary file: %m"))); state->status = TSS_WRITEFILE; /* * Update read pointers as needed; see API spec above. */ readptr = state->readptrs; for (i = 0; i < state->readptrcount; readptr++, i++) { if (readptr->eof_reached && i != state->activeptr) { readptr->eof_reached = false; readptr->file = state->writepos_file; readptr->offset = state->writepos_offset; } } WRITETUP(state, tuple); break; default: elog(ERROR, "invalid tuplestore state"); break; } } /* * Fetch the next tuple in either forward or back direction. * Returns NULL if no more tuples. If should_free is set, the * caller must pfree the returned tuple when done with it. * * Backward scan is only allowed if randomAccess was set true or * EXEC_FLAG_BACKWARD was specified to tuplestore_set_eflags(). */ static void * tuplestore_gettuple(Tuplestorestate *state, bool forward, bool *should_free) { TSReadPointer *readptr = &state->readptrs[state->activeptr]; unsigned int tuplen; void *tup; Assert(forward || (readptr->eflags & EXEC_FLAG_BACKWARD)); switch (state->status) { case TSS_INMEM: *should_free = false; if (forward) { if (readptr->eof_reached) return NULL; if (readptr->current < state->memtupcount) { /* We have another tuple, so return it */ return state->memtuples[readptr->current++]; } readptr->eof_reached = true; return NULL; } else { /* * if all tuples are fetched already then we return last * tuple, else tuple before last returned. */ if (readptr->eof_reached) { readptr->current = state->memtupcount; readptr->eof_reached = false; } else { if (readptr->current <= state->memtupdeleted) { Assert(!state->truncated); return NULL; } readptr->current--; /* last returned tuple */ } if (readptr->current <= state->memtupdeleted) { Assert(!state->truncated); return NULL; } return state->memtuples[readptr->current - 1]; } break; case TSS_WRITEFILE: /* Skip state change if we'll just return NULL */ if (readptr->eof_reached && forward) return NULL; /* * Switch from writing to reading. */ BufFileTell(state->myfile, &state->writepos_file, &state->writepos_offset); if (!readptr->eof_reached) if (BufFileSeek(state->myfile, readptr->file, readptr->offset, SEEK_SET) != 0) ereport(ERROR, (errcode_for_file_access(), errmsg("could not seek in tuplestore temporary file: %m"))); state->status = TSS_READFILE; /* FALL THRU into READFILE case */ case TSS_READFILE: *should_free = true; if (forward) { if ((tuplen = getlen(state, true)) != 0) { tup = READTUP(state, tuplen); return tup; } else { readptr->eof_reached = true; return NULL; } } /* * Backward. * * if all tuples are fetched already then we return last tuple, * else tuple before last returned. * * Back up to fetch previously-returned tuple's ending length * word. If seek fails, assume we are at start of file. */ if (BufFileSeek(state->myfile, 0, -(long) sizeof(unsigned int), SEEK_CUR) != 0) { /* even a failed backwards fetch gets you out of eof state */ readptr->eof_reached = false; Assert(!state->truncated); return NULL; } tuplen = getlen(state, false); if (readptr->eof_reached) { readptr->eof_reached = false; /* We will return the tuple returned before returning NULL */ } else { /* * Back up to get ending length word of tuple before it. */ if (BufFileSeek(state->myfile, 0, -(long) (tuplen + 2 * sizeof(unsigned int)), SEEK_CUR) != 0) { /* * If that fails, presumably the prev tuple is the first * in the file. Back up so that it becomes next to read * in forward direction (not obviously right, but that is * what in-memory case does). */ if (BufFileSeek(state->myfile, 0, -(long) (tuplen + sizeof(unsigned int)), SEEK_CUR) != 0) ereport(ERROR, (errcode_for_file_access(), errmsg("could not seek in tuplestore temporary file: %m"))); Assert(!state->truncated); return NULL; } tuplen = getlen(state, false); } /* * Now we have the length of the prior tuple, back up and read it. * Note: READTUP expects we are positioned after the initial * length word of the tuple, so back up to that point. */ if (BufFileSeek(state->myfile, 0, -(long) tuplen, SEEK_CUR) != 0) ereport(ERROR, (errcode_for_file_access(), errmsg("could not seek in tuplestore temporary file: %m"))); tup = READTUP(state, tuplen); return tup; default: elog(ERROR, "invalid tuplestore state"); return NULL; /* keep compiler quiet */ } } /* * tuplestore_gettupleslot - exported function to fetch a MinimalTuple * * If successful, put tuple in slot and return TRUE; else, clear the slot * and return FALSE. * * If copy is TRUE, the slot receives a copied tuple (allocated in current * memory context) that will stay valid regardless of future manipulations of * the tuplestore's state. If copy is FALSE, the slot may just receive a * pointer to a tuple held within the tuplestore. The latter is more * efficient but the slot contents may be corrupted if additional writes to * the tuplestore occur. (If using tuplestore_trim, see comments therein.) */ bool tuplestore_gettupleslot(Tuplestorestate *state, bool forward, bool copy, TupleTableSlot *slot) { MinimalTuple tuple; bool should_free; tuple = (MinimalTuple) tuplestore_gettuple(state, forward, &should_free); if (tuple) { if (copy && !should_free) { tuple = heap_copy_minimal_tuple(tuple); should_free = true; } ExecStoreMinimalTuple(tuple, slot, should_free); return true; } else { ExecClearTuple(slot); return false; } } /* * tuplestore_advance - exported function to adjust position without fetching * * We could optimize this case to avoid palloc/pfree overhead, but for the * moment it doesn't seem worthwhile. */ bool tuplestore_advance(Tuplestorestate *state, bool forward) { void *tuple; bool should_free; tuple = tuplestore_gettuple(state, forward, &should_free); if (tuple) { if (should_free) pfree(tuple); return true; } else { return false; } } /* * Advance over N tuples in either forward or back direction, * without returning any data. N<=0 is a no-op. * Returns TRUE if successful, FALSE if ran out of tuples. */ bool tuplestore_skiptuples(Tuplestorestate *state, int64 ntuples, bool forward) { TSReadPointer *readptr = &state->readptrs[state->activeptr]; Assert(forward || (readptr->eflags & EXEC_FLAG_BACKWARD)); if (ntuples <= 0) return true; switch (state->status) { case TSS_INMEM: if (forward) { if (readptr->eof_reached) return false; if (state->memtupcount - readptr->current >= ntuples) { readptr->current += ntuples; return true; } readptr->current = state->memtupcount; readptr->eof_reached = true; return false; } else { if (readptr->eof_reached) { readptr->current = state->memtupcount; readptr->eof_reached = false; ntuples--; } if (readptr->current - state->memtupdeleted > ntuples) { readptr->current -= ntuples; return true; } Assert(!state->truncated); readptr->current = state->memtupdeleted; return false; } break; default: /* We don't currently try hard to optimize other cases */ while (ntuples-- > 0) { void *tuple; bool should_free; tuple = tuplestore_gettuple(state, forward, &should_free); if (tuple == NULL) return false; if (should_free) pfree(tuple); CHECK_FOR_INTERRUPTS(); } return true; } } /* * dumptuples - remove tuples from memory and write to tape * * As a side effect, we must convert each read pointer's position from * "current" to file/offset format. But eof_reached pointers don't * need to change state. */ static void dumptuples(Tuplestorestate *state) { int i; for (i = state->memtupdeleted;; i++) { TSReadPointer *readptr = state->readptrs; int j; for (j = 0; j < state->readptrcount; readptr++, j++) { if (i == readptr->current && !readptr->eof_reached) BufFileTell(state->myfile, &readptr->file, &readptr->offset); } if (i >= state->memtupcount) break; WRITETUP(state, state->memtuples[i]); } state->memtupdeleted = 0; state->memtupcount = 0; } /* * tuplestore_rescan - rewind the active read pointer to start */ void tuplestore_rescan(Tuplestorestate *state) { TSReadPointer *readptr = &state->readptrs[state->activeptr]; Assert(readptr->eflags & EXEC_FLAG_REWIND); Assert(!state->truncated); switch (state->status) { case TSS_INMEM: readptr->eof_reached = false; readptr->current = 0; break; case TSS_WRITEFILE: readptr->eof_reached = false; readptr->file = 0; readptr->offset = 0L; break; case TSS_READFILE: readptr->eof_reached = false; if (BufFileSeek(state->myfile, 0, 0L, SEEK_SET) != 0) ereport(ERROR, (errcode_for_file_access(), errmsg("could not seek in tuplestore temporary file: %m"))); break; default: elog(ERROR, "invalid tuplestore state"); break; } } /* * tuplestore_copy_read_pointer - copy a read pointer's state to another */ void tuplestore_copy_read_pointer(Tuplestorestate *state, int srcptr, int destptr) { TSReadPointer *sptr = &state->readptrs[srcptr]; TSReadPointer *dptr = &state->readptrs[destptr]; Assert(srcptr >= 0 && srcptr < state->readptrcount); Assert(destptr >= 0 && destptr < state->readptrcount); /* Assigning to self is a no-op */ if (srcptr == destptr) return; if (dptr->eflags != sptr->eflags) { /* Possible change of overall eflags, so copy and then recompute */ int eflags; int i; *dptr = *sptr; eflags = state->readptrs[0].eflags; for (i = 1; i < state->readptrcount; i++) eflags |= state->readptrs[i].eflags; state->eflags = eflags; } else *dptr = *sptr; switch (state->status) { case TSS_INMEM: case TSS_WRITEFILE: /* no work */ break; case TSS_READFILE: /* * This case is a bit tricky since the active read pointer's * position corresponds to the seek point, not what is in its * variables. Assigning to the active requires a seek, and * assigning from the active requires a tell, except when * eof_reached. */ if (destptr == state->activeptr) { if (dptr->eof_reached) { if (BufFileSeek(state->myfile, state->writepos_file, state->writepos_offset, SEEK_SET) != 0) ereport(ERROR, (errcode_for_file_access(), errmsg("could not seek in tuplestore temporary file: %m"))); } else { if (BufFileSeek(state->myfile, dptr->file, dptr->offset, SEEK_SET) != 0) ereport(ERROR, (errcode_for_file_access(), errmsg("could not seek in tuplestore temporary file: %m"))); } } else if (srcptr == state->activeptr) { if (!dptr->eof_reached) BufFileTell(state->myfile, &dptr->file, &dptr->offset); } break; default: elog(ERROR, "invalid tuplestore state"); break; } } /* * tuplestore_trim - remove all no-longer-needed tuples * * Calling this function authorizes the tuplestore to delete all tuples * before the oldest read pointer, if no read pointer is marked as requiring * REWIND capability. * * Note: this is obviously safe if no pointer has BACKWARD capability either. * If a pointer is marked as BACKWARD but not REWIND capable, it means that * the pointer can be moved backward but not before the oldest other read * pointer. */ void tuplestore_trim(Tuplestorestate *state) { int oldest; int nremove; int i; /* * Truncation is disallowed if any read pointer requires rewind * capability. */ if (state->eflags & EXEC_FLAG_REWIND) return; /* * We don't bother trimming temp files since it usually would mean more * work than just letting them sit in kernel buffers until they age out. */ if (state->status != TSS_INMEM) return; /* Find the oldest read pointer */ oldest = state->memtupcount; for (i = 0; i < state->readptrcount; i++) { if (!state->readptrs[i].eof_reached) oldest = Min(oldest, state->readptrs[i].current); } /* * Note: you might think we could remove all the tuples before the oldest * "current", since that one is the next to be returned. However, since * tuplestore_gettuple returns a direct pointer to our internal copy of * the tuple, it's likely that the caller has still got the tuple just * before "current" referenced in a slot. So we keep one extra tuple * before the oldest "current". (Strictly speaking, we could require such * callers to use the "copy" flag to tuplestore_gettupleslot, but for * efficiency we allow this one case to not use "copy".) */ nremove = oldest - 1; if (nremove <= 0) return; /* nothing to do */ Assert(nremove >= state->memtupdeleted); Assert(nremove <= state->memtupcount); /* Release no-longer-needed tuples */ for (i = state->memtupdeleted; i < nremove; i++) { FREEMEM(state, GetMemoryChunkSpace(state->memtuples[i])); pfree(state->memtuples[i]); state->memtuples[i] = NULL; } state->memtupdeleted = nremove; /* mark tuplestore as truncated (used for Assert crosschecks only) */ state->truncated = true; /* * If nremove is less than 1/8th memtupcount, just stop here, leaving the * "deleted" slots as NULL. This prevents us from expending O(N^2) time * repeatedly memmove-ing a large pointer array. The worst case space * wastage is pretty small, since it's just pointers and not whole tuples. */ if (nremove < state->memtupcount / 8) return; /* * Slide the array down and readjust pointers. * * In mergejoin's current usage, it's demonstrable that there will always * be exactly one non-removed tuple; so optimize that case. */ if (nremove + 1 == state->memtupcount) state->memtuples[0] = state->memtuples[nremove]; else memmove(state->memtuples, state->memtuples + nremove, (state->memtupcount - nremove) * sizeof(void *)); state->memtupdeleted = 0; state->memtupcount -= nremove; for (i = 0; i < state->readptrcount; i++) { if (!state->readptrs[i].eof_reached) state->readptrs[i].current -= nremove; } } /* * tuplestore_in_memory * * Returns true if the tuplestore has not spilled to disk. * * XXX exposing this is a violation of modularity ... should get rid of it. */ bool tuplestore_in_memory(Tuplestorestate *state) { return (state->status == TSS_INMEM); } /* * Tape interface routines */ static unsigned int getlen(Tuplestorestate *state, bool eofOK) { unsigned int len; size_t nbytes; nbytes = BufFileRead(state->myfile, (void *) &len, sizeof(len)); if (nbytes == sizeof(len)) return len; if (nbytes != 0 || !eofOK) ereport(ERROR, (errcode_for_file_access(), errmsg("could not read from tuplestore temporary file: %m"))); return 0; } /* * Routines specialized for HeapTuple case * * The stored form is actually a MinimalTuple, but for largely historical * reasons we allow COPYTUP to work from a HeapTuple. * * Since MinimalTuple already has length in its first word, we don't need * to write that separately. */ static void * copytup_heap(Tuplestorestate *state, void *tup) { MinimalTuple tuple; tuple = minimal_tuple_from_heap_tuple((HeapTuple) tup); USEMEM(state, GetMemoryChunkSpace(tuple)); return (void *) tuple; } static void writetup_heap(Tuplestorestate *state, void *tup) { MinimalTuple tuple = (MinimalTuple) tup; /* the part of the MinimalTuple we'll write: */ char *tupbody = (char *) tuple + MINIMAL_TUPLE_DATA_OFFSET; unsigned int tupbodylen = tuple->t_len - MINIMAL_TUPLE_DATA_OFFSET; /* total on-disk footprint: */ unsigned int tuplen = tupbodylen + sizeof(int); if (BufFileWrite(state->myfile, (void *) &tuplen, sizeof(tuplen)) != sizeof(tuplen)) ereport(ERROR, (errcode_for_file_access(), errmsg("could not write to tuplestore temporary file: %m"))); if (BufFileWrite(state->myfile, (void *) tupbody, tupbodylen) != (size_t) tupbodylen) ereport(ERROR, (errcode_for_file_access(), errmsg("could not write to tuplestore temporary file: %m"))); if (state->backward) /* need trailing length word? */ if (BufFileWrite(state->myfile, (void *) &tuplen, sizeof(tuplen)) != sizeof(tuplen)) ereport(ERROR, (errcode_for_file_access(), errmsg("could not write to tuplestore temporary file: %m"))); FREEMEM(state, GetMemoryChunkSpace(tuple)); heap_free_minimal_tuple(tuple); } static void * readtup_heap(Tuplestorestate *state, unsigned int len) { unsigned int tupbodylen = len - sizeof(int); unsigned int tuplen = tupbodylen + MINIMAL_TUPLE_DATA_OFFSET; MinimalTuple tuple = (MinimalTuple) palloc(tuplen); char *tupbody = (char *) tuple + MINIMAL_TUPLE_DATA_OFFSET; USEMEM(state, GetMemoryChunkSpace(tuple)); /* read in the tuple proper */ tuple->t_len = tuplen; if (BufFileRead(state->myfile, (void *) tupbody, tupbodylen) != (size_t) tupbodylen) ereport(ERROR, (errcode_for_file_access(), errmsg("could not read from tuplestore temporary file: %m"))); if (state->backward) /* need trailing length word? */ if (BufFileRead(state->myfile, (void *) &tuplen, sizeof(tuplen)) != sizeof(tuplen)) ereport(ERROR, (errcode_for_file_access(), errmsg("could not read from tuplestore temporary file: %m"))); return (void *) tuple; }
30.320521
79
0.693481
[ "object" ]
06442d32fe70304a05ad0d0eb91fd20c181d0471
970
cpp
C++
src/gwmessage/GWUnpairResponse.cpp
tacr-iotcloud/base
caa10794b965c578f596d616e9654a6a8ef2c169
[ "BSD-3-Clause" ]
null
null
null
src/gwmessage/GWUnpairResponse.cpp
tacr-iotcloud/base
caa10794b965c578f596d616e9654a6a8ef2c169
[ "BSD-3-Clause" ]
null
null
null
src/gwmessage/GWUnpairResponse.cpp
tacr-iotcloud/base
caa10794b965c578f596d616e9654a6a8ef2c169
[ "BSD-3-Clause" ]
1
2019-01-08T14:48:29.000Z
2019-01-08T14:48:29.000Z
#include "gwmessage/GWUnpairResponse.h" using namespace std; using namespace Poco; using namespace Poco::JSON; using namespace BeeeOn; GWUnpairResponse::GWUnpairResponse(): GWResponse(GWMessageType::UNPAIR_RESPONSE) { } GWUnpairResponse::GWUnpairResponse(const Object::Ptr object): GWResponse(object) { } void GWUnpairResponse::setUnpairedDevices(const set<DeviceID> &devices) { Array::Ptr array = new Array; for (const auto &id : devices) { Object::Ptr entry = new Object; entry->set("device_id", id.toString()); array->add(entry); } json()->set("devices", array); } set<DeviceID> GWUnpairResponse::unpairedDevices() const { set<DeviceID> devices; Array::Ptr array = json()->getArray("devices"); if (array.isNull()) return devices; for (size_t i = 0; i < array->size(); ++i) { Object::Ptr entry = array->getObject(i); const string &id = entry->getValue<string>("device_id"); devices.emplace(DeviceID::parse(id)); } return devices; }
20.638298
71
0.71134
[ "object" ]
0648dd7fbb45b1d07e375e844ee0dc29d665b891
9,414
hpp
C++
include/System/Security/Cryptography/X509Certificates/X509Helper2.hpp
RedBrumbler/virtuoso-codegen
e83f6f0f9b47bec4b6dd976b21edc1d46bf3cfe3
[ "Unlicense" ]
null
null
null
include/System/Security/Cryptography/X509Certificates/X509Helper2.hpp
RedBrumbler/virtuoso-codegen
e83f6f0f9b47bec4b6dd976b21edc1d46bf3cfe3
[ "Unlicense" ]
null
null
null
include/System/Security/Cryptography/X509Certificates/X509Helper2.hpp
RedBrumbler/virtuoso-codegen
e83f6f0f9b47bec4b6dd976b21edc1d46bf3cfe3
[ "Unlicense" ]
null
null
null
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "beatsaber-hook/shared/utils/typedefs.h" #include "beatsaber-hook/shared/utils/byref.hpp" #include "beatsaber-hook/shared/utils/typedefs-array.hpp" #include "beatsaber-hook/shared/utils/typedefs-string.hpp" // Completed includes // Begin forward declares // Forward declaring namespace: System::Security::Cryptography::X509Certificates namespace System::Security::Cryptography::X509Certificates { // Forward declaring type: X509CertificateImpl class X509CertificateImpl; // Forward declaring type: X509Certificate2Impl class X509Certificate2Impl; // Forward declaring type: X509KeyStorageFlags struct X509KeyStorageFlags; // Forward declaring type: X509ChainImpl class X509ChainImpl; } // Forward declaring namespace: System namespace System { // Forward declaring type: Exception class Exception; } // Completed forward declares // Type namespace: System.Security.Cryptography.X509Certificates namespace System::Security::Cryptography::X509Certificates { // Forward declaring type: X509Helper2 class X509Helper2; } #include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp" NEED_NO_BOX(::System::Security::Cryptography::X509Certificates::X509Helper2); DEFINE_IL2CPP_ARG_TYPE(::System::Security::Cryptography::X509Certificates::X509Helper2*, "System.Security.Cryptography.X509Certificates", "X509Helper2"); // Type namespace: System.Security.Cryptography.X509Certificates namespace System::Security::Cryptography::X509Certificates { // Size: 0x10 #pragma pack(push, 1) // Autogenerated type: System.Security.Cryptography.X509Certificates.X509Helper2 // [TokenAttribute] Offset: FFFFFFFF class X509Helper2 : public ::Il2CppObject { public: // Nested type: ::System::Security::Cryptography::X509Certificates::X509Helper2::MyNativeHelper class MyNativeHelper; // static System.Void Initialize() // Offset: 0xAC90B4 static void Initialize(); // static System.Void ThrowIfContextInvalid(System.Security.Cryptography.X509Certificates.X509CertificateImpl impl) // Offset: 0xAC3F84 static void ThrowIfContextInvalid(::System::Security::Cryptography::X509Certificates::X509CertificateImpl* impl); // static System.Security.Cryptography.X509Certificates.X509Certificate2Impl Import(System.Byte[] rawData, System.String password, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags keyStorageFlags, System.Boolean disableProvider) // Offset: 0xAC4270 static ::System::Security::Cryptography::X509Certificates::X509Certificate2Impl* Import(::ArrayW<uint8_t> rawData, ::StringW password, ::System::Security::Cryptography::X509Certificates::X509KeyStorageFlags keyStorageFlags, bool disableProvider); // static System.Security.Cryptography.X509Certificates.X509ChainImpl CreateChainImpl(System.Boolean useMachineContext) // Offset: 0xAC73C8 static ::System::Security::Cryptography::X509Certificates::X509ChainImpl* CreateChainImpl(bool useMachineContext); // static public System.Boolean IsValid(System.Security.Cryptography.X509Certificates.X509ChainImpl impl) // Offset: 0xAC9110 static bool IsValid(::System::Security::Cryptography::X509Certificates::X509ChainImpl* impl); // static System.Void ThrowIfContextInvalid(System.Security.Cryptography.X509Certificates.X509ChainImpl impl) // Offset: 0xAC7318 static void ThrowIfContextInvalid(::System::Security::Cryptography::X509Certificates::X509ChainImpl* impl); // static System.Exception GetInvalidChainContextException() // Offset: 0xAC7C74 static ::System::Exception* GetInvalidChainContextException(); }; // System.Security.Cryptography.X509Certificates.X509Helper2 #pragma pack(pop) } #include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" // Writing MetadataGetter for method: System::Security::Cryptography::X509Certificates::X509Helper2::Initialize // Il2CppName: Initialize template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (*)()>(&System::Security::Cryptography::X509Certificates::X509Helper2::Initialize)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(System::Security::Cryptography::X509Certificates::X509Helper2*), "Initialize", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: System::Security::Cryptography::X509Certificates::X509Helper2::ThrowIfContextInvalid // Il2CppName: ThrowIfContextInvalid template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (*)(::System::Security::Cryptography::X509Certificates::X509CertificateImpl*)>(&System::Security::Cryptography::X509Certificates::X509Helper2::ThrowIfContextInvalid)> { static const MethodInfo* get() { static auto* impl = &::il2cpp_utils::GetClassFromName("System.Security.Cryptography.X509Certificates", "X509CertificateImpl")->byval_arg; return ::il2cpp_utils::FindMethod(classof(System::Security::Cryptography::X509Certificates::X509Helper2*), "ThrowIfContextInvalid", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{impl}); } }; // Writing MetadataGetter for method: System::Security::Cryptography::X509Certificates::X509Helper2::Import // Il2CppName: Import template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::System::Security::Cryptography::X509Certificates::X509Certificate2Impl* (*)(::ArrayW<uint8_t>, ::StringW, ::System::Security::Cryptography::X509Certificates::X509KeyStorageFlags, bool)>(&System::Security::Cryptography::X509Certificates::X509Helper2::Import)> { static const MethodInfo* get() { static auto* rawData = &il2cpp_functions::array_class_get(::il2cpp_utils::GetClassFromName("System", "Byte"), 1)->byval_arg; static auto* password = &::il2cpp_utils::GetClassFromName("System", "String")->byval_arg; static auto* keyStorageFlags = &::il2cpp_utils::GetClassFromName("System.Security.Cryptography.X509Certificates", "X509KeyStorageFlags")->byval_arg; static auto* disableProvider = &::il2cpp_utils::GetClassFromName("System", "Boolean")->byval_arg; return ::il2cpp_utils::FindMethod(classof(System::Security::Cryptography::X509Certificates::X509Helper2*), "Import", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{rawData, password, keyStorageFlags, disableProvider}); } }; // Writing MetadataGetter for method: System::Security::Cryptography::X509Certificates::X509Helper2::CreateChainImpl // Il2CppName: CreateChainImpl template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::System::Security::Cryptography::X509Certificates::X509ChainImpl* (*)(bool)>(&System::Security::Cryptography::X509Certificates::X509Helper2::CreateChainImpl)> { static const MethodInfo* get() { static auto* useMachineContext = &::il2cpp_utils::GetClassFromName("System", "Boolean")->byval_arg; return ::il2cpp_utils::FindMethod(classof(System::Security::Cryptography::X509Certificates::X509Helper2*), "CreateChainImpl", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{useMachineContext}); } }; // Writing MetadataGetter for method: System::Security::Cryptography::X509Certificates::X509Helper2::IsValid // Il2CppName: IsValid template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (*)(::System::Security::Cryptography::X509Certificates::X509ChainImpl*)>(&System::Security::Cryptography::X509Certificates::X509Helper2::IsValid)> { static const MethodInfo* get() { static auto* impl = &::il2cpp_utils::GetClassFromName("System.Security.Cryptography.X509Certificates", "X509ChainImpl")->byval_arg; return ::il2cpp_utils::FindMethod(classof(System::Security::Cryptography::X509Certificates::X509Helper2*), "IsValid", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{impl}); } }; // Writing MetadataGetter for method: System::Security::Cryptography::X509Certificates::X509Helper2::ThrowIfContextInvalid // Il2CppName: ThrowIfContextInvalid template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (*)(::System::Security::Cryptography::X509Certificates::X509ChainImpl*)>(&System::Security::Cryptography::X509Certificates::X509Helper2::ThrowIfContextInvalid)> { static const MethodInfo* get() { static auto* impl = &::il2cpp_utils::GetClassFromName("System.Security.Cryptography.X509Certificates", "X509ChainImpl")->byval_arg; return ::il2cpp_utils::FindMethod(classof(System::Security::Cryptography::X509Certificates::X509Helper2*), "ThrowIfContextInvalid", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{impl}); } }; // Writing MetadataGetter for method: System::Security::Cryptography::X509Certificates::X509Helper2::GetInvalidChainContextException // Il2CppName: GetInvalidChainContextException template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::System::Exception* (*)()>(&System::Security::Cryptography::X509Certificates::X509Helper2::GetInvalidChainContextException)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(System::Security::Cryptography::X509Certificates::X509Helper2*), "GetInvalidChainContextException", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } };
69.220588
331
0.778521
[ "vector" ]
064d9af8418cd2531a0f593a0869e09f84f91307
4,746
cpp
C++
src/caffe/test/test_yolo_bbs_layer.cpp
MSRCCS/Caffe
2eb05997f077fe93832b89d56ea0cd1ea72e3275
[ "BSD-2-Clause" ]
null
null
null
src/caffe/test/test_yolo_bbs_layer.cpp
MSRCCS/Caffe
2eb05997f077fe93832b89d56ea0cd1ea72e3275
[ "BSD-2-Clause" ]
null
null
null
src/caffe/test/test_yolo_bbs_layer.cpp
MSRCCS/Caffe
2eb05997f077fe93832b89d56ea0cd1ea72e3275
[ "BSD-2-Clause" ]
null
null
null
#include <vector> #include "boost/scoped_ptr.hpp" #include "gtest/gtest.h" #include "caffe/blob.hpp" #include "caffe/common.hpp" #include "caffe/filler.hpp" #include "caffe/layers/yolo_bbs_layer.hpp" #include "caffe/layers/sigmoid_layer.hpp" #include "caffe/test/test_caffe_main.hpp" #include "caffe/test/test_gradient_check_util.hpp" using boost::scoped_ptr; namespace caffe { template <typename TypeParam> class YoloBBsLayerTest : public MultiDeviceTest<TypeParam> { typedef typename TypeParam::Dtype Dtype; protected: YoloBBsLayerTest() : blob_xy_(new Blob<Dtype>(2, 3 * 2, 7, 7)), blob_wh_(new Blob<Dtype>(2, 3 * 2, 7, 7)), blob_imageinfo_(new Blob<Dtype>(1, 2, 1, 1)), blob_top_bbs_(new Blob<Dtype>()) { //// fill the values FillerParameter filler_param; filler_param.set_min(0); filler_param.set_max(1); UniformFiller<Dtype> filler(filler_param); filler.Fill(blob_xy_); filler.Fill(blob_wh_); SigmoidForward(*blob_xy_); blob_bottom_vec_.push_back(blob_xy_); blob_bottom_vec_.push_back(blob_wh_); blob_bottom_vec_.push_back(blob_imageinfo_); blob_top_vec_.push_back(blob_top_bbs_); } void SigmoidForward(Blob<Dtype> &blob) { LayerParameter param_sig_xy; shared_ptr<SigmoidLayer<Dtype>> sig_layer_xy( new SigmoidLayer<Dtype>(param_sig_xy)); std::vector<Blob<Dtype>*> sig_layer_xy_bottom; std::vector<Blob<Dtype>*> sig_layer_xy_top; sig_layer_xy_bottom.push_back(&blob); sig_layer_xy_top.push_back(&blob); sig_layer_xy->LayerSetUp(sig_layer_xy_bottom, sig_layer_xy_top); sig_layer_xy->Reshape(sig_layer_xy_bottom, sig_layer_xy_top); sig_layer_xy->Forward(sig_layer_xy_bottom, sig_layer_xy_top); } virtual ~YoloBBsLayerTest() { delete blob_xy_; delete blob_wh_; delete blob_imageinfo_; delete blob_top_bbs_; } Blob<Dtype>* const blob_xy_; Blob<Dtype>* const blob_wh_; Blob<Dtype>* const blob_imageinfo_; Blob<Dtype>* const blob_top_bbs_; vector<Blob<Dtype>*> blob_bottom_vec_; vector<Blob<Dtype>*> blob_top_vec_; }; TYPED_TEST_CASE(YoloBBsLayerTest, TestDtypesAndDevices); TYPED_TEST(YoloBBsLayerTest, TestForward) { typedef typename TypeParam::Dtype Dtype; const int kImageWidth = 315; const int kImageHeight = 416; this->blob_imageinfo_->mutable_cpu_data()[0] = kImageHeight; this->blob_imageinfo_->mutable_cpu_data()[1] = kImageWidth; vector<float> biases = { 0.77871f, 1.14074f, 3.00525f, 4.31277f, 9.22725f, 9.61974f }; LayerParameter layer_param; auto yolobbs_param = layer_param.mutable_yolobbs_param(); for (int i = 0; i < biases.size(); i++) { yolobbs_param->add_biases(biases[i]); } const int kFeatStride = 32; yolobbs_param->set_feat_stride(kFeatStride); scoped_ptr<YoloBBsLayer<Dtype> > layer(new YoloBBsLayer<Dtype>(layer_param)); layer->SetUp(this->blob_bottom_vec_, this->blob_top_vec_); layer->Forward(this->blob_bottom_vec_, this->blob_top_vec_); int batches = this->blob_xy_->num(); int height = this->blob_xy_->height(); int width = this->blob_xy_->width(); int num_anchor = this->blob_xy_->channels() / 2; int net_w = kFeatStride * width; int net_h = kFeatStride * height; auto bbs_data = this->blob_top_bbs_->cpu_data(); vector<Dtype> bbox(4); auto& x = bbox[0]; auto& y = bbox[1]; auto& w = bbox[2]; auto& h = bbox[3]; EXPECT_GT((Dtype)net_w / kImageWidth, (Dtype)net_h / kImageHeight); int new_h = net_h; int new_w = (kImageWidth * net_h) / kImageHeight; for (int b = 0; b < batches; b++) { for (int n = 0; n < num_anchor; n++) { for (int j = 0; j < height; j++) { for (int i = 0; i < width; i++) { x = (this->blob_xy_->data_at(b, n, j, i) + i) / width; y = (this->blob_xy_->data_at(b, n + num_anchor, j, i) + j) / height; w = exp(this->blob_wh_->data_at(b, n, j, i)) * biases[2 * n] / width; h = exp(this->blob_wh_->data_at(b, n + num_anchor, j, i)) * biases[2 * n + 1] / height; // Correct the box x = (x - (net_w - new_w) / 2. / net_w) / ((Dtype)new_w / net_w); y = (y - (net_h - new_h) / 2. / net_h) / ((Dtype)new_h / net_h); w *= (Dtype)net_w / new_w; h *= (Dtype)net_h / new_h; x *= kImageWidth; w *= kImageWidth; y *= kImageHeight; h *= kImageHeight; for (int k = 0; k < 4; ++k) EXPECT_FLOAT_EQ(bbox[k], *(bbs_data + this->blob_top_bbs_->offset({ b, n, j, i, k }))); } } } } } }
33.659574
107
0.633165
[ "vector" ]
0655e220a6e7332c36a92fdb1830b785d3a7077f
851
cpp
C++
sycl/test/esimd/regression/simd_wrapper.cpp
kathywar/llvm
5589fdd236b26340d86b3558480296b90bbf744a
[ "Apache-2.0" ]
61
2019-04-12T18:49:57.000Z
2022-03-19T22:23:16.000Z
sycl/test/esimd/regression/simd_wrapper.cpp
kathywar/llvm
5589fdd236b26340d86b3558480296b90bbf744a
[ "Apache-2.0" ]
127
2019-04-09T00:55:50.000Z
2022-03-21T15:35:41.000Z
sycl/test/esimd/regression/simd_wrapper.cpp
kathywar/llvm
5589fdd236b26340d86b3558480296b90bbf744a
[ "Apache-2.0" ]
10
2019-04-02T18:25:40.000Z
2022-02-15T07:11:37.000Z
// RUN: %clangxx -fsycl -fsyntax-only -Xclang -verify %s #include <limits> #include <sycl/ext/intel/experimental/esimd.hpp> #include <utility> // This is a regression test for simd object being non-trivial copy // constructible. In order to fix it, you need to provide copy constructor for // SimdWrapper, e.g.: // SimdWrapper (const SimdWrapper& rhs) : v1(rhs.v1) {} using namespace sycl::ext::intel::experimental::esimd; struct SimdWrapper { union { // expected-note@+1 {{copy constructor of 'SimdWrapper' is implicitly deleted because variant field '' has a non-trivial copy constructor}} struct { simd<int, 4> v1; }; }; SimdWrapper() {} }; void encapsulate_simd() SYCL_ESIMD_FUNCTION { SimdWrapper s1; // expected-error@+1 {{call to implicitly-deleted copy constructor of 'SimdWrapper'}} SimdWrapper s2(s1); }
29.344828
143
0.706228
[ "object" ]
065660c521b591a11565f65d94254a970656bcd5
1,606
hpp
C++
modules/python/src/Aquila/python/nodes.hpp
dtmoodie/Acquilla
b395b7d1338221369f9b0b46c7abc20f7bc5e827
[ "MIT" ]
null
null
null
modules/python/src/Aquila/python/nodes.hpp
dtmoodie/Acquilla
b395b7d1338221369f9b0b46c7abc20f7bc5e827
[ "MIT" ]
null
null
null
modules/python/src/Aquila/python/nodes.hpp
dtmoodie/Acquilla
b395b7d1338221369f9b0b46c7abc20f7bc5e827
[ "MIT" ]
null
null
null
#pragma once #include "Aquila/core/detail/Export.hpp" #include <RuntimeObjectSystem/ObjectInterface.h> #include <RuntimeObjectSystem/shared_ptr.hpp> #include <vector> struct IObjectConstructor; namespace aq { class IGraph; namespace python { template <class T> struct GraphOwnerWrapper { typedef T element_type; GraphOwnerWrapper(const rcc::shared_ptr<T>& obj_ = rcc::shared_ptr<T>()) : obj(obj_) { } ~GraphOwnerWrapper() { obj.reset(); graph.reset(); } operator rcc::shared_ptr<T>&() { return obj; } operator const rcc::shared_ptr<T>&() const { return obj; } rcc::shared_ptr<T> obj; rcc::shared_ptr<aq::IGraph> graph; }; template <class T> T* get_pointer(const GraphOwnerWrapper<T>& wrapper) { return wrapper.obj.get(); } template <class T> GraphOwnerWrapper<T> constructWrappedObject(IObjectConstructor* ctr) { rcc::shared_ptr<T> output; auto obj = ctr->Construct(); if (obj) { output = obj; output->Init(true); } return output; } AQUILA_EXPORTS void setupNodeInterface(); AQUILA_EXPORTS void setupNodeObjects(std::vector<IObjectConstructor*>& ctrs); } // namespace python } // namespace aq
24.333333
85
0.511208
[ "vector" ]
065740ac0612fc0f81a68f3fb31c155983b1eb50
770
cpp
C++
Codeforces/1000~1999/1251/E2.cpp
tiger0132/code-backup
9cb4ee5e99bf3c274e34f1e59d398ab52e51ecf7
[ "MIT" ]
6
2018-12-30T06:16:54.000Z
2022-03-23T08:03:33.000Z
Codeforces/1000~1999/1251/E2.cpp
tiger0132/code-backup
9cb4ee5e99bf3c274e34f1e59d398ab52e51ecf7
[ "MIT" ]
null
null
null
Codeforces/1000~1999/1251/E2.cpp
tiger0132/code-backup
9cb4ee5e99bf3c274e34f1e59d398ab52e51ecf7
[ "MIT" ]
null
null
null
#include <algorithm> #include <cstdio> #include <cstring> #include <queue> #include <vector> typedef long long ll; const int N = 2e5 + 52; std::priority_queue<int, std::vector<int>, std::greater<int>> pq; int n, cnt, p[N], m[N], pre[N]; std::vector<int> v[N]; ll ans; int main() { for (scanf("%*d"); ~scanf("%d", &n);) { for (int i = 0; i < n; i++) i[v].clear(); for (int i = 1; i <= n; i++) scanf("%d%d", m + i, p + i), m[i][v].push_back(p[i]); for (int i = 0; i < n; i++) pre[i] = (i > 0) * pre[i - 1] + i[v].size(); for (int i = n - 1; i >= 1; i--) { for (int j : i[v]) pq.push(j); while (pre[i - 1] + cnt < i) ans += pq.top(), pq.pop(), cnt++; } while (!pq.empty()) pq.pop(); printf("%lld\n", ans); memset(pre, 0, n * 4), ans = cnt = 0; } }
28.518519
84
0.509091
[ "vector" ]
065868e971c92eb7149c3503aa07b10be7c81e9a
13,989
cpp
C++
Modules/ModelFit/src/Common/mitkModelFitInfo.cpp
SVRTK/MITK
52252d60e42702e292d188e30f6717fe50c23962
[ "BSD-3-Clause" ]
null
null
null
Modules/ModelFit/src/Common/mitkModelFitInfo.cpp
SVRTK/MITK
52252d60e42702e292d188e30f6717fe50c23962
[ "BSD-3-Clause" ]
null
null
null
Modules/ModelFit/src/Common/mitkModelFitInfo.cpp
SVRTK/MITK
52252d60e42702e292d188e30f6717fe50c23962
[ "BSD-3-Clause" ]
null
null
null
/*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include <mitkNodePredicateDataProperty.h> #include <mitkUIDGenerator.h> #include "mitkDataNode.h" #include "mitkDataStorage.h" #include "mitkModelFitInfo.h" #include "mitkScalarListLookupTableProperty.h" #include "mitkModelFitException.h" void mitk::modelFit::ModelFitInfo::AddParameter(Parameter::Pointer p) { if (p.IsNull()) { mitkThrow() << "Given parameter must not be NULL"; } if (GetParameter(p->name, p->type).IsNull()) { MITK_DEBUG << "Adding parameter '" << p->name << "with type " << p->type << "' to modelFit '" << uid << "'."; LockType lock(mutex); parameterList.push_back(p); } else { MITK_DEBUG << "Parameter '" << p->name << "' of modelFit '" << uid << "' already exists. Aborting."; } } mitk::modelFit::Parameter::ConstPointer mitk::modelFit::ModelFitInfo::GetParameter(const std::string& name, const Parameter::Type& type) const { for (ConstIterType iter = parameterList.begin(); iter != parameterList.end(); ++iter) { Parameter::ConstPointer p = static_cast<Parameter::ConstPointer>(*iter); if (p->name == name && p->type == type) { return p; } } return nullptr; } const mitk::modelFit::ModelFitInfo::ParamListType& mitk::modelFit::ModelFitInfo::GetParameters() const { return this->parameterList; }; void mitk::modelFit::ModelFitInfo::DeleteParameter(const std::string& name, const Parameter::Type& type) { for (IterType iter = parameterList.begin(); iter != parameterList.end(); ++iter) { Parameter::ConstPointer p = static_cast<Parameter::ConstPointer>(*iter); if (p->name == name && p->type == type) { MITK_DEBUG << "Deleting parameter '" << name << " with type " << type << "' from modelFit '" << uid << "'."; LockType lock(mutex); parameterList.erase(iter); return; } } } const std::string mitk::modelFit::GetMandatoryProperty(const mitk::DataNode* node, const std::string& prop) { std::string result; if (!node || !node->GetData() || !node->GetData()->GetPropertyList()->GetStringProperty(prop.c_str(), result) || result.empty()) { mitkThrowException(mitk::modelFit::ModelFitException) << "Node " << node->GetName() << " is lacking the required " << "property '" << prop << "' or contains an empty string."; } return result; } const std::string mitk::modelFit::GetMandatoryProperty(const mitk::BaseData* data, const std::string& prop) { std::string result; if (!data || !data->GetPropertyList()->GetStringProperty(prop.c_str(), result) || result.empty()) { mitkThrowException(mitk::modelFit::ModelFitException) << "Data is lacking the required " << "property '" << prop << "' or contains an empty string."; } return result; } mitk::modelFit::ModelFitInfo::Pointer mitk::modelFit::CreateFitInfoFromNode(const ModelFitInfo::UIDType& uid, const mitk::DataStorage* storage) { if (!storage) { return nullptr; } mitk::DataStorage::SetOfObjects::ConstPointer nodes = GetNodesOfFit(uid, storage); if (nodes.IsNull() || nodes->empty()) { return nullptr; } mitk::DataNode::ConstPointer node = nodes->GetElement( 0).GetPointer(); //take one of the nodes as template if (!node->GetData()) { return nullptr; } ModelFitInfo::Pointer fit = ModelFitInfo::New(); fit->uid = uid; // Mandatory properties try { fit->fitType = GetMandatoryProperty(node, mitk::ModelFitConstants::FIT_TYPE_PROPERTY_NAME()); fit->modelType = GetMandatoryProperty(node, mitk::ModelFitConstants::MODEL_TYPE_PROPERTY_NAME()); fit->modelName = GetMandatoryProperty(node, mitk::ModelFitConstants::MODEL_NAME_PROPERTY_NAME()); } catch (const ModelFitException& e) { MITK_ERROR << e.what(); return nullptr; } // Either a function string or a function class must exist if (!node->GetData()->GetPropertyList()->GetStringProperty(mitk::ModelFitConstants::MODEL_FUNCTION_PROPERTY_NAME().c_str(), fit->function)) { fit->function = ""; } try { fit->functionClassID = GetMandatoryProperty(node, mitk::ModelFitConstants::MODEL_FUNCTION_CLASS_PROPERTY_NAME()); } catch (const ModelFitException&) { if (fit->function.empty()) { MITK_ERROR << "The properties '" << mitk::ModelFitConstants::MODEL_FUNCTION_PROPERTY_NAME() << "'and '" << mitk::ModelFitConstants::MODEL_FUNCTION_CLASS_PROPERTY_NAME() << "' are both empty or missing. One of these is required."; return nullptr; } } node->GetData()->GetPropertyList()->GetStringProperty(mitk::ModelFitConstants::FIT_NAME_PROPERTY_NAME().c_str(), fit->fitName); node->GetData()->GetPropertyList()->GetStringProperty(mitk::ModelFitConstants::MODEL_X_PROPERTY_NAME().c_str(), fit->x); node->GetData()->GetPropertyList()->GetStringProperty(mitk::ModelFitConstants::XAXIS_NAME_PROPERTY_NAME().c_str(), fit->xAxisName); node->GetData()->GetPropertyList()->GetStringProperty(mitk::ModelFitConstants::XAXIS_UNIT_PROPERTY_NAME().c_str(), fit->xAxisUnit); node->GetData()->GetPropertyList()->GetStringProperty(mitk::ModelFitConstants::YAXIS_NAME_PROPERTY_NAME().c_str(), fit->yAxisName); node->GetData()->GetPropertyList()->GetStringProperty(mitk::ModelFitConstants::YAXIS_UNIT_PROPERTY_NAME().c_str(), fit->yAxisUnit); // Parameter for (DataStorage::SetOfObjects::ConstIterator pos = nodes->Begin(); pos != nodes->End(); ++pos) { modelFit::Parameter::Pointer param = ExtractParameterFromData(pos->Value()->GetData()); if (param.IsNotNull()) { fit->AddParameter(param); } } // Static parameters mitk::ScalarListLookupTableProperty::ConstPointer varProp = dynamic_cast<const mitk::ScalarListLookupTableProperty*>(node->GetData()->GetProperty(mitk::ModelFitConstants::FIT_STATIC_PARAMETERS_PROPERTY_NAME().c_str()).GetPointer()); if (varProp.IsNotNull()) { const mitk::ScalarListLookupTable lut = varProp->GetValue(); const mitk::ScalarListLookupTable::LookupTableType& varMap = lut.GetLookupTable(); for (mitk::ScalarListLookupTable::LookupTableType::const_iterator mapIter = varMap.begin(); mapIter != varMap.end(); ++mapIter) { fit->staticParamMap.Add(mapIter->first, mapIter->second); } } //fit input and ROI try { fit->inputUID = GetMandatoryProperty(node, mitk::ModelFitConstants::FIT_INPUT_IMAGEUID_PROPERTY_NAME()); } catch (const ModelFitException& e) { MITK_ERROR << e.what(); return nullptr; } if (storage) { mitk::DataNode::Pointer inputNode = GetNodeByModelFitUID(storage, fit->inputUID); if (inputNode.IsNull()) { MITK_ERROR << "Cannot create valid model fit info. input node cannot be found."; return nullptr; } mitk::Image::Pointer inputImage = dynamic_cast<mitk::Image*>(inputNode->GetData()); if (inputImage.IsNull()) { MITK_ERROR << "Cannot create valid model fit info. input node does not contain an image."; return nullptr; } fit->inputImage = inputImage; } node->GetData()->GetPropertyList()->GetStringProperty(mitk::ModelFitConstants::FIT_INPUT_ROIUID_PROPERTY_NAME().c_str(), fit->roiUID); mitk::ScalarListLookupTableProperty::ConstPointer inputDataProp = dynamic_cast<const mitk::ScalarListLookupTableProperty*>(node->GetData()->GetProperty(mitk::ModelFitConstants::FIT_INPUT_DATA_PROPERTY_NAME().c_str()).GetPointer()); if (inputDataProp.IsNotNull()) { fit->inputData = inputDataProp->GetValue(); } return fit; } mitk::modelFit::ModelFitInfo::Pointer mitk::modelFit::CreateFitInfoFromModelParameterizer(const ModelParameterizerBase* usedParameterizer, mitk::BaseData* inputImage, const std::string& fitType, const std::string& fitName, const NodeUIDType roiUID) { if (!usedParameterizer) { return nullptr; } UIDGenerator generator("FitUID_"); std::string uid = generator.GetUID(); ModelFitInfo::Pointer fit = ModelFitInfo::New(); fit->uid = uid; fit->fitType = fitType; fit->fitName = fitName; fit->inputImage = dynamic_cast<Image*>(inputImage); fit->inputUID = EnsureModelFitUID(inputImage); if (fit->inputImage.IsNull()) { mitkThrow() << "Cannot generate model fit info. Input node does not contain an image."; } fit->modelType = usedParameterizer->GetModelType(); fit->modelName = usedParameterizer->GetModelDisplayName(); fit->function = usedParameterizer->GetFunctionString(); fit->x = usedParameterizer->GetXName(); fit->functionClassID = usedParameterizer->GetClassID(); fit->xAxisName = usedParameterizer->GetXAxisName(); fit->xAxisUnit = usedParameterizer->GetXAxisUnit(); fit->yAxisName = usedParameterizer->GetYAxisName(); fit->yAxisUnit = usedParameterizer->GetYAxisUnit(); // Parameter ModelTraitsInterface::ParameterNamesType paramNames = usedParameterizer->GetParameterNames(); ModelTraitsInterface::ParamterScaleMapType paramScales = usedParameterizer->GetParameterScales(); ModelTraitsInterface::ParamterUnitMapType paramUnits = usedParameterizer->GetParameterUnits(); for (ModelTraitsInterface::ParameterNamesType::iterator pos = paramNames.begin(); pos != paramNames.end(); ++pos) { modelFit::Parameter::Pointer param = modelFit::Parameter::New(); param->name = *pos; param->type = Parameter::ParameterType; if (paramScales.find(*pos) == paramScales.end()) { mitkThrow() << "Cannot generate model fit info. Model traits invalid (scales do not include parameter). Parameter name: " << *pos; } if (paramUnits.find(*pos) == paramUnits.end()) { mitkThrow() << "Cannot generate model fit info. Model traits invalid (units do not include parameter). Parameter name: " << *pos; } param->scale = paramScales[*pos]; param->unit = paramUnits[*pos]; fit->AddParameter(param); } //derived parameter ModelTraitsInterface::DerivedParameterNamesType derivedNames = usedParameterizer->GetDerivedParameterNames(); ModelTraitsInterface::DerivedParamterScaleMapType derivedScales = usedParameterizer->GetDerivedParameterScales(); ModelTraitsInterface::DerivedParamterUnitMapType derivedUnits = usedParameterizer->GetDerivedParameterUnits(); for (ModelTraitsInterface::ParameterNamesType::iterator pos = derivedNames.begin(); pos != derivedNames.end(); ++pos) { modelFit::Parameter::Pointer param = modelFit::Parameter::New(); param->name = *pos; param->type = Parameter::DerivedType; if (derivedScales.find(*pos) == derivedScales.end()) { mitkThrow() << "Cannot generate model fit info. Model traits invalid (scales do not include parameter). Parameter name: " << *pos; } if (derivedUnits.find(*pos) == derivedUnits.end()) { mitkThrow() << "Cannot generate model fit info. Model traits invalid (units do not include parameter). Parameter name: " << *pos; } param->scale = derivedScales[*pos]; param->unit = derivedUnits[*pos]; fit->AddParameter(param); } // Static parameters (but transfer only the global ones) ModelParameterizerBase::StaticParameterMapType staticParamMap = usedParameterizer->GetGlobalStaticParameters(); for (ModelParameterizerBase::StaticParameterMapType::const_iterator pos = staticParamMap.begin(); pos != staticParamMap.end(); ++pos) { fit->staticParamMap.Add(pos->first, pos->second); } fit->roiUID = roiUID; return fit; } mitk::modelFit::ModelFitInfo::Pointer mitk::modelFit::CreateFitInfoFromModelParameterizer(const ModelParameterizerBase* usedParameterizer, mitk::BaseData* inputImage, const std::string& fitType, const ScalarListLookupTable& inputData, const std::string& fitName, const NodeUIDType roiUID) { mitk::modelFit::ModelFitInfo::Pointer info = CreateFitInfoFromModelParameterizer(usedParameterizer, inputImage, fitType, fitName, roiUID); info->inputData = inputData; return info; } mitk::DataStorage::SetOfObjects::ConstPointer mitk::modelFit::GetNodesOfFit(const ModelFitInfo::UIDType& fitUID, const mitk::DataStorage* storage) { if (!storage) { return nullptr; } mitk::NodePredicateDataProperty::Pointer predicate = mitk::NodePredicateDataProperty::New( mitk::ModelFitConstants::FIT_UID_PROPERTY_NAME().c_str(), mitk::StringProperty::New(fitUID)); return storage->GetSubset(predicate); }; mitk::modelFit::NodeUIDSetType mitk::modelFit::GetFitUIDsOfNode(const mitk::DataNode* node, const mitk::DataStorage* storage) { mitk::modelFit::NodeUIDSetType result; if (node && storage) { mitk::NodePredicateDataProperty::Pointer predicate = mitk::NodePredicateDataProperty::New( mitk::ModelFitConstants::FIT_UID_PROPERTY_NAME().c_str()); mitk::DataStorage::SetOfObjects::ConstPointer nodes = storage->GetDerivations(node, predicate, false); for (mitk::DataStorage::SetOfObjects::ConstIterator pos = nodes->Begin(); pos != nodes->End(); ++pos) { mitk::modelFit::ModelFitInfo::UIDType uid; pos->Value()->GetData()->GetPropertyList()->GetStringProperty(mitk::ModelFitConstants::FIT_UID_PROPERTY_NAME().c_str(), uid); result.insert(uid); } } return result; };
32.532558
234
0.675531
[ "model" ]
065c3af845d5a2d1b4d8e90f7c60d1178c5c420e
6,393
cpp
C++
TapInfo.cpp
tap3edit/tap3xml
65225e823379e73df70817baf68b42cd4e820320
[ "Unlicense" ]
5
2019-01-14T18:04:29.000Z
2021-12-16T23:53:16.000Z
TapInfo.cpp
tap3edit/tap3xml
65225e823379e73df70817baf68b42cd4e820320
[ "Unlicense" ]
3
2020-04-29T06:28:46.000Z
2021-11-28T17:02:48.000Z
TapInfo.cpp
tap3edit/tap3xml
65225e823379e73df70817baf68b42cd4e820320
[ "Unlicense" ]
2
2020-02-17T13:32:23.000Z
2020-04-30T08:20:04.000Z
/**************************************************************************** |* |* tap3xml: both directions XML<->TAP3 Converter. |* |* tap3edit Tools (https://github.com/tap3edit) |* |* Copyright (C) 2005-2018 Javier Gutierrez. All rights reserved. |* email address <https://github.com/tap3edit/tap3xml> |* |* Permission to use, copy, modify, and/or distribute this software for any |* purpose with or without fee is hereby granted, provided that the above |* copyright notice and this permission notice appear in all copies. |* |* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES |* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF |* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR |* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES |* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN |* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF |* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. |* |* |* Module: TapInfo.cpp |* |* Description: |* |* Author: Javier Gutierrez (JG) |* |* Modifications: |* |* When Who Pos. What |* 20051026 JG Initial version |* 20060505 JG When Version of tap file in the rap file |* is not provided, we decode with default |* values (XML) |* 20060510 JG Same but for ASN.1 Files |* 20060510 JG Solved problem identifying XML |* Acknowledgment files |* ****************************************************************************/ /* 1. Includes */ #include "TapInfo.h" /* 2. Global Variables */ TapInfo::TapInfo() { _version=-1; _release=-1; _suplversion=-1; _suplrelease=-1; } void TapInfo::buffin(Buffin *bfin) { string str; int pos, bfin_pos, i; _bfin=bfin; bfin_pos=_bfin->get_pos(); _bfin->set_pos(0); _bfin->read(_bfin->get_end() > 500 ? 500 : _bfin->get_end()); str=bcd2hexa(_bfin->get_buf()); /* 1. Find out which kind of file it is */ pair<string, string> types[] = { pair<string,string>("", "ERR"), /* Not recognized file */ pair<string,string>("61", "TAP"), /* Tap file */ pair<string,string>("62", "TAP"), /* Notification file */ pair<string,string>("7f8416", "RAP"), /* Rap file */ pair<string,string>("7f8417", "ACK") /* Acknowledgment file */ }; for(i=0;i<5;i++) { if (str.substr(0,types[i].first.size())==types[i].first) { _type=types[i].second; } } /* 2. Find its version */ pair<string, int *> version[] = { pair<string,int *>("5f814901", &_version), pair<string,int *>("5f813d01", &_release), pair<string,int *>("5f842001", &_suplversion), pair<string,int *>("5f841f01", &_suplrelease) }; if (_type=="ACK" ) { _version=1; _release=1; _suplversion=3; _suplrelease=1; _type="RAP"; } else { for(i=0;i<4;i++) { if ((pos=str.find(version[i].first)) != (int)string::npos) { *(version[i].second)=atoi(bcd2dec(hexa2bcd(str.substr(pos+version[i].first.size(),2))).c_str()); } else { *(version[i].second)=-1; } } if (_type=="RAP") { i=_version; _version=_suplversion; _suplversion=i; i=_release; _release=_suplrelease; _suplrelease=i; if ( _suplversion < 0 ) _suplversion=3; if ( _suplrelease < 0 ) _suplrelease=1; } if (_version<0 || _release<0) _type="ERR"; } _bfin->set_pos(bfin_pos); } void TapInfo::_findtreeversion(treenode *tree, int depth) { vector<treenode *>::iterator vii; int i; if (depth>2) return; pair<string, string> types[] = { pair<string,string>("transferBatch", "TAP"), /* Tap file */ pair<string,string>("notification", "TAP"), /* Notification file */ pair<string,string>("returnBatch", "RAP"), /* Rap file */ pair<string,string>("acknowledgement", "ACK") /* Acknowledgment file */ }; pair<string, int *> version[] = { pair<string,int *>("specificationVersionNumber", &_version), pair<string,int *>("releaseVersionNumber", &_release), pair<string,int *>("rapSpecificationVersionNumber", &_suplversion), pair<string,int *>("rapReleaseVersionNumber", &_suplrelease) }; for (i=0;i<4;i++) if (tree->tagname==types[i].first) _type=types[i].second; if (tree->children!=NULL) { for (vii=tree->children->begin();vii!=tree->children->end();vii++) { for (i=0;i<4;i++) { if ((*vii)->tagname==version[i].first) if ( (*vii)->value!=NULL ) *(version[i].second)=atoi((*(*vii)->value).c_str()); } } } if (_version<0) { if (tree->children!=NULL) { _findtreeversion((*tree->children)[0],depth+1); } } return; } void TapInfo::tree(treenode *tree) { int i; _version=_release=_suplversion=_suplrelease=-1; _type="ERR"; _findtreeversion(tree, 0); if (_type=="RAP") { i=_version; _version=_suplversion; _suplversion=i; i=_release; _release=_suplrelease; _suplrelease=i; if ( _suplversion < 0 ) _suplversion=3; if ( _suplrelease < 0 ) _suplrelease=1; } if (_type=="ACK" ) { _version=1; _release=1; _suplversion=3; _suplrelease=1; _type="RAP"; } } int TapInfo::version() { return _version; } int TapInfo::release() { return _release; } int TapInfo::suplrelease() { return _suplrelease; } int TapInfo::suplversion() { return _suplversion; } string TapInfo::type() { return _type; } TapInfo::~TapInfo() {}
23.765799
112
0.523385
[ "vector" ]
066549e77b0308b5336c1145db44e5c441a80218
1,794
hpp
C++
krest/core/AbstractProxyModel.hpp
mwoehlke-kitware/krest
fe83740bd685507e358c4cdfb2438b3e3e70266f
[ "BSD-3-Clause" ]
1
2021-04-06T16:07:59.000Z
2021-04-06T16:07:59.000Z
krest/core/AbstractProxyModel.hpp
mwoehlke-kitware/krest
fe83740bd685507e358c4cdfb2438b3e3e70266f
[ "BSD-3-Clause" ]
1
2021-01-13T16:49:46.000Z
2021-01-13T16:49:46.000Z
krest/core/AbstractProxyModel.hpp
mwoehlke-kitware/krest
fe83740bd685507e358c4cdfb2438b3e3e70266f
[ "BSD-3-Clause" ]
2
2021-01-19T15:14:50.000Z
2021-01-19T15:16:16.000Z
/* This file is part of Krest, and is distributed under the OSI-approved BSD * 3-Clause License. See top-level LICENSE file or * https://github.com/Kitware/krest/blob/master/LICENSE for details. */ #ifndef krest_core_AbstractProxyModel_hpp #define krest_core_AbstractProxyModel_hpp #include <krest/core/Export.h> #include <qtGlobal.h> #include <QSortFilterProxyModel> namespace krest { namespace core { /// Base class for proxy models. /// /// This class provides a base class for implementing sort/filter proxy models. /// In particular, it provides a shared mechanism for comparing data that is /// data-role aware. class KREST_CORE_EXPORT AbstractProxyModel : public QSortFilterProxyModel { Q_OBJECT public: using QSortFilterProxyModel::QSortFilterProxyModel; protected: /// Test if data is valid. /// /// This method tests if a data value is valid (i.e. is convertible to the /// appropriate type) for a given data role. static bool isValidData(QVariant const& data, int role); /// Compare data. /// /// This method performs a comparison of two data items which have the type /// \p role. If \p role is not a supported data role, the result is \c false. /// /// \return \c true if the left data is less than the right data; otherwise /// \c false. virtual bool lessThan( QVariant const& left, QVariant const& right, int role) const; using QSortFilterProxyModel::lessThan; /// Emit dataChanged for all top-level items. /// /// This method emits QAbstractItemModel::dataChanged for all top-level /// items, with #VisibilityRole as the list of changed roles. This is useful /// for model data filters when their filtering criteria changes. void invalidateVisibility(); }; } // namespace core } // namespace krest #endif
28.03125
79
0.72854
[ "model" ]
066abfd7d592f0a1baeed200ed4d1b21f6d8d3c7
511
cpp
C++
C++/1150.cpp
rakhi2001/ecom7
73790d44605fbd51e8f7e804b9808e364fcfc680
[ "MIT" ]
854
2018-11-09T08:06:16.000Z
2022-03-31T06:05:53.000Z
C++/1150.cpp
rakhi2001/ecom7
73790d44605fbd51e8f7e804b9808e364fcfc680
[ "MIT" ]
29
2019-06-02T05:02:25.000Z
2021-11-15T04:09:37.000Z
C++/1150.cpp
rakhi2001/ecom7
73790d44605fbd51e8f7e804b9808e364fcfc680
[ "MIT" ]
347
2018-12-23T01:57:37.000Z
2022-03-12T14:51:21.000Z
__________________________________________________________________________________________________ class Solution { public: bool isMajorityElement(vector<int>& nums, int target) { int n=nums.size(); int cnt=0; for(int i=0;i<n;i++){ if(nums[i]==target) cnt++; } return cnt*2>n; } }; __________________________________________________________________________________________________ __________________________________________________________________________________________________
31.9375
98
0.808219
[ "vector" ]
0671f785adfc3ab3e19a0664b6b9d66b4da8f38d
5,267
cpp
C++
Classes/Vegolution.cpp
Fahien/vegolution
27f764e3f51d1e778fe476446938be50b4fd549f
[ "Apache-2.0" ]
3
2016-10-16T13:57:57.000Z
2016-10-28T09:23:25.000Z
Classes/Vegolution.cpp
Fahien/vegolution
27f764e3f51d1e778fe476446938be50b4fd549f
[ "Apache-2.0" ]
null
null
null
Classes/Vegolution.cpp
Fahien/vegolution
27f764e3f51d1e778fe476446938be50b4fd549f
[ "Apache-2.0" ]
null
null
null
#include "Vegolution.h" #include "SimpleAudioEngine.h" #include "scene/SplashScene.h" #include "scene/GameScene.h" USING_NS_CC; static Size designSize{ 570, 320 }; // Information about resources typedef struct tagResource { // The size that this resource is designed for Size size; // If the screen size is more than this value, this resource is a valid choice Size useIfScreenOverSize; // The name of the directory containing resources of this type char directory[3]; } Resource; // Define all our resource types and locations static Resource largeResource{ Size{ 1920, 1080 }, Size{ 1024, 768 }, "hd" }; static Resource mediumResource{ Size{ 1024, 768 }, Size{ 750, 544 }, "md" }; static Resource smallResource{ Size{ 480, 320 }, Size{ 0, 0 }, "sd" }; // Declare and array containing the resource descriptions, from largest to smallest static std::array<Resource, 3> resources{{ largeResource, mediumResource, smallResource }}; Vegolution::Vegolution() { log("Creating Vegolution"); } Vegolution::~Vegolution() { log("Destructing Vegolution"); CocosDenshion::SimpleAudioEngine::getInstance()->end(); } // If you want a different context, just modify the value of glContextAttrs // it will takes effect on all platforms void Vegolution::initGLContextAttrs() { // Set OpenGL context attributions, now can only set six attributions: // red, green, blue, alpha, depth, stencil GLContextAttrs glContextAttrs{ 8, 8, 8, 8, 24, 8 }; GLView::setGLContextAttrs(glContextAttrs); } // If you want to use packages manager to install more packages, // don't modify or remove this function static int register_all_packages() { return 0; //flag for packages manager } // Hook method for application did finish launching bool Vegolution::applicationDidFinishLaunching() { // Get Director instance Director* director{ Director::getInstance() }; // Get FileUtils instance FileUtils* fileUtils{ FileUtils::getInstance() }; // Load window size float width{ static_cast<float>(dataManager_.getInteger("window.width")) }; float height{ static_cast<float>(dataManager_.getInteger("window.height")) }; Size windowSize{ width, height }; log("Initializing View"); // Initialize director GLView* glView{ director->getOpenGLView() }; if (!glView) { #if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32) || (CC_TARGET_PLATFORM == CC_PLATFORM_MAC) || (CC_TARGET_PLATFORM == CC_PLATFORM_LINUX) glView = GLViewImpl::createWithRect("Vegolution", Rect{ 0, 0, windowSize.width, windowSize.height }); #else glView = GLViewImpl::create("Vegolution"); #endif director->setOpenGLView(glView); } log("Set interval 1/60"); // Set FPS. the default value is 1.0/60 if you don't call this director->setAnimationInterval(1.0f / 60.0f); // Set the design resolution glView->setDesignResolutionSize(designSize.width, designSize.height, ResolutionPolicy::FIXED_HEIGHT); // Get the frame size Size frameSize{ glView->getFrameSize() }; log("Frame size is %.0fx%.0f", frameSize.width, frameSize.height); // Vector to build a list of resources paths std::vector<std::string> searchPaths; float scaleFactor{ -1.0f }; // Look through our resource definitions for (auto resource : resources) { // If the screen is wider or higher than the resolution of the resource if (frameSize.width > resource.useIfScreenOverSize.width) { // Add this directory to the search path searchPaths.push_back(resource.directory); log("Searching in %s", resource.directory); // If we haven't already determined the scale factor if (scaleFactor == -1) { scaleFactor = resource.size.height / designSize.height; } break; } } // Set scale factor and search paths director->setContentScaleFactor(scaleFactor); fileUtils->setSearchPaths(searchPaths); register_all_packages(); // Create the main scene. it's an autorelease object Scene* scene{ SplashScene::create(dataManager_, textFactory_) }; // Run now! director->runWithScene(scene); return true; } // This function will be called when the app is inactive. When comes a phone call,it's be invoked too void Vegolution::applicationDidEnterBackground() { Director::getInstance()->stopAnimation(); // if you use SimpleAudioEngine, it must be pause CocosDenshion::SimpleAudioEngine* audioEngine{ CocosDenshion::SimpleAudioEngine::getInstance() }; audioEngine->pauseBackgroundMusic(); audioEngine->pauseAllEffects(); } // This function will be called when the app is active again void Vegolution::applicationWillEnterForeground() { Director* director{ Director::getInstance() }; director->startAnimation(); // if you use SimpleAudioEngine, it must resume here CocosDenshion::SimpleAudioEngine* audioEngine{ CocosDenshion::SimpleAudioEngine::getInstance() }; audioEngine->resumeBackgroundMusic(); audioEngine->resumeAllEffects(); Scene* scene{ director->getRunningScene() }; if (scene && scene->getTag() == 5) { static_cast<GameScene*>(scene)->willEnterForeground(); } }
34.651316
133
0.700778
[ "object", "vector" ]
067519d89e115bd88fdab13d425f2f73169bcda9
508
hpp
C++
Scene.hpp
JzObs/hyperx
8f7435d54a67dd65de8920099a3712ca309db652
[ "BSD-3-Clause" ]
null
null
null
Scene.hpp
JzObs/hyperx
8f7435d54a67dd65de8920099a3712ca309db652
[ "BSD-3-Clause" ]
null
null
null
Scene.hpp
JzObs/hyperx
8f7435d54a67dd65de8920099a3712ca309db652
[ "BSD-3-Clause" ]
null
null
null
#pragma once #ifndef HYPERX_SCENE_HPP #define HYPERX_SCENE_HPP #include "Object.hpp" #include "Renderer.hpp" #include "Texture.hpp" #include <array> class Scene { public: Scene(unsigned int width, unsigned int height); void AddBackground(Texture&& texture); void AddCloud(Texture&& texture); void Draw(Renderer& renderer); void Advance(const unsigned int ms); private: unsigned int width, height; Texture background; std::array<Star, 500> stars; Cloud cloud; }; #endif
19.538462
51
0.712598
[ "object" ]
0675d8df263ad36a4babb2343ddf82295a0f3f89
2,494
hpp
C++
src/algorithms/data_structures/string/valid_palindrome.hpp
iamantony/CppNotes
2707db6560ad80b0e5e286a04b2d46e5c0280b3f
[ "MIT" ]
2
2020-07-31T14:13:56.000Z
2021-02-03T09:51:43.000Z
src/algorithms/data_structures/string/valid_palindrome.hpp
iamantony/CppNotes
2707db6560ad80b0e5e286a04b2d46e5c0280b3f
[ "MIT" ]
28
2015-09-22T07:38:21.000Z
2018-10-02T11:00:58.000Z
src/algorithms/data_structures/string/valid_palindrome.hpp
iamantony/CppNotes
2707db6560ad80b0e5e286a04b2d46e5c0280b3f
[ "MIT" ]
2
2018-10-11T14:10:50.000Z
2021-02-27T08:53:50.000Z
#ifndef VALID_PALINDROME_HPP #define VALID_PALINDROME_HPP #include <string> #include <algorithm> #include <locale> namespace Algo::DS::String { class ValidPalindrome { public: /* https://leetcode.com/problems/valid-palindrome/description/ Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases. For example, "A man, a plan, a canal: Panama" is a palindrome. "race a car" is not a palindrome. Note: Have you consider that the string might be empty? This is a good question to ask during an interview. For the purpose of this problem, we define empty string as valid palindrome. */ bool isPalindrome(std::string s) { if (s.size() < 2) { return true; } std::transform(s.begin(), s.end(), s.begin(), ::tolower); size_t left = 0; size_t right = s.size() - 1; while (left < right) { if (!std::isalnum(s[left])) { left++; } else if (!std::isalnum(s[right])) { right--; } else { if (s[left] != s[right]) { return false; } else { ++left; --right; } } } return true; } /* https://leetcode.com/problems/valid-palindrome-ii/ Given a non-empty string s, you may delete at most one character. Judge whether you can make it a palindrome. Example 1: Input: "aba" Output: True Example 2: Input: "abca" Output: True Explanation: You could delete the character 'c'. Note: The string will only contain lowercase characters a-z. The maximum length of the string is 50000. */ bool isPalindromeWithOneError(std::string s) { if (s.size() < 2) { return true; } size_t l = 0, r = s.size() - 1; while (l < r && s[l] == s[r]) { ++l; --r; } return l >= r ? true : isPalindrome({s.data() + l + 1, r-l}) || isPalindrome({s.data() + l, r-l}); } }; } #endif // VALID_PALINDROME_HPP
28.022472
98
0.473136
[ "transform" ]
0678edced534e4ed5bcb49afad18859af63c834c
91,641
cc
C++
xapian/xapian-core-1.2.13/tests/termgentest.cc
pgs7179/xapian_modified
0229c9efb9eca19be4c9f463cd4b793672f24198
[ "MIT" ]
2
2021-01-13T21:17:42.000Z
2021-01-13T21:17:42.000Z
xapian/xapian-core-1.2.13/tests/termgentest.cc
Loslove55/tailbench
fbbf3f31e3f0af1bb7db7f07c2e7193b84abb1eb
[ "MIT" ]
null
null
null
xapian/xapian-core-1.2.13/tests/termgentest.cc
Loslove55/tailbench
fbbf3f31e3f0af1bb7db7f07c2e7193b84abb1eb
[ "MIT" ]
null
null
null
/* termgentest.cc: Tests of Xapian::TermGenerator * * Copyright (C) 2002,2003,2004,2005,2006,2007,2008,2009,2010 Olly Betts * Copyright (C) 2007 Lemur Consulting Ltd * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation; either version 2 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 * USA */ #include <config.h> #include <xapian.h> #include <iostream> #include <string> #include "str.h" #include "testsuite.h" #include "testutils.h" #include "utils.h" #include <stdlib.h> // For setenv() or putenv() using namespace std; #define TESTCASE(S) {#S, test_##S} #define END_OF_TESTCASES {0, 0} struct test { // A string of options, separated by commas. // Valid options are: // - cont: don't clear the document, so add to the previous output // - nopos: Don't store positions. // - weight=N: where N is a number - set the weight to N. // - stem=FOO: Change stemming algorithm to foo ("none" to turn off). // (this persists for subsequent tests until it's turned off). // - all: Set stemming strategy to STEM_ALL. // (this persists for subsequent tests until it's turned off). // - all_z: Set stemming strategy to STEM_ALL_Z. // (this persists for subsequent tests until it's turned off). // - none: Set stemming strategy to STEM_NONE. // (this persists for subsequent tests until it's turned off). // - some: Set stemming strategy to STEM_SOME. // (this persists for subsequent tests until it's turned off). // - prefix=FOO: Use the specified prefix. // (this persists for subsequent tests until it's turned off). const char *options; // The text to be processed. const char *text; // The expected output. // // This is the list of terms in the resulting document, in sorted order, // followed by ":WDF" if the wdf is not equal to the length of the position // list, followed by "[POSITIONS]" if positional information is stored, // where POSITIONS is a comma separated list of numbers. const char *expect; }; static const test test_simple[] = { // A basic test with a hyphen { "", "simple-example", "example[2] simple[1]" }, { "cont,weight=2", "simple-example", "example:3[2,104] simple:3[1,103]" }, // Test parsing of initials { "", "I.B.M.", "ibm[1]" }, { "", "I.B.M", "ibm[1]" }, { "", "I.B.", "ib[1]" }, { "", "I.B", "ib[1]" }, { "", "I.", "i[1]" }, // Test parsing initials with a stemmer. { "stem=en", "I.B.M.", "Zibm:1 ibm[1]" }, { "", "I.B.M", "Zibm:1 ibm[1]" }, { "", "I.B.", "Zib:1 ib[1]" }, { "", "I.B", "Zib:1 ib[1]" }, { "", "I.", "Zi:1 i[1]" }, { "", "I.B.M. P.C.", "Zibm:1 Zpc:1 ibm[1] pc[2]" }, { "", "I.B.M P.C.", "Zibm:1 Zpc:1 ibm[1] pc[2]" }, // Test parsing numbers { "", "1.0 1000,000.99 0.9.9,", "0.9.9[3] 1.0[1] 1000,000.99[2]" }, { "", "Pi is 3.1415926536 approximately", "3.1415926536[3] Zapproxim:1 Zis:1 Zpi:1 approximately[4] is[2] pi[1]"}, // Test parsing some capitalised words { "", "hello World Test", "Zhello:1 Ztest:1 Zworld:1 hello[1] test[3] world[2]" }, { "prefix=XA", "hello", "XAhello[1] ZXAhello:1" }, { "prefix=XA", "hello World Test", "XAhello[1] XAtest[3] XAworld[2] ZXAhello:1 ZXAtest:1 ZXAworld:1" }, // Assorted tests, corresponding to tests in queryparsertest. { "prefix=", "time_t", "Ztime_t:1 time_t[1]" }, { "", "stock -cooking", "Zcook:1 Zstock:1 cooking[2] stock[1]" }, { "", "d- school report", "Zd:1 Zreport:1 Zschool:1 d[1] report[3] school[2]" }, { "", "gtk+ -gnome", "Zgnome:1 Zgtk+:1 gnome[2] gtk+[1]" }, { "", "c++ -d--", "Zc++:1 Zd:1 c++[1] d[2]" }, { "", "cd'r toebehoren", "Zcd'r:1 Ztoebehoren:1 cd'r[1] toebehoren[2]" }, // Test discarding of terms > 64 bytes. { "", "a REALLYREALLYREALLYREALLYREALLYREALLYREALLYREALLYREALLYREALLYLONG term", "Za:1 Zreallyreallyreallyreallyreallyreallyreallyreallyreallyreallylong:1 Zterm:1 a[1] reallyreallyreallyreallyreallyreallyreallyreallyreallyreallylong[2] term[3]" }, { "", "a REALLYREALLYREALLYREALLYREALLYREALLYREALLYREALLYREALLYREALLYLONGX term", "Za:1 Zterm:1 a[1] term[2]" }, // In 1.1.4, ENCLOSING_MARK and COMBINING_SPACING_MARK were added, and // code to ignore several zero-width space characters was added. { "", "\xe1\x80\x9d\xe1\x80\xae\xe2\x80\x8b\xe1\x80\x80\xe1\x80\xae\xe2\x80\x8b\xe1\x80\x95\xe1\x80\xad\xe2\x80\x8b\xe1\x80\x9e\xe1\x80\xaf\xe1\x80\xb6\xe1\x80\xb8\xe2\x80\x8b\xe1\x80\x85\xe1\x80\xbd\xe1\x80\xb2\xe2\x80\x8b\xe1\x80\x9e\xe1\x80\xb0\xe2\x80\x8b\xe1\x80\x99\xe1\x80\xbb\xe1\x80\xac\xe1\x80\xb8\xe1\x80\x80", "Z\xe1\x80\x9d\xe1\x80\xae\xe1\x80\x80\xe1\x80\xae\xe1\x80\x95\xe1\x80\xad\xe1\x80\x9e\xe1\x80\xaf\xe1\x80\xb6\xe1\x80\xb8\xe1\x80\x85\xe1\x80\xbd\xe1\x80\xb2\xe1\x80\x9e\xe1\x80\xb0\xe1\x80\x99\xe1\x80\xbb\xe1\x80\xac\xe1\x80\xb8\xe1\x80\x80:1 \xe1\x80\x9d\xe1\x80\xae\xe1\x80\x80\xe1\x80\xae\xe1\x80\x95\xe1\x80\xad\xe1\x80\x9e\xe1\x80\xaf\xe1\x80\xb6\xe1\x80\xb8\xe1\x80\x85\xe1\x80\xbd\xe1\x80\xb2\xe1\x80\x9e\xe1\x80\xb0\xe1\x80\x99\xe1\x80\xbb\xe1\x80\xac\xe1\x80\xb8\xe1\x80\x80[1]" }, { "", "fish+chips", "Zchip:1 Zfish:1 chips[2] fish[1]" }, // Basic CJK tests: { "stem=", "久有归天", "久[1] 久有:1 天[4] 归[3] 归天:1 有[2] 有归:1" }, { "", "극지라", "극[1] 극지:1 라[3] 지[2] 지라:1" }, { "", "ウルス アップ", "ア[4] ウ[1] ウル:1 ス[3] ッ[5] ップ:1 プ[6] ル[2] ルス:1" }, // CJK with prefix: { "prefix=XA", "发送从", "XA从[3] XA发[1] XA发送:1 XA送[2] XA送从:1" }, { "prefix=XA", "点卡思考", "XA卡[2] XA卡思:1 XA思[3] XA思考:1 XA点[1] XA点卡:1 XA考[4]" }, // CJK mixed with non-CJK: { "prefix=", "インtestタ", "test[3] イ[1] イン:1 タ[4] ン[2]" }, { "", "配this is合a个 test!", "a[5] is[3] test[7] this[2] 个[6] 合[4] 配[1]" }, // Test set_stemming_strategy(): { "stem=en,none", "Unstemmed words!", "unstemmed[1] words[2]" }, { "all", "Only stemmed words!", "onli[1] stem[2] word[3]" }, { "all_z", "Only stemmed words!", "Zonli[1] Zstem[2] Zword[3]" }, // All following tests are for things which we probably don't really want to // behave as they currently do, but we haven't found a sufficiently general // way to implement them yet. // Test number like things { "stem=en,some", "11:59", "11[1] 59[2]" }, { "", "11:59am", "11[1] 59am[2]" }, { NULL, NULL, NULL } }; #if 0 // These are the queries from the main query parser test. We'll gradually // convert them into termgenerator test cases. { "Mg2+ Cl-", "(mg2+:(pos=1) OR cl:(pos=2))" }, { "\"c++ library\"", "(c++:(pos=1) PHRASE 2 library:(pos=2))" }, { "A&L A&RMCO AD&D", "(a&l:(pos=1) OR a&rmco:(pos=2) OR ad&d:(pos=3))" }, { "C# vs C++", "(c#:(pos=1) OR Zvs:(pos=2) OR c++:(pos=3))" }, { "j##", "Zj##:(pos=1)" }, { "a#b", "(Za:(pos=1) OR Zb:(pos=2))" }, { "O.K. U.N.C.L.E XY.Z.", "(ok:(pos=1) OR uncle:(pos=2) OR (xy:(pos=3) PHRASE 2 z:(pos=4)))" }, { "author:orwell animal farm", "(ZAorwel:(pos=1) OR Zanim:(pos=2) OR Zfarm:(pos=3))" }, { "author:Orwell Animal Farm", "(Aorwell:(pos=1) OR animal:(pos=2) OR farm:(pos=3))" }, // Regression test for bug reported in 0.9.6. { "author:\"orwell\" title:\"animal\"", "(Aorwell:(pos=1) OR XTanimal:(pos=2))" }, // Regression test for bug related to one reported in 0.9.6. { "author:(orwell) title:(animal)", "(ZAorwel:(pos=1) OR ZXTanim:(pos=2))" }, // Regression test for bug caused by fix for previous bug. { "author:\"milne, a.a.\"", "(Amilne:(pos=1) PHRASE 3 Aa:(pos=2) PHRASE 3 Aa:(pos=3))" }, { "author:\"milne a.a.\"", "(Amilne:(pos=1) PHRASE 3 Aa:(pos=2) PHRASE 3 Aa:(pos=3))" }, // Regression test for bug reported in 0.9.7. { "site:/path/name", "H/path/name" }, // Regression test for bug introduced into (and fixed in) SVN prior to 1.0. { "author:/path/name", "(author:(pos=1) PHRASE 3 path:(pos=2) PHRASE 3 name:(pos=3))" }, // Regression test for bug introduced into (and fixed in) SVN prior to 1.0. { "author:(title::case)", "(Atitle:(pos=1) PHRASE 2 Acase:(pos=2))" }, { "\"1.4\"", "1.4:(pos=1)" }, { "\"1.\"", "1:(pos=1)" }, { "\"A#.B.\"", "(a#:(pos=1) PHRASE 2 b:(pos=2))" }, { "h\xc3\xb6hle", "Zh\xc3\xb6hle:(pos=1)" }, { "one +two three", "(Ztwo:(pos=2) AND_MAYBE (Zone:(pos=1) OR Zthree:(pos=3)))" }, { "subject:test other", "(ZXTtest:(pos=1) OR Zother:(pos=2))" }, { "subject:\"space flight\"", "(XTspace:(pos=1) PHRASE 2 XTflight:(pos=2))" }, { "author:(twain OR poe) OR flight", "(ZAtwain:(pos=1) OR ZApoe:(pos=2) OR Zflight:(pos=3))" }, { "author:(twain OR title:pit OR poe)", "(ZAtwain:(pos=1) OR ZXTpit:(pos=2) OR ZApoe:(pos=3))" }, { "title:2001 title:space", "(XT2001:(pos=1) OR ZXTspace:(pos=2))" }, { "(title:help)", "ZXThelp:(pos=1)" }, { "beer NOT \"orange juice\"", "(Zbeer:(pos=1) AND_NOT (orange:(pos=2) PHRASE 2 juice:(pos=3)))" }, { "beer AND NOT lager", "(Zbeer:(pos=1) AND_NOT Zlager:(pos=2))" }, { "one AND two", "(Zone:(pos=1) AND Ztwo:(pos=2))" }, { "one A.N.D. two", "(Zone:(pos=1) OR and:(pos=2) OR Ztwo:(pos=3))" }, { "one \xc3\x81ND two", "(Zone:(pos=1) OR \xc3\xa1nd:(pos=2) OR Ztwo:(pos=3))" }, { "one author:AND two", "(Zone:(pos=1) OR Aand:(pos=2) OR Ztwo:(pos=3))" }, { "author:hyphen-ated", "(Ahyphen:(pos=1) PHRASE 2 Aated:(pos=2))" }, { "cvs site:xapian.org", "(Zcvs:(pos=1) FILTER Hxapian.org)" }, { "cvs -site:xapian.org", "(Zcvs:(pos=1) AND_NOT Hxapian.org)" }, { "site:xapian.org mail", "(Zmail:(pos=1) FILTER Hxapian.org)" }, { "-site:xapian.org mail", "(Zmail:(pos=1) AND_NOT Hxapian.org)" }, { "site:xapian.org", "Hxapian.org" }, { "mug +site:xapian.org -site:cvs.xapian.org", "((Zmug:(pos=1) AND_NOT Hcvs.xapian.org) FILTER Hxapian.org)" }, { "mug -site:cvs.xapian.org +site:xapian.org", "((Zmug:(pos=1) AND_NOT Hcvs.xapian.org) FILTER Hxapian.org)" }, { "NOT windows", "Syntax: <expression> NOT <expression>" }, { "a AND (NOT b)", "Syntax: <expression> NOT <expression>" }, { "AND NOT windows", "Syntax: <expression> AND NOT <expression>" }, { "gordian NOT", "Syntax: <expression> NOT <expression>" }, { "gordian AND NOT", "Syntax: <expression> AND NOT <expression>" }, { "foo OR (something AND)", "Syntax: <expression> AND <expression>" }, { "OR foo", "Syntax: <expression> OR <expression>" }, { "XOR", "Syntax: <expression> XOR <expression>" }, { "hard\xa0space", "(Zhard:(pos=1) OR Zspace:(pos=2))" }, { " white\r\nspace\ttest ", "(Zwhite:(pos=1) OR Zspace:(pos=2) OR Ztest:(pos=3))" }, { "one AND two/three", "(Zone:(pos=1) AND (two:(pos=2) PHRASE 2 three:(pos=3)))" }, { "one AND /two/three", "(Zone:(pos=1) AND (two:(pos=2) PHRASE 2 three:(pos=3)))" }, { "one AND/two/three", "(Zone:(pos=1) AND (two:(pos=2) PHRASE 2 three:(pos=3)))" }, { "one +/two/three", "((two:(pos=2) PHRASE 2 three:(pos=3)) AND_MAYBE Zone:(pos=1))" }, { "one//two", "(one:(pos=1) PHRASE 2 two:(pos=2))" }, { "\"missing quote", "(missing:(pos=1) PHRASE 2 quote:(pos=2))" }, { "DVD+RW", "(dvd:(pos=1) OR rw:(pos=2))" }, // Would a phrase be better? { "+\"must have\" optional", "((must:(pos=1) PHRASE 2 have:(pos=2)) AND_MAYBE Zoption:(pos=3))" }, { "one NEAR two NEAR three", "(one:(pos=1) NEAR 12 two:(pos=2) NEAR 12 three:(pos=3))" }, { "something NEAR/3 else", "(something:(pos=1) NEAR 4 else:(pos=2))" }, { "a NEAR/6 b NEAR c", "(a:(pos=1) NEAR 8 b:(pos=2) NEAR 8 c:(pos=3))" }, { "something ADJ else", "(something:(pos=1) PHRASE 11 else:(pos=2))" }, { "something ADJ/3 else", "(something:(pos=1) PHRASE 4 else:(pos=2))" }, { "a ADJ/6 b ADJ c", "(a:(pos=1) PHRASE 8 b:(pos=2) PHRASE 8 c:(pos=3))" }, // Regression test - Unicode character values were truncated to 8 bits // before testing C_isdigit(), so this rather artificial example parsed // to: (a:(pos=1) NEAR 262 b:(pos=2)) { "a NEAR/\xc4\xb5 b", "((a:(pos=1) NEAR 11 \xc4\xb5:(pos=2)) OR Zb:(pos=3))" }, // Real world examples from tweakers.net: { "Call to undefined function: imagecreate()", "(call:(pos=1) OR Zto:(pos=2) OR Zundefin:(pos=3) OR Zfunction:(pos=4) OR imagecreate:(pos=5))" }, { "mysql_fetch_row(): supplied argument is not a valid MySQL result resource", "(mysql_fetch_row:(pos=1) OR Zsuppli:(pos=2) OR Zargument:(pos=3) OR Zis:(pos=4) OR Znot:(pos=5) OR Za:(pos=6) OR Zvalid:(pos=7) OR mysql:(pos=8) OR Zresult:(pos=9) OR Zresourc:(pos=10))" }, { "php date() nedelands", "(Zphp:(pos=1) OR date:(pos=2) OR Znedeland:(pos=3))" }, { "wget domein --http-user", "(Zwget:(pos=1) OR Zdomein:(pos=2) OR (http:(pos=3) PHRASE 2 user:(pos=4)))" }, { "@home problemen", "(Zhome:(pos=1) OR Zproblemen:(pos=2))" }, { "'ipacsum'", "Zipacsum:(pos=1)" }, { "canal + ", "Zcanal:(pos=1)" }, { "/var/run/mysqld/mysqld.sock", "(var:(pos=1) PHRASE 5 run:(pos=2) PHRASE 5 mysqld:(pos=3) PHRASE 5 mysqld:(pos=4) PHRASE 5 sock:(pos=5))" }, { "\"QSI-161 drivers\"", "(qsi:(pos=1) PHRASE 3 161:(pos=2) PHRASE 3 drivers:(pos=3))" }, { "\"e-cube\" barebone", "((e:(pos=1) PHRASE 2 cube:(pos=2)) OR Zbarebon:(pos=3))" }, { "\"./httpd: symbol not found: dlopen\"", "(httpd:(pos=1) PHRASE 5 symbol:(pos=2) PHRASE 5 not:(pos=3) PHRASE 5 found:(pos=4) PHRASE 5 dlopen:(pos=5))" }, { "ERROR 2003: Can't connect to MySQL server on 'localhost' (10061)", "(error:(pos=1) OR 2003:(pos=2) OR can't:(pos=3) OR Zconnect:(pos=4) OR Zto:(pos=5) OR mysql:(pos=6) OR Zserver:(pos=7) OR Zon:(pos=8) OR Zlocalhost:(pos=9) OR 10061:(pos=10))" }, { "location.href = \"\"", "(location:(pos=1) PHRASE 2 href:(pos=2))" }, { "method=\"post\" action=\"\">", "(method:(pos=1) OR post:(pos=2) OR action:(pos=3))" }, { "behuizing 19\" inch", "(Zbehuiz:(pos=1) OR 19:(pos=2) OR inch:(pos=3))" }, { "19\" rack", "(19:(pos=1) OR rack:(pos=2))" }, { "3,5\" mainboard", "(3,5:(pos=1) OR mainboard:(pos=2))" }, { "553 sorry, that domain isn't in my list of allowed rcpthosts (#5.7.1)", "(553:(pos=1) OR Zsorri:(pos=2) OR Zthat:(pos=3) OR Zdomain:(pos=4) OR Zisn't:(pos=5) OR Zin:(pos=6) OR Zmy:(pos=7) OR Zlist:(pos=8) OR Zof:(pos=9) OR Zallow:(pos=10) OR Zrcpthost:(pos=11) OR 5.7.1:(pos=12))" }, { "data error (clic redundancy check)", "(Zdata:(pos=1) OR Zerror:(pos=2) OR Zclic:(pos=3) OR Zredund:(pos=4) OR Zcheck:(pos=5))" }, { "? mediaplayer 9\"", "(Zmediaplay:(pos=1) OR 9:(pos=2))" }, { "date(\"w\")", "(date:(pos=1) OR w:(pos=2))" }, { "Syntaxisfout (operator ontbreekt ASP", "(syntaxisfout:(pos=1) OR Zoper:(pos=2) OR Zontbreekt:(pos=3) OR asp:(pos=4))" }, { "Request.ServerVariables(\"logon_user\")", "((request:(pos=1) PHRASE 2 servervariables:(pos=2)) OR logon_user:(pos=3))" }, { "ASP \"request.form\" van \\\"enctype=\"MULTIPART/FORM-DATA\"\\\"", "(asp:(pos=1) OR (request:(pos=2) PHRASE 2 form:(pos=3)) OR Zvan:(pos=4) OR enctype:(pos=5) OR (multipart:(pos=6) PHRASE 3 form:(pos=7) PHRASE 3 data:(pos=8)))" }, { "USER ftp (Login failed): Invalid shell: /sbin/nologin", "(user:(pos=1) OR Zftp:(pos=2) OR login:(pos=3) OR Zfail:(pos=4) OR invalid:(pos=5) OR Zshell:(pos=6) OR (sbin:(pos=7) PHRASE 2 nologin:(pos=8)))" }, { "ip_masq_new(proto=TCP)", "(ip_masq_new:(pos=1) OR proto:(pos=2) OR tcp:(pos=3))" }, { "\"document.write(\"", "(document:(pos=1) PHRASE 2 write:(pos=2))" }, { "ERROR 1045: Access denied for user: 'root@localhost' (Using password: NO)", "(error:(pos=1) OR 1045:(pos=2) OR access:(pos=3) OR Zdeni:(pos=4) OR Zfor:(pos=5) OR Zuser:(pos=6) OR (root:(pos=7) PHRASE 2 localhost:(pos=8)) OR using:(pos=9) OR Zpassword:(pos=10) OR no:(pos=11))" }, { "TIP !! subtitles op TV-out (via DVD max g400)", "(tip:(pos=1) OR Zsubtitl:(pos=2) OR Zop:(pos=3) OR (tv:(pos=4) PHRASE 2 out:(pos=5)) OR Zvia:(pos=6) OR dvd:(pos=7) OR Zmax:(pos=8) OR Zg400:(pos=9))" }, { "Gigabyte 8PE667 (de Ultra versie) of Asus A7N8X Deluxe", "(gigabyte:(pos=1) OR 8pe667:(pos=2) OR Zde:(pos=3) OR ultra:(pos=4) OR Zversi:(pos=5) OR Zof:(pos=6) OR asus:(pos=7) OR a7n8x:(pos=8) OR deluxe:(pos=9))" }, { "\"1) Ze testen 8x AF op de GFFX tegen \"", "(1:(pos=1) PHRASE 9 ze:(pos=2) PHRASE 9 testen:(pos=3) PHRASE 9 8x:(pos=4) PHRASE 9 af:(pos=5) PHRASE 9 op:(pos=6) PHRASE 9 de:(pos=7) PHRASE 9 gffx:(pos=8) PHRASE 9 tegen:(pos=9))" }, { "\") Ze houden geen rekening met de kwaliteit van AF. Als ze dat gedaan hadden dan waren ze tot de conclusie gekomen dat Performance AF (dus Bilinear AF) op de 9700Pro goed te vergelijken is met Balanced AF op de GFFX. En dan hadden ze ook gezien dat de GFFX niet kan tippen aan de Quality AF van de 9700Pro.\"", "(ze:(pos=1) PHRASE 59 houden:(pos=2) PHRASE 59 geen:(pos=3) PHRASE 59 rekening:(pos=4) PHRASE 59 met:(pos=5) PHRASE 59 de:(pos=6) PHRASE 59 kwaliteit:(pos=7) PHRASE 59 van:(pos=8) PHRASE 59 af:(pos=9) PHRASE 59 als:(pos=10) PHRASE 59 ze:(pos=11) PHRASE 59 dat:(pos=12) PHRASE 59 gedaan:(pos=13) PHRASE 59 hadden:(pos=14) PHRASE 59 dan:(pos=15) PHRASE 59 waren:(pos=16) PHRASE 59 ze:(pos=17) PHRASE 59 tot:(pos=18) PHRASE 59 de:(pos=19) PHRASE 59 conclusie:(pos=20) PHRASE 59 gekomen:(pos=21) PHRASE 59 dat:(pos=22) PHRASE 59 performance:(pos=23) PHRASE 59 af:(pos=24) PHRASE 59 dus:(pos=25) PHRASE 59 bilinear:(pos=26) PHRASE 59 af:(pos=27) PHRASE 59 op:(pos=28) PHRASE 59 de:(pos=29) PHRASE 59 9700pro:(pos=30) PHRASE 59 goed:(pos=31) PHRASE 59 te:(pos=32) PHRASE 59 vergelijken:(pos=33) PHRASE 59 is:(pos=34) PHRASE 59 met:(pos=35) PHRASE 59 balanced:(pos=36) PHRASE 59 af:(pos=37) PHRASE 59 op:(pos=38) PHRASE 59 de:(pos=39) PHRASE 59 gffx:(pos=40) PHRASE 59 en:(pos=41) PHRASE 59 dan:(pos=42) PHRASE 59 hadden:(pos=43) PHRASE 59 ze:(pos=44) PHRASE 59 ook:(pos=45) PHRASE 59 gezien:(pos=46) PHRASE 59 dat:(pos=47) PHRASE 59 de:(pos=48) PHRASE 59 gffx:(pos=49) PHRASE 59 niet:(pos=50) PHRASE 59 kan:(pos=51) PHRASE 59 tippen:(pos=52) PHRASE 59 aan:(pos=53) PHRASE 59 de:(pos=54) PHRASE 59 quality:(pos=55) PHRASE 59 af:(pos=56) PHRASE 59 van:(pos=57) PHRASE 59 de:(pos=58) PHRASE 59 9700pro:(pos=59))" }, { "\"Ze houden geen rekening met de kwaliteit van AF. Als ze dat gedaan hadden dan waren ze tot de conclusie gekomen dat Performance AF (dus Bilinear AF) op de 9700Pro goed te vergelijken is met Balanced AF op de GFFX. En dan hadden ze ook gezien dat de GFFX niet kan tippen aan de Quality AF van de 9700Pro.\"", "(ze:(pos=1) PHRASE 59 houden:(pos=2) PHRASE 59 geen:(pos=3) PHRASE 59 rekening:(pos=4) PHRASE 59 met:(pos=5) PHRASE 59 de:(pos=6) PHRASE 59 kwaliteit:(pos=7) PHRASE 59 van:(pos=8) PHRASE 59 af:(pos=9) PHRASE 59 als:(pos=10) PHRASE 59 ze:(pos=11) PHRASE 59 dat:(pos=12) PHRASE 59 gedaan:(pos=13) PHRASE 59 hadden:(pos=14) PHRASE 59 dan:(pos=15) PHRASE 59 waren:(pos=16) PHRASE 59 ze:(pos=17) PHRASE 59 tot:(pos=18) PHRASE 59 de:(pos=19) PHRASE 59 conclusie:(pos=20) PHRASE 59 gekomen:(pos=21) PHRASE 59 dat:(pos=22) PHRASE 59 performance:(pos=23) PHRASE 59 af:(pos=24) PHRASE 59 dus:(pos=25) PHRASE 59 bilinear:(pos=26) PHRASE 59 af:(pos=27) PHRASE 59 op:(pos=28) PHRASE 59 de:(pos=29) PHRASE 59 9700pro:(pos=30) PHRASE 59 goed:(pos=31) PHRASE 59 te:(pos=32) PHRASE 59 vergelijken:(pos=33) PHRASE 59 is:(pos=34) PHRASE 59 met:(pos=35) PHRASE 59 balanced:(pos=36) PHRASE 59 af:(pos=37) PHRASE 59 op:(pos=38) PHRASE 59 de:(pos=39) PHRASE 59 gffx:(pos=40) PHRASE 59 en:(pos=41) PHRASE 59 dan:(pos=42) PHRASE 59 hadden:(pos=43) PHRASE 59 ze:(pos=44) PHRASE 59 ook:(pos=45) PHRASE 59 gezien:(pos=46) PHRASE 59 dat:(pos=47) PHRASE 59 de:(pos=48) PHRASE 59 gffx:(pos=49) PHRASE 59 niet:(pos=50) PHRASE 59 kan:(pos=51) PHRASE 59 tippen:(pos=52) PHRASE 59 aan:(pos=53) PHRASE 59 de:(pos=54) PHRASE 59 quality:(pos=55) PHRASE 59 af:(pos=56) PHRASE 59 van:(pos=57) PHRASE 59 de:(pos=58) PHRASE 59 9700pro:(pos=59))" }, { "$structure = imap_header($mbox, $tt);", "(Zstructur:(pos=1) OR imap_header:(pos=2) OR Zmbox:(pos=3) OR Ztt:(pos=4))" }, { "\"ifup: Could not get a valid interface name: -> skipped\"", "(ifup:(pos=1) PHRASE 9 could:(pos=2) PHRASE 9 not:(pos=3) PHRASE 9 get:(pos=4) PHRASE 9 a:(pos=5) PHRASE 9 valid:(pos=6) PHRASE 9 interface:(pos=7) PHRASE 9 name:(pos=8) PHRASE 9 skipped:(pos=9))" }, { "Er kan geen combinatie van filters worden gevonden om de gegevensstroom te genereren. (Error=80040218)", "(er:(pos=1) OR Zkan:(pos=2) OR Zgeen:(pos=3) OR Zcombinati:(pos=4) OR Zvan:(pos=5) OR Zfilter:(pos=6) OR Zworden:(pos=7) OR Zgevonden:(pos=8) OR Zom:(pos=9) OR Zde:(pos=10) OR Zgegevensstroom:(pos=11) OR Zte:(pos=12) OR Zgenereren:(pos=13) OR error:(pos=14) OR 80040218:(pos=15))" }, { "ereg_replace(\"\\\\\",\"\\/\"", "ereg_replace:(pos=1)" }, { "\\\\\"divx+geen+geluid\\\\\"", "(divx:(pos=1) PHRASE 3 geen:(pos=2) PHRASE 3 geluid:(pos=3))" }, { "lcase(\"string\")", "(lcase:(pos=1) OR string:(pos=2))" }, { "isEmpty( ) functie in visual basic", "(isempty:(pos=1) OR Zfuncti:(pos=2) OR Zin:(pos=3) OR Zvisual:(pos=4) OR Zbasic:(pos=5))" }, { "*** stop: 0x0000001E (0xC0000005,0x00000000,0x00000000,0x00000000)", "(Zstop:(pos=1) OR 0x0000001e:(pos=2) OR 0xc0000005,0x00000000,0x00000000,0x00000000:(pos=3))" }, { "\"ctrl+v+c+a fout\"", "(ctrl:(pos=1) PHRASE 5 v:(pos=2) PHRASE 5 c:(pos=3) PHRASE 5 a:(pos=4) PHRASE 5 fout:(pos=5))" }, { "Server.CreateObject(\"ADODB.connection\")", "((server:(pos=1) PHRASE 2 createobject:(pos=2)) OR (adodb:(pos=3) PHRASE 2 connection:(pos=4)))" }, { "Presario 6277EA-XP model P4/28 GHz-120GB-DVD-CDRW (512MBWXP) (470048-012)", "(presario:(pos=1) OR (6277ea:(pos=2) PHRASE 2 xp:(pos=3)) OR Zmodel:(pos=4) OR (p4:(pos=5) PHRASE 2 28:(pos=6)) OR (ghz:(pos=7) PHRASE 4 120gb:(pos=8) PHRASE 4 dvd:(pos=9) PHRASE 4 cdrw:(pos=10)) OR 512mbwxp:(pos=11) OR (470048:(pos=12) PHRASE 2 012:(pos=13)))" }, { "Failed to connect agent. (AGENT=dbaxchg2, EC=UserId =NUll)", "(failed:(pos=1) OR Zto:(pos=2) OR Zconnect:(pos=3) OR Zagent:(pos=4) OR agent:(pos=5) OR Zdbaxchg2:(pos=6) OR ec:(pos=7) OR userid:(pos=8) OR null:(pos=9))" }, { "delphi CreateOleObject(\"MSXML2.DomDocument\")", "(Zdelphi:(pos=1) OR createoleobject:(pos=2) OR (msxml2:(pos=3) PHRASE 2 domdocument:(pos=4)))" }, { "Unhandled exeption in IEXPLORE.EXE (FTAPP.DLL)", "(unhandled:(pos=1) OR Zexept:(pos=2) OR Zin:(pos=3) OR (iexplore:(pos=4) PHRASE 2 exe:(pos=5)) OR (ftapp:(pos=6) PHRASE 2 dll:(pos=7)))" }, { "IBM High Rate Wireless LAN PCI Adapter (Low Profile Enabled)", "(ibm:(pos=1) OR high:(pos=2) OR rate:(pos=3) OR wireless:(pos=4) OR lan:(pos=5) OR pci:(pos=6) OR adapter:(pos=7) OR low:(pos=8) OR profile:(pos=9) OR enabled:(pos=10))" }, { "asp ' en \"", "(Zasp:(pos=1) OR Zen:(pos=2))" }, { "Hercules 3D Prophet 8500 LE 64MB (OEM, Radeon 8500 LE)", "(hercules:(pos=1) OR 3d:(pos=2) OR prophet:(pos=3) OR 8500:(pos=4) OR le:(pos=5) OR 64mb:(pos=6) OR oem:(pos=7) OR radeon:(pos=8) OR 8500:(pos=9) OR le:(pos=10))" }, { "session_set_cookie_params(echo \"hoi\")", "(session_set_cookie_params:(pos=1) OR Zecho:(pos=2) OR hoi:(pos=3))" }, { "windows update werkt niet (windows se", "(Zwindow:(pos=1) OR Zupdat:(pos=2) OR Zwerkt:(pos=3) OR Zniet:(pos=4) OR Zwindow:(pos=5) OR Zse:(pos=6))" }, { "De statuscode van de fout is ( 0 x 4 , 0 , 0 , 0 )", "(de:(pos=1) OR Zstatuscod:(pos=2) OR Zvan:(pos=3) OR Zde:(pos=4) OR Zfout:(pos=5) OR Zis:(pos=6) OR 0:(pos=7) OR Zx:(pos=8) OR 4:(pos=9) OR 0:(pos=10) OR 0:(pos=11) OR 0:(pos=12))" }, { "sony +(u20 u-20)", "((Zu20:(pos=2) OR (u:(pos=3) PHRASE 2 20:(pos=4))) AND_MAYBE Zsoni:(pos=1))" }, { "[crit] (17)File exists: unable to create scoreboard (name-based shared memory failure)", "(Zcrit:(pos=1) OR 17:(pos=2) OR file:(pos=3) OR Zexist:(pos=4) OR Zunabl:(pos=5) OR Zto:(pos=6) OR Zcreat:(pos=7) OR Zscoreboard:(pos=8) OR (name:(pos=9) PHRASE 2 based:(pos=10)) OR Zshare:(pos=11) OR Zmemori:(pos=12) OR Zfailur:(pos=13))" }, { "directories lokaal php (uitlezen OR inladen)", "(Zdirectori:(pos=1) OR Zlokaal:(pos=2) OR Zphp:(pos=3) OR Zuitlezen:(pos=4) OR Zinladen:(pos=5))" }, { "(multi pc modem)+ (line sync)", "(Zmulti:(pos=1) OR Zpc:(pos=2) OR Zmodem:(pos=3) OR Zline:(pos=4) OR Zsync:(pos=5))" }, { "xp 5.1.2600.0 (xpclient.010817-1148)", "(Zxp:(pos=1) OR 5.1.2600.0:(pos=2) OR (xpclient:(pos=3) PHRASE 3 010817:(pos=4) PHRASE 3 1148:(pos=5)))" }, { "DirectDraw test results: Failure at step 5 (User verification of rectangles): HRESULT = 0x00000000 (error code) Direct3D 7 test results: Failure at step 32 (User verification of Direct3D rendering): HRESULT = 0x00000000 (error code) Direct3D 8 test results: Failure at step 32 (User verification of Direct3D rendering): HRESULT = 0x00000000 (error code) Direct3D 9 test results: Failure at step 32 (User verification of Direct3D rendering): HRESULT = 0x00000000 (error code)", "(directdraw:(pos=1) OR Ztest:(pos=2) OR Zresult:(pos=3) OR failure:(pos=4) OR Zat:(pos=5) OR Zstep:(pos=6) OR 5:(pos=7) OR user:(pos=8) OR Zverif:(pos=9) OR Zof:(pos=10) OR Zrectangl:(pos=11) OR hresult:(pos=12) OR 0x00000000:(pos=13) OR Zerror:(pos=14) OR Zcode:(pos=15) OR direct3d:(pos=16) OR 7:(pos=17) OR Ztest:(pos=18) OR Zresult:(pos=19) OR failure:(pos=20) OR Zat:(pos=21) OR Zstep:(pos=22) OR 32:(pos=23) OR user:(pos=24) OR Zverif:(pos=25) OR Zof:(pos=26) OR direct3d:(pos=27) OR Zrender:(pos=28) OR hresult:(pos=29) OR 0x00000000:(pos=30) OR Zerror:(pos=31) OR Zcode:(pos=32) OR direct3d:(pos=33) OR 8:(pos=34) OR Ztest:(pos=35) OR Zresult:(pos=36) OR failure:(pos=37) OR Zat:(pos=38) OR Zstep:(pos=39) OR 32:(pos=40) OR user:(pos=41) OR Zverif:(pos=42) OR Zof:(pos=43) OR direct3d:(pos=44) OR Zrender:(pos=45) OR hresult:(pos=46) OR 0x00000000:(pos=47) OR Zerror:(pos=48) OR Zcode:(pos=49) OR direct3d:(pos=50) OR 9:(pos=51) OR Ztest:(pos=52) OR Zresult:(pos=53) OR failure:(pos=54) OR Zat:(pos=55) OR Zstep:(pos=56) OR 32:(pos=57) OR user:(pos=58) OR Zverif:(pos=59) OR Zof:(pos=60) OR direct3d:(pos=61) OR Zrender:(pos=62) OR hresult:(pos=63) OR 0x00000000:(pos=64) OR Zerror:(pos=65) OR Zcode:(pos=66))" }, { "Thermaltake Aquarius II waterkoeling (kompleet voor P4 en XP)", "(thermaltake:(pos=1) OR aquarius:(pos=2) OR ii:(pos=3) OR Zwaterkoel:(pos=4) OR Zkompleet:(pos=5) OR Zvoor:(pos=6) OR p4:(pos=7) OR Zen:(pos=8) OR xp:(pos=9))" }, { "E3501 unable to add job to database (EC=-2005)", "(e3501:(pos=1) OR Zunabl:(pos=2) OR Zto:(pos=3) OR Zadd:(pos=4) OR Zjob:(pos=5) OR Zto:(pos=6) OR Zdatabas:(pos=7) OR ec:(pos=8) OR 2005:(pos=9))" }, { "\"arp -s\" ip veranderen", "((arp:(pos=1) PHRASE 2 s:(pos=2)) OR Zip:(pos=3) OR Zveranderen:(pos=4))" }, { "header(\"content-type: application/octet-stream\");", "(header:(pos=1) OR (content:(pos=2) PHRASE 2 type:(pos=3)) OR (application:(pos=4) PHRASE 3 octet:(pos=5) PHRASE 3 stream:(pos=6)))" }, { "$datum = date(\"d-m-Y\");", "(Zdatum:(pos=1) OR date:(pos=2) OR (d:(pos=3) PHRASE 3 m:(pos=4) PHRASE 3 y:(pos=5)))" }, { "\"'\" +asp", "Zasp:(pos=1)" }, { "+session +[", "Zsession:(pos=1)" }, { "Dit apparaat kan niet starten. (Code 10)", "(dit:(pos=1) OR Zapparaat:(pos=2) OR Zkan:(pos=3) OR Zniet:(pos=4) OR Zstarten:(pos=5) OR code:(pos=6) OR 10:(pos=7))" }, { "\"You cannot use the Administration program while the Domino Server is running. Either shut down the Domino Server (but keep the file server running) or choose the ican labeled 'Lotus Notes' instead.\"", "(you:(pos=1) PHRASE 32 cannot:(pos=2) PHRASE 32 use:(pos=3) PHRASE 32 the:(pos=4) PHRASE 32 administration:(pos=5) PHRASE 32 program:(pos=6) PHRASE 32 while:(pos=7) PHRASE 32 the:(pos=8) PHRASE 32 domino:(pos=9) PHRASE 32 server:(pos=10) PHRASE 32 is:(pos=11) PHRASE 32 running:(pos=12) PHRASE 32 either:(pos=13) PHRASE 32 shut:(pos=14) PHRASE 32 down:(pos=15) PHRASE 32 the:(pos=16) PHRASE 32 domino:(pos=17) PHRASE 32 server:(pos=18) PHRASE 32 but:(pos=19) PHRASE 32 keep:(pos=20) PHRASE 32 the:(pos=21) PHRASE 32 file:(pos=22) PHRASE 32 server:(pos=23) PHRASE 32 running:(pos=24) PHRASE 32 or:(pos=25) PHRASE 32 choose:(pos=26) PHRASE 32 the:(pos=27) PHRASE 32 ican:(pos=28) PHRASE 32 labeled:(pos=29) PHRASE 32 lotus:(pos=30) PHRASE 32 notes:(pos=31) PHRASE 32 instead:(pos=32))" }, { "\"+irq +veranderen +xp\"", "(irq:(pos=1) PHRASE 3 veranderen:(pos=2) PHRASE 3 xp:(pos=3))" }, { "\"is not a member of 'operator``global namespace''' + c++", "(is:(pos=1) PHRASE 9 not:(pos=2) PHRASE 9 a:(pos=3) PHRASE 9 member:(pos=4) PHRASE 9 of:(pos=5) PHRASE 9 operator:(pos=6) PHRASE 9 global:(pos=7) PHRASE 9 namespace:(pos=8) PHRASE 9 c++:(pos=9))" }, { "mkdir() failed (File exists) php", "(mkdir:(pos=1) OR Zfail:(pos=2) OR file:(pos=3) OR Zexist:(pos=4) OR Zphp:(pos=5))" }, { "laatsteIndex(int n)", "(laatsteindex:(pos=1) OR Zint:(pos=2) OR Zn:(pos=3))" }, { "\"line+in\" OR \"c8783\"", "((line:(pos=1) PHRASE 2 in:(pos=2)) OR c8783:(pos=3))" }, { "if ($_POST['Submit'])", "(Zif:(pos=1) OR _post:(pos=2) OR submit:(pos=3))" }, { "NEC DVD+-RW ND-1300A", "(nec:(pos=1) OR (dvd+:(pos=2) PHRASE 2 rw:(pos=3)) OR (nd:(pos=4) PHRASE 2 1300a:(pos=5)))" }, { "*String not found* (*String not found*.)", "(string:(pos=1) OR Znot:(pos=2) OR found:(pos=3) OR string:(pos=4) OR Znot:(pos=5) OR found:(pos=6))" }, { "MSI G4Ti4200-TD 128MB (GeForce4 Ti4200)", "(msi:(pos=1) OR (g4ti4200:(pos=2) PHRASE 2 td:(pos=3)) OR 128mb:(pos=4) OR geforce4:(pos=5) OR ti4200:(pos=6))" }, { "href=\"#\"", "href:(pos=1)" }, { "Request.ServerVariables(\"REMOTE_USER\") javascript", "((request:(pos=1) PHRASE 2 servervariables:(pos=2)) OR remote_user:(pos=3) OR Zjavascript:(pos=4))" }, { "XF86Config(-4) waar", "(xf86config:(pos=1) OR 4:(pos=2) OR Zwaar:(pos=3))" }, { "Unknown (tag 2000)", "(unknown:(pos=1) OR Ztag:(pos=2) OR 2000:(pos=3))" }, { "KT4V(MS-6712)", "(kt4v:(pos=1) OR (ms:(pos=2) PHRASE 2 6712:(pos=3)))" }, { "scheduled+AND+nieuwsgroepen+AND+updaten", "(Zschedul:(pos=1) AND Znieuwsgroepen:(pos=2) AND Zupdaten:(pos=3))" }, { "137(netbios-ns)", "(137:(pos=1) OR (netbios:(pos=2) PHRASE 2 ns:(pos=3)))" }, { "HARWARE ERROR, TRACKING SERVO (4:0X09:0X01)", "(harware:(pos=1) OR error:(pos=2) OR tracking:(pos=3) OR servo:(pos=4) OR (4:(pos=5) PHRASE 3 0x09:(pos=6) PHRASE 3 0x01:(pos=7)))" }, { "Chr(10) wat is code van \" teken", "(chr:(pos=1) OR 10:(pos=2) OR Zwat:(pos=3) OR Zis:(pos=4) OR Zcode:(pos=5) OR Zvan:(pos=6) OR Zteken:(pos=7))" }, { "wat is code van \" teken", "(Zwat:(pos=1) OR Zis:(pos=2) OR Zcode:(pos=3) OR Zvan:(pos=4) OR teken:(pos=5))" }, { "The Jet VBA file (VBAJET.dll for 16-bit version, VBAJET32.dll version", "(the:(pos=1) OR jet:(pos=2) OR vba:(pos=3) OR Zfile:(pos=4) OR (vbajet:(pos=5) PHRASE 2 dll:(pos=6)) OR Zfor:(pos=7) OR (16:(pos=8) PHRASE 2 bit:(pos=9)) OR Zversion:(pos=10) OR (vbajet32:(pos=11) PHRASE 2 dll:(pos=12)) OR Zversion:(pos=13))" }, { "Permission denied (publickey,password,keyboard-interactive).", "(permission:(pos=1) OR Zdeni:(pos=2) OR Zpublickey:(pos=3) OR Zpassword:(pos=4) OR (keyboard:(pos=5) PHRASE 2 interactive:(pos=6)))" }, { "De lees- of schrijfbewerking (\"written\") op het geheugen is mislukt", "(de:(pos=1) OR Zlee:(pos=2) OR Zof:(pos=3) OR Zschrijfbewerk:(pos=4) OR written:(pos=5) OR Zop:(pos=6) OR Zhet:(pos=7) OR Zgeheugen:(pos=8) OR Zis:(pos=9) OR Zmislukt:(pos=10))" }, { "Primary IDE channel no 80 conductor cable installed\"", "(primary:(pos=1) OR ide:(pos=2) OR Zchannel:(pos=3) OR Zno:(pos=4) OR 80:(pos=5) OR Zconductor:(pos=6) OR Zcabl:(pos=7) OR installed:(pos=8))" }, { "\"2020 NEAR zoom\"", "(2020:(pos=1) PHRASE 3 near:(pos=2) PHRASE 3 zoom:(pos=3))" }, { "setcookie(\"naam\",\"$user\");", "(setcookie:(pos=1) OR naam:(pos=2) OR user:(pos=3))" }, { "MSI 645 Ultra (MS-6547) Ver1", "(msi:(pos=1) OR 645:(pos=2) OR ultra:(pos=3) OR (ms:(pos=4) PHRASE 2 6547:(pos=5)) OR ver1:(pos=6))" }, { "if ($HTTP", "(Zif:(pos=1) OR http:(pos=2))" }, { "data error(cyclic redundancy check)", "(Zdata:(pos=1) OR error:(pos=2) OR Zcyclic:(pos=3) OR Zredund:(pos=4) OR Zcheck:(pos=5))" }, { "UObject::StaticAllocateObject <- (NULL None) <- UObject::StaticConstructObject <- InitEngine", "((uobject:(pos=1) PHRASE 2 staticallocateobject:(pos=2)) OR null:(pos=3) OR none:(pos=4) OR (uobject:(pos=5) PHRASE 2 staticconstructobject:(pos=6)) OR initengine:(pos=7))" }, { "Failure at step 8 (Creating 3D Device)", "(failure:(pos=1) OR Zat:(pos=2) OR Zstep:(pos=3) OR 8:(pos=4) OR creating:(pos=5) OR 3d:(pos=6) OR device:(pos=7))" }, { "Call Shell(\"notepad.exe\",", "(call:(pos=1) OR shell:(pos=2) OR (notepad:(pos=3) PHRASE 2 exe:(pos=4)))" }, { "2.5\" harddisk converter", "(2.5:(pos=1) OR (harddisk:(pos=2) PHRASE 2 converter:(pos=3)))" }, // FIXME better if " didn't generate a phrase here... { "creative labs \"dvd+rw\"", "(Zcreativ:(pos=1) OR Zlab:(pos=2) OR (dvd:(pos=3) PHRASE 2 rw:(pos=4)))" }, { "\"het beleid van deze computer staat u niet toe interactief", "(het:(pos=1) PHRASE 10 beleid:(pos=2) PHRASE 10 van:(pos=3) PHRASE 10 deze:(pos=4) PHRASE 10 computer:(pos=5) PHRASE 10 staat:(pos=6) PHRASE 10 u:(pos=7) PHRASE 10 niet:(pos=8) PHRASE 10 toe:(pos=9) PHRASE 10 interactief:(pos=10))" }, { "ati radeon \"driver cleaner", "(Zati:(pos=1) OR Zradeon:(pos=2) OR (driver:(pos=3) PHRASE 2 cleaner:(pos=4)))" }, { "\"../\" path", "Zpath:(pos=1)" }, { "(novell client) workstation only", "(Znovel:(pos=1) OR Zclient:(pos=2) OR Zworkstat:(pos=3) OR Zonli:(pos=4))" }, { "Unable to find libgd.(a|so) anywhere", "(unable:(pos=1) OR Zto:(pos=2) OR Zfind:(pos=3) OR Zlibgd:(pos=4) OR Za:(pos=5) OR Zso:(pos=6) OR Zanywher:(pos=7))" }, { "\"libstdc++-libc6.1-1.so.2\"", "(libstdc++:(pos=1) PHRASE 5 libc6.1:(pos=2) PHRASE 5 1:(pos=3) PHRASE 5 so:(pos=4) PHRASE 5 2:(pos=5))" }, { "ipsec_setup (/etc/ipsec.conf, line 1) cannot open configuration file \"/etc/ipsec.conf\" -- `' aborted", "(Zipsec_setup:(pos=1) OR (etc:(pos=2) PHRASE 3 ipsec:(pos=3) PHRASE 3 conf:(pos=4)) OR Zline:(pos=5) OR 1:(pos=6) OR Zcannot:(pos=7) OR Zopen:(pos=8) OR Zconfigur:(pos=9) OR Zfile:(pos=10) OR (etc:(pos=11) PHRASE 3 ipsec:(pos=12) PHRASE 3 conf:(pos=13)) OR Zabort:(pos=14))" }, { "Forwarden van domeinnaam (naar HTTP adres)", "(forwarden:(pos=1) OR Zvan:(pos=2) OR Zdomeinnaam:(pos=3) OR Znaar:(pos=4) OR http:(pos=5) OR Zadr:(pos=6))" }, { "Compaq HP, 146.8 GB (MPN-286716-B22) Hard Drives", "(compaq:(pos=1) OR hp:(pos=2) OR 146.8:(pos=3) OR gb:(pos=4) OR (mpn:(pos=5) PHRASE 3 286716:(pos=6) PHRASE 3 b22:(pos=7)) OR hard:(pos=8) OR drives:(pos=9))" }, { "httpd (no pid file) not running", "(Zhttpd:(pos=1) OR Zno:(pos=2) OR Zpid:(pos=3) OR Zfile:(pos=4) OR Znot:(pos=5) OR Zrun:(pos=6))" }, { "apache httpd (pid file) not running", "(Zapach:(pos=1) OR Zhttpd:(pos=2) OR Zpid:(pos=3) OR Zfile:(pos=4) OR Znot:(pos=5) OR Zrun:(pos=6))" }, { "Klasse is niet geregistreerd (Fout=80040154).", "(klasse:(pos=1) OR Zis:(pos=2) OR Zniet:(pos=3) OR Zgeregistreerd:(pos=4) OR fout:(pos=5) OR 80040154:(pos=6))" }, { "\"dvd+r\" \"dvd-r\"", "((dvd:(pos=1) PHRASE 2 r:(pos=2)) OR (dvd:(pos=3) PHRASE 2 r:(pos=4)))" }, { "\"=\" tekens uit csvfile", "(Zteken:(pos=1) OR Zuit:(pos=2) OR Zcsvfile:(pos=3))" }, { "libc.so.6(GLIBC_2.3)", "((libc:(pos=1) PHRASE 3 so:(pos=2) PHRASE 3 6:(pos=3)) OR glibc_2.3:(pos=4))" }, { "Sitecom Broadband xDSL / Cable Router 4S (DC-202)", "(sitecom:(pos=1) OR broadband:(pos=2) OR Zxdsl:(pos=3) OR cable:(pos=4) OR router:(pos=5) OR 4s:(pos=6) OR (dc:(pos=7) PHRASE 2 202:(pos=8)))" }, { "(t-mobile) bereik", "((t:(pos=1) PHRASE 2 mobile:(pos=2)) OR Zbereik:(pos=3))" }, { "error LNK2001: unresolved external symbol \"public", "(Zerror:(pos=1) OR lnk2001:(pos=2) OR Zunresolv:(pos=3) OR Zextern:(pos=4) OR Zsymbol:(pos=5) OR public:(pos=6))" }, { "patch linux exploit -p)", "(Zpatch:(pos=1) OR Zlinux:(pos=2) OR Zexploit:(pos=3) OR Zp:(pos=4))" }, { "MYD not found (Errcode: 2)", "(myd:(pos=1) OR Znot:(pos=2) OR Zfound:(pos=3) OR errcode:(pos=4) OR 2:(pos=5))" }, { "ob_start(\"ob_gzhandler\"); file download", "(ob_start:(pos=1) OR ob_gzhandler:(pos=2) OR Zfile:(pos=3) OR Zdownload:(pos=4))" }, { "ECS Elitegroup K7VZA (VIA VT8363/VT8363A)", "(ecs:(pos=1) OR elitegroup:(pos=2) OR k7vza:(pos=3) OR via:(pos=4) OR (vt8363:(pos=5) PHRASE 2 vt8363a:(pos=6)))" }, { "ASUS A7V8X (LAN + Serial-ATA + Firewire + Raid + Audio)", "(asus:(pos=1) OR a7v8x:(pos=2) OR lan:(pos=3) OR (serial:(pos=4) PHRASE 2 ata:(pos=5)) OR firewire:(pos=6) OR raid:(pos=7) OR audio:(pos=8))" }, { "Javascript:history.go(-1)", "((javascript:(pos=1) PHRASE 3 history:(pos=2) PHRASE 3 go:(pos=3)) OR 1:(pos=4))" }, { "java :) als icon", "(Zjava:(pos=1) OR Zal:(pos=2) OR Zicon:(pos=3))" }, { "onmouseover=setPointer(this", "(onmouseover:(pos=1) OR setpointer:(pos=2) OR Zthis:(pos=3))" }, { "\" in vbscript", "(in:(pos=1) PHRASE 2 vbscript:(pos=2))" }, { "IRC (FAQ OR (hulp NEAR bij))", "(irc:(pos=1) OR faq:(pos=2) OR (hulp:(pos=3) NEAR 11 bij:(pos=4)))" }, { "setProperty(\"McSquare\"+i, _xscale, _xscale++);", "(setproperty:(pos=1) OR mcsquare:(pos=2) OR Zi:(pos=3) OR _xscale:(pos=4) OR _xscale++:(pos=5))" }, { "[warn] Apache does not support line-end comments. Consider using quotes around argument: \"#-1\"", "(Zwarn:(pos=1) OR apache:(pos=2) OR Zdoe:(pos=3) OR Znot:(pos=4) OR Zsupport:(pos=5) OR (line:(pos=6) PHRASE 2 end:(pos=7)) OR Zcomment:(pos=8) OR consider:(pos=9) OR Zuse:(pos=10) OR Zquot:(pos=11) OR Zaround:(pos=12) OR Zargument:(pos=13) OR 1:(pos=14))" }, { "(php.ini) (memory_limit)", "((php:(pos=1) PHRASE 2 ini:(pos=2)) OR Zmemory_limit:(pos=3))" }, { "line 8: syntax error near unexpected token `kernel_thread(f'", "(Zline:(pos=1) OR 8:(pos=2) OR Zsyntax:(pos=3) OR Zerror:(pos=4) OR Znear:(pos=5) OR Zunexpect:(pos=6) OR Ztoken:(pos=7) OR kernel_thread:(pos=8) OR Zf:(pos=9))" }, { "VXD NAVEX()@)", "(vxd:(pos=1) OR navex:(pos=2))" }, { "\"Iiyama AS4314UT 17\" \"", "(iiyama:(pos=1) PHRASE 3 as4314ut:(pos=2) PHRASE 3 17:(pos=3))" }, { "include (\"$id.html\");", "(Zinclud:(pos=1) OR (id:(pos=2) PHRASE 2 html:(pos=3)))" }, { "include id.Today's date is: <? print (date (\"M d, Y\")); ?>hp", "(Zinclud:(pos=1) OR (id:(pos=2) PHRASE 2 today's:(pos=3)) OR Zdate:(pos=4) OR Zis:(pos=5) OR Zprint:(pos=6) OR Zdate:(pos=7) OR (m:(pos=8) PHRASE 3 d:(pos=9) PHRASE 3 y:(pos=10)) OR Zhp:(pos=11))" }, { "(program files\\common) opstarten", "(Zprogram:(pos=1) OR (files:(pos=2) PHRASE 2 common:(pos=3)) OR Zopstarten:(pos=4))" }, { "java \" string", "(Zjava:(pos=1) OR string:(pos=2))" }, { "+=", "" }, { "php +=", "Zphp:(pos=1)" }, { "[php] ereg_replace(\".\"", "(Zphp:(pos=1) OR ereg_replace:(pos=2))" }, { "\"echo -e\" kleur", "((echo:(pos=1) PHRASE 2 e:(pos=2)) OR Zkleur:(pos=3))" }, { "adobe premiere \"-1\"", "(Zadob:(pos=1) OR Zpremier:(pos=2) OR 1:(pos=3))" }, { "DVD brander \"+\" en \"-\"", "(dvd:(pos=1) OR Zbrander:(pos=2) OR Zen:(pos=3))" }, { "inspirion \"dvd+R\"", "(Zinspirion:(pos=1) OR (dvd:(pos=2) PHRASE 2 r:(pos=3)))" }, { "asp 0x80040E14)", "(Zasp:(pos=1) OR 0x80040e14:(pos=2))" }, { "\"e-tech motorola router", "(e:(pos=1) PHRASE 4 tech:(pos=2) PHRASE 4 motorola:(pos=3) PHRASE 4 router:(pos=4))" }, { "bluetooth '1.3.2.19\"", "(Zbluetooth:(pos=1) OR 1.3.2.19:(pos=2))" }, { "ms +-connect", "(Zms:(pos=1) OR Zconnect:(pos=2))" }, { "php+print+\"", "(Zphp:(pos=1) OR print+:(pos=2))" }, { "athlon 1400 :welke videokaart\"", "(Zathlon:(pos=1) OR 1400:(pos=2) OR Zwelk:(pos=3) OR videokaart:(pos=4))" }, { "+-dvd", "Zdvd:(pos=1)" }, { "glftpd \"-new-\"", "(Zglftpd:(pos=1) OR new:(pos=2))" }, { "\"scandisk + dos5.0", "(scandisk:(pos=1) PHRASE 2 dos5.0:(pos=2))" }, { "socket\\(\\)", "socket:(pos=1)" }, { "msn (e-tech) router", "(Zmsn:(pos=1) OR (e:(pos=2) PHRASE 2 tech:(pos=3)) OR Zrouter:(pos=4))" }, { "Het grote Epox 8k3a+ ervaring/prob topic\"", "(het:(pos=1) OR Zgrote:(pos=2) OR epox:(pos=3) OR 8k3a+:(pos=4) OR (ervaring:(pos=5) PHRASE 2 prob:(pos=6)) OR topic:(pos=7))" }, { "\"CF+bluetooth\"", "(cf:(pos=1) PHRASE 2 bluetooth:(pos=2))" }, { "kwaliteit (s-video) composite verschil tv out", "(Zkwaliteit:(pos=1) OR (s:(pos=2) PHRASE 2 video:(pos=3)) OR Zcomposit:(pos=4) OR Zverschil:(pos=5) OR Ztv:(pos=6) OR Zout:(pos=7))" }, { "Wie kan deze oude hardware nog gebruiken\" Deel", "(wie:(pos=1) OR Zkan:(pos=2) OR Zdeze:(pos=3) OR Zoud:(pos=4) OR Zhardwar:(pos=5) OR Znog:(pos=6) OR gebruiken:(pos=7) OR deel:(pos=8))" }, { "Public Declare Sub Sleep Lib \"kernel32\" (ByVal dwMilliseconds As Long)", "(public:(pos=1) OR declare:(pos=2) OR sub:(pos=3) OR sleep:(pos=4) OR lib:(pos=5) OR kernel32:(pos=6) OR byval:(pos=7) OR Zdwmillisecond:(pos=8) OR as:(pos=9) OR long:(pos=10))" }, { "for inclusion (include_path='.:/usr/share/php')", "(Zfor:(pos=1) OR Zinclus:(pos=2) OR include_path:(pos=3) OR (usr:(pos=4) PHRASE 3 share:(pos=5) PHRASE 3 php:(pos=6)))" }, { "\"muziek 2x zo snel\"\"", "(muziek:(pos=1) PHRASE 4 2x:(pos=2) PHRASE 4 zo:(pos=3) PHRASE 4 snel:(pos=4))" }, { "execCommand('inserthorizontalrule'", "(execcommand:(pos=1) OR Zinserthorizontalrul:(pos=2))" }, { "specs: IBM PS/2, Intel 8086 @ 25 mhz!!, 2 mb intern, 50 mb hd, 5.5\" floppy drive, toetsenbord en geen muis", "(Zspec:(pos=1) OR ibm:(pos=2) OR (ps:(pos=3) PHRASE 2 2:(pos=4)) OR intel:(pos=5) OR 8086:(pos=6) OR 25:(pos=7) OR Zmhz:(pos=8) OR 2:(pos=9) OR Zmb:(pos=10) OR Zintern:(pos=11) OR 50:(pos=12) OR Zmb:(pos=13) OR Zhd:(pos=14) OR 5.5:(pos=15) OR (floppy:(pos=16) PHRASE 6 drive:(pos=17) PHRASE 6 toetsenbord:(pos=18) PHRASE 6 en:(pos=19) PHRASE 6 geen:(pos=20) PHRASE 6 muis:(pos=21)))" }, { "History: GetEventTool <- GetMusicManager <- GetMusicScript <- DMCallRoutine <- AMusicScriptEvent::execCallRoutine <- UObject::execClassContext <- (U2GameInfo M08A1.U2GameInfo0 @ Function U2.U2GameInfo.NotifyLevelChangeEnd : 0075 line 744) <- UObject::ProcessEvent <- (U2GameInfo M08A1.U2GameInfo0, Function U2.U2GameInfo.NotifyLevelChangeEnd) <- UGameEngine::LoadMap <- LocalMapURL <- UGameEngine::Browse <- ServerTravel <- UGameEngine::Tick <- UpdateWorld <- MainLoop", "(history:(pos=1) OR geteventtool:(pos=2) OR getmusicmanager:(pos=3) OR getmusicscript:(pos=4) OR dmcallroutine:(pos=5) OR (amusicscriptevent:(pos=6) PHRASE 2 execcallroutine:(pos=7)) OR (uobject:(pos=8) PHRASE 2 execclasscontext:(pos=9)) OR u2gameinfo:(pos=10) OR (m08a1:(pos=11) PHRASE 2 u2gameinfo0:(pos=12)) OR function:(pos=13) OR (u2:(pos=14) PHRASE 3 u2gameinfo:(pos=15) PHRASE 3 notifylevelchangeend:(pos=16)) OR 0075:(pos=17) OR Zline:(pos=18) OR 744:(pos=19) OR (uobject:(pos=20) PHRASE 2 processevent:(pos=21)) OR u2gameinfo:(pos=22) OR (m08a1:(pos=23) PHRASE 2 u2gameinfo0:(pos=24)) OR function:(pos=25) OR (u2:(pos=26) PHRASE 3 u2gameinfo:(pos=27) PHRASE 3 notifylevelchangeend:(pos=28)) OR (ugameengine:(pos=29) PHRASE 2 loadmap:(pos=30)) OR localmapurl:(pos=31) OR (ugameengine:(pos=32) PHRASE 2 browse:(pos=33)) OR servertravel:(pos=34) OR (ugameengine:(pos=35) PHRASE 2 tick:(pos=36)) OR updateworld:(pos=37) OR mainloop:(pos=38))" }, { "Support AMD XP 2400+ & 2600+ (K7T Turbo2 only)", "(support:(pos=1) OR amd:(pos=2) OR xp:(pos=3) OR 2400+:(pos=4) OR 2600+:(pos=5) OR k7t:(pos=6) OR turbo2:(pos=7) OR Zonli:(pos=8))" }, { "'\"><br>bla</br>", "(br:(pos=1) PHRASE 3 bla:(pos=2) PHRASE 3 br:(pos=3))" }, { "The instruction at \"0x30053409\" referenced memory at \"0x06460504\". The memory could not be \"read'. Click OK to terminate the application.", "(the:(pos=1) OR Zinstruct:(pos=2) OR Zat:(pos=3) OR 0x30053409:(pos=4) OR Zreferenc:(pos=5) OR Zmemori:(pos=6) OR Zat:(pos=7) OR 0x06460504:(pos=8) OR the:(pos=9) OR Zmemori:(pos=10) OR Zcould:(pos=11) OR Znot:(pos=12) OR Zbe:(pos=13) OR (read:(pos=14) PHRASE 7 click:(pos=15) PHRASE 7 ok:(pos=16) PHRASE 7 to:(pos=17) PHRASE 7 terminate:(pos=18) PHRASE 7 the:(pos=19) PHRASE 7 application:(pos=20)))" }, { "\"(P5A-b)\"", "(p5a:(pos=1) PHRASE 2 b:(pos=2))" }, { "(13,5 > 13) == no-go!", "(13,5:(pos=1) OR 13:(pos=2) OR (no:(pos=3) PHRASE 2 go:(pos=4)))" }, { "eth not found \"ifconfig -a\"", "(Zeth:(pos=1) OR Znot:(pos=2) OR Zfound:(pos=3) OR (ifconfig:(pos=4) PHRASE 2 a:(pos=5)))" }, { "<META NAME=\"ROBOTS", "(meta:(pos=1) OR name:(pos=2) OR robots:(pos=3))" }, { "lp0: using parport0 (interrupt-driven)", "(Zlp0:(pos=1) OR Zuse:(pos=2) OR Zparport0:(pos=3) OR (interrupt:(pos=4) PHRASE 2 driven:(pos=5)))" }, { "ULTRA PC-TUNING, COOLING & MODDING (4,6)", "(ultra:(pos=1) OR (pc:(pos=2) PHRASE 2 tuning:(pos=3)) OR cooling:(pos=4) OR modding:(pos=5) OR 4,6:(pos=6))" }, { "512MB PC2700 DDR SDRAM Rood (Dane-Elec)", "(512mb:(pos=1) OR pc2700:(pos=2) OR ddr:(pos=3) OR sdram:(pos=4) OR rood:(pos=5) OR (dane:(pos=6) PHRASE 2 elec:(pos=7)))" }, { "header(\"Content Type: text/html\");", "(header:(pos=1) OR content:(pos=2) OR type:(pos=3) OR (text:(pos=4) PHRASE 2 html:(pos=5)))" }, { "\"-RW\" \"+RW\"", "(rw:(pos=1) OR rw:(pos=2))" }, { "\"cresta digital answering machine", "(cresta:(pos=1) PHRASE 4 digital:(pos=2) PHRASE 4 answering:(pos=3) PHRASE 4 machine:(pos=4))" }, { "Arctic Super Silent PRO TC (Athlon/P3 - 2,3 GHz)", "(arctic:(pos=1) OR super:(pos=2) OR silent:(pos=3) OR pro:(pos=4) OR tc:(pos=5) OR (athlon:(pos=6) PHRASE 2 p3:(pos=7)) OR 2,3:(pos=8) OR ghz:(pos=9))" }, { "c++ fopen \"r+t\"", "(Zc++:(pos=1) OR Zfopen:(pos=2) OR (r:(pos=3) PHRASE 2 t:(pos=4)))" }, { "c++ fopen (r+t)", "(Zc++:(pos=1) OR Zfopen:(pos=2) OR Zr:(pos=3) OR Zt:(pos=4))" }, { "\"DVD+R\"", "(dvd:(pos=1) PHRASE 2 r:(pos=2))" }, { "Class.forName(\"jdbc.odbc.JdbcOdbcDriver\");", "((class:(pos=1) PHRASE 2 forname:(pos=2)) OR (jdbc:(pos=3) PHRASE 3 odbc:(pos=4) PHRASE 3 jdbcodbcdriver:(pos=5)))" }, { "perl(find.pl)", "(perl:(pos=1) OR (find:(pos=2) PHRASE 2 pl:(pos=3)))" }, { "\"-5v\" voeding", "(5v:(pos=1) OR Zvoed:(pos=2))" }, { "\"-5v\" power supply", "(5v:(pos=1) OR Zpower:(pos=2) OR Zsuppli:(pos=3))" }, { "An Error occurred whie attempting to initialize the Borland Database Engine (error $2108)", "(an:(pos=1) OR error:(pos=2) OR Zoccur:(pos=3) OR Zwhie:(pos=4) OR Zattempt:(pos=5) OR Zto:(pos=6) OR Ziniti:(pos=7) OR Zthe:(pos=8) OR borland:(pos=9) OR database:(pos=10) OR engine:(pos=11) OR Zerror:(pos=12) OR 2108:(pos=13))" }, { "(error $2108) Borland", "(Zerror:(pos=1) OR 2108:(pos=2) OR borland:(pos=3))" }, { "On Friday 04 April 2003 09:32, Edwin van Eersel wrote: > ik voel me eigenlijk wel behoorlijk kut :)", "(on:(pos=1) OR friday:(pos=2) OR 04:(pos=3) OR april:(pos=4) OR 2003:(pos=5) OR (09:(pos=6) PHRASE 2 32:(pos=7)) OR edwin:(pos=8) OR Zvan:(pos=9) OR eersel:(pos=10) OR Zwrote:(pos=11) OR Zik:(pos=12) OR Zvoel:(pos=13) OR Zme:(pos=14) OR Zeigenlijk:(pos=15) OR Zwel:(pos=16) OR Zbehoorlijk:(pos=17) OR Zkut:(pos=18))" }, { "Elektrotechniek + \"hoe bevalt het?\"\"", "(elektrotechniek:(pos=1) OR (hoe:(pos=2) PHRASE 3 bevalt:(pos=3) PHRASE 3 het:(pos=4)))" }, { "Shortcuts in menu (java", "(shortcuts:(pos=1) OR Zin:(pos=2) OR Zmenu:(pos=3) OR Zjava:(pos=4))" }, { "detonator+settings\"", "(Zdeton:(pos=1) OR settings:(pos=2))" }, { "(ez-bios) convert", "((ez:(pos=1) PHRASE 2 bios:(pos=2)) OR Zconvert:(pos=3))" }, { "Sparkle 7100M4 64MB (GeForce4 MX440)", "(sparkle:(pos=1) OR 7100m4:(pos=2) OR 64mb:(pos=3) OR geforce4:(pos=4) OR mx440:(pos=5))" }, { "freebsd \"boek OR newbie\"", "(Zfreebsd:(pos=1) OR (boek:(pos=2) PHRASE 3 or:(pos=3) PHRASE 3 newbie:(pos=4)))" }, { "for (;;) c++", "(Zfor:(pos=1) OR Zc++:(pos=2))" }, { "1700+-2100+", "(1700+:(pos=1) PHRASE 2 2100+:(pos=2))" }, { "PHP Warning: Invalid library (maybe not a PHP library) 'libmysqlclient.so'", "(php:(pos=1) OR warning:(pos=2) OR invalid:(pos=3) OR Zlibrari:(pos=4) OR Zmayb:(pos=5) OR Znot:(pos=6) OR Za:(pos=7) OR php:(pos=8) OR Zlibrari:(pos=9) OR (libmysqlclient:(pos=10) PHRASE 2 so:(pos=11)))" }, { "NEC DV-5800B (Bul", "(nec:(pos=1) OR (dv:(pos=2) PHRASE 2 5800b:(pos=3)) OR bul:(pos=4))" }, { "org.jdom.input.SAXBuilder.<init>(SAXBuilder.java)", "((org:(pos=1) PHRASE 4 jdom:(pos=2) PHRASE 4 input:(pos=3) PHRASE 4 saxbuilder:(pos=4)) OR init:(pos=5) OR (saxbuilder:(pos=6) PHRASE 2 java:(pos=7)))" }, { "AMD Athlon XP 2500+ (1,83GHz, 512KB)", "(amd:(pos=1) OR athlon:(pos=2) OR xp:(pos=3) OR 2500+:(pos=4) OR 1,83ghz:(pos=5) OR 512kb:(pos=6))" }, { "'q ben\"", "(Zq:(pos=1) OR ben:(pos=2))" }, { "getsmbfilepwent: malformed password entry (uid not number)", "(Zgetsmbfilepw:(pos=1) OR Zmalform:(pos=2) OR Zpassword:(pos=3) OR Zentri:(pos=4) OR Zuid:(pos=5) OR Znot:(pos=6) OR Znumber:(pos=7))" }, { "\xc3\xb6ude onderdelen\"", "(Z\xc3\xb6ude:(pos=1) OR onderdelen:(pos=2))" }, { "Heeft iemand enig idee waarom de pioneer (zelf met originele firmware van pioneer) bij mij niet wil flashen ?" "?", "(heeft:(pos=1) OR Ziemand:(pos=2) OR Zenig:(pos=3) OR Zide:(pos=4) OR Zwaarom:(pos=5) OR Zde:(pos=6) OR Zpioneer:(pos=7) OR Zzelf:(pos=8) OR Zmet:(pos=9) OR Zoriginel:(pos=10) OR Zfirmwar:(pos=11) OR Zvan:(pos=12) OR Zpioneer:(pos=13) OR Zbij:(pos=14) OR Zmij:(pos=15) OR Zniet:(pos=16) OR Zwil:(pos=17) OR Zflashen:(pos=18))" }, // Split ? and ? to avoid trigram problems { "asus a7v266 bios nieuw -(a7v266-e)", "((Zasus:(pos=1) OR Za7v266:(pos=2) OR Zbio:(pos=3) OR Znieuw:(pos=4)) AND_NOT (a7v266:(pos=5) PHRASE 2 e:(pos=6)))" }, { "cybercom \"dvd+r\"", "(Zcybercom:(pos=1) OR (dvd:(pos=2) PHRASE 2 r:(pos=3)))" }, { "AMD PCNET Family Ethernet Adapter (PCI-ISA)", "(amd:(pos=1) OR pcnet:(pos=2) OR family:(pos=3) OR ethernet:(pos=4) OR adapter:(pos=5) OR (pci:(pos=6) PHRASE 2 isa:(pos=7)))" }, { "relais +/-", "Zrelai:(pos=1)" }, { "formules (slepen OR doortrekken) excel", "(Zformul:(pos=1) OR Zslepen:(pos=2) OR Zdoortrekken:(pos=3) OR Zexcel:(pos=4))" }, { "\"%English", "english:(pos=1)" }, { "select max( mysql", "(Zselect:(pos=1) OR max:(pos=2) OR Zmysql:(pos=3))" }, { "leejow(saait", "(leejow:(pos=1) OR Zsaait:(pos=2))" }, { "'Windows 2000 Advanced Server\" netwerkverbinding valt steeds weg", "(windows:(pos=1) OR 2000:(pos=2) OR advanced:(pos=3) OR server:(pos=4) OR (netwerkverbinding:(pos=5) PHRASE 4 valt:(pos=6) PHRASE 4 steeds:(pos=7) PHRASE 4 weg:(pos=8)))" }, { "K7T Turbo 2 (MS-6330)", "(k7t:(pos=1) OR turbo:(pos=2) OR 2:(pos=3) OR (ms:(pos=4) PHRASE 2 6330:(pos=5)))" }, { "failed to receive data from the client agent. (ec=1)", "(Zfail:(pos=1) OR Zto:(pos=2) OR Zreceiv:(pos=3) OR Zdata:(pos=4) OR Zfrom:(pos=5) OR Zthe:(pos=6) OR Zclient:(pos=7) OR Zagent:(pos=8) OR ec:(pos=9) OR 1:(pos=10))" }, { "\"cannot find -lz\"", "(cannot:(pos=1) PHRASE 3 find:(pos=2) PHRASE 3 lz:(pos=3))" }, { "undefined reference to `mysql_drop_db'\"", "(Zundefin:(pos=1) OR Zrefer:(pos=2) OR Zto:(pos=3) OR Zmysql_drop_db:(pos=4))" }, { "search form asp \"%'", "(Zsearch:(pos=1) OR Zform:(pos=2) OR Zasp:(pos=3))" }, { "(dvd+r) kwaliteit", "(Zdvd:(pos=1) OR Zr:(pos=2) OR Zkwaliteit:(pos=3))" }, { "Fatal error: Allowed memory size of 8388608 bytes exhausted (tried to allocate 35 bytes)", "(fatal:(pos=1) OR Zerror:(pos=2) OR allowed:(pos=3) OR Zmemori:(pos=4) OR Zsize:(pos=5) OR Zof:(pos=6) OR 8388608:(pos=7) OR Zbyte:(pos=8) OR Zexhaust:(pos=9) OR Ztri:(pos=10) OR Zto:(pos=11) OR Zalloc:(pos=12) OR 35:(pos=13) OR Zbyte:(pos=14))" }, { "geluid (schokt OR hapert)", "(Zgeluid:(pos=1) OR Zschokt:(pos=2) OR Zhapert:(pos=3))" }, { "Het wordt pas echt leuk als het hard staat!! >:)", "(het:(pos=1) OR Zwordt:(pos=2) OR Zpas:(pos=3) OR Zecht:(pos=4) OR Zleuk:(pos=5) OR Zal:(pos=6) OR Zhet:(pos=7) OR Zhard:(pos=8) OR Zstaat:(pos=9))" }, { "Uw configuratie bestand bevat instellingen (root zonder wachtwoord) die betrekking hebben tot de standaard MySQL account. Uw MySQL server draait met deze standaard waardes, en is open voor ongewilde toegang, het wordt dus aangeraden dit op te lossen", "(uw:(pos=1) OR Zconfigurati:(pos=2) OR Zbestand:(pos=3) OR Zbevat:(pos=4) OR Zinstellingen:(pos=5) OR Zroot:(pos=6) OR Zzonder:(pos=7) OR Zwachtwoord:(pos=8) OR Zdie:(pos=9) OR Zbetrekk:(pos=10) OR Zhebben:(pos=11) OR Ztot:(pos=12) OR Zde:(pos=13) OR Zstandaard:(pos=14) OR mysql:(pos=15) OR Zaccount:(pos=16) OR uw:(pos=17) OR mysql:(pos=18) OR Zserver:(pos=19) OR Zdraait:(pos=20) OR Zmet:(pos=21) OR Zdeze:(pos=22) OR Zstandaard:(pos=23) OR Zwaard:(pos=24) OR Zen:(pos=25) OR Zis:(pos=26) OR Zopen:(pos=27) OR Zvoor:(pos=28) OR Zongewild:(pos=29) OR Ztoegang:(pos=30) OR Zhet:(pos=31) OR Zwordt:(pos=32) OR Zdus:(pos=33) OR Zaangeraden:(pos=34) OR Zdit:(pos=35) OR Zop:(pos=36) OR Zte:(pos=37) OR Zlossen:(pos=38))" }, { "(library qt-mt) not found", "(Zlibrari:(pos=1) OR (qt:(pos=2) PHRASE 2 mt:(pos=3)) OR Znot:(pos=4) OR Zfound:(pos=5))" }, { "Qt (>= Qt 3.0.3) (library qt-mt) not found", "(qt:(pos=1) OR qt:(pos=2) OR 3.0.3:(pos=3) OR Zlibrari:(pos=4) OR (qt:(pos=5) PHRASE 2 mt:(pos=6)) OR Znot:(pos=7) OR Zfound:(pos=8))" }, { "setup was unable to find (or could not read) the language specific setup resource dll, unable to continue. Please reboot and try again.", "(Zsetup:(pos=1) OR Zwas:(pos=2) OR Zunabl:(pos=3) OR Zto:(pos=4) OR Zfind:(pos=5) OR Zor:(pos=6) OR Zcould:(pos=7) OR Znot:(pos=8) OR Zread:(pos=9) OR Zthe:(pos=10) OR Zlanguag:(pos=11) OR Zspecif:(pos=12) OR Zsetup:(pos=13) OR Zresourc:(pos=14) OR Zdll:(pos=15) OR Zunabl:(pos=16) OR Zto:(pos=17) OR Zcontinu:(pos=18) OR please:(pos=19) OR Zreboot:(pos=20) OR Zand:(pos=21) OR Ztri:(pos=22) OR Zagain:(pos=23))" }, { "Titan TTC-D5TB(4/CU35)", "(titan:(pos=1) OR (ttc:(pos=2) PHRASE 2 d5tb:(pos=3)) OR (4:(pos=4) PHRASE 2 cu35:(pos=5)))" }, { "[php] date( min", "(Zphp:(pos=1) OR date:(pos=2) OR Zmin:(pos=3))" }, { "EPOX EP-8RDA+ (nForce2 SPP+MCP-T) Rev. 1.1", "(epox:(pos=1) OR (ep:(pos=2) PHRASE 2 8rda+:(pos=3)) OR Znforce2:(pos=4) OR spp:(pos=5) OR (mcp:(pos=6) PHRASE 2 t:(pos=7)) OR rev:(pos=8) OR 1.1:(pos=9))" }, { "554 5.4.6 Too many hops 53 (25 max)", "(554:(pos=1) OR 5.4.6:(pos=2) OR too:(pos=3) OR Zmani:(pos=4) OR Zhop:(pos=5) OR 53:(pos=6) OR 25:(pos=7) OR Zmax:(pos=8))" }, { "ik had toch nog een vraagje: er zijn nu eigenlijk alleen maar schijfjes van 4.7GB alleen straks zullen er vast schijfjes van meer dan 4.7GB komen. Zal deze brander dit wel kunnen schijven?" "?(na bijvoorbeeld een firmware update?) ben erg benieuwd", "(Zik:(pos=1) OR Zhad:(pos=2) OR Ztoch:(pos=3) OR Znog:(pos=4) OR Zeen:(pos=5) OR Zvraagj:(pos=6) OR Zer:(pos=7) OR Zzijn:(pos=8) OR Znu:(pos=9) OR Zeigenlijk:(pos=10) OR Zalleen:(pos=11) OR Zmaar:(pos=12) OR Zschijfj:(pos=13) OR Zvan:(pos=14) OR 4.7gb:(pos=15) OR Zalleen:(pos=16) OR Zstrak:(pos=17) OR Zzullen:(pos=18) OR Zer:(pos=19) OR Zvast:(pos=20) OR Zschijfj:(pos=21) OR Zvan:(pos=22) OR Zmeer:(pos=23) OR Zdan:(pos=24) OR 4.7gb:(pos=25) OR Zkomen:(pos=26) OR zal:(pos=27) OR Zdeze:(pos=28) OR Zbrander:(pos=29) OR Zdit:(pos=30) OR Zwel:(pos=31) OR Zkunnen:(pos=32) OR Zschijven:(pos=33) OR Zna:(pos=34) OR Zbijvoorbeeld:(pos=35) OR Zeen:(pos=36) OR Zfirmwar:(pos=37) OR Zupdat:(pos=38) OR Zben:(pos=39) OR Zerg:(pos=40) OR Zbenieuwd:(pos=41))" }, // Split ? and ? to avoid trigram problems { "ati linux drivers (4.3.0)", "(Zati:(pos=1) OR Zlinux:(pos=2) OR Zdriver:(pos=3) OR 4.3.0:(pos=4))" }, { "ENCAPSED_AND_WHITESPACE", "encapsed_and_whitespace:(pos=1)" }, { "lpadmin: add-printer (set device) failed: client-error-not-possible", "(Zlpadmin:(pos=1) OR (add:(pos=2) PHRASE 2 printer:(pos=3)) OR Zset:(pos=4) OR Zdevic:(pos=5) OR Zfail:(pos=6) OR (client:(pos=7) PHRASE 4 error:(pos=8) PHRASE 4 not:(pos=9) PHRASE 4 possible:(pos=10)))" }, { "welke dvd \"+r\" media", "(Zwelk:(pos=1) OR Zdvd:(pos=2) OR r:(pos=3) OR Zmedia:(pos=4))" }, { "Warning: stat failed for fotos(errno=2 - No such file or directory)", "(warning:(pos=1) OR Zstat:(pos=2) OR Zfail:(pos=3) OR Zfor:(pos=4) OR fotos:(pos=5) OR errno:(pos=6) OR 2:(pos=7) OR no:(pos=8) OR Zsuch:(pos=9) OR Zfile:(pos=10) OR Zor:(pos=11) OR Zdirectori:(pos=12))" }, { "dvd +/-", "Zdvd:(pos=1)" }, { "7vaxp +voltage mod\"", "(Zvoltag:(pos=2) AND_MAYBE (7vaxp:(pos=1) OR mod:(pos=3)))" }, { "lpt port (SPP/EPP) is enabled", "(Zlpt:(pos=1) OR Zport:(pos=2) OR (spp:(pos=3) PHRASE 2 epp:(pos=4)) OR Zis:(pos=5) OR Zenabl:(pos=6))" }, { "getenv(\"HTTP_REFERER\")", "(getenv:(pos=1) OR http_referer:(pos=2))" }, { "Error setting display mode: CreateDevice failed (D3DERR_DRIVERINTERNALERROR)", "(error:(pos=1) OR Zset:(pos=2) OR Zdisplay:(pos=3) OR Zmode:(pos=4) OR createdevice:(pos=5) OR Zfail:(pos=6) OR d3derr_driverinternalerror:(pos=7))" }, { "Exception number: c0000005 (access violation)", "(exception:(pos=1) OR Znumber:(pos=2) OR Zc0000005:(pos=3) OR Zaccess:(pos=4) OR Zviolat:(pos=5))" }, { "header(\"Content-type:application/octetstream\");", "(header:(pos=1) OR (content:(pos=2) PHRASE 4 type:(pos=3) PHRASE 4 application:(pos=4) PHRASE 4 octetstream:(pos=5)))" }, { "java.security.AccessControlException: access denied (java.lang.RuntimePermission accessClassInPackage.sun.jdbc.odbc)", "((java:(pos=1) PHRASE 3 security:(pos=2) PHRASE 3 accesscontrolexception:(pos=3)) OR Zaccess:(pos=4) OR Zdeni:(pos=5) OR (java:(pos=6) PHRASE 3 lang:(pos=7) PHRASE 3 runtimepermission:(pos=8)) OR (accessclassinpackage:(pos=9) PHRASE 4 sun:(pos=10) PHRASE 4 jdbc:(pos=11) PHRASE 4 odbc:(pos=12)))" }, { "(001.part.met", "(001:(pos=1) PHRASE 3 part:(pos=2) PHRASE 3 met:(pos=3))" }, { "Warning: mail(): Use the -f option (5th param) to include valid reply-to address ! in /usr/home/vdb/www/mail.php on line 79", "(warning:(pos=1) OR mail:(pos=2) OR use:(pos=3) OR Zthe:(pos=4) OR Zf:(pos=5) OR Zoption:(pos=6) OR 5th:(pos=7) OR Zparam:(pos=8) OR Zto:(pos=9) OR Zinclud:(pos=10) OR Zvalid:(pos=11) OR (reply:(pos=12) PHRASE 2 to:(pos=13)) OR Zaddress:(pos=14) OR Zin:(pos=15) OR (usr:(pos=16) PHRASE 6 home:(pos=17) PHRASE 6 vdb:(pos=18) PHRASE 6 www:(pos=19) PHRASE 6 mail:(pos=20) PHRASE 6 php:(pos=21)) OR Zon:(pos=22) OR Zline:(pos=23) OR 79:(pos=24))" }, { "PHP Use the -f option (5th param)", "((php:(pos=1) OR use:(pos=2) OR Zthe:(pos=3) OR Zoption:(pos=5) OR 5th:(pos=6) OR Zparam:(pos=7)) AND_NOT Zf:(pos=4))" }, { "dvd \"+\" \"-\"", "Zdvd:(pos=1)" }, { "bericht ( %)", "Zbericht:(pos=1)" }, { "2500+ of 2600+ (niett OC)", "(2500+:(pos=1) OR Zof:(pos=2) OR 2600+:(pos=3) OR Zniett:(pos=4) OR oc:(pos=5))" }, { "maxtor windows xp werkt The drivers for this device are not installed. (Code 28)", "(Zmaxtor:(pos=1) OR Zwindow:(pos=2) OR Zxp:(pos=3) OR Zwerkt:(pos=4) OR the:(pos=5) OR Zdriver:(pos=6) OR Zfor:(pos=7) OR Zthis:(pos=8) OR Zdevic:(pos=9) OR Zare:(pos=10) OR Znot:(pos=11) OR Zinstal:(pos=12) OR code:(pos=13) OR 28:(pos=14))" }, { "Warning: stat failed for /mnt/web/react/got/react/board/non-www/headlines/tnet-headlines.txt (errno=2 - No such file or directory) in /mnt/web/react/got/react/global/non-www/templates/got/functions.inc.php on line 303", "(warning:(pos=1) OR Zstat:(pos=2) OR Zfail:(pos=3) OR Zfor:(pos=4) OR (mnt:(pos=5) PHRASE 12 web:(pos=6) PHRASE 12 react:(pos=7) PHRASE 12 got:(pos=8) PHRASE 12 react:(pos=9) PHRASE 12 board:(pos=10) PHRASE 12 non:(pos=11) PHRASE 12 www:(pos=12) PHRASE 12 headlines:(pos=13) PHRASE 12 tnet:(pos=14) PHRASE 12 headlines:(pos=15) PHRASE 12 txt:(pos=16)) OR errno:(pos=17) OR 2:(pos=18) OR no:(pos=19) OR Zsuch:(pos=20) OR Zfile:(pos=21) OR Zor:(pos=22) OR Zdirectori:(pos=23) OR Zin:(pos=24) OR (mnt:(pos=25) PHRASE 13 web:(pos=26) PHRASE 13 react:(pos=27) PHRASE 13 got:(pos=28) PHRASE 13 react:(pos=29) PHRASE 13 global:(pos=30) PHRASE 13 non:(pos=31) PHRASE 13 www:(pos=32) PHRASE 13 templates:(pos=33) PHRASE 13 got:(pos=34) PHRASE 13 functions:(pos=35) PHRASE 13 inc:(pos=36) PHRASE 13 php:(pos=37)) OR Zon:(pos=38) OR Zline:(pos=39) OR 303:(pos=40))" }, { "apm: BIOS version 1.2 Flags 0x03 (Driver version 1.16)", "(Zapm:(pos=1) OR bios:(pos=2) OR Zversion:(pos=3) OR 1.2:(pos=4) OR flags:(pos=5) OR 0x03:(pos=6) OR driver:(pos=7) OR Zversion:(pos=8) OR 1.16:(pos=9))" }, { "GA-8IHXP(3.0)", "((ga:(pos=1) PHRASE 2 8ihxp:(pos=2)) OR 3.0:(pos=3))" }, { "8IHXP(3.0)", "(8ihxp:(pos=1) OR 3.0:(pos=2))" }, { "na\xc2\xb7si (de ~ (m.))", "(Zna\xc2\xb7si:(pos=1) OR Zde:(pos=2) OR Zm:(pos=3))" }, { "header(\"Content-Disposition: attachment;", "(header:(pos=1) OR (content:(pos=2) PHRASE 3 disposition:(pos=3) PHRASE 3 attachment:(pos=4)))" }, { "\"header(\"Content-Disposition: attachment;\"", "(header:(pos=1) OR (content:(pos=2) PHRASE 2 disposition:(pos=3)) OR Zattach:(pos=4))" }, { "\"Beep -f\"", "(beep:(pos=1) PHRASE 2 f:(pos=2))" }, { "kraan NEAR (Elektrisch OR Electrisch)", "(Zkraan:(pos=1) OR near:(pos=2) OR elektrisch:(pos=3) OR or:(pos=4) OR electrisch:(pos=5))" }, { "checking for Qt... configure: error: Qt (>= Qt 3.0.2) (headers and libraries) not found. Please check your installation!", "(Zcheck:(pos=1) OR Zfor:(pos=2) OR qt:(pos=3) OR Zconfigur:(pos=4) OR Zerror:(pos=5) OR qt:(pos=6) OR qt:(pos=7) OR 3.0.2:(pos=8) OR Zheader:(pos=9) OR Zand:(pos=10) OR Zlibrari:(pos=11) OR Znot:(pos=12) OR Zfound:(pos=13) OR please:(pos=14) OR Zcheck:(pos=15) OR Zyour:(pos=16) OR Zinstal:(pos=17))" }, { "parse error, unexpected '\\\"', expecting T_STRING or T_VARIABLE or T_NUM_STRING", "(Zpars:(pos=1) OR Zerror:(pos=2) OR Zunexpect:(pos=3) OR (expecting:(pos=4) PHRASE 6 t_string:(pos=5) PHRASE 6 or:(pos=6) PHRASE 6 t_variable:(pos=7) PHRASE 6 or:(pos=8) PHRASE 6 t_num_string:(pos=9)))" }, { "ac3 (0x2000) \"Dolby Laboratories,", "(Zac3:(pos=1) OR 0x2000:(pos=2) OR (dolby:(pos=3) PHRASE 2 laboratories:(pos=4)))" }, { "Movie.FileName=(\"../../../~animations/\"+lesson1.recordset.fields('column3')+\"Intro.avi\")", "((movie:(pos=1) PHRASE 2 filename:(pos=2)) OR animations:(pos=3) OR (lesson1:(pos=4) PHRASE 3 recordset:(pos=5) PHRASE 3 fields:(pos=6)) OR Zcolumn3:(pos=7) OR (intro:(pos=8) PHRASE 2 avi:(pos=9)))" }, { "502 Permission Denied - Permission Denied - news.chello.nl -- http://www.chello.nl/ (Typhoon v1.2.3)", "(502:(pos=1) OR permission:(pos=2) OR denied:(pos=3) OR permission:(pos=4) OR denied:(pos=5) OR (news:(pos=6) PHRASE 3 chello:(pos=7) PHRASE 3 nl:(pos=8)) OR (http:(pos=9) PHRASE 4 www:(pos=10) PHRASE 4 chello:(pos=11) PHRASE 4 nl:(pos=12)) OR typhoon:(pos=13) OR Zv1.2.3:(pos=14))" }, { "Motion JPEG (MJPEG codec)", "(motion:(pos=1) OR jpeg:(pos=2) OR mjpeg:(pos=3) OR Zcodec:(pos=4))" }, { ": zoomtext\"", "zoomtext:(pos=1)" }, { "Your SORT command does not seem to support the \"-r -n -k 7\"", "(your:(pos=1) OR sort:(pos=2) OR Zcommand:(pos=3) OR Zdoe:(pos=4) OR Znot:(pos=5) OR Zseem:(pos=6) OR Zto:(pos=7) OR Zsupport:(pos=8) OR Zthe:(pos=9) OR (r:(pos=10) PHRASE 4 n:(pos=11) PHRASE 4 k:(pos=12) PHRASE 4 7:(pos=13)))" }, { "Geef de naam van de MSDOS prompt op C:\\\\WINDOWS.COM\\\"", "(geef:(pos=1) OR Zde:(pos=2) OR Znaam:(pos=3) OR Zvan:(pos=4) OR Zde:(pos=5) OR msdos:(pos=6) OR Zprompt:(pos=7) OR Zop:(pos=8) OR (c:(pos=9) PHRASE 3 windows:(pos=10) PHRASE 3 com:(pos=11)))" }, { "\"\"wa is fase\"", "(Zwa:(pos=1) OR Zis:(pos=2) OR fase:(pos=3))" }, { "<v:imagedata src=\"", "((v:(pos=1) PHRASE 2 imagedata:(pos=2)) OR src:(pos=3))" }, { "system(play ringin.wav); ?>", "(system:(pos=1) OR Zplay:(pos=2) OR (ringin:(pos=3) PHRASE 2 wav:(pos=4)))" }, { "\"perfect NEAR systems\"", "(perfect:(pos=1) PHRASE 3 near:(pos=2) PHRASE 3 systems:(pos=3))" }, { "LoadLibrary(\"mainta/gamex86.dll\") failed", "(loadlibrary:(pos=1) OR (mainta:(pos=2) PHRASE 3 gamex86:(pos=3) PHRASE 3 dll:(pos=4)) OR Zfail:(pos=5))" }, { "DATE_FORMAT('1997-10-04 22:23:00', '%W %M %Y');", "(date_format:(pos=1) OR (1997:(pos=2) PHRASE 3 10:(pos=3) PHRASE 3 04:(pos=4)) OR (22:(pos=5) PHRASE 3 23:(pos=6) PHRASE 3 00:(pos=7)) OR w:(pos=8) OR m:(pos=9) OR y:(pos=10))" }, { "secundaire IDE-controller (dubbele fifo)", "(Zsecundair:(pos=1) OR (ide:(pos=2) PHRASE 2 controller:(pos=3)) OR Zdubbel:(pos=4) OR Zfifo:(pos=5))" }, { "\"Postal2+Explorer.exe\"", "(postal2:(pos=1) PHRASE 3 explorer:(pos=2) PHRASE 3 exe:(pos=3))" }, { "COUNT(*)", "count:(pos=1)" }, { "Nuttige Windows progs (1/11)", "(nuttige:(pos=1) OR windows:(pos=2) OR Zprog:(pos=3) OR (1:(pos=4) PHRASE 2 11:(pos=5)))" }, { "if(usercode==passcode==)", "(if:(pos=1) OR usercode:(pos=2) OR passcode:(pos=3))" }, { "lg 8160b (dvd+r)", "(Zlg:(pos=1) OR 8160b:(pos=2) OR Zdvd:(pos=3) OR Zr:(pos=4))" }, { "iPAQ Pocket PC 2002 End User Update (EUU - Service Pack)", "(Zipaq:(pos=1) OR pocket:(pos=2) OR pc:(pos=3) OR 2002:(pos=4) OR end:(pos=5) OR user:(pos=6) OR update:(pos=7) OR euu:(pos=8) OR service:(pos=9) OR pack:(pos=10))" }, { "'ipod pakt tags niet\"", "(Zipod:(pos=1) OR Zpakt:(pos=2) OR Ztag:(pos=3) OR niet:(pos=4))" }, { "\"DVD+/-R\"", "(dvd+:(pos=1) PHRASE 2 r:(pos=2))" }, { "\"DVD+R DVD-R\"", "(dvd:(pos=1) PHRASE 4 r:(pos=2) PHRASE 4 dvd:(pos=3) PHRASE 4 r:(pos=4))" }, { "php ;) in een array zetten", "(Zphp:(pos=1) OR Zin:(pos=2) OR Zeen:(pos=3) OR Zarray:(pos=4) OR Zzetten:(pos=5))" }, { "De inhoud van uw advertentie is niet geschikt voor plaatsing op marktplaats! (001", "(de:(pos=1) OR Zinhoud:(pos=2) OR Zvan:(pos=3) OR Zuw:(pos=4) OR Zadvertenti:(pos=5) OR Zis:(pos=6) OR Zniet:(pos=7) OR Zgeschikt:(pos=8) OR Zvoor:(pos=9) OR Zplaats:(pos=10) OR Zop:(pos=11) OR Zmarktplaat:(pos=12) OR 001:(pos=13))" }, { "creative (soundblaster OR sb) 128", "(Zcreativ:(pos=1) OR Zsoundblast:(pos=2) OR Zsb:(pos=3) OR 128:(pos=4))" }, { "Can't open file: (errno: 145)", "(can't:(pos=1) OR Zopen:(pos=2) OR Zfile:(pos=3) OR Zerrno:(pos=4) OR 145:(pos=5))" }, { "Formateren lukt niet(98,XP)", "(formateren:(pos=1) OR Zlukt:(pos=2) OR niet:(pos=3) OR 98:(pos=4) OR xp:(pos=5))" }, { "access denied (java.io.", "(Zaccess:(pos=1) OR Zdeni:(pos=2) OR (java:(pos=3) PHRASE 2 io:(pos=4)))" }, { "(access denied (java.io.)", "(Zaccess:(pos=1) OR Zdeni:(pos=2) OR (java:(pos=3) PHRASE 2 io:(pos=4)))" }, { "wil niet installeren ( crc fouten)", "(Zwil:(pos=1) OR Zniet:(pos=2) OR Zinstalleren:(pos=3) OR Zcrc:(pos=4) OR Zfouten:(pos=5))" }, { "(DVD+RW) brandsoftware meerdere", "(dvd:(pos=1) OR rw:(pos=2) OR Zbrandsoftwar:(pos=3) OR Zmeerder:(pos=4))" }, { "(database OF databases) EN geheugen", "(Zdatabas:(pos=1) OR of:(pos=2) OR Zdatabas:(pos=3) OR en:(pos=4) OR Zgeheugen:(pos=5))" }, { "(server 2003) winroute", "(Zserver:(pos=1) OR 2003:(pos=2) OR Zwinrout:(pos=3))" }, { "54MHz (kanaal 2 VHF) tot tenminste 806 MHz (kanaal 69 UHF)", "(54mhz:(pos=1) OR Zkanaal:(pos=2) OR 2:(pos=3) OR vhf:(pos=4) OR Ztot:(pos=5) OR Ztenminst:(pos=6) OR 806:(pos=7) OR mhz:(pos=8) OR Zkanaal:(pos=9) OR 69:(pos=10) OR uhf:(pos=11))" }, { "(draadloos OR wireless) netwerk", "(Zdraadloo:(pos=1) OR Zwireless:(pos=2) OR Znetwerk:(pos=3))" }, { "localtime(time(NULL));", "(localtime:(pos=1) OR time:(pos=2) OR null:(pos=3))" }, { "ob_start(\"ob_gzhandler\");", "(ob_start:(pos=1) OR ob_gzhandler:(pos=2))" }, { "PPP Closed : LCP Time-out (VPN-0)", "(ppp:(pos=1) OR closed:(pos=2) OR lcp:(pos=3) OR (time:(pos=4) PHRASE 2 out:(pos=5)) OR (vpn:(pos=6) PHRASE 2 0:(pos=7)))" }, { "COM+-gebeurtenissysteem", "(com+:(pos=1) PHRASE 2 gebeurtenissysteem:(pos=2))" }, { "rcpthosts (#5.7.1)", "(Zrcpthost:(pos=1) OR 5.7.1:(pos=2))" }, { "Dit apparaat werkt niet goed omdat Windows de voor dit apparaat vereiste stuurprogramma's niet kan laden. (Code 31)", "(dit:(pos=1) OR Zapparaat:(pos=2) OR Zwerkt:(pos=3) OR Zniet:(pos=4) OR Zgo:(pos=5) OR Zomdat:(pos=6) OR windows:(pos=7) OR Zde:(pos=8) OR Zvoor:(pos=9) OR Zdit:(pos=10) OR Zapparaat:(pos=11) OR Zvereist:(pos=12) OR Zstuurprogramma:(pos=13) OR Zniet:(pos=14) OR Zkan:(pos=15) OR Zladen:(pos=16) OR code:(pos=17) OR 31:(pos=18))" }, { "window.open( scrollbar", "((window:(pos=1) PHRASE 2 open:(pos=2)) OR Zscrollbar:(pos=3))" }, { "T68i truc ->", "(t68i:(pos=1) OR Ztruc:(pos=2))" }, { "T68i ->", "t68i:(pos=1)" }, { "\"de lijn is bezet\"\"", "(de:(pos=1) PHRASE 4 lijn:(pos=2) PHRASE 4 is:(pos=3) PHRASE 4 bezet:(pos=4))" }, { "if (eregi(\"", "(Zif:(pos=1) OR eregi:(pos=2))" }, { "This device is not working properly because Windows cannot load the drivers required for this device. (Code 31)", "(this:(pos=1) OR Zdevic:(pos=2) OR Zis:(pos=3) OR Znot:(pos=4) OR Zwork:(pos=5) OR Zproper:(pos=6) OR Zbecaus:(pos=7) OR windows:(pos=8) OR Zcannot:(pos=9) OR Zload:(pos=10) OR Zthe:(pos=11) OR Zdriver:(pos=12) OR Zrequir:(pos=13) OR Zfor:(pos=14) OR Zthis:(pos=15) OR Zdevic:(pos=16) OR code:(pos=17) OR 31:(pos=18))" }, { "execCommand(\"Paste\");", "(execcommand:(pos=1) OR paste:(pos=2))" }, { "\"-1 unread\"", "(1:(pos=1) PHRASE 2 unread:(pos=2))" }, { "\"www.historical-fire-engines", "(www:(pos=1) PHRASE 4 historical:(pos=2) PHRASE 4 fire:(pos=3) PHRASE 4 engines:(pos=4))" }, { "\"DVD+RW\" erase", "((dvd:(pos=1) PHRASE 2 rw:(pos=2)) OR Zeras:(pos=3))" }, { "[showjekamer)", "Zshowjekam:(pos=1)" }, { "The description for Event ID 1 in Source True Vector Engine ) cannot be found. The local computer may not have the necessary registry information or message DLL files to display messages from a remote computer. You may be able to use the /AUXSOURC", "(the:(pos=1) OR Zdescript:(pos=2) OR Zfor:(pos=3) OR event:(pos=4) OR id:(pos=5) OR 1:(pos=6) OR Zin:(pos=7) OR source:(pos=8) OR true:(pos=9) OR vector:(pos=10) OR engine:(pos=11) OR Zcannot:(pos=12) OR Zbe:(pos=13) OR Zfound:(pos=14) OR the:(pos=15) OR Zlocal:(pos=16) OR Zcomput:(pos=17) OR Zmay:(pos=18) OR Znot:(pos=19) OR Zhave:(pos=20) OR Zthe:(pos=21) OR Znecessari:(pos=22) OR Zregistri:(pos=23) OR Zinform:(pos=24) OR Zor:(pos=25) OR Zmessag:(pos=26) OR dll:(pos=27) OR Zfile:(pos=28) OR Zto:(pos=29) OR Zdisplay:(pos=30) OR Zmessag:(pos=31) OR Zfrom:(pos=32) OR Za:(pos=33) OR Zremot:(pos=34) OR Zcomput:(pos=35) OR you:(pos=36) OR Zmay:(pos=37) OR Zbe:(pos=38) OR Zabl:(pos=39) OR Zto:(pos=40) OR Zuse:(pos=41) OR Zthe:(pos=42) OR auxsourc:(pos=43))" }, { "org.apache.jasper.JasperException: This absolute uri (http://java.sun.com/jstl/core) cannot be resolved in either web.xml or the jar files deployed with this application", "((org:(pos=1) PHRASE 4 apache:(pos=2) PHRASE 4 jasper:(pos=3) PHRASE 4 jasperexception:(pos=4)) OR this:(pos=5) OR Zabsolut:(pos=6) OR Zuri:(pos=7) OR (http:(pos=8) PHRASE 6 java:(pos=9) PHRASE 6 sun:(pos=10) PHRASE 6 com:(pos=11) PHRASE 6 jstl:(pos=12) PHRASE 6 core:(pos=13)) OR Zcannot:(pos=14) OR Zbe:(pos=15) OR Zresolv:(pos=16) OR Zin:(pos=17) OR Zeither:(pos=18) OR (web:(pos=19) PHRASE 2 xml:(pos=20)) OR Zor:(pos=21) OR Zthe:(pos=22) OR Zjar:(pos=23) OR Zfile:(pos=24) OR Zdeploy:(pos=25) OR Zwith:(pos=26) OR Zthis:(pos=27) OR Zapplic:(pos=28))" }, { "This absolute uri (http://java.sun.com/jstl/core) cannot be resolved in either web.xml or the jar files deployed with this application", "(this:(pos=1) OR Zabsolut:(pos=2) OR Zuri:(pos=3) OR (http:(pos=4) PHRASE 6 java:(pos=5) PHRASE 6 sun:(pos=6) PHRASE 6 com:(pos=7) PHRASE 6 jstl:(pos=8) PHRASE 6 core:(pos=9)) OR Zcannot:(pos=10) OR Zbe:(pos=11) OR Zresolv:(pos=12) OR Zin:(pos=13) OR Zeither:(pos=14) OR (web:(pos=15) PHRASE 2 xml:(pos=16)) OR Zor:(pos=17) OR Zthe:(pos=18) OR Zjar:(pos=19) OR Zfile:(pos=20) OR Zdeploy:(pos=21) OR Zwith:(pos=22) OR Zthis:(pos=23) OR Zapplic:(pos=24))" }, { "vervangen # \"/", "Zvervangen:(pos=1)" }, { "vervangen # /\"", "Zvervangen:(pos=1)" }, { "while(list($key, $val) = each($HTTP_POST_VARS))", "(while:(pos=1) OR list:(pos=2) OR Zkey:(pos=3) OR Zval:(pos=4) OR each:(pos=5) OR http_post_vars:(pos=6))" }, { "PowerDVD does not support the current display mode. (DDraw Overlay mode is recommended)", "(powerdvd:(pos=1) OR Zdoe:(pos=2) OR Znot:(pos=3) OR Zsupport:(pos=4) OR Zthe:(pos=5) OR Zcurrent:(pos=6) OR Zdisplay:(pos=7) OR Zmode:(pos=8) OR ddraw:(pos=9) OR overlay:(pos=10) OR Zmode:(pos=11) OR Zis:(pos=12) OR Zrecommend:(pos=13))" }, { "Warning: Unexpected character in input: '' (ASCII=92) state=1 highlight", "(warning:(pos=1) OR unexpected:(pos=2) OR Zcharact:(pos=3) OR Zin:(pos=4) OR Zinput:(pos=5) OR ascii:(pos=6) OR 92:(pos=7) OR state:(pos=8) OR 1:(pos=9) OR Zhighlight:(pos=10))" }, { "error: Qt-1.4 (headers and libraries) not found. Please check your installation!", "(Zerror:(pos=1) OR (qt:(pos=2) PHRASE 2 1.4:(pos=3)) OR Zheader:(pos=4) OR Zand:(pos=5) OR Zlibrari:(pos=6) OR Znot:(pos=7) OR Zfound:(pos=8) OR please:(pos=9) OR Zcheck:(pos=10) OR Zyour:(pos=11) OR Zinstal:(pos=12))" }, { "Error while initializing the sound driver: device /dev/dsp can't be opened (No such device) The sound server will continue, using the null output device.", "(error:(pos=1) OR Zwhile:(pos=2) OR Ziniti:(pos=3) OR Zthe:(pos=4) OR Zsound:(pos=5) OR Zdriver:(pos=6) OR Zdevic:(pos=7) OR (dev:(pos=8) PHRASE 2 dsp:(pos=9)) OR Zcan't:(pos=10) OR Zbe:(pos=11) OR Zopen:(pos=12) OR no:(pos=13) OR Zsuch:(pos=14) OR Zdevic:(pos=15) OR the:(pos=16) OR Zsound:(pos=17) OR Zserver:(pos=18) OR Zwill:(pos=19) OR Zcontinu:(pos=20) OR Zuse:(pos=21) OR Zthe:(pos=22) OR Znull:(pos=23) OR Zoutput:(pos=24) OR Zdevic:(pos=25))" }, { "mag mijn waarschuwing nu weg ? ;)", "(Zmag:(pos=1) OR Zmijn:(pos=2) OR Zwaarschuw:(pos=3) OR Znu:(pos=4) OR Zweg:(pos=5))" }, { "Abit NF7-S (nForce 2 Chipset) Rev 2.0", "(abit:(pos=1) OR (nf7:(pos=2) PHRASE 2 s:(pos=3)) OR Znforc:(pos=4) OR 2:(pos=5) OR chipset:(pos=6) OR rev:(pos=7) OR 2.0:(pos=8))" }, { "Setup Could Not Verify the Integrity of the File\" Error Message Occurs When You Try to Install Windows XP Service Pack 1", "(setup:(pos=1) OR could:(pos=2) OR not:(pos=3) OR verify:(pos=4) OR Zthe:(pos=5) OR integrity:(pos=6) OR Zof:(pos=7) OR Zthe:(pos=8) OR file:(pos=9) OR (error:(pos=10) PHRASE 13 message:(pos=11) PHRASE 13 occurs:(pos=12) PHRASE 13 when:(pos=13) PHRASE 13 you:(pos=14) PHRASE 13 try:(pos=15) PHRASE 13 to:(pos=16) PHRASE 13 install:(pos=17) PHRASE 13 windows:(pos=18) PHRASE 13 xp:(pos=19) PHRASE 13 service:(pos=20) PHRASE 13 pack:(pos=21) PHRASE 13 1:(pos=22)))" }, { "(browser 19) citrix", "(Zbrowser:(pos=1) OR 19:(pos=2) OR Zcitrix:(pos=3))" }, { "preg_replace (.*?)", "Zpreg_replac:(pos=1)" }, { "formule excel #naam\"?\"", "(Zformul:(pos=1) OR Zexcel:(pos=2) OR naam:(pos=3))" }, { "->", "" }, { "De instructie op 0x77f436f7 verwijst naar geheugen op 0x007f4778. De lees-of schrijfbewerking (\"written\") op het geheugen is mislukt", "(de:(pos=1) OR Zinstructi:(pos=2) OR Zop:(pos=3) OR 0x77f436f7:(pos=4) OR Zverwijst:(pos=5) OR Znaar:(pos=6) OR Zgeheugen:(pos=7) OR Zop:(pos=8) OR 0x007f4778:(pos=9) OR de:(pos=10) OR (lees:(pos=11) PHRASE 2 of:(pos=12)) OR Zschrijfbewerk:(pos=13) OR written:(pos=14) OR Zop:(pos=15) OR Zhet:(pos=16) OR Zgeheugen:(pos=17) OR Zis:(pos=18) OR Zmislukt:(pos=19))" }, { "<iframe src=\"www.tweakers.net></iframe>", "(Zifram:(pos=1) OR src:(pos=2) OR (www:(pos=3) PHRASE 4 tweakers:(pos=4) PHRASE 4 net:(pos=5) PHRASE 4 iframe:(pos=6)))" }, { "\"rpm -e httpd\"", "(rpm:(pos=1) PHRASE 3 e:(pos=2) PHRASE 3 httpd:(pos=3))" }, { "automatisch op All Flis (*.*)", "(Zautomatisch:(pos=1) OR Zop:(pos=2) OR all:(pos=3) OR flis:(pos=4))" }, { "(Windows; U; Windows NT 5.1; en-US; rv:1.3b) Gecko/20030210", "(windows:(pos=1) OR u:(pos=2) OR windows:(pos=3) OR nt:(pos=4) OR 5.1:(pos=5) OR (en:(pos=6) PHRASE 2 us:(pos=7)) OR (rv:(pos=8) PHRASE 2 1.3b:(pos=9)) OR (gecko:(pos=10) PHRASE 2 20030210:(pos=11)))" }, { "en-US; rv:1.3b) Gecko/20030210", "((en:(pos=1) PHRASE 2 us:(pos=2)) OR (rv:(pos=3) PHRASE 2 1.3b:(pos=4)) OR (gecko:(pos=5) PHRASE 2 20030210:(pos=6)))" }, { "\"en-US; rv:1.3b) Gecko/20030210\"", "(en:(pos=1) PHRASE 6 us:(pos=2) PHRASE 6 rv:(pos=3) PHRASE 6 1.3b:(pos=4) PHRASE 6 gecko:(pos=5) PHRASE 6 20030210:(pos=6))" }, { "(./) chmod.sh", "(chmod:(pos=1) PHRASE 2 sh:(pos=2))" }, { "document.write(ssg(\" html", "((document:(pos=1) PHRASE 2 write:(pos=2)) OR ssg:(pos=3) OR html:(pos=4))" }, { "superstack \"mac+adressen\"", "(Zsuperstack:(pos=1) OR (mac:(pos=2) PHRASE 2 adressen:(pos=3)))" }, { "IIS getenv(REMOTE_HOST)_", "(iis:(pos=1) OR getenv:(pos=2) OR remote_host:(pos=3) OR _:(pos=4))" }, { "IIS en getenv(REMOTE_HOST)", "(iis:(pos=1) OR Zen:(pos=2) OR getenv:(pos=3) OR remote_host:(pos=4))" }, { "php getenv(\"HTTP_REFERER\")", "(Zphp:(pos=1) OR getenv:(pos=2) OR http_referer:(pos=3))" }, { "nec+-1300", "(nec+:(pos=1) PHRASE 2 1300:(pos=2))" }, { "smbpasswd script \"-s\"", "(Zsmbpasswd:(pos=1) OR Zscript:(pos=2) OR s:(pos=3))" }, { "leestekens \" \xc3\xb6 \xc3\xab", "(Zleesteken:(pos=1) OR (\xc3\xb6:(pos=2) PHRASE 2 \xc3\xab:(pos=3)))" }, { "freesco and (all seeing eye)", "(Zfreesco:(pos=1) OR Zand:(pos=2) OR Zall:(pos=3) OR Zsee:(pos=4) OR Zeye:(pos=5))" }, { "('all seeing eye') and freesco", "(Zall:(pos=1) OR Zsee:(pos=2) OR Zeye:(pos=3) OR Zand:(pos=4) OR Zfreesco:(pos=5))" }, { "\"[......\"", "" }, { "Error = 11004 (500 No Data (Winsock error #11004))", "(error:(pos=1) OR 11004:(pos=2) OR 500:(pos=3) OR no:(pos=4) OR data:(pos=5) OR winsock:(pos=6) OR Zerror:(pos=7) OR 11004:(pos=8))" }, { "gegevensfout (cyclishe redundantiecontrole)", "(Zgegevensfout:(pos=1) OR Zcyclish:(pos=2) OR Zredundantiecontrol:(pos=3))" }, { "firmware versie waar NEC\"", "(Zfirmwar:(pos=1) OR Zversi:(pos=2) OR Zwaar:(pos=3) OR nec:(pos=4))" }, { "nu.nl \"-1\"", "((nu:(pos=1) PHRASE 2 nl:(pos=2)) OR 1:(pos=3))" }, { "provider+-webspace", "(provider+:(pos=1) PHRASE 2 webspace:(pos=2))" }, { "verschil \"dvd+rw\" \"dvd-rw\"", "(Zverschil:(pos=1) OR (dvd:(pos=2) PHRASE 2 rw:(pos=3)) OR (dvd:(pos=4) PHRASE 2 rw:(pos=5)))" }, { "(dhcp client) + hangt", "(Zdhcp:(pos=1) OR Zclient:(pos=2) OR Zhangt:(pos=3))" }, { "MSI 875P Neo-FIS2R (Intel 875P)", "(msi:(pos=1) OR 875p:(pos=2) OR (neo:(pos=3) PHRASE 2 fis2r:(pos=4)) OR intel:(pos=5) OR 875p:(pos=6))" }, { "voeding passief gekoeld\"", "(Zvoed:(pos=1) OR Zpassief:(pos=2) OR gekoeld:(pos=3))" }, { "if (mysql_num_rows($resultaat)==1)", "(Zif:(pos=1) OR mysql_num_rows:(pos=2) OR Zresultaat:(pos=3) OR 1:(pos=4))" }, { "Server.CreateObject(\"Persits.Upload.1\")", "((server:(pos=1) PHRASE 2 createobject:(pos=2)) OR (persits:(pos=3) PHRASE 3 upload:(pos=4) PHRASE 3 1:(pos=5)))" }, { "if(cod>9999999)cod=parseInt(cod/64)", "(if:(pos=1) OR cod:(pos=2) OR 9999999:(pos=3) OR cod:(pos=4) OR parseint:(pos=5) OR (cod:(pos=6) PHRASE 2 64:(pos=7)))" }, { "if (cod>9999999", "(Zif:(pos=1) OR cod:(pos=2) OR 9999999:(pos=3))" }, { "\"rm -rf /bin/laden\"", "(rm:(pos=1) PHRASE 4 rf:(pos=2) PHRASE 4 bin:(pos=3) PHRASE 4 laden:(pos=4))" }, { "\">>> 0) & 0xFF\"", "(0:(pos=1) PHRASE 2 0xff:(pos=2))" }, { "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\"> document.body.scrollHeight", "(doctype:(pos=1) OR html:(pos=2) OR public:(pos=3) OR (w3c:(pos=4) PHRASE 5 dtd:(pos=5) PHRASE 5 html:(pos=6) PHRASE 5 4.01:(pos=7) PHRASE 5 en:(pos=8)) OR (document:(pos=9) PHRASE 3 body:(pos=10) PHRASE 3 scrollheight:(pos=11)))" }, { "<BR>window.resizeBy(offsetX,offsetY)<P>kweet", "(br:(pos=1) OR (window:(pos=2) PHRASE 2 resizeby:(pos=3)) OR Zoffsetx:(pos=4) OR Zoffseti:(pos=5) OR p:(pos=6) OR Zkweet:(pos=7))" }, { "linux humor :)", "(Zlinux:(pos=1) OR Zhumor:(pos=2))" }, { "ClassFactory kan aangevraagde klasse niet leveren (Fout=80040111)", "(classfactory:(pos=1) OR Zkan:(pos=2) OR Zaangevraagd:(pos=3) OR Zklass:(pos=4) OR Zniet:(pos=5) OR Zleveren:(pos=6) OR fout:(pos=7) OR 80040111:(pos=8))" }, { "remote_smtp defer (-44)", "(Zremote_smtp:(pos=1) OR Zdefer:(pos=2) OR 44:(pos=3))" }, { "txtlogin.getText().trim().toUpperCase().intern() == inuser[2 * (i - 1) + 2].trim().toUpperCase().intern() && txtpass.getText().trim().toUpperCase().intern() == inuser[2 * (i - 1) + 3].trim().toUpperCase().intern())", "((txtlogin:(pos=1) PHRASE 2 gettext:(pos=2)) OR trim:(pos=3) OR touppercase:(pos=4) OR intern:(pos=5) OR inuser:(pos=6) OR 2:(pos=7) OR Zi:(pos=8) OR 1:(pos=9) OR 2:(pos=10) OR trim:(pos=11) OR touppercase:(pos=12) OR intern:(pos=13) OR (txtpass:(pos=14) PHRASE 2 gettext:(pos=15)) OR trim:(pos=16) OR touppercase:(pos=17) OR intern:(pos=18) OR inuser:(pos=19) OR 2:(pos=20) OR Zi:(pos=21) OR 1:(pos=22) OR 3:(pos=23) OR trim:(pos=24) OR touppercase:(pos=25) OR intern:(pos=26))" }, { "Koper + amoniak (NH2", "(koper:(pos=1) OR Zamoniak:(pos=2) OR nh2:(pos=3))" }, { "nec dvd -/+r", "((Znec:(pos=1) OR Zdvd:(pos=2)) AND_NOT Zr:(pos=3))" }, // Not ideal at all - "-" shouldn't fire here... { "er is een gereserveerde fout (-1104) opgetreden", "(Zer:(pos=1) OR Zis:(pos=2) OR Zeen:(pos=3) OR Zgereserveerd:(pos=4) OR Zfout:(pos=5) OR 1104:(pos=6) OR Zopgetreden:(pos=7))" }, { "Cor \\(CCN\\)'\" <cor.kloet@ccn.controlec.nl>", "(cor:(pos=1) OR ccn:(pos=2) OR (cor:(pos=3) PHRASE 5 kloet:(pos=4) PHRASE 5 ccn:(pos=5) PHRASE 5 controlec:(pos=6) PHRASE 5 nl:(pos=7)))" }, { "Warning: Failed opening for inclusion (include_path='') in Unknown on line 0", "(warning:(pos=1) OR failed:(pos=2) OR Zopen:(pos=3) OR Zfor:(pos=4) OR Zinclus:(pos=5) OR include_path:(pos=6) OR Zin:(pos=7) OR unknown:(pos=8) OR Zon:(pos=9) OR Zline:(pos=10) OR 0:(pos=11))" }, { "\"~\" + \"c:\\\"", "Zc:(pos=1)" }, { "mysql count(*)", "(Zmysql:(pos=1) OR count:(pos=2))" }, { "for %f in (*.*) do", "(Zfor:(pos=1) OR Zf:(pos=2) OR Zin:(pos=3) OR Zdo:(pos=4))" }, { "raar \"~\" bestand", "(Zraar:(pos=1) OR Zbestand:(pos=2))" }, { "NEC DVD +-R/RW 1300", "(nec:(pos=1) OR dvd:(pos=2) OR (r:(pos=3) PHRASE 2 rw:(pos=4)) OR 1300:(pos=5))" }, { "approved (ref: 38446-263)", "(Zapprov:(pos=1) OR Zref:(pos=2) OR (38446:(pos=3) PHRASE 2 263:(pos=4)))" }, { "GA-7VRXP(2.0)", "((ga:(pos=1) PHRASE 2 7vrxp:(pos=2)) OR 2.0:(pos=3))" }, { "~ Could not retrieve directory listing for \"/\"", "(could:(pos=1) OR Znot:(pos=2) OR Zretriev:(pos=3) OR Zdirectori:(pos=4) OR Zlist:(pos=5) OR Zfor:(pos=6))" }, { "asp CreateObject(\"Word.Document\")", "(Zasp:(pos=1) OR createobject:(pos=2) OR (word:(pos=3) PHRASE 2 document:(pos=4)))" }, { "De lees- of schrijfbewerking (\"written\") op het geheugen is mislukt.", "(de:(pos=1) OR Zlee:(pos=2) OR Zof:(pos=3) OR Zschrijfbewerk:(pos=4) OR written:(pos=5) OR Zop:(pos=6) OR Zhet:(pos=7) OR Zgeheugen:(pos=8) OR Zis:(pos=9) OR Zmislukt:(pos=10))" }, { "putStr (map (\\x -> chr (round (21/2 * x^3 - 92 * x^2 + 503/2 * x - 105))) [1..4])", "(Zputstr:(pos=1) OR Zmap:(pos=2) OR ((Zx:(pos=3) OR Zround:(pos=5) OR (21:(pos=6) PHRASE 2 2:(pos=7)) OR Zx:(pos=8) OR 3:(pos=9) OR 92:(pos=10) OR Zx:(pos=11) OR 2:(pos=12) OR (503:(pos=13) PHRASE 2 2:(pos=14)) OR Zx:(pos=15) OR 105:(pos=16)) AND_NOT Zchr:(pos=4)) OR (1:(pos=17) PHRASE 2 4:(pos=18)))" }, { "parent.document.getElementById(\\\"leftmenu\\\").cols", "((parent:(pos=1) PHRASE 3 document:(pos=2) PHRASE 3 getelementbyid:(pos=3)) OR leftmenu:(pos=4) OR Zcol:(pos=5))" }, { "<% if not isEmpty(Request.QueryString) then", "(Zif:(pos=1) OR Znot:(pos=2) OR isempty:(pos=3) OR (request:(pos=4) PHRASE 2 querystring:(pos=5)) OR Zthen:(pos=6))" }, { "Active Desktop (Hier issie)", "(active:(pos=1) OR desktop:(pos=2) OR hier:(pos=3) OR Zissi:(pos=4))" }, { "Asus A7V8X (LAN + Sound)", "(asus:(pos=1) OR a7v8x:(pos=2) OR lan:(pos=3) OR sound:(pos=4))" }, { "Novell This pentium class machine (or greater) lacks some required CPU feature(s", "(novell:(pos=1) OR this:(pos=2) OR Zpentium:(pos=3) OR Zclass:(pos=4) OR Zmachin:(pos=5) OR Zor:(pos=6) OR Zgreater:(pos=7) OR Zlack:(pos=8) OR Zsome:(pos=9) OR Zrequir:(pos=10) OR cpu:(pos=11) OR feature:(pos=12) OR Zs:(pos=13))" }, { "sql server install fails error code (-1)", "(Zsql:(pos=1) OR Zserver:(pos=2) OR Zinstal:(pos=3) OR Zfail:(pos=4) OR Zerror:(pos=5) OR Zcode:(pos=6) OR 1:(pos=7))" }, { "session_register(\"login\");", "(session_register:(pos=1) OR login:(pos=2))" }, { "\"kylix+ndmb\"", "(kylix:(pos=1) PHRASE 2 ndmb:(pos=2))" }, { "Cannot find imap library (libc-client.a).", "(cannot:(pos=1) OR Zfind:(pos=2) OR Zimap:(pos=3) OR Zlibrari:(pos=4) OR (libc:(pos=5) PHRASE 3 client:(pos=6) PHRASE 3 a:(pos=7)))" }, { "If ($_SESSION[\"Login\"] == 1)", "(if:(pos=1) OR _session:(pos=2) OR login:(pos=3) OR 1:(pos=4))" }, { "You have an error in your SQL syntax near '1')' at line 1", "(you:(pos=1) OR Zhave:(pos=2) OR Zan:(pos=3) OR Zerror:(pos=4) OR Zin:(pos=5) OR Zyour:(pos=6) OR sql:(pos=7) OR Zsyntax:(pos=8) OR Znear:(pos=9) OR 1:(pos=10) OR Zat:(pos=11) OR Zline:(pos=12) OR 1:(pos=13))" }, { "ASRock K7VT2 (incl. LAN)", "(asrock:(pos=1) OR k7vt2:(pos=2) OR Zincl:(pos=3) OR lan:(pos=4))" }, { "+windows98 +(geen communicatie) +ie5", "(Zwindows98:(pos=1) AND (Zgeen:(pos=2) OR Zcommunicati:(pos=3)) AND Zie5:(pos=4))" }, { "\"xterm -fn\"", "(xterm:(pos=1) PHRASE 2 fn:(pos=2))" }, { "IRQL_NOT_LESS_OR_EQUAL", "irql_not_less_or_equal:(pos=1)" }, { "access query \"NOT IN\"", "(Zaccess:(pos=1) OR Zqueri:(pos=2) OR (not:(pos=3) PHRASE 2 in:(pos=4)))" }, { "\"phrase one \"phrase two\"", "((phrase:(pos=1) PHRASE 2 one:(pos=2)) OR Zphrase:(pos=3) OR two:(pos=4))" }, // FIXME: 2 phrases better? { "NEAR 207 46 249 27", "(near:(pos=1) OR 207:(pos=2) OR 46:(pos=3) OR 249:(pos=4) OR 27:(pos=5))" }, { "- NEAR 12V voeding", "(near:(pos=1) OR 12v:(pos=2) OR Zvoed:(pos=3))" }, { "waarom \"~\" in directorynaam", "(Zwaarom:(pos=1) OR Zin:(pos=2) OR Zdirectorynaam:(pos=3))" }, #endif static string format_doc_termlist(const Xapian::Document & doc) { string output; Xapian::TermIterator it; for (it = doc.termlist_begin(); it != doc.termlist_end(); ++it) { if (!output.empty()) output += ' '; output += *it; if (it.positionlist_count() != 0) { // If we've got a position list, only display the wdf if it's not // the length of the positionlist. if (it.get_wdf() != it.positionlist_count()) { output += ':'; output += str(it.get_wdf()); } char ch = '['; Xapian::PositionIterator posit; for (posit = it.positionlist_begin(); posit != it.positionlist_end(); posit++) { output += ch; ch = ','; output += str(*posit); } output += ']'; } else if (it.get_wdf() != 0) { // If no position list, display any non-zero wdfs. output += ':'; output += str(it.get_wdf()); } } return output; } static bool test_termgen1() { Xapian::TermGenerator termgen; Xapian::Document doc; termgen.set_document(doc); string prefix; for (const test *p = test_simple; p->text; ++p) { int weight = 1; bool new_doc = true; bool nopos = false; const char * o = p->options; while (*o != '\0') { if (*o == ',') ++o; if (strncmp(o, "cont", 4) == 0) { o += 4; new_doc = false; } else if (strncmp(o, "nopos", 5) == 0) { o += 5; nopos = true; } else if (strncmp(o, "weight=", 7) == 0) { o += 7; weight = atoi(o); while (*o >= '0' && *o <= '9') ++o; } else if (strncmp(o, "stem=", 5) == 0) { o += 5; string stemmer; while (*o != '\0' && *o != ',') { stemmer += *o; ++o; } termgen.set_stemmer(Xapian::Stem(stemmer)); tout << "Setting stemmer to: " << stemmer << '\n'; } else if (strncmp(o, "all_z", 5) == 0) { o += 5; termgen.set_stemming_strategy(termgen.STEM_ALL_Z); } else if (strncmp(o, "all", 3) == 0) { o += 3; termgen.set_stemming_strategy(termgen.STEM_ALL); } else if (strncmp(o, "none", 4) == 0) { o += 4; termgen.set_stemming_strategy(termgen.STEM_NONE); } else if (strncmp(o, "some", 4) == 0) { o += 4; termgen.set_stemming_strategy(termgen.STEM_SOME); } else if (strncmp(o, "prefix=", 7) == 0) { o += 7; prefix.resize(0); while (*o != '\0' && *o != ',') { prefix += *o; ++o; } } else { FAIL_TEST("Invalid options string: " << p->options); } } if (new_doc) { doc = Xapian::Document(); termgen.set_document(doc); } else { termgen.increase_termpos(); } string expect, output; expect = p->expect; try { if (nopos) { termgen.index_text_without_positions(p->text, weight, prefix); } else { termgen.index_text(p->text, weight, prefix); } output = format_doc_termlist(doc); } catch (const Xapian::Error &e) { output = e.get_description(); } catch (...) { output = "Unknown exception!"; } if (prefix.empty()) tout << "Text: " << p->text << '\n'; else tout << "Prefix: " << prefix << " Text: " << p->text << '\n'; TEST_STRINGS_EQUAL(output, expect); } return true; } /// Test spelling data generation. static bool test_tg_spell1() { mkdir(".flint", 0755); string dbdir = ".flint/tg_spell1"; Xapian::WritableDatabase db(dbdir, Xapian::DB_CREATE_OR_OVERWRITE); Xapian::TermGenerator termgen; Xapian::Document doc; termgen.set_document(doc); termgen.set_database(db); termgen.set_flags(Xapian::TermGenerator::FLAG_SPELLING); termgen.index_text("hello world hullo"); termgen.index_text("zebra", 1, "S"); termgen.index_text("hello mum hallo"); TEST_STRINGS_EQUAL(db.get_spelling_suggestion("hillo"), "hello"); TEST_STRINGS_EQUAL(db.get_spelling_suggestion("hillo"), "hello"); TEST_STRINGS_EQUAL(db.get_spelling_suggestion("hull"), "hullo"); TEST_STRINGS_EQUAL(db.get_spelling_suggestion("mamm"), "mum"); // Prefixed terms should be ignored for spelling currently. TEST_STRINGS_EQUAL(db.get_spelling_suggestion("zzebra"), ""); return true; } /// Regression test for bug fixed in 1.0.5 - previously this segfaulted. static bool test_tg_spell2() { Xapian::TermGenerator termgen; Xapian::Document doc; termgen.set_document(doc); termgen.set_flags(Xapian::TermGenerator::FLAG_SPELLING); TEST_EXCEPTION(Xapian::InvalidOperationError, termgen.index_text("foo")); return true; } static bool test_tg_max_word_length1() { Xapian::TermGenerator termgen; termgen.set_stemmer(Xapian::Stem("en")); termgen.set_max_word_length(4); Xapian::Document doc; termgen.set_document(doc); termgen.index_text("cups bowls mugs"); TEST_STRINGS_EQUAL(format_doc_termlist(doc), "Zcup:1 Zmug:1 cups[1] mugs[2]"); return true; } /// Test cases for the TermGenerator. static const test_desc tests[] = { TESTCASE(termgen1), TESTCASE(tg_spell1), TESTCASE(tg_spell2), TESTCASE(tg_max_word_length1), END_OF_TESTCASES }; int main(int argc, char **argv) try { // FIXME: It would be better to test with and without XAPIAN_CJK_NGRAM set. #ifdef __WIN32__ _putenv_s("XAPIAN_CJK_NGRAM", "1"); #elif defined HAVE_SETENV setenv("XAPIAN_CJK_NGRAM", "1", 1); #else putenv(const_cast<char*>("XAPIAN_CJK_NGRAM=1")); #endif test_driver::parse_command_line(argc, argv); return test_driver::run(tests); } catch (const char * e) { cout << e << endl; return 1; }
106.932322
1,726
0.618402
[ "vector", "model", "3d" ]
0687ec08dc67dc896605ba52abc19a877e68dd3f
8,768
cc
C++
alb/src/model/UpdateListenerAttributeRequest.cc
aliyun/aliyun-openapi-cpp-sdk
0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36
[ "Apache-2.0" ]
89
2018-02-02T03:54:39.000Z
2021-12-13T01:32:55.000Z
alb/src/model/UpdateListenerAttributeRequest.cc
aliyun/aliyun-openapi-cpp-sdk
0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36
[ "Apache-2.0" ]
89
2018-03-14T07:44:54.000Z
2021-11-26T07:43:25.000Z
alb/src/model/UpdateListenerAttributeRequest.cc
aliyun/aliyun-openapi-cpp-sdk
0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36
[ "Apache-2.0" ]
69
2018-01-22T09:45:52.000Z
2022-03-28T07:58:38.000Z
/* * Copyright 2009-2017 Alibaba Cloud All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <alibabacloud/alb/model/UpdateListenerAttributeRequest.h> using AlibabaCloud::Alb::Model::UpdateListenerAttributeRequest; UpdateListenerAttributeRequest::UpdateListenerAttributeRequest() : RpcServiceRequest("alb", "2020-06-16", "UpdateListenerAttribute") { setMethod(HttpRequest::Method::Post); } UpdateListenerAttributeRequest::~UpdateListenerAttributeRequest() {} std::string UpdateListenerAttributeRequest::getClientToken() const { return clientToken_; } void UpdateListenerAttributeRequest::setClientToken(const std::string &clientToken) { clientToken_ = clientToken; setParameter(std::string("ClientToken"), clientToken); } bool UpdateListenerAttributeRequest::getGzipEnabled() const { return gzipEnabled_; } void UpdateListenerAttributeRequest::setGzipEnabled(bool gzipEnabled) { gzipEnabled_ = gzipEnabled; setParameter(std::string("GzipEnabled"), gzipEnabled ? "true" : "false"); } std::string UpdateListenerAttributeRequest::getListenerId() const { return listenerId_; } void UpdateListenerAttributeRequest::setListenerId(const std::string &listenerId) { listenerId_ = listenerId; setParameter(std::string("ListenerId"), listenerId); } UpdateListenerAttributeRequest::QuicConfig UpdateListenerAttributeRequest::getQuicConfig() const { return quicConfig_; } void UpdateListenerAttributeRequest::setQuicConfig(const UpdateListenerAttributeRequest::QuicConfig &quicConfig) { quicConfig_ = quicConfig; setParameter(std::string("QuicConfig") + ".QuicUpgradeEnabled", quicConfig.quicUpgradeEnabled ? "true" : "false"); setParameter(std::string("QuicConfig") + ".QuicListenerId", quicConfig.quicListenerId); } bool UpdateListenerAttributeRequest::getHttp2Enabled() const { return http2Enabled_; } void UpdateListenerAttributeRequest::setHttp2Enabled(bool http2Enabled) { http2Enabled_ = http2Enabled; setParameter(std::string("Http2Enabled"), http2Enabled ? "true" : "false"); } std::vector<UpdateListenerAttributeRequest::DefaultActions> UpdateListenerAttributeRequest::getDefaultActions() const { return defaultActions_; } void UpdateListenerAttributeRequest::setDefaultActions(const std::vector<UpdateListenerAttributeRequest::DefaultActions> &defaultActions) { defaultActions_ = defaultActions; for(int dep1 = 0; dep1 != defaultActions.size(); dep1++) { for(int dep2 = 0; dep2 != defaultActions[dep1].forwardGroupConfig.serverGroupTuples.size(); dep2++) { setParameter(std::string("DefaultActions") + "." + std::to_string(dep1 + 1) + ".ForwardGroupConfig.ServerGroupTuples." + std::to_string(dep2 + 1) + ".ServerGroupId", defaultActions[dep1].forwardGroupConfig.serverGroupTuples[dep2].serverGroupId); } setParameter(std::string("DefaultActions") + "." + std::to_string(dep1 + 1) + ".Type", defaultActions[dep1].type); } } bool UpdateListenerAttributeRequest::getDryRun() const { return dryRun_; } void UpdateListenerAttributeRequest::setDryRun(bool dryRun) { dryRun_ = dryRun; setParameter(std::string("DryRun"), dryRun ? "true" : "false"); } int UpdateListenerAttributeRequest::getRequestTimeout() const { return requestTimeout_; } void UpdateListenerAttributeRequest::setRequestTimeout(int requestTimeout) { requestTimeout_ = requestTimeout; setParameter(std::string("RequestTimeout"), std::to_string(requestTimeout)); } std::vector<UpdateListenerAttributeRequest::CaCertificates> UpdateListenerAttributeRequest::getCaCertificates() const { return caCertificates_; } void UpdateListenerAttributeRequest::setCaCertificates(const std::vector<UpdateListenerAttributeRequest::CaCertificates> &caCertificates) { caCertificates_ = caCertificates; for(int dep1 = 0; dep1 != caCertificates.size(); dep1++) { setParameter(std::string("CaCertificates") + "." + std::to_string(dep1 + 1) + ".CertificateId", caCertificates[dep1].certificateId); } } UpdateListenerAttributeRequest::XForwardedForConfig UpdateListenerAttributeRequest::getXForwardedForConfig() const { return xForwardedForConfig_; } void UpdateListenerAttributeRequest::setXForwardedForConfig(const UpdateListenerAttributeRequest::XForwardedForConfig &xForwardedForConfig) { xForwardedForConfig_ = xForwardedForConfig; setParameter(std::string("XForwardedForConfig") + ".XForwardedForClientCertSubjectDNAlias", xForwardedForConfig.xForwardedForClientCertSubjectDNAlias); setParameter(std::string("XForwardedForConfig") + ".XForwardedForClientCertIssuerDNEnabled", xForwardedForConfig.xForwardedForClientCertIssuerDNEnabled ? "true" : "false"); setParameter(std::string("XForwardedForConfig") + ".XForwardedForClientCertFingerprintEnabled", xForwardedForConfig.xForwardedForClientCertFingerprintEnabled ? "true" : "false"); setParameter(std::string("XForwardedForConfig") + ".XForwardedForClientCertIssuerDNAlias", xForwardedForConfig.xForwardedForClientCertIssuerDNAlias); setParameter(std::string("XForwardedForConfig") + ".XForwardedForProtoEnabled", xForwardedForConfig.xForwardedForProtoEnabled ? "true" : "false"); setParameter(std::string("XForwardedForConfig") + ".XForwardedForClientCertFingerprintAlias", xForwardedForConfig.xForwardedForClientCertFingerprintAlias); setParameter(std::string("XForwardedForConfig") + ".XForwardedForClientCertClientVerifyEnabled", xForwardedForConfig.xForwardedForClientCertClientVerifyEnabled ? "true" : "false"); setParameter(std::string("XForwardedForConfig") + ".XForwardedForSLBPortEnabled", xForwardedForConfig.xForwardedForSLBPortEnabled ? "true" : "false"); setParameter(std::string("XForwardedForConfig") + ".XForwardedForClientCertSubjectDNEnabled", xForwardedForConfig.xForwardedForClientCertSubjectDNEnabled ? "true" : "false"); setParameter(std::string("XForwardedForConfig") + ".XForwardedForClientCertClientVerifyAlias", xForwardedForConfig.xForwardedForClientCertClientVerifyAlias); setParameter(std::string("XForwardedForConfig") + ".XForwardedForClientSrcPortEnabled", xForwardedForConfig.xForwardedForClientSrcPortEnabled ? "true" : "false"); setParameter(std::string("XForwardedForConfig") + ".XForwardedForEnabled", xForwardedForConfig.xForwardedForEnabled ? "true" : "false"); setParameter(std::string("XForwardedForConfig") + ".XForwardedForSLBIdEnabled", xForwardedForConfig.xForwardedForSLBIdEnabled ? "true" : "false"); } std::string UpdateListenerAttributeRequest::getSecurityPolicyId() const { return securityPolicyId_; } void UpdateListenerAttributeRequest::setSecurityPolicyId(const std::string &securityPolicyId) { securityPolicyId_ = securityPolicyId; setParameter(std::string("SecurityPolicyId"), securityPolicyId); } int UpdateListenerAttributeRequest::getIdleTimeout() const { return idleTimeout_; } void UpdateListenerAttributeRequest::setIdleTimeout(int idleTimeout) { idleTimeout_ = idleTimeout; setParameter(std::string("IdleTimeout"), std::to_string(idleTimeout)); } std::vector<UpdateListenerAttributeRequest::Certificates> UpdateListenerAttributeRequest::getCertificates() const { return certificates_; } void UpdateListenerAttributeRequest::setCertificates(const std::vector<UpdateListenerAttributeRequest::Certificates> &certificates) { certificates_ = certificates; for(int dep1 = 0; dep1 != certificates.size(); dep1++) { setParameter(std::string("Certificates") + "." + std::to_string(dep1 + 1) + ".CertificateId", certificates[dep1].certificateId); } } std::string UpdateListenerAttributeRequest::getListenerDescription() const { return listenerDescription_; } void UpdateListenerAttributeRequest::setListenerDescription(const std::string &listenerDescription) { listenerDescription_ = listenerDescription; setParameter(std::string("ListenerDescription"), listenerDescription); } bool UpdateListenerAttributeRequest::getCaEnabled() const { return caEnabled_; } void UpdateListenerAttributeRequest::setCaEnabled(bool caEnabled) { caEnabled_ = caEnabled; setParameter(std::string("CaEnabled"), caEnabled ? "true" : "false"); }
47.394595
252
0.779539
[ "vector", "model" ]
06972df6bf17e830ac725983d8d1217d8ca3a3a7
29,823
cpp
C++
lib/game_save_gbaimpl.cpp
ncorgan/libpkmn
c683bf8b85b03eef74a132b5cfdce9be0969d523
[ "MIT" ]
4
2017-06-10T13:21:44.000Z
2019-10-30T21:20:19.000Z
lib/game_save_gbaimpl.cpp
PMArkive/libpkmn
c683bf8b85b03eef74a132b5cfdce9be0969d523
[ "MIT" ]
12
2017-04-05T11:13:34.000Z
2018-06-03T14:31:03.000Z
lib/game_save_gbaimpl.cpp
PMArkive/libpkmn
c683bf8b85b03eef74a132b5cfdce9be0969d523
[ "MIT" ]
2
2019-01-22T21:02:31.000Z
2019-10-30T21:20:20.000Z
/* * Copyright (c) 2016-2018 Nicholas Corgan (n.corgan@gmail.com) * * Distributed under the MIT License (MIT) (See accompanying file LICENSE.txt * or copy at http://opensource.org/licenses/MIT) */ #include "exception_internal.hpp" #include "game_save_gbaimpl.hpp" #include "item_bag_gbaimpl.hpp" #include "item_list_modernimpl.hpp" #include "pokedex_gbaimpl.hpp" #include "pokemon_party_gbaimpl.hpp" #include "pokemon_pc_gbaimpl.hpp" #include "pksav/enum_maps.hpp" #include "pksav/pksav_call.hpp" #include <pkmn/exception.hpp> #include <boost/algorithm/string.hpp> #include <boost/filesystem.hpp> #include <boost/thread/lock_guard.hpp> #include <cstring> #include <stdexcept> namespace fs = boost::filesystem; namespace pkmn { BOOST_STATIC_CONSTEXPR int RUBY_GAME_ID = 7; BOOST_STATIC_CONSTEXPR int SAPPHIRE_GAME_ID = 8; BOOST_STATIC_CONSTEXPR int EMERALD_GAME_ID = 9; BOOST_STATIC_CONSTEXPR int FIRERED_GAME_ID = 10; BOOST_STATIC_CONSTEXPR int LEAFGREEN_GAME_ID = 11; BOOST_STATIC_CONSTEXPR int RS_PC_ID = 20; BOOST_STATIC_CONSTEXPR int EMERALD_PC_ID = 26; BOOST_STATIC_CONSTEXPR int FRLG_PC_ID = 32; game_save_gbaimpl::game_save_gbaimpl( const std::string& filepath, std::vector<uint8_t>&& raw ): game_save_impl(filepath, std::move(raw)) { PKSAV_CALL( pksav_gba_load_save_from_buffer( _raw.data(), _raw.size(), &_pksav_save ); ) int item_pc_id = 0; std::string filename = boost::algorithm::to_lower_copy( fs::path(filepath).stem().string() ); boost::erase_all(filename, " "); switch(_pksav_save.save_type) { case PKSAV_GBA_SAVE_TYPE_RS: /* * As there is no way to distinguish Ruby and Sapphire saves from the saves * themselves, we'll try to depend on the fact that .sav files match * the name of their game's ROM, which are usually the game titles, so * we'll check for the version in the filename. */ if(filename.find("ruby") != std::string::npos) { _game_id = RUBY_GAME_ID; } else if(filename.find("sapphire") != std::string::npos) { _game_id = SAPPHIRE_GAME_ID; } else { // Default to Ruby, doesn't practically matter within a version group _game_id = RUBY_GAME_ID; } item_pc_id = RS_PC_ID; break; case PKSAV_GBA_SAVE_TYPE_FRLG: /* * As there is no way to distinguish FireRed and LeafGreen saves from the saves * themselves, we'll try to depend on the fact that .sav files match * the name of their game's ROM, which are usually the game titles, so * we'll check for the version in the filename. */ if(filename.find("firered") != std::string::npos or filename.find("fr") != std::string::npos ) { _game_id = FIRERED_GAME_ID; } else if(filename.find("leafgreen") != std::string::npos or filename.find("lg") != std::string::npos) { _game_id = LEAFGREEN_GAME_ID; } else { // Default to FireRed, doesn't practically matter within a version group _game_id = FIRERED_GAME_ID; } item_pc_id = FRLG_PC_ID; break; default: // Emerald _game_id = EMERALD_GAME_ID; item_pc_id = EMERALD_PC_ID; break; } BOOST_ASSERT(_pksav_save.pokedex.p_seenA != nullptr); BOOST_ASSERT(_pksav_save.pokedex.p_seenB != nullptr); BOOST_ASSERT(_pksav_save.pokedex.p_seenC != nullptr); BOOST_ASSERT(_pksav_save.pokedex.p_owned != nullptr); BOOST_ASSERT(_pksav_save.pokedex.p_nat_pokedex_unlockedB != nullptr); BOOST_ASSERT(_pksav_save.pokedex.p_nat_pokedex_unlockedC != nullptr); if(_pksav_save.save_type == PKSAV_GBA_SAVE_TYPE_FRLG) { BOOST_ASSERT(_pksav_save.pokedex.p_frlg_nat_pokedex_unlockedA != nullptr); } else { BOOST_ASSERT(_pksav_save.pokedex.p_rse_nat_pokedex_unlockedA != nullptr); } _pokedex = std::make_shared<pokedex_gbaimpl>( _game_id, &_pksav_save.pokedex ); BOOST_ASSERT(_pksav_save.pokemon_storage.p_party != nullptr); _pokemon_party = std::make_shared<pokemon_party_gbaimpl>( _game_id, _pksav_save.pokemon_storage.p_party ); BOOST_ASSERT(_pksav_save.pokemon_storage.p_pc != nullptr); _pokemon_pc = std::make_shared<pokemon_pc_gbaimpl>( _game_id, _pksav_save.pokemon_storage.p_pc ); BOOST_ASSERT(_pksav_save.item_storage.p_bag != nullptr); _item_bag = std::make_shared<item_bag_gbaimpl>( _game_id, _pksav_save.item_storage.p_bag ); BOOST_ASSERT(_pksav_save.item_storage.p_pc != nullptr); _item_pc = std::make_shared<item_list_modernimpl>( item_pc_id, _game_id, _pksav_save.item_storage.p_pc->items ); // When a Pokémon is added to the PC or party, it should be // reflected in the Pokédex. pokemon_party_impl* p_party_impl = dynamic_cast<pokemon_party_impl*>(_pokemon_party.get()); pokemon_pc_impl* p_pc_impl = dynamic_cast<pokemon_pc_impl*>(_pokemon_pc.get()); BOOST_ASSERT(p_party_impl != nullptr); BOOST_ASSERT(p_pc_impl != nullptr); p_party_impl->set_pokedex(_pokedex); p_pc_impl->set_pokedex(_pokedex); _register_attributes(); } game_save_gbaimpl::~game_save_gbaimpl() { pksav_gba_free_save(&_pksav_save); } void game_save_gbaimpl::save_as( const std::string& filepath ) { boost::lock_guard<game_save_gbaimpl> lock(*this); // These get_native() calls will call the mutex for every subclass // it copies, so we don't need to worry about that here. pkmn::rcast_equal<union pksav_gba_item_bag>( _item_bag->get_native(), _pksav_save.item_storage.p_bag ); pkmn::rcast_equal<struct pksav_gba_item_pc>( _item_pc->get_native(), _pksav_save.item_storage.p_pc ); pkmn::rcast_equal<struct pksav_gba_pokemon_party>( _pokemon_party->get_native(), _pksav_save.pokemon_storage.p_party ); pkmn::rcast_equal<struct pksav_gba_pokemon_pc>( _pokemon_pc->get_native(), _pksav_save.pokemon_storage.p_pc ); // TODO: put this in PKSav header static const size_t num_pokedex_bytes = ((386 / 8) + 1); struct pksav_gba_pokedex* p_pokedex_copy = static_cast<struct pksav_gba_pokedex*>( _pokedex->get_native() ); std::memcpy( _pksav_save.pokedex.p_seenA, p_pokedex_copy->p_seenA, num_pokedex_bytes ); std::memcpy( _pksav_save.pokedex.p_seenB, p_pokedex_copy->p_seenB, num_pokedex_bytes ); std::memcpy( _pksav_save.pokedex.p_seenB, p_pokedex_copy->p_seenB, num_pokedex_bytes ); std::memcpy( _pksav_save.pokedex.p_owned, p_pokedex_copy->p_owned, num_pokedex_bytes ); PKSAV_CALL( pksav_gba_save_save( filepath.c_str(), &_pksav_save ); ) _filepath = fs::absolute(filepath).string(); } pkmn::time_duration game_save_gbaimpl::get_time_played() { boost::lock_guard<game_save_gbaimpl> lock(*this); BOOST_ASSERT(_pksav_save.p_time_played != nullptr); return pkmn::time_duration( pksav_littleendian16(_pksav_save.p_time_played->hours), _pksav_save.p_time_played->minutes, _pksav_save.p_time_played->seconds, _pksav_save.p_time_played->frames ); } void game_save_gbaimpl::set_time_played( const pkmn::time_duration& time_played ) { pkmn::enforce_bounds( "Hours played", time_played.hours, 0, 65535 ); pkmn::enforce_bounds( "Minutes played", time_played.minutes, 0, 59 ); pkmn::enforce_bounds( "Seconds played", time_played.seconds, 0, 59 ); pkmn::enforce_bounds( "Frames played", time_played.frames, 0, 59 ); boost::lock_guard<game_save_gbaimpl> lock(*this); BOOST_ASSERT(_pksav_save.p_time_played != nullptr); _pksav_save.p_time_played->hours = pksav_littleendian16( static_cast<uint16_t>(time_played.hours) ); _pksav_save.p_time_played->minutes = static_cast<uint8_t>(time_played.minutes); _pksav_save.p_time_played->seconds = static_cast<uint8_t>(time_played.seconds); _pksav_save.p_time_played->frames = static_cast<uint8_t>(time_played.frames); } std::string game_save_gbaimpl::get_trainer_name() { boost::lock_guard<game_save_gbaimpl> lock(*this); BOOST_ASSERT(_pksav_save.trainer_info.p_name != nullptr); char trainer_name[PKSAV_GBA_TRAINER_NAME_LENGTH + 1] = {0}; PKSAV_CALL( pksav_gba_import_text( _pksav_save.trainer_info.p_name, trainer_name, PKSAV_GBA_TRAINER_NAME_LENGTH ); ) return std::string(trainer_name); } void game_save_gbaimpl::set_trainer_name( const std::string& trainer_name ) { pkmn::enforce_string_length( "Trainer name", trainer_name, 1, PKSAV_GBA_TRAINER_NAME_LENGTH ); boost::lock_guard<game_save_gbaimpl> lock(*this); BOOST_ASSERT(_pksav_save.trainer_info.p_name != nullptr); PKSAV_CALL( pksav_gba_export_text( trainer_name.c_str(), _pksav_save.trainer_info.p_name, PKSAV_GBA_TRAINER_NAME_LENGTH ); ) } uint32_t game_save_gbaimpl::get_trainer_id() { boost::lock_guard<game_save_gbaimpl> lock(*this); BOOST_ASSERT(_pksav_save.trainer_info.p_id != nullptr); return pksav_littleendian32(_pksav_save.trainer_info.p_id->id); } void game_save_gbaimpl::set_trainer_id( uint32_t trainer_id ) { boost::lock_guard<game_save_gbaimpl> lock(*this); BOOST_ASSERT(_pksav_save.trainer_info.p_id != nullptr); _pksav_save.trainer_info.p_id->id = pksav_littleendian32(trainer_id); } uint16_t game_save_gbaimpl::get_trainer_public_id() { boost::lock_guard<game_save_gbaimpl> lock(*this); BOOST_ASSERT(_pksav_save.trainer_info.p_id != nullptr); return pksav_littleendian16(_pksav_save.trainer_info.p_id->pid); } void game_save_gbaimpl::set_trainer_public_id( uint16_t trainer_public_id ) { boost::lock_guard<game_save_gbaimpl> lock(*this); BOOST_ASSERT(_pksav_save.trainer_info.p_id != nullptr); _pksav_save.trainer_info.p_id->pid = pksav_littleendian16(trainer_public_id); } uint16_t game_save_gbaimpl::get_trainer_secret_id() { boost::lock_guard<game_save_gbaimpl> lock(*this); BOOST_ASSERT(_pksav_save.trainer_info.p_id != nullptr); return pksav_littleendian16(_pksav_save.trainer_info.p_id->sid); } void game_save_gbaimpl::set_trainer_secret_id( uint16_t trainer_secret_id ) { boost::lock_guard<game_save_gbaimpl> lock(*this); BOOST_ASSERT(_pksav_save.trainer_info.p_id != nullptr); _pksav_save.trainer_info.p_id->sid = pksav_littleendian16(trainer_secret_id); } // TODO: PKSav gender enum pkmn::e_gender game_save_gbaimpl::get_trainer_gender() { boost::lock_guard<game_save_gbaimpl> lock(*this); BOOST_ASSERT(_pksav_save.trainer_info.p_gender != nullptr); return (*_pksav_save.trainer_info.p_gender == 0) ? pkmn::e_gender::MALE : pkmn::e_gender::FEMALE; } // TODO: PKSav gender enum, use bimap void game_save_gbaimpl::set_trainer_gender( pkmn::e_gender trainer_gender ) { boost::lock_guard<game_save_gbaimpl> lock(*this); pkmn::enforce_value_in_vector( "Trainer gender", trainer_gender, {pkmn::e_gender::MALE, pkmn::e_gender::FEMALE} ); BOOST_ASSERT(_pksav_save.trainer_info.p_gender != nullptr); if(trainer_gender == pkmn::e_gender::MALE) { *_pksav_save.trainer_info.p_gender = 0; } else { *_pksav_save.trainer_info.p_gender = 1; } } std::string game_save_gbaimpl::get_rival_name() { boost::lock_guard<game_save_gbaimpl> lock(*this); std::string ret; if(_pksav_save.save_type == PKSAV_GBA_SAVE_TYPE_FRLG) { BOOST_ASSERT(_pksav_save.misc_fields.p_rival_name != nullptr); char rival_name[PKSAV_GBA_TRAINER_NAME_LENGTH + 1] = {0}; PKSAV_CALL( pksav_gba_import_text( _pksav_save.misc_fields.p_rival_name, rival_name, PKSAV_GBA_TRAINER_NAME_LENGTH ); ) ret = std::string(rival_name); } else { BOOST_ASSERT(_pksav_save.trainer_info.p_gender != nullptr); ret = (*_pksav_save.trainer_info.p_gender == 0) ? "MAY" : "BRENDAN"; } return ret; } void game_save_gbaimpl::set_rival_name( const std::string& rival_name ) { if(_pksav_save.save_type == PKSAV_GBA_SAVE_TYPE_FRLG) { pkmn::enforce_string_length( "Rival name", rival_name, 1, PKSAV_GBA_TRAINER_NAME_LENGTH ); boost::lock_guard<game_save_gbaimpl> lock(*this); BOOST_ASSERT(_pksav_save.misc_fields.p_rival_name != nullptr); PKSAV_CALL( pksav_gba_export_text( rival_name.c_str(), _pksav_save.misc_fields.p_rival_name, PKSAV_GBA_TRAINER_NAME_LENGTH ); ) } else { throw pkmn::feature_not_in_game_error("Rivals cannot be renamed in Ruby/Sapphire/Emerald."); } } int game_save_gbaimpl::get_money() { boost::lock_guard<game_save_gbaimpl> lock(*this); BOOST_ASSERT(_pksav_save.trainer_info.p_money != nullptr); return int(pksav_littleendian32(*_pksav_save.trainer_info.p_money)); } void game_save_gbaimpl::set_money( int money ) { pkmn::enforce_bounds("Money", money, 0, MONEY_MAX_VALUE); boost::lock_guard<game_save_gbaimpl> lock(*this); BOOST_ASSERT(_pksav_save.trainer_info.p_money != nullptr); *_pksav_save.trainer_info.p_money = pksav_littleendian32(uint32_t(money)); } // Functions for attributes int game_save_gbaimpl::get_casino_coins() { boost::lock_guard<game_save_gbaimpl> lock(*this); BOOST_ASSERT(_pksav_save.misc_fields.p_casino_coins != nullptr); return pksav_littleendian16(*_pksav_save.misc_fields.p_casino_coins); } void game_save_gbaimpl::set_casino_coins( int casino_coins ) { pkmn::enforce_bounds( "Casino coins", casino_coins, 0, 9999 ); boost::lock_guard<game_save_gbaimpl> lock(*this); BOOST_ASSERT(_pksav_save.misc_fields.p_casino_coins != nullptr); *_pksav_save.misc_fields.p_casino_coins = pksav_littleendian16(uint16_t(casino_coins)); } bool game_save_gbaimpl::get_is_national_dex_unlocked() { boost::lock_guard<game_save_gbaimpl> lock(*this); BOOST_ASSERT(_pksav_save.pokedex.p_nat_pokedex_unlockedB != nullptr); // Easiest since it's the same for all types return bool(*_pksav_save.pokedex.p_nat_pokedex_unlockedB & PKSAV_GBA_NAT_POKEDEX_UNLOCKED_B_FLAG); } void game_save_gbaimpl::set_is_national_dex_unlocked( bool is_national_dex_unlocked ) { boost::lock_guard<game_save_gbaimpl> lock(*this); if(_pksav_save.save_type == PKSAV_GBA_SAVE_TYPE_FRLG) { BOOST_ASSERT(_pksav_save.pokedex.p_frlg_nat_pokedex_unlockedA != nullptr); } else { BOOST_ASSERT(_pksav_save.pokedex.p_rse_nat_pokedex_unlockedA != nullptr); } BOOST_ASSERT(_pksav_save.pokedex.p_nat_pokedex_unlockedB != nullptr); BOOST_ASSERT(_pksav_save.pokedex.p_nat_pokedex_unlockedC != nullptr); PKSAV_CALL( pksav_gba_pokedex_set_national_pokedex_unlocked( &_pksav_save.pokedex, _pksav_save.save_type, is_national_dex_unlocked ); ) } std::string game_save_gbaimpl::get_button_mode() { BOOST_ASSERT(_pksav_save.options.p_button_mode != nullptr); boost::lock_guard<game_save_gbaimpl> lock(*this); std::string button_mode; if(_pksav_save.save_type == PKSAV_GBA_SAVE_TYPE_FRLG) { // Sensible default in case of save corruption button_mode = "Help"; const pksav::gba_frlg_button_mode_bimap_t& gba_frlg_button_mode_bimap = pksav::get_gba_frlg_button_mode_bimap(); auto gba_frlg_button_mode_iter = gba_frlg_button_mode_bimap.right.find( (enum pksav_gba_frlg_button_mode)( *_pksav_save.options.p_button_mode ) ); if(gba_frlg_button_mode_iter != gba_frlg_button_mode_bimap.right.end()) { button_mode = gba_frlg_button_mode_iter->second; } } else { // Sensible default in case of save corruption button_mode = "Normal"; const pksav::gba_rse_button_mode_bimap_t& gba_rse_button_mode_bimap = pksav::get_gba_rse_button_mode_bimap(); auto gba_rse_button_mode_iter = gba_rse_button_mode_bimap.right.find( (enum pksav_gba_rse_button_mode)( *_pksav_save.options.p_button_mode ) ); if(gba_rse_button_mode_iter != gba_rse_button_mode_bimap.right.end()) { button_mode = gba_rse_button_mode_iter->second; } } return button_mode; } void game_save_gbaimpl::set_button_mode(const std::string& button_mode) { BOOST_ASSERT(_pksav_save.options.p_button_mode != nullptr); if(_pksav_save.save_type == PKSAV_GBA_SAVE_TYPE_FRLG) { const pksav::gba_frlg_button_mode_bimap_t& gba_frlg_button_mode_bimap = pksav::get_gba_frlg_button_mode_bimap(); pkmn::enforce_value_in_map_keys( "Button mode", button_mode, gba_frlg_button_mode_bimap.left ); boost::lock_guard<game_save_gbaimpl> lock(*this); *_pksav_save.options.p_button_mode = static_cast<uint8_t>(gba_frlg_button_mode_bimap.left.at( button_mode )); } else { const pksav::gba_rse_button_mode_bimap_t& gba_rse_button_mode_bimap = pksav::get_gba_rse_button_mode_bimap(); pkmn::enforce_value_in_map_keys( "Button mode", button_mode, gba_rse_button_mode_bimap.left ); boost::lock_guard<game_save_gbaimpl> lock(*this); *_pksav_save.options.p_button_mode = static_cast<uint8_t>(gba_rse_button_mode_bimap.left.at( button_mode )); } } std::string game_save_gbaimpl::get_text_speed() { BOOST_ASSERT(_pksav_save.options.p_text_options != nullptr); boost::lock_guard<game_save_gbaimpl> lock(*this); // Sensible default in case of corrupted save std::string text_speed = "Medium"; uint8_t raw_text_speed = (*_pksav_save.options.p_text_options & PKSAV_GBA_OPTIONS_TEXT_SPEED_MASK); const pksav::gba_text_speed_bimap_t& gba_text_speed_bimap = pksav::get_gba_text_speed_bimap(); auto gba_text_speed_iter = gba_text_speed_bimap.right.find( static_cast<enum pksav_gba_text_speed>( raw_text_speed ) ); if(gba_text_speed_iter != gba_text_speed_bimap.right.end()) { text_speed = gba_text_speed_iter->second; } return text_speed; } void game_save_gbaimpl::set_text_speed(const std::string& text_speed) { BOOST_ASSERT(_pksav_save.options.p_text_options != nullptr); const pksav::gba_text_speed_bimap_t& gba_text_speed_bimap = pksav::get_gba_text_speed_bimap(); pkmn::enforce_value_in_map_keys( "Text speed", text_speed, gba_text_speed_bimap.left ); boost::lock_guard<game_save_gbaimpl> lock(*this); *_pksav_save.options.p_text_options &= ~PKSAV_GBA_OPTIONS_TEXT_SPEED_MASK; *_pksav_save.options.p_text_options |= static_cast<uint8_t>( gba_text_speed_bimap.left.at( text_speed ) ); } int game_save_gbaimpl::get_textbox_frame_index() { BOOST_ASSERT(_pksav_save.options.p_text_options != nullptr); boost::lock_guard<game_save_gbaimpl> lock(*this); return static_cast<int>( PKSAV_GBA_OPTIONS_TEXTBOX_FRAME(*_pksav_save.options.p_text_options) ) + 1; } void game_save_gbaimpl::set_textbox_frame_index(int textbox_frame_index) { BOOST_ASSERT(_pksav_save.options.p_text_options != nullptr); pkmn::enforce_bounds( "Textbox frame", textbox_frame_index, static_cast<int>(PKSAV_GBA_OPTIONS_TEXTBOX_MIN_FRAME + 1), static_cast<int>(PKSAV_GBA_OPTIONS_TEXTBOX_MAX_FRAME + 1) ); boost::lock_guard<game_save_gbaimpl> lock(*this); // The value is stored 0-based. uint8_t raw_textbox_frame_index = static_cast<uint8_t>(textbox_frame_index) - 1; raw_textbox_frame_index <<= PKSAV_GBA_OPTIONS_TEXTBOX_FRAME_OFFSET; *_pksav_save.options.p_text_options &= ~PKSAV_GBA_OPTIONS_TEXTBOX_FRAME_MASK; *_pksav_save.options.p_text_options |= raw_textbox_frame_index; } std::string game_save_gbaimpl::get_sound_output() { BOOST_ASSERT(_pksav_save.options.p_sound_battle_options != nullptr); boost::lock_guard<game_save_gbaimpl> lock(*this); // Sensible default in the case of a corrupted save std::string sound_output = "Mono"; bool is_stereo = bool(*_pksav_save.options.p_sound_battle_options & PKSAV_GBA_OPTIONS_SOUND_STEREO_MASK); sound_output = is_stereo ? "Stereo" : "Mono"; return sound_output; } void game_save_gbaimpl::set_sound_output( const std::string& sound_output ) { BOOST_ASSERT(_pksav_save.options.p_sound_battle_options != nullptr); pkmn::enforce_value_in_vector( "Sound output", sound_output, {"Stereo", "Mono"} ); boost::lock_guard<game_save_gbaimpl> lock(*this); if(sound_output == "Stereo") { *_pksav_save.options.p_sound_battle_options |= PKSAV_GBA_OPTIONS_SOUND_STEREO_MASK; } else { *_pksav_save.options.p_sound_battle_options &= ~PKSAV_GBA_OPTIONS_SOUND_STEREO_MASK; } } std::string game_save_gbaimpl::get_battle_style() { BOOST_ASSERT(_pksav_save.options.p_sound_battle_options != nullptr); bool is_battle_style_set = (*_pksav_save.options.p_sound_battle_options & PKSAV_GBA_OPTIONS_BATTLE_STYLE_SET_MASK); return is_battle_style_set ? "Set" : "Shift"; } void game_save_gbaimpl::set_battle_style( const std::string& battle_style ) { BOOST_ASSERT(_pksav_save.options.p_sound_battle_options != nullptr); pkmn::enforce_value_in_vector( "Battle style", battle_style, {"Set", "Shift"} ); if(battle_style == "Set") { *_pksav_save.options.p_sound_battle_options |= PKSAV_GBA_OPTIONS_BATTLE_STYLE_SET_MASK; } else { *_pksav_save.options.p_sound_battle_options &= ~PKSAV_GBA_OPTIONS_BATTLE_STYLE_SET_MASK; } } bool game_save_gbaimpl::get_is_battle_scene_enabled() { BOOST_ASSERT(_pksav_save.options.p_sound_battle_options != nullptr); // The save stored whether the effects are disabled, so reverse // the result. return !(*_pksav_save.options.p_sound_battle_options & PKSAV_GBA_OPTIONS_BATTLE_SCENE_DISABLE_MASK); } void game_save_gbaimpl::set_is_battle_scene_enabled( bool is_battle_scene_enabled ) { BOOST_ASSERT(_pksav_save.options.p_sound_battle_options != nullptr); // The save stored whether the effects are disabled, so reverse // the input. if(is_battle_scene_enabled) { *_pksav_save.options.p_sound_battle_options &= ~PKSAV_GBA_OPTIONS_BATTLE_SCENE_DISABLE_MASK; } else { *_pksav_save.options.p_sound_battle_options |= PKSAV_GBA_OPTIONS_BATTLE_SCENE_DISABLE_MASK; } } void game_save_gbaimpl::_register_attributes() { using std::placeholders::_1; _numeric_attribute_engine.register_attribute_fcns( "Casino coins", std::bind(&game_save_gbaimpl::get_casino_coins, this), std::bind(&game_save_gbaimpl::set_casino_coins, this, _1) ); _numeric_attribute_engine.register_attribute_fcns( "Textbox frame", std::bind(&game_save_gbaimpl::get_textbox_frame_index, this), std::bind(&game_save_gbaimpl::set_textbox_frame_index, this, _1) ); _string_attribute_engine.register_attribute_fcns( "Button mode", std::bind(&game_save_gbaimpl::get_button_mode, this), std::bind(&game_save_gbaimpl::set_button_mode, this, _1) ); _string_attribute_engine.register_attribute_fcns( "Text speed", std::bind(&game_save_gbaimpl::get_text_speed, this), std::bind(&game_save_gbaimpl::set_text_speed, this, _1) ); _string_attribute_engine.register_attribute_fcns( "Sound output", std::bind(&game_save_gbaimpl::get_sound_output, this), std::bind(&game_save_gbaimpl::set_sound_output, this, _1) ); _string_attribute_engine.register_attribute_fcns( "Battle style", std::bind(&game_save_gbaimpl::get_battle_style, this), std::bind(&game_save_gbaimpl::set_battle_style, this, _1) ); // Don't use the whole word "Pokédex" to make life easier for // Python users. _boolean_attribute_engine.register_attribute_fcns( "National Dex unlocked?", std::bind(&game_save_gbaimpl::get_is_national_dex_unlocked, this), std::bind(&game_save_gbaimpl::set_is_national_dex_unlocked, this, _1) ); _boolean_attribute_engine.register_attribute_fcns( "Enable battle scene?", std::bind(&game_save_gbaimpl::get_is_battle_scene_enabled, this), std::bind(&game_save_gbaimpl::set_is_battle_scene_enabled, this, _1) ); } }
32.772527
108
0.592529
[ "vector" ]
069878f467973aba16587b2841bc3d4cb5c5415b
5,446
hpp
C++
modules/tracking/src/tldTracker.hpp
onearrow/opencv_calib
c6f1922adec976b565aba4b4a54d8790bdce2cfa
[ "BSD-3-Clause" ]
17
2020-03-13T00:10:28.000Z
2021-09-06T17:13:17.000Z
opencv_contrib-3.4.1/modules/tracking/src/tldTracker.hpp
luoyongheng/opencv_add_contrib
99fc5c28f5e39ebb1a2b76c592ef72d598c429cb
[ "BSD-3-Clause" ]
1
2020-03-12T08:10:07.000Z
2020-03-12T08:10:07.000Z
opencv_contrib-3.4.1/modules/tracking/src/tldTracker.hpp
luoyongheng/opencv_add_contrib
99fc5c28f5e39ebb1a2b76c592ef72d598c429cb
[ "BSD-3-Clause" ]
3
2018-02-26T06:43:33.000Z
2021-03-18T09:13:30.000Z
/*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2013, OpenCV Foundation, all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) however caused // and on any theory of liability, whether in contract, strict liability, // or tort (including negligence or otherwise) arising in any way out of // the use of this software, even if advised of the possibility of such damage. // //M*/ #ifndef OPENCV_TLD_TRACKER #define OPENCV_TLD_TRACKER #include "precomp.hpp" #include "opencv2/video/tracking.hpp" #include "opencv2/imgproc.hpp" #include "tldModel.hpp" #include<algorithm> #include<limits.h> namespace cv { namespace tld { class TrackerProxy { public: virtual bool init(const Mat& image, const Rect2d& boundingBox) = 0; virtual bool update(const Mat& image, Rect2d& boundingBox) = 0; virtual ~TrackerProxy(){} }; class MyMouseCallbackDEBUG { public: MyMouseCallbackDEBUG(Mat& img, Mat& imgBlurred, TLDDetector* detector) :img_(img), imgBlurred_(imgBlurred), detector_(detector){} static void onMouse(int event, int x, int y, int, void* obj){ ((MyMouseCallbackDEBUG*)obj)->onMouse(event, x, y); } MyMouseCallbackDEBUG& operator = (const MyMouseCallbackDEBUG& /*other*/){ return *this; } private: void onMouse(int event, int x, int y); Mat& img_, imgBlurred_; TLDDetector* detector_; }; class Data { public: Data(Rect2d initBox); Size getMinSize(){ return minSize; } double getScale(){ return scale; } bool confident; bool failedLastTime; int frameNum; void printme(FILE* port = stdout); private: double scale; Size minSize; }; template<class T, class Tparams> class TrackerProxyImpl : public TrackerProxy { public: TrackerProxyImpl(Tparams params = Tparams()) :params_(params){} bool init(const Mat& image, const Rect2d& boundingBox) { trackerPtr = T::create(); return trackerPtr->init(image, boundingBox); } bool update(const Mat& image, Rect2d& boundingBox) { return trackerPtr->update(image, boundingBox); } private: Ptr<T> trackerPtr; Tparams params_; Rect2d boundingBox_; }; #undef BLUR_AS_VADIM #undef CLOSED_LOOP class TrackerTLDImpl : public TrackerTLD { public: TrackerTLDImpl(const TrackerTLD::Params &parameters = TrackerTLD::Params()); void read(const FileNode& fn); void write(FileStorage& fs) const; Ptr<TrackerModel> getModel() { return model; } class Pexpert { public: Pexpert(const Mat& img_in, const Mat& imgBlurred_in, Rect2d& resultBox_in, const TLDDetector* detector_in, TrackerTLD::Params params_in, Size initSize_in) : img_(img_in), imgBlurred_(imgBlurred_in), resultBox_(resultBox_in), detector_(detector_in), params_(params_in), initSize_(initSize_in){} bool operator()(Rect2d /*box*/){ return false; } int additionalExamples(std::vector<Mat_<uchar> >& examplesForModel, std::vector<Mat_<uchar> >& examplesForEnsemble); protected: Pexpert(){} Mat img_, imgBlurred_; Rect2d resultBox_; const TLDDetector* detector_; TrackerTLD::Params params_; RNG rng; Size initSize_; }; class Nexpert : public Pexpert { public: Nexpert(const Mat& img_in, Rect2d& resultBox_in, const TLDDetector* detector_in, TrackerTLD::Params params_in) { img_ = img_in; resultBox_ = resultBox_in; detector_ = detector_in; params_ = params_in; } bool operator()(Rect2d box); int additionalExamples(std::vector<Mat_<uchar> >& examplesForModel, std::vector<Mat_<uchar> >& examplesForEnsemble) { examplesForModel.clear(); examplesForEnsemble.clear(); return 0; } }; bool initImpl(const Mat& image, const Rect2d& boundingBox); bool updateImpl(const Mat& image, Rect2d& boundingBox); TrackerTLD::Params params; Ptr<Data> data; Ptr<TrackerProxy> trackerProxy; }; } } #endif
31.12
139
0.720162
[ "vector", "model" ]
0698ae7ea159ae88eb22a55df958cc08716acb23
4,511
cpp
C++
hello_directx_12/src/hello_d3d9on12/build_window_environment.cpp
kingofthebongo2008/computer-games-sofia-univeristy
1d54a02a456b3dde5eb5793e01a99a76daf6f033
[ "Apache-2.0" ]
5
2019-03-29T16:47:47.000Z
2019-05-08T18:34:50.000Z
hello_directx_12/src/hello_d3d9on12/build_window_environment.cpp
kingofthebongo2008/computer-games-sofia-univeristy
1d54a02a456b3dde5eb5793e01a99a76daf6f033
[ "Apache-2.0" ]
3
2019-04-21T08:05:04.000Z
2019-04-21T08:05:44.000Z
hello_directx_12/src/hello_d3d9on12/build_window_environment.cpp
kingofthebongo2008/computer-games-sofia-univeristy
1d54a02a456b3dde5eb5793e01a99a76daf6f033
[ "Apache-2.0" ]
null
null
null
#pragma once #include "pch.h" #include "build_window_environment.h" #include <ShellScalingApi.h> namespace sample { inline DXGI_MODE_ROTATION compute_display_rotation(window_environment::DisplayOrientations native_orientation, window_environment::DisplayOrientations current_orientation) { DXGI_MODE_ROTATION rotation = DXGI_MODE_ROTATION_UNSPECIFIED; // Note: NativeOrientation can only be Landscape or Portrait even though // the DisplayOrientations enum has other values. switch (native_orientation) { case window_environment::DisplayOrientations::Landscape: switch (current_orientation) { case window_environment::DisplayOrientations::Landscape: rotation = DXGI_MODE_ROTATION_IDENTITY; break; case window_environment::DisplayOrientations::Portrait: rotation = DXGI_MODE_ROTATION_ROTATE270; break; case window_environment::DisplayOrientations::LandscapeFlipped: rotation = DXGI_MODE_ROTATION_ROTATE180; break; case window_environment::DisplayOrientations::PortraitFlipped: rotation = DXGI_MODE_ROTATION_ROTATE90; break; } break; case window_environment::DisplayOrientations::Portrait: switch (current_orientation) { case window_environment::DisplayOrientations::Landscape: rotation = DXGI_MODE_ROTATION_ROTATE90; break; case window_environment::DisplayOrientations::Portrait: rotation = DXGI_MODE_ROTATION_IDENTITY; break; case window_environment::DisplayOrientations::LandscapeFlipped: rotation = DXGI_MODE_ROTATION_ROTATE270; break; case window_environment::DisplayOrientations::PortraitFlipped: rotation = DXGI_MODE_ROTATION_ROTATE180; break; } break; } return rotation; } // Converts a length in device-independent pixels (DIPs) to a length in physical pixels. inline float convert_dips_to_pixels(float dips, float dpi) { static const float dipsPerInch = 96.0f; return floorf( dips * dpi / dipsPerInch + 0.5f ); // Round to nearest integer. } window_environment build_environment(const HWND window) { window_environment result = {}; RECT rect; GetWindowRect(window, &rect); auto monitor = MonitorFromWindow(window, MONITOR_DEFAULTTONEAREST); UINT dpix; UINT dpiy; if (GetDpiForMonitor(monitor, MONITOR_DPI_TYPE::MDT_EFFECTIVE_DPI, &dpix, &dpiy)!= S_OK) { dpix = 96; dpiy = 96; } auto windowDpi = static_cast<float>(dpix); const uint32_t dpi = dpix; result.m_logical_size.Width = static_cast<float>(rect.right - rect.left) / (dpi / 96.0F); result.m_logical_size.Height = static_cast<float>(rect.bottom - rect.top) / (dpi / 96.0F); float f; result.m_dpi = dpi; result.m_effective_dpi = result.m_dpi; // no scaling for now, scaling is used for phones to save power. // Calculate the necessary render target size in pixels. result.m_output_size.Width = convert_dips_to_pixels(result.m_logical_size.Width, result.m_effective_dpi); result.m_output_size.Height = convert_dips_to_pixels(result.m_logical_size.Height, result.m_effective_dpi); // Prevent small sizes DirectX content from being created. result.m_output_size.Width = result.m_output_size.Width < 8 ? 8 : result.m_output_size.Width; result.m_output_size.Height = result.m_output_size.Height < 8 ? 8 : result.m_output_size.Height; auto display_rotation = compute_display_rotation(result.m_native_orientation, result.m_current_orientation); bool swap_dimensions = display_rotation == DXGI_MODE_ROTATION_ROTATE90 || display_rotation == DXGI_MODE_ROTATION_ROTATE270; result.m_back_buffer_size.Width = swap_dimensions ? result.m_output_size.Height : result.m_output_size.Width; result.m_back_buffer_size.Height = swap_dimensions ? result.m_output_size.Width : result.m_output_size.Height; return result; } }
38.555556
175
0.649523
[ "render" ]
06a0b9147facb8293c325e566d867d769162ca9a
9,739
cpp
C++
ct_optcon/test/dms/oscillator/oscDMSTest.cpp
romainreignier/control-toolbox
6ee83d401b1a8d2fbfda2646a0ec1ec0e67b7c96
[ "BSD-2-Clause" ]
864
2019-04-26T18:18:23.000Z
2022-03-28T17:38:48.000Z
ct_optcon/test/dms/oscillator/oscDMSTest.cpp
romainreignier/control-toolbox
6ee83d401b1a8d2fbfda2646a0ec1ec0e67b7c96
[ "BSD-2-Clause" ]
154
2019-04-27T05:32:19.000Z
2022-03-28T16:17:00.000Z
ct_optcon/test/dms/oscillator/oscDMSTest.cpp
romainreignier/control-toolbox
6ee83d401b1a8d2fbfda2646a0ec1ec0e67b7c96
[ "BSD-2-Clause" ]
249
2019-05-03T11:34:36.000Z
2022-03-14T19:17:05.000Z
/********************************************************************************************************************** This file is part of the Control Toolbox (https://github.com/ethz-adrl/control-toolbox), copyright by ETH Zurich Licensed under the BSD-2 license (see LICENSE file in main directory) **********************************************************************************************************************/ /*! * This file implements dms unit tests. * For more intuitive examples, visit the tutorial. * \example oscDMSTest.cpp */ #include <ct/optcon/optcon.h> #include <gtest/gtest.h> #include "oscDMSTest_settings.h" #ifdef MATLAB #include <ct/optcon/matlab.hpp> #endif namespace ct { namespace optcon { namespace example { class OscDms { public: EIGEN_MAKE_ALIGNED_OPERATOR_NEW typedef DmsDimensions<2, 1> OscDimensions; OscDms() : w_n_(0.5), zeta_(0.01) { matlabPathIPOPT_ = std::string(DATA_DIR) + "/solutionIpopt.mat"; matlabPathSNOPT_ = std::string(DATA_DIR) + "/solutionSnopt.mat"; settings_.N_ = 25; settings_.T_ = 5.0; settings_.nThreads_ = 4; settings_.splineType_ = DmsSettings::PIECEWISE_LINEAR; settings_.costEvaluationType_ = DmsSettings::FULL; settings_.objectiveType_ = DmsSettings::KEEP_TIME_AND_GRID; settings_.h_min_ = 0.1; // minimum admissible distance between two nodes in [sec] settings_.integrationType_ = DmsSettings::RK4; settings_.dt_sim_ = 0.01; settings_.absErrTol_ = 1e-8; settings_.relErrTol_ = 1e-8; settings_.print(); } ~OscDms() { std::cout << "Oscillator dms destructor called" << std::endl; } void getIpoptMatlabTrajectories() { #ifdef MATLAB matFileIpopt_.open(matlabPathIPOPT_, matlab::MatFile::READ); assert(matFileIpopt_.isOpen()); matFileIpopt_.get("stateDmsIpopt", stateMatIpopt_.toImplementation()); matFileIpopt_.get("inputDmsIpopt", inputMatIpopt_.toImplementation()); std::vector<Eigen::Matrix<double, 1, 1>, Eigen::aligned_allocator<Eigen::Matrix<double, 1, 1>>> timeEigen; matFileIpopt_.get("timeDmsIpopt", timeEigen); timeMatIpopt_.fromEigenTrajectory(timeEigen); matFileIpopt_.close(); #endif } void getSnoptMatlabTrajectories() { #ifdef MATLAB matFileSnopt_.open(matlabPathSNOPT_, matlab::MatFile::READ); assert(matFileSnopt_.isOpen()); matFileSnopt_.get("stateDmsSnopt", stateMatSnopt_.toImplementation()); matFileSnopt_.get("inputDmsSnopt", inputMatSnopt_.toImplementation()); std::vector<Eigen::Matrix<double, 1, 1>, Eigen::aligned_allocator<Eigen::Matrix<double, 1, 1>>> timeEigen; matFileSnopt_.get("timeDmsSnopt", timeEigen); timeMatSnopt_.fromEigenTrajectory(timeEigen); matFileSnopt_.close(); #endif } void initialize() { oscillator_ = std::shared_ptr<ct::core::SecondOrderSystem>(new ct::core::SecondOrderSystem(w_n_, zeta_)); x_0_ << 0.0, 0.0; x_final_ << 2.0, -1.0; Q_ << 0.0, 0.0, 0.0, 10.0; Q_final_ << 0.0, 0.0, 0.0, 0.0; R_ << 0.001; u_des_ << 0.0; costFunction_ = std::shared_ptr<ct::optcon::CostFunctionQuadratic<2, 1>>( new ct::optcon::CostFunctionQuadraticSimple<2, 1>(Q_, R_, x_final_, u_des_, x_final_, Q_final_)); } void getIpoptSolution() { settings_.solverSettings_.solverType_ = NlpSolverType::IPOPT; generalConstraints_ = std::shared_ptr<ct::optcon::ConstraintContainerAnalytical<2, 1>>( new ct::optcon::ConstraintContainerAnalytical<2, 1>()); std::shared_ptr<TerminalConstraint<2, 1>> termConstraint(new TerminalConstraint<2, 1>(x_final_)); termConstraint->setName("TerminalConstraint"); generalConstraints_->addTerminalConstraint(termConstraint, true); generalConstraints_->initialize(); ContinuousOptConProblem<2, 1> optProblem(oscillator_, costFunction_); optProblem.setInitialState(x_0_); optProblem.setTimeHorizon(settings_.T_); optProblem.setGeneralConstraints(generalConstraints_); dmsPlanner_ = std::shared_ptr<DmsSolver<2, 1>>(new DmsSolver<2, 1>(optProblem, settings_)); calcInitGuess(); dmsPlanner_->setInitialGuess(initialPolicy_); dmsPlanner_->solve(); solutionPolicy_ = dmsPlanner_->getSolution(); stateSolutionIpopt_ = solutionPolicy_.xSolution_; inputSolutionIpopt_ = solutionPolicy_.uSolution_; timeSolutionIpopt_ = solutionPolicy_.tSolution_; } void getSnoptSolution() { settings_.solverSettings_.solverType_ = NlpSolverType::SNOPT; generalConstraints_ = std::shared_ptr<ct::optcon::ConstraintContainerAnalytical<2, 1>>( new ct::optcon::ConstraintContainerAnalytical<2, 1>()); std::shared_ptr<TerminalConstraint<2, 1>> termConstraint(new TerminalConstraint<2, 1>(x_final_)); termConstraint->setName("TerminalConstraint"); generalConstraints_->addTerminalConstraint(termConstraint, true); generalConstraints_->initialize(); ContinuousOptConProblem<2, 1> optProblem(oscillator_, costFunction_); optProblem.setInitialState(x_0_); optProblem.setTimeHorizon(settings_.T_); optProblem.setGeneralConstraints(generalConstraints_); dmsPlanner_ = std::shared_ptr<DmsSolver<2, 1>>(new DmsSolver<2, 1>(optProblem, settings_)); calcInitGuess(); dmsPlanner_->setInitialGuess(initialPolicy_); dmsPlanner_->solve(); solutionPolicy_ = dmsPlanner_->getSolution(); stateSolutionSnopt_ = solutionPolicy_.xSolution_; inputSolutionSnopt_ = solutionPolicy_.uSolution_; timeSolutionSnopt_ = solutionPolicy_.tSolution_; } void compareIpoptSolutions() { #ifdef MATLAB ASSERT_TRUE(stateSolutionIpopt_.size() == stateMatIpopt_.size()); for (size_t i = 0; i < stateSolutionIpopt_.size(); ++i) { ASSERT_TRUE(stateSolutionIpopt_[i].isApprox(stateMatIpopt_[i])); ASSERT_TRUE(inputSolutionIpopt_[i].isApprox(inputMatIpopt_[i])); ASSERT_TRUE(timeSolutionIpopt_[i] == timeMatIpopt_[i]); } #endif } void compareSnoptSolutions() { #ifdef MATLAB ASSERT_TRUE(stateSolutionSnopt_.size() == stateMatSnopt_.size()); for (size_t i = 0; i < stateSolutionSnopt_.size(); ++i) { ASSERT_TRUE(stateSolutionSnopt_[i].isApprox(stateMatSnopt_[i])); ASSERT_TRUE(inputSolutionSnopt_[i].isApprox(inputMatSnopt_[i])); ASSERT_TRUE(timeSolutionSnopt_[i] == timeMatSnopt_[i]); } #endif } private: void calcInitGuess() { x_initguess_.resize(settings_.N_ + 1, OscDimensions::state_vector_t::Zero()); u_initguess_.resize(settings_.N_ + 1, OscDimensions::control_vector_t::Zero()); for (size_t i = 0; i < settings_.N_ + 1; ++i) { x_initguess_[i] = x_0_ + (x_final_ - x_0_) * (i / settings_.N_); } initialPolicy_.xSolution_ = x_initguess_; initialPolicy_.uSolution_ = u_initguess_; } double w_n_; double zeta_; std::shared_ptr<ct::core::SecondOrderSystem> oscillator_; std::string matlabPathIPOPT_; std::string matlabPathSNOPT_; DmsSettings settings_; std::shared_ptr<DmsSolver<2, 1>> dmsPlanner_; std::shared_ptr<ct::optcon::CostFunctionQuadratic<2, 1>> costFunction_; std::shared_ptr<ct::optcon::ConstraintContainerAnalytical<2, 1>> generalConstraints_; OscDimensions::state_vector_t x_0_; OscDimensions::state_vector_t x_final_; OscDimensions::state_matrix_t Q_; OscDimensions::state_matrix_t Q_final_; OscDimensions::control_matrix_t R_; OscDimensions::control_vector_t u_des_; DmsPolicy<2, 1> initialPolicy_; DmsPolicy<2, 1> solutionPolicy_; OscDimensions::state_vector_array_t x_initguess_; OscDimensions::control_vector_array_t u_initguess_; //Solutions loaded from Mat Files OscDimensions::state_vector_array_t stateMatIpopt_; OscDimensions::control_vector_array_t inputMatIpopt_; OscDimensions::time_array_t timeMatIpopt_; OscDimensions::state_vector_array_t stateMatSnopt_; OscDimensions::control_vector_array_t inputMatSnopt_; OscDimensions::time_array_t timeMatSnopt_; //Solution obtained by IPOPT, SNOPT OscDimensions::state_vector_array_t stateSolutionIpopt_; OscDimensions::control_vector_array_t inputSolutionIpopt_; OscDimensions::time_array_t timeSolutionIpopt_; OscDimensions::state_vector_array_t stateSolutionSnopt_; OscDimensions::control_vector_array_t inputSolutionSnopt_; OscDimensions::time_array_t timeSolutionSnopt_; #ifdef MATLAB matlab::MatFile matFileIpopt_; matlab::MatFile matFileSnopt_; #endif //MATLAB }; TEST(DmsTest, OscDmsTest) { OscDms oscDms; oscDms.initialize(); #ifdef BUILD_WITH_SNOPT_SUPPORT oscDms.getSnoptMatlabTrajectories(); oscDms.getSnoptSolution(); oscDms.compareSnoptSolutions(); #endif // BUILD_WITH_SNOPT_SUPPORT #ifdef BUILD_WITH_IPOPT_SUPPORT oscDms.getIpoptMatlabTrajectories(); oscDms.getIpoptSolution(); oscDms.compareIpoptSolutions(); #endif // BUILD_WITH_IPOPT_SUPPORT } } // namespace example } // namespace optcon } // namespace ct /*! * This unit test applies Direct Multiple Shooting to an oscillator system, uses different solvers and compares the outputs. * \example oscDMSTest.cpp */ int main(int argc, char** argv) { // using namespace ct::optcon::example; testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
35.158845
124
0.679947
[ "vector" ]
a62a828c3fcff12d4cb091fd971cdfc606e05a58
945
cpp
C++
Range Queries/Static Range Minimum Queries.cpp
DecSP/cses-downloader
12a8f37665a33f6f790bd2c355f84dea8a0e332c
[ "MIT" ]
2
2022-02-12T12:30:13.000Z
2022-02-12T13:59:20.000Z
Range Queries/Static Range Minimum Queries.cpp
DecSP/cses-downloader
12a8f37665a33f6f790bd2c355f84dea8a0e332c
[ "MIT" ]
2
2022-02-12T11:09:41.000Z
2022-02-12T11:55:49.000Z
Range Queries/Static Range Minimum Queries.cpp
DecSP/cses-downloader
12a8f37665a33f6f790bd2c355f84dea8a0e332c
[ "MIT" ]
null
null
null
# include <bits/stdc++.h> # define ll long long # define all(x) x.begin(), x.end() # define fastio ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL) # define MOD 1000000007 using namespace std; vector<int> st; vector<int> arr; void build(int v,int tl,int tr){ if (tl==tr){ st[v]=arr[tl]; } else{ int mid=tl+tr>>1; build(v*2,tl,mid); build(v*2+1,mid+1,tr); st[v]=min(st[v*2],st[v*2+1]); } } int get(int v,int tl,int tr,int l , int r){ if (tl==l&&tr==r) return st[v]; if (tl>r||tr<l) return -1; int mid=tl+tr>>1; int x=get(v*2,tl,mid,l,min(mid,r)),y=get(v*2+1,mid+1,tr,max(l,mid+1),r); if (x==-1)return y; if (y==-1) return x; return min(x,y); } int main(){ fastio; int n,q; cin>>n>>q; st.assign(4*n,0); arr.assign(n,0); for (auto & v:arr)cin>>v; build(1,0,n-1); int x,y; for (int i=0;i<q;i++){ cin>>x>>y; cout<<get(1,0,n-1,x-1,y-1)<<'\n'; } return 0; }
21.477273
80
0.556614
[ "vector" ]
a63008fa83fa9fb7c45fcabdec9cccead2a1fd72
2,393
hpp
C++
hougeo/ttl/collection.hpp
all-in-one-of/hougeo
7ef770562f0095b59a4ce876976fc5c34a8b5533
[ "MIT" ]
9
2017-04-24T08:55:48.000Z
2021-12-21T13:15:02.000Z
hougeo/ttl/collection.hpp
all-in-one-of/hougeo
7ef770562f0095b59a4ce876976fc5c34a8b5533
[ "MIT" ]
null
null
null
hougeo/ttl/collection.hpp
all-in-one-of/hougeo
7ef770562f0095b59a4ce876976fc5c34a8b5533
[ "MIT" ]
2
2019-02-19T20:16:16.000Z
2019-08-22T08:51:26.000Z
// collection.hpp // // Copyright (c) 2004 Eugene Gladyshev // // Permission to copy, use, modify, sell and distribute this software // is granted provided this copyright notice appears in all copies. // This software is provided "as is" without express or implied // warranty, and with no claim as to its suitability for any purpose. // #if defined(_MSC_VER) #pragma once #endif #ifndef __ttl_collection__hpp #define __ttl_collection__hpp namespace ttl { #define TTL_COLLECTION_ARG(n,t) const T& t##n, #define TTL_COLLECTION_ARG_END(n,t) const T& t##n #define TTL_COLLECTION_ITEM(n,t) push_back(t##n); #define TTL_COLLECTION_ITEM_END(n,t) push_back(t##n); #define TTL_COLLECTION_ARGS(n) TTL_REPEAT(n, TTL_COLLECTION_ARG, TTL_COLLECTION_ARG_END, p) #define TTL_COLLECTION_ITEMS(n) TTL_REPEAT(n, TTL_COLLECTION_ITEM, TTL_COLLECTION_ITEM_END, p) template< typename T, typename C = std::vector<T> > struct collection : C { typedef C container; collection( ) {} collection( TTL_COLLECTION_ARGS(1) ) { reserve(1); TTL_COLLECTION_ITEMS(1) } collection( TTL_COLLECTION_ARGS(2) ) { reserve(2); TTL_COLLECTION_ITEMS(2) } collection( TTL_COLLECTION_ARGS(3) ) { reserve(3); TTL_COLLECTION_ITEMS(3) } collection( TTL_COLLECTION_ARGS(4) ) { reserve(4); TTL_COLLECTION_ITEMS(4) } collection( TTL_COLLECTION_ARGS(5) ) { reserve(5); TTL_COLLECTION_ITEMS(5) } collection( TTL_COLLECTION_ARGS(6) ) { reserve(6); TTL_COLLECTION_ITEMS(6) } collection( TTL_COLLECTION_ARGS(7) ) { reserve(7); TTL_COLLECTION_ITEMS(7) } collection( TTL_COLLECTION_ARGS(8) ) { reserve(8); TTL_COLLECTION_ITEMS(8) } collection( TTL_COLLECTION_ARGS(9) ) { reserve(9); TTL_COLLECTION_ITEMS(9) } collection( TTL_COLLECTION_ARGS(10) ) { reserve(10); TTL_COLLECTION_ITEMS(10) } collection( TTL_COLLECTION_ARGS(11) ) { reserve(11); TTL_COLLECTION_ITEMS(11) } collection( TTL_COLLECTION_ARGS(12) ) { reserve(12); TTL_COLLECTION_ITEMS(12) } collection( TTL_COLLECTION_ARGS(13) ) { reserve(13); TTL_COLLECTION_ITEMS(13) } collection( TTL_COLLECTION_ARGS(14) ) { reserve(14); TTL_COLLECTION_ITEMS(14) } collection( TTL_COLLECTION_ARGS(15) ) { reserve(15); TTL_COLLECTION_ITEMS(15) } }; }; #endif //__ttl_collection__hpp
20.62931
94
0.697869
[ "vector" ]
a6300d40bdf357b84d693bb2c59e829abb495fd8
1,162
cpp
C++
test/test_nvim_eval.cpp
Mu-L/nvui
568e9cb17970c56cee8909ac4f39ea7ab52bc46a
[ "MIT" ]
1,503
2021-08-29T16:57:50.000Z
2022-03-29T12:15:09.000Z
test/test_nvim_eval.cpp
Mu-L/nvui
568e9cb17970c56cee8909ac4f39ea7ab52bc46a
[ "MIT" ]
94
2021-08-29T17:06:23.000Z
2022-03-26T03:32:20.000Z
test/test_nvim_eval.cpp
Mu-L/nvui
568e9cb17970c56cee8909ac4f39ea7ab52bc46a
[ "MIT" ]
44
2021-08-29T18:11:09.000Z
2022-03-14T08:05:35.000Z
#include "nvim.hpp" #include "utils.hpp" #include <catch2/catch.hpp> #include <atomic> #include <iostream> #include <memory> #include <string> #include <utility> #include "object.hpp" using namespace std::chrono_literals; TEST_CASE("nvim_eval callbacks work", "[eval_cb]") { Nvim nvim; REQUIRE(nvim.running()); SECTION("Evaluating math") { std::atomic<bool> done = false; nvim.eval_cb("1 + 2", [&](Object res, Object err) { REQUIRE(err.is_null()); REQUIRE(res.try_convert<int>()); REQUIRE(*res.try_convert<int>() == 3); done = true; }); wait_for_value(done, true); } SECTION("Can evaluate variables") { std::atomic<bool> done = false; nvim.eval_cb("stdpath('config')", [&](Object res, Object err) { REQUIRE(err.is_null()); REQUIRE(res.string()); done = true; }); wait_for_value(done, true); } SECTION("Will send errors in the 'err' parameter") { std::atomic<bool> done = false; nvim.eval_cb("stdpath", [&](Object res, Object err) { REQUIRE(res.is_null()); REQUIRE(!err.is_null()); done = true; }); wait_for_value(done, true); } }
23.714286
67
0.614458
[ "object" ]
a634f8916fd1333c31fe033cf7c31729b0b6a0b8
10,361
cpp
C++
lib/Instrumenters/Preparer.cpp
sdasgup3/neongoby
961a043c21c46c139b1f7a4e11d1a3918c84da55
[ "BSD-3-Clause" ]
2
2020-08-29T15:04:36.000Z
2020-08-29T15:05:45.000Z
lib/Instrumenters/Preparer.cpp
sdasgup3/neongoby
961a043c21c46c139b1f7a4e11d1a3918c84da55
[ "BSD-3-Clause" ]
null
null
null
lib/Instrumenters/Preparer.cpp
sdasgup3/neongoby
961a043c21c46c139b1f7a4e11d1a3918c84da55
[ "BSD-3-Clause" ]
null
null
null
// vim: sw=2 #define DEBUG_TYPE "dyn-aa" #include <string> #include "llvm/Module.h" #include "llvm/Pass.h" #include "llvm/DerivedTypes.h" #include "llvm/Constants.h" #include "llvm/Support/CallSite.h" #include "llvm/Support/raw_ostream.h" #include "llvm/Support/Debug.h" #include "llvm/Support/CommandLine.h" #include "llvm/Target/TargetData.h" #include "llvm/ADT/DenseSet.h" #include "llvm/Transforms/Utils/BuildLibCalls.h" #include "rcs/typedefs.h" #include "dyn-aa/Utils.h" using namespace llvm; using namespace std; using namespace rcs; namespace neongoby { struct Preparer: public ModulePass { static char ID; Preparer(); virtual void getAnalysisUsage(AnalysisUsage &AU) const; virtual bool runOnModule(Module &M); private: static unsigned RoundUpToPowerOfTwo(unsigned Value); void replaceUndefsWithNull(Module &M); // use-def chains sometimes form a cycle. // Do not visit a User twice by using Replaced. void replaceUndefsWithNull(User *I, ValueSet &Replaced); void allocateExtraBytes(Module &M); void expandMemoryAllocation(Function *F); void expandGlobal(Module &M, GlobalVariable *GV); void expandAlloca(AllocaInst *AI); void expandMalloc(CallSite CS); void expandCallSite(CallSite CS); void fillInAllocationSize(Module &M); void fillInAllocationSize(CallSite CS); }; } using namespace neongoby; char Preparer::ID = 0; static RegisterPass<Preparer> X( "prepare", "Preparing transformations for both online and offline mode", false, false); void Preparer::getAnalysisUsage(AnalysisUsage &AU) const { AU.addRequired<TargetData>(); } Preparer::Preparer(): ModulePass(ID) {} bool Preparer::runOnModule(Module &M) { replaceUndefsWithNull(M); allocateExtraBytes(M); fillInAllocationSize(M); return true; } void Preparer::replaceUndefsWithNull(Module &M) { ValueSet Replaced; for (Module::global_iterator GI = M.global_begin(); GI != M.global_end(); ++GI) { if (GI->hasInitializer()) { replaceUndefsWithNull(GI->getInitializer(), Replaced); } } for (Module::iterator F = M.begin(); F != M.end(); ++F) { for (Function::iterator BB = F->begin(); BB != F->end(); ++BB) { for (BasicBlock::iterator Ins = BB->begin(); Ins != BB->end(); ++Ins) { replaceUndefsWithNull(Ins, Replaced); } } } } void Preparer::replaceUndefsWithNull(User *I, ValueSet &Replaced) { if (Replaced.count(I)) return; Replaced.insert(I); for (User::op_iterator OI = I->op_begin(); OI != I->op_end(); ++OI) { Value *V = OI->get(); if (isa<UndefValue>(V) && V->getType()->isPointerTy()) { OI->set(ConstantPointerNull::get(cast<PointerType>(V->getType()))); } if (User *I2 = dyn_cast<User>(V)) { replaceUndefsWithNull(I2, Replaced); } } } void Preparer::allocateExtraBytes(Module &M) { for (Module::global_iterator GI = M.global_begin(); GI != M.global_end(); ++GI) { expandGlobal(M, GI); } for (Module::iterator F = M.begin(); F != M.end(); ++F) { expandMemoryAllocation(F); } } void Preparer::expandGlobal(Module &M, GlobalVariable *GV) { if (GV->isDeclaration()) return; if (GV->getLinkage() == GlobalValue::AppendingLinkage) return; Type *OrigType = GV->getType()->getTypeAtIndex((unsigned)0); StructType *NewType = StructType::create(GV->getContext(), "pad_global_type"); NewType->setBody(OrigType, IntegerType::get(GV->getContext(), 8), NULL); // FIXME: AddressSpace? GlobalVariable *NewGV; Constant *NewInit = NULL; if (GV->hasInitializer()) { assert(GV->getInitializer()->getType() == OrigType); NewInit = ConstantStruct::get(NewType, GV->getInitializer(), ConstantInt::get(IntegerType::get(GV->getContext(), 8), 0), NULL); } NewGV = new GlobalVariable(M, NewType, GV->isConstant(), GV->getLinkage(), NewInit, "pad_global", GV, GV->isThreadLocal(), 0); Constant *NewValue = ConstantExpr::getBitCast(NewGV, GV->getType()); assert(NewValue->getType() == GV->getType()); GV->replaceAllUsesWith(NewValue); } void Preparer::expandMemoryAllocation(Function *F) { for (Function::iterator BB = F->begin(); BB != F->end(); ++BB) { for (BasicBlock::iterator Ins = BB->begin(); Ins != BB->end(); ) { // <Ins> may be removed in the body. Save its next instruction. BasicBlock::iterator NextIns = Ins; ++NextIns; if (AllocaInst *AI = dyn_cast<AllocaInst>(Ins)) { expandAlloca(AI); } else { CallSite CS(Ins); if (CS) { expandCallSite(CS); if (Function *Callee = CS.getCalledFunction()) { if (Callee && DynAAUtils::IsMalloc(Callee)) { expandMalloc(CS); } } } } Ins = NextIns; } } } void Preparer::expandMalloc(CallSite CS) { Function *Callee = CS.getCalledFunction(); assert(Callee); StringRef CalleeName = Callee->getName(); if (CalleeName == "malloc" || CalleeName == "valloc") { Value *Size = CS.getArgument(0); Value *ExpandedSize = BinaryOperator::Create( Instruction::Add, Size, ConstantInt::get(cast<IntegerType>(Size->getType()), 1), "expanded.size", CS.getInstruction()); CS.setArgument(0, ExpandedSize); } } void Preparer::expandAlloca(AllocaInst *AI) { // Skip ng.slots which is added by AliasCheckerInstrumenter. if (AI->getName().startswith(DynAAUtils::SlotsName)) return; if (AI->isArrayAllocation()) { // e.g. %32 = alloca i8, i64 %conv164 Value *Size = AI->getArraySize(); Value *ExpandedSize = BinaryOperator::Create( Instruction::Add, Size, ConstantInt::get(cast<IntegerType>(Size->getType()), 1), "expanded.size", AI); AI->setOperand(0, ExpandedSize); return; } Type *AllocatedType = AI->getAllocatedType(); if (ArrayType *ArrType = dyn_cast<ArrayType>(AllocatedType)) { ArrayType *NewArrType = ArrayType::get(ArrType->getElementType(), ArrType->getNumElements() + 1); AllocaInst *NewAI = new AllocaInst(NewArrType, AI->getName(), AI); // inherit the alignment as well NewAI->setAlignment(AI->getAlignment()); BitCastInst *CastNewAI = new BitCastInst(NewAI, AI->getType(), AI->getName(), AI); AI->replaceAllUsesWith(CastNewAI); AI->eraseFromParent(); return; } assert(AllocatedType->isSized()); IntegerType *PadType = IntegerType::get(AI->getContext(), 8); new AllocaInst(PadType, "alloca_pad", AI); } void Preparer::expandCallSite(CallSite CS) { // Skip the callsites that are not calling a va function. Value *Callee = CS.getCalledValue(); FunctionType *CalleeType = cast<FunctionType>( cast<PointerType>(Callee->getType())->getElementType()); if (!CalleeType->isVarArg()) { return; } vector<Value *> Args; for (CallSite::arg_iterator ArgI = CS.arg_begin(); ArgI != CS.arg_end(); ArgI++) { Args.push_back(*ArgI); } Args.push_back(ConstantInt::get( IntegerType::get(CS.getInstruction()->getContext(), 8), 0)); string InstName = ""; if (CS.getInstruction()->getName() != "") InstName = CS.getInstruction()->getName().str() + ".padded"; if (CallInst *CI = dyn_cast<CallInst>(CS.getInstruction())) { CallInst *NewCI = CallInst::Create(Callee, Args, InstName, CI); NewCI->setAttributes(CI->getAttributes()); CI->replaceAllUsesWith(NewCI); CI->eraseFromParent(); } else if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) { InvokeInst *NewII = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(), Args, InstName, II); NewII->setAttributes(II->getAttributes()); II->replaceAllUsesWith(NewII); II->eraseFromParent(); } } unsigned Preparer::RoundUpToPowerOfTwo(unsigned Value) { // TODO: should be able to be optimized using bitwise operations unsigned Result; for (Result = 1; Result < Value; Result *= 2); return Result; } void Preparer::fillInAllocationSize(Module &M) { Function *MemAllocHook = M.getFunction(DynAAUtils::MemAllocHookName); // Skip this process if there's no HookMemAlloc. if (!MemAllocHook) return; for (Module::iterator F = M.begin(); F != M.end(); ++F) { for (Function::iterator BB = F->begin(); BB != F->end(); ++BB) { for (BasicBlock::iterator I = BB->begin(); I != BB->end(); ++I) { CallSite CS(I); if (CS && CS.getCalledFunction() == MemAllocHook) { // HookMemAlloc(ValueID, Base, Size = undef) assert(CS.arg_size() == 3); if (isa<UndefValue>(CS.getArgument(2))) fillInAllocationSize(CS); } } } } } // CallSite is light-weight, and passed by value. void Preparer::fillInAllocationSize(CallSite CS) { // HookMemAlloc(ValueID, Base, Size = undef) Value *Base = CS.getArgument(1); while (BitCastInst *BCI = dyn_cast<BitCastInst>(Base)) { Base = BCI->getOperand(0); } if (AllocaInst *AI = dyn_cast<AllocaInst>(Base)) { TargetData &TD = getAnalysis<TargetData>(); Value *Size = ConstantInt::get( TD.getIntPtrType(AI->getContext()), TD.getTypeStoreSize(AI->getAllocatedType())); if (AI->isArrayAllocation()) { // e.g. %32 = alloca i8, i64 %conv164 Size = BinaryOperator::Create(Instruction::Mul, Size, AI->getArraySize(), "", AI); } CS.setArgument(2, Size); } else if (DynAAUtils::IsMallocCall(Base)) { CallSite MallocCS(Base); assert(MallocCS); Function *Malloc = MallocCS.getCalledFunction(); assert(Malloc); StringRef MallocName = Malloc->getName(); assert(MallocName == "malloc" || MallocName == "valloc"); CS.setArgument(2, MallocCS.getArgument(0)); } else { // For now, MemoryInstrumenter will only use undef for the allocation size // for AllocaInsts, malloc, and valloc. assert(false); } }
32.177019
80
0.621079
[ "vector" ]
a6351431578ef34d89cb899ea0746091a90747ea
2,267
hpp
C++
sourceCode/dotNet4.6/wpf/src/printing/cpp/inc/genericprinterlevelthunk.hpp
csoap/csoap.github.io
2a8db44eb63425deff147652b65c5912f065334e
[ "Apache-2.0" ]
5
2017-03-03T02:13:16.000Z
2021-08-18T09:59:56.000Z
sourceCode/dotNet4.6/wpf/src/printing/cpp/inc/genericprinterlevelthunk.hpp
295007712/295007712.github.io
25241dbf774427545c3ece6534be6667848a6faf
[ "Apache-2.0" ]
null
null
null
sourceCode/dotNet4.6/wpf/src/printing/cpp/inc/genericprinterlevelthunk.hpp
295007712/295007712.github.io
25241dbf774427545c3ece6534be6667848a6faf
[ "Apache-2.0" ]
4
2016-11-15T05:20:12.000Z
2021-11-13T16:32:11.000Z
#pragma once #ifndef __GENERICPRINTEREVELTHUNK_HPP__ #define __GENERICPRINTEREVELTHUNK_HPP__ /*++ Copyright (C) 2002 - 2003 Microsoft Corporation All rights reserved. Module Name: GenericPrinterLevelThunk.hpp Abstract: Win32PrinterThunk - This is object that does the Win32 thunking for a PrintQueue based on the level specified in the constructor. The object has the knowledge of calling the thunked GetPrinter, SetPrinter and EnumPrinters APIs. Author: Adina Trufinescu (adinatru) April 24th 2003 Revision History: --*/ namespace MS { namespace Internal { namespace PrintWin32Thunk { namespace AttributeNameToInfoLevelMapping { namespace PrintQueueThunk { using namespace System::Security; private ref class Win32PrinterThunk : public InfoLevelThunk { public: Win32PrinterThunk( UInt32 infoLevel, InfoLevelMask infoCoverageMask ); virtual void CallWin32ApiToGetPrintInfoData( PrinterThunkHandler^ printThunkHandler, Object^ cookie ) override; virtual UInt32 CallWin32ApiToEnumeratePrintInfoData( String^ serverName, UInt32 flags ); virtual void BeginCallWin32ApiToSetPrintInfoData( PrinterThunkHandler^ printThunkHandler ) override; ///<SecurityNote> /// Critical - Calls critical IPrinterInfo.get_Win32SafeHandle(). /// TreatAsSafe - Does not call critical SafeMemoryHandle.Dispose, does not expose critical SafeMemoryHandle ///</SecurityNote> [SecurityCritical, SecurityTreatAsSafe] virtual void EndCallWin32ApiToSetPrintInfoData( PrinterThunkHandler^ printThunkHandler ) override; }; } } } } } #endif
26.988095
116
0.55139
[ "object" ]
a6425148f65f4fd933eec08b3df589f3276da37d
14,680
cpp
C++
isis/src/newhorizons/objs/NewHorizonsMvicFrameCamera/NewHorizonsMvicFrameCameraDistortionMap.cpp
ihumphrey-usgs/ISIS3_old
284cc442b773f8369d44379ee29a9b46961d8108
[ "Unlicense" ]
1
2019-10-13T15:31:33.000Z
2019-10-13T15:31:33.000Z
isis/src/newhorizons/objs/NewHorizonsMvicFrameCamera/NewHorizonsMvicFrameCameraDistortionMap.cpp
ihumphrey-usgs/ISIS3_old
284cc442b773f8369d44379ee29a9b46961d8108
[ "Unlicense" ]
null
null
null
isis/src/newhorizons/objs/NewHorizonsMvicFrameCamera/NewHorizonsMvicFrameCameraDistortionMap.cpp
ihumphrey-usgs/ISIS3_old
284cc442b773f8369d44379ee29a9b46961d8108
[ "Unlicense" ]
1
2021-07-12T06:05:03.000Z
2021-07-12T06:05:03.000Z
/** * @file * * Unless noted otherwise, the portions of Isis written by the USGS are public * domain. See individual third-party library and package descriptions for * intellectual property information,user agreements, and related information. * * Although Isis has been used by the USGS, no warranty, expressed or implied, * is made by the USGS as to the accuracy and functioning of such software * and related material nor shall the fact of distribution constitute any such * warranty, and no responsibility is assumed by the USGS in connection * therewith. * * For additional information, launch * $ISISROOT/doc//documents/Disclaimers/Disclaimers.html in a browser or see * the Privacy &amp; Disclaimers page on the Isis website, * http://isis.astrogeology.usgs.gov, and the USGS privacy and disclaimers on * http://www.usgs.gov/privacy.html. */ #include <cmath> #include <iostream> #include <boost/math/special_functions/legendre.hpp> #include "Camera.h" #include "Constants.h" #include "FunctionTools.h" #include "IString.h" #include "NewHorizonsMvicFrameCameraDistortionMap.h" #include "CameraFocalPlaneMap.h" #include <QDebug> using namespace boost::math; using namespace std; using namespace Isis; namespace Isis { /** Camera distortion map constructor * * This class maps between distorted and undistorted focal plane x/y's. The default mapping is the * identity, that is, the focal plane x/y and undistorted focal plane x/y will be identical. * * @param parent the parent camera that will use this distortion map * @param zDirection the direction of the focal plane Z-axis * (either 1 or -1) * * @param xDistortionCoeffs distortion coefficients in x * @param yDistortionCoeffs distortion coefficients in y */ NewHorizonsMvicFrameCameraDistortionMap::NewHorizonsMvicFrameCameraDistortionMap(Camera *parent, vector<double> xDistortionCoeffs, vector<double> yDistortionCoeffs) : CameraDistortionMap(parent, 1.0) { m_xDistortionCoeffs = xDistortionCoeffs; m_yDistortionCoeffs = yDistortionCoeffs; double pixelPitch = p_camera->PixelPitch(); m_focalPlaneHalf_x = 0.5 * p_camera->Samples() * pixelPitch; // 32.5 mm m_focalPlaneHalf_y = 0.5 * p_camera->Lines() * pixelPitch; // 0.832 mm } /** Destructor */ NewHorizonsMvicFrameCameraDistortionMap::~NewHorizonsMvicFrameCameraDistortionMap() { } // /** // * Testing method to output corrections in x and y at pixel centers for entire focal plane. // * Output in csv format for viewing/plotting in Excel. // */ //bool NewHorizonsMvicFrameCameraDistortionMap::outputDeltas() { // // QString ofname("mvic_frame_deltas.csv"); // std::ofstream fp_out(ofname.toLatin1().data(), std::ios::out); // if (!fp_out) // return false; // // char buf[1056]; // // double deltax, deltay; // // for (double line = 0.5; line <= 128.5; line += 1.0) { // loop in y direction // for (double sample=0.5; sample <= 5000.5; sample += 1.0) { // loop in x direction // // p_camera->FocalPlaneMap()->SetDetector(sample,line); // // double fplanex = p_camera->FocalPlaneMap()->FocalPlaneX(); // double fplaney = p_camera->FocalPlaneMap()->FocalPlaneY(); // // SetFocalPlane(fplanex,fplaney); // // deltax = fplanex - p_undistortedFocalPlaneX; // deltay = fplaney - p_undistortedFocalPlaneY; // // sprintf(buf, "%lf,%lf,%lf,%lf\n", sample, deltax/0.013, line, deltay/0.013); // // fp_out << buf; // } // } // // fp_out.close(); // // return true; //} /** Compute undistorted focal plane x/y * * Compute undistorted focal plane x/y given a distorted focal plane x/y. * * @param dx distorted focal plane x in millimeters * @param dy distorted focal plane y in millimeters * * @return if the conversion was successful * @see SetDistortion */ bool NewHorizonsMvicFrameCameraDistortionMap::SetFocalPlane(const double dx, const double dy) { p_focalPlaneX = dx; p_focalPlaneY = dy; // in case of failures, initialize undistorted focal plane coordinates to the distorted // coordinate values p_undistortedFocalPlaneX = dx; p_undistortedFocalPlaneY = dy; // if x and/or y lie outside of the detector, do NOT apply distortion // set undistorted focal plane values to be identical to raw values if ((fabs(dx) > m_focalPlaneHalf_x) || (fabs(dy) > m_focalPlaneHalf_y)) { return true; } // shift from ISIS MVIC FT image coordinate system with +x to the left and +y down to // the desired system of +x to the right and +y up // e.g. negate x and y // scale x and y to lie in the range -1.0 to +1.0 // this is requirement for Legendre Polynomials, man double xscaled = -dx/m_focalPlaneHalf_x; double yscaled = -dy/m_focalPlaneHalf_y; // compute distortion corrections in x and y using Legendre Polynomials // these corrections are also in the -1.0 to +1.0 range // if Legendre computations fail, we set undistorted focal plane x and y // to be identical to distorted x and y and return true double deltax, deltay; if (!computeDistortionCorrections(xscaled, yscaled, deltax, deltay)) { return true; } // apply the corrections to original x,y xscaled += deltax; yscaled += deltay; // scale back from range of '-1.0 to +1.0' to the detector, '-32.5 to 32.5 mm' p_undistortedFocalPlaneX = -xscaled * m_focalPlaneHalf_x; p_undistortedFocalPlaneY = -yscaled * m_focalPlaneHalf_y; return true; } // bool NewHorizonsMvicFrameCameraDistortionMap::SetFocalPlane(const double dx, const double dy) { // p_focalPlaneX = dx; // p_focalPlaneY = dy; // // if x and/or y lie outside of the detector, do NOT apply distortion // // set undistorted focal plane values to be identical to raw values // if ((fabs(dx) > m_focalPlaneHalf_x) || (fabs(dy) > m_focalPlaneHalf_y)) { // p_undistortedFocalPlaneX = dx; // p_undistortedFocalPlaneY = dy; // return true; // } // // scale x and y to lie in the range -1.0 to +1.0 // // this is requirement for Legendre Polynomials, man // double xscaled = dx/m_focalPlaneHalf_x; // double yscaled = dy/m_focalPlaneHalf_y; // // compute distortion corrections in x and y using Legendre Polynomials // // these corrections are also in the -1.0 to +1.0 range // double deltax, deltay; // computeDistortionCorrections(xscaled, yscaled, deltax, deltay); // // apply the corrections // xscaled += deltax; // yscaled += deltay; // // scale back from range of '-1.0 to +1.0' to the detector, '-32.656 to 32.656 mm' // p_undistortedFocalPlaneX = xscaled * m_focalPlaneHalf_x; // p_undistortedFocalPlaneY = yscaled * m_focalPlaneHalf_y; // return true; // } /** Compute distorted focal plane x/y * * Compute distorted focal plane x/y given an undistorted focal plane x/y. * * This is an iterative procedure. * * @param ux undistorted focal plane x in millimeters * @param uy undistorted focal plane y in millimeters * * @return if the conversion was successful * @see SetDistortion */ bool NewHorizonsMvicFrameCameraDistortionMap::SetUndistortedFocalPlane(const double ux, const double uy) { // image coordinates prior to introducing distortion p_undistortedFocalPlaneX = ux; p_undistortedFocalPlaneY = uy; double xScaledDistortion, yScaledDistortion; // scale undistorted coordinates to range of -1.0 to +1.0 double xtScaled = -ux/m_focalPlaneHalf_x; double ytScaled = -uy/m_focalPlaneHalf_y; double uxScaled = xtScaled; double uyScaled = ytScaled; double xScaledPrevious = 1000000.0; double yScaledPrevious = 1000000.0; double tolerance = 0.000001; bool bConverged = false; // iterating to introduce distortion... // we stop when the difference between distorted coordinates // in successive iterations is at or below the given tolerance for( int i = 0; i < 50; i++ ) { // compute distortion in x and y (scaled to -1.0 - +1.0) using Legendre Polynomials computeDistortionCorrections(xtScaled, ytScaled, xScaledDistortion, yScaledDistortion); // update scaled image coordinates xtScaled = uxScaled - xScaledDistortion; ytScaled = uyScaled - yScaledDistortion; // check for convergence if((fabs(xtScaled - xScaledPrevious) <= tolerance) && (fabs(ytScaled - yScaledPrevious) <= tolerance)) { bConverged = true; break; } xScaledPrevious = xtScaled; yScaledPrevious = ytScaled; } if (bConverged) { // scale coordinates back to detector (-32.5 to +32.5) xtScaled *= -m_focalPlaneHalf_x; ytScaled *= -m_focalPlaneHalf_y; // set distorted coordinates p_focalPlaneX = xtScaled; p_focalPlaneY = ytScaled; } return bConverged; } // bool NewHorizonsMvicFrameCameraDistortionMap::SetUndistortedFocalPlane(const double ux, const double uy) { // // image coordinates prior to introducing distortion // p_undistortedFocalPlaneX = ux; // p_undistortedFocalPlaneY = uy; // double xScaledDistortion, yScaledDistortion; // // scale undistorted coordinates to range of -1.0 to +1.0 // double xtScaled = ux/m_focalPlaneHalf_x; // double ytScaled = uy/m_focalPlaneHalf_y; // double uxScaled = xtScaled; // double uyScaled = ytScaled; // double xScaledPrevious = 1000000.0; // double yScaledPrevious = 1000000.0; // double tolerance = 0.000001; // bool bConverged = false; // // iterating to introduce distortion... // // we stop when the difference between distorted coordinates // // in successive iterations is at or below the given tolerance // for( int i = 0; i < 50; i++ ) { // // compute distortion in x and y (scaled to -1.0 - +1.0) using Legendre Polynomials // computeDistortionCorrections(xtScaled, ytScaled, xScaledDistortion, yScaledDistortion); // // update scaled image coordinates // xtScaled = uxScaled - xScaledDistortion; // ytScaled = uyScaled - yScaledDistortion; // // check for convergence // if((fabs(xtScaled - xScaledPrevious) <= tolerance) && (fabs(ytScaled - yScaledPrevious) <= tolerance)) { // bConverged = true; // break; // } // xScaledPrevious = xtScaled; // yScaledPrevious = ytScaled; // } // if (bConverged) { // // scale coordinates back to detector (-32.656 to +32.656) // xtScaled *= m_focalPlaneHalf_x; // ytScaled *= m_focalPlaneHalf_y; // // set distorted coordinates // p_focalPlaneX = xtScaled; // p_focalPlaneY = ytScaled; // } // return bConverged; // } /** Compute distortion corrections in x and y direction * * For Legendre Polynomials, see ... * * http://mathworld.wolfram.com/LegendrePolynomial.html * http://www.boost.org/doc/libs/1_36_0/libs/math/doc/sf_and_dist/html/math_toolkit/special/sf_poly/legendre.html * * @param xscaled focal plane x scaled to range of 1- to 1 for Legendre Polynomials * @param yscaled focal plane y scaled to range of 1- to 1 for Legendre Polynomials * @param deltax focal plane distortion correction to x in millimeters * @param deltay focal plane distortion correction to y in millimeters * * @return if successful */ bool NewHorizonsMvicFrameCameraDistortionMap::computeDistortionCorrections(const double xscaled, const double yscaled, double &deltax, double &deltay) { double lpx0, lpx1, lpx2, lpx3, lpx4, lpx5; double lpy0, lpy1, lpy2, lpy3, lpy4, lpy5; // Legendre polynomials // boost library method legendre_p will generate an exception if xscaled or yscaled do not lie // between -1 to 1 (inclusive). In this event we return false. try { lpx0 = legendre_p(0,xscaled); lpx1 = legendre_p(1,xscaled); lpx2 = legendre_p(2,xscaled); lpx3 = legendre_p(3,xscaled); lpx4 = legendre_p(4,xscaled); lpx5 = legendre_p(5,xscaled); lpy0 = legendre_p(0,yscaled); lpy1 = legendre_p(1,yscaled); lpy2 = legendre_p(2,yscaled); lpy3 = legendre_p(3,yscaled); lpy4 = legendre_p(4,yscaled); lpy5 = legendre_p(5,yscaled); } // TESTING NOTE: Could not find a way to cause this error. If one is found a test should be added catch (const std::exception& e) { return false; } deltax = m_xDistortionCoeffs[0] * lpx0 * lpy1 + m_xDistortionCoeffs[1] * lpx1 * lpy0 + m_xDistortionCoeffs[2] * lpx0 * lpy2 + m_xDistortionCoeffs[3] * lpx1 * lpy1 + m_xDistortionCoeffs[4] * lpx2 * lpy0 + m_xDistortionCoeffs[5] * lpx0 * lpy3 + m_xDistortionCoeffs[6] * lpx1 * lpy2 + m_xDistortionCoeffs[7] * lpx2 * lpy1 + m_xDistortionCoeffs[8] * lpx3 * lpy0 + m_xDistortionCoeffs[9] * lpx0 * lpy4 + m_xDistortionCoeffs[10] * lpx1 * lpy3 + m_xDistortionCoeffs[11] * lpx2 * lpy2 + m_xDistortionCoeffs[12] * lpx3 * lpy1 + m_xDistortionCoeffs[13] * lpx4 * lpy0 + m_xDistortionCoeffs[14] * lpx0 * lpy5 + m_xDistortionCoeffs[15] * lpx1 * lpy4 + m_xDistortionCoeffs[16] * lpx2 * lpy3 + m_xDistortionCoeffs[17] * lpx3 * lpy2 + m_xDistortionCoeffs[18] * lpx4 * lpy1 + m_xDistortionCoeffs[19] * lpx5 * lpy0; deltay = m_yDistortionCoeffs[0] * lpx0 * lpy1 + m_yDistortionCoeffs[1] * lpx1 * lpy0 + m_yDistortionCoeffs[2] * lpx0 * lpy2 + m_yDistortionCoeffs[3] * lpx1 * lpy1 + m_yDistortionCoeffs[4] * lpx2 * lpy0 + m_yDistortionCoeffs[5] * lpx0 * lpy3 + m_yDistortionCoeffs[6] * lpx1 * lpy2 + m_yDistortionCoeffs[7] * lpx2 * lpy1 + m_yDistortionCoeffs[8] * lpx3 * lpy0 + m_yDistortionCoeffs[9] * lpx0 * lpy4 + m_yDistortionCoeffs[10] * lpx1 * lpy3 + m_yDistortionCoeffs[11] * lpx2 * lpy2 + m_yDistortionCoeffs[12] * lpx3 * lpy1 + m_yDistortionCoeffs[13] * lpx4 * lpy0 + m_yDistortionCoeffs[14] * lpx0 * lpy5 + m_yDistortionCoeffs[15] * lpx1 * lpy4 + m_yDistortionCoeffs[16] * lpx2 * lpy3 + m_yDistortionCoeffs[17] * lpx3 * lpy2 + m_yDistortionCoeffs[18] * lpx4 * lpy1 + m_yDistortionCoeffs[19] * lpx5 * lpy0; return true; } }
34.704492
115
0.661717
[ "vector" ]
a64ac58c21ab8547bfb52620de5ebee69bf7a5ed
13,233
hpp
C++
src/thirdparty/stlsoft/STLSoft/include/inetstl/filesystem/ftpdir_sequence.hpp
nneesshh/servercore
8aceb7c9d5b26976469645a708b4ab804864c03f
[ "MIT" ]
null
null
null
src/thirdparty/stlsoft/STLSoft/include/inetstl/filesystem/ftpdir_sequence.hpp
nneesshh/servercore
8aceb7c9d5b26976469645a708b4ab804864c03f
[ "MIT" ]
null
null
null
src/thirdparty/stlsoft/STLSoft/include/inetstl/filesystem/ftpdir_sequence.hpp
nneesshh/servercore
8aceb7c9d5b26976469645a708b4ab804864c03f
[ "MIT" ]
2
2020-11-04T03:07:09.000Z
2020-11-05T08:14:45.000Z
/* ///////////////////////////////////////////////////////////////////////// * File: inetstl/filesystem/ftpdir_sequence.hpp * * Purpose: Contains the basic_ftpdir_sequence template class, and ANSI * and Unicode specialisations thereof. * * Created: 18th January 2006 * Updated: 19th February 2017 * * Home: http://stlsoft.org/ * * Copyright (c) 2006-2017, Matthew Wilson and Synesis Software * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * - Neither the name(s) of Matthew Wilson and Synesis Software nor the * names of any contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * ////////////////////////////////////////////////////////////////////// */ /** \file inetstl/filesystem/ftpdir_sequence.hpp * * \brief [C++ only] Definition of the inetstl::ftpdir_sequence * class template * (\ref group__library__FileSystem "File System" Library). */ #ifndef INETSTL_INCL_INETSTL_FILESYSTEM_HPP_FTPDIR_SEQUENCE #define INETSTL_INCL_INETSTL_FILESYSTEM_HPP_FTPDIR_SEQUENCE #ifndef STLSOFT_DOCUMENTATION_SKIP_SECTION # define INETSTL_VER_INETSTL_FILESYSTEM_HPP_FTPDIR_SEQUENCE_MAJOR 2 # define INETSTL_VER_INETSTL_FILESYSTEM_HPP_FTPDIR_SEQUENCE_MINOR 1 # define INETSTL_VER_INETSTL_FILESYSTEM_HPP_FTPDIR_SEQUENCE_REVISION 9 # define INETSTL_VER_INETSTL_FILESYSTEM_HPP_FTPDIR_SEQUENCE_EDIT 39 #endif /* !STLSOFT_DOCUMENTATION_SKIP_SECTION */ /* ///////////////////////////////////////////////////////////////////////// * compatibility */ /* [Incompatibilies-start] STLSOFT_COMPILER_IS_MSVC: _MSC_VER<1100 [Incompatibilies-end] */ /* ///////////////////////////////////////////////////////////////////////// * includes */ #ifndef INETSTL_INCL_INETSTL_H_INETSTL # include <inetstl/inetstl.h> #endif /* !INETSTL_INCL_INETSTL_H_INETSTL */ #ifdef STLSOFT_TRACE_INCLUDE # pragma message(__FILE__) #endif /* STLSOFT_TRACE_INCLUDE */ #ifndef INETSTL_OS_IS_WINDOWS # error This file is currently compatible only with the Win32/Win64 API #endif /* !INETSTL_OS_IS_WINDOWS */ #ifndef INETSTL_INCL_INETSTL_FILESYSTEM_HPP_FILESYSTEM_TRAITS # include <inetstl/filesystem/filesystem_traits.hpp> #endif /* !INETSTL_INCL_INETSTL_FILESYSTEM_HPP_FILESYSTEM_TRAITS */ #ifdef STLSOFT_CF_EXCEPTION_SUPPORT # ifndef INETSTL_INCL_INETSTL_EXCEPTION_HPP_THROW_POLICIES # include <inetstl/exception/throw_policies.hpp> // for throw_internet_exception_policy # endif /* !INETSTL_INCL_INETSTL_EXCEPTION_HPP_THROW_POLICIES */ #else /* ? STLSOFT_CF_EXCEPTION_SUPPORT */ # ifndef WINSTL_INCL_WINSTL_EXCEPTION_HPP_THROW_POLICIES # include <stlsoft/exception/throw_policies.hpp> // for stlsoft::null_exception_policy # endif /* !WINSTL_INCL_WINSTL_EXCEPTION_HPP_THROW_POLICIES */ #endif /* STLSOFT_CF_EXCEPTION_SUPPORT */ #ifndef INETSTL_INCL_INETSTL_FILESYSTEM_HPP_FINDFILE_SEQUENCE # include <inetstl/filesystem/findfile_sequence.hpp> #endif /* !INETSTL_INCL_INETSTL_FILESYSTEM_HPP_FINDFILE_SEQUENCE */ #ifndef STLSOFT_INCL_STLSOFT_COLLECTIONS_UTIL_HPP_COLLECTIONS # include <stlsoft/collections/util/collections.hpp> #endif /* !STLSOFT_INCL_STLSOFT_COLLECTIONS_UTIL_HPP_COLLECTIONS */ #ifndef STLSOFT_INCL_ALGORITHM # define STLSOFT_INCL_ALGORITHM # include <algorithm> #endif /* !STLSOFT_INCL_ALGORITHM */ #ifndef STLSOFT_INCL_ITERATOR # define STLSOFT_INCL_ITERATOR # include <iterator> #endif /* !STLSOFT_INCL_ITERATOR */ #ifndef STLSOFT_INCL_VECTOR # define STLSOFT_INCL_VECTOR # include <vector> #endif /* !STLSOFT_INCL_VECTOR */ /* ///////////////////////////////////////////////////////////////////////// * namespace */ #ifndef INETSTL_NO_NAMESPACE # if defined(STLSOFT_NO_NAMESPACE) || \ defined(STLSOFT_DOCUMENTATION_SKIP_SECTION) /* There is no stlsoft namespace, so must define ::inetstl */ namespace inetstl { # else /* Define stlsoft::inetstl_project */ namespace stlsoft { namespace inetstl_project { # endif /* STLSOFT_NO_NAMESPACE */ #endif /* !INETSTL_NO_NAMESPACE */ /* ///////////////////////////////////////////////////////////////////////// * classes */ /** STL collection of the files in an FTP directory matching a given pattern * * This class is described in detail in section 21.2 of * <a href="http://extendedstl.com/">Extended STL, volume 1</a>. */ template< ss_typename_param_k C #ifdef STLSOFT_CF_TEMPLATE_CLASS_DEFAULT_CLASS_ARGUMENT_SUPPORT # ifdef STLSOFT_CF_EXCEPTION_SUPPORT , ss_typename_param_k X = throw_internet_exception_policy # else /* ? STLSOFT_CF_EXCEPTION_SUPPORT */ , ss_typename_param_k X = STLSOFT_NS_QUAL(null_exception_policy) # endif /* STLSOFT_CF_EXCEPTION_SUPPORT */ , ss_typename_param_k T = filesystem_traits<C> #else /* ? STLSOFT_CF_TEMPLATE_CLASS_DEFAULT_CLASS_ARGUMENT_SUPPORT */ , ss_typename_param_k X /* = throw_internet_exception_policy */ , ss_typename_param_k T /* = filesystem_traits<C> */ #endif /* STLSOFT_CF_TEMPLATE_CLASS_DEFAULT_CLASS_ARGUMENT_SUPPORT */ > class basic_ftpdir_sequence : public STLSOFT_NS_QUAL(stl_collection_tag) { /// \name Member Types /// @{ private: typedef basic_findfile_sequence<C, T, X> sequence_type_; public: typedef ss_typename_type_k sequence_type_::char_type char_type; typedef ss_typename_type_k sequence_type_::value_type value_type; typedef ss_typename_type_k sequence_type_::size_type size_type; typedef ss_typename_type_k sequence_type_::bool_type bool_type; typedef is_sint_t flags_type; private: typedef STLSOFT_NS_QUAL_STD(vector)<value_type> values_type_; public: typedef ss_typename_type_k values_type_::const_reference const_reference; typedef ss_typename_type_k values_type_::const_iterator const_iterator; typedef ss_typename_type_k values_type_::const_reverse_iterator const_reverse_iterator; typedef basic_ftpdir_sequence<C, X, T> class_type; /// @} /// \name Member Constants /// @{ public: enum search_flags { includeDots = sequence_type_::includeDots , directories = sequence_type_::directories , files = sequence_type_::files #ifndef STLSOFT_DOCUMENTATION_SKIP_SECTION , noSort = sequence_type_::noSort #endif /* !STLSOFT_DOCUMENTATION_SKIP_SECTION */ }; /// @} /// \name Construction /// @{ public: basic_ftpdir_sequence( HINTERNET hconn , char_type const* pattern , flags_type flags = directories | files) { sequence_type_ ffs(hconn, pattern, flags); STLSOFT_NS_QUAL_STD(copy)(ffs.begin(), ffs.end(), STLSOFT_NS_QUAL_STD(back_inserter)(m_values)); } /// Commence a search according to the given search pattern and flags, relative to \c directory basic_ftpdir_sequence( HINTERNET hconn , char_type const* directory , char_type const* pattern , flags_type flags = directories | files) { sequence_type_ ffs(hconn, directory, pattern, flags); STLSOFT_NS_QUAL_STD(copy)(ffs.begin(), ffs.end(), STLSOFT_NS_QUAL_STD(back_inserter)(m_values)); } /// Commence a search according to the given search pattern and flags, relative to \c directory basic_ftpdir_sequence( HINTERNET hconn , char_type const* directory , char_type const* patterns , char_type delim , flags_type flags = directories | files) { sequence_type_ ffs(hconn, directory, patterns, delim, flags); STLSOFT_NS_QUAL_STD(copy)(ffs.begin(), ffs.end(), STLSOFT_NS_QUAL_STD(back_inserter)(m_values)); } #ifdef STLSOFT_DOCUMENTATION_SKIP_SECTION /// Constructs an instance of the sequence containing all the elements of the other basic_ftpdir_sequence(class_type const& rhs); /// Copies the contents of the given instance class_type& operator =(class_type const& rhs); #endif /* STLSOFT_DOCUMENTATION_SKIP_SECTION */ /// @} /// \name Element access /// @{ public: const_reference operator [](size_type index) const { INETSTL_MESSAGE_ASSERT("Invalid index", index < size()); return m_values[index]; } /// @} /// \name Iteration /// @{ public: const_iterator begin() const { return m_values.begin(); } const_iterator end() const { return m_values.end(); } const_reverse_iterator rbegin() const { return m_values.rbegin(); } const_reverse_iterator rend() const { return m_values.rend(); } /// @} /// \name Size /// @{ public: size_type size() const { return m_values.size(); } bool_type empty() const { return m_values.empty(); } /// @} /// \name Members /// @{ private: values_type_ m_values; /// @} }; /* ///////////////////////////////////////////////////////////////////////// * typedefs for commonly encountered types */ /** Specialisation of the basic_findfile_sequence template for the ANSI character type \c char * * */ typedef basic_ftpdir_sequence<is_char_a_t #ifdef STLSOFT_CF_EXCEPTION_SUPPORT , throw_internet_exception_policy #else /* ? STLSOFT_CF_EXCEPTION_SUPPORT */ , STLSOFT_NS_QUAL(null_exception_policy) #endif /* STLSOFT_CF_EXCEPTION_SUPPORT */ , filesystem_traits<is_char_a_t> > ftpdir_sequence_a; /** Specialisation of the basic_ftpdir_sequence template for the Unicode character type \c wchar_t * * \ingroup group__library__FileSystem */ typedef basic_ftpdir_sequence<is_char_w_t #ifdef STLSOFT_CF_EXCEPTION_SUPPORT , throw_internet_exception_policy #else /* ? STLSOFT_CF_EXCEPTION_SUPPORT */ , STLSOFT_NS_QUAL(null_exception_policy) #endif /* STLSOFT_CF_EXCEPTION_SUPPORT */ , filesystem_traits<is_char_w_t> > ftpdir_sequence_w; /** Specialisation of the basic_ftpdir_sequence template for the Win32 character type \c TCHAR * * \ingroup group__library__FileSystem */ typedef basic_ftpdir_sequence<TCHAR #ifdef STLSOFT_CF_EXCEPTION_SUPPORT , throw_internet_exception_policy #else /* ? STLSOFT_CF_EXCEPTION_SUPPORT */ , STLSOFT_NS_QUAL(null_exception_policy) #endif /* STLSOFT_CF_EXCEPTION_SUPPORT */ , filesystem_traits<TCHAR> > ftpdir_sequence; //////////////////////////////////////////////////////////////////////////// // Implementation #ifndef STLSOFT_DOCUMENTATION_SKIP_SECTION #endif /* !STLSOFT_DOCUMENTATION_SKIP_SECTION */ /* ////////////////////////////////////////////////////////////////////// */ #ifndef INETSTL_NO_NAMESPACE # if defined(STLSOFT_NO_NAMESPACE) || \ defined(STLSOFT_DOCUMENTATION_SKIP_SECTION) } /* namespace inetstl */ # else } /* namespace inetstl_project */ } /* namespace stlsoft */ # endif /* STLSOFT_NO_NAMESPACE */ #endif /* !INETSTL_NO_NAMESPACE */ /* ///////////////////////////////////////////////////////////////////////// * inclusion control */ #ifdef STLSOFT_CF_PRAGMA_ONCE_SUPPORT # pragma once #endif /* STLSOFT_CF_PRAGMA_ONCE_SUPPORT */ #endif /* !INETSTL_INCL_INETSTL_FILESYSTEM_HPP_FTPDIR_SEQUENCE */ /* ///////////////////////////// end of file //////////////////////////// */
36.860724
104
0.654198
[ "vector" ]
a64ad36e6e99223205b7f3c5143446dbc01bc2fb
11,039
cxx
C++
Base/QTCLI/qSlicerCLIProgressBar.cxx
TheInterventionCentre/NorMIT-Plan-App
765ed9a5dccc1cc134b65ccabe93fc132baeb2ea
[ "MIT" ]
null
null
null
Base/QTCLI/qSlicerCLIProgressBar.cxx
TheInterventionCentre/NorMIT-Plan-App
765ed9a5dccc1cc134b65ccabe93fc132baeb2ea
[ "MIT" ]
null
null
null
Base/QTCLI/qSlicerCLIProgressBar.cxx
TheInterventionCentre/NorMIT-Plan-App
765ed9a5dccc1cc134b65ccabe93fc132baeb2ea
[ "MIT" ]
null
null
null
/*============================================================================== Program: 3D Slicer Copyright (c) Kitware Inc. See COPYRIGHT.txt or http://www.slicer.org/copyright/copyright.txt for details. Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. This file was originally developed by Jean-Christophe Fillion-Robin, Kitware Inc. and was partially funded by NIH grant 3P41RR013218-12S1 ==============================================================================*/ // Qt includes #include <QApplication> #include <QDebug> #include <QFormLayout> #include <QGridLayout> #include <QLabel> #include <QProgressBar> // Slicer includes #include "qSlicerCLIProgressBar.h" // SlicerExecutionModel includes #include <ModuleDescription.h> #include <ModuleProcessInformation.h> // MRML includes #include <vtkMRMLCommandLineModuleNode.h> //----------------------------------------------------------------------------- // qSlicerCLIProgressBarPrivate methods //----------------------------------------------------------------------------- class qSlicerCLIProgressBarPrivate { Q_DECLARE_PUBLIC(qSlicerCLIProgressBar); protected: qSlicerCLIProgressBar* const q_ptr; public: typedef qSlicerCLIProgressBarPrivate Self; qSlicerCLIProgressBarPrivate(qSlicerCLIProgressBar& object); void init(); bool isVisible(qSlicerCLIProgressBar::Visibility visibility)const; private: QGridLayout * GridLayout; QLabel * NameLabel; QLabel * StatusLabelLabel; QLabel * StatusLabel; QProgressBar * ProgressBar; QProgressBar * StageProgressBar; vtkMRMLCommandLineModuleNode* CommandLineModuleNode; qSlicerCLIProgressBar::Visibility NameVisibility; qSlicerCLIProgressBar::Visibility StatusVisibility; qSlicerCLIProgressBar::Visibility ProgressVisibility; qSlicerCLIProgressBar::Visibility StageProgressVisibility; }; //----------------------------------------------------------------------------- // qSlicerCLIProgressBarPrivate methods //----------------------------------------------------------------------------- qSlicerCLIProgressBarPrivate::qSlicerCLIProgressBarPrivate(qSlicerCLIProgressBar& object) :q_ptr(&object) { this->CommandLineModuleNode = 0; this->NameVisibility = qSlicerCLIProgressBar::AlwaysHidden; this->StatusVisibility = qSlicerCLIProgressBar::AlwaysVisible; this->ProgressVisibility = qSlicerCLIProgressBar::VisibleAfterCompletion; this->StageProgressVisibility = qSlicerCLIProgressBar::HiddenWhenIdle; } //----------------------------------------------------------------------------- void qSlicerCLIProgressBarPrivate::init() { Q_Q(qSlicerCLIProgressBar); // Create widget .. layout this->GridLayout = new QGridLayout(this->q_ptr); this->GridLayout->setObjectName(QString::fromUtf8("gridLayout")); this->GridLayout->setContentsMargins(0,0,0,0); this->NameLabel = new QLabel(); this->NameLabel->setObjectName(QString::fromUtf8("NameLabel")); this->GridLayout->addWidget(NameLabel, 1, 0, 1, 1); this->StatusLabelLabel = new QLabel(); this->StatusLabelLabel->setObjectName(QString::fromUtf8("StatusLabelLabel")); QSizePolicy sizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred); sizePolicy.setHorizontalStretch(0); sizePolicy.setVerticalStretch(0); sizePolicy.setHeightForWidth(StatusLabelLabel->sizePolicy().hasHeightForWidth()); this->StatusLabelLabel->setSizePolicy(sizePolicy); this->StatusLabelLabel->setAlignment(Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter); this->GridLayout->addWidget(StatusLabelLabel, 1, 0, 1, 1); this->StatusLabel = new QLabel(); this->StatusLabel->setObjectName(QString::fromUtf8("StatusLabel")); this->GridLayout->addWidget(StatusLabel, 1, 1, 1, 1); this->ProgressBar = new QProgressBar(); this->ProgressBar->setObjectName(QString::fromUtf8("ProgressBar")); this->ProgressBar->setMaximum(100); this->ProgressBar->setValue(0); this->GridLayout->addWidget(ProgressBar, 2, 0, 1, 2); this->StageProgressBar = new QProgressBar(); this->StageProgressBar->setObjectName(QString::fromUtf8("StageProgressBar")); this->StageProgressBar->setValue(0); this->GridLayout->addWidget(StageProgressBar, 3, 0, 1, 2); this->NameLabel->setText(QObject::tr("")); this->StatusLabelLabel->setText(QObject::tr("Status:")); this->StatusLabel->setText(QObject::tr("Idle")); q->updateUiFromCommandLineModuleNode(this->CommandLineModuleNode); } //----------------------------------------------------------------------------- bool qSlicerCLIProgressBarPrivate ::isVisible(qSlicerCLIProgressBar::Visibility visibility)const { if (visibility == qSlicerCLIProgressBar::AlwaysHidden) { return false; } if (visibility == qSlicerCLIProgressBar::AlwaysVisible) { return true; } if (visibility == qSlicerCLIProgressBar::HiddenWhenIdle) { return this->CommandLineModuleNode ? this->CommandLineModuleNode->IsBusy() : false; } if (visibility == qSlicerCLIProgressBar::VisibleAfterCompletion) { return this->CommandLineModuleNode ? (this->CommandLineModuleNode->IsBusy() || this->CommandLineModuleNode->GetStatus() == vtkMRMLCommandLineModuleNode::Completed || this->CommandLineModuleNode->GetStatus() == vtkMRMLCommandLineModuleNode::CompletedWithErrors) : false; } return true; } //----------------------------------------------------------------------------- // qSlicerCLIProgressBar methods //----------------------------------------------------------------------------- qSlicerCLIProgressBar::qSlicerCLIProgressBar(QWidget* _parent) : Superclass(_parent) , d_ptr(new qSlicerCLIProgressBarPrivate(*this)) { Q_D(qSlicerCLIProgressBar); d->init(); } //----------------------------------------------------------------------------- qSlicerCLIProgressBar::~qSlicerCLIProgressBar() { } //----------------------------------------------------------------------------- vtkMRMLCommandLineModuleNode * qSlicerCLIProgressBar::commandLineModuleNode()const { Q_D(const qSlicerCLIProgressBar); return d->CommandLineModuleNode; } //----------------------------------------------------------------------------- qSlicerCLIProgressBar::Visibility qSlicerCLIProgressBar::nameVisibility()const { Q_D(const qSlicerCLIProgressBar); return d->NameVisibility; } //----------------------------------------------------------------------------- void qSlicerCLIProgressBar::setNameVisibility(qSlicerCLIProgressBar::Visibility visibility) { Q_D(qSlicerCLIProgressBar); if (visibility == d->NameVisibility) { return; } d->NameVisibility = visibility; this->updateUiFromCommandLineModuleNode(d->CommandLineModuleNode); } //----------------------------------------------------------------------------- qSlicerCLIProgressBar::Visibility qSlicerCLIProgressBar::statusVisibility()const { Q_D(const qSlicerCLIProgressBar); return d->StatusVisibility; } //----------------------------------------------------------------------------- void qSlicerCLIProgressBar::setStatusVisibility(qSlicerCLIProgressBar::Visibility visibility) { Q_D(qSlicerCLIProgressBar); if (visibility == d->StatusVisibility) { return; } d->StatusVisibility = visibility; this->updateUiFromCommandLineModuleNode(d->CommandLineModuleNode); } //----------------------------------------------------------------------------- qSlicerCLIProgressBar::Visibility qSlicerCLIProgressBar::progressVisibility()const { Q_D(const qSlicerCLIProgressBar); return d->ProgressVisibility; } //----------------------------------------------------------------------------- void qSlicerCLIProgressBar::setProgressVisibility(qSlicerCLIProgressBar::Visibility visibility) { Q_D(qSlicerCLIProgressBar); if (visibility == d->ProgressVisibility) { return; } d->ProgressVisibility = visibility; this->updateUiFromCommandLineModuleNode(d->CommandLineModuleNode); } //----------------------------------------------------------------------------- void qSlicerCLIProgressBar::setCommandLineModuleNode( vtkMRMLCommandLineModuleNode* commandLineModuleNode) { Q_D(qSlicerCLIProgressBar); if (commandLineModuleNode == d->CommandLineModuleNode) { return; } // Connect node modified event to updateUi that synchronize the values of the // nodes with the Ui this->qvtkReconnect(d->CommandLineModuleNode, commandLineModuleNode, vtkCommand::ModifiedEvent, this, SLOT(updateUiFromCommandLineModuleNode(vtkObject*))); d->CommandLineModuleNode = commandLineModuleNode; this->updateUiFromCommandLineModuleNode(d->CommandLineModuleNode); } //----------------------------------------------------------------------------- void qSlicerCLIProgressBar::updateUiFromCommandLineModuleNode( vtkObject* commandLineModuleNode) { Q_D(qSlicerCLIProgressBar); Q_ASSERT(commandLineModuleNode == d->CommandLineModuleNode); vtkMRMLCommandLineModuleNode * node = vtkMRMLCommandLineModuleNode::SafeDownCast(commandLineModuleNode); d->NameLabel->setVisible(d->isVisible(d->NameVisibility)); d->StatusLabelLabel->setVisible(d->isVisible(d->StatusVisibility)); d->StatusLabel->setVisible(d->isVisible(d->StatusVisibility)); d->ProgressBar->setVisible(d->isVisible(d->ProgressVisibility)); d->StageProgressBar->setVisible(d->isVisible(d->StageProgressVisibility)); if (!node) { d->StatusLabel->setText(""); d->ProgressBar->setMaximum(0); d->StageProgressBar->setMaximum(0); return; } // Update progress d->StatusLabel->setText(node->GetStatusString()); d->NameLabel->setText(node->GetName()); // Update Progress ModuleProcessInformation* info = node->GetModuleDescription().GetProcessInformation(); switch (node->GetStatus()) { case vtkMRMLCommandLineModuleNode::Cancelled: d->ProgressBar->setMaximum(0); break; case vtkMRMLCommandLineModuleNode::Scheduled: d->ProgressBar->setMaximum(0); break; case vtkMRMLCommandLineModuleNode::Running: d->ProgressBar->setMaximum(info->Progress != 0.0 ? 100 : 0); d->ProgressBar->setValue(info->Progress * 100.); if (info->ElapsedTime != 0.) { d->StatusLabel->setText(QString("%1 (%2)").arg(node->GetStatusString()).arg(info->ElapsedTime)); } d->StageProgressBar->setMaximum(info->StageProgress != 0.0 ? 100 : 0); d->StageProgressBar->setFormat(info->ProgressMessage); d->StageProgressBar->setValue(info->StageProgress * 100.); break; case vtkMRMLCommandLineModuleNode::Completed: case vtkMRMLCommandLineModuleNode::CompletedWithErrors: d->ProgressBar->setMaximum(100); d->ProgressBar->setValue(100); break; default: case vtkMRMLCommandLineModuleNode::Idle: break; } }
34.176471
110
0.648519
[ "object", "3d" ]
a658976824c0404ca00f274b63c953f2deca0aa8
2,085
cpp
C++
cppcore/tests/test_detail.cpp
lise1020/pybinding
921d5c2ac0ecc0ef317ba28b0bf68899ea30709a
[ "BSD-2-Clause" ]
159
2016-01-20T17:40:48.000Z
2022-03-24T06:08:55.000Z
cppcore/tests/test_detail.cpp
deilynazar/pybinding
ec1128aaa84a1b43a74fb970479ce4544bd63179
[ "BSD-2-Clause" ]
36
2016-11-01T17:15:12.000Z
2022-03-08T14:31:51.000Z
cppcore/tests/test_detail.cpp
deilynazar/pybinding
ec1128aaa84a1b43a74fb970479ce4544bd63179
[ "BSD-2-Clause" ]
57
2016-04-23T22:12:01.000Z
2022-03-08T12:33:04.000Z
#include <catch.hpp> #include <complex> #include "Model.hpp" #include "detail/algorithm.hpp" using namespace cpb; namespace static_test_typelist { using List = TypeList<float, double, std::complex<float>, std::complex<double>>; static_assert(tl::AnyOf<List, float>::value, ""); static_assert(!tl::AnyOf<List, int>::value, ""); } TEST_CASE("Symmetry masks") { SECTION("1") { auto const masks = detail::make_masks({true, false, false}, 1); REQUIRE_THAT(masks, Catch::Equals(std::vector<Index3D>{{0, 0, 0}, {1, 0, 0}})); } SECTION("2-1") { auto const masks = detail::make_masks({false, true, false}, 2); REQUIRE_THAT(masks, Catch::Equals(std::vector<Index3D>{{0, 0, 0}, {0, 1, 0}})); } SECTION("2-2") { auto const masks = detail::make_masks({true, true, false}, 2); REQUIRE_THAT(masks, Catch::Equals(std::vector<Index3D>{ {0, 0, 0}, {0, 1, 0}, {1, 0, 0}, {1, 1, 0} })); } SECTION("3") { auto const masks = detail::make_masks({true, true, true}, 3); REQUIRE_THAT(masks, Catch::Equals(std::vector<Index3D>{ {0, 0, 0}, {0, 0, 1}, {0, 1, 0}, {0, 1, 1}, {1, 0, 0}, {1, 0, 1}, {1, 1, 0}, {1, 1, 1} })); } } TEST_CASE("sliced") { auto const v = []{ auto result = std::vector<int>(10); std::iota(result.begin(), result.end(), 0); return result; }(); REQUIRE_THAT(v, Catch::Equals(std::vector<int>{0, 1, 2, 3, 4, 5, 6, 7, 8, 9})); auto vectors = std::vector<std::vector<int>>(); for (auto const& slice : sliced(v, 3)) { auto tmp = std::vector<int>(); std::copy(slice.begin(), slice.end(), std::back_inserter(tmp)); vectors.push_back(tmp); } REQUIRE(vectors.size() == 4); REQUIRE_THAT(vectors[0], Catch::Equals(std::vector<int>{0, 1, 2})); REQUIRE_THAT(vectors[1], Catch::Equals(std::vector<int>{3, 4, 5})); REQUIRE_THAT(vectors[2], Catch::Equals(std::vector<int>{6, 7, 8})); REQUIRE_THAT(vectors[3], Catch::Equals(std::vector<int>{9})); }
35.338983
87
0.56211
[ "vector", "model" ]
a658b58d2ef0d10ff4fcfa8e2d160cc8c9c7c566
1,187
cpp
C++
src/eigen.cpp
fritzo/kazoo
7281fe382b98ec81a0e223bfc76c49749543afdb
[ "MIT" ]
3
2015-04-29T11:38:29.000Z
2018-08-31T01:32:13.000Z
src/eigen.cpp
fritzo/kazoo
7281fe382b98ec81a0e223bfc76c49749543afdb
[ "MIT" ]
null
null
null
src/eigen.cpp
fritzo/kazoo
7281fe382b98ec81a0e223bfc76c49749543afdb
[ "MIT" ]
null
null
null
#include "eigen.h" #include <fstream> #define EIGEN_YES_I_KNOW_SPARSE_MODULE_IS_NOT_STABLE_YET #include <Eigen/Eigen> #include <Eigen/Sparse> Vector<float> as_vector (const VectorXf & x) { return Vector<float>(x.size(), const_cast<float *>(x.data())); } Vector<float> as_vector (const MatrixXf & x) { return Vector<float>(x.size(), const_cast<float *>(x.data())); } Vector<double> as_vector (const VectorXd & x) { return Vector<double>(x.size(), const_cast<double *>(x.data())); } Vector<double> as_vector (const MatrixXd & x) { return Vector<double>(x.size(), const_cast<double *>(x.data())); } void write_to_python (const VectorXf & x, ostream & os) { const int entries_per_line = 8; os << "["; for (int i = 0; i < x.size(); ++i) { os << x[i] << ", "; if ((i + 1) % entries_per_line == 0) os << "\n "; } os << "]"; } void save_to_python (const MatrixXf & A, string filename) { LOG("saving MatrixXf to " << filename); std::ofstream file(filename); file << "["; for (int i = 0; i < A.rows(); ++i) { file << "\n ["; for (int j = 0; j < A.cols(); ++j) { file << A(i,j) << ", "; } file << "],"; } file << "\n]\n"; }
20.465517
66
0.582982
[ "vector" ]
a65e3a12b0a97ec6acb70c4b7ede349bf8d24202
38,100
cpp
C++
shared/ebm_native/ApplyModelUpdateTraining.cpp
ashishpatel26/interpret
c7cff5ca8f31b78e0435e90526fa7cd16f9b1a6a
[ "MIT" ]
null
null
null
shared/ebm_native/ApplyModelUpdateTraining.cpp
ashishpatel26/interpret
c7cff5ca8f31b78e0435e90526fa7cd16f9b1a6a
[ "MIT" ]
null
null
null
shared/ebm_native/ApplyModelUpdateTraining.cpp
ashishpatel26/interpret
c7cff5ca8f31b78e0435e90526fa7cd16f9b1a6a
[ "MIT" ]
1
2021-01-05T15:56:30.000Z
2021-01-05T15:56:30.000Z
// Copyright (c) 2018 Microsoft Corporation // Licensed under the MIT license. // Author: Paul Koch <ebm@koch.ninja> #include "PrecompiledHeader.h" #include <stddef.h> // size_t, ptrdiff_t #include "ebm_native.h" #include "EbmInternal.h" // very independent includes #include "Logging.h" // EBM_ASSERT & LOG #include "ApproximateMath.h" #include "EbmStatisticUtils.h" // FeatureGroup.h depends on FeatureInternal.h #include "FeatureGroup.h" // dataset depends on features #include "DataSetBoosting.h" #include "Booster.h" // C++ does not allow partial function specialization, so we need to use these cumbersome static class functions to do partial function specialization template<ptrdiff_t compilerLearningTypeOrCountTargetClasses> class ApplyModelUpdateTrainingZeroFeatures final { public: ApplyModelUpdateTrainingZeroFeatures() = delete; // this is a static class. Do not construct static void Func( EbmBoostingState * const pEbmBoostingState, const FloatEbmType * const aModelFeatureGroupUpdateTensor ) { static_assert(IsClassification(compilerLearningTypeOrCountTargetClasses), "must be classification"); static_assert(!IsBinaryClassification(compilerLearningTypeOrCountTargetClasses), "must be multiclass"); const ptrdiff_t runtimeLearningTypeOrCountTargetClasses = pEbmBoostingState->GetRuntimeLearningTypeOrCountTargetClasses(); DataSetByFeatureGroup * const pTrainingSet = pEbmBoostingState->GetTrainingSet(); FloatEbmType * const aTempFloatVector = pEbmBoostingState->GetCachedThreadResources()->GetTempFloatVector(); FloatEbmType aLocalExpVector[ k_dynamicClassification == compilerLearningTypeOrCountTargetClasses ? 1 : GetVectorLength(compilerLearningTypeOrCountTargetClasses) ]; FloatEbmType * const aExpVector = k_dynamicClassification == compilerLearningTypeOrCountTargetClasses ? aTempFloatVector : aLocalExpVector; const ptrdiff_t learningTypeOrCountTargetClasses = GET_LEARNING_TYPE_OR_COUNT_TARGET_CLASSES( compilerLearningTypeOrCountTargetClasses, runtimeLearningTypeOrCountTargetClasses ); const size_t cVectorLength = GetVectorLength(learningTypeOrCountTargetClasses); const size_t cSamples = pTrainingSet->GetCountSamples(); EBM_ASSERT(0 < cSamples); FloatEbmType * pResidualError = pTrainingSet->GetResidualPointer(); const StorageDataType * pTargetData = pTrainingSet->GetTargetDataPointer(); FloatEbmType * pPredictorScores = pTrainingSet->GetPredictorScores(); const FloatEbmType * const pPredictorScoresEnd = pPredictorScores + cSamples * cVectorLength; do { size_t targetData = static_cast<size_t>(*pTargetData); ++pTargetData; const FloatEbmType * pValues = aModelFeatureGroupUpdateTensor; FloatEbmType * pExpVector = aExpVector; FloatEbmType sumExp = FloatEbmType { 0 }; size_t iVector = 0; do { // TODO : because there is only one bin for a zero feature feature group, we could move these values to the stack where the // compiler could reason about their visibility and optimize small arrays into registers const FloatEbmType smallChangeToPredictorScores = *pValues; ++pValues; // this will apply a small fix to our existing TrainingPredictorScores, either positive or negative, whichever is needed const FloatEbmType predictorScore = *pPredictorScores + smallChangeToPredictorScores; *pPredictorScores = predictorScore; ++pPredictorScores; const FloatEbmType oneExp = ExpForResiduals(predictorScore); *pExpVector = oneExp; ++pExpVector; sumExp += oneExp; ++iVector; } while(iVector < cVectorLength); pExpVector -= cVectorLength; iVector = 0; do { const FloatEbmType residualError = EbmStatistics::ComputeResidualErrorMulticlass( sumExp, *pExpVector, targetData, iVector ); ++pExpVector; *pResidualError = residualError; ++pResidualError; ++iVector; } while(iVector < cVectorLength); // TODO: this works as a way to remove one parameter, but it obviously insn't as efficient as omitting the parameter // // this works out in the math as making the first model vector parameter equal to zero, which in turn removes one degree of freedom // from the model vector parameters. Since the model vector weights need to be normalized to sum to a probabilty of 100%, we can set the first // one to the constant 1 (0 in log space) and force the other parameters to adjust to that scale which fixes them to a single valid set of // values insted of allowing them to be scaled. // Probability = exp(T1 + I1) / [exp(T1 + I1) + exp(T2 + I2) + exp(T3 + I3)] => we can add a constant inside each exp(..) term, which // will be multiplication outside the exp(..), which means the numerator and denominator are multiplied by the same constant, which cancels // eachother out. We can thus set exp(T2 + I2) to exp(0) and adjust the other terms constexpr bool bZeroingResiduals = 0 <= k_iZeroResidual; if(bZeroingResiduals) { *(pResidualError - (static_cast<ptrdiff_t>(cVectorLength) - k_iZeroResidual)) = 0; } } while(pPredictorScoresEnd != pPredictorScores); } }; #ifndef EXPAND_BINARY_LOGITS template<> class ApplyModelUpdateTrainingZeroFeatures<2> final { public: ApplyModelUpdateTrainingZeroFeatures() = delete; // this is a static class. Do not construct static void Func( EbmBoostingState * const pEbmBoostingState, const FloatEbmType * const aModelFeatureGroupUpdateTensor ) { DataSetByFeatureGroup * const pTrainingSet = pEbmBoostingState->GetTrainingSet(); const size_t cSamples = pTrainingSet->GetCountSamples(); EBM_ASSERT(0 < cSamples); FloatEbmType * pResidualError = pTrainingSet->GetResidualPointer(); const StorageDataType * pTargetData = pTrainingSet->GetTargetDataPointer(); FloatEbmType * pPredictorScores = pTrainingSet->GetPredictorScores(); const FloatEbmType * const pPredictorScoresEnd = pPredictorScores + cSamples; const FloatEbmType smallChangeToPredictorScores = aModelFeatureGroupUpdateTensor[0]; do { size_t targetData = static_cast<size_t>(*pTargetData); ++pTargetData; // this will apply a small fix to our existing TrainingPredictorScores, either positive or negative, whichever is needed const FloatEbmType predictorScore = *pPredictorScores + smallChangeToPredictorScores; *pPredictorScores = predictorScore; ++pPredictorScores; const FloatEbmType residualError = EbmStatistics::ComputeResidualErrorBinaryClassification(predictorScore, targetData); *pResidualError = residualError; ++pResidualError; } while(pPredictorScoresEnd != pPredictorScores); } }; #endif // EXPAND_BINARY_LOGITS template<> class ApplyModelUpdateTrainingZeroFeatures<k_regression> final { public: ApplyModelUpdateTrainingZeroFeatures() = delete; // this is a static class. Do not construct static void Func( EbmBoostingState * const pEbmBoostingState, const FloatEbmType * const aModelFeatureGroupUpdateTensor ) { DataSetByFeatureGroup * const pTrainingSet = pEbmBoostingState->GetTrainingSet(); const size_t cSamples = pTrainingSet->GetCountSamples(); EBM_ASSERT(0 < cSamples); FloatEbmType * pResidualError = pTrainingSet->GetResidualPointer(); const FloatEbmType * const pResidualErrorEnd = pResidualError + cSamples; const FloatEbmType smallChangeToPrediction = aModelFeatureGroupUpdateTensor[0]; do { // this will apply a small fix to our existing TrainingPredictorScores, either positive or negative, whichever is needed const FloatEbmType residualError = EbmStatistics::ComputeResidualErrorRegression(*pResidualError - smallChangeToPrediction); *pResidualError = residualError; ++pResidualError; } while(pResidualErrorEnd != pResidualError); } }; template<ptrdiff_t compilerLearningTypeOrCountTargetClassesPossible> class ApplyModelUpdateTrainingZeroFeaturesTarget final { public: ApplyModelUpdateTrainingZeroFeaturesTarget() = delete; // this is a static class. Do not construct INLINE_ALWAYS static void Func( EbmBoostingState * const pEbmBoostingState, const FloatEbmType * const aModelFeatureGroupUpdateTensor ) { static_assert(IsClassification(compilerLearningTypeOrCountTargetClassesPossible), "compilerLearningTypeOrCountTargetClassesPossible needs to be a classification"); static_assert(compilerLearningTypeOrCountTargetClassesPossible <= k_cCompilerOptimizedTargetClassesMax, "We can't have this many items in a data pack."); const ptrdiff_t runtimeLearningTypeOrCountTargetClasses = pEbmBoostingState->GetRuntimeLearningTypeOrCountTargetClasses(); EBM_ASSERT(IsClassification(runtimeLearningTypeOrCountTargetClasses)); EBM_ASSERT(runtimeLearningTypeOrCountTargetClasses <= k_cCompilerOptimizedTargetClassesMax); if(compilerLearningTypeOrCountTargetClassesPossible == runtimeLearningTypeOrCountTargetClasses) { ApplyModelUpdateTrainingZeroFeatures<compilerLearningTypeOrCountTargetClassesPossible>::Func( pEbmBoostingState, aModelFeatureGroupUpdateTensor ); } else { ApplyModelUpdateTrainingZeroFeaturesTarget< compilerLearningTypeOrCountTargetClassesPossible + 1 >::Func( pEbmBoostingState, aModelFeatureGroupUpdateTensor ); } } }; template<> class ApplyModelUpdateTrainingZeroFeaturesTarget<k_cCompilerOptimizedTargetClassesMax + 1> final { public: ApplyModelUpdateTrainingZeroFeaturesTarget() = delete; // this is a static class. Do not construct INLINE_ALWAYS static void Func( EbmBoostingState * const pEbmBoostingState, const FloatEbmType * const aModelFeatureGroupUpdateTensor ) { static_assert(IsClassification(k_cCompilerOptimizedTargetClassesMax), "k_cCompilerOptimizedTargetClassesMax needs to be a classification"); EBM_ASSERT(IsClassification(pEbmBoostingState->GetRuntimeLearningTypeOrCountTargetClasses())); EBM_ASSERT(k_cCompilerOptimizedTargetClassesMax < pEbmBoostingState->GetRuntimeLearningTypeOrCountTargetClasses()); ApplyModelUpdateTrainingZeroFeatures<k_dynamicClassification>::Func( pEbmBoostingState, aModelFeatureGroupUpdateTensor ); } }; template<ptrdiff_t compilerLearningTypeOrCountTargetClasses, size_t compilerCountItemsPerBitPackedDataUnit> class ApplyModelUpdateTrainingInternal final { public: ApplyModelUpdateTrainingInternal() = delete; // this is a static class. Do not construct static void Func( EbmBoostingState * const pEbmBoostingState, const FeatureGroup * const pFeatureGroup, const FloatEbmType * const aModelFeatureGroupUpdateTensor ) { static_assert(IsClassification(compilerLearningTypeOrCountTargetClasses), "must be classification"); static_assert(!IsBinaryClassification(compilerLearningTypeOrCountTargetClasses), "must be multiclass"); const ptrdiff_t runtimeLearningTypeOrCountTargetClasses = pEbmBoostingState->GetRuntimeLearningTypeOrCountTargetClasses(); DataSetByFeatureGroup * const pTrainingSet = pEbmBoostingState->GetTrainingSet(); FloatEbmType * const aTempFloatVector = pEbmBoostingState->GetCachedThreadResources()->GetTempFloatVector(); FloatEbmType aLocalExpVector[ k_dynamicClassification == compilerLearningTypeOrCountTargetClasses ? 1 : GetVectorLength(compilerLearningTypeOrCountTargetClasses) ]; FloatEbmType * const aExpVector = k_dynamicClassification == compilerLearningTypeOrCountTargetClasses ? aTempFloatVector : aLocalExpVector; const ptrdiff_t learningTypeOrCountTargetClasses = GET_LEARNING_TYPE_OR_COUNT_TARGET_CLASSES( compilerLearningTypeOrCountTargetClasses, runtimeLearningTypeOrCountTargetClasses ); const size_t cVectorLength = GetVectorLength(learningTypeOrCountTargetClasses); const size_t cSamples = pTrainingSet->GetCountSamples(); EBM_ASSERT(0 < cSamples); EBM_ASSERT(0 < pFeatureGroup->GetCountFeatures()); const size_t cItemsPerBitPackedDataUnit = GET_COUNT_ITEMS_PER_BIT_PACKED_DATA_UNIT( compilerCountItemsPerBitPackedDataUnit, pFeatureGroup->GetCountItemsPerBitPackedDataUnit() ); EBM_ASSERT(1 <= cItemsPerBitPackedDataUnit); EBM_ASSERT(cItemsPerBitPackedDataUnit <= k_cBitsForStorageType); const size_t cBitsPerItemMax = GetCountBits(cItemsPerBitPackedDataUnit); EBM_ASSERT(1 <= cBitsPerItemMax); EBM_ASSERT(cBitsPerItemMax <= k_cBitsForStorageType); const size_t maskBits = std::numeric_limits<size_t>::max() >> (k_cBitsForStorageType - cBitsPerItemMax); FloatEbmType * pResidualError = pTrainingSet->GetResidualPointer(); const StorageDataType * pInputData = pTrainingSet->GetInputDataPointer(pFeatureGroup); const StorageDataType * pTargetData = pTrainingSet->GetTargetDataPointer(); FloatEbmType * pPredictorScores = pTrainingSet->GetPredictorScores(); // this shouldn't overflow since we're accessing existing memory const FloatEbmType * const pPredictorScoresTrueEnd = pPredictorScores + cSamples * cVectorLength; const FloatEbmType * pPredictorScoresExit = pPredictorScoresTrueEnd; const FloatEbmType * pPredictorScoresInnerEnd = pPredictorScoresTrueEnd; if(cSamples <= cItemsPerBitPackedDataUnit) { goto one_last_loop; } pPredictorScoresExit = pPredictorScoresTrueEnd - ((cSamples - 1) % cItemsPerBitPackedDataUnit + 1) * cVectorLength; EBM_ASSERT(pPredictorScores < pPredictorScoresExit); EBM_ASSERT(pPredictorScoresExit < pPredictorScoresTrueEnd); do { pPredictorScoresInnerEnd = pPredictorScores + cItemsPerBitPackedDataUnit * cVectorLength; // jumping back into this loop and changing pPredictorScoresInnerEnd to a dynamic value that isn't compile time determinable causes this // function to NOT be optimized for templated cItemsPerBitPackedDataUnit, but that's ok since avoiding one unpredictable branch here is negligible one_last_loop:; // we store the already multiplied dimensional value in *pInputData size_t iTensorBinCombined = static_cast<size_t>(*pInputData); ++pInputData; do { size_t targetData = static_cast<size_t>(*pTargetData); ++pTargetData; const size_t iTensorBin = maskBits & iTensorBinCombined; const FloatEbmType * pValues = &aModelFeatureGroupUpdateTensor[iTensorBin * cVectorLength]; FloatEbmType * pExpVector = aExpVector; FloatEbmType sumExp = FloatEbmType { 0 }; size_t iVector = 0; do { const FloatEbmType smallChangeToPredictorScores = *pValues; ++pValues; // this will apply a small fix to our existing TrainingPredictorScores, either positive or negative, whichever is needed const FloatEbmType predictorScore = *pPredictorScores + smallChangeToPredictorScores; *pPredictorScores = predictorScore; ++pPredictorScores; const FloatEbmType oneExp = ExpForResiduals(predictorScore); *pExpVector = oneExp; ++pExpVector; sumExp += oneExp; ++iVector; } while(iVector < cVectorLength); pExpVector -= cVectorLength; iVector = 0; do { const FloatEbmType residualError = EbmStatistics::ComputeResidualErrorMulticlass( sumExp, *pExpVector, targetData, iVector ); ++pExpVector; *pResidualError = residualError; ++pResidualError; ++iVector; } while(iVector < cVectorLength); // TODO: this works as a way to remove one parameter, but it obviously insn't as efficient as omitting the parameter // // this works out in the math as making the first model vector parameter equal to zero, which in turn removes one degree of freedom // from the model vector parameters. Since the model vector weights need to be normalized to sum to a probabilty of 100%, we can set the // first one to the constant 1 (0 in log space) and force the other parameters to adjust to that scale which fixes them to a single valid // set of values insted of allowing them to be scaled. // Probability = exp(T1 + I1) / [exp(T1 + I1) + exp(T2 + I2) + exp(T3 + I3)] => we can add a constant inside each exp(..) term, which // will be multiplication outside the exp(..), which means the numerator and denominator are multiplied by the same constant, which // cancels eachother out. We can thus set exp(T2 + I2) to exp(0) and adjust the other terms constexpr bool bZeroingResiduals = 0 <= k_iZeroResidual; if(bZeroingResiduals) { *(pResidualError - (static_cast<ptrdiff_t>(cVectorLength) - k_iZeroResidual)) = 0; } iTensorBinCombined >>= cBitsPerItemMax; } while(pPredictorScoresInnerEnd != pPredictorScores); } while(pPredictorScoresExit != pPredictorScores); // first time through? if(pPredictorScoresTrueEnd != pPredictorScores) { pPredictorScoresInnerEnd = pPredictorScoresTrueEnd; pPredictorScoresExit = pPredictorScoresTrueEnd; goto one_last_loop; } } }; #ifndef EXPAND_BINARY_LOGITS template<size_t compilerCountItemsPerBitPackedDataUnit> class ApplyModelUpdateTrainingInternal<2, compilerCountItemsPerBitPackedDataUnit> final { public: ApplyModelUpdateTrainingInternal() = delete; // this is a static class. Do not construct static void Func( EbmBoostingState * const pEbmBoostingState, const FeatureGroup * const pFeatureGroup, const FloatEbmType * const aModelFeatureGroupUpdateTensor ) { const size_t runtimeCountItemsPerBitPackedDataUnit = pFeatureGroup->GetCountItemsPerBitPackedDataUnit(); DataSetByFeatureGroup * const pTrainingSet = pEbmBoostingState->GetTrainingSet(); const size_t cSamples = pTrainingSet->GetCountSamples(); EBM_ASSERT(0 < cSamples); EBM_ASSERT(0 < pFeatureGroup->GetCountFeatures()); const size_t cItemsPerBitPackedDataUnit = GET_COUNT_ITEMS_PER_BIT_PACKED_DATA_UNIT( compilerCountItemsPerBitPackedDataUnit, runtimeCountItemsPerBitPackedDataUnit ); EBM_ASSERT(1 <= cItemsPerBitPackedDataUnit); EBM_ASSERT(cItemsPerBitPackedDataUnit <= k_cBitsForStorageType); const size_t cBitsPerItemMax = GetCountBits(cItemsPerBitPackedDataUnit); EBM_ASSERT(1 <= cBitsPerItemMax); EBM_ASSERT(cBitsPerItemMax <= k_cBitsForStorageType); const size_t maskBits = std::numeric_limits<size_t>::max() >> (k_cBitsForStorageType - cBitsPerItemMax); FloatEbmType * pResidualError = pTrainingSet->GetResidualPointer(); const StorageDataType * pInputData = pTrainingSet->GetInputDataPointer(pFeatureGroup); const StorageDataType * pTargetData = pTrainingSet->GetTargetDataPointer(); FloatEbmType * pPredictorScores = pTrainingSet->GetPredictorScores(); // this shouldn't overflow since we're accessing existing memory const FloatEbmType * const pPredictorScoresTrueEnd = pPredictorScores + cSamples; const FloatEbmType * pPredictorScoresExit = pPredictorScoresTrueEnd; const FloatEbmType * pPredictorScoresInnerEnd = pPredictorScoresTrueEnd; if(cSamples <= cItemsPerBitPackedDataUnit) { goto one_last_loop; } pPredictorScoresExit = pPredictorScoresTrueEnd - ((cSamples - 1) % cItemsPerBitPackedDataUnit + 1); EBM_ASSERT(pPredictorScores < pPredictorScoresExit); EBM_ASSERT(pPredictorScoresExit < pPredictorScoresTrueEnd); do { pPredictorScoresInnerEnd = pPredictorScores + cItemsPerBitPackedDataUnit; // jumping back into this loop and changing pPredictorScoresInnerEnd to a dynamic value that isn't compile time determinable causes this // function to NOT be optimized for templated cItemsPerBitPackedDataUnit, but that's ok since avoiding one unpredictable branch here is negligible one_last_loop:; // we store the already multiplied dimensional value in *pInputData size_t iTensorBinCombined = static_cast<size_t>(*pInputData); ++pInputData; do { size_t targetData = static_cast<size_t>(*pTargetData); ++pTargetData; const size_t iTensorBin = maskBits & iTensorBinCombined; const FloatEbmType smallChangeToPredictorScores = aModelFeatureGroupUpdateTensor[iTensorBin]; // this will apply a small fix to our existing TrainingPredictorScores, either positive or negative, whichever is needed const FloatEbmType predictorScore = *pPredictorScores + smallChangeToPredictorScores; *pPredictorScores = predictorScore; ++pPredictorScores; const FloatEbmType residualError = EbmStatistics::ComputeResidualErrorBinaryClassification(predictorScore, targetData); *pResidualError = residualError; ++pResidualError; iTensorBinCombined >>= cBitsPerItemMax; } while(pPredictorScoresInnerEnd != pPredictorScores); } while(pPredictorScoresExit != pPredictorScores); // first time through? if(pPredictorScoresTrueEnd != pPredictorScores) { pPredictorScoresInnerEnd = pPredictorScoresTrueEnd; pPredictorScoresExit = pPredictorScoresTrueEnd; goto one_last_loop; } } }; #endif // EXPAND_BINARY_LOGITS template<size_t compilerCountItemsPerBitPackedDataUnit> class ApplyModelUpdateTrainingInternal<k_regression, compilerCountItemsPerBitPackedDataUnit> final { public: ApplyModelUpdateTrainingInternal() = delete; // this is a static class. Do not construct static void Func( EbmBoostingState * const pEbmBoostingState, const FeatureGroup * const pFeatureGroup, const FloatEbmType * const aModelFeatureGroupUpdateTensor ) { const size_t runtimeCountItemsPerBitPackedDataUnit = pFeatureGroup->GetCountItemsPerBitPackedDataUnit(); DataSetByFeatureGroup * const pTrainingSet = pEbmBoostingState->GetTrainingSet(); const size_t cSamples = pTrainingSet->GetCountSamples(); EBM_ASSERT(0 < cSamples); EBM_ASSERT(0 < pFeatureGroup->GetCountFeatures()); const size_t cItemsPerBitPackedDataUnit = GET_COUNT_ITEMS_PER_BIT_PACKED_DATA_UNIT( compilerCountItemsPerBitPackedDataUnit, runtimeCountItemsPerBitPackedDataUnit ); EBM_ASSERT(1 <= cItemsPerBitPackedDataUnit); EBM_ASSERT(cItemsPerBitPackedDataUnit <= k_cBitsForStorageType); const size_t cBitsPerItemMax = GetCountBits(cItemsPerBitPackedDataUnit); EBM_ASSERT(1 <= cBitsPerItemMax); EBM_ASSERT(cBitsPerItemMax <= k_cBitsForStorageType); const size_t maskBits = std::numeric_limits<size_t>::max() >> (k_cBitsForStorageType - cBitsPerItemMax); FloatEbmType * pResidualError = pTrainingSet->GetResidualPointer(); const StorageDataType * pInputData = pTrainingSet->GetInputDataPointer(pFeatureGroup); // this shouldn't overflow since we're accessing existing memory const FloatEbmType * const pResidualErrorTrueEnd = pResidualError + cSamples; const FloatEbmType * pResidualErrorExit = pResidualErrorTrueEnd; const FloatEbmType * pResidualErrorInnerEnd = pResidualErrorTrueEnd; if(cSamples <= cItemsPerBitPackedDataUnit) { goto one_last_loop; } pResidualErrorExit = pResidualErrorTrueEnd - ((cSamples - 1) % cItemsPerBitPackedDataUnit + 1); EBM_ASSERT(pResidualError < pResidualErrorExit); EBM_ASSERT(pResidualErrorExit < pResidualErrorTrueEnd); do { pResidualErrorInnerEnd = pResidualError + cItemsPerBitPackedDataUnit; // jumping back into this loop and changing pPredictorScoresInnerEnd to a dynamic value that isn't compile time determinable causes this // function to NOT be optimized for templated cItemsPerBitPackedDataUnit, but that's ok since avoiding one unpredictable branch here is negligible one_last_loop:; // we store the already multiplied dimensional value in *pInputData size_t iTensorBinCombined = static_cast<size_t>(*pInputData); ++pInputData; do { const size_t iTensorBin = maskBits & iTensorBinCombined; const FloatEbmType smallChangeToPrediction = aModelFeatureGroupUpdateTensor[iTensorBin]; // this will apply a small fix to our existing TrainingPredictorScores, either positive or negative, whichever is needed const FloatEbmType residualError = EbmStatistics::ComputeResidualErrorRegression(*pResidualError - smallChangeToPrediction); *pResidualError = residualError; ++pResidualError; iTensorBinCombined >>= cBitsPerItemMax; } while(pResidualErrorInnerEnd != pResidualError); } while(pResidualErrorExit != pResidualError); // first time through? if(pResidualErrorTrueEnd != pResidualError) { pResidualErrorInnerEnd = pResidualErrorTrueEnd; pResidualErrorExit = pResidualErrorTrueEnd; goto one_last_loop; } } }; template<ptrdiff_t compilerLearningTypeOrCountTargetClassesPossible> class ApplyModelUpdateTrainingNormalTarget final { public: ApplyModelUpdateTrainingNormalTarget() = delete; // this is a static class. Do not construct INLINE_ALWAYS static void Func( EbmBoostingState * const pEbmBoostingState, const FeatureGroup * const pFeatureGroup, const FloatEbmType * const aModelFeatureGroupUpdateTensor ) { static_assert(IsClassification(compilerLearningTypeOrCountTargetClassesPossible), "compilerLearningTypeOrCountTargetClassesPossible needs to be a classification"); static_assert(compilerLearningTypeOrCountTargetClassesPossible <= k_cCompilerOptimizedTargetClassesMax, "We can't have this many items in a data pack."); const ptrdiff_t runtimeLearningTypeOrCountTargetClasses = pEbmBoostingState->GetRuntimeLearningTypeOrCountTargetClasses(); EBM_ASSERT(IsClassification(runtimeLearningTypeOrCountTargetClasses)); EBM_ASSERT(runtimeLearningTypeOrCountTargetClasses <= k_cCompilerOptimizedTargetClassesMax); if(compilerLearningTypeOrCountTargetClassesPossible == runtimeLearningTypeOrCountTargetClasses) { ApplyModelUpdateTrainingInternal<compilerLearningTypeOrCountTargetClassesPossible, k_cItemsPerBitPackedDataUnitDynamic>::Func( pEbmBoostingState, pFeatureGroup, aModelFeatureGroupUpdateTensor ); } else { ApplyModelUpdateTrainingNormalTarget< compilerLearningTypeOrCountTargetClassesPossible + 1 >::Func( pEbmBoostingState, pFeatureGroup, aModelFeatureGroupUpdateTensor ); } } }; template<> class ApplyModelUpdateTrainingNormalTarget<k_cCompilerOptimizedTargetClassesMax + 1> final { public: ApplyModelUpdateTrainingNormalTarget() = delete; // this is a static class. Do not construct INLINE_ALWAYS static void Func( EbmBoostingState * const pEbmBoostingState, const FeatureGroup * const pFeatureGroup, const FloatEbmType * const aModelFeatureGroupUpdateTensor ) { static_assert(IsClassification(k_cCompilerOptimizedTargetClassesMax), "k_cCompilerOptimizedTargetClassesMax needs to be a classification"); EBM_ASSERT(IsClassification(pEbmBoostingState->GetRuntimeLearningTypeOrCountTargetClasses())); EBM_ASSERT(k_cCompilerOptimizedTargetClassesMax < pEbmBoostingState->GetRuntimeLearningTypeOrCountTargetClasses()); ApplyModelUpdateTrainingInternal<k_dynamicClassification, k_cItemsPerBitPackedDataUnitDynamic>::Func( pEbmBoostingState, pFeatureGroup, aModelFeatureGroupUpdateTensor ); } }; template<ptrdiff_t compilerLearningTypeOrCountTargetClasses, size_t compilerCountItemsPerBitPackedDataUnitPossible> class ApplyModelUpdateTrainingSIMDPacking final { public: ApplyModelUpdateTrainingSIMDPacking() = delete; // this is a static class. Do not construct INLINE_ALWAYS static void Func( EbmBoostingState * const pEbmBoostingState, const FeatureGroup * const pFeatureGroup, const FloatEbmType * const aModelFeatureGroupUpdateTensor ) { const size_t runtimeCountItemsPerBitPackedDataUnit = pFeatureGroup->GetCountItemsPerBitPackedDataUnit(); EBM_ASSERT(1 <= runtimeCountItemsPerBitPackedDataUnit); EBM_ASSERT(runtimeCountItemsPerBitPackedDataUnit <= k_cBitsForStorageType); static_assert(compilerCountItemsPerBitPackedDataUnitPossible <= k_cBitsForStorageType, "We can't have this many items in a data pack."); if(compilerCountItemsPerBitPackedDataUnitPossible == runtimeCountItemsPerBitPackedDataUnit) { ApplyModelUpdateTrainingInternal<compilerLearningTypeOrCountTargetClasses, compilerCountItemsPerBitPackedDataUnitPossible>::Func( pEbmBoostingState, pFeatureGroup, aModelFeatureGroupUpdateTensor ); } else { ApplyModelUpdateTrainingSIMDPacking< compilerLearningTypeOrCountTargetClasses, GetNextCountItemsBitPacked(compilerCountItemsPerBitPackedDataUnitPossible) >::Func( pEbmBoostingState, pFeatureGroup, aModelFeatureGroupUpdateTensor ); } } }; template<ptrdiff_t compilerLearningTypeOrCountTargetClasses> class ApplyModelUpdateTrainingSIMDPacking<compilerLearningTypeOrCountTargetClasses, k_cItemsPerBitPackedDataUnitDynamic> final { public: ApplyModelUpdateTrainingSIMDPacking() = delete; // this is a static class. Do not construct INLINE_ALWAYS static void Func( EbmBoostingState * const pEbmBoostingState, const FeatureGroup * const pFeatureGroup, const FloatEbmType * const aModelFeatureGroupUpdateTensor ) { EBM_ASSERT(1 <= pFeatureGroup->GetCountItemsPerBitPackedDataUnit()); EBM_ASSERT(pFeatureGroup->GetCountItemsPerBitPackedDataUnit() <= k_cBitsForStorageType); ApplyModelUpdateTrainingInternal<compilerLearningTypeOrCountTargetClasses, k_cItemsPerBitPackedDataUnitDynamic>::Func( pEbmBoostingState, pFeatureGroup, aModelFeatureGroupUpdateTensor ); } }; template<ptrdiff_t compilerLearningTypeOrCountTargetClassesPossible> class ApplyModelUpdateTrainingSIMDTarget final { public: ApplyModelUpdateTrainingSIMDTarget() = delete; // this is a static class. Do not construct INLINE_ALWAYS static void Func( EbmBoostingState * const pEbmBoostingState, const FeatureGroup * const pFeatureGroup, const FloatEbmType * const aModelFeatureGroupUpdateTensor ) { static_assert(IsClassification(compilerLearningTypeOrCountTargetClassesPossible), "compilerLearningTypeOrCountTargetClassesPossible needs to be a classification"); static_assert(compilerLearningTypeOrCountTargetClassesPossible <= k_cCompilerOptimizedTargetClassesMax, "We can't have this many items in a data pack."); const ptrdiff_t runtimeLearningTypeOrCountTargetClasses = pEbmBoostingState->GetRuntimeLearningTypeOrCountTargetClasses(); EBM_ASSERT(IsClassification(runtimeLearningTypeOrCountTargetClasses)); EBM_ASSERT(runtimeLearningTypeOrCountTargetClasses <= k_cCompilerOptimizedTargetClassesMax); if(compilerLearningTypeOrCountTargetClassesPossible == runtimeLearningTypeOrCountTargetClasses) { ApplyModelUpdateTrainingSIMDPacking< compilerLearningTypeOrCountTargetClassesPossible, k_cItemsPerBitPackedDataUnitMax >::Func( pEbmBoostingState, pFeatureGroup, aModelFeatureGroupUpdateTensor ); } else { ApplyModelUpdateTrainingSIMDTarget< compilerLearningTypeOrCountTargetClassesPossible + 1 >::Func( pEbmBoostingState, pFeatureGroup, aModelFeatureGroupUpdateTensor ); } } }; template<> class ApplyModelUpdateTrainingSIMDTarget<k_cCompilerOptimizedTargetClassesMax + 1> final { public: ApplyModelUpdateTrainingSIMDTarget() = delete; // this is a static class. Do not construct INLINE_ALWAYS static void Func( EbmBoostingState * const pEbmBoostingState, const FeatureGroup * const pFeatureGroup, const FloatEbmType * const aModelFeatureGroupUpdateTensor ) { static_assert(IsClassification(k_cCompilerOptimizedTargetClassesMax), "k_cCompilerOptimizedTargetClassesMax needs to be a classification"); EBM_ASSERT(IsClassification(pEbmBoostingState->GetRuntimeLearningTypeOrCountTargetClasses())); EBM_ASSERT(k_cCompilerOptimizedTargetClassesMax < pEbmBoostingState->GetRuntimeLearningTypeOrCountTargetClasses()); ApplyModelUpdateTrainingSIMDPacking< k_dynamicClassification, k_cItemsPerBitPackedDataUnitMax >::Func( pEbmBoostingState, pFeatureGroup, aModelFeatureGroupUpdateTensor ); } }; extern void ApplyModelUpdateTraining( EbmBoostingState * const pEbmBoostingState, const FeatureGroup * const pFeatureGroup, const FloatEbmType * const aModelFeatureGroupUpdateTensor ) { LOG_0(TraceLevelVerbose, "Entered ApplyModelUpdateTraining"); const ptrdiff_t runtimeLearningTypeOrCountTargetClasses = pEbmBoostingState->GetRuntimeLearningTypeOrCountTargetClasses(); if(0 == pFeatureGroup->GetCountFeatures()) { if(IsClassification(runtimeLearningTypeOrCountTargetClasses)) { ApplyModelUpdateTrainingZeroFeaturesTarget<2>::Func( pEbmBoostingState, aModelFeatureGroupUpdateTensor ); } else { EBM_ASSERT(IsRegression(runtimeLearningTypeOrCountTargetClasses)); ApplyModelUpdateTrainingZeroFeatures<k_regression>::Func( pEbmBoostingState, aModelFeatureGroupUpdateTensor ); } } else { if(k_bUseSIMD) { // TODO : enable SIMD(AVX-512) to work // 64 - do 8 at a time and unroll the loop 8 times. These are bool features and are common. Put the unrolled inner loop into a function // 32 - do 8 at a time and unroll the loop 4 times. These are bool features and are common. Put the unrolled inner loop into a function // 21 - do 8 at a time and unroll the loop 3 times (ignore the last 3 with a mask) // 16 - do 8 at a time and unroll the loop 2 times. These are bool features and are common. Put the unrolled inner loop into a function // 12 - do 8 of them, shift the low 4 upwards and then load the next 12 and take the top 4, repeat. // 10 - just drop this down to packing 8 together // 9 - just drop this down to packing 8 together // 8 - do all 8 at a time without an inner loop. This is one of the most common values. 256 binned values // 7,6,5,4,3,2,1 - use a mask to exclude the non-used conditions and process them like the 8. These are rare since they require more than 256 values if(IsClassification(runtimeLearningTypeOrCountTargetClasses)) { ApplyModelUpdateTrainingSIMDTarget<2>::Func( pEbmBoostingState, pFeatureGroup, aModelFeatureGroupUpdateTensor ); } else { EBM_ASSERT(IsRegression(runtimeLearningTypeOrCountTargetClasses)); ApplyModelUpdateTrainingSIMDPacking< k_regression, k_cItemsPerBitPackedDataUnitMax >::Func( pEbmBoostingState, pFeatureGroup, aModelFeatureGroupUpdateTensor ); } } else { // there isn't much benefit in eliminating the loop that unpacks a data unit unless we're also unpacking that to SIMD code // Our default packing structure is to bin continuous values to 256 values, and we have 64 bit packing structures, so we usually // have more than 8 values per memory fetch. Eliminating the inner loop for multiclass is valuable since we can have low numbers like 3 class, // 4 class, etc, but by the time we get to 8 loops with exp inside and a lot of other instructures we should worry that our code expansion // will exceed the L1 instruction cache size. With SIMD we do 8 times the work in the same number of instructions so these are lesser issues if(IsClassification(runtimeLearningTypeOrCountTargetClasses)) { ApplyModelUpdateTrainingNormalTarget<2>::Func( pEbmBoostingState, pFeatureGroup, aModelFeatureGroupUpdateTensor ); } else { EBM_ASSERT(IsRegression(runtimeLearningTypeOrCountTargetClasses)); ApplyModelUpdateTrainingInternal<k_regression, k_cItemsPerBitPackedDataUnitDynamic>::Func( pEbmBoostingState, pFeatureGroup, aModelFeatureGroupUpdateTensor ); } } } LOG_0(TraceLevelVerbose, "Exited ApplyModelUpdateTraining"); }
48.971722
169
0.72748
[ "vector", "model" ]
a665fe38a6caa4d4f7b41572a2416a4784cf6879
1,107
cpp
C++
Entropy/Matrix22.cpp
Shadorc/Entropy
8608f41eb5f3339f73578dedd54acc40ee6e8d1e
[ "Zlib" ]
null
null
null
Entropy/Matrix22.cpp
Shadorc/Entropy
8608f41eb5f3339f73578dedd54acc40ee6e8d1e
[ "Zlib" ]
null
null
null
Entropy/Matrix22.cpp
Shadorc/Entropy
8608f41eb5f3339f73578dedd54acc40ee6e8d1e
[ "Zlib" ]
null
null
null
#include "Precompiled.h" Matrix22::Matrix22() : Matrix22(0.0f, 0.0f, 0.0f, 0.0f) { } Matrix22::Matrix22(float m00, float m01, float m10, float m11) : m00(m00) , m01(m01) , m10(m10) , m11(m11) { } Matrix22::Matrix22(float angle) { FromAngle(angle); } void Matrix22::Reset() { m00 = 0.0f; m01 = 0.0f; m10 = 0.0f; m11 = 0.0f; } void Matrix22::FromAngle(float angle) { float cos = cosf(angle); float sin = sinf(angle); m00 = cos; m01 = -sin; m10 = sin; m11 = cos; } Matrix22 Matrix22::Transpose() const { return Matrix22(m00, m10, m01, m11); } Matrix22 Matrix22::operator+(const Matrix22& other) const { return Matrix22( m00 + other.m00, m01 + other.m01, m10 + other.m10, m11 + other.m11 ); } Matrix22 Matrix22::operator*(const Matrix22& other) const { return Matrix22( m00 * other.m00 + m01 * other.m10, m00 * other.m01 + m01 * other.m11, m10 * other.m00 + m11 * other.m10, m10 * other.m01 + m11 * other.m11 ); } Vector2 Matrix22::operator*(const Vector2& vector) const { return Vector2( m00 * vector.x + m01 * vector.y, m10 * vector.x + m11 * vector.y ); }
15.591549
62
0.63776
[ "vector" ]
a6660e972b02d3992801c35aa7d3301189ab57da
2,057
cc
C++
src/util/util.cc
agarick/emergence
9d49828909b4eba19f11c108756ffe73c7d1eb66
[ "MIT" ]
null
null
null
src/util/util.cc
agarick/emergence
9d49828909b4eba19f11c108756ffe73c7d1eb66
[ "MIT" ]
16
2020-11-02T20:21:07.000Z
2021-06-02T00:19:57.000Z
src/util/util.cc
blobject/emergence
3c4ea9c0cfd1e4b41cc9d1eb325ba20aee448980
[ "MIT" ]
null
null
null
#include "common.hh" #include "util.hh" std::string Util::execution_dir() { std::vector<char> buf(1024, 0); std::vector<char>::size_type size = buf.size(); bool path_yes = false; bool go = true; while (go) { int res = readlink("/proc/self/exe", &buf[0], size); if (0 > res) { go = false; } else if (size > static_cast<std::vector<char>::size_type>(res)) { path_yes = true; go = false; size = res; } else { size *= 2; buf.resize(size); std::fill(std::begin(buf), std::end(buf), 0); } } if (!path_yes) { std::string empty; return empty; } return std::regex_replace(std::string(&buf[0], size), std::regex("/[^/]*$"), ""); } std::string Util::working_dir() { char buf[1024]; getcwd(buf, 1024); std::string cwd(buf); return cwd; } bool Util::debug_gl(const std::string& func, const std::string& path, int line) { std::string error; while (GLenum e = glGetError()) { if (GL_INVALID_ENUM == e) { error = "invalid enum"; } else if (GL_INVALID_VALUE == e) { error = "invalid value"; } else if (GL_INVALID_OPERATION == e) { error = "invalid operation"; } else if (GL_STACK_OVERFLOW == e) { error = "stack overflow"; } else if (GL_STACK_UNDERFLOW == e) { error = "stack underflow"; } else if (GL_OUT_OF_MEMORY == e) { error = "out of memory"; } else { error = "unknown"; } std::cerr << "Error(gl): " << error << " at " << std::regex_replace(path, std::regex("^.*[\\/]src[\\/]"), "") << ':' << std::to_string(line) << "\n " << func << "\n"; return false; } return true; } std::string Util::trim(std::string s) { s.erase(std::find_if_not(s.rbegin(), s.rend(), [](int c) { return std::isspace(c); }).base(), s.end()); s.erase(s.begin(), std::find_if_not(s.begin(), s.end(), [](int c) { return std::isspace(c); })); return s; }
25.7125
78
0.519689
[ "vector" ]
a66a80b84c2a783db78d992e7b975b0ecd8961c4
4,264
cpp
C++
src/vision/matcher/RandomICPMatcher.cpp
eagleeye1105/VForce
8a0b80ff633ccabff4410eaf7c368de2cfb0f15c
[ "MIT" ]
17
2018-05-04T04:55:47.000Z
2021-07-03T06:56:23.000Z
src/vision/matcher/RandomICPMatcher.cpp
eagleeye1105/VForce
8a0b80ff633ccabff4410eaf7c368de2cfb0f15c
[ "MIT" ]
1
2019-08-06T06:22:58.000Z
2019-08-06T06:22:58.000Z
src/vision/matcher/RandomICPMatcher.cpp
freealong/VForce
8a0b80ff633ccabff4410eaf7c368de2cfb0f15c
[ "MIT" ]
17
2018-05-04T04:53:01.000Z
2021-09-28T15:51:33.000Z
// // Created by yongqi on 17-12-4. // #include "RandomICPMatcher.hpp" #include <glog/logging.h> #include <opencv2/opencv.hpp> #include <pcl/io/pcd_io.h> #include <pcl/registration/icp.h> #include "utils/PointCloudUtils.hpp" namespace VForce { using namespace std; RandomICPMatcher::RandomICPMatcher(const string &cfg_root, const string &cfg_file) : Matcher(cfg_root, cfg_file), uniform_radius_(0.001), divide_num_(1) { LoadConfig(cfg_root + "/" + cfg_file); } bool RandomICPMatcher::LoadConfig(const std::string &cfg_file) { init_ = false; // open cfg file LOG(INFO) << "Load config file from: " << cfg_file; cv::FileStorage fs(cfg_file, cv::FileStorage::READ); if (!fs.isOpened()) { LOG(ERROR) << "Open config file failed: " << cfg_file; return false; } // load cfg fs["uniform_radius"] >> uniform_radius_; DLOG(INFO) << "uniform_radius: " << uniform_radius_; fs["divide_num"] >> divide_num_; DLOG(INFO) << "divide_num_: " << divide_num_; fs["iter_num"] >> iter_num_; DLOG(INFO) << "iter_num_: " << iter_num_; init_ = true; return true; } double RandomICPMatcher::EstimatePose(const PointTCloudPtr &model, const float* model_size, const PointTCloudPtr &target, Eigen::Matrix4f &tf, PointTCloudPtr &final) { if (!init_) { LOG(ERROR) << "Matcher not initialized"; return std::numeric_limits<double>::max(); } if (target->empty()) { return 1; } PointTCloudPtr sampled_target(new PointTCloud); Utils::sampling_cloud(target, sampled_target, uniform_radius_); final = PointTCloudPtr(new PointTCloud); #ifdef DEBUG pcl::io::savePCDFile("debug_target.pcd", *sampled_target); #endif pcl::PointXYZ center = Utils::calculate_cloud_center(sampled_target); // shift sampled_target to origin Utils::shift_cloud(sampled_target, {-center.x, -center.y, -center.z}); pcl::IterativeClosestPoint<PointT, PointT> icp; icp.setMaxCorrespondenceDistance(0.2); // icp.setRANSACOutlierRejectionThreshold (0.05); icp.setTransformationEpsilon(1e-6); // icp.setEuclideanFitnessEpsilon(0.00001); icp.setMaximumIterations(300); icp.setInputSource(model); icp.setInputTarget(sampled_target); // find the best initial tf Eigen::Matrix4f best_initial_tf; double min_error = std::numeric_limits<double>::max(); Eigen::Matrix4f guess_tf = Eigen::Matrix4f::Identity(); float phi; // @TODO: using openmp for (int i = 0; i < divide_num_; ++i) { phi = static_cast<float>(i * 2 * M_PI / 12); guess_tf(0, 0) = cos(phi); guess_tf(0, 1) = -sin(phi); guess_tf(1, 0) = sin(phi); guess_tf(1, 1) = cos(phi); icp.align(*final, guess_tf); auto error = icp.getFitnessScore(); if (error < min_error) { best_initial_tf = icp.getFinalTransformation(); min_error = error; } } // make sure transformed model's z points to the origin of the target Eigen::Vector3f oz(0, 0, 1); Eigen::Vector3f transformed_oz = best_initial_tf.block<3, 3>(0, 0) * oz; if (transformed_oz(2) < 0) { DLOG(INFO) << "Rotate 180° around aixs y" << endl; Eigen::AngleAxisf rotation(M_PI, Eigen::Vector3f{0, 1, 0}); Eigen::Matrix4f rot_tf = Eigen::Matrix4f::Identity(); rot_tf.block<3, 3>(0, 0) = rotation.toRotationMatrix(); rot_tf(2, 3) = model_size[2]; best_initial_tf *= rot_tf; } // run icp again based on best initial tf tf = best_initial_tf; icp.setMaxCorrespondenceDistance(0.01); icp.setTransformationEpsilon(1e-6); icp.setMaximumIterations(2); transformPointCloud(*model, *final, tf); Eigen::Matrix4f prev = Eigen::Matrix4f::Identity(); for (int i = 0; i < iter_num_; ++i) { icp.setInputSource(final); icp.align(*final); if (fabs((icp.getLastIncrementalTransformation() - prev).sum() < icp.getTransformationEpsilon())) icp.setMaxCorrespondenceDistance(icp.getMaxCorrespondenceDistance() - 0.001); prev = icp.getLastIncrementalTransformation(); tf = icp.getFinalTransformation() * tf; } tf(0, 3) += center.x; tf(1, 3) += center.y; tf(2, 3) += center.z; pcl::transformPointCloud(*model, *final, tf); Utils::shift_cloud(sampled_target, center); return CalculateMatchError(final, sampled_target); } }
34.112
101
0.676829
[ "model" ]
a66af5bce368f32a7402bcde9ca0e9666b1afa28
143,466
cpp
C++
Contrib/at67/keywords.cpp
xopr/gigatron-rom
3db078626c23f259702962488e47184e7feda9e9
[ "BSD-2-Clause" ]
null
null
null
Contrib/at67/keywords.cpp
xopr/gigatron-rom
3db078626c23f259702962488e47184e7feda9e9
[ "BSD-2-Clause" ]
null
null
null
Contrib/at67/keywords.cpp
xopr/gigatron-rom
3db078626c23f259702962488e47184e7feda9e9
[ "BSD-2-Clause" ]
null
null
null
#include <stdio.h> #include <stdlib.h> #include <ctype.h> #include <cmath> #include <algorithm> #include "memory.h" #include "cpu.h" #include "assembler.h" #include "keywords.h" #include "operators.h" namespace Keywords { enum EmitStringResult {SyntaxError, InvalidStringVar, ValidStringVar}; std::vector<std::string> _operators; std::map<std::string, Keyword> _keywords; std::map<std::string, std::string> _functions; std::map<std::string, std::string> _stringKeywords; std::map<std::string, std::string> _equalsKeywords; std::vector<std::string>& getOperators(void) {return _operators; } std::map<std::string, Keyword>& getKeywords(void) {return _keywords; } std::map<std::string, std::string>& getFunctions(void) {return _functions; } std::map<std::string, std::string>& getStringKeywords(void) {return _stringKeywords;} std::map<std::string, std::string>& getEqualsKeywords(void) {return _equalsKeywords;} bool initialise(void) { _operators.push_back(" AND "); _operators.push_back(" XOR "); _operators.push_back(" OR " ); _operators.push_back(" NOT "); _operators.push_back(" MOD "); _operators.push_back(" LSL "); _operators.push_back(" LSR "); _operators.push_back(" ASR "); _operators.push_back("<<" ); _operators.push_back(">>" ); _functions["PEEK"] = "PEEK"; _functions["DEEK"] = "DEEK"; _functions["USR" ] = "USR"; _functions["RND" ] = "RND"; _functions["LEN" ] = "LEN"; _functions["ABS" ] = "ABS"; _functions["ACS" ] = "ACS"; _functions["ASC" ] = "ASC"; _functions["ASN" ] = "ASN"; _functions["ATN" ] = "ATN"; _functions["COS" ] = "COS"; _functions["EXP" ] = "EXP"; _functions["INT" ] = "INT"; _functions["LOG" ] = "LOG"; _functions["SIN" ] = "SIN"; _functions["SQR" ] = "SQR"; _functions["TAN" ] = "TAN"; _functions["FRE" ] = "FRE"; _functions["TIME"] = "TIME"; _keywords["LET" ] = {"LET", keywordLET, Compiler::SingleStatementParsed}; _keywords["END" ] = {"END", keywordEND, Compiler::SingleStatementParsed}; _keywords["INC" ] = {"INC", keywordINC, Compiler::SingleStatementParsed}; _keywords["DEC" ] = {"DEC", keywordDEC, Compiler::SingleStatementParsed}; _keywords["ON" ] = {"ON", keywordON, Compiler::SingleStatementParsed}; _keywords["GOTO" ] = {"GOTO", keywordGOTO, Compiler::SingleStatementParsed}; _keywords["GOSUB" ] = {"GOSUB", keywordGOSUB, Compiler::SingleStatementParsed}; _keywords["RETURN" ] = {"RETURN", keywordRETURN, Compiler::SingleStatementParsed}; _keywords["CLS" ] = {"CLS", keywordCLS, Compiler::SingleStatementParsed}; _keywords["?" ] = {"?", keywordPRINT, Compiler::SingleStatementParsed}; _keywords["PRINT" ] = {"PRINT", keywordPRINT, Compiler::SingleStatementParsed}; _keywords["INPUT" ] = {"INPUT", keywordINPUT, Compiler::SingleStatementParsed}; _keywords["FOR" ] = {"FOR", keywordFOR, Compiler::SingleStatementParsed}; _keywords["NEXT" ] = {"NEXT", keywordNEXT, Compiler::SingleStatementParsed}; _keywords["IF" ] = {"IF", keywordIF, Compiler::MultiStatementParsed }; _keywords["ELSEIF" ] = {"ELSEIF", keywordELSEIF, Compiler::SingleStatementParsed}; _keywords["ELSE" ] = {"ELSE", keywordELSE, Compiler::SingleStatementParsed}; _keywords["ENDIF" ] = {"ENDIF", keywordENDIF, Compiler::SingleStatementParsed}; _keywords["WHILE" ] = {"WHILE", keywordWHILE, Compiler::SingleStatementParsed}; _keywords["WEND" ] = {"WEND", keywordWEND, Compiler::SingleStatementParsed}; _keywords["REPEAT" ] = {"REPEAT", keywordREPEAT, Compiler::SingleStatementParsed}; _keywords["UNTIL" ] = {"UNTIL", keywordUNTIL, Compiler::SingleStatementParsed}; _keywords["CONST" ] = {"CONST", keywordCONST, Compiler::SingleStatementParsed}; _keywords["DIM" ] = {"DIM", keywordDIM, Compiler::SingleStatementParsed}; _keywords["DEF" ] = {"DEF", keywordDEF, Compiler::SingleStatementParsed}; _keywords["AT" ] = {"AT", keywordAT, Compiler::SingleStatementParsed}; _keywords["PUT" ] = {"PUT", keywordPUT, Compiler::SingleStatementParsed}; _keywords["MODE" ] = {"MODE", keywordMODE, Compiler::SingleStatementParsed}; _keywords["WAIT" ] = {"WAIT", keywordWAIT, Compiler::SingleStatementParsed}; _keywords["LINE" ] = {"LINE", keywordLINE, Compiler::SingleStatementParsed}; _keywords["HLINE" ] = {"HLINE", keywordHLINE, Compiler::SingleStatementParsed}; _keywords["VLINE" ] = {"VLINE", keywordVLINE, Compiler::SingleStatementParsed}; _keywords["CIRCLE" ] = {"CIRCLE", keywordCIRCLE, Compiler::SingleStatementParsed}; _keywords["CIRCLEF"] = {"CIRCLEF", keywordCIRCLEF, Compiler::SingleStatementParsed}; _keywords["RECT" ] = {"RECT", keywordRECT, Compiler::SingleStatementParsed}; _keywords["RECTF" ] = {"RECTF", keywordRECTF, Compiler::SingleStatementParsed}; _keywords["POLY" ] = {"POLY", keywordPOLY, Compiler::SingleStatementParsed}; _keywords["SCROLL" ] = {"SCROLL", keywordSCROLL, Compiler::SingleStatementParsed}; _keywords["POKE" ] = {"POKE", keywordPOKE, Compiler::SingleStatementParsed}; _keywords["DOKE" ] = {"DOKE", keywordDOKE, Compiler::SingleStatementParsed}; _keywords["PLAY" ] = {"PLAY", keywordPLAY, Compiler::SingleStatementParsed}; _stringKeywords["CHR$" ] = "CHR$"; _stringKeywords["HEX$" ] = "HEX$"; _stringKeywords["HEXW$" ] = "HEXW$"; _stringKeywords["MID$" ] = "MID$"; _stringKeywords["LEFT$" ] = "LEFT$"; _stringKeywords["RIGHT$"] = "RIGHT$"; _stringKeywords["SPC$" ] = "SPC$"; _stringKeywords["STR$" ] = "STR$"; _stringKeywords["TIME$" ] = "TIME$"; _equalsKeywords["CONST" ] = "CONST"; _equalsKeywords["DIM" ] = "DIM"; _equalsKeywords["DEF" ] = "DEF"; _equalsKeywords["FOR" ] = "FOR"; _equalsKeywords["IF" ] = "IF"; _equalsKeywords["ELSEIF"] = "ELSEIF"; _equalsKeywords["WHILE" ] = "WHILE"; _equalsKeywords["UNTIL" ] = "UNTIL"; return true; } bool findKeyword(std::string code, const std::string& keyword, size_t& foundPos) { Expression::strToUpper(code); foundPos = code.find(keyword); if(foundPos != std::string::npos) { foundPos += keyword.size(); return true; } return false; } KeywordResult handleKeywords(Compiler::CodeLine& codeLine, const std::string& keyword, int codeLineIndex, int tokenIndex, KeywordFuncResult& result) { size_t foundPos; std::string key = keyword; Expression::strToUpper(key); if(_keywords.find(key) == _keywords.end()) return KeywordNotFound; // Handle keyword in code line if(findKeyword(key, _keywords[key]._name, foundPos) && _keywords[key]._func) { bool success = _keywords[key]._func(codeLine, codeLineIndex, tokenIndex, foundPos, result); return (!success) ? KeywordError : KeywordFound; } return KeywordFound; } EmitStringResult emitStringAddr(const std::string& token, const std::string& operand) { std::string strToken = token; Expression::stripNonStringWhitespace(strToken); if(strToken.back() == '$' && Expression::isVarNameValid(strToken)) { uint16_t srcAddr; int strIndexSrc = Compiler::findStr(strToken); if(strIndexSrc >= 0) { srcAddr = Compiler::getStringVars()[strIndexSrc]._address; } else { strIndexSrc = Compiler::findConst(strToken); if(strIndexSrc == -1) return SyntaxError; srcAddr = Compiler::getConstants()[strIndexSrc]._address; } Compiler::emitVcpuAsm("LDWI", Expression::wordToHexString(srcAddr), false); Compiler::emitVcpuAsm("STW", operand, false); return ValidStringVar; } return InvalidStringVar; } void getOrCreateString(const Expression::Numeric& numeric, std::string& name, uint16_t& addr, int& index) { switch(numeric._varType) { case Expression::String: { Compiler::getOrCreateConstString(numeric._text, index); name = Compiler::getStringVars()[index]._name; addr = Compiler::getStringVars()[index]._address; } break; case Expression::StrVar: { name = Compiler::getStringVars()[index]._name; addr = Compiler::getStringVars()[index]._address; } break; case Expression::Constant: { name = Compiler::getConstants()[index]._name; addr = Compiler::getConstants()[index]._address; } break; default: break; } } void handleConstantString(const Expression::Numeric& numeric, Compiler::ConstStrType constStrType, std::string& name, int& index) { switch(constStrType) { case Compiler::StrLeft: case Compiler::StrRight: { uint8_t length = uint8_t(std::lround(numeric._parameters[0]._value)); Compiler::getOrCreateConstString(constStrType, numeric._text, length, 0, index); } break; case Compiler::StrMid: { uint8_t offset = uint8_t(std::lround(numeric._parameters[0]._value)); uint8_t length = uint8_t(std::lround(numeric._parameters[1]._value)); Compiler::getOrCreateConstString(constStrType, numeric._text, length, offset, index); } break; default: break; } name = Compiler::getStringVars()[index]._name; uint16_t srcAddr = Compiler::getStringVars()[index]._address; if(Expression::getEnableOptimisedPrint()) { Compiler::emitVcpuAsm("LDWI", Expression::wordToHexString(srcAddr), false); Compiler::emitVcpuAsm("%PrintAcString", "", false); } else { uint16_t dstAddr = Compiler::getStringVars()[Expression::getOutputNumeric()._index]._address; Compiler::emitVcpuAsm("LDWI", Expression::wordToHexString(srcAddr), false); Compiler::emitVcpuAsm("STW", "strSrcAddr", false); Compiler::emitVcpuAsm("LDWI", Expression::wordToHexString(dstAddr), false); Compiler::emitVcpuAsm("STW", "strDstAddr", false); Compiler::emitVcpuAsm("%StringCopy", "", false); } } void handleStringParameter(Expression::Numeric& param) { // Literals if(param._varType == Expression::Number) { // 8bit if(param._value >=0 && param._value <= 255) { Compiler::emitVcpuAsm("LDI", std::to_string(int16_t(std::lround(param._value))), false); } // 16bit else { Compiler::emitVcpuAsm("LDWI", std::to_string(int16_t(std::lround(param._value))), false); } return; } Operators::handleSingleOp("LDW", param); } // ******************************************************************************************** // Functions // ******************************************************************************************** Expression::Numeric functionARR(Expression::Numeric& numeric) { Compiler::getNextTempVar(); int intSize = Compiler::getIntegerVars()[numeric._index]._intSize; uint16_t arrayPtr = Compiler::getIntegerVars()[numeric._index]._array; // Literal array index if(numeric._parameters[0]._varType == Expression::Number) { std::string operand = Expression::wordToHexString(arrayPtr + uint16_t(numeric._parameters[0]._value*intSize)); switch(numeric._int16Byte) { case Expression::Int16Low: Compiler::emitVcpuAsm("LDWI", operand, false); Compiler::emitVcpuAsm("PEEK", "", false); break; case Expression::Int16High: Compiler::emitVcpuAsm("LDWI", operand + " + 1", false); Compiler::emitVcpuAsm("PEEK", "", false); break; case Expression::Int16Both: Compiler::emitVcpuAsm("LDWI", operand, false); Compiler::emitVcpuAsm("DEEK", "", false); break; default: break; } numeric._value = uint8_t(Compiler::getTempVarStart()); numeric._varType = Expression::TmpVar; numeric._name = Compiler::getTempVarStartStr(); } // Variable array index else { // Can't call Operators::handleSingleOp() here, so special case it switch(numeric._parameters[0]._varType) { // Temporary variable address case Expression::TmpVar: { Compiler::emitVcpuAsm("LDW", Expression::byteToHexString(uint8_t(std::lround(numeric._parameters[0]._value))), false); } break; // User variable name case Expression::IntVar: { Compiler::emitVcpuAsmUserVar("LDW", numeric._parameters[0], false); } break; default: break; } numeric._value = uint8_t(Compiler::getTempVarStart()); numeric._varType = Expression::TmpVar; numeric._name = Compiler::getTempVarStartStr(); #ifdef SMALL_CODE_SIZE // Saves 2 bytes per array access but costs an extra 2 instructions in performance if(Assembler::getUseOpcodeCALLI()) { Compiler::emitVcpuAsm("STW", "memIndex", false); Compiler::emitVcpuAsm("LDWI", Expression::wordToHexString(arrayPtr), false); Compiler::emitVcpuAsm("CALLI", "getArrayInt16", false); } else #endif { Compiler::emitVcpuAsm("STW", "register2", false); Compiler::emitVcpuAsm("LDWI", Expression::wordToHexString(arrayPtr), false); Compiler::emitVcpuAsm("ADDW", "register2", false); Compiler::emitVcpuAsm("ADDW", "register2", false); switch(numeric._int16Byte) { case Expression::Int16Low: Compiler::emitVcpuAsm("PEEK", "", false); break; case Expression::Int16High: Compiler::emitVcpuAsm("ADDI", "1", false); Compiler::emitVcpuAsm("PEEK", "", false); break; case Expression::Int16Both: Compiler::emitVcpuAsm("DEEK", "", false); break; default: break; } } } Compiler::emitVcpuAsm("STW", Expression::byteToHexString(uint8_t(Compiler::getTempVarStart())), false); return numeric; } Expression::Numeric functionPEEK(Expression::Numeric& numeric) { if(numeric._varType == Expression::Number) { // Optimise for page 0 if(numeric._value >= 0 && numeric._value <= 255) { Compiler::emitVcpuAsm("LD", Expression::byteToHexString(uint8_t(std::lround(numeric._value))), false); Compiler::emitVcpuAsm("STW", Expression::byteToHexString(uint8_t(Compiler::getTempVarStart())), false); numeric._value = uint8_t(Compiler::getTempVarStart()); numeric._varType = Expression::TmpVar; numeric._name = Compiler::getTempVarStartStr(); return numeric; } else { Compiler::emitVcpuAsm("LDWI", Expression::wordToHexString(int16_t(std::lround(numeric._value))), false); } } Compiler::getNextTempVar(); Operators::handleSingleOp("LDW", numeric); Compiler::emitVcpuAsm("PEEK", "", false); Compiler::emitVcpuAsm("STW", Expression::byteToHexString(uint8_t(Compiler::getTempVarStart())), false); return numeric; } Expression::Numeric functionDEEK(Expression::Numeric& numeric) { if(numeric._varType == Expression::Number) { // Optimise for page 0 if(numeric._value >= 0 && numeric._value <= 255) { Compiler::emitVcpuAsm("LDW", Expression::byteToHexString(uint8_t(std::lround(numeric._value))), false); Compiler::emitVcpuAsm("STW", Expression::byteToHexString(uint8_t(Compiler::getTempVarStart())), false); numeric._value = uint8_t(Compiler::getTempVarStart()); numeric._varType = Expression::TmpVar; numeric._name = Compiler::getTempVarStartStr(); return numeric; } else { Compiler::emitVcpuAsm("LDWI", Expression::wordToHexString(int16_t(std::lround(numeric._value))), false); } } Compiler::getNextTempVar(); Operators::handleSingleOp("LDW", numeric); Compiler::emitVcpuAsm("DEEK", "", false); Compiler::emitVcpuAsm("STW", Expression::byteToHexString(uint8_t(Compiler::getTempVarStart())), false); return numeric; } Expression::Numeric functionUSR(Expression::Numeric& numeric) { if(numeric._varType == Expression::Number) { if(Assembler::getUseOpcodeCALLI()) { (numeric._value >= 0 && numeric._value <= 255) ? Compiler::emitVcpuAsm("CALLI", Expression::byteToHexString(uint8_t(std::lround(numeric._value))), false) : Compiler::emitVcpuAsm("CALLI", Expression::wordToHexString(int16_t(std::lround(numeric._value))), false); } else { (numeric._value >= 0 && numeric._value <= 255) ? Compiler::emitVcpuAsm("LDI", Expression::byteToHexString(uint8_t(std::lround(numeric._value))), false) : Compiler::emitVcpuAsm("LDWI", Expression::wordToHexString(int16_t(std::lround(numeric._value))), false); } } Compiler::getNextTempVar(); if(Assembler::getUseOpcodeCALLI()) { Operators::handleSingleOp("CALLI", numeric); } else { Operators::handleSingleOp("LDW", numeric); Compiler::emitVcpuAsm("CALL", "giga_vAC", false); } Compiler::emitVcpuAsm("STW", Expression::byteToHexString(uint8_t(Compiler::getTempVarStart())), false); return numeric; } Expression::Numeric functionRND(Expression::Numeric& numeric) { bool useMod = true; if(numeric._varType == Expression::Number) { // RND(0) skips the MOD call and allows you to filter the output manually if(numeric._value == 0) { useMod = false; } else { (numeric._value > 0 && numeric._value <= 255) ? Compiler::emitVcpuAsm("LDI", Expression::byteToHexString(uint8_t(std::lround(numeric._value))), false) : Compiler::emitVcpuAsm("LDWI", Expression::wordToHexString(int16_t(std::lround(numeric._value))), false); } } Compiler::getNextTempVar(); if(useMod) { Operators::handleSingleOp("LDW", numeric); Compiler::emitVcpuAsm("%RandMod", "", false); } else { numeric._value = uint8_t(Compiler::getTempVarStart()); numeric._varType = Expression::TmpVar; numeric._name = Compiler::getTempVarStartStr(); Compiler::emitVcpuAsm("%Rand", "", false); } Compiler::emitVcpuAsm("STW", Expression::byteToHexString(uint8_t(Compiler::getTempVarStart())), false); return numeric; } Expression::Numeric functionLEN(Expression::Numeric& numeric) { if(numeric._varType != Expression::Number) { Compiler::getNextTempVar(); // Handle non variables if(numeric._index == -1) { switch(numeric._varType) { // Get or create constant string case Expression::String: { int index; Compiler::getOrCreateConstString(numeric._text, index); numeric._index = int16_t(index); numeric._varType = Expression::StrVar; } break; case Expression::TmpStrVar: { } break; default: { fprintf(stderr, "Compiler::functionLEN() : couldn't find variable name '%s'\n", numeric._name.c_str()); return numeric; } } } int length = 0; switch(numeric._varType) { case Expression::IntVar: length = Compiler::getIntegerVars()[numeric._index]._intSize; break; case Expression::ArrVar: length = Compiler::getIntegerVars()[numeric._index]._arrSize; break; case Expression::StrVar: length = Compiler::getStringVars()[numeric._index]._maxSize; break; case Expression::Constant: length = Compiler::getConstants()[numeric._index]._size; break; default: break; } // Variable lengths if(numeric._varType == Expression::StrVar && !Compiler::getStringVars()[numeric._index]._constant) { Compiler::emitVcpuAsm("LDWI", Expression::wordToHexString(Compiler::getStringVars()[numeric._index]._address), false); Compiler::emitVcpuAsm("PEEK", "", false); } else if(numeric._varType == Expression::TmpStrVar) { Compiler::emitVcpuAsm("LDWI", Expression::wordToHexString(Compiler::getStrWorkArea()), false); Compiler::emitVcpuAsm("PEEK", "", false); } // Constants lengths else { (length <= 255) ? Compiler::emitVcpuAsm("LDI", std::to_string(length), false) : Compiler::emitVcpuAsm("LDWI", std::to_string(length), false); } numeric._value = uint8_t(Compiler::getTempVarStart()); numeric._varType = Expression::TmpVar; numeric._name = Compiler::getTempVarStartStr(); Compiler::emitVcpuAsm("STW", Expression::byteToHexString(uint8_t(Compiler::getTempVarStart())), false); } return numeric; } Expression::Numeric functionCHR$(Expression::Numeric& numeric) { int index; uint16_t dstAddr; Expression::VarType varType; if(Expression::getOutputNumeric()._varType == Expression::StrVar) { index = Expression::getOutputNumeric()._index; dstAddr = Compiler::getStringVars()[index]._address; varType = Expression::StrVar; } else { index = -1; dstAddr = Compiler::getStrWorkArea(); varType = Expression::TmpStrVar; } if(numeric._varType == Expression::Number) { // Print CHR string, (without wasting memory) if(Expression::getEnableOptimisedPrint()) { Compiler::emitVcpuAsm("LDI", std::to_string(int16_t(std::lround(numeric._value))), false); Compiler::emitVcpuAsm("%PrintAcChar", "", false); return numeric; } // Create CHR string Compiler::emitVcpuAsm("LDI", std::to_string(int16_t(std::lround(numeric._value))), false); Compiler::emitVcpuAsm("STW", "strChr", false); Compiler::emitVcpuAsm("LDWI", Expression::wordToHexString(dstAddr), false); Compiler::emitVcpuAsm("STW", "strDstAddr", false); Compiler::emitVcpuAsm("%StringChr", "", false); return Expression::Numeric(dstAddr, uint16_t(index), true, varType, Expression::BooleanCC, Expression::Int16Both, std::string(""), std::string("")); } Compiler::getNextTempVar(); Operators::handleSingleOp("LDW", numeric); if(Expression::getEnableOptimisedPrint()) { Compiler::emitVcpuAsm("%PrintAcChar", "", false); return numeric; } // Create CHR string Compiler::emitVcpuAsm("STW", "strChr", false); Compiler::emitVcpuAsm("LDWI", Expression::wordToHexString(dstAddr), false); Compiler::emitVcpuAsm("STW", "strDstAddr", false); Compiler::emitVcpuAsm("%StringChr", "", false); return Expression::Numeric(dstAddr, uint16_t(index), true, varType, Expression::BooleanCC, Expression::Int16Both, std::string(""), std::string("")); } Expression::Numeric functionHEX$(Expression::Numeric& numeric) { int index; uint16_t dstAddr; Expression::VarType varType; if(Expression::getOutputNumeric()._varType == Expression::StrVar) { index = Expression::getOutputNumeric()._index; dstAddr = Compiler::getStringVars()[index]._address; varType = Expression::StrVar; } else { index = -1; dstAddr = Compiler::getStrWorkArea(); varType = Expression::TmpStrVar; } if(numeric._varType == Expression::Number) { // Print HEX string, (without wasting memory) if(Expression::getEnableOptimisedPrint()) { Compiler::emitVcpuAsm("LDI", Expression::byteToHexString(uint8_t(std::lround(numeric._value))), false); Compiler::emitVcpuAsm("%PrintAcHexByte", "", false); return numeric; } // Create HEX string Compiler::emitVcpuAsm("LDI", Expression::byteToHexString(uint8_t(std::lround(numeric._value))), false); Compiler::emitVcpuAsm("STW", "strChr", false); Compiler::emitVcpuAsm("LDWI", Expression::wordToHexString(dstAddr), false); Compiler::emitVcpuAsm("STW", "strDstAddr", false); Compiler::emitVcpuAsm("%StringHex", "", false); return Expression::Numeric(dstAddr, uint16_t(index), true, varType, Expression::BooleanCC, Expression::Int16Both, std::string(""), std::string("")); } Compiler::getNextTempVar(); Operators::handleSingleOp("LDW", numeric); if(Expression::getEnableOptimisedPrint()) { Compiler::emitVcpuAsm("%PrintAcHexByte", "", false); return numeric; } // Create HEX string Compiler::emitVcpuAsm("STW", "strChr", false); Compiler::emitVcpuAsm("LDWI", Expression::wordToHexString(dstAddr), false); Compiler::emitVcpuAsm("STW", "strDstAddr", false); Compiler::emitVcpuAsm("%StringHex", "", false); return Expression::Numeric(dstAddr, uint16_t(index), true, varType, Expression::BooleanCC, Expression::Int16Both, std::string(""), std::string("")); } Expression::Numeric functionHEXW$(Expression::Numeric& numeric) { int index; uint16_t dstAddr; Expression::VarType varType; if(Expression::getOutputNumeric()._varType == Expression::StrVar) { index = Expression::getOutputNumeric()._index; dstAddr = Compiler::getStringVars()[index]._address; varType = Expression::StrVar; } else { index = -1; dstAddr = Compiler::getStrWorkArea(); varType = Expression::TmpStrVar; } if(numeric._varType == Expression::Number) { // Print HEXW string, (without wasting memory) if(Expression::getEnableOptimisedPrint()) { Compiler::emitVcpuAsm("LDWI", Expression::wordToHexString(int16_t(std::lround(numeric._value))), false); Compiler::emitVcpuAsm("%PrintAcHexWord", "", false); return numeric; } // Create HEXW string Compiler::emitVcpuAsm("LDWI", Expression::wordToHexString(int16_t(std::lround(numeric._value))), false); Compiler::emitVcpuAsm("STW", "strHex", false); Compiler::emitVcpuAsm("LDWI", Expression::wordToHexString(dstAddr), false); Compiler::emitVcpuAsm("STW", "strDstAddr", false); Compiler::emitVcpuAsm("%StringHexw", "", false); return Expression::Numeric(dstAddr, uint16_t(index), true, varType, Expression::BooleanCC, Expression::Int16Both, std::string(""), std::string("")); } Compiler::getNextTempVar(); Operators::handleSingleOp("LDW", numeric); if(Expression::getEnableOptimisedPrint()) { Compiler::emitVcpuAsm("%PrintAcHexWord", "", false); return numeric; } // Create HEXW string Compiler::emitVcpuAsm("STW", "strHex", false); Compiler::emitVcpuAsm("LDWI", Expression::wordToHexString(dstAddr), false); Compiler::emitVcpuAsm("STW", "strDstAddr", false); Compiler::emitVcpuAsm("%StringHexw", "", false); return Expression::Numeric(dstAddr, uint16_t(index), true, varType, Expression::BooleanCC, Expression::Int16Both, std::string(""), std::string("")); } Expression::Numeric functionLEFT$(Expression::Numeric& numeric) { // Literal string and parameter, (optimised case) if(numeric._varType == Expression::String && numeric._parameters.size() == 1 && numeric._parameters[0]._varType == Expression::Number) { int index; std::string name; handleConstantString(numeric, Compiler::StrLeft, name, index); return Expression::Numeric(0, uint16_t(index), true, Expression::StrVar, Expression::BooleanCC, Expression::Int16Both, name, std::string("")); } // Non optimised case if(numeric._parameters.size() == 1) { std::string name; uint16_t srcAddr; int index = int(numeric._index); getOrCreateString(numeric, name, srcAddr, index); if(Expression::getEnableOptimisedPrint()) { handleStringParameter(numeric._parameters[0]); Compiler::emitVcpuAsm("STW", "textLen", false); Compiler::emitVcpuAsm("LDWI", Expression::wordToHexString(srcAddr), false); Compiler::emitVcpuAsm("%PrintAcLeft", "", false); } else { uint16_t dstAddr = Compiler::getStringVars()[Expression::getOutputNumeric()._index]._address; handleStringParameter(numeric._parameters[0]); Compiler::emitVcpuAsm("STW", "strLength", false); Compiler::emitVcpuAsm("LDWI", Expression::wordToHexString(srcAddr), false); Compiler::emitVcpuAsm("STW", "strSrcAddr", false); Compiler::emitVcpuAsm("LDWI", Expression::wordToHexString(dstAddr), false); Compiler::emitVcpuAsm("STW", "strDstAddr", false); Compiler::emitVcpuAsm("%StringLeft", "", false); } return Expression::Numeric(0, uint16_t(index), true, Expression::StrVar, Expression::BooleanCC, Expression::Int16Both, name, std::string("")); } return numeric; } Expression::Numeric functionRIGHT$(Expression::Numeric& numeric) { // Literal string and parameter, (optimised case) if(numeric._varType == Expression::String && numeric._parameters.size() == 1 && numeric._parameters[0]._varType == Expression::Number) { int index; std::string name; handleConstantString(numeric, Compiler::StrRight, name, index); return Expression::Numeric(0, uint16_t(index), true, Expression::StrVar, Expression::BooleanCC, Expression::Int16Both, name, std::string("")); } // Non optimised case if(numeric._parameters.size() == 1) { std::string name; uint16_t srcAddr; int index = int(numeric._index); getOrCreateString(numeric, name, srcAddr, index); if(Expression::getEnableOptimisedPrint()) { handleStringParameter(numeric._parameters[0]); Compiler::emitVcpuAsm("STW", "textLen", false); Compiler::emitVcpuAsm("LDWI", Expression::wordToHexString(srcAddr), false); Compiler::emitVcpuAsm("%PrintAcRight", "", false); } else { uint16_t dstAddr = Compiler::getStringVars()[Expression::getOutputNumeric()._index]._address; handleStringParameter(numeric._parameters[0]); Compiler::emitVcpuAsm("STW", "strLength", false); Compiler::emitVcpuAsm("LDWI", Expression::wordToHexString(srcAddr), false); Compiler::emitVcpuAsm("STW", "strSrcAddr", false); Compiler::emitVcpuAsm("LDWI", Expression::wordToHexString(dstAddr), false); Compiler::emitVcpuAsm("STW", "strDstAddr", false); Compiler::emitVcpuAsm("%StringRight", "", false); } return Expression::Numeric(0, uint16_t(index), true, Expression::StrVar, Expression::BooleanCC, Expression::Int16Both, name, std::string("")); } return numeric; } Expression::Numeric functionMID$(Expression::Numeric& numeric) { // Literal string and parameters, (optimised case) if(numeric._varType == Expression::String && numeric._parameters.size() == 2 && numeric._parameters[0]._varType == Expression::Number && numeric._parameters[1]._varType == Expression::Number) { int index; std::string name; handleConstantString(numeric, Compiler::StrMid, name, index); return Expression::Numeric(0, uint16_t(index), true, Expression::StrVar, Expression::BooleanCC, Expression::Int16Both, name, std::string("")); } // Non optimised case if(numeric._parameters.size() == 2) { std::string name; uint16_t srcAddr; int index = int(numeric._index); getOrCreateString(numeric, name, srcAddr, index); if(Expression::getEnableOptimisedPrint()) { handleStringParameter(numeric._parameters[0]); Compiler::emitVcpuAsm("STW", "textOfs", false); handleStringParameter(numeric._parameters[1]); Compiler::emitVcpuAsm("STW", "textLen", false); Compiler::emitVcpuAsm("LDWI", Expression::wordToHexString(srcAddr), false); Compiler::emitVcpuAsm("%PrintAcMid", "", false); } else { uint16_t dstAddr = Compiler::getStringVars()[Expression::getOutputNumeric()._index]._address; handleStringParameter(numeric._parameters[0]); Compiler::emitVcpuAsm("STW", "strOffset", false); handleStringParameter(numeric._parameters[1]); Compiler::emitVcpuAsm("STW", "strLength", false); Compiler::emitVcpuAsm("LDWI", Expression::wordToHexString(srcAddr), false); Compiler::emitVcpuAsm("STW", "strSrcAddr", false); Compiler::emitVcpuAsm("LDWI", Expression::wordToHexString(dstAddr), false); Compiler::emitVcpuAsm("STW", "strDstAddr", false); Compiler::emitVcpuAsm("%StringMid", "", false); } return Expression::Numeric(0, uint16_t(index), true, Expression::StrVar, Expression::BooleanCC, Expression::Int16Both, name, std::string("")); } return numeric; } // ******************************************************************************************** // Keywords // ******************************************************************************************** bool keywordLET(Compiler::CodeLine& codeLine, int codeLineIndex, int tokenIndex, size_t foundPos, KeywordFuncResult& result) { UNREFERENCED_PARAM(result); UNREFERENCED_PARAM(tokenIndex); UNREFERENCED_PARAM(codeLineIndex); // Remove LET from code codeLine._code.erase(foundPos, 3); size_t let; std::string expr = codeLine._expression; Expression::strToUpper(expr); if((let = expr.find("LET")) != std::string::npos) { codeLine._expression.erase(let, 3); } for(int i=0; i<int(codeLine._tokens.size()); i++) { std::string str = codeLine._tokens[i]; Expression::strToUpper(str); if((let = expr.find("LET")) != std::string::npos) { codeLine._tokens[i].erase(let, 3); break; } } return true; } bool keywordEND(Compiler::CodeLine& codeLine, int codeLineIndex, int tokenIndex, size_t foundPos, KeywordFuncResult& result) { UNREFERENCED_PARAM(result); UNREFERENCED_PARAM(foundPos); UNREFERENCED_PARAM(tokenIndex); UNREFERENCED_PARAM(codeLineIndex); UNREFERENCED_PARAM(codeLine); std::string labelName = "_end_" + Expression::wordToHexString(Compiler::getVasmPC()); Compiler::emitVcpuAsm("BRA", labelName, false, codeLineIndex, labelName); return true; } bool keywordINC(Compiler::CodeLine& codeLine, int codeLineIndex, int tokenIndex, size_t foundPos, KeywordFuncResult& result) { UNREFERENCED_PARAM(result); UNREFERENCED_PARAM(tokenIndex); // Operand must be an integer var std::string varToken = codeLine._code.substr(foundPos); Expression::stripWhitespace(varToken); int varIndex = Compiler::findVar(varToken, false); if(varIndex < 0) { fprintf(stderr, "Compiler::keywordINC() : Syntax error, integer variable '%s' not found, in '%s' on line %d\n", varToken.c_str(), codeLine._text.c_str(), codeLineIndex + 1); return false; } Compiler::emitVcpuAsm("INC", "_" + Compiler::getIntegerVars()[varIndex]._name, false, codeLineIndex); return true; } bool keywordDEC(Compiler::CodeLine& codeLine, int codeLineIndex, int tokenIndex, size_t foundPos, KeywordFuncResult& result) { UNREFERENCED_PARAM(result); UNREFERENCED_PARAM(tokenIndex); // Operand must be an integer var std::string varToken = codeLine._code.substr(foundPos); Expression::stripWhitespace(varToken); int varIndex = Compiler::findVar(varToken, false); if(varIndex < 0) { fprintf(stderr, "Compiler::keywordDEC() : Syntax error, integer variable '%s' not found, in '%s' on line %d\n", varToken.c_str(), codeLine._text.c_str(), codeLineIndex + 1); return false; } Compiler::emitVcpuAsm("LDW", "_" + Compiler::getIntegerVars()[varIndex]._name, false, codeLineIndex); Compiler::emitVcpuAsm("SUBI", "1", false, codeLineIndex); Compiler::emitVcpuAsm("STW", "_" + Compiler::getIntegerVars()[varIndex]._name, false, codeLineIndex); return true; } bool keywordON(Compiler::CodeLine& codeLine, int codeLineIndex, int tokenIndex, size_t foundPos, KeywordFuncResult& result) { UNREFERENCED_PARAM(result); UNREFERENCED_PARAM(tokenIndex); std::string code = codeLine._code; Expression::strToUpper(code); size_t gotoOffset = code.find("GOTO"); size_t gosubOffset = code.find("GOSUB"); if(gotoOffset == std::string::npos && gosubOffset == std::string::npos) { fprintf(stderr, "Compiler::keywordON() : Syntax error in '%s' on line %d\n", codeLine._text.c_str(), codeLineIndex + 1); return false; } size_t gSize = (gotoOffset != std::string::npos) ? 4 : 5; size_t gOffset = (gotoOffset != std::string::npos) ? gotoOffset : gosubOffset; // Parse ON field Expression::Numeric onValue; std::string onToken = codeLine._code.substr(foundPos, gOffset - (foundPos + 1)); Expression::stripWhitespace(onToken); Compiler::parseExpression(codeLine, codeLineIndex, onToken, onValue); Compiler::emitVcpuAsm("STW", "register0", false, codeLineIndex); // Parse labels std::vector<size_t> gOffsets; std::vector<std::string> gotoTokens = Expression::tokenise(codeLine._code.substr(gOffset + gSize), ',', gOffsets, false); if(gotoTokens.size() < 1) { fprintf(stderr, "Compiler::keywordON() : Syntax error, must have at least one label after GOTO, in '%s' on line %d\n", codeLine._text.c_str(), codeLineIndex + 1); return false; } // Create label LUT Compiler::getCodeLines()[codeLineIndex]._onGotoGosubLut._lut.clear(); for(int i=0; i<int(gotoTokens.size()); i++) { std::string gotoLabel = gotoTokens[i]; Expression::stripWhitespace(gotoLabel); int labelIndex = Compiler::findLabel(gotoLabel); if(labelIndex == -1) { fprintf(stderr, "Compiler::keywordON() : invalid label %s in slot %d in '%s' on line %d\n", gotoLabel.c_str(), i, codeLine._text.c_str(), codeLineIndex + 1); Compiler::getCodeLines()[codeLineIndex]._onGotoGosubLut._lut.clear(); return false; } // Only ON GOSUB needs a PUSH, (emitted in createVasmCode()) if(gosubOffset != std::string::npos) Compiler::getLabels()[labelIndex]._gosub = true; // Create lookup table out of label addresses Compiler::getCodeLines()[codeLineIndex]._onGotoGosubLut._lut.push_back(labelIndex); } // Allocate giga memory for LUT int size = int(gotoTokens.size()) * 2; uint16_t address; if(!Memory::getFreeRAM(Memory::FitAscending, size, 0x0200, Compiler::getRuntimeStart(), address)) { fprintf(stderr, "Compiler::keywordON() : Not enough RAM for onGotoGosub LUT of size %d\n", size); return false; } Compiler::getCodeLines()[codeLineIndex]._onGotoGosubLut._address = address; Compiler::getCodeLines()[codeLineIndex]._onGotoGosubLut._name = "lut_" + Expression::wordToHexString(address); Compiler::emitVcpuAsm("ADDW", "register0", false, codeLineIndex); Compiler::emitVcpuAsm("STW", "register0", false, codeLineIndex); Compiler::emitVcpuAsm("LDWI", Compiler::getCodeLines()[codeLineIndex]._onGotoGosubLut._name, false, codeLineIndex); Compiler::emitVcpuAsm("ADDW", "register0", false, codeLineIndex); #ifdef ARRAY_INDICES_ONE Compiler::emitVcpuAsm("SUBI", "2", false, codeLineIndex); // enable this to start at 1 instead of 0 #endif Compiler::emitVcpuAsm("DEEK", "", false, codeLineIndex); Compiler::emitVcpuAsm("CALL", "giga_vAC", false, codeLineIndex); return true; } bool keywordGOTO(Compiler::CodeLine& codeLine, int codeLineIndex, int tokenIndex, size_t foundPos, KeywordFuncResult& result) { UNREFERENCED_PARAM(result); UNREFERENCED_PARAM(tokenIndex); // Parse labels std::vector<size_t> gotoOffsets; std::vector<std::string> gotoTokens = Expression::tokenise(codeLine._code.substr(foundPos), ',', gotoOffsets, false); if(gotoTokens.size() < 1 || gotoTokens.size() > 2) { fprintf(stderr, "Compiler::keywordGOTO() : Syntax error, must have one or two parameters, e.g. 'GOTO 200' or 'GOTO k+1,default' : in '%s' on line %d\n", codeLine._text.c_str(), codeLineIndex + 1); return false; } // Parse GOTO field Expression::Numeric gotoValue; std::string gotoToken = gotoTokens[0]; Expression::stripWhitespace(gotoToken); bool useBRA = false; if(gotoToken[0] == '&') { useBRA = true; gotoToken.erase(0, 1); } int labelIndex = Compiler::findLabel(gotoToken); if(labelIndex == -1) { Compiler::setCreateNumericLabelLut(true); parseExpression(codeLine, codeLineIndex, gotoToken, gotoValue); Compiler::emitVcpuAsm("STW", "numericLabel", false, codeLineIndex); // Default label exists if(gotoTokens.size() == 2) { std::string defaultToken = gotoTokens[1]; Expression::stripWhitespace(defaultToken); labelIndex = Compiler::findLabel(defaultToken); if(labelIndex == -1) { fprintf(stderr, "Compiler::keywordGOTO() : Default label does not exist : in '%s' on line %d\n", codeLine._text.c_str(), codeLineIndex + 1); return false; } Compiler::emitVcpuAsm("LDWI", "_" + Compiler::getLabels()[labelIndex]._name, false, codeLineIndex); } // No default label else { Compiler::emitVcpuAsm("LDI", "0", false, codeLineIndex); } Compiler::emitVcpuAsm("STW", "defaultLabel", false, codeLineIndex); // Call gotoNumericLabel if(Assembler::getUseOpcodeCALLI()) { Compiler::emitVcpuAsm("CALLI", "gotoNumericLabel", false, codeLineIndex); } else { Compiler::emitVcpuAsm("LDWI", "gotoNumericLabel", false, codeLineIndex); Compiler::emitVcpuAsm("CALL", "giga_vAC", false, codeLineIndex); } return true; } // Within same page, (validation check on same page branch may fail after outputCode(), user will be warned) if(useBRA) { Compiler::emitVcpuAsm("BRA", "_" + gotoToken, false, codeLineIndex); } // Long jump else { if(Assembler::getUseOpcodeCALLI()) { Compiler::emitVcpuAsm("CALLI", "_" + gotoToken, false, codeLineIndex); } else { Compiler::emitVcpuAsm("LDWI", "_" + gotoToken, false, codeLineIndex); Compiler::emitVcpuAsm("CALL", "giga_vAC", false, codeLineIndex); } } return true; } bool keywordGOSUB(Compiler::CodeLine& codeLine, int codeLineIndex, int tokenIndex, size_t foundPos, KeywordFuncResult& result) { UNREFERENCED_PARAM(result); UNREFERENCED_PARAM(tokenIndex); // Parse labels std::vector<size_t> gosubOffsets; std::vector<std::string> gosubTokens = Expression::tokenise(codeLine._code.substr(foundPos), ',', gosubOffsets, false); if(gosubTokens.size() < 1 || gosubTokens.size() > 2) { fprintf(stderr, "Compiler::keywordGOSUB() : Syntax error, must have one or two parameters, e.g. 'GOSUB 200' or 'GOSUB k+1,default' : in '%s' on line %d\n", codeLine._text.c_str(), codeLineIndex + 1); return false; } // Parse GOSUB field Expression::Numeric gosubValue; std::string gosubToken = gosubTokens[0]; Expression::stripWhitespace(gosubToken); int labelIndex = Compiler::findLabel(gosubToken); if(labelIndex == -1) { Compiler::setCreateNumericLabelLut(true); parseExpression(codeLine, codeLineIndex, gosubToken, gosubValue); Compiler::emitVcpuAsm("STW", "numericLabel", false, codeLineIndex); // Default label exists if(gosubTokens.size() == 2) { std::string defaultToken = gosubTokens[1]; Expression::stripWhitespace(defaultToken); labelIndex = Compiler::findLabel(defaultToken); if(labelIndex == -1) { fprintf(stderr, "Compiler::keywordGOSUB() : Default label does not exist : in '%s' on line %d\n", codeLine._text.c_str(), codeLineIndex + 1); return false; } Compiler::getLabels()[labelIndex]._gosub = true; Compiler::emitVcpuAsm("LDWI", "_" + Compiler::getLabels()[labelIndex]._name, false, codeLineIndex); } // No default label else { Compiler::emitVcpuAsm("LDI", "0", false, codeLineIndex); } Compiler::emitVcpuAsm("STW", "defaultLabel", false, codeLineIndex); // Call gosubNumericLabel if(Assembler::getUseOpcodeCALLI()) { Compiler::emitVcpuAsm("CALLI", "gosubNumericLabel", false, codeLineIndex); } else { Compiler::emitVcpuAsm("LDWI", "gosubNumericLabel", false, codeLineIndex); Compiler::emitVcpuAsm("CALL", "giga_vAC", false, codeLineIndex); } return true; } // CALL label Compiler::getLabels()[labelIndex]._gosub = true; if(Assembler::getUseOpcodeCALLI()) { Compiler::emitVcpuAsm("CALLI", "_" + gosubToken, false, codeLineIndex); } else { Compiler::emitVcpuAsm("LDWI", "_" + gosubToken, false, codeLineIndex); Compiler::emitVcpuAsm("CALL", "giga_vAC", false, codeLineIndex); } return true; } bool keywordRETURN(Compiler::CodeLine& codeLine, int codeLineIndex, int tokenIndex, size_t foundPos, KeywordFuncResult& result) { UNREFERENCED_PARAM(result); UNREFERENCED_PARAM(foundPos); UNREFERENCED_PARAM(tokenIndex); UNREFERENCED_PARAM(codeLine); Compiler::emitVcpuAsm("POP", "", false, codeLineIndex); Compiler::emitVcpuAsm("RET", "", false, codeLineIndex); return true; } bool keywordCLS(Compiler::CodeLine& codeLine, int codeLineIndex, int tokenIndex, size_t foundPos, KeywordFuncResult& result) { UNREFERENCED_PARAM(result); UNREFERENCED_PARAM(foundPos); UNREFERENCED_PARAM(tokenIndex); if(codeLine._tokens.size() > 2) { fprintf(stderr, "Compiler::keywordCLS() : Syntax error in '%s' on line %d\n", codeLine._text.c_str(), codeLineIndex + 1); return false; } if(codeLine._tokens.size() == 2) { Expression::Numeric param; parseExpression(codeLine, codeLineIndex, codeLine._tokens[1], param); Compiler::emitVcpuAsm("STW", "clsAddress", false, codeLineIndex); if(Assembler::getUseOpcodeCALLI()) { Compiler::emitVcpuAsm("CALLI", "clearScreen", false, codeLineIndex); } else { Compiler::emitVcpuAsm("LDWI", "clearScreen", false, codeLineIndex); Compiler::emitVcpuAsm("CALL", "giga_vAC", false, codeLineIndex); } } else { if(Assembler::getUseOpcodeCALLI()) { Compiler::emitVcpuAsm("CALLI", "clearVertBlinds", false, codeLineIndex); } else { Compiler::emitVcpuAsm("LDWI", "clearVertBlinds", false, codeLineIndex); Compiler::emitVcpuAsm("CALL", "giga_vAC", false, codeLineIndex); } } return true; } bool keywordPRINT(Compiler::CodeLine& codeLine, int codeLineIndex, int tokenIndex, size_t foundPos, KeywordFuncResult& result) { UNREFERENCED_PARAM(result); UNREFERENCED_PARAM(tokenIndex); // Parse print tokens //std::vector<std::string> tokens = Expression::tokeniseLine(codeLine._code.substr(foundPos), ";"); std::vector<std::string> tokens = Expression::tokenise(codeLine._code.substr(foundPos), ';', false, false); for(int i=0; i<int(tokens.size()); i++) { Expression::Numeric numeric; int varIndex = -1, constIndex = -1, strIndex = -1; uint32_t expressionType = Compiler::isExpression(tokens[i], varIndex, constIndex, strIndex); if((expressionType & Expression::HasStringKeywords) && (expressionType & Expression::HasOptimisedPrint)) { // Prints text on the fly without creating strings Expression::setEnableOptimisedPrint(true); Expression::parse(tokens[i], codeLineIndex, numeric); Expression::setEnableOptimisedPrint(false); } else if(expressionType & Expression::HasFunctions) { Expression::parse(tokens[i], codeLineIndex, numeric); if(numeric._varType == Expression::Number) { Compiler::emitVcpuAsm("%PrintInt16", Expression::wordToHexString(int16_t(std::lround(numeric._value))), false, codeLineIndex); } else { Compiler::emitVcpuAsm("LDW", Expression::byteToHexString(uint8_t(Compiler::getTempVarStart())), false, codeLineIndex); Compiler::emitVcpuAsm("%PrintAcInt16", "", false, codeLineIndex); } } else if((expressionType & Expression::HasIntVars) && (expressionType & Expression::HasOperators)) { Expression::parse(tokens[i], codeLineIndex, numeric); if(numeric._varType == Expression::Number) { Compiler::emitVcpuAsm("%PrintInt16", Expression::wordToHexString(int16_t(std::lround(numeric._value))), false, codeLineIndex); } else { Compiler::emitVcpuAsm("LDW", Expression::byteToHexString(uint8_t(Compiler::getTempVarStart())), false, codeLineIndex); Compiler::emitVcpuAsm("%PrintAcInt16", "", false, codeLineIndex); } } else if(expressionType & Expression::HasIntVars) { Expression::parse(tokens[i], codeLineIndex, numeric); if(varIndex >= 0) { if(Compiler::getIntegerVars()[varIndex]._varType == Compiler::VarArray) { Compiler::emitVcpuAsm("LDW", Expression::byteToHexString(uint8_t(Compiler::getTempVarStart())), false, codeLineIndex); Compiler::emitVcpuAsm("%PrintAcInt16", "", false, codeLineIndex); } else { switch(numeric._int16Byte) { case Expression::Int16Low: Compiler::emitVcpuAsm("LD", "_" + Compiler::getIntegerVars()[varIndex]._name, false, codeLineIndex); break; case Expression::Int16High: Compiler::emitVcpuAsm("LD", "_" + Compiler::getIntegerVars()[varIndex]._name + " + 1", false, codeLineIndex); break; case Expression::Int16Both: Compiler::emitVcpuAsm("LDW", "_" + Compiler::getIntegerVars()[varIndex]._name, false, codeLineIndex); break; default: break; } Compiler::emitVcpuAsm("%PrintAcInt16", "", false, codeLineIndex); } } else { Compiler::emitVcpuAsm("%PrintAcInt16", "", false, codeLineIndex); } } else if(expressionType & Expression::HasStrVars) { if(strIndex >= 0) { std::string strName = Compiler::getStringVars()[strIndex]._name; Compiler::emitVcpuAsm("%PrintString", "_" + strName, false, codeLineIndex); } } else if(expressionType & Expression::HasKeywords) { Expression::parse(tokens[i], codeLineIndex, numeric); Compiler::emitVcpuAsm("LDW", Expression::byteToHexString(uint8_t(Compiler::getTempVarStart())), false, codeLineIndex); Compiler::emitVcpuAsm("%PrintAcInt16", "", false, codeLineIndex); } else if(expressionType & Expression::HasOperators) { Expression::parse(tokens[i], codeLineIndex, numeric); Compiler::emitVcpuAsm("%PrintInt16", Expression::wordToHexString(int16_t(std::lround(numeric._value))), false, codeLineIndex); } else if(expressionType & Expression::HasStrings) { size_t lquote = tokens[i].find_first_of("\""); size_t rquote = tokens[i].find_first_of("\"", lquote + 1); if(lquote != std::string::npos && rquote != std::string::npos) { if(rquote == lquote + 1) continue; // skip empty strings std::string str = tokens[i].substr(lquote + 1, rquote - (lquote + 1)); // Create string std::string name; uint16_t address; if(Compiler::getOrCreateString(codeLine, codeLineIndex, str, name, address) == -1) return false; // Print string Compiler::emitVcpuAsm("%PrintString", "_" + name, false, codeLineIndex); } } else if(expressionType == Expression::HasStrConsts) { // Print constant string std::string internalName = Compiler::getConstants()[constIndex]._internalName; Compiler::emitVcpuAsm("%PrintString", "_" + internalName, false, codeLineIndex); } else if(expressionType == Expression::HasIntConsts) { // Print constant int int16_t data = Compiler::getConstants()[constIndex]._data; Compiler::emitVcpuAsm("%PrintInt16", Expression::wordToHexString(data), false, codeLineIndex); } else if(expressionType == Expression::HasNumbers) { // If valid expression if(Expression::parse(tokens[i], codeLineIndex, numeric)) { Compiler::emitVcpuAsm("%PrintInt16", Expression::wordToHexString(int16_t(std::lround(numeric._value))), false, codeLineIndex); } } } // New line if(codeLine._code[codeLine._code.size() - 1] != ';') { Compiler::emitVcpuAsm("%NewLine", "", false, codeLineIndex); } return true; } bool keywordINPUT(Compiler::CodeLine& codeLine, int codeLineIndex, int tokenIndex, size_t foundPos, KeywordFuncResult& result) { UNREFERENCED_PARAM(result); UNREFERENCED_PARAM(tokenIndex); // Tokenise string and vars std::vector<std::string> strings; std::string text = codeLine._code.substr(foundPos); Expression::stripNonStringWhitespace(text); std::vector<std::string> tokens = Expression::tokenise(text, ',', false, false); std::string code = Expression::stripStrings(text, strings, true); std::vector<std::string> varTokens = Expression::tokenise(code, ',', false, false); if(varTokens.size() < 1 || (strings.size() > varTokens.size() + 1)) { fprintf(stderr, "Compiler::keywordINPUT() : Syntax error in INPUT statement, must be 'INPUT <heading string>, <int/str var0>, <prompt string0>, ... <int/str varN>, <prompt stringN>', in '%s' on line %d\n", codeLine._code.c_str(), codeLineIndex + 1); return false; } // Print heading string bool foundHeadingString = false; if(tokens.size()) { if(!Expression::isValidString(tokens[0])) { fprintf(stderr, "Compiler::keywordINPUT() : Syntax error in heading string '%s' of INPUT statement, in '%s' on line %d\n", tokens[0].c_str(), codeLine._code.c_str(), codeLineIndex + 1); return false; } size_t lquote = tokens[0].find_first_of("\""); size_t rquote = tokens[0].find_first_of("\"", lquote + 1); if(lquote != std::string::npos && rquote != std::string::npos) { // Skip empty strings if(rquote > lquote + 1) { std::string str = tokens[0].substr(lquote + 1, rquote - (lquote + 1)); // Create string std::string name; uint16_t address; if(Compiler::getOrCreateString(codeLine, codeLineIndex, str, name, address) == -1) return false; // Print string Compiler::emitVcpuAsm("%PrintString", "_" + name, false, codeLineIndex); foundHeadingString = true; } } } // INPUT vars/strs/types LUTs, (extra 0x0000 delimiter used by VASM runtime) std::vector<uint16_t> varsLut(varTokens.size()); std::vector<uint16_t> strsLut(varTokens.size()); std::vector<uint16_t> typesLut(varTokens.size() + 1, 0x0000); // Loop through vars for(int i=0; i<int(varTokens.size()); i++) { // Int var exists bool isStrVar = false; int intVar = Compiler::findVar(varTokens[i]); if(intVar >= 0) { varsLut[i] = Compiler::getIntegerVars()[intVar]._address; typesLut[i] = Compiler::VarInt16; continue; } // Str var exists else { if(varTokens[i].back() == '$' && Expression::isVarNameValid(varTokens[i])) { isStrVar = true; int strIndex = Compiler::findStr(varTokens[i]); if(strIndex >= 0) { varsLut[i] = Compiler::getStringVars()[strIndex]._address; typesLut[i] = Compiler::VarStr; continue; } } } // Create int var int varIndex = 0; if(!isStrVar) { Compiler::createIntVar(varTokens[i], 0, 0, codeLine, codeLineIndex, false, varIndex); if(varIndex == -1) return false; varsLut[i] = Compiler::getIntegerVars()[varIndex]._address; typesLut[i] = Compiler::VarInt16; } // Create str var else { uint16_t address; varIndex = getOrCreateString(codeLine, codeLineIndex, "", varTokens[i], address, USER_STR_SIZE, false); if(varIndex == -1) return false; varsLut[i] = Compiler::getStringVars()[varIndex]._address; typesLut[i] = Compiler::VarStr; } } // Loop through strs for(int i=0; i<int(varTokens.size()); i++) { // Create string std::string name; uint16_t address; int index = (foundHeadingString) ? i + 1 : i; std::string str = (index < int(strings.size())) ? strings[index] : "\"?\""; size_t fquote = str.find_first_of('"'); size_t lquote = str.find_last_of('"'); // Semicolons if(str.size() > lquote + 1 && str[lquote + 1] != ';') typesLut[i] |= 0x40; if(str.size() > lquote + 1 && str[lquote + 1] == ';') str.erase(lquote + 1, 1); if(str.back() != ';') typesLut[i] |= 0x80; if(str.back() == ';') str.erase(str.size() - 1, 1); // Text length field if(str.size() > lquote + 1 && isdigit((unsigned char)str[lquote + 1])) { uint8_t length; std::string field = str.substr(lquote + 1); if(!Expression::stringToU8(field, length)) { fprintf(stderr, "Compiler::keywordINPUT() : Syntax error in text size field of string '%s' of INPUT statement, in '%s' on line %d\n", str.c_str(), codeLine._code.c_str(), codeLineIndex + 1); return false; } str.erase(lquote + 1, field.size()); typesLut[i] |= (length + 1) << 8; // increment length as INPUT VASM code counts cursor } // Remove quotes, (remove last quote first) str.erase(lquote, 1); str.erase(fquote, 1); if(Compiler::getOrCreateString(codeLine, codeLineIndex, str, name, address) == -1) return false; strsLut[i] = address; } // INPUT LUTs const int lutSize = 3; uint16_t lutAddr, varsAddr, strsAddr, typesAddr; if(!Memory::getFreeRAM(Memory::FitAscending, lutSize*2, 0x0200, Compiler::getRuntimeStart(), lutAddr)) { fprintf(stderr, "Compiler::keywordINPUT() : Not enough RAM for INPUT LUT of size %d, in '%s' on line %d\n", lutSize*2, codeLine._code.c_str(), codeLineIndex + 1); return false; } if(!Memory::getFreeRAM(Memory::FitAscending, int(varsLut.size()*2), 0x0200, Compiler::getRuntimeStart(), varsAddr)) { fprintf(stderr, "Compiler::keywordINPUT() : Not enough RAM for INPUT Vars LUT of size %d, in '%s' on line %d\n", int(varsLut.size()*2), codeLine._code.c_str(), codeLineIndex + 1); return false; } if(!Memory::getFreeRAM(Memory::FitAscending, int(strsLut.size()*2), 0x0200, Compiler::getRuntimeStart(), strsAddr)) { fprintf(stderr, "Compiler::keywordINPUT() : Not enough RAM for INPUT Strings LUT of size %d, in '%s' on line %d\n", int(strsLut.size()*2), codeLine._code.c_str(), codeLineIndex + 1); return false; } if(!Memory::getFreeRAM(Memory::FitAscending, int(typesLut.size()*2), 0x0200, Compiler::getRuntimeStart(), typesAddr)) { fprintf(stderr, "Compiler::keywordINPUT() : Not enough RAM for INPUT Var Types LUT of size %d, in '%s' on line %d\n", int(typesLut.size()*2), codeLine._code.c_str(), codeLineIndex + 1); return false; } Compiler::getCodeLines()[codeLineIndex]._inputLut = {lutAddr, varsAddr, strsAddr, typesAddr, varsLut, strsLut, typesLut}; // save LUT in global codeLine not local copy Compiler::emitVcpuAsm("LDWI", Expression::wordToHexString(lutAddr), false, codeLineIndex); Compiler::emitVcpuAsm("%Input", "", false, codeLineIndex); return true; } bool keywordFOR(Compiler::CodeLine& codeLine, int codeLineIndex, int tokenIndex, size_t foundPos, KeywordFuncResult& result) { UNREFERENCED_PARAM(result); UNREFERENCED_PARAM(tokenIndex); bool optimise = true; int varIndex, constIndex, strIndex; uint32_t expressionType; // Parse first line of FOR loop std::string code = codeLine._code; Expression::strToUpper(code); size_t equals, to, step; if((equals = code.find("=")) == std::string::npos) { fprintf(stderr, "Compiler::keywordFOR() : Syntax error, (missing '='), in '%s' on line %d\n", codeLine._text.c_str(), codeLineIndex + 1); return false; } bool farJump = (code.find("&TO") == std::string::npos); if((to = code.find("TO")) == std::string::npos) { fprintf(stderr, "Compiler::keywordFOR() : Syntax error, (missing 'TO'), in '%s' on line %d\n", codeLine._text.c_str(), codeLineIndex + 1); return false; } step = code.find("STEP"); // Maximum of 4 nested loops if(Compiler::getForNextDataStack().size() == 4) { fprintf(stderr, "Compiler::keywordFOR() : Syntax error, (maximum nested loops is 4), in '%s' on line %d\n", codeLine._text.c_str(), codeLineIndex + 1); return false; } // Nested loops temporary variables uint16_t offset = uint16_t(Compiler::getForNextDataStack().size()) * 4; uint16_t varEnd = LOOP_VAR_START + offset; uint16_t varStep = LOOP_VAR_START + offset + 2; // Loop start int16_t loopStart = 0; int toOffset = (farJump) ? 0 : -1; std::string startToken = codeLine._code.substr(equals + 1, to - (equals + 1) + toOffset); Expression::stripWhitespace(startToken); expressionType = Compiler::isExpression(startToken, varIndex, constIndex, strIndex); if((expressionType & Expression::HasIntVars) || (expressionType & Expression::HasKeywords) || (expressionType & Expression::HasFunctions)) optimise = false; // Var counter, (create or update if being reused) std::string var = codeLine._code.substr(foundPos, equals - foundPos); Expression::stripWhitespace(var); int varCounter = Compiler::findVar(var); (varCounter < 0) ? Compiler::createIntVar(var, loopStart, 0, codeLine, codeLineIndex, false, varCounter) : Compiler::updateVar(loopStart, codeLine, varCounter, false); // Loop end int16_t loopEnd = 0; size_t end = (step == std::string::npos) ? codeLine._code.size() : step; std::string endToken = codeLine._code.substr(to + 2, end - (to + 2)); Expression::stripWhitespace(endToken); expressionType = Compiler::isExpression(endToken, varIndex, constIndex, strIndex); if((expressionType & Expression::HasIntVars) || (expressionType & Expression::HasKeywords) || (expressionType & Expression::HasFunctions)) optimise = false; // Loop step int16_t loopStep = 1; std::string stepToken; if(step != std::string::npos) { end = codeLine._code.size(); stepToken = codeLine._code.substr(step + 4, end - (step + 4)); Expression::stripWhitespace(stepToken); expressionType = Compiler::isExpression(stepToken, varIndex, constIndex, strIndex); if((expressionType & Expression::HasIntVars) || (expressionType & Expression::HasKeywords) || (expressionType & Expression::HasFunctions)) optimise = false; } Expression::Numeric startNumeric, endNumeric, stepNumeric; if(optimise) { // Parse start Expression::parse(startToken, codeLineIndex, startNumeric); loopStart = int16_t(std::lround(startNumeric._value)); // Parse end Expression::parse(endToken, codeLineIndex, endNumeric); loopEnd = int16_t(std::lround(endNumeric._value)); // Parse step if(stepToken.size()) { Expression::parse(stepToken, codeLineIndex, stepNumeric); loopStep = int16_t(std::lround(stepNumeric._value)); if(abs(loopStep) > 255) optimise = false; } else { // Auto step based on start and end loopStep = (loopEnd >= loopStart) ? 1 : -1; } // 8bit constants if(optimise && startNumeric._isValid && loopStart >= 0 && loopStart <= 255 && endNumeric._isValid && loopEnd >= 0 && loopEnd <= 255) { Compiler::emitVcpuAsm("LDI", std::to_string(loopStart), false, codeLineIndex); Compiler::emitVcpuAsm("STW", "_" + Compiler::getIntegerVars()[varCounter]._name, false, codeLineIndex); } // 16bit constants require variables else { optimise = false; Compiler::emitVcpuAsm("LDWI", std::to_string(loopStart), false, codeLineIndex); Compiler::emitVcpuAsm("STW", "_" + Compiler::getIntegerVars()[varCounter]._name, false, codeLineIndex); Compiler::emitVcpuAsm("LDWI", std::to_string(loopEnd), false, codeLineIndex); Compiler::emitVcpuAsm("STW", Expression::byteToHexString(uint8_t(varEnd)), false, codeLineIndex); Compiler::emitVcpuAsm("LDWI", std::to_string(loopStep), false, codeLineIndex); Compiler::emitVcpuAsm("STW", Expression::byteToHexString(uint8_t(varStep)), false, codeLineIndex); } } else { // Parse start parseExpression(codeLine, codeLineIndex, startToken, startNumeric); loopStart = int16_t(std::lround(startNumeric._value)); Compiler::emitVcpuAsm("STW", "_" + Compiler::getIntegerVars()[varCounter]._name, false, codeLineIndex); // Parse end parseExpression(codeLine, codeLineIndex, endToken, endNumeric); loopEnd = int16_t(std::lround(endNumeric._value)); Compiler::emitVcpuAsm("STW", Expression::byteToHexString(uint8_t(varEnd)), false, codeLineIndex); // Parse step if(stepToken.size()) { parseExpression(codeLine, codeLineIndex, stepToken, stepNumeric); loopStep = int16_t(std::lround(stepNumeric._value)); } else { loopStep = 1; Compiler::emitVcpuAsm("LDI", std::to_string(loopStep), false, codeLineIndex); } Compiler::emitVcpuAsm("STW", Expression::byteToHexString(uint8_t(varStep)), false, codeLineIndex); } // Label and stack Compiler::setNextInternalLabel("_next_" + Expression::wordToHexString(Compiler::getVasmPC())); Compiler::getForNextDataStack().push({varCounter, Compiler::getNextInternalLabel(), loopEnd, loopStep, varEnd, varStep, farJump, optimise, codeLineIndex}); return true; } bool keywordNEXT(Compiler::CodeLine& codeLine, int codeLineIndex, int tokenIndex, size_t foundPos, KeywordFuncResult& result) { UNREFERENCED_PARAM(result); UNREFERENCED_PARAM(tokenIndex); if(codeLine._tokens.size() != 2) { fprintf(stderr, "Compiler::keywordNEXT() : Syntax error, (wrong number of tokens), in '%s' on line %d\n", codeLine._text.c_str(), codeLineIndex + 1); return false; } std::string var = codeLine._code.substr(foundPos); int varIndex = Compiler::findVar(codeLine._tokens[1]); if(varIndex < 0) { fprintf(stderr, "Compiler::keywordNEXT() : Syntax error, (bad var), in '%s' on line %d\n", codeLine._text.c_str(), codeLineIndex + 1); return false; } // Pop stack for this nested loop if(Compiler::getForNextDataStack().empty()) { fprintf(stderr, "Compiler::keywordNEXT() : Syntax error, missing FOR statement, for '%s' on line %d\n", codeLine._text.c_str(), codeLineIndex + 1); return false; } Compiler::ForNextData forNextData = Compiler::getForNextDataStack().top(); Compiler::getForNextDataStack().pop(); if(varIndex != forNextData._varIndex) { fprintf(stderr, "Compiler::keywordNEXT() : Syntax error, (wrong var), in '%s' on line %d\n", codeLine._text.c_str(), codeLineIndex + 1); return false; } std::string varName = Compiler::getIntegerVars()[varIndex]._name; std::string labName = forNextData._labelName; int16_t loopEnd = forNextData._loopEnd; int16_t loopStep = forNextData._loopStep; uint16_t varEnd = forNextData._varEnd; uint16_t varStep = forNextData._varStep; bool farJump = forNextData._farJump; bool optimise = forNextData._optimise; std::string forNextCmd; if(optimise) { if(abs(loopStep) == 1) { // Increment/decrement step forNextCmd = (loopStep > 0) ? (farJump) ? "%ForNextFarInc" : "%ForNextInc" : (farJump) ? "%ForNextFarDec" : "%ForNextDec"; Compiler::emitVcpuAsm(forNextCmd, "_" + varName + " " + labName + " " + std::to_string(loopEnd), false, codeLineIndex); } else { // Additive/subtractive step forNextCmd = (loopStep > 0) ? (farJump) ? "%ForNextFarAdd" : "%ForNextAdd" : (farJump) ? "%ForNextFarSub" : "%ForNextSub"; Compiler::emitVcpuAsm(forNextCmd, "_" + varName + " " + labName + " " + std::to_string(loopEnd) + " " + std::to_string(abs(loopStep)), false, codeLineIndex); } } else { // TODO: this can fail for corner cases // Positive/negative variable step forNextCmd = (loopStep > 0) ? (farJump) ? "%ForNextFarVarPos" : "%ForNextVarPos" : (farJump) ? "%ForNextFarVarNeg" : "%ForNextVarNeg"; Compiler::emitVcpuAsm(forNextCmd, "_" + varName + " " + labName + " " + Expression::byteToHexString(uint8_t(varEnd)) + " " + Expression::byteToHexString(uint8_t(varStep)), false, codeLineIndex); } return true; } bool keywordIF(Compiler::CodeLine& codeLine, int codeLineIndex, int tokenIndex, size_t foundPos, KeywordFuncResult& result) { UNREFERENCED_PARAM(result); UNREFERENCED_PARAM(tokenIndex); bool ifElseEndif = false; // IF std::string code = Compiler::getCodeLines()[codeLineIndex]._code; Expression::strToUpper(code); size_t offsetIF = code.find("IF"); // THEN code = codeLine._code; Expression::strToUpper(code); size_t offsetTHEN = code.find("THEN"); if(offsetTHEN == std::string::npos) ifElseEndif = true; // Condition Expression::Numeric condition; std::string conditionToken = codeLine._code.substr(foundPos, offsetTHEN - foundPos); parseExpression(codeLine, codeLineIndex, conditionToken, condition); if(condition._ccType == Expression::BooleanCC) Compiler::emitVcpuAsm("%JumpFalse", "", false, codeLineIndex); // Boolean condition requires this extra check int jmpIndex = int(Compiler::getCodeLines()[codeLineIndex]._vasm.size()) - 1; // Bail early as we assume this is an IF ELSE ENDIF block if(ifElseEndif) { Compiler::getElseIfDataStack().push({jmpIndex, "", codeLineIndex, Compiler::IfBlock, condition._ccType}); return true; } // Action std::string actionToken = Compiler::getCodeLines()[codeLineIndex]._code.substr(offsetIF + offsetTHEN + 4); if(actionToken.size() == 0) { fprintf(stderr, "Compiler::keywordIF() : Syntax error, IF THEN <action>, (missing action), in '%s' on line %d\n", codeLine._text.c_str(), codeLineIndex + 1); return false; } Expression::trimWhitespace(actionToken); std::string actionText = Expression::collapseWhitespaceNotStrings(actionToken); // Multi-statements int varIndex, strIndex; if(Compiler::parseMultiStatements(actionText, codeLine, codeLineIndex, varIndex, strIndex) == Compiler::StatementError) return false; // Create label on next line of vasm code Compiler::setNextInternalLabel("_else_" + Expression::wordToHexString(Compiler::getVasmPC())); std::string nextInternalLabel = Compiler::getNextInternalLabel() + " " + std::to_string(Compiler::incJumpFalseUniqueId()); // Update if's jump to this new label Compiler::VasmLine* vasm = &Compiler::getCodeLines()[codeLineIndex]._vasm[jmpIndex]; switch(condition._ccType) { case Expression::BooleanCC: vasm->_code = "JumpFalse" + std::string(OPCODE_TRUNC_SIZE - (sizeof("JumpFalse")-1), ' ') + nextInternalLabel; break; case Expression::NormalCC: addLabelToJumpCC(Compiler::getCodeLines()[codeLineIndex]._vasm, nextInternalLabel); break; case Expression::FastCC: addLabelToJumpCC(Compiler::getCodeLines()[codeLineIndex]._vasm, Compiler::getNextInternalLabel()); break; default: break; } return true; } bool keywordELSEIF(Compiler::CodeLine& codeLine, int codeLineIndex, int tokenIndex, size_t foundPos, KeywordFuncResult& result) { UNREFERENCED_PARAM(result); UNREFERENCED_PARAM(tokenIndex); // Check stack for this IF ELSE ENDIF block if(Compiler::getElseIfDataStack().empty()) { fprintf(stderr, "Compiler::keywordELSEIF() : Syntax error, missing IF statement, for '%s' on line %d\n", codeLine._text.c_str(), codeLineIndex + 1); return false; } Compiler::ElseIfData elseIfData = Compiler::getElseIfDataStack().top(); int jmpIndex = elseIfData._jmpIndex; int codeIndex = elseIfData._codeLineIndex; Expression::CCType ccType = elseIfData._ccType; Compiler::getElseIfDataStack().pop(); if(elseIfData._ifElseEndType != Compiler::IfBlock && elseIfData._ifElseEndType != Compiler::ElseIfBlock) { fprintf(stderr, "Compiler::keywordELSEIF() : Syntax error, ELSEIF follows IF or ELSEIF, for '%s' on line %d\n", codeLine._text.c_str(), codeLineIndex + 1); return false; } // Jump to endif for previous BASIC line if(Assembler::getUseOpcodeCALLI()) { Compiler::emitVcpuAsm("CALLI", "CALLI_JUMP", false, codeLineIndex - 1); Compiler::getEndIfDataStack().push({int(Compiler::getCodeLines()[codeLineIndex - 1]._vasm.size()) - 1, codeLineIndex - 1}); } else { // There are no checks to see if this BRA's destination is in the same page, programmer discretion required when using this feature if(ccType == Expression::FastCC) { Compiler::emitVcpuAsm("BRA", "BRA_JUMP", false, codeLineIndex - 1); Compiler::getEndIfDataStack().push({int(Compiler::getCodeLines()[codeLineIndex - 1]._vasm.size()) - 1, codeLineIndex - 1}); } else { Compiler::emitVcpuAsm("LDWI", "LDWI_JUMP", false, codeLineIndex - 1); Compiler::emitVcpuAsm("CALL", "giga_vAC", false, codeLineIndex - 1); Compiler::getEndIfDataStack().push({int(Compiler::getCodeLines()[codeLineIndex - 1]._vasm.size()) - 2, codeLineIndex - 1}); } } // Create label on next line of vasm code Compiler::setNextInternalLabel("_elseif_" + Expression::wordToHexString(Compiler::getVasmPC())); std::string nextInternalLabel = Compiler::getNextInternalLabel() + " " + std::to_string(Compiler::incJumpFalseUniqueId()); // Update if's jump to this new label Compiler::VasmLine* vasm = &Compiler::getCodeLines()[codeIndex]._vasm[jmpIndex]; switch(ccType) { case Expression::BooleanCC: vasm->_code = "JumpFalse" + std::string(OPCODE_TRUNC_SIZE - (sizeof("JumpFalse")-1), ' ') + nextInternalLabel; break; case Expression::NormalCC: addLabelToJumpCC(Compiler::getCodeLines()[codeIndex]._vasm, nextInternalLabel); break; case Expression::FastCC: addLabelToJumpCC(Compiler::getCodeLines()[codeIndex]._vasm, Compiler::getNextInternalLabel()); break; default: break; } // Condition Expression::Numeric condition; std::string conditionToken = codeLine._code.substr(foundPos); parseExpression(codeLine, codeLineIndex, conditionToken, condition); if(condition._ccType == Expression::BooleanCC) Compiler::emitVcpuAsm("%JumpFalse", "", false, codeLineIndex); // Boolean condition requires this extra check jmpIndex = int(Compiler::getCodeLines()[codeLineIndex]._vasm.size()) - 1; Compiler::getElseIfDataStack().push({jmpIndex, "", codeLineIndex, Compiler::ElseIfBlock, condition._ccType}); return true; } bool keywordELSE(Compiler::CodeLine& codeLine, int codeLineIndex, int tokenIndex, size_t foundPos, KeywordFuncResult& result) { UNREFERENCED_PARAM(result); UNREFERENCED_PARAM(foundPos); UNREFERENCED_PARAM(tokenIndex); if(codeLine._tokens.size() != 1) { fprintf(stderr, "Compiler::keywordELSE() : Syntax error, (wrong number of tokens), in '%s' on line %d\n", codeLine._text.c_str(), codeLineIndex + 1); return false; } // Check stack for this IF ELSE ENDIF block if(Compiler::getElseIfDataStack().empty()) { fprintf(stderr, "Compiler::keywordELSE() : Syntax error, missing IF statement, for '%s' on line %d\n", codeLine._text.c_str(), codeLineIndex + 1); return false; } Compiler::ElseIfData elseIfData = Compiler::getElseIfDataStack().top(); int jmpIndex = elseIfData._jmpIndex; int codeIndex = elseIfData._codeLineIndex; Expression::CCType ccType = elseIfData._ccType; Compiler::getElseIfDataStack().pop(); // Jump to endif for previous BASIC line if(Assembler::getUseOpcodeCALLI()) { Compiler::emitVcpuAsm("CALLI", "CALLI_JUMP", false, codeLineIndex - 1); Compiler::getEndIfDataStack().push({int(Compiler::getCodeLines()[codeLineIndex - 1]._vasm.size()) - 1, codeLineIndex - 1}); } else { // There are no checks to see if this BRA's destination is in the same page, programmer discretion required when using this feature if(ccType == Expression::FastCC) { Compiler::emitVcpuAsm("BRA", "BRA_JUMP", false, codeLineIndex - 1); Compiler::getEndIfDataStack().push({int(Compiler::getCodeLines()[codeLineIndex - 1]._vasm.size()) - 1, codeLineIndex - 1}); } else { Compiler::emitVcpuAsm("LDWI", "LDWI_JUMP", false, codeLineIndex - 1); Compiler::emitVcpuAsm("CALL", "giga_vAC", false, codeLineIndex - 1); Compiler::getEndIfDataStack().push({int(Compiler::getCodeLines()[codeLineIndex - 1]._vasm.size()) - 2, codeLineIndex - 1}); } } // Create label on next line of vasm code Compiler::setNextInternalLabel("_else_" + Expression::wordToHexString(Compiler::getVasmPC())); std::string nextInternalLabel = Compiler::getNextInternalLabel() + " " + std::to_string(Compiler::incJumpFalseUniqueId()); // Update if's or elseif's jump to this new label Compiler::VasmLine* vasm = &Compiler::getCodeLines()[codeIndex]._vasm[jmpIndex]; switch(ccType) { case Expression::BooleanCC: vasm->_code = "JumpFalse" + std::string(OPCODE_TRUNC_SIZE - (sizeof("JumpFalse")-1), ' ') + nextInternalLabel; break; case Expression::NormalCC: addLabelToJumpCC(Compiler::getCodeLines()[codeIndex]._vasm, nextInternalLabel); break; case Expression::FastCC: addLabelToJumpCC(Compiler::getCodeLines()[codeIndex]._vasm, Compiler::getNextInternalLabel()); break; default: break; } Compiler::getElseIfDataStack().push({jmpIndex, nextInternalLabel, codeIndex, Compiler::ElseBlock, ccType}); return true; } bool keywordENDIF(Compiler::CodeLine& codeLine, int codeLineIndex, int tokenIndex, size_t foundPos, KeywordFuncResult& result) { UNREFERENCED_PARAM(result); UNREFERENCED_PARAM(foundPos); UNREFERENCED_PARAM(tokenIndex); if(codeLine._tokens.size() != 1) { fprintf(stderr, "Compiler::keywordENDIF() : Syntax error, (wrong number of tokens), in '%s' on line %d\n", codeLine._text.c_str(), codeLineIndex + 1); return false; } // Check stack for this IF ELSE ENDIF block if(Compiler::getElseIfDataStack().empty()) { fprintf(stderr, "Compiler::keywordENDIF() : Syntax error, missing IF statement, for '%s' on line %d\n", codeLine._text.c_str(), codeLineIndex + 1); return false; } Compiler::ElseIfData elseIfData = Compiler::getElseIfDataStack().top(); int jmpIndex = elseIfData._jmpIndex; int codeIndex = elseIfData._codeLineIndex; Compiler::IfElseEndType ifElseEndType = elseIfData._ifElseEndType; Expression::CCType ccType = elseIfData._ccType; Compiler::getElseIfDataStack().pop(); // Create label on next line of vasm code Compiler::setNextInternalLabel("_endif_" + Expression::wordToHexString(Compiler::getVasmPC())); std::string nextInternalLabel = Compiler::getNextInternalLabel() + " " + std::to_string(Compiler::incJumpFalseUniqueId()); // Update if's/elseif's jump to this new label if(ifElseEndType == Compiler::IfBlock || ifElseEndType == Compiler::ElseIfBlock) { Compiler::VasmLine* vasm = &Compiler::getCodeLines()[codeIndex]._vasm[jmpIndex]; switch(ccType) { case Expression::BooleanCC: vasm->_code = "JumpFalse" + std::string(OPCODE_TRUNC_SIZE - (sizeof("JumpFalse")-1), ' ') + nextInternalLabel; break; case Expression::NormalCC: addLabelToJumpCC(Compiler::getCodeLines()[codeIndex]._vasm, nextInternalLabel); break; case Expression::FastCC: addLabelToJumpCC(Compiler::getCodeLines()[codeIndex]._vasm, Compiler::getNextInternalLabel()); break; default: break; } } // Update elseif's and/or else's jump to endif label while(!Compiler::getEndIfDataStack().empty()) { codeIndex = Compiler::getEndIfDataStack().top()._codeLineIndex; jmpIndex = Compiler::getEndIfDataStack().top()._jmpIndex; Compiler::VasmLine* vasm = &Compiler::getCodeLines()[codeIndex]._vasm[jmpIndex]; switch(ccType) { case Expression::BooleanCC: { if(Assembler::getUseOpcodeCALLI()) { vasm->_code = "CALLI" + std::string(OPCODE_TRUNC_SIZE - (sizeof("CALLI")-1), ' ') + Compiler::getNextInternalLabel(); } else { vasm->_code = "LDWI" + std::string(OPCODE_TRUNC_SIZE - (sizeof("LDWI")-1), ' ') + Compiler::getNextInternalLabel(); } } break; case Expression::NormalCC: addLabelToJump(Compiler::getCodeLines()[codeIndex]._vasm, Compiler::getNextInternalLabel()); break; case Expression::FastCC: addLabelToJump(Compiler::getCodeLines()[codeIndex]._vasm, Compiler::getNextInternalLabel()); break; default: break; } Compiler::getEndIfDataStack().pop(); } return true; } bool keywordWHILE(Compiler::CodeLine& codeLine, int codeLineIndex, int tokenIndex, size_t foundPos, KeywordFuncResult& result) { UNREFERENCED_PARAM(result); UNREFERENCED_PARAM(tokenIndex); Compiler::setNextInternalLabel("_while_" + Expression::wordToHexString(Compiler::getVasmPC())); Compiler::getWhileWendDataStack().push({0, Compiler::getNextInternalLabel(), codeLineIndex, Expression::BooleanCC}); // Condition Expression::Numeric condition; std::string conditionToken = codeLine._code.substr(foundPos); parseExpression(codeLine, codeLineIndex, conditionToken, condition); if(condition._ccType == Expression::BooleanCC) Compiler::emitVcpuAsm("%JumpFalse", "", false, codeLineIndex); // Boolean condition requires this extra check Compiler::getWhileWendDataStack().top()._jmpIndex = int(Compiler::getCodeLines()[codeLineIndex]._vasm.size()) - 1; Compiler::getWhileWendDataStack().top()._ccType = condition._ccType; return true; } bool keywordWEND(Compiler::CodeLine& codeLine, int codeLineIndex, int tokenIndex, size_t foundPos, KeywordFuncResult& result) { UNREFERENCED_PARAM(result); UNREFERENCED_PARAM(foundPos); UNREFERENCED_PARAM(tokenIndex); // Pop stack for this WHILE loop if(Compiler::getWhileWendDataStack().empty()) { fprintf(stderr, "Compiler::keywordWEND() : Syntax error, missing WHILE statement, for '%s' on line %d\n", codeLine._text.c_str(), codeLineIndex + 1); return false; } Compiler::WhileWendData whileWendData = Compiler::getWhileWendDataStack().top(); Compiler::getWhileWendDataStack().pop(); // Branch to WHILE and check condition again if(Assembler::getUseOpcodeCALLI()) { Compiler::emitVcpuAsm("CALLI", whileWendData._labelName, false, codeLineIndex); } else { // There are no checks to see if this BRA's destination is in the same page, programmer discretion required when using this feature if(whileWendData._ccType == Expression::FastCC) { Compiler::emitVcpuAsm("BRA", whileWendData._labelName, false, codeLineIndex); } else { Compiler::emitVcpuAsm("LDWI", whileWendData._labelName, false, codeLineIndex); Compiler::emitVcpuAsm("CALL", "giga_vAC", false, codeLineIndex); } } // Branch if condition false to instruction after WEND Compiler::setNextInternalLabel("_wend_" + Expression::wordToHexString(Compiler::getVasmPC())); Compiler::VasmLine* vasm = &Compiler::getCodeLines()[whileWendData._codeLineIndex]._vasm[whileWendData._jmpIndex]; switch(whileWendData._ccType) { case Expression::BooleanCC: vasm->_code = "JumpFalse" + std::string(OPCODE_TRUNC_SIZE - (sizeof("JumpFalse")-1), ' ') + Compiler::getNextInternalLabel() + " " + std::to_string(Compiler::incJumpFalseUniqueId()); break; case Expression::NormalCC: addLabelToJumpCC(Compiler::getCodeLines()[whileWendData._codeLineIndex]._vasm, Compiler::getNextInternalLabel() + " " + std::to_string(Compiler::incJumpFalseUniqueId())); break; case Expression::FastCC: addLabelToJumpCC(Compiler::getCodeLines()[whileWendData._codeLineIndex]._vasm, Compiler::getNextInternalLabel()); break; default: break; } return true; } bool keywordREPEAT(Compiler::CodeLine& codeLine, int codeLineIndex, int tokenIndex, size_t foundPos, KeywordFuncResult& result) { UNREFERENCED_PARAM(result); UNREFERENCED_PARAM(foundPos); UNREFERENCED_PARAM(tokenIndex); UNREFERENCED_PARAM(codeLine); Compiler::setNextInternalLabel("_repeat_" + Expression::wordToHexString(Compiler::getVasmPC())); Compiler::getRepeatUntilDataStack().push({Compiler::getNextInternalLabel(), codeLineIndex}); return true; } bool keywordUNTIL(Compiler::CodeLine& codeLine, int codeLineIndex, int tokenIndex, size_t foundPos, KeywordFuncResult& result) { UNREFERENCED_PARAM(result); UNREFERENCED_PARAM(tokenIndex); // Pop stack for this REPEAT loop if(Compiler::getRepeatUntilDataStack().empty()) { fprintf(stderr, "Compiler::keywordUNTIL() : Syntax error, missing REPEAT statement, for '%s' on line %d\n", codeLine._text.c_str(), codeLineIndex + 1); return false; } Compiler::RepeatUntilData repeatUntilData = Compiler::getRepeatUntilDataStack().top(); Compiler::getRepeatUntilDataStack().pop(); // Condition Expression::Numeric condition; std::string conditionToken = codeLine._code.substr(foundPos); parseExpression(codeLine, codeLineIndex, conditionToken, condition); // Branch if condition false to instruction after REPEAT switch(condition._ccType) { case Expression::BooleanCC: Compiler::emitVcpuAsm("%JumpFalse", repeatUntilData._labelName + " " + std::to_string(Compiler::incJumpFalseUniqueId()), false, codeLineIndex); break; case Expression::NormalCC: addLabelToJumpCC(Compiler::getCodeLines()[codeLineIndex]._vasm, repeatUntilData._labelName + " " + std::to_string(Compiler::incJumpFalseUniqueId())); break; case Expression::FastCC: addLabelToJumpCC(Compiler::getCodeLines()[codeLineIndex]._vasm, repeatUntilData._labelName); break; default: break; } return true; } bool keywordCONST(Compiler::CodeLine& codeLine, int codeLineIndex, int tokenIndex, size_t foundPos, KeywordFuncResult& result) { UNREFERENCED_PARAM(result); UNREFERENCED_PARAM(tokenIndex); std::vector<std::string> tokens = Expression::tokenise(codeLine._code.substr(foundPos), '=', true); if(tokens.size() != 2) { fprintf(stderr, "Compiler::keywordCONST() : Syntax error, require a variable and an int or str constant, e.g. CONST a=50 or CONST a$=\"doggy\", in '%s' on line %d\n", codeLine._text.c_str(), codeLineIndex + 1); return false; } Expression::stripWhitespace(tokens[0]); if(!Expression::isVarNameValid(tokens[0])) { fprintf(stderr, "Compiler::keywordCONST() : Syntax error, name must contain only alphanumerics and '$', in '%s' on line %d\n", codeLine._text.c_str(), codeLineIndex + 1); return false; } // String if(tokens[0].back() == '$') { // Strip whitespace Expression::stripNonStringWhitespace(tokens[1]); if(Expression::isValidString(tokens[1])) { uint16_t address; std::string internalName; // Strip quotes tokens[1].erase(0, 1); tokens[1].erase(tokens[1].size()-1, 1); Compiler::getOrCreateString(codeLine, codeLineIndex, tokens[1], internalName, address); Compiler::getConstants().push_back({uint8_t(tokens[1].size()), 0, address, tokens[1], tokens[0], internalName, Compiler::ConstStr}); } // String keyword else { size_t lbra, rbra; if(!Expression::findMatchingBrackets(tokens[1], 0, lbra, rbra)) { fprintf(stderr, "Compiler::keywordCONST() : Syntax error, invalid string or keyword, in '%s' on line %d\n", codeLine._text.c_str(), codeLineIndex + 1); return false; } std::string keywordToken = tokens[1].substr(0, lbra); std::string paramToken = tokens[1].substr(lbra + 1, rbra - (lbra + 1)); Expression::strToUpper(keywordToken); if(_stringKeywords.find(keywordToken) == _stringKeywords.end()) { fprintf(stderr, "Compiler::keywordCONST() : Syntax error, invalid string or keyword, in '%s' on line %d\n", codeLine._text.c_str(), codeLineIndex + 1); return false; } int16_t param; if(!Expression::stringToI16(paramToken, param)) { fprintf(stderr, "Compiler::keywordCONST() : Syntax error, keyword param must be a constant number, in '%s' on line %d\n", codeLine._text.c_str(), codeLineIndex + 1); return false; } // Create constant string int index; uint8_t length = 0; uint16_t address = 0x0000; if(keywordToken == "CHR$") {length = 1; address = Compiler::getOrCreateConstString(Compiler::StrChar, param, index);} else if(keywordToken == "HEX$") {length = 2; address = Compiler::getOrCreateConstString(Compiler::StrHex, param, index);} else if(keywordToken == "HEXW$") {length = 4; address = Compiler::getOrCreateConstString(Compiler::StrHexw, param, index);} // Create constant if(address) { std::string internalName = Compiler::getStringVars().back()._name; Compiler::getConstants().push_back({length, 0, address, Compiler::getStringVars().back()._text, tokens[0], internalName, Compiler::ConstStr}); } } } // Integer else { Expression::stripWhitespace(tokens[1]); Expression::Numeric numeric; Expression::parse(tokens[1], codeLineIndex, numeric); if(tokens[1].size() == 0 || !numeric._isValid || numeric._varType == Expression::TmpVar || numeric._varType == Expression::IntVar) { fprintf(stderr, "Compiler::keywordCONST() : Syntax error, invalid constant expression, in '%s' on line %d\n", codeLine._text.c_str(), codeLineIndex + 1); return false; } Compiler::getConstants().push_back({2, int16_t(std::lround(numeric._value)), 0x0000, "", tokens[0], "_" + tokens[0], Compiler::ConstInt16}); } return true; } bool keywordDIM(Compiler::CodeLine& codeLine, int codeLineIndex, int tokenIndex, size_t foundPos, KeywordFuncResult& result) { UNREFERENCED_PARAM(result); UNREFERENCED_PARAM(tokenIndex); std::string dimText = codeLine._code.substr(foundPos); size_t lbra, rbra; if(!Expression::findMatchingBrackets(codeLine._code, foundPos, lbra, rbra)) { fprintf(stderr, "Compiler::keywordDIM() : Syntax error in DIM statement, must be DIM var(x), in '%s' on line %d\n", codeLine._code.c_str(), codeLineIndex + 1); return false; } // Positive constant size uint16_t arraySize; std::string sizeText = codeLine._code.substr(lbra + 1, rbra - (lbra + 1)); int varIndex = -1, constIndex = -1, strIndex = -1; uint32_t expressionType = Compiler::isExpression(sizeText, varIndex, constIndex, strIndex); if(expressionType == Expression::HasIntConsts) { // Print constant int arraySize = Compiler::getConstants()[constIndex]._data; } else if(!Expression::stringToU16(sizeText, arraySize) || arraySize <= 0) { fprintf(stderr, "Compiler::keywordDIM() : Array size must be a positive constant, found %s in '%s' on line %d\n", sizeText.c_str(), codeLine._code.c_str(), codeLineIndex + 1); return false; } // Most BASIC's declared 0 to n elements, hence size = n + 1 #ifndef ARRAY_INDICES_ONE arraySize++; #endif std::string varName = codeLine._code.substr(foundPos, lbra - foundPos); Expression::stripWhitespace(varName); // Var already exists? varIndex = Compiler::findVar(varName); if(varIndex >= 0) { fprintf(stderr, "Compiler::keywordDIM() : Var %s already exists in '%s' on line %d\n", varName.c_str(), codeLine._code.c_str(), codeLineIndex + 1); return false; } // Optional array var init values uint16_t varInit = 0; size_t varPos = codeLine._code.find("="); if(varPos != std::string::npos) { std::string varText = codeLine._code.substr(varPos + 1); Expression::stripWhitespace(varText); if(!Expression::stringToU16(varText, varInit)) { fprintf(stderr, "Compiler::keywordDIM() : Initial value must be a constant, found %s in '%s' on line %d\n", varText.c_str(), codeLine._code.c_str(), codeLineIndex + 1); return false; } } arraySize *= 2; uint16_t arrayStart = 0x0000; if(!Memory::getFreeRAM(Memory::FitAscending, arraySize, 0x0200, Compiler::getRuntimeStart(), arrayStart)) { fprintf(stderr, "Compiler::keywordDIM() : Not enough RAM for int array of size %d in '%s' on line %d\n", arraySize, codeLine._code.c_str(), codeLineIndex + 1); return false; } createIntVar(varName, 0, varInit, codeLine, codeLineIndex, false, varIndex, Compiler::VarArray, arrayStart, Compiler::Int16, arraySize); return true; } bool keywordDEF(Compiler::CodeLine& codeLine, int codeLineIndex, int tokenIndex, size_t foundPos, KeywordFuncResult& result) { UNREFERENCED_PARAM(result); UNREFERENCED_PARAM(tokenIndex); std::string defText = codeLine._code.substr(foundPos); // Equals size_t equalsPos = codeLine._code.find("="); if(equalsPos == std::string::npos) { fprintf(stderr, "Compiler::keywordDEF() : Syntax error, missing equals sign, in '%s' on line %d\n", codeLine._code.c_str(), codeLineIndex + 1); return false; } // Address field size_t typePos, lbra, rbra; uint16_t address = 0; bool foundAddress = false; bool foundFunction = false; std::string addrText, operand; std::vector<std::string> addrTokens; Expression::Numeric addrNumeric; if(Expression::findMatchingBrackets(codeLine._code, foundPos, lbra, rbra)) { // Check for function generator addrText = codeLine._code.substr(lbra + 1, rbra - (lbra + 1)); addrTokens = Expression::tokenise(addrText, ',', true); if(addrTokens.size() > 1) { foundFunction = true; } // Parse address field if(addrTokens.size() == 0) { fprintf(stderr, "Compiler::keywordDEF() : Address field does not exist, found %s in '%s' on line %d\n", addrText.c_str(), codeLine._code.c_str(), codeLineIndex + 1); return false; } parseExpression(codeLine, codeLineIndex, addrTokens[0], operand, addrNumeric); address = int16_t(std::lround(addrNumeric._value)); if(address < DEFAULT_START_ADDRESS) { fprintf(stderr, "Compiler::keywordDEF() : Address field must be above %04x, found %s in '%s' on line %d\n", DEFAULT_START_ADDRESS, addrText.c_str(), codeLine._code.c_str(), codeLineIndex + 1); return false; } typePos = lbra; foundAddress = true; } else { typePos = equalsPos; } // Type field std::string typeText = codeLine._code.substr(foundPos, typePos - foundPos); Expression::stripWhitespace(typeText); Expression::strToUpper(typeText); if(typeText != "BYTE" && typeText != "WORD") { fprintf(stderr, "Compiler::keywordDEF() : Type field must be either BYTE or WORD, found %s in '%s' on line %d\n", typeText.c_str(), codeLine._code.c_str(), codeLineIndex + 1); return false; } // ************************************************************************************************************ // Function generator if(foundFunction) { if(addrTokens.size() != 5) { fprintf(stderr, "Compiler::keywordDEF() : function generator must have 5 parameters, found %d in '%s' on line %d\n", int(addrTokens.size()), codeLine._code.c_str(), codeLineIndex + 1); return false; } for(int i=0; i<int(addrTokens.size()); i++) Expression::stripWhitespace(addrTokens[i]); std::string funcVar = addrTokens[1]; std::string function = codeLine._code.substr(equalsPos + 1); Expression::stripWhitespace(function); if(function.size() == 0) { fprintf(stderr, "Compiler::keywordDEF() : function '%s' is invalid in '%s' on line %d\n", function.c_str(), codeLine._code.c_str(), codeLineIndex + 1); return false; } // Parse function variable size_t varPos = function.find(funcVar); if(varPos == std::string::npos) { fprintf(stderr, "Compiler::keywordDEF() : function variable '%s' invalid in '%s' on line %d\n", funcVar.c_str(), codeLine._code.c_str(), codeLineIndex + 1); return false; } function.erase(varPos, funcVar.size()); // Parse function paramaters std::vector<Expression::Numeric> funcParams = {Expression::Numeric(), Expression::Numeric(), Expression::Numeric()}; for(int i=0; i<int(funcParams.size()); i++) { parseExpression(codeLine, codeLineIndex, addrTokens[i + 2], operand, funcParams[i]); } if(funcParams[2]._value == 0.0) { fprintf(stderr, "Compiler::keywordDEF() : Divide by zero detected in '%s' : '%s' : on line %d\n", function.c_str(), codeLine._code.c_str(), codeLineIndex + 1); return false; } // Evaluate function double start = funcParams[0]._value; double end = funcParams[1]._value; double count = fabs(funcParams[2]._value); double step = (end - start) / count; std::vector<int16_t> funcData; for(double d=start; d<end; d+=step) { std::string var = std::to_string(d); function.insert(varPos, var); Expression::Numeric funcResult; parseExpression(codeLine, codeLineIndex, function, operand, funcResult); funcData.push_back(int16_t(std::lround(funcResult._value))); function.erase(varPos, var.size()); } if(typeText == "BYTE") { std::vector<uint8_t> dataBytes(int(count), 0); for(int i=0; i<int(dataBytes.size()); i++) dataBytes[i] = uint8_t(funcData[i]); Compiler::getDefDataBytes().push_back({address, dataBytes}); if(!Memory::takeFreeRAM(address, int(dataBytes.size()))) return false; } else if(typeText == "WORD") { std::vector<int16_t> dataWords(int(count), 0); for(int i=0; i<int(dataWords.size()); i++) dataWords[i] = int16_t(funcData[i]); Compiler::getDefDataWords().push_back({address, dataWords}); if(!Memory::takeFreeRAM(address, int(dataWords.size()) * 2)) return false; } return true; } // ************************************************************************************************************ // Data fields std::vector<std::string> dataTokens = Expression::tokenise(codeLine._code.substr(equalsPos + 1), ',', true); if(dataTokens.size() == 0) { fprintf(stderr, "Compiler::keywordDEF() : Syntax error, require at least one data field in '%s' on line %d\n", codeLine._text.c_str(), codeLineIndex + 1); return false; } // BYTE data if(typeText == "BYTE") { std::vector<uint8_t> dataBytes; for(int i=0; i<int(dataTokens.size()); i++) { uint8_t data; Expression::stripWhitespace(dataTokens[i]); if(!Expression::stringToU8(dataTokens[i], data)) { fprintf(stderr, "Compiler::keywordDEF() : Numeric error '%s', in '%s' on line %d\n", dataTokens[i].c_str(), codeLine._text.c_str(), codeLineIndex + 1); return false; } dataBytes.push_back(data); } // New address entry if(foundAddress) { Compiler::getDefDataBytes().push_back({address, dataBytes}); if(!Memory::takeFreeRAM(address, int(dataBytes.size()))) return false; } // Update current address data else { // Append data address = Compiler::getDefDataBytes().back()._address + uint16_t(Compiler::getDefDataBytes().back()._data.size()); for(int i=0; i<int(dataBytes.size()); i++) Compiler::getDefDataBytes().back()._data.push_back(dataBytes[i]); // Mark new RAM chunk as used if(!Memory::takeFreeRAM(address, int(dataBytes.size()))) return false; } } // WORD data else if(typeText == "WORD") { std::vector<int16_t> dataWords; for(int i=0; i<int(dataTokens.size()); i++) { int16_t data; Expression::stripWhitespace(dataTokens[i]); if(!Expression::stringToI16(dataTokens[i], data)) { fprintf(stderr, "Compiler::keywordDEF() : Numeric error '%s', in '%s' on line %d\n", dataTokens[i].c_str(), codeLine._text.c_str(), codeLineIndex + 1); return false; } dataWords.push_back(data); } // New address entry if(foundAddress) { Compiler::getDefDataWords().push_back({address, dataWords}); if(!Memory::takeFreeRAM(address, int(dataWords.size()) * 2)) return false; } // Update current address data else { // Append data address = Compiler::getDefDataWords().back()._address + uint16_t(Compiler::getDefDataWords().back()._data.size()) * 2; for(int i=0; i<int(dataWords.size()); i++) Compiler::getDefDataWords().back()._data.push_back(dataWords[i]); // Mark new RAM chunk as used if(!Memory::takeFreeRAM(address, int(dataWords.size()) * 2)) return false; } } return true; } bool keywordAT(Compiler::CodeLine& codeLine, int codeLineIndex, int tokenIndex, size_t foundPos, KeywordFuncResult& result) { UNREFERENCED_PARAM(result); UNREFERENCED_PARAM(tokenIndex); std::vector<std::string> tokens = Expression::tokenise(codeLine._code.substr(foundPos), ',', false); if(tokens.size() < 1 && tokens.size() > 2) { fprintf(stderr, "Compiler::keywordAT() : Syntax error, 'AT X' or 'AT X,Y', in '%s' on line %d\n", codeLine._text.c_str(), codeLineIndex + 1); return false; } std::vector<Expression::Numeric> params = {Expression::Numeric(), Expression::Numeric()}; for(int i=0; i<int(tokens.size()); i++) { parseExpression(codeLine, codeLineIndex, tokens[i], params[i]); switch(i) { case 0: Compiler::emitVcpuAsm("ST", "cursorXY", false, codeLineIndex); break; case 1: Compiler::emitVcpuAsm("ST", "cursorXY + 1", false, codeLineIndex); break; default: break; } } if(Assembler::getUseOpcodeCALLI()) { Compiler::emitVcpuAsm("CALLI", "atTextCursor", false, codeLineIndex); } else { Compiler::emitVcpuAsm("LDWI", "atTextCursor", false, codeLineIndex); Compiler::emitVcpuAsm("CALL", "giga_vAC", false, codeLineIndex); } return true; } bool keywordPUT(Compiler::CodeLine& codeLine, int codeLineIndex, int tokenIndex, size_t foundPos, KeywordFuncResult& result) { UNREFERENCED_PARAM(result); UNREFERENCED_PARAM(tokenIndex); std::string expression = codeLine._code.substr(foundPos); if(expression.size() == 0) { fprintf(stderr, "Compiler::keywordPUT() : Syntax error in '%s' on line %d\n", codeLine._text.c_str(), codeLineIndex + 1); return false; } Expression::Numeric param; parseExpression(codeLine, codeLineIndex, expression, param); Compiler::emitVcpuAsm("%PrintAcChar", "", false, codeLineIndex); return true; } bool keywordMODE(Compiler::CodeLine& codeLine, int codeLineIndex, int tokenIndex, size_t foundPos, KeywordFuncResult& result) { UNREFERENCED_PARAM(result); UNREFERENCED_PARAM(tokenIndex); std::string expression = codeLine._code.substr(foundPos); if(expression.size() == 0) { fprintf(stderr, "Compiler::keywordMODE() : Syntax error in '%s' on line %d\n", codeLine._text.c_str(), codeLineIndex + 1); return false; } Expression::Numeric param; parseExpression(codeLine, codeLineIndex, expression, param); Compiler::emitVcpuAsm("STW", "graphicsMode", false, codeLineIndex); Compiler::emitVcpuAsm("%ScanlineMode", "", false, codeLineIndex); return true; } bool keywordWAIT(Compiler::CodeLine& codeLine, int codeLineIndex, int tokenIndex, size_t foundPos, KeywordFuncResult& result) { UNREFERENCED_PARAM(result); UNREFERENCED_PARAM(tokenIndex); std::string expression = codeLine._code.substr(foundPos); if(expression.size() == 0) { fprintf(stderr, "Compiler::keywordWAIT() : Syntax error in '%s' on line %d\n", codeLine._text.c_str(), codeLineIndex + 1); return false; } Expression::Numeric param; parseExpression(codeLine, codeLineIndex, expression, param); Compiler::emitVcpuAsm("STW", "waitVBlankNum", false, codeLineIndex); Compiler::emitVcpuAsm("%WaitVBlank", "", false, codeLineIndex); return true; } bool keywordLINE(Compiler::CodeLine& codeLine, int codeLineIndex, int tokenIndex, size_t foundPos, KeywordFuncResult& result) { UNREFERENCED_PARAM(result); UNREFERENCED_PARAM(tokenIndex); std::vector<std::string> tokens = Expression::tokenise(codeLine._code.substr(foundPos), ',', false); if(tokens.size() != 2 && tokens.size() != 4) { fprintf(stderr, "Compiler::keywordLINE() : Syntax error, 'LINE X,Y' or 'LINE X1,Y1,X2,Y2', in '%s' on line %d\n", codeLine._text.c_str(), codeLineIndex + 1); return false; } if(tokens.size() == 2) { std::vector<Expression::Numeric> params = {Expression::Numeric(), Expression::Numeric()}; for(int i=0; i<int(tokens.size()); i++) { parseExpression(codeLine, codeLineIndex, tokens[i], params[i]); switch(i) { case 0: Compiler::emitVcpuAsm("STW", "drawLine_x2", false, codeLineIndex); break; case 1: Compiler::emitVcpuAsm("STW", "drawLine_y2", false, codeLineIndex); break; default: break; } } Compiler::emitVcpuAsm("%AtLineCursor", "", false, codeLineIndex); Compiler::emitVcpuAsm("%DrawVTLine", "", false, codeLineIndex); } else { std::vector<Expression::Numeric> params = {Expression::Numeric(), Expression::Numeric(), Expression::Numeric(), Expression::Numeric()}; for(int i=0; i<int(tokens.size()); i++) { parseExpression(codeLine, codeLineIndex, tokens[i], params[i]); switch(i) { case 0: Compiler::emitVcpuAsm("STW", "drawLine_x1", false, codeLineIndex); break; case 1: Compiler::emitVcpuAsm("STW", "drawLine_y1", false, codeLineIndex); break; case 2: Compiler::emitVcpuAsm("STW", "drawLine_x2", false, codeLineIndex); break; case 3: Compiler::emitVcpuAsm("STW", "drawLine_y2", false, codeLineIndex); break; default: break; } } Compiler::emitVcpuAsm("%DrawLine", "", false, codeLineIndex); } return true; } bool keywordHLINE(Compiler::CodeLine& codeLine, int codeLineIndex, int tokenIndex, size_t foundPos, KeywordFuncResult& result) { UNREFERENCED_PARAM(result); UNREFERENCED_PARAM(tokenIndex); std::vector<std::string> tokens = Expression::tokenise(codeLine._code.substr(foundPos), ',', false); if(tokens.size() != 3) { fprintf(stderr, "Compiler::keywordHLINE() : Syntax error, 'HLINE X1,Y,X2', in '%s' on line %d\n", codeLine._text.c_str(), codeLineIndex + 1); return false; } std::vector<Expression::Numeric> params = {Expression::Numeric(), Expression::Numeric(), Expression::Numeric()}; for(int i=0; i<int(tokens.size()); i++) { parseExpression(codeLine, codeLineIndex, tokens[i], params[i]); switch(i) { case 0: Compiler::emitVcpuAsm("STW", "drawHLine_x1", false, codeLineIndex); break; case 1: Compiler::emitVcpuAsm("STW", "drawHLine_y1", false, codeLineIndex); break; case 2: Compiler::emitVcpuAsm("STW", "drawHLine_x2", false, codeLineIndex); break; default: break; } } Compiler::emitVcpuAsm("%DrawHLine", "", false, codeLineIndex); return true; } bool keywordVLINE(Compiler::CodeLine& codeLine, int codeLineIndex, int tokenIndex, size_t foundPos, KeywordFuncResult& result) { UNREFERENCED_PARAM(result); UNREFERENCED_PARAM(tokenIndex); std::vector<std::string> tokens = Expression::tokenise(codeLine._code.substr(foundPos), ',', false); if(tokens.size() != 3) { fprintf(stderr, "Compiler::keywordVLINE() : Syntax error, 'VLINE X1,Y,X2', in '%s' on line %d\n", codeLine._text.c_str(), codeLineIndex + 1); return false; } std::vector<Expression::Numeric> params = {Expression::Numeric(), Expression::Numeric(), Expression::Numeric()}; for(int i=0; i<int(tokens.size()); i++) { parseExpression(codeLine, codeLineIndex, tokens[i], params[i]); switch(i) { case 0: Compiler::emitVcpuAsm("STW", "drawVLine_x1", false, codeLineIndex); break; case 1: Compiler::emitVcpuAsm("STW", "drawVLine_y1", false, codeLineIndex); break; case 2: Compiler::emitVcpuAsm("STW", "drawVLine_y2", false, codeLineIndex); break; default: break; } } Compiler::emitVcpuAsm("%DrawVLine", "", false, codeLineIndex); return true; } bool keywordCIRCLE(Compiler::CodeLine& codeLine, int codeLineIndex, int tokenIndex, size_t foundPos, KeywordFuncResult& result) { UNREFERENCED_PARAM(result); UNREFERENCED_PARAM(tokenIndex); std::vector<std::string> tokens = Expression::tokenise(codeLine._code.substr(foundPos), ',', false); if(tokens.size() != 3) { fprintf(stderr, "Compiler::keywordCIRCLE() : Syntax error, 'CIRCLE X,Y,R', in '%s' on line %d\n", codeLine._text.c_str(), codeLineIndex + 1); return false; } std::vector<Expression::Numeric> params = {Expression::Numeric(), Expression::Numeric(), Expression::Numeric()}; for(int i=0; i<int(tokens.size()); i++) { parseExpression(codeLine, codeLineIndex, tokens[i], params[i]); switch(i) { case 0: Compiler::emitVcpuAsm("STW", "drawCircle_cx", false, codeLineIndex); break; case 1: Compiler::emitVcpuAsm("ADDI", "8", false, codeLineIndex); Compiler::emitVcpuAsm("STW", "drawCircle_cy", false, codeLineIndex); break; case 2: Compiler::emitVcpuAsm("STW", "drawCircle_r", false, codeLineIndex); break; default: break; } } Compiler::emitVcpuAsm("%DrawCircle", "", false, codeLineIndex); return true; } bool keywordCIRCLEF(Compiler::CodeLine& codeLine, int codeLineIndex, int tokenIndex, size_t foundPos, KeywordFuncResult& result) { UNREFERENCED_PARAM(result); UNREFERENCED_PARAM(tokenIndex); std::vector<std::string> tokens = Expression::tokenise(codeLine._code.substr(foundPos), ',', false); if(tokens.size() != 3) { fprintf(stderr, "Compiler::keywordCIRCLEF() : Syntax error, 'CIRCLEF X,Y,R', in '%s' on line %d\n", codeLine._text.c_str(), codeLineIndex + 1); return false; } std::vector<Expression::Numeric> params = {Expression::Numeric(), Expression::Numeric(), Expression::Numeric()}; for(int i=0; i<int(tokens.size()); i++) { parseExpression(codeLine, codeLineIndex, tokens[i], params[i]); switch(i) { case 0: Compiler::emitVcpuAsm("STW", "drawCircleF_cx", false, codeLineIndex); break; case 1: Compiler::emitVcpuAsm("STW", "drawCircleF_cy", false, codeLineIndex); break; case 2: Compiler::emitVcpuAsm("STW", "drawCircleF_r", false, codeLineIndex); break; default: break; } } Compiler::emitVcpuAsm("%DrawCircleF", "", false, codeLineIndex); return true; } bool keywordRECT(Compiler::CodeLine& codeLine, int codeLineIndex, int tokenIndex, size_t foundPos, KeywordFuncResult& result) { UNREFERENCED_PARAM(result); UNREFERENCED_PARAM(tokenIndex); std::vector<std::string> tokens = Expression::tokenise(codeLine._code.substr(foundPos), ',', false); if(tokens.size() != 4) { fprintf(stderr, "Compiler::keywordRECT() : Syntax error, 'RECT X1,Y1,X2,Y2', in '%s' on line %d\n", codeLine._text.c_str(), codeLineIndex + 1); return false; } std::vector<Expression::Numeric> params = {Expression::Numeric(), Expression::Numeric(), Expression::Numeric(), Expression::Numeric()}; for(int i=0; i<int(tokens.size()); i++) { parseExpression(codeLine, codeLineIndex, tokens[i], params[i]); switch(i) { case 0: Compiler::emitVcpuAsm("STW", "drawRect_x1", false, codeLineIndex); break; case 1: Compiler::emitVcpuAsm("STW", "drawRect_y1", false, codeLineIndex); break; case 2: Compiler::emitVcpuAsm("STW", "drawRect_x2", false, codeLineIndex); break; case 3: Compiler::emitVcpuAsm("STW", "drawRect_y2", false, codeLineIndex); break; default: break; } } Compiler::emitVcpuAsm("%DrawRect", "", false, codeLineIndex); return true; } bool keywordRECTF(Compiler::CodeLine& codeLine, int codeLineIndex, int tokenIndex, size_t foundPos, KeywordFuncResult& result) { UNREFERENCED_PARAM(result); UNREFERENCED_PARAM(tokenIndex); std::vector<std::string> tokens = Expression::tokenise(codeLine._code.substr(foundPos), ',', false); if(tokens.size() != 4) { fprintf(stderr, "Compiler::keywordRECTF() : Syntax error, 'RECTF X1,Y1,X2,Y2', in '%s' on line %d\n", codeLine._text.c_str(), codeLineIndex + 1); return false; } std::vector<Expression::Numeric> params = {Expression::Numeric(), Expression::Numeric(), Expression::Numeric(), Expression::Numeric()}; for(int i=0; i<int(tokens.size()); i++) { parseExpression(codeLine, codeLineIndex, tokens[i], params[i]); switch(i) { case 0: Compiler::emitVcpuAsm("STW", "drawRectF_x1", false, codeLineIndex); break; case 1: Compiler::emitVcpuAsm("STW", "drawRectF_y1", false, codeLineIndex); break; case 2: Compiler::emitVcpuAsm("STW", "drawRectF_x2", false, codeLineIndex); break; case 3: Compiler::emitVcpuAsm("STW", "drawRectF_y2", false, codeLineIndex); break; default: break; } } Compiler::emitVcpuAsm("%DrawRectF", "", false, codeLineIndex); return true; } bool keywordPOLY(Compiler::CodeLine& codeLine, int codeLineIndex, int tokenIndex, size_t foundPos, KeywordFuncResult& result) { UNREFERENCED_PARAM(result); UNREFERENCED_PARAM(tokenIndex); std::vector<std::string> tokens = Expression::tokenise(codeLine._code.substr(foundPos), ',', false); if(tokens.size() != 1) { fprintf(stderr, "Compiler::keywordPOLY() : Syntax error, 'POLY ADDR', in '%s' on line %d\n", codeLine._text.c_str(), codeLineIndex + 1); return false; } Expression::Numeric param; parseExpression(codeLine, codeLineIndex, tokens[0], param); Compiler::emitVcpuAsm("STW", "drawPoly_addr", false, codeLineIndex); Compiler::emitVcpuAsm("%DrawPoly", "", false, codeLineIndex); return true; } bool keywordSCROLL(Compiler::CodeLine& codeLine, int codeLineIndex, int tokenIndex, size_t foundPos, KeywordFuncResult& result) { UNREFERENCED_PARAM(result); UNREFERENCED_PARAM(tokenIndex); std::vector<std::string> tokens = Expression::tokenise(codeLine._code.substr(foundPos), ' ', false); if(tokens.size() != 1) { fprintf(stderr, "Compiler::keywordSCROLL() : Syntax error, 'SCROLL ON' or 'SCROLL OFF', in '%s' on line %d\n", codeLine._text.c_str(), codeLineIndex + 1); return false; } std::string scrollToken = Expression::strToUpper(tokens[0]); Expression::stripWhitespace(scrollToken); if(scrollToken != "ON" && scrollToken != "OFF") { fprintf(stderr, "Compiler::keywordSCROLL() : Syntax error, 'SCROLL ON' or 'SCROLL OFF', in '%s' on line %d\n", codeLine._text.c_str(), codeLineIndex + 1); return false; } if(scrollToken == "ON") { Compiler::emitVcpuAsm("LDWI", "0x0001", false, codeLineIndex); Compiler::emitVcpuAsm("ORW", "miscFlags", false, codeLineIndex); } else { Compiler::emitVcpuAsm("LDWI", "0xFFFE", false, codeLineIndex); Compiler::emitVcpuAsm("ANDW", "miscFlags", false, codeLineIndex); } Compiler::emitVcpuAsm("STW", "miscFlags", false, codeLineIndex); return true; } bool keywordPOKE(Compiler::CodeLine& codeLine, int codeLineIndex, int tokenIndex, size_t foundPos, KeywordFuncResult& result) { UNREFERENCED_PARAM(result); UNREFERENCED_PARAM(tokenIndex); std::vector<std::string> tokens = Expression::tokenise(codeLine._code.substr(foundPos), ',', false); if(tokens.size() != 2) { fprintf(stderr, "Compiler::keywordPOKE() : Syntax error, 'POKE A,X', in '%s' on line %d\n", codeLine._text.c_str(), codeLineIndex + 1); return false; } std::vector<std::string> operands = {"", ""}; std::vector<Expression::Numeric> numerics = {Expression::Numeric(), Expression::Numeric()}; std::vector<Compiler::OperandType> operandTypes {Compiler::OperandConst, Compiler::OperandConst}; for(int i=0; i<int(tokens.size()); i++) { operandTypes[i] = parseExpression(codeLine, codeLineIndex, tokens[i], operands[i], numerics[i]); } std::string opcode, operand; switch(numerics[1]._int16Byte) { case Expression::Int16Low: opcode = "LD"; operand = "_" + operands[1]; break; case Expression::Int16High: opcode = "LD"; operand = "_" + operands[1] + " + 1"; break; case Expression::Int16Both: opcode = "LDW"; operand = "_" + operands[1]; break; default: break; } if((operandTypes[0] == Compiler::OperandVar || operandTypes[0] == Compiler::OperandTemp) && (operandTypes[1] == Compiler::OperandVar || operandTypes[1] == Compiler::OperandTemp)) { (operandTypes[1] == Compiler::OperandVar) ? Compiler::emitVcpuAsm(opcode, operand, false, codeLineIndex) : Compiler::emitVcpuAsm("LDW", operands[1], false, codeLineIndex); (operandTypes[0] == Compiler::OperandVar) ? Compiler::emitVcpuAsm("POKE", "_" + operands[0], false, codeLineIndex) : Compiler::emitVcpuAsm("POKE", operands[0], false, codeLineIndex); } else if((operandTypes[0] == Compiler::OperandVar || operandTypes[0] == Compiler::OperandTemp) && operandTypes[1] == Compiler::OperandConst) { Compiler::emitVcpuAsm("LDI", operands[1], false, codeLineIndex); (operandTypes[0] == Compiler::OperandVar) ? Compiler::emitVcpuAsm("POKE", "_" + operands[0], false, codeLineIndex) : Compiler::emitVcpuAsm("POKE", operands[0], false, codeLineIndex); } else if(operandTypes[0] == Compiler::OperandConst && (operandTypes[1] == Compiler::OperandVar || operandTypes[1] == Compiler::OperandTemp)) { uint16_t addr; if(Expression::stringToU16(operands[0], addr) && addr < 0x0100) { (operandTypes[1] == Compiler::OperandVar) ? Compiler::emitVcpuAsm(opcode, operand, false, codeLineIndex) : Compiler::emitVcpuAsm("LDW", operands[1], false, codeLineIndex); Compiler::emitVcpuAsm("ST", operands[0], false, codeLineIndex); } else { Compiler::emitVcpuAsm("LDWI", operands[0], false, codeLineIndex); Compiler::emitVcpuAsm("STW", "register0", false, codeLineIndex); (operandTypes[1] == Compiler::OperandVar) ? Compiler::emitVcpuAsm(opcode, operand, false, codeLineIndex) : Compiler::emitVcpuAsm("LDW", operands[1], false, codeLineIndex); Compiler::emitVcpuAsm("POKE", "register0", false, codeLineIndex); } } else { // Optimise for page 0 uint16_t addr; if(Expression::stringToU16(operands[0], addr) && addr < 0x0100) { Compiler::emitVcpuAsm("LDI", operands[1], false, codeLineIndex); Compiler::emitVcpuAsm("ST", operands[0], false, codeLineIndex); } // All other pages else { Compiler::emitVcpuAsm("LDWI", operands[0], false, codeLineIndex); Compiler::emitVcpuAsm("STW", "register0", false, codeLineIndex); Compiler::emitVcpuAsm("LDI", operands[1], false, codeLineIndex); Compiler::emitVcpuAsm("POKE", "register0", false, codeLineIndex); } } return true; } bool keywordDOKE(Compiler::CodeLine& codeLine, int codeLineIndex, int tokenIndex, size_t foundPos, KeywordFuncResult& result) { UNREFERENCED_PARAM(result); UNREFERENCED_PARAM(tokenIndex); std::vector<std::string> tokens = Expression::tokenise(codeLine._code.substr(foundPos), ',', false); if(tokens.size() != 2) { fprintf(stderr, "Compiler::keywordDOKE() : syntax error, 'DOKE A,X', in '%s' on line %d\n", codeLine._text.c_str(), codeLineIndex + 1); return false; } std::vector<std::string> operands = {"", ""}; std::vector<Expression::Numeric> numerics = {Expression::Numeric(), Expression::Numeric()}; std::vector<Compiler::OperandType> operandTypes {Compiler::OperandConst, Compiler::OperandConst}; for(int i=0; i<int(tokens.size()); i++) { operandTypes[i] = parseExpression(codeLine, codeLineIndex, tokens[i], operands[i], numerics[i]); } std::string opcode, operand; switch(numerics[1]._int16Byte) { case Expression::Int16Low: opcode = "LD"; operand = "_" + operands[1]; break; case Expression::Int16High: opcode = "LD"; operand = "_" + operands[1] + " + 1"; break; case Expression::Int16Both: opcode = "LDW"; operand = "_" + operands[1]; break; default: break; } if((operandTypes[0] == Compiler::OperandVar || operandTypes[0] == Compiler::OperandTemp) && (operandTypes[1] == Compiler::OperandVar || operandTypes[1] == Compiler::OperandTemp)) { (operandTypes[1] == Compiler::OperandVar) ? Compiler::emitVcpuAsm(opcode, operand, false, codeLineIndex) : Compiler::emitVcpuAsm("LDW", "" + operands[1], false, codeLineIndex); (operandTypes[0] == Compiler::OperandVar) ? Compiler::emitVcpuAsm("DOKE", "_" + operands[0], false, codeLineIndex) : Compiler::emitVcpuAsm("DOKE", "" + operands[0], false, codeLineIndex); } else if((operandTypes[0] == Compiler::OperandVar || operandTypes[0] == Compiler::OperandTemp) && operandTypes[1] == Compiler::OperandConst) { Compiler::emitVcpuAsm("LDWI", operands[1], false, codeLineIndex); (operandTypes[0] == Compiler::OperandVar) ? Compiler::emitVcpuAsm("DOKE", "_" + operands[0], false, codeLineIndex) : Compiler::emitVcpuAsm("DOKE", "" + operands[0], false, codeLineIndex); } else if(operandTypes[0] == Compiler::OperandConst && (operandTypes[1] == Compiler::OperandVar || operandTypes[1] == Compiler::OperandTemp)) { uint16_t addr; if(Expression::stringToU16(operands[0], addr) && addr < 0x0100) { (operandTypes[1] == Compiler::OperandVar) ? Compiler::emitVcpuAsm(opcode, operand, false, codeLineIndex) : Compiler::emitVcpuAsm("LDW", "" + operands[1], false, codeLineIndex); Compiler::emitVcpuAsm("STW", operands[0], false, codeLineIndex); } else { Compiler::emitVcpuAsm("LDWI", operands[0], false, codeLineIndex); Compiler::emitVcpuAsm("STW", "register0", false, codeLineIndex); (operandTypes[1] == Compiler::OperandVar) ? Compiler::emitVcpuAsm(opcode, operand, false, codeLineIndex) : Compiler::emitVcpuAsm("LDW", "" + operands[1], false, codeLineIndex); Compiler::emitVcpuAsm("DOKE", "register0", false, codeLineIndex); } } else { // Optimise for page 0 uint16_t addr; if(Expression::stringToU16(operands[0], addr) && addr < 0x0100) { Compiler::emitVcpuAsm("LDWI", operands[1], false, codeLineIndex); Compiler::emitVcpuAsm("STW", operands[0], false, codeLineIndex); } // All other pages else { Compiler::emitVcpuAsm("LDWI", operands[0], false, codeLineIndex); Compiler::emitVcpuAsm("STW", "register0", false, codeLineIndex); Compiler::emitVcpuAsm("LDWI", operands[1], false, codeLineIndex); Compiler::emitVcpuAsm("DOKE", "register0", false, codeLineIndex); } } return true; } bool keywordPLAY(Compiler::CodeLine& codeLine, int codeLineIndex, int tokenIndex, size_t foundPos, KeywordFuncResult& result) { UNREFERENCED_PARAM(result); UNREFERENCED_PARAM(tokenIndex); std::vector<std::string> tokens = Expression::tokenise(codeLine._code.substr(foundPos), " ,", false); if(tokens.size() < 1 || tokens.size() > 3) { fprintf(stderr, "Compiler::keywordPLAY() : Syntax error, use 'PLAY MIDI <address>, <waveType>', where <address> and <waveType> are optional; in '%s' on line %d\n", codeLine._text.c_str(), codeLineIndex + 1); return false; } std::string midiToken = Expression::strToUpper(tokens[0]); Expression::stripWhitespace(midiToken); if(midiToken != "MIDI") { fprintf(stderr, "Compiler::keywordPLAY() : Syntax error, use 'PLAY MIDI <address>, <waveType>', where <address> and <waveType> are optional; in '%s' on line %d\n", codeLine._text.c_str(), codeLineIndex + 1); return false; } // Tick Midi if(tokens.size() == 1) { Compiler::emitVcpuAsm("%TickMidi", "", false, codeLineIndex); return true; } // Default wave type if(tokens.size() == 2) { Compiler::emitVcpuAsm("LDI", "2", false, codeLineIndex); Compiler::emitVcpuAsm("ST", "waveType", false, codeLineIndex); } // Midi wave type, (optional) else if(tokens.size() == 3) { std::string waveTypeToken = tokens[2]; Expression::stripWhitespace(waveTypeToken); Expression::Numeric param; parseExpression(codeLine, codeLineIndex, waveTypeToken, param); Compiler::emitVcpuAsm("ST", "waveType", false, codeLineIndex); } // Midi stream address std::string addressToken = tokens[1]; Expression::stripWhitespace(addressToken); Expression::Numeric param; parseExpression(codeLine, codeLineIndex, addressToken, param); Compiler::emitVcpuAsm("%PlayMidi", "", false, codeLineIndex); return true; } }
44.889237
261
0.576889
[ "vector" ]
a674b3ac42dd04a15d4980bb4e2242e696a95d3b
22,620
cpp
C++
BookSmithEPUB/main.cpp
ldraconus/NovelSmith
a0bcb04f701f58a35c9ff23a0119bf4bf2cc4534
[ "Apache-2.0" ]
null
null
null
BookSmithEPUB/main.cpp
ldraconus/NovelSmith
a0bcb04f701f58a35c9ff23a0119bf4bf2cc4534
[ "Apache-2.0" ]
1
2020-09-13T18:55:33.000Z
2020-09-13T18:55:33.000Z
BookSmithEPUB/main.cpp
ldraconus/BookSmith
a0bcb04f701f58a35c9ff23a0119bf4bf2cc4534
[ "Apache-2.0" ]
null
null
null
#include "mainwindow.h" #include "Zippy/Zippy.hpp" #include <map> #include <QApplication> #include <QTextDocumentWriter> #include <QTextDocument> #include <QTextBlock> #include <QTextEdit> #include <QTextFormat> #include <QFile> #include <QJsonDocument> #include <QJsonObject> #include <QJsonArray> #include <QUuid> namespace EPUB { struct Scene { QList<QString> _tags; QString _html; QString _name; QList<struct Scene> _children; Scene(): _html(""), _name("") { } Scene(const Scene& s): _tags(s._tags), _html(s._html), _name(s._name), _children(s._children) { } Scene& operator=(const Scene& s) { if (this != &s) { _tags = s._tags; _html = s._html; _name = s._name; _children = s._children; } return *this; } }; struct Tree { Scene _top; }; static QString _dir; static Tree tree; static Scene objectToScene(const QJsonObject& obj) { Scene scene; scene._html = obj["doc"].toString(""); scene._name = obj["name"].toString(""); const QJsonArray& tags = obj["tags"].toArray(); for (auto tag: tags) scene._tags.append(tag.toString("")); return scene; } static Scene objectToItem(const QJsonObject& obj) { Scene scene = objectToScene(obj); const QJsonArray& children = obj["children"].toArray(); for (auto child: children) scene._children.append(objectToItem(child.toObject())); return scene; } static bool open(QString filename) { int ext = filename.lastIndexOf(".novel"); if (ext != -1) filename = filename.left(ext); int sep = filename.lastIndexOf("/"); if (sep != -1) { _dir = filename.left(sep); filename = filename.right(filename.length() - sep - 1); } sep = filename.lastIndexOf("\\"); if (sep != -1) { _dir = filename.left(sep); filename = filename.right(filename.length() - sep - 1); } filename = _dir + "/" + filename + ".novel"; QFile file; file.setFileName(filename); if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) return false; QByteArray data(file.readAll()); QString jsonStr(data); file.close(); QJsonDocument json = QJsonDocument::fromJson(jsonStr.toUtf8()); const QJsonObject& top = json.object(); if (!top.contains("document")) return false; const QJsonObject& doc = top["document"].toObject(); const QJsonObject& root = doc["root"].toObject(); tree._top = objectToItem(root); return true; } struct Chapter { QString _name; QString _html; Chapter(): _name(""), _html("") { } Chapter(const QString& n): _name(n), _html("") { } Chapter(const Chapter& c): _name(c._name), _html(c._html) { } Chapter& operator=(const Chapter& c) { if (this != &c) { _name = c._name; _html = c._html; } return *this; } }; static QString Cover = ""; static QString Author = "Anonymous"; static QString Name = ""; static QString Rights = "Public Domain"; static QString Language = "en-US"; static QString Publisher = "Independent"; static QString Id = ""; static bool recognizeTag(const QList<QString>& tags, const QString& tag) { return (tags.indexOf(tag) != -1 || tags.indexOf(tag.left(1).toUpper() + tag.right(tag.length() - 1)) != -1 || tags.indexOf(tag.toUpper()) != -1); } static bool SaveStringByTag(const QList<QString>& tags, QString& where, QString tag, const QString& html) { if (recognizeTag(tags, tag)) { QTextEdit edit; edit.setHtml(html); where = edit.toPlainText(); return true; } return false; } static void sceneToDocument(QList<Chapter>& book, QTextEdit& edit, const Scene& scene) { if (!SaveStringByTag(scene._tags, Cover, "cover", scene._html) && !SaveStringByTag(scene._tags, Author, "author", scene._html) && !SaveStringByTag(scene._tags, Rights, "rights", scene._html) && !SaveStringByTag(scene._tags, Language, "language", scene._html) && !SaveStringByTag(scene._tags, Publisher, "publisher", scene._html) && !SaveStringByTag(scene._tags, Id, "id", scene._html)) { QTextEdit temp; if (recognizeTag(scene._tags, "chapter")) { int last = book.length() - 1; if (last >= 0) book[last]._html = edit.toHtml(); Chapter n(scene._name); book.append(n); edit.clear(); temp.setHtml(scene._html); } else if (recognizeTag(scene._tags, "scene")) temp.setHtml(scene._html); temp.selectAll(); if (temp.textCursor().selectedText().length() != 0) { temp.cut(); edit.paste(); edit.insertPlainText("\r\n"); } } for (const auto& scn: scene._children) sceneToDocument(book, edit, scn); } static void novelToDocument(QList<Chapter>& book, Tree& tree) { QTextEdit edit; Name = tree._top._name; sceneToDocument(book, edit, tree._top); int last = book.length() - 1; if (last >= 0) book[last]._html = edit.toHtml(); } static int chapterNumWidth(const QList<Chapter>& book) { char buffer[15]; sprintf(buffer, "%d", book.length()); return (int) strlen(buffer); } static QString chapterManifest(const QList<Chapter>& book) { QString manifest = ""; int len = chapterNumWidth(book); for (int i = 1; i < book.length() + 1; ++i) { char line[1024]; sprintf(line, " <item id=\"chapter%0*d\" href=\"chap%0*d.xhtml\" media-type=\"application/xhtml+xml\" />\n", len, i, len, i); manifest += line; } return manifest; } static QString spineTOC(const QList<Chapter>& book) { QString spine; int len = chapterNumWidth(book); for (int i = 1; i < book.length() + 1; ++i) { char line[1024]; sprintf(line, " <itemref idref=\"chapter%0*d\" />\n", len, i); spine += line; } return spine; } static QString navPoints(const QList<Chapter>& book) { QString nav; int len = chapterNumWidth(book); for (int i = 1; i < book.length() + 1; ++i) { char line[1024]; sprintf(line, " <navPoint id=\"chapter%0*d\" playOrder=\"%d\">\n" " <navLabel>\n" " <text>%s</text>\n" " </navLabel>\n" " <content src=\"chap%0*d.xhtml\"/>\n" " </navPoint>\n", len, i, i, book[i - 1]._name.toStdString().c_str(), len, i); nav += line; } return nav; } static QString convertHTML(QString html, QString title) { // remove all style="..." html = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" + html; int pos = html.indexOf("<!DOCTYPE"); QString left = html.left(pos); html = html.right(html.length() - pos); pos = html.indexOf(">"); html = left + "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.1//EN\" \"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd\">" + html.right(html.length() - pos - 1); pos = html.indexOf("<html>") + 5; html = html.left(pos) + " xmlns=\"http://www.w3.org/1999/xhtml\"" + html.right(html.length() - pos); pos = html.indexOf("<style "); int end = html.indexOf("</style>") + 8; html = html.left(pos) + html.right(html.length() - end); while ((pos = html.indexOf(" align=\"center\"")) != -1) html = html.left(pos) + html.right(html.length() - pos - 15); while ((pos = html.indexOf(" align=\"right\"")) != -1) html = html.left(pos) + html.right(html.length() - pos - 14); while ((pos = html.indexOf(" align=\"left\"")) != -1) html = html.left(pos) + html.right(html.length() - pos - 13); while ((pos = html.indexOf(" align=\"full\"")) != -1) html = html.left(pos) + html.right(html.length() - pos - 13); pos = html.indexOf("<head>") + 6; html = html.left(pos) + "<title>" + title + "</title>" + html.right(html.length() - pos); return html; } #ifdef NOTDEF class ZipEntry { public: typedef QList<unsigned char> ZipEntryData; private: ZipEntryData _binary; QString _data; QString _name; bool _compress; public: ZipEntry(bool c = true): _compress(c) { } ZipEntry(const QString& n, const QString& d, bool c = true): _data(d), _name(n), _compress(c) { } ZipEntry(const QString& n, const ZipEntryData& b, bool c = true): _binary(b), _name(n), _compress(c) { } ZipEntry(const ZipEntry& z): _binary(z._binary), _data(z._data), _name(z._name), _compress(z._compress) { } ZipEntry& operator=(const ZipEntry& z) { if (this != &z) { _binary = z._binary; _data = z._data; _name = z._name; _compress = z._compress; } return *this; } QString Data() const { return _data; } QString Name() const { return _name; } const ZipEntryData& Binary() const { return _binary; } bool Compress() const { return _compress; } zip_source_t* asSource() const; }; zip_source_t* ZipEntry::asSource() const { zip_error_t err; if (Data().isEmpty()) { char* data = (char*) malloc(Binary().size()); for (int i = 0; i < Binary().size(); ++i) data[i] = Binary()[i]; return zip_source_buffer_create((const void*) data, (size_t) Binary().size(), 1, &err); } else return zip_source_buffer_create((const void*) Data().toStdString().c_str(), (size_t) Data().length(), 1, &err); } class Zip { private: zip_t* _zip; QList<ZipEntry> _files; public: Zip() {} void Close(); void Create(const QString& filename); void AddEntry(const QString& n, const QString& d, bool c = true); void AddEntry(const QString& n, const ZipEntry::ZipEntryData& b, bool c = true); void Save(); static const bool DO_NOT_COMPRESS = false; }; void Zip::Create(const QString& filename) { int err; _zip = zip_open(filename.toStdString().c_str(), ZIP_CREATE | ZIP_TRUNCATE, &err); _files.clear(); } void Zip::AddEntry(const QString& n, const QString& d, bool c) { _files.append(ZipEntry(n, d, c)); } void Zip::AddEntry(const QString& n, const ZipEntry::ZipEntryData& b, bool c) { _files.append(ZipEntry(n, b, c)); } void Zip::Close() { zip_close(_zip); } static QList<QString> split(QString name, const QString& sep) { QList<QString> parts; int pos; while ((pos = name.indexOf(sep)) != -1) { parts.append(name.left(pos)); name = name.right(name.length() - pos - 1); } parts.append(name); return parts; } void Zip::Save() { std::map<QString, bool> dirs; for (const auto& x: _files) { zip_source_t* src = x.asSource(); QList<QString> parts = split(x.Name(), "/"); QString dir = ""; for (int i = 0; i < parts.size() - 1; ++i) { if (i != 0) dir += "/"; dir += parts[i]; if (!dirs[dir]) zip_add_dir(_zip, dir.toStdString().c_str()); dirs[dir] = true; } zip_int64_t idx = zip_file_add(_zip, x.Name().toStdString().c_str(), src, ZIP_FL_OVERWRITE); if (!x.Compress()) zip_set_file_compression(_zip, idx, ZIP_CM_STORE, 0); else zip_set_file_compression(_zip, idx, ZIP_CM_DEFAULT, 0); } } static void loadCover(const QString& name, ZipEntry::ZipEntryData& jpg) { QFile file(name); if (!file.open(QIODevice::ReadOnly)) return; QByteArray data(file.readAll()); for (const auto& x: data) jpg.append(x); } #else static void loadCover(const QString& name, Zippy::ZipEntryData& jpg) { QFile file(name); if (!file.open(QIODevice::ReadOnly)) return; QByteArray data(file.readAll()); for (const auto& x: data) jpg.emplace_back(x); } #endif } namespace EPUB { int epub(int argc, char *argv[]) { if (argc != 3) return -1; if (!EPUB::open(argv[1])) return -1; QList<EPUB::Chapter> book; EPUB::novelToDocument(book, EPUB::tree); // create the zip file from the book Zippy::ZipArchive arch; arch.Create(argv[2]); arch.AddEntry("mimetype", "application/epub+zip"); arch.AddEntry("META-INF/container.xml", "<?xml version=\"1.0\"?>" "<container xmlns=\"urn:oasis:names:tc:opendocument:xmlns:container\" version=\"1.0\">" " <rootfiles>" " <rootfile media-type=\"application/oebps-package+xml\" full-path=\"OEBPS/content.opf\"/>" " </rootfiles>" "</container>"); if (!EPUB::Cover.isEmpty()) { Zippy::ZipEntryData jpg; EPUB::loadCover(EPUB::Cover, jpg); arch.AddEntry("OEBPS/images/Cover.jpg", jpg); arch.AddEntry("OEBPS/Cover.xhtml", "<?xml version=\"1.0\" encoding=\"utf-8\"?>" "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.1//EN\" \"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd\">" "<html xmlns=\"http://www.w3.org/1999/xhtml\"><head><title>Chapter 1</title><meta name=\"qrichtext\" content=\"1\" /></head>" " <body>\n" " <img src=\"images/Cover.jpg\"/>\n" " </body>\n" "</html>"); } if (!EPUB::Cover.isEmpty()) { Zippy::ZipEntryData jpg; EPUB::loadCover(EPUB::Cover, jpg); arch.AddEntry("OEBPS/images/Cover.jpg", jpg); arch.AddEntry("OEBPS/Cover.xhtml", "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n" "<html>\n" " <body>\n" " <img src=\"images/Cover.jpg\"/>\n" " </body>\n" "</html>"); } arch.AddEntry("OEBPS/page-template.xpgt", "<ade:template xmlns=\"http://www.w3.org/1999/xhtml\" xmlns:ade=\"http://ns.adobe.com/2006/ade\"" " xmlns:fo=\"http://www.w3.org/1999/XSL/Format\">" " <fo:layout-master-set>" " <fo:simple-page-master master-name=\"single_column\">" " <fo:region-body margin-bottom=\"3pt\" margin-top=\"0.5em\" margin-left=\"3pt\" margin-right=\"3pt\"/>" " </fo:simple-page-master>" " <fo:simple-page-master master-name=\"single_column_head\">" " <fo:region-before extent=\"8.3em\"/>" " <fo:region-body margin-bottom=\"3pt\" margin-top=\"6em\" margin-left=\"3pt\" margin-right=\"3pt\"/>" " </fo:simple-page-master>" " <fo:simple-page-master master-name=\"two_column\" margin-bottom=\"0.5em\" margin-top=\"0.5em\" margin-left=\"0.5em\" margin-right=\"0.5em\">" " <fo:region-body column-count=\"2\" column-gap=\"10pt\"/>" " </fo:simple-page-master>" " <fo:simple-page-master master-name=\"two_column_head\" margin-bottom=\"0.5em\" margin-left=\"0.5em\" margin-right=\"0.5em\">" " <fo:region-before extent=\"8.3em\"/>" " <fo:region-body column-count=\"2\" margin-top=\"6em\" column-gap=\"10pt\"/>" " </fo:simple-page-master>" " <fo:simple-page-master master-name=\"three_column\" margin-bottom=\"0.5em\" margin-top=\"0.5em\" margin-left=\"0.5em\" margin-right=\"0.5em\">" " <fo:region-body column-count=\"3\" column-gap=\"10pt\"/>" " </fo:simple-page-master>" " <fo:simple-page-master master-name=\"three_column_head\" margin-bottom=\"0.5em\" margin-top=\"0.5em\" margin-left=\"0.5em\" margin-right=\"0.5em\">" " <fo:region-before extent=\"8.3em\"/>" " <fo:region-body column-count=\"3\" margin-top=\"6em\" column-gap=\"10pt\"/>" " </fo:simple-page-master>" " <fo:page-sequence-master>" " <fo:repeatable-page-master-alternatives>" " <fo:conditional-page-master-reference master-reference=\"three_column_head\" page-position=\"first\" ade:min-page-width=\"80em\"/>" " <fo:conditional-page-master-reference master-reference=\"three_column\" ade:min-page-width=\"80em\"/>" " <fo:conditional-page-master-reference master-reference=\"two_column_head\" page-position=\"first\" ade:min-page-width=\"50em\"/>" " <fo:conditional-page-master-reference master-reference=\"two_column\" ade:min-page-width=\"50em\"/>" " <fo:conditional-page-master-reference master-reference=\"single_column_head\" page-position=\"first\" />" " <fo:conditional-page-master-reference master-reference=\"single_column\"/>" " </fo:repeatable-page-master-alternatives>" " </fo:page-sequence-master>" " </fo:layout-master-set>" " <ade:style>" " <ade:styling-rule selector=\".title_box\" display=\"adobe-other-region\" adobe-region=\"xsl-region-before\"/>" " </ade:style>" "</ade:template>"); arch.AddEntry("OEBPS/stylesheet.css", "/* Style Sheet */\n" "/* This defines styles and classes used in the book */\n" "body { margin-left: 5%; margin-right: 5%; margin-top: 5%; margin-bottom: 5%; text-align: justify; }\n" "pre { font-size: x-small; }\n" "h1 { text-align: center; }\n" "h2 { text-align: center; }\n" "h3 { text-align: center; }\n" "h4 { text-align: center; }\n" "h5 { text-align: center; }\n" "h6 { text-align: center; }\n" ".CI {\n" " text-align:center;\n" " margin-top:0px;\n" " margin-bottom:0px;\n" " padding:0px;\n" " }\n" ".center {text-align: center;}\n" ".smcap {font-variant: small-caps;}\n" ".u {text-decoration: underline;}\n" ".bold {font-weight: bold;}\n"); if (EPUB::Id.isEmpty()) EPUB::Id = QUuid::createUuid().toString(QUuid::WithoutBraces); arch.AddEntry("OEBPS/content.opf", ("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n" "<package xmlns=\"http://www.idpf.org/2007/opf\" unique-identifier=\"BookID\" version=\"2.0\" >\n" " <metadata xmlns:dc=\"http://purl.org/dc/elements/1.1/\" xmlns:opf=\"http://www.idpf.org/2007/opf\">\n" " <dc:title>" + EPUB::Name + "</dc:title>\n" " <dc:creator opf:role=\"aut\">" + EPUB::Author + "</dc:creator>\n" " <dc:language>" + EPUB::Language + "</dc:language>\n" " <dc:rights>" + EPUB::Rights + "</dc:rights>\n" " <dc:publisher>" + EPUB::Publisher + "</dc:publisher>\n" " <dc:identifier id=\"BookID\" opf:scheme=\"UUID\">" + EPUB::Id +"</dc:identifier>\n" " <meta name=\"cover\" content=\"images/Cover.jpg\" />" " </metadata>\n" " <manifest>\n" " <item id=\"cover_jpg\" href=\"images/Cover.jpg\" media-type=\"image/jpeg\" />" " <item id=\"ncx\" href=\"toc.ncx\" media-type=\"application/x-dtbncx+xml\" />\n" " <item id=\"style\" href=\"stylesheet.css\" media-type=\"text/css\" />\n" " <item id=\"pagetemplate\" href=\"page-template.xpgt\" media-type=\"application/vnd.adobe-page-template+xml\" />\n" " <item id=\"cover_html\" href=\"Cover.xhtml\" media-type=\"application/xhtml+xml\" />\n" + EPUB::chapterManifest(book) + " </manifest>\n" " <spine toc=\"ncx\">\n" + EPUB::spineTOC(book) + " </spine>\n" "</package>").toStdString().c_str()); arch.AddEntry("OEBPS/toc.ncx", ("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" "<ncx xmlns=\"http://www.daisy.org/z3986/2005/ncx/\" version=\"2005-1\">\n" " <head>\n" " <meta name=\"dtb:uid\" content=\"" + EPUB::Id + "\"/>\n" " <meta name=\"dtb:depth\" content=\"1\"/>\n" " <meta name=\"dtb:totalPageCount\" content=\"0\"/>\n" " <meta name=\"dtb:maxPageNumber\" content=\"0\"/>\n" " </head>\n" " <docTitle>\n" " <text>" + EPUB::Name + "</text>\n" " </docTitle>\n" " <navMap>" + EPUB::navPoints(book) + " </navMap>\n" "</ncx>").toStdString().c_str()); int len = EPUB::chapterNumWidth(book); for (int i = 1; i <= book.length(); ++i) { char name[1024]; sprintf(name, "OEBPS/chap%0*d.xhtml", len, i); arch.AddEntry(name, EPUB::convertHTML(book[i - 1]._html, book[i - 1]._name).toStdString().c_str()); } arch.Save(); arch.Close(); return 0; } }
43.416507
171
0.511848
[ "object" ]