hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
108
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
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
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
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
dca4a1757c98b6a03295d2ae7698c595e290363c
427
cpp
C++
AtCoder/AtCoder_Beginner_Contest_176/C_Step/main.cpp
sungmen/Acmicpc_Solve
0298a6aec84993a4d8767bd2c00490b7201e06a4
[ "MIT" ]
1
2020-07-08T23:16:19.000Z
2020-07-08T23:16:19.000Z
AtCoder/AtCoder_Beginner_Contest_176/C_Step/main.cpp
sungmen/Acmicpc_Solve
0298a6aec84993a4d8767bd2c00490b7201e06a4
[ "MIT" ]
1
2020-05-16T03:12:24.000Z
2020-05-16T03:14:42.000Z
AtCoder/AtCoder_Beginner_Contest_176/C_Step/main.cpp
sungmen/Acmicpc_Solve
0298a6aec84993a4d8767bd2c00490b7201e06a4
[ "MIT" ]
2
2020-05-16T03:25:16.000Z
2021-02-10T16:51:25.000Z
#include <bits/stdc++.h> using namespace std; int main() { ios_base::sync_with_stdio(false);cin.tie(nullptr);cout.tie(nullptr); int n;cin>>n; int before; long long sum = 0; for (int i = 0; i < n; i++) { int a; cin >> a; if(i==0) { before = a; } else { if(before > a) sum += (before - a); else before = a; } } cout << sum; }
22.473684
72
0.456674
sungmen
dca84e1837382a5d915962c1f8f563619001e9b6
393
hpp
C++
src/RenderSystem.Direct3D/PrerequisitesDirect3D.hpp
bis83/pomdog
133a9262958d539ae6d93664e6cb2207b5b6c7ff
[ "MIT" ]
null
null
null
src/RenderSystem.Direct3D/PrerequisitesDirect3D.hpp
bis83/pomdog
133a9262958d539ae6d93664e6cb2207b5b6c7ff
[ "MIT" ]
null
null
null
src/RenderSystem.Direct3D/PrerequisitesDirect3D.hpp
bis83/pomdog
133a9262958d539ae6d93664e6cb2207b5b6c7ff
[ "MIT" ]
null
null
null
// Copyright (c) 2013-2015 mogemimi. // Distributed under the MIT license. See LICENSE.md file for details. #ifndef POMDOG_PREREQUISITESDIRECT3D_373FDC61_HPP #define POMDOG_PREREQUISITESDIRECT3D_373FDC61_HPP #if defined(_XBOX_ONE) && defined(_TITLE) #include <d3dcompiler_x.h> #else #include <d3dcompiler.h> #include <d3dcommon.h> #endif #endif // POMDOG_PREREQUISITESDIRECT3D_373FDC61_HPP
26.2
70
0.80916
bis83
dcaeb731ec2a112ef61adb5b892de419a3edd2b6
11,227
cpp
C++
vireo/encode/h264.cpp
shahzadlone/vireo
73e7176d0255a9506b009c9ab8cc532ecd86e98c
[ "MIT" ]
890
2017-12-15T17:55:42.000Z
2022-03-27T07:46:49.000Z
vireo/encode/h264.cpp
shahzadlone/vireo
73e7176d0255a9506b009c9ab8cc532ecd86e98c
[ "MIT" ]
29
2017-12-16T21:49:08.000Z
2021-09-08T23:04:10.000Z
vireo/encode/h264.cpp
shahzadlone/vireo
73e7176d0255a9506b009c9ab8cc532ecd86e98c
[ "MIT" ]
88
2017-12-15T19:29:49.000Z
2022-03-21T00:59:29.000Z
/* * MIT License * * Copyright (c) 2017 Twitter * * 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 "vireo/base_cpp.h" #include "vireo/common/security.h" #include "vireo/encode/h264.h" #include "vireo/error/error.h" extern "C" { #include "x264.h" } #define X264_CSP X264_CSP_I420 #define X264_LOG_LEVEL X264_LOG_WARNING #define X264_NALU_LENGTH_SIZE 4 #define X264_PROFILE "main" #define X264_TUNE "ssim" static vireo::encode::VideoProfileType GetDefaultProfile(const int width, const int height) { auto min_dimension = min(width, height); if (min_dimension <= 480) { return vireo::encode::VideoProfileType::Baseline; } else if (min_dimension <= 720) { return vireo::encode::VideoProfileType::Main; } else { return vireo::encode::VideoProfileType::High; } } namespace vireo { using common::Data16; namespace encode { struct _H264 { unique_ptr<x264_t, decltype(&x264_encoder_close)> encoder = { NULL, [](x264_t* encoder) { if (encoder) x264_encoder_close(encoder); } }; functional::Video<frame::Frame> frames; uint32_t num_cached_frames = 0; uint32_t num_threads = 0; uint32_t max_delay = 0; static inline const char* const GetProfile(VideoProfileType profile) { THROW_IF(profile != VideoProfileType::Baseline && profile != VideoProfileType::Main && profile != VideoProfileType::High, Unsupported, "unsupported profile type"); switch (profile) { case VideoProfileType::Baseline: return "baseline"; case VideoProfileType::Main: return "main"; case VideoProfileType::High: return "high"; default: return "baseline"; } } }; H264::H264(const functional::Video<frame::Frame>& frames, float crf, uint32_t optimization, float fps, uint32_t max_bitrate, uint32_t thread_count) : H264(frames, H264Params(H264Params::ComputationalParams(optimization, thread_count), H264Params::RateControlParams(RCMethod::CRF, crf, max_bitrate), H264Params::GopParams(0), GetDefaultProfile(frames.settings().width, frames.settings().height), fps)) {}; H264::H264(const functional::Video<frame::Frame>& frames, const H264Params& params) : functional::DirectVideo<H264, Sample>(frames.a(), frames.b()), _this(new _H264()) { THROW_IF(frames.count() >= security::kMaxSampleCount, Unsafe); THROW_IF(params.computation.optimization < kH264MinOptimization || params.computation.optimization > kH264MaxOptimization, InvalidArguments); THROW_IF(params.fps < 0.0f, InvalidArguments); THROW_IF(params.rc.max_bitrate < 0.0f, InvalidArguments); THROW_IF(params.computation.thread_count < kH264MinThreadCount || params.computation.thread_count > kH264MaxThreadCount, InvalidArguments); THROW_IF(!security::valid_dimensions(frames.settings().width, frames.settings().height), Unsafe); THROW_IF(frames.settings().par_width != frames.settings().par_height, InvalidArguments); x264_param_t param; { // Params x264_param_default_preset(&param, x264_preset_names[params.computation.optimization], X264_TUNE); param.i_threads = params.computation.thread_count ? params.computation.thread_count : 1; param.i_log_level = X264_LOG_LEVEL; param.i_width = (int)((frames.settings().width + 1) / 2) * 2; param.i_height = (int)((frames.settings().height + 1) / 2) * 2; param.i_fps_num = (int)(params.fps * 1000.0f + 0.5f); param.i_fps_den = params.fps > 0.0f ? 1000 : 0.0; param.i_csp = X264_CSP; param.b_annexb = 0; param.b_repeat_headers = 0; param.b_vfr_input = 0; if (params.gop.num_bframes >= 0) { // if num_bframes < 0, use default settings param.i_bframe = params.gop.num_bframes; param.i_bframe_pyramid = params.gop.pyramid_mode; } if (param.i_bframe == 0) { // set these zerolatency settings in case number of b frames is 0, otherwise use default settings param.rc.i_lookahead = 0; param.i_sync_lookahead = 0; param.rc.b_mb_tree = 0; param.b_sliced_threads = 1; } if (!params.rc.stats_log_path.empty()) { if (!params.rc.is_second_pass) { param.rc.b_stat_write = true; param.rc.psz_stat_out = (char*)params.rc.stats_log_path.c_str(); } else { param.rc.b_stat_read = true; param.rc.psz_stat_in = (char*)params.rc.stats_log_path.c_str(); } param.rc.b_mb_tree = params.rc.enable_mb_tree; param.rc.i_lookahead = params.rc.look_ahead; param.rc.i_aq_mode = params.rc.aq_mode; param.rc.i_qp_min = params.rc.qp_min; param.i_frame_reference = params.gop.frame_references; param.analyse.b_mixed_references = params.rc.mixed_refs; param.analyse.i_trellis = params.rc.trellis; param.analyse.i_me_method = params.rc.me_method; param.analyse.i_me_range = 16; param.analyse.i_subpel_refine = params.rc.subpel_refine; param.i_keyint_max = params.gop.keyint_max; param.i_keyint_min = params.gop.keyint_min; param.b_sliced_threads = 0; param.i_lookahead_threads = 1; } switch (params.rc.rc_method) { case RCMethod::CRF: param.rc.i_rc_method = X264_RC_CRF; THROW_IF(params.rc.crf < kH264MinCRF || params.rc.crf > kH264MaxCRF, InvalidArguments); param.rc.f_rf_constant = params.rc.crf; if (params.rc.max_bitrate != 0.0) { param.rc.i_vbv_max_bitrate = params.rc.max_bitrate; param.rc.i_vbv_buffer_size = params.rc.max_bitrate; } break; case RCMethod::CBR: CHECK(params.rc.bitrate == params.rc.max_bitrate); param.rc.i_rc_method = X264_RC_ABR; param.rc.i_bitrate = params.rc.bitrate; param.rc.i_vbv_max_bitrate = params.rc.bitrate; param.rc.i_vbv_buffer_size = params.rc.buffer_size; param.rc.f_vbv_buffer_init = params.rc.buffer_init; break; case RCMethod::ABR: param.rc.i_rc_method = X264_RC_ABR; param.rc.i_bitrate = params.rc.bitrate; break; default: // USE CRF as default mode param.rc.i_rc_method = X264_RC_CRF; param.rc.f_rf_constant = 28.0f; break; } THROW_IF(x264_param_apply_profile(&param, _H264::GetProfile(params.profile)) < 0, InvalidArguments); } _this->frames = frames; _this->num_threads = params.computation.thread_count; _this->max_delay = params.computation.thread_count + params.rc.look_ahead + params.gop.num_bframes; { // Encoder _this->encoder.reset(x264_encoder_open(&param)); CHECK(_this->encoder); } _settings = frames.settings(); _settings.codec = settings::Video::Codec::H264; { x264_nal_t* nals; int count; THROW_IF(x264_encoder_headers(_this->encoder.get(), &nals, &count) < 0, InvalidArguments); CHECK(count >= 3); _settings.sps_pps = (header::SPS_PPS){ Data16(nals[0].p_payload + X264_NALU_LENGTH_SIZE, nals[0].i_payload - X264_NALU_LENGTH_SIZE, NULL), Data16(nals[1].p_payload + X264_NALU_LENGTH_SIZE, nals[1].i_payload - X264_NALU_LENGTH_SIZE, NULL), X264_NALU_LENGTH_SIZE }; } } H264::H264(const H264& h264) : functional::DirectVideo<H264, Sample>(h264.a(), h264.b(), h264.settings()), _this(h264._this) { } auto H264::operator()(uint32_t index) const -> Sample { THROW_IF(index >= count(), OutOfRange); THROW_IF(index >= _this->frames.count(), OutOfRange); x264_nal_t* nals = nullptr; int i_nals; x264_picture_t out_picture; int video_size = 0; auto has_more_frames_to_encode = [_this = _this, &index]() -> bool { return index + _this->num_cached_frames < _this->frames.count(); }; if (has_more_frames_to_encode()) { while (video_size == 0 && has_more_frames_to_encode()) { const frame::Frame frame = _this->frames(index + _this->num_cached_frames); const uint64_t pts = frame.pts; const frame::YUV yuv = frame.yuv(); x264_picture_t in_picture; x264_picture_init(&in_picture); in_picture.i_pts = pts; in_picture.img.i_csp = X264_CSP; in_picture.img.i_plane = 3; in_picture.img.plane[0] = (uint8_t*)yuv.plane(frame::Y).bytes().data(); in_picture.img.plane[1] = (uint8_t*)yuv.plane(frame::U).bytes().data(); in_picture.img.plane[2] = (uint8_t*)yuv.plane(frame::V).bytes().data(); in_picture.img.i_stride[0] = (int)yuv.plane(frame::Y).row(); in_picture.img.i_stride[1] = (int)yuv.plane(frame::U).row(); in_picture.img.i_stride[2] = (int)yuv.plane(frame::V).row(); video_size = x264_encoder_encode(_this->encoder.get(), &nals, &i_nals, &in_picture, &out_picture); _this->num_cached_frames += (video_size == 0); THROW_IF(_this->num_cached_frames > _this->max_delay, Unsupported); } } if (!has_more_frames_to_encode()) { CHECK(_this->num_cached_frames > 0); uint32_t thread = 0; while (video_size == 0 && (_this->num_threads == 0 || thread < _this->num_threads)) { CHECK(thread < kH264MaxThreadCount); video_size = x264_encoder_encode(_this->encoder.get(), &nals, &i_nals, nullptr, &out_picture); // flush out cached frames thread++; } _this->num_cached_frames--; } CHECK(video_size > 0); CHECK(nals); CHECK(i_nals != 0); CHECK(out_picture.i_pts >= 0); const auto video_nal = common::Data32(nals[0].p_payload, video_size, NULL); if (out_picture.b_keyframe) { common::Data16 sps_pps_data = _settings.sps_pps.as_extradata(header::SPS_PPS::ExtraDataType::avcc); uint32_t sps_pps_size = sps_pps_data.count(); uint32_t video_sample_data_size = sps_pps_size + video_size; common::Data32 video_sample_data = common::Data32(new uint8_t[video_sample_data_size], video_sample_data_size, [](uint8_t* p) { delete[] p; }); video_sample_data.copy(common::Data32(sps_pps_data.data(), sps_pps_size, nullptr)); video_sample_data.set_bounds(video_sample_data.a() + sps_pps_size, video_sample_data_size); video_sample_data.copy(video_nal); video_sample_data.set_bounds(0, video_sample_data_size); return Sample(out_picture.i_pts, out_picture.i_dts, (bool)out_picture.b_keyframe, SampleType::Video, video_sample_data); } else { return Sample(out_picture.i_pts, out_picture.i_dts, (bool)out_picture.b_keyframe, SampleType::Video, video_nal); } } }}
43.34749
258
0.703394
shahzadlone
dcaff48a13a08466dd426f5713284ae52db97bd7
62,756
cpp
C++
SOURCES/sim/fcc/fccmain.cpp
IsraelyFlightSimulator/Negev-Storm
86de63e195577339f6e4a94198bedd31833a8be8
[ "Unlicense" ]
1
2021-02-19T06:06:31.000Z
2021-02-19T06:06:31.000Z
src/sim/fcc/fccmain.cpp
markbb1957/FFalconSource
07b12e2c41a93fa3a95b912a2433a8056de5bc4d
[ "BSD-2-Clause" ]
null
null
null
src/sim/fcc/fccmain.cpp
markbb1957/FFalconSource
07b12e2c41a93fa3a95b912a2433a8056de5bc4d
[ "BSD-2-Clause" ]
2
2019-08-20T13:35:13.000Z
2021-04-24T07:32:04.000Z
#include "Graphics\Include\Render2D.h" #include "Graphics\Include\DrawBsp.h" #include "stdhdr.h" #include "entity.h" #include "PilotInputs.h" #include "simveh.h" #include "sms.h" #include "airframe.h" #include "object.h" #include "fsound.h" #include "soundfx.h" #include "simdrive.h" #include "mfd.h" #include "radar.h" #include "classtbl.h" #include "playerop.h" #include "navsystem.h" #include "commands.h" #include "hud.h" #include "fcc.h" #include "fault.h" #include "fack.h" #include "aircrft.h" #include "smsdraw.h" #include "airunit.h" #include "handoff.h" #include "otwdrive.h" //MI #include "radardoppler.h" //MI #include "missile.h" //MI #include "misslist.h" //MLR #include "getsimobjectdata.h" // MLR #include "bomb.h" // MLR #include "bombfunc.h" // MLR #include "profiler.h" #include "harmpod.h" // RV - I-Hawk extern bool g_bUseRC135; extern bool g_bEnableColorMfd; extern bool g_bRealisticAvionics; extern bool g_bEnableFCCSubNavCycle; // ASSOCIATOR 04/12/03: Enables you to cycle the Nav steerpoint modes modes with the FCC submodes key extern bool g_bWeaponStepToGun; // MLR 3/13/2004 - optionally turns off weapon stepping to guns extern bool g_bGreyMFD; extern bool g_bGreyScaleMFD; extern bool bNVGmode; const int FireControlComputer::DATALINK_CYCLE = 20;//JPO = 20 seconds const float FireControlComputer::MAXJSTARRANGESQ = 200*200;//JPO = 200 nm const float FireControlComputer::EMITTERRANGE = 60;//JPO = 40 km const float FireControlComputer::CursorRate = 0.15f; //MI added FireControlComputer::FireControlComputer (SimVehicleClass* vehicle, int numHardpoints) { // sfr: smartpointer //fccWeaponPtr = NULL; // MLR 3/16/2004 - simulated weapon fccWeaponId = 0; //rocketPointer = NULL; // MLR 3/5/2004 - For impact prediction rocketWeaponId = 0; platform = vehicle; airGroundDelayTime = 0.0F; airGroundRange = 10.0F * NM_TO_FT; missileMaxTof = -1.0f; missileActiveTime = -1.0f; lastmissileActiveTime = -1.0f; bombPickle = FALSE; postDrop = FALSE; preDesignate = TRUE; tossAnticipationCue = NoCue; laddAnticipationCue = NoLADDCue; //MI lastMasterMode = Nav; // ASSOCIATOR lastNavMasterMode = Nav; lastAgMasterMode = (FCCMasterMode)-1; // AirGroundBomb; // MLR 2/8/2004 - EnterAGMasterMode() will see this, and determine the default weapon // MLR 3/13/2004 - back to using hp ids lastAirAirHp = -1; lastAirGroundHp = -1; lastDogfightHp = -1; lastMissileOverrideHp = -1; lastAirAirGunSubMode = EEGS; // MLR 2/7/2004 - lastAirGroundGunSubMode = STRAF; // MLR 2/7/2004 - lastAirGroundLaserSubMode = SLAVE; // MLR 4/11/2004 - inAAGunMode = 0; // MLR 3/14/2004 - inAGGunMode = 0; // MLR 3/14/2004 - lastSubMode = ETE; //lastAirGroundSubMode = CCRP;//me123 lastDogfightGunSubMode = EEGS; //MI lastAirAirSubMode = Aim9; // ASSOCIATOR strcpy (subModeString, ""); playerFCC = FALSE; targetList = NULL; releaseConsent = FALSE; designateCmd = FALSE; dropTrackCmd = FALSE; targetPtr = NULL; missileCageCmd = FALSE; missileTDBPCmd = FALSE; missileSpotScanCmd = FALSE; missileSlaveCmd = FALSE; cursorXCmd = 0; cursorYCmd = 0; waypointStepCmd = 127; // Force an intial update (GM radar, at least, needs this) HSDRangeStepCmd = 0; HSDRange = 15.0F; HsdRangeIndex = 0; // JPO groundPipperAz = groundPipperEl = 0.0F; masterMode = Nav; subMode = ETE; dgftSubMode = Aim9; // JPO dogfight specific mrmSubMode = Aim120; // ASSOCIATOR 04/12/03: for remembering MRM mode missiles autoTarget = FALSE; missileWEZDisplayRange = 20.0F * NM_TO_FT; mSavedWayNumber = 0; mpSavedWaypoint = NULL; mStptMode = FCCWaypoint; mNewStptMode = mStptMode; bombReleaseOverride = FALSE; lastMissileShootRng = -1; missileLaunched = 0; lastMissileShootHeight = 0; lastMissileShootEnergy = 0; nextMissileImpactTime = -1.0F; lastMissileImpactTime = -1.0f; Height = 0;//me123 targetspeed = 0;//me123 hsdstates = 0; // JPO MissileImpactTimeFlash = 0; // JPO grndlist = NULL; BuildPrePlanned(); // JPO //MI LaserArm = FALSE; LaserFire = FALSE; ManualFire = FALSE; LaserWasFired = FALSE; CheckForLaserFire = FALSE; InhibitFire = FALSE; Timer = 0.0F; ImpactTime = 0.0F; LaserRange = 0.0F; SafetyDistance = 1 * NM_TO_FT; pitch = 0.0F; roll = 0.0F; yaw = 0.0F; time = 0; //MI SOI and HSD IsSOI = FALSE; CouldBeSOI = FALSE; HSDZoom = 0; HSDXPos = 0; //Wombat778 11-10-2003 HSDYPos = 0; //Wombat778 11-10-2003 HSDCursorXCmd = 0; HSDCursorYCmd = 0; xPos = 0; //position of the curson on the scope yPos = 0; HSDDesignate = 0; curCursorRate = CursorRate; DispX = 0; DispY = 0; missileSeekerAz = missileSeekerEl = 0; } FireControlComputer::~FireControlComputer (void) { ClearCurrentTarget(); ClearPlanned(); // JPO } void FireControlComputer::SetPlayerFCC (int flag) { WayPointClass* tmpWaypoint; playerFCC = flag; Sms->SetPlayerSMS(flag); tmpWaypoint = platform->waypoint; TheHud->waypointNum = 0; while (tmpWaypoint && tmpWaypoint != platform->curWaypoint) { tmpWaypoint = tmpWaypoint->GetNextWP(); TheHud->waypointNum ++; } } // JPO - just note it is launched. void FireControlComputer::MissileLaunch() { if(subMode == Aim120) { missileLaunched = 1; lastMissileShootTime = SimLibElapsedTime; } if(!Sms->GetCurrentWeapon()) { switch(masterMode) // MLR 4/12/2004 - Even though this function only appears to be called in AA modes { case Missile: case MissileOverride: if(!Sms->FindWeaponType (wtAim120)) Sms->FindWeaponType (wtAim9); SetMasterMode(masterMode); break; case Dogfight: if(!Sms->FindWeaponType (wtAim9)) Sms->FindWeaponType (wtAim120); SetMasterMode(masterMode); break; } } UpdateLastData(); // UpdateWeaponPtr(); } SimObjectType* FireControlComputer::Exec (SimObjectType* curTarget, SimObjectType* newList, PilotInputs* theInputs) { #ifdef Prof_ENABLED Prof(FireControlComputer_Exec); #endif //me123 overtake needs to be calgulated the same way in MissileClass::GetTOF static const float MISSILE_ALTITUDE_BONUS = 23.0f; //me123 addet here and in // JB 010215 changed from 24 to 23 static const float MISSILE_SPEED = 1500.0f; // JB 010215 changed from 1300 to 1500 if (playerFCC && ((AircraftClass*)platform)->mFaults->GetFault(FaultClass::fcc_fault)) { SetTarget (NULL); } else { if (SimDriver.MotionOn()) { if (!targetPtr) { MissileImpactTimeFlash = 0; // cancel flashing lastMissileImpactTime = 0; lastmissileActiveTime = 0; } if (targetPtr && missileLaunched) { lastMissileShootRng = targetPtr->localData->range; lastMissileImpactTime = nextMissileImpactTime; lastMissileShootHeight = Height; lastMissileShootEnergy = (platform->GetVt() * FTPSEC_TO_KNOTS - 150.0f)/2 ; // JB 010215 changed from 250 to 150 } missileLaunched = 0; if (lastMissileImpactTime > 0.0F && targetPtr ) { //me123 addet this stuff //this is the missiles approximate overtake //missilespeed + altitude bonus + target closure float overtake = lastMissileShootEnergy + MISSILE_SPEED +(lastMissileShootHeight/1000.0f * MISSILE_ALTITUDE_BONUS) + targetspeed * (float)cos(targetPtr->localData->ataFrom); //this is the predicted range from the missile to the target lastMissileShootRng = lastMissileShootRng - (overtake / SimLibMajorFrameRate); lastMissileImpactTime = max (0.0F, lastMissileShootRng/overtake); // this is TOF. Counting on silent failure of divid by 0.0 here... lastMissileImpactTime += -5.0f * (float) sin(.07f * lastMissileImpactTime); // JB 010215 if (lastMissileImpactTime == 0.0f) { // JPO - trigger flashing X // 8 seconds steady, 5 seconds flash MissileImpactTimeFlash = SimLibElapsedTime + (5+8) * CampaignSeconds; lastMissileShootRng = -1.0f; // reset for next } else MissileImpactTimeFlash = 0; } } SetTarget(curTarget); targetList = newList; NavMode(); switch (masterMode) { case AGGun: //if (GetSubMode() == STRAF) { AirGroundMode(); break; case ILS: case Nav: break; case Dogfight: case MissileOverride: case Missile: AirAirMode(); lastCage = missileCageCmd; break; case AirGroundBomb: AirGroundMode(); break; case AirGroundRocket: AirGroundMode(); break; case AirGroundMissile: case AirGroundHARM: AirGroundMissileMode(); break; case AirGroundLaser: //if(!playerFCC) TargetingPodMode(); break; } // always run targeting pod for player // FRB - always run targeting pod for All //TargetingPodMode(); //if(playerFCC) TargetingPodMode(); // COBRA - RED - CCIP HUD FIX - make the Time To target equal to 0, targeting Pod mode is assigning a time to target // messing up the CCIP pipper in HudClas::DrawCCIP call //if(subMode==CCIP) airGroundDelayTime=0.0F; lastDesignate = designateCmd; } return (targetPtr); } void FireControlComputer::SetSubMode (FCCSubMode newSubMode) { if (newSubMode == CCRP && Sms && Sms->Ownship() && Sms->Ownship()->IsAirplane() && // MLR not always owned by a/c ((AircraftClass *)(Sms->Ownship()))->af && (!((AircraftClass *)Sms->Ownship())->af->IsSet(AirframeClass::IsDigital) || (!(((AircraftClass *)(Sms->Ownship()))->AutopilotType() == AircraftClass::CombatAP))) && platform && RadarDataTable[platform->GetRadarType()].NominalRange == 0.0) // JB 011018 { newSubMode = CCIP; } // It has been stated (by Leon R) that changing modes while releasing weapons is bad, so... if (bombPickle) { return; } if (masterMode != Dogfight && masterMode != MissileOverride) { lastSubMode = subMode; } if (lastSubMode == BSGT || lastSubMode == SLAVE || lastSubMode == HARM || lastSubMode == HTS ) { platform->SOIManager (SimVehicleClass::SOI_RADAR); } subMode = newSubMode; // COBRA - RED - Default to immediate release Pickle Time PICKLE(DEFAULT_PICKLE); switch (subMode) { case SAM: strcpy (subModeString, "SAM"); Sms->SetWeaponType (wtNone); Sms->FindWeaponClass (wcSamWpn); break; case Aim9: strcpy (subModeString, "SRM"); if(Sms && Sms->Ownship() && ((AircraftClass *)Sms->Ownship())->AutopilotType() == AircraftClass::CombatAP ) { if(Sms->GetCoolState() == SMSClass::WARM && Sms->MasterArm() == SMSClass::Arm) { // JPO aim9 cooling Sms->SetCoolState(SMSClass::COOLING); } } platform->SOIManager (SimVehicleClass::SOI_RADAR); break; case Aim120: strcpy (subModeString, "MRM"); platform->SOIManager (SimVehicleClass::SOI_RADAR); // COBRA - RED - 1 Second Pickle for AIM 120 PICKLE(SEC_1_PICKLE); break; case EEGS: strcpy (subModeString, "EEGS"); platform->SOIManager (SimVehicleClass::SOI_RADAR); break; // ASSOCIATOR 03/12/03: Added the combined SnapShot LCOS Gunmode SSLC case SSLC: strcpy (subModeString, "SSLC"); platform->SOIManager (SimVehicleClass::SOI_RADAR); break; case LCOS: strcpy (subModeString, "LCOS"); platform->SOIManager (SimVehicleClass::SOI_RADAR); break; case Snapshot: strcpy (subModeString, "SNAP"); platform->SOIManager (SimVehicleClass::SOI_RADAR); break; case CCIP: // MLR 4/1/2004 - rewrite based on Mirv's info. preDesignate = TRUE; strcpy (subModeString, "CCIP"); platform->SOIManager (SimVehicleClass::SOI_RADAR); break; case CCRP: // MLR 4/1/2004 - rewrite based on Mirv's info. preDesignate = FALSE; strcpy (subModeString, "CCRP");//me123 moved so we don't write this with no bombs platform->SOIManager (SimVehicleClass::SOI_RADAR); // 2001-04-18 ADDED BY S.G. I'LL SET MY RANDOM NUMBER FOR CCRP BOMBING INNACURACY NOW // Since autoTarget is a byte :-( I'm limiting to just use the same value for both x and y offset :-( // autoTarget = (rand() & 0x3f) - 32; // In RP5, I'm limited to the variables I can use xBombAccuracy = (rand() & 0x3f) - 32; yBombAccuracy = (rand() & 0x3f) - 32; // COBRA - RED - 1 Second Pickle for CCRP PICKLE(SEC_1_PICKLE); break; case DTOSS: preDesignate = TRUE; groundPipperAz = 0.0F; groundPipperEl = 0.0F; platform->SOIManager (SimVehicleClass::SOI_HUD); // MLR 4/1/2004 - rewrite based on Mirv's info. strcpy (subModeString, "DTOS"); // COBRA - RED - 1 Second Pickle for DTOSS PICKLE(SEC_1_PICKLE); break; case LADD: preDesignate = FALSE; groundPipperAz = 0.0F; groundPipperEl = 0.0F; platform->SOIManager (SimVehicleClass::SOI_RADAR); // MLR 4/1/2004 - rewrite based on Mirv's info. strcpy (subModeString, "LADD"); break; case MAN: // JPO preDesignate = TRUE; strcpy (subModeString, "MAN"); platform->SOIManager (SimVehicleClass::SOI_RADAR); // COBRA - RED - 1 Second Pickle for MAN PICKLE(SEC_1_PICKLE); break; case OBSOLETERCKT: preDesignate = TRUE; strcpy (subModeString, "RCKT"); platform->SOIManager (SimVehicleClass::SOI_RADAR); break; case STRAF: preDesignate = TRUE; strcpy (subModeString, "STRF"); platform->SOIManager (SimVehicleClass::SOI_RADAR); break; case BSGT: preDesignate = TRUE; groundPipperAz = 0.0F; groundPipperEl = 0.0F; strcpy (subModeString, "BSGT"); platform->SOIManager (SimVehicleClass::SOI_HUD); break; case SLAVE: preDesignate = TRUE; groundPipperAz = 0.0F; groundPipperEl = 0.0F; strcpy (subModeString, "SLAV"); platform->SOIManager (SimVehicleClass::SOI_RADAR); // COBRA - RED - 1 Second Pickle for SLAVE PICKLE(SEC_1_PICKLE); break; case HARM: case HTS: preDesignate = TRUE; groundPipperAz = 0.0F; groundPipperEl = 0.0F; // RV - I-Hawk - on HUD it should read "HTS" for HTS and "HARM" for the HARM WPN mode usage if ( subMode == HTS ) { strcpy (subModeString, "HTS"); } else { strcpy (subModeString, "HARM"); } if (Sms->GetCurrentWeaponHardpoint() >= 0 && // JPO CTD fix Sms->CurHardpoint() >= 0 && // JB 010805 Possible CTD check curhardpoint Sms->hardPoint[Sms->CurHardpoint()] != NULL) // Cobra - Sms->GetCurrentWeaponHardpoint() was causing a CTD (returned with a very large number) { Sms->SetWeaponType(Sms->hardPoint[Sms->CurHardpoint()]->GetWeaponType()); // RV - I-Hawk - Don't auto pass SOI to HARM if we are using the advanced HARM systems HarmTargetingPod* harmPod = (HarmTargetingPod*)FindSensor(platform, SensorClass::HTS); if ( harmPod && (harmPod->GetSubMode() == HarmTargetingPod::HAS || harmPod->GetSubMode() == HarmTargetingPod::HAD) ) { platform->SOIManager (SimVehicleClass::SOI_RADAR); } else { platform->SOIManager (SimVehicleClass::SOI_WEAPON); } } else Sms->SetWeaponType (wtNone); // COBRA - RED - 1 Second Pickle for HTS PICKLE(SEC_1_PICKLE); break; case TargetingPod: preDesignate = TRUE; groundPipperAz = 0.0F; groundPipperEl = 0.0F; strcpy (subModeString, "GBU"); if (Sms->GetCurrentWeaponHardpoint() >= 0 && // JPO CTD fix Sms->CurHardpoint() >= 0 && // JB 010805 Possible CTD check curhardpoint Sms->hardPoint[Sms->GetCurrentWeaponHardpoint()] != NULL && Sms->hardPoint[Sms->GetCurrentWeaponHardpoint()]->weaponPointer) Sms->SetWeaponType(Sms->hardPoint[Sms->CurHardpoint()]->GetWeaponType()); else Sms->SetWeaponType (wtNone); platform->SOIManager (SimVehicleClass::SOI_RADAR); // COBRA - RED - 1 Second Pickle for TGP PICKLE(SEC_1_PICKLE); break; case TimeToGo: case ETE: case ETA: platform->SOIManager (SimVehicleClass::SOI_RADAR); break; } // Make sure string is correct in override modes switch (masterMode) { case Dogfight: //strcpy (subModeString, "DGFT"); //JPG 29 Apr 04 - This is no longer displayed in new software tapes break; case MissileOverride: if (Sms->curWeaponType == Aim9) { strcpy (subModeString, "SRM"); } if (Sms->curWeaponType == Aim120) { strcpy (subModeString, "MRM"); } break; } // MLR 4/1/2004 - Memorize SubMode switch(masterMode) { case ILS: case Nav: break; case Dogfight: lastDogfightGunSubMode = subMode; break; case MissileOverride: lastMissileOverrideSubMode = subMode; break; case AAGun: lastAirAirGunSubMode = subMode; break; case Missile: lastAirAirSubMode = subMode; break; case AGGun: lastAirGroundGunSubMode = subMode; break; case AirGroundBomb: Sms->SetAGBSubMode(subMode); { if (playerFCC && SimDriver.GetPlayerAircraft()->AutopilotType() != AircraftClass::CombatAP) { RadarDopplerClass* pradar = (RadarDopplerClass*) FindSensor (platform, SensorClass::Radar); if(g_bRealisticAvionics && pradar) { if(subMode == CCRP || subMode == MAN) { pradar->SelectLastAGMode(); } else { pradar->DefaultAGMode(); } pradar->SetScanDir(1.0F); } } else { RadarClass* pradar = (RadarClass*) FindSensor (platform, SensorClass::Radar); pradar->DefaultAGMode(); } } break; case AirGroundMissile: //lastAirGroundMissileSubMode = subMode; break; case AirGroundHARM: //lastAirGroundHARMSubMode = subMode; break; case AirGroundLaser: lastAirGroundLaserSubMode = subMode; break; case AirGroundCamera: //lastAirGroundCameraSubMode = subMode; break; } } void FireControlComputer::ClearOverrideMode (void) { if ((GetMasterMode() == Dogfight) || (GetMasterMode() == MissileOverride)) { masterMode = lastMasterMode; // MLR - little kludge so I can get the MM MASTERMODES mmm = GetMainMasterMode(); masterMode = ClearOveride;//me123 to allow leaving an overide mode switch(mmm) { case MM_AA: EnterAAMasterMode(); break; case MM_AG: EnterAGMasterMode(); break; default: SetMasterMode (lastMasterMode); break; } } } void FireControlComputer::NextSubMode (void) { // MLR 4/3/2004 - Added calls to SetSubMode instead of doing 'stuff' for ourselves. //MI RadarDopplerClass* pradar = (RadarDopplerClass*) FindSensor (platform, SensorClass::Radar); switch (masterMode) { // ASSOCIATOR 02/12/03: Now we can use the Cycle FCC Submodes key when in Dogfight Mode // ASSOCIATOR 03/12/03: Added the combined SnapShot LCOS Gunmode SSLC case Dogfight: switch (subMode) { case EEGS: if (PlayerOptions.GetAvionicsType() != ATEasy) { SetSubMode (SSLC); } break; case SSLC: SetSubMode (LCOS); break; case LCOS: SetSubMode (Snapshot); break; case Snapshot: SetSubMode (EEGS); break; } break; // ASSOCIATOR 02/12/03: Now we can use the Cycle FCC Submodes key when in MissileOverride // ASSOCIATOR 03/12/03: Added the combined SnapShot LCOS Gunmode SSLC case AAGun: switch (subMode) { case EEGS: if (PlayerOptions.GetAvionicsType() != ATEasy) { SetSubMode (SSLC); } break; case SSLC: SetSubMode (LCOS); break; case LCOS: SetSubMode (Snapshot); break; case Snapshot: SetSubMode (EEGS); break; } break; case Nav: // MD -- 20031203: removed this since sources seem to indicate that there is no such function in the real jet. // ASSOCIATOR Added g_bEnableFCCSubNavCycle as an option and !g_bRealisticAvionics to not break the other modes if( g_bEnableFCCSubNavCycle | !g_bRealisticAvionics ) { switch (subMode) { case ETE: if (PlayerOptions.GetAvionicsType() != ATEasy) { SetSubMode (TimeToGo); } break; case TimeToGo: SetSubMode (ETA); break; case ETA: SetSubMode (ETE); break; } break; } else break; case AirGroundBomb: switch (subMode) { case CCIP: if (PlayerOptions.GetAvionicsType() != ATEasy) { SetSubMode (DTOSS); } break; case CCRP: SetSubMode (CCIP); break; case DTOSS: SetSubMode (CCRP); break; default: // catch LADD MAN etc SetSubMode(CCRP); break; } break; case AirGroundLaser: if(g_bRealisticAvionics) { SetSubMode(lastAirGroundLaserSubMode); SetSubMode(SLAVE); break; } // intentionally fall thru case AirGroundMissile: switch (subMode) { case SLAVE: if (PlayerOptions.GetAvionicsType() != ATEasy) { SetSubMode (BSGT); } break; case BSGT: SetSubMode (SLAVE); break; } break; } } void FireControlComputer::WeaponStep(void) { RadarDopplerClass* pradar = (RadarDopplerClass*) FindSensor (platform, SensorClass::Radar); BombClass *TheBomb=GetTheBomb(); switch (masterMode) { case Dogfight: case MissileOverride: case Missile: case AirGroundMissile: case AirGroundHARM: Sms->WeaponStep(); if(pradar && (masterMode == AirGroundMissile || masterMode == AirGroundHARM)) //MI fix { pradar->SetScanDir(1.0F); pradar->SelectLastAGMode(); } break; case AGGun: if(lastAgMasterMode==AirGroundBomb) { ToggleAGGunMode(); SetSubMode(CCRP); } break; case AirGroundBomb: // COBRA - RED - FIXING POSSIBLE CTDs // CCIP -> DTOS -> STRAF -> CCRP /*if ((Sms->GetCurrentHardpoint() > 0) && (Sms->hardPoint[Sms->GetCurrentHardpoint()]->GetWeaponType()==wtGPS || // Cobra - no rippling GPS (((BombClass*)Sms->hardPoint[Sms->GetCurrentHardpoint()]->weaponPointer) && ((BombClass*)Sms->hardPoint[Sms->GetCurrentHardpoint()]->weaponPointer)->IsSetBombFlag(BombClass::IsJSOW))))*/ { if( TheBomb && ( TheBomb->IsSetBombFlag(BombClass::IsGPS) || TheBomb->IsSetBombFlag(BombClass::IsJSOW))) Sms->WeaponStep(); break; } switch (subMode) { case CCIP: SetSubMode (DTOSS); break; case DTOSS: //Cobra TJL 11/17/04 Aircraft w/o guns get stuck in DTOSS //with missile step //ToggleAGGunMode(); if( Sms->FindWeaponClass(wcGunWpn, TRUE) ) ToggleAGGunMode(); else SetSubMode(CCRP); break; case CCRP: SetSubMode (CCIP); break; default: // catch LADD MAN etc SetSubMode(CCRP); break; } break; } } SimObjectType* FireControlComputer::TargetStep (SimObjectType* startObject, int checkFeature) { VuEntity* testObject = NULL; VuEntity* groundTarget = NULL; SimObjectType* curObject = NULL; SimObjectType* retObject = NULL; float angOff; // Starting in the object list if (startObject == NULL || startObject != targetPtr){ // Start at next and go on if (startObject){ curObject = startObject->next; while (curObject){ if (curObject->localData->ata < 60.0F * DTR){ retObject = curObject; break; } curObject = curObject->next; } } // Did we go off the End of the objects? if (!retObject && checkFeature){ // Check features { VuListIterator featureWalker(SimDriver.featureList); testObject = featureWalker.GetFirst(); while (testObject) { angOff = (float)atan2 (testObject->YPos() - platform->YPos(), testObject->XPos() - platform->XPos()) - platform->Yaw(); if (fabs(angOff) < 60.0F * DTR) { break; } testObject = featureWalker.GetNext(); } } if (testObject) { groundTarget = testObject; // KCK NOTE: Uh.. why are we doing this? //if (retObject) //{ //Tpoint pos; //targetPtr->BaseData()->drawPointer->GetPosition (&pos); //targetPtr->BaseData()->SetPosition (pos.x, pos.y, pos.z); //} groundDesignateX = testObject->XPos(); groundDesignateY = testObject->YPos(); groundDesignateZ = testObject->ZPos(); } } // Did we go off the end of the Features? if (!retObject && !groundTarget){ // Check the head of the object list curObject = targetList; if (curObject){ if (curObject->localData->ata < 60.0F * DTR){ retObject = curObject; } else { while (curObject != startObject){ curObject = curObject->next; if (curObject && curObject->localData->ata < 60.0F * DTR){ retObject = curObject; break; } } } } } } else if (startObject == targetPtr) { // Find the current object if (checkFeature) { { VuListIterator featureWalker(SimDriver.featureList); testObject = featureWalker.GetFirst(); // Iterate up to our position in the list. while (testObject && testObject != targetPtr->BaseData()) testObject = featureWalker.GetNext(); // And then get the next object if (testObject) testObject = featureWalker.GetNext(); // Is there anything after the current object? while (testObject) { angOff = (float)atan2 (testObject->YPos() - platform->YPos(), testObject->XPos() - platform->XPos()) - platform->Yaw(); if (fabs(angOff) < 60.0F * DTR) { break; } testObject = featureWalker.GetNext(); } } // Found one, so use it if (testObject) { groundTarget = testObject; // KCK: Why are we doing this? // Tpoint pos; // targetPtr->BaseData()->drawPointer->GetPosition (&pos); // targetPtr->BaseData()->SetPosition (pos.x, pos.y, pos.z); groundDesignateX = testObject->XPos(); groundDesignateY = testObject->YPos(); groundDesignateZ = testObject->ZPos(); } } // Off the end of the feature list? if (!retObject && !groundTarget) { // Check the head of the object list curObject = targetList; while (curObject) { if (curObject->localData->ata < 60.0F * DTR) { retObject = curObject; break; } curObject = curObject->next; } } // Of the End of the object list ? if (!retObject && checkFeature && !groundTarget){ // Check features VuListIterator featureWalker(SimDriver.featureList); testObject = featureWalker.GetFirst(); while (testObject && testObject != targetPtr->BaseData()){ angOff = (float)atan2 (testObject->YPos() - platform->YPos(), testObject->XPos() - platform->XPos()) - platform->Yaw(); if (fabs(angOff) < 60.0F * DTR){ break; } testObject = featureWalker.GetNext(); } if (testObject) { groundTarget = testObject; groundDesignateX = testObject->XPos(); groundDesignateY = testObject->YPos(); groundDesignateZ = testObject->ZPos(); } } } if (groundTarget){ // We're targeting a feature thing - make a new SimObjectType #ifdef DEBUG //retObject = new SimObjectType(OBJ_TAG, platform, (SimBaseClass*)groundTarget); #else retObject = new SimObjectType((SimBaseClass*)groundTarget); #endif retObject->localData->ataFrom = 180.0F * DTR; } SetTarget(retObject); return retObject; } void FireControlComputer::ClearCurrentTarget (void) { if (targetPtr) targetPtr->Release( ); targetPtr = NULL; } void FireControlComputer::SetTarget (SimObjectType* newTarget) { if (newTarget == targetPtr) return; /* MLR debugging stuff MonoPrint(" FCC::SetTarget - prev:%08x/%08x, new: %08x/%08x\n", targetPtr,(targetPtr?targetPtr->BaseData():0), newTarget,(newTarget?newTarget->BaseData():0)); if(!newTarget) int stop=0; */ ClearCurrentTarget(); if (newTarget) { ShiAssert( newTarget->BaseData() != (FalconEntity*)0xDDDDDDDD ); newTarget->Reference( ); } targetPtr = newTarget; } void FireControlComputer::DisplayInit (ImageBuffer* image) { DisplayExit(); privateDisplay = new Render2D; ((Render2D*)privateDisplay)->Setup (image); if ((g_bGreyMFD) && (!bNVGmode)) privateDisplay->SetColor(GetMfdColor(MFD_WHITE)); else privateDisplay->SetColor (0xff00ff00); } void FireControlComputer::Display (VirtualDisplay* newDisplay) { display = newDisplay; // JPO intercept for now FCC power... if (!((AircraftClass*)platform)->HasPower(AircraftClass::FCCPower)) { BottomRow(); display->TextCenter(0.0f, 0.2f, "FCC"); int ofont = display->CurFont(); display->SetFont(2); display->TextCenterVertical (0.0f, 0.0f, "OFF"); display->SetFont(3); return; } NavDisplay(); } void FireControlComputer::PushButton(int whichButton, int whichMFD) { AircraftClass *playerAC = SimDriver.GetPlayerAircraft(); ShiAssert(whichButton < 20); ShiAssert(whichMFD < 4); if (IsHsdState(HSDCNTL)) { if (hsdcntlcfg[whichButton].mode != HSDNONE) { ToggleHsdState(hsdcntlcfg[whichButton].mode); return; } } //MI if(g_bRealisticAvionics) { if(playerAC) { if(IsSOI && (whichButton >=11 && whichButton <= 13)) platform->StepSOI(2); } } switch (whichButton) { case 0: // DEP - JPO if (g_bRealisticAvionics) { ToggleHsdState (HSDCEN); } break; case 1: // DCPL - JPO if (g_bRealisticAvionics) { ToggleHsdState (HSDCPL); } break; //MI case 2: if(g_bRealisticAvionics) ToggleHSDZoom(); break; case 4: // CTRL if (g_bRealisticAvionics) { ToggleHsdState (HSDCNTL); } break; case 6: // FRZ - JPO if (g_bRealisticAvionics) { frz_x = platform->XPos(); frz_y = platform->YPos(); frz_dir = platform->Yaw(); ToggleHsdState(HSDFRZ); } break; case 10: if (g_bRealisticAvionics) { MfdDrawable::PushButton(whichButton, whichMFD); } break; case 11: // SMS if (g_bRealisticAvionics) MfdDrawable::PushButton(whichButton, whichMFD); else MfdDisplay[whichMFD]->SetNewMode(MFDClass::SMSMode); break; case 12: // jpo if (g_bRealisticAvionics) MfdDrawable::PushButton(whichButton, whichMFD); break; case 13: // HSD if (g_bRealisticAvionics) MfdDrawable::PushButton(whichButton, whichMFD); else MfdDisplay[whichMFD]->SetNewMode(MFDClass::MfdMenu); break; case 14: // SWAP if (g_bRealisticAvionics) MfdDrawable::PushButton(whichButton, whichMFD); else MFDSwapDisplays(); break; case 18: // Down if(!g_bRealisticAvionics) SimHSDRangeStepDown (0, KEY_DOWN, NULL); else { //MI if(HSDZoom == 0) SimHSDRangeStepDown (0, KEY_DOWN, NULL); } break; case 19: // UP if(!g_bRealisticAvionics) SimHSDRangeStepUp (0, KEY_DOWN, NULL); else { //MI if(HSDZoom == 0) SimHSDRangeStepUp (0, KEY_DOWN, NULL); } break; } } // STUFF Copied from Harm - now merged. JPO // JPO // This routine builds the initial list of preplanned targets. // this will remain unchanged if there is no dlink/jstar access void FireControlComputer::BuildPrePlanned() { FlightClass* theFlight = (FlightClass*)(platform->GetCampaignObject()); FalconPrivateList* knownEmmitters = NULL; GroundListElement* tmpElement; GroundListElement* curElement = NULL; FalconEntity* eHeader; // this is all based around waypoints. if (SimDriver.RunningCampaignOrTactical() && theFlight) knownEmmitters = theFlight->GetKnownEmitters(); if (knownEmmitters) { { VuListIterator elementWalker (knownEmmitters); eHeader = (FalconEntity*)elementWalker.GetFirst(); while (eHeader) { tmpElement = new GroundListElement (eHeader); if (grndlist == NULL) grndlist = tmpElement; else curElement->next = tmpElement; curElement = tmpElement; eHeader = (FalconEntity*)elementWalker.GetNext(); } } knownEmmitters->Unregister(); delete knownEmmitters; } nextDlUpdate = SimLibElapsedTime + CampaignSeconds * DATALINK_CYCLE; } // update - every so often from a JSTAR platform if available. void FireControlComputer::UpdatePlanned() { if (nextDlUpdate > SimLibElapsedTime) return; //Cobra This function was killing SAMs and threat rings on HSD //without it, everything is appearing as normal on the HSD. nextDlUpdate = SimLibElapsedTime + 5000/*CampaignSeconds * DATALINK_CYCLE*/; /*if (((AircraftClass*)platform)->mFaults->GetFault(FaultClass::dlnk_fault) || !((AircraftClass*)platform)->HasPower(AircraftClass::DLPower)) return;*/ // RV version // nextDlUpdate = SimLibElapsedTime + CampaignSeconds * DATALINK_CYCLE; //if (((AircraftClass*)platform)->mFaults->GetFault(FaultClass::dlnk_fault) || !((AircraftClass*)platform)->HasPower(AircraftClass::DLPower)) // return; FlightClass* theFlight = (FlightClass*)(platform->GetCampaignObject()); if (!theFlight) return; CampEntity e; VuListIterator myit(EmitterList); // see if we have a jstar. Flight jstar = theFlight->GetJSTARFlight(); Team us = theFlight->GetTeam(); // If we didn't find JSTAR do other search if (!jstar) { Unit nu, cf; VuListIterator new_myit(AllAirList); nu = (Unit) new_myit.GetFirst(); while (nu && !jstar) { cf = nu; nu = (Unit) new_myit.GetNext(); if (!cf->IsFlight() || cf->IsDead()) continue; if (cf->GetUnitMission() == AMIS_JSTAR && cf->GetTeam() == us && cf->GetUnitTOT()+5*CampaignMinutes < Camp_GetCurrentTime() && cf->GetUnitTOT()+95*CampaignMinutes > Camp_GetCurrentTime()) { // Check if JSTAR is in range for communication if (Distance(platform->XPos(), platform->YPos(), cf->XPos(), cf->YPos()) * FT_TO_NM <= 250.0f) { jstar = (Flight)cf; } } } } if ((!jstar)||(!g_bUseRC135)) { // completely new list please //cobra added here float myx = platform->XPos(); float myy = platform->YPos(); ClearPlanned(); GroundListElement* tmpElement; GroundListElement* curElement = NULL; for (e = (CampEntity) myit.GetFirst(); e; e = (Unit) myit.GetNext()) { if (e->GetTeam() != us /*&& e->GetSpotted(us) && (!e->IsUnit() || !((Unit)e)->Moving()) && e->GetElectronicDetectionRange(Air)*/) { float ex = e -> XPos(); float ey = e -> YPos(); if (Distance(ex,ey,myx,myy) * FT_TO_NM < 150/*EMITTERRANGE*/) { tmpElement = new GroundListElement(e); tmpElement->SetFlag(GroundListElement::DataLink);//Cobra nothing is using this... tmpElement->SetFlag(GroundListElement::RangeRing);//Cobra set the ring??? if (grndlist == NULL){ grndlist = tmpElement; } else { curElement->next = tmpElement; } curElement = tmpElement; } } } return; } //cobra added here int jstarDetectionChance = 0; if (jstar) { // This is a ELINT flight (e.g. RC-135) if (jstar->class_data->Role == ROLE_ELINT) jstarDetectionChance = 75; else // FRB - Give JSTAR SAM finder capabilities if (!g_bUseRC135) jstarDetectionChance = 75; else jstarDetectionChance = 25; } //CampEntity e; // VuListIterator myit(EmitterList); for (e = (CampEntity) myit.GetFirst(); e; e = (CampEntity) myit.GetNext()) { if (e->IsUnit() && e->IsBattalion() && rand()%100 > jstarDetectionChance) continue; if (e->IsGroundVehicle()) { GroundListElement* tmpElement = GetFirstGroundElement(); while (tmpElement) { if (tmpElement->BaseObject() == e) break; tmpElement = tmpElement->GetNext(); } if (!tmpElement) { tmpElement = new GroundListElement(e); AddGroundElement(tmpElement); } } } } // every so often - remove dead targets void FireControlComputer::PruneList() { GroundListElement **gpp; for (gpp = &grndlist; *gpp; ) { if ((*gpp)->BaseObject() == NULL) { // delete this one GroundListElement *gp = *gpp; *gpp = gp -> next; delete gp; } else gpp = &(*gpp)->next; } } GroundListElement::GroundListElement(FalconEntity* newEntity) { F4Assert (newEntity); baseObject = newEntity; VuReferenceEntity(newEntity); symbol = RadarDataTable[newEntity->GetRadarType()].RWRsymbol; if (newEntity->IsCampaign()) range = (float)((CampBaseClass*)newEntity)->GetAproxWeaponRange(Air); else range = 0; flags = RangeRing; next = NULL; lastHit = SimLibElapsedTime; } GroundListElement::~GroundListElement() { VuDeReferenceEntity(baseObject); } void GroundListElement::HandoffBaseObject() { FalconEntity *newBase; if (baseObject == NULL) return; newBase = SimCampHandoff( baseObject, HANDOFF_RADAR); if (newBase != baseObject) { VuDeReferenceEntity(baseObject); baseObject = newBase; if (baseObject) { VuReferenceEntity(baseObject); } } } void FireControlComputer::ClearPlanned() { GroundListElement* tmpElement; while (grndlist) { tmpElement = grndlist; grndlist = tmpElement->next; delete tmpElement; } } MASTERMODES FireControlComputer::GetMainMasterMode() { switch (masterMode) { case AAGun: case Missile: return MM_AA; case ILS: case Nav: default: return MM_NAV; case AirGroundBomb: case AirGroundRocket: case AirGroundMissile: case AirGroundHARM: case AirGroundLaser: case AirGroundCamera: case AGGun: return MM_AG; //case Gun: //if (subMode == STRAF) // return MM_AG; //else return MM_AA; case Dogfight: return MM_DGFT; case MissileOverride: return MM_MSL; } } int FireControlComputer::LastMissileWillMiss(float range) { /* if (lastMissileImpactTime >0 && range > missileRMax ) { return 1; } else return 0; */ //me123 if the predicted total TOF is over xx seconds the missile is considered out of energy if (lastMissileImpactTime >0 && //me123 let's make sure there is a missile in the air lastMissileImpactTime - ((lastMissileShootTime - SimLibElapsedTime) /1000) >= 80) return 1; return 0; } float FireControlComputer::Aim120ASECRadius(float range) { float asecradius = 0.6f; static const float bestmaxrange = 0.8f; // upper bound if (!g_bRealisticAvionics) return asecradius; if (range > bestmaxrange*missileRMax) { // above best range float dr = (range - bestmaxrange*missileRMax) / (0.2f*missileRMax); dr = 1.0f - dr; asecradius *= dr; } else if (range < (missileRneMax - missileRneMin)/2.0f) { float dr = (range - missileRMin); dr /= (missileRneMax - missileRneMin)/2.0f - missileRMin; asecradius *= dr; } //MI make the size dependant on missile mode if(Sms && Sms->curWeapon && ((MissileClass*)Sms->GetCurrentWeapon())->isSlave) asecradius = max(min(0.3f, asecradius), 0.1f); else asecradius = max(min(0.6f, asecradius), 0.1f); return asecradius; } // MLR - SetMasterMode() no longer finds matching weapons if the currently // selected weapon doesn't match the mastermode. // However - SMM() will change HPs when Master Modes change. void FireControlComputer::SetMasterMode (FCCMasterMode newMode) { RadarClass* theRadar = (RadarClass*) FindSensor (platform, SensorClass::Radar); FCCMasterMode oldMode; HarmTargetingPod* harmPod = (HarmTargetingPod*) FindSensor (platform, SensorClass::HTS); /* appears to not be needed anymore if( playerFCC && (masterMode == Dogfight || masterMode == MissileOverride) && newMode != MissileOverride && newMode != Dogfight && (Sms->curWeaponType == wtAim9 || Sms->curWeaponType == wtAim120 )) // MLR 1/19/2004 - put these two in parenthesis { if ( masterMode == MissileOverride ) weaponMisOvrdMode = Sms->curWeaponType; else if ( masterMode == Dogfight ) weaponDogOvrdMode = Sms->curWeaponType; else weaponNoOvrdMode = Sms->curWeaponType; } */ // Nav only if Amux and Bmux failed, no change if FCC fail if(playerFCC && ( ( ((AircraftClass*)platform)->mFaults->GetFault(FaultClass::fcc_fault) ) || ( ((AircraftClass*)platform)->mFaults->GetFault(FaultClass::amux_fault) && ((AircraftClass*)platform)->mFaults->GetFault(FaultClass::bmux_fault) && newMode != Nav ) ) ) return; // It has been stated (by Leon R) that changing modes while releasing weapons is bad, so... if (bombPickle) { return; } switch (masterMode) { case ClearOveride: if (theRadar) theRadar->ClearOverride(); break; // Clear any holdouts from previous modes case AirGroundHARM: ((AircraftClass*)platform)->SetTarget (NULL); break; } oldMode = masterMode; if (masterMode != Dogfight && masterMode != MissileOverride) masterMode = newMode;//me123 int isAI = !playerFCC || ( playerFCC && ((AircraftClass *)Sms->Ownship())->AutopilotType() == AircraftClass::CombatAP) ; switch (masterMode) { case Dogfight: // Clear out any non-air-to-air targets we had locked. if (oldMode != Dogfight && oldMode != Missile && oldMode != MissileOverride) ClearCurrentTarget(); //if (oldMode != Dogfight)// MLR 4/11/2004 - I'ld like to remove these, but the AI still calls SMM() directly //Sms->SetCurrentHpByWeaponId(lastDogfightWId); // Sms->SetCurrentHardPoint(lastDogfightHp); postDrop = FALSE; //MI changed so it remembers last gun submode too if(!g_bRealisticAvionics) SetSubMode (EEGS); else SetSubMode(lastDogfightGunSubMode); if(isAI && !WeaponClassMatchesMaster(Sms->curWeaponClass)) if(!Sms->FindWeaponType (wtAim9)) Sms->FindWeaponType(wtAim120); switch(Sms->curWeaponType) { case wtAim9: SetDgftSubMode(Aim9); break; case wtAim120: SetDgftSubMode(Aim120); break; } if (theRadar && oldMode != Dogfight) { theRadar->SetSRMOverride(); } if (TheHud && playerFCC) { TheHud->headingPos = HudClass::Low; } break; case MissileOverride://me123 multi changes here //strcpy (subModeString, "MSL"); // JPG 20 Jan 04 // Clear out any non-air-to-air targets we had locked. if (oldMode != Dogfight && oldMode != Missile && oldMode != MissileOverride) ClearCurrentTarget(); postDrop = FALSE; //if (oldMode != MissileOverride)// MLR 4/11/2004 - I'ld like to remove these, but the AI still calls SMM() directly // Sms->SetCurrentHardPoint(lastMissileOverrideHp); // Sms->SetCurrentHpByWeaponId(lastMissileOverrideWId); if(isAI && !WeaponClassMatchesMaster(Sms->curWeaponClass)) if(!Sms->FindWeaponType (wtAim120)) Sms->FindWeaponType (wtAim9); switch(Sms->curWeaponType) { case wtAim9: SetSubMode(Aim9); SetMrmSubMode(Aim9); break; case wtAim120: SetSubMode(Aim120); SetMrmSubMode(Aim120); break; } if (theRadar ) { theRadar->SetMRMOverride(); } if (TheHud && playerFCC) TheHud->headingPos = HudClass::Low; break; case Missile: // Clear out any non-air-to-air targets we had locked. if (oldMode != Dogfight && oldMode != MissileOverride) ClearCurrentTarget(); postDrop = FALSE; //if(oldMode != masterMode) // MLR 4/11/2004 - I'ld like to remove these, but the AI still calls SMM() directly // Sms->SetCurrentHardPoint(lastAirAirHp); //MonoPrint("FCC:SetMasterMode - 1. CurrentWeaponType=%d\n",Sms->GetCurrentWeaponType()); // make sure the AI get a proper weapon if(isAI && !WeaponClassMatchesMaster(Sms->curWeaponClass)) if(!Sms->FindWeaponType (wtAim120)) Sms->FindWeaponType (wtAim9); switch(Sms->GetCurrentWeaponType()) { case wtAim120: SetSubMode(Aim120); break; case wtAim9: SetSubMode(Aim9); break; } if (TheHud && playerFCC) TheHud->headingPos = HudClass::Low; break; case ILS: // Clear out any previous targets we had locked. ClearCurrentTarget(); Sms->SetWeaponType (wtNone); Sms->FindWeaponClass (wcNoWpn); if (TheHud && playerFCC) TheHud->headingPos = HudClass::High; platform->SOIManager (SimVehicleClass::SOI_RADAR); break; case Nav: // Clear out any previous targets we had locked. strcpy (subModeString, "NAV"); ClearCurrentTarget(); Sms->SetWeaponType (wtNone); Sms->FindWeaponClass (wcNoWpn); SetSubMode (ETE); releaseConsent = FALSE; postDrop = FALSE; preDesignate = TRUE; postDrop = FALSE; bombPickle = FALSE; // Find currentwaypoint if (TheHud && playerFCC) { TheHud->headingPos = HudClass::Low; } // SOI is RADAR in NAV //Cobra test Double here since ETE above sets SOI_RADAR //platform->SOIManager (SimVehicleClass::SOI_RADAR); break; case AirGroundBomb: // Clear out any previous targets we had locked. ClearCurrentTarget(); preDesignate = TRUE; postDrop = FALSE; inRange = TRUE; if(isAI && !WeaponClassMatchesMaster(Sms->curWeaponClass)) Sms->FindWeaponClass (wcBombWpn); if(g_bRealisticAvionics) { SetSubMode(Sms->GetAGBSubMode()); } else { SetSubMode(CCIP); } //if(playerFCC) //{ // Sms->drawable->SetDisplayMode(SmsDrawable::Wpn); ///} if (TheHud && playerFCC) TheHud->headingPos = HudClass::High; break; case AirGroundRocket: // Clear out any previous targets we had locked. ClearCurrentTarget(); preDesignate = TRUE; postDrop = FALSE; inRange = TRUE; if(isAI && !WeaponClassMatchesMaster(Sms->curWeaponClass)) Sms->FindWeaponClass (wcRocketWpn); SetSubMode (OBSOLETERCKT); /* if(!playerFCC) { SetSubMode (OBSOLETERCKT); } else { if(g_bRealisticAvionics) { SetSubMode (Sms->GetAGBSubMode()); } else { SetSubMode (OBSOLETERCKT); } } */ if (TheHud && playerFCC) TheHud->headingPos = HudClass::High; break; case AirGroundMissile: // Clear out any previous targets we had locked. ClearCurrentTarget(); preDesignate = TRUE; postDrop = FALSE; inRange = TRUE; missileTarget = FALSE; if(isAI && !WeaponClassMatchesMaster(Sms->curWeaponClass)) Sms->FindWeaponType (wtAgm65); if(WeaponClassMatchesMaster(Sms->curWeaponClass)) { if(playerFCC) { this-> Sms->StepMavSubMode(TRUE); // TRUE means initial step } /* if (PlayerOptions.GetAvionicsType() == ATRealistic || PlayerOptions.GetAvionicsType() == ATRealisticAV) SetSubMode (BSGT); else SetSubMode (SLAVE); */ } else { if(playerFCC) { Sms->drawable->SetDisplayMode(SmsDrawable::Wpn); } } /* if (Sms->curWeaponClass != wcAgmWpn) { if (Sms->FindWeaponClass (wcAgmWpn) && Sms->CurHardpoint() >= 0) // JB 010805 Possible CTD check curhardpoint { Sms->SetWeaponType(Sms->hardPoint[Sms->CurHardpoint()]->GetWeaponType()); switch (Sms->curWeaponType) { case wtAgm65: // M.N. added full realism mode if (PlayerOptions.GetAvionicsType() == ATRealistic || PlayerOptions.GetAvionicsType() == ATRealisticAV) SetSubMode (BSGT); else SetSubMode (SLAVE); break; } } else { Sms->SetWeaponType (wtNone); if( playerFCC ) { Sms->GetNextWeapon(wdGround); Sms->drawable->SetDisplayMode(SmsDrawable::Wpn); } } } */ if (TheHud && playerFCC) TheHud->headingPos = HudClass::High; break; case AirGroundHARM: // Clear out any previous targets we had locked. ClearCurrentTarget(); preDesignate = TRUE; postDrop = FALSE; // RV - I-Hawk - Get into the right HARM modes if( isAI && !WeaponClassMatchesMaster(Sms->curWeaponClass) ) { Sms->FindWeaponType (wtAgm88); } if ( isAI ) { harmPod->SetSubMode ( HarmTargetingPod::HAS ); harmPod->SetHandedoff ( true ); // AI doesn't need any target hadnoff delay } else { harmPod->SetSubMode( HarmTargetingPod::HarmModeChooser ); } /* if (Sms->curWeaponClass != wcHARMWpn) { if (Sms->FindWeaponClass (wcHARMWpn, FALSE) && Sms->CurHardpoint() >= 0) // JB 010805 Possible CTD check curhardpoint { Sms->SetWeaponType(Sms->hardPoint[Sms->CurHardpoint()]->GetWeaponType()); switch (Sms->curWeaponType) { case wtAgm88: SetSubMode (HTS); break; } } else { Sms->SetWeaponType (wtNone); if( playerFCC ) { Sms->GetNextWeapon(wdGround); Sms->drawable->SetDisplayMode(SmsDrawable::Wpn); } } } */ if (TheHud && playerFCC) { TheHud->headingPos = HudClass::High; } break; case AirGroundLaser: // Clear out any previous targets we had locked. ClearCurrentTarget(); preDesignate = TRUE; postDrop = FALSE; if(isAI && !WeaponClassMatchesMaster(Sms->curWeaponClass)) Sms->FindWeaponType (wtGBU); if(WeaponClassMatchesMaster(Sms->curWeaponClass)) { if(!g_bRealisticAvionics) { //Mi this isn't true... doc states you start off in SLAVE if (PlayerOptions.GetAvionicsType() == ATRealistic) SetSubMode (BSGT); else SetSubMode (SLAVE); } else { InhibitFire = FALSE; // M.N. added full realism mode if( PlayerOptions.GetAvionicsType() != ATRealistic && PlayerOptions.GetAvionicsType() != ATRealisticAV) SetSubMode (BSGT); else SetSubMode (SLAVE); } } else { if( playerFCC ) { Sms->drawable->SetDisplayMode(SmsDrawable::Wpn); } } /* if (Sms->curWeaponClass != wcGbuWpn) { if (Sms->FindWeaponClass (wcGbuWpn, FALSE) && Sms->CurHardpoint() >= 0) // JB 010805 Possible CTD check curhardpoint { Sms->SetWeaponType(Sms->hardPoint[Sms->CurHardpoint()]->GetWeaponType()); switch (Sms->curWeaponType) { case wtGBU: //Mi this isn't true... doc states you start off in SLAVE if(!g_bRealisticAvionics) { if (PlayerOptions.GetAvionicsType() == ATRealistic) SetSubMode (BSGT); else SetSubMode (SLAVE); } else { InhibitFire = FALSE; // M.N. added full realism mode if(PlayerOptions.GetAvionicsType() != ATRealistic && PlayerOptions.GetAvionicsType() != ATRealisticAV) SetSubMode (BSGT); else SetSubMode (SLAVE); } break; } } else { Sms->SetWeaponType (wtNone); if( playerFCC ) { Sms->GetNextWeapon(wdGround); Sms->drawable->SetDisplayMode(SmsDrawable::Wpn); } } } */ if (TheHud && playerFCC) TheHud->headingPos = HudClass::High; break; case AirGroundCamera: // Clear out any previous targets we had locked. ClearCurrentTarget(); preDesignate = TRUE; postDrop = FALSE; if(isAI && !WeaponClassMatchesMaster(Sms->curWeaponClass)) Sms->FindWeaponClass (wcCamera); if(WeaponClassMatchesMaster(Sms->curWeaponClass)) { SetSubMode(PRE); // MLR 2/14/2004 - who knows if this it correct } else { Sms->drawable->SetDisplayMode(SmsDrawable::Wpn); } /* if (Sms->curWeaponClass != wcCamera) { if (Sms->FindWeaponClass (wcCamera, FALSE) && Sms->CurHardpoint() >= 0) // JB 010805 Possible CTD check curhardpoint { Sms->SetWeaponType(Sms->hardPoint[Sms->CurHardpoint()]->GetWeaponType()); } else { Sms->SetWeaponType (wtNone); if( playerFCC ) { Sms->GetNextWeapon(wdGround); Sms->drawable->SetDisplayMode(SmsDrawable::Wpn); } } } */ if (TheHud && playerFCC) TheHud->headingPos = HudClass::High; strcpy (subModeString, "RPOD"); platform->SOIManager (SimVehicleClass::SOI_RADAR); break; } // MLR 2/1/2004 - we check this last, because sometimes we fall back to gun mode in the switch above if(masterMode==AAGun) { if(g_bRealisticAvionics) SetSubMode(lastAirAirGunSubMode); else SetSubMode(EEGS); if(!WeaponClassMatchesMaster(Sms->curWeaponClass)) Sms->FindWeaponType (wtGuns); // we only want to store this as the previous weapon if g_bWeaponStepToGun is TRUE //if(g_bWeaponStepToGun) // lastAirAirHp = Sms->GetCurrentWeaponHardpoint(); //lastAirAirWId=Sms->GetCurrentWeaponId(); if (TheHud && playerFCC) TheHud->headingPos = HudClass::Low; } if(masterMode==AGGun) { { SetSubMode(STRAF); } if(!WeaponClassMatchesMaster(Sms->curWeaponClass)) Sms->FindWeaponType (wtGuns); // we only want to store this as the previous weapon if g_bWeaponStepToGun is TRUE //if(g_bWeaponStepToGun) // lastAirGroundHp = Sms->GetCurrentWeaponHardpoint(); //lastAirGroundWId=Sms->GetCurrentWeaponId(); //>GetCurrentWeaponHardpoint(); if (TheHud && playerFCC) TheHud->headingPos = HudClass::High; } // store master mode, used when leaving DF or MO. switch(masterMode) { case Dogfight: case MissileOverride: break; default: lastMasterMode = masterMode; } UpdateWeaponPtr(); UpdateLastData(); } void FireControlComputer::UpdateLastData(void) { switch(masterMode) { case ILS: case Nav: lastNavMasterMode = masterMode; break; case Dogfight: lastDogfightHp = Sms->GetCurrentWeaponHardpoint(); break; case MissileOverride: lastMissileOverrideHp = Sms->GetCurrentWeaponHardpoint(); break; case AAGun: break; //if(!g_bWeaponStepToGun) //{ // break; //} // intentionally fall thru case Missile: //lastAaMasterMode = masterMode; lastAirAirHp = Sms->GetCurrentWeaponHardpoint(); break; case AGGun: break; //if(!g_bWeaponStepToGun) //{ // break; //} // intentionally fall thru case AirGroundBomb: case AirGroundRocket: case AirGroundMissile: case AirGroundHARM: case AirGroundLaser: case AirGroundCamera: lastAgMasterMode = masterMode; lastAirGroundHp = Sms->GetCurrentWeaponHardpoint(); break; } } int FireControlComputer::WeaponClassMatchesMaster(WeaponClass wc) { switch(masterMode) { case Missile: if(wc==wcAimWpn || wc==wcGunWpn) return 1; return 0; case Dogfight: case MissileOverride: if(wc==wcAimWpn ) return 1; return 0; case AAGun: case AGGun: if(wc==wcGunWpn) return 1; return 0; case AirGroundMissile: if(wc==wcAgmWpn) return 1; return 0; break; case AirGroundBomb: if(wc==wcBombWpn)// || wc==wcRocketWpn) return 1; return 0; break; case AirGroundRocket: if(wc==wcRocketWpn)// || wc==wcRocketWpn) return 1; return 0; break; case AirGroundHARM: if(wc==wcHARMWpn) return 1; return 0; break; case AirGroundLaser: if(wc==wcGbuWpn) return 1; return 0; break; case AirGroundCamera: if(wc==wcCamera) return 1; return 0; break; /* case ClearOveride: if(wc==) return 1; return 0; break; */ } return 0; } int FireControlComputer::CanStepToWeaponClass(WeaponClass wc) { switch(masterMode) { case AAGun: if( ( wc==wcAimWpn && g_bWeaponStepToGun) || wc==wcGunWpn ) return 1; return 0; case Missile: if( wc==wcAimWpn || (wc==wcGunWpn && g_bWeaponStepToGun) ) return 1; return 0; case MissileOverride: case Dogfight: if(wc==wcAimWpn ) return 1; return 0; case AGGun: if( ( ( wc==wcAgmWpn || wc==wcBombWpn || wc==wcRocketWpn || wc==wcHARMWpn || wc==wcGbuWpn || wc==wcCamera ) && g_bWeaponStepToGun) || wc==wcGunWpn ) return 1; return 0; case AirGroundBomb: case AirGroundRocket: case AirGroundMissile: case AirGroundHARM: case AirGroundLaser: case AirGroundCamera: if( wc==wcAgmWpn || wc==wcBombWpn || wc==wcRocketWpn || wc==wcHARMWpn || wc==wcGbuWpn || wc==wcCamera || ( wc==wcGunWpn && g_bWeaponStepToGun ) ) return 1; return 0; } return 0; /* switch(GetMainMasterMode()) { case MM_AA: if(g_bWeaponStepToGun) { if( wc==wcAimWpn || wc==wcGunWpn ) return 1; } else { } return 0; case MM_DGFT: case MM_MSL: if(wc==wcAimWpn ) return 1; return 0; case MM_AG: if( wc==wcAgmWpn || wc==wcBombWpn || wc==wcRocketWpn || wc==wcHARMWpn || wc==wcGbuWpn || wc==wcCamera || ( wc==wcGunWpn && g_bWeaponStepToGun ) ) return 1; return 0; } return 0; */ } void FireControlComputer::SetAAMasterModeForCurrentWeapon(void) { //UpdateWeaponPtr(); FCCMasterMode newmode = masterMode; if(Sms->GetCurrentWeaponHardpoint() == -1) { // maybe we've jetted the weapons, and the Sms curHardpoint is -1 // anyhow, find what we were using before Sms->SetCurrentHardPoint(lastAirAirHp,1); } inAAGunMode = 0; switch(Sms->curWeaponClass) { case wcAimWpn: newmode = Missile; break; case wcGunWpn: inAAGunMode = 1; newmode = AAGun; break; } SetMasterMode(newmode); } void FireControlComputer::SetAGMasterModeForCurrentWeapon(void) { if(Sms->GetCurrentWeaponHardpoint() == -1) { // maybe we've jetted the weapons, and the Sms curHardpoint is -1 // anyhow, find what we were using before Sms->SetCurrentHardPoint(lastAirGroundHp,1); } //UpdateWeaponPtr(); if( Sms->CurHardpoint()<0 ) { // whoops return; } else if(!Sms->hardPoint[Sms->CurHardpoint()]) return; FCCMasterMode newmode = masterMode; inAGGunMode = 0; switch(Sms->hardPoint[Sms->CurHardpoint()]->GetWeaponClass()) { case wcRocketWpn: newmode = AirGroundRocket; break; case wcBombWpn: newmode = AirGroundBomb; break; case wcGunWpn: inAGGunMode = 1; newmode = AGGun; break; case wcAgmWpn: newmode = AirGroundMissile; break; case wcHARMWpn: newmode = AirGroundHARM; break; case wcGbuWpn: newmode = AirGroundLaser; break; case wcCamera: newmode = AirGroundCamera; break; default: newmode = AirGroundBomb; /* case wcSamWpn: break; case wcNoWpn: break; case wcECM: break; case wcTank: break; */ } SetMasterMode(newmode); } int FireControlComputer::IsInAAMasterMode(void) { return(GetMainMasterMode()==MM_AA); } int FireControlComputer::IsInAGMasterMode(void) { return(GetMainMasterMode()==MM_AG); } void FireControlComputer::EnterAAMasterMode(void) { if(inAAGunMode) { // go to gun mode if( Sms->FindWeaponClass(wcGunWpn, TRUE) ) SetMasterMode(AAGun); } else { Sms->SetCurrentHardPoint(lastAirAirHp); //SetMasterMode(lastAaMasterMode); SetMasterMode(Missile); } } void FireControlComputer::EnterAGMasterMode(void) { if(inAGGunMode) { // go to gun mode if( Sms->FindWeaponClass(wcGunWpn, TRUE) ) SetMasterMode(AGGun); } else { Sms->SetCurrentHardPoint(lastAirGroundHp); SetMasterMode(lastAgMasterMode); } } void FireControlComputer::EnterMissileOverrideMode(void) { Sms->SetCurrentHardPoint(lastMissileOverrideHp); SetMasterMode(MissileOverride); } void FireControlComputer::EnterDogfightMode(void) { Sms->SetCurrentHardPoint(lastDogfightHp); SetMasterMode(Dogfight); } void FireControlComputer::ToggleAAGunMode(void) { inAAGunMode = !inAAGunMode; EnterAAMasterMode(); } void FireControlComputer::ToggleAGGunMode(void) { inAGGunMode = !inAGGunMode; EnterAGMasterMode(); } void FireControlComputer::UpdateWeaponPtr(void) { // the fccWeaponPointer is ONLY used to access weapon data, impact prediction etc, it is NEVER fired. int wid; wid = Sms->GetCurrentWeaponId(); if(wid != fccWeaponId) { fccWeaponPtr.reset(); fccWeaponId = wid; if(fccWeaponId) { Falcon4EntityClassType *classPtr = GetWeaponF4CT(fccWeaponId); if(classPtr) { if ( classPtr->vuClassData.classInfo_[VU_TYPE] == TYPE_MISSILE || classPtr->vuClassData.classInfo_[VU_TYPE] == TYPE_ROCKET ){ fccWeaponPtr.reset(InitAMissile(Sms->Ownship(), fccWeaponId, 0)); } else { if ( classPtr->vuClassData.classInfo_[VU_TYPE] == TYPE_BOMB || ( classPtr->vuClassData.classInfo_[VU_TYPE] == TYPE_ELECTRONICS && classPtr->vuClassData.classInfo_[VU_CLASS] == CLASS_VEHICLE ) || ( classPtr->vuClassData.classInfo_[VU_TYPE] == TYPE_FUEL_TANK && classPtr->vuClassData.classInfo_[VU_STYPE] == STYPE_FUEL_TANK ) || ( classPtr->vuClassData.classInfo_[VU_TYPE] == TYPE_RECON && classPtr->vuClassData.classInfo_[VU_STYPE] == STYPE_CAMERA ) || ( classPtr->vuClassData.classInfo_[VU_TYPE] == TYPE_LAUNCHER && classPtr->vuClassData.classInfo_[VU_STYPE] == STYPE_ROCKET ) ){ fccWeaponPtr.reset(InitABomb(Sms->Ownship(), fccWeaponId, 0)); } } } if (fccWeaponPtr && fccWeaponPtr->IsLauncher()){ wid = ((BombClass *)fccWeaponPtr.get())->LauGetWeaponId(); if(wid != rocketWeaponId){ if(wid){ rocketPointer.reset((MissileClass *)InitAMissile(Sms->Ownship(), wid, 0)); } else{ rocketPointer.reset(0); } rocketWeaponId = wid; } } } } } void FireControlComputer::SetSms(SMSClass *SMS) { Sms = SMS; // setup default HPs for MMs // dogfight if(!Sms->FindWeaponType (wtAim9)) Sms->FindWeaponType(wtAim120); lastDogfightHp = Sms->CurHardpoint(); // missile override & aamm if(!Sms->FindWeaponType (wtAim120)) Sms->FindWeaponType(wtAim9); lastMissileOverrideHp = Sms->CurHardpoint(); lastAirAirHp = Sms->CurHardpoint(); // agmm /*if(!Sms->FindWeaponType (wtAgm88)) if(!Sms->FindWeaponType (wtAgm65)) if(!Sms->FindWeaponType (wtGBU)) if(!Sms->FindWeaponType (wtGPS)) if(!Sms->FindWeaponType (wtMk84)) if(!Sms->FindWeaponType (wtMk82)) Sms->FindWeaponClass (wcRocketWpn); // used to be: Sms->FindWeaponType (wtLAU); but jammers are marks as wtLAU :rolleyes:*/ //Cobra if(!Sms->FindWeaponType (wtAgm88)) if(!Sms->FindWeaponType (wtAgm65)) if(!Sms->FindWeaponType (wtGBU)) if(!Sms->FindWeaponType (wtGPS)) if(!Sms->FindWeaponType (wtMk84)) if(!Sms->FindWeaponType (wtMk82)) if(!Sms->FindWeaponClass (wcRocketWpn)) Sms->FindWeaponClass (wcGunWpn); //end if(Sms->CurHardpoint() > 0) { switch(Sms->hardPoint[Sms->CurHardpoint()]->GetWeaponClass()) { case wcRocketWpn: lastAgMasterMode = AirGroundRocket; break; case wcBombWpn: lastAgMasterMode = AirGroundBomb; break; case wcAgmWpn: lastAgMasterMode = AirGroundMissile; break; case wcHARMWpn: lastAgMasterMode = AirGroundHARM; break; case wcGbuWpn: lastAgMasterMode = AirGroundLaser; break; case wcCamera: lastAgMasterMode = AirGroundCamera; break; default: lastAgMasterMode = AirGroundBomb; } } lastAirGroundHp = Sms->CurHardpoint(); // Set us up in Gun mode if we have no AA or AG stores if(lastAirAirHp == -1) { inAAGunMode = 1; } //Cobra change to HP 0 for Gun from -1 if(lastAirGroundHp == 0) { inAGGunMode = 1; } } // RV - I-Hawk - Added function bool FireControlComputer::AllowMaddog() { if ( Sms && Sms->GetCurrentWeaponType() == wtAim120 ) { MissileClass* currMissile = (MissileClass*)Sms->GetCurrentWeapon(); if ( !targetPtr && currMissile && currMissile->isSlave ) { return false; } } return true; }
24.072114
192
0.656846
IsraelyFlightSimulator
dcb191f58b8f8965632d152292210f1c119e9587
847
cpp
C++
Sid's Levels/Level - 2/Recursion/Subset2.cpp
Tiger-Team-01/DSA-A-Z-Practice
e08284ffdb1409c08158dd4e90dc75dc3a3c5b18
[ "MIT" ]
14
2021-08-22T18:21:14.000Z
2022-03-08T12:04:23.000Z
Sid's Levels/Level - 2/Recursion/Subset2.cpp
Tiger-Team-01/DSA-A-Z-Practice
e08284ffdb1409c08158dd4e90dc75dc3a3c5b18
[ "MIT" ]
1
2021-10-17T18:47:17.000Z
2021-10-17T18:47:17.000Z
Sid's Levels/Level - 2/Recursion/Subset2.cpp
Tiger-Team-01/DSA-A-Z-Practice
e08284ffdb1409c08158dd4e90dc75dc3a3c5b18
[ "MIT" ]
5
2021-09-01T08:21:12.000Z
2022-03-09T12:13:39.000Z
class Solution { public: void subsets(vector<int> nums, set<vector<int>> &s, int i, vector<int> r) { if(i == nums.size()) { sort(r.begin(), r.end()); s.insert(r); return; } else { subsets(nums, s, i+1, r); r.push_back(nums[i]); subsets(nums, s, i+1, r); } } vector<vector<int>> subsetsWithDup(vector<int>& nums) { //OM GAN GANAPATHAYE NAMO NAMAH //JAI SHRI RAM //JAI BAJRANGBALI //AMME NARAYANA, DEVI NARAYANA, LAKSHMI NARAYANA, BHADRE NARAYANA set<vector<int>> s; vector<int> r; subsets(nums, s, 0, r); vector<vector<int>> res; for(auto it = s.begin(); it != s.end(); it++) res.push_back(*it); return res; } };
26.46875
77
0.475797
Tiger-Team-01
dcb1bd3f76d5ed4ec7788822aef7f5dbf4380dd7
530
cpp
C++
cisco-ios-xe/ydk/models/cisco_ios_xe/Cisco_IOS_XE_eem.cpp
CiscoDevNet/ydk-cpp
ef7d75970f2ef1154100e0f7b0a2ee823609b481
[ "ECL-2.0", "Apache-2.0" ]
17
2016-12-02T05:45:49.000Z
2022-02-10T19:32:54.000Z
cisco-ios-xe/ydk/models/cisco_ios_xe/Cisco_IOS_XE_eem.cpp
CiscoDevNet/ydk-cpp
ef7d75970f2ef1154100e0f7b0a2ee823609b481
[ "ECL-2.0", "Apache-2.0" ]
2
2017-03-27T15:22:38.000Z
2019-11-05T08:30:16.000Z
cisco-ios-xe/ydk/models/cisco_ios_xe/Cisco_IOS_XE_eem.cpp
CiscoDevNet/ydk-cpp
ef7d75970f2ef1154100e0f7b0a2ee823609b481
[ "ECL-2.0", "Apache-2.0" ]
11
2016-12-02T05:45:52.000Z
2019-11-07T08:28:17.000Z
#include <sstream> #include <iostream> #include <ydk/entity_util.hpp> #include "bundle_info.hpp" #include "generated_entity_lookup.hpp" #include "Cisco_IOS_XE_eem.hpp" using namespace ydk; namespace cisco_ios_xe { namespace Cisco_IOS_XE_eem { const Enum::YLeaf OperatorType::eq {0, "eq"}; const Enum::YLeaf OperatorType::ge {1, "ge"}; const Enum::YLeaf OperatorType::gt {2, "gt"}; const Enum::YLeaf OperatorType::le {3, "le"}; const Enum::YLeaf OperatorType::lt {4, "lt"}; const Enum::YLeaf OperatorType::ne {5, "ne"}; } }
21.2
45
0.720755
CiscoDevNet
dcb2961b51cfe8469920dfbeb1b1c061f228c712
3,198
cc
C++
main.cc
purpl3F0x/MQA_identifier
3f9ece1cf6ca407ee4c251ab9f1e3d98013d75eb
[ "Apache-2.0" ]
57
2020-01-04T22:45:55.000Z
2022-03-28T07:01:53.000Z
main.cc
purpl3F0x/MQA_identifier
3f9ece1cf6ca407ee4c251ab9f1e3d98013d75eb
[ "Apache-2.0" ]
15
2019-12-11T17:01:26.000Z
2022-03-17T15:04:40.000Z
main.cc
purpl3F0x/MQA_identifier
3f9ece1cf6ca407ee4c251ab9f1e3d98013d75eb
[ "Apache-2.0" ]
8
2020-02-28T18:01:12.000Z
2022-01-26T15:57:27.000Z
/** * @file main.cc * @author Stavros Avramidis (@purpl3F0x) * @date 16/12/2019 * @copyright 2019 Stavros Avramidis under Apache 2.0 License */ #include <filesystem> #include <iomanip> #include <iostream> #include <sstream> #include <string> #include <vector> #include "mqa_identifier.h" namespace fs = std::filesystem; auto getSampleRateString(const uint32_t fs) { std::stringstream ss; if (fs <= 768000) ss << fs / 1000. << "K"; else if (fs % 44100 == 0) ss << "DSD" << fs / 44100; else ss << "DSD" << fs / 48000 << "x48"; return ss.str(); } /** * @short Recursively scan a directory for .flac files * @param curDir directory to scan * @param files vector to add the file paths */ void recursiveScan(const fs::directory_entry &curDir, std::vector<std::string> &files) { for (const auto &entry : fs::directory_iterator(curDir)) { if (fs::is_regular_file(entry) && (fs::path(entry).extension() == ".flac")) files.push_back(entry.path().string()); else if (fs::is_directory(entry)) recursiveScan(entry, files); } } int main(int argc, char *argv[]) { std::vector<std::string> files; if (argc == 1) { std::cout << "HINT: To use the tool provide files and/or directories as program arguments\n\n"; } for (auto argn = 1; argn < argc; argn++) { if (fs::is_directory(argv[argn])) recursiveScan(fs::directory_entry(argv[argn]), files); else if (fs::is_regular_file(argv[argn])) { if (fs::path(argv[argn]).extension() == ".flac") files.emplace_back(argv[argn]); else std::cerr << argv[argn] << " not .flac file\n"; } } // Flush error buffer (just to make sure our print is pretty and no error line get in between) std::cerr << std::flush; // Let's do some printing std::cout << "**************************************************\n"; std::cout << "*********** MQA flac identifier tool ***********\n"; std::cout << "******** Stavros Avramidis (@purpl3F0x) ********\n"; std::cout << "** https://github.com/purpl3F0x/MQA_identifier **\n"; std::cout << "**************************************************\n"; std::cout << "Found " << files.size() << " file for scanning...\n\n"; // Start parsing the files size_t count = 0; size_t mqa_files = 0; std::cout << " #\tEncoding\t\tName\n"; for (const auto &file : files) { std::cout << std::setw(3) << ++count << "\t"; auto id = MQA_identifier(file); if (id.detect()) { std::cout << "MQA " << (id.isMQAStudio() ? "Studio " : "") << getSampleRateString(id.originalSampleRate()) << " \t" << fs::path(file).filename().string() << "\n"; mqa_files++; } else std::cout << "NOT MQA \t" << fs::path(file).filename().string() << "\n"; } std::cout << "\n**************************************************\n"; std::cout << "Scanned " << files.size() << " files\n"; std::cout << "Found " << mqa_files << " MQA files\n"; }
30.75
103
0.518449
purpl3F0x
dcb2dc65f5d0c224f199ea103597941bc05e14bf
11,359
cpp
C++
ARM/Nordic/exemples/BlueIOThingy/BlueIOMPU9250.cpp
tmaltesen/IOsonata
3ada9216305653670fccfca8fd53c6597ace8f12
[ "MIT" ]
94
2015-03-12T14:49:43.000Z
2021-08-05T00:43:50.000Z
ARM/Nordic/exemples/BlueIOThingy/BlueIOMPU9250.cpp
tmaltesen/IOsonata
3ada9216305653670fccfca8fd53c6597ace8f12
[ "MIT" ]
3
2017-06-05T20:36:09.000Z
2021-05-08T21:39:48.000Z
ARM/Nordic/exemples/BlueIOThingy/BlueIOMPU9250.cpp
tmaltesen/IOsonata
3ada9216305653670fccfca8fd53c6597ace8f12
[ "MIT" ]
24
2015-04-22T20:35:28.000Z
2022-01-10T13:08:40.000Z
/* * BLueIOMPU9250.h * * Created on: Jul 25, 2018 * Author: hoan */ #include "app_util_platform.h" #include "app_scheduler.h" #include "istddef.h" #include "ble_app.h" #include "ble_service.h" #include "device_intrf.h" #include "coredev/spi.h" #include "coredev/timer.h" #include "sensors/agm_mpu9250.h" #include "imu/imu_mpu9250.h" #include "idelay.h" #include "board.h" #include "BlueIOThingy.h" #include "BlueIOMPU9250.h" static const ACCELSENSOR_CFG s_AccelCfg = { .DevAddr = 0, .OpMode = SENSOR_OPMODE_CONTINUOUS, .Freq = 50000, .Scale = 2, .FltrFreq = 0, .bInter = true, .IntPol = DEVINTR_POL_LOW, }; static const GYROSENSOR_CFG s_GyroCfg = { .DevAddr = 0, .OpMode = SENSOR_OPMODE_CONTINUOUS, .Freq = 50000, .Sensitivity = 10, .FltrFreq = 200, }; static const MAGSENSOR_CFG s_MagCfg = { .DevAddr = 0, .OpMode = SENSOR_OPMODE_CONTINUOUS,//SENSOR_OPMODE_SINGLE, .Freq = 50000, .Precision = MAGSENSOR_PRECISION_HIGH, }; AgmMpu9250 g_Mpu9250; static void ImuEvtHandler(Device * const pDev, DEV_EVT Evt); static const IMU_CFG s_ImuCfg = { .EvtHandler = ImuEvtHandler }; static ImuMpu9250 s_Imu; static Timer * s_pTimer; static uint32_t s_MotionFeature = 0; int8_t g_AlignMatrix[9] = { 0, 1, 0, -1, 0, 0, 0, 0, -1 }; #if 0 /**@brief Acclerometer rotation matrix. * * @note Accellerometer inverted to get positive readings when axis is aligned with g (down). */ static struct platform_data_s s_accel_pdata = { .orientation = { 0, 1, 0, -1, 0, 0, 0, 0, -1} }; /* The sensors can be mounted onto the board in any orientation. The mounting * matrix seen below tells the MPL how to rotate the raw data from the * driver(s). * TODO: The following matrices refer to the configuration on internal test * boards at Invensense. If needed, please modify the matrices to match the * chip-to-body matrix for your particular set up. */ #if 1 static struct platform_data_s gyro_pdata = { .orientation = { 0, 1, 0, -1, 0, 0, 0, 0, -1} }; #else // BLUEIO-TAG-EVIM static struct platform_data_s gyro_pdata = { .orientation = { 0, 1, 0, 1, 0, 0, 0, 0, 1} }; #endif #if defined MPU9150 || defined MPU9250 static struct platform_data_s compass_pdata = { #if 1 .orientation = { 1, 0, 0, 0, 1, 0, 0, 0, -1} #else .orientation = { 1, 0, 0, 0, -1, 0, 0, 0, -1} #endif }; #define COMPASS_ENABLED 1 #elif defined AK8975_SECONDARY static struct platform_data_s compass_pdata = { .orientation = {-1, 0, 0, 0, 1, 0, 0, 0,-1} }; #define COMPASS_ENABLED 1 #elif defined AK8963_SECONDARY static struct platform_data_s compass_pdata = { .orientation = {-1, 0, 0, 0,-1, 0, 0, 0, 1} }; #define COMPASS_ENABLED 1 #endif #endif void ImuRawDataSend(ACCELSENSOR_DATA &AccData, GYROSENSOR_DATA GyroData, MAGSENSOR_DATA &MagData); void ImuQuatDataSend(long Quat[4]); static void ImuDataChedHandler(void * p_event_data, uint16_t event_size) { ACCELSENSOR_DATA accdata; GYROSENSOR_DATA gyrodata; MAGSENSOR_DATA magdata; IMU_QUAT quat; long q[4]; s_Imu.Read(accdata); s_Imu.Read(gyrodata); s_Imu.Read(magdata); ImuRawDataSend(accdata, gyrodata, magdata); s_Imu.Read(quat); //q[0] = ((float)quat.Q[0] / 32768.0) * (float)(1<<30); //q[1] = ((float)quat.Q[1] / 32768.0) * (float)(1<<30); //q[2] = ((float)quat.Q[2] / 32768.0) * (float)(1<<30); //q[3] = ((float)quat.Q[3] / 32768.0) * (float)(1<<30); //q[0] = quat.Q[0] << 15; //q[1] = quat.Q[1] << 15; //q[2] = quat.Q[2] << 15; //q[3] = quat.Q[3] << 15; q[0] = quat.Q[0] * (1 << 30); q[1] = quat.Q[1] * (1 << 30); q[2] = quat.Q[2] * (1 << 30); q[3] = quat.Q[3] * (1 << 30); //printf("Quat %d: %d %d %d %d\r\n", quat.Timestamp, q[0], q[1], q[2], q[3]); ImuQuatDataSend(q); } static void ImuEvtHandler(Device * const pDev, DEV_EVT Evt) { switch (Evt) { case DEV_EVT_DATA_RDY: app_sched_event_put(NULL, 0, ImuDataChedHandler); //ImuDataChedHandler(NULL, 0); //g_MotSensor.Read(accdata); break; } } void MPU9250IntHandler(int IntNo) { s_Imu.IntHandler(); return; } void mpulib_data_handler_cb() { } void MPU9250EnableFeature(uint32_t Feature) { s_MotionFeature |= Feature; } static void mpulib_tap_cb(unsigned char direction, unsigned char count) { // ble_tms_tap_t tap; // tap.dir = direction; // tap.cnt = count; // BleSrvcCharNotify(GetImuSrvcInstance(), 2, (uint8_t*)&tap, sizeof(ble_tms_tap_t)); /* if (m_motion.features & DRV_MOTION_FEATURE_MASK_TAP) { drv_motion_evt_t evt = DRV_MOTION_EVT_TAP; uint8_t data[2] = {direction, count}; m_motion.evt_handler(&evt, data, sizeof(data)); } */ #ifdef MOTION_DEBUG switch (direction) { case TAP_X_UP: NRF_LOG_DEBUG("drv_motion: tap x+ "); break; case TAP_X_DOWN: NRF_LOG_DEBUG("drv_motion: tap x- "); break; case TAP_Y_UP: NRF_LOG_DEBUG("drv_motion: tap y+ "); break; case TAP_Y_DOWN: NRF_LOG_DEBUG("drv_motion: tap y- "); break; case TAP_Z_UP: NRF_LOG_DEBUG("drv_motion: tap z+ "); break; case TAP_Z_DOWN: NRF_LOG_DEBUG("drv_motion: tap z- "); break; default: return; } NRF_LOG_DEBUG("x%d\r\n", count); #endif } static void mpulib_orient_cb(unsigned char orientation) { BleSrvcCharNotify(GetImuSrvcInstance(), 2, &orientation, 1); /* if (m_motion.features & DRV_MOTION_FEATURE_MASK_ORIENTATION) { drv_motion_evt_t evt = DRV_MOTION_EVT_ORIENTATION; m_motion.evt_handler(&evt, &orientation, 1); } */ #ifdef MOTION_DEBUG switch (orientation) { case ANDROID_ORIENT_PORTRAIT: NRF_LOG_DEBUG("Portrait\r\n"); break; case ANDROID_ORIENT_LANDSCAPE: NRF_LOG_DEBUG("Landscape\r\n"); break; case ANDROID_ORIENT_REVERSE_PORTRAIT: NRF_LOG_DEBUG("Reverse Portrait\r\n"); break; case ANDROID_ORIENT_REVERSE_LANDSCAPE: NRF_LOG_DEBUG("Reverse Landscape\r\n"); break; default: return; } #endif } SPI *g_pSpi = NULL; bool MPU9250Init(DeviceIntrf * const pIntrF, Timer * const pTimer) { g_pSpi = (SPI*)pIntrF; s_pTimer = pTimer; bool res = g_Mpu9250.Init(s_AccelCfg, pIntrF, pTimer); if (res == false) return res; g_Mpu9250.Init(s_GyroCfg, NULL); g_Mpu9250.Init(s_MagCfg, NULL); IOPinConfig(BLUEIO_TAG_EVIM_IMU_INT_PORT, BLUEIO_TAG_EVIM_IMU_INT_PIN, BLUEIO_TAG_EVIM_IMU_INT_PINOP, IOPINDIR_INPUT, IOPINRES_PULLUP, IOPINTYPE_NORMAL); IOPinEnableInterrupt(BLUEIO_TAG_EVIM_IMU_INT_NO, 6, BLUEIO_TAG_EVIM_IMU_INT_PORT, BLUEIO_TAG_EVIM_IMU_INT_PIN, IOPINSENSE_LOW_TRANSITION, MPU9250IntHandler); // g_Mpu9250.Enable(); #if 0 while (1) { long l[3]; g_Mpu9250.UpdateData(); ACCELSENSOR_DATA accdata; g_Mpu9250.Read(accdata); l[0] = accdata.X; l[1] = accdata.Y; l[2] = accdata.Z; inv_build_accel(l, 0, accdata.Timestamp); } #endif s_Imu.Init(s_ImuCfg, &g_Mpu9250, &g_Mpu9250, &g_Mpu9250); s_Imu.SetAxisAlignmentMatrix(g_AlignMatrix); s_Imu.Quaternion(true, 6); //s_Imu.Compass(true); return true; } int Mpu9250AuxRead(uint8_t DevAddr, uint8_t *pCmdAddr, int CmdAddrLen, uint8_t *pBuff, int BuffLen) { int retval = 0; uint8_t regaddr; uint8_t d[8]; d[0] = MPU9250_AG_I2C_SLV0_ADDR; d[1] = DevAddr | MPU9250_AG_I2C_SLV0_ADDR_I2C_SLVO_RD; d[2] = *pCmdAddr; while (BuffLen > 0) { int cnt = min(15, BuffLen); d[3] = MPU9250_AG_I2C_SLV0_CTRL_I2C_SLV0_EN |cnt; g_pSpi->Write(0, d, 4, NULL, 0); // Delay require for transfer to complete usDelay(300 + (cnt << 4)); regaddr = MPU9250_AG_EXT_SENS_DATA_00; cnt = g_pSpi->Read(0, &regaddr, 1, pBuff, cnt); if (cnt <=0) break; pBuff += cnt; BuffLen -= cnt; retval += cnt; } return retval; } int Mpu9250AuxWrite(uint8_t DevAddr, uint8_t *pCmdAddr, int CmdAddrLen, uint8_t *pData, int DataLen) { int retval = 0; uint8_t regaddr; uint8_t d[8]; d[0] = MPU9250_AG_I2C_SLV0_ADDR; d[1] = DevAddr; d[2] = *pCmdAddr; d[3] = MPU9250_AG_I2C_SLV0_CTRL_I2C_SLV0_EN; while (DataLen > 0) { regaddr = MPU9250_AG_I2C_SLV0_DO; g_pSpi->Write(0, &regaddr, 1, pData, 1); g_pSpi->Write(0, d, 4, NULL, 0); d[2]++; pData++; DataLen--; retval++; } return retval; } /**@brief Function for writing to a MPU-9250 register. * * @param[in] slave_addr Slave address on the TWI bus. * @param[in] reg_addr Register address to write. * @param[in] length Length of the data to write. * @param[in] p_data Pointer to the data to write. * * @retval 0 if success. Else -1. */ int drv_mpu9250_write(unsigned char slave_addr, unsigned char reg_addr, unsigned char length, unsigned char const * p_data) { if (slave_addr != MPU9250_I2C_DEV_ADDR0 && slave_addr != MPU9250_I2C_DEV_ADDR1) { return Mpu9250AuxWrite(slave_addr, &reg_addr, 1, (uint8_t*)p_data, length) <= 0; } /* else { reg_addr &= 0x7F; return g_pSpi->Write(0, &reg_addr, 1, (uint8_t*)p_data, length) <= 0; }*/ return g_Mpu9250.Write(&reg_addr, 1, (uint8_t*)p_data, length) <= 0; } /**@brief Function for reading a MPU-9250 register. * * @param[in] slave_addr Slave address on the TWI bus. * @param[in] reg_addr Register address to read. * @param[in] length Length of the data to read. * @param[out] p_data Pointer to where the data should be stored. * * @retval 0 if success. Else -1. */ int drv_mpu9250_read(unsigned char slave_addr, unsigned char reg_addr, unsigned char length, unsigned char * p_data) { if (slave_addr != MPU9250_I2C_DEV_ADDR0 && slave_addr != MPU9250_I2C_DEV_ADDR1) { return Mpu9250AuxRead(slave_addr, &reg_addr, 1, (uint8_t*)p_data, length) <= 0; } /* else { reg_addr |= 0x80; return g_pSpi->Read(0, &reg_addr, 1, p_data, length) <= 0; }*/ return g_Mpu9250.Read(&reg_addr, 1, p_data, length) <= 0; } /**@brief Function for getting a timestamp in milliseconds. * * @param[out] p_count Pointer to the timestamp. * * @retval 0 if success. Else -1. */ int drv_mpu9250_ms_get(unsigned long * p_count) { *p_count = s_pTimer->uSecond() / 1000; return 0; } /**@brief Function for enabling and registering the MPU-9250 interrupt callback. * * @param[in] p_int_param Pointer to the interrupt parameter structure. * * @retval 0 if success. Else -1. */ int drv_mpu9250_int_register(struct int_param_s * p_int_param) { printf("drv_mpu9250_int_register\r\n"); IOPinConfig(BLUEIO_TAG_EVIM_IMU_INT_PORT, BLUEIO_TAG_EVIM_IMU_INT_PIN, BLUEIO_TAG_EVIM_IMU_INT_PINOP, IOPINDIR_INPUT, IOPINRES_PULLDOWN, IOPINTYPE_NORMAL); IOPinEnableInterrupt(BLUEIO_TAG_EVIM_IMU_INT_NO, 6, BLUEIO_TAG_EVIM_IMU_INT_PORT, BLUEIO_TAG_EVIM_IMU_INT_PIN, IOPINSENSE_LOW_TRANSITION, MPU9250IntHandler); return 0; }
24.58658
123
0.640725
tmaltesen
dcb6598eb2eb0d9e87bffeb93e34dd6533eadcf1
3,881
hpp
C++
src/sweepers/mc/fission_bank.hpp
tp-ntouran/mocc
77d386cdf341b1a860599ff7c6e4017d46e0b102
[ "Apache-2.0" ]
11
2016-03-31T17:46:15.000Z
2022-02-14T01:07:56.000Z
src/sweepers/mc/fission_bank.hpp
tp-ntouran/mocc
77d386cdf341b1a860599ff7c6e4017d46e0b102
[ "Apache-2.0" ]
3
2016-04-04T16:40:47.000Z
2019-10-16T22:22:54.000Z
src/sweepers/mc/fission_bank.hpp
tp-ntouran/mocc
77d386cdf341b1a860599ff7c6e4017d46e0b102
[ "Apache-2.0" ]
3
2019-10-16T22:20:15.000Z
2019-11-28T11:59:03.000Z
/* Copyright 2016 Mitchell Young Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #pragma once #include <array> #include <iosfwd> #include <vector> #include "util/global_config.hpp" #include "util/pugifwd.hpp" #include "util/rng_lcg.hpp" #include "core/core_mesh.hpp" #include "core/geometry/geom.hpp" #include "core/xs_mesh.hpp" #include "particle.hpp" namespace mocc { namespace mc { /** * A FissionBank stores a sequence of fission sites. Nothing fancy */ class FissionBank { public: FissionBank(const CoreMesh &mesh); /** * \brief Construct a FissionBank by uniformly sampling fission sites. * * \param input XML node containing bounds of a 3-D box within which to * sample initial fission sites * \param n the number of initial sites to sample * \param mesh the \ref CoreMesh to use for initial sampling * \param xs_mesh the \ref XSMesh to use for initial sampling * \param rng a reference to the random number generator to be used for * sampling initial fission sites. * * This constructor initializes a \ref FissionBank using input specified in * an XML node. */ FissionBank(const pugi::xml_node &input, int n, const CoreMesh &mesh, const XSMesh &xs_mesh, RNG_LCG &rng); auto begin() { return sites_.begin(); } const auto begin() const { return sites_.cbegin(); } auto end() { return sites_.end(); } const auto end() const { return sites_.cend(); } int size() const { return sites_.size(); } /** * \brief Add a new fission site to the \ref FissionBank * * \param p a \ref Point3 for the location of the fission site * * This method adds a new fission site to the fission bank, and makes a * contribution to the total number of neutrons that were generated into * the bank. */ void push_back(Particle &p) { #pragma omp critical { sites_.push_back(p); total_fission_ += p.weight; } return; } /** * \brief Return the Shannon entropy of the fission bank. * * This is used to estimate the change in the spatial distribution of * fission sites from generation to generation. Observing little * variation in this metric throughout the active cycles lends some * confidence that the fission source distribution was well converged * before beginning active cycles. */ real_t shannon_entropy() const; /** * \brief Swap contents with another \ref FissionBank * * \param other the other \ref FissionBank to swap with */ void swap(FissionBank &other); const auto &operator[](unsigned i) const { return sites_[i]; } /** * \brief Clear the \ref FissionBank of all fission sites */ void clear() { #pragma omp single { sites_.clear(); total_fission_ = 0.0; } } void resize(unsigned int n, RNG_LCG &rng); real_t total_fission() const { return total_fission_; } friend std::ostream &operator<<(std::ostream &os, const FissionBank &bank); private: const CoreMesh &mesh_; std::vector<Particle> sites_; real_t total_fission_; }; } // namespace mc } // namespace mocc
25.532895
79
0.644164
tp-ntouran
dcb688dac9c295fec11fe28b1e4585d74298aa9e
366
cpp
C++
Engine/Plugins/Editor/PluginBrowser/Templates/ThirdPartyLibrary/Source/ThirdParty/PLUGIN_NAMELibrary/ExampleLibrary.cpp
windystrife/UnrealEngine_NVIDIAGameWork
b50e6338a7c5b26374d66306ebc7807541ff815e
[ "MIT" ]
1
2022-01-29T18:36:12.000Z
2022-01-29T18:36:12.000Z
Engine/Plugins/Editor/PluginBrowser/Templates/ThirdPartyLibrary/Source/ThirdParty/PLUGIN_NAMELibrary/ExampleLibrary.cpp
windystrife/UnrealEngine_NVIDIAGameWork
b50e6338a7c5b26374d66306ebc7807541ff815e
[ "MIT" ]
null
null
null
Engine/Plugins/Editor/PluginBrowser/Templates/ThirdPartyLibrary/Source/ThirdParty/PLUGIN_NAMELibrary/ExampleLibrary.cpp
windystrife/UnrealEngine_NVIDIAGameWork
b50e6338a7c5b26374d66306ebc7807541ff815e
[ "MIT" ]
null
null
null
#if defined _WIN32 || defined _WIN64 #include <Windows.h> #define DLLEXPORT __declspec(dllexport) #else #include <stdio.h> #endif #ifndef DLLEXPORT #define DLLEXPORT #endif DLLEXPORT void ExampleLibraryFunction() { #if defined _WIN32 || defined _WIN64 MessageBox(NULL, TEXT("Hello world!"), NULL, MB_OK); #else printf("Hello World"); #endif }
18.3
53
0.70765
windystrife
dcb6a1644cf3c3baa909cf163721d1324f193a37
369
cpp
C++
src/23/zad3_9.cpp
AdamSiekierski/cpp
09b9a46b44ecce5cc1d6e0cb9d1c689b350563d5
[ "WTFPL" ]
2
2020-10-27T11:56:10.000Z
2020-10-27T12:42:32.000Z
src/23/zad3_9.cpp
AdamSiekierski/cpp
09b9a46b44ecce5cc1d6e0cb9d1c689b350563d5
[ "WTFPL" ]
null
null
null
src/23/zad3_9.cpp
AdamSiekierski/cpp
09b9a46b44ecce5cc1d6e0cb9d1c689b350563d5
[ "WTFPL" ]
null
null
null
#include <iostream> int main() { float x; int n; std::cout << "Podaj x i n: "; std::cin >> x >> n; switch (n) { case 1: std::cout << "y = " << sqrt(2 * x); break; case 2: std::cout << "y = " << (x * x) - 5; break; case 3: std::cout << "y = " << cos(x) + 1; break; default: std::cout << "y = " << 1; } return 0; }
13.178571
39
0.414634
AdamSiekierski
dcb7c38bae57b96d1ec8c378f65844df77ba0800
4,355
cc
C++
LibreOJ/2245.cc
DesZou/Eros
f49c9ce1dfe193de8199163286afc28ff8c52eef
[ "MIT" ]
1
2017-10-12T13:49:10.000Z
2017-10-12T13:49:10.000Z
LibreOJ/2245.cc
DesZou/Eros
f49c9ce1dfe193de8199163286afc28ff8c52eef
[ "MIT" ]
null
null
null
LibreOJ/2245.cc
DesZou/Eros
f49c9ce1dfe193de8199163286afc28ff8c52eef
[ "MIT" ]
1
2017-10-12T13:49:38.000Z
2017-10-12T13:49:38.000Z
/* * libreoj2245 * * LCT 维护最大值。 * 首先把边按 a 权值排序,从小到大加入,那么所需的 a 就是当前边的 a 。 * 然后用 LCT 维护从 1 到 n 的路径的 b 权值的最大值。 * 由于维护的是边权,我们要给边特别地开点,然后把本来应该相连的点连到两边。 * 动态维护一棵最小生成树,每次加入一条从 u 到 v 的路径的时候就把原来的 * u, v 之间的路径拉出来查询一下路径上的最大值,如果比当前的边要大, * 就把代表这条边的点从路径里拿出来,再把新边放进去。 * */ #include <cstdio> #include <algorithm> #include <iostream> const size_t Size = 5e4 + 5; const int Inf = -1u >> 1; template<class T> T max(const T &a, const T &b) { return a > b? a : b; } template<class T> T min(const T &a, const T &b) { return a < b? a : b; } template<class T> bool chkmin(T &a, const T &b) { return a > b? a = b, 1 : 0; } template<class T> bool chkmax(T &a, const T &b) { return a <b? a = b, 1 : 0; } struct IM { template<class T> IM& operator>>(T &a) { a = 0; char c = getchar(); bool n = false; for(;!isdigit(c); c = getchar()) if(c == '-') n = 1; for(; isdigit(c); c = getchar()) a = a * 10 - 48 + c; if(n) a = -a; return *this; } } getInt; struct UnionFindSet { int fa[Size * 4]; void init(int x) { for(int i = 1; i <= x; ++i) fa[i] = i; } int find(int x) { return x == fa[x]? x : fa[x] = find(fa[x]); } int& operator[](const int &x) { return fa[x]; } } set; struct Edge { int u, v, a, b; } e[Size * 2]; bool operator<(const Edge &a, const Edge &b) { return a.a < b.a; } struct Node { int val, id; Node *fa, *ch[2], *mx; bool rev; bool isroot() { return fa? (fa->ch[0] != this && fa->ch[1] != this) : true; } void pushup() { mx = this; if(ch[0] && ch[0]->mx->val > mx->val) mx = ch[0]->mx; if(ch[1] && ch[1]->mx->val > mx->val) mx = ch[1]->mx; } void reverse() { rev ^= 1; std::swap(ch[0], ch[1]); } void pushdown() { if(rev) { if(ch[0]) ch[0]->reverse(); if(ch[1]) ch[1]->reverse(); rev = 0; } } bool operator!() { return fa->ch[1] == this; } } nd[Size * 4]; void rotate(Node *x) { Node *y = x->fa; bool d = !*x; // must take care here, !*x IS NOT !x if(!y->isroot()) y->fa->ch[!*y] = x; x->fa = y->fa; y->fa = x; y->ch[d] = x->ch[!d]; x->ch[!d] = y; if(y->ch[d]) y->ch[d]->fa = y; y->pushup(); x->pushup(); } void push(Node *x) { if(!x->isroot()) push(x->fa); x->pushdown(); } void splay(Node *x) { push(x); for(Node *y = x->fa; !x->isroot(); y = x->fa) { if(!y->isroot()) rotate(!*x == !*y? y : x); rotate(x); } } void access(Node *x) { for(Node *y = NULL; x; x = (y = x)->fa) { splay(x); x->ch[1] = y; x->pushup(); } } void makeroot(Node *x) { access(x); splay(x); x->reverse(); } Node* findroot(Node *x) { access(x); splay(x); while(x->ch[0]) x = x->ch[0]; return x; } void link(Node *x, Node *y) { makeroot(x); if(findroot(y) != x) x->fa = y; } void cut(Node *x, Node *y) { makeroot(x); if(findroot(y) == x && x->fa == y && x->ch[1] == NULL) { x->fa = y->ch[0] = NULL; y->pushup(); } } void split(Node *x, Node *y) { makeroot(x); access(y); splay(y); } int query(int x, int y) { split(&nd[x], &nd[y]); return nd[y].mx->val; } int n, m; int ans = Inf; int main() { getInt >> n >> m; set.init(n); for(int i = 1; i <= m; ++i) { getInt >> e[i].u >> e[i].v >> e[i].a >> e[i].b; } std::sort(e + 1, e + 1 + m); for(int i = 1, u, v, a, b; i <= m; ++i) { u = e[i].u, v = e[i].v, a = e[i].a, b = e[i].b; if(set.find(u) == set.find(v)) { split(&nd[u], &nd[v]); Node *x = nd[v].mx; if(x->val > b) { cut(x, &nd[e[x->id].u]); cut(x, &nd[e[x->id].v]); } else { // if(set.find(1) == set.find(n)) chkmin(ans, a + query(1, n)); continue; } } else { set[set[u]] = set[v]; } nd[n + i].val = b; nd[n + i].mx = &nd[n + 1]; nd[n + i].id = i; link(&nd[u], &nd[n + i]); link(&nd[v], &nd[n + i]); if(set.find(1) == set.find(n)) chkmin(ans, a + query(1, n)); } std::printf("%d\n", ans == Inf? -1 : ans); return 0; }
20.162037
79
0.439265
DesZou
dcb7d026a3fa1e6f2ee4d10da9242592af650434
3,224
cpp
C++
EVENTS/GeoClawOpenFOAM/swsolvers/geoclaw/geoclaw.cpp
claudioperez/HydroUQ
89447d50524057f7e30d9d31e04f074a94095aad
[ "BSD-2-Clause" ]
2
2021-03-03T06:37:21.000Z
2021-03-29T20:46:37.000Z
EVENTS/GeoClawOpenFOAM/swsolvers/geoclaw/geoclaw.cpp
claudioperez/HydroUQ
89447d50524057f7e30d9d31e04f074a94095aad
[ "BSD-2-Clause" ]
10
2021-07-22T04:22:28.000Z
2021-07-29T02:16:52.000Z
EVENTS/GeoClawOpenFOAM/swsolvers/geoclaw/geoclaw.cpp
claudioperez/HydroUQ
89447d50524057f7e30d9d31e04f074a94095aad
[ "BSD-2-Clause" ]
9
2020-05-18T18:37:44.000Z
2021-08-02T18:12:49.000Z
#include "geoclaw.h" #include "H20utilities/h20utilities.h" //********************************************************************************* // GeoClaw starts here //********************************************************************************* geoclaw::geoclaw(int flag, QStringList data) { // If needed to reach the topo information if(flag == 1) { QString topofilepath = data[0]; QString destination = data[1]; readtopo(); } // Get total number of timesteps if(flag == 2) { // data[0] - file path to working directory int totaltimesteps = gclawtotaltime(data[0]); } } //********************************************************************************* // Read the Geoclaw file //********************************************************************************* void geoclaw::readtopo() { } //********************************************************************************* // Get total timesteps in the Geoclaw file //********************************************************************************* int geoclaw::gclawtotaltime(QString filepath) { // Local temporary variables int ii = 1; int checkt = 0; int checkq = 0; do { // Get filepaths for t-files QString tfilename = getfilename(filepath,ii,1); // Get filepaths for q-files QString qfilename = getfilename(filepath,ii,2); // Check for existence of files H20Utilities utility; checkt = utility.fileexistance(tfilename.toStdString()); checkq = utility.fileexistance(qfilename.toStdString()); // If both files exist, use up to that time step // Else produce an error accordingly if ((checkt == 0) && (checkq == 0)) ii = ii + 1; else ii = ii - 1; } while((checkt == 0) && (checkq == 0)); // Return the flag int totaltimesteps =ii; return totaltimesteps; } //********************************************************************************* // Get filename of the GeoClaw file //********************************************************************************* QString geoclaw::getfilename(QString path, int timestep, int flag) { QString fullpath; if(flag == 1) //For t-files { if((timestep >= 0) && (timestep < 10)) fullpath = path + "/fort.t000" + QString::number(timestep); else if((timestep > 9) && (timestep < 100)) fullpath = path + "/fort.t00" + QString::number(timestep); else if((timestep > 99) && (timestep < 1000)) fullpath = path + "/fort.t0" + QString::number(timestep); else if((timestep > 999) && (timestep < 10000)) fullpath = path + "/fort.t" + QString::number(timestep); } else if(flag == 2) { if((timestep >= 0) && (timestep < 10)) fullpath = path + "/fort.q000" + QString::number(timestep); else if((timestep > 9) && (timestep < 100)) fullpath = path + "/fort.q00" + QString::number(timestep); else if((timestep > 99) && (timestep < 1000)) fullpath = path + "/fort.q0" + QString::number(timestep); else if((timestep > 999) && (timestep < 10000)) fullpath = path + "/fort.q" + QString::number(timestep); } return fullpath; }
34.297872
112
0.476117
claudioperez
dcbd88bbf7b50be1b27c9846ddd29f0b192622d4
15,217
cpp
C++
tests/index/test_index_fm_rank_dictionary.cpp
kneubert/seqan
3c4f01dbe67ead02b1ca957b217309493f1ddccf
[ "BSD-3-Clause" ]
null
null
null
tests/index/test_index_fm_rank_dictionary.cpp
kneubert/seqan
3c4f01dbe67ead02b1ca957b217309493f1ddccf
[ "BSD-3-Clause" ]
null
null
null
tests/index/test_index_fm_rank_dictionary.cpp
kneubert/seqan
3c4f01dbe67ead02b1ca957b217309493f1ddccf
[ "BSD-3-Clause" ]
null
null
null
// ========================================================================== // SeqAn - The Library for Sequence Analysis // ========================================================================== // Copyright (c) 2006-2016, Knut Reinert, FU Berlin // Copyright (c) 2013 NVIDIA Corporation // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of Knut Reinert or the FU Berlin 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 KNUT REINERT OR THE FU BERLIN 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. // // ========================================================================== // Author: Enrico Siragusa <enrico.siragusa@fu-berlin.de> // ========================================================================== #include <seqan/basic.h> #include <seqan/reduced_aminoacid.h> #include <seqan/index.h> #include "test_index_helpers.h" using namespace seqan; // ========================================================================== // Metafunctions // ========================================================================== // ---------------------------------------------------------------------------- // Metafunction Size // ---------------------------------------------------------------------------- //namespace seqan { //template <typename TValue> //struct Size<RankDictionary<TValue, Levels<unsigned> > > //{ // typedef unsigned Type; //}; //} // ========================================================================== // Types // ========================================================================== // -------------------------------------------------------------------------- // RankDictionary Types // -------------------------------------------------------------------------- typedef SimpleType<unsigned char, ReducedAminoAcid_<Murphy10> > ReducedMurphy10; typedef Levels<void, LevelsPrefixRDConfig<uint32_t, Alloc<>, 1, 1> > Prefix1Level; typedef Levels<void, LevelsPrefixRDConfig<uint32_t, Alloc<>, 2, 2> > Prefix2Level; typedef Levels<void, LevelsPrefixRDConfig<uint32_t, Alloc<>, 3, 3> > Prefix3Level; typedef Levels<void, LevelsRDConfig<uint32_t, Alloc<>, 1, 1> > Default1Level; typedef Levels<void, LevelsRDConfig<uint32_t, Alloc<>, 2, 2> > Default2Level; typedef Levels<void, LevelsRDConfig<uint32_t, Alloc<>, 3, 3> > Default3Level; typedef TagList<RankDictionary<bool, Prefix1Level>, TagList<RankDictionary<Dna, Prefix1Level>, TagList<RankDictionary<Dna5Q, Prefix1Level>, TagList<RankDictionary<ReducedMurphy10, Prefix1Level>, TagList<RankDictionary<AminoAcid, Prefix1Level>, TagList<RankDictionary<bool, Prefix2Level>, TagList<RankDictionary<Dna, Prefix2Level>, TagList<RankDictionary<Dna5Q, Prefix2Level>, TagList<RankDictionary<ReducedMurphy10, Prefix2Level>, TagList<RankDictionary<AminoAcid, Prefix2Level>, TagList<RankDictionary<bool, Prefix3Level>, TagList<RankDictionary<Dna, Prefix3Level>, TagList<RankDictionary<Dna5Q, Prefix3Level>, TagList<RankDictionary<ReducedMurphy10, Prefix3Level>, TagList<RankDictionary<AminoAcid, Prefix3Level>, TagList<RankDictionary<bool, WaveletTree<> >, TagList<RankDictionary<Dna, WaveletTree<> >, TagList<RankDictionary<Dna5Q, WaveletTree<> >, TagList<RankDictionary<AminoAcid, WaveletTree<> > > > > > > > > > > > > > > > > > > > > RankDictionaryPrefixSumTypes; typedef TagList<RankDictionary<bool, Naive<> >, TagList<RankDictionary<bool, Default1Level>, TagList<RankDictionary<Dna, Default1Level>, TagList<RankDictionary<Dna5Q, Default1Level>, TagList<RankDictionary<ReducedMurphy10, Default1Level>, TagList<RankDictionary<AminoAcid, Default1Level>, TagList<RankDictionary<bool, Default2Level>, TagList<RankDictionary<Dna, Default2Level>, TagList<RankDictionary<Dna5Q, Default2Level>, TagList<RankDictionary<ReducedMurphy10, Default2Level>, TagList<RankDictionary<AminoAcid, Default2Level>, TagList<RankDictionary<bool, Default3Level>, TagList<RankDictionary<Dna, Default3Level>, TagList<RankDictionary<Dna5Q, Default3Level>, TagList<RankDictionary<ReducedMurphy10, Default3Level>, TagList<RankDictionary<AminoAcid, Default3Level>, RankDictionaryPrefixSumTypes > > > > > > > > > > > > > > > > RankDictionaryAllTypes; // ========================================================================== // Test Classes // ========================================================================== // -------------------------------------------------------------------------- // Class RankDictionaryTest // -------------------------------------------------------------------------- template <typename TRankDictionary> class RankDictionaryTest : public Test { public: typedef TRankDictionary TRankDict; typedef typename Value<TRankDict>::Type TValue; typedef typename Size<TValue>::Type TValueSize; typedef String<TValue> TText; typedef typename Iterator<TText, Standard>::Type TTextIterator; TValueSize alphabetSize; TText text; TTextIterator textBegin; TTextIterator textEnd; RankDictionaryTest() : alphabetSize(ValueSize<TValue>::VALUE), text(), textBegin(), textEnd() {} void setUp() { generateText(text, 3947); textBegin = begin(text, Standard()); textEnd = end(text, Standard()); } }; template <typename TRankDictionary> class RankDictionaryPrefixTest : public RankDictionaryTest<TRankDictionary> {}; SEQAN_TYPED_TEST_CASE(RankDictionaryTest, RankDictionaryAllTypes); SEQAN_TYPED_TEST_CASE(RankDictionaryPrefixTest, RankDictionaryPrefixSumTypes); // ========================================================================== // Tests // ========================================================================== // ---------------------------------------------------------------------------- // Test RankDictionary() // ---------------------------------------------------------------------------- SEQAN_TYPED_TEST(RankDictionaryTest, Constructor) { typename TestFixture::TRankDict dict(this->text); } // ---------------------------------------------------------------------------- // Test createRankDictionary() // ---------------------------------------------------------------------------- SEQAN_TYPED_TEST(RankDictionaryTest, CreateRankDictionary) { typename TestFixture::TRankDict dict; createRankDictionary(dict, this->text); } // ---------------------------------------------------------------------------- // Test clear() and empty() // ---------------------------------------------------------------------------- SEQAN_TYPED_TEST(RankDictionaryTest, ClearEmpty) { typename TestFixture::TRankDict dict; SEQAN_ASSERT(empty(dict)); createRankDictionary(dict, this->text); SEQAN_ASSERT_NOT(empty(dict)); clear(dict); SEQAN_ASSERT(empty(dict)); } // ---------------------------------------------------------------------------- // Test getValue() // ---------------------------------------------------------------------------- SEQAN_TYPED_TEST(RankDictionaryTest, GetValue) { typedef typename TestFixture::TTextIterator TTextIterator; typename TestFixture::TRankDict dict(this->text); for (TTextIterator textIt = this->textBegin; textIt != this->textEnd; ++textIt) SEQAN_ASSERT_EQ(getValue(dict, (unsigned long)(textIt - this->textBegin)), value(textIt)); } // ---------------------------------------------------------------------------- // Test getRank() // ---------------------------------------------------------------------------- SEQAN_TYPED_TEST(RankDictionaryTest, GetRank) { typedef typename TestFixture::TValueSize TValueSize; typedef typename TestFixture::TText TText; typedef typename TestFixture::TTextIterator TTextIterator; typedef typename Size<TText>::Type TTextSize; typedef String<TTextSize> TPrefixSum; typename TestFixture::TRankDict dict(this->text); // The prefix sum is built while scanning the text. TPrefixSum prefixSum; resize(prefixSum, this->alphabetSize, 0); // Scan the text. for (TTextIterator textIt = this->textBegin; textIt != this->textEnd; ++textIt) { // Update the prefix sum. prefixSum[ordValue(value(textIt))]++; // Check the rank for all alphabet symbols. for (TValueSize c = 0; c < this->alphabetSize; ++c) SEQAN_ASSERT_EQ(getRank(dict, (unsigned long)(textIt - this->textBegin), c), prefixSum[c]); } } SEQAN_TYPED_TEST(RankDictionaryPrefixTest, GetPrefixRank) { typedef typename TestFixture::TValueSize TValueSize; typedef typename TestFixture::TText TText; typedef typename TestFixture::TTextIterator TTextIterator; typedef typename Size<TText>::Type TTextSize; typedef String<TTextSize> TPrefixSum; typename TestFixture::TRankDict dict(this->text); // The prefix sum is built while scanning the text. TPrefixSum prefixSum; resize(prefixSum, this->alphabetSize, 0); // Scan the text. for (TTextIterator textIt = this->textBegin; textIt != this->textEnd; ++textIt) { // Update the prefix sum. prefixSum[ordValue(value(textIt))]++; // Check the rank for all alphabet symbols. unsigned long smallerNaive = 0; for (TValueSize c = 0; c < this->alphabetSize; ++c) { unsigned long smaller; SEQAN_ASSERT_EQ(getRank(dict, (unsigned long)(textIt - this->textBegin), c, smaller), prefixSum[c]); SEQAN_ASSERT_EQ(smaller, smallerNaive); smallerNaive += prefixSum[c]; } } } // ---------------------------------------------------------------------------- // Test setValue() // ---------------------------------------------------------------------------- // NOTE(esiragusa): rename it as assignValue() // ---------------------------------------------------------------------------- // Test length() // ---------------------------------------------------------------------------- // ---------------------------------------------------------------------------- // Test resize() // ---------------------------------------------------------------------------- // ---------------------------------------------------------------------------- // Test reserve() // ---------------------------------------------------------------------------- // ---------------------------------------------------------------------------- // Test open() and save() // ---------------------------------------------------------------------------- // ---------------------------------------------------------------------------- // Test Size<> // ---------------------------------------------------------------------------- //SEQAN_DEFINE_TEST(test_rss_sizeof) //{ // typedef Dna TAlphabet; // typedef Alloc<unsigned> TTextSpec; // typedef String<TAlphabet, TTextSpec> TText; // // typedef Levels<TAlphabet, unsigned> TRankDictionarySpec; // typedef RankDictionary<TRankDictionarySpec> TRankDictionary; // // TRankSupport rs; // // std::cout << "sizeof(Block): " << sizeof(rs.block) << std::endl; // // std::cout << "bits(Block): " << BitsPerValue<TRankSupport::TBlock>::VALUE << std::endl; // std::cout << "length(Block): " << length(rs.block) << std::endl; // std::cout << "capacity(Block): " << capacity(rs.block) << std::endl; // std::cout << std::endl; // // std::cout << "sizeof(SuperBlock): " << sizeof(rs.sblock) << std::endl; // std::cout << "bits(SuperBlock): " << BitsPerValue<TRankSupport::TSuperBlock>::VALUE << std::endl; // std::cout << "length(SuperBlock): " << length(rs.sblock) << std::endl; // std::cout << "capacity(SuperBlock): " << capacity(rs.sblock) << std::endl; // std::cout << std::endl; // // std::cout << "sizeof(RankSupport): " << sizeof(rs) << std::endl; // std::cout << "bits(RankSupport): " << BitsPerValue<TRankSupport>::VALUE << std::endl; // std::cout << std::endl; //} //SEQAN_DEFINE_TEST(test_rss_resize) //{ // typedef Dna TAlphabet; // typedef Alloc<unsigned> TTextSpec; // typedef String<TAlphabet, TTextSpec> TText; // // typedef Levels<TAlphabet, unsigned> TRankDictionarySpec; // typedef RankDictionary<TRankDictionarySpec> TRankDictionary; // //// TText text = "ACGTNACGTNACGTNACGTNA"; // TText text = "ACGTACGTACGTACGTACGTACGTACGTACGT"; //// TText text = "ACGTACGTACGTACGTACGTACGTACGTACGTCCCCCCCCCCCCCCC"; // // TRankDictionary dict(text); //// createRankDictionary(dict, text); // // std::cout << "Text: " << text << std::endl; //// std::cout << "Block: " << rs.block << std::endl; // // for (unsigned i = 0; i < 10; i++) // for (unsigned char c = 0; c < 4; c++) // std::cout << "getRank(" << Dna(c) << ", " << i << "): " << getRank(dict, i, Dna(c)) << std::endl; // // std::cout << std::endl; //} // ========================================================================== // Functions // ========================================================================== int main(int argc, char const ** argv) { TestSystem::init(argc, argv); return TestSystem::runAll(); }
41.576503
112
0.51495
kneubert
dcbf3b49f6c2ef697fad900d545cb2f9e209f432
3,176
hpp
C++
src/app/Events.hpp
uwmisl/purpledrop-stm32
7e40314f244e27fed04379774f00b4659ece3381
[ "MIT" ]
1
2022-03-27T02:32:01.000Z
2022-03-27T02:32:01.000Z
src/app/Events.hpp
uwmisl/purpledrop-stm32
7e40314f244e27fed04379774f00b4659ece3381
[ "MIT" ]
null
null
null
src/app/Events.hpp
uwmisl/purpledrop-stm32
7e40314f244e27fed04379774f00b4659ece3381
[ "MIT" ]
null
null
null
#pragma once #include "AppConfig.hpp" #include "EventEx.hpp" #include "ScanGroups.hpp" using namespace EventEx; /** Defines all of the events in the application */ namespace events { struct CapActive : public Event { CapActive() : CapActive(0, 0, 0) {} CapActive(uint16_t _baseline, uint16_t _measurement, uint8_t _settings) : baseline(_baseline), measurement(_measurement), settings(_settings) {} uint16_t baseline; // Initial zero level uint16_t measurement; // Final voltage value uint8_t settings; // Metadata about the sample; bit 0 indicates low gain. }; struct CapOffsetCalibrationRequest : public Event {}; struct CapScan : public Event { const uint16_t *measurements; // Size is N_HV507 * 64 }; struct CapGroups : public Event { std::array<uint16_t, AppConfig::N_CAP_GROUPS> measurements; ScanGroups<AppConfig::N_PINS, AppConfig::N_CAP_GROUPS> scanGroups; }; struct ElectrodesUpdated : public Event {}; struct GpioControl : public Event { uint8_t pin; bool value; bool outputEnable; bool write; std::function<void(uint8_t pin, bool value)> callback; }; struct SetGain : public Event { SetGain() : data{0} {} uint8_t data[(AppConfig::N_PINS + 3) / 4]; uint8_t get_channel(uint8_t channel) { uint32_t offset = channel / 4; uint32_t shift = (channel % 4) * 2; return (data[offset] >> shift) & 0x3; } void set_channel(uint8_t channel, uint8_t value) { uint32_t offset = channel / 4; uint32_t shift = (channel % 4) * 2; if(offset < sizeof(data)/sizeof(data[0])) { data[offset] &= ~(0x3 << shift); data[offset] |= (value & 0x3) << shift; } } }; struct SetElectrodes : public Event { uint8_t groupID; uint8_t setting; uint8_t values[AppConfig::N_BYTES]; }; struct SetDutyCycle : public Event { bool updateA; bool updateB; uint8_t dutyCycleA; uint8_t dutyCycleB; }; struct DutyCycleUpdated : public Event { uint8_t dutyCycleA; uint8_t dutyCycleB; }; struct FeedbackCommand : public Event { float target; uint8_t mode; uint8_t measureGroupsPMask; uint8_t measureGroupsNMask; uint8_t baseline; }; struct HvRegulatorUpdate : public Event { float voltage; uint16_t vTargetOut; }; struct SetParameter : public Event { uint32_t paramIdx; ConfigOptionValue paramValue; // If set, this message is setting a param. If clear, this is requesting the current value. uint8_t writeFlag; std::function<void(const uint32_t &idx, const ConfigOptionValue &paramValue)> callback; }; struct SetPwm : public Event { uint8_t channel; uint16_t duty_cycle; }; struct TemperatureMeasurement : public Event { uint16_t measurements[AppConfig::N_TEMP_SENSOR]; }; // Partial update of the electrode calibration data // Calibrations are sent via DataBlob messages, in chunks. struct UpdateElectrodeCalibration : public Event { uint16_t offset; // Offset of first byte to update uint16_t length; // Number of bytes to copy const uint8_t *data; // Source data to copy }; } //namespace events
25.408
95
0.683879
uwmisl
dcc193ade7d89d5a84e99778ad5bfa2cd061f1d7
164,690
cpp
C++
CWE-119/source_files/CVE-2006-1739/Firefox_1.5b2_CVE_2006_1739_layout_base_nsCSSRendering.cpp
CGCL-codes/VulDeePecker
98610f3e116df97a1e819ffc81fbc7f6f138a8f2
[ "Apache-2.0" ]
185
2017-12-14T08:18:15.000Z
2022-03-30T02:58:36.000Z
CWE-119/source_files/CVE-2006-1739/Firefox_1.5b2_CVE_2006_1739_layout_base_nsCSSRendering.cpp
CGCL-codes/VulDeePecker
98610f3e116df97a1e819ffc81fbc7f6f138a8f2
[ "Apache-2.0" ]
11
2018-01-30T23:31:20.000Z
2022-01-17T05:03:56.000Z
CWE-119/source_files/CVE-2006-1739/Firefox_1.5b2_CVE_2006_1739_layout_base_nsCSSRendering.cpp
CGCL-codes/VulDeePecker
98610f3e116df97a1e819ffc81fbc7f6f138a8f2
[ "Apache-2.0" ]
87
2018-01-10T08:12:32.000Z
2022-02-19T10:29:31.000Z
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ // vim:cindent:ts=2:et:sw=2: /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is mozilla.org code. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1998 * the Initial Developer. All Rights Reserved. * * Contributor(s): * * Alternatively, the contents of this file may be used under the terms of * either of the GNU General Public License Version 2 or later (the "GPL"), * or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #include "nsStyleConsts.h" #include "nsPresContext.h" #include "nsIImage.h" #include "nsIFrame.h" #include "nsPoint.h" #include "nsRect.h" #include "nsIViewManager.h" #include "nsIPresShell.h" #include "nsFrameManager.h" #include "nsStyleContext.h" #include "nsIScrollableView.h" #include "nsLayoutAtoms.h" #include "nsIDrawingSurface.h" #include "nsTransform2D.h" #include "nsIDeviceContext.h" #include "nsIContent.h" #include "nsHTMLAtoms.h" #include "nsIDocument.h" #include "nsIScrollableFrame.h" #include "imgIRequest.h" #include "imgIContainer.h" #include "gfxIImageFrame.h" #include "nsCSSRendering.h" #include "nsCSSColorUtils.h" #include "nsITheme.h" #include "nsThemeConstants.h" #include "nsIServiceManager.h" #include "nsIDOMHTMLBodyElement.h" #include "nsIDOMHTMLDocument.h" #include "nsLayoutUtils.h" #include "nsINameSpaceManager.h" #define BORDER_FULL 0 //entire side #define BORDER_INSIDE 1 //inside half #define BORDER_OUTSIDE 2 //outside half //thickness of dashed line relative to dotted line #define DOT_LENGTH 1 //square #define DASH_LENGTH 3 //3 times longer than dot /** The following classes are used by CSSRendering for the rounded rect implementation */ #define MAXPATHSIZE 12 #define MAXPOLYPATHSIZE 1000 enum ePathTypes{ eOutside =0, eInside, eCalc, eCalcRev }; // To avoid storing this data on nsInlineFrame (bloat) and to avoid // recalculating this for each frame in a continuation (perf), hold // a cache of various coordinate information that we need in order // to paint inline backgrounds. struct InlineBackgroundData { InlineBackgroundData() : mFrame(nsnull) { } ~InlineBackgroundData() { } void Reset() { mBoundingBox.SetRect(0,0,0,0); mContinuationPoint = mUnbrokenWidth = 0; mFrame = nsnull; } nsRect GetContinuousRect(nsIFrame* aFrame) { SetFrame(aFrame); // Assume background-origin: border and return a rect with offsets // relative to (0,0). If we have a different background-origin, // then our rect should be deflated appropriately by our caller. return nsRect(-mContinuationPoint, 0, mUnbrokenWidth, mFrame->GetSize().height); } nsRect GetBoundingRect(nsIFrame* aFrame) { SetFrame(aFrame); // Move the offsets relative to (0,0) which puts the bounding box into // our coordinate system rather than our parent's. We do this by // moving it the back distance from us to the bounding box. // This also assumes background-origin: border, so our caller will // need to deflate us if needed. nsRect boundingBox(mBoundingBox); nsPoint point = mFrame->GetPosition(); boundingBox.MoveBy(-point.x, -point.y); return boundingBox; } protected: nsIFrame* mFrame; nscoord mContinuationPoint; nscoord mUnbrokenWidth; nsRect mBoundingBox; void SetFrame(nsIFrame* aFrame) { NS_PRECONDITION(aFrame, "Need a frame"); nsIFrame *prevInFlow = aFrame->GetPrevInFlow(); if (!prevInFlow || mFrame != prevInFlow) { // Ok, we've got the wrong frame. We have to start from scratch. Reset(); Init(aFrame); return; } // Get our last frame's size and add its width to our continuation // point before we cache the new frame. mContinuationPoint += mFrame->GetSize().width; mFrame = aFrame; } void Init(nsIFrame* aFrame) { // Start with the previous flow frame as our continuation point // is the total of the widths of the previous frames. nsIFrame* inlineFrame = aFrame->GetPrevInFlow(); while (inlineFrame) { nsRect rect = inlineFrame->GetRect(); mContinuationPoint += rect.width; mUnbrokenWidth += rect.width; mBoundingBox.UnionRect(mBoundingBox, rect); inlineFrame = inlineFrame->GetPrevInFlow(); } // Next add this frame and subsequent frames to the bounding box and // unbroken width. inlineFrame = aFrame; while (inlineFrame) { nsRect rect = inlineFrame->GetRect(); mUnbrokenWidth += rect.width; mBoundingBox.UnionRect(mBoundingBox, rect); inlineFrame = inlineFrame->GetNextInFlow(); } mFrame = aFrame; } }; static InlineBackgroundData gInlineBGData; static void GetPath(nsFloatPoint aPoints[],nsPoint aPolyPath[],PRInt32 *aCurIndex,ePathTypes aPathType,PRInt32 &aC1Index,float aFrac=0); // FillRect or InvertRect depending on the renderingaInvert parameter static void FillOrInvertRect(nsIRenderingContext& aRC,nscoord aX, nscoord aY, nscoord aWidth, nscoord aHeight, PRBool aInvert); static void FillOrInvertRect(nsIRenderingContext& aRC,const nsRect& aRect, PRBool aInvert); // Draw a line, skipping that portion which crosses aGap. aGap defines a rectangle gap // This services fieldset legends and only works for coords defining horizontal lines. void nsCSSRendering::DrawLine (nsIRenderingContext& aContext, nscoord aX1, nscoord aY1, nscoord aX2, nscoord aY2, nsRect* aGap) { if (nsnull == aGap) { aContext.DrawLine(aX1, aY1, aX2, aY2); } else { nscoord x1 = (aX1 < aX2) ? aX1 : aX2; nscoord x2 = (aX1 < aX2) ? aX2 : aX1; nsPoint gapUpperRight(aGap->x + aGap->width, aGap->y); nsPoint gapLowerRight(aGap->x + aGap->width, aGap->y + aGap->height); if ((aGap->y <= aY1) && (gapLowerRight.y >= aY2)) { if ((aGap->x > x1) && (aGap->x < x2)) { aContext.DrawLine(x1, aY1, aGap->x, aY1); } if ((gapLowerRight.x > x1) && (gapLowerRight.x < x2)) { aContext.DrawLine(gapUpperRight.x, aY2, x2, aY2); } } else { aContext.DrawLine(aX1, aY1, aX2, aY2); } } } // Fill a polygon, skipping that portion which crosses aGap. aGap defines a rectangle gap // This services fieldset legends and only works for points defining a horizontal rectangle void nsCSSRendering::FillPolygon (nsIRenderingContext& aContext, const nsPoint aPoints[], PRInt32 aNumPoints, nsRect* aGap) { #ifdef DEBUG nsPenMode penMode; if (NS_SUCCEEDED(aContext.GetPenMode(penMode)) && penMode == nsPenMode_kInvert) { NS_WARNING( "Invert mode ignored in FillPolygon" ); } #endif if (nsnull == aGap) { aContext.FillPolygon(aPoints, aNumPoints); } else if (4 == aNumPoints) { nsPoint gapUpperRight(aGap->x + aGap->width, aGap->y); nsPoint gapLowerRight(aGap->x + aGap->width, aGap->y + aGap->height); // sort the 4 points by x nsPoint points[4]; for (PRInt32 pX = 0; pX < 4; pX++) { points[pX] = aPoints[pX]; } for (PRInt32 i = 0; i < 3; i++) { for (PRInt32 j = i+1; j < 4; j++) { if (points[j].x < points[i].x) { nsPoint swap = points[i]; points[i] = points[j]; points[j] = swap; } } } nsPoint upperLeft = (points[0].y <= points[1].y) ? points[0] : points[1]; nsPoint lowerLeft = (points[0].y <= points[1].y) ? points[1] : points[0]; nsPoint upperRight = (points[2].y <= points[3].y) ? points[2] : points[3]; nsPoint lowerRight = (points[2].y <= points[3].y) ? points[3] : points[2]; if ((aGap->y <= upperLeft.y) && (gapLowerRight.y >= lowerRight.y)) { if ((aGap->x > upperLeft.x) && (aGap->x < upperRight.x)) { nsPoint leftRect[4]; leftRect[0] = upperLeft; leftRect[1] = nsPoint(aGap->x, upperLeft.y); leftRect[2] = nsPoint(aGap->x, lowerLeft.y); leftRect[3] = lowerLeft; aContext.FillPolygon(leftRect, 4); } if ((gapUpperRight.x > upperLeft.x) && (gapUpperRight.x < upperRight.x)) { nsPoint rightRect[4]; rightRect[0] = nsPoint(gapUpperRight.x, upperRight.y); rightRect[1] = upperRight; rightRect[2] = lowerRight; rightRect[3] = nsPoint(gapLowerRight.x, lowerRight.y); aContext.FillPolygon(rightRect, 4); } } else { aContext.FillPolygon(aPoints, aNumPoints); } } } /** * Make a bevel color */ nscolor nsCSSRendering::MakeBevelColor(PRIntn whichSide, PRUint8 style, nscolor aBackgroundColor, nscolor aBorderColor, PRBool aSpecialCase) { nscolor colors[2]; nscolor theColor; // Given a background color and a border color // calculate the color used for the shading if(aSpecialCase) NS_GetSpecial3DColors(colors, aBackgroundColor, aBorderColor); else NS_Get3DColors(colors, aBackgroundColor); if ((style == NS_STYLE_BORDER_STYLE_BG_OUTSET) || (style == NS_STYLE_BORDER_STYLE_OUTSET) || (style == NS_STYLE_BORDER_STYLE_RIDGE)) { // Flip colors for these three border styles switch (whichSide) { case NS_SIDE_BOTTOM: whichSide = NS_SIDE_TOP; break; case NS_SIDE_RIGHT: whichSide = NS_SIDE_LEFT; break; case NS_SIDE_TOP: whichSide = NS_SIDE_BOTTOM; break; case NS_SIDE_LEFT: whichSide = NS_SIDE_RIGHT; break; } } switch (whichSide) { case NS_SIDE_BOTTOM: theColor = colors[1]; break; case NS_SIDE_RIGHT: theColor = colors[1]; break; case NS_SIDE_TOP: theColor = colors[0]; break; case NS_SIDE_LEFT: default: theColor = colors[0]; break; } return theColor; } // Maximum poly points in any of the polygons we generate below #define MAX_POLY_POINTS 4 // a nifty helper function to create a polygon representing a // particular side of a border. This helps localize code for figuring // mitered edges. It is mainly used by the solid, inset, and outset // styles. // // If the side can be represented as a line segment (because the thickness // is one pixel), then a line with two endpoints is returned PRIntn nsCSSRendering::MakeSide(nsPoint aPoints[], nsIRenderingContext& aContext, PRIntn whichSide, const nsRect& outside, const nsRect& inside, PRIntn aSkipSides, PRIntn borderPart, float borderFrac, nscoord twipsPerPixel) { float borderRest = 1.0f - borderFrac; PRIntn np = 0; nscoord thickness, outsideEdge, insideEdge, outsideTL, insideTL, outsideBR, insideBR; // Initialize the following six nscoord's: // outsideEdge, insideEdge, outsideTL, insideTL, outsideBR, insideBR // so that outsideEdge is the x or y of the outside edge, etc., and // outsideTR is the y or x at the top or right end, etc., e.g.: // // outsideEdge --- ---------------------------------------- // \ / // \ / // \ / // insideEdge ------- ---------------------------------- // | | | | // outsideTL insideTL insideBR outsideBR // // if we don't want the bevel, we'll get rid of it later by setting // outsideXX to insideXX switch (whichSide) { case NS_SIDE_TOP: // the TL points are the left end; the BR points are the right end outsideEdge = outside.y; insideEdge = inside.y; outsideTL = outside.x; insideTL = inside.x; insideBR = inside.XMost(); outsideBR = outside.XMost(); break; case NS_SIDE_BOTTOM: // the TL points are the left end; the BR points are the right end outsideEdge = outside.YMost(); insideEdge = inside.YMost(); outsideTL = outside.x; insideTL = inside.x; insideBR = inside.XMost(); outsideBR = outside.XMost(); break; case NS_SIDE_LEFT: // the TL points are the top end; the BR points are the bottom end outsideEdge = outside.x; insideEdge = inside.x; outsideTL = outside.y; insideTL = inside.y; insideBR = inside.YMost(); outsideBR = outside.YMost(); break; default: NS_ASSERTION(whichSide == NS_SIDE_RIGHT, "whichSide is not a valid side"); // the TL points are the top end; the BR points are the bottom end outsideEdge = outside.XMost(); insideEdge = inside.XMost(); outsideTL = outside.y; insideTL = inside.y; insideBR = inside.YMost(); outsideBR = outside.YMost(); break; } // Don't draw the bevels if an adjacent side is skipped if ( (whichSide == NS_SIDE_TOP) || (whichSide == NS_SIDE_BOTTOM) ) { // a top or bottom side if ((1<<NS_SIDE_LEFT) & aSkipSides) { insideTL = outsideTL; } if ((1<<NS_SIDE_RIGHT) & aSkipSides) { insideBR = outsideBR; } } else { // a right or left side if ((1<<NS_SIDE_TOP) & aSkipSides) { insideTL = outsideTL; } if ((1<<NS_SIDE_BOTTOM) & aSkipSides) { insideBR = outsideBR; } } // move things around when only drawing part of the border if (borderPart == BORDER_INSIDE) { outsideEdge = nscoord(outsideEdge * borderFrac + insideEdge * borderRest); outsideTL = nscoord(outsideTL * borderFrac + insideTL * borderRest); outsideBR = nscoord(outsideBR * borderFrac + insideBR * borderRest); } else if (borderPart == BORDER_OUTSIDE ) { insideEdge = nscoord(insideEdge * borderFrac + outsideEdge * borderRest); insideTL = nscoord(insideTL * borderFrac + outsideTL * borderRest); insideBR = nscoord(insideBR * borderFrac + outsideBR * borderRest); } // Base our thickness check on the segment being less than a pixel and 1/2 twipsPerPixel += twipsPerPixel >> 2; // find the thickness of the piece being drawn if ((whichSide == NS_SIDE_TOP) || (whichSide == NS_SIDE_LEFT)) { thickness = insideEdge - outsideEdge; } else { thickness = outsideEdge - insideEdge; } // if returning a line, do it along inside edge for bottom or right borders // so that it's in the same place as it would be with polygons (why?) // XXX The previous version of the code shortened the right border too. if ( !((thickness >= twipsPerPixel) || (borderPart != BORDER_FULL)) && ((whichSide == NS_SIDE_BOTTOM) || (whichSide == NS_SIDE_RIGHT))) { outsideEdge = insideEdge; } // return the appropriate line or trapezoid if ((whichSide == NS_SIDE_TOP) || (whichSide == NS_SIDE_BOTTOM)) { // top and bottom borders aPoints[np++].MoveTo(outsideTL,outsideEdge); aPoints[np++].MoveTo(outsideBR,outsideEdge); // XXX Making this condition only (thickness >= twipsPerPixel) will // improve double borders and some cases of groove/ridge, // but will cause problems with table borders. See last and third // from last tests in test4.htm // Doing it this way emulates the old behavior. It might be worth // fixing. if ((thickness >= twipsPerPixel) || (borderPart != BORDER_FULL) ) { aPoints[np++].MoveTo(insideBR,insideEdge); aPoints[np++].MoveTo(insideTL,insideEdge); } } else { // right and left borders // XXX Ditto above if ((thickness >= twipsPerPixel) || (borderPart != BORDER_FULL) ) { aPoints[np++].MoveTo(insideEdge,insideBR); aPoints[np++].MoveTo(insideEdge,insideTL); } aPoints[np++].MoveTo(outsideEdge,outsideTL); aPoints[np++].MoveTo(outsideEdge,outsideBR); } return np; } void nsCSSRendering::DrawSide(nsIRenderingContext& aContext, PRIntn whichSide, const PRUint8 borderStyle, const nscolor borderColor, const nscolor aBackgroundColor, const nsRect& borderOutside, const nsRect& borderInside, PRIntn aSkipSides, nscoord twipsPerPixel, nsRect* aGap) { nsPoint theSide[MAX_POLY_POINTS]; nscolor theColor = borderColor; PRUint8 theStyle = borderStyle; PRInt32 np; switch (theStyle) { case NS_STYLE_BORDER_STYLE_NONE: case NS_STYLE_BORDER_STYLE_HIDDEN: return; case NS_STYLE_BORDER_STYLE_DOTTED: //handled a special case elsewhere case NS_STYLE_BORDER_STYLE_DASHED: //handled a special case elsewhere break; // That was easy... case NS_STYLE_BORDER_STYLE_GROOVE: case NS_STYLE_BORDER_STYLE_RIDGE: np = MakeSide (theSide, aContext, whichSide, borderOutside, borderInside, aSkipSides, BORDER_INSIDE, 0.5f, twipsPerPixel); aContext.SetColor ( MakeBevelColor (whichSide, ((theStyle == NS_STYLE_BORDER_STYLE_RIDGE) ? NS_STYLE_BORDER_STYLE_GROOVE : NS_STYLE_BORDER_STYLE_RIDGE), aBackgroundColor, theColor, PR_TRUE)); if (2 == np) { //aContext.DrawLine (theSide[0].x, theSide[0].y, theSide[1].x, theSide[1].y); DrawLine (aContext, theSide[0].x, theSide[0].y, theSide[1].x, theSide[1].y, aGap); } else { //aContext.FillPolygon (theSide, np); FillPolygon (aContext, theSide, np, aGap); } np = MakeSide (theSide, aContext, whichSide, borderOutside, borderInside,aSkipSides, BORDER_OUTSIDE, 0.5f, twipsPerPixel); aContext.SetColor ( MakeBevelColor (whichSide, theStyle, aBackgroundColor, theColor, PR_TRUE)); if (2 == np) { //aContext.DrawLine (theSide[0].x, theSide[0].y, theSide[1].x, theSide[1].y); DrawLine (aContext, theSide[0].x, theSide[0].y, theSide[1].x, theSide[1].y, aGap); } else { //aContext.FillPolygon (theSide, np); FillPolygon (aContext, theSide, np, aGap); } break; case NS_STYLE_BORDER_STYLE_AUTO: case NS_STYLE_BORDER_STYLE_SOLID: np = MakeSide (theSide, aContext, whichSide, borderOutside, borderInside,aSkipSides, BORDER_FULL, 1.0f, twipsPerPixel); aContext.SetColor (borderColor); if (2 == np) { //aContext.DrawLine (theSide[0].x, theSide[0].y, theSide[1].x, theSide[1].y); DrawLine (aContext, theSide[0].x, theSide[0].y, theSide[1].x, theSide[1].y, aGap); } else { //aContext.FillPolygon (theSide, np); FillPolygon (aContext, theSide, np, aGap); } break; case NS_STYLE_BORDER_STYLE_BG_SOLID: np = MakeSide (theSide, aContext, whichSide, borderOutside, borderInside, aSkipSides, BORDER_FULL, 1.0f, twipsPerPixel); nscolor colors[2]; NS_Get3DColors(colors, aBackgroundColor); aContext.SetColor (colors[0]); if (2 == np) { DrawLine (aContext, theSide[0].x, theSide[0].y, theSide[1].x, theSide[1].y, aGap); } else { FillPolygon (aContext, theSide, np, aGap); } break; case NS_STYLE_BORDER_STYLE_DOUBLE: np = MakeSide (theSide, aContext, whichSide, borderOutside, borderInside,aSkipSides, BORDER_INSIDE, 0.333333f, twipsPerPixel); aContext.SetColor (borderColor); if (2 == np) { //aContext.DrawLine (theSide[0].x, theSide[0].y, theSide[1].x, theSide[1].y); DrawLine (aContext, theSide[0].x, theSide[0].y, theSide[1].x, theSide[1].y, aGap); } else { //aContext.FillPolygon (theSide, np); FillPolygon (aContext, theSide, np, aGap); } np = MakeSide (theSide, aContext, whichSide, borderOutside, borderInside,aSkipSides, BORDER_OUTSIDE, 0.333333f, twipsPerPixel); if (2 == np) { //aContext.DrawLine (theSide[0].x, theSide[0].y, theSide[1].x, theSide[1].y); DrawLine (aContext, theSide[0].x, theSide[0].y, theSide[1].x, theSide[1].y, aGap); } else { //aContext.FillPolygon (theSide, np); FillPolygon (aContext, theSide, np, aGap); } break; case NS_STYLE_BORDER_STYLE_BG_OUTSET: case NS_STYLE_BORDER_STYLE_BG_INSET: np = MakeSide (theSide, aContext, whichSide, borderOutside, borderInside,aSkipSides, BORDER_FULL, 1.0f, twipsPerPixel); aContext.SetColor ( MakeBevelColor (whichSide, theStyle, aBackgroundColor, theColor, PR_FALSE)); if (2 == np) { //aContext.DrawLine (theSide[0].x, theSide[0].y, theSide[1].x, theSide[1].y); DrawLine (aContext, theSide[0].x, theSide[0].y, theSide[1].x, theSide[1].y, aGap); } else { //aContext.FillPolygon (theSide, np); FillPolygon (aContext, theSide, np, aGap); } break; case NS_STYLE_BORDER_STYLE_OUTSET: case NS_STYLE_BORDER_STYLE_INSET: np = MakeSide (theSide, aContext, whichSide, borderOutside, borderInside,aSkipSides, BORDER_FULL, 1.0f, twipsPerPixel); aContext.SetColor ( MakeBevelColor (whichSide, theStyle, aBackgroundColor, theColor, PR_TRUE)); if (2 == np) { //aContext.DrawLine (theSide[0].x, theSide[0].y, theSide[1].x, theSide[1].y); DrawLine (aContext, theSide[0].x, theSide[0].y, theSide[1].x, theSide[1].y, aGap); } else { //aContext.FillPolygon (theSide, np); FillPolygon (aContext, theSide, np, aGap); } break; } } /** * Draw a dotted/dashed sides of a box */ //XXX dashes which span more than two edges are not handled properly MMP void nsCSSRendering::DrawDashedSides(PRIntn startSide, nsIRenderingContext& aContext, /* XXX unused */ const nsRect& aDirtyRect, const PRUint8 borderStyles[], const nscolor borderColors[], const nsRect& borderOutside, const nsRect& borderInside, PRIntn aSkipSides, /* XXX unused */ nsRect* aGap) { PRIntn dashLength; nsRect dashRect, firstRect, currRect; PRBool bSolid = PR_TRUE; float over = 0.0f; PRUint8 style = borderStyles[startSide]; PRBool skippedSide = PR_FALSE; for (PRIntn whichSide = startSide; whichSide < 4; whichSide++) { PRUint8 prevStyle = style; style = borderStyles[whichSide]; if ((1<<whichSide) & aSkipSides) { // Skipped side skippedSide = PR_TRUE; continue; } if ((style == NS_STYLE_BORDER_STYLE_DASHED) || (style == NS_STYLE_BORDER_STYLE_DOTTED)) { if ((style != prevStyle) || skippedSide) { //style discontinuity over = 0.0f; bSolid = PR_TRUE; } // XXX units for dash & dot? if (style == NS_STYLE_BORDER_STYLE_DASHED) { dashLength = DASH_LENGTH; } else { dashLength = DOT_LENGTH; } aContext.SetColor(borderColors[whichSide]); switch (whichSide) { case NS_SIDE_LEFT: //XXX need to properly handle wrap around from last edge to first edge //(this is the first edge) MMP dashRect.width = borderInside.x - borderOutside.x; dashRect.height = nscoord(dashRect.width * dashLength); dashRect.x = borderOutside.x; dashRect.y = borderInside.YMost() - dashRect.height; if (over > 0.0f) { firstRect.x = dashRect.x; firstRect.width = dashRect.width; firstRect.height = nscoord(dashRect.height * over); firstRect.y = dashRect.y + (dashRect.height - firstRect.height); over = 0.0f; currRect = firstRect; } else { currRect = dashRect; } while (currRect.YMost() > borderInside.y) { //clip if necessary if (currRect.y < borderInside.y) { over = float(borderInside.y - dashRect.y) / float(dashRect.height); currRect.height = currRect.height - (borderInside.y - currRect.y); currRect.y = borderInside.y; } //draw if necessary if (bSolid) { aContext.FillRect(currRect); } //setup for next iteration if (over == 0.0f) { bSolid = PRBool(!bSolid); } dashRect.y = dashRect.y - currRect.height; currRect = dashRect; } break; case NS_SIDE_TOP: //if we are continuing a solid rect, fill in the corner first if (bSolid) { aContext.FillRect(borderOutside.x, borderOutside.y, borderInside.x - borderOutside.x, borderInside.y - borderOutside.y); } dashRect.height = borderInside.y - borderOutside.y; dashRect.width = dashRect.height * dashLength; dashRect.x = borderInside.x; dashRect.y = borderOutside.y; if (over > 0.0f) { firstRect.x = dashRect.x; firstRect.y = dashRect.y; firstRect.width = nscoord(dashRect.width * over); firstRect.height = dashRect.height; over = 0.0f; currRect = firstRect; } else { currRect = dashRect; } while (currRect.x < borderInside.XMost()) { //clip if necessary if (currRect.XMost() > borderInside.XMost()) { over = float(dashRect.XMost() - borderInside.XMost()) / float(dashRect.width); currRect.width = currRect.width - (currRect.XMost() - borderInside.XMost()); } //draw if necessary if (bSolid) { aContext.FillRect(currRect); } //setup for next iteration if (over == 0.0f) { bSolid = PRBool(!bSolid); } dashRect.x = dashRect.x + currRect.width; currRect = dashRect; } break; case NS_SIDE_RIGHT: //if we are continuing a solid rect, fill in the corner first if (bSolid) { aContext.FillRect(borderInside.XMost(), borderOutside.y, borderOutside.XMost() - borderInside.XMost(), borderInside.y - borderOutside.y); } dashRect.width = borderOutside.XMost() - borderInside.XMost(); dashRect.height = nscoord(dashRect.width * dashLength); dashRect.x = borderInside.XMost(); dashRect.y = borderInside.y; if (over > 0.0f) { firstRect.x = dashRect.x; firstRect.y = dashRect.y; firstRect.width = dashRect.width; firstRect.height = nscoord(dashRect.height * over); over = 0.0f; currRect = firstRect; } else { currRect = dashRect; } while (currRect.y < borderInside.YMost()) { //clip if necessary if (currRect.YMost() > borderInside.YMost()) { over = float(dashRect.YMost() - borderInside.YMost()) / float(dashRect.height); currRect.height = currRect.height - (currRect.YMost() - borderInside.YMost()); } //draw if necessary if (bSolid) { aContext.FillRect(currRect); } //setup for next iteration if (over == 0.0f) { bSolid = PRBool(!bSolid); } dashRect.y = dashRect.y + currRect.height; currRect = dashRect; } break; case NS_SIDE_BOTTOM: //if we are continuing a solid rect, fill in the corner first if (bSolid) { aContext.FillRect(borderInside.XMost(), borderInside.YMost(), borderOutside.XMost() - borderInside.XMost(), borderOutside.YMost() - borderInside.YMost()); } dashRect.height = borderOutside.YMost() - borderInside.YMost(); dashRect.width = nscoord(dashRect.height * dashLength); dashRect.x = borderInside.XMost() - dashRect.width; dashRect.y = borderInside.YMost(); if (over > 0.0f) { firstRect.y = dashRect.y; firstRect.width = nscoord(dashRect.width * over); firstRect.height = dashRect.height; firstRect.x = dashRect.x + (dashRect.width - firstRect.width); over = 0.0f; currRect = firstRect; } else { currRect = dashRect; } while (currRect.XMost() > borderInside.x) { //clip if necessary if (currRect.x < borderInside.x) { over = float(borderInside.x - dashRect.x) / float(dashRect.width); currRect.width = currRect.width - (borderInside.x - currRect.x); currRect.x = borderInside.x; } //draw if necessary if (bSolid) { aContext.FillRect(currRect); } //setup for next iteration if (over == 0.0f) { bSolid = PRBool(!bSolid); } dashRect.x = dashRect.x - currRect.width; currRect = dashRect; } break; } } skippedSide = PR_FALSE; } } /** --------------------------------------------------- * See documentation in nsCSSRendering.h * @update 10/22/99 dwc */ void nsCSSRendering::DrawDashedSides(PRIntn startSide, nsIRenderingContext& aContext, const nsRect& aDirtyRect, const nsStyleColor* aColorStyle, const nsStyleBorder* aBorderStyle, const nsStyleOutline* aOutlineStyle, PRBool aDoOutline, const nsRect& borderOutside, const nsRect& borderInside, PRIntn aSkipSides, /* XXX unused */ nsRect* aGap) { PRIntn dashLength; nsRect dashRect, currRect; nscoord temp, temp1, adjust; PRBool bSolid = PR_TRUE; float over = 0.0f; PRBool skippedSide = PR_FALSE; const nscolor kBlackColor = NS_RGB(0,0,0); NS_ASSERTION((aDoOutline && aOutlineStyle) || (!aDoOutline && aBorderStyle), "null params not allowed"); PRUint8 style = aDoOutline ? aOutlineStyle->GetOutlineStyle() : aBorderStyle->GetBorderStyle(startSide); // find the x and y width nscoord xwidth = aDirtyRect.XMost(); nscoord ywidth = aDirtyRect.YMost(); for (PRIntn whichSide = startSide; whichSide < 4; whichSide++) { PRUint8 prevStyle = style; style = aDoOutline ? aOutlineStyle->GetOutlineStyle() : aBorderStyle->GetBorderStyle(whichSide); if ((1<<whichSide) & aSkipSides) { // Skipped side skippedSide = PR_TRUE; continue; } if ((style == NS_STYLE_BORDER_STYLE_DASHED) || (style == NS_STYLE_BORDER_STYLE_DOTTED)) { if ((style != prevStyle) || skippedSide) { //style discontinuity over = 0.0f; bSolid = PR_TRUE; } if (style == NS_STYLE_BORDER_STYLE_DASHED) { dashLength = DASH_LENGTH; } else { dashLength = DOT_LENGTH; } nscolor sideColor(kBlackColor); // default to black in case color cannot be resolved // (because invert is not supported on cur platform) PRBool isInvert=PR_FALSE; if (aDoOutline) { // see if the outline color is 'invert' if (aOutlineStyle->GetOutlineInvert()) { isInvert = PR_TRUE; } else { aOutlineStyle->GetOutlineColor(sideColor); } } else { PRBool transparent; PRBool foreground; aBorderStyle->GetBorderColor(whichSide, sideColor, transparent, foreground); if (foreground) sideColor = aColorStyle->mColor; if (transparent) continue; // side is transparent } aContext.SetColor(sideColor); switch (whichSide) { case NS_SIDE_RIGHT: case NS_SIDE_LEFT: bSolid = PR_FALSE; // This is our dot or dash.. if(whichSide==NS_SIDE_LEFT){ dashRect.width = borderInside.x - borderOutside.x; } else { dashRect.width = borderOutside.XMost() - borderInside.XMost(); } if( dashRect.width >0 ) { dashRect.height = dashRect.width * dashLength; dashRect.y = borderOutside.y; if(whichSide == NS_SIDE_RIGHT){ dashRect.x = borderInside.XMost(); } else { dashRect.x = borderOutside.x; } temp = borderOutside.YMost(); temp1 = temp/dashRect.height; currRect = dashRect; if((temp1%2)==0){ adjust = (dashRect.height-(temp%dashRect.height))/2; // adjust back // draw in the left and right FillOrInvertRect(aContext, dashRect.x, borderOutside.y,dashRect.width, dashRect.height-adjust,isInvert); FillOrInvertRect(aContext,dashRect.x,(borderOutside.YMost()-(dashRect.height-adjust)),dashRect.width, dashRect.height-adjust,isInvert); currRect.y += (dashRect.height-adjust); temp = temp-= (dashRect.height-adjust); } else { adjust = (temp%dashRect.width)/2; // adjust a tad longer // draw in the left and right FillOrInvertRect(aContext, dashRect.x, borderOutside.y,dashRect.width, dashRect.height+adjust,isInvert); FillOrInvertRect(aContext, dashRect.x,(borderOutside.YMost()-(dashRect.height+adjust)),dashRect.width, dashRect.height+adjust,isInvert); currRect.y += (dashRect.height+adjust); temp = temp-= (dashRect.height+adjust); } if( temp > ywidth) temp = ywidth; // get the currRect's x into the view before we start if( currRect.y < aDirtyRect.y){ temp1 = NSToCoordFloor((float)((aDirtyRect.y-currRect.y)/dashRect.height)); currRect.y += temp1*dashRect.height; if((temp1%2)==1){ bSolid = PR_TRUE; } } while(currRect.y<temp) { //draw if necessary if (bSolid) { FillOrInvertRect(aContext, currRect,isInvert); } bSolid = PRBool(!bSolid); currRect.y += dashRect.height; } } break; case NS_SIDE_BOTTOM: case NS_SIDE_TOP: bSolid = PR_FALSE; // This is our dot or dash.. if(whichSide==NS_SIDE_TOP){ dashRect.height = borderInside.y - borderOutside.y; } else { dashRect.height = borderOutside.YMost() - borderInside.YMost(); } if( dashRect.height >0 ) { dashRect.width = dashRect.height * dashLength; dashRect.x = borderOutside.x; if(whichSide == NS_SIDE_BOTTOM){ dashRect.y = borderInside.YMost(); } else { dashRect.y = borderOutside.y; } temp = borderOutside.XMost(); temp1 = temp/dashRect.width; currRect = dashRect; if((temp1%2)==0){ adjust = (dashRect.width-(temp%dashRect.width))/2; // even, adjust back // draw in the left and right FillOrInvertRect(aContext, borderOutside.x,dashRect.y,dashRect.width-adjust,dashRect.height,isInvert); FillOrInvertRect(aContext, (borderOutside.XMost()-(dashRect.width-adjust)),dashRect.y,dashRect.width-adjust,dashRect.height,isInvert); currRect.x += (dashRect.width-adjust); temp = temp-= (dashRect.width-adjust); } else { adjust = (temp%dashRect.width)/2; // draw in the left and right FillOrInvertRect(aContext, borderOutside.x,dashRect.y,dashRect.width+adjust,dashRect.height,isInvert); FillOrInvertRect(aContext, (borderOutside.XMost()-(dashRect.width+adjust)),dashRect.y,dashRect.width+adjust,dashRect.height,isInvert); currRect.x += (dashRect.width+adjust); temp = temp-= (dashRect.width+adjust); } if( temp > xwidth) temp = xwidth; // get the currRect's x into the view before we start if( currRect.x < aDirtyRect.x){ temp1 = NSToCoordFloor((float)((aDirtyRect.x-currRect.x)/dashRect.width)); currRect.x += temp1*dashRect.width; if((temp1%2)==1){ bSolid = PR_TRUE; } } while(currRect.x<temp) { //draw if necessary if (bSolid) { FillOrInvertRect(aContext, currRect,isInvert); } bSolid = PRBool(!bSolid); currRect.x += dashRect.width; } } break; } } skippedSide = PR_FALSE; } } /* draw the portions of the border described in aBorderEdges that are dashed. * a border has 4 edges. Each edge has 1 or more segments. * "inside edges" are drawn differently than "outside edges" so the shared edges will match up. * in the case of table collapsing borders, the table edge is the "outside" edge and * cell edges are always "inside" edges (so adjacent cells have 2 shared "inside" edges.) * There is a case for each of the four sides. Only the left side is well documented. The others * are very similar. */ // XXX: doesn't do corners or junctions well at all. Just uses logic stolen // from DrawDashedSides which is insufficient void nsCSSRendering::DrawDashedSegments(nsIRenderingContext& aContext, const nsRect& aBounds, nsBorderEdges * aBorderEdges, PRIntn aSkipSides, /* XXX unused */ nsRect* aGap) { PRIntn dashLength; nsRect dashRect, currRect; PRBool bSolid = PR_TRUE; float over = 0.0f; PRBool skippedSide = PR_FALSE; PRIntn whichSide=0; // do this just to set up initial condition for loop // "segment" is the current portion of the edge we are computing nsBorderEdge * segment = (nsBorderEdge *)(aBorderEdges->mEdges[whichSide].ElementAt(0)); PRUint8 style = segment->mStyle; for ( ; whichSide < 4; whichSide++) { if ((1<<whichSide) & aSkipSides) { // Skipped side skippedSide = PR_TRUE; continue; } nscoord x=0; nscoord y=0; PRInt32 i; PRInt32 segmentCount = aBorderEdges->mEdges[whichSide].Count(); nsBorderEdges * neighborBorderEdges=nsnull; PRIntn neighborEdgeCount=0; // keeps track of which inside neighbor is shared with an outside segment for (i=0; i<segmentCount; i++) { bSolid=PR_TRUE; over = 0.0f; segment = (nsBorderEdge *)(aBorderEdges->mEdges[whichSide].ElementAt(i)); style = segment->mStyle; // XXX units for dash & dot? if (style == NS_STYLE_BORDER_STYLE_DASHED) { dashLength = DASH_LENGTH; } else { dashLength = DOT_LENGTH; } aContext.SetColor(segment->mColor); switch (whichSide) { case NS_SIDE_LEFT: { // draw left segment i nsBorderEdge * topEdge = (nsBorderEdge *)(aBorderEdges->mEdges[NS_SIDE_TOP].ElementAt(0)); if (0==y) { // y is the offset to the top of this segment. 0 means its the topmost left segment y = aBorderEdges->mMaxBorderWidth.top - topEdge->mWidth; if (PR_TRUE==aBorderEdges->mOutsideEdge) y += topEdge->mWidth; } // the x offset is the x position offset by the max width of the left edge minus this segment's width x = aBounds.x + (aBorderEdges->mMaxBorderWidth.left - segment->mWidth); nscoord height = segment->mLength; // the space between borderOutside and borderInside inclusive is the segment. nsRect borderOutside(x, y, aBounds.width, height); y += segment->mLength; // keep track of the y offset for the next segment if ((style == NS_STYLE_BORDER_STYLE_DASHED) || (style == NS_STYLE_BORDER_STYLE_DOTTED)) { nsRect borderInside(borderOutside); nsMargin outsideMargin(segment->mWidth, 0, 0, 0); borderInside.Deflate(outsideMargin); nscoord totalLength = segment->mLength; // the computed length of this segment // outside edges need info from their inside neighbor. The following code keeps track // of which segment of the inside neighbor's shared edge we should use for this outside segment if (PR_TRUE==aBorderEdges->mOutsideEdge) { if (segment->mInsideNeighbor == neighborBorderEdges) { neighborEdgeCount++; } else { neighborBorderEdges = segment->mInsideNeighbor; neighborEdgeCount=0; } nsBorderEdge * neighborLeft = (nsBorderEdge *)(segment->mInsideNeighbor->mEdges[NS_SIDE_LEFT].ElementAt(neighborEdgeCount)); totalLength = neighborLeft->mLength; } dashRect.width = borderInside.x - borderOutside.x; dashRect.height = nscoord(dashRect.width * dashLength); dashRect.x = borderOutside.x; dashRect.y = borderOutside.y + (totalLength/2) - dashRect.height; if ((PR_TRUE==aBorderEdges->mOutsideEdge) && (0!=i)) dashRect.y -= topEdge->mWidth; // account for the topmost left edge corner with the leftmost top edge if (0) { printf(" L: totalLength = %d, borderOutside.y = %d, midpoint %d, dashRect.y = %d\n", totalLength, borderOutside.y, borderOutside.y +(totalLength/2), dashRect.y); } currRect = dashRect; // we draw the segment in 2 halves to get the inside and outside edges to line up on the // centerline of the shared edge. // draw the top half while (currRect.YMost() > borderInside.y) { //clip if necessary if (currRect.y < borderInside.y) { over = float(borderInside.y - dashRect.y) / float(dashRect.height); currRect.height = currRect.height - (borderInside.y - currRect.y); currRect.y = borderInside.y; } //draw if necessary if (0) { printf("DASHED LEFT: xywh in loop currRect = %d %d %d %d %s\n", currRect.x, currRect.y, currRect.width, currRect.height, bSolid?"TRUE":"FALSE"); } if (bSolid) { aContext.FillRect(currRect); } //setup for next iteration if (over == 0.0f) { bSolid = PRBool(!bSolid); } dashRect.y = dashRect.y - currRect.height; currRect = dashRect; } // draw the bottom half dashRect.y = borderOutside.y + (totalLength/2) + dashRect.height; if ((PR_TRUE==aBorderEdges->mOutsideEdge) && (0!=i)) dashRect.y -= topEdge->mWidth; currRect = dashRect; bSolid=PR_TRUE; over = 0.0f; while (currRect.YMost() < borderInside.YMost()) { //clip if necessary if (currRect.y < borderInside.y) { over = float(borderInside.y - dashRect.y) / float(dashRect.height); currRect.height = currRect.height - (borderInside.y - currRect.y); currRect.y = borderInside.y; } //draw if necessary if (0) { printf("DASHED LEFT: xywh in loop currRect = %d %d %d %d %s\n", currRect.x, currRect.y, currRect.width, currRect.height, bSolid?"TRUE":"FALSE"); } if (bSolid) { aContext.FillRect(currRect); } //setup for next iteration if (over == 0.0f) { bSolid = PRBool(!bSolid); } dashRect.y = dashRect.y + currRect.height; currRect = dashRect; } } } break; case NS_SIDE_TOP: { // draw top segment i if (0==x) { nsBorderEdge * leftEdge = (nsBorderEdge *)(aBorderEdges->mEdges[NS_SIDE_LEFT].ElementAt(0)); x = aBorderEdges->mMaxBorderWidth.left - leftEdge->mWidth; } y = aBounds.y; if (PR_TRUE==aBorderEdges->mOutsideEdge) // segments of the outside edge are bottom-aligned y += aBorderEdges->mMaxBorderWidth.top - segment->mWidth; nsRect borderOutside(x, y, segment->mLength, aBounds.height); x += segment->mLength; if ((style == NS_STYLE_BORDER_STYLE_DASHED) || (style == NS_STYLE_BORDER_STYLE_DOTTED)) { nsRect borderInside(borderOutside); nsBorderEdge * neighbor; // XXX Adding check to make sure segment->mInsideNeighbor is not null // so it will do the else part, at this point we are assuming this is an // ok thing to do (Bug 52130) if (PR_TRUE==aBorderEdges->mOutsideEdge && segment->mInsideNeighbor) neighbor = (nsBorderEdge *)(segment->mInsideNeighbor->mEdges[NS_SIDE_LEFT].ElementAt(0)); else neighbor = (nsBorderEdge *)(aBorderEdges->mEdges[NS_SIDE_LEFT].ElementAt(0)); nsMargin outsideMargin(neighbor->mWidth, segment->mWidth, 0, segment->mWidth); borderInside.Deflate(outsideMargin); nscoord firstRectWidth = 0; if (PR_TRUE==aBorderEdges->mOutsideEdge && 0==i) { firstRectWidth = borderInside.x - borderOutside.x; aContext.FillRect(borderOutside.x, borderOutside.y, firstRectWidth, borderInside.y - borderOutside.y); } dashRect.height = borderInside.y - borderOutside.y; dashRect.width = dashRect.height * dashLength; dashRect.x = borderOutside.x + firstRectWidth; dashRect.y = borderOutside.y; currRect = dashRect; while (currRect.x < borderInside.XMost()) { //clip if necessary if (currRect.XMost() > borderInside.XMost()) { over = float(dashRect.XMost() - borderInside.XMost()) / float(dashRect.width); currRect.width = currRect.width - (currRect.XMost() - borderInside.XMost()); } //draw if necessary if (bSolid) { aContext.FillRect(currRect); } //setup for next iteration if (over == 0.0f) { bSolid = PRBool(!bSolid); } dashRect.x = dashRect.x + currRect.width; currRect = dashRect; } } } break; case NS_SIDE_RIGHT: { // draw right segment i nsBorderEdge * topEdge = (nsBorderEdge *) (aBorderEdges->mEdges[NS_SIDE_TOP].ElementAt(aBorderEdges->mEdges[NS_SIDE_TOP].Count()-1)); if (0==y) { y = aBorderEdges->mMaxBorderWidth.top - topEdge->mWidth; if (PR_TRUE==aBorderEdges->mOutsideEdge) y += topEdge->mWidth; } nscoord width; if (PR_TRUE==aBorderEdges->mOutsideEdge) { width = aBounds.width - aBorderEdges->mMaxBorderWidth.right; width += segment->mWidth; } else { width = aBounds.width; } nscoord height = segment->mLength; nsRect borderOutside(aBounds.x, y, width, height); y += segment->mLength; if ((style == NS_STYLE_BORDER_STYLE_DASHED) || (style == NS_STYLE_BORDER_STYLE_DOTTED)) { nsRect borderInside(borderOutside); nsMargin outsideMargin(segment->mWidth, 0, (segment->mWidth), 0); borderInside.Deflate(outsideMargin); nscoord totalLength = segment->mLength; if (PR_TRUE==aBorderEdges->mOutsideEdge) { if (segment->mInsideNeighbor == neighborBorderEdges) { neighborEdgeCount++; } else { neighborBorderEdges = segment->mInsideNeighbor; neighborEdgeCount=0; } nsBorderEdge * neighborRight = (nsBorderEdge *)(segment->mInsideNeighbor->mEdges[NS_SIDE_RIGHT].ElementAt(neighborEdgeCount)); totalLength = neighborRight->mLength; } dashRect.width = borderOutside.XMost() - borderInside.XMost(); dashRect.height = nscoord(dashRect.width * dashLength); dashRect.x = borderInside.XMost(); dashRect.y = borderOutside.y + (totalLength/2) - dashRect.height; if ((PR_TRUE==aBorderEdges->mOutsideEdge) && (0!=i)) dashRect.y -= topEdge->mWidth; currRect = dashRect; // draw the top half while (currRect.YMost() > borderInside.y) { //clip if necessary if (currRect.y < borderInside.y) { over = float(borderInside.y - dashRect.y) / float(dashRect.height); currRect.height = currRect.height - (borderInside.y - currRect.y); currRect.y = borderInside.y; } //draw if necessary if (bSolid) { aContext.FillRect(currRect); } //setup for next iteration if (over == 0.0f) { bSolid = PRBool(!bSolid); } dashRect.y = dashRect.y - currRect.height; currRect = dashRect; } // draw the bottom half dashRect.y = borderOutside.y + (totalLength/2) + dashRect.height; if ((PR_TRUE==aBorderEdges->mOutsideEdge) && (0!=i)) dashRect.y -= topEdge->mWidth; currRect = dashRect; bSolid=PR_TRUE; over = 0.0f; while (currRect.YMost() < borderInside.YMost()) { //clip if necessary if (currRect.y < borderInside.y) { over = float(borderInside.y - dashRect.y) / float(dashRect.height); currRect.height = currRect.height - (borderInside.y - currRect.y); currRect.y = borderInside.y; } //draw if necessary if (bSolid) { aContext.FillRect(currRect); } //setup for next iteration if (over == 0.0f) { bSolid = PRBool(!bSolid); } dashRect.y = dashRect.y + currRect.height; currRect = dashRect; } } } break; case NS_SIDE_BOTTOM: { // draw bottom segment i if (0==x) { nsBorderEdge * leftEdge = (nsBorderEdge *) (aBorderEdges->mEdges[NS_SIDE_LEFT].ElementAt(aBorderEdges->mEdges[NS_SIDE_LEFT].Count()-1)); x = aBorderEdges->mMaxBorderWidth.left - leftEdge->mWidth; } y = aBounds.y; if (PR_TRUE==aBorderEdges->mOutsideEdge) // segments of the outside edge are top-aligned y -= aBorderEdges->mMaxBorderWidth.bottom - segment->mWidth; nsRect borderOutside(x, y, segment->mLength, aBounds.height); x += segment->mLength; if ((style == NS_STYLE_BORDER_STYLE_DASHED) || (style == NS_STYLE_BORDER_STYLE_DOTTED)) { nsRect borderInside(borderOutside); nsBorderEdge * neighbor; if (PR_TRUE==aBorderEdges->mOutsideEdge) neighbor = (nsBorderEdge *)(segment->mInsideNeighbor->mEdges[NS_SIDE_LEFT].ElementAt(0)); else neighbor = (nsBorderEdge *)(aBorderEdges->mEdges[NS_SIDE_LEFT].ElementAt(0)); nsMargin outsideMargin(neighbor->mWidth, segment->mWidth, 0, segment->mWidth); borderInside.Deflate(outsideMargin); nscoord firstRectWidth = 0; if (PR_TRUE==aBorderEdges->mOutsideEdge && 0==i) { firstRectWidth = borderInside.x - borderOutside.x; aContext.FillRect(borderOutside.x, borderInside.YMost(), firstRectWidth, borderOutside.YMost() - borderInside.YMost()); } dashRect.height = borderOutside.YMost() - borderInside.YMost(); dashRect.width = nscoord(dashRect.height * dashLength); dashRect.x = borderOutside.x + firstRectWidth; dashRect.y = borderInside.YMost(); currRect = dashRect; while (currRect.x < borderInside.XMost()) { //clip if necessary if (currRect.XMost() > borderInside.XMost()) { over = float(dashRect.XMost() - borderInside.XMost()) / float(dashRect.width); currRect.width = currRect.width - (currRect.XMost() - borderInside.XMost()); } //draw if necessary if (bSolid) { aContext.FillRect(currRect); } //setup for next iteration if (over == 0.0f) { bSolid = PRBool(!bSolid); } dashRect.x = dashRect.x + currRect.width; currRect = dashRect; } } } break; } } skippedSide = PR_FALSE; } } nscolor nsCSSRendering::TransformColor(nscolor aMapColor,PRBool aNoBackGround) { PRUint16 hue,sat,value; nscolor newcolor; newcolor = aMapColor; if (PR_TRUE == aNoBackGround){ // convert the RBG to HSV so we can get the lightness (which is the v) NS_RGB2HSV(newcolor,hue,sat,value); // The goal here is to send white to black while letting colored // stuff stay colored... So we adopt the following approach. // Something with sat = 0 should end up with value = 0. Something // with a high sat can end up with a high value and it's ok.... At // the same time, we don't want to make things lighter. Do // something simple, since it seems to work. if (value > sat) { value = sat; // convert this color back into the RGB color space. NS_HSV2RGB(newcolor,hue,sat,value); } } return newcolor; } // method GetBGColorForHTMLElement // // Now here's a *fun* hack: Nav4 uses the BODY element's background color for the // background color on tables so we need to find that element's // color and use it... Actually, we can use the HTML element as well. // // Traverse from PresContext to PresShell to Document to RootContent. The RootContent is // then checked to ensure that it is the HTML or BODY element, and if it is, we get // it's primary frame and from that the style context and from that the color to use. // PRBool GetBGColorForHTMLElement( nsPresContext *aPresContext, const nsStyleBackground *&aBGColor ) { NS_ASSERTION(aPresContext, "null params not allowed"); PRBool result = PR_FALSE; // assume we did not find the HTML element nsIPresShell* shell = aPresContext->GetPresShell(); if (shell) { nsIDocument *doc = shell->GetDocument(); if (doc) { nsIContent *pContent; if ((pContent = doc->GetRootContent())) { // make sure that this is the HTML element nsIAtom *tag = pContent->Tag(); NS_ASSERTION(tag, "Tag could not be retrieved from root content element"); if (tag == nsHTMLAtoms::html || tag == nsHTMLAtoms::body) { // use this guy's color nsIFrame *pFrame = nsnull; if (NS_SUCCEEDED(shell->GetPrimaryFrameFor(pContent, &pFrame)) && pFrame) { nsStyleContext *pContext = pFrame->GetStyleContext(); if (pContext) { const nsStyleBackground* color = pContext->GetStyleBackground(); if (0 == (color->mBackgroundFlags & NS_STYLE_BG_COLOR_TRANSPARENT)) { aBGColor = color; // set the reslt to TRUE to indicate we mapped the color result = PR_TRUE; } }// if context }// if frame }// if tag == html or body #ifdef DEBUG else { printf( "Root Content is not HTML or BODY: cannot get bgColor of HTML or BODY\n"); } #endif }// if content }// if doc } // if shell return result; } // helper macro to determine if the borderstyle 'a' is a MOZ-BG-XXX style #define MOZ_BG_BORDER(a)\ ((a==NS_STYLE_BORDER_STYLE_BG_INSET) || (a==NS_STYLE_BORDER_STYLE_BG_OUTSET)\ || (a==NS_STYLE_BORDER_STYLE_BG_SOLID)) static PRBool GetBorderColor(const nsStyleColor* aColor, const nsStyleBorder& aBorder, PRUint8 aSide, nscolor& aColorVal, nsBorderColors** aCompositeColors = nsnull) { PRBool transparent; PRBool foreground; if (aCompositeColors) { aBorder.GetCompositeColors(aSide, aCompositeColors); if (*aCompositeColors) return PR_TRUE; } aBorder.GetBorderColor(aSide, aColorVal, transparent, foreground); if (foreground) aColorVal = aColor->mColor; return !transparent; } // XXX improve this to constrain rendering to the damaged area void nsCSSRendering::PaintBorder(nsPresContext* aPresContext, nsIRenderingContext& aRenderingContext, nsIFrame* aForFrame, const nsRect& aDirtyRect, const nsRect& aBorderArea, const nsStyleBorder& aBorderStyle, nsStyleContext* aStyleContext, PRIntn aSkipSides, nsRect* aGap, nscoord aHardBorderSize, PRBool aShouldIgnoreRounded) { PRIntn cnt; nsMargin border; nsStyleCoord bordStyleRadius[4]; PRInt16 borderRadii[4],i; float percent; nsCompatibility compatMode = aPresContext->CompatibilityMode(); PRBool forceSolid; // Check to see if we have an appearance defined. If so, we let the theme // renderer draw the border. DO not get the data from aForFrame, since the passed in style context // may be different! Always use |aStyleContext|! const nsStyleDisplay* displayData = aStyleContext->GetStyleDisplay(); if (displayData->mAppearance) { nsITheme *theme = aPresContext->GetTheme(); if (theme && theme->ThemeSupportsWidget(aPresContext, aForFrame, displayData->mAppearance)) return; // Let the theme handle it. } // Get our style context's color struct. const nsStyleColor* ourColor = aStyleContext->GetStyleColor(); // in NavQuirks mode we want to use the parent's context as a starting point // for determining the background color const nsStyleBackground* bgColor = nsCSSRendering::FindNonTransparentBackground(aStyleContext, compatMode == eCompatibility_NavQuirks ? PR_TRUE : PR_FALSE); // mozBGColor is used instead of bgColor when the display type is BG_INSET or BG_OUTSET // or BG_SOLID, and, in quirk mode, it is set to the BODY element's background color // instead of the nearest ancestor's background color. const nsStyleBackground* mozBGColor = bgColor; // now check if we are in Quirks mode and have a border style of BG_INSET or OUTSET // or BG_SOLID - if so we use the bgColor from the HTML element instead of the // nearest ancestor if (compatMode == eCompatibility_NavQuirks) { PRBool bNeedBodyBGColor = PR_FALSE; if (aStyleContext) { for (cnt=0; cnt<4;cnt++) { bNeedBodyBGColor = MOZ_BG_BORDER(aBorderStyle.GetBorderStyle(cnt)); if (bNeedBodyBGColor) { break; } } } if (bNeedBodyBGColor) { GetBGColorForHTMLElement(aPresContext, mozBGColor); } } if (aHardBorderSize > 0) { border.SizeTo(aHardBorderSize, aHardBorderSize, aHardBorderSize, aHardBorderSize); } else { aBorderStyle.CalcBorderFor(aForFrame, border); } if ((0 == border.left) && (0 == border.right) && (0 == border.top) && (0 == border.bottom)) { // Empty border area return; } // get the radius for our border aBorderStyle.mBorderRadius.GetTop(bordStyleRadius[0]); //topleft aBorderStyle.mBorderRadius.GetRight(bordStyleRadius[1]); //topright aBorderStyle.mBorderRadius.GetBottom(bordStyleRadius[2]); //bottomright aBorderStyle.mBorderRadius.GetLeft(bordStyleRadius[3]); //bottomleft for(i=0;i<4;i++) { borderRadii[i] = 0; switch ( bordStyleRadius[i].GetUnit()) { case eStyleUnit_Percent: percent = bordStyleRadius[i].GetPercentValue(); borderRadii[i] = (nscoord)(percent * aBorderArea.width); break; case eStyleUnit_Coord: borderRadii[i] = bordStyleRadius[i].GetCoordValue(); break; default: break; } } // rounded version of the outline // check for any corner that is rounded for(i=0;i<4;i++){ if(borderRadii[i] > 0 && !aBorderStyle.mBorderColors){ PaintRoundedBorder(aPresContext,aRenderingContext,aForFrame,aDirtyRect,aBorderArea,&aBorderStyle,nsnull,aStyleContext,aSkipSides,borderRadii,aGap,PR_FALSE); return; } } // Turn off rendering for all of the zero sized sides if (0 == border.top) aSkipSides |= (1 << NS_SIDE_TOP); if (0 == border.right) aSkipSides |= (1 << NS_SIDE_RIGHT); if (0 == border.bottom) aSkipSides |= (1 << NS_SIDE_BOTTOM); if (0 == border.left) aSkipSides |= (1 << NS_SIDE_LEFT); // get the inside and outside parts of the border nsRect outerRect(aBorderArea); nsRect innerRect(outerRect); innerRect.Deflate(border); if (border.left + border.right > aBorderArea.width) { innerRect.x = outerRect.x; innerRect.width = outerRect.width; } if (border.top + border.bottom > aBorderArea.height) { innerRect.y = outerRect.y; innerRect.height = outerRect.height; } // If the dirty rect is completely inside the border area (e.g., only the // content is being painted), then we can skip out now if (innerRect.Contains(aDirtyRect)) { return; } //see if any sides are dotted or dashed for (cnt = 0; cnt < 4; cnt++) { if ((aBorderStyle.GetBorderStyle(cnt) == NS_STYLE_BORDER_STYLE_DOTTED) || (aBorderStyle.GetBorderStyle(cnt) == NS_STYLE_BORDER_STYLE_DASHED)) { break; } } if (cnt < 4) { DrawDashedSides(cnt, aRenderingContext,aDirtyRect, ourColor, &aBorderStyle,nsnull, PR_FALSE, outerRect, innerRect, aSkipSides, aGap); } // dont clip the borders for composite borders, they use the inner and // outer rect to compute the diagonale to cross the border radius nsRect compositeInnerRect(innerRect); nsRect compositeOuterRect(outerRect); // Draw all the other sides if (!aDirtyRect.Contains(outerRect)) { // Border leaks out of the dirty rectangle - lets clip it but with care if (innerRect.y < aDirtyRect.y) { aSkipSides |= (1 << NS_SIDE_TOP); PRUint32 shortenBy = PR_MIN(innerRect.height, aDirtyRect.y - innerRect.y); innerRect.y += shortenBy; innerRect.height -= shortenBy; outerRect.y += shortenBy; outerRect.height -= shortenBy; } if (aDirtyRect.YMost() < innerRect.YMost()) { aSkipSides |= (1 << NS_SIDE_BOTTOM); PRUint32 shortenBy = PR_MIN(innerRect.height, innerRect.YMost() - aDirtyRect.YMost()); innerRect.height -= shortenBy; outerRect.height -= shortenBy; } if (innerRect.x < aDirtyRect.x) { aSkipSides |= (1 << NS_SIDE_LEFT); PRUint32 shortenBy = PR_MIN(innerRect.width, aDirtyRect.x - innerRect.x); innerRect.x += shortenBy; innerRect.width -= shortenBy; outerRect.x += shortenBy; outerRect.width -= shortenBy; } if (aDirtyRect.XMost() < innerRect.XMost()) { aSkipSides |= (1 << NS_SIDE_RIGHT); PRUint32 shortenBy = PR_MIN(innerRect.width, innerRect.XMost() - aDirtyRect.XMost()); innerRect.width -= shortenBy; outerRect.width -= shortenBy; } } /* Get our conversion values */ nscoord twipsPerPixel = aPresContext->IntScaledPixelsToTwips(1); static PRUint8 sideOrder[] = { NS_SIDE_BOTTOM, NS_SIDE_LEFT, NS_SIDE_TOP, NS_SIDE_RIGHT }; nscolor sideColor; nsBorderColors* compositeColors = nsnull; for (cnt = 0; cnt < 4; cnt++) { PRUint8 side = sideOrder[cnt]; // If a side needs a double border but will be less than two pixels, // force it to be solid (see bug 1781). if (aBorderStyle.GetBorderStyle(side) == NS_STYLE_BORDER_STYLE_DOUBLE) { nscoord widths[] = { border.top, border.right, border.bottom, border.left }; forceSolid = (widths[side]/twipsPerPixel < 2); } else forceSolid = PR_FALSE; if (0 == (aSkipSides & (1<<side))) { if (GetBorderColor(ourColor, aBorderStyle, side, sideColor, &compositeColors)) { if (compositeColors) DrawCompositeSide(aRenderingContext, side, compositeColors, compositeOuterRect, compositeInnerRect, borderRadii, twipsPerPixel, aGap); else DrawSide(aRenderingContext, side, forceSolid ? NS_STYLE_BORDER_STYLE_SOLID : aBorderStyle.GetBorderStyle(side), sideColor, MOZ_BG_BORDER(aBorderStyle.GetBorderStyle(side)) ? mozBGColor->mBackgroundColor : bgColor->mBackgroundColor, outerRect,innerRect, aSkipSides, twipsPerPixel, aGap); } } } } void nsCSSRendering::DrawCompositeSide(nsIRenderingContext& aRenderingContext, PRIntn aWhichSide, nsBorderColors* aCompositeColors, const nsRect& aOuterRect, const nsRect& aInnerRect, PRInt16* aBorderRadii, nscoord twipsPerPixel, nsRect* aGap) { // Loop over each color and at each iteration shrink the length of the // lines that we draw. nsRect currOuterRect(aOuterRect); // XXXdwh This border radius code is rather hacky and will only work for // small radii, but it will be sufficient to get a major performance // improvement in themes with small curvature (like Modern). // Still, this code should be rewritten if/when someone chooses to pick // up the -moz-border-radius gauntlet. // Alternatively we could add support for a -moz-border-diagonal property, which is // what this code actually draws (instead of a curve). // determine the the number of pixels we need to draw for this side // and the start and end radii nscoord shrinkage, startRadius, endRadius; if (aWhichSide == NS_SIDE_TOP) { shrinkage = aInnerRect.y - aOuterRect.y; startRadius = aBorderRadii[0]; endRadius = aBorderRadii[1]; } else if (aWhichSide == NS_SIDE_BOTTOM) { shrinkage = (aOuterRect.height+aOuterRect.y) - (aInnerRect.height+aInnerRect.y); startRadius = aBorderRadii[3]; endRadius = aBorderRadii[2]; } else if (aWhichSide == NS_SIDE_RIGHT) { shrinkage = (aOuterRect.width+aOuterRect.x) - (aInnerRect.width+aInnerRect.x); startRadius = aBorderRadii[1]; endRadius = aBorderRadii[2]; } else { NS_ASSERTION(aWhichSide == NS_SIDE_LEFT, "incorrect aWhichSide"); shrinkage = aInnerRect.x - aOuterRect.x; startRadius = aBorderRadii[0]; endRadius = aBorderRadii[3]; } while (shrinkage > 0) { nscoord xshrink = 0; nscoord yshrink = 0; nscoord widthshrink = 0; nscoord heightshrink = 0; if (startRadius || endRadius) { if (aWhichSide == NS_SIDE_TOP || aWhichSide == NS_SIDE_BOTTOM) { xshrink = startRadius; widthshrink = startRadius + endRadius; } else if (aWhichSide == NS_SIDE_LEFT || aWhichSide == NS_SIDE_RIGHT) { yshrink = startRadius-1; heightshrink = yshrink + endRadius; } } // subtract any rounded pixels from the outer rect nsRect newOuterRect(currOuterRect); newOuterRect.x += xshrink; newOuterRect.y += yshrink; newOuterRect.width -= widthshrink; newOuterRect.height -= heightshrink; nsRect borderInside(currOuterRect); // try to subtract one pixel from each side of the outer rect, but only if // that side has any extra space left to shrink if (aInnerRect.x > borderInside.x) { // shrink left borderInside.x += twipsPerPixel; borderInside.width -= twipsPerPixel; } if (borderInside.x+borderInside.width > aInnerRect.x+aInnerRect.width) // shrink right borderInside.width -= twipsPerPixel; if (aInnerRect.y > borderInside.y) { // shrink top borderInside.y += twipsPerPixel; borderInside.height -= twipsPerPixel; } if (borderInside.y+borderInside.height > aInnerRect.y+aInnerRect.height) // shrink bottom borderInside.height -= twipsPerPixel; if (!aCompositeColors->mTransparent) { nsPoint theSide[MAX_POLY_POINTS]; PRInt32 np = MakeSide(theSide, aRenderingContext, aWhichSide, newOuterRect, borderInside, 0, BORDER_FULL, 1.0f, twipsPerPixel); NS_ASSERTION(np == 2, "Composite border should always be single pixel!"); aRenderingContext.SetColor(aCompositeColors->mColor); DrawLine(aRenderingContext, theSide[0].x, theSide[0].y, theSide[1].x, theSide[1].y, aGap); if (aWhichSide == NS_SIDE_TOP) { if (startRadius) { // Connecting line between top/left nscoord distance = (startRadius+twipsPerPixel)/2; nscoord remainder = distance%twipsPerPixel; if (remainder) distance += twipsPerPixel - remainder; DrawLine(aRenderingContext, currOuterRect.x+startRadius, currOuterRect.y, currOuterRect.x+startRadius-distance, currOuterRect.y+distance, aGap); } if (endRadius) { // Connecting line between top/right nscoord distance = (endRadius+twipsPerPixel)/2; nscoord remainder = distance%twipsPerPixel; if (remainder) distance += twipsPerPixel - remainder; DrawLine(aRenderingContext, currOuterRect.x+currOuterRect.width-endRadius-twipsPerPixel, currOuterRect.y, currOuterRect.x+currOuterRect.width-endRadius-twipsPerPixel+distance, currOuterRect.y+distance, aGap); } } else if (aWhichSide == NS_SIDE_BOTTOM) { if (startRadius) { // Connecting line between bottom/left nscoord distance = (startRadius+twipsPerPixel)/2; nscoord remainder = distance%twipsPerPixel; if (remainder) distance += twipsPerPixel - remainder; DrawLine(aRenderingContext, currOuterRect.x+startRadius, currOuterRect.y+currOuterRect.height-twipsPerPixel, currOuterRect.x+startRadius-distance, currOuterRect.y+currOuterRect.height-twipsPerPixel-distance, aGap); } if (endRadius) { // Connecting line between bottom/right nscoord distance = (endRadius+twipsPerPixel)/2; nscoord remainder = distance%twipsPerPixel; if (remainder) distance += twipsPerPixel - remainder; DrawLine(aRenderingContext, currOuterRect.x+currOuterRect.width-endRadius-twipsPerPixel, currOuterRect.y+currOuterRect.height-twipsPerPixel, currOuterRect.x+currOuterRect.width-endRadius-twipsPerPixel+distance, currOuterRect.y+currOuterRect.height-twipsPerPixel-distance, aGap); } } else if (aWhichSide == NS_SIDE_LEFT) { if (startRadius) { // Connecting line between left/top nscoord distance = (startRadius-twipsPerPixel)/2; nscoord remainder = distance%twipsPerPixel; if (remainder) distance -= remainder; DrawLine(aRenderingContext, currOuterRect.x+distance, currOuterRect.y+startRadius-distance, currOuterRect.x, currOuterRect.y+startRadius, aGap); } if (endRadius) { // Connecting line between left/bottom nscoord distance = (endRadius-twipsPerPixel)/2; nscoord remainder = distance%twipsPerPixel; if (remainder) distance -= remainder; DrawLine(aRenderingContext, currOuterRect.x+distance, currOuterRect.y+currOuterRect.height-twipsPerPixel-endRadius+distance, currOuterRect.x, currOuterRect.y+currOuterRect.height-twipsPerPixel-endRadius, aGap); } } else if (aWhichSide == NS_SIDE_RIGHT) { if (startRadius) { // Connecting line between right/top nscoord distance = (startRadius-twipsPerPixel)/2; nscoord remainder = distance%twipsPerPixel; if (remainder) distance -= remainder; DrawLine(aRenderingContext, currOuterRect.x+currOuterRect.width-twipsPerPixel-distance, currOuterRect.y+startRadius-distance, currOuterRect.x+currOuterRect.width-twipsPerPixel, currOuterRect.y+startRadius, aGap); } if (endRadius) { // Connecting line between right/bottom nscoord distance = (endRadius-twipsPerPixel)/2; nscoord remainder = distance%twipsPerPixel; if (remainder) distance -= remainder; DrawLine(aRenderingContext, currOuterRect.x+currOuterRect.width-twipsPerPixel-distance, currOuterRect.y+currOuterRect.height-twipsPerPixel-endRadius+distance, currOuterRect.x+currOuterRect.width-twipsPerPixel, currOuterRect.y+currOuterRect.height-twipsPerPixel-endRadius, aGap); } } } if (aCompositeColors->mNext) aCompositeColors = aCompositeColors->mNext; currOuterRect = borderInside; shrinkage -= twipsPerPixel; startRadius -= twipsPerPixel; if (startRadius < 0) startRadius = 0; endRadius -= twipsPerPixel; if (endRadius < 0) endRadius = 0; } } // XXX improve this to constrain rendering to the damaged area void nsCSSRendering::PaintOutline(nsPresContext* aPresContext, nsIRenderingContext& aRenderingContext, nsIFrame* aForFrame, const nsRect& aDirtyRect, const nsRect& aBorderArea, const nsStyleBorder& aBorderStyle, const nsStyleOutline& aOutlineStyle, nsStyleContext* aStyleContext, PRIntn aSkipSides, nsRect* aGap) { nsStyleCoord bordStyleRadius[4]; PRInt16 borderRadii[4],i; float percent; const nsStyleBackground* bgColor = nsCSSRendering::FindNonTransparentBackground(aStyleContext); nscoord width, offset; // Get our style context's color struct. const nsStyleColor* ourColor = aStyleContext->GetStyleColor(); aOutlineStyle.GetOutlineWidth(width); if (0 == width) { // Empty outline return; } // get the radius for our outline aOutlineStyle.mOutlineRadius.GetTop(bordStyleRadius[0]); //topleft aOutlineStyle.mOutlineRadius.GetRight(bordStyleRadius[1]); //topright aOutlineStyle.mOutlineRadius.GetBottom(bordStyleRadius[2]); //bottomright aOutlineStyle.mOutlineRadius.GetLeft(bordStyleRadius[3]); //bottomleft for(i=0;i<4;i++) { borderRadii[i] = 0; switch ( bordStyleRadius[i].GetUnit()) { case eStyleUnit_Percent: percent = bordStyleRadius[i].GetPercentValue(); borderRadii[i] = (nscoord)(percent * aBorderArea.width); break; case eStyleUnit_Coord: borderRadii[i] = bordStyleRadius[i].GetCoordValue(); break; default: break; } } nsRect* overflowArea = aForFrame->GetOverflowAreaProperty(PR_FALSE); if (!overflowArea) { NS_WARNING("Hmm, outline painting should always find an overflow area here"); return; } // get the offset for our outline aOutlineStyle.GetOutlineOffset(offset); nsRect outside(*overflowArea); nsRect inside(outside); if (width + offset >= 0) { // the overflow area is exactly the outside edge of the outline inside.Deflate(width, width); } else { // the overflow area is exactly the rectangle containing the frame and its // children; we can compute the outline directly inside.Deflate(-offset, -offset); if (inside.width < 0 || inside.height < 0) { return; // Protect against negative outline sizes } outside = inside; outside.Inflate(width, width); } // rounded version of the border for(i=0;i<4;i++){ if(borderRadii[i] > 0){ PaintRoundedBorder(aPresContext, aRenderingContext, aForFrame, aDirtyRect, outside, nsnull, &aOutlineStyle, aStyleContext, aSkipSides, borderRadii, aGap, PR_TRUE); return; } } PRUint8 outlineStyle = aOutlineStyle.GetOutlineStyle(); //see if any sides are dotted or dashed if ((outlineStyle == NS_STYLE_BORDER_STYLE_DOTTED) || (outlineStyle == NS_STYLE_BORDER_STYLE_DASHED)) { DrawDashedSides(0, aRenderingContext, aDirtyRect, ourColor, nsnull, &aOutlineStyle, PR_TRUE, outside, inside, aSkipSides, aGap); return; } // Draw all the other sides /* XXX something is misnamed here!!!! */ nscoord twipsPerPixel;/* XXX */ float p2t;/* XXX */ p2t = aPresContext->PixelsToTwips();/* XXX */ twipsPerPixel = (nscoord) p2t;/* XXX */ nscolor outlineColor(NS_RGB(0,0,0)); // default to black in case it is invert color and the platform does not support that PRBool canDraw = PR_FALSE; PRBool modeChanged=PR_FALSE; // see if the outline color is 'invert' or can invert. if (aOutlineStyle.GetOutlineInvert()) { canDraw = PR_TRUE; if( NS_SUCCEEDED(aRenderingContext.SetPenMode(nsPenMode_kInvert)) ) { modeChanged=PR_TRUE; } } else { canDraw = aOutlineStyle.GetOutlineColor(outlineColor); } if (PR_TRUE == canDraw) { DrawSide(aRenderingContext, NS_SIDE_BOTTOM, outlineStyle, outlineColor, bgColor->mBackgroundColor, outside, inside, aSkipSides, twipsPerPixel, aGap); DrawSide(aRenderingContext, NS_SIDE_LEFT, outlineStyle, outlineColor, bgColor->mBackgroundColor,outside, inside,aSkipSides, twipsPerPixel, aGap); DrawSide(aRenderingContext, NS_SIDE_TOP, outlineStyle, outlineColor, bgColor->mBackgroundColor,outside, inside,aSkipSides, twipsPerPixel, aGap); DrawSide(aRenderingContext, NS_SIDE_RIGHT, outlineStyle, outlineColor, bgColor->mBackgroundColor,outside, inside,aSkipSides, twipsPerPixel, aGap); if(modeChanged ) { aRenderingContext.SetPenMode(nsPenMode_kNone); } } } /* draw the edges of the border described in aBorderEdges one segment at a time. * a border has 4 edges. Each edge has 1 or more segments. * "inside edges" are drawn differently than "outside edges" so the shared edges will match up. * in the case of table collapsing borders, the table edge is the "outside" edge and * cell edges are always "inside" edges (so adjacent cells have 2 shared "inside" edges.) * dashed segments are drawn by DrawDashedSegments(). */ // XXX: doesn't do corners or junctions well at all. Just uses logic stolen // from PaintBorder which is insufficient void nsCSSRendering::PaintBorderEdges(nsPresContext* aPresContext, nsIRenderingContext& aRenderingContext, nsIFrame* aForFrame, const nsRect& aDirtyRect, const nsRect& aBorderArea, nsBorderEdges * aBorderEdges, nsStyleContext* aStyleContext, PRIntn aSkipSides, nsRect* aGap) { const nsStyleBackground* bgColor = nsCSSRendering::FindNonTransparentBackground(aStyleContext); if (nsnull==aBorderEdges) { // Empty border segments return; } // Turn off rendering for all of the zero sized sides if (0 == aBorderEdges->mMaxBorderWidth.top) aSkipSides |= (1 << NS_SIDE_TOP); if (0 == aBorderEdges->mMaxBorderWidth.right) aSkipSides |= (1 << NS_SIDE_RIGHT); if (0 == aBorderEdges->mMaxBorderWidth.bottom) aSkipSides |= (1 << NS_SIDE_BOTTOM); if (0 == aBorderEdges->mMaxBorderWidth.left) aSkipSides |= (1 << NS_SIDE_LEFT); // Draw any dashed or dotted segments separately DrawDashedSegments(aRenderingContext, aBorderArea, aBorderEdges, aSkipSides, aGap); // Draw all the other sides nscoord twipsPerPixel; float p2t; p2t = aPresContext->PixelsToTwips(); twipsPerPixel = (nscoord) p2t;/* XXX huh!*/ if (0 == (aSkipSides & (1<<NS_SIDE_TOP))) { PRInt32 segmentCount = aBorderEdges->mEdges[NS_SIDE_TOP].Count(); PRInt32 i; nsBorderEdge * leftEdge = (nsBorderEdge *)(aBorderEdges->mEdges[NS_SIDE_LEFT].ElementAt(0)); nscoord x = aBorderEdges->mMaxBorderWidth.left - leftEdge->mWidth; for (i=0; i<segmentCount; i++) { nsBorderEdge * borderEdge = (nsBorderEdge *)(aBorderEdges->mEdges[NS_SIDE_TOP].ElementAt(i)); nscoord y = aBorderArea.y; if (PR_TRUE==aBorderEdges->mOutsideEdge) // segments of the outside edge are bottom-aligned y += aBorderEdges->mMaxBorderWidth.top - borderEdge->mWidth; nsRect inside(x, y, borderEdge->mLength, aBorderArea.height); x += borderEdge->mLength; nsRect outside(inside); nsMargin outsideMargin(0, borderEdge->mWidth, 0, 0); outside.Deflate(outsideMargin); DrawSide(aRenderingContext, NS_SIDE_TOP, borderEdge->mStyle, borderEdge->mColor, bgColor->mBackgroundColor, inside, outside,aSkipSides, twipsPerPixel, aGap); } } if (0 == (aSkipSides & (1<<NS_SIDE_LEFT))) { PRInt32 segmentCount = aBorderEdges->mEdges[NS_SIDE_LEFT].Count(); PRInt32 i; nsBorderEdge * topEdge = (nsBorderEdge *)(aBorderEdges->mEdges[NS_SIDE_TOP].ElementAt(0)); nscoord y = aBorderEdges->mMaxBorderWidth.top - topEdge->mWidth; for (i=0; i<segmentCount; i++) { nsBorderEdge * borderEdge = (nsBorderEdge *)(aBorderEdges->mEdges[NS_SIDE_LEFT].ElementAt(i)); nscoord x = aBorderArea.x + (aBorderEdges->mMaxBorderWidth.left - borderEdge->mWidth); nsRect inside(x, y, aBorderArea.width, borderEdge->mLength); y += borderEdge->mLength; nsRect outside(inside); nsMargin outsideMargin(borderEdge->mWidth, 0, 0, 0); outside.Deflate(outsideMargin); DrawSide(aRenderingContext, NS_SIDE_LEFT, borderEdge->mStyle, borderEdge->mColor, bgColor->mBackgroundColor, inside, outside, aSkipSides, twipsPerPixel, aGap); } } if (0 == (aSkipSides & (1<<NS_SIDE_BOTTOM))) { PRInt32 segmentCount = aBorderEdges->mEdges[NS_SIDE_BOTTOM].Count(); PRInt32 i; nsBorderEdge * leftEdge = (nsBorderEdge *) (aBorderEdges->mEdges[NS_SIDE_LEFT].ElementAt(aBorderEdges->mEdges[NS_SIDE_LEFT].Count()-1)); nscoord x = aBorderEdges->mMaxBorderWidth.left - leftEdge->mWidth; for (i=0; i<segmentCount; i++) { nsBorderEdge * borderEdge = (nsBorderEdge *)(aBorderEdges->mEdges[NS_SIDE_BOTTOM].ElementAt(i)); nscoord y = aBorderArea.y; if (PR_TRUE==aBorderEdges->mOutsideEdge) // segments of the outside edge are top-aligned y -= (aBorderEdges->mMaxBorderWidth.bottom - borderEdge->mWidth); nsRect inside(x, y, borderEdge->mLength, aBorderArea.height); x += borderEdge->mLength; nsRect outside(inside); nsMargin outsideMargin(0, 0, 0, borderEdge->mWidth); outside.Deflate(outsideMargin); DrawSide(aRenderingContext, NS_SIDE_BOTTOM, borderEdge->mStyle, borderEdge->mColor, bgColor->mBackgroundColor, inside, outside,aSkipSides, twipsPerPixel, aGap); } } if (0 == (aSkipSides & (1<<NS_SIDE_RIGHT))) { PRInt32 segmentCount = aBorderEdges->mEdges[NS_SIDE_RIGHT].Count(); PRInt32 i; nsBorderEdge * topEdge = (nsBorderEdge *) (aBorderEdges->mEdges[NS_SIDE_TOP].ElementAt(aBorderEdges->mEdges[NS_SIDE_TOP].Count()-1)); nscoord y = aBorderEdges->mMaxBorderWidth.top - topEdge->mWidth; for (i=0; i<segmentCount; i++) { nsBorderEdge * borderEdge = (nsBorderEdge *)(aBorderEdges->mEdges[NS_SIDE_RIGHT].ElementAt(i)); nscoord width; if (PR_TRUE==aBorderEdges->mOutsideEdge) { width = aBorderArea.width - aBorderEdges->mMaxBorderWidth.right; width += borderEdge->mWidth; } else { width = aBorderArea.width; } nsRect inside(aBorderArea.x, y, width, borderEdge->mLength); y += borderEdge->mLength; nsRect outside(inside); nsMargin outsideMargin(0, 0, (borderEdge->mWidth), 0); outside.Deflate(outsideMargin); DrawSide(aRenderingContext, NS_SIDE_RIGHT, borderEdge->mStyle, borderEdge->mColor, bgColor->mBackgroundColor, inside, outside,aSkipSides, twipsPerPixel, aGap); } } } //---------------------------------------------------------------------- // Returns the anchor point to use for the background image. The // anchor point is the (x, y) location where the first tile should // be placed // // For repeated tiling, the anchor values are normalized wrt to the upper-left // edge of the bounds, and are always in the range: // -(aTileWidth - 1) <= anchor.x <= 0 // -(aTileHeight - 1) <= anchor.y <= 0 // // i.e., they are either 0 or a negative number whose absolute value is // less than the tile size in that dimension // // aOriginBounds is the box to which the tiling position should be relative // aClipBounds is the box in which the tiling will actually be done // They should correspond to 'background-origin' and 'background-clip', // except when painting on the canvas, in which case the origin bounds // should be the bounds of the root element's frame and the clip bounds // should be the bounds of the canvas frame. static void ComputeBackgroundAnchorPoint(const nsStyleBackground& aColor, const nsRect& aOriginBounds, const nsRect& aClipBounds, nscoord aTileWidth, nscoord aTileHeight, nsPoint& aResult) { nscoord x; if (NS_STYLE_BG_X_POSITION_LENGTH & aColor.mBackgroundFlags) { x = aColor.mBackgroundXPosition.mCoord; } else if (NS_STYLE_BG_X_POSITION_PERCENT & aColor.mBackgroundFlags) { PRFloat64 percent = PRFloat64(aColor.mBackgroundXPosition.mFloat); nscoord tilePos = nscoord(percent * PRFloat64(aTileWidth)); nscoord boxPos = nscoord(percent * PRFloat64(aOriginBounds.width)); x = boxPos - tilePos; } else { x = 0; } x += aOriginBounds.x - aClipBounds.x; if (NS_STYLE_BG_REPEAT_X & aColor.mBackgroundRepeat) { // When we are tiling in the x direction the loop will run from // the left edge of the box to the right edge of the box. We need // to adjust the starting coordinate to lie within the band being // rendered. if (x < 0) { x = -x; if (x < 0) { // Some joker gave us max-negative-integer. x = 0; } x %= aTileWidth; x = -x; } else if (x != 0) { x %= aTileWidth; if (x > 0) { x = x - aTileWidth; } } NS_POSTCONDITION((x >= -(aTileWidth - 1)) && (x <= 0), "bad computed anchor value"); } aResult.x = x; nscoord y; if (NS_STYLE_BG_Y_POSITION_LENGTH & aColor.mBackgroundFlags) { y = aColor.mBackgroundYPosition.mCoord; } else if (NS_STYLE_BG_Y_POSITION_PERCENT & aColor.mBackgroundFlags){ PRFloat64 percent = PRFloat64(aColor.mBackgroundYPosition.mFloat); nscoord tilePos = nscoord(percent * PRFloat64(aTileHeight)); nscoord boxPos = nscoord(percent * PRFloat64(aOriginBounds.height)); y = boxPos - tilePos; } else { y = 0; } y += aOriginBounds.y - aClipBounds.y; if (NS_STYLE_BG_REPEAT_Y & aColor.mBackgroundRepeat) { // When we are tiling in the y direction the loop will run from // the top edge of the box to the bottom edge of the box. We need // to adjust the starting coordinate to lie within the band being // rendered. if (y < 0) { y = -y; if (y < 0) { // Some joker gave us max-negative-integer. y = 0; } y %= aTileHeight; y = -y; } else if (y != 0) { y %= aTileHeight; if (y > 0) { y = y - aTileHeight; } } NS_POSTCONDITION((y >= -(aTileHeight - 1)) && (y <= 0), "bad computed anchor value"); } aResult.y = y; } // Returns the root scrollable frame, which is the first child of the root // frame. static nsIScrollableFrame* GetRootScrollableFrame(nsPresContext* aPresContext, nsIFrame* aRootFrame) { nsIScrollableFrame* scrollableFrame = nsnull; if (nsLayoutAtoms::viewportFrame == aRootFrame->GetType()) { nsIFrame* childFrame = aRootFrame->GetFirstChild(nsnull); if (childFrame) { if (nsLayoutAtoms::scrollFrame == childFrame->GetType()) { // Use this frame, even if we are using GFX frames for the // viewport, which contains another scroll frame below this // frame, since the GFX scrollport frame does not implement // nsIScrollableFrame. CallQueryInterface(childFrame, &scrollableFrame); } } } #ifdef DEBUG else { NS_WARNING("aRootFrame is not a viewport frame"); } #endif // DEBUG return scrollableFrame; } const nsStyleBackground* nsCSSRendering::FindNonTransparentBackground(nsStyleContext* aContext, PRBool aStartAtParent /*= PR_FALSE*/) { NS_ASSERTION(aContext, "Cannot find NonTransparentBackground in a null context" ); const nsStyleBackground* result = nsnull; nsStyleContext* context = nsnull; if (aStartAtParent) { context = aContext->GetParent(); } if (!context) { context = aContext; } while (context) { result = context->GetStyleBackground(); if (0 == (result->mBackgroundFlags & NS_STYLE_BG_COLOR_TRANSPARENT)) break; context = context->GetParent(); } return result; } /** * |FindBackground| finds the correct style data to use to paint the * background. It is responsible for handling the following two * statements in section 14.2 of CSS2: * * The background of the box generated by the root element covers the * entire canvas. * * For HTML documents, however, we recommend that authors specify the * background for the BODY element rather than the HTML element. User * agents should observe the following precedence rules to fill in the * background: if the value of the 'background' property for the HTML * element is different from 'transparent' then use it, else use the * value of the 'background' property for the BODY element. If the * resulting value is 'transparent', the rendering is undefined. * * Thus, in our implementation, it is responsible for ensuring that: * + we paint the correct background on the |nsCanvasFrame|, * |nsRootBoxFrame|, or |nsPageFrame|, * + we don't paint the background on the root element, and * + we don't paint the background on the BODY element in *some* cases, * and for SGML-based HTML documents only. * * |FindBackground| returns true if a background should be painted, and * the resulting style context to use for the background information * will be filled in to |aBackground|. It fills in a boolean indicating * whether the frame is the canvas frame to allow PaintBackground to * ensure that it always paints something non-transparent for the * canvas. */ // Returns nsnull if aFrame is not a canvas frame. // Otherwise, it returns the frame we should look for the background on. // This is normally aFrame but if aFrame is the viewport, we need to // look for the background starting at the scroll root (which shares // style context with the document root) or the document root itself. // We need to treat the viewport as canvas because, even though // it does not actually paint a background, we need to get the right // background style so we correctly detect transparent documents. inline nsIFrame* IsCanvasFrame(nsPresContext* aPresContext, nsIFrame *aFrame) { nsIAtom* frameType = aFrame->GetType(); if (frameType == nsLayoutAtoms::canvasFrame || frameType == nsLayoutAtoms::rootFrame || frameType == nsLayoutAtoms::pageFrame) { return aFrame; } else if (frameType == nsLayoutAtoms::viewportFrame) { nsIFrame* firstChild = aFrame->GetFirstChild(nsnull); if (firstChild) { return firstChild; } } return nsnull; } inline PRBool FindCanvasBackground(nsPresContext* aPresContext, nsIFrame* aForFrame, const nsStyleBackground** aBackground) { // XXXldb What if the root element is positioned, etc.? (We don't // allow that yet, do we?) nsIFrame *firstChild = aForFrame->GetFirstChild(nsnull); if (firstChild) { const nsStyleBackground* result = firstChild->GetStyleBackground(); // for printing and print preview.. this should be a pageContentFrame nsStyleContext* parentContext; if (firstChild->GetType() == nsLayoutAtoms::pageContentFrame) { // we have to find the background style ourselves.. since the // pageContentframe does not have content while(firstChild){ for (nsIFrame* kidFrame = firstChild; nsnull != kidFrame; ) { parentContext = kidFrame->GetStyleContext(); result = parentContext->GetStyleBackground(); if (!result->IsTransparent()) { *aBackground = kidFrame->GetStyleBackground(); return PR_TRUE; } else { kidFrame = kidFrame->GetNextSibling(); } } firstChild = firstChild->GetFirstChild(nsnull); } return PR_FALSE; // nothing found for this } // Check if we need to do propagation from BODY rather than HTML. if (result->IsTransparent()) { nsIContent* content = aForFrame->GetContent(); if (content) { // Use |GetOwnerDoc| so it works during destruction. nsIDocument* document = content->GetOwnerDoc(); nsCOMPtr<nsIDOMHTMLDocument> htmlDoc = do_QueryInterface(document); if (htmlDoc) { if (!document->IsCaseSensitive()) { // HTML, not XHTML nsCOMPtr<nsIDOMHTMLElement> body; htmlDoc->GetBody(getter_AddRefs(body)); nsCOMPtr<nsIContent> bodyContent = do_QueryInterface(body); // We need to null check the body node (bug 118829) since // there are cases, thanks to the fix for bug 5569, where we // will reflow a document with no body. In particular, if a // SCRIPT element in the head blocks the parser and then has a // SCRIPT that does "document.location.href = 'foo'", then // nsParser::Terminate will call |DidBuildModel| methods // through to the content sink, which will call |StartLayout| // and thus |InitialReflow| on the pres shell. See bug 119351 // for the ugly details. if (bodyContent) { nsIFrame *bodyFrame; nsresult rv = aPresContext->PresShell()-> GetPrimaryFrameFor(bodyContent, &bodyFrame); if (NS_SUCCEEDED(rv) && bodyFrame) result = bodyFrame->GetStyleBackground(); } } } } } *aBackground = result; } else { // This should always give transparent, so we'll fill it in with the // default color if needed. This seems to happen a bit while a page is // being loaded. *aBackground = aForFrame->GetStyleBackground(); } return PR_TRUE; } inline PRBool FindElementBackground(nsPresContext* aPresContext, nsIFrame* aForFrame, const nsStyleBackground** aBackground) { nsIFrame *parentFrame = aForFrame->GetParent(); // XXXldb We shouldn't have to null-check |parentFrame| here. if (parentFrame && IsCanvasFrame(aPresContext, parentFrame) == parentFrame) { // Check that we're really the root (rather than in another child list). nsIFrame *childFrame = parentFrame->GetFirstChild(nsnull); if (childFrame == aForFrame) return PR_FALSE; // Background was already drawn for the canvas. } *aBackground = aForFrame->GetStyleBackground(); // Return true unless the frame is for a BODY element whose background // was propagated to the viewport. if (aForFrame->GetStyleContext()->GetPseudoType()) return PR_TRUE; // A pseudo-element frame. nsIContent* content = aForFrame->GetContent(); if (!content || !content->IsContentOfType(nsIContent::eHTML)) return PR_TRUE; // not frame for an HTML element if (!parentFrame) return PR_TRUE; // no parent to look at if (content->Tag() != nsHTMLAtoms::body) return PR_TRUE; // not frame for <BODY> element // We should only look at the <html> background if we're in an HTML document nsIDocument* document = content->GetOwnerDoc(); nsCOMPtr<nsIDOMHTMLDocument> htmlDoc = do_QueryInterface(document); if (!htmlDoc) return PR_TRUE; if (document->IsCaseSensitive()) // XHTML, not HTML return PR_TRUE; const nsStyleBackground* htmlBG = parentFrame->GetStyleBackground(); return !htmlBG->IsTransparent(); } PRBool nsCSSRendering::FindBackground(nsPresContext* aPresContext, nsIFrame* aForFrame, const nsStyleBackground** aBackground, PRBool* aIsCanvas) { nsIFrame* canvasFrame = IsCanvasFrame(aPresContext, aForFrame); *aIsCanvas = canvasFrame != nsnull; return canvasFrame ? FindCanvasBackground(aPresContext, canvasFrame, aBackground) : FindElementBackground(aPresContext, aForFrame, aBackground); } void nsCSSRendering::DidPaint() { gInlineBGData.Reset(); } void nsCSSRendering::PaintBackground(nsPresContext* aPresContext, nsIRenderingContext& aRenderingContext, nsIFrame* aForFrame, const nsRect& aDirtyRect, const nsRect& aBorderArea, const nsStyleBorder& aBorder, const nsStylePadding& aPadding, PRBool aUsePrintSettings, nsRect* aBGClipRect) { NS_PRECONDITION(aForFrame, "Frame is expected to be provided to PaintBackground"); PRBool isCanvas; const nsStyleBackground *color; if (!FindBackground(aPresContext, aForFrame, &color, &isCanvas)) { // we don't want to bail out of moz-appearance is set on a root // node. If it has a parent content node, bail because it's not // a root, other wise keep going in order to let the theme stuff // draw the background. The canvas really should be drawing the // bg, but there's no way to hook that up via css. if (!aForFrame->GetStyleDisplay()->mAppearance) { return; } nsIContent* content = aForFrame->GetContent(); if (!content || content->GetParent()) { return; } color = aForFrame->GetStyleBackground(); } if (!isCanvas) { PaintBackgroundWithSC(aPresContext, aRenderingContext, aForFrame, aDirtyRect, aBorderArea, *color, aBorder, aPadding, aUsePrintSettings, aBGClipRect); return; } if (!color) return; nsStyleBackground canvasColor(*color); nsIViewManager* vm = aPresContext->GetViewManager(); if (canvasColor.mBackgroundFlags & NS_STYLE_BG_COLOR_TRANSPARENT) { nsIView* rootView; vm->GetRootView(rootView); if (!rootView->GetParent()) { PRBool widgetIsTranslucent = PR_FALSE; if (rootView->HasWidget()) { rootView->GetWidget()->GetWindowTranslucency(widgetIsTranslucent); } if (!widgetIsTranslucent) { // Ensure that we always paint a color for the root (in case there's // no background at all or a partly transparent image). canvasColor.mBackgroundFlags &= ~NS_STYLE_BG_COLOR_TRANSPARENT; canvasColor.mBackgroundColor = aPresContext->DefaultBackgroundColor(); } } } vm->SetDefaultBackgroundColor(canvasColor.mBackgroundColor); // Since nsHTMLContainerFrame::CreateViewForFrame might have created // the view before we knew about the child with the fixed background // attachment (root or BODY) or the stylesheet specifying that // attachment, set the BitBlt flag here as well. if (canvasColor.mBackgroundAttachment == NS_STYLE_BG_ATTACHMENT_FIXED) { nsIView *view = aForFrame->GetView(); if (view) vm->SetViewBitBltEnabled(view, PR_FALSE); } PaintBackgroundWithSC(aPresContext, aRenderingContext, aForFrame, aDirtyRect, aBorderArea, canvasColor, aBorder, aPadding, aUsePrintSettings, aBGClipRect); } void nsCSSRendering::PaintBackgroundWithSC(nsPresContext* aPresContext, nsIRenderingContext& aRenderingContext, nsIFrame* aForFrame, const nsRect& aDirtyRect, const nsRect& aBorderArea, const nsStyleBackground& aColor, const nsStyleBorder& aBorder, const nsStylePadding& aPadding, PRBool aUsePrintSettings, nsRect* aBGClipRect) { NS_PRECONDITION(aForFrame, "Frame is expected to be provided to PaintBackground"); PRBool canDrawBackgroundImage = PR_TRUE; PRBool canDrawBackgroundColor = PR_TRUE; if (aUsePrintSettings) { canDrawBackgroundImage = aPresContext->GetBackgroundImageDraw(); canDrawBackgroundColor = aPresContext->GetBackgroundColorDraw(); } // Check to see if we have an appearance defined. If so, we let the theme // renderer draw the background and bail out. const nsStyleDisplay* displayData = aForFrame->GetStyleDisplay(); if (displayData->mAppearance) { nsITheme *theme = aPresContext->GetTheme(); if (theme && theme->ThemeSupportsWidget(aPresContext, aForFrame, displayData->mAppearance)) { theme->DrawWidgetBackground(&aRenderingContext, aForFrame, displayData->mAppearance, aBorderArea, aDirtyRect); return; } } nsRect bgClipArea; if (aBGClipRect) { bgClipArea = *aBGClipRect; } else { // The background is rendered over the 'background-clip' area. bgClipArea = aBorderArea; if (aColor.mBackgroundClip != NS_STYLE_BG_CLIP_BORDER) { NS_ASSERTION(aColor.mBackgroundClip == NS_STYLE_BG_CLIP_PADDING, "unknown background-clip value"); bgClipArea.Deflate(aBorder.GetBorder()); } } // The actual dirty rect is the intersection of the 'background-clip' // area and the dirty rect we were given nsRect dirtyRect; if (!dirtyRect.IntersectRect(bgClipArea, aDirtyRect)) { // Nothing to paint return; } // if there is no background image or background images are turned off, try a color. if (!aColor.mBackgroundImage || !canDrawBackgroundImage) { PaintBackgroundColor(aPresContext, aRenderingContext, aForFrame, bgClipArea, aColor, aBorder, aPadding, canDrawBackgroundColor); return; } // We have a background image // Lookup the image imgIRequest *req = aPresContext->LoadImage(aColor.mBackgroundImage, aForFrame); PRUint32 status = imgIRequest::STATUS_ERROR; if (req) req->GetImageStatus(&status); if (!req || !(status & imgIRequest::STATUS_FRAME_COMPLETE) || !(status & imgIRequest::STATUS_SIZE_AVAILABLE)) { PaintBackgroundColor(aPresContext, aRenderingContext, aForFrame, bgClipArea, aColor, aBorder, aPadding, canDrawBackgroundColor); return; } nsCOMPtr<imgIContainer> image; req->GetImage(getter_AddRefs(image)); nsSize imageSize; image->GetWidth(&imageSize.width); image->GetHeight(&imageSize.height); float p2t; p2t = aPresContext->PixelsToTwips(); imageSize.width = NSIntPixelsToTwips(imageSize.width, p2t); imageSize.height = NSIntPixelsToTwips(imageSize.height, p2t); req = nsnull; nsRect bgOriginArea; nsIAtom* frameType = aForFrame->GetType(); if (frameType == nsLayoutAtoms::inlineFrame) { switch (aColor.mBackgroundInlinePolicy) { case NS_STYLE_BG_INLINE_POLICY_EACH_BOX: bgOriginArea = aBorderArea; break; case NS_STYLE_BG_INLINE_POLICY_BOUNDING_BOX: bgOriginArea = gInlineBGData.GetBoundingRect(aForFrame); break; default: NS_ERROR("Unknown background-inline-policy value! " "Please, teach me what to do."); case NS_STYLE_BG_INLINE_POLICY_CONTINUOUS: bgOriginArea = gInlineBGData.GetContinuousRect(aForFrame); break; } } else { bgOriginArea = aBorderArea; } // Background images are tiled over the 'background-clip' area // but the origin of the tiling is based on the 'background-origin' area if (aColor.mBackgroundOrigin != NS_STYLE_BG_ORIGIN_BORDER) { bgOriginArea.Deflate(aBorder.GetBorder()); if (aColor.mBackgroundOrigin != NS_STYLE_BG_ORIGIN_PADDING) { nsMargin padding; // XXX CalcPaddingFor is deprecated, but we need it for percentage padding aPadding.CalcPaddingFor(aForFrame, padding); bgOriginArea.Deflate(padding); NS_ASSERTION(aColor.mBackgroundOrigin == NS_STYLE_BG_ORIGIN_CONTENT, "unknown background-origin value"); } } // Based on the repeat setting, compute how many tiles we should // lay down for each axis. The value computed is the maximum based // on the dirty rect before accounting for the background-position. nscoord tileWidth = imageSize.width; nscoord tileHeight = imageSize.height; PRBool needBackgroundColor = !(aColor.mBackgroundFlags & NS_STYLE_BG_COLOR_TRANSPARENT); PRIntn repeat = aColor.mBackgroundRepeat; nscoord xDistance, yDistance; switch (repeat) { case NS_STYLE_BG_REPEAT_X: xDistance = dirtyRect.width; yDistance = tileHeight; break; case NS_STYLE_BG_REPEAT_Y: xDistance = tileWidth; yDistance = dirtyRect.height; break; case NS_STYLE_BG_REPEAT_XY: xDistance = dirtyRect.width; yDistance = dirtyRect.height; if (needBackgroundColor) { // If the image is completely opaque, we do not need to paint the // background color nsCOMPtr<gfxIImageFrame> gfxImgFrame; image->GetCurrentFrame(getter_AddRefs(gfxImgFrame)); if (gfxImgFrame) { gfxImgFrame->GetNeedsBackground(&needBackgroundColor); /* check for tiling of a image where frame smaller than container */ nsSize iSize; image->GetWidth(&iSize.width); image->GetHeight(&iSize.height); nsRect iframeRect; gfxImgFrame->GetRect(iframeRect); if (iSize.width != iframeRect.width || iSize.height != iframeRect.height) { needBackgroundColor = PR_TRUE; } } } break; case NS_STYLE_BG_REPEAT_OFF: default: NS_ASSERTION(repeat == NS_STYLE_BG_REPEAT_OFF, "unknown background-repeat value"); xDistance = tileWidth; yDistance = tileHeight; break; } // The background color is rendered over the 'background-clip' area if (needBackgroundColor) { PaintBackgroundColor(aPresContext, aRenderingContext, aForFrame, bgClipArea, aColor, aBorder, aPadding, canDrawBackgroundColor); } if ((tileWidth == 0) || (tileHeight == 0) || dirtyRect.IsEmpty()) { // Nothing left to paint return; } // Compute the anchor point. // // When tiling, the anchor coordinate values will be negative offsets // from the background-origin area. nsPoint anchor; if (NS_STYLE_BG_ATTACHMENT_FIXED == aColor.mBackgroundAttachment) { // If it's a fixed background attachment, then the image is placed // relative to the viewport nsIView* viewportView = nsnull; nsRect viewportArea; nsIFrame* rootFrame = aPresContext->PresShell()->FrameManager()->GetRootFrame(); NS_ASSERTION(rootFrame, "no root frame"); if (aPresContext->IsPaginated()) { nsIFrame* page = nsLayoutUtils::GetPageFrame(aForFrame); NS_ASSERTION(page, "no page"); rootFrame = page; } viewportView = rootFrame->GetView(); NS_ASSERTION(viewportView, "no viewport view"); viewportArea = viewportView->GetBounds(); viewportArea.x = 0; viewportArea.y = 0; nsIScrollableFrame* scrollableFrame = GetRootScrollableFrame(aPresContext, rootFrame); if (scrollableFrame) { nsMargin scrollbars = scrollableFrame->GetActualScrollbarSizes(); viewportArea.Deflate(scrollbars); } // Get the anchor point ComputeBackgroundAnchorPoint(aColor, viewportArea, viewportArea, tileWidth, tileHeight, anchor); // Convert the anchor point to aForFrame's coordinate space nsPoint offset(0, 0); nsIView* view = aForFrame->GetClosestView(&offset); anchor -= offset; NS_ASSERTION(view, "expected a view"); anchor -= view->GetOffsetTo(viewportView); } else { if (frameType == nsLayoutAtoms::canvasFrame) { // If the frame is the canvas, the image is placed relative to // the root element's (first) frame (see bug 46446) nsRect firstRootElementFrameArea; nsIFrame* firstRootElementFrame = aForFrame->GetFirstChild(nsnull); NS_ASSERTION(firstRootElementFrame, "A canvas with a background " "image had no child frame, which is impossible according to CSS. " "Make sure there isn't a background image specified on the " "|:viewport| pseudo-element in |html.css|."); // temporary null check -- see bug 97226 if (firstRootElementFrame) { firstRootElementFrameArea = firstRootElementFrame->GetRect(); // Take the border out of the frame's rect const nsStyleBorder* borderStyle = firstRootElementFrame->GetStyleBorder(); firstRootElementFrameArea.Deflate(borderStyle->GetBorder()); // Get the anchor point ComputeBackgroundAnchorPoint(aColor, firstRootElementFrameArea, bgClipArea, tileWidth, tileHeight, anchor); } else { ComputeBackgroundAnchorPoint(aColor, bgOriginArea, bgClipArea, tileWidth, tileHeight, anchor); } } else { // Otherwise, it is the normal case, and the background is // simply placed relative to the frame's background-clip area ComputeBackgroundAnchorPoint(aColor, bgOriginArea, bgClipArea, tileWidth, tileHeight, anchor); } } #if (!defined(XP_UNIX) && !defined(XP_BEOS)) || defined(XP_MACOSX) // Setup clipping so that rendering doesn't leak out of the computed // dirty rect aRenderingContext.PushState(); aRenderingContext.SetClipRect(dirtyRect, nsClipCombine_kIntersect); #endif // Compute the x and y starting points and limits for tiling /* An Overview Of The Following Logic A........ . . . . . . . . . . . . . . : +---:-------.-------.-------.---- /|\ : | : . . . | nh :.......: . . . x . . . . . . . . . . \|/ . | . . . . . | . . ########### . . . . . . . . . . .#. . . . .#. . . . . | . . ########### . /|\ . | . . . . | h . . | . . . . . . . . . . . . . z . . \|/ . | . . . . |<-----nw------>| |<--w-->| ---- = the background clip area edge. The painting is done within to this area. If the background is positioned relative to the viewport ('fixed') then this is the viewport edge. .... = the primary tile. . . = the other tiles. #### = the dirtyRect. This is the minimum region we want to cover. A = The anchor point. This is the point at which the tile should start. Always negative or zero. x = x0 and y0 in the code. The point at which tiling must start so that the fewest tiles are laid out while completly covering the dirtyRect area. z = x1 and y1 in the code. The point at which tiling must end so that the fewest tiles are laid out while completly covering the dirtyRect area. w = the width of the tile (tileWidth). h = the height of the tile (tileHeight). n = the number of whole tiles that fit between 'A' and 'x'. (the vertical n and the horizontal n are different) Therefore, x0 = bgClipArea.x + anchor.x + n * tileWidth; ...where n is an integer greater or equal to 0 fitting: n * tileWidth <= dirtyRect.x - (bgClipArea.x + anchor.x) <= (n+1) * tileWidth ...i.e., n <= (dirtyRect.x - (bgClipArea.x + anchor.x)) / tileWidth < n + 1 ...which, treating the division as an integer divide rounding down, gives: n = (dirtyRect.x - (bgClipArea.x + anchor.x)) / tileWidth Substituting into the original expression for x0: x0 = bgClipArea.x + anchor.x + ((dirtyRect.x - (bgClipArea.x + anchor.x)) / tileWidth) * tileWidth; From this x1 is determined, x1 = x0 + m * tileWidth; ...where m is an integer greater than 0 fitting: (m - 1) * tileWidth < dirtyRect.x + dirtyRect.width - x0 <= m * tileWidth ...i.e., m - 1 < (dirtyRect.x + dirtyRect.width - x0) / tileWidth <= m ...which, treating the division as an integer divide, and making it round up, gives: m = (dirtyRect.x + dirtyRect.width - x0 + tileWidth - 1) / tileWidth Substituting into the original expression for x1: x1 = x0 + ((dirtyRect.x + dirtyRect.width - x0 + tileWidth - 1) / tileWidth) * tileWidth The vertical case is analogous. If the background is fixed, then bgClipArea.x and bgClipArea.y are set to zero when finding the parent viewport, above. */ // first do the horizontal case nscoord x0, x1; // For scrolling attachment, the anchor is within the 'background-clip' // For fixed attachment, the anchor is within the bounds of the nearest // scrolling ancestor (or the viewport) x0 = (NS_STYLE_BG_ATTACHMENT_SCROLL == aColor.mBackgroundAttachment) ? bgClipArea.x : 0; if (repeat & NS_STYLE_BG_REPEAT_X) { // When tiling in the x direction, adjust the starting position of the // tile to account for dirtyRect.x. When tiling in x, the anchor.x value // will be a negative value used to adjust the starting coordinate. x0 += anchor.x + ((dirtyRect.x - (bgClipArea.x + anchor.x)) / tileWidth) * tileWidth; x1 = x0 + ((dirtyRect.x + dirtyRect.width - x0 + tileWidth - 1) / tileWidth) * tileWidth; } else { x0 += anchor.x; x1 = x0 + tileWidth; } // now do all that again with the vertical case nscoord y0, y1; // For scrolling attachment, the anchor is within the 'background-clip' // For fixed attachment, the anchor is within the bounds of the nearest // scrolling ancestor (or the viewport) y0 = (NS_STYLE_BG_ATTACHMENT_SCROLL == aColor.mBackgroundAttachment) ? bgClipArea.y : 0; if (repeat & NS_STYLE_BG_REPEAT_Y) { // When tiling in the y direction, adjust the starting position of the // tile to account for dirtyRect.y. When tiling in y, the anchor.y value // will be a negative value used to adjust the starting coordinate. y0 += anchor.y + ((dirtyRect.y - (bgClipArea.y + anchor.y)) / tileHeight) * tileHeight; y1 = y0 + ((dirtyRect.y + dirtyRect.height - y0 + tileHeight - 1) / tileHeight) * tileHeight; } else { y0 += anchor.y; y1 = y0 + tileHeight; } // Take the intersection again to paint only the required area nsRect tileRect(x0, y0, (x1 - x0), (y1 - y0)); nsRect drawRect; if (drawRect.IntersectRect(tileRect, dirtyRect)) aRenderingContext.DrawTile(image, x0, y0, &drawRect); #if (!defined(XP_UNIX) && !defined(XP_BEOS)) || defined(XP_MACOSX) // Restore clipping aRenderingContext.PopState(); #endif } void nsCSSRendering::PaintBackgroundColor(nsPresContext* aPresContext, nsIRenderingContext& aRenderingContext, nsIFrame* aForFrame, const nsRect& aBgClipArea, const nsStyleBackground& aColor, const nsStyleBorder& aBorder, const nsStylePadding& aPadding, PRBool aCanPaintNonWhite) { if (aColor.mBackgroundFlags & NS_STYLE_BG_COLOR_TRANSPARENT) { // nothing to paint return; } nsStyleCoord bordStyleRadius[4]; PRInt16 borderRadii[4]; nsRect bgClipArea(aBgClipArea); // get the radius for our border aBorder.mBorderRadius.GetTop(bordStyleRadius[NS_SIDE_TOP]); // topleft aBorder.mBorderRadius.GetRight(bordStyleRadius[NS_SIDE_RIGHT]); // topright aBorder.mBorderRadius.GetBottom(bordStyleRadius[NS_SIDE_BOTTOM]); // bottomright aBorder.mBorderRadius.GetLeft(bordStyleRadius[NS_SIDE_LEFT]); // bottomleft PRUint8 side = 0; for (; side < 4; ++side) { borderRadii[side] = 0; switch (bordStyleRadius[side].GetUnit()) { case eStyleUnit_Percent: borderRadii[side] = nscoord(bordStyleRadius[side].GetPercentValue() * aBgClipArea.width); break; case eStyleUnit_Coord: borderRadii[side] = bordStyleRadius[side].GetCoordValue(); break; default: break; } } // Rounded version of the border // XXXdwh Composite borders (with multiple colors per side) use their own border radius // algorithm now, since the current one doesn't work right for small radii. if (!aBorder.mBorderColors) { for (side = 0; side < 4; ++side) { if (borderRadii[side] > 0) { PaintRoundedBackground(aPresContext, aRenderingContext, aForFrame, bgClipArea, aColor, aBorder, borderRadii, aCanPaintNonWhite); return; } } } else if (aColor.mBackgroundClip == NS_STYLE_BG_CLIP_BORDER) { // XXX users of -moz-border-*-colors expect a transparent border-color // to show the parent's background-color instead of its background-color. // This seems wrong, but we handle that here by explictly clipping the // background to the padding area. bgClipArea.Deflate(aBorder.GetBorder()); } nscolor color = aColor.mBackgroundColor; if (!aCanPaintNonWhite) { color = NS_RGB(255, 255, 255); } aRenderingContext.SetColor(color); aRenderingContext.FillRect(bgClipArea); } /** --------------------------------------------------- * See documentation in nsCSSRendering.h * @update 3/26/99 dwc */ void nsCSSRendering::PaintRoundedBackground(nsPresContext* aPresContext, nsIRenderingContext& aRenderingContext, nsIFrame* aForFrame, const nsRect& aBgClipArea, const nsStyleBackground& aColor, const nsStyleBorder& aBorder, PRInt16 aTheRadius[4], PRBool aCanPaintNonWhite) { RoundedRect outerPath; QBCurve cr1,cr2,cr3,cr4; QBCurve UL,UR,LL,LR; PRInt32 curIndex,c1Index; nsFloatPoint thePath[MAXPATHSIZE]; static nsPoint polyPath[MAXPOLYPATHSIZE]; PRInt16 np; nscoord twipsPerPixel; float p2t; // needed for our border thickness p2t = aPresContext->PixelsToTwips(); twipsPerPixel = NSToCoordRound(p2t); nscolor color = aColor.mBackgroundColor; if (!aCanPaintNonWhite) { color = NS_RGB(255, 255, 255); } aRenderingContext.SetColor(color); // Adjust for background-clip, if necessary if (aColor.mBackgroundClip != NS_STYLE_BG_CLIP_BORDER) { NS_ASSERTION(aColor.mBackgroundClip == NS_STYLE_BG_CLIP_PADDING, "unknown background-clip value"); // Get the radius to the outer edge of the padding. // -moz-border-radius is the radius to the outer edge of the border. NS_FOR_CSS_SIDES(side) { aTheRadius[side] -= aBorder.GetBorderWidth(side); aTheRadius[side] = PR_MAX(aTheRadius[side], 0); } } // set the rounded rect up, and let'er rip outerPath.Set(aBgClipArea.x,aBgClipArea.y,aBgClipArea.width,aBgClipArea.height,aTheRadius,twipsPerPixel); outerPath.GetRoundedBorders(UL,UR,LL,LR); // BUILD THE ENTIRE OUTSIDE PATH // TOP LINE ---------------------------------------------------------------- UL.MidPointDivide(&cr1,&cr2); UR.MidPointDivide(&cr3,&cr4); np=0; thePath[np++].MoveTo(cr2.mAnc1.x,cr2.mAnc1.y); thePath[np++].MoveTo(cr2.mCon.x, cr2.mCon.y); thePath[np++].MoveTo(cr2.mAnc2.x, cr2.mAnc2.y); thePath[np++].MoveTo(cr3.mAnc1.x, cr3.mAnc1.y); thePath[np++].MoveTo(cr3.mCon.x, cr3.mCon.y); thePath[np++].MoveTo(cr3.mAnc2.x, cr3.mAnc2.y); polyPath[0].x = NSToCoordRound(thePath[0].x); polyPath[0].y = NSToCoordRound(thePath[0].y); curIndex = 1; GetPath(thePath,polyPath,&curIndex,eOutside,c1Index); // RIGHT LINE ---------------------------------------------------------------- LR.MidPointDivide(&cr2,&cr3); np=0; thePath[np++].MoveTo(cr4.mAnc1.x,cr4.mAnc1.y); thePath[np++].MoveTo(cr4.mCon.x, cr4.mCon.y); thePath[np++].MoveTo(cr4.mAnc2.x, cr4.mAnc2.y); thePath[np++].MoveTo(cr2.mAnc1.x, cr2.mAnc1.y); thePath[np++].MoveTo(cr2.mCon.x, cr2.mCon.y); thePath[np++].MoveTo(cr2.mAnc2.x, cr2.mAnc2.y); GetPath(thePath,polyPath,&curIndex,eOutside,c1Index); // BOTTOM LINE ---------------------------------------------------------------- LL.MidPointDivide(&cr2,&cr4); np=0; thePath[np++].MoveTo(cr3.mAnc1.x,cr3.mAnc1.y); thePath[np++].MoveTo(cr3.mCon.x, cr3.mCon.y); thePath[np++].MoveTo(cr3.mAnc2.x, cr3.mAnc2.y); thePath[np++].MoveTo(cr2.mAnc1.x, cr2.mAnc1.y); thePath[np++].MoveTo(cr2.mCon.x, cr2.mCon.y); thePath[np++].MoveTo(cr2.mAnc2.x, cr2.mAnc2.y); GetPath(thePath,polyPath,&curIndex,eOutside,c1Index); // LEFT LINE ---------------------------------------------------------------- np=0; thePath[np++].MoveTo(cr4.mAnc1.x,cr4.mAnc1.y); thePath[np++].MoveTo(cr4.mCon.x, cr4.mCon.y); thePath[np++].MoveTo(cr4.mAnc2.x, cr4.mAnc2.y); thePath[np++].MoveTo(cr1.mAnc1.x, cr1.mAnc1.y); thePath[np++].MoveTo(cr1.mCon.x, cr1.mCon.y); thePath[np++].MoveTo(cr1.mAnc2.x, cr1.mAnc2.y); GetPath(thePath,polyPath,&curIndex,eOutside,c1Index); aRenderingContext.FillPolygon(polyPath,curIndex); } /** --------------------------------------------------- * See documentation in nsCSSRendering.h * @update 3/26/99 dwc */ void nsCSSRendering::PaintRoundedBorder(nsPresContext* aPresContext, nsIRenderingContext& aRenderingContext, nsIFrame* aForFrame, const nsRect& aDirtyRect, const nsRect& aBorderArea, const nsStyleBorder* aBorderStyle, const nsStyleOutline* aOutlineStyle, nsStyleContext* aStyleContext, PRIntn aSkipSides, PRInt16 aBorderRadius[4], nsRect* aGap, PRBool aIsOutline) { RoundedRect outerPath; QBCurve UL,LL,UR,LR; QBCurve IUL,ILL,IUR,ILR; QBCurve cr1,cr2,cr3,cr4; QBCurve Icr1,Icr2,Icr3,Icr4; nsFloatPoint thePath[MAXPATHSIZE]; PRInt16 np; nsMargin border; nscoord twipsPerPixel,qtwips; float p2t; NS_ASSERTION((aIsOutline && aOutlineStyle) || (!aIsOutline && aBorderStyle), "null params not allowed"); if (!aIsOutline) { aBorderStyle->CalcBorderFor(aForFrame, border); if ((0 == border.left) && (0 == border.right) && (0 == border.top) && (0 == border.bottom)) { return; } } else { nscoord width; if (!aOutlineStyle->GetOutlineWidth(width)) { return; } border.left = width; border.right = width; border.top = width; border.bottom = width; } // needed for our border thickness p2t = aPresContext->PixelsToTwips(); twipsPerPixel = NSToCoordRound(p2t); // Base our thickness check on the segment being less than a pixel and 1/2 qtwips = twipsPerPixel >> 2; //qtwips = twipsPerPixel; outerPath.Set(aBorderArea.x,aBorderArea.y,aBorderArea.width,aBorderArea.height,aBorderRadius,twipsPerPixel); outerPath.GetRoundedBorders(UL,UR,LL,LR); outerPath.CalcInsetCurves(IUL,IUR,ILL,ILR,border); // TOP LINE -- construct and divide the curves first, then put together our top and bottom paths UL.MidPointDivide(&cr1,&cr2); UR.MidPointDivide(&cr3,&cr4); IUL.MidPointDivide(&Icr1,&Icr2); IUR.MidPointDivide(&Icr3,&Icr4); if(0!=border.top){ np=0; thePath[np++].MoveTo(cr2.mAnc1.x,cr2.mAnc1.y); thePath[np++].MoveTo(cr2.mCon.x, cr2.mCon.y); thePath[np++].MoveTo(cr2.mAnc2.x, cr2.mAnc2.y); thePath[np++].MoveTo(cr3.mAnc1.x, cr3.mAnc1.y); thePath[np++].MoveTo(cr3.mCon.x, cr3.mCon.y); thePath[np++].MoveTo(cr3.mAnc2.x, cr3.mAnc2.y); thePath[np++].MoveTo(Icr3.mAnc2.x,Icr3.mAnc2.y); thePath[np++].MoveTo(Icr3.mCon.x, Icr3.mCon.y); thePath[np++].MoveTo(Icr3.mAnc1.x, Icr3.mAnc1.y); thePath[np++].MoveTo(Icr2.mAnc2.x, Icr2.mAnc2.y); thePath[np++].MoveTo(Icr2.mCon.x, Icr2.mCon.y); thePath[np++].MoveTo(Icr2.mAnc1.x, Icr2.mAnc1.y); RenderSide(thePath,aRenderingContext,aBorderStyle,aOutlineStyle,aStyleContext,NS_SIDE_TOP,border,qtwips, aIsOutline); } // RIGHT LINE ---------------------------------------------------------------- LR.MidPointDivide(&cr2,&cr3); ILR.MidPointDivide(&Icr2,&Icr3); if(0!=border.right){ np=0; thePath[np++].MoveTo(cr4.mAnc1.x,cr4.mAnc1.y); thePath[np++].MoveTo(cr4.mCon.x, cr4.mCon.y); thePath[np++].MoveTo(cr4.mAnc2.x,cr4.mAnc2.y); thePath[np++].MoveTo(cr2.mAnc1.x,cr2.mAnc1.y); thePath[np++].MoveTo(cr2.mCon.x, cr2.mCon.y); thePath[np++].MoveTo(cr2.mAnc2.x,cr2.mAnc2.y); thePath[np++].MoveTo(Icr2.mAnc2.x,Icr2.mAnc2.y); thePath[np++].MoveTo(Icr2.mCon.x, Icr2.mCon.y); thePath[np++].MoveTo(Icr2.mAnc1.x,Icr2.mAnc1.y); thePath[np++].MoveTo(Icr4.mAnc2.x,Icr4.mAnc2.y); thePath[np++].MoveTo(Icr4.mCon.x, Icr4.mCon.y); thePath[np++].MoveTo(Icr4.mAnc1.x,Icr4.mAnc1.y); RenderSide(thePath,aRenderingContext,aBorderStyle,aOutlineStyle,aStyleContext,NS_SIDE_RIGHT,border,qtwips, aIsOutline); } // bottom line ---------------------------------------------------------------- LL.MidPointDivide(&cr2,&cr4); ILL.MidPointDivide(&Icr2,&Icr4); if(0!=border.bottom){ np=0; thePath[np++].MoveTo(cr3.mAnc1.x,cr3.mAnc1.y); thePath[np++].MoveTo(cr3.mCon.x, cr3.mCon.y); thePath[np++].MoveTo(cr3.mAnc2.x, cr3.mAnc2.y); thePath[np++].MoveTo(cr2.mAnc1.x, cr2.mAnc1.y); thePath[np++].MoveTo(cr2.mCon.x, cr2.mCon.y); thePath[np++].MoveTo(cr2.mAnc2.x, cr2.mAnc2.y); thePath[np++].MoveTo(Icr2.mAnc2.x,Icr2.mAnc2.y); thePath[np++].MoveTo(Icr2.mCon.x, Icr2.mCon.y); thePath[np++].MoveTo(Icr2.mAnc1.x, Icr2.mAnc1.y); thePath[np++].MoveTo(Icr3.mAnc2.x, Icr3.mAnc2.y); thePath[np++].MoveTo(Icr3.mCon.x, Icr3.mCon.y); thePath[np++].MoveTo(Icr3.mAnc1.x, Icr3.mAnc1.y); RenderSide(thePath,aRenderingContext,aBorderStyle,aOutlineStyle,aStyleContext,NS_SIDE_BOTTOM,border,qtwips, aIsOutline); } // left line ---------------------------------------------------------------- if(0==border.left) return; np=0; thePath[np++].MoveTo(cr4.mAnc1.x,cr4.mAnc1.y); thePath[np++].MoveTo(cr4.mCon.x, cr4.mCon.y); thePath[np++].MoveTo(cr4.mAnc2.x, cr4.mAnc2.y); thePath[np++].MoveTo(cr1.mAnc1.x, cr1.mAnc1.y); thePath[np++].MoveTo(cr1.mCon.x, cr1.mCon.y); thePath[np++].MoveTo(cr1.mAnc2.x, cr1.mAnc2.y); thePath[np++].MoveTo(Icr1.mAnc2.x,Icr1.mAnc2.y); thePath[np++].MoveTo(Icr1.mCon.x, Icr1.mCon.y); thePath[np++].MoveTo(Icr1.mAnc1.x, Icr1.mAnc1.y); thePath[np++].MoveTo(Icr4.mAnc2.x, Icr4.mAnc2.y); thePath[np++].MoveTo(Icr4.mCon.x, Icr4.mCon.y); thePath[np++].MoveTo(Icr4.mAnc1.x, Icr4.mAnc1.y); RenderSide(thePath,aRenderingContext,aBorderStyle,aOutlineStyle,aStyleContext,NS_SIDE_LEFT,border,qtwips, aIsOutline); } /** --------------------------------------------------- * See documentation in nsCSSRendering.h * @update 3/26/99 dwc */ void nsCSSRendering::RenderSide(nsFloatPoint aPoints[],nsIRenderingContext& aRenderingContext, const nsStyleBorder* aBorderStyle,const nsStyleOutline* aOutlineStyle,nsStyleContext* aStyleContext, PRUint8 aSide,nsMargin &aBorThick,nscoord aTwipsPerPixel, PRBool aIsOutline) { QBCurve thecurve; nscolor sideColor = NS_RGB(0,0,0); static nsPoint polypath[MAXPOLYPATHSIZE]; PRInt32 curIndex,c1Index,c2Index,junk; PRInt8 border_Style; PRInt16 thickness; // Get our style context's color struct. const nsStyleColor* ourColor = aStyleContext->GetStyleColor(); NS_ASSERTION((aIsOutline && aOutlineStyle) || (!aIsOutline && aBorderStyle), "null params not allowed"); // set the style information if (!aIsOutline) { if (!GetBorderColor(ourColor, *aBorderStyle, aSide, sideColor)) { return; } } else { aOutlineStyle->GetOutlineColor(sideColor); } aRenderingContext.SetColor ( sideColor ); thickness = 0; switch(aSide){ case NS_SIDE_LEFT: thickness = aBorThick.left; break; case NS_SIDE_TOP: thickness = aBorThick.top; break; case NS_SIDE_RIGHT: thickness = aBorThick.right; break; case NS_SIDE_BOTTOM: thickness = aBorThick.bottom; break; } // if the border is thin, just draw it if (thickness<=aTwipsPerPixel) { // NOTHING FANCY JUST DRAW OUR OUTSIDE BORDER thecurve.SetPoints(aPoints[0].x,aPoints[0].y,aPoints[1].x,aPoints[1].y,aPoints[2].x,aPoints[2].y); thecurve.SubDivide((nsIRenderingContext*)&aRenderingContext,0,0); aRenderingContext.DrawLine((nscoord)aPoints[2].x,(nscoord)aPoints[2].y,(nscoord)aPoints[3].x,(nscoord)aPoints[3].y); thecurve.SetPoints(aPoints[3].x,aPoints[3].y,aPoints[4].x,aPoints[4].y,aPoints[5].x,aPoints[5].y); thecurve.SubDivide((nsIRenderingContext*)&aRenderingContext,0,0); } else { if (!aIsOutline) { border_Style = aBorderStyle->GetBorderStyle(aSide); } else { border_Style = aOutlineStyle->GetOutlineStyle(); } switch (border_Style){ case NS_STYLE_BORDER_STYLE_OUTSET: case NS_STYLE_BORDER_STYLE_INSET: case NS_STYLE_BORDER_STYLE_BG_OUTSET: case NS_STYLE_BORDER_STYLE_BG_INSET: case NS_STYLE_BORDER_STYLE_BG_SOLID: { const nsStyleBackground* bgColor = nsCSSRendering::FindNonTransparentBackground(aStyleContext); if (border_Style == NS_STYLE_BORDER_STYLE_BG_SOLID) { nscolor colors[2]; NS_Get3DColors(colors, bgColor->mBackgroundColor); aRenderingContext.SetColor(colors[0]); } else { aRenderingContext.SetColor(MakeBevelColor(aSide, border_Style, bgColor->mBackgroundColor, sideColor, !MOZ_BG_BORDER(border_Style))); } } case NS_STYLE_BORDER_STYLE_DOTTED: case NS_STYLE_BORDER_STYLE_DASHED: // break; XXX This is here until dotted and dashed are supported. It is ok to have // dotted and dashed render in solid until this style is supported. This code should // be moved when it is supported so that the above outset and inset will fall into the // solid code below.... case NS_STYLE_BORDER_STYLE_AUTO: case NS_STYLE_BORDER_STYLE_SOLID: polypath[0].x = NSToCoordRound(aPoints[0].x); polypath[0].y = NSToCoordRound(aPoints[0].y); curIndex = 1; GetPath(aPoints,polypath,&curIndex,eOutside,c1Index); c2Index = curIndex; polypath[curIndex].x = NSToCoordRound(aPoints[6].x); polypath[curIndex].y = NSToCoordRound(aPoints[6].y); curIndex++; GetPath(aPoints,polypath,&curIndex,eInside,junk); polypath[curIndex].x = NSToCoordRound(aPoints[0].x); polypath[curIndex].y = NSToCoordRound(aPoints[0].y); curIndex++; aRenderingContext.FillPolygon(polypath,curIndex); break; case NS_STYLE_BORDER_STYLE_DOUBLE: polypath[0].x = NSToCoordRound(aPoints[0].x); polypath[0].y = NSToCoordRound(aPoints[0].y); curIndex = 1; GetPath(aPoints,polypath,&curIndex,eOutside,c1Index); aRenderingContext.DrawPolyline(polypath,curIndex); polypath[0].x = NSToCoordRound(aPoints[6].x); polypath[0].y = NSToCoordRound(aPoints[6].y); curIndex = 1; GetPath(aPoints,polypath,&curIndex,eInside,c1Index); aRenderingContext.DrawPolyline(polypath,curIndex); break; case NS_STYLE_BORDER_STYLE_NONE: case NS_STYLE_BORDER_STYLE_HIDDEN: break; case NS_STYLE_BORDER_STYLE_RIDGE: case NS_STYLE_BORDER_STYLE_GROOVE: { const nsStyleBackground* bgColor = nsCSSRendering::FindNonTransparentBackground(aStyleContext); aRenderingContext.SetColor ( MakeBevelColor (aSide, border_Style, bgColor->mBackgroundColor,sideColor, PR_TRUE)); polypath[0].x = NSToCoordRound(aPoints[0].x); polypath[0].y = NSToCoordRound(aPoints[0].y); curIndex = 1; GetPath(aPoints,polypath,&curIndex,eOutside,c1Index); polypath[curIndex].x = NSToCoordRound((aPoints[5].x + aPoints[6].x)/2.0f); polypath[curIndex].y = NSToCoordRound((aPoints[5].y + aPoints[6].y)/2.0f); curIndex++; GetPath(aPoints,polypath,&curIndex,eCalcRev,c1Index,.5); polypath[curIndex].x = NSToCoordRound(aPoints[0].x); polypath[curIndex].y = NSToCoordRound(aPoints[0].y); curIndex++; aRenderingContext.FillPolygon(polypath,curIndex); aRenderingContext.SetColor ( MakeBevelColor (aSide, ((border_Style == NS_STYLE_BORDER_STYLE_RIDGE) ? NS_STYLE_BORDER_STYLE_GROOVE : NS_STYLE_BORDER_STYLE_RIDGE), bgColor->mBackgroundColor,sideColor, PR_TRUE)); polypath[0].x = NSToCoordRound((aPoints[0].x + aPoints[11].x)/2.0f); polypath[0].y = NSToCoordRound((aPoints[0].y + aPoints[11].y)/2.0f); curIndex = 1; GetPath(aPoints,polypath,&curIndex,eCalc,c1Index,.5); polypath[curIndex].x = NSToCoordRound(aPoints[6].x) ; polypath[curIndex].y = NSToCoordRound(aPoints[6].y); curIndex++; GetPath(aPoints,polypath,&curIndex,eInside,c1Index); polypath[curIndex].x = NSToCoordRound(aPoints[0].x); polypath[curIndex].y = NSToCoordRound(aPoints[0].y); curIndex++; aRenderingContext.FillPolygon(polypath,curIndex); } break; default: break; } } } /** --------------------------------------------------- * See documentation in nsCSSRendering.h * @update 3/26/99 dwc */ void RoundedRect::CalcInsetCurves(QBCurve &aULCurve,QBCurve &aURCurve,QBCurve &aLLCurve,QBCurve &aLRCurve,nsMargin &aBorder) { PRInt32 nLeft,nTop,nRight,nBottom; PRInt32 tLeft,bLeft,tRight,bRight,lTop,rTop,lBottom,rBottom; PRInt16 adjust=0; if(mDoRound) adjust = mRoundness[0]>>3; nLeft = mLeft + aBorder.left; tLeft = mLeft + mRoundness[0]; bLeft = mLeft + mRoundness[3]; if(tLeft < nLeft){ tLeft = nLeft; } if(bLeft < nLeft){ bLeft = nLeft; } nRight = mRight - aBorder.right; tRight = mRight - mRoundness[1]; bRight = mRight - mRoundness[2]; if(tRight > nRight){ tRight = nRight; } if(bRight > nRight){ bRight = nRight; } nTop = mTop + aBorder.top; lTop = mTop + mRoundness[0]; rTop = mTop + mRoundness[1]; if(lTop < nTop){ lTop = nTop; } if(rTop < nTop){ rTop = nTop; } nBottom = mBottom - aBorder.bottom; lBottom = mBottom - mRoundness[3]; rBottom = mBottom - mRoundness[2]; if(lBottom > nBottom){ lBottom = nBottom; } if(rBottom > nBottom){ rBottom = nBottom; } // set the passed in curves to the rounded borders of the rectangle aULCurve.SetPoints( (float)nLeft,(float)lTop, (float)nLeft+adjust,(float)nTop+adjust, (float)tLeft,(float)nTop); aURCurve.SetPoints( (float)tRight,(float)nTop, (float)nRight-adjust,(float)nTop+adjust, (float)nRight,(float)rTop); aLRCurve.SetPoints( (float)nRight,(float)rBottom, (float)nRight-adjust,(float)nBottom-adjust, (float)bRight,(float)nBottom); aLLCurve.SetPoints( (float)bLeft,(float)nBottom, (float)nLeft+adjust,(float)nBottom-adjust, (float)nLeft,(float)lBottom); } /** --------------------------------------------------- * See documentation in nsCSSRendering.h * @update 4/13/99 dwc */ void RoundedRect::Set(nscoord aLeft,nscoord aTop,PRInt32 aWidth,PRInt32 aHeight,PRInt16 aRadius[4],PRInt16 aNumTwipPerPix) { nscoord x,y,width,height; int i; // convert this rect to pixel boundaries x = (aLeft/aNumTwipPerPix)*aNumTwipPerPix; y = (aTop/aNumTwipPerPix)*aNumTwipPerPix; width = (aWidth/aNumTwipPerPix)*aNumTwipPerPix; height = (aHeight/aNumTwipPerPix)*aNumTwipPerPix; for(i=0;i<4;i++) { if( (aRadius[i]) > (aWidth>>1) ){ mRoundness[i] = (aWidth>>1); } else { mRoundness[i] = aRadius[i]; } if( mRoundness[i] > (aHeight>>1) ) mRoundness[i] = aHeight>>1; } // if we are drawing a circle mDoRound = PR_FALSE; if(aHeight==aWidth){ PRBool doRound = PR_TRUE; for(i=0;i<4;i++){ if(mRoundness[i]<(aWidth>>1)){ doRound = PR_FALSE; break; } } if(doRound){ mDoRound = PR_TRUE; for(i=0;i<4;i++){ mRoundness[i] = aWidth>>1; } } } // important coordinates that the path hits mLeft = x; mTop = y; mRight = x+width; mBottom = y+height; } /** --------------------------------------------------- * See documentation in nsCSSRendering.h * @update 4/13/99 dwc */ void RoundedRect::GetRoundedBorders(QBCurve &aULCurve,QBCurve &aURCurve,QBCurve &aLLCurve,QBCurve &aLRCurve) { PRInt16 adjust=0; if(mDoRound) adjust = mRoundness[0]>>3; // set the passed in curves to the rounded borders of the rectangle aULCurve.SetPoints( (float)mLeft,(float)mTop + mRoundness[0], (float)mLeft+adjust,(float)mTop+adjust, (float)mLeft+mRoundness[0],(float)mTop); aURCurve.SetPoints( (float)mRight - mRoundness[1],(float)mTop, (float)mRight-adjust,(float)mTop+adjust, (float)mRight,(float)mTop + mRoundness[1]); aLRCurve.SetPoints( (float)mRight,(float)mBottom - mRoundness[2], (float)mRight-adjust,(float)mBottom-adjust, (float)mRight - mRoundness[2],(float)mBottom); aLLCurve.SetPoints( (float)mLeft + mRoundness[3],(float)mBottom, (float)mLeft+adjust,(float)mBottom-adjust, (float)mLeft,(float)mBottom - mRoundness[3]); } /** --------------------------------------------------- * Given a qbezier path, convert it into a polygon path * @update 3/26/99 dwc * @param aPoints -- an array of points to use for the path * @param aPolyPath -- an array of points containing the flattened polygon to use * @param aCurIndex -- the index that points to the last element of the array * @param aPathType -- what kind of path that should be returned * @param aFrac -- the inset amount for a eCalc type path */ static void GetPath(nsFloatPoint aPoints[],nsPoint aPolyPath[],PRInt32 *aCurIndex,ePathTypes aPathType,PRInt32 &aC1Index,float aFrac) { QBCurve thecurve; switch (aPathType) { case eOutside: thecurve.SetPoints(aPoints[0].x,aPoints[0].y,aPoints[1].x,aPoints[1].y,aPoints[2].x,aPoints[2].y); thecurve.SubDivide(nsnull,aPolyPath,aCurIndex); aC1Index = *aCurIndex; aPolyPath[*aCurIndex].x = (nscoord)aPoints[3].x; aPolyPath[*aCurIndex].y = (nscoord)aPoints[3].y; (*aCurIndex)++; thecurve.SetPoints(aPoints[3].x,aPoints[3].y,aPoints[4].x,aPoints[4].y,aPoints[5].x,aPoints[5].y); thecurve.SubDivide(nsnull,aPolyPath,aCurIndex); break; case eInside: thecurve.SetPoints(aPoints[6].x,aPoints[6].y,aPoints[7].x,aPoints[7].y,aPoints[8].x,aPoints[8].y); thecurve.SubDivide(nsnull,aPolyPath,aCurIndex); aPolyPath[*aCurIndex].x = (nscoord)aPoints[9].x; aPolyPath[*aCurIndex].y = (nscoord)aPoints[9].y; (*aCurIndex)++; thecurve.SetPoints(aPoints[9].x,aPoints[9].y,aPoints[10].x,aPoints[10].y,aPoints[11].x,aPoints[11].y); thecurve.SubDivide(nsnull,aPolyPath,aCurIndex); break; case eCalc: thecurve.SetPoints( (aPoints[0].x+aPoints[11].x)/2.0f,(aPoints[0].y+aPoints[11].y)/2.0f, (aPoints[1].x+aPoints[10].x)/2.0f,(aPoints[1].y+aPoints[10].y)/2.0f, (aPoints[2].x+aPoints[9].x)/2.0f,(aPoints[2].y+aPoints[9].y)/2.0f); thecurve.SubDivide(nsnull,aPolyPath,aCurIndex); aPolyPath[*aCurIndex].x = (nscoord)((aPoints[3].x+aPoints[8].x)/2.0f); aPolyPath[*aCurIndex].y = (nscoord)((aPoints[3].y+aPoints[8].y)/2.0f); (*aCurIndex)++; thecurve.SetPoints( (aPoints[3].x+aPoints[8].x)/2.0f,(aPoints[3].y+aPoints[8].y)/2.0f, (aPoints[4].x+aPoints[7].x)/2.0f,(aPoints[4].y+aPoints[7].y)/2.0f, (aPoints[5].x+aPoints[6].x)/2.0f,(aPoints[5].y+aPoints[6].y)/2.0f); thecurve.SubDivide(nsnull,aPolyPath,aCurIndex); break; case eCalcRev: thecurve.SetPoints( (aPoints[5].x+aPoints[6].x)/2.0f,(aPoints[5].y+aPoints[6].y)/2.0f, (aPoints[4].x+aPoints[7].x)/2.0f,(aPoints[4].y+aPoints[7].y)/2.0f, (aPoints[3].x+aPoints[8].x)/2.0f,(aPoints[3].y+aPoints[8].y)/2.0f); thecurve.SubDivide(nsnull,aPolyPath,aCurIndex); aPolyPath[*aCurIndex].x = (nscoord)((aPoints[2].x+aPoints[9].x)/2.0f); aPolyPath[*aCurIndex].y = (nscoord)((aPoints[2].y+aPoints[9].y)/2.0f); (*aCurIndex)++; thecurve.SetPoints( (aPoints[2].x+aPoints[9].x)/2.0f,(aPoints[2].y+aPoints[9].y)/2.0f, (aPoints[1].x+aPoints[10].x)/2.0f,(aPoints[1].y+aPoints[10].y)/2.0f, (aPoints[0].x+aPoints[11].x)/2.0f,(aPoints[0].y+aPoints[11].y)/2.0f); thecurve.SubDivide(nsnull,aPolyPath,aCurIndex); break; } } /** --------------------------------------------------- * See documentation in nsCSSRendering.h * @update 4/13/99 dwc */ void QBCurve::SubDivide(nsIRenderingContext *aRenderingContext,nsPoint aPointArray[],PRInt32 *aCurIndex) { QBCurve curve1,curve2; float fx,fy,smag; // divide the curve into 2 pieces MidPointDivide(&curve1,&curve2); fx = (float)fabs(curve1.mAnc2.x - this->mCon.x); fy = (float)fabs(curve1.mAnc2.y - this->mCon.y); //smag = fx+fy-(PR_MIN(fx,fy)>>1); smag = fx*fx + fy*fy; if (smag>1){ // split the curve again curve1.SubDivide(aRenderingContext,aPointArray,aCurIndex); curve2.SubDivide(aRenderingContext,aPointArray,aCurIndex); }else{ if(aPointArray ) { // save the points for further processing aPointArray[*aCurIndex].x = (nscoord)curve1.mAnc2.x; aPointArray[*aCurIndex].y = (nscoord)curve1.mAnc2.y; (*aCurIndex)++; aPointArray[*aCurIndex].x = (nscoord)curve2.mAnc2.x; aPointArray[*aCurIndex].y = (nscoord)curve2.mAnc2.y; (*aCurIndex)++; }else{ // draw the curve nsTransform2D *aTransform; aRenderingContext->GetCurrentTransform(aTransform); aRenderingContext->DrawLine((nscoord)curve1.mAnc1.x,(nscoord)curve1.mAnc1.y,(nscoord)curve1.mAnc2.x,(nscoord)curve1.mAnc2.y); aRenderingContext->DrawLine((nscoord)curve1.mAnc2.x,(nscoord)curve1.mAnc2.y,(nscoord)curve2.mAnc2.x,(nscoord)curve2.mAnc2.y); } } } /** --------------------------------------------------- * See documentation in nsCSSRendering.h * @update 4/13/99 dwc */ void QBCurve::MidPointDivide(QBCurve *A,QBCurve *B) { float c1x,c1y,c2x,c2y; nsFloatPoint a1; c1x = (mAnc1.x+mCon.x)/2.0f; c1y = (mAnc1.y+mCon.y)/2.0f; c2x = (mAnc2.x+mCon.x)/2.0f; c2y = (mAnc2.y+mCon.y)/2.0f; a1.x = (c1x + c2x)/2.0f; a1.y = (c1y + c2y)/2.0f; // put the math into our 2 new curves A->mAnc1 = this->mAnc1; A->mCon.x = c1x; A->mCon.y = c1y; A->mAnc2 = a1; B->mAnc1 = a1; B->mCon.x = c2x; B->mCon.y = c2y; B->mAnc2 = this->mAnc2; } void FillOrInvertRect(nsIRenderingContext& aRC, nscoord aX, nscoord aY, nscoord aWidth, nscoord aHeight, PRBool aInvert) { if (aInvert) { aRC.InvertRect(aX, aY, aWidth, aHeight); } else { aRC.FillRect(aX, aY, aWidth, aHeight); } } void FillOrInvertRect(nsIRenderingContext& aRC, const nsRect& aRect, PRBool aInvert) { if (aInvert) { aRC.InvertRect(aRect); } else { aRC.FillRect(aRect); } } // Begin table border-collapsing section // These functions were written to not disrupt the normal ones and yet satisfy some additional requirements // At some point, all functions should be unified to include the additional functionality that these provide static nscoord RoundIntToPixel(nscoord aValue, nscoord aTwipsPerPixel, PRBool aRoundDown = PR_FALSE) { if (aTwipsPerPixel <= 0) // We must be rendering to a device that has a resolution greater than Twips! // In that case, aValue is as accurate as it's going to get. return aValue; nscoord halfPixel = NSToCoordRound(aTwipsPerPixel / 2.0f); nscoord extra = aValue % aTwipsPerPixel; nscoord finalValue = (!aRoundDown && (extra >= halfPixel)) ? aValue + (aTwipsPerPixel - extra) : aValue - extra; return finalValue; } static nscoord RoundFloatToPixel(float aValue, nscoord aTwipsPerPixel, PRBool aRoundDown = PR_FALSE) { return RoundIntToPixel(NSToCoordRound(aValue), aTwipsPerPixel, aRoundDown); } static void SetPoly(const nsRect& aRect, nsPoint* poly) { poly[0].x = aRect.x; poly[0].y = aRect.y; poly[1].x = aRect.x + aRect.width; poly[1].y = aRect.y; poly[2].x = aRect.x + aRect.width; poly[2].y = aRect.y + aRect.height; poly[3].x = aRect.x; poly[3].y = aRect.y + aRect.height; poly[4].x = aRect.x; poly[4].y = aRect.y; } static void DrawSolidBorderSegment(nsIRenderingContext& aContext, nsRect aRect, nscoord aTwipsPerPixel, PRUint8 aStartBevelSide = 0, nscoord aStartBevelOffset = 0, PRUint8 aEndBevelSide = 0, nscoord aEndBevelOffset = 0) { if ((aRect.width == aTwipsPerPixel) || (aRect.height == aTwipsPerPixel) || ((0 == aStartBevelOffset) && (0 == aEndBevelOffset))) { // simple line or rectangle if ((NS_SIDE_TOP == aStartBevelSide) || (NS_SIDE_BOTTOM == aStartBevelSide)) { if (1 == aRect.height) aContext.DrawLine(aRect.x, aRect.y, aRect.x, aRect.y + aRect.height); else aContext.FillRect(aRect); } else { if (1 == aRect.width) aContext.DrawLine(aRect.x, aRect.y, aRect.x + aRect.width, aRect.y); else aContext.FillRect(aRect); } } else { // polygon with beveling nsPoint poly[5]; SetPoly(aRect, poly); switch(aStartBevelSide) { case NS_SIDE_TOP: poly[0].x += aStartBevelOffset; poly[4].x = poly[0].x; break; case NS_SIDE_BOTTOM: poly[3].x += aStartBevelOffset; break; case NS_SIDE_RIGHT: poly[1].y += aStartBevelOffset; break; case NS_SIDE_LEFT: poly[0].y += aStartBevelOffset; poly[4].y = poly[0].y; } switch(aEndBevelSide) { case NS_SIDE_TOP: poly[1].x -= aEndBevelOffset; break; case NS_SIDE_BOTTOM: poly[2].x -= aEndBevelOffset; break; case NS_SIDE_RIGHT: poly[2].y -= aEndBevelOffset; break; case NS_SIDE_LEFT: poly[3].y -= aEndBevelOffset; } aContext.FillPolygon(poly, 5); } } static void GetDashInfo(nscoord aBorderLength, nscoord aDashLength, nscoord aTwipsPerPixel, PRInt32& aNumDashSpaces, nscoord& aStartDashLength, nscoord& aEndDashLength) { aNumDashSpaces = 0; if (aStartDashLength + aDashLength + aEndDashLength >= aBorderLength) { aStartDashLength = aBorderLength; aEndDashLength = 0; } else { aNumDashSpaces = aBorderLength / (2 * aDashLength); // round down nscoord extra = aBorderLength - aStartDashLength - aEndDashLength - (((2 * aNumDashSpaces) - 1) * aDashLength); if (extra > 0) { nscoord half = RoundIntToPixel(extra / 2, aTwipsPerPixel); aStartDashLength += half; aEndDashLength += (extra - half); } } } void nsCSSRendering::DrawTableBorderSegment(nsIRenderingContext& aContext, PRUint8 aBorderStyle, nscolor aBorderColor, const nsStyleBackground* aBGColor, const nsRect& aBorder, float aPixelsToTwips, PRUint8 aStartBevelSide, nscoord aStartBevelOffset, PRUint8 aEndBevelSide, nscoord aEndBevelOffset) { aContext.SetColor (aBorderColor); PRBool horizontal = ((NS_SIDE_TOP == aStartBevelSide) || (NS_SIDE_BOTTOM == aStartBevelSide)); nscoord twipsPerPixel = NSIntPixelsToTwips(1, aPixelsToTwips); PRBool ridgeGroove = NS_STYLE_BORDER_STYLE_RIDGE; if ((twipsPerPixel >= aBorder.width) || (twipsPerPixel >= aBorder.height) || (NS_STYLE_BORDER_STYLE_DASHED == aBorderStyle) || (NS_STYLE_BORDER_STYLE_DOTTED == aBorderStyle)) { // no beveling for 1 pixel border, dash or dot aStartBevelOffset = 0; aEndBevelOffset = 0; } switch (aBorderStyle) { case NS_STYLE_BORDER_STYLE_NONE: case NS_STYLE_BORDER_STYLE_HIDDEN: //NS_ASSERTION(PR_FALSE, "style of none or hidden"); break; case NS_STYLE_BORDER_STYLE_DOTTED: case NS_STYLE_BORDER_STYLE_DASHED: { nscoord dashLength = (NS_STYLE_BORDER_STYLE_DASHED == aBorderStyle) ? DASH_LENGTH : DOT_LENGTH; // make the dash length proportional to the border thickness dashLength *= (horizontal) ? aBorder.height : aBorder.width; // make the min dash length for the ends 1/2 the dash length nscoord minDashLength = (NS_STYLE_BORDER_STYLE_DASHED == aBorderStyle) ? RoundFloatToPixel(((float)dashLength) / 2.0f, twipsPerPixel) : dashLength; minDashLength = PR_MAX(minDashLength, twipsPerPixel); nscoord numDashSpaces = 0; nscoord startDashLength = minDashLength; nscoord endDashLength = minDashLength; if (horizontal) { GetDashInfo(aBorder.width, dashLength, twipsPerPixel, numDashSpaces, startDashLength, endDashLength); nsRect rect(aBorder.x, aBorder.y, startDashLength, aBorder.height); DrawSolidBorderSegment(aContext, rect, PR_TRUE); for (PRInt32 spaceX = 0; spaceX < numDashSpaces; spaceX++) { rect.x += rect.width + dashLength; rect.width = (spaceX == (numDashSpaces - 1)) ? endDashLength : dashLength; DrawSolidBorderSegment(aContext, rect, PR_TRUE); } } else { GetDashInfo(aBorder.height, dashLength, twipsPerPixel, numDashSpaces, startDashLength, endDashLength); nsRect rect(aBorder.x, aBorder.y, aBorder.width, startDashLength); DrawSolidBorderSegment(aContext, rect, PR_FALSE); for (PRInt32 spaceY = 0; spaceY < numDashSpaces; spaceY++) { rect.y += rect.height + dashLength; rect.height = (spaceY == (numDashSpaces - 1)) ? endDashLength : dashLength; DrawSolidBorderSegment(aContext, rect, PR_FALSE); } } } break; case NS_STYLE_BORDER_STYLE_GROOVE: ridgeGroove = NS_STYLE_BORDER_STYLE_GROOVE; // and fall through to ridge case NS_STYLE_BORDER_STYLE_RIDGE: if ((horizontal && (twipsPerPixel >= aBorder.height)) || (!horizontal && (twipsPerPixel >= aBorder.width))) { // a one pixel border DrawSolidBorderSegment(aContext, aBorder, twipsPerPixel, aStartBevelSide, aStartBevelOffset, aEndBevelSide, aEndBevelOffset); } else { nscoord startBevel = (aStartBevelOffset > 0) ? RoundFloatToPixel(0.5f * (float)aStartBevelOffset, twipsPerPixel, PR_TRUE) : 0; nscoord endBevel = (aEndBevelOffset > 0) ? RoundFloatToPixel(0.5f * (float)aEndBevelOffset, twipsPerPixel, PR_TRUE) : 0; PRUint8 ridgeGrooveSide = (horizontal) ? NS_SIDE_TOP : NS_SIDE_LEFT; aContext.SetColor ( MakeBevelColor (ridgeGrooveSide, ridgeGroove, aBGColor->mBackgroundColor, aBorderColor, PR_TRUE)); nsRect rect(aBorder); nscoord half; if (horizontal) { // top, bottom half = RoundFloatToPixel(0.5f * (float)aBorder.height, twipsPerPixel); rect.height = half; if (NS_SIDE_TOP == aStartBevelSide) { rect.x += startBevel; rect.width -= startBevel; } if (NS_SIDE_TOP == aEndBevelSide) { rect.width -= endBevel; } DrawSolidBorderSegment(aContext, rect, twipsPerPixel, aStartBevelSide, startBevel, aEndBevelSide, endBevel); } else { // left, right half = RoundFloatToPixel(0.5f * (float)aBorder.width, twipsPerPixel); rect.width = half; if (NS_SIDE_LEFT == aStartBevelSide) { rect.y += startBevel; rect.height -= startBevel; } if (NS_SIDE_LEFT == aEndBevelSide) { rect.height -= endBevel; } DrawSolidBorderSegment(aContext, rect, twipsPerPixel, aStartBevelSide, startBevel, aEndBevelSide, endBevel); } rect = aBorder; ridgeGrooveSide = (NS_SIDE_TOP == ridgeGrooveSide) ? NS_SIDE_BOTTOM : NS_SIDE_RIGHT; aContext.SetColor ( MakeBevelColor (ridgeGrooveSide, ridgeGroove, aBGColor->mBackgroundColor, aBorderColor, PR_TRUE)); if (horizontal) { rect.y = rect.y + half; rect.height = aBorder.height - half; if (NS_SIDE_BOTTOM == aStartBevelSide) { rect.x += startBevel; rect.width -= startBevel; } if (NS_SIDE_BOTTOM == aEndBevelSide) { rect.width -= endBevel; } DrawSolidBorderSegment(aContext, rect, twipsPerPixel, aStartBevelSide, startBevel, aEndBevelSide, endBevel); } else { rect.x = rect.x + half; rect.width = aBorder.width - half; if (NS_SIDE_RIGHT == aStartBevelSide) { rect.y += aStartBevelOffset - startBevel; rect.height -= startBevel; } if (NS_SIDE_RIGHT == aEndBevelSide) { rect.height -= endBevel; } DrawSolidBorderSegment(aContext, rect, twipsPerPixel, aStartBevelSide, startBevel, aEndBevelSide, endBevel); } } break; case NS_STYLE_BORDER_STYLE_DOUBLE: if ((aBorder.width > 2) && (aBorder.height > 2)) { nscoord startBevel = (aStartBevelOffset > 0) ? RoundFloatToPixel(0.333333f * (float)aStartBevelOffset, twipsPerPixel) : 0; nscoord endBevel = (aEndBevelOffset > 0) ? RoundFloatToPixel(0.333333f * (float)aEndBevelOffset, twipsPerPixel) : 0; if (horizontal) { // top, bottom nscoord thirdHeight = RoundFloatToPixel(0.333333f * (float)aBorder.height, twipsPerPixel); // draw the top line or rect nsRect topRect(aBorder.x, aBorder.y, aBorder.width, thirdHeight); if (NS_SIDE_TOP == aStartBevelSide) { topRect.x += aStartBevelOffset - startBevel; topRect.width -= aStartBevelOffset - startBevel; } if (NS_SIDE_TOP == aEndBevelSide) { topRect.width -= aEndBevelOffset - endBevel; } DrawSolidBorderSegment(aContext, topRect, twipsPerPixel, aStartBevelSide, startBevel, aEndBevelSide, endBevel); // draw the botom line or rect nscoord heightOffset = aBorder.height - thirdHeight; nsRect bottomRect(aBorder.x, aBorder.y + heightOffset, aBorder.width, aBorder.height - heightOffset); if (NS_SIDE_BOTTOM == aStartBevelSide) { bottomRect.x += aStartBevelOffset - startBevel; bottomRect.width -= aStartBevelOffset - startBevel; } if (NS_SIDE_BOTTOM == aEndBevelSide) { bottomRect.width -= aEndBevelOffset - endBevel; } DrawSolidBorderSegment(aContext, bottomRect, twipsPerPixel, aStartBevelSide, startBevel, aEndBevelSide, endBevel); } else { // left, right nscoord thirdWidth = RoundFloatToPixel(0.333333f * (float)aBorder.width, twipsPerPixel); nsRect leftRect(aBorder.x, aBorder.y, thirdWidth, aBorder.height); if (NS_SIDE_LEFT == aStartBevelSide) { leftRect.y += aStartBevelOffset - startBevel; leftRect.height -= aStartBevelOffset - startBevel; } if (NS_SIDE_LEFT == aEndBevelSide) { leftRect.height -= aEndBevelOffset - endBevel; } DrawSolidBorderSegment(aContext, leftRect, twipsPerPixel, aStartBevelSide, startBevel, aEndBevelSide, endBevel); nscoord widthOffset = aBorder.width - thirdWidth; nsRect rightRect(aBorder.x + widthOffset, aBorder.y, aBorder.width - widthOffset, aBorder.height); if (NS_SIDE_RIGHT == aStartBevelSide) { rightRect.y += aStartBevelOffset - startBevel; rightRect.height -= aStartBevelOffset - startBevel; } if (NS_SIDE_RIGHT == aEndBevelSide) { rightRect.height -= aEndBevelOffset - endBevel; } DrawSolidBorderSegment(aContext, rightRect, twipsPerPixel, aStartBevelSide, startBevel, aEndBevelSide, endBevel); } break; } // else fall through to solid case NS_STYLE_BORDER_STYLE_BG_SOLID: case NS_STYLE_BORDER_STYLE_SOLID: DrawSolidBorderSegment(aContext, aBorder, twipsPerPixel, aStartBevelSide, aStartBevelOffset, aEndBevelSide, aEndBevelOffset); break; case NS_STYLE_BORDER_STYLE_BG_OUTSET: case NS_STYLE_BORDER_STYLE_BG_INSET: case NS_STYLE_BORDER_STYLE_OUTSET: case NS_STYLE_BORDER_STYLE_INSET: NS_ASSERTION(PR_FALSE, "inset, outset should have been converted to groove, ridge"); break; case NS_STYLE_BORDER_STYLE_AUTO: NS_ASSERTION(PR_FALSE, "Unexpected 'auto' table border"); break; } } // End table border-collapsing section
37.583295
162
0.613571
CGCL-codes
dcc19d9965d66836aaf2949a938de1a5a15c19ca
215,503
cpp
C++
usdmayautils/AL/usdmaya/utils/DgNodeHelper.cpp
garvitverma/AL_USDMaya
5976020facdafce4783fc59aae73a773579f796b
[ "Apache-2.0" ]
275
2017-07-31T16:42:07.000Z
2022-01-27T09:27:45.000Z
usdmayautils/AL/usdmaya/utils/DgNodeHelper.cpp
garvitverma/AL_USDMaya
5976020facdafce4783fc59aae73a773579f796b
[ "Apache-2.0" ]
114
2017-08-01T07:37:35.000Z
2020-01-12T20:27:56.000Z
usdmayautils/AL/usdmaya/utils/DgNodeHelper.cpp
garvitverma/AL_USDMaya
5976020facdafce4783fc59aae73a773579f796b
[ "Apache-2.0" ]
87
2017-08-02T03:00:43.000Z
2021-09-13T02:09:19.000Z
// // Copyright 2017 Animal Logic // // 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 "AL/usd/utils/ALHalf.h" #include "AL/usd/utils/SIMD.h" #include "AL/usdmaya/utils/DgNodeHelper.h" #include "AL/maya/utils/NodeHelper.h" #include "maya/MDGModifier.h" #include "maya/MFloatArray.h" #include "maya/MFloatMatrix.h" #include "maya/MFnCompoundAttribute.h" #include "maya/MFnDoubleArrayData.h" #include "maya/MFnFloatArrayData.h" #include "maya/MFnMatrixData.h" #include "maya/MFnMatrixArrayData.h" #include "maya/MFnNumericAttribute.h" #include "maya/MFnNumericData.h" #include "maya/MFnTypedAttribute.h" #include "maya/MMatrix.h" #include "maya/MMatrixArray.h" namespace AL { namespace usdmaya { namespace utils { //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::setFloat(const MObject node, const MObject attr, float value) { const char* const errorString = "float error"; MPlug plug(node, attr); AL_MAYA_CHECK_ERROR(plug.setValue(value), errorString); return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::setAngle(const MObject node, const MObject attr, MAngle value) { const char* const errorString = "DgNodeHelper::setAngle"; MPlug plug(node, attr); AL_MAYA_CHECK_ERROR(plug.setValue(value), errorString); return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::setTime(const MObject node, const MObject attr, MTime value) { const char* const errorString = "DgNodeHelper::setTime"; MPlug plug(node, attr); AL_MAYA_CHECK_ERROR(plug.setValue(value), errorString); return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::setDistance(const MObject node, const MObject attr, MDistance value) { const char* const errorString = "DgNodeHelper::setDistance"; MPlug plug(node, attr); AL_MAYA_CHECK_ERROR(plug.setValue(value), errorString); return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::setDouble(MObject node, MObject attr, double value) { const char* const errorString = "double error"; MPlug plug(node, attr); AL_MAYA_CHECK_ERROR(plug.setValue(value), errorString); return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::setBool(MObject node, MObject attr, bool value) { const char* const errorString = "int error"; MPlug plug(node, attr); AL_MAYA_CHECK_ERROR(plug.setValue(value), errorString); return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::setInt8(MObject node, MObject attr, int8_t value) { const char* const errorString = "int error"; MPlug plug(node, attr); AL_MAYA_CHECK_ERROR(plug.setChar(value), errorString); return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::setInt16(MObject node, MObject attr, int16_t value) { const char* const errorString = "int error"; MPlug plug(node, attr); AL_MAYA_CHECK_ERROR(plug.setShort(value), errorString); return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::setInt32(MObject node, MObject attr, int32_t value) { const char* const errorString = "int error"; MPlug plug(node, attr); AL_MAYA_CHECK_ERROR(plug.setValue(value), errorString); return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::setInt64(MObject node, MObject attr, int64_t value) { const char* const errorString = "int64 error"; MPlug plug(node, attr); AL_MAYA_CHECK_ERROR(plug.setInt64(value), errorString); return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::setVec3(MObject node, MObject attr, float x, float y, float z) { const char* const errorString = "vec3f error"; MPlug plug(node, attr); AL_MAYA_CHECK_ERROR(plug.child(0).setValue(x), errorString); AL_MAYA_CHECK_ERROR(plug.child(1).setValue(y), errorString); AL_MAYA_CHECK_ERROR(plug.child(2).setValue(z), errorString); return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::setVec3(MObject node, MObject attr, double x, double y, double z) { const char* const errorString = "vec3d error"; MPlug plug(node, attr); AL_MAYA_CHECK_ERROR(plug.child(0).setValue(x), errorString); AL_MAYA_CHECK_ERROR(plug.child(1).setValue(y), errorString); AL_MAYA_CHECK_ERROR(plug.child(2).setValue(z), errorString); return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::setVec3(MObject node, MObject attr, MAngle x, MAngle y, MAngle z) { const char* const errorString = "vec3d error"; MPlug plug(node, attr); AL_MAYA_CHECK_ERROR(plug.child(0).setValue(x), errorString); AL_MAYA_CHECK_ERROR(plug.child(1).setValue(y), errorString); AL_MAYA_CHECK_ERROR(plug.child(2).setValue(z), errorString); return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::setBoolArray(MObject node, MObject attribute, const bool* const values, const size_t count) { MPlug plug(node, attribute); if(!plug || !plug.isArray()) return MS::kFailure; AL_MAYA_CHECK_ERROR(plug.setNumElements(count), "DgNodeHelper: attribute array could not be resized"); for(size_t i = 0; i != count; ++i) { plug.elementByLogicalIndex(i).setBool(values[i]); } return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::setBoolArray(const MObject& node, const MObject& attribute, const std::vector<bool>& values) { MPlug plug(node, attribute); if(!plug || !plug.isArray()) return MS::kFailure; AL_MAYA_CHECK_ERROR(plug.setNumElements(values.size()), "DgNodeHelper: attribute array could not be resized"); for(size_t i = 0, n = values.size(); i != n; ++i) { plug.elementByLogicalIndex(i).setBool(values[i]); } return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::setInt8Array(MObject node, MObject attribute, const int8_t* const values, const size_t count) { MPlug plug(node, attribute); if(!plug || !plug.isArray()) return MS::kFailure; AL_MAYA_CHECK_ERROR(plug.setNumElements(count), "DgNodeHelper: attribute array could not be resized"); for(size_t i = 0; i != count; ++i) { plug.elementByLogicalIndex(i).setChar(values[i]); } return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::setInt16Array(MObject node, MObject attribute, const int16_t* const values, const size_t count) { MPlug plug(node, attribute); if(!plug || !plug.isArray()) return MS::kFailure; AL_MAYA_CHECK_ERROR(plug.setNumElements(count), "DgNodeHelper: attribute array could not be resized"); for(size_t i = 0; i != count; ++i) { plug.elementByLogicalIndex(i).setShort(values[i]); } return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::setInt32Array(MObject node, MObject attribute, const int32_t* const values, const size_t count) { MPlug plug(node, attribute); if(!plug || !plug.isArray()) return MS::kFailure; AL_MAYA_CHECK_ERROR(plug.setNumElements(count), "DgNodeHelper: attribute array could not be resized"); for(size_t i = 0; i != count; ++i) { plug.elementByLogicalIndex(i).setValue(values[i]); } return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::setInt64Array(MObject node, MObject attribute, const int64_t* const values, const size_t count) { MPlug plug(node, attribute); if(!plug || !plug.isArray()) return MS::kFailure; AL_MAYA_CHECK_ERROR(plug.setNumElements(count), "DgNodeHelper: attribute array could not be resized"); for(size_t i = 0; i != count; ++i) { plug.elementByLogicalIndex(i).setInt64(values[i]); } return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::setHalfArray(MObject node, MObject attribute, const GfHalf* const values, const size_t count) { MPlug plug(node, attribute); if(!plug || !plug.isArray()) return MS::kFailure; AL_MAYA_CHECK_ERROR(plug.setNumElements(count), "DgNodeHelper: attribute array could not be resized"); size_t count8 = count & ~0x7ULL; for(size_t j = 0; j != count8; j += 8) { float f[8]; AL::usd::utils::half2float_8f(values + j, f); plug.elementByLogicalIndex(j + 0).setFloat(f[0]); plug.elementByLogicalIndex(j + 1).setFloat(f[1]); plug.elementByLogicalIndex(j + 2).setFloat(f[2]); plug.elementByLogicalIndex(j + 3).setFloat(f[3]); plug.elementByLogicalIndex(j + 4).setFloat(f[4]); plug.elementByLogicalIndex(j + 5).setFloat(f[5]); plug.elementByLogicalIndex(j + 6).setFloat(f[6]); plug.elementByLogicalIndex(j + 7).setFloat(f[7]); } if(count & 0x4) { float f[4]; AL::usd::utils::half2float_4f(values + count8, f); plug.elementByLogicalIndex(count8 + 0).setFloat(f[0]); plug.elementByLogicalIndex(count8 + 1).setFloat(f[1]); plug.elementByLogicalIndex(count8 + 2).setFloat(f[2]); plug.elementByLogicalIndex(count8 + 3).setFloat(f[3]); count8 |= 0x4; } switch(count & 0x3) { case 3: plug.elementByLogicalIndex(count8 + 2).setFloat(AL::usd::utils::half2float_1f(values[count8 + 2])); case 2: plug.elementByLogicalIndex(count8 + 1).setFloat(AL::usd::utils::half2float_1f(values[count8 + 1])); case 1: plug.elementByLogicalIndex(count8 + 0).setFloat(AL::usd::utils::half2float_1f(values[count8 + 0])); default: break; } return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::setFloatArray(MObject node, MObject attribute, const float* const values, const size_t count) { MPlug plug(node, attribute); if(!plug) { } else { if(!plug.isArray()) { MStatus status; MFnFloatArrayData fn; MFloatArray temp(values, count); MObject obj = fn.create(temp, &status); if(status) { plug.setValue(obj); return MS::kSuccess; } } else { AL_MAYA_CHECK_ERROR(plug.setNumElements(count), "DgNodeHelper: attribute array could not be resized"); for(size_t i = 0; i != count; ++i) { plug.elementByLogicalIndex(i).setFloat(values[i]); } } return MS::kSuccess; } return MS::kFailure; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::setDoubleArray(MObject node, MObject attribute, const double* const values, const size_t count) { MPlug plug(node, attribute); if(!plug) { } else { if(!plug.isArray()) { MStatus status; MFnDoubleArrayData fn; MDoubleArray temp(values, count); MObject obj = fn.create(temp, &status); if(status) { plug.setValue(obj); return MS::kSuccess; } } else { AL_MAYA_CHECK_ERROR(plug.setNumElements(count), "DgNodeHelper: attribute array could not be resized"); for(size_t i = 0; i != count; ++i) { plug.elementByLogicalIndex(i).setDouble(values[i]); } } return MS::kSuccess; } return MS::kFailure; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::setVec2Array(MObject node, MObject attribute, const int32_t* const values, const size_t count) { MPlug plug(node, attribute); if(!plug || !plug.isArray()) return MS::kFailure; AL_MAYA_CHECK_ERROR(plug.setNumElements(count), "DgNodeHelper: attribute array could not be resized"); for(size_t i = 0, j = 0; i != count; ++i, j += 2) { auto v = plug.elementByLogicalIndex(i); v.child(0).setInt(values[j]); v.child(1).setInt(values[j + 1]); } return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::setVec2Array(MObject node, MObject attribute, const GfHalf* const values, const size_t count) { MPlug plug(node, attribute); if(!plug || !plug.isArray()) return MS::kFailure; AL_MAYA_CHECK_ERROR(plug.setNumElements(count), "DgNodeHelper: attribute array could not be resized"); size_t count4 = count & ~0x3ULL; for(size_t i = 0, j = 0; i != count4; i += 4, j += 8) { float f[8]; AL::usd::utils::half2float_8f(values + j, f); auto v0 = plug.elementByLogicalIndex(i + 0); auto v1 = plug.elementByLogicalIndex(i + 1); auto v2 = plug.elementByLogicalIndex(i + 2); auto v3 = plug.elementByLogicalIndex(i + 3); v0.child(0).setFloat(f[0]); v0.child(1).setFloat(f[1]); v1.child(0).setFloat(f[2]); v1.child(1).setFloat(f[3]); v2.child(0).setFloat(f[4]); v2.child(1).setFloat(f[5]); v3.child(0).setFloat(f[6]); v3.child(1).setFloat(f[7]); } if(count & 0x2) { float f[4]; AL::usd::utils::half2float_4f(values + count4 * 2, f); auto v0 = plug.elementByLogicalIndex(count4 + 0); auto v1 = plug.elementByLogicalIndex(count4 + 1); v0.child(0).setFloat(f[0]); v0.child(1).setFloat(f[1]); v1.child(0).setFloat(f[2]); v1.child(1).setFloat(f[3]); count4 += 2; } if(count & 0x1) { auto v0 = plug.elementByLogicalIndex(count4); v0.child(0).setFloat(AL::usd::utils::half2float_1f(values[count4 * 2])); v0.child(1).setFloat(AL::usd::utils::half2float_1f(values[count4 * 2 + 1])); } return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::setVec2Array(MObject node, MObject attribute, const float* const values, const size_t count) { MPlug plug(node, attribute); if(!plug || !plug.isArray()) return MS::kFailure; AL_MAYA_CHECK_ERROR(plug.setNumElements(count), "DgNodeHelper: attribute array could not be resized"); for(size_t i = 0, j = 0; i != count; ++i, j += 2) { auto v = plug.elementByLogicalIndex(i); v.child(0).setFloat(values[j]); v.child(1).setFloat(values[j + 1]); } return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::setVec2Array(MObject node, MObject attribute, const double* const values, const size_t count) { MPlug plug(node, attribute); if(!plug || !plug.isArray()) return MS::kFailure; AL_MAYA_CHECK_ERROR(plug.setNumElements(count), "DgNodeHelper: attribute array could not be resized"); for(size_t i = 0, j = 0; i != count; ++i, j += 2) { auto v = plug.elementByLogicalIndex(i); v.child(0).setDouble(values[j]); v.child(1).setDouble(values[j + 1]); } return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::setVec3Array(MObject node, MObject attribute, const int32_t* const values, const size_t count) { MPlug plug(node, attribute); if(!plug || !plug.isArray()) return MS::kFailure; AL_MAYA_CHECK_ERROR(plug.setNumElements(count), "DgNodeHelper: attribute array could not be resized"); for(size_t i = 0, j = 0; i != count; ++i, j += 3) { auto v = plug.elementByLogicalIndex(i); v.child(0).setInt(values[j]); v.child(1).setInt(values[j + 1]); v.child(2).setInt(values[j + 2]); } return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::setVec3Array(MObject node, MObject attribute, const GfHalf* const values, const size_t count) { MPlug plug(node, attribute); if(!plug || !plug.isArray()) return MS::kFailure; AL_MAYA_CHECK_ERROR(plug.setNumElements(count), "DgNodeHelper: attribute array could not be resized"); size_t count8 = count & ~0x7ULL; for(size_t i = 0, j = 0; i != count8; i += 8, j += 24) { float f[24]; AL::usd::utils::half2float_8f(values + j, f); AL::usd::utils::half2float_8f(values + j + 8, f + 8); AL::usd::utils::half2float_8f(values + j + 16, f + 16); for(int k = 0; k < 8; ++k) { auto v = plug.elementByLogicalIndex(i + k); v.child(0).setFloat(f[k * 3 + 0]); v.child(1).setFloat(f[k * 3 + 1]); v.child(2).setFloat(f[k * 3 + 2]); } } for(size_t i = count8, j = count8 * 3; i != count; ++i, j += 3) { float f[4]; GfHalf h[4]; h[0] = values[j]; h[1] = values[j + 1]; h[2] = values[j + 2]; AL::usd::utils::half2float_4f(h, f); auto v = plug.elementByLogicalIndex(i); v.child(0).setFloat(f[0]); v.child(1).setFloat(f[1]); v.child(2).setFloat(f[2]); } return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::setVec3Array(MObject node, MObject attribute, const float* const values, const size_t count) { MPlug plug(node, attribute); if(!plug || !plug.isArray()) return MS::kFailure; AL_MAYA_CHECK_ERROR(plug.setNumElements(count), "DgNodeHelper: attribute array could not be resized"); for(size_t i = 0, j = 0; i != count; ++i, j += 3) { auto v = plug.elementByLogicalIndex(i); v.child(0).setFloat(values[j]); v.child(1).setFloat(values[j + 1]); v.child(2).setFloat(values[j + 2]); } return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::setVec3Array(MObject node, MObject attribute, const double* const values, const size_t count) { MPlug plug(node, attribute); if(!plug || !plug.isArray()) return MS::kFailure; AL_MAYA_CHECK_ERROR(plug.setNumElements(count), "DgNodeHelper: attribute array could not be resized"); for(size_t i = 0, j = 0; i != count; ++i, j += 3) { auto v = plug.elementByLogicalIndex(i); v.child(0).setDouble(values[j]); v.child(1).setDouble(values[j + 1]); v.child(2).setDouble(values[j + 2]); } return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::setVec4Array(MObject node, MObject attribute, const GfHalf* const values, const size_t count) { MPlug plug(node, attribute); if(!plug || !plug.isArray()) { return MS::kFailure; } AL_MAYA_CHECK_ERROR(plug.setNumElements(count), "DgNodeHelper: attribute array could not be resized"); size_t count2 = count & ~0x1ULL; for(size_t i = 0, j = 0; i != count2; i += 2, j += 8) { float f[8]; AL::usd::utils::half2float_8f(values + j, f); auto v0 = plug.elementByLogicalIndex(i); auto v1 = plug.elementByLogicalIndex(i + 1); v0.child(0).setFloat(f[0]); v0.child(1).setFloat(f[1]); v0.child(2).setFloat(f[2]); v0.child(3).setFloat(f[3]); v1.child(0).setFloat(f[4]); v1.child(1).setFloat(f[5]); v1.child(2).setFloat(f[6]); v1.child(3).setFloat(f[7]); } if(count & 0x1) { float f[4]; AL::usd::utils::half2float_4f(values + count2 * 4, f); auto v0 = plug.elementByLogicalIndex(count2); v0.child(0).setFloat(f[0]); v0.child(1).setFloat(f[1]); v0.child(2).setFloat(f[2]); v0.child(3).setFloat(f[3]); } return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::setVec4Array(MObject node, MObject attribute, const int* const values, const size_t count) { MPlug plug(node, attribute); if(!plug || !plug.isArray()) return MS::kFailure; AL_MAYA_CHECK_ERROR(plug.setNumElements(count), "DgNodeHelper: attribute array could not be resized"); for(size_t i = 0, j = 0; i != count; ++i, j += 4) { auto v = plug.elementByLogicalIndex(i); v.child(0).setInt(values[j]); v.child(1).setInt(values[j + 1]); v.child(2).setInt(values[j + 2]); v.child(3).setInt(values[j + 3]); } return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::setVec4Array(MObject node, MObject attribute, const float* const values, const size_t count) { MPlug plug(node, attribute); if(!plug || !plug.isArray()) return MS::kFailure; AL_MAYA_CHECK_ERROR(plug.setNumElements(count), "DgNodeHelper: attribute array could not be resized"); for(size_t i = 0, j = 0; i != count; ++i, j += 4) { auto v = plug.elementByLogicalIndex(i); v.child(0).setFloat(values[j]); v.child(1).setFloat(values[j + 1]); v.child(2).setFloat(values[j + 2]); v.child(3).setFloat(values[j + 3]); } return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::setVec4Array(MObject node, MObject attribute, const double* const values, const size_t count) { MPlug plug(node, attribute); if(!plug || !plug.isArray()) return MS::kFailure; AL_MAYA_CHECK_ERROR(plug.setNumElements(count), "DgNodeHelper: attribute array could not be resized"); for(size_t i = 0, j = 0; i != count; ++i, j += 4) { auto v = plug.elementByLogicalIndex(i); v.child(0).setDouble(values[j]); v.child(1).setDouble(values[j + 1]); v.child(2).setDouble(values[j + 2]); v.child(3).setDouble(values[j + 3]); } return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::setMatrix4x4Array(MObject node, MObject attribute, const double* const values, const size_t count) { MPlug plug(node, attribute); if(!plug) return MS::kFailure; if(!plug.isArray()) { MStatus status; MMatrixArray arrayData; arrayData.setLength(count); memcpy(&arrayData[0], values, sizeof(MMatrix) * count); MFnMatrixArrayData fn; MObject data = fn.create(arrayData, &status); AL_MAYA_CHECK_ERROR2(status, MString("Count not set array value")); status = plug.setValue(data); AL_MAYA_CHECK_ERROR2(status, MString("Count not set array value")); } else { // Yes this is horrible. It would appear that as of Maya 2017, setting the contents of matrix array attributes doesn't work. // Well, at least for dynamic attributes. Using an array builder inside a compute method would be one way char tempStr[1024] = {0}; for(uint32_t i = 0; i < 16 * count; i += 16) { sprintf(tempStr, "setAttr \"%s[%d]\" -type \"matrix\" %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf %lf;", plug.name().asChar(), (i >> 4), values[i + 0], values[i + 1], values[i + 2], values[i + 3], values[i + 4], values[i + 5], values[i + 6], values[i + 7], values[i + 8], values[i + 9], values[i + 10], values[i + 11], values[i + 12], values[i + 13], values[i + 14], values[i + 15] ); MGlobal::executeCommand(tempStr); } } return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::setMatrix4x4Array(MObject node, MObject attribute, const float* const values, const size_t count) { MPlug plug(node, attribute); if(!plug) return MS::kFailure; if(!plug.isArray()) { MStatus status; MMatrixArray arrayData; arrayData.setLength(count); double* ptr = &arrayData[0].matrix[0][0]; for(size_t i = 0, j = 0; i != count; ++i, j += 16) { double* const dptr = ptr + j; const float* const fptr = values + j; #if AL_UTILS_ENABLE_SIMD # if __AVX__ const f256 d0 = loadu8f(fptr); const f256 d1 = loadu8f(fptr + 8); storeu4d(dptr , cvt4f_to_4d(extract4f(d0, 0))); storeu4d(dptr + 4, cvt4f_to_4d(extract4f(d0, 1))); storeu4d(dptr + 8, cvt4f_to_4d(extract4f(d1, 0))); storeu4d(dptr + 12, cvt4f_to_4d(extract4f(d1, 1))); # else const f128 d0 = loadu4f(fptr); const f128 d1 = loadu4f(fptr + 4); const f128 d2 = loadu4f(fptr + 8); const f128 d3 = loadu4f(fptr + 12); storeu2d(dptr , cvt2f_to_2d(d0)); storeu2d(dptr + 2, cvt2f_to_2d(movehl4f(d0, d0))); storeu2d(dptr + 4, cvt2f_to_2d(d1)); storeu2d(dptr + 6, cvt2f_to_2d(movehl4f(d1, d1))); storeu2d(dptr + 8, cvt2f_to_2d(d2)); storeu2d(dptr + 10, cvt2f_to_2d(movehl4f(d2, d2))); storeu2d(dptr + 12, cvt2f_to_2d(d3)); storeu2d(dptr + 14, cvt2f_to_2d(movehl4f(d3, d3))); # endif #else for(int k = 0; k < 16; ++k) { dptr[k] = fptr[k]; } #endif } MFnMatrixArrayData fn; MObject data = fn.create(arrayData, &status); AL_MAYA_CHECK_ERROR2(status, MString("Count not set array value")); status = plug.setValue(data); AL_MAYA_CHECK_ERROR2(status, MString("Count not set array value")); } else { // I can't seem to create a multi of arrays within the Maya API (without using an array data builder within a compute). char tempStr[2048] = {0}; for(uint32_t i = 0; i < 16 * count; i += 16) { sprintf(tempStr, "setAttr \"%s[%d]\" -type \"matrix\" %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f %f;", plug.name().asChar(), (i >> 4), values[i + 0], values[i + 1], values[i + 2], values[i + 3], values[i + 4], values[i + 5], values[i + 6], values[i + 7], values[i + 8], values[i + 9], values[i + 10], values[i + 11], values[i + 12], values[i + 13], values[i + 14], values[i + 15] ); MGlobal::executeCommand(tempStr); } } return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::setTimeArray(MObject node, MObject attribute, const float* const values, const size_t count, MTime::Unit unit) { // determine how much we need to modify the const MTime mod(1.0, unit); const float unitConversion = float(mod.as(MTime::k6000FPS)); MPlug plug(node, attribute); if(!plug || !plug.isArray()) return MS::kFailure; AL_MAYA_CHECK_ERROR(plug.setNumElements(count), "DgNodeHelper: attribute array could not be resized"); #if AL_UTILS_ENABLE_SIMD const f128 unitConversion128 = splat4f(unitConversion); const size_t count4 = count & ~3ULL; size_t i = 0; for(; i < count4; i += 4) { MPlug v0 = plug.elementByLogicalIndex(i); MPlug v1 = plug.elementByLogicalIndex(i + 1); MPlug v2 = plug.elementByLogicalIndex(i + 2); MPlug v3 = plug.elementByLogicalIndex(i + 3); const f128 temp = mul4f(unitConversion128, loadu4f(values + i)); ALIGN16(float tempf[4]); store4f(tempf, temp); v0.setFloat(tempf[0]); v1.setFloat(tempf[1]); v2.setFloat(tempf[2]); v3.setFloat(tempf[3]); } switch(count & 3) { case 3: plug.elementByLogicalIndex(i + 2).setFloat(unitConversion * values[i + 2]); case 2: plug.elementByLogicalIndex(i + 1).setFloat(unitConversion * values[i + 1]); case 1: plug.elementByLogicalIndex(i ).setFloat(unitConversion * values[i ]); default: break; } #else for(size_t i = 0; i < count; ++i) { plug.elementByLogicalIndex(i).setFloat(unitConversion * values[i]); } #endif return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::setAngleArray(MObject node, MObject attribute, const float* const values, const size_t count, MAngle::Unit unit) { // determine how much we need to modify the const MAngle mod(1.0, unit); const float unitConversion = float(mod.as(MAngle::internalUnit())); MPlug plug(node, attribute); if(!plug || !plug.isArray()) return MS::kFailure; AL_MAYA_CHECK_ERROR(plug.setNumElements(count), "DgNodeHelper: attribute array could not be resized"); #if AL_UTILS_ENABLE_SIMD const f128 unitConversion128 = splat4f(unitConversion); const size_t count4 = count & ~3ULL; size_t i = 0; for(; i < count4; i += 4) { MPlug v0 = plug.elementByLogicalIndex(i); MPlug v1 = plug.elementByLogicalIndex(i + 1); MPlug v2 = plug.elementByLogicalIndex(i + 2); MPlug v3 = plug.elementByLogicalIndex(i + 3); const f128 temp = mul4f(unitConversion128, loadu4f(values + i)); ALIGN16(float tempf[4]); store4f(tempf, temp); v0.setFloat(tempf[0]); v1.setFloat(tempf[1]); v2.setFloat(tempf[2]); v3.setFloat(tempf[3]); } switch(count & 3) { case 3: plug.elementByLogicalIndex(i + 2).setFloat(unitConversion * values[i + 2]); case 2: plug.elementByLogicalIndex(i + 1).setFloat(unitConversion * values[i + 1]); case 1: plug.elementByLogicalIndex(i ).setFloat(unitConversion * values[i]); default: break; } #else for(size_t i = 0; i < count; ++i) { plug.elementByLogicalIndex(i).setFloat(unitConversion * values[i]); } #endif return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::setDistanceArray(MObject node, MObject attribute, const float* const values, const size_t count, MDistance::Unit unit) { // determine how much we need to modify the const MDistance mod(1.0, unit); const float unitConversion = float(mod.as(MDistance::internalUnit())); MPlug plug(node, attribute); if(!plug || !plug.isArray()) return MS::kFailure; AL_MAYA_CHECK_ERROR(plug.setNumElements(count), "DgNodeHelper: attribute array could not be resized"); #if AL_UTILS_ENABLE_SIMD const f128 unitConversion128 = splat4f(unitConversion); const size_t count4 = count & ~3ULL; size_t i = 0; for(; i < count4; i += 4) { MPlug v0 = plug.elementByLogicalIndex(i); MPlug v1 = plug.elementByLogicalIndex(i + 1); MPlug v2 = plug.elementByLogicalIndex(i + 2); MPlug v3 = plug.elementByLogicalIndex(i + 3); const f128 temp = mul4f(unitConversion128, loadu4f(values + i)); ALIGN16(float tempf[4]); store4f(tempf, temp); v0.setFloat(tempf[0]); v1.setFloat(tempf[1]); v2.setFloat(tempf[2]); v3.setFloat(tempf[3]); } switch(count & 0x3) { case 3: plug.elementByLogicalIndex(i + 2).setFloat(unitConversion * values[i + 2]); case 2: plug.elementByLogicalIndex(i + 1).setFloat(unitConversion * values[i + 1]); case 1: plug.elementByLogicalIndex(i ).setFloat(unitConversion * values[i]); default: break; } #else for(size_t i = 0; i < count; ++i) { plug.elementByLogicalIndex(i).setFloat(unitConversion * values[i]); } #endif return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::setUsdBoolArray(const MObject& node, const MObject& attribute, const VtArray<bool>& values) { MPlug plug(node, attribute); if(!plug || !plug.isArray()) return MS::kFailure; AL_MAYA_CHECK_ERROR(plug.setNumElements(values.size()), "DgNodeTranslator: attribute array could not be resized"); for(size_t i = 0, n = values.size(); i != n; ++i) { plug.elementByLogicalIndex(i).setBool(values[i]); } return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::setAngleAnim(MObject node, MObject attr, const UsdGeomXformOp op) { MStatus status; const char* const errorString = "DgNodeHelper::setAngleAnim"; MPlug plug(node, attr); MFnAnimCurve fnCurve; fnCurve.create(plug, NULL, &status); AL_MAYA_CHECK_ERROR(status, errorString); std::vector<double> times; op.GetTimeSamples(&times); const float conversionFactor = 0.0174533f; float value = 0; for(auto const& timeValue: times) { const bool retValue = op.GetAs<float>(&value, timeValue); if (!retValue) continue; MTime tm(timeValue, MTime::kFilm); switch (fnCurve.animCurveType()) { case MFnAnimCurve::kAnimCurveTL: case MFnAnimCurve::kAnimCurveTA: case MFnAnimCurve::kAnimCurveTU: { fnCurve.addKey(tm, value * conversionFactor, MFnAnimCurve::kTangentGlobal, MFnAnimCurve::kTangentGlobal, NULL, &status); AL_MAYA_CHECK_ERROR(status, errorString); break; } default: { std::cout << "[DgNodeHelper::setAngleAnim] Unexpected anim curve type: " << fnCurve.animCurveType() << std::endl; break; } } } return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::setFloatAttrAnim(const MObject node, const MObject attr, UsdAttribute usdAttr, double conversionFactor) { if (!usdAttr.GetNumTimeSamples()) { return MS::kFailure; } const char* const errorString = "DgNodeTranslator::setFloatAttrAnim"; MStatus status; MPlug plug(node, attr); MPlug srcPlug; MFnAnimCurve fnCurve; MDGModifier dgmod; srcPlug = plug.source(&status); AL_MAYA_CHECK_ERROR(status, errorString); if(!srcPlug.isNull()) { std::cout << "[DgNodeTranslator::setFloatAttrAnim] disconnecting curve! = " << srcPlug.name().asChar() << std::endl; dgmod.disconnect(srcPlug, plug); dgmod.doIt(); } fnCurve.create(plug, NULL, &status); AL_MAYA_CHECK_ERROR(status, errorString); std::vector<double> times; usdAttr.GetTimeSamples(&times); float value; for(auto const& timeValue: times) { const bool retValue = usdAttr.Get(&value, timeValue); if(!retValue) continue; MTime tm(timeValue, MTime::kFilm); switch(fnCurve.animCurveType()) { case MFnAnimCurve::kAnimCurveTL: case MFnAnimCurve::kAnimCurveTA: case MFnAnimCurve::kAnimCurveTU: { fnCurve.addKey(tm, value * conversionFactor, MFnAnimCurve::kTangentGlobal, MFnAnimCurve::kTangentGlobal, NULL, &status); AL_MAYA_CHECK_ERROR(status, errorString); break; } default: { std::cout << "[DgNodeTranslator::setFloatAttrAnim] OTHER ANIM CURVE TYPE! = " << fnCurve.animCurveType() << std::endl; break; } } } return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::setVisAttrAnim(const MObject node, const MObject attr, const UsdAttribute &usdAttr) { if (!usdAttr.GetNumTimeSamples()) { return MS::kFailure; } const char* const errorString = "DgNodeTranslator::setVisAttrAnim"; MStatus status; MPlug plug(node, attr); MPlug srcPlug; MFnAnimCurve fnCurve; MDGModifier dgmod; srcPlug = plug.source(&status); AL_MAYA_CHECK_ERROR(status, errorString); if(!srcPlug.isNull()) { std::cout << "[DgNodeTranslator::setVisAttrAnim] disconnecting curve! = " << srcPlug.name().asChar() << std::endl; dgmod.disconnect(srcPlug, plug); dgmod.doIt(); } fnCurve.create(plug, NULL, &status); AL_MAYA_CHECK_ERROR(status, errorString); std::vector<double> times; usdAttr.GetTimeSamples(&times); TfToken value; for(auto const& timeValue: times) { const bool retValue = usdAttr.Get<TfToken>(&value, timeValue); if(!retValue) continue; MTime tm(timeValue, MTime::kFilm); fnCurve.addKey(tm, (value == UsdGeomTokens->invisible) ? 0 : 1, MFnAnimCurve::kTangentGlobal, MFnAnimCurve::kTangentGlobal, NULL, &status); AL_MAYA_CHECK_ERROR(status, errorString); } return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::getBoolArray(const MObject& node, const MObject& attr, std::vector<bool>& values) { // // Handle the oddity that is std::vector<bool> // MPlug plug(node, attr); if(!plug || !plug.isArray()) return MS::kFailure; uint32_t num = plug.numElements(); values.resize(num); for(uint32_t i = 0; i < num; ++i) { values[i] = plug.elementByLogicalIndex(i).asBool(); } return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::getBoolArray(MObject node, MObject attribute, bool* const values, const size_t count) { MPlug plug(node, attribute); if(!plug || !plug.isArray()) return MS::kFailure; uint32_t num = plug.numElements(); if(num != count) { MGlobal::displayError("array is sized incorrectly"); return MS::kFailure; } #if AL_UTILS_ENABLE_SIMD uint32_t count16 = count & ~0xF; for(uint32_t i = 0; i < count16; i += 16) { ALIGN16(bool temp[16]); temp[0] = plug.elementByLogicalIndex(i).asBool(); temp[1] = plug.elementByLogicalIndex(i + 1).asBool(); temp[2] = plug.elementByLogicalIndex(i + 2).asBool(); temp[3] = plug.elementByLogicalIndex(i + 3).asBool(); temp[4] = plug.elementByLogicalIndex(i + 4).asBool(); temp[5] = plug.elementByLogicalIndex(i + 5).asBool(); temp[6] = plug.elementByLogicalIndex(i + 6).asBool(); temp[7] = plug.elementByLogicalIndex(i + 7).asBool(); temp[8] = plug.elementByLogicalIndex(i + 8).asBool(); temp[9] = plug.elementByLogicalIndex(i + 9).asBool(); temp[10] = plug.elementByLogicalIndex(i + 10).asBool(); temp[11] = plug.elementByLogicalIndex(i + 11).asBool(); temp[12] = plug.elementByLogicalIndex(i + 12).asBool(); temp[13] = plug.elementByLogicalIndex(i + 13).asBool(); temp[14] = plug.elementByLogicalIndex(i + 14).asBool(); temp[15] = plug.elementByLogicalIndex(i + 15).asBool(); storeu4i(values + i, load4i(temp)); } for(uint32_t i = count16; i < num; ++i) { values[i] = plug.elementByLogicalIndex(i).asBool(); } #else for(uint32_t i = 0; i < num; ++i) { values[i] = plug.elementByLogicalIndex(i).asBool(); } #endif return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::getInt64Array(MObject node, MObject attribute, int64_t* const values, const size_t count) { MPlug plug(node, attribute); if(!plug || !plug.isArray()) return MS::kFailure; uint32_t num = plug.numElements(); if(num != count) { MGlobal::displayError(plug.name() + ", error array is sized incorrectly"); return MS::kFailure; } #if AL_UTILS_ENABLE_SIMD #ifdef __AVX__ uint32_t count4 = count & ~0x3; uint32_t i = 0; for(; i < count4; i += 4) { ALIGN32(int64_t temp[4]); temp[0] = plug.elementByLogicalIndex(i).asInt64(); temp[1] = plug.elementByLogicalIndex(i + 1).asInt64(); temp[2] = plug.elementByLogicalIndex(i + 2).asInt64(); temp[3] = plug.elementByLogicalIndex(i + 3).asInt64(); storeu8i(values + i, load8i(temp)); } if(count & 0x2) { ALIGN16(int64_t temp[2]); temp[0] = plug.elementByLogicalIndex(i).asInt64(); temp[1] = plug.elementByLogicalIndex(i + 1).asInt64(); storeu4i(values + i, load4i(temp)); i += 2; } #else uint32_t count2 = count & ~0x1; uint32_t i = 0; for(; i < count2; i += 2) { ALIGN16(int64_t temp[2]); temp[0] = plug.elementByLogicalIndex(i).asInt64(); temp[1] = plug.elementByLogicalIndex(i + 1).asInt64(); storeu4i(values + i, load4i(temp)); } #endif if(count & 1) { values[i] = plug.elementByLogicalIndex(i).asInt64(); } #else for(uint32_t i = 0; i < num; ++i) { values[i] = plug.elementByLogicalIndex(i).asInt64(); } #endif return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::getInt32Array(MObject node, MObject attribute, int32_t* const values, const size_t count) { MPlug plug(node, attribute); if(!plug || !plug.isArray()) return MS::kFailure; uint32_t num = plug.numElements(); if(num != count) { MGlobal::displayError("array is sized incorrectly"); return MS::kFailure; } #if AL_UTILS_ENABLE_SIMD #ifdef __AVX__ uint32_t count8 = count & ~0x7; uint32_t i = 0; for(; i < count8; i += 8) { ALIGN32(int32_t temp[8]); temp[0] = plug.elementByLogicalIndex(i).asInt(); temp[1] = plug.elementByLogicalIndex(i + 1).asInt(); temp[2] = plug.elementByLogicalIndex(i + 2).asInt(); temp[3] = plug.elementByLogicalIndex(i + 3).asInt(); temp[4] = plug.elementByLogicalIndex(i + 4).asInt(); temp[5] = plug.elementByLogicalIndex(i + 5).asInt(); temp[6] = plug.elementByLogicalIndex(i + 6).asInt(); temp[7] = plug.elementByLogicalIndex(i + 7).asInt(); storeu8i(values + i, load8i(temp)); } if(count & 0x4) { ALIGN16(int32_t temp[4]); temp[0] = plug.elementByLogicalIndex(i).asInt(); temp[1] = plug.elementByLogicalIndex(i + 1).asInt(); temp[2] = plug.elementByLogicalIndex(i + 2).asInt(); temp[3] = plug.elementByLogicalIndex(i + 3).asInt(); storeu4i(values + i, load4i(temp)); i += 4; } #else uint32_t count4 = count & ~0x3; uint32_t i = 0; for(; i < count4; i += 4) { ALIGN16(int32_t temp[4]); temp[0] = plug.elementByLogicalIndex(i).asInt(); temp[1] = plug.elementByLogicalIndex(i + 1).asInt(); temp[2] = plug.elementByLogicalIndex(i + 2).asInt(); temp[3] = plug.elementByLogicalIndex(i + 3).asInt(); storeu4i(values + i, load4i(temp)); } #endif switch(count & 3) { case 3: values[i + 2] = plug.elementByLogicalIndex(i + 2).asInt(); case 2: values[i + 1] = plug.elementByLogicalIndex(i + 1).asInt(); case 1: values[i] = plug.elementByLogicalIndex(i).asInt(); default: break; } #else for(uint32_t i = 0; i < num; ++i) { values[i] = plug.elementByLogicalIndex(i).asInt(); } #endif return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::getInt8Array(MObject node, MObject attribute, int8_t* const values, const size_t count) { MPlug plug(node, attribute); if(!plug || !plug.isArray()) return MS::kFailure; uint32_t num = plug.numElements(); if(num != count) { MGlobal::displayError("array is sized incorrectly"); return MS::kFailure; } for(uint32_t i = 0; i < num; ++i) { values[i] = plug.elementByLogicalIndex(i).asChar(); } return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::getInt16Array(MObject node, MObject attribute, int16_t* const values, const size_t count) { MPlug plug(node, attribute); if(!plug || !plug.isArray()) return MS::kFailure; uint32_t num = plug.numElements(); if(num != count) { MGlobal::displayError("array is sized incorrectly"); return MS::kFailure; } for(uint32_t i = 0; i < num; ++i) { values[i] = plug.elementByLogicalIndex(i).asShort(); } return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::getFloatArray(MObject node, MObject attribute, float* const values, const size_t count) { MPlug plug(node, attribute); if(!plug || !plug.isArray()) return MS::kFailure; uint32_t num = plug.numElements(); if(num != count) { MGlobal::displayError("array is sized incorrectly"); return MS::kFailure; } #if AL_UTILS_ENABLE_SIMD #ifdef __AVX__ uint32_t count8 = count & ~0x7; uint32_t i = 0; for(; i < count8; i += 8) { ALIGN32(float temp[8]); temp[0] = plug.elementByLogicalIndex(i).asFloat(); temp[1] = plug.elementByLogicalIndex(i + 1).asFloat(); temp[2] = plug.elementByLogicalIndex(i + 2).asFloat(); temp[3] = plug.elementByLogicalIndex(i + 3).asFloat(); temp[4] = plug.elementByLogicalIndex(i + 4).asFloat(); temp[5] = plug.elementByLogicalIndex(i + 5).asFloat(); temp[6] = plug.elementByLogicalIndex(i + 6).asFloat(); temp[7] = plug.elementByLogicalIndex(i + 7).asFloat(); storeu8f(values + i, load8f(temp)); } if(count & 0x4) { ALIGN16(float temp[4]); temp[0] = plug.elementByLogicalIndex(i).asFloat(); temp[1] = plug.elementByLogicalIndex(i + 1).asFloat(); temp[2] = plug.elementByLogicalIndex(i + 2).asFloat(); temp[3] = plug.elementByLogicalIndex(i + 3).asFloat(); storeu4f(values + i, load4f(temp)); i += 4; } #else uint32_t count4 = count & ~0x3; uint32_t i = 0; for(; i < count4; i += 4) { ALIGN16(float temp[4]); temp[0] = plug.elementByLogicalIndex(i).asFloat(); temp[1] = plug.elementByLogicalIndex(i + 1).asFloat(); temp[2] = plug.elementByLogicalIndex(i + 2).asFloat(); temp[3] = plug.elementByLogicalIndex(i + 3).asFloat(); storeu4f(values + i, load4f(temp)); } #endif switch(count & 3) { case 3: values[i + 2] = plug.elementByLogicalIndex(i + 2).asFloat(); case 2: values[i + 1] = plug.elementByLogicalIndex(i + 1).asFloat(); case 1: values[i] = plug.elementByLogicalIndex(i).asFloat(); default: break; } #else for(uint32_t i = 0; i < num; ++i) { values[i] = plug.elementByLogicalIndex(i).asFloat(); } #endif return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::getHalfArray(MObject node, MObject attribute, GfHalf* const values, const size_t count) { MPlug plug(node, attribute); if(!plug || !plug.isArray()) return MS::kFailure; uint32_t num = plug.numElements(); if(num != count) { MGlobal::displayError("array is sized incorrectly"); return MS::kFailure; } size_t count8 = count & ~0x7ULL; for(uint32_t i = 0; i < count8; i += 8) { float f[8]; f[0] = plug.elementByLogicalIndex(i + 0).asFloat(); f[1] = plug.elementByLogicalIndex(i + 1).asFloat(); f[2] = plug.elementByLogicalIndex(i + 2).asFloat(); f[3] = plug.elementByLogicalIndex(i + 3).asFloat(); f[4] = plug.elementByLogicalIndex(i + 4).asFloat(); f[5] = plug.elementByLogicalIndex(i + 5).asFloat(); f[6] = plug.elementByLogicalIndex(i + 6).asFloat(); f[7] = plug.elementByLogicalIndex(i + 7).asFloat(); AL::usd::utils::float2half_8f(f, values + i); } if(count & 0x4) { float f[4]; f[0] = plug.elementByLogicalIndex(count8 + 0).asFloat(); f[1] = plug.elementByLogicalIndex(count8 + 1).asFloat(); f[2] = plug.elementByLogicalIndex(count8 + 2).asFloat(); f[3] = plug.elementByLogicalIndex(count8 + 3).asFloat(); AL::usd::utils::float2half_4f(f, values + count8); count8 += 4; } switch(count & 0x3) { case 3: values[count8 + 2] = AL::usd::utils::float2half_1f(plug.elementByLogicalIndex(count8 + 2).asFloat()); case 2: values[count8 + 1] = AL::usd::utils::float2half_1f(plug.elementByLogicalIndex(count8 + 1).asFloat()); case 1: values[count8 + 0] = AL::usd::utils::float2half_1f(plug.elementByLogicalIndex(count8 + 0).asFloat()); default: break; } return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::getDoubleArray(MObject node, MObject attribute, double* const values, const size_t count) { MPlug plug(node, attribute); if(!plug || !plug.isArray()) return MS::kFailure; uint32_t num = plug.numElements(); if(num != count) { MGlobal::displayError("array is sized incorrectly"); return MS::kFailure; } #if AL_UTILS_ENABLE_SIMD #ifdef __AVX__ uint32_t count8 = count & ~0x7; uint32_t i = 0; for(; i < count8; i += 8) { ALIGN32(double temp[8]); temp[0] = plug.elementByLogicalIndex(i).asDouble(); temp[1] = plug.elementByLogicalIndex(i + 1).asDouble(); temp[2] = plug.elementByLogicalIndex(i + 2).asDouble(); temp[3] = plug.elementByLogicalIndex(i + 3).asDouble(); temp[4] = plug.elementByLogicalIndex(i + 4).asDouble(); temp[5] = plug.elementByLogicalIndex(i + 5).asDouble(); temp[6] = plug.elementByLogicalIndex(i + 6).asDouble(); temp[7] = plug.elementByLogicalIndex(i + 7).asDouble(); storeu4d(values + i, load4d(temp)); storeu4d(values + i + 4, load4d(temp + 4)); } if(count & 0x4) { ALIGN16(double temp[4]); temp[0] = plug.elementByLogicalIndex(i).asDouble(); temp[1] = plug.elementByLogicalIndex(i + 1).asDouble(); temp[2] = plug.elementByLogicalIndex(i + 2).asDouble(); temp[3] = plug.elementByLogicalIndex(i + 3).asDouble(); storeu4d(values + i, load4d(temp)); i += 4; } #else uint32_t count4 = count & ~0x3; uint32_t i = 0; for(; i < count4; i += 4) { ALIGN16(double temp[4]); temp[0] = plug.elementByLogicalIndex(i).asDouble(); temp[1] = plug.elementByLogicalIndex(i + 1).asDouble(); temp[2] = plug.elementByLogicalIndex(i + 2).asDouble(); temp[3] = plug.elementByLogicalIndex(i + 3).asDouble(); storeu2d(values + i, load2d(temp)); storeu2d(values + i + 2, load2d(temp + 2)); } #endif switch(count & 3) { case 3: values[i + 2] = plug.elementByLogicalIndex(i + 2).asDouble(); case 2: values[i + 1] = plug.elementByLogicalIndex(i + 1).asDouble(); case 1: values[i] = plug.elementByLogicalIndex(i).asDouble(); default: break; } #else for(uint32_t i = 0; i < num; ++i) { values[i] = plug.elementByLogicalIndex(i).asDouble(); } #endif return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::getVec2Array(MObject node, MObject attribute, double* const values, const size_t count) { MPlug plug(node, attribute); if(!plug || !plug.isArray()) return MS::kFailure; uint32_t num = plug.numElements(); if(num != count) { MGlobal::displayError("array is sized incorrectly"); return MS::kFailure; } #if AL_UTILS_ENABLE_SIMD #ifdef __AVX__ uint32_t count2 = count & ~0x1; uint32_t i = 0; for(; i < count2; i += 2) { ALIGN32(double temp[4]); temp[0] = plug.elementByLogicalIndex(i).child(0).asDouble(); temp[1] = plug.elementByLogicalIndex(i).child(1).asDouble(); temp[2] = plug.elementByLogicalIndex(i + 1).child(0).asDouble(); temp[3] = plug.elementByLogicalIndex(i + 1).child(1).asDouble(); storeu4d(values + i * 2, load4d(temp)); } if(count & 1) { ALIGN16(double temp[2]); temp[0] = plug.elementByLogicalIndex(i).child(0).asDouble(); temp[1] = plug.elementByLogicalIndex(i).child(1).asDouble(); storeu2d(values + i * 2, load2d(temp)); } #else uint32_t i = 0; for(; i < count; ++i) { ALIGN16(double temp[2]); temp[0] = plug.elementByLogicalIndex(i).child(0).asDouble(); temp[1] = plug.elementByLogicalIndex(i).child(1).asDouble(); storeu2d(values + i * 2, load2d(temp)); } #endif #else for(uint32_t i = 0, j = 0; i < num; ++i, j += 2) { values[j] = plug.elementByLogicalIndex(i).child(0).asDouble(); values[j + 1] = plug.elementByLogicalIndex(i).child(1).asDouble(); } #endif return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::getVec2Array(MObject node, MObject attribute, float* const values, const size_t count) { MPlug plug(node, attribute); if(!plug || !plug.isArray()) return MS::kFailure; uint32_t num = plug.numElements(); if(num != count) { MGlobal::displayError("array is sized incorrectly"); return MS::kFailure; } #if AL_UTILS_ENABLE_SIMD #ifdef __AVX__ uint32_t count4 = count & ~0x3; uint32_t i = 0; for(; i < count4; i += 4) { ALIGN32(float temp[8]); temp[0] = plug.elementByLogicalIndex(i).child(0).asFloat(); temp[1] = plug.elementByLogicalIndex(i).child(1).asFloat(); temp[2] = plug.elementByLogicalIndex(i + 1).child(0).asFloat(); temp[3] = plug.elementByLogicalIndex(i + 1).child(1).asFloat(); temp[4] = plug.elementByLogicalIndex(i + 2).child(0).asFloat(); temp[5] = plug.elementByLogicalIndex(i + 2).child(1).asFloat(); temp[6] = plug.elementByLogicalIndex(i + 3).child(0).asFloat(); temp[7] = plug.elementByLogicalIndex(i + 3).child(1).asFloat(); storeu8f(values + i * 2, load8f(temp)); } if(count & 0x2) { ALIGN16(float temp[4]); temp[0] = plug.elementByLogicalIndex(i).child(0).asFloat(); temp[1] = plug.elementByLogicalIndex(i).child(1).asFloat(); temp[2] = plug.elementByLogicalIndex(i + 1).child(0).asFloat(); temp[3] = plug.elementByLogicalIndex(i + 1).child(1).asFloat(); storeu4f(values + i * 2, load4f(temp)); i += 2; } #else uint32_t count2 = count & ~0x1; uint32_t i = 0; for(; i < count2; i += 2) { ALIGN16(float temp[4]); temp[0] = plug.elementByLogicalIndex(i).child(0).asFloat(); temp[1] = plug.elementByLogicalIndex(i).child(1).asFloat(); temp[2] = plug.elementByLogicalIndex(i + 1).child(0).asFloat(); temp[3] = plug.elementByLogicalIndex(i + 1).child(1).asFloat(); storeu4f(values + i * 2, load4f(temp)); } #endif switch(count & 1) { case 1: values[i * 2] = plug.elementByLogicalIndex(i).child(0).asFloat(); values[i * 2 + 1] = plug.elementByLogicalIndex(i).child(1).asFloat(); default: break; } #else for(uint32_t i = 0, j = 0; i < num; ++i, j += 2) { values[j] = plug.elementByLogicalIndex(i).child(0).asFloat(); values[j + 1] = plug.elementByLogicalIndex(i).child(1).asFloat(); } #endif return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::getVec2Array(MObject node, MObject attribute, GfHalf* const values, const size_t count) { MPlug plug(node, attribute); if(!plug || !plug.isArray()) return MS::kFailure; uint32_t num = plug.numElements(); if(num != count) { MGlobal::displayError("array is sized incorrectly"); return MS::kFailure; } for(uint32_t i = 0, j = 0; i < num; ++i, j += 2) { values[j] = plug.elementByLogicalIndex(i).child(0).asFloat(); values[j + 1] = plug.elementByLogicalIndex(i).child(1).asFloat(); } size_t count4 = count & ~0x3FULL; for(uint32_t i = 0, j = 0; i < count4; i += 4, j += 8) { float f[8]; auto v0 = plug.elementByLogicalIndex(i + 0); auto v1 = plug.elementByLogicalIndex(i + 1); auto v2 = plug.elementByLogicalIndex(i + 2); auto v3 = plug.elementByLogicalIndex(i + 3); f[0] = v0.child(0).asFloat(); f[1] = v0.child(1).asFloat(); f[2] = v1.child(0).asFloat(); f[3] = v1.child(1).asFloat(); f[4] = v2.child(0).asFloat(); f[5] = v2.child(1).asFloat(); f[6] = v3.child(0).asFloat(); f[7] = v3.child(1).asFloat(); AL::usd::utils::float2half_8f(f, values + j); } if(count & 0x2) { float f[4]; auto v0 = plug.elementByLogicalIndex(count4 + 0); auto v1 = plug.elementByLogicalIndex(count4 + 1); f[0] = v0.child(0).asFloat(); f[1] = v0.child(1).asFloat(); f[2] = v1.child(0).asFloat(); f[3] = v1.child(1).asFloat(); AL::usd::utils::float2half_4f(f, values + count4 * 2); count4 += 2; } if(count & 0x1) { auto v = plug.elementByLogicalIndex(count4); values[count4 * 2 + 0] = AL::usd::utils::float2half_1f(v.child(0).asFloat()); values[count4 * 2 + 1] = AL::usd::utils::float2half_1f(v.child(1).asFloat()); } return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::getVec2Array(MObject node, MObject attribute, int32_t* const values, const size_t count) { MPlug plug(node, attribute); if(!plug || !plug.isArray()) return MS::kFailure; uint32_t num = plug.numElements(); if(num != count) { MGlobal::displayError("array is sized incorrectly"); return MS::kFailure; } #if AL_UTILS_ENABLE_SIMD #ifdef __AVX__ uint32_t count4 = count & ~0x3; uint32_t i = 0; for(; i < count4; i += 4) { ALIGN32(int32_t temp[8]); temp[0] = plug.elementByLogicalIndex(i).child(0).asInt(); temp[1] = plug.elementByLogicalIndex(i).child(1).asInt(); temp[2] = plug.elementByLogicalIndex(i + 1).child(0).asInt(); temp[3] = plug.elementByLogicalIndex(i + 1).child(1).asInt(); temp[4] = plug.elementByLogicalIndex(i + 2).child(0).asInt(); temp[5] = plug.elementByLogicalIndex(i + 2).child(1).asInt(); temp[6] = plug.elementByLogicalIndex(i + 3).child(0).asInt(); temp[7] = plug.elementByLogicalIndex(i + 3).child(1).asInt(); storeu8i(values + i * 2, load8i(temp)); } if(count & 0x2) { ALIGN16(int32_t temp[4]); temp[0] = plug.elementByLogicalIndex(i).child(0).asInt(); temp[1] = plug.elementByLogicalIndex(i).child(1).asInt(); temp[2] = plug.elementByLogicalIndex(i + 1).child(0).asInt(); temp[3] = plug.elementByLogicalIndex(i + 1).child(1).asInt(); storeu4i(values + i * 2, load4i(temp)); i += 2; } #else uint32_t count2 = count & ~0x1; uint32_t i = 0; for(; i < count2; i += 2) { ALIGN16(int32_t temp[4]); temp[0] = plug.elementByLogicalIndex(i).child(0).asInt(); temp[1] = plug.elementByLogicalIndex(i).child(1).asInt(); temp[2] = plug.elementByLogicalIndex(i + 1).child(0).asInt(); temp[3] = plug.elementByLogicalIndex(i + 1).child(1).asInt(); storeu4i(values + i * 2, load4i(temp)); } #endif if(count & 1) { values[i * 2] = plug.elementByLogicalIndex(i).child(0).asInt(); values[i * 2 + 1] = plug.elementByLogicalIndex(i).child(1).asInt(); } #else for(uint32_t i = 0, j = 0; i < num; ++i, j += 2) { values[j] = plug.elementByLogicalIndex(i).child(0).asInt(); values[j + 1] = plug.elementByLogicalIndex(i).child(1).asInt(); } #endif return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::getVec3Array(MObject node, MObject attribute, float* const values, const size_t count) { MPlug plug(node, attribute); if(!plug || !plug.isArray()) return MS::kFailure; uint32_t num = plug.numElements(); if(num != count) { MGlobal::displayError("array is sized incorrectly"); return MS::kFailure; } #if AL_UTILS_ENABLE_SIMD #ifdef __AVX__ uint32_t count8 = count & ~0x7; uint32_t i = 0; for(; i < count8; i += 8) { ALIGN32(float temp[24]); const MPlug c0 = plug.elementByLogicalIndex(i ); const MPlug c1 = plug.elementByLogicalIndex(i + 1); const MPlug c2 = plug.elementByLogicalIndex(i + 2); const MPlug c3 = plug.elementByLogicalIndex(i + 3); const MPlug c4 = plug.elementByLogicalIndex(i + 4); const MPlug c5 = plug.elementByLogicalIndex(i + 5); const MPlug c6 = plug.elementByLogicalIndex(i + 6); const MPlug c7 = plug.elementByLogicalIndex(i + 7); temp[ 0] = c0.child(0).asFloat(); temp[ 1] = c0.child(1).asFloat(); temp[ 2] = c0.child(2).asFloat(); temp[ 3] = c1.child(0).asFloat(); temp[ 4] = c1.child(1).asFloat(); temp[ 5] = c1.child(2).asFloat(); temp[ 6] = c2.child(0).asFloat(); temp[ 7] = c2.child(1).asFloat(); temp[ 8] = c2.child(2).asFloat(); temp[ 9] = c3.child(0).asFloat(); temp[10] = c3.child(1).asFloat(); temp[11] = c3.child(2).asFloat(); temp[12] = c4.child(0).asFloat(); temp[13] = c4.child(1).asFloat(); temp[14] = c4.child(2).asFloat(); temp[15] = c5.child(0).asFloat(); temp[16] = c5.child(1).asFloat(); temp[17] = c5.child(2).asFloat(); temp[18] = c6.child(0).asFloat(); temp[19] = c6.child(1).asFloat(); temp[20] = c6.child(2).asFloat(); temp[21] = c7.child(0).asFloat(); temp[22] = c7.child(1).asFloat(); temp[23] = c7.child(2).asFloat(); float* optr = values + (i * 3); storeu8f(optr, load8f(temp)); storeu8f(optr + 8, load8f(temp + 8)); storeu8f(optr + 16, load8f(temp + 16)); } if(count & 0x4) { ALIGN32(float temp[12]); const MPlug c0 = plug.elementByLogicalIndex(i ); const MPlug c1 = plug.elementByLogicalIndex(i + 1); const MPlug c2 = plug.elementByLogicalIndex(i + 2); const MPlug c3 = plug.elementByLogicalIndex(i + 3); temp[ 0] = c0.child(0).asFloat(); temp[ 1] = c0.child(1).asFloat(); temp[ 2] = c0.child(2).asFloat(); temp[ 3] = c1.child(0).asFloat(); temp[ 4] = c1.child(1).asFloat(); temp[ 5] = c1.child(2).asFloat(); temp[ 6] = c2.child(0).asFloat(); temp[ 7] = c2.child(1).asFloat(); temp[ 8] = c2.child(2).asFloat(); temp[ 9] = c3.child(0).asFloat(); temp[10] = c3.child(1).asFloat(); temp[11] = c3.child(2).asFloat(); float* optr = values + (i * 3); storeu8f(optr, load8f(temp)); storeu4f(optr + 8, load4f(temp + 8)); i += 4; } #else uint32_t count4 = count & ~0x3; uint32_t i = 0; for(; i < count4; i += 4) { ALIGN16(float temp[12]); const MPlug c0 = plug.elementByLogicalIndex(i ); const MPlug c1 = plug.elementByLogicalIndex(i + 1); const MPlug c2 = plug.elementByLogicalIndex(i + 2); const MPlug c3 = plug.elementByLogicalIndex(i + 3); temp[ 0] = c0.child(0).asFloat(); temp[ 1] = c0.child(1).asFloat(); temp[ 2] = c0.child(2).asFloat(); temp[ 3] = c1.child(0).asFloat(); temp[ 4] = c1.child(1).asFloat(); temp[ 5] = c1.child(2).asFloat(); temp[ 6] = c2.child(0).asFloat(); temp[ 7] = c2.child(1).asFloat(); temp[ 8] = c2.child(2).asFloat(); temp[ 9] = c3.child(0).asFloat(); temp[10] = c3.child(1).asFloat(); temp[11] = c3.child(2).asFloat(); float* optr = values + (i * 3); storeu4f(optr + 0, load4f(temp + 0)); storeu4f(optr + 4, load4f(temp + 4)); storeu4f(optr + 8, load4f(temp + 8)); } #endif float* optr = values + (i * 3); MPlug elem; switch(count & 3) { case 3: elem = plug.elementByLogicalIndex(i + 2); optr[6] = elem.child(0).asFloat(); optr[7] = elem.child(1).asFloat(); optr[8] = elem.child(2).asFloat(); case 2: elem = plug.elementByLogicalIndex(i + 1); optr[3] = elem.child(0).asFloat(); optr[4] = elem.child(1).asFloat(); optr[5] = elem.child(2).asFloat(); case 1: elem = plug.elementByLogicalIndex(i); optr[0] = elem.child(0).asFloat(); optr[1] = elem.child(1).asFloat(); optr[2] = elem.child(2).asFloat(); default: break; } #else for(uint32_t i = 0, j = 0; i < num; ++i, j += 3) { MPlug elem = plug.elementByLogicalIndex(i); values[j ] = elem.child(0).asFloat(); values[j + 1] = elem.child(1).asFloat(); values[j + 2] = elem.child(2).asFloat(); } #endif return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::getVec3Array(MObject node, MObject attribute, double* const values, const size_t count) { MPlug plug(node, attribute); if(!plug || !plug.isArray()) return MS::kFailure; uint32_t num = plug.numElements(); if(num != count) { MGlobal::displayError("array is sized incorrectly"); return MS::kFailure; } #if AL_UTILS_ENABLE_SIMD #ifdef __AVX__ uint32_t count4 = count & ~0x3; uint32_t i = 0; for(; i < count4; i += 4) { ALIGN32(double temp[12]); const MPlug c0 = plug.elementByLogicalIndex(i ); const MPlug c1 = plug.elementByLogicalIndex(i + 1); const MPlug c2 = plug.elementByLogicalIndex(i + 2); const MPlug c3 = plug.elementByLogicalIndex(i + 3); temp[ 0] = c0.child(0).asDouble(); temp[ 1] = c0.child(1).asDouble(); temp[ 2] = c0.child(2).asDouble(); temp[ 3] = c1.child(0).asDouble(); temp[ 4] = c1.child(1).asDouble(); temp[ 5] = c1.child(2).asDouble(); temp[ 6] = c2.child(0).asDouble(); temp[ 7] = c2.child(1).asDouble(); temp[ 8] = c2.child(2).asDouble(); temp[ 9] = c3.child(0).asDouble(); temp[10] = c3.child(1).asDouble(); temp[11] = c3.child(2).asDouble(); double* optr = values + (i * 3); storeu4d(optr, load4d(temp)); storeu4d(optr + 4, load4d(temp + 4)); storeu4d(optr + 8, load4d(temp + 8)); } if(count & 0x2) { ALIGN32(double temp[6]); const MPlug c0 = plug.elementByLogicalIndex(i ); const MPlug c1 = plug.elementByLogicalIndex(i + 1); temp[ 0] = c0.child(0).asDouble(); temp[ 1] = c0.child(1).asDouble(); temp[ 2] = c0.child(2).asDouble(); temp[ 3] = c1.child(0).asDouble(); temp[ 4] = c1.child(1).asDouble(); temp[ 5] = c1.child(2).asDouble(); double* optr = values + (i * 3); storeu4d(optr, load4d(temp)); storeu2d(optr + 4, load2d(temp + 4)); i += 2; } #else uint32_t count2 = count & ~0x1; uint32_t i = 0; for(; i < count2; i += 2) { ALIGN16(double temp[6]); const MPlug c0 = plug.elementByLogicalIndex(i ); const MPlug c1 = plug.elementByLogicalIndex(i + 1); temp[ 0] = c0.child(0).asDouble(); temp[ 1] = c0.child(1).asDouble(); temp[ 2] = c0.child(2).asDouble(); temp[ 3] = c1.child(0).asDouble(); temp[ 4] = c1.child(1).asDouble(); temp[ 5] = c1.child(2).asDouble(); double* optr = values + (i * 3); storeu2d(optr + 0, load2d(temp + 0)); storeu2d(optr + 2, load2d(temp + 2)); storeu2d(optr + 4, load2d(temp + 4)); } #endif if(count & 1) { double* optr = values + (i * 3); MPlug elem = plug.elementByLogicalIndex(i); optr[0] = elem.child(0).asDouble(); optr[1] = elem.child(1).asDouble(); optr[2] = elem.child(2).asDouble(); } #else for(uint32_t i = 0, j = 0; i < num; ++i, j += 3) { MPlug elem = plug.elementByLogicalIndex(i); values[j ] = elem.child(0).asFloat(); values[j + 1] = elem.child(1).asFloat(); values[j + 2] = elem.child(2).asFloat(); } #endif return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::getVec3Array(MObject node, MObject attribute, GfHalf* const values, const size_t count) { MPlug plug(node, attribute); if(!plug || !plug.isArray()) return MS::kFailure; uint32_t num = plug.numElements(); if(num != count) { MGlobal::displayError("array is sized incorrectly"); return MS::kFailure; } size_t count8 = count & ~0x7ULL; for(uint32_t i = 0, j = 0; i < count8; i += 8, j += 24) { float r[24]; MPlug v0 = plug.elementByLogicalIndex(i + 0); MPlug v1 = plug.elementByLogicalIndex(i + 1); MPlug v2 = plug.elementByLogicalIndex(i + 2); MPlug v3 = plug.elementByLogicalIndex(i + 3); MPlug v4 = plug.elementByLogicalIndex(i + 4); MPlug v5 = plug.elementByLogicalIndex(i + 5); MPlug v6 = plug.elementByLogicalIndex(i + 6); MPlug v7 = plug.elementByLogicalIndex(i + 7); r[ 0] = v0.child(0).asFloat(); r[ 1] = v0.child(1).asFloat(); r[ 2] = v0.child(2).asFloat(); r[ 3] = v1.child(0).asFloat(); r[ 4] = v1.child(1).asFloat(); r[ 5] = v1.child(2).asFloat(); r[ 6] = v2.child(0).asFloat(); r[ 7] = v2.child(1).asFloat(); r[ 8] = v2.child(2).asFloat(); r[ 9] = v3.child(0).asFloat(); r[10] = v3.child(1).asFloat(); r[11] = v3.child(2).asFloat(); r[12] = v4.child(0).asFloat(); r[13] = v4.child(1).asFloat(); r[14] = v4.child(2).asFloat(); r[15] = v5.child(0).asFloat(); r[16] = v5.child(1).asFloat(); r[17] = v5.child(2).asFloat(); r[18] = v6.child(0).asFloat(); r[19] = v6.child(1).asFloat(); r[20] = v6.child(2).asFloat(); r[21] = v7.child(0).asFloat(); r[22] = v7.child(1).asFloat(); r[23] = v7.child(2).asFloat(); AL::usd::utils::float2half_8f(r, values + j); AL::usd::utils::float2half_8f(r + 8, values + j + 8); AL::usd::utils::float2half_8f(r + 16, values + j + 16); } for(uint32_t i = count8, j = count8 * 3; i < count; ++i, j += 3) { float v[4]; GfHalf h[4]; MPlug elem = plug.elementByLogicalIndex(i); v[0] = elem.child(0).asFloat(); v[1] = elem.child(1).asFloat(); v[2] = elem.child(2).asFloat(); AL::usd::utils::float2half_4f(v, h); values[j + 0] = h[0]; values[j + 1] = h[1]; values[j + 2] = h[2]; } return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::getVec3Array(MObject node, MObject attribute, int32_t* const values, const size_t count) { MPlug plug(node, attribute); if(!plug || !plug.isArray()) return MS::kFailure; uint32_t num = plug.numElements(); if(num != count) { MGlobal::displayError("array is sized incorrectly"); return MS::kFailure; } #if AL_UTILS_ENABLE_SIMD #ifdef __AVX__ uint32_t count8 = count & ~0x7; uint32_t i = 0; for(; i < count8; i += 8) { ALIGN32(int32_t temp[24]); const MPlug c0 = plug.elementByLogicalIndex(i ); const MPlug c1 = plug.elementByLogicalIndex(i + 1); const MPlug c2 = plug.elementByLogicalIndex(i + 2); const MPlug c3 = plug.elementByLogicalIndex(i + 3); const MPlug c4 = plug.elementByLogicalIndex(i + 4); const MPlug c5 = plug.elementByLogicalIndex(i + 5); const MPlug c6 = plug.elementByLogicalIndex(i + 6); const MPlug c7 = plug.elementByLogicalIndex(i + 7); temp[ 0] = c0.child(0).asInt(); temp[ 1] = c0.child(1).asInt(); temp[ 2] = c0.child(2).asInt(); temp[ 3] = c1.child(0).asInt(); temp[ 4] = c1.child(1).asInt(); temp[ 5] = c1.child(2).asInt(); temp[ 6] = c2.child(0).asInt(); temp[ 7] = c2.child(1).asInt(); temp[ 8] = c2.child(2).asInt(); temp[ 9] = c3.child(0).asInt(); temp[10] = c3.child(1).asInt(); temp[11] = c3.child(2).asInt(); temp[12] = c4.child(0).asInt(); temp[13] = c4.child(1).asInt(); temp[14] = c4.child(2).asInt(); temp[15] = c5.child(0).asInt(); temp[16] = c5.child(1).asInt(); temp[17] = c5.child(2).asInt(); temp[18] = c6.child(0).asInt(); temp[19] = c6.child(1).asInt(); temp[20] = c6.child(2).asInt(); temp[21] = c7.child(0).asInt(); temp[22] = c7.child(1).asInt(); temp[23] = c7.child(2).asInt(); int32_t* optr = values + (i * 3); storeu8i(optr + 0, load8i(temp + 0)); storeu8i(optr + 8, load8i(temp + 8)); storeu8i(optr + 16, load8i(temp + 16)); } if(count & 0x4) { ALIGN32(int32_t temp[12]); const MPlug c0 = plug.elementByLogicalIndex(i ); const MPlug c1 = plug.elementByLogicalIndex(i + 1); const MPlug c2 = plug.elementByLogicalIndex(i + 2); const MPlug c3 = plug.elementByLogicalIndex(i + 3); temp[ 0] = c0.child(0).asInt(); temp[ 1] = c0.child(1).asInt(); temp[ 2] = c0.child(2).asInt(); temp[ 3] = c1.child(0).asInt(); temp[ 4] = c1.child(1).asInt(); temp[ 5] = c1.child(2).asInt(); temp[ 6] = c2.child(0).asInt(); temp[ 7] = c2.child(1).asInt(); temp[ 8] = c2.child(2).asInt(); temp[ 9] = c3.child(0).asInt(); temp[10] = c3.child(1).asInt(); temp[11] = c3.child(2).asInt(); int32_t* optr = values + (i * 3); storeu8i(optr + 0, load8i(temp + 0)); storeu4i(optr + 8, load4i(temp + 8)); i += 4; } #else uint32_t count4 = count & ~0x3; uint32_t i = 0; for(; i < count4; i += 4) { ALIGN16(int32_t temp[12]); const MPlug c0 = plug.elementByLogicalIndex(i ); const MPlug c1 = plug.elementByLogicalIndex(i + 1); const MPlug c2 = plug.elementByLogicalIndex(i + 2); const MPlug c3 = plug.elementByLogicalIndex(i + 3); temp[ 0] = c0.child(0).asInt(); temp[ 1] = c0.child(1).asInt(); temp[ 2] = c0.child(2).asInt(); temp[ 3] = c1.child(0).asInt(); temp[ 4] = c1.child(1).asInt(); temp[ 5] = c1.child(2).asInt(); temp[ 6] = c2.child(0).asInt(); temp[ 7] = c2.child(1).asInt(); temp[ 8] = c2.child(2).asInt(); temp[ 9] = c3.child(0).asInt(); temp[10] = c3.child(1).asInt(); temp[11] = c3.child(2).asInt(); int32_t* optr = values + (i * 3); storeu4i(optr + 0, load4i(temp + 0)); storeu4i(optr + 4, load4i(temp + 4)); storeu4i(optr + 8, load4i(temp + 8)); } #endif int32_t* optr = values + (i * 3); MPlug elem; switch(count & 3) { case 3: elem = plug.elementByLogicalIndex(i + 2); optr[6] = elem.child(0).asInt(); optr[7] = elem.child(1).asInt(); optr[8] = elem.child(2).asInt(); case 2: elem = plug.elementByLogicalIndex(i + 1); optr[3] = elem.child(0).asInt(); optr[4] = elem.child(1).asInt(); optr[5] = elem.child(2).asInt(); case 1: elem = plug.elementByLogicalIndex(i); optr[0] = elem.child(0).asInt(); optr[1] = elem.child(1).asInt(); optr[2] = elem.child(2).asInt(); default: break; } #else for(uint32_t i = 0, j = 0; i < num; ++i, j += 3) { MPlug elem = plug.elementByLogicalIndex(i); values[j ] = elem.child(0).asInt(); values[j + 1] = elem.child(1).asInt(); values[j + 2] = elem.child(2).asInt(); } #endif return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::getVec4Array(MObject node, MObject attribute, int32_t* const values, const size_t count) { MPlug plug(node, attribute); if(!plug || !plug.isArray()) return MS::kFailure; uint32_t num = plug.numElements(); if(num != count) { MGlobal::displayError("array is sized incorrectly"); return MS::kFailure; } size_t count2 = count & ~1; size_t i = 0, j = 0; for(; i < count2; i += 2, j += 8) { ALIGN32(int32_t temp[8]); MPlug elem0 = plug.elementByLogicalIndex(i); MPlug elem1 = plug.elementByLogicalIndex(i + 1); temp[0] = elem0.child(0).asInt(); temp[1] = elem0.child(1).asInt(); temp[2] = elem0.child(2).asInt(); temp[3] = elem0.child(3).asInt(); temp[4] = elem1.child(0).asInt(); temp[5] = elem1.child(1).asInt(); temp[6] = elem1.child(2).asInt(); temp[7] = elem1.child(3).asInt(); #if AL_UTILS_ENABLE_SIMD # ifdef __AVX__ storeu8i(values + j, load8i(temp)); # else storeu4i(values + j, load4i(temp)); storeu4i(values + j + 4, load4i(temp + 4)); # endif #else values[j + 0] = temp[0]; values[j + 1] = temp[1]; values[j + 2] = temp[2]; values[j + 3] = temp[3]; values[j + 4] = temp[4]; values[j + 5] = temp[5]; values[j + 6] = temp[6]; values[j + 7] = temp[7]; #endif } if(count & 1) { ALIGN16(int32_t temp[4]); MPlug elem0 = plug.elementByLogicalIndex(i); temp[0] = elem0.child(0).asInt(); temp[1] = elem0.child(1).asInt(); temp[2] = elem0.child(2).asInt(); temp[3] = elem0.child(3).asInt(); #if AL_UTILS_ENABLE_SIMD storeu4i(values + j, load4i(temp)); #else values[j + 0] = temp[0]; values[j + 1] = temp[1]; values[j + 2] = temp[2]; values[j + 3] = temp[3]; #endif } return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::getVec4Array(MObject node, MObject attribute, float* const values, const size_t count) { MPlug plug(node, attribute); if(!plug || !plug.isArray()) return MS::kFailure; uint32_t num = plug.numElements(); if(num != count) { MGlobal::displayError("array is sized incorrectly"); return MS::kFailure; } size_t count2 = count & ~1; size_t i = 0, j = 0; for(; i < count2; i += 2, j += 8) { ALIGN32(float temp[8]); MPlug elem0 = plug.elementByLogicalIndex(i); MPlug elem1 = plug.elementByLogicalIndex(i + 1); temp[0] = elem0.child(0).asFloat(); temp[1] = elem0.child(1).asFloat(); temp[2] = elem0.child(2).asFloat(); temp[3] = elem0.child(3).asFloat(); temp[4] = elem1.child(0).asFloat(); temp[5] = elem1.child(1).asFloat(); temp[6] = elem1.child(2).asFloat(); temp[7] = elem1.child(3).asFloat(); #if AL_UTILS_ENABLE_SIMD # ifdef __AVX__ storeu8f(values + j, load8f(temp)); # else storeu4f(values + j, load4f(temp)); storeu4f(values + j + 4, load4f(temp + 4)); # endif #else values[j + 0] = temp[0]; values[j + 1] = temp[1]; values[j + 2] = temp[2]; values[j + 3] = temp[3]; values[j + 4] = temp[4]; values[j + 5] = temp[5]; values[j + 6] = temp[6]; values[j + 7] = temp[7]; #endif } if(count & 1) { ALIGN16(float temp[4]); MPlug elem0 = plug.elementByLogicalIndex(i); temp[0] = elem0.child(0).asFloat(); temp[1] = elem0.child(1).asFloat(); temp[2] = elem0.child(2).asFloat(); temp[3] = elem0.child(3).asFloat(); #if AL_UTILS_ENABLE_SIMD storeu4f(values + j, load4f(temp)); #else values[j + 0] = temp[0]; values[j + 1] = temp[1]; values[j + 2] = temp[2]; values[j + 3] = temp[3]; #endif } return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::getVec4Array(MObject node, MObject attribute, double* const values, const size_t count) { MPlug plug(node, attribute); if(!plug || !plug.isArray()) return MS::kFailure; uint32_t num = plug.numElements(); if(num != count) { MGlobal::displayError("array is sized incorrectly"); return MS::kFailure; } for(uint32_t i = 0, j = 0; i < num; ++i, j += 4) { ALIGN32(double temp[4]); MPlug elem = plug.elementByLogicalIndex(i); temp[0] = elem.child(0).asDouble(); temp[1] = elem.child(1).asDouble(); temp[2] = elem.child(2).asDouble(); temp[3] = elem.child(3).asDouble(); #if AL_UTILS_ENABLE_SIMD # ifdef __AVX__ storeu4d(values + j, load4d(temp)); # else storeu2d(values + j, load2d(temp)); storeu2d(values + j + 2, load2d(temp + 2)); # endif #else values[j + 0] = temp[0]; values[j + 1] = temp[1]; values[j + 2] = temp[2]; values[j + 3] = temp[3]; #endif } return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::getVec4Array(MObject node, MObject attribute, GfHalf* const values, const size_t count) { MPlug plug(node, attribute); if(!plug || !plug.isArray()) return MS::kFailure; uint32_t num = plug.numElements(); if(num != count) { MGlobal::displayError("array is sized incorrectly"); return MS::kFailure; } size_t count2 = count & ~0x1ULL; for(uint32_t i = 0, j = 0; i < count2; i += 2, j += 8) { MPlug v0 = plug.elementByLogicalIndex(i + 0); MPlug v1 = plug.elementByLogicalIndex(i + 1); float f[8]; f[0] = v0.child(0).asFloat(); f[1] = v0.child(1).asFloat(); f[2] = v0.child(2).asFloat(); f[3] = v0.child(3).asFloat(); f[4] = v1.child(0).asFloat(); f[5] = v1.child(1).asFloat(); f[6] = v1.child(2).asFloat(); f[7] = v1.child(3).asFloat(); AL::usd::utils::float2half_8f(f, values + j); } if(count & 0x1) { MPlug v0 = plug.elementByLogicalIndex(count2); float f[4]; f[0] = v0.child(0).asFloat(); f[1] = v0.child(1).asFloat(); f[2] = v0.child(2).asFloat(); f[3] = v0.child(3).asFloat(); AL::usd::utils::float2half_4f(f, values + count2 * 4); } return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::getQuatArray(MObject node, MObject attr, GfHalf* const values, const size_t count) { return getVec4Array(node, attr, values, count); } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::getQuatArray(MObject node, MObject attr, float* const values, const size_t count) { return getVec4Array(node, attr, values, count); } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::getQuatArray(MObject node, MObject attr, double* const values, const size_t count) { return getVec4Array(node, attr, values, count); } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::getMatrix2x2Array(MObject node, MObject attribute, double* const values, const size_t count) { const char* const errorString = "getMatrix2x2Array error"; MPlug arrayPlug(node, attribute); for(uint32_t i = 0; i < count; ++i) { double* const str = values + i * 4; MPlug plug = arrayPlug.elementByLogicalIndex(i); AL_MAYA_CHECK_ERROR(plug.child(0).child(0).getValue(str[0]), errorString); AL_MAYA_CHECK_ERROR(plug.child(0).child(1).getValue(str[1]), errorString); AL_MAYA_CHECK_ERROR(plug.child(1).child(0).getValue(str[2]), errorString); AL_MAYA_CHECK_ERROR(plug.child(1).child(1).getValue(str[3]), errorString); } return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::getMatrix2x2Array(MObject node, MObject attribute, float* const values, const size_t count) { const char* const errorString = "getMatrix2x2Array error"; MPlug arrayPlug(node, attribute); for(uint32_t i = 0; i < count; ++i) { float* const str = values + i * 4; MPlug plug = arrayPlug.elementByLogicalIndex(i); AL_MAYA_CHECK_ERROR(plug.child(0).child(0).getValue(str[0]), errorString); AL_MAYA_CHECK_ERROR(plug.child(0).child(1).getValue(str[1]), errorString); AL_MAYA_CHECK_ERROR(plug.child(1).child(0).getValue(str[2]), errorString); AL_MAYA_CHECK_ERROR(plug.child(1).child(1).getValue(str[3]), errorString); } return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::getMatrix3x3Array(MObject node, MObject attribute, double* const values, const size_t count) { const char* const errorString = "getMatrix3x3Array error"; MPlug arrayPlug(node, attribute); for(uint32_t i = 0; i < count; ++i) { double* const str = values + i * 9; MPlug plug = arrayPlug.elementByLogicalIndex(i); AL_MAYA_CHECK_ERROR(plug.child(0).child(0).getValue(str[0]), errorString); AL_MAYA_CHECK_ERROR(plug.child(0).child(1).getValue(str[1]), errorString); AL_MAYA_CHECK_ERROR(plug.child(0).child(2).getValue(str[2]), errorString); AL_MAYA_CHECK_ERROR(plug.child(1).child(0).getValue(str[3]), errorString); AL_MAYA_CHECK_ERROR(plug.child(1).child(1).getValue(str[4]), errorString); AL_MAYA_CHECK_ERROR(plug.child(1).child(2).getValue(str[5]), errorString); AL_MAYA_CHECK_ERROR(plug.child(2).child(0).getValue(str[6]), errorString); AL_MAYA_CHECK_ERROR(plug.child(2).child(1).getValue(str[7]), errorString); AL_MAYA_CHECK_ERROR(plug.child(2).child(2).getValue(str[8]), errorString); } return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::getMatrix3x3Array(MObject node, MObject attribute, float* const values, const size_t count) { const char* const errorString = "getMatrix3x3Array error"; MPlug arrayPlug(node, attribute); for(uint32_t i = 0; i < count; ++i) { float* const str = values + i * 9; MPlug plug = arrayPlug.elementByLogicalIndex(i); AL_MAYA_CHECK_ERROR(plug.child(0).child(0).getValue(str[0]), errorString); AL_MAYA_CHECK_ERROR(plug.child(0).child(1).getValue(str[1]), errorString); AL_MAYA_CHECK_ERROR(plug.child(0).child(2).getValue(str[2]), errorString); AL_MAYA_CHECK_ERROR(plug.child(1).child(0).getValue(str[3]), errorString); AL_MAYA_CHECK_ERROR(plug.child(1).child(1).getValue(str[4]), errorString); AL_MAYA_CHECK_ERROR(plug.child(1).child(2).getValue(str[5]), errorString); AL_MAYA_CHECK_ERROR(plug.child(2).child(0).getValue(str[6]), errorString); AL_MAYA_CHECK_ERROR(plug.child(2).child(1).getValue(str[7]), errorString); AL_MAYA_CHECK_ERROR(plug.child(2).child(2).getValue(str[8]), errorString); } return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::getMatrix4x4Array(MObject node, MObject attribute, float* const values, const size_t count) { MPlug plug(node, attribute); if(!plug) return MS::kFailure; if(plug.isArray()) { uint32_t num = plug.numElements(); if(num != count) { MGlobal::displayError("array is sized incorrectly"); return MS::kFailure; } MFnMatrixData fn; MObject elementValue; for(uint32_t i = 0, j = 0; i < count; ++i, j += 16) { plug.elementByLogicalIndex(i).getValue(elementValue); fn.setObject(elementValue); const MMatrix& m = fn.matrix(); #if AL_UTILS_ENABLE_SIMD # ifdef __AVX__ const f128 m0 = cvt4d_to_4f(loadu4d(&m.matrix[0][0])); const f128 m1 = cvt4d_to_4f(loadu4d(&m.matrix[1][0])); const f128 m2 = cvt4d_to_4f(loadu4d(&m.matrix[2][0])); const f128 m3 = cvt4d_to_4f(loadu4d(&m.matrix[3][0])); # else const f128 m0a = cvt2d_to_2f(loadu2d(&m.matrix[0][0])); const f128 m0b = cvt2d_to_2f(loadu2d(&m.matrix[0][2])); const f128 m1a = cvt2d_to_2f(loadu2d(&m.matrix[1][0])); const f128 m1b = cvt2d_to_2f(loadu2d(&m.matrix[1][2])); const f128 m2a = cvt2d_to_2f(loadu2d(&m.matrix[2][0])); const f128 m2b = cvt2d_to_2f(loadu2d(&m.matrix[2][2])); const f128 m3a = cvt2d_to_2f(loadu2d(&m.matrix[3][0])); const f128 m3b = cvt2d_to_2f(loadu2d(&m.matrix[3][2])); const f128 m0 = movelh4f(m0a, m0b); const f128 m1 = movelh4f(m1a, m1b); const f128 m2 = movelh4f(m2a, m2b); const f128 m3 = movelh4f(m3a, m3b); # endif float* optr = values + j; storeu4f(optr, m0); storeu4f(optr + 4, m1); storeu4f(optr + 8, m2); storeu4f(optr + 12, m3); #else float* optr = values + j; optr[0] = m.matrix[0][0]; optr[1] = m.matrix[0][1]; optr[2] = m.matrix[0][2]; optr[3] = m.matrix[0][3]; optr[4] = m.matrix[1][0]; optr[5] = m.matrix[1][1]; optr[6] = m.matrix[1][2]; optr[7] = m.matrix[1][3]; optr[8] = m.matrix[2][0]; optr[9] = m.matrix[2][1]; optr[10] = m.matrix[2][2]; optr[11] = m.matrix[2][3]; optr[12] = m.matrix[3][0]; optr[13] = m.matrix[3][1]; optr[14] = m.matrix[3][2]; optr[15] = m.matrix[3][3]; #endif } } else { MObject value; plug.getValue(value); MFnMatrixArrayData fn(value); for(uint32_t i = 0, n = fn.length(); i < n; ++i) { float* optr = values + i * 16; double* iptr = &fn[i].matrix[0][0]; #if AL_UTILS_ENABLE_SIMD # ifdef __AVX__ const f128 m0 = cvt4d_to_4f(loadu4d(iptr)); const f128 m1 = cvt4d_to_4f(loadu4d(iptr + 4)); const f128 m2 = cvt4d_to_4f(loadu4d(iptr + 8)); const f128 m3 = cvt4d_to_4f(loadu4d(iptr + 12)); # else const f128 m0a = cvt2d_to_2f(loadu2d(iptr)); const f128 m0b = cvt2d_to_2f(loadu2d(iptr + 2)); const f128 m1a = cvt2d_to_2f(loadu2d(iptr + 4)); const f128 m1b = cvt2d_to_2f(loadu2d(iptr + 6)); const f128 m2a = cvt2d_to_2f(loadu2d(iptr + 8)); const f128 m2b = cvt2d_to_2f(loadu2d(iptr + 10)); const f128 m3a = cvt2d_to_2f(loadu2d(iptr + 12)); const f128 m3b = cvt2d_to_2f(loadu2d(iptr + 14)); const f128 m0 = movelh4f(m0a, m0b); const f128 m1 = movelh4f(m1a, m1b); const f128 m2 = movelh4f(m2a, m2b); const f128 m3 = movelh4f(m3a, m3b); # endif storeu4f(optr, m0); storeu4f(optr + 4, m1); storeu4f(optr + 8, m2); storeu4f(optr + 12, m3); #else for(int k = 0; k < 16; ++k) { optr[k] = iptr[k]; } #endif } } return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::getMatrix4x4Array(MObject node, MObject attribute, double* const values, const size_t count) { MPlug plug(node, attribute); if(!plug) return MS::kFailure; if(plug.isArray()) { uint32_t num = plug.numElements(); if(num != count) { MGlobal::displayError("array is sized incorrectly"); return MS::kFailure; } MFnMatrixData fn; MObject elementValue; for(uint32_t i = 0, j = 0; i < count; ++i, j += 16) { plug.elementByLogicalIndex(i).getValue(elementValue); fn.setObject(elementValue); const MMatrix& m = fn.matrix(); #if AL_UTILS_ENABLE_SIMD # ifdef __AVX__ double* optr = values + j; storeu4d(optr + 0, loadu4d(&m.matrix[0][0])); storeu4d(optr + 4, loadu4d(&m.matrix[1][0])); storeu4d(optr + 8, loadu4d(&m.matrix[2][0])); storeu4d(optr + 12, loadu4d(&m.matrix[3][0])); # else double* optr = values + j; storeu2d(optr + 0, loadu2d(&m.matrix[0][0])); storeu2d(optr + 2, loadu2d(&m.matrix[0][2])); storeu2d(optr + 4, loadu2d(&m.matrix[1][0])); storeu2d(optr + 6, loadu2d(&m.matrix[1][2])); storeu2d(optr + 8, loadu2d(&m.matrix[2][0])); storeu2d(optr + 10, loadu2d(&m.matrix[2][2])); storeu2d(optr + 12, loadu2d(&m.matrix[3][0])); storeu2d(optr + 14, loadu2d(&m.matrix[3][2])); # endif #else double* optr = values + j; optr[0] = m.matrix[0][0]; optr[1] = m.matrix[0][1]; optr[2] = m.matrix[0][2]; optr[3] = m.matrix[0][3]; optr[4] = m.matrix[1][0]; optr[5] = m.matrix[1][1]; optr[6] = m.matrix[1][2]; optr[7] = m.matrix[1][3]; optr[8] = m.matrix[2][0]; optr[9] = m.matrix[2][1]; optr[10] = m.matrix[2][2]; optr[11] = m.matrix[2][3]; optr[12] = m.matrix[3][0]; optr[13] = m.matrix[3][1]; optr[14] = m.matrix[3][2]; optr[15] = m.matrix[3][3]; #endif } } else { MObject value; plug.getValue(value); MFnMatrixArrayData fn(value); for(uint32_t i = 0, n = fn.length(); i < n; ++i) { double* optr = values + i * 16; double* iptr = &fn[i].matrix[0][0]; #if AL_UTILS_ENABLE_SIMD # ifdef __AVX__ storeu4d(optr, loadu4d(iptr)); storeu4d(optr + 4, loadu4d(iptr + 4)); storeu4d(optr + 8, loadu4d(iptr + 8)); storeu4d(optr + 12, loadu4d(iptr + 12)); # else storeu2d(optr , loadu2d(iptr)); storeu2d(optr + 2, loadu2d(iptr + 2)); storeu2d(optr + 4, loadu2d(iptr + 4)); storeu2d(optr + 6, loadu2d(iptr + 6)); storeu2d(optr + 8, loadu2d(iptr + 8)); storeu2d(optr + 10, loadu2d(iptr + 10)); storeu2d(optr + 12, loadu2d(iptr + 12)); storeu2d(optr + 14, loadu2d(iptr + 14)); # endif #else for(uint32_t k = 0; k < 16; ++k) { optr[k] = iptr[k]; } #endif } } return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::getTimeArray(MObject node, MObject attribute, float* const values, const size_t count, MTime::Unit unit) { const MTime mod(1.0, MTime::k6000FPS); const float unitConversion = float(mod.as(unit)); MPlug plug(node, attribute); if(!plug || !plug.isArray()) return MS::kFailure; uint32_t num = plug.numElements(); if(num != count) { MGlobal::displayError("array is sized incorrectly"); return MS::kFailure; } #if AL_UTILS_ENABLE_SIMD #if defined(__AVX__) && ENABLE_SOME_AVX_ROUTINES const f256 unitConversion256 = splat8f(unitConversion); const f128 unitConversion128 = splat4f(unitConversion); uint32_t count8 = count & ~0x7; uint32_t i = 0; for(; i < count8; i += 8) { ALIGN32(float temp[8]); temp[0] = plug.elementByLogicalIndex(i).asFloat(); temp[1] = plug.elementByLogicalIndex(i + 1).asFloat(); temp[2] = plug.elementByLogicalIndex(i + 2).asFloat(); temp[3] = plug.elementByLogicalIndex(i + 3).asFloat(); temp[4] = plug.elementByLogicalIndex(i + 4).asFloat(); temp[5] = plug.elementByLogicalIndex(i + 5).asFloat(); temp[6] = plug.elementByLogicalIndex(i + 6).asFloat(); temp[7] = plug.elementByLogicalIndex(i + 7).asFloat(); storeu8f(values + i, mul8f(unitConversion256, load8f(temp))); } if(count & 0x4) { ALIGN16(float temp[4]); temp[0] = plug.elementByLogicalIndex(i).asFloat(); temp[1] = plug.elementByLogicalIndex(i + 1).asFloat(); temp[2] = plug.elementByLogicalIndex(i + 2).asFloat(); temp[3] = plug.elementByLogicalIndex(i + 3).asFloat(); storeu4f(values + i, mul4f(unitConversion128, load4f(temp))); i += 4; } #else const f128 unitConversion128 = splat4f(unitConversion); uint32_t count4 = count & ~0x3; uint32_t i = 0; for(; i < count4; i += 4) { ALIGN16(float temp[4]); temp[0] = plug.elementByLogicalIndex(i).asFloat(); temp[1] = plug.elementByLogicalIndex(i + 1).asFloat(); temp[2] = plug.elementByLogicalIndex(i + 2).asFloat(); temp[3] = plug.elementByLogicalIndex(i + 3).asFloat(); storeu4f(values + i, mul4f(unitConversion128, load4f(temp))); } #endif switch(count & 3) { case 3: values[i + 2] = unitConversion * plug.elementByLogicalIndex(i + 2).asFloat(); case 2: values[i + 1] = unitConversion * plug.elementByLogicalIndex(i + 1).asFloat(); case 1: values[i ] = unitConversion * plug.elementByLogicalIndex(i ).asFloat(); default: break; } #else for(uint32_t i = 0; i < num; ++i) { values[i] = unitConversion * plug.elementByLogicalIndex(i).asFloat(); } #endif return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::getAngleArray(MObject node, MObject attribute, float* const values, const size_t count, MAngle::Unit unit) { const MAngle mod(1.0, MAngle::internalUnit()); const float unitConversion = float(mod.as(unit)); MPlug plug(node, attribute); if(!plug || !plug.isArray()) return MS::kFailure; uint32_t num = plug.numElements(); if(num != count) { MGlobal::displayError("array is sized incorrectly"); return MS::kFailure; } #if AL_UTILS_ENABLE_SIMD #if defined(__AVX__) && ENABLE_SOME_AVX_ROUTINES const f256 unitConversion256 = splat8f(unitConversion); const f128 unitConversion128 = splat4f(unitConversion); uint32_t count8 = count & ~0x7; uint32_t i = 0; for(; i < count8; i += 8) { ALIGN32(float temp[8]); temp[0] = plug.elementByLogicalIndex(i).asFloat(); temp[1] = plug.elementByLogicalIndex(i + 1).asFloat(); temp[2] = plug.elementByLogicalIndex(i + 2).asFloat(); temp[3] = plug.elementByLogicalIndex(i + 3).asFloat(); temp[4] = plug.elementByLogicalIndex(i + 4).asFloat(); temp[5] = plug.elementByLogicalIndex(i + 5).asFloat(); temp[6] = plug.elementByLogicalIndex(i + 6).asFloat(); temp[7] = plug.elementByLogicalIndex(i + 7).asFloat(); storeu8f(values + i, mul8f(unitConversion256, load8f(temp))); } if(count & 0x4) { ALIGN16(float temp[4]); temp[0] = plug.elementByLogicalIndex(i).asFloat(); temp[1] = plug.elementByLogicalIndex(i + 1).asFloat(); temp[2] = plug.elementByLogicalIndex(i + 2).asFloat(); temp[3] = plug.elementByLogicalIndex(i + 3).asFloat(); storeu4f(values + i, mul4f(unitConversion128, load4f(temp))); i += 4; } #else const f128 unitConversion128 = splat4f(unitConversion); uint32_t count4 = count & ~0x3; uint32_t i = 0; for(; i < count4; i += 4) { ALIGN16(float temp[4]); temp[0] = plug.elementByLogicalIndex(i).asFloat(); temp[1] = plug.elementByLogicalIndex(i + 1).asFloat(); temp[2] = plug.elementByLogicalIndex(i + 2).asFloat(); temp[3] = plug.elementByLogicalIndex(i + 3).asFloat(); storeu4f(values + i, mul4f(unitConversion128, load4f(temp))); } #endif switch(count & 3) { case 3: values[i + 2] = unitConversion * plug.elementByLogicalIndex(i + 2).asFloat(); case 2: values[i + 1] = unitConversion * plug.elementByLogicalIndex(i + 1).asFloat(); case 1: values[i] = unitConversion * plug.elementByLogicalIndex(i).asFloat(); default: break; } #else for(uint32_t i = 0; i < num; ++i) { values[i] = unitConversion * plug.elementByLogicalIndex(i).asFloat(); } #endif return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::getDistanceArray(MObject node, MObject attribute, float* const values, const size_t count, MDistance::Unit unit) { const MDistance mod(1.0, MDistance::internalUnit()); const float unitConversion = float(mod.as(unit)); MPlug plug(node, attribute); if(!plug || !plug.isArray()) return MS::kFailure; uint32_t num = plug.numElements(); if(num != count) { MGlobal::displayError("array is sized incorrectly"); return MS::kFailure; } #if AL_UTILS_ENABLE_SIMD #if defined(__AVX__) && ENABLE_SOME_AVX_ROUTINES const f256 unitConversion256 = splat8f(unitConversion); const f128 unitConversion128 = splat4f(unitConversion); uint32_t count8 = count & ~0x7; uint32_t i = 0; for(; i < count8; i += 8) { ALIGN32(float temp[8]); temp[0] = plug.elementByLogicalIndex(i).asFloat(); temp[1] = plug.elementByLogicalIndex(i + 1).asFloat(); temp[2] = plug.elementByLogicalIndex(i + 2).asFloat(); temp[3] = plug.elementByLogicalIndex(i + 3).asFloat(); temp[4] = plug.elementByLogicalIndex(i + 4).asFloat(); temp[5] = plug.elementByLogicalIndex(i + 5).asFloat(); temp[6] = plug.elementByLogicalIndex(i + 6).asFloat(); temp[7] = plug.elementByLogicalIndex(i + 7).asFloat(); storeu8f(values + i, mul8f(unitConversion256, load8f(temp))); } if(count & 0x4) { ALIGN16(float temp[4]); temp[0] = plug.elementByLogicalIndex(i).asFloat(); temp[1] = plug.elementByLogicalIndex(i + 1).asFloat(); temp[2] = plug.elementByLogicalIndex(i + 2).asFloat(); temp[3] = plug.elementByLogicalIndex(i + 3).asFloat(); storeu4f(values + i, mul4f(unitConversion128, load4f(temp))); i += 4; } #else const f128 unitConversion128 = splat4f(unitConversion); uint32_t count4 = count & ~0x3; uint32_t i = 0; for(; i < count4; i += 4) { ALIGN16(float temp[4]); temp[0] = plug.elementByLogicalIndex(i).asFloat(); temp[1] = plug.elementByLogicalIndex(i + 1).asFloat(); temp[2] = plug.elementByLogicalIndex(i + 2).asFloat(); temp[3] = plug.elementByLogicalIndex(i + 3).asFloat(); storeu4f(values + i, mul4f(unitConversion128, load4f(temp))); } #endif switch(count & 3) { case 3: values[i + 2] = unitConversion * plug.elementByLogicalIndex(i + 2).asFloat(); case 2: values[i + 1] = unitConversion * plug.elementByLogicalIndex(i + 1).asFloat(); case 1: values[i] = unitConversion * plug.elementByLogicalIndex(i).asFloat(); default: break; } #else for(uint32_t i = 0; i < num; ++i) { values[i] = unitConversion * plug.elementByLogicalIndex(i).asFloat(); } #endif return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::setString(MObject node, MObject attr, const std::string& str) { return setString(node, attr, str.c_str()); } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::setVec2(MObject node, MObject attr, const int* const xy) { const char* const errorString = "vec2i error"; MPlug plug(node, attr); AL_MAYA_CHECK_ERROR(plug.child(0).setValue(xy[0]), errorString); AL_MAYA_CHECK_ERROR(plug.child(1).setValue(xy[1]), errorString); return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::setVec2(MObject node, MObject attr, const float* const xy) { const char* const errorString = "vec2f error"; MPlug plug(node, attr); AL_MAYA_CHECK_ERROR(plug.child(0).setValue(xy[0]), errorString); AL_MAYA_CHECK_ERROR(plug.child(1).setValue(xy[1]), errorString); return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::setVec2(MObject node, MObject attr, const GfHalf* const xy) { const char* const errorString = "vec2h error"; MPlug plug(node, attr); AL_MAYA_CHECK_ERROR(plug.child(0).setValue(AL::usd::utils::float2half_1f(xy[0])), errorString); AL_MAYA_CHECK_ERROR(plug.child(1).setValue(AL::usd::utils::float2half_1f(xy[1])), errorString); return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::setVec2(MObject node, MObject attr, const double* const xy) { const char* const errorString = "vec2d error"; MPlug plug(node, attr); AL_MAYA_CHECK_ERROR(plug.child(0).setValue(xy[0]), errorString); AL_MAYA_CHECK_ERROR(plug.child(1).setValue(xy[1]), errorString); return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::setVec3(MObject node, MObject attr, const int* const xyz) { const char* const errorString = "vec3i error"; MPlug plug(node, attr); AL_MAYA_CHECK_ERROR(plug.child(0).setValue(xyz[0]), errorString); AL_MAYA_CHECK_ERROR(plug.child(1).setValue(xyz[1]), errorString); AL_MAYA_CHECK_ERROR(plug.child(2).setValue(xyz[2]), errorString); return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::setVec3(MObject node, MObject attr, const float* const xyz) { const char* const errorString = "vec3f error"; MPlug plug(node, attr); AL_MAYA_CHECK_ERROR(plug.child(0).setValue(xyz[0]), errorString); AL_MAYA_CHECK_ERROR(plug.child(1).setValue(xyz[1]), errorString); AL_MAYA_CHECK_ERROR(plug.child(2).setValue(xyz[2]), errorString); return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::setVec3(MObject node, MObject attr, const GfHalf* const xyz) { const char* const errorString = "vec3h error"; MPlug plug(node, attr); AL_MAYA_CHECK_ERROR(plug.child(0).setValue(AL::usd::utils::float2half_1f(xyz[0])), errorString); AL_MAYA_CHECK_ERROR(plug.child(1).setValue(AL::usd::utils::float2half_1f(xyz[1])), errorString); AL_MAYA_CHECK_ERROR(plug.child(2).setValue(AL::usd::utils::float2half_1f(xyz[2])), errorString); return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::setVec3(MObject node, MObject attr, const double* const xyz) { const char* const errorString = "vec3d error"; MPlug plug(node, attr); AL_MAYA_CHECK_ERROR(plug.child(0).setValue(xyz[0]), errorString); AL_MAYA_CHECK_ERROR(plug.child(1).setValue(xyz[1]), errorString); AL_MAYA_CHECK_ERROR(plug.child(2).setValue(xyz[2]), errorString); return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::setVec4(MObject node, MObject attr, const int* const xyzw) { const char* const errorString = "vec4i error"; MPlug plug(node, attr); AL_MAYA_CHECK_ERROR(plug.child(0).setValue(xyzw[0]), errorString); AL_MAYA_CHECK_ERROR(plug.child(1).setValue(xyzw[1]), errorString); AL_MAYA_CHECK_ERROR(plug.child(2).setValue(xyzw[2]), errorString); AL_MAYA_CHECK_ERROR(plug.child(3).setValue(xyzw[3]), errorString); return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::setVec4(MObject node, MObject attr, const float* const xyzw) { const char* const errorString = "vec4f error"; MPlug plug(node, attr); AL_MAYA_CHECK_ERROR(plug.child(0).setValue(xyzw[0]), errorString); AL_MAYA_CHECK_ERROR(plug.child(1).setValue(xyzw[1]), errorString); AL_MAYA_CHECK_ERROR(plug.child(2).setValue(xyzw[2]), errorString); AL_MAYA_CHECK_ERROR(plug.child(3).setValue(xyzw[3]), errorString); return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::setVec4(MObject node, MObject attr, const double* const xyzw) { const char* const errorString = "vec4d error"; MPlug plug(node, attr); AL_MAYA_CHECK_ERROR(plug.child(0).setValue(xyzw[0]), errorString); AL_MAYA_CHECK_ERROR(plug.child(1).setValue(xyzw[1]), errorString); AL_MAYA_CHECK_ERROR(plug.child(2).setValue(xyzw[2]), errorString); AL_MAYA_CHECK_ERROR(plug.child(3).setValue(xyzw[3]), errorString); return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::setVec4(MObject node, MObject attr, const GfHalf* const xyzw) { const char* const errorString = "vec4h error"; MPlug plug(node, attr); AL_MAYA_CHECK_ERROR(plug.child(0).setValue(AL::usd::utils::float2half_1f(xyzw[0])), errorString); AL_MAYA_CHECK_ERROR(plug.child(1).setValue(AL::usd::utils::float2half_1f(xyzw[1])), errorString); AL_MAYA_CHECK_ERROR(plug.child(2).setValue(AL::usd::utils::float2half_1f(xyzw[2])), errorString); AL_MAYA_CHECK_ERROR(plug.child(3).setValue(AL::usd::utils::float2half_1f(xyzw[3])), errorString); return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::setQuat(MObject node, MObject attr, const float* const xyzw) { const char* const errorString = "quatf error"; MPlug plug(node, attr); AL_MAYA_CHECK_ERROR(plug.child(0).setValue(xyzw[0]), errorString); AL_MAYA_CHECK_ERROR(plug.child(1).setValue(xyzw[1]), errorString); AL_MAYA_CHECK_ERROR(plug.child(2).setValue(xyzw[2]), errorString); AL_MAYA_CHECK_ERROR(plug.child(3).setValue(xyzw[3]), errorString); return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::setQuat(MObject node, MObject attr, const double* const xyzw) { const char* const errorString = "quatd error"; MPlug plug(node, attr); AL_MAYA_CHECK_ERROR(plug.child(0).setValue(xyzw[0]), errorString); AL_MAYA_CHECK_ERROR(plug.child(1).setValue(xyzw[1]), errorString); AL_MAYA_CHECK_ERROR(plug.child(2).setValue(xyzw[2]), errorString); AL_MAYA_CHECK_ERROR(plug.child(3).setValue(xyzw[3]), errorString); return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::setQuat(MObject node, MObject attr, const GfHalf* const xyzw) { const char* const errorString = "quath error"; MPlug plug(node, attr); AL_MAYA_CHECK_ERROR(plug.child(0).setValue(AL::usd::utils::float2half_1f(xyzw[0])), errorString); AL_MAYA_CHECK_ERROR(plug.child(1).setValue(AL::usd::utils::float2half_1f(xyzw[1])), errorString); AL_MAYA_CHECK_ERROR(plug.child(2).setValue(AL::usd::utils::float2half_1f(xyzw[2])), errorString); AL_MAYA_CHECK_ERROR(plug.child(3).setValue(AL::usd::utils::float2half_1f(xyzw[3])), errorString); return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::setString(MObject node, MObject attr, const char* const str) { const char* const errorString = "string error"; MPlug plug(node, attr); AL_MAYA_CHECK_ERROR(plug.setString(str), errorString); return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::setMatrix4x4(MObject node, MObject attr, const double* const str) { const char* const errorString = "matrix4x4 error - unimplemented"; MPlug plug(node, attr); MFnMatrixData fn; typedef double hack[4]; MObject data = fn.create(MMatrix((const hack*)str)); AL_MAYA_CHECK_ERROR(plug.setValue(data), errorString); return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::setMatrix4x4(MObject node, MObject attr, const float* const ptr) { const char* const errorString = "matrix4x4 error - unimplemented"; MPlug plug(node, attr); MFnMatrixData fn; MMatrix m; #if AL_UTILS_ENABLE_SIMD # if __AVX__ const f256 d0 = loadu8f(ptr); const f256 d1 = loadu8f(ptr + 8); storeu4d(&m.matrix[0][0], cvt4f_to_4d(extract4f(d0, 0))); storeu4d(&m.matrix[1][0], cvt4f_to_4d(extract4f(d0, 1))); storeu4d(&m.matrix[2][0], cvt4f_to_4d(extract4f(d1, 0))); storeu4d(&m.matrix[3][0], cvt4f_to_4d(extract4f(d1, 1))); # else const f128 d0 = loadu4f(ptr); const f128 d1 = loadu4f(ptr + 4); const f128 d2 = loadu4f(ptr + 8); const f128 d3 = loadu4f(ptr + 12); storeu2d(&m.matrix[0][0], cvt2f_to_2d(d0)); storeu2d(&m.matrix[0][2], cvt2f_to_2d(movehl4f(d0, d0))); storeu2d(&m.matrix[1][0], cvt2f_to_2d(d1)); storeu2d(&m.matrix[1][2], cvt2f_to_2d(movehl4f(d1, d1))); storeu2d(&m.matrix[2][0], cvt2f_to_2d(d2)); storeu2d(&m.matrix[2][2], cvt2f_to_2d(movehl4f(d2, d2))); storeu2d(&m.matrix[3][0], cvt2f_to_2d(d3)); storeu2d(&m.matrix[3][2], cvt2f_to_2d(movehl4f(d3, d3))); # endif #else m[0][0] = ptr[0]; m[0][1] = ptr[1]; m[0][2] = ptr[2]; m[0][3] = ptr[3]; m[1][0] = ptr[4]; m[1][1] = ptr[5]; m[1][2] = ptr[6]; m[1][3] = ptr[7]; m[2][0] = ptr[8]; m[2][1] = ptr[9]; m[2][2] = ptr[10]; m[2][3] = ptr[11]; m[3][0] = ptr[12]; m[3][1] = ptr[13]; m[3][2] = ptr[14]; m[3][3] = ptr[15]; #endif MObject data = fn.create(m); AL_MAYA_CHECK_ERROR(plug.setValue(data), errorString); return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::setMatrix3x3(MObject node, MObject attr, const double* const str) { const char* const errorString = "matrix3x3 error"; MPlug plug(node, attr); AL_MAYA_CHECK_ERROR(plug.child(0).child(0).setValue(str[0]), errorString); AL_MAYA_CHECK_ERROR(plug.child(0).child(1).setValue(str[1]), errorString); AL_MAYA_CHECK_ERROR(plug.child(0).child(2).setValue(str[2]), errorString); AL_MAYA_CHECK_ERROR(plug.child(1).child(0).setValue(str[3]), errorString); AL_MAYA_CHECK_ERROR(plug.child(1).child(1).setValue(str[4]), errorString); AL_MAYA_CHECK_ERROR(plug.child(1).child(2).setValue(str[5]), errorString); AL_MAYA_CHECK_ERROR(plug.child(2).child(0).setValue(str[6]), errorString); AL_MAYA_CHECK_ERROR(plug.child(2).child(1).setValue(str[7]), errorString); AL_MAYA_CHECK_ERROR(plug.child(2).child(2).setValue(str[8]), errorString); return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::setMatrix3x3(MObject node, MObject attr, const float* const str) { const char* const errorString = "matrix3x3 error"; MPlug plug(node, attr); AL_MAYA_CHECK_ERROR(plug.child(0).child(0).setValue(str[0]), errorString); AL_MAYA_CHECK_ERROR(plug.child(0).child(1).setValue(str[1]), errorString); AL_MAYA_CHECK_ERROR(plug.child(0).child(2).setValue(str[2]), errorString); AL_MAYA_CHECK_ERROR(plug.child(1).child(0).setValue(str[3]), errorString); AL_MAYA_CHECK_ERROR(plug.child(1).child(1).setValue(str[4]), errorString); AL_MAYA_CHECK_ERROR(plug.child(1).child(2).setValue(str[5]), errorString); AL_MAYA_CHECK_ERROR(plug.child(2).child(0).setValue(str[6]), errorString); AL_MAYA_CHECK_ERROR(plug.child(2).child(1).setValue(str[7]), errorString); AL_MAYA_CHECK_ERROR(plug.child(2).child(2).setValue(str[8]), errorString); return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::setMatrix2x2(MObject node, MObject attr, const double* const str) { const char* const errorString = "matrix2x2 error"; MPlug plug(node, attr); AL_MAYA_CHECK_ERROR(plug.child(0).child(0).setValue(str[0]), errorString); AL_MAYA_CHECK_ERROR(plug.child(0).child(1).setValue(str[1]), errorString); AL_MAYA_CHECK_ERROR(plug.child(1).child(0).setValue(str[2]), errorString); AL_MAYA_CHECK_ERROR(plug.child(1).child(1).setValue(str[3]), errorString); return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::setMatrix2x2(MObject node, MObject attr, const float* const str) { const char* const errorString = "matrix2x2 error"; MPlug plug(node, attr); AL_MAYA_CHECK_ERROR(plug.child(0).child(0).setValue(str[0]), errorString); AL_MAYA_CHECK_ERROR(plug.child(0).child(1).setValue(str[1]), errorString); AL_MAYA_CHECK_ERROR(plug.child(1).child(0).setValue(str[2]), errorString); AL_MAYA_CHECK_ERROR(plug.child(1).child(1).setValue(str[3]), errorString); return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::setMatrix2x2Array(MObject node, MObject attribute, const double* const values, const size_t count) { const char* const errorString = "setMatrix2x2Array error"; MPlug arrayPlug(node, attribute); arrayPlug.setNumElements(count); for(uint32_t i = 0; i < count; ++i) { const double* const str = values + i * 4; MPlug plug = arrayPlug.elementByLogicalIndex(i); AL_MAYA_CHECK_ERROR(plug.child(0).child(0).setValue(str[0]), errorString); AL_MAYA_CHECK_ERROR(plug.child(0).child(1).setValue(str[1]), errorString); AL_MAYA_CHECK_ERROR(plug.child(1).child(0).setValue(str[2]), errorString); AL_MAYA_CHECK_ERROR(plug.child(1).child(1).setValue(str[3]), errorString); } return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::setMatrix2x2Array(MObject node, MObject attribute, const float* const values, const size_t count) { const char* const errorString = "setMatrix2x2Array error"; MPlug arrayPlug(node, attribute); arrayPlug.setNumElements(count); for(uint32_t i = 0; i < count; ++i) { const float* const str = values + i * 4; MPlug plug = arrayPlug.elementByLogicalIndex(i); AL_MAYA_CHECK_ERROR(plug.child(0).child(0).setValue(str[0]), errorString); AL_MAYA_CHECK_ERROR(plug.child(0).child(1).setValue(str[1]), errorString); AL_MAYA_CHECK_ERROR(plug.child(1).child(0).setValue(str[2]), errorString); AL_MAYA_CHECK_ERROR(plug.child(1).child(1).setValue(str[3]), errorString); } return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::setMatrix3x3Array(MObject node, MObject attribute, const double* const values, const size_t count) { const char* const errorString = "setMatrix3x3Array error"; MPlug arrayPlug(node, attribute); arrayPlug.setNumElements(count); for(uint32_t i = 0; i < count; ++i) { const double* const str = values + i * 9; MPlug plug = arrayPlug.elementByLogicalIndex(i); AL_MAYA_CHECK_ERROR(plug.child(0).child(0).setValue(str[0]), errorString); AL_MAYA_CHECK_ERROR(plug.child(0).child(1).setValue(str[1]), errorString); AL_MAYA_CHECK_ERROR(plug.child(0).child(2).setValue(str[2]), errorString); AL_MAYA_CHECK_ERROR(plug.child(1).child(0).setValue(str[3]), errorString); AL_MAYA_CHECK_ERROR(plug.child(1).child(1).setValue(str[4]), errorString); AL_MAYA_CHECK_ERROR(plug.child(1).child(2).setValue(str[5]), errorString); AL_MAYA_CHECK_ERROR(plug.child(2).child(0).setValue(str[6]), errorString); AL_MAYA_CHECK_ERROR(plug.child(2).child(1).setValue(str[7]), errorString); AL_MAYA_CHECK_ERROR(plug.child(2).child(2).setValue(str[8]), errorString); } return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::setMatrix3x3Array(MObject node, MObject attribute, const float* const values, const size_t count) { const char* const errorString = "setMatrix3x3Array error"; MPlug arrayPlug(node, attribute); arrayPlug.setNumElements(count); for(uint32_t i = 0; i < count; ++i) { const float* const str = values + i * 9; MPlug plug = arrayPlug.elementByLogicalIndex(i); AL_MAYA_CHECK_ERROR(plug.child(0).child(0).setValue(str[0]), errorString); AL_MAYA_CHECK_ERROR(plug.child(0).child(1).setValue(str[1]), errorString); AL_MAYA_CHECK_ERROR(plug.child(0).child(2).setValue(str[2]), errorString); AL_MAYA_CHECK_ERROR(plug.child(1).child(0).setValue(str[3]), errorString); AL_MAYA_CHECK_ERROR(plug.child(1).child(1).setValue(str[4]), errorString); AL_MAYA_CHECK_ERROR(plug.child(1).child(2).setValue(str[5]), errorString); AL_MAYA_CHECK_ERROR(plug.child(2).child(0).setValue(str[6]), errorString); AL_MAYA_CHECK_ERROR(plug.child(2).child(1).setValue(str[7]), errorString); AL_MAYA_CHECK_ERROR(plug.child(2).child(2).setValue(str[8]), errorString); } return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::setStringArray(MObject node, MObject attribute, const std::string* const values, const size_t count) { const char* const errorString = "DgNodeHelper::setStringArray error"; MPlug plug(node, attribute); if(!plug) { MGlobal::displayError(errorString); return MS::kFailure; } plug.setNumElements(count); for(uint32_t i = 0; i < count; ++i) { MPlug elem = plug.elementByLogicalIndex(i); elem.setString(MString(values[i].c_str(), values[i].size())); } return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::setQuatArray(MObject node, MObject attr, const GfHalf* const values, const size_t count) { return setVec4Array(node, attr, values, count); } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::setQuatArray(MObject node, MObject attr, const float* const values, const size_t count) { return setVec4Array(node, attr, values, count); } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::setQuatArray(MObject node, MObject attr, const double* const values, const size_t count) { return setVec4Array(node, attr, values, count); } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::getFloat(MObject node, MObject attr, float& value) { const char* const errorString = "DgNodeHelper::getFloat error"; MPlug plug(node, attr); if(!plug) { MGlobal::displayError(errorString); return MS::kFailure; } return plug.getValue(value); } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::getDouble(MObject node, MObject attr, double& value) { const char* const errorString = "DgNodeHelper::getDouble error"; MPlug plug(node, attr); if(!plug) { MGlobal::displayError(errorString); return MS::kFailure; } return plug.getValue(value); } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::getTime(MObject node, MObject attr, MTime& value) { const char* const errorString = "DgNodeHelper::getTime error"; MPlug plug(node, attr); if(!plug) { MGlobal::displayError(errorString); return MS::kFailure; } return plug.getValue(value); } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::getDistance(MObject node, MObject attr, MDistance& value) { const char* const errorString = "DgNodeHelper::getDistance error"; MPlug plug(node, attr); if(!plug) { MGlobal::displayError(errorString); return MS::kFailure; } return plug.getValue(value); } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::getAngle(MObject node, MObject attr, MAngle& value) { const char* const errorString = "DgNodeHelper::getAngle error"; MPlug plug(node, attr); if(!plug) { MGlobal::displayError(errorString); return MS::kFailure; } return plug.getValue(value); } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::getBool(MObject node, MObject attr, bool& value) { const char* const errorString = "DgNodeHelper::getBool error"; MPlug plug(node, attr); if(!plug) { MGlobal::displayError(errorString); return MS::kFailure; } return plug.getValue(value); } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::getInt8(MObject node, MObject attr, int8_t& value) { const char* const errorString = "DgNodeHelper::getInt32 error"; MPlug plug(node, attr); if(!plug) { MGlobal::displayError(errorString); return MS::kFailure; } char c; MStatus status = plug.getValue(c); value = c; return status; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::getInt16(MObject node, MObject attr, int16_t& value) { const char* const errorString = "DgNodeHelper::getInt32 error"; MPlug plug(node, attr); if(!plug) { MGlobal::displayError(errorString); return MS::kFailure; } return plug.getValue(value); } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::getInt32(MObject node, MObject attr, int32_t& value) { const char* const errorString = "DgNodeHelper::getInt32 error"; MPlug plug(node, attr); if(!plug) { MGlobal::displayError(errorString); return MS::kFailure; } return plug.getValue(value); } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::getInt64(MObject node, MObject attr, int64_t& value) { const char* const errorString = "DgNodeHelper::getInt32 error"; MPlug plug(node, attr); if(!plug) { MGlobal::displayError(errorString); return MS::kFailure; } MStatus status; #if MAYA_API_VERSION >= 201800 value = plug.asInt64(&status); #else value = plug.asInt64(MDGContext::fsNormal, &status); #endif return status; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::getMatrix2x2(MObject node, MObject attr, float* const str) { const char* const errorString = "DgNodeHelper::getMatrix2x2 error"; MPlug plug(node, attr); if(!plug) { MGlobal::displayError(errorString); return MS::kFailure; } AL_MAYA_CHECK_ERROR(plug.child(0).child(0).getValue(str[0]), errorString); AL_MAYA_CHECK_ERROR(plug.child(0).child(1).getValue(str[1]), errorString); AL_MAYA_CHECK_ERROR(plug.child(1).child(0).getValue(str[2]), errorString); AL_MAYA_CHECK_ERROR(plug.child(1).child(1).getValue(str[3]), errorString); return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::getMatrix3x3(MObject node, MObject attr, float* const str) { const char* const errorString = "getMatrix3x3 error"; MPlug plug(node, attr); if(!plug) { MGlobal::displayError(errorString); return MS::kFailure; } AL_MAYA_CHECK_ERROR(plug.child(0).child(0).getValue(str[0]), errorString); AL_MAYA_CHECK_ERROR(plug.child(0).child(1).getValue(str[1]), errorString); AL_MAYA_CHECK_ERROR(plug.child(0).child(2).getValue(str[2]), errorString); AL_MAYA_CHECK_ERROR(plug.child(1).child(0).getValue(str[3]), errorString); AL_MAYA_CHECK_ERROR(plug.child(1).child(1).getValue(str[4]), errorString); AL_MAYA_CHECK_ERROR(plug.child(1).child(2).getValue(str[5]), errorString); AL_MAYA_CHECK_ERROR(plug.child(2).child(0).getValue(str[6]), errorString); AL_MAYA_CHECK_ERROR(plug.child(2).child(1).getValue(str[7]), errorString); AL_MAYA_CHECK_ERROR(plug.child(2).child(2).getValue(str[8]), errorString); return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::getMatrix4x4(MObject node, MObject attr, float* const values) { const char* const errorString = "DgNodeHelper::getMatrix4x4 error"; MPlug plug(node, attr); if(!plug) { MGlobal::displayError(errorString); return MS::kFailure; } MObject data; AL_MAYA_CHECK_ERROR(plug.getValue(data), errorString); MFnMatrixData fn(data); const MMatrix& mat = fn.matrix(); #if AL_UTILS_ENABLE_SIMD # ifdef __AVX__ const f128 r0 = cvt4d_to_4f(loadu4d(&mat.matrix[0][0])); const f128 r1 = cvt4d_to_4f(loadu4d(&mat.matrix[1][0])); const f128 r2 = cvt4d_to_4f(loadu4d(&mat.matrix[2][0])); const f128 r3 = cvt4d_to_4f(loadu4d(&mat.matrix[3][0])); # else const f128 r0 = movelh4f( cvt2d_to_2f(loadu2d(&mat.matrix[0][0])), cvt2d_to_2f(loadu2d(&mat.matrix[0][2]))); const f128 r1 = movelh4f( cvt2d_to_2f(loadu2d(&mat.matrix[1][0])), cvt2d_to_2f(loadu2d(&mat.matrix[1][2]))); const f128 r2 = movelh4f( cvt2d_to_2f(loadu2d(&mat.matrix[2][0])), cvt2d_to_2f(loadu2d(&mat.matrix[2][2]))); const f128 r3 = movelh4f( cvt2d_to_2f(loadu2d(&mat.matrix[3][0])), cvt2d_to_2f(loadu2d(&mat.matrix[3][2]))); # endif storeu4f(values, r0); storeu4f(values + 4, r1); storeu4f(values + 8, r2); storeu4f(values + 12, r3); #else values[0] = mat.matrix[0][0]; values[1] = mat.matrix[0][1]; values[2] = mat.matrix[0][2]; values[3] = mat.matrix[0][3]; values[4] = mat.matrix[1][0]; values[5] = mat.matrix[1][1]; values[6] = mat.matrix[1][2]; values[7] = mat.matrix[1][3]; values[8] = mat.matrix[2][0]; values[9] = mat.matrix[2][1]; values[10] = mat.matrix[2][2]; values[11] = mat.matrix[2][3]; values[12] = mat.matrix[3][0]; values[13] = mat.matrix[3][1]; values[14] = mat.matrix[3][2]; values[15] = mat.matrix[3][3]; #endif return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::getMatrix2x2(MObject node, MObject attr, double* const str) { const char* const errorString = "DgNodeHelper::getMatrix2x2 error"; MPlug plug(node, attr); if(!plug) { MGlobal::displayError(errorString); return MS::kFailure; } AL_MAYA_CHECK_ERROR(plug.child(0).child(0).getValue(str[0]), errorString); AL_MAYA_CHECK_ERROR(plug.child(0).child(1).getValue(str[1]), errorString); AL_MAYA_CHECK_ERROR(plug.child(1).child(0).getValue(str[2]), errorString); AL_MAYA_CHECK_ERROR(plug.child(1).child(1).getValue(str[3]), errorString); return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::getMatrix3x3(MObject node, MObject attr, double* const str) { const char* const errorString = "DgNodeHelper::getMatrix3x3 error"; MPlug plug(node, attr); if(!plug) { MGlobal::displayError(errorString); return MS::kFailure; } AL_MAYA_CHECK_ERROR(plug.child(0).child(0).getValue(str[0]), errorString); AL_MAYA_CHECK_ERROR(plug.child(0).child(1).getValue(str[1]), errorString); AL_MAYA_CHECK_ERROR(plug.child(0).child(2).getValue(str[2]), errorString); AL_MAYA_CHECK_ERROR(plug.child(1).child(0).getValue(str[3]), errorString); AL_MAYA_CHECK_ERROR(plug.child(1).child(1).getValue(str[4]), errorString); AL_MAYA_CHECK_ERROR(plug.child(1).child(2).getValue(str[5]), errorString); AL_MAYA_CHECK_ERROR(plug.child(2).child(0).getValue(str[6]), errorString); AL_MAYA_CHECK_ERROR(plug.child(2).child(1).getValue(str[7]), errorString); AL_MAYA_CHECK_ERROR(plug.child(2).child(2).getValue(str[8]), errorString); return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::getMatrix4x4(MObject node, MObject attr, double* const values) { const char* const errorString = "DgNodeHelper::getMatrix4x4 error"; MPlug plug(node, attr); if(!plug) { MGlobal::displayError(errorString); return MS::kFailure; } MObject data; AL_MAYA_CHECK_ERROR(plug.getValue(data), errorString); MFnMatrixData fn(data); const MMatrix& mat = fn.matrix(); #if AL_UTILS_ENABLE_SIMD # ifdef __AVX__ const d256 r0 = loadu4d(&mat.matrix[0][0]); const d256 r1 = loadu4d(&mat.matrix[1][0]); const d256 r2 = loadu4d(&mat.matrix[2][0]); const d256 r3 = loadu4d(&mat.matrix[3][0]); storeu4d(values, r0); storeu4d(values + 4, r1); storeu4d(values + 8, r2); storeu4d(values + 12, r3); # else const d128 r0a = loadu2d(&mat.matrix[0][0]); const d128 r0b = loadu2d(&mat.matrix[0][2]); const d128 r1a = loadu2d(&mat.matrix[1][0]); const d128 r1b = loadu2d(&mat.matrix[1][2]); const d128 r2a = loadu2d(&mat.matrix[2][0]); const d128 r2b = loadu2d(&mat.matrix[2][2]); const d128 r3a = loadu2d(&mat.matrix[3][0]); const d128 r3b = loadu2d(&mat.matrix[3][2]); storeu2d(values, r0a); storeu2d(values + 2, r0b); storeu2d(values + 4, r1a); storeu2d(values + 6, r1b); storeu2d(values + 8, r2a); storeu2d(values + 10, r2b); storeu2d(values + 12, r3a); storeu2d(values + 14, r3b); # endif #else values[0] = mat.matrix[0][0]; values[1] = mat.matrix[0][1]; values[2] = mat.matrix[0][2]; values[3] = mat.matrix[0][3]; values[4] = mat.matrix[1][0]; values[5] = mat.matrix[1][1]; values[6] = mat.matrix[1][2]; values[7] = mat.matrix[1][3]; values[8] = mat.matrix[2][0]; values[9] = mat.matrix[2][1]; values[10] = mat.matrix[2][2]; values[11] = mat.matrix[2][3]; values[12] = mat.matrix[3][0]; values[13] = mat.matrix[3][1]; values[14] = mat.matrix[3][2]; values[15] = mat.matrix[3][3]; #endif return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::getString(MObject node, MObject attr, std::string& str) { const char* const errorString = "DgNodeHelper::getString error"; MPlug plug(node, attr); if(!plug) { MGlobal::displayError(errorString); return MS::kFailure; } MString value; AL_MAYA_CHECK_ERROR(plug.getValue(value), errorString); str.assign(value.asChar(), value.asChar() + value.length()); return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::getVec2(MObject node, MObject attr, int* xy) { const char* const errorString = "DgNodeHelper::getVec2 error"; MPlug plug(node, attr); if(!plug) { MGlobal::displayError(errorString); return MS::kFailure; } AL_MAYA_CHECK_ERROR(plug.child(0).getValue(xy[0]), errorString); AL_MAYA_CHECK_ERROR(plug.child(1).getValue(xy[1]), errorString); return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::getVec2(MObject node, MObject attr, float* xy) { const char* const errorString = "DgNodeHelper::getVec2 error"; MPlug plug(node, attr); if(!plug) { MGlobal::displayError(errorString); return MS::kFailure; } AL_MAYA_CHECK_ERROR(plug.child(0).getValue(xy[0]), errorString); AL_MAYA_CHECK_ERROR(plug.child(1).getValue(xy[1]), errorString); return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::getVec2(MObject node, MObject attr, double* xy) { const char* const errorString = "DgNodeHelper::getVec2 error"; MPlug plug(node, attr); if(!plug) { MGlobal::displayError(errorString); return MS::kFailure; } AL_MAYA_CHECK_ERROR(plug.child(0).getValue(xy[0]), errorString); AL_MAYA_CHECK_ERROR(plug.child(1).getValue(xy[1]), errorString); return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::getVec2(MObject node, MObject attr, GfHalf* xy) { float fxy[2]; MStatus status = getVec2(node, attr, fxy); xy[0] = AL::usd::utils::float2half_1f(fxy[0]); xy[1] = AL::usd::utils::float2half_1f(fxy[1]); return status; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::getVec3(MObject node, MObject attr, int* xyz) { const char* const errorString = "DgNodeHelper::getVec3 error"; MPlug plug(node, attr); if(!plug) { MGlobal::displayError(errorString); return MS::kFailure; } AL_MAYA_CHECK_ERROR(plug.child(0).getValue(xyz[0]), errorString); AL_MAYA_CHECK_ERROR(plug.child(1).getValue(xyz[1]), errorString); AL_MAYA_CHECK_ERROR(plug.child(2).getValue(xyz[2]), errorString); return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::getVec3(MObject node, MObject attr, float* xyz) { const char* const errorString = "DgNodeHelper::getVec3 error"; MPlug plug(node, attr); if(!plug) { MGlobal::displayError(errorString); return MS::kFailure; } AL_MAYA_CHECK_ERROR(plug.child(0).getValue(xyz[0]), errorString); AL_MAYA_CHECK_ERROR(plug.child(1).getValue(xyz[1]), errorString); AL_MAYA_CHECK_ERROR(plug.child(2).getValue(xyz[2]), errorString); return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::getVec3(MObject node, MObject attr, double* xyz) { const char* const errorString = "DgNodeHelper::getVec3 error"; MPlug plug(node, attr); if(!plug) { MGlobal::displayError(errorString); return MS::kFailure; } AL_MAYA_CHECK_ERROR(plug.child(0).getValue(xyz[0]), errorString); AL_MAYA_CHECK_ERROR(plug.child(1).getValue(xyz[1]), errorString); AL_MAYA_CHECK_ERROR(plug.child(2).getValue(xyz[2]), errorString); return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::getVec3(MObject node, MObject attr, GfHalf* xyz) { float fxyz[4]; GfHalf xyzw[4]; MStatus status = getVec3(node, attr, fxyz); AL::usd::utils::float2half_4f(fxyz, xyzw); xyz[0] = xyzw[0]; xyz[1] = xyzw[1]; xyz[2] = xyzw[2]; return status; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::getVec4(MObject node, MObject attr, int* xyzw) { const char* const errorString = "DgNodeHelper::getVec4 error"; MPlug plug(node, attr); if(!plug) { MGlobal::displayError(errorString); return MS::kFailure; } AL_MAYA_CHECK_ERROR(plug.child(0).getValue(xyzw[0]), errorString); AL_MAYA_CHECK_ERROR(plug.child(1).getValue(xyzw[1]), errorString); AL_MAYA_CHECK_ERROR(plug.child(2).getValue(xyzw[2]), errorString); AL_MAYA_CHECK_ERROR(plug.child(3).getValue(xyzw[3]), errorString); return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::getVec4(MObject node, MObject attr, float* xyzw) { const char* const errorString = "DgNodeHelper::getVec4 error"; MPlug plug(node, attr); if(!plug) { MGlobal::displayError(errorString); return MS::kFailure; } AL_MAYA_CHECK_ERROR(plug.child(0).getValue(xyzw[0]), errorString); AL_MAYA_CHECK_ERROR(plug.child(1).getValue(xyzw[1]), errorString); AL_MAYA_CHECK_ERROR(plug.child(2).getValue(xyzw[2]), errorString); AL_MAYA_CHECK_ERROR(plug.child(3).getValue(xyzw[3]), errorString); return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::getVec4(MObject node, MObject attr, double* xyzw) { const char* const errorString = "DgNodeHelper::getVec4 error"; MPlug plug(node, attr); if(!plug) { MGlobal::displayError(errorString); return MS::kFailure; } AL_MAYA_CHECK_ERROR(plug.child(0).getValue(xyzw[0]), errorString); AL_MAYA_CHECK_ERROR(plug.child(1).getValue(xyzw[1]), errorString); AL_MAYA_CHECK_ERROR(plug.child(2).getValue(xyzw[2]), errorString); AL_MAYA_CHECK_ERROR(plug.child(3).getValue(xyzw[3]), errorString); return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::getVec4(MObject node, MObject attr, GfHalf* xyzw) { float fxyzw[4]; MStatus status = getVec4(node, attr, fxyzw); AL::usd::utils::float2half_4f(fxyzw, xyzw); return status; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::getQuat(MObject node, MObject attr, float* xyzw) { return getVec4(node, attr, xyzw); } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::getQuat(MObject node, MObject attr, double* xyzw) { return getVec4(node, attr, xyzw); } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::getQuat(MObject node, MObject attr, GfHalf* xyzw) { return getVec4(node, attr, xyzw); } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::getUsdBoolArray(const MObject& node, const MObject& attr, VtArray<bool>& values) { // // Handle the oddity that is std::vector<bool> // MPlug plug(node, attr); if(!plug || !plug.isArray()) return MS::kFailure; uint32_t num = plug.numElements(); values.resize(num); for(uint32_t i = 0; i < num; ++i) { values[i] = plug.elementByLogicalIndex(i).asBool(); } return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::getStringArray(MObject node, MObject attr, std::string* const values, const size_t count) { const char* const errorString = "DgNodeHelper::getStringArray"; MPlug plug(node, attr); if(!plug) { MGlobal::displayError(errorString); return MS::kFailure; } if(count != plug.numElements()) { return MS::kFailure; } for(size_t i = 0; i < count; ++i) { const MString& str = plug.elementByLogicalIndex(i).asString(); values[i].assign(str.asChar(), str.length()); } return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::addStringValue(MObject node, const char* const attrName, const char* const stringValue) { MFnTypedAttribute fnT; MObject attribute = fnT.create(attrName, attrName, MFnData::kString); fnT.setArray(false); fnT.setReadable(true); fnT.setWritable(true); MFnDependencyNode fn(node); if(fn.addAttribute(attribute)) { MPlug plug(node, attribute); plug.setValue(stringValue); return MS::kSuccess; } return MS::kFailure; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::setMatrix4x4(MObject node, MObject attr, const MFloatMatrix& value) { return setMatrix4x4(node, attr, &value[0][0]); } MStatus DgNodeHelper::setMatrix4x4(MObject node, MObject attr, const MMatrix& value) { return setMatrix4x4(node, attr, &value[0][0]); } MStatus DgNodeHelper::getMatrix4x4(MObject node, MObject attr, MFloatMatrix& value) { return getMatrix4x4(node, attr, &value[0][0]); } MStatus DgNodeHelper::getMatrix4x4(MObject node, MObject attr, MMatrix& value) { return getMatrix4x4(node, attr, &value[0][0]); } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::copyBool(MObject node, MObject attr, const UsdAttribute& value) { if(value.IsAuthored() && value.HasValue()) { bool data; value.Get<bool> (&data); return setBool(node, attr, data); } return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::copyFloat(MObject node, MObject attr, const UsdAttribute& value) { if(value.IsAuthored() && value.HasValue()) { float data; value.Get<float> (&data); return setFloat(node, attr, data); } return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::copyDouble(MObject node, MObject attr, const UsdAttribute& value) { if(value.IsAuthored() && value.HasValue()) { double data; value.Get<double> (&data); return setDouble(node, attr, data); } return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::copyInt(MObject node, MObject attr, const UsdAttribute& value) { if(value.IsAuthored() && value.HasValue()) { int data; value.Get<int> (&data); return setBool(node, attr, data); } return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::copyVec3(MObject node, MObject attr, const UsdAttribute& value) { if(value.IsAuthored() && value.HasValue()) { int data; value.Get<int> (&data); return setBool(node, attr, data); } return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::addDynamicAttribute(MObject node, const UsdAttribute& usdAttr) { const SdfValueTypeName typeName = usdAttr.GetTypeName(); const bool isArray = typeName.IsArray(); const UsdDataType dataType = getAttributeType(usdAttr); MObject attribute = MObject::kNullObj; const char* attrName = usdAttr.GetName().GetString().c_str(); const uint32_t flags = (isArray ? AL::maya::utils::NodeHelper::kArray : 0) | AL::maya::utils::NodeHelper::kReadable | AL::maya::utils::NodeHelper::kWritable | AL::maya::utils::NodeHelper::kStorable | AL::maya::utils::NodeHelper::kConnectable; switch(dataType) { case UsdDataType::kAsset: { return MS::kSuccess; } break; case UsdDataType::kBool: { AL::maya::utils::NodeHelper::addBoolAttr(node, attrName, attrName, false, flags, &attribute); } break; case UsdDataType::kUChar: { AL::maya::utils::NodeHelper::addInt8Attr(node, attrName, attrName, 0, flags, &attribute); } break; case UsdDataType::kInt: case UsdDataType::kUInt: { AL::maya::utils::NodeHelper::addInt32Attr(node, attrName, attrName, 0, flags, &attribute); } break; case UsdDataType::kInt64: case UsdDataType::kUInt64: { AL::maya::utils::NodeHelper::addInt64Attr(node, attrName, attrName, 0, flags, &attribute); } break; case UsdDataType::kHalf: case UsdDataType::kFloat: { AL::maya::utils::NodeHelper::addFloatAttr(node, attrName, attrName, 0, flags, &attribute); } break; case UsdDataType::kDouble: { AL::maya::utils::NodeHelper::addDoubleAttr(node, attrName, attrName, 0, flags, &attribute); } break; case UsdDataType::kString: { AL::maya::utils::NodeHelper::addStringAttr(node, attrName, attrName, flags, true, &attribute); } break; case UsdDataType::kMatrix2d: { const float defValue[2][2] = {{0, 0}, {0, 0}}; AL::maya::utils::NodeHelper::addMatrix2x2Attr(node, attrName, attrName, defValue, flags, &attribute); } break; case UsdDataType::kMatrix3d: { const float defValue[3][3] = {{0, 0, 0}, {0, 0, 0}, {0, 0, 0}}; AL::maya::utils::NodeHelper::addMatrix3x3Attr(node, attrName, attrName, defValue, flags, &attribute); } break; case UsdDataType::kMatrix4d: { AL::maya::utils::NodeHelper::addMatrixAttr(node, attrName, attrName, MMatrix(), flags, &attribute); } break; case UsdDataType::kQuatd: { AL::maya::utils::NodeHelper::addVec4dAttr(node, attrName, attrName, flags, &attribute); } break; case UsdDataType::kQuatf: case UsdDataType::kQuath: { AL::maya::utils::NodeHelper::addVec4fAttr(node, attrName, attrName, flags, &attribute); } break; case UsdDataType::kVec2d: { AL::maya::utils::NodeHelper::addVec2dAttr(node, attrName, attrName, flags, &attribute); } break; case UsdDataType::kVec2f: case UsdDataType::kVec2h: { AL::maya::utils::NodeHelper::addVec2fAttr(node, attrName, attrName, flags, &attribute); } break; case UsdDataType::kVec2i: { AL::maya::utils::NodeHelper::addVec2iAttr(node, attrName, attrName, flags, &attribute); } break; case UsdDataType::kVec3d: { AL::maya::utils::NodeHelper::addVec3dAttr(node, attrName, attrName, flags, &attribute); } break; case UsdDataType::kVec3f: case UsdDataType::kVec3h: { AL::maya::utils::NodeHelper::addVec3fAttr(node, attrName, attrName, flags, &attribute); } break; case UsdDataType::kVec3i: { AL::maya::utils::NodeHelper::addVec3iAttr(node, attrName, attrName, flags, &attribute); } break; case UsdDataType::kVec4d: { AL::maya::utils::NodeHelper::addVec4dAttr(node, attrName, attrName, flags, &attribute); } break; case UsdDataType::kVec4f: case UsdDataType::kVec4h: { AL::maya::utils::NodeHelper::addVec4fAttr(node, attrName, attrName, flags, &attribute); } break; case UsdDataType::kVec4i: { AL::maya::utils::NodeHelper::addVec4iAttr(node, attrName, attrName, flags, &attribute); } break; default: MGlobal::displayError("DgNodeTranslator::addDynamicAttribute - unsupported USD data type"); return MS::kFailure; } if(isArray) { return setArrayMayaValue(node, attribute, usdAttr, dataType); } return setSingleMayaValue(node, attribute, usdAttr, dataType); } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::setMayaValue(MObject node, MObject attr, const UsdAttribute& usdAttr) { const SdfValueTypeName typeName = usdAttr.GetTypeName(); UsdDataType dataType = getAttributeType(usdAttr); if(typeName.IsArray()) { return setArrayMayaValue(node, attr, usdAttr, dataType); } return setSingleMayaValue(node, attr, usdAttr, dataType); } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::setArrayMayaValue(MObject node, MObject attr, const UsdAttribute& usdAttr, const UsdDataType type) { switch(type) { case UsdDataType::kBool: { VtArray<bool> value; usdAttr.Get(&value); return setUsdBoolArray(node, attr, value); } case UsdDataType::kUChar: { VtArray<unsigned char> value; usdAttr.Get(&value); return setInt8Array(node, attr, (const int8_t*)value.cdata(), value.size()); } case UsdDataType::kInt: { VtArray<int32_t> value; usdAttr.Get(&value); return setInt32Array(node, attr, (const int32_t*)value.cdata(), value.size()); } case UsdDataType::kUInt: { VtArray<uint32_t> value; usdAttr.Get(&value); return setInt32Array(node, attr, (const int32_t*)value.cdata(), value.size()); } case UsdDataType::kInt64: { VtArray<int64_t> value; usdAttr.Get(&value); return setInt64Array(node, attr, (const int64_t*)value.cdata(), value.size()); } case UsdDataType::kUInt64: { VtArray<uint64_t> value; usdAttr.Get(&value); return setInt64Array(node, attr, (const int64_t*)value.cdata(), value.size()); } case UsdDataType::kHalf: { VtArray<GfHalf> value; usdAttr.Get(&value); return setHalfArray(node, attr, (const GfHalf*)value.cdata(), value.size()); } case UsdDataType::kFloat: { VtArray<float> value; usdAttr.Get(&value); return setFloatArray(node, attr, (const float*)value.cdata(), value.size()); } case UsdDataType::kDouble: { VtArray<double> value; usdAttr.Get(&value); return setDoubleArray(node, attr, (const double*)value.cdata(), value.size()); } case UsdDataType::kString: { VtArray<std::string> value; usdAttr.Get(&value); return setStringArray(node, attr, (const std::string*)value.cdata(), value.size()); } case UsdDataType::kMatrix2d: { VtArray<GfMatrix2d> value; usdAttr.Get(&value); return setMatrix2x2Array(node, attr, (const double*)value.cdata(), value.size()); } case UsdDataType::kMatrix3d: { VtArray<GfMatrix3d> value; usdAttr.Get(&value); return setMatrix3x3Array(node, attr, (const double*)value.cdata(), value.size()); } case UsdDataType::kMatrix4d: { VtArray<GfMatrix4d> value; usdAttr.Get(&value); return setMatrix4x4Array(node, attr, (const double*)value.cdata(), value.size()); } case UsdDataType::kQuatd: { VtArray<GfQuatd> value; usdAttr.Get(&value); return setQuatArray(node, attr, (const double*)value.cdata(), value.size()); } case UsdDataType::kQuatf: { VtArray<GfQuatf> value; usdAttr.Get(&value); return setQuatArray(node, attr, (const float*)value.cdata(), value.size()); } case UsdDataType::kQuath: { VtArray<GfQuath> value; usdAttr.Get(&value); return setQuatArray(node, attr, (const GfHalf*)value.cdata(), value.size()); } case UsdDataType::kVec2d: { VtArray<GfVec2d> value; usdAttr.Get(&value); return setVec2Array(node, attr, (const double*)value.cdata(), value.size()); } case UsdDataType::kVec2f: { VtArray<GfVec2f> value; usdAttr.Get(&value); return setVec2Array(node, attr, (const float*)value.cdata(), value.size()); } case UsdDataType::kVec2h: { VtArray<GfVec2h> value; usdAttr.Get(&value); return setVec2Array(node, attr, (const GfHalf*)value.cdata(), value.size()); } case UsdDataType::kVec2i: { VtArray<GfVec2i> value; usdAttr.Get(&value); return setVec2Array(node, attr, (const int32_t*)value.cdata(), value.size()); } case UsdDataType::kVec3d: { VtArray<GfVec3d> value; usdAttr.Get(&value); return setVec3Array(node, attr, (const double*)value.cdata(), value.size()); } case UsdDataType::kVec3f: { VtArray<GfVec3f> value; usdAttr.Get(&value); return setVec3Array(node, attr, (const float*)value.cdata(), value.size()); } case UsdDataType::kVec3h: { VtArray<GfVec3h> value; usdAttr.Get(&value); return setVec3Array(node, attr, (const GfHalf*)value.cdata(), value.size()); } case UsdDataType::kVec3i: { VtArray<GfVec3i> value; usdAttr.Get(&value); return setVec3Array(node, attr, (const int32_t*)value.cdata(), value.size()); } case UsdDataType::kVec4d: { VtArray<GfVec4d> value; usdAttr.Get(&value); return setVec4Array(node, attr, (const double*)value.cdata(), value.size()); } case UsdDataType::kVec4f: { VtArray<GfVec4f> value; usdAttr.Get(&value); return setVec4Array(node, attr, (const float*)value.cdata(), value.size()); } case UsdDataType::kVec4h: { VtArray<GfVec4h> value; usdAttr.Get(&value); return setVec4Array(node, attr, (const GfHalf*)value.cdata(), value.size()); } case UsdDataType::kVec4i: { VtArray<GfVec4i> value; usdAttr.Get(&value); return setVec4Array(node, attr, (const int32_t*)value.cdata(), value.size()); } default: MGlobal::displayError("DgNodeTranslator::setArrayMayaValue - unsupported USD data type"); break; } return MS::kFailure; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::setSingleMayaValue(MObject node, MObject attr, const UsdAttribute& usdAttr, const UsdDataType type) { switch(type) { case UsdDataType::kBool: { bool value; usdAttr.Get<bool>(&value); return setBool(node, attr, value); } case UsdDataType::kUChar: { unsigned char value; usdAttr.Get<unsigned char>(&value); return setInt8(node, attr, value); } case UsdDataType::kInt: { int32_t value; usdAttr.Get<int32_t>(&value); return setInt32(node, attr, value); } case UsdDataType::kUInt: { uint32_t value; usdAttr.Get<uint32_t>(&value); return setInt32(node, attr, value); } case UsdDataType::kInt64: { int64_t value; usdAttr.Get<int64_t>(&value); return setInt64(node, attr, value); } case UsdDataType::kUInt64: { uint64_t value; usdAttr.Get<uint64_t>(&value); return setInt64(node, attr, value); } case UsdDataType::kHalf: { GfHalf value; usdAttr.Get<GfHalf>(&value); return setFloat(node, attr, value); } case UsdDataType::kFloat: { float value; usdAttr.Get<float>(&value); return setFloat(node, attr, value); } case UsdDataType::kDouble: { double value; usdAttr.Get<double>(&value); return setDouble(node, attr, value); } case UsdDataType::kString: { std::string value; usdAttr.Get<std::string>(&value); return setString(node, attr, value.c_str()); } case UsdDataType::kMatrix2d: { GfMatrix2d value; usdAttr.Get<GfMatrix2d>(&value); return setMatrix2x2(node, attr, value.GetArray()); } case UsdDataType::kMatrix3d: { GfMatrix3d value; usdAttr.Get<GfMatrix3d>(&value); return setMatrix3x3(node, attr, value.GetArray()); } case UsdDataType::kMatrix4d: { GfMatrix4d value; usdAttr.Get<GfMatrix4d>(&value); return setMatrix4x4(node, attr, value.GetArray()); } case UsdDataType::kQuatd: { GfQuatd value; usdAttr.Get<GfQuatd>(&value); return setQuat(node, attr, reinterpret_cast<const double*>(&value)); } case UsdDataType::kQuatf: { GfQuatf value; usdAttr.Get<GfQuatf>(&value); return setQuat(node, attr, reinterpret_cast<const float*>(&value)); } case UsdDataType::kQuath: { GfQuath value; usdAttr.Get<GfQuath>(&value); float xyzw[4]; xyzw[0] = value.GetImaginary()[0]; xyzw[1] = value.GetImaginary()[1]; xyzw[2] = value.GetImaginary()[2]; xyzw[3] = value.GetReal(); return setQuat(node, attr, xyzw); } case UsdDataType::kVec2d: { GfVec2d value; usdAttr.Get<GfVec2d>(&value); return setVec2(node, attr, reinterpret_cast<const double*>(&value)); } case UsdDataType::kVec2f: { GfVec2f value; usdAttr.Get<GfVec2f>(&value); return setVec2(node, attr, reinterpret_cast<const float*>(&value)); } case UsdDataType::kVec2h: { GfVec2h value; usdAttr.Get<GfVec2h>(&value); float data[2]; data[0] = value[0]; data[1] = value[1]; return setVec2(node, attr, data); } case UsdDataType::kVec2i: { GfVec2i value; usdAttr.Get<GfVec2i>(&value); return setVec2(node, attr, reinterpret_cast<const int32_t*>(&value)); } case UsdDataType::kVec3d: { GfVec3d value; usdAttr.Get<GfVec3d>(&value); return setVec3(node, attr, reinterpret_cast<const double*>(&value)); } case UsdDataType::kVec3f: { GfVec3f value; usdAttr.Get<GfVec3f>(&value); return setVec3(node, attr, reinterpret_cast<const float*>(&value)); } case UsdDataType::kVec3h: { GfVec3h value; usdAttr.Get<GfVec3h>(&value); return setVec3(node, attr, value[0], value[1], value[2]); } case UsdDataType::kVec3i: { GfVec3i value; usdAttr.Get<GfVec3i>(&value); return setVec3(node, attr, reinterpret_cast<const int32_t*>(&value)); } case UsdDataType::kVec4d: { GfVec4d value; usdAttr.Get<GfVec4d>(&value); return setVec4(node, attr, reinterpret_cast<const double*>(&value)); } case UsdDataType::kVec4f: { GfVec4f value; usdAttr.Get<GfVec4f>(&value); return setVec4(node, attr, reinterpret_cast<const float*>(&value)); } case UsdDataType::kVec4h: { GfVec4h value; usdAttr.Get<GfVec4h>(&value); float xyzw[4]; xyzw[0] = value[0]; xyzw[1] = value[1]; xyzw[2] = value[2]; xyzw[3] = value[3]; return setVec4(node, attr, xyzw); } case UsdDataType::kVec4i: { GfVec4i value; usdAttr.Get<GfVec4i>(&value); return setVec4(node, attr, reinterpret_cast<const int32_t*>(&value)); } default: MGlobal::displayError("DgNodeTranslator::setArrayMayaValue - unsupported USD data type"); break; } return MS::kFailure; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::convertSpecialValueToUSDAttribute(const MPlug& plug, UsdAttribute& usdAttr) { // now we start some hard-coded special attribute value type conversion, no better way found: // interpolateBoundary: This property comes from alembic, in maya it is boolean type: if(usdAttr.GetName() == UsdGeomTokens->interpolateBoundary) { if(plug.asBool()) usdAttr.Set(UsdGeomTokens->edgeAndCorner); else usdAttr.Set(UsdGeomTokens->edgeOnly); return MS::kSuccess; } // more special type conversion rules might come here.. return MS::kFailure; } //---------------------------------------------------------------------------------------------------------------------- MStatus DgNodeHelper::copyDynamicAttributes(MObject node, UsdPrim& prim) { MFnDependencyNode fn(node); uint32_t numAttributes = fn.attributeCount(); for(uint32_t i = 0; i < numAttributes; ++i) { MObject attribute = fn.attribute(i); MPlug plug(node, attribute); // skip child attributes (only export from highest level) if(plug.isChild()) continue; bool isDynamic = plug.isDynamic(); if(isDynamic) { TfToken attributeName = TfToken(plug.partialName(false, false, false, false, false, true).asChar()); // first test if the attribute happen to come with the prim by nature and we have a mapping rule for it: if(prim.HasAttribute(attributeName)) { UsdAttribute usdAttr = prim.GetAttribute(attributeName); // if the conversion works, we are done: if(convertSpecialValueToUSDAttribute(plug, usdAttr)) { continue; } // if not, then we count on CreateAttribute codes below since that will return the USDAttribute if // already exists and hopefully the type conversions below will work. } bool isArray = plug.isArray(); switch(attribute.apiType()) { case MFn::kAttribute2Double: { if(!isArray) { UsdAttribute usdAttr = prim.CreateAttribute(attributeName, SdfValueTypeNames->Double2); GfVec2d m; getVec2(node, attribute, (double*)&m); usdAttr.Set(m); usdAttr.SetCustom(true); } else { UsdAttribute usdAttr = prim.CreateAttribute(attributeName, SdfValueTypeNames->Double2Array); VtArray<GfVec2d> m; m.resize(plug.numElements()); getVec2Array(node, attribute, (double*)m.data(), m.size()); usdAttr.Set(m); usdAttr.SetCustom(true); } } break; case MFn::kAttribute2Float: { if(!isArray) { UsdAttribute usdAttr = prim.CreateAttribute(attributeName, SdfValueTypeNames->Float2); GfVec2f m; getVec2(node, attribute, (float*)&m); usdAttr.Set(m); usdAttr.SetCustom(true); } else { UsdAttribute usdAttr = prim.CreateAttribute(attributeName, SdfValueTypeNames->Float2Array); VtArray<GfVec2f> m; m.resize(plug.numElements()); getVec2Array(node, attribute, (float*)m.data(), m.size()); usdAttr.Set(m); usdAttr.SetCustom(true); } } break; case MFn::kAttribute2Int: case MFn::kAttribute2Short: { if(!isArray) { UsdAttribute usdAttr = prim.CreateAttribute(attributeName, SdfValueTypeNames->Int2); GfVec2i m; getVec2(node, attribute, (int32_t*)&m); usdAttr.Set(m); usdAttr.SetCustom(true); } else { UsdAttribute usdAttr = prim.CreateAttribute(attributeName, SdfValueTypeNames->Int2Array); VtArray<GfVec2i> m; m.resize(plug.numElements()); getVec2Array(node, attribute, (int32_t*)m.data(), m.size()); usdAttr.Set(m); usdAttr.SetCustom(true); } } break; case MFn::kAttribute3Double: { if(!isArray) { UsdAttribute usdAttr = prim.CreateAttribute(attributeName, SdfValueTypeNames->Double3); GfVec3d m; getVec3(node, attribute, (double*)&m); usdAttr.Set(m); usdAttr.SetCustom(true); } else { UsdAttribute usdAttr = prim.CreateAttribute(attributeName, SdfValueTypeNames->Double3Array); VtArray<GfVec3d> m; m.resize(plug.numElements()); getVec3Array(node, attribute, (double*)m.data(), m.size()); usdAttr.Set(m); usdAttr.SetCustom(true); } } break; case MFn::kAttribute3Float: { if(!isArray) { UsdAttribute usdAttr = prim.CreateAttribute(attributeName, SdfValueTypeNames->Float3); GfVec3f m; getVec3(node, attribute, (float*)&m); usdAttr.Set(m); usdAttr.SetCustom(true); } else { UsdAttribute usdAttr = prim.CreateAttribute(attributeName, SdfValueTypeNames->Float3Array); VtArray<GfVec3f> m; m.resize(plug.numElements()); getVec3Array(node, attribute, (float*)m.data(), m.size()); usdAttr.Set(m); usdAttr.SetCustom(true); } } break; case MFn::kAttribute3Long: case MFn::kAttribute3Short: { if(!isArray) { UsdAttribute usdAttr = prim.CreateAttribute(attributeName, SdfValueTypeNames->Int3); GfVec3i m; getVec3(node, attribute, (int32_t*)&m); usdAttr.Set(m); usdAttr.SetCustom(true); } else { UsdAttribute usdAttr = prim.CreateAttribute(attributeName, SdfValueTypeNames->Int3Array); VtArray<GfVec3i> m; m.resize(plug.numElements()); getVec3Array(node, attribute, (int32_t*)m.data(), m.size()); usdAttr.Set(m); usdAttr.SetCustom(true); } } break; case MFn::kAttribute4Double: { if(!isArray) { UsdAttribute usdAttr = prim.CreateAttribute(attributeName, SdfValueTypeNames->Double4); GfVec4d m; getVec4(node, attribute, (double*)&m); usdAttr.Set(m); usdAttr.SetCustom(true); } else { UsdAttribute usdAttr = prim.CreateAttribute(attributeName, SdfValueTypeNames->Double4Array); VtArray<GfVec4d> m; m.resize(plug.numElements()); getVec4Array(node, attribute, (double*)m.data(), m.size()); usdAttr.Set(m); usdAttr.SetCustom(true); } } break; case MFn::kNumericAttribute: { MFnNumericAttribute fn(attribute); switch(fn.unitType()) { case MFnNumericData::kBoolean: { if(!isArray) { UsdAttribute usdAttr = prim.CreateAttribute(attributeName, SdfValueTypeNames->Bool); bool value; getBool(node, attribute, value); usdAttr.Set(value); usdAttr.SetCustom(true); } else { UsdAttribute usdAttr = prim.CreateAttribute(attributeName, SdfValueTypeNames->BoolArray); VtArray<bool> m; m.resize(plug.numElements()); getUsdBoolArray(node, attribute, m); usdAttr.Set(m); usdAttr.SetCustom(true); } } break; case MFnNumericData::kFloat: { if(!isArray) { UsdAttribute usdAttr = prim.CreateAttribute(attributeName, SdfValueTypeNames->Float); float value; getFloat(node, attribute, value); usdAttr.Set(value); usdAttr.SetCustom(true); } else { UsdAttribute usdAttr = prim.CreateAttribute(attributeName, SdfValueTypeNames->FloatArray); VtArray<float> m; m.resize(plug.numElements()); getFloatArray(node, attribute, (float*)m.data(), m.size()); usdAttr.Set(m); usdAttr.SetCustom(true); } } break; case MFnNumericData::kDouble: { if(!isArray) { UsdAttribute usdAttr = prim.CreateAttribute(attributeName, SdfValueTypeNames->Double); double value; getDouble(node, attribute, value); usdAttr.Set(value); usdAttr.SetCustom(true); } else { UsdAttribute usdAttr = prim.CreateAttribute(attributeName, SdfValueTypeNames->DoubleArray); VtArray<double> m; m.resize(plug.numElements()); getDoubleArray(node, attribute, (double*)m.data(), m.size()); usdAttr.Set(m); usdAttr.SetCustom(true); } } break; case MFnNumericData::kInt: case MFnNumericData::kShort: { if(!isArray) { UsdAttribute usdAttr = prim.CreateAttribute(attributeName, SdfValueTypeNames->Int); int32_t value; getInt32(node, attribute, value); usdAttr.Set(value); usdAttr.SetCustom(true); } else { UsdAttribute usdAttr = prim.CreateAttribute(attributeName, SdfValueTypeNames->IntArray); VtArray<int> m; m.resize(plug.numElements()); getInt32Array(node, attribute, (int32_t*)m.data(), m.size()); usdAttr.Set(m); usdAttr.SetCustom(true); } } break; case MFnNumericData::kInt64: { if(!isArray) { UsdAttribute usdAttr = prim.CreateAttribute(attributeName, SdfValueTypeNames->Int64); int64_t value; getInt64(node, attribute, value); usdAttr.Set(value); usdAttr.SetCustom(true); } else { UsdAttribute usdAttr = prim.CreateAttribute(attributeName, SdfValueTypeNames->Int64Array); VtArray<int64_t> m; m.resize(plug.numElements()); getInt64Array(node, attribute, (int64_t*)m.data(), m.size()); usdAttr.Set(m); usdAttr.SetCustom(true); } } break; case MFnNumericData::kByte: case MFnNumericData::kChar: { if(!isArray) { UsdAttribute usdAttr = prim.CreateAttribute(attributeName, SdfValueTypeNames->UChar); int16_t value; getInt16(node, attribute, value); usdAttr.Set(uint8_t(value)); usdAttr.SetCustom(true); } else { UsdAttribute usdAttr = prim.CreateAttribute(attributeName, SdfValueTypeNames->UCharArray); VtArray<uint8_t> m; m.resize(plug.numElements()); getInt8Array(node, attribute, (int8_t*)m.data(), m.size()); usdAttr.Set(m); usdAttr.SetCustom(true); } } break; default: { std::cout << "Unhandled numeric attribute: " << fn.name().asChar() << " " << fn.unitType() << std::endl; } break; } } break; case MFn::kDoubleAngleAttribute: { if(!isArray) { UsdAttribute usdAttr = prim.CreateAttribute(attributeName, SdfValueTypeNames->Double); double value; getDouble(node, attribute, value); usdAttr.Set(value); usdAttr.SetCustom(true); } else { UsdAttribute usdAttr = prim.CreateAttribute(attributeName, SdfValueTypeNames->DoubleArray); VtArray<double> value; value.resize(plug.numElements()); getDoubleArray(node, attribute, (double*)value.data(), value.size()); usdAttr.Set(value); usdAttr.SetCustom(true); } } break; case MFn::kFloatAngleAttribute: { if(!isArray) { UsdAttribute usdAttr = prim.CreateAttribute(attributeName, SdfValueTypeNames->Float); float value; getFloat(node, attribute, value); usdAttr.Set(value); usdAttr.SetCustom(true); } else { UsdAttribute usdAttr = prim.CreateAttribute(attributeName, SdfValueTypeNames->FloatArray); VtArray<float> value; value.resize(plug.numElements()); getFloatArray(node, attribute, (float*)value.data(), value.size()); usdAttr.Set(value); usdAttr.SetCustom(true); } } break; case MFn::kDoubleLinearAttribute: { if(!isArray) { UsdAttribute usdAttr = prim.CreateAttribute(attributeName, SdfValueTypeNames->Double); double value; getDouble(node, attribute, value); usdAttr.Set(value); usdAttr.SetCustom(true); } else { UsdAttribute usdAttr = prim.CreateAttribute(attributeName, SdfValueTypeNames->DoubleArray); VtArray<double> value; value.resize(plug.numElements()); getDoubleArray(node, attribute, (double*)value.data(), value.size()); usdAttr.Set(value); usdAttr.SetCustom(true); } } break; case MFn::kFloatLinearAttribute: { if(!isArray) { UsdAttribute usdAttr = prim.CreateAttribute(attributeName, SdfValueTypeNames->Float); float value; getFloat(node, attribute, value); usdAttr.Set(value); usdAttr.SetCustom(true); } else { UsdAttribute usdAttr = prim.CreateAttribute(attributeName, SdfValueTypeNames->FloatArray); VtArray<float> value; value.resize(plug.numElements()); getFloatArray(node, attribute, (float*)value.data(), value.size()); usdAttr.Set(value); usdAttr.SetCustom(true); } } break; case MFn::kTimeAttribute: { if(!isArray) { UsdAttribute usdAttr = prim.CreateAttribute(attributeName, SdfValueTypeNames->Double); double value; getDouble(node, attribute, value); usdAttr.Set(value); usdAttr.SetCustom(true); } else { UsdAttribute usdAttr = prim.CreateAttribute(attributeName, SdfValueTypeNames->DoubleArray); VtArray<double> value; value.resize(plug.numElements()); getDoubleArray(node, attribute, (double*)value.data(), value.size()); usdAttr.Set(value); usdAttr.SetCustom(true); } } break; case MFn::kEnumAttribute: { if(!isArray) { UsdAttribute usdAttr = prim.CreateAttribute(attributeName, SdfValueTypeNames->Int); int32_t value; getInt32(node, attribute, value); usdAttr.Set(value); usdAttr.SetCustom(true); } else { UsdAttribute usdAttr = prim.CreateAttribute(attributeName, SdfValueTypeNames->IntArray); VtArray<int> m; m.resize(plug.numElements()); getInt32Array(node, attribute, (int32_t*)m.data(), m.size()); usdAttr.Set(m); usdAttr.SetCustom(true); } } break; case MFn::kTypedAttribute: { MFnTypedAttribute fnTyped(plug.attribute()); MFnData::Type type = fnTyped.attrType(); switch(type) { case MFnData::kString: { if(!isArray) { UsdAttribute usdAttr = prim.CreateAttribute(attributeName, SdfValueTypeNames->String); std::string value; getString(node, attribute, value); usdAttr.Set(value); usdAttr.SetCustom(true); } else { UsdAttribute usdAttr = prim.CreateAttribute(attributeName, SdfValueTypeNames->StringArray); VtArray<std::string> value; value.resize(plug.numElements()); getStringArray(node, attribute, (std::string*)value.data(), value.size()); usdAttr.Set(value); usdAttr.SetCustom(true); } } break; case MFnData::kMatrixArray: { MFnMatrixArrayData fnData(plug.asMObject()); UsdAttribute usdAttr = prim.CreateAttribute(attributeName, SdfValueTypeNames->Matrix4dArray); VtArray<GfMatrix4d> m; m.assign((const GfMatrix4d*)&fnData.array()[0], ((const GfMatrix4d*)&fnData.array()[0]) + fnData.array().length()); usdAttr.Set(m); usdAttr.SetCustom(true); } break; default: { std::cout << "Unhandled typed attribute: " << fn.name().asChar() << " " << fn.typeName().asChar() << std::endl; } break; } } break; case MFn::kCompoundAttribute: { MFnCompoundAttribute fnCompound(plug.attribute()); { if(fnCompound.numChildren() == 2) { MObject x = fnCompound.child(0); MObject y = fnCompound.child(1); if(x.apiType() == MFn::kCompoundAttribute && y.apiType() == MFn::kCompoundAttribute) { MFnCompoundAttribute fnCompoundX(x); MFnCompoundAttribute fnCompoundY(y); if(fnCompoundX.numChildren() == 2 && fnCompoundY.numChildren() == 2) { MObject xx = fnCompoundX.child(0); MObject xy = fnCompoundX.child(1); MObject yx = fnCompoundY.child(0); MObject yy = fnCompoundY.child(1); if(xx.apiType() == MFn::kNumericAttribute && xy.apiType() == MFn::kNumericAttribute && yx.apiType() == MFn::kNumericAttribute && yy.apiType() == MFn::kNumericAttribute) { if(!isArray) { UsdAttribute usdAttr = prim.CreateAttribute(attributeName, SdfValueTypeNames->Matrix2d); GfMatrix2d value; getMatrix2x2(node, attribute, (double*)&value); usdAttr.Set(value); usdAttr.SetCustom(true); } else { UsdAttribute usdAttr = prim.CreateAttribute(attributeName, SdfValueTypeNames->Matrix2dArray); VtArray<GfMatrix2d> value; value.resize(plug.numElements()); getMatrix2x2Array(node, attribute, (double*)value.data(), plug.numElements()); usdAttr.Set(value); usdAttr.SetCustom(true); } } } } } else if(fnCompound.numChildren() == 3) { MObject x = fnCompound.child(0); MObject y = fnCompound.child(1); MObject z = fnCompound.child(2); if(x.apiType() == MFn::kCompoundAttribute && y.apiType() == MFn::kCompoundAttribute && z.apiType() == MFn::kCompoundAttribute) { MFnCompoundAttribute fnCompoundX(x); MFnCompoundAttribute fnCompoundY(y); MFnCompoundAttribute fnCompoundZ(z); if(fnCompoundX.numChildren() == 3 && fnCompoundY.numChildren() == 3 && fnCompoundZ.numChildren() == 3) { MObject xx = fnCompoundX.child(0); MObject xy = fnCompoundX.child(1); MObject xz = fnCompoundX.child(2); MObject yx = fnCompoundY.child(0); MObject yy = fnCompoundY.child(1); MObject yz = fnCompoundY.child(2); MObject zx = fnCompoundZ.child(0); MObject zy = fnCompoundZ.child(1); MObject zz = fnCompoundZ.child(2); if(xx.apiType() == MFn::kNumericAttribute && xy.apiType() == MFn::kNumericAttribute && xz.apiType() == MFn::kNumericAttribute && yx.apiType() == MFn::kNumericAttribute && yy.apiType() == MFn::kNumericAttribute && yz.apiType() == MFn::kNumericAttribute && zx.apiType() == MFn::kNumericAttribute && zy.apiType() == MFn::kNumericAttribute && zz.apiType() == MFn::kNumericAttribute) { if(!isArray) { UsdAttribute usdAttr = prim.CreateAttribute(attributeName, SdfValueTypeNames->Matrix3d); GfMatrix3d value; getMatrix3x3(node, attribute, (double*)&value); usdAttr.Set(value); usdAttr.SetCustom(true); } else { UsdAttribute usdAttr = prim.CreateAttribute(attributeName, SdfValueTypeNames->Matrix3dArray); VtArray<GfMatrix3d> value; value.resize(plug.numElements()); getMatrix3x3Array(node, attribute, (double*)value.data(), plug.numElements()); usdAttr.Set(value); usdAttr.SetCustom(true); } } } } } else if(fnCompound.numChildren() == 4) { MObject x = fnCompound.child(0); MObject y = fnCompound.child(1); MObject z = fnCompound.child(2); MObject w = fnCompound.child(3); if(x.apiType() == MFn::kNumericAttribute && y.apiType() == MFn::kNumericAttribute && z.apiType() == MFn::kNumericAttribute && w.apiType() == MFn::kNumericAttribute) { MFnNumericAttribute fnx(x); MFnNumericAttribute fny(y); MFnNumericAttribute fnz(z); MFnNumericAttribute fnw(w); MFnNumericData::Type typex = fnx.unitType(); MFnNumericData::Type typey = fny.unitType(); MFnNumericData::Type typez = fnz.unitType(); MFnNumericData::Type typew = fnw.unitType(); if(typex == typey && typex == typez && typex == typew) { switch(typex) { case MFnNumericData::kInt: { if(!isArray) { UsdAttribute usdAttr = prim.CreateAttribute(attributeName, SdfValueTypeNames->Int4); GfVec4i value; getVec4(node, attribute, (int32_t*)&value); usdAttr.Set(value); usdAttr.SetCustom(true); } else { UsdAttribute usdAttr = prim.CreateAttribute(attributeName, SdfValueTypeNames->Int4Array); VtArray<GfVec4i> value; value.resize(plug.numElements()); getVec4Array(node, attribute, (int32_t*)value.data(), value.size()); usdAttr.Set(value); usdAttr.SetCustom(true); } } break; case MFnNumericData::kFloat: { if(!isArray) { UsdAttribute usdAttr = prim.CreateAttribute(attributeName, SdfValueTypeNames->Float4); GfVec4f value; getVec4(node, attribute, (float*)&value); usdAttr.Set(value); usdAttr.SetCustom(true); } else { UsdAttribute usdAttr = prim.CreateAttribute(attributeName, SdfValueTypeNames->Float4Array); VtArray<GfVec4f> value; value.resize(plug.numElements()); getVec4Array(node, attribute, (float*)value.data(), value.size()); usdAttr.Set(value); usdAttr.SetCustom(true); } } break; case MFnNumericData::kDouble: { if(!isArray) { UsdAttribute usdAttr = prim.CreateAttribute(attributeName, SdfValueTypeNames->Double4); GfVec4d value; getVec4(node, attribute, (double*)&value); usdAttr.Set(value); usdAttr.SetCustom(true); } else { UsdAttribute usdAttr = prim.CreateAttribute(attributeName, SdfValueTypeNames->Double4Array); VtArray<GfVec4d> value; value.resize(plug.numElements()); getVec4Array(node, attribute, (double*)value.data(), value.size()); usdAttr.Set(value); usdAttr.SetCustom(true); } } break; default: break; } } } } } } break; case MFn::kFloatMatrixAttribute: case MFn::kMatrixAttribute: { if(!isArray) { UsdAttribute usdAttr = prim.CreateAttribute(attributeName, SdfValueTypeNames->Matrix4d); GfMatrix4d m; getMatrix4x4(node, attribute, (double*)&m); usdAttr.Set(m); usdAttr.SetCustom(true); } else { UsdAttribute usdAttr = prim.CreateAttribute(attributeName, SdfValueTypeNames->Matrix4dArray); VtArray<GfMatrix4d> value; value.resize(plug.numElements()); getMatrix4x4Array(node, attribute, (double*)value.data(), value.size()); usdAttr.Set(value); usdAttr.SetCustom(true); } } break; default: break; } } } return MS::kSuccess; } //---------------------------------------------------------------------------------------------------------------------- void DgNodeHelper::copySimpleValue(const MPlug& plug, UsdAttribute& usdAttr, const UsdTimeCode& timeCode) { MObject node = plug.node(); MObject attribute = plug.attribute(); bool isArray = plug.isArray(); switch(getAttributeType(usdAttr)) { case UsdDataType::kUChar: if(!isArray) { int8_t value; getInt8(node, attribute, value); usdAttr.Set(uint8_t(value), timeCode); } else { VtArray<uint8_t> m; m.resize(plug.numElements()); getInt8Array(node, attribute, (int8_t*)m.data(), m.size()); usdAttr.Set(m, timeCode); } break; case UsdDataType::kInt: if(!isArray) { int32_t value; getInt32(node, attribute, value); usdAttr.Set(value, timeCode); } else { VtArray<int32_t> m; m.resize(plug.numElements()); getInt32Array(node, attribute, (int32_t*)m.data(), m.size()); usdAttr.Set(m, timeCode); } break; case UsdDataType::kUInt: if(!isArray) { int32_t value; getInt32(node, attribute, value); usdAttr.Set(uint32_t(value), timeCode); } else { VtArray<uint32_t> m; m.resize(plug.numElements()); getInt32Array(node, attribute, (int32_t*)m.data(), m.size()); usdAttr.Set(m, timeCode); } break; case UsdDataType::kInt64: if(!isArray) { int64_t value; getInt64(node, attribute, value); usdAttr.Set(value, timeCode); } else { VtArray<int64_t> m; m.resize(plug.numElements()); getInt64Array(node, attribute, (int64_t*)m.data(), m.size()); usdAttr.Set(m, timeCode); } break; case UsdDataType::kUInt64: if(!isArray) { int64_t value; getInt64(node, attribute, value); usdAttr.Set(value, timeCode); } else { VtArray<int64_t> m; m.resize(plug.numElements()); getInt64Array(node, attribute, (int64_t*)m.data(), m.size()); usdAttr.Set(m, timeCode); } break; case UsdDataType::kFloat: if(!isArray) { float value; getFloat(node, attribute, value); usdAttr.Set(value, timeCode); } else { VtArray<float> m; m.resize(plug.numElements()); getFloatArray(node, attribute, (float*)m.data(), m.size()); usdAttr.Set(m, timeCode); } break; case UsdDataType::kDouble: if(!isArray) { double value; getDouble(node, attribute, value); usdAttr.Set(value, timeCode); } else { VtArray<double> m; m.resize(plug.numElements()); getDoubleArray(node, attribute, (double*)m.data(), m.size()); usdAttr.Set(m, timeCode); } break; case UsdDataType::kHalf: if(!isArray) { GfHalf value; getHalf(node, attribute, value); usdAttr.Set(value, timeCode); } else { VtArray<GfHalf> m; m.resize(plug.numElements()); getHalfArray(node, attribute, (GfHalf*)m.data(), m.size()); usdAttr.Set(m, timeCode); } break; default: break; } } //---------------------------------------------------------------------------------------------------------------------- void DgNodeHelper::copyAttributeValue(const MPlug& plug, UsdAttribute& usdAttr, const UsdTimeCode& timeCode) { MObject node = plug.node(); MObject attribute = plug.attribute(); bool isArray = plug.isArray(); switch(attribute.apiType()) { case MFn::kAttribute2Double: case MFn::kAttribute2Float: case MFn::kAttribute2Int: case MFn::kAttribute2Short: { switch(getAttributeType(usdAttr)) { case UsdDataType::kVec2d: if(!isArray) { GfVec2d m; getVec2(node, attribute, (double*)&m); usdAttr.Set(m, timeCode); } else { VtArray<GfVec2d> m; m.resize(plug.numElements()); getVec2Array(node, attribute, (double*)m.data(), m.size()); usdAttr.Set(m, timeCode); } break; case UsdDataType::kVec2f: if(!isArray) { GfVec2f m; getVec2(node, attribute, (float*)&m); usdAttr.Set(m, timeCode); } else { VtArray<GfVec2f> m; m.resize(plug.numElements()); getVec2Array(node, attribute, (float*)m.data(), m.size()); usdAttr.Set(m, timeCode); } break; case UsdDataType::kVec2i: if(!isArray) { GfVec2i m; getVec2(node, attribute, (int*)&m); usdAttr.Set(m, timeCode); } else { VtArray<GfVec2i> m; m.resize(plug.numElements()); getVec2Array(node, attribute, (int*)m.data(), m.size()); usdAttr.Set(m, timeCode); } break; case UsdDataType::kVec2h: if(!isArray) { GfVec2h m; getVec2(node, attribute, (GfHalf*)&m); usdAttr.Set(m, timeCode); } else { VtArray<GfVec2h> m; m.resize(plug.numElements()); getVec2Array(node, attribute, (GfHalf*)m.data(), m.size()); usdAttr.Set(m, timeCode); } break; default: break; } } break; case MFn::kAttribute3Double: case MFn::kAttribute3Float: case MFn::kAttribute3Long: case MFn::kAttribute3Short: { switch(getAttributeType(usdAttr)) { case UsdDataType::kVec3d: if(!isArray) { GfVec3d m; getVec3(node, attribute, (double*)&m); usdAttr.Set(m, timeCode); } else { VtArray<GfVec3d> m; m.resize(plug.numElements()); getVec3Array(node, attribute, (double*)m.data(), m.size()); usdAttr.Set(m, timeCode); } break; case UsdDataType::kVec3f: if(!isArray) { GfVec3f m; getVec3(node, attribute, (float*)&m); usdAttr.Set(m, timeCode); } else { VtArray<GfVec3f> m; m.resize(plug.numElements()); getVec3Array(node, attribute, (float*)m.data(), m.size()); usdAttr.Set(m, timeCode); } break; case UsdDataType::kVec3i: if(!isArray) { GfVec3i m; getVec3(node, attribute, (int*)&m); usdAttr.Set(m, timeCode); } else { VtArray<GfVec3i> m; m.resize(plug.numElements()); getVec3Array(node, attribute, (int*)m.data(), m.size()); usdAttr.Set(m, timeCode); } break; case UsdDataType::kVec3h: if(!isArray) { GfVec3h m; getVec3(node, attribute, (GfHalf*)&m); usdAttr.Set(m, timeCode); } else { VtArray<GfVec3h> m; m.resize(plug.numElements()); getVec3Array(node, attribute, (GfHalf*)m.data(), m.size()); usdAttr.Set(m, timeCode); } break; default: break; } } break; case MFn::kAttribute4Double: { switch(getAttributeType(usdAttr)) { case UsdDataType::kVec4d: if(!isArray) { GfVec4d m; getVec4(node, attribute, (double*)&m); usdAttr.Set(m, timeCode); } else { VtArray<GfVec4d> m; m.resize(plug.numElements()); getVec4Array(node, attribute, (double*)m.data(), m.size()); usdAttr.Set(m, timeCode); } break; case UsdDataType::kVec4f: if(!isArray) { GfVec4f m; getVec4(node, attribute, (float*)&m); usdAttr.Set(m, timeCode); } else { VtArray<GfVec4f> m; m.resize(plug.numElements()); getVec4Array(node, attribute, (float*)m.data(), m.size()); usdAttr.Set(m, timeCode); } break; case UsdDataType::kVec4i: if(!isArray) { GfVec4i m; getVec4(node, attribute, (int*)&m); usdAttr.Set(m, timeCode); } else { VtArray<GfVec4i> m; m.resize(plug.numElements()); getVec4Array(node, attribute, (int*)m.data(), m.size()); usdAttr.Set(m, timeCode); } break; case UsdDataType::kVec4h: if(!isArray) { GfVec4h m; getVec4(node, attribute, (GfHalf*)&m); usdAttr.Set(m, timeCode); } else { VtArray<GfVec4h> m; m.resize(plug.numElements()); getVec4Array(node, attribute, (GfHalf*)m.data(), m.size()); usdAttr.Set(m, timeCode); } break; default: break; } } break; case MFn::kNumericAttribute: { MFnNumericAttribute fn(attribute); switch(fn.unitType()) { case MFnNumericData::kBoolean: { if(!isArray) { bool value; getBool(node, attribute, value); usdAttr.Set(value, timeCode); } else { VtArray<bool> m; m.resize(plug.numElements()); getUsdBoolArray(node, attribute, m); usdAttr.Set(m, timeCode); } } break; case MFnNumericData::kFloat: case MFnNumericData::kDouble: case MFnNumericData::kInt: case MFnNumericData::kShort: case MFnNumericData::kInt64: case MFnNumericData::kByte: case MFnNumericData::kChar: { copySimpleValue(plug, usdAttr, timeCode); } break; default: { } break; } } break; case MFn::kTimeAttribute: case MFn::kFloatAngleAttribute: case MFn::kDoubleAngleAttribute: case MFn::kDoubleLinearAttribute: case MFn::kFloatLinearAttribute: { copySimpleValue(plug, usdAttr, timeCode); } break; case MFn::kEnumAttribute: { switch(getAttributeType(usdAttr)) { case UsdDataType::kInt: { if(!isArray) { int32_t value; getInt32(node, attribute, value); usdAttr.Set(value, timeCode); } else { VtArray<int> m; m.resize(plug.numElements()); getInt32Array(node, attribute, m.data(), m.size()); usdAttr.Set(m, timeCode); } } } } break; case MFn::kTypedAttribute: { MFnTypedAttribute fnTyped(plug.attribute()); MFnData::Type type = fnTyped.attrType(); switch(type) { case MFnData::kString: { std::string value; getString(node, attribute, value); usdAttr.Set(value, timeCode); } break; case MFnData::kMatrixArray: { MFnMatrixArrayData fnData(plug.asMObject()); VtArray<GfMatrix4d> m; m.assign((const GfMatrix4d*)&fnData.array()[0], ((const GfMatrix4d*)&fnData.array()[0]) + fnData.array().length()); usdAttr.Set(m, timeCode); } break; default: { } break; } } break; case MFn::kCompoundAttribute: { MFnCompoundAttribute fnCompound(plug.attribute()); { if(fnCompound.numChildren() == 2) { MObject x = fnCompound.child(0); MObject y = fnCompound.child(1); if(x.apiType() == MFn::kCompoundAttribute && y.apiType() == MFn::kCompoundAttribute) { MFnCompoundAttribute fnCompoundX(x); MFnCompoundAttribute fnCompoundY(y); if(fnCompoundX.numChildren() == 2 && fnCompoundY.numChildren() == 2) { MObject xx = fnCompoundX.child(0); MObject xy = fnCompoundX.child(1); MObject yx = fnCompoundY.child(0); MObject yy = fnCompoundY.child(1); if(xx.apiType() == MFn::kNumericAttribute && xy.apiType() == MFn::kNumericAttribute && yx.apiType() == MFn::kNumericAttribute && yy.apiType() == MFn::kNumericAttribute) { if(!isArray) { GfMatrix2d value; getMatrix2x2(node, attribute, (double*)&value); usdAttr.Set(value, timeCode); } else { VtArray<GfMatrix2d> value; value.resize(plug.numElements()); getMatrix2x2Array(node, attribute, (double*)value.data(), plug.numElements()); usdAttr.Set(value, timeCode); } } } } } else if(fnCompound.numChildren() == 3) { MObject x = fnCompound.child(0); MObject y = fnCompound.child(1); MObject z = fnCompound.child(2); if(x.apiType() == MFn::kCompoundAttribute && y.apiType() == MFn::kCompoundAttribute && z.apiType() == MFn::kCompoundAttribute) { MFnCompoundAttribute fnCompoundX(x); MFnCompoundAttribute fnCompoundY(y); MFnCompoundAttribute fnCompoundZ(z); if(fnCompoundX.numChildren() == 3 && fnCompoundY.numChildren() == 3 && fnCompoundZ.numChildren() == 3) { MObject xx = fnCompoundX.child(0); MObject xy = fnCompoundX.child(1); MObject xz = fnCompoundX.child(2); MObject yx = fnCompoundY.child(0); MObject yy = fnCompoundY.child(1); MObject yz = fnCompoundY.child(2); MObject zx = fnCompoundZ.child(0); MObject zy = fnCompoundZ.child(1); MObject zz = fnCompoundZ.child(2); if(xx.apiType() == MFn::kNumericAttribute && xy.apiType() == MFn::kNumericAttribute && xz.apiType() == MFn::kNumericAttribute && yx.apiType() == MFn::kNumericAttribute && yy.apiType() == MFn::kNumericAttribute && yz.apiType() == MFn::kNumericAttribute && zx.apiType() == MFn::kNumericAttribute && zy.apiType() == MFn::kNumericAttribute && zz.apiType() == MFn::kNumericAttribute) { if(!isArray) { GfMatrix3d value; getMatrix3x3(node, attribute, (double*)&value); usdAttr.Set(value, timeCode); } else { VtArray<GfMatrix3d> value; value.resize(plug.numElements()); getMatrix3x3Array(node, attribute, (double*)value.data(), plug.numElements()); usdAttr.Set(value, timeCode); } } } } } else if(fnCompound.numChildren() == 4) { MObject x = fnCompound.child(0); MObject y = fnCompound.child(1); MObject z = fnCompound.child(2); MObject w = fnCompound.child(3); if(x.apiType() == MFn::kNumericAttribute && y.apiType() == MFn::kNumericAttribute && z.apiType() == MFn::kNumericAttribute && w.apiType() == MFn::kNumericAttribute) { MFnNumericAttribute fnx(x); MFnNumericAttribute fny(y); MFnNumericAttribute fnz(z); MFnNumericAttribute fnw(w); MFnNumericData::Type typex = fnx.unitType(); MFnNumericData::Type typey = fny.unitType(); MFnNumericData::Type typez = fnz.unitType(); MFnNumericData::Type typew = fnw.unitType(); if(typex == typey && typex == typez && typex == typew) { switch(typex) { case MFnNumericData::kInt: { if(!isArray) { GfVec4i value; getVec4(node, attribute, (int32_t*)&value); usdAttr.Set(value, timeCode); } else { VtArray<GfVec4i> value; value.resize(plug.numElements()); getVec4Array(node, attribute, (int32_t*)value.data(), value.size()); usdAttr.Set(value, timeCode); } } break; case MFnNumericData::kFloat: { if(!isArray) { GfVec4f value; getVec4(node, attribute, (float*)&value); usdAttr.Set(value, timeCode); } else { VtArray<GfVec4f> value; value.resize(plug.numElements()); getVec4Array(node, attribute, (float*)value.data(), value.size()); usdAttr.Set(value, timeCode); } } break; case MFnNumericData::kDouble: { if(!isArray) { GfVec4d value; getVec4(node, attribute, (double*)&value); usdAttr.Set(value, timeCode); } else { VtArray<GfVec4d> value; value.resize(plug.numElements()); getVec4Array(node, attribute, (double*)value.data(), value.size()); usdAttr.Set(value, timeCode); } } break; default: break; } } } } } } break; case MFn::kFloatMatrixAttribute: case MFn::kMatrixAttribute: { if(!isArray) { GfMatrix4d m; getMatrix4x4(node, attribute, (double*)&m); usdAttr.Set(m, timeCode); } else { VtArray<GfMatrix4d> value; value.resize(plug.numElements()); getMatrix4x4Array(node, attribute, (double*)value.data(), value.size()); usdAttr.Set(value, timeCode); } } break; default: break; } } //---------------------------------------------------------------------------------------------------------------------- void DgNodeHelper::copySimpleValue(const MPlug& plug, UsdAttribute& usdAttr, const float scale, const UsdTimeCode& timeCode) { MObject node = plug.node(); MObject attribute = plug.attribute(); bool isArray = plug.isArray(); switch(getAttributeType(usdAttr)) { case UsdDataType::kFloat: if(!isArray) { float value; getFloat(node, attribute, value); usdAttr.Set(value * scale, timeCode); } else { VtArray<float> m; m.resize(plug.numElements()); getFloatArray(node, attribute, (float*)m.data(), m.size()); for(auto it = m.begin(), e = m.end(); it != e; ++it) { *it *= scale; } usdAttr.Set(m, timeCode); } break; case UsdDataType::kDouble: if(!isArray) { double value; getDouble(node, attribute, value); usdAttr.Set(value * scale, timeCode); } else { VtArray<double> m; m.resize(plug.numElements()); getDoubleArray(node, attribute, (double*)m.data(), m.size()); double temp = scale; for(auto it = m.begin(), e = m.end(); it != e; ++it) { *it *= temp; } usdAttr.Set(m, timeCode); } break; default: break; } } //---------------------------------------------------------------------------------------------------------------------- void DgNodeHelper::copyAttributeValue(const MPlug& plug, UsdAttribute& usdAttr, const float scale, const UsdTimeCode& timeCode) { MObject node = plug.node(); MObject attribute = plug.attribute(); bool isArray = plug.isArray(); switch(attribute.apiType()) { case MFn::kAttribute2Double: case MFn::kAttribute2Float: case MFn::kAttribute2Int: case MFn::kAttribute2Short: { switch(getAttributeType(usdAttr)) { case UsdDataType::kVec2d: if(!isArray) { GfVec2d m; getVec2(node, attribute, (double*)&m); m *= scale; usdAttr.Set(m, timeCode); } else { VtArray<GfVec2d> m; m.resize(plug.numElements()); getVec2Array(node, attribute, (double*)m.data(), m.size()); double temp = scale; for(auto it = m.begin(), e = m.end(); it != e; ++it) { *it *= temp; } usdAttr.Set(m, timeCode); } break; case UsdDataType::kVec2f: if(!isArray) { GfVec2f m; getVec2(node, attribute, (float*)&m); m *= scale; usdAttr.Set(m, timeCode); } else { VtArray<GfVec2f> m; m.resize(plug.numElements()); getVec2Array(node, attribute, (float*)m.data(), m.size()); for(auto it = m.begin(), e = m.end(); it != e; ++it) { *it *= scale; } usdAttr.Set(m, timeCode); } break; default: break; } } break; case MFn::kAttribute3Double: case MFn::kAttribute3Float: case MFn::kAttribute3Long: case MFn::kAttribute3Short: { switch(getAttributeType(usdAttr)) { case UsdDataType::kVec3d: if(!isArray) { GfVec3d m; getVec3(node, attribute, (double*)&m); m *= scale; usdAttr.Set(m, timeCode); } else { VtArray<GfVec3d> m; m.resize(plug.numElements()); getVec3Array(node, attribute, (double*)m.data(), m.size()); double temp = scale; for(auto it = m.begin(), e = m.end(); it != e; ++it) { *it *= temp; } usdAttr.Set(m, timeCode); } break; case UsdDataType::kVec3f: if(!isArray) { GfVec3f m; getVec3(node, attribute, (float*)&m); m *= scale; usdAttr.Set(m, timeCode); } else { VtArray<GfVec3f> m; m.resize(plug.numElements()); getVec3Array(node, attribute, (float*)m.data(), m.size()); for(auto it = m.begin(), e = m.end(); it != e; ++it) { *it *= scale; } usdAttr.Set(m, timeCode); } break; default: break; } } break; case MFn::kAttribute4Double: { switch(getAttributeType(usdAttr)) { case UsdDataType::kVec4d: if(!isArray) { GfVec4d m; getVec4(node, attribute, (double*)&m); m *= scale; usdAttr.Set(m, timeCode); } else { VtArray<GfVec4d> m; m.resize(plug.numElements()); getVec4Array(node, attribute, (double*)m.data(), m.size()); double temp = scale; for(auto it = m.begin(), e = m.end(); it != e; ++it) { *it *= temp; } usdAttr.Set(m, timeCode); } break; case UsdDataType::kVec4f: if(!isArray) { GfVec4f m; getVec4(node, attribute, (float*)&m); m *= scale; usdAttr.Set(m, timeCode); } else { VtArray<GfVec4f> m; m.resize(plug.numElements()); getVec4Array(node, attribute, (float*)m.data(), m.size()); for(auto it = m.begin(), e = m.end(); it != e; ++it) { *it *= scale; } usdAttr.Set(m, timeCode); } break; default: break; } } break; case MFn::kNumericAttribute: { MFnNumericAttribute fn(attribute); switch(fn.unitType()) { case MFnNumericData::kFloat: case MFnNumericData::kDouble: case MFnNumericData::kInt: case MFnNumericData::kShort: case MFnNumericData::kInt64: case MFnNumericData::kByte: case MFnNumericData::kChar: { copySimpleValue(plug, usdAttr, scale, timeCode); } break; default: { } break; } } break; case MFn::kTimeAttribute: case MFn::kFloatAngleAttribute: case MFn::kDoubleAngleAttribute: case MFn::kDoubleLinearAttribute: case MFn::kFloatLinearAttribute: { copySimpleValue(plug, usdAttr, scale, timeCode); } break; default: break; } } //---------------------------------------------------------------------------------------------------------------------- } // utils } // usdmaya } // AL //----------------------------------------------------------------------------------------------------------------------
32.766155
151
0.55667
garvitverma
dcc228844073de0aa75390a5ac731493b40ee6f3
8,072
cc
C++
UX/src/Application.cc
frankencode/cc
2923d4e807659d73b91ff05142b33dc251332bea
[ "Zlib" ]
1
2019-07-29T04:07:29.000Z
2019-07-29T04:07:29.000Z
UX/src/Application.cc
frankencode/cc
2923d4e807659d73b91ff05142b33dc251332bea
[ "Zlib" ]
null
null
null
UX/src/Application.cc
frankencode/cc
2923d4e807659d73b91ff05142b33dc251332bea
[ "Zlib" ]
1
2020-03-04T17:13:04.000Z
2020-03-04T17:13:04.000Z
/* * Copyright (C) 2020 Frank Mertens. * * Distribution and use is allowed under the terms of the zlib license * (see cc/LICENSE-zlib). * */ #include <cc/Application> #include <cc/TimeMaster> #include <cc/PlatformPlugin> #include <cc/PosGuard> #include <cc/InputControl> #include <cc/Process> #include <cc/Bmp> #include <cc/stdio> namespace cc { void Application::State::notifyTimer(const Timer &timer) { if (!timer) return; if (timer.interval() > 0) { TimeMaster{}.ack(); } timer.me().timeout_.emit(); } Application::State::State() { textInputArea.onChanged([this]{ if (focusControl()) setTextInputArea(textInputArea()); }); focusControl.onChanged([this]{ if (focusControlSaved_) stopTextInput(); focusControlSaved_ = focusControl(); if (focusControl()) { startTextInput(focusControl().window()); textInputArea([this]{ if (!focusControl()) return Rect{}; Rect a = focusControl().me().textInputArea(); return Rect{focusControl().mapToGlobal(a.pos()), a.size()}; }); setTextInputArea(textInputArea()); } else textInputArea = Rect{}; }); cursorControl.onChanged([this]{ if (cursorControl()) { cursor([this]{ return cursorControl() ? cursorControl().cursor() : Cursor{}; }); } else { cursor = Cursor{}; } }); cursor.onChanged([this]{ if (cursor()) setCursor(cursor()); else unsetCursor(); }); } bool Application::State::feedFingerEvent(const Window &window, FingerEvent &event) { if (cursorControl()) cursorControl = Control{}; if (hoverControl()) hoverControl = Control{}; showCursor(false); Point eventPos = window.size() * event.pos(); Control topControl = window.findControl(eventPos); if (topControl) { topControl->pointerPos = topControl.mapToLocal(eventPos); } if (event.action() == PointerAction::Moved) ; else if (event.action() == PointerAction::Pressed) { if (!pressedControl()) { pressedControl = topControl; } } else if (event.action() == PointerAction::Released) { if (focusControl() != pressedControl()) { focusControl = Control{}; } } bool eaten = false; if (pressedControl()) { eaten = pressedControl()->feedFingerEvent(event); if (event.action() == PointerAction::Released) { PosGuard guard{event, pressedControl().mapToLocal(eventPos)}; if ( pressedControl()->onPointerClicked(event) || pressedControl()->onFingerClicked(event) ) { eaten = true; } pressedControl = Control{}; } } if (!eaten) { eaten = window.view()->feedFingerEvent(event); } return eaten; } bool Application::State::feedMouseEvent(const Window &window, MouseEvent &event) { Control topControl = window.findControl(event.pos()); if (topControl) { topControl->pointerPos = topControl.mapToLocal(event.pos()); } if (event.action() == PointerAction::Moved) { hoverControl = topControl; } else if (event.action() == PointerAction::Pressed) { if (!pressedControl()) { pressedControl = topControl; if (topControl) captureMouse(true); } hoverControl = Control{}; } else if (event.action() == PointerAction::Released) { if (focusControl() != pressedControl()) { focusControl = Control{}; } hoverControl = topControl; } bool eaten = false; if (pressedControl()) { eaten = pressedControl()->feedMouseEvent(event); if (event.action() == PointerAction::Released) { PosGuard guard{event, pressedControl().mapToLocal(event.pos())}; if ( pressedControl()->onPointerClicked(event) || pressedControl()->onMouseClicked(event) ) { eaten = true; } pressedControl = Control{}; captureMouse(false); } } if (!eaten) { eaten = window.view()->feedMouseEvent(event); } cursorControl = topControl; showCursor(true); return eaten; } bool Application::State::feedWheelEvent(const Window &window, WheelEvent &event) { bool eaten = false; if (hoverControl()) eaten = hoverControl().me().feedWheelEvent(event); if (!eaten) eaten = window.view().me().feedWheelEvent(event); return eaten; } bool Application::State::feedKeyEvent(const Window &window, KeyEvent &event) { if ( event.scanCode() == ScanCode::Key_ScrollLock && event.action() == KeyAction::Pressed ) { takeScreenshot(window); return true; } if (focusControl()) { return focusControl().me().feedKeyEvent(event); } if ( event.scanCode() == ScanCode::Key_Tab && event.action() == KeyAction::Pressed && !(event.modifiers() & KeyModifier::Shift) && !(event.modifiers() & KeyModifier::Alt) && !(event.modifiers() & KeyModifier::Control) ) { List<InputControl> inputControls; window.view().collectVisible<InputControl>(&inputControls); if (inputControls.count() > 0) { inputControls.mutableAt(0).focus(true); } } return true; } bool Application::State::feedExposedEvent(const Window &window) { return window.view().me().feedExposedEvent(); } bool Application::State::feedEnterEvent(const Window &window) { return window.view().me().feedEnterEvent(); } bool Application::State::feedLeaveEvent(const Window &window) { hoverControl = Control{}; return window.view().me().feedLeaveEvent(); } bool Application::State::feedTextEditingEvent(const String &text, int start, int length) { if (focusControl()) { focusControl().me().onTextEdited(text, start, length); return true; } return false; } bool Application::State::feedTextInputEvent(const String &text) { if (focusControl()) { focusControl().me().onTextInput(text); return true; } return false; } void Application::State::takeScreenshot(const Window &window) { View view = window.view(); Image image{view.size()}; String path = Format{"%%.bmp"}.arg(fixed(System::now(), 0)); view.renderTo(image); Bmp::save(path, image); ferr() << "Written screenshot to file://" << Process::cwd() << "/" << path << nl; } void Application::State::disengage(const View &view) { if (view.isParentOf(hoverControl())) { hoverControl(Control{}); } if (view.isParentOf(pressedControl())) { pressedControl(Control{}); } if (view.isParentOf(focusControl())) { focusControl(Control{}); } if (view.isParentOf(cursorControl())) { cursorControl(Control{}); } if (view.isParentOf(focusControlSaved_)) { focusControlSaved_ = Control{}; } } Application::Application() { *this = platform().application(); } Application::Application(int argc, char *argv[]) { *this = platform().application(); me().init(argc, argv); } FontSmoothing Application::fontSmoothing() const { if (me().fontSmoothing_ == FontSmoothing::Default) return DisplayManager{}.defaultFontSmoothing(); return me().fontSmoothing_; } bool Application::pointerIsDragged(const PointerEvent &event, Point dragStart) const { double minDragDistance = event.is<MouseEvent>() ? minMouseDragDistance() : minFingerDragDistance(); return (event.pos() - dragStart).absPow2() >= minDragDistance * minDragDistance; } void Application::postEvent(Fun<void()> &&doNext) { me().postEvent(move(doNext)); } Application app() { return platform().application(); } } // namespace cc
24.24024
103
0.594896
frankencode
dcc2f73627d9404a4d8a10bb990a50a1ba28b96b
374
hpp
C++
include/common/cpu_affinity.hpp
JYLeeLYJ/libcoio
2046e3376b9db3e0a8bf19ca5e58c4456b3cd1c2
[ "MIT" ]
null
null
null
include/common/cpu_affinity.hpp
JYLeeLYJ/libcoio
2046e3376b9db3e0a8bf19ca5e58c4456b3cd1c2
[ "MIT" ]
null
null
null
include/common/cpu_affinity.hpp
JYLeeLYJ/libcoio
2046e3376b9db3e0a8bf19ca5e58c4456b3cd1c2
[ "MIT" ]
null
null
null
#ifndef COIO_CPU_AFFINITY #define COIO_CPU_AFFINITY #include <sched.h> #include <sys/syscall.h> #include <unistd.h> namespace coio { static inline bool reset_cpu_affinity(int cpuno) { cpu_set_t mask; CPU_ZERO(&mask); CPU_SET(cpuno, &mask); auto tid = syscall(SYS_gettid); return sched_setaffinity(tid, sizeof(mask), &mask) != -1; } } // namespace coio #endif
17.809524
59
0.721925
JYLeeLYJ
dcc40eb7eb4ca5a842c1d7db4b9ed4e93b1dc0a1
4,395
cc
C++
biod/ec_command_test.cc
kalyankondapally/chromiumos-platform2
5e5337009a65b1c9aa9e0ea565f567438217e91f
[ "BSD-3-Clause" ]
4
2020-07-24T06:54:16.000Z
2021-06-16T17:13:53.000Z
biod/ec_command_test.cc
kalyankondapally/chromiumos-platform2
5e5337009a65b1c9aa9e0ea565f567438217e91f
[ "BSD-3-Clause" ]
1
2021-04-02T17:35:07.000Z
2021-04-02T17:35:07.000Z
biod/ec_command_test.cc
dgreid/platform2
9b8b30df70623c94f1c8aa634dba94195343f37b
[ "BSD-3-Clause" ]
1
2020-11-04T22:31:45.000Z
2020-11-04T22:31:45.000Z
// Copyright 2019 The Chromium OS 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 <gmock/gmock.h> #include <gtest/gtest.h> #include "biod/ec_command.h" using testing::_; using testing::InvokeWithoutArgs; using testing::Return; namespace biod { namespace { constexpr int kDummyFd = 0; constexpr int kIoctlFailureRetVal = -1; template <typename O, typename I> class MockEcCommand : public EcCommand<O, I> { public: using EcCommand<O, I>::EcCommand; ~MockEcCommand() override = default; using Data = typename EcCommand<O, I>::Data; MOCK_METHOD(int, ioctl, (int fd, uint32_t request, Data* data)); }; class MockFpModeCommand : public MockEcCommand<struct ec_params_fp_mode, struct ec_response_fp_mode> { public: MockFpModeCommand() : MockEcCommand(EC_CMD_FP_MODE, 0, {.mode = 1}) {} }; // ioctl behavior for EC commands: // returns sizeof(EC response) (>=0) on success, -1 on failure // cmd.result is error code from EC (EC_RES_SUCCESS, etc) TEST(EcCommand, Run_Success) { MockFpModeCommand mock; EXPECT_CALL(mock, ioctl).WillOnce(Return(mock.RespSize())); EXPECT_TRUE(mock.Run(kDummyFd)); } TEST(EcCommand, Run_IoctlFailure) { MockFpModeCommand mock; EXPECT_CALL(mock, ioctl).WillOnce(Return(kIoctlFailureRetVal)); EXPECT_FALSE(mock.Run(kDummyFd)); } TEST(EcCommand, Run_CommandFailure) { MockFpModeCommand mock; EXPECT_CALL(mock, ioctl) .WillOnce([](int, uint32_t, MockFpModeCommand::Data* data) { // Test the case where the ioctl itself succeeds, the but the EC // command did not. In this case, "result" will be set, but the // response size will not match the command's response size. data->cmd.result = EC_RES_ACCESS_DENIED; return 0; }); EXPECT_FALSE(mock.Run(kDummyFd)); } TEST(EcCommand, ConstReq) { const MockFpModeCommand mock; EXPECT_TRUE(mock.Req()); } TEST(EcCommand, ConstResp) { const MockFpModeCommand mock; EXPECT_TRUE(mock.Resp()); } TEST(EcCommand, Run_CheckResult_Success) { constexpr int kExpectedResult = 42; MockFpModeCommand mock; EXPECT_CALL(mock, ioctl) .WillOnce([](int, uint32_t, MockFpModeCommand::Data* data) { data->cmd.result = kExpectedResult; return data->cmd.insize; }); EXPECT_TRUE(mock.Run(kDummyFd)); EXPECT_EQ(mock.Result(), kExpectedResult); } TEST(EcCommand, Run_CheckResult_Failure) { MockFpModeCommand mock; EXPECT_CALL(mock, ioctl) .WillOnce([](int, uint32_t, MockFpModeCommand::Data* data) { // Note that it's not expected that the result would be set by the // kernel driver in this case, but we want to be defensive against // the behavior in case there is an instance where it does. data->cmd.result = EC_RES_ERROR; return kIoctlFailureRetVal; }); EXPECT_FALSE(mock.Run(kDummyFd)); EXPECT_EQ(mock.Result(), kEcCommandUninitializedResult); } TEST(EcCommand, RunWithMultipleAttempts_Success) { constexpr int kNumAttempts = 2; MockFpModeCommand mock; EXPECT_CALL(mock, ioctl) .Times(kNumAttempts) // First ioctl() fails .WillOnce(InvokeWithoutArgs([]() { errno = ETIMEDOUT; return kIoctlFailureRetVal; })) // Second ioctl() succeeds .WillOnce(Return(mock.RespSize())); EXPECT_TRUE(mock.RunWithMultipleAttempts(kDummyFd, kNumAttempts)); } TEST(EcCommand, RunWithMultipleAttempts_Timeout_Failure) { constexpr int kNumAttempts = 2; MockFpModeCommand mock; EXPECT_CALL(mock, ioctl) .Times(kNumAttempts) // All calls to ioctl() timeout .WillRepeatedly(InvokeWithoutArgs([]() { errno = ETIMEDOUT; return kIoctlFailureRetVal; })); EXPECT_FALSE(mock.RunWithMultipleAttempts(kDummyFd, kNumAttempts)); } TEST(EcCommand, RunWithMultipleAttempts_ErrorNotTimeout_Failure) { constexpr int kNumAttempts = 2; MockFpModeCommand mock; EXPECT_CALL(mock, ioctl) // Errors other than timeout should cause immediate failure even when // attempting retries. .Times(1) .WillOnce(InvokeWithoutArgs([]() { errno = EINVAL; return kIoctlFailureRetVal; })); EXPECT_FALSE(mock.RunWithMultipleAttempts(kDummyFd, kNumAttempts)); } } // namespace } // namespace biod
30.10274
76
0.698521
kalyankondapally
dcc82974b04253cd0551e2a9589bcea8013daf22
3,091
hpp
C++
deps/boost/include/boost/detail/bitmask.hpp
kindlychung/mediasoup-sfu-cpp
f69d2f48f7edbf4f0c57244280a47bea985f39cf
[ "Apache-2.0" ]
995
2018-06-22T10:39:18.000Z
2022-03-25T01:22:14.000Z
deps/boost/include/boost/detail/bitmask.hpp
kindlychung/mediasoup-sfu-cpp
f69d2f48f7edbf4f0c57244280a47bea985f39cf
[ "Apache-2.0" ]
32
2018-06-23T14:19:37.000Z
2022-03-29T10:20:37.000Z
deps/boost/include/boost/detail/bitmask.hpp
kindlychung/mediasoup-sfu-cpp
f69d2f48f7edbf4f0c57244280a47bea985f39cf
[ "Apache-2.0" ]
172
2018-06-22T11:12:00.000Z
2022-03-29T07:44:33.000Z
// boost/detail/bitmask.hpp ------------------------------------------------// // Copyright Beman Dawes 2006 // Distributed under the Boost Software License, Version 1.0 // http://www.boost.org/LICENSE_1_0.txt // Usage: enum foo { a=1, b=2, c=4 }; // BOOST_BITMASK( foo ) // // void f( foo arg ); // ... // f( a | c ); // // See [bitmask.types] in the C++ standard for the formal specification #ifndef BOOST_BITMASK_HPP #define BOOST_BITMASK_HPP #include <boost/config.hpp> #include <boost/cstdint.hpp> #define BOOST_BITMASK(Bitmask) \ \ inline BOOST_CONSTEXPR Bitmask operator| (Bitmask x , Bitmask y ) \ { return static_cast<Bitmask>( static_cast<boost::int_least32_t>(x) \ | static_cast<boost::int_least32_t>(y)); } \ \ inline BOOST_CONSTEXPR Bitmask operator& (Bitmask x , Bitmask y ) \ { return static_cast<Bitmask>( static_cast<boost::int_least32_t>(x) \ & static_cast<boost::int_least32_t>(y)); } \ \ inline BOOST_CONSTEXPR Bitmask operator^ (Bitmask x , Bitmask y ) \ { return static_cast<Bitmask>( static_cast<boost::int_least32_t>(x) \ ^ static_cast<boost::int_least32_t>(y)); } \ \ inline BOOST_CONSTEXPR Bitmask operator~ (Bitmask x ) \ { return static_cast<Bitmask>(~static_cast<boost::int_least32_t>(x)); } \ \ inline Bitmask & operator&=(Bitmask& x , Bitmask y) \ { x = x & y ; return x ; } \ \ inline Bitmask & operator|=(Bitmask& x , Bitmask y) \ { x = x | y ; return x ; } \ \ inline Bitmask & operator^=(Bitmask& x , Bitmask y) \ { x = x ^ y ; return x ; } \ \ /* Boost extensions to [bitmask.types] */ \ \ inline BOOST_CONSTEXPR bool operator!(Bitmask x) \ { return !static_cast<int>(x); } \ \ inline BOOST_CONSTEXPR bool bitmask_set(Bitmask x) \ { return !!x; } #endif // BOOST_BITMASK_HPP
52.389831
81
0.371724
kindlychung
dcc869cf1d46f33d81b28dd7a3d0131fb0832472
1,857
cxx
C++
PWGPP/EvTrkSelection/AliAnalysisTaskEventCutsValidation.cxx
AudreyFrancisco/AliPhysics
cb36cfa7d1edcd969780e90fe6bfab5107f0f099
[ "BSD-3-Clause" ]
1
2021-06-11T20:36:16.000Z
2021-06-11T20:36:16.000Z
PWGPP/EvTrkSelection/AliAnalysisTaskEventCutsValidation.cxx
AudreyFrancisco/AliPhysics
cb36cfa7d1edcd969780e90fe6bfab5107f0f099
[ "BSD-3-Clause" ]
1
2017-03-14T15:11:43.000Z
2017-03-14T15:53:09.000Z
PWGPP/EvTrkSelection/AliAnalysisTaskEventCutsValidation.cxx
AudreyFrancisco/AliPhysics
cb36cfa7d1edcd969780e90fe6bfab5107f0f099
[ "BSD-3-Clause" ]
1
2018-09-22T01:09:25.000Z
2018-09-22T01:09:25.000Z
#include "AliAnalysisTaskEventCutsValidation.h" // ROOT includes #include <TChain.h> #include <TH2F.h> #include <TList.h> // ALIROOT includes #include "AliAODEvent.h" #include "AliAODHeader.h" #include "AliAODTrack.h" #include "AliESDEvent.h" #include "AliESDtrack.h" #include "AliVEvent.h" ///\cond CLASSIMP ClassImp(AliAnalysisTaskEventCutsValidation); ///\endcond /// Standard and default constructor of the class. /// /// \param taskname Name of the task /// \param partname Name of the analysed particle /// AliAnalysisTaskEventCutsValidation::AliAnalysisTaskEventCutsValidation(bool storeCuts, TString taskname) : AliAnalysisTaskSE(taskname.Data()), fEventCut(false), fList(nullptr), fStoreCuts(storeCuts) { DefineInput(0, TChain::Class()); DefineOutput(1, TList::Class()); if (storeCuts) DefineOutput(2, AliEventCuts::Class()); } /// Standard destructor /// AliAnalysisTaskEventCutsValidation::~AliAnalysisTaskEventCutsValidation() { if (fList) delete fList; } /// This function creates all the histograms and all the objects in general used during the analysis /// \return void /// void AliAnalysisTaskEventCutsValidation::UserCreateOutputObjects() { fList = new TList(); fList->SetOwner(true); fEventCut.AddQAplotsToList(fList,true); PostData(1,fList); if (fStoreCuts) PostData(2,&fEventCut); } /// This is the function that is evaluated for each event. The analysis code stays here. /// /// \param options Deprecated parameter /// \return void /// void AliAnalysisTaskEventCutsValidation::UserExec(Option_t *) { AliVEvent* ev = InputEvent(); fEventCut.AcceptEvent(ev); PostData(1,fList); if (fStoreCuts) PostData(2,&fEventCut); return; } /// Merge the output. Called once at the end of the query. /// /// \return void /// void AliAnalysisTaskEventCutsValidation::Terminate(Option_t *) { return; }
24.116883
106
0.740442
AudreyFrancisco
dcc96397a4d54d55f0f0b63606e5efb0dd6dee70
27,548
cpp
C++
toonz/sources/toonz/linetestviewer.cpp
ss23/opentoonz
b42e43d4b8d9fedc26022d145218b9a147a30985
[ "BSD-3-Clause" ]
null
null
null
toonz/sources/toonz/linetestviewer.cpp
ss23/opentoonz
b42e43d4b8d9fedc26022d145218b9a147a30985
[ "BSD-3-Clause" ]
null
null
null
toonz/sources/toonz/linetestviewer.cpp
ss23/opentoonz
b42e43d4b8d9fedc26022d145218b9a147a30985
[ "BSD-3-Clause" ]
1
2019-10-07T17:12:30.000Z
2019-10-07T17:12:30.000Z
#include "linetestviewer.h" #ifdef LINETEST #include "tapp.h" #include "viewerdraw.h" #include "timagecache.h" #include "tgl.h" #include "trop.h" #include "toonz/txsheethandle.h" #include "toonz/tframehandle.h" #include "toonz/tcolumnhandle.h" #include "toonz/txshlevelhandle.h" #include "toonz/tobjecthandle.h" #include "toonz/txshsimplelevel.h" #include "toonz/stage2.h" #include "toonz/stagevisitor.h" #include "toonz/tonionskinmaskhandle.h" #include "toonz/imagemanager.h" #include "toonz/tstageobjecttree.h" #include "toonz/childstack.h" #include "toonz/dpiscale.h" #include "toonz/toonzscene.h" #include "toonz/sceneproperties.h" #include "toonz/tcamera.h" #include "tools/toolhandle.h" #include "tools/cursormanager.h" #include "tools/toolcommandids.h" #include "toonzqt/menubarcommand.h" #include "toonzqt/imageutils.h" #include <QPainter> #include <QPaintEvent> #include <QApplication> #include <QInputContext> #include <QMenu> #ifndef USE_QPAINTER GLshort vertices[] = { 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0}; GLshort coords[] = { 0, 1, 0, 0, 1, 0, 1, 1}; // function pointers for PBO Extension // Windows needs to get function pointers from ICD OpenGL drivers, // because opengl32.dll does not support extensions higher than v1.1. #ifdef _WIN32 PFNGLGENBUFFERSARBPROC pglGenBuffersARB = 0; // VBO Name Generation Procedure PFNGLBINDBUFFERARBPROC pglBindBufferARB = 0; // VBO Bind Procedure PFNGLBUFFERDATAARBPROC pglBufferDataARB = 0; // VBO Data Loading Procedure PFNGLBUFFERSUBDATAARBPROC pglBufferSubDataARB = 0; // VBO Sub Data Loading Procedure PFNGLDELETEBUFFERSARBPROC pglDeleteBuffersARB = 0; // VBO Deletion Procedure PFNGLGETBUFFERPARAMETERIVARBPROC pglGetBufferParameterivARB = 0; // return various parameters of VBO PFNGLMAPBUFFERARBPROC pglMapBufferARB = 0; // map VBO procedure PFNGLUNMAPBUFFERARBPROC pglUnmapBufferARB = 0; // unmap VBO procedure #define glGenBuffersARB pglGenBuffersARB #define glBindBufferARB pglBindBufferARB #define glBufferDataARB pglBufferDataARB #define glBufferSubDataARB pglBufferSubDataARB #define glDeleteBuffersARB pglDeleteBuffersARB #define glGetBufferParameterivARB pglGetBufferParameterivARB #define glMapBufferARB pglMapBufferARB #define glUnmapBufferARB pglUnmapBufferARB #endif #endif //USE_QPAINTER //----------------------------------------------------------------------------- namespace { //----------------------------------------------------------------------------- void initToonzEvent(TMouseEvent &toonzEvent, QMouseEvent *event, int widgetHeight, double pressure, bool isTablet) { toonzEvent.m_pos = TPoint(event->pos().x(), widgetHeight - 1 - event->pos().y()); toonzEvent.setModifiers(event->modifiers() & Qt::ShiftModifier, event->modifiers() & Qt::AltModifier, event->modifiers() & Qt::CtrlModifier); if (isTablet) toonzEvent.m_pressure = (int)(255 * pressure); else toonzEvent.m_pressure = 255; } //----------------------------------------------------------------------------- class ViewerZoomer : public ImageUtils::ShortcutZoomer { public: ViewerZoomer(QWidget *parent) : ShortcutZoomer(parent) {} void zoom(bool zoomin, bool resetZoom) { if (resetZoom) ((LineTestViewer *)getWidget())->resetView(); else ((LineTestViewer *)getWidget())->zoomQt(zoomin, resetZoom); } void fit() { //((LineTestViewer*)getWidget())->fitToCamera(); } void setActualPixelSize() { //((LineTestViewer*)getWidget())->setActualPixelSize(); } }; //----------------------------------------------------------------------------- } //namespace //----------------------------------------------------------------------------- // definito - per ora - in tapp.cpp extern string updateToolEnableStatus(TTool *tool); //============================================================================= // LineTestViewer //----------------------------------------------------------------------------- LineTestViewer::LineTestViewer(QWidget *parent) #ifdef USE_QPAINTER : QWidget(parent) #else : QGLWidget(parent) //, m_pboSupported(false) #endif //USE_QPAINTER , m_pos(), m_mouseButton(Qt::NoButton), m_viewAffine() { m_viewAffine = getNormalZoomScale(); setMouseTracking(true); } //----------------------------------------------------------------------------- LineTestViewer::~LineTestViewer() { //#ifndef USE_QPAINTER // clean up PBO //if(m_pboSupported) // glDeleteBuffersARB(1, &m_pboId); //#endif //USE_QPAINTER } //----------------------------------------------------------------------------- TPointD LineTestViewer::winToWorld(const QPoint &pos) const { // coordinate window (origine in alto a sinistra) -> coordinate colonna (origine al centro dell'immagine) TPointD pp(pos.x() - width() * 0.5, -pos.y() + height() * 0.5); return getViewMatrix().inv() * pp; } //----------------------------------------------------------------------------- TPointD LineTestViewer::winToWorld(const TPoint &winPos) const { return winToWorld(QPoint(winPos.x, height() - winPos.y)); } //----------------------------------------------------------------------------- void LineTestViewer::resetInputMethod() { qApp->inputContext()->reset(); } //----------------------------------------------------------------------------- TAffine LineTestViewer::getViewMatrix() const { int frame = TApp::instance()->getCurrentFrame()->getFrame(); TXsheet *xsh = TApp::instance()->getCurrentXsheet()->getXsheet(); TAffine aff = xsh->getCameraAff(frame); return m_viewAffine * aff.inv(); } //----------------------------------------------------------------------------- #ifdef USE_QPAINTER void LineTestViewer::paintEvent(QPaintEvent *) { QPainter p(this); p.begin(this); p.resetMatrix(); TApp *app = TApp::instance(); ToonzScene *scene = app->getCurrentScene()->getScene(); p.fillRect(visibleRegion().boundingRect(), QBrush(QColor(Qt::white))); TPixel32 cameraBgColor = scene->getProperties()->getBgColor(); TPixel32 viewerBgColor = scene->getProperties()->getViewerBgColor(); p.fillRect(visibleRegion().boundingRect(), QBrush(QColor(viewerBgColor.r, viewerBgColor.g, viewerBgColor.b, viewerBgColor.m))); int h = height(); int w = width(); TDimension viewerSize(w, h); TRect clipRect(viewerSize); clipRect -= TPoint(viewerSize.lx * 0.5, viewerSize.ly * 0.5); TAffine viewAff = getViewMatrix(); Stage::RasterPainter stagePainter(viewerSize, viewAff, clipRect, 0, true); TFrameHandle *frameHandle = app->getCurrentFrame(); if (app->getCurrentFrame()->isEditingLevel()) { Stage::visit(stagePainter, app->getCurrentLevel()->getLevel(), app->getCurrentFrame()->getFid(), OnionSkinMask(), frameHandle->isPlaying()); } else { int xsheetLevel = 0; TXsheet *xsh = app->getCurrentXsheet()->getXsheet(); int frame = app->getCurrentFrame()->getFrame(); Stage::VisitArgs args; args.scene = scene; args.xsh = xsh; args.row = frame; args.currentColumnIndex = app->getCurrentColumn()->getColumnIndex(); OnionSkinMask osm = app->getCurrentOnionSkin()->getOnionSkinMask(); args.osm = &osm; args.xsheetLevel = xsheetLevel; args.isPlaying = frameHandle->isPlaying(); args.onlyVisible = true; args.checkPreviewVisibility = true; Stage::visit(stagePainter, args); } //Draw camera rect and mask TRectD rect = ViewerDraw::getCameraRect(); TXsheet *xsh = app->getCurrentXsheet()->getXsheet(); TStageObjectId cameraId = xsh->getStageObjectTree()->getCurrentCameraId(); int row = app->getCurrentFrame()->getFrameIndex(); double cameraZ = xsh->getZ(cameraId, row); TAffine aff = xsh->getPlacement(cameraId, row) * TScale((1000 + cameraZ) / 1000); aff = TAffine(1, 0, 0, 0, -1, viewerSize.ly) * TTranslation(viewerSize.lx * 0.5, viewerSize.ly * 0.5) * viewAff * aff; QMatrix matrix(aff.a11, aff.a21, aff.a12, aff.a22, aff.a13, aff.a23); QPolygon cameraPolygon(QRect(rect.getP00().x, rect.getP00().y, rect.getLx(), rect.getLy())); cameraPolygon = cameraPolygon * matrix; p.fillRect(cameraPolygon.boundingRect(), QBrush(QColor(cameraBgColor.r, cameraBgColor.g, cameraBgColor.b, cameraBgColor.m))); stagePainter.drawRasterImages(p, cameraPolygon); p.end(); } #else //----------------------------------------------------------------------------- void LineTestViewer::initializeGL() { glClearColor(1.0f, 1.0f, 1.0f, 0.0f); glPixelStorei(GL_UNPACK_ALIGNMENT, 4); // 4-byte pixel alignment glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glEnable(GL_TEXTURE_2D); //checkPBOSupport(); // Generater pbuffer //if(m_pboSupported) // glGenBuffersARB(1, &m_pboId); } //----------------------------------------------------------------------------- void LineTestViewer::resizeGL(int width, int height) { glViewport(0, 0, width, height); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(0, width, 0, height, -1, 1); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); // To maintain pixel accuracy glTranslated(0.375, 0.375, 0.0); } //----------------------------------------------------------------------------- //#include "tstopwatch.h" void LineTestViewer::paintRaster(TRasterP ras) { //TStopWatch timer; //TStopWatch timer2; //timer.start(); //timer2.start(); int w = ras->getLx(); int h = ras->getLy(); vertices[1] = h; vertices[6] = w; vertices[9] = w; vertices[10] = h; int dataSize = w * h * 4; //timer.stop(); //timer2.stop(); //qDebug("time 1: %d",timer.getTotalTime()); //timer.start(true); //timer2.start(); /**************************************************************************************** ATTENZIONE!!! Qeesto codice potrebbe dare problemi!!!!! quando si utilizzano le texture le loro dimensioni dovrebbero essere potenze di dur... le nuove schede grafiche sembrerebbero funzionare lo stesso ma le vecchie a volte danno problemi!!! Inoltre non viene fatto il controllo se le dimenzioni dei raster da disegnare superano le dimenzioni supportate dalla scheda grafica... se cio' accade bisognerebbe spezzare il raster in due... Questo codice sembra essere meolto veloce (cosa di cui abbiamo bisogno) ma puo' dare seri problemi!!!! *****************************************************************************************/ ras->lock(); int pixelSize = ras->getPixelSize(); glGenTextures(1, &m_textureId); glBindTexture(GL_TEXTURE_2D, m_textureId); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP); if (pixelSize == 4) glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, w, h, 0, GL_BGRA, GL_UNSIGNED_BYTE, (GLvoid *)0); else if (pixelSize == 1) { glPixelStorei(GL_UNPACK_ALIGNMENT, 1); glTexImage2D(GL_TEXTURE_2D, 0, GL_LUMINANCE8, w, h, 0, GL_LUMINANCE, GL_UNSIGNED_BYTE, (GLvoid *)0); } else return; //if(m_pboSupported) // { // // bind PBO to update pixel values // glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, m_pboId); // // map the buffer object into client's memory // // Note that glMapBufferARB() causes sync issue. // // If GPU is working with this buffer, glMapBufferARB() will wait(stall) // // for GPU to finish its job. To avoid waiting (stall), you can call // // first glBufferDataARB() with NULL pointer before glMapBufferARB(). // // If you do that, the previous data in PBO will be discarded and // // glMapBufferARB() returns a new allocated pointer immediately // // even if GPU is still working with the previous data. // glBufferDataARB(GL_PIXEL_UNPACK_BUFFER_ARB, dataSize, 0, GL_STREAM_DRAW_ARB); // GLubyte* ptr = (GLubyte*)glMapBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, GL_WRITE_ONLY_ARB); // if(ptr) // { // ras->lock(); // memcpy( ptr, ras->getRawData(), dataSize); // glUnmapBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB); // release pointer to mapping buffer // ras->unlock(); // } // // it is good idea to release PBOs with ID 0 after use. // // Once bound with 0, all pixel operations behave normal ways. // //glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, 0); // // // bind the texture and PBO // glBindTexture(GL_TEXTURE_2D, m_textureId); // glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, m_pboId); // // copy pixels from PBO to texture object // // Use offset instead of ponter. // glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, w, h, GL_BGRA, GL_UNSIGNED_BYTE, 0); // } // else // { // start to copy pixels from system memory to textrure object glBindTexture(GL_TEXTURE_2D, m_textureId); if (pixelSize == 4) glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, w, h, GL_BGRA, GL_UNSIGNED_BYTE, (GLvoid *)ras->getRawData()); else if (pixelSize == 1) glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, w, h, GL_LUMINANCE, GL_UNSIGNED_BYTE, (GLvoid *)ras->getRawData()); else return; ras->unlock(); // } glEnable(GL_BLEND); glEnableClientState(GL_VERTEX_ARRAY); glEnableClientState(GL_TEXTURE_COORD_ARRAY); glVertexPointer(3, GL_SHORT, 0, vertices); glTexCoordPointer(2, GL_SHORT, 0, &coords); glDrawArrays(GL_QUADS, 0, 4); glDisableClientState(GL_VERTEX_ARRAY); glDisableClientState(GL_TEXTURE_COORD_ARRAY); glDisable(GL_BLEND); // clean up texture glDeleteTextures(1, &m_textureId); //timer.stop(); //timer2.stop(); //qDebug("time 2: %d",timer.getTotalTime()); //qDebug("total time: %d",timer2.getTotalTime()); } //----------------------------------------------------------------------------- void LineTestViewer::paintGL() { TApp *app = TApp::instance(); ToonzScene *scene = app->getCurrentScene()->getScene(); TPixel32 cameraBgColor = scene->getProperties()->getBgColor(); TPixel32 viewerBgColor = scene->getProperties()->getViewerBgColor(); glClearColor(viewerBgColor.r / 255.0, viewerBgColor.g / 255.0, viewerBgColor.b / 255.0, viewerBgColor.m / 255.0); glClear(GL_COLOR_BUFFER_BIT); int h = height(); int w = width(); TDimension viewerSize(w, h); TRect clipRect(viewerSize); //clipRect -= TPoint(viewerSize.lx*0.5,viewerSize.ly*0.5); TAffine viewAff = getViewMatrix(); Stage::RasterPainter stagePainter(viewerSize, viewAff, clipRect, 0, true); TFrameHandle *frameHandle = app->getCurrentFrame(); int frame = frameHandle->getFrame(); if (app->getCurrentFrame()->isEditingLevel()) { Stage::visit(stagePainter, app->getCurrentLevel()->getLevel(), frameHandle->getFid(), OnionSkinMask(), frameHandle->isPlaying()); } else { int xsheetLevel = 0; TXsheet *xsh = app->getCurrentXsheet()->getXsheet(); Stage::VisitArgs args; args.scene = scene; args.xsh = xsh; args.row = frame; args.currentColumnIndex = app->getCurrentColumn()->getColumnIndex(); OnionSkinMask osm = app->getCurrentOnionSkin()->getOnionSkinMask(); args.osm = &osm; args.xsheetLevel = xsheetLevel; args.isPlaying = frameHandle->isPlaying(); args.onlyVisible = true; args.checkPreviewVisibility = true; Stage::visit(stagePainter, args); } //Draw camera rect and mask TRectD cameraRect = ViewerDraw::getCameraRect(); TXsheet *xsh = app->getCurrentXsheet()->getXsheet(); TStageObjectId cameraId = xsh->getStageObjectTree()->getCurrentCameraId(); int row = frameHandle->getFrameIndex(); double cameraZ = xsh->getZ(cameraId, row); TAffine aff = xsh->getPlacement(cameraId, row) * TScale((1000 + cameraZ) / 1000); aff = TTranslation(viewerSize.lx * 0.5, viewerSize.ly * 0.5) * viewAff * aff; QMatrix matrix(aff.a11, aff.a21, aff.a12, aff.a22, aff.a13, aff.a23); QPolygon cameraPolygon(QRect(cameraRect.getP00().x, cameraRect.getP00().y, cameraRect.getLx(), cameraRect.getLy())); cameraPolygon = cameraPolygon * matrix; tglColor(cameraBgColor); glBegin(GL_POLYGON); glVertex2d(cameraPolygon.at(0).x(), cameraPolygon.at(0).y()); glVertex2d(cameraPolygon.at(1).x(), cameraPolygon.at(1).y()); glVertex2d(cameraPolygon.at(2).x(), cameraPolygon.at(2).y()); glVertex2d(cameraPolygon.at(3).x(), cameraPolygon.at(3).y()); glEnd(); tglColor(TPixel::White); int nodesSize = stagePainter.getNodesCount(); if (nodesSize == 0) return; int cameraWidth = cameraPolygon.at(2).x() - cameraPolygon.at(0).x(); int cameraHeight = cameraPolygon.at(2).y() - cameraPolygon.at(0).y(); int i; GLfloat mat[4][4]; QMatrix mtx; //GLubyte *pbo; //TRaster32P pboRaster; //if(m_pboSupported) //{ // glGenTextures(1, &m_textureId); // glBindTexture(GL_TEXTURE_2D, m_textureId); // glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); // glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); // glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP); // glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP); // glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, cameraWidth, cameraHeight, 0, GL_BGRA, GL_UNSIGNED_BYTE, (GLvoid*)0); // glBindTexture(GL_TEXTURE_2D, m_textureId); // glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, m_pboId); // // copy pixels from PBO to texture object // // Use offset instead of ponter. // glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, cameraWidth, cameraHeight, GL_BGRA, GL_UNSIGNED_BYTE, 0); // // bind PBO to update pixel values // glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, m_pboId); // // map the buffer object into client's memory // // Note that glMapBufferARB() causes sync issue. // // If GPU is working with this buffer, glMapBufferARB() will wait(stall) // // for GPU to finish its job. To avoid waiting (stall), you can call // // first glBufferDataARB() with NULL pointer before glMapBufferARB(). // // If you do that, the previous data in PBO will be discarded and // // glMapBufferARB() returns a new allocated pointer immediately // // even if GPU is still working with the previous data. // glBufferDataARB(GL_PIXEL_UNPACK_BUFFER_ARB, cameraWidth * cameraHeight * 4, 0, GL_STREAM_DRAW_ARB); // pbo = (GLubyte*)glMapBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, GL_WRITE_ONLY_ARB); // pboRaster = TRaster32P(cameraWidth, cameraHeight,cameraWidth, (TPixelRGBM32*) pbo, false); // pboRaster->fill(TPixel32::Green); //} glScissor(cameraPolygon.at(0).x(), cameraPolygon.at(0).y(), cameraWidth, cameraHeight); glEnable(GL_SCISSOR_TEST); //if(!m_pboSupported) glPushMatrix(); for (i = 0; i < nodesSize; i++) { TRasterP ras = stagePainter.getRaster(i, mtx); if (!ras.getPointer()) continue; //if(!m_pboSupported) //{ //Matrix tranformation mat[0][0] = mtx.m11(); mat[0][1] = mtx.m12(); mat[0][2] = 0; mat[0][3] = 0; mat[1][0] = mtx.m21(); mat[1][1] = mtx.m22(); mat[1][2] = 0; mat[1][3] = 0; mat[2][0] = 0; mat[2][1] = 0; mat[2][2] = 1; mat[2][3] = 0; mat[3][0] = mtx.dx(); mat[3][1] = mtx.dy(); mat[3][2] = 0; mat[3][3] = 1; //Draw Raster // CASO NON PBO glLoadMatrixf(&mat[0][0]); paintRaster(ras); //} //else //{ // TAffine aff;// (mtx.m11(),mtx.m12(),mtx.dx(),mtx.m21(),mtx.m22(),mtx.dy()); // //TRop::quickPut(pboRaster, ras, aff); //} } //if(!m_pboSupported) glPopMatrix(); // Convert PBO to texture and draw it //if(m_pboSupported) //{ // glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, 0); // vertices[0] = cameraPolygon.at(0).x(); // vertices[1] = cameraPolygon.at(0).y() + cameraHeight; // vertices[3] = cameraPolygon.at(0).x(); // vertices[4] = cameraPolygon.at(0).y(); // vertices[6] = cameraPolygon.at(0).x() + cameraWidth; // vertices[7] = cameraPolygon.at(0).y(); // vertices[9] = cameraPolygon.at(0).x() + cameraWidth; // vertices[10] = cameraPolygon.at(0).y() + cameraHeight; // glBindTexture(GL_TEXTURE_2D, m_textureId); // glEnable(GL_BLEND); // glEnableClientState(GL_VERTEX_ARRAY); // glEnableClientState(GL_TEXTURE_COORD_ARRAY); // glVertexPointer(3, GL_SHORT, 0, vertices); // glTexCoordPointer(2,GL_SHORT,0,&coords); // glDrawArrays(GL_QUADS, 0, 4); // glDisableClientState(GL_VERTEX_ARRAY); // glDisableClientState(GL_TEXTURE_COORD_ARRAY); // glDisable(GL_BLEND); // // clean up texture // glDeleteTextures(1, &m_textureId); //} glDisable(GL_SCISSOR_TEST); stagePainter.clearNodes(); } #endif //USE_QPAINTER //----------------------------------------------------------------------------- void LineTestViewer::showEvent(QShowEvent *) { TApp *app = TApp::instance(); bool ret = true; ret = ret && connect(TApp::instance()->getCurrentObject(), SIGNAL(objectSwitched()), this, SLOT(update())); ret = ret && connect(TApp::instance()->getCurrentObject(), SIGNAL(objectChanged(bool)), this, SLOT(update())); ret = ret && connect(TApp::instance()->getCurrentOnionSkin(), SIGNAL(onionSkinMaskChanged()), this, SLOT(update())); ret = ret && connect(TApp::instance()->getCurrentLevel(), SIGNAL(xshLevelChanged()), this, SLOT(update())); TFrameHandle *frameHandle = app->getCurrentFrame(); ret = ret && connect(frameHandle, SIGNAL(frameSwitched()), this, SLOT(update())); TXsheetHandle *xsheetHandle = app->getCurrentXsheet(); ret = ret && connect(xsheetHandle, SIGNAL(xsheetChanged()), this, SLOT(update())); ret = ret && connect(xsheetHandle, SIGNAL(xsheetSwitched()), this, SLOT(update())); TSceneHandle *sceneHandle = app->getCurrentScene(); ret = ret && connect(sceneHandle, SIGNAL(sceneSwitched()), this, SLOT(onSceneSwitched())); ret = ret && connect(sceneHandle, SIGNAL(sceneChanged()), this, SLOT(update())); ret = ret && connect(TApp::instance()->getCurrentOnionSkin(), SIGNAL(onionSkinMaskChanged()), this, SLOT(update())); assert(ret); } //----------------------------------------------------------------------------- void LineTestViewer::hideEvent(QHideEvent *e) { TApp *app = TApp::instance(); disconnect(TApp::instance()->getCurrentObject(), SIGNAL(objectSwitched()), this, SLOT(update())); disconnect(TApp::instance()->getCurrentObject(), SIGNAL(objectChanged(bool)), this, SLOT(update())); disconnect(TApp::instance()->getCurrentOnionSkin(), SIGNAL(onionSkinMaskChanged()), this, SLOT(update())); disconnect(TApp::instance()->getCurrentLevel(), SIGNAL(xshLevelChanged()), this, SLOT(update())); TFrameHandle *frameHandle = app->getCurrentFrame(); disconnect(frameHandle, SIGNAL(frameSwitched()), this, SLOT(update())); TXsheetHandle *xsheetHandle = app->getCurrentXsheet(); disconnect(xsheetHandle, SIGNAL(xsheetChanged()), this, SLOT(update())); disconnect(xsheetHandle, SIGNAL(xsheetSwitched()), this, SLOT(update())); TSceneHandle *sceneHandle = app->getCurrentScene(); disconnect(sceneHandle, SIGNAL(sceneSwitched()), this, SLOT(onSceneSwitched())); disconnect(sceneHandle, SIGNAL(sceneChanged()), this, SLOT(update())); disconnect(TApp::instance()->getCurrentOnionSkin(), SIGNAL(onionSkinMaskChanged()), this, SLOT(update())); QWidget::hideEvent(e); } //----------------------------------------------------------------------------- void LineTestViewer::leaveEvent(QEvent *) { //update(); QApplication::restoreOverrideCursor(); } //----------------------------------------------------------------------------- void LineTestViewer::enterEvent(QEvent *) { QApplication::setOverrideCursor(Qt::ForbiddenCursor); //update(); setFocus(); } //----------------------------------------------------------------------------- void LineTestViewer::mouseMoveEvent(QMouseEvent *event) { if (m_mouseButton == Qt::MidButton) { //panning QPoint curPos = event->pos(); panQt(curPos - m_pos); m_pos = curPos; return; } } //----------------------------------------------------------------------------- void LineTestViewer::mousePressEvent(QMouseEvent *event) { m_pos = event->pos(); m_mouseButton = event->button(); } //----------------------------------------------------------------------------- void LineTestViewer::mouseReleaseEvent(QMouseEvent *event) { m_pos = QPoint(0, 0); m_mouseButton = Qt::NoButton; } //----------------------------------------------------------------------------- void LineTestViewer::wheelEvent(QWheelEvent *e) { if (e->orientation() == Qt::Horizontal) return; int delta = e->delta() > 0 ? 120 : -120; zoomQt(e->pos(), exp(0.001 * delta)); } //----------------------------------------------------------------------------- // delta.x: right panning, pixel; delta.y: down panning, pixel void LineTestViewer::panQt(const QPoint &delta) { if (delta == QPoint()) return; m_viewAffine = TTranslation(delta.x(), -delta.y()) * m_viewAffine; update(); } //----------------------------------------------------------------------------- void LineTestViewer::contextMenuEvent(QContextMenuEvent *event) { QMenu *menu = new QMenu(this); QAction *act = menu->addAction("Reset View"); act->setShortcut(QKeySequence(CommandManager::instance()->getKeyFromId(T_ZoomReset))); connect(act, SIGNAL(triggered()), this, SLOT(resetView())); menu->exec(event->globalPos()); } //----------------------------------------------------------------------------- void LineTestViewer::keyPressEvent(QKeyEvent *event) { ViewerZoomer(this).exec(event); } //----------------------------------------------------------------------------- // center: window coordinate, pixels, topleft origin void LineTestViewer::zoomQt(const QPoint &center, double factor) { if (factor == 1.0) return; TPointD delta(center.x() - width() * 0.5, -center.y() + height() * 0.5); double scale2 = fabs(m_viewAffine.det()); if ((scale2 < 100000 || factor < 1) && (scale2 > 0.001 * 0.05 || factor > 1)) m_viewAffine = TTranslation(delta) * TScale(factor) * TTranslation(-delta) * m_viewAffine; update(); emit onZoomChanged(); } //----------------------------------------------------------------------------- void LineTestViewer::zoomQt(bool forward, bool reset) { int i; double normalZoom = sqrt(getNormalZoomScale().det()); double scale2 = m_viewAffine.det(); if (reset || ((scale2 < 256 || !forward) && (scale2 > 0.001 * 0.05 || forward))) { double oldZoomScale = sqrt(scale2); double zoomScale = reset ? 1 : ImageUtils::getQuantizedZoomFactor(oldZoomScale / normalZoom, forward); m_viewAffine = TScale(zoomScale * normalZoom / oldZoomScale) * m_viewAffine; } update(); emit onZoomChanged(); } //----------------------------------------------------------------------------- void LineTestViewer::onFrameSwitched() { update(); } //----------------------------------------------------------------------------- void LineTestViewer::onXsheetChanged() { update(); } //----------------------------------------------------------------------------- void LineTestViewer::onSceneSwitched() { resetView(); } //----------------------------------------------------------------------------- void LineTestViewer::resetView() { m_viewAffine = getNormalZoomScale(); update(); emit onZoomChanged(); } //----------------------------------------------------------------------------- void LineTestViewer::onButtonPressed(FlipConsole::EGadget button) { switch (button) { CASE FlipConsole::eFilledRaster: { TXshSimpleLevel::m_fillFullColorRaster = !TXshSimpleLevel::m_fillFullColorRaster; update(); } DEFAULT:; } } //----------------------------------------------------------------------------- TAffine LineTestViewer::getNormalZoomScale() { TApp *app = TApp::instance(); const double inch = Stage::inch; TCamera *camera = app->getCurrentScene()->getScene()->getCurrentCamera(); double size; int res; if (camera->isXPrevalence()) { size = camera->getSize().lx; res = camera->getRes().lx; } else { size = camera->getSize().ly; res = camera->getRes().ly; } TScale cameraScale(inch * size / res); return cameraScale.inv(); } #endif
32.257611
128
0.632605
ss23
dcc9cf2a648f6f4c0768a1b376fc711fe500e9bc
1,216
cpp
C++
sources/middle_layer/src/result.cpp
hhb584520/DML
014eb9894e85334f03ec74435933c972f3d05b50
[ "MIT" ]
null
null
null
sources/middle_layer/src/result.cpp
hhb584520/DML
014eb9894e85334f03ec74435933c972f3d05b50
[ "MIT" ]
null
null
null
sources/middle_layer/src/result.cpp
hhb584520/DML
014eb9894e85334f03ec74435933c972f3d05b50
[ "MIT" ]
1
2022-03-28T07:52:21.000Z
2022-03-28T07:52:21.000Z
/******************************************************************************* * Copyright (C) 2021 Intel Corporation * * SPDX-License-Identifier: MIT ******************************************************************************/ #include <core/view.hpp> #include <dml/detail/ml/result.hpp> namespace dml::detail::ml { detail::execution_status get_status(completion_record &record) noexcept { return static_cast<execution_status>(0b111111 & core::any_completion_record(record).status()); } detail::result_t get_result(completion_record &record) noexcept { return core::any_completion_record(record).result(); } detail::transfer_size_t get_bytes_completed(completion_record &record) noexcept { return core::any_completion_record(record).bytes_completed(); } detail::transfer_size_t get_delta_record_size(completion_record &record) noexcept { return core::make_view<core::operation::create_delta>(record).delta_record_size(); } detail::transfer_size_t get_crc_value(completion_record &record) noexcept { return core::make_view<core::operation::crc>(record).crc_value(); } } // namespace dml::detail::ml
32
102
0.621711
hhb584520
dcccd221f52744da844a1137deaefcb37c2c16ef
7,220
cpp
C++
ideccmbd/CrdIdecTou/QryIdecTouRef1NFile.cpp
mpsitech/idec_public
a74cf1c7095e08ee61b237fddc1642f83dbb852d
[ "BSD-2-Clause" ]
null
null
null
ideccmbd/CrdIdecTou/QryIdecTouRef1NFile.cpp
mpsitech/idec_public
a74cf1c7095e08ee61b237fddc1642f83dbb852d
[ "BSD-2-Clause" ]
null
null
null
ideccmbd/CrdIdecTou/QryIdecTouRef1NFile.cpp
mpsitech/idec_public
a74cf1c7095e08ee61b237fddc1642f83dbb852d
[ "BSD-2-Clause" ]
null
null
null
/** * \file QryIdecTouRef1NFile.cpp * job handler for job QryIdecTouRef1NFile (implementation) * \author Alexander Wirthmueller * \date created: 30 Dec 2017 * \date modified: 30 Dec 2017 */ #ifdef IDECCMBD #include <Ideccmbd.h> #else #include <Idecd.h> #endif #include "QryIdecTouRef1NFile.h" #include "QryIdecTouRef1NFile_blks.cpp" /****************************************************************************** class QryIdecTouRef1NFile ******************************************************************************/ QryIdecTouRef1NFile::QryIdecTouRef1NFile( XchgIdec* xchg , DbsIdec* dbsidec , const ubigint jrefSup , const uint ixIdecVLocale ) : JobIdec(xchg, VecIdecVJob::QRYIDECTOUREF1NFILE, jrefSup, ixIdecVLocale) { jref = xchg->addJob(this); // IP constructor.cust1 --- INSERT xchg->addStmgr(jref, Stub::VecVNonetype::SHORT); ixIdecVQrystate = VecIdecVQrystate::OOD; // IP constructor.cust2 --- INSERT rerun(dbsidec); xchg->addClstn(VecIdecVCall::CALLIDECSTUBCHG, jref, Clstn::VecVJobmask::SPEC, jref, Arg(), Clstn::VecVJactype::LOCK); // IP constructor.cust3 --- INSERT // IP constructor.spec3 --- INSERT }; QryIdecTouRef1NFile::~QryIdecTouRef1NFile() { // IP destructor.spec --- INSERT // IP destructor.cust --- INSERT xchg->removeJobByJref(jref); }; // IP cust --- INSERT void QryIdecTouRef1NFile::refreshJnum() { ubigint preRefSel = xchg->getRefPreset(VecIdecVPreset::PREIDECREFSEL, jref); stgiac.jnum = getJnumByRef(preRefSel); }; void QryIdecTouRef1NFile::rerun( DbsIdec* dbsidec , const bool call ) { string sqlstr; uint cnt; ubigint preRefTou = xchg->getRefPreset(VecIdecVPreset::PREIDECREFTOU, jref); xchg->removeClstns(VecIdecVCall::CALLIDECFILMOD_RETREUEQ, jref); dbsidec->tblidecqselect->removeRstByJref(jref); dbsidec->tblidecqtouref1nfile->removeRstByJref(jref); sqlstr = "SELECT COUNT(TblIdecMFile.ref)"; sqlstr += " FROM TblIdecMFile"; sqlstr += " WHERE TblIdecMFile.refIxVTbl = " + to_string(VecIdecVMFileRefTbl::TOU); sqlstr += " AND TblIdecMFile.refUref = " + to_string(preRefTou) + ""; dbsidec->loadUintBySQL(sqlstr, cnt); statshr.ntot = cnt; statshr.nload = 0; if (stgiac.jnumFirstload > cnt) { if (cnt >= stgiac.nload) stgiac.jnumFirstload = cnt-stgiac.nload+1; else stgiac.jnumFirstload = 1; }; sqlstr = "INSERT INTO TblIdecQTouRef1NFile(jref, jnum, ref)"; sqlstr += " SELECT " + to_string(jref) + ", 0, TblIdecMFile.ref"; sqlstr += " FROM TblIdecMFile"; sqlstr += " WHERE TblIdecMFile.refIxVTbl = " + to_string(VecIdecVMFileRefTbl::TOU); sqlstr += " AND TblIdecMFile.refUref = " + to_string(preRefTou) + ""; sqlstr += " ORDER BY Filename ASC"; sqlstr += " LIMIT " + to_string(stgiac.nload) + " OFFSET " + to_string(stgiac.jnumFirstload-1); dbsidec->executeQuery(sqlstr); sqlstr = "UPDATE TblIdecQTouRef1NFile SET jnum = qref WHERE jref = " + to_string(jref); dbsidec->executeQuery(sqlstr); ixIdecVQrystate = VecIdecVQrystate::UTD; statshr.jnumFirstload = stgiac.jnumFirstload; fetch(dbsidec); if (call) xchg->triggerCall(dbsidec, VecIdecVCall::CALLIDECSTATCHG, jref); xchg->addIxRefClstn(VecIdecVCall::CALLIDECFILMOD_RETREUEQ, jref, Clstn::VecVJobmask::ALL, 0, VecIdecVMFileRefTbl::TOU, preRefTou, Clstn::VecVJactype::LOCK); }; void QryIdecTouRef1NFile::fetch( DbsIdec* dbsidec ) { string sqlstr; StmgrIdec* stmgr = NULL; Stcch* stcch = NULL; IdecQTouRef1NFile* rec = NULL; dbsidec->tblidecqtouref1nfile->loadRstByJref(jref, false, rst); statshr.nload = rst.nodes.size(); stmgr = xchg->getStmgrByJref(jref); if (stmgr) { stmgr->begin(); stcch = stmgr->stcch; stcch->clear(); for (unsigned int i=0;i<rst.nodes.size();i++) { rec = rst.nodes[i]; rec->jnum = statshr.jnumFirstload + i; rec->stubRef = StubIdec::getStubFilStd(dbsidec, rec->ref, ixIdecVLocale, Stub::VecVNonetype::SHORT, stcch); }; stmgr->commit(); stmgr->unlockAccess("QryIdecTouRef1NFile", "fetch"); }; refreshJnum(); }; uint QryIdecTouRef1NFile::getJnumByRef( const ubigint ref ) { uint retval = 0; IdecQTouRef1NFile* rec = NULL; for (unsigned int i=0;i<rst.nodes.size();i++) { rec = rst.nodes[i]; if (rec->ref == ref) { retval = rec->jnum; break; }; }; return retval; }; ubigint QryIdecTouRef1NFile::getRefByJnum( const uint jnum ) { uint ref = 0; IdecQTouRef1NFile* rec = getRecByJnum(jnum); if (rec) ref = rec->ref; return ref; }; IdecQTouRef1NFile* QryIdecTouRef1NFile::getRecByJnum( const uint jnum ) { IdecQTouRef1NFile* rec = NULL; for (unsigned int i=0;i<rst.nodes.size();i++) { rec = rst.nodes[i]; if (rec->jnum == jnum) break; }; if (rec) if (rec->jnum != jnum) rec = NULL; return rec; }; void QryIdecTouRef1NFile::handleRequest( DbsIdec* dbsidec , ReqIdec* req ) { if (req->ixVBasetype == ReqIdec::VecVBasetype::CMD) { reqCmd = req; if (req->cmd == "cmdset") { cout << "\trerun" << endl; cout << "\tshow" << endl; } else if (req->cmd == "rerun") { req->retain = handleRerun(dbsidec); } else if (req->cmd == "show") { req->retain = handleShow(dbsidec); } else { cout << "\tinvalid command!" << endl; }; if (!req->retain) reqCmd = NULL; } else if (req->ixVBasetype == ReqIdec::VecVBasetype::REGULAR) { }; }; bool QryIdecTouRef1NFile::handleRerun( DbsIdec* dbsidec ) { bool retval = false; string input; cout << "\tjnumFirstload (" << stgiac.jnumFirstload << "): "; cin >> input; stgiac.jnumFirstload = atol(input.c_str()); cout << "\tnload (" << stgiac.nload << "): "; cin >> input; stgiac.nload = atol(input.c_str()); rerun(dbsidec); return retval; }; bool QryIdecTouRef1NFile::handleShow( DbsIdec* dbsidec ) { bool retval = false; IdecQTouRef1NFile* rec = NULL; // header row cout << "\tqref"; cout << "\tjref"; cout << "\tjnum"; cout << "\tref"; cout << "\tstubRef"; cout << endl; // record rows for (unsigned int i=0;i<rst.nodes.size();i++) { rec = rst.nodes[i]; cout << "\t" << rec->qref; cout << "\t" << rec->jref; cout << "\t" << rec->jnum; cout << "\t" << rec->ref; cout << "\t" << rec->stubRef; cout << endl; }; return retval; }; void QryIdecTouRef1NFile::handleCall( DbsIdec* dbsidec , Call* call ) { if (call->ixVCall == VecIdecVCall::CALLIDECSTUBCHG) { call->abort = handleCallIdecStubChg(dbsidec, call->jref); } else if (call->ixVCall == VecIdecVCall::CALLIDECFILMOD_RETREUEQ) { call->abort = handleCallIdecFilMod_retReuEq(dbsidec, call->jref, call->argInv.ix, call->argInv.ref); }; }; bool QryIdecTouRef1NFile::handleCallIdecStubChg( DbsIdec* dbsidec , const ubigint jrefTrig ) { bool retval = false; if (ixIdecVQrystate == VecIdecVQrystate::UTD) { ixIdecVQrystate = VecIdecVQrystate::SLM; xchg->triggerCall(dbsidec, VecIdecVCall::CALLIDECSTATCHG, jref); }; return retval; }; bool QryIdecTouRef1NFile::handleCallIdecFilMod_retReuEq( DbsIdec* dbsidec , const ubigint jrefTrig , const uint ixInv , const ubigint refInv ) { bool retval = false; if (ixIdecVQrystate != VecIdecVQrystate::OOD) { ixIdecVQrystate = VecIdecVQrystate::OOD; xchg->triggerCall(dbsidec, VecIdecVCall::CALLIDECSTATCHG, jref); }; return retval; };
23.75
157
0.666343
mpsitech
dccd08cdbb82e841c8aaa3b60503f9e462c21548
6,008
cpp
C++
schwarzwald/core/util/Scheduler.cpp
igd-geo/schwarzwald
e3e041f87c93985394444ee056ce8ba7ae62194b
[ "Apache-2.0" ]
10
2021-01-06T14:16:31.000Z
2022-02-13T00:15:17.000Z
schwarzwald/core/util/Scheduler.cpp
igd-geo/schwarzwald
e3e041f87c93985394444ee056ce8ba7ae62194b
[ "Apache-2.0" ]
1
2022-03-25T08:37:30.000Z
2022-03-30T06:28:06.000Z
schwarzwald/core/util/Scheduler.cpp
igd-geo/schwarzwald
e3e041f87c93985394444ee056ce8ba7ae62194b
[ "Apache-2.0" ]
3
2020-12-03T13:50:42.000Z
2022-02-08T11:45:45.000Z
#include "util/Scheduler.h" #include "util/Config.h" #include <logging/Journal.h> #include <gsl/gsl> TilingScheduler::~TilingScheduler() {} FixedThreadsScheduler::FixedThreadsScheduler(FixedThreadsSchedulerArgs args) : _read_executor(args.read_threads) , _indexing_executor(args.indexing_threads) { if (!global_config().is_journaling_enabled) return; _read_executor_observer = _read_executor.make_observer<tf::ExecutorObserver>(); _indexing_executor_observer = _indexing_executor.make_observer<tf::ExecutorObserver>(); } FixedThreadsScheduler::~FixedThreadsScheduler() { if (!_read_executor_observer) return; auto read_trace = _read_executor_observer->dump(); auto indexing_trace = _indexing_executor_observer->dump(); auto read_journal = logging::JournalStore::global() .new_journal("executor_read_trace") .with_flat_type<std::string>() .as_text(global_config().journal_directory) .into_unique_files() .build(); read_journal->add_record(std::move(read_trace)); auto indexing_journal = logging::JournalStore::global() .new_journal("executor_indexing_trace") .with_flat_type<std::string>() .as_text(global_config().journal_directory) .into_unique_files() .build(); indexing_journal->add_record(std::move(indexing_trace)); } std::future<void> FixedThreadsScheduler::execute_tiling_iteration(tf::Taskflow& read_graph, tf::Taskflow& index_graph) { auto read_future = _read_executor.run(read_graph).share(); auto index_future = _indexing_executor.run(index_graph).share(); return std::async(std::launch::deferred, [wait_for_read = std::move(read_future), wait_for_index = std::move(index_future)]() mutable { wait_for_read.wait(); wait_for_index.wait(); }); } std::pair<uint32_t, uint32_t> FixedThreadsScheduler::get_read_and_index_concurrency(uint32_t remaining_files) { return { _read_executor.num_workers(), _indexing_executor.num_workers() }; } AdaptiveScheduler::AdaptiveScheduler( uint32_t num_threads, ThroughputSampler& read_throughput_sampler, ThroughputSampler& indexing_throughput_sampler) : _num_read_threads(1) , _num_index_threads(std::max(1u, num_threads - 1)) , _executor( _num_read_threads + _num_index_threads) // Important to use the sum of read+index threads, // instead of num_threads, because num_threads can be // <= 1 but we need at least two threads! , _read_throughput_sampler(read_throughput_sampler) , _indexing_throughput_sampler(indexing_throughput_sampler) { if (global_config().is_journaling_enabled) { _executor_observer = _executor.make_observer<tf::ExecutorObserver>(); } } AdaptiveScheduler::~AdaptiveScheduler() { if (!_executor_observer) return; auto trace = _executor_observer->dump(); auto journal = logging::JournalStore::global() .new_journal("executor_adaptive_trace") .with_flat_type<std::string>() .as_text(global_config().journal_directory) .into_unique_files() .build(); journal->add_record(std::move(trace)); } std::future<void> AdaptiveScheduler::execute_tiling_iteration(tf::Taskflow& read_graph, tf::Taskflow& index_graph) { auto read_future = _executor.run(read_graph).share(); auto index_future = _executor.run(index_graph).share(); return std::async(std::launch::deferred, [this, wait_for_read = std::move(read_future), wait_for_index = std::move(index_future)]() mutable { wait_for_read.wait(); wait_for_index.wait(); }); } std::pair<uint32_t, uint32_t> AdaptiveScheduler::get_read_and_index_concurrency(uint32_t remaining_files) { // The main question that this function answers is: Should we use more or less // read threads, or keep the count the same? For this, we solve the equation // following set of equations: 1) R*tr = I*ti 2) R + I = max_threads // // R = number of read threads // tr = throughput of a single read thread in points/s // I = number of index threads // ti = throughput of a single index thread in points/s const auto read_throughput_per_thread = _read_throughput_sampler.get_throughput_per_second() / _num_read_threads; const auto index_throughput_per_thread = _indexing_throughput_sampler.get_throughput_per_second() / _num_index_threads; const auto total_thread_count = gsl::narrow_cast<uint32_t>(_executor.num_workers()); _num_read_threads = std::min(_num_read_threads, remaining_files); _num_index_threads = total_thread_count - _num_read_threads; // Any of the throughputs can be zero (e.g. on the first and last iteration). // In this case we can't calculate a meaningful new thread distribution if (read_throughput_per_thread == 0 || index_throughput_per_thread == 0) { return { _num_read_threads, _num_index_threads }; } const auto exact_index_threads = total_thread_count / (1 + (index_throughput_per_thread / read_throughput_per_thread)); const auto exact_read_threads = total_thread_count - exact_index_threads; const auto rounded_read_threads = std::ceil(exact_read_threads); const auto max_read_threads = std::min(total_thread_count - 1, remaining_files); _num_read_threads = gsl::narrow_cast<uint32_t>( std::min<double>(max_read_threads, rounded_read_threads)); _num_index_threads = total_thread_count - _num_read_threads; return { _num_read_threads, _num_index_threads }; }
36.412121
80
0.675266
igd-geo
dcce0ed1d440d4e5c460ae7a10f3abf60b064485
2,031
cc
C++
RecoParticleFlow/PFClusterProducer/plugins/ECALPFSeedCleaner.cc
Purva-Chaudhari/cmssw
32e5cbfe54c4d809d60022586cf200b7c3020bcf
[ "Apache-2.0" ]
852
2015-01-11T21:03:51.000Z
2022-03-25T21:14:00.000Z
RecoParticleFlow/PFClusterProducer/plugins/ECALPFSeedCleaner.cc
Purva-Chaudhari/cmssw
32e5cbfe54c4d809d60022586cf200b7c3020bcf
[ "Apache-2.0" ]
30,371
2015-01-02T00:14:40.000Z
2022-03-31T23:26:05.000Z
RecoParticleFlow/PFClusterProducer/plugins/ECALPFSeedCleaner.cc
Purva-Chaudhari/cmssw
32e5cbfe54c4d809d60022586cf200b7c3020bcf
[ "Apache-2.0" ]
3,240
2015-01-02T05:53:18.000Z
2022-03-31T17:24:21.000Z
#include "CondFormats/DataRecord/interface/EcalPFSeedingThresholdsRcd.h" #include "CondFormats/EcalObjects/interface/EcalPFSeedingThresholds.h" #include "RecoParticleFlow/PFClusterProducer/interface/RecHitTopologicalCleanerBase.h" class ECALPFSeedCleaner : public RecHitTopologicalCleanerBase { public: ECALPFSeedCleaner(const edm::ParameterSet& conf, edm::ConsumesCollector& cc); ECALPFSeedCleaner(const ECALPFSeedCleaner&) = delete; ECALPFSeedCleaner& operator=(const ECALPFSeedCleaner&) = delete; void update(const edm::EventSetup&) override; void clean(const edm::Handle<reco::PFRecHitCollection>& input, std::vector<bool>& mask) override; private: edm::ESHandle<EcalPFSeedingThresholds> ths_; edm::ESGetToken<EcalPFSeedingThresholds, EcalPFSeedingThresholdsRcd> thsToken_; }; DEFINE_EDM_PLUGIN(RecHitTopologicalCleanerFactory, ECALPFSeedCleaner, "ECALPFSeedCleaner"); ECALPFSeedCleaner::ECALPFSeedCleaner(const edm::ParameterSet& conf, edm::ConsumesCollector& cc) : RecHitTopologicalCleanerBase(conf, cc), thsToken_(cc.esConsumes<edm::Transition::BeginLuminosityBlock>()) {} void ECALPFSeedCleaner::update(const edm::EventSetup& iSetup) { ths_ = iSetup.getHandle(thsToken_); } void ECALPFSeedCleaner::clean(const edm::Handle<reco::PFRecHitCollection>& input, std::vector<bool>& mask) { //need to run over energy sorted rechits, as this is order used in seeding step // this can cause ambiguity, isn't it better to index by detid ? auto const& hits = *input; std::vector<unsigned> ordered_hits(hits.size()); for (unsigned i = 0; i < hits.size(); ++i) ordered_hits[i] = i; std::sort(ordered_hits.begin(), ordered_hits.end(), [&](unsigned i, unsigned j) { return hits[i].energy() > hits[j].energy(); }); for (const auto& idx : ordered_hits) { if (!mask[idx]) continue; // is it useful ? const reco::PFRecHit& rechit = hits[idx]; float threshold = (*ths_)[rechit.detId()]; if (rechit.energy() < threshold) mask[idx] = false; } // rechit loop }
40.62
114
0.743968
Purva-Chaudhari
dcceb8b3b20685b8b2bb61e847810b3470c47996
403
hpp
C++
Spike/Backend/Dummy/Synapses/Synapses.hpp
elliotelliot/Spike
a2ecda4d7e0395a6693d4a10932ad72f58b156af
[ "MIT" ]
null
null
null
Spike/Backend/Dummy/Synapses/Synapses.hpp
elliotelliot/Spike
a2ecda4d7e0395a6693d4a10932ad72f58b156af
[ "MIT" ]
1
2019-08-16T21:18:21.000Z
2019-08-16T21:18:21.000Z
Spike/Backend/Dummy/Synapses/Synapses.hpp
elliotelliot/Spike
a2ecda4d7e0395a6693d4a10932ad72f58b156af
[ "MIT" ]
4
2019-09-02T14:06:08.000Z
2020-02-20T05:36:46.000Z
#pragma once #include "Spike/Synapses/Synapses.hpp" namespace Backend { namespace Dummy { class Synapses : public virtual ::Backend::Synapses { public: ~Synapses() override = default; void prepare() override; void reset_state() override; void copy_to_frontend() override; void copy_to_backend() override; }; } // namespace Dummy } // namespace Backend
20.15
57
0.665012
elliotelliot
dcced838bfab5c139c3d430666f146f38aca72c2
3,451
cpp
C++
224BasicCalculator.cpp
yuyangh/LeetCode
5d81cbd975c0c1f2bbca0cb25cefe361a169e460
[ "MIT" ]
1
2020-10-11T08:10:53.000Z
2020-10-11T08:10:53.000Z
224BasicCalculator.cpp
yuyangh/LeetCode
5d81cbd975c0c1f2bbca0cb25cefe361a169e460
[ "MIT" ]
null
null
null
224BasicCalculator.cpp
yuyangh/LeetCode
5d81cbd975c0c1f2bbca0cb25cefe361a169e460
[ "MIT" ]
null
null
null
#include "LeetCodeLib.h" class Solution { public: // iterative approach int calculate(string s) { int result = 0; int sign = 1; stack<int> st; for (int i = 0; i < s.size(); i++) { // get the number from string if (s[i] >= '0') { int num = 0; while (i < s.size() && s[i] >= '0') { num *= 10; num += int(s[i]) - '0'; i++; } i--; result += num * sign; } else if (s[i] == '+') { sign = 1; } else if (s[i] == '-') { sign = -1; } else if (s[i] == '(') { st.push(result); st.push(sign); result = 0; sign = 1; } else if (s[i] == ')') { sign = st.top(); st.pop(); result *= sign; result += st.top(); st.pop(); } } return result; } // prev own approach // #define LEFT_PARA_VALUE -999999 /* -999999 represents '('*/ // stack<int> reverse, order; // int calculate(string s) { // int result = 0; // // for (int i = 0; i < s.size(); ++i) { // if (s[i] == ' ') { // continue; // } // if(s[i]=='('){ // reverse.push(LEFT_PARA_VALUE); // continue; // } // if (s[i] == ')') { // while (reverse.top() != LEFT_PARA_VALUE/*represents '('*/) { // order.push(reverse.top()); // reverse.pop(); // } // reverse.pop();// get rid of "(" // result = calculatePara(); // reverse.push(result); // } else { // // check each input is a num or not // if (isdigit(s[i])) { // string numString = s.substr(i, 20); // int num = stoi(numString); // reverse.push(num); // i += to_string(num).size() - 1; // } else { // reverse.push((s[i])); // } // } // } // // // handle all nums in () // if (reverse.empty()) { // return result; // } else { // while (!reverse.empty()) { // order.push(reverse.top()); // reverse.pop(); // } // return calculatePara(); // } // } // // int calculatePara() { // if(order.empty()){ // cout<<"Problem in order stack"<<endl; // return 0; // } // int result = (order.top()), right; // int op; // order.pop(); // // do operations on each num // while (!order.empty()) { // op = order.top(); // order.pop(); // right = order.top(); // order.pop(); // if (op == '+') { // result = result + right; // } else { // result = result - right; // } // } // return result; // } }; string stringToString(string input) { assert(input.length() >= 2); string result; for (int i = 1; i < input.length() - 1; i++) { char currentChar = input[i]; if (input[i] == '\\') { char nextChar = input[i + 1]; switch (nextChar) { case '\"': result.push_back('\"'); break; case '/' : result.push_back('/'); break; case '\\': result.push_back('\\'); break; case 'b' : result.push_back('\b'); break; case 'f' : result.push_back('\f'); break; case 'r' : result.push_back('\r'); break; case 'n' : result.push_back('\n'); break; case 't' : result.push_back('\t'); break; default: break; } i++; } else { result.push_back(currentChar); } } return result; } int main() { string line; while (getline(cin, line)) { string s = stringToString(line); int ret = Solution().calculate(s); string out = to_string(ret); cout << out << endl; } return 0; } /* * testcase * "1 + 1"=2 * "(1+(4+5+2)-3)+(6+8)"=23 * */
19.833333
67
0.474065
yuyangh
dcd079abf4a416110e6198d5a8b999d35bc2f049
794
cpp
C++
answers/codeforces/534B Covered Path.cpp
FeiZhan/Algo-Collection
708c4a38112e0b381864809788b9e44ac5ae4d05
[ "MIT" ]
3
2015-09-04T21:32:31.000Z
2020-12-06T00:37:32.000Z
answers/codeforces/534B Covered Path.cpp
FeiZhan/Algo-Collection
708c4a38112e0b381864809788b9e44ac5ae4d05
[ "MIT" ]
null
null
null
answers/codeforces/534B Covered Path.cpp
FeiZhan/Algo-Collection
708c4a38112e0b381864809788b9e44ac5ae4d05
[ "MIT" ]
null
null
null
//@type greedy, DP //@result 12964986 2015-09-11 22:53:08 zetta217 534B - Covered Path GNU C++ Accepted 15 ms 0 KB // I don't use DP #include <iostream> using namespace std; int main() { int begin(0); int end(0); while (cin >> begin >> end) { if (begin > end) { int temp = begin; begin = end; end = temp; } int time(0); int change(0); cin >> time >> change; int current(begin); int distance(begin); for (int i = 1; i + 1 < time; ++ i) { current = current + change; if (current > end && current - change * (time - 1 - i) > end) { current = end + change * (time - 1 - i); } distance += current; //cout << "test " << i << " " << current << " " << distance << endl; } cout << distance + end << endl; } return 0; }
24.8125
96
0.531486
FeiZhan
dcd1f03705bda70716cfff206fff0721f0f39208
2,928
cp
C++
src/TFractalViewerWindow.cp
pfuentes69/FractalViewer
397bc2c7f1182d016ff57fbf93a5f6da302bd06e
[ "Apache-2.0" ]
null
null
null
src/TFractalViewerWindow.cp
pfuentes69/FractalViewer
397bc2c7f1182d016ff57fbf93a5f6da302bd06e
[ "Apache-2.0" ]
null
null
null
src/TFractalViewerWindow.cp
pfuentes69/FractalViewer
397bc2c7f1182d016ff57fbf93a5f6da302bd06e
[ "Apache-2.0" ]
null
null
null
/***** * TFractalViewerWindow.c * * The window methods for the application. * * TFractalViewerWindow inherits its Draw method from TWindow. * TMandelbrot, TJulia, and others override DrawShape to draw their own kind of CGI. * *****/ #include <Packages.h> // for NumToString prototype #include "TFractalViewerWindow.h" #include <stdlib.h> #include "Utils.h" /**** * TFractalViewerWindow constructor * * Create a bullseye window. This constructor relies * on the TWindow constructor to place the window in * in attractive place. Then it appends a number to the * window title. * ****/ TFractalViewerWindow::TFractalViewerWindow(void) { Str15 numStr; Str255 title; long windowNumber; // Set the title of the window to be // the title in the resource // plus the window counter. // The window counter is a class variable // declared in the TWindow class. GetWindowTitle(title); windowNumber = GetWindowNumber(); NumToString(GetWindowNumber(), numStr); concat(title, numStr); SetWindowTitle(title); } /**** * Hit * * Handle a mouse down in the window. * Bullseye window just force a refresh. * ****/ void TFractalViewerWindow::Hit(Point where) { RefreshWindow(false); // preserve the scroll bars } /**** * GetStyle * SetStyle * * Get and set the color style * ****/ short TFractalViewerWindow::GetStyle() { return style; } void TFractalViewerWindow::SetStyle(short w) { style = w; RefreshWindow(true); } short TFractalViewerWindow::GetDrawMode() { return drawMode; } void TFractalViewerWindow::SetDrawMode(short m) { if (drawMode != m) { drawMode = m; RefreshWindow(true); } } /**** * Draw * * Draw the bullseye figures. * Repeatedly call DrawShape with a smaller drawing area. * The drawing area gets smaller by 2 * the width. * ****/ void TFractalViewerWindow::Draw(void) { RgnHandle saveClip = NewRgn(); PenState pen; Rect drawingRect; GetPenState(&pen); GetClip(saveClip); inherited::Draw(); GetWindowRect(&drawingRect, false); // Don't draw in the scroll // bar areas. Note that it's // ok to pass the address of // drawingRect because // GetWindowRect won't move // memory. sTop = drawingRect.top; sLeft = drawingRect.left; DrawShape(&drawingRect); SetClip(saveClip); DisposeRgn(saveClip); SetPenState(&pen); } /**** * DrawShape methods * * These are the DrawShape methods for * TBullWindow: does nothing * TCircleBull: Circles * TSquareBull: Squares * TPlasma: "Triangles" * * All the DrawShape methods take a drawingRect * as a parameter. The pen width * is already set to the appropriate width. * ****/ void TFractalViewerWindow::DrawShape(Rect *drawingRect) { } // // ZOOM CONTENT // void TFractalViewerWindow::ZoomContent(short z) { RefreshWindow(false); // preserve the scroll bars }
2,928
2,928
0.676913
pfuentes69
dcd24d5a9b94a8f29c988684fd2c44d7ab91e342
1,105
cpp
C++
test/data-tests/testcases/test-123.cpp
zhaitianduo/libosmium
42fc3238f942baac47d8520425664376478718b1
[ "BSL-1.0" ]
4,526
2015-01-01T15:31:00.000Z
2022-03-31T17:33:49.000Z
test/data-tests/testcases/test-123.cpp
zhaitianduo/libosmium
42fc3238f942baac47d8520425664376478718b1
[ "BSL-1.0" ]
4,497
2015-01-01T15:29:12.000Z
2022-03-31T19:19:35.000Z
test/data-tests/testcases/test-123.cpp
zhaitianduo/libosmium
42fc3238f942baac47d8520425664376478718b1
[ "BSL-1.0" ]
3,023
2015-01-01T18:40:53.000Z
2022-03-30T13:30:46.000Z
#include <cstring> #include <stdexcept> #include "common.hpp" class TestHandler123 : public osmium::handler::Handler { public: TestHandler123() : osmium::handler::Handler() { } void way(const osmium::Way& way) const { if (way.id() == 123800) { REQUIRE(way.version() == 1); REQUIRE(way.nodes().size() == 2); REQUIRE(way.nodes()[0] != way.nodes()[1]); REQUIRE(way.nodes()[0].location() == way.nodes()[1].location()); } else { throw std::runtime_error{"Unknown ID"}; } } }; // class TestHandler123 TEST_CASE("123") { osmium::io::Reader reader{dirname + "/1/123/data.osm"}; index_pos_type index_pos; index_neg_type index_neg; location_handler_type location_handler{index_pos, index_neg}; location_handler.ignore_errors(); CheckBasicsHandler check_basics_handler{123, 2, 1, 0}; CheckWKTHandler check_wkt_handler{dirname, 123}; TestHandler123 test_handler; osmium::apply(reader, location_handler, check_basics_handler, check_wkt_handler, test_handler); }
25.697674
99
0.637104
zhaitianduo
dcd9006f6fd4f19c1f158d2653e87a8ec15083c8
17,392
cc
C++
chrome/test/chromedriver/chrome/chrome_desktop_impl.cc
zipated/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
2,151
2020-04-18T07:31:17.000Z
2022-03-31T08:39:18.000Z
chrome/test/chromedriver/chrome/chrome_desktop_impl.cc
cangulcan/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
395
2020-04-18T08:22:18.000Z
2021-12-08T13:04:49.000Z
chrome/test/chromedriver/chrome/chrome_desktop_impl.cc
cangulcan/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
338
2020-04-18T08:03:10.000Z
2022-03-29T12:33:22.000Z
// Copyright (c) 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/test/chromedriver/chrome/chrome_desktop_impl.h" #include <stddef.h> #include <utility> #include "base/files/file_path.h" #include "base/logging.h" #include "base/posix/eintr_wrapper.h" #include "base/process/kill.h" #include "base/strings/string_util.h" #include "base/sys_info.h" #include "base/threading/platform_thread.h" #include "base/time/time.h" #include "build/build_config.h" #include "chrome/test/chromedriver/chrome/automation_extension.h" #include "chrome/test/chromedriver/chrome/devtools_client.h" #include "chrome/test/chromedriver/chrome/devtools_event_listener.h" #include "chrome/test/chromedriver/chrome/devtools_http_client.h" #include "chrome/test/chromedriver/chrome/status.h" #include "chrome/test/chromedriver/chrome/web_view_impl.h" #include "chrome/test/chromedriver/net/timeout.h" #if defined(OS_POSIX) #include <errno.h> #include <signal.h> #include <sys/wait.h> #include <unistd.h> #endif namespace { // Enables wifi and data only, not airplane mode. const int kDefaultConnectionType = 6; bool KillProcess(const base::Process& process, bool kill_gracefully) { #if defined(OS_POSIX) if (!kill_gracefully) { kill(process.Pid(), SIGKILL); base::TimeTicks deadline = base::TimeTicks::Now() + base::TimeDelta::FromSeconds(30); while (base::TimeTicks::Now() < deadline) { pid_t pid = HANDLE_EINTR(waitpid(process.Pid(), NULL, WNOHANG)); if (pid == process.Pid()) return true; if (pid == -1) { if (errno == ECHILD) { // The wait may fail with ECHILD if another process also waited for // the same pid, causing the process state to get cleaned up. return true; } LOG(WARNING) << "Error waiting for process " << process.Pid(); } base::PlatformThread::Sleep(base::TimeDelta::FromMilliseconds(50)); } return false; } #endif if (!process.Terminate(0, true)) { int exit_code; return base::GetTerminationStatus(process.Handle(), &exit_code) != base::TERMINATION_STATUS_STILL_RUNNING; } return true; } } // namespace ChromeDesktopImpl::ChromeDesktopImpl( std::unique_ptr<DevToolsHttpClient> http_client, std::unique_ptr<DevToolsClient> websocket_client, std::vector<std::unique_ptr<DevToolsEventListener>> devtools_event_listeners, std::string page_load_strategy, base::Process process, const base::CommandLine& command, base::ScopedTempDir* user_data_dir, base::ScopedTempDir* extension_dir, bool network_emulation_enabled) : ChromeImpl(std::move(http_client), std::move(websocket_client), std::move(devtools_event_listeners), page_load_strategy), process_(std::move(process)), command_(command), network_connection_enabled_(network_emulation_enabled), network_connection_(kDefaultConnectionType) { if (user_data_dir->IsValid()) CHECK(user_data_dir_.Set(user_data_dir->Take())); if (extension_dir->IsValid()) CHECK(extension_dir_.Set(extension_dir->Take())); } ChromeDesktopImpl::~ChromeDesktopImpl() { if (!quit_) { base::FilePath user_data_dir = user_data_dir_.Take(); base::FilePath extension_dir = extension_dir_.Take(); LOG(WARNING) << "chrome quit unexpectedly, leaving behind temporary " "directories for debugging:"; if (user_data_dir_.IsValid()) LOG(WARNING) << "chrome user data directory: " << user_data_dir.value(); if (extension_dir_.IsValid()) LOG(WARNING) << "chromedriver automation extension directory: " << extension_dir.value(); } } Status ChromeDesktopImpl::WaitForPageToLoad( const std::string& url, const base::TimeDelta& timeout_raw, std::unique_ptr<WebView>* web_view, bool w3c_compliant) { Timeout timeout(timeout_raw); std::string id; WebViewInfo::Type type = WebViewInfo::Type::kPage; while (timeout.GetRemainingTime() > base::TimeDelta()) { WebViewsInfo views_info; Status status = devtools_http_client_->GetWebViewsInfo(&views_info); if (status.IsError()) return status; for (size_t i = 0; i < views_info.GetSize(); ++i) { const WebViewInfo& view_info = views_info.Get(i); if (base::StartsWith(view_info.url, url, base::CompareCase::SENSITIVE)) { id = view_info.id; type = view_info.type; break; } } if (!id.empty()) break; base::PlatformThread::Sleep(base::TimeDelta::FromMilliseconds(100)); } if (id.empty()) return Status(kUnknownError, "page could not be found: " + url); const DeviceMetrics* device_metrics = devtools_http_client_->device_metrics(); if (type == WebViewInfo::Type::kApp || type == WebViewInfo::Type::kBackgroundPage) { // Apps and extensions don't work on Android, so it doesn't make sense to // provide override device metrics in mobile emulation mode, and can also // potentially crash the renderer, for more details see: // https://code.google.com/p/chromedriver/issues/detail?id=1205 device_metrics = nullptr; } std::unique_ptr<WebView> web_view_tmp( new WebViewImpl(id, w3c_compliant, devtools_http_client_->browser_info(), devtools_http_client_->CreateClient(id), device_metrics, page_load_strategy())); Status status = web_view_tmp->ConnectIfNecessary(); if (status.IsError()) return status; status = web_view_tmp->WaitForPendingNavigations( std::string(), timeout, false); if (status.IsOk()) *web_view = std::move(web_view_tmp); return status; } Status ChromeDesktopImpl::GetAutomationExtension( AutomationExtension** extension, bool w3c_compliant) { if (!automation_extension_) { std::unique_ptr<WebView> web_view; Status status = WaitForPageToLoad( "chrome-extension://aapnijgdinlhnhlmodcfapnahmbfebeb/" "_generated_background_page.html", base::TimeDelta::FromSeconds(10), &web_view, w3c_compliant); if (status.IsError()) return Status(kUnknownError, "cannot get automation extension", status); automation_extension_.reset(new AutomationExtension(std::move(web_view))); } *extension = automation_extension_.get(); return Status(kOk); } Status ChromeDesktopImpl::GetAsDesktop(ChromeDesktopImpl** desktop) { *desktop = this; return Status(kOk); } std::string ChromeDesktopImpl::GetOperatingSystemName() { return base::SysInfo::OperatingSystemName(); } bool ChromeDesktopImpl::IsMobileEmulationEnabled() const { return devtools_http_client_->device_metrics() != NULL; } bool ChromeDesktopImpl::HasTouchScreen() const { return IsMobileEmulationEnabled(); } bool ChromeDesktopImpl::IsNetworkConnectionEnabled() const { return network_connection_enabled_; } Status ChromeDesktopImpl::QuitImpl() { Status status = devtools_websocket_client_->ConnectIfNecessary(); if (status.IsOk()) { status = devtools_websocket_client_->SendCommandAndIgnoreResponse( "Browser.close", base::DictionaryValue()); if (status.IsOk() && process_.WaitForExitWithTimeout( base::TimeDelta::FromSeconds(10), nullptr)) return status; } // If the Chrome session uses a custom user data directory, try sending a // SIGTERM signal before SIGKILL, so that Chrome has a chance to write // everything back out to the user data directory and exit cleanly. If we're // using a temporary user data directory, we're going to delete the temporary // directory anyway, so just send SIGKILL immediately. bool kill_gracefully = !user_data_dir_.IsValid(); // If the Chrome session is being run with --log-net-log, send SIGTERM first // to allow Chrome to write out all the net logs to the log path. kill_gracefully |= command_.HasSwitch("log-net-log"); if (!KillProcess(process_, kill_gracefully)) return Status(kUnknownError, "cannot kill Chrome"); return Status(kOk); } const base::CommandLine& ChromeDesktopImpl::command() const { return command_; } int ChromeDesktopImpl::GetNetworkConnection() const { return network_connection_; } void ChromeDesktopImpl::SetNetworkConnection( int network_connection) { network_connection_ = network_connection; } Status ChromeDesktopImpl::GetWindowPosition(const std::string& target_id, int* x, int* y) { Window window; Status status = GetWindow(target_id, &window); if (status.IsError()) return status; *x = window.left; *y = window.top; return Status(kOk); } Status ChromeDesktopImpl::GetWindowSize(const std::string& target_id, int* width, int* height) { Window window; Status status = GetWindow(target_id, &window); if (status.IsError()) return status; *width = window.width; *height = window.height; return Status(kOk); } Status ChromeDesktopImpl::SetWindowRect(const std::string& target_id, const base::DictionaryValue& params) { Window window; Status status = GetWindow(target_id, &window); if (status.IsError()) return status; auto bounds = std::make_unique<base::DictionaryValue>(); // fully exit fullscreen if (window.state != "normal") { auto bounds = std::make_unique<base::DictionaryValue>(); bounds->SetString("windowState", "normal"); status = SetWindowBounds(window.id, std::move(bounds)); if (status.IsError()) return status; } // window position int x = 0; int y = 0; if (params.GetInteger("x", &x) && params.GetInteger("y", &y)) { bounds->SetInteger("left", x); bounds->SetInteger("top", y); } // window size int width = 0; int height = 0; if (params.GetInteger("width", &width) && params.GetInteger("height", &height)) { bounds->SetInteger("width", width); bounds->SetInteger("height", height); } return SetWindowBounds(window.id, std::move(bounds)); } Status ChromeDesktopImpl::SetWindowPosition(const std::string& target_id, int x, int y) { Window window; Status status = GetWindow(target_id, &window); if (status.IsError()) return status; if (window.state != "normal") { // restore window to normal first to allow position change. auto bounds = std::make_unique<base::DictionaryValue>(); bounds->SetString("windowState", "normal"); status = SetWindowBounds(window.id, std::move(bounds)); if (status.IsError()) return status; } auto bounds = std::make_unique<base::DictionaryValue>(); bounds->SetInteger("left", x); bounds->SetInteger("top", y); return SetWindowBounds(window.id, std::move(bounds)); } Status ChromeDesktopImpl::SetWindowSize(const std::string& target_id, int width, int height) { Window window; Status status = GetWindow(target_id, &window); if (status.IsError()) return status; if (window.state != "normal") { // restore window to normal first to allow size change. auto bounds = std::make_unique<base::DictionaryValue>(); bounds->SetString("windowState", "normal"); status = SetWindowBounds(window.id, std::move(bounds)); if (status.IsError()) return status; } auto bounds = std::make_unique<base::DictionaryValue>(); bounds->SetInteger("width", width); bounds->SetInteger("height", height); return SetWindowBounds(window.id, std::move(bounds)); } Status ChromeDesktopImpl::MaximizeWindow(const std::string& target_id) { Window window; Status status = GetWindow(target_id, &window); if (status.IsError()) return status; if (window.state == "maximized") return Status(kOk); if (window.state != "normal") { // always restore window to normal first, since chrome ui doesn't allow // maximizing a minimized or fullscreen window. auto bounds = std::make_unique<base::DictionaryValue>(); bounds->SetString("windowState", "normal"); status = SetWindowBounds(window.id, std::move(bounds)); if (status.IsError()) return status; } auto bounds = std::make_unique<base::DictionaryValue>(); bounds->SetString("windowState", "maximized"); return SetWindowBounds(window.id, std::move(bounds)); } Status ChromeDesktopImpl::MinimizeWindow(const std::string& target_id) { Window window; Status status = GetWindow(target_id, &window); if (status.IsError()) return status; if (window.state == "minimized") return Status(kOk); if (window.state != "normal") { // restore window to normal first auto bounds = std::make_unique<base::DictionaryValue>(); bounds->SetString("windowState", "normal"); status = SetWindowBounds(window.id, std::move(bounds)); if (status.IsError()) return status; } auto bounds = std::make_unique<base::DictionaryValue>(); bounds->SetString("windowState", "minimized"); return SetWindowBounds(window.id, std::move(bounds)); } Status ChromeDesktopImpl::FullScreenWindow(const std::string& target_id) { Window window; Status status = GetWindow(target_id, &window); if (status.IsError()) return status; if (window.state == "fullscreen") return Status(kOk); if (window.state != "normal") { auto bounds = std::make_unique<base::DictionaryValue>(); bounds->SetString("windowState", "normal"); status = SetWindowBounds(window.id, std::move(bounds)); if (status.IsError()) return status; } auto bounds = std::make_unique<base::DictionaryValue>(); bounds->SetString("windowState", "fullscreen"); return SetWindowBounds(window.id, std::move(bounds)); } Status ChromeDesktopImpl::ParseWindowBounds( std::unique_ptr<base::DictionaryValue> params, Window* window) { const base::Value* value = nullptr; const base::DictionaryValue* bounds_dict = nullptr; if (!params->Get("bounds", &value) || !value->GetAsDictionary(&bounds_dict)) return Status(kUnknownError, "no window bounds in response"); if (!bounds_dict->GetString("windowState", &window->state)) return Status(kUnknownError, "no window state in window bounds"); if (!bounds_dict->GetInteger("left", &window->left)) return Status(kUnknownError, "no left offset in window bounds"); if (!bounds_dict->GetInteger("top", &window->top)) return Status(kUnknownError, "no top offset in window bounds"); if (!bounds_dict->GetInteger("width", &window->width)) return Status(kUnknownError, "no width in window bounds"); if (!bounds_dict->GetInteger("height", &window->height)) return Status(kUnknownError, "no height in window bounds"); return Status(kOk); } Status ChromeDesktopImpl::ParseWindow( std::unique_ptr<base::DictionaryValue> params, Window* window) { if (!params->GetInteger("windowId", &window->id)) return Status(kUnknownError, "no window id in response"); return ParseWindowBounds(std::move(params), window); } Status ChromeDesktopImpl::GetWindow(const std::string& target_id, Window* window) { Status status = devtools_websocket_client_->ConnectIfNecessary(); if (status.IsError()) return status; base::DictionaryValue params; params.SetString("targetId", target_id); std::unique_ptr<base::DictionaryValue> result; status = devtools_websocket_client_->SendCommandAndGetResult( "Browser.getWindowForTarget", params, &result); if (status.IsError()) return status; return ParseWindow(std::move(result), window); } Status ChromeDesktopImpl::GetWindowBounds(int window_id, Window* window) { Status status = devtools_websocket_client_->ConnectIfNecessary(); if (status.IsError()) return status; base::DictionaryValue params; params.SetInteger("windowId", window_id); std::unique_ptr<base::DictionaryValue> result; status = devtools_websocket_client_->SendCommandAndGetResult( "Browser.getWindowBounds", params, &result); if (status.IsError()) return status; return ParseWindowBounds(std::move(result), window); } Status ChromeDesktopImpl::SetWindowBounds( int window_id, std::unique_ptr<base::DictionaryValue> bounds) { Status status = devtools_websocket_client_->ConnectIfNecessary(); if (status.IsError()) return status; base::DictionaryValue params; params.SetInteger("windowId", window_id); params.Set("bounds", bounds->CreateDeepCopy()); status = devtools_websocket_client_->SendCommand("Browser.setWindowBounds", params); if (status.IsError()) return status; base::PlatformThread::Sleep(base::TimeDelta::FromMilliseconds(100)); std::string state; if (!bounds->GetString("windowState", &state)) return Status(kOk); Window window; status = GetWindowBounds(window_id, &window); if (status.IsError()) return status; if (window.state != state) return Status(kUnknownError, "failed to change window state to " + state + ", current state is " + window.state); return Status(kOk); }
33.770874
80
0.683188
zipated
dcddf1ed62acf71cefecdfbb5e14b82b07b2098d
6,223
hpp
C++
Visitors/AcceptanceVisitors/DilatedVarianceDifferenceAcceptanceVisitor.hpp
jingtangliao/ff
d308fe62045e241a4822bb855df97ee087420d9b
[ "Apache-2.0" ]
39
2015-01-01T07:59:51.000Z
2021-10-01T18:11:46.000Z
Visitors/AcceptanceVisitors/DilatedVarianceDifferenceAcceptanceVisitor.hpp
jingtangliao/ff
d308fe62045e241a4822bb855df97ee087420d9b
[ "Apache-2.0" ]
1
2019-04-24T09:56:15.000Z
2019-04-24T14:45:46.000Z
Visitors/AcceptanceVisitors/DilatedVarianceDifferenceAcceptanceVisitor.hpp
jingtangliao/ff
d308fe62045e241a4822bb855df97ee087420d9b
[ "Apache-2.0" ]
18
2015-01-11T15:10:23.000Z
2022-02-24T20:02:10.000Z
/*========================================================================= * * Copyright David Doria 2012 daviddoria@gmail.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *=========================================================================*/ #ifndef DilatedVarianceDifferenceAcceptanceVisitor_HPP #define DilatedVarianceDifferenceAcceptanceVisitor_HPP #include <boost/graph/graph_traits.hpp> // Parent class #include "Visitors/AcceptanceVisitors/AcceptanceVisitorParent.h" // Custom #include <Mask/Mask.h> #include <ITKHelpers/ITKHelpers.h> // ITK #include "itkImage.h" #include "itkImageRegion.h" /** */ template <typename TGraph, typename TImage> struct DilatedVarianceDifferenceAcceptanceVisitor : public AcceptanceVisitorParent<TGraph> { TImage* Image; Mask* MaskImage; const unsigned int HalfWidth; unsigned int NumberOfFinishedVertices = 0; float DifferenceThreshold; typedef typename boost::graph_traits<TGraph>::vertex_descriptor VertexDescriptorType; DilatedVarianceDifferenceAcceptanceVisitor(TImage* const image, Mask* const mask, const unsigned int halfWidth, const float differenceThreshold = 100) : Image(image), MaskImage(mask), HalfWidth(halfWidth), DifferenceThreshold(differenceThreshold) { } bool AcceptMatch(VertexDescriptorType target, VertexDescriptorType source, float& computedEnergy) const override { //std::cout << "DilatedVarianceDifferenceAcceptanceVisitor::AcceptMatch" << std::endl; itk::Index<2> targetPixel = ITKHelpers::CreateIndex(target); itk::ImageRegion<2> targetRegion = ITKHelpers::GetRegionInRadiusAroundPixel(targetPixel, HalfWidth); itk::Index<2> sourcePixel = ITKHelpers::CreateIndex(source); itk::ImageRegion<2> sourceRegion = ITKHelpers::GetRegionInRadiusAroundPixel(sourcePixel, HalfWidth); //std::cout << "Extracting target region mask..." << std::endl; Mask::Pointer targetRegionMask = Mask::New(); ITKHelpers::ExtractRegion(MaskImage, targetRegion, targetRegionMask.GetPointer()); //std::cout << "There are " << ITKHelpers::CountPixelsWithValue(targetRegionMask.GetPointer(), targetRegionMask->GetHoleValue()) << " hole pixels in the target region." << std::endl; //std::cout << "Dilating target region mask..." << std::endl; Mask::Pointer dilatedTargetRegionMask = Mask::New(); ITKHelpers::DilateImage(targetRegionMask.GetPointer(), dilatedTargetRegionMask.GetPointer(), 6); //std::cout << "There are " << ITKHelpers::CountPixelsWithValue(dilatedTargetRegionMask.GetPointer(), dilatedTargetRegionMask->GetHoleValue()) << " dilated hole pixels in the target region." << std::endl; // Separate so that only the newly dilated part of the hole remains //std::cout << "XORing dilated target mask with target mask..." << std::endl; typedef itk::Image<bool, 2> BoolImage; BoolImage::Pointer rindImage = BoolImage::New(); // "rind" like an "orange rind" ITKHelpers::XORRegions(targetRegionMask.GetPointer(), targetRegionMask->GetLargestPossibleRegion(), dilatedTargetRegionMask.GetPointer(), dilatedTargetRegionMask->GetLargestPossibleRegion(), rindImage.GetPointer()); //std::cout << "There are " << ITKHelpers::CountPixelsWithValue(rindImage.GetPointer(), true) << " XORed hole pixels in the target region." << std::endl; std::vector<itk::Index<2> > rindPixels = ITKHelpers::GetPixelsWithValue(rindImage.GetPointer(), rindImage->GetLargestPossibleRegion(), true); //std::cout << "There are " << rindPixels.size() << " rindPixels." << std::endl; std::vector<itk::Offset<2> > rindOffsets = ITKHelpers::IndicesToOffsets(rindPixels, ITKHelpers::ZeroIndex()); //std::cout << "There are " << rindOffsets.size() << " rindOffsets." << std::endl; //std::cout << "Computing variances..." << std::endl; // Compute the variance of the rind pixels in the target region std::vector<itk::Index<2> > targetRindPixels = ITKHelpers::OffsetsToIndices(rindOffsets, targetRegion.GetIndex()); //std::cout << "There are " << targetRindPixels.size() << " targetRindPixels." << std::endl; //std::cout << "Computing target variances..." << std::endl; typename TImage::PixelType targetRegionSourcePixelVariance = ITKHelpers::VarianceOfPixelsAtIndices(Image, targetRindPixels); //std::cout << "targetRegionSourcePixelVariance: " << targetRegionSourcePixelVariance << std::endl; // Compute the variance of the rind pixels in the source region std::vector<itk::Index<2> > sourceRindPixels = ITKHelpers::OffsetsToIndices(rindOffsets, sourceRegion.GetIndex()); //std::cout << "There are " << sourceRindPixels.size() << " targetRindPixels." << std::endl; //std::cout << "Computing source variances..." << std::endl; typename TImage::PixelType sourceRegionTargetPixelVariance = ITKHelpers::VarianceOfPixelsAtIndices(Image, sourceRindPixels); //std::cout << "sourceRegionTargetPixelVariance: " << sourceRegionTargetPixelVariance << std::endl; // Compute the difference computedEnergy = (targetRegionSourcePixelVariance - sourceRegionTargetPixelVariance).GetNorm(); std::cout << "DilatedVarianceDifferenceAcceptanceVisitor Energy: " << computedEnergy << std::endl; if(computedEnergy < DifferenceThreshold) { std::cout << "DilatedVarianceDifferenceAcceptanceVisitor: Match accepted (less than " << DifferenceThreshold << ")" << std::endl; return true; } else { std::cout << "DilatedVarianceDifferenceAcceptanceVisitor: Match rejected (greater than " << DifferenceThreshold << ")" << std::endl; return false; } }; }; #endif
49.388889
208
0.703198
jingtangliao
dcdf01b01665dec4690b9d0213b32be1f7039302
7,145
cpp
C++
vfd_bench/custom/src/vfd_task.cpp
milesfrain/stm32template
c7a55661c21a3ea0266b1e3950c6fb5210ccff25
[ "CC0-1.0" ]
1
2021-07-26T16:27:28.000Z
2021-07-26T16:27:28.000Z
vfd_bench/custom/src/vfd_task.cpp
milesfrain/stm32template
c7a55661c21a3ea0266b1e3950c6fb5210ccff25
[ "CC0-1.0" ]
3
2020-10-23T22:59:07.000Z
2020-10-23T23:02:35.000Z
vfd_bench/custom/src/vfd_task.cpp
milesfrain/stm32template
c7a55661c21a3ea0266b1e3950c6fb5210ccff25
[ "CC0-1.0" ]
1
2022-01-18T04:57:14.000Z
2022-01-18T04:57:14.000Z
/* * See header for notes. */ #include "vfd_task.h" #include "board_defs.h" #include "catch_errors.h" #include "packet_utils.h" #include "string.h" // memcpy #include "vfd_defs.h" VfdTask::VfdTask( // const char* name, UartTasks& uart, Writable& target, TaskUtilitiesArg& utilArg, UBaseType_t priority) : uart{ uart } , target{ target } , util{ utilArg } , task{ name, funcWrapper, this, priority } , bus{ uart, responseDelayMs, target, packet, util } {} void VfdTask::func() { // Assuming sequential address, including broadcast address (0) // Todo - more flexible address configuration const uint8_t numNodes = 3; // node 1, 2, and broadcast // const uint8_t numNodes = 6; // nodes 1-5, and broadcast uint16_t lastFrequency[numNodes]; for (int i = 0; i < numNodes; i++) { lastFrequency[i] = -1; // invalid, max of 4000 } uint16_t setFrequency[numNodes] = { 0 }; // Which address we're focusing on updating. // Address 0 is broadcast, which does not get any responses. uint8_t focus = 0; util.watchdogRegisterTask(); while (1) { util.watchdogKick(); // Collect all incoming host commands before deciding what modbus commands to send while (msgbuf.read(&packet, sizeof(packet), 0)) { switch (packet.id) { case PacketID::VfdSetFrequency: { uint8_t node = packet.body.vfdSetFrequency.node; uint16_t freq = packet.body.vfdSetFrequency.frequency; util.logln( // "%s got command to set vfd %u frequency to %u.%u Hz", pcTaskGetName(task.handle), node, freq / 10, freq % 10); if (node < numNodes) { setFrequency[node] = freq; } else { util.logln( // "%s got invalid address %u, exceeds %u", pcTaskGetName(task.handle), node, numNodes - 1); } break; } default: util.logln( // "%s doesn't know what to do with packet id: %s", pcTaskGetName(task.handle), packetIdToString(packet.id)); critical(); break; } } // For each address in round-robbin fashion, // create a modbus "Request" packet to send. // If there's a new frequency setpoint, send that, // otherwise request status. focus += 1; focus %= numNodes; if (setFrequency[focus] != lastFrequency[focus]) { // Write frequency value bus.outPkt->nodeAddress = focus; bus.outPkt->command = FunctionCode::WriteSingleRegister; bus.outPkt->writeSingleRegisterRequest.registerAddress = frequencyRegAddress; bus.outPkt->writeSingleRegisterRequest.data = setFrequency[focus]; } else { // Don't broadcast status request. Won't get a response. if (focus == 0) { continue; } // Read status registers bus.outPkt->nodeAddress = focus; bus.outPkt->command = FunctionCode::ReadMultipleRegisters; bus.outPkt->readMultipleRegistersRequest.startingAddress = statusRegAddress; bus.outPkt->readMultipleRegistersRequest.numRegisters = statusRegNum; } // Set origin for all outgoing reporting packets. // Note that this packet is reused by modbus driver. packet.origin = PacketOrigin::TargetToHost; uint32_t respLen = bus.sendRequest(); // Special handling for broadcast messages if (respLen == 1 && bus.outPkt->nodeAddress == 0) { // If frequency setpoint update if (bus.outPkt->command == FunctionCode::WriteSingleRegister && // __builtin_bswap16(bus.outPkt->writeSingleRegisterRequest.registerAddress) == frequencyRegAddress) { // Only update last frequency setpoint if write succeeded. // Otherwise, will attempt retransmission next lap. // For broadcast, failure could be due to a bad echo. lastFrequency[focus] = setFrequency[focus]; } else { error("Unexpected modbus broadcast"); } // Successful non-broadcast requests } else if (respLen) { switch (bus.inPkt->command) { case FunctionCode::ReadMultipleRegisters: { // The requested register is not returned in the response, // and the outgoing request packet inverted endianness, so // need to reverse that conversion. uint16_t regAddr = __builtin_bswap16(bus.outPkt->readMultipleRegistersRequest.startingAddress); switch (regAddr) { case statusRegAddress: // Response size is already verified by modbus driver. // Form packet for reporting setPacketIdAndLength(packet, PacketID::VfdStatus); packet.body.vfdStatus.nodeAddress = bus.inPkt->nodeAddress; memcpy(&packet.body.vfdStatus.payload, bus.inPkt->readMultipleRegistersResponse.payload, sizeof(VfdStatus::payload)); // Report result of modbus request util.write(target, &packet, packet.length); break; default: // util.logln("Unexpected multi-reg modbus read response at address 0x%x", regAddr); break; } break; } case FunctionCode::WriteSingleRegister: { uint16_t regAddr = bus.inPkt->writeSingleRegisterResponse.registerAddress; switch (regAddr) { case frequencyRegAddress: util.logln( // "node %u: wrote frequency %u, %u.%u Hz", bus.inPkt->nodeAddress, bus.inPkt->writeSingleRegisterResponse.data, bus.inPkt->writeSingleRegisterResponse.data / 10, bus.inPkt->writeSingleRegisterResponse.data % 10); // Only update last frequency setpoint if write succeeded. // Otherwise, will attempt retransmission next lap. lastFrequency[focus] = setFrequency[focus]; break; default: // util.logln("Unexpected single-reg modbus write response at address 0x%x", regAddr); break; } } case FunctionCode::WriteMultipleRegisters: // not expecting anything for this yet case FunctionCode::Exception: // error bit convenience default: // util.logln( // "node %u unexpected modbus response command 0x%x - possible exception", bus.outPkt->nodeAddress, bus.inPkt->command); VfdErrorDbgPinHigh(); VfdErrorDbgPinLow(); VfdErrorDbgPinHigh(); // Hold to allow capture by low sample rate scope osDelay(1); VfdErrorDbgPinLow(); break; } bus.shiftOutConsumedBytes(respLen); } else { util.logln("node %u: Unsuccessful modbus request", bus.outPkt->nodeAddress); VfdErrorDbgPinHigh(); // Hold to allow capture by low sample rate scope osDelay(1); VfdErrorDbgPinLow(); } } } size_t VfdTask::write(const void* buf, size_t len, TickType_t ticks) { return msgbuf.write(buf, len, ticks); }
32.330317
131
0.613436
milesfrain
dcdf739247cfd9069822d09dcb438ea035b20678
463
cpp
C++
service/src/exo/videorw.cpp
BOBBYWY/exodusdb
cfe8a3452480af90071dd10cefeed58299eed4e7
[ "MIT" ]
null
null
null
service/src/exo/videorw.cpp
BOBBYWY/exodusdb
cfe8a3452480af90071dd10cefeed58299eed4e7
[ "MIT" ]
null
null
null
service/src/exo/videorw.cpp
BOBBYWY/exodusdb
cfe8a3452480af90071dd10cefeed58299eed4e7
[ "MIT" ]
null
null
null
#include <exodus/library.h> libraryinit() function main(in x, in y, in x2, in y2, in readwrite, io buffer) { //TODO implement if screen handling required //VIDEO.RW(0,0,@CRTWIDE-1,@CRTHIGH-1,'R',startBUFFER) //eg to copy a whole screen sized 80x25, use 0,0,79,24 //R=Read, W=Write //evade warning "usused" false and x and y and x2 and y2 and readwrite; if (readwrite=="R") { buffer=""; } else if (readwrite=="W") { } return 0; } libraryexit()
18.52
66
0.660907
BOBBYWY
dce1a9d48c363461b86d90f7c8ebc32d37e1fe13
6,887
cpp
C++
editor/src/editor.cpp
gabyrobles93/worms-game-remake
b97781f39369f807ae8c8316f7f313353d7a2df7
[ "MIT" ]
2
2019-04-24T18:27:29.000Z
2020-04-06T17:15:34.000Z
editor/src/editor.cpp
gabyrobles93/tp-final-taller
b97781f39369f807ae8c8316f7f313353d7a2df7
[ "MIT" ]
null
null
null
editor/src/editor.cpp
gabyrobles93/tp-final-taller
b97781f39369f807ae8c8316f7f313353d7a2df7
[ "MIT" ]
null
null
null
#include <iostream> #include <string> #include <SDL2/SDL.h> #include <QApplication> #include <QMessageBox> #include <QDebug> #include "editor.h" #include "yaml.h" #include "map_game.h" #include "yaml.h" #include "inventory.h" #include "inventory_editor.h" #define EXIT_PADDING 5 #define EXIT_ICON_SIDE 20 #define SAVE_PADDING 10 #define SAVE_ICON_SIDE 60 Editor::Editor(YAML::Node map, std::string mn, std::string bgn, std::string bgp) : bg_name(bgn), bg_path(bgp), map_name(mn), mapNode(YAML::Clone(map)), staticNode(mapNode["static"]), mapGame(mapNode), editorWindow(staticNode, 0, 0, true, true), camera(editorWindow.getScreenWidth(), editorWindow.getScreenHeight(), editorWindow.getBgWidth(), editorWindow.getBgHeight()), renderer(editorWindow.getRenderer()), editorInventory(renderer, mapNode["static"]["teams_amount"].as<int>(), mapNode["static"]["worms_health"].as<int>()) { this->teamsAmount = mapNode["static"]["teams_amount"].as<int>(); this->wormsHealth = mapNode["static"]["worms_health"].as<int>(); this->editorInventory.toggleOpen(); this->mapGame.setRenderer(this->renderer); this->mapGame.initializeStates(); this->mapGame.createMapToSave(); this->exitTexture.loadFromFile(gPath.PATH_EXIT_ICON, this->renderer); this->exitTexture.setX(this->editorWindow.getScreenWidth() - EXIT_PADDING - EXIT_ICON_SIDE); this->exitTexture.setY(EXIT_PADDING); this->saveTexture.loadFromFile(gPath.PATH_SAVE_ICON, this->renderer); this->saveTexture.setX(this->editorWindow.getScreenWidth() - SAVE_PADDING - SAVE_ICON_SIDE); this->saveTexture.setY(EXIT_PADDING + EXIT_ICON_SIDE + SAVE_PADDING); this->unsaved_changes = false; this->notice.setScreenWidth(this->editorWindow.getScreenWidth()); this->notice.setScreenHeight(this->editorWindow.getScreenHeight()); } int Editor::start(void) { bool quit = false; SDL_Event e; while (!quit) { int camX = camera.getX(), camY = camera.getY(); while (SDL_PollEvent(&e) != 0) { if (e.type == SDL_QUIT) { quit = true; editorWindow.hide(); validMap = mapGame.hasWorms(); if (!validMap) { QMessageBox msgBox; msgBox.setWindowTitle("Mapa inválido."); msgBox.setText("El mapa debe tener al menos un worm de cada team." "¿Desea continuar editando el mapa?"); msgBox.setStandardButtons(QMessageBox::Yes); msgBox.addButton(QMessageBox::No); msgBox.setDefaultButton(QMessageBox::Yes); if(msgBox.exec() == QMessageBox::Yes) { editorWindow.show(); quit = false; } } } if (e.type == SDL_KEYDOWN) { if (e.key.keysym.sym == SDLK_z && (e.key.keysym.mod & KMOD_CTRL)) { mapGame.setPreviousState(editorInventory); } if (e.key.keysym.sym == SDLK_y && (e.key.keysym.mod & KMOD_CTRL)) { mapGame.setNextState(editorInventory); } } if (e.type == SDL_MOUSEBUTTONDOWN) { int mouseX, mouseY; SDL_GetMouseState(&mouseX, &mouseY); if (e.button.button == SDL_BUTTON_LEFT) { if ( mouseX > this->saveTexture.getX() && mouseX < this->saveTexture.getX() + SAVE_ICON_SIDE && mouseY > this->saveTexture.getY() && mouseY < this->saveTexture.getY() + SAVE_ICON_SIDE ) { if (!this->unsaved_changes) { std::cout << "No hay cambios sin guardar." << std::endl; this->notice.showFlashNotice(this->renderer, "No hay cambios sin guardar."); continue; } validMap = mapGame.hasWorms(); if (!validMap) { std::cout << "El mapa debe tener al menos un worm de cada team." << std::endl; this->notice.showFlashError(this->renderer, "El mapa debe tener al menos un worm de cada team."); continue; } mapGame.saveAs(this->map_name, this->bg_name, this->bg_path); this->unsaved_changes = false; std::cout << "Mapa guardado." << std::endl; this->notice.showFlashNotice(this->renderer, "Mapa guardado en /usr/etc/worms/maps/" + this->map_name); } else if ( mouseX > this->exitTexture.getX() && mouseX < this->exitTexture.getX() + EXIT_ICON_SIDE && mouseY > this->exitTexture.getY() && mouseY < this->exitTexture.getY() + EXIT_ICON_SIDE) { quit = true; editorWindow.hide(); validMap = mapGame.hasWorms(); if (!validMap) { QMessageBox msgBox; msgBox.setWindowTitle("Mapa inválido."); msgBox.setText("El mapa debe tener al menos un worm de cada team." "¿Desea continuar editando el mapa?"); msgBox.setStandardButtons(QMessageBox::Yes); msgBox.addButton(QMessageBox::No); msgBox.setDefaultButton(QMessageBox::Yes); if(msgBox.exec() == QMessageBox::Yes) { editorWindow.show(); quit = false; continue; } } if (this->unsaved_changes) { QMessageBox msgBox; msgBox.setWindowTitle("Guardar antes de salir."); msgBox.setText("Hay cambios sin guardar. Desea guardar el mapa antes de salir?"); msgBox.setStandardButtons(QMessageBox::Yes); msgBox.addButton(QMessageBox::No); msgBox.setDefaultButton(QMessageBox::Yes); if(msgBox.exec() == QMessageBox::Yes) { mapGame.saveAs(this->map_name, this->bg_name, this->bg_path); this->unsaved_changes = false; continue; } } } else { editorInventory.handleEvent(renderer, e, mapGame, camX, camY); this->unsaved_changes = true; } } } else { editorInventory.handleEvent(renderer, e, mapGame, camX, camY); } } SDL_SetRenderDrawColor(renderer, 0x00, 0x00, 0x00, 0x00); SDL_RenderClear(renderer); camera.updateCameraPosition(); editorWindow.render(camera); mapGame.render(renderer, camX, camY); editorInventory.renderSelectedInMouse(renderer); editorWindow.renderWater(camera); editorInventory.render(renderer); notice.render(renderer); this->saveTexture.render(this->renderer, this->saveTexture.getX(), this->saveTexture.getY(), SAVE_ICON_SIDE, SAVE_ICON_SIDE); this->exitTexture.render(this->renderer, this->exitTexture.getX(), this->exitTexture.getY(), EXIT_ICON_SIDE, EXIT_ICON_SIDE); SDL_RenderPresent(renderer); SDL_Delay(50); // Para no usar al mango el CPU } if (validMap && this->unsaved_changes) { QMessageBox msgBox; msgBox.setWindowTitle("Fin de edición"); msgBox.setText("¿Desea guardar el mapa?"); msgBox.setStandardButtons(QMessageBox::Yes); msgBox.addButton(QMessageBox::No); msgBox.setDefaultButton(QMessageBox::Yes); if(msgBox.exec() == QMessageBox::Yes) { mapGame.saveAs(this->map_name, this->bg_name, this->bg_path); this->unsaved_changes = false; return 0; } } return -1; }
34.782828
127
0.652098
gabyrobles93
dce1aa108a1408397a6280c0e66fdf626d083d24
2,589
cc
C++
src/core/wakeup_handler.cc
nugulinux/nugu-linux
c166d61b2037247d4574b7f791c31ba79ceb575e
[ "Apache-2.0" ]
null
null
null
src/core/wakeup_handler.cc
nugulinux/nugu-linux
c166d61b2037247d4574b7f791c31ba79ceb575e
[ "Apache-2.0" ]
null
null
null
src/core/wakeup_handler.cc
nugulinux/nugu-linux
c166d61b2037247d4574b7f791c31ba79ceb575e
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) 2019 SK Telecom Co., Ltd. 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 "base/nugu_log.h" #include "capability_manager.hh" #include "wakeup_handler.hh" namespace NuguCore { WakeupHandler::WakeupHandler(const std::string& model_path) : wakeup_detector(std::unique_ptr<WakeupDetector>(new WakeupDetector(WakeupDetector::Attribute { "", "", "", model_path }))) , uniq(0) { wakeup_detector->setListener(this); } WakeupHandler::~WakeupHandler() { } void WakeupHandler::setListener(IWakeupListener* listener) { this->listener = listener; } bool WakeupHandler::startWakeup() { std::string id = "id#" + std::to_string(uniq++); setWakeupId(id); return wakeup_detector->startWakeup(id); } void WakeupHandler::stopWakeup() { wakeup_detector->stopWakeup(); } void WakeupHandler::onWakeupState(WakeupState state, const std::string& id, float noise, float speech) { if (request_wakeup_id != id) { nugu_warn("[id: %s] ignore [id: %s]'s state %d", request_wakeup_id.c_str(), id.c_str(), state); return; } switch (state) { case WakeupState::FAIL: nugu_dbg("[id: %s] WakeupState::FAIL", id.c_str()); if (listener) listener->onWakeupState(WakeupDetectState::WAKEUP_FAIL, noise, speech); break; case WakeupState::DETECTING: nugu_dbg("[id: %s] WakeupState::DETECTING", id.c_str()); if (listener) listener->onWakeupState(WakeupDetectState::WAKEUP_DETECTING, noise, speech); break; case WakeupState::DETECTED: nugu_dbg("[id: %s] WakeupState::DETECTED", id.c_str()); if (listener) listener->onWakeupState(WakeupDetectState::WAKEUP_DETECTED, noise, speech); break; case WakeupState::DONE: nugu_dbg("[id: %s] WakeupState::DONE", id.c_str()); break; } } void WakeupHandler::setWakeupId(const std::string& id) { request_wakeup_id = id; nugu_dbg("startListening with new id(%s)", request_wakeup_id.c_str()); } } // NuguCore
28.141304
128
0.676323
nugulinux
dce1bcbcedbc4a903fa76a3767a126f677d91a66
197
cpp
C++
Basics/IfElse/decisionMaking.cpp
dibyanshushekhardey/C--Program-Codes
d84452c95dcf85c2e4e97fa644bbd4cabde7f5b4
[ "MIT" ]
null
null
null
Basics/IfElse/decisionMaking.cpp
dibyanshushekhardey/C--Program-Codes
d84452c95dcf85c2e4e97fa644bbd4cabde7f5b4
[ "MIT" ]
null
null
null
Basics/IfElse/decisionMaking.cpp
dibyanshushekhardey/C--Program-Codes
d84452c95dcf85c2e4e97fa644bbd4cabde7f5b4
[ "MIT" ]
null
null
null
// C++ program to illustrate If statement #include<iostream> using namespace std; int main() { int i = 10; if (i > 15) { cout<<"10 is less than 15"; } cout<<"I am Not in if"; }
12.3125
41
0.573604
dibyanshushekhardey
dce1dfd76f66d0749bdacb0cdf77658fefd4cc9d
3,652
cpp
C++
graph-source-code/182-A/1625475.cpp
AmrARaouf/algorithm-detection
59f3028d2298804870b32729415d71eec6116557
[ "MIT" ]
null
null
null
graph-source-code/182-A/1625475.cpp
AmrARaouf/algorithm-detection
59f3028d2298804870b32729415d71eec6116557
[ "MIT" ]
null
null
null
graph-source-code/182-A/1625475.cpp
AmrARaouf/algorithm-detection
59f3028d2298804870b32729415d71eec6116557
[ "MIT" ]
null
null
null
//Language: GNU C++ //HACK ME, PLEASE! ^_^ #include <cstdio> #include <iostream> #include <algorithm> #include <cstring> #include <string> #include <vector> #include <set> #include <utility> #include <math.h> #include <cstdlib> #include <memory.h> #include <queue> #define pb push_back #define i64 long long #define mp make_pair #define pii pair <int,int> #define vi vector <int> #define vii vector <pii> #define f first #define s second #define foran(i,a,b) for (int i=a;i<(int)b;i++) #define forn(i,n) for (int i=0;i<(int)n;i++) #define ford(i,n) for (int i=(int)n-1;i>=0;i--) const double eps = 1e-9; const int int_inf = 2000000000; const i64 i64_inf = 1000000000000000000LL; const double pi = acos(-1.0); using namespace std; struct p { int x,y; p() {}; }; struct tr { p a,b; tr(int x1=0,int y1=0,int x2=0,int y2=0) { a.x=x1; a.y=y1; b.x=x2; b.y=y2; }; }; int dest(tr F, tr S) { if (F.a.x == F.b.x && S.a.x == S.b.x) { int y = F.a.y; int yy = F.b.y; int y1 = S.a.y; int yy1 = S.b.y; if ( min(y,yy) > max(y1,yy1) || min(y1,yy1) > max(y,yy)) { if (y1 < yy1) swap(y1,yy1); if (y < yy) swap(y,yy); int dx = abs(F.a.x - S.b.x); int dy = min(abs(yy1 - y),abs(y1-yy)); return dx * dx + dy * dy; } else return (F.a.x - S.a.x) * (F.a.x - S.a.x); } else if (F.a.y == F.b.y && S.a.y == S.b.y) { int x = F.a.x; int xx = F.b.x; int x1 = S.a.x; int xx1 = S.b.x; if ( min(x,xx) > max(x1,xx1) || min(x1,xx1) > max(x,xx)) { if (x1 < xx1) swap(x1,xx1); if (x < xx) swap(x,xx); int dy = abs(F.a.y - S.b.y); int dx = min(abs(xx1 - x), abs(x1-xx)); return dx * dx + dy * dy; } else return (F.a.y - S.a.y) * (F.a.y - S.a.y); } else { if (F.a.y == F.b.y) swap(F,S); int y = F.b.y; int y1 = F.a.y; int x = S.a.x; int x1 = S.b.x; if (y1 < y) swap(y,y1); if (x1 < x) swap(x,x1); if (S.a.y <= y1 && S.a.y >= y) return min( (x - F.b.x)*(x - F.b.x), (x1 - F.b.x)*(x1 - F.b.x) ); if (F.a.x >= x && F.a.x <= x1) return min( (y1 - S.a.y)*(y1 - S.a.y), (y - S.a.y) * (y - S.a.y) ); if (abs(x - F.a.x) > abs(x1 - F.a.x)) swap(x,x1); if (abs(y - S.a.y) < abs(y1 - S.a.y)) swap(y,y1); int dx = F.a.x - x; int dy = y1 - S.a.y; return dx * dx + dy * dy; } } int n; int a,aa,b; p A; p B; tr c[1100]; int d[1050]; int main() { cin >> a >> b; aa = a; a = a * a; cin >> A.x >> A.y >> B.x >> B.y; cin >> n; forn(i,n) scanf("%d%d%d%d",&c[i].a.x,&c[i].a.y,&c[i].b.x,&c[i].b.y); if ( (A.x - B.x)*(A.x - B.x) + (A.y - B.y)*(A.y - B.y) <= a) { int de = (A.x - B.x)*(A.x - B.x) + (A.y - B.y)*(A.y - B.y); printf("%.8lf",(double)sqrt((double)de)); return 0; } forn(i,n) if (dest(tr(A.x,A.y,A.x,A.y),c[i]) <= a) d[i] = 1; else d[i] = int_inf; queue <int> q; forn(i,n) if (d[i] < int_inf) q.push(i); double res = int_inf; while (!q.empty()) { int j = q.front(); q.pop(); if (dest(tr(B.x,B.y,B.x,B.y),c[j]) <= a) res = min(res,(double)d[j]*(aa+b) + (double)sqrt((double)dest(tr(B.x,B.y,B.x,B.y),c[j]))); forn(i,n) if (dest(c[i],c[j]) <= a && i != j && d[i] > d[j] + 1) q.push(i), d[i] = d[j] + 1; } if (res == int_inf) { cout << "-1"; return 0; } printf("%.8lf",(double)res); return 0; }
26.463768
107
0.441128
AmrARaouf
dce21c1663f64fff45a035362b019a7ee5de494a
1,089
cpp
C++
Challenge-2020-05/construct_BST_from_preorder_traversal.cpp
qiufengyu/LetsCode
196fae0bf5c78ee20d05798a9439596e702fdb24
[ "MIT" ]
null
null
null
Challenge-2020-05/construct_BST_from_preorder_traversal.cpp
qiufengyu/LetsCode
196fae0bf5c78ee20d05798a9439596e702fdb24
[ "MIT" ]
null
null
null
Challenge-2020-05/construct_BST_from_preorder_traversal.cpp
qiufengyu/LetsCode
196fae0bf5c78ee20d05798a9439596e702fdb24
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> #include "binary_tree.h" using namespace std; class Solution { public: TreeNode* bstFromPreorder(vector<int>& preorder) { if (preorder.size() == 0) return nullptr; TreeNode* root = new TreeNode {preorder[0]}; for (int i = 1; i < preorder.size(); i++) { TreeNode *parent = nullptr; TreeNode *child = root; // TreeNode *child = root; int val = preorder[i]; while (child) { parent = child; if (child->val < val) { child = child->right; } else { child = child->left; } } if (parent->val < val) { parent->right = new TreeNode {val}; } else { parent->left = new TreeNode {val}; } } return root; } }; int main() { vector<int> v {8, 5, 1, 7, 10, 12}; TreeNode* root = Solution().bstFromPreorder(v); prettyPrintTree(root); }
27.225
59
0.458219
qiufengyu
dce3f023c98881b19d854ae1beaebfa69001d3cb
17,829
cpp
C++
src/cpp/rtps/builtin/data/ReaderProxyData.cpp
ruffsl/Fast-RTPS
ae7cf4e961801956e59cba37a5c17cdc2258ec6c
[ "Apache-2.0" ]
1
2018-03-20T21:31:38.000Z
2018-03-20T21:31:38.000Z
src/cpp/rtps/builtin/data/ReaderProxyData.cpp
ruffsl/Fast-RTPS
ae7cf4e961801956e59cba37a5c17cdc2258ec6c
[ "Apache-2.0" ]
null
null
null
src/cpp/rtps/builtin/data/ReaderProxyData.cpp
ruffsl/Fast-RTPS
ae7cf4e961801956e59cba37a5c17cdc2258ec6c
[ "Apache-2.0" ]
1
2018-09-19T10:12:29.000Z
2018-09-19T10:12:29.000Z
// Copyright 2016 Proyectos y Sistemas de Mantenimiento SL (eProsima). // // 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. /** * @file ReaderProxyData.cpp * */ #include <fastrtps/rtps/builtin/data/ReaderProxyData.h> #include <fastrtps/rtps/common/CDRMessage_t.h> #include <fastrtps/log/Log.h> namespace eprosima { namespace fastrtps{ namespace rtps { ReaderProxyData::ReaderProxyData() : m_expectsInlineQos(false), m_userDefinedId(0), m_isAlive(true), m_topicKind(NO_KEY) { } ReaderProxyData::~ReaderProxyData() { logInfo(RTPS_PROXY_DATA,"ReaderProxyData destructor: "<< this->m_guid;); } ReaderProxyData::ReaderProxyData(const ReaderProxyData& readerInfo) : m_expectsInlineQos(readerInfo.m_expectsInlineQos), m_guid(readerInfo.m_guid), m_unicastLocatorList(readerInfo.m_unicastLocatorList), m_multicastLocatorList(readerInfo.m_multicastLocatorList), m_key(readerInfo.m_key), m_RTPSParticipantKey(readerInfo.m_RTPSParticipantKey), m_typeName(readerInfo.m_typeName), m_topicName(readerInfo.m_topicName), m_userDefinedId(readerInfo.m_userDefinedId), m_isAlive(readerInfo.m_isAlive), m_topicKind(readerInfo.m_topicKind) { m_qos.setQos(readerInfo.m_qos, true); } ReaderProxyData& ReaderProxyData::operator=(const ReaderProxyData& readerInfo) { m_expectsInlineQos = readerInfo.m_expectsInlineQos; m_guid = readerInfo.m_guid; m_unicastLocatorList = readerInfo.m_unicastLocatorList; m_multicastLocatorList = readerInfo.m_multicastLocatorList; m_key = readerInfo.m_key; m_RTPSParticipantKey = readerInfo.m_RTPSParticipantKey; m_typeName = readerInfo.m_typeName; m_topicName = readerInfo.m_topicName; m_userDefinedId = readerInfo.m_userDefinedId; m_isAlive = readerInfo.m_isAlive; m_expectsInlineQos = readerInfo.m_expectsInlineQos; m_topicKind = readerInfo.m_topicKind; m_qos.setQos(readerInfo.m_qos, true); return *this; } ParameterList_t ReaderProxyData::toParameterList() { ParameterList_t parameter_list; for(LocatorListIterator lit = m_unicastLocatorList.begin(); lit!=m_unicastLocatorList.end();++lit) { ParameterLocator_t* p = new ParameterLocator_t(PID_UNICAST_LOCATOR,PARAMETER_LOCATOR_LENGTH,*lit); parameter_list.m_parameters.push_back((Parameter_t*)p); } for(LocatorListIterator lit = m_multicastLocatorList.begin(); lit!=m_multicastLocatorList.end();++lit) { ParameterLocator_t* p = new ParameterLocator_t(PID_MULTICAST_LOCATOR,PARAMETER_LOCATOR_LENGTH,*lit); parameter_list.m_parameters.push_back((Parameter_t*)p); } { ParameterBool_t * p = new ParameterBool_t(PID_EXPECTS_INLINE_QOS,PARAMETER_BOOL_LENGTH,m_expectsInlineQos); parameter_list.m_parameters.push_back((Parameter_t*)p); } { ParameterGuid_t* p = new ParameterGuid_t(PID_PARTICIPANT_GUID,PARAMETER_GUID_LENGTH,m_RTPSParticipantKey); parameter_list.m_parameters.push_back((Parameter_t*)p); } { ParameterString_t * p = new ParameterString_t(PID_TOPIC_NAME,0,m_topicName); parameter_list.m_parameters.push_back((Parameter_t*)p); } { ParameterString_t * p = new ParameterString_t(PID_TYPE_NAME,0,m_typeName); parameter_list.m_parameters.push_back((Parameter_t*)p); } { ParameterKey_t * p = new ParameterKey_t(PID_KEY_HASH,16,m_key); parameter_list.m_parameters.push_back((Parameter_t*)p); } { ParameterGuid_t * p = new ParameterGuid_t(PID_ENDPOINT_GUID,16,m_guid); parameter_list.m_parameters.push_back((Parameter_t*)p); } { ParameterProtocolVersion_t* p = new ParameterProtocolVersion_t(PID_PROTOCOL_VERSION,4); parameter_list.m_parameters.push_back((Parameter_t*)p); } { ParameterVendorId_t*p = new ParameterVendorId_t(PID_VENDORID,4); parameter_list.m_parameters.push_back((Parameter_t*)p); } if(m_qos.m_durability.sendAlways() || m_qos.m_durability.hasChanged) { DurabilityQosPolicy*p = new DurabilityQosPolicy(); *p = m_qos.m_durability; parameter_list.m_parameters.push_back((Parameter_t*)p); } if(m_qos.m_durabilityService.sendAlways() || m_qos.m_durabilityService.hasChanged) { DurabilityServiceQosPolicy*p = new DurabilityServiceQosPolicy(); *p = m_qos.m_durabilityService; parameter_list.m_parameters.push_back((Parameter_t*)p); } if(m_qos.m_deadline.sendAlways() || m_qos.m_deadline.hasChanged) { DeadlineQosPolicy*p = new DeadlineQosPolicy(); *p = m_qos.m_deadline; parameter_list.m_parameters.push_back((Parameter_t*)p); } if(m_qos.m_latencyBudget.sendAlways() || m_qos.m_latencyBudget.hasChanged) { LatencyBudgetQosPolicy*p = new LatencyBudgetQosPolicy(); *p = m_qos.m_latencyBudget; parameter_list.m_parameters.push_back((Parameter_t*)p); } if(m_qos.m_liveliness.sendAlways() || m_qos.m_liveliness.hasChanged) { LivelinessQosPolicy*p = new LivelinessQosPolicy(); *p = m_qos.m_liveliness; parameter_list.m_parameters.push_back((Parameter_t*)p); } if(m_qos.m_reliability.sendAlways() || m_qos.m_reliability.hasChanged) { ReliabilityQosPolicy*p = new ReliabilityQosPolicy(); *p = m_qos.m_reliability; parameter_list.m_parameters.push_back((Parameter_t*)p); } if(m_qos.m_lifespan.sendAlways() || m_qos.m_lifespan.hasChanged) { LifespanQosPolicy*p = new LifespanQosPolicy(); *p = m_qos.m_lifespan; parameter_list.m_parameters.push_back((Parameter_t*)p); } if(m_qos.m_userData.sendAlways() || m_qos.m_userData.hasChanged) { UserDataQosPolicy*p = new UserDataQosPolicy(); *p = m_qos.m_userData; parameter_list.m_parameters.push_back((Parameter_t*)p); } if(m_qos.m_timeBasedFilter.sendAlways() || m_qos.m_timeBasedFilter.hasChanged) { TimeBasedFilterQosPolicy*p = new TimeBasedFilterQosPolicy(); *p = m_qos.m_timeBasedFilter; parameter_list.m_parameters.push_back((Parameter_t*)p); } if(m_qos.m_ownership.sendAlways() || m_qos.m_ownership.hasChanged) { OwnershipQosPolicy*p = new OwnershipQosPolicy(); *p = m_qos.m_ownership; parameter_list.m_parameters.push_back((Parameter_t*)p); } if(m_qos.m_destinationOrder.sendAlways() || m_qos.m_destinationOrder.hasChanged) { DestinationOrderQosPolicy*p = new DestinationOrderQosPolicy(); *p = m_qos.m_destinationOrder; parameter_list.m_parameters.push_back((Parameter_t*)p); } if(m_qos.m_presentation.sendAlways() || m_qos.m_presentation.hasChanged) { PresentationQosPolicy*p = new PresentationQosPolicy(); *p = m_qos.m_presentation; parameter_list.m_parameters.push_back((Parameter_t*)p); } if(m_qos.m_partition.sendAlways() || m_qos.m_partition.hasChanged) { PartitionQosPolicy*p = new PartitionQosPolicy(); *p = m_qos.m_partition; parameter_list.m_parameters.push_back((Parameter_t*)p); } if(m_qos.m_topicData.sendAlways() || m_qos.m_topicData.hasChanged) { TopicDataQosPolicy*p = new TopicDataQosPolicy(); *p = m_qos.m_topicData; parameter_list.m_parameters.push_back((Parameter_t*)p); } if(m_qos.m_groupData.sendAlways() || m_qos.m_groupData.hasChanged) { GroupDataQosPolicy*p = new GroupDataQosPolicy(); *p = m_qos.m_groupData; parameter_list.m_parameters.push_back((Parameter_t*)p); } if(m_qos.m_timeBasedFilter.sendAlways() || m_qos.m_timeBasedFilter.hasChanged) { TimeBasedFilterQosPolicy*p = new TimeBasedFilterQosPolicy(); *p = m_qos.m_timeBasedFilter; parameter_list.m_parameters.push_back((Parameter_t*)p); } logInfo(RTPS_PROXY_DATA,"DiscoveredReaderData converted to ParameterList with " << parameter_list.m_parameters.size()<< " parameters"); return parameter_list; } bool ReaderProxyData::readFromCDRMessage(CDRMessage_t* msg) { ParameterList_t parameter_list; if(ParameterList::readParameterListfromCDRMsg(msg, &parameter_list, NULL, true)>0) { for(std::vector<Parameter_t*>::iterator it = parameter_list.m_parameters.begin(); it!=parameter_list.m_parameters.end();++it) { switch((*it)->Pid) { case PID_DURABILITY: { DurabilityQosPolicy * p = (DurabilityQosPolicy*)(*it); m_qos.m_durability = *p; break; } case PID_DURABILITY_SERVICE: { DurabilityServiceQosPolicy * p = (DurabilityServiceQosPolicy*)(*it); m_qos.m_durabilityService = *p; break; } case PID_DEADLINE: { DeadlineQosPolicy * p = (DeadlineQosPolicy*)(*it); m_qos.m_deadline = *p; break; } case PID_LATENCY_BUDGET: { LatencyBudgetQosPolicy * p = (LatencyBudgetQosPolicy*)(*it); m_qos.m_latencyBudget = *p; break; } case PID_LIVELINESS: { LivelinessQosPolicy * p = (LivelinessQosPolicy*)(*it); m_qos.m_liveliness = *p; break; } case PID_RELIABILITY: { ReliabilityQosPolicy * p = (ReliabilityQosPolicy*)(*it); m_qos.m_reliability = *p; break; } case PID_LIFESPAN: { LifespanQosPolicy * p = (LifespanQosPolicy*)(*it); m_qos.m_lifespan = *p; break; } case PID_USER_DATA: { UserDataQosPolicy * p = (UserDataQosPolicy*)(*it); m_qos.m_userData = *p; break; } case PID_TIME_BASED_FILTER: { TimeBasedFilterQosPolicy * p = (TimeBasedFilterQosPolicy*)(*it); m_qos.m_timeBasedFilter = *p; break; } case PID_OWNERSHIP: { OwnershipQosPolicy * p = (OwnershipQosPolicy*)(*it); m_qos.m_ownership = *p; break; } case PID_DESTINATION_ORDER: { DestinationOrderQosPolicy * p = (DestinationOrderQosPolicy*)(*it); m_qos.m_destinationOrder = *p; break; } case PID_PRESENTATION: { PresentationQosPolicy * p = (PresentationQosPolicy*)(*it); m_qos.m_presentation = *p; break; } case PID_PARTITION: { PartitionQosPolicy * p = (PartitionQosPolicy*)(*it); m_qos.m_partition = *p; break; } case PID_TOPIC_DATA: { TopicDataQosPolicy * p = (TopicDataQosPolicy*)(*it); m_qos.m_topicData = *p; break; } case PID_GROUP_DATA: { GroupDataQosPolicy * p = (GroupDataQosPolicy*)(*it); m_qos.m_groupData = *p; break; } case PID_TOPIC_NAME: { ParameterString_t*p = (ParameterString_t*)(*it); m_topicName = std::string(p->getName()); break; } case PID_TYPE_NAME: { ParameterString_t*p = (ParameterString_t*)(*it); m_typeName = std::string(p->getName()); break; } case PID_PARTICIPANT_GUID: { ParameterGuid_t * p = (ParameterGuid_t*)(*it); for(uint8_t i = 0; i < 16; ++i) { if(i < 12) m_RTPSParticipantKey.value[i] = p->guid.guidPrefix.value[i]; else m_RTPSParticipantKey.value[i] = p->guid.entityId.value[i - 12]; } break; } case PID_ENDPOINT_GUID: { ParameterGuid_t * p = (ParameterGuid_t*)(*it); m_guid = p->guid; for(uint8_t i=0;i<16;++i) { if(i<12) m_key.value[i] = p->guid.guidPrefix.value[i]; else m_key.value[i] = p->guid.entityId.value[i - 12]; } break; } case PID_UNICAST_LOCATOR: { ParameterLocator_t* p = (ParameterLocator_t*)(*it); m_unicastLocatorList.push_back(p->locator); break; } case PID_MULTICAST_LOCATOR: { ParameterLocator_t* p = (ParameterLocator_t*)(*it); m_multicastLocatorList.push_back(p->locator); break; } case PID_EXPECTS_INLINE_QOS: { ParameterBool_t*p =(ParameterBool_t*)(*it); m_expectsInlineQos = p->value; break; } case PID_KEY_HASH: { ParameterKey_t*p=(ParameterKey_t*)(*it); m_key = p->key; iHandle2GUID(m_guid,m_key); break; } default: { //logInfo(RTPS_PROXY_DATA,"Parameter with ID: " <<(uint16_t)(*it)->Pid << " NOT CONSIDERED"); break; } } } if(m_guid.entityId.value[3] == 0x04) m_topicKind = NO_KEY; else if(m_guid.entityId.value[3] == 0x07) m_topicKind = WITH_KEY; return true; } return false; } void ReaderProxyData::clear() { m_expectsInlineQos = false; m_guid = c_Guid_Unknown; m_unicastLocatorList.clear(); m_multicastLocatorList.clear(); m_key = InstanceHandle_t(); m_RTPSParticipantKey = InstanceHandle_t(); m_typeName = ""; m_topicName = ""; m_userDefinedId = 0; m_qos = ReaderQos(); m_isAlive = true; m_topicKind = NO_KEY; } void ReaderProxyData::update(ReaderProxyData* rdata) { m_unicastLocatorList = rdata->m_unicastLocatorList; m_multicastLocatorList = rdata->m_multicastLocatorList; m_qos.setQos(rdata->m_qos,false); m_isAlive = rdata->m_isAlive; m_expectsInlineQos = rdata->m_expectsInlineQos; } void ReaderProxyData::copy(ReaderProxyData* rdata) { m_guid = rdata->m_guid; m_unicastLocatorList = rdata->m_unicastLocatorList; m_multicastLocatorList = rdata->m_multicastLocatorList; m_key = rdata->m_key; m_RTPSParticipantKey = rdata->m_RTPSParticipantKey; m_typeName = rdata->m_typeName; m_topicName = rdata->m_topicName; m_userDefinedId = rdata->m_userDefinedId; m_qos = rdata->m_qos; //cout << "COPYING DATA: expects inlineQOS : " << rdata->m_expectsInlineQos << endl; m_expectsInlineQos = rdata->m_expectsInlineQos; m_isAlive = rdata->m_isAlive; m_topicKind = rdata->m_topicKind; } RemoteReaderAttributes ReaderProxyData::toRemoteReaderAttributes() const { RemoteReaderAttributes remoteAtt; remoteAtt.guid = m_guid; remoteAtt.expectsInlineQos = this->m_expectsInlineQos; remoteAtt.endpoint.durabilityKind = m_qos.m_durability.durabilityKind(); remoteAtt.endpoint.endpointKind = READER; remoteAtt.endpoint.topicKind = m_topicKind; remoteAtt.endpoint.reliabilityKind = m_qos.m_reliability.kind == RELIABLE_RELIABILITY_QOS ? RELIABLE : BEST_EFFORT; remoteAtt.endpoint.unicastLocatorList = this->m_unicastLocatorList; remoteAtt.endpoint.multicastLocatorList = this->m_multicastLocatorList; return remoteAtt; } } } /* namespace rtps */ } /* namespace eprosima */
37.613924
139
0.577991
ruffsl
dce4aad7a9eb59ed664ded57f1c97bd02678062b
10,180
cpp
C++
server/lsp/p4unit.cpp
emacsmirror/lsp-p4
669460d93b87fb876df11b2b68229677e7ad1a26
[ "MIT" ]
15
2018-04-08T06:45:56.000Z
2022-01-13T12:47:19.000Z
server/lsp/p4unit.cpp
emacsmirror/lsp-p4
669460d93b87fb876df11b2b68229677e7ad1a26
[ "MIT" ]
12
2018-12-30T11:45:38.000Z
2021-12-20T10:24:19.000Z
server/lsp/p4unit.cpp
emacsmirror/lsp-p4
669460d93b87fb876df11b2b68229677e7ad1a26
[ "MIT" ]
4
2018-04-01T18:45:27.000Z
2020-11-06T23:28:58.000Z
#include "p4unit.h" #include <boost/log/attributes/constant.hpp> #include <boost/log/sinks/syslog_backend.hpp> #include <boost/tokenizer.hpp> #include <fstream> #include <sstream> #include "../p4l/lexer.h" namespace { boost::log::sources::severity_logger<int> _logger(boost::log::keywords::severity = boost::log::sinks::syslog::debug); std::string::size_type get_position_index(const std::string& content, const Position& position) { const std::string newline(1, '\n'); std::string::size_type index = 0; for (auto it = 0U; it != position._line; ++it) { auto next_index = content.find_first_of(newline, index); if (next_index == std::string::npos) { BOOST_LOG_SEV(_logger, boost::log::sinks::syslog::error) << "has " << it + 1 << " lines, but changes requested on line " << position._line; return std::string::npos; } index = next_index + 1; } auto line_end_index = content.find_first_of(newline, index); if (line_end_index == std::string::npos) { line_end_index = content.size(); } if (index + position._character < line_end_index) { return index + position._character; } BOOST_LOG_SEV(_logger, boost::log::sinks::syslog::error) << "line " << position._line << " is shorter than " << position._character << " characters"; return std::string::npos; } } // namespace #if 0 bool Symbol_collector::preorder(const IR::Node* node) { if (!node->is<Util::IHasSourceInfo>()) { return false; } if (auto ctxt = getContext()) { Range range; const char* file = ""; if (auto info = node->getSourceInfo()) { range.set(info); file = info.getSourceFile().c_str(); } auto unit = _temp_path == file ? _unit_path.c_str() : file; Location location{unit, range}; BOOST_LOG(_logger) << ctxt->depth << " " << node->node_type_name() << " " << node->toString() << " " << location; // definitions if (node->is<IR::Type_Header>() || node->is<IR::Type_HeaderUnion>() || node->is<IR::Type_Struct>() || node->is<IR::Type_Extern>() || node->is<IR::Type_Enum>()) { std::ostringstream definition; definition << node; auto name = node->to<IR::IDeclaration>()->getName().toString().c_str(); _definitions.emplace(name, definition.str()); BOOST_LOG(_logger) << "Header or Struct: \"" << name << "\"\n" << definition.str(); } else if (node->is<IR::Type_Typedef>()) { auto name = node->to<IR::IDeclaration>()->getName().toString().c_str(); std::ostringstream definition; definition << "typedef " << node->to<IR::Type_Typedef>()->type << " " << name << ";"; _definitions.emplace(name, definition.str()); BOOST_LOG(_logger) << "Typedef:\"" << name << "\"\n" << definition.str(); } // highlights if (_unit_path == unit) { if (node->is<IR::Parameter>() || node->is<IR::PathExpression>()) { auto name = node->toString().c_str(); auto it = _highlights.find(name); if (it == _highlights.end()) { it = _highlights.emplace(std::piecewise_construct, std::forward_as_tuple(name), std::forward_as_tuple()).first; } it->second.emplace_back(range, DOCUMENT_HIGHLIGHT_KIND::Text); _locations[unit].emplace(std::make_pair(range, name)); } } // locations of types, but need locations for all other interesting items as well if (node->is<IR::Type_Name>()) { _locations[unit].emplace(std::make_pair(range, node->toString().c_str())); } else if (ctxt->depth == _max_depth && node->is<IR::IDeclaration>() && !node->is<IR::Type_Control>() && !node->is<IR::Type_Parser>()) { boost::optional<std::string> container; if (!_container.empty()) { container.emplace(_container.back()); } auto name = node->to<IR::IDeclaration>()->getName().toString().c_str(); _indexes[name] = _symbols.size(); _symbols.emplace_back(name, get_symbol_kind(node), location, container); if (node->is<IR::Type_Header>() || node->is<IR::Type_Struct>() || node->is<IR::P4Control>() || node->is<IR::P4Parser>()) { _container.push_back(name); ++_max_depth; } } } return true; } void Symbol_collector::postorder(const IR::Node* node) { if (auto ctxt = getContext()) { BOOST_LOG(_logger) << "exit from " << ctxt->depth << " " << node->node_type_name(); if (ctxt->depth < _max_depth) { --_max_depth; _container.pop_back(); } } } SYMBOL_KIND Symbol_collector::get_symbol_kind(const IR::Node* node) { if (node->is<IR::Declaration_Constant>()) { return SYMBOL_KIND::Constant; } if (node->is<IR::Type_Header>() || node->is<IR::Type_Struct>()) { return SYMBOL_KIND::Class; } if (node->is<IR::P4Parser>() || node->is<IR::P4Control>()) { return SYMBOL_KIND::Class; } if (node->is<IR::Type_Typedef>()) { return SYMBOL_KIND::Interface; } if (node->is<IR::Declaration_Instance>()) { return SYMBOL_KIND::Variable; } if (node->is<IR::StructField>()) { return SYMBOL_KIND::Field; } if (node->is<IR::ParserState>() || node->is<IR::P4Action>() || node->is<IR::P4Table>()) { return SYMBOL_KIND::Method; } return SYMBOL_KIND::Null; } #endif P4_file::P4_file(const std::string &command, const std::string &unit_path, const std::string& text) : _command(std::make_unique<char[]>(command.size() + 1)) , _unit_path(unit_path) , _source_code(text) , _changed(true) { _logger.add_attribute("Tag", boost::log::attributes::constant<std::string>("P4UNIT")); BOOST_LOG(_logger) << "constructor started."; boost::char_separator<char> separator(" "); boost::tokenizer<boost::char_separator<char>> tokens(command, separator); auto arg = _command.get(); for (auto it = tokens.begin(); it != tokens.end(); ++it) { BOOST_LOG(_logger) << "process token " << *it; auto size = it->size() + 1; strncpy(arg, it->c_str(), size); _argv.emplace_back(arg); arg += size; } compile(); BOOST_LOG(_logger) << "constructed."; } void P4_file::change_source_code(const std::vector<Text_document_content_change_event>& content_changes) { _changed = true; for (auto& it : content_changes) { if (!it._range) { _source_code = it._text; BOOST_LOG(_logger) << "replaced entire source code with new content."; } else { const auto start = get_position_index(_source_code, it._range->_start); const auto end = get_position_index(_source_code, it._range->_end); if (start != std::string::npos && end != std::string::npos && start <= end && (!it._range_length || *it._range_length == end - start)) { std::string content; content.reserve(start + it._text.size() + _source_code.size() - end); content = _source_code.substr(0, start); content += it._text; content += _source_code.substr(end); _source_code = std::move(content); BOOST_LOG(_logger) << "applied content change in range " << *it._range; } else { BOOST_LOG_SEV(_logger, boost::log::sinks::syslog::error) << "ignore invalid content change in range " << *it._range; } } } } std::vector<Symbol_information>& P4_file::get_symbols() { if (_changed) { compile(); } return _symbols; } boost::optional<std::string> P4_file::get_hover(const Location& location) { BOOST_LOG(_logger) << "search hover for " << location; for (const auto& it : _locations[location._uri]) { BOOST_LOG(_logger) << "check location " << it.first; if (it.first & location._range) { auto def = _definitions.find(it.second); if (def != _definitions.end()) { return def->second; } return boost::none; } } return boost::none; } boost::optional<std::vector<Text_document_highlight>> P4_file::get_highlights(const Location& location) { BOOST_LOG(_logger) << "search highlight for " << location; for (const auto& it : _locations[location._uri]) { BOOST_LOG(_logger) << "check location " << it.first; if (it.first & location._range) { return _highlights[it.second]; } } return boost::none; } void P4_file::compile() { using token_type = p4l::p4lex_token<>; using lexer_type = p4l::p4lex_iterator<token_type>; using context_type = boost::wave::context<std::string::iterator, lexer_type>; context_type::token_type current_token; context_type ctx(_source_code.begin(), _source_code.end(), _unit_path.c_str()); ctx.set_language(boost::wave::support_cpp0x); ctx.set_language(boost::wave::enable_preserve_comments(ctx.get_language())); ctx.set_language(boost::wave::enable_prefer_pp_numbers(ctx.get_language())); ctx.set_language(boost::wave::enable_emit_contnewlines(ctx.get_language())); auto token = ctx.begin(); while (token != ctx.end()) { try { ++token; } catch (boost::wave::cpp_exception const& e) { std::cerr << e.file_name() << "(" << e.line_no() << "): " << e.description() << std::endl; } catch (std::exception const& e) { std::cerr << current_token.get_position().get_file() << "(" << current_token.get_position().get_line() << "): " << "unexpected exception: " << e.what() << std::endl; } catch (...) { std::cerr << current_token.get_position().get_file() << "(" << current_token.get_position().get_line() << "): " << "unexpected exception." << std::endl; } } #if 0 p4c_options.process(_argv.size(), _argv.data()); BOOST_LOG(_logger) << "processed options, number of errors " << ::errorCount(); auto temp_file_path = boost::filesystem::temp_directory_path() / boost::filesystem::unique_path("%%%%-%%%%-%%%%-%%%%.p4"); p4c_options.file = temp_file_path.native(); std::ofstream ofs(p4c_options.file); ofs << _source_code; ofs.close(); BOOST_LOG(_logger) << "wrote document \"" << _unit_path << "\" to a temporary file \"" << p4c_options.file << "\""; _program.reset(P4::parseP4File(p4c_options)); auto error_count = ::errorCount(); BOOST_LOG(_logger) << "compiled p4 source file, number of errors " << error_count; auto existed = remove(temp_file_path); BOOST_LOG(_logger) << "removed temporary file " << temp_file_path << " " << existed; if (_program && error_count == 0) { _definitions.clear(); _highlights.clear(); _locations.clear(); _indexes.clear(); _symbols.clear(); Collected_data output{_symbols, _definitions, _highlights, _locations, _indexes}; Outline outline(p4c_options, _unit_path, output); outline.process(_program); _changed = false; } #endif }
31.036585
168
0.66002
emacsmirror
dce6ee9dfeccca2323e051210f3cbdc7907fdb94
2,336
cpp
C++
WebKit/Source/WebKit2/UIProcess/API/qt/qwebiconimageprovider.cpp
JavaScriptTesting/LJS
9818dbdb421036569fff93124ac2385d45d01c3a
[ "Apache-2.0" ]
1
2019-06-18T06:52:54.000Z
2019-06-18T06:52:54.000Z
WebKit/Source/WebKit2/UIProcess/API/qt/qwebiconimageprovider.cpp
JavaScriptTesting/LJS
9818dbdb421036569fff93124ac2385d45d01c3a
[ "Apache-2.0" ]
null
null
null
WebKit/Source/WebKit2/UIProcess/API/qt/qwebiconimageprovider.cpp
JavaScriptTesting/LJS
9818dbdb421036569fff93124ac2385d45d01c3a
[ "Apache-2.0" ]
null
null
null
/* Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "config.h" #include "qwebiconimageprovider_p.h" #include "QtWebContext.h" #include "QtWebIconDatabaseClient.h" #include <QtCore/QUrl> #include <QtGui/QImage> #include <wtf/text/WTFString.h> using namespace WebKit; QWebIconImageProvider::QWebIconImageProvider() : QDeclarativeImageProvider(QDeclarativeImageProvider::Image) { } QWebIconImageProvider::~QWebIconImageProvider() { } QImage QWebIconImageProvider::requestImage(const QString& id, QSize* size, const QSize& requestedSize) { QString decodedIconUrl = id; decodedIconUrl.remove(0, decodedIconUrl.indexOf('#') + 1); String pageURL = QString::fromUtf8(QUrl(decodedIconUrl).toEncoded()); // The string identifier has the leading image://webicon/ already stripped, so we just // need to truncate from the first slash to get the context id. QString contextIDAsString = id; contextIDAsString.truncate(contextIDAsString.indexOf(QLatin1Char('/'))); bool ok = false; uint64_t contextId = contextIDAsString.toUInt(&ok); if (!ok) return QImage(); QtWebContext* context = QtWebContext::contextByID(contextId); if (!context) return QImage(); QtWebIconDatabaseClient* iconDatabase = context->iconDatabase(); QImage icon = requestedSize.isValid() ? iconDatabase->iconImageForPageURL(pageURL, requestedSize) : iconDatabase->iconImageForPageURL(pageURL); ASSERT(!icon.isNull()); if (size) *size = icon.size(); return icon; }
34.865672
147
0.733733
JavaScriptTesting
dce7bc0cd2c7defa0c032a2f8ec3efdfb7e7dfc0
2,150
cc
C++
src/remoting/host/screen_resolution_unittest.cc
jxjnjjn/chromium
435c1d02fd1b99001dc9e1e831632c894523580d
[ "Apache-2.0" ]
9
2018-09-21T05:36:12.000Z
2021-11-15T15:14:36.000Z
src/remoting/host/screen_resolution_unittest.cc
jxjnjjn/chromium
435c1d02fd1b99001dc9e1e831632c894523580d
[ "Apache-2.0" ]
null
null
null
src/remoting/host/screen_resolution_unittest.cc
jxjnjjn/chromium
435c1d02fd1b99001dc9e1e831632c894523580d
[ "Apache-2.0" ]
3
2018-11-28T14:54:13.000Z
2020-07-02T07:36:07.000Z
// Copyright (c) 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "remoting/host/screen_resolution.h" #include <limits> #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" namespace remoting { TEST(ScreenResolutionTest, Empty) { ScreenResolution resolution; EXPECT_TRUE(resolution.IsEmpty()); resolution.dimensions_.set(-1, 0); EXPECT_TRUE(resolution.IsEmpty()); resolution.dimensions_.set(0, -1); EXPECT_TRUE(resolution.IsEmpty()); resolution.dimensions_.set(-1, -1); EXPECT_TRUE(resolution.IsEmpty()); resolution.dpi_.set(-1, 0); EXPECT_TRUE(resolution.IsEmpty()); resolution.dpi_.set(0, -1); EXPECT_TRUE(resolution.IsEmpty()); resolution.dpi_.set(-1, -1); EXPECT_TRUE(resolution.IsEmpty()); } TEST(ScreenResolutionTest, Invalid) { ScreenResolution resolution; EXPECT_TRUE(resolution.IsValid()); resolution.dimensions_.set(-1, 0); EXPECT_FALSE(resolution.IsValid()); resolution.dimensions_.set(0, -1); EXPECT_FALSE(resolution.IsValid()); resolution.dimensions_.set(-1, -1); EXPECT_FALSE(resolution.IsValid()); resolution.dpi_.set(-1, 0); EXPECT_FALSE(resolution.IsValid()); resolution.dpi_.set(0, -1); EXPECT_FALSE(resolution.IsValid()); resolution.dpi_.set(-1, -1); EXPECT_FALSE(resolution.IsValid()); } TEST(ScreenResolutionTest, Scaling) { ScreenResolution resolution( SkISize::Make(100, 100), SkIPoint::Make(10, 10)); EXPECT_EQ(resolution.ScaleDimensionsToDpi(SkIPoint::Make(5, 5)), SkISize::Make(50, 50)); EXPECT_EQ(resolution.ScaleDimensionsToDpi(SkIPoint::Make(20, 20)), SkISize::Make(200, 200)); } TEST(ScreenResolutionTest, ScalingSaturation) { ScreenResolution resolution( SkISize::Make(10000000, 1000000), SkIPoint::Make(1, 1)); EXPECT_EQ(resolution.ScaleDimensionsToDpi(SkIPoint::Make(1000000, 1000000)), SkISize::Make(std::numeric_limits<int32>::max(), std::numeric_limits<int32>::max())); } } // namespace remoting
26.54321
78
0.710233
jxjnjjn
dce7c7e21f38167ab9d28022a0e0c56bf0c96614
13,250
cpp
C++
app/rtkconv/codeopt.cpp
mws-rmain/RTKLIB
3cd1f799b04da433f29473332c250b0518aa762c
[ "BSD-2-Clause" ]
2
2021-11-06T07:23:27.000Z
2021-11-07T14:29:21.000Z
app/rtkconv/codeopt.cpp
mws-rmain/RTKLIB
3cd1f799b04da433f29473332c250b0518aa762c
[ "BSD-2-Clause" ]
null
null
null
app/rtkconv/codeopt.cpp
mws-rmain/RTKLIB
3cd1f799b04da433f29473332c250b0518aa762c
[ "BSD-2-Clause" ]
3
2020-09-28T02:42:26.000Z
2020-09-28T09:01:08.000Z
//--------------------------------------------------------------------------- #include <vcl.h> #pragma hdrstop #include "rtklib.h" #include "convopt.h" #include "codeopt.h" //--------------------------------------------------------------------------- #pragma package(smart_init) #pragma resource "*.dfm" TCodeOptDialog *CodeOptDialog; //--------------------------------------------------------------------------- __fastcall TCodeOptDialog::TCodeOptDialog(TComponent* Owner) : TForm(Owner) { } //--------------------------------------------------------------------------- void __fastcall TCodeOptDialog::FormShow(TObject *Sender) { char mask[7][64]={""}; for (int i=0;i<7;i++) strcpy(mask[i],ConvOptDialog->CodeMask[i].c_str()); G01->Checked=mask[0][ 0]=='1'; G02->Checked=mask[0][ 1]=='1'; G03->Checked=mask[0][ 2]=='1'; G04->Checked=mask[0][ 3]=='1'; G05->Checked=mask[0][ 4]=='1'; G06->Checked=mask[0][ 5]=='1'; G07->Checked=mask[0][ 6]=='1'; G08->Checked=mask[0][ 7]=='1'; G14->Checked=mask[0][13]=='1'; G15->Checked=mask[0][14]=='1'; G16->Checked=mask[0][15]=='1'; G17->Checked=mask[0][16]=='1'; G18->Checked=mask[0][17]=='1'; G19->Checked=mask[0][18]=='1'; G20->Checked=mask[0][19]=='1'; G21->Checked=mask[0][20]=='1'; G22->Checked=mask[0][21]=='1'; G23->Checked=mask[0][22]=='1'; G24->Checked=mask[0][23]=='1'; G25->Checked=mask[0][24]=='1'; G26->Checked=mask[0][25]=='1'; R01->Checked=mask[1][ 0]=='1'; R02->Checked=mask[1][ 1]=='1'; R14->Checked=mask[1][13]=='1'; R19->Checked=mask[1][18]=='1'; R44->Checked=mask[1][43]=='1'; R45->Checked=mask[1][44]=='1'; R46->Checked=mask[1][45]=='1'; E01->Checked=mask[2][ 0]=='1'; E10->Checked=mask[2][ 9]=='1'; E11->Checked=mask[2][10]=='1'; E12->Checked=mask[2][11]=='1'; E13->Checked=mask[2][12]=='1'; E24->Checked=mask[2][23]=='1'; E25->Checked=mask[2][24]=='1'; E26->Checked=mask[2][25]=='1'; E27->Checked=mask[2][26]=='1'; E28->Checked=mask[2][27]=='1'; E29->Checked=mask[2][28]=='1'; E30->Checked=mask[2][29]=='1'; E31->Checked=mask[2][30]=='1'; E32->Checked=mask[2][31]=='1'; E33->Checked=mask[2][32]=='1'; E34->Checked=mask[2][33]=='1'; E37->Checked=mask[2][36]=='1'; E38->Checked=mask[2][37]=='1'; E39->Checked=mask[2][38]=='1'; J01->Checked=mask[3][ 0]=='1'; J07->Checked=mask[3][ 6]=='1'; J08->Checked=mask[3][ 7]=='1'; J13->Checked=mask[3][12]=='1'; J12->Checked=mask[3][11]=='1'; J16->Checked=mask[3][15]=='1'; J17->Checked=mask[3][16]=='1'; J18->Checked=mask[3][17]=='1'; J24->Checked=mask[3][23]=='1'; J25->Checked=mask[3][24]=='1'; J26->Checked=mask[3][25]=='1'; J35->Checked=mask[3][34]=='1'; J36->Checked=mask[3][35]=='1'; J33->Checked=mask[3][32]=='1'; C40->Checked=mask[5][39]=='1'; C41->Checked=mask[5][40]=='1'; C12->Checked=mask[5][11]=='1'; C27->Checked=mask[5][26]=='1'; C28->Checked=mask[5][27]=='1'; C29->Checked=mask[5][28]=='1'; C42->Checked=mask[5][41]=='1'; C43->Checked=mask[5][42]=='1'; C33->Checked=mask[5][32]=='1'; I49->Checked=mask[6][48]=='1'; I50->Checked=mask[6][49]=='1'; I51->Checked=mask[6][50]=='1'; I26->Checked=mask[6][25]=='1'; I52->Checked=mask[6][51]=='1'; I53->Checked=mask[6][52]=='1'; I54->Checked=mask[6][53]=='1'; I55->Checked=mask[6][54]=='1'; S01->Checked=mask[4][ 0]=='1'; S24->Checked=mask[4][23]=='1'; S25->Checked=mask[4][24]=='1'; S26->Checked=mask[4][25]=='1'; UpdateEnable(); } //--------------------------------------------------------------------------- void __fastcall TCodeOptDialog::BtnOkClick(TObject *Sender) { char mask[7][64]={""}; for (int i=0;i<7;i++) for (int j=0;j<MAXCODE;j++) mask[i][j]='0'; if (G01->Checked) mask[0][ 0]='1'; if (G02->Checked) mask[0][ 1]='1'; if (G03->Checked) mask[0][ 2]='1'; if (G04->Checked) mask[0][ 3]='1'; if (G05->Checked) mask[0][ 4]='1'; if (G06->Checked) mask[0][ 5]='1'; if (G07->Checked) mask[0][ 6]='1'; if (G08->Checked) mask[0][ 7]='1'; if (G14->Checked) mask[0][13]='1'; if (G15->Checked) mask[0][14]='1'; if (G16->Checked) mask[0][15]='1'; if (G17->Checked) mask[0][16]='1'; if (G18->Checked) mask[0][17]='1'; if (G19->Checked) mask[0][18]='1'; if (G20->Checked) mask[0][19]='1'; if (G21->Checked) mask[0][20]='1'; if (G22->Checked) mask[0][21]='1'; if (G23->Checked) mask[0][22]='1'; if (G24->Checked) mask[0][23]='1'; if (G25->Checked) mask[0][24]='1'; if (G26->Checked) mask[0][25]='1'; if (R01->Checked) mask[1][ 0]='1'; if (R02->Checked) mask[1][ 1]='1'; if (R14->Checked) mask[1][13]='1'; if (R19->Checked) mask[1][18]='1'; if (R44->Checked) mask[1][43]='1'; if (R45->Checked) mask[1][44]='1'; if (R46->Checked) mask[1][45]='1'; if (E01->Checked) mask[2][ 0]='1'; if (E10->Checked) mask[2][ 9]='1'; if (E11->Checked) mask[2][10]='1'; if (E12->Checked) mask[2][11]='1'; if (E13->Checked) mask[2][12]='1'; if (E24->Checked) mask[2][23]='1'; if (E25->Checked) mask[2][24]='1'; if (E26->Checked) mask[2][25]='1'; if (E27->Checked) mask[2][26]='1'; if (E28->Checked) mask[2][27]='1'; if (E29->Checked) mask[2][28]='1'; if (E30->Checked) mask[2][29]='1'; if (E31->Checked) mask[2][30]='1'; if (E32->Checked) mask[2][31]='1'; if (E33->Checked) mask[2][32]='1'; if (E34->Checked) mask[2][33]='1'; if (E37->Checked) mask[2][36]='1'; if (E38->Checked) mask[2][37]='1'; if (E39->Checked) mask[2][38]='1'; if (J01->Checked) mask[3][ 0]='1'; if (J07->Checked) mask[3][ 6]='1'; if (J08->Checked) mask[3][ 7]='1'; if (J13->Checked) mask[3][12]='1'; if (J12->Checked) mask[3][11]='1'; if (J16->Checked) mask[3][15]='1'; if (J17->Checked) mask[3][16]='1'; if (J18->Checked) mask[3][17]='1'; if (J24->Checked) mask[3][23]='1'; if (J25->Checked) mask[3][24]='1'; if (J26->Checked) mask[3][25]='1'; if (J35->Checked) mask[3][34]='1'; if (J36->Checked) mask[3][35]='1'; if (J33->Checked) mask[3][32]='1'; if (C40->Checked) mask[5][39]='1'; if (C41->Checked) mask[5][40]='1'; if (C12->Checked) mask[5][11]='1'; if (C27->Checked) mask[5][26]='1'; if (C28->Checked) mask[5][27]='1'; if (C29->Checked) mask[5][28]='1'; if (C42->Checked) mask[5][41]='1'; if (C43->Checked) mask[5][42]='1'; if (C33->Checked) mask[5][32]='1'; if (I49->Checked) mask[6][48]='1'; if (I50->Checked) mask[6][49]='1'; if (I51->Checked) mask[6][50]='1'; if (I26->Checked) mask[6][25]='1'; if (I52->Checked) mask[6][51]='1'; if (I53->Checked) mask[6][52]='1'; if (I54->Checked) mask[6][53]='1'; if (I55->Checked) mask[6][54]='1'; if (S01->Checked) mask[4][ 0]='1'; if (S24->Checked) mask[4][23]='1'; if (S25->Checked) mask[4][24]='1'; if (S26->Checked) mask[4][25]='1'; for (int i=0;i<7;i++) ConvOptDialog->CodeMask[i]=mask[i]; } //--------------------------------------------------------------------------- void __fastcall TCodeOptDialog::BtnSetAllClick(TObject *Sender) { int set=BtnSetAll->Caption=="Set All"; G01->Checked=set; G02->Checked=set; G03->Checked=set; G04->Checked=set; G05->Checked=set; G06->Checked=set; G07->Checked=set; G08->Checked=set; G14->Checked=set; G15->Checked=set; G16->Checked=set; G17->Checked=set; G18->Checked=set; G19->Checked=set; G20->Checked=set; G21->Checked=set; G22->Checked=set; G23->Checked=set; G24->Checked=set; G25->Checked=set; G26->Checked=set; R01->Checked=set; R02->Checked=set; R14->Checked=set; R19->Checked=set; R44->Checked=set; R45->Checked=set; R46->Checked=set; E01->Checked=set; E10->Checked=set; E11->Checked=set; E12->Checked=set; E13->Checked=set; E24->Checked=set; E25->Checked=set; E26->Checked=set; E27->Checked=set; E28->Checked=set; E29->Checked=set; E30->Checked=set; E31->Checked=set; E32->Checked=set; E33->Checked=set; E34->Checked=set; E37->Checked=set; E38->Checked=set; E39->Checked=set; J01->Checked=set; J07->Checked=set; J08->Checked=set; J13->Checked=set; J12->Checked=set; J16->Checked=set; J17->Checked=set; J18->Checked=set; J24->Checked=set; J25->Checked=set; J26->Checked=set; J35->Checked=set; J36->Checked=set; J33->Checked=set; C40->Checked=set; C41->Checked=set; C12->Checked=set; C27->Checked=set; C28->Checked=set; C29->Checked=set; C42->Checked=set; C43->Checked=set; C33->Checked=set; I49->Checked=set; I50->Checked=set; I51->Checked=set; I26->Checked=set; I52->Checked=set; I53->Checked=set; I54->Checked=set; I55->Checked=set; S01->Checked=set; S24->Checked=set; S25->Checked=set; S26->Checked=set; BtnSetAll->Caption=BtnSetAll->Caption=="Set All"?"Unset All":"Set All"; } //--------------------------------------------------------------------------- void __fastcall TCodeOptDialog::UpdateEnable(void) { G01->Enabled=(NavSys&SYS_GPS)&&(FreqType&FREQTYPE_L1); G02->Enabled=(NavSys&SYS_GPS)&&(FreqType&FREQTYPE_L1); G03->Enabled=(NavSys&SYS_GPS)&&(FreqType&FREQTYPE_L1); G04->Enabled=(NavSys&SYS_GPS)&&(FreqType&FREQTYPE_L1); G05->Enabled=(NavSys&SYS_GPS)&&(FreqType&FREQTYPE_L1); G06->Enabled=(NavSys&SYS_GPS)&&(FreqType&FREQTYPE_L1); G07->Enabled=(NavSys&SYS_GPS)&&(FreqType&FREQTYPE_L1); G08->Enabled=(NavSys&SYS_GPS)&&(FreqType&FREQTYPE_L1); G14->Enabled=(NavSys&SYS_GPS)&&(FreqType&FREQTYPE_L2); G15->Enabled=(NavSys&SYS_GPS)&&(FreqType&FREQTYPE_L2); G16->Enabled=(NavSys&SYS_GPS)&&(FreqType&FREQTYPE_L2); G17->Enabled=(NavSys&SYS_GPS)&&(FreqType&FREQTYPE_L2); G18->Enabled=(NavSys&SYS_GPS)&&(FreqType&FREQTYPE_L2); G19->Enabled=(NavSys&SYS_GPS)&&(FreqType&FREQTYPE_L2); G20->Enabled=(NavSys&SYS_GPS)&&(FreqType&FREQTYPE_L2); G21->Enabled=(NavSys&SYS_GPS)&&(FreqType&FREQTYPE_L2); G22->Enabled=(NavSys&SYS_GPS)&&(FreqType&FREQTYPE_L2); G23->Enabled=(NavSys&SYS_GPS)&&(FreqType&FREQTYPE_L2); G24->Enabled=(NavSys&SYS_GPS)&&(FreqType&FREQTYPE_L5); G25->Enabled=(NavSys&SYS_GPS)&&(FreqType&FREQTYPE_L5); G26->Enabled=(NavSys&SYS_GPS)&&(FreqType&FREQTYPE_L5); R01->Enabled=(NavSys&SYS_GLO)&&(FreqType&FREQTYPE_L1); R02->Enabled=(NavSys&SYS_GLO)&&(FreqType&FREQTYPE_L1); R14->Enabled=(NavSys&SYS_GLO)&&(FreqType&FREQTYPE_L2); R19->Enabled=(NavSys&SYS_GLO)&&(FreqType&FREQTYPE_L2); R44->Enabled=(NavSys&SYS_GLO)&&(FreqType&FREQTYPE_L5); R45->Enabled=(NavSys&SYS_GLO)&&(FreqType&FREQTYPE_L5); R46->Enabled=(NavSys&SYS_GLO)&&(FreqType&FREQTYPE_L5); E01->Enabled=(NavSys&SYS_GAL)&&(FreqType&FREQTYPE_L1); E10->Enabled=(NavSys&SYS_GAL)&&(FreqType&FREQTYPE_L1); E11->Enabled=(NavSys&SYS_GAL)&&(FreqType&FREQTYPE_L1); E12->Enabled=(NavSys&SYS_GAL)&&(FreqType&FREQTYPE_L1); E13->Enabled=(NavSys&SYS_GAL)&&(FreqType&FREQTYPE_L1); E24->Enabled=(NavSys&SYS_GAL)&&(FreqType&FREQTYPE_L5); E25->Enabled=(NavSys&SYS_GAL)&&(FreqType&FREQTYPE_L5); E26->Enabled=(NavSys&SYS_GAL)&&(FreqType&FREQTYPE_L5); E27->Enabled=(NavSys&SYS_GAL)&&(FreqType&FREQTYPE_L2); E28->Enabled=(NavSys&SYS_GAL)&&(FreqType&FREQTYPE_L2); E29->Enabled=(NavSys&SYS_GAL)&&(FreqType&FREQTYPE_L2); E30->Enabled=(NavSys&SYS_GAL)&&(FreqType&FREQTYPE_E6); E31->Enabled=(NavSys&SYS_GAL)&&(FreqType&FREQTYPE_E6); E32->Enabled=(NavSys&SYS_GAL)&&(FreqType&FREQTYPE_E6); E33->Enabled=(NavSys&SYS_GAL)&&(FreqType&FREQTYPE_E6); E34->Enabled=(NavSys&SYS_GAL)&&(FreqType&FREQTYPE_E6); E37->Enabled=(NavSys&SYS_GAL)&&(FreqType&FREQTYPE_E5ab); E38->Enabled=(NavSys&SYS_GAL)&&(FreqType&FREQTYPE_E5ab); E39->Enabled=(NavSys&SYS_GAL)&&(FreqType&FREQTYPE_E5ab); J01->Enabled=(NavSys&SYS_QZS)&&(FreqType&FREQTYPE_L1); J07->Enabled=(NavSys&SYS_QZS)&&(FreqType&FREQTYPE_L1); J08->Enabled=(NavSys&SYS_QZS)&&(FreqType&FREQTYPE_L1); J13->Enabled=(NavSys&SYS_QZS)&&(FreqType&FREQTYPE_L1); J12->Enabled=(NavSys&SYS_QZS)&&(FreqType&FREQTYPE_L1); J16->Enabled=(NavSys&SYS_QZS)&&(FreqType&FREQTYPE_L2); J17->Enabled=(NavSys&SYS_QZS)&&(FreqType&FREQTYPE_L2); J18->Enabled=(NavSys&SYS_QZS)&&(FreqType&FREQTYPE_L2); J24->Enabled=(NavSys&SYS_QZS)&&(FreqType&FREQTYPE_L2); J25->Enabled=(NavSys&SYS_QZS)&&(FreqType&FREQTYPE_L2); J26->Enabled=(NavSys&SYS_QZS)&&(FreqType&FREQTYPE_L2); J35->Enabled=(NavSys&SYS_QZS)&&(FreqType&FREQTYPE_E6); J36->Enabled=(NavSys&SYS_QZS)&&(FreqType&FREQTYPE_E6); J33->Enabled=(NavSys&SYS_QZS)&&(FreqType&FREQTYPE_E6); C40->Enabled=(NavSys&SYS_CMP)&&(FreqType&FREQTYPE_L1); C41->Enabled=(NavSys&SYS_CMP)&&(FreqType&FREQTYPE_L1); C12->Enabled=(NavSys&SYS_CMP)&&(FreqType&FREQTYPE_L1); C27->Enabled=(NavSys&SYS_CMP)&&(FreqType&FREQTYPE_L2); C28->Enabled=(NavSys&SYS_CMP)&&(FreqType&FREQTYPE_L2); C29->Enabled=(NavSys&SYS_CMP)&&(FreqType&FREQTYPE_L2); C42->Enabled=(NavSys&SYS_CMP)&&(FreqType&FREQTYPE_E6); C43->Enabled=(NavSys&SYS_CMP)&&(FreqType&FREQTYPE_E6); C33->Enabled=(NavSys&SYS_CMP)&&(FreqType&FREQTYPE_E6); I49->Enabled=(NavSys&SYS_IRN)&&(FreqType&FREQTYPE_L5); I50->Enabled=(NavSys&SYS_IRN)&&(FreqType&FREQTYPE_L5); I51->Enabled=(NavSys&SYS_IRN)&&(FreqType&FREQTYPE_L5); I26->Enabled=(NavSys&SYS_IRN)&&(FreqType&FREQTYPE_L5); I52->Enabled=(NavSys&SYS_IRN)&&(FreqType&FREQTYPE_S); I53->Enabled=(NavSys&SYS_IRN)&&(FreqType&FREQTYPE_S); I54->Enabled=(NavSys&SYS_IRN)&&(FreqType&FREQTYPE_S); I55->Enabled=(NavSys&SYS_IRN)&&(FreqType&FREQTYPE_S); S01->Enabled=(NavSys&SYS_SBS)&&(FreqType&FREQTYPE_L1); S24->Enabled=(NavSys&SYS_SBS)&&(FreqType&FREQTYPE_L5); S25->Enabled=(NavSys&SYS_SBS)&&(FreqType&FREQTYPE_L5); S26->Enabled=(NavSys&SYS_SBS)&&(FreqType&FREQTYPE_L5); } //---------------------------------------------------------------------------
35.333333
77
0.621057
mws-rmain
dce8f2d9c0b49f28c69ed3956605127dc5d9ea22
268
cpp
C++
benchmarks/lmbench/src/App/SysEnvironment/grp_ocall.cpp
shwetasshinde24/Panoply
9a762c24dec61250d953d1769b070df7f0dd0317
[ "Apache-2.0" ]
30
2017-02-08T02:53:36.000Z
2022-03-24T14:26:17.000Z
benchmarks/lmbench/src/App/SysEnvironment/grp_ocall.cpp
shwetasshinde24/Panoply
9a762c24dec61250d953d1769b070df7f0dd0317
[ "Apache-2.0" ]
4
2017-05-25T00:39:02.000Z
2018-04-27T10:38:47.000Z
benchmarks/lmbench/src/App/SysEnvironment/grp_ocall.cpp
shwetasshinde24/Panoply
9a762c24dec61250d953d1769b070df7f0dd0317
[ "Apache-2.0" ]
8
2017-10-31T11:12:35.000Z
2020-06-15T04:12:51.000Z
/** * @author ${kekkaishivn} - dattl@ifi.uio.no * * ${tags} */ #include <grp.h> #include "MyEnclave_u.h" struct group *ocall_getgrgid(gid_t gid) { return getgrgid(gid); } int ocall_initgroups(const char *user, gid_t group) { return initgroups(user, group); }
14.105263
51
0.675373
shwetasshinde24
dce93554c6735c0cd9fe675aaa1c4e96a80b1b64
10,164
hpp
C++
include/openpose/producer/datumProducer.hpp
mooktj/openpose
f4ee9cba3621093bba88bb17d1ea6a19ff3236ad
[ "DOC" ]
null
null
null
include/openpose/producer/datumProducer.hpp
mooktj/openpose
f4ee9cba3621093bba88bb17d1ea6a19ff3236ad
[ "DOC" ]
null
null
null
include/openpose/producer/datumProducer.hpp
mooktj/openpose
f4ee9cba3621093bba88bb17d1ea6a19ff3236ad
[ "DOC" ]
null
null
null
#ifndef OPENPOSE_PRODUCER_DATUM_PRODUCER_HPP #define OPENPOSE_PRODUCER_DATUM_PRODUCER_HPP #include <atomic> #include <limits> // std::numeric_limits #include <tuple> #include <openpose/core/common.hpp> #include <openpose/core/datum.hpp> #include <openpose/utilities/fastMath.hpp> #include <openpose/producer/producer.hpp> #include <iostream> #include <string> namespace op { template<typename TDatum> class DatumProducer { public: explicit DatumProducer( const std::shared_ptr<Producer>& producerSharedPtr, const unsigned long long frameFirst = 0, const unsigned long long frameStep = 1, const unsigned long long frameLast = std::numeric_limits<unsigned long long>::max(), const std::shared_ptr<std::pair<std::atomic<bool>, std::atomic<int>>>& videoSeekSharedPtr = nullptr); virtual ~DatumProducer(); std::pair<bool, std::shared_ptr<std::vector<std::shared_ptr<TDatum>>>> checkIfRunningAndGetDatum(); private: const unsigned long long mNumberFramesToProcess; std::shared_ptr<Producer> spProducer; unsigned long long mGlobalCounter; unsigned long long mFrameStep; unsigned int mNumberConsecutiveEmptyFrames; std::shared_ptr<std::pair<std::atomic<bool>, std::atomic<int>>> spVideoSeek; void checkIfTooManyConsecutiveEmptyFrames( unsigned int& numberConsecutiveEmptyFrames, const bool emptyFrame) const; DELETE_COPY(DatumProducer); }; } // Implementation #include <opencv2/imgproc/imgproc.hpp> // cv::cvtColor #include <openpose/producer/datumProducer.hpp> namespace op { template<typename TDatum> DatumProducer<TDatum>::DatumProducer( const std::shared_ptr<Producer>& producerSharedPtr, const unsigned long long frameFirst, const unsigned long long frameStep, const unsigned long long frameLast, const std::shared_ptr<std::pair<std::atomic<bool>, std::atomic<int>>>& videoSeekSharedPtr) : mNumberFramesToProcess{(frameLast != std::numeric_limits<unsigned long long>::max() ? frameLast - frameFirst : frameLast)}, spProducer{producerSharedPtr}, mGlobalCounter{0ll}, mFrameStep{frameStep}, mNumberConsecutiveEmptyFrames{0u}, spVideoSeek{videoSeekSharedPtr} { try { // Sanity check if (frameLast < frameFirst) error("The desired initial frame must be lower than the last one (flags `--frame_first` vs." " `--frame_last`). Current: " + std::to_string(frameFirst) + " vs. " + std::to_string(frameLast) + ".", __LINE__, __FUNCTION__, __FILE__); if (frameLast != std::numeric_limits<unsigned long long>::max() && frameLast > spProducer->get(CV_CAP_PROP_FRAME_COUNT)-1) error("The desired last frame must be lower than the length of the video or the number of images." " Current: " + std::to_string(frameLast) + " vs. " + std::to_string(positiveIntRound(spProducer->get(CV_CAP_PROP_FRAME_COUNT))-1) + ".", __LINE__, __FUNCTION__, __FILE__); // Set frame first and step if (spProducer->getType() != ProducerType::FlirCamera && spProducer->getType() != ProducerType::IPCamera && spProducer->getType() != ProducerType::Webcam) { // Frame first spProducer->set(CV_CAP_PROP_POS_FRAMES, (double)frameFirst); // Frame step spProducer->set(ProducerProperty::FrameStep, (double)frameStep); } } catch (const std::exception& e) { error(e.what(), __LINE__, __FUNCTION__, __FILE__); } } template<typename TDatum> DatumProducer<TDatum>::~DatumProducer() { } template<typename TDatum> std::pair<bool, std::shared_ptr<std::vector<std::shared_ptr<TDatum>>>> DatumProducer<TDatum>::checkIfRunningAndGetDatum() { try { auto datums = std::make_shared<std::vector<std::shared_ptr<TDatum>>>(); // Check last desired frame has not been reached if (mNumberFramesToProcess != std::numeric_limits<unsigned long long>::max() && mGlobalCounter > mNumberFramesToProcess) { spProducer->release(); } // If producer released -> it sends an empty cv::Mat + a datumProducerRunning signal const bool datumProducerRunning = spProducer->isOpened(); // If device is open if (datumProducerRunning) { // Fast forward/backward - Seek to specific frame index desired if (spVideoSeek != nullptr) { // Fake pause vs. normal mode const auto increment = spVideoSeek->second - (spVideoSeek->first ? 1 : 0); // Normal mode if (increment != 0) spProducer->set(CV_CAP_PROP_POS_FRAMES, spProducer->get(CV_CAP_PROP_POS_FRAMES) + increment); // It must be always reset or bug in fake pause spVideoSeek->second = 0; } auto nextFrameName = spProducer->getNextFrameName(); const auto nextFrameNumber = (unsigned long long)spProducer->get(CV_CAP_PROP_POS_FRAMES); const auto cvMats = spProducer->getFrames(); const auto cameraMatrices = spProducer->getCameraMatrices(); auto cameraExtrinsics = spProducer->getCameraExtrinsics(); auto cameraIntrinsics = spProducer->getCameraIntrinsics(); // Check frames are not empty checkIfTooManyConsecutiveEmptyFrames(mNumberConsecutiveEmptyFrames, cvMats.empty() || cvMats[0].empty()); if (!cvMats.empty()) { datums->resize(cvMats.size()); // Datum cannot be assigned before resize() auto& datumPtr = (*datums)[0]; datumPtr = std::make_shared<TDatum>(); // Filling first element std::swap(datumPtr->name, nextFrameName); datumPtr->frameNumber = nextFrameNumber; datumPtr->cvInputData = cvMats[0]; if (!cameraMatrices.empty()) { datumPtr->cameraMatrix = cameraMatrices[0]; datumPtr->cameraExtrinsics = cameraExtrinsics[0]; datumPtr->cameraIntrinsics = cameraIntrinsics[0]; } // Image integrity if (datumPtr->cvInputData.channels() != 3) { const std::string commonMessage{"Input images must be 3-channel BGR."}; // Grey to RGB if required if (datumPtr->cvInputData.channels() == 1) { log(commonMessage + " Converting grey image into BGR.", Priority::High); cv::cvtColor(datumPtr->cvInputData, datumPtr->cvInputData, CV_GRAY2BGR); } else error(commonMessage, __LINE__, __FUNCTION__, __FILE__); } // std::cout << "DatumProducer:: datumPtr->cvOutputData is empty? " << datumPtr->cvOutputData.empty() << "\n"; datumPtr->cvOutputData = datumPtr->cvInputData; // Resize if it's stereo-system if (datums->size() > 1) { // Stereo-system: Assign all cv::Mat for (auto i = 1u ; i < datums->size() ; i++) { auto& datumIPtr = (*datums)[i]; datumIPtr = std::make_shared<TDatum>(); datumIPtr->name = datumPtr->name; datumIPtr->frameNumber = datumPtr->frameNumber; datumIPtr->cvInputData = cvMats[i]; datumIPtr->cvOutputData = datumIPtr->cvInputData; if (cameraMatrices.size() > i) { datumIPtr->cameraMatrix = cameraMatrices[i]; datumIPtr->cameraExtrinsics = cameraExtrinsics[i]; datumIPtr->cameraIntrinsics = cameraIntrinsics[i]; } } } // Check producer is running if (!datumProducerRunning || (*datums)[0]->cvInputData.empty()) datums = nullptr; // Increase counter if successful image if (datums != nullptr) mGlobalCounter += mFrameStep; } } // Return result return std::make_pair(datumProducerRunning, datums); } catch (const std::exception& e) { error(e.what(), __LINE__, __FUNCTION__, __FILE__); return std::make_pair(false, std::make_shared<std::vector<std::shared_ptr<TDatum>>>()); } } template<typename TDatum> void DatumProducer<TDatum>::checkIfTooManyConsecutiveEmptyFrames( unsigned int& numberConsecutiveEmptyFrames, const bool emptyFrame) const { numberConsecutiveEmptyFrames = (emptyFrame ? numberConsecutiveEmptyFrames+1 : 0); const auto threshold = 500u; if (numberConsecutiveEmptyFrames >= threshold) error("Detected too many (" + std::to_string(numberConsecutiveEmptyFrames) + ") empty frames in a row.", __LINE__, __FUNCTION__, __FILE__); } extern template class DatumProducer<BASE_DATUM>; } #endif // OPENPOSE_PRODUCER_DATUM_PRODUCER_HPP
45.375
130
0.55854
mooktj
dceb343d5fe0af1a7e3b086a79d7797eb8378261
16,637
cpp
C++
Blocks/manager.cpp
dtulga/arcBlocks
db54cfc09e51a7330135fa139f7436e81fd9de9f
[ "MIT" ]
null
null
null
Blocks/manager.cpp
dtulga/arcBlocks
db54cfc09e51a7330135fa139f7436e81fd9de9f
[ "MIT" ]
null
null
null
Blocks/manager.cpp
dtulga/arcBlocks
db54cfc09e51a7330135fa139f7436e81fd9de9f
[ "MIT" ]
null
null
null
#include "manager.h" namespace Blocks { Manager manager; Manager::~Manager() { // So the 0x1 placeholders are not accidentally deleted. blocks_[0] = nullptr; groups_[0] = nullptr; deleteallslotvector(connections_); deleteallslotvector(blocks_); deleteallslotvector(groups_); } // TODO: Multiple windows/screens on desktop. void Manager::Init(ExpandingInteractive& main_canvas_or_scene, const ScreenProperties& props) { if (!graphics.Init()) { log::Fatal("Blocks Manager", "Graphics failed to initialize!"); } main_cs_ = &main_canvas_or_scene; screen_props_ = props; screen_props_.hidden = true; input.RegisterDefaultEventHandler(Event); input.RegisterInterruptEventHandler(InterruptEvent); // Create the screen but hidden for now. (So everything can be loaded.) Screen& screen = graphics.CreateCustomScreen(screen_props_); main_screen_ = &screen; render.SetScreenContext(screen); input.RegisterFrameDrawHandler(screen, Draw); // Set based on interpreted values in case of fullscreen, mobile, etc. main_cs_->setDrawableArea(main_screen_->width(), main_screen_->height()); active_.store(true); } // Run the event loop, draw frames, and pass events to the component blocks. int Manager::Exec() { // Set based on interpreted values in case of fullscreen, mobile, etc. main_cs_->setDrawableArea(main_screen_->width(), main_screen_->height()); main_screen_->show(); return input.ExecEventHandlerLoop(); } void Manager::Event(InputModule::Event e) { manager.EventInternal(e); } // Thread Safe void Manager::InterruptEvent(InputModule::Event e) { manager.InterruptEventInternal(e); } // Thread Safe void Manager::InterruptEventInternal(InputModule::Event e) { switch (e.type) { case InputModule::AppToBackground: active_.store(false); if (onbackground_ != nullptr) onbackground_(); break; case InputModule::AppToForeground: active_.store(true); if (onforeground_ != nullptr) onforeground_(); break; // TODO: LowMemory, Termination events } } // This handles events directly from the input module. void Manager::EventInternal(InputModule::Event e) { BlockEvent be; switch (e.type) { case InputModule::ScreenResize: // If resize, then resize the main_canvas main_cs_->setDrawableArea(e.screen.width, e.screen.height); break; // If mouse/touch, pass down. case InputModule::MouseMove: be.screen.x = e.mouse.x; be.screen.y = e.mouse.y; be.screen.dx = e.mouse.dx; be.screen.dy = e.mouse.dy; if (e.mouse.button_state & SDL_BUTTON_LMASK) { be.type = BlockEvent::PressDrag; // Drag events start at x/y and travel by dx/dy be.screen.x -= e.mouse.dx; be.screen.y -= e.mouse.dy; } else { be.type = BlockEvent::Hover; } break; case InputModule::MouseDown: if (e.mouse.button != SDL_BUTTON_LEFT) { break; } be.type = BlockEvent::PressDown; be.screen.x = e.mouse.x; be.screen.y = e.mouse.y; break; case InputModule::MouseUp: if (e.mouse.button != SDL_BUTTON_LEFT) { break; } be.type = BlockEvent::PressUp; be.screen.x = e.mouse.x; be.screen.y = e.mouse.y; break; // TODO: Right-click/menu button (and 3D touch on iOS too?) // case InputModule::MouseWheel: // TODO! // break; // TODO: These two may have no coordinates? // case InputModule::MouseEnter: be.type = BlockEvent::HoverEnter; break; case InputModule::MouseExit: be.type = BlockEvent::HoverExit; break; case InputModule::TouchMove: be.type = BlockEvent::PressDrag; be.screen.x = e.touch.x - e.touch.dx; be.screen.y = e.touch.y - e.touch.dy; be.screen.dx = e.touch.dx; be.screen.dy = e.touch.dy; break; case InputModule::TouchDown: be.type = BlockEvent::PressDown; be.screen.x = e.touch.x; be.screen.y = e.touch.y; break; case InputModule::TouchUp: be.type = BlockEvent::PressUp; be.screen.x = e.touch.x; be.screen.y = e.touch.y; break; case InputModule::MultiTouch: // TODO! // break; default: // Ignore other events. return; } if (be.is_screen()) { // Send to the Main Canvas (or through the Scene) main_cs_->event(be); } // Process Inter-Block Events Here: ProcessAllBlockEvents(); } void Manager::ProcessAllBlockEvents() { BlockEvent e; const size_t total_group_count = groups_.size(); while (event_queue_.recvEvent(&e)) { // More events to process const size_t o_id = e.origin_id; if (o_id == 0) { // Manager itself, which is impossible. log::Error("Blocks Manager", "Event sent to queue with invalid zero id!"); continue; } else if (o_id >= blocks_.size()) { // Since events are never sent from a group id. log::Error("Blocks Manager", "Invalid inter-block event source id: " + string::itoa(o_id)); continue; } BlockConn* bc = blocks_[o_id]; if (bc == nullptr) { log::Error("Blocks Manager", "Event sent to queue from removed/deleted block!"); continue; } std::vector<Connection*>* conns_ = &(bc->conn_from); // All connections from this block ID. size_t group_j = -1; const size_t group_len = bc->groups.size(); while (true) { for (size_t i = 0; i < conns_->size(); i++) { Connection* c = (*conns_)[i]; if (c == nullptr || (c->event != BlockEvent::Any && c->event != e.type)) { continue; // Check next connection, not a match. } // Possible match, check other connection conditions. if (c->type == Connection::Always) { // OK! } else if (c->type == Connection::IfFunc) { if (c->test_func == nullptr || !(c->test_func(e))) { continue; // Not active, otherwise OK. } } else if (c->type == Connection::IfVar) { if (c->test_var == nullptr || !(c->test_var)) { continue; // Not active, otherwise OK. } } else { log::Error("Blocks Manager", "Unsupported connection type!"); continue; } // Send Action size_t d_id = c->destination; if (d_id == 0) { // Manager itself if (c->action == BlockAction::Quit) { input.Quit(); // Doesn't actually quit immediately, in case of a save dialog, etc. continue; } else if (c->action == BlockAction::RunFunc) { if (c->action_func != nullptr) { c->action_func(e); } else { log::Error("Blocks Manager", "Custom action function missing!"); } continue; } else { log::Error("Blocks Manager", "Invalid action passed to manager: " + string::itoa(c->action)); continue; } } else if (d_id == Connection::ID_SELF) { // Send the action to the origin block SendActionToBlock(o_id, c, e); } else if (d_id >= Connection::ID_GROUP_OFFSET) { // Group destination d_id -= Connection::ID_GROUP_OFFSET; if (d_id >= groups_.size() || d_id == 0) { // Group zero is also reserved. log::Error("Blocks Manager", "Invalid inter-block action destination group id: " + string::itoa(d_id)); continue; } BlockGroup* group = groups_[d_id]; if (group == nullptr) { log::Error("Blocks Manager", "Action sent to removed/deleted group!"); return; } const size_t g_len = group->blocks.size(); for (size_t g = 0; g < g_len; g++) { Eventable* block = group->blocks[g]; if (block != nullptr) { SendActionToBlock(block, c, e); } } } else { // Send the action to the (single) block SendActionToBlock(d_id, c, e); } } group_j++; while (group_j < group_len && (bc->groups[group_j] == 0 || bc->groups[group_j] >= total_group_count || groups_[bc->groups[group_j]] == nullptr)) { // Skip invalid groups group_j++; } if (group_j < group_len) { conns_ = &(groups_[bc->groups[group_j]]->conn_from); } else { // Done with groups break; } } } } void Manager::SendActionToBlock(const size_t destination_id, Connection* c, const BlockEvent& e) { if (destination_id >= blocks_.size() || destination_id == 0) { log::Error("Blocks Manager", "Invalid inter-block action destination id: " + string::itoa(destination_id)); return; } BlockConn* dest_bc = blocks_[destination_id]; if (dest_bc == nullptr || dest_bc->block == nullptr) { log::Error("Blocks Manager", "Action sent to removed/deleted block!"); return; } SendActionToBlock(dest_bc->block, c, e); } void Manager::SendActionToBlock(Eventable* block, Connection* c, const BlockEvent& e) { BlockAction a(c->action); if (c->default_data.type != BlockAction::Invalid) { a = c->default_data; a.type = c->action; } if (a.is_movement()) { if (a.type == BlockAction::SetPos) { a.position.x = e.screen.x; a.position.y = e.screen.y; } else if (a.type == BlockAction::MoveBy) { a.delta.dx = e.screen.dx; a.delta.dy = e.screen.dy; } } else if (a.is_block()) { Drawable* d = nullptr; switch (a.type) { case BlockAction::BlockEnable: block->enable(); break; case BlockAction::BlockDisable: block->disable(); break; case BlockAction::BlockToggleEnabled: block->toggle_enabled(); break; case BlockAction::BlockShow: case BlockAction::BlockHide: case BlockAction::BlockToggleVisible: case BlockAction::BlockShowEnable: case BlockAction::BlockHideDisable: case BlockAction::BlockToggleVisibleEnabled: d = dynamic_cast<Drawable*>(block); if (d == nullptr) { log::Fatal("Blocks Manager", "Attempted to show/hide a non-drawable block!"); } switch (a.type) { case BlockAction::BlockShow: d->show(); break; case BlockAction::BlockHide: d->hide(); break; case BlockAction::BlockToggleVisible: d->toggle_visible(); break; case BlockAction::BlockShowEnable: d->show(); block->enable(); break; case BlockAction::BlockHideDisable: d->hide(); block->disable(); break; case BlockAction::BlockToggleVisibleEnabled: d->toggle_visible(); block->toggle_enabled(); break; default: log::Error("Blocks Manager", "Unknown block-specific action!"); break; } break; default: log::Error("Blocks Manager", "Unknown block-specific action!"); break; } return; // These actions are done directly without passing to the block. } else if (a.is_generate()) { if (a.type == BlockAction::GenerateRemoveSender || a.type == BlockAction::GenerateReplaceSender) { a.sender.id = e.origin_id; } } block->action(a); } void Manager::Draw(const double frame_delta_time_msec) { manager.DrawInternal(frame_delta_time_msec); } // This handles the frame_draw from the input module's event loop. void Manager::DrawInternal(const double frame_delta_time_msec) { if (!active_.load(std::memory_order_relaxed)) return; frame_delta_time_msec_ = frame_delta_time_msec; frame_count_++; // Process any physics/etc. before drawing. const size_t len = frame_processors_.size(); for (size_t i = 0; i < len; i++) { FrameProcessor* fp = frame_processors_[i]; if (fp != nullptr) { fp->frame(frame_delta_time_msec); } } if (!active_.load(std::memory_order_relaxed)) return; render.ClearDrawOffset(); // As the main canvas fills the entire screen. render.Clear(white); main_cs_->draw(); if (!active_.load(std::memory_order_relaxed)) return; render.RenderFrameDone(); } void Manager::AddFrameProcessor(FrameProcessor& proc) { addtoslotvectorindex(frame_processors_, &proc); } void Manager::RemoveFrameProcessor(FrameProcessor& proc) { // Don't delete as the frame processor object is not owned here, and may be re-used or re-added later on. deletefromslotvector(frame_processors_, &proc, false); } // To allow this block to participate in the event connection system. // If the block only draws or handles screen events from the canvas, then this is unneccessary. size_t Manager::RegisterEventable(Eventable& block) { const size_t id = addtoslotvectorindex(blocks_, new BlockConn(block)); block.registerEventSendQueue(id, event_queue_); // So this block can send events to the manager and other blocks. return id; } void Manager::DeregisterEventable(const size_t block_id) { if (block_id >= blocks_.size()) { // TODO: Print error here? return; } BlockConn* bc = blocks_[block_id]; if (bc == nullptr) { return; // OK if already deleted. } Eventable* e = blocks_[block_id]->block; if (e != nullptr) { e->deregisterEventSendQueue(); }/* else { // TODO: Print error here? }*/ for (size_t i = 0; i < bc->groups.size(); i++) { RemoveEventableFromGroup(block_id, bc->groups[i]); } delete blocks_[block_id]; blocks_[block_id] = nullptr; } size_t Manager::RegisterGroup() { // Returns the next available group ID return addtoslotvectorindex(groups_, new BlockGroup()) + Connection::ID_GROUP_OFFSET; } // TODO: Remove the groups each block in this group is a part of from their BlockConn(s) // OR: Make sure all blocks are removed from this group first, before it can be deleted? void Manager::DeregisterGroup(size_t group_id) { if (group_id >= Connection::ID_GROUP_OFFSET) { group_id -= Connection::ID_GROUP_OFFSET; } if (group_id >= groups_.size() || group_id == 0) { // TODO: Print error here? return; } BlockGroup* group = groups_[group_id]; if (group == nullptr) { return; // OK if already deleted. } delete groups_[group_id]; groups_[group_id] = nullptr; } size_t Manager::RegisterEventableInGroup(Eventable& block, const size_t group_id) { // Returns the index/id of the block added. const size_t id = RegisterEventable(block); AddEventableToGroup(id, group_id); return id; } void Manager::AddEventableToGroup(const size_t block_id, size_t group_id) { if (group_id >= Connection::ID_GROUP_OFFSET) { group_id -= Connection::ID_GROUP_OFFSET; } if (group_id >= groups_.size() || group_id == 0 || block_id >= blocks_.size()) { // TODO: Print error here? return; } BlockGroup* group = groups_[group_id]; BlockConn* bc = blocks_[block_id]; if (group == nullptr || bc == nullptr) { // TODO: Print error here? return; } addtoslotvectorindex(group->blocks, bc->block); addtozerovector(bc->groups, group_id); } void Manager::RemoveEventableFromGroup(const size_t block_id, size_t group_id) { if (group_id >= Connection::ID_GROUP_OFFSET) { group_id -= Connection::ID_GROUP_OFFSET; } if (group_id >= groups_.size() || group_id == 0 || block_id >= blocks_.size()) { // TODO: Print error here? return; } BlockGroup* group = groups_[group_id]; BlockConn* bc = blocks_[block_id]; if (group == nullptr || bc == nullptr) { // TODO: Print error here? return; } Eventable* e = bc->block; if (e == nullptr) { // TODO: Print error here? return; } deletefromslotvector(group->blocks, e, false); // Don't actually delete as the Eventable is not owned. removefromzerovector(bc->groups, group_id); } size_t Manager::AddEventActionConnection(const Connection& conn) { const size_t o = conn.origin; const size_t d = conn.destination; const size_t bc_len = blocks_.size(); // Destination can be the manager (0), and both can be a group. if (o == 0 || (o >= bc_len && !(o >= Connection::ID_GROUP_OFFSET && (o - Connection::ID_GROUP_OFFSET) < groups_.size())) || (d >= bc_len && !(d >= Connection::ID_GROUP_OFFSET && (d - Connection::ID_GROUP_OFFSET) < groups_.size()) && d != Connection::ID_SELF)) { log::Error("Invalid connection added to manager (invalid origin/destination)!"); return -1; // TODO: Should connection zero be returned/reserved instead? } if (conn.type == Connection::IfFunc && conn.test_func == nullptr) { log::Error("Blocks Manager", "Invalid IfFunc connection - no test function!"); return -1; } if (conn.type == Connection::IfVar && conn.test_var == nullptr) { log::Error("Blocks Manager", "Invalid IfFunc connection - no test function!"); return -1; } Connection* c = new Connection(conn); const size_t conn_id = addtoslotvectorindex(connections_, c); // Copy data. if (o >= Connection::ID_GROUP_OFFSET) { // Is a group-based connection. groups_[o - Connection::ID_GROUP_OFFSET]->conn_from.push_back(c); } else { blocks_[o]->conn_from.push_back(c); } return conn_id; } } // namespace Blocks
29.239016
128
0.652521
dtulga
dcec710ff4c3a62228b325e1546ef90961b041af
2,076
cpp
C++
ihmc-pub-sub/cppsrc/FastRTPS/subscriberexample.cpp
loulansuiye/ihmc-pub-sub-group
c6635ac0cb3a28c18252ffc8033e76360c540e3a
[ "ECL-2.0", "Apache-2.0" ]
1
2018-11-03T02:48:20.000Z
2018-11-03T02:48:20.000Z
ihmc-pub-sub/cppsrc/FastRTPS/subscriberexample.cpp
loulansuiye/ihmc-pub-sub-group
c6635ac0cb3a28c18252ffc8033e76360c540e3a
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
ihmc-pub-sub/cppsrc/FastRTPS/subscriberexample.cpp
loulansuiye/ihmc-pub-sub-group
c6635ac0cb3a28c18252ffc8033e76360c540e3a
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
#include "nativeparticipantimpl.h" #include "nativesubscriberimpl.h" #include <iostream> #include <chrono> #include <thread> using namespace us::ihmc::rtps::impl::fastRTPS; class ExampleParticipantListener : public NativeParticipantListener { void onParticipantDiscovery(int64_t infoPtr, int64_t guidHigh, int64_t guidLow, DISCOVERY_STATUS status) { std::cout << "Discovered participant " << getName(infoPtr) << std::endl; } }; class ExampleSubscriberListener : public NativeSubscriberListener { virtual void onSubscriptionMatched(MatchingStatus status, int64_t guidHigh, int64_t guidLow) { std::cout << "Found publisher" << std::endl; } virtual void onNewDataMessage() { std::cout << "Got callback" << std::endl; } }; int main() { RTPSParticipantAttributes rtps; rtps.setName("Participant"); rtps.builtin.domainId = 1; ExampleParticipantListener participantListener; NativeParticipantImpl participant(rtps, &participantListener); participant.registerType("chat::ChatMessage", 64000, false); SubscriberAttributes attr; attr.topic.topicName = "ChatBox1"; attr.topic.topicDataType = "chat::ChatMessage"; attr.qos.m_reliability.kind = BEST_EFFORT_RELIABILITY_QOS; attr.qos.m_partition.push_back("us/ihmc"); ExampleSubscriberListener subscriberListener; NativeSubscriberImpl subscriber(-1, -1, 528, PREALLOCATED_MEMORY_MODE, &attr.topic, &attr.qos, &attr.times, &attr.unicastLocatorList, &attr.multicastLocatorList, &attr.outLocatorList, false, &participant, &subscriberListener); subscriber.createSubscriber(); std::vector<unsigned char> data(64000); SampleInfoMarshaller marshaller; while(true) { subscriber.waitForUnreadMessage(); if(subscriber.takeNextData(64000, data.data(), &marshaller, NO_KEY, SHARED_OWNERSHIP_QOS)) { std::cout << "Got message of length " << marshaller.dataLength << std::endl; } } }
28.833333
148
0.688343
loulansuiye
dcef3916bce8005255e1572fbfb090a643a8dbcc
6,860
cpp
C++
jshEngine/src/Engine.cpp
JoseLRM/jshEngine
589851ca3e845e407d81dc555dc76dc70c010f25
[ "Apache-2.0" ]
1
2021-11-03T08:05:57.000Z
2021-11-03T08:05:57.000Z
jshEngine/src/Engine.cpp
JoseLRM/jshEngine
589851ca3e845e407d81dc555dc76dc70c010f25
[ "Apache-2.0" ]
null
null
null
jshEngine/src/Engine.cpp
JoseLRM/jshEngine
589851ca3e845e407d81dc555dc76dc70c010f25
[ "Apache-2.0" ]
null
null
null
#include "common.h" #include "Window.h" #include "TaskSystem.h" #include "Timer.h" #include "Graphics.h" #include "Renderer.h" #include "State.h" #include "DefaultLoadState.h" #include "StateManager.h" #include "GuiSystem.h" using namespace jsh; using namespace jsh::_internal; namespace jshEngine { void BeginUpdate(float dt); void EndUpdate(float dt); uint32 g_FPS = 0u; Time g_DeltaTime = 0.f; uint32 g_FixedUpdateFrameRate; float g_FixedUpdateDeltaTime; StateManager g_State; GuiSystem g_GuiSystem; enum JSH_ENGINE_STATE : uint8 { JSH_ENGINE_STATE_NONE, JSH_ENGINE_STATE_INITIALIZING, JSH_ENGINE_STATE_INITIALIZED, JSH_ENGINE_STATE_RUNNING, JSH_ENGINE_STATE_CLOSING, JSH_ENGINE_STATE_CLOSED }; JSH_ENGINE_STATE g_EngineState = JSH_ENGINE_STATE_NONE; bool Initialize(jsh::State* state, jsh::State* loadState) { jshTimer::Initialize(); jshDebug::_internal::Initialize(); if (g_EngineState != JSH_ENGINE_STATE_NONE) { jshDebug::LogW("jshEngine is already initialized"); return false; } g_EngineState = JSH_ENGINE_STATE_INITIALIZING; try { if (!jshTask::Initialize()) { jshDebug::LogE("Can't initialize jshTaskSystem"); return false; } SetFixedUpdateFrameRate(60u); if (!jshWindow::Initialize()) { jshDebug::LogE("Can't initialize jshWindow"); return false; } if (!jshRenderer::_internal::Initialize()) { jshDebug::LogE("Can't initialize jshRenderer"); return false; } //im gui initialize jshImGui(if (!jshGraphics::_internal::InitializeImGui()) { jshDebug::LogE("Cant't initialize ImGui"); return false; }); jshScene::Initialize(); g_GuiSystem.Initialize(); LoadState(state, loadState); jshDebug::LogI("jshEngine initialized"); jshDebug::LogSeparator(); g_EngineState = JSH_ENGINE_STATE_INITIALIZED; } catch (std::exception e) { jshFatalError("STD Exception: '%s'", e.what()); return false; } catch (...) { jshFatalError("Unknown error"); return false; } return true; } void Run() { if (g_EngineState != JSH_ENGINE_STATE_INITIALIZED) { jshFatalError("You must initialize jshEngine"); } g_EngineState = JSH_ENGINE_STATE_RUNNING; try { Time lastTime = jshTimer::Now(); g_DeltaTime = lastTime; Time actualTime = 0.f; const float SHOW_FPS_RATE = 1.0f; float dtCount = 0.f; float fpsCount = 0u; float fixedUpdateCount = 0.f; while (jshWindow::UpdateInput()) { actualTime = jshTimer::Now(); g_DeltaTime = actualTime - lastTime; lastTime = actualTime; fixedUpdateCount += g_DeltaTime; if (g_DeltaTime > 0.2f) g_DeltaTime = 0.2f; g_State.Prepare(); // update BeginUpdate(g_DeltaTime); g_State.Update(g_DeltaTime); if (fixedUpdateCount >= 0.01666666f) { fixedUpdateCount -= 0.01666666f; g_State.FixedUpdate(); } EndUpdate(g_DeltaTime); // render jshRenderer::_internal::Begin(); g_State.Render(); jshRenderer::_internal::Render(); jshRenderer::_internal::End(); // FPS count dtCount += g_DeltaTime; fpsCount++; if (dtCount >= SHOW_FPS_RATE) { g_FPS = uint32(fpsCount / SHOW_FPS_RATE); //jshDebug::Log("%u", g_FPS); fpsCount = 0.f; dtCount -= SHOW_FPS_RATE; } } } catch (std::exception e) { jshFatalError("STD Exception: '%s'", e.what()); } catch (...) { jshFatalError("Unknown error"); } } bool Close() { jshDebug::LogSeparator(); if (g_EngineState == JSH_ENGINE_STATE_CLOSING || g_EngineState == JSH_ENGINE_STATE_CLOSED) { jshDebug::LogW("jshEngine is already closed"); } g_EngineState = JSH_ENGINE_STATE_CLOSING; try { g_State.ClearState(); jshScene::Close(); if (!jshTask::Close()) return false; if (!jshWindow::Close()) return false; if (!jshRenderer::_internal::Close()) return false; jshDebug::LogI("jshEngine closed"); jshDebug::_internal::Close(); g_EngineState = JSH_ENGINE_STATE_CLOSED; } catch (std::exception e) { jshFatalError("STD Exception: '%s'", e.what()); return false; } catch (...) { jshFatalError("Unknown error"); return false; } return true; } void Exit(int code) { if (g_EngineState != JSH_ENGINE_STATE_CLOSED) { if (!Close()) jshDebug::LogE("Can't close jshEngine properly"); } exit(code); } ///////////////////////////////////////UPDATE///////////////////////////////////// void BeginUpdate(float dt) { if (jshInput::IsKey(JSH_KEY_CONTROL) && jshInput::IsKeyPressed(JSH_KEY_F11)) jshEngine::Exit(0); // Update Camera matrices { auto& cameras = jshScene::_internal::GetComponentsList()[CameraComponent::ID]; for (uint32 i = 0; i < cameras.size(); i += uint32(CameraComponent::SIZE)) { CameraComponent* camera = reinterpret_cast<CameraComponent*>(&cameras[i]); camera->UpdateMatrices(); } } // Update Gui g_GuiSystem.Update(dt); } void EndUpdate(float dt) { } ////////////////////////////////////////STATE MANAGEMENT//////////////////////////// void LoadState(jsh::State* state, jsh::State* loadState) { g_State.LoadState(state, loadState); } State* GetCurrentState() { return g_State.GetCurrentState(); } uint32 GetFPS() { return g_FPS; } float GetDeltaTime() { return g_DeltaTime; } bool IsInitialized() { return g_EngineState != JSH_ENGINE_STATE_NONE && g_EngineState != JSH_ENGINE_STATE_INITIALIZING; } // FIXED UPDATE METHODS void SetFixedUpdateFrameRate(uint32 frameRate) { g_FixedUpdateFrameRate = frameRate; g_FixedUpdateDeltaTime = 1.f / (float)frameRate; } float GetFixedUpdateDeltaTime() { return g_FixedUpdateDeltaTime; } // VERSION constexpr uint64 g_MajorVersion = 0u; constexpr uint64 g_MinorVersion = 1u; constexpr uint64 g_RevisionVersion = 2u; uint64 GetMajorVersion() { return g_MajorVersion; } uint64 GetMinorVersion() { return g_MinorVersion; } uint64 GetRevisionVersion() { return g_RevisionVersion; } uint64 GetVersion() { return g_MajorVersion * 1000000u + g_MinorVersion * 1000u + g_RevisionVersion; } const char* GetVersionStr() { const static std::string str = std::string(std::to_string(g_MajorVersion) + '.' + std::to_string(g_MinorVersion) + '.' + std::to_string(g_RevisionVersion)); return str.c_str(); } const wchar* GetVersionStrW() { const static std::wstring str = std::wstring(std::to_wstring(g_MajorVersion) + L'.' + std::to_wstring(g_MinorVersion) + L'.' + std::to_wstring(g_RevisionVersion)); return str.c_str(); } // PROPERTIES const char* GetName() { const static std::string str = std::string("jshEngine " + std::string(GetVersionStr())); return str.c_str(); } const wchar* GetNameW() { const static std::wstring str = std::wstring(L"jshEngine " + std::wstring(GetVersionStrW())); return str.c_str(); } }
21.847134
165
0.669388
JoseLRM
dcefd235f4e7e990c1ed1fea4014b36d03e2140f
2,191
cpp
C++
src/Utils/Utils/Optimizer/LeastSquares/LevenbergMarquardt.cpp
DockBio/utilities
213ed5ac2a64886b16d0fee1fcecb34d36eea9e9
[ "BSD-3-Clause" ]
null
null
null
src/Utils/Utils/Optimizer/LeastSquares/LevenbergMarquardt.cpp
DockBio/utilities
213ed5ac2a64886b16d0fee1fcecb34d36eea9e9
[ "BSD-3-Clause" ]
null
null
null
src/Utils/Utils/Optimizer/LeastSquares/LevenbergMarquardt.cpp
DockBio/utilities
213ed5ac2a64886b16d0fee1fcecb34d36eea9e9
[ "BSD-3-Clause" ]
null
null
null
/** * @file * @copyright This code is licensed under the 3-clause BSD license.\n * Copyright ETH Zurich, Laboratory for Physical Chemistry, Reiher Group.\n * See LICENSE.txt for details. */ #include "LevenbergMarquardt.h" #include <Eigen/Dense> #include <unsupported/Eigen/NonLinearOptimization> namespace Scine { namespace Utils { void LevenbergMarquardt::optimize(Eigen::VectorXd& parameters, UpdateFunctionManagerBase& updateFunctionManager) { LMFunctor functor(updateFunctionManager); functor.n = static_cast<int>(parameters.size()); functor.m = functor.updateFunctionManager_.getNumberOfDataPoints(parameters); Eigen::LevenbergMarquardt<LMFunctor, double> lm(functor); // Set maximum number of function evaluations if it was set to a sensible value if (maxFuncEval > 0) lm.parameters.maxfev = maxFuncEval; lm.minimize(parameters); // Calculate and update covariance matrix if desired if (calculateCovarianceMatrix) { auto hessian = lm.fjac.transpose() * lm.fjac; auto inverseHessian = hessian.inverse(); auto variance = (1.0 / (functor.m - functor.n + 1.0)) * lm.fvec.squaredNorm(); covarianceMatrix_ = variance * inverseHessian; } } LevenbergMarquardt::LMFunctor::LMFunctor(UpdateFunctionManagerBase& updateFunctionManager) : updateFunctionManager_(updateFunctionManager) { } // Compute 'm' errors, one for each data point, for the given parameter values in 'x' int LevenbergMarquardt::LMFunctor::operator()(const Eigen::VectorXd& parameters, Eigen::VectorXd& fvec) const { updateFunctionManager_.updateErrors(parameters, fvec); return 0; } // Compute the Jacobian of the errors int LevenbergMarquardt::LMFunctor::df(const Eigen::VectorXd& parameters, Eigen::MatrixXd& fjac) const { updateFunctionManager_.updateJacobian(parameters, fjac); return 0; } // Returns 'm', the number of values. int LevenbergMarquardt::LMFunctor::values() const { return m; } // Returns 'n', the number of inputs. int LevenbergMarquardt::LMFunctor::inputs() const { return n; } const Eigen::MatrixXd& LevenbergMarquardt::getCovarianceMatrix() { return covarianceMatrix_; } } // namespace Utils } // namespace Scine
34.234375
114
0.748517
DockBio
fd62bfc933d9c3e56aa94762113b6f80e107d6f5
2,182
cc
C++
codejam/2016/round1B/A.cc
metaflow/contests
5e9ffcb72c3e7da54b5e0818b1afa59f5778ffa2
[ "MIT" ]
1
2019-05-12T23:41:00.000Z
2019-05-12T23:41:00.000Z
codejam/2016/round1B/A.cc
metaflow/contests
5e9ffcb72c3e7da54b5e0818b1afa59f5778ffa2
[ "MIT" ]
null
null
null
codejam/2016/round1B/A.cc
metaflow/contests
5e9ffcb72c3e7da54b5e0818b1afa59f5778ffa2
[ "MIT" ]
null
null
null
#include<bits/stdc++.h> using namespace std; using vi = vector<int>; using vvi = vector<vi>; using ii = pair<int,int>; using vii = vector<ii>; using l = long long; using vl = vector<l>; using vvl = vector<vl>; using ll = pair<l,l>; using vll = vector<ll>; using vvll = vector<vll>; using lu = unsigned long long; using vb = vector<bool>; using vvb = vector<vb>; using vd = vector<double>; using vvd = vector<vd>; const int INF = numeric_limits<int>::max(); const double EPS = 1e-10; const l e5 = 100000, e6 = 1000000, e7 = 10000000, e9 = 1000000000; vvl masks(10); const l MAX = 30; bool solve(vl& chars, vl& solution, int number) { if (number == 10) { for (auto c : chars) if (c) return false; return true; } l min_count = INF; for (l i = 0; i < MAX; i++) { if (masks[number][i]) min_count = min(min_count, chars[i] / masks[number][i]); } // cerr << number << " min " << min_count << endl; for (l i = min_count; i >= 0; i--) { for (l j = 0; j < MAX; j++) { chars[j] -= i * masks[number][j]; } solution[number] = i; if (solve(chars, solution, number+1)) return true; for (l j = 0; j < MAX; j++) { chars[j] += i * masks[number][j]; } } return false; } vl get_mask(string s) { vl result(MAX); for (auto c : s) result[c - 'A']++; return result; } int main() { ios_base::sync_with_stdio(false); cin.tie(0); l tcc; cin >> tcc; struct { string value; char mark; int digit; } traits[] = { {"ZERO", 'Z', 0}, {"TWO", 'W', 2}, {"FOUR", 'U', 4}, {"SIX", 'X', 6}, {"FIVE", 'F', 5}, {"SEVEN", 'V', 7}, {"EIGHT", 'G', 8}, {"NINE", 'I', 9}, {"THREE", 'R', 3}, {"ONE", 'N', 1}, }; for (l tc = 0; tc < tcc; tc++) { cout << "Case #" << (tc + 1) << ": "; string s; cin >> s; auto ms = get_mask(s); vl counts(10); for (auto t : traits) { l c = ms[t.mark - 'A']; auto m = get_mask(t.value); for (l j = 0; j < MAX; j++) { ms[j] -= m[j] * c; } counts[t.digit] = c; } for (l i = 0; i < 10; i++) { for (l j = 0; j < counts[i]; j++) { cout << i; } } cout << endl; } }
24.516854
82
0.504125
metaflow
fd63b8fb642c55df7570d013d857ccc936715c9e
64,295
cpp
C++
compiler/util/clangUtil.cpp
krishnakeshav/chapel
c7840d76944cfb1b63878e51e81138d1a0c808cf
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
compiler/util/clangUtil.cpp
krishnakeshav/chapel
c7840d76944cfb1b63878e51e81138d1a0c808cf
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
compiler/util/clangUtil.cpp
krishnakeshav/chapel
c7840d76944cfb1b63878e51e81138d1a0c808cf
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
/* * Copyright 2004-2017 Cray Inc. * Other additional copyright holders may be indicated within. * * The entirety of this work is 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 __STDC_FORMAT_MACROS #define __STDC_FORMAT_MACROS #endif #include "clangUtil.h" #include <inttypes.h> #include <cctype> #include <cstring> #include <cstdio> #include <sstream> #include "astutil.h" #include "driver.h" #include "expr.h" #include "files.h" #include "mysystem.h" #include "passes.h" #include "stmt.h" #include "stringutil.h" #include "symbol.h" #include "type.h" #include "codegen.h" #include "clangSupport.h" #include "build.h" #include "llvmDebug.h" typedef Type ChapelType; #ifndef HAVE_LLVM void readExternC(void) { // Do nothing if we don't have LLVM support. } void cleanupExternC(void) { // Do nothing if we don't have LLVM support. } #else using namespace clang; using namespace llvm; #define GLOBAL_PTR_SPACE 100 #define WIDE_PTR_SPACE 101 #define GLOBAL_PTR_SIZE 64 #define GLOBAL_PTR_ABI_ALIGN 64 #define GLOBAL_PTR_PREF_ALIGN 64 #include "llvmGlobalToWide.h" #include "llvmAggregateGlobalOps.h" // TODO - add functionality to clang so that we don't // have to have what are basically copies of // ModuleBuilder.cpp // ( and BackendUtil.cpp but we used PassManagerBuilder::addGlobalExtension) // // This one is not normally included by clang clients // and not normally installed in the include directory. // // Q. Could we instead call methods on clang::CodeGenerator subclass of // ASTConsumer such as HandleTopLevelDecl to achieve what we want? // We would have a different AST visitor for populating the LVT. // // It is likely that we can leave the C parser "open" somehow and then // add statements to it at the end. // BUT we couldn't call EmitDeferredDecl. // // #include "CodeGenModule.h" #include "CGRecordLayout.h" #include "CGDebugInfo.h" #include "clang/CodeGen/BackendUtil.h" static void setupForGlobalToWide(); fileinfo gAllExternCode; fileinfo gChplCompilationConfig; static VarSymbol *minMaxConstant(int nbits, bool isSigned, bool isMin) { if( nbits == 8 && isSigned && isMin ) return new_IntSymbol(INT8_MIN, INT_SIZE_8); else if( nbits == 8 && isSigned && !isMin ) return new_IntSymbol(INT8_MAX, INT_SIZE_8); else if( nbits == 8 && !isSigned && isMin ) return new_IntSymbol(0, INT_SIZE_8); else if( nbits == 8 && !isSigned && !isMin ) return new_IntSymbol(UINT8_MAX, INT_SIZE_8); else if( nbits == 16 && isSigned && isMin ) return new_IntSymbol(INT16_MIN, INT_SIZE_16); else if( nbits == 16 && isSigned && !isMin ) return new_IntSymbol(INT16_MAX, INT_SIZE_16); else if( nbits == 16 && !isSigned && isMin ) return new_IntSymbol(0, INT_SIZE_16); else if( nbits == 16 && !isSigned && !isMin ) return new_IntSymbol(UINT16_MAX, INT_SIZE_16); else if( nbits == 32 && isSigned && isMin ) return new_IntSymbol(INT32_MIN, INT_SIZE_32); else if( nbits == 32 && isSigned && !isMin ) return new_IntSymbol(INT32_MAX, INT_SIZE_32); else if( nbits == 32 && !isSigned && isMin ) return new_IntSymbol(0, INT_SIZE_32); else if( nbits == 32 && !isSigned && !isMin ) return new_IntSymbol(UINT32_MAX, INT_SIZE_32); else if( nbits == 64 && isSigned && isMin ) return new_IntSymbol(INT64_MIN, INT_SIZE_64); else if( nbits == 64 && isSigned && !isMin ) return new_IntSymbol(INT64_MAX, INT_SIZE_64); else if( nbits == 64 && !isSigned && isMin ) return new_IntSymbol(0, INT_SIZE_64); else if( nbits == 64 && !isSigned && !isMin ) return new_IntSymbol(UINT64_MAX, INT_SIZE_64); else INT_ASSERT(0 && "Bad options for minMaxConstant"); return NULL; } static void addMinMax(const char* prefix, int nbits, bool isSigned) { GenInfo* info = gGenInfo; LayeredValueTable *lvt = info->lvt; astlocT prevloc = currentAstLoc; currentAstLoc.lineno = 0; currentAstLoc.filename = astr("<internal>"); const char* min_name = astr(prefix, "_MIN"); const char* max_name = astr(prefix, "_MAX"); if( isSigned ) { // only signed versions have a meaningful min. lvt->addGlobalVarSymbol(min_name, minMaxConstant(nbits, isSigned, true)); } // but signed and unsigned both have a max lvt->addGlobalVarSymbol(max_name, minMaxConstant(nbits, isSigned, false)); currentAstLoc = prevloc; } static void addMinMax(ASTContext* Ctx, const char* prefix, clang::CanQualType qt) { const clang::Type* ct = qt.getTypePtr(); int nbits = Ctx->getTypeSize(ct); bool isSigned = ct->isSignedIntegerType(); addMinMax(prefix, nbits, isSigned); } static void setupClangContext(GenInfo* info, ASTContext* Ctx) { std::string layout; info->Ctx = Ctx; if( ! info->parseOnly ) { info->module->setTargetTriple( info->Ctx->getTargetInfo().getTriple().getTriple()); // Also setup some basic TBAA metadata nodes. llvm::LLVMContext& cx = info->module->getContext(); // Create the TBAA root node { LLVM_METADATA_OPERAND_TYPE* Ops[1]; Ops[0] = llvm::MDString::get(cx, "Chapel types"); info->tbaaRootNode = llvm::MDNode::get(cx, Ops); } // Create type for ftable { LLVM_METADATA_OPERAND_TYPE* Ops[3]; Ops[0] = llvm::MDString::get(cx, "Chapel ftable"); Ops[1] = info->tbaaRootNode; // and mark it as constant Ops[2] = llvm_constant_as_metadata( ConstantInt::get(llvm::Type::getInt64Ty(cx), 1)); info->tbaaFtableNode = llvm::MDNode::get(cx, Ops); } { LLVM_METADATA_OPERAND_TYPE* Ops[3]; Ops[0] = llvm::MDString::get(cx, "Chapel vmtable"); Ops[1] = info->tbaaRootNode; // and mark it as constant Ops[2] = llvm_constant_as_metadata( ConstantInt::get(llvm::Type::getInt64Ty(cx), 1)); info->tbaaVmtableNode = llvm::MDNode::get(cx, Ops); } } info->targetLayout = info->Ctx->getTargetInfo().getTargetDescription(); layout = info->targetLayout; if( fLLVMWideOpt && ! info->parseOnly ) { char buf[200]; //needs to store up to 8 32-bit numbers in decimal assert(GLOBAL_PTR_SIZE == GLOBAL_PTR_BITS); // Add global pointer info to layout. snprintf(buf, sizeof(buf), "-p%u:%u:%u:%u-p%u:%u:%u:%u", GLOBAL_PTR_SPACE, GLOBAL_PTR_SIZE, GLOBAL_PTR_ABI_ALIGN, GLOBAL_PTR_PREF_ALIGN, WIDE_PTR_SPACE, GLOBAL_PTR_SIZE, GLOBAL_PTR_ABI_ALIGN, GLOBAL_PTR_PREF_ALIGN); layout += buf; // Save the global address space we are using in info. info->globalToWideInfo.globalSpace = GLOBAL_PTR_SPACE; info->globalToWideInfo.wideSpace = WIDE_PTR_SPACE; } // Always set the module layout. This works around an apparent bug in // clang or LLVM (trivial/deitz/test_array_low.chpl would print out the // wrong answer because some i64s were stored at the wrong alignment). if( info->module ) info->module->setDataLayout(layout); info->targetData = new LLVM_TARGET_DATA(info->Ctx->getTargetInfo().getTargetDescription()); if( ! info->parseOnly ) { info->cgBuilder = new CodeGen::CodeGenModule(*Ctx, #if HAVE_LLVM_VER >= 37 info->Clang->getHeaderSearchOpts(), info->Clang->getPreprocessorOpts(), #endif info->codegenOptions, *info->module, *info->targetData, *info->Diags); } // Set up some constants that depend on the Clang context. { addMinMax(Ctx, "CHAR", Ctx->CharTy); addMinMax(Ctx, "SCHAR", Ctx->SignedCharTy); addMinMax(Ctx, "UCHAR", Ctx->UnsignedCharTy); addMinMax(Ctx, "SHRT", Ctx->ShortTy); addMinMax(Ctx, "USHRT", Ctx->UnsignedShortTy); addMinMax(Ctx, "INT", Ctx->IntTy); addMinMax(Ctx, "UINT", Ctx->UnsignedIntTy); addMinMax(Ctx, "LONG", Ctx->LongTy); addMinMax(Ctx, "ULONG", Ctx->UnsignedLongTy); addMinMax(Ctx, "LLONG", Ctx->LongLongTy); addMinMax(Ctx, "ULLONG", Ctx->UnsignedLongLongTy); } } // Adds a mapping from id->getName() to a variable or CDecl to info->lvt static void handleMacro(const IdentifierInfo* id, const MacroInfo* macro) { GenInfo* info = gGenInfo; Preprocessor &preproc = info->Clang->getPreprocessor(); VarSymbol* varRet = NULL; TypeDecl* cTypeRet = NULL; ValueDecl* cValueRet = NULL; const bool debugPrint = false; if( debugPrint) printf("Adding macro %s\n", id->getName().str().c_str()); //Handling only simple string or integer defines if(macro->getNumArgs() > 0) { if( debugPrint) { printf("the macro takes arguments\n"); } return; // TODO -- handle macro functions. } // Check that we have a single token surrounded by any // number of parens. ie 1, (1), ((1)) Token tok; // the main token. size_t left_parens = 0; size_t right_parens = 0; ssize_t ntokens = macro->getNumTokens(); ssize_t t_idx; bool negate = false; if( ntokens > 0 ) { MacroInfo::tokens_iterator ti = macro->tokens_end() - 1; for( t_idx = ntokens - 1; t_idx >= 0; t_idx-- ) { tok = *ti; if(tok.getKind() == tok::r_paren) right_parens++; else break; --ti; } } { MacroInfo::tokens_iterator ti = macro->tokens_begin(); for( t_idx = 0; t_idx < ntokens; t_idx++ ) { tok = *ti; if(tok.getKind() == tok::l_paren) left_parens++; else if(tok.getKind() == tok::minus) { negate = true; ntokens--; } else break; ++ti; } } if( left_parens == right_parens && ntokens - left_parens - right_parens == 1 ) { // OK! } else { if( debugPrint) { printf("the following macro is too complicated or empty:\n"); } return; // we don't handle complicated expressions like A+B } switch(tok.getKind()) { case tok::numeric_constant: { std::string numString; int hex; int isfloat; if( negate ) numString.append("-"); if (tok.getLiteralData() && tok.getLength()) { numString.append(tok.getLiteralData(), tok.getLength()); } if( debugPrint) printf("num = %s\n", numString.c_str()); hex = 0; if( numString[0] == '0' && (numString[1] == 'x' || numString[1] == 'X')) { hex = 1; } isfloat = 0; if(numString.find('.') != std::string::npos) { isfloat = 1; } // also check for exponent since e.g. 1e10 is a float. if( hex ) { // C99 hex floats use p for exponent if(numString.find('p') != std::string::npos || numString.find('P') != std::string::npos) { isfloat = 1; } } else { if(numString.find('e') != std::string::npos || numString.find('E') != std::string::npos) { isfloat = 1; } } if( !isfloat ) { IF1_int_type size = INT_SIZE_32; if(tolower(numString[numString.length() - 1]) == 'l') { numString[numString.length() - 1] = '\0'; size = INT_SIZE_64; } if(tolower(numString[numString.length() - 1]) == 'u') { numString[numString.length() - 1] = '\0'; varRet = new_UIntSymbol(strtoul(numString.c_str(), NULL, 0), size); } else { varRet = new_IntSymbol(strtol(numString.c_str(), NULL, 0), size); } } else { IF1_float_type size = FLOAT_SIZE_64; if(tolower(numString[numString.length() - 1]) == 'l') { numString[numString.length() - 1] = '\0'; } varRet = new_RealSymbol(numString.c_str(), size); } break; } case tok::string_literal: { std::string body = std::string(tok.getLiteralData(), tok.getLength()); if( debugPrint) printf("str = %s\n", body.c_str()); varRet = new_CStringSymbol(body.c_str()); break; } case tok::identifier: { IdentifierInfo* tokId = tok.getIdentifierInfo(); std::string idName = tokId->getName(); if( debugPrint) { printf("id = %s\n", idName.c_str()); } // Handle the case where the macro refers to something we've // already parsed in C varRet = info->lvt->getVarSymbol(idName); if( !varRet ) { info->lvt->getCDecl(idName, &cTypeRet, &cValueRet); } if( !varRet && !cTypeRet && !cValueRet ) { // Check to see if it's another macro. MacroInfo* otherMacro = preproc.getMacroInfo(tokId); if( otherMacro && otherMacro != macro ) { // Handle the other macro to add it to the LVT under the new name // The recursive call will add it to the LVT if( debugPrint) printf("other macro\n"); handleMacro(tokId, otherMacro); // Get whatever was added in the recursive call // so that we can add it under the new name. varRet = info->lvt->getVarSymbol(idName); info->lvt->getCDecl(idName, &cTypeRet, &cValueRet); } } if( debugPrint ) { if( varRet ) printf("found var %s\n", varRet->cname); if( cTypeRet ) { std::string s = cTypeRet->getName(); printf("found cdecl type %s\n", s.c_str()); } if( cValueRet ) { std::string s = cValueRet->getName(); printf("found cdecl value %s\n", s.c_str()); } } break; } default: break; } if( debugPrint ) { std::string s = id->getName(); const char* kind = NULL; if( varRet ) kind = "var"; if( cTypeRet ) kind = "cdecl type"; if( cValueRet ) kind = "cdecl value"; if( kind ) printf("%s: adding an %s to the lvt\n", s.c_str(), kind); } if( varRet ) { info->lvt->addGlobalVarSymbol(id->getName(), varRet); } if( cTypeRet ) { info->lvt->addGlobalCDecl(id->getName(), cTypeRet); } if( cValueRet ) { info->lvt->addGlobalCDecl(id->getName(), cValueRet); } } static void readMacrosClang(void) { GenInfo* info = gGenInfo; LayeredValueTable *lvt = info->lvt; SET_LINENO(rootModule); // Pre-populate with important INTxx_MIN/MAX from stdint.h // because we have trouble reading these because they have // special stuff to get the right constant width, but they // are all known integer values. lvt->addGlobalVarSymbol("NULL", new_IntSymbol(0, INT_SIZE_64)); // Add INT{8,16,32,64}_{MIN,MAX} and INT_MAX and friends. addMinMax("INT8", 8, true); addMinMax("UINT8", 8, false); addMinMax("INT16", 16, true); addMinMax("UINT16", 16, false); addMinMax("INT32", 32, true); addMinMax("UINT32", 32, false); addMinMax("INT64", 64, true); addMinMax("UINT64", 64, false); //printf("Running ReadMacrosAction\n"); Preprocessor &preproc = info->Clang->getPreprocessor(); // Identify macro-functions and macro-values. // Later, if we see a use of a macro-function, we can // compile it to a static/inline function with args types based an use // how will we know the return type? // expr->getType() stmt->getRetValue()->getType.... // ... add function wrapping macro with wrong type // parse/analyze squelching errors; get the macro expression type; // correct the type and recompile to LLVM // See ClangExpressionParser.cpp in lldb which parses // a C expression from a command line... we need to // do something similar. for(Preprocessor::macro_iterator i = preproc.macro_begin(); i != preproc.macro_end(); i++) { #if HAVE_LLVM_VER >= 37 handleMacro(i->first, i->second.getLatest()->getMacroInfo()); #elif HAVE_LLVM_VER >= 33 handleMacro(i->first, i->second->getMacroInfo()); #else handleMacro(i->first, i->second); #endif } }; // We need a way to: // 1: parse code only // 2: keep the code generator open until we finish generating Chapel code, // since we might need to code generate called functions. // 3: append to the target description // 4: get LLVM values for code generated C things (e.g. types, function ptrs) // // This code is boiler-plate code mostly copied from ModuleBuilder.cpp - see // http://clang.llvm.org/doxygen/ModuleBuilder_8cpp_source.html // Note that ModuleBuilder.cpp is from the clang project and distributed // under a BSD-like license. // // As far as we know, there is no public API for clang that // would allow us the level of control we need over code generation. // The portions that are not copied are delineated by // comments indicating that they are custom to Chapel. class CCodeGenConsumer : public ASTConsumer { private: GenInfo* info; unsigned HandlingTopLevelDecls; SmallVector<CXXMethodDecl *, 8> DeferredInlineMethodDefinitions; struct HandlingTopLevelDeclRAII { CCodeGenConsumer &Self; HandlingTopLevelDeclRAII(CCodeGenConsumer &Self) : Self(Self) { ++Self.HandlingTopLevelDecls; } ~HandlingTopLevelDeclRAII() { if (--Self.HandlingTopLevelDecls == 0) Self.EmitDeferredDecls(); } }; public: CCodeGenConsumer() : ASTConsumer(), info(gGenInfo), HandlingTopLevelDecls(0) { } virtual ~CCodeGenConsumer() { } // these macros help us to copy and paste the code from ModuleBuilder. #define Ctx (info->Ctx) #define Diags (* info->Diags) #define Builder (info->cgBuilder) #define CodeGenOpts (info->codegenOptions) // mostly taken from ModuleBuilder.cpp /// ASTConsumer override: // Initialize - This is called to initialize the consumer, providing // the ASTContext. virtual void Initialize(ASTContext &Context) LLVM_CXX_OVERRIDE { // This does setTargetTriple, setDataLayout, initialize targetData // and cgBuilder. setupClangContext(info, &Context); for (size_t i = 0, e = CodeGenOpts.DependentLibraries.size(); i < e; ++i) HandleDependentLibrary(CodeGenOpts.DependentLibraries[i]); } // ASTConsumer override: // HandleCXXStaticMemberVarInstantiation - Tell the consumer that // this variable has been instantiated. virtual void HandleCXXStaticMemberVarInstantiation(VarDecl *VD) LLVM_CXX_OVERRIDE { // Custom to Chapel if( info->parseOnly ) return; // End custom to Chapel if (Diags.hasErrorOccurred()) return; Builder->HandleCXXStaticMemberVarInstantiation(VD); } // ASTConsumer override: // // HandleTopLevelDecl - Handle the specified top-level declaration. // This is called by the parser to process every top-level Decl*. // // \returns true to continue parsing, or false to abort parsing. virtual bool HandleTopLevelDecl(DeclGroupRef DG) LLVM_CXX_OVERRIDE { if (Diags.hasErrorOccurred()) return true; HandlingTopLevelDeclRAII HandlingDecl(*this); // Make sure to emit all elements of a Decl. for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I) { // Custom to Chapel if(TypedefDecl *td = dyn_cast<TypedefDecl>(*I)) { const clang::Type *ctype= td->getUnderlyingType().getTypePtrOrNull(); //printf("Adding typedef %s\n", td->getNameAsString().c_str()); if(ctype != NULL) { info->lvt->addGlobalCDecl(td); } } else if(FunctionDecl *fd = dyn_cast<FunctionDecl>(*I)) { info->lvt->addGlobalCDecl(fd); } else if(VarDecl *vd = dyn_cast<VarDecl>(*I)) { info->lvt->addGlobalCDecl(vd); } else if(clang::RecordDecl *rd = dyn_cast<RecordDecl>(*I)) { if( rd->getName().size() > 0 ) { // Handle forward declaration for structs info->lvt->addGlobalCDecl(rd); } } if( info->parseOnly ) continue; // End custom to Chapel Builder->EmitTopLevelDecl(*I); } return true; } // ModuleBuilder.cpp has EmitDeferredDecls but that's not in ASTConsumer. void EmitDeferredDecls() { if (DeferredInlineMethodDefinitions.empty()) return; // Emit any deferred inline method definitions. Note that more deferred // methods may be added during this loop, since ASTConsumer callbacks // can be invoked if AST inspection results in declarations being added. HandlingTopLevelDeclRAII HandlingDecl(*this); for (unsigned I = 0; I != DeferredInlineMethodDefinitions.size(); ++I) Builder->EmitTopLevelDecl(DeferredInlineMethodDefinitions[I]); DeferredInlineMethodDefinitions.clear(); } // ASTConsumer override: // \brief This callback is invoked each time an inline method // definition is completed. virtual void HandleInlineMethodDefinition(CXXMethodDecl *D) LLVM_CXX_OVERRIDE { if (Diags.hasErrorOccurred()) return; assert(D->doesThisDeclarationHaveABody()); // We may want to emit this definition. However, that decision might be // based on computing the linkage, and we have to defer that in case we // are inside of something that will change the method's final linkage, // e.g. // typedef struct { // void bar(); // void foo() { bar(); } // } A; DeferredInlineMethodDefinitions.push_back(D); // Provide some coverage mapping even for methods that aren't emitted. // Don't do this for templated classes though, as they may not be // instantiable. if (!D->getParent()->getDescribedClassTemplate()) Builder->AddDeferredUnusedCoverageMapping(D); } // skipped ASTConsumer HandleInterestingDecl // HandleTagDeclRequiredDefinition // HandleCXXImplicitFunctionInstantiation // HandleTopLevelDeclInObjCContainer // HandleImplicitImportDecl // GetASTMutationListener // GetASTDeserializationListener // PrintStats // shouldSkipFunctionBody // ASTConsumer override: // HandleTagDeclDefinition - This callback is invoked each time a TagDecl // to (e.g. struct, union, enum, class) is completed. This allows the // client hack on the type, which can occur at any point in the file // (because these can be defined in declspecs). virtual void HandleTagDeclDefinition(TagDecl *D) LLVM_CXX_OVERRIDE { if (Diags.hasErrorOccurred()) return; // Custom to Chapel - make a note of C globals if(EnumDecl *ed = dyn_cast<EnumDecl>(D)) { // Add the enum type info->lvt->addGlobalCDecl(ed); // Add the enum values for(EnumDecl::enumerator_iterator e = ed->enumerator_begin(); e != ed->enumerator_end(); e++) { info->lvt->addGlobalCDecl(*e); // & goes away with newer clang } } else if(RecordDecl *rd = dyn_cast<RecordDecl>(D)) { const clang::Type *ctype = rd->getTypeForDecl(); if(ctype != NULL && rd->getDefinition() != NULL) { info->lvt->addGlobalCDecl(rd); } } if( info->parseOnly ) return; // End Custom to Chapel Builder->UpdateCompletedType(D); // For MSVC compatibility, treat declarations of static data members with // inline initializers as definitions. if (Ctx->getLangOpts().MSVCCompat) { for (Decl *Member : D->decls()) { if (VarDecl *VD = dyn_cast<VarDecl>(Member)) { if (Ctx->isMSStaticDataMemberInlineDefinition(VD) && Ctx->DeclMustBeEmitted(VD)) { Builder->EmitGlobal(VD); } } } } } // ASTConsumer override: // \brief This callback is invoked the first time each TagDecl is required // to be complete. virtual void HandleTagDeclRequiredDefinition(const TagDecl *D) LLVM_CXX_OVERRIDE { if (Diags.hasErrorOccurred()) return; if( info->parseOnly ) return; if (CodeGen::CGDebugInfo *DI = Builder->getModuleDebugInfo()) if (const RecordDecl *RD = dyn_cast<RecordDecl>(D)) DI->completeRequiredType(RD); } // ASTConsumer override: // HandleTranslationUnit - This method is called when the ASTs for // entire translation unit have been parsed. virtual void HandleTranslationUnit(ASTContext &Context) LLVM_CXX_OVERRIDE { if (Diags.hasErrorOccurred()) { if(Builder) Builder->clear(); return; } /* custom to Chapel - we don't release the builder now, because we want to add a bunch of uses of functions that may not have been codegened yet. Instead, we call this in cleanupClang. if (Builder) Builder->Release(); */ } // ASTConsumer override: // // CompleteTentativeDefinition - Callback invoked at the end of a // translation unit to notify the consumer that the given tentative // definition should be completed. // // The variable declaration // itself will be a tentative definition. If it had an incomplete // array type, its type will have already been changed to an array // of size 1. However, the declaration remains a tentative // definition and has not been modified by the introduction of an // implicit zero initializer. virtual void CompleteTentativeDefinition(VarDecl *D) LLVM_CXX_OVERRIDE { if (Diags.hasErrorOccurred()) return; // Custom to Chapel if( info->parseOnly ) return; // End Custom to Chapel Builder->EmitTentativeDefinition(D); } // ASTConsumer override: // \brief Callback involved at the end of a translation unit to // notify the consumer that a vtable for the given C++ class is // required. // // \param RD The class whose vtable was used. virtual void HandleVTable(CXXRecordDecl *RD #if HAVE_LLVM_VER < 37 , bool DefinitionRequired #endif ) LLVM_CXX_OVERRIDE { if (Diags.hasErrorOccurred()) return; // Custom to Chapel if( info->parseOnly ) return; // End Custom to Chapel Builder->EmitVTable(RD #if HAVE_LLVM_VER < 37 , DefinitionRequired #endif ); } // ASTConsumer override: // // \brief Handle a pragma that appends to Linker Options. Currently // this only exists to support Microsoft's #pragma comment(linker, // "/foo"). void HandleLinkerOptionPragma(llvm::StringRef Opts) override { Builder->AppendLinkerOptions(Opts); } // HandleLinkerOptionPragma // ASTConsumer override: // \brief Handle a pragma that emits a mismatch identifier and value to // the object file for the linker to work with. Currently, this only // exists to support Microsoft's #pragma detect_mismatch. virtual void HandleDetectMismatch(llvm::StringRef Name, llvm::StringRef Value) LLVM_CXX_OVERRIDE { Builder->AddDetectMismatch(Name, Value); } // ASTConsumer override: // \brief Handle a dependent library created by a pragma in the source. /// Currently this only exists to support Microsoft's /// #pragma comment(lib, "/foo"). virtual void HandleDependentLibrary(llvm::StringRef Lib) LLVM_CXX_OVERRIDE { Builder->AddDependentLib(Lib); } // undefine macros we created to help with ModuleBuilder #undef Ctx #undef Diags #undef Builder #undef CodeGenOpts }; #if HAVE_LLVM_VER >= 36 #define CREATE_AST_CONSUMER_RETURN_TYPE std::unique_ptr<ASTConsumer> #else #define CREATE_AST_CONSUMER_RETURN_TYPE ASTConsumer* #endif class CCodeGenAction : public ASTFrontendAction { public: CCodeGenAction() { } protected: virtual CREATE_AST_CONSUMER_RETURN_TYPE CreateASTConsumer( CompilerInstance &CI, StringRef InFile); }; CREATE_AST_CONSUMER_RETURN_TYPE CCodeGenAction::CreateASTConsumer( CompilerInstance &CI, StringRef InFile) { #if HAVE_LLVM_VER >= 36 return std::unique_ptr<ASTConsumer>(new CCodeGenConsumer()); #else return new CCodeGenConsumer(); #endif }; static void finishClang(GenInfo* info){ if( info->cgBuilder ) { info->cgBuilder->Release(); } info->Diags.reset(); info->DiagID.reset(); } static void deleteClang(GenInfo* info){ if( info->cgBuilder ) { delete info->cgBuilder; info->cgBuilder = NULL; } delete info->targetData; delete info->Clang; info->Clang = NULL; delete info->cgAction; info->cgAction = NULL; } static void cleanupClang(GenInfo* info) { finishClang(info); deleteClang(info); } void setupClang(GenInfo* info, std::string mainFile) { std::string clangexe = info->clangCC; std::vector<const char*> clangArgs; for( size_t i = 0; i < info->clangCCArgs.size(); ++i ) { clangArgs.push_back(info->clangCCArgs[i].c_str()); } for( size_t i = 0; i < info->clangLDArgs.size(); ++i ) { clangArgs.push_back(info->clangLDArgs[i].c_str()); } for( size_t i = 0; i < info->clangOtherArgs.size(); ++i ) { clangArgs.push_back(info->clangOtherArgs[i].c_str()); } if (llvmCodegen) { clangArgs.push_back("-emit-llvm"); } //clangArgs.push_back("-c"); clangArgs.push_back(mainFile.c_str()); // chpl - always compile rt file info->diagOptions = new DiagnosticOptions(); info->DiagClient= new TextDiagnosticPrinter(errs(),&*info->diagOptions); info->DiagID = new DiagnosticIDs(); #if HAVE_LLVM_VER >= 32 info->Diags = new DiagnosticsEngine( info->DiagID, &*info->diagOptions, info->DiagClient); #else info->Diags = new DiagnosticsEngine(info->DiagID, info->DiagClient); #endif CompilerInvocation* CI = createInvocationFromCommandLine(clangArgs, info->Diags); // Get the codegen options from the clang command line. info->codegenOptions = CI->getCodeGenOpts(); // if --fast is given, we should be at least at -O3. if(fFastFlag && info->codegenOptions.OptimizationLevel < 3) { info->codegenOptions.OptimizationLevel = 3; } { // Make sure we include clang's internal header dir #if HAVE_LLVM_VER >= 34 SmallString<128> P; SmallString<128> P2; // avoids a valgrind overlapping memcpy P = clangexe; // Remove /clang from foo/bin/clang P2 = sys::path::parent_path(P); // Remove /bin from foo/bin P = sys::path::parent_path(P2); if( ! P.equals("") ) { // Get foo/lib/clang/<version>/ sys::path::append(P, "lib"); sys::path::append(P, "clang"); sys::path::append(P, CLANG_VERSION_STRING); } CI->getHeaderSearchOpts().ResourceDir = P.str(); sys::path::append(P, "include"); #else sys::Path P(clangexe); if (!P.isEmpty()) { P.eraseComponent(); // Remove /clang from foo/bin/clang P.eraseComponent(); // Remove /bin from foo/bin // Get foo/lib/clang/<version>/ P.appendComponent("lib"); P.appendComponent("clang"); P.appendComponent(CLANG_VERSION_STRING); } CI->getHeaderSearchOpts().ResourceDir = P.str(); sys::Path P2(P); P.appendComponent("include"); #endif #if HAVE_LLVM_VER >= 33 CI->getHeaderSearchOpts().AddPath( P.str(), frontend::System,false, false); #else CI->getHeaderSearchOpts().AddPath( P.str(), frontend::System,false, false, false, true, false); #endif } // Create a compiler instance to handle the actual work. info->Clang = new CompilerInstance(); info->Clang->setInvocation(CI); // Save the TargetOptions and LangOptions since these // are used during machine code generation. info->clangTargetOptions = info->Clang->getTargetOpts(); info->clangLangOptions = info->Clang->getLangOpts(); // Create the compilers actual diagnostics engine. // Create the compilers actual diagnostics engine. #if HAVE_LLVM_VER >= 33 info->Clang->createDiagnostics(); #else info->Clang->createDiagnostics(int(clangArgs.size()),&clangArgs[0]); #endif if (!info->Clang->hasDiagnostics()) INT_FATAL("Bad diagnostics from clang"); } void finishCodegenLLVM() { GenInfo* info = gGenInfo; // Codegen extra stuff for global-to-wide optimization. setupForGlobalToWide(); // Finish up our cleanup optimizers... info->FPM_postgen->doFinalization(); // We don't need our postgen function pass manager anymore. delete info->FPM_postgen; info->FPM_postgen = NULL; // Now finish any Clang code generation. finishClang(info); if(debug_info)debug_info->finalize(); // Verify the LLVM module. if( developer ) { bool problems; #if HAVE_LLVM_VER >= 35 problems = verifyModule(*info->module, &errs()); //problems = false; #else problems = verifyModule(*info->module, PrintMessageAction); #endif if(problems) { INT_FATAL("LLVM module verification failed"); } } } void prepareCodegenLLVM() { GenInfo *info = gGenInfo; LEGACY_FUNCTION_PASS_MANAGER *fpm = new LEGACY_FUNCTION_PASS_MANAGER(info->module); PassManagerBuilder PMBuilder; // Set up the optimizer pipeline. // Start with registering info about how the // target lays out data structures. #if HAVE_LLVM_VER >= 37 // We already set the data layout in setupClangContext // don't need to do anything else. #elif HAVE_LLVM_VER >= 36 // We already set the data layout in setupClangContext fpm->add(new DataLayoutPass()); #elif HAVE_LLVM_VER >= 35 fpm->add(new DataLayoutPass(info->module)); #else fpm->add(new DataLayout(info->module)); #endif if( fFastFlag ) { PMBuilder.OptLevel = 2; PMBuilder.populateFunctionPassManager(*fpm); } info->FPM_postgen = fpm; info->FPM_postgen->doInitialization(); } #if HAVE_LLVM_VER >= 33 static void handleErrorLLVM(void* user_data, const std::string& reason, bool gen_crash_diag) #else static void handleErrorLLVM(void* user_data, const std::string& reason) #endif { INT_FATAL("llvm fatal error: %s", reason.c_str()); } struct ExternBlockInfo { GenInfo* gen_info; fileinfo file; ExternBlockInfo() : gen_info(NULL), file() { } ~ExternBlockInfo() { } }; typedef std::set<ModuleSymbol*> module_set_t; typedef module_set_t::iterator module_set_iterator_t; module_set_t gModulesWithExternBlocks; bool lookupInExternBlock(ModuleSymbol* module, const char* name, clang::TypeDecl** cTypeOut, clang::ValueDecl** cValueOut, ChapelType** chplTypeOut) { if( ! module->extern_info ) return false; module->extern_info->gen_info->lvt->getCDecl(name, cTypeOut, cValueOut); VarSymbol* var = module->extern_info->gen_info->lvt->getVarSymbol(name); if( var ) *chplTypeOut = var->typeInfo(); return ( (*cTypeOut) || (*cValueOut) || (*chplTypeOut) ); } bool alreadyConvertedExtern(ModuleSymbol* module, const char* name) { return module->extern_info->gen_info->lvt->isAlreadyInChapelAST(name); } bool setAlreadyConvertedExtern(ModuleSymbol* module, const char* name) { return module->extern_info->gen_info->lvt->markAddedToChapelAST(name); } void runClang(const char* just_parse_filename) { static bool is_installed_fatal_error_handler = false; /* TODO -- note that clang/examples/clang-interpreter/main.cpp includes an example for getting the executable path, so that we could automatically set CHPL_HOME. */ std::string home(CHPL_HOME); std::string compileline = home + "/util/config/compileline"; compileline += " COMP_GEN_WARN="; compileline += istr(ccwarnings); compileline += " COMP_GEN_DEBUG="; compileline += istr(debugCCode); compileline += " COMP_GEN_OPT="; compileline += istr(optimizeCCode); compileline += " COMP_GEN_SPECIALIZE="; compileline += istr(specializeCCode); compileline += " COMP_GEN_FLOAT_OPT="; compileline += istr(ffloatOpt); std::string readargsfrom; if( !llvmCodegen && just_parse_filename ) { // We're handling an extern block and not using the LLVM backend. // Don't ask for any compiler-specific C flags. readargsfrom = compileline + " --llvm" " --clang" " --clang-sysroot-arguments" " --includes-and-defines"; } else { // We're parsing extern blocks AND any parts of the runtime // in order to prepare for an --llvm compilation. // Use compiler-specific flags for clang-included. readargsfrom = compileline + " --llvm" " --clang" " --clang-sysroot-arguments" " --cflags" " --includes-and-defines"; } std::vector<std::string> args; std::vector<std::string> clangCCArgs; std::vector<std::string> clangLDArgs; std::vector<std::string> clangOtherArgs; std::string clangCC, clangCXX; // Gather information from readargsfrom into clangArgs. readArgsFromCommand(readargsfrom.c_str(), args); if( args.size() < 2 ) USR_FATAL("Could not find runtime dependencies for --llvm build"); clangCC = args[0]; clangCXX = args[1]; // Note that these CC arguments will be saved in info->clangCCArgs // and will be used when compiling C files as well. for( size_t i = 2; i < args.size(); ++i ) { clangCCArgs.push_back(args[i]); } forv_Vec(const char*, dirName, incDirs) { clangCCArgs.push_back(std::string("-I") + dirName); } clangCCArgs.push_back(std::string("-I") + getIntermediateDirName()); //split ccflags by spaces std::stringstream ccArgsStream(ccflags); std::string ccArg; while(ccArgsStream >> ccArg) clangCCArgs.push_back(ccArg); clangCCArgs.push_back("-pthread"); // libFlag and ldflags are handled during linking later. clangCCArgs.push_back("-DCHPL_GEN_CODE"); // Always include sys_basic because it might change the // behaviour of macros! clangOtherArgs.push_back("-include"); clangOtherArgs.push_back("sys_basic.h"); if (!just_parse_filename) { // Running clang to compile all runtime and extern blocks // Include header files from the command line. { int filenum = 0; while (const char* inputFilename = nthFilename(filenum++)) { if (isCHeader(inputFilename)) { clangOtherArgs.push_back("-include"); clangOtherArgs.push_back(inputFilename); } } } // Include extern C blocks if( externC && gAllExternCode.filename ) { clangOtherArgs.push_back("-include"); clangOtherArgs.push_back(gAllExternCode.filename); } } else { // Just running clang to parse the extern blocks for this module. clangOtherArgs.push_back("-include"); clangOtherArgs.push_back(just_parse_filename); } if( printSystemCommands ) { printf("<internal clang> "); for( size_t i = 0; i < clangCCArgs.size(); i++ ) { printf("%s ", clangCCArgs[i].c_str()); } for( size_t i = 0; i < clangOtherArgs.size(); i++ ) { printf("%s ", clangOtherArgs[i].c_str()); } printf("\n"); } // Initialize gGenInfo // Toggle LLVM code generation in our clang run; // turn it off if we just wanted to parse some C. gGenInfo = new GenInfo(clangCC, clangCXX, compileline, clangCCArgs, clangLDArgs, clangOtherArgs, just_parse_filename != NULL); if( llvmCodegen || externC ) { GenInfo *info = gGenInfo; // Install an LLVM Fatal Error Handler. if (!is_installed_fatal_error_handler) { is_installed_fatal_error_handler = true; install_fatal_error_handler(handleErrorLLVM); } // Run the Start Generation action // Now initialize a code generator... // this will enable us to ask for addresses of static (inline) functions // and cause them to be emitted eventually. // CCodeGenAction is defined above. It traverses the C AST // and does the code generation. info->cgAction = new CCodeGenAction(); if (!info->Clang->ExecuteAction(*info->cgAction)) { if (just_parse_filename) { USR_FATAL("error running clang on extern block"); } else { USR_FATAL("error running clang during code generation"); } } if( ! info->parseOnly ) { // This seems to be needed, even though it is strange. // (otherwise we segfault in info->builder->CreateGlobalString) // Some IRBuilder methods, codegenning a string, // need a basic block in order to get to the module // so we create a dummy function to code generate into llvm::Type * voidTy = llvm::Type::getVoidTy(info->module->getContext()); std::vector<llvm::Type*> args; llvm::FunctionType * FT = llvm::FunctionType::get(voidTy, args, false); Function * F = Function::Create(FT, Function::InternalLinkage, "chplDummyFunction", info->module); llvm::BasicBlock *block = llvm::BasicBlock::Create(info->module->getContext(), "entry", F); info->builder->SetInsertPoint(block); } // read macros. May call IRBuilder methods to codegen a string, // so needs to happen after we set the insert point. readMacrosClang(); if( ! info->parseOnly ) { info->builder->CreateRetVoid(); } } } static void saveExternBlock(ModuleSymbol* module, const char* extern_code) { if( ! gAllExternCode.filename ) { openCFile(&gAllExternCode, "extern-code", "c"); INT_ASSERT(gAllExternCode.fptr); // Allow code in extern block to use malloc/calloc/realloc/free // Note though that e.g. strdup or other library routines that // allocate memory might still be an issue... fprintf(gAllExternCode.fptr, "#include \"chpl-mem-no-warning-macros.h\"\n"); } if( ! module->extern_info ) { // Figure out what file to place the C code into. module->extern_info = new ExternBlockInfo(); const char* name = astr("extern_block_", module->cname); openCFile(&module->extern_info->file, name, "c"); // Could put #ifndef/define/endif wrapper start here. } FILE* f = module->extern_info->file.fptr; INT_ASSERT(f); // Append the C code to that file. fputs(extern_code, f); // Always make sure it ends in a close semi (solves errors) fputs("\n;\n", f); // Add this module to the set of modules needing extern compilation. std::pair<module_set_iterator_t,bool> already_there; already_there = gModulesWithExternBlocks.insert(module); if( already_there.second ) { // A new element was added to the map -> // first time we have worked with this module. // Add a #include of this module's extern block code to the // global extern code file. fprintf(gAllExternCode.fptr, "#include \"%s\"\n", module->extern_info->file.filename); } } void readExternC(void) { // Handle extern C blocks. forv_Vec(ExternBlockStmt, eb, gExternBlockStmts) { // Figure out the parent module symbol. ModuleSymbol* module = eb->getModule(); saveExternBlock(module, eb->c_code); } // Close extern_c_file. if( gAllExternCode.fptr ) closefile(&gAllExternCode); // Close any extern files for any modules we had generated code for. module_set_iterator_t it; for( it = gModulesWithExternBlocks.begin(); it != gModulesWithExternBlocks.end(); ++it ) { ModuleSymbol* module = *it; INT_ASSERT(module->extern_info); // Could put #ifndef/define/endif wrapper end here. closefile(&module->extern_info->file); // Now parse the extern C code for that module. runClang(module->extern_info->file.filename); // Now swap what went into the global layered value table // into the module's own layered value table. module->extern_info->gen_info = gGenInfo; gGenInfo = NULL; } } void cleanupExternC(void) { module_set_iterator_t it; for( it = gModulesWithExternBlocks.begin(); it != gModulesWithExternBlocks.end(); ++it ) { ModuleSymbol* module = *it; INT_ASSERT(module->extern_info); cleanupClang(module->extern_info->gen_info); delete module->extern_info->gen_info; delete module->extern_info; // Remove all ExternBlockStmts from this module. forv_Vec(ExternBlockStmt, eb, gExternBlockStmts) { eb->remove(); } gExternBlockStmts.clear(); } } llvm::Function* getFunctionLLVM(const char* name) { GenInfo* info = gGenInfo; Function* fn = info->module->getFunction(name); if( fn ) return fn; GenRet got = info->lvt->getValue(name); if( got.val ) { fn = cast<Function>(got.val); return fn; } return NULL; } llvm::Type* getTypeLLVM(const char* name) { GenInfo* info = gGenInfo; llvm::Type* t = info->module->getTypeByName(name); if( t ) return t; t = info->lvt->getType(name); if( t ) return t; return NULL; } // should support TypedefDecl,EnumDecl,RecordDecl llvm::Type* codegenCType(const TypeDecl* td) { GenInfo* info = gGenInfo; CodeGen::CodeGenTypes & cdt = info->cgBuilder->getTypes(); QualType qType; // handle TypedefDecl if( const TypedefNameDecl* tnd = dyn_cast<TypedefNameDecl>(td) ) { qType = tnd->getCanonicalDecl()->getUnderlyingType(); // had const Type *ctype = td->getUnderlyingType().getTypePtrOrNull(); //could also do: // qType = // tnd->getCanonicalDecl()->getTypeForDecl()->getCanonicalTypeInternal(); } else if( const EnumDecl* ed = dyn_cast<EnumDecl>(td) ) { qType = ed->getCanonicalDecl()->getIntegerType(); // could also use getPromotionType() //could also do: // qType = // tnd->getCanonicalDecl()->getTypeForDecl()->getCanonicalTypeInternal(); } else if( const RecordDecl* rd = dyn_cast<RecordDecl>(td) ) { RecordDecl *def = rd->getDefinition(); INT_ASSERT(def); qType=def->getCanonicalDecl()->getTypeForDecl()->getCanonicalTypeInternal(); } else { INT_FATAL("Unknown clang type declaration"); } return cdt.ConvertTypeForMem(qType); } // should support FunctionDecl,VarDecl,EnumConstantDecl GenRet codegenCValue(const ValueDecl *vd) { GenInfo* info = gGenInfo; GenRet ret; if( info->cfile ) { ret.c = vd->getName(); return ret; } if(const FunctionDecl *fd = dyn_cast<FunctionDecl>(vd)) { // It's a function decl. ret.val = info->cgBuilder->GetAddrOfFunction(fd); ret.isLVPtr = GEN_VAL; } else if(const VarDecl *vard = dyn_cast<VarDecl>(vd)) { // It's a (global) variable decl ret.val = info->cgBuilder->GetAddrOfGlobalVar(vard); ret.isLVPtr = GEN_PTR; } else if(const EnumConstantDecl *ed = dyn_cast<EnumConstantDecl>(vd)) { // It's a constant enum value APInt v = ed->getInitVal(); ret.isUnsigned = ! ed->getType()->hasSignedIntegerRepresentation(); CodeGen::CodeGenTypes & cdt = info->cgBuilder->getTypes(); llvm::Type* type = cdt.ConvertTypeForMem(ed->getType()); ret.val = ConstantInt::get(type, v); ret.isLVPtr = GEN_VAL; } else { INT_FATAL("Unknown clang value declaration"); } return ret; } LayeredValueTable::LayeredValueTable(){ layers.push_front(map_type()); } void LayeredValueTable::addLayer(){ layers.push_front(map_type()); } void LayeredValueTable::removeLayer(){ if(layers.size() != 1) { layers.pop_front(); } } void LayeredValueTable::addValue( StringRef name, Value *value, uint8_t isLVPtr, bool isUnsigned) { Storage store; store.u.value = value; store.isLVPtr = isLVPtr; store.isUnsigned = isUnsigned; (layers.front())[name] = store; } void LayeredValueTable::addGlobalValue( StringRef name, Value *value, uint8_t isLVPtr, bool isUnsigned) { Storage store; store.u.value = value; store.isLVPtr = isLVPtr; store.isUnsigned = isUnsigned; (layers.back())[name] = store; } void LayeredValueTable::addGlobalValue(StringRef name, GenRet gend) { addGlobalValue(name, gend.val, gend.isLVPtr, gend.isUnsigned); } void LayeredValueTable::addGlobalType(StringRef name, llvm::Type *type) { Storage store; store.u.type = type; /*fprintf(stderr, "Adding global type %s ", name.str().c_str()); type->dump(); fprintf(stderr, "\n"); */ (layers.back())[name] = store; } void LayeredValueTable::addGlobalCDecl(NamedDecl* cdecl) { addGlobalCDecl(cdecl->getName(), cdecl); // Also file structs under 'struct struct_name' if(isa<RecordDecl>(cdecl)) { std::string sname = "struct "; sname += cdecl->getName(); addGlobalCDecl(sname, cdecl); } } void LayeredValueTable::addGlobalCDecl(StringRef name, NamedDecl* cdecl) { if(RecordDecl *rd = dyn_cast<RecordDecl>(cdecl)) { // For record decls, always use the completed definition // if it is available. // E.g., we might visit decls in this order: // struct stat { ... } // struct stat; RecordDecl* completed = rd->getDefinition(); if (completed) { // Use the completed version below. cdecl = completed; } } // Add to an existing Storage record, so that it can store // both a type and a value (e.g. struct stat and function stat). Storage & store = (layers.back())[name]; if (isa<TypeDecl>(cdecl)) store.u.cTypeDecl = cast<TypeDecl>(cdecl); if (isa<ValueDecl>(cdecl)) store.u.cValueDecl = cast<ValueDecl>(cdecl); } void LayeredValueTable::addGlobalVarSymbol(llvm::StringRef name, VarSymbol* var) { Storage store; store.u.chplVar = var; (layers.back())[name] = store; } void LayeredValueTable::addBlock(StringRef name, llvm::BasicBlock *block) { Storage store; store.u.block = block; layer_iterator blockLayer = --layers.end(); if(layers.size() > 1) { blockLayer = --blockLayer; } (*blockLayer)[name] = store; } GenRet LayeredValueTable::getValue(StringRef name) { if(Storage *store = get(name)) { if( store->u.value ) { INT_ASSERT(isa<Value>(store->u.value)); GenRet ret; ret.val = store->u.value; ret.isLVPtr = store->isLVPtr; ret.isUnsigned = store->isUnsigned; return ret; } if( store->u.cValueDecl ) { INT_ASSERT(isa<ValueDecl>(store->u.cValueDecl)); // we have a clang value decl. // maybe FunctionDecl,VarDecl,EnumConstantDecl // Convert it to an LLVM value // should support FunctionDecl,VarDecl,EnumConstantDecl return codegenCValue(store->u.cValueDecl); } if( store->u.chplVar && isVarSymbol(store->u.chplVar) ) { VarSymbol* var = store->u.chplVar; GenRet ret = var; // code generate it! return ret; } } GenRet ret; return ret; } llvm::BasicBlock *LayeredValueTable::getBlock(StringRef name) { if(Storage *store = get(name)) { if( store->u.block && isa<llvm::BasicBlock>(store->u.block) ) return store->u.block; } return NULL; } llvm::Type *LayeredValueTable::getType(StringRef name) { if(Storage *store = get(name)) { if( store->u.type ) { INT_ASSERT(isa<llvm::Type>(store->u.type)); return store->u.type; } if( store->u.cTypeDecl ) { INT_ASSERT(isa<TypeDecl>(store->u.cTypeDecl)); // we have a clang type decl. // maybe TypedefDecl,EnumDecl,RecordDecl // Convert it to an LLVM type. return codegenCType(store->u.cTypeDecl); } } return NULL; } // Returns a type or a name decl for a given name // Note that C can have a function and a type sharing the same name // (e.g. stat/struct stat). // Sets the output arguments to NULL if a type/value was not found. // Either output argument can be NULL. void LayeredValueTable::getCDecl(StringRef name, TypeDecl** cTypeOut, ValueDecl** cValueOut) { if (cValueOut) *cValueOut = NULL; if (cTypeOut) *cTypeOut = NULL; if(Storage *store = get(name)) { if( store->u.cValueDecl ) { INT_ASSERT(isa<ValueDecl>(store->u.cValueDecl)); // we have a clang value decl. // maybe FunctionDecl,VarDecl,EnumConstantDecl if (cValueOut) *cValueOut = store->u.cValueDecl; } if( store->u.cTypeDecl ) { INT_ASSERT(isa<TypeDecl>(store->u.cTypeDecl)); // we have a clang type decl. // maybe TypedefDecl,EnumDecl,RecordDecl if (cTypeOut) *cTypeOut = store->u.cTypeDecl; } } } VarSymbol* LayeredValueTable::getVarSymbol(StringRef name) { if(Storage *store = get(name)) { if( store->u.chplVar && isVarSymbol(store->u.chplVar) ) { // we have a Chapel Var Symbol. // maybe immediate number or string, possibly variable reference. // These come from macros. return store->u.chplVar; } } return NULL; } LayeredValueTable::Storage* LayeredValueTable::get(StringRef name) { for(layer_iterator i = layers.begin(); i != layers.end(); ++i) { value_iterator j = i->find(name); if(j != i->end()) { return &j->second; } } return NULL; } bool LayeredValueTable::isAlreadyInChapelAST(llvm::StringRef name) { if(Storage *store = get(name)) { return store->addedToChapelAST; } return false; } bool LayeredValueTable::markAddedToChapelAST(llvm::StringRef name) { if(Storage *store = get(name)) { if( store->addedToChapelAST ) return false; store->addedToChapelAST = true; return true; } else { // Otherwise, make a new entry. Storage toStore; toStore.addedToChapelAST = true; (layers.back())[name] = toStore; return true; } } void LayeredValueTable::swap(LayeredValueTable* other) { this->layers.swap(other->layers); } int getCRecordMemberGEP(const char* typeName, const char* fieldName) { GenInfo* info = gGenInfo; TypeDecl* d = NULL; int ret; info->lvt->getCDecl(typeName, &d, NULL); INT_ASSERT(d); if( isa<TypedefDecl>(d) ) { TypedefDecl* td = cast<TypedefDecl>(d); const clang::Type* t = td->getUnderlyingType().getTypePtr(); while( t->isPointerType() ) { t = t->getPointeeType().getTypePtr(); } const RecordType* rt = t->getAsStructureType(); INT_ASSERT(rt); d = rt->getDecl(); // getAsUnionType also available, but we don't support extern unions } INT_ASSERT(isa<RecordDecl>(d)); RecordDecl* rec = cast<RecordDecl>(d); // Find the field decl. RecordDecl::field_iterator it; FieldDecl* field = NULL; for( it = rec->field_begin(); it != rec->field_end(); ++it ) { if( fieldName == it->getName() ) { field = *it; break; } } INT_ASSERT(field); ret=info->cgBuilder->getTypes().getCGRecordLayout(rec).getLLVMFieldNo(field); return ret; } bool isBuiltinExternCFunction(const char* cname) { if( 0 == strcmp(cname, "sizeof") ) return true; else return false; } static void addAggregateGlobalOps(const PassManagerBuilder &Builder, LEGACY_PASS_MANAGER &PM) { GenInfo* info = gGenInfo; if( fLLVMWideOpt ) { PM.add(createAggregateGlobalOpsOptPass(info->globalToWideInfo.globalSpace)); } } static void addGlobalToWide(const PassManagerBuilder &Builder, LEGACY_PASS_MANAGER &PM) { GenInfo* info = gGenInfo; if( fLLVMWideOpt ) { PM.add(createGlobalToWide(&info->globalToWideInfo, info->targetLayout)); } } // If we're using the LLVM wide optimizations, we have to add // some functions to call put/get into the Chapel runtime layers // (the optimization is meant to be portable to other languages) static void setupForGlobalToWide(void) { if( ! fLLVMWideOpt ) return; GenInfo* ginfo = gGenInfo; GlobalToWideInfo* info = &ginfo->globalToWideInfo; info->localeIdType = ginfo->lvt->getType("chpl_localeID_t"); assert(info->localeIdType); info->nodeIdType = ginfo->lvt->getType("c_nodeid_t"); assert(info->nodeIdType); info->addrFn = getFunctionLLVM("chpl_wide_ptr_get_address"); INT_ASSERT(info->addrFn); info->locFn = getFunctionLLVM("chpl_wide_ptr_read_localeID"); INT_ASSERT(info->locFn); info->nodeFn = getFunctionLLVM("chpl_wide_ptr_get_node"); INT_ASSERT(info->nodeFn); info->makeFn = getFunctionLLVM("chpl_return_wide_ptr_loc_ptr"); INT_ASSERT(info->makeFn); info->getFn = getFunctionLLVM("chpl_gen_comm_get_ctl"); INT_ASSERT(info->getFn); info->putFn = getFunctionLLVM("chpl_gen_comm_put_ctl"); INT_ASSERT(info->putFn); info->getPutFn = getFunctionLLVM("chpl_gen_comm_getput"); INT_ASSERT(info->getPutFn); info->memsetFn = getFunctionLLVM("chpl_gen_comm_memset"); INT_ASSERT(info->memsetFn); // Call these functions in a dummy externally visible // function which GlobalToWide should remove. We need to do that // in order to prevent the functions from being removed for // not having references when they are inline/internal linkage. // Our function here just returns a pointer to the i'th (i is the argument) // such function - and since it is marked externally visible, there // is no way that the compiler can completely remove the needed // runtime functions. const char* dummy = "chpl_wide_opt_dummy"; if( getFunctionLLVM(dummy) ) INT_FATAL("dummy function already exists"); llvm::Type* retType = llvm::Type::getInt8PtrTy(ginfo->module->getContext()); llvm::Type* argType = llvm::Type::getInt64Ty(ginfo->module->getContext()); llvm::Value* fval = ginfo->module->getOrInsertFunction( dummy, retType, argType, NULL); llvm::Function* fn = llvm::dyn_cast<llvm::Function>(fval); // Mark the function as external so that it will not be removed fn->setLinkage(llvm::GlobalValue::ExternalLinkage); llvm::BasicBlock* block = llvm::BasicBlock::Create(ginfo->module->getContext(), "entry", fn); ginfo->builder->SetInsertPoint(block); llvm::Constant* fns[] = {info->addrFn, info->locFn, info->nodeFn, info->makeFn, info->getFn, info->putFn, info->getPutFn, info->memsetFn, NULL}; llvm::Value* ret = llvm::Constant::getNullValue(retType); llvm::Function::arg_iterator args = fn->arg_begin(); llvm::Value* arg = args++; for( int i = 0; fns[i]; i++ ) { llvm::Constant* f = fns[i]; llvm::Value* ptr = ginfo->builder->CreatePointerCast(f, retType); llvm::Value* id = llvm::ConstantInt::get(argType, i); llvm::Value* eq = ginfo->builder->CreateICmpEQ(arg, id); ret = ginfo->builder->CreateSelect(eq, ptr, ret); } ginfo->builder->CreateRet(ret); #if HAVE_LLVM_VER >= 35 llvm::verifyFunction(*fn, &errs()); #endif info->preservingFn = fn; } void makeBinaryLLVM(void) { #if HAVE_LLVM_VER >= 36 std::error_code errorInfo; #else std::string errorInfo; #endif GenInfo* info = gGenInfo; std::string moduleFilename = genIntermediateFilename("chpl__module.bc"); std::string preOptFilename = genIntermediateFilename("chpl__module-nopt.bc"); if( saveCDir[0] != '\0' ) { // Save the generated LLVM before optimization. tool_output_file output (preOptFilename.c_str(), errorInfo, #if HAVE_LLVM_VER >= 34 sys::fs::F_None #else raw_fd_ostream::F_Binary #endif ); WriteBitcodeToFile(info->module, output.os()); output.keep(); output.os().flush(); } tool_output_file output (moduleFilename.c_str(), errorInfo, #if HAVE_LLVM_VER >= 34 sys::fs::F_None #else raw_fd_ostream::F_Binary #endif ); static bool addedGlobalExts = false; if( ! addedGlobalExts ) { // Add the Global to Wide optimization if necessary. PassManagerBuilder::addGlobalExtension(PassManagerBuilder::EP_ScalarOptimizerLate, addAggregateGlobalOps); PassManagerBuilder::addGlobalExtension(PassManagerBuilder::EP_ScalarOptimizerLate, addGlobalToWide); PassManagerBuilder::addGlobalExtension(PassManagerBuilder::EP_EnabledOnOptLevel0, addGlobalToWide); addedGlobalExts = true; } EmitBackendOutput(*info->Diags, info->codegenOptions, info->clangTargetOptions, info->clangLangOptions, #if HAVE_LLVM_VER >= 35 info->Ctx->getTargetInfo().getTargetDescription(), #endif info->module, Backend_EmitBC, &output.os()); output.keep(); output.os().flush(); //finishClang is before the call to the debug finalize deleteClang(info); std::string options = ""; std::string home(CHPL_HOME); std::string compileline = info->compileline; compileline += " --llvm" " --clang" " --main.o" " --clang-sysroot-arguments" " --libraries"; std::vector<std::string> args; readArgsFromCommand(compileline.c_str(), args); INT_ASSERT(args.size() >= 1); std::string clangCC = args[0]; std::string clangCXX = args[1]; std::string maino = args[2]; std::vector<std::string> dotOFiles; // Gather C flags for compiling C files. std::string cargs; for( size_t i = 0; i < info->clangCCArgs.size(); ++i ) { cargs += " "; cargs += info->clangCCArgs[i]; } // Compile any C files. { // Start with configuration settings const char* inputFilename = gChplCompilationConfig.pathname; const char* objFilename = objectFileForCFile(inputFilename); mysystem(astr(clangCC.c_str(), " -c -o ", objFilename, " ", inputFilename, cargs.c_str()), "Compile C File"); dotOFiles.push_back(objFilename); } int filenum = 0; while (const char* inputFilename = nthFilename(filenum++)) { if (isCSource(inputFilename)) { const char* objFilename = objectFileForCFile(inputFilename); mysystem(astr(clangCC.c_str(), " -c -o ", objFilename, " ", inputFilename, cargs.c_str()), "Compile C File"); dotOFiles.push_back(objFilename); } else if( isObjFile(inputFilename) ) { dotOFiles.push_back(inputFilename); } } // Start linker options with C args // This is important to get e.g. -O3 -march=native // since with LLVM we are doing link-time optimization. // We know it's OK to include -I (e.g.) since we're calling // clang++ to link so that it can optimize the .bc files. options = cargs; if(debugCCode) { options += " -g"; } options += " "; options += ldflags; options += " -pthread"; // Now, if we're doing a multilocale build, we have to make a launcher. // For this reason, we create a makefile. codegen_makefile // also gives us the name of the temporary place to save // the generated program. fileinfo mainfile; mainfile.filename = "chpl__module.bc"; mainfile.pathname = moduleFilename.c_str(); const char* tmpbinname = NULL; codegen_makefile(&mainfile, &tmpbinname, true); INT_ASSERT(tmpbinname); // Run the linker. We always use clang++ because some third-party // libraries are written in C++. With the C backend, this switcheroo // is accomplished in the Makefiles somewhere std::string command = clangCXX + " " + options + " " + moduleFilename + " " + maino + " -o " + tmpbinname; for( size_t i = 0; i < dotOFiles.size(); i++ ) { command += " "; command += dotOFiles[i]; } // 0 is clang, 1 is clang++, 2 is main.o for(size_t i = 3; i < args.size(); ++i) { command += " "; command += args[i]; } // Put user-requested libraries at the end of the compile line, // they should at least be after the .o files and should be in // order where libraries depend on libraries to their right. for (int i=0; i<numLibFlags; i++) { command += " "; command += libFlag[i]; } if( printSystemCommands ) { printf("%s\n", command.c_str()); } mysystem(command.c_str(), "Make Binary - Linking"); // Now run the makefile to move from tmpbinname to the proper program // name and to build a launcher (if necessary). const char* makeflags = printSystemCommands ? "-f " : "-s -f "; const char* makecmd = astr(astr(CHPL_MAKE, " "), makeflags, getIntermediateDirName(), "/Makefile"); if( printSystemCommands ) { printf("%s\n", makecmd); } mysystem(makecmd, "Make Binary - Building Launcher and Copying"); } #endif
31.766304
219
0.653052
krishnakeshav
fd63d6164e4ba01eee2a2d2cbaec4be198826867
6,403
cc
C++
chrome/browser/ui/ash/projector/projector_client_impl.cc
chromium/chromium
df46e572c3449a4b108d6e02fbe4f6d24cf98381
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
14,668
2015-01-01T01:57:10.000Z
2022-03-31T23:33:32.000Z
chrome/browser/ui/ash/projector/projector_client_impl.cc
chromium/chromium
df46e572c3449a4b108d6e02fbe4f6d24cf98381
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
86
2015-10-21T13:02:42.000Z
2022-03-14T07:50:50.000Z
chrome/browser/ui/ash/projector/projector_client_impl.cc
chromium/chromium
df46e572c3449a4b108d6e02fbe4f6d24cf98381
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
5,941
2015-01-02T11:32:21.000Z
2022-03-31T16:35:46.000Z
// Copyright 2021 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/ash/projector/projector_client_impl.h" #include "ash/constants/ash_features.h" #include "ash/public/cpp/projector/projector_controller.h" #include "ash/webui/projector_app/annotator_message_handler.h" #include "ash/webui/projector_app/projector_app_client.h" #include "ash/webui/projector_app/public/cpp/projector_app_constants.h" #include "chrome/browser/ash/drive/drive_integration_service.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/download/download_prefs.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/profiles/profile_manager.h" #include "chrome/browser/speech/on_device_speech_recognizer.h" #include "chrome/browser/ui/browser_window.h" #include "chrome/browser/ui/web_applications/system_web_app_ui_utils.h" #include "chrome/browser/web_applications/system_web_apps/system_web_app_types.h" #include "chromeos/login/login_state/login_state.h" #include "components/soda/soda_installer.h" #include "content/public/browser/download_manager.h" #include "content/public/browser/web_contents.h" #include "content/public/browser/web_ui.h" #include "media/base/media_switches.h" #include "projector_client_impl.h" #include "third_party/abseil-cpp/absl/types/optional.h" #include "ui/display/display.h" #include "ui/display/screen.h" #include "ui/views/controls/webview/webview.h" #include "url/gurl.h" namespace { inline const std::string& GetLocale() { return g_browser_process->GetApplicationLocale(); } } // namespace // static void ProjectorClientImpl::InitForProjectorAnnotator(views::WebView* web_view) { web_view->LoadInitialURL(GURL(ash::kChromeUITrustedAnnotatorUrl)); content::WebContents* web_contents = web_view->GetWebContents(); content::WebUI* web_ui = web_contents->GetWebUI(); web_ui->AddMessageHandler(std::make_unique<ash::AnnotatorMessageHandler>()); } ProjectorClientImpl::ProjectorClientImpl(ash::ProjectorController* controller) : controller_(controller) { controller_->SetClient(this); } ProjectorClientImpl::ProjectorClientImpl() : ProjectorClientImpl(ash::ProjectorController::Get()) {} ProjectorClientImpl::~ProjectorClientImpl() = default; void ProjectorClientImpl::StartSpeechRecognition() { // ProjectorController should only request for speech recognition after it // has been informed that recognition is available. // TODO(crbug.com/1165437): Dynamically determine language code. DCHECK(OnDeviceSpeechRecognizer::IsOnDeviceSpeechRecognizerAvailable( GetLocale())); DCHECK_EQ(speech_recognizer_.get(), nullptr); recognizer_status_ = SPEECH_RECOGNIZER_OFF; speech_recognizer_ = std::make_unique<OnDeviceSpeechRecognizer>( weak_ptr_factory_.GetWeakPtr(), ProfileManager::GetActiveUserProfile(), GetLocale(), /*recognition_mode_ime=*/false, /*enable_formatting=*/true); } void ProjectorClientImpl::StopSpeechRecognition() { speech_recognizer_.reset(); recognizer_status_ = SPEECH_RECOGNIZER_OFF; } void ProjectorClientImpl::ShowSelfieCam() { selfie_cam_bubble_manager_.Show( ProfileManager::GetActiveUserProfile(), display::Screen::GetScreen()->GetPrimaryDisplay().work_area()); } void ProjectorClientImpl::CloseSelfieCam() { selfie_cam_bubble_manager_.Close(); } bool ProjectorClientImpl::IsSelfieCamVisible() const { return selfie_cam_bubble_manager_.IsVisible(); } void ProjectorClientImpl::OnSpeechResult( const std::u16string& text, bool is_final, const absl::optional<media::SpeechRecognitionResult>& full_result) { DCHECK(full_result.has_value()); controller_->OnTranscription(full_result.value()); } void ProjectorClientImpl::OnSpeechRecognitionStateChanged( SpeechRecognizerStatus new_state) { if (new_state == SPEECH_RECOGNIZER_ERROR) { speech_recognizer_.reset(); recognizer_status_ = SPEECH_RECOGNIZER_OFF; controller_->OnTranscriptionError(); } else if (new_state == SPEECH_RECOGNIZER_READY) { if (recognizer_status_ == SPEECH_RECOGNIZER_OFF && speech_recognizer_) { // The SpeechRecognizer was initialized after being created, and // is ready to start recognizing speech. speech_recognizer_->Start(); } } recognizer_status_ = new_state; } bool ProjectorClientImpl::GetDriveFsMountPointPath( base::FilePath* result) const { if (!IsDriveFsMounted()) return false; if (ash::ProjectorController::AreExtendedProjectorFeaturesDisabled()) { auto* profile = ProfileManager::GetActiveUserProfile(); DCHECK(profile); DownloadPrefs* download_prefs = DownloadPrefs::FromBrowserContext( ProfileManager::GetActiveUserProfile()); *result = download_prefs->GetDefaultDownloadDirectoryForProfile(); return true; } drive::DriveIntegrationService* integration_service = drive::DriveIntegrationServiceFactory::FindForProfile( ProfileManager::GetActiveUserProfile()); *result = integration_service->GetMountPointPath(); return true; } bool ProjectorClientImpl::IsDriveFsMounted() const { if (!chromeos::LoginState::Get()->IsUserLoggedIn()) return false; if (ash::ProjectorController::AreExtendedProjectorFeaturesDisabled()) { // Return true when extended projector features are disabled. Use download // folder for Projector storage. return true; } auto* profile = ProfileManager::GetActiveUserProfile(); drive::DriveIntegrationService* integration_service = drive::DriveIntegrationServiceFactory::FindForProfile(profile); return integration_service && integration_service->IsMounted(); } void ProjectorClientImpl::OpenProjectorApp() const { auto* profile = ProfileManager::GetActiveUserProfile(); web_app::LaunchSystemWebAppAsync(profile, web_app::SystemAppType::PROJECTOR); } void ProjectorClientImpl::MinimizeProjectorApp() const { auto* profile = ProfileManager::GetActiveUserProfile(); auto* browser = FindSystemWebAppBrowser(profile, web_app::SystemAppType::PROJECTOR); if (browser) browser->window()->Minimize(); } void ProjectorClientImpl::OnNewScreencastPreconditionChanged( const ash::NewScreencastPrecondition& precondition) const { ash::ProjectorAppClient::Get()->OnNewScreencastPreconditionChanged( precondition); }
36.380682
81
0.777917
chromium
fd65a275b913fb8299109047f325f9caef81e801
160
cpp
C++
src/examples/01_module/01_output/main.cpp
acc-cosc-1337-spring-2020/acc-cosc-1337-spring-2020-artgonzalezacc
fc87779a7c8aa6fde4def06ff7c2fbf3541a5cd9
[ "MIT" ]
null
null
null
src/examples/01_module/01_output/main.cpp
acc-cosc-1337-spring-2020/acc-cosc-1337-spring-2020-artgonzalezacc
fc87779a7c8aa6fde4def06ff7c2fbf3541a5cd9
[ "MIT" ]
null
null
null
src/examples/01_module/01_output/main.cpp
acc-cosc-1337-spring-2020/acc-cosc-1337-spring-2020-artgonzalezacc
fc87779a7c8aa6fde4def06ff7c2fbf3541a5cd9
[ "MIT" ]
null
null
null
#include "output.h"//use file code that I created #include<iostream>//use standard library using std::cout; int main() { cout<<"Hello World!"; return 0; }
14.545455
49
0.6875
acc-cosc-1337-spring-2020
fd6a3b4000d861cb9ec281e3622d6e5dc9163967
3,023
cpp
C++
modules/task_3/trevogin_k_hoar_tbb/Main.cpp
allnes/pp_2022_spring
159191f9c2f218f8b8487f92853cc928a7652462
[ "BSD-3-Clause" ]
null
null
null
modules/task_3/trevogin_k_hoar_tbb/Main.cpp
allnes/pp_2022_spring
159191f9c2f218f8b8487f92853cc928a7652462
[ "BSD-3-Clause" ]
null
null
null
modules/task_3/trevogin_k_hoar_tbb/Main.cpp
allnes/pp_2022_spring
159191f9c2f218f8b8487f92853cc928a7652462
[ "BSD-3-Clause" ]
2
2022-03-31T17:48:22.000Z
2022-03-31T18:06:07.000Z
// Copyright 2022 Trevogin Kirill #include <tbb/tbb.h> #include <algorithm> #include <cmath> #include <ctime> #include <iostream> #include <random> #include <utility> #include <vector> #include "../../../modules/task_3/trevogin_k_hoar_tbb/hoar.h" #include "gtest/gtest.h" #define N 100000 TEST(Hoare_Quick_Sort_TBB, Can_Sort_Correctly) { double* arr = new double[N]; Get_Random_Array(arr, N); qHoareSortTbb(arr, N); ASSERT_EQ(1, IsSorted(arr, N)); } TEST(Hoare_Quick_Sort_TBB, Can_Sort_Empty_Array) { double* arr = new double[N]; for (int i = 0; i < N; i++) { arr[i] = 0; } qHoareSortTbb(arr, N); double sum_element = 0.0; for (int i = 0; i < N; i++) { sum_element += arr[i]; } ASSERT_EQ(sum_element, 0); } TEST(Hoare_Quick_Sort_TBB, Can_Sort_Opposite_Elements) { double* arr = new double[N]; Get_Random_Array(arr, N); for (int i = 0; i < N; i += 2) { arr[i] = arr[i + 1] * (-1); } double* arr2 = new double[N]; Copy_elements(arr, arr2, N); qHoareSortTbb(arr, N); qHoareSort(arr2, 0, N - 1); ASSERT_EQ((int)std::equal(&arr[0], &arr[N], &arr2[0]), 1); } TEST(Hoare_Quick_Sort_TBB, Can_Sort_Already_Sorted_Elements) { double* arr = new double[N]; Get_Random_Array(arr, N); qHoareSort(arr, 0, N - 1); double* arr2 = new double[N]; Copy_elements(arr, arr2, N); qHoareSortTbb(arr, N); ASSERT_EQ((int)std::equal(&arr[0], &arr[N], &arr2[0]), 1); } TEST(Hoare_Quick_Sort_TBB, Can_Sort_Mixed_Array) { double* arr = new double[N]; Get_Random_Array(arr, N); qHoareSort(arr, 0, N - 1); double* arr2 = new double[N]; Copy_elements(arr, arr2, N); for (int i = 2; i < N; i += 3) { double temp = arr[i - 2]; arr[i - 2] = arr[i]; arr[i] = temp; } qHoareSortTbb(arr, N); ASSERT_EQ((int)std::equal(&arr[0], &arr[N], &arr2[0]), 1); } TEST(Hoare_Quick_Sort_TBB, DISABLED_Compare_Seq_and_Tbb_Average_Time) { double* arr = new double[N]; double* arr2 = new double[N]; std::vector<bool> sorted; Get_Random_Array(arr, N); Copy_elements(arr, arr2, N); tbb::tick_count t1 = tbb::tick_count::now(); qHoareSort(arr2, 0, N - 1); double seq_time = (tbb::tick_count::now() - t1).seconds(); std::cout << "Sequential time: " << seq_time << " s" << '\n'; sorted.push_back(IsSorted(arr2, N)); tbb::tick_count t2 = tbb::tick_count::now(); qHoareSortTbb(arr, N); double parallel_time = (tbb::tick_count::now() - t2).seconds(); std::cout << "Parallel tbb time: " << parallel_time << " s" << '\n'; std::cout << "Acceleration = seqtime/partime = " << seq_time / parallel_time << " " << '\n'; sorted.push_back(IsSorted(arr, N)); bool x = true; for (auto i : sorted) x = x && i; ASSERT_EQ(1, x); } int main(int argc, char** argv) { tbb::task_scheduler_init init(tbb::task_scheduler_init::automatic); ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
29.930693
96
0.607344
allnes
fd6b2581413138bd5080f874be9df0cf35e6fb1c
37,123
cc
C++
ThirdParty/webrtc/src/webrtc/modules/audio_processing/audio_processing_impl.cc
JokeJoe8806/licode-windows
2bfdaf6e87669df2b9960da50c6800bc3621b80b
[ "MIT" ]
8
2018-12-27T14:57:13.000Z
2021-04-07T07:03:15.000Z
ThirdParty/webrtc/src/webrtc/modules/audio_processing/audio_processing_impl.cc
JokeJoe8806/licode-windows
2bfdaf6e87669df2b9960da50c6800bc3621b80b
[ "MIT" ]
1
2019-03-13T01:35:03.000Z
2020-10-08T04:13:04.000Z
ThirdParty/webrtc/src/webrtc/modules/audio_processing/audio_processing_impl.cc
JokeJoe8806/licode-windows
2bfdaf6e87669df2b9960da50c6800bc3621b80b
[ "MIT" ]
9
2018-12-28T11:45:12.000Z
2021-05-11T02:15:31.000Z
/* * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "webrtc/modules/audio_processing/audio_processing_impl.h" #include <assert.h> #include "webrtc/base/checks.h" #include "webrtc/base/platform_file.h" #include "webrtc/common_audio/include/audio_util.h" #include "webrtc/common_audio/channel_buffer.h" #include "webrtc/common_audio/signal_processing/include/signal_processing_library.h" extern "C" { #include "webrtc/modules/audio_processing/aec/aec_core.h" } #include "webrtc/modules/audio_processing/agc/agc_manager_direct.h" #include "webrtc/modules/audio_processing/audio_buffer.h" #include "webrtc/modules/audio_processing/beamformer/nonlinear_beamformer.h" #include "webrtc/modules/audio_processing/common.h" #include "webrtc/modules/audio_processing/echo_cancellation_impl.h" #include "webrtc/modules/audio_processing/echo_control_mobile_impl.h" #include "webrtc/modules/audio_processing/gain_control_impl.h" #include "webrtc/modules/audio_processing/high_pass_filter_impl.h" #include "webrtc/modules/audio_processing/level_estimator_impl.h" #include "webrtc/modules/audio_processing/noise_suppression_impl.h" #include "webrtc/modules/audio_processing/processing_component.h" #include "webrtc/modules/audio_processing/transient/transient_suppressor.h" #include "webrtc/modules/audio_processing/voice_detection_impl.h" #include "webrtc/modules/interface/module_common_types.h" #include "webrtc/system_wrappers/interface/critical_section_wrapper.h" #include "webrtc/system_wrappers/interface/file_wrapper.h" #include "webrtc/system_wrappers/interface/logging.h" #include "webrtc/system_wrappers/interface/metrics.h" #ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP // Files generated at build-time by the protobuf compiler. #ifdef WEBRTC_ANDROID_PLATFORM_BUILD #include "external/webrtc/webrtc/modules/audio_processing/debug.pb.h" #else #include "webrtc/audio_processing/debug.pb.h" #endif #endif // WEBRTC_AUDIOPROC_DEBUG_DUMP #define RETURN_ON_ERR(expr) \ do { \ int err = (expr); \ if (err != kNoError) { \ return err; \ } \ } while (0) namespace webrtc { // Throughout webrtc, it's assumed that success is represented by zero. static_assert(AudioProcessing::kNoError == 0, "kNoError must be zero"); // This class has two main functionalities: // // 1) It is returned instead of the real GainControl after the new AGC has been // enabled in order to prevent an outside user from overriding compression // settings. It doesn't do anything in its implementation, except for // delegating the const methods and Enable calls to the real GainControl, so // AGC can still be disabled. // // 2) It is injected into AgcManagerDirect and implements volume callbacks for // getting and setting the volume level. It just caches this value to be used // in VoiceEngine later. class GainControlForNewAgc : public GainControl, public VolumeCallbacks { public: explicit GainControlForNewAgc(GainControlImpl* gain_control) : real_gain_control_(gain_control), volume_(0) { } // GainControl implementation. int Enable(bool enable) override { return real_gain_control_->Enable(enable); } bool is_enabled() const override { return real_gain_control_->is_enabled(); } int set_stream_analog_level(int level) override { volume_ = level; return AudioProcessing::kNoError; } int stream_analog_level() override { return volume_; } int set_mode(Mode mode) override { return AudioProcessing::kNoError; } Mode mode() const override { return GainControl::kAdaptiveAnalog; } int set_target_level_dbfs(int level) override { return AudioProcessing::kNoError; } int target_level_dbfs() const override { return real_gain_control_->target_level_dbfs(); } int set_compression_gain_db(int gain) override { return AudioProcessing::kNoError; } int compression_gain_db() const override { return real_gain_control_->compression_gain_db(); } int enable_limiter(bool enable) override { return AudioProcessing::kNoError; } bool is_limiter_enabled() const override { return real_gain_control_->is_limiter_enabled(); } int set_analog_level_limits(int minimum, int maximum) override { return AudioProcessing::kNoError; } int analog_level_minimum() const override { return real_gain_control_->analog_level_minimum(); } int analog_level_maximum() const override { return real_gain_control_->analog_level_maximum(); } bool stream_is_saturated() const override { return real_gain_control_->stream_is_saturated(); } // VolumeCallbacks implementation. void SetMicVolume(int volume) override { volume_ = volume; } int GetMicVolume() override { return volume_; } private: GainControl* real_gain_control_; int volume_; }; AudioProcessing* AudioProcessing::Create() { Config config; return Create(config, nullptr); } AudioProcessing* AudioProcessing::Create(const Config& config) { return Create(config, nullptr); } AudioProcessing* AudioProcessing::Create(const Config& config, Beamformer<float>* beamformer) { AudioProcessingImpl* apm = new AudioProcessingImpl(config, beamformer); if (apm->Initialize() != kNoError) { delete apm; apm = NULL; } return apm; } AudioProcessingImpl::AudioProcessingImpl(const Config& config) : AudioProcessingImpl(config, nullptr) {} AudioProcessingImpl::AudioProcessingImpl(const Config& config, Beamformer<float>* beamformer) : echo_cancellation_(NULL), echo_control_mobile_(NULL), gain_control_(NULL), high_pass_filter_(NULL), level_estimator_(NULL), noise_suppression_(NULL), voice_detection_(NULL), crit_(CriticalSectionWrapper::CreateCriticalSection()), #ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP debug_file_(FileWrapper::Create()), event_msg_(new audioproc::Event()), #endif fwd_in_format_(kSampleRate16kHz, 1), fwd_proc_format_(kSampleRate16kHz), fwd_out_format_(kSampleRate16kHz, 1), rev_in_format_(kSampleRate16kHz, 1), rev_proc_format_(kSampleRate16kHz, 1), split_rate_(kSampleRate16kHz), stream_delay_ms_(0), delay_offset_ms_(0), was_stream_delay_set_(false), last_stream_delay_ms_(0), last_aec_system_delay_ms_(0), output_will_be_muted_(false), key_pressed_(false), #if defined(WEBRTC_ANDROID) || defined(WEBRTC_IOS) use_new_agc_(false), #else use_new_agc_(config.Get<ExperimentalAgc>().enabled), #endif agc_startup_min_volume_(config.Get<ExperimentalAgc>().startup_min_volume), #if defined(WEBRTC_ANDROID) || defined(WEBRTC_IOS) transient_suppressor_enabled_(false), #else transient_suppressor_enabled_(config.Get<ExperimentalNs>().enabled), #endif beamformer_enabled_(config.Get<Beamforming>().enabled), beamformer_(beamformer), array_geometry_(config.Get<Beamforming>().array_geometry), supports_48kHz_(config.Get<AudioProcessing48kHzSupport>().enabled) { echo_cancellation_ = new EchoCancellationImpl(this, crit_); component_list_.push_back(echo_cancellation_); echo_control_mobile_ = new EchoControlMobileImpl(this, crit_); component_list_.push_back(echo_control_mobile_); gain_control_ = new GainControlImpl(this, crit_); component_list_.push_back(gain_control_); high_pass_filter_ = new HighPassFilterImpl(this, crit_); component_list_.push_back(high_pass_filter_); level_estimator_ = new LevelEstimatorImpl(this, crit_); component_list_.push_back(level_estimator_); noise_suppression_ = new NoiseSuppressionImpl(this, crit_); component_list_.push_back(noise_suppression_); voice_detection_ = new VoiceDetectionImpl(this, crit_); component_list_.push_back(voice_detection_); gain_control_for_new_agc_.reset(new GainControlForNewAgc(gain_control_)); SetExtraOptions(config); } AudioProcessingImpl::~AudioProcessingImpl() { { CriticalSectionScoped crit_scoped(crit_); // Depends on gain_control_ and gain_control_for_new_agc_. agc_manager_.reset(); // Depends on gain_control_. gain_control_for_new_agc_.reset(); while (!component_list_.empty()) { ProcessingComponent* component = component_list_.front(); component->Destroy(); delete component; component_list_.pop_front(); } #ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP if (debug_file_->Open()) { debug_file_->CloseFile(); } #endif } delete crit_; crit_ = NULL; } int AudioProcessingImpl::Initialize() { CriticalSectionScoped crit_scoped(crit_); return InitializeLocked(); } int AudioProcessingImpl::set_sample_rate_hz(int rate) { CriticalSectionScoped crit_scoped(crit_); return InitializeLocked(rate, rate, rev_in_format_.rate(), fwd_in_format_.num_channels(), fwd_out_format_.num_channels(), rev_in_format_.num_channels()); } int AudioProcessingImpl::Initialize(int input_sample_rate_hz, int output_sample_rate_hz, int reverse_sample_rate_hz, ChannelLayout input_layout, ChannelLayout output_layout, ChannelLayout reverse_layout) { CriticalSectionScoped crit_scoped(crit_); return InitializeLocked(input_sample_rate_hz, output_sample_rate_hz, reverse_sample_rate_hz, ChannelsFromLayout(input_layout), ChannelsFromLayout(output_layout), ChannelsFromLayout(reverse_layout)); } int AudioProcessingImpl::InitializeLocked() { const int fwd_audio_buffer_channels = beamformer_enabled_ ? fwd_in_format_.num_channels() : fwd_out_format_.num_channels(); render_audio_.reset(new AudioBuffer(rev_in_format_.samples_per_channel(), rev_in_format_.num_channels(), rev_proc_format_.samples_per_channel(), rev_proc_format_.num_channels(), rev_proc_format_.samples_per_channel())); capture_audio_.reset(new AudioBuffer(fwd_in_format_.samples_per_channel(), fwd_in_format_.num_channels(), fwd_proc_format_.samples_per_channel(), fwd_audio_buffer_channels, fwd_out_format_.samples_per_channel())); // Initialize all components. for (auto item : component_list_) { int err = item->Initialize(); if (err != kNoError) { return err; } } InitializeExperimentalAgc(); InitializeTransient(); InitializeBeamformer(); #ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP if (debug_file_->Open()) { int err = WriteInitMessage(); if (err != kNoError) { return err; } } #endif return kNoError; } int AudioProcessingImpl::InitializeLocked(int input_sample_rate_hz, int output_sample_rate_hz, int reverse_sample_rate_hz, int num_input_channels, int num_output_channels, int num_reverse_channels) { if (input_sample_rate_hz <= 0 || output_sample_rate_hz <= 0 || reverse_sample_rate_hz <= 0) { return kBadSampleRateError; } if (num_output_channels > num_input_channels) { return kBadNumberChannelsError; } // Only mono and stereo supported currently. if (num_input_channels > 2 || num_input_channels < 1 || num_output_channels > 2 || num_output_channels < 1 || num_reverse_channels > 2 || num_reverse_channels < 1) { return kBadNumberChannelsError; } if (beamformer_enabled_ && (static_cast<size_t>(num_input_channels) != array_geometry_.size() || num_output_channels > 1)) { return kBadNumberChannelsError; } fwd_in_format_.set(input_sample_rate_hz, num_input_channels); fwd_out_format_.set(output_sample_rate_hz, num_output_channels); rev_in_format_.set(reverse_sample_rate_hz, num_reverse_channels); // We process at the closest native rate >= min(input rate, output rate)... int min_proc_rate = std::min(fwd_in_format_.rate(), fwd_out_format_.rate()); int fwd_proc_rate; if (supports_48kHz_ && min_proc_rate > kSampleRate32kHz) { fwd_proc_rate = kSampleRate48kHz; } else if (min_proc_rate > kSampleRate16kHz) { fwd_proc_rate = kSampleRate32kHz; } else if (min_proc_rate > kSampleRate8kHz) { fwd_proc_rate = kSampleRate16kHz; } else { fwd_proc_rate = kSampleRate8kHz; } // ...with one exception. if (echo_control_mobile_->is_enabled() && min_proc_rate > kSampleRate16kHz) { fwd_proc_rate = kSampleRate16kHz; } fwd_proc_format_.set(fwd_proc_rate); // We normally process the reverse stream at 16 kHz. Unless... int rev_proc_rate = kSampleRate16kHz; if (fwd_proc_format_.rate() == kSampleRate8kHz) { // ...the forward stream is at 8 kHz. rev_proc_rate = kSampleRate8kHz; } else { if (rev_in_format_.rate() == kSampleRate32kHz) { // ...or the input is at 32 kHz, in which case we use the splitting // filter rather than the resampler. rev_proc_rate = kSampleRate32kHz; } } // Always downmix the reverse stream to mono for analysis. This has been // demonstrated to work well for AEC in most practical scenarios. rev_proc_format_.set(rev_proc_rate, 1); if (fwd_proc_format_.rate() == kSampleRate32kHz || fwd_proc_format_.rate() == kSampleRate48kHz) { split_rate_ = kSampleRate16kHz; } else { split_rate_ = fwd_proc_format_.rate(); } return InitializeLocked(); } // Calls InitializeLocked() if any of the audio parameters have changed from // their current values. int AudioProcessingImpl::MaybeInitializeLocked(int input_sample_rate_hz, int output_sample_rate_hz, int reverse_sample_rate_hz, int num_input_channels, int num_output_channels, int num_reverse_channels) { if (input_sample_rate_hz == fwd_in_format_.rate() && output_sample_rate_hz == fwd_out_format_.rate() && reverse_sample_rate_hz == rev_in_format_.rate() && num_input_channels == fwd_in_format_.num_channels() && num_output_channels == fwd_out_format_.num_channels() && num_reverse_channels == rev_in_format_.num_channels()) { return kNoError; } return InitializeLocked(input_sample_rate_hz, output_sample_rate_hz, reverse_sample_rate_hz, num_input_channels, num_output_channels, num_reverse_channels); } void AudioProcessingImpl::SetExtraOptions(const Config& config) { CriticalSectionScoped crit_scoped(crit_); for (auto item : component_list_) { item->SetExtraOptions(config); } if (transient_suppressor_enabled_ != config.Get<ExperimentalNs>().enabled) { transient_suppressor_enabled_ = config.Get<ExperimentalNs>().enabled; InitializeTransient(); } } int AudioProcessingImpl::input_sample_rate_hz() const { CriticalSectionScoped crit_scoped(crit_); return fwd_in_format_.rate(); } int AudioProcessingImpl::sample_rate_hz() const { CriticalSectionScoped crit_scoped(crit_); return fwd_in_format_.rate(); } int AudioProcessingImpl::proc_sample_rate_hz() const { return fwd_proc_format_.rate(); } int AudioProcessingImpl::proc_split_sample_rate_hz() const { return split_rate_; } int AudioProcessingImpl::num_reverse_channels() const { return rev_proc_format_.num_channels(); } int AudioProcessingImpl::num_input_channels() const { return fwd_in_format_.num_channels(); } int AudioProcessingImpl::num_output_channels() const { return fwd_out_format_.num_channels(); } void AudioProcessingImpl::set_output_will_be_muted(bool muted) { CriticalSectionScoped lock(crit_); output_will_be_muted_ = muted; if (agc_manager_.get()) { agc_manager_->SetCaptureMuted(output_will_be_muted_); } } bool AudioProcessingImpl::output_will_be_muted() const { CriticalSectionScoped lock(crit_); return output_will_be_muted_; } int AudioProcessingImpl::ProcessStream(const float* const* src, int samples_per_channel, int input_sample_rate_hz, ChannelLayout input_layout, int output_sample_rate_hz, ChannelLayout output_layout, float* const* dest) { CriticalSectionScoped crit_scoped(crit_); if (!src || !dest) { return kNullPointerError; } RETURN_ON_ERR(MaybeInitializeLocked(input_sample_rate_hz, output_sample_rate_hz, rev_in_format_.rate(), ChannelsFromLayout(input_layout), ChannelsFromLayout(output_layout), rev_in_format_.num_channels())); if (samples_per_channel != fwd_in_format_.samples_per_channel()) { return kBadDataLengthError; } #ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP if (debug_file_->Open()) { event_msg_->set_type(audioproc::Event::STREAM); audioproc::Stream* msg = event_msg_->mutable_stream(); const size_t channel_size = sizeof(float) * fwd_in_format_.samples_per_channel(); for (int i = 0; i < fwd_in_format_.num_channels(); ++i) msg->add_input_channel(src[i], channel_size); } #endif capture_audio_->CopyFrom(src, samples_per_channel, input_layout); RETURN_ON_ERR(ProcessStreamLocked()); capture_audio_->CopyTo(fwd_out_format_.samples_per_channel(), output_layout, dest); #ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP if (debug_file_->Open()) { audioproc::Stream* msg = event_msg_->mutable_stream(); const size_t channel_size = sizeof(float) * fwd_out_format_.samples_per_channel(); for (int i = 0; i < fwd_out_format_.num_channels(); ++i) msg->add_output_channel(dest[i], channel_size); RETURN_ON_ERR(WriteMessageToDebugFile()); } #endif return kNoError; } int AudioProcessingImpl::ProcessStream(AudioFrame* frame) { CriticalSectionScoped crit_scoped(crit_); if (!frame) { return kNullPointerError; } // Must be a native rate. if (frame->sample_rate_hz_ != kSampleRate8kHz && frame->sample_rate_hz_ != kSampleRate16kHz && frame->sample_rate_hz_ != kSampleRate32kHz && frame->sample_rate_hz_ != kSampleRate48kHz) { return kBadSampleRateError; } if (echo_control_mobile_->is_enabled() && frame->sample_rate_hz_ > kSampleRate16kHz) { LOG(LS_ERROR) << "AECM only supports 16 or 8 kHz sample rates"; return kUnsupportedComponentError; } // TODO(ajm): The input and output rates and channels are currently // constrained to be identical in the int16 interface. RETURN_ON_ERR(MaybeInitializeLocked(frame->sample_rate_hz_, frame->sample_rate_hz_, rev_in_format_.rate(), frame->num_channels_, frame->num_channels_, rev_in_format_.num_channels())); if (frame->samples_per_channel_ != fwd_in_format_.samples_per_channel()) { return kBadDataLengthError; } #ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP if (debug_file_->Open()) { event_msg_->set_type(audioproc::Event::STREAM); audioproc::Stream* msg = event_msg_->mutable_stream(); const size_t data_size = sizeof(int16_t) * frame->samples_per_channel_ * frame->num_channels_; msg->set_input_data(frame->data_, data_size); } #endif capture_audio_->DeinterleaveFrom(frame); RETURN_ON_ERR(ProcessStreamLocked()); capture_audio_->InterleaveTo(frame, output_copy_needed(is_data_processed())); #ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP if (debug_file_->Open()) { audioproc::Stream* msg = event_msg_->mutable_stream(); const size_t data_size = sizeof(int16_t) * frame->samples_per_channel_ * frame->num_channels_; msg->set_output_data(frame->data_, data_size); RETURN_ON_ERR(WriteMessageToDebugFile()); } #endif return kNoError; } int AudioProcessingImpl::ProcessStreamLocked() { #ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP if (debug_file_->Open()) { audioproc::Stream* msg = event_msg_->mutable_stream(); msg->set_delay(stream_delay_ms_); msg->set_drift(echo_cancellation_->stream_drift_samples()); msg->set_level(gain_control()->stream_analog_level()); msg->set_keypress(key_pressed_); } #endif MaybeUpdateHistograms(); AudioBuffer* ca = capture_audio_.get(); // For brevity. if (use_new_agc_ && gain_control_->is_enabled()) { agc_manager_->AnalyzePreProcess(ca->channels()[0], ca->num_channels(), fwd_proc_format_.samples_per_channel()); } bool data_processed = is_data_processed(); if (analysis_needed(data_processed)) { ca->SplitIntoFrequencyBands(); } if (beamformer_enabled_) { beamformer_->ProcessChunk(*ca->split_data_f(), ca->split_data_f()); ca->set_num_channels(1); } RETURN_ON_ERR(high_pass_filter_->ProcessCaptureAudio(ca)); RETURN_ON_ERR(gain_control_->AnalyzeCaptureAudio(ca)); RETURN_ON_ERR(noise_suppression_->AnalyzeCaptureAudio(ca)); RETURN_ON_ERR(echo_cancellation_->ProcessCaptureAudio(ca)); if (echo_control_mobile_->is_enabled() && noise_suppression_->is_enabled()) { ca->CopyLowPassToReference(); } RETURN_ON_ERR(noise_suppression_->ProcessCaptureAudio(ca)); RETURN_ON_ERR(echo_control_mobile_->ProcessCaptureAudio(ca)); RETURN_ON_ERR(voice_detection_->ProcessCaptureAudio(ca)); if (use_new_agc_ && gain_control_->is_enabled() && (!beamformer_enabled_ || beamformer_->is_target_present())) { agc_manager_->Process(ca->split_bands_const(0)[kBand0To8kHz], ca->num_frames_per_band(), split_rate_); } RETURN_ON_ERR(gain_control_->ProcessCaptureAudio(ca)); if (synthesis_needed(data_processed)) { ca->MergeFrequencyBands(); } // TODO(aluebs): Investigate if the transient suppression placement should be // before or after the AGC. if (transient_suppressor_enabled_) { float voice_probability = agc_manager_.get() ? agc_manager_->voice_probability() : 1.f; transient_suppressor_->Suppress(ca->channels_f()[0], ca->num_frames(), ca->num_channels(), ca->split_bands_const_f(0)[kBand0To8kHz], ca->num_frames_per_band(), ca->keyboard_data(), ca->num_keyboard_frames(), voice_probability, key_pressed_); } // The level estimator operates on the recombined data. RETURN_ON_ERR(level_estimator_->ProcessStream(ca)); was_stream_delay_set_ = false; return kNoError; } int AudioProcessingImpl::AnalyzeReverseStream(const float* const* data, int samples_per_channel, int sample_rate_hz, ChannelLayout layout) { CriticalSectionScoped crit_scoped(crit_); if (data == NULL) { return kNullPointerError; } const int num_channels = ChannelsFromLayout(layout); RETURN_ON_ERR(MaybeInitializeLocked(fwd_in_format_.rate(), fwd_out_format_.rate(), sample_rate_hz, fwd_in_format_.num_channels(), fwd_out_format_.num_channels(), num_channels)); if (samples_per_channel != rev_in_format_.samples_per_channel()) { return kBadDataLengthError; } #ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP if (debug_file_->Open()) { event_msg_->set_type(audioproc::Event::REVERSE_STREAM); audioproc::ReverseStream* msg = event_msg_->mutable_reverse_stream(); const size_t channel_size = sizeof(float) * rev_in_format_.samples_per_channel(); for (int i = 0; i < num_channels; ++i) msg->add_channel(data[i], channel_size); RETURN_ON_ERR(WriteMessageToDebugFile()); } #endif render_audio_->CopyFrom(data, samples_per_channel, layout); return AnalyzeReverseStreamLocked(); } int AudioProcessingImpl::AnalyzeReverseStream(AudioFrame* frame) { CriticalSectionScoped crit_scoped(crit_); if (frame == NULL) { return kNullPointerError; } // Must be a native rate. if (frame->sample_rate_hz_ != kSampleRate8kHz && frame->sample_rate_hz_ != kSampleRate16kHz && frame->sample_rate_hz_ != kSampleRate32kHz && frame->sample_rate_hz_ != kSampleRate48kHz) { return kBadSampleRateError; } // This interface does not tolerate different forward and reverse rates. if (frame->sample_rate_hz_ != fwd_in_format_.rate()) { return kBadSampleRateError; } RETURN_ON_ERR(MaybeInitializeLocked(fwd_in_format_.rate(), fwd_out_format_.rate(), frame->sample_rate_hz_, fwd_in_format_.num_channels(), fwd_in_format_.num_channels(), frame->num_channels_)); if (frame->samples_per_channel_ != rev_in_format_.samples_per_channel()) { return kBadDataLengthError; } #ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP if (debug_file_->Open()) { event_msg_->set_type(audioproc::Event::REVERSE_STREAM); audioproc::ReverseStream* msg = event_msg_->mutable_reverse_stream(); const size_t data_size = sizeof(int16_t) * frame->samples_per_channel_ * frame->num_channels_; msg->set_data(frame->data_, data_size); RETURN_ON_ERR(WriteMessageToDebugFile()); } #endif render_audio_->DeinterleaveFrom(frame); return AnalyzeReverseStreamLocked(); } int AudioProcessingImpl::AnalyzeReverseStreamLocked() { AudioBuffer* ra = render_audio_.get(); // For brevity. if (rev_proc_format_.rate() == kSampleRate32kHz) { ra->SplitIntoFrequencyBands(); } RETURN_ON_ERR(echo_cancellation_->ProcessRenderAudio(ra)); RETURN_ON_ERR(echo_control_mobile_->ProcessRenderAudio(ra)); if (!use_new_agc_) { RETURN_ON_ERR(gain_control_->ProcessRenderAudio(ra)); } return kNoError; } int AudioProcessingImpl::set_stream_delay_ms(int delay) { Error retval = kNoError; was_stream_delay_set_ = true; delay += delay_offset_ms_; if (delay < 0) { delay = 0; retval = kBadStreamParameterWarning; } // TODO(ajm): the max is rather arbitrarily chosen; investigate. if (delay > 500) { delay = 500; retval = kBadStreamParameterWarning; } stream_delay_ms_ = delay; return retval; } int AudioProcessingImpl::stream_delay_ms() const { return stream_delay_ms_; } bool AudioProcessingImpl::was_stream_delay_set() const { return was_stream_delay_set_; } void AudioProcessingImpl::set_stream_key_pressed(bool key_pressed) { key_pressed_ = key_pressed; } bool AudioProcessingImpl::stream_key_pressed() const { return key_pressed_; } void AudioProcessingImpl::set_delay_offset_ms(int offset) { CriticalSectionScoped crit_scoped(crit_); delay_offset_ms_ = offset; } int AudioProcessingImpl::delay_offset_ms() const { return delay_offset_ms_; } int AudioProcessingImpl::StartDebugRecording( const char filename[AudioProcessing::kMaxFilenameSize]) { CriticalSectionScoped crit_scoped(crit_); static_assert(kMaxFilenameSize == FileWrapper::kMaxFileNameSize, ""); if (filename == NULL) { return kNullPointerError; } #ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP // Stop any ongoing recording. if (debug_file_->Open()) { if (debug_file_->CloseFile() == -1) { return kFileError; } } if (debug_file_->OpenFile(filename, false) == -1) { debug_file_->CloseFile(); return kFileError; } int err = WriteInitMessage(); if (err != kNoError) { return err; } return kNoError; #else return kUnsupportedFunctionError; #endif // WEBRTC_AUDIOPROC_DEBUG_DUMP } int AudioProcessingImpl::StartDebugRecording(FILE* handle) { CriticalSectionScoped crit_scoped(crit_); if (handle == NULL) { return kNullPointerError; } #ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP // Stop any ongoing recording. if (debug_file_->Open()) { if (debug_file_->CloseFile() == -1) { return kFileError; } } if (debug_file_->OpenFromFileHandle(handle, true, false) == -1) { return kFileError; } int err = WriteInitMessage(); if (err != kNoError) { return err; } return kNoError; #else return kUnsupportedFunctionError; #endif // WEBRTC_AUDIOPROC_DEBUG_DUMP } int AudioProcessingImpl::StartDebugRecordingForPlatformFile( rtc::PlatformFile handle) { FILE* stream = rtc::FdopenPlatformFileForWriting(handle); return StartDebugRecording(stream); } int AudioProcessingImpl::StopDebugRecording() { CriticalSectionScoped crit_scoped(crit_); #ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP // We just return if recording hasn't started. if (debug_file_->Open()) { if (debug_file_->CloseFile() == -1) { return kFileError; } } return kNoError; #else return kUnsupportedFunctionError; #endif // WEBRTC_AUDIOPROC_DEBUG_DUMP } EchoCancellation* AudioProcessingImpl::echo_cancellation() const { return echo_cancellation_; } EchoControlMobile* AudioProcessingImpl::echo_control_mobile() const { return echo_control_mobile_; } GainControl* AudioProcessingImpl::gain_control() const { if (use_new_agc_) { return gain_control_for_new_agc_.get(); } return gain_control_; } HighPassFilter* AudioProcessingImpl::high_pass_filter() const { return high_pass_filter_; } LevelEstimator* AudioProcessingImpl::level_estimator() const { return level_estimator_; } NoiseSuppression* AudioProcessingImpl::noise_suppression() const { return noise_suppression_; } VoiceDetection* AudioProcessingImpl::voice_detection() const { return voice_detection_; } bool AudioProcessingImpl::is_data_processed() const { if (beamformer_enabled_) { return true; } int enabled_count = 0; for (auto item : component_list_) { if (item->is_component_enabled()) { enabled_count++; } } // Data is unchanged if no components are enabled, or if only level_estimator_ // or voice_detection_ is enabled. if (enabled_count == 0) { return false; } else if (enabled_count == 1) { if (level_estimator_->is_enabled() || voice_detection_->is_enabled()) { return false; } } else if (enabled_count == 2) { if (level_estimator_->is_enabled() && voice_detection_->is_enabled()) { return false; } } return true; } bool AudioProcessingImpl::output_copy_needed(bool is_data_processed) const { // Check if we've upmixed or downmixed the audio. return ((fwd_out_format_.num_channels() != fwd_in_format_.num_channels()) || is_data_processed || transient_suppressor_enabled_); } bool AudioProcessingImpl::synthesis_needed(bool is_data_processed) const { return (is_data_processed && (fwd_proc_format_.rate() == kSampleRate32kHz || fwd_proc_format_.rate() == kSampleRate48kHz)); } bool AudioProcessingImpl::analysis_needed(bool is_data_processed) const { if (!is_data_processed && !voice_detection_->is_enabled() && !transient_suppressor_enabled_) { // Only level_estimator_ is enabled. return false; } else if (fwd_proc_format_.rate() == kSampleRate32kHz || fwd_proc_format_.rate() == kSampleRate48kHz) { // Something besides level_estimator_ is enabled, and we have super-wb. return true; } return false; } void AudioProcessingImpl::InitializeExperimentalAgc() { if (use_new_agc_) { if (!agc_manager_.get()) { agc_manager_.reset(new AgcManagerDirect(gain_control_, gain_control_for_new_agc_.get(), agc_startup_min_volume_)); } agc_manager_->Initialize(); agc_manager_->SetCaptureMuted(output_will_be_muted_); } } void AudioProcessingImpl::InitializeTransient() { if (transient_suppressor_enabled_) { if (!transient_suppressor_.get()) { transient_suppressor_.reset(new TransientSuppressor()); } transient_suppressor_->Initialize(fwd_proc_format_.rate(), split_rate_, fwd_out_format_.num_channels()); } } void AudioProcessingImpl::InitializeBeamformer() { if (beamformer_enabled_) { if (!beamformer_) { beamformer_.reset(new NonlinearBeamformer(array_geometry_)); } beamformer_->Initialize(kChunkSizeMs, split_rate_); } } void AudioProcessingImpl::MaybeUpdateHistograms() { static const int kMinDiffDelayMs = 60; if (echo_cancellation()->is_enabled()) { // Detect a jump in platform reported system delay and log the difference. const int diff_stream_delay_ms = stream_delay_ms_ - last_stream_delay_ms_; if (diff_stream_delay_ms > kMinDiffDelayMs && last_stream_delay_ms_ != 0) { RTC_HISTOGRAM_COUNTS("WebRTC.Audio.PlatformReportedStreamDelayJump", diff_stream_delay_ms, kMinDiffDelayMs, 1000, 100); } last_stream_delay_ms_ = stream_delay_ms_; // Detect a jump in AEC system delay and log the difference. const int frames_per_ms = rtc::CheckedDivExact(split_rate_, 1000); const int aec_system_delay_ms = WebRtcAec_system_delay(echo_cancellation()->aec_core()) / frames_per_ms; const int diff_aec_system_delay_ms = aec_system_delay_ms - last_aec_system_delay_ms_; if (diff_aec_system_delay_ms > kMinDiffDelayMs && last_aec_system_delay_ms_ != 0) { RTC_HISTOGRAM_COUNTS("WebRTC.Audio.AecSystemDelayJump", diff_aec_system_delay_ms, kMinDiffDelayMs, 1000, 100); } last_aec_system_delay_ms_ = aec_system_delay_ms; // TODO(bjornv): Consider also logging amount of jumps. This gives a better // indication of how frequent jumps are. } } #ifdef WEBRTC_AUDIOPROC_DEBUG_DUMP int AudioProcessingImpl::WriteMessageToDebugFile() { int32_t size = event_msg_->ByteSize(); if (size <= 0) { return kUnspecifiedError; } #if defined(WEBRTC_ARCH_BIG_ENDIAN) // TODO(ajm): Use little-endian "on the wire". For the moment, we can be // pretty safe in assuming little-endian. #endif if (!event_msg_->SerializeToString(&event_str_)) { return kUnspecifiedError; } // Write message preceded by its size. if (!debug_file_->Write(&size, sizeof(int32_t))) { return kFileError; } if (!debug_file_->Write(event_str_.data(), event_str_.length())) { return kFileError; } event_msg_->Clear(); return kNoError; } int AudioProcessingImpl::WriteInitMessage() { event_msg_->set_type(audioproc::Event::INIT); audioproc::Init* msg = event_msg_->mutable_init(); msg->set_sample_rate(fwd_in_format_.rate()); msg->set_num_input_channels(fwd_in_format_.num_channels()); msg->set_num_output_channels(fwd_out_format_.num_channels()); msg->set_num_reverse_channels(rev_in_format_.num_channels()); msg->set_reverse_sample_rate(rev_in_format_.rate()); msg->set_output_sample_rate(fwd_out_format_.rate()); int err = WriteMessageToDebugFile(); if (err != kNoError) { return err; } return kNoError; } #endif // WEBRTC_AUDIOPROC_DEBUG_DUMP } // namespace webrtc
34.373148
84
0.679309
JokeJoe8806
fd6d5010db5327ded31a87d1913a84624e0e7282
12,911
cpp
C++
lib/StaticAnalyzer/Core/SarifDiagnostics.cpp
iotamudelta/hcc-clang-upgrade
5c47459ff44167287070644415ecc4d1bf705aa4
[ "Apache-2.0" ]
158
2015-01-01T15:56:38.000Z
2022-02-15T19:27:40.000Z
lib/StaticAnalyzer/Core/SarifDiagnostics.cpp
iotamudelta/hcc-clang-upgrade
5c47459ff44167287070644415ecc4d1bf705aa4
[ "Apache-2.0" ]
497
2017-04-04T14:22:22.000Z
2020-03-10T14:12:27.000Z
lib/StaticAnalyzer/Core/SarifDiagnostics.cpp
iotamudelta/hcc-clang-upgrade
5c47459ff44167287070644415ecc4d1bf705aa4
[ "Apache-2.0" ]
26
2017-04-21T12:51:33.000Z
2019-05-06T13:31:02.000Z
//===--- SarifDiagnostics.cpp - Sarif Diagnostics for Paths -----*- C++ -*-===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // // This file defines the SarifDiagnostics object. // //===----------------------------------------------------------------------===// #include "clang/Basic/Version.h" #include "clang/Lex/Preprocessor.h" #include "clang/StaticAnalyzer/Core/AnalyzerOptions.h" #include "clang/StaticAnalyzer/Core/BugReporter/PathDiagnostic.h" #include "clang/StaticAnalyzer/Core/PathDiagnosticConsumers.h" #include "llvm/ADT/STLExtras.h" #include "llvm/ADT/StringMap.h" #include "llvm/Support/JSON.h" #include "llvm/Support/Path.h" using namespace llvm; using namespace clang; using namespace ento; namespace { class SarifDiagnostics : public PathDiagnosticConsumer { std::string OutputFile; public: SarifDiagnostics(AnalyzerOptions &, const std::string &Output) : OutputFile(Output) {} ~SarifDiagnostics() override = default; void FlushDiagnosticsImpl(std::vector<const PathDiagnostic *> &Diags, FilesMade *FM) override; StringRef getName() const override { return "SarifDiagnostics"; } PathGenerationScheme getGenerationScheme() const override { return Minimal; } bool supportsLogicalOpControlFlow() const override { return true; } bool supportsCrossFileDiagnostics() const override { return true; } }; } // end anonymous namespace void ento::createSarifDiagnosticConsumer( AnalyzerOptions &AnalyzerOpts, PathDiagnosticConsumers &C, const std::string &Output, const Preprocessor &, const cross_tu::CrossTranslationUnitContext &) { C.push_back(new SarifDiagnostics(AnalyzerOpts, Output)); } static StringRef getFileName(const FileEntry &FE) { StringRef Filename = FE.tryGetRealPathName(); if (Filename.empty()) Filename = FE.getName(); return Filename; } static std::string percentEncodeURICharacter(char C) { // RFC 3986 claims alpha, numeric, and this handful of // characters are not reserved for the path component and // should be written out directly. Otherwise, percent // encode the character and write that out instead of the // reserved character. if (llvm::isAlnum(C) || StringRef::npos != StringRef("-._~:@!$&'()*+,;=").find(C)) return std::string(&C, 1); return "%" + llvm::toHex(StringRef(&C, 1)); } static std::string fileNameToURI(StringRef Filename) { llvm::SmallString<32> Ret = StringRef("file://"); // Get the root name to see if it has a URI authority. StringRef Root = sys::path::root_name(Filename); if (Root.startswith("//")) { // There is an authority, so add it to the URI. Ret += Root.drop_front(2).str(); } else if (!Root.empty()) { // There is no authority, so end the component and add the root to the URI. Ret += Twine("/" + Root).str(); } auto Iter = sys::path::begin(Filename), End = sys::path::end(Filename); assert(Iter != End && "Expected there to be a non-root path component."); // Add the rest of the path components, encoding any reserved characters; // we skip past the first path component, as it was handled it above. std::for_each(++Iter, End, [&Ret](StringRef Component) { // For reasons unknown to me, we may get a backslash with Windows native // paths for the initial backslash following the drive component, which // we need to ignore as a URI path part. if (Component == "\\") return; // Add the separator between the previous path part and the one being // currently processed. Ret += "/"; // URI encode the part. for (char C : Component) { Ret += percentEncodeURICharacter(C); } }); return Ret.str().str(); } static json::Object createFileLocation(const FileEntry &FE) { return json::Object{{"uri", fileNameToURI(getFileName(FE))}}; } static json::Object createFile(const FileEntry &FE) { return json::Object{{"fileLocation", createFileLocation(FE)}, {"roles", json::Array{"resultFile"}}, {"length", FE.getSize()}, {"mimeType", "text/plain"}}; } static json::Object createFileLocation(const FileEntry &FE, json::Array &Files) { std::string FileURI = fileNameToURI(getFileName(FE)); // See if the Files array contains this URI already. If it does not, create // a new file object to add to the array. auto I = llvm::find_if(Files, [&](const json::Value &File) { if (const json::Object *Obj = File.getAsObject()) { if (const json::Object *FileLoc = Obj->getObject("fileLocation")) { Optional<StringRef> URI = FileLoc->getString("uri"); return URI && URI->equals(FileURI); } } return false; }); // Calculate the index within the file location array so it can be stored in // the JSON object. auto Index = static_cast<unsigned>(std::distance(Files.begin(), I)); if (I == Files.end()) Files.push_back(createFile(FE)); return json::Object{{"uri", FileURI}, {"fileIndex", Index}}; } static json::Object createTextRegion(SourceRange R, const SourceManager &SM) { return json::Object{ {"startLine", SM.getExpansionLineNumber(R.getBegin())}, {"endLine", SM.getExpansionLineNumber(R.getEnd())}, {"startColumn", SM.getExpansionColumnNumber(R.getBegin())}, {"endColumn", SM.getExpansionColumnNumber(R.getEnd())}}; } static json::Object createPhysicalLocation(SourceRange R, const FileEntry &FE, const SourceManager &SMgr, json::Array &Files) { return json::Object{{{"fileLocation", createFileLocation(FE, Files)}, {"region", createTextRegion(R, SMgr)}}}; } enum class Importance { Important, Essential, Unimportant }; static StringRef importanceToStr(Importance I) { switch (I) { case Importance::Important: return "important"; case Importance::Essential: return "essential"; case Importance::Unimportant: return "unimportant"; } llvm_unreachable("Fully covered switch is not so fully covered"); } static json::Object createThreadFlowLocation(json::Object &&Location, Importance I) { return json::Object{{"location", std::move(Location)}, {"importance", importanceToStr(I)}}; } static json::Object createMessage(StringRef Text) { return json::Object{{"text", Text.str()}}; } static json::Object createLocation(json::Object &&PhysicalLocation, StringRef Message = "") { json::Object Ret{{"physicalLocation", std::move(PhysicalLocation)}}; if (!Message.empty()) Ret.insert({"message", createMessage(Message)}); return Ret; } static Importance calculateImportance(const PathDiagnosticPiece &Piece) { switch (Piece.getKind()) { case PathDiagnosticPiece::Call: case PathDiagnosticPiece::Macro: case PathDiagnosticPiece::Note: case PathDiagnosticPiece::PopUp: // FIXME: What should be reported here? break; case PathDiagnosticPiece::Event: return Piece.getTagStr() == "ConditionBRVisitor" ? Importance::Important : Importance::Essential; case PathDiagnosticPiece::ControlFlow: return Importance::Unimportant; } return Importance::Unimportant; } static json::Object createThreadFlow(const PathPieces &Pieces, json::Array &Files) { const SourceManager &SMgr = Pieces.front()->getLocation().getManager(); json::Array Locations; for (const auto &Piece : Pieces) { const PathDiagnosticLocation &P = Piece->getLocation(); Locations.push_back(createThreadFlowLocation( createLocation(createPhysicalLocation(P.asRange(), *P.asLocation().getFileEntry(), SMgr, Files), Piece->getString()), calculateImportance(*Piece))); } return json::Object{{"locations", std::move(Locations)}}; } static json::Object createCodeFlow(const PathPieces &Pieces, json::Array &Files) { return json::Object{ {"threadFlows", json::Array{createThreadFlow(Pieces, Files)}}}; } static json::Object createTool() { return json::Object{{"name", "clang"}, {"fullName", "clang static analyzer"}, {"language", "en-US"}, {"version", getClangFullVersion()}}; } static json::Object createResult(const PathDiagnostic &Diag, json::Array &Files, const StringMap<unsigned> &RuleMapping) { const PathPieces &Path = Diag.path.flatten(false); const SourceManager &SMgr = Path.front()->getLocation().getManager(); auto Iter = RuleMapping.find(Diag.getCheckName()); assert(Iter != RuleMapping.end() && "Rule ID is not in the array index map?"); return json::Object{ {"message", createMessage(Diag.getVerboseDescription())}, {"codeFlows", json::Array{createCodeFlow(Path, Files)}}, {"locations", json::Array{createLocation(createPhysicalLocation( Diag.getLocation().asRange(), *Diag.getLocation().asLocation().getFileEntry(), SMgr, Files))}}, {"ruleIndex", Iter->getValue()}, {"ruleId", Diag.getCheckName()}}; } static StringRef getRuleDescription(StringRef CheckName) { return llvm::StringSwitch<StringRef>(CheckName) #define GET_CHECKERS #define CHECKER(FULLNAME, CLASS, HELPTEXT, DOC_URI, IS_HIDDEN) \ .Case(FULLNAME, HELPTEXT) #include "clang/StaticAnalyzer/Checkers/Checkers.inc" #undef CHECKER #undef GET_CHECKERS ; } static StringRef getRuleHelpURIStr(StringRef CheckName) { return llvm::StringSwitch<StringRef>(CheckName) #define GET_CHECKERS #define CHECKER(FULLNAME, CLASS, HELPTEXT, DOC_URI, IS_HIDDEN) \ .Case(FULLNAME, DOC_URI) #include "clang/StaticAnalyzer/Checkers/Checkers.inc" #undef CHECKER #undef GET_CHECKERS ; } static json::Object createRule(const PathDiagnostic &Diag) { StringRef CheckName = Diag.getCheckName(); json::Object Ret{ {"fullDescription", createMessage(getRuleDescription(CheckName))}, {"name", createMessage(CheckName)}, {"id", CheckName}}; std::string RuleURI = getRuleHelpURIStr(CheckName); if (!RuleURI.empty()) Ret["helpUri"] = RuleURI; return Ret; } static json::Array createRules(std::vector<const PathDiagnostic *> &Diags, StringMap<unsigned> &RuleMapping) { json::Array Rules; llvm::StringSet<> Seen; llvm::for_each(Diags, [&](const PathDiagnostic *D) { StringRef RuleID = D->getCheckName(); std::pair<llvm::StringSet<>::iterator, bool> P = Seen.insert(RuleID); if (P.second) { RuleMapping[RuleID] = Rules.size(); // Maps RuleID to an Array Index. Rules.push_back(createRule(*D)); } }); return Rules; } static json::Object createResources(std::vector<const PathDiagnostic *> &Diags, StringMap<unsigned> &RuleMapping) { return json::Object{{"rules", createRules(Diags, RuleMapping)}}; } static json::Object createRun(std::vector<const PathDiagnostic *> &Diags) { json::Array Results, Files; StringMap<unsigned> RuleMapping; json::Object Resources = createResources(Diags, RuleMapping); llvm::for_each(Diags, [&](const PathDiagnostic *D) { Results.push_back(createResult(*D, Files, RuleMapping)); }); return json::Object{{"tool", createTool()}, {"resources", std::move(Resources)}, {"results", std::move(Results)}, {"files", std::move(Files)}}; } void SarifDiagnostics::FlushDiagnosticsImpl( std::vector<const PathDiagnostic *> &Diags, FilesMade *) { // We currently overwrite the file if it already exists. However, it may be // useful to add a feature someday that allows the user to append a run to an // existing SARIF file. One danger from that approach is that the size of the // file can become large very quickly, so decoding into JSON to append a run // may be an expensive operation. std::error_code EC; llvm::raw_fd_ostream OS(OutputFile, EC, llvm::sys::fs::F_Text); if (EC) { llvm::errs() << "warning: could not create file: " << EC.message() << '\n'; return; } json::Object Sarif{ {"$schema", "http://json.schemastore.org/sarif-2.0.0-csd.2.beta.2018-11-28"}, {"version", "2.0.0-csd.2.beta.2018-11-28"}, {"runs", json::Array{createRun(Diags)}}}; OS << llvm::formatv("{0:2}\n", json::Value(std::move(Sarif))); }
36.888571
80
0.646193
iotamudelta
fd6f38712b3dc29d17a87f86edc8d8f16a1b4938
846
cpp
C++
src/lib/Charting.cpp
kp2pml30/optimization-methods-labs
654d982fafea4dcaaea80aa78d89128bc443398b
[ "Apache-2.0" ]
3
2021-05-13T14:05:21.000Z
2021-05-13T14:05:39.000Z
src/lib/Charting.cpp
kp2pml30/optimization-methods-labs
654d982fafea4dcaaea80aa78d89128bc443398b
[ "Apache-2.0" ]
null
null
null
src/lib/Charting.cpp
kp2pml30/optimization-methods-labs
654d982fafea4dcaaea80aa78d89128bc443398b
[ "Apache-2.0" ]
null
null
null
#include "opt-methods/util/Charting.hpp" using namespace Charting; void Charting::addToChart(QtCharts::QChart *chart, QtCharts::QAbstractSeries *s) { s->setUseOpenGL(); chart->addSeries(s); s->attachAxis(axisX(chart)); s->attachAxis(axisY(chart)); } qreal Charting::getAxisRange(QtCharts::QValueAxis *axis) { return axis->max() - axis->min(); } void Charting::growAxisRange(QtCharts::QValueAxis *axis, double coef) { qreal r = getAxisRange(axis); axis->setRange(axis->min() - r * coef, axis->max() + r * coef); } void Charting::createNaturalSequenceAxes(QtCharts::QChart* chart, [[maybe_unused]] int n) { using namespace QtCharts; chart->createDefaultAxes(); auto* x = axisX<QtCharts::QValueAxis>(chart); auto* y = axisY<QtCharts::QValueAxis>(chart); growAxisRange(x, 0.01); x->setLabelFormat("%i"); growAxisRange(y, 0.01); }
25.636364
94
0.712766
kp2pml30
fd7186dc43a9c6d64be001f6b105453320532cd5
2,200
inl
C++
TAO/orbsvcs/orbsvcs/Event/EC_ProxySupplier.inl
cflowe/ACE
5ff60b41adbe1772372d1a43bcc1f2726ff8f810
[ "DOC" ]
36
2015-01-10T07:27:33.000Z
2022-03-07T03:32:08.000Z
TAO/orbsvcs/orbsvcs/Event/EC_ProxySupplier.inl
cflowe/ACE
5ff60b41adbe1772372d1a43bcc1f2726ff8f810
[ "DOC" ]
2
2018-08-13T07:30:51.000Z
2019-02-25T03:04:31.000Z
TAO/orbsvcs/orbsvcs/Event/EC_ProxySupplier.inl
cflowe/ACE
5ff60b41adbe1772372d1a43bcc1f2726ff8f810
[ "DOC" ]
38
2015-01-08T14:12:06.000Z
2022-01-19T08:33:00.000Z
// -*- C++ -*- // // $Id: EC_ProxySupplier.inl 77001 2007-02-12 07:54:49Z johnnyw $ TAO_BEGIN_VERSIONED_NAMESPACE_DECL ACE_INLINE void TAO_EC_ProxyPushSupplier::suspend_connection_i (void) { this->suspended_ = 1; } ACE_INLINE void TAO_EC_ProxyPushSupplier::suspend_connection_locked (void) { ACE_GUARD_THROW_EX ( ACE_Lock, ace_mon, *this->lock_, CORBA::INTERNAL ()); // @@ RtecEventChannelAdmin::EventChannel::SYNCHRONIZATION_ERROR ()); this->suspend_connection_i (); } ACE_INLINE void TAO_EC_ProxyPushSupplier::resume_connection_i (void) { this->suspended_ = 0; } ACE_INLINE void TAO_EC_ProxyPushSupplier::resume_connection_locked (void) { ACE_GUARD_THROW_EX ( ACE_Lock, ace_mon, *this->lock_, CORBA::INTERNAL ()); // @@ RtecEventChannelAdmin::EventChannel::SYNCHRONIZATION_ERROR ()); this->resume_connection_i (); } ACE_INLINE CORBA::Boolean TAO_EC_ProxyPushSupplier::is_connected_i (void) const { return !CORBA::is_nil (this->consumer_.in ()); } ACE_INLINE CORBA::Boolean TAO_EC_ProxyPushSupplier::is_connected (void) const { ACE_GUARD_RETURN (ACE_Lock, ace_mon, *this->lock_, 0); return this->is_connected_i (); } ACE_INLINE CORBA::Boolean TAO_EC_ProxyPushSupplier::is_suspended (void) const { ACE_GUARD_RETURN (ACE_Lock, ace_mon, *this->lock_, 0); return this->suspended_; } ACE_INLINE RtecEventComm::PushConsumer_ptr TAO_EC_ProxyPushSupplier::consumer (void) const { ACE_GUARD_RETURN (ACE_Lock, ace_mon, *this->lock_, 0); return RtecEventComm::PushConsumer::_duplicate (this->consumer_.in ()); } ACE_INLINE void TAO_EC_ProxyPushSupplier::consumer_i (RtecEventComm::PushConsumer_ptr consumer) { this->consumer_ = consumer; } ACE_INLINE void TAO_EC_ProxyPushSupplier::consumer (RtecEventComm::PushConsumer_ptr consumer) { ACE_GUARD (ACE_Lock, ace_mon, *this->lock_); this->consumer_i (consumer); } ACE_INLINE const RtecEventChannelAdmin::ConsumerQOS& TAO_EC_ProxyPushSupplier::subscriptions (void) const { // @@ TODO There should be a better way to signal errors here. ACE_GUARD_RETURN (ACE_Lock, ace_mon, *this->lock_, this->qos_); return this->qos_; } TAO_END_VERSIONED_NAMESPACE_DECL
23.404255
79
0.749091
cflowe
fd728e771c59ecfe46e03ea25061b9de7d356cc2
827
cpp
C++
sem2/sda/Laborator4/Lab4/Lab4/Lab4/TestScurt.cpp
itsbratu/bachelor
b3bcae07fc8297fb0557a4bf752b20c6104c2563
[ "MIT" ]
null
null
null
sem2/sda/Laborator4/Lab4/Lab4/Lab4/TestScurt.cpp
itsbratu/bachelor
b3bcae07fc8297fb0557a4bf752b20c6104c2563
[ "MIT" ]
null
null
null
sem2/sda/Laborator4/Lab4/Lab4/Lab4/TestScurt.cpp
itsbratu/bachelor
b3bcae07fc8297fb0557a4bf752b20c6104c2563
[ "MIT" ]
null
null
null
#include <assert.h> #include "DO.h" #include "Iterator.h" #include <exception> using namespace std; bool relatie1(TCheie cheie1, TCheie cheie2) { if (cheie1 <= cheie2) { return true; } else { return false; } } void testAll() { DO dictOrd = DO(relatie1); assert(dictOrd.dim() == 0); assert(dictOrd.vid()); dictOrd.adauga(1, 2); assert(dictOrd.dim() == 1); assert(!dictOrd.vid()); assert(dictOrd.cauta(1) != NULL_TVALOARE); TValoare v = dictOrd.adauga(1, 3); assert(v == 2); assert(dictOrd.cauta(1) == 3); Iterator it = dictOrd.iterator(); it.prim(); while (it.valid()) { TElem e = it.element(); assert(e.second != NULL_TVALOARE); it.urmator(); } assert(dictOrd.sterge(1) == 3); assert(dictOrd.vid()); }
20.675
46
0.571947
itsbratu
fd7346af94f38b65d71e77985c6fc30d0c1a0b07
1,315
cpp
C++
src/util/game_loop.cpp
Paul-Hubert/vulkan_sdf_marcher
3905c3d41f534de6e4144ebc60c38a18bc6a1cb3
[ "MIT" ]
1
2021-11-26T05:00:32.000Z
2021-11-26T05:00:32.000Z
src/util/game_loop.cpp
Paul-Hubert/vulkan_sdf_marcher
3905c3d41f534de6e4144ebc60c38a18bc6a1cb3
[ "MIT" ]
null
null
null
src/util/game_loop.cpp
Paul-Hubert/vulkan_sdf_marcher
3905c3d41f534de6e4144ebc60c38a18bc6a1cb3
[ "MIT" ]
null
null
null
#include "game_loop.h" #include <chrono> #include <thread> #include <iostream> using namespace std::chrono_literals; // we use a fixed timestep of 1 / (60 fps) = 16 milliseconds constexpr std::chrono::nanoseconds timestep(16666666ns); void GameLoop::run(std::function<void(float)> update) { using clock = std::chrono::high_resolution_clock; std::chrono::nanoseconds total_frame_time = timestep; std::chrono::nanoseconds sleepy_time = timestep; int num = 0; std::chrono::nanoseconds sum = 0ns; while(running) { auto start = clock::now(); update(total_frame_time.count() / 1000000.f); auto update_duration = std::chrono::duration_cast<std::chrono::nanoseconds> (clock::now() - start); sleepy_time = timestep - update_duration - (total_frame_time - sleepy_time - update_duration); std::this_thread::sleep_for(sleepy_time); total_frame_time = std::chrono::duration_cast<std::chrono::nanoseconds> (clock::now() - start); num++; sum += total_frame_time; if (num >= 120) { std::cout << 1000000000.f / (sum.count()/num) << " fps" << std::endl; num = 0; sum = 0ns; } } } void GameLoop::setQuitting() { running = false; }
25.288462
107
0.614449
Paul-Hubert
fd74d7a645e78d29cffcd3b134de025abd4490d2
1,348
cpp
C++
VSProject/LeetCodeSol/Src/MergeTwoSortedListsSolution.cpp
wangxiaotao1980/leetCodeCPP
1806c00cd89eacddbdd20a7c33875f54400a20a8
[ "MIT" ]
null
null
null
VSProject/LeetCodeSol/Src/MergeTwoSortedListsSolution.cpp
wangxiaotao1980/leetCodeCPP
1806c00cd89eacddbdd20a7c33875f54400a20a8
[ "MIT" ]
null
null
null
VSProject/LeetCodeSol/Src/MergeTwoSortedListsSolution.cpp
wangxiaotao1980/leetCodeCPP
1806c00cd89eacddbdd20a7c33875f54400a20a8
[ "MIT" ]
null
null
null
/******************************************************************************************* * @file MergeTwoSortedListsSolution.cpp 2015\12\7 18:00:31 $ * @author Wang Xiaotao<wangxiaotao1980@gmail.com> (中文编码测试) * @note LeetCode No.21 Merge Two Sorted Lists *******************************************************************************************/ #include "MergeTwoSortedListsSolution.hpp" #include "Struct.hpp" // ------------------------------------------------------------------------------------------ // LeetCode No.21 Merge Two Sorted Lists ListNode* MergeTwoSortedListsSolution::mergeTwoLists(ListNode* l1, ListNode* l2) { ListNode* pRealHead = new ListNode(0); ListNode* pCurrent = pRealHead; while (l1 && l2) { if ((l1->val) > (l2->val)) { pCurrent->next = l2; pCurrent = pCurrent->next; l2 = l2->next; } else { pCurrent->next = l1; pCurrent = pCurrent->next; l1 = l1->next; } } if (l1) { pCurrent->next = l1; } if (l2) { pCurrent->next = l2; } ListNode* pResult = pRealHead->next; delete pRealHead; return pResult; } // // ------------------------------------------------------------------------------------------
28.680851
94
0.396884
wangxiaotao1980
fd76422330862fd1ee98feb18e6f9351912ecdac
2,194
cc
C++
asylo/platform/common/debug_strings_test.cc
kevin405/mosl_vsgx_migration
76ddd438c8caad1051ea9a7e2040bf6ccee996a2
[ "Apache-2.0" ]
1
2019-01-13T21:39:32.000Z
2019-01-13T21:39:32.000Z
asylo/platform/common/debug_strings_test.cc
kevin405/mosl_vsgx_migration
76ddd438c8caad1051ea9a7e2040bf6ccee996a2
[ "Apache-2.0" ]
null
null
null
asylo/platform/common/debug_strings_test.cc
kevin405/mosl_vsgx_migration
76ddd438c8caad1051ea9a7e2040bf6ccee996a2
[ "Apache-2.0" ]
1
2019-01-02T22:04:21.000Z
2019-01-02T22:04:21.000Z
/* * * Copyright 2018 Asylo 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 "asylo/platform/common/debug_strings.h" #include <gmock/gmock.h> #include <gtest/gtest.h> namespace asylo { namespace { using ::testing::Eq; using ::testing::StrEq; TEST(DebugStringsTest, Null) { EXPECT_THAT(buffer_to_hex_string(nullptr, 0), StrEq("null")); } TEST(DebugStringsTest, ZeroLength) { char buffer[] = "abc"; EXPECT_THAT(buffer_to_hex_string(static_cast<const void *>(buffer), 0), StrEq("[]")); } TEST(DebugStringsTest, NegativeLength) { char buffer[] = "abc"; EXPECT_THAT(buffer_to_hex_string(static_cast<const void *>(buffer), -4), StrEq("[ERROR: negative length -4]")); } TEST(DebugStringsTest, SingletonNullBuffer) { uint8_t buffer[] = {0}; ASSERT_THAT(sizeof(buffer), Eq(1)); EXPECT_THAT(buffer_to_hex_string(static_cast<const void *>(buffer), 1), StrEq("[0x00]")); } TEST(DebugStringsTest, NonemptyBufferDecimalDigits) { char buffer[] = "ABC"; ASSERT_THAT(sizeof(buffer), Eq(4)); EXPECT_THAT(buffer_to_hex_string(static_cast<const void *>(buffer), 4), StrEq("[0x41424300]")); } TEST(DebugStringsTest, NonemptyBufferHighDigits) { char buffer[] = "[-]"; ASSERT_THAT(sizeof(buffer), Eq(4)); EXPECT_THAT(buffer_to_hex_string(static_cast<const void *>(buffer), 4), StrEq("[0x5B2D5D00]")); } TEST(DebugStringsTest, NonemptyNullBuffer) { uint8_t buffer[] = {0, 0, 0, 0}; ASSERT_THAT(sizeof(buffer), Eq(4)); EXPECT_THAT(buffer_to_hex_string(static_cast<const void *>(buffer), 4), StrEq("[0x00000000]")); } } // namespace } // namespace asylo
29.253333
75
0.690064
kevin405
fd77e307f7ff4ebbe739acd4ba3d54542df12a31
3,411
cpp
C++
firmware/lib/LFO.cpp
JordanAceto/whooshy_sound
29056707c27413bac8fc56eed32da390e117dc4f
[ "CC-BY-4.0", "MIT" ]
null
null
null
firmware/lib/LFO.cpp
JordanAceto/whooshy_sound
29056707c27413bac8fc56eed32da390e117dc4f
[ "CC-BY-4.0", "MIT" ]
6
2021-07-13T22:25:55.000Z
2022-01-16T15:16:09.000Z
firmware/lib/LFO.cpp
JordanAceto/whooshy_sound
29056707c27413bac8fc56eed32da390e117dc4f
[ "CC-BY-4.0", "MIT" ]
null
null
null
#include "LFO.hpp" #include "lookup_tables.hpp" #include "PRNG.hpp" #include "wave_scanner.hpp" LFO::LFO(uint32_t sample_rate) : sample_rate(sample_rate) {} void LFO::tick(void) { phase_accumulator += tuning_word; updateWaveshapes(); } void LFO::setInput(Input_t input_type, int value) { input[input_type] = value; if (input_type == FREQ_mHz) { updateTuningWord(); } } int LFO::getOutput(Shape_t output_type) { return output[output_type]; } void LFO::updateTuningWord(void) { /* * In DDS, the tuning word M = (2^N * f_out)/(f_c), where N is the number of * bits in the accumulator, f_out is the desired output frequency, and f_c * is the sample rate. * * Since the LFO frequency is measured in milli Hertz, this becomes * M = (2^N * f_out_mHz)/(f_c * 1000) * * Note that the MAX_ACCUMULATOR value is actually equal to 2^N - 1, but this * off-by-one does not meaningfully impact the calculation. */ const uint32_t two_to_the_N = ACCUMULATOR_FULL_SCALE; const uint32_t f_c = sample_rate; const uint32_t f_out_mHz = input[FREQ_mHz]; const uint32_t mSec_per_sec = 1000u; const uint32_t M = (two_to_the_N / (f_c * mSec_per_sec)) * f_out_mHz; tuning_word = M; } void LFO::updateWaveshapes(void) { updateTriangle(); updateSine(); updateSquare(); updateRandom(); updateCrossfade(); } void LFO::updateSine(void) { const uint32_t lut_idx = phase_accumulator >> NUM_FRACTIONAL_BITS_IN_ACCUMULATOR; const uint32_t next_idx = (lut_idx + 1u) % SINE_LOOKUP_TABLE_SIZE; const uint32_t fraction = phase_accumulator & ACCUMULATOR_FRACTION_MASK; output[SINE] = linearInterpolation(Lookup_Tables::SINE_LUT[lut_idx], Lookup_Tables::SINE_LUT[next_idx], fraction); } void LFO::updateTriangle(void) { // keep the tri in phase with the sine const uint32_t phase_shifted_accum = phase_accumulator + ACCUMULATOR_QUARTER_SCALE; // derive the triangle directly from the phase accumulator if (phase_shifted_accum <= ACCUMULATOR_HALF_SCALE) { output[TRIANGLE] = (phase_shifted_accum >> (ACCUMULATOR_BIT_WIDTH - OUTPUT_NUM_BITS - 1u)) - OUTPUT_MAX_VAL; } else { output[TRIANGLE] = ((ACCUMULATOR_FULL_SCALE - phase_shifted_accum) >> (ACCUMULATOR_BIT_WIDTH - OUTPUT_NUM_BITS - 1u)) - OUTPUT_MAX_VAL; } } void LFO::updateSquare(void) { output[SQUARE] = phase_accumulator < ACCUMULATOR_HALF_SCALE ? OUTPUT_MAX_VAL : OUTPUT_MIN_VAL; } void LFO::updateRandom(void) { // the LFO "feels" better if the random signal updates at twice the base frequency const uint32_t double_time_accum = phase_accumulator << 1u; static uint32_t last_double_time_accum; const bool accum_rolled_over = double_time_accum < last_double_time_accum; if (accum_rolled_over) { // get a random sample in the bounds of the LFO range, centered around zero const int random_sample = (PRNG::nextRand() & ((1 << OUTPUT_NUM_BITS) - 1)) - OUTPUT_MAX_VAL; output[RANDOM] = random_sample; } last_double_time_accum = double_time_accum; } void LFO::updateCrossfade(void) { output[CROSSFADED] = Wave_Scanner::crossfade(output, NUM_LFO_SHAPES - 1, input[WAVE_SCAN]); } int LFO::linearInterpolation(int y1, int y2, uint32_t fraction) { return y1 + (fraction * (y2 - y1)) / ACCUMULATOR_FRACTION_MASK; }
28.90678
143
0.703313
JordanAceto
fd78343ffbeccb87480e5cc38f8119a8a2678c4e
13,674
cc
C++
be/src/util/memory-metrics.cc
kexianda/impala
2e60347868d7e719d80401f9abcbe971e659502b
[ "Apache-2.0" ]
null
null
null
be/src/util/memory-metrics.cc
kexianda/impala
2e60347868d7e719d80401f9abcbe971e659502b
[ "Apache-2.0" ]
null
null
null
be/src/util/memory-metrics.cc
kexianda/impala
2e60347868d7e719d80401f9abcbe971e659502b
[ "Apache-2.0" ]
null
null
null
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. #include "util/memory-metrics.h" #include <boost/algorithm/string.hpp> #include <gutil/strings/substitute.h> #include "runtime/bufferpool/buffer-pool.h" #include "runtime/bufferpool/reservation-tracker.h" #include "util/jni-util.h" #include "util/mem-info.h" #include "util/time.h" using boost::algorithm::to_lower; using namespace impala; using namespace strings; DECLARE_bool(mmap_buffers); SumGauge* AggregateMemoryMetrics::TOTAL_USED = nullptr; IntGauge* AggregateMemoryMetrics::NUM_MAPS = nullptr; IntGauge* AggregateMemoryMetrics::MAPPED_BYTES = nullptr; IntGauge* AggregateMemoryMetrics::RSS = nullptr; IntGauge* AggregateMemoryMetrics::ANON_HUGE_PAGE_BYTES = nullptr; StringProperty* AggregateMemoryMetrics::THP_ENABLED = nullptr; StringProperty* AggregateMemoryMetrics::THP_DEFRAG = nullptr; StringProperty* AggregateMemoryMetrics::THP_KHUGEPAGED_DEFRAG = nullptr; TcmallocMetric* TcmallocMetric::BYTES_IN_USE = nullptr; TcmallocMetric* TcmallocMetric::PAGEHEAP_FREE_BYTES = nullptr; TcmallocMetric* TcmallocMetric::TOTAL_BYTES_RESERVED = nullptr; TcmallocMetric* TcmallocMetric::PAGEHEAP_UNMAPPED_BYTES = nullptr; TcmallocMetric::PhysicalBytesMetric* TcmallocMetric::PHYSICAL_BYTES_RESERVED = nullptr; SanitizerMallocMetric* SanitizerMallocMetric::BYTES_ALLOCATED = nullptr; BufferPoolMetric* BufferPoolMetric::LIMIT = nullptr; BufferPoolMetric* BufferPoolMetric::SYSTEM_ALLOCATED = nullptr; BufferPoolMetric* BufferPoolMetric::RESERVED = nullptr; BufferPoolMetric* BufferPoolMetric::UNUSED_RESERVATION_BYTES = nullptr; BufferPoolMetric* BufferPoolMetric::NUM_FREE_BUFFERS = nullptr; BufferPoolMetric* BufferPoolMetric::FREE_BUFFER_BYTES = nullptr; BufferPoolMetric* BufferPoolMetric::CLEAN_PAGES_LIMIT = nullptr; BufferPoolMetric* BufferPoolMetric::NUM_CLEAN_PAGES = nullptr; BufferPoolMetric* BufferPoolMetric::CLEAN_PAGE_BYTES = nullptr; TcmallocMetric* TcmallocMetric::CreateAndRegister( MetricGroup* metrics, const string& key, const string& tcmalloc_var) { return metrics->RegisterMetric(new TcmallocMetric(MetricDefs::Get(key), tcmalloc_var)); } Status impala::RegisterMemoryMetrics(MetricGroup* metrics, bool register_jvm_metrics, ReservationTracker* global_reservations, BufferPool* buffer_pool) { if (global_reservations != nullptr) { DCHECK(buffer_pool != nullptr); RETURN_IF_ERROR(BufferPoolMetric::InitMetrics( metrics->GetOrCreateChildGroup("buffer-pool"), global_reservations, buffer_pool)); } // Add compound metrics that track totals across malloc and the buffer pool. // total-used should track the total physical memory in use. vector<IntGauge*> used_metrics; if (FLAGS_mmap_buffers && global_reservations != nullptr) { // If we mmap() buffers, the buffers are not allocated via malloc. Ensure they are // properly tracked. used_metrics.push_back(BufferPoolMetric::SYSTEM_ALLOCATED); } #if defined(ADDRESS_SANITIZER) || defined(THREAD_SANITIZER) SanitizerMallocMetric::BYTES_ALLOCATED = metrics->RegisterMetric( new SanitizerMallocMetric(MetricDefs::Get("sanitizer-total-bytes-allocated"))); used_metrics.push_back(SanitizerMallocMetric::BYTES_ALLOCATED); #else MetricGroup* tcmalloc_metrics = metrics->GetOrCreateChildGroup("tcmalloc"); // We rely on TCMalloc for our global memory metrics, so skip setting them up // if we're not using TCMalloc. TcmallocMetric::BYTES_IN_USE = TcmallocMetric::CreateAndRegister( tcmalloc_metrics, "tcmalloc.bytes-in-use", "generic.current_allocated_bytes"); TcmallocMetric::TOTAL_BYTES_RESERVED = TcmallocMetric::CreateAndRegister( tcmalloc_metrics, "tcmalloc.total-bytes-reserved", "generic.heap_size"); TcmallocMetric::PAGEHEAP_FREE_BYTES = TcmallocMetric::CreateAndRegister( tcmalloc_metrics, "tcmalloc.pageheap-free-bytes", "tcmalloc.pageheap_free_bytes"); TcmallocMetric::PAGEHEAP_UNMAPPED_BYTES = TcmallocMetric::CreateAndRegister(tcmalloc_metrics, "tcmalloc.pageheap-unmapped-bytes", "tcmalloc.pageheap_unmapped_bytes"); TcmallocMetric::PHYSICAL_BYTES_RESERVED = tcmalloc_metrics->RegisterMetric(new TcmallocMetric::PhysicalBytesMetric( MetricDefs::Get("tcmalloc.physical-bytes-reserved"))); used_metrics.push_back(TcmallocMetric::PHYSICAL_BYTES_RESERVED); #endif MetricGroup* aggregate_metrics = metrics->GetOrCreateChildGroup("memory"); AggregateMemoryMetrics::TOTAL_USED = aggregate_metrics->RegisterMetric( new SumGauge(MetricDefs::Get("memory.total-used"), used_metrics)); if (register_jvm_metrics) { RETURN_IF_ERROR(JvmMetric::InitMetrics(metrics->GetOrCreateChildGroup("jvm"))); } if (MemInfo::HaveSmaps()) { AggregateMemoryMetrics::NUM_MAPS = aggregate_metrics->AddGauge("memory.num-maps", 0U); AggregateMemoryMetrics::MAPPED_BYTES = aggregate_metrics->AddGauge("memory.mapped-bytes", 0U); AggregateMemoryMetrics::RSS = aggregate_metrics->AddGauge("memory.rss", 0U); AggregateMemoryMetrics::ANON_HUGE_PAGE_BYTES = aggregate_metrics->AddGauge("memory.anon-huge-page-bytes", 0U); } ThpConfig thp_config = MemInfo::ParseThpConfig(); AggregateMemoryMetrics::THP_ENABLED = aggregate_metrics->AddProperty("memory.thp.enabled", thp_config.enabled); AggregateMemoryMetrics::THP_DEFRAG = aggregate_metrics->AddProperty("memory.thp.defrag", thp_config.defrag); AggregateMemoryMetrics::THP_KHUGEPAGED_DEFRAG = aggregate_metrics->AddProperty( "memory.thp.khugepaged-defrag", thp_config.khugepaged_defrag); AggregateMemoryMetrics::Refresh(); return Status::OK(); } void AggregateMemoryMetrics::Refresh() { if (NUM_MAPS != nullptr) { // Only call ParseSmaps() if the metrics were created. MappedMemInfo map_info = MemInfo::ParseSmaps(); NUM_MAPS->SetValue(map_info.num_maps); MAPPED_BYTES->SetValue(map_info.size_kb * 1024); RSS->SetValue(map_info.rss_kb * 1024); ANON_HUGE_PAGE_BYTES->SetValue(map_info.anon_huge_pages_kb * 1024); } ThpConfig thp_config = MemInfo::ParseThpConfig(); THP_ENABLED->SetValue(thp_config.enabled); THP_DEFRAG->SetValue(thp_config.defrag); THP_KHUGEPAGED_DEFRAG->SetValue(thp_config.khugepaged_defrag); } JvmMetric* JvmMetric::CreateAndRegister(MetricGroup* metrics, const string& key, const string& pool_name, JvmMetric::JvmMetricType type) { string pool_name_for_key = pool_name; to_lower(pool_name_for_key); replace(pool_name_for_key.begin(), pool_name_for_key.end(), ' ', '-'); return metrics->RegisterMetric(new JvmMetric(MetricDefs::Get(key, pool_name_for_key), pool_name, type)); } JvmMetric::JvmMetric(const TMetricDef& def, const string& mempool_name, JvmMetricType type) : IntGauge(def, 0) { mempool_name_ = mempool_name; metric_type_ = type; } Status JvmMetric::InitMetrics(MetricGroup* metrics) { DCHECK(metrics != nullptr); TGetJvmMetricsRequest request; request.get_all = true; TGetJvmMetricsResponse response; RETURN_IF_ERROR(JniUtil::GetJvmMetrics(request, &response)); for (const TJvmMemoryPool& usage: response.memory_pools) { JvmMetric::CreateAndRegister(metrics, "jvm.$0.max-usage-bytes", usage.name, MAX); JvmMetric::CreateAndRegister(metrics, "jvm.$0.current-usage-bytes", usage.name, CURRENT); JvmMetric::CreateAndRegister(metrics, "jvm.$0.committed-usage-bytes", usage.name, COMMITTED); JvmMetric::CreateAndRegister(metrics, "jvm.$0.init-usage-bytes", usage.name, INIT); JvmMetric::CreateAndRegister(metrics, "jvm.$0.peak-max-usage-bytes", usage.name, PEAK_MAX); JvmMetric::CreateAndRegister(metrics, "jvm.$0.peak-current-usage-bytes", usage.name, PEAK_CURRENT); JvmMetric::CreateAndRegister(metrics, "jvm.$0.peak-committed-usage-bytes", usage.name, PEAK_COMMITTED); JvmMetric::CreateAndRegister(metrics, "jvm.$0.peak-init-usage-bytes", usage.name, PEAK_INIT); } return Status::OK(); } int64_t JvmMetric::GetValue() { TGetJvmMetricsRequest request; request.get_all = false; request.__set_memory_pool(mempool_name_); TGetJvmMetricsResponse response; if (!JniUtil::GetJvmMetrics(request, &response).ok()) return 0; if (response.memory_pools.size() != 1) return 0; TJvmMemoryPool& pool = response.memory_pools[0]; DCHECK(pool.name == mempool_name_); switch (metric_type_) { case MAX: return pool.max; case INIT: return pool.init; case CURRENT: return pool.used; case COMMITTED: return pool.committed; case PEAK_MAX: return pool.peak_max; case PEAK_INIT: return pool.peak_init; case PEAK_CURRENT: return pool.peak_used; case PEAK_COMMITTED: return pool.peak_committed; default: DCHECK(false) << "Unknown JvmMetricType: " << metric_type_; } return 0; } Status BufferPoolMetric::InitMetrics(MetricGroup* metrics, ReservationTracker* global_reservations, BufferPool* buffer_pool) { LIMIT = metrics->RegisterMetric( new BufferPoolMetric(MetricDefs::Get("buffer-pool.limit"), BufferPoolMetricType::LIMIT, global_reservations, buffer_pool)); SYSTEM_ALLOCATED = metrics->RegisterMetric( new BufferPoolMetric(MetricDefs::Get("buffer-pool.system-allocated"), BufferPoolMetricType::SYSTEM_ALLOCATED, global_reservations, buffer_pool)); RESERVED = metrics->RegisterMetric( new BufferPoolMetric(MetricDefs::Get("buffer-pool.reserved"), BufferPoolMetricType::RESERVED, global_reservations, buffer_pool)); UNUSED_RESERVATION_BYTES = metrics->RegisterMetric( new BufferPoolMetric(MetricDefs::Get("buffer-pool.unused-reservation-bytes"), BufferPoolMetricType::UNUSED_RESERVATION_BYTES, global_reservations, buffer_pool)); NUM_FREE_BUFFERS = metrics->RegisterMetric( new BufferPoolMetric(MetricDefs::Get("buffer-pool.free-buffers"), BufferPoolMetricType::NUM_FREE_BUFFERS, global_reservations, buffer_pool)); FREE_BUFFER_BYTES = metrics->RegisterMetric( new BufferPoolMetric(MetricDefs::Get("buffer-pool.free-buffer-bytes"), BufferPoolMetricType::FREE_BUFFER_BYTES, global_reservations, buffer_pool)); CLEAN_PAGES_LIMIT = metrics->RegisterMetric( new BufferPoolMetric(MetricDefs::Get("buffer-pool.clean-pages-limit"), BufferPoolMetricType::CLEAN_PAGES_LIMIT, global_reservations, buffer_pool)); NUM_CLEAN_PAGES = metrics->RegisterMetric( new BufferPoolMetric(MetricDefs::Get("buffer-pool.clean-pages"), BufferPoolMetricType::NUM_CLEAN_PAGES, global_reservations, buffer_pool)); CLEAN_PAGE_BYTES = metrics->RegisterMetric( new BufferPoolMetric(MetricDefs::Get("buffer-pool.clean-page-bytes"), BufferPoolMetricType::CLEAN_PAGE_BYTES, global_reservations, buffer_pool)); return Status::OK(); } BufferPoolMetric::BufferPoolMetric(const TMetricDef& def, BufferPoolMetricType type, ReservationTracker* global_reservations, BufferPool* buffer_pool) : IntGauge(def, 0), type_(type), global_reservations_(global_reservations), buffer_pool_(buffer_pool) {} int64_t BufferPoolMetric::GetValue() { // IMPALA-6362: we have to be careful that none of the below calls to ReservationTracker // methods acquire ReservationTracker::lock_ to avoid a potential circular dependency // with MemTracker::child_trackers_lock_, which may be held when refreshing MemTracker // consumption. switch (type_) { case BufferPoolMetricType::LIMIT: return buffer_pool_->GetSystemBytesLimit(); case BufferPoolMetricType::SYSTEM_ALLOCATED: return buffer_pool_->GetSystemBytesAllocated(); case BufferPoolMetricType::RESERVED: return global_reservations_->GetReservation(); case BufferPoolMetricType::UNUSED_RESERVATION_BYTES: { // Estimate the unused reservation based on other aggregate values, defined as // the total bytes of reservation where there is no corresponding buffer in use // by a client. Buffers are either in-use, free buffers, or attached to clean pages. int64_t total_used_reservation = buffer_pool_->GetSystemBytesAllocated() - buffer_pool_->GetFreeBufferBytes() - buffer_pool_->GetCleanPageBytes(); return global_reservations_->GetReservation() - total_used_reservation; } case BufferPoolMetricType::NUM_FREE_BUFFERS: return buffer_pool_->GetNumFreeBuffers(); case BufferPoolMetricType::FREE_BUFFER_BYTES: return buffer_pool_->GetFreeBufferBytes(); case BufferPoolMetricType::CLEAN_PAGES_LIMIT: return buffer_pool_->GetCleanPageBytesLimit(); case BufferPoolMetricType::NUM_CLEAN_PAGES: return buffer_pool_->GetNumCleanPages(); case BufferPoolMetricType::CLEAN_PAGE_BYTES: return buffer_pool_->GetCleanPageBytes(); default: DCHECK(false) << "Unknown BufferPoolMetricType: " << static_cast<int>(type_); } return 0; }
45.128713
90
0.762835
kexianda
fd788cf6029b78c1e8987ddba8568ed05cc64ddd
353
cpp
C++
source/realtimertfilters/realtimertfilters-app/sources/renderpasses/Renderpass.cpp
Realtime-RT-Filters/Realtime-RT-Filters
aa4d44d9f2bbc795bea63358c246fb94465bdde2
[ "Zlib", "Apache-2.0", "MIT-0", "MIT" ]
null
null
null
source/realtimertfilters/realtimertfilters-app/sources/renderpasses/Renderpass.cpp
Realtime-RT-Filters/Realtime-RT-Filters
aa4d44d9f2bbc795bea63358c246fb94465bdde2
[ "Zlib", "Apache-2.0", "MIT-0", "MIT" ]
null
null
null
source/realtimertfilters/realtimertfilters-app/sources/renderpasses/Renderpass.cpp
Realtime-RT-Filters/Realtime-RT-Filters
aa4d44d9f2bbc795bea63358c246fb94465bdde2
[ "Zlib", "Apache-2.0", "MIT-0", "MIT" ]
null
null
null
#include "../../headers/renderpasses/Renderpass.hpp" #include "../../headers/RTFilterDemo.hpp" namespace rtf { void Renderpass::setRtFilterDemo(RTFilterDemo* rtFilterDemo) { m_rtFilterDemo = rtFilterDemo; m_vulkanDevice = rtFilterDemo->vulkanDevice; m_attachmentManager = rtFilterDemo->m_attachmentManager; m_rtFilterDemo = rtFilterDemo; } }
27.153846
61
0.773371
Realtime-RT-Filters
fd79063c1974456a021f9436ca1fce5b5a36dc50
2,664
cpp
C++
src/compiler/trainingdeps.cpp
petabricks/petabricks
b498b93880b0c4ac3924ddb82cff2e6541e60bd1
[ "MIT" ]
10
2015-03-12T18:09:57.000Z
2022-03-17T03:18:36.000Z
src/compiler/trainingdeps.cpp
petabricks/petabricks
b498b93880b0c4ac3924ddb82cff2e6541e60bd1
[ "MIT" ]
2
2021-01-12T15:12:21.000Z
2022-03-22T07:47:37.000Z
src/compiler/trainingdeps.cpp
petabricks/petabricks
b498b93880b0c4ac3924ddb82cff2e6541e60bd1
[ "MIT" ]
3
2017-06-28T06:01:03.000Z
2021-01-12T15:05:34.000Z
/***************************************************************************** * Copyright (C) 2008-2011 Massachusetts Institute of Technology * * * * 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 * * * * This source code is part of the PetaBricks project: * * http://projects.csail.mit.edu/petabricks/ * * * *****************************************************************************/ #include "trainingdeps.h" std::map<std::string, std::vector<std::string> > petabricks::TrainingDeps::_callgraph; namespace petabricks { void TrainingDeps::emitRules(std::string& choicename, const std::vector<RulePtr>& sortedRules) { _os << " <rules choicename=\"" << choicename << "\">\n"; int index = 0; for (std::vector<RulePtr>::const_iterator i = sortedRules.begin(), e = sortedRules.end(); i != e; ++i) { _os << " <rule index=\"" << index << "\" label=\"" << (*i)->getLabel() << "\" />\n"; ++index; } _os << " </rules>\n"; } }
56.680851
86
0.482357
petabricks
fd7bbf7288a28fe0bf676a99f0b27cdf30f4f90b
458
cpp
C++
Project-Euler/206 Concealed Square/206temp.cpp
kishorevarma369/Competitive-Programming
f2fd01b0168cb2908f2cc1794ba2c8a461b06838
[ "MIT" ]
1
2019-05-20T14:38:05.000Z
2019-05-20T14:38:05.000Z
Project-Euler/206 Concealed Square/206temp.cpp
kishorevarma369/Competitive-Programming
f2fd01b0168cb2908f2cc1794ba2c8a461b06838
[ "MIT" ]
null
null
null
Project-Euler/206 Concealed Square/206temp.cpp
kishorevarma369/Competitive-Programming
f2fd01b0168cb2908f2cc1794ba2c8a461b06838
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; int main(int argc, char const *argv[]) { char s[100]; long long int a=138902663,k,l,i=8; while(1) { k=(a*a)/100,i=8; while(k!=0) { if(k%10!=i--) break; k/=100; } if(k==0) break; i=8; a-=6; k=(a*a)/100; while(k!=0) { if((k%10)!=i) break; i--; k/=100; } if(k==0) break; a-=4; } cout<<"a="<<a<<"0\na*a="<<a*a; return 0; }
13.878788
38
0.436681
kishorevarma369
fd81e819085ab0decd461d03c01c838a95c9dfe8
9,537
cpp
C++
renderers/samplerrenderer.cpp
cathook/rendering_final_proj
d0c147b563d6949839983bf38317c81367e2ed4c
[ "BSD-2-Clause" ]
null
null
null
renderers/samplerrenderer.cpp
cathook/rendering_final_proj
d0c147b563d6949839983bf38317c81367e2ed4c
[ "BSD-2-Clause" ]
null
null
null
renderers/samplerrenderer.cpp
cathook/rendering_final_proj
d0c147b563d6949839983bf38317c81367e2ed4c
[ "BSD-2-Clause" ]
null
null
null
/* pbrt source code Copyright(c) 1998-2012 Matt Pharr and Greg Humphreys. This file is part of pbrt. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ // renderers/samplerrenderer.cpp* #include "stdafx.h" #include "renderers/samplerrenderer.h" #include "scene.h" #include "film.h" #include "volume.h" #include "sampler.h" #include "integrator.h" #include "progressreporter.h" #include "camera.h" #include "intersection.h" static uint32_t hash(char *key, uint32_t len) { uint32_t hash = 0, i; for (hash=0, i=0; i<len; ++i) { hash += key[i]; hash += (hash << 10); hash ^= (hash >> 6); } hash += (hash << 3); hash ^= (hash >> 11); hash += (hash << 15); return hash; } // SamplerRendererTask Definitions void SamplerRendererTask::Run() { PBRT_STARTED_RENDERTASK(taskNum); // Get sub-_Sampler_ for _SamplerRendererTask_ Sampler *sampler = mainSampler->GetSubSampler(taskNum, taskCount); if (!sampler) { reporter.Update(); PBRT_FINISHED_RENDERTASK(taskNum); return; } // Declare local variables used for rendering loop MemoryArena arena; RNG rng(taskNum); // Allocate space for samples and intersections int maxSamples = sampler->MaximumSampleCount(); Sample *samples = origSample->Duplicate(maxSamples); RayDifferential *rays = new RayDifferential[maxSamples]; Spectrum *Ls = new Spectrum[maxSamples]; Spectrum *Ts = new Spectrum[maxSamples]; Intersection *isects = new Intersection[maxSamples]; // Get samples from _Sampler_ and update image int sampleCount; while ((sampleCount = sampler->GetMoreSamples(samples, rng)) > 0) { // Generate camera rays and compute radiance along rays for (int i = 0; i < sampleCount; ++i) { // Find camera ray for _sample[i]_ PBRT_STARTED_GENERATING_CAMERA_RAY(&samples[i]); float rayWeight = camera->GenerateRayDifferential(samples[i], &rays[i]); rays[i].ScaleDifferentials(1.f / sqrtf(sampler->samplesPerPixel)); PBRT_FINISHED_GENERATING_CAMERA_RAY(&samples[i], &rays[i], rayWeight); // Evaluate radiance along camera ray PBRT_STARTED_CAMERA_RAY_INTEGRATION(&rays[i], &samples[i]); if (visualizeObjectIds) { if (rayWeight > 0.f && scene->Intersect(rays[i], &isects[i])) { // random shading based on shape id... uint32_t ids[2] = { isects[i].shapeId, isects[i].primitiveId }; uint32_t h = hash((char *)ids, sizeof(ids)); float rgb[3] = { float(h & 0xff), float((h >> 8) & 0xff), float((h >> 16) & 0xff) }; Ls[i] = Spectrum::FromRGB(rgb); Ls[i] /= 255.f; } else Ls[i] = 0.f; } else { if (rayWeight > 0.f) Ls[i] = rayWeight * renderer->Li(scene, rays[i], &samples[i], rng, arena, &isects[i], &Ts[i]); else { Ls[i] = 0.f; Ts[i] = 1.f; } // Issue warning if unexpected radiance value returned if (Ls[i].HasNaNs()) { Error("Not-a-number radiance value returned " "for image sample. Setting to black."); Ls[i] = Spectrum(0.f); } else if (Ls[i].y() < -1e-5) { Error("Negative luminance value, %f, returned " "for image sample. Setting to black.", Ls[i].y()); Ls[i] = Spectrum(0.f); } else if (isinf(Ls[i].y())) { Error("Infinite luminance value returned " "for image sample. Setting to black."); Ls[i] = Spectrum(0.f); } } PBRT_FINISHED_CAMERA_RAY_INTEGRATION(&rays[i], &samples[i], &Ls[i]); } // Report sample results to _Sampler_, add contributions to image if (sampler->ReportResults(samples, rays, Ls, isects, sampleCount)) { for (int i = 0; i < sampleCount; ++i) { PBRT_STARTED_ADDING_IMAGE_SAMPLE(&samples[i], &rays[i], &Ls[i], &Ts[i]); camera->film->AddSample(samples[i], Ls[i]); PBRT_FINISHED_ADDING_IMAGE_SAMPLE(); } } // Free _MemoryArena_ memory from computing image sample values arena.FreeAll(); } // Clean up after _SamplerRendererTask_ is done with its image region camera->film->UpdateDisplay(sampler->xPixelStart, sampler->yPixelStart, sampler->xPixelEnd+1, sampler->yPixelEnd+1); delete sampler; delete[] samples; delete[] rays; delete[] Ls; delete[] Ts; delete[] isects; reporter.Update(); PBRT_FINISHED_RENDERTASK(taskNum); } // SamplerRenderer Method Definitions SamplerRenderer::SamplerRenderer(Sampler *s, Camera *c, SurfaceIntegrator *si, VolumeIntegrator *vi, bool visIds) { sampler = s; camera = c; surfaceIntegrator = si; volumeIntegrator = vi; visualizeObjectIds = visIds; } SamplerRenderer::~SamplerRenderer() { delete sampler; delete camera; delete surfaceIntegrator; delete volumeIntegrator; } void SamplerRenderer::Render(const Scene *scene) { PBRT_FINISHED_PARSING(); // Allow integrators to do preprocessing for the scene PBRT_STARTED_PREPROCESSING(); surfaceIntegrator->Preprocess(scene, camera, this); volumeIntegrator->Preprocess(scene, camera, this); PBRT_FINISHED_PREPROCESSING(); PBRT_STARTED_RENDERING(); // Allocate and initialize _sample_ Sample *sample = new Sample(sampler, surfaceIntegrator, volumeIntegrator, scene); // Create and launch _SamplerRendererTask_s for rendering image // Compute number of _SamplerRendererTask_s to create for rendering int nPixels = camera->film->xResolution * camera->film->yResolution; int nTasks = max(32 * NumSystemCores(), nPixels / (16*16)); nTasks = RoundUpPow2(nTasks); ProgressReporter reporter(nTasks, "Rendering"); vector<Task *> renderTasks; for (int i = 0; i < nTasks; ++i) renderTasks.push_back(new SamplerRendererTask(scene, this, camera, reporter, sampler, sample, visualizeObjectIds, nTasks-1-i, nTasks)); EnqueueTasks(renderTasks); WaitForAllTasks(); for (uint32_t i = 0; i < renderTasks.size(); ++i) delete renderTasks[i]; reporter.Done(); PBRT_FINISHED_RENDERING(); // Clean up after rendering and store final image delete sample; camera->film->WriteImage(); } Spectrum SamplerRenderer::Li(const Scene *scene, const RayDifferential &ray, const Sample *sample, RNG &rng, MemoryArena &arena, Intersection *isect, Spectrum *T) const { Assert(ray.time == sample->time); Assert(!ray.HasNaNs()); // Allocate local variables for _isect_ and _T_ if needed Spectrum localT; if (!T) T = &localT; Intersection localIsect; if (!isect) isect = &localIsect; Spectrum Li = 0.f; if (scene->Intersect(ray, isect)) Li = surfaceIntegrator->Li(scene, this, ray, *isect, sample, rng, arena); else { // Handle ray that doesn't intersect any geometry for (uint32_t i = 0; i < scene->lights.size(); ++i) Li += scene->lights[i]->Le(ray); } Spectrum Lvi = volumeIntegrator->Li(scene, this, ray, sample, rng, T, arena); return *T * Li + Lvi; } Spectrum SamplerRenderer::Transmittance(const Scene *scene, const RayDifferential &ray, const Sample *sample, RNG &rng, MemoryArena &arena) const { return volumeIntegrator->Transmittance(scene, this, ray, sample, rng, arena); }
36.965116
88
0.59893
cathook
fd823c10c00187180754b42fdfd38d4b830d51b6
46
cpp
C++
TEST/src/TestLaunch.cpp
Morderaccman/Test
31cd84e8994646851f89df7902acc97a9bf46692
[ "Apache-2.0" ]
null
null
null
TEST/src/TestLaunch.cpp
Morderaccman/Test
31cd84e8994646851f89df7902acc97a9bf46692
[ "Apache-2.0" ]
null
null
null
TEST/src/TestLaunch.cpp
Morderaccman/Test
31cd84e8994646851f89df7902acc97a9bf46692
[ "Apache-2.0" ]
null
null
null
#include "i4pch.h" #include "WinShipLinker.h"
15.333333
26
0.73913
Morderaccman
fd82721bbcfe09dafba648adedc4e83c294ba339
1,104
cpp
C++
lldb/source/Plugins/Process/Windows/Common/NativeRegisterContextWindows.cpp
dan-zheng/llvm-project
6b792850da0345274758c9260fda5df5e57ab486
[ "Apache-2.0" ]
765
2015-12-03T16:44:59.000Z
2022-03-07T12:41:10.000Z
lldb/source/Plugins/Process/Windows/Common/NativeRegisterContextWindows.cpp
dan-zheng/llvm-project
6b792850da0345274758c9260fda5df5e57ab486
[ "Apache-2.0" ]
1,815
2015-12-11T23:56:05.000Z
2020-01-10T19:28:43.000Z
lldb/source/Plugins/Process/Windows/Common/NativeRegisterContextWindows.cpp
dan-zheng/llvm-project
6b792850da0345274758c9260fda5df5e57ab486
[ "Apache-2.0" ]
284
2015-12-03T16:47:25.000Z
2022-03-12T05:39:48.000Z
//===-- NativeRegisterContextWindows.cpp ------------------------*- C++ -*-===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #include "lldb/Host/HostThread.h" #include "lldb/Host/windows/HostThreadWindows.h" #include "lldb/Host/windows/windows.h" #include "lldb/Utility/Log.h" #include "NativeRegisterContextWindows.h" #include "NativeThreadWindows.h" #include "ProcessWindowsLog.h" using namespace lldb; using namespace lldb_private; NativeRegisterContextWindows::NativeRegisterContextWindows( NativeThreadProtocol &thread, RegisterInfoInterface *reg_info_interface_p) : NativeRegisterContextRegisterInfo(thread, reg_info_interface_p) {} lldb::thread_t NativeRegisterContextWindows::GetThreadHandle() const { auto wthread = static_cast<NativeThreadWindows *>(&m_thread); return wthread->GetHostThread().GetNativeThread().GetSystemHandle(); }
38.068966
80
0.709239
dan-zheng
fd82822ceda3c10b211ff37a2f4cd7288f84a933
7,876
cpp
C++
Programs/ColladaConverter/Collada15/FCollada/FColladaTest/FCTestParameters.cpp
stinvi/dava.engine
2b396ca49cdf10cdc98ad8a9ffcf7768a05e285e
[ "BSD-3-Clause" ]
26
2018-09-03T08:48:22.000Z
2022-02-14T05:14:50.000Z
Programs/ColladaConverter/Collada15/FCollada/FColladaTest/FCTestParameters.cpp
ANHELL-blitz/dava.engine
ed83624326f000866e29166c7f4cccfed1bb41d4
[ "BSD-3-Clause" ]
null
null
null
Programs/ColladaConverter/Collada15/FCollada/FColladaTest/FCTestParameters.cpp
ANHELL-blitz/dava.engine
ed83624326f000866e29166c7f4cccfed1bb41d4
[ "BSD-3-Clause" ]
45
2018-05-11T06:47:17.000Z
2022-02-03T11:30:55.000Z
/* Copyright (C) 2005-2007 Feeling Software Inc. Portions of the code are: Copyright (C) 2005-2007 Sony Computer Entertainment America MIT License: http://www.opensource.org/licenses/mit-license.php */ #include "StdAfx.h" #include "FUtils/FUParameter.h" #include "FCDocument/FCDocument.h" #include "FCDocument/FCDAnimated.h" #include "FCDocument/FCDAnimation.h" #include "FCDocument/FCDAnimationChannel.h" #include "FCDocument/FCDAnimationCurve.h" #include "FCDocument/FCDEntity.h" #include "FCDocument/FCDLibrary.h" #include "FCDocument/FCDParameterAnimatable.h" class FCTestOutsideParameter : public FCDObject { public: DeclareParameter(float, FUParameterQualifiers::SIMPLE, test1, FC("A large parameter name!")); DeclareParameterAnimatable(FMVector3, FUParameterQualifiers::VECTOR, test2, FC("An animatable parameter")); DeclareParameterAnimatable(FMVector3, FUParameterQualifiers::COLOR, test3, FC("A complex animatable parameter")); DeclareParameterPtr(FCDObject, test4, FC("A simple object pointer")); DeclareParameterRef(FCDObject, test5, FC("An object reference!")); DeclareParameterList(Float, test6, FC("A float list parameter.")); DeclareParameterTrackList(FCDObject, test7, FC("An object tracker list.")); DeclareParameterContainer(FCDObject, test8, FC("An object container.")); DeclareParameterListAnimatable(FMVector3, FUParameterQualifiers::COLOR, test9, FC("An animatable color list.")); FCTestOutsideParameter(FCDocument* document) : FCDObject(document) , InitializeParameter(test1, 0.0f) , InitializeParameterAnimatableNoArg(test2) , InitializeParameterAnimatable(test3, FMVector3::XAxis) , InitializeParameter(test4, NULL) , InitializeParameterNoArg(test5) , InitializeParameterNoArg(test6) , InitializeParameterNoArg(test7) , InitializeParameterNoArg(test8) , InitializeParameterAnimatableNoArg(test9) { } virtual ~FCTestOutsideParameter() { } }; ImplementParameterObject(FCTestOutsideParameter, FCDObject, test4, new FCDObject(parent->GetDocument())); ImplementParameterObject(FCTestOutsideParameter, FCDObject, test5, new FCDObject(parent->GetDocument())); ImplementParameterObject(FCTestOutsideParameter, FCDObject, test7, new FCDObject(parent->GetDocument())); ImplementParameterObject(FCTestOutsideParameter, FCDObject, test8, new FCDObject(parent->GetDocument())); TESTSUITE_START(FCDParameter) TESTSUITE_TEST(0, Simple) FUObjectRef<FCDocument> document = FCollada::NewTopDocument(); FUObjectRef<FCDEntity> entity = new FCDEntity(document); entity->SetNote(FC("Noting down.")); PassIf(IsEquivalent(entity->GetNote(), FC("Noting down."))); TESTSUITE_TEST(1, Functionality) FUObjectRef<FCDocument> document = FCollada::NewTopDocument(); FUObjectRef<FCTestOutsideParameter> parameter = new FCTestOutsideParameter(document); // Simple float parameter PassIf(parameter->test1 == 0.0f); parameter->test1 = 2.1f; PassIf(parameter->test1 == 2.1f); // Animatable 3D vector parameter. parameter->test2 = FMVector3::One; PassIf(parameter->test2 == FMVector3::One); PassIf(parameter->test2 - FMVector3::One == FMVector3::Zero); PassIf(parameter->test2.GetAnimated() != NULL); PassIf(parameter->test2.GetAnimated()->GetValueCount() == 3); // Object parameters parameter->test4 = parameter->test5; PassIf(parameter->test4 == parameter->test5); parameter->test5 = NULL; PassIf(parameter->test5 == NULL); parameter->test4 = new FCDObject(document); PassIf(parameter->test4 != NULL); PassIf(parameter->test4->GetTrackerCount() == 1); parameter->test5 = parameter->test4; PassIf(parameter->test5 != NULL); PassIf(parameter->test5->GetTrackerCount() == 1); parameter->test5 = NULL; PassIf(parameter->test4 == NULL); // Primitive list parameter size_t count = parameter->test6.size(); PassIf(count == 0 && parameter->test6.empty()); parameter->test6.push_back(0.52f); PassIf(parameter->test6.size() == 1); parameter->test6.clear(); PassIf(parameter->test6.size() == 0); parameter->test6.push_back(0.45f); PassIf(parameter->test6.size() == 1); parameter->test6.erase(0, 1); PassIf(parameter->test6.size() == 0); // Tracked object list parameter FUTrackedPtr<FCDObject> testObject = new FCDObject(document); count = parameter->test7.size(); PassIf(count == 0 && parameter->test7.empty()); parameter->test7.push_back(testObject); PassIf(parameter->test7.size() == 1); parameter->test7.clear(); PassIf(testObject != NULL); PassIf(parameter->test7.size() == 0); parameter->test7.push_back(testObject); PassIf(parameter->test7.size() == 1); parameter->test7.erase(0, 1); PassIf(parameter->test7.size() == 0); testObject->Release(); PassIf(testObject == NULL); // Object container parameter testObject = new FCDObject(document); count = parameter->test8.size(); PassIf(count == 0 && parameter->test8.empty()); parameter->test8.push_back(testObject); PassIf(parameter->test8.size() == 1); parameter->test8.clear(); PassIf(testObject == NULL); // this is a container, so testObject should have been released! PassIf(parameter->test8.size() == 0); parameter->test8.push_back(new FCDObject(document)); PassIf(parameter->test8.size() == 1); parameter->test8.erase(0, 1); PassIf(parameter->test8.size() == 0); TESTSUITE_TEST(2, AnimatedListParameter) FUObjectRef<FCDocument> document = FCollada::NewTopDocument(); FUObjectRef<FCTestOutsideParameter> parameter = new FCTestOutsideParameter(document); FCDAnimation* animation = document->GetAnimationLibrary()->AddEntity(); FCDAnimationChannel* channel = animation->AddChannel(); // Animated list parameter. // Simple operations #define TESTP parameter->test9 PassIf(TESTP.size() == 0); TESTP.push_back(FMVector3::XAxis); TESTP.push_back(FMVector3::YAxis); TESTP.push_back(FMVector3::ZAxis); PassIf(TESTP.size() == 3); FailIf(TESTP.IsAnimated()); FailIf(TESTP.IsAnimated(0)); PassIf(TESTP.GetAnimatedValues().empty()); PassIf(TESTP.GetAnimated(2) != NULL); FailIf(TESTP.GetAnimatedValues().empty()); FailIf(TESTP.IsAnimated(2)); TESTP.push_front(FMVector3::XAxis); TESTP.push_front(FMVector3::YAxis); TESTP.push_front(FMVector3::ZAxis); PassIf(TESTP.GetAnimated(2) != NULL); PassIf(TESTP.at(1) == FMVector3::YAxis); PassIf(TESTP.at(4) == FMVector3::YAxis); PassIf(!TESTP.IsAnimated(5)); PassIf(!TESTP.IsAnimated(4)); PassIf(TESTP.GetAnimated(2)->GetArrayElement() == 2); // List insertion tests. TESTP.GetAnimated(2)->AddCurve(0, channel->AddCurve()); PassIf(TESTP.IsAnimated()); PassIf(TESTP.IsAnimated(2)); PassIf(!TESTP.IsAnimated(1)); PassIf(!TESTP.IsAnimated(3)); TESTP.insert(2, FMVector3::XAxis); // should move the curve up to index 3! PassIf(TESTP.IsAnimated(3)); PassIf(!TESTP.IsAnimated(2)); PassIf(!TESTP.IsAnimated(4)); PassIf(TESTP.GetAnimated(3)->GetArrayElement() == 3); TESTP.insert(5, FMVector3::YAxis); // no movement of the curve. PassIf(TESTP.IsAnimated(3)); PassIf(!TESTP.IsAnimated(2)); PassIf(!TESTP.IsAnimated(4)); PassIf(TESTP.GetAnimated(4)->GetArrayElement() == 4); // List removal tests. TESTP.erase(0); // should move the curve back to index 2. PassIf(TESTP.IsAnimated(2)); PassIf(!TESTP.IsAnimated(1)); PassIf(!TESTP.IsAnimated(3)); PassIf(TESTP.GetAnimated(2)->GetArrayElement() == 2); TESTP.erase(0, 4); // nothing should be animated anymore. FailIf(TESTP.IsAnimated()); // List resizing tests. TESTP.clear(); FailIf(TESTP.IsAnimated()); TESTP.resize(4); FailIf(TESTP.IsAnimated()); TESTP.GetAnimated(1)->AddCurve(0, channel->AddCurve()); PassIf(TESTP.IsAnimated()); PassIf(TESTP.IsAnimated(1)); TESTP.resize(6); PassIf(TESTP.IsAnimated()); PassIf(TESTP.IsAnimated(1)); TESTP.resize(1); FailIf(TESTP.IsAnimated()); TESTSUITE_END
37.865385
118
0.727908
stinvi
fd83ced9c176abbafd7511bd6a4af163693e3418
283
hpp
C++
cegui/src/ScriptModules/Python/bindings/output/CEGUI/SingletonWindowFactoryManager.pypp.hpp
OpenTechEngine-Libraries/CEGUI
6f00952d31f318f9482766d1ad2206cb540a78b9
[ "MIT" ]
257
2020-01-03T10:13:29.000Z
2022-03-26T14:55:12.000Z
cegui/src/ScriptModules/Python/bindings/output/CEGUI/SingletonWindowFactoryManager.pypp.hpp
OpenTechEngine-Libraries/CEGUI
6f00952d31f318f9482766d1ad2206cb540a78b9
[ "MIT" ]
116
2020-01-09T18:13:13.000Z
2022-03-15T18:32:02.000Z
cegui/src/ScriptModules/Python/bindings/output/CEGUI/SingletonWindowFactoryManager.pypp.hpp
OpenTechEngine-Libraries/CEGUI
6f00952d31f318f9482766d1ad2206cb540a78b9
[ "MIT" ]
58
2020-01-09T03:07:02.000Z
2022-03-22T17:21:36.000Z
// This file has been generated by Py++. #ifndef SingletonWindowFactoryManager_hpp__pyplusplus_wrapper #define SingletonWindowFactoryManager_hpp__pyplusplus_wrapper void register_SingletonWindowFactoryManager_class(); #endif//SingletonWindowFactoryManager_hpp__pyplusplus_wrapper
31.444444
61
0.890459
OpenTechEngine-Libraries
fd885f2679731563b14d5b0e66942c9569b81c0b
1,009
hpp
C++
stan/math/prim/fun/inverse.hpp
LaudateCorpus1/math
990a66b3cccd27a5fd48626360bb91093a48278b
[ "BSD-3-Clause" ]
1
2020-05-18T13:10:50.000Z
2020-05-18T13:10:50.000Z
stan/math/prim/fun/inverse.hpp
LaudateCorpus1/math
990a66b3cccd27a5fd48626360bb91093a48278b
[ "BSD-3-Clause" ]
2
2019-07-23T12:45:30.000Z
2020-05-01T20:43:03.000Z
stan/math/prim/fun/inverse.hpp
LaudateCorpus1/math
990a66b3cccd27a5fd48626360bb91093a48278b
[ "BSD-3-Clause" ]
1
2020-05-10T12:55:07.000Z
2020-05-10T12:55:07.000Z
#ifndef STAN_MATH_PRIM_FUN_INVERSE_HPP #define STAN_MATH_PRIM_FUN_INVERSE_HPP #include <stan/math/prim/meta.hpp> #include <stan/math/prim/err.hpp> #include <stan/math/prim/fun/Eigen.hpp> namespace stan { namespace math { /** * Returns the inverse of the specified matrix. * * @tparam T type of elements in the matrix * @tparam R number of rows, can be Eigen::Dynamic * @tparam C number of columns, can be Eigen::Dynamic * * @param m specified matrix * @return Inverse of the matrix (an empty matrix if the specified matrix has * size zero). * @throw std::invalid_argument if the matrix is not square. */ template <typename EigMat, require_eigen_vt<std::is_arithmetic, EigMat>* = nullptr> inline Eigen::Matrix<value_type_t<EigMat>, EigMat::RowsAtCompileTime, EigMat::ColsAtCompileTime> inverse(const EigMat& m) { check_square("inverse", "m", m); if (m.size() == 0) { return {}; } return m.inverse(); } } // namespace math } // namespace stan #endif
25.871795
77
0.698712
LaudateCorpus1
fd89614e4a1f4d53cdb77144c91da2d3c147a1ec
750
cpp
C++
Testing/Arrays/ArrayCat.cpp
Psy-Rat/FPTL
f3e1f560efa0c67ce62e673a8e142bc4df837a6e
[ "MIT" ]
5
2019-11-21T23:14:00.000Z
2021-02-03T15:39:30.000Z
Testing/Arrays/ArrayCat.cpp
Psy-Rat/FPTL
f3e1f560efa0c67ce62e673a8e142bc4df837a6e
[ "MIT" ]
null
null
null
Testing/Arrays/ArrayCat.cpp
Psy-Rat/FPTL
f3e1f560efa0c67ce62e673a8e142bc4df837a6e
[ "MIT" ]
4
2020-02-23T22:38:04.000Z
2021-02-05T16:59:31.000Z
#include "../Shared.h" namespace UnitTests { namespace Arrays { TEST(ArrayCat, One) { const std::string innerCode = "@ = (((3 * 1).arrayCreate * 1 * 2).arraySet * 2 * 3).arraySet.(id * arrayCat).(print * ([-1] * 0 * 0).arraySet.print * print);"; const std::string expected = "[1, 2, 3]"; GeneralizedTest(standardInput, expected, MakeTestProgram(innerCode)); } TEST(ArrayCat, Three) { const std::string innerCode = R"( @ = ( (1 * 1).arrayCreate * ((2 * 2).arrayCreate * 1 * 3).arraySet * (((3 * 4).arrayCreate * 1 * 5).arraySet * 2 * 6).arraySet ).arrayCat.print;)"; const std::string expected = "[1, 2, 3, 4, 5, 6]"; GeneralizedTest(standardInput, expected, MakeTestProgram(innerCode)); } } }
25.862069
162
0.6
Psy-Rat
fd89f6d824ab982c0dfb7108248aec3f088e6f18
870
cpp
C++
coast/modules/Renderer/CeilingRenderer.cpp
zer0infinity/CuteForCoast
37d933c5fe2e0ce9a801f51b2aa27c7a18098511
[ "BSD-3-Clause" ]
null
null
null
coast/modules/Renderer/CeilingRenderer.cpp
zer0infinity/CuteForCoast
37d933c5fe2e0ce9a801f51b2aa27c7a18098511
[ "BSD-3-Clause" ]
null
null
null
coast/modules/Renderer/CeilingRenderer.cpp
zer0infinity/CuteForCoast
37d933c5fe2e0ce9a801f51b2aa27c7a18098511
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright (c) 2005, Peter Sommerlad and IFS Institute for Software at HSR Rapperswil, Switzerland * All rights reserved. * * This library/application is free software; you can redistribute and/or modify it under the terms of * the license that is included with this library/application in the file license.txt. */ #include "CeilingRenderer.h" #include "Tracer.h" //---- CeilingRenderer --------------------------------------------------------------- RegisterRenderer(CeilingRenderer); CeilingRenderer::CeilingRenderer(const char *name) : ComparingRenderer(name) { } CeilingRenderer::~CeilingRenderer() { } long CeilingRenderer::FindSlot(String &key, const ROAnything &list) { StartTrace(CeilingRenderer.FindSlot); long i = 0; long sz = list.GetSize(); while ((i < sz) && (key.Compare(list.SlotName(i)) > 0) ) { ++i; } return i < sz ? i : -1; }
28.064516
102
0.666667
zer0infinity
fd8c072a378d048aecb14aba47c62234aab215fc
12,784
cpp
C++
tf2_src/game/client/tf/vgui/select_player_dialog.cpp
d3fc0n6/TeamFortress2
1b81dded673d49adebf4d0958e52236ecc28a956
[ "MIT" ]
4
2021-10-03T05:16:55.000Z
2021-12-28T16:49:27.000Z
tf2_src/game/client/tf/vgui/select_player_dialog.cpp
Counter2828/TeamFortress2
1b81dded673d49adebf4d0958e52236ecc28a956
[ "MIT" ]
null
null
null
tf2_src/game/client/tf/vgui/select_player_dialog.cpp
Counter2828/TeamFortress2
1b81dded673d49adebf4d0958e52236ecc28a956
[ "MIT" ]
3
2022-02-02T18:09:58.000Z
2022-03-06T18:54:39.000Z
//========= Copyright Valve Corporation, All rights reserved. ============// // // Purpose: // //=============================================================================// #include "cbase.h" #include <vgui/ILocalize.h> #include "vgui_controls/TextEntry.h" #include "select_player_dialog.h" #include "tf_controls.h" #include "c_playerresource.h" #include "ienginevgui.h" // memdbgon must be the last include file in a .cpp file!!! #include <tier0/memdbgon.h> int CSelectPlayerDialog::SortPartnerInfoFunc( const partner_info_t *pA, const partner_info_t *pB ) { return Q_stricmp( pA->m_name.Get(), pB->m_name.Get() ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- CSelectPlayerDialog::CSelectPlayerDialog( vgui::Panel *parent ) : vgui::EditablePanel( parent, "SelectPlayerDialog" ) , m_bAllowSameTeam( true ) , m_bAllowOutsideServer( true ) { if ( parent == NULL ) { vgui::HScheme scheme = vgui::scheme()->LoadSchemeFromFileEx( enginevgui->GetPanel( PANEL_CLIENTDLL ), "resource/ClientScheme.res", "ClientScheme"); SetScheme(scheme); SetProportional( true ); } m_pSelectFromServerButton = NULL; m_pCancelButton = NULL; m_pButtonKV = NULL; m_bReapplyButtonKVs = false; for ( int i = 0; i < SPDS_NUM_STATES; i++ ) { m_pStatePanels[i] = new vgui::EditablePanel( this, VarArgs("StatePanel%d",i) ); } m_pPlayerList = new vgui::EditablePanel( this, "PlayerList" ); m_pPlayerListScroller = new vgui::ScrollableEditablePanel( this, m_pPlayerList, "PlayerListScroller" ); m_iCurrentState = SPDS_SELECTING_PLAYER; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- CSelectPlayerDialog::~CSelectPlayerDialog( void ) { if ( m_pButtonKV ) { m_pButtonKV->deleteThis(); m_pButtonKV = NULL; } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CSelectPlayerDialog::Reset( void ) { m_iCurrentState = SPDS_SELECTING_PLAYER; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CSelectPlayerDialog::ApplySettings( KeyValues *inResourceData ) { BaseClass::ApplySettings( inResourceData ); KeyValues *pItemKV = inResourceData->FindKey( "button_kv" ); if ( pItemKV ) { if ( m_pButtonKV ) { m_pButtonKV->deleteThis(); } m_pButtonKV = new KeyValues("button_kv"); pItemKV->CopySubkeys( m_pButtonKV ); m_bReapplyButtonKVs = true; } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CSelectPlayerDialog::ApplySchemeSettings( vgui::IScheme *pScheme ) { BaseClass::ApplySchemeSettings( pScheme ); LoadControlSettings( GetResFile() ); m_pCancelButton = dynamic_cast<CExButton*>( FindChildByName( "CancelButton" ) ); // Find all the sub buttons, and set their action signals to point to this panel for ( int i = 0; i < SPDS_NUM_STATES; i++ ) { int iButton = 0; CExButton *pButton = NULL; do { pButton = dynamic_cast<CExButton*>( m_pStatePanels[i]->FindChildByName( VarArgs("subbutton%d",iButton)) ); if ( pButton ) { pButton->AddActionSignalTarget( this ); // The second button on the first state is the server button if ( iButton == 1 ) { m_pSelectFromServerButton = pButton; } iButton++; } } while (pButton); } UpdateState(); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CSelectPlayerDialog::PerformLayout( void ) { BaseClass::PerformLayout(); // Layout the player list buttons if ( m_pPlayerPanels.Count() ) { int iButtonH = m_pPlayerPanels[0]->GetTall() + YRES(2); m_pPlayerList->SetSize( m_pPlayerList->GetWide(), YRES(2) + (iButtonH * m_pPlayerPanels.Count()) ); // These need to all be layout-complete before we can position the player panels, // because the scrollbar will cause the playerlist entries to move when it lays out. m_pPlayerList->InvalidateLayout( true ); m_pPlayerListScroller->InvalidateLayout( true ); m_pPlayerListScroller->GetScrollbar()->InvalidateLayout( true ); for ( int i = 0; i < m_pPlayerPanels.Count(); i++ ) { m_pPlayerPanels[i]->SetPos( 0, YRES(2) + (iButtonH * i) ); } } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CSelectPlayerDialog::OnCommand( const char *command ) { if ( !Q_stricmp( command, "cancel" ) ) { if ( m_iCurrentState != SPDS_SELECTING_PLAYER ) { m_iCurrentState = SPDS_SELECTING_PLAYER; UpdateState(); return; } TFModalStack()->PopModal( this ); SetVisible( false ); MarkForDeletion(); if ( GetParent() ) { PostMessage( GetParent(), new KeyValues("CancelSelection") ); } return; } else if ( !Q_stricmp( command, "friends" ) ) { m_iCurrentState = SPDS_SELECTING_FROM_FRIENDS; UpdateState(); return; } else if ( !Q_stricmp( command, "server" ) ) { m_iCurrentState = SPDS_SELECTING_FROM_SERVER; UpdateState(); return; } else if ( !Q_strnicmp( command, "select_player", 13 ) ) { int iPlayer = atoi( command + 13 ) - 1; if ( iPlayer >= 0 && iPlayer < m_PlayerInfoList.Count() ) { m_iCurrentState = SPDS_SELECTING_PLAYER; OnCommand( "cancel" ); OnSelectPlayer( m_PlayerInfoList[iPlayer].m_steamID ); } return; } BaseClass::OnCommand( command ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CSelectPlayerDialog::UpdateState( void ) { for ( int i = 0; i < SPDS_NUM_STATES; i++ ) { if ( !m_pStatePanels[i] ) continue; m_pStatePanels[i]->SetVisible( m_iCurrentState == i ); } if ( m_pSelectFromServerButton ) { m_pSelectFromServerButton->SetEnabled( engine->IsInGame() ); } if ( m_iCurrentState == SPDS_SELECTING_PLAYER ) { m_pCancelButton->SetText( g_pVGuiLocalize->Find( "#Cancel" ) ); } else { m_pCancelButton->SetText( g_pVGuiLocalize->Find( "#TF_Back" ) ); } switch ( m_iCurrentState ) { case SPDS_SELECTING_FROM_FRIENDS: SetupSelectFriends(); break; case SPDS_SELECTING_FROM_SERVER: SetupSelectServer( false ); break; case SPDS_SELECTING_PLAYER: default: m_pPlayerListScroller->SetVisible( false ); break; } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CSelectPlayerDialog::SetupSelectFriends( void ) { // @todo optional check to see if friend is on my server if ( m_bAllowOutsideServer == false ) { SetupSelectServer( true ); return; } m_PlayerInfoList.Purge(); if ( steamapicontext && steamapicontext->SteamFriends() ) { // Get our game info so we can use that to test if our friends are connected to the same game as us FriendGameInfo_t myGameInfo; CSteamID mySteamID = steamapicontext->SteamUser()->GetSteamID(); steamapicontext->SteamFriends()->GetFriendGamePlayed( mySteamID, &myGameInfo ); int iFriends = steamapicontext->SteamFriends()->GetFriendCount( k_EFriendFlagImmediate ); for ( int i = 0; i < iFriends; i++ ) { CSteamID friendSteamID = steamapicontext->SteamFriends()->GetFriendByIndex( i, k_EFriendFlagImmediate ); FriendGameInfo_t gameInfo; if ( !AllowOutOfGameFriends() && !steamapicontext->SteamFriends()->GetFriendGamePlayed( friendSteamID, &gameInfo ) ) continue; // Friends is in-game. Make sure it's TF2. if ( AllowOutOfGameFriends() || (gameInfo.m_gameID.IsValid() && gameInfo.m_gameID == myGameInfo.m_gameID) ) { const char *pszName = steamapicontext->SteamFriends()->GetFriendPersonaName( friendSteamID ); int idx = m_PlayerInfoList.AddToTail(); partner_info_t &info = m_PlayerInfoList[idx]; info.m_steamID = friendSteamID; info.m_name = pszName; } } } UpdatePlayerList(); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CSelectPlayerDialog::SetupSelectServer( bool bFriendsOnly ) { m_PlayerInfoList.Purge(); if ( steamapicontext && steamapicontext->SteamUtils() ) { for( int iPlayerIndex = 1 ; iPlayerIndex <= MAX_PLAYERS; iPlayerIndex++ ) { // find all players who are on the local player's team int iLocalPlayerIndex = GetLocalPlayerIndex(); if( ( iPlayerIndex != iLocalPlayerIndex ) && ( g_PR->IsConnected( iPlayerIndex ) ) ) { player_info_t pi; if ( !engine->GetPlayerInfo( iPlayerIndex, &pi ) ) continue; if ( !pi.friendsID ) continue; CSteamID steamID( pi.friendsID, 1, GetUniverse(), k_EAccountTypeIndividual ); if ( bFriendsOnly ) { EFriendRelationship eRelationship = steamapicontext->SteamFriends()->GetFriendRelationship( steamID ); if ( eRelationship != k_EFriendRelationshipFriend ) { continue; } } if ( g_PR->GetTeam( iPlayerIndex ) != TF_TEAM_RED && g_PR->GetTeam( iPlayerIndex ) != TF_TEAM_BLUE ) continue; if ( m_bAllowSameTeam == false ) { if ( GetLocalPlayerTeam() == g_PR->GetTeam( iPlayerIndex ) ) { continue; } } int idx = m_PlayerInfoList.AddToTail(); partner_info_t &info = m_PlayerInfoList[idx]; info.m_steamID = steamID; info.m_name = pi.name; } } } UpdatePlayerList(); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CSelectPlayerDialog::UpdatePlayerList( void ) { vgui::Label *pLabelEmpty = dynamic_cast<vgui::Label*>( m_pStatePanels[m_iCurrentState]->FindChildByName("EmptyPlayerListLabel") ); vgui::Label *pLabelQuery = dynamic_cast<vgui::Label*>( m_pStatePanels[m_iCurrentState]->FindChildByName("QueryLabel") ); // If we have no players in our list, show the no-player label. if ( m_PlayerInfoList.Count() == 0 ) { if ( pLabelEmpty ) { pLabelEmpty->SetVisible( true ); } if ( pLabelQuery ) { pLabelQuery->SetVisible( false ); } return; } // First, reapply any KVs we have to reapply if ( m_bReapplyButtonKVs ) { m_bReapplyButtonKVs = false; if ( m_pButtonKV ) { FOR_EACH_VEC( m_pPlayerPanels, i ) { m_pPlayerPanels[i]->ApplySettings( m_pButtonKV ); } } } // sort by name m_PlayerInfoList.Sort( &SortPartnerInfoFunc ); // Otherwise, build the player panels from the list of steam IDs for ( int i = 0; i < m_PlayerInfoList.Count(); i++ ) { if ( m_pPlayerPanels.Count() <= i ) { m_pPlayerPanels.AddToTail(); m_pPlayerPanels[i] = new CSelectPlayerTargetPanel( m_pPlayerList, VarArgs("player%d",i) ); m_pPlayerPanels[i]->GetButton()->SetCommand( VarArgs("select_player%d",i+1) ); m_pPlayerPanels[i]->GetButton()->AddActionSignalTarget( this ); m_pPlayerPanels[i]->GetAvatar()->SetShouldDrawFriendIcon( false ); m_pPlayerPanels[i]->GetAvatar()->SetMouseInputEnabled( false ); if ( m_pButtonKV ) { m_pPlayerPanels[i]->ApplySettings( m_pButtonKV ); m_pPlayerPanels[i]->InvalidateLayout( true ); } } m_pPlayerPanels[i]->SetInfo( m_PlayerInfoList[i].m_steamID, m_PlayerInfoList[i].m_name ); } m_pPlayerListScroller->GetScrollbar()->SetAutohideButtons( true ); m_pPlayerListScroller->GetScrollbar()->SetValue( 0 ); // Remove any extra player panels for ( int i = m_pPlayerPanels.Count()-1; i >= m_PlayerInfoList.Count(); i-- ) { m_pPlayerPanels[i]->MarkForDeletion(); m_pPlayerPanels.Remove(i); } if ( pLabelEmpty ) { pLabelEmpty->SetVisible( false ); } if ( pLabelQuery ) { pLabelQuery->SetVisible( true ); } m_pPlayerListScroller->SetVisible( true ); InvalidateLayout(); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CSelectPlayerTargetPanel::SetInfo( const CSteamID &steamID, const char *pszName ) { if ( !steamapicontext || !steamapicontext->SteamFriends() ) return; m_pAvatar->SetPlayer( steamID, k_EAvatarSize64x64 ); m_pButton->SetText( pszName ); }
28.599553
149
0.586045
d3fc0n6
fd8f62263a6b544ba6ec739cdb6ee84623310cbc
35,174
cpp
C++
Source/driver/Castro_setup.cpp
taehoryu/Castro
223c72c993343ba5df84613d058ffb0767c2a7c9
[ "BSD-3-Clause-LBNL" ]
1
2019-06-05T19:23:47.000Z
2019-06-05T19:23:47.000Z
Source/driver/Castro_setup.cpp
taehoryu/Castro
223c72c993343ba5df84613d058ffb0767c2a7c9
[ "BSD-3-Clause-LBNL" ]
null
null
null
Source/driver/Castro_setup.cpp
taehoryu/Castro
223c72c993343ba5df84613d058ffb0767c2a7c9
[ "BSD-3-Clause-LBNL" ]
null
null
null
#include <cstdio> #include "AMReX_LevelBld.H" #include <AMReX_ParmParse.H> #include "Castro.H" #include "Castro_F.H" #ifdef AMREX_DIMENSION_AGNOSTIC #include "Castro_bc_fill_nd_F.H" #include "Castro_bc_fill_nd.H" #else #include "Castro_bc_fill_F.H" #include "Castro_bc_fill.H" #endif #include "Castro_generic_fill_F.H" #include "Castro_generic_fill.H" #include <Derive_F.H> #include "Derive.H" #ifdef RADIATION # include "Radiation.H" # include "RAD_F.H" #endif #include "AMReX_buildInfo.H" using std::string; using namespace amrex; static Box the_same_box (const Box& b) { return b; } static Box grow_box_by_one (const Box& b) { return amrex::grow(b,1); } typedef StateDescriptor::BndryFunc BndryFunc; // // Components are: // Interior, Inflow, Outflow, Symmetry, SlipWall, NoSlipWall // static int scalar_bc[] = { INT_DIR, EXT_DIR, FOEXTRAP, REFLECT_EVEN, REFLECT_EVEN, REFLECT_EVEN }; static int norm_vel_bc[] = { INT_DIR, EXT_DIR, FOEXTRAP, REFLECT_ODD, REFLECT_ODD, REFLECT_ODD }; static int tang_vel_bc[] = { INT_DIR, EXT_DIR, FOEXTRAP, REFLECT_EVEN, REFLECT_EVEN, REFLECT_EVEN }; static void set_scalar_bc (BCRec& bc, const BCRec& phys_bc) { const int* lo_bc = phys_bc.lo(); const int* hi_bc = phys_bc.hi(); for (int i = 0; i < BL_SPACEDIM; i++) { bc.setLo(i,scalar_bc[lo_bc[i]]); bc.setHi(i,scalar_bc[hi_bc[i]]); } } static void set_x_vel_bc(BCRec& bc, const BCRec& phys_bc) { const int* lo_bc = phys_bc.lo(); const int* hi_bc = phys_bc.hi(); bc.setLo(0,norm_vel_bc[lo_bc[0]]); bc.setHi(0,norm_vel_bc[hi_bc[0]]); #if (BL_SPACEDIM >= 2) bc.setLo(1,tang_vel_bc[lo_bc[1]]); bc.setHi(1,tang_vel_bc[hi_bc[1]]); #endif #if (BL_SPACEDIM == 3) bc.setLo(2,tang_vel_bc[lo_bc[2]]); bc.setHi(2,tang_vel_bc[hi_bc[2]]); #endif } static void set_y_vel_bc(BCRec& bc, const BCRec& phys_bc) { const int* lo_bc = phys_bc.lo(); const int* hi_bc = phys_bc.hi(); bc.setLo(0,tang_vel_bc[lo_bc[0]]); bc.setHi(0,tang_vel_bc[hi_bc[0]]); #if (BL_SPACEDIM >= 2) bc.setLo(1,norm_vel_bc[lo_bc[1]]); bc.setHi(1,norm_vel_bc[hi_bc[1]]); #endif #if (BL_SPACEDIM == 3) bc.setLo(2,tang_vel_bc[lo_bc[2]]); bc.setHi(2,tang_vel_bc[hi_bc[2]]); #endif } static void set_z_vel_bc(BCRec& bc, const BCRec& phys_bc) { const int* lo_bc = phys_bc.lo(); const int* hi_bc = phys_bc.hi(); bc.setLo(0,tang_vel_bc[lo_bc[0]]); bc.setHi(0,tang_vel_bc[hi_bc[0]]); #if (BL_SPACEDIM >= 2) bc.setLo(1,tang_vel_bc[lo_bc[1]]); bc.setHi(1,tang_vel_bc[hi_bc[1]]); #endif #if (BL_SPACEDIM == 3) bc.setLo(2,norm_vel_bc[lo_bc[2]]); bc.setHi(2,norm_vel_bc[hi_bc[2]]); #endif } void Castro::variableSetUp () { // Castro::variableSetUp is called in the constructor of Amr.cpp, so // it should get called every time we start or restart a job // initialize the start time for our CPU-time tracker startCPUTime = ParallelDescriptor::second(); // Output the git commit hashes used to build the executable. if (ParallelDescriptor::IOProcessor()) { const char* castro_hash = buildInfoGetGitHash(1); const char* amrex_hash = buildInfoGetGitHash(2); const char* microphysics_hash = buildInfoGetGitHash(3); const char* buildgithash = buildInfoGetBuildGitHash(); const char* buildgitname = buildInfoGetBuildGitName(); if (strlen(castro_hash) > 0) { std::cout << "\n" << "Castro git describe: " << castro_hash << "\n"; } if (strlen(amrex_hash) > 0) { std::cout << "AMReX git describe: " << amrex_hash << "\n"; } if (strlen(microphysics_hash) > 0) { std::cout << "Microphysics git describe: " << microphysics_hash << "\n"; } if (strlen(buildgithash) > 0){ std::cout << buildgitname << " git describe: " << buildgithash << "\n"; } std::cout << "\n"; } BL_ASSERT(desc_lst.size() == 0); // Get options, set phys_bc read_params(); // Initialize the runtime parameters for any of the external // microphysics extern_init(); // Initialize the network network_init(); #ifdef REACTIONS // Initialize the burner burner_init(); #endif #ifdef SPONGE // Initialize the sponge sponge_init(); #endif // Initialize the amr info amrinfo_init(); const int dm = BL_SPACEDIM; // // Set number of state variables and pointers to components // // Get the number of species from the network model. ca_get_num_spec(&NumSpec); // Get the number of auxiliary quantities from the network model. ca_get_num_aux(&NumAux); // Get the number of advected quantities -- set at compile time ca_get_num_adv(&NumAdv); #include "set_conserved.H" NUM_STATE = cnt; #include "set_primitive.H" #include "set_godunov.H" // Define NUM_GROW from the f90 module. ca_get_method_params(&NUM_GROW); const Real run_strt = ParallelDescriptor::second() ; // Read in the input values to Fortran. ca_set_castro_method_params(); // set the conserved, primitive, aux, and godunov indices in Fortran ca_set_method_params(dm, Density, Xmom, #ifdef HYBRID_MOMENTUM Rmom, #endif Eden, Eint, Temp, FirstAdv, FirstSpec, FirstAux, #ifdef SHOCK_VAR Shock, #endif #ifdef MHD QMAGX, QMAGY, QMAGZ, #endif #ifdef RADIATION QPTOT, QREITOT, QRAD, #endif QRHO, QU, QV, QW, QGAME, QGC, QPRES, QREINT, QTEMP, QFA, QFS, QFX, #ifdef RADIATION GDLAMS, GDERADS, #endif GDRHO, GDU, GDV, GDW, GDPRES, GDGAME); // Get the number of primitive variables from Fortran. ca_get_nqsrc(&NQSRC); // and the auxiliary variables ca_get_nqaux(&NQAUX); // and the number of primitive variable source terms ca_get_nqsrc(&NQSRC); // initialize the Godunov state array used in hydro ca_get_ngdnv(&NGDNV); // NQ will be used to dimension the primitive variable state // vector it will include the "pure" hydrodynamical variables + // any radiation variables ca_get_nq(&NQ); Real run_stop = ParallelDescriptor::second() - run_strt; ParallelDescriptor::ReduceRealMax(run_stop,ParallelDescriptor::IOProcessorNumber()); if (ParallelDescriptor::IOProcessor()) std::cout << "\nTime in ca_set_method_params: " << run_stop << '\n' ; const Geometry& dgeom = DefaultGeometry(); const int coord_type = dgeom.Coord(); // Get the center variable from the inputs and pass it directly to Fortran. Vector<Real> center(BL_SPACEDIM, 0.0); ParmParse ppc("castro"); ppc.queryarr("center",center,0,BL_SPACEDIM); ca_set_problem_params(dm,phys_bc.lo(),phys_bc.hi(), Interior,Inflow,Outflow,Symmetry,SlipWall,NoSlipWall,coord_type, dgeom.ProbLo(),dgeom.ProbHi(),center.dataPtr()); // Read in the parameters for the tagging criteria // and store them in the Fortran module. const int probin_file_length = probin_file.length(); Vector<int> probin_file_name(probin_file_length); for (int i = 0; i < probin_file_length; i++) probin_file_name[i] = probin_file[i]; ca_get_tagging_params(probin_file_name.dataPtr(),&probin_file_length); #ifdef SPONGE // Read in the parameters for the sponge // and store them in the Fortran module. ca_get_sponge_params(probin_file_name.dataPtr(),&probin_file_length); #endif Interpolater* interp; if (state_interp_order == 0) { interp = &pc_interp; } else { if (lin_limit_state_interp == 1) interp = &lincc_interp; else interp = &cell_cons_interp; } #ifdef RADIATION // cell_cons_interp is not conservative in spherical coordinates. // We could do this for other cases too, but I'll confine it to // neutrino problems for now so as not to change the results of // other people's tests. Better to fix cell_cons_interp! if (dgeom.IsSPHERICAL() && Radiation::nNeutrinoSpecies > 0) { interp = &pc_interp; } #endif // Note that the default is state_data_extrap = false, // store_in_checkpoint = true. We only need to put these in // explicitly if we want to do something different, // like not store the state data in a checkpoint directory bool state_data_extrap = false; bool store_in_checkpoint; #ifdef RADIATION // Radiation should always have at least one ghost zone. int ngrow_state = std::max(1, state_nghost); #else int ngrow_state = state_nghost; #endif BL_ASSERT(ngrow_state >= 0); store_in_checkpoint = true; desc_lst.addDescriptor(State_Type,IndexType::TheCellType(), StateDescriptor::Point,ngrow_state,NUM_STATE, interp,state_data_extrap,store_in_checkpoint); #ifdef SELF_GRAVITY store_in_checkpoint = true; desc_lst.addDescriptor(PhiGrav_Type, IndexType::TheCellType(), StateDescriptor::Point, 1, 1, &cell_cons_interp, state_data_extrap, store_in_checkpoint); store_in_checkpoint = false; desc_lst.addDescriptor(Gravity_Type,IndexType::TheCellType(), StateDescriptor::Point,NUM_GROW,3, &cell_cons_interp,state_data_extrap,store_in_checkpoint); #endif // Source terms -- for the CTU method, because we do characteristic // tracing on the source terms, we need NUM_GROW ghost cells to do // the reconstruction. For MOL and SDC, on the other hand, we only // need 1 (for the fourth-order stuff). Simplified SDC uses the CTU // advance, so it behaves the same way as CTU here. store_in_checkpoint = true; int source_ng; if (time_integration_method == CornerTransportUpwind || time_integration_method == SimplifiedSpectralDeferredCorrections) { source_ng = NUM_GROW; } else if (time_integration_method == MethodOfLines || time_integration_method == SpectralDeferredCorrections) { source_ng = 1; } else { amrex::Error("Unknown time_integration_method"); } desc_lst.addDescriptor(Source_Type, IndexType::TheCellType(), StateDescriptor::Point, source_ng, NUM_STATE, &cell_cons_interp, state_data_extrap, store_in_checkpoint); #ifdef ROTATION store_in_checkpoint = false; desc_lst.addDescriptor(PhiRot_Type, IndexType::TheCellType(), StateDescriptor::Point, 1, 1, &cell_cons_interp, state_data_extrap, store_in_checkpoint); store_in_checkpoint = false; desc_lst.addDescriptor(Rotation_Type,IndexType::TheCellType(), StateDescriptor::Point,NUM_GROW,3, &cell_cons_interp,state_data_extrap,store_in_checkpoint); #endif #ifdef REACTIONS // Components 0:Numspec-1 are omegadot_i // Component NumSpec is enuc = (eout-ein) // Component NumSpec+1 is rho_enuc= rho * (eout-ein) store_in_checkpoint = true; desc_lst.addDescriptor(Reactions_Type,IndexType::TheCellType(), StateDescriptor::Point,0,NumSpec+2, &cell_cons_interp,state_data_extrap,store_in_checkpoint); #endif #ifdef REACTIONS // For simplified SDC, we want to store the reactions source. if (time_integration_method == SimplifiedSpectralDeferredCorrections) { store_in_checkpoint = true; desc_lst.addDescriptor(Simplified_SDC_React_Type, IndexType::TheCellType(), StateDescriptor::Point, NUM_GROW, NQSRC, &cell_cons_interp, state_data_extrap, store_in_checkpoint); } #endif Vector<BCRec> bcs(NUM_STATE); Vector<std::string> name(NUM_STATE); BCRec bc; set_scalar_bc(bc, phys_bc); bcs[Density] = bc; name[Density] = "density"; set_x_vel_bc(bc, phys_bc); bcs[Xmom] = bc; name[Xmom] = "xmom"; set_y_vel_bc(bc, phys_bc); bcs[Ymom] = bc; name[Ymom] = "ymom"; set_z_vel_bc(bc, phys_bc); bcs[Zmom] = bc; name[Zmom] = "zmom"; #ifdef HYBRID_MOMENTUM set_scalar_bc(bc, phys_bc); bcs[Rmom] = bc; name[Rmom] = "rmom"; set_scalar_bc(bc, phys_bc); bcs[Lmom] = bc; name[Lmom] = "lmom"; set_scalar_bc(bc, phys_bc); bcs[Pmom] = bc; name[Pmom] = "pmom"; #endif set_scalar_bc(bc, phys_bc); bcs[Eden] = bc; name[Eden] = "rho_E"; set_scalar_bc(bc, phys_bc); bcs[Eint] = bc; name[Eint] = "rho_e"; set_scalar_bc(bc, phys_bc); bcs[Temp] = bc; name[Temp] = "Temp"; for (int i=0; i<NumAdv; ++i) { char buf[64]; sprintf(buf, "adv_%d", i); set_scalar_bc(bc, phys_bc); bcs[FirstAdv+i] = bc; name[FirstAdv+i] = string(buf); } // Get the species names from the network model. std::vector<std::string> spec_names; for (int i = 0; i < NumSpec; i++) { int len = 20; Vector<int> int_spec_names(len); // This call return the actual length of each string in "len" ca_get_spec_names(int_spec_names.dataPtr(),&i,&len); char char_spec_names[len+1]; for (int j = 0; j < len; j++) char_spec_names[j] = int_spec_names[j]; char_spec_names[len] = '\0'; spec_names.push_back(std::string(char_spec_names)); } if ( ParallelDescriptor::IOProcessor()) { std::cout << NumSpec << " Species: " << std::endl; for (int i = 0; i < NumSpec; i++) std::cout << spec_names[i] << ' ' << ' '; std::cout << std::endl; } for (int i=0; i<NumSpec; ++i) { set_scalar_bc(bc, phys_bc); bcs[FirstSpec+i] = bc; name[FirstSpec+i] = "rho_" + spec_names[i]; } // Get the auxiliary names from the network model. std::vector<std::string> aux_names; for (int i = 0; i < NumAux; i++) { int len = 20; Vector<int> int_aux_names(len); // This call return the actual length of each string in "len" ca_get_aux_names(int_aux_names.dataPtr(),&i,&len); char char_aux_names[len+1]; for (int j = 0; j < len; j++) char_aux_names[j] = int_aux_names[j]; char_aux_names[len] = '\0'; aux_names.push_back(std::string(char_aux_names)); } if ( ParallelDescriptor::IOProcessor()) { std::cout << NumAux << " Auxiliary Variables: " << std::endl; for (int i = 0; i < NumAux; i++) std::cout << aux_names[i] << ' ' << ' '; std::cout << std::endl; } for (int i=0; i<NumAux; ++i) { set_scalar_bc(bc, phys_bc); bcs[FirstAux+i] = bc; name[FirstAux+i] = "rho_" + aux_names[i]; } #ifdef SHOCK_VAR set_scalar_bc(bc, phys_bc); bcs[Shock] = bc; name[Shock] = "Shock"; #endif desc_lst.setComponent(State_Type, Density, name, bcs, BndryFunc(ca_denfill,ca_hypfill)); #ifdef SELF_GRAVITY set_scalar_bc(bc,phys_bc); desc_lst.setComponent(PhiGrav_Type,0,"phiGrav",bc,BndryFunc(ca_phigravfill)); set_x_vel_bc(bc,phys_bc); desc_lst.setComponent(Gravity_Type,0,"grav_x",bc,BndryFunc(ca_gravxfill)); set_y_vel_bc(bc,phys_bc); desc_lst.setComponent(Gravity_Type,1,"grav_y",bc,BndryFunc(ca_gravyfill)); set_z_vel_bc(bc,phys_bc); desc_lst.setComponent(Gravity_Type,2,"grav_z",bc,BndryFunc(ca_gravzfill)); #endif #ifdef ROTATION set_scalar_bc(bc,phys_bc); desc_lst.setComponent(PhiRot_Type,0,"phiRot",bc,BndryFunc(ca_phirotfill)); set_x_vel_bc(bc,phys_bc); desc_lst.setComponent(Rotation_Type,0,"rot_x",bc,BndryFunc(ca_rotxfill)); set_y_vel_bc(bc,phys_bc); desc_lst.setComponent(Rotation_Type,1,"rot_y",bc,BndryFunc(ca_rotyfill)); set_z_vel_bc(bc,phys_bc); desc_lst.setComponent(Rotation_Type,2,"rot_z",bc,BndryFunc(ca_rotzfill)); #endif // Source term array will use standard hyperbolic fill. Vector<BCRec> source_bcs(NUM_STATE); Vector<std::string> state_type_source_names(NUM_STATE); for (int i = 0; i < NUM_STATE; ++i) { state_type_source_names[i] = name[i] + "_source"; source_bcs[i] = bcs[i]; // Replace inflow BCs with FOEXTRAP. for (int j = 0; j < AMREX_SPACEDIM; ++j) { if (source_bcs[i].lo(j) == EXT_DIR) source_bcs[i].setLo(j, FOEXTRAP); if (source_bcs[i].hi(j) == EXT_DIR) source_bcs[i].setHi(j, FOEXTRAP); } } desc_lst.setComponent(Source_Type,Density,state_type_source_names,source_bcs, BndryFunc(ca_generic_single_fill,ca_generic_multi_fill)); #ifdef REACTIONS std::string name_react; for (int i=0; i<NumSpec; ++i) { set_scalar_bc(bc,phys_bc); name_react = "omegadot_" + spec_names[i]; desc_lst.setComponent(Reactions_Type, i, name_react, bc,BndryFunc(ca_reactfill)); } desc_lst.setComponent(Reactions_Type, NumSpec , "enuc", bc, BndryFunc(ca_reactfill)); desc_lst.setComponent(Reactions_Type, NumSpec+1, "rho_enuc", bc, BndryFunc(ca_reactfill)); #endif #ifdef REACTIONS if (time_integration_method == SimplifiedSpectralDeferredCorrections) { for (int i = 0; i < NQSRC; ++i) { char buf[64]; sprintf(buf, "sdc_react_source_%d", i); set_scalar_bc(bc,phys_bc); // Replace inflow BCs with FOEXTRAP. for (int j = 0; j < AMREX_SPACEDIM; ++j) { if (bc.lo(j) == EXT_DIR) bc.setLo(j, FOEXTRAP); if (bc.hi(j) == EXT_DIR) bc.setHi(j, FOEXTRAP); } desc_lst.setComponent(Simplified_SDC_React_Type,i,std::string(buf),bc,BndryFunc(ca_generic_single_fill)); } } #endif #ifdef RADIATION int ngrow = 1; int ncomp = Radiation::nGroups; desc_lst.addDescriptor(Rad_Type, IndexType::TheCellType(), StateDescriptor::Point, ngrow, ncomp, interp); set_scalar_bc(bc,phys_bc); if (ParallelDescriptor::IOProcessor()) { std::cout << "Radiation::nGroups = " << Radiation::nGroups << std::endl; std::cout << "Radiation::nNeutrinoSpecies = " << Radiation::nNeutrinoSpecies << std::endl; if (Radiation::nNeutrinoSpecies > 0) { std::cout << "Radiation::nNeutrinoGroups = "; for (int n = 0; n < Radiation::nNeutrinoSpecies; n++) { std::cout << " " << Radiation::nNeutrinoGroups[n]; } std::cout << std::endl; if (Radiation::nNeutrinoGroups[0] > 0 && NumAdv != 0) { amrex::Error("Neutrino solver assumes NumAdv == 0"); } if (Radiation::nNeutrinoGroups[0] > 0 && (NumSpec != 1 || NumAux != 1)) { amrex::Error("Neutrino solver assumes NumSpec == NumAux == 1"); } } } char rad_name[10]; if (!Radiation::do_multigroup) { desc_lst .setComponent(Rad_Type, Rad, "rad", bc, BndryFunc(ca_radfill)); } else { if (Radiation::nNeutrinoSpecies == 0 || Radiation::nNeutrinoGroups[0] == 0) { for (int i = 0; i < Radiation::nGroups; i++) { sprintf(rad_name, "rad%d", i); desc_lst .setComponent(Rad_Type, i, rad_name, bc, BndryFunc(ca_radfill)); } } else { int indx = 0; for (int j = 0; j < Radiation::nNeutrinoSpecies; j++) { for (int i = 0; i < Radiation::nNeutrinoGroups[j]; i++) { sprintf(rad_name, "rads%dg%d", j, i); desc_lst.setComponent(Rad_Type, indx, rad_name, bc, BndryFunc(ca_radfill)); indx++; } } } } #endif // some optional State_Type's -- since these depend on the value of // runtime parameters, we don't add these to the enum, but instead // add them to the count of State_Type's if we will use them if (use_custom_knapsack_weights) { Knapsack_Weight_Type = desc_lst.size(); desc_lst.addDescriptor(Knapsack_Weight_Type, IndexType::TheCellType(), StateDescriptor::Point, 0, 1, &pc_interp); // Because we use piecewise constant interpolation, we do not use bc and BndryFunc. desc_lst.setComponent(Knapsack_Weight_Type, 0, "KnapsackWeight", bc, BndryFunc(ca_nullfill)); } #ifdef REACTIONS if (time_integration_method == SpectralDeferredCorrections && (mol_order == 4 || sdc_order == 4)) { // we are doing 4th order reactive SDC. We need 2 ghost cells here SDC_Source_Type = desc_lst.size(); store_in_checkpoint = false; desc_lst.addDescriptor(SDC_Source_Type, IndexType::TheCellType(), StateDescriptor::Point, 2, NUM_STATE, interp, state_data_extrap, store_in_checkpoint); // this is the same thing we do for the sources desc_lst.setComponent(SDC_Source_Type, Density, state_type_source_names, source_bcs, BndryFunc(ca_generic_single_fill, ca_generic_multi_fill)); } #endif num_state_type = desc_lst.size(); // // DEFINE DERIVED QUANTITIES // // Pressure // derive_lst.add("pressure",IndexType::TheCellType(),1,ca_derpres,the_same_box); derive_lst.addComponent("pressure",desc_lst,State_Type,Density,NUM_STATE); // // Kinetic energy // derive_lst.add("kineng",IndexType::TheCellType(),1,ca_derkineng,the_same_box); derive_lst.addComponent("kineng",desc_lst,State_Type,Density,1); derive_lst.addComponent("kineng",desc_lst,State_Type,Xmom,3); // // Sound speed (c) // derive_lst.add("soundspeed",IndexType::TheCellType(),1,ca_dersoundspeed,the_same_box); derive_lst.addComponent("soundspeed",desc_lst,State_Type,Density,NUM_STATE); // // Gamma_1 // derive_lst.add("Gamma_1",IndexType::TheCellType(),1,ca_dergamma1,the_same_box); derive_lst.addComponent("Gamma_1",desc_lst,State_Type,Density,NUM_STATE); // // Mach number(M) // derive_lst.add("MachNumber",IndexType::TheCellType(),1,ca_dermachnumber,the_same_box); derive_lst.addComponent("MachNumber",desc_lst,State_Type,Density,NUM_STATE); #if (BL_SPACEDIM == 1) // // Wave speed u+c // derive_lst.add("uplusc",IndexType::TheCellType(),1,ca_deruplusc,the_same_box); derive_lst.addComponent("uplusc",desc_lst,State_Type,Density,NUM_STATE); // // Wave speed u-c // derive_lst.add("uminusc",IndexType::TheCellType(),1,ca_deruminusc,the_same_box); derive_lst.addComponent("uminusc",desc_lst,State_Type,Density,NUM_STATE); #endif // // Gravitational forcing // #ifdef SELF_GRAVITY // derive_lst.add("rhog",IndexType::TheCellType(),1, // BL_FORT_PROC_CALL(CA_RHOG,ca_rhog),the_same_box); // derive_lst.addComponent("rhog",desc_lst,State_Type,Density,1); // derive_lst.addComponent("rhog",desc_lst,Gravity_Type,0,BL_SPACEDIM); #endif // // Entropy (S) // derive_lst.add("entropy",IndexType::TheCellType(),1,ca_derentropy,the_same_box); derive_lst.addComponent("entropy",desc_lst,State_Type,Density,NUM_STATE); #ifdef DIFFUSION if (diffuse_temp) { // // thermal conductivity (k_th) // derive_lst.add("thermal_cond",IndexType::TheCellType(),1,ca_dercond,the_same_box); derive_lst.addComponent("thermal_cond",desc_lst,State_Type,Density,NUM_STATE); // // thermal diffusivity (k_th/(rho c_v)) // derive_lst.add("diff_coeff",IndexType::TheCellType(),1,ca_derdiffcoeff,the_same_box); derive_lst.addComponent("diff_coeff",desc_lst,State_Type,Density,NUM_STATE); // // diffusion term (the divergence of thermal flux) // derive_lst.add("diff_term",IndexType::TheCellType(),1,ca_derdiffterm,grow_box_by_one); derive_lst.addComponent("diff_term",desc_lst,State_Type,Density,NUM_STATE); } #endif // // Vorticity // derive_lst.add("magvort",IndexType::TheCellType(),1,ca_dermagvort,grow_box_by_one); // Here we exploit the fact that Xmom = Density + 1 // in order to use the correct interpolation. if (Xmom != Density+1) amrex::Error("We are assuming Xmom = Density + 1 in Castro_setup.cpp"); derive_lst.addComponent("magvort",desc_lst,State_Type,Density,4); // // Div(u) // derive_lst.add("divu",IndexType::TheCellType(),1,ca_derdivu,grow_box_by_one); derive_lst.addComponent("divu",desc_lst,State_Type,Density,1); derive_lst.addComponent("divu",desc_lst,State_Type,Xmom,3); // // Internal energy as derived from rho*E, part of the state // derive_lst.add("eint_E",IndexType::TheCellType(),1,ca_dereint1,the_same_box); derive_lst.addComponent("eint_E",desc_lst,State_Type,Density,NUM_STATE); // // Internal energy as derived from rho*e, part of the state // derive_lst.add("eint_e",IndexType::TheCellType(),1,ca_dereint2,the_same_box); derive_lst.addComponent("eint_e",desc_lst,State_Type,Density,NUM_STATE); // // Log(density) // derive_lst.add("logden",IndexType::TheCellType(),1,ca_derlogden,the_same_box); derive_lst.addComponent("logden",desc_lst,State_Type,Density,NUM_STATE); derive_lst.add("StateErr",IndexType::TheCellType(),3,ca_derstate,grow_box_by_one); derive_lst.addComponent("StateErr",desc_lst,State_Type,Density,1); derive_lst.addComponent("StateErr",desc_lst,State_Type,Temp,1); derive_lst.addComponent("StateErr",desc_lst,State_Type,FirstSpec,1); // // X from rhoX // for (int i = 0; i < NumSpec; i++){ std::string spec_string = "X("+spec_names[i]+")"; derive_lst.add(spec_string,IndexType::TheCellType(),1,ca_derspec,the_same_box); derive_lst.addComponent(spec_string,desc_lst,State_Type,Density,1); derive_lst.addComponent(spec_string,desc_lst,State_Type,FirstSpec+i,1); } // // Abar // derive_lst.add("abar",IndexType::TheCellType(),1,ca_derabar,the_same_box); derive_lst.addComponent("abar",desc_lst,State_Type,Density,1); derive_lst.addComponent("abar",desc_lst,State_Type,FirstSpec,NumSpec); // // Velocities // derive_lst.add("x_velocity",IndexType::TheCellType(),1,ca_dervel,the_same_box); derive_lst.addComponent("x_velocity",desc_lst,State_Type,Density,1); derive_lst.addComponent("x_velocity",desc_lst,State_Type,Xmom,1); derive_lst.add("y_velocity",IndexType::TheCellType(),1,ca_dervel,the_same_box); derive_lst.addComponent("y_velocity",desc_lst,State_Type,Density,1); derive_lst.addComponent("y_velocity",desc_lst,State_Type,Ymom,1); derive_lst.add("z_velocity",IndexType::TheCellType(),1,ca_dervel,the_same_box); derive_lst.addComponent("z_velocity",desc_lst,State_Type,Density,1); derive_lst.addComponent("z_velocity",desc_lst,State_Type,Zmom,1); #ifdef REACTIONS // // Nuclear energy generation timescale t_e == e / edot // Sound-crossing time t_s == dx / c_s // Ratio of these is t_s_t_e == t_s / t_e // derive_lst.add("t_sound_t_enuc",IndexType::TheCellType(),1,ca_derenuctimescale,the_same_box); derive_lst.addComponent("t_sound_t_enuc",desc_lst,State_Type,Density,NUM_STATE); derive_lst.addComponent("t_sound_t_enuc",desc_lst,Reactions_Type,NumSpec,1); #endif derive_lst.add("magvel",IndexType::TheCellType(),1,ca_dermagvel,the_same_box); derive_lst.addComponent("magvel",desc_lst,State_Type,Density,1); derive_lst.addComponent("magvel",desc_lst,State_Type,Xmom,3); derive_lst.add("radvel",IndexType::TheCellType(),1,ca_derradialvel,the_same_box); derive_lst.addComponent("radvel",desc_lst,State_Type,Density,1); derive_lst.addComponent("radvel",desc_lst,State_Type,Xmom,3); derive_lst.add("magmom",IndexType::TheCellType(),1,ca_dermagmom,the_same_box); derive_lst.addComponent("magmom",desc_lst,State_Type,Xmom,3); derive_lst.add("angular_momentum_x",IndexType::TheCellType(),1,ca_derangmomx,the_same_box); derive_lst.addComponent("angular_momentum_x",desc_lst,State_Type,Density,1); derive_lst.addComponent("angular_momentum_x",desc_lst,State_Type,Xmom,3); derive_lst.add("angular_momentum_y",IndexType::TheCellType(),1,ca_derangmomy,the_same_box); derive_lst.addComponent("angular_momentum_y",desc_lst,State_Type,Density,1); derive_lst.addComponent("angular_momentum_y",desc_lst,State_Type,Xmom,3); derive_lst.add("angular_momentum_z",IndexType::TheCellType(),1,ca_derangmomz,the_same_box); derive_lst.addComponent("angular_momentum_z",desc_lst,State_Type,Density,1); derive_lst.addComponent("angular_momentum_z",desc_lst,State_Type,Xmom,3); #ifdef SELF_GRAVITY derive_lst.add("maggrav",IndexType::TheCellType(),1,ca_dermaggrav,the_same_box); derive_lst.addComponent("maggrav",desc_lst,Gravity_Type,0,3); #endif #ifdef AMREX_PARTICLES // // We want a derived type that corresponds to the number of particles // in each cell. We only intend to use it in plotfiles for debugging // purposes. We'll just use the DERNULL since don't do anything in // fortran for now. We'll actually set the values in writePlotFile(). // derive_lst.add("particle_count",IndexType::TheCellType(),1,ca_dernull,the_same_box); derive_lst.addComponent("particle_count",desc_lst,State_Type,Density,1); derive_lst.add("total_particle_count",IndexType::TheCellType(),1,ca_dernull,the_same_box); derive_lst.addComponent("total_particle_count",desc_lst,State_Type,Density,1); #endif #ifdef RADIATION if (Radiation::do_multigroup) { derive_lst.add("Ertot", IndexType::TheCellType(),1,ca_derertot,the_same_box); derive_lst.addComponent("Ertot",desc_lst,Rad_Type,0,Radiation::nGroups); } #endif #ifdef NEUTRINO if (Radiation::nNeutrinoSpecies > 0 && Radiation::plot_neutrino_group_energies_per_MeV) { char rad_name[10]; int indx = 0; for (int j = 0; j < Radiation::nNeutrinoSpecies; j++) { for (int i = 0; i < Radiation::nNeutrinoGroups[j]; i++) { sprintf(rad_name, "Neuts%dg%d", j, i); derive_lst.add(rad_name,IndexType::TheCellType(),1,ca_derneut,the_same_box); derive_lst.addComponent(rad_name,desc_lst,Rad_Type,indx,1); indx++; } } } if (Radiation::nNeutrinoSpecies > 0 && Radiation::nNeutrinoGroups[0] > 0) { derive_lst.add("Enue", IndexType::TheCellType(),1,ca_derenue,the_same_box); derive_lst.addComponent("Enue",desc_lst,Rad_Type,0,Radiation::nGroups); derive_lst.add("Enuae", IndexType::TheCellType(),1,ca_derenuae,the_same_box); derive_lst.addComponent("Enuae",desc_lst,Rad_Type,0,Radiation::nGroups); // // rho_Yl = rho(Ye + Ynue - Ynuebar) // derive_lst.add("rho_Yl",IndexType::TheCellType(),1,ca_derrhoyl,the_same_box); // Don't actually need density for rho * Yl derive_lst.addComponent("rho_Yl",desc_lst,State_Type,Density,1); // FirstAux is (rho * Ye) derive_lst.addComponent("rho_Yl",desc_lst,State_Type,FirstAux,1); derive_lst.addComponent("rho_Yl",desc_lst,Rad_Type,0,Radiation::nGroups); // // Yl = (Ye + Ynue - Ynuebar) // derive_lst.add("Yl",IndexType::TheCellType(),1,ca_deryl,the_same_box); derive_lst.addComponent("Yl",desc_lst,State_Type,Density,1); // FirstAux is (rho * Ye) derive_lst.addComponent("Yl",desc_lst,State_Type,FirstAux,1); derive_lst.addComponent("Yl",desc_lst,Rad_Type,0,Radiation::nGroups); // // Ynue // derive_lst.add("Ynue",IndexType::TheCellType(),1,ca_derynue,the_same_box); derive_lst.addComponent("Ynue",desc_lst,State_Type,Density,1); // FirstAux is (rho * Ye) derive_lst.addComponent("Ynue",desc_lst,State_Type,FirstAux,1); derive_lst.addComponent("Ynue",desc_lst,Rad_Type,0,Radiation::nGroups); // // Ynuebar // derive_lst.add("Ynuae",IndexType::TheCellType(),1,ca_derynuae,the_same_box); derive_lst.addComponent("Ynuae",desc_lst,State_Type,Density,1); // FirstAux is (rho * Ye) derive_lst.addComponent("Ynuae",desc_lst,State_Type,FirstAux,1); derive_lst.addComponent("Ynuae",desc_lst,Rad_Type,0,Radiation::nGroups); } #endif for (int i = 0; i < NumAux; i++) { derive_lst.add(aux_names[i],IndexType::TheCellType(),1,ca_derspec,the_same_box); derive_lst.addComponent(aux_names[i],desc_lst,State_Type,Density,1); derive_lst.addComponent(aux_names[i],desc_lst,State_Type,FirstAux+i,1); } #if 0 // // A derived quantity equal to all the state variables. // derive_lst.add("FULLSTATE",IndexType::TheCellType(),NUM_STATE,FORT_DERCOPY,the_same_box); derive_lst.addComponent("FULLSTATE",desc_lst,State_Type,Density,NUM_STATE); #endif // // Problem-specific adds #include <Problem_Derives.H> // // DEFINE ERROR ESTIMATION QUANTITIES // ErrorSetUp(); // // Construct an array holding the names of the source terms. // source_names.resize(num_src); // Fill with an empty string to initialize. for (int n = 0; n < num_src; ++n) source_names[n] = ""; source_names[ext_src] = "user-defined external"; source_names[thermo_src] = "pdivU source"; #ifdef SPONGE source_names[sponge_src] = "sponge"; #endif #ifdef DIFFUSION source_names[diff_src] = "diffusion"; #endif #ifdef HYBRID_MOMENTUM source_names[hybrid_src] = "hybrid"; #endif #ifdef GRAVITY source_names[grav_src] = "gravity"; #endif #ifdef ROTATION source_names[rot_src] = "rotation"; #endif #ifdef AMREX_USE_CUDA // Set the minimum number of threads needed per // threadblock to do BC fills with CUDA. We will // force this to be 8. The reason is that it is // not otherwise guaranteed for our thread blocks // to be aligned with the grid in such a way that // the synchronization logic in amrex_filccn works // out. We need at least NUM_GROW + 1 threads in a // block for CTU. If we used this minimum of 5, we // would hit cases where this doesn't work since // our blocking_factor is usually a power of 2, and // the thread blocks would not be aligned to guarantee // that the threadblocks containing the ghost zones // contained all of the ghost zones, as well as the // required interior zone. And for reflecting BCs, // we need NUM_GROW * 2 == 8 threads anyway. This logic // then requires that blocking_factor be a multiple // of 8. It is a little wasteful for MOL/SDC and for // problems that only have outflow BCs, but the BC // fill is not the expensive part of the algorithm // for our production science problems anyway, so // we ignore this extra cost in favor of safety. for (int dim = 0; dim < AMREX_SPACEDIM; ++dim) { numBCThreadsMin[dim] = 8; } #endif // method of lines Butcher tableau if (mol_order == 1) { // first order Euler MOL_STAGES = 1; a_mol.resize(MOL_STAGES); for (int n = 0; n < MOL_STAGES; ++n) a_mol[n].resize(MOL_STAGES); a_mol[0] = {1}; b_mol = {1.0}; c_mol = {0.0}; } else if (mol_order == 2) { // second order TVD MOL_STAGES = 2; a_mol.resize(MOL_STAGES); for (int n = 0; n < MOL_STAGES; ++n) a_mol[n].resize(MOL_STAGES); a_mol[0] = {0, 0,}; a_mol[1] = {1.0, 0,}; b_mol = {0.5, 0.5}; c_mol = {0.0, 1.0}; } else if (mol_order == 3) { // third order TVD MOL_STAGES = 3; a_mol.resize(MOL_STAGES); for (int n = 0; n < MOL_STAGES; ++n) a_mol[n].resize(MOL_STAGES); a_mol[0] = {0.0, 0.0, 0.0}; a_mol[1] = {1.0, 0.0, 0.0}; a_mol[2] = {0.25, 0.25, 0.0}; b_mol = {1./6., 1./6., 2./3.}; c_mol = {0.0, 1.0, 0.5}; } else if (mol_order == 4) { // fourth order TVD MOL_STAGES = 4; a_mol.resize(MOL_STAGES); for (int n = 0; n < MOL_STAGES; ++n) a_mol[n].resize(MOL_STAGES); a_mol[0] = {0.0, 0.0, 0.0, 0.0}; a_mol[1] = {0.5, 0.0, 0.0, 0.0}; a_mol[2] = {0.0, 0.5, 0.0, 0.0}; a_mol[3] = {0.0, 0.0, 1.0, 0.0}; b_mol = {1./6., 1./3., 1./3., 1./6.}; c_mol = {0.0, 0.5, 0.5, 1.0}; } else { amrex::Error("invalid value of mol_order\n"); } if (sdc_order == 2) { SDC_NODES = 2; dt_sdc.resize(SDC_NODES); dt_sdc = {0.0, 1.0}; } else if (sdc_order == 4) { SDC_NODES = 3; dt_sdc.resize(SDC_NODES); dt_sdc = {0.0, 0.5, 1.0}; } else { amrex::Error("invalid value of sdc_order"); } }
30.218213
125
0.682948
taehoryu
fd950068b66f62a9cda8be91187ffc09d07c0317
347
cpp
C++
SDK/MISC/sprites.cpp
playday3008/hack-cs-1.6-eV0L
40bdc3ef0fbe4d14a24939417efed6df58efe856
[ "MIT" ]
5
2020-05-02T17:29:32.000Z
2021-09-20T19:19:15.000Z
SDK/MISC/sprites.cpp
playday3008/hack-cs-1.6-eV0L
40bdc3ef0fbe4d14a24939417efed6df58efe856
[ "MIT" ]
null
null
null
SDK/MISC/sprites.cpp
playday3008/hack-cs-1.6-eV0L
40bdc3ef0fbe4d14a24939417efed6df58efe856
[ "MIT" ]
3
2020-05-02T19:03:48.000Z
2021-09-22T03:44:22.000Z
#include <windows.h> #define MAX_SPRITES 500 static char * sprites[MAX_SPRITES]; void add_sprite (int id, const char * sprite) { if ( id >= 0 && id < MAX_SPRITES ) sprites[id] = _strdup(sprite); } const char * sprite_lookup (int id) { if ( id >= 0 && id < MAX_SPRITES && sprites[id] ) return sprites[id]; else return "unknown"; }
15.086957
50
0.642651
playday3008
fd959e3560b430d01b109c088e8fdc86c2af665d
324
cpp
C++
atcoder.jp/abc171/abc171_b/Main.cpp
shikij1/AtCoder
7ae2946efdceaea3cc8725e99a2b9c137598e2f8
[ "MIT" ]
null
null
null
atcoder.jp/abc171/abc171_b/Main.cpp
shikij1/AtCoder
7ae2946efdceaea3cc8725e99a2b9c137598e2f8
[ "MIT" ]
null
null
null
atcoder.jp/abc171/abc171_b/Main.cpp
shikij1/AtCoder
7ae2946efdceaea3cc8725e99a2b9c137598e2f8
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; int main() { int n, k; cin >> n >> k; vector<int> p(n); for (int i = 0; i < n; i++) { cin >> p.at(i); } sort(p.begin(), p.end()); int ans = 0; for (int i = 0; i < k; i++) { ans += p.at(i); } cout << ans << endl; }
16.2
31
0.398148
shikij1
fd9608a96dc28699a5f4d4a75a9407d3b75524cc
1,057
cpp
C++
code/osx_clipboard.cpp
robbitay/ConstPort
d948ceb5f0e22504640578e3ef31e3823b29c1c3
[ "Unlicense" ]
null
null
null
code/osx_clipboard.cpp
robbitay/ConstPort
d948ceb5f0e22504640578e3ef31e3823b29c1c3
[ "Unlicense" ]
null
null
null
code/osx_clipboard.cpp
robbitay/ConstPort
d948ceb5f0e22504640578e3ef31e3823b29c1c3
[ "Unlicense" ]
null
null
null
/* File: osx_clipboard.cpp Author: Taylor Robbins Date: 10\07\2017 Description: ** Holds the functions that handle interfacing with the OSX clipboard #included from osx_main.cpp */ // +==============================+ // | OSX_CopyToClipboard | // +==============================+ // void OSX_CopyToClipboard(const void* dataPntr, u32 dataSize) CopyToClipboard_DEFINITION(OSX_CopyToClipboard) { char* tempSpace = (char*)malloc(dataSize+1); memcpy(tempSpace, dataPntr, dataSize); tempSpace[dataSize] = '\0'; glfwSetClipboardString(PlatformInfo.window, tempSpace); free(tempSpace); } // +==============================+ // | OSX_CopyFromClipboard | // +==============================+ // void* OSX_CopyFromClipboard(MemoryArena_t* arenaPntr, u32* dataLengthOut) CopyFromClipboard_DEFINITION(OSX_CopyFromClipboard) { *dataLengthOut = 0; const char* contents = glfwGetClipboardString(PlatformInfo.window); if (contents == nullptr) { return nullptr; } *dataLengthOut = (u32)strlen(contents); return (void*)contents; }
25.780488
76
0.645222
robbitay
fd96c243bab575938e03e880d4e9e4aed91aa768
35
cpp
C++
tests/syntax/bad/testfile-keyword1-1.cpp
xuedong/mini-cpp
3f4c505e3c422709e2da3fec1ecea7165f76292b
[ "MIT" ]
null
null
null
tests/syntax/bad/testfile-keyword1-1.cpp
xuedong/mini-cpp
3f4c505e3c422709e2da3fec1ecea7165f76292b
[ "MIT" ]
null
null
null
tests/syntax/bad/testfile-keyword1-1.cpp
xuedong/mini-cpp
3f4c505e3c422709e2da3fec1ecea7165f76292b
[ "MIT" ]
null
null
null
void m() { fora (i = 0; 1; i++); }
17.5
34
0.371429
xuedong
fd970f34f194556769ef7690cc14f1031e52ea60
2,182
cpp
C++
input-output_example_gen/bench/stencil_tiled.cpp
dongchen-coder/symRIByInputOuputExamples
e7434699f44ceb01f153ac8623b5bafac57f8abf
[ "MIT" ]
null
null
null
input-output_example_gen/bench/stencil_tiled.cpp
dongchen-coder/symRIByInputOuputExamples
e7434699f44ceb01f153ac8623b5bafac57f8abf
[ "MIT" ]
null
null
null
input-output_example_gen/bench/stencil_tiled.cpp
dongchen-coder/symRIByInputOuputExamples
e7434699f44ceb01f153ac8623b5bafac57f8abf
[ "MIT" ]
null
null
null
#include "./utility/rt.h" int DIM_SIZE; int TILE_SIZE; void stencil_trace(int *a, int *b, unsigned int dim_size, unsigned int tile_size) { vector<int> idx; for (int i = 1; i < dim_size+1 ; i += tile_size) { for (int j = 1; j < dim_size+1; j += tile_size) { for (int i_tiled = i; i_tiled < min(i+tile_size, dim_size+1); i_tiled++) { for (int j_tiled = j; j_tiled < min(j+tile_size, dim_size+1); j_tiled++) { idx.clear(); idx.push_back(i); idx.push_back(j); idx.push_back(i_tiled), idx.push_back(j_tiled); b[i_tiled* (DIM_SIZE + 2) +j_tiled] = a[i_tiled* (DIM_SIZE + 2)+j_tiled] + a[i_tiled* (DIM_SIZE + 2)+j_tiled + 1] + a[i_tiled* (DIM_SIZE + 2)+j_tiled - 1] + a[(i_tiled-1)* (DIM_SIZE + 2) +j_tiled] + a[(i_tiled+1)* (DIM_SIZE + 2) +j_tiled]; rtTmpAccess(i_tiled * (DIM_SIZE + 2) + j_tiled, 0, 0, idx); rtTmpAccess(i_tiled * (DIM_SIZE + 2) + j_tiled + 1, 1, 0, idx); rtTmpAccess(i_tiled * (DIM_SIZE + 2) + j_tiled - 1, 2, 0, idx); rtTmpAccess( (i_tiled-1) * (DIM_SIZE + 2) + j_tiled, 3, 0, idx); rtTmpAccess( (i_tiled+1) * (DIM_SIZE + 2) + j_tiled, 4, 0, idx); rtTmpAccess(i_tiled * (DIM_SIZE + 2) + j_tiled + (DIM_SIZE + 2)* (DIM_SIZE + 2), 5, 0, idx); } } } } return; } int main(int argc, char* argv[]) { if (argc != 3) { cout << "This benchmark needs 1 loop bounds" << endl; return 0; } for (int i = 1; i < argc; i++) { if (!isdigit(argv[i][0])) { cout << "arguments must be integer" << endl; return 0; } } DIM_SIZE = stoi(argv[1]); TILE_SIZE = stoi(argv[2]); int* a = (int*)malloc( (DIM_SIZE+2)* (DIM_SIZE+2)*sizeof(int)); int* b = (int*)malloc( (DIM_SIZE+2)* (DIM_SIZE+2)*sizeof(int)); for (int i = 0; i < (DIM_SIZE+2) * (DIM_SIZE+2); i++) { a[i] = i % 256; } stencil_trace(a, b, DIM_SIZE, TILE_SIZE); dumpRIHistogram(); return 0; }
34.09375
260
0.502291
dongchen-coder
fd9a2aa2b476753aee013574d07f04915d3804f9
18,463
cpp
C++
lib/offline/OfflineStorageHandler.cpp
lulululululu/cpp_client_telemetry
211acc586225d3f030fbf8bee016c4ab48e1c96a
[ "Apache-2.0" ]
null
null
null
lib/offline/OfflineStorageHandler.cpp
lulululululu/cpp_client_telemetry
211acc586225d3f030fbf8bee016c4ab48e1c96a
[ "Apache-2.0" ]
1
2021-03-03T11:37:10.000Z
2021-03-03T11:37:10.000Z
lib/offline/OfflineStorageHandler.cpp
isabella232/cpp_client_telemetry
46a7d65089799c216207ae4758980158affced47
[ "Apache-2.0" ]
null
null
null
// // Copyright (c) 2015-2020 Microsoft Corporation and Contributors. // SPDX-License-Identifier: Apache-2.0 // #include "OfflineStorageHandler.hpp" #include "OfflineStorageFactory.hpp" #include "offline/MemoryStorage.hpp" #include "ILogManager.hpp" #include <algorithm> #include <numeric> #include <set> namespace MAT_NS_BEGIN { MATSDK_LOG_INST_COMPONENT_CLASS(OfflineStorageHandler, "EventsSDK.StorageHandler", "Events telemetry client - OfflineStorageHandler class"); OfflineStorageHandler::OfflineStorageHandler(ILogManager& logManager, IRuntimeConfig& runtimeConfig, ITaskDispatcher& taskDispatcher) : m_observer(nullptr), m_logManager(logManager), m_config(runtimeConfig), m_taskDispatcher(taskDispatcher), m_killSwitchManager(), m_clockSkewManager(), m_flushPending(false), m_offlineStorageMemory(nullptr), m_offlineStorageDisk(nullptr), m_readFromMemory(false), m_lastReadCount(0), m_shutdownStarted(false), m_memoryDbSize(0), m_queryDbSize(0), m_isStorageFullNotificationSend(false) { // TODO: [MG] - OfflineStorage_SQLite.cpp is performing similar checks uint32_t percentage = m_config[CFG_INT_RAMCACHE_FULL_PCT]; uint32_t cacheMemorySizeLimitInBytes = m_config[CFG_INT_RAM_QUEUE_SIZE]; if (percentage > 0 && percentage <= 100) { m_memoryDbSizeNotificationLimit = (percentage * cacheMemorySizeLimitInBytes) / 100; } else { // In case if user has specified bad percentage, we stick to 75% m_memoryDbSizeNotificationLimit = (DB_FULL_NOTIFICATION_DEFAULT_PERCENTAGE * cacheMemorySizeLimitInBytes) / 100; } } bool OfflineStorageHandler::isKilled(StorageRecord const& record) { return ( /* fast */ m_killSwitchManager.isActive() && /* slower */ m_killSwitchManager.isTokenBlocked(record.tenantToken)); } void OfflineStorageHandler::WaitForFlush() { { LOCKGUARD(m_flushLock); if (!m_flushPending) return; } LOG_INFO("Waiting for pending Flush (%p) to complete...", m_flushHandle.m_task); m_flushComplete.wait(); } OfflineStorageHandler::~OfflineStorageHandler() { WaitForFlush(); if (nullptr != m_offlineStorageMemory) { m_offlineStorageMemory.reset(); } if (nullptr != m_offlineStorageDisk) { m_offlineStorageDisk.reset(); } } void OfflineStorageHandler::Initialize(IOfflineStorageObserver& observer) { m_observer = &observer; uint32_t cacheMemorySizeLimitInBytes = m_config[CFG_INT_RAM_QUEUE_SIZE]; m_offlineStorageDisk = OfflineStorageFactory::Create(m_logManager, m_config); m_offlineStorageDisk->Initialize(*this); // TODO: [MG] - consider passing m_offlineStorageDisk to m_offlineStorageMemory, // so that the Flush() op on memory storage leads to saving unflushed events to // disk. if (cacheMemorySizeLimitInBytes > 0) { m_offlineStorageMemory.reset(new MemoryStorage(m_logManager, m_config)); m_offlineStorageMemory->Initialize(*this); } m_shutdownStarted = false; LOG_TRACE("Initializing offline storage handler"); } void OfflineStorageHandler::Shutdown() { LOG_TRACE("Shutting down offline storage handler"); m_shutdownStarted = true; WaitForFlush(); if (nullptr != m_offlineStorageMemory) { m_offlineStorageMemory->ReleaseAllRecords(); Flush(); m_offlineStorageMemory->Shutdown(); } if (nullptr != m_offlineStorageDisk) { m_offlineStorageDisk->Shutdown(); } } /// <summary> /// Get estimated DB size /// </summary> /// <returns> /// Size of memory + disk storage /// </returns> /// <remarks> /// Value may change at runtime, so it's only approximate value. /// </remarks> size_t OfflineStorageHandler::GetSize() { size_t size = 0; if (m_offlineStorageMemory != nullptr) size += m_offlineStorageMemory->GetSize(); if (m_offlineStorageDisk != nullptr) size += m_offlineStorageDisk->GetSize(); return size; } size_t OfflineStorageHandler::GetRecordCount(EventLatency latency) const { size_t count = 0; if (m_offlineStorageMemory != nullptr) count += m_offlineStorageMemory->GetRecordCount(latency); if (m_offlineStorageDisk != nullptr) count += m_offlineStorageDisk->GetRecordCount(latency); return count; } void OfflineStorageHandler::Flush() { // Flush could be executed from context of worker thread, as well as from TPM and // after HTTP callback. Make sure it is atomic / thread-safe. LOCKGUARD(m_flushLock); // If item isn't scheduled yet, it gets canceled, so that we don't do two flushes. // If we are running that item right now (our thread), then nothing happens other // than the handle gets replaced by nullptr in this DeferredCallbackHandle obj. m_flushHandle.Cancel(); size_t dbSizeBeforeFlush = m_offlineStorageMemory->GetSize(); if ((m_offlineStorageMemory) && (dbSizeBeforeFlush > 0) && (m_offlineStorageDisk)) { // This will block on and then take a lock for the duration of this move, and // StoreRecord() will then block until the move completes. auto records = m_offlineStorageMemory->GetRecords(false, EventLatency_Unspecified); std::vector<StorageRecordId> ids; // TODO: [MG] - consider running the batch in transaction // if (sqlite) // sqlite->Execute("BEGIN"); size_t totalSaved = m_offlineStorageDisk->StoreRecords(records); // TODO: [MG] - consider running the batch in transaction // if (sqlite) // sqlite->Execute("END"); // Delete records from reserved on flush HttpHeaders dummy; bool fromMemory = true; m_offlineStorageMemory->DeleteRecords(ids, dummy, fromMemory); // Notify event listener about the records cached OnStorageRecordsSaved(totalSaved); if (m_offlineStorageMemory->GetSize() > dbSizeBeforeFlush) { // We managed to accumulate as much data as we had before the flush, // means we cannot keep up flushing at the same speed as incoming // obviously because the disk is slower than ram. LOG_WARN("Data is arriving too fast!"); } } m_isStorageFullNotificationSend = false; // Flush is done, notify the waiters m_flushComplete.post(); m_flushPending = false; } bool OfflineStorageHandler::StoreRecord(StorageRecord const& record) { // Don't discard on shutdown because the kill-switch may be temporary. // Attempt to upload after restart. if ((!m_shutdownStarted) && isKilled(record)) { // Discard unwanted records associated with killed tenant, reporting events as dropped return false; } // Check cache size only once at start static uint32_t cacheMemorySizeLimitInBytes = m_config[CFG_INT_RAM_QUEUE_SIZE]; if (nullptr != m_offlineStorageMemory && !m_shutdownStarted) { auto memDbSize = m_offlineStorageMemory->GetSize(); { // During flush, this will block on a mutex while records // are selected and removed from the cache (but will // not block for the subsequent handoff to persistent // storage) m_offlineStorageMemory->StoreRecord(record); } // Perform periodic flush to disk if (memDbSize > cacheMemorySizeLimitInBytes) { if (m_flushLock.try_lock()) { if (!m_flushPending) { m_flushPending = true; m_flushComplete.Reset(); m_flushHandle = PAL::scheduleTask(&m_taskDispatcher, 0, this, &OfflineStorageHandler::Flush); LOG_INFO("Requested Flush (%p)", m_flushHandle.m_task); } m_flushLock.unlock(); } } } else { if (m_offlineStorageDisk != nullptr) { if (record.persistence != EventPersistence::EventPersistence_DoNotStoreOnDisk) { m_offlineStorageDisk->StoreRecord(record); } } } return true; } size_t OfflineStorageHandler::StoreRecords(std::vector<StorageRecord>& records) { size_t stored = 0; for (auto& i : records) { if (StoreRecord(i)) { ++stored; } } return stored; } bool OfflineStorageHandler::ResizeDb() { if (nullptr != m_offlineStorageMemory) { m_offlineStorageMemory->ResizeDb(); } if (nullptr != m_offlineStorageDisk) { m_offlineStorageDisk->ResizeDb(); } return true; } bool OfflineStorageHandler::IsLastReadFromMemory() { return m_readFromMemory; } unsigned OfflineStorageHandler::LastReadRecordCount() { return m_lastReadCount; } bool OfflineStorageHandler::GetAndReserveRecords(std::function<bool(StorageRecord&&)> const& consumer, unsigned leaseTimeMs, EventLatency minLatency, unsigned maxCount) { bool returnValue = false; m_lastReadCount = 0; m_readFromMemory = false; if (m_offlineStorageMemory) { returnValue |= m_offlineStorageMemory->GetAndReserveRecords(consumer, leaseTimeMs, minLatency, maxCount); m_lastReadCount += m_offlineStorageMemory->LastReadRecordCount(); if (m_lastReadCount <= maxCount) maxCount -= m_lastReadCount; m_readFromMemory = true; // Prefer to send all of in-memory first before going to disk. This also helps in case if in-ram queue // is larger than request size (2MB), we'd exit the function because the consumer no longer wants more // records. if (m_lastReadCount) return returnValue; } if (m_offlineStorageDisk) { returnValue |= m_offlineStorageDisk->GetAndReserveRecords(consumer, leaseTimeMs, minLatency, maxCount); auto lastOfflineReadCount = m_offlineStorageDisk->LastReadRecordCount(); if (lastOfflineReadCount) { m_lastReadCount += lastOfflineReadCount; m_readFromMemory = false; } } if (m_config.IsClockSkewEnabled() && !m_clockSkewManager.GetResumeTransmissionAfterClockSkew() /* && !consumedIds.empty() */ ) { m_clockSkewManager.GetDelta(); } return returnValue; } std::vector<StorageRecord> OfflineStorageHandler::GetRecords(bool shutdown, EventLatency minLatency, unsigned maxCount) { // This method should not be called directly because it's a no-op assert(false); UNREFERENCED_PARAMETER(shutdown); UNREFERENCED_PARAMETER(minLatency); UNREFERENCED_PARAMETER(maxCount); return std::vector<StorageRecord>{}; } /** * Delete records by API ingestion key aka "Tenant Token". * Internal method used by DeleteRecords and ReleaseRecords * invoked by HTTP callback thread. The scrubbing is done * async in context where the HTTP callback is running. */ void OfflineStorageHandler::DeleteRecordsByKeys(const std::list<std::string>& keys) { for (const auto& key : keys) { /* DELETE * FROM events WHERE tenant_token=${key} */ DeleteRecords({{"tenant_token", key}}); } } /** * Delete all records locally". */ void OfflineStorageHandler::DeleteAllRecords() { for (const auto storagePtr : { m_offlineStorageMemory.get() , m_offlineStorageDisk.get() }) { if (storagePtr != nullptr) { storagePtr->DeleteAllRecords(); } } } /** * Perform scrub of both memory queue and offline storage. */ /// <summary> /// Perform scrub of underlying storage systems using 'where' clause /// </summary> /// <param name="whereFilter">The where filter.</param> /// <remarks> /// whereFilter contains the key-value pairs for the /// WHERE [key0==value0 .. keyN==valueN] clause. /// </remarks> void OfflineStorageHandler::DeleteRecords(const std::map<std::string, std::string>& whereFilter) { for (const auto storagePtr : {m_offlineStorageMemory.get(), m_offlineStorageDisk.get()}) { if (storagePtr != nullptr) { storagePtr->DeleteRecords(whereFilter); } } } /// <summary> /// Delete records that would match the set of ids or based on kill-switch header /// </summary> /// <param name="ids">Identifiers of records to delete</param> /// <param name="headers">Headers may indicate "Kill-Token" several times</param> /// <param name="fromMemory">Flag that indicates where to delete from by IDs</param> /// <remarks> /// IDs of records that are no longer found in the storage are silently ignored. /// Called from the internal worker thread. /// Killed tokens deleted from both - memory storage and offline storage if available. /// </remarks> void OfflineStorageHandler::DeleteRecords(std::vector<StorageRecordId> const& ids, HttpHeaders headers, bool& fromMemory) { if (m_clockSkewManager.isWaitingForClockSkew()) { m_clockSkewManager.handleResponse(headers); } /* Handle delete of killed tokens on 200 OK or non-retryable status code */ if ((!headers.empty()) && m_killSwitchManager.handleResponse(headers)) { /* Since we got the ask for a new token kill, means we sent something we should now stop sending */ LOG_TRACE("Scrub all pending events associated with killed token(s)"); DeleteRecordsByKeys(m_killSwitchManager.getTokensList()); } LOG_TRACE(" OfflineStorageHandler Deleting %u sent event(s) {%s%s}...", static_cast<unsigned>(ids.size()), ids.front().c_str(), (ids.size() > 1) ? ", ..." : ""); if (fromMemory && nullptr != m_offlineStorageMemory) { m_offlineStorageMemory->DeleteRecords(ids, headers, fromMemory); } else { if (nullptr != m_offlineStorageDisk) { m_offlineStorageDisk->DeleteRecords(ids, headers, fromMemory); } } } void OfflineStorageHandler::ReleaseRecords(std::vector<StorageRecordId> const& ids, bool incrementRetryCount, HttpHeaders headers, bool& fromMemory) { if (m_clockSkewManager.isWaitingForClockSkew()) { m_clockSkewManager.handleResponse(headers); } /* Handle delete of kills tokens on 503 or other retryable status code */ if ((!headers.empty()) && m_killSwitchManager.handleResponse(headers)) { /* Since we got the ask for a new token kill, means we sent something we should now stop sending */ LOG_TRACE("Scrub all pending events associated with killed token(s)"); DeleteRecordsByKeys(m_killSwitchManager.getTokensList()); } if (fromMemory && nullptr != m_offlineStorageMemory) { m_offlineStorageMemory->ReleaseRecords(ids, incrementRetryCount, headers, fromMemory); } else { if (nullptr != m_offlineStorageDisk) { m_offlineStorageDisk->ReleaseRecords(ids, incrementRetryCount, headers, fromMemory); } } } bool OfflineStorageHandler::StoreSetting(std::string const& name, std::string const& value) { if (nullptr != m_offlineStorageDisk) { m_offlineStorageDisk->StoreSetting(name, value); return true; } return false; } std::string OfflineStorageHandler::GetSetting(std::string const& name) { if (nullptr != m_offlineStorageDisk) { return m_offlineStorageDisk->GetSetting(name); } return ""; } bool OfflineStorageHandler::DeleteSetting(std::string const& name) { if (nullptr != m_offlineStorageDisk) { return m_offlineStorageDisk->DeleteSetting(name); } return false; } void OfflineStorageHandler::OnStorageOpened(std::string const& type) { m_observer->OnStorageOpened(type); } void OfflineStorageHandler::OnStorageFailed(std::string const& reason) { m_observer->OnStorageOpenFailed(reason); } void OfflineStorageHandler::OnStorageOpenFailed(std::string const& reason) { m_observer->OnStorageOpenFailed(reason); } void OfflineStorageHandler::OnStorageTrimmed(std::map<std::string, size_t> const& numRecords) { m_observer->OnStorageTrimmed(numRecords); } void OfflineStorageHandler::OnStorageRecordsDropped(std::map<std::string, size_t> const& numRecords) { m_observer->OnStorageRecordsDropped(numRecords); } void OfflineStorageHandler::OnStorageRecordsRejected(std::map<std::string, size_t> const& numRecords) { m_observer->OnStorageRecordsRejected(numRecords); } void OfflineStorageHandler::OnStorageRecordsSaved(size_t numRecords) { m_observer->OnStorageRecordsSaved(numRecords); } } MAT_NS_END
34.51028
172
0.612901
lulululululu
fd9b63a2ff034bce7550b1d9c585059b7a485831
1,357
cpp
C++
examples/sound/metering.cpp
AlloSphere-Research-Group/al_lib
94d23fe71b79d3464a658f16ca34c2040e6d7334
[ "BSD-3-Clause" ]
26
2018-11-05T23:29:43.000Z
2022-03-17T18:16:49.000Z
examples/sound/metering.cpp
yangevelyn/allolib
1654be795b6515c058eb8243751b903a2aa6efdc
[ "BSD-3-Clause" ]
41
2018-01-19T18:34:41.000Z
2022-01-27T23:52:01.000Z
examples/sound/metering.cpp
yangevelyn/allolib
1654be795b6515c058eb8243751b903a2aa6efdc
[ "BSD-3-Clause" ]
11
2018-01-05T16:42:19.000Z
2022-01-27T22:08:01.000Z
// OutputMaster example // By Andrés Cabrera mantaraya36@gmail.com // July 2018 #include <iostream> #include "al/app/al_App.hpp" #include "al/graphics/al_Shapes.hpp" // This example shows a simple input level meter using namespace al; struct MyApp : public App { float *meterValues; void onCreate() override { meterValues = new float(audioIO().channelsIn()); } void onSound(AudioIOData &io) override { while (io()) { for (auto i = 0; i < io.channelsOut(); i++) { // Write meter values. This is only safe because float is atomic on // desktops. if (meterValues[i] < fabs(io.in(0))) { meterValues[i] = io.in(0); } } } } void onDraw(Graphics &g) override { g.clear(0); // Copies the current values to the array passed Mesh m; addQuad(m, 0.2f, 0.2f); g.color(1.0); for (auto i = 0; i < audioIO().channelsOut(); i++) { g.pushMatrix(); g.color(HSV(0.5f + 0.5f * meterValues[i])); g.translate(-1.0f + (2.0f * i / (audioIO().channelsOut() - 1.0f)), -0.5f + meterValues[i], -4); meterValues[i] = 0; g.draw(m); g.popMatrix(); } } }; int main(int argc, char *argv[]) { MyApp app; app.title("Stereo Audio Scene"); app.fps(30); app.configureAudio(44100, 256, 2, 2); app.start(); return 0; }
23
79
0.580693
AlloSphere-Research-Group
fd9bac4ea6c171531547acca5321b589e4b835f5
331
hpp
C++
include/lua_blt_debug.hpp
magicmoremagic/bengine-blt
fc2e07107dca0689d44ebd066b74d5bac7cacfa8
[ "MIT" ]
null
null
null
include/lua_blt_debug.hpp
magicmoremagic/bengine-blt
fc2e07107dca0689d44ebd066b74d5bac7cacfa8
[ "MIT" ]
null
null
null
include/lua_blt_debug.hpp
magicmoremagic/bengine-blt
fc2e07107dca0689d44ebd066b74d5bac7cacfa8
[ "MIT" ]
null
null
null
#pragma once #ifndef BE_BLT_LUA_BLT_DEBUG_HPP_ #define BE_BLT_LUA_BLT_DEBUG_HPP_ #include <lua/lua.h> #include <lua/lauxlib.h> namespace be::belua { /////////////////////////////////////////////////////////////////////////////// int open_blt_debug(lua_State* L); extern const luaL_Reg blt_debug_module; } // be::belua #endif
18.388889
79
0.586103
magicmoremagic
fd9c2ba127d918e8af4c838a2055f606c87b22f5
3,133
cpp
C++
main_d1/editor/kcurve.cpp
ziplantil/CacaoticusDescent
b4299442bc43310690a666e181dd983c1491dce1
[ "MIT" ]
22
2019-08-19T21:09:29.000Z
2022-03-25T23:19:15.000Z
main_d1/editor/kcurve.cpp
ziplantil/CacaoticusDescent
b4299442bc43310690a666e181dd983c1491dce1
[ "MIT" ]
6
2019-11-08T22:17:03.000Z
2022-03-10T05:02:59.000Z
main_d1/editor/kcurve.cpp
ziplantil/CacaoticusDescent
b4299442bc43310690a666e181dd983c1491dce1
[ "MIT" ]
6
2019-08-24T08:03:14.000Z
2022-02-04T15:04:52.000Z
/* THE COMPUTER CODE CONTAINED HEREIN IS THE SOLE PROPERTY OF PARALLAX SOFTWARE CORPORATION ("PARALLAX"). PARALLAX, IN DISTRIBUTING THE CODE TO END-USERS, AND SUBJECT TO ALL OF THE TERMS AND CONDITIONS HEREIN, GRANTS A ROYALTY-FREE, PERPETUAL LICENSE TO SUCH END-USERS FOR USE BY SUCH END-USERS IN USING, DISPLAYING, AND CREATING DERIVATIVE WORKS THEREOF, SO LONG AS SUCH USE, DISPLAY OR CREATION IS FOR NON-COMMERCIAL, ROYALTY OR REVENUE FREE PURPOSES. IN NO EVENT SHALL THE END-USER USE THE COMPUTER CODE CONTAINED HEREIN FOR REVENUE-BEARING PURPOSES. THE END-USER UNDERSTANDS AND AGREES TO THE TERMS HEREIN AND ACCEPTS THE SAME BY USE OF THIS FILE. COPYRIGHT 1993-1998 PARALLAX SOFTWARE CORPORATION. ALL RIGHTS RESERVED. */ #ifdef EDITOR #include <string.h> #include "main_d1/inferno.h" #include "editor.h" #include "kdefs.h" static fix r1scale, r4scale; static int curve; int InitCurve() { curve = 0; return 1; } int GenerateCurve() { if ( (Markedsegp != 0) && !IS_CHILD(Markedsegp->children[Markedside])) { r1scale = r4scale = F1_0*20; autosave_mine( mine_filename ); diagnostic_message("Curve Generated."); Update_flags |= UF_WORLD_CHANGED; curve = generate_curve(r1scale, r4scale); mine_changed = 1; if (curve == 1) { strcpy(undo_status[Autosave_count], "Curve Generation UNDONE.\n"); } if (curve == 0) diagnostic_message("Cannot generate curve -- check Current segment."); } else diagnostic_message("Cannot generate curve -- check Marked segment."); warn_if_concave_segments(); return 1; } int DecreaseR4() { if (curve) { Update_flags |= UF_WORLD_CHANGED; delete_curve(); r4scale -= F1_0; generate_curve(r1scale, r4scale); diagnostic_message("R4 vector decreased."); mine_changed = 1; warn_if_concave_segments(); } return 1; } int IncreaseR4() { if (curve) { Update_flags |= UF_WORLD_CHANGED; delete_curve(); r4scale += F1_0; generate_curve(r1scale, r4scale); diagnostic_message("R4 vector increased."); mine_changed = 1; warn_if_concave_segments(); } return 1; } int DecreaseR1() { if (curve) { Update_flags |= UF_WORLD_CHANGED; delete_curve(); r1scale -= F1_0; generate_curve(r1scale, r4scale); diagnostic_message("R1 vector decreased."); mine_changed = 1; warn_if_concave_segments(); } return 1; } int IncreaseR1() { if (curve) { Update_flags |= UF_WORLD_CHANGED; delete_curve(); r1scale += F1_0; generate_curve(r1scale, r4scale); diagnostic_message("R1 vector increased."); mine_changed = 1; warn_if_concave_segments(); } return 1; } int DeleteCurve() { // fix_bogus_uvs_all(); set_average_light_on_curside(); if (curve) { Update_flags |= UF_WORLD_CHANGED; delete_curve(); curve = 0; mine_changed = 1; diagnostic_message("Curve Deleted."); warn_if_concave_segments(); } return 1; } int SetCurve() { if (curve) curve = 0; //autosave_mine( mine_filename ); //strcpy(undo_status[Autosave_count], "Curve Generation UNDONE.\n"); return 1; } #endif
23.734848
94
0.691031
ziplantil
fd9c65cff4c22e9600b1a2369c1c0ef5af326a73
2,822
cpp
C++
Components/Paging/src/OgrePageContentCollection.cpp
rjdgtn/OgreCPPBuilder
1d3fa5874e54da9c19f4fe9fd128fcda19285b5e
[ "MIT" ]
108
2015-01-23T01:43:56.000Z
2021-12-23T07:00:48.000Z
Components/Paging/src/OgrePageContentCollection.cpp
venscn/ogre
069a43c4c4fcb5264c995fca65a28acd3154b230
[ "MIT" ]
2
2016-03-05T14:40:20.000Z
2017-02-20T11:33:51.000Z
Components/Paging/src/OgrePageContentCollection.cpp
venscn/ogre
069a43c4c4fcb5264c995fca65a28acd3154b230
[ "MIT" ]
92
2015-01-13T08:57:11.000Z
2021-09-19T05:20:55.000Z
/* ----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org/ Copyright (c) 2000-2011 Torus Knot Software Ltd 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 "OgrePageContentCollection.h" #include "OgrePageContentCollectionFactory.h" #include "OgreStreamSerialiser.h" #include "OgrePageContent.h" #include "OgrePage.h" namespace Ogre { //--------------------------------------------------------------------- const uint32 PageContentCollection::CHUNK_ID = StreamSerialiser::makeIdentifier("PGCC"); const uint16 PageContentCollection::CHUNK_VERSION = 1; //--------------------------------------------------------------------- PageContentCollection::PageContentCollection(PageContentCollectionFactory* creator) : mCreator(creator), mParent(0) { } //--------------------------------------------------------------------- PageContentCollection::~PageContentCollection() { // don't call destroy(), we're not the final subclass } //--------------------------------------------------------------------- PageManager* PageContentCollection::getManager() const { return mParent->getManager(); } //--------------------------------------------------------------------- const String& PageContentCollection::getType() const { return mCreator->getName(); } //--------------------------------------------------------------------- void PageContentCollection::_notifyAttached(Page* parent) { mParent = parent; } //--------------------------------------------------------------------- SceneManager* PageContentCollection::getSceneManager() const { return mParent->getSceneManager(); } }
38.135135
89
0.600283
rjdgtn
fd9f3b0459849abb0072bd7323eb50d492d7fdee
14,122
cpp
C++
src/joystick_node.cpp
SS47816/lgsvl-utils
ec8d03b228d270c3485be0badea48f81c405c058
[ "MIT" ]
3
2022-01-13T12:39:11.000Z
2022-03-31T01:48:41.000Z
src/joystick_node.cpp
SS47816/lgsvl-utils
ec8d03b228d270c3485be0badea48f81c405c058
[ "MIT" ]
1
2021-12-07T15:29:26.000Z
2021-12-07T15:29:26.000Z
src/joystick_node.cpp
SS47816/lgsvl_utils
ec8d03b228d270c3485be0badea48f81c405c058
[ "MIT" ]
null
null
null
/* joystick_node.cpp * Copyright (C) 2021 SS47816 * ROS Node for controlling the vehicle using joysticks **/ #include <math.h> #include <ros/ros.h> #include <ros/console.h> #include <std_msgs/String.h> #include <sensor_msgs/Joy.h> #include <lgsvl_msgs/VehicleControlData.h> #include <lgsvl_msgs/VehicleStateData.h> #include <autoware_msgs/VehicleCmd.h> class JoystickTeleop { public: JoystickTeleop(); private: bool is_healthy_ = true; int curr_mode_; int curr_gear_; float deadzone_; float steering_limit_; // [deg] std::string joy_type_; std::string control_setting_; std::string steering_mapping_; std_msgs::String curr_mode_name_; std_msgs::String curr_gear_name_; ros::NodeHandle nh; ros::Subscriber joystick_sub; ros::Subscriber autonomous_cmd_sub; ros::Subscriber health_monitor_sub; ros::Publisher vehicle_cmd_pub; ros::Publisher vehicle_state_pub; ros::Publisher pub_curr_mode; ros::Publisher pub_curr_gear; void joystickCallback(const sensor_msgs::Joy::ConstPtr& joy_msg); void autonomousCmdCallback(const autoware_msgs::VehicleCmd::ConstPtr& auto_cmd_msg); // void healthMonitorCallback(const agv::HealthMonitor::ConstPtr& health_msg); }; JoystickTeleop::JoystickTeleop() { ros::NodeHandle private_nh("~"); std::string joy_topic; std::string autonomous_cmd_topic; std::string vehicle_cmd_topic; std::string vehicle_state_topic; std::string curr_mode_topic; std::string curr_gear_topic; // std::string health_monitor_topic; ROS_ASSERT(private_nh.getParam("joy_topic", joy_topic)); ROS_ASSERT(private_nh.getParam("joy_type", joy_type_)); ROS_ASSERT(private_nh.getParam("control_setting", control_setting_)); ROS_ASSERT(private_nh.getParam("steering_mapping", steering_mapping_)); ROS_ASSERT(private_nh.getParam("autonomous_cmd_topic", autonomous_cmd_topic)); ROS_ASSERT(private_nh.getParam("vehicle_cmd_topic", vehicle_cmd_topic)); ROS_ASSERT(private_nh.getParam("vehicle_state_topic", vehicle_state_topic)); ROS_ASSERT(private_nh.getParam("curr_mode_topic", curr_mode_topic)); ROS_ASSERT(private_nh.getParam("curr_gear_topic", curr_gear_topic)); // ROS_ASSERT(private_nh.getParam("health_monitor_topic", health_monitor_topic)); ROS_ASSERT(private_nh.getParam("steering_limit", steering_limit_)); ROS_ASSERT(private_nh.getParam("deadzone", deadzone_)); joystick_sub = nh.subscribe(joy_topic, 1, &JoystickTeleop::joystickCallback, this); autonomous_cmd_sub = nh.subscribe(autonomous_cmd_topic, 1, &JoystickTeleop::autonomousCmdCallback, this); // health_monitor_sub = nh.subscribe(health_monitor_topic, 1, &JoystickTeleop::healthMonitorCallback, this); vehicle_cmd_pub = nh.advertise<lgsvl_msgs::VehicleControlData>(vehicle_cmd_topic, 1); vehicle_state_pub = nh.advertise<lgsvl_msgs::VehicleStateData>(vehicle_state_topic, 1); pub_curr_mode = nh.advertise<std_msgs::String>(curr_mode_topic, 1); pub_curr_gear = nh.advertise<std_msgs::String>(curr_gear_topic, 1); curr_mode_name_.data = "MANUAL"; curr_gear_name_.data = "PARKING"; curr_mode_ = lgsvl_msgs::VehicleStateData::VEHICLE_MODE_COMPLETE_MANUAL; curr_gear_ == lgsvl_msgs::VehicleControlData::GEAR_PARKING; ROS_INFO("joy_type: using %s\n", joy_type_.c_str()); } void JoystickTeleop::joystickCallback(const sensor_msgs::Joy::ConstPtr& joy_msg) { bool A, B, X, Y, LB, RB, button_stick_left, button_stick_right; float LT, RT, LR_axis_stick_L, UD_axis_stick_L, LR_axis_stick_R, UD_axis_stick_R, cross_key_LR, cross_key_UD; float accel_axes, brake_axes, steer_axes; lgsvl_msgs::VehicleControlData vehicle_cmd; vehicle_cmd.header = joy_msg->header; vehicle_cmd.header.frame_id = "base_link"; vehicle_cmd.target_wheel_angular_rate = 0.0; vehicle_cmd.acceleration_pct = 0.0; vehicle_cmd.braking_pct = 1.0; lgsvl_msgs::VehicleStateData vehicle_state; vehicle_state.header = joy_msg->header; vehicle_state.header.frame_id = "base_link"; vehicle_state.blinker_state = lgsvl_msgs::VehicleStateData::BLINKERS_OFF; vehicle_state.headlight_state = lgsvl_msgs::VehicleStateData::HEADLIGHTS_OFF; vehicle_state.wiper_state = lgsvl_msgs::VehicleStateData::WIPERS_OFF; vehicle_state.autonomous_mode_active = 0; vehicle_state.hand_brake_active = 0; vehicle_state.horn_active = 0; // Select the joystick type used if (joy_type_.compare("F710") == 0) // Logitech F710 XInput Mode { A = joy_msg->buttons[0]; B = joy_msg->buttons[1]; X = joy_msg->buttons[2]; Y = joy_msg->buttons[3]; // LB = joy_msg->buttons[4]; // doing nothing // RB = joy_msg->buttons[5]; // doing nothing // button_stick_left = joy_msg->buttons[10]; // doing nothing // button_stick_right = joy_msg->buttons[11]; // doing nothing cross_key_LR = joy_msg->axes[0]; cross_key_UD = joy_msg->axes[1]; LT = joy_msg->axes[2]; // [0, 1], doing nothing LR_axis_stick_R = joy_msg->axes[3]; UD_axis_stick_R = joy_msg->axes[4]; RT = joy_msg->axes[5]; // [0, 1], release the full power // LR_axis_stick_L = joy_msg->axes[6]; // doing nothing // UD_axis_stick_L = joy_msg->axes[7]; // doing nothing } else if (joy_type_.compare("Xbox") == 0) // default using xbox wired controller { A = joy_msg->buttons[0]; B = joy_msg->buttons[1]; X = joy_msg->buttons[2]; Y = joy_msg->buttons[3]; // LB = joy_msg->buttons[4]; // doing nothing // RB = joy_msg->buttons[5]; // doing nothing // button_stick_left = joy_msg->buttons[9]; // doing nothing // button_stick_right = joy_msg->buttons[10]; // doing nothing LR_axis_stick_L = joy_msg->axes[0]; UD_axis_stick_L = joy_msg->axes[1]; LT = joy_msg->axes[2]; // [1.0, -1.0], doing nothing LR_axis_stick_R = joy_msg->axes[3]; UD_axis_stick_R = joy_msg->axes[4]; RT = joy_msg->axes[5]; // [1.0, -1.0], release the full power // cross_key_LR = joy_msg->axes[6]; // doing nothing // cross_key_UD = joy_msg->axes[7]; // doing nothing } else { ROS_ERROR("[joystick_node]: Invalid joystick type (%s) used, 'Xbox' or 'F710' expected", joy_type_.c_str()); return; } // Select the joystick control setting used if (control_setting_.compare("ForzaHorizon") == 0) { accel_axes = (-RT + 1.0)/2.0; brake_axes = (-LT + 1.0)/2.0; steer_axes = LR_axis_stick_L; } else if (control_setting_.compare("JapanHand") == 0) { accel_axes = UD_axis_stick_R; brake_axes = -accel_axes; steer_axes = LR_axis_stick_L; } else if (control_setting_.compare("USAHand") == 0) { accel_axes = UD_axis_stick_L; brake_axes = -accel_axes; steer_axes = LR_axis_stick_R; } else { ROS_ERROR("[joystick_node]: Invalid control setting (%s) used, 'ForzaHorizon', 'JapanHand' or 'USAHand' expected", control_setting_.c_str()); return; } // Switch Vehicle Mode and Gear if (B) { // Manual Mode, Parking Gear curr_mode_name_.data = "MANUAL"; curr_mode_ = lgsvl_msgs::VehicleStateData::VEHICLE_MODE_COMPLETE_MANUAL; curr_gear_name_.data = "PARKING"; curr_gear_ = lgsvl_msgs::VehicleControlData::GEAR_PARKING; } else if (X) { // Manual Mode, Forward Gear curr_mode_name_.data = "MANUAL"; curr_mode_ = lgsvl_msgs::VehicleStateData::VEHICLE_MODE_COMPLETE_MANUAL; curr_gear_name_.data = "DRIVE"; curr_gear_ = lgsvl_msgs::VehicleControlData::GEAR_DRIVE; } else if (Y) { // Manual Mode, Reverse Gear curr_mode_name_.data = "MANUAL"; curr_mode_ = lgsvl_msgs::VehicleStateData::VEHICLE_MODE_COMPLETE_MANUAL; curr_gear_name_.data = "REVERSE"; curr_gear_ = lgsvl_msgs::VehicleControlData::GEAR_REVERSE; } else if (A) { // Autonomous Mode, Auto Gear if (!is_healthy_) { // Emergency Mode, Neutral Gear curr_mode_name_.data = "EMERGENCY"; curr_mode_ = lgsvl_msgs::VehicleStateData::VEHICLE_MODE_EMERGENCY_MODE; curr_gear_name_.data = "NEUTRAL"; curr_gear_ = lgsvl_msgs::VehicleControlData::GEAR_NEUTRAL; vehicle_state.hand_brake_active = 1; ROS_ERROR("[Emergency Mode]: Unhealthy vehicle!"); return; } else if (curr_mode_ == lgsvl_msgs::VehicleStateData::VEHICLE_MODE_COMPLETE_MANUAL && curr_gear_ == lgsvl_msgs::VehicleControlData::GEAR_PARKING) { // Autonomous Mode, Drive TBD curr_mode_name_.data = "AUTONOMOUS"; curr_mode_ = lgsvl_msgs::VehicleStateData::VEHICLE_MODE_COMPLETE_AUTO_DRIVE; } else if (curr_mode_ == lgsvl_msgs::VehicleStateData::VEHICLE_MODE_COMPLETE_AUTO_DRIVE) { ROS_DEBUG("[ Auto Mode ]: Vehicle Already in Autonomous Mode"); return; } else { ROS_DEBUG("[joystick_node]: Can only enter Autonomous Mode from Brake Mode!"); return; } } // Publish vehicle control messages based on vehicle mode if (curr_mode_ == lgsvl_msgs::VehicleStateData::VEHICLE_MODE_COMPLETE_AUTO_DRIVE) { // Empty Action, Let autonomousCmdCallback() function handle publishing autonomous mode messages pub_curr_mode.publish(curr_mode_name_); pub_curr_gear.publish(curr_gear_name_); return; } else if (curr_mode_ == lgsvl_msgs::VehicleStateData::VEHICLE_MODE_COMPLETE_MANUAL) { // Map Accel & Brake axes output if (curr_gear_ == lgsvl_msgs::VehicleControlData::GEAR_DRIVE) { vehicle_cmd.acceleration_pct = accel_axes; vehicle_cmd.braking_pct = brake_axes; } else if (curr_gear_ == lgsvl_msgs::VehicleControlData::GEAR_REVERSE) { vehicle_cmd.acceleration_pct = brake_axes; vehicle_cmd.braking_pct = accel_axes; } // Map Steering axes output if (control_setting_.compare("Quadratic") == 0) { vehicle_cmd.target_wheel_angle = -(steer_axes*steer_axes)*steering_limit_/180.0*M_PI; } else { vehicle_cmd.target_wheel_angle = -steer_axes*steering_limit_/180.0*M_PI; } // ROS_DEBUG("[Manual Mode]: Steering Goal Angle: %.1f [deg] Throttle Value: %.2f", // joy_type_.c_str(), vehicle_cmd.target_wheel_angle*180.0/M_PI, vehicle_cmd.acceleration_pct); } else { // Emergency Mode, Neutral Gear curr_mode_name_.data = "EMERGENCY"; curr_mode_ = lgsvl_msgs::VehicleStateData::VEHICLE_MODE_EMERGENCY_MODE; curr_gear_name_.data = "NEUTRAL"; curr_gear_ = lgsvl_msgs::VehicleControlData::GEAR_NEUTRAL; vehicle_state.hand_brake_active = 1; ROS_ERROR("[Emergency Mode]: Unhealthy vehicle!"); } // Publish final vehicle command, state, mode, and gear messages vehicle_cmd.target_gear = curr_gear_; vehicle_cmd_pub.publish(std::move(vehicle_cmd)); vehicle_state.vehicle_mode = curr_mode_; vehicle_state.current_gear = curr_gear_; vehicle_state_pub.publish(std::move(vehicle_state)); pub_curr_mode.publish(curr_mode_name_); pub_curr_gear.publish(curr_gear_name_); return; } void JoystickTeleop::autonomousCmdCallback(const autoware_msgs::VehicleCmd::ConstPtr& auto_cmd_msg) { if (curr_mode_ != lgsvl_msgs::VehicleStateData::VEHICLE_MODE_COMPLETE_AUTO_DRIVE) { return; } lgsvl_msgs::VehicleControlData vehicle_cmd; vehicle_cmd.header = auto_cmd_msg->header; vehicle_cmd.header.frame_id = "base_link"; lgsvl_msgs::VehicleStateData vehicle_state; vehicle_state.header = auto_cmd_msg->header; vehicle_state.header.frame_id = "base_link"; vehicle_state.blinker_state = lgsvl_msgs::VehicleStateData::BLINKERS_OFF; vehicle_state.headlight_state = lgsvl_msgs::VehicleStateData::HEADLIGHTS_OFF; vehicle_state.wiper_state = lgsvl_msgs::VehicleStateData::WIPERS_OFF; vehicle_state.vehicle_mode = lgsvl_msgs::VehicleStateData::VEHICLE_MODE_COMPLETE_AUTO_DRIVE; vehicle_state.autonomous_mode_active = 1; vehicle_state.hand_brake_active = 0; vehicle_state.horn_active = 0; if (!is_healthy_) { // Emergency Mode, Neutral Gear curr_mode_name_.data = "EMERGENCY"; curr_mode_ = lgsvl_msgs::VehicleStateData::VEHICLE_MODE_EMERGENCY_MODE; curr_gear_name_.data = "NEUTRAL"; curr_gear_ = lgsvl_msgs::VehicleControlData::GEAR_NEUTRAL; vehicle_state.hand_brake_active = 1; ROS_ERROR("[Emergency Mode]: Unhealthy vehicle!"); } else if (auto_cmd_msg->gear_cmd.gear == autoware_msgs::Gear::PARK) { curr_gear_ = lgsvl_msgs::VehicleControlData::GEAR_PARKING; curr_gear_name_.data = "PARKING"; } else if (auto_cmd_msg->gear_cmd.gear == autoware_msgs::Gear::DRIVE) { curr_gear_ = lgsvl_msgs::VehicleControlData::GEAR_DRIVE; curr_gear_name_.data = "DRIVE"; vehicle_cmd.acceleration_pct = std::fabs(std::max(0.0, auto_cmd_msg->twist_cmd.twist.linear.x)); vehicle_cmd.braking_pct = std::fabs(std::min(0.0, auto_cmd_msg->twist_cmd.twist.linear.x)); vehicle_cmd.target_wheel_angle = -(auto_cmd_msg->twist_cmd.twist.angular.z); } else if (auto_cmd_msg->gear_cmd.gear == autoware_msgs::Gear::REVERSE) { curr_gear_ = lgsvl_msgs::VehicleControlData::GEAR_REVERSE; curr_gear_name_.data = "REVERSE"; } else if (auto_cmd_msg->gear_cmd.gear == autoware_msgs::Gear::LOW) { curr_gear_ = lgsvl_msgs::VehicleControlData::GEAR_LOW; curr_gear_name_.data = "LOW"; } else { curr_gear_ = lgsvl_msgs::VehicleControlData::GEAR_NEUTRAL; curr_gear_name_.data = "NEUTRAL"; } // ROS_DEBUG("[ Auto Mode ]: Steering Goal Angle: %.1f [deg] Throttle Value: %.2f", // joy_type_.c_str(), vehicle_cmd.target_wheel_angle*180.0/M_PI, vehicle_cmd.acceleration_pct); vehicle_cmd.target_gear = curr_gear_; vehicle_cmd_pub.publish(std::move(vehicle_cmd)); vehicle_state.current_gear = curr_gear_; vehicle_state_pub.publish(std::move(vehicle_state)); pub_curr_mode.publish(curr_mode_name_); pub_curr_gear.publish(curr_gear_name_); return; } int main(int argc, char** argv) { ros::init(argc, argv, "joystick_node"); JoystickTeleop joystick_teleop_obj; ros::spin(); return 0; }
36.585492
145
0.714559
SS47816
fd9f677956fdd04c41a4c5bc69eebff87eeb6257
3,156
hpp
C++
includes/sigma-male-algorithm.hpp
TheLandfill/tsp
ae2b90c8a44f4521373259a587d4c91c5bc318a3
[ "MIT" ]
null
null
null
includes/sigma-male-algorithm.hpp
TheLandfill/tsp
ae2b90c8a44f4521373259a587d4c91c5bc318a3
[ "MIT" ]
null
null
null
includes/sigma-male-algorithm.hpp
TheLandfill/tsp
ae2b90c8a44f4521373259a587d4c91c5bc318a3
[ "MIT" ]
null
null
null
#pragma once #include "matrix.hpp" #include "max-or-inf.hpp" #include "global-greedy.hpp" #include "edge.hpp" #include "print-info.hpp" #include "k-opt.hpp" #include <unordered_set> #include <random> #include <iostream> #include <cmath> template<typename T> class Sigma_Male { public: Sigma_Male(uint32_t seed, double recency = 1.0 / 1024.0); void grind(const Matrix<T>& mat, size_t start, size_t num_iterations, bool run_kopt = true); const Matrix<double>& get_freq_mat(); T get_min_path_length() const; const std::vector<size_t>& get_shortest_path_found(); private: Matrix<double> frequency; std::vector<size_t> shortest_path_found; T min_path_length; std::mt19937 rng; double recency; }; template<typename T> Sigma_Male<T>::Sigma_Male(uint32_t s, double r) : min_path_length{get_max_val_or_inf<T>()}, rng{s}, recency(r) {} template<typename T> void Sigma_Male<T>::grind(const Matrix<T>& mat, size_t start, size_t num_iterations, bool run_kopt) { frequency = Matrix<double>(mat.get_num_rows(), mat.get_num_cols(), [](){ return 0; }); Global_Greedy<T> gg; Matrix<T> cur_mat = mat; K_Opt<T> kopt(137, 5); double cur_path_length = 1.0; double thing_to_add = 0.0; for (size_t i = 0; i < num_iterations; i++) { gg.run(cur_mat, start); std::vector<size_t> path = gg.get_path(); if (run_kopt) { //print_path(path); //std::cout << "Path Length: " << get_path_length(path, mat) << "\n"; kopt.run(mat, start, path); //print_path(path); //std::cout << "Path Length: " << get_path_length(path, mat) << "\n"; //std::cout << "--------------------------------------------------------------------------------\n"; } cur_path_length = get_path_length(path, mat); if (cur_path_length < min_path_length) { min_path_length = get_path_length(path, mat); shortest_path_found = path; } std::vector<Edge> edges; edges.reserve(path.size()); T path_length{}; for (size_t j = 0; j < path.size() - 1; j++) { const size_t& cur = path[j]; const size_t& next = path[j + 1]; if (cur_path_length <= min_path_length) { thing_to_add = 1.0; } else { thing_to_add = 1.0 / (1.0 + cur_path_length - min_path_length); thing_to_add *= thing_to_add; } frequency.at(cur, next) *= (1.0 - recency); frequency.at(cur, next) += thing_to_add * recency; edges.push_back({cur, next}); path_length += mat.at(cur, next); } // std::cout << "Path Length: " << path_length << "\n"; cur_mat = mat; std::vector<double> edge_weights; edge_weights.reserve(edges.size()); for (const Edge& edge : edges) { T cur_edge_length = mat.at(edge.start, edge.end); edge_weights.push_back(mat.at(edge.start, edge.end)); } std::discrete_distribution<size_t> dist{edge_weights.begin(), edge_weights.end()}; for (size_t j = 0; j < 2 * sqrt(edges.size()); j++) { const Edge& cur_edge = edges[dist(rng)]; cur_mat.at(cur_edge.start, cur_edge.end) = get_max_val_or_inf<T>() / mat.get_num_cols(); } } } template<typename T> const Matrix<double>& Sigma_Male<T>::get_freq_mat() { return frequency; } template<typename T> T Sigma_Male<T>::get_min_path_length() const { return min_path_length; }
32.204082
113
0.66033
TheLandfill
fd9f7924ebf04332cf47b9b218a81f138e03bb0e
2,920
hpp
C++
ble-cpp/src/impl/StatusInitializerStub.hpp
harsh-agarwal/blelocpp
eaba46c6239981c7b8e69bef2ab33bb08ecb15b4
[ "MIT" ]
8
2016-06-13T20:47:18.000Z
2021-12-22T17:29:32.000Z
ble-cpp/src/impl/StatusInitializerStub.hpp
harsh-agarwal/blelocpp
eaba46c6239981c7b8e69bef2ab33bb08ecb15b4
[ "MIT" ]
11
2016-03-14T07:00:04.000Z
2019-05-07T18:20:15.000Z
ble-cpp/src/impl/StatusInitializerStub.hpp
harsh-agarwal/blelocpp
eaba46c6239981c7b8e69bef2ab33bb08ecb15b4
[ "MIT" ]
11
2016-02-03T07:41:00.000Z
2019-09-11T10:03:48.000Z
/******************************************************************************* * Copyright (c) 2014, 2015 IBM Corporation and others * * 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 StatusInitializerStub_hpp #define StatusInitializerStub_hpp #include <stdio.h> #include "StatusInitializer.hpp" namespace loc{ class StatusInitializerStub : public StatusInitializer{ public: Locations initializeLocations(int n){ Locations locs; //int n= 100; for(int i=0; i<n; i++){ Location loc(0,0,0,0); locs.push_back(loc); } return locs; } Poses initializePoses(int n){ Locations locs = initializeLocations(n); //int n = (int) locs.size(); Poses poses(n); for(int i=0; i<n; i++){ Location loc = locs.at(i); Pose pose; pose.x(loc.x()).y(loc.y()).floor(loc.floor()).z(loc.z()); pose.orientation(0.0).velocity(1.0).normalVelocity(1.0); poses[i]=pose; } return poses; } States initializeStates(int n){ Poses poses = initializePoses(n); //int n = (int) poses.size(); States states(n); for(int i=0; i<n; i++){ Pose pose = poses.at(i); State state; state.x(pose.x()).y(pose.y()).floor(pose.floor()).z(pose.z()); state.orientation(0.0).velocity(1.0).normalVelocity(1.0); state.orientationBias(0.0).rssiBias(0.0); states[i]=state; } return states; } }; } #endif /* StatusInitializerStub_hpp */
37.922078
81
0.561986
harsh-agarwal
fd9fa1cb52f4650aa6bc9139634f2be98da4524b
706
cpp
C++
Music/Chou/OnKai/a.cpp
p-adic/cpp
9404a08f26c55a19c53ab0a11edb70f3ed6a8e3c
[ "MIT" ]
2
2020-09-13T07:31:22.000Z
2022-03-26T08:37:32.000Z
Music/Chou/OnKai/a.cpp
p-adic/cpp
9404a08f26c55a19c53ab0a11edb70f3ed6a8e3c
[ "MIT" ]
null
null
null
Music/Chou/OnKai/a.cpp
p-adic/cpp
9404a08f26c55a19c53ab0a11edb70f3ed6a8e3c
[ "MIT" ]
null
null
null
// c:/Users/user/Documents/Programming/Music/Chou/OnKai/a.cpp #include "../../Header.hpp" #include "a_Body.hpp" #include "../../../Error/FaultInCoding/a.hpp" const PitchClass& OnKai::PitchClassTable( const KaiMei& num ) const noexcept { const PitchClass* p_Table[7] = { &m_I , &m_II , &m_III , &m_IV , &m_V , &m_VI , &m_VII }; return *p_Table[ num.Represent() ]; } DEFINITION_OF_GLOBAL_CONST_ON_KAI( ChouOnKai , 0 , 2 , 4 , 5 , 7 , 9 , 11 ); DEFINITION_OF_GLOBAL_CONST_ON_KAI( WaSeiTekiTanOnKai , 0 , 2 , 3 , 5 , 7 , 8 , 11 ); DEFINITION_OF_GLOBAL_CONST_ON_KAI( ShiZenTanOnKai , 0 , 2 , 3 , 5 , 7 , 8 , 10 );
22.774194
85
0.580737
p-adic
fda09761de2f2d8eaf5a45aad594e469001f8e07
2,320
cpp
C++
examples/timer-test/timer-test.cpp
Godzil/32blit-beta
1e829fc70fff8b83775b8f57894819b5c86cde40
[ "MIT" ]
1
2019-11-28T17:11:04.000Z
2019-11-28T17:11:04.000Z
examples/timer-test/timer-test.cpp
Godzil/32blit-beta
1e829fc70fff8b83775b8f57894819b5c86cde40
[ "MIT" ]
null
null
null
examples/timer-test/timer-test.cpp
Godzil/32blit-beta
1e829fc70fff8b83775b8f57894819b5c86cde40
[ "MIT" ]
null
null
null
#include <string> #include <string.h> #include <memory> #include <cstdlib> #include "timer-test.hpp" /* TODO: This example is really dry, how can we make it awesome? Without making it so complicated that it fails to elucidate its point. */ using namespace blit; const uint16_t screen_width = 320; const uint16_t screen_height = 240; blit::timer timer_count; uint32_t count; void timer_count_update(blit::timer &t){ count++; // Instead of using loops we're going to stop the timer in our callback // In this case it will count to ten and then stop. // But you could depend upon any condition to stop the timer. if(count == 10) { t.stop(); } } void init() { blit::set_screen_mode(blit::screen_mode::hires); // Timers must be initialized // In this case we want our timer to call the `timer_count_update` function // very 1000ms, or 1 second. We also want it to loop indefinitely. // We can pass -1 to loop indefinitely, or just nothing at all since -1 // is the default. timer_count.init(timer_count_update, 1000, -1); // Next we probably want to start our timer! timer_count.start(); } int tick_count = 0; void render(uint32_t time_ms) { char text_buffer[60]; fb.pen(rgba(20, 30, 40)); fb.clear(); // Fancy title bar, nothing to see here. fb.pen(rgba(255, 255, 255)); fb.rectangle(rect(0, 0, 320, 14)); fb.pen(rgba(0, 0, 0)); fb.text("Timer Test", &minimal_font[0][0], point(5, 4)); // Since our timer callback is updating our `count` variable // we can just display it on the screen and watch it tick up! fb.pen(rgba(255, 255, 255)); sprintf(text_buffer, "Count: %d", count); fb.text(text_buffer, &minimal_font[0][0], point(120, 100)); // `is_running()` is a handy shorthand for checking the timer state if(timer_count.is_running()) { fb.text("Timer running...", &minimal_font[0][0], point(120, 110)); } else { fb.text("Timer stopped!", &minimal_font[0][0], point(120, 110)); fb.text("Press A to restart.", &minimal_font[0][0], point(120, 120)); } } void update(uint32_t time_ms) { // `is_stopped()` works too! if (blit::buttons & blit::button::A && timer_count.is_stopped()) { count = 0; timer_count.start(); } }
29.74359
78
0.646983
Godzil
fda1d5ce2c84d7bc8d28f9369623e7ed5f1a1fd9
983
cpp
C++
C++/minimum-absolute-sum-difference.cpp
Priyansh2/LeetCode-Solutions
d613da1881ec2416ccbe15f20b8000e36ddf1291
[ "MIT" ]
3,269
2018-10-12T01:29:40.000Z
2022-03-31T17:58:41.000Z
C++/minimum-absolute-sum-difference.cpp
Priyansh2/LeetCode-Solutions
d613da1881ec2416ccbe15f20b8000e36ddf1291
[ "MIT" ]
53
2018-12-16T22:54:20.000Z
2022-02-25T08:31:20.000Z
C++/minimum-absolute-sum-difference.cpp
Priyansh2/LeetCode-Solutions
d613da1881ec2416ccbe15f20b8000e36ddf1291
[ "MIT" ]
1,236
2018-10-12T02:51:40.000Z
2022-03-30T13:30:37.000Z
// Time: O(nlogn) // Space: O(n) class Solution { public: int minAbsoluteSumDiff(vector<int>& nums1, vector<int>& nums2) { static const int MOD = 1e9 + 7; vector<int> sorted_nums1(cbegin(nums1), cend(nums1)); sort(begin(sorted_nums1), end(sorted_nums1)); int result = 0, max_change = 0; for (int i = 0; i < size(nums2); ++i) { int diff = abs(nums1[i] - nums2[i]); result = (result + diff) % MOD; if (diff < max_change) { continue; } const auto cit = lower_bound(cbegin(sorted_nums1), cend(sorted_nums1), nums2[i]); if (cit != cend(sorted_nums1)) { max_change = max(max_change, diff - abs(*cit - nums2[i])); } if (cit != cbegin(sorted_nums1)) { max_change = max(max_change, diff - abs(*prev(cit) - nums2[i])); } } return (result - max_change + MOD) % MOD; } };
33.896552
93
0.513733
Priyansh2
fda2321fad5286503ca80c58a301c01a2e4d797d
2,258
cpp
C++
src/Core/Utils/Attribs.cpp
Yasoo31/Radium-Engine
e22754d0abe192207fd946509cbd63c4f9e52dd4
[ "Apache-2.0" ]
78
2017-12-01T12:23:22.000Z
2022-03-31T05:08:09.000Z
src/Core/Utils/Attribs.cpp
neurodiverseEsoteric/Radium-Engine
ebebc29d889a9d32e0637e425e589e403d8edef8
[ "Apache-2.0" ]
527
2017-09-25T13:05:32.000Z
2022-03-31T18:47:44.000Z
src/Core/Utils/Attribs.cpp
neurodiverseEsoteric/Radium-Engine
ebebc29d889a9d32e0637e425e589e403d8edef8
[ "Apache-2.0" ]
48
2018-01-04T22:08:08.000Z
2022-03-03T08:13:41.000Z
#include <Core/Types.hpp> #include <Core/Utils/Attribs.hpp> #include <Core/Utils/Log.hpp> namespace Ra { namespace Core { namespace Utils { AttribBase::~AttribBase() { notify(); } template <> size_t Attrib<float>::getElementSize() const { return 1; } template <> size_t Attrib<double>::getElementSize() const { return 1; } AttribManager::~AttribManager() { clear(); } void AttribManager::clear() { m_attribs.clear(); m_attribsIndex.clear(); } void AttribManager::copyAllAttributes( const AttribManager& m ) { for ( const auto& attr : m.m_attribs ) { if ( attr == nullptr ) continue; if ( attr->isFloat() ) { auto h = addAttrib<Scalar>( attr->getName() ); getAttrib( h ).setData( static_cast<Attrib<Scalar>*>( attr.get() )->data() ); } else if ( attr->isVector2() ) { auto h = addAttrib<Vector2>( attr->getName() ); getAttrib( h ).setData( static_cast<Attrib<Vector2>*>( attr.get() )->data() ); } else if ( attr->isVector3() ) { auto h = addAttrib<Vector3>( attr->getName() ); getAttrib( h ).setData( static_cast<Attrib<Vector3>*>( attr.get() )->data() ); } else if ( attr->isVector4() ) { auto h = addAttrib<Vector4>( attr->getName() ); getAttrib( h ).setData( static_cast<Attrib<Vector4>*>( attr.get() )->data() ); } else LOG( logWARNING ) << "Warning, copy of mesh attribute " << attr->getName() << " type is not supported (only float, vec2, vec3 nor vec4 are " "supported) [from AttribManager::copyAllAttribute()]"; } } bool AttribManager::hasSameAttribs( const AttribManager& other ) { // one way for ( const auto& attr : m_attribsIndex ) { if ( other.m_attribsIndex.find( attr.first ) == other.m_attribsIndex.cend() ) { return false; } } // the other way for ( const auto& attr : other.m_attribsIndex ) { if ( m_attribsIndex.find( attr.first ) == m_attribsIndex.cend() ) { return false; } } return true; } } // namespace Utils } // namespace Core } // namespace Ra
27.876543
95
0.564659
Yasoo31
fda45ab8946115d46903b347808c6f73083c3ed5
521
cpp
C++
libcxx/test/std/utilities/smartptr/unique.ptr/unique.ptr.create/make_unique.array2.fail.cpp
medismailben/llvm-project
e334a839032fe500c3bba22bf976ab7af13ce1c1
[ "Apache-2.0" ]
2,338
2018-06-19T17:34:51.000Z
2022-03-31T11:00:37.000Z
libcxx/test/std/utilities/smartptr/unique.ptr/unique.ptr.create/make_unique.array2.fail.cpp
medismailben/llvm-project
e334a839032fe500c3bba22bf976ab7af13ce1c1
[ "Apache-2.0" ]
3,740
2019-01-23T15:36:48.000Z
2022-03-31T22:01:13.000Z
libcxx/test/std/utilities/smartptr/unique.ptr/unique.ptr.create/make_unique.array2.fail.cpp
medismailben/llvm-project
e334a839032fe500c3bba22bf976ab7af13ce1c1
[ "Apache-2.0" ]
500
2019-01-23T07:49:22.000Z
2022-03-30T02:59:37.000Z
//===----------------------------------------------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #include <memory> #include <string> #include <cassert> int main(int, char**) { auto up2 = std::make_unique<int[]>(10, 20, 30, 40); return 0; }
27.421053
80
0.474088
medismailben
fda6887ac89caed203cb87e0564c5addc3e98af8
5,654
cpp
C++
dep/include/yse/juce_audio_basics/sources/juce_ChannelRemappingAudioSource.cpp
ChrSacher/MyEngine
8fe71fd9e84b9536148e0d4ebb4e53751ab49ce8
[ "Apache-2.0" ]
8
2016-04-14T17:17:07.000Z
2021-12-06T06:49:28.000Z
dep/include/yse/juce_audio_basics/sources/juce_ChannelRemappingAudioSource.cpp
ChrSacher/MyEngine
8fe71fd9e84b9536148e0d4ebb4e53751ab49ce8
[ "Apache-2.0" ]
null
null
null
dep/include/yse/juce_audio_basics/sources/juce_ChannelRemappingAudioSource.cpp
ChrSacher/MyEngine
8fe71fd9e84b9536148e0d4ebb4e53751ab49ce8
[ "Apache-2.0" ]
2
2019-06-13T10:01:32.000Z
2021-11-19T18:53:52.000Z
/* ============================================================================== This file is part of the JUCE library. Copyright (c) 2015 - ROLI Ltd. Permission is granted to use this software under the terms of either: a) the GPL v2 (or any later version) b) the Affero GPL v3 Details of these licenses can be found at: www.gnu.org/licenses JUCE 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. ------------------------------------------------------------------------------ To release a closed-source product which uses JUCE, commercial licenses are available: visit www.juce.com for more information. ============================================================================== */ ChannelRemappingAudioSource::ChannelRemappingAudioSource (AudioSource* const source_, const bool deleteSourceWhenDeleted) : source (source_, deleteSourceWhenDeleted), requiredNumberOfChannels (2) { remappedInfo.buffer = &buffer; remappedInfo.startSample = 0; } ChannelRemappingAudioSource::~ChannelRemappingAudioSource() {} //============================================================================== void ChannelRemappingAudioSource::setNumberOfChannelsToProduce (const int requiredNumberOfChannels_) { const ScopedLock sl (lock); requiredNumberOfChannels = requiredNumberOfChannels_; } void ChannelRemappingAudioSource::clearAllMappings() { const ScopedLock sl (lock); remappedInputs.clear(); remappedOutputs.clear(); } void ChannelRemappingAudioSource::setInputChannelMapping (const int destIndex, const int sourceIndex) { const ScopedLock sl (lock); while (remappedInputs.size() < destIndex) remappedInputs.add (-1); remappedInputs.set (destIndex, sourceIndex); } void ChannelRemappingAudioSource::setOutputChannelMapping (const int sourceIndex, const int destIndex) { const ScopedLock sl (lock); while (remappedOutputs.size() < sourceIndex) remappedOutputs.add (-1); remappedOutputs.set (sourceIndex, destIndex); } int ChannelRemappingAudioSource::getRemappedInputChannel (const int inputChannelIndex) const { const ScopedLock sl (lock); if (inputChannelIndex >= 0 && inputChannelIndex < remappedInputs.size()) return remappedInputs.getUnchecked (inputChannelIndex); return -1; } int ChannelRemappingAudioSource::getRemappedOutputChannel (const int outputChannelIndex) const { const ScopedLock sl (lock); if (outputChannelIndex >= 0 && outputChannelIndex < remappedOutputs.size()) return remappedOutputs .getUnchecked (outputChannelIndex); return -1; } //============================================================================== void ChannelRemappingAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate) { source->prepareToPlay (samplesPerBlockExpected, sampleRate); } void ChannelRemappingAudioSource::releaseResources() { source->releaseResources(); } void ChannelRemappingAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill) { const ScopedLock sl (lock); buffer.setSize (requiredNumberOfChannels, bufferToFill.numSamples, false, false, true); const int numChans = bufferToFill.buffer->getNumChannels(); for (int i = 0; i < buffer.getNumChannels(); ++i) { const int remappedChan = getRemappedInputChannel (i); if (remappedChan >= 0 && remappedChan < numChans) { buffer.copyFrom (i, 0, *bufferToFill.buffer, remappedChan, bufferToFill.startSample, bufferToFill.numSamples); } else { buffer.clear (i, 0, bufferToFill.numSamples); } } remappedInfo.numSamples = bufferToFill.numSamples; source->getNextAudioBlock (remappedInfo); bufferToFill.clearActiveBufferRegion(); for (int i = 0; i < requiredNumberOfChannels; ++i) { const int remappedChan = getRemappedOutputChannel (i); if (remappedChan >= 0 && remappedChan < numChans) { bufferToFill.buffer->addFrom (remappedChan, bufferToFill.startSample, buffer, i, 0, bufferToFill.numSamples); } } } //============================================================================== XmlElement* ChannelRemappingAudioSource::createXml() const { XmlElement* e = new XmlElement ("MAPPINGS"); String ins, outs; const ScopedLock sl (lock); for (int i = 0; i < remappedInputs.size(); ++i) ins << remappedInputs.getUnchecked(i) << ' '; for (int i = 0; i < remappedOutputs.size(); ++i) outs << remappedOutputs.getUnchecked(i) << ' '; e->setAttribute ("inputs", ins.trimEnd()); e->setAttribute ("outputs", outs.trimEnd()); return e; } void ChannelRemappingAudioSource::restoreFromXml (const XmlElement& e) { if (e.hasTagName ("MAPPINGS")) { const ScopedLock sl (lock); clearAllMappings(); StringArray ins, outs; ins.addTokens (e.getStringAttribute ("inputs"), false); outs.addTokens (e.getStringAttribute ("outputs"), false); for (int i = 0; i < ins.size(); ++i) remappedInputs.add (ins[i].getIntValue()); for (int i = 0; i < outs.size(); ++i) remappedOutputs.add (outs[i].getIntValue()); } }
30.562162
102
0.616732
ChrSacher
fda8bca1f11fd4555be3bb77310f663474672c39
3,155
cc
C++
polardb/src/model/DescribeDatabasesResult.cc
iamzken/aliyun-openapi-cpp-sdk
3c991c9ca949b6003c8f498ce7a672ea88162bf1
[ "Apache-2.0" ]
null
null
null
polardb/src/model/DescribeDatabasesResult.cc
iamzken/aliyun-openapi-cpp-sdk
3c991c9ca949b6003c8f498ce7a672ea88162bf1
[ "Apache-2.0" ]
null
null
null
polardb/src/model/DescribeDatabasesResult.cc
iamzken/aliyun-openapi-cpp-sdk
3c991c9ca949b6003c8f498ce7a672ea88162bf1
[ "Apache-2.0" ]
1
2020-11-27T09:13:12.000Z
2020-11-27T09:13:12.000Z
/* * Copyright 2009-2017 Alibaba Cloud All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <alibabacloud/polardb/model/DescribeDatabasesResult.h> #include <json/json.h> using namespace AlibabaCloud::Polardb; using namespace AlibabaCloud::Polardb::Model; DescribeDatabasesResult::DescribeDatabasesResult() : ServiceResult() {} DescribeDatabasesResult::DescribeDatabasesResult(const std::string &payload) : ServiceResult() { parse(payload); } DescribeDatabasesResult::~DescribeDatabasesResult() {} void DescribeDatabasesResult::parse(const std::string &payload) { Json::Reader reader; Json::Value value; reader.parse(payload, value); setRequestId(value["RequestId"].asString()); auto allDatabasesNode = value["Databases"]["Database"]; for (auto valueDatabasesDatabase : allDatabasesNode) { Database databasesObject; if(!valueDatabasesDatabase["DBName"].isNull()) databasesObject.dBName = valueDatabasesDatabase["DBName"].asString(); if(!valueDatabasesDatabase["DBStatus"].isNull()) databasesObject.dBStatus = valueDatabasesDatabase["DBStatus"].asString(); if(!valueDatabasesDatabase["DBDescription"].isNull()) databasesObject.dBDescription = valueDatabasesDatabase["DBDescription"].asString(); if(!valueDatabasesDatabase["CharacterSetName"].isNull()) databasesObject.characterSetName = valueDatabasesDatabase["CharacterSetName"].asString(); if(!valueDatabasesDatabase["Engine"].isNull()) databasesObject.engine = valueDatabasesDatabase["Engine"].asString(); auto allAccountsNode = valueDatabasesDatabase["Accounts"]["Account"]; for (auto valueDatabasesDatabaseAccountsAccount : allAccountsNode) { Database::Account accountsObject; if(!valueDatabasesDatabaseAccountsAccount["AccountName"].isNull()) accountsObject.accountName = valueDatabasesDatabaseAccountsAccount["AccountName"].asString(); if(!valueDatabasesDatabaseAccountsAccount["AccountStatus"].isNull()) accountsObject.accountStatus = valueDatabasesDatabaseAccountsAccount["AccountStatus"].asString(); if(!valueDatabasesDatabaseAccountsAccount["AccountPrivilege"].isNull()) accountsObject.accountPrivilege = valueDatabasesDatabaseAccountsAccount["AccountPrivilege"].asString(); if(!valueDatabasesDatabaseAccountsAccount["PrivilegeStatus"].isNull()) accountsObject.privilegeStatus = valueDatabasesDatabaseAccountsAccount["PrivilegeStatus"].asString(); databasesObject.accounts.push_back(accountsObject); } databases_.push_back(databasesObject); } } std::vector<DescribeDatabasesResult::Database> DescribeDatabasesResult::getDatabases()const { return databases_; }
39.4375
107
0.784152
iamzken