hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
109
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
48.5k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
60fe7a6990fc51147116a00050371cd827657893
26,418
cpp
C++
XRVessels/XR2Ravenstar/XR2Ravenstar/XR2VCInstrumentPanels.cpp
dbeachy1/XRVessels
8dd2d879886154de2f31fa75393d8a6ac56a2089
[ "MIT" ]
10
2021-08-20T05:49:10.000Z
2022-01-07T13:00:20.000Z
XRVessels/XR2Ravenstar/XR2Ravenstar/XR2VCInstrumentPanels.cpp
dbeachy1/XRVessels
8dd2d879886154de2f31fa75393d8a6ac56a2089
[ "MIT" ]
null
null
null
XRVessels/XR2Ravenstar/XR2Ravenstar/XR2VCInstrumentPanels.cpp
dbeachy1/XRVessels
8dd2d879886154de2f31fa75393d8a6ac56a2089
[ "MIT" ]
4
2021-09-11T12:08:01.000Z
2022-02-09T00:16:19.000Z
/** XR Vessel add-ons for OpenOrbiter Space Flight Simulator Copyright (C) 2006-2021 Douglas Beachy This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. Email: mailto:doug.beachy@outlook.com Web: https://www.alteaaerospace.com **/ // ============================================================== // XR2Ravenstar implementation class // // XR2InstrumentPanels.cpp // Custom instrument panels for the XR2 // ============================================================== #include "OrbiterSDK.h" #include "resource.h" #include "XR2AreaIDs.h" #include "XR2InstrumentPanels.h" // ------------------------------------------------------------------------ // VC Convenience macros // TODO: #define ADD_TOGGLE_SWITCH(areaID, pHandler, activatedStatus) AddArea(new VCToggleSwitchArea(*this, _COORD2(-1, -1), areaID, pHandler, activatedStatus)) // // Construct our Virtual Cockpit Pilot panel and passenger views // // This is the base class, which is invoked in *all* VC views // Constructor // vessel = our parent vessel // panelID = unique panel ID XR2VCInstrumentPanel::XR2VCInstrumentPanel(XR2Ravenstar &vessel, int panelID) : XR2InstrumentPanel(vessel, panelID) // NOTE: force3DRedrawTo2D = true for the XR2's VC (default value defined in class definition) { /* TODO // create our components AddComponent(new MFDComponent (*this, _COORD2( 112, 214), MFD_LEFT)); AddComponent(new MFDComponent (*this, _COORD2( 112, 234), MFD_RIGHT)); AddComponent(new AngularDataComponent (*this, _COORD2( 56, 32))); AddComponent(new ScramPanelComponent (*this, _COORD2( 141, 2))); AddComponent(new MainHoverPanelComponent(*this, _COORD2( 1, 0))); // // Create our areas // // create the four HUD mode button areas for (int i = 0; i < 4; i++) AddArea(new VCHudModeButtonArea(*this, _COORD2(-1, -1), AID_HUDBUTTON1+i)); // panelCoordinates are ignored for these areas // create the six autopilot (NAV mode) button areas for (int i=0; i < 6; i++) AddArea(new VCAutopilotButtonArea(*this, _COORD2(-1, -1), AID_NAVBUTTON1 + i)); // panelCoordinates are ignored for these areas AddArea(new ElevatorTrimArea (*this, _COORD2(252, 0), AID_ELEVATORTRIM)); AddArea(new HoverBalanceVerticalGaugeArea(*this, _COORD2( 97, 95), AID_HBALANCEDISP)); AddArea(new ScramPitchVerticalGaugeArea (*this, _COORD2(236, 86), AID_GIMBALSCRAMDISP)); AddArea(new MainPitchVerticalGaugeArea (*this, _COORD2(227, 2), AID_PGIMBALMAINDISP)); AddArea(new MainYawHorizontalGaugeArea (*this, _COORD2( 6, 107), AID_YGIMBALMAINDISP)); AddArea(new AOAAnalogGaugeArea (*this, _COORD2( 17, 181), AID_AOAINSTR)); AddArea(new SlipAnalogGaugeArea (*this, _COORD2(109, 181), AID_SLIPINSTR)); AddArea(new WingLoadAnalogGaugeArea (*this, _COORD2(111, 17), AID_LOADINSTR)); AddArea(new ArtificialHorizonArea (*this, _COORD2( 0, 159), AID_HORIZON)); AddArea(new ScramTempGaugeArea (*this, _COORD2( 6, 10), AID_SCRAMTEMPDISP)); AddArea(new DoorIndicatorArea (*this, _COORD2( 1, 127), AID_GEARINDICATOR, &GetXR2().gear_status, IDB_INDICATOR_UD, &GetXR2().gear_proc)); AddArea(new DoorIndicatorArea (*this, _COORD2( 32, 127), AID_NOSECONEINDICATOR, &GetXR2().nose_status, IDB_INDICATOR_OC, &GetXR2().nose_proc)); // panelCoordinates are ignored for these interactive areas AddArea(new MWSArea (*this, _COORD2(-1, -1), AID_MWS)); AddArea(new RCSModeArea (*this, _COORD2(-1, -1), AID_RCSMODE)); AddArea(new AFCtrlArea (*this, _COORD2(-1, -1), AID_AFCTRLMODE)); AddArea(new MainThrottleArea (*this, _COORD2(-1, -1), AID_ENGINEMAIN)); AddArea(new LargeHoverThrottleArea (*this, _COORD2(-1, -1), AID_ENGINEHOVER)); AddArea(new ScramThrottleArea (*this, _COORD2(-1, -1), AID_ENGINESCRAM)); AddArea(new MainPitchSwitchArea (*this, _COORD2(-1, -1), AID_PGIMBALMAIN)); AddArea(new ScramPitchSwitchArea (*this, _COORD2(-1, -1), AID_GIMBALSCRAM)); AddArea(new HoverBalanceSwitchArea (*this, _COORD2(-1, -1), AID_HOVERBALANCE)); AddArea(new MainYawSwitchArea (*this, _COORD2(-1, -1), AID_YGIMBALMAIN)); AddArea(new SimpleButtonArea (*this, _COORD2(-1, -1), AID_HBALANCECENTER, &GetXR2().m_hoverCenteringMode, MESHGRP_VC_HBALANCECNT)); AddArea(new SimpleButtonArea (*this, _COORD2(-1, -1), AID_GIMBALSCRAMCENTER, &GetXR2().m_scramCenteringMode, MESHGRP_VC_SCRAMGIMBALCNT)); AddArea(new SimpleButtonArea (*this, _COORD2(-1, -1), AID_PGIMBALMAINCENTER, &GetXR2().m_mainPitchCenteringMode, MESHGRP_VC_PGIMBALCNT)); AddArea(new SimpleButtonArea (*this, _COORD2(-1, -1), AID_YGIMBALMAINCENTER, &GetXR2().m_mainYawCenteringMode, MESHGRP_VC_YGIMBALCNT)); AddArea(new SimpleButtonArea (*this, _COORD2(-1, -1), AID_YGIMBALMAINDIV, &GetXR2().m_mainDivMode, MESHGRP_VC_YGIMBALDIV)); AddArea(new SimpleButtonArea (*this, _COORD2(-1, -1), AID_YGIMBALMAINAUTO, &GetXR2().m_mainAutoMode, MESHGRP_VC_YGIMBALAUTO)); AddArea(new HudIntensitySwitchArea (*this, _COORD2(-1, -1), AID_HUDINTENSITY)); AddArea(new HudColorButtonArea (*this, _COORD2(-1, -1), AID_HUDCOLOR)); // add toggle switches (panelCoordinates are ignored for these) ADD_TOGGLE_SWITCH(AID_GEARDOWN, &XR2Ravenstar::ActivateLandingGear, DoorStatus::DOOR_OPENING); ADD_TOGGLE_SWITCH(AID_GEARUP, &XR2Ravenstar::ActivateLandingGear, DoorStatus::DOOR_CLOSING); ADD_TOGGLE_SWITCH(AID_NCONEOPEN, &XR2Ravenstar::ActivateNoseCone, DoorStatus::DOOR_OPENING); ADD_TOGGLE_SWITCH(AID_NCONECLOSE, &XR2Ravenstar::ActivateNoseCone, DoorStatus::DOOR_CLOSING); ADD_TOGGLE_SWITCH(AID_OLOCKOPEN, &XR2Ravenstar::ActivateOuterAirlock, DoorStatus::DOOR_OPENING); ADD_TOGGLE_SWITCH(AID_OLOCKCLOSE, &XR2Ravenstar::ActivateOuterAirlock, DoorStatus::DOOR_CLOSING); ADD_TOGGLE_SWITCH(AID_ILOCKOPEN, &XR2Ravenstar::ActivateInnerAirlock, DoorStatus::DOOR_OPENING); ADD_TOGGLE_SWITCH(AID_ILOCKCLOSE, &XR2Ravenstar::ActivateInnerAirlock, DoorStatus::DOOR_CLOSING); // TODO: ADD VC SWITCH FOR AIRLOCK PRESSURIZE / DEPRESSUREIZE ADD_TOGGLE_SWITCH(AID_RCOVEROPEN, &XR2Ravenstar::ActivateRCover, DoorStatus::DOOR_OPENING); ADD_TOGGLE_SWITCH(AID_RCOVERCLOSE, &XR2Ravenstar::ActivateRCover, DoorStatus::DOOR_CLOSING); ADD_TOGGLE_SWITCH(AID_RADIATOREX, &XR2Ravenstar::ActivateRadiator, DoorStatus::DOOR_OPENING); ADD_TOGGLE_SWITCH(AID_RADIATORIN, &XR2Ravenstar::ActivateRadiator, DoorStatus::DOOR_CLOSING); ADD_TOGGLE_SWITCH(AID_HATCHOPEN, &XR2Ravenstar::ActivateHatch, DoorStatus::DOOR_OPENING); ADD_TOGGLE_SWITCH(AID_HATCHCLOSE, &XR2Ravenstar::ActivateHatch, DoorStatus::DOOR_CLOSING); ADD_TOGGLE_SWITCH(AID_LADDEREX, &XR2Ravenstar::ActivateLadder, DoorStatus::DOOR_OPENING); ADD_TOGGLE_SWITCH(AID_LADDERIN, &XR2Ravenstar::ActivateLadder, DoorStatus::DOOR_CLOSING); */ } // Activate and initialize this panel // Invoked from VESSEL2's InitPanel method. // Load our surface bitmaps. The inverse of this method is 'Deactivate' // Returns: true on success, false on error (e.g., a bitmap failed to load) bool XR2VCInstrumentPanel::Activate() { // activate all our areas, including our components' areas; this will invoke oapiVCRegisterArea, etc. ActivateAllAreas(); // Hide the active VC HUD mesh so we don't render it twice; this is also invoked in clbkVisualCreated GetXR2().HideActiveVCHUDMesh(); /* {YYY} TODO // // Define interactive (clickable) areas in the VC // const double buttonRadius = .005; // radius of small buttons oapiVCSetAreaClickmode_Quadrilateral(AID_ELEVATORTRIM, _V(0.2873,1.0276,7.2286), _V(0.3040,1.0327,7.2151), _V(0.2873,0.9957,7.2165), _V(0.3040,1.0008,7.2030)); oapiVCSetAreaClickmode_Spherical (AID_MWS, _V(0.0755,1.2185,7.3576), 0.013); oapiVCSetAreaClickmode_Spherical (AID_RCSMODE, _V(-0.3358,1.0683,7.2049),0.02); oapiVCSetAreaClickmode_Spherical (AID_AFCTRLMODE, _V(-0.3351,1.1153,7.2131),0.02); oapiVCSetAreaClickmode_Quadrilateral(AID_ENGINEMAIN, _V(-0.372,0.918,6.905), _V(-0.279,0.918,6.905), _V(-0.372,0.885,7.11), _V(-0.279,0.885,7.11)); oapiVCSetAreaClickmode_Quadrilateral(AID_ENGINEHOVER, _V(-0.44,0.87,6.81), _V(-0.35,0.87,6.81), _V(-0.44,0.95,6.91), _V(-0.35,0.95,6.91)); oapiVCSetAreaClickmode_Quadrilateral(AID_ENGINESCRAM, _V(-0.45,0.98,6.94), _V(-0.39,0.98,6.94), _V(-0.45,0.95,7.07), _V(-0.39,0.95,7.07)); oapiVCSetAreaClickmode_Quadrilateral(AID_HOVERBALANCE, _V(-0.2691,1.1353,7.27), _V(-0.2606,1.1346,7.2729), _V(-0.2691,1.1065,7.2625), _V(-0.2606,1.1058,7.2654)); oapiVCSetAreaClickmode_Quadrilateral(AID_PGIMBALMAIN, _V(-0.3739,1.1105,7.1478), _V(-0.3593,1.108,7.1618), _V(-0.3728,1.0875,7.1426), _V(-0.3582,1.085,7.1566)); oapiVCSetAreaClickmode_Quadrilateral(AID_GIMBALSCRAM, _V(-0.2666,1.0629,7.2484), _V(-0.248,1.0613,7.2548), _V(-0.2666,1.04,7.2425), _V(-0.248,1.0384,7.2488)); oapiVCSetAreaClickmode_Quadrilateral(AID_YGIMBALMAIN, _V(-0.3728,1.0522,7.1301), _V(-0.3566,1.0494,7.1460), _V(-0.3720,1.0324,7.1259), _V(-0.3558,1.0293,7.1416)); oapiVCSetAreaClickmode_Quadrilateral(AID_HUDINTENSITY, _V(0.2327,1.1682,7.3136), _V(0.2500,1.1682,7.3136), _V(0.2327,1.1300,7.3134), _V(0.2500,1.1300,7.3134)); oapiVCSetAreaClickmode_Spherical (AID_HUDCOLOR, _V(0.2511,1.1456,7.3031), buttonRadius); // Gimble buttons oapiVCSetAreaClickmode_Spherical(AID_YGIMBALMAINCENTER, _V(-0.393, 1.065, 7.1074), buttonRadius); oapiVCSetAreaClickmode_Spherical(AID_YGIMBALMAINDIV, _V(-0.394, 1.053, 7.1073), buttonRadius); oapiVCSetAreaClickmode_Spherical(AID_YGIMBALMAINAUTO, _V(-0.395, 1.040, 7.1072), buttonRadius); oapiVCSetAreaClickmode_Spherical(AID_PGIMBALMAINCENTER, _V(-0.3708,1.0743,7.1357), buttonRadius); oapiVCSetAreaClickmode_Spherical(AID_HBALANCECENTER, _V(-0.2684,1.0972,7.2555), buttonRadius); oapiVCSetAreaClickmode_Spherical(AID_GIMBALSCRAMCENTER, _V(-0.2672,1.0256,7.2336), buttonRadius); // Left MFD clickable areas oapiVCSetAreaClickmode_Quadrilateral(AID_MFD1_LBUTTONS, _V(-0.2301,1.1592,7.3322), _V(-0.2161,1.1592,7.3322), _V(-0.2301,1.0302,7.2852), _V(-0.2161,1.0302,7.2852)); oapiVCSetAreaClickmode_Quadrilateral(AID_MFD1_RBUTTONS, _V(-0.023942,1.1592,7.3322), _V(-0.009927,1.1592,7.3322), _V(-0.023942,1.0302,7.2852), _V(-0.009927,1.0302,7.2852)); oapiVCSetAreaClickmode_Spherical(AID_MFD1_PWR, _V(-0.1914,1.009,7.2775), 0.01); oapiVCSetAreaClickmode_Spherical(AID_MFD1_SEL, _V(-0.0670,1.009,7.2775), 0.01); oapiVCSetAreaClickmode_Spherical(AID_MFD1_MNU, _V(-0.0485,1.009,7.2775), 0.01); // Right MFD clickable areas oapiVCSetAreaClickmode_Quadrilateral(AID_MFD2_LBUTTONS, _V(0.009927,1.1592,7.3322), _V(0.023942,1.1592,7.3322), _V(0.009927,1.0302,7.2852), _V(0.023942,1.0302,7.2852)); oapiVCSetAreaClickmode_Quadrilateral(AID_MFD2_RBUTTONS, _V(0.216058,1.1592,7.3322), _V(0.230072,1.1592,7.3322), _V(0.216058,1.0302,7.2852), _V(0.230072,1.0302,7.2852)); oapiVCSetAreaClickmode_Spherical(AID_MFD2_PWR, _V(0.0483,1.009,7.2775), 0.01); oapiVCSetAreaClickmode_Spherical(AID_MFD2_SEL, _V(0.1726,1.009,7.2775), 0.01); oapiVCSetAreaClickmode_Spherical(AID_MFD2_MNU, _V(0.1913,1.009,7.2775), 0.01); // Switches and toggle levers oapiVCSetAreaClickmode_Spherical (AID_GEARDOWN, _V(0.3008,1.0197,7.1656),0.02); oapiVCSetAreaClickmode_Spherical (AID_GEARUP, _V(0.3052,0.9061,7.1280),0.02); oapiVCSetAreaClickmode_Spherical (AID_NCONEOPEN, _V(0.3317,1.1078,7.1968),0.02); oapiVCSetAreaClickmode_Spherical (AID_NCONECLOSE, _V(0.3281,1.0302,7.1630),0.02); oapiVCSetAreaClickmode_Spherical (AID_OLOCKOPEN, _V(0.2506,1.0884,7.2866),0.01); oapiVCSetAreaClickmode_Spherical (AID_OLOCKCLOSE, _V(0.2506,1.1054,7.2866),0.01); oapiVCSetAreaClickmode_Spherical (AID_ILOCKOPEN, _V(0.2824,1.0981,7.2611),0.01); oapiVCSetAreaClickmode_Spherical (AID_ILOCKCLOSE, _V(0.2824,1.1151,7.2611),0.01); oapiVCSetAreaClickmode_Spherical (AID_RCOVEROPEN, _V(0.2508,1.0420,7.2694),0.01); oapiVCSetAreaClickmode_Spherical (AID_RCOVERCLOSE, _V(0.2508,1.0590,7.2694),0.01); oapiVCSetAreaClickmode_Spherical (AID_RADIATOREX, _V(0.2582,0.9448,7.22),0.01); oapiVCSetAreaClickmode_Spherical (AID_RADIATORIN, _V(0.2582,0.9618,7.22),0.01); oapiVCSetAreaClickmode_Spherical (AID_HATCHOPEN, _V(0.2511,0.9921,7.2507), 0.01); oapiVCSetAreaClickmode_Spherical (AID_HATCHCLOSE, _V(0.2511,1.0091,7.2507), 0.01); oapiVCSetAreaClickmode_Spherical (AID_LADDEREX, _V(0.2889,1.0537,7.2388), 0.01); oapiVCSetAreaClickmode_Spherical (AID_LADDERIN, _V(0.2889,1.0707,7.2388), 0.01); // define the four HUD clickable buttons and trigger a redraw of each in case the mode changed in 2D mode for (int i=0; i < 4; i++) { int buttonAreaID = AID_HUDBUTTON1 + i; oapiVCSetAreaClickmode_Spherical(buttonAreaID, _V(-0.1094,1.4174+0.0101*i,7.0406+i*0.0070), 0.0065); TriggerRedrawArea(buttonAreaID); } // define the HUD display in the VC static VCHUDSPEC huds = {1, MESHGRP_VC_HUDDISP, {0,1.462,7.09}, 0.15}; oapiVCRegisterHUD(&huds); // HUD parameters // define the six autopilot (NAV mode) clickable buttons and trigger a redraw of each in case the mode changed in 2D mode for (int i=0; i < 6; i++) { int buttonAreaID = AID_NAVBUTTON1 + i; oapiVCSetAreaClickmode_Spherical (AID_NAVBUTTON1+i, _V(0.11264,1.461821-0.0132572*i,7.071551-0.0090569*i), 0.0065); TriggerRedrawArea(buttonAreaID); } */ return true; } //========================================================================= // Activate and initialize pilot instrument panel // Invoked from VESSEL2's InitPanel method. // Load our surface bitmaps. The inverse of this method is 'Deactivate' // Returns: true on success, false on error (e.g., a bitmap failed to load) bool XR2VCPilotInstrumentPanel::Activate() { // define the HUD display in the VC // Note: Orbiter only supports ONE active HUD surface in the VC // NOTE #2: the "size" value seems to be ignored by the Orbiter core static VCHUDSPEC huds = {0, PILOT_HUD_MESHGRP, {-0.414, 1.946, 8.011}, 0.127}; // X,Y match eyepoint oapiVCRegisterHUD(&huds); // HUD parameters GetVessel().SetXRCameraDirection (_V(0,0,1)); // center, facing forward // set for Pilot GetVessel().SetCameraOffset(_V(-0.414, 1.946, 7.27)); // pilot's eyes GetVessel().SetCameraShiftRange (_V(0,0,0.32), _V(-0.1,0,0), _V(0.25,0,0)); oapiVCSetNeighbours(-1, ORBITER_VC_NUMBER(PANELVC_COPILOT), -1, ORBITER_VC_NUMBER(PANELVC_PSNGR2)); // set current camera position flag GetXR2().campos = DeltaGliderXR1::CAMERA_POSITION::CAM_VCPILOT; // invoke the superclass to activate all VC areas return XR2VCInstrumentPanel::Activate(); } // Activate and initialize copilot instrument panel bool XR2VCCopilotInstrumentPanel::Activate() { // define the HUD display in the VC // Note: Orbiter only supports ONE active HUD surface in the VC // NOTE #2: the "size" value seems to be ignored by the Orbiter core static VCHUDSPEC huds = {0, COPILOT_HUD_MESHGRP, {0.407, 1.922, 8.011}, 0.1325}; // X,Y match eyepoint oapiVCRegisterHUD(&huds); // HUD parameters GetVessel().SetXRCameraDirection (_V(0,0,1)); // center, facing forward // set for Copilot // as measured: GetVessel().SetCameraOffset(_V(0.397, 1.922, 7.461)); // copilot's eyes GetVessel().SetCameraOffset(_V(0.407, 1.922, 7.461)); // moved directly in front of HUD GetVessel().SetCameraShiftRange (_V(0,0,0.25), _V(-0.25,0,0), _V(0.1,0,0)); oapiVCSetNeighbours(ORBITER_VC_NUMBER(PANELVC_PILOT), -1, -1, ORBITER_VC_NUMBER(PANELVC_PSNGR3)); // set current camera position flag GetXR2().campos = DeltaGliderXR1::CAMERA_POSITION::CAM_VCCOPILOT; // invoke the superclass to activate all VC areas return XR2VCInstrumentPanel::Activate(); } // Note: passengers are here (looking FORWARD): // pilot copilot // // A = airlock // 1 2 3 4 // 5 6 7 8 // 9 10 11 12 // shift each headrest coordinate forward by this amount #define PASSENGER_ZSHIFT 0.25 // Activate and initialize passenger #1 instrument panel bool XR2VCPassenger1InstrumentPanel::Activate() { GetVessel().SetXRCameraDirection (_V(0,0,1)); // center, facing forward GetVessel().SetCameraOffset(_V(-1.222, 1.004, 5.973 + PASSENGER_ZSHIFT)); GetVessel().SetCameraShiftRange (_V(0,0,0.25), _V(-0.10,0,0), _V(0.25,0,0)); oapiVCSetNeighbours(-1, ORBITER_VC_NUMBER(PANELVC_PSNGR2), ORBITER_VC_NUMBER(PANELVC_PILOT), ORBITER_VC_NUMBER(PANELVC_PSNGR5)); // set current camera position flag GetXR2().campos = DeltaGliderXR1::CAMERA_POSITION::CAM_VCPSNGR1; // invoke the superclass to activate all VC areas return XR2VCInstrumentPanel::Activate(); } // Activate and initialize passenger #2 instrument panel bool XR2VCPassenger2InstrumentPanel::Activate() { GetVessel().SetXRCameraDirection (_V(0,0,1)); // center, facing forward GetVessel().SetCameraOffset(_V(-0.59, 1.004, 5.973 + PASSENGER_ZSHIFT)); GetVessel().SetCameraShiftRange (_V(0,0,0.25), _V(-0.25,0,0), _V(0.25,0,0)); oapiVCSetNeighbours(ORBITER_VC_NUMBER(PANELVC_PSNGR1), ORBITER_VC_NUMBER(PANELVC_AIRLOCK), ORBITER_VC_NUMBER(PANELVC_PILOT), ORBITER_VC_NUMBER(PANELVC_PSNGR6)); // set current camera position flag GetXR2().campos = DeltaGliderXR1::CAMERA_POSITION::CAM_VCPSNGR2; // invoke the superclass to activate all VC areas return XR2VCInstrumentPanel::Activate(); } // Activate and initialize airlock instrument panel bool XR2VCAirlockInstrumentPanel::Activate() { GetVessel().SetXRCameraDirection (_V(0,0,-1)); // center, facing AFT GetVessel().SetCameraOffset(_V(0.0, 0.253, 9.24)); GetVessel().SetCameraShiftRange (_V(0,0,0.75), _V(-0.25,0,0), _V(0.25,0,0)); GetVessel().SetCameraRotationRange(PI*0.99, PI*0.99, PI*0.4, PI*0.4); // allow extra rotation range in airlock oapiVCSetNeighbours(ORBITER_VC_NUMBER(PANELVC_PSNGR2), ORBITER_VC_NUMBER(PANELVC_PSNGR3), ORBITER_VC_NUMBER(PANELVC_PILOT), -1); // set current camera position flag GetXR2().campos = DeltaGliderXR1::CAMERA_POSITION::CAM_VCAIRLOCK; // invoke the superclass to activate all VC areas return XR2VCInstrumentPanel::Activate(); } // Activate and initialize passenger #3 instrument panel bool XR2VCPassenger3InstrumentPanel::Activate() { GetVessel().SetXRCameraDirection (_V(0,0,1)); // center, facing forward GetVessel().SetCameraOffset(_V(0.551, 1.004, 5.973 + PASSENGER_ZSHIFT)); GetVessel().SetCameraShiftRange (_V(0,0,0.25), _V(-0.25,0,0), _V(0.25,0,0)); oapiVCSetNeighbours(ORBITER_VC_NUMBER(PANELVC_AIRLOCK), ORBITER_VC_NUMBER(PANELVC_PSNGR4), ORBITER_VC_NUMBER(PANELVC_COPILOT), ORBITER_VC_NUMBER(PANELVC_PSNGR7)); // set current camera position flag GetXR2().campos = DeltaGliderXR1::CAMERA_POSITION::CAM_VCPSNGR3; // invoke the superclass to activate all VC areas return XR2VCInstrumentPanel::Activate(); } // Activate and initialize passenger #4 instrument panel bool XR2VCPassenger4InstrumentPanel::Activate() { GetVessel().SetXRCameraDirection (_V(0,0,1)); // center, facing forward GetVessel().SetCameraOffset(_V(1.183, 1.004, 5.973 + PASSENGER_ZSHIFT)); GetVessel().SetCameraShiftRange (_V(0,0,0.25), _V(-0.25,0,0), _V(0.10,0,0)); oapiVCSetNeighbours(ORBITER_VC_NUMBER(PANELVC_PSNGR3), -1, ORBITER_VC_NUMBER(PANELVC_COPILOT), ORBITER_VC_NUMBER(PANELVC_PSNGR8)); // set current camera position flag GetXR2().campos = DeltaGliderXR1::CAMERA_POSITION::CAM_VCPSNGR4; // invoke the superclass to activate all VC areas return XR2VCInstrumentPanel::Activate(); } // Activate and initialize passenger #5 instrument panel bool XR2VCPassenger5InstrumentPanel::Activate() { GetVessel().SetXRCameraDirection (_V(0,0,1)); // center, facing forward GetVessel().SetCameraOffset(_V(-1.222, 1.004, 4.873 + PASSENGER_ZSHIFT)); GetVessel().SetCameraShiftRange (_V(0,0,0.25), _V(-0.10,0,0), _V(0.25,0,0)); oapiVCSetNeighbours(-1, ORBITER_VC_NUMBER(PANELVC_PSNGR6), ORBITER_VC_NUMBER(PANELVC_PSNGR1), ORBITER_VC_NUMBER(PANELVC_PSNGR9)); // set current camera position flag GetXR2().campos = DeltaGliderXR1::CAMERA_POSITION::CAM_VCPSNGR5; // invoke the superclass to activate all VC areas return XR2VCInstrumentPanel::Activate(); } // Activate and initialize passenger #6 instrument panel bool XR2VCPassenger6InstrumentPanel::Activate() { GetVessel().SetXRCameraDirection (_V(0,0,1)); // center, facing forward GetVessel().SetCameraOffset(_V(-0.59, 1.004, 4.873 + PASSENGER_ZSHIFT)); GetVessel().SetCameraShiftRange (_V(0,0,0.25), _V(-0.25,0,0), _V(0.25,0,0)); oapiVCSetNeighbours(ORBITER_VC_NUMBER(PANELVC_PSNGR5), ORBITER_VC_NUMBER(PANELVC_PSNGR7), ORBITER_VC_NUMBER(PANELVC_PSNGR2), ORBITER_VC_NUMBER(PANELVC_PSNGR10)); // set current camera position flag GetXR2().campos = DeltaGliderXR1::CAMERA_POSITION::CAM_VCPSNGR6; // invoke the superclass to activate all VC areas return XR2VCInstrumentPanel::Activate(); } // Activate and initialize passenger #7 instrument panel bool XR2VCPassenger7InstrumentPanel::Activate() { GetVessel().SetXRCameraDirection (_V(0,0,1)); // center, facing forward GetVessel().SetCameraOffset(_V(0.551, 1.004, 4.873 + PASSENGER_ZSHIFT)); GetVessel().SetCameraShiftRange (_V(0,0,0.25), _V(-0.25,0,0), _V(0.25,0,0)); oapiVCSetNeighbours(ORBITER_VC_NUMBER(PANELVC_PSNGR6), ORBITER_VC_NUMBER(PANELVC_PSNGR8), ORBITER_VC_NUMBER(PANELVC_PSNGR3), ORBITER_VC_NUMBER(PANELVC_PSNGR11)); // set current camera position flag GetXR2().campos = DeltaGliderXR1::CAMERA_POSITION::CAM_VCPSNGR7; // invoke the superclass to activate all VC areas return XR2VCInstrumentPanel::Activate(); } // Activate and initialize passenger #8 instrument panel bool XR2VCPassenger8InstrumentPanel::Activate() { GetVessel().SetXRCameraDirection (_V(0,0,1)); // center, facing forward GetVessel().SetCameraOffset(_V(1.183, 1.004, 4.873 + PASSENGER_ZSHIFT)); GetVessel().SetCameraShiftRange (_V(0,0,0.25), _V(-0.25,0,0), _V(0.10,0,0)); oapiVCSetNeighbours(ORBITER_VC_NUMBER(PANELVC_PSNGR7), -1, ORBITER_VC_NUMBER(PANELVC_PSNGR4), ORBITER_VC_NUMBER(PANELVC_PSNGR12)); // set current camera position flag GetXR2().campos = DeltaGliderXR1::CAMERA_POSITION::CAM_VCPSNGR8; // invoke the superclass to activate all VC areas return XR2VCInstrumentPanel::Activate(); } // Activate and initialize passenger #9 instrument panel bool XR2VCPassenger9InstrumentPanel::Activate() { GetVessel().SetXRCameraDirection (_V(0,0,1)); // center, facing forward GetVessel().SetCameraOffset(_V(-1.222, 1.004, 3.773 + PASSENGER_ZSHIFT)); GetVessel().SetCameraShiftRange (_V(0,0,0.25), _V(-0.10,0,0), _V(0.25,0,0)); oapiVCSetNeighbours(-1, ORBITER_VC_NUMBER(PANELVC_PSNGR10), ORBITER_VC_NUMBER(PANELVC_PSNGR5), -1); // set current camera position flag GetXR2().campos = DeltaGliderXR1::CAMERA_POSITION::CAM_VCPSNGR9; // invoke the superclass to activate all VC areas return XR2VCInstrumentPanel::Activate(); } // Activate and initialize passenger #10 instrument panel bool XR2VCPassenger10InstrumentPanel::Activate() { GetVessel().SetXRCameraDirection (_V(0,0,1)); // center, facing forward GetVessel().SetCameraOffset(_V(-0.59, 1.004, 3.773 + PASSENGER_ZSHIFT)); GetVessel().SetCameraShiftRange (_V(0,0,0.25), _V(-0.25,0,0), _V(0.25,0,0)); oapiVCSetNeighbours(ORBITER_VC_NUMBER(PANELVC_PSNGR9), ORBITER_VC_NUMBER(PANELVC_PSNGR11), ORBITER_VC_NUMBER(PANELVC_PSNGR6), -1); // set current camera position flag GetXR2().campos = DeltaGliderXR1::CAMERA_POSITION::CAM_VCPSNGR10; // invoke the superclass to activate all VC areas return XR2VCInstrumentPanel::Activate(); } // Activate and initialize passenger #11 instrument panel bool XR2VCPassenger11InstrumentPanel::Activate() { GetVessel().SetXRCameraDirection (_V(0,0,1)); // center, facing forward GetVessel().SetCameraOffset(_V(0.551, 1.004, 3.773 + PASSENGER_ZSHIFT)); GetVessel().SetCameraShiftRange (_V(0,0,0.25), _V(-0.25,0,0), _V(0.25,0,0)); oapiVCSetNeighbours(ORBITER_VC_NUMBER(PANELVC_PSNGR10), ORBITER_VC_NUMBER(PANELVC_PSNGR12), ORBITER_VC_NUMBER(PANELVC_PSNGR7), -1); // set current camera position flag GetXR2().campos = DeltaGliderXR1::CAMERA_POSITION::CAM_VCPSNGR11; // invoke the superclass to activate all VC areas return XR2VCInstrumentPanel::Activate(); } // Activate and initialize passenger #12 instrument panel bool XR2VCPassenger12InstrumentPanel::Activate() { GetVessel().SetXRCameraDirection (_V(0,0,1)); // center, facing forward GetVessel().SetCameraOffset(_V(1.183, 1.004, 3.773 + PASSENGER_ZSHIFT)); GetVessel().SetCameraShiftRange (_V(0,0,0.25), _V(-0.25,0,0), _V(0.10,0,0)); oapiVCSetNeighbours(ORBITER_VC_NUMBER(PANELVC_PSNGR11), -1, ORBITER_VC_NUMBER(PANELVC_PSNGR8), -1); // set current camera position flag GetXR2().campos = DeltaGliderXR1::CAMERA_POSITION::CAM_VCPSNGR8; // invoke the superclass to activate all VC areas return XR2VCInstrumentPanel::Activate(); }
51.901768
176
0.710652
dbeachy1
60ffd00df76bd3ff64363a47b7c9937255a19811
1,463
hh
C++
src/video/RendererFactory.hh
imulilla/openMSX_TSXadv_nofork
4ee003d87a44633c14c054bd59ec2bfd866e5d9f
[ "Naumen", "Condor-1.1", "MS-PL" ]
null
null
null
src/video/RendererFactory.hh
imulilla/openMSX_TSXadv_nofork
4ee003d87a44633c14c054bd59ec2bfd866e5d9f
[ "Naumen", "Condor-1.1", "MS-PL" ]
null
null
null
src/video/RendererFactory.hh
imulilla/openMSX_TSXadv_nofork
4ee003d87a44633c14c054bd59ec2bfd866e5d9f
[ "Naumen", "Condor-1.1", "MS-PL" ]
null
null
null
#ifndef RENDERERFACTORY_HH #define RENDERERFACTORY_HH #include <memory> #include "components.hh" namespace openmsx { class Reactor; class Display; class VideoSystem; class Renderer; class VDP; class V9990Renderer; class V9990; class LDRenderer; class LaserdiscPlayer; /** Interface for renderer factories. * Every Renderer type has its own RendererFactory. * A RendererFactory can be queried about the availability of the * associated Renderer and can instantiate that Renderer. */ namespace RendererFactory { /** Create the video system required by the current renderer setting. */ std::unique_ptr<VideoSystem> createVideoSystem(Reactor& reactor); /** Create the Renderer selected by the current renderer setting. * @param vdp The VDP whose display will be rendered. * @param display TODO */ std::unique_ptr<Renderer> createRenderer(VDP& vdp, Display& display); /** Create the V9990 Renderer selected by the current renderer setting. * @param vdp The V9990 VDP whose display will be rendered. * @param display TODO */ std::unique_ptr<V9990Renderer> createV9990Renderer( V9990& vdp, Display& display); #if COMPONENT_LASERDISC /** Create the Laserdisc Renderer * @param ld The Laserdisc player whose display will be rendered. * @param display TODO */ std::unique_ptr<LDRenderer> createLDRenderer( LaserdiscPlayer& ld, Display& display); #endif } // namespace RendererFactory } // namespace openmsx #endif
26.125
72
0.755981
imulilla
8802203cd7eb7ab0caefe806e347713739b9aed0
4,490
hpp
C++
include/range/v3/view/take_while.hpp
CornedBee/range-v3
99a9f5f70e65dfcf6bbc8894bf2a22d8f5d4552a
[ "MIT" ]
null
null
null
include/range/v3/view/take_while.hpp
CornedBee/range-v3
99a9f5f70e65dfcf6bbc8894bf2a22d8f5d4552a
[ "MIT" ]
null
null
null
include/range/v3/view/take_while.hpp
CornedBee/range-v3
99a9f5f70e65dfcf6bbc8894bf2a22d8f5d4552a
[ "MIT" ]
null
null
null
/// \file // Range v3 library // // Copyright Eric Niebler 2013-2014 // // Use, modification and distribution is subject to the // Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // // Project home: https://github.com/ericniebler/range-v3 // #ifndef RANGES_V3_VIEW_TAKE_WHILE_HPP #define RANGES_V3_VIEW_TAKE_WHILE_HPP #include <utility> #include <functional> #include <type_traits> #include <range/v3/range_fwd.hpp> #include <range/v3/range_concepts.hpp> #include <range/v3/range_adaptor.hpp> #include <range/v3/utility/meta.hpp> #include <range/v3/utility/invokable.hpp> #include <range/v3/utility/functional.hpp> #include <range/v3/utility/iterator_concepts.hpp> #include <range/v3/utility/iterator_concepts.hpp> #include <range/v3/view/view.hpp> namespace ranges { inline namespace v3 { /// \addtogroup group-views /// @{ template<typename Rng, typename Pred, bool Inf /*= is_infinite<Rng>::value*/> struct take_while_view : range_adaptor<take_while_view<Rng, Pred, Inf>, Rng, Inf> { private: friend range_access; semiregular_invokable_t<Pred> pred_; template<bool IsConst> struct sentinel_adaptor : adaptor_base { private: semiregular_invokable_ref_t<Pred, IsConst> pred_; public: sentinel_adaptor() = default; sentinel_adaptor(semiregular_invokable_ref_t<Pred, IsConst> pred) : pred_(std::move(pred)) {} bool empty(range_iterator_t<Rng> it, range_sentinel_t<Rng> end) const { return it == end || !pred_(*it); } }; CONCEPT_REQUIRES(!Invokable<Pred const, range_common_reference_t<Rng>>()) sentinel_adaptor<false> end_adaptor() { return {pred_}; } CONCEPT_REQUIRES(Invokable<Pred const, range_common_reference_t<Rng>>()) sentinel_adaptor<true> end_adaptor() const { return {pred_}; } public: take_while_view() = default; take_while_view(Rng && rng, Pred pred) : range_adaptor_t<take_while_view>{std::forward<Rng>(rng)} , pred_(invokable(std::move(pred))) {} }; namespace view { struct take_while_fn { private: friend view_access; template<typename Pred> static auto bind(take_while_fn take_while, Pred pred) RANGES_DECLTYPE_AUTO_RETURN ( make_pipeable(std::bind(take_while, std::placeholders::_1, protect(std::move(pred)))) ) public: template<typename Rng, typename Pred> using Concept = meta::and_< InputIterable<Rng>, InvokablePredicate<Pred, range_common_reference_t<Rng>>>; template<typename Rng, typename Pred, CONCEPT_REQUIRES_(Concept<Rng, Pred>())> take_while_view<Rng, Pred> operator()(Rng && rng, Pred pred) const { return {std::forward<Rng>(rng), std::move(pred)}; } #ifndef RANGES_DOXYGEN_INVOKED template<typename Rng, typename Pred, CONCEPT_REQUIRES_(!Concept<Rng, Pred>())> void operator()(Rng &&, Pred) const { CONCEPT_ASSERT_MSG(InputIterable<Rng>(), "The object on which view::take_while operates must be a model of the " "InputIterable concept."); CONCEPT_ASSERT_MSG(InvokablePredicate<Pred, range_common_reference_t<Rng>>(), "The function passed to view::take_while must be callable with objects of " "the range's common reference type, and its result type must be " "convertible to bool."); } #endif }; /// \relates take_while_fn /// \ingroup group-views constexpr view<take_while_fn> take_while{}; } /// @} } } #endif
34.806202
99
0.550334
CornedBee
8802b36004c98405f34fa5f3f746878740b9a093
150
cpp
C++
oop-rubook/cp4/4-3.cpp
lymven-io/OOP
dd4f8487c15b4b58c7d24b0f7c0f0ad90b9ee54a
[ "MIT" ]
null
null
null
oop-rubook/cp4/4-3.cpp
lymven-io/OOP
dd4f8487c15b4b58c7d24b0f7c0f0ad90b9ee54a
[ "MIT" ]
null
null
null
oop-rubook/cp4/4-3.cpp
lymven-io/OOP
dd4f8487c15b4b58c7d24b0f7c0f0ad90b9ee54a
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; void f(int a) { cout << a << endl; } int main() { int i = 5; f(10); f(i); return 0; }
10
22
0.493333
lymven-io
8806b37b9aa2be06a05cbdaa8b49e67111cd800f
42,283
cpp
C++
src/player.cpp
sodomon2/Cavestory-nx
a65ce948c820b3c60b5a5252e5baba6b918d9ebd
[ "BSD-2-Clause" ]
8
2018-04-03T23:06:33.000Z
2021-12-28T18:04:19.000Z
src/player.cpp
sodomon2/Cavestory-nx
a65ce948c820b3c60b5a5252e5baba6b918d9ebd
[ "BSD-2-Clause" ]
null
null
null
src/player.cpp
sodomon2/Cavestory-nx
a65ce948c820b3c60b5a5252e5baba6b918d9ebd
[ "BSD-2-Clause" ]
1
2020-07-31T00:23:27.000Z
2020-07-31T00:23:27.000Z
#include "nx.h" #include "player.h" #include "playerstats.h" #include "caret.h" #include "ObjManager.h" #include "map.h" #include "tsc.h" #include "input.h" #include "game.h" #include "sound/sound.h" #include "common/misc.h" #include "ai/weapons/whimstar.h" #include "p_arms.h" #include "ai/sym/smoke.h" #include "autogen/sprites.h" #include "graphics/sprites.h" using namespace Sprites; #include "settings.h" #include "screeneffect.h" #include "inventory.h" Player *player = NULL; //static void InitWeapon(int wpn, int l1, int l2, int l3, int maxammo=0); bool pinputs[INPUT_COUNT]; bool lastpinputs[INPUT_COUNT]; static void InitWeapon(int wpn, int l1, int l2, int l3, int maxammo=0) { player->weapons[wpn].max_xp[0] = l1; player->weapons[wpn].max_xp[1] = l2; player->weapons[wpn].max_xp[2] = l3; player->weapons[wpn].maxammo = maxammo; } void PInitFirstTime() { player->dir = RIGHT; player->hp = player->maxHealth = 3; player->nxflags |= NXFLAG_FOLLOW_SLOPE; player->ninventory = 0; memset(player->weapons, 0, sizeof(player->weapons)); InitWeapon(WPN_POLARSTAR, 10, 20, 10); InitWeapon(WPN_MGUN, 30, 40, 10, 100); InitWeapon(WPN_MISSILE, 10, 20, 10, 10); InitWeapon(WPN_FIREBALL, 10, 20, 20); InitWeapon(WPN_BLADE, 15, 18, 0); InitWeapon(WPN_BUBBLER, 10, 20, 5); InitWeapon(WPN_SUPER_MISSILE, 30, 60, 10, 10); InitWeapon(WPN_SNAKE, 30, 40, 16); InitWeapon(WPN_SPUR, 40, 60, 200); InitWeapon(WPN_NEMESIS, 1, 1, 0); player->weapons[WPN_MGUN].SetFireRate(6, 6, 6); player->weapons[WPN_MGUN].SetRechargeRate(5, 5, 5); player->weapons[WPN_BUBBLER].SetFireRate(0, 7, 7); player->weapons[WPN_BUBBLER].SetRechargeRate(20, 2, 2); player->curWeapon = WPN_NONE; if (player->XPText) delete player->XPText; player->XPText = new FloatText(SPR_WHITENUMBERS); // initialize player repel points PInitRepel(); } void InitPlayer(void) { player->lookaway = false; player->walking = false; player->dead = false; player->drowned = false; player->disabled = false; player->hurt_time = 0; player->hurt_flash_state = 0; player->water_shield_frame = 0; player->movementmode = MOVEMODE_NORMAL; player->inputs_locked_lasttime = true; player->booststate = BOOST_OFF; player->lastbooststate = BOOST_OFF; player->boosterfuel = BOOSTER_FUEL_QTY; player->xinertia = 0; player->yinertia = 0; player->riding = NULL; player->lastriding = NULL; player->cannotride = NULL; player->DamageText->Reset(); player->XPText->Reset(); statusbar.xpflashcount = 0; PResetWeapons(); PSelectSprite(); // this prevents a splash if we start underwater, and prevents us // from drowning immediately since our air isn't yet set up player->touchattr = TA_WATER; player->airleft = 1000; player->airshowtimer = 0; } Player::~Player() { if (XPText) { delete XPText; XPText = NULL; } } /* void c------------------------------() {} */ void HandlePlayer(void) { // freeze player for the split-second between <TRA to a new map and the // start of the on-entry script for that map. (Fixes: player could shoot during // end sequence if he holds key down). if (game.switchstage.mapno != -1) return; PUpdateInput(); if (!player->dead) { PHandleAttributes(); // handle special tile attributes PHandleSolidMushyObjects(); // handle objects like bugs marked "solid / mushy" PDoWeapons(); // p_arms.cpp PDoHurtFlash(); switch((inputs[DEBUG_MOVE_KEY] && settings->enable_debug_keys) ? MOVEMODE_DEBUG : \ player->movementmode) { case MOVEMODE_NORMAL: { PDoBooster(); PDoBoosterEnd(); PDoWalking(); PDoLooking(); PDoJumping(); PDoFalling(); PSelectFrame(); } break; case MOVEMODE_ZEROG: // Ironhead battle/UNI 1 { PHandleZeroG(); } break; case MOVEMODE_DEBUG: { player->xinertia = player->yinertia = 0; player->blockl = player->blockr = player->blockd = player->blocku = 0; if (inputs[DOWNKEY]) player->y += 0x1000; if (inputs[UPKEY]) player->y -= 0x1000; if (inputs[LEFTKEY]) { player->x -= 0x1000; player->dir = LEFT; } if (inputs[RIGHTKEY]) { player->x += 0x1000; player->dir = RIGHT; } map_scroll_jump(player->x, player->y); player->frame = 2; } break; default: { player->xinertia = player->yinertia = 0; } break; } // handle some special features, like damage and bouncy, of // 100% solid objects such as moving blocks. It's put at the end // so that we can see the desired inertia of the player before // it's canceled out by any block points that are set. That way // we can tell if the player is trying to move into it. PHandleSolidBrickObjects(); } // apply inertia PDoPhysics(); // thud sound when land on some objects if (player->riding && !player->lastriding && (player->riding->nxflags & NXFLAG_THUD_ON_RIDING)) { rumble(0.3,100); sound(SND_THUD); } } // player aftermove routine void HandlePlayer_am(void) { //debug("xinertia: %s", strhex(player->xinertia)); //debug("yinertia: %s", strhex(player->yinertia)); //debug("booststate: %d", player->booststate); //debug("y: %d", player->y / CSFI); //debug("riding %x", player->riding); //debug("block: %d%d%d%d", player->blockl, player->blockr, player->blocku, player->blockd); // if player is riding some sort of platform apply it's inertia to him if (player->riding) { player->apply_xinertia(player->riding->xinertia); player->apply_yinertia(player->riding->yinertia); } // keep player out of blocks "SMB1 style" PDoRepel(); // handle landing and bonking head if (player->blockd && player->yinertia > 0) { if (player->yinertia > 0x400 && !player->hide) { rumble(0.3,100); sound(SND_THUD); } player->yinertia = 0; player->jumping = 0; } else if (player->blocku && player->yinertia < 0) { // he behaves a bit differently when bonking his head on a // solid-brick object vs. bonking his head on the map. // bonk-head star effect if (player->yinertia < -0x200 && !player->hide && \ player->blocku == BLOCKED_MAP) { sound(SND_BONK_HEAD); rumble(0.4,200); effect(player->CenterX(), player->y, EFFECT_BONKPLUS); } // bounces off ceiling with booster 0.8 if (player->booststate == BOOST_08) { player->yinertia = 0x200; } else if (player->bopped_object && player->bopped_object->yinertia != 0) { // no clear yinertia when bop head on OBJ_BLOCK_MOVEV in labyrinth. } else { player->yinertia = 0; } player->jumping = false; } player->lastwalking = player->walking; player->lastriding = player->riding; player->inputs_locked_lasttime = player->inputs_locked; memcpy(lastpinputs, pinputs, sizeof(lastpinputs)); } /* void c------------------------------() {} */ void PDoPhysics(void) { if (player->xinertia > 0x5ff) player->xinertia = 0x5ff; if (player->xinertia < -0x5ff) player->xinertia = -0x5ff; if (player->yinertia > 0x5ff) player->yinertia = 0x5ff; if (player->yinertia < -0x5ff) player->yinertia = -0x5ff; if (player->blockd && player->yinertia > 0) player->yinertia = 0; player->apply_yinertia(player->yinertia); // if xinertia is less than the decel speed then maintain the value but don't actually // move anything. It seems a bit odd...but that's the best I can figure to make it // behave like the original. if (player->xinertia > player->decelspeed || player->xinertia < -player->decelspeed) { player->apply_xinertia(player->xinertia); } } void PUpdateInput(void) { int i; if (player->inputs_locked || player->disabled) { memset(pinputs, 0, sizeof(pinputs)); } else { memcpy(pinputs, inputs, sizeof(pinputs)); // prevent jumping/shooting when leaving a messagebox if (player->inputs_locked_lasttime) { for(i=0;i<INPUT_COUNT;i++) lastpinputs[i] |= pinputs[i]; } // allow entering inventory if (justpushed(INVENTORYKEY)) { if (!game.frozen && !player->dead && game.tsc->GetCurrentScript() == -1) { game.setmode(GM_INVENTORY); } } // Map System if (justpushed(MAPSYSTEMKEY) && (FindInventory(ITEM_MAP_SYSTEM)!=-1)) { if (!game.frozen && !player->dead && game.tsc->GetCurrentScript() == -1) { if (fade.getstate() == FS_NO_FADE && game.switchstage.mapno == -1) { game.setmode(GM_MAP_SYSTEM, game.mode); } } } } } // handles tile attributes of tiles player is touching void PHandleAttributes(void) { static const Point pattrpoints[] = { {8, 8}, {8, 14} }; static const Point hurt_bottom_attrpoint = {8, 7}; unsigned int attr; int tile; // get attributes of tiles player it touching. // first, we'll check the top pattrpoint alone; this is the point at // which you go underwater, when that point is lower than the water level. // ** There is a spot in Labyrinth W just after the Shop where the positioning // of this point is a minor element in the gameplay, and so it must be set // correctly. If set too high you will not be underwater after climbing up the // small slope and you can just jump over the wall that you shouldn't be able to. attr = player->GetAttributes(&pattrpoints[0], 1, &tile); // water handler -- water uses only the top pattrpoint if (attr & TA_WATER) { // check if we just entered the water if (!(player->touchattr & TA_WATER)) { // splash on entering water quick enough if ((player->yinertia > 0x200 && !player->blockd) || \ (player->xinertia < -0x200 || player->xinertia > 0x200)) { int x = player->CenterX(); int y = player->CenterY(); int splashtype = !(player->touchattr & TA_HURTS_PLAYER) ? \ OBJ_WATER_DROPLET : OBJ_LAVA_DROPLET; for(int i=0;i<8;i++) { Object *o = CreateObject(x + (random(-8, 8) * CSFI), y, splashtype); o->xinertia = random(-0x200, 0x200) + player->xinertia; o->yinertia = random(-0x200, 0x80) - (player->yinertia >> 1); } sound(SND_SPLASH); } } // setup physics constants for water player->walkspeed = 0x196; player->fallspeed = 0x2ff; player->fallaccel = 0x28; player->jumpfallaccel = 0x10; player->walkaccel = 0x2a; player->jumpwalkaccel = 0x10; player->decelspeed = 0x19; // was set at 0x280 but I believe that makes it impossible to clear one of the long // spike jumps in River player->jumpvelocity = 0x280; //0x2c0; // decrement air left if (player->equipmask & EQUIP_AIRTANK) { player->airleft = 1000; player->airshowtimer = 0; } else { player->airshowtimer = 60; if (!player->drowned) { if (!player->inputs_locked) player->airleft--; if (player->airleft <= 0 && !game.debug.god) { // player drowned // if flag 4000 is set, then we do not drown, but are in the Almond // level after Core battle, and should instead execute script 1100. if (game.flags[4000]) { // "your senses dim and the world grows dark" game.tsc->StartScript(1100); } else { // nope sorry buddy, no such luck this time Object *o = CreateObject(player->x, player->y, OBJ_NULL); o->state = 1; // so ai doesn't fire o->sprite = SPR_PDROWNED; o->dir = player->dir; killplayer(SCRIPT_DROWNED); } player->drowned = 1; } } } } else { // setup normal physics constants player->walkspeed = 0x32c;////0x030e; player->fallspeed = 0x5ff; player->fallaccel = 0x50; player->jumpfallaccel = 0x20; player->walkaccel = 0x55; player->jumpwalkaccel = 0x20; player->decelspeed = 0x33; player->jumpvelocity = 0x500; // reset air supply player->airleft = 1000; if (player->airshowtimer) player->airshowtimer--; } // add in the bottom pattrpoint, but don't let it set the "water" bit. // only the top pattrpoint can set "water". attr |= (player->GetAttributes(&pattrpoints[1], 1, &tile) & ~TA_WATER); // If the tile has "hurt" bit, we recheck it with the the different bottom attrpoint. // This fixes bottom spikes in water level, last cave... Standard bottom attrpoint // allows intersection with spike only for 1 pixel, but origianl game allows 8 pixels // of safe intersection. if (attr & TA_HURTS_PLAYER) { attr &= ~TA_HURTS_PLAYER; attr |= (player->GetAttributes(&hurt_bottom_attrpoint, 1, &tile) & ~TA_WATER); } if (attr & TA_HURTS_PLAYER) hurtplayer(10); // water current/wind: // for water currents--get the sum total of several points on the player to see // all the directions he's getting blown around at (support multiple directions) DoWaterCurrents(); player->touchattr = attr; } // handes player being blown around by water currents void DoWaterCurrents(void) { static Point currentpoints[] = { {7, 8}, {1, 2}, {1, 8}, {1, 14}, {7, 2}, {7, 14}, {15,2}, {15, 8}, {15, 14} }; int i; static const int current_dir[] = { LEFTMASK, UPMASK, RIGHTMASK, DOWNMASK }; uint8_t currentmask; int tile; // check each point in currentpoints[] for a water current, and if found, // add it to the list of directions we're being blown currentmask = 0; for(i=0;i<9;i++) { //DebugCrosshair(player->x+(currentpoints[i].x * CSFI),player->y+(currentpoints[i].y * CSFI), 255,0,0); if (player->GetAttributes(&currentpoints[i], 1, &tile) & TA_CURRENT) { currentmask |= current_dir[tilecode[tile] & 3]; } // if the center point (the first one) has no current, then don't // bother checking the rest. as during 90% of the game you are NOT underwater. if (!currentmask) return; } // these constants are very critical for Waterway to work properly. // please be careful with them. if (currentmask & LEFTMASK) player->xinertia -= 0x88; if (currentmask & RIGHTMASK) player->xinertia += 0x88; if (currentmask & UPMASK) player->yinertia -= 0x80; if (currentmask & DOWNMASK) player->yinertia += 0x50; } void PDoWalking(void) { int walk_accel; walk_accel = (player->blockd) ? player->walkaccel : player->jumpwalkaccel; // walking/moving if (pinputs[LEFTKEY] || pinputs[RIGHTKEY]) { // we check both without an else so that both keys down=turn right & walk in place if (pinputs[LEFTKEY]) { player->walking = true; player->dir = LEFT; if (player->xinertia > -player->walkspeed) { player->xinertia -= walk_accel; if (player->xinertia < -player->walkspeed) player->xinertia = -player->walkspeed; } } if (pinputs[RIGHTKEY]) { player->walking = true; player->dir = RIGHT; if (player->xinertia < player->walkspeed) { player->xinertia += walk_accel; if (player->xinertia > player->walkspeed) player->xinertia = player->walkspeed; } } if (player->walking && !player->lastwalking) player->walkanimframe = 1; } else { player->walking = false; player->walkanimframe = 0; player->walkanimtimer = 0; // tap sound when stopped walking if (player->lastwalking && player->blockd) sound(SND_PLAYER_WALK); } // deceleration if (player->blockd && player->yinertia >= 0) { // deceleration on ground... // always move towards zero at decelspeed if (player->xinertia > 0) { if (player->blockr && !pinputs[RIGHTKEY]) { player->xinertia = 0; } else if (player->xinertia > player->decelspeed) { player->xinertia -= player->decelspeed; } else { player->xinertia = 0; } } else if (player->xinertia < 0) { if (player->blockl && !pinputs[LEFTKEY]) { player->xinertia = 0; } else if (player->xinertia < -player->decelspeed) { player->xinertia += player->decelspeed; } else { player->xinertia = 0; } } } else // deceleration in air... { // implements 2 things // 1) if player partially hits a brick while in air, his inertia is lesser after he passes it // 2) but, if he's trying to turn around, let him! don't "stick" him to it just because // of a high inertia when he hit it if (player->blockl) { if (player->xinertia < -0x180) player->xinertia = -0x180; if (player->xinertia < 0 && !pinputs[LEFTKEY]) player->xinertia = 0; } if (player->blockr) { if (player->xinertia > 0x180) player->xinertia = 0x180; if (player->xinertia > 0 && !pinputs[RIGHTKEY]) player->xinertia = 0; } } } void PDoFalling(void) { if (player->disabled) return; if (player->booststate) return; if (game.curmap == STAGE_KINGS_TABLE && \ fade.getstate() == FS_FADING) return; // needed to be able to see the falling blocks during // good-ending Helicopter cutscene (otherwise your // invisible character falls and the blocks spawn too low). if (player->hide) { player->xinertia = 0; player->yinertia = 0; return; } // use jump gravity as long as Jump Key is down and we're moving up, // regardless of whether a jump was ever actually initiated. // this is for the fans that blow up--you can push JUMP to climb higher. if (player->yinertia < 0 && pinputs[JUMPKEY]) { // use jump gravity if (player->yinertia < player->fallspeed) { player->yinertia += player->jumpfallaccel; if (player->yinertia > player->fallspeed) player->yinertia = player->fallspeed; } } else { // use normal gravity if (player->yinertia < player->fallspeed) { player->yinertia += player->fallaccel; if (player->yinertia > player->fallspeed) player->yinertia = player->fallspeed; } // if we no longer qualify for jump gravity then the jump is over player->jumping = 0; } } void PDoJumping(void) { // jumping if (pinputs[JUMPKEY] && !lastpinputs[JUMPKEY]) { if (player->blockd) { if (!player->jumping) { player->jumping = true; player->yinertia -= player->jumpvelocity; sound(SND_PLAYER_JUMP); } } else if ((player->equipmask & (EQUIP_BOOSTER08 | EQUIP_BOOSTER20))) { PStartBooster(); } } } void PDoLooking(void) { int lookscroll_want; int i, key; // looking/aiming up and down player->look = lookscroll_want = 0; if (pinputs[DOWNKEY]) { if (!player->blockd) { player->look = DOWN; } else if (!lastpinputs[DOWNKEY]) { // activating scripts/talking to NPC's if (!player->walking && !player->lookaway && \ !pinputs[JUMPKEY] && !pinputs[FIREKEY]) { if (!inputs[DEBUG_MOVE_KEY] || !settings->enable_debug_keys) { player->lookaway = true; player->xinertia = 0; PTryActivateScript(); } } } // can still scroll screen down while standing, even though // it doesn't show any different frame. lookscroll_want = DOWN; } if (pinputs[UPKEY]) { player->look = lookscroll_want = UP; } // when looking, pause a second to be sure they really want to do it // before triggering any real screen scrolling if (player->lookscroll != lookscroll_want) { if (player->lookscroll_timer >= 4 || !lookscroll_want) { player->lookscroll = lookscroll_want; } else { player->lookscroll_timer++; } } else { player->lookscroll_timer = 0; } // deactivation of lookaway if (player->lookaway) { // keys which deactivate lookaway when you are facing away from player static const char actionkeys[] = \ { LEFTKEY, RIGHTKEY, UPKEY, JUMPKEY, FIREKEY, INPUT_COUNT }; // stop looking away if any keys are pushed for(i=0;;i++) { key = actionkeys[i]; if (key == INPUT_COUNT) break; if (pinputs[key]) { player->lookaway = false; break; } } if (!player->blockd) player->lookaway = false; } } /* void c------------------------------() {} */ // called when the player has just turned on the booster void PStartBooster(void) { if (player->boosterfuel <= 0) return; // booster 2.0 lets you pick a direction and tacks inertia // solid in that direction when first activated if ((player->equipmask & EQUIP_BOOSTER20)) { // default boost direction if no key is pressed player->booststate = BOOST_UP; // in order of precedence if (inputs[LEFTKEY] || inputs[RIGHTKEY]) player->booststate = BOOST_HOZ; if (inputs[DOWNKEY]) player->booststate = BOOST_DOWN; if (inputs[UPKEY]) player->booststate = BOOST_UP; // set initial inertia full on if (player->booststate == BOOST_UP || player->booststate == BOOST_DOWN) player->xinertia = 0; switch(player->booststate) { case BOOST_UP: player->yinertia = -0x5ff; break; case BOOST_DOWN: player->yinertia = 0x5ff; break; case BOOST_HOZ: { player->yinertia = 0; if (inputs[LEFTKEY]) player->xinertia = -0x5ff; else player->xinertia = 0x5ff; } break; } } else { player->booststate = BOOST_08; // help it overcome gravity if (player->yinertia > 0x100) player->yinertia >>= 1; } PBoosterSmokePuff(); } // called every tick to run the booster void PDoBooster(void) { /*static const char *statedesc[] = { "OFF", "UP", "DN", "HOZ", "0.8" }; debug("fuel: %d", player->boosterfuel); debug("booststate: %s", statedesc[player->booststate]); debug("xinertia: %d", player->xinertia); debug("yinertia: %d", player->yinertia);*/ if (!(player->equipmask & (EQUIP_BOOSTER08 | EQUIP_BOOSTER20))) { player->booststate = BOOST_OFF; return; } if (!pinputs[JUMPKEY]) { player->booststate = BOOST_OFF; if (player->blockd) player->boosterfuel = BOOSTER_FUEL_QTY; return; } if (!player->booststate) return; // player seems to want it active...check the fuel if (player->boosterfuel <= 0) { player->booststate = BOOST_OFF; return; } else { player->boosterfuel--; } // ok so then, booster is active right now bool sputtering = false; switch(player->booststate) { case BOOST_HOZ: { if ((player->dir == LEFT && player->blockl) || \ (player->dir == RIGHT && player->blockr)) { player->yinertia = -0x100; } // this probably isn't the right way to do this, but this // bit makes the hurt-hop work if you get hit during a sideways boost //if (player->hitwhileboosting) // player->yinertia = -0x400; if (player->dir == LEFT) player->xinertia -= 0x20; if (player->dir == RIGHT) player->xinertia += 0x20; } break; case BOOST_UP: { player->yinertia -= 0x20; } break; case BOOST_DOWN: { player->yinertia += 0x20; } break; case BOOST_08: { // top speed and sputtering if (player->yinertia < -0x400) { player->yinertia += 0x20; sputtering = true; // no sound/smoke this frame } else { player->yinertia -= 0x20; } } break; } // don't land if we booster through a one-tile high corridor, // but do land if we're, well, landing on something (yinertia not negative). // must be done after booster inertia applied to work properly. // for 1) there's a place in the village next to Mahin that is good for testing this, // for 2) the gaps in outer wall by the little house. if (player->blockd) { if (player->yinertia < 0) player->blockd = false; else { player->booststate = BOOST_OFF; return; } } // smoke and sound effects if ((player->boosterfuel % 3) == 1 && !sputtering) { PBoosterSmokePuff(); } } // called every tick just after PDoBooster returns. // tones down player's inertia a bit once the Booster 2.0 stops firing void PDoBoosterEnd() { // put here to be sure it catches all the different ways the Booster can get turned off //if (!player->booststate) //player->hitwhileboosting = false; if (player->booststate != player->lastbooststate) { if (player->booststate == BOOST_OFF && (player->equipmask & EQUIP_BOOSTER20)) { switch(player->lastbooststate) { case BOOST_HOZ: player->xinertia >>= 1; break; case BOOST_UP: player->yinertia >>= 1; break; } } } // in the original touching a slope while boosting horizontally // disables the booster. In that case, we don't want to half the xinertia, // which is why it's here. //if (player->booststate == BOOST_HOZ && CheckStandOnSlope(player)) //player->booststate = BOOST_OFF; player->lastbooststate = player->booststate; } // spawn a Booster smoke puff void PBoosterSmokePuff() { // these are the directions the SMOKE is traveling, not the player // RT LT UP DN static const int smoke_xoffs[] = { 10, 4, 7, 7 }; static const int smoke_yoffs[] = { 10, 10, 0, 14 }; int smokedir; switch(player->booststate) { case BOOST_HOZ: smokedir = (player->dir ^ 1); break; case BOOST_UP: smokedir = DOWN; break; case BOOST_DOWN:smokedir = UP; break; case BOOST_08: smokedir = DOWN; break; default: return; } int x = player->x + (smoke_xoffs[smokedir] * CSFI); int y = player->y + (smoke_yoffs[smokedir] * CSFI); Caret *smoke = effect(x, y, EFFECT_SMOKETRAIL_SLOW); smoke->MoveAtDir(smokedir, 0x200); sound(SND_BOOSTER); } /* void c------------------------------() {} */ // handle some special characteristics of solid-brick objects, // such as bouncy and damage. Unlike with FLAG_SOLID_MUSHY; the // block/l/r/u/d flags for these objects have already been set in // UpdateBlockStates, so we don't have to worry about those. void PHandleSolidBrickObjects(void) { int i; SIFSprite *sprite = player->Sprite(); Object *o; // calculate total inertia of player--this is needed so that // the forcefields in the Monster X arena will damage you if // the treads carry you into them. int p_xinertia = player->xinertia; int p_yinertia = player->yinertia; if (player->riding) { p_xinertia += player->riding->xinertia; p_yinertia += player->riding->yinertia; } for(i=0;i<nOnscreenObjects;i++) { o = onscreen_objects[i]; if (!(o->flags & FLAG_SOLID_BRICK)) continue; // left, right, and up contact damage if (o->damage > 0) { if (player->blockl && player->CheckSolidIntersect(o, &sprite->block_l)) { if (p_xinertia < 0 || o->xinertia > 0) o->DealContactDamage(); } if (player->blockr && player->CheckSolidIntersect(o, &sprite->block_r)) { if (p_xinertia > 0 || o->xinertia < 0) o->DealContactDamage(); } if (player->blocku && player->CheckSolidIntersect(o, &sprite->block_u)) { if (p_yinertia < 0 || o->yinertia > 0) o->DealContactDamage(); } } // stuff for when you are standing on it if (player->blockd && player->CheckSolidIntersect(o, &sprite->block_d)) { if (o->damage && (player->yinertia >= 0 || o->yinertia < 0)) o->DealContactDamage(); // don't do weird glitchy shit if we jump while being carried upward // by an object moving faster than us. handles if you jump while flying // momorin's rocket. if (player->yinertia < 0 && o->yinertia < player->yinertia) player->yinertia = 0; // handle FLAG_BOUNCY--used eg by treads on Monster X when tipped up if (o->flags & FLAG_BOUNCY) { if (player->yinertia > (o->yinertia - 0x200)) player->yinertia = (o->yinertia - 0x200); } else if (o->yinertia <= player->yinertia) { // snap his Y right on top if it player->y = o->SolidTop() - (sprites[player->sprite].block_d[0].y * CSFI); } } } } void PHandleSolidMushyObjects(void) { for(int i=0;i<nOnscreenObjects;i++) { Object *o = onscreen_objects[i]; if (o->flags & FLAG_SOLID_MUSHY) PRunSolidMushy(o); } } // handle "solid mushy" objects, such as bugs. These objects are solid but not 100% super // solid like a brick. Their solidity is more of an "it repels the player" kind of way. // NOTE: This is also responsible for the horizontal motion you see when hit by many kinds // of enemies. The hurtplayer damage routine makes you hop vertically, but it is this that // throws you away horizontally. void PRunSolidMushy(Object *o) { // cache these, so we're not calling the same functions over and over again const int p_left = player->SolidLeft(); const int p_right = player->SolidRight(); const int p_top = player->SolidTop(); const int p_bottom = player->SolidBottom(); const int o_left = o->SolidLeft(); const int o_right = o->SolidRight(); const int o_top = o->SolidTop(); const int o_bottom = o->SolidBottom(); static const int MUSHY_MARGIN = (3 * CSFI); static const int STAND_MARGIN = (1 * CSFI); static const int REPEL_FORCE = 0x200; // hitting sides of object if ((p_top < (o_bottom - MUSHY_MARGIN)) && (p_bottom > (o_top + MUSHY_MARGIN))) { // left side if ((p_right > o_left) && (p_right < o->CenterX())) { if (player->xinertia > -REPEL_FORCE) player->xinertia -= REPEL_FORCE; } // right side if ((p_left < o_right) && (p_left > o->CenterX())) { if (player->xinertia < REPEL_FORCE) player->xinertia += REPEL_FORCE; } } // bonking head on object or standing on object // to tell if we are within horizontal bounds to be standing on the object, // we will check if we have NOT FALLEN OFF the object. if (p_left > (o_right - STAND_MARGIN) || p_right < (o_left + STAND_MARGIN)) { } else { // standing on object if (p_bottom >= o_top && p_bottom <= o->CenterY()) { if (o->flags & FLAG_BOUNCY) { if (player->yinertia > (o->yinertia - 0x200)) player->yinertia = (o->yinertia - 0x200); } else { // force to top of sprite if we're REALLY far into it int em_fline = o->SolidTop() + (3 * CSFI); if (player->SolidBottom() > em_fline) { int over_amt = (em_fline - player->SolidBottom()); int dec_amt = (3 * CSFI); if (over_amt < dec_amt) dec_amt = over_amt; if (dec_amt < (1 * CSFI)) dec_amt = (1 * CSFI); player->apply_yinertia(-dec_amt); } player->blockd = true; player->riding = o; } } else if (p_top < o_bottom && p_top > o->CenterY()) { // hit bottom of object with head if (player->yinertia < 0) player->yinertia = 0; } } } /* void c------------------------------() {} */ // does "damage" points of damage to the player // if even_if_controls_locked is true the damage is // dealt even if the player's input is locked. void hurtplayer(int damage) { if (damage == 0) return; if (!player || !player->hp) return; if (settings->enable_debug_keys && (game.debug.god || inputs[DEBUG_MOVE_KEY])) return; if (player->hurt_time) return; if (player->hide) return; player->hp -= damage; player->DamageText->AddQty(damage); player->lookaway = 0; player->hurt_time = 128; if (player->equipmask & EQUIP_WHIMSTAR) remove_whimstar(&player->whimstar); //if (player->booststate) //player->hitwhileboosting = true; if (player->hp <= 0) { sound(SND_PLAYER_DIE); SmokeClouds(player, 64, 16, 16); rumble(1.0,1000); killplayer(SCRIPT_DIED); } else { sound(SND_PLAYER_HURT); rumble(0.5,500); // hop if (player->movementmode != MOVEMODE_ZEROG) player->yinertia = -0x400; } // decrement weapon XP. if (player->equipmask & EQUIP_ARMS_BARRIER) SubXP(damage); else SubXP(damage * 2); } // set the player state to "dead" and execute script "script" void killplayer(int script) { player->hp = 0; player->dead = true; player->hide = true; player->xinertia = 0; player->yinertia = 0; player->riding = NULL; // why exactly did I say this? i dunno, but not touching for safety StopLoopSounds(); // important for Almond game.tsc->StartScript(script); } /* void c------------------------------() {} */ // this is basically a replacement for most of the player code, // used when the player is in <UNI0001 (the Ironhead battle). void PHandleZeroG(void) { if (!player->inputs_locked) { if (inputs[LEFTKEY] || inputs[RIGHTKEY]) { if (inputs[LEFTKEY]) player->xinertia -= 0x100; if (inputs[RIGHTKEY]) player->xinertia += 0x100; } else { // decel if (player->xinertia < 0x80 || player->xinertia > -0x80) { player->xinertia = 0; } else { player->xinertia += (player->xinertia > 0) ? -0x80 : 0x80; } } if (inputs[UPKEY] || inputs[DOWNKEY]) { if (inputs[UPKEY]) player->yinertia -= 0x100; if (inputs[DOWNKEY]) player->yinertia += 0x100; } else { // decel if (player->yinertia < 0x80 || player->yinertia > -0x80) { player->yinertia = 0; } else { player->xinertia += (player->xinertia > 0) ? -0x80 : 0x80; } } } else { // decel for when inputs locked after victory if (player->xinertia < 0x80 && player->xinertia > -0x40) { player->xinertia = 0; } else { player->xinertia += (player->xinertia > 0) ? -0x80 : 0x80; } if (player->yinertia < 0x80 && player->yinertia > -0x40) { player->yinertia = 0; } else { player->yinertia += (player->yinertia > 0) ? -0x80 : 0x80; } } if (player->xinertia > 0x400) player->xinertia = 0x400; if (player->xinertia < -0x400) player->xinertia = -0x400; if (player->yinertia > 0x400) player->yinertia = 0x400; if (player->yinertia < -0x400) player->yinertia = -0x400; player->frame = (player->yinertia > 0) ? 1 : 2; } /* void c------------------------------() {} */ void PInitRepel(void) { const int s = SPR_MYCHAR; int i; player->nrepel_l = sprites[s].block_l.count; player->nrepel_r = sprites[s].block_r.count; player->nrepel_d = sprites[s].block_d.count; player->nrepel_u = sprites[s].block_u.count; for(i=0;i<player->nrepel_l;i++) { player->repel_l[i].x = sprites[s].block_l[i].x + 1; player->repel_l[i].y = sprites[s].block_l[i].y; } for(i=0;i<player->nrepel_r;i++) { player->repel_r[i].x = sprites[s].block_r[i].x - 1; player->repel_r[i].y = sprites[s].block_r[i].y; } for(i=0;i<player->nrepel_d;i++) { player->repel_d[i].x = sprites[s].block_d[i].x; player->repel_d[i].y = sprites[s].block_d[i].y - 1; } for(i=0;i<player->nrepel_u;i++) { player->repel_u[i].x = sprites[s].block_u[i].x; player->repel_u[i].y = sprites[s].block_u[i].y + 1; } } // the player's block points are assymetrical--block u/d are closer together than block l/r. // So it's quite possible to get e.g. your blockl points embedded in a wall by // falling off the top of it. This function implements a SMB1-style "repel" that // allows this to happen but then pushes the player out of the block over the next // few frames. void PDoRepel(void) { // since this function is called from the aftermove, regular player->blockl etc // won't be updated until the following frame, so we always check the attributes // directly here. static const int REPEL_SPEED = (1 * CSFI); if (settings->enable_debug_keys && inputs[DEBUG_MOVE_KEY]) return; // pushes player out of walls if he become embedded in them, ala Super Mario 1. // this can happen for example because his R,L block points are further out than // his D block points so it's possible to fall really close to a block and // embed the R or L points further into the block than they should be if (player->CheckAttribute(player->repel_r, player->nrepel_r, TA_SOLID_PLAYER)) { if (!player->CheckAttribute(&sprites[player->sprite].block_l, TA_SOLID_PLAYER)) { player->x -= REPEL_SPEED; //debug("REPEL [to left]"); } } if (player->CheckAttribute(player->repel_l, player->nrepel_l, TA_SOLID_PLAYER)) { if (!player->CheckAttribute(&sprites[player->sprite].block_r, TA_SOLID_PLAYER)) { player->x += REPEL_SPEED; //debug("REPEL [to right]"); } } // vertical repel doesn't happen normally, but if we get embedded in a // block somehow, it can happen. /* // do repel down if (player->CheckAttribute(player->repel_u, player->nrepel_u, TA_SOLID_PLAYER)) { if (!player->CheckAttribute(&sprites[player->sprite].block_d, TA_SOLID_PLAYER)) { player->y += REPEL_SPEED; //debug("REPEL [down]"); } } */ // do repel up if (player->CheckAttribute(player->repel_d, player->nrepel_d, TA_SOLID_PLAYER)) { if (!player->CheckAttribute(&sprites[player->sprite].block_u, TA_SOLID_PLAYER)) { player->y -= REPEL_SPEED; //debug("REPEL [up]"); } } } /* void c------------------------------() {} */ static bool RunScriptAtLocation(int x, int y) { // top-to-bottom scan for(int i=nOnscreenObjects-1; i>=0; i--) { Object *o = onscreen_objects[i]; if (o->flags & FLAG_SCRIPTONACTIVATE) { if (x >= o->Left() && x <= o->Right() && \ y >= o->Top() && y <= o->Bottom()) { game.tsc->StartScript(o->id2); return true; } } } return false; } static bool RunScriptAtX(int x) { if (RunScriptAtLocation(x, player->y + (8 * CSFI)) || \ RunScriptAtLocation(x, player->y + (14 * CSFI)) || \ RunScriptAtLocation(x, player->y + (2 * CSFI))) { return true; } return false; } // called when you press down. // Tries to find an SCRIPTONACTIVATE object you are standing near and activate it. // if it can't find anything to activate, spawns the "question mark" effect. void PTryActivateScript() { if (RunScriptAtX(player->CenterX())) return; if (player->dir == RIGHT) { if (RunScriptAtX(player->Right()) || RunScriptAtX(player->Left())) return; } else { if (RunScriptAtX(player->Left()) || RunScriptAtX(player->Right())) return; } // e.g. Plantation Rocket if (player->riding && (player->riding->flags & FLAG_SCRIPTONACTIVATE)) { game.tsc->StartScript(player->riding->id2); return; } effect(player->CenterX(), player->CenterY(), EFFECT_QMARK); } /* void c------------------------------() {} */ // does the invincibility flash when the player has recently been hurt void PDoHurtFlash(void) { // note that hurt_flash_state is NOT cleared when timer reaches 0, // but this is ok because the number of blinks are and always should be even. // (if not it wouldn't look right when he unhurts). if (player->hurt_time) { player->hurt_time--; player->hurt_flash_state = (player->hurt_time & 2); } } // decides which player frame to show void PSelectFrame(void) { if (player->lookaway) { // looking away player->frame = 11; } else if (!player->blockd || player->yinertia < 0) { // jumping/falling player->frame = (player->yinertia > 0) ? 1 : 2; } else if (player->walking) { // do walk animation static const uint8_t pwalkanimframes[] = { 0, 1, 0, 2 }; if (++player->walkanimtimer >= 5) { player->walkanimtimer = 0; if (++player->walkanimframe >= 4) player->walkanimframe = 0; if (pwalkanimframes[player->walkanimframe]==0) sound(SND_PLAYER_WALK); } player->frame = pwalkanimframes[player->walkanimframe]; } else { // standing player->frame = 0; } // switch frames to "up" or "down" versions if we're looking if (player->look) { if (player->look == UP) { if (!player->blockd || player->yinertia < 0) player->frame = 4; else player->frame += 3; } else { player->frame += 6; } } // mimiga mask support-- it would be better to make equipmask private, // and funnel all player->equipmask changes through a setter function, // then I'd feel safe doing this only when equipped items are changed. PSelectSprite(); } // mimiga mask support void PSelectSprite(void) { player->sprite = (player->equipmask & EQUIP_MIMIGA_MASK) ? \ SPR_MYCHAR_MIMIGA : SPR_MYCHAR; } /* void c------------------------------() {} */ // returns the sprite and frame # to be used for drawing the given weapon void GetSpriteForGun(int wpn, int look, int *spr, int *frame) { int s; switch(wpn) { case WPN_SUPER_MISSILE: s = SPR_SUPER_MLAUNCHER; break; case WPN_NEMESIS: s = SPR_NEMESIS; break; case WPN_BUBBLER: s = SPR_BUBBLER; break; case WPN_SPUR: s = SPR_SPUR; break; default: s = SPR_WEAPONS_START + (wpn * 2); break; } if (look) { s++; *frame = (look == DOWN); } else { *frame = 0; } *spr = s; } // returns the point that a player's shot should be centered on when firing void GetPlayerShootPoint(int *x_out, int *y_out) { int spr, frame; int x, y; GetSpriteForGun(player->curWeapon, player->look, &spr, &frame); // we have to figure out where the gun is being carried, then figure out where the // gun's sprite is drawn relative to that, then finally we can offset in the // shoot point of the gun's sprite. x = player->x + (sprites[player->sprite].frame[player->frame].dir[player->dir].actionpoint.x * CSFI); x -= sprites[spr].frame[frame].dir[player->dir].drawpoint.x * CSFI; x += sprites[spr].frame[frame].dir[player->dir].actionpoint.x * CSFI; y = player->y + (sprites[player->sprite].frame[player->frame].dir[player->dir].actionpoint.y * CSFI); y -= sprites[spr].frame[frame].dir[player->dir].drawpoint.y * CSFI; y += sprites[spr].frame[frame].dir[player->dir].actionpoint.y * CSFI; *x_out = x; *y_out = y; } // draws the player void DrawPlayer(void) { int scr_x, scr_y; if (player->hide || player->disabled) return; // keep his floattext position linked--do NOT update this if he is hidden // so that floattext doesn't follow him after he dies. player->DamageText->UpdatePos(player); player->XPText->UpdatePos(player); // get screen position to draw him at scr_x = (player->x / CSFI) - (map.displayed_xscroll / CSFI); scr_y = (player->y / CSFI) - (map.displayed_yscroll / CSFI); // draw his gun if (player->curWeapon != WPN_NONE && player->curWeapon != WPN_BLADE) { int spr, frame; GetSpriteForGun(player->curWeapon, player->look, &spr, &frame); // draw the gun at the player's Action Point. Since guns have their Draw Point set // to point at their handle, this places the handle in the player's hand. draw_sprite_at_dp(scr_x + sprites[player->sprite].frame[player->frame].dir[player->dir].actionpoint.x, \ scr_y + sprites[player->sprite].frame[player->frame].dir[player->dir].actionpoint.y, \ spr, frame, player->dir); } // draw the player sprite if (!player->hurt_flash_state) { draw_sprite(scr_x, scr_y, player->sprite, player->frame, player->dir); // draw the air bubble shield if we have it on if (((player->touchattr & TA_WATER) && (player->equipmask & EQUIP_AIRTANK)) || \ player->movementmode == MOVEMODE_ZEROG) { draw_sprite_at_dp(scr_x, scr_y, SPR_WATER_SHIELD, \ player->water_shield_frame, player->dir); if (++player->water_shield_timer > 1) { player->water_shield_frame ^= 1; player->water_shield_timer = 0; } } } if (player->equipmask & EQUIP_WHIMSTAR) draw_whimstars(&player->whimstar); }
24.886992
106
0.648133
sodomon2
8807b491d190378f103c681f9f4cd16d4c807b54
4,889
hpp
C++
compendium/DeclarativeServices/src/manager/ReferenceManager.hpp
hkgmahwa/CppMicroServices
05260dcf70e5f161da5093a5c8547b00d4d626ac
[ "Apache-2.0" ]
1
2020-12-08T16:21:45.000Z
2020-12-08T16:21:45.000Z
compendium/DeclarativeServices/src/manager/ReferenceManager.hpp
iHouLei/CppMicroServices
aa9cc47dde75ba9ead18df399ce08269c15e3aa1
[ "Apache-2.0" ]
null
null
null
compendium/DeclarativeServices/src/manager/ReferenceManager.hpp
iHouLei/CppMicroServices
aa9cc47dde75ba9ead18df399ce08269c15e3aa1
[ "Apache-2.0" ]
null
null
null
/*============================================================================= Library: CppMicroServices Copyright (c) The CppMicroServices developers. See the COPYRIGHT file at the top-level directory of this distribution and at https://github.com/CppMicroServices/CppMicroServices/COPYRIGHT . Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =============================================================================*/ #ifndef __REFERENCEMANAGER_HPP__ #define __REFERENCEMANAGER_HPP__ #include "cppmicroservices/BundleContext.h" #include "cppmicroservices/ServiceTracker.h" #include "../metadata/ReferenceMetadata.hpp" #include "cppmicroservices/servicecomponent/detail/ComponentInstance.hpp" #include "cppmicroservices/logservice/LogService.hpp" namespace cppmicroservices { namespace scrimpl { /** * Enum used to indicate the state of a {@link ReferenceManager} */ enum class RefEvent { BECAME_SATISFIED, /* used to notify the listener that the reference has become satisfied */ BECAME_UNSATISFIED,/* used to notify the listener that the reference has become unsatisfied */ REBIND, /* used to notify the listener that dynamic rebinding needs to happen */ }; /** * This class is used by ReferenceManager to notify it's listener about the * state of the Reference. */ struct RefChangeNotification { RefChangeNotification( std::string name, const RefEvent evt = RefEvent::BECAME_SATISFIED, const ServiceReference<void> svcRefToBind = ServiceReference<void>(), const ServiceReference<void> svcRefToUnbind = ServiceReference<void>()) : senderName(std::move(name)) , event(evt) , serviceRefToBind(svcRefToBind) , serviceRefToUnbind(svcRefToUnbind) {} std::string senderName; RefEvent event = RefEvent::BECAME_SATISFIED; ServiceReference<void> serviceRefToBind = ServiceReference<void>(); ServiceReference<void> serviceRefToUnbind = ServiceReference<void>(); }; /** * This is the interface for the ReferenceManager implementations. * This interface is consumed by ServiceComponentRuntimeImpl and * ComponentContextImpl classes to provide information about the * current state of a reference for a component. */ class ReferenceManager { public: ReferenceManager(const ReferenceManager&) = delete; ReferenceManager(ReferenceManager&&) = delete; ReferenceManager& operator=(const ReferenceManager&) = delete; ReferenceManager& operator=(ReferenceManager&&) = delete; virtual ~ReferenceManager() = default; /** * This method returns the name specified in the component * description for the reference managed by this object. */ virtual std::string GetReferenceName() const = 0; /** * This method returns the service scope specified in the component * description for the reference managed by this object. */ virtual std::string GetReferenceScope() const = 0; /** * This method returns the target string specified in the component * description for the reference managed by this object. */ virtual std::string GetLDAPString() const = 0; /** * Returns true if the reference is satisfied, false otherwise. */ virtual bool IsSatisfied() const = 0; /** * Returns true if the cardinality for this reference is "optional" */ virtual bool IsOptional() const = 0; /** * Returns a set of ServiceReferences that are bound to the component. */ virtual std::set<cppmicroservices::ServiceReferenceBase> GetBoundReferences() const = 0; /** * Returns a set of ServiceReferences that match the reference criteria but * are not bound to the component because the cardinality is not satisfied yet. */ virtual std::set<cppmicroservices::ServiceReferenceBase> GetTargetReferences() const = 0; /** * Method is used to receive callbacks when the dependency is satisfied */ virtual cppmicroservices::ListenerTokenId RegisterListener(std::function<void(const RefChangeNotification&)> notify) = 0; /** * Method is used to remove the callbacks registered using RegisterListener */ virtual void UnregisterListener(cppmicroservices::ListenerTokenId token) = 0; /** * Method to stop tracking the reference service. */ virtual void StopTracking() = 0; protected: ReferenceManager() = default; }; } } #endif // __REFERENCEMANAGER_HPP__
33.717241
123
0.714256
hkgmahwa
8809549b335c5e5d6b849af29a74696f4eb3921e
1,021
cpp
C++
hexapod_emlid/Navio/IMUSender.cpp
helios57/hexapod
82b4fc54f49e0acca62a42635ba8844abdb541a7
[ "MIT" ]
null
null
null
hexapod_emlid/Navio/IMUSender.cpp
helios57/hexapod
82b4fc54f49e0acca62a42635ba8844abdb541a7
[ "MIT" ]
null
null
null
hexapod_emlid/Navio/IMUSender.cpp
helios57/hexapod
82b4fc54f49e0acca62a42635ba8844abdb541a7
[ "MIT" ]
null
null
null
/* * IMUSender.cpp * * Created on: 26.06.2016 * Author: Helios */ #include "IMUSender.h" #include <iostream> #include <stdlib.h> #include <unistd.h> #include "NavioLib/Util.h" #include <string> #include <chrono> #include <thread> using namespace std::chrono; IMUSender::IMUSender(Mqtt *mqtt) : mqtt(mqtt) { imuData = new ch::sharpsoft::hexapod::transfer::IMU(); imu = new MPU9250(); } IMUSender::~IMUSender() { } void IMUSender::start() { imu->initialize(); } void IMUSender::loop() { milliseconds now = duration_cast<milliseconds>( system_clock::now().time_since_epoch()); long long nowAsMillis = now.count(); //if (lastSent + 9 < nowAsMillis) { imu->getMotion9(imuData); imuData->set_timestamp(nowAsMillis); mqtt->send_message(imuData); //lastSent = nowAsMillis; //} else { // long long int toSleep = lastSent + 9 - 2 - nowAsMillis; // if (toSleep > 0) { // std::this_thread::sleep_for(std::chrono::milliseconds(toSleep)); // } //} }
21.270833
70
0.63859
helios57
8810b94fa903c7663b7cf8eca63e37c50fb7ff07
28,089
cpp
C++
Engine/ModuleScene.cpp
SOLID-TEAM/SOLID_ENGINE
7fa9eccc28217d49a937fcf1dcfc052716825d30
[ "MIT" ]
2
2019-11-22T23:34:36.000Z
2019-11-27T10:27:35.000Z
Engine/ModuleScene.cpp
SOLID-TEAM/SOLID_ENGINE
7fa9eccc28217d49a937fcf1dcfc052716825d30
[ "MIT" ]
null
null
null
Engine/ModuleScene.cpp
SOLID-TEAM/SOLID_ENGINE
7fa9eccc28217d49a937fcf1dcfc052716825d30
[ "MIT" ]
null
null
null
#include "ModuleScene.h" #include "GL/glew.h" #include "Application.h" #include "C_Transform.h" #include "Viewport.h" #include "CameraEditor.h" #include "W_Scene.h" #include "ImGuizmo/ImGuizmo.h" #include "IconFontAwesome/IconsFontAwesome5.h" #include "R_Model.h" #include "R_Mesh.h" #include "external/MathGeoLib/include/Math/MathAll.h" ModuleScene::ModuleScene() { name.assign("ModuleScene"); } ModuleScene::~ModuleScene() {} bool ModuleScene::Init(Config& config) { return true; } bool ModuleScene::Start(Config& config) { // Scene --------------------- scene_name.assign("untitled"); // Root ---------------------- root_go = new GameObject("Scene Root", nullptr, true); root_go->uid = 0; // scene root always 0 uid root_go->is_static = true; root_go->ignore_culling = true; // Main camera --------------- main_camera = CreateGameObject("Main Camera", root_go, false); main_camera->AddComponent<C_Camera>(); main_camera->ignore_culling = true; // Editor camera --------------- editor_camera = new CameraEditor(); // Viewports ----------------------------- scene_viewport = new Viewport(editor_camera); game_viewport = new Viewport(main_camera); Load(config); App->importer->CreateDefaultMeshResources(); // TODO: get the last scene saved, or simply do nothing and let the user load one //ToLoadScene(scene_name.c_str()); // load default scene //ToLoadScene("default.solidscene"); // TODO: assignment 2 requeriment, auto-load street App->resources->ImportFileDropped("Assets/Models/Monkey/monkey.fbx"); App->resources->ImportFileDropped(".Editor/Models/sphere.fbx"); App->resources->ImportFileDropped(".Editor/Models/cube.fbx"); return true; } bool ModuleScene::CleanUp() { // release undo buffers while (to_undo_buffer_go.size() > 0) { to_undo_buffer_go.front()->DoCleanUp(); delete to_undo_buffer_go.front(); to_undo_buffer_go.pop_front(); } to_undo_buffer_go.clear(); std::vector<GameObject*>::iterator game_objects = root_go->childs.begin(); // TODO: search why dont work normal delete std::queue<GameObject*> delete_forever; for (; game_objects != root_go->childs.end();) { (*game_objects)->DoCleanUp(); delete_forever.push((*game_objects)); game_objects = root_go->childs.erase(game_objects); } while (!delete_forever.empty()) { delete delete_forever.front(); delete_forever.front() = nullptr; delete_forever.pop(); } selected_go = nullptr; main_camera = nullptr; // Clear lists -------------------------------------------------- static_go_list.clear(); dynamic_go_list.clear(); go_to_render.clear(); // TODO /*if (editor_camera != nullptr) { delete editor_camera; editor_camera = nullptr; }*/ return true; } update_status ModuleScene::PreUpdate() // TODO: SHORTCUTS { if (create_new_scene) { // If scene has selected go save id --------------- if (selected_go != nullptr) { last_selected_go_uid = selected_go->uid; } App->editor->DeselectSelectedObject(); CleanUp(); create_new_scene = false; if (!load_new_scene) { // Main camera --------------- main_camera = CreateGameObject("Main Camera", root_go, false); main_camera->AddComponent<C_Camera>(); main_camera->ignore_culling = true; game_viewport->SetCamera(main_camera); } } if (load_new_scene) { LoadSceneNow(); load_new_scene = false; // After reload scene attach it again -------------- if (delete_after_load) { GameObject* last_selected_go = FindByUID(last_selected_go_uid, root_go); if (last_selected_go != nullptr) { App->editor->SetSelectedObject(last_selected_go, SelectedObject::Type::GAME_OBJECT); } } // TODO!!!: // in the case the save doesnt contain any camera, adds default one if (main_camera == nullptr) { // Main camera --------------- main_camera = CreateGameObject("Main Camera", root_go, false); main_camera->AddComponent<C_Camera>(); main_camera->ignore_culling = true; game_viewport->SetCamera(main_camera); } } // check CTRL + Z if (App->input->GetKey(SDL_SCANCODE_LCTRL) == KEY_REPEAT && App->input->GetKey(SDL_SCANCODE_Z) == KEY_DOWN) { UndoLastDelete(); } // Set selected game object --------------------------- if (App->editor->IsSelectedObjectValid(SelectedObject::Type::GAME_OBJECT)) { selected_go = (GameObject*)App->editor->GetSelectedObject().data; } else { selected_go = nullptr; } return UPDATE_CONTINUE; } update_status ModuleScene::Update() { // Update hierarchy ----------------------------------------- UpdateHierarchy(); // Update Game Objects Lists ------------------------------- UpdateGoLists(); // Update All GameObjects ----------------------------------- if (editor_camera) editor_camera->DoUpdate(); if (root_go != nullptr) { std::stack<GameObject*> go_stack; go_stack.push(root_go); while (!go_stack.empty()) { GameObject* go = go_stack.top(); go_stack.pop(); if (go->active) { go->DoUpdate(); for (GameObject* child : go->childs) { go_stack.push(child); } } } } // Update Space partitioning ------------------------------ UpdateSpacePartitioning(); // -------------------------------------------------------- UpdateMousePicking(); // Update Gizmo -------------------------------------------- UpdateGizmo(); // Update render list ------------------------------------- (Pre Render/Draw Function ?) UpdateGoToRender(); return UPDATE_CONTINUE; } update_status ModuleScene::Draw() { C_Camera* camera = main_camera->GetComponent<C_Camera>(); for (Viewport* viewport : viewports) { if (!viewport->active) continue; editor_mode = (viewport == scene_viewport) ? true : false; // Begin ----------------------------------------------- viewport->BeginViewport(); // Draw GameObjects / Components ----------------------- for (GameObject* go : go_to_render) { go->DoRender(); } // TODO:: Remove light -------------------------------- App->renderer3D->lights[0].SetPos(viewport->GetCamera()->linked_go->transform->position); App->renderer3D->lights[0].Render(); // Debug Renders -------------------------------------- if (editor_mode) { // Main grid --------------------------- App->test->main_grid->Render(); // Space partitioning ------------------ if (render_kdtree && camera->culling && App->time->game_state != GameState::STOP) App->renderer3D->RenderKDTree(kdtree, 3.f); } // End ------------------------------------------------ viewport->EndViewport(); } // Always clean render list ------------------------------ debug_renders.clear(); go_to_render.clear(); return UPDATE_CONTINUE; } void ModuleScene::UpdateMousePicking() { if (App->input->GetMouseButton(SDL_BUTTON_LEFT) == KEY_DOWN && IsGizmoActived() == false && App->editor->w_scene->is_focused ) { std::vector< GameObject*> intersections; float2 screen_point(ImGui::GetMousePos().x, ImGui::GetMousePos().y); C_Camera* camera = editor_camera->GetComponent<C_Camera>(); if (!scene_viewport->ScreenPointToViewport(screen_point)) { return; // Point not contained in viewport pixel size } LineSegment& ray = camera->ViewportPointToRay(screen_point); uint check = 0; // Get all dynamic ray intersections ------------------------------------ for (GameObject* go : dynamic_go_list) { if (go->bounding_box.IsFinite() && go->bounding_box.Intersects(ray)) { intersections.push_back(go); } } for (GameObject* go : static_go_list) { if (go->bounding_box.IsFinite() && go->bounding_box.Intersects(ray)) { intersections.push_back(go); } } // Check all meshes ----------------------------------------------------- LineSegment local_ray; Triangle triangle; float* vertices = nullptr; uint* indices = nullptr; uint indx = 0u; R_Mesh* res = nullptr; C_Mesh* mesh = nullptr; float triangle_dist = 100.f; float near_triangle_dist = triangle_dist; GameObject* near_go = nullptr; for (GameObject* go : intersections) { mesh = go->GetComponent<C_Mesh>(); if (mesh != nullptr) res = (R_Mesh*)App->resources->Get(mesh->GetResource()); if (res == nullptr) continue; local_ray = ray; local_ray.Transform(go->transform->GetGlobalTransform().Inverted()); vertices = res->vertices; indices = res->indices; for (uint i = 0u; i < res->buffers_size[R_Mesh::INDICES]; i += 3u) { // Set triangle ------------------------------------------------- indx = indices[i]; triangle.a = (float3)&vertices[indx *3]; indx = indices[i + 1u]; triangle.b = (float3)&vertices[indx * 3]; indx = indices[i + 2u]; triangle.c = (float3)&vertices[indx * 3]; // Check intersection ------------------------------------------- float3 hit_point; if (local_ray.Intersects(triangle, &triangle_dist, &hit_point)) { hit_point = go->transform->GetGlobalTransform().MulPos(hit_point); if (triangle_dist < near_triangle_dist) { near_go = go; near_triangle_dist = triangle_dist; } } } } if (near_go != nullptr) { App->editor->SetSelectedObject(near_go, SelectedObject::Type::GAME_OBJECT); } else { App->editor->DeselectSelectedObject(); } selected_go = near_go; } } void ModuleScene::UpdateHierarchy() { // iterates once the list, if any goes wrong inform to user for (std::vector<GameObject*>::iterator gotu = temp_to_undo_go.begin(); gotu != temp_to_undo_go.end(); ++gotu) { if ((*gotu)->parent != nullptr) { std::vector<GameObject*>::iterator it = std::find((*gotu)->parent->childs.begin(), (*gotu)->parent->childs.end(), (*gotu)); if (it != (*gotu)->parent->childs.end()) { (*gotu)->parent->childs.erase(it); LOG(" ------------------------------------------------------- "); LOG("[Info] Succesfully erased child %s from parent %s", (*gotu)->GetName(), (*gotu)->parent->GetName()); // Delete from lists ----------------- std::stack<GameObject*> go_stack; go_stack.push((*gotu)); while (!go_stack.empty()) { GameObject* go = go_stack.top(); go_stack.pop(); PushEvent(go, (go->is_static) ? EventGoType::DELETE_FROM_STATIC : EventGoType::DELETE_FROM_DYNAMIC); for (GameObject* child : go->childs) { go_stack.push(child); } } // Add to undo buffer --------------- AddGOToUndoDeque(*gotu); LOG(" ------------------------------------------------------- "); // "unselect from hierarchy" App->editor->DeselectSelectedObject(); selected_go = nullptr; } else LOG("child not found on parent"); } else LOG("[Info] Parent not found"); } if (temp_to_undo_go.size() > 0) temp_to_undo_go.clear(); // RE-parent all needed childrens if needed -------------- // map is done for when we are able to move on hierarchy more than 1 go at once WIP std::map<GameObject*, GameObject*>::iterator it = childrens_to_move.begin(); for (; it != childrens_to_move.end(); ++it) { (*it).first->AddChild((*it).second); } if (childrens_to_move.size() > 0) childrens_to_move.clear(); } void ModuleScene::UpdateGoLists() { EventGo event_go; //GameObject* go = nullptr; while (!events_go_stack.empty()) { event_go = events_go_stack.top(); events_go_stack.pop(); if (event_go.go == nullptr) continue; if (event_go.type == EventGoType::ADD_TO_STATIC) { static_go_list.push_back(event_go.go); update_kdtree = true; } else if (event_go.type == EventGoType::ADD_TO_DYNAMIC) { dynamic_go_list.push_back(event_go.go); } else if (event_go.type == EventGoType::DELETE_FROM_STATIC) { static_go_list.remove(event_go.go); update_kdtree = true; if (event_go.go == selected_go) { App->editor->DeselectSelectedObject(); selected_go = nullptr; } } else if (event_go.type == EventGoType::DELETE_FROM_DYNAMIC) { dynamic_go_list.remove(event_go.go); if (event_go.go == selected_go) { App->editor->DeselectSelectedObject(); selected_go = nullptr; } } else if (event_go.type == EventGoType::DYNAMIC_TO_STATIC || event_go.type == EventGoType::STATIC_TO_DYNAMIC) { std::list<GameObject*>& list_from = (event_go.type == EventGoType::DYNAMIC_TO_STATIC) ? (dynamic_go_list) : (static_go_list); std::list<GameObject*>& list_to = (event_go.type == EventGoType::DYNAMIC_TO_STATIC) ? (static_go_list) : (dynamic_go_list); list_from.remove(event_go.go); list_to.push_back(event_go.go); update_kdtree = true; } else if (event_go.type == EventGoType::DEACTIVATE) { RemoveMyTreeFromPartitioningLists(event_go.go); } else if (event_go.type == EventGoType::ACTIVATE) { if(!IsAnyParentInactive(event_go.go)) AddMyTreeToPartitioningLists(event_go.go); } } dynamic_go_list.unique(); static_go_list.unique(); } void ModuleScene::RemoveMyTreeFromPartitioningLists(GameObject* go) { go->is_static ? static_go_list.remove(go) : dynamic_go_list.remove(go); for (std::vector<GameObject*>::iterator it = go->childs.begin(); it != go->childs.end(); ++it) { RemoveMyTreeFromPartitioningLists(*it); } update_kdtree = true; } bool ModuleScene::IsAnyParentInactive(GameObject* go) const { std::stack<GameObject*> go_stack; go_stack.push(go); bool inactive_parent = false; while (!go_stack.empty()) { GameObject* _go = go_stack.top(); if (!_go->active && _go != go) { inactive_parent = true; break; } go_stack.pop(); if (_go->parent != nullptr) go_stack.push(_go->parent); } return inactive_parent; } void ModuleScene::AddMyTreeToPartitioningLists(GameObject* go) { if (!go->active) return; go->is_static ? static_go_list.push_back(go) : dynamic_go_list.push_back(go); for (std::vector<GameObject*>::iterator it = go->childs.begin(); it != go->childs.end(); ++it) { AddMyTreeToPartitioningLists(*it); } update_kdtree = true; } void ModuleScene::UpdateGizmo() { if (selected_go != nullptr) { bool enable_gizmo; if (App->time->game_state != GameState::STOP) { enable_gizmo = !selected_go->is_static; } else { enable_gizmo = true; } ImGuizmo::Enable(enable_gizmo); float4x4 global_transform = selected_go->transform->global_transform.Transposed(); ImGuizmo::Manipulate(editor_camera->GetViewMatrix().Transposed().ptr(), editor_camera->GetProjectionMatrix().Transposed().ptr(), global_transform.ptr()); if (enable_gizmo && !global_transform.Equals(selected_go->transform->global_transform.Transposed())) { selected_go->transform->SetGlobalTransform(global_transform.Transposed()); } } } void ModuleScene::UpdateSpacePartitioning() { kdtree_collisions = 0u; dyntree_collisions = 0u; frustum_collisions = 0u; // Update kdtree for static game objects -------------------------- if (update_kdtree == true) { go_ignore_culling.clear(); std::vector<GameObject*> go_vector; for (GameObject* go : static_go_list) { //if (!go->active) continue; if (go->ignore_culling) { go_ignore_culling.push_back(go); } else if (go->bounding_box.IsFinite()) { go_vector.push_back(go); } } kdtree.Fill(4, 2, EncloseAllStaticGo(), go_vector); update_kdtree = false; } } void ModuleScene::UpdateGoToRender() { // Fill render list ---------------------------------------------- C_Camera* camera = main_camera->GetComponent<C_Camera>(); if (camera->culling && App->time->game_state != GameState::STOP) // Check if go is colliding with main camera frustum optimizing the game { // Add dynamic go to render list ----------------------------- for (GameObject* go : dynamic_go_list) { //if (!go->active) continue; if (go->ignore_culling) { go_to_render.push_back(go); } else if (go->bounding_box.IsFinite()) { camera->CheckCollisionAABB(go->bounding_box) ? go_to_render.push_back(go) : false; ++frustum_collisions; } } // Add static game objects ----------------------------------- kdtree.GetIntersections<C_Camera>(*camera, go_to_render, kdtree_collisions); frustum_collisions += kdtree_collisions; go_to_render.insert(go_to_render.end(), go_ignore_culling.begin(), go_ignore_culling.end()); // Merge go ignore culling } else // Directly render all go without any optimization { go_to_render.insert(go_to_render.end(), static_go_list.begin(), static_go_list.end()); // Merge go ignore culling go_to_render.insert(go_to_render.end(), dynamic_go_list.begin(), dynamic_go_list.end()); // Merge go ignore culling } // Test Window -------------------------------------------- //if (ImGui::Begin("Space Partitioning")) //{ // ImGui::Title("Game Objects"); ImGui::Text(""); // ImGui::Title("Static", 2); ImGui::Text("%i", static_go_list.size()); // ImGui::Title("Dynamic", 2); ImGui::Text("%i", dynamic_go_list.size()); // ImGui::Title("Rendering", 2); ImGui::Text("%i", go_to_render.size()); // ImGui::Spacing(); // if (camera->culling) // { // ImGui::Separator(); // ImGui::Title("KDTree"); ImGui::Text((kdtree.Active()) ? "ON" : "OFF"); // ImGui::Title("Render", 2); ImGui::Checkbox("##render_kdtree", &render_kdtree); // ImGui::Title("Checked Collisions"); ImGui::Text(""); // ImGui::Title("Frustum", 2); ImGui::Text("%i", frustum_collisions); // } // else // { // ImGui::Title("Active Camera Culling", 2); ImGui::Text(""); // } // //} //ImGui::End(); } GameObject* ModuleScene::Find(std::string name) { std::stack<GameObject*> go_stack; go_stack.push(root_go); while (!go_stack.empty()) { GameObject* go = go_stack.top(); if (go->name == name) { return go; } go_stack.pop(); for (GameObject * child : go->childs) { go_stack.push(child); } } return nullptr; } GameObject* ModuleScene::CreateGameObject(std::string name , GameObject* parent, bool is_static) { GameObject* new_go = nullptr; if (parent == nullptr) { parent = root_go; } new_go = new GameObject(name , parent, is_static); PushEvent(new_go, (is_static) ? EventGoType::ADD_TO_STATIC : EventGoType::ADD_TO_DYNAMIC); return new_go; } void ModuleScene::DeleteGameObject(GameObject* go) { temp_to_undo_go.push_back(go); } void ModuleScene::UndoLastDelete() { if (to_undo_buffer_go.size() > 0) { // re-add gameobject to its parent // TODO: for advanced delete history recovery, we must to search: // 1 -if the parent exists in the scene // 1.2 - if not, search if exists on undo buffer // 1.3 - if not, assign to scene root object // if the go previosly has parent if (to_undo_buffer_go.back()->parent != nullptr) { // re-add child to its parent to_undo_buffer_go.back()->parent->childs.push_back(to_undo_buffer_go.back()); // Add To Lists ---------------------- std::stack<GameObject*> go_stack; go_stack.push(to_undo_buffer_go.back()); while (!go_stack.empty()) { GameObject* go = go_stack.top(); go_stack.pop(); PushEvent(go , (go->is_static) ? EventGoType::ADD_TO_STATIC : EventGoType::ADD_TO_DYNAMIC); for (GameObject* child : go->childs) { go_stack.push(child); } } // TODO: if the parent is already deleted the object doesn't re-arrange on scene (not tested) || currently this never gonna happen LOG("[Info] Succesfully re-attached child %s to its parent %s", to_undo_buffer_go.back()->GetName(), to_undo_buffer_go.back()->parent->GetName()); // restore hierarchy selection App->editor->SetSelectedObject( to_undo_buffer_go.back(), SelectedObject::Type::GAME_OBJECT); LOG("[Info] %s deleted from undo buffer", to_undo_buffer_go.back()->GetName()); to_undo_buffer_go.pop_back(); } } else LOG("no more gameobjects to restore"); } void ModuleScene::PushEvent(GameObject* go, EventGoType type) { events_go_stack.push(EventGo(go, type)); } void ModuleScene::PushDebugRender(DebugRender debug_render) { debug_renders.push_back(debug_render); } AABB ModuleScene::EncloseAllStaticGo() { AABB global_aabb; global_aabb.SetNegativeInfinity(); for (GameObject* go : static_go_list) { if (go->bounding_box.IsFinite()) { global_aabb.Enclose(go->bounding_box); } } return global_aabb; } AABB ModuleScene::EncloseAllGo() { AABB global_aabb; global_aabb.SetNegativeInfinity(); std::stack<GameObject*> go_stack; go_stack.push(root_go); while (!go_stack.empty()) { GameObject* go = go_stack.top(); if (go->ignore_culling == false) { global_aabb.Enclose(go->bounding_box); } go_stack.pop(); for (GameObject* child : go->childs) { go_stack.push(child); } } return global_aabb; } void ModuleScene::AddGOToUndoDeque(GameObject* go) { if (to_undo_buffer_go.size() >= MAX_UNDO_ACTIONS) { LOG("[Error] Max %i undo buffer reached, permanently deleted %s gameObject", to_undo_buffer_go.size(), to_undo_buffer_go.front()->GetName()) to_undo_buffer_go.front()->DoCleanUp(); delete to_undo_buffer_go.front(); to_undo_buffer_go.pop_front(); } to_undo_buffer_go.push_back(go); LOG("[Info] Added %s to undo buffers", go->GetName()); } bool ModuleScene::IsGizmoActived() { return (ImGuizmo::IsOver() || ImGuizmo::IsUsing()); } std::deque<GameObject*>& ModuleScene::GetUndoDeque() { return to_undo_buffer_go; } void ModuleScene::AddGoToHierarchyChange(GameObject* target_go, GameObject* source_go) { childrens_to_move.insert({ target_go, source_go }); } // testing function to launch the process of save // TODO: add a intermediate pass for wait to order module interests and then save bool ModuleScene::ToSaveScene(const char* name, const char* destination_path) { Config new_scene_save; this->scene_name.assign(name); std::string scene_name(name + std::string(".solidscene")); // save first other scene needed values // name // etc Config other = new_scene_save.AddSection("general"); other.AddString("scene_name", name); //Config GameObjects = new_scene_save.AddSection("GameObjects"); // save all gameobjects needed values new_scene_save.AddArray("GameObjects"); SaveScene(new_scene_save, root_go); new_scene_save.SaveConfigToFile((destination_path + scene_name).c_str()); return true; } bool ModuleScene::Save(Config& config) { if (editor_camera != nullptr) { config.AddFloatArray("Camera editor position", editor_camera->transform->position.ptr(), 3); config.AddFloatArray("Camera editor rotation", editor_camera->transform->rotation.ptr(), 3); } else { config.AddFloatArray("Camera editor position", float3(0.f, 0.f, 0.f).ptr(), 3); config.AddFloatArray("Camera editor rotation", float3(0.f, 0.f, 0.f).ptr(), 3); } return true; } void ModuleScene::Load(Config& config) { if (editor_camera != nullptr) { editor_camera->SetPosition(float3( config.GetFloat("Camera editor position", 0.f, 0), config.GetFloat("Camera editor position", 0.f, 1), config.GetFloat("Camera editor position", 0.f, 2))); editor_camera->SetRotation(float3( config.GetFloat("Camera editor rotation", 0.f, 0), config.GetFloat("Camera editor rotation", 0.f, 1), config.GetFloat("Camera editor rotation", 0.f, 2))); } } bool ModuleScene::SaveScene(Config& config, GameObject* go) { for (std::vector<GameObject*>::iterator it = go->childs.begin(); it != go->childs.end(); ++it) { (*it)->Save(config); SaveScene(config, (*it)); } return true; } bool ModuleScene::LoadScene(Config& scene) { Config general = scene.GetSection("general"); scene_name.assign(general.GetString("scene_name", scene_name.c_str())); std::map<GameObject*, uint> relations; int go_count = scene.GetArrayCount("GameObjects"); if (go_count <= 0) return false; /*std::vector<GameObject*> to_load_gos; to_load_gos.reserve(go_count);*/ for (int i = 0; i < go_count; ++i) { GameObject* new_go = new GameObject("Unknown", root_go, false); new_go->Load(scene.GetArray("GameObjects", i), relations); //if(new_go->active) //PushEvent(new_go, (new_go->is_static) ? EventGoType::ADD_TO_STATIC : EventGoType::ADD_TO_DYNAMIC); //to_load_gos.push_back(new_go); } for (std::map<GameObject*, uint>::iterator it = relations.begin(); it != relations.end(); ++it) { GameObject* go = (*it).first; uint parent_id = (*it).second; if (parent_id == 0) // 0 is root scene { if (go->parent != root_go) { go->SetNewParent(root_go); } continue; } GameObject* parent_match = FindByUID(parent_id, root_go); go->SetNewParent(parent_match); } FillCullingLists(); return true; } void ModuleScene::FillCullingLists() { std::stack<GameObject*> go_stack; for(GameObject* childs_of_root : root_go->childs) go_stack.push(childs_of_root); while (!go_stack.empty()) { GameObject* go = go_stack.top(); go_stack.pop(); if (go->IsActive()) { go->is_static ? static_go_list.push_back(go) : dynamic_go_list.push_back(go); for (GameObject* child : go->childs) { go_stack.push(child); } } } } GameObject* ModuleScene::FindByUID(UID uid, GameObject* go) { GameObject* ret = nullptr; if (uid == go->uid) return go; for (std::vector<GameObject*>::iterator it = go->childs.begin(); it != go->childs.end(); ++it) { ret = FindByUID(uid, (*it)); if (ret) break; } return ret; } bool ModuleScene::LoadSceneNow() { // TODO: maybe the scene is not on assets folder, but for now we dont let decide, scene are saved on assets folder Config to_load(std::string(scene_to_load).c_str()); if(delete_after_load) App->file_sys->Remove(scene_to_load.c_str()); scene_to_load.clear(); return LoadScene(to_load);; } // TODO: pass this on finishupdate on app.cpp bool ModuleScene::ToLoadScene(const char* name, const char* source_path, bool clean, bool delete_after_load) { bool ret = false; if (name != nullptr) { // TODO: make VFS for all project files on runtime // re-search if this filename exists /*if (App->file_sys->Exists(name)) { LOG(""); }*/ /*std::vector<std::string> file_list, dir_list; file_list.push_back(name); App->file_sys->DiscoverFiles(ASSETS_FOLDER, file_list, dir_list);*/ std::vector<std::string> file_list; App->file_sys->GetAllFilesWithExtension(source_path, "solidscene", file_list); for (uint i = 0; i < file_list.size(); ++i) { if (file_list[i].compare(name) == 0) { scene_to_load.assign(source_path + std::string(name)); create_new_scene = clean; this->delete_after_load = delete_after_load; load_new_scene = true; ret = true; } } } return ret; } GameObject* ModuleScene::CreateGameObjectFromModel(UID uid) { Resource* r = App->resources->Get(uid); if (r->GetType() != Resource::Type::MODEL) { LOG("[Error] bad resource type to create gameobjects from"); return nullptr; } R_Model* model = (R_Model*)r; model->LoadToMemory(); std::vector<GameObject*> all_go; uint num_nodes = model->GetNumNodes(); all_go.reserve(num_nodes); for (uint i = 0; i < num_nodes; ++i) { const R_Model::Node& node = model->GetNode(i); GameObject* parent = root_go; if (i > 0) parent = all_go[node.parent]; GameObject* new_go = CreateGameObject(node.name.c_str(), parent); // Set transform ------------------------------- new_go->transform->SetLocalTransform(node.transform); if (node.mesh > 0) { C_Mesh* c_mesh = new_go->AddComponent< C_Mesh>(); if (c_mesh->SetMeshResource(node.mesh)) { new_go->AddComponent<C_MeshRenderer>(); } } if (node.material > 0) { C_Material* c_mat = new_go->AddComponent< C_Material>(); c_mat->SetMaterialResource(node.material); /*if (c_mat->SetMaterialResource(node.material)) { new_go->CreateComponent<C_MeshRenderer>(); }*/ } all_go.push_back(new_go); } // TODO: improve models to be a prefab, currently is only used as container of hierarchy and meshes/materials // when we are done creating a usable gameobjects classes from model data, unload model model->Release(); return all_go[0]; } std::string ModuleScene::GetSceneName() const { return scene_name; } void ModuleScene::NewScene() { create_new_scene = true; }
23.683811
155
0.651323
SOLID-TEAM
8810fa94eb1f7caf7af65704790a018db450ca89
3,524
cpp
C++
src/lib/PawPet_FlashTransport.cpp
NanoCodeBug/pawpet
da5f50f98562289ef555b44b35c74373135cda7a
[ "MIT" ]
23
2021-12-18T09:00:40.000Z
2022-03-24T03:25:13.000Z
src/lib/PawPet_FlashTransport.cpp
NanoCodeBug/pawpet
da5f50f98562289ef555b44b35c74373135cda7a
[ "MIT" ]
null
null
null
src/lib/PawPet_FlashTransport.cpp
NanoCodeBug/pawpet
da5f50f98562289ef555b44b35c74373135cda7a
[ "MIT" ]
3
2021-12-14T07:18:00.000Z
2022-01-27T19:33:27.000Z
#include "PawPet_FlashTransport.h" PawPet_FlashTransport_SPI::PawPet_FlashTransport_SPI(uint8_t ss, SPIClass *spiinterface) { _cmd_read = SFLASH_CMD_READ; _addr_len = 3; // work with most device if not set _ss = ss; _spi = spiinterface; _clock_wr = _clock_rd = 4000000; } PawPet_FlashTransport_SPI::PawPet_FlashTransport_SPI(uint8_t ss, SPIClass &spiinterface) : PawPet_FlashTransport_SPI(ss, &spiinterface) { } void PawPet_FlashTransport_SPI::begin(void) { pinMode(_ss, OUTPUT); digitalWrite(_ss, HIGH); // removed _spi->begin() } void PawPet_FlashTransport_SPI::end(void) { _spi->end(); pinMode(_ss, INPUT); } void PawPet_FlashTransport_SPI::setClockSpeed(uint32_t write_hz, uint32_t read_hz) { _clock_wr = write_hz; _clock_rd = read_hz; } bool PawPet_FlashTransport_SPI::runCommand(uint8_t command) { beginTransaction(_clock_wr); _spi->transfer(command); endTransaction(); return true; } bool PawPet_FlashTransport_SPI::readCommand(uint8_t command, uint8_t *response, uint32_t len) { beginTransaction(_clock_rd); _spi->transfer(command); while (len--) { *response++ = _spi->transfer(0xFF); } endTransaction(); return true; } bool PawPet_FlashTransport_SPI::writeCommand(uint8_t command, uint8_t const *data, uint32_t len) { beginTransaction(_clock_wr); _spi->transfer(command); while (len--) { (void)_spi->transfer(*data++); } endTransaction(); return true; } bool PawPet_FlashTransport_SPI::eraseCommand(uint8_t command, uint32_t addr) { beginTransaction(_clock_wr); uint8_t cmd_with_addr[5] = {command}; fillAddress(cmd_with_addr + 1, addr); _spi->transfer(cmd_with_addr, 1 + _addr_len); endTransaction(); return true; } void PawPet_FlashTransport_SPI::fillAddress(uint8_t *buf, uint32_t addr) { switch (_addr_len) { case 4: *buf++ = (addr >> 24) & 0xFF; //__attribute__((fallthrough)); ESP32 doesn't support this attribute yet // fall through case 3: *buf++ = (addr >> 16) & 0xFF; //__attribute__((fallthrough)); ESP32 doesn't support this attribute yet // fall through case 2: default: *buf++ = (addr >> 8) & 0xFF; *buf++ = addr & 0xFF; } } bool PawPet_FlashTransport_SPI::readMemory(uint32_t addr, uint8_t *data, uint32_t len) { beginTransaction(_clock_rd); uint8_t cmd_with_addr[6] = {_cmd_read}; fillAddress(cmd_with_addr + 1, addr); // Fast Read has 1 extra dummy byte uint8_t const cmd_len = 1 + _addr_len + (SFLASH_CMD_FAST_READ == _cmd_read ? 1 : 0); _spi->transfer(cmd_with_addr, cmd_len); // Use SPI DMA if available for best performance #if defined(ARDUINO_ARCH_SAMD) && defined(_ADAFRUIT_ZERODMA_H_) _spi->transfer(NULL, data, len, true); #else _spi->transfer(data, len); #endif endTransaction(); return true; } bool PawPet_FlashTransport_SPI::writeMemory(uint32_t addr, uint8_t const *data, uint32_t len) { beginTransaction(_clock_wr); uint8_t cmd_with_addr[5] = {SFLASH_CMD_PAGE_PROGRAM}; fillAddress(cmd_with_addr + 1, addr); _spi->transfer(cmd_with_addr, 1 + _addr_len); // Use SPI DMA if available for best performance #if defined(ARDUINO_ARCH_SAMD) && defined(_ADAFRUIT_ZERODMA_H_) _spi->transfer(data, NULL, len, true); #else while (len--) { _spi->transfer(*data++); } #endif endTransaction(); return true; }
21.753086
96
0.678207
NanoCodeBug
8811d3088cf5203a9741d816114ef5d8676aa31d
14,055
cpp
C++
tests/IResearch/IResearchQueryLateMaterialization-test.cpp
corona3000/arangodb
e4d5a5d2d7e83b1a094c5ac01706a13fdecfc1da
[ "Apache-2.0" ]
1
2020-01-16T06:16:53.000Z
2020-01-16T06:16:53.000Z
tests/IResearch/IResearchQueryLateMaterialization-test.cpp
corona3000/arangodb
e4d5a5d2d7e83b1a094c5ac01706a13fdecfc1da
[ "Apache-2.0" ]
null
null
null
tests/IResearch/IResearchQueryLateMaterialization-test.cpp
corona3000/arangodb
e4d5a5d2d7e83b1a094c5ac01706a13fdecfc1da
[ "Apache-2.0" ]
null
null
null
//////////////////////////////////////////////////////////////////////////////// /// DISCLAIMER /// /// Copyright 2019 ArangoDB GmbH, Cologne, Germany /// /// 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. /// /// Copyright holder is ArangoDB GmbH, Cologne, Germany /// /// @author Yuriy Popov //////////////////////////////////////////////////////////////////////////////// #include "IResearchQueryCommon.h" #include "Aql/OptimizerRulesFeature.h" #include "IResearch/IResearchLink.h" #include "IResearch/IResearchLinkHelper.h" #include "IResearch/IResearchView.h" #include "Transaction/StandaloneContext.h" #include "Utils/SingleCollectionTransaction.h" #include "VocBase/LogicalCollection.h" #include "VocBase/ManagedDocumentResult.h" #include <velocypack/Iterator.h> NS_LOCAL static const char* collectionName1 = "collection_1"; static const char* collectionName2 = "collection_2"; static const char* viewName1 = "view_1"; static const char* viewName2 = "view_2"; // ----------------------------------------------------------------------------- // --SECTION-- setup / tear-down // ----------------------------------------------------------------------------- class IResearchQueryLateMaterializationTest : public IResearchQueryTest { protected: std::deque<arangodb::ManagedDocumentResult> insertedDocs; void addLinkToCollection(std::shared_ptr<arangodb::iresearch::IResearchView>& view) { auto updateJson = VPackParser::fromJson( std::string("{") + "\"links\": {" "\"" + collectionName1 + "\": {\"includeAllFields\": true}," "\"" + collectionName2 + "\": {\"includeAllFields\": true}" "}}"); EXPECT_TRUE(view->properties(updateJson->slice(), true).ok()); arangodb::velocypack::Builder builder; builder.openObject(); view->properties(builder, arangodb::LogicalDataSource::Serialization::Properties); builder.close(); auto slice = builder.slice(); EXPECT_TRUE(slice.isObject()); EXPECT_TRUE(slice.get("type").copyString() == arangodb::iresearch::DATA_SOURCE_TYPE.name()); EXPECT_TRUE(slice.get("deleted").isNone()); // no system properties auto tmpSlice = slice.get("links"); EXPECT_TRUE(tmpSlice.isObject() && 2 == tmpSlice.length()); } void SetUp() override { // add collection_1 std::shared_ptr<arangodb::LogicalCollection> logicalCollection1; { auto collectionJson = VPackParser::fromJson(std::string("{\"name\": \"") + collectionName1 + "\"}"); logicalCollection1 = vocbase().createCollection(collectionJson->slice()); ASSERT_NE(nullptr, logicalCollection1); } // add collection_2 std::shared_ptr<arangodb::LogicalCollection> logicalCollection2; { auto collectionJson = VPackParser::fromJson(std::string("{\"name\": \"") + collectionName2 + "\"}"); logicalCollection2 = vocbase().createCollection(collectionJson->slice()); ASSERT_NE(nullptr, logicalCollection2); } // create view_1 std::shared_ptr<arangodb::iresearch::IResearchView> view1; { auto createJson = VPackParser::fromJson( std::string("{") + "\"name\": \"" + viewName1 + "\", \ \"type\": \"arangosearch\" \ }"); view1 = std::dynamic_pointer_cast<arangodb::iresearch::IResearchView>( vocbase().createView(createJson->slice())); ASSERT_FALSE(!view1); // add links to collections addLinkToCollection(view1); } // create view_2 std::shared_ptr<arangodb::iresearch::IResearchView> view2; { auto createJson = VPackParser::fromJson( std::string("{") + "\"name\": \"" + viewName2 + "\", \ \"type\": \"arangosearch\", \ \"primarySort\": [{\"field\": \"value\", \"direction\": \"asc\"}, {\"field\": \"foo\", \"direction\": \"desc\"}] \ }"); view2 = std::dynamic_pointer_cast<arangodb::iresearch::IResearchView>( vocbase().createView(createJson->slice())); ASSERT_FALSE(!view2); // add links to collections addLinkToCollection(view2); } // populate view with the data { arangodb::OperationOptions opt; static std::vector<std::string> const EMPTY; arangodb::transaction::Methods trx( arangodb::transaction::StandaloneContext::Create(vocbase()), EMPTY, EMPTY, EMPTY, arangodb::transaction::Options()); EXPECT_TRUE(trx.begin().ok()); // insert into collection_1 { auto builder = VPackParser::fromJson( "[" "{\"_key\": \"c0\", \"str\": \"cat\", \"foo\": \"foo0\", \"value\": 0}," "{\"_key\": \"c1\", \"str\": \"cat\", \"foo\": \"foo1\", \"value\": 1}," "{\"_key\": \"c2\", \"str\": \"cat\", \"foo\": \"foo2\", \"value\": 2}," "{\"_key\": \"c3\", \"str\": \"cat\", \"foo\": \"foo3\", \"value\": 3}" "]"); auto root = builder->slice(); ASSERT_TRUE(root.isArray()); for (auto doc : arangodb::velocypack::ArrayIterator(root)) { insertedDocs.emplace_back(); auto const res = logicalCollection1->insert(&trx, doc, insertedDocs.back(), opt, false); EXPECT_TRUE(res.ok()); } } // insert into collection_2 { auto builder = VPackParser::fromJson( "[" "{\"_key\": \"c_0\", \"str\": \"cat\", \"foo\": \"foo_0\", \"value\": 10}," "{\"_key\": \"c_1\", \"str\": \"cat\", \"foo\": \"foo_1\", \"value\": 11}," "{\"_key\": \"c_2\", \"str\": \"cat\", \"foo\": \"foo_2\", \"value\": 12}," "{\"_key\": \"c_3\", \"str\": \"cat\", \"foo\": \"foo_3\", \"value\": 13}" "]"); auto root = builder->slice(); ASSERT_TRUE(root.isArray()); for (auto doc : arangodb::velocypack::ArrayIterator(root)) { insertedDocs.emplace_back(); auto const res = logicalCollection2->insert(&trx, doc, insertedDocs.back(), opt, false); EXPECT_TRUE(res.ok()); } } EXPECT_TRUE(trx.commit().ok()); EXPECT_TRUE(arangodb::iresearch::IResearchLinkHelper::find(*logicalCollection1, *view1) ->commit().ok()); EXPECT_TRUE(arangodb::iresearch::IResearchLinkHelper::find(*logicalCollection2, *view1) ->commit().ok()); EXPECT_TRUE(arangodb::iresearch::IResearchLinkHelper::find(*logicalCollection1, *view2) ->commit().ok()); EXPECT_TRUE(arangodb::iresearch::IResearchLinkHelper::find(*logicalCollection2, *view2) ->commit().ok()); } } void executeAndCheck(std::string const& query, std::vector<arangodb::velocypack::Slice> const& expectedDocs, bool checkRuleOnly) { EXPECT_TRUE(arangodb::tests::assertRules(vocbase(), query, {arangodb::aql::OptimizerRule::handleArangoSearchViewsRule})); EXPECT_TRUE(arangodb::tests::assertRules(vocbase(), query, {arangodb::aql::OptimizerRule::lateDocumentMaterializationArangoSearchRule})); auto queryResult = arangodb::tests::executeQuery(vocbase(), query); ASSERT_TRUE(queryResult.result.ok()); auto result = queryResult.data->slice(); EXPECT_TRUE(result.isArray()); if (checkRuleOnly) { return; } arangodb::velocypack::ArrayIterator resultIt(result); ASSERT_EQ(expectedDocs.size(), resultIt.size()); // Check documents auto expectedDoc = expectedDocs.begin(); for (; resultIt.valid(); resultIt.next(), ++expectedDoc) { auto const actualDoc = resultIt.value(); auto const resolved = actualDoc.resolveExternals(); EXPECT_TRUE(0 == arangodb::basics::VelocyPackHelper::compare( arangodb::velocypack::Slice(*expectedDoc), resolved, true)); } EXPECT_EQ(expectedDoc, expectedDocs.end()); } }; NS_END // ----------------------------------------------------------------------------- // --SECTION-- test suite // ----------------------------------------------------------------------------- TEST_F(IResearchQueryLateMaterializationTest, test_1) { auto const query = std::string("FOR d IN ") + viewName2 + " SEARCH d.value IN [1, 2, 11, 12] LET a = NOOPT(d.foo) LET e = SUM(FOR c IN " + viewName1 + " LET p = CONCAT(c.foo, c.foo) RETURN p) SORT CONCAT(a, e) LIMIT 10 RETURN d"; std::vector<arangodb::velocypack::Slice> expectedDocs{ arangodb::velocypack::Slice(insertedDocs[5].vpack()), arangodb::velocypack::Slice(insertedDocs[6].vpack()), arangodb::velocypack::Slice(insertedDocs[1].vpack()), arangodb::velocypack::Slice(insertedDocs[2].vpack()) }; executeAndCheck(query, expectedDocs, false); } TEST_F(IResearchQueryLateMaterializationTest, test_2) { auto const query = std::string("FOR d IN ") + viewName2 + " FILTER d.value IN [1, 2] SORT d.foo DESC LIMIT 10 RETURN d"; std::vector<arangodb::velocypack::Slice> expectedDocs{ arangodb::velocypack::Slice(insertedDocs[2].vpack()), arangodb::velocypack::Slice(insertedDocs[1].vpack()) }; executeAndCheck(query, expectedDocs, false); } TEST_F(IResearchQueryLateMaterializationTest, test_3) { auto const query = std::string("FOR d IN ") + viewName2 + " SEARCH d.value IN [1, 2, 11, 12] SORT d.value DESC LET c = BM25(d) * 2 SORT CONCAT(BM25(d), c, d.value) LIMIT 10 RETURN d"; std::vector<arangodb::velocypack::Slice> expectedDocs{ arangodb::velocypack::Slice(insertedDocs[1].vpack()), arangodb::velocypack::Slice(insertedDocs[5].vpack()), arangodb::velocypack::Slice(insertedDocs[6].vpack()), arangodb::velocypack::Slice(insertedDocs[2].vpack()) }; executeAndCheck(query, expectedDocs, false); } TEST_F(IResearchQueryLateMaterializationTest, test_4) { auto const query = std::string("FOR d IN ") + viewName2 + " SEARCH d.value IN [1, 2, 11, 12] SORT RAND(), d.value DESC LIMIT 10 RETURN d"; executeAndCheck(query, std::vector<arangodb::velocypack::Slice>{}, true); } TEST_F(IResearchQueryLateMaterializationTest, test_5) { auto const query = std::string("FOR d IN ") + viewName2 + " SEARCH d.value IN [1, 2, 11, 12] SORT d.value DESC, d.foo LIMIT 10 RETURN d"; std::vector<arangodb::velocypack::Slice> expectedDocs{ arangodb::velocypack::Slice(insertedDocs[6].vpack()), arangodb::velocypack::Slice(insertedDocs[5].vpack()), arangodb::velocypack::Slice(insertedDocs[2].vpack()), arangodb::velocypack::Slice(insertedDocs[1].vpack()) }; executeAndCheck(query, expectedDocs, false); } TEST_F(IResearchQueryLateMaterializationTest, test_6) { auto const query = std::string("FOR d IN ") + viewName2 + " SEARCH d.value IN [1, 2, 11, 12] SORT d.value DESC LIMIT 10 RETURN d"; std::vector<arangodb::velocypack::Slice> expectedDocs{ arangodb::velocypack::Slice(insertedDocs[6].vpack()), arangodb::velocypack::Slice(insertedDocs[5].vpack()), arangodb::velocypack::Slice(insertedDocs[2].vpack()), arangodb::velocypack::Slice(insertedDocs[1].vpack()) }; executeAndCheck(query, expectedDocs, false); } TEST_F(IResearchQueryLateMaterializationTest, test_7) { auto const query = std::string("FOR d IN ") + viewName2 + " SEARCH d.value IN [1, 2, 11, 12] SORT d.value DESC LIMIT 10 SORT NOOPT(d.value) ASC RETURN d"; std::vector<arangodb::velocypack::Slice> expectedDocs{ arangodb::velocypack::Slice(insertedDocs[1].vpack()), arangodb::velocypack::Slice(insertedDocs[2].vpack()), arangodb::velocypack::Slice(insertedDocs[5].vpack()), arangodb::velocypack::Slice(insertedDocs[6].vpack()) }; executeAndCheck(query, expectedDocs, false); } TEST_F(IResearchQueryLateMaterializationTest, test_8) { auto const query = std::string("FOR d IN ") + viewName2 + " SEARCH d.value IN [1, 2, 11, 12] SORT d.value DESC LIMIT 10 SORT TFIDF(d) DESC LIMIT 4 RETURN d"; executeAndCheck(query, std::vector<arangodb::velocypack::Slice>{}, true); } TEST_F(IResearchQueryLateMaterializationTest, test_9) { auto const query = std::string("FOR d IN ") + viewName2 + " SEARCH d.value IN [1, 2, 11, 12] SORT d.value DESC LIMIT 10 LET c = CONCAT(NOOPT(d._key), '-C') RETURN c"; executeAndCheck(query, std::vector<arangodb::velocypack::Slice>{}, true); } TEST_F(IResearchQueryLateMaterializationTest, test_10) { auto const query = std::string("FOR d IN ") + viewName2 + " SEARCH d.value IN [1, 2, 11, 12] SORT d.value DESC LIMIT 3, 1 RETURN d"; std::vector<arangodb::velocypack::Slice> expectedDocs{ arangodb::velocypack::Slice(insertedDocs[1].vpack()) }; executeAndCheck(query, expectedDocs, false); } TEST_F(IResearchQueryLateMaterializationTest, test_11) { auto const query = std::string("FOR d IN ") + viewName2 + " SEARCH d.value IN [1, 2, 11, 12] SORT d.value DESC LIMIT 5, 10 RETURN d"; executeAndCheck(query, std::vector<arangodb::velocypack::Slice>{}, false); } TEST_F(IResearchQueryLateMaterializationTest, test_12) { auto const query = std::string("FOR c IN ") + viewName1 + " SEARCH c.value == 1 FOR d IN " + viewName2 + " SEARCH d.value IN [c.value, c.value + 1] SORT d.value DESC LIMIT 10 RETURN d"; std::vector<arangodb::velocypack::Slice> expectedDocs{ arangodb::velocypack::Slice(insertedDocs[2].vpack()), arangodb::velocypack::Slice(insertedDocs[1].vpack()) }; executeAndCheck(query, expectedDocs, false); }
38.401639
132
0.618072
corona3000
88134cd91cf5d4dfcb9dcb98cf6d92176a79f3f1
9,479
cpp
C++
_studio/mfx_lib/shared/src/mfx_log.cpp
jwang11/MediaSDK
08cb9405401d1db3599bd16580249c4690914be3
[ "MIT" ]
1
2018-08-28T09:47:31.000Z
2018-08-28T09:47:31.000Z
_studio/mfx_lib/shared/src/mfx_log.cpp
jwang11/MediaSDK
08cb9405401d1db3599bd16580249c4690914be3
[ "MIT" ]
2
2017-10-09T10:34:44.000Z
2017-11-29T12:20:13.000Z
_studio/mfx_lib/shared/src/mfx_log.cpp
jwang11/MediaSDK
08cb9405401d1db3599bd16580249c4690914be3
[ "MIT" ]
1
2018-01-04T06:53:11.000Z
2018-01-04T06:53:11.000Z
// Copyright (c) 2017 Intel Corporation // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. #include <mfx_log.h> #include <umc_mutex.h> #include <umc_automatic_mutex.h> #if defined(LINUX32) || defined(LINUX64) #error Overlappped I/O mechanism is not implemented in Unix version. #include <unistd.h> #include <stdbool.h> #include <sys/types.h> #include <sys/syscall.h> // Be care. Need to check sizeof. typedef char byte_t; typedef long dword_t; typedef long DWORD; typedef bool BOOL; #define FALSE false; #define TRUE true; #endif #include <stdio.h> using namespace UMC; // static section of the file namespace { // Declare the byte type typedef unsigned char byte_t; typedef unsigned int dword_t; // Declare the default log path const char *MFX_LOG_DEFAULT_PATH = "c:\\mfx_log.log"; enum { MFX_LOG_ALIGN_VALUE = 64 * 1024, MFX_LOG_NUM_PARTS = 4, MFX_LOG_DEF_SIZE = 1024 * 1024 }; // Declare log class class mfxLogObject { public: // Default constructor mfxLogObject(void) { #if defined(LINUX32) || defined(LINUX64) m_file = NULL; #endif #if defined(LINUX32) || defined(LINUX64) # error Overlappped I/O mechanism is not implemented in Unix version. #endif m_pAlloc = 0; m_allocSize = 0; memset(m_pBuf, 0, sizeof(m_pBuf)); m_pCur = 0; m_bufSize = 0; m_logIdx = 0; m_callNumber = 0; } // Destructor ~mfxLogObject(void) { // exchange the last buffer to avoid data loss if (m_pCur) { if (MFX_LOG_DEF_SIZE != m_bufSize) { memset(m_pCur, 0, m_bufSize); m_pCur += m_bufSize; m_bufSize = 0; ExchangeBuffer(); } } Release(); } bool Init(const char *pLogPath) { dword_t i; // check error(s) if (0 == pLogPath) { return false; } // release the object before initialzation Release(); // open the destination file #if defined(LINUX32) || defined(LINUX64) m_file = fopen(pLogPath, "rw"); if (NULL == m_file) { return false; } #endif #if defined(LINUX32) || defined(LINUX64) # error Overlappped I/O mechanism is not implemented in Unix version. #endif // create the output buffer m_pAlloc = new byte_t [MFX_LOG_DEF_SIZE * MFX_LOG_NUM_PARTS + MFX_LOG_ALIGN_VALUE]; m_allocSize = MFX_LOG_DEF_SIZE * MFX_LOG_NUM_PARTS; // set the working buffers m_pBuf[0] = m_pAlloc + ((MFX_LOG_ALIGN_VALUE - ((size_t) (m_pAlloc - 0))) & (MFX_LOG_ALIGN_VALUE - 1)); for (i = 1; i < MFX_LOG_NUM_PARTS; i += 1) { m_pBuf[i] = m_pBuf[i - 1] + MFX_LOG_DEF_SIZE; } // set the current buffer position m_pCur = m_pBuf[0]; m_bufSize = MFX_LOG_DEF_SIZE; m_callNumber = 0; return true; } void AddString(const char *pStr, size_t strLen) { AutomaticUMCMutex guard(m_guard); char cStr[32]; size_t callNumLen; // check error(s) if (false == isReady()) { return; } // render current call number #if defined(LINUX32) || defined(LINUX64) callNumLen = sprintf(cStr, "[% 8u]", m_callNumber += 1); #endif AddStringSafe(cStr, callNumLen); AddStringSafe(pStr, strLen); } bool isReady(void) { return (0 != m_pCur); } protected: // Release the object void Release(void) { dword_t i; DWORD nWritten; #if defined(LINUX32) || defined(LINUX64) # error Overlappped I/O mechanism is not implemented in Unix version. #endif #if defined(LINUX32) || defined(LINUX64) if (NULL != m_file) { fclose(m_file); m_file = NULL; } #endif if (m_pAlloc) { delete [] m_pAlloc; } #if defined(LINUX32) || defined(LINUX64) # error Overlappped I/O mechanism is not implemented in Unix version. #endif m_pAlloc = 0; m_allocSize = 0; memset(m_pBuf, 0, sizeof(m_pBuf)); m_pCur = 0; m_bufSize = 0; m_logIdx = 0; } void AddStringSafe(const char *pStr, size_t strLen) { // check error(s) if ((0 == pStr) || (strLen > MFX_LOG_DEF_SIZE)) { return; } do { size_t copySize; // copy the string to the buffer copySize = (m_bufSize < strLen) ? (m_bufSize) : (strLen); memcpy_s(m_pCur, copySize, pStr, copySize); m_pCur += copySize; m_bufSize -= copySize; pStr += copySize; strLen -= copySize; // issue file writing if (0 == m_bufSize) { ExchangeBuffer(); } } while (strLen); } // Set the current buffer to the flushing state, // get a fresh buffer to save. void ExchangeBuffer(void) { dword_t newLogIdx = (m_logIdx + 1) % MFX_LOG_NUM_PARTS; DWORD nWritten; BOOL bRes; // the current buffer has nothing if (m_bufSize == MFX_LOG_DEF_SIZE) { return; } #if defined(LINUX32) || defined(LINUX64) # error Overlappped I/O mechanism is not implemented in Unix version. #endif #if defined(LINUX32) || defined(LINUX64) // start writing operation bRes = fwrite(m_pBuf[m_logIdx], MFX_LOG_DEF_SIZE, 1, m_file); if (MFX_LOG_DEF_SIZE != bRes) { return; } #endif // exchange the buffer m_logIdx = newLogIdx; m_pCur = m_pBuf[m_logIdx]; m_bufSize = MFX_LOG_DEF_SIZE; } // Log guard Mutex m_guard; // Output file #if defined(LINUX32) || defined(LINUX64) FILE *m_file; #endif // Overlapped I/O are absent on Linux. // Unix sockets provides same functionality in the readv() and writev() calls. // Some Unixes provide the aio_*() family of functions, but this is not implemented widely at the moment. // Allocated buffer byte_t *m_pAlloc; // Allocated buffer size size_t m_allocSize; // Array of working buffers byte_t *(m_pBuf[MFX_LOG_NUM_PARTS]); // Current position in the buffer byte_t *m_pCur; // Remain buffer size size_t m_bufSize; // Current log buffer index dword_t m_logIdx; // Current call number dword_t m_callNumber; }; mfxLogObject defaultLogObject; const log_t defaultLog = &defaultLogObject; } // namespace extern "C" log_t mfxLogInit(const char *pLogPath) { mfxLogObject *pLog = NULL; // check if the default log is initialized already if (0 == pLogPath) { if (defaultLogObject.isReady()) { return (log_t) defaultLog; } } try { // allocate one more log object if (pLogPath) { pLog = new mfxLogObject(); } else { pLog = &defaultLogObject; pLogPath = MFX_LOG_DEFAULT_PATH; } if (false == pLog->Init(pLogPath)) { throw (int) 0; } } catch(...) { // delete log object if ((pLog) && (pLog != &defaultLogObject)) { delete pLog; pLog = 0; } } return (log_t) pLog; } // log_t mfxLogInit(const char *pLogPath) extern "C" void mfxLogWriteA(const log_t log, const char *pString, ...) { mfxLogObject *pLog = (mfxLogObject *) log; char cStr[4096]; va_list argList; size_t strLen; if (0 == pLog) { pLog = &defaultLogObject; } // create argument list va_start(argList, pString); // render the string strLen = vsprintf(cStr, pString, argList); pLog->AddString(cStr, strLen); } // void mfxLogWriteA(const log_t log, const char *pString, ...) extern "C" void mfxLogClose(log_t log) { mfxLogObject *pLog = (mfxLogObject *) log; // check if it is not a default log object if ((0 == pLog) || (pLog == &defaultLogObject)) { return; } try { delete pLog; } catch(...) { } } // void mfxLogClose(log_t log)
23.06326
111
0.58445
jwang11
88137ff0b25723a3f0c6d905c0f0c047348c3982
417
cpp
C++
2021/12. Classes/20311029/01.Point/point.cpp
RumiChausheva/CS104
95f4df990f1a9d1397fc7da7cf137aa092498ea1
[ "MIT" ]
7
2021-03-24T16:30:45.000Z
2022-03-27T09:02:15.000Z
2021/12. Classes/20311029/01.Point/point.cpp
RumiChausheva/CS104
95f4df990f1a9d1397fc7da7cf137aa092498ea1
[ "MIT" ]
null
null
null
2021/12. Classes/20311029/01.Point/point.cpp
RumiChausheva/CS104
95f4df990f1a9d1397fc7da7cf137aa092498ea1
[ "MIT" ]
17
2021-03-22T09:42:22.000Z
2022-03-28T03:24:07.000Z
#include <iostream>; #include "point.h"; using namespace std; void point::setX(int xInput) { x = xInput; } void point::setY(int yInput) { y = yInput; } point::point() { setX(0); setY(0); } point::point(int x, int y) { setX(x); setY(y); } point::~point() { } int point::getX() { return x; } int point::getY() { return y; } void point::print() { cout << "Point: x = " << x << ", y= " << y << endl; }
8.87234
52
0.551559
RumiChausheva
88143795c180073063bcd08f0ea6146e848503d9
13,879
cpp
C++
android/app/src/cpp/src/backend/cpu/CpuWorker.cpp
FlameSalamander/react-native-xmrig
6a6e3b301bd78b88459989f334d759f65e434082
[ "MIT" ]
null
null
null
android/app/src/cpp/src/backend/cpu/CpuWorker.cpp
FlameSalamander/react-native-xmrig
6a6e3b301bd78b88459989f334d759f65e434082
[ "MIT" ]
null
null
null
android/app/src/cpp/src/backend/cpu/CpuWorker.cpp
FlameSalamander/react-native-xmrig
6a6e3b301bd78b88459989f334d759f65e434082
[ "MIT" ]
null
null
null
/* XMRig * Copyright (c) 2018-2020 SChernykh <https://github.com/SChernykh> * Copyright (c) 2016-2020 XMRig <https://github.com/xmrig>, <support@xmrig.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <cassert> #include <thread> #include <mutex> #include "backend/cpu/Cpu.h" #include "backend/cpu/CpuWorker.h" #include "base/tools/Chrono.h" #include "core/config/Config.h" #include "core/Miner.h" #include "crypto/cn/CnCtx.h" #include "crypto/cn/CryptoNight_test.h" #include "crypto/cn/CryptoNight.h" #include "crypto/common/Nonce.h" #include "crypto/common/VirtualMemory.h" #include "crypto/rx/Rx.h" #include "crypto/rx/RxDataset.h" #include "crypto/rx/RxVm.h" #include "net/JobResults.h" #ifdef XMRIG_ALGO_RANDOMX # include "crypto/randomx/randomx.h" #endif #ifdef XMRIG_ALGO_ASTROBWT # include "crypto/astrobwt/AstroBWT.h" #endif #ifdef XMRIG_FEATURE_BENCHMARK # include "backend/common/benchmark/BenchState.h" #endif namespace xmrig { static constexpr uint32_t kReserveCount = 32768; #ifdef XMRIG_ALGO_CN_HEAVY static std::mutex cn_heavyZen3MemoryMutex; VirtualMemory* cn_heavyZen3Memory = nullptr; #endif } // namespace xmrig template<size_t N> xmrig::CpuWorker<N>::CpuWorker(size_t id, const CpuLaunchData &data) : Worker(id, data.affinity, data.priority), m_algorithm(data.algorithm), m_assembly(data.assembly), m_astrobwtAVX2(data.astrobwtAVX2), m_hwAES(data.hwAES), m_yield(data.yield), m_av(data.av()), m_astrobwtMaxSize(data.astrobwtMaxSize * 1000), m_miner(data.miner), m_threads(data.threads), m_ctx() { # ifdef XMRIG_ALGO_CN_HEAVY // cn-heavy optimization for Zen3 CPUs if ((N == 1) && (m_av == CnHash::AV_SINGLE) && (m_algorithm.family() == Algorithm::CN_HEAVY) && (m_assembly != Assembly::NONE) && (Cpu::info()->arch() == ICpuInfo::ARCH_ZEN3)) { std::lock_guard<std::mutex> lock(cn_heavyZen3MemoryMutex); if (!cn_heavyZen3Memory) { // Round up number of threads to the multiple of 8 const size_t num_threads = ((m_threads + 7) / 8) * 8; cn_heavyZen3Memory = new VirtualMemory(m_algorithm.l3() * num_threads, data.hugePages, false, false, node()); } m_memory = cn_heavyZen3Memory; } else # endif { m_memory = new VirtualMemory(m_algorithm.l3() * N, data.hugePages, false, true, node()); } } template<size_t N> xmrig::CpuWorker<N>::~CpuWorker() { # ifdef XMRIG_ALGO_RANDOMX RxVm::destroy(m_vm); # endif CnCtx::release(m_ctx, N); # ifdef XMRIG_ALGO_CN_HEAVY if (m_memory != cn_heavyZen3Memory) # endif { delete m_memory; } } #ifdef XMRIG_ALGO_RANDOMX template<size_t N> void xmrig::CpuWorker<N>::allocateRandomX_VM() { RxDataset *dataset = Rx::dataset(m_job.currentJob(), node()); while (dataset == nullptr) { std::this_thread::sleep_for(std::chrono::milliseconds(200)); if (Nonce::sequence(Nonce::CPU) == 0) { return; } dataset = Rx::dataset(m_job.currentJob(), node()); } if (!m_vm) { // Try to allocate scratchpad from dataset's 1 GB huge pages, if normal huge pages are not available uint8_t* scratchpad = m_memory->isHugePages() ? m_memory->scratchpad() : dataset->tryAllocateScrathpad(); m_vm = RxVm::create(dataset, scratchpad ? scratchpad : m_memory->scratchpad(), !m_hwAES, m_assembly, node()); } } #endif template<size_t N> bool xmrig::CpuWorker<N>::selfTest() { # ifdef XMRIG_ALGO_RANDOMX if (m_algorithm.family() == Algorithm::RANDOM_X) { return N == 1; } # endif allocateCnCtx(); if (m_algorithm.family() == Algorithm::CN) { const bool rc = verify(Algorithm::CN_0, test_output_v0) && verify(Algorithm::CN_1, test_output_v1) && verify(Algorithm::CN_2, test_output_v2) && verify(Algorithm::CN_FAST, test_output_msr) && verify(Algorithm::CN_XAO, test_output_xao) && verify(Algorithm::CN_RTO, test_output_rto) && verify(Algorithm::CN_HALF, test_output_half) && verify2(Algorithm::CN_R, test_output_r) && verify(Algorithm::CN_RWZ, test_output_rwz) && verify(Algorithm::CN_ZLS, test_output_zls) && verify(Algorithm::CN_CCX, test_output_ccx) && # ifdef XMRIG_ALGO_CN_GPU verify(Algorithm::CN_GPU, test_output_gpu) && # endif verify(Algorithm::CN_DOUBLE, test_output_double); # ifdef XMRIG_ALGO_CN_GPU if (!rc || N > 1) { return rc; } return verify(Algorithm::CN_GPU, test_output_gpu); # else return rc; # endif } # ifdef XMRIG_ALGO_CN_LITE if (m_algorithm.family() == Algorithm::CN_LITE) { return verify(Algorithm::CN_LITE_0, test_output_v0_lite) && verify(Algorithm::CN_LITE_1, test_output_v1_lite); } # endif # ifdef XMRIG_ALGO_CN_HEAVY if (m_algorithm.family() == Algorithm::CN_HEAVY) { return verify(Algorithm::CN_HEAVY_0, test_output_v0_heavy) && verify(Algorithm::CN_HEAVY_XHV, test_output_xhv_heavy) && verify(Algorithm::CN_HEAVY_TUBE, test_output_tube_heavy); } # endif # ifdef XMRIG_ALGO_CN_PICO if (m_algorithm.family() == Algorithm::CN_PICO) { return verify(Algorithm::CN_PICO_0, test_output_pico_trtl) && verify(Algorithm::CN_PICO_TLO, test_output_pico_tlo); } # endif # ifdef XMRIG_ALGO_CN_FEMTO if (m_algorithm.family() == Algorithm::CN_FEMTO) { return verify(Algorithm::CN_UPX2, test_output_femto_upx2); } # endif # ifdef XMRIG_ALGO_ARGON2 if (m_algorithm.family() == Algorithm::ARGON2) { return verify(Algorithm::AR2_CHUKWA, argon2_chukwa_test_out) && verify(Algorithm::AR2_CHUKWA_V2, argon2_chukwa_v2_test_out) && verify(Algorithm::AR2_WRKZ, argon2_wrkz_test_out); } # endif # ifdef XMRIG_ALGO_ASTROBWT if (m_algorithm.family() == Algorithm::ASTROBWT) { return verify(Algorithm::ASTROBWT_DERO, astrobwt_dero_test_out); } # endif return false; } template<size_t N> void xmrig::CpuWorker<N>::hashrateData(uint64_t &hashCount, uint64_t &, uint64_t &rawHashes) const { hashCount = m_count; rawHashes = m_count; } template<size_t N> void xmrig::CpuWorker<N>::start() { while (Nonce::sequence(Nonce::CPU) > 0) { if (Nonce::isPaused()) { do { std::this_thread::sleep_for(std::chrono::milliseconds(200)); } while (Nonce::isPaused() && Nonce::sequence(Nonce::CPU) > 0); if (Nonce::sequence(Nonce::CPU) == 0) { break; } consumeJob(); } # ifdef XMRIG_ALGO_RANDOMX bool first = true; alignas(16) uint64_t tempHash[8] = {}; # endif while (!Nonce::isOutdated(Nonce::CPU, m_job.sequence())) { const Job &job = m_job.currentJob(); if (job.algorithm().l3() != m_algorithm.l3()) { break; } uint32_t current_job_nonces[N]; for (size_t i = 0; i < N; ++i) { current_job_nonces[i] = *m_job.nonce(i); } # ifdef XMRIG_FEATURE_BENCHMARK if (m_benchSize) { if (current_job_nonces[0] >= m_benchSize) { return BenchState::done(); } // Make each hash dependent on the previous one in single thread benchmark to prevent cheating with multiple threads if (m_threads == 1) { *(uint64_t*)(m_job.blob()) ^= BenchState::data(); } } # endif bool valid = true; # ifdef XMRIG_ALGO_RANDOMX if (job.algorithm().family() == Algorithm::RANDOM_X) { if (first) { first = false; randomx_calculate_hash_first(m_vm, tempHash, m_job.blob(), job.size(), job.algorithm()); } if (!nextRound()) { break; } randomx_calculate_hash_next(m_vm, tempHash, m_job.blob(), job.size(), m_hash, job.algorithm()); } else # endif { # ifdef XMRIG_ALGO_ASTROBWT if (job.algorithm().family() == Algorithm::ASTROBWT) { if (!astrobwt::astrobwt_dero(m_job.blob(), job.size(), m_ctx[0]->memory, m_hash, m_astrobwtMaxSize, m_astrobwtAVX2)) valid = false; } else # endif { fn(job.algorithm())(m_job.blob(), job.size(), m_hash, m_ctx, job.height()); } if (!nextRound()) { break; }; } if (valid) { for (size_t i = 0; i < N; ++i) { const uint64_t value = *reinterpret_cast<uint64_t*>(m_hash + (i * 32) + 24); # ifdef XMRIG_FEATURE_BENCHMARK if (m_benchSize) { if (current_job_nonces[i] < m_benchSize) { BenchState::add(value); } } else # endif if (value < job.target()) { JobResults::submit(job, current_job_nonces[i], m_hash + (i * 32)); } } m_count += N; } if (m_yield) { std::this_thread::yield(); } } consumeJob(); } } template<size_t N> bool xmrig::CpuWorker<N>::nextRound() { # ifdef XMRIG_FEATURE_BENCHMARK const uint32_t count = m_benchSize ? 1U : kReserveCount; # else constexpr uint32_t count = kReserveCount; # endif if (!m_job.nextRound(count, 1)) { JobResults::done(m_job.currentJob()); return false; } return true; } template<size_t N> bool xmrig::CpuWorker<N>::verify(const Algorithm &algorithm, const uint8_t *referenceValue) { cn_hash_fun func = fn(algorithm); if (!func) { return false; } func(test_input, 76, m_hash, m_ctx, 0); return memcmp(m_hash, referenceValue, sizeof m_hash) == 0; } template<size_t N> bool xmrig::CpuWorker<N>::verify2(const Algorithm &algorithm, const uint8_t *referenceValue) { cn_hash_fun func = fn(algorithm); if (!func) { return false; } for (size_t i = 0; i < (sizeof(cn_r_test_input) / sizeof(cn_r_test_input[0])); ++i) { const size_t size = cn_r_test_input[i].size; for (size_t k = 0; k < N; ++k) { memcpy(m_job.blob() + (k * size), cn_r_test_input[i].data, size); } func(m_job.blob(), size, m_hash, m_ctx, cn_r_test_input[i].height); for (size_t k = 0; k < N; ++k) { if (memcmp(m_hash + k * 32, referenceValue + i * 32, sizeof m_hash / N) != 0) { return false; } } } return true; } namespace xmrig { template<> bool CpuWorker<1>::verify2(const Algorithm &algorithm, const uint8_t *referenceValue) { cn_hash_fun func = fn(algorithm); if (!func) { return false; } for (size_t i = 0; i < (sizeof(cn_r_test_input) / sizeof(cn_r_test_input[0])); ++i) { func(cn_r_test_input[i].data, cn_r_test_input[i].size, m_hash, m_ctx, cn_r_test_input[i].height); if (memcmp(m_hash, referenceValue + i * 32, sizeof m_hash) != 0) { return false; } } return true; } } // namespace xmrig template<size_t N> void xmrig::CpuWorker<N>::allocateCnCtx() { if (m_ctx[0] == nullptr) { int shift = 0; # ifdef XMRIG_ALGO_CN_HEAVY // cn-heavy optimization for Zen3 CPUs if (m_memory == cn_heavyZen3Memory) { shift = (id() / 8) * m_algorithm.l3() * 8 + (id() % 8) * 64; } # endif CnCtx::create(m_ctx, m_memory->scratchpad() + shift, m_algorithm.l3(), N); } } template<size_t N> void xmrig::CpuWorker<N>::consumeJob() { if (Nonce::sequence(Nonce::CPU) == 0) { return; } auto job = m_miner->job(); # ifdef XMRIG_FEATURE_BENCHMARK m_benchSize = job.benchSize(); const uint32_t count = m_benchSize ? 1U : kReserveCount; # else constexpr uint32_t count = kReserveCount; # endif m_job.add(job, count, Nonce::CPU); # ifdef XMRIG_ALGO_RANDOMX if (m_job.currentJob().algorithm().family() == Algorithm::RANDOM_X) { allocateRandomX_VM(); } else # endif { allocateCnCtx(); } } namespace xmrig { template class CpuWorker<1>; template class CpuWorker<2>; template class CpuWorker<3>; template class CpuWorker<4>; template class CpuWorker<5>; } // namespace xmrig
28.266802
181
0.580589
FlameSalamander
8815bcfe8fccd69f147bdabd84a9d0701811cf62
2,483
cc
C++
ortools/util/proto_tools.cc
gnanakeethan/or-tools
554cbccaa95b4c11eced13f145de1bf468e1f919
[ "Apache-2.0" ]
null
null
null
ortools/util/proto_tools.cc
gnanakeethan/or-tools
554cbccaa95b4c11eced13f145de1bf468e1f919
[ "Apache-2.0" ]
null
null
null
ortools/util/proto_tools.cc
gnanakeethan/or-tools
554cbccaa95b4c11eced13f145de1bf468e1f919
[ "Apache-2.0" ]
null
null
null
// Copyright 2010-2018 Google LLC // 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 "ortools/util/proto_tools.h" #include "google/protobuf/descriptor.h" #include "google/protobuf/message.h" #include "google/protobuf/text_format.h" #include "ortools/base/join.h" namespace operations_research { using ::google::protobuf::Descriptor; using ::google::protobuf::FieldDescriptor; using ::google::protobuf::Reflection; using ::google::protobuf::TextFormat; namespace { void WriteFullProtocolMessage(const google::protobuf::Message& message, int indent_level, std::string* out) { std::string temp_string; const std::string indent(indent_level * 2, ' '); const Descriptor* desc = message.GetDescriptor(); const Reflection* refl = message.GetReflection(); for (int i = 0; i < desc->field_count(); ++i) { const FieldDescriptor* fd = desc->field(i); const bool repeated = fd->is_repeated(); const int start = repeated ? 0 : -1; const int limit = repeated ? refl->FieldSize(message, fd) : 0; for (int j = start; j < limit; ++j) { absl::StrAppend(out, indent, fd->name()); if (fd->cpp_type() == FieldDescriptor::CPPTYPE_MESSAGE) { absl::StrAppend(out, " {\n"); const google::protobuf::Message& nested_message = repeated ? refl->GetRepeatedMessage(message, fd, j) : refl->GetMessage(message, fd); WriteFullProtocolMessage(nested_message, indent_level + 1, out); absl::StrAppend(out, indent, "}\n"); } else { TextFormat::PrintFieldValueToString(message, fd, j, &temp_string); absl::StrAppend(out, ": ", temp_string, "\n"); } } } } } // namespace std::string FullProtocolMessageAsString( const google::protobuf::Message& message, int indent_level) { std::string message_str; WriteFullProtocolMessage(message, indent_level, &message_str); return message_str; } } // namespace operations_research
37.621212
75
0.686267
gnanakeethan
88193b6b255dc104812c873698fe6f12c03e9468
911
hpp
C++
src/Module/Encoder/Polar/Encoder_polar.hpp
WilliamMajor/aff3ct
4e71ab99f33a040ec06336d3e1d50bd2c0d6a579
[ "MIT" ]
1
2022-02-17T08:47:47.000Z
2022-02-17T08:47:47.000Z
src/Module/Encoder/Polar/Encoder_polar.hpp
WilliamMajor/aff3ct
4e71ab99f33a040ec06336d3e1d50bd2c0d6a579
[ "MIT" ]
null
null
null
src/Module/Encoder/Polar/Encoder_polar.hpp
WilliamMajor/aff3ct
4e71ab99f33a040ec06336d3e1d50bd2c0d6a579
[ "MIT" ]
1
2021-11-24T01:54:41.000Z
2021-11-24T01:54:41.000Z
#ifndef ENCODER_POLAR_HPP_ #define ENCODER_POLAR_HPP_ #include <vector> #include "Tools/Code/Polar/Frozenbits_notifier.hpp" #include "Module/Encoder/Encoder.hpp" namespace aff3ct { namespace module { template <typename B = int> class Encoder_polar : public Encoder<B>, public tools::Frozenbits_notifier { protected: const int m; // log_2 of code length const std::vector<bool>& frozen_bits; // true means frozen, false means set to 0/1 std::vector<B> X_N_tmp; public: Encoder_polar(const int& K, const int& N, const std::vector<bool>& frozen_bits, const int n_frames = 1); virtual ~Encoder_polar() = default; void light_encode(B *bits); bool is_codeword(const B *X_N); virtual void notify_frozenbits_update(); protected: virtual void _encode(const B *U_K, B *X_N, const int frame_id); void convert(const B *U_K, B *U_N); }; } } #endif // ENCODER_POLAR_HPP_
23.358974
105
0.715697
WilliamMajor
881a1997d372e4b7fd93c86ee22717b4cd9a50c8
1,697
hpp
C++
CAD/Files/Sum.hpp
BRutan/Cpp
8acbc6c341f49d6d83168ccd5ba49bd6824214f9
[ "MIT" ]
null
null
null
CAD/Files/Sum.hpp
BRutan/Cpp
8acbc6c341f49d6d83168ccd5ba49bd6824214f9
[ "MIT" ]
null
null
null
CAD/Files/Sum.hpp
BRutan/Cpp
8acbc6c341f49d6d83168ccd5ba49bd6824214f9
[ "MIT" ]
null
null
null
/* Sum.hpp -Description: *Declare and define template Sum functions. -Function Catalogue: *double Sum(const T&): Return sum of passed STL container. *double Sum<map<string,double>(const T&): Return sum of passed map<string,double>. *double Sum(T::const_iterator&, T::const_iterator&): Overloaded Sum function, get sum of elements in between two iterators. *double Sum<map<string,double>>(T::const_iterator&, T::const_iterator): Overloaded Sum function, get sum of map elements in between two iterators. */ #ifndef SUM_HPP #define SUM_HPP #include<map> #include<string> template<typename T> double Sum(const T &cont_in) { double total = 0; for (typename T::const_iterator iter = cont_in.begin(); iter != cont_in.end(); iter++) { total += *iter; } return total; } template<> double Sum<std::map<std::string, double>>(const std::map<std::string, double> &map_in) { double total = 0; for (std::map<std::string, double>::const_iterator iter = map_in.begin(); iter != map_in.end(); iter++) { total += iter->second; } return total; } template<typename T> double Sum(typename const T::const_iterator &begin_in, typename const T::const_iterator &end_in) { double total = 0; for (typename T::const_iterator iter = begin_in; iter != end_in; iter++) { total += *iter; } return total; } template<> double Sum<std::map<std::string, double>>(const std::map<std::string, double>::const_iterator &iter1 , const std::map<std::string, double>::const_iterator &iter2) { double total = 0; for (std::map<std::string, double>::const_iterator i = iter1; i != iter2; i++) { total += i->second; } return total; } #endif
27.370968
163
0.67472
BRutan
881c650a3cd2b5ea341bdc79641b7e35b2ad754e
28,672
cpp
C++
mics2_3k-master2/source/movegen.cpp
Andyryo/3k
7070471e7e8a544fa6609725f2902469b6255717
[ "Apache-2.0" ]
null
null
null
mics2_3k-master2/source/movegen.cpp
Andyryo/3k
7070471e7e8a544fa6609725f2902469b6255717
[ "Apache-2.0" ]
null
null
null
mics2_3k-master2/source/movegen.cpp
Andyryo/3k
7070471e7e8a544fa6609725f2902469b6255717
[ "Apache-2.0" ]
null
null
null
// 指し手生成ライブラリ #include "position.h" #include <iostream> using namespace std; // ---------------------------------- // 移動による指し手 // ---------------------------------- // ----------------------------------------------- // 上位16bitに移動後の駒を格納しながらの指し手生成 // ----------------------------------------------- // 上位16bitに格納する駒を生成する。 // そのままの駒 #define OurPt(Us,Pt) Move(((Us ? u32(PIECE_WHITE):0)+(Pt)) << 16) // 成るときの駒(+8) #define OurProPt(Us,Pt) Move(((Us ? u32(PIECE_WHITE):0)+(Pt)+u32(PIECE_PROMOTE)) << 16) // 駒打ちするときの駒 #define OurDropPt(Us,Pt) Move(((Us ? u32(PIECE_WHITE):0)+(Pt)) << 16) // 成らない指し手生成を生成する #define MAKE_MOVE_TARGET(target_) { FOREACH_BB(target_,to,{ \ mlist++->move = make_move(from,to) + OurPt(Us,Pt); \ });} // 移動させる駒が不明な場合 #define MAKE_MOVE_TARGET_UNKNOWN(target_) { FOREACH_BB(target_,to,{ \ mlist++->move = make_move(from,to) + Move(pos.piece_on(from) << 16); \ });} // 成りと不成の指し手を生成する #define MAKE_MOVE_TARGET_PRO(target_) { FOREACH_BB(target_,to,{ \ mlist++->move = make_move_promote(from,to) + OurProPt(Us,Pt); \ mlist++->move = make_move(from,to) + OurPt(Us,Pt); \ });} // 成りの指し手のみを生成する #define MAKE_MOVE_TARGET_PRO_ONLY(target_) { FOREACH_BB(target_,to,{ \ mlist++->move = make_move_promote(from,to) + OurProPt(Us,Pt); \ });} // 成れることが確定しているときにAllのときだけ不成の指し手を生成する指し手生成(角、飛車用) #define MAKE_MOVE_TARGET_PRO_BR(target_) { FOREACH_BB(target_,to,{ \ mlist++->move = make_move_promote(from,to) + OurProPt(Us,Pt); \ if (All) mlist++->move = make_move(from,to) + OurPt(Us,Pt); \ });} // ↑のと同じだが移動させる駒が確定していないとき。 #define MAKE_MOVE_TARGET_PRO_BR_UNKNOWN(target_) { FOREACH_BB(target_,to,{ \ mlist++->move = make_move_promote(from,to) + Move((pos.piece_on(from) + PIECE_PROMOTE) << 16); \ if (All) mlist++->move = make_move(from,to) + Move(pos.piece_on(from) << 16) ; \ });} // 駒打ち #define MAKE_MOVE_TARGET_DROP(target_,Pt) { FOREACH_BB(target_, sq, { \ mlist++->move = make_move_drop(Pt,sq) + OurDropPt(Us,Pt); \ });} // fromにあるpcをtargetの升に移動させる指し手の生成。 // 遅いので駒王手の指し手生成のときにしか使わない。 template <Piece Pt, Color Us, bool All> struct make_move_target { FORCE_INLINE ExtMove* operator()(const Position& pos, Square from, const Bitboard& target_, ExtMove* mlist) { Square to; Bitboard target = target_; Bitboard target2; switch (Pt) { // 成れるなら成りも生成するが、2,3段目への不成を生成するのはAllのときだけ。また1段目には不成で移動できない。 case PAWN: if (target) { to = from + (Us == BLACK ? SQ_U : SQ_D); // to = target.pop(); より少し速い if (canPromote(Us, to)) mlist++->move = make_move_promote(from, to) + OurProPt(Us, Pt); else mlist++->move = make_move(from, to) + OurPt(Us, Pt); } break; // 成れるなら成りも生成する駒 case SILVER: { if (enemy_field(Us) & from) { // 敵陣からなら成れることは確定している MAKE_MOVE_TARGET_PRO(target); } else { // 非敵陣からなので敵陣への移動のみ成り target2 = target & enemy_field(Us); MAKE_MOVE_TARGET_PRO(target2); target &= ~enemy_field(Us); MAKE_MOVE_TARGET(target); } } break; // 成れない駒 case GOLD: case PRO_PAWN: case PRO_SILVER: case HORSE: case DRAGON: case KING: MAKE_MOVE_TARGET(target); break; // 成れない駒。(対象の駒は不明) case GPM_GHDK: MAKE_MOVE_TARGET_UNKNOWN(target); break; // 成れるなら成る駒。ただしAllのときは不成も生成。 case BISHOP: case ROOK: // 移動元が敵陣なら無条件で成れる if (canPromote(Us, from)) { MAKE_MOVE_TARGET_PRO_BR(target); } else { target2 = target & enemy_field(Us); MAKE_MOVE_TARGET_PRO_BR(target2); target &= ~enemy_field(Us); MAKE_MOVE_TARGET(target); } break; // 成れるなら成る駒。ただしAllのときは不成も生成。(対象は不明) case GPM_BR: if (canPromote(Us, from)) { MAKE_MOVE_TARGET_PRO_BR_UNKNOWN(target); } else { target2 = target & enemy_field(Us); MAKE_MOVE_TARGET_PRO_BR_UNKNOWN(target2); target &= ~enemy_field(Us); MAKE_MOVE_TARGET_UNKNOWN(target); } break; default: UNREACHABLE; break; } return mlist; } }; // 指し手生成のうち、一般化されたもの。香・桂・銀はこの指し手生成を用いる。 template <MOVE_GEN_TYPE GenType, Piece Pt, Color Us, bool All> struct GeneratePieceMoves { FORCE_INLINE ExtMove* operator()(const Position& pos, ExtMove* mlist, const Bitboard& target) { // 盤上の駒pc(香・桂・銀)に対して auto pieces = pos.pieces(Us, Pt); const auto occ = pos.pieces(); while (pieces) { auto from = pieces.pop(); // 移動できる場所 = 利きのある場所 auto target2 = Pt == SILVER ? silverEffect(Us, from) : ALL_BB; // error target2 &= target; mlist = make_move_target<Pt, Us, All>()(pos, from, target2, mlist); } return mlist; } }; // 歩の移動による指し手生成 template <MOVE_GEN_TYPE GenType, Color Us, bool All> struct GeneratePieceMoves<GenType, PAWN, Us, All> { FORCE_INLINE ExtMove* operator()(const Position& pos, ExtMove* mlist, const Bitboard& target) { // 盤上の自駒の歩に対して auto pieces = pos.pieces(Us, PAWN); // 歩の利き auto target2 = pawnEffect(Us, pieces) & target; // 先手に対する1段目(後手ならば9段目)を表す定数 const Rank T_RANK1 = (Us == BLACK) ? RANK_1 : RANK_5; while (target2) { auto to = target2.pop(); auto from = to + (Us == BLACK ? SQ_D : SQ_U); // 歩が成れるときは成る指し手しか生成しない。 if (canPromote(Us, to)) mlist++->move = make_move_promote(from, to) + OurProPt(Us, PAWN); else mlist++->move = make_move(from, to) + OurPt(Us, PAWN); } return mlist; } }; // 角・飛による移動による指し手生成。これらの駒は成れるなら絶対に成る template <MOVE_GEN_TYPE GenType, Color Us, bool All> struct GeneratePieceMoves<GenType, GPM_BR, Us, All> { FORCE_INLINE ExtMove* operator()(const Position& pos, ExtMove* mlist, const Bitboard& target) { // 角と飛に対して(馬と龍は除く) auto pieces = pos.pieces(Us, BISHOP, ROOK); auto occ = pos.pieces(); while (pieces) { auto from = pieces.pop(); // fromの升にある駒をfromの升においたときの利き auto target2 = effects_from(pos.piece_on(from), from, occ) & target; mlist = make_move_target<GPM_BR, Us, All>()(pos, from, target2, mlist); } return mlist; } }; // 成れない駒による移動による指し手。(金相当の駒・馬・龍・王) template <MOVE_GEN_TYPE GenType, Color Us, bool All> struct GeneratePieceMoves<GenType, GPM_GHDK, Us, All> { FORCE_INLINE ExtMove* operator()(const Position& pos, ExtMove* mlist, const Bitboard& target) { // 金相当の駒・馬・龍・玉に対して auto pieces = pos.pieces(Us, GOLDS, HDK); auto occ = pos.pieces(); while (pieces) { auto from = pieces.pop(); // fromの升にある駒をfromの升においたときの利き auto target2 = effects_from(pos.piece_on(from), from, occ) & target; mlist = make_move_target<GPM_GHDK, Us, All>()(pos, from, target2, mlist); } return mlist; } }; // 玉を除く成れない駒による移動による指し手。(金相当の駒・馬・龍) template <MOVE_GEN_TYPE GenType, Color Us, bool All> struct GeneratePieceMoves<GenType, GPM_GHD, Us, All> { FORCE_INLINE ExtMove* operator()(const Position& pos, ExtMove* mlist, const Bitboard& target) { // 金相当の駒・馬・龍に対して auto pieces = pos.pieces(Us, GOLDS, HORSE, DRAGON); auto occ = pos.pieces(); Square to; while (pieces) { auto from = pieces.pop(); // fromの升にある駒をfromの升においたときの利き const auto Pt = pos.piece_on(from); auto target2 = effects_from(Pt, from, occ) & target; MAKE_MOVE_TARGET_UNKNOWN(target2); } return mlist; } }; // ---------------------------------- // 駒打ちによる指し手 // ---------------------------------- // 駒打ちの指し手生成 template <Color Us> struct GenerateDropMoves { ExtMove* operator()(const Position& pos, ExtMove* mlist, const Bitboard& target) { const Hand hand = pos.hand_of(Us); // 手駒を持っていないならば終了 if (hand == 0) return mlist; Square sq; // --- 歩を打つ指し手生成 if (hand_exists(hand, PAWN)) { // 歩の駒打ちの基本戦略 // 1) 一段目以外に打てる // 2) 二歩のところには打てない // 3) 打ち歩詰め回避 // ここでは2)のためにソフトウェア飽和加算に似たテクニックを用いる // cf. http://yaneuraou.yaneu.com/2015/10/15/%E7%B8%A6%E5%9E%8Bbitboard%E3%81%AE%E5%94%AF%E4%B8%80%E3%81%AE%E5%BC%B1%E7%82%B9%E3%82%92%E5%85%8B%E6%9C%8D%E3%81%99%E3%82%8B/ // このときにテーブルを引くので、用意するテーブルのほうで先に1)の処理をしておく。 // → この方法はPEXTが必要なので愚直な方法に変更する。 // 歩の打てる場所 Bitboard target2 = rank1_n_bb(~Us, RANK_4) & target; // 歩が二歩のために打てない筋を消していく(Aperyの手法) Bitboard pawnBB = pos.pieces(Us, PAWN); Square pawnSq; foreachBB(pawnBB, pawnSq, [&]() { target2.p &= PAWN_DROP_MASKS[pawnSq]; }); // 打ち歩詰めチェック // 敵玉に敵の歩を置いた位置に打つ予定だったのなら、打ち歩詰めチェックして、打ち歩詰めならそこは除外する。 Bitboard pe = pawnEffect(~Us, pos.king_square(~Us)); if (pe & target2) { Square to = pe.pop_c(); if (!pos.legal_drop(to)) target2 ^= pe; } // targetで表現される升に歩を打つ指し手の生成。 MAKE_MOVE_TARGET_DROP(target2, PAWN); } // --- 歩以外を打つ指し手生成 // 歩以外の手駒を持っているか if (hand_except_pawn_exists(hand)) { Move drops[6]; // 打つ先の升を埋めればいいだけの指し手を事前に生成しておく。 // 基本的な戦略としては、(先手から見て) // 1) 1段目に打てない駒( = 香・桂)を除いたループ // 2) 2段目に打てない駒( = 桂)を除いたループ // 3) 3〜9段目に打てる駒( = すべての駒)のループ // という3つの場合分けによるループで構成される。 // そのため、手駒から香・桂を除いた駒と、桂を除いた駒が必要となる。 int num = 0; if (hand_exists(hand, SILVER)) drops[num++] = make_move_drop(SILVER, SQ_ZERO) + OurDropPt(Us, SILVER); if (hand_exists(hand, GOLD)) drops[num++] = make_move_drop(GOLD, SQ_ZERO) + OurDropPt(Us, GOLD); if (hand_exists(hand, BISHOP)) drops[num++] = make_move_drop(BISHOP, SQ_ZERO) + OurDropPt(Us, BISHOP); if (hand_exists(hand, ROOK)) drops[num++] = make_move_drop(ROOK, SQ_ZERO) + OurDropPt(Us, ROOK); Bitboard target2 = target; switch (num) { case 1: FOREACH_BB(target2, sq, { UNROLLER1({ mlist++->move = (Move)(drops[i] + sq); }); }); break; case 2: FOREACH_BB(target2, sq, { UNROLLER2({ mlist++->move = (Move)(drops[i] + sq); }); }); break; case 3: FOREACH_BB(target2, sq, { UNROLLER3({ mlist++->move = (Move)(drops[i] + sq); }); }); break; case 4: FOREACH_BB(target2, sq, { UNROLLER4({ mlist++->move = (Move)(drops[i] + sq); }); }); break; default: UNREACHABLE; } } return mlist; } }; // 手番側が王手がかかっているときに、王手を回避する手を生成する。 template<Color Us, bool All> ExtMove* generate_evasions(const Position& pos, ExtMove* mlist) { // この実装において引数のtargetは無視する。 // この関数を呼び出しているということは、王手がかかっているはずであり、 // 王手をしている駒があるばすだから、checkers(王手をしている駒)が存在しなければおかしいのでassertを入れてある ASSERT_LV2(pos.in_check()); // 自玉に王手をかけている敵の駒の利き(そこには玉は移動できないので) Bitboard sliderAttacks = ZERO_BB; // 王手している駒 Bitboard checkers = pos.checkers(); // 王手をしている駒の数を数えるカウンター int checkersCnt = 0; // 自玉を移動させるので、この玉はないものとして利きを求める必要がある。 Square ksq = pos.king_square(Us); Bitboard occ = pos.pieces() ^ Bitboard(ksq); // 王手している駒のある升 Square checksq; // 王手している駒は必ず1つ以上あるのでdo〜whileで回る do { // 王手をしている敵の駒のカウントを加算 ++checkersCnt; // 王手をしている敵の駒の位置を取り出す checksq = checkers.pop(); // この駒は敵駒でなくてはならない ASSERT_LV3(color_of(pos.piece_on(checksq)) == ~Us); // 王手している駒の利きを加えていく。 sliderAttacks |= effects_from(pos.piece_on(checksq), checksq, occ); } while (checkers); // 王手回避のための玉の移動先は、玉の利きで、自駒のない場所でかつさきほどの王手していた駒が利いていないところが候補として挙げられる // これがまだ自殺手である可能性もあるが、それはis_legal()でチェックすればいいと思う。 Bitboard bb = kingEffect(ksq) & ~(pos.pieces(Us) | sliderAttacks); while (bb) { Square to = bb.pop(); mlist++->move = make_move(ksq, to) + OurPt(Us, KING); } // 両王手であるなら、王の移動のみが回避手となる。ゆえにこれで指し手生成は終了。 if (checkersCnt > 1) return mlist; // 両王手でないことは確定した // このあと生成すべきは // 1) 王手している駒を王以外で取る指し手 // 2) 王手している駒と王の間に駒を移動させる指し手(移動合い) // 3) 王手している駒との間に駒を打つ指し手(合駒打ち) // target1 == 王手している駒と王との間の升 == 3)の駒打ちの場所 // target2 == 移動による指し手は1)+2) = 王手している駒と王との間の升 + 王手している駒 の升 const Bitboard target1 = between_bb(checksq, ksq); const Bitboard target2 = target1 | checksq; // あとはNON_EVASIONS扱いで普通に指し手生成。 mlist = GeneratePieceMoves<NON_EVASIONS, PAWN, Us, All>()(pos, mlist, target2); mlist = GeneratePieceMoves<NON_EVASIONS, SILVER, Us, All>()(pos, mlist, target2); mlist = GeneratePieceMoves<NON_EVASIONS, GPM_BR, Us, All>()(pos, mlist, target2); mlist = GeneratePieceMoves<NON_EVASIONS, GPM_GHD, Us, All>()(pos, mlist, target2); // 玉は除かないといけない mlist = GenerateDropMoves<Us>()(pos, mlist, target1); return mlist; } // ---------------------------------- // 指し手生成器本体 // ---------------------------------- // 指し手の生成器本体 // mlist : 指し手を返して欲しい指し手生成バッファのアドレス // Us : 生成するほうの手番 // All : 歩・香の2段目での不成や角・飛の不成などをすべて生成するのか。 // 返し値 : 生成した指し手の終端 // generateMovesのほうから内部的に呼び出される。(直接呼び出さないこと。) template<MOVE_GEN_TYPE GenType, Color Us, bool All> ExtMove* generate_general(const Position& pos, ExtMove* mlist, Square recapSq = SQ_NB) { // --- 駒の移動による指し手 // ・移動先の升。 // NON_CAPTURESなら駒のない場所 // CAPTURESなら敵駒のあるところ // CAPTURE_PRO_PLUsならCAPTURES + 歩の成り。 // (価値のある成り以外はオーダリングを阻害するので含めない) static_assert(GenType != EVASIONS_ALL && GenType != NON_EVASIONS_ALL && GenType != RECAPTURES_ALL, "*_ALL is not allowed."); // 歩以外の駒の移動先 const Bitboard target = (GenType == NON_CAPTURES) ? pos.empties() : // 捕獲しない指し手 = 移動先の升は駒のない升 (GenType == CAPTURES) ? pos.pieces(~Us) : // 捕獲する指し手 = 移動先の升は敵駒のある升 (GenType == NON_CAPTURES_PRO_MINUS) ? pos.empties() : // 捕獲しない指し手 - 歩の成る指し手 = 移動先の升は駒のない升 - 敵陣(歩のときのみ) (GenType == CAPTURES_PRO_PLUS) ? pos.pieces(~Us) : // 捕獲 + 歩の成る指し手 = 移動先の升は敵駒のある升 + 敵陣(歩のときのみ) (GenType == NON_EVASIONS) ? ~pos.pieces(Us) : // すべて = 移動先の升は自駒のない升 (GenType == RECAPTURES) ? Bitboard(recapSq) : // リキャプチャー用の升(直前で相手の駒が移動したわけだからここには移動できるはず) ALL_BB; // error // 歩の移動先(↑のtargetと違う部分のみをオーバーライド) const Bitboard targetPawn = (GenType == NON_CAPTURES_PRO_MINUS) ? (pos.empties() & ~enemy_field(Us)) : // 駒を取らない指し手 かつ、歩の成る指し手を引いたもの (GenType == CAPTURES_PRO_PLUS) ? (pos.pieces(~Us) | (~pos.pieces(Us) & enemy_field(Us))) : // 歩の場合は敵陣での成りもこれに含める target; // 各駒による移動の指し手の生成 // 歩の指し手は歩のBitboardをbit shiftすることで移動先が一発で求まるので特別扱い mlist = GeneratePieceMoves<GenType, PAWN, Us, All>()(pos, mlist, targetPawn); // 銀は成れるなら成らない手の他に成る手も生成する駒。これらによる移動の指し手 mlist = GeneratePieceMoves<GenType, SILVER, Us, All>()(pos, mlist, target); // 角・飛による移動による指し手生成。これらの駒は成れるなら絶対に成る mlist = GeneratePieceMoves<GenType, GPM_BR, Us, All>()(pos, mlist, target); // 金相当の駒・馬・龍・王による移動による指し手。(成れない駒による移動による指し手) mlist = GeneratePieceMoves<GenType, GPM_GHDK, Us, All>()(pos, mlist, target); // --- 駒打ち // → オーダリング性能改善のためにDropをもう少し細分化できるといいのだが、なかなか簡単ではなさげ。 if (GenType == NON_CAPTURES || GenType == NON_CAPTURES_PRO_MINUS || GenType == NON_EVASIONS) mlist = GenerateDropMoves<Us>()(pos, mlist, pos.empties()); return mlist; } // ----------------------------------------------------- // 王手生成関係。(やねうら王nanoでは削除予定) // ----------------------------------------------------- // make_move_targetを呼び出すための踏み台 // ptの駒をfromに置いたときの移動する指し手を生成する。ただし、targetで指定された升のみ。 template <Color Us, bool All> struct make_move_target_general { ExtMove* operator()(const Position& pos, Piece pc, Square from, const Bitboard& target, ExtMove* mlist) { ASSERT_LV2(pc != NO_PIECE); auto effect = effects_from(pc, from, pos.pieces()); switch (type_of(pc)) { case PAWN: mlist = make_move_target<PAWN, Us, All>()(pos, from, effect & target, mlist); break; case SILVER: mlist = make_move_target<SILVER, Us, All>()(pos, from, effect & target, mlist); break; case GOLD: mlist = make_move_target<GOLD, Us, All>()(pos, from, effect & target, mlist); break; case BISHOP: mlist = make_move_target<BISHOP, Us, All>()(pos, from, effect & target, mlist); break; case ROOK: mlist = make_move_target<ROOK, Us, All>()(pos, from, effect & target, mlist); break; case KING: mlist = make_move_target<KING, Us, All>()(pos, from, effect & target, mlist); break; case PRO_PAWN: mlist = make_move_target<PRO_PAWN, Us, All>()(pos, from, effect & target, mlist); break; case PRO_SILVER: mlist = make_move_target<PRO_SILVER, Us, All>()(pos, from, effect & target, mlist); break; case HORSE: mlist = make_move_target<HORSE, Us, All>()(pos, from, effect & target, mlist); break; case DRAGON: mlist = make_move_target<DRAGON, Us, All>()(pos, from, effect & target, mlist); break; default: UNREACHABLE; } return mlist; } }; // promoteかどうかを呼び出し元で選択できるmake_move_target template <Piece Pt, Color Us, bool All, bool Promote> ExtMove* make_move_target_pro(Square from, const Bitboard& target, ExtMove* mlist) { auto bb = target; while (bb) { auto to = bb.pop(); if (Promote) mlist++->move = make_move_promote(from, to) + OurProPt(Us, Pt); else { if (((Pt == PAWN) && ((!All && !canPromote(Us, to)) || (All && rank_of(to) != (Us == BLACK ? RANK_1 : RANK_5)))) || (Pt == SILVER) || ((Pt == BISHOP || Pt == ROOK) && (!(canPromote(Us, from) || canPromote(Us, to)) || All)) ) mlist++->move = make_move(from, to) + OurPt(Us, Pt); } } return mlist; } // pcをfromにおいたときにksqにいる敵玉に対して王手になる移動による指し手の生成 template <Color Us, bool All> ExtMove* make_move_check(const Position& pos, Piece pc, Square from, Square ksq, const Bitboard& target, ExtMove* mlist) { // Xで成るとYになる駒に関する王手になる指し手生成 // 移動元が敵陣でないなら、移動先が敵陣でないと成れない。 #define GEN_MOVE_NONPRO_CHECK(X,X_Effect,Y_Effect) { \ dst = X_Effect(Us, from) & Y_Effect(~Us, ksq) & target; \ if (!(enemy_field(Us) & from)) \ dst &= enemy_field(Us); \ mlist = make_move_target_pro<X, Us, All, true>(from, dst, mlist); \ dst = X_Effect(Us, from) & X_Effect(~Us, ksq) & target; \ mlist = make_move_target_pro<X, Us, All, false>(from, dst, mlist); } // ↑のBISHOP,ROOK用 #define GEN_MOVE_NONPRO_PRO_CHECK_BR(X,X_Effect,Y_Effect) { \ occ = pos.pieces(); \ dst = X_Effect(from,occ) & Y_Effect(ksq,occ) & target; \ if (!(enemy_field(Us) & from)) \ dst &= enemy_field(Us); \ mlist = make_move_target_pro<X, Us, All, true>(from, dst, mlist); \ dst = X_Effect(from,occ) & X_Effect(ksq,occ) & target; \ mlist = make_move_target_pro<X, Us, All, false>(from, dst, mlist); } // ↑の成れない駒用 #define GEN_MOVE_GOLD_CHECK(X,X_Effect) { \ dst = X_Effect(Us, from) & X_Effect(~Us, ksq) & target; \ mlist = make_move_target<X, Us, All>()(pos,from, dst, mlist); } // ↑のHORSE,DRAGON駒用 #define GEN_MOVE_HD_CHECK(X,X_Effect) { \ occ = pos.pieces(); \ dst = X_Effect(from,occ) & X_Effect(ksq,occ) & target; \ mlist = make_move_target<X, Us, All>()(pos,from, dst, mlist); } Bitboard dst, occ; switch (type_of(pc)) { // -- 成れる駒 case PAWN: GEN_MOVE_NONPRO_CHECK(PAWN, pawnEffect, goldEffect); break; case SILVER: GEN_MOVE_NONPRO_CHECK(SILVER, silverEffect, goldEffect); break; case BISHOP: GEN_MOVE_NONPRO_PRO_CHECK_BR(BISHOP, bishopEffect, horseEffect); break; case ROOK: GEN_MOVE_NONPRO_PRO_CHECK_BR(ROOK, rookEffect, dragonEffect); break; // -- 成れない駒 case PRO_PAWN: GEN_MOVE_GOLD_CHECK(PRO_PAWN, goldEffect); break; case PRO_SILVER: GEN_MOVE_GOLD_CHECK(PRO_SILVER, goldEffect); break; case GOLD: GEN_MOVE_GOLD_CHECK(GOLD, goldEffect); break; case HORSE: GEN_MOVE_HD_CHECK(HORSE, horseEffect); break; case DRAGON: GEN_MOVE_HD_CHECK(DRAGON, dragonEffect); break; default:UNREACHABLE; } return mlist; } // 王手になる駒打ち template <Color Us, Piece Pt> struct GenerateCheckDropMoves { ExtMove* operator()(const Position&, const Bitboard& target, ExtMove* mlist) { auto bb = target; while (bb) { auto to = bb.pop(); mlist++->move = make_move_drop(Pt, to) + OurDropPt(Us, Pt); } return mlist; } }; // 歩だけ特殊化(2歩の判定/打ち歩詰め判定が必要なため) template <Color Us> struct GenerateCheckDropMoves<Us, PAWN> { ExtMove* operator()(const Position& pos, const Bitboard& target, ExtMove* mlist) { auto bb = target; if (bb) // 歩を打って王手になる箇所は1箇所しかないのでwhileである必要はない。 { auto to = bb.pop_c(); // 二歩と打ち歩詰めでないならこの指し手を生成。 if (pos.legal_pawn_drop(Us, to)) mlist++->move = make_move_drop(PAWN, to) + OurDropPt(Us, PAWN); } return mlist; } }; // 指し手の生成器本体(王手専用) template<MOVE_GEN_TYPE GenType, Color Us, bool All> ExtMove* generate_checks(const Position& pos, ExtMove* mlist) { // --- 駒の移動による王手 // 王手になる指し手 // 1) 成らない移動による直接王手 // 2) 成る移動による直接王手 // 3) pinされている駒の移動による間接王手 // 集合としては1),2) <--> 3)は被覆している可能性があるのでこれを除外できるような指し手生成をしなくてはならない。 // これを綺麗に実装するのは結構難しい。 // x = 直接王手となる候補 // y = 間接王手となる候補 // ほとんどのケースにおいて y == emptyなのでそれを前提に最適化をする。 // yと、yを含まないxとに分けて処理する。 // すなわち、y と (x | y)^y const Square themKing = pos.king_square(~Us); // 以下の方法だとxとして飛(龍)は100%含まれる。角・馬は60%ぐらいの確率で含まれる。事前条件でもう少し省ければ良いのだが…。 const Bitboard x = ( (pos.pieces(PAWN) & check_candidate_bb(Us, PAWN, themKing)) | (pos.pieces(SILVER) & check_candidate_bb(Us, SILVER, themKing)) | (pos.pieces(GOLDS) & check_candidate_bb(Us, GOLD, themKing)) | (pos.pieces(BISHOP) & check_candidate_bb(Us, BISHOP, themKing)) | (pos.pieces(ROOK_DRAGON)) | // ROOK,DRAGONは無条件全域 (pos.pieces(HORSE) & check_candidate_bb(Us, ROOK, themKing)) // check_candidate_bbにはROOKと書いてるけど、HORSE ) & pos.pieces(Us); // ここには王を敵玉の8近傍に移動させる指し手も含まれるが、王が近接する形はレアケースなので // 指し手生成の段階では除外しなくても良いと思う。 // 移動させると(相手側=非手番側)の玉に対して空き王手となる候補の(手番側)駒のbitboard。 const Bitboard y = pos.blockers_for_king(~Us) & pos.pieces(Us); const Bitboard target = (GenType == CHECKS || GenType == CHECKS_ALL) ? ~pos.pieces(Us) : // 自駒がない場所が移動対象升 (GenType == QUIET_CHECKS || GenType == QUIET_CHECKS_ALL) ? pos.empties() : // 捕獲の指し手を除外するため駒がない場所が移動対象升 ALL_BB; // Error! // yのみ。ただしxかつyである可能性もある。 auto src = y; while (src) { auto from = src.pop(); // 両王手候補なので指し手を生成してしまう。 // いまの敵玉とfromを通る直線上の升と違うところに移動させれば開き王手が確定する。その直線を求める。 auto pin_line = line_bb(themKing, from); mlist = make_move_target_general<Us, All>()(pos, pos.piece_on(from), from, target & ~pin_line, mlist); if (x & from) // 直接王手にもなるので↑で生成した~line_bb以外の升への指し手を生成。 mlist = make_move_check<Us, All>(pos, pos.piece_on(from), from, themKing, target & pin_line, mlist); } // yに被覆しないx src = (x | y) ^ y; while (src) { auto from = src.pop(); // 直接王手のみ。 mlist = make_move_check<Us, All>(pos, pos.piece_on(from), from, themKing, target, mlist); } // --- 駒打ちによる王手 const Bitboard& empties = pos.empties(); Hand h = pos.hand_of(Us); if (hand_exists(h, PAWN)) mlist = GenerateCheckDropMoves<Us, PAWN>()(pos, pos.check_squares(PAWN) & empties, mlist); if (hand_exists(h, SILVER)) mlist = GenerateCheckDropMoves<Us, SILVER>()(pos, pos.check_squares(SILVER) & empties, mlist); if (hand_exists(h, GOLD)) mlist = GenerateCheckDropMoves<Us, GOLD>()(pos, pos.check_squares(GOLD) & empties, mlist); if (hand_exists(h, BISHOP)) mlist = GenerateCheckDropMoves<Us, BISHOP>()(pos, pos.check_squares(BISHOP) & empties, mlist); if (hand_exists(h, ROOK)) mlist = GenerateCheckDropMoves<Us, ROOK>()(pos, pos.check_squares(ROOK) & empties, mlist); return mlist; } // ---------------------------------- // 指し手生成踏み台 // ---------------------------------- // generate_general()を先後分けて実体化するための踏み台 template<MOVE_GEN_TYPE GenType, bool All> ExtMove* generateMoves(const Position& pos, ExtMove* mlist, Square sq = SQ_NB) { return pos.side_to_move() == BLACK ? generate_general<GenType, BLACK, All>(pos, mlist, sq) : generate_general<GenType, WHITE, All>(pos, mlist, sq); } // 同じく、Evasionsの指し手生成を呼ぶための踏み台 template<bool All> ExtMove* generateEvasionMoves(const Position& pos, ExtMove* mlist) { return pos.side_to_move() == BLACK ? generate_evasions<BLACK, All>(pos, mlist) : generate_evasions<WHITE, All>(pos, mlist); } // 同じく、Checksの指し手生成を呼ぶための踏み台 template<MOVE_GEN_TYPE GenType, bool All> ExtMove* generateChecksMoves(const Position& pos, ExtMove* mlist) { return pos.side_to_move() == BLACK ? generate_checks<GenType, BLACK, All>(pos, mlist) : generate_checks<GenType, WHITE, All>(pos, mlist); } // 一般的な指し手生成 template<MOVE_GEN_TYPE GenType> ExtMove* generateMoves(const Position& pos, ExtMove* mlist, Square recapSq) { // 歩の不成などを含め、すべての指し手を生成するのか。 // GenTypeの末尾に"ALL"とついているものがその対象。 const bool All = (GenType == EVASIONS_ALL) || (GenType == CHECKS_ALL) || (GenType == LEGAL_ALL) || (GenType == NON_EVASIONS_ALL) || (GenType == RECAPTURES_ALL) || (GenType == QUIET_CHECKS_ALL) || (GenType == CAPTURES_PRO_PLUS_ALL) || (GenType == NON_CAPTURES_PRO_MINUS_ALL); if (GenType == LEGAL || GenType == LEGAL_ALL) { // 合法性な指し手のみを生成する。 // 自殺手や打ち歩詰めが含まれているのでそれを取り除く。かなり重い。ゆえにLEGALは特殊な状況でしか使うべきではない。 auto last = pos.in_check() ? generateEvasionMoves<All>(pos, mlist) : generateMoves<NON_EVASIONS, All>(pos, mlist); // 合法ではない指し手を末尾の指し手と入れ替え while (mlist != last) { if (!pos.legal(*mlist)) mlist->move = (--last)->move; else ++mlist; } return last; } // 王手生成 if (GenType == CHECKS || GenType == CHECKS_ALL || GenType == QUIET_CHECKS || GenType == QUIET_CHECKS_ALL) { auto last = generateChecksMoves<GenType, All>(pos, mlist); // 王手がかかっている局面においては王手生成において、回避手になっていない指し手も含まれるので(王手放置での駒打ち等) // pseudo_legal()でない指し手はここで除外する。これはレアケースなので少々の無駄は許容する。 if (pos.in_check()) while (mlist != last) { if (!pos.pseudo_legal(*mlist)) mlist->move = (--last)->move; else ++mlist; } return last; } // 回避手 if (GenType == EVASIONS || GenType == EVASIONS_ALL) return generateEvasionMoves<All>(pos, mlist); // 上記のもの以外 // ただし、NON_EVASIONS_ALL , RECAPTURES_ALLは、ALLではないほうを呼び出す必要がある。 // EVASIONS_ALLは上で呼び出されているが、実際はここでも実体化されたあと、最適化によって削除されるので、ここでも書く必要がある。 const auto GenType2 = GenType == NON_EVASIONS_ALL ? NON_EVASIONS : GenType == RECAPTURES_ALL ? RECAPTURES : GenType == EVASIONS_ALL ? EVASIONS : GenType == CAPTURES_PRO_PLUS_ALL ? CAPTURES_PRO_PLUS : GenType == NON_CAPTURES_PRO_MINUS_ALL ? NON_CAPTURES_PRO_MINUS : GenType; // さもなくば元のまま。 return generateMoves<GenType2, All>(pos, mlist, recapSq); } template<MOVE_GEN_TYPE GenType> ExtMove* generateMoves(const Position& pos, ExtMove* mlist) { static_assert(GenType != RECAPTURES && GenType != RECAPTURES_ALL, "RECAPTURES , not allowed."); return generateMoves<GenType>(pos, mlist, SQ_NB); } // テンプレートの実体化。これを書いておかないとリンクエラーになる。 // .h(ヘッダー)ではなく.cppのほうに書くことでコンパイル時間を節約できる。 template ExtMove* generateMoves<NON_CAPTURES >(const Position& pos, ExtMove* mlist); template ExtMove* generateMoves<CAPTURES >(const Position& pos, ExtMove* mlist); template ExtMove* generateMoves<NON_CAPTURES_PRO_MINUS >(const Position& pos, ExtMove* mlist); template ExtMove* generateMoves<NON_CAPTURES_PRO_MINUS_ALL>(const Position& pos, ExtMove* mlist); template ExtMove* generateMoves<CAPTURES_PRO_PLUS >(const Position& pos, ExtMove* mlist); template ExtMove* generateMoves<CAPTURES_PRO_PLUS_ALL >(const Position& pos, ExtMove* mlist); template ExtMove* generateMoves<EVASIONS >(const Position& pos, ExtMove* mlist); template ExtMove* generateMoves<EVASIONS_ALL >(const Position& pos, ExtMove* mlist); template ExtMove* generateMoves<NON_EVASIONS >(const Position& pos, ExtMove* mlist); template ExtMove* generateMoves<NON_EVASIONS_ALL >(const Position& pos, ExtMove* mlist); template ExtMove* generateMoves<LEGAL >(const Position& pos, ExtMove* mlist); template ExtMove* generateMoves<LEGAL_ALL >(const Position& pos, ExtMove* mlist); template ExtMove* generateMoves<CHECKS >(const Position& pos, ExtMove* mlist); template ExtMove* generateMoves<CHECKS_ALL >(const Position& pos, ExtMove* mlist); template ExtMove* generateMoves<QUIET_CHECKS >(const Position& pos, ExtMove* mlist); template ExtMove* generateMoves<QUIET_CHECKS_ALL >(const Position& pos, ExtMove* mlist); template ExtMove* generateMoves<RECAPTURES >(const Position& pos, ExtMove* mlist, Square recapSq); template ExtMove* generateMoves<RECAPTURES_ALL >(const Position& pos, ExtMove* mlist, Square recapSq);
33.378347
174
0.642997
Andyryo
881f6ac9e7fb8f4edf9fbed299e36efce2431645
8,744
cpp
C++
samples/directx/d3d9_interop.cpp
VladKarpushin/opencv
9787ab598b6609a6ca6652a12441d741cb15f695
[ "BSD-3-Clause" ]
17
2016-03-16T08:48:30.000Z
2022-02-21T12:09:28.000Z
samples/directx/d3d9_interop.cpp
nurisis/opencv
4378b4d03d8415a132b6675883957243f95d75ee
[ "BSD-3-Clause" ]
5
2017-10-15T15:44:47.000Z
2022-02-17T11:31:32.000Z
samples/directx/d3d9_interop.cpp
nurisis/opencv
4378b4d03d8415a132b6675883957243f95d75ee
[ "BSD-3-Clause" ]
25
2018-09-26T08:51:13.000Z
2022-02-24T13:43:58.000Z
/* // Sample demonstrating interoperability of OpenCV UMat with Direct X surface // At first, the data obtained from video file or camera and // placed onto Direct X surface, // following mapping of this Direct X surface to OpenCV UMat and call cv::Blur // function. The result is mapped back to Direct X surface and rendered through // Direct X API. */ #define WIN32_LEAN_AND_MEAN #include <windows.h> #include <d3d9.h> #include "opencv2/core.hpp" #include "opencv2/core/directx.hpp" #include "opencv2/core/ocl.hpp" #include "opencv2/imgproc.hpp" #include "opencv2/videoio.hpp" #include "d3dsample.hpp" #pragma comment (lib, "d3d9.lib") using namespace std; using namespace cv; class D3D9WinApp : public D3DSample { public: D3D9WinApp(int width, int height, std::string& window_name, cv::VideoCapture& cap) : D3DSample(width, height, window_name, cap) {} ~D3D9WinApp() {} int create(void) { // base initialization D3DSample::create(); // initialize DirectX HRESULT r; m_pD3D9 = ::Direct3DCreate9(D3D_SDK_VERSION); if (NULL == m_pD3D9) { return -1; } DWORD flags = D3DCREATE_HARDWARE_VERTEXPROCESSING | D3DCREATE_PUREDEVICE | D3DCREATE_NOWINDOWCHANGES | D3DCREATE_MULTITHREADED | D3DCREATE_FPU_PRESERVE; D3DPRESENT_PARAMETERS d3dpp; ::ZeroMemory(&d3dpp, sizeof(D3DPRESENT_PARAMETERS)); d3dpp.Windowed = true; d3dpp.Flags = 0; d3dpp.BackBufferCount = 0; d3dpp.BackBufferFormat = D3DFMT_A8R8G8B8; d3dpp.BackBufferHeight = m_height; d3dpp.BackBufferWidth = m_width; d3dpp.MultiSampleType = D3DMULTISAMPLE_NONE; d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD; d3dpp.hDeviceWindow = m_hWnd; d3dpp.PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE; d3dpp.FullScreen_RefreshRateInHz = D3DPRESENT_RATE_DEFAULT; r = m_pD3D9->CreateDevice(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, m_hWnd, flags, &d3dpp, &m_pD3D9Dev); if (FAILED(r)) { return -1; } r = m_pD3D9Dev->GetBackBuffer(0, 0, D3DBACKBUFFER_TYPE_MONO, &m_pBackBuffer); if (FAILED(r)) { return -1; } r = m_pD3D9Dev->CreateOffscreenPlainSurface(m_width, m_height, D3DFMT_A8R8G8B8, D3DPOOL_DEFAULT, &m_pSurface, NULL); if (FAILED(r)) { std::cerr << "Can't create surface for result" << std::endl; return -1; } // initialize OpenCL context of OpenCV lib from DirectX if (cv::ocl::haveOpenCL()) { m_oclCtx = cv::directx::ocl::initializeContextFromDirect3DDevice9(m_pD3D9Dev); } m_oclDevName = cv::ocl::useOpenCL() ? cv::ocl::Context::getDefault().device(0).name() : "No OpenCL device"; return 0; } // create() // get media data on DX surface for further processing int get_surface(LPDIRECT3DSURFACE9* ppSurface) { HRESULT r; if (!m_cap.read(m_frame_bgr)) return -1; cv::cvtColor(m_frame_bgr, m_frame_rgba, COLOR_BGR2BGRA); D3DLOCKED_RECT memDesc = { 0, NULL }; RECT rc = { 0, 0, m_width, m_height }; r = m_pSurface->LockRect(&memDesc, &rc, 0); if (FAILED(r)) { return r; } cv::Mat m(m_height, m_width, CV_8UC4, memDesc.pBits, memDesc.Pitch); // copy video frame data to surface m_frame_rgba.copyTo(m); r = m_pSurface->UnlockRect(); if (FAILED(r)) { return r; } *ppSurface = m_pSurface; return 0; } // get_surface() // process and render media data int render() { try { if (m_shutdown) return 0; // capture user input once MODE mode = (m_mode == MODE_GPU_NV12) ? MODE_GPU_RGBA : m_mode; HRESULT r; LPDIRECT3DSURFACE9 pSurface; r = get_surface(&pSurface); if (FAILED(r)) { return -1; } m_timer.start(); switch (mode) { case MODE_CPU: { // process video frame on CPU D3DLOCKED_RECT memDesc = { 0, NULL }; RECT rc = { 0, 0, m_width, m_height }; r = pSurface->LockRect(&memDesc, &rc, 0); if (FAILED(r)) { return -1; } cv::Mat m(m_height, m_width, CV_8UC4, memDesc.pBits, memDesc.Pitch); if (m_demo_processing) { // blur D3D9 surface with OpenCV on CPU cv::blur(m, m, cv::Size(15, 15), cv::Point(-7, -7)); } r = pSurface->UnlockRect(); if (FAILED(r)) { return -1; } break; } case MODE_GPU_RGBA: { // process video frame on GPU cv::UMat u; cv::directx::convertFromDirect3DSurface9(pSurface, u); if (m_demo_processing) { // blur D3D9 surface with OpenCV on GPU with OpenCL cv::blur(u, u, cv::Size(15, 15), cv::Point(-7, -7)); } cv::directx::convertToDirect3DSurface9(u, pSurface); break; } } // switch m_timer.stop(); print_info(pSurface, mode, m_timer.time(Timer::UNITS::MSEC), m_oclDevName); // traditional DX render pipeline: // BitBlt surface to backBuffer and flip backBuffer to frontBuffer r = m_pD3D9Dev->StretchRect(pSurface, NULL, m_pBackBuffer, NULL, D3DTEXF_NONE); if (FAILED(r)) { return -1; } // present the back buffer contents to the display r = m_pD3D9Dev->Present(NULL, NULL, NULL, NULL); if (FAILED(r)) { return -1; } } // try catch (cv::Exception& e) { std::cerr << "Exception: " << e.what() << std::endl; return 10; } return 0; } // render() void print_info(LPDIRECT3DSURFACE9 pSurface, int mode, float time, cv::String oclDevName) { HDC hDC; HRESULT r = pSurface->GetDC(&hDC); if (FAILED(r)) { return; } HFONT hFont = (HFONT)::GetStockObject(SYSTEM_FONT); HFONT hOldFont = (HFONT)::SelectObject(hDC, hFont); if (hOldFont) { TEXTMETRIC tm; ::GetTextMetrics(hDC, &tm); char buf[256]; int y = 0; buf[0] = 0; sprintf(buf, "mode: %s", m_modeStr[mode].c_str()); ::TextOut(hDC, 0, y, buf, (int)strlen(buf)); y += tm.tmHeight; buf[0] = 0; sprintf(buf, m_demo_processing ? "blur frame" : "copy frame"); ::TextOut(hDC, 0, y, buf, (int)strlen(buf)); y += tm.tmHeight; buf[0] = 0; sprintf(buf, "time: %4.1f msec", time); ::TextOut(hDC, 0, y, buf, (int)strlen(buf)); y += tm.tmHeight; buf[0] = 0; sprintf(buf, "OpenCL device: %s", oclDevName.c_str()); ::TextOut(hDC, 0, y, buf, (int)strlen(buf)); ::SelectObject(hDC, hOldFont); } r = pSurface->ReleaseDC(hDC); return; } // print_info() int cleanup(void) { SAFE_RELEASE(m_pSurface); SAFE_RELEASE(m_pBackBuffer); SAFE_RELEASE(m_pD3D9Dev); SAFE_RELEASE(m_pD3D9); D3DSample::cleanup(); return 0; } // cleanup() private: LPDIRECT3D9 m_pD3D9; LPDIRECT3DDEVICE9 m_pD3D9Dev; LPDIRECT3DSURFACE9 m_pBackBuffer; LPDIRECT3DSURFACE9 m_pSurface; cv::ocl::Context m_oclCtx; cv::String m_oclPlatformName; cv::String m_oclDevName; }; // main func int main(int argc, char** argv) { std::string title = "D3D9 interop sample"; return d3d_app<D3D9WinApp>(argc, argv, title); }
27.496855
124
0.510293
VladKarpushin
8822139bf60878f5588ea0076a11292dd50b4467
2,123
hpp
C++
sprout/range/algorithm/next_symmetric_difference.hpp
kariya-mitsuru/Sprout
8274f34db498b02bff12277bac5416ea72e018cd
[ "BSL-1.0" ]
null
null
null
sprout/range/algorithm/next_symmetric_difference.hpp
kariya-mitsuru/Sprout
8274f34db498b02bff12277bac5416ea72e018cd
[ "BSL-1.0" ]
null
null
null
sprout/range/algorithm/next_symmetric_difference.hpp
kariya-mitsuru/Sprout
8274f34db498b02bff12277bac5416ea72e018cd
[ "BSL-1.0" ]
null
null
null
/*============================================================================= Copyright (c) 2011-2017 Bolero MURAKAMI https://github.com/bolero-MURAKAMI/Sprout Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) =============================================================================*/ #ifndef SPROUT_RANGE_ALGORITHM_NEXT_SYMMETRIC_DIFFERENCE_HPP #define SPROUT_RANGE_ALGORITHM_NEXT_SYMMETRIC_DIFFERENCE_HPP #include <sprout/config.hpp> #include <sprout/container/functions.hpp> #include <sprout/utility/forward.hpp> #include <sprout/utility/pair/pair.hpp> #include <sprout/range/type_traits/lvalue_iterator.hpp> #include <sprout/algorithm/next_symmetric_difference.hpp> namespace sprout { namespace range { // // next_symmetric_difference // template<typename Range1, typename Range2, typename Compare> inline SPROUT_CONSTEXPR sprout::pair< typename sprout::range::lvalue_iterator<Range1>::type, typename sprout::range::lvalue_iterator<Range2>::type > next_symmetric_difference(Range1&& range1, Range2&& range2, Compare comp) { return sprout::next_symmetric_difference( sprout::begin(SPROUT_FORWARD(Range1, range1)), sprout::end(SPROUT_FORWARD(Range1, range1)), sprout::begin(SPROUT_FORWARD(Range2, range2)), sprout::end(SPROUT_FORWARD(Range2, range2)), comp ); } template<typename Range1, typename Range2> inline SPROUT_CONSTEXPR sprout::pair< typename sprout::range::lvalue_iterator<Range1>::type, typename sprout::range::lvalue_iterator<Range2>::type > next_symmetric_difference(Range1&& range1, Range2&& range2) { return sprout::next_symmetric_difference( sprout::begin(SPROUT_FORWARD(Range1, range1)), sprout::end(SPROUT_FORWARD(Range1, range1)), sprout::begin(SPROUT_FORWARD(Range2, range2)), sprout::end(SPROUT_FORWARD(Range2, range2)) ); } } // namespace range } // namespace sprout #endif // #ifndef SPROUT_RANGE_ALGORITHM_NEXT_SYMMETRIC_DIFFERENCE_HPP
38.6
80
0.688648
kariya-mitsuru
882850d1a88a74536a8c5926a80bf59b9fabc452
2,847
cpp
C++
SerialPrograms/Source/CommonFramework/Options/EnumDropdownOption.cpp
Gin890/Arduino-Source
9047ff584010d8ddc3558068874f16fb3c7bb46d
[ "MIT" ]
null
null
null
SerialPrograms/Source/CommonFramework/Options/EnumDropdownOption.cpp
Gin890/Arduino-Source
9047ff584010d8ddc3558068874f16fb3c7bb46d
[ "MIT" ]
null
null
null
SerialPrograms/Source/CommonFramework/Options/EnumDropdownOption.cpp
Gin890/Arduino-Source
9047ff584010d8ddc3558068874f16fb3c7bb46d
[ "MIT" ]
null
null
null
/* Enum Dropdown Option * * From: https://github.com/PokemonAutomation/Arduino-Source * */ #include <QJsonValue> #include <QHBoxLayout> #include <QLabel> #include "Common/Qt/NoWheelComboBox.h" #include "EnumDropdownOption.h" #include "EnumDropdownWidget.h" namespace PokemonAutomation{ EnumDropdownOption::EnumDropdownOption( QString label, std::vector<QString> cases, size_t default_index ) : m_label(std::move(label)) , m_case_list(std::move(cases)) , m_default(default_index) , m_current(default_index) { if (default_index >= m_case_list.size()){ throw "Index is too large."; } for (size_t index = 0; index < m_case_list.size(); index++){ const QString& item = m_case_list[index]; auto ret = m_case_map.emplace( std::piecewise_construct, std::forward_as_tuple(item), std::forward_as_tuple(index) ); if (!ret.second){ throw "Duplicate enum label."; } } } void EnumDropdownOption::load_json(const QJsonValue& json){ if (!json.isString()){ return; } QString str = json.toString(); auto iter = m_case_map.find(str); if (iter != m_case_map.end()){ m_current.store(iter->second, std::memory_order_relaxed); } } QJsonValue EnumDropdownOption::to_json() const{ return QJsonValue(m_case_list[m_current]); } void EnumDropdownOption::restore_defaults(){ m_current.store(m_default, std::memory_order_relaxed); } ConfigWidget* EnumDropdownOption::make_ui(QWidget& parent){ return new EnumDropdownWidget(parent, *this); } EnumDropdownWidget::EnumDropdownWidget(QWidget& parent, EnumDropdownOption& value) : QWidget(&parent) , ConfigWidget(value, *this) , m_value(value) { QHBoxLayout* layout = new QHBoxLayout(this); layout->setContentsMargins(0, 0, 0, 0); QLabel* text = new QLabel(m_value.label(), this); layout->addWidget(text, 1); text->setWordWrap(true); m_box = new NoWheelComboBox(&parent); layout->addWidget(m_box); for (const QString& item : m_value.case_list()){ m_box->addItem(item); } m_box->setCurrentIndex((int)m_value); layout->addWidget(m_box, 1); connect( m_box, static_cast<void(QComboBox::*)(int)>(&QComboBox::currentIndexChanged), this, [=](int index){ if (index < 0){ m_value.restore_defaults(); return; } m_value.set(index); emit on_changed(); } ); } void EnumDropdownWidget::restore_defaults(){ m_value.restore_defaults(); update_ui(); } void EnumDropdownWidget::update_ui(){ m_box->setCurrentIndex((int)m_value); } }
25.19469
86
0.617492
Gin890
88292f12184ed19f3e48204eeecfb922261b6126
433
cpp
C++
2022.04.17-Retake control 2/Project1/Source.cpp
Hasan-bit-droid/programming-1-c-rus-2021
4d3fc27793a753d7c2b9c4eed31fda354792e766
[ "Apache-2.0" ]
null
null
null
2022.04.17-Retake control 2/Project1/Source.cpp
Hasan-bit-droid/programming-1-c-rus-2021
4d3fc27793a753d7c2b9c4eed31fda354792e766
[ "Apache-2.0" ]
null
null
null
2022.04.17-Retake control 2/Project1/Source.cpp
Hasan-bit-droid/programming-1-c-rus-2021
4d3fc27793a753d7c2b9c4eed31fda354792e766
[ "Apache-2.0" ]
null
null
null
#include <iostream> #include "ArrayList.h" using namespace std; int main() { int* tmp = new int[2]; tmp[0] = 2; tmp[1] = -1; IntArray arr1(tmp, 2, 2), arr2; delete[] tmp; tmp = nullptr; for (int i = 0; i < 3; ++i) { arr2 += i; } cout << arr1 + arr2 << endl; IntArray arrClone(arr1); arrClone = arr2; if (arrClone == arr2) { cout << arrClone << endl; } }
16.037037
35
0.491917
Hasan-bit-droid
8831e85b1f9dbdb0c3414d0e1165c0f0c944201f
784
hpp
C++
stan/math/prim/mat/fun/typedefs.hpp
jrmie/math
2850ec262181075a5843968e805dc9ad1654e069
[ "BSD-3-Clause" ]
null
null
null
stan/math/prim/mat/fun/typedefs.hpp
jrmie/math
2850ec262181075a5843968e805dc9ad1654e069
[ "BSD-3-Clause" ]
null
null
null
stan/math/prim/mat/fun/typedefs.hpp
jrmie/math
2850ec262181075a5843968e805dc9ad1654e069
[ "BSD-3-Clause" ]
null
null
null
#ifndef STAN_MATH_PRIM_MAT_FUN_TYPEDEFS_HPP #define STAN_MATH_PRIM_MAT_FUN_TYPEDEFS_HPP #include <stan/math/prim/mat/fun/Eigen.hpp> #include <stan/math/prim/mat/meta/index_type.hpp> namespace stan { namespace math { /** * Type for sizes and indexes in an Eigen matrix with double e */ typedef index_type<Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> >::type size_type; /** * Type for matrix of double values. */ typedef Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> matrix_d; /** * Type for (column) vector of double values. */ typedef Eigen::Matrix<double, Eigen::Dynamic, 1> vector_d; /** * Type for (row) vector of double values. */ typedef Eigen::Matrix<double, 1, Eigen::Dynamic> row_vector_d; } // namespace math } // namespace stan #endif
22.4
80
0.727041
jrmie
883210c360059dd6fc0ad41f01f2f8be0c7967a6
2,243
cpp
C++
src/utils/SkBitmapChecksummer.cpp
glennw/skia
79aa9354837bc195b83fa041b9632ea628e6f7d0
[ "BSD-3-Clause" ]
null
null
null
src/utils/SkBitmapChecksummer.cpp
glennw/skia
79aa9354837bc195b83fa041b9632ea628e6f7d0
[ "BSD-3-Clause" ]
null
null
null
src/utils/SkBitmapChecksummer.cpp
glennw/skia
79aa9354837bc195b83fa041b9632ea628e6f7d0
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright 2012 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "SkBitmap.h" #include "SkBitmapChecksummer.h" #include "SkBitmapTransformer.h" #include "SkCityHash.h" #include "SkEndian.h" /** * Write an integer value into a bytebuffer in little-endian order. */ static void write_int_to_buffer(int val, char* buf) { val = SkEndian_SwapLE32(val); for (int byte=0; byte<4; byte++) { *buf++ = (char)(val & 0xff); val = val >> 8; } } /*static*/ uint64_t SkBitmapChecksummer::Compute64Internal( const SkBitmap& bitmap, const SkBitmapTransformer& transformer) { size_t pixelBufferSize = transformer.bytesNeededTotal(); size_t totalBufferSize = pixelBufferSize + 8; // leave room for x/y dimensions SkAutoMalloc bufferManager(totalBufferSize); char *bufferStart = static_cast<char *>(bufferManager.get()); char *bufPtr = bufferStart; // start with the x/y dimensions write_int_to_buffer(bitmap.width(), bufPtr); bufPtr += 4; write_int_to_buffer(bitmap.height(), bufPtr); bufPtr += 4; // add all the pixel data if (!transformer.copyBitmapToPixelBuffer(bufPtr, pixelBufferSize)) { return 0; } return SkCityHash::Compute64(bufferStart, totalBufferSize); } /*static*/ uint64_t SkBitmapChecksummer::Compute64(const SkBitmap& bitmap) { const SkBitmapTransformer::PixelFormat kPixelFormat = SkBitmapTransformer::kARGB_8888_Premul_PixelFormat; // First, try to transform the existing bitmap. const SkBitmapTransformer transformer = SkBitmapTransformer(bitmap, kPixelFormat); if (transformer.isValid(false)) { return Compute64Internal(bitmap, transformer); } // Hmm, that didn't work. Maybe if we create a new // kARGB_8888_Config version of the bitmap it will work better? SkBitmap copyBitmap; bitmap.copyTo(&copyBitmap, SkBitmap::kARGB_8888_Config); const SkBitmapTransformer copyTransformer = SkBitmapTransformer(copyBitmap, kPixelFormat); if (copyTransformer.isValid(true)) { return Compute64Internal(copyBitmap, copyTransformer); } else { return 0; } }
32.042857
82
0.701293
glennw
8839d685bc65ad377d64ab04340a1508308ccbe8
3,730
cpp
C++
live555/liveMedia/TheoraVideoRTPSource.cpp
SQZhangOwO/videoMonitoring
d0c5890dc161ad13e84d597faed3ef28ad171645
[ "MIT" ]
1
2020-05-13T19:04:11.000Z
2020-05-13T19:04:11.000Z
live555/liveMedia/TheoraVideoRTPSource.cpp
SQZhangOwO/videoMonitoring
d0c5890dc161ad13e84d597faed3ef28ad171645
[ "MIT" ]
1
2021-06-11T06:11:22.000Z
2021-06-11T06:11:22.000Z
live555/liveMedia/TheoraVideoRTPSource.cpp
SQZhangOwO/videoMonitoring
d0c5890dc161ad13e84d597faed3ef28ad171645
[ "MIT" ]
1
2018-03-12T14:18:12.000Z
2018-03-12T14:18:12.000Z
/********** This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. (See <http://www.gnu.org/copyleft/lesser.html>.) This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA **********/ // "liveMedia" // Copyright (c) 1996-2018 Live Networks, Inc. All rights reserved. // Theora Video RTP Sources // Implementation #include "TheoraVideoRTPSource.hh" ////////// TheoraBufferedPacket and TheoraBufferedPacketFactory ////////// class TheoraBufferedPacket: public BufferedPacket { public: TheoraBufferedPacket(); virtual ~TheoraBufferedPacket(); private: // redefined virtual functions virtual unsigned nextEnclosedFrameSize(unsigned char*& framePtr, unsigned dataSize); }; class TheoraBufferedPacketFactory: public BufferedPacketFactory { private: // redefined virtual functions virtual BufferedPacket* createNewPacket(MultiFramedRTPSource* ourSource); }; ///////// TheoraVideoRTPSource implementation //////// TheoraVideoRTPSource* TheoraVideoRTPSource::createNew(UsageEnvironment& env, Groupsock* RTPgs, unsigned char rtpPayloadFormat) { return new TheoraVideoRTPSource(env, RTPgs, rtpPayloadFormat); } TheoraVideoRTPSource ::TheoraVideoRTPSource(UsageEnvironment& env, Groupsock* RTPgs, unsigned char rtpPayloadFormat) : MultiFramedRTPSource(env, RTPgs, rtpPayloadFormat, 90000, new TheoraBufferedPacketFactory), fCurPacketIdent(0) { } TheoraVideoRTPSource::~TheoraVideoRTPSource() { } Boolean TheoraVideoRTPSource ::processSpecialHeader(BufferedPacket* packet, unsigned& resultSpecialHeaderSize) { unsigned char* headerStart = packet->data(); unsigned packetSize = packet->dataSize(); resultSpecialHeaderSize = 4; if (packetSize < resultSpecialHeaderSize) return False; // packet was too small // The first 3 bytes of the header are the "Ident" field: fCurPacketIdent = (headerStart[0]<<16) | (headerStart[1]<<8) | headerStart[2]; // The 4th byte is F|TDT|numPkts. // Reject any packet with TDT == 3: if ((headerStart[3]&0x30) == 0x30) return False; u_int8_t F = headerStart[3]>>6; fCurrentPacketBeginsFrame = F <= 1; // "Not Fragmented" or "Start Fragment" fCurrentPacketCompletesFrame = F == 0 || F == 3; // "Not Fragmented" or "End Fragment" return True; } char const* TheoraVideoRTPSource::MIMEtype() const { return "video/THEORA"; } ////////// TheoraBufferedPacket and TheoraBufferedPacketFactory implementation ////////// TheoraBufferedPacket::TheoraBufferedPacket() { } TheoraBufferedPacket::~TheoraBufferedPacket() { } unsigned TheoraBufferedPacket ::nextEnclosedFrameSize(unsigned char*& framePtr, unsigned dataSize) { if (dataSize < 2) { // There's not enough space for a 2-byte header. TARFU! Just return the data that's left: return dataSize; } unsigned frameSize = (framePtr[0]<<8) | framePtr[1]; framePtr += 2; if (frameSize > dataSize - 2) return dataSize - 2; // inconsistent frame size => just return all the data that's left return frameSize; } BufferedPacket* TheoraBufferedPacketFactory ::createNewPacket(MultiFramedRTPSource* /*ourSource*/) { return new TheoraBufferedPacket(); }
32.719298
119
0.741555
SQZhangOwO
883a99791219c451be9f08ec36a8bf09b32189de
224
cpp
C++
src/xray/xr_3da/xrGame/ai/monsters/snork/snork_script.cpp
OLR-xray/OLR-3.0
b6a9bb2a0c1fb849b8c6cea2e831e1ceea5cc611
[ "Apache-2.0" ]
8
2016-01-25T20:18:51.000Z
2019-03-06T07:00:04.000Z
src/xray/xr_3da/xrGame/ai/monsters/snork/snork_script.cpp
OLR-xray/OLR-3.0
b6a9bb2a0c1fb849b8c6cea2e831e1ceea5cc611
[ "Apache-2.0" ]
null
null
null
src/xray/xr_3da/xrGame/ai/monsters/snork/snork_script.cpp
OLR-xray/OLR-3.0
b6a9bb2a0c1fb849b8c6cea2e831e1ceea5cc611
[ "Apache-2.0" ]
3
2016-02-14T01:20:43.000Z
2021-02-03T11:19:11.000Z
#include "pch_script.h" #include "snork.h" using namespace luabind; #pragma optimize("s",on) void CSnork::script_register(lua_State *L) { module(L) [ class_<CSnork,CGameObject>("CSnork") .def(constructor<>()) ]; }
14.933333
42
0.6875
OLR-xray
88458a22f6b44cd2895540fef216646976260e9e
5,729
cpp
C++
jtk.tests/image_tests.cpp
janm31415/jtk
513fa8ac4f3ef29d8989a82a6c46df9ba15e4d2a
[ "MIT" ]
3
2021-02-15T07:58:56.000Z
2021-02-16T01:02:38.000Z
jtk.tests/image_tests.cpp
janm31415/jtk
513fa8ac4f3ef29d8989a82a6c46df9ba15e4d2a
[ "MIT" ]
null
null
null
jtk.tests/image_tests.cpp
janm31415/jtk
513fa8ac4f3ef29d8989a82a6c46df9ba15e4d2a
[ "MIT" ]
null
null
null
#include "image_tests.h" #include <stdint.h> #define JTK_IMAGE_IMPLEMENTATION #include "../jtk/image.h" #include "../jtk/vec.h" #include "test_assert.h" namespace jtk { void test_fill_image() { int w = 10; int h = 10; image<uint8_t> im(w, h); fill_image(im, (uint8_t)5); for (int y = 0; y < h; ++y) { for (int x = 0; x < w; ++x) { TEST_EQ(5, im(x, y)); } } fill_image(im, (uint8_t)6); for (int y = 0; y < h; ++y) { for (int x = 0; x < w; ++x) { TEST_EQ(6, im(x, y)); } } } namespace { #ifndef _JTK_FOR_ARM inline image<uint32_t> census_transform_avx(const image<uint8_t>& im) { /* The census transform is an image operator that associates to each pixel of a grayscale image a binary string, encoding whether the pixel has smaller intensity than each of its neighbours, one for each bit. We use a 9x7 window. */ using namespace image_details; const int w = (int)im.width(); const int s = (int)im.stride(); const int h = (int)im.height(); const int ns = (int)(sizeof(census_samples) / sizeof(int)) / 2; image<uint32_t> ct(w, h, true); const int cs = (int)ct.stride(); for (int y = 4; y < h - 4; ++y) { __m256i descriptor = _mm256_setzero_si256(); const uint8_t* p_im = im.data() + s * y; for (int x = 4; x < w - 4; ++x, ++p_im) { uint32_t* ct_pos = ct.data() + (y*cs) + x; uint8_t* descriptor_it = (uint8_t*)&descriptor; uint8_t value = *p_im; const __m256i value256 = _mm256_set1_epi8(value); const int pos = y * s + x; for (int p = 0; p < ns; p++) { *descriptor_it = *(p_im + census_samples[2 * p] + census_samples[2 * p + 1] * s); ++descriptor_it; } const __m256i r1 = _mm256_cmpgt_epi8(descriptor, value256); *ct_pos = _mm256_movemask_epi8(r1); } } return ct; } inline image<vec3<uint32_t>> census_transform_avx(const image<uint32_t>& im) { /* The census transform is an image operator that associates to each pixel of a grayscale image a binary string, encoding whether the pixel has smaller intensity than each of its neighbours, one for each bit. We use a 9x7 window. */ using namespace image_details; const int w = (int)im.width(); const int s = (int)im.stride(); const int h = (int)im.height(); const int ns = (int)(sizeof(census_samples) / sizeof(int)) / 2; image<vec3<uint32_t>> ct(w, h, true); const int cs = (int)ct.stride(); for (int y = 4; y < h - 4; ++y) { __m256i descriptor_red = _mm256_setzero_si256(); __m256i descriptor_green = _mm256_setzero_si256(); __m256i descriptor_blue = _mm256_setzero_si256(); const uint32_t* p_im = im.data() + s * y; for (int x = 4; x < w - 4; ++x, ++p_im) { vec3<uint32_t>* ct_pos = ct.data() + (y*cs) + x; uint8_t* descriptor_red_it = (uint8_t*)&descriptor_red; uint8_t* descriptor_green_it = (uint8_t*)&descriptor_green; uint8_t* descriptor_blue_it = (uint8_t*)&descriptor_blue; uint32_t value = *p_im; const __m256i red256 = _mm256_set1_epi8(value & 0xff); const __m256i green256 = _mm256_set1_epi8((value >> 8) & 0xff); const __m256i blue256 = _mm256_set1_epi8((value >> 16) & 0xff); const int pos = y * s + x; for (int p = 0; p < ns; p++) { const uint32_t color = *(p_im + census_samples[2 * p] + census_samples[2 * p + 1] * s); *descriptor_red_it = color & 0xff; *descriptor_green_it = (color >> 8) & 0xff; *descriptor_blue_it = (color >> 16) & 0xff; ++descriptor_red_it; ++descriptor_green_it; ++descriptor_blue_it; } const __m256i r1 = _mm256_cmpgt_epi8(descriptor_red, red256); const __m256i g1 = _mm256_cmpgt_epi8(descriptor_green, green256); const __m256i b1 = _mm256_cmpgt_epi8(descriptor_blue, blue256); *ct_pos = vec3<uint32_t>(_mm256_movemask_epi8(r1), _mm256_movemask_epi8(g1), _mm256_movemask_epi8(b1)); } } return ct; } #endif } void test_census() { #ifndef _JTK_FOR_ARM int w = 64; int h = 64; image<uint8_t> im(w, h); for (int y = 0; y < h; ++y) for (int x = 0; x < w; ++x) im(x, y) = (x*y) & 255; image<uint32_t> imc1 = census_transform_avx(im); image<uint32_t> imc2 = census_transform(im); for (int y = 0; y < h; ++y) for (int x = 0; x < w; ++x) { TEST_EQ(imc1(x, y), imc2(x, y)); } #endif } void test_census_32() { #ifndef _JTK_FOR_ARM int w = 64; int h = 64; image<uint32_t> im(w, h); for (int y = 0; y < h; ++y) for (int x = 0; x < w; ++x) { uint32_t clr = ((x*y) & 255) | ((x*y*2) & 255) << 8 | ((x*y * 3) & 255) << 16 | 0xff000000; im(x, y) = clr; } image<vec3<uint32_t>> imc1 = census_transform_avx(im); image<uint32_t> imcr, imcg, imcb; census_transform(imcr, imcg, imcb, im); for (int y = 0; y < h; ++y) for (int x = 0; x < w; ++x) { TEST_EQ(imcr(x, y), imc1(x, y)[0]); TEST_EQ(imcg(x, y), imc1(x, y)[1]); TEST_EQ(imcb(x, y), imc1(x, y)[2]); } #endif } } void run_all_image_tests() { using namespace jtk; test_fill_image(); test_census(); test_census_32(); }
29.838542
115
0.542678
janm31415
88461e31bbf796da9378cddaf9fd57362ff01690
4,595
cc
C++
source/particles/pyG4ParticleDefinition.cc
yu22mal/geant4_pybind
ff7efc322fe53f39c7ae7ed140861052a92479fd
[ "Unlicense" ]
6
2021-08-08T08:40:13.000Z
2022-03-23T03:05:15.000Z
source/particles/pyG4ParticleDefinition.cc
yu22mal/geant4_pybind
ff7efc322fe53f39c7ae7ed140861052a92479fd
[ "Unlicense" ]
3
2021-12-01T14:38:06.000Z
2022-02-10T11:28:28.000Z
source/particles/pyG4ParticleDefinition.cc
yu22mal/geant4_pybind
ff7efc322fe53f39c7ae7ed140861052a92479fd
[ "Unlicense" ]
3
2021-07-16T13:57:34.000Z
2022-02-07T11:17:19.000Z
#include <pybind11/pybind11.h> #include <pybind11/stl.h> #include <G4DecayTable.hh> #include <G4ParticleDefinition.hh> #include <G4ParticleTable.hh> #include <G4ProcessManager.hh> #include "typecast.hh" #include "opaques.hh" namespace py = pybind11; void export_G4ParticleDefinition(py::module &m) { py::class_<G4ParticleDefinition>(m, "G4ParticleDefinition", "particle definition") .def(py::init<>([](const G4String &aName, G4double mass, G4double width, G4double charge, G4int iSpin, G4int iParity, G4int iConjugation, G4int iIsospin, G4int iIsospin3, G4int gParity, const G4String &pType, G4int lepton, G4int baryon, G4int encoding, G4bool stable, G4double lifetime, py::disown_ptr<G4DecayTable> decaytable, G4bool shortlived, const G4String &subType, G4int anti_encoding, G4double magneticMoment) { return new G4ParticleDefinition(aName, mass, width, charge, iSpin, iParity, iConjugation, iIsospin, iIsospin3, gParity, pType, lepton, baryon, encoding, stable, lifetime, decaytable, shortlived, subType, anti_encoding, magneticMoment); }), py::arg("aName"), py::arg("mass"), py::arg("width"), py::arg("charge"), py::arg("iSpin"), py::arg("iParity"), py::arg("iConjugation"), py::arg("iIsospin"), py::arg("iIsospinZ"), py::arg("gParity"), py::arg("pType"), py::arg("lepton"), py::arg("baryon"), py::arg("encoding"), py::arg("stable"), py::arg("lifetime"), py::arg("decaytable"), py::arg("shortlived") = false, py::arg("subType") = "", py::arg("anti_encoding") = 0, py::arg("magneticMoment") = 0.0) .def("GetParticleName", &G4ParticleDefinition::GetParticleName) .def("GetPDGMass", &G4ParticleDefinition::GetPDGMass) .def("GetPDGWidth", &G4ParticleDefinition::GetPDGWidth) .def("GetPDGCharge", &G4ParticleDefinition::GetPDGCharge) .def("GetPDGSpin", &G4ParticleDefinition::GetPDGSpin) .def("GetPDGiSpin", &G4ParticleDefinition::GetPDGiSpin) .def("GetPDGiParity", &G4ParticleDefinition::GetPDGiParity) .def("GetPDGiConjugation", &G4ParticleDefinition::GetPDGiConjugation) .def("GetPDGIsospin", &G4ParticleDefinition::GetPDGIsospin) .def("GetPDGIsospin3", &G4ParticleDefinition::GetPDGIsospin3) .def("GetPDGiIsospin", &G4ParticleDefinition::GetPDGiIsospin) .def("GetPDGiIsospin3", &G4ParticleDefinition::GetPDGiIsospin3) .def("GetPDGiGParity", &G4ParticleDefinition::GetPDGiGParity) .def("GetParticleType", &G4ParticleDefinition::GetParticleType) .def("GetParticleSubType", &G4ParticleDefinition::GetParticleSubType) .def("GetLeptonNumber", &G4ParticleDefinition::GetLeptonNumber) .def("GetBaryonNumber", &G4ParticleDefinition::GetBaryonNumber) .def("GetPDGEncoding", &G4ParticleDefinition::GetPDGEncoding) .def("GetAntiPDGEncoding", &G4ParticleDefinition::GetAntiPDGEncoding) .def("GetQuarkContent", &G4ParticleDefinition::GetQuarkContent) .def("GetAntiQuarkContent", &G4ParticleDefinition::GetAntiQuarkContent) .def("IsShortLived", &G4ParticleDefinition::IsShortLived) .def("GetPDGStable", &G4ParticleDefinition::GetPDGStable) .def("SetPDGStable", &G4ParticleDefinition::SetPDGStable) .def("GetPDGLifeTime", &G4ParticleDefinition::GetPDGLifeTime) .def("SetPDGLifeTime", &G4ParticleDefinition::SetPDGLifeTime) .def("GetDecayTable", &G4ParticleDefinition::GetDecayTable, py::return_value_policy::reference_internal) .def("SetDecayTable", [](G4ParticleDefinition &self, py::disown_ptr<G4DecayTable> decayTable) { self.SetDecayTable(decayTable); }) .def("GetProcessManager", &G4ParticleDefinition::GetProcessManager, py::return_value_policy::reference_internal) .def("SetProcessManager", &G4ParticleDefinition::SetProcessManager) .def("GetParticleTable", &G4ParticleDefinition::GetParticleTable, py::return_value_policy::reference) .def("DumpTable", &G4ParticleDefinition::DumpTable) .def("GetAtomicNumber", &G4ParticleDefinition::GetAtomicNumber) .def("GetAtomicMass", &G4ParticleDefinition::GetAtomicMass) .def("SetVerboseLevel", &G4ParticleDefinition::SetVerboseLevel) .def("GetVerboseLevel", &G4ParticleDefinition::GetVerboseLevel) .def("SetApplyCutsFlag", &G4ParticleDefinition::SetApplyCutsFlag) .def("GetApplyCutsFlag", &G4ParticleDefinition::GetApplyCutsFlag); }
62.094595
120
0.698585
yu22mal
884659826ce1551b680cc6cd72afa829794e0f01
10,772
cpp
C++
earth_enterprise/src/common/khxml/khxml.cpp
arjntc1/earthenterprise
3a0a1dcefcd38e0d5b5257f351b6c3c0d30335fd
[ "Apache-2.0" ]
3
2017-12-21T05:40:09.000Z
2018-05-16T11:18:25.000Z
earth_enterprise/src/common/khxml/khxml.cpp
Albinlk/GoogleEarth
f8cde66d5271b1b9cdbe0b8fc7da9fdc389ce172
[ "Apache-2.0" ]
null
null
null
earth_enterprise/src/common/khxml/khxml.cpp
Albinlk/GoogleEarth
f8cde66d5271b1b9cdbe0b8fc7da9fdc389ce172
[ "Apache-2.0" ]
1
2019-09-09T09:48:08.000Z
2019-09-09T09:48:08.000Z
// Copyright 2017 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <xercesc/framework/LocalFileFormatTarget.hpp> #include <xercesc/framework/MemBufFormatTarget.hpp> #include <xercesc/framework/MemBufInputSource.hpp> #include <xercesc/framework/Wrapper4InputSource.hpp> #include <xercesc/util/PlatformUtils.hpp> #include <notify.h> #include <khThread.h> #include <khFileUtils.h> #include "khxml.h" #include "khdom.h" using namespace khxml; std::string ListElementTagName(const std::string &tagname) { if (tagname[tagname.length()-1] == 's') { return tagname.substr(0, tagname.length()-1); } else { return tagname + "_element"; } } // This is used only in the following function class UsingXMLGuard { friend void InitializeXMLLibrary(void) throw(); UsingXMLGuard(void) throw() { try { XMLPlatformUtils::Initialize(); } catch(const XMLException& toCatch) { notify(NFY_FATAL, "Unable to initialize Xerces: %s", FromXMLStr(toCatch.getMessage()).c_str()); } } ~UsingXMLGuard(void) throw() { try { XMLPlatformUtils::Terminate(); } catch (...) { } } }; static khMutexBase xmlLibLock = KH_MUTEX_BASE_INITIALIZER; void InitializeXMLLibrary(void) throw() { khLockGuard guard(xmlLibLock); static UsingXMLGuard XMLLibGuard; } DOMDocument * CreateEmptyDocument(const std::string &rootTagname) throw() { InitializeXMLLibrary(); try { DOMImplementation* impl = DOMImplementationRegistry::getDOMImplementation(0); DOMDocument* doc = impl->createDocument( 0,// root element namespace URI. ToXMLStr(rootTagname),// root element name 0);// document type object (DTD) return doc; } catch (...) { return 0; } } namespace { bool WriteDocumentImpl(DOMDocument *doc, const std::string &filename) throw() { InitializeXMLLibrary(); bool success = false; try { // "LS" -> Load/Save extensions DOMImplementationLS* impl = (DOMImplementationLS*) DOMImplementationRegistry::getDOMImplementation(ToXMLStr("LS")); DOMLSSerializer* writer = impl->createLSSerializer(); try { // optionally you can set some features on this serializer if (writer->getDomConfig()->canSetParameter(XMLUni::fgDOMWRTDiscardDefaultContent, true)) writer->getDomConfig()->setParameter(XMLUni::fgDOMWRTDiscardDefaultContent, true); if (writer->getDomConfig()->canSetParameter(XMLUni::fgDOMWRTFormatPrettyPrint, true)) writer->getDomConfig()->setParameter(XMLUni::fgDOMWRTFormatPrettyPrint, true); if (!khEnsureParentDir(filename)) { notify(NFY_WARN, "Unable to write %s: Can't make parent directory.", filename.c_str()); } else { ToXMLStr fname(filename); LocalFileFormatTarget formatTarget(fname); DOMLSOutput* lsOutput = impl->createLSOutput(); lsOutput->setByteStream(&formatTarget); if (writer->write(doc, lsOutput)) { success = true; } else { notify(NFY_WARN, "Unable to write %s: Xerces didn't tell me why not.", filename.c_str()); } lsOutput->release(); } } catch (const XMLException& toCatch) { notify(NFY_WARN, "Unable to write %s: %s", filename.c_str(), XMLString::transcode(toCatch.getMessage())); } catch (const DOMException& toCatch) { notify(NFY_WARN, "Unable to write %s: %s", filename.c_str(), XMLString::transcode(toCatch.msg)); } catch (...) { notify(NFY_WARN, "Unable to write %s: Unknown exception", filename.c_str()); } writer->release(); } catch (const XMLException& toCatch) { notify(NFY_WARN, "Unable to create DOM Writer for %s: %s", filename.c_str(), XMLString::transcode(toCatch.getMessage())); } catch (const DOMException& toCatch) { notify(NFY_WARN, "Unable to create DOM Writer for %s: %s", filename.c_str(), XMLString::transcode(toCatch.msg)); } catch (...) { notify(NFY_WARN, "Unable to create DOM Writer for %s: Unknown exception", filename.c_str()); } return success; } } // anonymous namespace bool WriteDocument(DOMDocument *doc, const std::string &filename) throw() { static const std::string newext = ".new"; static const std::string backupext = ".old"; const std::string newname = filename + newext; const std::string backupname = filename + backupext; if (!WriteDocumentImpl(doc, newname)) { return false; } if (!khReplace(filename, newext, backupext)) { (void) khUnlink(newname); return false; } if (khExists(backupname)) { (void) khUnlink(backupname); } return true; } bool WriteDocumentToString(DOMDocument *doc, std::string &buf) throw() { InitializeXMLLibrary(); bool success = false; try { // "LS" -> Load/Save extensions DOMImplementationLS* impl = (DOMImplementationLS*) DOMImplementationRegistry::getDOMImplementation(ToXMLStr("LS")); DOMLSSerializer* writer = impl->createLSSerializer(); try { // optionally you can set some features on this serializer if (writer->getDomConfig()->canSetParameter(XMLUni::fgDOMWRTDiscardDefaultContent, true)) writer->getDomConfig()->setParameter(XMLUni::fgDOMWRTDiscardDefaultContent, true); if (writer->getDomConfig()->canSetParameter(XMLUni::fgDOMWRTFormatPrettyPrint, true)) writer->getDomConfig()->setParameter(XMLUni::fgDOMWRTFormatPrettyPrint, true); MemBufFormatTarget formatTarget; DOMLSOutput* lsOutput = impl->createLSOutput(); lsOutput->setByteStream(&formatTarget); if (writer->write(doc, lsOutput)) { buf.append((const char *)formatTarget.getRawBuffer(), formatTarget.getLen()); success = true; } else { notify(NFY_WARN, "Unable to write XML to string: Xerces didn't tell me why not."); } lsOutput->release(); } catch (const XMLException& toCatch) { notify(NFY_WARN, "Unable to write XML: %s", XMLString::transcode(toCatch.getMessage())); } catch (const DOMException& toCatch) { notify(NFY_WARN, "Unable to write XML: %s", XMLString::transcode(toCatch.msg)); } catch (...) { notify(NFY_WARN, "Unable to write XML: Unknown exception"); } writer->release(); } catch (const XMLException& toCatch) { notify(NFY_WARN, "Unable to create DOM Writer: %s", XMLString::transcode(toCatch.getMessage())); } catch (const DOMException& toCatch) { notify(NFY_WARN, "Unable to create DOM writer: %s", XMLString::transcode(toCatch.msg)); } catch (...) { notify(NFY_WARN, "Unable to create DOM writer: Unknown exception"); } return success; } khxml::DOMLSParser* CreateDOMParser(void) throw() { InitializeXMLLibrary(); class FatalErrorHandler : public DOMErrorHandler { public: virtual bool handleError(const DOMError &err) { if (err.getSeverity() >= DOMError::DOM_SEVERITY_FATAL_ERROR) { char* message = XMLString::transcode(err.getMessage()); notify(NFY_DEBUG, "XML Error: %s", message); XMLString::release(&message); throw DOMException(DOMException::SYNTAX_ERR); } return true; } }; static FatalErrorHandler fatalHandler; try { // "LS" -> Load/Save extensions DOMImplementationLS* impl = (DOMImplementationLS*) DOMImplementationRegistry::getDOMImplementation(ToXMLStr("LS")); DOMLSParser* parser = impl->createLSParser(DOMImplementationLS::MODE_SYNCHRONOUS, 0); // optionally you can set some features on this builder if (parser->getDomConfig()->canSetParameter(XMLUni::fgDOMValidate, true)) parser->getDomConfig()->setParameter(XMLUni::fgDOMValidate, true); if (parser->getDomConfig()->canSetParameter(XMLUni::fgDOMNamespaces, true)) parser->getDomConfig()->setParameter(XMLUni::fgDOMNamespaces, true); parser->getDomConfig()->setParameter(XMLUni::fgDOMErrorHandler, &fatalHandler); return parser; } catch (...) { return 0; } } khxml::DOMDocument* ReadDocument(khxml::DOMLSParser *parser, const std::string &filename) throw() { DOMDocument *doc = 0; try { // Note: parseURI doesn't handle missing files nicely...returns // invalid doc object. Must check file existence ourselves. if (khExists(filename)) { doc = parser->parseURI(filename.c_str()); } else { notify(NFY_WARN, "XML file does not exist: %s", filename.c_str()); } } catch (const XMLException& toCatch) { notify(NFY_WARN, "Unable to read XML: %s", XMLString::transcode(toCatch.getMessage())); } catch (const DOMException& toCatch) { notify(NFY_WARN, "Unable to read XML: %s", XMLString::transcode(toCatch.msg)); } catch (...) { notify(NFY_WARN, "Unable to read XML"); } return doc; } khxml::DOMDocument* ReadDocumentFromString(khxml::DOMLSParser *parser, const std::string &buf, const std::string &ref) throw() { DOMDocument *doc = 0; try { MemBufInputSource memBufIS( (const XMLByte*)buf.data(), buf.size(), ref.c_str(), false); // don't adopt buffer Wrapper4InputSource inputSource(&memBufIS, false); // don't adopt input source doc = parser->parse(&inputSource); } catch (const XMLException& toCatch) { notify(NFY_WARN, "Unable to read XML: %s", XMLString::transcode(toCatch.getMessage())); } catch (const DOMException& toCatch) { notify(NFY_WARN, "Unable to read XML: %s", XMLString::transcode(toCatch.msg)); } catch (...) { notify(NFY_WARN, "Unable to read XML"); } return doc; } bool DestroyDocument(khxml::DOMDocument *doc) throw() { try { doc->release(); return true; } catch (...) { } return false; } bool DestroyParser(khxml::DOMLSParser *parser) throw() { try { parser->release(); return true; } catch (...) { } return false; }
30.777143
96
0.649462
arjntc1
884b2bee6f74278662d506a7f6f07a42950ae39e
919
hpp
C++
archive/stan/src/stan/lang/ast/fun/has_var.hpp
alashworth/stan-monorepo
75596bc1f860ededd7b3e9ae9002aea97ee1cd46
[ "BSD-3-Clause" ]
1
2019-09-06T15:53:17.000Z
2019-09-06T15:53:17.000Z
archive/stan/src/stan/lang/ast/fun/has_var.hpp
alashworth/stan-monorepo
75596bc1f860ededd7b3e9ae9002aea97ee1cd46
[ "BSD-3-Clause" ]
8
2019-01-17T18:51:16.000Z
2019-01-17T18:51:39.000Z
archive/stan/src/stan/lang/ast/fun/has_var.hpp
alashworth/stan-monorepo
75596bc1f860ededd7b3e9ae9002aea97ee1cd46
[ "BSD-3-Clause" ]
null
null
null
#ifndef STAN_LANG_AST_FUN_HAS_VAR_HPP #define STAN_LANG_AST_FUN_HAS_VAR_HPP namespace stan { namespace lang { struct expression; struct variable_map; /** * Returns true if the specified expression contains a variable * that is defined as a parameter, defined as a transformed * parameter, or is a local variable that is not an integer. * * <p>Compare to <code>has_nonparam_var</code>, which is similar, * but excludes variables declared as parameters. * * @param e Expression to test. * @param var_map Variable mapping for origin and types of * variables. * @return true if expression contains a variable defined as as a * parameter, defined as a transformedparameter, or is a local * variable that is not an integer. */ bool has_var(const expression& e, const variable_map& var_map); } } #endif
30.633333
70
0.674646
alashworth
884de5b69edacde8ef7328589432243605df8599
17,658
cpp
C++
src/BlitHelper.cpp
procedural/d3d12_translation_layer
fc07d09db68e304b1210a7c4d7793c944dd8151f
[ "MIT" ]
1
2020-04-08T03:12:17.000Z
2020-04-08T03:12:17.000Z
src/BlitHelper.cpp
procedural/d3d12_translation_layer
fc07d09db68e304b1210a7c4d7793c944dd8151f
[ "MIT" ]
null
null
null
src/BlitHelper.cpp
procedural/d3d12_translation_layer
fc07d09db68e304b1210a7c4d7793c944dd8151f
[ "MIT" ]
null
null
null
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #pragma once #include "pch.h" #include "BlitHelperShaders.h" const UINT MAX_PLANES = 3; namespace D3D12TranslationLayer { static UINT RectHeight(const RECT& r) { return r.bottom - r.top; } static UINT RectWidth(const RECT& r) { return r.right - r.left; } BlitHelper::BlitHelper(ImmediateContext *pContext) : m_pParent(pContext) { } auto BlitHelper::PrepareShaders(Resource *pSrc, UINT srcPlanes, Resource *pDst, UINT dstPlanes, bool bEnableAlpha, bool bSwapRB) -> BlitPipelineState* { const D3D12_RESOURCE_DESC &srcDesc = pSrc->GetUnderlyingResource()->GetDesc(); const D3D12_RESOURCE_DESC &dstDesc = pDst->GetUnderlyingResource()->GetDesc(); if (CD3D11FormatHelper::YUV(dstDesc.Format)) { // YUV -> RGB conversion only for now, or RGB -> RGB stretching throw _com_error(E_INVALIDARG); } if (srcPlanes > MAX_PLANES) { throw _com_error(E_INVALIDARG); } if (dstPlanes != 1) { // just RGB output for now throw _com_error(E_INVALIDARG); } BlitHelperKeyUnion key; key.m_Bits.SrcFormat = srcDesc.Format; key.m_Bits.DstFormat = dstDesc.Format; key.m_Bits.DstSampleCount = dstDesc.SampleDesc.Count; key.m_Bits.bSwapRB = bSwapRB; key.m_Bits.bEnableAlpha = bEnableAlpha; key.m_Bits.Unused = 0; auto& spPSO = m_spBlitPSOs[key.m_Data]; if (!spPSO) { spPSO.reset(new BlitPipelineState(m_pParent)); struct ConvertPSOStreamDescriptor { CD3DX12_PIPELINE_STATE_STREAM_VS VS{ CD3DX12_SHADER_BYTECODE(g_VSMain, sizeof(g_VSMain)) }; CD3DX12_PIPELINE_STATE_STREAM_PS PS; CD3DX12_PIPELINE_STATE_STREAM_PRIMITIVE_TOPOLOGY PrimitiveTopology{ D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE }; CD3DX12_PIPELINE_STATE_STREAM_NODE_MASK NodeMask; CD3DX12_PIPELINE_STATE_STREAM_RENDER_TARGET_FORMATS RTVFormats; CD3DX12_PIPELINE_STATE_STREAM_DEPTH_STENCIL DSS; CD3DX12_PIPELINE_STATE_STREAM_BLEND_DESC Blend; CD3DX12_PIPELINE_STATE_STREAM_SAMPLE_DESC Samples; CD3DX12_PIPELINE_STATE_STREAM_SAMPLE_MASK SampleMask{ UINT_MAX }; } psoStream; if (srcDesc.Format == DXGI_FORMAT_P010 || srcDesc.Format == DXGI_FORMAT_Y210) { // we need to add additional math in the shader to scale from the 10bit range into the output [0,1]. As // the input to the shader is normalized, we need to multiply by 2^6 to get a float in the [0,1] range. throw _com_error(E_INVALIDARG); } switch (srcPlanes) { case 3: psoStream.PS = CD3DX12_SHADER_BYTECODE(g_PS3PlaneYUV, sizeof(g_PS3PlaneYUV)); break; case 2: psoStream.PS = CD3DX12_SHADER_BYTECODE(g_PS2PlaneYUV, sizeof(g_PS2PlaneYUV)); break; default: switch (srcDesc.Format) { case DXGI_FORMAT_AYUV: psoStream.PS = CD3DX12_SHADER_BYTECODE(g_PSAYUV, sizeof(g_PSAYUV)); break; case DXGI_FORMAT_Y410: case DXGI_FORMAT_Y416: psoStream.PS = CD3DX12_SHADER_BYTECODE(g_PSY4XX, sizeof(g_PSY4XX)); break; case DXGI_FORMAT_YUY2: case DXGI_FORMAT_Y210: case DXGI_FORMAT_Y216: psoStream.PS = CD3DX12_SHADER_BYTECODE(g_PSPackedYUV, sizeof(g_PSPackedYUV)); break; default: if (bSwapRB) { psoStream.PS = CD3DX12_SHADER_BYTECODE(g_PSBasic_SwapRB, sizeof(g_PSBasic_SwapRB)); } else { psoStream.PS = CD3DX12_SHADER_BYTECODE(g_PSBasic, sizeof(g_PSBasic)); } } break; } psoStream.NodeMask = m_pParent->GetNodeMask(); psoStream.RTVFormats = D3D12_RT_FORMAT_ARRAY{ { dstDesc.Format }, 1 }; psoStream.Samples = dstDesc.SampleDesc; CD3DX12_DEPTH_STENCIL_DESC DSS(CD3DX12_DEFAULT{}); DSS.DepthEnable = false; psoStream.DSS = DSS; if (bEnableAlpha) { auto& blendDesc = static_cast<CD3DX12_BLEND_DESC&>(psoStream.Blend).RenderTarget[0]; blendDesc.BlendEnable = TRUE; blendDesc.SrcBlend = D3D12_BLEND_SRC_ALPHA; blendDesc.DestBlend = D3D12_BLEND_INV_SRC_ALPHA; blendDesc.BlendOp = D3D12_BLEND_OP_ADD; blendDesc.SrcBlendAlpha = D3D12_BLEND_ONE; blendDesc.DestBlendAlpha = D3D12_BLEND_ONE; blendDesc.BlendOpAlpha = D3D12_BLEND_OP_ADD; } D3D12_PIPELINE_STATE_STREAM_DESC psoStreamDesc = { sizeof(psoStream), &psoStream }; ThrowFailure(m_pParent->m_pDevice12_2->CreatePipelineState(&psoStreamDesc, IID_PPV_ARGS(spPSO->GetForCreate()))); } if (!m_spRootSig) { m_spRootSig.reset(new InternalRootSignature(m_pParent)); // throw( bad_alloc ) m_spRootSig->Create(g_PSBasic, sizeof(g_PSBasic)); // throw( _com_error ) } return spPSO.get(); } void BlitHelper::Blit(Resource* pSrc, UINT SrcSubresourceIdx, const RECT& SrcRect, Resource* pDst, UINT DstSubresourceIdx, const RECT& DstRect, bool bEnableAlpha, bool bSwapRBChannels) { UINT SrcPlaneCount = pSrc->AppDesc()->NonOpaquePlaneCount(); UINT DstPlaneCount = pDst->AppDesc()->NonOpaquePlaneCount(); UINT SrcSubresourceIndices[MAX_PLANES]; UINT DstSubresourceIndices[MAX_PLANES]; auto FillIndices = [](Resource* pResource, UINT SubresourceIdx, UINT PlaneCount, UINT* pIndices) { UINT MipLevel, ArraySlice, PlaneIdx; pResource->DecomposeSubresource(SubresourceIdx, MipLevel, ArraySlice, PlaneIdx); assert(PlaneIdx == 0); for (UINT i = 0; i < PlaneCount; ++i) { pIndices[i] = pResource->GetSubresourceIndex(i, MipLevel, ArraySlice); } }; FillIndices(pSrc, SrcSubresourceIdx, SrcPlaneCount, SrcSubresourceIndices); FillIndices(pDst, DstSubresourceIdx, DstPlaneCount, DstSubresourceIndices); Blit(pSrc, SrcSubresourceIndices, SrcPlaneCount, SrcRect, pDst, DstSubresourceIndices, DstPlaneCount, DstRect, bEnableAlpha, bSwapRBChannels); } void BlitHelper::Blit(Resource *pSrc, UINT *pSrcSubresourceIndices, UINT numSrcSubresources, const RECT& srcRect, Resource *pDst, UINT *pDstSubresourceIndices, UINT numDstSubresources, const RECT& dstRect, bool bEnableAlpha, bool bSwapRBChannels) { const D3D12_RESOURCE_DESC &dstDesc = pDst->GetUnderlyingResource()->GetDesc(); BlitPipelineState* pPSO = PrepareShaders(pSrc, numSrcSubresources, pDst, numDstSubresources, bEnableAlpha, bSwapRBChannels); m_pParent->PreRender(COMMAND_LIST_TYPE::GRAPHICS); // // setup the RTV // bool needsTempRenderTarget = (dstDesc.Flags & D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET) == D3D12_RESOURCE_FLAG_NONE; bool needsTwoPassColorConvert = (bSwapRBChannels && CD3D11FormatHelper::YUV(pSrc->AppDesc()->Format())); auto pNewDestinationResource = pDst; RTV* pRTV = nullptr; std::optional<RTV> LocalRTV; ResourceCacheEntry OwnedCacheEntry; if (needsTempRenderTarget || needsTwoPassColorConvert) { auto& CacheEntry = m_pParent->GetResourceCache().GetResource(pDst->AppDesc()->Format(), RectWidth(dstRect), RectHeight(dstRect)); pNewDestinationResource = CacheEntry.m_Resource.get(); pRTV = CacheEntry.m_RTV.get(); if (needsTempRenderTarget && needsTwoPassColorConvert) { // If we're doing both of these, then our two-pass approach is going to turn into // a three-pass approach (first color convert to a cache entry, then swap RB channels // into another cache entry, then copy to the non-renderable destination). // In this case, passes one and two will both try to render to the cache entry, // with pass two trying to simultaneously read AND write from the cache entry. // // To prevent this, take ownership of the cache entry during pass one, so that pass two // allocates a new resource. The resource from pass one will then be destroyed rather than // being cached... but this seems okay since this should be *very* uncommon m_pParent->GetResourceCache().TakeCacheEntryOwnership(pDst->AppDesc()->Format(), OwnedCacheEntry); } } else { UINT subresource = pDstSubresourceIndices[0]; UINT8 DstPlane = 0, DstMip = 0; UINT16 DstArraySlice = 0; D3D12DecomposeSubresource(subresource, pDst->AppDesc()->MipLevels(), pDst->AppDesc()->ArraySize(), DstMip, DstArraySlice, DstPlane); D3D12_RENDER_TARGET_VIEW_DESC RTVDesc = {}; RTVDesc.Format = dstDesc.Format; if (pDst->AppDesc()->Samples() > 1) { RTVDesc.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE2DMSARRAY; RTVDesc.Texture2DMSArray.ArraySize = 1; RTVDesc.Texture2DMSArray.FirstArraySlice = DstArraySlice; } else { RTVDesc.ViewDimension = D3D12_RTV_DIMENSION_TEXTURE2DARRAY; RTVDesc.Texture2DArray.MipSlice = DstMip; RTVDesc.Texture2DArray.PlaneSlice = DstPlane; RTVDesc.Texture2DArray.ArraySize = 1; RTVDesc.Texture2DArray.FirstArraySlice = DstArraySlice; } LocalRTV.emplace(m_pParent, RTVDesc, *pDst); pRTV = &LocalRTV.value(); } // // Transition the src & dst resources // { assert(numSrcSubresources <= MAX_PLANES); for (UINT i = 0; i < numSrcSubresources; i++) { UINT subresourceIndex = pSrcSubresourceIndices[i]; m_pParent->GetResourceStateManager().TransitionSubresource(pSrc, subresourceIndex, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE); } assert(numDstSubresources == 1); // for now, just packed output for (UINT i = 0; i < numDstSubresources; i++) { UINT subresourceIndex = needsTempRenderTarget ? 0 : pDstSubresourceIndices[i]; m_pParent->GetResourceStateManager().TransitionSubresource(pNewDestinationResource, subresourceIndex, D3D12_RESOURCE_STATE_RENDER_TARGET); } m_pParent->GetResourceStateManager().ApplyAllResourceTransitions(); } // No predication in DX9 ImmediateContext::CDisablePredication DisablePredication(m_pParent); UINT SRVBaseSlot = m_pParent->ReserveSlots(m_pParent->m_ViewHeap, MAX_PLANES); ID3D12GraphicsCommandList* pCommandList = m_pParent->GetGraphicsCommandList(); pCommandList->SetGraphicsRootSignature(m_spRootSig->GetRootSignature()); pCommandList->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP); { // Unbind all VBs D3D12_VERTEX_BUFFER_VIEW VBVArray[D3D11_IA_VERTEX_INPUT_RESOURCE_SLOT_COUNT]; memset(VBVArray, 0, sizeof(VBVArray)); pCommandList->IASetVertexBuffers(0, D3D11_IA_VERTEX_INPUT_RESOURCE_SLOT_COUNT, VBVArray); } // // set up the SRVs // for (UINT i = 0; i < numSrcSubresources; i++) { UINT subresource = pSrcSubresourceIndices[i]; UINT8 SrcPlane = 0, SrcMip = 0; UINT16 SrcArraySlice = 0; D3D12DecomposeSubresource(subresource, pSrc->AppDesc()->MipLevels(), pSrc->AppDesc()->ArraySize(), SrcMip, SrcArraySlice, SrcPlane); auto& SrcFootprint = pSrc->GetSubresourcePlacement(subresource).Footprint; DXGI_FORMAT ViewFormat = SrcFootprint.Format; switch (ViewFormat) { case DXGI_FORMAT_R8_TYPELESS: ViewFormat = DXGI_FORMAT_R8_UNORM; break; case DXGI_FORMAT_R8G8_TYPELESS: ViewFormat = DXGI_FORMAT_R8G8_UNORM; break; case DXGI_FORMAT_R16_TYPELESS: ViewFormat = DXGI_FORMAT_R16_UNORM; break; case DXGI_FORMAT_R16G16_TYPELESS: ViewFormat = DXGI_FORMAT_R16G16_UNORM; break; case DXGI_FORMAT_AYUV: // 8bpc case DXGI_FORMAT_YUY2: // 8bpc ViewFormat = DXGI_FORMAT_R8G8B8A8_UNORM; break; case DXGI_FORMAT_Y410: // 10bpc except 2 bit alpha ViewFormat = DXGI_FORMAT_R10G10B10A2_UNORM; break; case DXGI_FORMAT_Y416: // 16bpc case DXGI_FORMAT_Y210: // 10bpc for all 4 channels case DXGI_FORMAT_Y216: // 16bpc ViewFormat = DXGI_FORMAT_R16G16B16A16_UNORM; break; } D3D12_SHADER_RESOURCE_VIEW_DESC SRVDesc = {}; SRVDesc.Format = ViewFormat; SRVDesc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; if (pSrc->AppDesc()->Samples() > 1) { SRVDesc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2DMSARRAY; SRVDesc.Texture2DMSArray.ArraySize = 1; SRVDesc.Texture2DMSArray.FirstArraySlice = SrcArraySlice; } else { SRVDesc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2DARRAY; SRVDesc.Texture2DArray.MipLevels = 1; SRVDesc.Texture2DArray.MostDetailedMip = SrcMip; SRVDesc.Texture2DArray.PlaneSlice = SrcPlane; SRVDesc.Texture2DArray.ArraySize = 1; SRVDesc.Texture2DArray.FirstArraySlice = SrcArraySlice; SRVDesc.Texture2DArray.ResourceMinLODClamp = 0.0f; } D3D12_CPU_DESCRIPTOR_HANDLE SRVBaseCPU = m_pParent->m_ViewHeap.CPUHandle(SRVBaseSlot + i); m_pParent->m_pDevice12->CreateShaderResourceView(pSrc->GetUnderlyingResource(), &SRVDesc, SRVBaseCPU); } for (UINT i = numSrcSubresources; i < MAX_PLANES; ++i) { D3D12_CPU_DESCRIPTOR_HANDLE SRVBaseCPU = m_pParent->m_ViewHeap.CPUHandle(SRVBaseSlot + i); m_pParent->m_pDevice12->CopyDescriptorsSimple(1, SRVBaseCPU, m_pParent->m_NullSRVs[(UINT)RESOURCE_DIMENSION::TEXTURE2DARRAY], D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); } D3D12_GPU_DESCRIPTOR_HANDLE SRVBaseGPU = m_pParent->m_ViewHeap.GPUHandle(SRVBaseSlot); pCommandList->SetGraphicsRootDescriptorTable(0, SRVBaseGPU); pCommandList->OMSetRenderTargets(1, &pRTV->m_Descriptor, TRUE, nullptr); // Constant buffers: srcRect, src dimensions { UINT subresourceIndex = pSrcSubresourceIndices[0]; auto& srcSubresourceFootprint = pSrc->GetSubresourcePlacement(subresourceIndex).Footprint; int srcPositions[6] = { srcRect.left, srcRect.right, srcRect.top, srcRect.bottom, (int)srcSubresourceFootprint.Width, (int)srcSubresourceFootprint.Height }; pCommandList->SetGraphicsRoot32BitConstants(1, _countof(srcPositions), &srcPositions[0], 0); } pCommandList->SetPipelineState(pPSO->GetForUse(COMMAND_LIST_TYPE::GRAPHICS)); CD3DX12_VIEWPORT Viewport((FLOAT)dstRect.left, (FLOAT)dstRect.top, (FLOAT)RectWidth(dstRect), (FLOAT)RectHeight(dstRect)); CD3DX12_RECT Scissor(dstRect); pCommandList->RSSetViewports(1, &Viewport); pCommandList->RSSetScissorRects(1, &Scissor); pCommandList->DrawInstanced(4, 1, 0, 0); if (needsTwoPassColorConvert) { UINT srcSubresourceIndex = 0; Blit(pNewDestinationResource, &srcSubresourceIndex, 1, dstRect, pDst, pDstSubresourceIndices, numDstSubresources, dstRect, bEnableAlpha, bSwapRBChannels); } else if (needsTempRenderTarget) { D3D12_BOX srcBox = { 0, 0, 0, RectWidth(dstRect), RectHeight(dstRect), 1 }; m_pParent->ResourceCopyRegion( pDst, pDstSubresourceIndices[0], dstRect.left, dstRect.top, 0, pNewDestinationResource, 0, &srcBox); } m_pParent->PostRender(COMMAND_LIST_TYPE::GRAPHICS, e_GraphicsStateDirty); } }
46.591029
251
0.606864
procedural
884facaedb3cf7bdc62e614a139892e1e9798e22
1,535
cpp
C++
22_computational_geo/4_coder_rating.cpp
meyash/dust
8f90d7f9cc42f61193c737cde14e9c4bb32884b4
[ "MIT" ]
1
2020-09-30T10:36:06.000Z
2020-09-30T10:36:06.000Z
22_computational_geo/4_coder_rating.cpp
meyash/dust
8f90d7f9cc42f61193c737cde14e9c4bb32884b4
[ "MIT" ]
null
null
null
22_computational_geo/4_coder_rating.cpp
meyash/dust
8f90d7f9cc42f61193c737cde14e9c4bb32884b4
[ "MIT" ]
null
null
null
#include<bits/stdc++.h> using namespace std; // each index of BIT will shows that patrical index coder is good than how many coders // sample input // 8 // 1798 1832 // 862 700 // 1075 1089 // 1568 1557 // 2575 1984 // 1033 950 // 1656 1649 // 1014 1473 class coder{ public: int x,y,index; }; int BIT[100001]; //each index contains no of coders smaller int level than that coder void update(int y){ for(;y<=10000;y+=y&(-y)){ BIT[y]++; } } int query(int y){ int val=0; for(;y>0;y-=y&(-y)){ val+=BIT[y]; } return val; } bool operator <(coder A,coder B){ if(A.x==B.x){ return A.y<B.y; } return A.x<B.x; } int main(){ int n; cin>>n; coder arr[n]; for(int i=0;i<n;i++){ cin>>arr[i].x>>arr[i].y; arr[i].index=i; } sort(arr,arr+n); // this fn will use the overloaded operator automatically int ans[n]; for(int i=0;i<n;){ int endindex=i; //this is for case if two or more coders have same x and y // so we need to update this for every same level code simultainously while(endindex<n&&arr[endindex].x==arr[i].x&&arr[endindex].y==arr[i].y){ endindex++; } for(int j=i;j<endindex;j++){ // query ans[arr[j].index]=query(arr[j].y); } for(int j=i;j<endindex;j++){ // update update(arr[j].y); } i=endindex; } for(int i=0;i<n;i++){ cout<<ans[i]<<endl; } }
18.950617
86
0.521824
meyash
9c00f683884cd05dbf09625e898224748f1acf01
2,496
hpp
C++
RIT_Library/src/include/heap/FibonacciHeap.hpp
PWrGitHub194238/RIT
74ae41ce8cfdca3f14fc1e9a36840c68dff42b23
[ "Apache-2.0" ]
null
null
null
RIT_Library/src/include/heap/FibonacciHeap.hpp
PWrGitHub194238/RIT
74ae41ce8cfdca3f14fc1e9a36840c68dff42b23
[ "Apache-2.0" ]
1
2016-02-14T18:27:05.000Z
2016-03-15T17:32:11.000Z
BinaryIMST_Library/src/include/heap/FibonacciHeap.hpp
PWrGitHub194238/BinaryIMST
53490c10580fd4ad61c9234b82b3140c5cce5de0
[ "Apache-2.0" ]
null
null
null
/* * FibonacciHeap.hpp * * Created on: 9 sty 2016 * Author: tomasz */ #ifndef SRC_INCLUDE_HEAP_FIBONACCIHEAP_HPP_ #define SRC_INCLUDE_HEAP_FIBONACCIHEAP_HPP_ #include <boost/heap/fibonacci_heap.hpp> #include <boost/heap/policies.hpp> #include <map> #include "../typedefs/primitive.hpp" #include "VertexHeapIF.hpp" #include "VertexHeapItem.hpp" struct compare_node { bool operator()(VertexHeapItem * const & vertexU, VertexHeapItem * const & vertexV) const { return vertexU->getKey() > vertexV->getKey(); } }; class FibonacciHeap: public VertexHeapIF { private: //************************************ PRIVATE CONSTANT FIELDS *************************************// //************************************** PRIVATE CLASS FIELDS **************************************// boost::heap::fibonacci_heap<VertexHeapItem *, boost::heap::compare<compare_node>> heap; std::map<VertexIdx, boost::heap::fibonacci_heap<VertexHeapItem *, boost::heap::compare<compare_node>>::handle_type> heapMap; //*************************************** PRIVATE FUNCTIONS ****************************************// protected: //*********************************** PROTECTED CONSTANT FIELDS ************************************// //************************************ PROTECTED CLASS FIELDS **************************************// //************************************** PROTECTED FUNCTIONS ***************************************// public: //************************************* PUBLIC CONSTANT FIELDS *************************************// //************************************** PUBLIC CLASS FIELDS ***************************************// //************************************ CONSTRUCTOR & DESTRUCTOR ************************************// FibonacciHeap(); virtual ~FibonacciHeap(); //*************************************** PUBLIC FUNCTIONS *****************************************// VertexCount size() const; void push(VertexHeapItem * const vertex); VertexIF * pop(); VertexHeapItem * peek(); void increaseKey(VertexHeapItem * heapItem, VertexKey newKey); void decreaseKey(VertexHeapItem * heapItem, VertexKey newKey); VertexHeapItem * getItem(VertexIdx const vertexId); bool isVertexInsideHeap(VertexIF * const vertex); bool isVertexInsideHeap(VertexIdx const vertexId); //*************************************** GETTERS & SETTERS ****************************************// }; #endif /* SRC_INCLUDE_HEAP_FIBONACCIHEAP_HPP_ */
29.023256
103
0.482372
PWrGitHub194238
9c03bddc7b32e38d06e2c49651eff7663e3e9c8b
22,911
cpp
C++
src/Etterna/Models/NoteLoaders/NotesLoaderDWI.cpp
thenerdie/etterna
341b7c506c785e3a15e7af18814791aefff5c958
[ "MIT" ]
null
null
null
src/Etterna/Models/NoteLoaders/NotesLoaderDWI.cpp
thenerdie/etterna
341b7c506c785e3a15e7af18814791aefff5c958
[ "MIT" ]
null
null
null
src/Etterna/Models/NoteLoaders/NotesLoaderDWI.cpp
thenerdie/etterna
341b7c506c785e3a15e7af18814791aefff5c958
[ "MIT" ]
null
null
null
#include "Etterna/Globals/global.h" #include "Etterna/Models/Misc/Difficulty.h" #include "Etterna/Models/Misc/GameInput.h" #include "Etterna/FileTypes/MsdFile.h" #include "Etterna/Models/NoteData/NoteData.h" #include "NotesLoader.h" #include "NotesLoaderDWI.h" #include "Etterna/Singletons/PrefsManager.h" #include "RageUtil/Misc/RageLog.h" #include "RageUtil/Utils/RageUtil.h" #include "RageUtil/Utils/RageUtil_CharConversions.h" #include "Etterna/Models/Songs/Song.h" #include "Etterna/Models/StepsAndStyles/Steps.h" #include <map> Difficulty DwiCompatibleStringToDifficulty(const RString& sDC); /** @brief The different types of core DWI arrows and pads. */ enum DanceNotes { DANCE_NOTE_NONE = 0, DANCE_NOTE_PAD1_LEFT, DANCE_NOTE_PAD1_UPLEFT, DANCE_NOTE_PAD1_DOWN, DANCE_NOTE_PAD1_UP, DANCE_NOTE_PAD1_UPRIGHT, DANCE_NOTE_PAD1_RIGHT, DANCE_NOTE_PAD2_LEFT, DANCE_NOTE_PAD2_UPLEFT, DANCE_NOTE_PAD2_DOWN, DANCE_NOTE_PAD2_UP, DANCE_NOTE_PAD2_UPRIGHT, DANCE_NOTE_PAD2_RIGHT }; /** * @brief Turn the individual character to the proper note. * @param c The character in question. * @param i The player. * @param note1Out The first result based on the character. * @param note2Out The second result based on the character. * @param sPath the path to the file. */ static void DWIcharToNote(char c, GameController i, int& note1Out, int& note2Out, const RString& sPath) { switch (c) { case '0': note1Out = DANCE_NOTE_NONE; note2Out = DANCE_NOTE_NONE; break; case '1': note1Out = DANCE_NOTE_PAD1_DOWN; note2Out = DANCE_NOTE_PAD1_LEFT; break; case '2': note1Out = DANCE_NOTE_PAD1_DOWN; note2Out = DANCE_NOTE_NONE; break; case '3': note1Out = DANCE_NOTE_PAD1_DOWN; note2Out = DANCE_NOTE_PAD1_RIGHT; break; case '4': note1Out = DANCE_NOTE_PAD1_LEFT; note2Out = DANCE_NOTE_NONE; break; case '5': note1Out = DANCE_NOTE_NONE; note2Out = DANCE_NOTE_NONE; break; case '6': note1Out = DANCE_NOTE_PAD1_RIGHT; note2Out = DANCE_NOTE_NONE; break; case '7': note1Out = DANCE_NOTE_PAD1_UP; note2Out = DANCE_NOTE_PAD1_LEFT; break; case '8': note1Out = DANCE_NOTE_PAD1_UP; note2Out = DANCE_NOTE_NONE; break; case '9': note1Out = DANCE_NOTE_PAD1_UP; note2Out = DANCE_NOTE_PAD1_RIGHT; break; case 'A': note1Out = DANCE_NOTE_PAD1_UP; note2Out = DANCE_NOTE_PAD1_DOWN; break; case 'B': note1Out = DANCE_NOTE_PAD1_LEFT; note2Out = DANCE_NOTE_PAD1_RIGHT; break; case 'C': note1Out = DANCE_NOTE_PAD1_UPLEFT; note2Out = DANCE_NOTE_NONE; break; case 'D': note1Out = DANCE_NOTE_PAD1_UPRIGHT; note2Out = DANCE_NOTE_NONE; break; case 'E': note1Out = DANCE_NOTE_PAD1_LEFT; note2Out = DANCE_NOTE_PAD1_UPLEFT; break; case 'F': note1Out = DANCE_NOTE_PAD1_UPLEFT; note2Out = DANCE_NOTE_PAD1_DOWN; break; case 'G': note1Out = DANCE_NOTE_PAD1_UPLEFT; note2Out = DANCE_NOTE_PAD1_UP; break; case 'H': note1Out = DANCE_NOTE_PAD1_UPLEFT; note2Out = DANCE_NOTE_PAD1_RIGHT; break; case 'I': note1Out = DANCE_NOTE_PAD1_LEFT; note2Out = DANCE_NOTE_PAD1_UPRIGHT; break; case 'J': note1Out = DANCE_NOTE_PAD1_DOWN; note2Out = DANCE_NOTE_PAD1_UPRIGHT; break; case 'K': note1Out = DANCE_NOTE_PAD1_UP; note2Out = DANCE_NOTE_PAD1_UPRIGHT; break; case 'L': note1Out = DANCE_NOTE_PAD1_UPRIGHT; note2Out = DANCE_NOTE_PAD1_RIGHT; break; case 'M': note1Out = DANCE_NOTE_PAD1_UPLEFT; note2Out = DANCE_NOTE_PAD1_UPRIGHT; break; default: LOG->UserLog( "Song file", sPath, "has an invalid DWI note character '%c'.", c); note1Out = DANCE_NOTE_NONE; note2Out = DANCE_NOTE_NONE; break; } switch (i) { case GameController_1: break; case GameController_2: if (note1Out != DANCE_NOTE_NONE) note1Out += 6; if (note2Out != DANCE_NOTE_NONE) note2Out += 6; break; default: FAIL_M(ssprintf("Invalid GameController: %i", i)); } } /** * @brief Determine the note column[s] to place notes. * @param c The character in question. * @param i The player. * @param col1Out The first result based on the character. * @param col2Out The second result based on the character. * @param sPath the path to the file. * @param mapDanceNoteToColumn a map to pass to keep track of column info. */ static void DWIcharToNoteCol(char c, GameController i, int& col1Out, int& col2Out, const RString& sPath, map<int, int>& mapDanceNoteToColumn) { int note1, note2; DWIcharToNote(c, i, note1, note2, sPath); if (note1 != DANCE_NOTE_NONE) col1Out = mapDanceNoteToColumn[note1]; else col1Out = -1; if (note2 != DANCE_NOTE_NONE) col2Out = mapDanceNoteToColumn[note2]; else col2Out = -1; } /** * @brief Determine if the note in question is a 192nd note. * * DWI used to use <...> to indicate 1/192nd notes; at some * point, <...> was changed to indicate jumps, and `' was used for * 1/192nds. So, we have to do a check to figure out what it really * means. If it contains 0s, it's most likely 192nds; otherwise, * it's most likely a jump. Search for a 0 before the next >: * @param sStepData the step data. * @param pos the position of the step data. * @return true if it's a 192nd note, false otherwise. */ static bool Is192(const RString& sStepData, size_t pos) { while (pos < sStepData.size()) { if (sStepData[pos] == '>') return false; if (sStepData[pos] == '0') return true; ++pos; } return false; } /** @brief All DWI files use 4 beats per measure. */ const int BEATS_PER_MEASURE = 4; /* We prefer the normal names; recognize a number of others, too. (They'll get * normalized when written to SMs, etc.) */ Difficulty DwiCompatibleStringToDifficulty(const RString& sDC) { RString s2 = sDC; s2.MakeLower(); if (s2 == "beginner") return Difficulty_Beginner; if (s2 == "easy") return Difficulty_Easy; if (s2 == "basic") return Difficulty_Easy; else if (s2 == "light") return Difficulty_Easy; else if (s2 == "medium") return Difficulty_Medium; else if (s2 == "another") return Difficulty_Medium; else if (s2 == "trick") return Difficulty_Medium; else if (s2 == "standard") return Difficulty_Medium; else if (s2 == "difficult") return Difficulty_Medium; else if (s2 == "hard") return Difficulty_Hard; else if (s2 == "ssr") return Difficulty_Hard; else if (s2 == "maniac") return Difficulty_Hard; else if (s2 == "heavy") return Difficulty_Hard; else if (s2 == "smaniac") return Difficulty_Challenge; else if (s2 == "challenge") return Difficulty_Challenge; else if (s2 == "expert") return Difficulty_Challenge; else if (s2 == "oni") return Difficulty_Challenge; else if (s2 == "edit") return Difficulty_Edit; else return Difficulty_Invalid; } static StepsType GetTypeFromMode(const RString& mode) { if (mode == "SINGLE") return StepsType_dance_single; if (mode == "DOUBLE") return StepsType_dance_double; else if (mode == "SOLO") return StepsType_dance_solo; return StepsType_Invalid; // just in case. } static NoteData ParseNoteData(RString& step1, RString& step2, Steps& out, const RString& path) { std::map<int, int> g_mapDanceNoteToNoteDataColumn; switch (out.m_StepsType) { case StepsType_dance_single: g_mapDanceNoteToNoteDataColumn[DANCE_NOTE_PAD1_LEFT] = 0; g_mapDanceNoteToNoteDataColumn[DANCE_NOTE_PAD1_DOWN] = 1; g_mapDanceNoteToNoteDataColumn[DANCE_NOTE_PAD1_UP] = 2; g_mapDanceNoteToNoteDataColumn[DANCE_NOTE_PAD1_RIGHT] = 3; break; case StepsType_dance_double: g_mapDanceNoteToNoteDataColumn[DANCE_NOTE_PAD1_LEFT] = 0; g_mapDanceNoteToNoteDataColumn[DANCE_NOTE_PAD1_DOWN] = 1; g_mapDanceNoteToNoteDataColumn[DANCE_NOTE_PAD1_UP] = 2; g_mapDanceNoteToNoteDataColumn[DANCE_NOTE_PAD1_RIGHT] = 3; g_mapDanceNoteToNoteDataColumn[DANCE_NOTE_PAD2_LEFT] = 4; g_mapDanceNoteToNoteDataColumn[DANCE_NOTE_PAD2_DOWN] = 5; g_mapDanceNoteToNoteDataColumn[DANCE_NOTE_PAD2_UP] = 6; g_mapDanceNoteToNoteDataColumn[DANCE_NOTE_PAD2_RIGHT] = 7; break; case StepsType_dance_solo: g_mapDanceNoteToNoteDataColumn[DANCE_NOTE_PAD1_LEFT] = 0; g_mapDanceNoteToNoteDataColumn[DANCE_NOTE_PAD1_UPLEFT] = 1; g_mapDanceNoteToNoteDataColumn[DANCE_NOTE_PAD1_DOWN] = 2; g_mapDanceNoteToNoteDataColumn[DANCE_NOTE_PAD1_UP] = 3; g_mapDanceNoteToNoteDataColumn[DANCE_NOTE_PAD1_UPRIGHT] = 4; g_mapDanceNoteToNoteDataColumn[DANCE_NOTE_PAD1_RIGHT] = 5; break; DEFAULT_FAIL(out.m_StepsType); } NoteData newNoteData; newNoteData.SetNumTracks(g_mapDanceNoteToNoteDataColumn.size()); for (int pad = 0; pad < 2; pad++) // foreach pad { RString sStepData; switch (pad) { case 0: sStepData = step1; break; case 1: if (step2 == "") // no data continue; // skip sStepData = step2; break; DEFAULT_FAIL(pad); } sStepData.Replace("\n", ""); sStepData.Replace("\r", ""); sStepData.Replace("\t", ""); sStepData.Replace(" ", ""); double fCurrentBeat = 0; double fCurrentIncrementer = 1.0 / 8 * BEATS_PER_MEASURE; for (size_t i = 0; i < sStepData.size();) { char c = sStepData[i++]; switch (c) { // begins a series case '(': fCurrentIncrementer = 1.0 / 16 * BEATS_PER_MEASURE; break; case '[': fCurrentIncrementer = 1.0 / 24 * BEATS_PER_MEASURE; break; case '{': fCurrentIncrementer = 1.0 / 64 * BEATS_PER_MEASURE; break; case '`': fCurrentIncrementer = 1.0 / 192 * BEATS_PER_MEASURE; break; // ends a series case ')': case ']': case '}': case '\'': case '>': fCurrentIncrementer = 1.0 / 8 * BEATS_PER_MEASURE; break; default : // this is a note character { if (c == '!') { LOG->UserLog("Song file", path, "has an unexpected character: '!'."); continue; } bool jump = false; if (c == '<') { /* Arr. Is this a jump or a 1/192 marker? */ if (Is192(sStepData, i)) { fCurrentIncrementer = 1.0 / 192 * BEATS_PER_MEASURE; break; } /* It's a jump. * We need to keep reading notes until we hit a >. */ jump = true; i++; } const int iIndex = BeatToNoteRow(static_cast<float>(fCurrentBeat)); i--; do { c = sStepData[i++]; if (jump && c == '>') break; int iCol1, iCol2; DWIcharToNoteCol(c, (GameController)pad, iCol1, iCol2, path, g_mapDanceNoteToNoteDataColumn); if (iCol1 != -1) newNoteData.SetTapNote( iCol1, iIndex, TAP_ORIGINAL_TAP); if (iCol2 != -1) newNoteData.SetTapNote( iCol2, iIndex, TAP_ORIGINAL_TAP); if (i >= sStepData.length()) { break; // we ran out of data // while looking for the ending > mark } if (sStepData[i] == '!') { i++; const char holdChar = sStepData[i++]; DWIcharToNoteCol(holdChar, (GameController)pad, iCol1, iCol2, path, g_mapDanceNoteToNoteDataColumn); if (iCol1 != -1) newNoteData.SetTapNote( iCol1, iIndex, TAP_ORIGINAL_HOLD_HEAD); if (iCol2 != -1) newNoteData.SetTapNote( iCol2, iIndex, TAP_ORIGINAL_HOLD_HEAD); } } while (jump); fCurrentBeat += fCurrentIncrementer; } break; } } } /* Fill in iDuration. */ for (int t = 0; t < newNoteData.GetNumTracks(); ++t) { FOREACH_NONEMPTY_ROW_IN_TRACK(newNoteData, t, iHeadRow) { TapNote tn = newNoteData.GetTapNote(t, iHeadRow); if (tn.type != TapNoteType_HoldHead) continue; int iTailRow = iHeadRow; bool bFound = false; while (!bFound && newNoteData.GetNextTapNoteRowForTrack(t, iTailRow)) { const TapNote& TailTap = newNoteData.GetTapNote(t, iTailRow); if (TailTap.type == TapNoteType_Empty) continue; newNoteData.SetTapNote(t, iTailRow, TAP_EMPTY); tn.iDuration = iTailRow - iHeadRow; newNoteData.SetTapNote(t, iHeadRow, tn); bFound = true; } if (!bFound) { /* The hold was never closed. */ LOG->UserLog( "Song file", path, "failed to close a hold note in \"%s\" on track %i", DifficultyToString(out.GetDifficulty()).c_str(), t); newNoteData.SetTapNote(t, iHeadRow, TAP_EMPTY); } } } ASSERT(newNoteData.GetNumTracks() > 0); return newNoteData; } /** * @brief Look through the notes tag to extract the data. * @param sMode the steps type. * @param sDescription the difficulty. * @param sNumFeet the meter. * @param sStepData1 the guaranteed step data. * @param sStepData2 used if sMode is double or couple. * @param out the step data. * @param sPath the path to the file. * @return the success or failure of the operation. */ static bool LoadFromDWITokens(RString sMode, RString sDescription, RString sNumFeet, RString sStepData1, RString sStepData2, Steps& out, const RString& sPath) { CHECKPOINT_M("DWILoader::LoadFromDWITokens()"); out.m_StepsType = GetTypeFromMode(sMode); if (out.m_StepsType == StepsType_Invalid) return false; // if the meter is empty, force it to 1. if (sNumFeet.empty()) sNumFeet = "1"; out.SetMeter(StringToInt(sNumFeet)); out.SetDifficulty(DwiCompatibleStringToDifficulty(sDescription)); out.SetNoteData(ParseNoteData(sStepData1, sStepData2, out, sPath)); out.TidyUpData(); out.SetSavedToDisk( true); // we're loading from disk, so this is by definintion already saved return true; } /** * @brief Turn the DWI style timestamp into a compatible time for our system. * * This value can be in either "HH:MM:SS.sssss", "MM:SS.sssss", "SSS.sssss" * or milliseconds. * @param arg1 Either hours, minutes, or seconds, depending on other args. * @param arg2 Either minutes or seconds, depending on other args. * @param arg3 Seconds if not empty. * @return the proper timestamp. */ static float ParseBrokenDWITimestamp(const RString& arg1, const RString& arg2, const RString& arg3) { if (arg1.empty()) return 0; /* 1+ args */ if (arg2.empty()) { /* If the value contains a period, treat it as seconds; otherwise ms. */ if (arg1.find_first_of(".") != arg1.npos) return StringToFloat(arg1); return StringToFloat(arg1) / 1000.f; } /* 2+ args */ if (arg3.empty()) return HHMMSSToSeconds(arg1 + ":" + arg2); /* 3+ args */ return HHMMSSToSeconds(arg1 + ":" + arg2 + ":" + arg3); } void DWILoader::GetApplicableFiles(const RString& sPath, vector<RString>& out) { GetDirListing(sPath + RString("*.dwi"), out); } bool DWILoader::LoadNoteDataFromSimfile(const RString& path, Steps& out) { MsdFile msd; if (!msd.ReadFile(path, false)) // don't unescape { LOG->UserLog( "Song file", path, "couldn't be opened: %s", msd.GetError().c_str()); return false; } for (unsigned i = 0; i < msd.GetNumValues(); i++) { int iNumParams = msd.GetNumParams(i); const MsdFile::value_t& params = msd.GetValue(i); RString valueName = params[0]; if (valueName.EqualsNoCase("SINGLE") || valueName.EqualsNoCase("DOUBLE") || valueName.EqualsNoCase("COUPLE") || valueName.EqualsNoCase("SOLO")) { if (out.m_StepsType != GetTypeFromMode(valueName)) continue; if (out.GetDifficulty() != DwiCompatibleStringToDifficulty(params[1]) && out.GetDescription().find( DifficultyToString( DwiCompatibleStringToDifficulty(params[1])) + " Edit") == RString::npos) continue; if (out.GetMeter() != StringToInt(params[2])) continue; RString step1 = params[3]; RString step2 = (iNumParams == 5) ? params[4] : RString(""); out.SetNoteData(ParseNoteData(step1, step2, out, path)); return true; } } return false; } bool DWILoader::LoadFromDir(const RString& sPath_, Song& out, set<RString>& BlacklistedImages) { vector<RString> aFileNames; GetApplicableFiles(sPath_, aFileNames); if (aFileNames.size() > 1) { LOG->UserLog("Song", sPath_, "has more than one DWI file. There should be only one!"); return false; } /* We should have exactly one; if we had none, we shouldn't have been called * to begin with. */ ASSERT(aFileNames.size() == 1); const RString sPath = sPath_ + aFileNames[0]; LOG->Trace("Song::LoadFromDWIFile(%s)", sPath.c_str()); MsdFile msd; if (!msd.ReadFile(sPath, false)) // don't unescape { LOG->UserLog( "Song file", sPath, "couldn't be opened: %s", msd.GetError().c_str()); return false; } out.m_sSongFileName = sPath; for (unsigned i = 0; i < msd.GetNumValues(); i++) { int iNumParams = msd.GetNumParams(i); const MsdFile::value_t& sParams = msd.GetValue(i); RString sValueName = sParams[0]; if (iNumParams < 1) { LOG->UserLog("Song file", sPath, "has tag \"%s\" with no parameters.", sValueName.c_str()); continue; } // handle the data if (sValueName.EqualsNoCase("FILE")) out.m_sMusicFile = sParams[1]; else if (sValueName.EqualsNoCase("TITLE")) { NotesLoader::GetMainAndSubTitlesFromFullTitle( sParams[1], out.m_sMainTitle, out.m_sSubTitle); /* As far as I know, there's no spec on the encoding of this text. * (I didn't look very hard, though.) I've seen at least one file * in ISO-8859-1. */ ConvertString(out.m_sMainTitle, "utf-8,english"); ConvertString(out.m_sSubTitle, "utf-8,english"); } else if (sValueName.EqualsNoCase("ARTIST")) { out.m_sArtist = sParams[1]; ConvertString(out.m_sArtist, "utf-8,english"); } else if (sValueName.EqualsNoCase("GENRE")) { out.m_sGenre = sParams[1]; ConvertString(out.m_sGenre, "utf-8,english"); } else if (sValueName.EqualsNoCase("CDTITLE")) out.m_sCDTitleFile = sParams[1]; else if (sValueName.EqualsNoCase("BPM")) { const float fBPM = StringToFloat(sParams[1]); if (unlikely(fBPM <= 0.0f)) { LOG->UserLog("Song file", sPath, "has an invalid BPM change at beat %f, BPM %f.", 0.0f, fBPM); } else { out.m_SongTiming.AddSegment(BPMSegment(0, fBPM)); } } else if (sValueName.EqualsNoCase("DISPLAYBPM")) { // #DISPLAYBPM:[xxx..xxx]|[xxx]|[*]; int iMin, iMax; /* We can't parse this as a float with sscanf, since '.' is a valid * character in a float. (We could do it with a regex, but it's not * worth bothering with since we don't display fractional BPM * anyway.) */ if (sscanf(sParams[1], "%i..%i", &iMin, &iMax) == 2) { out.m_DisplayBPMType = DISPLAY_BPM_SPECIFIED; out.m_fSpecifiedBPMMin = static_cast<float>(iMin); out.m_fSpecifiedBPMMax = static_cast<float>(iMax); } else if (sscanf(sParams[1], "%i", &iMin) == 1) { out.m_DisplayBPMType = DISPLAY_BPM_SPECIFIED; out.m_fSpecifiedBPMMin = out.m_fSpecifiedBPMMax = static_cast<float>(iMin); } else { out.m_DisplayBPMType = DISPLAY_BPM_RANDOM; } } else if (sValueName.EqualsNoCase("GAP")) // the units of GAP is 1/1000 second out.m_SongTiming.m_fBeat0OffsetInSeconds = -StringToInt(sParams[1]) / 1000.0f; else if (sValueName.EqualsNoCase("SAMPLESTART")) out.m_fMusicSampleStartSeconds = ParseBrokenDWITimestamp(sParams[1], sParams[2], sParams[3]); else if (sValueName.EqualsNoCase("SAMPLELENGTH")) { float sampleLength = ParseBrokenDWITimestamp(sParams[1], sParams[2], sParams[3]); if (sampleLength > 0 && sampleLength < 1) { // there were multiple versions of this tag allegedly: ensure a // decent length if requested. sampleLength *= 1000; } out.m_fMusicSampleLengthSeconds = sampleLength; } else if (sValueName.EqualsNoCase("FREEZE")) { vector<RString> arrayFreezeExpressions; split(sParams[1], ",", arrayFreezeExpressions); for (unsigned f = 0; f < arrayFreezeExpressions.size(); f++) { vector<RString> arrayFreezeValues; split(arrayFreezeExpressions[f], "=", arrayFreezeValues); if (arrayFreezeValues.size() != 2) { LOG->UserLog("Song file", sPath, "has an invalid FREEZE: '%s'.", arrayFreezeExpressions[f].c_str()); continue; } int iFreezeRow = BeatToNoteRow(StringToFloat(arrayFreezeValues[0]) / 4.0f); float fFreezeSeconds = StringToFloat(arrayFreezeValues[1]) / 1000.0f; out.m_SongTiming.AddSegment( StopSegment(iFreezeRow, fFreezeSeconds)); // LOG->Trace( "Adding a freeze segment: beat: %f, // seconds = %f", fFreezeBeat, fFreezeSeconds ); } } else if (sValueName.EqualsNoCase("CHANGEBPM") || sValueName.EqualsNoCase("BPMCHANGE")) { vector<RString> arrayBPMChangeExpressions; split(sParams[1], ",", arrayBPMChangeExpressions); for (unsigned b = 0; b < arrayBPMChangeExpressions.size(); b++) { vector<RString> arrayBPMChangeValues; split(arrayBPMChangeExpressions[b], "=", arrayBPMChangeValues); if (arrayBPMChangeValues.size() != 2) { LOG->UserLog("Song file", sPath, "has an invalid CHANGEBPM: '%s'.", arrayBPMChangeExpressions[b].c_str()); continue; } int iStartIndex = BeatToNoteRow(StringToFloat(arrayBPMChangeValues[0]) / 4.0f); float fBPM = StringToFloat(arrayBPMChangeValues[1]); if (fBPM > 0.0f) out.m_SongTiming.AddSegment(BPMSegment(iStartIndex, fBPM)); else LOG->UserLog( "Song file", sPath, "has an invalid BPM change at beat %f, BPM %f.", NoteRowToBeat(iStartIndex), fBPM); } } else if (sValueName.EqualsNoCase("SINGLE") || sValueName.EqualsNoCase("DOUBLE") || sValueName.EqualsNoCase("COUPLE") || sValueName.EqualsNoCase("SOLO")) { Steps* pNewNotes = out.CreateSteps(); LoadFromDWITokens(sParams[0], sParams[1], sParams[2], sParams[3], (iNumParams == 5) ? sParams[4] : RString(""), *pNewNotes, sPath); if (pNewNotes->m_StepsType != StepsType_Invalid) { pNewNotes->SetFilename(sPath); out.AddSteps(pNewNotes); } else delete pNewNotes; } else if (sValueName.EqualsNoCase("DISPLAYTITLE") || sValueName.EqualsNoCase("DISPLAYARTIST")) { /* We don't want to support these tags. However, we don't want * to pick up images used here as song images (eg. banners). */ RString param = sParams[1]; /* "{foo} ... {foo2}" */ size_t pos = 0; while (pos < RString::npos) { size_t startpos = param.find('{', pos); if (startpos == RString::npos) break; size_t endpos = param.find('}', startpos); if (endpos == RString::npos) break; RString sub = param.substr(startpos + 1, endpos - startpos - 1); pos = endpos + 1; sub.MakeLower(); BlacklistedImages.insert(sub); } } else { // do nothing. We don't care about this value name } } return true; }
27.145735
78
0.664877
thenerdie
9c03d41217c99d93107abfa35710e931d917cef6
18,373
hpp
C++
libs/iterator_support/include/hpx/iterator_support/zip_iterator.hpp
folshost/hpx
6b3dc70c4fcade16052cc964790a98522bbfc3ec
[ "BSL-1.0" ]
null
null
null
libs/iterator_support/include/hpx/iterator_support/zip_iterator.hpp
folshost/hpx
6b3dc70c4fcade16052cc964790a98522bbfc3ec
[ "BSL-1.0" ]
null
null
null
libs/iterator_support/include/hpx/iterator_support/zip_iterator.hpp
folshost/hpx
6b3dc70c4fcade16052cc964790a98522bbfc3ec
[ "BSL-1.0" ]
null
null
null
// Copyright (c) 2007-2015 Hartmut Kaiser // Copyright (c) 2014 Agustin Berge // // SPDX-License-Identifier: BSL-1.0 // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #if !defined(HPX_ITERATOR_SUPPORT_ZIP_ITERATOR_MAY_29_2014_0852PM) #define HPX_ITERATOR_SUPPORT_ZIP_ITERATOR_MAY_29_2014_0852PM #include <hpx/config.hpp> #include <hpx/datastructures/detail/pack.hpp> #include <hpx/datastructures/tuple.hpp> #include <hpx/functional/result_of.hpp> #include <hpx/iterator_support/iterator_facade.hpp> #include <hpx/iterator_support/traits/is_iterator.hpp> #include <hpx/serialization/serialization_fwd.hpp> #include <cstddef> #include <iterator> #include <type_traits> #include <utility> namespace hpx { namespace util { namespace detail { /////////////////////////////////////////////////////////////////////// template <typename IteratorTuple> struct zip_iterator_value; template <typename... Ts> struct zip_iterator_value<tuple<Ts...>> { typedef tuple<typename std::iterator_traits<Ts>::value_type...> type; }; /////////////////////////////////////////////////////////////////////// template <typename IteratorTuple> struct zip_iterator_reference; template <typename... Ts> struct zip_iterator_reference<tuple<Ts...>> { typedef tuple<typename std::iterator_traits<Ts>::reference...> type; }; /////////////////////////////////////////////////////////////////////// template <typename T, typename U> struct zip_iterator_category_impl { static_assert(sizeof(T) == 0 && sizeof(U) == 0, "unknown combination of iterator categories"); }; // random_access_iterator_tag template <> struct zip_iterator_category_impl<std::random_access_iterator_tag, std::random_access_iterator_tag> { typedef std::random_access_iterator_tag type; }; template <> struct zip_iterator_category_impl<std::random_access_iterator_tag, std::bidirectional_iterator_tag> { typedef std::bidirectional_iterator_tag type; }; template <> struct zip_iterator_category_impl<std::bidirectional_iterator_tag, std::random_access_iterator_tag> { typedef std::bidirectional_iterator_tag type; }; template <> struct zip_iterator_category_impl<std::random_access_iterator_tag, std::forward_iterator_tag> { typedef std::forward_iterator_tag type; }; template <> struct zip_iterator_category_impl<std::forward_iterator_tag, std::random_access_iterator_tag> { typedef std::forward_iterator_tag type; }; template <> struct zip_iterator_category_impl<std::random_access_iterator_tag, std::input_iterator_tag> { typedef std::input_iterator_tag type; }; template <> struct zip_iterator_category_impl<std::input_iterator_tag, std::random_access_iterator_tag> { typedef std::input_iterator_tag type; }; // bidirectional_iterator_tag template <> struct zip_iterator_category_impl<std::bidirectional_iterator_tag, std::bidirectional_iterator_tag> { typedef std::bidirectional_iterator_tag type; }; template <> struct zip_iterator_category_impl<std::bidirectional_iterator_tag, std::forward_iterator_tag> { typedef std::forward_iterator_tag type; }; template <> struct zip_iterator_category_impl<std::forward_iterator_tag, std::bidirectional_iterator_tag> { typedef std::forward_iterator_tag type; }; template <> struct zip_iterator_category_impl<std::bidirectional_iterator_tag, std::input_iterator_tag> { typedef std::input_iterator_tag type; }; template <> struct zip_iterator_category_impl<std::input_iterator_tag, std::bidirectional_iterator_tag> { typedef std::input_iterator_tag type; }; // forward_iterator_tag template <> struct zip_iterator_category_impl<std::forward_iterator_tag, std::forward_iterator_tag> { typedef std::forward_iterator_tag type; }; template <> struct zip_iterator_category_impl<std::input_iterator_tag, std::forward_iterator_tag> { typedef std::input_iterator_tag type; }; template <> struct zip_iterator_category_impl<std::forward_iterator_tag, std::input_iterator_tag> { typedef std::input_iterator_tag type; }; // input_iterator_tag template <> struct zip_iterator_category_impl<std::input_iterator_tag, std::input_iterator_tag> { typedef std::input_iterator_tag type; }; /////////////////////////////////////////////////////////////////////// template <typename IteratorTuple, typename Enable = void> struct zip_iterator_category; template <typename T> struct zip_iterator_category<tuple<T>, typename std::enable_if<tuple_size<tuple<T>>::value == 1>::type> { typedef typename std::iterator_traits<T>::iterator_category type; }; template <typename T, typename U> struct zip_iterator_category<tuple<T, U>, typename std::enable_if<tuple_size<tuple<T, U>>::value == 2>::type> : zip_iterator_category_impl< typename std::iterator_traits<T>::iterator_category, typename std::iterator_traits<U>::iterator_category> { }; template <typename T, typename U, typename... Tail> struct zip_iterator_category<tuple<T, U, Tail...>, typename std::enable_if<( tuple_size<tuple<T, U, Tail...>>::value > 2)>::type> : zip_iterator_category_impl< typename zip_iterator_category_impl< typename std::iterator_traits<T>::iterator_category, typename std::iterator_traits<U>::iterator_category>::type, typename zip_iterator_category<tuple<Tail...>>::type> { }; /////////////////////////////////////////////////////////////////////// template <typename IteratorTuple> struct dereference_iterator; template <typename... Ts> struct dereference_iterator<tuple<Ts...>> { template <std::size_t... Is> HPX_HOST_DEVICE static typename zip_iterator_reference<tuple<Ts...>>::type call(detail::pack_c<std::size_t, Is...>, tuple<Ts...> const& iterators) { return util::forward_as_tuple(*util::get<Is>(iterators)...); } }; struct increment_iterator { template <typename T> HPX_HOST_DEVICE void operator()(T& iter) const { ++iter; } }; struct decrement_iterator { template <typename T> HPX_HOST_DEVICE void operator()(T& iter) const { --iter; } }; struct advance_iterator { explicit advance_iterator(std::ptrdiff_t n) : n_(n) { } template <typename T> HPX_HOST_DEVICE void operator()(T& iter) const { iter += n_; } std::ptrdiff_t n_; }; /////////////////////////////////////////////////////////////////////// template <typename IteratorTuple, typename Derived> class zip_iterator_base : public hpx::util::iterator_facade<Derived, typename zip_iterator_value<IteratorTuple>::type, typename zip_iterator_category<IteratorTuple>::type, typename zip_iterator_reference<IteratorTuple>::type> { typedef hpx::util::iterator_facade< zip_iterator_base<IteratorTuple, Derived>, typename zip_iterator_value<IteratorTuple>::type, typename zip_iterator_category<IteratorTuple>::type, typename zip_iterator_reference<IteratorTuple>::type> base_type; public: HPX_HOST_DEVICE zip_iterator_base() {} HPX_HOST_DEVICE zip_iterator_base(IteratorTuple const& iterators) : iterators_(iterators) { } HPX_HOST_DEVICE zip_iterator_base(IteratorTuple&& iterators) : iterators_(std::move(iterators)) { } typedef IteratorTuple iterator_tuple_type; HPX_HOST_DEVICE iterator_tuple_type get_iterator_tuple() const { return iterators_; } private: friend class hpx::util::iterator_core_access; HPX_HOST_DEVICE bool equal(zip_iterator_base const& other) const { return iterators_ == other.iterators_; } HPX_HOST_DEVICE typename base_type::reference dereference() const { return dereference_iterator<IteratorTuple>::call( typename detail::make_index_pack< util::tuple_size<IteratorTuple>::value>::type(), iterators_); } HPX_HOST_DEVICE void increment() { this->apply(increment_iterator()); } HPX_HOST_DEVICE void decrement() { this->apply(decrement_iterator()); } HPX_HOST_DEVICE void advance(std::ptrdiff_t n) { this->apply(advance_iterator(n)); } HPX_HOST_DEVICE std::ptrdiff_t distance_to(zip_iterator_base const& other) const { return util::get<0>(other.iterators_) - util::get<0>(iterators_); } private: template <typename F, std::size_t... Is> HPX_HOST_DEVICE void apply( F&& f, detail::pack_c<std::size_t, Is...>) { int const _sequencer[] = { ((f(util::get<Is>(iterators_))), 0)...}; (void) _sequencer; } template <typename F> HPX_HOST_DEVICE void apply(F&& f) { return apply(std::forward<F>(f), detail::make_index_pack< util::tuple_size<IteratorTuple>::value>()); } private: friend class hpx::serialization::access; template <typename Archive> void serialize(Archive& ar, unsigned) { ar& iterators_; } private: IteratorTuple iterators_; }; } // namespace detail template <typename... Ts> class zip_iterator : public detail::zip_iterator_base<tuple<Ts...>, zip_iterator<Ts...>> { static_assert( sizeof...(Ts) != 0, "zip_iterator must wrap at least one iterator"); typedef detail::zip_iterator_base<tuple<Ts...>, zip_iterator<Ts...>> base_type; public: HPX_HOST_DEVICE zip_iterator() : base_type() { } HPX_HOST_DEVICE explicit zip_iterator(Ts const&... vs) : base_type(util::tie(vs...)) { } HPX_HOST_DEVICE explicit zip_iterator(tuple<Ts...>&& t) : base_type(std::move(t)) { } HPX_HOST_DEVICE zip_iterator(zip_iterator const& other) : base_type(other) { } HPX_HOST_DEVICE zip_iterator(zip_iterator&& other) : base_type(std::move(other)) { } HPX_HOST_DEVICE zip_iterator& operator=(zip_iterator const& other) { base_type::operator=(other); return *this; } HPX_HOST_DEVICE zip_iterator& operator=(zip_iterator&& other) { base_type::operator=(std::move(other)); return *this; } template <typename... Ts_> HPX_HOST_DEVICE typename std::enable_if< detail::are_tuples_compatible_not_same< typename zip_iterator::iterator_tuple_type, typename zip_iterator<Ts_...>::iterator_tuple_type&&>::value, zip_iterator&>::type operator=(zip_iterator<Ts_...> const& other) { base_type::operator=(base_type(other.get_iterator_tuple())); return *this; } template <typename... Ts_> HPX_HOST_DEVICE typename std::enable_if< detail::are_tuples_compatible_not_same< typename zip_iterator::iterator_tuple_type, typename zip_iterator<Ts_...>::iterator_tuple_type&&>::value, zip_iterator&>::type operator=(zip_iterator<Ts_...>&& other) { base_type::operator=( base_type(std::move(other.get_iterator_tuple()))); return *this; } }; template <typename... Ts> class zip_iterator<tuple<Ts...>> : public detail::zip_iterator_base<tuple<Ts...>, zip_iterator<tuple<Ts...>>> { static_assert( sizeof...(Ts) != 0, "zip_iterator must wrap at least one iterator"); typedef detail::zip_iterator_base<tuple<Ts...>, zip_iterator<tuple<Ts...>>> base_type; public: HPX_HOST_DEVICE zip_iterator() : base_type() { } HPX_HOST_DEVICE explicit zip_iterator(Ts const&... vs) : base_type(util::tie(vs...)) { } HPX_HOST_DEVICE explicit zip_iterator(tuple<Ts...>&& t) : base_type(std::move(t)) { } HPX_HOST_DEVICE zip_iterator(zip_iterator const& other) : base_type(other) { } HPX_HOST_DEVICE zip_iterator(zip_iterator&& other) : base_type(std::move(other)) { } HPX_HOST_DEVICE zip_iterator& operator=(zip_iterator const& other) { base_type::operator=(other); return *this; } HPX_HOST_DEVICE zip_iterator& operator=(zip_iterator&& other) { base_type::operator=(std::move(other)); return *this; } template <typename... Ts_> HPX_HOST_DEVICE typename std::enable_if< detail::are_tuples_compatible_not_same< typename zip_iterator::iterator_tuple_type, typename zip_iterator<Ts_...>::iterator_tuple_type&&>::value, zip_iterator&>::type operator=(zip_iterator<Ts_...> const& other) { base_type::operator=(base_type(other.get_iterator_tuple())); return *this; } template <typename... Ts_> HPX_HOST_DEVICE typename std::enable_if< detail::are_tuples_compatible_not_same< typename zip_iterator::iterator_tuple_type, typename zip_iterator<Ts_...>::iterator_tuple_type&&>::value, zip_iterator&>::type operator=(zip_iterator<Ts_...>&& other) { base_type::operator=( base_type(std::move(other.get_iterator_tuple()))); return *this; } }; /////////////////////////////////////////////////////////////////////////// template <typename... Ts> HPX_HOST_DEVICE zip_iterator<typename decay<Ts>::type...> make_zip_iterator( Ts&&... vs) { typedef zip_iterator<typename decay<Ts>::type...> result_type; return result_type(std::forward<Ts>(vs)...); } /////////////////////////////////////////////////////////////////////////// template <typename ZipIter> struct zip_iterator_category : detail::zip_iterator_category<typename ZipIter::iterator_tuple_type> { }; }} // namespace hpx::util namespace hpx { namespace traits { namespace functional { /////////////////////////////////////////////////////////////////////// template <typename F, typename T> struct element_result_of : util::invoke_result<F, T> { }; template <typename F, typename Iter> struct lift_zipped_iterators; template <typename F, typename... Ts> struct lift_zipped_iterators<F, util::zip_iterator<Ts...>> { typedef typename util::zip_iterator<Ts...>::iterator_tuple_type tuple_type; typedef util::tuple<typename element_result_of< typename F::template apply<Ts>, Ts>::type...> result_type; template <std::size_t... Is, typename... Ts_> static result_type call(util::detail::pack_c<std::size_t, Is...>, util::tuple<Ts_...> const& t) { return util::make_tuple( typename F::template apply<Ts>()(util::get<Is>(t))...); } template <typename... Ts_> static result_type call(util::zip_iterator<Ts_...> const& iter) { using hpx::util::detail::make_index_pack; return call(typename make_index_pack<sizeof...(Ts)>::type(), iter.get_iterator_tuple()); } }; } // namespace functional /////////////////////////////////////////////////////////////////////////// template <typename... Iter> struct is_zip_iterator<hpx::util::zip_iterator<Iter...>> : std::true_type { }; }} // namespace hpx::traits #endif
32.008711
80
0.54161
folshost
9c03e748b59fa8c7d334a783e666a2ebc649b2a6
5,574
cpp
C++
test/shard/RelationshipTypes.cpp
raphaelsc/ragedb
8116d17480b7a1fa9af38139b41385973e2941fd
[ "Apache-2.0" ]
58
2021-07-08T14:20:54.000Z
2022-03-31T08:20:39.000Z
test/shard/RelationshipTypes.cpp
raphaelsc/ragedb
8116d17480b7a1fa9af38139b41385973e2941fd
[ "Apache-2.0" ]
15
2021-07-29T14:37:57.000Z
2022-03-31T04:22:36.000Z
test/shard/RelationshipTypes.cpp
raphaelsc/ragedb
8116d17480b7a1fa9af38139b41385973e2941fd
[ "Apache-2.0" ]
2
2021-07-29T14:24:57.000Z
2021-09-08T10:14:52.000Z
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * 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 <catch2/catch.hpp> #include "../../src/graph/Shard.h" SCENARIO( "Shard can handle Relationship Types", "[relationship_types]" ) { GIVEN("An empty shard") { ragedb::Shard shard(4); WHEN("we get the relationship types") { THEN("it should be empty") { std::set<std::string> types = shard.RelationshipTypesGet(); REQUIRE(types.empty()); } } WHEN("we get the count of relationship types") { THEN("it should be zero") { uint64_t count = shard.RelationshipTypesGetCount(); REQUIRE(count == 0); } } WHEN("we get the type id and type") { THEN("it should have the empty id and type") { uint16_t type_id = shard.RelationshipTypeGetTypeId("NOT_THERE"); std::string type = shard.RelationshipTypeGetType(99); REQUIRE(type_id == 0); REQUIRE(type.empty()); } } WHEN("we add a relationship type") { shard.RelationshipTypeInsert("LOVES", 1); THEN("it should be one") { uint64_t count = shard.RelationshipTypesGetCount(); REQUIRE(count == 1); } THEN("it should be in the set") { std::set<std::string> types = shard.RelationshipTypesGet(); REQUIRE(types.size() == 1); REQUIRE(types == std::set<std::string>({"LOVES"})); } THEN("it should have the correct id and type") { uint16_t type_id = shard.RelationshipTypeGetTypeId("LOVES"); std::string type = shard.RelationshipTypeGetType(1); REQUIRE(type_id == 1); REQUIRE(type == "LOVES"); } THEN("it should be unique and retain original id") { shard.RelationshipTypeInsert("LOVES", 2); uint16_t type_id = shard.RelationshipTypeGetTypeId("LOVES"); std::string type = shard.RelationshipTypeGetType(1); std::string invalid = shard.RelationshipTypeGetType(2); REQUIRE(type_id == 1); REQUIRE(type == "LOVES"); REQUIRE(invalid.empty()); } } WHEN("we add two relationship types") { shard.RelationshipTypeInsert("LOVES", 1); shard.RelationshipTypeInsert("HATES", 2); THEN("it should be two") { uint64_t count = shard.RelationshipTypesGetCount(); REQUIRE(count == 2); } } } GIVEN("A shard with three nodes") { ragedb::Shard shard(4); shard.NodeTypeInsert("Node", 1); shard.NodeTypeInsert("User", 2); uint64_t node1id = shard.NodeAddEmpty(1, "one"); uint64_t node2id = shard.NodeAddEmpty(1, "two"); uint64_t node3id = shard.NodeAddEmpty(1, "three"); WHEN("we get the count of an invalid relationship type") { THEN("it should be zero") { uint64_t count = shard.RelationshipTypesGetCount("DOES_NOT_EXIST"); REQUIRE(count == 0); } } WHEN("we get the count of an invalid relationship type id") { THEN("it should be zero") { uint64_t count = shard.RelationshipTypesGetCount(99); REQUIRE(count == 0); } } WHEN("add a relationship") { shard.RelationshipTypeInsert("LOVES", 1); shard.RelationshipAddEmptySameShard(1, node1id, node2id); THEN("request the count of the relationship type") { uint64_t count_by_id = shard.RelationshipTypesGetCount(1); uint64_t count_by_type = shard.RelationshipTypesGetCount("LOVES"); REQUIRE(count_by_id == 1); REQUIRE(count_by_type == 1); } } WHEN("add new relationships") { shard.RelationshipTypeInsert("LOVES", 1); shard.RelationshipTypeInsert("HATES", 2); shard.RelationshipAddEmptySameShard(1, node1id, node2id); shard.RelationshipAddEmptySameShard(1, node2id, node3id); shard.RelationshipAddEmptySameShard(2, node3id, node1id); THEN("request the count of the relationship types") { uint64_t likes_count = shard.RelationshipTypesGetCount("LOVES"); uint64_t likes_count_by_id = shard.RelationshipTypesGetCount(1); uint64_t hates_count = shard.RelationshipTypesGetCount("HATES"); uint64_t hates_count_by_id = shard.RelationshipTypesGetCount(2); REQUIRE(likes_count == 2); REQUIRE(likes_count_by_id == 2); REQUIRE(hates_count == 1); REQUIRE(hates_count_by_id == 1); } } } }
38.441379
83
0.568353
raphaelsc
9c059e2aec9c9d8b24dce83de1d6acec3c311ac0
567
cpp
C++
src/test/14_pch/main.cpp
zerger/UDRefl
1a2f67a3d94f191d6eafd520359428ac3d579ab2
[ "MIT" ]
null
null
null
src/test/14_pch/main.cpp
zerger/UDRefl
1a2f67a3d94f191d6eafd520359428ac3d579ab2
[ "MIT" ]
null
null
null
src/test/14_pch/main.cpp
zerger/UDRefl
1a2f67a3d94f191d6eafd520359428ac3d579ab2
[ "MIT" ]
null
null
null
#include <UDRefl/UDRefl.h> #include <iostream> #include "A.h" #include "B.h" using namespace Ubpa; using namespace Ubpa::UDRefl; int main() { RegisterA(); RegisterB(); ReflMngr::Instance().RegisterTypeAuto<std::array<size_t, 5>>(); for (const auto& [ID, info] : ReflMngr::Instance().typeinfos) { ReflMngr::Instance().ForEachMethod(ID, [](TypeRef type, MethodRef method) { std::cout << ReflMngr::Instance().tregistry.Nameof(type.ID) << ": " << ReflMngr::Instance().nregistry.Nameof(method.ID) << std::endl; return true; }); } return 0; }
21
77
0.659612
zerger
9c06ec704aceb141270183d8ef02df4e1f4c2bae
5,617
cpp
C++
Development/SDKs/1.7.1/SDK/LinearTimecode_functions.cpp
ResaloliPT/HydroneerReleases
3a3501f04608cea77ccbf7229f94089295128ea7
[ "Unlicense" ]
null
null
null
Development/SDKs/1.7.1/SDK/LinearTimecode_functions.cpp
ResaloliPT/HydroneerReleases
3a3501f04608cea77ccbf7229f94089295128ea7
[ "Unlicense" ]
null
null
null
Development/SDKs/1.7.1/SDK/LinearTimecode_functions.cpp
ResaloliPT/HydroneerReleases
3a3501f04608cea77ccbf7229f94089295128ea7
[ "Unlicense" ]
null
null
null
// Name: Hydroneer, Version: 1.7.1 #include "../pch.h" /*!!DEFINE!!*/ /*!!HELPER_DEF!!*/ /*!!HELPER_INC!!*/ #ifdef _MSC_VER #pragma pack(push, 0x01) #endif namespace CG { //--------------------------------------------------------------------------- // Functions //--------------------------------------------------------------------------- void FDropTimecode::AfterRead() { } void FDropTimecode::BeforeDelete() { } // Function: // Offset -> 0x007E5220 // Name -> Function LinearTimecode.LinearTimecodeComponent.SetDropTimecodeFrameNumber // Flags -> (Final, Native, Static, Public, HasOutParms, BlueprintCallable) // Parameters: // struct FDropTimecode Timecode (ConstParm, Parm, OutParm, ReferenceParm, NoDestructor, NativeAccessSpecifierPublic) // int FrameNumber (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic) // struct FDropTimecode OutTimecode (Parm, OutParm, NoDestructor, NativeAccessSpecifierPublic) void ULinearTimecodeComponent::STATIC_SetDropTimecodeFrameNumber(const struct FDropTimecode& Timecode, int FrameNumber, struct FDropTimecode* OutTimecode) { static UFunction* fn = UObject::FindObject<UFunction>("Function LinearTimecode.LinearTimecodeComponent.SetDropTimecodeFrameNumber"); ULinearTimecodeComponent_SetDropTimecodeFrameNumber_Params params {}; params.Timecode = Timecode; params.FrameNumber = FrameNumber; auto flags = fn->FunctionFlags; fn->FunctionFlags |= 0x00000400; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; if (OutTimecode != nullptr) *OutTimecode = params.OutTimecode; } // Function: // Offset -> 0x007E5130 // Name -> Function LinearTimecode.LinearTimecodeComponent.GetDropTimeCodeFrameNumber // Flags -> (Final, Native, Static, Public, HasOutParms, BlueprintCallable) // Parameters: // struct FDropTimecode Timecode (ConstParm, Parm, OutParm, ReferenceParm, NoDestructor, NativeAccessSpecifierPublic) // int FrameNumber (Parm, OutParm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic) void ULinearTimecodeComponent::STATIC_GetDropTimeCodeFrameNumber(const struct FDropTimecode& Timecode, int* FrameNumber) { static UFunction* fn = UObject::FindObject<UFunction>("Function LinearTimecode.LinearTimecodeComponent.GetDropTimeCodeFrameNumber"); ULinearTimecodeComponent_GetDropTimeCodeFrameNumber_Params params {}; params.Timecode = Timecode; auto flags = fn->FunctionFlags; fn->FunctionFlags |= 0x00000400; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; if (FrameNumber != nullptr) *FrameNumber = params.FrameNumber; } // Function: // Offset -> 0x007E5100 // Name -> Function LinearTimecode.LinearTimecodeComponent.GetDropFrameNumber // Flags -> (Final, Native, Public, BlueprintCallable, BlueprintPure, Const) // Parameters: // int ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic) int ULinearTimecodeComponent::GetDropFrameNumber() { static UFunction* fn = UObject::FindObject<UFunction>("Function LinearTimecode.LinearTimecodeComponent.GetDropFrameNumber"); ULinearTimecodeComponent_GetDropFrameNumber_Params params {}; auto flags = fn->FunctionFlags; fn->FunctionFlags |= 0x00000400; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } void ULinearTimecodeComponent::AfterRead() { USceneComponent::AfterRead(); READ_PTR_FULL(MediaPlayer, UMediaPlayer); } void ULinearTimecodeComponent::BeforeDelete() { USceneComponent::BeforeDelete(); DELE_PTR_FULL(MediaPlayer); } // Function: // Offset -> 0x007E5020 // Name -> Function LinearTimecode.DropTimecodeToStringConversion.Conv_DropTimecodeToString // Flags -> (Final, Native, Static, Private, HasOutParms, BlueprintCallable, BlueprintPure) // Parameters: // struct FDropTimecode InTimecode (ConstParm, Parm, OutParm, ReferenceParm, NoDestructor, NativeAccessSpecifierPublic) // struct FString ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, HasGetValueTypeHash, NativeAccessSpecifierPublic) struct FString UDropTimecodeToStringConversion::STATIC_Conv_DropTimecodeToString(const struct FDropTimecode& InTimecode) { static UFunction* fn = UObject::FindObject<UFunction>("Function LinearTimecode.DropTimecodeToStringConversion.Conv_DropTimecodeToString"); UDropTimecodeToStringConversion_Conv_DropTimecodeToString_Params params {}; params.InTimecode = InTimecode; auto flags = fn->FunctionFlags; fn->FunctionFlags |= 0x00000400; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } void UDropTimecodeToStringConversion::AfterRead() { UBlueprintFunctionLibrary::AfterRead(); } void UDropTimecodeToStringConversion::BeforeDelete() { UBlueprintFunctionLibrary::BeforeDelete(); } } #ifdef _MSC_VER #pragma pack(pop) #endif
34.67284
238
0.672957
ResaloliPT
9c07e6dd66ea4a9466b4a4c34043497f32600893
1,140
hpp
C++
src/include/XEUI/HealthBar.hpp
devxkh/FrankE
72faca02759b54aaec842831f3c7a051e7cf5335
[ "MIT" ]
11
2017-01-17T15:02:25.000Z
2020-11-27T16:54:42.000Z
src/include/XEUI/HealthBar.hpp
devxkh/FrankE
72faca02759b54aaec842831f3c7a051e7cf5335
[ "MIT" ]
9
2016-10-23T20:15:38.000Z
2018-02-06T11:23:17.000Z
src/include/XEUI/HealthBar.hpp
devxkh/FrankE
72faca02759b54aaec842831f3c7a051e7cf5335
[ "MIT" ]
2
2019-08-29T10:23:51.000Z
2020-04-03T06:08:34.000Z
#ifndef HEALTHBAR_H #define HEALTHBAR_H #include <XEScene/XESceneNode.hpp> #include <XEMath/Vectors/Vector3.hpp> #include <XEGraphics.hpp> // caption Text ! .......... // http://www.ogre3d.org/forums/viewtopic.php?f=11&t=59984&start=325 //http://www.ogre3d.org/forums/viewtopic.php?f=11&t=59984&start=450#p429016 // BFG Editor // http://www.ogre3d.org/forums/viewtopic.php?f=11&t=59984&start=525#p437220 //Sprite Rotation // http://www.ogre3d.org/forums/viewtopic.php?f=11&t=59984&start=550#p438323 namespace XE { namespace UI { class HealthBar { public: HealthBar(XE::XE_G::Silverback* silverback,SM::SceneNode* node, Math::Vector3f offset); void setValue(XE::Float percent); // 0 - 1 void setVisible(bool value); bool isVisible() { return m_bVisible; }; private: Float m_rValue; bool m_bVisible; Math::Vector2f m_pMaxSize; SM::SceneNode* m_pSceneNode; XE_G::ScreenRenderable* m_pScreen; XE_G::Layer* m_pOverLayer; XE_G::Layer* m_pUnderLayer; XE_G::Rectangle* m_pGrid; XE_G::Rectangle* m_pColour; XE_G::Rectangle* m_pBlack; }; } // namespace UI } //namespace XE #endif//HEALTHBAR_H
22.8
88
0.713158
devxkh
9c085c989ce9407eb41fc8888b69cfb2d75a5802
17,588
hpp
C++
definitions.hpp
hardwareExplorer/HLS_IntegerNet
f656fc67c7886ef62d6d1260ea2961bf75107447
[ "MIT" ]
null
null
null
definitions.hpp
hardwareExplorer/HLS_IntegerNet
f656fc67c7886ef62d6d1260ea2961bf75107447
[ "MIT" ]
null
null
null
definitions.hpp
hardwareExplorer/HLS_IntegerNet
f656fc67c7886ef62d6d1260ea2961bf75107447
[ "MIT" ]
null
null
null
#ifndef INT_OP #define INT_OP #include "ap_axi_sdata.h" #include "hls_stream.h" #include "hls_math.h" #include <stdio.h> #include "ap_int.h" #include "parameters.hpp" #include "datafilepaths.hpp" #include <math.h> #include <assert.h> #include <iostream> using namespace std; //Absolute function #ifdef ABS #undef ABS #endif #define ABS(n) ((n < 0) ? -n : n) float abs_f(float x); float sigmoid(float x); //flatten template<typename T, int mtx_d, int mtx_h, int mtx_w> void flatten(T (&in1)[mtx_d][mtx_h][mtx_w], T (&out1)[mtx_d*mtx_h*mtx_w][1]) { int i,j,k; for(k=0;k<mtx_d;k++) for(i=0;i<mtx_h;i++) for(j=0;j<mtx_w;j++) { out1[k*(mtx_h*mtx_w) + i*mtx_w + j][0] = in1[k][i][j]; } } //////////////////////////////////////////////////////////////////////// /////// Conv & Maxpool//////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////// template<int in_h,int in_w, int in_d, int k_h, int k_w, int k_d, int k_cnt, int out_h, int out_w > void conv_int(float (&in_map)[in_d][in_h][in_w], float scalar_wt[k_cnt], ap_int<INT_SIZE+2> (&wt)[k_cnt][k_d][k_h][k_w], int st_v, int st_h, float (&out_map)[k_cnt][out_h][out_w] ) { int m,n,k,i,j,p,q,r; float scalar_in; float win[k_d][k_h][k_w]; ap_int<INT_SIZE+2> in_int[in_d][in_h][in_w]; int acc; float max; float scalar_acc; //output feature map is produced in its channel wise (an extracted window is convolved against all the kernels in that layer thus producing output in 3rd dim) //1.Extract window integerize(in_map,in_int); //print_mtx(in_int,1); for(m=0,q=0; m<(in_h-k_h)+1; m=m+st_v,q++)//vertical count for(n=0,r=0; n<(in_w-k_w)+1; n=n+st_h,r++)//horizontal count { //1. Extract scalar scalar_acc = 0; for (i=0; i <k_h; i++) for(j=0; j<k_w; j++) { max = fabs(in_map[0][m+i][n+j]); for(k=0; k<k_d; k++) { if(fabs(in_map[k][m+i][n+j]) > max) max = fabs(in_map[k][m+i][n+j]); } scalar_acc += max; } scalar_acc /= 32; cout<<"\t "<<scalar_acc; //2. Convovle the inegerized matrix against all the kernels: produces channel wise output in OFM for(p=0;p<k_cnt;p++) { acc=0; for(k=0; k<k_d; k++) for (i=0; i <k_h; i++) for(j=0; j<k_w; j++) { acc += in_int[k][m+i][n+j] * wt[p][k][i][j]; } //4. Multiply with the in and wt scalar out_map[p][q][r] = scalar_acc * scalar_wt[p] * acc; //5. Activation: reLu if(out_map[p][q][r]<0) out_map[p][q][r] = 0; } }//horizontal count repeat } //-----------------------------------conv maxpool : REAL --------------------------------------------------------------- template<int in_h,int in_w, int in_d, int k_h, int k_w, int k_d, int k_cnt, int out_h, int out_w > void conv_real(float (&in_map)[in_d][in_h][in_w], float (&wt)[k_cnt][k_d][k_h][k_w], int st_v, int st_h, float (&out_map)[k_cnt][out_h][out_w] ) { int m,n,k,i,j,p,q,r; //output feature map is produced in its channel wise (an extracted window is convolved against all the kernels in that layer thus producing output in 3rd dim) //1.Extract window for(m=0,q=0; m<(in_h-k_h)+1; m=m+st_v,q++)//vertical count for(n=0,r=0; n<(in_w-k_w)+1; n=n+st_h,r++)//horizontal count { for(p=0;p<k_cnt;p++) { out_map[p][q][r]=0; for(k=0; k<k_d; k++) for (i=0; i <k_h; i++) for(j=0; j<k_w; j++) { out_map[p][q][r]+= in_map[k][m+i][n+j]*wt[p][k][i][j]; //cout<<"\t"<<in_map[k][m+i][n+j]<<"\t*\t"<<wt[p][k][i][j]<<"\t"<<in_map[k][m+i][n+j]*wt[p][k][i][j]<<"\t"<<out_map[p][q][r] ; } //cout<<"\n"; //Activation: reLu if(out_map[p][q][r]<0) out_map[p][q][r] = 0; } }//horizontal count repeat } template<int in_h,int in_w, int in_d> void BN_real(float (&in_map)[in_d][in_h][in_w], float mean[in_d], float variance[in_d], float beta[in_d], float gamma[in_d] ){ for(int k=0; k<in_d; k++) for (int i=0; i <in_h; i++) { for(int j=0; j<in_w; j++) { //BN the input in_map[k][i][j] = (in_map[k][i][j] - mean[k])/sqrt(variance[k]); //scale and shift in_map[k][i][j] = in_map[k][i][j]* gamma[k] + beta[k]; } } } template<int in_h,int in_w, int in_d, int out_h, int out_w > void maxpool_real(float (&in_map)[in_d][in_h][in_w], int k_h, int k_w, int st_v, int st_h, float (&out_map)[in_d][out_h][out_w] ) { int m,n,k,i,j,q,r; float max; //output feature map is produced in its channel wise (an extracted window is convolved against all the kernels in that layer thus producing output in 3rd dim) for(m=0,q=0; m<(in_h-k_h)+1; m=m+st_v,q++)//vertical count for(n=0,r=0; n<(in_w-k_w)+1; n=n+st_h,r++)//horizontal count { for(k=0; k<in_d; k++) { max = in_map[k][m][n]; for (i=0; i <k_h; i++) { for(j=0; j<k_w; j++) { if(in_map[k][m+i][n+j] > max) max = in_map[k][m+i][n+j]; //cout<<"\t"<<max<<"\t" ; } } out_map[k][q][r] = max; //cout<<"\t"<<out_map[k][q][r]<<"\t" ; } //cout<<"\n"; } } //////////////////////////////////////////////////////////////////////// /////// Mtx mult top//////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////// template<int mtx_m> void softmax(float (&in)[mtx_m][1], float (sum)) { for (int i=0; i<mtx_m; i++) { cout <<"i: "<< i<< " sum "<<sum<<" in : "<<in[i][0]; in[i][0] = exp(in[i][0])/sum; cout<<"Softmax of "<<i<<" "<< in[i][0]; } } template<int mtx_m, int mtx_n> //(input_mtx nxp, weight scalar, weight_int mxn, out_mtx nxp) void dense1d_top_int(float (&MxA)[mtx_n], float scalarB,ap_int<INT_SIZE+2> (&MxB_int)[mtx_m][mtx_n], float (&MxC)[mtx_m], int ACT){ float scalarA; ap_int<INT_SIZE+2> MxA_int[mtx_n]; scalarA = integerize_1d(MxA,MxA_int); int_int_mx_mult1d(scalarA, MxA_int, scalarB,MxB_int, MxC, ACT); } // for real just call is enough ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //Matrix Multiplication template<int mtx_m, int mtx_n> //A input nxp, B weight mxn, C = BxA mxp void int_int_mx_mult1d(float scalarA, ap_int<INT_SIZE+2> (&MxA_int)[mtx_n], float scalarB, ap_int<INT_SIZE+2> (&MxB_int)[mtx_m][mtx_n], float (&MxC)[mtx_m], int ACT ) { int i,j,k; ap_int<INT_SIZE+2+9> acc = 0; //saves 17bits from standard int float scalarC = scalarA*scalarB; //cout<<"Acc out"; for(i=0; i<mtx_m; i++) { for(k=0;k<mtx_n;k++) { acc = acc + MxB_int[i][k]*MxA_int[k]; //cout<<"\n"<<acc; } MxC[i] = scalarC * acc; //Activation: //If ACT = 0 -> Sigmoid, ACT=1 ->Softmax if(ACT==1) MxC[i] = sigmoid(MxC[i]); acc =0; } //if(ACT==2) // softmax(MxC); } template<int mtx_m, int mtx_n> //A input nxp, B weight mxn, C = BxA mxp void dense1d_top_real(float (&MxA)[mtx_n], float (&MxB)[mtx_m][mtx_n], float (&MxC)[mtx_m], int ACT ) { int i,j,k; for(i=0; i<mtx_m; i++) { MxC[i] = 0; for(k=0;k<mtx_n;k++) { MxC[i] = MxC[i] + MxB[i][k]*MxA[k]; if(ACT==1) MxC[i] = sigmoid(MxC[i]); } } // if(ACT==2) // softmax(MxC); } //-----2D--------- template<int mtx_m, int mtx_n, int mtx_p> //(input_mtx nxp, weight scalar, weight_int mxn, out_mtx nxp) void dense_top_int(float (&MxA)[mtx_n][mtx_p], float scalarB,ap_int<INT_SIZE+2> (&MxB_int)[mtx_m][mtx_n], float (&MxC)[mtx_m][mtx_p], int ACT){ float scalarA; ap_int<INT_SIZE+2> MxA_int[mtx_n][mtx_p]; scalarA = integerize_2d(MxA,MxA_int); int_int_mx_mult(scalarA, MxA_int, scalarB,MxB_int, MxC, ACT); } // for real just call is enough ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //Matrix Multiplication template<int mtx_m, int mtx_n,int mtx_p> //A input nxp, B weight mxn, C = BxA mxp void int_int_mx_mult(float scalarA, ap_int<INT_SIZE+2> (&MxA_int)[mtx_n][mtx_p], float scalarB, ap_int<INT_SIZE+2> (&MxB_int)[mtx_m][mtx_n], float (&MxC)[mtx_m][mtx_p], int ACT ) { int i,j,k; ap_int<INT_SIZE+2+9> acc = 0; //saves 17bits from standard int float scalarC = scalarA*scalarB; float sum=0; //cout<<"Acc out"; for(i=0; i<mtx_m; i++) { for(j=0; j<mtx_p; j++) { for(k=0;k<mtx_n;k++) { acc = acc + MxB_int[i][k]*MxA_int[k][j]; //cout<<"\n"<<acc; } MxC[i][j] = scalarC * acc; //Activation: //If ACT = 0 -> Sigmoid, ACT=1 ->Softmax if(ACT==1) MxC[i][j] = sigmoid(MxC[i][j]); else if (ACT ==2) sum += exp( MxC[i][j]); acc =0; } } if(ACT==2) softmax(MxC,sum); } template<int mtx_m, int mtx_n,int mtx_p> //A input nxp, B weight mxn, C = BxA mxp void dense_top_real(float (&MxA)[mtx_n][mtx_p], float (&MxB)[mtx_m][mtx_n], float (&MxC)[mtx_m][mtx_p], int ACT ) { int i,j,k; float sum=0; for(i=0; i<mtx_m; i++) { for(j=0; j<mtx_p; j++) { MxC[i][j] = 0; for(k=0;k<mtx_n;k++) { MxC[i][j] = MxC[i][j] + MxB[i][k]*MxA[k][j]; } if(ACT==1) MxC[i][j] = sigmoid(MxC[i][j]); else if (ACT ==2){ sum += exp( MxC[i][j]); //cout<<"\nMxC "<<MxC[i][j]<<" sum : "<< sum; } } } if(ACT==2) softmax(MxC, sum); } template<int mtx_m, int mtx_n,int mtx_p> //A input nxp, B weight mxn, C = BxA mxp void dense_top_pureint(ap_int<INT_SIZE+2> (&MxA)[mtx_n][mtx_p], ap_int<INT_SIZE+2> (&MxB)[mtx_m][mtx_n], ap_int<INT_SIZE+3> MxC[mtx_m][mtx_p] ) { int i,j,k; int acc = 0; for(i=0; i<mtx_m; i++) for(j=0; j<mtx_p; j++) { for(k=0;k<mtx_n;k++) { acc = acc + MxB[i][k]*MxA[k][j]; } MxC[i][j] = acc; acc =0; } } //////////////////////////////////////////////////////////////////////// ///////////////// MAC tops ///////////////////////////////////////// //////////////////////////////////////////////////////////////////////// template<int mtx_m, int mtx_n,int mtx_k, int k_cnt> void mac_top_int (float (&MxA)[mtx_k][mtx_m][mtx_n], ap_int<INT_SIZE+2> (&MxB_int)[k_cnt][mtx_k][mtx_m][mtx_n], float scalarB[k_cnt], float mac_int[k_cnt]) { int k; float scalarA; ap_int<INT_SIZE+2> MxA_int[mtx_k][mtx_m][mtx_n]; scalarA = integerize(MxA,MxA_int); for(k=0;k<k_cnt;k++) { mac_int[k] = int_int_mx_mac(scalarA,MxA_int,scalarB[k],MxB_int[k]); } } template<int mtx_m, int mtx_n,int mtx_k, int k_cnt> void mac_top_real (float (&MxA)[mtx_k][mtx_m][mtx_n], float (&MxB)[k_cnt][mtx_k][mtx_m][mtx_n], float mac_real[k_cnt]) { int k; for(k=0;k<k_cnt;k++) { mac_real[k] = real_mx_mac (MxA,MxB[k]); } } /// TO_DO : S //How fp multiplication is avoided?!! //Try other rounding techniques //Try other quantization techniques //Try other correction techniques: improvising scalar factor ///--------------- MAC OPERATION --------------- //(mxn) * (nxk) -> (mxk) //---Single/multiple kernel Integerized MAC with A real template<int mtx_h, int mtx_w, int mtx_d> float int_mx_mac(float (&MxA)[mtx_d][mtx_h][mtx_w], float scalarB, ap_int<INT_SIZE+2> (&MxB_int)[mtx_d][mtx_h][mtx_w]) { float scalarA; ap_int<INT_SIZE+2> MxA_int [mtx_d][mtx_h][mtx_w]; int i,j,k; int mac = 0; scalarA = integerize (MxA,MxA_int); for(k=0; k<mtx_d; k++) for(i=0; i<mtx_h; i++) for(j=0;j<mtx_w;j++) { mac = mac + MxA_int[k][i][j]*MxB_int[k][i][j]; } return scalarA * scalarB * mac; } //Single/Multiple kernel integerized MAC both A & B are integerized template<int mtx_h, int mtx_w, int mtx_d> float int_int_mx_mac(float scalarA, ap_int<INT_SIZE+2> (&MxA_int)[mtx_d][mtx_h][mtx_w], float scalarB, ap_int<INT_SIZE+2> (&MxB_int)[mtx_d][mtx_h][mtx_w]) { int i,j,k; int mac = 0; for(k=0; k<mtx_d; k++) for(i=0; i<mtx_h; i++) for(j=0;j<mtx_w;j++) { mac = mac + MxA_int[k][i][j]*MxB_int[k][i][j]; } return scalarA * scalarB * mac; } //---Real MAC template<int mtx_h, int mtx_w, int mtx_d> float real_mx_mac(float (&MxA)[mtx_d][mtx_h][mtx_w], float (&MxB)[mtx_d][mtx_h][mtx_w]) { int i,j,k; float mac = 0; for(k=0; k<mtx_d; k++) for(i=0; i<mtx_h; i++) { for(j=0;j<mtx_w;j++) { mac = mac + MxA[k][i][j]*MxB[k][i][j]; } } return mac; } //Integer MAC template<int mtx_h, int mtx_w, int mtx_d> int int_only_mx_mac(int (&MxA)[mtx_d][mtx_h][mtx_w], int (&MxB)[mtx_d][mtx_h][mtx_w]) { int i,j,k; int mac = 0; for(k=0; k<mtx_d; k++) for(i=0; i<mtx_h; i++) { for(j=0;j<mtx_w;j++) { mac = mac + MxA[k][i][j]*MxB[k][i][j]; } } return mac; } ///////////////////////////////////////////////////////////////////////// ///---------------INTEGERIZE FUNCTION --------------------------- //////////////////////////////////////////////////////////////////////// template<int mtx_h, int mtx_w, int mtx_d> float integerize_M(float (&x)[mtx_d][mtx_h][mtx_w], ap_int<INT_SIZE+2> (&y)[mtx_d][mtx_h][mtx_w]) //x : input { int i,j,k; float max = 0; float scalar; float max_c[mtx_h][mtx_w] ; //channel-wise max float sum=0; //find max(abs(x)) <-- max|x| ; x:2D/3D for(i=0; i<mtx_h; i++) for(j=0;j<mtx_w;j++) { max_c[i][j] = 0; //since max of abs is found 0 will be the min for(k=0; k<mtx_d; k++) //channel-wise { max = (abs_f(x[k][i][j]) > (max)) ? abs_f(x[k][i][j]) : max; //fcmp max_c[i][j] = (abs_f(x[k][i][j]) > (max_c[i][j])) ? abs_f(x[k][i][j]) : max_c[i][j]; //fcmp //channelwise max } sum = sum+max_c[i][j]; //fadd //sum up channel wise max matrix } //scalar = max / pow(2,INT_SIZE);//avoiding pow func scalar = sum / 32; //Integerized matrix for(k=0; k<mtx_d; k++) { for(i=0; i<mtx_h; i++) { for(j=0;j<mtx_w;j++) { //y[k][i][j] =round((x[k][i][j]/max)*pow(2,INT_SIZE)); //avoiding pow func y[k][i][j] =round((x[k][i][j]/max)*32); //fmul , fdiv } } } return scalar; } template<int mtx_h, int mtx_w, int mtx_d> float integerize(float (&x)[mtx_d][mtx_h][mtx_w], ap_int<INT_SIZE+2> (&y)[mtx_d][mtx_h][mtx_w]) //x : input { int i,j,k; float max = 0; float scalar; //find max(abs(x)) <-- max|x| ; x:2D/3D for(k=0; k<mtx_d; k++) for(i=0; i<mtx_h; i++) for(j=0;j<mtx_w;j++) { max = (abs_f(x[k][i][j]) > (max)) ? abs_f(x[k][i][j]) : max; //fcmp } //scalar = max / pow(2,INT_SIZE);//avoiding pow func scalar = max / 32; //Integerized matrix for(k=0; k<mtx_d; k++) { for(i=0; i<mtx_h; i++) { for(j=0;j<mtx_w;j++) { //y[k][i][j] =round((x[k][i][j]/max)*pow(2,INT_SIZE)); //avoiding pow func y[k][i][j] =round((x[k][i][j]/max)*32); //fmul , fdiv } } } return scalar; } // template<int mtx_h, int mtx_w> float integerize_2d(float (&x)[mtx_h][mtx_w], ap_int<INT_SIZE+2> (&y)[mtx_h][mtx_w]) //x : input { int i,j; float max = 0; float scalar; //find max(abs(x)) <-- max|x| ; x:2D/3D integerize_2d_max:for(i=0; i<mtx_h; i++) //#pragma HLS PIPELINE II=1 for(j=0;j<mtx_w;j++) { max = (abs_f(x[i][j]) > (max)) ? abs_f(x[i][j]) : max; //fcmp } //scalar = max / pow(2,INT_SIZE);//avoiding pow func scalar = max / 32; //Integerized matrix integerize_2d_convert_top: for(i=0; i<mtx_h; i++) { integerize_2d_convert: for(j=0;j<mtx_w;j++) { //#pragma HLS PIPELINE II=1 y[i][j] =round((x[i][j]/max)*32); //fmul , fdiv } } return scalar; } // template<int mtx_h> float integerize_1d(float (&x)[mtx_h], ap_int<INT_SIZE+2> (&y)[mtx_h]) //x : input { int i; float max = 0; float scalar; //find max(abs(x)) <-- max|x| ; x:2D/3D for(i=0; i<mtx_h; i++) { max = (abs_f(x[i]) > (max)) ? abs_f(x[i]) : max; //fcmp } //scalar = max / pow(2,INT_SIZE);//avoiding pow func scalar = max / 32; //Integerized matrix for(i=0; i<mtx_h; i++) { y[i] =round((x[i]/max)*32); //fmul , fdiv } return scalar; } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////// //--------Misc functions---------- //////////////////////////////////////////////////////////////////////// template <typename T1, typename T2, size_t mtx_d, size_t mtx_h, size_t mtx_w > void print_mtx(T1 (&x)[mtx_d][mtx_h][mtx_w], T2 scalar ) { int i,j,k; //printf("\nPrinting Matrix\n"); for(k=0; k<mtx_d; k++) { for(i=0; i<mtx_h; i++) { for(j=0;j<mtx_w;j++) { //if(typeid(T1) == typeid(ap_int<4>) && typeid(T2) == typeid(ap_int<4>)) cout<<x[k][i][j]*scalar<<"\t"; } printf("\n"); } printf("\n"); } } template <typename T1, typename T2, size_t mtx_h, size_t mtx_w > void print_mtx_2d(T1 (&x)[mtx_h][mtx_w], T2 scalar ) { int i,j; //printf("\nPrinting Matrix\n"); for(i=0; i<mtx_h; i++) { for(j=0;j<mtx_w;j++) { //if(typeid(T1) == typeid(ap_int<4>) && typeid(T2) == typeid(ap_int<4>)) cout<<x[i][j]*scalar<<"\t"; } printf("\n"); } printf("\n"); } template <typename T1, typename T2, size_t mtx_h > void print_mtx_1d(T1 (&x)[mtx_h], T2 scalar ) { int i,j; //printf("\nPrinting Matrix\n"); for(i=0; i<mtx_h; i++) { cout<<x[i]*scalar<<"\t"; } printf("\n"); } #endif
20.838863
182
0.518024
hardwareExplorer
9c08acb3bccf04b55c60977962a0d9a3cd7e08dc
469
hpp
C++
library/ATF/ATL__CSimpleStringT.hpp
lemkova/Yorozuya
f445d800078d9aba5de28f122cedfa03f26a38e4
[ "MIT" ]
29
2017-07-01T23:08:31.000Z
2022-02-19T10:22:45.000Z
library/ATF/ATL__CSimpleStringT.hpp
kotopes/Yorozuya
605c97d3a627a8f6545cc09f2a1b0a8afdedd33a
[ "MIT" ]
90
2017-10-18T21:24:51.000Z
2019-06-06T02:30:33.000Z
library/ATF/ATL__CSimpleStringT.hpp
kotopes/Yorozuya
605c97d3a627a8f6545cc09f2a1b0a8afdedd33a
[ "MIT" ]
44
2017-12-19T08:02:59.000Z
2022-02-24T23:15:01.000Z
// This file auto generated by plugin for ida pro. Generated code only for x64. Please, dont change manually #pragma once #include <common/common.h> START_ATF_NAMESPACE namespace ATL { template<typename _Ty, bool _b> struct CSimpleStringT { _Ty *m_pszData; }; static_assert(ATF::checkSize<ATL::CSimpleStringT<char, true>, 8>(), "ATL::CSimpleStringT<char,1>"); }; // end namespace ATL END_ATF_NAMESPACE
26.055556
108
0.656716
lemkova
9c0906b165fb3ae23e2965a6fe1424315f08a310
23
cc
C++
chapter-10/10.28.cc
hongmi/cpp-primer-4-exercises
98ddb98b41d457a1caa525d246dfb7453be0c8d2
[ "MIT" ]
1
2017-04-01T06:57:30.000Z
2017-04-01T06:57:30.000Z
chapter-10/10.28.cc
hongmi/cpp-primer-4-exercises
98ddb98b41d457a1caa525d246dfb7453be0c8d2
[ "MIT" ]
null
null
null
chapter-10/10.28.cc
hongmi/cpp-primer-4-exercises
98ddb98b41d457a1caa525d246dfb7453be0c8d2
[ "MIT" ]
null
null
null
//for A to Z, traverse
11.5
22
0.652174
hongmi
9c0958a316a7afd805e085798b91925bb540c2fd
319
hh
C++
Mu2eG4/inc/constructProtonAbsorber.hh
lborrel/Offline
db9f647bad3c702171ab5ffa5ccc04c82b3f8984
[ "Apache-2.0" ]
9
2020-03-28T00:21:41.000Z
2021-12-09T20:53:26.000Z
Mu2eG4/inc/constructProtonAbsorber.hh
lborrel/Offline
db9f647bad3c702171ab5ffa5ccc04c82b3f8984
[ "Apache-2.0" ]
684
2019-08-28T23:37:43.000Z
2022-03-31T22:47:45.000Z
Mu2eG4/inc/constructProtonAbsorber.hh
lborrel/Offline
db9f647bad3c702171ab5ffa5ccc04c82b3f8984
[ "Apache-2.0" ]
61
2019-08-16T23:28:08.000Z
2021-12-20T08:29:48.000Z
#ifndef Mu2eG4_constructProtonAbsorber_hh #define Mu2eG4_constructProtonAbsorber_hh // // Free function to construct Proton Absorber // // // Original author KLG // namespace mu2e { class SimpleConfig; void constructProtonAbsorber(const SimpleConfig& _config); } #endif /* Mu2eG4_constructProtonAbsorber_hh */
16.789474
60
0.786834
lborrel
9c0c2e93192817a733de8322bb055cebb87a7110
532
hpp
C++
inference-engine/src/inference_engine/include/openvino/runtime/common.hpp
Nitin-Mane/openvino
600eef24bca97fb049fc580c2d02f6982050ff6c
[ "Apache-2.0" ]
null
null
null
inference-engine/src/inference_engine/include/openvino/runtime/common.hpp
Nitin-Mane/openvino
600eef24bca97fb049fc580c2d02f6982050ff6c
[ "Apache-2.0" ]
null
null
null
inference-engine/src/inference_engine/include/openvino/runtime/common.hpp
Nitin-Mane/openvino
600eef24bca97fb049fc580c2d02f6982050ff6c
[ "Apache-2.0" ]
null
null
null
// Copyright (C) 2018-2021 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // /** * @brief This is a header file for the OpenVINO Runtime common aliases that depend only from external API * * @file openvino/runtime/common.hpp */ #pragma once #include <map> #include <string> namespace ov { namespace ie = InferenceEngine; namespace runtime { /** * @brief This type of map is commonly used to pass set of parameters */ using ConfigMap = std::map<std::string, std::string>; } // namespace runtime } // namespace ov
23.130435
106
0.714286
Nitin-Mane
9c0e2cd4d609a6326fa2d1537b571a0fecdd8f55
3,385
cpp
C++
node/silkworm/downloader/messages/InboundGetBlockHeaders.cpp
mriccobene/silkworm
353f5c4c4f9c9e726c9a4647cd887743ef131d48
[ "Apache-2.0" ]
null
null
null
node/silkworm/downloader/messages/InboundGetBlockHeaders.cpp
mriccobene/silkworm
353f5c4c4f9c9e726c9a4647cd887743ef131d48
[ "Apache-2.0" ]
null
null
null
node/silkworm/downloader/messages/InboundGetBlockHeaders.cpp
mriccobene/silkworm
353f5c4c4f9c9e726c9a4647cd887743ef131d48
[ "Apache-2.0" ]
null
null
null
/* Copyright 2021 The Silkworm Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "InboundGetBlockHeaders.hpp" #include <silkworm/common/cast.hpp> #include <silkworm/common/log.hpp> #include <silkworm/downloader/internals/header_retrieval.hpp> #include <silkworm/downloader/packets/BlockHeadersPacket.hpp> #include <silkworm/downloader/rpc/SendMessageById.hpp> namespace silkworm { InboundGetBlockHeaders::InboundGetBlockHeaders(const sentry::InboundMessage& msg, Db::ReadOnlyAccess db, SentryClient& sentry) : InboundMessage(), db_(db), sentry_(sentry) { if (msg.id() != sentry::MessageId::GET_BLOCK_HEADERS_66) { throw std::logic_error("InboundGetBlockHeaders received wrong InboundMessage"); } peerId_ = string_from_H512(msg.peer_id()); ByteView data = string_view_to_byte_view(msg.data()); rlp::DecodingResult err = rlp::decode(data, packet_); if (err != rlp::DecodingResult::kOk) { throw rlp::rlp_error("rlp decoding error decoding GetBlockHeaders"); } SILKWORM_LOG(LogLevel::Info) << "Received message " << *this << "\n"; } void InboundGetBlockHeaders::execute() { using namespace std; HeaderRetrieval header_retrieval(db_); BlockHeadersPacket66 reply; reply.requestId = packet_.requestId; if (holds_alternative<Hash>(packet_.request.origin)) { reply.request = header_retrieval.recover_by_hash(get<Hash>(packet_.request.origin), packet_.request.amount, packet_.request.skip, packet_.request.reverse); } else { reply.request = header_retrieval.recover_by_number(get<BlockNum>(packet_.request.origin), packet_.request.amount, packet_.request.skip, packet_.request.reverse); } Bytes rlp_encoding; rlp::encode(rlp_encoding, reply); auto msg_reply = std::make_unique<sentry::OutboundMessageData>(); msg_reply->set_id(sentry::MessageId::BLOCK_HEADERS_66); msg_reply->set_data(rlp_encoding.data(), rlp_encoding.length()); // copy SILKWORM_LOG(LogLevel::Info) << "Replying to " << identify(*this) << " using send_message_by_id with " << reply.request.size() << " headers\n"; rpc::SendMessageById rpc{peerId_, std::move(msg_reply)}; sentry_.exec_remotely(rpc); sentry::SentPeers peers = rpc.reply(); SILKWORM_LOG(LogLevel::Info) << "Received rpc result of " << identify(*this) << ": " << std::to_string(peers.peers_size()) + " peer(s)\n"; } uint64_t InboundGetBlockHeaders::reqId() const { return packet_.requestId; } std::string InboundGetBlockHeaders::content() const { std::stringstream content; content << packet_; return content.str(); } } // namespace silkworm
38.465909
115
0.677696
mriccobene
9c0f13619c98e7ae96aa0c43abfe4a772f404c8d
874
hpp
C++
generator/translator_factory.hpp
kadetlessy/omim
f28560ac36899ef8694e75a36535b0f1487b285b
[ "Apache-2.0" ]
1
2021-07-02T08:45:02.000Z
2021-07-02T08:45:02.000Z
generator/translator_factory.hpp
kadetlessy/omim
f28560ac36899ef8694e75a36535b0f1487b285b
[ "Apache-2.0" ]
1
2020-06-15T15:16:23.000Z
2020-06-15T15:59:19.000Z
generator/translator_factory.hpp
maksimandrianov/omim
cbc5a80d09d585afbda01e471887f63b9d3ab0c2
[ "Apache-2.0" ]
null
null
null
#pragma once #include "generator/factory_utils.hpp" #include "generator/translator_geo_objects.hpp" #include "generator/translator_interface.hpp" #include "generator/translator_planet.hpp" #include "generator/translator_region.hpp" #include "base/assert.hpp" #include <memory> #include <utility> namespace generator { enum class TranslatorType { Planet, Region, GeoObjects }; template <class... Args> std::shared_ptr<TranslatorInterface> CreateTranslator(TranslatorType type, Args&&... args) { switch (type) { case TranslatorType::Planet: return create<TranslatorPlanet>(std::forward<Args>(args)...); case TranslatorType::Region: return create<TranslatorRegion>(std::forward<Args>(args)...); case TranslatorType::GeoObjects: return create<TranslatorGeoObjects>(std::forward<Args>(args)...); } CHECK_SWITCH(); } } // namespace generator
23
90
0.74714
kadetlessy
9c1260ecdfc14624dfb2d660ad67b0195ef15e24
796
hpp
C++
inc/parser.hpp
Anishka0107/Wunner
997749e44909fbb0551c4e7c630302dee72c19b8
[ "MIT" ]
9
2017-10-27T11:34:42.000Z
2021-07-16T04:13:11.000Z
inc/parser.hpp
Anishka0107/Wunner
997749e44909fbb0551c4e7c630302dee72c19b8
[ "MIT" ]
1
2018-03-13T15:04:42.000Z
2018-03-15T05:39:07.000Z
inc/parser.hpp
Anishka0107/Wunner
997749e44909fbb0551c4e7c630302dee72c19b8
[ "MIT" ]
7
2017-10-29T15:47:58.000Z
2021-07-13T12:37:49.000Z
/* * * Author : Anishka Gupta * Created on July 7, 2017 * */ #ifndef STOPPER #define STOPPER "res/stop_words" #endif // STOPPER #ifndef PARSER #define PARSER #include <string> #include <unordered_set> #include <vector> namespace wunner { class Parser { private: std::vector<std::string> parsed_doc; std::unordered_set<std::string> stop_words; void tokenizer(std::string const &); void query_tokenizer(std::string const &); void normalizer(); void stop_words_removal(); void stemmer(); public: Parser(); std::vector<std::string> get_parsed_document(std::string const &); const std::vector<std::string> & get_parsed_query(std::string const &); }; } #endif // PARSER
19.414634
81
0.611809
Anishka0107
9c15e4337c3b5fb09fb768cf0f474b4aface18f1
1,662
cpp
C++
example/tuple_algorithm.cpp
deepgrace/monster
3cb524ddaf2239f9332dc7cfbe449e085cec2a4b
[ "BSL-1.0" ]
132
2019-04-02T07:47:03.000Z
2022-03-25T10:13:38.000Z
example/tuple_algorithm.cpp
deepgrace/monster
3cb524ddaf2239f9332dc7cfbe449e085cec2a4b
[ "BSL-1.0" ]
2
2020-06-01T19:05:27.000Z
2021-11-29T12:08:29.000Z
example/tuple_algorithm.cpp
deepgrace/monster
3cb524ddaf2239f9332dc7cfbe449e085cec2a4b
[ "BSL-1.0" ]
16
2017-08-15T02:57:24.000Z
2022-02-25T08:01:57.000Z
// // Copyright (c) 2016-present DeepGrace (complex dot invoke at gmail dot com) // // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // // Official repository: https://github.com/deepgrace/monster // // g++ -I include -m64 -std=c++20 -s -Wall -Os -o /tmp/tuple_algorithm example/tuple_algorithm.cpp #include <iostream> #include <tuple_algorithm.hpp> using namespace tuple_algorithm; int main(int argc, char* argv[]) { auto is_float = [](auto v){ return std::is_floating_point_v<decltype(v)>; }; static_assert(all_of(is_float, std::make_tuple(1.0f, 2.0f, 3.0f))); static_assert(none_of(is_float, std::make_tuple('1', nullptr, '3'))); static_assert(any_of(is_float, std::make_tuple(1.0f, '2', nullptr))); auto print = [](auto v){ std::cout << v << std::endl; }; for_each(print, std::make_tuple(2, 4, 8)); for_each_n<2>(print, std::make_tuple(2, 4, 8)); static_assert(count(std::make_tuple(1, 3, 2, 4, 3, 3), 3) == 3); static_assert(count_if(is_float, std::make_tuple('1', 2.0, 'c', nullptr)) == 1); static_assert(mismatch(std::make_tuple(4, 3, 2, 1), std::make_tuple(4, 3, 1, 2)).value() == 2); static_assert(mismatch([](auto x, auto y){ return x != y; }, std::make_tuple(1, 3), std::make_tuple(1, 4)).value() == 0); static_assert(find(std::make_tuple(4, 6, 7, 8), 6).value() == 1); static_assert(find_if([](auto x) { return x == 6; }, std::make_tuple(7, 8, 6, 9)).value() == 2); static_assert(find_if_not([](auto x) { return x == 6; }, std::make_tuple(6, 5, 7)).value() == 1); return 0; }
40.536585
125
0.644404
deepgrace
9c17377156d4660a9c98f1f68ef91d9f632838b4
1,267
cpp
C++
Data Structures/week4_binary_search_trees/3_is_bst_advanced/is_bst_hard.cpp
Roopam-mishra/Data-Structures-and-Algorithms
0422c64769909ad82c631c14e814d958136afc18
[ "MIT" ]
12
2020-06-01T17:34:08.000Z
2022-03-25T12:27:09.000Z
Data Structures/week4_binary_search_trees/3_is_bst_advanced/is_bst_hard.cpp
Roopam-mishra/Data-Structures-and-Algorithms
0422c64769909ad82c631c14e814d958136afc18
[ "MIT" ]
null
null
null
Data Structures/week4_binary_search_trees/3_is_bst_advanced/is_bst_hard.cpp
Roopam-mishra/Data-Structures-and-Algorithms
0422c64769909ad82c631c14e814d958136afc18
[ "MIT" ]
2
2021-06-26T19:43:49.000Z
2022-03-05T22:02:59.000Z
#include <iostream> #include <algorithm> #include <vector> #include <math.h> #include <cstring> #include <string> #include <stack> #include <queue> #include <deque> #include <map> #include <set> #include <utility> #include <iomanip> #include <climits> using namespace std; #define ll long long #define MOD 1000000007 #define MAX 1000000000000000000 #define ln "\n" #define pb push_back #define pll pair<ll,ll> #define f first #define s second #define TEST ll t;cin>>t; while(t--) #define fast_io ios_base::sync_with_stdio(false);cin.tie(NULL); struct roop { ll key; ll left; ll right; }; ll n; struct roop r[100001]; ll flag=1; bool is_binary_search_tree(ll node,ll maxi,ll mini) { if((node<0) || (node>=n)) return true; if((r[node].key<mini) || (r[node].key>maxi)) return false; return is_binary_search_tree(r[node].left,r[node].key-1,mini) && is_binary_search_tree(r[node].right,maxi,r[node].key); } int main() { fast_io; ll i; cin>>n; for(i=0;i<n;i++) cin>>r[i].key>>r[i].left>>r[i].right; if(is_binary_search_tree(0,MAX,-MAX)) cout<<"CORRECT"<<endl; else cout<<"INCORRECT"<<endl; return 0; }
11.623853
125
0.611681
Roopam-mishra
9c1b31c2fe3746bef79eb0e14df5c0bc2ce9bc9c
3,379
hpp
C++
include/argot/concepts/expandable_argument_provider/detail/is_expandable_argument_provider.hpp
mattcalabrese/argot
97349baaf27659c9dc4d67cf8963b2e871eaedae
[ "BSL-1.0" ]
49
2018-05-09T23:17:45.000Z
2021-07-21T10:05:19.000Z
include/argot/concepts/expandable_argument_provider/detail/is_expandable_argument_provider.hpp
mattcalabrese/argot
97349baaf27659c9dc4d67cf8963b2e871eaedae
[ "BSL-1.0" ]
null
null
null
include/argot/concepts/expandable_argument_provider/detail/is_expandable_argument_provider.hpp
mattcalabrese/argot
97349baaf27659c9dc4d67cf8963b2e871eaedae
[ "BSL-1.0" ]
2
2019-08-04T03:51:36.000Z
2020-12-28T06:53:29.000Z
/*============================================================================== Copyright (c) 2016, 2017, 2018, 2019 Matt Calabrese Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) ==============================================================================*/ #ifndef ARGOT_CONCEPTS_ARGUMENT_PROVIDER_OF_EXPANDABLES_DETAIL_IS_HPP_ #define ARGOT_CONCEPTS_ARGUMENT_PROVIDER_OF_EXPANDABLES_DETAIL_IS_HPP_ #include <argot/concepts/argument_receiver.hpp> #include <argot/concepts/expandable.hpp> #include <argot/detail/conditional.hpp> #include <argot/detail/detection.hpp> #include <argot/gen/is_modeled.hpp> #include <argot/gen/make_concept_map.hpp> #include <argot/prov_traits/provide.hpp> #include <argot/receiver_traits/argument_list_kinds.hpp> #include <argot/receiver_traits/argument_types.hpp> #include <type_traits> namespace argot { namespace expandable_argument_provider_detail { struct is_expandable_argument_provider_impl_t {} inline constexpr is_expandable_argument_provider_impl{}; template< class T > struct all_are_expandables_impl; // TODO(mattcalabrese) Just check callability of prov_traits::provide template< class... T > struct all_are_expandables_impl < receiver_traits::argument_types_t< T... > > { static bool constexpr value = ( ARGOT_IS_MODELED( Expandable< T&& > ) && ... ); }; template< class T > bool constexpr all_are_expandables_v = all_are_expandables_impl< T >::value; template< class T > using is_expandable_argument_provider_result = prov_traits ::result_of_provide_t< T, is_expandable_argument_provider_impl_t >; template< class T > using is_expandable_argument_provider_t = typename argot_detail::conditional < call_detail::is_detected_v < is_expandable_argument_provider_result, T > >::template apply < call_detail::lazy_expand< is_expandable_argument_provider_result, T > , std::false_type >::type; template< class T > struct is_expandable_argument_provider : is_expandable_argument_provider_t< T >{}; template< class T > bool constexpr is_expandable_argument_provider_v = is_expandable_argument_provider_t< T >::value; } // namespace argot(::expandable_argument_provider_detail) template<> struct make_concept_map < ArgumentReceiver < expandable_argument_provider_detail ::is_expandable_argument_provider_impl_t > > { template< class... LeadingArgumentListKinds , class... TrailingArgumentListKinds , class... P > static constexpr/* std::bool_constant < ( expandable_argument_provider_detail ::all_are_expandables_v< LeadingArgumentListKinds > && ... ) && ( expandable_argument_provider_detail ::all_are_expandables_v< TrailingArgumentListKinds > && ... ) && ( ARGOT_IS_MODELED( Expandable< P&& > ) && ... ) >*/ std::true_type receive_branch ( expandable_argument_provider_detail ::is_expandable_argument_provider_impl_t , receiver_traits::argument_list_kinds_t< LeadingArgumentListKinds... > , receiver_traits::argument_list_kinds_t< TrailingArgumentListKinds... > , P&&... ) noexcept { return {}; } }; } // namespace argot #endif // ARGOT_CONCEPTS_ARGUMENT_PROVIDER_OF_EXPANDABLES_DETAIL_IS_HPP_
30.169643
80
0.715004
mattcalabrese
9c1b66cb25f4b907ef8e44a0d4bdb310d067d325
14,024
cpp
C++
app/table_server.cpp
rolevax/libsaki
399ea22c45fe033b011b511c65610f9405fee709
[ "MIT" ]
8
2017-11-01T20:14:42.000Z
2022-01-18T09:06:05.000Z
app/table_server.cpp
rolevax/libsaki
399ea22c45fe033b011b511c65610f9405fee709
[ "MIT" ]
31
2017-10-23T15:35:38.000Z
2019-07-24T09:20:14.000Z
app/table_server.cpp
mjpancake/libsaki
399ea22c45fe033b011b511c65610f9405fee709
[ "MIT" ]
18
2017-10-25T11:32:44.000Z
2021-02-25T10:46:57.000Z
#include "table_server.h" #include "../util/string_enum.h" namespace saki { using namespace nlohmann; using namespace field; template<typename T> void rotate(T &arr) { auto temp = arr[0]; arr[0] = arr[1]; arr[1] = arr[2]; arr[2] = arr[3]; arr[3] = temp; } TableServer::TableServer(Table::InitConfig config, std::vector<TableObserver *> obs, const TableEnv &env) : mTable(std::move(config), (static_cast<void>(obs.push_back(this)), obs), env) , mNonces{0, 0, 0, 0} { } TableServer::Msgs TableServer::start() { mTable.start(); pushActivationMsgs(); return popMsgs(); } TableServer::Msgs TableServer::action(Who who, const Action &action, int nonce) { switch (mTable.check(who, action, nonce)) { case Table::CheckResult::OK: mTable.action(who, action, nonce); pushActivationMsgs(); break; case Table::CheckResult::EXPIRED: pushActionExpired(who); break; case Table::CheckResult::ILLEGAL: pushActionIllegal(who); break; } return popMsgs(); } TableServer::Msgs TableServer::resume(Who comer) { if (mTable.beforeEast1()) return popMsgs(); // no serious info needs to be provided json args; args["whoDrawn"] = -1; args["barkss"] = json::array(); args["rivers"] = json::array(); args["riichiBars"] = json::array(); args["dice"] = mTable.getDice(); if (mTable.getDice() > 0) { for (Who who : whos::ALL4) { const Hand &hand = mTable.getHand(who); auto pers = static_cast<unsigned>(who.turnFrom(comer)); if (hand.hasDrawn()) { args["whoDrawn"] = pers; if (who == comer) args["drawn"] = stringOf(hand.drawn()); } if (who == comer) args["myHand"] = hand.closed().t37s13(true).range(); args["barkss"][pers] = hand.barks(); args["rivers"][pers] = mTable.getRiver(who).range(); args["riichiBars"][pers] = mTable.riichiEstablished(who); } args["drids"] = mTable.getMount().getDrids().range(); } const auto &pts = mTable.getPoints(); args["points"] = json { pts[comer.uIndex()], pts[comer.right().uIndex()], pts[comer.cross().uIndex()], pts[comer.left().uIndex()], }; args["girlKeys"] = json::array(); for (Who who: { comer, comer.right(), comer.cross(), comer.left() }) { json key; key["id"] = static_cast<int>(mTable.getGirl(who).getId()); key["path"] = ""; args["girlKeys"].push_back(key); } args["wallRemain"] = mTable.getMount().remainPii(); args["deadRemain"] = mTable.getMount().remainRinshan(); args["round"] = mTable.getRound(); args["extraRound"] = mTable.getExtraRound(); args["dealer"] = mTable.getDealer().turnFrom(comer); args["allLast"] = mTable.isAllLast(); args["deposit"] = mTable.getDeposit(); pushPeerMsg(comer, "resume", args); if (mTable.getView(comer)->myChoices().any()) pushActivationMsg(comer, true); return popMsgs(); } void TableServer::onTableEvent(const Table &table, const TE::TableStarted &event) { (void) event; pushPointsChanged(table); } void TableServer::onTableEvent(const Table &table, const TE::FirstDealerChosen &event) { (void) table; json args; for (Who to : whos::ALL4) { args["dealer"] = event.who.turnFrom(to); pushPeerMsg(to, util::stringOf(event.TYPE), args); } } void TableServer::onTableEvent(const Table &table, const TE::RoundStarted &event) { (void) table; json args; args["round"] = event.round; args["extra"] = event.extraRound; args["allLast"] = event.allLast; args["deposit"] = event.deposit; for (Who to : whos::ALL4) { args["dealer"] = event.dealer.turnFrom(to); pushPeerMsg(to, util::stringOf(event.TYPE), args); } args["dealer"] = event.dealer.index(); args["seed"] = event.seed; pushSystemMsg("round-start-log", args); } void TableServer::onTableEvent(const Table &table, const TE::Cleaned &event) { (void) table; (void) event; pushBroadcastMsg(util::stringOf(event.TYPE), json::object()); } void TableServer::onTableEvent(const Table &table, const TE::Diced &event) { (void) table; json args; args["die1"] = event.die1; args["die2"] = event.die2; pushBroadcastMsg(util::stringOf(event.TYPE), args); } void TableServer::onTableEvent(const Table &table, const TE::Dealt &event) { (void) event; for (Who to : whos::ALL4) { const auto &init = table.getHand(to).closed().t37s13(true); json args; args["init"] = init.range(); pushPeerMsg(to, util::stringOf(event.TYPE), args); } } void TableServer::onTableEvent(const Table &table, const TE::Flipped &event) { (void) event; json args; args["newIndic"] = stringOf(table.getMount().getDrids().back()); pushBroadcastMsg(util::stringOf(event.TYPE), args); } void TableServer::onTableEvent(const Table &table, const TE::Drawn &event) { const T37 &in = table.getHand(event.who).drawn(); for (Who to : whos::ALL4) { json args; args["who"] = event.who.turnFrom(to); if (table.duringKan()) args["rinshan"] = true; if (to == event.who) args["tile"] = stringOf(in); pushPeerMsg(to, util::stringOf(event.TYPE), args); } } void TableServer::onTableEvent(const Table &table, const TE::Discarded &event) { Who discarder = table.getFocus().who(); const T37 &out = table.getFocusTile(); bool lay = table.lastDiscardLay(); json args; args["tile"] = stringOf(out, lay); args["spin"] = event.spin; for (Who to : whos::ALL4) { args["who"] = discarder.turnFrom(to); pushPeerMsg(to, util::stringOf(event.TYPE), args); } } void TableServer::onTableEvent(const Table &table, const TE::RiichiCalled &event) { (void) table; for (Who to : whos::ALL4) { json args; args["who"] = event.who.turnFrom(to); pushPeerMsg(to, util::stringOf(event.TYPE), args); } } void TableServer::onTableEvent(const Table &table, const TE::RiichiEstablished &event) { (void) table; for (Who to : whos::ALL4) { json args; args["who"] = event.who.turnFrom(to); pushPeerMsg(to, util::stringOf(event.TYPE), args); } } void TableServer::onTableEvent(const Table &table, const TE::Barked &event) { Who from = event.bark.isCpdmk() ? table.getFocus().who() : Who(); json args; args["actStr"] = util::stringOf(event.bark.type()); args["bark"] = event.bark; args["spin"] = event.spin; for (Who to : whos::ALL4) { args["who"] = event.who.turnFrom(to); args["fromWhom"] = from.somebody() ? from.turnFrom(to) : -1; pushPeerMsg(to, util::stringOf(event.TYPE), args); } } void TableServer::onTableEvent(const Table &table, const TE::RoundEnded &event) { using RR = RoundResult; // form and hand lists have same order as openers // but they don't need to be rotated since openers // are not rotated but changed by value json formsList = json::array(); json handsList = json::array(); for (Who who : event.openers) { const Hand &hand = table.getHand(who); json handMap; handMap["closed"] = hand.closed().t37s13(true).range(); handMap["barks"] = hand.barks(); if (event.result == RR::TSUMO || event.result == RR::KSKP) handMap[PICK] = stringOf(hand.drawn()); else if (event.result == RR::RON || event.result == RR::SCHR) handMap[PICK] = stringOf(table.getFocusTile()); handsList.emplace_back(handMap); } for (const Form &form : event.forms) { json formMap; formMap["spell"] = form.spell(); formMap["charge"] = form.charge(); formsList.emplace_back(formMap); } json args; args[RESULT] = util::stringOf(event.result); args[HANDS] = handsList; args[FORMS] = formsList; args["urids"] = table.getMount().getUrids().range(); for (Who to : whos::ALL4) { args[OPENERS] = json::array(); for (Who who : event.openers) args[OPENERS].push_back(who.turnFrom(to)); Who gunner = event.gunner; args["gunner"] = gunner.somebody() ? gunner.turnFrom(to) : -1; pushPeerMsg(to, util::stringOf(event.TYPE), args); } } void TableServer::onTableEvent(const Table &table, const TE::PointsChanged &event) { (void) event; pushPointsChanged(table); } void TableServer::onTableEvent(const Table &table, const TE::TableEnded &event) { (void) table; // tableEndStat(scores); json args; args["scores"] = event.scores; for (Who to : whos::ALL4) { json rankList; for (Who who : event.ranks) rankList.push_back(who.turnFrom(to)); args["rank"] = rankList; pushPeerMsg(to, util::stringOf(event.TYPE), args); rotate(args["scores"]); } pushSystemMsg("game-over", json()); } void TableServer::onTableEvent(const Table &table, const TE::PoppedUp &event) { json args; args["str"] = table.getGirl(event.who).popUpStr(); pushPeerMsg(event.who, util::stringOf(event.TYPE), args); } const Table &TableServer::table() const { return mTable; } void TableServer::pushActivationMsgs() { for (Who who : whos::ALL4) if (mTable.getView(who)->myChoices().any()) pushActivationMsg(who); } void TableServer::pushActivationMsg(Who who, bool isResume) { using AC = ActCode; using Mode = Choices::Mode; const auto view = mTable.getView(who); const Choices &choices = view->myChoices(); if (!isResume && mTable.getNonce(who) == mNonces[who.uIndex()]) return; // still waiting for input mNonces[who.uIndex()] = mTable.getNonce(who); if (view->riichiEstablished(who) && choices.spinOnly()) { json args; args["Who"] = who.index(); args["Nonce"] = mTable.getNonce(who); pushSystemMsg("riichi-auto", args); return; } json map; int focusWho = -1; switch (choices.mode()) { case Mode::WATCH: break; case Mode::IRS_CHECK: activateIrsCheck(map, *view); break; case Mode::DICE: map[util::stringOf(AC::DICE)] = true; break; case Mode::DRAWN: activateDrawn(map, *view); break; case Mode::BARK: focusWho = view->getFocus().who().turnFrom(who); activateBark(map, *view); break; case Mode::END: if (choices.can(AC::END_TABLE)) map[util::stringOf(AC::END_TABLE)] = true; if (choices.can(AC::NEXT_ROUND)) map[util::stringOf(AC::NEXT_ROUND)] = true; break; } if (choices.can(AC::IRS_CLICK)) map[util::stringOf(AC::IRS_CLICK)] = true; json args; args["action"] = map; args["lastDiscarder"] = focusWho; args["nonce"] = mTable.getNonce(who); // args["green"] = view->myChoices().forwardAll(); pushPeerMsg(who, "activated", args); } void TableServer::pushPointsChanged(const Table &table) { json args; args["points"] = table.getPoints(); for (Who to : whos::ALL4) { pushPeerMsg(to, util::stringOf(TE::Type::POINTS_CHANGED), args); rotate(args["points"]); } } void TableServer::pushActionExpired(Who who) { json args; args["Who"] = who.index(); pushSystemMsg("action-expired", args); } void TableServer::pushActionIllegal(Who who) { json args; args["Who"] = who.index(); pushSystemMsg("action-illegal", args); } void TableServer::pushPeerMsg(Who who, const char *event, const json &args) { TableMsgContent msg(event, args); mMsgs.push_back(TableMsg { who, msg }); } void TableServer::pushBroadcastMsg(const char *event, const json &args) { TableMsgContent msg(event, args); for (Who who : whos::ALL4) mMsgs.push_back(TableMsg { who, msg }); } void TableServer::pushSystemMsg(const char *type, const json &args) { TableMsgContent msg(type, args); mMsgs.push_back(TableMsg { Who(), msg }); } TableServer::Msgs TableServer::popMsgs() { auto msgs = mMsgs; mMsgs.clear(); return msgs; } void TableServer::activateDrawn(json &map, const TableView &view) { using AC = ActCode; for (AC ac : { AC::SPIN_OUT, AC::SPIN_RIICHI, AC::TSUMO, AC::RYUUKYOKU }) if (view.myChoices().can(ac)) map[util::stringOf(ac)] = true; const Choices::ModeDrawn &mode = view.myChoices().drawn(); if (mode.swapOut) map[util::stringOf(AC::SWAP_OUT)] = (1 << 13) - 1; if (!mode.swapRiichis.empty()) { const auto &closed = view.myHand().closed(); map[util::stringOf(AC::SWAP_RIICHI)] = createSwapMask(closed, mode.swapRiichis); } if (!mode.ankans.empty()) map[util::stringOf(AC::ANKAN)] = mode.ankans.range(); if (!mode.kakans.empty()) { std::vector<int> kakans; for (int i : mode.kakans) kakans.push_back(i); map[util::stringOf(AC::KAKAN)] = kakans; } } void TableServer::activateBark(json &map, const TableView &view) { using AC = saki::ActCode; std::array<AC, 7> just { AC::PASS, AC::CHII_AS_LEFT, AC::CHII_AS_MIDDLE, AC::CHII_AS_RIGHT, AC::PON, AC::DAIMINKAN, AC::RON }; for (AC ac : just) if (view.myChoices().can(ac)) map[util::stringOf(ac)] = true; } void TableServer::activateIrsCheck(json &map, const TableView &view) { const Choices::ModeIrsCheck &mode = view.myChoices().irsCheck(); json args; args["name"] = mode.name; json items; for (const auto &item : mode.list) items.push_back(item); args["items"] = items; map[util::stringOf(saki::ActCode::IRS_CHECK)] = args; } } // namespace saki
26.018553
88
0.601897
rolevax
9c1cf4ed842d3c5fc0161c8f691ca8ddfabba2cb
8,095
hpp
C++
third_party/libosmium/include/osmium/index/detail/vector_map.hpp
Mapotempo/osrm-backend
a62c10321c0a269e218ab4164c4ccd132048f271
[ "BSD-2-Clause" ]
1
2016-11-29T15:02:40.000Z
2016-11-29T15:02:40.000Z
third_party/libosmium/include/osmium/index/detail/vector_map.hpp
aaronbenz/osrm-backend
758d4023050d1f49971f919cea872a2276dafe14
[ "BSD-2-Clause" ]
1
2019-02-04T18:10:57.000Z
2019-02-04T18:10:57.000Z
third_party/libosmium/include/osmium/index/detail/vector_map.hpp
Mapotempo/osrm-backend
a62c10321c0a269e218ab4164c4ccd132048f271
[ "BSD-2-Clause" ]
null
null
null
#ifndef OSMIUM_INDEX_DETAIL_VECTOR_MAP_HPP #define OSMIUM_INDEX_DETAIL_VECTOR_MAP_HPP /* This file is part of Osmium (http://osmcode.org/libosmium). Copyright 2013-2015 Jochen Topf <jochen@topf.org> and others (see README). Boost Software License - Version 1.0 - August 17th, 2003 Permission is hereby granted, free of charge, to any person or organization obtaining a copy of the software and accompanying documentation covered by this license (the "Software") to use, reproduce, display, distribute, execute, and transmit the Software, and to prepare derivative works of the Software, and to permit third-parties to whom the Software is furnished to do so, all subject to the following: The copyright notices in the Software and this entire statement, including the above license grant, this restriction and the following disclaimer, must be included in all copies of the Software, in whole or in part, and all derivative works of the Software, unless such copies or derivative works are solely in the form of machine-executable object code generated by a source language processor. 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, TITLE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <algorithm> #include <cstddef> #include <stdexcept> #include <utility> #include <osmium/index/index.hpp> #include <osmium/index/map.hpp> #include <osmium/io/detail/read_write.hpp> namespace osmium { namespace index { namespace map { template <class TVector, typename TId, typename TValue> class VectorBasedDenseMap : public Map<TId, TValue> { TVector m_vector; public: typedef TValue element_type; typedef TVector vector_type; typedef typename vector_type::iterator iterator; typedef typename vector_type::const_iterator const_iterator; VectorBasedDenseMap() : m_vector() { } explicit VectorBasedDenseMap(int fd) : m_vector(fd) { } ~VectorBasedDenseMap() = default; void reserve(const size_t size) override final { m_vector.reserve(size); } void set(const TId id, const TValue value) override final { if (size() <= id) { m_vector.resize(id+1); } m_vector[id] = value; } const TValue get(const TId id) const override final { try { const TValue& value = m_vector.at(id); if (value == osmium::index::empty_value<TValue>()) { not_found_error(id); } return value; } catch (std::out_of_range&) { not_found_error(id); } } size_t size() const override final { return m_vector.size(); } size_t byte_size() const { return m_vector.size() * sizeof(element_type); } size_t used_memory() const override final { return sizeof(TValue) * size(); } void clear() override final { m_vector.clear(); m_vector.shrink_to_fit(); } void dump_as_array(const int fd) override final { osmium::io::detail::reliable_write(fd, reinterpret_cast<const char*>(m_vector.data()), byte_size()); } iterator begin() { return m_vector.begin(); } iterator end() { return m_vector.end(); } const_iterator cbegin() const { return m_vector.cbegin(); } const_iterator cend() const { return m_vector.cend(); } const_iterator begin() const { return m_vector.cbegin(); } const_iterator end() const { return m_vector.cend(); } }; // class VectorBasedDenseMap template <typename TId, typename TValue, template<typename...> class TVector> class VectorBasedSparseMap : public Map<TId, TValue> { public: typedef typename std::pair<TId, TValue> element_type; typedef TVector<element_type> vector_type; typedef typename vector_type::iterator iterator; typedef typename vector_type::const_iterator const_iterator; private: vector_type m_vector; public: VectorBasedSparseMap() : m_vector() { } VectorBasedSparseMap(int fd) : m_vector(fd) { } ~VectorBasedSparseMap() override final = default; void set(const TId id, const TValue value) override final { m_vector.push_back(element_type(id, value)); } const TValue get(const TId id) const override final { const element_type element { id, osmium::index::empty_value<TValue>() }; const auto result = std::lower_bound(m_vector.begin(), m_vector.end(), element, [](const element_type& a, const element_type& b) { return a.first < b.first; }); if (result == m_vector.end() || result->first != id) { not_found_error(id); } else { return result->second; } } size_t size() const override final { return m_vector.size(); } size_t byte_size() const { return m_vector.size() * sizeof(element_type); } size_t used_memory() const override final { return sizeof(element_type) * size(); } void clear() override final { m_vector.clear(); m_vector.shrink_to_fit(); } void sort() override final { std::sort(m_vector.begin(), m_vector.end()); } void dump_as_list(const int fd) override final { osmium::io::detail::reliable_write(fd, reinterpret_cast<const char*>(m_vector.data()), byte_size()); } iterator begin() { return m_vector.begin(); } iterator end() { return m_vector.end(); } const_iterator cbegin() const { return m_vector.cbegin(); } const_iterator cend() const { return m_vector.cend(); } const_iterator begin() const { return m_vector.cbegin(); } const_iterator end() const { return m_vector.cend(); } }; // class VectorBasedSparseMap } // namespace map } // namespace index } // namespace osmium #endif // OSMIUM_INDEX_DETAIL_VECTOR_MAP_HPP
32.773279
150
0.519704
Mapotempo
9c1e39c17bd386cbcb84789c9d7bbb31e03eed7d
12,261
cpp
C++
src/server/scripts/Kalimdor/Zones/ashenvale.cpp
FrenchCORE/OLD_FrenchCORE
edf1a2859246493c0667b44497c4bbb0fe718cbd
[ "OpenSSL" ]
1
2019-12-03T18:41:39.000Z
2019-12-03T18:41:39.000Z
src/server/scripts/Kalimdor/Zones/ashenvale.cpp
FrenchCORE/OLD_FrenchCORE
edf1a2859246493c0667b44497c4bbb0fe718cbd
[ "OpenSSL" ]
null
null
null
src/server/scripts/Kalimdor/Zones/ashenvale.cpp
FrenchCORE/OLD_FrenchCORE
edf1a2859246493c0667b44497c4bbb0fe718cbd
[ "OpenSSL" ]
null
null
null
/* * Copyright (C) 2005 - 2012 MaNGOS <http://www.getmangos.com/> * * Copyright (C) 2008 - 2012 Trinity <http://www.trinitycore.org/> * * Copyright (C) 2006 - 2012 ScriptDev2 <http://www.scriptdev2.com/> * * Copyright (C) 2012 - 2012 FrenchCORE <http://www.frcore.com/> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ /* ScriptData SDName: Ashenvale SD%Complete: 70 SDComment: Quest support: 6544, 6482 SDCategory: Ashenvale Forest EndScriptData */ /* ContentData npc_torek npc_ruul_snowhoof EndContentData */ #include "ScriptPCH.h" #include "ScriptedEscortAI.h" /*#### # npc_torek ####*/ #define SAY_READY -1000106 #define SAY_MOVE -1000107 #define SAY_PREPARE -1000108 #define SAY_WIN -1000109 #define SAY_END -1000110 #define SPELL_REND 11977 #define SPELL_THUNDERCLAP 8078 #define QUEST_TOREK_ASSULT 6544 #define ENTRY_SPLINTERTREE_RAIDER 12859 #define ENTRY_DURIEL 12860 #define ENTRY_SILVERWING_SENTINEL 12896 #define ENTRY_SILVERWING_WARRIOR 12897 class npc_torek: public CreatureScript { public: npc_torek() : CreatureScript("npc_torek") { } struct npc_torekAI: public npc_escortAI { npc_torekAI(Creature *c) : npc_escortAI(c) { } uint32 Rend_Timer; uint32 Thunderclap_Timer; bool Completed; void WaypointReached(uint32 i) { Player* pPlayer = GetPlayerForEscort(); if (!pPlayer) return; switch (i) { case 1: DoScriptText(SAY_MOVE, me, pPlayer); break; case 8: DoScriptText(SAY_PREPARE, me, pPlayer); break; case 19: //TODO: verify location and creatures amount. me->SummonCreature(ENTRY_DURIEL, 1776.73f, -2049.06f, 109.83f, 1.54f, TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT, 25000); me->SummonCreature(ENTRY_SILVERWING_SENTINEL, 1774.64f, -2049.41f, 109.83f, 1.40f, TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT, 25000); me->SummonCreature(ENTRY_SILVERWING_WARRIOR, 1778.73f, -2049.50f, 109.83f, 1.67f, TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT, 25000); break; case 20: DoScriptText(SAY_WIN, me, pPlayer); Completed = true; if (pPlayer) pPlayer->GroupEventHappens(QUEST_TOREK_ASSULT, me); break; case 21: DoScriptText(SAY_END, me, pPlayer); break; } } void Reset() { Rend_Timer = 5000; Thunderclap_Timer = 8000; Completed = false; } void EnterCombat(Unit* /*who*/) { } void JustSummoned(Creature* summoned) { summoned->AI()->AttackStart(me); } void UpdateAI(const uint32 diff) { npc_escortAI::UpdateAI(diff); if (!UpdateVictim()) return; if (Rend_Timer <= diff) { DoCast(me->getVictim(), SPELL_REND); Rend_Timer = 20000; } else Rend_Timer -= diff; if (Thunderclap_Timer <= diff) { DoCast(me, SPELL_THUNDERCLAP); Thunderclap_Timer = 30000; } else Thunderclap_Timer -= diff; } }; CreatureAI* GetAI(Creature* creature) const { return new npc_torekAI(creature); } bool OnQuestAccept(Player* player, Creature* creature, Quest const* quest) { if (quest->GetQuestId() == QUEST_TOREK_ASSULT) { //TODO: find companions, make them follow Torek, at any time (possibly done by core/database in future?) DoScriptText(SAY_READY, creature, player); creature->setFaction(113); if (npc_escortAI* pEscortAI = CAST_AI(npc_torekAI, creature->AI())) pEscortAI->Start(true, true, player->GetGUID()); } return true; } }; /*#### # npc_ruul_snowhoof ####*/ #define QUEST_FREEDOM_TO_RUUL 6482 #define GO_CAGE 178147 class npc_ruul_snowhoof: public CreatureScript { public: npc_ruul_snowhoof() : CreatureScript("npc_ruul_snowhoof") { } struct npc_ruul_snowhoofAI: public npc_escortAI { npc_ruul_snowhoofAI(Creature *c) : npc_escortAI(c) { } void WaypointReached(uint32 i) { Player* pPlayer = GetPlayerForEscort(); if (!pPlayer) return; switch (i) { case 0: { me->SetUInt32Value(UNIT_FIELD_BYTES_1, 0); GameObject* Cage = me->FindNearestGameObject(GO_CAGE, 20); if (Cage) Cage->SetGoState(GO_STATE_ACTIVE); break; } case 13: me->SummonCreature(3922, 3449.218018f, -587.825073f, 174.978867f, 4.714445f, TEMPSUMMON_DEAD_DESPAWN, 60000); me->SummonCreature(3921, 3446.384521f, -587.830872f, 175.186279f, 4.714445f, TEMPSUMMON_DEAD_DESPAWN, 60000); me->SummonCreature(3926, 3444.218994f, -587.835327f, 175.380600f, 4.714445f, TEMPSUMMON_DEAD_DESPAWN, 60000); break; case 19: me->SummonCreature(3922, 3508.344482f, -492.024261f, 186.929031f, 4.145029f, TEMPSUMMON_DEAD_DESPAWN, 60000); me->SummonCreature(3921, 3506.265625f, -490.531006f, 186.740128f, 4.239277f, TEMPSUMMON_DEAD_DESPAWN, 60000); me->SummonCreature(3926, 3503.682373f, -489.393799f, 186.629684f, 4.349232f, TEMPSUMMON_DEAD_DESPAWN, 60000); break; case 21: { if (pPlayer) pPlayer->GroupEventHappens(QUEST_FREEDOM_TO_RUUL, me); break; } } } void EnterCombat(Unit* /*who*/) { } void Reset() { GameObject* Cage = me->FindNearestGameObject(GO_CAGE, 20); if (Cage) Cage->SetGoState(GO_STATE_READY); } void JustSummoned(Creature* summoned) { summoned->AI()->AttackStart(me); } void UpdateAI(const uint32 diff) { npc_escortAI::UpdateAI(diff); } }; CreatureAI* GetAI(Creature* creature) const { return new npc_ruul_snowhoofAI(creature); } bool OnQuestAccept(Player* player, Creature* creature, Quest const* quest) { if (quest->GetQuestId() == QUEST_FREEDOM_TO_RUUL) { creature->setFaction(113); if (npc_escortAI* pEscortAI = CAST_AI(npc_ruul_snowhoofAI, (creature->AI()))) pEscortAI->Start(true, false, player->GetGUID()); } return true; } }; enum eEnums { SAY_MUG_START1 = -1800054, SAY_MUG_START2 = -1800055, SAY_MUG_BRAZIER = -1800056, SAY_MUG_BRAZIER_WAIT = -1800057, SAY_MUG_ON_GUARD = -1800058, SAY_MUG_REST = -1800059, SAY_MUG_DONE = -1800060, SAY_MUG_GRATITUDE = -1800061, SAY_MUG_PATROL = -1800062, SAY_MUG_RETURN = -1800063, QUEST_VORSHA = 6641, GO_NAGA_BRAZIER = 178247, NPC_WRATH_RIDER = 3713, NPC_WRATH_SORCERESS = 3717, NPC_WRATH_RAZORTAIL = 3712, NPC_WRATH_PRIESTESS = 3944, NPC_WRATH_MYRMIDON = 3711, NPC_WRATH_SEAWITCH = 3715, NPC_VORSHA = 12940, NPC_MUGLASH = 12717 }; static float m_afFirstNagaCoord[3][3] = { { 3603.504150f, 1122.631104f, 1.635f }, // rider { 3589.293945f, 1148.664063f, 5.565f }, // sorceress { 3609.925537f, 1168.759521f, -1.168f } // razortail }; static float m_afSecondNagaCoord[3][3] = { { 3609.925537f, 1168.759521f, -1.168f }, // witch { 3645.652100f, 1139.425415f, 1.322f }, // priest { 3583.602051f, 1128.405762f, 2.347f } // myrmidon }; static float m_fVorshaCoord[] = { 3633.056885f, 1172.924072f, -5.388f }; class npc_muglash: public CreatureScript { public: npc_muglash() : CreatureScript("npc_muglash") { } struct npc_muglashAI: public npc_escortAI { npc_muglashAI(Creature* pCreature) : npc_escortAI(pCreature) { } uint32 m_uiWaveId; uint32 m_uiEventTimer; bool m_bIsBrazierExtinguished; void JustSummoned(Creature* pSummoned) { pSummoned->AI()->AttackStart(me); } void WaypointReached(uint32 i) { Player* pPlayer = GetPlayerForEscort(); switch (i) { case 0: if (pPlayer) DoScriptText(SAY_MUG_START2, me, pPlayer); break; case 24: if (pPlayer) DoScriptText(SAY_MUG_BRAZIER, me, pPlayer); if (GameObject* pGo = GetClosestGameObjectWithEntry(me, GO_NAGA_BRAZIER, INTERACTION_DISTANCE*2)) { pGo->RemoveFlag(GAMEOBJECT_FLAGS, GO_FLAG_UNK1); SetEscortPaused(true); } break; case 25: DoScriptText(SAY_MUG_GRATITUDE, me); if (pPlayer) pPlayer->GroupEventHappens(QUEST_VORSHA, me); break; case 26: DoScriptText(SAY_MUG_PATROL, me); break; case 27: DoScriptText(SAY_MUG_RETURN, me); break; } } void EnterCombat(Unit* /*pWho*/) { if (Player* pPlayer = GetPlayerForEscort()) if (HasEscortState(STATE_ESCORT_PAUSED)) { if (urand(0, 1)) DoScriptText(SAY_MUG_ON_GUARD, me, pPlayer); return; } } void Reset() { m_uiEventTimer = 10000; m_uiWaveId = 0; m_bIsBrazierExtinguished = false; } void JustDied(Unit* /*pKiller*/) { Player* pPlayer = GetPlayerForEscort(); if (HasEscortState(STATE_ESCORT_ESCORTING)) { if (pPlayer) { pPlayer->FailQuest(QUEST_VORSHA); } } } void DoWaveSummon() { switch (m_uiWaveId) { case 1: me->SummonCreature(NPC_WRATH_RIDER, m_afFirstNagaCoord[0][0], m_afFirstNagaCoord[0][1], m_afFirstNagaCoord[0][2], 0.0f, TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT, 60000); me->SummonCreature(NPC_WRATH_SORCERESS, m_afFirstNagaCoord[1][0], m_afFirstNagaCoord[1][1], m_afFirstNagaCoord[1][2], 0.0f, TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT, 60000); me->SummonCreature(NPC_WRATH_RAZORTAIL, m_afFirstNagaCoord[2][0], m_afFirstNagaCoord[2][1], m_afFirstNagaCoord[2][2], 0.0f, TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT, 60000); break; case 2: me->SummonCreature(NPC_WRATH_PRIESTESS, m_afSecondNagaCoord[0][0], m_afSecondNagaCoord[0][1], m_afSecondNagaCoord[0][2], 0.0f, TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT, 60000); me->SummonCreature(NPC_WRATH_MYRMIDON, m_afSecondNagaCoord[1][0], m_afSecondNagaCoord[1][1], m_afSecondNagaCoord[1][2], 0.0f, TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT, 60000); me->SummonCreature(NPC_WRATH_SEAWITCH, m_afSecondNagaCoord[2][0], m_afSecondNagaCoord[2][1], m_afSecondNagaCoord[2][2], 0.0f, TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT, 60000); break; case 3: me->SummonCreature(NPC_VORSHA, m_fVorshaCoord[0], m_fVorshaCoord[1], m_fVorshaCoord[2], 0.0f, TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT, 60000); break; case 4: SetEscortPaused(false); DoScriptText(SAY_MUG_DONE, me); break; } } void UpdateAI(const uint32 uiDiff) { npc_escortAI::UpdateAI(uiDiff); if (!me->getVictim()) { if (HasEscortState(STATE_ESCORT_PAUSED) && m_bIsBrazierExtinguished) { if (m_uiEventTimer < uiDiff) { ++m_uiWaveId; DoWaveSummon(); m_uiEventTimer = 10000; } else m_uiEventTimer -= uiDiff; } return; } DoMeleeAttackIfReady(); } }; CreatureAI* GetAI(Creature* pCreature) const { return new npc_muglashAI(pCreature); } bool OnQuestAccept(Player* player, Creature* creature, Quest const* quest) { if (quest->GetQuestId() == QUEST_VORSHA) { if (npc_muglashAI* pEscortAI = CAST_AI(npc_muglashAI, creature->AI())) { DoScriptText(SAY_MUG_START1, creature); creature->setFaction(113); pEscortAI->Start(true, true, player->GetGUID()); } } return true; } }; class go_naga_brazier: public GameObjectScript { public: go_naga_brazier() : GameObjectScript("go_naga_brazier") { } bool OnGossipHello(Player* /*player*/, GameObject* go) { if (Creature* creature = GetClosestCreatureWithEntry(go, NPC_MUGLASH, INTERACTION_DISTANCE*2)) { if (npc_muglash::npc_muglashAI* pEscortAI = CAST_AI(npc_muglash::npc_muglashAI, creature->AI())) { DoScriptText(SAY_MUG_BRAZIER_WAIT, creature); pEscortAI->m_bIsBrazierExtinguished = true; return false; } } return true; } }; void AddSC_ashenvale() { new npc_torek(); new npc_ruul_snowhoof(); new npc_muglash(); new go_naga_brazier(); }
25.704403
107
0.684854
FrenchCORE
9c1fc9a65b9d8750ed8b52b397e00c0176465aa4
3,229
cpp
C++
ARP/Utils/Mutex.cpp
dechterlab/CVO
1085223ef383584837d6ac4ff723b9ff54b05071
[ "MIT" ]
null
null
null
ARP/Utils/Mutex.cpp
dechterlab/CVO
1085223ef383584837d6ac4ff723b9ff54b05071
[ "MIT" ]
null
null
null
ARP/Utils/Mutex.cpp
dechterlab/CVO
1085223ef383584837d6ac4ff723b9ff54b05071
[ "MIT" ]
null
null
null
#include <stdlib.h> #if defined WINDOWS || _WINDOWS #include <windows.h> #else #include <pthread.h> #include "sched.h" #endif // WINDOWS #include <iostream> #include "Utils/Mutex.h" namespace ARE { namespace utils { RecursiveMutex::RecursiveMutex( #ifdef USE_MUTEX_WITH_NAME const std::string *pName #else void #endif // USE_MUTEX_WITH_NAME ) throw() { #ifdef USE_MUTEX_WITH_NAME setName(pName) ; #endif // USE_MUTEX_WITH_NAME #if defined WINDOWS || _WINDOWS InitializeCriticalSection(&_CS) ; #elif defined LINUX pthread_mutexattr_t mutexAttributes ; pthread_mutexattr_init(&mutexAttributes) ; pthread_mutexattr_settype(&mutexAttributes, PTHREAD_MUTEX_RECURSIVE_NP) ; pthread_mutex_init(&_RM, &mutexAttributes) ; pthread_mutexattr_destroy(&mutexAttributes) ; #endif } RecursiveMutex::~RecursiveMutex(void) throw() { #if defined WINDOWS || _WINDOWS DeleteCriticalSection(&_CS) ; #elif defined LINUX pthread_mutex_destroy(&_RM) ; #endif } void RecursiveMutex::setName(const std::string *pName) throw() { #ifdef USE_MUTEX_WITH_NAME if (pName) _Name = *pName ; else _Name = "" ; #endif // USE_MUTEX_WITH_NAME } void RecursiveMutex::lock(void) throw() { #if defined WINDOWS || _WINDOWS //#ifdef USE_MUTEX_WITH_NAME // if (_Name.length() > 0) //g_log << maui::util::logMessage(10, "--------MUTEX: [" + _Name + "] :LOCK BEGIN\n", true); //#endif // USE_MUTEX_WITH_NAME // else // g_log << maui::util::logMessage(10, "--------MUTEX: [] :LOCK BEGIN", true); //std::cout << "--------MUTEX: [" << _Name << "] :LOCK BEGIN" << std::endl; EnterCriticalSection(&_CS) ; //std::cout << "--------MUTEX: [" << _Name << "] :LOCK GOT" << std::endl; //#ifdef USE_MUTEX_WITH_NAME // if (_Name.length() > 0) //g_log << maui::util::logMessage(10, "--------MUTEX: [" + _Name + "] :LOCK GOT\n", true); //#endif // USE_MUTEX_WITH_NAME // else // g_log << maui::util::logMessage(10, "--------MUTEX: [] :LOCK GOT", true); #elif defined LINUX pthread_mutex_lock(&_RM) ; //std::cout << "--------MUTEX: " << this << ": LOCKED" << std::endl; #endif } bool RecursiveMutex::trylock(void) throw() { #if defined WINDOWS || _WINDOWS // does not compile in VC++6.0 // return TryEnterCriticalSection(&_CS); #elif defined LINUX // TODO : implement for linux #endif return false ; } void RecursiveMutex::unlock(void) throw() { #if defined WINDOWS || _WINDOWS //#ifdef USE_MUTEX_WITH_NAME // if (_Name.length() > 0) //g_log << maui::util::logMessage(10, "--------MUTEX: [" + _Name + "] :unLOCK BEGIN\n", true); //#endif // USE_MUTEX_WITH_NAME // else // g_log << maui::util::logMessage(10, "--------MUTEX: [] :unLOCK BEGIN", true); //std::cout << "--------MUTEX: [" << _Name << "] :unLOCK BEGIN" << std::endl; LeaveCriticalSection(&_CS) ; //#ifdef USE_MUTEX_WITH_NAME // if (_Name.length() > 0) //g_log << maui::util::logMessage(10, "--------MUTEX: [" + _Name + "] :unLOCK GOT\n", true); //#endif // USE_MUTEX_WITH_NAME // else // g_log << maui::util::logMessage(10, "--------MUTEX: [] :unLOCK GOT", true); //std::cout << "--------MUTEX: [" << _Name << "] :unLOCK GOT" << std::endl; #elif defined LINUX pthread_mutex_unlock(&_RM) ; //std::cout << "--------MUTEX: " << this << ": UNLOCKED" << std::endl; #endif } } }
25.832
96
0.648498
dechterlab
9c22a03a33ab84f85dbcdcc91a432202931503bf
1,244
cpp
C++
server/Common/Packets/GCCharMoveResult.cpp
viticm/web-pap
7c9b1f49d9ba8d8e40f8fddae829c2e414ccfeca
[ "BSD-3-Clause" ]
3
2018-06-19T21:37:38.000Z
2021-07-31T21:51:40.000Z
server/Common/Packets/GCCharMoveResult.cpp
viticm/web-pap
7c9b1f49d9ba8d8e40f8fddae829c2e414ccfeca
[ "BSD-3-Clause" ]
null
null
null
server/Common/Packets/GCCharMoveResult.cpp
viticm/web-pap
7c9b1f49d9ba8d8e40f8fddae829c2e414ccfeca
[ "BSD-3-Clause" ]
13
2015-01-30T17:45:06.000Z
2022-01-06T02:29:34.000Z
#include "stdafx.h" // GCCharMoveResult.cpp #include "GCCharMoveResult.h" BOOL GCCharMoveResult::Read( SocketInputStream& iStream ) { __ENTER_FUNCTION iStream.Read( (CHAR*)(&m_nHandleID), sizeof(m_nHandleID)); iStream.Read( (CHAR*)(&m_nResult), sizeof(m_nResult)); iStream.Read( (CHAR*)(&m_yNumTargetPos), sizeof(m_yNumTargetPos)); if ( m_yNumTargetPos>0 && m_yNumTargetPos<=MAX_CHAR_PATH_NODE_NUMBER ) iStream.Read( (CHAR*)(&m_aTargetPos), sizeof(WORLD_POS) * m_yNumTargetPos ); return TRUE ; __LEAVE_FUNCTION return FALSE ; } BOOL GCCharMoveResult::Write( SocketOutputStream& oStream )const { __ENTER_FUNCTION oStream.Write( (CHAR*)(&m_nHandleID), sizeof(m_nHandleID)); oStream.Write( (CHAR*)(&m_nResult), sizeof(m_nResult)); oStream.Write( (CHAR*)(&m_yNumTargetPos), sizeof(m_yNumTargetPos)); if ( m_yNumTargetPos>0 && m_yNumTargetPos<=MAX_CHAR_PATH_NODE_NUMBER ) oStream.Write( (CHAR*)(&m_aTargetPos), sizeof(WORLD_POS) * m_yNumTargetPos ); return TRUE ; __LEAVE_FUNCTION return FALSE ; } UINT GCCharMoveResult::Execute( Player* pPlayer ) { __ENTER_FUNCTION return GCCharMoveResultHandler::Execute( this, pPlayer ) ; __LEAVE_FUNCTION return FALSE ; }
24.392157
85
0.720257
viticm
9c269e91f9e590ddae266d807f163767f4371b87
225
cpp
C++
3rdparty/build_opencv-4.5.2/modules/imgproc/box_filter.sse4_1.cpp
LordOfTheUnicorn/trdrop
6da4bf1528878e90cf14232dfb4adeec3458ee0f
[ "MIT" ]
null
null
null
3rdparty/build_opencv-4.5.2/modules/imgproc/box_filter.sse4_1.cpp
LordOfTheUnicorn/trdrop
6da4bf1528878e90cf14232dfb4adeec3458ee0f
[ "MIT" ]
7
2021-05-24T22:57:32.000Z
2021-08-23T05:32:30.000Z
3rdparty/build_opencv-4.5.2/modules/imgproc/box_filter.sse4_1.cpp
LordOfTheUnicorn/trdrop
6da4bf1528878e90cf14232dfb4adeec3458ee0f
[ "MIT" ]
null
null
null
#include "/Users/unicorn1343/Documents/GitHub/trdrop/3rdParty/opencv-4.5.2/modules/imgproc/src/precomp.hpp" #include "/Users/unicorn1343/Documents/GitHub/trdrop/3rdParty/opencv-4.5.2/modules/imgproc/src/box_filter.simd.hpp"
56.25
115
0.813333
LordOfTheUnicorn
9c27bdef6458b3506e998bc543a67cad4f4fb5c9
1,903
hpp
C++
include/cxxmidi/output/default.hpp
MisterBalboa/midi-server
62896d3342c11e063e12672edcd206a7e8cf39c9
[ "MIT" ]
30
2018-05-01T22:27:23.000Z
2022-01-19T13:17:56.000Z
include/cxxmidi/output/default.hpp
MisterBalboa/midi-server
62896d3342c11e063e12672edcd206a7e8cf39c9
[ "MIT" ]
2
2019-11-16T21:50:02.000Z
2020-02-08T09:18:19.000Z
include/cxxmidi/output/default.hpp
MisterBalboa/midi-server
62896d3342c11e063e12672edcd206a7e8cf39c9
[ "MIT" ]
8
2017-10-13T14:30:23.000Z
2021-06-28T02:55:53.000Z
/* ***************************************************************************** Copyright (c) 2018 Stan Chlebicki 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 INCLUDE_CXXMIDI_OUTPUT_DEFAULT_HPP_ #define INCLUDE_CXXMIDI_OUTPUT_DEFAULT_HPP_ #ifdef _WIN32 // Windows 32-bit and 64-bit #include <cxxmidi/output/windows.hpp> namespace cxxmidi { namespace output { typedef output::windows Default; } // namespace output } // namespace cxxmidi #elif __APPLE__ // Mac OS X #error "CxxMidi: OSX Midi output not yet implemented" #elif __unix // Linux, *BSD, Mac OS X #include <cxxmidi/output/linux/alsa.hpp> namespace cxxmidi { namespace output { typedef output::linuxo::Alsa Default; } // namespace output } // namespace cxxmidi #else #error "CxxMidi: couldn't determine the OS" #endif #endif // INCLUDE_CXXMIDI_OUTPUT_DEFAULT_HPP_
40.489362
80
0.723069
MisterBalboa
9c2b099ae17c1befbe4e68423c9f76b37562deb8
8,952
hpp
C++
libs/network/include/network/generics/requesting_queue.hpp
devjsc/ledger-1
2aa68e05b9f9c10a9971fc8ddf4848695511af3c
[ "Apache-2.0" ]
3
2019-07-11T08:49:27.000Z
2021-09-07T16:49:15.000Z
libs/network/include/network/generics/requesting_queue.hpp
devjsc/ledger-1
2aa68e05b9f9c10a9971fc8ddf4848695511af3c
[ "Apache-2.0" ]
null
null
null
libs/network/include/network/generics/requesting_queue.hpp
devjsc/ledger-1
2aa68e05b9f9c10a9971fc8ddf4848695511af3c
[ "Apache-2.0" ]
2
2019-07-13T12:45:22.000Z
2021-03-12T08:48:57.000Z
#pragma once //------------------------------------------------------------------------------ // // Copyright 2018-2019 Fetch.AI Limited // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //------------------------------------------------------------------------------ #include "core/serializers/stl_types.hpp" #include "network/generics/promise_of.hpp" #include "network/service/promise.hpp" #include <algorithm> #include <atomic> #include <deque> #include <iterator> #include <unordered_map> namespace fetch { namespace network { template <typename K, typename R, typename P = PromiseOf<R>, typename H = std::hash<K>> class RequestingQueueOf { public: using Key = K; using Promised = R; using Mutex = fetch::mutex::Mutex; using Lock = std::lock_guard<Mutex>; using Promise = P; using PromiseState = fetch::service::PromiseState; using PromiseMap = std::unordered_map<Key, Promise, H>; using KeySet = std::unordered_set<Key>; using Counter = std::atomic<std::size_t>; using Timepoint = typename Promise::Timepoint; struct SuccessfulResult { Key key; Promised promised; }; struct FailedResult { Key key; Promise promise; }; struct Counters { std::size_t completed; std::size_t failed; std::size_t pending; }; using SuccessfulResults = std::deque<SuccessfulResult>; using FailedResults = std::deque<FailedResult>; // Construction / Destruction RequestingQueueOf() = default; RequestingQueueOf(RequestingQueueOf const &) = delete; RequestingQueueOf(RequestingQueueOf &&) = delete; ~RequestingQueueOf() = default; bool Add(Key const &key, Promise const &promise); SuccessfulResults Get(std::size_t limit); FailedResults GetFailures(std::size_t limit); PromiseMap GetPending(); KeySet FilterOutInFlight(KeySet const &inputs); bool IsInFlight(Key const &key) const; Counters Resolve(); Counters Resolve(Timepoint const &time_point); bool HasCompletedPromises() const; bool HasFailedPromises() const; void DiscardFailures(); void DiscardCompleted(); // Operators RequestingQueueOf &operator=(RequestingQueueOf const &) = delete; RequestingQueueOf &operator=(RequestingQueueOf &&) = delete; private: mutable Mutex mutex_{__LINE__, __FILE__}; PromiseMap requests_; ///< The map of currently monitored promises SuccessfulResults completed_; ///< The map of completed promises FailedResults failed_; ///< The set of failed keys Counter num_completed_{0}; Counter num_failed_{0}; Counter num_pending_{0}; }; template <typename K, typename R, typename P, typename H> bool RequestingQueueOf<K, R, P, H>::Add(Key const &key, Promise const &promise) { bool success = false; { FETCH_LOCK(mutex_); if (requests_.find(key) == requests_.end()) { requests_.emplace(key, promise); ++num_pending_; success = true; } } return success; } template <typename K, typename R, typename P, typename H> typename RequestingQueueOf<K, R, P, H>::SuccessfulResults RequestingQueueOf<K, R, P, H>::Get( std::size_t limit) { FETCH_LOCK(mutex_); SuccessfulResults results; if (limit == 0) { assert(false); } else if (completed_.size() <= limit) { results = std::move(completed_); completed_.clear(); // needed? } else // (completed_.size() > limit) { // copy "limit" number of entries from the completed list std::copy_n(completed_.begin(), limit, std::inserter(results, results.begin())); // erase these entries from the completed map completed_.erase(completed_.begin(), completed_.begin() + static_cast<std::ptrdiff_t>(limit)); } return results; } template <typename K, typename R, typename P, typename H> typename RequestingQueueOf<K, R, P, H>::FailedResults RequestingQueueOf<K, R, P, H>::GetFailures( std::size_t limit) { FETCH_LOCK(mutex_); FailedResults results; if (limit == 0) { assert(false); } else if (failed_.size() <= limit) { results = std::move(failed_); failed_.clear(); // needed? } else // (completed_.size() > limit) { // copy "limit" number of entries from the completed list std::copy_n(failed_.begin(), limit, std::inserter(results, results.begin())); // erase these entries from the completed map failed_.erase(failed_.begin(), failed_.begin() + static_cast<std::ptrdiff_t>(limit)); } return results; } template <typename K, typename R, typename P, typename H> typename RequestingQueueOf<K, R, P, H>::PromiseMap RequestingQueueOf<K, R, P, H>::GetPending() { FETCH_LOCK(mutex_); PromiseMap pending = std::move(requests_); requests_.clear(); return pending; } template <typename K, typename R, typename P, typename H> typename RequestingQueueOf<K, R, P, H>::Counters RequestingQueueOf<K, R, P, H>::Resolve() { FETCH_LOCK(mutex_); auto iter = requests_.begin(); while (iter != requests_.end()) { auto const &key = iter->first; auto & promise = iter->second; switch (promise.GetState()) { case PromiseState::WAITING: ++iter; break; case PromiseState::SUCCESS: completed_.emplace_back(SuccessfulResult{key, promise.Get()}); ++num_completed_; --num_pending_; iter = requests_.erase(iter); break; case PromiseState::FAILED: case PromiseState::TIMEDOUT: failed_.emplace_back(FailedResult{key, promise}); ++num_failed_; --num_pending_; iter = requests_.erase(iter); break; default: break; } } // TODO(EJF): Not really sure why the value is here? num_completed_ = completed_.size(); num_pending_ = requests_.size(); num_failed_ = failed_.size(); return {completed_.size(), failed_.size(), requests_.size()}; } template <typename K, typename R, typename P, typename H> typename RequestingQueueOf<K, R, P, H>::Counters RequestingQueueOf<K, R, P, H>::Resolve( Timepoint const &time_point) { FETCH_LOCK(mutex_); auto iter = requests_.begin(); while (iter != requests_.end()) { auto const &key = iter->first; auto & promise = iter->second; switch (promise.GetState(time_point)) { case PromiseState::WAITING: ++iter; break; case PromiseState::SUCCESS: completed_.emplace_back(SuccessfulResult{key, promise.Get()}); ++num_completed_; --num_pending_; iter = requests_.erase(iter); break; case PromiseState::FAILED: case PromiseState::TIMEDOUT: failed_.emplace_back(FailedResult{key, promise}); ++num_failed_; --num_pending_; iter = requests_.erase(iter); break; default: break; } } // TODO(EJF): Not really sure why the value is here? num_completed_ = completed_.size(); num_pending_ = requests_.size(); num_failed_ = failed_.size(); return {completed_.size(), failed_.size(), requests_.size()}; } template <typename K, typename R, typename P, typename H> typename RequestingQueueOf<K, R, P, H>::KeySet RequestingQueueOf<K, R, P, H>::FilterOutInFlight( KeySet const &inputs) { FETCH_LOCK(mutex_); KeySet keys; std::copy_if(inputs.begin(), inputs.end(), std::inserter(keys, keys.begin()), [this](Key const &key) { return requests_.find(key) == requests_.end(); }); return keys; } template <typename K, typename R, typename P, typename H> bool RequestingQueueOf<K, R, P, H>::IsInFlight(Key const &key) const { FETCH_LOCK(mutex_); return requests_.find(key) != requests_.end(); } template <typename K, typename R, typename P, typename H> bool RequestingQueueOf<K, R, P, H>::HasCompletedPromises() const { FETCH_LOCK(mutex_); return !completed_.empty(); } template <typename K, typename R, typename P, typename H> bool RequestingQueueOf<K, R, P, H>::HasFailedPromises() const { FETCH_LOCK(mutex_); return !failed_.empty(); } template <typename K, typename R, typename P, typename H> void RequestingQueueOf<K, R, P, H>::DiscardFailures() { FETCH_LOCK(mutex_); failed_.clear(); } template <typename K, typename R, typename P, typename H> void RequestingQueueOf<K, R, P, H>::DiscardCompleted() { FETCH_LOCK(mutex_); completed_.clear(); } } // namespace network } // namespace fetch
27.209726
98
0.655719
devjsc
9c2b41de1df782579c724c982ec3080be14e211c
19,156
hpp
C++
libuavcan/include/dsdlc_generated/uavcan/protocol/GetDataTypeInfo.hpp
thiemar/vectorcontrol
6bc7bcfdcfb4216523195ab530babfbd9a974024
[ "MIT" ]
55
2015-06-04T22:36:53.000Z
2022-03-05T07:03:48.000Z
libuavcan/include/dsdlc_generated/uavcan/protocol/GetDataTypeInfo.hpp
donginhb/vectorcontrol
6bc7bcfdcfb4216523195ab530babfbd9a974024
[ "MIT" ]
20
2015-08-25T13:16:19.000Z
2019-12-11T07:52:35.000Z
libuavcan/include/dsdlc_generated/uavcan/protocol/GetDataTypeInfo.hpp
donginhb/vectorcontrol
6bc7bcfdcfb4216523195ab530babfbd9a974024
[ "MIT" ]
34
2015-08-25T13:40:29.000Z
2021-08-24T02:18:37.000Z
/* * UAVCAN data structure definition for libuavcan. * * Autogenerated, do not edit. * * Source file: /Users/bendyer/Projects/ARM/workspace/libuavcan/dsdl/uavcan/protocol/2.GetDataTypeInfo.uavcan */ #ifndef UAVCAN_PROTOCOL_GETDATATYPEINFO_HPP_INCLUDED #define UAVCAN_PROTOCOL_GETDATATYPEINFO_HPP_INCLUDED #include <uavcan/build_config.hpp> #include <uavcan/node/global_data_type_registry.hpp> #include <uavcan/marshal/types.hpp> #include <uavcan/protocol/DataTypeKind.hpp> /******************************* Source text ********************************** # # Get the implementation details of a given data type. # # Request is interpreted as follows: # - If the field 'name' is empty, the fields 'kind' and 'id' will be used to identify the data type. # - If the field 'name' is non-empty, it will be used to identify the data type; the # fields 'kind' and 'id' will be ignored. # uint16 id # Ignored if 'name' is non-empty DataTypeKind kind # Ignored if 'name' is non-empty uint8[<=80] name # Full data type name, e.g. "uavcan.protocol.GetDataTypeInfo" --- uint64 signature # Data type signature; valid only if the data type is known (see FLAG_KNOWN) uint16 id # Valid only if the data type is known (see FLAG_KNOWN) DataTypeKind kind # Ditto uint8 FLAG_KNOWN = 1 # This data type is defined uint8 FLAG_SUBSCRIBED = 2 # Subscribed to messages of this type uint8 FLAG_PUBLISHING = 4 # Publishing messages of this type uint8 FLAG_SERVING = 8 # Providing service of this type uint8 flags uint8[<=80] name # Full data type name ******************************************************************************/ /********************* DSDL signature source definition *********************** uavcan.protocol.GetDataTypeInfo saturated uint16 id uavcan.protocol.DataTypeKind kind saturated uint8[<=80] name --- saturated uint64 signature saturated uint16 id uavcan.protocol.DataTypeKind kind saturated uint8 flags saturated uint8[<=80] name ******************************************************************************/ #undef id #undef kind #undef name #undef signature #undef id #undef kind #undef flags #undef name #undef FLAG_KNOWN #undef FLAG_SUBSCRIBED #undef FLAG_PUBLISHING #undef FLAG_SERVING namespace uavcan { namespace protocol { struct UAVCAN_EXPORT GetDataTypeInfo_ { template <int _tmpl> struct Request_ { typedef const Request_<_tmpl>& ParameterType; typedef Request_<_tmpl>& ReferenceType; struct ConstantTypes { }; struct FieldTypes { typedef ::uavcan::IntegerSpec< 16, ::uavcan::SignednessUnsigned, ::uavcan::CastModeSaturate > id; typedef ::uavcan::protocol::DataTypeKind kind; typedef ::uavcan::Array< ::uavcan::IntegerSpec< 8, ::uavcan::SignednessUnsigned, ::uavcan::CastModeSaturate >, ::uavcan::ArrayModeDynamic, 80 > name; }; enum { MinBitLen = FieldTypes::id::MinBitLen + FieldTypes::kind::MinBitLen + FieldTypes::name::MinBitLen }; enum { MaxBitLen = FieldTypes::id::MaxBitLen + FieldTypes::kind::MaxBitLen + FieldTypes::name::MaxBitLen }; // Constants // Fields typename ::uavcan::StorageType< typename FieldTypes::id >::Type id; typename ::uavcan::StorageType< typename FieldTypes::kind >::Type kind; typename ::uavcan::StorageType< typename FieldTypes::name >::Type name; Request_() : id() , kind() , name() { ::uavcan::StaticAssert<_tmpl == 0>::check(); // Usage check #if UAVCAN_DEBUG /* * Cross-checking MaxBitLen provided by the DSDL compiler. * This check shall never be performed in user code because MaxBitLen value * actually depends on the nested types, thus it is not invariant. */ ::uavcan::StaticAssert<671 == MaxBitLen>::check(); #endif } bool operator==(ParameterType rhs) const; bool operator!=(ParameterType rhs) const { return !operator==(rhs); } /** * This comparison is based on @ref uavcan::areClose(), which ensures proper comparison of * floating point fields at any depth. */ bool isClose(ParameterType rhs) const; static int encode(ParameterType self, ::uavcan::ScalarCodec& codec, ::uavcan::TailArrayOptimizationMode tao_mode = ::uavcan::TailArrayOptEnabled); static int decode(ReferenceType self, ::uavcan::ScalarCodec& codec, ::uavcan::TailArrayOptimizationMode tao_mode = ::uavcan::TailArrayOptEnabled); }; template <int _tmpl> struct Response_ { typedef const Response_<_tmpl>& ParameterType; typedef Response_<_tmpl>& ReferenceType; struct ConstantTypes { typedef ::uavcan::IntegerSpec< 8, ::uavcan::SignednessUnsigned, ::uavcan::CastModeSaturate > FLAG_KNOWN; typedef ::uavcan::IntegerSpec< 8, ::uavcan::SignednessUnsigned, ::uavcan::CastModeSaturate > FLAG_SUBSCRIBED; typedef ::uavcan::IntegerSpec< 8, ::uavcan::SignednessUnsigned, ::uavcan::CastModeSaturate > FLAG_PUBLISHING; typedef ::uavcan::IntegerSpec< 8, ::uavcan::SignednessUnsigned, ::uavcan::CastModeSaturate > FLAG_SERVING; }; struct FieldTypes { typedef ::uavcan::IntegerSpec< 64, ::uavcan::SignednessUnsigned, ::uavcan::CastModeSaturate > signature; typedef ::uavcan::IntegerSpec< 16, ::uavcan::SignednessUnsigned, ::uavcan::CastModeSaturate > id; typedef ::uavcan::protocol::DataTypeKind kind; typedef ::uavcan::IntegerSpec< 8, ::uavcan::SignednessUnsigned, ::uavcan::CastModeSaturate > flags; typedef ::uavcan::Array< ::uavcan::IntegerSpec< 8, ::uavcan::SignednessUnsigned, ::uavcan::CastModeSaturate >, ::uavcan::ArrayModeDynamic, 80 > name; }; enum { MinBitLen = FieldTypes::signature::MinBitLen + FieldTypes::id::MinBitLen + FieldTypes::kind::MinBitLen + FieldTypes::flags::MinBitLen + FieldTypes::name::MinBitLen }; enum { MaxBitLen = FieldTypes::signature::MaxBitLen + FieldTypes::id::MaxBitLen + FieldTypes::kind::MaxBitLen + FieldTypes::flags::MaxBitLen + FieldTypes::name::MaxBitLen }; // Constants static const typename ::uavcan::StorageType< typename ConstantTypes::FLAG_KNOWN >::Type FLAG_KNOWN; // 1 static const typename ::uavcan::StorageType< typename ConstantTypes::FLAG_SUBSCRIBED >::Type FLAG_SUBSCRIBED; // 2 static const typename ::uavcan::StorageType< typename ConstantTypes::FLAG_PUBLISHING >::Type FLAG_PUBLISHING; // 4 static const typename ::uavcan::StorageType< typename ConstantTypes::FLAG_SERVING >::Type FLAG_SERVING; // 8 // Fields typename ::uavcan::StorageType< typename FieldTypes::signature >::Type signature; typename ::uavcan::StorageType< typename FieldTypes::id >::Type id; typename ::uavcan::StorageType< typename FieldTypes::kind >::Type kind; typename ::uavcan::StorageType< typename FieldTypes::flags >::Type flags; typename ::uavcan::StorageType< typename FieldTypes::name >::Type name; Response_() : signature() , id() , kind() , flags() , name() { ::uavcan::StaticAssert<_tmpl == 0>::check(); // Usage check #if UAVCAN_DEBUG /* * Cross-checking MaxBitLen provided by the DSDL compiler. * This check shall never be performed in user code because MaxBitLen value * actually depends on the nested types, thus it is not invariant. */ ::uavcan::StaticAssert<743 == MaxBitLen>::check(); #endif } bool operator==(ParameterType rhs) const; bool operator!=(ParameterType rhs) const { return !operator==(rhs); } /** * This comparison is based on @ref uavcan::areClose(), which ensures proper comparison of * floating point fields at any depth. */ bool isClose(ParameterType rhs) const; static int encode(ParameterType self, ::uavcan::ScalarCodec& codec, ::uavcan::TailArrayOptimizationMode tao_mode = ::uavcan::TailArrayOptEnabled); static int decode(ReferenceType self, ::uavcan::ScalarCodec& codec, ::uavcan::TailArrayOptimizationMode tao_mode = ::uavcan::TailArrayOptEnabled); }; typedef Request_<0> Request; typedef Response_<0> Response; /* * Static type info */ enum { DataTypeKind = ::uavcan::DataTypeKindService }; enum { DefaultDataTypeID = 2 }; static const char* getDataTypeFullName() { return "uavcan.protocol.GetDataTypeInfo"; } static void extendDataTypeSignature(::uavcan::DataTypeSignature& signature) { signature.extend(getDataTypeSignature()); } static ::uavcan::DataTypeSignature getDataTypeSignature(); private: GetDataTypeInfo_(); // Don't create objects of this type. Use Request/Response instead. }; /* * Out of line struct method definitions */ template <int _tmpl> bool GetDataTypeInfo_::Request_<_tmpl>::operator==(ParameterType rhs) const { return id == rhs.id && kind == rhs.kind && name == rhs.name; } template <int _tmpl> bool GetDataTypeInfo_::Request_<_tmpl>::isClose(ParameterType rhs) const { return ::uavcan::areClose(id, rhs.id) && ::uavcan::areClose(kind, rhs.kind) && ::uavcan::areClose(name, rhs.name); } template <int _tmpl> int GetDataTypeInfo_::Request_<_tmpl>::encode(ParameterType self, ::uavcan::ScalarCodec& codec, ::uavcan::TailArrayOptimizationMode tao_mode) { (void)self; (void)codec; (void)tao_mode; int res = 1; res = FieldTypes::id::encode(self.id, codec, ::uavcan::TailArrayOptDisabled); if (res <= 0) { return res; } res = FieldTypes::kind::encode(self.kind, codec, ::uavcan::TailArrayOptDisabled); if (res <= 0) { return res; } res = FieldTypes::name::encode(self.name, codec, tao_mode); return res; } template <int _tmpl> int GetDataTypeInfo_::Request_<_tmpl>::decode(ReferenceType self, ::uavcan::ScalarCodec& codec, ::uavcan::TailArrayOptimizationMode tao_mode) { (void)self; (void)codec; (void)tao_mode; int res = 1; res = FieldTypes::id::decode(self.id, codec, ::uavcan::TailArrayOptDisabled); if (res <= 0) { return res; } res = FieldTypes::kind::decode(self.kind, codec, ::uavcan::TailArrayOptDisabled); if (res <= 0) { return res; } res = FieldTypes::name::decode(self.name, codec, tao_mode); return res; } template <int _tmpl> bool GetDataTypeInfo_::Response_<_tmpl>::operator==(ParameterType rhs) const { return signature == rhs.signature && id == rhs.id && kind == rhs.kind && flags == rhs.flags && name == rhs.name; } template <int _tmpl> bool GetDataTypeInfo_::Response_<_tmpl>::isClose(ParameterType rhs) const { return ::uavcan::areClose(signature, rhs.signature) && ::uavcan::areClose(id, rhs.id) && ::uavcan::areClose(kind, rhs.kind) && ::uavcan::areClose(flags, rhs.flags) && ::uavcan::areClose(name, rhs.name); } template <int _tmpl> int GetDataTypeInfo_::Response_<_tmpl>::encode(ParameterType self, ::uavcan::ScalarCodec& codec, ::uavcan::TailArrayOptimizationMode tao_mode) { (void)self; (void)codec; (void)tao_mode; int res = 1; res = FieldTypes::signature::encode(self.signature, codec, ::uavcan::TailArrayOptDisabled); if (res <= 0) { return res; } res = FieldTypes::id::encode(self.id, codec, ::uavcan::TailArrayOptDisabled); if (res <= 0) { return res; } res = FieldTypes::kind::encode(self.kind, codec, ::uavcan::TailArrayOptDisabled); if (res <= 0) { return res; } res = FieldTypes::flags::encode(self.flags, codec, ::uavcan::TailArrayOptDisabled); if (res <= 0) { return res; } res = FieldTypes::name::encode(self.name, codec, tao_mode); return res; } template <int _tmpl> int GetDataTypeInfo_::Response_<_tmpl>::decode(ReferenceType self, ::uavcan::ScalarCodec& codec, ::uavcan::TailArrayOptimizationMode tao_mode) { (void)self; (void)codec; (void)tao_mode; int res = 1; res = FieldTypes::signature::decode(self.signature, codec, ::uavcan::TailArrayOptDisabled); if (res <= 0) { return res; } res = FieldTypes::id::decode(self.id, codec, ::uavcan::TailArrayOptDisabled); if (res <= 0) { return res; } res = FieldTypes::kind::decode(self.kind, codec, ::uavcan::TailArrayOptDisabled); if (res <= 0) { return res; } res = FieldTypes::flags::decode(self.flags, codec, ::uavcan::TailArrayOptDisabled); if (res <= 0) { return res; } res = FieldTypes::name::decode(self.name, codec, tao_mode); return res; } /* * Out of line type method definitions */ inline ::uavcan::DataTypeSignature GetDataTypeInfo_::getDataTypeSignature() { ::uavcan::DataTypeSignature signature(0x88C93DC9F68D24FCULL); Request::FieldTypes::id::extendDataTypeSignature(signature); Request::FieldTypes::kind::extendDataTypeSignature(signature); Request::FieldTypes::name::extendDataTypeSignature(signature); Response::FieldTypes::signature::extendDataTypeSignature(signature); Response::FieldTypes::id::extendDataTypeSignature(signature); Response::FieldTypes::kind::extendDataTypeSignature(signature); Response::FieldTypes::flags::extendDataTypeSignature(signature); Response::FieldTypes::name::extendDataTypeSignature(signature); return signature; } /* * Out of line constant definitions */ template <int _tmpl> const typename ::uavcan::StorageType< typename GetDataTypeInfo_::Response_<_tmpl>::ConstantTypes::FLAG_KNOWN >::Type GetDataTypeInfo_::Response_<_tmpl>::FLAG_KNOWN = 1U; // 1 template <int _tmpl> const typename ::uavcan::StorageType< typename GetDataTypeInfo_::Response_<_tmpl>::ConstantTypes::FLAG_SUBSCRIBED >::Type GetDataTypeInfo_::Response_<_tmpl>::FLAG_SUBSCRIBED = 2U; // 2 template <int _tmpl> const typename ::uavcan::StorageType< typename GetDataTypeInfo_::Response_<_tmpl>::ConstantTypes::FLAG_PUBLISHING >::Type GetDataTypeInfo_::Response_<_tmpl>::FLAG_PUBLISHING = 4U; // 4 template <int _tmpl> const typename ::uavcan::StorageType< typename GetDataTypeInfo_::Response_<_tmpl>::ConstantTypes::FLAG_SERVING >::Type GetDataTypeInfo_::Response_<_tmpl>::FLAG_SERVING = 8U; // 8 /* * Final typedef */ typedef GetDataTypeInfo_ GetDataTypeInfo; namespace { const ::uavcan::DefaultDataTypeRegistrator< ::uavcan::protocol::GetDataTypeInfo > _uavcan_gdtr_registrator_GetDataTypeInfo; } } // Namespace protocol } // Namespace uavcan /* * YAML streamer specialization */ namespace uavcan { template <> class UAVCAN_EXPORT YamlStreamer< ::uavcan::protocol::GetDataTypeInfo::Request > { public: template <typename Stream> static void stream(Stream& s, ::uavcan::protocol::GetDataTypeInfo::Request::ParameterType obj, const int level); }; template <typename Stream> void YamlStreamer< ::uavcan::protocol::GetDataTypeInfo::Request >::stream(Stream& s, ::uavcan::protocol::GetDataTypeInfo::Request::ParameterType obj, const int level) { (void)s; (void)obj; (void)level; if (level > 0) { s << '\n'; for (int pos = 0; pos < level; pos++) { s << " "; } } s << "id: "; YamlStreamer< ::uavcan::protocol::GetDataTypeInfo::Request::FieldTypes::id >::stream(s, obj.id, level + 1); s << '\n'; for (int pos = 0; pos < level; pos++) { s << " "; } s << "kind: "; YamlStreamer< ::uavcan::protocol::GetDataTypeInfo::Request::FieldTypes::kind >::stream(s, obj.kind, level + 1); s << '\n'; for (int pos = 0; pos < level; pos++) { s << " "; } s << "name: "; YamlStreamer< ::uavcan::protocol::GetDataTypeInfo::Request::FieldTypes::name >::stream(s, obj.name, level + 1); } template <> class UAVCAN_EXPORT YamlStreamer< ::uavcan::protocol::GetDataTypeInfo::Response > { public: template <typename Stream> static void stream(Stream& s, ::uavcan::protocol::GetDataTypeInfo::Response::ParameterType obj, const int level); }; template <typename Stream> void YamlStreamer< ::uavcan::protocol::GetDataTypeInfo::Response >::stream(Stream& s, ::uavcan::protocol::GetDataTypeInfo::Response::ParameterType obj, const int level) { (void)s; (void)obj; (void)level; if (level > 0) { s << '\n'; for (int pos = 0; pos < level; pos++) { s << " "; } } s << "signature: "; YamlStreamer< ::uavcan::protocol::GetDataTypeInfo::Response::FieldTypes::signature >::stream(s, obj.signature, level + 1); s << '\n'; for (int pos = 0; pos < level; pos++) { s << " "; } s << "id: "; YamlStreamer< ::uavcan::protocol::GetDataTypeInfo::Response::FieldTypes::id >::stream(s, obj.id, level + 1); s << '\n'; for (int pos = 0; pos < level; pos++) { s << " "; } s << "kind: "; YamlStreamer< ::uavcan::protocol::GetDataTypeInfo::Response::FieldTypes::kind >::stream(s, obj.kind, level + 1); s << '\n'; for (int pos = 0; pos < level; pos++) { s << " "; } s << "flags: "; YamlStreamer< ::uavcan::protocol::GetDataTypeInfo::Response::FieldTypes::flags >::stream(s, obj.flags, level + 1); s << '\n'; for (int pos = 0; pos < level; pos++) { s << " "; } s << "name: "; YamlStreamer< ::uavcan::protocol::GetDataTypeInfo::Response::FieldTypes::name >::stream(s, obj.name, level + 1); } } namespace uavcan { namespace protocol { template <typename Stream> inline Stream& operator<<(Stream& s, ::uavcan::protocol::GetDataTypeInfo::Request::ParameterType obj) { ::uavcan::YamlStreamer< ::uavcan::protocol::GetDataTypeInfo::Request >::stream(s, obj, 0); return s; } template <typename Stream> inline Stream& operator<<(Stream& s, ::uavcan::protocol::GetDataTypeInfo::Response::ParameterType obj) { ::uavcan::YamlStreamer< ::uavcan::protocol::GetDataTypeInfo::Response >::stream(s, obj, 0); return s; } } // Namespace protocol } // Namespace uavcan #endif // UAVCAN_PROTOCOL_GETDATATYPEINFO_HPP_INCLUDED
31.715232
168
0.625966
thiemar
9c2c1f6b8df124447aca66a67e75e262fb13f335
3,932
cpp
C++
src/plugins/process/single_filter/medItkAddProcess.cpp
arthursw/medInria-public
d52af882c36f0d96cc433cc1a4082accaa1ca11a
[ "BSD-4-Clause" ]
61
2015-04-14T13:00:50.000Z
2022-03-09T22:22:18.000Z
src/plugins/process/single_filter/medItkAddProcess.cpp
arthursw/medInria-public
d52af882c36f0d96cc433cc1a4082accaa1ca11a
[ "BSD-4-Clause" ]
510
2016-02-03T13:28:18.000Z
2022-03-23T10:23:44.000Z
src/plugins/process/single_filter/medItkAddProcess.cpp
arthursw/medInria-public
d52af882c36f0d96cc433cc1a4082accaa1ca11a
[ "BSD-4-Clause" ]
36
2015-03-03T22:58:19.000Z
2021-12-28T18:19:23.000Z
/*========================================================================= medInria Copyright (c) INRIA 2013 - 2018. All rights reserved. See LICENSE.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. =========================================================================*/ #include <medItkAddProcess.h> #include <dtkLog> #include <itkImage.h> #include <itkAddImageFilter.h> #include <itkCommand.h> #include <medAbstractImageData.h> #include <medAbstractDataFactory.h> #include <medDoubleParameter.h> medItkAddProcess::medItkAddProcess(QObject *parent) : medAbstractAddFilterProcess(parent) { m_filter = nullptr; } medItkAddProcess::~medItkAddProcess() { } QString medItkAddProcess::caption() const { return "Add constant"; } QString medItkAddProcess::description() const { return "Use ITK AddImageFilter to add a constant to an image"; } medAbstractJob::medJobExitStatus medItkAddProcess::run() { medAbstractJob::medJobExitStatus jobExitSatus = medAbstractJob::MED_JOB_EXIT_FAILURE; if(this->input()) { QString id = this->input()->identifier(); if ( id == "itkDataImageChar3" ) { jobExitSatus = this->_run<char>(); } else if ( id == "itkDataImageUChar3" ) { jobExitSatus = this->_run<unsigned char>(); } else if ( id == "itkDataImageShort3" ) { jobExitSatus = this->_run<short>(); } else if ( id == "itkDataImageUShort3" ) { jobExitSatus = this->_run<unsigned short>(); } else if ( id == "itkDataImageInt3" ) { jobExitSatus = this->_run<int>(); } else if ( id == "itkDataImageUInt3" ) { jobExitSatus = this->_run<unsigned int>(); } else if ( id == "itkDataImageLong3" ) { jobExitSatus = this->_run<long>(); } else if ( id== "itkDataImageULong3" ) { jobExitSatus = this->_run<unsigned long>(); } else if ( id == "itkDataImageFloat3" ) { jobExitSatus = this->_run<float>(); } else if ( id == "itkDataImageDouble3" ) { jobExitSatus = this->_run<double>(); } } return jobExitSatus; } template <class inputType> medAbstractJob::medJobExitStatus medItkAddProcess::_run() { typedef itk::Image<inputType, 3> ImageType; typename ImageType::Pointer in1 = dynamic_cast<ImageType *>((itk::Object*)(this->input()->data())); double factor = this->doubleParameter()->value(); if(in1.IsNotNull()) { typedef itk::AddImageFilter< ImageType, itk::Image<double, ImageType::ImageDimension>, ImageType > FilterType; typename FilterType::Pointer filter = FilterType::New(); m_filter = filter; filter->SetInput(in1); filter->SetConstant(factor); itk::CStyleCommand::Pointer callback = itk::CStyleCommand::New(); callback->SetClientData((void*)this); callback->SetCallback(medItkAddProcess::eventCallback); filter->AddObserver(itk::ProgressEvent(), callback); try { filter->Update(); } catch(itk::ProcessAborted &) { return medAbstractJob::MED_JOB_EXIT_CANCELLED; } medAbstractImageData *out= qobject_cast<medAbstractImageData *>(medAbstractDataFactory::instance()->create(this->input()->identifier())); out->setData(filter->GetOutput()); this->setOutput(out); return medAbstractJob::MED_JOB_EXIT_SUCCESS; } return medAbstractJob::MED_JOB_EXIT_FAILURE; } void medItkAddProcess::cancel() { if(this->isRunning() && m_filter.IsNotNull()) { m_filter->AbortGenerateDataOn(); } }
25.699346
145
0.590285
arthursw
9c2cfc7399f456240810ba1717d1b1ad5f9bc69c
7,669
cpp
C++
src/SKSE/RegistrationSetUnique.cpp
fireundubh/CommonLibSSE-po3
cf30265f3cd3aa70a8eeff4d598754439e983ddd
[ "MIT" ]
1
2021-08-30T20:33:43.000Z
2021-08-30T20:33:43.000Z
src/SKSE/RegistrationSetUnique.cpp
fireundubh/CommonLibSSE-po3
cf30265f3cd3aa70a8eeff4d598754439e983ddd
[ "MIT" ]
null
null
null
src/SKSE/RegistrationSetUnique.cpp
fireundubh/CommonLibSSE-po3
cf30265f3cd3aa70a8eeff4d598754439e983ddd
[ "MIT" ]
null
null
null
#include "SKSE/RegistrationSetUnique.h" #include "SKSE/Logger.h" namespace SKSE { namespace Impl { RegistrationSetUniqueBase::RegistrationSetUniqueBase(const std::string_view& a_eventName) : _handles(), _eventName(a_eventName), _lock() {} RegistrationSetUniqueBase::RegistrationSetUniqueBase(const RegistrationSetUniqueBase& a_rhs) : _handles(), _eventName(a_rhs._eventName), _lock() { a_rhs._lock.lock(); _handles = a_rhs._handles; a_rhs._lock.unlock(); auto vm = RE::BSScript::Internal::VirtualMachine::GetSingleton(); auto policy = vm ? vm->GetObjectHandlePolicy() : nullptr; if (policy) { for (auto& [refHandle, vmHandle] : _handles) { policy->PersistHandle(vmHandle); } } } RegistrationSetUniqueBase::RegistrationSetUniqueBase(RegistrationSetUniqueBase&& a_rhs) : _handles(), _eventName(a_rhs._eventName), _lock() { Locker locker(a_rhs._lock); _handles = std::move(a_rhs._handles); a_rhs._handles.clear(); } RegistrationSetUniqueBase::~RegistrationSetUniqueBase() { auto vm = RE::BSScript::Internal::VirtualMachine::GetSingleton(); auto policy = vm ? vm->GetObjectHandlePolicy() : nullptr; if (policy) { for (auto& [refHandle, vmHandle] : _handles) { policy->ReleaseHandle(vmHandle); } } } RegistrationSetUniqueBase& RegistrationSetUniqueBase::operator=(const RegistrationSetUniqueBase& a_rhs) { if (this == &a_rhs) { return *this; } Locker lhsLocker(_lock); Clear(); { Locker rhsLocker(a_rhs._lock); _handles = a_rhs._handles; _eventName = a_rhs._eventName; } auto vm = RE::BSScript::Internal::VirtualMachine::GetSingleton(); auto policy = vm ? vm->GetObjectHandlePolicy() : nullptr; if (policy) { for (auto& [refHandle, vmHandle] : _handles) { policy->PersistHandle(vmHandle); } } return *this; } RegistrationSetUniqueBase& RegistrationSetUniqueBase::operator=(RegistrationSetUniqueBase&& a_rhs) { if (this == &a_rhs) { return *this; } Locker lhsLocker(_lock); Locker rhsLocker(a_rhs._lock); Clear(); _eventName = a_rhs._eventName; _handles = std::move(a_rhs._handles); a_rhs._handles.clear(); return *this; } bool RegistrationSetUniqueBase::Register(RE::BGSRefAlias* a_alias) { assert(a_alias); auto target = a_alias->GetActorReference(); auto handle = target ? target->CreateRefHandle().native_handle() : 0; if (handle != 0) { return Register(a_alias, std::move(handle), RE::BGSRefAlias::VMTYPEID); } else { return false; } } bool RegistrationSetUniqueBase::Register(RE::ActiveEffect* a_activeEffect) { assert(a_activeEffect); auto target = a_activeEffect->GetTargetActor(); auto handle = target ? target->CreateRefHandle().native_handle() : 0; if (handle != 0) { return Register(a_activeEffect, std::move(handle), RE::ActiveEffect::VMTYPEID); } else { return false; } } bool RegistrationSetUniqueBase::Unregister(RE::BGSRefAlias* a_alias) { assert(a_alias); auto target = a_alias->GetActorReference(); auto handle = target ? target->CreateRefHandle().native_handle() : 0; if (handle != 0) { return Unregister(a_alias, std::move(handle), RE::BGSRefAlias::VMTYPEID); } else { return false; } } bool RegistrationSetUniqueBase::Unregister(RE::ActiveEffect* a_activeEffect) { assert(a_activeEffect); auto target = a_activeEffect->GetTargetActor(); auto handle = target ? target->CreateRefHandle().native_handle() : 0; if (handle != 0) { return Unregister(a_activeEffect, std::move(handle), RE::ActiveEffect::VMTYPEID); } else { return false; } } void RegistrationSetUniqueBase::Clear() { auto vm = RE::BSScript::Internal::VirtualMachine::GetSingleton(); auto policy = vm ? vm->GetObjectHandlePolicy() : nullptr; Locker locker(_lock); if (policy) { for (auto& [refHandle, vmHandle] : _handles) { policy->ReleaseHandle(vmHandle); } } _handles.clear(); } bool RegistrationSetUniqueBase::Save(SerializationInterface* a_intfc, std::uint32_t a_type, std::uint32_t a_version) { assert(a_intfc); if (!a_intfc->OpenRecord(a_type, a_version)) { log::error("Failed to open record"); return false; } return Save(a_intfc); } bool RegistrationSetUniqueBase::Save(SerializationInterface* a_intfc) { assert(a_intfc); Locker locker(_lock); const std::size_t numHandles = _handles.size(); if (!a_intfc->WriteRecordData(numHandles)) { log::error("Failed to save number of handles ({})", numHandles); return false; } for (auto& [refHandle, vmHandle] : _handles) { if (!a_intfc->WriteRecordData(refHandle)) { log::error("Failed to save reg ({})", refHandle); return false; } if (!a_intfc->WriteRecordData(vmHandle)) { log::error("Failed to save reg ({})", vmHandle); return false; } } return true; } bool RegistrationSetUniqueBase::Load(SerializationInterface* a_intfc) { assert(a_intfc); std::size_t numHandles; if (!a_intfc->ReadRecordData(numHandles)) { log::warn("Error loading handle count"); return false; } Locker locker(_lock); _handles.clear(); RE::RefHandle refHandle; RE::VMHandle vmHandle; for (std::size_t i = 0; i < numHandles; ++i) { if (!a_intfc->ReadRecordData(refHandle)) { log::warn("Error reading refHandle ({})", refHandle); return false; } a_intfc->ReadRecordData(vmHandle); if (!a_intfc->ResolveHandle(vmHandle, vmHandle)) { log::warn("Failed to resolve vmHandle ({})", vmHandle); return false; } auto result = _handles.insert({ refHandle, vmHandle }); if (!result.second) { log::error("Loaded duplicate handle ({},{})", refHandle, vmHandle); } } return true; } bool RegistrationSetUniqueBase::Register(const void* a_object, RE::RefHandle a_refHandle, RE::VMTypeID a_typeID) { assert(a_object); auto vm = RE::BSScript::Internal::VirtualMachine::GetSingleton(); auto policy = vm ? vm->GetObjectHandlePolicy() : nullptr; if (!policy) { log::error("Failed to get handle policy"); return false; } const auto invalidHandle = policy->EmptyHandle(); const auto handle = policy->GetHandleForObject(a_typeID, a_object); if (handle == invalidHandle) { log::error("Failed to create handle"); return false; } _lock.lock(); auto result = _handles.insert({ a_refHandle, handle }); _lock.unlock(); if (!result.second) { //log::warn("Handle already registered ({})", handle); } else { policy->PersistHandle(handle); } return result.second; } bool RegistrationSetUniqueBase::Unregister(const void* a_object, RE::RefHandle a_refHandle, RE::VMTypeID a_typeID) { assert(a_object); auto vm = RE::BSScript::Internal::VirtualMachine::GetSingleton(); auto policy = vm ? vm->GetObjectHandlePolicy() : nullptr; if (!policy) { log::error("Failed to get handle policy!"); return false; } auto invalidHandle = policy->EmptyHandle(); auto handle = policy->GetHandleForObject(a_typeID, a_object); if (handle == invalidHandle) { log::error("Failed to create handle!"); return false; } Locker locker(_lock); auto handlePair = std::pair{ a_refHandle, handle }; auto it = _handles.find(handlePair); if (it == _handles.end()) { //log::warn("Could not find registration"); return false; } else { policy->ReleaseHandle((*it).second); _handles.erase(it); return true; } } } }
24.501597
118
0.663972
fireundubh
9c3147752c52207ba6bfb4b2f97873ad5c33be58
750
cpp
C++
Servercpp/ServerCPP/ServerCPP/lib/Communication/ApplicationLayer/Instruction/InstructionStream.cpp
RobotGuide/RobotGuideProject
ba7fcc4a0fc4eb6b743ddbaeb75e7ae114eefb4e
[ "MIT" ]
2
2021-01-27T20:06:54.000Z
2021-03-02T14:30:37.000Z
Servercpp/ServerCPP/ServerCPP/lib/Communication/ApplicationLayer/Instruction/InstructionStream.cpp
RobotGuide/RobotGuideProject
ba7fcc4a0fc4eb6b743ddbaeb75e7ae114eefb4e
[ "MIT" ]
null
null
null
Servercpp/ServerCPP/ServerCPP/lib/Communication/ApplicationLayer/Instruction/InstructionStream.cpp
RobotGuide/RobotGuideProject
ba7fcc4a0fc4eb6b743ddbaeb75e7ae114eefb4e
[ "MIT" ]
null
null
null
#include "robotguide/Communication/ApplicationLayer/Instruction/InstructionStream.h" #include "robotguide/Communication/ApplicationLayer/Instruction/InstructionPrinter.h" using namespace robotguide::com::applicationlayer; InstructionStream::~InstructionStream() { for (auto* instruction : instructions) { delete instruction; instruction = nullptr; } } void InstructionStream::AddInstruction(Instruction* instruction) { instructions.push_back(instruction); } std::string InstructionStream::ToString() const { std::string completeString; for (const auto& instruction : instructions) { completeString += instruction->ToString(); } return completeString; } unsigned InstructionStream::size() const { return instructions.size(); }
20.833333
85
0.784
RobotGuide
9c37dce8d79eade12fec65d3e13bcdeba94e7e09
66,861
cc
C++
src/bgp-path-attrib.cc
Nat-Lab/bgp-fsm
c86b6eb8e2252d312e75c7b24b588eff4e54b4fa
[ "MIT" ]
6
2020-05-11T05:32:56.000Z
2022-01-21T13:25:37.000Z
src/bgp-path-attrib.cc
Nat-Lab/bgp-fsm
c86b6eb8e2252d312e75c7b24b588eff4e54b4fa
[ "MIT" ]
2
2021-01-18T22:19:45.000Z
2022-01-21T13:26:43.000Z
src/bgp-path-attrib.cc
Nat-Lab/bgp-fsm
c86b6eb8e2252d312e75c7b24b588eff4e54b4fa
[ "MIT" ]
null
null
null
/** * @file bgp-path-attrib.cc * @author Nato Morichika <nat@nat.moe> * @brief BGP Path attributes. * @version 0.1 * @date 2019-07-06 * * @copyright Copyright (c) 2019 * */ #include "bgp-path-attrib.h" #include "bgp-errcode.h" #include "bgp-afi.h" #include "value-op.h" #include <stdlib.h> #include <arpa/inet.h> namespace libbgp { /** * @brief Get type of attribute from buffer. * * @param from Pointer to buffer. * @param buffer_sz Size of buffre. * @return int8_t Attribute type. * @retval 0 Failed to get attribute type. * @retval >0 Attribute type. */ uint8_t BgpPathAttrib::GetTypeFromBuffer(const uint8_t *from, size_t buffer_sz) { if (buffer_sz < 3) return -1; return *((uint8_t *) (from + 1)); } /** * @brief Construct a new Bgp Path Attrib:: Bgp Path Attrib object * * @param logger Pointer to logger object for error logging. */ BgpPathAttrib::BgpPathAttrib(BgpLogHandler *logger) : Serializable(logger) { optional = transitive = partial = extended = false; value_ptr = NULL; } /** * @brief Construct a new Bgp Path Attrib:: Bgp Path Attrib object * * @param logger Pointer to logger object for error logging. * @param value Pointer to value buffer of unknow type attribute. * @param val_len Length of the value buffer. */ BgpPathAttrib::BgpPathAttrib(BgpLogHandler *logger, const uint8_t *value, uint16_t val_len) : BgpPathAttrib(logger) { if (value_len > 0) { logger->log(FATAL, "BgpPathAttrib::BgpPathAttrib: unknow attribute created with length != 0 but buffer NULL.\n"); throw "bad_value_buffer"; } value_ptr = (uint8_t *) malloc(val_len); memcpy(value_ptr, value, value_len); } /** * @brief Destroy the Bgp Path Attrib:: Bgp Path Attrib object * */ BgpPathAttrib::~BgpPathAttrib() { if (value_ptr != NULL) free(value_ptr); } BgpPathAttrib* BgpPathAttrib::clone(BgpLogHandler *new_logger) const { BgpPathAttrib* cloned = clone(); cloned->setLogger(new_logger); return cloned; } BgpPathAttrib* BgpPathAttrib::clone() const { if(hasError()) { logger->log(FATAL, "BgpPathAttrib::clone: can't clone an attribute with error.\n"); throw "has_error"; } BgpPathAttrib *attr = new BgpPathAttrib(logger, value_ptr, value_len); attr->transitive = transitive; attr->optional = optional; attr->partial = partial; attr->extended = attr->extended; return attr; } /** * @brief Utility function to print flags for attribute. * * @param indent Indentation level. * @param to Pointer to buffer pointer. * @param buf_sz Pointer to avaliable buffer counter. * @return ssize_t Bytes written. */ ssize_t BgpPathAttrib::printFlags(size_t indent, uint8_t **to, size_t *buf_sz) const { size_t written = 0; if (!(transitive || optional || partial || extended)) { written += _print(indent, to, buf_sz, "Flags { }\n"); return written; } written += _print(indent, to, buf_sz, "Flags {\n"); indent++; { if (optional) written += _print(indent, to, buf_sz, "Optional\n"); if (transitive) written += _print(indent, to, buf_sz, "Transitive\n"); if (partial) written += _print(indent, to, buf_sz, "Partial\n"); if (extended) written += _print(indent, to, buf_sz, "Extended\n"); }; indent--; written += _print(indent, to, buf_sz, "}\n"); return written; } ssize_t BgpPathAttrib::doPrint(size_t indent, uint8_t **to, size_t *buf_sz) const { size_t written = 0; written += _print(indent, to, buf_sz, "UnknowAttribute {\n"); indent++; { written += printFlags(indent, to, buf_sz); written += _print(indent, to, buf_sz, "TypeCode { %d }\n", type_code); }; indent--; written += _print(indent, to, buf_sz, "}\n"); return written; } ssize_t BgpPathAttrib::parse(const uint8_t *from, size_t length) { ssize_t header_len = parseHeader(from, length); if (header_len < 0) return -1; const uint8_t *buffer = from + 3; // Well-Known, Mandatory = !optional, transitive // Well-Known, Discretionary = !optional, !transitive // Optional, Transitive = optional, transitive // Optional, Non-Transitive = optional, !transitive if (!optional && transitive) { // well-known mandatory, but not recognized setError(E_UPDATE, E_BAD_WELL_KNOWN, from, value_len + header_len); logger->log(ERROR, "BgpPathAttrib::parse: flag indicates well-known, mandatory but this attribute is unknown.\n"); // set value_len = 0, so we won't free() nullptr when destruct. value_len = 0; return -1; } if (optional && !transitive && partial) { // optional non-transitive must not be partial setError(E_UPDATE, E_ATTR_FLAG, from, value_len + header_len); logger->log(ERROR, "BgpPathAttrib::parse: optional non-transitive must not be partial.\n"); // set value_len = 0, so we won't free() nullptr when destruct. value_len = 0; return -1; } value_ptr = (uint8_t *) malloc(value_len); memcpy(value_ptr, buffer, value_len); return value_len + header_len; } ssize_t BgpPathAttrib::length() const { return value_len + (extended ? 4 : 3); } ssize_t BgpPathAttrib::write(uint8_t *to, size_t buffer_sz) const { if (buffer_sz < (size_t) (value_len + 3)) { logger->log(ERROR, "BgpPathAttrib::write: destination buffer size too small.\n"); return -1; } if (!extended && value_len >= 0xffff) { logger->log(ERROR, "BgpPathAttrib::write: non-extended value has size > 65535: %d\n", value_len); return -1; } if (writeHeader(to, buffer_sz) < 2) return -1; uint8_t *buffer = to + 2; if (extended) putValue<uint16_t>(&buffer, htons(value_len)); else putValue<uint8_t>(&buffer, value_len); if (value_len > 0) memcpy(buffer, value_ptr, value_len); return value_len + 3; } /** * @brief Utility function to parse attribute header. (Flag, type, length) * * @param from Pointer to buffer. * @param buffer_sz Size of buffer. * @return ssize_t Bytes read. * @retval -1 Failed to parse header. error may be written to stderr with log * handler. * @retval >=0 Bytes read. */ ssize_t BgpPathAttrib::parseHeader(const uint8_t *from, size_t buffer_sz) { if (buffer_sz < 3) { setError(E_UPDATE, E_UNSPEC_UPDATE, NULL, 0); logger->log(ERROR, "BgpPathAttrib::parseHeader: invalid attribute header size.\n"); return -1; } const uint8_t *buffer = from; uint8_t flags = getValue<uint8_t>(&buffer); optional = (flags >> 7) & 0x1; transitive = (flags >> 6) & 0x1; partial = (flags >> 5) & 0x1; extended = (flags >> 4) & 0x1; type_code = getValue<uint8_t>(&buffer); if (extended && buffer_sz < 4) { setError(E_UPDATE, E_UNSPEC_UPDATE, NULL, 0); logger->log(ERROR, "BgpPathAttrib::parseHeader: invalid attribute header size (extended but size < 4).\n"); return -1; } if (extended) value_len = ntohs(getValue<uint16_t>(&buffer)); else value_len = getValue<uint8_t>(&buffer); if (value_len > buffer_sz - 3) { err_code = E_UPDATE; // This is kind of "invalid length", but we are not using E_ATTR_LEN. // E_ATTR_LEN: "Attribute Length that conflict with the expected length // (based on the attribute type code)." This is not based on type code, // but it is buffer overflow, so we set subcode to E_UNSPEC, setError(E_UPDATE, E_UNSPEC_UPDATE, NULL, 0); logger->log(ERROR, "BgpPathAttrib::parseHeader: value_length (%d) < buffer left (%d).\n", value_len, buffer_sz - 3); return -1; } return extended ? 4 : 3; } /** * @brief Write attribute header to buffer. (Flag, Type) * * Write attribute header to buffer. Notice that only attribute flags and type * will be written to buffer. You need to write attribute length yourself. * * @param to Destnation buiffer. * @param buffer_sz Max write size. * @return ssize_t Bytes written. * @retval -1 Failed to write buffer. error may be written to stderr with log * handler. * @retval >=0 Bytes written. */ ssize_t BgpPathAttrib::writeHeader(uint8_t *to, size_t buffer_sz) const { if (buffer_sz < (extended ? 3 : 4)) { logger->log(ERROR, "BgpPathAttrib::writeHeader: dst buffer too small: %d\n", buffer_sz); return -1; } uint8_t *buffer = to; uint8_t flags = (optional << 7) | (transitive << 6)| (partial << 5) | (extended << 4); putValue<uint8_t>(&buffer, flags); putValue<uint8_t>(&buffer, type_code); return 2; } /** * @brief Construct a new Bgp Path Attrib Origin:: Bgp Path Attrib Origin object * * @param logger Pointer to logger object for error logging. */ BgpPathAttribOrigin::BgpPathAttribOrigin(BgpLogHandler *logger) : BgpPathAttrib(logger) { transitive = true; type_code = ORIGIN; } BgpPathAttrib* BgpPathAttribOrigin::clone() const { if(hasError()) { logger->log(FATAL, "BgpPathAttribOrigin::clone: can't clone an attribute with error.\n"); throw "has_error"; } return new BgpPathAttribOrigin(*this); } ssize_t BgpPathAttribOrigin::doPrint(size_t indent, uint8_t **to, size_t *buf_sz) const { const char *origin_name = NULL; switch(origin) { case 0: origin_name = "IGP"; break; case 1: origin_name= "EGP"; break; case 2: origin_name = "Incomplete"; break; default: origin_name = "Invalid"; break; } size_t written = 0; written += _print(indent, to, buf_sz, "OriginAttribute {\n"); indent++; { written += printFlags(indent, to, buf_sz); written += _print(indent, to, buf_sz, "Origin { %s }\n", origin_name); }; indent--; written += _print(indent, to, buf_sz, "}\n"); return written; } ssize_t BgpPathAttribOrigin::parse(const uint8_t *from, size_t length) { ssize_t header_length = parseHeader(from, length); if (header_length < 0) return -1; if (type_code != ORIGIN) { logger->log(FATAL, "BgpPathAttribOrigin::parse: type in header mismatch.\n"); throw "bad_type"; } const uint8_t *buffer = from + 3; if (value_len < 1) { logger->log(ERROR, "BgpPathAttribOrigin::parse: incomplete attrib.\n"); setError(E_UPDATE, E_UNSPEC_UPDATE, NULL, 0); return -1; } if (value_len != 1) { logger->log(ERROR, "BgpPathAttribOrigin::parse: bad length, want 1, saw %d.\n", value_len); setError(E_UPDATE, E_ATTR_LEN, from, value_len + header_length); return -1; } if (optional || !transitive || extended || partial) { logger->log(ERROR, "BgpPathAttribOrigin::parse: bad flag bits, must be !optional, !extended, !partial, transitive.\n"); setError(E_UPDATE, E_ATTR_FLAG, from, value_len + header_length); return -1; } origin = getValue<uint8_t>(&buffer); if (origin > 2) { setError(E_UPDATE, E_ORIGIN, from, 4); logger->log(ERROR, "BgpPathAttribOrigin::parse: Bad Origin Value: %d.\n", origin); return -1; } return 4; } ssize_t BgpPathAttribOrigin::write(uint8_t *to, size_t buffer_sz) const { if (buffer_sz < 4) { logger->log(ERROR, "BgpPathAttribOrigin::write: destination buffer size too small.\n"); return -1; } if (writeHeader(to, buffer_sz) < 0) return -1; uint8_t *buffer = to + 2; putValue<uint8_t>(&buffer, 1); // length = 1 putValue<uint8_t>(&buffer, origin); return 4; } ssize_t BgpPathAttribOrigin::length() const { return 4; } /** * @brief Construct a new Bgp Path Attrib As Path:: Bgp Path Attrib As Path object * * @param logger Pointer to logger object for error logging. * @param is_4b Enable four octets ASN support. */ BgpPathAttribAsPath::BgpPathAttribAsPath(BgpLogHandler *logger, bool is_4b) : BgpPathAttrib(logger) { this->is_4b = is_4b; transitive = true; type_code = AS_PATH; } /** * @brief Construct a new Bgp As Path Segment:: Bgp As Path Segment object * * @param is_4b Enable four octets ASN support. * @param type Type of AS path segment. */ BgpAsPathSegment::BgpAsPathSegment(bool is_4b, uint8_t type) { this->is_4b = is_4b; this->type = type; } /** * @brief Get number of ASNs in the segment. * * @return size_t Number of ASNs. */ size_t BgpAsPathSegment::getCount() const { return value.size(); } /** * @brief Prepend ASN to AS segment. * * @param asn ASN to prepend. * @return true ASN prepended. * @return false Failed to prepend ASN. */ bool BgpAsPathSegment::prepend(uint32_t asn) { if (value.size() >= (is_4b ? 127 : 255)) return false; uint32_t prepend_asn = is_4b ? asn : (asn >= 0xffff ? 23456 : asn); value.insert(value.begin(), prepend_asn); return true; } BgpPathAttrib* BgpPathAttribAsPath::clone() const { if(hasError()) { logger->log(FATAL, "BgpPathAttribAsPath::clone: can't clone an attribute with error.\n"); throw "has_error"; } return new BgpPathAttribAsPath(*this); } ssize_t BgpPathAttribAsPath::doPrint(size_t indent, uint8_t **to, size_t *buf_sz) const { size_t written = 0; written += _print(indent, to, buf_sz, "AsPathAttribute {\n"); indent++; { written += _print(indent, to, buf_sz, "FourOctet { %s }\n", is_4b ? "true" : "false"); written += printFlags(indent, to, buf_sz); if (as_paths.size() == 0) written += _print(indent, to, buf_sz, "AsPathSegments { } \n"); else { written += _print(indent, to, buf_sz, "AsPathSegments {\n"); indent++; { for (const BgpAsPathSegment &seg : as_paths) { switch (seg.type) { case 1: written += _print(indent, to, buf_sz, "AsSet {\n"); break; case 2: written += _print(indent, to, buf_sz, "AsSequence {\n"); break; default: written += _print(indent, to, buf_sz, "Invalid {\n"); break; } indent++; { for (uint32_t asn : seg.value) { written += _print(indent, to, buf_sz, "%u\n", asn); } }; indent--; written += _print(indent, to, buf_sz, "}\n"); } }; indent--; written += _print(indent, to, buf_sz, "}\n"); } }; indent--; written += _print(indent, to, buf_sz, "}\n"); return written; } ssize_t BgpPathAttribAsPath::parse(const uint8_t *from, size_t length) { ssize_t header_length = parseHeader(from, length); if (header_length < 0) return -1; if (type_code != AS_PATH) { logger->log(FATAL, "BgpPathAttribAsPath::parse: type in header mismatch.\n"); throw "bad_type"; } if (optional || !transitive || extended || partial) { logger->log(ERROR, "BgpPathAttribAsPath::parse: bad flag bits, must be !optional, !extended, !partial, transitive.\n"); setError(E_UPDATE, E_ATTR_FLAG, from , value_len + header_length); return -1; } const uint8_t *buffer = from + 3; // empty as_path if (value_len == 0) return 3; uint8_t parsed_len = 0; while (parsed_len < value_len) { // bad as_path if (value_len - parsed_len < 3) { logger->log(ERROR, "BgpPathAttribAsPath::parse: incomplete as_path segment.\n"); setError(E_UPDATE, E_AS_PATH, NULL, 0); return -1; } uint8_t type = getValue<uint8_t>(&buffer); uint8_t n_asn = getValue<uint8_t>(&buffer); // type & count parsed_len += 2; uint8_t asns_length = is_4b ? n_asn * sizeof(uint32_t) : n_asn * sizeof(uint16_t); // overflow if (parsed_len + asns_length > value_len) { logger->log(ERROR, "BgpPathAttribAsPath::parse: as_path overflow attribute length.\n"); setError(E_UPDATE, E_AS_PATH, NULL, 0); return -1; } BgpAsPathSegment path(is_4b, type); if (is_4b) for (int i = 0; i < n_asn; i++) path.value.push_back(ntohl(getValue<uint32_t>(&buffer))); else for (int i = 0; i < n_asn; i++) path.value.push_back(ntohs(getValue<uint16_t>(&buffer))); as_paths.push_back(path); // parsed asns parsed_len += asns_length; } if (parsed_len != value_len) { logger->log(FATAL, "BgpPathAttribAsPath::parse: parsed length and value length mismatch, but no error reported.\n"); throw "bad_parse"; } return parsed_len + 3; } ssize_t BgpPathAttribAsPath::length() const { size_t len = 3; // header len = 3 for (const BgpAsPathSegment &seg : as_paths) { len += (seg.is_4b ? 4 : 2) * seg.value.size() + 2; } return len; } /** * @brief Add a new segment with one ASN in it. * * @param asn The first ASN in the segment. */ void BgpPathAttribAsPath::addSeg(uint32_t asn) { BgpAsPathSegment segment(is_4b, AS_SEQUENCE); segment.prepend(asn); as_paths.push_back(segment); } /** * @brief Prepend an ASN into AS path. * * This method will prepend an ASN to AS_SEQUENCE segment if the segment is the * first in path. A new AS_SEQUENCE will be create and append to AS_PATH * otherwise. A new AS_SEQUENCE will also be create if the current one is full. * * @param asn The ASN to append. * @return true ASN prepended. * @return false Failed to append ASN. error may be written to stderr with log * handler. */ bool BgpPathAttribAsPath::prepend(uint32_t asn) { if (as_paths.size() == 0) { // nothing here yet, add a new sequence. (5.1.2.b.3) addSeg(asn); return true; } // something here already. what to do? BgpAsPathSegment *segment = as_paths.data(); if (segment->type == AS_SET) { // seg is set, create a new segment of type AS_SEQUENCE (5.1.2.b.2) // FIXME: checks needed: really create a new segment? addSeg(asn); return true; } else if (segment->type == AS_SEQUENCE) { if (segment->getCount() >= (is_4b ? 127 : 255)) { // seg full, create a new segment of type AS_SEQUENCE (5.1.2.b.1) addSeg(asn); return true; } else { segment->prepend(asn); return true; } } logger->log(ERROR, "BgpPathAttribAsPath::prepend: unknow first segment type: %d, can't append.\n", segment->type); return false; } ssize_t BgpPathAttribAsPath::write(uint8_t *to, size_t buffer_sz) const { if (buffer_sz < 3) { logger->log(ERROR, "BgpPathAttribAsPath::write: destination buffer size too small.\n"); return -1; } if (writeHeader(to, buffer_sz) < 0) return -1; uint8_t *buffer = to + 2; // keep track of length field so we can write it later uint8_t *len_field = buffer; // skip length field for now buffer++; uint8_t written_len = 0; for (const BgpAsPathSegment &seg : as_paths) { if (seg.is_4b != is_4b) { // maybe allow 2b-seg in 4b-mode? logger->log(ERROR, "BgpPathAttribAsPath::write: segment 4b-mode and message 4b-mode mismatch.\n"); return -1; } size_t asn_count = seg.value.size(); if (asn_count >= (is_4b ? 127 : 255)) { logger->log(ERROR, "BgpPathAttribAsPath::write: segment size too big: %d\n", asn_count); return -1; } size_t bytes_need = asn_count * (is_4b ? sizeof(uint32_t) : sizeof(uint16_t)) + 2; if (written_len + bytes_need > buffer_sz) { logger->log(ERROR, "BgpPathAttribAsPath::write: destination buffer size too small.\n"); return -1; } putValue<uint8_t>(&buffer, seg.type); putValue<uint8_t>(&buffer, asn_count); if (seg.is_4b) for (uint32_t asn : seg.value) putValue<uint32_t>(&buffer, htonl(asn)); else for (uint16_t asn : seg.value) putValue<uint16_t>(&buffer, htons(asn)); written_len += bytes_need; } // fill in the length. putValue<uint8_t>(&len_field, written_len); // written_len: the as_paths, 3: attr header (flag, typecode, length) return written_len + 3; } /** * @brief Construct a new Bgp Path Attrib Nexthop:: Bgp Path Attrib Nexthop object * * @param logger Pointer to logger object for error logging. */ BgpPathAttribNexthop::BgpPathAttribNexthop(BgpLogHandler *logger) : BgpPathAttrib(logger) { type_code = NEXT_HOP; transitive = true; } ssize_t BgpPathAttribNexthop::doPrint(size_t indent, uint8_t **to, size_t *buf_sz) const { size_t written = 0; written += _print(indent, to, buf_sz, "NexthopAttribute {\n"); indent++; { written += printFlags(indent, to, buf_sz); written += _print(indent, to, buf_sz, "Nexthop { %s }\n", inet_ntoa(*(struct in_addr*) &next_hop)); }; indent--; written += _print(indent, to, buf_sz, "}\n"); return written; } BgpPathAttrib* BgpPathAttribNexthop::clone() const { if(hasError()) { logger->log(FATAL, "BgpPathAttribNexthop::clone: can't clone an attribute with error.\n"); throw "has_error"; } return new BgpPathAttribNexthop(*this); } ssize_t BgpPathAttribNexthop::parse(const uint8_t *from, size_t length) { ssize_t header_length = parseHeader(from, length); if (header_length < 0) return -1; if (type_code != NEXT_HOP) { logger->log(FATAL, "BgpPathAttribNexthop::parse: type in header mismatch.\n"); throw "bad_type"; } const uint8_t *buffer = from + 3; if (value_len < 4) { logger->log(ERROR, "BgpPathAttribNexthop::parse: incomplete attrib.\n"); setError(E_UPDATE, E_UNSPEC_UPDATE, NULL, 0); return -1; } if (value_len != 4) { logger->log(ERROR, "BgpPathAttribNexthop::parse: bad length, want 4, saw %d.\n", value_len); setError(E_UPDATE, E_ATTR_LEN, from, value_len + header_length); return -1; } if (optional || !transitive || extended || partial) { logger->log(ERROR, "BgpPathAttribNexthop::parse: bad flag bits, must be !optional, !extended, !partial, transitive.\n"); setError(E_UPDATE, E_ATTR_FLAG, from, value_len + header_length); return -1; } next_hop = getValue<uint32_t>(&buffer); return 7; } ssize_t BgpPathAttribNexthop::write(uint8_t *to, size_t buffer_sz) const { if (buffer_sz < 7) { logger->log(ERROR, "BgpPathAttribNexthop::write: destination buffer size too small.\n"); return -1; } if (writeHeader(to, buffer_sz) < 0) return -1; uint8_t *buffer = to + 2; putValue<uint8_t>(&buffer, 4); // length = 4 putValue<uint32_t>(&buffer, next_hop); return 7; } ssize_t BgpPathAttribNexthop::length() const { return 7; } /** * @brief Construct a new Bgp Path Attrib Med:: Bgp Path Attrib Med object * * @param logger Pointer to logger object for error logging. */ BgpPathAttribMed::BgpPathAttribMed(BgpLogHandler *logger) : BgpPathAttrib(logger) { type_code = MULTI_EXIT_DISC; optional = true; } ssize_t BgpPathAttribMed::doPrint(size_t indent, uint8_t **to, size_t *buf_sz) const { size_t written = 0; written += _print(indent, to, buf_sz, "MedAttribute {\n"); indent++; { written += printFlags(indent, to, buf_sz); written += _print(indent, to, buf_sz, "Med { %d }\n", med); }; indent--; written += _print(indent, to, buf_sz, "}\n"); return written; } BgpPathAttrib* BgpPathAttribMed::clone() const { if(hasError()) { logger->log(FATAL, "BgpPathAttribMed::clone: can't clone an attribute with error.\n"); throw "has_error"; } return new BgpPathAttribMed(*this); } ssize_t BgpPathAttribMed::parse(const uint8_t *from, size_t length) { ssize_t header_length = parseHeader(from, length); if (header_length < 0) return -1; if (type_code != MULTI_EXIT_DISC) { logger->log(FATAL, "BgpPathAttribMed::parse: type in header mismatch.\n"); throw "bad_type"; } const uint8_t *buffer = from + 3; if (value_len < 4) { logger->log(ERROR, "BgpPathAttribMed::parse: incomplete attrib.\n"); setError(E_UPDATE, E_UNSPEC_UPDATE, NULL, 0); return -1; } if (value_len != 4) { logger->log(ERROR, "BgpPathAttribMed::parse: bad length, want 4, saw %d.\n", value_len); setError(E_UPDATE, E_ATTR_LEN, from, value_len + header_length); return -1; } if (!optional || transitive || extended || partial) { logger->log(ERROR, "BgpPathAttribMed::parse: bad flag bits, must be optional, !extended, !partial, !transitive.\n"); setError(E_UPDATE, E_ATTR_FLAG, from, value_len + header_length); return -1; } med = ntohl(getValue<uint32_t>(&buffer)); return 7; } ssize_t BgpPathAttribMed::write(uint8_t *to, size_t buffer_sz) const { if (buffer_sz < 7) { logger->log(ERROR, "BgpPathAttribMed::write: destination buffer size too small.\n"); return -1; } if (writeHeader(to, buffer_sz) < 0) return -1; uint8_t *buffer = to + 2; putValue<uint8_t>(&buffer, 4); // length = 4 putValue<uint32_t>(&buffer, htonl(med)); return 7; } ssize_t BgpPathAttribMed::length() const { return 7; } /** * @brief Construct a new Bgp Path Attrib Local Pref:: Bgp Path Attrib Local Pref object * * @param logger Pointer to logger object for error logging. */ BgpPathAttribLocalPref::BgpPathAttribLocalPref(BgpLogHandler *logger) : BgpPathAttrib(logger) { type_code = LOCAL_PREF; } ssize_t BgpPathAttribLocalPref::doPrint(size_t indent, uint8_t **to, size_t *buf_sz) const { size_t written = 0; written += _print(indent, to, buf_sz, "LocalPrefAttribute {\n"); indent++; { written += printFlags(indent, to, buf_sz); written += _print(indent, to, buf_sz, "LocalPref { %d }\n", local_pref); }; indent--; written += _print(indent, to, buf_sz, "}\n"); return written; } BgpPathAttrib* BgpPathAttribLocalPref::clone() const { if(hasError()) { logger->log(FATAL, "BgpPathAttribLocalPref::clone: can't clone an attribute with error.\n"); throw "has_error"; } return new BgpPathAttribLocalPref(*this); } ssize_t BgpPathAttribLocalPref::parse(const uint8_t *from, size_t length) { ssize_t header_length = parseHeader(from, length); if (header_length < 0) return -1; if (type_code != LOCAL_PREF) { logger->log(FATAL, "BgpPathAttribLocalPref::parse: type in header mismatch.\n"); throw "bad_type"; } const uint8_t *buffer = from + 3; if (value_len < 4) { logger->log(ERROR, "BgpPathAttribLocalPref::parse: incomplete attrib.\n"); setError(E_UPDATE, E_UNSPEC_UPDATE, NULL, 0); return -1; } if (value_len != 4) { logger->log(ERROR, "BgpPathAttribLocalPref::parse: bad length, want 4, saw %d.\n", value_len); setError(E_UPDATE, E_ATTR_LEN, from, value_len + header_length); return -1; } if (optional || !transitive || extended || partial) { logger->log(ERROR, "BgpPathAttribLocalPref::parse: bad flag bits, must be !optional, !extended, !partial, transitive.\n"); setError(E_UPDATE, E_ATTR_FLAG, from, value_len + header_length); return -1; } local_pref = ntohl(getValue<uint32_t>(&buffer)); return 7; } ssize_t BgpPathAttribLocalPref::write(uint8_t *to, size_t buffer_sz) const { if (buffer_sz < 7) { logger->log(ERROR, "BgpPathAttribLocalPref::write: destination buffer size too small.\n"); return -1; } if (writeHeader(to, buffer_sz) < 0) return -1; uint8_t *buffer = to + 2; putValue<uint8_t>(&buffer, 4); // length = 4 putValue<uint32_t>(&buffer, htonl(local_pref)); return 7; } ssize_t BgpPathAttribLocalPref::length() const { return 7; } /** * @brief Construct a new Bgp Path Attrib Atomic Aggregate:: Bgp Path Attrib Atomic Aggregate object * * @param logger Pointer to logger object for error logging. */ BgpPathAttribAtomicAggregate::BgpPathAttribAtomicAggregate(BgpLogHandler *logger) : BgpPathAttrib(logger) { type_code = ATOMIC_AGGREGATE; transitive = true; } ssize_t BgpPathAttribAtomicAggregate::doPrint(size_t indent, uint8_t **to, size_t *buf_sz) const { size_t written = 0; written += _print(indent, to, buf_sz, "AtomicAggregateAttribute {\n"); indent++; { written += printFlags(indent, to, buf_sz); }; indent--; written += _print(indent, to, buf_sz, "}\n"); return written; } BgpPathAttrib* BgpPathAttribAtomicAggregate::clone() const { if(hasError()) { logger->log(FATAL, "BgpPathAttribAtomicAggregate::clone: can't clone an attribute with error.\n"); throw "has_error"; } return new BgpPathAttribAtomicAggregate(*this); } ssize_t BgpPathAttribAtomicAggregate::parse(const uint8_t *from, size_t length) { ssize_t header_length = parseHeader(from, length); if (header_length < 0) return -1; if (type_code != ATOMIC_AGGREGATE) { logger->log(FATAL, "BgpPathAttribAtomicAggregate::parse: type in header mismatch.\n"); throw "bad_type"; } if (value_len != 0) { logger->log(ERROR, "BgpPathAttribAtomicAggregate::parse: bad length, want 0, saw %d.\n", value_len); setError(E_UPDATE, E_ATTR_LEN, from, value_len + header_length); return -1; } if (optional || !transitive || extended || partial) { logger->log(ERROR, "BgpPathAttribAtomicAggregate::parse: bad flag bits, must be !optional, !extended, !partial, transitive.\n"); setError(E_UPDATE, E_ATTR_FLAG, from, value_len + header_length); return -1; } return 3; } ssize_t BgpPathAttribAtomicAggregate::write(uint8_t *to, size_t buffer_sz) const { if (buffer_sz < 3) { logger->log(ERROR, "BgpPathAttribAtomicAggregate::write: destination buffer size too small.\n"); return -1; } if (writeHeader(to, buffer_sz) < 0) return -1; uint8_t *buffer = to + 2; putValue<uint8_t>(&buffer, 0); // length = 0 return 3; } ssize_t BgpPathAttribAtomicAggregate::length() const { return 3; } /** * @brief Construct a new Bgp Path Attrib Aggregator:: Bgp Path Attrib Aggregator object * * @param logger Pointer to logger object for error logging. * @param is_4b Enable four octets ASN support. */ BgpPathAttribAggregator::BgpPathAttribAggregator(BgpLogHandler *logger, bool is_4b) : BgpPathAttrib(logger) { this->is_4b = is_4b; type_code = AGGREATOR; optional = true; transitive = true; } ssize_t BgpPathAttribAggregator::doPrint(size_t indent, uint8_t **to, size_t *buf_sz) const { size_t written = 0; written += _print(indent, to, buf_sz, "AggregatorAttribute {\n"); indent++; { written += printFlags(indent, to, buf_sz); written += _print(indent, to, buf_sz, "Aggregator { %s }\n", inet_ntoa(*(struct in_addr*) &aggregator)); written += _print(indent, to, buf_sz, "AggregatorAsn { %d }\n", aggregator_asn); }; indent--; written += _print(indent, to, buf_sz, "}\n"); return written; } BgpPathAttrib* BgpPathAttribAggregator::clone() const { if(hasError()) { logger->log(FATAL, "BgpPathAttribAggregator::clone: can't clone an attribute with error.\n"); throw "has_error"; } return new BgpPathAttribAggregator(*this); } ssize_t BgpPathAttribAggregator::parse(const uint8_t *from, size_t length) { ssize_t header_length = parseHeader(from, length); if (header_length < 0) return -1; if (type_code != AGGREATOR) { logger->log(FATAL, "BgpPathAttribAggregator::parse: type in header mismatch.\n"); throw "bad_type"; } const uint8_t *buffer = from + 3; const uint8_t want_len = (is_4b ? 8 : 6); if (value_len < want_len) { logger->log(ERROR, "BgpPathAttribAggregator::parse: incomplete attrib.\n"); setError(E_UPDATE, E_UNSPEC_UPDATE, NULL, 0); return -1; } if (value_len != want_len) { logger->log(ERROR, "BgpPathAttribAggregator::parse: bad length, want %d, saw %d.\n", want_len, value_len); setError(E_UPDATE, E_ATTR_LEN, from, value_len + header_length); return -1; } if (!optional || !transitive || extended || partial) { logger->log(ERROR, "BgpPathAttribAggregator::parse: bad flag bits, must be optional, !extended, !partial, transitive.\n"); setError(E_UPDATE, E_ATTR_FLAG, from, value_len + header_length); return -1; } if (is_4b) aggregator_asn = ntohl(getValue<uint32_t>(&buffer)); else aggregator_asn = ntohs(getValue<uint16_t>(&buffer)); aggregator = getValue<uint32_t>(&buffer); return 3 + want_len; } ssize_t BgpPathAttribAggregator::write(uint8_t *to, size_t buffer_sz) const { uint8_t write_value_sz = (is_4b ? 6 : 8); if (buffer_sz < (size_t) (write_value_sz + 3)) { logger->log(ERROR, "BgpPathAttribAggregator::write: destination buffer size too small.\n"); return -1; } if (writeHeader(to, buffer_sz) < 0) return -1; uint8_t *buffer = to + 2; putValue<uint8_t>(&buffer, write_value_sz); if (!is_4b && aggregator_asn >= 0xffff) { logger->log(ERROR, "BgpPathAttribAggregator::write: bad asn. not 4b but asn is %d.\n", aggregator_asn); return -1; } if (is_4b) putValue<uint32_t>(&buffer, htonl(aggregator_asn)); else putValue<uint16_t>(&buffer, htons(aggregator_asn)); putValue<uint32_t>(&buffer, aggregator); return write_value_sz + 3; } ssize_t BgpPathAttribAggregator::length() const { return 3 + (is_4b ? 6 : 8); } /** * @brief Construct a new Bgp Path Attrib As 4 Path:: Bgp Path Attrib As 4 Path object * * @param logger Pointer to logger object for error logging. */ BgpPathAttribAs4Path::BgpPathAttribAs4Path(BgpLogHandler *logger) : BgpPathAttrib(logger) { optional = true; transitive = true; type_code = AS4_PATH; } ssize_t BgpPathAttribAs4Path::doPrint(size_t indent, uint8_t **to, size_t *buf_sz) const { size_t written = 0; written += _print(indent, to, buf_sz, "As4PathAttribute {\n"); indent++; { written += printFlags(indent, to, buf_sz); if (as4_paths.size() == 0) written += _print(indent, to, buf_sz, "As4PathSegments { } \n"); else { written += _print(indent, to, buf_sz, "As4PathSegments {\n"); indent++; { for (const BgpAsPathSegment &seg : as4_paths) { switch (seg.type) { case 1: written += _print(indent, to, buf_sz, "AsSet {\n"); break; case 2: written += _print(indent, to, buf_sz, "AsSequence {\n"); break; default: written += _print(indent, to, buf_sz, "Invalid {\n"); break; } indent++; { for (uint32_t asn : seg.value) { written += _print(indent, to, buf_sz, "%u\n", asn); } }; indent--; written += _print(indent, to, buf_sz, "}\n"); } }; indent--; written += _print(indent, to, buf_sz, "}\n"); } }; indent--; written += _print(indent, to, buf_sz, "}\n"); return written; } BgpPathAttrib* BgpPathAttribAs4Path::clone() const { if(hasError()) { logger->log(FATAL, "BgpPathAttribAs4Path::clone: can't clone an attribute with error.\n"); throw "has_error"; } return new BgpPathAttribAs4Path(*this); } ssize_t BgpPathAttribAs4Path::parse(const uint8_t *from, size_t length) { ssize_t header_length = parseHeader(from, length); if (header_length < 0) return -1; if (type_code != AS4_PATH) { logger->log(FATAL, "BgpPathAttribAs4Path::parse: type in header mismatch.\n"); throw "bad_type"; } if (!optional || !transitive || extended || partial) { logger->log(ERROR, "BgpPathAttribAs4Path::parse: bad flag bits, must be optional, !extended, !partial, transitive.\n"); setError(E_UPDATE, E_ATTR_FLAG, from , value_len + header_length); return -1; } const uint8_t *buffer = from + 3; // empty as_path if (value_len == 0) return 3; uint8_t parsed_len = 0; while (parsed_len < value_len) { // bad as_path if (value_len - parsed_len < 3) { logger->log(ERROR, "BgpPathAttribAs4Path::parse: incomplete as_path segment.\n"); setError(E_UPDATE, E_AS_PATH, NULL, 0); return -1; } uint8_t type = getValue<uint8_t>(&buffer); uint8_t n_asn = getValue<uint8_t>(&buffer); // type & count parsed_len += 2; uint8_t asns_length = n_asn * sizeof(uint32_t); // overflow if (parsed_len + asns_length > value_len) { logger->log(ERROR, "BgpPathAttribAs4Path::parse: as_path overflow attribute length.\n"); setError(E_UPDATE, E_AS_PATH, NULL, 0); return -1; } BgpAsPathSegment path(true, type); for (int i = 0; i < n_asn; i++) path.value.push_back(ntohl(getValue<uint32_t>(&buffer))); as4_paths.push_back(path); // parsed asns parsed_len += asns_length; } if (parsed_len != value_len) { logger->log(FATAL, "BgpPathAttribAs4Path::parse: parsed length and value length mismatch, but no error reported.\n"); throw "bad_parse"; } return parsed_len + 3; } ssize_t BgpPathAttribAs4Path::length() const { size_t len = 3; // header len = 3 for (const BgpAsPathSegment &seg : as4_paths) { len += 4 * seg.value.size() + 2; } return len; } /** * @brief Add a new segment with one ASN in it. * * @param asn The first ASN in the segment. */ void BgpPathAttribAs4Path::addSeg(uint32_t asn) { BgpAsPathSegment segment(true, AS_SEQUENCE); segment.prepend(asn); as4_paths.push_back(segment); } /** * @brief Prepend an ASN into AS4 path. * * This method will prepend an ASN to AS_SEQUENCE segment if the segment is the * first in path. A new AS_SEQUENCE will be create and append to AS_PATH * otherwise. A new AS_SEQUENCE will also be create if the current one is full. * * @param asn The ASN to append. * @return true ASN prepended. * @return false Failed to append ASN. error may be written to stderr with log * handler. */ bool BgpPathAttribAs4Path::prepend(uint32_t asn) { if (as4_paths.size() == 0) { // nothing here yet, add a new sequence. (5.1.2.b.3) addSeg(asn); return true; } // something here already. what to do? BgpAsPathSegment *segment = as4_paths.data(); if (segment->type == AS_SET) { // seg is set, create a new segment of type AS_SEQUENCE (5.1.2.b.2) // FIXME: checks needed: really create a new segment? addSeg(asn); return true; } else if (segment->type == AS_SEQUENCE) { if (segment->getCount() >= 127) { // seg full, create a new segment of type AS_SEQUENCE (5.1.2.b.1) addSeg(asn); return true; } else { segment->prepend(asn); return true; } } logger->log(ERROR, "BgpPathAttribAs4Path::prepend: unknow first segment type: %d, can't append.\n", segment->type); return false; } ssize_t BgpPathAttribAs4Path::write(uint8_t *to, size_t buffer_sz) const { if (buffer_sz < 3) { logger->log(ERROR, "BgpPathAttribAs4Path::write: destination buffer size too small.\n"); return -1; } if (writeHeader(to, buffer_sz) < 0) return -1; uint8_t *buffer = to + 2; // keep track of length field so we can write it later uint8_t *len_field = buffer; // skip length field for now buffer++; uint8_t written_len = 0; for (const BgpAsPathSegment &seg4 : as4_paths) { size_t asn_count = seg4.value.size(); if (asn_count > 127) { logger->log(ERROR, "BgpPathAttribAs4Path::write: segment size too big: %d\n", asn_count); return -1; } // asn list + seg type & asn count size_t bytes_need = asn_count * sizeof(uint32_t) + 2; if (written_len + bytes_need > buffer_sz) { logger->log(ERROR, "BgpPathAttribAs4Path::write: destination buffer size too small.\n"); return -1; } // put type putValue<uint8_t>(&buffer, seg4.type); // put asn count putValue<uint8_t>(&buffer, asn_count); // put asns for (uint32_t asn : seg4.value) { putValue<uint32_t>(&buffer, htonl(asn)); } written_len += bytes_need; } // fill in the length. putValue<uint8_t>(&len_field, written_len); // written_len: the as_paths, 3: attr header (flag, typecode, length) return written_len + 3; } BgpPathAttrib* BgpPathAttribAs4Aggregator::clone() const { if(hasError()) { logger->log(FATAL, "BgpPathAttribAs4Aggregator::clone: can't clone an attribute with error.\n"); throw "has_error"; } return new BgpPathAttribAs4Aggregator(*this); } /** * @brief Construct a new Bgp Path Attrib As 4 Aggregator:: Bgp Path Attrib As 4 Aggregator object * * @param logger Pointer to logger object for error logging. */ BgpPathAttribAs4Aggregator::BgpPathAttribAs4Aggregator(BgpLogHandler *logger) : BgpPathAttrib(logger) { type_code = AS4_AGGREGATOR; optional = true; transitive = true; } ssize_t BgpPathAttribAs4Aggregator::doPrint(size_t indent, uint8_t **to, size_t *buf_sz) const { size_t written = 0; written += _print(indent, to, buf_sz, "Aggregator4Attribute {\n"); indent++; { written += printFlags(indent, to, buf_sz); written += _print(indent, to, buf_sz, "Aggregator { %s }\n", inet_ntoa(*(struct in_addr*) &aggregator)); written += _print(indent, to, buf_sz, "AggregatorAsn { %d }\n", aggregator_asn4); }; indent--; written += _print(indent, to, buf_sz, "}\n"); return written; } ssize_t BgpPathAttribAs4Aggregator::parse(const uint8_t *from, size_t length) { ssize_t header_length = parseHeader(from, length); if (header_length < 0) return -1; if (type_code != AS4_AGGREGATOR) { logger->log(FATAL, "BgpPathAttribAs4Aggregator::parse: type in header mismatch.\n"); throw "bad_type"; } const uint8_t *buffer = from + 3; if (value_len < 8) { logger->log(ERROR, "BgpPathAttribAs4Aggregator::parse: incomplete attrib.\n"); setError(E_UPDATE, E_UNSPEC_UPDATE, NULL, 0); return -1; } if (value_len != 8) { logger->log(ERROR, "BgpPathAttribAs4Aggregator::parse: bad length, want 8, saw %d.\n", value_len); setError(E_UPDATE, E_ATTR_LEN, from, value_len + header_length); return -1; } if (!optional || !transitive || extended || partial) { logger->log(ERROR, "BgpPathAttribAs4Aggregator::parse: bad flag bits, must be optional, !extended, !partial, transitive.\n"); setError(E_UPDATE, E_ATTR_FLAG, from, value_len + header_length); return -1; } aggregator_asn4 = ntohl(getValue<uint32_t>(&buffer)); aggregator = getValue<uint32_t>(&buffer); return 11; } ssize_t BgpPathAttribAs4Aggregator::write(uint8_t *to, size_t buffer_sz) const { if (buffer_sz < 11) { logger->log(ERROR, "BgpPathAttribAs4Aggregator::write: destination buffer size too small.\n"); return -1; } if (writeHeader(to, buffer_sz) < 0) return -1; uint8_t *buffer = to + 2; putValue<uint8_t>(&buffer, 11); putValue<uint32_t>(&buffer, htonl(aggregator_asn4)); putValue<uint32_t>(&buffer, aggregator); return 11; } ssize_t BgpPathAttribAs4Aggregator::length() const { return 11; } /** * @brief Construct a new Bgp Path Attrib Community:: Bgp Path Attrib Community object * * @param logger Pointer to logger object for error logging. */ BgpPathAttribCommunity::BgpPathAttribCommunity(BgpLogHandler *logger) : BgpPathAttrib(logger) { type_code = COMMUNITY; optional = true; transitive = true; } ssize_t BgpPathAttribCommunity::doPrint(size_t indent, uint8_t **to, size_t *buf_sz) const { size_t written = 0; written += _print(indent, to, buf_sz, "CommunityAttribute {\n"); indent++; { written += printFlags(indent, to, buf_sz); written += _print(indent, to, buf_sz, "Community {\n"); indent++; { for (uint32_t community : communites) { uint16_t community_[2]; memcpy(community_, &community, 4); written += _print(indent, to, buf_sz, "%d:%d\n", ntohs(community_[0]), ntohs(community_[1])); } }; indent--; written += _print(indent, to, buf_sz, "}\n"); }; indent--; written += _print(indent, to, buf_sz, "}\n"); return written; } BgpPathAttrib* BgpPathAttribCommunity::clone() const { if(hasError()) { logger->log(FATAL, "BgpPathAttribCommunity::clone: can't clone an attribute with error.\n"); throw "has_error"; } return new BgpPathAttribCommunity(*this); } ssize_t BgpPathAttribCommunity::parse(const uint8_t *from, size_t length) { ssize_t header_length = parseHeader(from, length); if (header_length < 0) return -1; if (type_code != COMMUNITY) { logger->log(FATAL, "BgpPathAttribCommunity::parse: type in header mismatch.\n"); throw "bad_type"; } const uint8_t *buffer = from + 3; if (value_len < 4) { logger->log(ERROR, "BgpPathAttribCommunity::parse: incomplete attrib.\n"); setError(E_UPDATE, E_UNSPEC_UPDATE, NULL, 0); return -1; } if (value_len % 4 != 0) { logger->log(ERROR, "BgpPathAttribCommunity::parse: bad length, want multiple of 4, saw %d.\n", value_len); setError(E_UPDATE, E_ATTR_LEN, from, value_len + header_length); return -1; } if (!optional || !transitive || extended || partial) { logger->log(ERROR, "BgpPathAttribCommunity::parse: bad flag bits, must be optional, !extended, !partial, transitive.\n"); setError(E_UPDATE, E_ATTR_FLAG, from, value_len + header_length); return -1; } size_t read_len = 0; while (read_len < value_len) { communites.push_back(getValue<uint32_t>(&buffer)); read_len += 4; } if (read_len != value_len) { logger->log(FATAL, " BgpPathAttribCommunity::parse: parse ends with read_len != value_len.\n"); throw "bad_parse"; } return value_len + 3; } ssize_t BgpPathAttribCommunity::write(uint8_t *to, size_t buffer_sz) const { if (buffer_sz < 7) { logger->log(ERROR, "BgpPathAttribCommunity::write: destination buffer size too small.\n"); return -1; } if (writeHeader(to, buffer_sz) < 0) return -1; uint8_t *buffer = to + 2; putValue<uint8_t>(&buffer, 4 * communites.size()); // length = 4 * nCommunity size_t write_len = 0; for (uint32_t community : communites) { write_len += putValue<uint32_t>(&buffer, community); } return 3 + write_len; } ssize_t BgpPathAttribCommunity::length() const { return 3 + 4 * communites.size(); } BgpPathAttribMpNlriBase::BgpPathAttribMpNlriBase(BgpLogHandler *logger) : BgpPathAttrib(logger) { optional = true; } int16_t BgpPathAttribMpNlriBase::GetAfiFromBuffer(const uint8_t *buffer, size_t length) { if (length < 3) return -1; const uint8_t *ptr = buffer + 3; return ntohs(getValue<uint16_t>(&ptr)); } ssize_t BgpPathAttribMpNlriBase::parseHeader(const uint8_t *from, size_t length) { ssize_t hdr_len = BgpPathAttrib::parseHeader(from, length); if (hdr_len < 0) return -1; if (!optional || transitive || extended || extended) { logger->log(ERROR, "BgpPathAttribMpNlriBase::parse: bad flag bits, must be optional, !extended, !partial, !transitive.\n"); setError(E_UPDATE, E_ATTR_FLAG, from , value_len + hdr_len); return -1; } if (type_code != MP_REACH_NLRI && type_code != MP_UNREACH_NLRI) { logger->log(FATAL, "BgpPathAttribMpNlriBase::parseHeader: type in header mismatch.\n"); throw "bad_type"; } if (value_len < 5) { logger->log(ERROR, "BgpPathAttribMpNlriBase::parseHeader: incompete attribute.\n"); setError(E_UPDATE, E_OPT_ATTR, NULL, 0); return -1; } const uint8_t *buffer = from + hdr_len; afi = ntohs(getValue<uint16_t>(&buffer)); safi = getValue<uint8_t>(&buffer); return hdr_len + 3; } BgpPathAttribMpReachNlriIpv6::BgpPathAttribMpReachNlriIpv6(BgpLogHandler *logger) : BgpPathAttribMpNlriBase(logger) { afi = IPV6; } BgpPathAttrib* BgpPathAttribMpReachNlriIpv6::clone() const { if (hasError()) { logger->log(ERROR, "BgpPathAttribMpReachNlriIpv6::clone: can't clone an attribute with error.\n"); throw "has_error"; } return new BgpPathAttribMpReachNlriIpv6(*this); } ssize_t BgpPathAttribMpReachNlriIpv6::parse(const uint8_t *from, size_t length) { ssize_t hdr_len = parseHeader(from, length); if (hdr_len < 0) return -1; if (afi != IPV6) { logger->log(FATAL, "BgpPathAttribMpReachNlriIpv6::parse: afi mismatch.\n"); throw "bad_type"; } const uint8_t *buffer = from + hdr_len; uint8_t nexthop_length = getValue<uint8_t>(&buffer); if (nexthop_length != 16 && nexthop_length != 32) { logger->log(ERROR, "BgpPathAttribMpReachNlriIpv6::parse: bad nexthop length %d (want 16 or 32).\n", nexthop_length); setError(E_UPDATE, E_OPT_ATTR, NULL, 0); return -1; } ssize_t buf_left = value_len - hdr_len - 1 + 3; // 3: attr headers if (buf_left < (ssize_t) nexthop_length) { logger->log(ERROR, "BgpPathAttribMpReachNlriIpv6::parse: nexthop overflows buffer.\n"); setError(E_UPDATE, E_OPT_ATTR, NULL, 0); return -1; } memcpy(nexthop_global, buffer, 16); buffer += 16; if (nexthop_length == 32) { memcpy(nexthop_linklocal, buffer, 16); buffer += 16; } else memset(nexthop_linklocal, 0, 16); buf_left -= nexthop_length; if (buf_left < 1) { logger->log(ERROR, "BgpPathAttribMpReachNlriIpv6::parse: reserved bits overflows buffer.\n"); setError(E_UPDATE, E_OPT_ATTR, NULL, 0); return -1; } uint8_t res = getValue<uint8_t>(&buffer); buf_left--; if (res != 0) { logger->log(WARN, "BgpPathAttribMpReachNlriIpv6::parse: reserved bits != 0\n"); } while (buf_left > 0) { Prefix6 this_prefix = Prefix6(); ssize_t pfx_read_len = this_prefix.parse(buffer, buf_left); if (pfx_read_len < 0) { logger->log(ERROR, "BgpPathAttribMpReachNlriIpv6::parse: error parsing nlri entry.\n"); setError(E_UPDATE, E_OPT_ATTR, NULL, 0); return -1; } buffer += pfx_read_len; buf_left -= pfx_read_len; nlri.push_back(this_prefix); } if (buf_left != 0) { logger->log(FATAL, "BgpPathAttribMpReachNlriIpv6::parse: parsed end with non-zero buf_left (%d).\n", buf_left); throw "bad_parse"; } return value_len + hdr_len - 3; // 3: afi/safi, already part of "value_len" } ssize_t BgpPathAttribMpReachNlriIpv6::write(uint8_t *to, size_t buffer_sz) const { ssize_t header_len = writeHeader(to, buffer_sz); if (header_len < 0) return -1; uint8_t *attr_len_field = to + header_len; uint8_t *buffer = attr_len_field + 1; if (buffer_sz - header_len < 5) { logger->log(ERROR, "BgpPathAttribMpReachNlriIpv6::write: dst buffer too small.\n"); return -1; } size_t written_len = header_len + 1; putValue<uint16_t>(&buffer, htons(afi)); putValue<uint8_t>(&buffer, safi); bool has_linklocak = !v6addr_is_zero(nexthop_linklocal); putValue<uint8_t>(&buffer, has_linklocak ? 32 : 16); written_len += 4; if ((has_linklocak && buffer_sz - written_len < 32) || (!has_linklocak && buffer_sz - written_len < 16)) { logger->log(ERROR, "BgpPathAttribMpReachNlriIpv6::write: dst buffer too small.\n"); return -1; } memcpy(buffer, nexthop_global, 16); buffer += 16; written_len += 16; if (has_linklocak) { memcpy(buffer, nexthop_linklocal, 16); buffer += 16; written_len += 16; } putValue<uint8_t>(&buffer, 0); written_len++; for (const Prefix6 &route : nlri) { ssize_t rou_wrt_len = route.write(buffer, buffer_sz - written_len); if (rou_wrt_len < 0) { logger->log(ERROR, "BgpPathAttribMpReachNlriIpv6::write: failed to write nlri.\n"); return -1; } written_len += rou_wrt_len; buffer += rou_wrt_len; } putValue<uint8_t>(&attr_len_field, written_len - 3); if (written_len != (size_t) (buffer - to)) { logger->log(FATAL, "BgpPathAttribMpReachNlriIpv6::write: inconsistent written size (len=%d, diff=%d)\n", written_len, buffer - to); return -1; } return written_len; } ssize_t BgpPathAttribMpReachNlriIpv6::doPrint(size_t indent, uint8_t **to, size_t *buf_sz) const { size_t written = 0; written += _print(indent, to, buf_sz, "MpReachNlriAttribute {\n"); indent++; { written += printFlags(indent, to, buf_sz); const char *safi_str = "Unknow"; if (safi == UNICAST) safi_str = "Unicast"; if (safi == MULTICAST) safi_str = "Multicast"; written += _print(indent, to, buf_sz, "AFI { IPv6 }\n"); written += _print(indent, to, buf_sz, "SAFI { %s }\n", safi_str); char nh_global_str[INET6_ADDRSTRLEN]; inet_ntop(AF_INET6, nexthop_global, nh_global_str, INET6_ADDRSTRLEN); written += _print(indent, to, buf_sz, "Nexthops {\n"); indent++; { written += _print(indent, to, buf_sz, "%s\n", nh_global_str); if (!v6addr_is_zero(nexthop_linklocal)) { char nh_linklocal_str[INET6_ADDRSTRLEN]; inet_ntop(AF_INET6, nexthop_linklocal, nh_linklocal_str, INET6_ADDRSTRLEN); written += _print(indent, to, buf_sz, "%s\n", nh_linklocal_str); } }; indent--; written += _print(indent, to, buf_sz, "}\n"); written += _print(indent, to, buf_sz, "NLRI {\n"); indent++; { for (const Prefix6 &route : nlri) { uint8_t prefix[16]; route.getPrefix(prefix); char prefix_str[INET6_ADDRSTRLEN]; inet_ntop(AF_INET6, prefix, prefix_str, INET6_ADDRSTRLEN); written += _print(indent, to, buf_sz, "%s/%d\n", prefix_str, route.getLength()); } }; indent--; written += _print(indent, to, buf_sz, "}\n"); }; indent--; written += _print(indent, to, buf_sz, "}\n"); return written; } ssize_t BgpPathAttribMpReachNlriIpv6::length() const { size_t len = 3 + 5; // 3: attribute headers, 5: afi, safi, nh_len, res bool has_linklocak = !v6addr_is_zero(nexthop_linklocal); len += (has_linklocak ? 32 : 16); for (const Prefix6 &route : nlri) { len += (1 + (route.getLength() + 7) / 8); } return len; } BgpPathAttribMpReachNlriUnknow::BgpPathAttribMpReachNlriUnknow(BgpLogHandler *logger) : BgpPathAttribMpNlriBase(logger) { nexthop = NULL; nexthop_len = 0; nlri = NULL; nlri_len = 0; } BgpPathAttribMpReachNlriUnknow::BgpPathAttribMpReachNlriUnknow(BgpLogHandler *logger, const uint8_t *nexthop, size_t nexthop_len, const uint8_t *nlri, size_t nlri_len) : BgpPathAttribMpNlriBase(logger) { if (nexthop_len > 0) { this->nexthop = (uint8_t *) malloc(nexthop_len); memcpy(this->nexthop, nexthop, nexthop_len); } if (nlri_len > 0) { this->nlri = (uint8_t *) malloc(nlri_len); memcpy(this->nlri, nlri, nlri_len); } this->nexthop_len = nexthop_len; this->nlri_len = nlri_len; } BgpPathAttribMpReachNlriUnknow::~BgpPathAttribMpReachNlriUnknow() { if (nlri_len != 0) free(nlri); if (nexthop_len != 0) free(nexthop); } BgpPathAttrib* BgpPathAttribMpReachNlriUnknow::clone() const { if (hasError()) { logger->log(FATAL, "BgpPathAttribMpReachNlriUnknow::clone: can't clone an attribute with error.\n"); throw "has_error"; } if (nexthop_len == 0 && nlri_len == 0) return new BgpPathAttribMpReachNlriUnknow(logger); return new BgpPathAttribMpReachNlriUnknow(logger, nexthop, nexthop_len, nlri, nlri_len); } ssize_t BgpPathAttribMpReachNlriUnknow::parse(const uint8_t *from, size_t length) { ssize_t hdr_len = parseHeader(from, length); if (hdr_len < 0) return -1; if (nexthop_len != 0) free(nexthop); const uint8_t *buffer = from + hdr_len; nexthop_len = getValue<uint8_t>(&buffer); size_t parsed_len = hdr_len + 1; if (length < parsed_len + nexthop_len) { logger->log(FATAL, "BgpPathAttribMpReachNlriUnknow::parse: unexpected end of attribute.\n"); setError(E_UPDATE, E_OPT_ATTR, NULL, 0); return -1; } parsed_len += nexthop_len; nexthop = (uint8_t *) malloc(nexthop_len); memcpy(nexthop, buffer, nexthop_len); buffer += nexthop_len; uint8_t res = getValue<uint8_t>(&buffer); parsed_len++; if (res != 0) { logger->log(WARN, "BgpPathAttribMpReachNlriIpv6::parse: reserved bits != 0\n"); } if (nlri_len != 0) free(nlri); nlri_len = value_len - parsed_len - 3; // 3: attr header parsed_len += nlri_len; nlri = (uint8_t *) malloc(nlri_len); memcpy(nlri, buffer, nlri_len); return parsed_len; } ssize_t BgpPathAttribMpReachNlriUnknow::write(uint8_t *to, size_t buffer_sz) const { size_t expected_len = 3 + 5 + nexthop_len + nlri_len; if (buffer_sz < expected_len) { logger->log(ERROR, "BgpPathAttribMpReachNlriUnknow::write: dst buffer too small.\n"); return -1; } ssize_t hdr_len = writeHeader(to, buffer_sz); if (hdr_len < 0) return -1; uint8_t *buffer = to + hdr_len; putValue<uint8_t>(&buffer, expected_len - 3); putValue<uint16_t>(&buffer, htons(afi)); putValue<uint8_t>(&buffer, safi); putValue<uint8_t>(&buffer, nexthop_len); memcpy(buffer, nexthop, nexthop_len); buffer += nexthop_len; putValue<uint8_t>(&buffer, 0); memcpy(buffer, nlri, nlri_len); if ((size_t) (buffer - to) != expected_len) { logger->log(ERROR, "BgpPathAttribMpReachNlriUnknow::write: unexpected written length.\n"); return -1; } return expected_len; } ssize_t BgpPathAttribMpReachNlriUnknow::doPrint(size_t indent, uint8_t **to, size_t *buf_sz) const { size_t written = 0; written += _print(indent, to, buf_sz, "MpReachNlriAttribute {\n"); indent++; { written += printFlags(indent, to, buf_sz); written += _print(indent, to, buf_sz, "AFI { %d }\n", afi); written += _print(indent, to, buf_sz, "SAFI { %d }\n", safi); }; indent--; written += _print(indent, to, buf_sz, "}\n"); return written; } ssize_t BgpPathAttribMpReachNlriUnknow::length() const { return 3 + 5 + nexthop_len + nlri_len; } const uint8_t* BgpPathAttribMpReachNlriUnknow::getNexthop() const { return nexthop; } const uint8_t* BgpPathAttribMpReachNlriUnknow::getNlri() const { return nlri; } size_t BgpPathAttribMpReachNlriUnknow::getNexthopLength() const { return nexthop_len; } size_t BgpPathAttribMpReachNlriUnknow::getNlriLength() const { return nlri_len; } BgpPathAttribMpUnreachNlriIpv6::BgpPathAttribMpUnreachNlriIpv6(BgpLogHandler *logger) : BgpPathAttribMpNlriBase(logger) { afi = IPV6; } BgpPathAttrib* BgpPathAttribMpUnreachNlriIpv6::clone() const { if (hasError()) { logger->log(FATAL, "BgpPathAttribMpUnreachNlriIpv6::clone: can clone attribute with error.\n"); throw "has_error"; } return new BgpPathAttribMpUnreachNlriIpv6(*this); } ssize_t BgpPathAttribMpUnreachNlriIpv6::parse(const uint8_t *from, size_t length) { ssize_t hdr_len = parseHeader(from ,length); if (hdr_len < 0) return -1; if (afi != IPV6) { logger->log(FATAL, "BgpPathAttribMpUnreachNlriIpv6::parse: afi mismatch.\n"); throw "bad_type"; } size_t buf_left = value_len - hdr_len + 3; // 3: attrib headers const uint8_t *buffer = from + hdr_len; while (buf_left > 0) { Prefix6 this_prefix = Prefix6(); ssize_t pfx_read_len = this_prefix.parse(buffer, buf_left); if (pfx_read_len < 0) { logger->log(ERROR, "BgpPathAttribMpUnreachNlriIpv6::parse: error parsing withdrawn entry.\n"); setError(E_UPDATE, E_OPT_ATTR, NULL, 0); return -1; } buffer += pfx_read_len; buf_left -= pfx_read_len; withdrawn_routes.push_back(this_prefix); } if (buf_left != 0) { logger->log(FATAL, "BgpPathAttribMpUnreachNlriIpv6::parse: parsed end with non-zero buf_left (%d).\n", buf_left); throw "bad_parse"; } return hdr_len + value_len - 3; // 3: afi/safi, already part of "value_len" } ssize_t BgpPathAttribMpUnreachNlriIpv6::write(uint8_t *to, size_t buffer_sz) const { if (buffer_sz < 3 + 3) { logger->log(ERROR, "BgpPathAttribMpUnreachNlriIpv6::write: dst buffer too small.\n"); return -1; } ssize_t hdr_len = writeHeader(to, buffer_sz); if (hdr_len < 0) return -1; uint8_t *len_field = to + hdr_len; uint8_t *buffer = len_field + 1; putValue<uint16_t>(&buffer, htons(afi)); putValue<uint8_t>(&buffer, safi); size_t written_val_len = 3; for (const Prefix6 &route : withdrawn_routes) { ssize_t pfx_wrt_ret = route.write(buffer, buffer_sz - 3 - written_val_len); if (pfx_wrt_ret < 0) { logger->log(ERROR, "BgpPathAttribMpUnreachNlriIpv6::write: error writing withdrawn routes.\n"); return -1; } buffer += pfx_wrt_ret; written_val_len += pfx_wrt_ret; } return 3 + written_val_len; } ssize_t BgpPathAttribMpUnreachNlriIpv6::doPrint(size_t indent, uint8_t **to, size_t *buf_sz) const { size_t written = 0; written += _print(indent, to, buf_sz, "MpUnreachNlriAttribute {\n"); indent++; { written += printFlags(indent, to, buf_sz); const char *safi_str = "Unknow"; if (safi == UNICAST) safi_str = "Unicast"; if (safi == MULTICAST) safi_str = "Multicast"; written += _print(indent, to, buf_sz, "AFI { IPv6 }\n"); written += _print(indent, to, buf_sz, "SAFI { %s }\n", safi_str); written += _print(indent, to, buf_sz, "WithdrawnRoutes {\n"); indent++; { for (const Prefix6 &route : withdrawn_routes) { uint8_t prefix[16]; route.getPrefix(prefix); char prefix_str[INET6_ADDRSTRLEN]; inet_ntop(AF_INET6, prefix, prefix_str, INET6_ADDRSTRLEN); written += _print(indent, to, buf_sz, "%s/%d\n", prefix_str, route.getLength()); } }; indent--; written += _print(indent, to, buf_sz, "}\n"); }; indent--; _print(indent, to, buf_sz, "}\n"); return written; } ssize_t BgpPathAttribMpUnreachNlriIpv6::length() const { size_t len = 3 + 3; // 3: attribute headers, 3: afi, safi for (const Prefix6 &route : withdrawn_routes) { len += (1 + (route.getLength() + 7) / 8); } return len; } BgpPathAttribMpUnreachNlriUnknow::BgpPathAttribMpUnreachNlriUnknow(BgpLogHandler *logger) : BgpPathAttribMpNlriBase(logger) { withdrawn_routes_len = 0; withdrawn_routes = NULL; } BgpPathAttribMpUnreachNlriUnknow::BgpPathAttribMpUnreachNlriUnknow(BgpLogHandler *logger, const uint8_t *withdrawn, size_t len) : BgpPathAttribMpNlriBase(logger) { withdrawn_routes_len = len; if (len > 0) { withdrawn_routes = (uint8_t *) malloc(len); memcpy(withdrawn_routes, withdrawn, len); } } BgpPathAttribMpUnreachNlriUnknow::~BgpPathAttribMpUnreachNlriUnknow() { if (withdrawn_routes_len > 0) free(withdrawn_routes); } BgpPathAttrib* BgpPathAttribMpUnreachNlriUnknow::clone() const { if (hasError()) { logger->log(FATAL, "BgpPathAttribMpUnreachNlriUnknow::clone: can clone attribute with error.\n"); throw "has_error"; } if (withdrawn_routes_len == 0) return new BgpPathAttribMpUnreachNlriUnknow(logger); return new BgpPathAttribMpUnreachNlriUnknow(logger, withdrawn_routes, withdrawn_routes_len); } ssize_t BgpPathAttribMpUnreachNlriUnknow::parse(const uint8_t *from, size_t length) { ssize_t hdr_len = parseHeader(from, length); if (hdr_len < 0) return -1; if (withdrawn_routes_len > 0) free(withdrawn_routes); withdrawn_routes_len = value_len - hdr_len; const uint8_t *buffer = from + hdr_len; withdrawn_routes = (uint8_t *) malloc(withdrawn_routes_len); memcpy(withdrawn_routes, buffer, withdrawn_routes_len); return hdr_len + value_len - 3; // 3: afi/safi, already part of "value_len" } ssize_t BgpPathAttribMpUnreachNlriUnknow::write(uint8_t *to, size_t buffer_sz) const { size_t expected_len = 3 + 3 + withdrawn_routes_len; if (buffer_sz < expected_len) { logger->log(ERROR, "BgpPathAttribMpUnreachNlriUnknow::write: dst buffer too small.\n"); return -1; } ssize_t hdr_len = writeHeader(to, buffer_sz); if (hdr_len < 0) return -1; uint8_t *buffer = to + hdr_len; putValue<uint8_t>(&buffer, expected_len - 3); putValue<uint16_t>(&buffer, htons(afi)); putValue<uint8_t>(&buffer, safi); memcpy(buffer, withdrawn_routes, withdrawn_routes_len); return expected_len; } ssize_t BgpPathAttribMpUnreachNlriUnknow::doPrint(size_t indent, uint8_t **to, size_t *buf_sz) const { size_t written = 0; written += _print(indent, to, buf_sz, "MpUnreachNlriAttribute {\n"); indent++; { written += printFlags(indent, to, buf_sz); written += _print(indent, to, buf_sz, "AFI { %d }\n", afi); written += _print(indent, to, buf_sz, "SAFI { %d }\n", safi); }; indent--; written += _print(indent, to, buf_sz, "}\n"); return written; } ssize_t BgpPathAttribMpUnreachNlriUnknow::length() const { return 3 + 3 + withdrawn_routes_len; } const uint8_t* BgpPathAttribMpUnreachNlriUnknow::getWithdrawnRoutes() const { return withdrawn_routes; } size_t BgpPathAttribMpUnreachNlriUnknow::getWithdrawnRoutesLength() const { return withdrawn_routes_len; } }
32.871681
203
0.637337
Nat-Lab
9c386f0871ce737deb7e8b95a6364343dbf0391f
17,957
hpp
C++
timer.hpp
joeljk13/Timer
07174ea48f7012749ef7f1db42bd6a291c1e4d38
[ "MIT" ]
null
null
null
timer.hpp
joeljk13/Timer
07174ea48f7012749ef7f1db42bd6a291c1e4d38
[ "MIT" ]
null
null
null
timer.hpp
joeljk13/Timer
07174ea48f7012749ef7f1db42bd6a291c1e4d38
[ "MIT" ]
null
null
null
#ifndef TIMER_HPP_ #define TIMER_HPP_ 1 #include <algorithm> #include <chrono> #include <iterator> #include <numeric> #include <utility> #include <vector> #include <cmath> #include <cstddef> /* * Each timer stores the total number of repetitions done, and the total * duration (from these, the duration per repetition can be calculated). The * timer does *not* store the function. As a result, you could use multiple * functions with a single timer. The duration and repetitions will just add. */ class timer { public: typedef std::chrono::nanoseconds duration_type; typedef unsigned int repetition_type; typedef long long duration_per_repetition_type; typedef duration_per_repetition_type ratio_type; typedef std::chrono::steady_clock clock_type; /* * Initializes the timer to no duration or repetitions. */ timer() : duration_ (0), reps_ (0) { } /* * Initializes the timer, and immediately calls measure with the arguments. */ template <class Func, class... Args> timer(Func func, repetition_type reps, Args... args) : duration_ (0), reps_ (0) { this->measure(func, reps, std::forward<Args>(args)...); } /* * Initializes the timer, and immediately calls measure with the arguments. */ template <class Func, class Reps, class Period, class... Args> timer(Func func, std::chrono::duration<Reps, Period> duration, Args... args) : duration_ (0), reps_ (0) { this->measure(func, duration, std::forward<Args>(args)...); } /* * Times function 'func' with 'reps' repetitions, and forwards 'args' to * the function. */ template <class Func, class... Args> void measure(Func func, repetition_type reps, Args... args) { clock_type::time_point start, end; reps_ += reps; start = clock_type::now(); while (reps) { --reps; func(std::forward<Args>(args)...); } end = clock_type::now(); duration_ += std::chrono::duration_cast<duration_type>(end - start); } /* * Times function 'func' with duration 'duration'. Automatically stops * after around the amount of time specified by 'duration'. It may not be * exact. Forwards 'args' to the function. */ template <class Func, class Reps, class Period, class... Args> void measure(Func func, std::chrono::duration<Reps, Period> duration, Args... args) { // Find the minimum number of repetitions that measure to nonzero time // (call it n). Then use n to estimate how many repetitions will be // needed to pass half the given duration. After running the function // that many times, update the estimate of repitions for the next // quarter of 'duration'. Keep repeating this until the time alloted // has passed, or the number of repetitions estimated becomes less than // n. clock_type::time_point start, end, func_start (clock_type::now()), func_end (func_start + duration); duration_type func_duration (0); constexpr duration_type zero = duration_type::zero(); repetition_type min_reps; for (min_reps = 1; func_duration == zero; min_reps *= 2) { repetition_type reps = min_reps; start = clock_type::now(); while (reps) { --reps; func(std::forward<Args>(args)...); } end = clock_type::now(); func_duration = std::chrono::duration_cast<duration_type>(end - start); } reps_ += min_reps; duration_ += func_duration; for (duration_type dur; (dur = std::chrono::duration_cast<duration_type>(func_end - end)) > zero; ) { // Try to have this set of repetions spend half of the remaining // time alloted; while this will have more overhead, there's less // chance that it will accidentally go over the time limit repetition_type reps = static_cast<repetition_type>((dur * reps_) / (duration_ * 2)); if (reps < min_reps) { return; } reps_ += reps; start = clock_type::now(); while (reps) { --reps; func(std::forward<Args>(args)...); } end = clock_type::now(); duration_ += std::chrono::duration_cast<duration_type>(end - start); } } duration_type get_duration() const { return duration_; } repetition_type get_repetitions() const { return reps_; } ratio_type get_duration_per_repetition() const { return duration_.count() / reps_; } ratio_type get_ratio() const { return get_duration_per_repetition(); } typedef long double real; /* * The default alpha value for statistical testing. */ static constexpr real default_alpha = 0.1l; /* * Does a statistical analysis (specifically, a t-test) comparing the * timers in 'timers1' and 'timers2'. Uses 'alpha' for the statistical * analysis. */ template <template <class, class...> class container> static int compare(container<timer> timers1, container<timer> timers2, real alpha = default_alpha); // I think these are basically arbitrary numbers. static constexpr repetition_type MIN_REPS = 8; static constexpr unsigned int MAX_TIMERS = 16; /* * Compares 'func1' and 'func2' using 'reps' repetitions, passing 'args' to * each of them. Returns 1 if func1 is faster than func2, -1 if func2 is * faster than func1, and 0 if the difference is not statistically * significant (it uses a t-test to check for significance). */ template <class Func1, class Func2, class... Args> static int compare(Func1 func1, Func2 func2, repetition_type reps, Args... args); /* * Compares 'func1' and 'func2', for the amount of time given by * 'duration'. It may not last for exactly 'duration', but it should be * close. Returns 1 if func1 is faster than func2, -1 if func2 is faster * than func1, and 0 if the difference is not statistically significant (it * uses a t-test to check for significance). * * This is my favorite function, since it's an easy way to compare two * functions in terms of speed, and it uses all the time you give it to get * the best result possible, but it's still gets you the answer when you * want it. */ template <class Func1, class Func2, class Reps, class Period, class... Args> static int compare(Func1 func1, Func2 func2, std::chrono::duration<Reps, Period> duration, Args... args); /* * Calculates the correlation coefficient. */ template <class T, std::size_t N> static real cc(T (&xs)[N], T (&ys)[N]); enum time_complexity { CONSTANT, LOGARITHMIC, LINEAR, LINEARITHMIC, QUADRATIC, CUBIC, QUARTIC, EXPONENTIAL, FACTORIAL }; /* * Approximates the time complexity of 'func' emperically. 'func' should * take a std::size_t argument. It won't be called with argument > max_n * (e.g. for a factorial function max_n should be set <= 20 to prevent * overflow, with sizeof(std::size_t) == 8). * * In my tests, it worked very well, and detected subtle differences like * O(n) vs O(n*log(n)). */ template <class Func, class T, std::size_t N = 15> static time_complexity approx_time_complexity(Func func, std::size_t max_n, T duration_); private: duration_type duration_; repetition_type reps_; }; // class timer template <template <class, class...> class container> int timer::compare(container<timer> timers1, container<timer> timers2, real alpha) { std::vector<real> ratios1, ratios2; int size1 = 0, size2 = 0; real mean1 = 0.0l, mean2 = 0.0l, variance1 = 0.0l, variance2 = 0.0l, residuals = 0.0l; for (const timer &tm : timers1) { real ratio = static_cast<real>(tm.get_duration_per_repetition()); mean1 += ratio; ++size1; ratios1.emplace_back(ratio); } for (const timer & tm : timers2) { real ratio = static_cast<real>(tm.get_duration_per_repetition()); mean2 += ratio; ++size2; ratios2.emplace_back(ratio); } mean1 /= size1; mean2 /= size2; std::sort(ratios1.begin(), ratios1.end()); std::sort(ratios2.begin(), ratios2.end()); for (real ratio : ratios1) { residuals += ratio; variance1 += ratio * ratio; } // Corrected 2-pass formula variance1 = (variance1 - residuals * residuals / size1) / (size1 - 1); residuals = 0.0l; for (real ratio : ratios2) { residuals += ratio; variance2 += ratio * ratio; } // Corrected 2-pass formula variance2 = (variance2 - residuals * residuals / size2) / (size2 - 1); real median1 = ratios1[size1 / 2]; if (size1 % 2 == 0) { median1 = (median1 + ratios1[size1 / 2 + 1]) * 0.5l; } real median2 = ratios2[size2 / 2]; if (size2 % 2 == 0) { median2 = (median2 + ratios2[size2 / 2 + 1]) * 0.5l; } // Test that timers1 < timers2 bool swapped = false; if (mean2 < mean1 && median2 < median1) { swapped = true; // Only swap what will be used later on std::swap(size1, size2); std::swap(mean1, mean2); std::swap(median1, median2); std::swap(variance1, variance2); } if (mean1 >= mean2 || median1 >= median2) { // Neither set won in both mean and median return 0; } // t-test variables real tmp1 = variance1 / size1, tmp2 = variance2 / size2; real t = (mean1 - mean2) / std::sqrt(tmp1 + tmp2); real df = (tmp1 + tmp2) * (tmp1 + tmp2) / (tmp1 * tmp1 / (size1 - 1) + tmp2 * tmp2 / (size2 - 1)); #ifdef BOOST_VERSION boost::math::students_t dist (static_cast<double>(df)); real prob = boost::math::cdf(dist, t); if (prob < alpha) { int ret = (mean1 < mean2 ? 1 : -1); if (swapped) { ret = -ret; } return ret; } return 0; #else // Incomplete beta function real x = df / (t * t + df), a = df * 0.5l, b = 0.5l, tmp = (x <= 0.0l || x >= 1.0l ? 0.0l : std::exp(std::lgamma(a + b) + a * std::log(x) - std::lgamma(a) + b * std::log(1.0l - x) - std::lgamma(b))); bool sub_from_1 = false; if (x >= (a + 1.0l) / (a + b + 2.0l)) { sub_from_1 = true; std::swap(a, b); x = 1.0l - x; } // Use Lentz's method with continued fractions // I don't have good variable names, so these are just single-letter real c = 1.0l, d = 1.0l / (1.0l - (a + b) * x / (a + 1.0l)), e; // This doesn't represent the probability yet, but it will real prob = d; for (int n = 1; n <= 64; ++n) { e = n * (b - n) * x / ((a - 1.0l + n * 2) * (a + n * 2)); d = 1.0l / (e * d + 1.0l); c = e / c + 1.0l; prob *= c * d; e = -(a + n) * (a + b + n) * x / ((a + n * 2) * (a + 1.0l + n * 2)); d = 1.0l / (e * d + 1.0l); c = e / c + 1.0l; prob *= c * d; if (c * d - 1.0l < 1.0e-12l) { break; } } prob *= tmp / a; if (sub_from_1) { prob = 1.0l - prob; } if (prob < 0.0l || prob > 1.0l) { return 0; } if (prob < alpha / 2) { int ret = (mean1 < mean2 ? 1 : -1); if (swapped) { ret = -ret; } return ret; } return 0; #endif } template <class Func1, class Func2, class... Args> int timer::compare(Func1 func1, Func2 func2, timer::repetition_type reps, Args... args) { timer::repetition_type n = 1; std::vector<timer> timers1, timers2; while (reps / (n * 2) >= timer::MIN_REPS && n * 2 <= timer::MAX_TIMERS) { n *= 2; } reps /= n; timers1.reserve(n); timers2.reserve(n); n /= 2; while (n) { --n; timers1.emplace_back(func1, reps, std::forward<Args>(args)...); timers2.emplace_back(func2, reps, std::forward<Args>(args)...); timers2.emplace_back(func2, reps, std::forward<Args>(args)...); timers1.emplace_back(func1, reps, std::forward<Args>(args)...); } return compare(timers1, timers2); } template <class Func1, class Func2, class Reps, class Period, class... Args> int timer::compare(Func1 func1, Func2 func2, std::chrono::duration<Reps, Period> duration, Args... args) { // Add 1 to allow for the time involved in the analysis duration_type dur (std::chrono::duration_cast<duration_type>(duration) / (2 * MAX_TIMERS + 1)); std::vector<timer> timers1, timers2; timers1.reserve(MAX_TIMERS); timers2.reserve(MAX_TIMERS); repetition_type n = MAX_TIMERS / 2; while (n) { --n; timers1.emplace_back(func1, dur, std::forward<Args>(args)...); timers2.emplace_back(func2, dur, std::forward<Args>(args)...); timers2.emplace_back(func2, dur, std::forward<Args>(args)...); timers1.emplace_back(func1, dur, std::forward<Args>(args)...); } return compare(timers1, timers2); } // Calculates the correlation coefficient template <class T, std::size_t N> timer::real timer::cc(T (&xs)[N], T (&ys)[N]) { real x[N], y[N], xmean = 0.0l, ymean = 0.0l; for (std::size_t i = 0; i < N; ++i) { x[i] = static_cast<real>(xs[i]); xmean += x[i]; y[i] = static_cast<real>(ys[i]); ymean += y[i]; } xmean /= N; ymean /= N; real xres, yres, sx = 0.0l, sy = 0.0l, sxy = 0.0l; for (std::size_t i = 0; i < N; ++i) { xres = x[i] - xmean; sx += xres * xres; yres = y[i] - ymean; sy += yres * yres; sxy += xres * yres; } return sxy / std::sqrt(sx * sy); } template <class Func, class T, std::size_t N> timer::time_complexity timer::approx_time_complexity(Func func, std::size_t max_n, T duration) { ratio_type times[N], dur_orig[N], dur[N]; for (std::size_t i = 0, n = 1; i < N; ++i, n += max_n / N) { dur_orig[i] = n; timer tm (func, duration / N, n); times[i] = tm.get_ratio(); } std::vector< std::pair<time_complexity, real> > crs; crs.reserve(N); // O(1) is easy to detect manually, plus it's difficult to detect it via // correlation, so just assume it's not that and move on // Logarithmic for (ratio_type i = 0; i < N; ++i) { dur[i] = std::ilogb(dur_orig[i]); } crs.emplace_back(std::make_pair(LOGARITHMIC, cc(times, dur))); // Linear for (ratio_type i = 0; i < N; ++i) { dur[i] = dur_orig[i]; } crs.emplace_back(std::make_pair(LINEAR, cc(times, dur))); // Linearithmic for (ratio_type i = 0; i < N; ++i) { dur[i] = std::ilogb(dur_orig[i]) * dur_orig[i]; } crs.emplace_back(std::make_pair(LINEARITHMIC, cc(times, dur))); // Quadratic for (ratio_type i = 0; i < N; ++i) { dur[i] = dur_orig[i] * dur_orig[i]; } crs.emplace_back(std::make_pair(QUADRATIC, cc(times, dur))); // Cubic for (ratio_type i = 0; i < N; ++i) { ratio_type tmp = dur_orig[i]; dur[i] = tmp * tmp * tmp; } crs.emplace_back(std::make_pair(CUBIC, cc(times, dur))); // Quartic for (ratio_type i = 0; i < N; ++i) { ratio_type tmp = dur_orig[i]; dur[i] = (tmp * tmp) * (tmp * tmp); } crs.emplace_back(std::make_pair(QUADRATIC, cc(times, dur))); // Only calclate these next ones if they won't overflow // Exponential if (max_n < std::ilogb(std::numeric_limits<ratio_type>::max())) { for (ratio_type i = 0; i < N; ++i) { auto pow2 = [] (ratio_type e) { ratio_type result = 1; ratio_type b = 2; for ( ; e > 0; e /= 2) { if (e % 2 == 1) { result *= b; } b *= b; } return result; }; dur[i] = pow2(dur_orig[i]); } crs.emplace_back(std::make_pair(EXPONENTIAL, cc(times, dur))); } // Factorial if (max_n <= 20) { for (ratio_type i = 0; i < N; ++i) { auto factorial = [] (ratio_type x) -> ratio_type { ratio_type f = 1; for (ratio_type j = 2; j <= x; ++j) { f *= j; } return f; }; dur[i] = factorial(dur_orig[i]); } crs.emplace_back(std::make_pair(FACTORIAL, cc(times, dur))); } auto iter = std::max_element(crs.begin(), crs.end(), [] (const std::pair<time_complexity, real> & elem1, const std::pair<time_complexity, real> & elem2) { return elem1.second < elem2.second; }); return iter->first; } #endif
28.368088
79
0.540736
joeljk13
9c3fcc20596d48b57015504d9e0f58d0e511aa6f
5,880
cpp
C++
libs/libcommon/src/shift10.cpp
ywandy/ClickHouse
a4093f2b1aba01eca7aa901bd0543f17c178b796
[ "Apache-2.0" ]
5
2018-05-10T14:40:44.000Z
2020-12-13T11:43:15.000Z
libs/libcommon/src/shift10.cpp
ywandy/ClickHouse
a4093f2b1aba01eca7aa901bd0543f17c178b796
[ "Apache-2.0" ]
null
null
null
libs/libcommon/src/shift10.cpp
ywandy/ClickHouse
a4093f2b1aba01eca7aa901bd0543f17c178b796
[ "Apache-2.0" ]
2
2020-05-23T04:55:22.000Z
2020-05-24T11:30:51.000Z
#include <common/shift10.h> #include <common/likely.h> #include <limits> template <typename T> static T shift10Impl(T x, int exponent) { static constexpr ssize_t MIN_EXPONENT = -323; static constexpr ssize_t MAX_EXPONENT = 308; static const long double powers10[] = { 1e-323L, 1e-322L, 1e-321L, 1e-320L, 1e-319L, 1e-318L, 1e-317L, 1e-316L, 1e-315L, 1e-314L, 1e-313L, 1e-312L, 1e-311L, 1e-310L,1e-309L,1e-308L,1e-307L,1e-306L,1e-305L,1e-304L,1e-303L,1e-302L,1e-301L,1e-300L,1e-299L,1e-298L,1e-297L,1e-296L,1e-295L,1e-294L,1e-293L,1e-292L,1e-291L, 1e-290L,1e-289L,1e-288L,1e-287L,1e-286L,1e-285L,1e-284L,1e-283L,1e-282L,1e-281L,1e-280L,1e-279L,1e-278L,1e-277L,1e-276L,1e-275L,1e-274L,1e-273L,1e-272L,1e-271L, 1e-270L,1e-269L,1e-268L,1e-267L,1e-266L,1e-265L,1e-264L,1e-263L,1e-262L,1e-261L,1e-260L,1e-259L,1e-258L,1e-257L,1e-256L,1e-255L,1e-254L,1e-253L,1e-252L,1e-251L, 1e-250L,1e-249L,1e-248L,1e-247L,1e-246L,1e-245L,1e-244L,1e-243L,1e-242L,1e-241L,1e-240L,1e-239L,1e-238L,1e-237L,1e-236L,1e-235L,1e-234L,1e-233L,1e-232L,1e-231L, 1e-230L,1e-229L,1e-228L,1e-227L,1e-226L,1e-225L,1e-224L,1e-223L,1e-222L,1e-221L,1e-220L,1e-219L,1e-218L,1e-217L,1e-216L,1e-215L,1e-214L,1e-213L,1e-212L,1e-211L, 1e-210L,1e-209L,1e-208L,1e-207L,1e-206L,1e-205L,1e-204L,1e-203L,1e-202L,1e-201L,1e-200L,1e-199L,1e-198L,1e-197L,1e-196L,1e-195L,1e-194L,1e-193L,1e-192L,1e-191L, 1e-190L,1e-189L,1e-188L,1e-187L,1e-186L,1e-185L,1e-184L,1e-183L,1e-182L,1e-181L,1e-180L,1e-179L,1e-178L,1e-177L,1e-176L,1e-175L,1e-174L,1e-173L,1e-172L,1e-171L, 1e-170L,1e-169L,1e-168L,1e-167L,1e-166L,1e-165L,1e-164L,1e-163L,1e-162L,1e-161L,1e-160L,1e-159L,1e-158L,1e-157L,1e-156L,1e-155L,1e-154L,1e-153L,1e-152L,1e-151L, 1e-150L,1e-149L,1e-148L,1e-147L,1e-146L,1e-145L,1e-144L,1e-143L,1e-142L,1e-141L,1e-140L,1e-139L,1e-138L,1e-137L,1e-136L,1e-135L,1e-134L,1e-133L,1e-132L,1e-131L, 1e-130L,1e-129L,1e-128L,1e-127L,1e-126L,1e-125L,1e-124L,1e-123L,1e-122L,1e-121L,1e-120L,1e-119L,1e-118L,1e-117L,1e-116L,1e-115L,1e-114L,1e-113L,1e-112L,1e-111L, 1e-110L,1e-109L,1e-108L,1e-107L,1e-106L,1e-105L,1e-104L,1e-103L,1e-102L,1e-101L,1e-100L,1e-99L,1e-98L,1e-97L,1e-96L,1e-95L,1e-94L,1e-93L,1e-92L,1e-91L,1e-90L, 1e-89L,1e-88L,1e-87L,1e-86L,1e-85L,1e-84L,1e-83L,1e-82L,1e-81L,1e-80L,1e-79L,1e-78L,1e-77L,1e-76L,1e-75L,1e-74L,1e-73L,1e-72L,1e-71L,1e-70, 1e-69L,1e-68L,1e-67L,1e-66L,1e-65L,1e-64L,1e-63L,1e-62L,1e-61L,1e-60L,1e-59L,1e-58L,1e-57L,1e-56L,1e-55L,1e-54L,1e-53L,1e-52L,1e-51L,1e-50, 1e-49L,1e-48L,1e-47L,1e-46L,1e-45L,1e-44L,1e-43L,1e-42L,1e-41L,1e-40L,1e-39L,1e-38L,1e-37L,1e-36L,1e-35L,1e-34L,1e-33L,1e-32L,1e-31L,1e-30, 1e-29L,1e-28L,1e-27L,1e-26L,1e-25L,1e-24L,1e-23L,1e-22L,1e-21L,1e-20L,1e-19L,1e-18L,1e-17L,1e-16L,1e-15L,1e-14L,1e-13L,1e-12L,1e-11L,1e-10, 1e-9L,1e-8L,1e-7L,1e-6L,1e-5L,1e-4L,1e-3L,1e-2L,1e-1L,1e0L,1e1L,1e2L,1e3L,1e4L,1e5L,1e6L,1e7L,1e8L,1e9L,1e10, 1e11L,1e12L,1e13L,1e14L,1e15L,1e16L,1e17L,1e18L,1e19L,1e20L,1e21L,1e22L,1e23L,1e24L,1e25L,1e26L,1e27L,1e28L,1e29L,1e30, 1e31L,1e32L,1e33L,1e34L,1e35L,1e36L,1e37L,1e38L,1e39L,1e40L,1e41L,1e42L,1e43L,1e44L,1e45L,1e46L,1e47L,1e48L,1e49L,1e50, 1e51L,1e52L,1e53L,1e54L,1e55L,1e56L,1e57L,1e58L,1e59L,1e60L,1e61L,1e62L,1e63L,1e64L,1e65L,1e66L,1e67L,1e68L,1e69L,1e70, 1e71L,1e72L,1e73L,1e74L,1e75L,1e76L,1e77L,1e78L,1e79L,1e80L,1e81L,1e82L,1e83L,1e84L,1e85L,1e86L,1e87L,1e88L,1e89L,1e90, 1e91L,1e92L,1e93L,1e94L,1e95L,1e96L,1e97L,1e98L,1e99L,1e100L,1e101L,1e102L,1e103L,1e104L,1e105L,1e106L,1e107L,1e108L,1e109L,1e110, 1e111L,1e112L,1e113L,1e114L,1e115L,1e116L,1e117L,1e118L,1e119L,1e120L,1e121L,1e122L,1e123L,1e124L,1e125L,1e126L,1e127L,1e128L,1e129L,1e130, 1e131L,1e132L,1e133L,1e134L,1e135L,1e136L,1e137L,1e138L,1e139L,1e140L,1e141L,1e142L,1e143L,1e144L,1e145L,1e146L,1e147L,1e148L,1e149L,1e150, 1e151L,1e152L,1e153L,1e154L,1e155L,1e156L,1e157L,1e158L,1e159L,1e160L,1e161L,1e162L,1e163L,1e164L,1e165L,1e166L,1e167L,1e168L,1e169L,1e170, 1e171L,1e172L,1e173L,1e174L,1e175L,1e176L,1e177L,1e178L,1e179L,1e180L,1e181L,1e182L,1e183L,1e184L,1e185L,1e186L,1e187L,1e188L,1e189L,1e190, 1e191L,1e192L,1e193L,1e194L,1e195L,1e196L,1e197L,1e198L,1e199L,1e200L,1e201L,1e202L,1e203L,1e204L,1e205L,1e206L,1e207L,1e208L,1e209L,1e210, 1e211L,1e212L,1e213L,1e214L,1e215L,1e216L,1e217L,1e218L,1e219L,1e220L,1e221L,1e222L,1e223L,1e224L,1e225L,1e226L,1e227L,1e228L,1e229L,1e230, 1e231L,1e232L,1e233L,1e234L,1e235L,1e236L,1e237L,1e238L,1e239L,1e240L,1e241L,1e242L,1e243L,1e244L,1e245L,1e246L,1e247L,1e248L,1e249L,1e250, 1e251L,1e252L,1e253L,1e254L,1e255L,1e256L,1e257L,1e258L,1e259L,1e260L,1e261L,1e262L,1e263L,1e264L,1e265L,1e266L,1e267L,1e268L,1e269L,1e270, 1e271L,1e272L,1e273L,1e274L,1e275L,1e276L,1e277L,1e278L,1e279L,1e280L,1e281L,1e282L,1e283L,1e284L,1e285L,1e286L,1e287L,1e288L,1e289L,1e290, 1e291L,1e292L,1e293L,1e294L,1e295L,1e296L,1e297L,1e298L,1e299L,1e300L,1e301L,1e302L,1e303L,1e304L,1e305L,1e306L,1e307L,1e308L }; if (unlikely(exponent < MIN_EXPONENT)) /// Note: there are some values below MIN_EXPONENT that is greater than zero. x *= 0; /// Multiplying to keep the sign of zero. else if (unlikely(exponent > MAX_EXPONENT)) x *= std::numeric_limits<T>::infinity(); /// Multiplying to keep the sign of infinity. else x *= powers10[exponent - MIN_EXPONENT]; return x; } double shift10(double x, int exponent) { return shift10Impl(x, exponent); } float shift10(float x, int exponent) { return shift10Impl(x, exponent); } double shift10(UInt64 x, int exponent) { return shift10Impl(static_cast<long double>(x), exponent); } double shift10(Int64 x, int exponent) { return shift10Impl(static_cast<long double>(x), exponent); }
75.384615
168
0.728571
ywandy
9c4344e25291feac116e958142fb34664e920d03
7,085
cpp
C++
testsuites/unittest/fs/vfat/full/It_vfs_fat_873.cpp
qdsxinyee4/PatentsViewh
c0e2da8d88ccb6af89d80e38dfc8f2b70f8627f9
[ "BSD-3-Clause" ]
175
2020-10-21T15:15:18.000Z
2022-03-31T04:59:30.000Z
testsuites/unittest/fs/vfat/full/It_vfs_fat_873.cpp
qdsxinyee4/PatentsViewh
c0e2da8d88ccb6af89d80e38dfc8f2b70f8627f9
[ "BSD-3-Clause" ]
1
2020-12-20T11:41:53.000Z
2020-12-21T04:49:33.000Z
testsuites/unittest/fs/vfat/full/It_vfs_fat_873.cpp
qdsxinyee4/PatentsViewh
c0e2da8d88ccb6af89d80e38dfc8f2b70f8627f9
[ "BSD-3-Clause" ]
39
2020-10-26T03:23:18.000Z
2022-03-28T16:23:03.000Z
/* * Copyright (c) 2013-2019 Huawei Technologies Co., Ltd. All rights reserved. * Copyright (c) 2020-2021 Huawei Device Co., Ltd. All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this list * of conditions and the following disclaimer in the documentation and/or other materials * provided with the distribution. * * 3. Neither the name of the copyright holder nor the names of its contributors may be used * to endorse or promote products derived from this software without specific prior written * permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "It_vfs_fat.h" static UINT32 TestCase(VOID) { INT32 ret; INT32 i = 0; INT32 j = 0; CHAR pathname[FAT_STANDARD_NAME_LENGTH] = FAT_PATH_NAME; CHAR filebuf[260] = "abcdeabcde0123456789abcedfghij9876550210abcdeabcde0123456789abcedfghij9876550210abcdeabcde0123" "456789abcedfghij9876550210abcdeabcde0123456789abcedfghij9876550210abcdeabcde0123456789abcedfgh" "ij9876550210abcdeabcde0123456789abcedfghij9876550210lalalalalalalala"; CHAR *bufWrite = nullptr; CHAR *bufWrite1 = nullptr; CHAR *bufWrite2 = nullptr; g_testCount = 0; ret = mkdir(pathname, S_IRWXU | S_IRWXG | S_IRWXO); ICUNIT_GOTO_EQUAL(ret, FAT_NO_ERROR, ret, EXIT); bufWrite = (CHAR *)malloc(8 * BYTES_PER_MBYTES + 1); // 8 * BYTES_PER_MBYTES = 8MB ICUNIT_GOTO_NOT_EQUAL(bufWrite, NULL, 0, EXIT1); (void)memset_s(bufWrite, 8 * BYTES_PER_MBYTES, 0, 8 * BYTES_PER_MBYTES + 1); // 8 * BYTES_PER_MBYTES = 8MB bufWrite1 = (CHAR *)malloc(BYTES_PER_MBYTES + 1); // BYTES_PER_MBYTES = 1MB ICUNIT_GOTO_NOT_EQUAL(bufWrite1, NULL, 0, EXIT2); (void)memset_s(bufWrite1, BYTES_PER_MBYTES + 1, 0, BYTES_PER_MBYTES + 1); // BYTES_PER_MBYTES = 1MB bufWrite2 = (CHAR *)malloc(16 * BYTES_PER_KBYTES + 1); // 16 * BYTES_PER_KBYTES = 16KB ICUNIT_GOTO_NOT_EQUAL(bufWrite2, NULL, 0, EXIT3); (void)memset_s(bufWrite2, 16 * BYTES_PER_KBYTES + 1, 0, 16 * BYTES_PER_KBYTES + 1); // 16 kb for (j = 0; j < 16; j++) { // 16 * 4 * 256 = 16K (void)strcat_s(bufWrite2, 16 * BYTES_PER_KBYTES + 1, filebuf); // 16 kb // 16 * BYTES_PER_KBYTES = 16KB (void)strcat_s(bufWrite2, 16 * BYTES_PER_KBYTES + 1, filebuf); // 16 kb // 16 * BYTES_PER_KBYTES = 16KB (void)strcat_s(bufWrite2, 16 * BYTES_PER_KBYTES + 1, filebuf); // 16 kb // 16 * BYTES_PER_KBYTES = 16KB (void)strcat_s(bufWrite2, 16 * BYTES_PER_KBYTES + 1, filebuf); // 16 kb // 16 * BYTES_PER_KBYTES = 16KB } for (j = 0; j < 16; j++) { // 16 * 4 * 16K = 1M (void)strcat_s(bufWrite1, BYTES_PER_MBYTES + 1, bufWrite2); // BYTES_PER_MBYTES = 1MB (void)strcat_s(bufWrite1, BYTES_PER_MBYTES + 1, bufWrite2); // BYTES_PER_MBYTES = 1MB (void)strcat_s(bufWrite1, BYTES_PER_MBYTES + 1, bufWrite2); // BYTES_PER_MBYTES = 1MB (void)strcat_s(bufWrite1, BYTES_PER_MBYTES + 1, bufWrite2); // BYTES_PER_MBYTES = 1MB } for (i = 0; i < 4; i++) { // 4 * 2 * 1M = 8M (void)strcat_s(bufWrite, 8 * BYTES_PER_MBYTES + 1, bufWrite1); // 8 * BYTES_PER_KBYTES = 8KB (void)strcat_s(bufWrite, 8 * BYTES_PER_MBYTES + 1, bufWrite1); // 8 * BYTES_PER_KBYTES = 8KB } free(bufWrite1); free(bufWrite2); g_testCount++; (void)memset_s(g_fatPathname1, FAT_STANDARD_NAME_LENGTH, 0, FAT_STANDARD_NAME_LENGTH); (void)strcat_s(g_fatPathname1, FAT_STANDARD_NAME_LENGTH, pathname); (void)strcat_s(g_fatPathname1, FAT_STANDARD_NAME_LENGTH, "/031.txt"); g_fatFfd = fopen64(g_fatPathname1, "w+"); ICUNIT_GOTO_NOT_EQUAL(g_fatFfd, nullptr, g_fatFfd, EXIT2); while (1) { ret = fwrite(bufWrite, strlen(bufWrite), 1, g_fatFfd); if (ret <= 0) { if (g_testCount < (4 * BYTES_PER_KBYTES / 8)) { // 4 * BYTES_PER_KBYTES MB/GB, 8MB per write printf("The biggest file size is smaller than the 4GB,count = :%d,%d", g_testCount, errno); goto EXIT2; } printf("The cycle count = :%d,the file size = :%dMB,= :%0.3lfGB\n", g_testCount, g_testCount * 8, // 8MB per write (g_testCount * 8) * 1.0 / BYTES_PER_KBYTES); // BYTES_PER_KBYTES MB/GB, 8MB per write break; } if (g_testCount >= 256 + 1) { // write more than 256 times for 4GB printf("The cycle count = :%d,the file size = :%dMB,= :%0.3lfGB\n", g_testCount, g_testCount * 8, // 8MB per write (g_testCount * 8) * 1.0 / BYTES_PER_KBYTES); // BYTES_PER_KBYTES MB/GB, 8MB per write break; } g_testCount++; } free(bufWrite); ret = fclose(g_fatFfd); ICUNIT_GOTO_EQUAL(ret, FAT_NO_ERROR, ret, EXIT1); g_fatFfd = fopen64(g_fatPathname1, "w+"); ICUNIT_GOTO_NOT_EQUAL(g_fatFfd, nullptr, g_fatFfd, EXIT2); ret = fclose(g_fatFfd); ICUNIT_GOTO_EQUAL(ret, FAT_NO_ERROR, ret, EXIT1); ret = remove(g_fatPathname1); ICUNIT_GOTO_EQUAL(ret, FAT_NO_ERROR, ret, EXIT0); ret = remove(pathname); ICUNIT_GOTO_EQUAL(ret, FAT_NO_ERROR, ret, EXIT); return FAT_NO_ERROR; EXIT3: free(bufWrite1); EXIT2: free(bufWrite); EXIT1: fclose(g_fatFfd); EXIT0: remove(g_fatPathname1); EXIT: remove(pathname); return FAT_NO_ERROR; } /* * * @ingroup los_fsoperationbigfile * @par type: void * API test * @brief fopen64 操作超过2G大小的文件 * @par description: write the file size to 2GB and fopen64 it * @par precon: task moudle open * @par step: see below * create 2GB file \n * fopen64 this file * @par expect: see below * create file successful \n * operator it successful,return successed * @par prior: nothing */ VOID ItFsFat873(VOID) { TEST_ADD_CASE("IT_FS_FAT_873", TestCase, TEST_VFS, TEST_VFAT, TEST_LEVEL3, TEST_FUNCTION); }
42.172619
120
0.664502
qdsxinyee4
9c44f8381d3ce36a8ee1e3aa9fb1531936dc078a
7,069
hpp
C++
Roguelike/Code/Game/MapGenerator.hpp
cugone/Roguelike
0f53a1ae2a37e683773c1707ce4aeb056973af13
[ "MIT" ]
null
null
null
Roguelike/Code/Game/MapGenerator.hpp
cugone/Roguelike
0f53a1ae2a37e683773c1707ce4aeb056973af13
[ "MIT" ]
4
2021-05-04T03:21:49.000Z
2021-10-06T05:21:24.000Z
Roguelike/Code/Game/MapGenerator.hpp
cugone/Roguelike
0f53a1ae2a37e683773c1707ce4aeb056973af13
[ "MIT" ]
2
2020-01-19T00:50:34.000Z
2021-04-01T07:51:02.000Z
#pragma once #include "Engine/Core/DataUtils.hpp" #include "Engine/Math/AABB2.hpp" #include <string> #include <vector> class Map; class MapGenerator { public: MapGenerator() = delete; explicit MapGenerator(Map* map, const XMLElement& elem) noexcept; MapGenerator(const MapGenerator& other) = delete; MapGenerator(MapGenerator&& other) = delete; MapGenerator& operator=(const MapGenerator& other) = delete; MapGenerator& operator=(MapGenerator&& other) = delete; virtual ~MapGenerator() noexcept = default; virtual void Generate() = 0; protected: void LoadLayers(const XMLElement& elem); virtual void LoadItems(const XMLElement& elem) = 0; virtual void LoadActors(const XMLElement& elem) = 0; virtual void LoadFeatures(const XMLElement& elem) = 0; const XMLElement& _xml_element; Map* _map = nullptr; private: }; class HeightMapGenerator : public MapGenerator { public: HeightMapGenerator() = delete; explicit HeightMapGenerator(Map* map, const XMLElement& elem) noexcept; HeightMapGenerator(const HeightMapGenerator& other) = delete; HeightMapGenerator(HeightMapGenerator&& other) = delete; HeightMapGenerator& operator=(const HeightMapGenerator& other) = delete; HeightMapGenerator& operator=(HeightMapGenerator&& other) = delete; virtual ~HeightMapGenerator() noexcept = default; void Generate() override; protected: private: void LoadItems(const XMLElement& elem) override; void LoadActors(const XMLElement& elem) override; void LoadFeatures(const XMLElement& elem) override; }; //TODO: Implement binary files class FileMapGenerator : public MapGenerator { public: FileMapGenerator() = delete; explicit FileMapGenerator(Map* map, const XMLElement& elem) noexcept; FileMapGenerator(const FileMapGenerator& other) = delete; FileMapGenerator(FileMapGenerator&& other) = delete; FileMapGenerator& operator=(const FileMapGenerator& other) = delete; FileMapGenerator& operator=(FileMapGenerator&& other) = delete; virtual ~FileMapGenerator() noexcept = default; void Generate() override; protected: private: void LoadLayersFromFile(const XMLElement& elem); void LoadItems(const XMLElement& elem) override; void LoadActors(const XMLElement& elem) override; void LoadFeatures(const XMLElement& elem) override; }; class XmlMapGenerator : public MapGenerator { public: XmlMapGenerator() = delete; explicit XmlMapGenerator(Map* map, const XMLElement& elem) noexcept; XmlMapGenerator(const XmlMapGenerator& other) = delete; XmlMapGenerator(XmlMapGenerator&& other) = delete; XmlMapGenerator& operator=(const XmlMapGenerator& other) = delete; XmlMapGenerator& operator=(XmlMapGenerator&& other) = delete; virtual ~XmlMapGenerator() noexcept = default; void Generate() override; protected: private: void LoadLayersFromXml(const XMLElement& elem); void LoadItems(const XMLElement& elem) override; void LoadActors(const XMLElement& elem) override; void LoadFeatures(const XMLElement& elem) override; }; class MazeMapGenerator : public MapGenerator { public: MazeMapGenerator() = delete; explicit MazeMapGenerator(Map* map, const XMLElement& elem) noexcept; MazeMapGenerator(const MazeMapGenerator& other) = delete; MazeMapGenerator(MazeMapGenerator&& other) = delete; MazeMapGenerator& operator=(const MazeMapGenerator& other) = delete; MazeMapGenerator& operator=(MazeMapGenerator&& other) = delete; virtual ~MazeMapGenerator() noexcept = default; static void Generate(Map* map, const XMLElement& elem); virtual void Generate() = 0; protected: virtual void LoadItems(const XMLElement& elem) = 0; virtual void LoadActors(const XMLElement& elem) = 0; virtual void LoadFeatures(const XMLElement& elem) = 0; virtual void PlaceActors() noexcept = 0; virtual void PlaceFeatures() noexcept = 0; virtual void PlaceItems() noexcept = 0; private: }; class RoomsMapGenerator : public MazeMapGenerator { public: RoomsMapGenerator() = delete; explicit RoomsMapGenerator(Map* map, const XMLElement& elem) noexcept; RoomsMapGenerator(const RoomsMapGenerator& other) = delete; RoomsMapGenerator(RoomsMapGenerator&& other) = delete; RoomsMapGenerator& operator=(const RoomsMapGenerator& other) = delete; RoomsMapGenerator& operator=(RoomsMapGenerator&& other) = delete; virtual ~RoomsMapGenerator() noexcept = default; void Generate() override; void GetTileTypes() noexcept; void CreateOrOverwriteLayer(const int width, const int height) noexcept; std::vector<AABB2> rooms{}; std::vector<IntVector2> doors{}; protected: std::string defaultType{"void"}; std::string floorType{"void"}; std::string wallType{"void"}; std::string stairsDownType{"void"}; std::string stairsUpType{"void"}; std::string enterType{"void"}; std::string exitType{"void"}; void FillRoomsWithFloorTiles() noexcept; void LoadActors(const XMLElement& elem) override; void LoadItems(const XMLElement& elem) override; void LoadFeatures(const XMLElement& elem) override; void PlaceActors() noexcept override; void PlaceFeatures() noexcept override; void PlaceItems() noexcept override; private: }; class RoomsOnlyMapGenerator : public RoomsMapGenerator { public: RoomsOnlyMapGenerator() = delete; explicit RoomsOnlyMapGenerator(Map* map, const XMLElement& elem) noexcept; RoomsOnlyMapGenerator(const RoomsOnlyMapGenerator& other) = delete; RoomsOnlyMapGenerator(RoomsOnlyMapGenerator&& other) = delete; RoomsOnlyMapGenerator& operator=(const RoomsOnlyMapGenerator& other) = delete; RoomsOnlyMapGenerator& operator=(RoomsOnlyMapGenerator&& other) = delete; virtual ~RoomsOnlyMapGenerator() noexcept = default; void Generate() override; protected: private: }; class RoomsAndCorridorsMapGenerator : public RoomsMapGenerator { public: RoomsAndCorridorsMapGenerator() = delete; explicit RoomsAndCorridorsMapGenerator(Map* map, const XMLElement& elem) noexcept; RoomsAndCorridorsMapGenerator(const RoomsAndCorridorsMapGenerator& other) = delete; RoomsAndCorridorsMapGenerator(RoomsAndCorridorsMapGenerator&& other) = delete; RoomsAndCorridorsMapGenerator& operator=(const RoomsAndCorridorsMapGenerator& other) = delete; RoomsAndCorridorsMapGenerator& operator=(RoomsAndCorridorsMapGenerator&& other) = delete; virtual ~RoomsAndCorridorsMapGenerator() noexcept = default; void Generate() override; private: void GenerateCorridors() noexcept; bool GenerateExitAndEntrance() noexcept; void MakeHorizontalCorridor(const AABB2& from, const AABB2& to) noexcept; void MakeCorridorSegmentAt(float x, const float y) const noexcept; void MakeVerticalCorridor(const AABB2& from, const AABB2& to) noexcept; bool VerifyExitIsReachable(const IntVector2& enter_loc, const IntVector2& exit_loc) const noexcept; bool CanTileBeCorridorWall(const std::string& name) const noexcept; };
39.713483
104
0.750035
cugone
9c4634f2b35d113eb03512342276c4d2f462d2f0
2,728
hh
C++
src/meshReaders/test/TestHexMeshReader.hh
rspavel/Draco
b279b1afbfbb39f2d521579697172394c5efd81d
[ "BSD-3-Clause-Open-MPI" ]
null
null
null
src/meshReaders/test/TestHexMeshReader.hh
rspavel/Draco
b279b1afbfbb39f2d521579697172394c5efd81d
[ "BSD-3-Clause-Open-MPI" ]
null
null
null
src/meshReaders/test/TestHexMeshReader.hh
rspavel/Draco
b279b1afbfbb39f2d521579697172394c5efd81d
[ "BSD-3-Clause-Open-MPI" ]
null
null
null
//----------------------------------*-C++-*----------------------------------// /*! * \file meshReaders/test/TestHexMeshReader.hh * \author John McGhee * \date Thu Mar 9 08:54:59 2000 * \brief Header file for the Hex_Mesh_Reader class unit test. * \note Copyright (C) 2016-2019 Triad National Security, LLC. * All rights reserved. */ //---------------------------------------------------------------------------// #ifndef __meshReaders_test_TestHexMeshReader_hh__ #define __meshReaders_test_TestHexMeshReader_hh__ #include "ds++/ScalarUnitTest.hh" #include <set> namespace rtt_meshReaders { class Hex_Mesh_Reader; } namespace rtt_meshReaders_test { using rtt_dsxx::UnitTest; bool check_mesh(UnitTest &ut, const rtt_meshReaders::Hex_Mesh_Reader &mesh, const std::string &testid); bool check_nodes(UnitTest &ut, const rtt_meshReaders::Hex_Mesh_Reader &mesh, const std::string &testid); bool check_node_units(UnitTest &ut, const rtt_meshReaders::Hex_Mesh_Reader &mesh); bool check_node_sets(UnitTest &ut, const rtt_meshReaders::Hex_Mesh_Reader &mesh, const std::string &testid); bool check_title(UnitTest &ut, const rtt_meshReaders::Hex_Mesh_Reader &mesh); bool check_element_nodes(UnitTest &ut, const rtt_meshReaders::Hex_Mesh_Reader &mesh, const std::string &testid); bool check_invariant(UnitTest &ut, const rtt_meshReaders::Hex_Mesh_Reader &mesh); bool check_element_sets(UnitTest &ut, const rtt_meshReaders::Hex_Mesh_Reader &mesh, const std::string &testid); bool check_element_types(UnitTest &ut, const rtt_meshReaders::Hex_Mesh_Reader &mesh, const std::string &testid); bool check_unique_element_types(UnitTest &ut, const rtt_meshReaders::Hex_Mesh_Reader &mesh, const std::string &testid); bool compare_double(const double &lhs, const double &rhs); bool check_map(const std::map<std::string, std::set<unsigned>> &elmsets, const std::string &name, const unsigned &begin, const unsigned &end); bool check_get_dims_ndim(UnitTest &ut, const rtt_meshReaders::Hex_Mesh_Reader &mesh, const std::string &testid); } // end namespace rtt_meshReaders_test #endif // __meshReaders_test_TestHexMeshReader_hh__ //---------------------------------------------------------------------------// // end of meshReaders/test/TestHexMeshReader.hh //---------------------------------------------------------------------------//
44
80
0.587243
rspavel
9c46c502f2e74c7cf2b372bb936f0b045a6e73f5
1,280
hpp
C++
sprout/math/acosh.hpp
osyo-manga/Sprout
8885b115f739ef255530f772067475d3bc0dcef7
[ "BSL-1.0" ]
1
2020-02-04T05:16:01.000Z
2020-02-04T05:16:01.000Z
sprout/math/acosh.hpp
osyo-manga/Sprout
8885b115f739ef255530f772067475d3bc0dcef7
[ "BSL-1.0" ]
null
null
null
sprout/math/acosh.hpp
osyo-manga/Sprout
8885b115f739ef255530f772067475d3bc0dcef7
[ "BSL-1.0" ]
null
null
null
#ifndef SPROUT_MATH_ACOSH_HPP #define SPROUT_MATH_ACOSH_HPP #include <limits> #include <type_traits> #include <sprout/config.hpp> #include <sprout/math/detail/config.hpp> #include <sprout/math/log.hpp> #include <sprout/math/sqrt.hpp> #include <sprout/type_traits/enabler_if.hpp> namespace sprout { namespace math { namespace detail { template< typename FloatType, typename sprout::enabler_if<std::is_floating_point<FloatType>::value>::type = sprout::enabler > inline SPROUT_CONSTEXPR FloatType acosh(FloatType x) { return x == 1 ? FloatType(0) : x < 1 ? std::numeric_limits<FloatType>::quiet_NaN() : x == std::numeric_limits<FloatType>::infinity() ? std::numeric_limits<FloatType>::infinity() : sprout::math::log(x + sprout::math::sqrt(x * x - 1)) ; } template< typename IntType, typename sprout::enabler_if<std::is_integral<IntType>::value>::type = sprout::enabler > inline SPROUT_CONSTEXPR double acosh(IntType x) { return sprout::math::detail::acosh(static_cast<double>(x)); } } // namespace detail using NS_SPROUT_MATH_DETAIL::acosh; } // namespace math using sprout::math::acosh; } // namespace sprout #endif // #ifndef SPROUT_MATH_ACOSH_HPP
28.444444
100
0.678906
osyo-manga
9c49e65ac75942222b2b62f7b399395aadf4c1e3
10,084
cpp
C++
Source/Urho3D/Urho2D/StaticSprite2D.cpp
jayrulez/rbfx
8641813787d558b6e8318c1b8e9da86c0e52f9dc
[ "MIT" ]
null
null
null
Source/Urho3D/Urho2D/StaticSprite2D.cpp
jayrulez/rbfx
8641813787d558b6e8318c1b8e9da86c0e52f9dc
[ "MIT" ]
null
null
null
Source/Urho3D/Urho2D/StaticSprite2D.cpp
jayrulez/rbfx
8641813787d558b6e8318c1b8e9da86c0e52f9dc
[ "MIT" ]
null
null
null
// // Copyright (c) 2008-2022 the Urho3D project. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // #include "../Precompiled.h" #include "../Core/Context.h" #include "../Graphics/Material.h" #include "../Graphics/Technique.h" #include "../Graphics/Texture2D.h" #include "../Resource/ResourceCache.h" #include "../Scene/Scene.h" #include "../Urho2D/Renderer2D.h" #include "../Urho2D/Sprite2D.h" #include "../Urho2D/StaticSprite2D.h" #include "../DebugNew.h" namespace Urho3D { extern const char* URHO2D_CATEGORY; StaticSprite2D::StaticSprite2D(Context* context) : Drawable2D(context), blendMode_(BLEND_ALPHA), flipX_(false), flipY_(false), swapXY_(false), color_(Color::WHITE), useHotSpot_(false), useDrawRect_(false), useTextureRect_(false), hotSpot_(0.5f, 0.5f), drawRect_(Rect::ZERO), textureRect_(Rect::ZERO) { sourceBatches_.resize(1); sourceBatches_[0].owner_ = this; } StaticSprite2D::~StaticSprite2D() = default; void StaticSprite2D::RegisterObject(Context* context) { context->RegisterFactory<StaticSprite2D>(URHO2D_CATEGORY); URHO3D_ACCESSOR_ATTRIBUTE("Is Enabled", IsEnabled, SetEnabled, bool, true, AM_DEFAULT); URHO3D_COPY_BASE_ATTRIBUTES(Drawable2D); URHO3D_MIXED_ACCESSOR_ATTRIBUTE("Sprite", GetSpriteAttr, SetSpriteAttr, ResourceRef, ResourceRef(Sprite2D::GetTypeStatic()), AM_DEFAULT); URHO3D_ENUM_ACCESSOR_ATTRIBUTE("Blend Mode", GetBlendMode, SetBlendMode, BlendMode, blendModeNames, BLEND_ALPHA, AM_DEFAULT); URHO3D_ACCESSOR_ATTRIBUTE("Flip X", GetFlipX, SetFlipX, bool, false, AM_DEFAULT); URHO3D_ACCESSOR_ATTRIBUTE("Flip Y", GetFlipY, SetFlipY, bool, false, AM_DEFAULT); URHO3D_ACCESSOR_ATTRIBUTE("Color", GetColor, SetColor, Color, Color::WHITE, AM_DEFAULT); URHO3D_MIXED_ACCESSOR_ATTRIBUTE("Custom material", GetCustomMaterialAttr, SetCustomMaterialAttr, ResourceRef, ResourceRef(Material::GetTypeStatic()), AM_DEFAULT); URHO3D_ACCESSOR_ATTRIBUTE("Hot Spot", GetHotSpot, SetHotSpot, Vector2, Vector2(0.5f, 0.5f), AM_DEFAULT); URHO3D_ACCESSOR_ATTRIBUTE("Use Hot Spot", GetUseHotSpot, SetUseHotSpot, bool, false, AM_DEFAULT); URHO3D_ACCESSOR_ATTRIBUTE("Draw Rectangle", GetDrawRect, SetDrawRect, Rect, Rect::ZERO, AM_DEFAULT); URHO3D_ACCESSOR_ATTRIBUTE("Use Draw Rectangle", GetUseDrawRect, SetUseDrawRect, bool, false, AM_DEFAULT); URHO3D_ACCESSOR_ATTRIBUTE("Texture Rectangle", GetTextureRect, SetTextureRect, Rect, Rect::ZERO, AM_DEFAULT); URHO3D_ACCESSOR_ATTRIBUTE("Use Texture Rectangle", GetUseTextureRect, SetUseTextureRect, bool, false, AM_DEFAULT); } void StaticSprite2D::SetSprite(Sprite2D* sprite) { if (sprite == sprite_) return; sprite_ = sprite; UpdateMaterial(); sourceBatchesDirty_ = true; MarkNetworkUpdate(); UpdateDrawRect(); } void StaticSprite2D::SetDrawRect(const Rect& rect) { drawRect_ = rect; if(useDrawRect_) { sourceBatchesDirty_ = true; } } void StaticSprite2D::SetTextureRect(const Rect& rect) { textureRect_ = rect; if(useTextureRect_) { sourceBatchesDirty_ = true; } } void StaticSprite2D::SetBlendMode(BlendMode blendMode) { if (blendMode == blendMode_) return; blendMode_ = blendMode; UpdateMaterial(); MarkNetworkUpdate(); } void StaticSprite2D::SetFlip(bool flipX, bool flipY, bool swapXY) { if (flipX == flipX_ && flipY == flipY_ && swapXY == swapXY_) return; flipX_ = flipX; flipY_ = flipY; swapXY_ = swapXY; sourceBatchesDirty_ = true; MarkNetworkUpdate(); } void StaticSprite2D::SetFlipX(bool flipX) { SetFlip(flipX, flipY_, swapXY_); } void StaticSprite2D::SetFlipY(bool flipY) { SetFlip(flipX_, flipY, swapXY_); } void StaticSprite2D::SetSwapXY(bool swapXY) { SetFlip(flipX_, flipY_, swapXY); } void StaticSprite2D::SetColor(const Color& color) { if (color == color_) return; color_ = color; sourceBatchesDirty_ = true; MarkNetworkUpdate(); } void StaticSprite2D::SetAlpha(float alpha) { if (alpha == color_.a_) return; color_.a_ = alpha; sourceBatchesDirty_ = true; MarkNetworkUpdate(); } void StaticSprite2D::SetUseHotSpot(bool useHotSpot) { if (useHotSpot == useHotSpot_) return; useHotSpot_ = useHotSpot; sourceBatchesDirty_ = true; MarkNetworkUpdate(); UpdateDrawRect(); } void StaticSprite2D::SetUseDrawRect(bool useDrawRect) { if (useDrawRect == useDrawRect_) return; useDrawRect_ = useDrawRect; sourceBatchesDirty_ = true; MarkNetworkUpdate(); UpdateDrawRect(); } void StaticSprite2D::SetUseTextureRect(bool useTextureRect) { if (useTextureRect == useTextureRect_) return; useTextureRect_ = useTextureRect; sourceBatchesDirty_ = true; MarkNetworkUpdate(); } void StaticSprite2D::SetHotSpot(const Vector2& hotspot) { if (hotspot == hotSpot_) return; hotSpot_ = hotspot; if (useHotSpot_) { sourceBatchesDirty_ = true; MarkNetworkUpdate(); } UpdateDrawRect(); } void StaticSprite2D::SetCustomMaterial(Material* customMaterial) { if (customMaterial == customMaterial_) return; customMaterial_ = customMaterial; sourceBatchesDirty_ = true; UpdateMaterial(); MarkNetworkUpdate(); } Sprite2D* StaticSprite2D::GetSprite() const { return sprite_; } Material* StaticSprite2D::GetCustomMaterial() const { return customMaterial_; } void StaticSprite2D::SetSpriteAttr(const ResourceRef& value) { Sprite2D* sprite = Sprite2D::LoadFromResourceRef(this, value); if (sprite) SetSprite(sprite); } ResourceRef StaticSprite2D::GetSpriteAttr() const { return Sprite2D::SaveToResourceRef(sprite_); } void StaticSprite2D::SetCustomMaterialAttr(const ResourceRef& value) { auto* cache = GetSubsystem<ResourceCache>(); SetCustomMaterial(cache->GetResource<Material>(value.name_)); } ResourceRef StaticSprite2D::GetCustomMaterialAttr() const { return GetResourceRef(customMaterial_, Material::GetTypeStatic()); } void StaticSprite2D::OnSceneSet(Scene* scene) { Drawable2D::OnSceneSet(scene); UpdateMaterial(); } void StaticSprite2D::OnWorldBoundingBoxUpdate() { boundingBox_.Clear(); worldBoundingBox_.Clear(); const ea::vector<SourceBatch2D>& sourceBatches = GetSourceBatches(); for (unsigned i = 0; i < sourceBatches[0].vertices_.size(); ++i) worldBoundingBox_.Merge(sourceBatches[0].vertices_[i].position_); boundingBox_ = worldBoundingBox_.Transformed(node_->GetWorldTransform().Inverse()); } void StaticSprite2D::OnDrawOrderChanged() { sourceBatches_[0].drawOrder_ = GetDrawOrder(); } void StaticSprite2D::UpdateSourceBatches() { if (!sourceBatchesDirty_) return; ea::vector<Vertex2D>& vertices = sourceBatches_[0].vertices_; vertices.clear(); if (!sprite_) return; if (!useTextureRect_) { if (!sprite_->GetTextureRectangle(textureRect_, flipX_, flipY_)) return; } /* V1---------V2 | / | | / | | / | | / | | / | V0---------V3 */ Vertex2D vertex0; Vertex2D vertex1; Vertex2D vertex2; Vertex2D vertex3; // Convert to world space const Matrix3x4& worldTransform = node_->GetWorldTransform(); vertex0.position_ = worldTransform * Vector3(drawRect_.min_.x_, drawRect_.min_.y_, 0.0f); vertex1.position_ = worldTransform * Vector3(drawRect_.min_.x_, drawRect_.max_.y_, 0.0f); vertex2.position_ = worldTransform * Vector3(drawRect_.max_.x_, drawRect_.max_.y_, 0.0f); vertex3.position_ = worldTransform * Vector3(drawRect_.max_.x_, drawRect_.min_.y_, 0.0f); vertex0.uv_ = textureRect_.min_; (swapXY_ ? vertex3.uv_ : vertex1.uv_) = Vector2(textureRect_.min_.x_, textureRect_.max_.y_); vertex2.uv_ = textureRect_.max_; (swapXY_ ? vertex1.uv_ : vertex3.uv_) = Vector2(textureRect_.max_.x_, textureRect_.min_.y_); vertex0.color_ = vertex1.color_ = vertex2.color_ = vertex3.color_ = color_.ToUInt(); vertices.push_back(vertex0); vertices.push_back(vertex1); vertices.push_back(vertex2); vertices.push_back(vertex3); sourceBatchesDirty_ = false; } void StaticSprite2D::UpdateMaterial() { if (customMaterial_) sourceBatches_[0].material_ = customMaterial_; else { if (sprite_ && renderer_) sourceBatches_[0].material_ = renderer_->GetMaterial(sprite_->GetTexture(), blendMode_); else sourceBatches_[0].material_ = nullptr; } } void StaticSprite2D::UpdateDrawRect() { if (!useDrawRect_) { if (useHotSpot_) { if (sprite_ && !sprite_->GetDrawRectangle(drawRect_, hotSpot_, flipX_, flipY_)) return; } else { if (sprite_ && !sprite_->GetDrawRectangle(drawRect_, flipX_, flipY_)) return; } } } }
26.60686
129
0.696351
jayrulez
9c4c318d658199d4e0531c89bc797c295bc46346
1,514
cpp
C++
src/nholthaus/avg_speed_generic.cpp
mpusz/units-compare
1515cb8e163c9f50ebe7571aa329e5c0f332ba72
[ "MIT" ]
1
2019-05-09T12:22:07.000Z
2019-05-09T12:22:07.000Z
src/nholthaus/avg_speed_generic.cpp
mpusz/units_compare
1515cb8e163c9f50ebe7571aa329e5c0f332ba72
[ "MIT" ]
null
null
null
src/nholthaus/avg_speed_generic.cpp
mpusz/units_compare
1515cb8e163c9f50ebe7571aa329e5c0f332ba72
[ "MIT" ]
null
null
null
#include <units.h> #include <cassert> #include <iostream> namespace { template<typename Length, typename Time, typename = std::enable_if_t<units::traits::is_length_unit<Length>::value && units::traits::is_time_unit<Time>::value>> constexpr auto avg_speed(Length d, Time t) { const auto v = d / t; static_assert(units::traits::is_velocity_unit<decltype(v)>::value); return v; } template<typename T> void km_per_h(const T& v) { std::cout << "v = " << v << '\n'; // prints "v = 30.5556 m s^-1" using namespace units::literals; assert(v.value() == 110); assert(v == 110_kph); } void km_per_h() { using namespace units::literals; constexpr auto v = avg_speed(220_km, 2_hr); km_per_h(v); } void km_per_h(double a, double b) { const auto v = avg_speed(units::length::kilometer_t(a), units::time::hour_t(b)); km_per_h(v); } template<typename T> void mi_per_h(const T& v) { std::cout << "v = " << v << '\n'; // prints "v = 31.2928 m s^-1" using namespace units::literals; assert(v.value() == 70); assert(v == 70_mph); } void mi_per_h() { using namespace units::literals; const auto v = avg_speed(140_mi, 2_hr); mi_per_h(v); } void mi_per_h(double a, double b) { const auto v = avg_speed(units::length::mile_t(a), units::time::hour_t(b)); mi_per_h(v); } } // namespace int main() { km_per_h(); km_per_h(220, 2); mi_per_h(); mi_per_h(140, 2); }
21.027778
85
0.601717
mpusz
9c4d4e43b18262e132c658f70e801c10fd0542c7
1,225
cc
C++
test/unittests/heap/cppgc/tests.cc
yuri91/v8
be3a6690bd47c6ff3d34188f260a67347b7d94e4
[ "BSD-3-Clause" ]
null
null
null
test/unittests/heap/cppgc/tests.cc
yuri91/v8
be3a6690bd47c6ff3d34188f260a67347b7d94e4
[ "BSD-3-Clause" ]
null
null
null
test/unittests/heap/cppgc/tests.cc
yuri91/v8
be3a6690bd47c6ff3d34188f260a67347b7d94e4
[ "BSD-3-Clause" ]
null
null
null
// Copyright 2020 the V8 project authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "test/unittests/heap/cppgc/tests.h" #include <memory> #include "src/heap/cppgc/object-allocator.h" #include "test/unittests/heap/cppgc/test-platform.h" namespace cppgc { namespace internal { namespace testing { // static std::shared_ptr<TestPlatform> TestWithPlatform::platform_; // static void TestWithPlatform::SetUpTestSuite() { platform_ = std::make_unique<TestPlatform>( std::make_unique<DelegatingTracingController>()); cppgc::InitializeProcess(platform_->GetPageAllocator()); } // static void TestWithPlatform::TearDownTestSuite() { cppgc::ShutdownProcess(); platform_.reset(); } TestWithHeap::TestWithHeap() : heap_(Heap::Create(platform_)), allocation_handle_(heap_->GetAllocationHandle()) {} void TestWithHeap::ResetLinearAllocationBuffers() { Heap::From(GetHeap())->object_allocator().ResetLinearAllocationBuffers(); } TestSupportingAllocationOnly::TestSupportingAllocationOnly() : no_gc_scope_(GetHeap()->GetHeapHandle()) {} } // namespace testing } // namespace internal } // namespace cppgc
26.630435
75
0.752653
yuri91
9c5082762df40761a36f4ef0674a575ea7dc3b55
15,766
cpp
C++
Paper/Private/PathFitter.cpp
mokafolio/Paper
d7e9c1450b29b1d3d8873de4f959bffa02232055
[ "MIT" ]
20
2016-12-13T22:34:35.000Z
2021-09-20T12:44:56.000Z
Paper/Private/PathFitter.cpp
mokafolio/Paper
d7e9c1450b29b1d3d8873de4f959bffa02232055
[ "MIT" ]
null
null
null
Paper/Private/PathFitter.cpp
mokafolio/Paper
d7e9c1450b29b1d3d8873de4f959bffa02232055
[ "MIT" ]
null
null
null
#include <Paper/Private/PathFitter.hpp> #include <Paper/Segment.hpp> #include <Paper/Constants.hpp> #include <Paper/Components.hpp> #include <Paper/Document.hpp> namespace paper { namespace detail { using namespace stick; using namespace crunch; PathFitter::PathFitter(const Path & _p, Float64 _error, bool _bIgnoreClosed) : m_path(_p), m_error(_error), m_bIgnoreClosed(_bIgnoreClosed) { auto & segs = m_path.segmentArray(); m_positions.reserve(segs.count()); Vec2f prev, point; prev = point = Vec2f(0); // Copy over points from path and filter out adjacent duplicates. for (stick::Size i = 0; i < segs.count(); ++i) { point = segs[i]->position(); if (i < 1 || prev != point) { m_positions.append(point); prev = point; } } // printf("PREV C %lu\n", m_positions.count()); if (m_path.isClosed() && !m_bIgnoreClosed) { // printf("F %f %f L %f %f\n", m_positions[0].x, m_positions[0].y, // m_positions.last().x, m_positions.last().y); //this is kinda unefficient :( we should propably just insert that point first //rather than shifting the whole array Vec2f last = m_positions.last(); m_positions.insert(m_positions.begin(), last); m_positions.append(m_positions[1]); // The point previously at index 0 is now 1. } // for (auto & pos : m_positions) // { // printf("POS %f %f\n", pos.x, pos.y); // } // printf("POS COUNT %lu\n", m_positions.count()); } void PathFitter::fit() { if (m_positions.count() > 0) { m_newSegments.append({m_positions[0], Vec2f(0), Vec2f(0)}); stick::Size i = 0; stick::Size count = m_newSegments.count(); bool bReclose = false; if (m_positions.count() > 1) { fitCubic(0, m_positions.count() - 1, // Left Tangent m_positions[1] - m_positions[0], // Right Tangent m_positions[m_positions.count() - 2] - m_positions[m_positions.count() - 1]); if (m_path.isClosed()) { // i++; // if (count > 0) // count--; bReclose = true; m_path.set<comps::ClosedFlag>(false); // printf("F %f %f L %f %f\n", (*m_newSegments.begin()).position.x, (*m_newSegments.begin()).position.y, // m_newSegments.last().position.x, m_newSegments.last().position.y); if (!m_bIgnoreClosed) { m_newSegments.remove(m_newSegments.begin()); m_newSegments.removeLast(); } } } // m_path.removeSegments(); auto & segs = m_path.segmentArray(); segs.clear(); Document doc = m_path.document(); for (i = 0; i < m_newSegments.count(); ++i) { segs.append(stick::makeUnique<Segment>(doc.allocator(), m_path, m_newSegments[i].position, m_newSegments[i].handleIn, m_newSegments[i].handleOut, segs.count())); } m_path.rebuildCurves(); if (bReclose) m_path.closePath(); } // printf("SOOOOO SIMPLEEE\n"); } void PathFitter::fitCubic(stick::Size _first, stick::Size _last, const Vec2f & _tan1, const Vec2f & _tan2) { // printf("FIRST %lu LAST %lu\n", _first, _last); // Use heuristic if region only has two points in it if (_last - _first == 1) { // printf("heuristic\n"); const Vec2f & pt1 = m_positions[_first]; const Vec2f & pt2 = m_positions[_last]; Float64 dist = crunch::distance(pt1, pt2) / 3.0; addCurve(pt1, pt1 + normalize(_tan1) * dist, pt2 + normalize(_tan2) * dist, pt2); return; } stick::DynamicArray<Float64> uPrime; chordLengthParameterize(_first, _last, uPrime); // printf("NORMAL\n"); Float64 maxError = std::max(m_error, m_error * m_error); stick::Size split; bool bParametersInOrder = true; // Try 4 iterations for (stick::Int32 i = 0; i <= 4; ++i) { Bezier curve = generateBezier(_first, _last, uPrime, _tan1, _tan2); // printf("GEN BEZ %f %f, %f %f, %f %f, %f %f\n", curve.positionOne().x, curve.positionOne().y, // curve.handleOne().x, curve.handleOne().y, // curve.handleTwo().x, curve.handleTwo().y, // curve.positionTwo().x, curve.positionTwo().y); // Find max deviation of points to fitted curve auto max = findMaxError(_first, _last, curve, uPrime); if (max.value < m_error && bParametersInOrder) { // printf("ADDING CURVE\n"); addCurve(curve.positionOne(), curve.handleOne(), curve.handleTwo(), curve.positionTwo()); return; } split = max.index; // If error not too large, try reparameterization and iteration if (max.value >= maxError) { // printf("MAX ERROR %f %f %f\n", m_error, maxError, max.value); break; } bParametersInOrder = reparameterize(_first, _last, uPrime, curve); maxError = max.value; } // Fitting failed -- split at max error point and fit recursively // Vec2f v1 = m_positions[split - 1] - m_positions[split]; // Vec2f v2 = m_positions[split] - m_positions[split + 1]; // Vec2f tanCenter = crunch::normalize((v1 + v2) * 0.5); Vec2f tanCenter = m_positions[split - 1] - m_positions[split + 1]; fitCubic(_first, split, _tan1, tanCenter); fitCubic(split, _last, -tanCenter, _tan2); } void PathFitter::addCurve(const Vec2f & _pointOne, const Vec2f & _handleOne, const Vec2f & _handleTwo, const Vec2f & _pointTwo) { m_newSegments.last().handleOut = _handleOne - _pointOne; m_newSegments.append({_pointTwo, _handleTwo - _pointTwo, Vec2f(0)}); } Bezier PathFitter::generateBezier(stick::Size _first, stick::Size _last, const stick::DynamicArray<Float64> & _uPrime, const Vec2f & _tan1, const Vec2f & _tan2) { static const Float64 s_epsilon = detail::PaperConstants::epsilon(); const Vec2f & pt1 = m_positions[_first]; const Vec2f & pt2 = m_positions[_last]; Float64 c[2][2] = {{0, 0}, {0, 0}}; Float64 x[2] = {0, 0}; for (stick::Size i = 0, l = _last - _first + 1; i < l; ++i) { Float64 u = _uPrime[i]; Float64 t = 1.0 - u; Float64 b = 3.0 * u * t; Float64 b0 = t * t * t; Float64 b1 = b * t; Float64 b2 = b * u; Float64 b3 = u * u * u; Vec2f a1 = normalize(_tan1) * b1; Vec2f a2 = normalize(_tan2) * b2; Vec2f tmp = m_positions[_first + i]; tmp -= pt1 * (b0 + b1); tmp -= pt2 * (b2 + b3); c[0][0] += crunch::dot(a1, a1); c[0][1] += crunch::dot(a1, a2); c[1][0] = c[0][1]; c[1][1] += crunch::dot(a2, a2); x[0] += crunch::dot(a1, tmp); x[1] += crunch::dot(a2, tmp); } Float64 detC0C1 = c[0][0] * c[1][1] - c[1][0] * c[0][1]; Float64 alpha1, alpha2; if (crunch::abs(detC0C1) > s_epsilon) { // Kramer's rule Float64 detC0X = c[0][0] * x[1] - c[1][0] * x[0]; Float64 detXC1 = x[0] * c[1][1] - x[1] * c[0][1]; // Derive alpha values alpha1 = detXC1 / detC0C1; alpha2 = detC0X / detC0C1; } else { // Matrix is under-determined, try assuming alpha1 == alpha2 Float64 c0 = c[0][0] + c[0][1]; Float64 c1 = c[1][0] + c[1][1]; if (crunch::abs(c0) > s_epsilon) { alpha1 = alpha2 = x[0] / c0; } else if (crunch::abs(c1) > s_epsilon) { alpha1 = alpha2 = x[1] / c1; } else { // Handle below alpha1 = alpha2 = 0; } } // If alpha negative, use the Wu/Barsky heuristic (see text) // (if alpha is 0, you get coincident control points that lead to // divide by zero in any subsequent NewtonRaphsonRootFind() call. Float64 segLength = crunch::distance(pt1, pt2); Float64 epsilon = s_epsilon * segLength; Vec2f handleOne(0); Vec2f handleTwo(0); if (alpha1 < epsilon || alpha2 < epsilon) { // fall back on standard (probably inaccurate) formula, // and subdivide further if needed. alpha1 = alpha2 = segLength / 3.0; } else { // Check if the found control points are in the right order when // projected onto the line through pt1 and pt2. Vec2f line = pt2 - pt1; handleOne = normalize(_tan1) * alpha1; handleTwo = normalize(_tan2) * alpha2; if (crunch::dot(handleOne, line) - crunch::dot(handleTwo, line) > segLength * segLength) { // Fall back to the Wu/Barsky heuristic above. alpha1 = alpha2 = segLength / 3.0; handleOne = normalize(_tan1) * alpha1; handleTwo = normalize(_tan2) * alpha2; } } // First and last control points of the Bezier curve are // positioned exactly at the first and last data points // Control points 1 and 2 are positioned an alpha distance out // on the tangent vectors, left and right, respectively // printf("PT1, %f %f, PT2 %f %f\n", pt1.x, pt1.y, handleOne.x, handleOne.y); return Bezier(pt1, pt1 + handleOne, pt2 + handleTwo, pt2); } Vec2f PathFitter::evaluate(stick::Int32 _degree, const Bezier & _curve, Float64 _t) { Vec2f tmp[4] = {_curve.positionOne(), _curve.handleOne(), _curve.handleTwo(), _curve.positionTwo()}; // printf("BEZ %f %f, %f %f, %f %f, %f %f\n", _curve.positionOne().x, _curve.positionOne().y, // _curve.handleOne().x, _curve.handleOne().y, // _curve.handleTwo().x, _curve.handleTwo().y, // _curve.positionTwo().x, _curve.positionTwo().y); for (stick::Int32 i = 1; i <= _degree; ++i) { for (stick::Int32 j = 0; j <= _degree - i; ++j) { tmp[j] = tmp[j] * (1 - _t) + tmp[j + 1] * _t; } } return tmp[0]; } bool PathFitter::reparameterize(stick::Size _first, stick::Size _last, stick::DynamicArray<Float64> & _u, const Bezier & _curve) { // printf("REPARA\n"); for (stick::Size i = _first; i <= _last; ++i) { _u[i - _first] = findRoot(_curve, m_positions[i], _u[i - _first]); } // Detect if the new parameterization has reordered the points. // In that case, we would fit the points of the path in the wrong order. for (stick::Size i = 1; i < _u.count(); ++i) { if (_u[i] <= _u[i - 1]) return false; } return true; } Float64 PathFitter::findRoot(const Bezier & _curve, const Vec2f & _point, Float64 _u) { static Float64 s_tolerance = detail::PaperConstants::tolerance(); Bezier curve1; Bezier curve2; // control vertices for Q' curve1.setPositionOne((_curve.handleOne() - _curve.positionOne()) * 3.0); curve1.setHandleOne((_curve.handleTwo() - _curve.handleOne()) * 3.0); curve1.setHandleTwo((_curve.positionTwo() - _curve.handleTwo()) * 3.0); // control vertices for Q'' curve2.setPositionOne((curve1.handleOne() - curve1.positionOne()) * 2.0); curve2.setHandleOne((curve1.handleTwo() - curve1.handleOne()) * 2.0); // Compute Q(u), Q'(u) and Q''(u) Vec2f pt = evaluate(3, _curve, _u); Vec2f pt1 = evaluate(2, curve1, _u); Vec2f pt2 = evaluate(1, curve2, _u); Vec2f diff = pt - _point; Float64 df = crunch::dot(pt1, pt1) + crunch::dot(diff, pt2); // u = u - f(u) / f'(u) return crunch::isClose(df, (Float64)0.0) ? _u : _u - crunch::dot(diff, pt1) / df; } void PathFitter::chordLengthParameterize(stick::Size _first, stick::Size _last, stick::DynamicArray<Float64> & _outResult) { stick::Size size = _last - _first; _outResult.resize(size + 1); _outResult[0] = 0; for (stick::Size i = _first + 1; i <= _last; ++i) { _outResult[i - _first] = _outResult[i - _first - 1] + crunch::distance(m_positions[i], m_positions[i - 1]); } for (stick::Size i = 1; i <= size; i++) _outResult[i] /= _outResult[size]; } PathFitter::MaxError PathFitter::findMaxError(stick::Size _first, stick::Size _last, const Bezier & _curve, const stick::DynamicArray<Float64> & _u) { stick::Size index = crunch::floor((_last - _first + 1) / 2.0); Float64 maxDist = 0; for (stick::Size i = _first + 1; i < _last; ++i) { Vec2f p = evaluate(3, _curve, _u[i - _first]); // printf("P %f %f\n", p.x, p.y); Vec2f v = p - m_positions[i]; Float64 dist = v.x * v.x + v.y * v.y; // squared // printf("D %f\n", dist); if (dist >= maxDist) { maxDist = dist; index = i; } } return {maxDist, index}; } } }
40.219388
181
0.464417
mokafolio
9c51f793e2487a5b74d7ae60deb77e17f066bdf3
7,734
cpp
C++
source/math/BoundingBox.cpp
HeavenWu/slimdx
e014bb34b89bbf694d01c8f6d6b6dfa3cba58aac
[ "MIT" ]
85
2015-04-06T05:37:10.000Z
2022-03-22T19:53:03.000Z
source/math/BoundingBox.cpp
HeavenWu/slimdx
e014bb34b89bbf694d01c8f6d6b6dfa3cba58aac
[ "MIT" ]
10
2016-03-17T11:18:24.000Z
2021-05-11T09:21:43.000Z
source/math/BoundingBox.cpp
HeavenWu/slimdx
e014bb34b89bbf694d01c8f6d6b6dfa3cba58aac
[ "MIT" ]
45
2015-09-14T03:54:01.000Z
2022-03-22T19:53:09.000Z
#include "stdafx.h" /* * Copyright (c) 2007-2012 SlimDX Group * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #include <d3dx9.h> #include "../SlimDXException.h" #include "../DataStream.h" #include "BoundingBox.h" #include "BoundingSphere.h" #include "Ray.h" #include "Plane.h" using namespace System; using namespace System::Globalization; namespace SlimDX { BoundingBox::BoundingBox( Vector3 minimum, Vector3 maximum ) { Minimum = minimum; Maximum = maximum; } array<Vector3>^ BoundingBox::GetCorners() { array<Vector3>^ results = gcnew array<Vector3>( 8 ); results[0] = Vector3(Minimum.X, Maximum.Y, Maximum.Z); results[1] = Vector3(Maximum.X, Maximum.Y, Maximum.Z); results[2] = Vector3(Maximum.X, Minimum.Y, Maximum.Z); results[3] = Vector3(Minimum.X, Minimum.Y, Maximum.Z); results[4] = Vector3(Minimum.X, Maximum.Y, Minimum.Z); results[5] = Vector3(Maximum.X, Maximum.Y, Minimum.Z); results[6] = Vector3(Maximum.X, Minimum.Y, Minimum.Z); results[7] = Vector3(Minimum.X, Minimum.Y, Minimum.Z); return results; } ContainmentType BoundingBox::Contains( BoundingBox box1, BoundingBox box2 ) { if( box1.Maximum.X < box2.Minimum.X || box1.Minimum.X > box2.Maximum.X ) return ContainmentType::Disjoint; if( box1.Maximum.Y < box2.Minimum.Y || box1.Minimum.Y > box2.Maximum.Y ) return ContainmentType::Disjoint; if( box1.Maximum.Z < box2.Minimum.Z || box1.Minimum.Z > box2.Maximum.Z ) return ContainmentType::Disjoint; if( box1.Minimum.X <= box2.Minimum.X && box2.Maximum.X <= box1.Maximum.X && box1.Minimum.Y <= box2.Minimum.Y && box2.Maximum.Y <= box1.Maximum.Y && box1.Minimum.Z <= box2.Minimum.Z && box2.Maximum.Z <= box1.Maximum.Z ) return ContainmentType::Contains; return ContainmentType::Intersects; } ContainmentType BoundingBox::Contains( BoundingBox box, BoundingSphere sphere ) { float dist; Vector3 clamped; Vector3::Clamp( sphere.Center, box.Minimum, box.Maximum, clamped ); float x = sphere.Center.X - clamped.X; float y = sphere.Center.Y - clamped.Y; float z = sphere.Center.Z - clamped.Z; dist = (x * x) + (y * y) + (z * z); float radius = sphere.Radius; if( dist > (radius * radius) ) return ContainmentType::Disjoint; if( box.Minimum.X + radius <= sphere.Center.X && sphere.Center.X <= box.Maximum.X - radius && box.Maximum.X - box.Minimum.X > radius && box.Minimum.Y + radius <= sphere.Center.Y && sphere.Center.Y <= box.Maximum.Y - radius && box.Maximum.Y - box.Minimum.Y > radius && box.Minimum.Z + radius <= sphere.Center.Z && sphere.Center.Z <= box.Maximum.Z - radius && box.Maximum.X - box.Minimum.X > radius ) return ContainmentType::Contains; return ContainmentType::Intersects; } ContainmentType BoundingBox::Contains( BoundingBox box, Vector3 vector ) { if( box.Minimum.X <= vector.X && vector.X <= box.Maximum.X && box.Minimum.Y <= vector.Y && vector.Y <= box.Maximum.Y && box.Minimum.Z <= vector.Z && vector.Z <= box.Maximum.Z ) return ContainmentType::Contains; return ContainmentType::Disjoint; } BoundingBox BoundingBox::FromPoints( array<Vector3>^ points ) { if( points == nullptr || points->Length <= 0 ) throw gcnew ArgumentNullException( "points" ); Vector3 min = Vector3( float::MaxValue ); Vector3 max = Vector3( float::MinValue ); for each( Vector3 vector in points ) { Vector3::Minimize( min, vector, min ); Vector3::Maximize( max, vector, max ); } return BoundingBox( min, max ); } BoundingBox BoundingBox::FromPoints( DataStream^ points, int count, int stride ) { BoundingBox box; HRESULT hr = D3DXComputeBoundingBox( reinterpret_cast<D3DXVECTOR3*>( points->PositionPointer ), count, stride, reinterpret_cast<D3DXVECTOR3*>( &box.Minimum ), reinterpret_cast<D3DXVECTOR3*>( &box.Maximum ) ); if( RECORD_SDX( hr ).IsFailure ) return BoundingBox(); return box; } BoundingBox BoundingBox::FromSphere( BoundingSphere sphere ) { BoundingBox box; box.Minimum = Vector3( sphere.Center.X - sphere.Radius, sphere.Center.Y - sphere.Radius, sphere.Center.Z - sphere.Radius ); box.Maximum = Vector3( sphere.Center.X + sphere.Radius, sphere.Center.Y + sphere.Radius, sphere.Center.Z + sphere.Radius ); return box; } BoundingBox BoundingBox::Merge( BoundingBox box1, BoundingBox box2 ) { BoundingBox box; Vector3::Minimize( box1.Minimum, box2.Minimum, box.Minimum ); Vector3::Maximize( box1.Maximum, box2.Maximum, box.Maximum ); return box; } bool BoundingBox::Intersects( BoundingBox box1, BoundingBox box2 ) { if ( box1.Maximum.X < box2.Minimum.X || box1.Minimum.X > box2.Maximum.X ) return false; if ( box1.Maximum.Y < box2.Minimum.Y || box1.Minimum.Y > box2.Maximum.Y ) return false; return ( box1.Maximum.Z >= box2.Minimum.Z && box1.Minimum.Z <= box2.Maximum.Z ); } bool BoundingBox::Intersects( BoundingBox box, BoundingSphere sphere ) { float dist; Vector3 clamped; Vector3::Clamp( sphere.Center, box.Minimum, box.Maximum, clamped ); float x = sphere.Center.X - clamped.X; float y = sphere.Center.Y - clamped.Y; float z = sphere.Center.Z - clamped.Z; dist = (x * x) + (y * y) + (z * z); return ( dist <= (sphere.Radius * sphere.Radius) ); } bool BoundingBox::Intersects( BoundingBox box, Ray ray, [Out] float% distance ) { return Ray::Intersects( ray, box, distance ); } PlaneIntersectionType BoundingBox::Intersects( BoundingBox box, Plane plane ) { return Plane::Intersects( plane, box ); } bool BoundingBox::operator == ( BoundingBox left, BoundingBox right ) { return BoundingBox::Equals( left, right ); } bool BoundingBox::operator != ( BoundingBox left, BoundingBox right ) { return !BoundingBox::Equals( left, right ); } String^ BoundingBox::ToString() { return String::Format( CultureInfo::CurrentCulture, "Minimum:{0} Maximum:{1}", Minimum.ToString(), Maximum.ToString() ); } int BoundingBox::GetHashCode() { return Minimum.GetHashCode() + Maximum.GetHashCode(); } bool BoundingBox::Equals( Object^ value ) { if( value == nullptr ) return false; if( value->GetType() != GetType() ) return false; return Equals( safe_cast<BoundingBox>( value ) ); } bool BoundingBox::Equals( BoundingBox value ) { return ( Minimum == value.Minimum && Maximum == value.Maximum ); } bool BoundingBox::Equals( BoundingBox% value1, BoundingBox% value2 ) { return ( value1.Minimum == value2.Minimum && value1.Maximum == value2.Maximum ); } }
32.632911
126
0.678821
HeavenWu
9c538819091c2e282886e3d5f7770e7045cc8988
19,638
cc
C++
src/proto/core/asset-system/serialization.cc
kcpikkt/proto
2d7458c2ce2f571303de040f660137dc0a1d33de
[ "MIT" ]
null
null
null
src/proto/core/asset-system/serialization.cc
kcpikkt/proto
2d7458c2ce2f571303de040f660137dc0a1d33de
[ "MIT" ]
null
null
null
src/proto/core/asset-system/serialization.cc
kcpikkt/proto
2d7458c2ce2f571303de040f660137dc0a1d33de
[ "MIT" ]
null
null
null
#include "proto/core/asset-system/serialization.hh" #include "proto/core/asset-system/common.hh" #include "proto/core/asset-system/interface.hh" #include "proto/core/context.hh" #include "proto/core/memory/common.hh" #include "proto/core/util/algo.hh" #include "proto/core/platform/api.hh" #include "proto/core/math/hash.hh" #include "proto/core/graphics/Cubemap.hh" #include "proto/core/graphics/gl.hh" namespace proto { namespace serialization { #if 0 template<typename T> void serialize_specific_asset_to_buffer(T*, MemBuffer buffer); template<typename T> MemBuffer serialize_asset(T* asset, memory::Allocator * allocator) { assert(allocator); AssetMetadata * metadata = get_metadata(asset); assert(metadata); u64 main_header_size = sizeof(AssetFileHeader); u64 deps_size = metadata->deps.size() * sizeof(AssetDependency); MemBuffer buffer; // technically it should be next_multiple(next element alignment, size) // but it is a lot of writing u64 buf_size = next_multiple(16, main_header_size) + next_multiple(16, deps_size) + next_multiple(16, asset->serialized_size()); buffer.data8 = (u8*)allocator->alloc(buf_size); assert(buffer.data8); assert((size_t)buffer.data % 16 == 0); buffer.size = buf_size; u8 * main_header_ptr = buffer.data8; AssetFileHeader main_header; main_header.handle.type = AssetType<T>::index; main_header.handle.hash = asset->handle.hash; strcpy((char*)main_header.name, metadata->name); main_header.deps_count = metadata->deps.size(); main_header.deps_size = main_header.deps_count * sizeof(AssetDependency); u8 * deps_ptr = (u8*) memory::align_forw(main_header_ptr + sizeof(AssetFileHeader), alignof(AssetDependency)); main_header.deps_offset = deps_ptr - main_header_ptr; u8 * asset_data_ptr = (u8*) memory::align_forw(deps_ptr + deps_size, alignof(AssetHeader<T>)); main_header.data_offset = asset_data_ptr - main_header_ptr; assert(main_header.data_offset >= main_header_size + deps_size); memcpy(main_header_ptr, &main_header, sizeof(main_header)); for(u64 i =0; i<metadata->deps.size(); i++) { AssetHandle dep_handle = metadata->deps[i]; AssetMetadata * dep_metadata = get_metadata(dep_handle); if(!dep_metadata) { debug_warn(debug::category::data, "Could not fetch asset dependency metadata " "during asset serialization."); } AssetDependency serialized_dep; serialized_dep.handle = dep_handle; strcpy((char*)serialized_dep.name, (dep_metadata) ? dep_metadata->name : "(unknown)"); assert(make_handle((const char*) serialized_dep.name, serialized_dep.handle.type) == serialized_dep.handle); memcpy(((u8*)deps_ptr + i * sizeof(AssetDependency)), &serialized_dep, sizeof(AssetDependency)); } MemBuffer asset_buffer; asset_buffer.data8 = asset_data_ptr; asset_buffer.size = (buffer.data8 + buffer.size) - asset_data_ptr; serialize_specific_asset_to_buffer (asset, asset_buffer); return buffer; } template<> void serialize_specific_asset_to_buffer<Mesh>(Mesh* mesh, MemBuffer buffer) { assert(buffer.size >= mesh->serialized_size()); u8 * mesh_header_ptr = buffer.data8; AssetHeader<Mesh> mesh_header = mesh->serialization_header_map(); u8 * vertices_ptr = mesh_header_ptr + mesh_header.vertices_offset; u8 * indices_ptr = mesh_header_ptr + mesh_header.indices_offset; u8 * spans_ptr = mesh_header_ptr + mesh_header.spans_offset; memcpy(mesh_header_ptr, &mesh_header, sizeof(AssetHeader<Mesh>)); memcpy(vertices_ptr, (void*)mesh->vertices.raw(), mesh_header.vertices_size); memcpy(indices_ptr, (void*)mesh->indices.raw(), mesh_header.indices_size); memcpy(spans_ptr, (void*)mesh->spans.raw(), mesh_header.spans_size); } template<> void serialize_specific_asset_to_buffer<Texture2D>(Texture2D* texture, MemBuffer buffer) { assert(buffer.size >= texture->serialized_size()); assert(texture->data); u8 * texture_header_ptr = buffer.data8; AssetHeader<Texture2D> texture_header = texture->serialization_header_map(); u8 * texture_data_ptr = texture_header_ptr + texture_header.data_offset; memcpy(texture_header_ptr, &texture_header, sizeof(AssetHeader<Texture2D>)); memcpy(texture_data_ptr, texture->data, texture_header.data_size); } template<> void serialize_specific_asset_to_buffer<Cubemap>(Cubemap* cubemap, MemBuffer buffer) { assert(buffer.size >= cubemap->serialized_size()); assert(cubemap->data[0]); assert(cubemap->data[1]); assert(cubemap->data[2]); assert(cubemap->data[3]); assert(cubemap->data[4]); assert(cubemap->data[5]); AssetHeader<Cubemap> cubemap_header = cubemap->serialization_header_map(); u8 * cubemap_header_ptr = buffer.data8; u8 * cubemap_data_ptr = cubemap_header_ptr + cubemap_header.data_offset; memcpy(cubemap_header_ptr, &cubemap_header, sizeof(AssetHeader<Cubemap>)); u64 one_side_size = cubemap_header.data_size / 6; u8 * rt_data_ptr = cubemap_data_ptr; u8 * lf_data_ptr = rt_data_ptr + one_side_size; u8 * up_data_ptr = lf_data_ptr + one_side_size; u8 * dn_data_ptr = up_data_ptr + one_side_size; u8 * fw_data_ptr = dn_data_ptr + one_side_size; u8 * bk_data_ptr = fw_data_ptr + one_side_size; memcpy(rt_data_ptr, cubemap->data[0], one_side_size); memcpy(lf_data_ptr, cubemap->data[1], one_side_size); memcpy(up_data_ptr, cubemap->data[2], one_side_size); memcpy(dn_data_ptr, cubemap->data[3], one_side_size); memcpy(fw_data_ptr, cubemap->data[4], one_side_size); memcpy(bk_data_ptr, cubemap->data[5], one_side_size); } template<typename T> void deserialize_specific_asset_buffer(T * asset, MemBuffer buffer); template<> void deserialize_specific_asset_buffer<Texture2D>(Texture2D * texture, MemBuffer buffer) { assert(texture); AssetHeader<Texture2D> texture_header; u64 texture_header_size = sizeof(AssetHeader<Texture2D>); memcpy(&texture_header, buffer.data, texture_header_size); u8 * tex_data_ptr = buffer.data8 + texture_header.data_offset; memory::Allocator * allocator = &context->memory; void * data = allocator->alloc(texture_header.data_size); assert(data); texture->data = data; texture->_allocator = allocator; texture->channels = texture_header.channels; texture->format = texture_header.format; texture->gpu_format = texture_header.gpu_format; texture->size = texture_header.size; assert(texture_header.data_size == texture->serialized_data_size()); memcpy(texture->data, tex_data_ptr, texture_header.data_size); // NOTE(kacper): here memory is not freed, it should be freed after // gfx::gpu_upload(). Allocator is known since it is pointed // by Texture2D::_allocator but idk if it is good idea. // Perhaps there will be just one texture staging allocator // for that known globally. // allocator->free(data); } template<> void deserialize_specific_asset_buffer<Cubemap>(Cubemap * cubemap, MemBuffer buffer) { assert(cubemap); AssetHeader<Cubemap> cubemap_header; u64 cubemap_header_size = sizeof(AssetHeader<Cubemap>); memcpy(&cubemap_header, buffer.data, cubemap_header_size); u8 * tex_data_ptr = buffer.data8 + cubemap_header.data_offset; memory::Allocator * allocator = &context->memory; void * data = allocator->alloc(cubemap_header.data_size); assert(data); cubemap->channels = cubemap_header.channels; cubemap->format = cubemap_header.format; cubemap->gpu_format = cubemap_header.gpu_format; cubemap->size = cubemap_header.size; u64 one_side_size = cubemap_header.data_size / 6; // TODO(kacper): reorder when parsing cubemap->data[4] = data; cubemap->data[5] = (u8*)cubemap->data[4] + one_side_size; cubemap->data[2] = (u8*)cubemap->data[5] + one_side_size; cubemap->data[3] = (u8*)cubemap->data[2] + one_side_size; cubemap->data[0] = (u8*)cubemap->data[3] + one_side_size; cubemap->data[1] = (u8*)cubemap->data[0] + one_side_size; assert(cubemap_header.data_size == cubemap->serialized_data_size()); memcpy(data, tex_data_ptr, cubemap_header.data_size); // NOTE(kacper): here memory is not freed, it should be freed after // gfx::gpu_upload(). Allocator is known since it is pointed // by Texture2D::_allocator but idk if it is good idea. // Perhaps there will be just one texture staging allocator // for that known globally. // allocator->free(data); } template<> void deserialize_specific_asset_buffer<Mesh>(Mesh * mesh, MemBuffer buffer) { AssetHeader<Mesh> mesh_header; u64 mesh_header_size = sizeof(AssetHeader<Mesh>); memcpy(&mesh_header, buffer.data, mesh_header_size); u8 * vertices_ptr = buffer.data8 + mesh_header.vertices_offset; u8 * indices_ptr = buffer.data8 + mesh_header.indices_offset; u8 * spans_ptr = buffer.data8 + mesh_header.spans_offset; mesh->vertices.resize(mesh_header.vertices_count); mesh->indices.resize(mesh_header.indices_count); mesh->spans.resize(mesh_header.spans_count); assert(mesh->serialized_vertices_size() == mesh_header.vertices_size); assert(mesh->serialized_indices_size() == mesh_header.indices_size); assert(mesh->serialized_spans_size() == mesh_header.spans_size); memcpy(mesh->vertices.raw(), vertices_ptr, mesh_header.vertices_size); memcpy(mesh->indices.raw(), indices_ptr, mesh_header.indices_size); memcpy(mesh->spans.raw(), spans_ptr, mesh_header.spans_size); } void deserialize_specific_asset_buffer(AssetHandle handle, MemBuffer buffer) { switch(handle.type){ case AssetType<Mesh>::index: { Mesh * asset = get_asset<Mesh>(handle); assert(asset); deserialize_specific_asset_buffer(asset, buffer); } break; //case AssetType<Material>::index: { // Material * asset = get_asset<Material>(handle); // assert(asset); // deserialize_specific_asset_buffer(asset, buffer); //} break; case AssetType<Texture2D>::index: { Texture2D * asset = get_asset<Texture2D>(handle); assert(asset); deserialize_specific_asset_buffer(asset, buffer); } break; case AssetType<Cubemap>::index: { Cubemap * asset = get_asset<Cubemap>(handle); assert(asset); deserialize_specific_asset_buffer(asset, buffer); } break; default: { assert(0); } } } AssetHandle deserialize_asset_buffer(MemBuffer buffer) { AssetFileHeader main_header; u64 main_header_size = sizeof(AssetFileHeader); memcpy(&main_header, buffer.data, main_header_size); assert(main_header.signature == asset_file_signature); AssetHandle handle = create_init_asset((const char*)main_header.name, main_header.handle.type); if(handle.type == AssetType<Mesh>::index) { assert(get_asset<Mesh>(handle)->State::is_initialized()); } assert(handle = main_header.handle); AssetMetadata * metadata = get_metadata(handle); assert(metadata); assert(main_header.deps_size == main_header.deps_count * sizeof(AssetDependency)); u8* deps_ptr = buffer.data8 + main_header.deps_offset; metadata->deps.resize(main_header.deps_count); for(u64 i=0; i<main_header.deps_count; i++){ AssetDependency * serialized_dep = (AssetDependency*) ((u8*) deps_ptr + i * sizeof(AssetDependency)); assert(make_handle((const char*) serialized_dep->name, serialized_dep->handle.type) == serialized_dep->handle); metadata->deps[i] = serialized_dep->handle; } u8 * asset_header_ptr = buffer.data8 + main_header.data_offset; u64 asset_data_size = (buffer.data8 + buffer.size) - asset_header_ptr; MemBuffer asset_buffer = {.data8 = asset_header_ptr, .size = asset_data_size }; deserialize_specific_asset_buffer(handle ,asset_buffer); return handle; } template<typename T> int save_asset(T * asset, const char * path, [[maybe_unused]]AssetContext * asset_context) { namespace sys = proto::platform; //TODO(kacper): use asset context allocator memory::Allocator * allocator = &proto::context->memory; MemBuffer buffer = serialize_asset(asset, allocator); sys::File file; assert(!file.open(path, sys::File::write_mode)); assert(!file.size()); assert( buffer.size == file.write(buffer.data, buffer.size) ); file.close(); return 0; } template int save_asset<Mesh>(Mesh*, const char*, AssetContext*); template int save_asset<Texture2D>(Texture2D*, const char*, AssetContext*); template int save_asset<Cubemap>(Cubemap*, const char*, AssetContext*); int save_asset(AssetHandle handle, const char * path, [[maybe_unused]]AssetContext * context ) { switch(handle.type){ case AssetType<Mesh>::index: { Mesh * asset = get_asset<Mesh>(handle); assert(asset); return save_asset(asset, path); } break; //case AssetType<Material>::index: { // Material * asset = get_asset<Material>(handle); // assert(asset); // return save_asset(asset, path); //} break; case AssetType<Texture2D>::index: { Texture2D * asset = get_asset<Texture2D>(handle); assert(asset); return save_asset(asset, path); } break; case AssetType<Cubemap>::index: { Cubemap * asset = get_asset<Cubemap>(handle); assert(asset); return save_asset(asset, path); } break; default: { assert(0); } } return -1; } int save_asset_tree_rec(AssetHandle handle, StringView dirpath, AssetContext * asset_context) { assert(asset_context); //AssetContext & ctx = *asset_context; namespace sys = proto::platform; // TODO(kacper): access check file exists if(!sys::is_directory(dirpath)) { debug_error(debug::category::data, "Path ", dirpath, ", passed to ", __func__, " is not a path to directory"); return -1; } // we construct such a list first to avoid writing // many times to the same asset file. // e.g. some materials use the same texture for one thing or // share it between each other. Savelist savelist; savelist.init(100,&context->memory); get_deps_rec(savelist, handle); char filepath[PROTO_ASSET_MAX_PATH_LEN]; for(u32 i=0; i<savelist.size(); i++) { AssetMetadata * metadata = get_metadata(savelist[i]); strview_copy(filepath, dirpath); sys::path_ncat(filepath, metadata->name, PROTO_ASSET_MAX_PATH_LEN); strview_cat(filepath, "_"); strview_cat(filepath, AssetType(savelist[i]).name); strview_cat(filepath, ".past"); if(savelist[i].type != AssetType<Material>::index) save_asset(savelist[i], filepath, asset_context); } return 0; } AssetHandle load_asset_dir(StringView path, AssetContext * asset_context) { namespace sys = proto::platform; log_info(debug::category::data, "Loading assets from directory ", path); AssetHandle ret = invalid_asset_handle; auto filenames = sys::ls(path); for(auto filename : filenames) { StringView ext = sys::extension_view(filename); char asset_path[256]; // NOTE(kacper): remember strcmp is stupid if(ext.length() == 4 && !strncmp("past", ext, ext.length())) { strview_copy(asset_path, path); sys::path_ncat(asset_path, filename, 256); ret = load_asset(asset_path, asset_context); } } return invalid_asset_handle; } AssetHandle load_asset(StringView path, [[maybe_unused]]AssetContext * context) { //AssetContext & ctx = *context; namespace sys = proto::platform; if(strncmp(sys::extension_substr(path), "past", 4)) debug_warn(debug::category::data, "loaded file extension is not .past"); sys::File file; assert(!file.open(path, sys::File::read_mode)); assert( file.size()); memory::Allocator * allocator = &proto::context->memory; void * filebuf = allocator->alloc(file.size()); assert(filebuf); assert( file.size() == file.read(filebuf, file.size()) ); file.close(); AssetHandle handle = deserialize_asset_buffer(MemBuffer{.data = filebuf, .size = file.size()}); AssetMetadata * metadata = get_metadata(handle); assert(metadata); allocator->free(filebuf); return handle; } #endif } // namespace serialization } // namespace proto
39.276
86
0.587891
kcpikkt
9c53e754b4f2519e6e98ef6b91ba064f480da2b0
42,251
cpp
C++
source/common/2d/v_draw.cpp
prg318/Raze
4ff4fa643bcea6a19a6cce5f06dd436c454b88f3
[ "RSA-MD" ]
5
2021-07-31T03:34:09.000Z
2021-08-31T21:43:50.000Z
source/common/2d/v_draw.cpp
prg318/Raze
4ff4fa643bcea6a19a6cce5f06dd436c454b88f3
[ "RSA-MD" ]
null
null
null
source/common/2d/v_draw.cpp
prg318/Raze
4ff4fa643bcea6a19a6cce5f06dd436c454b88f3
[ "RSA-MD" ]
null
null
null
/* ** v_draw.cpp ** Draw patches and blocks to a canvas ** **--------------------------------------------------------------------------- ** Copyright 1998-2008 Randy Heit ** All rights reserved. ** ** Redistribution and use in source and binary forms, with or without ** modification, are permitted provided that the following conditions ** are met: ** ** 1. Redistributions of source code must retain the above copyright ** notice, this list of conditions and the following disclaimer. ** 2. Redistributions in binary form must reproduce the above copyright ** notice, this list of conditions and the following disclaimer in the ** documentation and/or other materials provided with the distribution. ** 3. The name of the author may not be used to endorse or promote products ** derived from this software without specific prior written permission. ** ** THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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 <stdio.h> #include <stdarg.h> #include "v_draw.h" #include "vm.h" #include "templates.h" #include "texturemanager.h" #include "r_videoscale.h" #include "c_cvars.h" EXTERN_CVAR(Int, vid_aspect) EXTERN_CVAR(Int, uiscale) CVAR(Bool, ui_screenborder_classic_scaling, true, CVAR_ARCHIVE) // vid_allowtrueultrawide - preserve the classic behavior of stretching screen elements to 16:9 when false // Defaults to "true" now because "21:9" (actually actually 64:27) screens are becoming more common, it's // nonsense that graphics should not be able to actually use that extra screen space. extern bool setsizeneeded; CUSTOM_CVAR(Int, vid_allowtrueultrawide, 1, CVAR_ARCHIVE|CVAR_NOINITCALL) { setsizeneeded = true; } static void VirtualToRealCoords(F2DDrawer* drawer, double Width, double Height, double& x, double& y, double& w, double& h, double vwidth, double vheight, bool vbottom, bool handleaspect); // Helper for ActiveRatio and CheckRatio. Returns the forced ratio type, or -1 if none. int ActiveFakeRatio(int width, int height) { int fakeratio = -1; if ((vid_aspect >= 1) && (vid_aspect <= 6)) { // [SP] User wants to force aspect ratio; let them. fakeratio = int(vid_aspect); if (fakeratio == 3) { fakeratio = 0; } else if (fakeratio == 5) { fakeratio = 3; } } return fakeratio; } // Active screen ratio based on cvars and size float ActiveRatio(int width, int height, float* trueratio) { static float forcedRatioTypes[] = { 4 / 3.0f, 16 / 9.0f, 16 / 10.0f, 17 / 10.0f, 5 / 4.0f, 17 / 10.0f, 64 / 27.0f // 21:9 is actually 64:27 in reality - pow(4/3, 3.0) - https://en.wikipedia.org/wiki/21:9_aspect_ratio }; float ratio = width / (float)height; int fakeratio = ActiveFakeRatio(width, height); if (trueratio) *trueratio = ratio; return (fakeratio != -1) ? forcedRatioTypes[fakeratio] : (ratio / ViewportPixelAspect()); } bool AspectTallerThanWide(float aspect) { return aspect < 1.333f; } int AspectBaseWidth(float aspect) { return (int)round(240.0f * aspect * 3.0f); } int AspectBaseHeight(float aspect) { if (!AspectTallerThanWide(aspect)) return (int)round(200.0f * (320.0f / (AspectBaseWidth(aspect) / 3.0f)) * 3.0f); else return (int)round((200.0f * (4.0f / 3.0f)) / aspect * 3.0f); } double AspectPspriteOffset(float aspect) { if (!AspectTallerThanWide(aspect)) return 0.0; else return ((4.0 / 3.0) / aspect - 1.0) * 97.5; } int AspectMultiplier(float aspect) { if (!AspectTallerThanWide(aspect)) return (int)round(320.0f / (AspectBaseWidth(aspect) / 3.0f) * 48.0f); else return (int)round(200.0f / (AspectBaseHeight(aspect) / 3.0f) * 48.0f); } int GetUIScale(F2DDrawer *drawer, int altval) { int scaleval; if (altval > 0) scaleval = altval; else if (uiscale == 0) { // Default should try to scale to 640x400 int vscale = drawer->GetHeight() / 400; int hscale = drawer->GetWidth() / 640; scaleval = clamp(vscale, 1, hscale); } else scaleval = uiscale; // block scales that result in something larger than the current screen. int vmax = drawer->GetHeight() / 200; int hmax = drawer->GetWidth() / 320; int max = MAX(vmax, hmax); return MAX(1,MIN(scaleval, max)); } // The new console font is twice as high, so the scaling calculation must factor that in. int GetConScale(F2DDrawer* drawer, int altval) { int scaleval; if (altval > 0) scaleval = (altval+1) / 2; else if (uiscale == 0) { // Default should try to scale to 640x400 int vscale = drawer->GetHeight() / 800; int hscale = drawer->GetWidth() / 1280; scaleval = clamp(vscale, 1, hscale); } else scaleval = (uiscale+1) / 2; // block scales that result in something larger than the current screen. int vmax = drawer->GetHeight() / 400; int hmax = drawer->GetWidth() / 640; int max = MAX(vmax, hmax); return MAX(1, MIN(scaleval, max)); } // [RH] Stretch values to make a 320x200 image best fit the screen // without using fractional steppings int CleanXfac, CleanYfac; // [RH] Effective screen sizes that the above scale values give you int CleanWidth, CleanHeight; // Above minus 1 (or 1, if they are already 1) int CleanXfac_1, CleanYfac_1, CleanWidth_1, CleanHeight_1; //========================================================================== // // Internal texture drawing function // //========================================================================== void DrawTexture(F2DDrawer *drawer, FGameTexture* img, double x, double y, int tags_first, ...) { Va_List tags; va_start(tags.list, tags_first); DrawParms parms; if (!img || !img->isValid()) return; bool res = ParseDrawTextureTags(drawer, img, x, y, tags_first, tags, &parms, false); va_end(tags.list); if (!res) { return; } drawer->AddTexture(img, parms); } //========================================================================== // // ZScript texture drawing function // //========================================================================== int ListGetInt(VMVa_List &tags); static void DrawTexture(F2DDrawer *drawer, FGameTexture *img, double x, double y, VMVa_List &args) { DrawParms parms; uint32_t tag = ListGetInt(args); if (!img || !img->isValid()) return; bool res = ParseDrawTextureTags(drawer, img, x, y, tag, args, &parms, false); if (!res) return; drawer->AddTexture(img, parms); } DEFINE_ACTION_FUNCTION(_Screen, DrawTexture) { PARAM_PROLOGUE; PARAM_INT(texid); PARAM_BOOL(animate); PARAM_FLOAT(x); PARAM_FLOAT(y); PARAM_VA_POINTER(va_reginfo) // Get the hidden type information array if (!twod->HasBegun2D()) ThrowAbortException(X_OTHER, "Attempt to draw to screen outside a draw function"); auto tex = TexMan.GameByIndex(texid, animate); VMVa_List args = { param + 4, 0, numparam - 5, va_reginfo + 4 }; DrawTexture(twod, tex, x, y, args); return 0; } //========================================================================== // // ZScript arbitrary textured shape drawing functions // //========================================================================== void DrawShape(F2DDrawer *drawer, FGameTexture *img, DShape2D *shape, int tags_first, ...) { Va_List tags; va_start(tags.list, tags_first); DrawParms parms; bool res = ParseDrawTextureTags(drawer, img, 0, 0, tags_first, tags, &parms, false); va_end(tags.list); if (!res) return; drawer->AddShape(img, shape, parms); } void DrawShape(F2DDrawer *drawer, FGameTexture *img, DShape2D *shape, VMVa_List &args) { DrawParms parms; uint32_t tag = ListGetInt(args); bool res = ParseDrawTextureTags(drawer, img, 0, 0, tag, args, &parms, false); if (!res) return; drawer->AddShape(img, shape, parms); } DEFINE_ACTION_FUNCTION(_Screen, DrawShape) { PARAM_PROLOGUE; PARAM_INT(texid); PARAM_BOOL(animate); PARAM_POINTER(shape, DShape2D); PARAM_VA_POINTER(va_reginfo) // Get the hidden type information array if (!twod->HasBegun2D()) ThrowAbortException(X_OTHER, "Attempt to draw to screen outside a draw function"); auto tex = TexMan.GameByIndex(texid, animate); VMVa_List args = { param + 3, 0, numparam - 4, va_reginfo + 3 }; DrawShape(twod, tex, shape, args); return 0; } //========================================================================== // // Clipping rect // //========================================================================== void F2DDrawer::SetClipRect(int x, int y, int w, int h) { clipleft = clamp(x, 0, GetWidth()); clipwidth = clamp(w, -1, GetWidth() - x); cliptop = clamp(y, 0, GetHeight()); clipheight = clamp(h, -1, GetHeight() - y); } DEFINE_ACTION_FUNCTION(_Screen, SetClipRect) { PARAM_PROLOGUE; PARAM_INT(x); PARAM_INT(y); PARAM_INT(w); PARAM_INT(h); twod->SetClipRect(x, y, w, h); return 0; } DEFINE_ACTION_FUNCTION(_Screen, ClearClipRect) { PARAM_PROLOGUE; twod->ClearClipRect(); return 0; } DEFINE_ACTION_FUNCTION(_Screen, ClearScreen) { PARAM_PROLOGUE; twod->ClearScreen(); return 0; } DEFINE_ACTION_FUNCTION(_Screen, SetScreenFade) { PARAM_PROLOGUE; PARAM_FLOAT(x); twod->SetScreenFade(float(x)); return 0; } void F2DDrawer::GetClipRect(int *x, int *y, int *w, int *h) { if (x) *x = clipleft; if (y) *y = cliptop; if (w) *w = clipwidth; if (h) *h = clipheight; } DEFINE_ACTION_FUNCTION(_Screen, GetClipRect) { PARAM_PROLOGUE; int x, y, w, h; twod->GetClipRect(&x, &y, &w, &h); if (numret > 0) ret[0].SetInt(x); if (numret > 1) ret[1].SetInt(y); if (numret > 2) ret[2].SetInt(w); if (numret > 3) ret[3].SetInt(h); return MIN(numret, 4); } void CalcFullscreenScale(DrawParms *parms, double srcwidth, double srcheight, int oautoaspect, DoubleRect &rect) { auto GetWidth = [=]() { return parms->viewport.width; }; auto GetHeight = [=]() {return parms->viewport.height; }; int autoaspect = oautoaspect; if (autoaspect == FSMode_ScaleToScreen) { rect.left = rect.top = 0; rect.width = GetWidth(); rect.height = GetHeight(); return; } double aspect; if (srcheight == 200) srcheight = 240.; else if (srcheight == 400) srcheight = 480; aspect = srcwidth / srcheight; rect.left = rect.top = 0; auto screenratio = ActiveRatio(GetWidth(), GetHeight()); if (autoaspect == FSMode_ScaleToFit43 || autoaspect == FSMode_ScaleToFit43Top || autoaspect == FSMode_ScaleToFit43Bottom) { // screen is wider than the image -> pillarbox it. 4:3 images must also be pillarboxed if the screen is taller than the image if (screenratio >= aspect || aspect < 1.4) autoaspect = FSMode_ScaleToFit; else if (screenratio > 1.32) autoaspect = FSMode_ScaleToFill; // on anything 4:3 and wider crop the sides of the image. else { // special case: Crop image to 4:3 and then letterbox this. This avoids too much cropping on narrow windows. double width4_3 = srcheight * (4. / 3.); rect.width = (double)GetWidth() * srcwidth / width4_3; rect.height = GetHeight() * screenratio * (3. / 4.); // use 4:3 for the image rect.left = (double)GetWidth() * (-(srcwidth - width4_3) / 2) / width4_3; switch (oautoaspect) { default: rect.top = (GetHeight() - rect.height) / 2; break; case FSMode_ScaleToFit43Top: rect.top = 0; break; case FSMode_ScaleToFit43Bottom: rect.top = (GetHeight() - rect.height); break; } return; } } if (autoaspect == FSMode_ScaleToHeight || (screenratio > aspect) ^ (autoaspect == FSMode_ScaleToFill)) { // pillarboxed or vertically cropped (i.e. scale to height) rect.height = GetHeight(); rect.width = GetWidth() * aspect / screenratio; rect.left = (GetWidth() - rect.width) / 2; } else { // letterboxed or horizontally cropped (i.e. scale to width) rect.width = GetWidth(); rect.height = GetHeight() * screenratio / aspect; switch (oautoaspect) { default: rect.top = (GetHeight() - rect.height) / 2; break; case FSMode_ScaleToFit43Top: rect.top = 0; break; case FSMode_ScaleToFit43Bottom: rect.top = (GetHeight() - rect.height); break; } } } void GetFullscreenRect(double width, double height, int fsmode, DoubleRect* rect) { DrawParms parms; parms.viewport.width = twod->GetWidth(); parms.viewport.height = twod->GetHeight(); CalcFullscreenScale(&parms, width, height, fsmode, *rect); } DEFINE_ACTION_FUNCTION(_Screen, GetFullscreenRect) { PARAM_PROLOGUE; PARAM_FLOAT(virtw); PARAM_FLOAT(virth); PARAM_INT(fsmode); DrawParms parms; DoubleRect rect; parms.viewport.width = twod->GetWidth(); parms.viewport.height = twod->GetHeight(); CalcFullscreenScale(&parms, virtw, virth, fsmode, rect); if (numret >= 1) ret[0].SetFloat(rect.left); if (numret >= 2) ret[1].SetFloat(rect.top); if (numret >= 3) ret[2].SetFloat(rect.width); if (numret >= 4) ret[3].SetFloat(rect.height); return MIN(numret, 4); } //========================================================================== // // Draw parameter parsing // //========================================================================== bool SetTextureParms(F2DDrawer * drawer, DrawParms *parms, FGameTexture *img, double xx, double yy) { auto GetWidth = [=]() { return parms->viewport.width; }; auto GetHeight = [=]() {return parms->viewport.height; }; if (img != NULL) { parms->x = xx; parms->y = yy; parms->texwidth = img->GetDisplayWidth(); parms->texheight = img->GetDisplayHeight(); if (parms->top == INT_MAX || parms->fortext) { parms->top = img->GetDisplayTopOffset(); } if (parms->left == INT_MAX || parms->fortext) { parms->left = img->GetDisplayLeftOffset(); } if (parms->destwidth == INT_MAX || parms->fortext) { parms->destwidth = parms->texwidth; } if (parms->destheight == INT_MAX || parms->fortext) { parms->destheight = parms->texheight; } parms->destwidth *= parms->patchscalex; parms->destheight *= parms->patchscaley; if (parms->flipoffsets && parms->flipY) parms->top = parms->texheight - parms->top; if (parms->flipoffsets && parms->flipX) parms->left = parms->texwidth - parms->left; switch (parms->cleanmode) { default: break; case DTA_Clean: parms->x = (parms->x - 160.0) * CleanXfac + (GetWidth() * 0.5); parms->y = (parms->y - 100.0) * CleanYfac + (GetHeight() * 0.5); parms->destwidth = parms->texwidth * CleanXfac; parms->destheight = parms->texheight * CleanYfac; break; case DTA_CleanTop: parms->x = (parms->x - 160.0) * CleanXfac + (GetWidth() * 0.5); parms->y = (parms->y) * CleanYfac; parms->destwidth = parms->texwidth * CleanXfac; parms->destheight = parms->texheight * CleanYfac; break; case DTA_CleanNoMove: parms->destwidth = parms->texwidth * CleanXfac; parms->destheight = parms->texheight * CleanYfac; break; case DTA_CleanNoMove_1: parms->destwidth = parms->texwidth * CleanXfac_1; parms->destheight = parms->texheight * CleanYfac_1; break; case DTA_Base: if (parms->fsscalemode > 0) { // First calculate the destination rect for an image of the given size and then reposition this object in it. DoubleRect rect; CalcFullscreenScale(parms, parms->virtWidth, parms->virtHeight, parms->fsscalemode, rect); double adder = parms->keepratio < 0 ? 0 : parms->keepratio == 0 ? rect.left : 2 * rect.left; parms->x = parms->viewport.left + adder + parms->x * rect.width / parms->virtWidth; parms->y = parms->viewport.top + rect.top + parms->y * rect.height / parms->virtHeight; parms->destwidth = parms->destwidth * rect.width / parms->virtWidth; parms->destheight = parms->destheight * rect.height / parms->virtHeight; return false; } break; case DTA_Fullscreen: case DTA_FullscreenEx: { DoubleRect rect; CalcFullscreenScale(parms, parms->texwidth, parms->texheight, parms->fsscalemode, rect); parms->keepratio = -1; parms->x = parms->viewport.left + rect.left; parms->y = parms->viewport.top + rect.top; parms->destwidth = rect.width; parms->destheight = rect.height; parms->top = parms->left = 0; return false; // Do not call VirtualToRealCoords for this! } case DTA_HUDRules: case DTA_HUDRulesC: { // Note that this has been deprecated and become non-functional. The HUD should be drawn by the status bar. bool xright = parms->x < 0; bool ybot = parms->y < 0; DVector2 scale = { 1., 1. }; parms->x *= scale.X; if (parms->cleanmode == DTA_HUDRulesC) parms->x += GetWidth() * 0.5; else if (xright) parms->x = GetWidth() + parms->x; parms->y *= scale.Y; if (ybot) parms->y = GetHeight() + parms->y; parms->destwidth = parms->texwidth * scale.X; parms->destheight = parms->texheight * scale.Y; break; } } if (parms->virtWidth != GetWidth() || parms->virtHeight != GetHeight()) { VirtualToRealCoords(drawer, GetWidth(), GetHeight(), parms->x, parms->y, parms->destwidth, parms->destheight, parms->virtWidth, parms->virtHeight, parms->virtBottom, !parms->keepratio); } parms->x += parms->viewport.left; parms->y += parms->viewport.top; } return false; } //========================================================================== // // template helpers // //========================================================================== static void ListEnd(Va_List &tags) { va_end(tags.list); } static int ListGetInt(Va_List &tags) { return va_arg(tags.list, int); } static inline double ListGetDouble(Va_List &tags) { return va_arg(tags.list, double); } static inline FSpecialColormap * ListGetSpecialColormap(Va_List &tags) { return va_arg(tags.list, FSpecialColormap *); } static void ListEnd(VMVa_List &tags) { } int ListGetInt(VMVa_List &tags) { if (tags.curindex < tags.numargs) { if (tags.reginfo[tags.curindex] == REGT_INT) { return tags.args[tags.curindex++].i; } ThrowAbortException(X_OTHER, "Invalid parameter in draw function, int expected"); } return TAG_DONE; } static inline double ListGetDouble(VMVa_List &tags) { if (tags.curindex < tags.numargs) { if (tags.reginfo[tags.curindex] == REGT_FLOAT) { return tags.args[tags.curindex++].f; } if (tags.reginfo[tags.curindex] == REGT_INT) { return tags.args[tags.curindex++].i; } ThrowAbortException(X_OTHER, "Invalid parameter in draw function, float expected"); } return 0; } static inline FSpecialColormap * ListGetSpecialColormap(VMVa_List &tags) { ThrowAbortException(X_OTHER, "Invalid tag in draw function"); return nullptr; } //========================================================================== // // Main taglist parsing // //========================================================================== template<class T> bool ParseDrawTextureTags(F2DDrawer *drawer, FGameTexture *img, double x, double y, uint32_t tag, T& tags, DrawParms *parms, bool fortext) { INTBOOL boolval; int intval; bool translationset = false; bool fillcolorset = false; if (!fortext) { if (img == NULL || !img->isValid()) { ListEnd(tags); return false; } } // Do some sanity checks on the coordinates. if (x < -16383 || x > 16383 || y < -16383 || y > 16383) { ListEnd(tags); return false; } parms->fortext = fortext; parms->windowleft = 0; parms->windowright = INT_MAX; parms->dclip = drawer->GetHeight(); parms->uclip = 0; parms->lclip = 0; parms->rclip = drawer->GetWidth(); parms->left = INT_MAX; parms->top = INT_MAX; parms->destwidth = INT_MAX; parms->destheight = INT_MAX; parms->Alpha = 1.f; parms->fillcolor = -1; parms->TranslationId = -1; parms->colorOverlay = 0; parms->alphaChannel = false; parms->flipX = false; parms->flipY = false; parms->color = 0xffffffff; //parms->shadowAlpha = 0; parms->shadowColor = 0; parms->virtWidth = INT_MAX; // these need to match the viewport if not explicitly set, but we do not know that yet. parms->virtHeight = INT_MAX; parms->keepratio = false; parms->style.BlendOp = 255; // Dummy "not set" value parms->masked = true; parms->bilinear = false; parms->specialcolormap = NULL; parms->desaturate = 0; parms->cleanmode = DTA_Base; parms->scalex = parms->scaley = 1; parms->cellx = parms->celly = 0; parms->maxstrlen = INT_MAX; parms->virtBottom = false; parms->srcx = 0.; parms->srcy = 0.; parms->srcwidth = 1.; parms->srcheight = 1.; parms->burn = false; parms->monospace = EMonospacing::Off; parms->spacing = 0; parms->fsscalemode = -1; parms->patchscalex = parms->patchscaley = 1; parms->viewport = { 0,0,drawer->GetWidth(), drawer->GetHeight() }; parms->rotateangle = 0; parms->flipoffsets = false; parms->indexed = false; parms->nooffset = false; // Parse the tag list for attributes. (For floating point attributes, // consider that the C ABI dictates that all floats be promoted to // doubles when passed as function arguments.) while (tag != TAG_DONE) { switch (tag) { default: ListGetInt(tags); break; case DTA_DestWidth: assert(fortext == false); if (fortext) return false; parms->cleanmode = DTA_Base; parms->destwidth = ListGetInt(tags); break; case DTA_DestWidthF: assert(fortext == false); if (fortext) return false; parms->cleanmode = DTA_Base; parms->destwidth = ListGetDouble(tags); break; case DTA_DestHeight: assert(fortext == false); if (fortext) return false; parms->cleanmode = DTA_Base; parms->destheight = ListGetInt(tags); break; case DTA_DestHeightF: assert(fortext == false); if (fortext) return false; parms->cleanmode = DTA_Base; parms->destheight = ListGetDouble(tags); break; case DTA_Clean: case DTA_CleanTop: boolval = ListGetInt(tags); if (boolval) { parms->scalex = 1; parms->scaley = 1; parms->cleanmode = tag; } break; case DTA_CleanNoMove: boolval = ListGetInt(tags); if (boolval) { parms->scalex = CleanXfac; parms->scaley = CleanYfac; parms->cleanmode = tag; } break; case DTA_CleanNoMove_1: boolval = ListGetInt(tags); if (boolval) { parms->scalex = CleanXfac_1; parms->scaley = CleanYfac_1; parms->cleanmode = tag; } break; case DTA_320x200: boolval = ListGetInt(tags); if (boolval) { parms->cleanmode = DTA_Base; parms->scalex = 1; parms->scaley = 1; parms->virtWidth = 320; parms->virtHeight = 200; } break; case DTA_Bottom320x200: boolval = ListGetInt(tags); if (boolval) { parms->cleanmode = DTA_Base; parms->scalex = 1; parms->scaley = 1; parms->virtWidth = 320; parms->virtHeight = 200; } parms->virtBottom = true; break; case DTA_HUDRules: intval = ListGetInt(tags); parms->cleanmode = intval == HUD_HorizCenter ? DTA_HUDRulesC : DTA_HUDRules; break; case DTA_VirtualWidth: parms->cleanmode = DTA_Base; parms->virtWidth = ListGetInt(tags); break; case DTA_VirtualWidthF: parms->cleanmode = DTA_Base; parms->virtWidth = ListGetDouble(tags); break; case DTA_VirtualHeight: parms->cleanmode = DTA_Base; parms->virtHeight = ListGetInt(tags); break; case DTA_VirtualHeightF: parms->cleanmode = DTA_Base; parms->virtHeight = ListGetDouble(tags); break; case DTA_FullscreenScale: intval = ListGetInt(tags); if (intval >= FSMode_None && intval < FSMode_Max) { parms->fsscalemode = (int8_t)intval; } else if (intval >= FSMode_Predefined && intval < FSMode_Predefined_Max) { static const uint8_t modes[] = { FSMode_ScaleToFit43, FSMode_ScaleToFit43, FSMode_ScaleToFit43, FSMode_ScaleToFit43, FSMode_ScaleToFit43Top}; static const uint16_t widths[] = { 320, 320, 640, 640, 320}; static const uint16_t heights[] = { 200, 240, 400, 480, 200}; parms->fsscalemode = modes[intval - FSMode_Predefined]; parms->virtWidth = widths[intval - FSMode_Predefined]; parms->virtHeight = heights[intval - FSMode_Predefined]; } break; case DTA_Fullscreen: boolval = ListGetInt(tags); if (boolval) { assert(fortext == false); if (img == NULL) return false; parms->cleanmode = DTA_Fullscreen; parms->fsscalemode = (uint8_t)twod->fullscreenautoaspect; parms->virtWidth = img->GetDisplayWidth(); parms->virtHeight = img->GetDisplayHeight(); } break; case DTA_FullscreenEx: intval = ListGetInt(tags); if (intval >= 0 && intval <= 3) { assert(fortext == false); if (img == NULL) return false; parms->cleanmode = DTA_Fullscreen; parms->fsscalemode = (uint8_t)intval; parms->virtWidth = img->GetDisplayWidth(); parms->virtHeight = img->GetDisplayHeight(); } break; case DTA_Alpha: parms->Alpha = (float)(MIN<double>(1., ListGetDouble(tags))); break; case DTA_AlphaChannel: parms->alphaChannel = ListGetInt(tags); break; case DTA_FillColor: parms->fillcolor = ListGetInt(tags); if (parms->fillcolor != ~0u) { fillcolorset = true; } else if (parms->fillcolor != 0) { // The crosshair is the only thing which uses a non-black fill color. parms->fillcolor = PalEntry(ColorMatcher.Pick(parms->fillcolor), RPART(parms->fillcolor), GPART(parms->fillcolor), BPART(parms->fillcolor)); } break; case DTA_TranslationIndex: parms->TranslationId = ListGetInt(tags); break; case DTA_ColorOverlay: parms->colorOverlay = ListGetInt(tags); break; case DTA_Color: parms->color = ListGetInt(tags); break; case DTA_FlipX: parms->flipX = ListGetInt(tags); break; case DTA_FlipY: parms->flipY = ListGetInt(tags); break; case DTA_FlipOffsets: parms->flipoffsets = ListGetInt(tags); break; case DTA_NoOffset: parms->nooffset = ListGetInt(tags); break; case DTA_SrcX: parms->srcx = ListGetDouble(tags) / img->GetDisplayWidth(); break; case DTA_SrcY: parms->srcy = ListGetDouble(tags) / img->GetDisplayHeight(); break; case DTA_SrcWidth: parms->srcwidth = ListGetDouble(tags) / img->GetDisplayWidth(); break; case DTA_SrcHeight: parms->srcheight = ListGetDouble(tags) / img->GetDisplayHeight(); break; case DTA_TopOffset: assert(fortext == false); if (fortext) return false; parms->top = ListGetInt(tags); break; case DTA_TopOffsetF: assert(fortext == false); if (fortext) return false; parms->top = ListGetDouble(tags); break; case DTA_LeftOffset: assert(fortext == false); if (fortext) return false; parms->left = ListGetInt(tags); break; case DTA_LeftOffsetF: assert(fortext == false); if (fortext) return false; parms->left = ListGetDouble(tags); break; case DTA_TopLeft: assert(fortext == false); if (fortext) return false; if (ListGetInt(tags)) { parms->left = 0; parms->top = 0; } break; case DTA_CenterOffset: assert(fortext == false); if (fortext) return false; if (ListGetInt(tags)) { parms->left = img->GetDisplayWidth() * 0.5; parms->top = img->GetDisplayHeight() * 0.5; } break; case DTA_CenterOffsetRel: assert(fortext == false); if (fortext) return false; if (ListGetInt(tags)) { parms->left = img->GetDisplayLeftOffset() + img->GetDisplayWidth() * 0.5; parms->top = img->GetDisplayTopOffset() + img->GetDisplayHeight() * 0.5; } break; case DTA_CenterBottomOffset: assert(fortext == false); if (fortext) return false; if (ListGetInt(tags)) { parms->left = img->GetDisplayWidth() * 0.5; parms->top = img->GetDisplayHeight(); } break; case DTA_WindowLeft: assert(fortext == false); if (fortext) return false; parms->windowleft = ListGetInt(tags); break; case DTA_WindowLeftF: assert(fortext == false); if (fortext) return false; parms->windowleft = ListGetDouble(tags); break; case DTA_WindowRight: assert(fortext == false); if (fortext) return false; parms->windowright = ListGetInt(tags); break; case DTA_WindowRightF: assert(fortext == false); if (fortext) return false; parms->windowright = ListGetDouble(tags); break; case DTA_ClipTop: parms->uclip = ListGetInt(tags); if (parms->uclip < 0) { parms->uclip = 0; } break; case DTA_ClipBottom: parms->dclip = ListGetInt(tags); if (parms->dclip > drawer->GetHeight()) { parms->dclip = drawer->GetHeight(); } break; case DTA_ClipLeft: parms->lclip = ListGetInt(tags); if (parms->lclip < 0) { parms->lclip = 0; } break; case DTA_ClipRight: parms->rclip = ListGetInt(tags); if (parms->rclip > drawer->GetWidth()) { parms->rclip = drawer->GetWidth(); } break; case DTA_ShadowAlpha: //parms->shadowAlpha = (float)MIN(1., ListGetDouble(tags)); break; case DTA_ShadowColor: parms->shadowColor = ListGetInt(tags); break; case DTA_Shadow: boolval = ListGetInt(tags); if (boolval) { //parms->shadowAlpha = 0.5; parms->shadowColor = 0; } else { //parms->shadowAlpha = 0; } break; case DTA_ScaleX: parms->patchscalex = ListGetDouble(tags); break; case DTA_ScaleY: parms->patchscaley = ListGetDouble(tags); break; case DTA_Masked: parms->masked = ListGetInt(tags); break; case DTA_BilinearFilter: parms->bilinear = ListGetInt(tags); break; case DTA_KeepRatio: parms->keepratio = ListGetInt(tags) ? -1 : 0; break; case DTA_Pin: parms->keepratio = ListGetInt(tags); break; case DTA_RenderStyle: parms->style.AsDWORD = ListGetInt(tags); break; case DTA_LegacyRenderStyle: // mainly for ZScript which does not handle FRenderStyle that well. parms->style = (ERenderStyle)ListGetInt(tags); break; case DTA_SpecialColormap: parms->specialcolormap = ListGetSpecialColormap(tags); break; case DTA_Desaturate: parms->desaturate = ListGetInt(tags); break; case DTA_TextLen: parms->maxstrlen = ListGetInt(tags); break; case DTA_CellX: parms->cellx = ListGetInt(tags); break; case DTA_CellY: parms->celly = ListGetInt(tags); break; case DTA_Monospace: parms->monospace = ListGetInt(tags); break; case DTA_Spacing: parms->spacing = ListGetInt(tags); break; case DTA_Burn: parms->burn = true; break; case DTA_ViewportX: parms->viewport.left = ListGetInt(tags); break; case DTA_ViewportY: parms->viewport.top = ListGetInt(tags); break; case DTA_ViewportWidth: parms->viewport.width = ListGetInt(tags); break; case DTA_ViewportHeight: parms->viewport.height = ListGetInt(tags); break; case DTA_Rotate: assert(fortext == false); if (fortext) return false; parms->rotateangle = ListGetDouble(tags); break; case DTA_Indexed: parms->indexed = !!ListGetInt(tags); break; } tag = ListGetInt(tags); } ListEnd(tags); if (parms->virtWidth == INT_MAX) parms->virtWidth = parms->viewport.width; if (parms->virtHeight == INT_MAX) parms->virtHeight = parms->viewport.height; auto clipleft = drawer->clipleft; auto cliptop = drawer->cliptop; auto clipwidth = drawer->clipwidth; auto clipheight = drawer->clipheight; // intersect with the canvas's clipping rectangle. if (clipwidth >= 0 && clipheight >= 0) { if (parms->lclip < clipleft) parms->lclip = clipleft; if (parms->rclip > clipleft + clipwidth) parms->rclip = clipleft + clipwidth; if (parms->uclip < cliptop) parms->uclip = cliptop; if (parms->dclip > cliptop + clipheight) parms->dclip = cliptop + clipheight; } if (parms->uclip >= parms->dclip || parms->lclip >= parms->rclip) { return false; } if (img != NULL) { SetTextureParms(drawer, parms, img, x, y); if (parms->destwidth <= 0 || parms->destheight <= 0) { return false; } } if (parms->style.BlendOp == 255) { if (fillcolorset) { if (parms->alphaChannel) { parms->style = STYLE_Shaded; } else if (parms->Alpha < 1.f) { parms->style = STYLE_TranslucentStencil; } else { parms->style = STYLE_Stencil; } } else if (parms->Alpha < 1.f) { parms->style = STYLE_Translucent; } else { parms->style = STYLE_Normal; } } return true; } // explicitly instantiate both versions for v_text.cpp. template bool ParseDrawTextureTags<Va_List>(F2DDrawer* drawer, FGameTexture *img, double x, double y, uint32_t tag, Va_List& tags, DrawParms *parms, bool fortext); template bool ParseDrawTextureTags<VMVa_List>(F2DDrawer* drawer, FGameTexture *img, double x, double y, uint32_t tag, VMVa_List& tags, DrawParms *parms, bool fortext); //========================================================================== // // Coordinate conversion // //========================================================================== static void VirtualToRealCoords(F2DDrawer *drawer, double Width, double Height, double &x, double &y, double &w, double &h, double vwidth, double vheight, bool vbottom, bool handleaspect) { float myratio = float(handleaspect ? ActiveRatio (Width, Height) : (4.0 / 3.0)); // if 21:9 AR, map to 16:9 for all callers. // this allows for black bars and stops the stretching of fullscreen images switch (vid_allowtrueultrawide) { case 1: default: myratio = MIN(64.0f / 27.0f, myratio); break; case 0: myratio = MIN(16.0f / 9.0f, myratio); case -1: break; } double right = x + w; double bottom = y + h; if (myratio > 1.334f) { // The target surface is either 16:9 or 16:10, so expand the // specified virtual size to avoid undesired stretching of the // image. Does not handle non-4:3 virtual sizes. I'll worry about // those if somebody expresses a desire to use them. x = (x - vwidth * 0.5) * Width * 960 / (vwidth * AspectBaseWidth(myratio)) + Width * 0.5; w = (right - vwidth * 0.5) * Width * 960 / (vwidth * AspectBaseWidth(myratio)) + Width * 0.5 - x; } else { x = x * Width / vwidth; w = right * Width / vwidth - x; } if (AspectTallerThanWide(myratio)) { // The target surface is 5:4 y = (y - vheight * 0.5) * Height * 600 / (vheight * AspectBaseHeight(myratio)) + Height * 0.5; h = (bottom - vheight * 0.5) * Height * 600 / (vheight * AspectBaseHeight(myratio)) + Height * 0.5 - y; if (vbottom) { y += (Height - Height * AspectMultiplier(myratio) / 48.0) * 0.5; } } else { y = y * Height / vheight; h = bottom * Height / vheight - y; } } void VirtualToRealCoords(F2DDrawer* drawer, double& x, double& y, double& w, double& h, double vwidth, double vheight, bool vbottom, bool handleaspect) { auto Width = drawer->GetWidth(); auto Height = drawer->GetHeight(); VirtualToRealCoords(drawer, Width, Height, x, y, w, h, vwidth, vheight, vbottom, handleaspect); } DEFINE_ACTION_FUNCTION(_Screen, VirtualToRealCoords) { PARAM_PROLOGUE; PARAM_FLOAT(x); PARAM_FLOAT(y); PARAM_FLOAT(w); PARAM_FLOAT(h); PARAM_FLOAT(vw); PARAM_FLOAT(vh); PARAM_BOOL(vbottom); PARAM_BOOL(handleaspect); VirtualToRealCoords(twod, x, y, w, h, vw, vh, vbottom, handleaspect); if (numret >= 1) ret[0].SetVector2(DVector2(x, y)); if (numret >= 2) ret[1].SetVector2(DVector2(w, h)); return MIN(numret, 2); } void VirtualToRealCoordsInt(F2DDrawer *drawer, int &x, int &y, int &w, int &h, int vwidth, int vheight, bool vbottom, bool handleaspect) { double dx, dy, dw, dh; dx = x; dy = y; dw = w; dh = h; VirtualToRealCoords(drawer, dx, dy, dw, dh, vwidth, vheight, vbottom, handleaspect); x = int(dx + 0.5); y = int(dy + 0.5); w = int(dx + dw + 0.5) - x; h = int(dy + dh + 0.5) - y; } //========================================================================== // // Draw a line // //========================================================================== static void DrawLine(int x0, int y0, int x1, int y1, uint32_t realcolor, int alpha) { if (!twod->HasBegun2D()) ThrowAbortException(X_OTHER, "Attempt to draw to screen outside a draw function"); twod->AddLine((float)x0, (float)y0, (float)x1, (float)y1, -1, -1, INT_MAX, INT_MAX, realcolor | MAKEARGB(255, 0, 0, 0), alpha); } DEFINE_ACTION_FUNCTION_NATIVE(_Screen, DrawLine, DrawLine) { PARAM_PROLOGUE; PARAM_INT(x0); PARAM_INT(y0); PARAM_INT(x1); PARAM_INT(y1); PARAM_INT(color); PARAM_INT(alpha); DrawLine(x0, y0, x1, y1, color, alpha); return 0; } static void DrawThickLine(int x0, int y0, int x1, int y1, double thickness, uint32_t realcolor, int alpha) { if (!twod->HasBegun2D()) ThrowAbortException(X_OTHER, "Attempt to draw to screen outside a draw function"); twod->AddThickLine(x0, y0, x1, y1, thickness, realcolor, alpha); } DEFINE_ACTION_FUNCTION_NATIVE(_Screen, DrawThickLine, DrawThickLine) { PARAM_PROLOGUE; PARAM_INT(x0); PARAM_INT(y0); PARAM_INT(x1); PARAM_INT(y1); PARAM_FLOAT(thickness); PARAM_INT(color); PARAM_INT(alpha); DrawThickLine(x0, y0, x1, y1, thickness, color, alpha); return 0; } //========================================================================== // // ClearRect // // Set an area to a specified color. // //========================================================================== void ClearRect(F2DDrawer *drawer, int left, int top, int right, int bottom, int palcolor, uint32_t color) { auto clipleft = drawer->clipleft; auto cliptop = drawer->cliptop; auto clipwidth = drawer->clipwidth; auto clipheight = drawer->clipheight; if (clipwidth >= 0 && clipheight >= 0) { int w = right - left; int h = bottom - top; if (left < clipleft) { w -= (clipleft - left); left = clipleft; } if (w > clipwidth) w = clipwidth; if (w <= 0) return; if (top < cliptop) { h -= (cliptop - top); top = cliptop; } if (h > clipheight) w = clipheight; if (h <= 0) return; right = left + w; bottom = top + h; } if (palcolor >= 0 && color == 0) { color = GPalette.BaseColors[palcolor] | 0xff000000; } drawer->AddColorOnlyQuad(left, top, right - left, bottom - top, color | 0xFF000000, nullptr); } DEFINE_ACTION_FUNCTION(_Screen, Clear) { PARAM_PROLOGUE; PARAM_INT(x1); PARAM_INT(y1); PARAM_INT(x2); PARAM_INT(y2); PARAM_INT(color); PARAM_INT(palcol); if (!twod->HasBegun2D()) ThrowAbortException(X_OTHER, "Attempt to draw to screen outside a draw function"); ClearRect(twod, x1, y1, x2, y2, palcol, color); return 0; } //========================================================================== // // DoDim // // Applies a colored overlay to an area of the screen. // //========================================================================== void DoDim(F2DDrawer *drawer, PalEntry color, float amount, int x1, int y1, int w, int h, FRenderStyle *style) { if (amount <= 0) { return; } if (amount > 1) { amount = 1; } drawer->AddColorOnlyQuad(x1, y1, w, h, (color.d & 0xffffff) | (int(amount * 255) << 24), style); } void Dim(F2DDrawer *drawer, PalEntry color, float damount, int x1, int y1, int w, int h, FRenderStyle *style) { auto clipleft = drawer->clipleft; auto cliptop = drawer->cliptop; auto clipwidth = drawer->clipwidth; auto clipheight = drawer->clipheight; if (clipwidth >= 0 && clipheight >= 0) { if (x1 < clipleft) { w -= (clipleft - x1); x1 = clipleft; } if (w > clipwidth) w = clipwidth; if (w <= 0) return; if (y1 < cliptop) { h -= (cliptop - y1); y1 = cliptop; } if (h > clipheight) h = clipheight; if (h <= 0) return; } DoDim(drawer, color, damount, x1, y1, w, h, style); } DEFINE_ACTION_FUNCTION(_Screen, Dim) { PARAM_PROLOGUE; PARAM_INT(color); PARAM_FLOAT(amount); PARAM_INT(x1); PARAM_INT(y1); PARAM_INT(w); PARAM_INT(h); if (!twod->HasBegun2D()) ThrowAbortException(X_OTHER, "Attempt to draw to screen outside a draw function"); Dim(twod, color, float(amount), x1, y1, w, h); return 0; } //========================================================================== // // screen->DrawBorder // //========================================================================== void DrawBorder (F2DDrawer *drawer, FTextureID picnum, int x1, int y1, int x2, int y2) { int filltype = (ui_screenborder_classic_scaling) ? -1 : 0; if (picnum.isValid()) { drawer->AddFlatFill (x1, y1, x2, y2, TexMan.GetGameTexture(picnum, false), filltype); } else { ClearRect(drawer, x1, y1, x2, y2, 0, 0); } } //========================================================================== // // V_DrawFrame // // Draw a frame around the specified area using the view border // frame graphics. The border is drawn outside the area, not in it. // //========================================================================== void DrawFrame(F2DDrawer* twod, PalEntry color, int left, int top, int width, int height, int thickness) { // Sanity check for incomplete gameinfo int offset = thickness == -1 ? twod->GetHeight() / 400 : thickness; int right = left + width; int bottom = top + height; // Draw top and bottom sides. twod->AddColorOnlyQuad(left, top - offset, width, offset, color); twod->AddColorOnlyQuad(left - offset, top - offset, offset, height + 2 * offset, color); twod->AddColorOnlyQuad(left, bottom, width, offset, color); twod->AddColorOnlyQuad(right, top - offset, offset, height + 2 * offset, color); } DEFINE_ACTION_FUNCTION(_Screen, DrawLineFrame) { PARAM_PROLOGUE; PARAM_COLOR(color); PARAM_INT(left); PARAM_INT(top); PARAM_INT(width); PARAM_INT(height); PARAM_INT(thickness); DrawFrame(twod, color, left, top, width, height, thickness); return 0; } void V_CalcCleanFacs(int designwidth, int designheight, int realwidth, int realheight, int* cleanx, int* cleany, int* _cx1, int* _cx2) { if (designheight < 240 && realheight >= 480) designheight = 240; *cleanx = *cleany = std::min(realwidth / designwidth, realheight / designheight); } DEFINE_ACTION_FUNCTION(_Screen, SetOffset) { PARAM_PROLOGUE; PARAM_FLOAT(x); PARAM_FLOAT(y); ACTION_RETURN_VEC2(twod->SetOffset(DVector2(x, y))); }
26.308219
167
0.642612
prg318
9c58debd046c5e7cccddb611c89309f409922d05
1,343
cpp
C++
0029_DivideTwoIntegers.cpp
taro-masuda/leetcode
39739e9fec7c66513b114c740ef982ccc09dc39f
[ "MIT" ]
null
null
null
0029_DivideTwoIntegers.cpp
taro-masuda/leetcode
39739e9fec7c66513b114c740ef982ccc09dc39f
[ "MIT" ]
null
null
null
0029_DivideTwoIntegers.cpp
taro-masuda/leetcode
39739e9fec7c66513b114c740ef982ccc09dc39f
[ "MIT" ]
1
2020-03-18T05:23:40.000Z
2020-03-18T05:23:40.000Z
class Solution { public: int divide(int dividend, int divisor) { int dividedCount = 0; if (dividend == - pow(2,31) && divisor == -1) return pow(2,31) - 1; else if (dividend == - pow(2,31) && divisor > 0) { dividend += divisor; dividedCount++; } else if (dividend == - pow(2,31) && divisor < 0) { dividend -= divisor; dividedCount++; } if (dividend > 0 && divisor > 0) { while (dividend >= divisor) { dividend -= divisor; dividedCount++; } return dividedCount; } else if (dividend > 0 && divisor < 0) { while (-dividend <= divisor) { dividend += divisor; dividedCount++; } return -dividedCount; } else if (dividend < 0 && divisor > 0) { while (-dividend >= divisor) { dividend += divisor; dividedCount++; } return -dividedCount; } else if (dividend < 0 && divisor < 0) { while (-dividend >= -divisor) { dividend -= divisor; dividedCount++; } return dividedCount; } else return 0; // dividend == 0 && divisor != 0 } };
31.97619
75
0.437826
taro-masuda
9c5c1b835aa211d114bed2c1a8335a7b08f19f90
1,168
cpp
C++
OC_Time/main.cpp
Picrik/GameDevC-
ddc46b60605da490e9bfaf838ef7ef3ee0757eb1
[ "MIT" ]
null
null
null
OC_Time/main.cpp
Picrik/GameDevC-
ddc46b60605da490e9bfaf838ef7ef3ee0757eb1
[ "MIT" ]
null
null
null
OC_Time/main.cpp
Picrik/GameDevC-
ddc46b60605da490e9bfaf838ef7ef3ee0757eb1
[ "MIT" ]
null
null
null
#include "Duree.h" #include "Duree.cpp" #include <iostream> #include <string> int main() { Duree duree1(0,10,20), duree2(0,10,20); if(duree1 == duree2) { std::cout << "Les deux durées sont égales" << std::endl; } else { std::cout << "Les deux durées sont différentes" << std::endl; } if(duree1<duree2) { std::cout << "Elle est plus petite" << std::endl; } else { std::cout << "Elle est plus grande" << std::endl; } if(duree1<=duree2) { std::cout << "Elle est plus petite ou égale" << std::endl; } else { std::cout << "Elle est plus grande" << std::endl; } if(duree1>duree2) { std::cout << "Elle est plus grande vraie" << std::endl; } else { std::cout << "Elle est plus petite" << std::endl; } if(duree1>=duree2) { std::cout << "Elle est plus grande vraie2" << std::endl; } else { std::cout << "Elle est plus petite 2" << std::endl; } duree1+=duree2; duree1.afficher(); Duree duree3 = duree1 + duree2; duree3.afficher(); return 0; }
18.83871
69
0.510274
Picrik
9c5fda96dffd53eb4c5a845b8ff20056735a3358
3,844
cpp
C++
sort/src/track.cpp
AsakusaRinne/tensorrt_yolov5_tracker
b9a3a6fc94710e8291d6a614ed2b04cbc4c56599
[ "MIT" ]
22
2021-03-03T10:16:37.000Z
2022-01-05T14:47:38.000Z
sort/src/track.cpp
AsakusaRinne/tensorrt_yolov5_tracker
b9a3a6fc94710e8291d6a614ed2b04cbc4c56599
[ "MIT" ]
3
2021-05-27T01:52:16.000Z
2021-07-13T08:49:30.000Z
sort/src/track.cpp
AsakusaRinne/tensorrt_yolov5_tracker
b9a3a6fc94710e8291d6a614ed2b04cbc4c56599
[ "MIT" ]
5
2021-03-23T07:13:05.000Z
2022-02-18T09:10:17.000Z
#include "track.h" Track::Track() : kf_(8, 4) { /*** Define constant velocity model ***/ // state - center_x, center_y, width, height, v_cx, v_cy, v_width, v_height kf_.F_ << 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1; // Give high uncertainty to the unobservable initial velocities kf_.P_ << 10, 0, 0, 0, 0, 0, 0, 0, 0, 10, 0, 0, 0, 0, 0, 0, 0, 0, 10, 0, 0, 0, 0, 0, 0, 0, 0, 10, 0, 0, 0, 0, 0, 0, 0, 0, 10000, 0, 0, 0, 0, 0, 0, 0, 0, 10000, 0, 0, 0, 0, 0, 0, 0, 0, 10000, 0, 0, 0, 0, 0, 0, 0, 0, 10000; kf_.H_ << 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0; kf_.Q_ << 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0.01, 0, 0, 0, 0, 0, 0, 0, 0, 0.01, 0, 0, 0, 0, 0, 0, 0, 0, 0.0001, 0, 0, 0, 0, 0, 0, 0, 0, 0.0001; kf_.R_ << 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 10, 0, 0, 0, 0, 10; } // Get predicted locations from existing trackers // dt is time elapsed between the current and previous measurements void Track::Predict() { kf_.Predict(); // hit streak count will be reset if (coast_cycles_ > 0) { hit_streak_ = 0; } // accumulate coast cycle count coast_cycles_++; } // Update matched trackers with assigned detections void Track::Update(const cv::Rect& bbox) { // get measurement update, reset coast cycle count coast_cycles_ = 0; // accumulate hit streak count hit_streak_++; // observation - center_x, center_y, area, ratio Eigen::VectorXd observation = ConvertBboxToObservation(bbox); kf_.Update(observation); } // Create and initialize new trackers for unmatched detections, with initial bounding box void Track::Init(const cv::Rect &bbox) { kf_.x_.head(4) << ConvertBboxToObservation(bbox); hit_streak_++; } /** * Returns the current bounding box estimate * @return */ cv::Rect Track::GetStateAsBbox() const { return ConvertStateToBbox(kf_.x_); } float Track::GetNIS() const { return kf_.NIS_; } /** * Takes a bounding box in the form [x, y, width, height] and returns z in the form * [x, y, s, r] where x,y is the centre of the box and s is the scale/area and r is * the aspect ratio * * @param bbox * @return */ Eigen::VectorXd Track::ConvertBboxToObservation(const cv::Rect& bbox) const{ Eigen::VectorXd observation = Eigen::VectorXd::Zero(4); auto width = static_cast<float>(bbox.width); auto height = static_cast<float>(bbox.height); float center_x = bbox.x + width / 2; float center_y = bbox.y + height / 2; observation << center_x, center_y, width, height; return observation; } /** * Takes a bounding box in the centre form [x,y,s,r] and returns it in the form * [x1,y1,x2,y2] where x1,y1 is the top left and x2,y2 is the bottom right * * @param state * @return */ cv::Rect Track::ConvertStateToBbox(const Eigen::VectorXd &state) const { // state - center_x, center_y, width, height, v_cx, v_cy, v_width, v_height auto width = static_cast<int>(state[2]); auto height = static_cast<int>(state[3]); auto tl_x = static_cast<int>(state[0] - width / 2.0); auto tl_y = static_cast<int>(state[1] - height / 2.0); cv::Rect rect(cv::Point(tl_x, tl_y), cv::Size(width, height)); return rect; }
27.654676
89
0.538502
AsakusaRinne
9c69bd2b5410676b272084a6a2cae6d9675822bb
985
cc
C++
test/TestMoList/testMoList.cc
satyam1990/vterm
ec63cceb81ae5fd6da823c4c1a68d14d28ef3149
[ "Apache-2.0" ]
1
2015-08-13T16:24:41.000Z
2015-08-13T16:24:41.000Z
test/TestMoList/testMoList.cc
satyam1990/vterm
ec63cceb81ae5fd6da823c4c1a68d14d28ef3149
[ "Apache-2.0" ]
null
null
null
test/TestMoList/testMoList.cc
satyam1990/vterm
ec63cceb81ae5fd6da823c4c1a68d14d28ef3149
[ "Apache-2.0" ]
null
null
null
/****************************************************************************** * * testMoList.cc * * Author: mSatyam * * 2015, August * * Tests functionality of MoList class. * *****************************************************************************/ #include <Mo.hh> #include <MoTree.hh> #include <MoList.hh> int main() { try { // init xerces XML Parser library XMLPlatformUtils::Initialize(); } catch (const XMLException& ex) { cerr << ex.getMessage() << endl; return 1; } // create the base MoTree string xmlfile = "../data/test.xml"; MoTree* tree = new MoTree(xmlfile); // get the root Mo Mo* root = tree->getRootMo(); // create child MoList from root Mo MoList* list = root->getChildMos(); // print each child Mo for (int i = 0; i < list->getLength(); i++) { cout << i << " Mo Name: " << list->getMoAtIndex(i)->getName() << endl; } return 0; }
20.102041
79
0.463959
satyam1990
9c6c70b3fb4b9efcd227a1d8a11f15c94f207c93
16,949
hpp
C++
c4/color_plane.hpp
akasitskyi/c4
56925e25430bc73cd407a8976656797b04d52348
[ "MIT" ]
2
2020-11-11T12:28:27.000Z
2022-01-31T20:31:28.000Z
c4/color_plane.hpp
akasitskyi/c4
56925e25430bc73cd407a8976656797b04d52348
[ "MIT" ]
15
2018-09-30T12:48:50.000Z
2020-07-14T18:36:50.000Z
c4/color_plane.hpp
akasitskyi/c4
56925e25430bc73cd407a8976656797b04d52348
[ "MIT" ]
3
2019-01-04T07:04:44.000Z
2020-09-06T16:53:21.000Z
//MIT License // //Copyright(c) 2018 Alex Kasitskyi // //Permission is hereby granted, free of charge, to any person obtaining a copy //of this software and associated documentation files(the "Software"), to deal //in the Software without restriction, including without limitation the rights //to use, copy, modify, merge, publish, distribute, sublicense, and/or sell //copies of the Software, and to permit persons to whom the Software is //furnished to do so, subject to the following conditions : // //The above copyright notice and this permission notice shall be included in all //copies or substantial portions of the Software. // //THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR //IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, //FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE //AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER //LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, //OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE //SOFTWARE. #pragma once #include "simd.hpp" #include "pixel.hpp" #include "range.hpp" #include "matrix.hpp" #include "exception.hpp" namespace c4 { enum class RgbByteOrder { ARGB, ABGR, BGRA, RGBA, RGB }; enum class UvByteOrder { UV, VU, CbCr = UV, CrCb = VU }; inline void img_to_rgb(const matrix_ref<pixel<uint8_t>>& img, uint8_t* ptr, int strideBytes, RgbByteOrder byteOrder) { for(int i : range(img.height())) { const c4::pixel<uint8_t>* psrc = img[i]; uint8_t* pdst = ptr + i * strideBytes; switch(byteOrder) { case RgbByteOrder::ARGB: for(int j : range(img.width())) { pdst[4 * j + 0] = 255; pdst[4 * j + 1] = psrc[j].r; pdst[4 * j + 2] = psrc[j].g; pdst[4 * j + 3] = psrc[j].b; } break; case RgbByteOrder::ABGR: for (int j : range(img.width())) { pdst[4 * j + 0] = 255; pdst[4 * j + 1] = psrc[j].b; pdst[4 * j + 2] = psrc[j].g; pdst[4 * j + 3] = psrc[j].r; } break; case RgbByteOrder::BGRA: for (int j : range(img.width())) { pdst[4 * j + 0] = psrc[j].b; pdst[4 * j + 1] = psrc[j].g; pdst[4 * j + 2] = psrc[j].r; pdst[4 * j + 3] = 255; } break; case RgbByteOrder::RGBA: for (int j : range(img.width())) { pdst[4 * j + 0] = psrc[j].r; pdst[4 * j + 1] = psrc[j].g; pdst[4 * j + 2] = psrc[j].b; pdst[4 * j + 3] = 255; } break; case RgbByteOrder::RGB: for (int j : range(img.width())) { pdst[3 * j + 0] = psrc[j].r; pdst[3 * j + 1] = psrc[j].g; pdst[3 * j + 2] = psrc[j].b; } break; default: THROW_EXCEPTION("Byte order not supported"); } } } inline void rgb_to_img(const uint8_t* ptr, int width, int height, int strideBytes, RgbByteOrder byteOrder, matrix<pixel<uint8_t>>& img) { img.resize(height, width); for(int i : range(height)) { c4::pixel<uint8_t>* pdst = img[i]; const uint8_t* psrc = ptr + i * strideBytes; switch(byteOrder) { case RgbByteOrder::ARGB: for(int j : range(width)) { pdst[j].r = psrc[4 * j + 1]; pdst[j].g = psrc[4 * j + 2]; pdst[j].b = psrc[4 * j + 3]; } break; case RgbByteOrder::ABGR: for(int j : range(width)) { pdst[j].r = psrc[4 * j + 3]; pdst[j].g = psrc[4 * j + 2]; pdst[j].b = psrc[4 * j + 1]; } break; case RgbByteOrder::BGRA: for (int j : range(width)) { pdst[j].r = psrc[4 * j + 2]; pdst[j].g = psrc[4 * j + 1]; pdst[j].b = psrc[4 * j + 0]; } break; case RgbByteOrder::RGBA: for (int j : range(width)) { pdst[j].r = psrc[4 * j + 0]; pdst[j].g = psrc[4 * j + 1]; pdst[j].b = psrc[4 * j + 2]; } break; case RgbByteOrder::RGB: for (int j : range(width)) { pdst[j].r = psrc[3 * j + 0]; pdst[j].g = psrc[3 * j + 1]; pdst[j].b = psrc[3 * j + 2]; } break; default: THROW_EXCEPTION("Byte order not supported"); } } } template<UvByteOrder byteOrder> struct getUV; template<> struct getUV<UvByteOrder::UV> { inline void operator()(const uint8_t* p, int& u, int& v) { u = p[0] - 128; v = p[1] - 128; } #ifdef __C4_SIMD__ inline void operator()(const uint8_t* p, const c4::simd::int16x8 c128, c4::simd::int32x4& u, c4::simd::int32x4& v) { c4::simd::int16x8 uvi = c4::simd::reinterpret_signed(c4::simd::load_long(p)); uvi = c4::simd::sub(uvi, c128); c4::simd::int32x4x2 uv = c4::simd::deinterleave(c4::simd::long_move(uvi)); u = uv.val[0]; v = uv.val[1]; } #endif }; template<> struct getUV<UvByteOrder::VU> { inline void operator()(const uint8_t* p, int& u, int& v) { v = p[0] - 128; u = p[1] - 128; } #ifdef __C4_SIMD__ inline void operator()(const uint8_t* p, const c4::simd::int16x8 c128, c4::simd::int32x4& u, c4::simd::int32x4& v) { c4::simd::int16x8 uvi = c4::simd::reinterpret_signed(c4::simd::load_long(p)); uvi = c4::simd::sub(uvi, c128); c4::simd::int32x4x2 vu = c4::simd::deinterleave(c4::simd::long_move(uvi)); v = vu.val[0]; u = vu.val[1]; } #endif }; template<RgbByteOrder byteOrder> struct setRGB; template<> struct setRGB<RgbByteOrder::ARGB> { inline void operator()(uint8_t* p, int i, uint8_t r, uint8_t g, uint8_t b) { p[4 * i + 0] = 255; p[4 * i + 1] = r; p[4 * i + 2] = g; p[4 * i + 3] = b; } #ifdef __C4_SIMD__ inline void operator()(uint8_t* p, int i, c4::simd::int16x8 r, c4::simd::int16x8 g, c4::simd::int16x8 b, const c4::simd::int16x8 c255) { c4::simd::int16x8x4 rgb{ c255, r, g, b }; c4::simd::store_4_interleaved_narrow_saturate(p + i * 4, rgb); } #endif }; template<> struct setRGB<RgbByteOrder::ABGR> { inline void operator()(uint8_t* p, int i, uint8_t r, uint8_t g, uint8_t b) { p[4 * i + 0] = 255; p[4 * i + 1] = b; p[4 * i + 2] = g; p[4 * i + 3] = r; } #ifdef __C4_SIMD__ inline void operator()(uint8_t* p, int i, c4::simd::int16x8 r, c4::simd::int16x8 g, c4::simd::int16x8 b, const c4::simd::int16x8 c255) { c4::simd::int16x8x4 rgb{ c255, b, g, r }; c4::simd::store_4_interleaved_narrow_saturate(p + i * 4, rgb); } #endif }; template<> struct setRGB<RgbByteOrder::BGRA> { inline void operator()(uint8_t* p, int i, uint8_t r, uint8_t g, uint8_t b) { p[4 * i + 0] = b; p[4 * i + 1] = g; p[4 * i + 2] = r; p[4 * i + 3] = 255; } #ifdef __C4_SIMD__ inline void operator()(uint8_t* p, int i, c4::simd::int16x8 r, c4::simd::int16x8 g, c4::simd::int16x8 b, const c4::simd::int16x8 c255) { c4::simd::int16x8x4 rgb{ b, g, r, c255 }; c4::simd::store_4_interleaved_narrow_saturate(p + i * 4, rgb); } #endif }; template<> struct setRGB<RgbByteOrder::RGBA> { inline void operator()(uint8_t* p, int i, uint8_t r, uint8_t g, uint8_t b) { p[4 * i + 0] = r; p[4 * i + 1] = g; p[4 * i + 2] = b; p[4 * i + 3] = 255; } #ifdef __C4_SIMD__ inline void operator()(uint8_t* p, int i, c4::simd::int16x8 r, c4::simd::int16x8 g, c4::simd::int16x8 b, const c4::simd::int16x8 c255) { c4::simd::int16x8x4 rgb{ r, g, b, c255 }; c4::simd::store_4_interleaved_narrow_saturate(p + i * 4, rgb); } #endif }; template<> struct setRGB<RgbByteOrder::RGB> { inline void operator()(uint8_t* p, int i, uint8_t r, uint8_t g, uint8_t b) { p[3 * i + 0] = r; p[3 * i + 1] = g; p[3 * i + 2] = b; } #ifdef __C4_SIMD__ inline void operator()(uint8_t* p, int i, c4::simd::int16x8 r, c4::simd::int16x8 g, c4::simd::int16x8 b, const c4::simd::int16x8 c255) { c4::simd::int16x8x3 rgb{r, g, b}; c4::simd::store_3_interleaved_narrow_unsigned_saturate(p + i * 3, rgb); } #endif }; struct yuv_to_rgb_coefficients { int rv; int gv; int gu; int bu; // saturation >= 0 inline yuv_to_rgb_coefficients adjust_saturation(float saturation) const { return yuv_to_rgb_coefficients{ int(rv * saturation), int(gv * saturation), int(gu * saturation), int(bu * saturation) }; } }; static yuv_to_rgb_coefficients ITU_R{359, -183, -88, 454 }; template<UvByteOrder uvByteOrder, RgbByteOrder dstByteOrder> inline void yuv420_to_rgb(const c4::matrix_ref<uint8_t>& Y, const c4::matrix_ref<std::pair<uint8_t, uint8_t> >& UV, uint8_t* dst, int dstStrideBytes, const yuv_to_rgb_coefficients c = ITU_R, const c4::pixel<int> add = c4::pixel<int>()) { int w2 = Y.width() / 2; int h2 = Y.height() / 2; ASSERT_EQUAL(Y.width(), w2 * 2); ASSERT_EQUAL(Y.height(), h2 * 2); ASSERT_EQUAL(UV.width(), w2); ASSERT_EQUAL(UV.height(), h2); for(int i : range(h2)) { const uint8_t* py0 = Y[2 * i + 0]; const uint8_t* py1 = Y[2 * i + 1]; uint8_t* pdst0 = dst + (2 * i + 0) * dstStrideBytes; uint8_t* pdst1 = dst + (2 * i + 1) * dstStrideBytes; const uint8_t* puv = (const uint8_t*)UV[i]; int j = 0; #ifdef __C4_SIMD__ using namespace c4::simd; const int16x8 c128(128); const int16x8 c255(255); int32x4 radd(add.r); int32x4 gadd(add.g); int32x4 badd(add.b); int32x4 crv(c.rv); int32x4 cgv(c.gv); int32x4 cgu(c.gu); int32x4 cbu(c.bu); for(; j + 4 < w2; j += 4){ int16x8 y0 = reinterpret_signed(load_long(py0 + 2 * j)); int16x8 y1 = reinterpret_signed(load_long(py1 + 2 * j)); int32x4 u, v; getUV<uvByteOrder>()(puv + 2 * j, c128, u, v); int32x4 tr = c4::simd::add(shift_right<8>(mul_lo(v, crv)), radd); int32x4 tg = c4::simd::add(shift_right<8>(mul_acc(mul_lo(v, cgv), u, cgu)), gadd); int32x4 tb = c4::simd::add(shift_right<8>(mul_lo(u, cbu)), badd); int32x4x2 tR = interleave({ tr, tr }); int32x4x2 tG = interleave({ tg, tg }); int32x4x2 tB = interleave({ tb, tb }); int16x8 tRd = narrow(tR); int16x8 tGd = narrow(tG); int16x8 tBd = narrow(tB); setRGB<dstByteOrder>()(pdst0, 2 * j, c4::simd::add(y0, tRd), c4::simd::add(y0, tGd), c4::simd::add(y0, tBd), c255); setRGB<dstByteOrder>()(pdst1, 2 * j, c4::simd::add(y1, tRd), c4::simd::add(y1, tGd), c4::simd::add(y1, tBd), c255); } #endif for(; j < w2; j++) { int y00 = py0[2 * j + 0]; int y01 = py0[2 * j + 1]; int y10 = py1[2 * j + 0]; int y11 = py1[2 * j + 1]; int u, v; getUV<uvByteOrder>()(puv + 2 * j, u, v); int tr = add.r + ((v * c.rv) >> 8); int tg = add.g + ((u * c.gu + v * c.gv) >> 8); int tb = add.b + ((u * c.bu) >> 8); setRGB<dstByteOrder>()(pdst0, 2 * j + 0, c4::clamp<uint8_t>(y00 + tr), c4::clamp<uint8_t>(y00 + tg), c4::clamp<uint8_t>(y00 + tb)); setRGB<dstByteOrder>()(pdst0, 2 * j + 1, c4::clamp<uint8_t>(y01 + tr), c4::clamp<uint8_t>(y01 + tg), c4::clamp<uint8_t>(y01 + tb)); setRGB<dstByteOrder>()(pdst1, 2 * j + 0, c4::clamp<uint8_t>(y10 + tr), c4::clamp<uint8_t>(y10 + tg), c4::clamp<uint8_t>(y10 + tb)); setRGB<dstByteOrder>()(pdst1, 2 * j + 1, c4::clamp<uint8_t>(y11 + tr), c4::clamp<uint8_t>(y11 + tg), c4::clamp<uint8_t>(y11 + tb)); } } } template<RgbByteOrder dstByteOrder> inline void y_to_rgb(const c4::matrix_ref<uint8_t>& Y, uint8_t* dst, int dstStrideBytes) { int w = Y.width(); for(int i : range(Y.height())) { const uint8_t* py = Y[i]; uint8_t* pdst = dst + i * dstStrideBytes; int j = 0; #ifdef __C4_SIMD__ using namespace c4::simd; const int16x8 c255(255); for (; j + 8 < w; j += 8) { int16x8 y = reinterpret_signed(load_long(py + j)); setRGB<dstByteOrder>()(pdst, j, y, y, y, c255); } #endif for (; j < w; j++) { uint8_t y = py[j]; setRGB<dstByteOrder>()(pdst, j, y, y, y); } } } template<UvByteOrder uvByteOrder> inline void yuv420_to_rgb(const c4::matrix_ref<uint8_t>& Y, const c4::matrix_ref<std::pair<uint8_t, uint8_t> >& UV, uint8_t* dst, int dstStrideBytes, const RgbByteOrder dstByteOrder, const yuv_to_rgb_coefficients c = ITU_R, const c4::pixel<int> add = c4::pixel<int>()) { switch(dstByteOrder) { case RgbByteOrder::ABGR: yuv420_to_rgb<uvByteOrder, RgbByteOrder::ABGR>(Y, UV, dst, dstStrideBytes, c, add); break; case RgbByteOrder::ARGB: yuv420_to_rgb<uvByteOrder, RgbByteOrder::ARGB>(Y, UV, dst, dstStrideBytes, c, add); break; case RgbByteOrder::BGRA: yuv420_to_rgb<uvByteOrder, RgbByteOrder::BGRA>(Y, UV, dst, dstStrideBytes, c, add); break; case RgbByteOrder::RGBA: yuv420_to_rgb<uvByteOrder, RgbByteOrder::RGBA>(Y, UV, dst, dstStrideBytes, c, add); break; case RgbByteOrder::RGB: yuv420_to_rgb<uvByteOrder, RgbByteOrder::RGB>(Y, UV, dst, dstStrideBytes, c, add); break; default: THROW_EXCEPTION("Byte order not supported"); } } inline void y_to_rgb(const c4::matrix_ref<uint8_t>& Y, uint8_t* dst, int dstStrideBytes, const RgbByteOrder dstByteOrder) { switch (dstByteOrder) { case RgbByteOrder::ABGR: y_to_rgb<RgbByteOrder::ABGR>(Y, dst, dstStrideBytes); break; case RgbByteOrder::ARGB: y_to_rgb<RgbByteOrder::ARGB>(Y, dst, dstStrideBytes); break; case RgbByteOrder::BGRA: y_to_rgb<RgbByteOrder::BGRA>(Y, dst, dstStrideBytes); break; case RgbByteOrder::RGBA: y_to_rgb<RgbByteOrder::RGBA>(Y, dst, dstStrideBytes); break; case RgbByteOrder::RGB: y_to_rgb<RgbByteOrder::RGB>(Y, dst, dstStrideBytes); break; default: THROW_EXCEPTION("Byte order not supported"); } } inline void yuv420_to_rgb(const c4::matrix_ref<uint8_t>& Y, const c4::matrix_ref<std::pair<uint8_t, uint8_t> >& UV, const UvByteOrder uvByteOrder, uint8_t* dst, int dstStrideBytes, const RgbByteOrder dstByteOrder, const yuv_to_rgb_coefficients c = ITU_R, const c4::pixel<int> add = c4::pixel<int>()) { switch(uvByteOrder) { case UvByteOrder::UV: yuv420_to_rgb<UvByteOrder::UV>(Y, UV, dst, dstStrideBytes, dstByteOrder, c, add); break; case UvByteOrder::VU: yuv420_to_rgb<UvByteOrder::VU>(Y, UV, dst, dstStrideBytes, dstByteOrder, c, add); break; default: THROW_EXCEPTION("Byte order not supported"); } } }; // namespace c4
36.215812
305
0.507877
akasitskyi
9c6d268f18ebb2c2bafee2693648469da86c18ae
1,479
hpp
C++
src/Animus/Error.hpp
RobertZ2011/animus
525f3eb6b93bd71c60889261b4d7f1d5a2d52e69
[ "BSD-3-Clause" ]
null
null
null
src/Animus/Error.hpp
RobertZ2011/animus
525f3eb6b93bd71c60889261b4d7f1d5a2d52e69
[ "BSD-3-Clause" ]
null
null
null
src/Animus/Error.hpp
RobertZ2011/animus
525f3eb6b93bd71c60889261b4d7f1d5a2d52e69
[ "BSD-3-Clause" ]
null
null
null
#ifndef ANIMUS_ERROR #define ANIMUS_ERROR #include <exception> #include "types/types.hpp" #include "macros/debug.hpp" #include "String.hpp" namespace Animus { class FilePath; ANIMUS_REQUIRES_STD typedef std::exception Exception; template<> String toString<Exception>(Exception e); class FilePermissionDenied : public Exception { String message; public: FilePermissionDenied(const FilePath& path); ~FilePermissionDenied(void) = default; const char *what(void) const noexcept override; }; class FileNotExist : public Exception { String message; public: FileNotExist(const FilePath& path); ~FileNotExist(void) = default; const char *what(void) const noexcept override; }; class FileUnknownError : public Exception { String message; public: FileUnknownError(const FilePath& path); ~FileUnknownError(void) = default; const char *what(void) const noexcept override; }; class FileNotOpen : public Exception { String message; public: FileNotOpen(void) = default; ~FileNotOpen(void) = default; const char *what(void) const noexcept override; }; class RuntimeError : public Exception { String message; public: RuntimeError(const String& str); ~RuntimeError(void) = default; const char *what(void) const noexcept override; }; } #endif
22.753846
55
0.648411
RobertZ2011
9c6dbdb68a3782646162e49f1a23ab4db1ea444b
4,130
cpp
C++
src/api/c/features.cpp
pavanky/arrayfire
f983a79c7d402450bd2a704bbc1015b89f0cd504
[ "BSD-3-Clause" ]
4
2015-12-16T09:41:32.000Z
2018-10-29T10:38:53.000Z
src/api/c/features.cpp
pavanky/arrayfire
f983a79c7d402450bd2a704bbc1015b89f0cd504
[ "BSD-3-Clause" ]
3
2015-11-15T18:43:47.000Z
2015-12-16T09:43:14.000Z
src/api/c/features.cpp
pavanky/arrayfire
f983a79c7d402450bd2a704bbc1015b89f0cd504
[ "BSD-3-Clause" ]
null
null
null
/******************************************************* * Copyright (c) 2014, ArrayFire * All rights reserved. * * This file is distributed under 3-clause BSD license. * The complete license agreement can be obtained at: * http://arrayfire.com/licenses/BSD-3-Clause ********************************************************/ #include <af/features.h> #include <af/array.h> #include <handle.hpp> af_err af_destroy_features(af_features feat) { feat.n = 0; try { if (feat.x != 0) AF_CHECK(af_destroy_array(feat.x)); if (feat.y != 0) AF_CHECK(af_destroy_array(feat.y)); if (feat.score != 0) AF_CHECK(af_destroy_array(feat.score)); if (feat.orientation != 0) AF_CHECK(af_destroy_array(feat.orientation)); if (feat.size != 0) AF_CHECK(af_destroy_array(feat.size)); } CATCHALL; return AF_SUCCESS; } namespace af { features::features() { feat.n = 0; feat.x = 0; feat.y = 0; feat.score = 0; feat.orientation = 0; feat.size = 0; } features::features(const size_t n) { feat.n = n; dim_type out_dims[4] = {dim_type(n), 1, 1, 1}; af_create_handle(&feat.x, 4, out_dims, f32); af_create_handle(&feat.y, 4, out_dims, f32); af_create_handle(&feat.score, 4, out_dims, f32); af_create_handle(&feat.orientation, 4, out_dims, f32); af_create_handle(&feat.size, 4, out_dims, f32); } features::features(af_features f) { feat.n = f.n; af_weak_copy(&feat.x, f.x); af_weak_copy(&feat.y, f.y); af_weak_copy(&feat.score, f.score); af_weak_copy(&feat.orientation, f.orientation); af_weak_copy(&feat.size, f.size); } features& features::operator= (const features& f) { if (this != &f) { setNumFeatures(f.getNumFeatures()); setX(f.getX()); setY(f.getY()); setScore(f.getScore()); setOrientation(f.getOrientation()); setSize(f.getSize()); } return *this; } features::~features() { af_destroy_features(feat); } size_t features::getNumFeatures() const { return feat.n; } array features::getX() const { return weakCopy(feat.x); } array features::getY() const { return weakCopy(feat.y); } array features::getScore() const { return weakCopy(feat.score); } array features::getOrientation() const { return weakCopy(feat.orientation); } array features::getSize() const { return weakCopy(feat.size); } void features::setNumFeatures(const size_t n) { feat.n = n; } void features::setX(const array x) { af_weak_copy(&feat.x, x.get()); } void features::setX(const af_array x) { af_weak_copy(&feat.x, x); } void features::setY(const array y) { af_weak_copy(&feat.y, y.get()); } void features::setY(const af_array y) { af_weak_copy(&feat.y, y); } void features::setScore(const array score) { af_weak_copy(&feat.score, score.get()); } void features::setScore(const af_array score) { af_weak_copy(&feat.score, score); } void features::setOrientation(const array orientation) { af_weak_copy(&feat.orientation, orientation.get()); } void features::setOrientation(const af_array orientation) { af_weak_copy(&feat.orientation, orientation); } void features::setSize(const array size) { af_weak_copy(&feat.size, size.get()); } void features::setSize(const af_array size) { af_weak_copy(&feat.size, size); } af_features features::get() { af_features f; f.n = feat.n; af_weak_copy(&f.x, feat.x); af_weak_copy(&f.y, feat.y); af_weak_copy(&f.score, feat.score); af_weak_copy(&f.orientation, feat.orientation); af_weak_copy(&f.size, feat.size); return f; } };
22.81768
80
0.559564
pavanky
9c71361e56669242af745684ec1ffb7baf5ca14c
124,888
cpp
C++
Scripts/UnityEngine.SubsystemsModule.cpp
SympactDev/ChickenSimulator
655d578b78263992dea04031954daf59d45383c7
[ "Apache-2.0" ]
null
null
null
Scripts/UnityEngine.SubsystemsModule.cpp
SympactDev/ChickenSimulator
655d578b78263992dea04031954daf59d45383c7
[ "Apache-2.0" ]
null
null
null
Scripts/UnityEngine.SubsystemsModule.cpp
SympactDev/ChickenSimulator
655d578b78263992dea04031954daf59d45383c7
[ "Apache-2.0" ]
null
null
null
#include "pch-cpp.hpp" #ifndef _MSC_VER # include <alloca.h> #else # include <malloc.h> #endif #include <limits> #include <stdint.h> // System.Collections.Generic.List`1<UnityEngine.IntegratedSubsystem> struct List_1_t2DAF7481782912A6F8E6180AC19B83A5EEFEE9EF; // System.Collections.Generic.List`1<UnityEngine.IntegratedSubsystemDescriptor> struct List_1_t13B7F19BE124BF950C29583D073B7D2174DCA122; // System.Collections.Generic.List`1<System.Object> struct List_1_t3F94120C77410A62EAE48421CF166B83AB95A2F5; // System.Collections.Generic.List`1<UnityEngine.Subsystem> struct List_1_t58BB84B47855540E6D2640B387506E01436DCF82; // System.Collections.Generic.List`1<UnityEngine.SubsystemDescriptor> struct List_1_t32E50BD66297C6541AEA401E1C13D4EC530CC56B; // System.Collections.Generic.List`1<UnityEngine.SubsystemsImplementation.SubsystemDescriptorWithProvider> struct List_1_t4DCA5C48F3390AC8CD79C7AD8D0963D5DAE5CF2E; // System.Collections.Generic.List`1<UnityEngine.SubsystemsImplementation.SubsystemWithProvider> struct List_1_t6E613DAFFAFE896B759F1C5260D6234F04C9DD41; // System.Delegate[] struct DelegateU5BU5D_t677D8FE08A5F99E8EE49150B73966CD6E9BF7DB8; // UnityEngine.IntegratedSubsystem[] struct IntegratedSubsystemU5BU5D_t1CDC088E79AAF042898970524412BC793663F481; // UnityEngine.IntegratedSubsystemDescriptor[] struct IntegratedSubsystemDescriptorU5BU5D_t201C14D38056400FA925FEFB411D041AA9F94AD8; // UnityEngine.Subsystem[] struct SubsystemU5BU5D_t4353D7C1DD71692C1BF7D355ADCB47DBD6DB91ED; // UnityEngine.SubsystemDescriptor[] struct SubsystemDescriptorU5BU5D_t52E78FFA3141BD25855CE03337EB1BB6C2984877; // UnityEngine.SubsystemsImplementation.SubsystemDescriptorWithProvider[] struct SubsystemDescriptorWithProviderU5BU5D_tD40368996299CE59717A7256C15AE12F9DD44EC0; // UnityEngine.SubsystemsImplementation.SubsystemWithProvider[] struct SubsystemWithProviderU5BU5D_t8A3DC7B8FFB1D676FD165C6B1FFE6DC8DF52CFCB; // System.Action struct Action_tAF41423D285AE0862865348CF6CE51CD085ABBA6; // System.AsyncCallback struct AsyncCallback_tA7921BEF974919C46FF8F9D9867C567B200BB0EA; // System.DelegateData struct DelegateData_t17DD30660E330C49381DAA99F934BE75CB11F288; // System.IAsyncResult struct IAsyncResult_tC9F97BF36FCF122D29D3101D80642278297BF370; // UnityEngine.ISubsystemDescriptor struct ISubsystemDescriptor_tEB935323042076ECFC076435FBD756B1E7953A14; // UnityEngine.IntegratedSubsystem struct IntegratedSubsystem_t8FB3A371F812CF9521903AC016C64E95C7412002; // UnityEngine.IntegratedSubsystemDescriptor struct IntegratedSubsystemDescriptor_tDC8AF8E5B67B983E4492D784A419F01693926D7A; // System.Reflection.MethodInfo struct MethodInfo_t; // System.String struct String_t; // UnityEngine.Subsystem struct Subsystem_t2D97454A946149D608974CB6B674F5F5C613A6A4; // UnityEngine.SubsystemDescriptor struct SubsystemDescriptor_tF663011CB44AB1D342821BBEF7B6811E799A7245; // UnityEngine.SubsystemsImplementation.SubsystemDescriptorWithProvider struct SubsystemDescriptorWithProvider_t32DD334657CFBA22F2FBA399258B087104A29C3E; // UnityEngine.SubsystemsImplementation.SubsystemWithProvider struct SubsystemWithProvider_t1C1868CF8676F5596C1AD20A7CE69BDF7C7DE73E; // System.Void struct Void_t700C6383A2A510C2CF4DD86DABD5CA9FF70ADAC5; IL2CPP_EXTERN_C RuntimeClass* IntPtr_t_il2cpp_TypeInfo_var; IL2CPP_EXTERN_C RuntimeClass* List_1_t13B7F19BE124BF950C29583D073B7D2174DCA122_il2cpp_TypeInfo_var; IL2CPP_EXTERN_C RuntimeClass* List_1_t2DAF7481782912A6F8E6180AC19B83A5EEFEE9EF_il2cpp_TypeInfo_var; IL2CPP_EXTERN_C RuntimeClass* List_1_t32E50BD66297C6541AEA401E1C13D4EC530CC56B_il2cpp_TypeInfo_var; IL2CPP_EXTERN_C RuntimeClass* List_1_t4DCA5C48F3390AC8CD79C7AD8D0963D5DAE5CF2E_il2cpp_TypeInfo_var; IL2CPP_EXTERN_C RuntimeClass* List_1_t58BB84B47855540E6D2640B387506E01436DCF82_il2cpp_TypeInfo_var; IL2CPP_EXTERN_C RuntimeClass* List_1_t6E613DAFFAFE896B759F1C5260D6234F04C9DD41_il2cpp_TypeInfo_var; IL2CPP_EXTERN_C RuntimeClass* SubsystemDescriptorStore_tE5D99C3159868DE6506269CB6B830621F8BC31A6_il2cpp_TypeInfo_var; IL2CPP_EXTERN_C RuntimeClass* SubsystemManager_t4397CEF2ED795CB9B3DDBA2BB468BCB6B45B76D9_il2cpp_TypeInfo_var; IL2CPP_EXTERN_C const RuntimeMethod* Enumerator_Dispose_m235C7DA3DE890C01AC2BDBF3700F46D8D9F70205_RuntimeMethod_var; IL2CPP_EXTERN_C const RuntimeMethod* Enumerator_Dispose_m2422FBD5B59F54B43DEF2796536DBDFBE7B27B17_RuntimeMethod_var; IL2CPP_EXTERN_C const RuntimeMethod* Enumerator_MoveNext_m0F18497A43DA01DEAB0F3019B04B284D42A5BC02_RuntimeMethod_var; IL2CPP_EXTERN_C const RuntimeMethod* Enumerator_MoveNext_mC10CBAADB9DFA0A091393D78B464F2AB2617750D_RuntimeMethod_var; IL2CPP_EXTERN_C const RuntimeMethod* Enumerator_get_Current_mA9ED75A7F28667B3CA286C561A8983A6355CB28C_RuntimeMethod_var; IL2CPP_EXTERN_C const RuntimeMethod* Enumerator_get_Current_mD5DC4E82EC765AC61BFA8600AB8C1D92014F12AB_RuntimeMethod_var; IL2CPP_EXTERN_C const RuntimeMethod* List_1_Add_m54714E32B888D33E0D24E8AF9B2C0BE61334C065_RuntimeMethod_var; IL2CPP_EXTERN_C const RuntimeMethod* List_1_Add_m5E7B6700296FDF9A86831BA41AB8D5974BC98EBF_RuntimeMethod_var; IL2CPP_EXTERN_C const RuntimeMethod* List_1_Clear_m2D220FFB24BAB221D99A0CA9543AFE6DF8D155B6_RuntimeMethod_var; IL2CPP_EXTERN_C const RuntimeMethod* List_1_Clear_mA624B195E1AC838905EB58332EE3BAAF99A9D2CA_RuntimeMethod_var; IL2CPP_EXTERN_C const RuntimeMethod* List_1_Clear_mEE68874407E18C9127133CC13AEEA9F5A4BD8392_RuntimeMethod_var; IL2CPP_EXTERN_C const RuntimeMethod* List_1_Clear_mF2DE990480F55E83ED1A30803FCA939DAC4295FB_RuntimeMethod_var; IL2CPP_EXTERN_C const RuntimeMethod* List_1_GetEnumerator_m0593C6B2A3413655213A5E61FB90E1927DDEAE20_RuntimeMethod_var; IL2CPP_EXTERN_C const RuntimeMethod* List_1_GetEnumerator_mCB28B8715FD5729AB10F27E74B5DCA1EDB12DBF2_RuntimeMethod_var; IL2CPP_EXTERN_C const RuntimeMethod* List_1__ctor_m1BE065BC3C4D6B70B245126E58C7DAFC7460A597_RuntimeMethod_var; IL2CPP_EXTERN_C const RuntimeMethod* List_1__ctor_m64996A7345F49B6600D4FD19B96FA0D4DBADBDC5_RuntimeMethod_var; IL2CPP_EXTERN_C const RuntimeMethod* List_1__ctor_m68FA0963B0052EA071AC894D7ACFF63E1477ED83_RuntimeMethod_var; IL2CPP_EXTERN_C const RuntimeMethod* List_1__ctor_m880D76E786031830863F68A2C4F0B7DF425666E5_RuntimeMethod_var; IL2CPP_EXTERN_C const RuntimeMethod* List_1__ctor_mAB9CAE208C61BBAF2266DA3CB6EF7DE1F16BF08C_RuntimeMethod_var; IL2CPP_EXTERN_C const RuntimeMethod* List_1__ctor_mB5053799863D389932A9DE8C00C290CBE78E176D_RuntimeMethod_var; IL2CPP_EXTERN_C const RuntimeMethod* SubsystemDescriptorStore_RegisterDescriptor_TisSubsystemDescriptor_tF663011CB44AB1D342821BBEF7B6811E799A7245_TisSubsystemDescriptor_tF663011CB44AB1D342821BBEF7B6811E799A7245_mA2A113AA1886D1110BD5C6506B4EDFD8E4BFE230_RuntimeMethod_var; struct Delegate_t_marshaled_com; struct Delegate_t_marshaled_pinvoke; IL2CPP_EXTERN_C_BEGIN IL2CPP_EXTERN_C_END #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // <Module> struct U3CModuleU3E_t7D657B68C133361A594C708A6FD672221623F690 { public: public: }; // System.Object // System.Collections.Generic.List`1<UnityEngine.IntegratedSubsystem> struct List_1_t2DAF7481782912A6F8E6180AC19B83A5EEFEE9EF : public RuntimeObject { public: // T[] System.Collections.Generic.List`1::_items IntegratedSubsystemU5BU5D_t1CDC088E79AAF042898970524412BC793663F481* ____items_1; // System.Int32 System.Collections.Generic.List`1::_size int32_t ____size_2; // System.Int32 System.Collections.Generic.List`1::_version int32_t ____version_3; // System.Object System.Collections.Generic.List`1::_syncRoot RuntimeObject * ____syncRoot_4; public: inline static int32_t get_offset_of__items_1() { return static_cast<int32_t>(offsetof(List_1_t2DAF7481782912A6F8E6180AC19B83A5EEFEE9EF, ____items_1)); } inline IntegratedSubsystemU5BU5D_t1CDC088E79AAF042898970524412BC793663F481* get__items_1() const { return ____items_1; } inline IntegratedSubsystemU5BU5D_t1CDC088E79AAF042898970524412BC793663F481** get_address_of__items_1() { return &____items_1; } inline void set__items_1(IntegratedSubsystemU5BU5D_t1CDC088E79AAF042898970524412BC793663F481* value) { ____items_1 = value; Il2CppCodeGenWriteBarrier((void**)(&____items_1), (void*)value); } inline static int32_t get_offset_of__size_2() { return static_cast<int32_t>(offsetof(List_1_t2DAF7481782912A6F8E6180AC19B83A5EEFEE9EF, ____size_2)); } inline int32_t get__size_2() const { return ____size_2; } inline int32_t* get_address_of__size_2() { return &____size_2; } inline void set__size_2(int32_t value) { ____size_2 = value; } inline static int32_t get_offset_of__version_3() { return static_cast<int32_t>(offsetof(List_1_t2DAF7481782912A6F8E6180AC19B83A5EEFEE9EF, ____version_3)); } inline int32_t get__version_3() const { return ____version_3; } inline int32_t* get_address_of__version_3() { return &____version_3; } inline void set__version_3(int32_t value) { ____version_3 = value; } inline static int32_t get_offset_of__syncRoot_4() { return static_cast<int32_t>(offsetof(List_1_t2DAF7481782912A6F8E6180AC19B83A5EEFEE9EF, ____syncRoot_4)); } inline RuntimeObject * get__syncRoot_4() const { return ____syncRoot_4; } inline RuntimeObject ** get_address_of__syncRoot_4() { return &____syncRoot_4; } inline void set__syncRoot_4(RuntimeObject * value) { ____syncRoot_4 = value; Il2CppCodeGenWriteBarrier((void**)(&____syncRoot_4), (void*)value); } }; struct List_1_t2DAF7481782912A6F8E6180AC19B83A5EEFEE9EF_StaticFields { public: // T[] System.Collections.Generic.List`1::_emptyArray IntegratedSubsystemU5BU5D_t1CDC088E79AAF042898970524412BC793663F481* ____emptyArray_5; public: inline static int32_t get_offset_of__emptyArray_5() { return static_cast<int32_t>(offsetof(List_1_t2DAF7481782912A6F8E6180AC19B83A5EEFEE9EF_StaticFields, ____emptyArray_5)); } inline IntegratedSubsystemU5BU5D_t1CDC088E79AAF042898970524412BC793663F481* get__emptyArray_5() const { return ____emptyArray_5; } inline IntegratedSubsystemU5BU5D_t1CDC088E79AAF042898970524412BC793663F481** get_address_of__emptyArray_5() { return &____emptyArray_5; } inline void set__emptyArray_5(IntegratedSubsystemU5BU5D_t1CDC088E79AAF042898970524412BC793663F481* value) { ____emptyArray_5 = value; Il2CppCodeGenWriteBarrier((void**)(&____emptyArray_5), (void*)value); } }; // System.Collections.Generic.List`1<UnityEngine.IntegratedSubsystemDescriptor> struct List_1_t13B7F19BE124BF950C29583D073B7D2174DCA122 : public RuntimeObject { public: // T[] System.Collections.Generic.List`1::_items IntegratedSubsystemDescriptorU5BU5D_t201C14D38056400FA925FEFB411D041AA9F94AD8* ____items_1; // System.Int32 System.Collections.Generic.List`1::_size int32_t ____size_2; // System.Int32 System.Collections.Generic.List`1::_version int32_t ____version_3; // System.Object System.Collections.Generic.List`1::_syncRoot RuntimeObject * ____syncRoot_4; public: inline static int32_t get_offset_of__items_1() { return static_cast<int32_t>(offsetof(List_1_t13B7F19BE124BF950C29583D073B7D2174DCA122, ____items_1)); } inline IntegratedSubsystemDescriptorU5BU5D_t201C14D38056400FA925FEFB411D041AA9F94AD8* get__items_1() const { return ____items_1; } inline IntegratedSubsystemDescriptorU5BU5D_t201C14D38056400FA925FEFB411D041AA9F94AD8** get_address_of__items_1() { return &____items_1; } inline void set__items_1(IntegratedSubsystemDescriptorU5BU5D_t201C14D38056400FA925FEFB411D041AA9F94AD8* value) { ____items_1 = value; Il2CppCodeGenWriteBarrier((void**)(&____items_1), (void*)value); } inline static int32_t get_offset_of__size_2() { return static_cast<int32_t>(offsetof(List_1_t13B7F19BE124BF950C29583D073B7D2174DCA122, ____size_2)); } inline int32_t get__size_2() const { return ____size_2; } inline int32_t* get_address_of__size_2() { return &____size_2; } inline void set__size_2(int32_t value) { ____size_2 = value; } inline static int32_t get_offset_of__version_3() { return static_cast<int32_t>(offsetof(List_1_t13B7F19BE124BF950C29583D073B7D2174DCA122, ____version_3)); } inline int32_t get__version_3() const { return ____version_3; } inline int32_t* get_address_of__version_3() { return &____version_3; } inline void set__version_3(int32_t value) { ____version_3 = value; } inline static int32_t get_offset_of__syncRoot_4() { return static_cast<int32_t>(offsetof(List_1_t13B7F19BE124BF950C29583D073B7D2174DCA122, ____syncRoot_4)); } inline RuntimeObject * get__syncRoot_4() const { return ____syncRoot_4; } inline RuntimeObject ** get_address_of__syncRoot_4() { return &____syncRoot_4; } inline void set__syncRoot_4(RuntimeObject * value) { ____syncRoot_4 = value; Il2CppCodeGenWriteBarrier((void**)(&____syncRoot_4), (void*)value); } }; struct List_1_t13B7F19BE124BF950C29583D073B7D2174DCA122_StaticFields { public: // T[] System.Collections.Generic.List`1::_emptyArray IntegratedSubsystemDescriptorU5BU5D_t201C14D38056400FA925FEFB411D041AA9F94AD8* ____emptyArray_5; public: inline static int32_t get_offset_of__emptyArray_5() { return static_cast<int32_t>(offsetof(List_1_t13B7F19BE124BF950C29583D073B7D2174DCA122_StaticFields, ____emptyArray_5)); } inline IntegratedSubsystemDescriptorU5BU5D_t201C14D38056400FA925FEFB411D041AA9F94AD8* get__emptyArray_5() const { return ____emptyArray_5; } inline IntegratedSubsystemDescriptorU5BU5D_t201C14D38056400FA925FEFB411D041AA9F94AD8** get_address_of__emptyArray_5() { return &____emptyArray_5; } inline void set__emptyArray_5(IntegratedSubsystemDescriptorU5BU5D_t201C14D38056400FA925FEFB411D041AA9F94AD8* value) { ____emptyArray_5 = value; Il2CppCodeGenWriteBarrier((void**)(&____emptyArray_5), (void*)value); } }; // System.Collections.Generic.List`1<UnityEngine.Subsystem> struct List_1_t58BB84B47855540E6D2640B387506E01436DCF82 : public RuntimeObject { public: // T[] System.Collections.Generic.List`1::_items SubsystemU5BU5D_t4353D7C1DD71692C1BF7D355ADCB47DBD6DB91ED* ____items_1; // System.Int32 System.Collections.Generic.List`1::_size int32_t ____size_2; // System.Int32 System.Collections.Generic.List`1::_version int32_t ____version_3; // System.Object System.Collections.Generic.List`1::_syncRoot RuntimeObject * ____syncRoot_4; public: inline static int32_t get_offset_of__items_1() { return static_cast<int32_t>(offsetof(List_1_t58BB84B47855540E6D2640B387506E01436DCF82, ____items_1)); } inline SubsystemU5BU5D_t4353D7C1DD71692C1BF7D355ADCB47DBD6DB91ED* get__items_1() const { return ____items_1; } inline SubsystemU5BU5D_t4353D7C1DD71692C1BF7D355ADCB47DBD6DB91ED** get_address_of__items_1() { return &____items_1; } inline void set__items_1(SubsystemU5BU5D_t4353D7C1DD71692C1BF7D355ADCB47DBD6DB91ED* value) { ____items_1 = value; Il2CppCodeGenWriteBarrier((void**)(&____items_1), (void*)value); } inline static int32_t get_offset_of__size_2() { return static_cast<int32_t>(offsetof(List_1_t58BB84B47855540E6D2640B387506E01436DCF82, ____size_2)); } inline int32_t get__size_2() const { return ____size_2; } inline int32_t* get_address_of__size_2() { return &____size_2; } inline void set__size_2(int32_t value) { ____size_2 = value; } inline static int32_t get_offset_of__version_3() { return static_cast<int32_t>(offsetof(List_1_t58BB84B47855540E6D2640B387506E01436DCF82, ____version_3)); } inline int32_t get__version_3() const { return ____version_3; } inline int32_t* get_address_of__version_3() { return &____version_3; } inline void set__version_3(int32_t value) { ____version_3 = value; } inline static int32_t get_offset_of__syncRoot_4() { return static_cast<int32_t>(offsetof(List_1_t58BB84B47855540E6D2640B387506E01436DCF82, ____syncRoot_4)); } inline RuntimeObject * get__syncRoot_4() const { return ____syncRoot_4; } inline RuntimeObject ** get_address_of__syncRoot_4() { return &____syncRoot_4; } inline void set__syncRoot_4(RuntimeObject * value) { ____syncRoot_4 = value; Il2CppCodeGenWriteBarrier((void**)(&____syncRoot_4), (void*)value); } }; struct List_1_t58BB84B47855540E6D2640B387506E01436DCF82_StaticFields { public: // T[] System.Collections.Generic.List`1::_emptyArray SubsystemU5BU5D_t4353D7C1DD71692C1BF7D355ADCB47DBD6DB91ED* ____emptyArray_5; public: inline static int32_t get_offset_of__emptyArray_5() { return static_cast<int32_t>(offsetof(List_1_t58BB84B47855540E6D2640B387506E01436DCF82_StaticFields, ____emptyArray_5)); } inline SubsystemU5BU5D_t4353D7C1DD71692C1BF7D355ADCB47DBD6DB91ED* get__emptyArray_5() const { return ____emptyArray_5; } inline SubsystemU5BU5D_t4353D7C1DD71692C1BF7D355ADCB47DBD6DB91ED** get_address_of__emptyArray_5() { return &____emptyArray_5; } inline void set__emptyArray_5(SubsystemU5BU5D_t4353D7C1DD71692C1BF7D355ADCB47DBD6DB91ED* value) { ____emptyArray_5 = value; Il2CppCodeGenWriteBarrier((void**)(&____emptyArray_5), (void*)value); } }; // System.Collections.Generic.List`1<UnityEngine.SubsystemDescriptor> struct List_1_t32E50BD66297C6541AEA401E1C13D4EC530CC56B : public RuntimeObject { public: // T[] System.Collections.Generic.List`1::_items SubsystemDescriptorU5BU5D_t52E78FFA3141BD25855CE03337EB1BB6C2984877* ____items_1; // System.Int32 System.Collections.Generic.List`1::_size int32_t ____size_2; // System.Int32 System.Collections.Generic.List`1::_version int32_t ____version_3; // System.Object System.Collections.Generic.List`1::_syncRoot RuntimeObject * ____syncRoot_4; public: inline static int32_t get_offset_of__items_1() { return static_cast<int32_t>(offsetof(List_1_t32E50BD66297C6541AEA401E1C13D4EC530CC56B, ____items_1)); } inline SubsystemDescriptorU5BU5D_t52E78FFA3141BD25855CE03337EB1BB6C2984877* get__items_1() const { return ____items_1; } inline SubsystemDescriptorU5BU5D_t52E78FFA3141BD25855CE03337EB1BB6C2984877** get_address_of__items_1() { return &____items_1; } inline void set__items_1(SubsystemDescriptorU5BU5D_t52E78FFA3141BD25855CE03337EB1BB6C2984877* value) { ____items_1 = value; Il2CppCodeGenWriteBarrier((void**)(&____items_1), (void*)value); } inline static int32_t get_offset_of__size_2() { return static_cast<int32_t>(offsetof(List_1_t32E50BD66297C6541AEA401E1C13D4EC530CC56B, ____size_2)); } inline int32_t get__size_2() const { return ____size_2; } inline int32_t* get_address_of__size_2() { return &____size_2; } inline void set__size_2(int32_t value) { ____size_2 = value; } inline static int32_t get_offset_of__version_3() { return static_cast<int32_t>(offsetof(List_1_t32E50BD66297C6541AEA401E1C13D4EC530CC56B, ____version_3)); } inline int32_t get__version_3() const { return ____version_3; } inline int32_t* get_address_of__version_3() { return &____version_3; } inline void set__version_3(int32_t value) { ____version_3 = value; } inline static int32_t get_offset_of__syncRoot_4() { return static_cast<int32_t>(offsetof(List_1_t32E50BD66297C6541AEA401E1C13D4EC530CC56B, ____syncRoot_4)); } inline RuntimeObject * get__syncRoot_4() const { return ____syncRoot_4; } inline RuntimeObject ** get_address_of__syncRoot_4() { return &____syncRoot_4; } inline void set__syncRoot_4(RuntimeObject * value) { ____syncRoot_4 = value; Il2CppCodeGenWriteBarrier((void**)(&____syncRoot_4), (void*)value); } }; struct List_1_t32E50BD66297C6541AEA401E1C13D4EC530CC56B_StaticFields { public: // T[] System.Collections.Generic.List`1::_emptyArray SubsystemDescriptorU5BU5D_t52E78FFA3141BD25855CE03337EB1BB6C2984877* ____emptyArray_5; public: inline static int32_t get_offset_of__emptyArray_5() { return static_cast<int32_t>(offsetof(List_1_t32E50BD66297C6541AEA401E1C13D4EC530CC56B_StaticFields, ____emptyArray_5)); } inline SubsystemDescriptorU5BU5D_t52E78FFA3141BD25855CE03337EB1BB6C2984877* get__emptyArray_5() const { return ____emptyArray_5; } inline SubsystemDescriptorU5BU5D_t52E78FFA3141BD25855CE03337EB1BB6C2984877** get_address_of__emptyArray_5() { return &____emptyArray_5; } inline void set__emptyArray_5(SubsystemDescriptorU5BU5D_t52E78FFA3141BD25855CE03337EB1BB6C2984877* value) { ____emptyArray_5 = value; Il2CppCodeGenWriteBarrier((void**)(&____emptyArray_5), (void*)value); } }; // System.Collections.Generic.List`1<UnityEngine.SubsystemsImplementation.SubsystemDescriptorWithProvider> struct List_1_t4DCA5C48F3390AC8CD79C7AD8D0963D5DAE5CF2E : public RuntimeObject { public: // T[] System.Collections.Generic.List`1::_items SubsystemDescriptorWithProviderU5BU5D_tD40368996299CE59717A7256C15AE12F9DD44EC0* ____items_1; // System.Int32 System.Collections.Generic.List`1::_size int32_t ____size_2; // System.Int32 System.Collections.Generic.List`1::_version int32_t ____version_3; // System.Object System.Collections.Generic.List`1::_syncRoot RuntimeObject * ____syncRoot_4; public: inline static int32_t get_offset_of__items_1() { return static_cast<int32_t>(offsetof(List_1_t4DCA5C48F3390AC8CD79C7AD8D0963D5DAE5CF2E, ____items_1)); } inline SubsystemDescriptorWithProviderU5BU5D_tD40368996299CE59717A7256C15AE12F9DD44EC0* get__items_1() const { return ____items_1; } inline SubsystemDescriptorWithProviderU5BU5D_tD40368996299CE59717A7256C15AE12F9DD44EC0** get_address_of__items_1() { return &____items_1; } inline void set__items_1(SubsystemDescriptorWithProviderU5BU5D_tD40368996299CE59717A7256C15AE12F9DD44EC0* value) { ____items_1 = value; Il2CppCodeGenWriteBarrier((void**)(&____items_1), (void*)value); } inline static int32_t get_offset_of__size_2() { return static_cast<int32_t>(offsetof(List_1_t4DCA5C48F3390AC8CD79C7AD8D0963D5DAE5CF2E, ____size_2)); } inline int32_t get__size_2() const { return ____size_2; } inline int32_t* get_address_of__size_2() { return &____size_2; } inline void set__size_2(int32_t value) { ____size_2 = value; } inline static int32_t get_offset_of__version_3() { return static_cast<int32_t>(offsetof(List_1_t4DCA5C48F3390AC8CD79C7AD8D0963D5DAE5CF2E, ____version_3)); } inline int32_t get__version_3() const { return ____version_3; } inline int32_t* get_address_of__version_3() { return &____version_3; } inline void set__version_3(int32_t value) { ____version_3 = value; } inline static int32_t get_offset_of__syncRoot_4() { return static_cast<int32_t>(offsetof(List_1_t4DCA5C48F3390AC8CD79C7AD8D0963D5DAE5CF2E, ____syncRoot_4)); } inline RuntimeObject * get__syncRoot_4() const { return ____syncRoot_4; } inline RuntimeObject ** get_address_of__syncRoot_4() { return &____syncRoot_4; } inline void set__syncRoot_4(RuntimeObject * value) { ____syncRoot_4 = value; Il2CppCodeGenWriteBarrier((void**)(&____syncRoot_4), (void*)value); } }; struct List_1_t4DCA5C48F3390AC8CD79C7AD8D0963D5DAE5CF2E_StaticFields { public: // T[] System.Collections.Generic.List`1::_emptyArray SubsystemDescriptorWithProviderU5BU5D_tD40368996299CE59717A7256C15AE12F9DD44EC0* ____emptyArray_5; public: inline static int32_t get_offset_of__emptyArray_5() { return static_cast<int32_t>(offsetof(List_1_t4DCA5C48F3390AC8CD79C7AD8D0963D5DAE5CF2E_StaticFields, ____emptyArray_5)); } inline SubsystemDescriptorWithProviderU5BU5D_tD40368996299CE59717A7256C15AE12F9DD44EC0* get__emptyArray_5() const { return ____emptyArray_5; } inline SubsystemDescriptorWithProviderU5BU5D_tD40368996299CE59717A7256C15AE12F9DD44EC0** get_address_of__emptyArray_5() { return &____emptyArray_5; } inline void set__emptyArray_5(SubsystemDescriptorWithProviderU5BU5D_tD40368996299CE59717A7256C15AE12F9DD44EC0* value) { ____emptyArray_5 = value; Il2CppCodeGenWriteBarrier((void**)(&____emptyArray_5), (void*)value); } }; // System.Collections.Generic.List`1<UnityEngine.SubsystemsImplementation.SubsystemWithProvider> struct List_1_t6E613DAFFAFE896B759F1C5260D6234F04C9DD41 : public RuntimeObject { public: // T[] System.Collections.Generic.List`1::_items SubsystemWithProviderU5BU5D_t8A3DC7B8FFB1D676FD165C6B1FFE6DC8DF52CFCB* ____items_1; // System.Int32 System.Collections.Generic.List`1::_size int32_t ____size_2; // System.Int32 System.Collections.Generic.List`1::_version int32_t ____version_3; // System.Object System.Collections.Generic.List`1::_syncRoot RuntimeObject * ____syncRoot_4; public: inline static int32_t get_offset_of__items_1() { return static_cast<int32_t>(offsetof(List_1_t6E613DAFFAFE896B759F1C5260D6234F04C9DD41, ____items_1)); } inline SubsystemWithProviderU5BU5D_t8A3DC7B8FFB1D676FD165C6B1FFE6DC8DF52CFCB* get__items_1() const { return ____items_1; } inline SubsystemWithProviderU5BU5D_t8A3DC7B8FFB1D676FD165C6B1FFE6DC8DF52CFCB** get_address_of__items_1() { return &____items_1; } inline void set__items_1(SubsystemWithProviderU5BU5D_t8A3DC7B8FFB1D676FD165C6B1FFE6DC8DF52CFCB* value) { ____items_1 = value; Il2CppCodeGenWriteBarrier((void**)(&____items_1), (void*)value); } inline static int32_t get_offset_of__size_2() { return static_cast<int32_t>(offsetof(List_1_t6E613DAFFAFE896B759F1C5260D6234F04C9DD41, ____size_2)); } inline int32_t get__size_2() const { return ____size_2; } inline int32_t* get_address_of__size_2() { return &____size_2; } inline void set__size_2(int32_t value) { ____size_2 = value; } inline static int32_t get_offset_of__version_3() { return static_cast<int32_t>(offsetof(List_1_t6E613DAFFAFE896B759F1C5260D6234F04C9DD41, ____version_3)); } inline int32_t get__version_3() const { return ____version_3; } inline int32_t* get_address_of__version_3() { return &____version_3; } inline void set__version_3(int32_t value) { ____version_3 = value; } inline static int32_t get_offset_of__syncRoot_4() { return static_cast<int32_t>(offsetof(List_1_t6E613DAFFAFE896B759F1C5260D6234F04C9DD41, ____syncRoot_4)); } inline RuntimeObject * get__syncRoot_4() const { return ____syncRoot_4; } inline RuntimeObject ** get_address_of__syncRoot_4() { return &____syncRoot_4; } inline void set__syncRoot_4(RuntimeObject * value) { ____syncRoot_4 = value; Il2CppCodeGenWriteBarrier((void**)(&____syncRoot_4), (void*)value); } }; struct List_1_t6E613DAFFAFE896B759F1C5260D6234F04C9DD41_StaticFields { public: // T[] System.Collections.Generic.List`1::_emptyArray SubsystemWithProviderU5BU5D_t8A3DC7B8FFB1D676FD165C6B1FFE6DC8DF52CFCB* ____emptyArray_5; public: inline static int32_t get_offset_of__emptyArray_5() { return static_cast<int32_t>(offsetof(List_1_t6E613DAFFAFE896B759F1C5260D6234F04C9DD41_StaticFields, ____emptyArray_5)); } inline SubsystemWithProviderU5BU5D_t8A3DC7B8FFB1D676FD165C6B1FFE6DC8DF52CFCB* get__emptyArray_5() const { return ____emptyArray_5; } inline SubsystemWithProviderU5BU5D_t8A3DC7B8FFB1D676FD165C6B1FFE6DC8DF52CFCB** get_address_of__emptyArray_5() { return &____emptyArray_5; } inline void set__emptyArray_5(SubsystemWithProviderU5BU5D_t8A3DC7B8FFB1D676FD165C6B1FFE6DC8DF52CFCB* value) { ____emptyArray_5 = value; Il2CppCodeGenWriteBarrier((void**)(&____emptyArray_5), (void*)value); } }; struct Il2CppArrayBounds; // System.Array // UnityEngine.Internal_SubsystemDescriptors struct Internal_SubsystemDescriptors_tE02B181DE901DC42D96F1726BD97F696190A08B5 : public RuntimeObject { public: public: }; // System.String struct String_t : public RuntimeObject { public: // System.Int32 System.String::m_stringLength int32_t ___m_stringLength_0; // System.Char System.String::m_firstChar Il2CppChar ___m_firstChar_1; public: inline static int32_t get_offset_of_m_stringLength_0() { return static_cast<int32_t>(offsetof(String_t, ___m_stringLength_0)); } inline int32_t get_m_stringLength_0() const { return ___m_stringLength_0; } inline int32_t* get_address_of_m_stringLength_0() { return &___m_stringLength_0; } inline void set_m_stringLength_0(int32_t value) { ___m_stringLength_0 = value; } inline static int32_t get_offset_of_m_firstChar_1() { return static_cast<int32_t>(offsetof(String_t, ___m_firstChar_1)); } inline Il2CppChar get_m_firstChar_1() const { return ___m_firstChar_1; } inline Il2CppChar* get_address_of_m_firstChar_1() { return &___m_firstChar_1; } inline void set_m_firstChar_1(Il2CppChar value) { ___m_firstChar_1 = value; } }; struct String_t_StaticFields { public: // System.String System.String::Empty String_t* ___Empty_5; public: inline static int32_t get_offset_of_Empty_5() { return static_cast<int32_t>(offsetof(String_t_StaticFields, ___Empty_5)); } inline String_t* get_Empty_5() const { return ___Empty_5; } inline String_t** get_address_of_Empty_5() { return &___Empty_5; } inline void set_Empty_5(String_t* value) { ___Empty_5 = value; Il2CppCodeGenWriteBarrier((void**)(&___Empty_5), (void*)value); } }; // UnityEngine.Subsystem struct Subsystem_t2D97454A946149D608974CB6B674F5F5C613A6A4 : public RuntimeObject { public: public: }; // UnityEngine.SubsystemDescriptor struct SubsystemDescriptor_tF663011CB44AB1D342821BBEF7B6811E799A7245 : public RuntimeObject { public: // System.String UnityEngine.SubsystemDescriptor::<id>k__BackingField String_t* ___U3CidU3Ek__BackingField_0; public: inline static int32_t get_offset_of_U3CidU3Ek__BackingField_0() { return static_cast<int32_t>(offsetof(SubsystemDescriptor_tF663011CB44AB1D342821BBEF7B6811E799A7245, ___U3CidU3Ek__BackingField_0)); } inline String_t* get_U3CidU3Ek__BackingField_0() const { return ___U3CidU3Ek__BackingField_0; } inline String_t** get_address_of_U3CidU3Ek__BackingField_0() { return &___U3CidU3Ek__BackingField_0; } inline void set_U3CidU3Ek__BackingField_0(String_t* value) { ___U3CidU3Ek__BackingField_0 = value; Il2CppCodeGenWriteBarrier((void**)(&___U3CidU3Ek__BackingField_0), (void*)value); } }; // UnityEngine.SubsystemDescriptorBindings struct SubsystemDescriptorBindings_t76C3E565A7953CD735CB10C1EF0B2DA8734DD795 : public RuntimeObject { public: public: }; // UnityEngine.SubsystemsImplementation.SubsystemDescriptorStore struct SubsystemDescriptorStore_tE5D99C3159868DE6506269CB6B830621F8BC31A6 : public RuntimeObject { public: public: }; struct SubsystemDescriptorStore_tE5D99C3159868DE6506269CB6B830621F8BC31A6_StaticFields { public: // System.Collections.Generic.List`1<UnityEngine.IntegratedSubsystemDescriptor> UnityEngine.SubsystemsImplementation.SubsystemDescriptorStore::s_IntegratedDescriptors List_1_t13B7F19BE124BF950C29583D073B7D2174DCA122 * ___s_IntegratedDescriptors_0; // System.Collections.Generic.List`1<UnityEngine.SubsystemsImplementation.SubsystemDescriptorWithProvider> UnityEngine.SubsystemsImplementation.SubsystemDescriptorStore::s_StandaloneDescriptors List_1_t4DCA5C48F3390AC8CD79C7AD8D0963D5DAE5CF2E * ___s_StandaloneDescriptors_1; // System.Collections.Generic.List`1<UnityEngine.SubsystemDescriptor> UnityEngine.SubsystemsImplementation.SubsystemDescriptorStore::s_DeprecatedDescriptors List_1_t32E50BD66297C6541AEA401E1C13D4EC530CC56B * ___s_DeprecatedDescriptors_2; public: inline static int32_t get_offset_of_s_IntegratedDescriptors_0() { return static_cast<int32_t>(offsetof(SubsystemDescriptorStore_tE5D99C3159868DE6506269CB6B830621F8BC31A6_StaticFields, ___s_IntegratedDescriptors_0)); } inline List_1_t13B7F19BE124BF950C29583D073B7D2174DCA122 * get_s_IntegratedDescriptors_0() const { return ___s_IntegratedDescriptors_0; } inline List_1_t13B7F19BE124BF950C29583D073B7D2174DCA122 ** get_address_of_s_IntegratedDescriptors_0() { return &___s_IntegratedDescriptors_0; } inline void set_s_IntegratedDescriptors_0(List_1_t13B7F19BE124BF950C29583D073B7D2174DCA122 * value) { ___s_IntegratedDescriptors_0 = value; Il2CppCodeGenWriteBarrier((void**)(&___s_IntegratedDescriptors_0), (void*)value); } inline static int32_t get_offset_of_s_StandaloneDescriptors_1() { return static_cast<int32_t>(offsetof(SubsystemDescriptorStore_tE5D99C3159868DE6506269CB6B830621F8BC31A6_StaticFields, ___s_StandaloneDescriptors_1)); } inline List_1_t4DCA5C48F3390AC8CD79C7AD8D0963D5DAE5CF2E * get_s_StandaloneDescriptors_1() const { return ___s_StandaloneDescriptors_1; } inline List_1_t4DCA5C48F3390AC8CD79C7AD8D0963D5DAE5CF2E ** get_address_of_s_StandaloneDescriptors_1() { return &___s_StandaloneDescriptors_1; } inline void set_s_StandaloneDescriptors_1(List_1_t4DCA5C48F3390AC8CD79C7AD8D0963D5DAE5CF2E * value) { ___s_StandaloneDescriptors_1 = value; Il2CppCodeGenWriteBarrier((void**)(&___s_StandaloneDescriptors_1), (void*)value); } inline static int32_t get_offset_of_s_DeprecatedDescriptors_2() { return static_cast<int32_t>(offsetof(SubsystemDescriptorStore_tE5D99C3159868DE6506269CB6B830621F8BC31A6_StaticFields, ___s_DeprecatedDescriptors_2)); } inline List_1_t32E50BD66297C6541AEA401E1C13D4EC530CC56B * get_s_DeprecatedDescriptors_2() const { return ___s_DeprecatedDescriptors_2; } inline List_1_t32E50BD66297C6541AEA401E1C13D4EC530CC56B ** get_address_of_s_DeprecatedDescriptors_2() { return &___s_DeprecatedDescriptors_2; } inline void set_s_DeprecatedDescriptors_2(List_1_t32E50BD66297C6541AEA401E1C13D4EC530CC56B * value) { ___s_DeprecatedDescriptors_2 = value; Il2CppCodeGenWriteBarrier((void**)(&___s_DeprecatedDescriptors_2), (void*)value); } }; // UnityEngine.SubsystemsImplementation.SubsystemDescriptorWithProvider struct SubsystemDescriptorWithProvider_t32DD334657CFBA22F2FBA399258B087104A29C3E : public RuntimeObject { public: // System.String UnityEngine.SubsystemsImplementation.SubsystemDescriptorWithProvider::<id>k__BackingField String_t* ___U3CidU3Ek__BackingField_0; public: inline static int32_t get_offset_of_U3CidU3Ek__BackingField_0() { return static_cast<int32_t>(offsetof(SubsystemDescriptorWithProvider_t32DD334657CFBA22F2FBA399258B087104A29C3E, ___U3CidU3Ek__BackingField_0)); } inline String_t* get_U3CidU3Ek__BackingField_0() const { return ___U3CidU3Ek__BackingField_0; } inline String_t** get_address_of_U3CidU3Ek__BackingField_0() { return &___U3CidU3Ek__BackingField_0; } inline void set_U3CidU3Ek__BackingField_0(String_t* value) { ___U3CidU3Ek__BackingField_0 = value; Il2CppCodeGenWriteBarrier((void**)(&___U3CidU3Ek__BackingField_0), (void*)value); } }; // UnityEngine.SubsystemManager struct SubsystemManager_t4397CEF2ED795CB9B3DDBA2BB468BCB6B45B76D9 : public RuntimeObject { public: public: }; struct SubsystemManager_t4397CEF2ED795CB9B3DDBA2BB468BCB6B45B76D9_StaticFields { public: // System.Action UnityEngine.SubsystemManager::beforeReloadSubsystems Action_tAF41423D285AE0862865348CF6CE51CD085ABBA6 * ___beforeReloadSubsystems_0; // System.Action UnityEngine.SubsystemManager::afterReloadSubsystems Action_tAF41423D285AE0862865348CF6CE51CD085ABBA6 * ___afterReloadSubsystems_1; // System.Collections.Generic.List`1<UnityEngine.IntegratedSubsystem> UnityEngine.SubsystemManager::s_IntegratedSubsystems List_1_t2DAF7481782912A6F8E6180AC19B83A5EEFEE9EF * ___s_IntegratedSubsystems_2; // System.Collections.Generic.List`1<UnityEngine.SubsystemsImplementation.SubsystemWithProvider> UnityEngine.SubsystemManager::s_StandaloneSubsystems List_1_t6E613DAFFAFE896B759F1C5260D6234F04C9DD41 * ___s_StandaloneSubsystems_3; // System.Collections.Generic.List`1<UnityEngine.Subsystem> UnityEngine.SubsystemManager::s_DeprecatedSubsystems List_1_t58BB84B47855540E6D2640B387506E01436DCF82 * ___s_DeprecatedSubsystems_4; // System.Action UnityEngine.SubsystemManager::reloadSubsytemsStarted Action_tAF41423D285AE0862865348CF6CE51CD085ABBA6 * ___reloadSubsytemsStarted_5; // System.Action UnityEngine.SubsystemManager::reloadSubsytemsCompleted Action_tAF41423D285AE0862865348CF6CE51CD085ABBA6 * ___reloadSubsytemsCompleted_6; public: inline static int32_t get_offset_of_beforeReloadSubsystems_0() { return static_cast<int32_t>(offsetof(SubsystemManager_t4397CEF2ED795CB9B3DDBA2BB468BCB6B45B76D9_StaticFields, ___beforeReloadSubsystems_0)); } inline Action_tAF41423D285AE0862865348CF6CE51CD085ABBA6 * get_beforeReloadSubsystems_0() const { return ___beforeReloadSubsystems_0; } inline Action_tAF41423D285AE0862865348CF6CE51CD085ABBA6 ** get_address_of_beforeReloadSubsystems_0() { return &___beforeReloadSubsystems_0; } inline void set_beforeReloadSubsystems_0(Action_tAF41423D285AE0862865348CF6CE51CD085ABBA6 * value) { ___beforeReloadSubsystems_0 = value; Il2CppCodeGenWriteBarrier((void**)(&___beforeReloadSubsystems_0), (void*)value); } inline static int32_t get_offset_of_afterReloadSubsystems_1() { return static_cast<int32_t>(offsetof(SubsystemManager_t4397CEF2ED795CB9B3DDBA2BB468BCB6B45B76D9_StaticFields, ___afterReloadSubsystems_1)); } inline Action_tAF41423D285AE0862865348CF6CE51CD085ABBA6 * get_afterReloadSubsystems_1() const { return ___afterReloadSubsystems_1; } inline Action_tAF41423D285AE0862865348CF6CE51CD085ABBA6 ** get_address_of_afterReloadSubsystems_1() { return &___afterReloadSubsystems_1; } inline void set_afterReloadSubsystems_1(Action_tAF41423D285AE0862865348CF6CE51CD085ABBA6 * value) { ___afterReloadSubsystems_1 = value; Il2CppCodeGenWriteBarrier((void**)(&___afterReloadSubsystems_1), (void*)value); } inline static int32_t get_offset_of_s_IntegratedSubsystems_2() { return static_cast<int32_t>(offsetof(SubsystemManager_t4397CEF2ED795CB9B3DDBA2BB468BCB6B45B76D9_StaticFields, ___s_IntegratedSubsystems_2)); } inline List_1_t2DAF7481782912A6F8E6180AC19B83A5EEFEE9EF * get_s_IntegratedSubsystems_2() const { return ___s_IntegratedSubsystems_2; } inline List_1_t2DAF7481782912A6F8E6180AC19B83A5EEFEE9EF ** get_address_of_s_IntegratedSubsystems_2() { return &___s_IntegratedSubsystems_2; } inline void set_s_IntegratedSubsystems_2(List_1_t2DAF7481782912A6F8E6180AC19B83A5EEFEE9EF * value) { ___s_IntegratedSubsystems_2 = value; Il2CppCodeGenWriteBarrier((void**)(&___s_IntegratedSubsystems_2), (void*)value); } inline static int32_t get_offset_of_s_StandaloneSubsystems_3() { return static_cast<int32_t>(offsetof(SubsystemManager_t4397CEF2ED795CB9B3DDBA2BB468BCB6B45B76D9_StaticFields, ___s_StandaloneSubsystems_3)); } inline List_1_t6E613DAFFAFE896B759F1C5260D6234F04C9DD41 * get_s_StandaloneSubsystems_3() const { return ___s_StandaloneSubsystems_3; } inline List_1_t6E613DAFFAFE896B759F1C5260D6234F04C9DD41 ** get_address_of_s_StandaloneSubsystems_3() { return &___s_StandaloneSubsystems_3; } inline void set_s_StandaloneSubsystems_3(List_1_t6E613DAFFAFE896B759F1C5260D6234F04C9DD41 * value) { ___s_StandaloneSubsystems_3 = value; Il2CppCodeGenWriteBarrier((void**)(&___s_StandaloneSubsystems_3), (void*)value); } inline static int32_t get_offset_of_s_DeprecatedSubsystems_4() { return static_cast<int32_t>(offsetof(SubsystemManager_t4397CEF2ED795CB9B3DDBA2BB468BCB6B45B76D9_StaticFields, ___s_DeprecatedSubsystems_4)); } inline List_1_t58BB84B47855540E6D2640B387506E01436DCF82 * get_s_DeprecatedSubsystems_4() const { return ___s_DeprecatedSubsystems_4; } inline List_1_t58BB84B47855540E6D2640B387506E01436DCF82 ** get_address_of_s_DeprecatedSubsystems_4() { return &___s_DeprecatedSubsystems_4; } inline void set_s_DeprecatedSubsystems_4(List_1_t58BB84B47855540E6D2640B387506E01436DCF82 * value) { ___s_DeprecatedSubsystems_4 = value; Il2CppCodeGenWriteBarrier((void**)(&___s_DeprecatedSubsystems_4), (void*)value); } inline static int32_t get_offset_of_reloadSubsytemsStarted_5() { return static_cast<int32_t>(offsetof(SubsystemManager_t4397CEF2ED795CB9B3DDBA2BB468BCB6B45B76D9_StaticFields, ___reloadSubsytemsStarted_5)); } inline Action_tAF41423D285AE0862865348CF6CE51CD085ABBA6 * get_reloadSubsytemsStarted_5() const { return ___reloadSubsytemsStarted_5; } inline Action_tAF41423D285AE0862865348CF6CE51CD085ABBA6 ** get_address_of_reloadSubsytemsStarted_5() { return &___reloadSubsytemsStarted_5; } inline void set_reloadSubsytemsStarted_5(Action_tAF41423D285AE0862865348CF6CE51CD085ABBA6 * value) { ___reloadSubsytemsStarted_5 = value; Il2CppCodeGenWriteBarrier((void**)(&___reloadSubsytemsStarted_5), (void*)value); } inline static int32_t get_offset_of_reloadSubsytemsCompleted_6() { return static_cast<int32_t>(offsetof(SubsystemManager_t4397CEF2ED795CB9B3DDBA2BB468BCB6B45B76D9_StaticFields, ___reloadSubsytemsCompleted_6)); } inline Action_tAF41423D285AE0862865348CF6CE51CD085ABBA6 * get_reloadSubsytemsCompleted_6() const { return ___reloadSubsytemsCompleted_6; } inline Action_tAF41423D285AE0862865348CF6CE51CD085ABBA6 ** get_address_of_reloadSubsytemsCompleted_6() { return &___reloadSubsytemsCompleted_6; } inline void set_reloadSubsytemsCompleted_6(Action_tAF41423D285AE0862865348CF6CE51CD085ABBA6 * value) { ___reloadSubsytemsCompleted_6 = value; Il2CppCodeGenWriteBarrier((void**)(&___reloadSubsytemsCompleted_6), (void*)value); } }; // UnityEngine.SubsystemsImplementation.SubsystemWithProvider struct SubsystemWithProvider_t1C1868CF8676F5596C1AD20A7CE69BDF7C7DE73E : public RuntimeObject { public: public: }; // System.ValueType struct ValueType_tDBF999C1B75C48C68621878250DBF6CDBCF51E52 : public RuntimeObject { public: public: }; // Native definition for P/Invoke marshalling of System.ValueType struct ValueType_tDBF999C1B75C48C68621878250DBF6CDBCF51E52_marshaled_pinvoke { }; // Native definition for COM marshalling of System.ValueType struct ValueType_tDBF999C1B75C48C68621878250DBF6CDBCF51E52_marshaled_com { }; // System.Collections.Generic.List`1/Enumerator<UnityEngine.IntegratedSubsystem> struct Enumerator_tCF86CE3FF03B86F9FF1AB5746DF9DEE36DCAD59D { public: // System.Collections.Generic.List`1<T> System.Collections.Generic.List`1/Enumerator::list List_1_t2DAF7481782912A6F8E6180AC19B83A5EEFEE9EF * ___list_0; // System.Int32 System.Collections.Generic.List`1/Enumerator::index int32_t ___index_1; // System.Int32 System.Collections.Generic.List`1/Enumerator::version int32_t ___version_2; // T System.Collections.Generic.List`1/Enumerator::current IntegratedSubsystem_t8FB3A371F812CF9521903AC016C64E95C7412002 * ___current_3; public: inline static int32_t get_offset_of_list_0() { return static_cast<int32_t>(offsetof(Enumerator_tCF86CE3FF03B86F9FF1AB5746DF9DEE36DCAD59D, ___list_0)); } inline List_1_t2DAF7481782912A6F8E6180AC19B83A5EEFEE9EF * get_list_0() const { return ___list_0; } inline List_1_t2DAF7481782912A6F8E6180AC19B83A5EEFEE9EF ** get_address_of_list_0() { return &___list_0; } inline void set_list_0(List_1_t2DAF7481782912A6F8E6180AC19B83A5EEFEE9EF * value) { ___list_0 = value; Il2CppCodeGenWriteBarrier((void**)(&___list_0), (void*)value); } inline static int32_t get_offset_of_index_1() { return static_cast<int32_t>(offsetof(Enumerator_tCF86CE3FF03B86F9FF1AB5746DF9DEE36DCAD59D, ___index_1)); } inline int32_t get_index_1() const { return ___index_1; } inline int32_t* get_address_of_index_1() { return &___index_1; } inline void set_index_1(int32_t value) { ___index_1 = value; } inline static int32_t get_offset_of_version_2() { return static_cast<int32_t>(offsetof(Enumerator_tCF86CE3FF03B86F9FF1AB5746DF9DEE36DCAD59D, ___version_2)); } inline int32_t get_version_2() const { return ___version_2; } inline int32_t* get_address_of_version_2() { return &___version_2; } inline void set_version_2(int32_t value) { ___version_2 = value; } inline static int32_t get_offset_of_current_3() { return static_cast<int32_t>(offsetof(Enumerator_tCF86CE3FF03B86F9FF1AB5746DF9DEE36DCAD59D, ___current_3)); } inline IntegratedSubsystem_t8FB3A371F812CF9521903AC016C64E95C7412002 * get_current_3() const { return ___current_3; } inline IntegratedSubsystem_t8FB3A371F812CF9521903AC016C64E95C7412002 ** get_address_of_current_3() { return &___current_3; } inline void set_current_3(IntegratedSubsystem_t8FB3A371F812CF9521903AC016C64E95C7412002 * value) { ___current_3 = value; Il2CppCodeGenWriteBarrier((void**)(&___current_3), (void*)value); } }; // System.Collections.Generic.List`1/Enumerator<UnityEngine.IntegratedSubsystemDescriptor> struct Enumerator_t743A52D99B71AF8E5AB3809E59FF43C7108E85D9 { public: // System.Collections.Generic.List`1<T> System.Collections.Generic.List`1/Enumerator::list List_1_t13B7F19BE124BF950C29583D073B7D2174DCA122 * ___list_0; // System.Int32 System.Collections.Generic.List`1/Enumerator::index int32_t ___index_1; // System.Int32 System.Collections.Generic.List`1/Enumerator::version int32_t ___version_2; // T System.Collections.Generic.List`1/Enumerator::current IntegratedSubsystemDescriptor_tDC8AF8E5B67B983E4492D784A419F01693926D7A * ___current_3; public: inline static int32_t get_offset_of_list_0() { return static_cast<int32_t>(offsetof(Enumerator_t743A52D99B71AF8E5AB3809E59FF43C7108E85D9, ___list_0)); } inline List_1_t13B7F19BE124BF950C29583D073B7D2174DCA122 * get_list_0() const { return ___list_0; } inline List_1_t13B7F19BE124BF950C29583D073B7D2174DCA122 ** get_address_of_list_0() { return &___list_0; } inline void set_list_0(List_1_t13B7F19BE124BF950C29583D073B7D2174DCA122 * value) { ___list_0 = value; Il2CppCodeGenWriteBarrier((void**)(&___list_0), (void*)value); } inline static int32_t get_offset_of_index_1() { return static_cast<int32_t>(offsetof(Enumerator_t743A52D99B71AF8E5AB3809E59FF43C7108E85D9, ___index_1)); } inline int32_t get_index_1() const { return ___index_1; } inline int32_t* get_address_of_index_1() { return &___index_1; } inline void set_index_1(int32_t value) { ___index_1 = value; } inline static int32_t get_offset_of_version_2() { return static_cast<int32_t>(offsetof(Enumerator_t743A52D99B71AF8E5AB3809E59FF43C7108E85D9, ___version_2)); } inline int32_t get_version_2() const { return ___version_2; } inline int32_t* get_address_of_version_2() { return &___version_2; } inline void set_version_2(int32_t value) { ___version_2 = value; } inline static int32_t get_offset_of_current_3() { return static_cast<int32_t>(offsetof(Enumerator_t743A52D99B71AF8E5AB3809E59FF43C7108E85D9, ___current_3)); } inline IntegratedSubsystemDescriptor_tDC8AF8E5B67B983E4492D784A419F01693926D7A * get_current_3() const { return ___current_3; } inline IntegratedSubsystemDescriptor_tDC8AF8E5B67B983E4492D784A419F01693926D7A ** get_address_of_current_3() { return &___current_3; } inline void set_current_3(IntegratedSubsystemDescriptor_tDC8AF8E5B67B983E4492D784A419F01693926D7A * value) { ___current_3 = value; Il2CppCodeGenWriteBarrier((void**)(&___current_3), (void*)value); } }; // System.Collections.Generic.List`1/Enumerator<System.Object> struct Enumerator_tB6009981BD4E3881E3EC83627255A24198F902D6 { public: // System.Collections.Generic.List`1<T> System.Collections.Generic.List`1/Enumerator::list List_1_t3F94120C77410A62EAE48421CF166B83AB95A2F5 * ___list_0; // System.Int32 System.Collections.Generic.List`1/Enumerator::index int32_t ___index_1; // System.Int32 System.Collections.Generic.List`1/Enumerator::version int32_t ___version_2; // T System.Collections.Generic.List`1/Enumerator::current RuntimeObject * ___current_3; public: inline static int32_t get_offset_of_list_0() { return static_cast<int32_t>(offsetof(Enumerator_tB6009981BD4E3881E3EC83627255A24198F902D6, ___list_0)); } inline List_1_t3F94120C77410A62EAE48421CF166B83AB95A2F5 * get_list_0() const { return ___list_0; } inline List_1_t3F94120C77410A62EAE48421CF166B83AB95A2F5 ** get_address_of_list_0() { return &___list_0; } inline void set_list_0(List_1_t3F94120C77410A62EAE48421CF166B83AB95A2F5 * value) { ___list_0 = value; Il2CppCodeGenWriteBarrier((void**)(&___list_0), (void*)value); } inline static int32_t get_offset_of_index_1() { return static_cast<int32_t>(offsetof(Enumerator_tB6009981BD4E3881E3EC83627255A24198F902D6, ___index_1)); } inline int32_t get_index_1() const { return ___index_1; } inline int32_t* get_address_of_index_1() { return &___index_1; } inline void set_index_1(int32_t value) { ___index_1 = value; } inline static int32_t get_offset_of_version_2() { return static_cast<int32_t>(offsetof(Enumerator_tB6009981BD4E3881E3EC83627255A24198F902D6, ___version_2)); } inline int32_t get_version_2() const { return ___version_2; } inline int32_t* get_address_of_version_2() { return &___version_2; } inline void set_version_2(int32_t value) { ___version_2 = value; } inline static int32_t get_offset_of_current_3() { return static_cast<int32_t>(offsetof(Enumerator_tB6009981BD4E3881E3EC83627255A24198F902D6, ___current_3)); } inline RuntimeObject * get_current_3() const { return ___current_3; } inline RuntimeObject ** get_address_of_current_3() { return &___current_3; } inline void set_current_3(RuntimeObject * value) { ___current_3 = value; Il2CppCodeGenWriteBarrier((void**)(&___current_3), (void*)value); } }; // System.Boolean struct Boolean_t07D1E3F34E4813023D64F584DFF7B34C9D922F37 { public: // System.Boolean System.Boolean::m_value bool ___m_value_0; public: inline static int32_t get_offset_of_m_value_0() { return static_cast<int32_t>(offsetof(Boolean_t07D1E3F34E4813023D64F584DFF7B34C9D922F37, ___m_value_0)); } inline bool get_m_value_0() const { return ___m_value_0; } inline bool* get_address_of_m_value_0() { return &___m_value_0; } inline void set_m_value_0(bool value) { ___m_value_0 = value; } }; struct Boolean_t07D1E3F34E4813023D64F584DFF7B34C9D922F37_StaticFields { public: // System.String System.Boolean::TrueString String_t* ___TrueString_5; // System.String System.Boolean::FalseString String_t* ___FalseString_6; public: inline static int32_t get_offset_of_TrueString_5() { return static_cast<int32_t>(offsetof(Boolean_t07D1E3F34E4813023D64F584DFF7B34C9D922F37_StaticFields, ___TrueString_5)); } inline String_t* get_TrueString_5() const { return ___TrueString_5; } inline String_t** get_address_of_TrueString_5() { return &___TrueString_5; } inline void set_TrueString_5(String_t* value) { ___TrueString_5 = value; Il2CppCodeGenWriteBarrier((void**)(&___TrueString_5), (void*)value); } inline static int32_t get_offset_of_FalseString_6() { return static_cast<int32_t>(offsetof(Boolean_t07D1E3F34E4813023D64F584DFF7B34C9D922F37_StaticFields, ___FalseString_6)); } inline String_t* get_FalseString_6() const { return ___FalseString_6; } inline String_t** get_address_of_FalseString_6() { return &___FalseString_6; } inline void set_FalseString_6(String_t* value) { ___FalseString_6 = value; Il2CppCodeGenWriteBarrier((void**)(&___FalseString_6), (void*)value); } }; // System.IntPtr struct IntPtr_t { public: // System.Void* System.IntPtr::m_value void* ___m_value_0; public: inline static int32_t get_offset_of_m_value_0() { return static_cast<int32_t>(offsetof(IntPtr_t, ___m_value_0)); } inline void* get_m_value_0() const { return ___m_value_0; } inline void** get_address_of_m_value_0() { return &___m_value_0; } inline void set_m_value_0(void* value) { ___m_value_0 = value; } }; struct IntPtr_t_StaticFields { public: // System.IntPtr System.IntPtr::Zero intptr_t ___Zero_1; public: inline static int32_t get_offset_of_Zero_1() { return static_cast<int32_t>(offsetof(IntPtr_t_StaticFields, ___Zero_1)); } inline intptr_t get_Zero_1() const { return ___Zero_1; } inline intptr_t* get_address_of_Zero_1() { return &___Zero_1; } inline void set_Zero_1(intptr_t value) { ___Zero_1 = value; } }; // System.Void struct Void_t700C6383A2A510C2CF4DD86DABD5CA9FF70ADAC5 { public: union { struct { }; uint8_t Void_t700C6383A2A510C2CF4DD86DABD5CA9FF70ADAC5__padding[1]; }; public: }; // System.Delegate struct Delegate_t : public RuntimeObject { public: // System.IntPtr System.Delegate::method_ptr Il2CppMethodPointer ___method_ptr_0; // System.IntPtr System.Delegate::invoke_impl intptr_t ___invoke_impl_1; // System.Object System.Delegate::m_target RuntimeObject * ___m_target_2; // System.IntPtr System.Delegate::method intptr_t ___method_3; // System.IntPtr System.Delegate::delegate_trampoline intptr_t ___delegate_trampoline_4; // System.IntPtr System.Delegate::extra_arg intptr_t ___extra_arg_5; // System.IntPtr System.Delegate::method_code intptr_t ___method_code_6; // System.Reflection.MethodInfo System.Delegate::method_info MethodInfo_t * ___method_info_7; // System.Reflection.MethodInfo System.Delegate::original_method_info MethodInfo_t * ___original_method_info_8; // System.DelegateData System.Delegate::data DelegateData_t17DD30660E330C49381DAA99F934BE75CB11F288 * ___data_9; // System.Boolean System.Delegate::method_is_virtual bool ___method_is_virtual_10; public: inline static int32_t get_offset_of_method_ptr_0() { return static_cast<int32_t>(offsetof(Delegate_t, ___method_ptr_0)); } inline Il2CppMethodPointer get_method_ptr_0() const { return ___method_ptr_0; } inline Il2CppMethodPointer* get_address_of_method_ptr_0() { return &___method_ptr_0; } inline void set_method_ptr_0(Il2CppMethodPointer value) { ___method_ptr_0 = value; } inline static int32_t get_offset_of_invoke_impl_1() { return static_cast<int32_t>(offsetof(Delegate_t, ___invoke_impl_1)); } inline intptr_t get_invoke_impl_1() const { return ___invoke_impl_1; } inline intptr_t* get_address_of_invoke_impl_1() { return &___invoke_impl_1; } inline void set_invoke_impl_1(intptr_t value) { ___invoke_impl_1 = value; } inline static int32_t get_offset_of_m_target_2() { return static_cast<int32_t>(offsetof(Delegate_t, ___m_target_2)); } inline RuntimeObject * get_m_target_2() const { return ___m_target_2; } inline RuntimeObject ** get_address_of_m_target_2() { return &___m_target_2; } inline void set_m_target_2(RuntimeObject * value) { ___m_target_2 = value; Il2CppCodeGenWriteBarrier((void**)(&___m_target_2), (void*)value); } inline static int32_t get_offset_of_method_3() { return static_cast<int32_t>(offsetof(Delegate_t, ___method_3)); } inline intptr_t get_method_3() const { return ___method_3; } inline intptr_t* get_address_of_method_3() { return &___method_3; } inline void set_method_3(intptr_t value) { ___method_3 = value; } inline static int32_t get_offset_of_delegate_trampoline_4() { return static_cast<int32_t>(offsetof(Delegate_t, ___delegate_trampoline_4)); } inline intptr_t get_delegate_trampoline_4() const { return ___delegate_trampoline_4; } inline intptr_t* get_address_of_delegate_trampoline_4() { return &___delegate_trampoline_4; } inline void set_delegate_trampoline_4(intptr_t value) { ___delegate_trampoline_4 = value; } inline static int32_t get_offset_of_extra_arg_5() { return static_cast<int32_t>(offsetof(Delegate_t, ___extra_arg_5)); } inline intptr_t get_extra_arg_5() const { return ___extra_arg_5; } inline intptr_t* get_address_of_extra_arg_5() { return &___extra_arg_5; } inline void set_extra_arg_5(intptr_t value) { ___extra_arg_5 = value; } inline static int32_t get_offset_of_method_code_6() { return static_cast<int32_t>(offsetof(Delegate_t, ___method_code_6)); } inline intptr_t get_method_code_6() const { return ___method_code_6; } inline intptr_t* get_address_of_method_code_6() { return &___method_code_6; } inline void set_method_code_6(intptr_t value) { ___method_code_6 = value; } inline static int32_t get_offset_of_method_info_7() { return static_cast<int32_t>(offsetof(Delegate_t, ___method_info_7)); } inline MethodInfo_t * get_method_info_7() const { return ___method_info_7; } inline MethodInfo_t ** get_address_of_method_info_7() { return &___method_info_7; } inline void set_method_info_7(MethodInfo_t * value) { ___method_info_7 = value; Il2CppCodeGenWriteBarrier((void**)(&___method_info_7), (void*)value); } inline static int32_t get_offset_of_original_method_info_8() { return static_cast<int32_t>(offsetof(Delegate_t, ___original_method_info_8)); } inline MethodInfo_t * get_original_method_info_8() const { return ___original_method_info_8; } inline MethodInfo_t ** get_address_of_original_method_info_8() { return &___original_method_info_8; } inline void set_original_method_info_8(MethodInfo_t * value) { ___original_method_info_8 = value; Il2CppCodeGenWriteBarrier((void**)(&___original_method_info_8), (void*)value); } inline static int32_t get_offset_of_data_9() { return static_cast<int32_t>(offsetof(Delegate_t, ___data_9)); } inline DelegateData_t17DD30660E330C49381DAA99F934BE75CB11F288 * get_data_9() const { return ___data_9; } inline DelegateData_t17DD30660E330C49381DAA99F934BE75CB11F288 ** get_address_of_data_9() { return &___data_9; } inline void set_data_9(DelegateData_t17DD30660E330C49381DAA99F934BE75CB11F288 * value) { ___data_9 = value; Il2CppCodeGenWriteBarrier((void**)(&___data_9), (void*)value); } inline static int32_t get_offset_of_method_is_virtual_10() { return static_cast<int32_t>(offsetof(Delegate_t, ___method_is_virtual_10)); } inline bool get_method_is_virtual_10() const { return ___method_is_virtual_10; } inline bool* get_address_of_method_is_virtual_10() { return &___method_is_virtual_10; } inline void set_method_is_virtual_10(bool value) { ___method_is_virtual_10 = value; } }; // Native definition for P/Invoke marshalling of System.Delegate struct Delegate_t_marshaled_pinvoke { intptr_t ___method_ptr_0; intptr_t ___invoke_impl_1; Il2CppIUnknown* ___m_target_2; intptr_t ___method_3; intptr_t ___delegate_trampoline_4; intptr_t ___extra_arg_5; intptr_t ___method_code_6; MethodInfo_t * ___method_info_7; MethodInfo_t * ___original_method_info_8; DelegateData_t17DD30660E330C49381DAA99F934BE75CB11F288 * ___data_9; int32_t ___method_is_virtual_10; }; // Native definition for COM marshalling of System.Delegate struct Delegate_t_marshaled_com { intptr_t ___method_ptr_0; intptr_t ___invoke_impl_1; Il2CppIUnknown* ___m_target_2; intptr_t ___method_3; intptr_t ___delegate_trampoline_4; intptr_t ___extra_arg_5; intptr_t ___method_code_6; MethodInfo_t * ___method_info_7; MethodInfo_t * ___original_method_info_8; DelegateData_t17DD30660E330C49381DAA99F934BE75CB11F288 * ___data_9; int32_t ___method_is_virtual_10; }; // UnityEngine.IntegratedSubsystem struct IntegratedSubsystem_t8FB3A371F812CF9521903AC016C64E95C7412002 : public RuntimeObject { public: // System.IntPtr UnityEngine.IntegratedSubsystem::m_Ptr intptr_t ___m_Ptr_0; // UnityEngine.ISubsystemDescriptor UnityEngine.IntegratedSubsystem::m_SubsystemDescriptor RuntimeObject* ___m_SubsystemDescriptor_1; public: inline static int32_t get_offset_of_m_Ptr_0() { return static_cast<int32_t>(offsetof(IntegratedSubsystem_t8FB3A371F812CF9521903AC016C64E95C7412002, ___m_Ptr_0)); } inline intptr_t get_m_Ptr_0() const { return ___m_Ptr_0; } inline intptr_t* get_address_of_m_Ptr_0() { return &___m_Ptr_0; } inline void set_m_Ptr_0(intptr_t value) { ___m_Ptr_0 = value; } inline static int32_t get_offset_of_m_SubsystemDescriptor_1() { return static_cast<int32_t>(offsetof(IntegratedSubsystem_t8FB3A371F812CF9521903AC016C64E95C7412002, ___m_SubsystemDescriptor_1)); } inline RuntimeObject* get_m_SubsystemDescriptor_1() const { return ___m_SubsystemDescriptor_1; } inline RuntimeObject** get_address_of_m_SubsystemDescriptor_1() { return &___m_SubsystemDescriptor_1; } inline void set_m_SubsystemDescriptor_1(RuntimeObject* value) { ___m_SubsystemDescriptor_1 = value; Il2CppCodeGenWriteBarrier((void**)(&___m_SubsystemDescriptor_1), (void*)value); } }; // Native definition for P/Invoke marshalling of UnityEngine.IntegratedSubsystem struct IntegratedSubsystem_t8FB3A371F812CF9521903AC016C64E95C7412002_marshaled_pinvoke { intptr_t ___m_Ptr_0; RuntimeObject* ___m_SubsystemDescriptor_1; }; // Native definition for COM marshalling of UnityEngine.IntegratedSubsystem struct IntegratedSubsystem_t8FB3A371F812CF9521903AC016C64E95C7412002_marshaled_com { intptr_t ___m_Ptr_0; RuntimeObject* ___m_SubsystemDescriptor_1; }; // UnityEngine.IntegratedSubsystemDescriptor struct IntegratedSubsystemDescriptor_tDC8AF8E5B67B983E4492D784A419F01693926D7A : public RuntimeObject { public: // System.IntPtr UnityEngine.IntegratedSubsystemDescriptor::m_Ptr intptr_t ___m_Ptr_0; public: inline static int32_t get_offset_of_m_Ptr_0() { return static_cast<int32_t>(offsetof(IntegratedSubsystemDescriptor_tDC8AF8E5B67B983E4492D784A419F01693926D7A, ___m_Ptr_0)); } inline intptr_t get_m_Ptr_0() const { return ___m_Ptr_0; } inline intptr_t* get_address_of_m_Ptr_0() { return &___m_Ptr_0; } inline void set_m_Ptr_0(intptr_t value) { ___m_Ptr_0 = value; } }; // Native definition for P/Invoke marshalling of UnityEngine.IntegratedSubsystemDescriptor struct IntegratedSubsystemDescriptor_tDC8AF8E5B67B983E4492D784A419F01693926D7A_marshaled_pinvoke { intptr_t ___m_Ptr_0; }; // Native definition for COM marshalling of UnityEngine.IntegratedSubsystemDescriptor struct IntegratedSubsystemDescriptor_tDC8AF8E5B67B983E4492D784A419F01693926D7A_marshaled_com { intptr_t ___m_Ptr_0; }; // System.MulticastDelegate struct MulticastDelegate_t : public Delegate_t { public: // System.Delegate[] System.MulticastDelegate::delegates DelegateU5BU5D_t677D8FE08A5F99E8EE49150B73966CD6E9BF7DB8* ___delegates_11; public: inline static int32_t get_offset_of_delegates_11() { return static_cast<int32_t>(offsetof(MulticastDelegate_t, ___delegates_11)); } inline DelegateU5BU5D_t677D8FE08A5F99E8EE49150B73966CD6E9BF7DB8* get_delegates_11() const { return ___delegates_11; } inline DelegateU5BU5D_t677D8FE08A5F99E8EE49150B73966CD6E9BF7DB8** get_address_of_delegates_11() { return &___delegates_11; } inline void set_delegates_11(DelegateU5BU5D_t677D8FE08A5F99E8EE49150B73966CD6E9BF7DB8* value) { ___delegates_11 = value; Il2CppCodeGenWriteBarrier((void**)(&___delegates_11), (void*)value); } }; // Native definition for P/Invoke marshalling of System.MulticastDelegate struct MulticastDelegate_t_marshaled_pinvoke : public Delegate_t_marshaled_pinvoke { Delegate_t_marshaled_pinvoke** ___delegates_11; }; // Native definition for COM marshalling of System.MulticastDelegate struct MulticastDelegate_t_marshaled_com : public Delegate_t_marshaled_com { Delegate_t_marshaled_com** ___delegates_11; }; // System.Action struct Action_tAF41423D285AE0862865348CF6CE51CD085ABBA6 : public MulticastDelegate_t { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif // System.Void System.Collections.Generic.List`1<System.Object>::Add(!0) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void List_1_Add_mE5B3CBB3A625606D9BC4337FEAAF1D66BCB6F96E_gshared (List_1_t3F94120C77410A62EAE48421CF166B83AB95A2F5 * __this, RuntimeObject * ___item0, const RuntimeMethod* method); // System.Collections.Generic.List`1/Enumerator<!0> System.Collections.Generic.List`1<System.Object>::GetEnumerator() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR Enumerator_tB6009981BD4E3881E3EC83627255A24198F902D6 List_1_GetEnumerator_m1739A5E25DF502A6984F9B98CFCAC2D3FABCF233_gshared (List_1_t3F94120C77410A62EAE48421CF166B83AB95A2F5 * __this, const RuntimeMethod* method); // !0 System.Collections.Generic.List`1/Enumerator<System.Object>::get_Current() IL2CPP_MANAGED_FORCE_INLINE IL2CPP_METHOD_ATTR RuntimeObject * Enumerator_get_Current_m9C4EBBD2108B51885E750F927D7936290C8E20EE_gshared_inline (Enumerator_tB6009981BD4E3881E3EC83627255A24198F902D6 * __this, const RuntimeMethod* method); // System.Boolean System.Collections.Generic.List`1/Enumerator<System.Object>::MoveNext() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR bool Enumerator_MoveNext_m2E56233762839CE55C67E00AC8DD3D4D3F6C0DF0_gshared (Enumerator_tB6009981BD4E3881E3EC83627255A24198F902D6 * __this, const RuntimeMethod* method); // System.Void System.Collections.Generic.List`1/Enumerator<System.Object>::Dispose() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void Enumerator_Dispose_mCFB225D9E5E597A1CC8F958E53BEA1367D8AC7B8_gshared (Enumerator_tB6009981BD4E3881E3EC83627255A24198F902D6 * __this, const RuntimeMethod* method); // System.Void System.Collections.Generic.List`1<System.Object>::Clear() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void List_1_Clear_m5FB5A9C59D8625FDFB06876C4D8848F0F07ABFD0_gshared (List_1_t3F94120C77410A62EAE48421CF166B83AB95A2F5 * __this, const RuntimeMethod* method); // System.Void UnityEngine.SubsystemsImplementation.SubsystemDescriptorStore::RegisterDescriptor<System.Object,System.Object>(TDescriptor,System.Collections.Generic.List`1<TBaseTypeInList>) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void SubsystemDescriptorStore_RegisterDescriptor_TisRuntimeObject_TisRuntimeObject_mAB56DC82E916F116B981E0849B9B474384B36376_gshared (RuntimeObject * ___descriptor0, List_1_t3F94120C77410A62EAE48421CF166B83AB95A2F5 * ___storeInList1, const RuntimeMethod* method); // System.Void System.Collections.Generic.List`1<System.Object>::.ctor() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void List_1__ctor_m0F0E00088CF56FEACC9E32D8B7D91B93D91DAA3B_gshared (List_1_t3F94120C77410A62EAE48421CF166B83AB95A2F5 * __this, const RuntimeMethod* method); // System.Void System.Object::.ctor() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void Object__ctor_m88880E0413421D13FD95325EDCE231707CE1F405 (RuntimeObject * __this, const RuntimeMethod* method); // System.String UnityEngine.SubsystemDescriptorBindings::GetId(System.IntPtr) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR String_t* SubsystemDescriptorBindings_GetId_mDEF8D961120A68B1B81C6E3F802CB6C9E8116698 (intptr_t ___descriptorPtr0, const RuntimeMethod* method); // System.Void UnityEngine.SubsystemsImplementation.SubsystemDescriptorStore::RegisterDeprecatedDescriptor(UnityEngine.SubsystemDescriptor) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void SubsystemDescriptorStore_RegisterDeprecatedDescriptor_m9AD18069E5C5168A36E15F2E6C3EB3050AAC5C57 (SubsystemDescriptor_tF663011CB44AB1D342821BBEF7B6811E799A7245 * ___descriptor0, const RuntimeMethod* method); // System.Void System.Collections.Generic.List`1<UnityEngine.IntegratedSubsystemDescriptor>::Add(!0) inline void List_1_Add_m5E7B6700296FDF9A86831BA41AB8D5974BC98EBF (List_1_t13B7F19BE124BF950C29583D073B7D2174DCA122 * __this, IntegratedSubsystemDescriptor_tDC8AF8E5B67B983E4492D784A419F01693926D7A * ___item0, const RuntimeMethod* method) { (( void (*) (List_1_t13B7F19BE124BF950C29583D073B7D2174DCA122 *, IntegratedSubsystemDescriptor_tDC8AF8E5B67B983E4492D784A419F01693926D7A *, const RuntimeMethod*))List_1_Add_mE5B3CBB3A625606D9BC4337FEAAF1D66BCB6F96E_gshared)(__this, ___item0, method); } // System.Collections.Generic.List`1/Enumerator<!0> System.Collections.Generic.List`1<UnityEngine.IntegratedSubsystemDescriptor>::GetEnumerator() inline Enumerator_t743A52D99B71AF8E5AB3809E59FF43C7108E85D9 List_1_GetEnumerator_mCB28B8715FD5729AB10F27E74B5DCA1EDB12DBF2 (List_1_t13B7F19BE124BF950C29583D073B7D2174DCA122 * __this, const RuntimeMethod* method) { return (( Enumerator_t743A52D99B71AF8E5AB3809E59FF43C7108E85D9 (*) (List_1_t13B7F19BE124BF950C29583D073B7D2174DCA122 *, const RuntimeMethod*))List_1_GetEnumerator_m1739A5E25DF502A6984F9B98CFCAC2D3FABCF233_gshared)(__this, method); } // !0 System.Collections.Generic.List`1/Enumerator<UnityEngine.IntegratedSubsystemDescriptor>::get_Current() inline IntegratedSubsystemDescriptor_tDC8AF8E5B67B983E4492D784A419F01693926D7A * Enumerator_get_Current_mD5DC4E82EC765AC61BFA8600AB8C1D92014F12AB_inline (Enumerator_t743A52D99B71AF8E5AB3809E59FF43C7108E85D9 * __this, const RuntimeMethod* method) { return (( IntegratedSubsystemDescriptor_tDC8AF8E5B67B983E4492D784A419F01693926D7A * (*) (Enumerator_t743A52D99B71AF8E5AB3809E59FF43C7108E85D9 *, const RuntimeMethod*))Enumerator_get_Current_m9C4EBBD2108B51885E750F927D7936290C8E20EE_gshared_inline)(__this, method); } // System.Boolean System.Collections.Generic.List`1/Enumerator<UnityEngine.IntegratedSubsystemDescriptor>::MoveNext() inline bool Enumerator_MoveNext_m0F18497A43DA01DEAB0F3019B04B284D42A5BC02 (Enumerator_t743A52D99B71AF8E5AB3809E59FF43C7108E85D9 * __this, const RuntimeMethod* method) { return (( bool (*) (Enumerator_t743A52D99B71AF8E5AB3809E59FF43C7108E85D9 *, const RuntimeMethod*))Enumerator_MoveNext_m2E56233762839CE55C67E00AC8DD3D4D3F6C0DF0_gshared)(__this, method); } // System.Void System.Collections.Generic.List`1/Enumerator<UnityEngine.IntegratedSubsystemDescriptor>::Dispose() inline void Enumerator_Dispose_m235C7DA3DE890C01AC2BDBF3700F46D8D9F70205 (Enumerator_t743A52D99B71AF8E5AB3809E59FF43C7108E85D9 * __this, const RuntimeMethod* method) { (( void (*) (Enumerator_t743A52D99B71AF8E5AB3809E59FF43C7108E85D9 *, const RuntimeMethod*))Enumerator_Dispose_mCFB225D9E5E597A1CC8F958E53BEA1367D8AC7B8_gshared)(__this, method); } // System.Void System.Collections.Generic.List`1<UnityEngine.IntegratedSubsystemDescriptor>::Clear() inline void List_1_Clear_mF2DE990480F55E83ED1A30803FCA939DAC4295FB (List_1_t13B7F19BE124BF950C29583D073B7D2174DCA122 * __this, const RuntimeMethod* method) { (( void (*) (List_1_t13B7F19BE124BF950C29583D073B7D2174DCA122 *, const RuntimeMethod*))List_1_Clear_m5FB5A9C59D8625FDFB06876C4D8848F0F07ABFD0_gshared)(__this, method); } // System.Void UnityEngine.SubsystemsImplementation.SubsystemDescriptorStore::RegisterDescriptor<UnityEngine.SubsystemDescriptor,UnityEngine.SubsystemDescriptor>(TDescriptor,System.Collections.Generic.List`1<TBaseTypeInList>) inline void SubsystemDescriptorStore_RegisterDescriptor_TisSubsystemDescriptor_tF663011CB44AB1D342821BBEF7B6811E799A7245_TisSubsystemDescriptor_tF663011CB44AB1D342821BBEF7B6811E799A7245_mA2A113AA1886D1110BD5C6506B4EDFD8E4BFE230 (SubsystemDescriptor_tF663011CB44AB1D342821BBEF7B6811E799A7245 * ___descriptor0, List_1_t32E50BD66297C6541AEA401E1C13D4EC530CC56B * ___storeInList1, const RuntimeMethod* method) { (( void (*) (SubsystemDescriptor_tF663011CB44AB1D342821BBEF7B6811E799A7245 *, List_1_t32E50BD66297C6541AEA401E1C13D4EC530CC56B *, const RuntimeMethod*))SubsystemDescriptorStore_RegisterDescriptor_TisRuntimeObject_TisRuntimeObject_mAB56DC82E916F116B981E0849B9B474384B36376_gshared)(___descriptor0, ___storeInList1, method); } // System.Void System.Collections.Generic.List`1<UnityEngine.IntegratedSubsystemDescriptor>::.ctor() inline void List_1__ctor_m1BE065BC3C4D6B70B245126E58C7DAFC7460A597 (List_1_t13B7F19BE124BF950C29583D073B7D2174DCA122 * __this, const RuntimeMethod* method) { (( void (*) (List_1_t13B7F19BE124BF950C29583D073B7D2174DCA122 *, const RuntimeMethod*))List_1__ctor_m0F0E00088CF56FEACC9E32D8B7D91B93D91DAA3B_gshared)(__this, method); } // System.Void System.Collections.Generic.List`1<UnityEngine.SubsystemsImplementation.SubsystemDescriptorWithProvider>::.ctor() inline void List_1__ctor_m64996A7345F49B6600D4FD19B96FA0D4DBADBDC5 (List_1_t4DCA5C48F3390AC8CD79C7AD8D0963D5DAE5CF2E * __this, const RuntimeMethod* method) { (( void (*) (List_1_t4DCA5C48F3390AC8CD79C7AD8D0963D5DAE5CF2E *, const RuntimeMethod*))List_1__ctor_m0F0E00088CF56FEACC9E32D8B7D91B93D91DAA3B_gshared)(__this, method); } // System.Void System.Collections.Generic.List`1<UnityEngine.SubsystemDescriptor>::.ctor() inline void List_1__ctor_m68FA0963B0052EA071AC894D7ACFF63E1477ED83 (List_1_t32E50BD66297C6541AEA401E1C13D4EC530CC56B * __this, const RuntimeMethod* method) { (( void (*) (List_1_t32E50BD66297C6541AEA401E1C13D4EC530CC56B *, const RuntimeMethod*))List_1__ctor_m0F0E00088CF56FEACC9E32D8B7D91B93D91DAA3B_gshared)(__this, method); } // System.Void System.Action::Invoke() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void Action_Invoke_m3FFA5BE3D64F0FF8E1E1CB6F953913FADB5EB89E (Action_tAF41423D285AE0862865348CF6CE51CD085ABBA6 * __this, const RuntimeMethod* method); // System.Void UnityEngine.IntegratedSubsystem::SetHandle(UnityEngine.IntegratedSubsystem) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void IntegratedSubsystem_SetHandle_m951ABC336E4544AAD792A7118E2261AC8F2A297E (IntegratedSubsystem_t8FB3A371F812CF9521903AC016C64E95C7412002 * __this, IntegratedSubsystem_t8FB3A371F812CF9521903AC016C64E95C7412002 * ___subsystem0, const RuntimeMethod* method); // System.Void System.Collections.Generic.List`1<UnityEngine.IntegratedSubsystem>::Add(!0) inline void List_1_Add_m54714E32B888D33E0D24E8AF9B2C0BE61334C065 (List_1_t2DAF7481782912A6F8E6180AC19B83A5EEFEE9EF * __this, IntegratedSubsystem_t8FB3A371F812CF9521903AC016C64E95C7412002 * ___item0, const RuntimeMethod* method) { (( void (*) (List_1_t2DAF7481782912A6F8E6180AC19B83A5EEFEE9EF *, IntegratedSubsystem_t8FB3A371F812CF9521903AC016C64E95C7412002 *, const RuntimeMethod*))List_1_Add_mE5B3CBB3A625606D9BC4337FEAAF1D66BCB6F96E_gshared)(__this, ___item0, method); } // System.Collections.Generic.List`1/Enumerator<!0> System.Collections.Generic.List`1<UnityEngine.IntegratedSubsystem>::GetEnumerator() inline Enumerator_tCF86CE3FF03B86F9FF1AB5746DF9DEE36DCAD59D List_1_GetEnumerator_m0593C6B2A3413655213A5E61FB90E1927DDEAE20 (List_1_t2DAF7481782912A6F8E6180AC19B83A5EEFEE9EF * __this, const RuntimeMethod* method) { return (( Enumerator_tCF86CE3FF03B86F9FF1AB5746DF9DEE36DCAD59D (*) (List_1_t2DAF7481782912A6F8E6180AC19B83A5EEFEE9EF *, const RuntimeMethod*))List_1_GetEnumerator_m1739A5E25DF502A6984F9B98CFCAC2D3FABCF233_gshared)(__this, method); } // !0 System.Collections.Generic.List`1/Enumerator<UnityEngine.IntegratedSubsystem>::get_Current() inline IntegratedSubsystem_t8FB3A371F812CF9521903AC016C64E95C7412002 * Enumerator_get_Current_mA9ED75A7F28667B3CA286C561A8983A6355CB28C_inline (Enumerator_tCF86CE3FF03B86F9FF1AB5746DF9DEE36DCAD59D * __this, const RuntimeMethod* method) { return (( IntegratedSubsystem_t8FB3A371F812CF9521903AC016C64E95C7412002 * (*) (Enumerator_tCF86CE3FF03B86F9FF1AB5746DF9DEE36DCAD59D *, const RuntimeMethod*))Enumerator_get_Current_m9C4EBBD2108B51885E750F927D7936290C8E20EE_gshared_inline)(__this, method); } // System.Boolean System.Collections.Generic.List`1/Enumerator<UnityEngine.IntegratedSubsystem>::MoveNext() inline bool Enumerator_MoveNext_mC10CBAADB9DFA0A091393D78B464F2AB2617750D (Enumerator_tCF86CE3FF03B86F9FF1AB5746DF9DEE36DCAD59D * __this, const RuntimeMethod* method) { return (( bool (*) (Enumerator_tCF86CE3FF03B86F9FF1AB5746DF9DEE36DCAD59D *, const RuntimeMethod*))Enumerator_MoveNext_m2E56233762839CE55C67E00AC8DD3D4D3F6C0DF0_gshared)(__this, method); } // System.Void System.Collections.Generic.List`1/Enumerator<UnityEngine.IntegratedSubsystem>::Dispose() inline void Enumerator_Dispose_m2422FBD5B59F54B43DEF2796536DBDFBE7B27B17 (Enumerator_tCF86CE3FF03B86F9FF1AB5746DF9DEE36DCAD59D * __this, const RuntimeMethod* method) { (( void (*) (Enumerator_tCF86CE3FF03B86F9FF1AB5746DF9DEE36DCAD59D *, const RuntimeMethod*))Enumerator_Dispose_mCFB225D9E5E597A1CC8F958E53BEA1367D8AC7B8_gshared)(__this, method); } // System.Void System.Collections.Generic.List`1<UnityEngine.IntegratedSubsystem>::Clear() inline void List_1_Clear_m2D220FFB24BAB221D99A0CA9543AFE6DF8D155B6 (List_1_t2DAF7481782912A6F8E6180AC19B83A5EEFEE9EF * __this, const RuntimeMethod* method) { (( void (*) (List_1_t2DAF7481782912A6F8E6180AC19B83A5EEFEE9EF *, const RuntimeMethod*))List_1_Clear_m5FB5A9C59D8625FDFB06876C4D8848F0F07ABFD0_gshared)(__this, method); } // System.Void System.Collections.Generic.List`1<UnityEngine.SubsystemsImplementation.SubsystemWithProvider>::Clear() inline void List_1_Clear_mA624B195E1AC838905EB58332EE3BAAF99A9D2CA (List_1_t6E613DAFFAFE896B759F1C5260D6234F04C9DD41 * __this, const RuntimeMethod* method) { (( void (*) (List_1_t6E613DAFFAFE896B759F1C5260D6234F04C9DD41 *, const RuntimeMethod*))List_1_Clear_m5FB5A9C59D8625FDFB06876C4D8848F0F07ABFD0_gshared)(__this, method); } // System.Void System.Collections.Generic.List`1<UnityEngine.Subsystem>::Clear() inline void List_1_Clear_mEE68874407E18C9127133CC13AEEA9F5A4BD8392 (List_1_t58BB84B47855540E6D2640B387506E01436DCF82 * __this, const RuntimeMethod* method) { (( void (*) (List_1_t58BB84B47855540E6D2640B387506E01436DCF82 *, const RuntimeMethod*))List_1_Clear_m5FB5A9C59D8625FDFB06876C4D8848F0F07ABFD0_gshared)(__this, method); } // System.Void System.Collections.Generic.List`1<UnityEngine.IntegratedSubsystem>::.ctor() inline void List_1__ctor_mAB9CAE208C61BBAF2266DA3CB6EF7DE1F16BF08C (List_1_t2DAF7481782912A6F8E6180AC19B83A5EEFEE9EF * __this, const RuntimeMethod* method) { (( void (*) (List_1_t2DAF7481782912A6F8E6180AC19B83A5EEFEE9EF *, const RuntimeMethod*))List_1__ctor_m0F0E00088CF56FEACC9E32D8B7D91B93D91DAA3B_gshared)(__this, method); } // System.Void System.Collections.Generic.List`1<UnityEngine.SubsystemsImplementation.SubsystemWithProvider>::.ctor() inline void List_1__ctor_mB5053799863D389932A9DE8C00C290CBE78E176D (List_1_t6E613DAFFAFE896B759F1C5260D6234F04C9DD41 * __this, const RuntimeMethod* method) { (( void (*) (List_1_t6E613DAFFAFE896B759F1C5260D6234F04C9DD41 *, const RuntimeMethod*))List_1__ctor_m0F0E00088CF56FEACC9E32D8B7D91B93D91DAA3B_gshared)(__this, method); } // System.Void System.Collections.Generic.List`1<UnityEngine.Subsystem>::.ctor() inline void List_1__ctor_m880D76E786031830863F68A2C4F0B7DF425666E5 (List_1_t58BB84B47855540E6D2640B387506E01436DCF82 * __this, const RuntimeMethod* method) { (( void (*) (List_1_t58BB84B47855540E6D2640B387506E01436DCF82 *, const RuntimeMethod*))List_1__ctor_m0F0E00088CF56FEACC9E32D8B7D91B93D91DAA3B_gshared)(__this, method); } // System.Void UnityEngine.SubsystemManager::StaticConstructScriptingClassMap() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void SubsystemManager_StaticConstructScriptingClassMap_m2D54CD8E480B334F4EC0EAAF49DE4186895885EE (const RuntimeMethod* method); // System.Boolean System.IntPtr::op_Equality(System.IntPtr,System.IntPtr) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR bool IntPtr_op_Equality_mD94F3FE43A65684EFF984A7B95E70D2520C0AC73 (intptr_t ___value10, intptr_t ___value21, const RuntimeMethod* method); #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif #ifdef __clang__ #pragma clang diagnostic pop #endif #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // Conversion methods for marshalling of: UnityEngine.IntegratedSubsystem IL2CPP_EXTERN_C void IntegratedSubsystem_t8FB3A371F812CF9521903AC016C64E95C7412002_marshal_pinvoke(const IntegratedSubsystem_t8FB3A371F812CF9521903AC016C64E95C7412002& unmarshaled, IntegratedSubsystem_t8FB3A371F812CF9521903AC016C64E95C7412002_marshaled_pinvoke& marshaled) { Exception_t* ___m_SubsystemDescriptor_1Exception = il2cpp_codegen_get_marshal_directive_exception("Cannot marshal field 'm_SubsystemDescriptor' of type 'IntegratedSubsystem': Reference type field marshaling is not supported."); IL2CPP_RAISE_MANAGED_EXCEPTION(___m_SubsystemDescriptor_1Exception, NULL); } IL2CPP_EXTERN_C void IntegratedSubsystem_t8FB3A371F812CF9521903AC016C64E95C7412002_marshal_pinvoke_back(const IntegratedSubsystem_t8FB3A371F812CF9521903AC016C64E95C7412002_marshaled_pinvoke& marshaled, IntegratedSubsystem_t8FB3A371F812CF9521903AC016C64E95C7412002& unmarshaled) { Exception_t* ___m_SubsystemDescriptor_1Exception = il2cpp_codegen_get_marshal_directive_exception("Cannot marshal field 'm_SubsystemDescriptor' of type 'IntegratedSubsystem': Reference type field marshaling is not supported."); IL2CPP_RAISE_MANAGED_EXCEPTION(___m_SubsystemDescriptor_1Exception, NULL); } // Conversion method for clean up from marshalling of: UnityEngine.IntegratedSubsystem IL2CPP_EXTERN_C void IntegratedSubsystem_t8FB3A371F812CF9521903AC016C64E95C7412002_marshal_pinvoke_cleanup(IntegratedSubsystem_t8FB3A371F812CF9521903AC016C64E95C7412002_marshaled_pinvoke& marshaled) { } // Conversion methods for marshalling of: UnityEngine.IntegratedSubsystem IL2CPP_EXTERN_C void IntegratedSubsystem_t8FB3A371F812CF9521903AC016C64E95C7412002_marshal_com(const IntegratedSubsystem_t8FB3A371F812CF9521903AC016C64E95C7412002& unmarshaled, IntegratedSubsystem_t8FB3A371F812CF9521903AC016C64E95C7412002_marshaled_com& marshaled) { Exception_t* ___m_SubsystemDescriptor_1Exception = il2cpp_codegen_get_marshal_directive_exception("Cannot marshal field 'm_SubsystemDescriptor' of type 'IntegratedSubsystem': Reference type field marshaling is not supported."); IL2CPP_RAISE_MANAGED_EXCEPTION(___m_SubsystemDescriptor_1Exception, NULL); } IL2CPP_EXTERN_C void IntegratedSubsystem_t8FB3A371F812CF9521903AC016C64E95C7412002_marshal_com_back(const IntegratedSubsystem_t8FB3A371F812CF9521903AC016C64E95C7412002_marshaled_com& marshaled, IntegratedSubsystem_t8FB3A371F812CF9521903AC016C64E95C7412002& unmarshaled) { Exception_t* ___m_SubsystemDescriptor_1Exception = il2cpp_codegen_get_marshal_directive_exception("Cannot marshal field 'm_SubsystemDescriptor' of type 'IntegratedSubsystem': Reference type field marshaling is not supported."); IL2CPP_RAISE_MANAGED_EXCEPTION(___m_SubsystemDescriptor_1Exception, NULL); } // Conversion method for clean up from marshalling of: UnityEngine.IntegratedSubsystem IL2CPP_EXTERN_C void IntegratedSubsystem_t8FB3A371F812CF9521903AC016C64E95C7412002_marshal_com_cleanup(IntegratedSubsystem_t8FB3A371F812CF9521903AC016C64E95C7412002_marshaled_com& marshaled) { } // System.Void UnityEngine.IntegratedSubsystem::SetHandle(UnityEngine.IntegratedSubsystem) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void IntegratedSubsystem_SetHandle_m951ABC336E4544AAD792A7118E2261AC8F2A297E (IntegratedSubsystem_t8FB3A371F812CF9521903AC016C64E95C7412002 * __this, IntegratedSubsystem_t8FB3A371F812CF9521903AC016C64E95C7412002 * ___subsystem0, const RuntimeMethod* method) { typedef void (*IntegratedSubsystem_SetHandle_m951ABC336E4544AAD792A7118E2261AC8F2A297E_ftn) (IntegratedSubsystem_t8FB3A371F812CF9521903AC016C64E95C7412002 *, IntegratedSubsystem_t8FB3A371F812CF9521903AC016C64E95C7412002 *); static IntegratedSubsystem_SetHandle_m951ABC336E4544AAD792A7118E2261AC8F2A297E_ftn _il2cpp_icall_func; if (!_il2cpp_icall_func) _il2cpp_icall_func = (IntegratedSubsystem_SetHandle_m951ABC336E4544AAD792A7118E2261AC8F2A297E_ftn)il2cpp_codegen_resolve_icall ("UnityEngine.IntegratedSubsystem::SetHandle(UnityEngine.IntegratedSubsystem)"); _il2cpp_icall_func(__this, ___subsystem0); } // System.Void UnityEngine.IntegratedSubsystem::.ctor() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void IntegratedSubsystem__ctor_mCD638F6C367F1B83B1CB62130E570CA64A757DCE (IntegratedSubsystem_t8FB3A371F812CF9521903AC016C64E95C7412002 * __this, const RuntimeMethod* method) { { Object__ctor_m88880E0413421D13FD95325EDCE231707CE1F405(__this, /*hidden argument*/NULL); return; } } #ifdef __clang__ #pragma clang diagnostic pop #endif #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // Conversion methods for marshalling of: UnityEngine.IntegratedSubsystemDescriptor IL2CPP_EXTERN_C void IntegratedSubsystemDescriptor_tDC8AF8E5B67B983E4492D784A419F01693926D7A_marshal_pinvoke(const IntegratedSubsystemDescriptor_tDC8AF8E5B67B983E4492D784A419F01693926D7A& unmarshaled, IntegratedSubsystemDescriptor_tDC8AF8E5B67B983E4492D784A419F01693926D7A_marshaled_pinvoke& marshaled) { marshaled.___m_Ptr_0 = unmarshaled.get_m_Ptr_0(); } IL2CPP_EXTERN_C void IntegratedSubsystemDescriptor_tDC8AF8E5B67B983E4492D784A419F01693926D7A_marshal_pinvoke_back(const IntegratedSubsystemDescriptor_tDC8AF8E5B67B983E4492D784A419F01693926D7A_marshaled_pinvoke& marshaled, IntegratedSubsystemDescriptor_tDC8AF8E5B67B983E4492D784A419F01693926D7A& unmarshaled) { intptr_t unmarshaled_m_Ptr_temp_0; memset((&unmarshaled_m_Ptr_temp_0), 0, sizeof(unmarshaled_m_Ptr_temp_0)); unmarshaled_m_Ptr_temp_0 = marshaled.___m_Ptr_0; unmarshaled.set_m_Ptr_0(unmarshaled_m_Ptr_temp_0); } // Conversion method for clean up from marshalling of: UnityEngine.IntegratedSubsystemDescriptor IL2CPP_EXTERN_C void IntegratedSubsystemDescriptor_tDC8AF8E5B67B983E4492D784A419F01693926D7A_marshal_pinvoke_cleanup(IntegratedSubsystemDescriptor_tDC8AF8E5B67B983E4492D784A419F01693926D7A_marshaled_pinvoke& marshaled) { } // Conversion methods for marshalling of: UnityEngine.IntegratedSubsystemDescriptor IL2CPP_EXTERN_C void IntegratedSubsystemDescriptor_tDC8AF8E5B67B983E4492D784A419F01693926D7A_marshal_com(const IntegratedSubsystemDescriptor_tDC8AF8E5B67B983E4492D784A419F01693926D7A& unmarshaled, IntegratedSubsystemDescriptor_tDC8AF8E5B67B983E4492D784A419F01693926D7A_marshaled_com& marshaled) { marshaled.___m_Ptr_0 = unmarshaled.get_m_Ptr_0(); } IL2CPP_EXTERN_C void IntegratedSubsystemDescriptor_tDC8AF8E5B67B983E4492D784A419F01693926D7A_marshal_com_back(const IntegratedSubsystemDescriptor_tDC8AF8E5B67B983E4492D784A419F01693926D7A_marshaled_com& marshaled, IntegratedSubsystemDescriptor_tDC8AF8E5B67B983E4492D784A419F01693926D7A& unmarshaled) { intptr_t unmarshaled_m_Ptr_temp_0; memset((&unmarshaled_m_Ptr_temp_0), 0, sizeof(unmarshaled_m_Ptr_temp_0)); unmarshaled_m_Ptr_temp_0 = marshaled.___m_Ptr_0; unmarshaled.set_m_Ptr_0(unmarshaled_m_Ptr_temp_0); } // Conversion method for clean up from marshalling of: UnityEngine.IntegratedSubsystemDescriptor IL2CPP_EXTERN_C void IntegratedSubsystemDescriptor_tDC8AF8E5B67B983E4492D784A419F01693926D7A_marshal_com_cleanup(IntegratedSubsystemDescriptor_tDC8AF8E5B67B983E4492D784A419F01693926D7A_marshaled_com& marshaled) { } // System.String UnityEngine.IntegratedSubsystemDescriptor::get_id() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR String_t* IntegratedSubsystemDescriptor_get_id_m0347A7AE998F0210CC7DAD1DA974F788AB2CF879 (IntegratedSubsystemDescriptor_tDC8AF8E5B67B983E4492D784A419F01693926D7A * __this, const RuntimeMethod* method) { { intptr_t L_0 = __this->get_m_Ptr_0(); String_t* L_1; L_1 = SubsystemDescriptorBindings_GetId_mDEF8D961120A68B1B81C6E3F802CB6C9E8116698((intptr_t)L_0, /*hidden argument*/NULL); return L_1; } } // System.Void UnityEngine.IntegratedSubsystemDescriptor::.ctor() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void IntegratedSubsystemDescriptor__ctor_m06A2C2DB3D3004DFAC7344C2B8FDEF89434CBF3A (IntegratedSubsystemDescriptor_tDC8AF8E5B67B983E4492D784A419F01693926D7A * __this, const RuntimeMethod* method) { { Object__ctor_m88880E0413421D13FD95325EDCE231707CE1F405(__this, /*hidden argument*/NULL); return; } } #ifdef __clang__ #pragma clang diagnostic pop #endif #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Void UnityEngine.Internal_SubsystemDescriptors::Internal_AddDescriptor(UnityEngine.SubsystemDescriptor) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void Internal_SubsystemDescriptors_Internal_AddDescriptor_mB9FD6DBE105FA735294E48F0DE9AA1382AA74F77 (SubsystemDescriptor_tF663011CB44AB1D342821BBEF7B6811E799A7245 * ___descriptor0, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&SubsystemDescriptorStore_tE5D99C3159868DE6506269CB6B830621F8BC31A6_il2cpp_TypeInfo_var); s_Il2CppMethodInitialized = true; } { SubsystemDescriptor_tF663011CB44AB1D342821BBEF7B6811E799A7245 * L_0 = ___descriptor0; IL2CPP_RUNTIME_CLASS_INIT(SubsystemDescriptorStore_tE5D99C3159868DE6506269CB6B830621F8BC31A6_il2cpp_TypeInfo_var); SubsystemDescriptorStore_RegisterDeprecatedDescriptor_m9AD18069E5C5168A36E15F2E6C3EB3050AAC5C57(L_0, /*hidden argument*/NULL); return; } } #ifdef __clang__ #pragma clang diagnostic pop #endif #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Void UnityEngine.Subsystem::.ctor() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void Subsystem__ctor_mC6AFF077E6D2BDFB272AFC1EA25D1375EC64EF77 (Subsystem_t2D97454A946149D608974CB6B674F5F5C613A6A4 * __this, const RuntimeMethod* method) { { Object__ctor_m88880E0413421D13FD95325EDCE231707CE1F405(__this, /*hidden argument*/NULL); return; } } #ifdef __clang__ #pragma clang diagnostic pop #endif #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.String UnityEngine.SubsystemDescriptor::get_id() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR String_t* SubsystemDescriptor_get_id_mC3D7972588D4B57F906A06CEE54A61B55D1306DB (SubsystemDescriptor_tF663011CB44AB1D342821BBEF7B6811E799A7245 * __this, const RuntimeMethod* method) { { String_t* L_0 = __this->get_U3CidU3Ek__BackingField_0(); return L_0; } } // System.Void UnityEngine.SubsystemDescriptor::.ctor() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void SubsystemDescriptor__ctor_m6BE761B6ADD71B136BCECB0F54B82801B7222114 (SubsystemDescriptor_tF663011CB44AB1D342821BBEF7B6811E799A7245 * __this, const RuntimeMethod* method) { { Object__ctor_m88880E0413421D13FD95325EDCE231707CE1F405(__this, /*hidden argument*/NULL); return; } } #ifdef __clang__ #pragma clang diagnostic pop #endif #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.String UnityEngine.SubsystemDescriptorBindings::GetId(System.IntPtr) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR String_t* SubsystemDescriptorBindings_GetId_mDEF8D961120A68B1B81C6E3F802CB6C9E8116698 (intptr_t ___descriptorPtr0, const RuntimeMethod* method) { typedef String_t* (*SubsystemDescriptorBindings_GetId_mDEF8D961120A68B1B81C6E3F802CB6C9E8116698_ftn) (intptr_t); static SubsystemDescriptorBindings_GetId_mDEF8D961120A68B1B81C6E3F802CB6C9E8116698_ftn _il2cpp_icall_func; if (!_il2cpp_icall_func) _il2cpp_icall_func = (SubsystemDescriptorBindings_GetId_mDEF8D961120A68B1B81C6E3F802CB6C9E8116698_ftn)il2cpp_codegen_resolve_icall ("UnityEngine.SubsystemDescriptorBindings::GetId(System.IntPtr)"); String_t* icallRetVal = _il2cpp_icall_func(___descriptorPtr0); return icallRetVal; } #ifdef __clang__ #pragma clang diagnostic pop #endif #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Void UnityEngine.SubsystemsImplementation.SubsystemDescriptorStore::InitializeManagedDescriptor(System.IntPtr,UnityEngine.IntegratedSubsystemDescriptor) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void SubsystemDescriptorStore_InitializeManagedDescriptor_mE61A5D7DF72A574A47CFCEF088FE87D28CFBD149 (intptr_t ___ptr0, IntegratedSubsystemDescriptor_tDC8AF8E5B67B983E4492D784A419F01693926D7A * ___desc1, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&List_1_Add_m5E7B6700296FDF9A86831BA41AB8D5974BC98EBF_RuntimeMethod_var); il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&SubsystemDescriptorStore_tE5D99C3159868DE6506269CB6B830621F8BC31A6_il2cpp_TypeInfo_var); s_Il2CppMethodInitialized = true; } { IntegratedSubsystemDescriptor_tDC8AF8E5B67B983E4492D784A419F01693926D7A * L_0 = ___desc1; intptr_t L_1 = ___ptr0; NullCheck(L_0); L_0->set_m_Ptr_0((intptr_t)L_1); IL2CPP_RUNTIME_CLASS_INIT(SubsystemDescriptorStore_tE5D99C3159868DE6506269CB6B830621F8BC31A6_il2cpp_TypeInfo_var); List_1_t13B7F19BE124BF950C29583D073B7D2174DCA122 * L_2 = ((SubsystemDescriptorStore_tE5D99C3159868DE6506269CB6B830621F8BC31A6_StaticFields*)il2cpp_codegen_static_fields_for(SubsystemDescriptorStore_tE5D99C3159868DE6506269CB6B830621F8BC31A6_il2cpp_TypeInfo_var))->get_s_IntegratedDescriptors_0(); IntegratedSubsystemDescriptor_tDC8AF8E5B67B983E4492D784A419F01693926D7A * L_3 = ___desc1; NullCheck(L_2); List_1_Add_m5E7B6700296FDF9A86831BA41AB8D5974BC98EBF(L_2, L_3, /*hidden argument*/List_1_Add_m5E7B6700296FDF9A86831BA41AB8D5974BC98EBF_RuntimeMethod_var); return; } } // System.Void UnityEngine.SubsystemsImplementation.SubsystemDescriptorStore::ClearManagedDescriptors() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void SubsystemDescriptorStore_ClearManagedDescriptors_mF6942653535F926FEED695280935CCF7D5AF1A69 (const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&Enumerator_Dispose_m235C7DA3DE890C01AC2BDBF3700F46D8D9F70205_RuntimeMethod_var); il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&Enumerator_MoveNext_m0F18497A43DA01DEAB0F3019B04B284D42A5BC02_RuntimeMethod_var); il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&Enumerator_get_Current_mD5DC4E82EC765AC61BFA8600AB8C1D92014F12AB_RuntimeMethod_var); il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&IntPtr_t_il2cpp_TypeInfo_var); il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&List_1_Clear_mF2DE990480F55E83ED1A30803FCA939DAC4295FB_RuntimeMethod_var); il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&List_1_GetEnumerator_mCB28B8715FD5729AB10F27E74B5DCA1EDB12DBF2_RuntimeMethod_var); il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&SubsystemDescriptorStore_tE5D99C3159868DE6506269CB6B830621F8BC31A6_il2cpp_TypeInfo_var); s_Il2CppMethodInitialized = true; } Enumerator_t743A52D99B71AF8E5AB3809E59FF43C7108E85D9 V_0; memset((&V_0), 0, sizeof(V_0)); IntegratedSubsystemDescriptor_tDC8AF8E5B67B983E4492D784A419F01693926D7A * V_1 = NULL; Exception_t * __last_unhandled_exception = 0; il2cpp::utils::ExceptionSupportStack<int32_t, 1> __leave_targets; { IL2CPP_RUNTIME_CLASS_INIT(SubsystemDescriptorStore_tE5D99C3159868DE6506269CB6B830621F8BC31A6_il2cpp_TypeInfo_var); List_1_t13B7F19BE124BF950C29583D073B7D2174DCA122 * L_0 = ((SubsystemDescriptorStore_tE5D99C3159868DE6506269CB6B830621F8BC31A6_StaticFields*)il2cpp_codegen_static_fields_for(SubsystemDescriptorStore_tE5D99C3159868DE6506269CB6B830621F8BC31A6_il2cpp_TypeInfo_var))->get_s_IntegratedDescriptors_0(); NullCheck(L_0); Enumerator_t743A52D99B71AF8E5AB3809E59FF43C7108E85D9 L_1; L_1 = List_1_GetEnumerator_mCB28B8715FD5729AB10F27E74B5DCA1EDB12DBF2(L_0, /*hidden argument*/List_1_GetEnumerator_mCB28B8715FD5729AB10F27E74B5DCA1EDB12DBF2_RuntimeMethod_var); V_0 = L_1; } IL_000d: try { // begin try (depth: 1) { goto IL_0022; } IL_000f: { IntegratedSubsystemDescriptor_tDC8AF8E5B67B983E4492D784A419F01693926D7A * L_2; L_2 = Enumerator_get_Current_mD5DC4E82EC765AC61BFA8600AB8C1D92014F12AB_inline((Enumerator_t743A52D99B71AF8E5AB3809E59FF43C7108E85D9 *)(&V_0), /*hidden argument*/Enumerator_get_Current_mD5DC4E82EC765AC61BFA8600AB8C1D92014F12AB_RuntimeMethod_var); V_1 = L_2; IntegratedSubsystemDescriptor_tDC8AF8E5B67B983E4492D784A419F01693926D7A * L_3 = V_1; NullCheck(L_3); L_3->set_m_Ptr_0((intptr_t)(0)); } IL_0022: { bool L_4; L_4 = Enumerator_MoveNext_m0F18497A43DA01DEAB0F3019B04B284D42A5BC02((Enumerator_t743A52D99B71AF8E5AB3809E59FF43C7108E85D9 *)(&V_0), /*hidden argument*/Enumerator_MoveNext_m0F18497A43DA01DEAB0F3019B04B284D42A5BC02_RuntimeMethod_var); if (L_4) { goto IL_000f; } } IL_002b: { IL2CPP_LEAVE(0x3C, FINALLY_002d); } } // end try (depth: 1) catch(Il2CppExceptionWrapper& e) { __last_unhandled_exception = (Exception_t *)e.ex; goto FINALLY_002d; } FINALLY_002d: { // begin finally (depth: 1) Enumerator_Dispose_m235C7DA3DE890C01AC2BDBF3700F46D8D9F70205((Enumerator_t743A52D99B71AF8E5AB3809E59FF43C7108E85D9 *)(&V_0), /*hidden argument*/Enumerator_Dispose_m235C7DA3DE890C01AC2BDBF3700F46D8D9F70205_RuntimeMethod_var); IL2CPP_END_FINALLY(45) } // end finally (depth: 1) IL2CPP_CLEANUP(45) { IL2CPP_RETHROW_IF_UNHANDLED(Exception_t *) IL2CPP_JUMP_TBL(0x3C, IL_003c) } IL_003c: { IL2CPP_RUNTIME_CLASS_INIT(SubsystemDescriptorStore_tE5D99C3159868DE6506269CB6B830621F8BC31A6_il2cpp_TypeInfo_var); List_1_t13B7F19BE124BF950C29583D073B7D2174DCA122 * L_5 = ((SubsystemDescriptorStore_tE5D99C3159868DE6506269CB6B830621F8BC31A6_StaticFields*)il2cpp_codegen_static_fields_for(SubsystemDescriptorStore_tE5D99C3159868DE6506269CB6B830621F8BC31A6_il2cpp_TypeInfo_var))->get_s_IntegratedDescriptors_0(); NullCheck(L_5); List_1_Clear_mF2DE990480F55E83ED1A30803FCA939DAC4295FB(L_5, /*hidden argument*/List_1_Clear_mF2DE990480F55E83ED1A30803FCA939DAC4295FB_RuntimeMethod_var); return; } } // System.Void UnityEngine.SubsystemsImplementation.SubsystemDescriptorStore::ReportSingleSubsystemAnalytics(System.String) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void SubsystemDescriptorStore_ReportSingleSubsystemAnalytics_m8DD2291586A77B073F3AF1E84F66C3AE77F5872D (String_t* ___id0, const RuntimeMethod* method) { typedef void (*SubsystemDescriptorStore_ReportSingleSubsystemAnalytics_m8DD2291586A77B073F3AF1E84F66C3AE77F5872D_ftn) (String_t*); static SubsystemDescriptorStore_ReportSingleSubsystemAnalytics_m8DD2291586A77B073F3AF1E84F66C3AE77F5872D_ftn _il2cpp_icall_func; if (!_il2cpp_icall_func) _il2cpp_icall_func = (SubsystemDescriptorStore_ReportSingleSubsystemAnalytics_m8DD2291586A77B073F3AF1E84F66C3AE77F5872D_ftn)il2cpp_codegen_resolve_icall ("UnityEngine.SubsystemsImplementation.SubsystemDescriptorStore::ReportSingleSubsystemAnalytics(System.String)"); _il2cpp_icall_func(___id0); } // System.Void UnityEngine.SubsystemsImplementation.SubsystemDescriptorStore::RegisterDeprecatedDescriptor(UnityEngine.SubsystemDescriptor) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void SubsystemDescriptorStore_RegisterDeprecatedDescriptor_m9AD18069E5C5168A36E15F2E6C3EB3050AAC5C57 (SubsystemDescriptor_tF663011CB44AB1D342821BBEF7B6811E799A7245 * ___descriptor0, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&SubsystemDescriptorStore_RegisterDescriptor_TisSubsystemDescriptor_tF663011CB44AB1D342821BBEF7B6811E799A7245_TisSubsystemDescriptor_tF663011CB44AB1D342821BBEF7B6811E799A7245_mA2A113AA1886D1110BD5C6506B4EDFD8E4BFE230_RuntimeMethod_var); il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&SubsystemDescriptorStore_tE5D99C3159868DE6506269CB6B830621F8BC31A6_il2cpp_TypeInfo_var); s_Il2CppMethodInitialized = true; } { SubsystemDescriptor_tF663011CB44AB1D342821BBEF7B6811E799A7245 * L_0 = ___descriptor0; IL2CPP_RUNTIME_CLASS_INIT(SubsystemDescriptorStore_tE5D99C3159868DE6506269CB6B830621F8BC31A6_il2cpp_TypeInfo_var); List_1_t32E50BD66297C6541AEA401E1C13D4EC530CC56B * L_1 = ((SubsystemDescriptorStore_tE5D99C3159868DE6506269CB6B830621F8BC31A6_StaticFields*)il2cpp_codegen_static_fields_for(SubsystemDescriptorStore_tE5D99C3159868DE6506269CB6B830621F8BC31A6_il2cpp_TypeInfo_var))->get_s_DeprecatedDescriptors_2(); SubsystemDescriptorStore_RegisterDescriptor_TisSubsystemDescriptor_tF663011CB44AB1D342821BBEF7B6811E799A7245_TisSubsystemDescriptor_tF663011CB44AB1D342821BBEF7B6811E799A7245_mA2A113AA1886D1110BD5C6506B4EDFD8E4BFE230(L_0, L_1, /*hidden argument*/SubsystemDescriptorStore_RegisterDescriptor_TisSubsystemDescriptor_tF663011CB44AB1D342821BBEF7B6811E799A7245_TisSubsystemDescriptor_tF663011CB44AB1D342821BBEF7B6811E799A7245_mA2A113AA1886D1110BD5C6506B4EDFD8E4BFE230_RuntimeMethod_var); return; } } // System.Void UnityEngine.SubsystemsImplementation.SubsystemDescriptorStore::.cctor() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void SubsystemDescriptorStore__cctor_mFD5033CA9CAA5C6D585E425EA1AD94F24B05BA2B (const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&List_1__ctor_m1BE065BC3C4D6B70B245126E58C7DAFC7460A597_RuntimeMethod_var); il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&List_1__ctor_m64996A7345F49B6600D4FD19B96FA0D4DBADBDC5_RuntimeMethod_var); il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&List_1__ctor_m68FA0963B0052EA071AC894D7ACFF63E1477ED83_RuntimeMethod_var); il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&List_1_t13B7F19BE124BF950C29583D073B7D2174DCA122_il2cpp_TypeInfo_var); il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&List_1_t32E50BD66297C6541AEA401E1C13D4EC530CC56B_il2cpp_TypeInfo_var); il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&List_1_t4DCA5C48F3390AC8CD79C7AD8D0963D5DAE5CF2E_il2cpp_TypeInfo_var); il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&SubsystemDescriptorStore_tE5D99C3159868DE6506269CB6B830621F8BC31A6_il2cpp_TypeInfo_var); s_Il2CppMethodInitialized = true; } { List_1_t13B7F19BE124BF950C29583D073B7D2174DCA122 * L_0 = (List_1_t13B7F19BE124BF950C29583D073B7D2174DCA122 *)il2cpp_codegen_object_new(List_1_t13B7F19BE124BF950C29583D073B7D2174DCA122_il2cpp_TypeInfo_var); List_1__ctor_m1BE065BC3C4D6B70B245126E58C7DAFC7460A597(L_0, /*hidden argument*/List_1__ctor_m1BE065BC3C4D6B70B245126E58C7DAFC7460A597_RuntimeMethod_var); ((SubsystemDescriptorStore_tE5D99C3159868DE6506269CB6B830621F8BC31A6_StaticFields*)il2cpp_codegen_static_fields_for(SubsystemDescriptorStore_tE5D99C3159868DE6506269CB6B830621F8BC31A6_il2cpp_TypeInfo_var))->set_s_IntegratedDescriptors_0(L_0); List_1_t4DCA5C48F3390AC8CD79C7AD8D0963D5DAE5CF2E * L_1 = (List_1_t4DCA5C48F3390AC8CD79C7AD8D0963D5DAE5CF2E *)il2cpp_codegen_object_new(List_1_t4DCA5C48F3390AC8CD79C7AD8D0963D5DAE5CF2E_il2cpp_TypeInfo_var); List_1__ctor_m64996A7345F49B6600D4FD19B96FA0D4DBADBDC5(L_1, /*hidden argument*/List_1__ctor_m64996A7345F49B6600D4FD19B96FA0D4DBADBDC5_RuntimeMethod_var); ((SubsystemDescriptorStore_tE5D99C3159868DE6506269CB6B830621F8BC31A6_StaticFields*)il2cpp_codegen_static_fields_for(SubsystemDescriptorStore_tE5D99C3159868DE6506269CB6B830621F8BC31A6_il2cpp_TypeInfo_var))->set_s_StandaloneDescriptors_1(L_1); List_1_t32E50BD66297C6541AEA401E1C13D4EC530CC56B * L_2 = (List_1_t32E50BD66297C6541AEA401E1C13D4EC530CC56B *)il2cpp_codegen_object_new(List_1_t32E50BD66297C6541AEA401E1C13D4EC530CC56B_il2cpp_TypeInfo_var); List_1__ctor_m68FA0963B0052EA071AC894D7ACFF63E1477ED83(L_2, /*hidden argument*/List_1__ctor_m68FA0963B0052EA071AC894D7ACFF63E1477ED83_RuntimeMethod_var); ((SubsystemDescriptorStore_tE5D99C3159868DE6506269CB6B830621F8BC31A6_StaticFields*)il2cpp_codegen_static_fields_for(SubsystemDescriptorStore_tE5D99C3159868DE6506269CB6B830621F8BC31A6_il2cpp_TypeInfo_var))->set_s_DeprecatedDescriptors_2(L_2); return; } } #ifdef __clang__ #pragma clang diagnostic pop #endif #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.String UnityEngine.SubsystemsImplementation.SubsystemDescriptorWithProvider::get_id() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR String_t* SubsystemDescriptorWithProvider_get_id_m0341F88D726C677F81277CD2C4A43919EA942861 (SubsystemDescriptorWithProvider_t32DD334657CFBA22F2FBA399258B087104A29C3E * __this, const RuntimeMethod* method) { { String_t* L_0 = __this->get_U3CidU3Ek__BackingField_0(); return L_0; } } // System.Void UnityEngine.SubsystemsImplementation.SubsystemDescriptorWithProvider::.ctor() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void SubsystemDescriptorWithProvider__ctor_m6549AFB004D82BC1439CF25E69BC8BAB9C315604 (SubsystemDescriptorWithProvider_t32DD334657CFBA22F2FBA399258B087104A29C3E * __this, const RuntimeMethod* method) { { Object__ctor_m88880E0413421D13FD95325EDCE231707CE1F405(__this, /*hidden argument*/NULL); return; } } #ifdef __clang__ #pragma clang diagnostic pop #endif #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Void UnityEngine.SubsystemManager::ReloadSubsystemsStarted() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void SubsystemManager_ReloadSubsystemsStarted_m133404E60993652E87FDF45DA28C87FDC5671D46 (const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&SubsystemManager_t4397CEF2ED795CB9B3DDBA2BB468BCB6B45B76D9_il2cpp_TypeInfo_var); s_Il2CppMethodInitialized = true; } bool V_0 = false; bool V_1 = false; { IL2CPP_RUNTIME_CLASS_INIT(SubsystemManager_t4397CEF2ED795CB9B3DDBA2BB468BCB6B45B76D9_il2cpp_TypeInfo_var); Action_tAF41423D285AE0862865348CF6CE51CD085ABBA6 * L_0 = ((SubsystemManager_t4397CEF2ED795CB9B3DDBA2BB468BCB6B45B76D9_StaticFields*)il2cpp_codegen_static_fields_for(SubsystemManager_t4397CEF2ED795CB9B3DDBA2BB468BCB6B45B76D9_il2cpp_TypeInfo_var))->get_reloadSubsytemsStarted_5(); V_0 = (bool)((!(((RuntimeObject*)(Action_tAF41423D285AE0862865348CF6CE51CD085ABBA6 *)L_0) <= ((RuntimeObject*)(RuntimeObject *)NULL)))? 1 : 0); bool L_1 = V_0; if (!L_1) { goto IL_0018; } } { IL2CPP_RUNTIME_CLASS_INIT(SubsystemManager_t4397CEF2ED795CB9B3DDBA2BB468BCB6B45B76D9_il2cpp_TypeInfo_var); Action_tAF41423D285AE0862865348CF6CE51CD085ABBA6 * L_2 = ((SubsystemManager_t4397CEF2ED795CB9B3DDBA2BB468BCB6B45B76D9_StaticFields*)il2cpp_codegen_static_fields_for(SubsystemManager_t4397CEF2ED795CB9B3DDBA2BB468BCB6B45B76D9_il2cpp_TypeInfo_var))->get_reloadSubsytemsStarted_5(); NullCheck(L_2); Action_Invoke_m3FFA5BE3D64F0FF8E1E1CB6F953913FADB5EB89E(L_2, /*hidden argument*/NULL); } IL_0018: { IL2CPP_RUNTIME_CLASS_INIT(SubsystemManager_t4397CEF2ED795CB9B3DDBA2BB468BCB6B45B76D9_il2cpp_TypeInfo_var); Action_tAF41423D285AE0862865348CF6CE51CD085ABBA6 * L_3 = ((SubsystemManager_t4397CEF2ED795CB9B3DDBA2BB468BCB6B45B76D9_StaticFields*)il2cpp_codegen_static_fields_for(SubsystemManager_t4397CEF2ED795CB9B3DDBA2BB468BCB6B45B76D9_il2cpp_TypeInfo_var))->get_beforeReloadSubsystems_0(); V_1 = (bool)((!(((RuntimeObject*)(Action_tAF41423D285AE0862865348CF6CE51CD085ABBA6 *)L_3) <= ((RuntimeObject*)(RuntimeObject *)NULL)))? 1 : 0); bool L_4 = V_1; if (!L_4) { goto IL_002f; } } { IL2CPP_RUNTIME_CLASS_INIT(SubsystemManager_t4397CEF2ED795CB9B3DDBA2BB468BCB6B45B76D9_il2cpp_TypeInfo_var); Action_tAF41423D285AE0862865348CF6CE51CD085ABBA6 * L_5 = ((SubsystemManager_t4397CEF2ED795CB9B3DDBA2BB468BCB6B45B76D9_StaticFields*)il2cpp_codegen_static_fields_for(SubsystemManager_t4397CEF2ED795CB9B3DDBA2BB468BCB6B45B76D9_il2cpp_TypeInfo_var))->get_beforeReloadSubsystems_0(); NullCheck(L_5); Action_Invoke_m3FFA5BE3D64F0FF8E1E1CB6F953913FADB5EB89E(L_5, /*hidden argument*/NULL); } IL_002f: { return; } } // System.Void UnityEngine.SubsystemManager::ReloadSubsystemsCompleted() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void SubsystemManager_ReloadSubsystemsCompleted_m764A6E65F5ABB205C7E4948E320D3F2558EBE9B3 (const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&SubsystemManager_t4397CEF2ED795CB9B3DDBA2BB468BCB6B45B76D9_il2cpp_TypeInfo_var); s_Il2CppMethodInitialized = true; } bool V_0 = false; bool V_1 = false; { IL2CPP_RUNTIME_CLASS_INIT(SubsystemManager_t4397CEF2ED795CB9B3DDBA2BB468BCB6B45B76D9_il2cpp_TypeInfo_var); Action_tAF41423D285AE0862865348CF6CE51CD085ABBA6 * L_0 = ((SubsystemManager_t4397CEF2ED795CB9B3DDBA2BB468BCB6B45B76D9_StaticFields*)il2cpp_codegen_static_fields_for(SubsystemManager_t4397CEF2ED795CB9B3DDBA2BB468BCB6B45B76D9_il2cpp_TypeInfo_var))->get_reloadSubsytemsCompleted_6(); V_0 = (bool)((!(((RuntimeObject*)(Action_tAF41423D285AE0862865348CF6CE51CD085ABBA6 *)L_0) <= ((RuntimeObject*)(RuntimeObject *)NULL)))? 1 : 0); bool L_1 = V_0; if (!L_1) { goto IL_0018; } } { IL2CPP_RUNTIME_CLASS_INIT(SubsystemManager_t4397CEF2ED795CB9B3DDBA2BB468BCB6B45B76D9_il2cpp_TypeInfo_var); Action_tAF41423D285AE0862865348CF6CE51CD085ABBA6 * L_2 = ((SubsystemManager_t4397CEF2ED795CB9B3DDBA2BB468BCB6B45B76D9_StaticFields*)il2cpp_codegen_static_fields_for(SubsystemManager_t4397CEF2ED795CB9B3DDBA2BB468BCB6B45B76D9_il2cpp_TypeInfo_var))->get_reloadSubsytemsCompleted_6(); NullCheck(L_2); Action_Invoke_m3FFA5BE3D64F0FF8E1E1CB6F953913FADB5EB89E(L_2, /*hidden argument*/NULL); } IL_0018: { IL2CPP_RUNTIME_CLASS_INIT(SubsystemManager_t4397CEF2ED795CB9B3DDBA2BB468BCB6B45B76D9_il2cpp_TypeInfo_var); Action_tAF41423D285AE0862865348CF6CE51CD085ABBA6 * L_3 = ((SubsystemManager_t4397CEF2ED795CB9B3DDBA2BB468BCB6B45B76D9_StaticFields*)il2cpp_codegen_static_fields_for(SubsystemManager_t4397CEF2ED795CB9B3DDBA2BB468BCB6B45B76D9_il2cpp_TypeInfo_var))->get_afterReloadSubsystems_1(); V_1 = (bool)((!(((RuntimeObject*)(Action_tAF41423D285AE0862865348CF6CE51CD085ABBA6 *)L_3) <= ((RuntimeObject*)(RuntimeObject *)NULL)))? 1 : 0); bool L_4 = V_1; if (!L_4) { goto IL_002f; } } { IL2CPP_RUNTIME_CLASS_INIT(SubsystemManager_t4397CEF2ED795CB9B3DDBA2BB468BCB6B45B76D9_il2cpp_TypeInfo_var); Action_tAF41423D285AE0862865348CF6CE51CD085ABBA6 * L_5 = ((SubsystemManager_t4397CEF2ED795CB9B3DDBA2BB468BCB6B45B76D9_StaticFields*)il2cpp_codegen_static_fields_for(SubsystemManager_t4397CEF2ED795CB9B3DDBA2BB468BCB6B45B76D9_il2cpp_TypeInfo_var))->get_afterReloadSubsystems_1(); NullCheck(L_5); Action_Invoke_m3FFA5BE3D64F0FF8E1E1CB6F953913FADB5EB89E(L_5, /*hidden argument*/NULL); } IL_002f: { return; } } // System.Void UnityEngine.SubsystemManager::InitializeIntegratedSubsystem(System.IntPtr,UnityEngine.IntegratedSubsystem) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void SubsystemManager_InitializeIntegratedSubsystem_m6FB689B16CAD4F343859F6CE93BFBC92818D1BDE (intptr_t ___ptr0, IntegratedSubsystem_t8FB3A371F812CF9521903AC016C64E95C7412002 * ___subsystem1, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&List_1_Add_m54714E32B888D33E0D24E8AF9B2C0BE61334C065_RuntimeMethod_var); il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&SubsystemManager_t4397CEF2ED795CB9B3DDBA2BB468BCB6B45B76D9_il2cpp_TypeInfo_var); s_Il2CppMethodInitialized = true; } { IntegratedSubsystem_t8FB3A371F812CF9521903AC016C64E95C7412002 * L_0 = ___subsystem1; intptr_t L_1 = ___ptr0; NullCheck(L_0); L_0->set_m_Ptr_0((intptr_t)L_1); IntegratedSubsystem_t8FB3A371F812CF9521903AC016C64E95C7412002 * L_2 = ___subsystem1; IntegratedSubsystem_t8FB3A371F812CF9521903AC016C64E95C7412002 * L_3 = ___subsystem1; NullCheck(L_2); IntegratedSubsystem_SetHandle_m951ABC336E4544AAD792A7118E2261AC8F2A297E(L_2, L_3, /*hidden argument*/NULL); IL2CPP_RUNTIME_CLASS_INIT(SubsystemManager_t4397CEF2ED795CB9B3DDBA2BB468BCB6B45B76D9_il2cpp_TypeInfo_var); List_1_t2DAF7481782912A6F8E6180AC19B83A5EEFEE9EF * L_4 = ((SubsystemManager_t4397CEF2ED795CB9B3DDBA2BB468BCB6B45B76D9_StaticFields*)il2cpp_codegen_static_fields_for(SubsystemManager_t4397CEF2ED795CB9B3DDBA2BB468BCB6B45B76D9_il2cpp_TypeInfo_var))->get_s_IntegratedSubsystems_2(); IntegratedSubsystem_t8FB3A371F812CF9521903AC016C64E95C7412002 * L_5 = ___subsystem1; NullCheck(L_4); List_1_Add_m54714E32B888D33E0D24E8AF9B2C0BE61334C065(L_4, L_5, /*hidden argument*/List_1_Add_m54714E32B888D33E0D24E8AF9B2C0BE61334C065_RuntimeMethod_var); return; } } // System.Void UnityEngine.SubsystemManager::ClearSubsystems() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void SubsystemManager_ClearSubsystems_mBABA311915C4E3302003EA18B4ED6C348289E2C2 (const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&Enumerator_Dispose_m2422FBD5B59F54B43DEF2796536DBDFBE7B27B17_RuntimeMethod_var); il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&Enumerator_MoveNext_mC10CBAADB9DFA0A091393D78B464F2AB2617750D_RuntimeMethod_var); il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&Enumerator_get_Current_mA9ED75A7F28667B3CA286C561A8983A6355CB28C_RuntimeMethod_var); il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&IntPtr_t_il2cpp_TypeInfo_var); il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&List_1_Clear_m2D220FFB24BAB221D99A0CA9543AFE6DF8D155B6_RuntimeMethod_var); il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&List_1_Clear_mA624B195E1AC838905EB58332EE3BAAF99A9D2CA_RuntimeMethod_var); il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&List_1_Clear_mEE68874407E18C9127133CC13AEEA9F5A4BD8392_RuntimeMethod_var); il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&List_1_GetEnumerator_m0593C6B2A3413655213A5E61FB90E1927DDEAE20_RuntimeMethod_var); il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&SubsystemManager_t4397CEF2ED795CB9B3DDBA2BB468BCB6B45B76D9_il2cpp_TypeInfo_var); s_Il2CppMethodInitialized = true; } Enumerator_tCF86CE3FF03B86F9FF1AB5746DF9DEE36DCAD59D V_0; memset((&V_0), 0, sizeof(V_0)); IntegratedSubsystem_t8FB3A371F812CF9521903AC016C64E95C7412002 * V_1 = NULL; Exception_t * __last_unhandled_exception = 0; il2cpp::utils::ExceptionSupportStack<int32_t, 1> __leave_targets; { IL2CPP_RUNTIME_CLASS_INIT(SubsystemManager_t4397CEF2ED795CB9B3DDBA2BB468BCB6B45B76D9_il2cpp_TypeInfo_var); List_1_t2DAF7481782912A6F8E6180AC19B83A5EEFEE9EF * L_0 = ((SubsystemManager_t4397CEF2ED795CB9B3DDBA2BB468BCB6B45B76D9_StaticFields*)il2cpp_codegen_static_fields_for(SubsystemManager_t4397CEF2ED795CB9B3DDBA2BB468BCB6B45B76D9_il2cpp_TypeInfo_var))->get_s_IntegratedSubsystems_2(); NullCheck(L_0); Enumerator_tCF86CE3FF03B86F9FF1AB5746DF9DEE36DCAD59D L_1; L_1 = List_1_GetEnumerator_m0593C6B2A3413655213A5E61FB90E1927DDEAE20(L_0, /*hidden argument*/List_1_GetEnumerator_m0593C6B2A3413655213A5E61FB90E1927DDEAE20_RuntimeMethod_var); V_0 = L_1; } IL_000d: try { // begin try (depth: 1) { goto IL_0022; } IL_000f: { IntegratedSubsystem_t8FB3A371F812CF9521903AC016C64E95C7412002 * L_2; L_2 = Enumerator_get_Current_mA9ED75A7F28667B3CA286C561A8983A6355CB28C_inline((Enumerator_tCF86CE3FF03B86F9FF1AB5746DF9DEE36DCAD59D *)(&V_0), /*hidden argument*/Enumerator_get_Current_mA9ED75A7F28667B3CA286C561A8983A6355CB28C_RuntimeMethod_var); V_1 = L_2; IntegratedSubsystem_t8FB3A371F812CF9521903AC016C64E95C7412002 * L_3 = V_1; NullCheck(L_3); L_3->set_m_Ptr_0((intptr_t)(0)); } IL_0022: { bool L_4; L_4 = Enumerator_MoveNext_mC10CBAADB9DFA0A091393D78B464F2AB2617750D((Enumerator_tCF86CE3FF03B86F9FF1AB5746DF9DEE36DCAD59D *)(&V_0), /*hidden argument*/Enumerator_MoveNext_mC10CBAADB9DFA0A091393D78B464F2AB2617750D_RuntimeMethod_var); if (L_4) { goto IL_000f; } } IL_002b: { IL2CPP_LEAVE(0x3C, FINALLY_002d); } } // end try (depth: 1) catch(Il2CppExceptionWrapper& e) { __last_unhandled_exception = (Exception_t *)e.ex; goto FINALLY_002d; } FINALLY_002d: { // begin finally (depth: 1) Enumerator_Dispose_m2422FBD5B59F54B43DEF2796536DBDFBE7B27B17((Enumerator_tCF86CE3FF03B86F9FF1AB5746DF9DEE36DCAD59D *)(&V_0), /*hidden argument*/Enumerator_Dispose_m2422FBD5B59F54B43DEF2796536DBDFBE7B27B17_RuntimeMethod_var); IL2CPP_END_FINALLY(45) } // end finally (depth: 1) IL2CPP_CLEANUP(45) { IL2CPP_RETHROW_IF_UNHANDLED(Exception_t *) IL2CPP_JUMP_TBL(0x3C, IL_003c) } IL_003c: { IL2CPP_RUNTIME_CLASS_INIT(SubsystemManager_t4397CEF2ED795CB9B3DDBA2BB468BCB6B45B76D9_il2cpp_TypeInfo_var); List_1_t2DAF7481782912A6F8E6180AC19B83A5EEFEE9EF * L_5 = ((SubsystemManager_t4397CEF2ED795CB9B3DDBA2BB468BCB6B45B76D9_StaticFields*)il2cpp_codegen_static_fields_for(SubsystemManager_t4397CEF2ED795CB9B3DDBA2BB468BCB6B45B76D9_il2cpp_TypeInfo_var))->get_s_IntegratedSubsystems_2(); NullCheck(L_5); List_1_Clear_m2D220FFB24BAB221D99A0CA9543AFE6DF8D155B6(L_5, /*hidden argument*/List_1_Clear_m2D220FFB24BAB221D99A0CA9543AFE6DF8D155B6_RuntimeMethod_var); List_1_t6E613DAFFAFE896B759F1C5260D6234F04C9DD41 * L_6 = ((SubsystemManager_t4397CEF2ED795CB9B3DDBA2BB468BCB6B45B76D9_StaticFields*)il2cpp_codegen_static_fields_for(SubsystemManager_t4397CEF2ED795CB9B3DDBA2BB468BCB6B45B76D9_il2cpp_TypeInfo_var))->get_s_StandaloneSubsystems_3(); NullCheck(L_6); List_1_Clear_mA624B195E1AC838905EB58332EE3BAAF99A9D2CA(L_6, /*hidden argument*/List_1_Clear_mA624B195E1AC838905EB58332EE3BAAF99A9D2CA_RuntimeMethod_var); List_1_t58BB84B47855540E6D2640B387506E01436DCF82 * L_7 = ((SubsystemManager_t4397CEF2ED795CB9B3DDBA2BB468BCB6B45B76D9_StaticFields*)il2cpp_codegen_static_fields_for(SubsystemManager_t4397CEF2ED795CB9B3DDBA2BB468BCB6B45B76D9_il2cpp_TypeInfo_var))->get_s_DeprecatedSubsystems_4(); NullCheck(L_7); List_1_Clear_mEE68874407E18C9127133CC13AEEA9F5A4BD8392(L_7, /*hidden argument*/List_1_Clear_mEE68874407E18C9127133CC13AEEA9F5A4BD8392_RuntimeMethod_var); return; } } // System.Void UnityEngine.SubsystemManager::StaticConstructScriptingClassMap() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void SubsystemManager_StaticConstructScriptingClassMap_m2D54CD8E480B334F4EC0EAAF49DE4186895885EE (const RuntimeMethod* method) { typedef void (*SubsystemManager_StaticConstructScriptingClassMap_m2D54CD8E480B334F4EC0EAAF49DE4186895885EE_ftn) (); static SubsystemManager_StaticConstructScriptingClassMap_m2D54CD8E480B334F4EC0EAAF49DE4186895885EE_ftn _il2cpp_icall_func; if (!_il2cpp_icall_func) _il2cpp_icall_func = (SubsystemManager_StaticConstructScriptingClassMap_m2D54CD8E480B334F4EC0EAAF49DE4186895885EE_ftn)il2cpp_codegen_resolve_icall ("UnityEngine.SubsystemManager::StaticConstructScriptingClassMap()"); _il2cpp_icall_func(); } // System.Void UnityEngine.SubsystemManager::.cctor() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void SubsystemManager__cctor_m623E9CEA1E2F73608F88CAA9F087A9A9A8A139AB (const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&List_1__ctor_m880D76E786031830863F68A2C4F0B7DF425666E5_RuntimeMethod_var); il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&List_1__ctor_mAB9CAE208C61BBAF2266DA3CB6EF7DE1F16BF08C_RuntimeMethod_var); il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&List_1__ctor_mB5053799863D389932A9DE8C00C290CBE78E176D_RuntimeMethod_var); il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&List_1_t2DAF7481782912A6F8E6180AC19B83A5EEFEE9EF_il2cpp_TypeInfo_var); il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&List_1_t58BB84B47855540E6D2640B387506E01436DCF82_il2cpp_TypeInfo_var); il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&List_1_t6E613DAFFAFE896B759F1C5260D6234F04C9DD41_il2cpp_TypeInfo_var); il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&SubsystemManager_t4397CEF2ED795CB9B3DDBA2BB468BCB6B45B76D9_il2cpp_TypeInfo_var); s_Il2CppMethodInitialized = true; } { List_1_t2DAF7481782912A6F8E6180AC19B83A5EEFEE9EF * L_0 = (List_1_t2DAF7481782912A6F8E6180AC19B83A5EEFEE9EF *)il2cpp_codegen_object_new(List_1_t2DAF7481782912A6F8E6180AC19B83A5EEFEE9EF_il2cpp_TypeInfo_var); List_1__ctor_mAB9CAE208C61BBAF2266DA3CB6EF7DE1F16BF08C(L_0, /*hidden argument*/List_1__ctor_mAB9CAE208C61BBAF2266DA3CB6EF7DE1F16BF08C_RuntimeMethod_var); ((SubsystemManager_t4397CEF2ED795CB9B3DDBA2BB468BCB6B45B76D9_StaticFields*)il2cpp_codegen_static_fields_for(SubsystemManager_t4397CEF2ED795CB9B3DDBA2BB468BCB6B45B76D9_il2cpp_TypeInfo_var))->set_s_IntegratedSubsystems_2(L_0); List_1_t6E613DAFFAFE896B759F1C5260D6234F04C9DD41 * L_1 = (List_1_t6E613DAFFAFE896B759F1C5260D6234F04C9DD41 *)il2cpp_codegen_object_new(List_1_t6E613DAFFAFE896B759F1C5260D6234F04C9DD41_il2cpp_TypeInfo_var); List_1__ctor_mB5053799863D389932A9DE8C00C290CBE78E176D(L_1, /*hidden argument*/List_1__ctor_mB5053799863D389932A9DE8C00C290CBE78E176D_RuntimeMethod_var); ((SubsystemManager_t4397CEF2ED795CB9B3DDBA2BB468BCB6B45B76D9_StaticFields*)il2cpp_codegen_static_fields_for(SubsystemManager_t4397CEF2ED795CB9B3DDBA2BB468BCB6B45B76D9_il2cpp_TypeInfo_var))->set_s_StandaloneSubsystems_3(L_1); List_1_t58BB84B47855540E6D2640B387506E01436DCF82 * L_2 = (List_1_t58BB84B47855540E6D2640B387506E01436DCF82 *)il2cpp_codegen_object_new(List_1_t58BB84B47855540E6D2640B387506E01436DCF82_il2cpp_TypeInfo_var); List_1__ctor_m880D76E786031830863F68A2C4F0B7DF425666E5(L_2, /*hidden argument*/List_1__ctor_m880D76E786031830863F68A2C4F0B7DF425666E5_RuntimeMethod_var); ((SubsystemManager_t4397CEF2ED795CB9B3DDBA2BB468BCB6B45B76D9_StaticFields*)il2cpp_codegen_static_fields_for(SubsystemManager_t4397CEF2ED795CB9B3DDBA2BB468BCB6B45B76D9_il2cpp_TypeInfo_var))->set_s_DeprecatedSubsystems_4(L_2); SubsystemManager_StaticConstructScriptingClassMap_m2D54CD8E480B334F4EC0EAAF49DE4186895885EE(/*hidden argument*/NULL); return; } } // UnityEngine.IntegratedSubsystem UnityEngine.SubsystemManager::GetIntegratedSubsystemByPtr(System.IntPtr) IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR IntegratedSubsystem_t8FB3A371F812CF9521903AC016C64E95C7412002 * SubsystemManager_GetIntegratedSubsystemByPtr_mD152809BEEF4343B0AFD44A64EEE832ED90760EA (intptr_t ___ptr0, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&Enumerator_Dispose_m2422FBD5B59F54B43DEF2796536DBDFBE7B27B17_RuntimeMethod_var); il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&Enumerator_MoveNext_mC10CBAADB9DFA0A091393D78B464F2AB2617750D_RuntimeMethod_var); il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&Enumerator_get_Current_mA9ED75A7F28667B3CA286C561A8983A6355CB28C_RuntimeMethod_var); il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&List_1_GetEnumerator_m0593C6B2A3413655213A5E61FB90E1927DDEAE20_RuntimeMethod_var); il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&SubsystemManager_t4397CEF2ED795CB9B3DDBA2BB468BCB6B45B76D9_il2cpp_TypeInfo_var); s_Il2CppMethodInitialized = true; } Enumerator_tCF86CE3FF03B86F9FF1AB5746DF9DEE36DCAD59D V_0; memset((&V_0), 0, sizeof(V_0)); IntegratedSubsystem_t8FB3A371F812CF9521903AC016C64E95C7412002 * V_1 = NULL; bool V_2 = false; IntegratedSubsystem_t8FB3A371F812CF9521903AC016C64E95C7412002 * V_3 = NULL; Exception_t * __last_unhandled_exception = 0; il2cpp::utils::ExceptionSupportStack<int32_t, 2> __leave_targets; { IL2CPP_RUNTIME_CLASS_INIT(SubsystemManager_t4397CEF2ED795CB9B3DDBA2BB468BCB6B45B76D9_il2cpp_TypeInfo_var); List_1_t2DAF7481782912A6F8E6180AC19B83A5EEFEE9EF * L_0 = ((SubsystemManager_t4397CEF2ED795CB9B3DDBA2BB468BCB6B45B76D9_StaticFields*)il2cpp_codegen_static_fields_for(SubsystemManager_t4397CEF2ED795CB9B3DDBA2BB468BCB6B45B76D9_il2cpp_TypeInfo_var))->get_s_IntegratedSubsystems_2(); NullCheck(L_0); Enumerator_tCF86CE3FF03B86F9FF1AB5746DF9DEE36DCAD59D L_1; L_1 = List_1_GetEnumerator_m0593C6B2A3413655213A5E61FB90E1927DDEAE20(L_0, /*hidden argument*/List_1_GetEnumerator_m0593C6B2A3413655213A5E61FB90E1927DDEAE20_RuntimeMethod_var); V_0 = L_1; } IL_000d: try { // begin try (depth: 1) { goto IL_002d; } IL_000f: { IntegratedSubsystem_t8FB3A371F812CF9521903AC016C64E95C7412002 * L_2; L_2 = Enumerator_get_Current_mA9ED75A7F28667B3CA286C561A8983A6355CB28C_inline((Enumerator_tCF86CE3FF03B86F9FF1AB5746DF9DEE36DCAD59D *)(&V_0), /*hidden argument*/Enumerator_get_Current_mA9ED75A7F28667B3CA286C561A8983A6355CB28C_RuntimeMethod_var); V_1 = L_2; IntegratedSubsystem_t8FB3A371F812CF9521903AC016C64E95C7412002 * L_3 = V_1; NullCheck(L_3); intptr_t L_4 = L_3->get_m_Ptr_0(); intptr_t L_5 = ___ptr0; bool L_6; L_6 = IntPtr_op_Equality_mD94F3FE43A65684EFF984A7B95E70D2520C0AC73((intptr_t)L_4, (intptr_t)L_5, /*hidden argument*/NULL); V_2 = L_6; bool L_7 = V_2; if (!L_7) { goto IL_002c; } } IL_0028: { IntegratedSubsystem_t8FB3A371F812CF9521903AC016C64E95C7412002 * L_8 = V_1; V_3 = L_8; IL2CPP_LEAVE(0x4B, FINALLY_0038); } IL_002c: { } IL_002d: { bool L_9; L_9 = Enumerator_MoveNext_mC10CBAADB9DFA0A091393D78B464F2AB2617750D((Enumerator_tCF86CE3FF03B86F9FF1AB5746DF9DEE36DCAD59D *)(&V_0), /*hidden argument*/Enumerator_MoveNext_mC10CBAADB9DFA0A091393D78B464F2AB2617750D_RuntimeMethod_var); if (L_9) { goto IL_000f; } } IL_0036: { IL2CPP_LEAVE(0x47, FINALLY_0038); } } // end try (depth: 1) catch(Il2CppExceptionWrapper& e) { __last_unhandled_exception = (Exception_t *)e.ex; goto FINALLY_0038; } FINALLY_0038: { // begin finally (depth: 1) Enumerator_Dispose_m2422FBD5B59F54B43DEF2796536DBDFBE7B27B17((Enumerator_tCF86CE3FF03B86F9FF1AB5746DF9DEE36DCAD59D *)(&V_0), /*hidden argument*/Enumerator_Dispose_m2422FBD5B59F54B43DEF2796536DBDFBE7B27B17_RuntimeMethod_var); IL2CPP_END_FINALLY(56) } // end finally (depth: 1) IL2CPP_CLEANUP(56) { IL2CPP_RETHROW_IF_UNHANDLED(Exception_t *) IL2CPP_JUMP_TBL(0x4B, IL_004b) IL2CPP_JUMP_TBL(0x47, IL_0047) } IL_0047: { V_3 = (IntegratedSubsystem_t8FB3A371F812CF9521903AC016C64E95C7412002 *)NULL; goto IL_004b; } IL_004b: { IntegratedSubsystem_t8FB3A371F812CF9521903AC016C64E95C7412002 * L_10 = V_3; return L_10; } } #ifdef __clang__ #pragma clang diagnostic pop #endif #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Void UnityEngine.SubsystemsImplementation.SubsystemWithProvider::.ctor() IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void SubsystemWithProvider__ctor_m7839AE90041C8237270AFC52FC96E1BEECCDC653 (SubsystemWithProvider_t1C1868CF8676F5596C1AD20A7CE69BDF7C7DE73E * __this, const RuntimeMethod* method) { { Object__ctor_m88880E0413421D13FD95325EDCE231707CE1F405(__this, /*hidden argument*/NULL); return; } } #ifdef __clang__ #pragma clang diagnostic pop #endif IL2CPP_MANAGED_FORCE_INLINE IL2CPP_METHOD_ATTR RuntimeObject * Enumerator_get_Current_m9C4EBBD2108B51885E750F927D7936290C8E20EE_gshared_inline (Enumerator_tB6009981BD4E3881E3EC83627255A24198F902D6 * __this, const RuntimeMethod* method) { { RuntimeObject * L_0 = (RuntimeObject *)__this->get_current_3(); return (RuntimeObject *)L_0; } }
55.309123
482
0.860227
SympactDev
9c735bf6af29787e98f05da1227267d7a744d6f0
615
cpp
C++
08. String to Integer (atoi).cpp
corn1ng/LeetCode-Solution
e7b6f77dd407c9a5cc8be43dc9b0e5d9bc185b95
[ "Apache-2.0" ]
6
2017-11-18T02:16:35.000Z
2017-12-17T06:30:40.000Z
08. String to Integer (atoi).cpp
corn1ng/LeetCode-Solution
e7b6f77dd407c9a5cc8be43dc9b0e5d9bc185b95
[ "Apache-2.0" ]
null
null
null
08. String to Integer (atoi).cpp
corn1ng/LeetCode-Solution
e7b6f77dd407c9a5cc8be43dc9b0e5d9bc185b95
[ "Apache-2.0" ]
null
null
null
class Solution { public: int myAtoi(string str) { long result = 0; int indicator = 1; for(int i = 0; i<str.size();) { i = str.find_first_not_of(' '); if(str[i] == '-' || str[i] == '+') indicator = (str[i++] == '-')? -1 : 1; while('0'<= str[i] && str[i] <= '9') { result = result*10 + (str[i++]-'0'); if(result*indicator >= INT_MAX) return INT_MAX; if(result*indicator <= INT_MIN) return INT_MIN; } return result*indicator; } return 0; } }; //直接参考leetcode答案的,测试数据有好多想不到的东西。。
25.625
75
0.466667
corn1ng
9c73ecae9b79b0c5b9de87ea14b95de23ecd250d
900
cpp
C++
Algorithm/Problem50/main.cpp
zsef123/ModernCppChallengeStudy
058c0a6c5e41758f53336e554f29b497c9881fae
[ "MIT" ]
null
null
null
Algorithm/Problem50/main.cpp
zsef123/ModernCppChallengeStudy
058c0a6c5e41758f53336e554f29b497c9881fae
[ "MIT" ]
null
null
null
Algorithm/Problem50/main.cpp
zsef123/ModernCppChallengeStudy
058c0a6c5e41758f53336e554f29b497c9881fae
[ "MIT" ]
null
null
null
#include <gsl/gsl> #include <iostream> #include <vector> #include <string> // Filtering a list of phone numbers // type const& == const type & ?? auto phone_filter(std::vector<std::string> const& vec, int region) { std::vector<std::string> filtered; for (auto const& num : vec) { int start = 0; if (num[0] == '+') start++; std::string n = num.substr(start, 2); if (std::stoi(n) == region) { // what diff with push_back filtered.emplace_back(num); } } return filtered; } int main(int argc, char* argv[]) { std::vector<std::string> vec = { "+821012345678", "821012345678", "01012345678", "+82-10-1234-5678", "82-10-1234-4567", "010-1234-5678" }; for (auto n : phone_filter(vec, 82)) std::cout << n << std::endl; return 0; }
23.684211
68
0.526667
zsef123
9c7453cd80a2006e8089b0fad4094d4be7f4f562
1,564
cpp
C++
ds18b20.cpp
rsmohamad/pi_controller
d85c0a4823d57104cfa8c12e6aeb60b0318676b0
[ "MIT" ]
null
null
null
ds18b20.cpp
rsmohamad/pi_controller
d85c0a4823d57104cfa8c12e6aeb60b0318676b0
[ "MIT" ]
null
null
null
ds18b20.cpp
rsmohamad/pi_controller
d85c0a4823d57104cfa8c12e6aeb60b0318676b0
[ "MIT" ]
null
null
null
#include "ds18b20.h" #include <dirent.h> #include <string.h> #include <unistd.h> #include <iostream> #include <QTimer> const std::string prefixPath = "/sys/bus/w1/devices/"; const std::string suffixPath = "/w1_slave"; DS18B20::DS18B20() { // Load kernel modules system("modprobe w1-gpio"); system("modprobe w1-therm"); // Get the temperature sensor id DIR *d = opendir(prefixPath.c_str()); dirent *entry; while (d && (entry = readdir(d))) { if (strncmp(entry->d_name, "28-", 3) == 0) { devName = std::string(entry->d_name); break; } } // Open file path = prefixPath + devName + suffixPath; std::cout << path << std::endl; // tempInput.open(path.c_str()); } DS18B20::~DS18B20() { tempInput.close(); } void DS18B20::readTemperature() { tempInput.open(path.c_str()); if (!tempInput.is_open()) { return; } double temperature = -1; std::string line; std::getline(tempInput, line); if (line.find("YES") != std::string::npos) { std::getline(tempInput, line); int pos = line.find("t=") + 2; temperature = std::stod(line.substr(pos)); temperature /= (double)1000.0; } tempInput.close(); emit updateTemperature(temperature); } bool DS18B20::isAvailable() { tempInput.open(path.c_str()); bool isOpen = tempInput.is_open(); tempInput.close(); return isOpen; } void DS18B20::run() { QTimer timer; connect(&timer, SIGNAL(timeout()), this, SLOT(readTemperature()), Qt::DirectConnection); timer.setInterval(100); timer.start(); exec(); timer.stop(); }
21.135135
67
0.633632
rsmohamad
9c746bbadd0da38723f11ccb962acb91fa8862fe
814
hpp
C++
Games/NetGame/Code/Game/GameNetMessages.hpp
tonyatpeking/SMU_SD
00ebc9c1acd437128de3562cf355f1d81e375975
[ "MIT" ]
null
null
null
Games/NetGame/Code/Game/GameNetMessages.hpp
tonyatpeking/SMU_SD
00ebc9c1acd437128de3562cf355f1d81e375975
[ "MIT" ]
null
null
null
Games/NetGame/Code/Game/GameNetMessages.hpp
tonyatpeking/SMU_SD
00ebc9c1acd437128de3562cf355f1d81e375975
[ "MIT" ]
1
2019-10-02T01:48:54.000Z
2019-10-02T01:48:54.000Z
#pragma once #include "Engine/Net/NetCommonH.hpp" #include "Engine/Core/EngineCommonH.hpp" class NetMessage; class NetCube; class ClientInputs; namespace GameNetMessages { enum eNetGameMessageIdx : uint8 { TEST_GAME_MESSAGE = eNetCoreMessageIdx::NET_CORE_COUNT, UNRELIABLE_TEST = 128, RELIABLE_TEST = 129, SEQUENCE_TEST = 130 }; NetMessage* Compose_UnreliableTest( uint currentCount, uint totalCount ); NetMessage* Compose_ReliableTest( uint currentCount, uint totalCount ); NetMessage* Compose_SequenceTest( uint currentCount, uint totalCount ); NetMessage* Compose_CreateCube( NetCube* cube ); NetMessage* Compose_DestroyCube( uint16 netID ); NetMessage* Compose_UpdateCube( NetCube* cube ); NetMessage* Compose_SendInputs( const ClientInputs& inputs ); NetMessage* Compose_EnterGame(); }
25.4375
73
0.791155
tonyatpeking
9c752bbabc0b259c4b2c69150c641d15da3ae3b7
129
cpp
C++
tensorflow-yolo-ios/dependencies/eigen/test/sparseqr.cpp
initialz/tensorflow-yolo-face-ios
ba74cf39168d0128e91318e65a1b88ce4d65a167
[ "MIT" ]
27
2017-06-07T19:07:32.000Z
2020-10-15T10:09:12.000Z
tensorflow-yolo-ios/dependencies/eigen/test/sparseqr.cpp
initialz/tensorflow-yolo-face-ios
ba74cf39168d0128e91318e65a1b88ce4d65a167
[ "MIT" ]
3
2017-08-25T17:39:46.000Z
2017-11-18T03:40:55.000Z
tensorflow-yolo-ios/dependencies/eigen/test/sparseqr.cpp
initialz/tensorflow-yolo-face-ios
ba74cf39168d0128e91318e65a1b88ce4d65a167
[ "MIT" ]
10
2017-06-16T18:04:45.000Z
2018-07-05T17:33:01.000Z
version https://git-lfs.github.com/spec/v1 oid sha256:1df6c55d9fbc80cdae67fa7355baed48fe6e8196b1cd76fa1d5763e15721b107 size 3094
32.25
75
0.883721
initialz
9c77d24bdcf222bf25c72a96c52c9a3bbc20d852
5,287
hpp
C++
include/ztd/text/encoding_error.hpp
vector-of-bool/text
a4d00c9f6047c73e2b04a0b58c95f10335c73405
[ "Apache-2.0" ]
null
null
null
include/ztd/text/encoding_error.hpp
vector-of-bool/text
a4d00c9f6047c73e2b04a0b58c95f10335c73405
[ "Apache-2.0" ]
null
null
null
include/ztd/text/encoding_error.hpp
vector-of-bool/text
a4d00c9f6047c73e2b04a0b58c95f10335c73405
[ "Apache-2.0" ]
null
null
null
// ============================================================================= // // ztd.text // Copyright © 2021 JeanHeyd "ThePhD" Meneide and Shepherd's Oasis, LLC // Contact: opensource@soasis.org // // Commercial License Usage // Licensees holding valid commercial ztd.text licenses may use this file in // accordance with the commercial license agreement provided with the // Software or, alternatively, in accordance with the terms contained in // a written agreement between you and Shepherd's Oasis, LLC. // For licensing terms and conditions see your agreement. For // further information contact opensource@soasis.org. // // Apache License Version 2 Usage // Alternatively, this file may be used under the terms of Apache License // Version 2.0 (the "License") for non-commercial use; you may not use this // file except in compliance with the License. You may obtain a copy of the // License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // ============================================================================> #pragma once #ifndef ZTD_TEXT_ENCODING_ERROR_HPP #define ZTD_TEXT_ENCODING_ERROR_HPP #include <ztd/text/version.hpp> #include <ztd/text/char8_t.hpp> #include <ztd/text/unicode_code_point.hpp> #include <ztd/text/detail/to_underlying.hpp> #include <cstddef> #include <system_error> #include <type_traits> #include <string> #include <exception> #include <array> namespace ztd { namespace text { ZTD_TEXT_INLINE_ABI_NAMESPACE_OPEN_I_ ////// /// @addtogroup ztd_text_encoding_error ztd::text::encoding_error /// @brief This enumeration describes the kind of failures that can happen in ztd_text_transcode, /// ztd_text_decode, ztd_text_encode, and lower-level operations. /// @{ ////// ////// /// @brief Describes a failure to encode, decode, transcode, or count, for four core various reasons. /// /// @remarks This does not cover specific failures, like if a sequence was overlong (e.g., UTF-8) or if an encode /// operation produced an uunpaired surrogate value (e.g. UTF-16). ////// enum class encoding_error : int { ////// /// @brief The okay status; everything is fine. /// /// @remarks This does not necessarily mean an error handler was not called. An error handler can set the /// error code to ztd::text::encoding_error::ok after performing corrective action: see /// ztd::text::replacement_handler for an example. ////// ok = 0x00, ////// /// Input contains ill-formed sequences. This means there were available units of input to read, but what was /// read resulted in an error. ////// invalid_sequence = 0x01, ////// /// Input contains incomplete sequences. This means that the input was exhausted, without finding an invalid /// sequence, and therefore more input may be required. /// /// @remarks Depending on context, this may or may not be an error in your use case (e.g., reading part of an /// incomplete network buffer and waiting for more). See ztd::text::incomplete_handler as a way to aid with /// this use case. ////// incomplete_sequence = 0x02, ////// /// Output cannot receive the successfully encoded or decoded sequence. This means that, while there were no /// invalid or incomplete sequences in the input, the output ran out of space to receive it. /// /// @remarks Provide a bigger storage area or guarantee that it meets the minimum required size for potential /// output. This can be queried for an encoding by using ztd::text::max_code_points_v<the_encoding> for code /// points, and ztd::text::max_code_units_v<the_encoding> for code units. ////// insufficient_output_space = 0x03, #if 0 ////// /// Input contains overlong encoding sequence. This is specific to certain encodings, such as Unicode /// Transformation Formats like UTF-8 where different sequences can end up encoding the same character but are /// not allowed. ////// invalid_sequence = 0x04, ////// /// leading code unit is wrong ////// invalid_sequence = 0x05, ////// /// leading code units were correct, trailing code units were wrong ////// invalid_sequence = 0x06 #endif }; ////// /// @brief Converts an encoding_error to a string value. /// /// @returns A null-terminated string_view to the data. /// /// @remarks If a value outside of the allowed encoding_error is passed, then undefined behavior happens. ////// inline constexpr std::string_view to_name(encoding_error __error_code) { constexpr std::array<std::string_view, 4> __translation { { "ok", "invalid_sequence", "incomplete_sequence", "insufficient_output_space" } }; return __translation[static_cast<::std::size_t>(__detail::__to_underlying(__error_code))]; } ////// /// @} ////// ZTD_TEXT_INLINE_ABI_NAMESPACE_CLOSE_I_ }} // namespace ztd::text #endif // ZTD_TEXT_ENCODING_ERROR_HPP
38.591241
115
0.682239
vector-of-bool
9c797df7d5706dd486efcb8177dc4faf27e33af4
11,829
hpp
C++
recipes-cgl/cgl/cgl/src/CglGMI/CglGMIParam.hpp
Justin790126/meta-coinor
0180187c583b3a6fd0a8dac7c85ac1bd89bf8cc9
[ "MIT" ]
null
null
null
recipes-cgl/cgl/cgl/src/CglGMI/CglGMIParam.hpp
Justin790126/meta-coinor
0180187c583b3a6fd0a8dac7c85ac1bd89bf8cc9
[ "MIT" ]
null
null
null
recipes-cgl/cgl/cgl/src/CglGMI/CglGMIParam.hpp
Justin790126/meta-coinor
0180187c583b3a6fd0a8dac7c85ac1bd89bf8cc9
[ "MIT" ]
null
null
null
// Name: CglGMIParam.hpp // Author: Giacomo Nannicini // Singapore University of Technology and Design // email: nannicini@sutd.edu.sg // based on CglRedSplitParam.hpp by Francois Margot // Date: 11/17/09 //----------------------------------------------------------------------------- // Copyright (C) 2009, Giacomo Nannicini and others. All Rights Reserved. #ifndef CglGMIParam_H #define CglGMIParam_H #include "CglParam.hpp" /**@name CglGMI Parameters */ //@{ /** Class collecting parameters for the GMI cut generator. Parameters of the generator are listed below. Modifying the default values for parameters other than the last four might result in invalid cuts. - MAXDYN: Maximum ratio between largest and smallest non zero coefficients in a cut. See method setMAXDYN(). - EPS_ELIM: Precision for deciding if a coefficient is zero when eliminating slack variables. See method setEPS_ELIM(). - MINVIOL: Minimum violation for the current basic solution in a generated cut. See method setMINVIOL(). - USE_INTSLACKS: Use integer slacks to generate cuts. (not implemented yet, will be in the future). See method setUSE_INTSLACKS(). - AWAY: Look only at basic integer variables whose current value is at least this value away from being integer. See method setAway(). - CHECK_DUPLICATES: Should we check for duplicates when adding a cut to the collection? Can be slow. Default 0 - do not check, add cuts anyway. - CLEAN_PROC: Cleaning procedure that should be used. Look below at the enumeration CleaningProcedure for possible values. - INTEGRAL_SCALE_CONT: If we try to scale cut coefficients so that they become integral, do we also scale on continuous variables? Default 0 - do not scale continuous vars. Used only if CLEAN_PROC does integral scaling. - ENFORCE_SCALING: Discard badly scaled cuts, or keep them (unscaled). Default 1 - yes. */ //@} class CGLLIB_EXPORT CglGMIParam : public CglParam { public: /**@name Enumerations */ enum CleaningProcedure{ /* CglLandP procedure I */ CP_CGLLANDP1, /* CglLandP procedure II */ CP_CGLLANDP2, /* CglRedSplit procedure I */ CP_CGLREDSPLIT, /* Only integral cuts, i.e. cuts with integral coefficients */ CP_INTEGRAL_CUTS, /* CglLandP procedure I with integral scaling */ CP_CGLLANDP1_INT, /* CglLandP procedure I with scaling of the max element to 1 if possible */ CP_CGLLANDP1_SCALEMAX, /* CglLandP procedure I with scaling of the rhs to 1 if possible */ CP_CGLLANDP1_SCALERHS }; /**@name Set/get methods */ //@{ /** Aliases for parameter get/set method in the base class CglParam */ /** Value for Infinity. Default: DBL_MAX */ inline void setInfinity(double value) {setINFINIT(value);} inline double getInfinity() const {return INFINIT;} /** Epsilon for comparing numbers. Default: 1.0e-6 */ inline void setEps(double value) {setEPS(value);} inline double getEps() const {return EPS;} /** Epsilon for zeroing out coefficients. Default: 1.0e-5 */ inline void setEpsCoeff(double value) {setEPS_COEFF(value);} inline double getEpsCoeff() const {return EPS_COEFF;} /** Maximum support of the cutting planes. Default: INT_MAX */ inline void setMaxSupport(int value) {setMAX_SUPPORT(value);} inline int getMaxSupport() const {return MAX_SUPPORT;} /** Alias for consistency with our naming scheme */ inline void setMaxSupportAbs(int value) {setMAX_SUPPORT(value);} inline int getMaxSupportAbs() const {return MAX_SUPPORT;} inline int getMAX_SUPPORT_ABS() const {return MAX_SUPPORT;} /** Set AWAY, the minimum distance from being integer used for selecting rows for cut generation; all rows whose pivot variable should be integer but is more than away from integrality will be selected; Default: 0.005 */ virtual void setAway(double value); /** Get value of away */ inline double getAway() const {return AWAY;} /// Aliases inline void setAWAY(double value) {setAway(value);} inline double getAWAY() const {return AWAY;} /** Set the value of EPS_ELIM, epsilon for values of coefficients when eliminating slack variables; Default: 0 */ virtual void setEPS_ELIM(double value); /** Get the value of EPS_ELIM */ inline double getEPS_ELIM() const {return EPS_ELIM;} /// Aliases inline void setEpsElim(double value) {setEPS_ELIM(value);} inline double getEpsElim() const {return EPS_ELIM;} /** Set EPS_RELAX_ABS */ virtual void setEPS_RELAX_ABS(double value); /** Get value of EPS_RELAX_ABS */ inline double getEPS_RELAX_ABS() const {return EPS_RELAX_ABS;} /// Aliases inline void setEpsRelaxAbs(double value) {setEPS_RELAX_ABS(value);} inline double getEpsRelaxAbs() const {return EPS_RELAX_ABS;} /** Set EPS_RELAX_REL */ virtual void setEPS_RELAX_REL(double value); /** Get value of EPS_RELAX_REL */ inline double getEPS_RELAX_REL() const {return EPS_RELAX_REL;} /// Aliases inline void setEpsRelaxRel(double value) {setEPS_RELAX_REL(value);} inline double getEpsRelaxRel() const {return EPS_RELAX_REL;} // Set the maximum ratio between largest and smallest non zero // coefficients in a cut. Default: 1e6. virtual void setMAXDYN(double value); /** Get the value of MAXDYN */ inline double getMAXDYN() const {return MAXDYN;} /// Aliases inline void setMaxDyn(double value) {setMAXDYN(value);} inline double getMaxDyn() const {return MAXDYN;} /** Set the value of MINVIOL, the minimum violation for the current basic solution in a generated cut. Default: 1e-7 */ virtual void setMINVIOL(double value); /** Get the value of MINVIOL */ inline double getMINVIOL() const {return MINVIOL;} /// Aliases inline void setMinViol(double value) {setMINVIOL(value);} inline double getMinViol() const {return MINVIOL;} /** Set the value of MAX_SUPPORT_REL, the factor contributing to the maximum support relative to the number of columns. Maximum allowed support is: MAX_SUPPORT_ABS + MAX_SUPPORT_REL*ncols. Default: 0.1 */ virtual void setMAX_SUPPORT_REL(double value); /** Get the value of MINVIOL */ inline double getMAX_SUPPORT_REL() const {return MAX_SUPPORT_REL;} /// Aliases inline void setMaxSupportRel(double value) {setMAX_SUPPORT_REL(value);} inline double getMaxSupportRel() const {return MAX_SUPPORT_REL;} /** Set the value of USE_INTSLACKS. Default: 0 */ virtual void setUSE_INTSLACKS(bool value); /** Get the value of USE_INTSLACKS */ inline bool getUSE_INTSLACKS() const {return USE_INTSLACKS;} /// Aliases inline void setUseIntSlacks(bool value) {setUSE_INTSLACKS(value);} inline int getUseIntSlacks() const {return USE_INTSLACKS;} /** Set the value of CHECK_DUPLICATES. Default: 0 */ virtual void setCHECK_DUPLICATES(bool value); /** Get the value of CHECK_DUPLICATES */ inline bool getCHECK_DUPLICATES() const {return CHECK_DUPLICATES;} /// Aliases inline void setCheckDuplicates(bool value) {setCHECK_DUPLICATES(value);} inline bool getCheckDuplicates() const {return CHECK_DUPLICATES;} /** Set the value of CLEAN_PROC. Default: CP_CGLLANDP1 */ virtual void setCLEAN_PROC(CleaningProcedure value); /** Get the value of CLEAN_PROC. */ inline CleaningProcedure getCLEAN_PROC() const {return CLEAN_PROC;} /// Aliases inline void setCleanProc(CleaningProcedure value) {setCLEAN_PROC(value);} inline CleaningProcedure getCleaningProcedure() const {return CLEAN_PROC;} /** Set the value of INTEGRAL_SCALE_CONT. Default: 0 */ virtual void setINTEGRAL_SCALE_CONT(bool value); /** Get the value of INTEGRAL_SCALE_CONT. */ inline bool getINTEGRAL_SCALE_CONT() const {return INTEGRAL_SCALE_CONT;} /// Aliases inline void setIntegralScaleCont(bool value) {setINTEGRAL_SCALE_CONT(value);} inline bool getIntegralScaleCont() const {return INTEGRAL_SCALE_CONT;} /** Set the value of ENFORCE_SCALING. Default: 1 */ virtual void setENFORCE_SCALING(bool value); /** Get the value of ENFORCE_SCALING. */ inline bool getENFORCE_SCALING() const {return ENFORCE_SCALING;} /// Aliases inline void setEnforceScaling(bool value) {setENFORCE_SCALING(value);} inline bool getEnforcescaling() const {return ENFORCE_SCALING;} //@} /**@name Constructors and destructors */ //@{ /// Default constructor CglGMIParam(double eps = 1e-12, double away = 0.005, double eps_coeff = 1e-11, double eps_elim = 0, double eps_relax_abs = 1e-11, double eps_relax_rel = 1e-13, double max_dyn = 1e6, double min_viol = 1e-4, int max_supp_abs = 1000, double max_supp_rel = 0.1, CleaningProcedure clean_proc = CP_CGLLANDP1, bool use_int_slacks = false, bool check_duplicates = false, bool integral_scale_cont = false, bool enforce_scaling = true); /// Constructor from CglParam CglGMIParam(CglParam &source, double away = 0.005, double eps_elim = 1e-12, double eps_relax_abs = 1e-11, double eps_relax_rel = 1e-13, double max_dyn = 1e6, double min_viol = 1e-4, double max_supp_rel = 0.1, CleaningProcedure clean_proc = CP_CGLLANDP1, bool use_int_slacks = false, bool check_duplicates = false, bool integral_scale_cont = false, bool enforce_scaling = true); /// Copy constructor CglGMIParam(const CglGMIParam &source); /// Clone virtual CglGMIParam* clone() const; /// Assignment operator virtual CglGMIParam& operator=(const CglGMIParam &rhs); /// Destructor virtual ~CglGMIParam(); //@} protected: /**@name Parameters */ //@{ /** Use row only if pivot variable should be integer but is more than AWAY from being integer. */ double AWAY; /** Epsilon for value of coefficients when eliminating slack variables. Default: 0. */ double EPS_ELIM; /** Value added to the right hand side of each generated cut to relax it. Default: 1e-11 */ double EPS_RELAX_ABS; /** For a generated cut with right hand side rhs_val, EPS_RELAX_EPS * fabs(rhs_val) is used to relax the constraint. Default: 1.e-13 */ double EPS_RELAX_REL; /** Maximum ratio between largest and smallest non zero coefficients in a cut. Default: 1e6. */ double MAXDYN; /** Minimum violation for the current basic solution in a generated cut. Default: 1e-4. */ double MINVIOL; /** Maximum support relative to number of columns. Must be between 0 and 1. Default: 0. */ double MAX_SUPPORT_REL; /** Which cleaning procedure should be used? */ CleaningProcedure CLEAN_PROC; /** Use integer slacks to generate cuts if USE_INTSLACKS = 1. Default: 0. */ bool USE_INTSLACKS; /** Check for duplicates when adding the cut to the collection? */ bool CHECK_DUPLICATES; /** Should we try to rescale cut coefficients on continuous variables so that they become integral, or do we only rescale coefficients on integral variables? Used only by cleaning procedure that try the integral scaling. */ bool INTEGRAL_SCALE_CONT; /** Should we discard badly scaled cuts (according to the scaling procedure in use)? If false, CglGMI::scaleCut always returns true, even though it still scales cuts whenever possible, but not cut is rejected for scaling. Default true. Used only by cleaning procedure that try to scale. */ bool ENFORCE_SCALING; //@} }; #endif
37.671975
79
0.692958
Justin790126
9c7c0f8e33dd30d0e296c048c48d704cc8af5cc0
1,113
hpp
C++
SDK/ARKSurvivalEvolved_Buff_GasBursts_Volcano_classes.hpp
2bite/ARK-SDK
c38ca9925309516b2093ad8c3a70ed9489e1d573
[ "MIT" ]
10
2020-02-17T19:08:46.000Z
2021-07-31T11:07:19.000Z
SDK/ARKSurvivalEvolved_Buff_GasBursts_Volcano_classes.hpp
2bite/ARK-SDK
c38ca9925309516b2093ad8c3a70ed9489e1d573
[ "MIT" ]
9
2020-02-17T18:15:41.000Z
2021-06-06T19:17:34.000Z
SDK/ARKSurvivalEvolved_Buff_GasBursts_Volcano_classes.hpp
2bite/ARK-SDK
c38ca9925309516b2093ad8c3a70ed9489e1d573
[ "MIT" ]
3
2020-07-22T17:42:07.000Z
2021-06-19T17:16:13.000Z
#pragma once // ARKSurvivalEvolved (329.9) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "ARKSurvivalEvolved_Buff_GasBursts_Volcano_structs.hpp" namespace sdk { //--------------------------------------------------------------------------- //Classes //--------------------------------------------------------------------------- // BlueprintGeneratedClass Buff_GasBursts_Volcano.Buff_GasBursts_Volcano_C // 0x0000 (0x0960 - 0x0960) class ABuff_GasBursts_Volcano_C : public ABuff_Base_GasMaskable_C { public: static UClass* StaticClass() { static auto ptr = UObject::FindClass("BlueprintGeneratedClass Buff_GasBursts_Volcano.Buff_GasBursts_Volcano_C"); return ptr; } float BPAdjustStatusValueModification(class UPrimalCharacterStatusComponent** ForComponent, TEnumAsByte<EPrimalCharacterStatusValue>* ValueType, float* InAmount, class UClass** DamageTypeClass, bool* bManualModification); void BPDeactivated(class AActor** ForInstigator); void UserConstructionScript(); void ExecuteUbergraph_Buff_GasBursts_Volcano(int EntryPoint); }; } #ifdef _MSC_VER #pragma pack(pop) #endif
26.5
222
0.699012
2bite
9c7d0916457b3e049acac543b2a436029bcf7d3e
7,930
cxx
C++
ThirdParty/Havok/include/Common/Compat/Patches/2013_3/hkdPatches_2013_3.cxx
wobbier/source3-engine
f59df759ee197aef5191cf13768c303c6ed17bf5
[ "MIT" ]
11
2016-08-02T03:40:36.000Z
2022-03-15T13:41:29.000Z
ThirdParty/Havok/include/Common/Compat/Patches/2013_3/hkdPatches_2013_3.cxx
wobbier/source3-engine
f59df759ee197aef5191cf13768c303c6ed17bf5
[ "MIT" ]
null
null
null
ThirdParty/Havok/include/Common/Compat/Patches/2013_3/hkdPatches_2013_3.cxx
wobbier/source3-engine
f59df759ee197aef5191cf13768c303c6ed17bf5
[ "MIT" ]
8
2017-03-17T05:59:25.000Z
2021-02-27T08:51:46.000Z
/* * * Confidential Information of Telekinesys Research Limited (t/a Havok). Not for disclosure or distribution without Havok's * prior written consent. This software contains code, techniques and know-how which is confidential and proprietary to Havok. * Product and Trade Secret source code contains trade secrets of Havok. Havok Software (C) Copyright 1999-2014 Telekinesys Research Limited t/a Havok. All Rights Reserved. Use of this software is subject to the terms of an end user license agreement. * */ // Destruction specific product patches applied to release 2013_3. // This file is #included by hkdPatches_2013_3.cpp HK_PATCH_BEGIN("hkdShape", 5, "hkdShape", 6) HK_PATCH_MEMBER_ADDED_BYTE("lockDeformation", 0) HK_PATCH_END() HK_PATCH_BEGIN("hkdAction", 0, "hkdAction", 1) HK_PATCH_MEMBER_ADDED_BYTE("priority", 100) HK_PATCH_END() HK_PATCH_BEGIN(HK_NULL, HK_CLASS_ADDED, "hkdConvexHullAction", 0) HK_PATCH_PARENT_SET(HK_NULL, "hkdAction") HK_PATCH_MEMBER_ADDED_BYTE("method", 0) HK_PATCH_MEMBER_ADDED_BYTE("self", 1) HK_PATCH_MEMBER_ADDED_BYTE("recurse", 1) HK_PATCH_DEPENDS("hkBaseObject", 0) HK_PATCH_DEPENDS("hkdAction", 0) HK_PATCH_DEPENDS("hkReferencedObject", 0) HK_PATCH_END() HK_PATCH_BEGIN("hkdRemoveWeakConnectionsAction", 0, "hkdRemoveWeakConnectionsAction", 1) HK_PATCH_FUNCTION(hkdRemoveWeakConnectionsAction_0_to_1) HK_PATCH_DEPENDS("hkdAction", 1) HK_PATCH_END() HK_PATCH_BEGIN("hkdConvexDecompositionAction", 3, "hkdConvexDecompositionAction", 4) HK_PATCH_FUNCTION(hkdConvexDecompositionAction_3_to_4) HK_PATCH_DEPENDS("hkdAction", 1) HK_PATCH_END() HK_PATCH_BEGIN("hkdSplitByPhysicsIslandsAction", 0, "hkdSplitByPhysicsIslandsAction", 1) HK_PATCH_FUNCTION(hkdSplitByPhysicsIslandsAction_0_to_1) HK_PATCH_DEPENDS("hkdAction", 1) HK_PATCH_END() HK_PATCH_BEGIN("hkdGlueFixedPiecesAction", 0, "hkdGlueFixedPiecesAction", 1) HK_PATCH_FUNCTION(hkdGlueFixedPiecesAction_0_to_1) HK_PATCH_DEPENDS("hkdAction", 1) HK_PATCH_END() HK_PATCH_BEGIN("hkdDecorateFractureFaceAction", 8, "hkdDecorateFractureFaceAction", 9) HK_PATCH_FUNCTION(hkdDecorateFractureFaceAction_8_to_9) HK_PATCH_DEPENDS("hkdAction", 1) HK_PATCH_END() HK_PATCH_BEGIN("hkdMeshSimplifierAction", 6, "hkdMeshSimplifierAction", 7) HK_PATCH_FUNCTION(hkdMeshSimplifierAction_6_to_7) HK_PATCH_DEPENDS("hkdAction", 1) HK_PATCH_END() HK_PATCH_BEGIN("hkdFlattenHierarchyAction", 0, "hkdFlattenHierarchyAction", 1) HK_PATCH_FUNCTION(hkdFlattenHierarchyAction_0_to_1) HK_PATCH_DEPENDS("hkdAction", 1) HK_PATCH_END() HK_PATCH_BEGIN("hkdDecalMapAction", 0, "hkdDecalMapAction", 1) HK_PATCH_FUNCTION(hkdDecalMapAction_0_to_1) HK_PATCH_DEPENDS("hkdAction", 1) HK_PATCH_END() HK_PATCH_BEGIN("hkdShareVerticesAction", 0, "hkdShareVerticesAction", 1) HK_PATCH_FUNCTION(hkdShareVerticesAction_0_to_1) HK_PATCH_DEPENDS("hkdAction", 1) HK_PATCH_END() HK_PATCH_BEGIN("hkdMeshOptimizerInfo", 0, "hkdMeshOptimizerInfo", 1) HK_PATCH_MEMBER_ADDED_BYTE("limitNumSectionBones", 0) HK_PATCH_END() HK_PATCH_BEGIN(HK_NULL, HK_CLASS_ADDED, "hkdPrepareForDynamicFractureAction", 0) HK_PATCH_PARENT_SET(HK_NULL, "hkdAction") HK_PATCH_MEMBER_ADDED_BYTE("createAccelerationMeshes", 1) HK_PATCH_DEPENDS("hkBaseObject", 0) HK_PATCH_DEPENDS("hkdAction", 1) HK_PATCH_DEPENDS("hkReferencedObject", 0) HK_PATCH_END() HK_PATCH_BEGIN("hkdImageBasedFracture", 0, "hkdImageBasedFracture", 1) HK_PATCH_MEMBER_ADDED_REAL("cutoutSideExpansion", 0.100000f) HK_PATCH_MEMBER_ADDED_BYTE("setFrameShapeFixed", 1) HK_PATCH_END() HK_PATCH_BEGIN("hkdImageBasedFracture", 1, "hkdImageBasedFracture", 2) HK_PATCH_MEMBER_ADDED_BYTE("outputDebugFiles", 0) HK_PATCH_MEMBER_DEFAULT_SET_REAL("normalAngleThreshold", 0.010000f) HK_PATCH_END() HK_PATCH_BEGIN(HK_NULL, HK_CLASS_ADDED, "hkdFxDebrisFracture", 0) HK_PATCH_PARENT_SET(HK_NULL, "hkdFracture") HK_PATCH_MEMBER_ADDED("templateDebris", TYPE_OBJECT, "hkdBreakableShape", 0) HK_PATCH_MEMBER_ADDED("templateDebrisUuid", TYPE_STRUCT, "hkUuid", 0) HK_PATCH_MEMBER_ADDED_INT("maxNumPieces", 100) HK_PATCH_MEMBER_ADDED_REAL("minLifeTime", 1.000000f) HK_PATCH_MEMBER_ADDED_REAL("maxLifeTime", 1.000000f) HK_PATCH_MEMBER_ADDED_REAL("minScale", 1.000000f) HK_PATCH_MEMBER_ADDED_REAL("maxScale", 1.000000f) HK_PATCH_MEMBER_ADDED_REAL("density", 1.000000f) HK_PATCH_MEMBER_ADDED_INT("userData", 0) HK_PATCH_DEPENDS("hkdFracture", 4) HK_PATCH_DEPENDS("hkBaseObject", 0) HK_PATCH_DEPENDS("hkpBreakableShape", 1) HK_PATCH_DEPENDS("hkdBreakableShape", 6) HK_PATCH_DEPENDS("hkReferencedObject", 0) HK_PATCH_DEPENDS("hkUuid", 1) HK_PATCH_END() HK_PATCH_BEGIN("hkdFlattenHierarchyAction", 1, "hkdFlattenHierarchyAction", 2) HK_PATCH_MEMBER_ADDED_BYTE("createGraphicsCompound", 0) HK_PATCH_MEMBER_ADDED_BYTE("createPhysicsCompound", 0) HK_PATCH_END() HK_PATCH_BEGIN("hkdFracture", 4, "hkdFracture", 5) HK_PATCH_MEMBER_REMOVED("allowOpenMeshes", TYPE_BYTE, HK_NULL, 0) HK_PATCH_END() HK_PATCH_BEGIN("hkdDecorateFractureFaceActionGlobalDecorationData", 3, "hkdDecorateFractureFaceActionGlobalDecorationData", 4) HK_PATCH_MEMBER_RENAMED("rawTransforms", "rawTransformsOld") HK_PATCH_MEMBER_ADDED("rawTransforms", TYPE_ARRAY_INT, HK_NULL, 0) HK_PATCH_FUNCTION(hkdDecorateFractureFaceActionGlobalDecorationData_3_to_4) HK_PATCH_MEMBER_REMOVED("rawTransformsOld", TYPE_ARRAY_REAL, HK_NULL, 0) HK_PATCH_END() HK_PATCH_BEGIN("hkdDeformableBreakableShapeBoneInfo", 1, "hkdDeformableBreakableShapeBoneInfo", 2) HK_PATCH_MEMBER_RENAMED("modelSpaceBindPoseTransform", "modelSpaceBindPoseTransformOld") HK_PATCH_MEMBER_ADDED("modelSpaceBindPoseTransform", TYPE_STRUCT, "hkQTransform", 0) HK_PATCH_FUNCTION(hkdDeformableBreakableShapeBoneInfo_1_to_2) HK_PATCH_MEMBER_REMOVED("modelSpaceBindPoseTransformOld", TYPE_STRUCT, "hkQTransformf", 0) HK_PATCH_DEPENDS("hkQTransformf", 0) HK_PATCH_DEPENDS("hkQTransform", 2) HK_PATCH_END() HK_PATCH_BEGIN("hkdShapeInstanceInfo", 4, "hkdShapeInstanceInfo", 5) HK_PATCH_MEMBER_RENAMED("transform", "transformOld") HK_PATCH_MEMBER_ADDED("transform", TYPE_STRUCT, "hkQTransform", 0) HK_PATCH_FUNCTION(hkdShapeInstanceInfo_4_to_5) HK_PATCH_MEMBER_REMOVED("transformOld", TYPE_STRUCT, "hkQTransformf", 0) HK_PATCH_DEPENDS("hkQTransformf", 0) HK_PATCH_DEPENDS("hkQTransform", 2) HK_PATCH_END() HK_PATCH_BEGIN("hkdDeformableBreakableShapePhysicsSkinInstance", 2, "hkdDeformableBreakableShapePhysicsSkinInstance", 3) HK_PATCH_MEMBER_RENAMED("modelSpaceBoneTransforms", "modelSpaceBoneTransformsOld") HK_PATCH_MEMBER_ADDED("modelSpaceBoneTransforms", TYPE_ARRAY_STRUCT, "hkQTransform", 0) HK_PATCH_FUNCTION(hkdDeformableBreakableShapePhysicsSkinInstance_2_to_3) HK_PATCH_MEMBER_REMOVED("modelSpaceBoneTransformsOld", TYPE_ARRAY_STRUCT, "hkQTransformf", 0) HK_PATCH_DEPENDS("hkQTransformf", 0) HK_PATCH_DEPENDS("hkQTransform", 2) HK_PATCH_END() HK_PATCH_BEGIN("hkdDeformableBreakableBodyMemento", 1, "hkdDeformableBreakableBodyMemento", 2) HK_PATCH_MEMBER_RENAMED("transforms", "transformsOld") HK_PATCH_MEMBER_ADDED("transforms", TYPE_ARRAY_STRUCT, "hkQTransform", 0) HK_PATCH_FUNCTION(hkdDeformableBreakableBodyMemento_1_to_2) HK_PATCH_MEMBER_REMOVED("transformsOld", TYPE_ARRAY_STRUCT, "hkQTransformf", 0) HK_PATCH_DEPENDS("hkQTransformf", 0) HK_PATCH_DEPENDS("hkQTransform", 2) HK_PATCH_END() /* * Havok SDK - NO SOURCE PC DOWNLOAD, BUILD(#20140907) * * Confidential Information of Havok. (C) Copyright 1999-2014 * Telekinesys Research Limited t/a Havok. All Rights Reserved. The Havok * Logo, and the Havok buzzsaw logo are trademarks of Havok. Title, ownership * rights, and intellectual property rights in the Havok software remain in * Havok and/or its suppliers. * * Use of this software for evaluation purposes is subject to and indicates * acceptance of the End User licence Agreement for this product. A copy of * the license is included with this software and is also available at www.havok.com/tryhavok. * */
43.571429
251
0.823077
wobbier
9c7f9cbaf88a9959eea7bfb55b988729f70323a3
2,677
cpp
C++
Plus7/Modules/Gfx/Src/SdlGl/GlBlendState.cpp
txfx/plus7
44df3622ea8abe296d921759144e5f0d630b2945
[ "MIT" ]
null
null
null
Plus7/Modules/Gfx/Src/SdlGl/GlBlendState.cpp
txfx/plus7
44df3622ea8abe296d921759144e5f0d630b2945
[ "MIT" ]
null
null
null
Plus7/Modules/Gfx/Src/SdlGl/GlBlendState.cpp
txfx/plus7
44df3622ea8abe296d921759144e5f0d630b2945
[ "MIT" ]
null
null
null
#include "SdlGl/GlBlendState.hpp" #include <Utils/Assert.hpp> namespace p7 { namespace gfx { namespace { GLenum ToGl(BlendFactor _mode) { switch (_mode) { case BlendFactor::Zero: return GL_ZERO; case BlendFactor::One: return GL_ONE; case BlendFactor::SrcColor: return GL_SRC_COLOR; case BlendFactor::OneMinusSrcColor: return GL_ONE_MINUS_SRC_COLOR; case BlendFactor::DstColor: return GL_DST_COLOR; case BlendFactor::OneMinusDstColor: return GL_ONE_MINUS_DST_COLOR; case BlendFactor::SrcAlpha: return GL_SRC_ALPHA; case BlendFactor::OneMinusSrcAlpha: return GL_ONE_MINUS_SRC_ALPHA; case BlendFactor::DstAlpha: return GL_DST_ALPHA; case BlendFactor::OneMinusDstAlpha: return GL_ONE_MINUS_DST_ALPHA; case BlendFactor::ConstColor: return GL_CONSTANT_COLOR; case BlendFactor::OneMinusConstColor: return GL_ONE_MINUS_CONSTANT_COLOR; case BlendFactor::ConstAlpha: return GL_CONSTANT_ALPHA; case BlendFactor::OneMinusConstAlpha: return GL_ONE_MINUS_CONSTANT_ALPHA; case BlendFactor::SrcAlphaSaturate: return GL_SRC_ALPHA_SATURATE; case BlendFactor::Src1Color: return GL_SRC1_COLOR; case BlendFactor::OneMinusSrc1Color: return GL_ONE_MINUS_SRC1_COLOR; case BlendFactor::Src1Alpha: return GL_SRC1_ALPHA; case BlendFactor::OneMinusSrc1Alpha: return GL_ONE_MINUS_SRC1_ALPHA; default: P7_ASSERT(false, "Unknown GL mode %d", _mode); return -1; } } GLenum ToGl(BlendOp _mode) { switch (_mode) { case BlendOp::Add: return GL_FUNC_ADD; case BlendOp::Subtract: return GL_FUNC_SUBTRACT; case BlendOp::ReverseSubtract: return GL_FUNC_REVERSE_SUBTRACT; case BlendOp::Min: return GL_MIN; case BlendOp::Max: return GL_MAX; default: P7_ASSERT(false, "Unknown GL mode %d", _mode); return -1; } } } // namespace GlBlendState::GlBlendState(const BlendProperties& _properties) : enable(_properties.enable) , srcRgb(ToGl(_properties.srcRgb)) , dstRgb(ToGl(_properties.dstRgb)) , opRgb(ToGl(_properties.opRgb)) , srcAlpha(ToGl(_properties.srcAlpha)) , dstAlpha(ToGl(_properties.dstAlpha)) , opAlpha(ToGl(_properties.opAlpha)) {} void GlBlendState::Bind() const { if (enable) { glEnable(GL_BLEND); glBlendFuncSeparate(srcRgb, dstRgb, srcAlpha, dstAlpha); glBlendEquationSeparate(opRgb, opAlpha); } else { glDisable(GL_BLEND); } } } // namespace gfx } // namespace p7
26.245098
64
0.676877
txfx
9c8491f5264122260f355e92073bad852f03aa9d
3,922
cpp
C++
core/test/SoftTimerTest.cpp
perimeno/LIO
62578bdee261735afa23f7c0c8437e927425aef6
[ "MIT" ]
25
2019-08-07T02:38:39.000Z
2022-01-14T03:13:58.000Z
core/test/SoftTimerTest.cpp
perimeno/LIO
62578bdee261735afa23f7c0c8437e927425aef6
[ "MIT" ]
6
2020-01-17T20:51:15.000Z
2021-03-11T12:38:29.000Z
core/test/SoftTimerTest.cpp
perimeno/LIO
62578bdee261735afa23f7c0c8437e927425aef6
[ "MIT" ]
2
2019-08-24T19:02:12.000Z
2020-06-11T06:14:34.000Z
#include <gtest/gtest.h> #include <gmock/gmock.h> #include <thread> #include <future> #include "SoftTimer.h" using namespace std; using namespace LIO; using testing::Return; ACTION_P(SignalCallback,promise){ promise->set_value(); } class SoftTimerTest:public testing::Test{ public: MOCK_METHOD0(timeoutCallback,void()); SoftTimer subject; promise<void> timerElapsedPromise; future<void> timerElapsed; SoftTimerTest():timerElapsed(timerElapsedPromise.get_future()){ ON_CALL(*this,timeoutCallback()).WillByDefault(SignalCallback(&timerElapsedPromise)); } }; TEST_F(SoftTimerTest,TimeoutWithoutCallback_NoProblem){ subject.SetTimeout(1ms); subject.Start(); this_thread::sleep_for(100ms); } TEST_F(SoftTimerTest,TimeoutWithCallback_ProperTiming){ EXPECT_CALL(*this,timeoutCallback).Times(1); subject.SetTimeout(10ms); subject.SetTimeoutCallback(bind(&SoftTimerTest::timeoutCallback,this)); auto start=chrono::steady_clock::now(); subject.Start(); timerElapsed.wait(); auto stop=chrono::steady_clock::now(); ASSERT_LT(stop-start,1s); ASSERT_GT(stop-start,10ms); } TEST_F(SoftTimerTest,NoTimeout_NoCallback){ EXPECT_CALL(*this,timeoutCallback).Times(0); subject.SetTimeout(10ms); subject.SetTimeoutCallback(bind(&SoftTimerTest::timeoutCallback,this)); subject.Start(); this_thread::sleep_for(5ms); subject.StopAndReset(); auto ret=timerElapsed.wait_for(100ms); ASSERT_EQ(ret,future_status::timeout); } TEST_F(SoftTimerTest,TimeoutWithCallback_MultipleStart){ EXPECT_CALL(*this,timeoutCallback).Times(1); subject.SetTimeout(10ms); subject.SetTimeoutCallback(bind(&SoftTimerTest::timeoutCallback,this)); auto start=chrono::steady_clock::now(); subject.Start(); subject.Start(); this_thread::sleep_for(5ms); subject.Start(); subject.Start(); timerElapsed.wait(); auto stop=chrono::steady_clock::now(); ASSERT_LT(stop-start,1s); ASSERT_GT(stop-start,10ms); } TEST_F(SoftTimerTest,TimeoutWithCallback_StartAfterTimeout){ EXPECT_CALL(*this,timeoutCallback).Times(1).WillOnce(SignalCallback(&timerElapsedPromise)); subject.SetTimeout(10ms); subject.SetTimeoutCallback(bind(&SoftTimerTest::timeoutCallback,this)); subject.Start(); timerElapsed.wait(); promise<void> run2; timerElapsed=run2.get_future(); EXPECT_CALL(*this,timeoutCallback).Times(1).WillOnce(SignalCallback(&run2)); auto start=chrono::steady_clock::now(); subject.Start(); timerElapsed.wait(); auto stop=chrono::steady_clock::now(); ASSERT_LT(stop-start,1s); ASSERT_GT(stop-start,10ms); } TEST_F(SoftTimerTest,TimeoutWithCallback_changeTimingAfterTimeout){ EXPECT_CALL(*this,timeoutCallback).Times(1).WillOnce(SignalCallback(&timerElapsedPromise)); subject.SetTimeout(10ms); subject.SetTimeoutCallback(bind(&SoftTimerTest::timeoutCallback,this)); subject.Start(); timerElapsed.wait(); promise<void> run2; timerElapsed=run2.get_future(); EXPECT_CALL(*this,timeoutCallback).Times(1).WillOnce(SignalCallback(&run2)); subject.SetTimeout(100ms); auto start=chrono::steady_clock::now(); subject.Start(); timerElapsed.wait(); auto stop=chrono::steady_clock::now(); ASSERT_LT(stop-start,1s); ASSERT_GT(stop-start,100ms); } TEST_F(SoftTimerTest,TimeoutWithCallback_ContinuousMode){ EXPECT_CALL(*this,timeoutCallback).Times(1).WillOnce(SignalCallback(&timerElapsedPromise)); subject.SetTimeout(10ms); subject.SetRepeatMode(BasicTimer::repeatMode::continuous); subject.SetTimeoutCallback(bind(&SoftTimerTest::timeoutCallback,this)); subject.Start(); timerElapsed.wait(); promise<void> run2; timerElapsed=run2.get_future(); EXPECT_CALL(*this,timeoutCallback).Times(1).WillOnce(SignalCallback(&run2)); timerElapsed.wait(); subject.StopAndReset(); }
33.810345
95
0.736614
perimeno
9c855d8c173cfb98705482064533bfa65db1cd3f
10,739
cpp
C++
src/passes/TrapMode.cpp
brion/binaryen
977aa84f357d051b0ddc60f204c6b743463c3c6f
[ "Apache-2.0" ]
null
null
null
src/passes/TrapMode.cpp
brion/binaryen
977aa84f357d051b0ddc60f204c6b743463c3c6f
[ "Apache-2.0" ]
null
null
null
src/passes/TrapMode.cpp
brion/binaryen
977aa84f357d051b0ddc60f204c6b743463c3c6f
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2017 WebAssembly Community Group participants * * 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. */ // // Pass that supports potentially-trapping wasm operations. // For example, integer division traps when dividing by zero, so this pass // generates a check and replaces the result with zero in that case. // #include "asm_v_wasm.h" #include "asmjs/shared-constants.h" #include "ir/trapping.h" #include "mixed_arena.h" #include "pass.h" #include "support/name.h" #include "wasm-builder.h" #include "wasm-printing.h" #include "wasm-type.h" #include "wasm.h" namespace wasm { Name I64S_REM("i64s-rem"); Name I64U_REM("i64u-rem"); Name I64S_DIV("i64s-div"); Name I64U_DIV("i64u-div"); Name getBinaryFuncName(Binary* curr) { switch (curr->op) { case RemSInt32: return I32S_REM; case RemUInt32: return I32U_REM; case DivSInt32: return I32S_DIV; case DivUInt32: return I32U_DIV; case RemSInt64: return I64S_REM; case RemUInt64: return I64U_REM; case DivSInt64: return I64S_DIV; case DivUInt64: return I64U_DIV; default: return Name(); } } Name getUnaryFuncName(Unary* curr) { switch (curr->op) { case TruncSFloat32ToInt32: return F32_TO_INT; case TruncUFloat32ToInt32: return F32_TO_UINT; case TruncSFloat32ToInt64: return F32_TO_INT64; case TruncUFloat32ToInt64: return F32_TO_UINT64; case TruncSFloat64ToInt32: return F64_TO_INT; case TruncUFloat64ToInt32: return F64_TO_UINT; case TruncSFloat64ToInt64: return F64_TO_INT64; case TruncUFloat64ToInt64: return F64_TO_UINT64; default: return Name(); } } bool isTruncOpSigned(UnaryOp op) { switch (op) { case TruncUFloat32ToInt32: case TruncUFloat32ToInt64: case TruncUFloat64ToInt32: case TruncUFloat64ToInt64: return false; default: return true; } } Function* generateBinaryFunc(Module& wasm, Binary* curr) { BinaryOp op = curr->op; Type type = curr->type; bool isI64 = type == i64; Builder builder(wasm); Expression* result = builder.makeBinary( op, builder.makeLocalGet(0, type), builder.makeLocalGet(1, type)); BinaryOp divSIntOp = isI64 ? DivSInt64 : DivSInt32; UnaryOp eqZOp = isI64 ? EqZInt64 : EqZInt32; Literal minLit = isI64 ? Literal(std::numeric_limits<int64_t>::min()) : Literal(std::numeric_limits<int32_t>::min()); Literal zeroLit = isI64 ? Literal(int64_t(0)) : Literal(int32_t(0)); if (op == divSIntOp) { // guard against signed division overflow BinaryOp eqOp = isI64 ? EqInt64 : EqInt32; Literal negLit = isI64 ? Literal(int64_t(-1)) : Literal(int32_t(-1)); result = builder.makeIf( builder.makeBinary( AndInt32, builder.makeBinary( eqOp, builder.makeLocalGet(0, type), builder.makeConst(minLit)), builder.makeBinary( eqOp, builder.makeLocalGet(1, type), builder.makeConst(negLit))), builder.makeConst(zeroLit), result); } auto func = new Function; func->name = getBinaryFuncName(curr); func->sig = Signature({type, type}, type); func->body = builder.makeIf(builder.makeUnary(eqZOp, builder.makeLocalGet(1, type)), builder.makeConst(zeroLit), result); return func; } template<typename IntType, typename FloatType> void makeClampLimitLiterals(Literal& iMin, Literal& fMin, Literal& fMax) { IntType minVal = std::numeric_limits<IntType>::min(); IntType maxVal = std::numeric_limits<IntType>::max(); iMin = Literal(minVal); fMin = Literal(FloatType(minVal) - 1); fMax = Literal(FloatType(maxVal) + 1); } Function* generateUnaryFunc(Module& wasm, Unary* curr) { Type type = curr->value->type; Type retType = curr->type; UnaryOp truncOp = curr->op; bool isF64 = type == f64; Builder builder(wasm); BinaryOp leOp = isF64 ? LeFloat64 : LeFloat32; BinaryOp geOp = isF64 ? GeFloat64 : GeFloat32; BinaryOp neOp = isF64 ? NeFloat64 : NeFloat32; Literal iMin, fMin, fMax; switch (truncOp) { case TruncSFloat32ToInt32: makeClampLimitLiterals<int32_t, float>(iMin, fMin, fMax); break; case TruncUFloat32ToInt32: makeClampLimitLiterals<uint32_t, float>(iMin, fMin, fMax); break; case TruncSFloat32ToInt64: makeClampLimitLiterals<int64_t, float>(iMin, fMin, fMax); break; case TruncUFloat32ToInt64: makeClampLimitLiterals<uint64_t, float>(iMin, fMin, fMax); break; case TruncSFloat64ToInt32: makeClampLimitLiterals<int32_t, double>(iMin, fMin, fMax); break; case TruncUFloat64ToInt32: makeClampLimitLiterals<uint32_t, double>(iMin, fMin, fMax); break; case TruncSFloat64ToInt64: makeClampLimitLiterals<int64_t, double>(iMin, fMin, fMax); break; case TruncUFloat64ToInt64: makeClampLimitLiterals<uint64_t, double>(iMin, fMin, fMax); break; default: WASM_UNREACHABLE("unexpected op"); } auto func = new Function; func->name = getUnaryFuncName(curr); func->sig = Signature(type, retType); func->body = builder.makeUnary(truncOp, builder.makeLocalGet(0, type)); // too small XXX this is different than asm.js, which does frem. here we // clamp, which is much simpler/faster, and similar to native builds func->body = builder.makeIf(builder.makeBinary(leOp, builder.makeLocalGet(0, type), builder.makeConst(fMin)), builder.makeConst(iMin), func->body); // too big XXX see above func->body = builder.makeIf( builder.makeBinary( geOp, builder.makeLocalGet(0, type), builder.makeConst(fMax)), // NB: min here as well. anything out of range => to the min builder.makeConst(iMin), func->body); // nan func->body = builder.makeIf( builder.makeBinary( neOp, builder.makeLocalGet(0, type), builder.makeLocalGet(0, type)), // NB: min here as well. anything invalid => to the min builder.makeConst(iMin), func->body); return func; } void ensureBinaryFunc(Binary* curr, Module& wasm, TrappingFunctionContainer& trappingFunctions) { Name name = getBinaryFuncName(curr); if (trappingFunctions.hasFunction(name)) { return; } trappingFunctions.addFunction(generateBinaryFunc(wasm, curr)); } void ensureUnaryFunc(Unary* curr, Module& wasm, TrappingFunctionContainer& trappingFunctions) { Name name = getUnaryFuncName(curr); if (trappingFunctions.hasFunction(name)) { return; } trappingFunctions.addFunction(generateUnaryFunc(wasm, curr)); } void ensureF64ToI64JSImport(TrappingFunctionContainer& trappingFunctions) { if (trappingFunctions.hasImport(F64_TO_INT)) { return; } // f64-to-int = asm2wasm.f64-to-int; auto import = new Function; import->name = F64_TO_INT; import->module = ASM2WASM; import->base = F64_TO_INT; import->sig = Signature(Type::f64, Type::i32); trappingFunctions.addImport(import); } Expression* makeTrappingBinary(Binary* curr, TrappingFunctionContainer& trappingFunctions) { Name name = getBinaryFuncName(curr); if (!name.is() || trappingFunctions.getMode() == TrapMode::Allow) { return curr; } // the wasm operation might trap if done over 0, so generate a safe call Type type = curr->type; Module& wasm = trappingFunctions.getModule(); Builder builder(wasm); ensureBinaryFunc(curr, wasm, trappingFunctions); return builder.makeCall(name, {curr->left, curr->right}, type); } Expression* makeTrappingUnary(Unary* curr, TrappingFunctionContainer& trappingFunctions) { Name name = getUnaryFuncName(curr); TrapMode mode = trappingFunctions.getMode(); if (!name.is() || mode == TrapMode::Allow) { return curr; } Module& wasm = trappingFunctions.getModule(); Builder builder(wasm); // WebAssembly traps on float-to-int overflows, but asm.js wouldn't, so we // must do something We can handle this in one of two ways: clamping, which is // fast, or JS, which is precisely like JS but in order to do that we do a // slow ffi If i64, there is no "JS" way to handle this, as no i64s in JS, so // always clamp if we don't allow traps asm.js doesn't have unsigned // f64-to-int, so just use the signed one. if (curr->type != i64 && mode == TrapMode::JS) { // WebAssembly traps on float-to-int overflows, but asm.js wouldn't, so we // must emulate that ensureF64ToI64JSImport(trappingFunctions); Expression* f64Value = ensureDouble(curr->value, wasm.allocator); return builder.makeCall(F64_TO_INT, {f64Value}, i32); } ensureUnaryFunc(curr, wasm, trappingFunctions); return builder.makeCall(name, {curr->value}, curr->type); } struct TrapModePass : public WalkerPass<PostWalker<TrapModePass>> { public: // Needs to be non-parallel so that visitModule gets called after visiting // each node in the module, so we can add the functions that we created. bool isFunctionParallel() override { return false; } TrapModePass(TrapMode mode) : mode(mode) { assert(mode != TrapMode::Allow); } Pass* create() override { return new TrapModePass(mode); } void visitUnary(Unary* curr) { replaceCurrent(makeTrappingUnary(curr, *trappingFunctions)); } void visitBinary(Binary* curr) { replaceCurrent(makeTrappingBinary(curr, *trappingFunctions)); } void visitModule(Module* curr) { trappingFunctions->addToModule(); } void doWalkModule(Module* module) { trappingFunctions = make_unique<TrappingFunctionContainer>(mode, *module); super::doWalkModule(module); } private: TrapMode mode; // Need to defer adding generated functions because adding functions while // iterating over existing functions causes problems. std::unique_ptr<TrappingFunctionContainer> trappingFunctions; }; Pass* createTrapModeClamp() { return new TrapModePass(TrapMode::Clamp); } Pass* createTrapModeJS() { return new TrapModePass(TrapMode::JS); } } // namespace wasm
32.740854
80
0.683676
brion
9c87c51a97c4421addfaa8e5ece97abaa99b33f4
949
hh
C++
build/x86/enums/Characteristic.hh
billionshang/gem5
18cc4294f32315595f865d07d1f33434e92b06b2
[ "BSD-3-Clause" ]
5
2019-12-12T16:26:09.000Z
2022-03-17T03:23:33.000Z
build/X86/enums/Characteristic.hh
zhoushuxin/impl_of_HPCA2018
594d807fb0c0712bb7766122c4efe3321d012687
[ "BSD-3-Clause" ]
1
2020-08-20T05:53:30.000Z
2020-08-20T05:53:30.000Z
build/X86/enums/Characteristic.hh
zhoushuxin/impl_of_HPCA2018
594d807fb0c0712bb7766122c4efe3321d012687
[ "BSD-3-Clause" ]
null
null
null
#ifndef __ENUM__Enums__Characteristic__ #define __ENUM__Enums__Characteristic__ namespace Enums { enum Characteristic { APM = 10, CDBoot = 15, CGA_Mono = 30, EDD = 19, EISA = 6, ESCD = 14, Flash = 11, Floppy_3_5_2_88MB = 25, Floppy_3_5_720KB = 24, Floppy_5_25_1_2MB = 23, Floppy_5_25_360KB = 22, ISA = 4, Keyboard8024 = 27, MCA = 5, NEC9800 = 20, NEC_PC_98 = 31, PCI = 7, PCMCIA = 8, PCMCIABoot = 18, PnP = 9, PrintScreen = 26, Printer = 29, SelectBoot = 16, Serial = 28, Shadow = 12, Socketed = 17, Toshiba = 21, Unknown = 2, Unsupported = 3, VL_Vesa = 13, Num_Characteristic = 30 }; extern const char *CharacteristicStrings[Num_Characteristic]; } #endif // __ENUM__Enums__Characteristic__
22.595238
61
0.531085
billionshang
9c8c5670a30b5ae9e953705bbe10b29b2c313ae6
1,265
hpp
C++
include/System/ComponentModel/TypeConverter_StandardValuesCollection.hpp
v0idp/virtuoso-codegen
6f560f04822c67f092d438a3f484249072c1d21d
[ "Unlicense" ]
null
null
null
include/System/ComponentModel/TypeConverter_StandardValuesCollection.hpp
v0idp/virtuoso-codegen
6f560f04822c67f092d438a3f484249072c1d21d
[ "Unlicense" ]
null
null
null
include/System/ComponentModel/TypeConverter_StandardValuesCollection.hpp
v0idp/virtuoso-codegen
6f560f04822c67f092d438a3f484249072c1d21d
[ "Unlicense" ]
1
2022-03-30T21:07:35.000Z
2022-03-30T21:07:35.000Z
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "beatsaber-hook/shared/utils/typedefs.h" #include "beatsaber-hook/shared/utils/byref.hpp" // Including type: System.ComponentModel.TypeConverter #include "System/ComponentModel/TypeConverter.hpp" // Completed includes #include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp" NEED_NO_BOX(::System::ComponentModel::TypeConverter::StandardValuesCollection); DEFINE_IL2CPP_ARG_TYPE(::System::ComponentModel::TypeConverter::StandardValuesCollection*, "System.ComponentModel", "TypeConverter/StandardValuesCollection"); // Type namespace: System.ComponentModel namespace System::ComponentModel { // Size: 0x10 #pragma pack(push, 1) // Autogenerated type: System.ComponentModel.TypeConverter/System.ComponentModel.StandardValuesCollection // [TokenAttribute] Offset: FFFFFFFF // [DefaultMemberAttribute] Offset: 69CF98 class TypeConverter::StandardValuesCollection : public ::Il2CppObject { public: }; // System.ComponentModel.TypeConverter/System.ComponentModel.StandardValuesCollection #pragma pack(pop) } #include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
46.851852
158
0.756522
v0idp
9c8e0164e2ae0912463351e1d0841ffae07f3294
8,902
hpp
C++
DxLibEngine/3rdparty/FastFunc.hpp
darknesswind/LiteSTG
ec24641948369e6ee1a3bdcc0d6b78515f1a0374
[ "MIT" ]
2
2015-09-11T08:17:20.000Z
2018-03-13T07:21:15.000Z
DxLibEngine/3rdparty/FastFunc.hpp
darknesswind/LiteSTG
ec24641948369e6ee1a3bdcc0d6b78515f1a0374
[ "MIT" ]
null
null
null
DxLibEngine/3rdparty/FastFunc.hpp
darknesswind/LiteSTG
ec24641948369e6ee1a3bdcc0d6b78515f1a0374
[ "MIT" ]
null
null
null
#ifndef SSVU_FASTFUNC #define SSVU_FASTFUNC #include <cstring> #include <type_traits> #include <cassert> #include <cstddef> #include <memory> #include <new> #include <utility> #ifndef constexpr #define constexpr const #endif #ifndef noexcept #define noexcept #endif namespace ssvu { #if _MSC_VER >= 1800 namespace Internal { class AnyClass; using AnyPtrThis = AnyClass*; using AnyPtrFunc = void(AnyClass::*)(); template<typename TReturn = void, typename... TArgs> using AnyPtrFuncT = TReturn(AnyClass::*)(TArgs...); template<typename TReturn = void, typename... TArgs> using AnyPtrStaticFuncT = TReturn(*)(TArgs...); constexpr std::size_t SingleMemFuncPtrSize{sizeof(void(AnyClass::*)())}; template<class TOut, class TIn> union HorribleUnion { TOut out; TIn in; }; template<class TOut, class TIn> inline TOut horrible_cast(TIn mIn) noexcept { HorribleUnion<TOut, TIn> u; static_assert(sizeof(TIn) == sizeof(u) && sizeof(TIn) == sizeof(TOut), "Cannot use horrible_cast<>"); u.in = mIn; return u.out; } template<class TOut, class TIn> inline TOut unsafe_horrible_cast(TIn mIn) noexcept { HorribleUnion<TOut, TIn> u; u.in = mIn; return u.out; } template<std::size_t TN> struct SimplifyMemFunc { template<class TThis, class TFunc> inline static AnyPtrThis convert(const TThis*, TFunc, AnyPtrFunc&) noexcept { static_assert(TN - 100, "Unsupported member function pointer on this compiler"); return 0; } }; template<> struct SimplifyMemFunc<SingleMemFuncPtrSize> { template<class TThis, class TFunc> inline static AnyPtrThis convert(const TThis* mThis, TFunc mFunc, AnyPtrFunc& mFuncOut) noexcept { mFuncOut = reinterpret_cast<AnyPtrFunc>(mFunc); return reinterpret_cast<AnyPtrThis>(const_cast<TThis*>(mThis)); } }; template<typename TReturn, typename... TArgs> struct Closure { private: using PtrFuncT = AnyPtrFuncT<TReturn, TArgs...>; using PtrStaticFuncT = AnyPtrStaticFuncT<TReturn, TArgs...>; AnyPtrThis ptrThis{nullptr}; AnyPtrFunc ptrFunction{nullptr}; public: template<class TThis, class TFunc> inline void bind(TThis* mThis, TFunc mFunc) noexcept { ptrThis = SimplifyMemFunc<sizeof(mFunc)>::convert(mThis, mFunc, ptrFunction); } template<class TThis, class TInvoker> inline void bind(TThis* mThis, TInvoker mInvoker, PtrStaticFuncT mFunc) noexcept { if(mFunc == nullptr) ptrFunction = nullptr; else bind(mThis, mInvoker); ptrThis = horrible_cast<AnyPtrThis>(mFunc); } inline bool operator==(std::nullptr_t) const noexcept { return ptrThis == nullptr && ptrFunction == nullptr; } inline bool operator==(const Closure& mRhs) const noexcept { return ptrThis == mRhs.ptrThis && ptrFunction == mRhs.ptrFunction; } inline bool operator==(PtrStaticFuncT mPtr) const noexcept { return mPtr == nullptr ? *this == nullptr : mPtr == reinterpret_cast<PtrStaticFuncT>(getStaticFunc()); } inline bool operator!=(std::nullptr_t) const noexcept { return !operator==(nullptr); } inline bool operator!=(const Closure& mRhs) const noexcept { return !operator==(mRhs); } inline bool operator!=(PtrStaticFuncT mPtr) const noexcept { return !operator==(mPtr); } inline bool operator<(const Closure& mRhs) const { return ptrThis != mRhs.ptrThis ? ptrThis < mRhs.ptrThis : std::memcmp(&ptrFunction, &mRhs.ptrFunction, sizeof(ptrFunction)) < 0; } inline bool operator>(const Closure& mRhs) const { return !operator<(mRhs); } inline std::size_t getHash() const noexcept { return reinterpret_cast<std::size_t>(ptrThis) ^ Internal::unsafe_horrible_cast<std::size_t>(ptrFunction); } inline AnyPtrThis getPtrThis() const noexcept { return ptrThis; } inline PtrFuncT getPtrFunction() const noexcept { return reinterpret_cast<PtrFuncT>(ptrFunction); } inline PtrStaticFuncT getStaticFunc() const noexcept { return horrible_cast<PtrStaticFuncT>(this); } }; template<typename TReturn, typename... TArgs> class FastFuncImpl { private: Closure<TReturn, TArgs...> closure; inline TReturn invokeStaticFunc(TArgs... mArgs) const { return (*(closure.getStaticFunc()))(std::forward<TArgs>(mArgs)...); } protected: using PtrStaticFuncT = AnyPtrStaticFuncT<TReturn, TArgs...>; template<class TThis, class TFunc> inline void bind(TThis* mThis, TFunc mFunc) noexcept { closure.bind(mThis, mFunc); } template<class TFunc> inline void bind(TFunc mFunc) noexcept { closure.bind(this, &FastFuncImpl::invokeStaticFunc, mFunc); } public: inline FastFuncImpl() noexcept = default; inline FastFuncImpl(std::nullptr_t) noexcept { } inline FastFuncImpl(PtrStaticFuncT mFunc) noexcept { bind(mFunc); } template<typename X, typename Y> inline FastFuncImpl(X* mThis, Y mFunc) noexcept { bind(mThis, mFunc); } inline FastFuncImpl& operator=(PtrStaticFuncT mFunc) noexcept { bind(mFunc); return *this; } inline TReturn operator()(TArgs... mArgs) const { return (closure.getPtrThis()->*(closure.getPtrFunction()))(std::forward<TArgs>(mArgs)...); } inline bool operator==(std::nullptr_t) const noexcept { return closure == nullptr; } inline bool operator==(const FastFuncImpl& mImpl) const noexcept { return closure == mImpl.closure; } inline bool operator==(PtrStaticFuncT mFuncPtr) const noexcept { return closure == mFuncPtr; } inline bool operator!=(std::nullptr_t) const noexcept { return !operator==(nullptr); } inline bool operator!=(const FastFuncImpl& mImpl) const noexcept { return !operator==(mImpl); } inline bool operator!=(PtrStaticFuncT mFuncPtr) const noexcept { return !operator==(mFuncPtr); } inline bool operator<(const FastFuncImpl& mImpl) const { return closure < mImpl.closure; } inline bool operator>(const FastFuncImpl& mImpl) const { return !operator<(mImpl); } }; } template<typename T> struct MemFuncToFunc; template<typename TReturn, typename TThis, typename... TArgs> struct MemFuncToFunc<TReturn(TThis::*)(TArgs...) const> { using Type = TReturn(*)(TArgs...); }; #define ENABLE_IF_CONV_TO_FUN_PTR(x) typename std::enable_if<std::is_constructible<typename MemFuncToFunc<decltype(&std::decay<x>::type::operator())>::Type, x>::value>::type* = nullptr #define ENABLE_IF_NOT_CONV_TO_FUN_PTR(x) typename std::enable_if<!std::is_constructible<typename MemFuncToFunc<decltype(&std::decay<x>::type::operator())>::Type, x>::value>::type* = nullptr #define ENABLE_IF_SAME_TYPE(x, y) typename = typename std::enable_if<!std::is_same<x, typename std::decay<y>::type>{}>::type template<typename T> class FastFunc; template<typename TReturn, typename... TArgs> class FastFunc<TReturn(TArgs...)> : public Internal::FastFuncImpl<TReturn, TArgs...> { private: std::shared_ptr<void> storage; template<typename T> inline static void funcDeleter(void* mPtr) { static_cast<T*>(mPtr)->~T(); operator delete(mPtr); } public: using BaseType = Internal::FastFuncImpl<TReturn, TArgs...>; using BaseType::operator =; using BaseType::operator (); // using BaseType::BaseType; inline FastFunc() noexcept = default; inline FastFunc(std::nullptr_t np) : BaseType(np) { } inline FastFunc(BaseType::PtrStaticFuncT mFunc) : BaseType(mFunc) { } template<typename X, typename Y> inline FastFunc(X* mThis, Y mFunc) : BaseType(mThis, mFunc) { } template<typename TFunc, ENABLE_IF_SAME_TYPE(FastFunc, TFunc)> inline FastFunc(TFunc&& mFunc, ENABLE_IF_CONV_TO_FUN_PTR(TFunc)) { using FuncType = typename std::decay<TFunc>::type; this->bind(&mFunc, &FuncType::operator()); } template<typename TFunc, ENABLE_IF_SAME_TYPE(FastFunc, TFunc)> inline FastFunc(TFunc&& mFunc, ENABLE_IF_NOT_CONV_TO_FUN_PTR(TFunc)) : storage(operator new(sizeof(TFunc)), funcDeleter<typename std::decay<TFunc>::type>) { using FuncType = typename std::decay<TFunc>::type; new (storage.get()) FuncType(std::forward<TFunc>(mFunc)); this->bind(storage.get(), &FuncType::operator()); } }; #undef ENABLE_IF_CONV_TO_FUN_PTR #undef ENABLE_IF_NOT_CONV_TO_FUN_PTR #undef ENABLE_IF_SAME_TYPE #else template<typename T> struct MemFuncToFunc; template<typename TReturn, typename TThis, typename TArgs> struct MemFuncToFunc<TReturn(TThis::*)(TArgs) const> { typedef TReturn(*Type)(TArgs); }; template<typename T> class FastFunc; template<typename TReturn, typename TArgs> class FastFunc<TReturn(TArgs)> { private: std::shared_ptr<void> storage; template<typename T> inline static void funcDeleter(void* mPtr) { static_cast<T*>(mPtr)->~T(); operator delete(mPtr); } public: inline FastFunc() noexcept { }; inline FastFunc(std::nullptr_t np) : BaseType(np) { } template<typename X, typename Y> inline FastFunc(X* mThis, Y mFunc) { } void operator()(TArgs) { } }; #undef ENABLE_IF_CONV_TO_FUN_PTR #undef ENABLE_IF_NOT_CONV_TO_FUN_PTR #undef ENABLE_IF_SAME_TYPE #endif } #endif
47.860215
237
0.722197
darknesswind
9c8faec10be00269a642a7d957b1bc3e8ea8eabc
2,343
cpp
C++
CodeForces-Contest/1276/B.cpp
Tech-Intellegent/CodeForces-Solution
2f291a38b80b8ff2a2595b2e526716468ff26bf8
[ "MIT" ]
1
2022-01-23T07:18:07.000Z
2022-01-23T07:18:07.000Z
CodeForces-Contest/1276/B.cpp
Tech-Intellegent/CodeForces-Solution
2f291a38b80b8ff2a2595b2e526716468ff26bf8
[ "MIT" ]
null
null
null
CodeForces-Contest/1276/B.cpp
Tech-Intellegent/CodeForces-Solution
2f291a38b80b8ff2a2595b2e526716468ff26bf8
[ "MIT" ]
1
2022-02-05T11:53:04.000Z
2022-02-05T11:53:04.000Z
#include<bits/stdc++.h> using namespace std; #define pii pair<int,int> #define pll pair<ll,ll> #define eb emplace_back #define ll long long #define nl '\n' #define deb(x) cerr<<#x" = "<<x<<nl #define in() ( { int a ; scanf("%d",&a); a; } ) const int N = 3e5 + 9; const int mod = 1e9 + 7; struct dsu { vector<int> par, rnk, size; int c; dsu(int n) : par(n+1), rnk(n+1,0), size(n+1,1), c(n) { for (int i = 1; i <= n; ++i) par[i] = i; } int find(int i) { return (par[i] == i ? i : (par[i] = find(par[i]))); } bool same(int i, int j) { return find(i) == find(j); } int get_size(int i) { return size[find(i)]; } int count() { return c; }///connected components int merge(int i, int j) { if ((i = find(i)) == (j = find(j))) return -1; else --c; if (rnk[i] > rnk[j]) swap(i, j); par[i] = j; size[j] += size[i]; if (rnk[i] == rnk[j]) rnk[j]++; return j; } }; ll yo(int n, dsu A, int a, int b, int ty) { //cout<<"asche\n"; ll sum=0, sqsum=0; vector<int> vis(n+1, 0); if(ty==0){ vis[a]=1; assert(A.get_size(a)==1); } if(ty==1){ vis[b]=1; assert(A.get_size(b)==1); } if(ty==2){ vis[a]=1, vis[b]=1; assert(A.get_size(a)==1); assert(A.get_size(b)==1); } for(int i=1; i<=n; i++){ int k=A.find(i); if(vis[k]==0){ vis[k]=1; int s=A.get_size(k); if(ty==0){ if(A.find(b)==k) s--; } if(ty==1){ if(A.find(a)==k) s--; } //deb(s); sum+=s; sqsum+=1LL*s*s; } } return sum*sum-sqsum; } int32_t main() { int t=in(); while(t--){ int n=in(), m=in(), a=in(), b=in(); dsu A(n), B(n), AB(n); for(int i=1; i<=m; i++){ int u=in(), v=in(); int dum; if(u==a||v==a){ } else A.merge(u, v); int dd; if(u==b||v==b){ } else B.merge(u, v); int dm; if((u==a||v==b)||(u==b||v==a)){ } else AB.merge(u, v); } ll ans=yo(n, A, a, b, 0)+yo(n, B, a, b, 1)-yo(n, AB, a, b, 2); assert(ans%2==0); assert(ans>=0); ans/=2; printf("%lld\n", ans); } return 0; }
23.908163
72
0.414853
Tech-Intellegent
9c987e59eae32e12af209dcda318a10226d51962
866
cpp
C++
Molecularity/Objects/RenderableGameObject.cpp
kyle-robinson/directx-game
ff5964a6edd3241b703409976f27d68205b9ddd3
[ "CC-BY-4.0" ]
1
2021-06-14T22:44:01.000Z
2021-06-14T22:44:01.000Z
Molecularity/Objects/RenderableGameObject.cpp
kyle-robinson/directx-game
ff5964a6edd3241b703409976f27d68205b9ddd3
[ "CC-BY-4.0" ]
null
null
null
Molecularity/Objects/RenderableGameObject.cpp
kyle-robinson/directx-game
ff5964a6edd3241b703409976f27d68205b9ddd3
[ "CC-BY-4.0" ]
1
2021-06-04T12:44:06.000Z
2021-06-04T12:44:06.000Z
#include "RenderableGameObject.h" #include "PhysicsModel.h" #include "Camera.h" bool RenderableGameObject::Initialize( const std::string& filePath, ID3D11Device* device, ID3D11DeviceContext* context, ConstantBuffer<CB_VS_matrix>& cb_vs_vertexshader ) { if ( !model.Initialize( filePath, device, context, cb_vs_vertexshader ) ) return false; physicsModel = std::make_shared<PhysicsModel>( this ); SetPosition( XMFLOAT3( 0.0f, 0.0f, 0.0f ) ); SetRotation( XMFLOAT3( 0.0f, 0.0f, 0.0f ) ); UpdateMatrix(); return true; } void RenderableGameObject::Draw() { model.Draw( worldMatrix ); } void RenderableGameObject::UpdateMatrix() { worldMatrix = XMMatrixScaling( scale.x, scale.y, scale.y ) * XMMatrixRotationRollPitchYaw( rotation.x, rotation.y, rotation.z ) * XMMatrixTranslation( position.x, position.y, position.z ); UpdateDirectionVectors(); }
26.242424
74
0.743649
kyle-robinson