hexsha
stringlengths
40
40
size
int64
19
11.4M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
3
270
max_stars_repo_name
stringlengths
5
110
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
3
270
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
9
max_issues_count
float64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
3
270
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
listlengths
1
9
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
19
11.4M
avg_line_length
float64
1.93
229k
max_line_length
int64
12
688k
alphanum_fraction
float64
0.07
0.99
matches
listlengths
1
10
67b82c97c60d1ec0e39cd0e476587fce31936f0c
1,817
cpp
C++
Algorithms/greedy/Kruskal.cpp
Divide-et-impera-11/AlgorithmWord
a78bb9272b59df5d16fdc0af565391ef2ac20117
[ "MIT" ]
null
null
null
Algorithms/greedy/Kruskal.cpp
Divide-et-impera-11/AlgorithmWord
a78bb9272b59df5d16fdc0af565391ef2ac20117
[ "MIT" ]
null
null
null
Algorithms/greedy/Kruskal.cpp
Divide-et-impera-11/AlgorithmWord
a78bb9272b59df5d16fdc0af565391ef2ac20117
[ "MIT" ]
null
null
null
#include <iostream> #include <string> #include <vector> #include <algorithm> //---------------------Kruskal--------------------- #define SIZ 4 template<class Type> void Kruskal(Type graph[SIZ][SIZ]) { int set[SIZ]; vector<pair<int, int>> edges; for (uint32_t line(0); line < SIZ; ++line) { set[line] = line; for (uint32_t column(0); column < SIZ; ++column) { if (graph[line][column] && line < column) { edges.push_back(make_pair(line, column)); } } } sort(edges.begin(), edges.end(), [&](pair<int, int> &p0, pair<int, int> &p1) -> bool {return graph[p0.first][p0.second] < graph[p1.first][p1.second];}); uint32_t idx = 0; while (idx < edges.size()) { if (set[edges.at(idx).first] != set[edges.at(idx).second]) { uint32_t set_id = set[edges.at(idx).second]; for (uint32_t offset(0); offset < SIZ; ++offset) { if (set[offset] == set_id) set[offset] = set[edges.at(idx).first]; } } else { edges.erase(edges.begin() + idx); continue; } ++idx; } for (vector<pair<int, int>>::iterator iter = edges.begin(); iter != edges.end(); ++iter) { cout << iter->first << " " << iter->second << endl; } } // Parameter List: //(Type graph[x][y] where x = line and y = column) = graph // Return Value Cases: // void // Function Call Example /*int graph[4][4]{ {0,30,0,5}, {30,0,10,0}, {0,10,0,10}, {5,0,10,0}}; Kruskal(graph); */
33.648148
160
0.443588
[ "vector" ]
67b8efb053564afb1cfe0fd50c76a461f01bf3d0
37,975
cpp
C++
src/game/server/tf/tf_weapon_builder.cpp
cstom4994/SourceEngineRebuild
edfd7f8ce8af13e9d23586318350319a2e193c08
[ "MIT" ]
6
2022-01-23T09:40:33.000Z
2022-03-20T20:53:25.000Z
src/game/server/tf/tf_weapon_builder.cpp
cstom4994/SourceEngineRebuild
edfd7f8ce8af13e9d23586318350319a2e193c08
[ "MIT" ]
null
null
null
src/game/server/tf/tf_weapon_builder.cpp
cstom4994/SourceEngineRebuild
edfd7f8ce8af13e9d23586318350319a2e193c08
[ "MIT" ]
1
2022-02-06T21:05:23.000Z
2022-02-06T21:05:23.000Z
//========= Copyright Valve Corporation, All rights reserved. ============// // // Purpose: The "weapon" used to build objects // // // $Workfile: $ // $Date: $ // $NoKeywords: $ //=============================================================================// #include "cbase.h" #include "tf_player.h" #include "entitylist.h" #include "in_buttons.h" #include "SoundEmitterSystem/isoundemittersystembase.h" #include "engine/IEngineSound.h" #include "tf_obj.h" #include "sendproxy.h" #include "tf_weapon_builder.h" #include "vguiscreen.h" #include "tf_gamerules.h" #include "tf_obj_teleporter.h" #include "tf_obj_sapper.h" extern ISoundEmitterSystemBase *soundemitterbase; extern ConVar tf2_object_hard_limits; extern ConVar tf_fastbuild; EXTERN_SEND_TABLE(DT_BaseCombatWeapon) BEGIN_NETWORK_TABLE_NOBASE( CTFWeaponBuilder, DT_BuilderLocalData ) SendPropInt( SENDINFO( m_iObjectType ), BUILDER_OBJECT_BITS, SPROP_UNSIGNED ), SendPropEHandle( SENDINFO( m_hObjectBeingBuilt ) ), SendPropArray3( SENDINFO_ARRAY3( m_aBuildableObjectTypes ), SendPropBool( SENDINFO_ARRAY( m_aBuildableObjectTypes ) ) ), END_NETWORK_TABLE() IMPLEMENT_SERVERCLASS_ST(CTFWeaponBuilder, DT_TFWeaponBuilder) SendPropInt( SENDINFO( m_iBuildState ), 4, SPROP_UNSIGNED ), SendPropDataTable( "BuilderLocalData", 0, &REFERENCE_SEND_TABLE( DT_BuilderLocalData ), SendProxy_SendLocalWeaponDataTable ), SendPropInt( SENDINFO( m_iObjectMode ) , 4, SPROP_UNSIGNED ), SendPropFloat( SENDINFO( m_flWheatleyTalkingUntil) ), END_SEND_TABLE() LINK_ENTITY_TO_CLASS( tf_weapon_builder, CTFWeaponBuilder ); PRECACHE_WEAPON_REGISTER( tf_weapon_builder ); // IMPLEMENT_SERVERCLASS_ST( CTFWeaponSapper, DT_TFWeaponSapper ) SendPropFloat( SENDINFO( m_flChargeBeginTime ) ), END_SEND_TABLE() LINK_ENTITY_TO_CLASS( tf_weapon_sapper, CTFWeaponSapper ); PRECACHE_WEAPON_REGISTER( tf_weapon_sapper ); //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- CTFWeaponBuilder::CTFWeaponBuilder() { m_iObjectType.Set( BUILDER_INVALID_OBJECT ); m_iObjectMode = 0; m_bAttack3Down = false; //Sapper VO Pack stuff WheatleyReset( true ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- CTFWeaponBuilder::~CTFWeaponBuilder() { StopPlacement(); if (m_pkvWavList) { m_pkvWavList->deleteThis(); } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CTFWeaponBuilder::SetSubType( int iSubType ) { m_iObjectType = iSubType; // m_iViewModelIndex is set by the base Precache(), which didn't know what // type of object we built, so it didn't get the right viewmodel index. // Now that our data is filled in, go and get the right index. const char *pszViewModel = GetViewModel(0); if ( pszViewModel && pszViewModel[0] ) { m_iViewModelIndex = CBaseEntity::PrecacheModel( pszViewModel ); } if ( m_iObjectType == OBJ_ATTACHMENT_SAPPER ) { if ( IsWheatleySapper() ) { if (m_pkvWavList) { m_pkvWavList->deleteThis(); } m_pkvWavList = new KeyValues("sappervo"); } } BaseClass::SetSubType( iSubType ); } void CTFWeaponBuilder::Precache( void ) { BaseClass::Precache(); // Precache all the viewmodels we could possibly be building for ( int iObj=0; iObj < OBJ_LAST; iObj++ ) { const CObjectInfo *pInfo = GetObjectInfo( iObj ); if ( pInfo ) { if ( pInfo->m_pViewModel ) { PrecacheModel( pInfo->m_pViewModel ); } if ( pInfo->m_pPlayerModel ) { PrecacheModel( pInfo->m_pPlayerModel ); } } } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- bool CTFWeaponBuilder::CanDeploy( void ) { CTFPlayer *pPlayer = ToTFPlayer( GetOwner() ); if (!pPlayer) return false; if ( pPlayer->m_Shared.IsCarryingObject() ) return BaseClass::CanDeploy(); if ( pPlayer->CanBuild( m_iObjectType, m_iObjectMode ) != CB_CAN_BUILD ) { return false; } return BaseClass::CanDeploy(); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- bool CTFWeaponBuilder::Deploy( void ) { bool bDeploy = BaseClass::Deploy(); if ( bDeploy ) { SetCurrentState( BS_PLACING ); StartPlacement(); m_flNextPrimaryAttack = gpGlobals->curtime + 0.35f; m_flNextSecondaryAttack = gpGlobals->curtime; // asap CTFPlayer *pPlayer = ToTFPlayer( GetOwner() ); if (!pPlayer) return false; pPlayer->SetNextAttack( gpGlobals->curtime ); m_iWorldModelIndex = modelinfo->GetModelIndex( GetWorldModel() ); m_flNextDenySound = 0; // Set off the hint here, because we don't know until now if our building // is rotate-able or not. if ( m_hObjectBeingBuilt && !m_hObjectBeingBuilt->MustBeBuiltOnAttachmentPoint() ) { // set the alt-fire hint so it gets removed when we holster m_iAltFireHint = HINT_ALTFIRE_ROTATE_BUILDING; pPlayer->StartHintTimer( m_iAltFireHint ); } pPlayer->PlayWearableAnimsForPlaybackEvent( WAP_START_BUILDING ); } return bDeploy; } Activity CTFWeaponBuilder::GetDrawActivity( void ) { // sapper used to call different draw animations , one when invis and one when not. // now you can go invis *while* deploying, so let's always use the one-handed deploy. if ( GetType() == OBJ_ATTACHMENT_SAPPER ) { return ACT_VM_DRAW_DEPLOYED; } return BaseClass::GetDrawActivity(); } //----------------------------------------------------------------------------- // Purpose: Stop placement when holstering //----------------------------------------------------------------------------- bool CTFWeaponBuilder::Holster( CBaseCombatWeapon *pSwitchingTo ) { CTFPlayer *pOwner = ToTFPlayer( GetOwner() ); if ( !pOwner ) return false; if ( pOwner->m_Shared.IsCarryingObject() ) return false; if ( m_iObjectType == OBJ_ATTACHMENT_SAPPER ) { if( IsWheatleySapper() ) { pOwner->ClearSappingTracking(); if ( pOwner->m_Shared.GetState() == TF_STATE_DYING) { if ( RandomInt( 0, 4) == 0 ) { WheatleyEmitSound( "PSap.DeathLong", true ); } else { WheatleyEmitSound( "PSap.Death", true ); } } else { float flSoundDuration; if ( gpGlobals->curtime - m_flWheatleyLastDeploy < 1.5 && gpGlobals->curtime - m_flWheatleyLastDeploy > -1.0 ) { flSoundDuration = WheatleyEmitSound( "PSap.HolsterFast"); } else { flSoundDuration = WheatleyEmitSound( "PSap.Holster"); } m_flWheatleyLastHolster = gpGlobals->curtime + flSoundDuration; } } } m_flNextVoicePakIdleStartTime = -1.0f; if ( m_iBuildState == BS_PLACING || m_iBuildState == BS_PLACING_INVALID ) { SetCurrentState( BS_IDLE ); } StopPlacement(); pOwner->PlayWearableAnimsForPlaybackEvent( WAP_STOP_BUILDING ); return BaseClass::Holster(pSwitchingTo); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CTFWeaponBuilder::ItemPostFrame( void ) { CTFPlayer *pOwner = ToTFPlayer( GetOwner() ); if ( !pOwner ) return; // If we're building, and our team has lost, stop placing the object if ( m_hObjectBeingBuilt.Get() && TFGameRules()->State_Get() == GR_STATE_TEAM_WIN && pOwner->GetTeamNumber() != TFGameRules()->GetWinningTeam() ) { StopPlacement(); return; } // Check that I still have enough resources to build this item if ( pOwner->CanBuild( m_iObjectType, m_iObjectMode ) != CB_CAN_BUILD ) { SwitchOwnersWeaponToLast(); } if ( ( pOwner->m_nButtons & IN_ATTACK ) && ( m_flNextPrimaryAttack <= gpGlobals->curtime ) ) { PrimaryAttack(); } if ( pOwner->m_nButtons & IN_ATTACK2 ) { if ( m_flNextSecondaryAttack <= gpGlobals->curtime ) { SecondaryAttack(); } } else { m_bInAttack2 = false; } // Attrib int iMarkForDeathOnPickup = 0; if ( pOwner->m_Shared.IsCarryingObject () ) { CALL_ATTRIB_HOOK_INT_ON_OTHER( pOwner, iMarkForDeathOnPickup, mark_for_death_on_building_pickup ); if ( iMarkForDeathOnPickup ) { pOwner->m_Shared.AddCond( TF_COND_MARKEDFORDEATH_SILENT, 3.f ); } } WeaponIdle(); } //----------------------------------------------------------------------------- // Purpose: Start placing or building the currently selected object //----------------------------------------------------------------------------- void CTFWeaponBuilder::PrimaryAttack( void ) { CTFPlayer *pOwner = ToTFPlayer( GetOwner() ); if ( !pOwner ) return; if ( !CanAttack() ) return; // Necessary so that we get the latest building position for the test, otherwise // we are one frame behind. UpdatePlacementState(); // What state should we move to? switch( m_iBuildState ) { case BS_IDLE: { // Idle state starts selection SetCurrentState( BS_SELECTING ); } break; case BS_SELECTING: { // Do nothing, client handles selection return; } break; case BS_PLACING: { if ( m_hObjectBeingBuilt ) { int iFlags = m_hObjectBeingBuilt->GetObjectFlags(); // Tricky, because this can re-calc the object position and change whether its a valid // pos or not. Best not to do this only in debug, but we can be pretty sure that this // will give the same result as was calculated in UpdatePlacementState() above. Assert( IsValidPlacement() ); // If we're placing an attachment, like a sapper, play a placement animation on the owner if ( m_hObjectBeingBuilt->MustBeBuiltOnAttachmentPoint() ) { pOwner->DoAnimationEvent( PLAYERANIMEVENT_ATTACK_GRENADE ); } CBaseEntity *pBuiltOnObject = m_hObjectBeingBuilt->GetBuiltOnObject(); if ( pBuiltOnObject && m_iObjectType == OBJ_ATTACHMENT_SAPPER ) { m_vLastKnownSapPos = pBuiltOnObject->GetAbsOrigin(); m_hLastSappedBuilding = pBuiltOnObject; } StartBuilding(); if ( m_iObjectType == OBJ_ATTACHMENT_SAPPER ) { // tell players a sapper was just placed (so bots can react) CUtlVector< CTFPlayer * > playerVector; CollectPlayers( &playerVector, TEAM_ANY, COLLECT_ONLY_LIVING_PLAYERS ); for( int i=0; i<playerVector.Count(); ++i ) playerVector[i]->OnSapperPlaced( pBuiltOnObject ); // if we just placed a sapper on a teleporter...try to sap the match, too? if ( pBuiltOnObject ) { CObjectTeleporter *pTeleporter = dynamic_cast<CObjectTeleporter*>( pBuiltOnObject ); if ( pTeleporter && pTeleporter->GetMatchingTeleporter() && !pTeleporter->GetMatchingTeleporter()->HasSapper() ) { // Start placing another SetCurrentState( BS_PLACING ); StartPlacement(); if ( m_hObjectBeingBuilt.Get() ) { m_hObjectBeingBuilt->UpdateAttachmentPlacement( pTeleporter->GetMatchingTeleporter() ); StartBuilding(); } } } } // Should we switch away? if ( iFlags & OF_ALLOW_REPEAT_PLACEMENT ) { // Start placing another SetCurrentState( BS_PLACING ); StartPlacement(); } else { SwitchOwnersWeaponToLast(); } } } break; case BS_PLACING_INVALID: { if ( m_flNextDenySound < gpGlobals->curtime ) { CSingleUserRecipientFilter filter( pOwner ); EmitSound( filter, entindex(), "Player.DenyWeaponSelection" ); m_flNextDenySound = gpGlobals->curtime + 0.5; } } break; } m_flNextPrimaryAttack = gpGlobals->curtime + 0.2f; } void CTFWeaponBuilder::SecondaryAttack( void ) { if ( m_bInAttack2 ) return; // require a re-press m_bInAttack2 = true; CTFPlayer *pOwner = ToTFPlayer( GetOwner() ); if ( !pOwner ) return; UpdatePlacementState(); if ( !pOwner->IsPlayerClass( TF_CLASS_ENGINEER ) && pOwner->DoClassSpecialSkill() ) { // Spies do the special skill first. } else if ( m_iBuildState == BS_PLACING || m_iBuildState == BS_PLACING_INVALID ) { if ( m_hObjectBeingBuilt ) { pOwner->StopHintTimer( HINT_ALTFIRE_ROTATE_BUILDING ); m_hObjectBeingBuilt->RotateBuildAngles(); } } else if ( pOwner->DoClassSpecialSkill() ) { // Engineers do the special skill last. } m_flNextSecondaryAttack = gpGlobals->curtime + 0.2f; } //----------------------------------------------------------------------------- // Purpose: Set the builder to the specified state //----------------------------------------------------------------------------- void CTFWeaponBuilder::SetCurrentState( int iState ) { m_iBuildState = iState; } //----------------------------------------------------------------------------- // Purpose: Set the owner's weapon and last weapon appropriately when we need to // switch away from the builder weapon. //----------------------------------------------------------------------------- void CTFWeaponBuilder::SwitchOwnersWeaponToLast() { CTFPlayer *pOwner = ToTFPlayer( GetOwner() ); if ( !pOwner ) return; // for engineer, switch to wrench and set last weapon appropriately if ( pOwner->IsPlayerClass( TF_CLASS_ENGINEER ) ) { // Switch to wrench if possible. if not, then best weapon CBaseCombatWeapon *pWpn = pOwner->Weapon_GetSlot( 2 ); // Don't store last weapon when we autoswitch off builder CBaseCombatWeapon *pLastWpn = pOwner->GetLastWeapon(); if ( pWpn ) { pOwner->Weapon_Switch( pWpn ); } else { pOwner->SwitchToNextBestWeapon( NULL ); } if ( pWpn == pLastWpn ) { // We had the wrench out before we started building. Go ahead and set out last // weapon to our primary weapon. pWpn = pOwner->Weapon_GetSlot( 0 ); pOwner->Weapon_SetLast( pWpn ); } else { pOwner->Weapon_SetLast( pLastWpn ); } } else { // for all other classes, just switch to last weapon used pOwner->Weapon_Switch( pOwner->GetLastWeapon() ); } } //----------------------------------------------------------------------------- // Purpose: updates the building postion and checks the new postion //----------------------------------------------------------------------------- void CTFWeaponBuilder::UpdatePlacementState( void ) { // This updates the building position bool bValidPos = IsValidPlacement(); // If we're in placement mode, update the placement model switch( m_iBuildState ) { case BS_PLACING: case BS_PLACING_INVALID: { if ( bValidPos ) { SetCurrentState( BS_PLACING ); } else { SetCurrentState( BS_PLACING_INVALID ); } } break; default: break; } } //----------------------------------------------------------------------------- // Purpose: Idle updates the position of the build placement model //----------------------------------------------------------------------------- /*#define SAPPER_VOPAK_DEFAULT_WAIT 0.0f*/ void CTFWeaponBuilder::WeaponIdle( void ) { CTFPlayer *pOwner = ToTFPlayer( GetOwner() ); if ( !pOwner ) return; WheatleySapperIdle( pOwner ); if ( HasWeaponIdleTimeElapsed() ) { SendWeaponAnim( ACT_VM_IDLE ); } } //----------------------------------------------------------------------------- // Purpose: Special Item Idle //----------------------------------------------------------------------------- bool CTFWeaponBuilder::IsWheatleySapper( void ) { float flVoicePak = 0.0; CALL_ATTRIB_HOOK_FLOAT( flVoicePak, sapper_voice_pak ); return (flVoicePak == 1.0); } //----------------------------------------------------------------------------- // Purpose: Special Item Reset //----------------------------------------------------------------------------- void CTFWeaponBuilder::WheatleyReset( bool bResetIntro ) { if ( IsWheatleySapper() ) { WheatleyEmitSound( "PSap.null" ); } if ( bResetIntro ) { m_bWheatleyIntroPlayed = false; } m_flNextVoicePakIdleStartTime = -1.0f; SetWheatleyState( TF_PSAPSTATE_IDLE ); m_flWheatleyTalkingUntil = 0.00; m_flWheatleyLastDamage = 0.00; m_iWheatleyVOSequenceOffset = 0; m_flWheatleyLastDeploy = 0.00; m_flWheatleyLastHolster = 0.00; } bool CTFWeaponBuilder::IsWheatleyTalking( void ) { return gpGlobals->curtime <= m_flWheatleyTalkingUntil; } float CTFWeaponBuilder::WheatleyEmitSound( const char *snd, bool bEmitToAll /*= false*/, bool bNoRepeats /*= false */ ) { CTFPlayer *pOwner = ToTFPlayer( GetOwner() ); CSoundParameters params; if ( !soundemitterbase->GetParametersForSound( snd, params, GENDER_NONE ) ) { return 0.00; } //Should we check to see if it's already been played? if ( bNoRepeats && m_pkvWavList ) { if ( m_pkvWavList->GetInt( params.soundname , 0 ) ) { return 0; } else { m_pkvWavList->SetInt( params.soundname , 1); } } //Look for special cases that require us to pick the next lines from a sequential list if ( Q_strcmp( params.soundname, "vo/items/wheatley_sapper/wheatley_sapper_idle38.mp3") == NULL ) { SetWheatleyState( TF_PSAPSTATE_SPECIALIDLE_HARMLESS ); m_iWheatleyVOSequenceOffset = 0; } else if ( Q_strcmp( params.soundname, "vo/items/wheatley_sapper/wheatley_sapper_idle41.mp3") == NULL ) { SetWheatleyState( TF_PSAPSTATE_SPECIALIDLE_HACK ); m_iWheatleyVOSequenceOffset = 0; } else if ( Q_strcmp( params.soundname, "vo/items/wheatley_sapper/wheatley_sapper_idle35.mp3") == NULL ) { SetWheatleyState( TF_PSAPSTATE_SPECIALIDLE_KNIFE ); m_iWheatleyVOSequenceOffset = 0; } //Play the sound // When playing a sound to all players, do it at the last known sapper location // This is not played on the object itself (building or sapper) cause it may not exist in the case of death and follow up audio // Also having it played on this entity itself prevents multiple VO playing in the case of mass sapping if ( bEmitToAll ) { //int entIndex = 0; CBroadcastNonOwnerRecipientFilter filter( pOwner ); EmitSound( filter, entindex(), snd, &m_vLastKnownSapPos ); } // GetSoundDuration is not supported on Linux or for MP3s. So lets just put in a good number //float flSoundDuration = enginesound->GetSoundDuration( params.soundname ); float flSoundDuration = 3.0f; CSingleUserRecipientFilter filter( pOwner ); EmitSound( filter, entindex(), params ); m_flWheatleyTalkingUntil = gpGlobals->curtime + flSoundDuration; return flSoundDuration; } //----------------------------------------------------------------------------- // Purpose: Set Wheatley Sapper State //----------------------------------------------------------------------------- void CTFWeaponBuilder::SetWheatleyState( int iNewState ) { m_iSapState = iNewState; } int CTFWeaponBuilder::GetWheatleyIdleWait() { return RandomInt( WHEATLEY_IDLE_WAIT_SECS_MIN, WHEATLEY_IDLE_WAIT_SECS_MAX ); } //----------------------------------------------------------------------------- // Purpose: Set Wheatley Sapper State //----------------------------------------------------------------------------- void CTFWeaponBuilder::WheatleyDamage( void ) { if ( (gpGlobals->curtime - m_flWheatleyLastDamage) > 10.0) { if ( RandomInt(0,2) == 0 ) { CTFPlayer *pOwner = ToTFPlayer( GetOwner() ); if (pOwner) { pOwner->ClearSappingEvent(); } SetWheatleyState( TF_PSAPSTATE_IDLE ); m_flWheatleyLastDamage = gpGlobals->curtime; WheatleyEmitSound( "PSap.Damage" ); } } } //----------------------------------------------------------------------------- // Purpose: Special Item Idle //----------------------------------------------------------------------------- void CTFWeaponBuilder::WheatleySapperIdle( CTFPlayer *pOwner ) { if ( pOwner && m_iObjectType == OBJ_ATTACHMENT_SAPPER && IsWheatleySapper()) { //Is Wheatley coming out of the player's pocket? if( m_flNextVoicePakIdleStartTime < 0.0f ) { pOwner->ClearSappingTracking(); float flSoundDuration; if ( gpGlobals->curtime - m_flWheatleyLastHolster < 2.0 && gpGlobals->curtime - m_flWheatleyLastHolster >= -1.00 ) { flSoundDuration = WheatleyEmitSound( "Psap.DeployAgain" ); } else { flSoundDuration = WheatleyEmitSound( (m_bWheatleyIntroPlayed) ? "Psap.Deploy" : "Psap.DeployIntro" ); } m_flWheatleyLastDeploy = gpGlobals->curtime + flSoundDuration; if ( (!m_bWheatleyIntroPlayed) && (RandomInt(0,2) == 0) ) { SetWheatleyState( TF_PSAPSTATE_INTRO ); m_bWheatleyIntroPlayed = true; m_iWheatleyVOSequenceOffset = 0; m_flNextVoicePakIdleStartTime = gpGlobals->curtime + flSoundDuration + 3.0; } else { m_bWheatleyIntroPlayed = true; SetWheatleyState( TF_PSAPSTATE_IDLE ); m_flNextVoicePakIdleStartTime = gpGlobals->curtime + flSoundDuration + GetWheatleyIdleWait(); } } //Is there a sapper event? (sapper placed / sapper finished) else if( pOwner->GetSappingEvent() != TF_SAPEVENT_NONE) { char *pVoicePakString = NULL; switch ( pOwner->GetSappingEvent() ) { case TF_SAPEVENT_PLACED: if (RandomInt(0,1) == 0) { if ( RandomInt(0,3) == 0 ) { pVoicePakString = (char*)"PSap.AttachedPW"; SetWheatleyState( TF_PSAPSTATE_WAITINGHACK ); } else { pVoicePakString = (char*)"PSap.Attached"; SetWheatleyState( TF_PSAPSTATE_WAITINGHACKPW ); } m_flNextVoicePakIdleStartTime = gpGlobals->curtime + 0.2; } else { pVoicePakString = (char*)"PSap.Hacking"; SetWheatleyState( TF_PSAPSTATE_IDLE ); m_flNextVoicePakIdleStartTime = gpGlobals->curtime + GetWheatleyIdleWait(); } break; case TF_SAPEVENT_DONE: if ( IsWheatleyTalking() ) { if ( m_hLastSappedBuilding && m_hLastSappedBuilding.Get() ) { //Building Alive, Sapper died pVoicePakString = (char*)"PSap.Death"; } else { pVoicePakString = (char*)"PSap.HackedLoud"; } if ( RandomInt( 0, 3 ) == 0 ) { SetWheatleyState( TF_PSAPSTATE_WAITINGFOLLOWUP); m_flNextVoicePakIdleStartTime = gpGlobals->curtime + 1.3; } else { m_flNextVoicePakIdleStartTime = gpGlobals->curtime + GetWheatleyIdleWait(); } } else { SetWheatleyState( TF_PSAPSTATE_WAITINGHACKED ); m_flNextVoicePakIdleStartTime = gpGlobals->curtime + 0.5; } break; default: break; } pOwner->ClearSappingEvent(); if ( pVoicePakString ) { float flSoundDuration = WheatleyEmitSound( pVoicePakString, true ); m_flNextVoicePakIdleStartTime += flSoundDuration; } } //Are we in the intro sequence? else if ( m_iSapState == TF_PSAPSTATE_INTRO && gpGlobals->curtime > m_flNextVoicePakIdleStartTime ) { if ( !IsWheatleyTalking() ) { char szVoicePakString[128]; szVoicePakString[0] = '\0'; if ( m_iWheatleyVOSequenceOffset >= 0 && m_iWheatleyVOSequenceOffset <=3 ) { V_sprintf_safe( szVoicePakString, "PSap.IdleIntro0%i", ++m_iWheatleyVOSequenceOffset); float flSoundDuration = WheatleyEmitSound( szVoicePakString ); if ( m_iWheatleyVOSequenceOffset == 4 ) { m_flNextVoicePakIdleStartTime = gpGlobals->curtime + GetWheatleyIdleWait() + flSoundDuration; } else { m_flNextVoicePakIdleStartTime = gpGlobals->curtime + 1.0 + flSoundDuration; } } else { SetWheatleyState( TF_PSAPSTATE_IDLE ); m_iWheatleyVOSequenceOffset = 0; } } } //Does a generic timed event need to be serviced? else if( gpGlobals->curtime > m_flNextVoicePakIdleStartTime ) { bool bNoRepeats = false; bool bEmitAll = false; char *pVoicePakString = NULL; //Sapped! vo if ( m_iSapState == TF_PSAPSTATE_WAITINGHACKED ) { bEmitAll = true; SetWheatleyState( TF_PSAPSTATE_IDLE ); if ( IsWheatleyTalking() ) { pVoicePakString = (char*)"PSap.HackedLoud"; } else { pVoicePakString = (char*)"PSap.Hacked"; } if ( RandomInt( 0, 3 ) == 0 ) { SetWheatleyState( TF_PSAPSTATE_WAITINGFOLLOWUP); m_flNextVoicePakIdleStartTime = gpGlobals->curtime + 1.3; } else { SetWheatleyState( TF_PSAPSTATE_IDLE ); m_flNextVoicePakIdleStartTime = gpGlobals->curtime + GetWheatleyIdleWait(); } } //Waiting to start the password guessing vo else if ( m_iSapState == TF_PSAPSTATE_WAITINGHACKPW ) { bEmitAll = true; SetWheatleyState( TF_PSAPSTATE_IDLE ); pVoicePakString = (char*)"PSap.HackingPW"; m_flNextVoicePakIdleStartTime = gpGlobals->curtime + GetWheatleyIdleWait(); } //Waiting to start regular hacking vo else if ( m_iSapState == TF_PSAPSTATE_WAITINGHACK ) { bEmitAll = true; SetWheatleyState( TF_PSAPSTATE_IDLE ); if ( RandomInt( 0, 2 ) == 0 ) { pVoicePakString = (char*)"PSap.HackingShort"; } else { pVoicePakString = (char*)"PSap.Hacking"; } m_flNextVoicePakIdleStartTime = gpGlobals->curtime + GetWheatleyIdleWait(); } //Waiting to start successful hack followup vo else if ( m_iSapState == TF_PSAPSTATE_WAITINGFOLLOWUP ) { bEmitAll = true; SetWheatleyState( TF_PSAPSTATE_IDLE ); pVoicePakString = (char*)"PSap.HackedFollowup"; m_flNextVoicePakIdleStartTime = gpGlobals->curtime + GetWheatleyIdleWait(); } //If Wheatley's talking, skip & check again later else if ( IsWheatleyTalking() ) { pVoicePakString = NULL; m_flNextVoicePakIdleStartTime = gpGlobals->curtime + 5.0; } //Are we in the SPECIAL IDLE SEQUENCE "HACK"? else if ( m_iSapState == TF_PSAPSTATE_SPECIALIDLE_HACK ) { switch ( m_iWheatleyVOSequenceOffset ) { case 0: pVoicePakString = (char*)"PSap.IdleHack02"; m_iWheatleyVOSequenceOffset++; break; default: SetWheatleyState( TF_PSAPSTATE_IDLE ); m_iWheatleyVOSequenceOffset = 0; break; } m_flNextVoicePakIdleStartTime = gpGlobals->curtime + GetWheatleyIdleWait(); } //Are we in the SPECIAL IDLE SEQUENCE "KNIFE"? else if ( m_iSapState == TF_PSAPSTATE_SPECIALIDLE_KNIFE ) { switch ( m_iWheatleyVOSequenceOffset ) { case 0: pVoicePakString = "PSap.IdleKnife02"; m_iWheatleyVOSequenceOffset++; m_flNextVoicePakIdleStartTime = gpGlobals->curtime + 0.3; break; case 1: pVoicePakString = "PSap.IdleKnife03"; m_iWheatleyVOSequenceOffset++; m_flNextVoicePakIdleStartTime = gpGlobals->curtime + GetWheatleyIdleWait(); break; default: SetWheatleyState( TF_PSAPSTATE_IDLE ); m_iWheatleyVOSequenceOffset = 0; m_flNextVoicePakIdleStartTime = gpGlobals->curtime + GetWheatleyIdleWait(); break; } } //Are we in the SPECIAL IDLE SEQUENCE "HARMLESS"? else if ( m_iSapState == TF_PSAPSTATE_SPECIALIDLE_HARMLESS ) { switch ( m_iWheatleyVOSequenceOffset ) { case 0: pVoicePakString = "PSap.IdleHarmless02"; m_iWheatleyVOSequenceOffset++; m_flNextVoicePakIdleStartTime = gpGlobals->curtime + GetWheatleyIdleWait(); break; default: SetWheatleyState( TF_PSAPSTATE_IDLE ); m_iWheatleyVOSequenceOffset = 0; m_flNextVoicePakIdleStartTime = gpGlobals->curtime + GetWheatleyIdleWait(); break; } } //Is the player stealthed? else if ( pOwner->m_Shared.IsStealthed() ) { if ( RandomInt(0,1) == 0 ) { pVoicePakString = "PSap.Sneak"; } m_flNextVoicePakIdleStartTime = gpGlobals->curtime + GetWheatleyIdleWait(); } else if ( m_iSapState == TF_PSAPSTATE_IDLE ) { pVoicePakString = "PSap.Idle"; bNoRepeats = true; m_flNextVoicePakIdleStartTime = gpGlobals->curtime + GetWheatleyIdleWait(); } else { pVoicePakString = NULL; } if (!pVoicePakString) { m_flNextVoicePakIdleStartTime = gpGlobals->curtime + GetWheatleyIdleWait(); return; } float flSoundDuration = WheatleyEmitSound( pVoicePakString, bEmitAll, bNoRepeats ); m_flNextVoicePakIdleStartTime += flSoundDuration; } } } //----------------------------------------------------------------------------- // Purpose: Start placing the object //----------------------------------------------------------------------------- void CTFWeaponBuilder::StartPlacement( void ) { StopPlacement(); CTFPlayer *pTFPlayer = ToTFPlayer( GetOwner() ); if ( !pTFPlayer ) return; if ( pTFPlayer->m_Shared.IsCarryingObject() ) { m_hObjectBeingBuilt = pTFPlayer->m_Shared.GetCarriedObject(); m_hObjectBeingBuilt->StopFollowingEntity(); } else { m_hObjectBeingBuilt = (CBaseObject*)CreateEntityByName( GetObjectInfo( m_iObjectType )->m_pClassName ); } if ( m_hObjectBeingBuilt ) { // Set the builder before Spawn() so attributes can hook correctly m_hObjectBeingBuilt->SetBuilder( pTFPlayer ); bool bIsCarried = m_hObjectBeingBuilt->IsCarried(); // split this off from the block at the bottom because we need to know what type of building // this is before we spawn so things like the teleporters have the correct placement models // but we need to set the starting construction health after we've called spawn if ( !bIsCarried ) { m_hObjectBeingBuilt->SetObjectMode( m_iObjectMode ); } m_hObjectBeingBuilt->Spawn(); m_hObjectBeingBuilt->StartPlacement( pTFPlayer ); if ( !bIsCarried ) { m_hObjectBeingBuilt->m_iHealth = OBJECT_CONSTRUCTION_STARTINGHEALTH; } } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CTFWeaponBuilder::StopPlacement( void ) { if ( m_hObjectBeingBuilt ) { if ( m_hObjectBeingBuilt->IsCarried() ) { m_hObjectBeingBuilt->MakeCarriedObject( ToTFPlayer( GetOwner() ) ); } else { m_hObjectBeingBuilt->StopPlacement(); } m_hObjectBeingBuilt = NULL; } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CTFWeaponBuilder::WeaponReset( void ) { //Check to see if the active weapon is the wheatley sapper, and, if so, reset him if ( m_iObjectType == OBJ_ATTACHMENT_SAPPER ) { if ( IsWheatleySapper() ) { CTFPlayer *pPlayer = ToTFPlayer( GetOwner() ); if ( pPlayer ) { pPlayer->ClearSappingTracking(); } WheatleyReset(); } } BaseClass::WeaponReset(); StopPlacement(); } //----------------------------------------------------------------------------- // Purpose: Move the placement model to the current position. Return false if it's an invalid position //----------------------------------------------------------------------------- bool CTFWeaponBuilder::IsValidPlacement( void ) { if ( !m_hObjectBeingBuilt ) return false; CBaseObject *pObj = m_hObjectBeingBuilt.Get(); pObj->UpdatePlacement(); return m_hObjectBeingBuilt->IsValidPlacement(); } //----------------------------------------------------------------------------- // Purpose: Player holding this weapon has started building something // Assumes we are in a valid build position //----------------------------------------------------------------------------- void CTFWeaponBuilder::StartBuilding( void ) { CBaseObject *pObj = m_hObjectBeingBuilt.Get(); Assert( pObj ); pObj->StartBuilding( GetOwner() ); m_hObjectBeingBuilt = NULL; CTFPlayer *pOwner = ToTFPlayer( GetOwner() ); if ( pOwner ) { pOwner->RemoveInvisibility(); pOwner->m_Shared.SetCarriedObject( NULL ); if ( TFGameRules() && TFGameRules()->GameModeUsesUpgrades() ) { if ( pObj->ObjectType() == OBJ_ATTACHMENT_SAPPER ) { // Let human players place player-targeted sappers in modes that allow upgrades if ( !pOwner->IsBot() && pObj->GetBuiltOnObject() && pObj->GetBuiltOnObject()->IsPlayer() ) { int iRoboSapper = 0; CALL_ATTRIB_HOOK_INT_ON_OTHER( pOwner, iRoboSapper, robo_sapper ); int nMode = iRoboSapper ? MODE_SAPPER_ANTI_ROBOT_RADIUS : MODE_SAPPER_ANTI_ROBOT; pObj->SetObjectMode( nMode ); pOwner->RemoveAmmo( 1, TF_AMMO_GRENADES2 ); StartEffectBarRegen(); } } #ifdef STAGING_ONLY // Traps use TF_AMMO_GRENADES1 else if ( pObj->GetType() == OBJ_SPY_TRAP ) { pOwner->RemoveAmmo( 1, TF_AMMO_GRENADES1 ); } #endif // STAGING_ONLY } } } //----------------------------------------------------------------------------- // Purpose: Return true if this weapon has some ammo //----------------------------------------------------------------------------- bool CTFWeaponBuilder::HasAmmo( void ) { CTFPlayer *pOwner = ToTFPlayer( GetOwner() ); if ( !pOwner ) return false; int iCost = pOwner->m_Shared.CalculateObjectCost( pOwner, m_iObjectType ); return ( pOwner->GetBuildResources() >= iCost ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- int CTFWeaponBuilder::GetSlot( void ) const { return GetObjectInfo( m_iObjectType )->m_SelectionSlot; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- int CTFWeaponBuilder::GetPosition( void ) const { return GetObjectInfo( m_iObjectType )->m_SelectionPosition; } //----------------------------------------------------------------------------- // Purpose: // Output : char const //----------------------------------------------------------------------------- const char *CTFWeaponBuilder::GetPrintName( void ) const { return GetObjectInfo( m_iObjectType )->m_pStatusName; } // ----------------------------------------------------------------------------- // Purpose: // ----------------------------------------------------------------------------- bool CTFWeaponBuilder::CanBuildObjectType( int iObjectType ) { if ( iObjectType < 0 || iObjectType >= OBJ_LAST ) return false; return m_aBuildableObjectTypes.Get( iObjectType ); } // ----------------------------------------------------------------------------- // Purpose: // ----------------------------------------------------------------------------- void CTFWeaponBuilder::SetObjectTypeAsBuildable( int iObjectType ) { if ( iObjectType < 0 || iObjectType >= OBJ_LAST ) return; m_aBuildableObjectTypes.Set( iObjectType, true ); SetSubType( iObjectType ); } // ----------------------------------------------------------------------------- // Purpose: // ----------------------------------------------------------------------------- Activity CTFWeaponBuilder::TranslateViewmodelHandActivity( Activity actBase ) { if ( GetObjectInfo( m_iObjectType )->m_bUseItemInfo ) { return BaseClass::TranslateViewmodelHandActivity( actBase ); } else { return actBase; } } // ----------------------------------------------------------------------------- // Purpose: // ----------------------------------------------------------------------------- const char *CTFWeaponBuilder::GetViewModel( int iViewModel ) const { if ( m_iObjectType != BUILDER_INVALID_OBJECT ) { if ( GetObjectInfo( m_iObjectType )->m_bUseItemInfo ) return BaseClass::GetViewModel(); return GetObjectInfo( m_iObjectType )->m_pViewModel; } return BaseClass::GetViewModel(); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- const char *CTFWeaponBuilder::GetWorldModel( void ) const { if ( m_iObjectType != BUILDER_INVALID_OBJECT ) { return GetObjectInfo( m_iObjectType )->m_pPlayerModel; } return BaseClass::GetWorldModel(); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- bool CTFWeaponBuilder::AllowsAutoSwitchTo( void ) const { // ask the object we're building return GetObjectInfo( m_iObjectType )->m_bAutoSwitchTo; } // **************************************************************************** // SAPPER // **************************************************************************** CTFWeaponSapper::CTFWeaponSapper() { m_flChargeBeginTime = 0; m_bAttackDown = false; } //----------------------------------------------------------------------------- void CTFWeaponSapper::ItemPostFrame( void ) { #ifdef STAGING_ONLY CTFPlayer *pPlayer = ToTFPlayer( GetPlayerOwner() ); if ( pPlayer ) { float flSapperDeployTime = 0; CALL_ATTRIB_HOOK_FLOAT( flSapperDeployTime, sapper_deploy_time ); if ( flSapperDeployTime ) { //IsValidPlacement if ( !( pPlayer->m_nButtons & IN_ATTACK ) || !IsValidPlacement() ) { m_bAttackDown = false; m_flChargeBeginTime = 0; } else if ( m_bAttackDown == false && ( pPlayer->m_nButtons & IN_ATTACK ) ) { m_bAttackDown = true; m_flChargeBeginTime = gpGlobals->curtime; } if ( ( m_bAttackDown == true && m_flChargeBeginTime + flSapperDeployTime < gpGlobals->curtime ) || !( pPlayer->m_nButtons & IN_ATTACK ) ) { BaseClass::ItemPostFrame(); } return; } } #endif // STAGING_ONLY BaseClass::ItemPostFrame(); } //----------------------------------------------------------------------------- const char *CTFWeaponSapper::GetViewModel( int iViewModel ) const { // Skip over Builder's version return CTFWeaponBase::GetViewModel(); } //----------------------------------------------------------------------------- const char *CTFWeaponSapper::GetWorldModel( void ) const { // Skip over Builder's version return CTFWeaponBase::GetWorldModel(); } //----------------------------------------------------------------------------- Activity CTFWeaponSapper::TranslateViewmodelHandActivity( Activity actBase ) { return BaseClass::TranslateViewmodelHandActivity( actBase ); // Skip over Builder's version //return CTFWeaponBase::TranslateViewmodelHandActivity( actBase ); }
28.812595
140
0.59763
[ "object", "model" ]
67bd094b6c56229753518f66ed5489ec4e7f46a0
2,724
cpp
C++
src/cpp/toolkit/engine/models/mesh.cpp
ismacaulay/code-adventures
05296f5bb873d7b0d2bda0303510bc90d7c467f4
[ "MIT" ]
1
2021-02-25T22:37:08.000Z
2021-02-25T22:37:08.000Z
src/cpp/toolkit/engine/models/mesh.cpp
ismacaulay/code-adventures
05296f5bb873d7b0d2bda0303510bc90d7c467f4
[ "MIT" ]
11
2020-01-12T22:47:12.000Z
2021-02-01T01:23:44.000Z
src/cpp/toolkit/engine/models/mesh.cpp
ismacaulay/code-adventures
05296f5bb873d7b0d2bda0303510bc90d7c467f4
[ "MIT" ]
null
null
null
#include "mesh.h" #include "defines.h" #include "engine/rendering/buffer_layout.h" #include "engine/rendering/index_buffer.h" #include "engine/rendering/renderer.h" #include "engine/rendering/shader.h" #include "engine/rendering/texture2d.h" #include "engine/rendering/vertex_array.h" #include "engine/rendering/vertex_buffer.h" #include "math/box.h" namespace tk { namespace engine { Mesh::Mesh(const std::vector<Vertex>& vertices, const std::vector<Index>& indices, const std::vector<std::shared_ptr<Texture2D>>& textures) : vertices_(vertices) , indices_(indices) , textures_(textures) , box_(nullptr) { auto vb = VertexBuffer::create(vertices_.data(), vertices_.size() * sizeof(Vertex)); vb->set_layout({ { ShaderDataType::Float3, "a_position" }, { ShaderDataType::Float3, "a_normal" }, { ShaderDataType::Float2, "a_tex_coords" }, }); auto ib = IndexBuffer::create(indices_.data(), indices_.size() * sizeof(Index)); va_ = VertexArray::create(); va_->add_vertex_buffer(vb); } Mesh::~Mesh() {} math::Box* Mesh::compute_bounding_box() { if (vertices_.size() == 0) { return nullptr; } if (box_) { return box_.get(); } box_ = std::make_unique<math::Box>(); glm::vec3 min = { MAX_F32, MAX_F32, MAX_F32 }; glm::vec3 max = { MIN_F32, MIN_F32, MIN_F32 }; for (auto& vertex : vertices_) { if (vertex.position.x < min.x) { min.x = vertex.position.x; } if (vertex.position.y < min.y) { min.y = vertex.position.y; } if (vertex.position.z < min.z) { min.z = vertex.position.z; } if (vertex.position.x > max.x) { max.x = vertex.position.x; } if (vertex.position.y > max.y) { max.y = vertex.position.y; } if (vertex.position.z > max.z) { max.z = vertex.position.z; } } box_->min = min; box_->max = max; return box_.get(); } void Mesh::render(const std::shared_ptr<Shader>& shader, const glm::mat4& transform) { for (size_t i = 0; i < textures_.size(); i++) { auto& texture = textures_[i]; texture->bind(i); shader->set_uniform_int("u_texture_" + std::to_string(i), i); } Renderer::submit(shader, va_, transform); } } }
29.290323
74
0.514684
[ "mesh", "render", "vector", "transform" ]
67be773588dd2b4fdd999bc66d553e64fa0c8fcd
5,956
cc
C++
code/Homa/src/DebugTest.cc
Lossless-Virtual-Switching/Backdraft
99e8f7acf833d1755a109898eb397c3412fff159
[ "MIT" ]
66
2018-08-07T12:04:24.000Z
2022-03-20T15:20:55.000Z
code/Homa/src/DebugTest.cc
Lossless-Virtual-Switching/Backdraft
99e8f7acf833d1755a109898eb397c3412fff159
[ "MIT" ]
10
2018-04-25T19:10:01.000Z
2021-01-24T20:41:48.000Z
code/Homa/src/DebugTest.cc
Lossless-Virtual-Switching/Backdraft
99e8f7acf833d1755a109898eb397c3412fff159
[ "MIT" ]
14
2018-10-19T00:47:41.000Z
2022-03-01T01:54:17.000Z
/* Copyright (c) 2012-2018 Stanford University * Copyright (c) 2014-2015 Diego Ongaro * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR(S) DISCLAIM ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL AUTHORS BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include <gtest/gtest.h> #include "Debug.h" #include "STLUtil.h" #include <sys/stat.h> #include <unordered_map> namespace Homa { namespace Debug { namespace Internal { extern std::unordered_map<const char*, LogLevel> isLoggingCache; const char* logLevelToString(LogLevel); LogLevel logLevelFromString(const std::string& level); LogLevel getLogLevel(const char* fileName); const char* relativeFileName(const char* fileName); } // namespace Internal namespace { class DebugTest : public ::testing::Test { public: DebugTest() { setLogPolicy({}); setLogFile(stderr); } ~DebugTest() { Debug::setLogHandler(std::function<void(DebugMessage)>()); FILE* prev = setLogFile(stderr); if (prev != stderr) fclose(prev); } }; TEST_F(DebugTest, logLevelToString) { EXPECT_STREQ("SILENT", Internal::logLevelToString(LogLevel::SILENT)); EXPECT_STREQ("ERROR", Internal::logLevelToString(LogLevel::ERROR)); EXPECT_STREQ("WARNING", Internal::logLevelToString(LogLevel::WARNING)); EXPECT_STREQ("NOTICE", Internal::logLevelToString(LogLevel::NOTICE)); EXPECT_STREQ("VERBOSE", Internal::logLevelToString(LogLevel::VERBOSE)); } TEST_F(DebugTest, logLevelFromString) { EXPECT_EQ(LogLevel::SILENT, Internal::logLevelFromString("SILeNT")); EXPECT_EQ(LogLevel::ERROR, Internal::logLevelFromString("ERrOR")); EXPECT_EQ(LogLevel::WARNING, Internal::logLevelFromString("WARNiNG")); EXPECT_EQ(LogLevel::NOTICE, Internal::logLevelFromString("NOTIcE")); EXPECT_EQ(LogLevel::VERBOSE, Internal::logLevelFromString("VERBOsE")); EXPECT_DEATH(Internal::logLevelFromString("asdlf"), "'asdlf' is not a valid log level."); } TEST_F(DebugTest, getLogLevel) { // verify default is NOTICE EXPECT_EQ(LogLevel::NOTICE, Internal::getLogLevel(__FILE__)); setLogPolicy({{"prefix", "VERBOSE"}, {"suffix", "ERROR"}, {"", "WARNING"}}); EXPECT_EQ(LogLevel::VERBOSE, Internal::getLogLevel("prefixabcsuffix")); EXPECT_EQ(LogLevel::ERROR, Internal::getLogLevel("abcsuffix")); EXPECT_EQ(LogLevel::WARNING, Internal::getLogLevel("asdf")); } TEST_F(DebugTest, relativeFileName) { EXPECT_STREQ("src/DebugTest.cc", Internal::relativeFileName(__FILE__)); EXPECT_STREQ("/a/b/c", Internal::relativeFileName("/a/b/c")); } TEST_F(DebugTest, isLogging) { EXPECT_TRUE(isLogging(LogLevel::ERROR, "abc")); EXPECT_TRUE(isLogging(LogLevel::ERROR, "abc")); EXPECT_FALSE(isLogging(LogLevel::VERBOSE, "abc")); EXPECT_EQ((std::vector<std::pair<const char*, LogLevel>>{ {"abc", LogLevel::NOTICE}, }), STLUtil::getItems(Internal::isLoggingCache)); } TEST_F(DebugTest, setLogFile) { EXPECT_EQ(stderr, setLogFile(stdout)); EXPECT_EQ(stdout, setLogFile(stderr)); } struct VectorHandler { VectorHandler() : messages() {} void operator()(DebugMessage message) { messages.push_back(message); } std::vector<DebugMessage> messages; }; TEST_F(DebugTest, setLogHandler) { VectorHandler handler; setLogHandler(std::ref(handler)); ERROR("Hello, world! %d", 9); EXPECT_EQ(1U, handler.messages.size()); const DebugMessage& m = handler.messages.at(0); EXPECT_STREQ("src/DebugTest.cc", m.filename); EXPECT_LT(1, m.linenum); EXPECT_STREQ("TestBody", m.function); EXPECT_EQ(int(LogLevel::ERROR), m.logLevel); EXPECT_STREQ("ERROR", m.logLevelString); EXPECT_EQ("Hello, world! 9", m.message); } TEST_F(DebugTest, setLogPolicy) { setLogPolicy({{"prefix", "VERBOSE"}, {"suffix", "ERROR"}, {"", "WARNING"}}); EXPECT_EQ(LogLevel::VERBOSE, Internal::getLogLevel("prefixabcsuffix")); EXPECT_EQ(LogLevel::ERROR, Internal::getLogLevel("abcsuffix")); EXPECT_EQ(LogLevel::WARNING, Internal::getLogLevel("asdf")); } std::string normalize(const std::string& in) { return logPolicyToString(logPolicyFromString(in)); } TEST_F(DebugTest, logPolicyFromString) { EXPECT_EQ("NOTICE", normalize("")); EXPECT_EQ("ERROR", normalize("ERROR")); EXPECT_EQ("ERROR", normalize("@ERROR")); EXPECT_EQ("prefix@VERBOSE,suffix@ERROR,WARNING", normalize("prefix@VERBOSE,suffix@ERROR,WARNING")); EXPECT_EQ("prefix@VERBOSE,suffix@ERROR,NOTICE", normalize("prefix@VERBOSE,suffix@ERROR,@NOTICE")); EXPECT_EQ("prefix@VERBOSE,suffix@ERROR,NOTICE", normalize("prefix@VERBOSE,suffix@ERROR,NOTICE")); } TEST_F(DebugTest, logPolicyToString) { EXPECT_EQ("NOTICE", logPolicyToString(getLogPolicy())); setLogPolicy({{"", "ERROR"}}); EXPECT_EQ("ERROR", logPolicyToString(getLogPolicy())); setLogPolicy({{"prefix", "VERBOSE"}, {"suffix", "ERROR"}, {"", "WARNING"}}); EXPECT_EQ("prefix@VERBOSE,suffix@ERROR,WARNING", logPolicyToString(getLogPolicy())); setLogPolicy({{"prefix", "VERBOSE"}, {"suffix", "ERROR"}}); EXPECT_EQ("prefix@VERBOSE,suffix@ERROR,NOTICE", logPolicyToString(getLogPolicy())); } // log: low cost-benefit in testing } // namespace } // namespace Debug } // namespace Homa
33.088889
80
0.691907
[ "vector" ]
67c1a53d87c669000472c0d4f32b043c5c71d4b1
1,113
cpp
C++
src/coherence/util/aggregator/AbstractInteger64Aggregator.cpp
chpatel3/coherence-cpp-extend-client
4ea5267eae32064dff1e73339aa3fbc9347ef0f6
[ "UPL-1.0", "Apache-2.0" ]
6
2020-07-01T21:38:30.000Z
2021-11-03T01:35:11.000Z
src/coherence/util/aggregator/AbstractInteger64Aggregator.cpp
chpatel3/coherence-cpp-extend-client
4ea5267eae32064dff1e73339aa3fbc9347ef0f6
[ "UPL-1.0", "Apache-2.0" ]
1
2020-07-24T17:29:22.000Z
2020-07-24T18:29:04.000Z
src/coherence/util/aggregator/AbstractInteger64Aggregator.cpp
chpatel3/coherence-cpp-extend-client
4ea5267eae32064dff1e73339aa3fbc9347ef0f6
[ "UPL-1.0", "Apache-2.0" ]
6
2020-07-10T18:40:58.000Z
2022-02-18T01:23:40.000Z
/* * Copyright (c) 2000, 2020, Oracle and/or its affiliates. * * Licensed under the Universal Permissive License v 1.0 as shown at * http://oss.oracle.com/licenses/upl. */ #include "coherence/util/aggregator/AbstractInteger64Aggregator.hpp" COH_OPEN_NAMESPACE3(coherence,util,aggregator) // ----- constructors ------------------------------------------------------- AbstractInteger64Aggregator::AbstractInteger64Aggregator() : super() { } AbstractInteger64Aggregator::AbstractInteger64Aggregator( ValueExtractor::View vExtractor) : super(vExtractor) { } AbstractInteger64Aggregator::AbstractInteger64Aggregator( String::View vsMethod) : super(vsMethod) { } // ----- AbstractAggregator Interface -------------------------------------- void AbstractInteger64Aggregator::init(bool /* fFinal */) { m_count = 0; } Object::Holder AbstractInteger64Aggregator::finalizeResult( bool /* fFinal */) { return m_count == 0 ? (Integer64::Handle) NULL : Integer64::valueOf(m_lResult); } COH_CLOSE_NAMESPACE3
24.195652
77
0.628032
[ "object" ]
67c7829db7feb643737a975977210308386087f5
4,184
cpp
C++
app/model/CTableModel.cpp
katecpp/sheep_sweeper
aa2fa8262f09460fc4b5ceb45174fec315fd6460
[ "MIT" ]
4
2016-01-23T13:35:25.000Z
2018-10-25T08:15:08.000Z
app/model/CTableModel.cpp
katecpp/sheep_sweeper
aa2fa8262f09460fc4b5ceb45174fec315fd6460
[ "MIT" ]
null
null
null
app/model/CTableModel.cpp
katecpp/sheep_sweeper
aa2fa8262f09460fc4b5ceb45174fec315fd6460
[ "MIT" ]
2
2017-04-13T06:23:41.000Z
2021-01-11T16:45:23.000Z
#include <model/CTableModel.h> #include <QPixmap> #include <QSize> namespace SSw { CTableModel::CTableModel(QObject *parent) : QAbstractTableModel(parent), m_model(), m_sheepDisplay(0), m_initialized(false) { } void CTableModel::init(const QModelIndex &index) { m_model.populate(index.row(), index.column()); m_initialized = true; emit gameStarted(); } int CTableModel::rowCount(const QModelIndex &parent) const { Q_UNUSED(parent) return m_model.width(); } int CTableModel::columnCount(const QModelIndex &parent) const { Q_UNUSED(parent) return m_model.height(); } QVariant CTableModel::data(const QModelIndex &index, int role) const { if (!index.isValid()) { return QVariant(); } if (Qt::UserRole == role) { QVariant variant; variant.setValue(m_model.field(index.row(), index.column())); return variant; } return QVariant(); } void CTableModel::resetModel(int32_t width, int32_t height, int32_t sheep) { m_initialized = false; m_sheepDisplay = sheep; m_model.reset(width, height, sheep); emit sheepDisplay(sheep); emit layoutChanged(); } void CTableModel::onTableClicked(const QModelIndex &index) { if (m_model.field(index.row(), index.column()).disarmed == 0) { discover(index); } } void CTableModel::discover(const QModelIndex &index) { if (!m_initialized) { init(index); } const int32_t x = index.row(); const int32_t y = index.column(); m_model.discover(x, y); if (m_model.field(x, y).neighbours == 0 && m_model.field(x, y).sheep == 0) { if (!m_model.getDiscovered(x-1, y-1)) discover(index.sibling(x-1, y-1)); // up if (!m_model.getDiscovered(x, y-1)) discover(index.sibling(x, y-1)); if (!m_model.getDiscovered(x+1, y-1)) discover(index.sibling(x+1, y-1)); if (!m_model.getDiscovered(x-1, y)) discover(index.sibling(x-1, y)); // mid if (!m_model.getDiscovered(x+1, y)) discover(index.sibling(x+1, y)); if (!m_model.getDiscovered(x-1, y+1)) discover(index.sibling(x-1, y+1)); // down if (!m_model.getDiscovered(x, y+1)) discover(index.sibling(x, y+1)); if (!m_model.getDiscovered(x+1, y+1)) discover(index.sibling(x+1, y+1)); } emit dataChanged(index, index); if (m_model.field(x, y).sheep && m_model.field(x, y).disarmed == 0) { emit gameLost(); } else if (m_model.checkWinCondition()) { emit gameWon(); } } void CTableModel::onRightClicked(const QModelIndex &index) { const int32_t x = index.row(); const int32_t y = index.column(); if (m_model.field(x, y).discovered == 0) { m_model.disarm(x, y); if (m_model.field(x, y).disarmed == 1) { m_sheepDisplay--; } else if (m_model.field(x, y).disarmed == 0) { m_sheepDisplay++; } emit sheepDisplay(m_sheepDisplay); emit dataChanged(index, index); } } void CTableModel::onBothClicked(const QModelIndex &index) { const int32_t x = index.row(); const int32_t y = index.column(); if (m_model.getDiscovered(x, y) && m_model.getNeighbours(x, y) == m_model.countFlagsAround(x, y)) { if (!m_model.getDiscovered(x-1, y-1)) discover(index.sibling(x-1, y-1)); // up if (!m_model.getDiscovered(x, y-1)) discover(index.sibling(x, y-1)); if (!m_model.getDiscovered(x+1, y-1)) discover(index.sibling(x+1, y-1)); if (!m_model.getDiscovered(x-1, y)) discover(index.sibling(x-1, y)); // mid if (!m_model.getDiscovered(x+1, y)) discover(index.sibling(x+1, y)); if (!m_model.getDiscovered(x-1, y+1)) discover(index.sibling(x-1, y+1)); // down if (!m_model.getDiscovered(x, y+1)) discover(index.sibling(x, y+1)); if (!m_model.getDiscovered(x+1, y+1)) discover(index.sibling(x+1, y+1)); } } } // namespace SSw
28.462585
91
0.58413
[ "model" ]
67c9fd2f7dde72f94309d3a684c921bc981d46b1
122,477
cc
C++
src/xenia/gpu/d3d12/texture_cache.cc
bomabomaboma/xenia-canary
e67b3327307d78290b290338871b95010f76a3a2
[ "BSD-3-Clause" ]
null
null
null
src/xenia/gpu/d3d12/texture_cache.cc
bomabomaboma/xenia-canary
e67b3327307d78290b290338871b95010f76a3a2
[ "BSD-3-Clause" ]
null
null
null
src/xenia/gpu/d3d12/texture_cache.cc
bomabomaboma/xenia-canary
e67b3327307d78290b290338871b95010f76a3a2
[ "BSD-3-Clause" ]
null
null
null
/** ****************************************************************************** * Xenia : Xbox 360 Emulator Research Project * ****************************************************************************** * Copyright 2018 Ben Vanik. All rights reserved. * * Released under the BSD license - see LICENSE in the root for more details. * ****************************************************************************** */ #include "xenia/gpu/d3d12/texture_cache.h" #include <algorithm> #include <array> #include <cfloat> #include <cstring> #include "xenia/base/assert.h" #include "xenia/base/clock.h" #include "xenia/base/cvar.h" #include "xenia/base/logging.h" #include "xenia/base/math.h" #include "xenia/base/profiling.h" #include "xenia/base/xxhash.h" #include "xenia/gpu/d3d12/d3d12_command_processor.h" #include "xenia/gpu/d3d12/d3d12_shared_memory.h" #include "xenia/gpu/gpu_flags.h" #include "xenia/gpu/texture_info.h" #include "xenia/gpu/texture_util.h" #include "xenia/ui/d3d12/d3d12_upload_buffer_pool.h" #include "xenia/ui/d3d12/d3d12_util.h" DEFINE_uint32( texture_cache_memory_limit_soft, 384, "Maximum host texture memory usage (in megabytes) above which old textures " "will be destroyed.", "GPU"); DEFINE_uint32( texture_cache_memory_limit_soft_lifetime, 30, "Seconds a texture should be unused to be considered old enough to be " "deleted if texture memory usage exceeds texture_cache_memory_limit_soft.", "GPU"); DEFINE_uint32( texture_cache_memory_limit_hard, 768, "Maximum host texture memory usage (in megabytes) above which textures " "will be destroyed as soon as possible.", "GPU"); DEFINE_uint32( texture_cache_memory_limit_render_to_texture, 24, "Part of the host texture memory budget (in megabytes) that will be scaled " "by the current drawing resolution scale.\n" "If texture_cache_memory_limit_soft, for instance, is 384, and this is 24, " "it will be assumed that the game will be using roughly 24 MB of " "render-to-texture (resolve) targets and 384 - 24 = 360 MB of regular " "textures - so with 2x resolution scaling, the soft limit will be 360 + 96 " "MB, and with 3x, it will be 360 + 216 MB.", "GPU"); namespace xe { namespace gpu { namespace d3d12 { // Generated with `xb buildhlsl`. #include "xenia/gpu/d3d12/shaders/dxbc/texture_load_128bpb_2x_cs.h" #include "xenia/gpu/d3d12/shaders/dxbc/texture_load_128bpb_3x_cs.h" #include "xenia/gpu/d3d12/shaders/dxbc/texture_load_128bpb_cs.h" #include "xenia/gpu/d3d12/shaders/dxbc/texture_load_16bpb_2x_cs.h" #include "xenia/gpu/d3d12/shaders/dxbc/texture_load_16bpb_3x_cs.h" #include "xenia/gpu/d3d12/shaders/dxbc/texture_load_16bpb_cs.h" #include "xenia/gpu/d3d12/shaders/dxbc/texture_load_32bpb_2x_cs.h" #include "xenia/gpu/d3d12/shaders/dxbc/texture_load_32bpb_3x_cs.h" #include "xenia/gpu/d3d12/shaders/dxbc/texture_load_32bpb_cs.h" #include "xenia/gpu/d3d12/shaders/dxbc/texture_load_64bpb_2x_cs.h" #include "xenia/gpu/d3d12/shaders/dxbc/texture_load_64bpb_3x_cs.h" #include "xenia/gpu/d3d12/shaders/dxbc/texture_load_64bpb_cs.h" #include "xenia/gpu/d3d12/shaders/dxbc/texture_load_8bpb_2x_cs.h" #include "xenia/gpu/d3d12/shaders/dxbc/texture_load_8bpb_3x_cs.h" #include "xenia/gpu/d3d12/shaders/dxbc/texture_load_8bpb_cs.h" #include "xenia/gpu/d3d12/shaders/dxbc/texture_load_ctx1_cs.h" #include "xenia/gpu/d3d12/shaders/dxbc/texture_load_depth_float_2x_cs.h" #include "xenia/gpu/d3d12/shaders/dxbc/texture_load_depth_float_3x_cs.h" #include "xenia/gpu/d3d12/shaders/dxbc/texture_load_depth_float_cs.h" #include "xenia/gpu/d3d12/shaders/dxbc/texture_load_depth_unorm_2x_cs.h" #include "xenia/gpu/d3d12/shaders/dxbc/texture_load_depth_unorm_3x_cs.h" #include "xenia/gpu/d3d12/shaders/dxbc/texture_load_depth_unorm_cs.h" #include "xenia/gpu/d3d12/shaders/dxbc/texture_load_dxn_rg8_cs.h" #include "xenia/gpu/d3d12/shaders/dxbc/texture_load_dxt1_rgba8_cs.h" #include "xenia/gpu/d3d12/shaders/dxbc/texture_load_dxt3_rgba8_cs.h" #include "xenia/gpu/d3d12/shaders/dxbc/texture_load_dxt3a_cs.h" #include "xenia/gpu/d3d12/shaders/dxbc/texture_load_dxt3aas1111_cs.h" #include "xenia/gpu/d3d12/shaders/dxbc/texture_load_dxt5_rgba8_cs.h" #include "xenia/gpu/d3d12/shaders/dxbc/texture_load_dxt5a_r8_cs.h" #include "xenia/gpu/d3d12/shaders/dxbc/texture_load_r10g11b11_rgba16_2x_cs.h" #include "xenia/gpu/d3d12/shaders/dxbc/texture_load_r10g11b11_rgba16_3x_cs.h" #include "xenia/gpu/d3d12/shaders/dxbc/texture_load_r10g11b11_rgba16_cs.h" #include "xenia/gpu/d3d12/shaders/dxbc/texture_load_r10g11b11_rgba16_snorm_2x_cs.h" #include "xenia/gpu/d3d12/shaders/dxbc/texture_load_r10g11b11_rgba16_snorm_3x_cs.h" #include "xenia/gpu/d3d12/shaders/dxbc/texture_load_r10g11b11_rgba16_snorm_cs.h" #include "xenia/gpu/d3d12/shaders/dxbc/texture_load_r11g11b10_rgba16_2x_cs.h" #include "xenia/gpu/d3d12/shaders/dxbc/texture_load_r11g11b10_rgba16_3x_cs.h" #include "xenia/gpu/d3d12/shaders/dxbc/texture_load_r11g11b10_rgba16_cs.h" #include "xenia/gpu/d3d12/shaders/dxbc/texture_load_r11g11b10_rgba16_snorm_2x_cs.h" #include "xenia/gpu/d3d12/shaders/dxbc/texture_load_r11g11b10_rgba16_snorm_3x_cs.h" #include "xenia/gpu/d3d12/shaders/dxbc/texture_load_r11g11b10_rgba16_snorm_cs.h" #include "xenia/gpu/d3d12/shaders/dxbc/texture_load_r4g4b4a4_b4g4r4a4_2x_cs.h" #include "xenia/gpu/d3d12/shaders/dxbc/texture_load_r4g4b4a4_b4g4r4a4_3x_cs.h" #include "xenia/gpu/d3d12/shaders/dxbc/texture_load_r4g4b4a4_b4g4r4a4_cs.h" #include "xenia/gpu/d3d12/shaders/dxbc/texture_load_r5g5b5a1_b5g5r5a1_2x_cs.h" #include "xenia/gpu/d3d12/shaders/dxbc/texture_load_r5g5b5a1_b5g5r5a1_3x_cs.h" #include "xenia/gpu/d3d12/shaders/dxbc/texture_load_r5g5b5a1_b5g5r5a1_cs.h" #include "xenia/gpu/d3d12/shaders/dxbc/texture_load_r5g5b6_b5g6r5_swizzle_rbga_2x_cs.h" #include "xenia/gpu/d3d12/shaders/dxbc/texture_load_r5g5b6_b5g6r5_swizzle_rbga_3x_cs.h" #include "xenia/gpu/d3d12/shaders/dxbc/texture_load_r5g5b6_b5g6r5_swizzle_rbga_cs.h" #include "xenia/gpu/d3d12/shaders/dxbc/texture_load_r5g6b5_b5g6r5_2x_cs.h" #include "xenia/gpu/d3d12/shaders/dxbc/texture_load_r5g6b5_b5g6r5_3x_cs.h" #include "xenia/gpu/d3d12/shaders/dxbc/texture_load_r5g6b5_b5g6r5_cs.h" // For formats with less than 4 components, assuming the last component is // replicated into the non-existent ones, similar to what is done for unused // components of operands in shaders. // For DXT3A and DXT5A, RRRR swizzle is specified in: // http://fileadmin.cs.lth.se/cs/Personal/Michael_Doggett/talks/unc-xenos-doggett.pdf // Halo 3 also expects replicated components in k_8 sprites. // DXN is read as RG in Halo 3, but as RA in Call of Duty. // TODO(Triang3l): Find out the correct contents of unused texture components. const TextureCache::HostFormat TextureCache::host_formats_[64] = { // k_1_REVERSE {DXGI_FORMAT_UNKNOWN, DXGI_FORMAT_UNKNOWN, LoadMode::kUnknown, DXGI_FORMAT_UNKNOWN, LoadMode::kUnknown, false, DXGI_FORMAT_UNKNOWN, LoadMode::kUnknown, {0, 0, 0, 0}}, // k_1 {DXGI_FORMAT_UNKNOWN, DXGI_FORMAT_UNKNOWN, LoadMode::kUnknown, DXGI_FORMAT_UNKNOWN, LoadMode::kUnknown, false, DXGI_FORMAT_UNKNOWN, LoadMode::kUnknown, {0, 0, 0, 0}}, // k_8 {DXGI_FORMAT_R8_TYPELESS, DXGI_FORMAT_R8_UNORM, LoadMode::k8bpb, DXGI_FORMAT_R8_SNORM, LoadMode::kUnknown, false, DXGI_FORMAT_UNKNOWN, LoadMode::kUnknown, {0, 0, 0, 0}}, // k_1_5_5_5 // Red and blue swapped in the load shader for simplicity. {DXGI_FORMAT_B5G5R5A1_UNORM, DXGI_FORMAT_B5G5R5A1_UNORM, LoadMode::kR5G5B5A1ToB5G5R5A1, DXGI_FORMAT_UNKNOWN, LoadMode::kUnknown, false, DXGI_FORMAT_UNKNOWN, LoadMode::kUnknown, {0, 1, 2, 3}}, // k_5_6_5 // Red and blue swapped in the load shader for simplicity. {DXGI_FORMAT_B5G6R5_UNORM, DXGI_FORMAT_B5G6R5_UNORM, LoadMode::kR5G6B5ToB5G6R5, DXGI_FORMAT_UNKNOWN, LoadMode::kUnknown, false, DXGI_FORMAT_UNKNOWN, LoadMode::kUnknown, {0, 1, 2, 2}}, // k_6_5_5 // On the host, green bits in blue, blue bits in green. {DXGI_FORMAT_B5G6R5_UNORM, DXGI_FORMAT_B5G6R5_UNORM, LoadMode::kR5G5B6ToB5G6R5WithRBGASwizzle, DXGI_FORMAT_UNKNOWN, LoadMode::kUnknown, false, DXGI_FORMAT_UNKNOWN, LoadMode::kUnknown, {0, 2, 1, 1}}, // k_8_8_8_8 {DXGI_FORMAT_R8G8B8A8_TYPELESS, DXGI_FORMAT_R8G8B8A8_UNORM, LoadMode::k32bpb, DXGI_FORMAT_R8G8B8A8_SNORM, LoadMode::kUnknown, false, DXGI_FORMAT_UNKNOWN, LoadMode::kUnknown, {0, 1, 2, 3}}, // k_2_10_10_10 {DXGI_FORMAT_R10G10B10A2_TYPELESS, DXGI_FORMAT_R10G10B10A2_UNORM, LoadMode::k32bpb, DXGI_FORMAT_UNKNOWN, LoadMode::kUnknown, false, DXGI_FORMAT_UNKNOWN, LoadMode::kUnknown, {0, 1, 2, 3}}, // k_8_A {DXGI_FORMAT_R8_TYPELESS, DXGI_FORMAT_R8_UNORM, LoadMode::k8bpb, DXGI_FORMAT_R8_SNORM, LoadMode::kUnknown, false, DXGI_FORMAT_UNKNOWN, LoadMode::kUnknown, {0, 0, 0, 0}}, // k_8_B {DXGI_FORMAT_UNKNOWN, DXGI_FORMAT_UNKNOWN, LoadMode::kUnknown, DXGI_FORMAT_UNKNOWN, LoadMode::kUnknown, false, DXGI_FORMAT_UNKNOWN, LoadMode::kUnknown, {0, 0, 0, 0}}, // k_8_8 {DXGI_FORMAT_R8G8_TYPELESS, DXGI_FORMAT_R8G8_UNORM, LoadMode::k16bpb, DXGI_FORMAT_R8G8_SNORM, LoadMode::kUnknown, false, DXGI_FORMAT_UNKNOWN, LoadMode::kUnknown, {0, 1, 1, 1}}, // k_Cr_Y1_Cb_Y0_REP // Red and blue probably must be swapped, similar to k_Y1_Cr_Y0_Cb_REP. {DXGI_FORMAT_G8R8_G8B8_UNORM, DXGI_FORMAT_G8R8_G8B8_UNORM, LoadMode::k32bpb, DXGI_FORMAT_UNKNOWN, LoadMode::kUnknown, true, DXGI_FORMAT_UNKNOWN, LoadMode::kUnknown, {2, 1, 0, 3}}, // k_Y1_Cr_Y0_Cb_REP // Used for videos in NBA 2K9. Red and blue must be swapped. // TODO(Triang3l): D3DFMT_G8R8_G8B8 is DXGI_FORMAT_R8G8_B8G8_UNORM * 255.0f, // watch out for num_format int, division in shaders, etc., in NBA 2K9 it // works as is. Also need to decompress if the size is uneven, but should be // a very rare case. {DXGI_FORMAT_R8G8_B8G8_UNORM, DXGI_FORMAT_R8G8_B8G8_UNORM, LoadMode::k32bpb, DXGI_FORMAT_UNKNOWN, LoadMode::kUnknown, true, DXGI_FORMAT_UNKNOWN, LoadMode::kUnknown, {2, 1, 0, 3}}, // k_16_16_EDRAM // Not usable as a texture, also has -32...32 range. {DXGI_FORMAT_UNKNOWN, DXGI_FORMAT_UNKNOWN, LoadMode::kUnknown, DXGI_FORMAT_UNKNOWN, LoadMode::kUnknown, false, DXGI_FORMAT_UNKNOWN, LoadMode::kUnknown, {0, 1, 1, 1}}, // k_8_8_8_8_A {DXGI_FORMAT_UNKNOWN, DXGI_FORMAT_UNKNOWN, LoadMode::kUnknown, DXGI_FORMAT_UNKNOWN, LoadMode::kUnknown, false, DXGI_FORMAT_UNKNOWN, LoadMode::kUnknown, {0, 1, 2, 3}}, // k_4_4_4_4 // Red and blue swapped in the load shader for simplicity. {DXGI_FORMAT_B4G4R4A4_UNORM, DXGI_FORMAT_B4G4R4A4_UNORM, LoadMode::kR4G4B4A4ToB4G4R4A4, DXGI_FORMAT_UNKNOWN, LoadMode::kUnknown, false, DXGI_FORMAT_UNKNOWN, LoadMode::kUnknown, {0, 1, 2, 3}}, // k_10_11_11 {DXGI_FORMAT_R16G16B16A16_TYPELESS, DXGI_FORMAT_R16G16B16A16_UNORM, LoadMode::kR11G11B10ToRGBA16, DXGI_FORMAT_R16G16B16A16_SNORM, LoadMode::kR11G11B10ToRGBA16SNorm, false, DXGI_FORMAT_UNKNOWN, LoadMode::kUnknown, {0, 1, 2, 2}}, // k_11_11_10 {DXGI_FORMAT_R16G16B16A16_TYPELESS, DXGI_FORMAT_R16G16B16A16_UNORM, LoadMode::kR10G11B11ToRGBA16, DXGI_FORMAT_R16G16B16A16_SNORM, LoadMode::kR10G11B11ToRGBA16SNorm, false, DXGI_FORMAT_UNKNOWN, LoadMode::kUnknown, {0, 1, 2, 2}}, // k_DXT1 {DXGI_FORMAT_BC1_UNORM, DXGI_FORMAT_BC1_UNORM, LoadMode::k64bpb, DXGI_FORMAT_UNKNOWN, LoadMode::kUnknown, true, DXGI_FORMAT_R8G8B8A8_UNORM, LoadMode::kDXT1ToRGBA8, {0, 1, 2, 3}}, // k_DXT2_3 {DXGI_FORMAT_BC2_UNORM, DXGI_FORMAT_BC2_UNORM, LoadMode::k128bpb, DXGI_FORMAT_UNKNOWN, LoadMode::kUnknown, true, DXGI_FORMAT_R8G8B8A8_UNORM, LoadMode::kDXT3ToRGBA8, {0, 1, 2, 3}}, // k_DXT4_5 {DXGI_FORMAT_BC3_UNORM, DXGI_FORMAT_BC3_UNORM, LoadMode::k128bpb, DXGI_FORMAT_UNKNOWN, LoadMode::kUnknown, true, DXGI_FORMAT_R8G8B8A8_UNORM, LoadMode::kDXT5ToRGBA8, {0, 1, 2, 3}}, // k_16_16_16_16_EDRAM // Not usable as a texture, also has -32...32 range. {DXGI_FORMAT_UNKNOWN, DXGI_FORMAT_UNKNOWN, LoadMode::kUnknown, DXGI_FORMAT_UNKNOWN, LoadMode::kUnknown, false, DXGI_FORMAT_UNKNOWN, LoadMode::kUnknown, {0, 1, 2, 3}}, // R32_FLOAT for depth because shaders would require an additional SRV to // sample stencil, which we don't provide. // k_24_8 {DXGI_FORMAT_R32_FLOAT, DXGI_FORMAT_R32_FLOAT, LoadMode::kDepthUnorm, DXGI_FORMAT_R32_FLOAT, LoadMode::kUnknown, false, DXGI_FORMAT_UNKNOWN, LoadMode::kUnknown, {0, 0, 0, 0}}, // k_24_8_FLOAT {DXGI_FORMAT_R32_FLOAT, DXGI_FORMAT_R32_FLOAT, LoadMode::kDepthFloat, DXGI_FORMAT_R32_FLOAT, LoadMode::kUnknown, false, DXGI_FORMAT_UNKNOWN, LoadMode::kUnknown, {0, 0, 0, 0}}, // k_16 {DXGI_FORMAT_R16_TYPELESS, DXGI_FORMAT_R16_UNORM, LoadMode::k16bpb, DXGI_FORMAT_R16_SNORM, LoadMode::kUnknown, false, DXGI_FORMAT_UNKNOWN, LoadMode::kUnknown, {0, 0, 0, 0}}, // k_16_16 {DXGI_FORMAT_R16G16_TYPELESS, DXGI_FORMAT_R16G16_UNORM, LoadMode::k32bpb, DXGI_FORMAT_R16G16_SNORM, LoadMode::kUnknown, false, DXGI_FORMAT_UNKNOWN, LoadMode::kUnknown, {0, 1, 1, 1}}, // k_16_16_16_16 {DXGI_FORMAT_R16G16B16A16_TYPELESS, DXGI_FORMAT_R16G16B16A16_UNORM, LoadMode::k64bpb, DXGI_FORMAT_R16G16B16A16_SNORM, LoadMode::kUnknown, false, DXGI_FORMAT_UNKNOWN, LoadMode::kUnknown, {0, 1, 2, 3}}, // k_16_EXPAND {DXGI_FORMAT_R16_FLOAT, DXGI_FORMAT_R16_FLOAT, LoadMode::k16bpb, DXGI_FORMAT_R16_FLOAT, LoadMode::kUnknown, false, DXGI_FORMAT_UNKNOWN, LoadMode::kUnknown, {0, 0, 0, 0}}, // k_16_16_EXPAND {DXGI_FORMAT_R16G16_FLOAT, DXGI_FORMAT_R16G16_FLOAT, LoadMode::k32bpb, DXGI_FORMAT_R16G16_FLOAT, LoadMode::kUnknown, false, DXGI_FORMAT_UNKNOWN, LoadMode::kUnknown, {0, 1, 1, 1}}, // k_16_16_16_16_EXPAND {DXGI_FORMAT_R16G16B16A16_FLOAT, DXGI_FORMAT_R16G16B16A16_FLOAT, LoadMode::k64bpb, DXGI_FORMAT_R16G16B16A16_FLOAT, LoadMode::kUnknown, false, DXGI_FORMAT_UNKNOWN, LoadMode::kUnknown, {0, 1, 2, 3}}, // k_16_FLOAT {DXGI_FORMAT_R16_FLOAT, DXGI_FORMAT_R16_FLOAT, LoadMode::k16bpb, DXGI_FORMAT_R16_FLOAT, LoadMode::kUnknown, false, DXGI_FORMAT_UNKNOWN, LoadMode::kUnknown, {0, 0, 0, 0}}, // k_16_16_FLOAT {DXGI_FORMAT_R16G16_FLOAT, DXGI_FORMAT_R16G16_FLOAT, LoadMode::k32bpb, DXGI_FORMAT_R16G16_FLOAT, LoadMode::kUnknown, false, DXGI_FORMAT_UNKNOWN, LoadMode::kUnknown, {0, 1, 1, 1}}, // k_16_16_16_16_FLOAT {DXGI_FORMAT_R16G16B16A16_FLOAT, DXGI_FORMAT_R16G16B16A16_FLOAT, LoadMode::k64bpb, DXGI_FORMAT_R16G16B16A16_FLOAT, LoadMode::kUnknown, false, DXGI_FORMAT_UNKNOWN, LoadMode::kUnknown, {0, 1, 2, 3}}, // k_32 {DXGI_FORMAT_UNKNOWN, DXGI_FORMAT_UNKNOWN, LoadMode::kUnknown, DXGI_FORMAT_UNKNOWN, LoadMode::kUnknown, false, DXGI_FORMAT_UNKNOWN, LoadMode::kUnknown, {0, 0, 0, 0}}, // k_32_32 {DXGI_FORMAT_UNKNOWN, DXGI_FORMAT_UNKNOWN, LoadMode::kUnknown, DXGI_FORMAT_UNKNOWN, LoadMode::kUnknown, false, DXGI_FORMAT_UNKNOWN, LoadMode::kUnknown, {0, 1, 1, 1}}, // k_32_32_32_32 {DXGI_FORMAT_UNKNOWN, DXGI_FORMAT_UNKNOWN, LoadMode::kUnknown, DXGI_FORMAT_UNKNOWN, LoadMode::kUnknown, false, DXGI_FORMAT_UNKNOWN, LoadMode::kUnknown, {0, 1, 2, 3}}, // k_32_FLOAT {DXGI_FORMAT_R32_FLOAT, DXGI_FORMAT_R32_FLOAT, LoadMode::k32bpb, DXGI_FORMAT_R32_FLOAT, LoadMode::kUnknown, false, DXGI_FORMAT_UNKNOWN, LoadMode::kUnknown, {0, 0, 0, 0}}, // k_32_32_FLOAT {DXGI_FORMAT_R32G32_FLOAT, DXGI_FORMAT_R32G32_FLOAT, LoadMode::k64bpb, DXGI_FORMAT_R32G32_FLOAT, LoadMode::kUnknown, false, DXGI_FORMAT_UNKNOWN, LoadMode::kUnknown, {0, 1, 1, 1}}, // k_32_32_32_32_FLOAT {DXGI_FORMAT_R32G32B32A32_FLOAT, DXGI_FORMAT_R32G32B32A32_FLOAT, LoadMode::k128bpb, DXGI_FORMAT_R32G32B32A32_FLOAT, LoadMode::kUnknown, false, DXGI_FORMAT_UNKNOWN, LoadMode::kUnknown, {0, 1, 2, 3}}, // k_32_AS_8 {DXGI_FORMAT_UNKNOWN, DXGI_FORMAT_UNKNOWN, LoadMode::kUnknown, DXGI_FORMAT_UNKNOWN, LoadMode::kUnknown, false, DXGI_FORMAT_UNKNOWN, LoadMode::kUnknown, {0, 0, 0, 0}}, // k_32_AS_8_8 {DXGI_FORMAT_UNKNOWN, DXGI_FORMAT_UNKNOWN, LoadMode::kUnknown, DXGI_FORMAT_UNKNOWN, LoadMode::kUnknown, false, DXGI_FORMAT_UNKNOWN, LoadMode::kUnknown, {0, 1, 1, 1}}, // k_16_MPEG {DXGI_FORMAT_UNKNOWN, DXGI_FORMAT_UNKNOWN, LoadMode::kUnknown, DXGI_FORMAT_UNKNOWN, LoadMode::kUnknown, false, DXGI_FORMAT_UNKNOWN, LoadMode::kUnknown, {0, 0, 0, 0}}, // k_16_16_MPEG {DXGI_FORMAT_UNKNOWN, DXGI_FORMAT_UNKNOWN, LoadMode::kUnknown, DXGI_FORMAT_UNKNOWN, LoadMode::kUnknown, false, DXGI_FORMAT_UNKNOWN, LoadMode::kUnknown, {0, 1, 1, 1}}, // k_8_INTERLACED {DXGI_FORMAT_UNKNOWN, DXGI_FORMAT_UNKNOWN, LoadMode::kUnknown, DXGI_FORMAT_UNKNOWN, LoadMode::kUnknown, false, DXGI_FORMAT_UNKNOWN, LoadMode::kUnknown, {0, 0, 0, 0}}, // k_32_AS_8_INTERLACED {DXGI_FORMAT_UNKNOWN, DXGI_FORMAT_UNKNOWN, LoadMode::kUnknown, DXGI_FORMAT_UNKNOWN, LoadMode::kUnknown, false, DXGI_FORMAT_UNKNOWN, LoadMode::kUnknown, {0, 0, 0, 0}}, // k_32_AS_8_8_INTERLACED {DXGI_FORMAT_UNKNOWN, DXGI_FORMAT_UNKNOWN, LoadMode::kUnknown, DXGI_FORMAT_UNKNOWN, LoadMode::kUnknown, false, DXGI_FORMAT_UNKNOWN, LoadMode::kUnknown, {0, 1, 1, 1}}, // k_16_INTERLACED {DXGI_FORMAT_UNKNOWN, DXGI_FORMAT_UNKNOWN, LoadMode::kUnknown, DXGI_FORMAT_UNKNOWN, LoadMode::kUnknown, false, DXGI_FORMAT_UNKNOWN, LoadMode::kUnknown, {0, 0, 0, 0}}, // k_16_MPEG_INTERLACED {DXGI_FORMAT_UNKNOWN, DXGI_FORMAT_UNKNOWN, LoadMode::kUnknown, DXGI_FORMAT_UNKNOWN, LoadMode::kUnknown, false, DXGI_FORMAT_UNKNOWN, LoadMode::kUnknown, {0, 0, 0, 0}}, // k_16_16_MPEG_INTERLACED {DXGI_FORMAT_UNKNOWN, DXGI_FORMAT_UNKNOWN, LoadMode::kUnknown, DXGI_FORMAT_UNKNOWN, LoadMode::kUnknown, false, DXGI_FORMAT_UNKNOWN, LoadMode::kUnknown, {0, 1, 1, 1}}, // k_DXN {DXGI_FORMAT_BC5_UNORM, DXGI_FORMAT_BC5_UNORM, LoadMode::k128bpb, DXGI_FORMAT_UNKNOWN, LoadMode::kUnknown, true, DXGI_FORMAT_R8G8_UNORM, LoadMode::kDXNToRG8, {0, 1, 1, 1}}, // k_8_8_8_8_AS_16_16_16_16 {DXGI_FORMAT_R8G8B8A8_TYPELESS, DXGI_FORMAT_R8G8B8A8_UNORM, LoadMode::k32bpb, DXGI_FORMAT_R8G8B8A8_SNORM, LoadMode::kUnknown, false, DXGI_FORMAT_UNKNOWN, LoadMode::kUnknown, {0, 1, 2, 3}}, // k_DXT1_AS_16_16_16_16 {DXGI_FORMAT_BC1_UNORM, DXGI_FORMAT_BC1_UNORM, LoadMode::k64bpb, DXGI_FORMAT_UNKNOWN, LoadMode::kUnknown, true, DXGI_FORMAT_R8G8B8A8_UNORM, LoadMode::kDXT1ToRGBA8, {0, 1, 2, 3}}, // k_DXT2_3_AS_16_16_16_16 {DXGI_FORMAT_BC2_UNORM, DXGI_FORMAT_BC2_UNORM, LoadMode::k128bpb, DXGI_FORMAT_UNKNOWN, LoadMode::kUnknown, true, DXGI_FORMAT_R8G8B8A8_UNORM, LoadMode::kDXT3ToRGBA8, {0, 1, 2, 3}}, // k_DXT4_5_AS_16_16_16_16 {DXGI_FORMAT_BC3_UNORM, DXGI_FORMAT_BC3_UNORM, LoadMode::k128bpb, DXGI_FORMAT_UNKNOWN, LoadMode::kUnknown, true, DXGI_FORMAT_R8G8B8A8_UNORM, LoadMode::kDXT5ToRGBA8, {0, 1, 2, 3}}, // k_2_10_10_10_AS_16_16_16_16 {DXGI_FORMAT_R10G10B10A2_UNORM, DXGI_FORMAT_R10G10B10A2_UNORM, LoadMode::k32bpb, DXGI_FORMAT_UNKNOWN, LoadMode::kUnknown, false, DXGI_FORMAT_UNKNOWN, LoadMode::kUnknown, {0, 1, 2, 3}}, // k_10_11_11_AS_16_16_16_16 {DXGI_FORMAT_R16G16B16A16_TYPELESS, DXGI_FORMAT_R16G16B16A16_UNORM, LoadMode::kR11G11B10ToRGBA16, DXGI_FORMAT_R16G16B16A16_SNORM, LoadMode::kR11G11B10ToRGBA16SNorm, false, DXGI_FORMAT_UNKNOWN, LoadMode::kUnknown, {0, 1, 2, 2}}, // k_11_11_10_AS_16_16_16_16 {DXGI_FORMAT_R16G16B16A16_TYPELESS, DXGI_FORMAT_R16G16B16A16_UNORM, LoadMode::kR10G11B11ToRGBA16, DXGI_FORMAT_R16G16B16A16_SNORM, LoadMode::kR10G11B11ToRGBA16SNorm, false, DXGI_FORMAT_UNKNOWN, LoadMode::kUnknown, {0, 1, 2, 2}}, // k_32_32_32_FLOAT {DXGI_FORMAT_UNKNOWN, DXGI_FORMAT_UNKNOWN, LoadMode::kUnknown, DXGI_FORMAT_UNKNOWN, LoadMode::kUnknown, false, DXGI_FORMAT_UNKNOWN, LoadMode::kUnknown, {0, 1, 2, 2}}, // k_DXT3A // R8_UNORM has the same size as BC2, but doesn't have the 4x4 size // alignment requirement. {DXGI_FORMAT_R8_UNORM, DXGI_FORMAT_R8_UNORM, LoadMode::kDXT3A, DXGI_FORMAT_UNKNOWN, LoadMode::kUnknown, false, DXGI_FORMAT_UNKNOWN, LoadMode::kUnknown, {0, 0, 0, 0}}, // k_DXT5A {DXGI_FORMAT_BC4_UNORM, DXGI_FORMAT_BC4_UNORM, LoadMode::k64bpb, DXGI_FORMAT_UNKNOWN, LoadMode::kUnknown, true, DXGI_FORMAT_R8_UNORM, LoadMode::kDXT5AToR8, {0, 0, 0, 0}}, // k_CTX1 {DXGI_FORMAT_R8G8_UNORM, DXGI_FORMAT_R8G8_UNORM, LoadMode::kCTX1, DXGI_FORMAT_UNKNOWN, LoadMode::kUnknown, false, DXGI_FORMAT_UNKNOWN, LoadMode::kUnknown, {0, 1, 1, 1}}, // k_DXT3A_AS_1_1_1_1 {DXGI_FORMAT_B4G4R4A4_UNORM, DXGI_FORMAT_B4G4R4A4_UNORM, LoadMode::kDXT3AAs1111, DXGI_FORMAT_UNKNOWN, LoadMode::kUnknown, false, DXGI_FORMAT_UNKNOWN, LoadMode::kUnknown, {0, 1, 2, 3}}, // k_8_8_8_8_GAMMA_EDRAM // Not usable as a texture. {DXGI_FORMAT_UNKNOWN, DXGI_FORMAT_UNKNOWN, LoadMode::kUnknown, DXGI_FORMAT_UNKNOWN, LoadMode::kUnknown, false, DXGI_FORMAT_UNKNOWN, LoadMode::kUnknown, {0, 1, 2, 3}}, // k_2_10_10_10_FLOAT_EDRAM // Not usable as a texture. {DXGI_FORMAT_UNKNOWN, DXGI_FORMAT_UNKNOWN, LoadMode::kUnknown, DXGI_FORMAT_UNKNOWN, LoadMode::kUnknown, false, DXGI_FORMAT_UNKNOWN, LoadMode::kUnknown, {0, 1, 2, 3}}, }; const char* const TextureCache::dimension_names_[4] = {"1D", "2D", "3D", "cube"}; const TextureCache::LoadModeInfo TextureCache::load_mode_info_[] = { {{{texture_load_8bpb_cs, sizeof(texture_load_8bpb_cs), 3, 4, 16}, {texture_load_8bpb_2x_cs, sizeof(texture_load_8bpb_2x_cs), 4, 4, 16 * 2}, {texture_load_8bpb_3x_cs, sizeof(texture_load_8bpb_3x_cs), 3, 3, 16 * 3}}}, {{{texture_load_16bpb_cs, sizeof(texture_load_16bpb_cs), 4, 4, 16}, {texture_load_16bpb_2x_cs, sizeof(texture_load_16bpb_2x_cs), 4, 4, 16 * 2}, {texture_load_16bpb_3x_cs, sizeof(texture_load_16bpb_3x_cs), 3, 3, 16 * 3}}}, {{{texture_load_32bpb_cs, sizeof(texture_load_32bpb_cs), 4, 4, 8}, {texture_load_32bpb_2x_cs, sizeof(texture_load_32bpb_2x_cs), 4, 4, 8 * 2}, {texture_load_32bpb_3x_cs, sizeof(texture_load_32bpb_3x_cs), 3, 3, 2 * 3}}}, {{{texture_load_64bpb_cs, sizeof(texture_load_64bpb_cs), 4, 4, 4}, {texture_load_64bpb_2x_cs, sizeof(texture_load_64bpb_2x_cs), 4, 4, 4 * 2}, {texture_load_64bpb_3x_cs, sizeof(texture_load_64bpb_3x_cs), 3, 3, 4 * 3}}}, {{{texture_load_128bpb_cs, sizeof(texture_load_128bpb_cs), 4, 4, 2}, {texture_load_128bpb_2x_cs, sizeof(texture_load_128bpb_2x_cs), 4, 4, 2 * 2}, {texture_load_128bpb_3x_cs, sizeof(texture_load_128bpb_3x_cs), 4, 4, 2 * 3}}}, {{{texture_load_r5g5b5a1_b5g5r5a1_cs, sizeof(texture_load_r5g5b5a1_b5g5r5a1_cs), 4, 4, 16}, {texture_load_r5g5b5a1_b5g5r5a1_2x_cs, sizeof(texture_load_r5g5b5a1_b5g5r5a1_2x_cs), 4, 4, 16 * 2}, {texture_load_r5g5b5a1_b5g5r5a1_3x_cs, sizeof(texture_load_r5g5b5a1_b5g5r5a1_3x_cs), 3, 3, 16 * 3}}}, {{{texture_load_r5g6b5_b5g6r5_cs, sizeof(texture_load_r5g6b5_b5g6r5_cs), 4, 4, 16}, {texture_load_r5g6b5_b5g6r5_2x_cs, sizeof(texture_load_r5g6b5_b5g6r5_2x_cs), 4, 4, 16 * 2}, {texture_load_r5g6b5_b5g6r5_3x_cs, sizeof(texture_load_r5g6b5_b5g6r5_3x_cs), 3, 3, 16 * 3}}}, {{{texture_load_r5g5b6_b5g6r5_swizzle_rbga_cs, sizeof(texture_load_r5g5b6_b5g6r5_swizzle_rbga_cs), 4, 4, 16}, {texture_load_r5g5b6_b5g6r5_swizzle_rbga_2x_cs, sizeof(texture_load_r5g5b6_b5g6r5_swizzle_rbga_2x_cs), 4, 4, 16 * 2}, {texture_load_r5g5b6_b5g6r5_swizzle_rbga_3x_cs, sizeof(texture_load_r5g5b6_b5g6r5_swizzle_rbga_3x_cs), 3, 3, 16 * 3}}}, {{{texture_load_r4g4b4a4_b4g4r4a4_cs, sizeof(texture_load_r4g4b4a4_b4g4r4a4_cs), 4, 4, 16}, {texture_load_r4g4b4a4_b4g4r4a4_2x_cs, sizeof(texture_load_r4g4b4a4_b4g4r4a4_2x_cs), 4, 4, 16 * 2}, {texture_load_r4g4b4a4_b4g4r4a4_3x_cs, sizeof(texture_load_r4g4b4a4_b4g4r4a4_3x_cs), 3, 3, 16 * 3}}}, {{{texture_load_r10g11b11_rgba16_cs, sizeof(texture_load_r10g11b11_rgba16_cs), 4, 4, 8}, {texture_load_r10g11b11_rgba16_2x_cs, sizeof(texture_load_r10g11b11_rgba16_2x_cs), 4, 4, 8 * 2}, {texture_load_r10g11b11_rgba16_3x_cs, sizeof(texture_load_r10g11b11_rgba16_3x_cs), 3, 3, 2 * 3}}}, {{{texture_load_r10g11b11_rgba16_snorm_cs, sizeof(texture_load_r10g11b11_rgba16_snorm_cs), 4, 4, 8}, {texture_load_r10g11b11_rgba16_snorm_2x_cs, sizeof(texture_load_r10g11b11_rgba16_snorm_2x_cs), 4, 4, 8 * 2}, {texture_load_r10g11b11_rgba16_snorm_3x_cs, sizeof(texture_load_r10g11b11_rgba16_snorm_3x_cs), 3, 3, 2 * 3}}}, {{{texture_load_r11g11b10_rgba16_cs, sizeof(texture_load_r11g11b10_rgba16_cs), 4, 4, 8}, {texture_load_r11g11b10_rgba16_2x_cs, sizeof(texture_load_r11g11b10_rgba16_2x_cs), 4, 4, 8 * 2}, {texture_load_r11g11b10_rgba16_3x_cs, sizeof(texture_load_r11g11b10_rgba16_3x_cs), 3, 3, 2 * 3}}}, {{{texture_load_r11g11b10_rgba16_snorm_cs, sizeof(texture_load_r11g11b10_rgba16_snorm_cs), 4, 4, 8}, {texture_load_r11g11b10_rgba16_snorm_2x_cs, sizeof(texture_load_r11g11b10_rgba16_snorm_2x_cs), 4, 4, 8 * 2}, {texture_load_r11g11b10_rgba16_snorm_3x_cs, sizeof(texture_load_r11g11b10_rgba16_snorm_3x_cs), 3, 3, 2 * 3}}}, {{{texture_load_dxt1_rgba8_cs, sizeof(texture_load_dxt1_rgba8_cs), 4, 4, 4}, {}, {}}}, {{{texture_load_dxt3_rgba8_cs, sizeof(texture_load_dxt3_rgba8_cs), 4, 4, 2}, {}, {}}}, {{{texture_load_dxt5_rgba8_cs, sizeof(texture_load_dxt5_rgba8_cs), 4, 4, 2}, {}, {}}}, {{{texture_load_dxn_rg8_cs, sizeof(texture_load_dxn_rg8_cs), 4, 4, 2}, {}, {}}}, {{{texture_load_dxt3a_cs, sizeof(texture_load_dxt3a_cs), 4, 4, 4}, {}, {}}}, {{{texture_load_dxt3aas1111_cs, sizeof(texture_load_dxt3aas1111_cs), 4, 4, 4}, {}, {}}}, {{{texture_load_dxt5a_r8_cs, sizeof(texture_load_dxt5a_r8_cs), 4, 4, 4}, {}, {}}}, {{{texture_load_ctx1_cs, sizeof(texture_load_ctx1_cs), 4, 4, 4}, {}, {}}}, {{{texture_load_depth_unorm_cs, sizeof(texture_load_depth_unorm_cs), 4, 4, 8}, {texture_load_depth_unorm_2x_cs, sizeof(texture_load_depth_unorm_2x_cs), 4, 4, 8 * 2}, {texture_load_depth_unorm_3x_cs, sizeof(texture_load_depth_unorm_3x_cs), 3, 3, 2 * 3}}}, {{{texture_load_depth_float_cs, sizeof(texture_load_depth_float_cs), 4, 4, 8}, {texture_load_depth_float_2x_cs, sizeof(texture_load_depth_float_2x_cs), 4, 4, 8 * 2}, {texture_load_depth_float_3x_cs, sizeof(texture_load_depth_float_3x_cs), 3, 3, 2 * 3}}}, }; TextureCache::TextureCache(D3D12CommandProcessor& command_processor, const RegisterFile& register_file, D3D12SharedMemory& shared_memory, bool bindless_resources_used, uint32_t draw_resolution_scale) : command_processor_(command_processor), register_file_(register_file), shared_memory_(shared_memory), bindless_resources_used_(bindless_resources_used), draw_resolution_scale_(draw_resolution_scale) { assert_true(draw_resolution_scale >= 1); assert_true(draw_resolution_scale <= 3); } TextureCache::~TextureCache() { Shutdown(); } bool TextureCache::Initialize() { auto& provider = command_processor_.GetD3D12Context().GetD3D12Provider(); auto device = provider.GetDevice(); if (draw_resolution_scale_ > 1) { assert_true(draw_resolution_scale_ <= GetMaxDrawResolutionScale(provider)); // Buffers not used yet - no need aliasing barriers to change ownership of // gigabytes between even and odd buffers. std::memset(scaled_resolve_1gb_buffer_indices_, UINT8_MAX, sizeof(scaled_resolve_1gb_buffer_indices_)); assert_true(scaled_resolve_heaps_.empty()); uint64_t scaled_resolve_address_space_size = uint64_t(SharedMemory::kBufferSize) * (draw_resolution_scale_ * draw_resolution_scale_); scaled_resolve_heaps_.resize(size_t(scaled_resolve_address_space_size >> kScaledResolveHeapSizeLog2)); constexpr uint32_t kScaledResolvePageDwordCount = SharedMemory::kBufferSize / 4096 / 32; scaled_resolve_pages_ = new uint32_t[kScaledResolvePageDwordCount]; std::memset(scaled_resolve_pages_, 0, kScaledResolvePageDwordCount * sizeof(uint32_t)); std::memset(scaled_resolve_pages_l2_, 0, sizeof(scaled_resolve_pages_l2_)); } scaled_resolve_heap_count_ = 0; // Create the loading root signature. D3D12_ROOT_PARAMETER root_parameters[3]; // Parameter 0 is constants (changed multiple times when untiling). root_parameters[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_CBV; root_parameters[0].Descriptor.ShaderRegister = 0; root_parameters[0].Descriptor.RegisterSpace = 0; root_parameters[0].ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL; // Parameter 1 is the source (may be changed multiple times for the same // destination). D3D12_DESCRIPTOR_RANGE root_dest_range; root_dest_range.RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_SRV; root_dest_range.NumDescriptors = 1; root_dest_range.BaseShaderRegister = 0; root_dest_range.RegisterSpace = 0; root_dest_range.OffsetInDescriptorsFromTableStart = 0; root_parameters[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; root_parameters[1].DescriptorTable.NumDescriptorRanges = 1; root_parameters[1].DescriptorTable.pDescriptorRanges = &root_dest_range; root_parameters[1].ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL; // Parameter 2 is the destination. D3D12_DESCRIPTOR_RANGE root_source_range; root_source_range.RangeType = D3D12_DESCRIPTOR_RANGE_TYPE_UAV; root_source_range.NumDescriptors = 1; root_source_range.BaseShaderRegister = 0; root_source_range.RegisterSpace = 0; root_source_range.OffsetInDescriptorsFromTableStart = 0; root_parameters[2].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; root_parameters[2].DescriptorTable.NumDescriptorRanges = 1; root_parameters[2].DescriptorTable.pDescriptorRanges = &root_source_range; root_parameters[2].ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL; D3D12_ROOT_SIGNATURE_DESC root_signature_desc; root_signature_desc.NumParameters = UINT(xe::countof(root_parameters)); root_signature_desc.pParameters = root_parameters; root_signature_desc.NumStaticSamplers = 0; root_signature_desc.pStaticSamplers = nullptr; root_signature_desc.Flags = D3D12_ROOT_SIGNATURE_FLAG_NONE; load_root_signature_ = ui::d3d12::util::CreateRootSignature(provider, root_signature_desc); if (load_root_signature_ == nullptr) { XELOGE( "D3D12TextureCache: Failed to create the texture loading root " "signature"); Shutdown(); return false; } // Create the loading pipelines. for (uint32_t i = 0; i < uint32_t(LoadMode::kCount); ++i) { const LoadModeInfo& mode_info = load_mode_info_[i]; load_pipelines_[i] = ui::d3d12::util::CreateComputePipeline( device, mode_info.shaders[0].shader, mode_info.shaders[0].shader_size, load_root_signature_); if (load_pipelines_[i] == nullptr) { XELOGE( "D3D12TextureCache: Failed to create the texture loading pipeline " "for mode {}", i); Shutdown(); return false; } if (draw_resolution_scale_ > 1) { const LoadShaderInfo& scaled_load_shader_info = mode_info.shaders[draw_resolution_scale_ - 1]; if (scaled_load_shader_info.shader) { load_pipelines_scaled_[i] = ui::d3d12::util::CreateComputePipeline( device, scaled_load_shader_info.shader, scaled_load_shader_info.shader_size, load_root_signature_); if (load_pipelines_scaled_[i] == nullptr) { XELOGE( "D3D12TextureCache: Failed to create the resolution-scaled " "texture loading pipeline for mode {}", i); Shutdown(); return false; } } } } srv_descriptor_cache_allocated_ = 0; // Create a heap with null SRV descriptors, since it's faster to copy a // descriptor than to create an SRV, and null descriptors are used a lot (for // the signed version when only unsigned is used, for instance). D3D12_DESCRIPTOR_HEAP_DESC null_srv_descriptor_heap_desc; null_srv_descriptor_heap_desc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV; null_srv_descriptor_heap_desc.NumDescriptors = uint32_t(NullSRVDescriptorIndex::kCount); null_srv_descriptor_heap_desc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_NONE; null_srv_descriptor_heap_desc.NodeMask = 0; if (FAILED(device->CreateDescriptorHeap( &null_srv_descriptor_heap_desc, IID_PPV_ARGS(&null_srv_descriptor_heap_)))) { XELOGE( "D3D12TextureCache: Failed to create the descriptor heap for null " "SRVs"); Shutdown(); return false; } null_srv_descriptor_heap_start_ = null_srv_descriptor_heap_->GetCPUDescriptorHandleForHeapStart(); D3D12_SHADER_RESOURCE_VIEW_DESC null_srv_desc; null_srv_desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; null_srv_desc.Shader4ComponentMapping = D3D12_ENCODE_SHADER_4_COMPONENT_MAPPING( D3D12_SHADER_COMPONENT_MAPPING_FORCE_VALUE_0, D3D12_SHADER_COMPONENT_MAPPING_FORCE_VALUE_0, D3D12_SHADER_COMPONENT_MAPPING_FORCE_VALUE_0, D3D12_SHADER_COMPONENT_MAPPING_FORCE_VALUE_0); null_srv_desc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2DARRAY; null_srv_desc.Texture2DArray.MostDetailedMip = 0; null_srv_desc.Texture2DArray.MipLevels = 1; null_srv_desc.Texture2DArray.FirstArraySlice = 0; null_srv_desc.Texture2DArray.ArraySize = 1; null_srv_desc.Texture2DArray.PlaneSlice = 0; null_srv_desc.Texture2DArray.ResourceMinLODClamp = 0.0f; device->CreateShaderResourceView( nullptr, &null_srv_desc, provider.OffsetViewDescriptor( null_srv_descriptor_heap_start_, uint32_t(NullSRVDescriptorIndex::k2DArray))); null_srv_desc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE3D; null_srv_desc.Texture3D.MostDetailedMip = 0; null_srv_desc.Texture3D.MipLevels = 1; null_srv_desc.Texture3D.ResourceMinLODClamp = 0.0f; device->CreateShaderResourceView( nullptr, &null_srv_desc, provider.OffsetViewDescriptor(null_srv_descriptor_heap_start_, uint32_t(NullSRVDescriptorIndex::k3D))); null_srv_desc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURECUBE; null_srv_desc.TextureCube.MostDetailedMip = 0; null_srv_desc.TextureCube.MipLevels = 1; null_srv_desc.TextureCube.ResourceMinLODClamp = 0.0f; device->CreateShaderResourceView( nullptr, &null_srv_desc, provider.OffsetViewDescriptor(null_srv_descriptor_heap_start_, uint32_t(NullSRVDescriptorIndex::kCube))); if (draw_resolution_scale_ > 1) { scaled_resolve_global_watch_handle_ = shared_memory_.RegisterGlobalWatch( ScaledResolveGlobalWatchCallbackThunk, this); } texture_current_usage_time_ = xe::Clock::QueryHostUptimeMillis(); return true; } void TextureCache::Shutdown() { ClearCache(); if (scaled_resolve_global_watch_handle_ != nullptr) { shared_memory_.UnregisterGlobalWatch(scaled_resolve_global_watch_handle_); scaled_resolve_global_watch_handle_ = nullptr; } ui::d3d12::util::ReleaseAndNull(null_srv_descriptor_heap_); for (uint32_t i = 0; i < uint32_t(LoadMode::kCount); ++i) { ui::d3d12::util::ReleaseAndNull(load_pipelines_scaled_[i]); ui::d3d12::util::ReleaseAndNull(load_pipelines_[i]); } ui::d3d12::util::ReleaseAndNull(load_root_signature_); if (scaled_resolve_pages_ != nullptr) { delete[] scaled_resolve_pages_; scaled_resolve_pages_ = nullptr; } // First free the buffers to detach them from the heaps. for (size_t i = 0; i < xe::countof(scaled_resolve_2gb_buffers_); ++i) { ScaledResolveVirtualBuffer*& scaled_resolve_buffer = scaled_resolve_2gb_buffers_[i]; if (scaled_resolve_buffer) { delete scaled_resolve_buffer; scaled_resolve_buffer = nullptr; } } for (ID3D12Heap* scaled_resolve_heap : scaled_resolve_heaps_) { if (scaled_resolve_heap) { scaled_resolve_heap->Release(); } } scaled_resolve_heaps_.clear(); scaled_resolve_heap_count_ = 0; COUNT_profile_set("gpu/texture_cache/scaled_resolve_buffer_used_mb", 0); } void TextureCache::ClearCache() { // Destroy all the textures. for (auto texture_pair : textures_) { Texture* texture = texture_pair.second; shared_memory_.UnwatchMemoryRange(texture->base_watch_handle); shared_memory_.UnwatchMemoryRange(texture->mip_watch_handle); // Bindful descriptor cache will be cleared entirely now, so only release // bindless descriptors. if (bindless_resources_used_) { for (auto descriptor_pair : texture->srv_descriptors) { command_processor_.ReleaseViewBindlessDescriptorImmediately( descriptor_pair.second); } } texture->resource->Release(); delete texture; } textures_.clear(); COUNT_profile_set("gpu/texture_cache/textures", 0); textures_total_size_ = 0; COUNT_profile_set("gpu/texture_cache/total_size_mb", 0); texture_used_first_ = texture_used_last_ = nullptr; // Clear texture descriptor cache. srv_descriptor_cache_free_.clear(); srv_descriptor_cache_allocated_ = 0; for (auto& page : srv_descriptor_cache_) { page.heap->Release(); } srv_descriptor_cache_.clear(); } void TextureCache::TextureFetchConstantWritten(uint32_t index) { texture_bindings_in_sync_ &= ~(1u << index); } void TextureCache::BeginSubmission() { // ExecuteCommandLists is a full UAV and aliasing barrier. if (draw_resolution_scale_ > 1) { size_t scaled_resolve_buffer_count = GetScaledResolveBufferCount(); for (size_t i = 0; i < scaled_resolve_buffer_count; ++i) { ScaledResolveVirtualBuffer* scaled_resolve_buffer = scaled_resolve_2gb_buffers_[i]; if (scaled_resolve_buffer) { scaled_resolve_buffer->ClearUAVBarrierPending(); } } std::memset(scaled_resolve_1gb_buffer_indices_, UINT8_MAX, sizeof(scaled_resolve_1gb_buffer_indices_)); } } void TextureCache::BeginFrame() { // In case there was a failure creating something in the previous frame, make // sure bindings are reset so a new attempt will surely be made if the texture // is requested again. ClearBindings(); std::memset(unsupported_format_features_used_, 0, sizeof(unsupported_format_features_used_)); texture_current_usage_time_ = xe::Clock::QueryHostUptimeMillis(); // If memory usage is too high, destroy unused textures. uint64_t completed_frame = command_processor_.GetCompletedFrame(); // texture_cache_memory_limit_render_to_texture is assumed to be included in // texture_cache_memory_limit_soft and texture_cache_memory_limit_hard, at 1x, // so subtracting 1 from the scale. uint32_t limit_scaled_resolve_add_mb = cvars::texture_cache_memory_limit_render_to_texture * (draw_resolution_scale_ * draw_resolution_scale_ - 1); uint32_t limit_soft_mb = cvars::texture_cache_memory_limit_soft + limit_scaled_resolve_add_mb; uint32_t limit_hard_mb = cvars::texture_cache_memory_limit_hard + limit_scaled_resolve_add_mb; uint32_t limit_soft_lifetime = cvars::texture_cache_memory_limit_soft_lifetime * 1000; bool destroyed_any = false; while (texture_used_first_ != nullptr) { uint64_t total_size_mb = textures_total_size_ >> 20; bool limit_hard_exceeded = total_size_mb >= limit_hard_mb; if (total_size_mb < limit_soft_mb && !limit_hard_exceeded) { break; } Texture* texture = texture_used_first_; if (texture->last_usage_frame > completed_frame) { break; } if (!limit_hard_exceeded && (texture->last_usage_time + limit_soft_lifetime) > texture_current_usage_time_) { break; } destroyed_any = true; // Remove the texture from the map. auto found_texture_it = textures_.find(texture->key); assert_true(found_texture_it != textures_.end()); if (found_texture_it != textures_.end()) { assert_true(found_texture_it->second == texture); textures_.erase(found_texture_it); } // Unlink the texture. texture_used_first_ = texture->used_next; if (texture_used_first_ != nullptr) { texture_used_first_->used_previous = nullptr; } else { texture_used_last_ = nullptr; } // Exclude the texture from the memory usage counter. textures_total_size_ -= texture->resource_size; // Destroy the texture. shared_memory_.UnwatchMemoryRange(texture->base_watch_handle); shared_memory_.UnwatchMemoryRange(texture->mip_watch_handle); if (bindless_resources_used_) { for (auto descriptor_pair : texture->srv_descriptors) { command_processor_.ReleaseViewBindlessDescriptorImmediately( descriptor_pair.second); } } else { for (auto descriptor_pair : texture->srv_descriptors) { srv_descriptor_cache_free_.push_back(descriptor_pair.second); } } texture->resource->Release(); delete texture; } if (destroyed_any) { COUNT_profile_set("gpu/texture_cache/textures", textures_.size()); COUNT_profile_set("gpu/texture_cache/total_size_mb", uint32_t(textures_total_size_ >> 20)); } } void TextureCache::EndFrame() { // Report used unsupported texture formats. bool unsupported_header_written = false; for (uint32_t i = 0; i < 64; ++i) { uint32_t unsupported_features = unsupported_format_features_used_[i]; if (unsupported_features == 0) { continue; } if (!unsupported_header_written) { XELOGE("Unsupported texture formats used in the frame:"); unsupported_header_written = true; } XELOGE("* {}{}{}{}", FormatInfo::Get(xenos::TextureFormat(i))->name, unsupported_features & kUnsupportedResourceBit ? " resource" : "", unsupported_features & kUnsupportedUnormBit ? " unorm" : "", unsupported_features & kUnsupportedSnormBit ? " snorm" : ""); unsupported_format_features_used_[i] = 0; } } void TextureCache::RequestTextures(uint32_t used_texture_mask) { const auto& regs = register_file_; #if XE_UI_D3D12_FINE_GRAINED_DRAW_SCOPES SCOPE_profile_cpu_f("gpu"); #endif // XE_UI_D3D12_FINE_GRAINED_DRAW_SCOPES if (texture_invalidated_.exchange(false, std::memory_order_acquire)) { // Clear the bindings not only for this draw call, but entirely, because // loading may be needed in some draw call later, which may have the same // key for some binding as before the invalidation, but texture_invalidated_ // being false (menu background in Halo 3). for (size_t i = 0; i < xe::countof(texture_bindings_); ++i) { texture_bindings_[i].Clear(); } texture_bindings_in_sync_ = 0; } // Update the texture keys and the textures. uint32_t textures_remaining = used_texture_mask; uint32_t index = 0; while (xe::bit_scan_forward(textures_remaining, &index)) { uint32_t index_bit = uint32_t(1) << index; textures_remaining &= ~index_bit; if (texture_bindings_in_sync_ & index_bit) { continue; } TextureBinding& binding = texture_bindings_[index]; const auto& fetch = regs.Get<xenos::xe_gpu_texture_fetch_t>( XE_GPU_REG_SHADER_CONSTANT_FETCH_00_0 + index * 6); TextureKey old_key = binding.key; uint8_t old_swizzled_signs = binding.swizzled_signs; BindingInfoFromFetchConstant(fetch, binding.key, &binding.host_swizzle, &binding.swizzled_signs); texture_bindings_in_sync_ |= index_bit; if (binding.key.IsInvalid()) { binding.texture = nullptr; binding.texture_signed = nullptr; binding.descriptor_index = UINT32_MAX; binding.descriptor_index_signed = UINT32_MAX; continue; } // Check if need to load the unsigned and the signed versions of the texture // (if the format is emulated with different host bit representations for // signed and unsigned - otherwise only the unsigned one is loaded). bool key_changed = binding.key != old_key; bool load_unsigned_data = false, load_signed_data = false; if (IsSignedVersionSeparate(binding.key.format)) { // Can reuse previously loaded unsigned/signed versions if the key is the // same and the texture was previously bound as unsigned/signed // respectively (checking the previous values of signedness rather than // binding.texture != nullptr and binding.texture_signed != nullptr also // prevents repeated attempts to load the texture if it has failed to // load). if (texture_util::IsAnySignNotSigned(binding.swizzled_signs)) { if (key_changed || !texture_util::IsAnySignNotSigned(old_swizzled_signs)) { binding.texture = FindOrCreateTexture(binding.key); binding.descriptor_index = binding.texture ? FindOrCreateTextureDescriptor(*binding.texture, false, binding.host_swizzle) : UINT32_MAX; load_unsigned_data = true; } } else { binding.texture = nullptr; binding.descriptor_index = UINT32_MAX; } if (texture_util::IsAnySignSigned(binding.swizzled_signs)) { if (key_changed || !texture_util::IsAnySignSigned(old_swizzled_signs)) { TextureKey signed_key = binding.key; signed_key.signed_separate = 1; binding.texture_signed = FindOrCreateTexture(signed_key); binding.descriptor_index_signed = binding.texture_signed ? FindOrCreateTextureDescriptor(*binding.texture_signed, true, binding.host_swizzle) : UINT32_MAX; load_signed_data = true; } } else { binding.texture_signed = nullptr; binding.descriptor_index_signed = UINT32_MAX; } } else { // Same resource for both unsigned and signed, but descriptor formats may // be different. if (key_changed) { binding.texture = FindOrCreateTexture(binding.key); load_unsigned_data = true; } binding.texture_signed = nullptr; if (texture_util::IsAnySignNotSigned(binding.swizzled_signs)) { if (key_changed || !texture_util::IsAnySignNotSigned(old_swizzled_signs)) { binding.descriptor_index = binding.texture ? FindOrCreateTextureDescriptor(*binding.texture, false, binding.host_swizzle) : UINT32_MAX; } } else { binding.descriptor_index = UINT32_MAX; } if (texture_util::IsAnySignSigned(binding.swizzled_signs)) { if (key_changed || !texture_util::IsAnySignSigned(old_swizzled_signs)) { binding.descriptor_index_signed = binding.texture ? FindOrCreateTextureDescriptor(*binding.texture, true, binding.host_swizzle) : UINT32_MAX; } } else { binding.descriptor_index_signed = UINT32_MAX; } } if (load_unsigned_data && binding.texture != nullptr) { LoadTextureData(binding.texture); } if (load_signed_data && binding.texture_signed != nullptr) { LoadTextureData(binding.texture_signed); } } // Transition the textures to the needed usage - always in // NON_PIXEL_SHADER_RESOURCE | PIXEL_SHADER_RESOURCE states because barriers // between read-only stages, if needed, are discouraged (also if these were // tracked separately, checks would be needed to make sure, if the same // texture is bound through different fetch constants to both VS and PS, it // would be in both states). textures_remaining = used_texture_mask; while (xe::bit_scan_forward(textures_remaining, &index)) { textures_remaining &= ~(uint32_t(1) << index); TextureBinding& binding = texture_bindings_[index]; if (binding.texture != nullptr) { // Will be referenced by the command list, so mark as used. MarkTextureUsed(binding.texture); command_processor_.PushTransitionBarrier( binding.texture->resource, binding.texture->state, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE | D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE); binding.texture->state = D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE | D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE; } if (binding.texture_signed != nullptr) { MarkTextureUsed(binding.texture_signed); command_processor_.PushTransitionBarrier( binding.texture_signed->resource, binding.texture_signed->state, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE | D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE); binding.texture_signed->state = D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE | D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE; } } } bool TextureCache::AreActiveTextureSRVKeysUpToDate( const TextureSRVKey* keys, const D3D12Shader::TextureBinding* host_shader_bindings, size_t host_shader_binding_count) const { for (size_t i = 0; i < host_shader_binding_count; ++i) { const TextureSRVKey& key = keys[i]; const TextureBinding& binding = texture_bindings_[host_shader_bindings[i].fetch_constant]; if (key.key != binding.key || key.host_swizzle != binding.host_swizzle || key.swizzled_signs != binding.swizzled_signs) { return false; } } return true; } void TextureCache::WriteActiveTextureSRVKeys( TextureSRVKey* keys, const D3D12Shader::TextureBinding* host_shader_bindings, size_t host_shader_binding_count) const { for (size_t i = 0; i < host_shader_binding_count; ++i) { TextureSRVKey& key = keys[i]; const TextureBinding& binding = texture_bindings_[host_shader_bindings[i].fetch_constant]; key.key = binding.key; key.host_swizzle = binding.host_swizzle; key.swizzled_signs = binding.swizzled_signs; } } void TextureCache::WriteActiveTextureBindfulSRV( const D3D12Shader::TextureBinding& host_shader_binding, D3D12_CPU_DESCRIPTOR_HANDLE handle) { assert_false(bindless_resources_used_); const TextureBinding& binding = texture_bindings_[host_shader_binding.fetch_constant]; uint32_t descriptor_index = UINT32_MAX; Texture* texture = nullptr; if (!binding.key.IsInvalid() && AreDimensionsCompatible(host_shader_binding.dimension, binding.key.dimension)) { if (host_shader_binding.is_signed) { // Not supporting signed compressed textures - hopefully DXN and DXT5A are // not used as signed. if (texture_util::IsAnySignSigned(binding.swizzled_signs)) { descriptor_index = binding.descriptor_index_signed; texture = IsSignedVersionSeparate(binding.key.format) ? binding.texture_signed : binding.texture; } } else { if (texture_util::IsAnySignNotSigned(binding.swizzled_signs)) { descriptor_index = binding.descriptor_index; texture = binding.texture; } } } auto& provider = command_processor_.GetD3D12Context().GetD3D12Provider(); D3D12_CPU_DESCRIPTOR_HANDLE source_handle; if (descriptor_index != UINT32_MAX) { assert_not_null(texture); MarkTextureUsed(texture); source_handle = GetTextureDescriptorCPUHandle(descriptor_index); } else { NullSRVDescriptorIndex null_descriptor_index; switch (host_shader_binding.dimension) { case xenos::FetchOpDimension::k3DOrStacked: null_descriptor_index = NullSRVDescriptorIndex::k3D; break; case xenos::FetchOpDimension::kCube: null_descriptor_index = NullSRVDescriptorIndex::kCube; break; default: assert_true( host_shader_binding.dimension == xenos::FetchOpDimension::k1D || host_shader_binding.dimension == xenos::FetchOpDimension::k2D); null_descriptor_index = NullSRVDescriptorIndex::k2DArray; } source_handle = provider.OffsetViewDescriptor( null_srv_descriptor_heap_start_, uint32_t(null_descriptor_index)); } auto device = provider.GetDevice(); { #if XE_UI_D3D12_FINE_GRAINED_DRAW_SCOPES SCOPE_profile_cpu_i( "gpu", "xe::gpu::d3d12::TextureCache::WriteActiveTextureBindfulSRV->" "CopyDescriptorsSimple"); #endif // XE_UI_D3D12_FINE_GRAINED_DRAW_SCOPES device->CopyDescriptorsSimple(1, handle, source_handle, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); } } uint32_t TextureCache::GetActiveTextureBindlessSRVIndex( const D3D12Shader::TextureBinding& host_shader_binding) { assert_true(bindless_resources_used_); uint32_t descriptor_index = UINT32_MAX; const TextureBinding& binding = texture_bindings_[host_shader_binding.fetch_constant]; if (!binding.key.IsInvalid() && AreDimensionsCompatible(host_shader_binding.dimension, binding.key.dimension)) { descriptor_index = host_shader_binding.is_signed ? binding.descriptor_index_signed : binding.descriptor_index; } if (descriptor_index == UINT32_MAX) { switch (host_shader_binding.dimension) { case xenos::FetchOpDimension::k3DOrStacked: descriptor_index = uint32_t(D3D12CommandProcessor::SystemBindlessView::kNullTexture3D); break; case xenos::FetchOpDimension::kCube: descriptor_index = uint32_t( D3D12CommandProcessor::SystemBindlessView::kNullTextureCube); break; default: assert_true( host_shader_binding.dimension == xenos::FetchOpDimension::k1D || host_shader_binding.dimension == xenos::FetchOpDimension::k2D); descriptor_index = uint32_t( D3D12CommandProcessor::SystemBindlessView::kNullTexture2DArray); } } return descriptor_index; } TextureCache::SamplerParameters TextureCache::GetSamplerParameters( const D3D12Shader::SamplerBinding& binding) const { const auto& regs = register_file_; const auto& fetch = regs.Get<xenos::xe_gpu_texture_fetch_t>( XE_GPU_REG_SHADER_CONSTANT_FETCH_00_0 + binding.fetch_constant * 6); SamplerParameters parameters; parameters.clamp_x = fetch.clamp_x; parameters.clamp_y = fetch.clamp_y; parameters.clamp_z = fetch.clamp_z; parameters.border_color = fetch.border_color; uint32_t mip_min_level; texture_util::GetSubresourcesFromFetchConstant( fetch, nullptr, nullptr, nullptr, nullptr, nullptr, &mip_min_level, nullptr, binding.mip_filter); parameters.mip_min_level = mip_min_level; xenos::AnisoFilter aniso_filter = binding.aniso_filter == xenos::AnisoFilter::kUseFetchConst ? fetch.aniso_filter : binding.aniso_filter; aniso_filter = std::min(aniso_filter, xenos::AnisoFilter::kMax_16_1); parameters.aniso_filter = aniso_filter; if (aniso_filter != xenos::AnisoFilter::kDisabled) { parameters.mag_linear = 1; parameters.min_linear = 1; parameters.mip_linear = 1; } else { xenos::TextureFilter mag_filter = binding.mag_filter == xenos::TextureFilter::kUseFetchConst ? fetch.mag_filter : binding.mag_filter; parameters.mag_linear = mag_filter == xenos::TextureFilter::kLinear; xenos::TextureFilter min_filter = binding.min_filter == xenos::TextureFilter::kUseFetchConst ? fetch.min_filter : binding.min_filter; parameters.min_linear = min_filter == xenos::TextureFilter::kLinear; xenos::TextureFilter mip_filter = binding.mip_filter == xenos::TextureFilter::kUseFetchConst ? fetch.mip_filter : binding.mip_filter; parameters.mip_linear = mip_filter == xenos::TextureFilter::kLinear; } return parameters; } void TextureCache::WriteSampler(SamplerParameters parameters, D3D12_CPU_DESCRIPTOR_HANDLE handle) const { D3D12_SAMPLER_DESC desc; if (parameters.aniso_filter != xenos::AnisoFilter::kDisabled) { desc.Filter = D3D12_FILTER_ANISOTROPIC; desc.MaxAnisotropy = 1u << (uint32_t(parameters.aniso_filter) - 1); } else { D3D12_FILTER_TYPE d3d_filter_min = parameters.min_linear ? D3D12_FILTER_TYPE_LINEAR : D3D12_FILTER_TYPE_POINT; D3D12_FILTER_TYPE d3d_filter_mag = parameters.mag_linear ? D3D12_FILTER_TYPE_LINEAR : D3D12_FILTER_TYPE_POINT; D3D12_FILTER_TYPE d3d_filter_mip = parameters.mip_linear ? D3D12_FILTER_TYPE_LINEAR : D3D12_FILTER_TYPE_POINT; desc.Filter = D3D12_ENCODE_BASIC_FILTER( d3d_filter_min, d3d_filter_mag, d3d_filter_mip, D3D12_FILTER_REDUCTION_TYPE_STANDARD); desc.MaxAnisotropy = 1; } static const D3D12_TEXTURE_ADDRESS_MODE kAddressModeMap[] = { /* kRepeat */ D3D12_TEXTURE_ADDRESS_MODE_WRAP, /* kMirroredRepeat */ D3D12_TEXTURE_ADDRESS_MODE_MIRROR, /* kClampToEdge */ D3D12_TEXTURE_ADDRESS_MODE_CLAMP, /* kMirrorClampToEdge */ D3D12_TEXTURE_ADDRESS_MODE_MIRROR_ONCE, // No GL_CLAMP (clamp to half edge, half border) equivalent in Direct3D // 12, but there's no Direct3D 9 equivalent anyway, and too weird to be // suitable for intentional real usage. /* kClampToHalfway */ D3D12_TEXTURE_ADDRESS_MODE_CLAMP, // No mirror and clamp to border equivalents in Direct3D 12, but they // aren't there in Direct3D 9 either. /* kMirrorClampToHalfway */ D3D12_TEXTURE_ADDRESS_MODE_MIRROR_ONCE, /* kClampToBorder */ D3D12_TEXTURE_ADDRESS_MODE_BORDER, /* kMirrorClampToBorder */ D3D12_TEXTURE_ADDRESS_MODE_MIRROR_ONCE, }; desc.AddressU = kAddressModeMap[uint32_t(parameters.clamp_x)]; desc.AddressV = kAddressModeMap[uint32_t(parameters.clamp_y)]; desc.AddressW = kAddressModeMap[uint32_t(parameters.clamp_z)]; // LOD is calculated in shaders. desc.MipLODBias = 0.0f; desc.ComparisonFunc = D3D12_COMPARISON_FUNC_NEVER; // TODO(Triang3l): Border colors k_ACBYCR_BLACK and k_ACBCRY_BLACK. if (parameters.border_color == xenos::BorderColor::k_AGBR_White) { desc.BorderColor[0] = 1.0f; desc.BorderColor[1] = 1.0f; desc.BorderColor[2] = 1.0f; desc.BorderColor[3] = 1.0f; } else { desc.BorderColor[0] = 0.0f; desc.BorderColor[1] = 0.0f; desc.BorderColor[2] = 0.0f; desc.BorderColor[3] = 0.0f; } desc.MinLOD = float(parameters.mip_min_level); // Maximum mip level is in the texture resource itself. desc.MaxLOD = FLT_MAX; auto device = command_processor_.GetD3D12Context().GetD3D12Provider().GetDevice(); device->CreateSampler(&desc, handle); } void TextureCache::MarkRangeAsResolved(uint32_t start_unscaled, uint32_t length_unscaled) { if (length_unscaled == 0) { return; } start_unscaled &= 0x1FFFFFFF; length_unscaled = std::min(length_unscaled, 0x20000000 - start_unscaled); if (draw_resolution_scale_ > 1) { uint32_t page_first = start_unscaled >> 12; uint32_t page_last = (start_unscaled + length_unscaled - 1) >> 12; uint32_t block_first = page_first >> 5; uint32_t block_last = page_last >> 5; auto global_lock = global_critical_region_.Acquire(); for (uint32_t i = block_first; i <= block_last; ++i) { uint32_t add_bits = UINT32_MAX; if (i == block_first) { add_bits &= ~((1u << (page_first & 31)) - 1); } if (i == block_last && (page_last & 31) != 31) { add_bits &= (1u << ((page_last & 31) + 1)) - 1; } scaled_resolve_pages_[i] |= add_bits; scaled_resolve_pages_l2_[i >> 6] |= 1ull << (i & 63); } } // Invalidate textures. Toggling individual textures between scaled and // unscaled also relies on invalidation through shared memory. shared_memory_.RangeWrittenByGpu(start_unscaled, length_unscaled, true); } bool TextureCache::EnsureScaledResolveMemoryCommitted( uint32_t start_unscaled, uint32_t length_unscaled) { assert_true(draw_resolution_scale_ > 1); if (length_unscaled == 0) { return true; } if (start_unscaled > SharedMemory::kBufferSize || (SharedMemory::kBufferSize - start_unscaled) < length_unscaled) { // Exceeds the physical address space. return false; } uint32_t draw_resolution_scale_square = draw_resolution_scale_ * draw_resolution_scale_; uint64_t first_scaled = uint64_t(start_unscaled) * draw_resolution_scale_square; uint64_t last_scaled = uint64_t(start_unscaled + (length_unscaled - 1)) * draw_resolution_scale_square; auto& provider = command_processor_.GetD3D12Context().GetD3D12Provider(); auto device = provider.GetDevice(); // Ensure GPU virtual memory for buffers that may be used to access the range // is allocated - buffers are created. Always creating both buffers for all // addresses before creating the heaps so when creating a new buffer, it can // be safely assumed that no existing heaps should be mapped to it. std::array<size_t, 2> possible_buffers_first = GetPossibleScaledResolveBufferIndices(first_scaled); std::array<size_t, 2> possible_buffers_last = GetPossibleScaledResolveBufferIndices(last_scaled); size_t possible_buffer_first = std::min(possible_buffers_first[0], possible_buffers_first[1]); size_t possible_buffer_last = std::max(possible_buffers_last[0], possible_buffers_last[1]); for (size_t i = possible_buffer_first; i <= possible_buffer_last; ++i) { if (scaled_resolve_2gb_buffers_[i]) { continue; } D3D12_RESOURCE_DESC scaled_resolve_buffer_desc; // Buffer indices are gigabytes. ui::d3d12::util::FillBufferResourceDesc( scaled_resolve_buffer_desc, std::min(uint64_t(1) << 31, uint64_t(SharedMemory::kBufferSize) * draw_resolution_scale_square - (uint64_t(i) << 30)), D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS); // The first access will be a resolve. constexpr D3D12_RESOURCE_STATES kScaledResolveVirtualBufferInitialState = D3D12_RESOURCE_STATE_UNORDERED_ACCESS; ID3D12Resource* scaled_resolve_buffer_resource; if (FAILED(device->CreateReservedResource( &scaled_resolve_buffer_desc, kScaledResolveVirtualBufferInitialState, nullptr, IID_PPV_ARGS(&scaled_resolve_buffer_resource)))) { XELOGE( "D3D12TextureCache: Failed to create a 2 GB tiled buffer for draw " "resolution scaling"); return false; } scaled_resolve_2gb_buffers_[i] = new ScaledResolveVirtualBuffer(scaled_resolve_buffer_resource, kScaledResolveVirtualBufferInitialState); scaled_resolve_buffer_resource->Release(); } uint32_t heap_first = uint32_t(first_scaled >> kScaledResolveHeapSizeLog2); uint32_t heap_last = uint32_t(last_scaled >> kScaledResolveHeapSizeLog2); for (uint32_t i = heap_first; i <= heap_last; ++i) { if (scaled_resolve_heaps_[i] != nullptr) { continue; } auto direct_queue = provider.GetDirectQueue(); D3D12_HEAP_DESC heap_desc = {}; heap_desc.SizeInBytes = kScaledResolveHeapSize; heap_desc.Properties.Type = D3D12_HEAP_TYPE_DEFAULT; heap_desc.Flags = D3D12_HEAP_FLAG_ALLOW_ONLY_BUFFERS | provider.GetHeapFlagCreateNotZeroed(); ID3D12Heap* scaled_resolve_heap; if (FAILED(device->CreateHeap(&heap_desc, IID_PPV_ARGS(&scaled_resolve_heap)))) { XELOGE("Texture cache: Failed to create a scaled resolve tile heap"); return false; } scaled_resolve_heaps_[i] = scaled_resolve_heap; ++scaled_resolve_heap_count_; COUNT_profile_set( "gpu/texture_cache/scaled_resolve_buffer_used_mb", scaled_resolve_heap_count_ << (kScaledResolveHeapSizeLog2 - 20)); D3D12_TILED_RESOURCE_COORDINATE region_start_coordinates; region_start_coordinates.Y = 0; region_start_coordinates.Z = 0; region_start_coordinates.Subresource = 0; D3D12_TILE_REGION_SIZE region_size; region_size.NumTiles = kScaledResolveHeapSize / D3D12_TILED_RESOURCE_TILE_SIZE_IN_BYTES; region_size.UseBox = FALSE; D3D12_TILE_RANGE_FLAGS range_flags = D3D12_TILE_RANGE_FLAG_NONE; UINT heap_range_start_offset = 0; UINT range_tile_count = kScaledResolveHeapSize / D3D12_TILED_RESOURCE_TILE_SIZE_IN_BYTES; std::array<size_t, 2> buffer_indices = GetPossibleScaledResolveBufferIndices(uint64_t(i) << kScaledResolveHeapSizeLog2); for (size_t j = 0; j < 2; ++j) { size_t buffer_index = buffer_indices[j]; if (j && buffer_index == buffer_indices[0]) { break; } region_start_coordinates.X = UINT(((uint64_t(i) << kScaledResolveHeapSizeLog2) - (uint64_t(buffer_index) << 30)) / D3D12_TILED_RESOURCE_TILE_SIZE_IN_BYTES); direct_queue->UpdateTileMappings( scaled_resolve_2gb_buffers_[buffer_index]->resource(), 1, &region_start_coordinates, &region_size, scaled_resolve_heap, 1, &range_flags, &heap_range_start_offset, &range_tile_count, D3D12_TILE_MAPPING_FLAG_NONE); } command_processor_.NotifyQueueOperationsDoneDirectly(); } return true; } bool TextureCache::MakeScaledResolveRangeCurrent(uint32_t start_unscaled, uint32_t length_unscaled) { assert_true(draw_resolution_scale_ > 1); if (!length_unscaled || start_unscaled >= SharedMemory::kBufferSize || (SharedMemory::kBufferSize - start_unscaled) < length_unscaled) { // If length is 0, the needed buffer can't be chosen because no buffer is // needed. return false; } uint32_t draw_resolution_scale_square = draw_resolution_scale_ * draw_resolution_scale_; uint64_t start_scaled = uint64_t(start_unscaled) * draw_resolution_scale_square; uint64_t length_scaled = uint64_t(length_unscaled) * draw_resolution_scale_square; uint64_t last_scaled = start_scaled + (length_scaled - 1); // Get one or two buffers that can hold the whole range. std::array<size_t, 2> possible_buffer_indices_first = GetPossibleScaledResolveBufferIndices(start_scaled); std::array<size_t, 2> possible_buffer_indices_last = GetPossibleScaledResolveBufferIndices(last_scaled); size_t possible_buffer_indices_common[2]; size_t possible_buffer_indices_common_count = 0; for (size_t i = 0; i <= size_t(possible_buffer_indices_first[0] != possible_buffer_indices_first[1]); ++i) { size_t possible_buffer_index_first = possible_buffer_indices_first[i]; for (size_t j = 0; j <= size_t(possible_buffer_indices_last[0] != possible_buffer_indices_last[1]); ++j) { if (possible_buffer_indices_last[j] == possible_buffer_index_first) { bool possible_buffer_index_already_added = false; for (size_t k = 0; k < possible_buffer_indices_common_count; ++k) { if (possible_buffer_indices_common[k] == possible_buffer_index_first) { possible_buffer_index_already_added = true; break; } } if (!possible_buffer_index_already_added) { assert_true(possible_buffer_indices_common_count < 2); possible_buffer_indices_common [possible_buffer_indices_common_count++] = possible_buffer_index_first; } } } } if (!possible_buffer_indices_common_count) { // Too wide range requested - no buffer that contains both the start and the // end. return false; } size_t gigabyte_first = size_t(start_scaled >> 30); size_t gigabyte_last = size_t(last_scaled >> 30); // Choose the buffer that the range will be accessed through. size_t new_buffer_index; if (possible_buffer_indices_common_count >= 2) { // Prefer the buffer that is already used to make less aliasing barriers. assert_true(gigabyte_first + 1 >= gigabyte_last); size_t possible_buffer_indices_already_used[2] = {}; for (size_t i = gigabyte_first; i <= gigabyte_last; ++i) { size_t gigabyte_current_buffer_index = scaled_resolve_1gb_buffer_indices_[i]; for (size_t j = 0; j < possible_buffer_indices_common_count; ++j) { if (possible_buffer_indices_common[j] == gigabyte_current_buffer_index) { ++possible_buffer_indices_already_used[j]; } } } new_buffer_index = possible_buffer_indices_common[size_t( possible_buffer_indices_already_used[1] > possible_buffer_indices_already_used[0])]; } else { // The range can be accessed only by one buffer. new_buffer_index = possible_buffer_indices_common[0]; } // Switch the current buffer for the range. const ScaledResolveVirtualBuffer* new_buffer = scaled_resolve_2gb_buffers_[new_buffer_index]; assert_not_null(new_buffer); ID3D12Resource* new_buffer_resource = new_buffer->resource(); for (size_t i = gigabyte_first; i <= gigabyte_last; ++i) { size_t gigabyte_current_buffer_index = scaled_resolve_1gb_buffer_indices_[i]; if (gigabyte_current_buffer_index == new_buffer_index) { continue; } if (gigabyte_current_buffer_index != SIZE_MAX) { ScaledResolveVirtualBuffer* gigabyte_current_buffer = scaled_resolve_2gb_buffers_[gigabyte_current_buffer_index]; assert_not_null(gigabyte_current_buffer); command_processor_.PushAliasingBarrier( gigabyte_current_buffer->resource(), new_buffer_resource); // An aliasing barrier synchronizes and flushes everything. gigabyte_current_buffer->ClearUAVBarrierPending(); } scaled_resolve_1gb_buffer_indices_[i] = new_buffer_index; } scaled_resolve_current_range_start_scaled_ = start_scaled; scaled_resolve_current_range_length_scaled_ = length_scaled; return true; } void TextureCache::TransitionCurrentScaledResolveRange( D3D12_RESOURCE_STATES new_state) { assert_true(draw_resolution_scale_ > 1); ScaledResolveVirtualBuffer& buffer = GetCurrentScaledResolveBuffer(); command_processor_.PushTransitionBarrier( buffer.resource(), buffer.SetResourceState(new_state), new_state); } void TextureCache::CreateCurrentScaledResolveRangeUintPow2SRV( D3D12_CPU_DESCRIPTOR_HANDLE handle, uint32_t element_size_bytes_pow2) { assert_true(draw_resolution_scale_ > 1); size_t buffer_index = GetCurrentScaledResolveBufferIndex(); const ScaledResolveVirtualBuffer* buffer = scaled_resolve_2gb_buffers_[buffer_index]; assert_not_null(buffer); ui::d3d12::util::CreateBufferTypedSRV( command_processor_.GetD3D12Context().GetD3D12Provider().GetDevice(), handle, buffer->resource(), ui::d3d12::util::GetUintPow2DXGIFormat(element_size_bytes_pow2), uint32_t(scaled_resolve_current_range_length_scaled_ >> element_size_bytes_pow2), (scaled_resolve_current_range_start_scaled_ - (uint64_t(buffer_index) << 30)) >> element_size_bytes_pow2); } void TextureCache::CreateCurrentScaledResolveRangeUintPow2UAV( D3D12_CPU_DESCRIPTOR_HANDLE handle, uint32_t element_size_bytes_pow2) { assert_true(draw_resolution_scale_ > 1); size_t buffer_index = GetCurrentScaledResolveBufferIndex(); const ScaledResolveVirtualBuffer* buffer = scaled_resolve_2gb_buffers_[buffer_index]; assert_not_null(buffer); ui::d3d12::util::CreateBufferTypedUAV( command_processor_.GetD3D12Context().GetD3D12Provider().GetDevice(), handle, buffer->resource(), ui::d3d12::util::GetUintPow2DXGIFormat(element_size_bytes_pow2), uint32_t(scaled_resolve_current_range_length_scaled_ >> element_size_bytes_pow2), (scaled_resolve_current_range_start_scaled_ - (uint64_t(buffer_index) << 30)) >> element_size_bytes_pow2); } ID3D12Resource* TextureCache::RequestSwapTexture( D3D12_SHADER_RESOURCE_VIEW_DESC& srv_desc_out, xenos::TextureFormat& format_out) { const auto& regs = register_file_; const auto& fetch = regs.Get<xenos::xe_gpu_texture_fetch_t>( XE_GPU_REG_SHADER_CONSTANT_FETCH_00_0); TextureKey key; uint32_t swizzle; BindingInfoFromFetchConstant(fetch, key, &swizzle, nullptr); if (key.base_page == 0 || key.dimension != xenos::DataDimension::k2DOrStacked) { return nullptr; } Texture* texture = FindOrCreateTexture(key); if (texture == nullptr || !LoadTextureData(texture)) { return nullptr; } MarkTextureUsed(texture); // The swap texture is likely to be used only for the presentation pixel // shader, and not during emulation, where it'd be NON_PIXEL_SHADER_RESOURCE | // PIXEL_SHADER_RESOURCE. command_processor_.PushTransitionBarrier( texture->resource, texture->state, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE); texture->state = D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE; srv_desc_out.Format = GetDXGIUnormFormat(key); srv_desc_out.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; srv_desc_out.Shader4ComponentMapping = swizzle | D3D12_SHADER_COMPONENT_MAPPING_ALWAYS_SET_BIT_AVOIDING_ZEROMEM_MISTAKES; srv_desc_out.Texture2D.MostDetailedMip = 0; srv_desc_out.Texture2D.MipLevels = 1; srv_desc_out.Texture2D.PlaneSlice = 0; srv_desc_out.Texture2D.ResourceMinLODClamp = 0.0f; format_out = key.format; return texture->resource; } bool TextureCache::IsDecompressionNeeded(xenos::TextureFormat format, uint32_t width, uint32_t height) { DXGI_FORMAT dxgi_format_uncompressed = host_formats_[uint32_t(format)].dxgi_format_uncompressed; if (dxgi_format_uncompressed == DXGI_FORMAT_UNKNOWN) { return false; } const FormatInfo* format_info = FormatInfo::Get(format); return (width & (format_info->block_width - 1)) != 0 || (height & (format_info->block_height - 1)) != 0; } TextureCache::LoadMode TextureCache::GetLoadMode(TextureKey key) { const HostFormat& host_format = host_formats_[uint32_t(key.format)]; if (key.signed_separate) { return host_format.load_mode_snorm; } if (IsDecompressionNeeded(key.format, key.width, key.height)) { return host_format.decompress_mode; } return host_format.load_mode; } void TextureCache::BindingInfoFromFetchConstant( const xenos::xe_gpu_texture_fetch_t& fetch, TextureKey& key_out, uint32_t* host_swizzle_out, uint8_t* swizzled_signs_out) { // Reset the key and the swizzle. key_out.MakeInvalid(); if (host_swizzle_out != nullptr) { *host_swizzle_out = xenos::XE_GPU_SWIZZLE_0 | (xenos::XE_GPU_SWIZZLE_0 << 3) | (xenos::XE_GPU_SWIZZLE_0 << 6) | (xenos::XE_GPU_SWIZZLE_0 << 9); } if (swizzled_signs_out != nullptr) { *swizzled_signs_out = uint8_t(xenos::TextureSign::kUnsigned) * uint8_t(0b01010101); } switch (fetch.type) { case xenos::FetchConstantType::kTexture: break; case xenos::FetchConstantType::kInvalidTexture: if (cvars::gpu_allow_invalid_fetch_constants) { break; } XELOGW( "Texture fetch constant ({:08X} {:08X} {:08X} {:08X} {:08X} {:08X}) " "has \"invalid\" type! This is incorrect behavior, but you can try " "bypassing this by launching Xenia with " "--gpu_allow_invalid_fetch_constants=true.", fetch.dword_0, fetch.dword_1, fetch.dword_2, fetch.dword_3, fetch.dword_4, fetch.dword_5); return; default: XELOGW( "Texture fetch constant ({:08X} {:08X} {:08X} {:08X} {:08X} {:08X}) " "is completely invalid!", fetch.dword_0, fetch.dword_1, fetch.dword_2, fetch.dword_3, fetch.dword_4, fetch.dword_5); return; } uint32_t width, height, depth_or_faces; uint32_t base_page, mip_page, mip_max_level; texture_util::GetSubresourcesFromFetchConstant( fetch, &width, &height, &depth_or_faces, &base_page, &mip_page, nullptr, &mip_max_level); if (base_page == 0 && mip_page == 0) { // No texture data at all. return; } // TODO(Triang3l): Support long 1D textures. if (fetch.dimension == xenos::DataDimension::k1D && width > xenos::kTexture2DCubeMaxWidthHeight) { XELOGE( "1D texture is too wide ({}) - ignoring! " "Report the game to Xenia developers", width); return; } xenos::TextureFormat format = GetBaseFormat(fetch.format); key_out.base_page = base_page; key_out.mip_page = mip_page; key_out.dimension = fetch.dimension; key_out.width = width; key_out.height = height; key_out.depth = depth_or_faces; key_out.pitch = fetch.pitch; key_out.mip_max_level = mip_max_level; key_out.tiled = fetch.tiled; key_out.packed_mips = fetch.packed_mips; key_out.format = format; key_out.endianness = fetch.endianness; if (host_swizzle_out != nullptr) { uint32_t host_swizzle = 0; for (uint32_t i = 0; i < 4; ++i) { uint32_t host_swizzle_component = (fetch.swizzle >> (i * 3)) & 0b111; if (host_swizzle_component >= 4) { // Get rid of 6 and 7 values (to prevent device losses if the game has // something broken) the quick and dirty way - by changing them to 4 (0) // and 5 (1). host_swizzle_component &= 0b101; } else { host_swizzle_component = host_formats_[uint32_t(format)].swizzle[host_swizzle_component]; } host_swizzle |= host_swizzle_component << (i * 3); } *host_swizzle_out = host_swizzle; } if (swizzled_signs_out != nullptr) { *swizzled_signs_out = texture_util::SwizzleSigns(fetch); } } void TextureCache::LogTextureKeyAction(TextureKey key, const char* action) { XELOGGPU( "{} {} {}{}x{}x{} {} {} texture with {} {}packed mip level{}, " "base at 0x{:08X} (pitch {}), mips at 0x{:08X}", action, key.tiled ? "tiled" : "linear", key.scaled_resolve ? "scaled " : "", key.width, key.height, key.depth, dimension_names_[uint32_t(key.dimension)], FormatInfo::Get(key.format)->name, key.mip_max_level + 1, key.packed_mips ? "" : "un", key.mip_max_level != 0 ? "s" : "", key.base_page << 12, key.pitch << 5, key.mip_page << 12); } void TextureCache::LogTextureAction(const Texture* texture, const char* action) { XELOGGPU( "{} {} {}{}x{}x{} {} {} texture with {} {}packed mip level{}, " "base at 0x{:08X} (pitch {}, size 0x{:08X}), mips at 0x{:08X} (size " "0x{:08X})", action, texture->key.tiled ? "tiled" : "linear", texture->key.scaled_resolve ? "scaled " : "", texture->key.width, texture->key.height, texture->key.depth, dimension_names_[uint32_t(texture->key.dimension)], FormatInfo::Get(texture->key.format)->name, texture->key.mip_max_level + 1, texture->key.packed_mips ? "" : "un", texture->key.mip_max_level != 0 ? "s" : "", texture->key.base_page << 12, texture->key.pitch << 5, texture->GetGuestBaseSize(), texture->key.mip_page << 12, texture->GetGuestMipsSize()); } TextureCache::Texture* TextureCache::FindOrCreateTexture(TextureKey key) { // Check if the texture is a scaled resolve texture. if (draw_resolution_scale_ > 1 && key.tiled) { LoadMode load_mode = GetLoadMode(key); if (load_mode != LoadMode::kUnknown && load_pipelines_scaled_[uint32_t(load_mode)] != nullptr) { texture_util::TextureGuestLayout scaled_resolve_guest_layout = texture_util::GetGuestTextureLayout( key.dimension, key.pitch, key.width, key.height, key.depth, key.tiled, key.format, key.packed_mips, key.base_page != 0, key.mip_max_level); if ((scaled_resolve_guest_layout.base.level_data_extent_bytes && IsRangeScaledResolved( key.base_page << 12, scaled_resolve_guest_layout.base.level_data_extent_bytes)) || (scaled_resolve_guest_layout.mips_total_extent_bytes && IsRangeScaledResolved( key.mip_page << 12, scaled_resolve_guest_layout.mips_total_extent_bytes))) { key.scaled_resolve = 1; } } } uint32_t host_width = key.width; uint32_t host_height = key.height; if (key.scaled_resolve) { host_width *= draw_resolution_scale_; host_height *= draw_resolution_scale_; } // With 3x resolution scaling, a 2D texture may become bigger than the // Direct3D 11 limit, and with 2x, a 3D one as well. uint32_t max_host_width_height = GetMaxHostTextureWidthHeight(key.dimension); uint32_t max_host_depth = GetMaxHostTextureDepth(key.dimension); if (host_width > max_host_width_height || host_height > max_host_width_height || key.depth > max_host_depth) { return nullptr; } // Try to find an existing texture. // TODO(Triang3l): Reuse a texture with mip_page unchanged, but base_page // previously 0, now not 0, to save memory - common case in streaming. auto found_texture_it = textures_.find(key); if (found_texture_it != textures_.end()) { return found_texture_it->second; } // Create the resource. If failed to create one, don't create a texture object // at all so it won't be in indeterminate state. D3D12_RESOURCE_DESC desc; desc.Format = GetDXGIResourceFormat(key); if (desc.Format == DXGI_FORMAT_UNKNOWN) { unsupported_format_features_used_[uint32_t(key.format)] |= kUnsupportedResourceBit; return nullptr; } if (key.dimension == xenos::DataDimension::k3D) { desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE3D; } else { // 1D textures are treated as 2D for simplicity. desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; } desc.Alignment = 0; desc.Width = host_width; desc.Height = host_height; desc.DepthOrArraySize = key.depth; desc.MipLevels = key.mip_max_level + 1; desc.SampleDesc.Count = 1; desc.SampleDesc.Quality = 0; desc.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN; // Untiling through a buffer instead of using unordered access because copying // is not done that often. desc.Flags = D3D12_RESOURCE_FLAG_NONE; auto& provider = command_processor_.GetD3D12Context().GetD3D12Provider(); auto device = provider.GetDevice(); // Assuming untiling will be the next operation. D3D12_RESOURCE_STATES state = D3D12_RESOURCE_STATE_COPY_DEST; ID3D12Resource* resource; if (FAILED(device->CreateCommittedResource( &ui::d3d12::util::kHeapPropertiesDefault, provider.GetHeapFlagCreateNotZeroed(), &desc, state, nullptr, IID_PPV_ARGS(&resource)))) { LogTextureKeyAction(key, "Failed to create"); return nullptr; } // Create the texture object and add it to the map. Texture* texture = new Texture; texture->key = key; texture->resource = resource; texture->resource_size = device->GetResourceAllocationInfo(0, 1, &desc).SizeInBytes; texture->state = state; texture->last_usage_frame = command_processor_.GetCurrentFrame(); texture->last_usage_time = texture_current_usage_time_; texture->used_previous = texture_used_last_; texture->used_next = nullptr; if (texture_used_last_ != nullptr) { texture_used_last_->used_next = texture; } else { texture_used_first_ = texture; } texture_used_last_ = texture; texture->base_resolved = key.scaled_resolve; texture->mips_resolved = key.scaled_resolve; texture->guest_layout = texture_util::GetGuestTextureLayout( key.dimension, key.pitch, key.width, key.height, key.depth, key.tiled, key.format, key.packed_mips, key.base_page != 0, key.mip_max_level); // Never try to upload data that doesn't exist. texture->base_in_sync = !texture->guest_layout.base.level_data_extent_bytes; texture->mips_in_sync = !texture->guest_layout.mips_total_extent_bytes; texture->base_watch_handle = nullptr; texture->mip_watch_handle = nullptr; textures_.emplace(key, texture); COUNT_profile_set("gpu/texture_cache/textures", textures_.size()); textures_total_size_ += texture->resource_size; COUNT_profile_set("gpu/texture_cache/total_size_mb", uint32_t(textures_total_size_ >> 20)); LogTextureAction(texture, "Created"); return texture; } bool TextureCache::LoadTextureData(Texture* texture) { // See what we need to upload. bool base_in_sync, mips_in_sync; { auto global_lock = global_critical_region_.Acquire(); base_in_sync = texture->base_in_sync; mips_in_sync = texture->mips_in_sync; } if (base_in_sync && mips_in_sync) { return true; } auto& command_list = command_processor_.GetDeferredCommandList(); auto device = command_processor_.GetD3D12Context().GetD3D12Provider().GetDevice(); // Get the pipeline. LoadMode load_mode = GetLoadMode(texture->key); if (load_mode == LoadMode::kUnknown) { return false; } uint32_t texture_resolution_scale = texture->key.scaled_resolve ? draw_resolution_scale_ : 1; ID3D12PipelineState* pipeline = texture_resolution_scale > 1 ? load_pipelines_scaled_[uint32_t(load_mode)] : load_pipelines_[uint32_t(load_mode)]; if (pipeline == nullptr) { return false; } const LoadModeInfo& load_mode_info = load_mode_info_[uint32_t(load_mode)]; const LoadShaderInfo& load_shader_info = load_mode_info.shaders[texture_resolution_scale - 1]; // Request uploading of the texture data to the shared memory. // This is also necessary when resolution scale is used - the texture cache // relies on shared memory for invalidation of both unscaled and scaled // textures! Plus a texture may be unscaled partially, when only a portion of // its pages is invalidated, in this case we'll need the texture from the // shared memory to load the unscaled parts. // TODO(Triang3l): Load unscaled parts. bool base_resolved = texture->base_resolved; if (!base_in_sync) { if (!shared_memory_.RequestRange( texture->key.base_page << 12, texture->GetGuestBaseSize(), texture->key.scaled_resolve ? nullptr : &base_resolved)) { return false; } } bool mips_resolved = texture->mips_resolved; if (!mips_in_sync) { if (!shared_memory_.RequestRange( texture->key.mip_page << 12, texture->GetGuestMipsSize(), texture->key.scaled_resolve ? nullptr : &mips_resolved)) { return false; } } if (texture_resolution_scale > 1) { // Make sure all heaps are created. if (!EnsureScaledResolveMemoryCommitted(texture->key.base_page << 12, texture->GetGuestBaseSize())) { return false; } if (!EnsureScaledResolveMemoryCommitted(texture->key.mip_page << 12, texture->GetGuestMipsSize())) { return false; } } // Get the guest layout. xenos::DataDimension dimension = texture->key.dimension; bool is_3d = dimension == xenos::DataDimension::k3D; uint32_t width = texture->key.width; uint32_t height = texture->key.height; uint32_t depth_or_array_size = texture->key.depth; uint32_t depth = is_3d ? depth_or_array_size : 1; uint32_t array_size = is_3d ? 1 : depth_or_array_size; xenos::TextureFormat guest_format = texture->key.format; const FormatInfo* guest_format_info = FormatInfo::Get(guest_format); uint32_t block_width = guest_format_info->block_width; uint32_t block_height = guest_format_info->block_height; uint32_t bytes_per_block = guest_format_info->bytes_per_block(); uint32_t level_first = base_in_sync ? 1 : 0; uint32_t level_last = mips_in_sync ? 0 : texture->key.mip_max_level; assert_true(level_first <= level_last); uint32_t level_packed = texture->guest_layout.packed_level; uint32_t level_stored_first = std::min(level_first, level_packed); uint32_t level_stored_last = std::min(level_last, level_packed); // Get the host layout and the buffer. UINT64 copy_buffer_size = 0; D3D12_PLACED_SUBRESOURCE_FOOTPRINT host_slice_layout_base; UINT64 host_slice_size_base; // Indexing is the same as for guest stored mips: // 1...min(level_last, level_packed) if level_packed is not 0, or only 0 if // level_packed == 0. D3D12_PLACED_SUBRESOURCE_FOOTPRINT host_slice_layouts_mips[xenos::kTexture2DCubeMaxWidthHeightLog2 + 1]; UINT64 host_slice_sizes_mips[xenos::kTexture2DCubeMaxWidthHeightLog2 + 1]; { // Using custom calculations instead of GetCopyableFootprints because // shaders may copy multiple blocks per thread for simplicity. For 3x // resolution scaling, the number becomes a multiple of 3 rather than a // power of 2 - so the 256-byte alignment required anyway by Direct3D 12 is // not enough. GetCopyableFootprints would be needed to be called with an // overaligned width - but it may exceed 16384 (the maximum Direct3D 12 // texture size) for 3x resolution scaling, and the function will fail. DXGI_FORMAT host_copy_format; uint32_t host_block_width; uint32_t host_block_height; uint32_t host_bytes_per_block; ui::d3d12::util::GetFormatCopyInfo( GetDXGIResourceFormat(guest_format, width, height), 0, host_copy_format, host_block_width, host_block_height, host_bytes_per_block); if (!level_first) { host_slice_layout_base.Offset = copy_buffer_size; host_slice_layout_base.Footprint.Format = host_copy_format; if (!level_packed) { // Loading the packed tail for the base - load the whole tail to copy // regions out of it. const texture_util::TextureGuestLevelLayout& guest_layout_base = texture->guest_layout.base; host_slice_layout_base.Footprint.Width = guest_layout_base.x_extent_blocks * block_width; host_slice_layout_base.Footprint.Height = guest_layout_base.y_extent_blocks * block_height; host_slice_layout_base.Footprint.Depth = guest_layout_base.z_extent; } else { host_slice_layout_base.Footprint.Width = width; host_slice_layout_base.Footprint.Height = height; host_slice_layout_base.Footprint.Depth = depth; } host_slice_layout_base.Footprint.Width = xe::round_up( host_slice_layout_base.Footprint.Width * texture_resolution_scale, UINT(host_block_width)); host_slice_layout_base.Footprint.Height = xe::round_up( host_slice_layout_base.Footprint.Height * texture_resolution_scale, UINT(host_block_height)); host_slice_layout_base.Footprint.RowPitch = xe::align(xe::round_up(host_slice_layout_base.Footprint.Width / host_block_width, load_shader_info.host_x_blocks_per_thread) * host_bytes_per_block, uint32_t(D3D12_TEXTURE_DATA_PITCH_ALIGNMENT)); host_slice_size_base = xe::align( UINT64(host_slice_layout_base.Footprint.RowPitch) * (host_slice_layout_base.Footprint.Height / host_block_height) * host_slice_layout_base.Footprint.Depth, UINT64(D3D12_TEXTURE_DATA_PLACEMENT_ALIGNMENT)); copy_buffer_size += host_slice_size_base * array_size; } if (level_last) { for (uint32_t level = level_stored_first; level <= level_stored_last; ++level) { D3D12_PLACED_SUBRESOURCE_FOOTPRINT& host_slice_layout_mip = host_slice_layouts_mips[level]; host_slice_layout_mip.Offset = copy_buffer_size; host_slice_layout_mip.Footprint.Format = host_copy_format; if (level == level_packed) { // Loading the packed tail for the mips - load the whole tail to copy // regions out of it. const texture_util::TextureGuestLevelLayout& guest_layout_packed_mips = texture->guest_layout.mips[level]; host_slice_layout_mip.Footprint.Width = guest_layout_packed_mips.x_extent_blocks * block_width; host_slice_layout_mip.Footprint.Height = guest_layout_packed_mips.y_extent_blocks * block_height; host_slice_layout_mip.Footprint.Depth = guest_layout_packed_mips.z_extent; } else { host_slice_layout_mip.Footprint.Width = std::max(width >> level, uint32_t(1)); host_slice_layout_mip.Footprint.Height = std::max(height >> level, uint32_t(1)); host_slice_layout_mip.Footprint.Depth = std::max(depth >> level, uint32_t(1)); } host_slice_layout_mip.Footprint.Width = xe::round_up( host_slice_layout_mip.Footprint.Width * texture_resolution_scale, UINT(host_block_width)); host_slice_layout_mip.Footprint.Height = xe::round_up( host_slice_layout_mip.Footprint.Height * texture_resolution_scale, UINT(host_block_height)); host_slice_layout_mip.Footprint.RowPitch = xe::align(xe::round_up(host_slice_layout_mip.Footprint.Width / host_block_width, load_shader_info.host_x_blocks_per_thread) * host_bytes_per_block, uint32_t(D3D12_TEXTURE_DATA_PITCH_ALIGNMENT)); UINT64 host_slice_sizes_mip = xe::align( UINT64(host_slice_layout_mip.Footprint.RowPitch) * (host_slice_layout_mip.Footprint.Height / host_block_height) * host_slice_layout_mip.Footprint.Depth, UINT64(D3D12_TEXTURE_DATA_PLACEMENT_ALIGNMENT)); host_slice_sizes_mips[level] = host_slice_sizes_mip; copy_buffer_size += host_slice_sizes_mip * array_size; } } } D3D12_RESOURCE_STATES copy_buffer_state = D3D12_RESOURCE_STATE_UNORDERED_ACCESS; ID3D12Resource* copy_buffer = command_processor_.RequestScratchGPUBuffer( uint32_t(copy_buffer_size), copy_buffer_state); if (copy_buffer == nullptr) { return false; } uint32_t host_block_width = 1; uint32_t host_block_height = 1; if (host_formats_[uint32_t(guest_format)].dxgi_format_block_aligned && !IsDecompressionNeeded(guest_format, width, height)) { host_block_width = block_width; host_block_height = block_height; } // Begin loading. // May use different buffers for scaled base and mips, and also can't address // more than 128 megatexels directly on Nvidia - need two separate UAV // descriptors for base and mips. // Destination. uint32_t descriptor_count = 1; if (texture_resolution_scale > 1) { // Source - base and mips, one or both. descriptor_count += (level_first == 0 && level_last != 0) ? 2 : 1; } else { // Source - shared memory. if (!bindless_resources_used_) { ++descriptor_count; } } ui::d3d12::util::DescriptorCpuGpuHandlePair descriptors_allocated[3]; if (!command_processor_.RequestOneUseSingleViewDescriptors( descriptor_count, descriptors_allocated)) { command_processor_.ReleaseScratchGPUBuffer(copy_buffer, copy_buffer_state); return false; } uint32_t descriptor_write_index = 0; command_processor_.SetExternalPipeline(pipeline); command_list.D3DSetComputeRootSignature(load_root_signature_); // Set up the destination descriptor. assert_true(descriptor_write_index < descriptor_count); ui::d3d12::util::DescriptorCpuGpuHandlePair descriptor_dest = descriptors_allocated[descriptor_write_index++]; ui::d3d12::util::CreateBufferTypedUAV( device, descriptor_dest.first, copy_buffer, ui::d3d12::util::GetUintPow2DXGIFormat(load_shader_info.uav_bpe_log2), uint32_t(copy_buffer_size) >> load_shader_info.uav_bpe_log2); command_list.D3DSetComputeRootDescriptorTable(2, descriptor_dest.second); // Set up the unscaled source descriptor (scaled needs two descriptors that // depend on the buffer being current, so they will be set later - for mips, // after loading the base is done). if (texture_resolution_scale <= 1) { shared_memory_.UseForReading(); ui::d3d12::util::DescriptorCpuGpuHandlePair descriptor_unscaled_source; if (bindless_resources_used_) { descriptor_unscaled_source = command_processor_.GetSharedMemoryUintPow2BindlessSRVHandlePair( load_shader_info.srv_bpe_log2); } else { assert_true(descriptor_write_index < descriptor_count); descriptor_unscaled_source = descriptors_allocated[descriptor_write_index++]; shared_memory_.WriteUintPow2SRVDescriptor( descriptor_unscaled_source.first, load_shader_info.srv_bpe_log2); } command_list.D3DSetComputeRootDescriptorTable( 1, descriptor_unscaled_source.second); } // Submit the copy buffer population commands. auto& cbuffer_pool = command_processor_.GetConstantBufferPool(); LoadConstants load_constants; load_constants.is_tiled_3d_endian = uint32_t(texture->key.tiled) | (uint32_t(is_3d) << 1) | (uint32_t(texture->key.endianness) << 2); // The loop counter can mean two things depending on whether the packed mip // tail is stored as mip 0, because in this case, it would be ambiguous since // both the base and the mips would be on "level 0", but stored in separate // places. uint32_t loop_level_first, loop_level_last; if (level_packed == 0) { // Packed mip tail is the level 0 - may need to load mip tails for the base, // the mips, or both. // Loop iteration 0 - base packed mip tail. // Loop iteration 1 - mips packed mip tail. loop_level_first = uint32_t(level_first != 0); loop_level_last = uint32_t(level_last != 0); } else { // Packed mip tail is not the level 0. // Loop iteration is the actual level being loaded. loop_level_first = level_stored_first; loop_level_last = level_stored_last; } // The loop is slices within levels because the base and the levels may need // different portions of the scaled resolve virtual address space to be // available through buffers, and to create a descriptor, the buffer start // address is required - which may be different for base and mips. bool scaled_mips_source_set_up = false; for (uint32_t loop_level = loop_level_first; loop_level <= loop_level_last; ++loop_level) { bool is_base = loop_level == 0; uint32_t level = (level_packed == 0) ? 0 : loop_level; uint32_t guest_address = (is_base ? texture->key.base_page : texture->key.mip_page) << 12; // Set up the base or mips source, also making it accessible if loading from // scaled resolve memory. if (texture_resolution_scale > 1 && (is_base || !scaled_mips_source_set_up)) { uint32_t guest_size_unscaled = is_base ? texture->GetGuestBaseSize() : texture->GetGuestMipsSize(); if (!MakeScaledResolveRangeCurrent(guest_address, guest_size_unscaled)) { command_processor_.ReleaseScratchGPUBuffer(copy_buffer, copy_buffer_state); return false; } TransitionCurrentScaledResolveRange( D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE); assert_true(descriptor_write_index < descriptor_count); ui::d3d12::util::DescriptorCpuGpuHandlePair descriptor_scaled_source = descriptors_allocated[descriptor_write_index++]; CreateCurrentScaledResolveRangeUintPow2SRV(descriptor_scaled_source.first, load_shader_info.srv_bpe_log2); command_list.D3DSetComputeRootDescriptorTable( 1, descriptor_scaled_source.second); if (!is_base) { scaled_mips_source_set_up = true; } } if (texture_resolution_scale > 1) { // Offset already applied in the buffer because more than 512 MB can't be // directly addresses on Nvidia as R32. load_constants.guest_offset = 0; } else { load_constants.guest_offset = guest_address; } if (!is_base) { load_constants.guest_offset += texture->guest_layout.mip_offsets_bytes[level]; } const texture_util::TextureGuestLevelLayout& level_guest_layout = is_base ? texture->guest_layout.base : texture->guest_layout.mips[level]; uint32_t level_guest_pitch = level_guest_layout.row_pitch_bytes; if (texture->key.tiled) { // Shaders expect pitch in blocks for tiled textures. level_guest_pitch /= bytes_per_block; assert_zero(level_guest_pitch & (xenos::kTextureTileWidthHeight - 1)); } load_constants.guest_pitch_aligned = level_guest_pitch; load_constants.guest_z_stride_block_rows_aligned = level_guest_layout.z_slice_stride_block_rows; assert_zero(load_constants.guest_z_stride_block_rows_aligned & (xenos::kTextureTileWidthHeight - 1)); uint32_t level_width, level_height, level_depth; if (level == level_packed) { // This is the packed mip tail, containing not only the specified level, // but also other levels at different offsets - load the entire needed // extents. level_width = level_guest_layout.x_extent_blocks * block_width; level_height = level_guest_layout.y_extent_blocks * block_height; level_depth = level_guest_layout.z_extent; } else { level_width = std::max(width >> level, uint32_t(1)); level_height = std::max(height >> level, uint32_t(1)); level_depth = std::max(depth >> level, uint32_t(1)); } load_constants.size_blocks[0] = (level_width + (block_width - 1)) / block_width; load_constants.size_blocks[1] = (level_height + (block_height - 1)) / block_height; load_constants.size_blocks[2] = level_depth; load_constants.height_texels = level_height; // Each thread group processes 32x32x1 guest blocks. uint32_t group_count_x = (load_constants.size_blocks[0] + 31) >> 5; uint32_t group_count_y = (load_constants.size_blocks[1] + 31) >> 5; const D3D12_PLACED_SUBRESOURCE_FOOTPRINT& host_slice_layout = is_base ? host_slice_layout_base : host_slice_layouts_mips[level]; uint32_t host_slice_size = uint32_t(is_base ? host_slice_size_base : host_slice_sizes_mips[level]); load_constants.host_offset = uint32_t(host_slice_layout.Offset); load_constants.host_pitch = host_slice_layout.Footprint.RowPitch; for (uint32_t slice = 0; slice < array_size; ++slice) { D3D12_GPU_VIRTUAL_ADDRESS cbuffer_gpu_address; uint8_t* cbuffer_mapping = cbuffer_pool.Request( command_processor_.GetCurrentFrame(), sizeof(load_constants), D3D12_CONSTANT_BUFFER_DATA_PLACEMENT_ALIGNMENT, nullptr, nullptr, &cbuffer_gpu_address); if (cbuffer_mapping == nullptr) { command_processor_.ReleaseScratchGPUBuffer(copy_buffer, copy_buffer_state); return false; } std::memcpy(cbuffer_mapping, &load_constants, sizeof(load_constants)); command_list.D3DSetComputeRootConstantBufferView(0, cbuffer_gpu_address); assert_true(copy_buffer_state == D3D12_RESOURCE_STATE_UNORDERED_ACCESS); command_processor_.SubmitBarriers(); command_list.D3DDispatch(group_count_x, group_count_y, load_constants.size_blocks[2]); load_constants.guest_offset += level_guest_layout.array_slice_stride_bytes; load_constants.host_offset += host_slice_size; } } // Update LRU caching because the texture will be used by the command list. MarkTextureUsed(texture); // Submit copying from the copy buffer to the host texture. command_processor_.PushTransitionBarrier(texture->resource, texture->state, D3D12_RESOURCE_STATE_COPY_DEST); texture->state = D3D12_RESOURCE_STATE_COPY_DEST; command_processor_.PushTransitionBarrier(copy_buffer, copy_buffer_state, D3D12_RESOURCE_STATE_COPY_SOURCE); copy_buffer_state = D3D12_RESOURCE_STATE_COPY_SOURCE; command_processor_.SubmitBarriers(); uint32_t texture_level_count = texture->key.mip_max_level + 1; D3D12_TEXTURE_COPY_LOCATION location_source, location_dest; location_source.pResource = copy_buffer; location_source.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT; location_dest.pResource = texture->resource; location_dest.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX; for (uint32_t level = level_first; level <= level_last; ++level) { uint32_t guest_level = std::min(level, level_packed); location_source.PlacedFootprint = level ? host_slice_layouts_mips[guest_level] : host_slice_layout_base; location_dest.SubresourceIndex = level; UINT64 host_slice_size = level ? host_slice_sizes_mips[guest_level] : host_slice_size_base; D3D12_BOX source_box; const D3D12_BOX* source_box_ptr; if (level >= level_packed) { uint32_t level_offset_blocks_x, level_offset_blocks_y, level_offset_z; texture_util::GetPackedMipOffset(width, height, depth, guest_format, level, level_offset_blocks_x, level_offset_blocks_y, level_offset_z); source_box.left = level_offset_blocks_x * block_width; source_box.top = level_offset_blocks_y * block_height; source_box.front = level_offset_z; source_box.right = source_box.left + xe::align(std::max(width >> level, uint32_t(1)), host_block_width); source_box.bottom = source_box.top + xe::align(std::max(height >> level, uint32_t(1)), host_block_height); source_box.back = source_box.front + std::max(depth >> level, uint32_t(1)); source_box_ptr = &source_box; } else { source_box_ptr = nullptr; } for (uint32_t slice = 0; slice < array_size; ++slice) { command_list.D3DCopyTextureRegion(&location_dest, 0, 0, 0, &location_source, source_box_ptr); location_dest.SubresourceIndex += texture_level_count; location_source.PlacedFootprint.Offset += host_slice_size; } } command_processor_.ReleaseScratchGPUBuffer(copy_buffer, copy_buffer_state); // Update the source of the texture (resolve vs. CPU or memexport) for // purposes of handling piecewise gamma emulation via sRGB and for resolution // scale in sampling offsets. texture->base_resolved = base_resolved; texture->mips_resolved = mips_resolved; // Mark the ranges as uploaded and watch them. This is needed for scaled // resolves as well to detect when the CPU wants to reuse the memory for a // regular texture or a vertex buffer, and thus the scaled resolve version is // not up to date anymore. { auto global_lock = global_critical_region_.Acquire(); texture->base_in_sync = true; texture->mips_in_sync = true; if (!base_in_sync) { texture->base_watch_handle = shared_memory_.WatchMemoryRange( texture->key.base_page << 12, texture->GetGuestBaseSize(), WatchCallbackThunk, this, texture, 0); } if (!mips_in_sync) { texture->mip_watch_handle = shared_memory_.WatchMemoryRange( texture->key.mip_page << 12, texture->GetGuestMipsSize(), WatchCallbackThunk, this, texture, 1); } } LogTextureAction(texture, "Loaded"); return true; } uint32_t TextureCache::FindOrCreateTextureDescriptor(Texture& texture, bool is_signed, uint32_t host_swizzle) { uint32_t descriptor_key = uint32_t(is_signed) | (host_swizzle << 1); // Try to find an existing descriptor. auto it = texture.srv_descriptors.find(descriptor_key); if (it != texture.srv_descriptors.end()) { return it->second; } // Create a new bindless or cached descriptor if supported. D3D12_SHADER_RESOURCE_VIEW_DESC desc; xenos::TextureFormat format = texture.key.format; if (IsSignedVersionSeparate(format) && texture.key.signed_separate != uint32_t(is_signed)) { // Not the version with the needed signedness. return UINT32_MAX; } if (is_signed) { // Not supporting signed compressed textures - hopefully DXN and DXT5A are // not used as signed. desc.Format = host_formats_[uint32_t(format)].dxgi_format_snorm; } else { desc.Format = GetDXGIUnormFormat(texture.key); } if (desc.Format == DXGI_FORMAT_UNKNOWN) { unsupported_format_features_used_[uint32_t(format)] |= is_signed ? kUnsupportedSnormBit : kUnsupportedUnormBit; return UINT32_MAX; } uint32_t mip_levels = texture.key.mip_max_level + 1; switch (texture.key.dimension) { case xenos::DataDimension::k1D: case xenos::DataDimension::k2DOrStacked: desc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2DARRAY; desc.Texture2DArray.MostDetailedMip = 0; desc.Texture2DArray.MipLevels = mip_levels; desc.Texture2DArray.FirstArraySlice = 0; desc.Texture2DArray.ArraySize = texture.key.depth; desc.Texture2DArray.PlaneSlice = 0; desc.Texture2DArray.ResourceMinLODClamp = 0.0f; break; case xenos::DataDimension::k3D: desc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE3D; desc.Texture3D.MostDetailedMip = 0; desc.Texture3D.MipLevels = mip_levels; desc.Texture3D.ResourceMinLODClamp = 0.0f; break; case xenos::DataDimension::kCube: desc.ViewDimension = D3D12_SRV_DIMENSION_TEXTURECUBE; desc.TextureCube.MostDetailedMip = 0; desc.TextureCube.MipLevels = mip_levels; desc.TextureCube.ResourceMinLODClamp = 0.0f; break; default: assert_unhandled_case(texture.key.dimension); return UINT32_MAX; } desc.Shader4ComponentMapping = host_swizzle | D3D12_SHADER_COMPONENT_MAPPING_ALWAYS_SET_BIT_AVOIDING_ZEROMEM_MISTAKES; auto device = command_processor_.GetD3D12Context().GetD3D12Provider().GetDevice(); uint32_t descriptor_index; if (bindless_resources_used_) { descriptor_index = command_processor_.RequestPersistentViewBindlessDescriptor(); if (descriptor_index == UINT32_MAX) { XELOGE( "Failed to create a texture descriptor - no free bindless view " "descriptors"); return UINT32_MAX; } } else { if (!srv_descriptor_cache_free_.empty()) { descriptor_index = srv_descriptor_cache_free_.back(); srv_descriptor_cache_free_.pop_back(); } else { // Allocated + 1 (including the descriptor that is being added), rounded // up to SRVDescriptorCachePage::kHeapSize, (allocated + 1 + size - 1). uint32_t cache_pages_needed = (srv_descriptor_cache_allocated_ + SRVDescriptorCachePage::kHeapSize) / SRVDescriptorCachePage::kHeapSize; if (srv_descriptor_cache_.size() < cache_pages_needed) { D3D12_DESCRIPTOR_HEAP_DESC cache_heap_desc; cache_heap_desc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV; cache_heap_desc.NumDescriptors = SRVDescriptorCachePage::kHeapSize; cache_heap_desc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_NONE; cache_heap_desc.NodeMask = 0; while (srv_descriptor_cache_.size() < cache_pages_needed) { SRVDescriptorCachePage cache_page; if (FAILED(device->CreateDescriptorHeap( &cache_heap_desc, IID_PPV_ARGS(&cache_page.heap)))) { XELOGE( "Failed to create a texture descriptor - couldn't create a " "descriptor cache heap"); return UINT32_MAX; } cache_page.heap_start = cache_page.heap->GetCPUDescriptorHandleForHeapStart(); srv_descriptor_cache_.push_back(cache_page); } } descriptor_index = srv_descriptor_cache_allocated_++; } } device->CreateShaderResourceView( texture.resource, &desc, GetTextureDescriptorCPUHandle(descriptor_index)); texture.srv_descriptors.emplace(descriptor_key, descriptor_index); return descriptor_index; } D3D12_CPU_DESCRIPTOR_HANDLE TextureCache::GetTextureDescriptorCPUHandle( uint32_t descriptor_index) const { auto& provider = command_processor_.GetD3D12Context().GetD3D12Provider(); if (bindless_resources_used_) { return provider.OffsetViewDescriptor( command_processor_.GetViewBindlessHeapCPUStart(), descriptor_index); } D3D12_CPU_DESCRIPTOR_HANDLE heap_start = srv_descriptor_cache_[descriptor_index / SRVDescriptorCachePage::kHeapSize] .heap_start; uint32_t heap_offset = descriptor_index % SRVDescriptorCachePage::kHeapSize; return provider.OffsetViewDescriptor(heap_start, heap_offset); } void TextureCache::MarkTextureUsed(Texture* texture) { uint64_t current_frame = command_processor_.GetCurrentFrame(); // This is called very frequently, don't relink unless needed for caching. if (texture->last_usage_frame != current_frame) { texture->last_usage_frame = current_frame; texture->last_usage_time = texture_current_usage_time_; if (texture->used_next == nullptr) { // Simplify the code a bit - already in the end of the list. return; } if (texture->used_previous != nullptr) { texture->used_previous->used_next = texture->used_next; } else { texture_used_first_ = texture->used_next; } texture->used_next->used_previous = texture->used_previous; texture->used_previous = texture_used_last_; texture->used_next = nullptr; if (texture_used_last_ != nullptr) { texture_used_last_->used_next = texture; } texture_used_last_ = texture; } } void TextureCache::WatchCallbackThunk(void* context, void* data, uint64_t argument, bool invalidated_by_gpu) { TextureCache* texture_cache = reinterpret_cast<TextureCache*>(context); texture_cache->WatchCallback(reinterpret_cast<Texture*>(data), argument != 0); } void TextureCache::WatchCallback(Texture* texture, bool is_mip) { // Mutex already locked here. if (is_mip) { texture->mips_in_sync = false; texture->mip_watch_handle = nullptr; } else { texture->base_in_sync = false; texture->base_watch_handle = nullptr; } texture_invalidated_.store(true, std::memory_order_release); } void TextureCache::ClearBindings() { for (size_t i = 0; i < xe::countof(texture_bindings_); ++i) { texture_bindings_[i].Clear(); } texture_bindings_in_sync_ = 0; // Already reset everything. texture_invalidated_.store(false, std::memory_order_relaxed); } bool TextureCache::IsRangeScaledResolved(uint32_t start_unscaled, uint32_t length_unscaled) { if (draw_resolution_scale_ <= 1) { return false; } start_unscaled = std::min(start_unscaled, SharedMemory::kBufferSize); length_unscaled = std::min(length_unscaled, SharedMemory::kBufferSize - start_unscaled); if (!length_unscaled) { return false; } // Two-level check for faster rejection since resolve targets are usually // placed in relatively small and localized memory portions (confirmed by // testing - pretty much all times the deeper level was entered, the texture // was a resolve target). uint32_t page_first = start_unscaled >> 12; uint32_t page_last = (start_unscaled + length_unscaled - 1) >> 12; uint32_t block_first = page_first >> 5; uint32_t block_last = page_last >> 5; uint32_t l2_block_first = block_first >> 6; uint32_t l2_block_last = block_last >> 6; auto global_lock = global_critical_region_.Acquire(); for (uint32_t i = l2_block_first; i <= l2_block_last; ++i) { uint64_t l2_block = scaled_resolve_pages_l2_[i]; if (i == l2_block_first) { l2_block &= ~((1ull << (block_first & 63)) - 1); } if (i == l2_block_last && (block_last & 63) != 63) { l2_block &= (1ull << ((block_last & 63) + 1)) - 1; } uint32_t block_relative_index; while (xe::bit_scan_forward(l2_block, &block_relative_index)) { l2_block &= ~(1ull << block_relative_index); uint32_t block_index = (i << 6) + block_relative_index; uint32_t check_bits = UINT32_MAX; if (block_index == block_first) { check_bits &= ~((1u << (page_first & 31)) - 1); } if (block_index == block_last && (page_last & 31) != 31) { check_bits &= (1u << ((page_last & 31) + 1)) - 1; } if (scaled_resolve_pages_[block_index] & check_bits) { return true; } } } return false; } void TextureCache::ScaledResolveGlobalWatchCallbackThunk( void* context, uint32_t address_first, uint32_t address_last, bool invalidated_by_gpu) { TextureCache* texture_cache = reinterpret_cast<TextureCache*>(context); texture_cache->ScaledResolveGlobalWatchCallback(address_first, address_last, invalidated_by_gpu); } void TextureCache::ScaledResolveGlobalWatchCallback(uint32_t address_first, uint32_t address_last, bool invalidated_by_gpu) { assert_true(draw_resolution_scale_ > 1); if (invalidated_by_gpu) { // Resolves themselves do exactly the opposite of what this should do. return; } // Mark scaled resolve ranges as non-scaled. Textures themselves will be // invalidated by their own per-range watches. uint32_t resolve_page_first = address_first >> 12; uint32_t resolve_page_last = address_last >> 12; uint32_t resolve_block_first = resolve_page_first >> 5; uint32_t resolve_block_last = resolve_page_last >> 5; uint32_t resolve_l2_block_first = resolve_block_first >> 6; uint32_t resolve_l2_block_last = resolve_block_last >> 6; for (uint32_t i = resolve_l2_block_first; i <= resolve_l2_block_last; ++i) { uint64_t resolve_l2_block = scaled_resolve_pages_l2_[i]; uint32_t resolve_block_relative_index; while ( xe::bit_scan_forward(resolve_l2_block, &resolve_block_relative_index)) { resolve_l2_block &= ~(1ull << resolve_block_relative_index); uint32_t resolve_block_index = (i << 6) + resolve_block_relative_index; uint32_t resolve_keep_bits = 0; if (resolve_block_index == resolve_block_first) { resolve_keep_bits |= (1u << (resolve_page_first & 31)) - 1; } if (resolve_block_index == resolve_block_last && (resolve_page_last & 31) != 31) { resolve_keep_bits |= ~((1u << ((resolve_page_last & 31) + 1)) - 1); } scaled_resolve_pages_[resolve_block_index] &= resolve_keep_bits; if (scaled_resolve_pages_[resolve_block_index] == 0) { scaled_resolve_pages_l2_[i] &= ~(1ull << resolve_block_relative_index); } } } } } // namespace d3d12 } // namespace gpu } // namespace xe
39.791098
87
0.697715
[ "render", "object", "3d" ]
67cb28dbcfa27ff547e3497a3162809d32215b84
5,636
cpp
C++
VoronoiVariant/src/ofApp.cpp
AmnonOwed/OF_GenerativeTypography
48d93403664d50688e5b0d6d452149240eb1ca30
[ "MIT" ]
103
2015-01-23T11:27:15.000Z
2022-02-10T02:16:38.000Z
VoronoiVariant/src/ofApp.cpp
sandblasted7/OF_GenerativeTypography
48d93403664d50688e5b0d6d452149240eb1ca30
[ "MIT" ]
null
null
null
VoronoiVariant/src/ofApp.cpp
sandblasted7/OF_GenerativeTypography
48d93403664d50688e5b0d6d452149240eb1ca30
[ "MIT" ]
15
2015-01-25T00:06:28.000Z
2017-08-14T02:48:49.000Z
#include "ofApp.h" //-------------------------------------------------------------- void ofApp::setup(){ saveOneFrame = false; // variable used to save a single frame as a PDF page reset = true; // variable used to reset/regenerate the voronoi shape ofBackground(255); ofEnableAntiAliasing(); ofEnableSmoothing(); ofSetFrameRate(60); ofTrueTypeFont ttf; // to extract points, loadFont must be called with makeContours set to true ttf.loadFont(OF_TTF_SANS, 275, true, false, true); string s = "TYPE"; // Center string code from: // https://github.com/armadillu/ofxCenteredTrueTypeFont/blob/master/src/ofxCenteredTrueTypeFont.h ofRectangle r = ttf.getStringBoundingBox(s, 0, 0); ofVec2f center = ofVec2f(floor(-r.x - r.width * 0.5f), floor(-r.y - r.height * 0.5f)); center.x += ofGetWidth() / 2; center.y += ofGetHeight() / 2; // get the string as paths, place all the text points in a vector vector <ofTTFCharacter> paths = ttf.getStringAsPoints(s); for(int i = 0; i < paths.size(); i++){ // for every character break it out to polylines vector <ofPolyline> polylines = paths[i].getOutline(); // for every polyline... for(int j = 0; j < polylines.size(); j++){ // resample polyline to enforce equal spacing between points ofPolyline spacePoly = polylines[j].getResampledBySpacing(25); // add all the points of the resampled polyline to the textPoints vector for(int k = 0; k < spacePoly.size(); k++){ // add center to each point to centralize the text placement textPoints.push_back(spacePoly[k] + center); } } } fbo_color = ofColor(0); ofFbo fbo; fbo.allocate(ofGetWidth(), ofGetHeight(), GL_RGBA); pix.allocate(ofGetWidth(), ofGetHeight(), OF_PIXELS_RGBA); fbo.begin(); ofClear(0, 0, 0, 0); ofSetColor(fbo_color); ttf.drawString(s, center.x, center.y); fbo.end(); fbo.readToPixels(pix); // the ofPixels class has a convenient getColor() method } //-------------------------------------------------------------- void ofApp::update(){ if(reset){ // clear voronoi voronoi.clear(); // add text points to the voronoi voronoi.addPoints(textPoints); // add random points to the voronoi vector <ofPoint> randomPoints = generateRandomPoints(225); voronoi.addPoints(randomPoints); // set the bounds of the voronoi ofRectangle bounds = ofRectangle(0, 0, ofGetWidth(), ofGetHeight()); voronoi.setBounds(bounds); // generate the voronoi voronoi.generate(); // store which cells/points are in the text vector <ofxVoronoiCell> cells = voronoi.getCells(); insideText.clear(); for(int i = 0; i < cells.size(); i++){ bool inside = isPointInList(cells[i].pt, textPoints); insideText.push_back(inside); } reset = false; } } //-------------------------------------------------------------- void ofApp::draw(){ if(saveOneFrame){ ofBeginSaveScreenAsPDF("VoronoiVariant-" + ofGetTimestampString() + ".pdf", false); } // scale the inner voronoi region shape based on the mouseX float scaleFactor = ofMap(ofClamp(ofGetMouseX(), 0, ofGetWidth()), 0, ofGetWidth(), 0, 1.15); // draw cells vector <ofxVoronoiCell> cells = voronoi.getCells(); for(int i = 0; i < cells.size(); i++){ if(insideText[i]){ vector <ofPoint> & cellPoints = cells[i].pts; // draw a straight voronoi region outline ofPath outline = ofPath(); outline.setFilled(false); outline.setStrokeColor(ofColor(0)); outline.setStrokeWidth(0.85); for(int j = 0; j < cellPoints.size(); j++){ ofPoint & thisPt = cellPoints[j]; if(j == 0){ outline.moveTo(thisPt); } else{ outline.lineTo(thisPt); } } outline.close(); outline.draw(); // calculate the center of the voronoi region ofPoint center; for(int j = 0; j < cellPoints.size(); j++){ ofPoint & thisPt = cellPoints[j]; center += thisPt; } center /= cellPoints.size(); // draw a curved, colored and scaled voronoi region ofPath path = ofPath(); ofSeedRandom(i * 1000000); ofColor fill_color; fill_color.setHsb(ofRandom(127.5, 165.75), ofRandom(89.25, 191.25), ofRandom(89.25, 216.75)); path.setFillColor(fill_color); path.setStrokeColor(ofColor(125)); path.setStrokeWidth(0.75); path.curveTo(cellPoints.back()); // control point for(int j = 0; j < cellPoints.size(); j++){ path.curveTo(cellPoints[j]); } path.curveTo(cellPoints[0]); // control point path.close(); path.translate(-center); path.scale(scaleFactor, scaleFactor); path.translate(center); path.draw(); } } if(saveOneFrame){ ofEndSaveScreenAsPDF(); saveOneFrame = false; } } //-------------------------------------------------------------- vector <ofPoint> ofApp::generateRandomPoints(int count){ vector <ofPoint> points; for(int i = 0; i < count; i++){ ofPoint newPoint = ofPoint(ofRandom(ofGetWidth()), ofRandom(ofGetHeight())); while(pix.getColor(newPoint.x, newPoint.y) == fbo_color){ newPoint = ofPoint(ofRandom(ofGetWidth()), ofRandom(ofGetHeight())); } points.push_back(newPoint); } return points; } //-------------------------------------------------------------- bool ofApp::isPointInList(const ofPoint & point, const vector <ofPoint> & pointList){ for(int i = 0; i < pointList.size(); i++){ if(point == pointList[i]){ return true; } } return false; } //-------------------------------------------------------------- void ofApp::keyPressed(int key){ if(key == 's'){ saveOneFrame = true; // set the variable to true to save a single frame as a PDF file / page } if(key == ' '){ reset = true; // set the variable to true to reset/regenerate the voronoi shape } }
30.139037
98
0.630767
[ "shape", "vector" ]
67d72f5b1538d8351ce41aab8d693fa048af79d9
1,592
cpp
C++
Dev02_Handout/Motor2D/j1Scene.cpp
AlbertCayuela/DevGame
643dbf249b33549cd243e76e549645bc2083f3d8
[ "MIT" ]
null
null
null
Dev02_Handout/Motor2D/j1Scene.cpp
AlbertCayuela/DevGame
643dbf249b33549cd243e76e549645bc2083f3d8
[ "MIT" ]
null
null
null
Dev02_Handout/Motor2D/j1Scene.cpp
AlbertCayuela/DevGame
643dbf249b33549cd243e76e549645bc2083f3d8
[ "MIT" ]
null
null
null
#include "p2Defs.h" #include "p2Log.h" #include "j1App.h" #include "j1Input.h" #include "j1Textures.h" #include "j1Audio.h" #include "j1Render.h" #include "j1Window.h" #include "j1Scene.h" j1Scene::j1Scene() : j1Module() { name.create("scene"); } // Destructor j1Scene::~j1Scene() {} // Called before render is available bool j1Scene::Awake() { LOG("Loading Scene"); bool ret = true; return ret; } // Called before the first frame bool j1Scene::Start() { img = App->tex->Load("textures/test.png"); App->audio->PlayMusic("audio/music/music_sadpiano.ogg"); return true; } // Called each loop iteration bool j1Scene::PreUpdate() { return true; } // Called each loop iteration bool j1Scene::Update(float dt) { // TODO 3: Call load / save methods when pressing L/S //if (App->input->GetKey(SDL_SCANCODE_S) == KEY_DOWN) //App->WantToSave(); //if (App->input->GetKey(SDL_SCANCODE_L) == KEY_DOWN) // App->WantToLoad(); if(App->input->GetKey(SDL_SCANCODE_UP) == KEY_REPEAT) App->render->camera.y -= 1; if(App->input->GetKey(SDL_SCANCODE_DOWN) == KEY_REPEAT) App->render->camera.y += 1; if(App->input->GetKey(SDL_SCANCODE_LEFT) == KEY_REPEAT) App->render->camera.x -= 1; if(App->input->GetKey(SDL_SCANCODE_RIGHT) == KEY_REPEAT) App->render->camera.x += 1; App->render->Blit(img, 0, 0); return true; } // Called each loop iteration bool j1Scene::PostUpdate() { bool ret = true; if(App->input->GetKey(SDL_SCANCODE_ESCAPE) == KEY_DOWN) ret = false; return ret; } // Called before quitting bool j1Scene::CleanUp() { LOG("Freeing scene"); return true; }
18.298851
57
0.680905
[ "render" ]
67da89ae276d9ba27245d769b0ca941a4589b671
4,266
cpp
C++
SPOJ/SPOJ/PRESIDEN.cpp
aqfaridi/Competitve-Programming-Codes
d055de2f42d3d6bc36e03e67804a1dd6b212241f
[ "MIT" ]
null
null
null
SPOJ/SPOJ/PRESIDEN.cpp
aqfaridi/Competitve-Programming-Codes
d055de2f42d3d6bc36e03e67804a1dd6b212241f
[ "MIT" ]
null
null
null
SPOJ/SPOJ/PRESIDEN.cpp
aqfaridi/Competitve-Programming-Codes
d055de2f42d3d6bc36e03e67804a1dd6b212241f
[ "MIT" ]
null
null
null
/******************************* // Name : Abdul Qadir Faridi // IPG-3rd yr // Institute : ABV-IIITM,Gwalior *********************************/ //header files #include <iostream> #include <cstdio> #include <cstring> #include <cmath> #include <cstdlib> #include <climits> #include <cassert> #include <iomanip> #include <vector> #include <utility> #include <map> #include <set> #include <list> #include <stack> #include <queue> #include <deque> #include <bitset> #include <complex> #include <numeric> #include <functional> #include <sstream> #include <algorithm> //Preprocessor directives #define MAX 1000010 #define MOD 1000000007 #define gc getchar_unlocked //macros input-output #define si(n) scanf("%d",&n) #define sll(n) scanf("%lld",&n) #define sf(n) scanf("%f",&n) #define ss(str) scanf("%s",str) #define sd(n) scanf("%lf",&n) #define INF INT_MAX #define LINF (LL)1e18 #define maX(a,b) ((a)>(b)?(a):(b)) #define miN(a,b) ((a)<(b)?(a):(b)) #define abS(x) ((x)<0?-(x):(x)) #define forr(i,a,b) for(int i=a;i<b;i++) #define rep(i,n) forr(i,0,n) #define pn() printf("\n") #define pi(n) printf("%d",n) #define pll(n) printf("%lld",n) #define pd(n) printf("%lf",n) #define ps(str) printf("%s",str) //macros stl #define mp make_pair #define tri(a,b,c) mp(a,mp(b,c)) #define pb push_back #define fill(a,v) memset(a,v,sizeof a) #define all(x) x.begin(),x.end() #define uniq(v) sort(all(v));v.erase(unique(all(v)),v.end()) #define findval(arr,val) (lower_bound(all(arr)),val)-arr.begin() #define clr(a) memset(a,0,sizeof a) //debug #define debug if(1) #define debugoff if(0) //constants #define PI M_PI #define E M_E using namespace std; //typedef typedef long long LL; typedef unsigned long long uLL; typedef pair<int,int> pii; typedef pair<LL,LL> pll; typedef pair<int,pii> tri; //FAST io #define input(n) read(&n) /** void read(int *x) { register int c = gc(); *x = 0; for(;(c<48 || c>57);c = gc()); for(;c>47 && c<58;c = gc()) {*x = (*x<<1) + (*x<<3) + c - 48;} } **/ int pref[200][200],vote[200]; int main() { int t; int n,c,v,max1,max2,pos1,pos2; si(t); while(t--) { clr(vote); si(c);si(v); for(int i=1;i<=v;i++) for(int j=1;j<=c;j++) si(pref[i][j]); debugoff rep(i,v+1) { rep(j,c+1) cout<<pref[i][j]<<" "; cout<<endl; } for(int i=1;i<=v;i++) vote[pref[i][1]]++; max1 = max2 = 0; pos1 = pos2 = 0; for(int j=1;j<=c;j++) if(vote[j] > max1) { max1 = vote[j]; pos1 = j; } vote[pos1] = -1; for(int j=1;j<=c;j++) if(vote[j] > max2) { max2 = vote[j]; pos2 = j; } //cout<<max1<<" "<<max2<<endl; if(max1>max2 && max1 > v/2) printf("%d 1\n",pos1); else { clr(vote); for(int i=1;i<=v;i++) for(int j=1;j<=c;j++) { if(pref[i][j] == pos1) { vote[pos1]++; break; } else if(pref[i][j] == pos2) { vote[pos2]++; break; } } if(vote[pos1] > vote[pos2]) printf("%d 2\n",pos1); else if(vote[pos2] > vote[pos1]) printf("%d 2\n",pos2); } } return 0; }
24.802326
80
0.401547
[ "vector" ]
67dfc5f297903d315ce22e45f96fecfc9887d579
19,971
cpp
C++
softSelectionQueryCmd/src/softSelectionQueryCmd.cpp
WebberHuang/SoftClusterEX
05a76a290260a90625f44b73c55d5b71d4b06b65
[ "BSD-3-Clause" ]
26
2015-05-23T09:01:59.000Z
2021-09-02T06:24:50.000Z
softSelectionQueryCmd/src/softSelectionQueryCmd.cpp
WebberHuang/SoftClusterEX
05a76a290260a90625f44b73c55d5b71d4b06b65
[ "BSD-3-Clause" ]
null
null
null
softSelectionQueryCmd/src/softSelectionQueryCmd.cpp
WebberHuang/SoftClusterEX
05a76a290260a90625f44b73c55d5b71d4b06b65
[ "BSD-3-Clause" ]
21
2015-03-18T14:54:02.000Z
2021-04-15T08:52:22.000Z
/* #---------------------------------------------------------------------- # This file is part of "Soft Cluster EX" # and covered by a BSD-style license, check # LICENSE for detail. # # Author: Webber Huang # Contact: xracz.fx@gmail.com # Homepage: http://riggingtd.com #---------------------------------------------------------------------- */ #include "softSelectionQueryCmd.h" #include <maya/MObject.h> #include <maya/MGlobal.h> #include <maya/MString.h> #include <maya/MStringArray.h> #include <maya/MDoubleArray.h> #include <maya/MFn.h> #include <maya/MDagPath.h> #include <maya/MFnDagNode.h> #include <maya/MFnDependencyNode.h> #include <maya/MRichSelection.h> #include <maya/MSelectionList.h> #include <maya/MStatus.h> #include <maya/MSyntax.h> #include <maya/MArgDatabase.h> #include <maya/MArgList.h> #include <maya/MArgDatabase.h> #include <maya/MItSelectionList.h> #include <maya/MItGeometry.h> #include <maya/MItMeshVertex.h> #include <maya/MItCurveCV.h> #include <maya/MItSurfaceCV.h> #include <maya/MItSubdVertex.h> #include <maya/MFnSingleIndexedComponent.h> #include <maya/MFnDoubleIndexedComponent.h> #include <maya/MFnTripleIndexedComponent.h> #include <maya/MFnUint64SingleIndexedComponent.h> #include <math.h> #define cAllPathFlag "-ap" #define cAllPathFlagLong "-allPaths" #define cLongnameFlag "-l" #define cLongnameFlagLong "-long" #define cSelectionFlag "-sl" #define cSelectionFlagLong "-selection" #define cTransformsFlag "-tr" #define cTransformsFlagLong "-transforms" #define cShapesFlag "-s" #define cShapesFlagLong "-shapes" #define cVerticesFlag "-vtx" #define cVerticesFlagLong "-vertices" #define cWeightFlag "-w" #define cWeightFlagLong "-weights" #define cCountFlag "-c" #define cCountFlagLong "-count" #define cTypeFlag "-t" #define cTypeFlagLong "-types" #define cNodeTypeFlag "-nt" #define cNodeTypeFlagLong "-nodeTypes" #define cAPINodeTypeFlag "-ant" #define cAPINodeTypeFlagLong "-apiNodeTypes" #define cExcludeObjectFlag "-exo" #define cExcludeObjectFlagLong "-excludeObjects" static const char* SUPPORT_TYPE[] = {"mesh", "nurbsSurface", "nurbsCurve", "lattice", "subdiv"}; SoftSelectionQueryCmd::~SoftSelectionQueryCmd(){} void* SoftSelectionQueryCmd::creator() { return new SoftSelectionQueryCmd; } MSyntax SoftSelectionQueryCmd::cmdSyntax() { MSyntax syntax; syntax.addFlag(cAllPathFlag, cAllPathFlagLong); syntax.addFlag(cLongnameFlag, cLongnameFlagLong); syntax.addFlag(cSelectionFlag, cSelectionFlagLong); syntax.addFlag(cTransformsFlag, cTransformsFlagLong); syntax.addFlag(cShapesFlag, cShapesFlagLong); syntax.addFlag(cVerticesFlag, cVerticesFlagLong); syntax.addFlag(cWeightFlag, cWeightFlagLong); syntax.addFlag(cCountFlag, cCountFlagLong); syntax.addFlag(cTypeFlag, cTypeFlagLong, MSyntax::kString); syntax.addFlag(cNodeTypeFlag, cNodeTypeFlagLong); syntax.addFlag(cAPINodeTypeFlag, cAPINodeTypeFlagLong); syntax.addFlag(cExcludeObjectFlag, cExcludeObjectFlagLong, MSyntax::kString); syntax.makeFlagMultiUse(cExcludeObjectFlag); syntax.makeFlagMultiUse(cTypeFlag); syntax.setObjectType(MSyntax::kSelectionList); syntax.useSelectionAsDefault(true); return syntax; } MStatus SoftSelectionQueryCmd::parseArgs(const MArgList& argList) { // parse syntax MStatus status; MArgDatabase argDB(syntax(), argList, &status); returnAllPath = argDB.isFlagSet(cAllPathFlag); returnLongname = argDB.isFlagSet(cLongnameFlag); returnSelection = argDB.isFlagSet(cSelectionFlag); returnTransforms = argDB.isFlagSet(cTransformsFlag); returnShapes = argDB.isFlagSet(cShapesFlag); returnVertices = argDB.isFlagSet(cVerticesFlag); returnWeight = argDB.isFlagSet(cWeightFlag); returnNodeType = argDB.isFlagSet(cNodeTypeFlag); returnAPINodeType = argDB.isFlagSet(cAPINodeTypeFlag); returnCount = argDB.isFlagSet(cCountFlag); if (argDB.isFlagSet(cTypeFlag)) { specifyTypeArray = retrieveStringArrayFromMultiFlag(argDB, cTypeFlag); } else { const size_t len = sizeof(SUPPORT_TYPE) / sizeof(SUPPORT_TYPE[0]); for(int i=0; i < len; i++) { specifyTypeArray.append(SUPPORT_TYPE[i]); } } excludeObjectArray = retrieveStringArrayFromMultiFlag(argDB, cExcludeObjectFlag); return status; } MStatus SoftSelectionQueryCmd::doIt( const MArgList& argList ) { // parse syntax MStatus status = parseArgs(argList); if (status != MS::kSuccess) { return MS::kFailure; } // MSelectionList selection; MRichSelection softSelection; MGlobal::getRichSelection(softSelection); softSelection.getSelection(selection); // MDagPath dagPath; MObject component; MItSelectionList iter(selection); count = 0; while(!iter.isDone()) { iter.getDagPath(dagPath, component); bool isTransform = false; if (dagPath.hasFn(MFn::kTransform)) { dagPath = getShapeDagPath(dagPath); isTransform = true; } MFnDagNode dagNodeFn(dagPath); // get parent dagPath MDagPath parentDagPath = getParentDagPath(dagPath); MFnDagNode parentDagNodeFn(parentDagPath); // skip the un-support type if (!isStrItemInArray(dagNodeFn.typeName(), specifyTypeArray)) { iter.next(); continue; } // skip the exclusive objects if (isExcludeObject(parentDagNodeFn.fullPathName(), excludeObjectArray)) { iter.next(); continue; } // store result getBaseData(dagPath); switch (dagPath.apiType()) { case MFn::kMesh: { getDataFromPolygon(dagPath, component, isTransform); break; } case MFn::kNurbsCurve: { getDataFromNurbsCurve(dagPath, component, isTransform); break; } case MFn::kNurbsSurface: { getDataFromNurbsSurface(dagPath, component, isTransform); break; } case MFn::kSubdiv: { getDataFromSubdiv(dagPath, component, isTransform); break; } case MFn::kLattice: { getDataFromLattice(dagPath, component, isTransform); break; } default: break; } iter.next(); } // set results if (returnSelection) { setResult(transformArray); appendToResult(vertexArray); } if (returnTransforms) { setResult(transformArray); } if (returnShapes) { setResult(shapeArray); } if (returnNodeType) { setResult(nodeTypeArray); } if (returnAPINodeType) { setResult(apiNodeTypeArray); } if (returnCount) { setResult(count); } if (returnVertices) { setResult(vertexArray); } if (returnWeight) { setResult(weightArray); } return MStatus::kSuccess; } MObject SoftSelectionQueryCmd::nameToMObject(const MString& name) { MSelectionList selList; selList.add (name); MObject node; selList.getDependNode(0, node); return node; } MStringArray SoftSelectionQueryCmd::retrieveStringArrayFromMultiFlag(MArgDatabase& argDB, const MString& flag) { MStatus status; MArgList argList; MStringArray strArray; int index = 0; while (true) { MString itemName; status = argDB.getFlagArgumentList( flag.asChar(), index, argList ); if (status == MStatus::kSuccess) { itemName = argList.asString(index); strArray.append(itemName); } else { break; } index++; } return strArray; } MDagPath SoftSelectionQueryCmd::getShapeDagPath(const MDagPath& dagPath) { MObject childObj = dagPath.child(0); MFnDagNode dagNodeFn(childObj); MDagPath shapeDagPath; dagNodeFn.getPath(shapeDagPath); return shapeDagPath; } MDagPath SoftSelectionQueryCmd::getParentDagPath(const MDagPath& dagPath) { MObject transformObj = dagPath.transform(); MFnDagNode parentDagNodeFn(transformObj); MDagPath parentDagPath; parentDagNodeFn.getPath(parentDagPath); return parentDagPath; } bool SoftSelectionQueryCmd::isStrItemInArray(const MString& item, const MStringArray& strArray) { for(unsigned int i=0; i < strArray.length(); i++) { if (item == strArray[i]) { return true; } } return false; } bool SoftSelectionQueryCmd::isExcludeObject(const MString& item, const MStringArray& strArray) { MObject itemObj = nameToMObject(item); MFnDagNode dagFn(itemObj); for(unsigned int i = 0; i < strArray.length(); i++) { MObject currObj = nameToMObject(strArray[i]); if (itemObj == currObj || dagFn.isChildOf(currObj)) { return true; } } return false; } void SoftSelectionQueryCmd::getBaseData(MDagPath& dagPath) { MFnDagNode dagNodeFn(dagPath); MObject obj = dagPath.node(); // get parent dagPath MDagPath parentDagPath = getParentDagPath(dagPath); MFnDagNode parentDagNodeFn(parentDagPath); // set data if (returnLongname) { transformArray.append(parentDagNodeFn.fullPathName()); shapeArray.append(dagNodeFn.fullPathName()); } else if (returnAllPath) { transformArray.append(parentDagNodeFn.partialPathName()); shapeArray.append(dagNodeFn.partialPathName()); } else { transformArray.append(parentDagNodeFn.name()); shapeArray.append(dagNodeFn.name()); } nodeTypeArray.append(dagNodeFn.typeName()); apiNodeTypeArray.append(obj.apiTypeStr()); count++; } void SoftSelectionQueryCmd::getDataFromLattice(MDagPath& dagPath, MObject& component, bool isTransform=false) { int s, t, u; MFnTripleIndexedComponent tripleCompFn(component); MDagPath parentDagPath = getParentDagPath(dagPath); MFnDagNode parentDagNodeFn(parentDagPath); if (isTransform) { MItGeometry geoIter(dagPath); while (!geoIter.isDone()) { MObject currItem = geoIter.currentItem(); MFnTripleIndexedComponent tripleCompFn(currItem); tripleCompFn.getElement(0, s, t, u); weightArray.append(1.0); if (returnAllPath) { vertexArray.append(parentDagNodeFn.partialPathName() + MString(".pt[") + s + MString("][") + t + MString("][") + u + MString("]")); } else if (returnLongname) { vertexArray.append(parentDagNodeFn.fullPathName() + MString(".pt[") + s + MString("][") + t + MString("][") + u + MString("]")); } else vertexArray.append(parentDagNodeFn.name() + MString(".pt[") + s + MString("][") + t + MString("][") + u + MString("]")); geoIter.next(); } } else { for(int i = 0; i < tripleCompFn.elementCount(); i++) { tripleCompFn.getElement(i, s, t, u); weightArray.append(tripleCompFn.weight(i).influence()); if (returnAllPath) { vertexArray.append(parentDagNodeFn.partialPathName() + MString(".pt[") + s + MString("][") + t + MString("][") + u + MString("]")); } else if (returnLongname) { vertexArray.append(parentDagNodeFn.fullPathName() + MString(".pt[") + s + MString("][") + t + MString("][") + u + MString("]")); } else vertexArray.append(parentDagNodeFn.name() + MString(".pt[") + s + MString("][") + t + MString("][") + u + MString("]")); } } } void SoftSelectionQueryCmd::getDataFromSubdiv(MDagPath& dagPath, MObject& component, bool isTransform=false) { int u, v; MFnUint64SingleIndexedComponent uSingleCompFn(component); MDagPath parentDagPath = getParentDagPath(dagPath); MFnDagNode parentDagNodeFn(parentDagPath); if (isTransform) { MItGeometry geoIter(dagPath); while (!geoIter.isDone()) { MObject currItem = geoIter.currentItem(); MFnUint64SingleIndexedComponent uSingleCompFn(currItem); MUint64 element = uSingleCompFn.element(0); u = element / pow((double)2,32); v = (int)element; weightArray.append(1.0); if (returnAllPath) { vertexArray.append(parentDagNodeFn.partialPathName() + MString(".smp[") + u + MString("][") + v + MString("]")); } else if (returnLongname) { vertexArray.append(parentDagNodeFn.fullPathName() + MString(".smp[") + u + MString("][") + v + MString("]")); } else vertexArray.append(parentDagNodeFn.name() + MString(".smp[") + u + MString("][") + v + MString("]")); geoIter.next(); } } else { for(int i = 0; i < uSingleCompFn.elementCount(); i++) { MUint64 element = uSingleCompFn.element(i); u = element / pow((double)2,32); v = (int)element; weightArray.append(uSingleCompFn.weight(i).influence()); if (returnAllPath) { vertexArray.append(parentDagNodeFn.partialPathName() + MString(".smp[") + u + MString("][") + v + MString("]")); } else if (returnLongname) { vertexArray.append(parentDagNodeFn.fullPathName() + MString(".smp[") + u + MString("][") + v + MString("]")); } else vertexArray.append(parentDagNodeFn.name() + MString(".smp[") + u + MString("][") + v + MString("]")); } } } void SoftSelectionQueryCmd::getDataFromNurbsSurface(MDagPath& dagPath, MObject& component, bool isTransform=false) { int u, v; MFnDoubleIndexedComponent doubleCompFn(component); MDagPath parentDagPath = getParentDagPath(dagPath); MFnDagNode parentDagNodeFn(parentDagPath); // if (isTransform) { MItGeometry geoIter(dagPath); while (!geoIter.isDone()) { MObject currItem = geoIter.currentItem(); MFnDoubleIndexedComponent doubleCompFn(currItem); doubleCompFn.getElement(0, u, v); weightArray.append(1.0); if (returnAllPath) { vertexArray.append(parentDagNodeFn.partialPathName() + MString(".cv[") + u + MString("][") + v + MString("]")); } else if (returnLongname) { vertexArray.append(parentDagNodeFn.fullPathName() + MString(".cv[") + u + MString("][") + v + MString("]")); } else vertexArray.append(parentDagNodeFn.name() + MString(".cv[") + u + MString("][") + v + MString("]")); geoIter.next(); } } else { for(int i = 0; i < doubleCompFn.elementCount(); i++) { doubleCompFn.getElement(i, u, v); weightArray.append(doubleCompFn.weight(i).influence()); if (returnAllPath) { vertexArray.append(parentDagNodeFn.partialPathName() + MString(".cv[") + u + MString("][") + v + MString("]")); } else if (returnLongname) { vertexArray.append(parentDagNodeFn.fullPathName() + MString(".cv[") + u + MString("][") + v + MString("]")); } else vertexArray.append(parentDagNodeFn.name() + MString(".cv[") + u + MString("][") + v + MString("]")); } } } void SoftSelectionQueryCmd::getDataFromNurbsCurve(MDagPath& dagPath, MObject& component, bool isTransform=false) { int index; MFnSingleIndexedComponent singleCompFn(component); MDagPath parentDagPath = getParentDagPath(dagPath); MFnDagNode parentDagNodeFn(parentDagPath); if (isTransform) { MItGeometry geoIter(dagPath); while (!geoIter.isDone()) { MObject currItem = geoIter.currentItem(); MFnSingleIndexedComponent singleCompFn(currItem); index = singleCompFn.element(0); weightArray.append(1.0); if (returnAllPath) { vertexArray.append(parentDagNodeFn.partialPathName() + MString(".cv[") + index + MString("]")); } else if (returnLongname) { vertexArray.append(parentDagNodeFn.fullPathName() + MString(".cv[") + index + MString("]")); } else vertexArray.append(parentDagNodeFn.name() + MString(".cv[") + index + MString("]")); geoIter.next(); } } else { for(int i = 0; i < singleCompFn.elementCount(); i++) { index = singleCompFn.element(i); weightArray.append(singleCompFn.weight(i).influence()); if (returnAllPath) { vertexArray.append(parentDagNodeFn.partialPathName() + MString(".cv[") + index + MString("]")); } else if (returnLongname) { vertexArray.append(parentDagNodeFn.fullPathName() + MString(".cv[") + index + MString("]")); } else vertexArray.append(parentDagNodeFn.name() + MString(".cv[") + index + MString("]")); } } } void SoftSelectionQueryCmd::getDataFromPolygon(MDagPath& dagPath, MObject& component, bool isTransform=false) { int index; MFnSingleIndexedComponent singleCompFn(component); MDagPath parentDagPath = getParentDagPath(dagPath); MFnDagNode parentDagNodeFn(parentDagPath); if (isTransform) { MItGeometry geoIter(dagPath); while (!geoIter.isDone()) { MObject currItem = geoIter.currentItem(); MFnSingleIndexedComponent singleCompFn(currItem); index = singleCompFn.element(0); weightArray.append(1.0); if (returnAllPath) { vertexArray.append(parentDagNodeFn.partialPathName() + MString(".vtx[") + index + MString("]")); } else if (returnLongname) { vertexArray.append(parentDagNodeFn.fullPathName() + MString(".vtx[") + index + MString("]")); } else vertexArray.append(parentDagNodeFn.name() + MString(".vtx[") + index + MString("]")); geoIter.next(); } } else { for(int i = 0; i < singleCompFn.elementCount(); i++) { index = singleCompFn.element(i); weightArray.append(singleCompFn.weight(i).influence()); if (returnAllPath) { vertexArray.append(parentDagNodeFn.partialPathName() + MString(".vtx[") + index + MString("]")); } else if (returnLongname) { vertexArray.append(parentDagNodeFn.fullPathName() + MString(".vtx[") + index + MString("]")); } else vertexArray.append(parentDagNodeFn.name() + MString(".vtx[") + index + MString("]")); } } }
31.450394
147
0.584548
[ "mesh", "transform" ]
67e125ad0dbda5d8883fd5e773a2242699e33037
6,425
cpp
C++
3DRacer/openglwindow.cpp
Isaquelc/abcg
cc92c5efd1fcfad78239edf9c16b92ea252b25c9
[ "MIT" ]
null
null
null
3DRacer/openglwindow.cpp
Isaquelc/abcg
cc92c5efd1fcfad78239edf9c16b92ea252b25c9
[ "MIT" ]
null
null
null
3DRacer/openglwindow.cpp
Isaquelc/abcg
cc92c5efd1fcfad78239edf9c16b92ea252b25c9
[ "MIT" ]
null
null
null
#include "openglwindow.hpp" #include "gamedata.hpp" #include <fmt/core.h> #include <imgui.h> #include <tiny_obj_loader.h> #include <cppitertools/itertools.hpp> #include <glm/gtx/fast_trigonometry.hpp> #include <glm/gtx/hash.hpp> #include <unordered_map> // Explicit specialization of std::hash for Vertex namespace std { template <> struct hash<Vertex> { size_t operator()(Vertex const& vertex) const noexcept { const std::size_t h1{std::hash<glm::vec3>()(vertex.position)}; return h1; } }; } // namespace std void OpenGLWindow::handleEvent(SDL_Event& ev) { if (ev.type == SDL_KEYDOWN) { if (ev.key.keysym.sym == SDLK_LEFT || ev.key.keysym.sym == SDLK_a) m_gameData.m_input.set(static_cast<size_t>(Input::Left)); if (ev.key.keysym.sym == SDLK_RIGHT || ev.key.keysym.sym == SDLK_d) m_gameData.m_input.set(static_cast<size_t>(Input::Right)); } if (ev.type == SDL_KEYUP) { if (ev.key.keysym.sym == SDLK_LEFT || ev.key.keysym.sym == SDLK_a) m_gameData.m_input.reset(static_cast<size_t>(Input::Left)); if (ev.key.keysym.sym == SDLK_RIGHT || ev.key.keysym.sym == SDLK_d) m_gameData.m_input.reset(static_cast<size_t>(Input::Right)); } } void OpenGLWindow::initializeGL() { // Load a new font ImGuiIO &io{ImGui::GetIO()}; auto filename{getAssetsPath() + "Inconsolata-Medium.ttf"}; m_font = io.Fonts->AddFontFromFileTTF(filename.c_str(), 60.0f); if (m_font == nullptr) { throw abcg::Exception{abcg::Exception::Runtime("Cannot load font file")}; } abcg::glClearColor(0, 0, 0, 1); // Enable depth buffering abcg::glEnable(GL_DEPTH_TEST); // Create program m_program = createProgramFromFile(getAssetsPath() + "depth.vert", getAssetsPath() + "depth.frag"); // Load model m_player.loadObj(getAssetsPath() + "DeLorean_DMC-12_V2.obj"); m_enemies.loadObj(getAssetsPath() + "DeLorean_DMC-12_V2.obj"); m_player.initializeGL(m_program); m_enemies.initializeGL(m_program); m_ground.initializeGL(m_program); resizeGL(getWindowSettings().width, getWindowSettings().height); } void OpenGLWindow::paintGL() { update(); // Clear color buffer and depth buffer abcg::glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); abcg::glViewport(0, 0, m_viewportWidth, m_viewportHeight); abcg::glUseProgram(m_program); // Get location of uniform variables (could be precomputed) const GLint viewMatrixLoc{abcg::glGetUniformLocation(m_program, "viewMatrix")}; const GLint projMatrixLoc{abcg::glGetUniformLocation(m_program, "projMatrix")}; // Set uniform variables for viewMatrix and projMatrix // These matrices are used for every scene object abcg::glUniformMatrix4fv(viewMatrixLoc, 1, GL_FALSE, &m_camera.m_viewMatrix[0][0]); abcg::glUniformMatrix4fv(projMatrixLoc, 1, GL_FALSE, &m_camera.m_projMatrix[0][0]); m_ground.paintGL(); m_player.paintGL(); m_enemies.paintGL(); abcg::glUseProgram(0); } void OpenGLWindow::paintUI() { abcg::OpenGLWindow::paintUI(); { if (m_gameData.m_state == State::GameOver) { auto size{ImVec2(400, 400)}; auto position{ImVec2((m_viewportWidth - size.x) / 2.0f, (m_viewportHeight - size.y) / 2.0f)}; ImGui::SetNextWindowPos(position); ImGui::SetNextWindowSize(size); ImGuiWindowFlags flags{ImGuiWindowFlags_NoBackground | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoInputs}; ImGui::Begin(" ", nullptr, flags); ImGui::PushFont(m_font); ImGui::Text("Game Over\nYour Score:\n%.2f Km", m_gameData.gameScore); } if (m_gameData.m_state == State::Playing) { auto size{ImVec2(600, 600)}; auto position{ImVec2((m_viewportWidth - size.x) / 2.0f, (m_viewportHeight - size.y) / 2.0f)}; ImGui::SetNextWindowPos(position); ImGui::SetNextWindowSize(size); ImGuiWindowFlags flags{ImGuiWindowFlags_NoBackground | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoInputs}; ImGui::Begin(" ", nullptr, flags); ImGui::PushFont(m_font); ImGui::Text("Score:%.2f Km", m_gameData.gameScore); } ImGui::PopFont(); ImGui::End(); } } void OpenGLWindow::resizeGL(int width, int height) { m_viewportWidth = width; m_viewportHeight = height; m_camera.computeProjectionMatrix(width, height); } void OpenGLWindow::terminateGL() { m_ground.terminateGL(); m_player.terminateGL(); m_enemies.terminateGL(); abcg::glDeleteProgram(m_program); abcg::glDeleteBuffers(1, &m_EBO); abcg::glDeleteBuffers(1, &m_VBO); abcg::glDeleteVertexArrays(1, &m_VAO); } void OpenGLWindow::restart() { m_gameData.m_state = State::Playing; // reset score m_gameData.gameScore = 0; m_ground.initializeGL(m_program); m_player.initializeGL(m_program); m_enemies.initializeGL(m_program); } void OpenGLWindow::update() { const float deltaTime{static_cast<float>(getDeltaTime())}; // increase score if (m_gameData.m_state == State::Playing) { m_gameData.gameScore += 0.1 * deltaTime; m_player.update(m_gameData, deltaTime); m_enemies.update(deltaTime); m_ground.update(deltaTime); checkCollisions(); } // Wait 5 seconds before restarting if (m_gameData.m_state != State::Playing && m_restartWaitTimer.elapsed() > 3) { restart(); return; } m_camera.computeViewMatrix(); } void OpenGLWindow::checkCollisions() { // Check collision between Player and enemies for (const auto index : iter::range(m_enemies.m_numCars)) { auto &position{m_enemies.m_enemiesPositions.at(index)}; const auto distance_x{std::abs(glm::distance(m_player.m_translation.x, position.x))}; const auto distance_z{std::abs(glm::distance(m_player.m_translation.z, position.z))}; if (distance_x < 0.7 && distance_z < 2.25) { m_gameData.m_state = State::GameOver; m_restartWaitTimer.restart(); } } }
33.994709
106
0.636732
[ "object", "model" ]
67e53295823375677211ee5c1d05bbd06fc38c0e
3,142
cc
C++
src/Features2d.cc
ATLCTO/node-opencv
028f3a336fe20729ffb3d084e22b8f331edd163a
[ "MIT" ]
null
null
null
src/Features2d.cc
ATLCTO/node-opencv
028f3a336fe20729ffb3d084e22b8f331edd163a
[ "MIT" ]
null
null
null
src/Features2d.cc
ATLCTO/node-opencv
028f3a336fe20729ffb3d084e22b8f331edd163a
[ "MIT" ]
null
null
null
#include "OpenCV.h" #if ((CV_MAJOR_VERSION == 2) && (CV_MINOR_VERSION >=4)) #include "Features2d.h" #include "Matrix.h" #include <nan.h> #include <stdio.h> #ifdef HAVE_OPENCV_FEATURES2D void Features::Init(Local<Object> target) { Nan::HandleScope scope; Nan::SetMethod(target, "ImageSimilarity", Similarity); } class AsyncDetectSimilarity: public Nan::AsyncWorker { public: AsyncDetectSimilarity(Nan::Callback *callback, Matrix *image1, Matrix *image2) : Nan::AsyncWorker(callback), image1(new Matrix(image1)), image2(new Matrix(image2)), dissimilarity(0) { } ~AsyncDetectSimilarity() { } void Execute() { cv::Ptr<cv::FeatureDetector> detector = cv::FeatureDetector::create("ORB"); cv::Ptr<cv::DescriptorExtractor> extractor = cv::DescriptorExtractor::create("ORB"); cv::Ptr<cv::DescriptorMatcher> matcher = cv::DescriptorMatcher::create( "BruteForce-Hamming"); std::vector<cv::DMatch> matches; cv::Mat descriptors1 = cv::Mat(); cv::Mat descriptors2 = cv::Mat(); std::vector<cv::KeyPoint> keypoints1; std::vector<cv::KeyPoint> keypoints2; detector->detect(image1->mat, keypoints1); detector->detect(image2->mat, keypoints2); extractor->compute(image1->mat, keypoints1, descriptors1); extractor->compute(image2->mat, keypoints2, descriptors2); matcher->match(descriptors1, descriptors2, matches); double max_dist = 0; double min_dist = 100; //-- Quick calculation of max and min distances between keypoints for (int i = 0; i < descriptors1.rows; i++) { double dist = matches[i].distance; if (dist < min_dist) { min_dist = dist; } if (dist > max_dist) { max_dist = dist; } } //-- Draw only "good" matches (i.e. whose distance is less than 2*min_dist, //-- or a small arbitary value ( 0.02 ) in the event that min_dist is very //-- small) //-- PS.- radiusMatch can also be used here. std::vector<cv::DMatch> good_matches; double good_matches_sum = 0.0; for (int i = 0; i < descriptors1.rows; i++) { double distance = matches[i].distance; if (distance <= std::max(2 * min_dist, 0.02)) { good_matches.push_back(matches[i]); good_matches_sum += distance; } } dissimilarity = (double) good_matches_sum / (double) good_matches.size(); } void HandleOKCallback() { Nan::HandleScope scope; delete image1; delete image2; image1 = NULL; image2 = NULL; Local<Value> argv[2]; argv[0] = Nan::Null(); argv[1] = Nan::New<Number>(dissimilarity); callback->Call(2, argv); } private: Matrix *image1; Matrix *image2; double dissimilarity; }; NAN_METHOD(Features::Similarity) { Nan::HandleScope scope; REQ_FUN_ARG(2, cb); Matrix *image1 = Nan::ObjectWrap::Unwrap<Matrix>(info[0]->ToObject()); Matrix *image2 = Nan::ObjectWrap::Unwrap<Matrix>(info[1]->ToObject()); Nan::Callback *callback = new Nan::Callback(cb.As<Function>()); Nan::AsyncQueueWorker( new AsyncDetectSimilarity(callback, image1, image2) ); return; } #endif #endif
25.544715
82
0.650541
[ "object", "vector" ]
67ea375e1b1af1bb3ede1a6a538132239c577e0e
14,667
cpp
C++
src/backends/odbc/vector-use-type.cpp
ChainSQL/soci
d4d50d65002ec2fb1486622634c31234b5f05686
[ "BSL-1.0" ]
3
2020-05-29T04:57:59.000Z
2021-04-07T02:11:12.000Z
src/backends/odbc/vector-use-type.cpp
ChainSQL/soci
d4d50d65002ec2fb1486622634c31234b5f05686
[ "BSL-1.0" ]
null
null
null
src/backends/odbc/vector-use-type.cpp
ChainSQL/soci
d4d50d65002ec2fb1486622634c31234b5f05686
[ "BSL-1.0" ]
1
2020-08-21T03:16:29.000Z
2020-08-21T03:16:29.000Z
// // Copyright (C) 2004-2006 Maciej Sobczak, Stephen Hutton, David Courtney // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // #define SOCI_ODBC_SOURCE #include "soci/soci-platform.h" #include "soci/odbc/soci-odbc.h" #include "soci-compiler.h" #include "soci-static-assert.h" #include <cctype> #include <cstdio> #include <cstring> #include <ctime> #include <sstream> #ifdef _MSC_VER // disables the warning about converting int to void*. This is a 64 bit compatibility // warning, but odbc requires the value to be converted on this line // SQLSetStmtAttr(statement_.hstmt_, SQL_ATTR_PARAMSET_SIZE, (SQLPOINTER)arraySize, 0); #pragma warning(disable:4312) #endif using namespace soci; using namespace soci::details; void odbc_vector_use_type_backend::prepare_indicators(std::size_t size) { if (size == 0) { throw soci_error("Vectors of size 0 are not allowed."); } indHolderVec_.resize(size); indHolders_ = &indHolderVec_[0]; } void odbc_vector_use_type_backend::prepare_for_bind(void *&data, SQLUINTEGER &size, SQLSMALLINT &sqlType, SQLSMALLINT &cType) { switch (type_) { // simple cases case x_short: { sqlType = SQL_SMALLINT; cType = SQL_C_SSHORT; size = sizeof(short); std::vector<short> *vp = static_cast<std::vector<short> *>(data); std::vector<short> &v(*vp); prepare_indicators(v.size()); data = &v[0]; } break; case x_integer: { sqlType = SQL_INTEGER; cType = SQL_C_SLONG; size = sizeof(SQLINTEGER); SOCI_STATIC_ASSERT(sizeof(SQLINTEGER) == sizeof(int)); std::vector<int> *vp = static_cast<std::vector<int> *>(data); std::vector<int> &v(*vp); prepare_indicators(v.size()); data = &v[0]; } break; case x_long_long: { std::vector<long long> *vp = static_cast<std::vector<long long> *>(data); std::vector<long long> &v(*vp); std::size_t const vsize = v.size(); prepare_indicators(vsize); if (use_string_for_bigint()) { sqlType = SQL_NUMERIC; cType = SQL_C_CHAR; size = max_bigint_length; buf_ = new char[size * vsize]; data = buf_; } else // Normal case, use ODBC support. { sqlType = SQL_BIGINT; cType = SQL_C_SBIGINT; size = sizeof(long long); data = &v[0]; } } break; case x_unsigned_long_long: { std::vector<unsigned long long> *vp = static_cast<std::vector<unsigned long long> *>(data); std::vector<unsigned long long> &v(*vp); std::size_t const vsize = v.size(); prepare_indicators(vsize); if (use_string_for_bigint()) { sqlType = SQL_NUMERIC; cType = SQL_C_CHAR; size = max_bigint_length; buf_ = new char[size * vsize]; data = buf_; } else // Normal case, use ODBC support. { sqlType = SQL_BIGINT; cType = SQL_C_SBIGINT; size = sizeof(unsigned long long); data = &v[0]; } } break; case x_double: { sqlType = SQL_DOUBLE; cType = SQL_C_DOUBLE; size = sizeof(double); std::vector<double> *vp = static_cast<std::vector<double> *>(data); std::vector<double> &v(*vp); prepare_indicators(v.size()); data = &v[0]; } break; // cases that require adjustments and buffer management case x_char: { std::vector<char> *vp = static_cast<std::vector<char> *>(data); std::size_t const vsize = vp->size(); prepare_indicators(vsize); size = sizeof(char) * 2; buf_ = new char[size * vsize]; char *pos = buf_; for (std::size_t i = 0; i != vsize; ++i) { *pos++ = (*vp)[i]; *pos++ = 0; } sqlType = SQL_CHAR; cType = SQL_C_CHAR; data = buf_; } break; case x_stdstring: { sqlType = SQL_CHAR; cType = SQL_C_CHAR; std::vector<std::string> *vp = static_cast<std::vector<std::string> *>(data); std::vector<std::string> &v(*vp); std::size_t maxSize = 0; std::size_t const vecSize = v.size(); prepare_indicators(vecSize); for (std::size_t i = 0; i != vecSize; ++i) { std::size_t sz = v[i].length(); set_sqllen_from_vector_at(i, static_cast<long>(sz)); maxSize = sz > maxSize ? sz : maxSize; } maxSize++; // For terminating nul. buf_ = new char[maxSize * vecSize]; memset(buf_, 0, maxSize * vecSize); char *pos = buf_; for (std::size_t i = 0; i != vecSize; ++i) { memcpy(pos, v[i].c_str(), v[i].length()); pos += maxSize; } data = buf_; size = static_cast<SQLINTEGER>(maxSize); } break; case x_stdtm: { std::vector<std::tm> *vp = static_cast<std::vector<std::tm> *>(data); prepare_indicators(vp->size()); buf_ = new char[sizeof(TIMESTAMP_STRUCT) * vp->size()]; sqlType = SQL_TYPE_TIMESTAMP; cType = SQL_C_TYPE_TIMESTAMP; data = buf_; size = 19; // This number is not the size in bytes, but the number // of characters in the date if it was written out // yyyy-mm-dd hh:mm:ss } break; // not supported default: throw soci_error("Use vector element used with non-supported type."); } colSize_ = size; } void odbc_vector_use_type_backend::bind_helper(int &position, void *data, exchange_type type) { data_ = data; // for future reference type_ = type; // for future reference SQLSMALLINT sqlType(0); SQLSMALLINT cType(0); SQLUINTEGER size(0); prepare_for_bind(data, size, sqlType, cType); SQLULEN const arraySize = static_cast<SQLULEN>(indHolderVec_.size()); SQLSetStmtAttr(statement_.hstmt_, SQL_ATTR_PARAMSET_SIZE, (SQLPOINTER)arraySize, 0); SQLRETURN rc = SQLBindParameter(statement_.hstmt_, static_cast<SQLUSMALLINT>(position++), SQL_PARAM_INPUT, cType, sqlType, size, 0, static_cast<SQLPOINTER>(data), size, indHolders_); if (is_odbc_error(rc)) { std::ostringstream ss; ss << "binding input vector parameter #" << position; throw odbc_soci_error(SQL_HANDLE_STMT, statement_.hstmt_, ss.str()); } } void odbc_vector_use_type_backend::bind_by_pos(int &position, void *data, exchange_type type) { if (statement_.boundByName_) { throw soci_error( "Binding for use elements must be either by position or by name."); } bind_helper(position, data, type); statement_.boundByPos_ = true; } void odbc_vector_use_type_backend::bind_by_name( std::string const &name, void *data, exchange_type type) { if (statement_.boundByPos_) { throw soci_error( "Binding for use elements must be either by position or by name."); } int position = -1; int count = 1; for (std::vector<std::string>::iterator it = statement_.names_.begin(); it != statement_.names_.end(); ++it) { if (*it == name) { position = count; break; } count++; } if (position != -1) { bind_helper(position, data, type); } else { std::ostringstream ss; ss << "Unable to find name '" << name << "' to bind to"; throw soci_error(ss.str().c_str()); } statement_.boundByName_ = true; } void odbc_vector_use_type_backend::pre_use(indicator const *ind) { // first deal with data SQLLEN non_null_indicator = 0; switch (type_) { case x_short: case x_integer: case x_double: // Length of the parameter value is ignored for these types. break; case x_char: case x_stdstring: non_null_indicator = SQL_NTS; break; case x_stdtm: { std::vector<std::tm> *vp = static_cast<std::vector<std::tm> *>(data_); std::vector<std::tm> &v(*vp); char *pos = buf_; std::size_t const vsize = v.size(); for (std::size_t i = 0; i != vsize; ++i) { std::tm t = v[i]; // See comment for the use of this macro in standard-into-type.cpp. GCC_WARNING_SUPPRESS(cast-align) TIMESTAMP_STRUCT * ts = reinterpret_cast<TIMESTAMP_STRUCT*>(pos); GCC_WARNING_RESTORE(cast-align) ts->year = static_cast<SQLSMALLINT>(t.tm_year + 1900); ts->month = static_cast<SQLUSMALLINT>(t.tm_mon + 1); ts->day = static_cast<SQLUSMALLINT>(t.tm_mday); ts->hour = static_cast<SQLUSMALLINT>(t.tm_hour); ts->minute = static_cast<SQLUSMALLINT>(t.tm_min); ts->second = static_cast<SQLUSMALLINT>(t.tm_sec); ts->fraction = 0; pos += sizeof(TIMESTAMP_STRUCT); } } break; case x_long_long: if (use_string_for_bigint()) { std::vector<long long> *vp = static_cast<std::vector<long long> *>(data_); std::vector<long long> &v(*vp); char *pos = buf_; std::size_t const vsize = v.size(); for (std::size_t i = 0; i != vsize; ++i) { snprintf(pos, max_bigint_length, "%" LL_FMT_FLAGS "d", v[i]); pos += max_bigint_length; } non_null_indicator = SQL_NTS; } break; case x_unsigned_long_long: if (use_string_for_bigint()) { std::vector<unsigned long long> *vp = static_cast<std::vector<unsigned long long> *>(data_); std::vector<unsigned long long> &v(*vp); char *pos = buf_; std::size_t const vsize = v.size(); for (std::size_t i = 0; i != vsize; ++i) { snprintf(pos, max_bigint_length, "%" LL_FMT_FLAGS "u", v[i]); pos += max_bigint_length; } non_null_indicator = SQL_NTS; } break; case x_statement: case x_rowid: case x_blob: case x_xmltype: case x_longstring: // Those are unreachable, we would have thrown from // prepare_for_bind() if we we were using one of them, only handle // them here to avoid compiler warnings about unhandled enum // elements. break; } // then handle indicators if (ind != NULL) { std::size_t const vsize = size(); for (std::size_t i = 0; i != vsize; ++i, ++ind) { if (*ind == i_null) { set_sqllen_from_vector_at(i, SQL_NULL_DATA); } else { // for strings we have already set the values if (type_ != x_stdstring) { set_sqllen_from_vector_at(i, non_null_indicator); } } } } else { // no indicators - treat all fields as OK std::size_t const vsize = size(); for (std::size_t i = 0; i != vsize; ++i, ++ind) { // for strings we have already set the values if (type_ != x_stdstring) { set_sqllen_from_vector_at(i, non_null_indicator); } } } } std::size_t odbc_vector_use_type_backend::size() { std::size_t sz = 0; // dummy initialization to please the compiler switch (type_) { // simple cases case x_char: { std::vector<char> *vp = static_cast<std::vector<char> *>(data_); sz = vp->size(); } break; case x_short: { std::vector<short> *vp = static_cast<std::vector<short> *>(data_); sz = vp->size(); } break; case x_integer: { std::vector<int> *vp = static_cast<std::vector<int> *>(data_); sz = vp->size(); } break; case x_long_long: { std::vector<long long> *vp = static_cast<std::vector<long long> *>(data_); sz = vp->size(); } break; case x_unsigned_long_long: { std::vector<unsigned long long> *vp = static_cast<std::vector<unsigned long long> *>(data_); sz = vp->size(); } break; case x_double: { std::vector<double> *vp = static_cast<std::vector<double> *>(data_); sz = vp->size(); } break; case x_stdstring: { std::vector<std::string> *vp = static_cast<std::vector<std::string> *>(data_); sz = vp->size(); } break; case x_stdtm: { std::vector<std::tm> *vp = static_cast<std::vector<std::tm> *>(data_); sz = vp->size(); } break; // not supported default: throw soci_error("Use vector element used with non-supported type."); } return sz; } void odbc_vector_use_type_backend::clean_up() { if (buf_ != NULL) { delete [] buf_; buf_ = NULL; } }
29.159046
93
0.505557
[ "vector" ]
67ec70d8970370acb8df0048e8db758597c2d3fa
9,909
cpp
C++
src/test.cpp
crockeo/optisearch
6e58e60c8ef58252fc62ec84758b66ea5d25aa42
[ "MIT" ]
null
null
null
src/test.cpp
crockeo/optisearch
6e58e60c8ef58252fc62ec84758b66ea5d25aa42
[ "MIT" ]
null
null
null
src/test.cpp
crockeo/optisearch
6e58e60c8ef58252fc62ec84758b66ea5d25aa42
[ "MIT" ]
null
null
null
// Note to random developer, // // Hi Randev, // This is really cluttered. I understand. The whole testing suite for a // whole project ought not be in a single file. That being said, to my // understanding, Catch (the library I'm using for my testing framework) // assigns IDs to tests based on line number in their .cpp file. I tried having // them in a bunch of places, but if they had conflicting line numbers they // just would NOT compile. // // In other words, sorry. I hope you'll forgive me one day. And if not, just // send all of your complaints nowhere. ////////////// // Includes // #include "catch.hpp" #include <vector> #include "search.hpp" #include "astar.hpp" #include "board.hpp" #include "heap.hpp" #include "maze.hpp" ////////// // Code // // LONG_TESTING defines whether or not one ought to wait for the long-running // tests to complete. const bool LONG_TESTING = false; //// // Search // Testing the board heuristic. TEST_CASE("Board Heuristic") { std::vector<int> states { 1, 3, 7, 2, 4, 8, 5, 0, 6 }; Board filled(3, 3, states); REQUIRE(heuristic(filled) == 18); } // Testing isSolution. TEST_CASE("Solution Checking") { std::vector<int> states { 0, 1, 2, 3, 4, 5, 6, 7, 8 }; Board filled(3, 3, states); REQUIRE(isSolution(filled)); } // Testing the search method. TEST_CASE("Board Search") { // An already-solved board. Board solved = loadBoard("res/solved.txt"); std::vector<BoardMove> solvedMoves = findSolution(solved); REQUIRE(solvedMoves.size() == 0); // An easy first-move solution. Board easy = loadBoard("res/easy.txt"); std::vector<BoardMove> easyMoves = findSolution(easy); REQUIRE(easyMoves.size() == 1); REQUIRE(easyMoves.at(0) == BoardMove(0, 0, 1, 0)); // Testing a move involved solution. Board complicated = loadBoard("res/complicated.txt"); std::vector<BoardMove> complicatedMoves = findSolution(complicated); REQUIRE(complicatedMoves.size() == 3); REQUIRE(complicatedMoves.at(0) == BoardMove(2, 0, 2, 1)); REQUIRE(complicatedMoves.at(1) == BoardMove(1, 0, 2, 0)); REQUIRE(complicatedMoves.at(2) == BoardMove(0, 0, 1, 0)); if (LONG_TESTING) { // Trying to find a solution on a board that has no solution. Board unsolvable = loadBoard("res/unsolvable.txt"); std::vector<BoardMove> unsolvableMoves = findSolution(unsolvable); REQUIRE(unsolvableMoves.size() == 0); } } //// // A* Search TEST_CASE("A* Search") { // Testing board solution. Board complicated = loadBoard("res/complicated.txt"); SearchableBoard searchableComplicated(complicated); std::vector<Board> boardSolution = AStarSearcher<Board>(searchableComplicated).findSolution(); REQUIRE(boardSolution.size() == 4); REQUIRE(boardSolution.at(0) == complicated); REQUIRE(boardSolution.at(1) == loadBoard("res/solution/01.txt")); REQUIRE(boardSolution.at(2) == loadBoard("res/solution/02.txt")); REQUIRE(boardSolution.at(3) == loadBoard("res/solved.txt")); // Testing maze solution. Maze maze(0, 0, 10, 0); SearchableMaze searchableMaze(maze); AStarSearcher<Maze> searcher(searchableMaze); std::vector<Maze> testSolution { Maze( 0, 0, 10, 0), Maze( 1, 0, 10, 0), Maze( 2, 0, 10, 0), Maze( 3, 0, 10, 0), Maze( 4, 0, 10, 0), Maze( 5, 0, 10, 0), Maze( 6, 0, 10, 0), Maze( 7, 0, 10, 0), Maze( 8, 0, 10, 0), Maze( 9, 0, 10, 0), Maze(10, 0, 10, 0), }; std::vector<Maze> foundSolution = searcher.findSolution(); for (int i = 0; i < testSolution.size(); i++) REQUIRE(testSolution.at(i) == foundSolution.at(i)); } //// // Board // Testing board construction. TEST_CASE("Board Construction") { Board empty(2, 2); for (int row = 0; row < empty.getHeight(); row++) for (int col = 0; col < empty.getWidth(); col++) REQUIRE(empty.getState(row, col) == 0); std::vector<int> states { 0, 1, 2, 3, 4, 5, 6, 7, 8 }; Board filled(3, 3, states); for (int row = 0; row < filled.getHeight(); row++) for (int col = 0; col < filled.getWidth(); col++) REQUIRE(filled.getState(col, row) == row * filled.getWidth() + col); } // Testing operator== for boards. TEST_CASE("Equality") { std::vector<int> states { 0, 1, 2, 3, 4, 5, 6, 7, 8 }; Board board1(3, 3, states); Board board2(3, 3, states); REQUIRE(board1 == board2); } // Testing isValidMove for a board. TEST_CASE("Validating Moves") { std::vector<int> states { 1, 3, 7, 2, 4, 8, 5, 0, 6 }; Board filled(3, 3, states); REQUIRE(filled.isValidMove(BoardMove(1, 1, 1, 2)) == true); REQUIRE(filled.isValidMove(BoardMove(0, 0, 0, 0)) == false); REQUIRE(filled.isValidMove(BoardMove(1, 3, 1, 2)) == false); } // Testing doMove for a board. TEST_CASE("doMove") { std::vector<int> vs0 { 1, 3, 7, 2, 0, 8, 5, 4, 6 }; Board moved1(3, 3, vs0); std::vector<int> vs1 { 1, 3, 7, 2, 4, 8, 0, 5, 6 }; Board moved2(3, 3, vs1); std::vector<int> vs2 { 1, 3, 7, 2, 4, 8, 5, 6, 0 }; Board moved3(3, 3, vs2); // Setting up the real board. std::vector<int> states { 1, 3, 7, 2, 4, 8, 5, 0, 6 }; Board filled(3, 3, states); REQUIRE(filled.doMove(BoardMove(1, 1, 1, 2)) == moved1); REQUIRE(filled.doMove(BoardMove(0, 2, 1, 2)) == moved2); REQUIRE(filled.doMove(BoardMove(2, 2, 1, 2)) == moved3); REQUIRE_THROWS(filled.doMove(BoardMove(-1, -1, 3, 3))); } // Testing getState & setState on the board. TEST_CASE("Get & Set") { Board empty(3, 3); empty.setState(0, 0, 3); empty.setState(1, 0, 2); REQUIRE(empty.getState(0, 0) == 3); REQUIRE(empty.getState(1, 0) == 2); REQUIRE(empty.getState(2, 0) == 0); } // Testing the distance function on a board. TEST_CASE("Board Distance") { std::vector<int> states { 1, 3, 7, 2, 4, 8, 5, 0, 6 }; Board filled(3, 3, states); REQUIRE(filled.distance(0, 0) == 1); REQUIRE(filled.distance(1, 0) == 2); REQUIRE(filled.distance(2, 0) == 3); REQUIRE(filled.distance(0, 1) == 3); REQUIRE(filled.distance(1, 1) == 0); REQUIRE(filled.distance(2, 1) == 1); REQUIRE(filled.distance(0, 2) == 3); REQUIRE(filled.distance(1, 2) == 3); REQUIRE(filled.distance(2, 2) == 2); } // Testing loading a board from a file. TEST_CASE("Load") { Board b = loadBoard("res/board01.txt"); for (int row = 0; row < b.getHeight(); row++) for (int col = 0; col < b.getWidth(); col++) REQUIRE(b.getState(col, row) == row * b.getWidth() + col); REQUIRE_THROWS(loadBoard("res/doesnotexist.txt")); REQUIRE_THROWS(loadBoard("res/invalidsize.txt")); REQUIRE_THROWS(loadBoard("res/invalidboard.txt")); } //// // Heap // Testing the .insert & .remove methods. TEST_CASE("Insert & Remove") { Heap<int, int> intHeap([](const int n1, const int n2) -> int { return n1 - n2; }); intHeap.insert(3, 3); intHeap.insert(1, 1); intHeap.insert(4, 4); intHeap.insert(2, 2); REQUIRE(intHeap.size() == 4); REQUIRE(intHeap.remove() == 4); REQUIRE(intHeap.size() == 3); REQUIRE(intHeap.remove() == 3); REQUIRE(intHeap.size() == 2); REQUIRE(intHeap.remove() == 2); REQUIRE(intHeap.size() == 1); REQUIRE(intHeap.remove() == 1); REQUIRE(intHeap.size() == 0); } // Testing the order of a vector returned from asVector. TEST_CASE("AsVector") { Heap<int, int> intHeap([](const int n1, const int n2) -> int { return n1 - n2; }); intHeap.insert(3, 3); intHeap.insert(1, 1); intHeap.insert(4, 4); intHeap.insert(2, 2); std::vector<Pair<int, int>> pairs = intHeap.asVector(); REQUIRE(pairs.at(0).value == 4); REQUIRE(pairs.at(1).value == 2); REQUIRE(pairs.at(2).value == 3); REQUIRE(pairs.at(3).value == 1); } //// // Maze // Testing the maze constructor. TEST_CASE("Maze Construction") { Maze maze(0, 0, 1, 1); REQUIRE(maze.px == 0); REQUIRE(maze.py == 0); REQUIRE(maze.tx == 1); REQUIRE(maze.ty == 1); } // Testing maze heuristic. TEST_CASE("Maze Heuristic") { Maze maze1(0, 0, 1, 1); REQUIRE(maze1.heuristic() == 2); Maze maze2(0, 0, 10, 0); REQUIRE(maze2.heuristic() == 10); } // Testing maze equality. TEST_CASE("Maze Equality") { Maze maze1(0, 0, 1, 1); Maze maze2(1, 1, 0, 0); Maze maze3(0, 0, 1, 1); REQUIRE(maze1 != maze2); REQUIRE(maze2 != maze3); REQUIRE(maze1 == maze3); } TEST_CASE("Maze Ordering") { Maze maze1(0, 0, 0, 0); Maze maze2(0, 0, 0, 1); Maze maze3(0, 0, 1, 0); Maze maze4(0, 1, 0, 0); Maze maze5(1, 0, 0, 0); REQUIRE(maze1 < maze2); REQUIRE(maze2 < maze3); REQUIRE(maze3 < maze4); REQUIRE(maze4 < maze5); } TEST_CASE("Searchable Maze") { Maze maze1(0, 0, 1, 0); Maze maze2(1, 0, 1, 0); SearchableMaze smaze(maze1); // Checking getInitialState REQUIRE(smaze.getInitialState() == maze1); REQUIRE(smaze.getInitialState() != maze2); // Checking isGoal REQUIRE(!smaze.isGoal(maze1)); REQUIRE( smaze.isGoal(maze2)); // Checking nextStates. std::vector<Maze> testNext { Maze(-1, 0, 1, 0), Maze( 1, 0, 1, 0), Maze( 0, -1, 1, 0), Maze( 0, 1, 1, 0) }; std::vector<Maze> realNext = smaze.nextStates(maze1); for (int i = 0; i < testNext.size(); i++) REQUIRE(testNext.at(i) == realNext.at(i)); }
25.670984
98
0.575941
[ "vector" ]
67f184481df4c46717a49745ef76cdd53d6506a8
6,107
cpp
C++
framework/core/pipeline_layout.cpp
AlejandroCosin/Vulkan-Samples
8029ffb6b22d32c5e8572288aaa133af3954350f
[ "Apache-2.0" ]
1
2020-05-24T23:43:06.000Z
2020-05-24T23:43:06.000Z
framework/core/pipeline_layout.cpp
AlejandroCosin/Vulkan-Samples
8029ffb6b22d32c5e8572288aaa133af3954350f
[ "Apache-2.0" ]
null
null
null
framework/core/pipeline_layout.cpp
AlejandroCosin/Vulkan-Samples
8029ffb6b22d32c5e8572288aaa133af3954350f
[ "Apache-2.0" ]
null
null
null
/* Copyright (c) 2019-2020, Arm Limited and Contributors * * SPDX-License-Identifier: Apache-2.0 * * 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 "pipeline_layout.h" #include "descriptor_set_layout.h" #include "device.h" #include "pipeline.h" #include "shader_module.h" namespace vkb { PipelineLayout::PipelineLayout(Device &device, const std::vector<ShaderModule *> &shader_modules) : device{device}, shader_modules{shader_modules} { // Collect and combine all the shader resources from each of the shader modules // Collate them all into a map that is indexed by the name of the resource for (auto *shader_module : shader_modules) { for (const auto &shader_resource : shader_module->get_resources()) { std::string key = shader_resource.name; // Since 'Input' and 'Output' resources can have the same name, we modify the key string if (shader_resource.type == ShaderResourceType::Input || shader_resource.type == ShaderResourceType::Output) { key = std::to_string(shader_resource.stages) + "_" + key; } auto it = shader_resources.find(key); if (it != shader_resources.end()) { // Append stage flags if resource already exists it->second.stages |= shader_resource.stages; } else { // Create a new entry in the map shader_resources.emplace(key, shader_resource); } } } // Sift through the map of name indexed shader resources // Seperate them into their respective sets for (auto &it : shader_resources) { auto &shader_resource = it.second; // Find binding by set index in the map. auto it2 = shader_sets.find(shader_resource.set); if (it2 != shader_sets.end()) { // Add resource to the found set index it2->second.push_back(shader_resource); } else { // Create a new set index and with the first resource shader_sets.emplace(shader_resource.set, std::vector<ShaderResource>{shader_resource}); } } // Create a descriptor set layout for each shader set in the shader modules for (auto &shader_set_it : shader_sets) { descriptor_set_layouts.emplace(shader_set_it.first, &device.get_resource_cache().request_descriptor_set_layout(shader_set_it.second)); } // Collect all the descriptor set layout handles std::vector<VkDescriptorSetLayout> descriptor_set_layout_handles(descriptor_set_layouts.size()); std::transform(descriptor_set_layouts.begin(), descriptor_set_layouts.end(), descriptor_set_layout_handles.begin(), [](auto &descriptor_set_layout_it) { return descriptor_set_layout_it.second->get_handle(); }); // Collect all the push constant shader resources std::vector<VkPushConstantRange> push_constant_ranges; for (auto &push_constant_resource : get_resources(ShaderResourceType::PushConstant)) { push_constant_ranges.push_back({push_constant_resource.stages, push_constant_resource.offset, push_constant_resource.size}); } VkPipelineLayoutCreateInfo create_info{VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO}; create_info.setLayoutCount = to_u32(descriptor_set_layout_handles.size()); create_info.pSetLayouts = descriptor_set_layout_handles.data(); create_info.pushConstantRangeCount = to_u32(push_constant_ranges.size()); create_info.pPushConstantRanges = push_constant_ranges.data(); // Create the Vulkan pipeline layout handle auto result = vkCreatePipelineLayout(device.get_handle(), &create_info, nullptr, &handle); if (result != VK_SUCCESS) { throw VulkanException{result, "Cannot create PipelineLayout"}; } } PipelineLayout::PipelineLayout(PipelineLayout &&other) : device{other.device}, handle{other.handle}, shader_modules{std::move(other.shader_modules)}, shader_resources{std::move(other.shader_resources)}, shader_sets{std::move(other.shader_sets)}, descriptor_set_layouts{std::move(other.descriptor_set_layouts)} { other.handle = VK_NULL_HANDLE; } PipelineLayout::~PipelineLayout() { // Destroy pipeline layout if (handle != VK_NULL_HANDLE) { vkDestroyPipelineLayout(device.get_handle(), handle, nullptr); } } VkPipelineLayout PipelineLayout::get_handle() const { return handle; } const std::vector<ShaderModule *> &PipelineLayout::get_shader_modules() const { return shader_modules; } const std::vector<ShaderResource> PipelineLayout::get_resources(const ShaderResourceType &type, VkShaderStageFlagBits stage) const { std::vector<ShaderResource> found_resources; for (auto &it : shader_resources) { auto &shader_resource = it.second; if (shader_resource.type == type || type == ShaderResourceType::All) { if (shader_resource.stages == stage || stage == VK_SHADER_STAGE_ALL) { found_resources.push_back(shader_resource); } } } return found_resources; } const std::unordered_map<uint32_t, std::vector<ShaderResource>> &PipelineLayout::get_shader_sets() const { return shader_sets; } bool PipelineLayout::has_descriptor_set_layout(uint32_t set_index) const { return set_index < descriptor_set_layouts.size(); } DescriptorSetLayout &PipelineLayout::get_descriptor_set_layout(uint32_t set_index) const { return *descriptor_set_layouts.at(set_index); } VkShaderStageFlags PipelineLayout::get_push_constant_range_stage(uint32_t offset, uint32_t size) const { VkShaderStageFlags stages = 0; for (auto &push_constant_resource : get_resources(ShaderResourceType::PushConstant)) { if (offset >= push_constant_resource.offset && offset + size <= push_constant_resource.offset + push_constant_resource.size) { stages |= push_constant_resource.stages; } } return stages; } } // namespace vkb
31.479381
136
0.754053
[ "vector", "transform" ]
67f1b354bb376b67b530fc6f4c42c70e7ca6f97f
725
cc
C++
solutions/Leetcode_304/leetcode_304.cc
YuhanShi53/Leetcode_solutions
cdcad34656d25d6af09b226e17250c6070305ab0
[ "MIT" ]
null
null
null
solutions/Leetcode_304/leetcode_304.cc
YuhanShi53/Leetcode_solutions
cdcad34656d25d6af09b226e17250c6070305ab0
[ "MIT" ]
null
null
null
solutions/Leetcode_304/leetcode_304.cc
YuhanShi53/Leetcode_solutions
cdcad34656d25d6af09b226e17250c6070305ab0
[ "MIT" ]
null
null
null
#include <vector> using namespace std; class NumMatrix { public: NumMatrix(vector<vector<int>> &matrix) { int num_row = matrix.size(); int num_col = matrix[0].size(); sums = vector<vector<int>>(num_row + 1, vector<int>(num_col + 1, 0)); for (int row = 1; row <= num_row; row++) for (int col = 1; col <= num_col; col++) sums[row][col] = matrix[row - 1][col - 1] + sums[row][col - 1] + sums[row - 1][col] - sums[row - 1][col - 1]; } int sumRegion(int row1, int col1, int row2, int col2) { return sums[row2 + 1][col2 + 1] - sums[row2 + 1][col1] - sums[row1][col2 + 1] + sums[row1][col1]; } private: vector<vector<int>> sums; };
27.884615
125
0.543448
[ "vector" ]
67fa05d6db0d94ac410c06e5b9b83e26b24dc092
881
cpp
C++
src/problems/101-150/119/problem119.cpp
abeccaro/project-euler
c3b124bb973dc3a1cf29e8c96c3e70c8816d5fa3
[ "MIT" ]
1
2019-12-25T10:17:15.000Z
2019-12-25T10:17:15.000Z
src/problems/101-150/119/problem119.cpp
abeccaro/project-euler
c3b124bb973dc3a1cf29e8c96c3e70c8816d5fa3
[ "MIT" ]
null
null
null
src/problems/101-150/119/problem119.cpp
abeccaro/project-euler
c3b124bb973dc3a1cf29e8c96c3e70c8816d5fa3
[ "MIT" ]
null
null
null
// // Created by Alex Beccaro on 17/01/2019. // #include "problem119.hpp" #include <numeric> #include <generics.hpp> using std::vector; using std::numeric_limits; using std::accumulate; using std::sort; using generics::digits; namespace problems { uint64_t problem119::solve(uint32_t n) { // empirical bounds const uint32_t BASE_UB = 100; const uint64_t UB = numeric_limits<uint64_t>::max() / BASE_UB; vector<uint64_t> v; for (uint32_t a = 2; a < BASE_UB; a++) { uint64_t x = a * a; while (x < UB) { vector<uint32_t> digs = digits(x); int d_sum = accumulate(digs.begin(), digs.end(), 0); if (d_sum == a) v.push_back(x); x *= a; } } sort(v.begin(), v.end()); return v[n-1]; } }
20.022727
70
0.523269
[ "vector" ]
67fe6cb00f27b4a59ed7930540785670aa196d77
12,638
cpp
C++
incremental_calibration_examples/incremental_calibration_examples_2dlrf/src/2dlrf/simulate-offline.cpp
ethz-asl/aslam_incremental_calibration
16a44b86b6e7eb5ae4ee247f10c429494697ae0b
[ "BSD-3-Clause" ]
16
2017-08-23T06:29:15.000Z
2021-07-17T16:56:29.000Z
incremental_calibration_examples/incremental_calibration_examples_2dlrf/src/2dlrf/simulate-offline.cpp
ethz-asl/aslam_incremental_calibration
16a44b86b6e7eb5ae4ee247f10c429494697ae0b
[ "BSD-3-Clause" ]
1
2017-02-14T16:02:18.000Z
2017-02-14T16:02:18.000Z
incremental_calibration_examples/incremental_calibration_examples_2dlrf/src/2dlrf/simulate-offline.cpp
ethz-asl/aslam_incremental_calibration
16a44b86b6e7eb5ae4ee247f10c429494697ae0b
[ "BSD-3-Clause" ]
11
2017-01-23T09:01:30.000Z
2021-04-10T05:13:23.000Z
/****************************************************************************** * Copyright (C) 2013 by Jerome Maye * * jerome.maye@gmail.com * ******************************************************************************/ /** \file simulate-offline.cpp \brief This file runs a simulation of the calibration problem in batch mode. */ #include <iostream> #include <iomanip> #include <fstream> #include <vector> #include <boost/shared_ptr.hpp> #include <boost/make_shared.hpp> #include <Eigen/Core> #include <sm/kinematics/rotations.hpp> #include <sm/kinematics/three_point_methods.hpp> #include <sm/BoostPropertyTree.hpp> #include <aslam/backend/Optimizer2Options.hpp> #include <aslam/backend/GaussNewtonTrustRegionPolicy.hpp> #include <aslam/backend/Optimizer2.hpp> #include <aslam/calibration/core/OptimizationProblem.h> #include <aslam/calibration/statistics/UniformDistribution.h> #include <aslam/calibration/statistics/NormalDistribution.h> #include <aslam/calibration/data-structures/VectorDesignVariable.h> #include <aslam/calibration/geometry/Transformation.h> #include <aslam/calibration/base/Timestamp.h> #include <aslam-tsvd-solver/aslam-tsvd-solver.h> #include "aslam/calibration/2dlrf/utils.h" #include "aslam/calibration/2dlrf/ErrorTermMotion.h" #include "aslam/calibration/2dlrf/ErrorTermObservation.h" using namespace aslam::calibration; using namespace aslam::backend; using namespace sm::kinematics; using namespace sm; typedef aslam::backend::AslamTruncatedSvdSolver LinearSolver; int main(int argc, char** argv) { if (argc != 2) { std::cerr << "Usage: " << argv[0] << " <conf_file>" << std::endl; return -1; } // load configuration file BoostPropertyTree propertyTree; propertyTree.loadXml(argv[1]); // steps to simulate const size_t steps = propertyTree.getInt("lrf/problem/steps"); // timestep size const double T = propertyTree.getDouble("lrf/problem/timestep"); // true state std::vector<Eigen::Vector3d > x_true; x_true.reserve(steps); // integrated odometry std::vector<Eigen::Vector3d > x_odom; x_odom.reserve(steps); // true control input std::vector<Eigen::Vector3d > u_true; const double sineWaveAmplitude = propertyTree.getDouble( "lrf/problem/sineWaveAmplitude"); const double sineWaveFrequency = propertyTree.getDouble( "lrf/problem/sineWaveFrequency"); genSineWavePath(u_true, steps, sineWaveAmplitude, sineWaveFrequency, T); // measured control input std::vector<Eigen::Vector3d > u_noise; u_noise.reserve(steps); // number of landmarks const size_t nl = propertyTree.getInt("lrf/problem/numLandmarks"); // playground size const Eigen::Vector2d min(propertyTree.getDouble("lrf/problem/groundMinX"), propertyTree.getDouble("lrf/problem/groundMinY")); const Eigen::Vector2d max(propertyTree.getDouble("lrf/problem/groundMaxX"), propertyTree.getDouble("lrf/problem/groundMaxY")); // bearing measurements std::vector<std::vector<double> > b; b.reserve(steps); b.push_back(std::vector<double>(nl, 0)); // range measurements std::vector<std::vector<double> > r; r.reserve(steps); r.push_back(std::vector<double>(nl, 0)); // covariance matrix for motion model Eigen::Matrix3d Q = Eigen::Matrix3d::Zero(); Q(0, 0) = propertyTree.getDouble("lrf/problem/motion/sigma2_x"); Q(1, 1) = propertyTree.getDouble("lrf/problem/motion/sigma2_y"); Q(2, 2) = propertyTree.getDouble("lrf/problem/motion/sigma2_t"); // covariance matrix for observation model Eigen::Matrix2d R = Eigen::Matrix2d::Zero(); R(0, 0) = propertyTree.getDouble("lrf/problem/observation/sigma2_r"); R(1, 1) = propertyTree.getDouble("lrf/problem/observation/sigma2_b"); // landmark positions std::vector<Eigen::Vector2d > x_l; UniformDistribution<double, 2>(min, max).getSamples(x_l, nl); // true calibration parameters const Eigen::Vector3d Theta(propertyTree.getDouble("lrf/problem/thetaTrue/x"), propertyTree.getDouble("lrf/problem/thetaTrue/y"), propertyTree.getDouble("lrf/problem/thetaTrue/t")); // guessed calibration parameters const Eigen::Vector3d Theta_hat( propertyTree.getDouble("lrf/problem/thetaHat/x"), propertyTree.getDouble("lrf/problem/thetaHat/y"), propertyTree.getDouble("lrf/problem/thetaHat/t")); // initial state const Eigen::Vector3d x_0(propertyTree.getDouble("lrf/problem/x0/x"), propertyTree.getDouble("lrf/problem/x0/y"), propertyTree.getDouble("lrf/problem/x0/t")); x_true.push_back(x_0); x_odom.push_back(x_0); u_noise.push_back(Eigen::Vector3d::Zero()); // simulate for (size_t i = 1; i < steps; ++i) { Eigen::Matrix3d B = Eigen::Matrix3d::Identity(); B(0, 0) = cos(x_true[i - 1](2)); B(0, 1) = -sin(x_true[i - 1](2)); B(1, 0) = sin(x_true[i - 1](2)); B(1, 1) = cos(x_true[i - 1](2)); Eigen::Vector3d xk = x_true[i - 1] + T * B * u_true[i]; xk(2) = angleMod(xk(2)); x_true.push_back(xk); u_noise.push_back(u_true[i] + NormalDistribution<3>(Eigen::Vector3d::Zero(), Q).getSample()); B(0, 0) = cos(x_odom[i - 1](2)); B(0, 1) = -sin(x_odom[i - 1](2)); B(1, 0) = sin(x_odom[i - 1](2)); B(1, 1) = cos(x_odom[i - 1](2)); xk = x_odom[i - 1] + T * B * u_noise[i]; xk(2) = angleMod(xk(2)); x_odom.push_back(xk); const double ct = cos(x_true[i](2)); const double st = sin(x_true[i](2)); std::vector<double> rk(nl, 0); std::vector<double> bk(nl, 0); for (size_t j = 0; j < nl; ++j) { const double aa = x_l[j](0) - x_true[i](0) - Theta(0) * ct + Theta(1) * st; const double bb = x_l[j](1) - x_true[i](1) - Theta(0) * st - Theta(1) * ct; const double range = sqrt(aa * aa + bb * bb) + NormalDistribution<1>(0, R(0, 0)).getSample(); rk[j] = range; bk[j] = angleMod(atan2(bb, aa) - x_true[i](2) - Theta(2) + NormalDistribution<1>(0, R(1, 1)).getSample()); } r.push_back(rk); b.push_back(bk); } // landmark guess std::vector<Eigen::Vector2d > x_l_hat; initLandmarks(x_l_hat, x_odom, Theta_hat, r, b); // create optimization problem auto problem = boost::make_shared<OptimizationProblem>(); // create calibration parameters design variable auto dv_Theta = boost::make_shared<VectorDesignVariable<3> >(Theta_hat); dv_Theta->setActive(true); problem->addDesignVariable(dv_Theta, 2); // create state design variables std::vector<boost::shared_ptr<VectorDesignVariable<3> > > dv_x; dv_x.reserve(steps); for (size_t i = 0; i < steps; ++i) { dv_x.push_back(boost::make_shared<VectorDesignVariable<3> >(x_odom[i])); dv_x[i]->setActive(true); problem->addDesignVariable(dv_x[i], 0); } // create landmarks design variables std::vector<boost::shared_ptr<VectorDesignVariable<2> > > dv_x_l; dv_x_l.reserve(nl); for (size_t i = 0; i < nl; ++i) { dv_x_l.push_back(boost::make_shared<VectorDesignVariable<2> >(x_l_hat[i])); dv_x_l[i]->setActive(true); problem->addDesignVariable(dv_x_l[i], 1); } // set the ordering of the problem problem->setGroupsOrdering({0, 1, 2}); // add motion and observation error terms for (size_t i = 1; i < steps; ++i) { auto e_mot = boost::make_shared<ErrorTermMotion>(dv_x[i - 1].get(), dv_x[i].get(), T, u_noise[i], Q); problem->addErrorTerm(e_mot); for (size_t j = 0; j < nl; ++j) { auto e_obs = boost::make_shared<ErrorTermObservation>(dv_x[i].get(), dv_x_l[j].get(), dv_Theta.get(), r[i][j], b[i][j], R); problem->addErrorTerm(e_obs); } } // optimization std::cout << "Calibration before: " << *dv_Theta << std::endl; Optimizer2 optimizer(PropertyTree(propertyTree, "lrf/estimator/optimizer"), boost::make_shared<LinearSolver>(PropertyTree(propertyTree, "lrf/estimator/optimizer/linearSolver")), boost::make_shared<GaussNewtonTrustRegionPolicy>()); optimizer.setProblem(problem); size_t JCols = 0; for (auto it = problem->getGroupsOrdering().cbegin(); it != problem->getGroupsOrdering().cend(); ++it) JCols += problem->getGroupDim(*it); const size_t dim = problem->getGroupDim(2); auto linearSolver = optimizer.getSolver<LinearSolver>(); linearSolver->setMargStartIndex(JCols - dim); const double before = Timestamp::now(); optimizer.optimize(); const double after = Timestamp::now(); std::cout << "Elapsed time [s]: " << after - before << std::endl; std::cout << "Calibration after: " << *dv_Theta << std::endl; std::cout << "Singular values (scaled): " << linearSolver->getSingularValues().transpose() << std::endl; std::cout << "Unobservable basis (scaled): " << std::endl << linearSolver->getNullSpace() << std::endl; std::cout << "Observable basis (scaled): " << std::endl << linearSolver->getRowSpace() << std::endl; linearSolver->analyzeMarginal(); std::cout << "SVD rank: " << linearSolver->getSVDRank() << std::endl; std::cout << "SVD rank deficiency: " << linearSolver->getSVDRankDeficiency() << std::endl; std::cout << "SVD tolerance: " << linearSolver->getSVDTolerance() << std::endl; std::cout << "Singular values: " << optimizer.getSolver<LinearSolver>() ->getSingularValues().transpose() << std::endl; std::cout << "QR rank: " << optimizer.getSolver<LinearSolver>()->getQRRank() << std::endl; std::cout << "QR rank deficiency: " << optimizer.getSolver<LinearSolver>() ->getQRRankDeficiency() << std::endl; std::cout << "QR tolerance: " << linearSolver->getQRTolerance() << std::endl; std::cout << "Unobservable basis: " << std::endl << linearSolver->getNullSpace() << std::endl; std::cout << "Observable basis: " << std::endl << linearSolver->getRowSpace() << std::endl; std::cout << "Covariance: " << std::endl << linearSolver->getCovariance() << std::endl; std::cout << "Observable covariance: " << std::endl << linearSolver->getRowSpaceCovariance() << std::endl; std::cout << "Peak memory usage (MB): " << linearSolver->getPeakMemoryUsage() / 1024.0 / 1024.0 << std::endl; std::cout << "Memory usage (MB): " << linearSolver->getMemoryUsage() / 1024.0 / 1024.0 << std::endl; std::cout << "Flop count: " << linearSolver->getNumFlops() << std::endl; std::cout << "Linear solver time: " << linearSolver->getLinearSolverTime() << std::endl; std::cout << "Marginal analysis time: " << linearSolver->getMarginalAnalysisTime() << std::endl; std::cout << "Symbolic factorization time: " << linearSolver->getSymbolicFactorizationTime() << std::endl; std::cout << "Numeric factorization time: " << linearSolver->getNumericFactorizationTime() << std::endl; std::cout << "Log2sum of singular values: " << linearSolver->getSingularValuesLog2Sum() << std::endl; // output results to file std::ofstream x_true_log("x_true.txt"); for (size_t i = 0; i < steps; ++i) x_true_log << x_true[i].transpose() << std::endl; std::ofstream x_odom_log("x_odom.txt"); for (size_t i = 0; i < steps; ++i) x_odom_log << x_odom[i].transpose() << std::endl; std::ofstream x_est_log("x_est.txt"); for (size_t i = 0; i < steps; ++i) x_est_log << *(dv_x[i]) << std::endl; std::ofstream l_log("l.txt"); for (size_t i = 0; i < nl; ++i) l_log << x_l[i].transpose() << std::endl; std::ofstream l_est_log("l_est.txt"); for (size_t i = 0; i < nl; ++i) l_est_log << *(dv_x_l[i]) << std::endl; // align landmarks Eigen::MatrixXd l = Eigen::MatrixXd::Zero(3, nl); Eigen::MatrixXd l_est = Eigen::MatrixXd::Zero(3, nl); for (size_t i = 0; i < nl; ++i) { l(0, i) = x_l[i](0); l(1, i) = x_l[i](1); l_est(0, i) = dv_x_l[i]->getValue()(0); l_est(1, i) = dv_x_l[i]->getValue()(1); } Transformation<double, 3> trans(threePointSvd(l, l_est)); Eigen::MatrixXd l_est_trans = Eigen::MatrixXd::Zero(3, nl); for (size_t i = 0; i < nl; ++i) l_est_trans.col(i) = trans(l_est.col(i)); std::ofstream l_est_trans_log("l_est_trans.txt"); for (size_t i = 0; i < nl; ++i) l_est_trans_log << l_est_trans.col(i).head<2>().transpose() << std::endl; // align poses std::vector<Eigen::Vector3d > x_est_trans; x_est_trans.reserve(steps); std::ofstream x_est_trans_log("x_est_trans.txt"); for (size_t i = 0; i < steps; ++i) { Eigen::Vector3d pose((Eigen::Vector3d() << dv_x[i]->getValue().head<2>(), 0).finished()); trans.transform(pose, pose); pose(2) = dv_x[i]->getValue()(2); x_est_trans.push_back(pose); x_est_trans_log << x_est_trans[i].transpose() << std::endl; } return 0; }
38.181269
80
0.649153
[ "geometry", "vector", "model", "transform" ]
67ff4b08caca947fe627a7ce3f2a50b0fa5b543a
44,119
cpp
C++
src/condor_dagman/condor_submit_dag.cpp
zzxuanyuan/htcondor
b6b150095d2984970d9440a26ae714da337a1224
[ "Apache-2.0" ]
1
2015-05-22T16:26:34.000Z
2015-05-22T16:26:34.000Z
src/condor_dagman/condor_submit_dag.cpp
bbockelm/htcondor
92b73bb15fd7187b1362ae0d43dbcfde3df3e354
[ "Apache-2.0" ]
null
null
null
src/condor_dagman/condor_submit_dag.cpp
bbockelm/htcondor
92b73bb15fd7187b1362ae0d43dbcfde3df3e354
[ "Apache-2.0" ]
2
2017-11-09T01:42:58.000Z
2020-07-14T20:20:05.000Z
/*************************************************************** * * Copyright (C) 1990-2007, Condor Team, Computer Sciences Department, * University of Wisconsin-Madison, WI. * * 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 "condor_common.h" #include "dagman_recursive_submit.h" #include "MyString.h" #include "which.h" #include "string_list.h" #include "condor_distribution.h" #include "condor_config.h" #include "env.h" #include "dagman_multi_dag.h" #include "basename.h" #include "read_multiple_logs.h" #include "condor_getcwd.h" #include "condor_string.h" // for getline() #include "condor_version.h" #include "tmp_dir.h" #include "my_popen.h" #include "setenv.h" #include "condor_attributes.h" #include "dag_tokener.h" #ifdef WIN32 const char* dagman_exe = "condor_dagman.exe"; const char* valgrind_exe = "valgrind.exe"; #else const char* dagman_exe = "condor_dagman"; const char* valgrind_exe = "valgrind"; #endif int printUsage(int iExitCode=1); // NOTE: printUsage calls exit(1), so it doesn't return void parseCommandLine(SubmitDagDeepOptions &deepOpts, SubmitDagShallowOptions &shallowOpts, int argc, const char * const argv[]); bool parsePreservedArgs(const MyString &strArg, int &argNum, int argc, const char * const argv[], SubmitDagShallowOptions &shallowOpts); int doRecursionNew( SubmitDagDeepOptions &deepOpts, SubmitDagShallowOptions &shallowOpts ); int parseJobOrDagLine( const char *dagLine, dag_tokener &tokens, const char *fileType, const char *&submitOrDagFile, const char *&directory ); int setUpOptions( SubmitDagDeepOptions &deepOpts, SubmitDagShallowOptions &shallowOpts, StringList &dagFileAttrLines ); void ensureOutputFilesExist(const SubmitDagDeepOptions &deepOpts, SubmitDagShallowOptions &shallowOpts); int getOldSubmitFlags( SubmitDagShallowOptions &shallowOpts ); int parseArgumentsLine( const MyString &subLine, SubmitDagShallowOptions &shallowOpts ); void writeSubmitFile(/* const */ SubmitDagDeepOptions &deepOpts, /* const */ SubmitDagShallowOptions &shallowOpts, /* const */ StringList &dagFileAttrLines ); int submitDag( SubmitDagShallowOptions &shallowOpts ); //--------------------------------------------------------------------------- int main(int argc, char *argv[]) { printf("\n"); // Set up the dprintf stuff to write to stderr, so that HTCondor // libraries which use it will write to the right place... dprintf_set_tool_debug("TOOL", 0); set_debug_flags(NULL, D_ALWAYS | D_NOHEADER); config(); // Initialize our Distribution object -- condor vs. hawkeye, etc. myDistro->Init( argc, argv ); // Save submit append lines from DAG file here (see gittrac #5107). StringList dagFileAttrLines; // Load command-line arguments into the deepOpts and shallowOpts // structures. SubmitDagDeepOptions deepOpts; SubmitDagShallowOptions shallowOpts; // We're setting strScheddDaemonAdFile and strScheddAddressFile // here so that the classad updating feature (see gittrac #1782) // works properly. The problem is that the schedd daemon ad and // address files are normally defined relative to the $LOG value. // Because we specify a different log directory on the condor_dagman // command line, if we don't set the values here, condor_dagman // won't be able to find those files when it tries to communicate /// with the schedd. wenger 2013-03-11 shallowOpts.strScheddDaemonAdFile = param( "SCHEDD_DAEMON_AD_FILE" ); shallowOpts.strScheddAddressFile = param( "SCHEDD_ADDRESS_FILE" ); parseCommandLine(deepOpts, shallowOpts, argc, argv); int tmpResult; // Recursively run ourself on nested DAGs. We need to do this // depth-first so all of the lower-level .condor.sub files already // exist when we check for log files. if ( deepOpts.recurse ) { if ( param_boolean( "DAGMAN_USE_OLD_DAG_READER", false ) ) { fprintf( stderr, "Warning: DAGMAN_USE_OLD_DAG_READER " "is no longer supported\n" ); } tmpResult = doRecursionNew( deepOpts, shallowOpts ); if ( tmpResult != 0) { fprintf( stderr, "Recursive submit(s) failed; exiting without " "attempting top-level submit\n" ); return tmpResult; } } // Further work to get the shallowOpts structure set up properly. tmpResult = setUpOptions( deepOpts, shallowOpts, dagFileAttrLines ); if ( tmpResult != 0 ) return tmpResult; // Check whether the output files already exist; if so, we may // abort depending on the -f flag and whether we're running // a rescue DAG. ensureOutputFilesExist( deepOpts, shallowOpts ); // Make sure that all node jobs have log files, the files // aren't on NFS, etc. // Note that this MUST come after recursion, otherwise we'd // pass down the "preserved" values from the current .condor.sub // file. if ( deepOpts.updateSubmit ) { tmpResult = getOldSubmitFlags( shallowOpts ); if ( tmpResult != 0 ) return tmpResult; } // Write the actual submit file for DAGMan. writeSubmitFile( deepOpts, shallowOpts, dagFileAttrLines ); return submitDag( shallowOpts ); } //--------------------------------------------------------------------------- /** Recursively call condor_submit_dag on nested DAGs. @param deepOpts: the condor_submit_dag deep options @return 0 if successful, 1 if failed */ int doRecursionNew( SubmitDagDeepOptions &deepOpts, SubmitDagShallowOptions &shallowOpts ) { int result = 0; shallowOpts.dagFiles.rewind(); // Go through all DAG files specified on the command line... const char *dagFile; while ( (dagFile = shallowOpts.dagFiles.next()) ) { // Get logical lines from this DAG file. MultiLogFiles::FileReader reader; MyString errMsg = reader.Open( dagFile ); if ( errMsg != "" ) { fprintf( stderr, "Error reading DAG file: %s\n", errMsg.Value() ); return 1; } // Find and parse JOB and SUBDAG lines. MyString dagLine; while ( reader.NextLogicalLine( dagLine ) ) { dag_tokener tokens( dagLine.Value() ); tokens.rewind(); const char *first = tokens.next(); if ( first && !strcasecmp( first, "JOB" ) ) { // Get the submit file and directory from the DAG // file line. const char *subFile; const char *directory; if ( parseJobOrDagLine( dagLine.Value(), tokens, "submit", subFile, directory ) != 0 ) { return 1; } // Now figure out whether JOB line is a nested DAG. MyString submitFile( subFile ); // If submit file ends in ".condor.sub", we assume it // refers to a sub-DAG. int start = submitFile.find( DAG_SUBMIT_FILE_SUFFIX ); if ( start >= 0 && start + (int)strlen( DAG_SUBMIT_FILE_SUFFIX) == submitFile.Length() ) { // Change submit file name to DAG file name. submitFile.replaceString( DAG_SUBMIT_FILE_SUFFIX, "" ); // Now run condor_submit_dag on the DAG file. if ( runSubmitDag( deepOpts, submitFile.Value(), directory, shallowOpts.priority, false ) != 0 ) { result = 1; } } } else if ( first && !strcasecmp( first, "SUBDAG" ) ) { const char *inlineOrExt = tokens.next(); if ( strcasecmp( inlineOrExt, "EXTERNAL" ) ) { fprintf( stderr, "ERROR: only SUBDAG EXTERNAL is supported " "at this time (line: <%s>)\n", dagLine.Value() ); return 1; } // Get the nested DAG file and directory from the DAG // file line. const char *nestedDagFile; const char *directory; if ( parseJobOrDagLine( dagLine.Value(), tokens, "DAG", nestedDagFile, directory ) != 0 ) { return 1; } // Now run condor_submit_dag on the DAG file. if ( runSubmitDag( deepOpts, nestedDagFile, directory, shallowOpts.priority, false ) != 0 ) { result = 1; } } } reader.Close(); } return result; } //--------------------------------------------------------------------------- /** Parse a JOB or SUBDAG line from a DAG file. @param dagLine: the line we're parsing @param tokens: tokens of this line @param fileType: "submit" or "DAG" (to be used in error message) @param submitOrDagFile: if successful, this will point to submit or nested DAG file name @param directory: if successful, this will point to directory (NULL if not specified) @return 0 if successful, 1 if failed */ int parseJobOrDagLine( const char *dagLine, dag_tokener &tokens, const char *fileType, const char *&submitOrDagFile, const char *&directory ) { const char *nodeName = tokens.next(); if ( !nodeName) { fprintf( stderr, "No node name specified in line: <%s>\n", dagLine ); return 1; } submitOrDagFile = tokens.next(); if ( !submitOrDagFile ) { fprintf( stderr, "No %s file specified in " "line: <%s>\n", fileType, dagLine ); return 1; } directory = NULL; const char *dirKeyword = tokens.next(); if ( dirKeyword && !strcasecmp( dirKeyword, "DIR" ) ) { directory = tokens.next(); if ( !directory ) { fprintf( stderr, "No directory specified in " "line: <%s>\n", dagLine ); return 1; } } return 0; } //--------------------------------------------------------------------------- /** Set up things in deep and shallow options that aren't directly specified on the command line. @param deepOpts: the condor_submit_dag deep options @param shallowOpts: the condor_submit_dag shallow options @return 0 if successful, 1 if failed */ int setUpOptions( SubmitDagDeepOptions &deepOpts, SubmitDagShallowOptions &shallowOpts, StringList &dagFileAttrLines ) { shallowOpts.strLibOut = shallowOpts.primaryDagFile + ".lib.out"; shallowOpts.strLibErr = shallowOpts.primaryDagFile + ".lib.err"; if ( deepOpts.strOutfileDir != "" ) { shallowOpts.strDebugLog = deepOpts.strOutfileDir + DIR_DELIM_STRING + condor_basename( shallowOpts.primaryDagFile.Value() ); } else { shallowOpts.strDebugLog = shallowOpts.primaryDagFile; } shallowOpts.strDebugLog += ".dagman.out"; shallowOpts.strSchedLog = shallowOpts.primaryDagFile + ".dagman.log"; shallowOpts.strSubFile = shallowOpts.primaryDagFile + DAG_SUBMIT_FILE_SUFFIX; MyString rescueDagBase; // If we're running each DAG in its own directory, write any rescue // DAG to the current directory, to avoid confusion (since the // rescue DAG must be run from the current directory). if ( deepOpts.useDagDir ) { if ( !condor_getcwd( rescueDagBase ) ) { fprintf( stderr, "ERROR: unable to get cwd: %d, %s\n", errno, strerror(errno) ); return 1; } rescueDagBase += DIR_DELIM_STRING; rescueDagBase += condor_basename(shallowOpts.primaryDagFile.Value()); } else { rescueDagBase = shallowOpts.primaryDagFile; } // If we're running multiple DAGs, put "_multi" in the rescue // DAG name to indicate that the rescue DAG is for *all* of // the DAGs we're running. if ( shallowOpts.dagFiles.number() > 1 ) { rescueDagBase += "_multi"; } shallowOpts.strRescueFile = rescueDagBase + ".rescue"; shallowOpts.strLockFile = shallowOpts.primaryDagFile + ".lock"; if (deepOpts.strDagmanPath == "" ) { deepOpts.strDagmanPath = which( dagman_exe ); } if (deepOpts.strDagmanPath == "") { fprintf( stderr, "ERROR: can't find %s in PATH, aborting.\n", dagman_exe ); return 1; } MyString msg; if ( !GetConfigAndAttrs( shallowOpts.dagFiles, deepOpts.useDagDir, shallowOpts.strConfigFile, dagFileAttrLines, msg) ) { fprintf( stderr, "ERROR: %s\n", msg.Value() ); return 1; } return 0; } //--------------------------------------------------------------------------- /** Submit the DAGMan submit file unless the -no_submit option was given. @param shallowOpts: the condor_submit_dag shallow options @return 0 if successful, 1 if failed */ int submitDag( SubmitDagShallowOptions &shallowOpts ) { printf("-----------------------------------------------------------------------\n"); printf("File for submitting this DAG to HTCondor : %s\n", shallowOpts.strSubFile.Value()); printf("Log of DAGMan debugging messages : %s\n", shallowOpts.strDebugLog.Value()); printf("Log of HTCondor library output : %s\n", shallowOpts.strLibOut.Value()); printf("Log of HTCondor library error messages : %s\n", shallowOpts.strLibErr.Value()); printf("Log of the life of condor_dagman itself : %s\n", shallowOpts.strSchedLog.Value()); printf("\n"); if (shallowOpts.bSubmit) { ArgList args; args.AppendArg( "condor_submit" ); if( shallowOpts.strRemoteSchedd != "" ) { args.AppendArg( "-r" ); args.AppendArg( shallowOpts.strRemoteSchedd ); } args.AppendArg( shallowOpts.strSubFile ); // It is important to set the destination Schedd before // calling condor_submit, otherwise it may submit to the // wrong Schedd. // // my_system() has a variant that takes an Env. // Unfortunately, it results in an execve and no path // searching, which makes the relative path to // "condor_submit" above not work. Instead, we'll set the // env before execvp is called. It may be more correct to // fix my_system to inject the Env after the fork() and // before the execvp(). if ( shallowOpts.strScheddDaemonAdFile != "" ) { SetEnv("_CONDOR_SCHEDD_DAEMON_AD_FILE", shallowOpts.strScheddDaemonAdFile.Value()); } if ( shallowOpts.strScheddAddressFile != "" ) { SetEnv("_CONDOR_SCHEDD_ADDRESS_FILE", shallowOpts.strScheddAddressFile.Value()); } int retval = my_system( args ); if( retval != 0 ) { fprintf( stderr, "ERROR: condor_submit failed; aborting.\n" ); return 1; } } else { printf("-no_submit given, not submitting DAG to HTCondor. " "You can do this with:\n"); printf("\"condor_submit %s\"\n", shallowOpts.strSubFile.Value()); } printf("-----------------------------------------------------------------------\n"); return 0; } //--------------------------------------------------------------------------- bool fileExists(const MyString &strFile) { int fd = safe_open_wrapper_follow(strFile.Value(), O_RDONLY); if (fd == -1) return false; close(fd); return true; } //--------------------------------------------------------------------------- void ensureOutputFilesExist(const SubmitDagDeepOptions &deepOpts, SubmitDagShallowOptions &shallowOpts) { int maxRescueDagNum = param_integer("DAGMAN_MAX_RESCUE_NUM", MAX_RESCUE_DAG_DEFAULT, 0, ABS_MAX_RESCUE_DAG_NUM); if (deepOpts.doRescueFrom > 0) { MyString rescueDagName = RescueDagName(shallowOpts.primaryDagFile.Value(), shallowOpts.dagFiles.number() > 1, deepOpts.doRescueFrom); if (!fileExists(rescueDagName)) { fprintf( stderr, "-dorescuefrom %d specified, but rescue " "DAG file %s does not exist!\n", deepOpts.doRescueFrom, rescueDagName.Value() ); exit( 1 ); } } // Get rid of the halt file (if one exists). tolerant_unlink( HaltFileName( shallowOpts.primaryDagFile ).Value() ); if (deepOpts.bForce) { tolerant_unlink(shallowOpts.strSubFile.Value()); tolerant_unlink(shallowOpts.strSchedLog.Value()); tolerant_unlink(shallowOpts.strLibOut.Value()); tolerant_unlink(shallowOpts.strLibErr.Value()); RenameRescueDagsAfter(shallowOpts.primaryDagFile.Value(), shallowOpts.dagFiles.number() > 1, 0, maxRescueDagNum); } // Check whether we're automatically running a rescue DAG -- if // so, allow things to continue even if the files generated // by condor_submit_dag already exist. bool autoRunningRescue = false; if (deepOpts.autoRescue) { int rescueDagNum = FindLastRescueDagNum(shallowOpts.primaryDagFile.Value(), shallowOpts.dagFiles.number() > 1, maxRescueDagNum); if (rescueDagNum > 0) { printf("Running rescue DAG %d\n", rescueDagNum); autoRunningRescue = true; } } bool bHadError = false; // If not running a rescue DAG, check for existing files // generated by condor_submit_dag... if (!autoRunningRescue && deepOpts.doRescueFrom < 1 && !deepOpts.updateSubmit) { if (fileExists(shallowOpts.strSubFile)) { fprintf( stderr, "ERROR: \"%s\" already exists.\n", shallowOpts.strSubFile.Value() ); bHadError = true; } if (fileExists(shallowOpts.strLibOut)) { fprintf( stderr, "ERROR: \"%s\" already exists.\n", shallowOpts.strLibOut.Value() ); bHadError = true; } if (fileExists(shallowOpts.strLibErr)) { fprintf( stderr, "ERROR: \"%s\" already exists.\n", shallowOpts.strLibErr.Value() ); bHadError = true; } if (fileExists(shallowOpts.strSchedLog)) { fprintf( stderr, "ERROR: \"%s\" already exists.\n", shallowOpts.strSchedLog.Value() ); bHadError = true; } } // This is checking for the existance of an "old-style" rescue // DAG file. if (!deepOpts.autoRescue && deepOpts.doRescueFrom < 1 && fileExists(shallowOpts.strRescueFile)) { fprintf( stderr, "ERROR: \"%s\" already exists.\n", shallowOpts.strRescueFile.Value() ); fprintf( stderr, " You may want to resubmit your DAG using that " "file, instead of \"%s\"\n", shallowOpts.primaryDagFile.Value()); fprintf( stderr, " Look at the HTCondor manual for details about DAG " "rescue files.\n" ); fprintf( stderr, " Please investigate and either remove \"%s\",\n", shallowOpts.strRescueFile.Value() ); fprintf( stderr, " or use it as the input to condor_submit_dag.\n" ); bHadError = true; } if (bHadError) { fprintf( stderr, "\nSome file(s) needed by %s already exist. ", dagman_exe ); fprintf( stderr, "Either rename them,\nuse the \"-f\" option to " "force them to be overwritten, or use\n" "the \"-update_submit\" option to update the submit " "file and continue.\n" ); exit( 1 ); } } //--------------------------------------------------------------------------- /** Get the command-line options we want to preserve from the .condor.sub file we're overwriting, and plug them into the shallowOpts structure. Note that it's *not* an error for the .condor.sub file to not exist. @param shallowOpts: the condor_submit_dag shallow options @return 0 if successful, 1 if failed */ int getOldSubmitFlags(SubmitDagShallowOptions &shallowOpts) { // It's not an error for the submit file to not exist. if ( fileExists( shallowOpts.strSubFile ) ) { MultiLogFiles::FileReader reader; MyString error = reader.Open( shallowOpts.strSubFile ); if ( error != "" ) { fprintf( stderr, "Error reading submit file: %s\n", error.Value() ); return 1; } MyString subLine; while ( reader.NextLogicalLine( subLine ) ) { StringList tokens( subLine.Value(), " \t" ); tokens.rewind(); const char *first = tokens.next(); if ( first && !strcasecmp( first, "arguments" ) ) { if ( parseArgumentsLine( subLine, shallowOpts ) != 0 ) { return 1; } } } reader.Close(); } return 0; } //--------------------------------------------------------------------------- /** Parse the arguments line of an existing .condor.sub file, extracing the arguments we want to preserve when updating the .condor.sub file. @param subLine: the arguments line from the .condor.sub file @param shallowOpts: the condor_submit_dag shallow options @return 0 if successful, 1 if failed */ int parseArgumentsLine( const MyString &subLine, SubmitDagShallowOptions &shallowOpts ) { const char *line = subLine.Value(); const char *start = strchr( line, '"' ); const char *end = strrchr( line, '"' ); MyString arguments; if ( start && end ) { arguments = subLine.substr( start - line, 1 + end - start ); } else { fprintf( stderr, "Missing quotes in arguments line: <%s>\n", subLine.Value() ); return 1; } ArgList arglist; MyString error; if ( !arglist.AppendArgsV2Quoted( arguments.Value(), &error ) ) { fprintf( stderr, "Error parsing arguments: %s\n", error.Value() ); return 1; } for ( int argNum = 0; argNum < arglist.Count(); argNum++ ) { MyString strArg = arglist.GetArg( argNum ); strArg.lower_case(); char **args = arglist.GetStringArray(); (void)parsePreservedArgs( strArg, argNum, arglist.Count(), args, shallowOpts); deleteStringArray(args); } return 0; } class EnvFilter : public Env { public: EnvFilter( void ) { }; virtual ~EnvFilter( void ) { }; virtual bool ImportFilter( const MyString & /*var*/, const MyString & /*val*/ ) const; }; bool EnvFilter::ImportFilter( const MyString &var, const MyString &val ) const { if ( (var.find(";") >= 0) || (val.find(";") >= 0) ) { return false; } return IsSafeEnvV2Value( val.Value() ); } //--------------------------------------------------------------------------- void writeSubmitFile( /* const */ SubmitDagDeepOptions &deepOpts, /* const */ SubmitDagShallowOptions &shallowOpts, /* const */ StringList &dagFileAttrLines ) { FILE *pSubFile = safe_fopen_wrapper_follow(shallowOpts.strSubFile.Value(), "w"); if (!pSubFile) { fprintf( stderr, "ERROR: unable to create submit file %s\n", shallowOpts.strSubFile.Value() ); exit( 1 ); } const char *executable = NULL; MyString valgrindPath; // outside if so executable is valid! if ( shallowOpts.runValgrind ) { valgrindPath = which( valgrind_exe ); if ( valgrindPath == "" ) { fprintf( stderr, "ERROR: can't find %s in PATH, aborting.\n", valgrind_exe ); exit( 1 ); } else { executable = valgrindPath.Value(); } } else { executable = deepOpts.strDagmanPath.Value(); } fprintf(pSubFile, "# Filename: %s\n", shallowOpts.strSubFile.Value()); fprintf(pSubFile, "# Generated by condor_submit_dag "); shallowOpts.dagFiles.rewind(); char *dagFile; while ( (dagFile = shallowOpts.dagFiles.next()) != NULL ) { fprintf(pSubFile, "%s ", dagFile); } fprintf(pSubFile, "\n"); fprintf(pSubFile, "universe\t= scheduler\n"); fprintf(pSubFile, "executable\t= %s\n", executable); fprintf(pSubFile, "getenv\t\t= True\n"); fprintf(pSubFile, "output\t\t= %s\n", shallowOpts.strLibOut.Value()); fprintf(pSubFile, "error\t\t= %s\n", shallowOpts.strLibErr.Value()); fprintf(pSubFile, "log\t\t= %s\n", shallowOpts.strSchedLog.Value()); if ( ! deepOpts.batchName.empty() ) { fprintf(pSubFile, "+%s\t= \"%s\"\n", ATTR_JOB_BATCH_NAME, deepOpts.batchName.c_str()); } #if !defined ( WIN32 ) fprintf(pSubFile, "remove_kill_sig\t= SIGUSR1\n" ); #endif fprintf(pSubFile, "+%s\t= \"%s =?= $(cluster)\"\n", ATTR_OTHER_JOB_REMOVE_REQUIREMENTS, ATTR_DAGMAN_JOB_ID ); // ensure DAGMan is automatically requeued by the schedd if it // exits abnormally or is killed (e.g., during a reboot) const char *defaultRemoveExpr = "( ExitSignal =?= 11 || " "(ExitCode =!= UNDEFINED && ExitCode >=0 && ExitCode <= 2))"; MyString removeExpr(defaultRemoveExpr); char *tmpRemoveExpr = param( "DAGMAN_ON_EXIT_REMOVE" ); if ( tmpRemoveExpr ) { removeExpr = tmpRemoveExpr; free(tmpRemoveExpr); } fprintf(pSubFile, "# Note: default on_exit_remove expression:\n"); fprintf(pSubFile, "# %s\n", defaultRemoveExpr); fprintf(pSubFile, "# attempts to ensure that DAGMan is automatically\n"); fprintf(pSubFile, "# requeued by the schedd if it exits abnormally or\n"); fprintf(pSubFile, "# is killed (e.g., during a reboot).\n"); fprintf(pSubFile, "on_exit_remove\t= %s\n", removeExpr.Value() ); fprintf(pSubFile, "copy_to_spool\t= %s\n", shallowOpts.copyToSpool ? "True" : "False" ); //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Be sure to change MIN_SUBMIT_FILE_VERSION in dagman_main.cpp // if the arguments passed to condor_dagman change in an // incompatible way!! //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ArgList args; if ( shallowOpts.runValgrind ) { args.AppendArg("--tool=memcheck"); args.AppendArg("--leak-check=yes"); args.AppendArg("--show-reachable=yes"); args.AppendArg(deepOpts.strDagmanPath.Value()); } // -p 0 causes DAGMan to run w/o a command socket (see gittrac #4987). args.AppendArg("-p"); args.AppendArg("0"); args.AppendArg("-f"); args.AppendArg("-l"); args.AppendArg("."); if ( shallowOpts.iDebugLevel != DEBUG_UNSET ) { args.AppendArg("-Debug"); args.AppendArg(shallowOpts.iDebugLevel); } args.AppendArg("-Lockfile"); args.AppendArg(shallowOpts.strLockFile.Value()); args.AppendArg("-AutoRescue"); args.AppendArg(deepOpts.autoRescue); args.AppendArg("-DoRescueFrom"); args.AppendArg(deepOpts.doRescueFrom); shallowOpts.dagFiles.rewind(); while ( (dagFile = shallowOpts.dagFiles.next()) != NULL ) { args.AppendArg("-Dag"); args.AppendArg(dagFile); } if(shallowOpts.iMaxIdle != 0) { args.AppendArg("-MaxIdle"); args.AppendArg(shallowOpts.iMaxIdle); } if(shallowOpts.iMaxJobs != 0) { args.AppendArg("-MaxJobs"); args.AppendArg(shallowOpts.iMaxJobs); } if(shallowOpts.iMaxPre != 0) { args.AppendArg("-MaxPre"); args.AppendArg(shallowOpts.iMaxPre); } if(shallowOpts.iMaxPost != 0) { args.AppendArg("-MaxPost"); args.AppendArg(shallowOpts.iMaxPost); } if ( shallowOpts.bPostRunSet ) { if (shallowOpts.bPostRun) { args.AppendArg("-AlwaysRunPost"); } else { args.AppendArg("-DontAlwaysRunPost"); } } if(deepOpts.useDagDir) { args.AppendArg("-UseDagDir"); } if(deepOpts.suppress_notification) { args.AppendArg("-Suppress_notification"); } else { args.AppendArg("-Dont_Suppress_notification"); } if ( shallowOpts.doRecovery ) { args.AppendArg( "-DoRecov" ); } args.AppendArg("-CsdVersion"); args.AppendArg(CondorVersion()); if(deepOpts.allowVerMismatch) { args.AppendArg("-AllowVersionMismatch"); } if(shallowOpts.dumpRescueDag) { args.AppendArg("-DumpRescue"); } if(deepOpts.bVerbose) { args.AppendArg("-Verbose"); } if(deepOpts.bForce) { args.AppendArg("-Force"); } if(deepOpts.strNotification != "") { args.AppendArg("-Notification"); args.AppendArg(deepOpts.strNotification); } if(deepOpts.strDagmanPath != "") { args.AppendArg("-Dagman"); args.AppendArg(deepOpts.strDagmanPath); } if(deepOpts.strOutfileDir != "") { args.AppendArg("-Outfile_dir"); args.AppendArg(deepOpts.strOutfileDir); } if(deepOpts.updateSubmit) { args.AppendArg("-Update_submit"); } if(deepOpts.importEnv) { args.AppendArg("-Import_env"); } if( shallowOpts.priority != 0 ) { args.AppendArg("-Priority"); args.AppendArg(shallowOpts.priority); } MyString arg_str,args_error; if(!args.GetArgsStringV1WackedOrV2Quoted(&arg_str,&args_error)) { fprintf(stderr,"Failed to insert arguments: %s",args_error.Value()); exit(1); } fprintf(pSubFile, "arguments\t= %s\n", arg_str.Value()); //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Be sure to change MIN_SUBMIT_FILE_VERSION in dagman_main.cpp // if the environment passed to condor_dagman changes in an // incompatible way!! //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ EnvFilter env; if ( deepOpts.importEnv ) { env.Import( ); } env.SetEnv("_CONDOR_DAGMAN_LOG", shallowOpts.strDebugLog.Value()); env.SetEnv("_CONDOR_MAX_DAGMAN_LOG=0"); if ( shallowOpts.strScheddDaemonAdFile != "" ) { env.SetEnv("_CONDOR_SCHEDD_DAEMON_AD_FILE", shallowOpts.strScheddDaemonAdFile.Value()); } if ( shallowOpts.strScheddAddressFile != "" ) { env.SetEnv("_CONDOR_SCHEDD_ADDRESS_FILE", shallowOpts.strScheddAddressFile.Value()); } if ( shallowOpts.strConfigFile != "" ) { if ( access( shallowOpts.strConfigFile.Value(), F_OK ) != 0 ) { fprintf( stderr, "ERROR: unable to read config file %s " "(error %d, %s)\n", shallowOpts.strConfigFile.Value(), errno, strerror(errno) ); exit(1); } env.SetEnv("_CONDOR_DAGMAN_CONFIG_FILE", shallowOpts.strConfigFile.Value()); } MyString env_str; MyString env_errors; if ( !env.getDelimitedStringV1RawOrV2Quoted( &env_str, &env_errors ) ) { fprintf( stderr,"Failed to insert environment: %s", env_errors.Value() ); exit(1); } fprintf(pSubFile, "environment\t= %s\n",env_str.Value()); if ( deepOpts.strNotification != "" ) { fprintf( pSubFile, "notification\t= %s\n", deepOpts.strNotification.Value() ); } // Append user-specified stuff to submit file... // ...first, the insert file, if any... if ( shallowOpts.appendFile != "" ) { FILE *aFile = safe_fopen_wrapper_follow( shallowOpts.appendFile.Value(), "r"); if ( !aFile ) { fprintf( stderr, "ERROR: unable to read submit append file (%s)\n", shallowOpts.appendFile.Value() ); exit( 1 ); } char *line; int lineno = 0; while ( (line = getline_trim( aFile, lineno )) != NULL ) { fprintf(pSubFile, "%s\n", line); } fclose( aFile ); } // ...now append lines specified in the DAG file... dagFileAttrLines.rewind(); char *attrCmd; while ( (attrCmd = dagFileAttrLines.next()) != NULL ) { // Note: prepending "+" here means that this only works // for setting ClassAd attributes. fprintf( pSubFile, "+%s\n", attrCmd ); } // ...now things specified directly on the command line. shallowOpts.appendLines.rewind(); char *command; while ( (command = shallowOpts.appendLines.next()) != NULL ) { fprintf( pSubFile, "%s\n", command ); } fprintf(pSubFile, "queue\n"); fclose(pSubFile); } //--------------------------------------------------------------------------- void parseCommandLine(SubmitDagDeepOptions &deepOpts, SubmitDagShallowOptions &shallowOpts, int argc, const char * const argv[]) { for (int iArg = 1; iArg < argc; iArg++) { MyString strArg = argv[iArg]; if (strArg[0] != '-') { // We assume an argument without a leading hyphen is // a DAG file name. shallowOpts.dagFiles.append(strArg.Value()); if ( shallowOpts.primaryDagFile == "" ) { shallowOpts.primaryDagFile = strArg; } } else if (shallowOpts.primaryDagFile != "") { // Disallow hyphen args after DAG file name(s). printf("ERROR: no arguments allowed after DAG file name(s)\n"); printUsage(); } else { strArg.lower_case(); // Note: in checking the argument names here, we only check for // as much of the full name as we need to unambiguously define // the argument. if (strArg.find("-no_s") != -1) // -no_submit { shallowOpts.bSubmit = false; } else if (strArg.find("-vers") != -1) // -version { printf( "%s\n%s\n", CondorVersion(), CondorPlatform() ); exit( 0 ); } else if (strArg.find("-help") != -1 || strArg.find("-h") != -1) // -help { printUsage(0); } // submit and stick to a specific schedd else if (strArg.find("-schedd-daemon-ad-file") != -1) { if (iArg + 1 >= argc) { fprintf(stderr, "-schedd-daemon-ad-file argument needs a value\n"); printUsage(); } shallowOpts.strScheddDaemonAdFile = argv[++iArg]; } // submit and stick to a specific schedd else if (strArg.find("-schedd-address-file") != -1) { if (iArg + 1 >= argc) { fprintf(stderr, "-schedd-address-file argument needs a value\n"); printUsage(); } shallowOpts.strScheddAddressFile = argv[++iArg]; } else if (strArg.find("-f") != -1) // -force { deepOpts.bForce = true; } else if (strArg.find("-not") != -1) // -notification { if (iArg + 1 >= argc) { fprintf(stderr, "-notification argument needs a value\n"); printUsage(); } deepOpts.strNotification = argv[++iArg]; } else if (strArg.find("-r") != -1) // submit to remote schedd { if (iArg + 1 >= argc) { fprintf(stderr, "-r argument needs a value\n"); printUsage(); } shallowOpts.strRemoteSchedd = argv[++iArg]; } else if (strArg.find("-dagman") != -1) { if (iArg + 1 >= argc) { fprintf(stderr, "-dagman argument needs a value\n"); printUsage(); } deepOpts.strDagmanPath = argv[++iArg]; } else if (strArg.find("-de") != -1) // -debug { if (iArg + 1 >= argc) { fprintf(stderr, "-debug argument needs a value\n"); printUsage(); } shallowOpts.iDebugLevel = atoi(argv[++iArg]); } else if (strArg.find("-noev") != -1) // -noeventchecks { printf( "Warning: -NoEventChecks is ignored; please use " "the DAGMAN_ALLOW_EVENTS config parameter instead\n"); } else if (strArg.find("-allowlog") != -1) // -allowlogerror { fprintf( stderr, "Warning: -AllowLogError is no longer supported\n" ); } else if (strArg.find("-use") != -1) // -usedagdir { deepOpts.useDagDir = true; } else if (strArg.find("-out") != -1) // -outfile_dir { if (iArg + 1 >= argc) { fprintf(stderr, "-outfile_dir argument needs a value\n"); printUsage(); } deepOpts.strOutfileDir = argv[++iArg]; } else if (strArg.find("-con") != -1) // -config { if (iArg + 1 >= argc) { fprintf(stderr, "-config argument needs a value\n"); printUsage(); } shallowOpts.strConfigFile = argv[++iArg]; // Internally we deal with all configuration file paths // as full paths, to make it easier to determine whether // several paths point to the same file. MyString errMsg; if (!MakePathAbsolute(shallowOpts.strConfigFile, errMsg)) { fprintf( stderr, "%s\n", errMsg.Value() ); exit( 1 ); } } else if (strArg.find("-app") != -1) // -append { if (iArg + 1 >= argc) { fprintf(stderr, "-append argument needs a value\n"); printUsage(); } shallowOpts.appendLines.append(argv[++iArg]); } else if (strArg.find("-bat") != -1) // -batch-name { if (iArg + 1 >= argc) { fprintf(stderr, "-batch-name argument needs a value\n"); printUsage(); } deepOpts.batchName = argv[++iArg]; deepOpts.batchName.trim_quotes("\""); // trim "" if any } else if (strArg.find("-insert") != -1) // -insert_sub_file { if (iArg + 1 >= argc) { fprintf(stderr, "-insert_sub_file argument needs a value\n"); printUsage(); } ++iArg; if (shallowOpts.appendFile != "") { printf("Note: -insert_sub_file value (%s) overriding " "DAGMAN_INSERT_SUB_FILE setting (%s)\n", argv[iArg], shallowOpts.appendFile.Value()); } shallowOpts.appendFile = argv[iArg]; } else if (strArg.find("-autor") != -1) // -autorescue { if (iArg + 1 >= argc) { fprintf(stderr, "-autorescue argument needs a value\n"); printUsage(); } deepOpts.autoRescue = (atoi(argv[++iArg]) != 0); } else if (strArg.find("-dores") != -1) // -dorescuefrom { if (iArg + 1 >= argc) { fprintf(stderr, "-dorescuefrom argument needs a value\n"); printUsage(); } deepOpts.doRescueFrom = atoi(argv[++iArg]); } else if (strArg.find("-allowver") != -1) // -AllowVersionMismatch { deepOpts.allowVerMismatch = true; } else if (strArg.find("-no_rec") != -1) // -no_recurse { deepOpts.recurse = false; } else if (strArg.find("-do_rec") != -1) // -do_recurse { deepOpts.recurse = true; } else if (strArg.find("-updat") != -1) // -update_submit { deepOpts.updateSubmit = true; } else if (strArg.find("-import_env") != -1) // -import_env { deepOpts.importEnv = true; } else if (strArg.find("-dumpr") != -1) // -DumpRescue { shallowOpts.dumpRescueDag = true; } else if (strArg.find("-valgrind") != -1) // -valgrind { shallowOpts.runValgrind = true; } // This must come last, so we can have other arguments // that start with -v. else if ( (strArg.find("-v") != -1) ) // -verbose { deepOpts.bVerbose = true; } else if ( (strArg.find("-dontalwaysrun") != -1) ) // DontAlwaysRunPost { if ( shallowOpts.bPostRunSet && shallowOpts.bPostRun ) { fprintf( stderr, "ERROR: -DontAlwaysRunPost and -AlwaysRunPost are both set!\n" ); exit(1); } shallowOpts.bPostRunSet = true; shallowOpts.bPostRun = false; } else if ( (strArg.find("-alwaysrun") != -1) ) // AlwaysRunPost { if ( shallowOpts.bPostRunSet && !shallowOpts.bPostRun ) { fprintf( stderr, "ERROR: -DontAlwaysRunPost and -AlwaysRunPost are both set!\n" ); exit(1); } shallowOpts.bPostRunSet = true; shallowOpts.bPostRun = true; } else if ( (strArg.find("-dont_use_default_node_log") != -1) ) { fprintf( stderr, "Error: -dont_use_default_node_log is no longer allowed\n" ); printUsage(); } else if ( (strArg.find("-suppress_notification") != -1) ) { deepOpts.suppress_notification = true; } else if ( (strArg.find("-dont_suppress_notification") != -1) ) { deepOpts.suppress_notification = false; } else if( (strArg.find("-prio") != -1) ) // -priority { if(iArg + 1 >= argc) { fprintf(stderr, "-priority argument needs a value\n"); printUsage(); } shallowOpts.priority = atoi(argv[++iArg]); } else if ( (strArg.find("-dorecov") != -1) ) { shallowOpts.doRecovery = true; } else if ( parsePreservedArgs( strArg, iArg, argc, argv, shallowOpts) ) { // No-op here } else { fprintf( stderr, "ERROR: unknown option %s\n", strArg.Value() ); printUsage(); } } } if (shallowOpts.primaryDagFile == "") { fprintf( stderr, "ERROR: no dag file specified; aborting.\n" ); printUsage(); } if (deepOpts.doRescueFrom < 0) { fprintf( stderr, "-dorescuefrom value must be non-negative; aborting.\n"); printUsage(); } } //--------------------------------------------------------------------------- /** Parse arguments that are to be preserved when updating a .condor.sub file. If the given argument such an argument, parse it and update the shallowOpts structure accordingly. (This function is meant to be called both when parsing "normal" command-line arguments, and when parsing the existing arguments line of a .condor.sub file we're overwriting.) @param strArg: the argument we're parsing @param argNum: the argument number of the current argument @param argc: the argument count (passed to get value for flag) @param argv: the argument vector (passed to get value for flag) @param shallowOpts: the condor_submit_dag shallow options @return true iff the argument vector contained any arguments processed by this function */ bool parsePreservedArgs(const MyString &strArg, int &argNum, int argc, const char * const argv[], SubmitDagShallowOptions &shallowOpts) { bool result = false; if (strArg.find("-maxi") != -1) // -maxidle { if (argNum + 1 >= argc) { fprintf(stderr, "-maxidle argument needs a value\n"); printUsage(); } shallowOpts.iMaxIdle = atoi(argv[++argNum]); result = true; } else if (strArg.find("-maxj") != -1) // -maxjobs { if (argNum + 1 >= argc) { fprintf(stderr, "-maxjobs argument needs a value\n"); printUsage(); } shallowOpts.iMaxJobs = atoi(argv[++argNum]); result = true; } else if (strArg.find("-maxpr") != -1) // -maxpre { if (argNum + 1 >= argc) { fprintf(stderr, "-maxpre argument needs a value\n"); printUsage(); } shallowOpts.iMaxPre = atoi(argv[++argNum]); result = true; } else if (strArg.find("-maxpo") != -1) // -maxpost { if (argNum + 1 >= argc) { fprintf(stderr, "-maxpost argument needs a value\n"); printUsage(); } shallowOpts.iMaxPost = atoi(argv[++argNum]); result = true; } return result; } //--------------------------------------------------------------------------- int printUsage(int iExitCode) { printf("Usage: condor_submit_dag [options] dag_file [dag_file_2 ... dag_file_n]\n"); printf(" where dag_file1, etc., is the name of a DAG input file\n"); printf(" and where [options] is one or more of:\n"); printf(" -help (print usage info and exit)\n"); printf(" -version (print version and exit)\n"); printf(" -dagman <path> (Full path to an alternate condor_dagman executable)\n"); printf(" -no_submit (DAG is not submitted to HTCondor)\n"); printf(" -verbose (Verbose error messages from condor_submit_dag)\n"); printf(" -force (Overwrite files condor_submit_dag uses if they exist)\n"); printf(" -r <schedd_name> (Submit to the specified remote schedd)\n"); printf(" -schedd-daemon-ad-file <path> (Submit to the schedd who dropped the ad file)\n"); printf(" -schedd-address-file <path> (Submit to the schedd who dropped the address file)\n"); printf(" -maxidle <number> (Maximum number of idle nodes to allow)\n"); printf(" -maxjobs <number> (Maximum number of jobs ever submitted at once)\n"); printf(" -MaxPre <number> (Maximum number of PRE scripts to run at once)\n"); printf(" -MaxPost <number> (Maximum number of POST scripts to run at once)\n"); printf(" -notification <value> (Determines how much email you get from HTCondor.\n"); printf(" See the condor_submit man page for values.)\n"); printf(" -NoEventChecks (Now ignored -- use DAGMAN_ALLOW_EVENTS)\n"); printf(" -DontAlwaysRunPost (Don't run POST script if PRE script fails)\n"); printf(" -AlwaysRunPost (Run POST script if PRE script fails)\n"); printf(" -AllowLogError (Allows the DAG to attempt execution even if the log\n"); printf(" reading code finds errors when parsing the submit files)\n"); printf(" (-AllowLogError is no longer supported as of 8.5.5)\n"); printf(" -UseDagDir (Run DAGs in directories specified in DAG file paths)\n"); printf(" -debug <number> (Determines how verbosely DAGMan logs its work\n"); printf(" about the life of the condor_dagman job. 'value' must be\n"); printf(" an integer with a value of 0-7 inclusive.)\n"); printf(" -outfile_dir <path> (Directory into which to put the dagman.out file,\n"); printf(" instead of the default\n"); printf(" -config <filename> (Specify a DAGMan configuration file)\n"); printf(" -append <command> (Append specified command to .condor.sub file)\n"); printf(" -insert_sub_file <filename> (Insert specified file into .condor.sub file)\n"); printf(" -batch-name <name> (Set the batch name for the dag)\n"); printf(" -AutoRescue 0|1 (whether to automatically run newest rescue DAG;\n"); printf(" 0 = false, 1 = true)\n"); printf(" -DoRescueFrom <number> (run rescue DAG of given number)\n"); printf(" -AllowVersionMismatch (allow version mismatch between the\n"); printf(" .condor.sub file and the condor_dagman binary)\n"); printf(" -no_recurse (don't recurse in nested DAGs)\n"); printf(" -do_recurse (do recurse in nested DAGs)\n"); printf(" -update_submit (update submit file if it exists)\n"); printf(" -import_env (explicitly import env into submit file)\n"); printf(" -DumpRescue (DAGMan dumps rescue DAG and exits)\n"); printf(" -valgrind (create submit file to run valgrind on DAGMan)\n"); printf(" -priority <priority> (jobs will run with this priority by default)\n"); printf(" -dont_use_default_node_log (Restore pre-7.9.0 behavior of using UserLog only)\n"); printf(" (-dont_use_default_node_log is no longer allowed as of 8.3.1)\n"); printf(" -suppress_notification (Set \"notification = never\" in all jobs submitted by this DAGMan)\n"); printf(" -dont_suppress_notification (Allow jobs to specify notification)\n"); printf(" -DoRecov (run in recovery mode)\n"); exit(iExitCode); }
32.608278
108
0.641356
[ "object", "vector" ]
db015250bb1d394eef33503979b200139ae15332
1,658
cc
C++
onnx/optimizer/optimize.cc
HeliWang/onnx-fixed
266ec0a6a302d99710921f9bc8047d5fe3558328
[ "MIT" ]
2
2021-07-31T20:42:42.000Z
2021-11-17T11:01:14.000Z
onnx/optimizer/optimize.cc
HeliWang/onnx-fixed
266ec0a6a302d99710921f9bc8047d5fe3558328
[ "MIT" ]
null
null
null
onnx/optimizer/optimize.cc
HeliWang/onnx-fixed
266ec0a6a302d99710921f9bc8047d5fe3558328
[ "MIT" ]
null
null
null
// ATTENTION: The code in this file is highly EXPERIMENTAL. // Adventurous users should note that the APIs will probably change. #include "onnx/optimizer/optimize.h" namespace ONNX_NAMESPACE { namespace optimization { void PrepareOutput(const ONNX_NAMESPACE::ModelProto& mp_in, ONNX_NAMESPACE::ModelProto& mp_out) { if (mp_in.has_producer_name()) { mp_out.set_ir_version(mp_in.ir_version()); } if (mp_in.has_producer_name()) { mp_out.set_producer_name(mp_in.producer_name()); } if (mp_in.has_producer_version()) { mp_out.set_producer_version(mp_in.producer_version()); } if (mp_in.has_domain()) { mp_out.set_domain(mp_in.domain()); } if (mp_in.has_model_version()) { mp_out.set_model_version(mp_in.model_version()); } if (mp_in.has_doc_string()) { mp_out.set_doc_string(mp_in.doc_string()); } for (int i = 0; i < mp_in.opset_import_size(); i++) { auto& oi_in = mp_in.opset_import(i); auto* oi_out = mp_out.add_opset_import(); if (oi_in.has_domain()) { oi_out->set_domain(oi_in.domain()); } if (oi_in.has_version()) { oi_out->set_version(oi_in.version()); } } for (int i = 0; i < mp_in.metadata_props_size(); i++) { auto& pp_in = mp_in.metadata_props(i); auto* pp_out = mp_out.add_metadata_props(); if (pp_in.has_key()) { pp_out->set_key(pp_in.key()); } if (pp_in.has_value()) { pp_out->set_value(pp_in.value()); } } } static Optimizer _optimizer; ONNX_NAMESPACE::ModelProto Optimize( const ONNX_NAMESPACE::ModelProto& mp_in, const std::vector<std::string>& names) { return _optimizer.optimize(mp_in, names); } }}
28.101695
97
0.679131
[ "vector" ]
db121a0c51df14c3bba175a169554645c462c786
1,070
cpp
C++
Competitive Programming/String/LongestDistinctCharacter.cpp
shreejitverma/GeeksforGeeks
d7bcb166369fffa9a031a258e925b6aff8d44e6c
[ "MIT" ]
2
2022-02-18T05:14:28.000Z
2022-03-08T07:00:08.000Z
Competitive Programming/String/LongestDistinctCharacter.cpp
shivaniverma1/Competitive-Programming-1
d7bcb166369fffa9a031a258e925b6aff8d44e6c
[ "MIT" ]
6
2022-01-13T04:31:04.000Z
2022-03-12T01:06:16.000Z
Competitive Programming/String/LongestDistinctCharacter.cpp
shivaniverma1/Competitive-Programming-1
d7bcb166369fffa9a031a258e925b6aff8d44e6c
[ "MIT" ]
2
2022-02-14T19:53:53.000Z
2022-02-18T05:14:30.000Z
#include<bits/stdc++.h> using namespace std; int main(){ //code int t; cin >> t; while(t--){ string s; cin >> s; int n = s.size(); if(s.size()==0){ return 0; } int i=0, j=0; vector<int> cnt(326, 0); cnt[s[0]]++; int ans=1; while(1){ if(j==n-1) break; if(cnt[s[j+1]] == 0) j++, cnt[s[j]]++, ans=max(ans,j-i+1); else { cnt[s[i++]]--; } } cout << ans << endl; } return 0; } class Solution { public: int lengthOfLongestSubstring(string s) { vector<int> chars(128); int left = 0; int right = 0; int res = 0; while (right < s.length()) { char r = s[right]; chars[r]++; while (chars[r] > 1) { char l = s[left]; chars[l]--; left++; } res = max(res, right - left + 1); right++; } return res; } };
18.77193
70
0.365421
[ "vector" ]
db14c4de6eda0bc93f902aed2f4b5763e95956b7
17,323
cpp
C++
src/behavior_planner.cpp
Zhanghq8/Udacity_Path_planning
3ec261dda15641370d660142c4909a718611d2cc
[ "MIT" ]
null
null
null
src/behavior_planner.cpp
Zhanghq8/Udacity_Path_planning
3ec261dda15641370d660142c4909a718611d2cc
[ "MIT" ]
null
null
null
src/behavior_planner.cpp
Zhanghq8/Udacity_Path_planning
3ec261dda15641370d660142c4909a718611d2cc
[ "MIT" ]
null
null
null
#include "../include/behavior_planner.h" Behavior_planner::Behavior_planner() { gap = std::vector<std::vector<double>> (2, std::vector<double> (3, 0)); init_gap(); vel = std::vector<std::vector<double>> (2, std::vector<double> (3, 0)); diff_vel = std::vector<std::vector<double>> (2, std::vector<double> (3, 0)); cost = std::vector<double> (3, 0); is_safe_left = true; is_safe_right = true; next_lane = LaneType::NONE; // state = BehaviorType::LANECLEAR; } void Behavior_planner::init_gap() { for (int i=0; i<gap[0].size(); i++) { gap[FRONT][i] = MAXGAP; gap[BACK][i] = -MAXGAP; } } LaneType Behavior_planner::update_state(const Vehicle &myCar, const std::vector<Vehicle>& otherCars, double& reference_vel, BehaviorType &state) { get_gap(myCar, otherCars); get_cost(myCar); // update safe gap flag // std::cout << "*********************" << std::endl; // std::cout << "gap back left " << gap[BACK][LEFTLANE] << std::endl; // std::cout << "gap front left " << gap[FRONT][LEFTLANE] << std::endl; // std::cout << "gap back right " << gap[BACK][RIGHTLANE] << std::endl; // std::cout << "gap front right " << gap[FRONT][RIGHTLANE] << std::endl; // std::cout << "*********************" << std::endl; if (gap[BACK][LEFTLANE] > -SAFE_BACK_GAP || gap[FRONT][LEFTLANE] < SAFE_FRONT_GAP) {// || //fabs(gap[BACK][LEFTLANE]) <= fabs(diff_vel[BACK][LEFTLANE])) { is_safe_left = false; } else { is_safe_left = true; } if (gap[BACK][RIGHTLANE] > -SAFE_BACK_GAP || gap[FRONT][RIGHTLANE] < SAFE_FRONT_GAP) {// || // fabs(gap[BACK][RIGHTLANE]) <= fabs(diff_vel[BACK][RIGHTLANE])) { is_safe_right = false; } else { is_safe_right = true; } // std::cout << "*********************" << std::endl; // std::cout << "left safe? " << is_safe_left << std::endl; // std::cout << "right safe? " << is_safe_right << std::endl; // std::cout << "*********************" << std::endl; switch(state) { case(BehaviorType::LANECLEAR): //stay at mid lane: // std::cout << "state: LANECLEAR" << std::endl; reference_vel = MAX_VEL; if (gap[FRONT][CURRENTLANE] < ACTION_FRONT_DISTANCE) { state = BehaviorType::PREP_CHANGE_LANE; // std::cout << " after: PREP_CHANGE_LANE" << std::endl; } // else if (myCar.current_lane != LaneType::MID) { // state = BehaviorType::PREP_CHANGE_LANE; // } next_lane = myCar.current_lane; break; case(BehaviorType::PREP_CHANGE_LANE): // std::cout << "state: PREP_CHANGE_LANE" << std::endl; if (gap[FRONT][CURRENTLANE] < FOLLOW_DISTANCE) { state = BehaviorType::FOLLOW; // std::cout << "state: FOLLOW" << std::endl; next_lane = myCar.current_lane; reference_vel = follow_speed(); } else if (gap[FRONT][CURRENTLANE] < SAFE_FRONT_GAP) { // state = BehaviorType::LANECLEAR; // std::cout << "state: LANECLEAR" << std::endl; reference_vel = std::min<double>(MAX_VEL, MAX_VEL * gap[FRONT][CURRENTLANE] / SAFE_FRONT_GAP) ; next_lane = myCar.current_lane; // if (gap[LEFTLANE][FRONT] >= ACTION_FRONT_DISTANCE && myCar.current_lane == LaneType::RIGHT) { // next_lane = myCar.lane_at_left; // } // else if (gap[RIGHTLANE][FRONT] >= ACTION_FRONT_DISTANCE && myCar.current_lane == LaneType::LEFT) { // next_lane = myCar.lane_at_right; // } } else if (gap[FRONT][CURRENTLANE] > ACTION_FRONT_DISTANCE) { std::cout << "greater distance!!" << std::endl; reference_vel = MAX_VEL; state = BehaviorType::LANECLEAR; next_lane = myCar.current_lane; } // else if (gap[FRONT][CURRENTLANE] > SAFE_FRONT_GAP) { if (is_safe_left == true && cost[LEFTLANE] <= cost[RIGHTLANE] && cost[LEFTLANE] < cost[CURRENTLANE]) { state = BehaviorType::TURNLEFT; // std::cout << "state: TURNLEFT" << std::endl; next_lane = myCar.lane_at_left; // reference_vel = MAX_VEL; // LANE? } if (is_safe_right == true && cost[RIGHTLANE] <= cost[LEFTLANE] && cost[RIGHTLANE] < cost[CURRENTLANE]) { state = BehaviorType::TURNRIGHT; // std::cout << "state: TURNRIGHT" << std::endl; next_lane = myCar.lane_at_right; // reference_vel = MAX_VEL; // LANE? } break; case(BehaviorType::FOLLOW): // std::cout << "state: FOLLOW" << std::endl; if (gap[FRONT][CURRENTLANE] < FOLLOW_DISTANCE) { reference_vel = follow_speed(); next_lane = myCar.current_lane; } else { state = BehaviorType::LANECLEAR; next_lane = myCar.current_lane; reference_vel = MAX_VEL; } break; case(BehaviorType::TURNLEFT): // std::cout << "state: TURNLEFT" << std::endl; std::cout << " next_d: " << d_center(next_lane) << std::endl; if (myCar.d > d_center(next_lane) - 0.2 && myCar.d < d_center(next_lane) + 0.2) { state = BehaviorType::LANECLEAR; reference_vel = MAX_VEL; next_lane = myCar.current_lane; // reference_vel = follow_speed(); std::cout << " left turn finished" << std::endl; // std::cout << " BUG HERE!!!!!!!!!!!!!!" << std::endl; // std::cout << " BUG HERE!!!!!!!!!!!!!!" << std::endl; // std::cout << " BUG HERE!!!!!!!!!!!!!!" << std::endl; // std::cout << " BUG HERE!!!!!!!!!!!!!!" << std::endl; } else if (fabs(gap[FRONT][CURRENTLANE]) < FOLLOW_DISTANCE || fabs(gap[FRONT][LEFTLANE]) < FOLLOW_DISTANCE) { next_lane = myCar.current_lane; reference_vel = follow_speed(); // std::cout << " BUG HERE!!!!!!!!!!!!!!" << std::endl; // std::cout << " BUG HERE!!!!!!!!!!!!!!" << std::endl; // std::cout << " BUG HERE!!!!!!!!!!!!!!" << std::endl; } // else { // std::cout << " BUG HERE!!!!!!!!!!!!!!" << std::endl; // std::cout << " BUG HERE!!!!!!!!!!!!!!" << std::endl; // std::cout << " BUG HERE!!!!!!!!!!!!!!" << std::endl; // std::cout << " BUG HERE!!!!!!!!!!!!!!" << std::endl; // std::cout << " BUG HERE!!!!!!!!!!!!!!" << std::endl; // reference_vel = MAX_VEL; // next_lane = myCar.lane_at_left; // } break; case(BehaviorType::TURNRIGHT): // std::cout << "state: TURNRIGHT" << std::endl; std::cout << " next_d: " << d_center(next_lane) << std::endl; if (myCar.d > d_center(next_lane) - 0.2 && myCar.d < d_center(next_lane) + 0.2) { state = BehaviorType::LANECLEAR; reference_vel = MAX_VEL; std::cout << " right turn finished" << std::endl; // std::cout << " BUG HERE!!!!!!!!!!!!!!" << std::endl; // std::cout << " BUG HERE!!!!!!!!!!!!!!" << std::endl; // std::cout << " BUG HERE!!!!!!!!!!!!!!" << std::endl; next_lane = myCar.current_lane; // reference_vel = follow_speed(); } else if (fabs(gap[FRONT][CURRENTLANE]) < FOLLOW_DISTANCE || fabs(gap[FRONT][RIGHTLANE]) < FOLLOW_DISTANCE) { next_lane = myCar.current_lane; reference_vel = follow_speed(); // std::cout << " BUG HERE!!!!!!!!!!!!!!" << std::endl; // std::cout << " BUG HERE!!!!!!!!!!!!!!" << std::endl; // std::cout << " BUG HERE!!!!!!!!!!!!!!" << std::endl; // std::cout << " BUG HERE!!!!!!!!!!!!!!" << std::endl; } // else { // reference_vel = MAX_VEL; // next_lane = myCar.lane_at_right; // std::cout << " BUG HERE!!!!!!!!!!!!!!" << std::endl; // std::cout << " BUG HERE!!!!!!!!!!!!!!" << std::endl; // std::cout << " BUG HERE!!!!!!!!!!!!!!" << std::endl; // std::cout << " BUG HERE!!!!!!!!!!!!!!" << std::endl; // std::cout << " BUG HERE!!!!!!!!!!!!!!" << std::endl; // } break; default: state = BehaviorType::LANECLEAR; } std::cout << "is left lane safe?" << is_safe_left << std::endl; std::cout << "is right lane safe?" << is_safe_right << std::endl; return next_lane; } // update gap and vel vector // store the cloest gap(front and back) in each lane void Behavior_planner::get_gap(const Vehicle &myCar, const std::vector<Vehicle>& otherCars) { init_gap(); double min_front_gap_cur = MAXGAP; double min_back_gap_cur = MAXGAP; double min_front_gap_left = MAXGAP; double min_back_gap_left = MAXGAP; double min_front_gap_right = MAXGAP; double min_back_gap_right = MAXGAP; // int mid = 0; // int left = 0; // int right = 0; for (auto othercar : otherCars) { // mycar is at left lane if (myCar.current_lane == LaneType::LEFT) { gap[FRONT][LEFTLANE] = DANGERGAP; gap[BACK][LEFTLANE] = -DANGERGAP; vel[FRONT][LEFTLANE] = DANGERVELOCITY; vel[BACK][LEFTLANE] = DANGERVELOCITY; diff_vel[FRONT][LEFTLANE] = DANGERVELOCITY - myCar.v; diff_vel[BACK][LEFTLANE] = DANGERVELOCITY - myCar.v; // the other car is at the same left lane if (othercar.current_lane == LaneType::LEFT) { double diffs = othercar.s - myCar.s; if (diffs >= 0) { if (fabs(diffs) < min_front_gap_cur) { min_front_gap_cur = fabs(diffs); gap[FRONT][CURRENTLANE] = diffs; vel[FRONT][CURRENTLANE] = othercar.v; diff_vel[FRONT][CURRENTLANE] = othercar.v - myCar.v; } } else { if (fabs(diffs) < min_back_gap_cur) { min_back_gap_cur = fabs(diffs); gap[BACK][CURRENTLANE] = diffs; vel[BACK][CURRENTLANE] = othercar.v; diff_vel[BACK][CURRENTLANE] = othercar.v - myCar.v; } } } // the other car is at the mid lane on the right of my car else if (othercar.current_lane == LaneType::MID) { double diffs = othercar.s - myCar.s; if (diffs >= 0) { if (fabs(diffs) < min_front_gap_right) { min_front_gap_right = fabs(diffs); gap[FRONT][RIGHTLANE] = diffs; vel[FRONT][RIGHTLANE] = othercar.v; diff_vel[FRONT][RIGHTLANE] = othercar.v - myCar.v; } } else { if (fabs(diffs) < min_back_gap_right) { min_back_gap_right = fabs(diffs); gap[BACK][RIGHTLANE] = diffs; vel[BACK][RIGHTLANE] = othercar.v; diff_vel[BACK][RIGHTLANE] = othercar.v - myCar.v; } } } } // mycar is at right lane else if (myCar.current_lane == LaneType::RIGHT) { gap[FRONT][RIGHTLANE] = DANGERGAP; gap[BACK][RIGHTLANE] = -DANGERGAP; vel[FRONT][RIGHTLANE] = DANGERVELOCITY; vel[BACK][RIGHTLANE] = DANGERVELOCITY; diff_vel[FRONT][RIGHTLANE] = DANGERVELOCITY - myCar.v; diff_vel[BACK][RIGHTLANE] = DANGERVELOCITY - myCar.v; // the other car is at the same right lane if (othercar.current_lane == LaneType::RIGHT) { double diffs = othercar.s - myCar.s; if (diffs >= 0) { if (fabs(diffs) < min_front_gap_cur) { min_front_gap_cur = fabs(diffs); gap[FRONT][CURRENTLANE] = diffs; vel[FRONT][CURRENTLANE] = othercar.v; diff_vel[FRONT][CURRENTLANE] = othercar.v - myCar.v; } } else { if (fabs(diffs) < min_back_gap_cur) { min_back_gap_cur = fabs(diffs); gap[BACK][CURRENTLANE] = diffs; vel[BACK][CURRENTLANE] = othercar.v; diff_vel[BACK][CURRENTLANE] = othercar.v - myCar.v; } } } // the other car is at the mid lane on the left of my car else if (othercar.current_lane == LaneType::MID) { double diffs = othercar.s - myCar.s; if (diffs >= 0) { if (fabs(diffs) < min_front_gap_left) { min_front_gap_left = fabs(diffs); gap[FRONT][LEFTLANE] = diffs; vel[FRONT][LEFTLANE] = othercar.v; diff_vel[FRONT][LEFTLANE] = othercar.v - myCar.v; } } else { if (fabs(diffs) < min_back_gap_left) { min_back_gap_left = fabs(diffs); gap[BACK][LEFTLANE] = diffs; vel[BACK][LEFTLANE] = othercar.v; diff_vel[BACK][LEFTLANE] = othercar.v - myCar.v; } } } } // mycar is at mid lane else { if (othercar.current_lane == LaneType::LEFT) { // left++; double diffs = othercar.s - myCar.s; // std::cout << "othercar s: " << othercar.s << std::endl; // std::cout << "mycar s: " << myCar.s << std::endl; // std::cout << "othercar v: " << othercar.v << std::endl; if (diffs >= 0) { if (fabs(diffs) < min_front_gap_left) { min_front_gap_left = fabs(diffs); gap[FRONT][LEFTLANE] = diffs; vel[FRONT][LEFTLANE] = othercar.v; diff_vel[FRONT][LEFTLANE] = othercar.v - myCar.v; } } else { if (fabs(diffs) < min_back_gap_left) { min_back_gap_left = fabs(diffs); gap[BACK][LEFTLANE] = diffs; vel[BACK][LEFTLANE] = othercar.v; diff_vel[BACK][LEFTLANE] = othercar.v - myCar.v; } } } else if (othercar.current_lane == LaneType::MID) { // mid++; double diffs = othercar.s - myCar.s; // std::cout << "othercar s: " << othercar.s << std::endl; // std::cout << "mycar s: " << myCar.s << std::endl; // std::cout << "othercar v: " << othercar.v << std::endl; if (diffs >= 0) { if (fabs(diffs) < min_front_gap_cur) { min_front_gap_cur = fabs(diffs); gap[FRONT][CURRENTLANE] = diffs; vel[FRONT][CURRENTLANE] = othercar.v; diff_vel[FRONT][CURRENTLANE] = othercar.v - myCar.v; } } else { if (fabs(diffs) < min_back_gap_cur) { min_back_gap_cur = fabs(diffs); gap[BACK][CURRENTLANE] = diffs; vel[BACK][CURRENTLANE] = othercar.v; diff_vel[BACK][CURRENTLANE] = othercar.v - myCar.v; } } } else if (othercar.current_lane == LaneType::RIGHT) { // right++; double diffs = othercar.s - myCar.s; // if (diffs == 0) { // std::cout << "othercar s: " << othercar.s << std::endl; // std::cout << "mycar s: " << myCar.s << std::endl; // std::cout << "othercar v: " << othercar.v << std::endl; // } if (diffs >= 0) { if (fabs(diffs) < min_front_gap_right) { min_front_gap_right = fabs(diffs); gap[FRONT][RIGHTLANE] = diffs; vel[FRONT][RIGHTLANE] = othercar.v; diff_vel[FRONT][RIGHTLANE] = othercar.v - myCar.v; } } else { if (fabs(diffs) < min_back_gap_right) { min_back_gap_right = fabs(diffs); gap[BACK][RIGHTLANE] = diffs; vel[BACK][RIGHTLANE] = othercar.v; diff_vel[BACK][RIGHTLANE] = othercar.v - myCar.v; } } } } } // std::cout << "car in left: " << left << ". " << std::endl; // std::cout << "car in mid: " << mid << ". " << std::endl; // std::cout << "car in right: " << left << ". " << std::endl; std::cout << "*********************" << std::endl; std::cout << "gap fLEFT: " << gap[FRONT][LEFTLANE] << " gap fCUR: " << gap[FRONT][CURRENTLANE] << " gap fRIGHT: " << gap[FRONT][RIGHTLANE]<< std::endl; std::cout << "gap bLEFT: " << gap[BACK][LEFTLANE] << " gap bCUR: " << gap[BACK][CURRENTLANE] << " gap bRIGHT: " << gap[BACK][RIGHTLANE]<< std::endl; std::cout << "*********************" << std::endl; } double Behavior_planner::d_center(const LaneType &nextlane) { if (nextlane == LaneType::RIGHT) { return 9.5; } else if (nextlane == LaneType::LEFT) { return 2.0; } else if (nextlane == LaneType::MID) { return 6.0; } else { return MAXGAP; } } void Behavior_planner::get_cost(const Vehicle &myCar) { for (int i=0; i<cost.size(); i++) { cost[LEFTLANE] = cal_cost(myCar, diff_vel[FRONT][LEFTLANE], vel[FRONT][LEFTLANE], gap[FRONT][LEFTLANE]) + cal_cost(myCar, diff_vel[BACK][LEFTLANE], vel[BACK][LEFTLANE], gap[BACK][LEFTLANE]); cost[CURRENTLANE] = cal_cost(myCar, diff_vel[FRONT][CURRENTLANE], vel[FRONT][CURRENTLANE], gap[FRONT][CURRENTLANE]) + cal_cost(myCar, diff_vel[BACK][CURRENTLANE], vel[BACK][CURRENTLANE], gap[BACK][CURRENTLANE]); cost[RIGHTLANE] = cal_cost(myCar, diff_vel[FRONT][RIGHTLANE], vel[FRONT][RIGHTLANE], gap[FRONT][RIGHTLANE]) + cal_cost(myCar, diff_vel[BACK][RIGHTLANE], vel[BACK][RIGHTLANE], gap[BACK][RIGHTLANE]); } std::cout << "*********************" << std::endl; std::cout << "left cost: " << cost[LEFTLANE] << std::endl; std::cout << "current cost: " << cost[CURRENTLANE] << std::endl; std::cout << "right cost: " << cost[RIGHTLANE] << std::endl; std::cout << "*********************" << std::endl; } double Behavior_planner::cal_cost(const Vehicle &myCar, const double diff_velocity, const double velocity, const double gap_value) { double cost = 0; // cost += fabs(myCar.v - velocity) * RELATIVE_VEL_COST; // cost += fabs(MAX_VEL - velocity) * MAX_VEL_COST; if (gap_value == DANGERGAP) { cost += DANGERCOST; } else { cost += LOOKAHEAD_DISTANCE / fabs(gap_value) * DIS_COST; } // cost += fabs(((myCar.s+gap_value+velocity) - (myCar.s+myCar.v))/LOOKAHEAD_DISTANCE) * DIS_COST; return cost; } // TODO: optimize double Behavior_planner::follow_speed() { double follow_velocity = 0; if (vel[CURRENTLANE][FRONT] <= 0.3 && gap[CURRENTLANE][FRONT] < 5) { follow_velocity = 0; } // if (gap[CURRENTLANE][FRONT] < 10) { // follow_velocity = std::min<double>(vel[CURRENTLANE][FRONT], vel[CURRENTLANE][FRONT] * gap[CURRENTLANE][FRONT] / 10); // } else { follow_velocity = std::min<double>(vel[CURRENTLANE][FRONT], MAX_VEL); // follow_velocity = std::min<double>(follow_velocity, MAX_VEL); // std::cout << " BUG HERE!!!!!!!!!!!!!!" << std::endl; // std::cout << " BUG HERE!!!!!!!!!!!!!!" << std::endl; // std::cout << " BUG HERE!!!!!!!!!!!!!!" << std::endl; // std::cout << " vel: " << vel[CURRENTLANE][FRONT] << std::endl; // std::cout << " gap: " << gap[CURRENTLANE][FRONT] << std::endl; // std::cout << " gap vel: " << vel[CURRENTLANE][FRONT] * gap[CURRENTLANE][FRONT] / 10 << std::endl; // std::cout << " follow_velocity: " << follow_velocity << std::endl; } return follow_velocity; } Behavior_planner::~Behavior_planner() { }
36.164927
132
0.589043
[ "vector" ]
db1903ff5ef2005d4cf8ea61b3f7bf95749f0e82
12,394
cpp
C++
src/08_RecurrentNeuralNetworks/rnn_scratch.cpp
jiamny/D2L_pytorch_cpp
5bd89bb5531b9fca4fbe0dc3bfe5beaa7c45cb09
[ "MIT" ]
null
null
null
src/08_RecurrentNeuralNetworks/rnn_scratch.cpp
jiamny/D2L_pytorch_cpp
5bd89bb5531b9fca4fbe0dc3bfe5beaa7c45cb09
[ "MIT" ]
null
null
null
src/08_RecurrentNeuralNetworks/rnn_scratch.cpp
jiamny/D2L_pytorch_cpp
5bd89bb5531b9fca4fbe0dc3bfe5beaa7c45cb09
[ "MIT" ]
1
2022-03-11T00:12:20.000Z
2022-03-11T00:12:20.000Z
#include <torch/torch.h> #include <torch/script.h> #include <torch/autograd.h> #include <torch/utils.h> #include <iostream> #include <unistd.h> #include <iomanip> #include "../utils/ch_8_9_util.h" #include "../utils.h" #include "../matplotlibcpp.h" namespace plt = matplotlibcpp; torch::Tensor normal(int d1, int d2, torch::Device device) { return torch::randn({d1, d2}, device) * 0.01; } //=============================================== // Initializing the Model Parameters //=============================================== std::vector<torch::Tensor> get_params(int vocab_size, int num_hiddens, torch::Device device) { int num_inputs = vocab_size; int num_outputs = vocab_size; std::vector<torch::Tensor> params; // Hidden layer parameters torch::Tensor W_xh = normal(num_inputs, num_hiddens, device).requires_grad_(true); params.push_back(W_xh); torch::Tensor W_hh = normal(num_hiddens, num_hiddens, device).requires_grad_(true); params.push_back(W_hh); torch::Tensor b_h = torch::zeros(num_hiddens, device).requires_grad_(true); params.push_back(b_h); // Output layer parameters torch::Tensor W_hq = normal(num_hiddens, num_outputs, device).requires_grad_(true); params.push_back(W_hq); torch::Tensor b_q = torch::zeros(num_outputs, device).requires_grad_(true); params.push_back(b_q); return params; } //================================================== // RNN Model //================================================== /* * To define an RNN model, we first need [an init_rnn_state function to return the hidden state at initialization.] * It returns a tensor filled with 0 and with a shape of (batch size, number of hidden units). */ torch::Tensor init_rnn_state(int batch_size, int num_hiddens, torch::Device device) { return torch::zeros({batch_size, num_hiddens}, device); } // The following rnn function defines how to compute the hidden state and output at a time step std::tuple<torch::Tensor, torch::Tensor> rnn(torch::Tensor inputs, torch::Tensor& state, std::vector<torch::Tensor>& params) { // Here `inputs` shape: (`num_steps`, `batch_size`, `vocab_size`) /* torch::Tensor W_xh = params[0]; torch::Tensor W_hh = params[1]; torch::Tensor b_h = params[2]; torch::Tensor W_hq = params[3]; torch::Tensor b_q = params[4]; */ //auto H = state; std::vector<torch::Tensor> outputs; for(int i = 0; i < inputs.size(0); i++ ) { state = torch::tanh(torch::mm(inputs[i], params[0]) + torch::mm(state, params[1]) + params[2]); auto Y = torch::mm(state, params[3]) + params[4]; outputs.push_back(Y); } return std::make_tuple(torch::cat(outputs, 0), state); } struct RNNModelScratch { std::vector<torch::Tensor> params; int vocab_size, num_hiddens; //A RNN Model implemented from scratch. RNNModelScratch(int vocab_sz, int number_hiddens, torch::Device device ) { vocab_size = vocab_sz; num_hiddens = number_hiddens; params = get_params(vocab_size, num_hiddens, device); } std::tuple<torch::Tensor, torch::Tensor> forward(torch::Tensor X, torch::Tensor state) { X = torch::nn::functional::one_hot(X.transpose(0, 1), vocab_size).to(torch::kFloat32); return rnn(X, state, params); } torch::Tensor begin_state(int batch_size, torch::Device device) { return init_rnn_state(batch_size, num_hiddens, device); } }; //================================================ // Prediction //================================================ template<typename T> std::string predict_ch8(std::vector<std::string> prefix, int64_t num_preds, T net, Vocab vocab, torch::Device device) { //"""Generate new characters following the `prefix`.""" auto state = net.begin_state(1, device); std::vector<int64_t> outputs; outputs.push_back(vocab[prefix[0]]); //outputs = [vocab[prefix[0]]] //get_input = lambda: d2l.reshape(d2l.tensor([outputs[-1]], device=device), // (1, 1)) for( int i = 1; i < prefix.size(); i ++ ) { //# Warm-up period std::string y = prefix[i]; torch::Tensor xx; // get_inpt torch::Tensor X = torch::tensor({{outputs[i-1]}}, device).reshape({1,1}); std::tie(xx, state) = net.forward(X, state); outputs.push_back(vocab[prefix[i]]); } //for y in prefix[1:]: //# Warm-up period // _, state = net(get_input(), state) // outputs.append(vocab[y]) for( int i = 0; i < num_preds; i ++ ) { torch::Tensor y; int j = outputs.size(); torch::Tensor X = torch::tensor({{outputs[j-1]}}, device).reshape({1,1}); std::tie(y, state) = net.forward(X, state); outputs.push_back(static_cast<int>(y.argmax(1, 0).reshape({1}).item<int>())); } //for _ in range(num_preds): //# Predict `num_preds` steps // y, state = net(get_input(), state) // outputs.append(int(y.argmax(dim=1).reshape(1))) std::string pred(""); for( auto& p : outputs ) pred += vocab.idx_to_token[p]; return pred; // ''.join([vocab.idx_to_token[i] for i in outputs]); } template<typename T> std::pair<double, double> train_epoch_ch8(T& net, std::vector<std::pair<torch::Tensor, torch::Tensor>> train_iter, torch::nn::CrossEntropyLoss loss, torch::optim::Optimizer& updater, torch::Device device, float lr, bool use_random_iter) { //*********************************************** //two ways of setting the precision std::streamsize ss = std::cout.precision(); std::cout.precision(15); // another way std::setprecision(N) double ppx = 0.0; int64_t tot_tk = 0; precise_timer timer; torch::Tensor state = torch::empty({0});; for( int i = 0; i < train_iter.size(); i++ ) { auto X = train_iter[i].first; auto Y = train_iter[i].second; if( state.numel() == 0 || use_random_iter ) { state = net.begin_state(X.size(0), device); } else { state.detach_(); } torch::Tensor y = Y.transpose(0, 1).reshape({-1}); X.to(device), y.to(device); torch::Tensor y_hat; std::tie(y_hat, state) = net.forward(X, state); auto l = loss(y_hat, y.to(torch::kLong)).mean(); updater.zero_grad(); l.backward(); //"""Clip the gradient.""" torch::nn::utils::clip_grad_norm_(net.params, 0.5); updater.step(); ppx += (l.data().item<float>() * y.numel()); tot_tk += y.numel(); } unsigned int dul = timer.stop<unsigned int, std::chrono::microseconds>(); auto t = (dul/1000000.0); //**************************************** //change back the precision std::cout.precision(ss); // another way std::setprecision(ss) return { std::exp(ppx*1.0 / tot_tk), (tot_tk * 1.0 / t) }; } template<typename T> std::pair<std::vector<double>, std::vector<double>> train_ch8(T& net, std::vector<std::pair<torch::Tensor, torch::Tensor>> train_iter, Vocab vocab, torch::Device device, float lr, int64_t num_epochs, bool use_random_iter) { std::string s = "time traveller", s2 = "traveller"; std::vector<char> v(s.begin(), s.end()), v2(s2.begin(), s2.end()); std::vector<std::string> prefix, prefix2; for(int i = 0; i < v.size(); i++ ) { std::string tc(1, v[i]); prefix.push_back(tc); } for(int i = 0; i < v2.size(); i++ ) { std::string tc(1, v[i]); prefix2.push_back(tc); } //"""Train a model (defined in Chapter 8).""" auto loss = torch::nn::CrossEntropyLoss(); torch::optim::SGD updater = torch::optim::SGD(net.params, lr); std::vector<double> epochs, ppl; // Train and predict double eppl, speed; for(int64_t epoch = 0; epoch < num_epochs; epoch++ ) { auto rlt = train_epoch_ch8(net, train_iter, loss, updater, device, lr, use_random_iter); eppl = rlt.first; speed = rlt.second; if( (epoch + 1) % 10 == 0 ) { std::cout << predict_ch8(prefix, 50, net, vocab, device) << std::endl; ppl.push_back(eppl); epochs.push_back((epoch+1)*1.0); } } printf("perplexity: %.1f, speed: %.1f tokens/sec on %s\n", eppl, speed, device.str().c_str()); std::cout << predict_ch8(prefix, 50, net, vocab, device) << std::endl; std::cout << predict_ch8(prefix2, 50, net, vocab, device) << std::endl; return {epochs, ppl}; } int main() { std::cout << "Current path is " << get_current_dir_name() << '\n'; // Device auto cuda_available = torch::cuda::is_available(); torch::Device device(cuda_available ? torch::kCUDA : torch::kCPU); std::cout << (cuda_available ? "CUDA available. Training on GPU." : "Training on CPU.") << '\n'; //========================================================================= // Implementation of Recurrent Neural Networks from Scratch //========================================================================= int64_t max_tokens = 10000; int64_t batch_size = 32, num_steps = 35; std::vector<std::string> lines = read_time_machine("./data/timemachine.txt"); //------------------------------------------------------------- // split words and extract first token upto max_tokens //------------------------------------------------------------- std::vector<std::string> ttokens = tokenize(lines, "char", true); std::vector<std::string> tokens(&ttokens[0], &ttokens[max_tokens]); // first 10000 tokens std::vector<std::pair<std::string, int64_t>> counter = count_corpus( tokens ); std::vector<std::string> rv(0); auto vocab = Vocab(counter, 0.0, rv); std::cout << vocab["t"] << "\n"; //===================================================== // One-Hot Encoding //===================================================== std::cout << torch::nn::functional::one_hot(torch::tensor({0, 2}), vocab.length()) << std::endl; // (The shape of the minibatch) that we sample each time (is (batch size, number of time steps). // The one_hot function transforms such a minibatch into a three-dimensional tensor with the last dimension // equals to the vocabulary size (len(vocab)).) auto X = torch::arange(10).reshape({2, 5}); std::cout << torch::nn::functional::one_hot(X.transpose(0, 1), vocab.length()).sizes() << std::endl; std::cout << X.transpose(0, 1) << std::endl; auto Y = torch::nn::functional::one_hot(X.transpose(0, 1), vocab.length()); std::vector<torch::Tensor> outputs; for(int i = 0; i < Y.size(0); i++ ) { //std::cout << Y[i] << std::endl; outputs.push_back(Y[i]); } std::cout << torch::cat(outputs, 0).sizes() << std::endl; torch::Tensor a = normal(10, 20, device); std::cout << a.sizes() << std::endl; //============================================================= // Let us [check whether the outputs have the correct shapes] int num_hiddens = 512; auto net = RNNModelScratch(vocab.length(), num_hiddens, device); torch::Tensor state = net.begin_state(X.size(0), device); std::tuple<torch::Tensor, torch::Tensor> rlt = net.forward(X.to(device), state); auto Z = std::get<0>(rlt); auto new_state = std::get<1>(rlt); std::cout << "Z: " << Z.sizes() << std::endl; //std::cout << Z << std::endl; std::cout << "new_state: " << new_state.sizes() << std::endl; //std::cout << new_state << std::endl; //================================================ // Prediction //================================================ // Let us [first define the prediction function to generate new characters following the user-provided prefix] std::string s = "time traveller "; std::vector<char> v(s.begin(), s.end()); std::vector<std::string> prefix; for(int i = 0; i < v.size(); i++ ) { std::string tc(1, v[i]); prefix.push_back(tc); } std::string prd = predict_ch8(prefix, 10, net, vocab, device); std::cout << prd << std::endl; std::vector<int> tokens_ids; for( size_t i = 0; i < tokens.size(); i++ ) tokens_ids.push_back(vocab[tokens[i]]); // Training and Predicting std::vector<std::pair<torch::Tensor, torch::Tensor>> train_iter = seq_data_iter_random(tokens_ids, batch_size, num_steps); int64_t num_epochs = 300; float lr = 1.0; bool use_random_iter = false; auto nett = RNNModelScratch(vocab.length(), num_hiddens, device); std::pair<std::vector<double>, std::vector<double>> trlt = train_ch8(nett, train_iter, vocab, device, lr, num_epochs, use_random_iter); plt::figure_size(800, 600); plt::named_plot("train", trlt.first, trlt.second, "b"); plt::xlabel("epoch"); plt::ylabel("perplexity"); plt::legend(); plt::show(); std::cout << "Done!\n"; return 0; }
35.011299
136
0.597467
[ "shape", "vector", "model" ]
db1bc99e006611f7ba05cd0f4b8529dfaac0124e
1,394
cpp
C++
ExtraFiles/NZArchive_AddDLL/NZArchive_AddDLL/Global.cpp
alwendya/NZArchive
57a3ce6104598d33001d2dab8677ccf49c740950
[ "MIT" ]
1
2022-02-27T14:48:34.000Z
2022-02-27T14:48:34.000Z
ExtraFiles/NZArchive_AddDLL/NZArchive_AddDLL/Global.cpp
alwendya/NZArchive
57a3ce6104598d33001d2dab8677ccf49c740950
[ "MIT" ]
null
null
null
ExtraFiles/NZArchive_AddDLL/NZArchive_AddDLL/Global.cpp
alwendya/NZArchive
57a3ce6104598d33001d2dab8677ccf49c740950
[ "MIT" ]
null
null
null
#include "Global.h" #include "OverlayIconExt.h" #include "MenuExt.h" // {C0552A55-A874-4ACC-9C64-F43A86D73F4E} const CLSID CLSID_MenuExt = { 0xc0552a55, 0xa874, 0x4acc, { 0x9c, 0x64, 0xf4, 0x3a, 0x86, 0xd7, 0x3f, 0x4e } }; // {E4FCBC8E-C70D-4B28-AF68-B98C99015730} const CLSID CLSID_OverlayIconExt = { 0xe4fcbc8e, 0xc70d, 0x4b28, { 0xaf, 0x68, 0xb9, 0x8c, 0x99, 0x1, 0x57, 0x30 } }; Global::Global(): m_hInst(nullptr), m_cDllRef(0) { InitializeExtensionsData(); m_shellIdList = RegisterClipboardFormat(CFSTR_SHELLIDLIST); } Global::~Global() { } void Global::InitializeExtensionsData() { m_FactoryData.push_back( FactoryInfo(CLSID_OverlayIconExt, &nsADDTO::OverlayIconExt::ComponentCreator, L"NZAEXTRHTOVERLAY" ) ); m_FactoryData.push_back( FactoryInfo(CLSID_MenuExt, &nsADDTO::MenuExt::ComponentCreator, L"NZAEXTRTOMENU" ) ); } long Global::DllRef() const { return m_cDllRef; } void Global::DllInst(HINSTANCE val) { m_hInst = val; } HINSTANCE Global::DllInst() const { return m_hInst; } int Global::ShellIdList() const { return m_shellIdList; } std::vector<FactoryInfo>& Global::FactoryData() { return m_FactoryData; } void Global::IncrementDllRef() { InterlockedIncrement(&m_cDllRef); } void Global::DecrementDllRef() { InterlockedDecrement(&m_cDllRef); }
18.103896
83
0.684362
[ "vector" ]
db1bf7c3d8df6f5c9f78ab5cb61c6891b6cb7545
8,916
cpp
C++
isis/src/control/objs/BundleUtilities/BundleObservationVector.cpp
ihumphrey-usgs/ISIS3_old
284cc442b773f8369d44379ee29a9b46961d8108
[ "Unlicense" ]
1
2019-10-13T15:31:33.000Z
2019-10-13T15:31:33.000Z
isis/src/control/objs/BundleUtilities/BundleObservationVector.cpp
ihumphrey-usgs/ISIS3_old
284cc442b773f8369d44379ee29a9b46961d8108
[ "Unlicense" ]
null
null
null
isis/src/control/objs/BundleUtilities/BundleObservationVector.cpp
ihumphrey-usgs/ISIS3_old
284cc442b773f8369d44379ee29a9b46961d8108
[ "Unlicense" ]
1
2021-07-12T06:05:03.000Z
2021-07-12T06:05:03.000Z
#include "BundleObservationVector.h" #include <QDebug> #include "BundleObservation.h" #include "IException.h" namespace Isis { /** * Constructs an empty BundleObservationVector. */ BundleObservationVector::BundleObservationVector() { } /** * Copy constructor. * * Constructs a BundleObservationVector as a copy of another BundleObservationVector. * * @param src A reference to the BundleObservationVector to copy from. */ BundleObservationVector::BundleObservationVector(const BundleObservationVector &src) :QVector<BundleObservationQsp>(src) { m_observationNumberToObservationMap = src.m_observationNumberToObservationMap; m_imageSerialToObservationMap = src.m_imageSerialToObservationMap; } /** * Destructor. * * Contained BundleObservations will remain until all shared pointers to them are deleted. */ BundleObservationVector::~BundleObservationVector() { clear(); } /** * Assignment operator. * * Assigns the state of the source BundleObservationVector to this BundleObservationVector. * * @param src The BundleObservationVector to assign from. * * @return @b BundleObservationVector& A reference to this BundleObservationVector. */ BundleObservationVector &BundleObservationVector::operator=(const BundleObservationVector &src) { if (&src != this) { QVector<BundleObservationQsp>::operator=(src); m_observationNumberToObservationMap = src.m_observationNumberToObservationMap; m_imageSerialToObservationMap = src.m_imageSerialToObservationMap; } return *this; } /** * Adds a new BundleObservation to this vector or fetches an existing BundleObservation if this * vector already contains the passed observation number. * * If observation mode is off, adds a new BundleObservation to this vector. Otherwise, if * observation mode is on and the BundleObservation has already been added with the same * observation number, the passed BundleImage is added to the existing BundleObservation. * * @param bundleImage QSharedPointer to the BundleImage to create or fetch a BundleObservation * from * @param observationNumber Observation number of the observation to add or fetch * @param instrumentId Instrument id of the observation * @param bundleSettings Qsp to BundleSettings for the observation * * @throws IException::Programmer "Unable to allocate new BundleObservation" * * @return @b BundleObservationQsp Returns a pointer to the BundleObservation that was added * * @internal * @history 2016-10-13 Ian Humphrey - When appending a new BundleObservation and there are * multiple BundleObservationSolveSettings, we set the settings * according to the observation number passed. References #4293. */ BundleObservationQsp BundleObservationVector::addNew(BundleImageQsp bundleImage, QString observationNumber, QString instrumentId, BundleSettingsQsp bundleSettings) { BundleObservationQsp bundleObservation; bool addToExisting = false; if (bundleSettings->solveObservationMode() && m_observationNumberToObservationMap.contains(observationNumber)) { bundleObservation = m_observationNumberToObservationMap.value(observationNumber); addToExisting = true; } if (addToExisting) { // if we have already added a BundleObservation with this number, we have to add the new // BundleImage to this observation bundleObservation->append(bundleImage); bundleImage->setParentObservation(bundleObservation); // update observation number to observation ptr map m_observationNumberToObservationMap.insertMulti(observationNumber,bundleObservation); // update image serial number to observation ptr map m_imageSerialToObservationMap.insertMulti(bundleImage->serialNumber(),bundleObservation); } else { // create new BundleObservation and append to this vector bundleObservation = BundleObservationQsp(new BundleObservation(bundleImage, observationNumber, instrumentId, bundleSettings->bundleTargetBody())); if (!bundleObservation) { QString message = "Unable to allocate new BundleObservation "; message += "for " + bundleImage->fileName(); throw IException(IException::Programmer, message, _FILEINFO_); } bundleImage->setParentObservation(bundleObservation); // Find the bundle observation solve settings for this new observation BundleObservationSolveSettings solveSettings; // When there is only one bundle observation solve setting, use it for all observations if ( bundleSettings->numberSolveSettings() == 1) { solveSettings = bundleSettings->observationSolveSettings(0); } // Otherwise, we want to grab the bundle observation solve settings that is associated with // the observation number for this new observation else { solveSettings = bundleSettings->observationSolveSettings(observationNumber); } bundleObservation->setSolveSettings(solveSettings); bundleObservation->setIndex(size()); append(bundleObservation); // update observation number to observation ptr map m_observationNumberToObservationMap.insertMulti(observationNumber, bundleObservation); // update image serial number to observation ptr map m_imageSerialToObservationMap.insertMulti(bundleImage->serialNumber(), bundleObservation); } return bundleObservation; } /** * Accesses the number of position parameters for the contained BundleObservations. * * @return @b int Returns the total number of position parameters for the BundleObservations */ int BundleObservationVector::numberPositionParameters() { int positionParameters = 0; for (int i = 0; i < size(); i++) { BundleObservationQsp observation = at(i); positionParameters += observation->numberPositionParameters(); } return positionParameters; } /** * Accesses the number of pointing parameters for the contained BundleObservations. * * @return @b int Returns the total number of pointing parameters for the BundleObservations */ int BundleObservationVector::numberPointingParameters() { int pointingParameters = 0; for (int i = 0; i < size(); i++) { BundleObservationQsp observation = at(i); pointingParameters += observation->numberPointingParameters(); } return pointingParameters; } /** * Returns the sum of the position parameters and pointing parameters for the contained * BundleObservations. * * @return @b int Returns the total number of parameters for the contained BundleObservations */ int BundleObservationVector::numberParameters() { return numberPositionParameters() + numberPointingParameters(); } /** * Accesses a BundleObservation associated with the passed serial number. * * If there is no BundleObservation associated with the serial number, a NULL * pointer is returned. * * @param cubeSerialNumber Serial number of a cube to try to find an associated BundleObservation * * @return @b BundleObservationQsp Pointer to the associated BundleObservation (NULL if not found) */ BundleObservationQsp BundleObservationVector:: observationByCubeSerialNumber(QString cubeSerialNumber) { BundleObservationQsp bundleObservation; if (m_imageSerialToObservationMap.contains(cubeSerialNumber)) bundleObservation = m_imageSerialToObservationMap.value(cubeSerialNumber); return bundleObservation; } /** * Initializes the exterior orientations for the contained BundleObservations. * * @return @b bool Returns true upon successful initialization */ bool BundleObservationVector::initializeExteriorOrientation() { int nObservations = size(); for (int i = 0; i < nObservations; i++) { BundleObservationQsp observation = at(i); observation->initializeExteriorOrientation(); } return true; } /** * Initializes the body rotations for the contained BundleObservations. * * @return @b bool Returns true upon successful initialization */ bool BundleObservationVector::initializeBodyRotation() { int nObservations = size(); for (int i = 0; i < nObservations; i++) { BundleObservationQsp observation = at(i); observation->initializeBodyRotation(); } return true; } }
35.241107
100
0.698632
[ "vector" ]
db1fcf1157d3ca71f20146d60d52b158a46a2353
2,782
cpp
C++
src/test/test_required_tile_selector.cpp
Muratam/mahjong-cpp
28a76a8e25a0084cb582e5c1e64c16f479da268f
[ "MIT" ]
null
null
null
src/test/test_required_tile_selector.cpp
Muratam/mahjong-cpp
28a76a8e25a0084cb582e5c1e64c16f479da268f
[ "MIT" ]
null
null
null
src/test/test_required_tile_selector.cpp
Muratam/mahjong-cpp
28a76a8e25a0084cb582e5c1e64c16f479da268f
[ "MIT" ]
null
null
null
#include <fstream> #include <iostream> #include <boost/algorithm/string/classification.hpp> #include <boost/algorithm/string/split.hpp> #include <boost/dll.hpp> #define CATCH_CONFIG_MAIN #define CATCH_CONFIG_ENABLE_BENCHMARKING #include <catch2/catch.hpp> #include "mahjong/mahjong.hpp" using namespace mahjong; /** * @brief テストケースを読み込む。 * * @param[out] cases テストケース * @return 読み込みに成功した場合は true、そうでない場合は false を返す。 */ bool load_testcase(std::vector<Hand> &cases) { cases.clear(); boost::filesystem::path path = boost::dll::program_location().parent_path() / "test_unnecessary_tile_selector.txt"; // ファイルを開く。 std::ifstream ifs(path.string()); if (!ifs) { std::cerr << "Failed to open " << path.string() << "." << std::endl; return false; } // ファイルを読み込む。 // 形式は `<牌1> <牌2> ... <牌14>` std::string line; while (std::getline(ifs, line)) { std::vector<std::string> tokens; boost::split(tokens, line, boost::is_any_of(" ")); std::vector<int> tiles(14); for (int i = 0; i < 14; ++i) tiles[i] = std::stoi(tokens[i]); cases.emplace_back(tiles); } return true; } // TEST_CASE("検証用") // { // std::vector<Hand> cases; // if (!load_testcase(cases)) // return; // std::vector<std::vector<int>> rets1; // for (const auto &hand : cases) { // auto ret = RequiredTileSelector::select_kokusi(hand); // rets1.push_back(ret); // } // std::vector<std::vector<int>> rets2; // for (const auto &hand : cases) { // auto ret = RequiredTileSelector::select_kokusi2(hand); // rets2.push_back(ret); // } // for (size_t i = 0; i < cases.size(); ++i) { // INFO(fmt::format("手牌: {}", cases[i].to_string())); // REQUIRE(rets1[i].size() == rets2[i].size()); // for (size_t j = 0; j < rets1[i].size(); ++j) // REQUIRE(rets1[i][j] == rets2[i][j]); // } // } TEST_CASE("一般手の有効牌を選択する") { std::vector<Hand> cases; if (!load_testcase(cases)) return; BENCHMARK("一般手の有効牌を選択する") { for (const auto &hand : cases) { RequiredTileSelector::select_normal(hand); } }; } TEST_CASE("七対子手の有効牌を選択する") { std::vector<Hand> cases; if (!load_testcase(cases)) return; BENCHMARK("七対子手の有効牌を選択する") { for (const auto &hand : cases) { RequiredTileSelector::select_tiitoi(hand); } }; } TEST_CASE("国士手の有効牌を選択する") { std::vector<Hand> cases; if (!load_testcase(cases)) return; BENCHMARK("国士手の有効牌を選択する") { for (const auto &hand : cases) { RequiredTileSelector::select_kokusi(hand); } }; }
22.803279
81
0.564342
[ "vector" ]
db219deb6ea2a6e20dd91756251032ed619052ba
16,195
cpp
C++
src/test/cpp/Balau/Util/StringsTest.cpp
borasoftware/balau
8bb82e9cbf7aa8193880eda1de5cbca4db1e1c14
[ "Apache-2.0" ]
6
2018-12-30T15:09:26.000Z
2020-04-20T09:27:59.000Z
src/test/cpp/Balau/Util/StringsTest.cpp
borasoftware/balau
8bb82e9cbf7aa8193880eda1de5cbca4db1e1c14
[ "Apache-2.0" ]
null
null
null
src/test/cpp/Balau/Util/StringsTest.cpp
borasoftware/balau
8bb82e9cbf7aa8193880eda1de5cbca4db1e1c14
[ "Apache-2.0" ]
2
2019-11-12T08:07:16.000Z
2019-11-29T11:19:47.000Z
// @formatter:off // // Balau core C++ library // // Copyright (C) 2008 Bora Software (contact@borasoftware.com) // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #include <TestResources.hpp> #include <Balau/Util/Random.hpp> namespace Balau { using Testing::is; namespace Util { struct StringsTest : public Testing::TestGroup<StringsTest> { StringsTest() { RegisterTestCase(toUpper_string); RegisterTestCase(toUpper_u32string); RegisterTestCase(toLower_string); RegisterTestCase(toLower_u32string); RegisterTestCase(equalsIgnoreCase_string_string); RegisterTestCase(equalsIgnoreCase_u32string_u32string); RegisterTestCase(startsWith_string_string); RegisterTestCase(startsWith_string_char); RegisterTestCase(startsWith_u32string_u32string); RegisterTestCase(startsWith_u32string_char32_t); RegisterTestCase(endsWith_string_string); RegisterTestCase(endsWith_string_char); RegisterTestCase(endsWith_u32string_u32string); RegisterTestCase(endsWith_u32string_char32_t); RegisterTestCase(contains_string_string); RegisterTestCase(contains_string_char); RegisterTestCase(contains_u16string_u16string); RegisterTestCase(contains_u16string_char16_t); RegisterTestCase(contains_u32string_u32string); RegisterTestCase(contains_u32string_char32_t); RegisterTestCase(occurrences_string_string); RegisterTestCase(occurrences_u32string_u32string); RegisterTestCase(occurrences_string_regex); RegisterTestCase(lineLengths); RegisterTestCase(lastIndexOf_string_string); RegisterTestCase(lastIndexOf_u32string_u32string); RegisterTestCase(codePointCount_string); RegisterTestCase(codePointCount_u32string); RegisterTestCase(append_string_char); RegisterTestCase(append_string_char32_t); RegisterTestCase(append_u32string_char32_t); RegisterTestCase(padLeft_string_char); RegisterTestCase(padLeft_string_char32_t); RegisterTestCase(padLeft_u32string_char32_t); RegisterTestCase(padRight_string_char); RegisterTestCase(padRight_string_char32_t); RegisterTestCase(padRight_u32string_char32_t); RegisterTestCase(trim_string); RegisterTestCase(trim_u32string); RegisterTestCase(trimLeft_string); RegisterTestCase(trimLeft_u32string); RegisterTestCase(trimRight_string); RegisterTestCase(trimRight_u32string); RegisterTestCase(replaceAll_string_string); RegisterTestCase(replaceAll_u32string_u32string); RegisterTestCase(join_string); RegisterTestCase(join_u32string); RegisterTestCase(split_string_string); RegisterTestCase(split_u32string_u32string); RegisterTestCase(split_string_regex); RegisterTestCase(replaceAll_string_regex); } void toUpper_string() { AssertThat(Strings::toUpper("weifuhaw"), is(std::string("WEIFUHAW"))); } void toUpper_u32string() { AssertThat(Strings::toUpper(U"weifuhaw"), is(std::u32string(U"WEIFUHAW"))); } void toLower_string() { AssertThat(Strings::toLower("WEIFUHAW"), is(std::string("weifuhaw"))); } void toLower_u32string() { AssertThat(Strings::toLower(U"WEIFUHAW"), is(std::u32string(U"weifuhaw"))); } void equalsIgnoreCase_string_string() { AssertThat(Strings::equalsIgnoreCase("WEIFUHAW", std::string("weifuhaw")), is(true)); AssertThat(Strings::equalsIgnoreCase("WeIfUHaW", std::string("weifuhaw")), is(true)); AssertThat(Strings::equalsIgnoreCase("EeIfUHaW", std::string("weifuhaw")), is(false)); } void equalsIgnoreCase_u32string_u32string() { AssertThat(Strings::equalsIgnoreCase(U"WEIFUHAW", std::u32string(U"weifuhaw")), is(true)); AssertThat(Strings::equalsIgnoreCase(U"WeIfUHaW", std::u32string(U"weifuhaw")), is(true)); AssertThat(Strings::equalsIgnoreCase(U"EeIfUHaW", std::u32string(U"weifuhaw")), is(false)); } void startsWith_string_string() { AssertThat(Strings::startsWith("qwertyuiop", "qwer"), is(true)); AssertThat(Strings::startsWith("qwertyuiop", "qwertiu"), is(false)); } void startsWith_string_char() { AssertThat(Strings::startsWith("qwertyuiop", 'q'), is(true)); AssertThat(Strings::startsWith("wertyuiop", 'q'), is(false)); } void startsWith_u32string_u32string() { AssertThat(Strings::startsWith(U"qwertyuiop", U"qwer"), is(true)); AssertThat(Strings::startsWith(U"qwertyuiop", U"qwertiu"), is(false)); } void startsWith_u32string_char32_t() { AssertThat(Strings::startsWith(U"qwertyuiop", U'q'), is(true)); AssertThat(Strings::startsWith(U"wertyuiop", U'q'), is(false)); } void endsWith_string_string() { AssertThat(Strings::endsWith("qwertyuiop", "uiop"), is(true)); AssertThat(Strings::endsWith("qwertyuiop", "uipp"), is(false)); } void endsWith_string_char() { AssertThat(Strings::endsWith("qwertyuiop", 'p'), is(true)); AssertThat(Strings::endsWith("qwertyuio", 'p'), is(false)); } void endsWith_u32string_u32string() { AssertThat(Strings::endsWith(U"qwertyuiop", U"uiop"), is(true)); AssertThat(Strings::endsWith(U"qwertyuiop", U"uipp"), is(false)); } void endsWith_u32string_char32_t() { AssertThat(Strings::endsWith(U"qwertyuiop", U'p'), is(true)); AssertThat(Strings::endsWith(U"qwertyuio", U'p'), is(false)); } void contains_string_string() { AssertThat(Strings::contains("qwertyuiop", "tyu"), is(true)); AssertThat(Strings::contains("qwertyuiop", "ttyu"), is(false)); } void contains_string_char() { AssertThat(Strings::contains("qwertyuiop", 't'), is(true)); AssertThat(Strings::contains("qwertyuiop", 'z'), is(false)); } void contains_u16string_u16string() { AssertThat(Strings::contains(u"qwertyuiop", u"tyu"), is(true)); AssertThat(Strings::contains(u"qwertyuiop", u"ttyu"), is(false)); } void contains_u16string_char16_t() { AssertThat(Strings::contains(u"qwertyuiop", u't'), is(true)); AssertThat(Strings::contains(u"qwertyuiop", u'z'), is(false)); } void contains_u32string_u32string() { AssertThat(Strings::contains(U"qwertyuiop", U"tyu"), is(true)); AssertThat(Strings::contains(U"qwertyuiop", U"ttyu"), is(false)); } void contains_u32string_char32_t() { AssertThat(Strings::contains(U"qwertyuiop", U't'), is(true)); AssertThat(Strings::contains(U"qwertyuiop", U'z'), is(false)); } void occurrences_string_string() { AssertThat(Strings::occurrences(std::string(""), std::string(".")), is(0U)); AssertThat(Strings::occurrences(std::string("..."), std::string(".")), is(3U)); AssertThat(Strings::occurrences(std::string("abfcjijffaaaiuygdafaagaajaaaaka"), std::string("aa")), is(5U)); } void occurrences_u32string_u32string() { AssertThat(Strings::occurrences(std::u32string(U""), std::u32string(U".")), is(0U)); AssertThat(Strings::occurrences(std::u32string(U"..."), std::u32string(U".")), is(3U)); AssertThat(Strings::occurrences(std::u32string(U"abfcjijffaaaiuygdafaagaajaaaaka"), std::u32string(U"aa")), is(5U)); } void occurrences_string_regex() { AssertThat(Strings::occurrences("", std::regex("\\.")), is(0U)); AssertThat(Strings::occurrences("...", std::regex("\\.")), is(3U)); AssertThat(Strings::occurrences("abfcjijffaaaiuygdafaagaajaaaaka", std::regex("aa")), is(5U)); AssertThat(Strings::occurrences("abfcjijffaaaiuygdafaagaajaaaaka", std::regex("aa|f")), is(9U)); AssertThat(Strings::occurrences("abf\ncj\n\rijf\r\n\nfa\r\r\raaiu\n\r\n\raa", std::regex("\n\r|\r\n|\n|\r")), is(9U)); AssertThat(Strings::occurrences("abf\n", std::regex("\n\r|\r\n|\n|\r")), is(1U)); } void lineLengths() { AssertThat(Strings::lineLengths("qwerty"), is(std::vector<size_t> { 6U })); AssertThat(Strings::lineLengths("qwerty\npoiu"), is(std::vector<size_t> { 6U, 4U })); AssertThat(Strings::lineLengths("qwerty\npoiu\r\n"), is(std::vector<size_t> { 6U, 4U })); AssertThat(Strings::lineLengths("qwerty\npoiu\r\ncvb"), is(std::vector<size_t> { 6U, 4U, 3U })); AssertThat(Strings::lineLengths("qwerty\npoiu\r\ncvb", false), is(std::vector<size_t> { 6U, 4U })); AssertThat(Strings::lineLengths("qwerty\npoiu\r\ncvb\r"), is(std::vector<size_t> { 6U, 4U, 3U })); } void lastIndexOf_string_string() { AssertThat(Strings::lastIndexOf("qabcweabcrtabcypoiabcucvb", "abc"), is(18U)); } void lastIndexOf_u32string_u32string() { AssertThat(Strings::lastIndexOf(U"qabcweabcrtabcypoiabcucvb", U"abc"), is(18U)); } void codePointCount_string() { AssertThat(Strings::codePointCount("qabcweabcrtabcypoiabcucvb"), is(25U)); } void codePointCount_u32string() { AssertThat(Strings::codePointCount(U"qabcweabcrtabcypoiabcucvb"), is(25U)); } void append_string_char() { std::string expected("abccc"); std::string actual("ab"); Strings::append(actual, 'c', 3); AssertThat(actual, is(expected)); } void append_string_char32_t() { std::string expected("abccc"); std::string actual("ab"); Strings::append(actual, U'c', 3); AssertThat(actual, is(expected)); } void append_u32string_char32_t() { std::u32string expected(U"abccc"); std::u32string actual(U"ab"); Strings::append(actual, U'c', 3); AssertThat(actual, is(expected)); } void padLeft_string_char() { AssertThat(Strings::padLeft("qwerty", 10), is(" qwerty")); AssertThat(Strings::padLeft("qwerty", 10, 'X'), is("XXXXqwerty")); } void padLeft_string_char32_t() { AssertThat(Strings::padLeft("qwerty", 10, U'λ'), is(u8"λλλλqwerty")); } void padLeft_u32string_char32_t() { AssertThat(Strings::padLeft(U"qwerty", 10), is(U" qwerty")); AssertThat(Strings::padLeft(U"qwerty", 10, U'λ'), is(U"λλλλqwerty")); } void padRight_string_char() { AssertThat(Strings::padRight("qwerty", 10), is("qwerty ")); AssertThat(Strings::padRight("qwerty", 10, 'X'), is("qwertyXXXX")); } void padRight_string_char32_t() { AssertThat(Strings::padRight("qwerty", 10, U'λ'), is(u8"qwertyλλλλ")); } void padRight_u32string_char32_t() { AssertThat(Strings::padRight(U"qwerty", 10), is(U"qwerty ")); AssertThat(Strings::padRight(U"qwerty", 10, U'λ'), is(U"qwertyλλλλ")); } void trim_string() { AssertThat(Strings::trim(" qwerty "), is(std::string("qwerty"))); } void trim_u32string() { AssertThat(Strings::trim(U" qwerty "), is(std::u32string(U"qwerty"))); } void trimLeft_string() { AssertThat(Strings::trimLeft(" qwerty "), is(std::string("qwerty "))); } void trimLeft_u32string() { AssertThat(Strings::trimLeft(U" qwerty "), is(std::u32string(U"qwerty "))); } void trimRight_string() { AssertThat(Strings::trimRight(" qwerty "), is(std::string(" qwerty"))); } void trimRight_u32string() { AssertThat(Strings::trimRight(U" qwerty "), is(std::u32string(U" qwerty"))); } void replaceAll_string_string() { AssertThat(Strings::replaceAll("ABCDEFCDEFGGDEDEFGTH", "DEF", "ZZ"), is(std::string("ABCZZCZZGGDEZZGTH"))); } void replaceAll_u32string_u32string() { AssertThat(Strings::replaceAll(U"ABCDEFCDEFGGDEDEFGTH", U"DEF", U"ZZ"), is(std::u32string(U"ABCZZCZZGGDEZZGTH"))); } void replaceAll_string_regex() { AssertThat(Strings::replaceAll("ABCDEFCDEFFGGDEDEFGTH", std::regex("DEFF?"), "ZZ"), is(std::string("ABCZZCZZGGDEZZGTH"))); AssertThat(Strings::replaceAll("ABC", std::regex("DEFF?"), "ZZ"), is(std::string("ABC"))); AssertThat(Strings::replaceAll("", std::regex("ccc"), "DD"), is(std::string(""))); } void join_string() { AssertThat(Strings::join("X", "ab", "cd", "ef"), is("abXcdXef")); AssertThat(Strings::join("X", "ab", "cd"), is("abXcd")); AssertThat(Strings::join("X", "ab"), is("ab")); } void join_u32string() { AssertThat(Strings::join(U"X", U"ab", U"cd", U"ef"), is(U"abXcdXef")); AssertThat(Strings::join(U"X", U"ab", U"cd"), is(U"abXcd")); AssertThat(Strings::join(U"X", U"ab"), is(U"ab")); } void split_string_string() { AssertThat(Strings::split("ABCDEFCDEFGGDEDEFGTH", "DEF"), is(std::vector<std::string_view> { "ABC", "C", "GGDE", "GTH" })); AssertThat(Strings::split("ABCDEF", "DEF", true), is(std::vector<std::string_view> { "ABC" })); AssertThat(Strings::split("ABCDEF", "DEF", false), is(std::vector<std::string_view> { "ABC", "" })); AssertThat(Strings::split("DEFABC", "DEF", true), is(std::vector<std::string_view> { "ABC" })); AssertThat(Strings::split("DEFABC", "DEF", false), is(std::vector<std::string_view> { "", "ABC" })); AssertThat(Strings::split("DEFABCDEF", "DEF", true), is(std::vector<std::string_view> { "ABC" })); AssertThat(Strings::split("DEFABCDEF", "DEF", false), is(std::vector<std::string_view> { "", "ABC", "" })); } void split_u32string_u32string() { AssertThat(Strings::split(U"ABCDEFCDEFGGDEDEFGTH", U"DEF"), is(std::vector<std::u32string_view> { U"ABC", U"C", U"GGDE", U"GTH" })); AssertThat(Strings::split(U"ABCDEF", U"DEF", true), is(std::vector<std::u32string_view> { U"ABC" })); AssertThat(Strings::split(U"ABCDEF", U"DEF", false), is(std::vector<std::u32string_view> { U"ABC", U"" })); AssertThat(Strings::split(U"DEFABC", U"DEF", true), is(std::vector<std::u32string_view> { U"ABC" })); AssertThat(Strings::split(U"DEFABC", U"DEF", false), is(std::vector<std::u32string_view> { U"", U"ABC" })); AssertThat(Strings::split(U"DEFABCDEF", U"DEF", true), is(std::vector<std::u32string_view> { U"ABC" })); AssertThat(Strings::split(U"DEFABCDEF", U"DEF", false), is(std::vector<std::u32string_view> { U"", U"ABC", U"" })); } void split_string_regex() { AssertThat(Strings::split("ABCDEFCDEFFGGDEDEFGTH", std::regex("DEFF?")), is(std::vector<std::string_view> { "ABC", "C", "GGDE", "GTH" })); AssertThat(Strings::split("ABC", std::regex("DEFF?")), is(std::vector<std::string_view> { "ABC" })); AssertThat(Strings::split("ABCDEF", std::regex("DEF"), false, true), is(std::vector<std::string_view> { "ABC" })); AssertThat(Strings::split("ABCDEF", std::regex("DEF"), false, false), is(std::vector<std::string_view> { "ABC", "" })); AssertThat(Strings::split("DEFABC", std::regex("DEF"), false, true), is(std::vector<std::string_view> { "ABC" })); AssertThat(Strings::split("DEFABC", std::regex("DEF"), false, false), is(std::vector<std::string_view> { "", "ABC" })); AssertThat(Strings::split("DEFABCDEF", std::regex("DEF"), false, true), is(std::vector<std::string_view> { "ABC" })); AssertThat(Strings::split("DEFABCDEF", std::regex("DEF"), false, false), is(std::vector<std::string_view> { "", "ABC", "" })); AssertThat(Strings::split("", std::regex("ccc"), false, true), is(std::vector<std::string_view> {})); AssertThat(Strings::split("", std::regex("ccc"), false, false), is(std::vector<std::string_view> {})); AssertThat(Strings::split("ABCDEFCDEFFGGDEDEFGTH", std::regex("DEFF?"), true), is(std::vector<std::string_view> { "ABC", "DEF", "C", "DEFF", "GGDE", "DEF", "GTH" })); AssertThat(Strings::split("ABC", std::regex("DEFF?"), true), is(std::vector<std::string_view> { "ABC" })); AssertThat(Strings::split("ABCDEF", std::regex("DEF"), true, true), is(std::vector<std::string_view> { "ABC", "DEF" })); AssertThat(Strings::split("ABCDEF", std::regex("DEF"), true, false), is(std::vector<std::string_view> { "ABC", "DEF", "" })); AssertThat(Strings::split("DEFABC", std::regex("DEF"), true, true), is(std::vector<std::string_view> { "DEF", "ABC" })); AssertThat(Strings::split("DEFABC", std::regex("DEF"), true, false), is(std::vector<std::string_view> { "", "DEF", "ABC" })); AssertThat(Strings::split("DEFABCDEF", std::regex("DEF"), true, true), is(std::vector<std::string_view> { "DEF", "ABC", "DEF" })); AssertThat(Strings::split("DEFABCDEF", std::regex("DEF"), true, false), is(std::vector<std::string_view> { "", "DEF", "ABC", "DEF", "" })); AssertThat(Strings::split("", std::regex("ccc"), true, true), is(std::vector<std::string_view> {})); AssertThat(Strings::split("", std::regex("ccc"), true, false), is(std::vector<std::string_view> {})); } }; } // namespace Util } // namespace Balau
43.186667
168
0.700587
[ "vector" ]
db2ca44d7f4d188d6e37f6ea99f1e791bc538886
7,511
cpp
C++
Viewer/ecflowUI/src/TriggerTableModel.cpp
mpartio/ecflow
ea4b89399d1e7b897ff48c59b1e885e6d53cc8d6
[ "Apache-2.0" ]
null
null
null
Viewer/ecflowUI/src/TriggerTableModel.cpp
mpartio/ecflow
ea4b89399d1e7b897ff48c59b1e885e6d53cc8d6
[ "Apache-2.0" ]
null
null
null
Viewer/ecflowUI/src/TriggerTableModel.cpp
mpartio/ecflow
ea4b89399d1e7b897ff48c59b1e885e6d53cc8d6
[ "Apache-2.0" ]
null
null
null
//============================================================================ // Copyright 2009- ECMWF. // This software is licensed under the terms of the Apache Licence version 2.0 // which can be obtained at http://www.apache.org/licenses/LICENSE-2.0. // In applying this licence, ECMWF does not waive the privileges and immunities // granted to it by virtue of its status as an intergovernmental organisation // nor does it submit to any jurisdiction. // //============================================================================ #include "TriggerTableModel.hpp" #include "IconProvider.hpp" #include "ServerHandler.hpp" #include "VAttribute.hpp" #include "VAttributeType.hpp" #include "VIcon.hpp" #include "VNode.hpp" #include <QDebug> TriggerTableModel::TriggerTableModel(Mode mode,QObject *parent) : QAbstractItemModel(parent), tc_(nullptr), mode_(mode) { } TriggerTableModel::~TriggerTableModel() = default; void TriggerTableModel::clearData() { beginResetModel(); tc_=nullptr; endResetModel(); } void TriggerTableModel::beginUpdate() { beginResetModel(); } void TriggerTableModel::endUpdate() { endResetModel(); } void TriggerTableModel::setTriggerCollector(TriggerTableCollector *tc) { //beginResetModel(); tc_ = tc; //endResetModel(); } bool TriggerTableModel::hasData() const { if(tc_) return tc_->size() > 0; else return false; } int TriggerTableModel::columnCount( const QModelIndex& /*parent */) const { return 1; } int TriggerTableModel::rowCount( const QModelIndex& parent) const { if(!hasData()) return 0; //Parent is the root: if(!parent.isValid()) { return tc_->size(); } return 0; } Qt::ItemFlags TriggerTableModel::flags ( const QModelIndex & index) const { return Qt::ItemIsEnabled | Qt::ItemIsSelectable; } QVariant TriggerTableModel::data( const QModelIndex& index, int role ) const { if(!index.isValid() || !hasData() || (role < Qt::UserRole && role != Qt::DisplayRole && role != Qt::BackgroundRole && role != Qt::TextAlignmentRole && role != Qt::ToolTipRole && role != Qt::ForegroundRole)) { return QVariant(); } int row=index.row(); if(row < 0 || row >= static_cast<int>(tc_->size())) return QVariant(); //QString id=columns_->id(index.column()); const std::vector<TriggerTableItem*>& items=tc_->items(); VItem *t=items[row]->item(); Q_ASSERT(t); if(index.column() == 0) { if(VAttribute* a=t->isAttribute()) { if(role == Qt::DisplayRole) { QStringList d=a->data(); if(VNode* pn=a->parent()) d.append(QString::fromStdString(pn->absNodePath())); return d; } else if(role == Qt::ToolTipRole) { return a->toolTip(); } } else if(VNode* vnode=t->isNode()) { if(role == Qt::DisplayRole) { return QString::fromStdString(vnode->absNodePath()); } else if(role == Qt::BackgroundRole) { if(vnode->isSuspended()) { QVariantList lst; lst << vnode->stateColour() << vnode->realStateColour(); return lst; } else return vnode->stateColour() ; } else if(role == Qt::ForegroundRole) return vnode->stateFontColour(); else if(role == Qt::ToolTipRole) { QString txt=vnode->toolTip(); //txt+=VIcon::toolTip(vnode,icons_); return txt; } else if(role == IconRole) { return VIcon::pixmapList(vnode,nullptr); } else if(role == NodeTypeRole) { if(vnode->isTask()) return 2; else if(vnode->isSuite()) return 0; else if(vnode->isFamily()) return 1; else if(vnode->isAlias()) return 3; return 0; } else if(role == NodeTypeForegroundRole) { return vnode->typeFontColour(); } else if(role == NodePointerRole) { return QVariant::fromValue((void *) vnode); } else if(role == Qt::TextAlignmentRole) { return( mode_==NodeMode)?Qt::AlignCenter:Qt::AlignLeft; } } } //We express the table cell background colour through the UserRole. The //BackgroundRole is already used for the node rendering if(role == Qt::UserRole && mode_ != NodeMode) { const std::set<TriggerCollector::Mode>& modes=items[row]->modes(); if(modes.find(TriggerCollector::Normal) != modes.end()) return QVariant(); else return QColor(233,242,247); } return QVariant(); } QVariant TriggerTableModel::headerData( const int section, const Qt::Orientation orient , const int role ) const { if ( orient != Qt::Horizontal) return QAbstractItemModel::headerData( section, orient, role ); return QVariant(); } QModelIndex TriggerTableModel::index( int row, int column, const QModelIndex & parent ) const { if(!hasData() || row < 0 || column < 0) { return {}; } //When parent is the root this index refers to a node or server if(!parent.isValid()) { return createIndex(row,column); } return {}; } QModelIndex TriggerTableModel::parent(const QModelIndex &child) const { return {}; } VInfo_ptr TriggerTableModel::nodeInfo(const QModelIndex& index) { //For invalid index no info is created. if(!index.isValid()) { VInfo_ptr res; return res; } if(index.row() >=0 && index.row() <= static_cast<int>(tc_->items().size())) { TriggerTableItem* d=tc_->items()[index.row()]; return VInfo::createFromItem(d->item()); } VInfo_ptr res; return res; } QModelIndex TriggerTableModel::itemToIndex(TriggerTableItem *item) { if(item) { for(std::size_t i=0; i < tc_->items().size(); i++) if(tc_->items()[i] == item) return index(i,0); } return {}; } TriggerTableItem* TriggerTableModel::indexToItem(const QModelIndex& index) const { if(!hasData()) return nullptr; int row=index.row(); if(row < 0 || row >= static_cast<int>(tc_->size())) return nullptr; const std::vector<TriggerTableItem*>& items=tc_->items(); return items[row]; } void TriggerTableModel::nodeChanged(const VNode* node, const std::vector<ecf::Aspect::Type>&) { if(!hasData()) return; int num=tc_->items().size(); for(int i=0; i < num; i++) { if(VItem* item=tc_->items()[i]->item()) { if(VNode* n=item->isNode()) { if(n == node) { QModelIndex idx=index(i,0); Q_EMIT dataChanged(idx,idx); } } else if(VAttribute* a=item->isAttribute()) { if(a->parent() == node) { QModelIndex idx=index(i,0); Q_EMIT dataChanged(idx,idx); } } } } }
25.120401
112
0.538543
[ "vector" ]
db2f04dfe086833af6bb8af491ed1d4b9c3a92a4
4,410
cpp
C++
willow/src/op/instancenorm.cpp
gglin001/popart
3225214343f6d98550b6620e809a3544e8bcbfc6
[ "MIT" ]
61
2020-07-06T17:11:46.000Z
2022-03-12T14:42:51.000Z
willow/src/op/instancenorm.cpp
gglin001/popart
3225214343f6d98550b6620e809a3544e8bcbfc6
[ "MIT" ]
1
2021-02-25T01:30:29.000Z
2021-11-09T11:13:14.000Z
willow/src/op/instancenorm.cpp
gglin001/popart
3225214343f6d98550b6620e809a3544e8bcbfc6
[ "MIT" ]
6
2020-07-15T12:33:13.000Z
2021-11-07T06:55:00.000Z
// Copyright (c) 2019 Graphcore Ltd. All rights reserved. #include <algorithm> #include <memory> #include <vector> #include <popart/op/instancenorm.hpp> #include <popart/opmanager.hpp> #include <popart/opserialiser.hpp> #include <popart/tensor.hpp> #include <popart/tensorindex.hpp> namespace popart { InstanceNormOp::InstanceNormOp(const OperatorIdentifier &_opid, float _epsilon, const Op::Settings &settings_) : Op(_opid, settings_), epsilon(_epsilon) {} std::unique_ptr<Op> InstanceNormOp::clone() const { return std::make_unique<InstanceNormOp>(*this); } std::vector<std::unique_ptr<Op>> InstanceNormOp::getGradOps() { std::vector<std::unique_ptr<Op>> upops; upops.emplace_back(std::make_unique<InstanceNormGradOp>(*this)); return upops; } void InstanceNormOp::setup() { auto input_info = inInfo(getInputInIndex()); auto input_shape = input_info.shape(); auto batch_size = input_shape[0]; auto features = input_shape[1]; outInfo(getOutIndex()) = input_info; if (!output->hasIndex(getMeanOutIndex())) { createAndConnectOutTensor(getMeanOutIndex(), outTensor(getOutIndex())->id + "_mean"); } outInfo(getMeanOutIndex()) = {input_info.dataType(), {batch_size * features}}; if (!output->hasIndex(getInvStdDevOutIndex())) { createAndConnectOutTensor(getInvStdDevOutIndex(), outTensor(getOutIndex())->id + "_invStdDev"); } outInfo(getInvStdDevOutIndex()) = {input_info.dataType(), Shape{batch_size * features}}; } void InstanceNormOp::appendOutlineAttributes(OpSerialiserBase &os) const { Op::appendOutlineAttributes(os); os.appendAttribute("epsilon", epsilon); } InstanceNormGradOp::InstanceNormGradOp(const InstanceNormOp &fwd_op) : Op(Onnx::GradOperators::InstanceNormalizationGrad, fwd_op.getSettings()) { } const std::vector<GradInOutMapper> &InstanceNormGradOp::gradInputInfo() const { static const std::vector<GradInOutMapper> inInfo = { {getInputInIndex(), InstanceNormOp::getInputInIndex(), GradOpInType::In}, {getScaleInIndex(), InstanceNormOp::getScaleInIndex(), GradOpInType::In}, {getOutGradInIndex(), InstanceNormOp::getInputInIndex(), GradOpInType::GradOut}, {getMeanInIndex(), InstanceNormOp::getMeanOutIndex(), GradOpInType::Out}, {getInvStdDevInIndex(), InstanceNormOp::getInvStdDevOutIndex(), GradOpInType::Out}, }; return inInfo; } const std::map<int, int> &InstanceNormGradOp::gradOutToNonGradIn() const { static const std::map<int, int> outInfo = { {getInputOutIndex(), InstanceNormOp::getInputInIndex()}, {getScaleOutIndex(), InstanceNormOp::getScaleInIndex()}, {getBOutIndex(), InstanceNormOp::getBInIndex()}}; return outInfo; } void InstanceNormGradOp::setup() { const auto in_info = inInfo(getOutGradInIndex()); const auto in_type = in_info.dataType(); const auto in_shape = in_info.shape(); outInfo(getInputOutIndex()) = in_info; outInfo(getScaleOutIndex()) = {in_type, {in_shape[1]}}; outInfo(getBOutIndex()) = {in_type, {in_shape[1]}}; } std::unique_ptr<Op> InstanceNormGradOp::clone() const { return std::make_unique<InstanceNormGradOp>(*this); } namespace { static OpDefinition::DataTypes T = {DataType::FLOAT16, DataType::FLOAT}; static OpDefinition instanceNormOpDef({OpDefinition::Inputs({ {"input", T}, {"scale", T}, {"B", T}, }), OpDefinition::Outputs({{"output", T}}), OpDefinition::Attributes({ {"epsilon", {"*"}}, })}); static OpCreator<InstanceNormOp> instanceNormOpCreator( OpDefinitions({ {Onnx::Operators::InstanceNormalization_6, instanceNormOpDef}, }), [](const OpCreatorInfo &info) { // default epsilon is 10**(-5) float epsilon = info.attributes.getAttribute<Attributes::Float>("epsilon", 1e-5f); return std::unique_ptr<Op>( new InstanceNormOp(info.opid, epsilon, info.settings)); }, true); } // namespace } // namespace popart
34.453125
80
0.632653
[ "shape", "vector" ]
db3a1ff9316fa8d071249085f16791c748ccf3d0
15,936
cc
C++
src/hash.cc
wanabe/xyzzy
a43581d9a2033d5c43d99cccfecc8e90aa3915e1
[ "RSA-MD" ]
1
2015-10-25T05:58:20.000Z
2015-10-25T05:58:20.000Z
src/hash.cc
wanabe/xyzzy
a43581d9a2033d5c43d99cccfecc8e90aa3915e1
[ "RSA-MD" ]
null
null
null
src/hash.cc
wanabe/xyzzy
a43581d9a2033d5c43d99cccfecc8e90aa3915e1
[ "RSA-MD" ]
null
null
null
#include "stdafx.h" #include "ed.h" #define SXHASH_DEPTH 3 #define MIN_REHASH_THRESHOLD 0.0625 lhash_table * make_hash_table () { lhash_table *p = ldata <lhash_table, Thash_table>::lalloc (); p->test = 0; p->size = 0; p->used = 0; p->count = 0; p->entry = 0; return p; } static inline u_int sxhashval (lisp object) { return u_int (object) >> 3; } /*GENERIC_FUNCTION:IMMEDIATE*/ static u_int sxhash_imm (lisp object, hash_test_proc test) { if (short_int_p (object)) return xshort_int_value (object); if (charp (object)) return (test == Fequalp ? char_upcase (xchar_code (object)) : xchar_code (object)); return sxhashval (object); } /*GENERIC_FUNCTION:NUMBER*/ static u_int sxhash_eql (lisp object) { if (immediatep (object)) return sxhash_imm (object, Feql); switch (object_typeof (object)) { case Tlong_int: return xlong_int_value (object); case Tbignum: { bignum_rep *r = xbignum_rep (object); u_short *p = r->br_data; u_int h = 0; for (int i = min (int (r->br_len), 5); i > 0; i--) h += *p++; return h; } case Tfraction: return (sxhash_eql (xfract_num (object)) + sxhash_eql (xfract_den (object))); case Tsingle_float: return *(u_int *)&xsingle_float_value (object); case Tdouble_float: return (((u_int *)&xdouble_float_value (object)) [0] + ((u_int *)&xdouble_float_value (object)) [1]); case Tcomplex: return (sxhash_eql (xcomplex_real (object)) + sxhash_eql (xcomplex_imag (object))); default: return sxhashval (object); } } /*GENERIC_FUNCTION*/ static u_int sxhash_equal (lisp object, int depth) { u_int hashval = 0; while (depth++ < SXHASH_DEPTH) { if (immediatep (object)) return hashval + sxhash_imm (object, Fequal); switch (object_typeof (object)) { case Tcons: hashval += sxhash_equal (xcar (object), depth); object = xcdr (object); break; case Tsimple_string: case Tcomplex_string: return hashval + hashpjw (object); default: return hashval + sxhash_eql (object); } } return hashval; } /*GENERIC_FUNCTION*/ static u_int sxhash_equalp (lisp object, int depth) { u_int hashval = 0; while (depth++ < SXHASH_DEPTH) { if (immediatep (object)) return hashval + sxhash_imm (object, Fequalp); switch (object_typeof (object)) { case Tcons: hashval += sxhash_equalp (xcar (object), depth); object = xcdr (object); break; case Tsimple_string: case Tcomplex_string: return hashval + ihashpjw (object); case Tsimple_vector: case Tcomplex_vector: { const lisp *p = xvector_contents (object); const lisp *pe = p + xvector_length (object); for (; p < pe; p++) if (!charp (*p)) { p = xvector_contents (object); for (int l = min (xvector_length (object), 8); l > 0; l--, p++) hashval += sxhash_equalp (*p, depth); return hashval; } return hashval + ihashpjw (xvector_contents (object), pe); } case Tstring_array: { const Char *p = xstring_array_contents (object); for (int l = min (xarray_total_size (object), 8); l > 0; l--, p++) hashval += sxhash_equalp (make_char (*p), depth); return hashval; } case Tarray: { const lisp *p = xgeneral_array_contents (object); for (int l = min (xarray_total_size (object), 8); l > 0; l--, p++) hashval += sxhash_equalp (*p, depth); return hashval; } case Thash_table: { const hash_entry *p = xhash_table_entry (object); for (int l = min (xhash_table_size (object), 8); l > 0; l--, p++) { hashval += sxhash_equalp (p->key, depth); hashval += sxhash_equalp (p->value, depth); } return hashval; } case Tstruct_data: { hashval += sxhash_equalp (xstrdata_def (object), depth); for (int i = min (xstrdata_nslots (object) - 1, 4); i >= 0; i--) hashval += sxhash_equalp (xstrdata_data (object) [i], depth); return hashval; } default: return hashval + sxhash_eql (object); } } return hashval; } static u_int sxhash (lisp object, hash_test_proc test) { if (test == Feq) return u_int (object) >> 3; if (test == Feql) return sxhash_eql (object); if (test == Fequal) return sxhash_equal (object, 0); return sxhash_equalp (object, 0); } static inline void clear_hash_entry (hash_entry *entry, int size) { for (int i = 0; i < size; i++, entry++) { entry->key = Qunbound; entry->value = Qnil; } } static inline hash_entry * alloc_hash_entry (int size) { hash_entry *p = (hash_entry *)xmalloc (sizeof (hash_entry) * size); clear_hash_entry (p, size); return p; } static inline void clear_hash_table (lisp hash_table) { assert (hash_table_p (hash_table)); clear_hash_entry (xhash_table_entry (hash_table), xhash_table_size (hash_table)); xhash_table_used (hash_table) = 0; xhash_table_count (hash_table) = 0; } static int hash_table_good_size (int size) { static int prime[] = { 17, 47, 101, 149, 199, 307, 401, 499, 599, 701, 797, 907, 997, 1103, 1499, 1999, 2999, 4001, 4999, 6007, 7001, 8009, 8999, 10007, 19997, 29989, 39989, 49999, 59999, 70001, 79999, 90001, 99991, }; for (u_int i = 0; i < numberof (prime); i++) if (size < prime[i]) return prime[i]; if (!(size & 1)) size++; while (!(size % 3) && !(size % 5) && !(size % 7)) size += 2; return size; } lhash_table * make_hash_table (hash_test_proc test, int size, lisp rehash_size, float rehash_threshold) { lhash_table *ht = make_hash_table (); size = hash_table_good_size (size); ht->entry = alloc_hash_entry (size); ht->size = size; ht->used = 0; ht->count = 0; ht->rehash_size = rehash_size; ht->rehash_threshold = rehash_threshold; ht->test = test; return ht; } lisp Fmake_hash_table (lisp keys) { hash_test_proc test = 0; lisp ltest = find_keyword (Ktest, keys); if (ltest == Qnil) test = Feql; else { if (symbolp (ltest)) ltest = xsymbol_function (ltest); if (functionp (ltest)) { hash_test_proc proc = hash_test_proc (xfunction_fn (ltest)); if (proc == Feq || proc == Feql || proc == Fequal || proc == Fequalp) test = proc; } if (!test) FEprogram_error (Einvalid_argument, xcons (Ktest, xcons (ltest, Qnil))); } int size = find_keyword_int (Ksize, keys); lisp lrehash_size = find_keyword (Krehash_size, keys, make_single_float (1.5)); if (fixnump (lrehash_size)) { int rehash_size = fixnum_value (lrehash_size); if (rehash_size < 1) FEtype_error (lrehash_size, xsymbol_value (Qor_real_integer_1_star)); } else if (floatp (lrehash_size)) { double rehash_size = coerce_to_double_float (lrehash_size); if (rehash_size < 1.0) FEtype_error (lrehash_size, xsymbol_value (Qor_real_integer_1_star)); } else FEtype_error (lrehash_size, xsymbol_value (Qor_real_integer_1_star)); float rehash_threshold = static_cast <float> (find_keyword_float (Krehash_threshold, keys, 0.8)); if (rehash_threshold < 0 || 1 < rehash_threshold) FEtype_error (find_keyword (Krehash_threshold, keys), xsymbol_value (Qreal_between_0_and_1)); if (rehash_threshold < MIN_REHASH_THRESHOLD) rehash_threshold = MIN_REHASH_THRESHOLD; return make_hash_table (test, size, lrehash_size, rehash_threshold); } lisp Fhash_table_p (lisp object) { return boole (hash_table_p (object)); } static inline u_int hashinc (u_int hashval, u_int size) { u_int d = hashval / size % size; return d ? d : 1; } static hash_entry * find_hash_entry (lisp key, lisp hash_table) { check_hash_table (hash_table); hash_entry *entry = xhash_table_entry (hash_table); u_int size = xhash_table_size (hash_table); assert (size); assert (size & 1); hash_test_proc test = xhash_table_test_fn (hash_table); u_int hashval = sxhash (key, test); u_int h = hashval % size; for (u_int i = 0; i <= size; i++) { if (entry[h].key == Qunbound) break; if (entry[h].key != Qdeleted && test (entry[h].key, key) != Qnil) return &entry[h]; if (!i) h = (h + hashinc (hashval, size)) % size; else h = (h + 2) % size; } return 0; } lChar Char_hash (Char key, lisp hash_table) { hash_entry *entry = xhash_table_entry (hash_table); u_int size = xhash_table_size (hash_table); u_int hashval = key; u_int h = hashval % size; for (u_int i = 0; i <= size; i++) { if (entry[h].key == Qunbound) break; if (charp (entry[h].key) && xchar_code (entry[h].key) == key) { if (charp (entry[h].value)) return xchar_code (entry[h].value); break; } if (!i) h = (h + hashinc (hashval, size)) % size; else h = (h + 2) % size; } return lChar_EOF; } lisp gethash (lisp key, lisp hash_table, lisp defalt) { hash_entry *entry = find_hash_entry (key, hash_table); if (entry) return entry->value; return defalt ? defalt : Qnil; } lisp Fgethash (lisp key, lisp hash_table, lisp defalt) { hash_entry *entry = find_hash_entry (key, hash_table); multiple_value::count () = 2; if (entry) { multiple_value::value (1) = Qt; return entry->value; } multiple_value::value (1) = Qnil; return defalt ? defalt : Qnil; } lisp Fremhash (lisp key, lisp hash_table) { hash_entry *entry = find_hash_entry (key, hash_table); if (!entry) return Qnil; entry->key = Qdeleted; entry->value = Qnil; xhash_table_count (hash_table)--; return Qt; } static int add_hash_entry (lisp key, lisp value, lhash_table *table) { u_int size = table->size; assert (size); assert (size & 1); hash_entry *entry = table->entry; hash_test_proc test = table->test; u_int hashval = sxhash (key, test); u_int h = hashval % size; int pos = -1; for (u_int i = 0; i <= size; i++) { if (entry[h].key == Qunbound) { if (pos == -1) pos = h; entry[pos].key = key; entry[pos].value = value; table->used++; table->count++; return 1; } if (entry[h].key == Qdeleted) { if (pos == -1) pos = h; } else if (test (entry[h].key, key) != Qnil) { entry[h].value = value; return 1; } if (!i) h = (h + hashinc (hashval, size)) % size; else h = (h + 2) % size; } return 0; } void hash_table_rehash (lisp hash_table, int inc) { assert (hash_table_p (hash_table)); int old_size = xhash_table_size (hash_table); hash_entry *old_entry = xhash_table_entry (hash_table); lhash_table *new_hash_table = make_hash_table (xhash_table_test_fn (hash_table), old_size + inc, xhash_table_rehash_size (hash_table), xhash_table_rehash_threshold (hash_table)); int new_size = xhash_table_size (new_hash_table); hash_entry *new_entry = xhash_table_entry (new_hash_table); for (int i = 0; i < old_size; i++, old_entry++) if (old_entry->key != Qunbound && old_entry->key != Qdeleted) add_hash_entry (old_entry->key, old_entry->value, new_hash_table); assert (xhash_table_used (new_hash_table) == xhash_table_used (hash_table)); xfree (xhash_table_entry (hash_table)); xhash_table_entry (hash_table) = new_entry; xhash_table_size (hash_table) = new_size; xhash_table_size (new_hash_table) = 0; xhash_table_entry (new_hash_table) = 0; } lisp Fsi_puthash (lisp key, lisp hash_table, lisp value) { check_hash_table (hash_table); if (xhash_table_used (hash_table) >= xhash_table_size (hash_table) * xhash_table_rehash_threshold (hash_table)) { lisp rehash_size = xhash_table_rehash_size (hash_table); int inc; if (fixnump (rehash_size)) inc = fixnum_value (rehash_size); else inc = static_cast <int> (xhash_table_size (hash_table) * coerce_to_double_float (rehash_size) - xhash_table_size (hash_table)); if (inc < xhash_table_size (hash_table) / 2) inc = xhash_table_size (hash_table) / 2; hash_table_rehash (hash_table, inc); } add_hash_entry (key, value, (lhash_table *)hash_table); return value; } lisp Fclrhash (lisp hash_table) { check_hash_table (hash_table); clear_hash_table (hash_table); return hash_table; } lisp Fhash_table_count (lisp hash_table) { check_hash_table (hash_table); return make_fixnum (xhash_table_count (hash_table)); } lisp Fhash_table_rehash_size (lisp hash_table) { check_hash_table (hash_table); return xhash_table_rehash_size (hash_table); } lisp Fhash_table_rehash_threshold (lisp hash_table) { check_hash_table (hash_table); return make_single_float (xhash_table_rehash_threshold (hash_table)); } lisp Fhash_table_size (lisp hash_table) { check_hash_table (hash_table); return make_fixnum (xhash_table_size (hash_table)); } lisp Fhash_table_test (lisp hash_table) { check_hash_table (hash_table); hash_test_proc test = xhash_table_test_fn (hash_table); if (test == Feq) return Seq; if (test == Feql) return Seql; if (test == Fequal) return Sequal; return Sequalp; } lisp Fsxhash (lisp object) { return make_fixnum (sxhash_equal (object, 0)); } int equalp (lhash_table *x, lhash_table *y) { assert (hash_table_p (x)); assert (hash_table_p (y)); if (xhash_table_test_fn (x) != xhash_table_test_fn (y)) return 0; if (xhash_table_count (x) != xhash_table_count (y)) return 0; int size = xhash_table_size (x); hash_entry *entry = xhash_table_entry (x); for (int i = 0; i < size; i++, entry++) if (entry->key != Qunbound && entry->key != Qdeleted) if (!find_hash_entry (entry->key, y)) return 0; entry = xhash_table_entry (x); for (int i = 0; i < size; i++, entry++) if (entry->key != Qunbound && entry->key != Qdeleted) { hash_entry *t = find_hash_entry (entry->key, y); if (Fequalp (entry->value, t->value) == Qnil) return 0; } return 1; } lisp Fsi_enum_hash_table (lisp hash_table, lisp index) { check_hash_table (hash_table); int i = fixnum_value (index); if (i < 0) FErange_error (index); int size = xhash_table_size (hash_table); hash_entry *entry = xhash_table_entry (hash_table) + i; for (; i < size; i++, entry++) if (entry->key != Qunbound && entry->key != Qdeleted) { multiple_value::count () = 3; multiple_value::value (1) = entry->key; multiple_value::value (2) = entry->value; return make_fixnum (i + 1); } return Qnil; } lisp Fgethash_region (lisp from, lisp to, lisp hash_table, lisp defalt) { Buffer *bp = selected_buffer (); point_t p1 = bp->coerce_to_restricted_point (from); point_t p2 = bp->coerce_to_restricted_point (to); if (p1 > p2) swap (p1, p2); int l = p2 - p1; Char *b = (Char *)alloca (sizeof *b * l); bp->substring (p1, l, b); temporary_string t (b, l); return Fgethash (t.string (), hash_table, defalt); }
25.74475
113
0.606049
[ "object" ]
db3edb209ae7360d8c4dc10448402ecd386332cc
700
cpp
C++
2015-04-Training-for-NOI/Problem - QrCode/qrcode.cpp
jsdelivrbot/AlgoAcademy
afcee2e76999346b936c70e00683b518692e97e9
[ "MIT" ]
10
2015-10-30T20:22:19.000Z
2019-03-28T22:37:30.000Z
2015-04-Training-for-NOI/Problem - QrCode/qrcode.cpp
jsdelivrbot/AlgoAcademy
afcee2e76999346b936c70e00683b518692e97e9
[ "MIT" ]
null
null
null
2015-04-Training-for-NOI/Problem - QrCode/qrcode.cpp
jsdelivrbot/AlgoAcademy
afcee2e76999346b936c70e00683b518692e97e9
[ "MIT" ]
12
2015-04-17T20:04:09.000Z
2021-07-03T15:24:24.000Z
#include<iostream> #include<vector> const int MOD = 1000000007; int n, A[16][1<<16]; std::vector<int> v[1<<16]; inline bool check(int i, int j) { for(int k=1; k<n; ++k) { int a = i&3, b = j&3; if((a==0 && b==0) || (a==3 && b==3)) return false; i >>= 1; j >>= 1; } return true; } int main() { std::cin >> n; for(int i=0; i<(1<<n); ++i) A[1][i] = 1; for(int i=0; i<(1<<n); ++i) for(int j=0; j<(1<<n); ++j) if(check(i,j)) v[i].push_back(j); for(int r=1; r<n; ++r) for(int i=0; i<(1<<n); ++i) for(int j:v[i]) A[r+1][j] = (A[r+1][j] + A[r][i]) % MOD; int total = 0; for(int i=0; i<(1<<n); ++i) total = (total + A[n][i]) % MOD; std::cout << total << '\n'; }
17.073171
44
0.462857
[ "vector" ]
b9cbfa0b82f947a13b91c70e03ce69753a07bb3d
4,940
cpp
C++
exercicios/Tp4/Tp4.cpp
xXHachimanXx/LPA
cbd7269b29fe80cb73b915acad79dad28f042f65
[ "MIT" ]
null
null
null
exercicios/Tp4/Tp4.cpp
xXHachimanXx/LPA
cbd7269b29fe80cb73b915acad79dad28f042f65
[ "MIT" ]
3
2020-03-05T12:28:46.000Z
2020-06-14T21:17:22.000Z
exercicios/Tp4/Tp4.cpp
xXHachimanXx/LPA
cbd7269b29fe80cb73b915acad79dad28f042f65
[ "MIT" ]
null
null
null
#include <stdio.h> #include <iostream> #include <string.h> #include <vector> #include <limits.h> #include <algorithm> #define infinity INT_MAX using namespace std; class Aresta { public: int v1, v2; int peso; Aresta(int v1, int v2, int peso); }; Aresta::Aresta(int v1, int v2, int peso) { this->v1 = v1; this->v2 = v2; this->peso = peso; } class Grafo { private: int vertices; int arestas; int **matriz; int menorDistancia(int *distancias, bool *visitados); public: ~Grafo(); //Destrutor Grafo(); //construtor Grafo(int vertices, int arestas); int djkstra(int inicio, int destino); void kruskal(vector<Aresta> arestas); void conectarVertices(int v1, int v2, int distancia); void printMatriz(); void criarConexoes(vector<string> estacoes, int numConexoes); void inicializar(); //inicializador }; /** * Destrutor */ Grafo::~Grafo() { for (int y = 0; y < vertices; y++) { delete matriz[y]; } delete matriz; } /** * Método para inicializar a matriz de adjascência. */ Grafo::Grafo(int vertices, int arestas) { this->vertices = vertices; this->arestas = arestas; this->matriz = new int *[vertices]; for (int y = 0; y < vertices; y++) { this->matriz[y] = new int[vertices]; } //end for inicializar(); } //end Grafo() /** * Inicializar todas as adjascências com '0'. */ void Grafo::inicializar() { if (matriz != NULL) { for (int x = 0; x < this->vertices; x++) for (int y = 0; y < this->vertices; y++) this->matriz[x][y] = 0; } } //end init() void Grafo::printMatriz() { if (matriz != NULL) { for (int x = 0; x < this->vertices; x++) { for (int y = 0; y < this->arestas; y++) { cout << matriz[x][y] << " "; } cout << "" << endl; } cout << endl; } else { cout << "MATRIZ NULA!"; } } //end printMatriz() /** * Método para registrar adjascência na matriz. */ void Grafo::conectarVertices(int x, int y, int distancia) { this->matriz[x][y] = distancia; this->matriz[y][x] = distancia; } //end conectarVertices() vector<string> lerEstacoes(int estacoes) { vector<string> nomes; string nome; for (int y = 0; y < estacoes; y++) { cin >> nome; nomes.push_back(nome); } return nomes; } int buscar(int *vertices, int x) { while (x != vertices[x]) x = vertices[x]; return x; } bool menor(Aresta a1, Aresta a2) { return (a1.peso < a2.peso); } void Grafo::kruskal(vector<Aresta> conexoes) { int somaPesos = 0; int vertices[this->vertices]; int contadorDeArestas = this->vertices - 1; for (size_t x = 0; x < this->vertices; x++) { vertices[x] = x; } // Ordenar arestas por peso sort(conexoes.begin(), conexoes.end(), menor); for (size_t x = 0; x < conexoes.size(); x++) { int v1 = buscar(vertices, conexoes[x].v1); int v2 = buscar(vertices, conexoes[x].v2); if (v1 != v2) { somaPesos += conexoes[x].peso; vertices[v1] = v2; contadorDeArestas--; } } if (contadorDeArestas > 0) cout << "Impossible" << endl; else cout << somaPesos << endl; } int main() { int numEstacoes, numConexoes; string nome; string estacaoInicial; string estacao1; string estacao2; vector<Aresta> conexoes; vector<string> estacoes; int index1; int index2; int distancia; cin >> numEstacoes >> numConexoes; while (numEstacoes != 0 && numConexoes != 0) { estacoes = lerEstacoes(numEstacoes); Grafo* g = new Grafo(numEstacoes, numConexoes); // CriarConexoes for (int y = 0; y < numConexoes; y++) { cin >> estacao1; cin >> estacao2; cin >> distancia; // ACHAR INDEX1 for (int z = 0; z < estacoes.size(); z++) { if (!(estacoes.at(z)).compare(estacao1)) { index1 = z; z = estacoes.size(); } } // ACHAR INDEX2 for (int z = 0; z < estacoes.size(); z++) { if (!(estacoes.at(z)).compare(estacao2)) { index2 = z; z = estacoes.size(); } } // Conectar Vértices g->conectarVertices(index1, index2, distancia); conexoes.push_back(Aresta(index1, index2, distancia)); } // end for cin >> estacaoInicial; g->kruskal(conexoes); conexoes.clear(); estacoes.clear(); cin >> numEstacoes >> numConexoes; } return 0; }
20
66
0.519636
[ "vector" ]
b9cc130d0964cce3249e5d186df29cd92d5d3578
34,175
cpp
C++
external/Carve/src/lib/polyhedron.cpp
AlexVlk/ifcplusplus
2f8cd5457312282b8d90b261dbf8fb66e1c84057
[ "MIT" ]
426
2015-04-12T10:00:46.000Z
2022-03-29T11:03:02.000Z
external/Carve/src/lib/polyhedron.cpp
AlexVlk/ifcplusplus
2f8cd5457312282b8d90b261dbf8fb66e1c84057
[ "MIT" ]
124
2015-05-15T05:51:00.000Z
2022-02-09T15:25:12.000Z
external/Carve/src/lib/polyhedron.cpp
AlexVlk/ifcplusplus
2f8cd5457312282b8d90b261dbf8fb66e1c84057
[ "MIT" ]
214
2015-05-06T07:30:37.000Z
2022-03-26T16:14:04.000Z
// Copyright 2006-2015 Tobias Sargeant (tobias.sargeant@gmail.com). // // This file is part of the Carve CSG Library (http://carve-csg.com/) // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, copy, // modify, merge, publish, distribute, sublicense, and/or sell copies // of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS // BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN // ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN // CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. #if defined(HAVE_CONFIG_H) #include <carve_config.h> #endif #if defined(CARVE_DEBUG) #define DEBUG_CONTAINS_VERTEX #endif #include <carve/djset.hpp> #include <carve/geom.hpp> #include <carve/poly.hpp> #include <carve/octree_impl.hpp> #include <carve/timing.hpp> #include <algorithm> #include <carve/mesh.hpp> #include <random> namespace { bool emb_test(carve::poly::Polyhedron* poly, std::map<int, std::set<int> >& embedding, carve::geom3d::Vector v, int m_id) { std::map<int, carve::PointClass> result; #if defined(CARVE_DEBUG) std::cerr << "test " << v << " (m_id:" << m_id << ")" << std::endl; #endif poly->testVertexAgainstClosedManifolds(v, result, true); std::set<int> inside; for (std::map<int, carve::PointClass>::iterator j = result.begin(); j != result.end(); ++j) { if ((*j).first == m_id) { continue; } if ((*j).second == carve::POINT_IN) { inside.insert((*j).first); } else if ((*j).second == carve::POINT_ON) { #if defined(CARVE_DEBUG) std::cerr << " FAIL" << std::endl; #endif return false; } } #if defined(CARVE_DEBUG) std::cerr << " OK (inside.size()==" << inside.size() << ")" << std::endl; #endif embedding[m_id] = inside; return true; } struct order_faces { bool operator()(const carve::poly::Polyhedron::face_t* const& a, const carve::poly::Polyhedron::face_t* const& b) const { return std::lexicographical_compare(a->vbegin(), a->vend(), b->vbegin(), b->vend()); } }; } // namespace namespace carve { namespace poly { bool Polyhedron::initSpatialIndex() { static carve::TimingName FUNC_NAME("Polyhedron::initSpatialIndex()"); carve::TimingBlock block(FUNC_NAME); octree.setBounds(aabb); octree.addFaces(faces); octree.addEdges(edges); octree.splitTree(); return true; } void Polyhedron::invertAll() { for (size_t i = 0; i < faces.size(); ++i) { faces[i].invert(); } for (size_t i = 0; i < edges.size(); ++i) { std::vector<const face_t*>& f = connectivity.edge_to_face[i]; for (size_t j = 0; j < (f.size() & ~1U); j += 2) { std::swap(f[j], f[j + 1]); } } for (size_t i = 0; i < manifold_is_negative.size(); ++i) { manifold_is_negative[i] = !manifold_is_negative[i]; } } void Polyhedron::invert(const std::vector<bool>& selected_manifolds) { bool altered = false; for (size_t i = 0; i < faces.size(); ++i) { if (faces[i].manifold_id >= 0 && (unsigned)faces[i].manifold_id < selected_manifolds.size() && selected_manifolds[faces[i].manifold_id]) { altered = true; faces[i].invert(); } } if (altered) { for (size_t i = 0; i < edges.size(); ++i) { std::vector<const face_t*>& f = connectivity.edge_to_face[i]; for (size_t j = 0; j < (f.size() & ~1U); j += 2) { int m_id = -1; if (f[j]) { m_id = f[j]->manifold_id; } if (f[j + 1]) { m_id = f[j + 1]->manifold_id; } if (m_id >= 0 && (unsigned)m_id < selected_manifolds.size() && selected_manifolds[m_id]) { std::swap(f[j], f[j + 1]); } } } for (size_t i = 0; i < std::min(selected_manifolds.size(), manifold_is_negative.size()); ++i) { manifold_is_negative[i] = !manifold_is_negative[i]; } } } void Polyhedron::initVertexConnectivity() { static carve::TimingName FUNC_NAME( "static Polyhedron initVertexConnectivity()"); carve::TimingBlock block(FUNC_NAME); // allocate space for connectivity info. connectivity.vertex_to_edge.resize(vertices.size()); connectivity.vertex_to_face.resize(vertices.size()); std::vector<size_t> vertex_face_count; vertex_face_count.resize(vertices.size()); // work out how many faces/edges each vertex is connected to, in // order to save on array reallocs. for (unsigned i = 0; i < faces.size(); ++i) { face_t& f = faces[i]; for (unsigned j = 0; j < f.nVertices(); j++) { vertex_face_count[vertexToIndex_fast(f.vertex(j))]++; } } for (size_t i = 0; i < vertices.size(); ++i) { connectivity.vertex_to_edge[i].reserve(vertex_face_count[i]); connectivity.vertex_to_face[i].reserve(vertex_face_count[i]); } // record connectivity from vertex to edges. for (size_t i = 0; i < edges.size(); ++i) { size_t v1i = vertexToIndex_fast(edges[i].v1); size_t v2i = vertexToIndex_fast(edges[i].v2); connectivity.vertex_to_edge[v1i].push_back(&edges[i]); connectivity.vertex_to_edge[v2i].push_back(&edges[i]); } // record connectivity from vertex to faces. for (size_t i = 0; i < faces.size(); ++i) { face_t& f = faces[i]; for (unsigned j = 0; j < f.nVertices(); j++) { size_t vi = vertexToIndex_fast(f.vertex(j)); connectivity.vertex_to_face[vi].push_back(&f); } } } bool Polyhedron::initConnectivity() { static carve::TimingName FUNC_NAME("Polyhedron::initConnectivity()"); carve::TimingBlock block(FUNC_NAME); // temporary measure: initialize connectivity by creating a // half-edge mesh, and then converting back. std::vector<mesh::Vertex<3> > vertex_storage; vertex_storage.reserve(vertices.size()); for (size_t i = 0; i < vertices.size(); ++i) { vertex_storage.push_back(mesh::Vertex<3>(vertices[i].v)); } std::vector<mesh::Face<3>*> mesh_faces; std::unordered_map<const mesh::Face<3>*, size_t> face_map; { std::vector<mesh::Vertex<3>*> vert_ptrs; for (size_t i = 0; i < faces.size(); ++i) { const face_t& src = faces[i]; vert_ptrs.clear(); vert_ptrs.reserve(src.nVertices()); for (size_t j = 0; j < src.nVertices(); ++j) { size_t vi = vertexToIndex_fast(src.vertex(j)); vert_ptrs.push_back(&vertex_storage[vi]); } mesh::Face<3>* face = new mesh::Face<3>(vert_ptrs.begin(), vert_ptrs.end()); mesh_faces.push_back(face); face_map[face] = i; } } std::vector<mesh::Mesh<3>*> meshes; mesh::Mesh<3>::create(mesh_faces.begin(), mesh_faces.end(), meshes, mesh::MeshOptions()); mesh::MeshSet<3>* meshset = new mesh::MeshSet<3>(vertex_storage, meshes); manifold_is_closed.resize(meshset->meshes.size()); manifold_is_negative.resize(meshset->meshes.size()); std::unordered_map<std::pair<size_t, size_t>, std::list<mesh::Edge<3>*>, carve::hash_pair> edge_map; if (meshset->vertex_storage.size()) { mesh::Vertex<3>* Vbase = &meshset->vertex_storage[0]; for (size_t m = 0; m < meshset->meshes.size(); ++m) { mesh::Mesh<3>* mesh = meshset->meshes[m]; manifold_is_closed[m] = mesh->isClosed(); for (size_t f = 0; f < mesh->faces.size(); ++f) { mesh::Face<3>* src = mesh->faces[f]; mesh::Edge<3>* e = src->edge; faces[face_map[src]].manifold_id = m; do { edge_map[std::make_pair(e->v1() - Vbase, e->v2() - Vbase)].push_back( e); e = e->next; } while (e != src->edge); } } } size_t n_edges = 0; for (auto& i : edge_map) { if (i.first.first < i.first.second || edge_map.find(std::make_pair(i.first.second, i.first.first)) == edge_map.end()) { n_edges++; } } edges.clear(); edges.reserve(n_edges); for (auto& i : edge_map) { if (i.first.first < i.first.second || edge_map.find(std::make_pair(i.first.second, i.first.first)) == edge_map.end()) { edges.push_back( edge_t(&vertices[i.first.first], &vertices[i.first.second], this)); } } initVertexConnectivity(); for (size_t f = 0; f < faces.size(); ++f) { face_t& face = faces[f]; size_t N = face.nVertices(); for (size_t v = 0; v < N; ++v) { size_t v1i = vertexToIndex_fast(face.vertex(v)); size_t v2i = vertexToIndex_fast(face.vertex((v + 1) % N)); std::vector<const edge_t*> found_edge; CARVE_ASSERT(carve::is_sorted(connectivity.vertex_to_edge[v1i].begin(), connectivity.vertex_to_edge[v1i].end())); CARVE_ASSERT(carve::is_sorted(connectivity.vertex_to_edge[v2i].begin(), connectivity.vertex_to_edge[v2i].end())); std::set_intersection(connectivity.vertex_to_edge[v1i].begin(), connectivity.vertex_to_edge[v1i].end(), connectivity.vertex_to_edge[v2i].begin(), connectivity.vertex_to_edge[v2i].end(), std::back_inserter(found_edge)); CARVE_ASSERT(found_edge.size() == 1); face.edge(v) = found_edge[0]; } } connectivity.edge_to_face.resize(edges.size()); for (size_t i = 0; i < edges.size(); ++i) { size_t v1i = vertexToIndex_fast(edges[i].v1); size_t v2i = vertexToIndex_fast(edges[i].v2); std::list<mesh::Edge<3>*>& efwd = edge_map[std::make_pair(v1i, v2i)]; std::list<mesh::Edge<3>*>& erev = edge_map[std::make_pair(v1i, v2i)]; for (std::list<mesh::Edge<3>*>::iterator j = efwd.begin(); j != efwd.end(); ++j) { mesh::Edge<3>* edge = *j; if (face_map.find(edge->face) != face_map.end()) { connectivity.edge_to_face[i].push_back(&faces[face_map[edge->face]]); if (edge->rev == nullptr) { connectivity.edge_to_face[i].push_back(nullptr); } else { connectivity.edge_to_face[i].push_back( &faces[face_map[edge->rev->face]]); } } } for (std::list<mesh::Edge<3>*>::iterator j = erev.begin(); j != erev.end(); ++j) { mesh::Edge<3>* edge = *j; if (face_map.find(edge->face) != face_map.end()) { if (edge->rev == nullptr) { connectivity.edge_to_face[i].push_back(nullptr); connectivity.edge_to_face[i].push_back(&faces[face_map[edge->face]]); } } } } delete meshset; return true; } bool Polyhedron::calcManifoldEmbedding() { // this could be significantly sped up using bounding box tests // to work out what pairs of manifolds are embedding candidates. // A per-manifold AABB could also be used to speed up // testVertexAgainstClosedManifolds(). static carve::TimingName FUNC_NAME("Polyhedron::calcManifoldEmbedding()"); static carve::TimingName CME_V( "Polyhedron::calcManifoldEmbedding() (vertices)"); static carve::TimingName CME_E("Polyhedron::calcManifoldEmbedding() (edges)"); static carve::TimingName CME_F("Polyhedron::calcManifoldEmbedding() (faces)"); carve::TimingBlock block(FUNC_NAME); const unsigned MCOUNT = manifoldCount(); if (MCOUNT < 2) { return true; } std::set<int> vertex_manifolds; std::map<int, std::set<int> > embedding; carve::Timing::start(CME_V); for (size_t i = 0; i < vertices.size(); ++i) { vertex_manifolds.clear(); if (vertexManifolds(&vertices[i], set_inserter(vertex_manifolds)) != 1) { continue; } int m_id = *vertex_manifolds.begin(); if (embedding.find(m_id) == embedding.end()) { if (emb_test(this, embedding, vertices[i].v, m_id) && embedding.size() == MCOUNT) { carve::Timing::stop(); goto done; } } } carve::Timing::stop(); carve::Timing::start(CME_E); for (size_t i = 0; i < edges.size(); ++i) { if (connectivity.edge_to_face[i].size() == 2) { int m_id; const face_t* f1 = connectivity.edge_to_face[i][0]; const face_t* f2 = connectivity.edge_to_face[i][1]; if (f1) { m_id = f1->manifold_id; } if (f2) { m_id = f2->manifold_id; } if (embedding.find(m_id) == embedding.end()) { if (emb_test(this, embedding, (edges[i].v1->v + edges[i].v2->v) / 2, m_id) && embedding.size() == MCOUNT) { carve::Timing::stop(); goto done; } } } } carve::Timing::stop(); carve::Timing::start(CME_F); for (size_t i = 0; i < faces.size(); ++i) { int m_id = faces[i].manifold_id; if (embedding.find(m_id) == embedding.end()) { carve::geom2d::P2 pv; if (!carve::geom2d::pickContainedPoint(faces[i].projectedVertices(), pv)) { continue; } carve::geom3d::Vector v = carve::poly::face::unproject(faces[i], pv); if (emb_test(this, embedding, v, m_id) && embedding.size() == MCOUNT) { carve::Timing::stop(); goto done; } } } carve::Timing::stop(); CARVE_FAIL("could not find test points"); // std::cerr << "could not find test points!!!" << std::endl; // return true; done:; for (std::map<int, std::set<int> >::iterator i = embedding.begin(); i != embedding.end(); ++i) { #if defined(CARVE_DEBUG) std::cerr << (*i).first << " : "; std::copy((*i).second.begin(), (*i).second.end(), std::ostream_iterator<int>(std::cerr, ",")); std::cerr << std::endl; #endif (*i).second.insert(-1); } std::set<int> parents, new_parents; parents.insert(-1); while (embedding.size()) { new_parents.clear(); for (std::map<int, std::set<int> >::iterator i = embedding.begin(); i != embedding.end(); ++i) { if ((*i).second.size() == 1) { if (parents.find(*(*i).second.begin()) != parents.end()) { new_parents.insert((*i).first); #if defined(CARVE_DEBUG) std::cerr << "parent(" << (*i).first << "): " << *(*i).second.begin() << std::endl; #endif } else { #if defined(CARVE_DEBUG) std::cerr << "no parent: " << (*i).first << " (looking for: " << *(*i).second.begin() << ")" << std::endl; #endif } } } for (std::set<int>::const_iterator i = new_parents.begin(); i != new_parents.end(); ++i) { embedding.erase(*i); } for (std::map<int, std::set<int> >::iterator i = embedding.begin(); i != embedding.end(); ++i) { size_t n = 0; for (std::set<int>::const_iterator j = parents.begin(); j != parents.end(); ++j) { n += (*i).second.erase((*j)); } CARVE_ASSERT(n != 0); } parents.swap(new_parents); } return true; } bool Polyhedron::init() { static carve::TimingName FUNC_NAME("Polyhedron::init()"); carve::TimingBlock block(FUNC_NAME); aabb.fit(vertices.begin(), vertices.end(), vec_adapt_vertex_ref()); connectivity.vertex_to_edge.clear(); connectivity.vertex_to_face.clear(); connectivity.edge_to_face.clear(); if (!initConnectivity()) { return false; } if (!initSpatialIndex()) { return false; } return true; } void Polyhedron::faceRecalc() { for (size_t i = 0; i < faces.size(); ++i) { if (!faces[i].recalc()) { std::ostringstream out; out << "face " << i << " recalc failed"; throw carve::exception(out.str()); } } } Polyhedron::Polyhedron(const Polyhedron& poly) { faces.reserve(poly.faces.size()); for (size_t i = 0; i < poly.faces.size(); ++i) { const face_t& src = poly.faces[i]; faces.push_back(src); } commonFaceInit(false); // calls setFaceAndVertexOwner() and init() } Polyhedron::Polyhedron(const Polyhedron& poly, const std::vector<bool>& selected_manifolds) { size_t n_faces = 0; for (size_t i = 0; i < poly.faces.size(); ++i) { const face_t& src = poly.faces[i]; if (src.manifold_id >= 0 && (unsigned)src.manifold_id < selected_manifolds.size() && selected_manifolds[src.manifold_id]) { n_faces++; } } faces.reserve(n_faces); for (size_t i = 0; i < poly.faces.size(); ++i) { const face_t& src = poly.faces[i]; if (src.manifold_id >= 0 && (unsigned)src.manifold_id < selected_manifolds.size() && selected_manifolds[src.manifold_id]) { faces.push_back(src); } } commonFaceInit(false); // calls setFaceAndVertexOwner() and init() } Polyhedron::Polyhedron(const Polyhedron& poly, int m_id) { size_t n_faces = 0; for (size_t i = 0; i < poly.faces.size(); ++i) { const face_t& src = poly.faces[i]; if (src.manifold_id == m_id) { n_faces++; } } faces.reserve(n_faces); for (size_t i = 0; i < poly.faces.size(); ++i) { const face_t& src = poly.faces[i]; if (src.manifold_id == m_id) { faces.push_back(src); } } commonFaceInit(false); // calls setFaceAndVertexOwner() and init() } Polyhedron::Polyhedron(const std::vector<carve::geom3d::Vector>& _vertices, int n_faces, const std::vector<int>& face_indices) { // The polyhedron is defined by a vector of vertices, which we // want to copy, and a face index list, from which we need to // generate a set of Faces. vertices.clear(); vertices.resize(_vertices.size()); for (size_t i = 0; i < _vertices.size(); ++i) { vertices[i].v = _vertices[i]; } faces.reserve(n_faces); std::vector<int>::const_iterator iter = face_indices.begin(); std::vector<const vertex_t*> v; for (int i = 0; i < n_faces; ++i) { int vertexCount = *iter++; v.clear(); while (vertexCount--) { CARVE_ASSERT(*iter >= 0); CARVE_ASSERT((unsigned)*iter < vertices.size()); v.push_back(&vertices[*iter++]); } faces.push_back(face_t(v)); } setFaceAndVertexOwner(); if (!init()) { throw carve::exception("polyhedron creation failed"); } } Polyhedron::Polyhedron(std::vector<face_t>& _faces, std::vector<vertex_t>& _vertices, bool _recalc) { faces.swap(_faces); vertices.swap(_vertices); setFaceAndVertexOwner(); if (_recalc) { faceRecalc(); } if (!init()) { throw carve::exception("polyhedron creation failed"); } } Polyhedron::Polyhedron(std::vector<face_t>& _faces, bool _recalc) { faces.swap(_faces); commonFaceInit(_recalc); // calls setFaceAndVertexOwner() and init() } Polyhedron::Polyhedron(std::list<face_t>& _faces, bool _recalc) { faces.reserve(_faces.size()); std::copy(_faces.begin(), _faces.end(), std::back_inserter(faces)); commonFaceInit(_recalc); // calls setFaceAndVertexOwner() and init() } void Polyhedron::collectFaceVertices( std::vector<face_t>& faces, std::vector<vertex_t>& vertices, std::unordered_map<const vertex_t*, const vertex_t*>& vmap) { // Given a set of faces, copy all referenced vertices into a // single vertex array and update the faces to point into that // array. On exit, vmap contains a mapping from old pointer to // new pointer. vertices.clear(); vmap.clear(); for (size_t i = 0, il = faces.size(); i != il; ++i) { face_t& f = faces[i]; for (size_t j = 0, jl = f.nVertices(); j != jl; ++j) { vmap[f.vertex(j)] = nullptr; } } vertices.reserve(vmap.size()); for (std::unordered_map<const vertex_t *, const vertex_t *>::iterator i = vmap.begin(), e = vmap.end(); i != e; ++i) { vertices.push_back(*(*i).first); (*i).second = &vertices.back(); } for (size_t i = 0, il = faces.size(); i != il; ++i) { face_t& f = faces[i]; for (size_t j = 0, jl = f.nVertices(); j != jl; ++j) { f.vertex(j) = vmap[f.vertex(j)]; } } } void Polyhedron::collectFaceVertices(std::vector<face_t>& faces, std::vector<vertex_t>& vertices) { std::unordered_map<const vertex_t*, const vertex_t*> vmap; collectFaceVertices(faces, vertices, vmap); } void Polyhedron::setFaceAndVertexOwner() { for (size_t i = 0; i < vertices.size(); ++i) { vertices[i].owner = this; } for (size_t i = 0; i < faces.size(); ++i) { faces[i].owner = this; } } void Polyhedron::commonFaceInit(bool _recalc) { collectFaceVertices(faces, vertices); setFaceAndVertexOwner(); if (_recalc) { faceRecalc(); } if (!init()) { throw carve::exception("polyhedron creation failed"); } } Polyhedron::~Polyhedron() {} void Polyhedron::testVertexAgainstClosedManifolds( const carve::geom3d::Vector& v, std::map<int, PointClass>& result, bool ignore_orientation) const { for (size_t i = 0; i < faces.size(); i++) { if (!manifold_is_closed[faces[i].manifold_id]) { continue; // skip open manifolds } if (faces[i].containsPoint(v)) { result[faces[i].manifold_id] = POINT_ON; } } double ray_len = aabb.extent.length() * 2; std::vector<const face_t*> possible_faces; std::vector<std::pair<const face_t*, carve::geom3d::Vector> > manifold_intersections; std::mt19937 rng; std::normal_distribution<double> norm; for (;;) { carve::geom3d::Vector ray_dir = geom::VECTOR(norm(rng), norm(rng), norm(rng)); ray_dir.normalize(); carve::geom3d::Vector v2 = v + ray_dir * ray_len; bool failed = false; carve::geom3d::LineSegment line(v, v2); carve::geom3d::Vector intersection; possible_faces.clear(); manifold_intersections.clear(); octree.findFacesNear(line, possible_faces); for (unsigned i = 0; !failed && i < possible_faces.size(); i++) { if (!manifold_is_closed[possible_faces[i]->manifold_id]) { continue; // skip open manifolds } if (result.find(possible_faces[i]->manifold_id) != result.end()) { continue; // already ON } switch (possible_faces[i]->lineSegmentIntersection(line, intersection)) { case INTERSECT_FACE: { manifold_intersections.push_back( std::make_pair(possible_faces[i], intersection)); break; } case INTERSECT_NONE: { break; } default: { failed = true; break; } } } if (!failed) { break; } } std::vector<int> crossings(manifold_is_closed.size(), 0); for (size_t i = 0; i < manifold_intersections.size(); ++i) { const face_t* f = manifold_intersections[i].first; crossings[f->manifold_id]++; } for (size_t i = 0; i < crossings.size(); ++i) { #if defined(CARVE_DEBUG) std::cerr << "crossing: " << i << " = " << crossings[i] << " is_negative = " << manifold_is_negative[i] << std::endl; #endif if (!manifold_is_closed[i]) { continue; } if (result.find(i) != result.end()) { continue; } PointClass pc = (crossings[i] & 1) ? POINT_IN : POINT_OUT; if (!ignore_orientation && manifold_is_negative[i]) { pc = (PointClass)-pc; } result[i] = pc; } } PointClass Polyhedron::containsVertex(const carve::geom3d::Vector& v, const face_t** hit_face, bool even_odd, int manifold_id) const { if (hit_face) { *hit_face = nullptr; } #if defined(DEBUG_CONTAINS_VERTEX) std::cerr << "{containsVertex " << v << "}" << std::endl; #endif if (!aabb.containsPoint(v)) { #if defined(DEBUG_CONTAINS_VERTEX) std::cerr << "{final:OUT(aabb short circuit)}" << std::endl; #endif // XXX: if the top level manifolds are negative, this should be POINT_IN. // for the moment, this only works for a single manifold. if (manifold_is_negative.size() == 1 && manifold_is_negative[0]) { return POINT_IN; } return POINT_OUT; } for (size_t i = 0; i < faces.size(); i++) { if (manifold_id != -1 && manifold_id != faces[i].manifold_id) { continue; } // XXX: Do allow the tested vertex to be ON an open // manifold. This was here originally because of the // possibility of an open manifold contained within a closed // manifold. // if (!manifold_is_closed[faces[i].manifold_id]) continue; if (faces[i].containsPoint(v)) { #if defined(DEBUG_CONTAINS_VERTEX) std::cerr << "{final:ON(hits face " << &faces[i] << ")}" << std::endl; #endif if (hit_face) { *hit_face = &faces[i]; } return POINT_ON; } } double ray_len = aabb.extent.length() * 2; std::vector<const face_t*> possible_faces; std::vector<std::pair<const face_t*, carve::geom3d::Vector> > manifold_intersections; for (;;) { double a1 = random() / double(RAND_MAX) * M_TWOPI; double a2 = random() / double(RAND_MAX) * M_TWOPI; carve::geom3d::Vector ray_dir = carve::geom::VECTOR(sin(a1) * sin(a2), cos(a1) * sin(a2), cos(a2)); #if defined(DEBUG_CONTAINS_VERTEX) std::cerr << "{testing ray: " << ray_dir << "}" << std::endl; #endif carve::geom3d::Vector v2 = v + ray_dir * ray_len; bool failed = false; carve::geom3d::LineSegment line(v, v2); carve::geom3d::Vector intersection; possible_faces.clear(); manifold_intersections.clear(); octree.findFacesNear(line, possible_faces); for (unsigned i = 0; !failed && i < possible_faces.size(); i++) { if (manifold_id != -1 && manifold_id != faces[i].manifold_id) { continue; } if (!manifold_is_closed[possible_faces[i]->manifold_id]) { continue; } switch (possible_faces[i]->lineSegmentIntersection(line, intersection)) { case INTERSECT_FACE: { #if defined(DEBUG_CONTAINS_VERTEX) std::cerr << "{intersects face: " << possible_faces[i] << " dp: " << dot(ray_dir, possible_faces[i]->plane_eqn.N) << "}" << std::endl; #endif if (!even_odd && fabs(dot(ray_dir, possible_faces[i]->plane_eqn.N)) < CARVE_EPSILON) { #if defined(DEBUG_CONTAINS_VERTEX) std::cerr << "{failing(small dot product)}" << std::endl; #endif failed = true; break; } manifold_intersections.push_back( std::make_pair(possible_faces[i], intersection)); break; } case INTERSECT_NONE: { break; } default: { #if defined(DEBUG_CONTAINS_VERTEX) std::cerr << "{failing(degenerate intersection)}" << std::endl; #endif failed = true; break; } } } if (!failed) { if (even_odd) { return (manifold_intersections.size() & 1) ? POINT_IN : POINT_OUT; } #if defined(DEBUG_CONTAINS_VERTEX) std::cerr << "{intersections ok [count:" << manifold_intersections.size() << "], sorting}" << std::endl; #endif carve::geom3d::sortInDirectionOfRay( ray_dir, manifold_intersections.begin(), manifold_intersections.end(), carve::geom3d::vec_adapt_pair_second()); std::vector<int> crossings(manifold_is_closed.size(), 0); for (size_t i = 0; i < manifold_intersections.size(); ++i) { const face_t* f = manifold_intersections[i].first; if (dot(ray_dir, f->plane_eqn.N) < 0.0) { crossings[f->manifold_id]++; } else { crossings[f->manifold_id]--; } } #if defined(DEBUG_CONTAINS_VERTEX) for (size_t i = 0; i < crossings.size(); ++i) { std::cerr << "{manifold " << i << " crossing count: " << crossings[i] << "}" << std::endl; } #endif for (size_t i = 0; i < manifold_intersections.size(); ++i) { const face_t* f = manifold_intersections[i].first; #if defined(DEBUG_CONTAINS_VERTEX) std::cerr << "{intersection at " << manifold_intersections[i].second << " id: " << f->manifold_id << " count: " << crossings[f->manifold_id] << "}" << std::endl; #endif if (crossings[f->manifold_id] < 0) { // inside this manifold. #if defined(DEBUG_CONTAINS_VERTEX) std::cerr << "{final:IN}" << std::endl; #endif return POINT_IN; } else if (crossings[f->manifold_id] > 0) { // outside this manifold, but it's an infinite manifold. (for instance, an // inverted cube) #if defined(DEBUG_CONTAINS_VERTEX) std::cerr << "{final:OUT}" << std::endl; #endif return POINT_OUT; } } #if defined(DEBUG_CONTAINS_VERTEX) std::cerr << "{final:OUT(default)}" << std::endl; #endif return POINT_OUT; } } } void Polyhedron::findEdgesNear(const carve::geom::aabb<3>& aabb, std::vector<const edge_t*>& outEdges) const { outEdges.clear(); octree.findEdgesNear(aabb, outEdges); } void Polyhedron::findEdgesNear(const carve::geom3d::LineSegment& line, std::vector<const edge_t*>& outEdges) const { outEdges.clear(); octree.findEdgesNear(line, outEdges); } void Polyhedron::findEdgesNear(const carve::geom3d::Vector& v, std::vector<const edge_t*>& outEdges) const { outEdges.clear(); octree.findEdgesNear(v, outEdges); } void Polyhedron::findEdgesNear(const face_t& face, std::vector<const edge_t*>& edges) const { edges.clear(); octree.findEdgesNear(face, edges); } void Polyhedron::findEdgesNear(const edge_t& edge, std::vector<const edge_t*>& outEdges) const { outEdges.clear(); octree.findEdgesNear(edge, outEdges); } void Polyhedron::findFacesNear(const carve::geom3d::LineSegment& line, std::vector<const face_t*>& outFaces) const { outFaces.clear(); octree.findFacesNear(line, outFaces); } void Polyhedron::findFacesNear(const carve::geom::aabb<3>& aabb, std::vector<const face_t*>& outFaces) const { outFaces.clear(); octree.findFacesNear(aabb, outFaces); } void Polyhedron::findFacesNear(const edge_t& edge, std::vector<const face_t*>& outFaces) const { outFaces.clear(); octree.findFacesNear(edge, outFaces); } void Polyhedron::transform(const carve::math::Matrix& xform) { for (size_t i = 0; i < vertices.size(); i++) { vertices[i].v = xform * vertices[i].v; } for (size_t i = 0; i < faces.size(); i++) { faces[i].recalc(); } init(); } void Polyhedron::print(std::ostream& o) const { o << "Polyhedron@" << this << " {" << std::endl; for (std::vector<vertex_t>::const_iterator i = vertices.begin(), e = vertices.end(); i != e; ++i) { o << " V@" << &(*i) << " " << (*i).v << std::endl; } for (std::vector<edge_t>::const_iterator i = edges.begin(), e = edges.end(); i != e; ++i) { o << " E@" << &(*i) << " {" << std::endl; o << " V@" << (*i).v1 << " - " << "V@" << (*i).v2 << std::endl; const std::vector<const face_t*>& faces = connectivity.edge_to_face[edgeToIndex_fast(&(*i))]; for (size_t j = 0; j < (faces.size() & ~1U); j += 2) { o << " fp: F@" << faces[j] << ", F@" << faces[j + 1] << std::endl; } o << " }" << std::endl; } for (std::vector<face_t>::const_iterator i = faces.begin(), e = faces.end(); i != e; ++i) { o << " F@" << &(*i) << " {" << std::endl; o << " vertices {" << std::endl; for (face_t::const_vertex_iter_t j = (*i).vbegin(), je = (*i).vend(); j != je; ++j) { o << " V@" << (*j) << std::endl; } o << " }" << std::endl; o << " edges {" << std::endl; for (face_t::const_edge_iter_t j = (*i).ebegin(), je = (*i).eend(); j != je; ++j) { o << " E@" << (*j) << std::endl; } carve::geom::plane<3> p = (*i).plane_eqn; o << " }" << std::endl; o << " normal " << (*i).plane_eqn.N << std::endl; o << " aabb " << (*i).aabb << std::endl; o << " plane_eqn "; carve::geom::operator<<<3>(o, p); o << std::endl; o << " }" << std::endl; } o << "}" << std::endl; } void Polyhedron::canonicalize() { orderVertices(); for (size_t i = 0; i < faces.size(); i++) { face_t& f = faces[i]; size_t j = std::distance(f.vbegin(), std::min_element(f.vbegin(), f.vend())); if (j) { { std::vector<const vertex_t*> temp; temp.reserve(f.nVertices()); std::copy(f.vbegin() + j, f.vend(), std::back_inserter(temp)); std::copy(f.vbegin(), f.vbegin() + j, std::back_inserter(temp)); std::copy(temp.begin(), temp.end(), f.vbegin()); } { std::vector<const edge_t*> temp; temp.reserve(f.nEdges()); std::copy(f.ebegin() + j, f.eend(), std::back_inserter(temp)); std::copy(f.ebegin(), f.ebegin() + j, std::back_inserter(temp)); std::copy(temp.begin(), temp.end(), f.ebegin()); } } } std::vector<face_t*> face_ptrs; face_ptrs.reserve(faces.size()); for (size_t i = 0; i < faces.size(); ++i) { face_ptrs.push_back(&faces[i]); } std::sort(face_ptrs.begin(), face_ptrs.end(), order_faces()); std::vector<face_t> sorted_faces; sorted_faces.reserve(faces.size()); for (size_t i = 0; i < faces.size(); ++i) { sorted_faces.push_back(*face_ptrs[i]); } std::swap(faces, sorted_faces); } } // namespace poly } // namespace carve
30.270151
83
0.58695
[ "mesh", "vector", "transform" ]
b9d457fbcb20ade041c2ac14245253f61a6e8e48
3,842
cpp
C++
src_v2/main.cpp
define-private-public/sqlite_orm_todo_sample
d42c41c6b641d663724137090569778106d1c5b0
[ "Unlicense" ]
1
2021-11-18T15:51:15.000Z
2021-11-18T15:51:15.000Z
src_v2/main.cpp
define-private-public/sqlite_orm_todo_sample
d42c41c6b641d663724137090569778106d1c5b0
[ "Unlicense" ]
null
null
null
src_v2/main.cpp
define-private-public/sqlite_orm_todo_sample
d42c41c6b641d663724137090569778106d1c5b0
[ "Unlicense" ]
null
null
null
#include <iostream> #include <string> #include "../tabulate.hpp" #include "Data/Storage.h" using namespace std; using namespace Data; // Commands to use const string quit_cmd("quit"); const string list_cmd("list"); const string add_cmd("add"); const string doing_cmd("doing"); const string done_cmd("done"); const string clean_cmd("clean"); // Shows a list of all TODOs in the database void do_list_cmd(const Storage &storage) { // Check for no entries const vector<TodoItem> all_todos = storage.todos(); if (all_todos.size() == 0) { cout << " No TODOs yet..." << endl; return; } // Setup a nice table to display all of the TODOs tabulate::Table display_table; display_table.format().border_top("").border_bottom("").border_left("").border_right("").corner("").padding_left(2); display_table.add_row({"Id no.", "Status", "Who", "Task"}); for (const TodoItem &td : all_todos) { display_table.add_row({ to_string(td.id()), td.status_as_printable_string(), td.who(), td.thing() }); } display_table[1].format().border_top("-"); cout << display_table << endl; } // Allows users to add new todos void do_add_cmd(Storage &storage, const string &line) { // parse out what we need const string args = line.substr(add_cmd.size() + 1); // Rest of the line are the arguments const size_t pivot = args.find(' '); const string who = args.substr(0, pivot); // First word is the person who needs todo it const string thing = args.substr(pivot + 1); // REst of it is the task // Put it in const TodoItem todo = storage.add_todo(who, thing); cout << " Added new TODO for " << todo.who() << " [id=" << todo.id() << "]" << endl; } // Lets users change the status of a TODO void change_status_cmd(Storage &storage, const string &line, const TodoItem::Status status) { // Get the id they want to change const string todo_id_str = line.substr(line.find(' ') + 1); const int todo_id = stoi(todo_id_str); // Try to make the change const bool ok = storage.change_todo_status(todo_id, status); if (ok) cout << " Marked TODO [" << todo_id << "] as " << TodoItem::printable_string(status) << endl; else cout << " Error, couldn't update TODO with id no. " << todo_id << endl; } // Cleans out all TODOs marked as "finished" void do_clean_cmd(Storage &storage) { const int num_cleaned = storage.remove_finished_todos(); if (num_cleaned != 0) cout << " Removed " << num_cleaned << " TODO(s) marked as done." << endl; else cout << " No TODOs cleaned out." << endl; } // Checks if a string starts with another substring inline bool string_starts_with(const string &haystack, const string &needle) { return (haystack.rfind(needle, 0) == 0); } int main(int argc, char *argv[]) { // Load the database Storage storage("todo_db.sqlite3"); cout << "Loaded TODO database; Lasted edited on " << storage.last_time_edited() << endl; // Loop until EOF or `quit` cout << "> "; string line; while (getline(cin, line)) { if (line == quit_cmd) break; else if (line == list_cmd) do_list_cmd(storage); else if (string_starts_with(line, add_cmd)) do_add_cmd(storage, line); else if (string_starts_with(line, doing_cmd)) change_status_cmd(storage, line, TodoItem::Status::InProgress); else if (string_starts_with(line, done_cmd)) change_status_cmd(storage, line, TodoItem::Status::Finished); else if (line == clean_cmd) do_clean_cmd(storage); // If not, prompt for another command cout << "> "; } cout << endl; return 0; }
31.235772
120
0.619469
[ "vector" ]
b9da234e0df1e225a98bb69ec56d514d0263f733
2,752
cpp
C++
src/server.cpp
nathan-osman/ldclient
7a85fed0d3f539e73b2671df5802d941099824eb
[ "MIT" ]
1
2018-01-23T07:31:58.000Z
2018-01-23T07:31:58.000Z
src/server.cpp
nathan-osman/ldclient
7a85fed0d3f539e73b2671df5802d941099824eb
[ "MIT" ]
null
null
null
src/server.cpp
nathan-osman/ldclient
7a85fed0d3f539e73b2671df5802d941099824eb
[ "MIT" ]
null
null
null
/* * The MIT License (MIT) * * Copyright (c) 2017 Nathan Osman * * 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 <QHostAddress> #include <QJsonDocument> #include <QJsonObject> #include <QJsonValue> #include <QWebSocket> #include <QWebSocketServer> #include "server.h" Server::Server(QObject *parent) : QObject(parent), mServer(new QWebSocketServer("", QWebSocketServer::NonSecureMode, this)), mSocket(nullptr) { connect(mServer, &QWebSocketServer::newConnection, this, &Server::onNewConnection); } Server::~Server() { if (mSocket) { mSocket->deleteLater(); } } bool Server::start(quint16 port) { return mServer->listen(QHostAddress::Any, port); } void Server::stop() { mServer->close(); } void Server::onNewConnection() { QWebSocket *socket = mServer->nextPendingConnection(); // Abort if there is already an active connection if (mSocket) { socket->abort(); socket->deleteLater(); return; } connect(socket, &QWebSocket::disconnected, this, &Server::onDisconnected); connect(socket, &QWebSocket::textMessageReceived, this, &Server::onTextMessageReceived); mSocket = socket; } void Server::onDisconnected() { mSocket->deleteLater(); mSocket = nullptr; } void Server::onTextMessageReceived(const QString &message) { QJsonObject object = QJsonDocument::fromJson(message.toUtf8()).object(); QString name = object.value("name").toString(); bool state = object.value("state").toBool(); if (name == "audio") { if (state) { emit audioStarted(); } else { emit audioStopped(); } } else { emit stateChanged(name, state); } }
28.081633
92
0.694041
[ "object" ]
b9dca5d37a62a6de0bd0424127fce3f05b393d80
18,296
cpp
C++
gbplanner/src/map_manager_voxblox_impl.cpp
HalfManHalfWookey/gbplanner_ros
26aecaf01202fbbf1dc122a4d8bc965406b5e9a9
[ "BSD-3-Clause" ]
2
2022-02-15T11:19:33.000Z
2022-03-30T12:10:58.000Z
gbplanner/src/map_manager_voxblox_impl.cpp
HalfManHalfWookey/gbplanner_ros
26aecaf01202fbbf1dc122a4d8bc965406b5e9a9
[ "BSD-3-Clause" ]
null
null
null
gbplanner/src/map_manager_voxblox_impl.cpp
HalfManHalfWookey/gbplanner_ros
26aecaf01202fbbf1dc122a4d8bc965406b5e9a9
[ "BSD-3-Clause" ]
1
2021-07-16T17:50:51.000Z
2021-07-16T17:50:51.000Z
#include "gbplanner/map_manager_voxblox_impl.h" namespace explorer { namespace gbplanner { // TSDF template <typename SDFServerType, typename SDFVoxelType> voxblox::Layer<SDFVoxelType>* MapManagerVoxblox<SDFServerType, SDFVoxelType>::getSDFLayer() { return sdf_server_.getTsdfMapPtr()->getTsdfLayerPtr(); } // ESDF template <> voxblox::Layer<voxblox::EsdfVoxel>* MapManagerVoxblox<voxblox::EsdfServer, voxblox::EsdfVoxel>::getSDFLayer() { return sdf_server_.getEsdfMapPtr()->getEsdfLayerPtr(); } template <typename SDFServerType, typename SDFVoxelType> MapManagerVoxblox<SDFServerType, SDFVoxelType>::MapManagerVoxblox( const ros::NodeHandle& nh, const ros::NodeHandle& nh_private) : MapManager(nh, nh_private), sdf_server_(nh, nh_private), occupancy_distance_voxelsize_factor_(1.0F) { sdf_layer_ = getSDFLayer(); CHECK_NOTNULL(sdf_layer_); // Get local parameters from passed nodehandle if (!nh_private.getParam("occupancy_distance_voxelsize_factor", occupancy_distance_voxelsize_factor_)) { ROS_INFO_STREAM( "MapManagerVoxblox: failed to find parameter for " "occupancy_distance_voxelsize_factor, using default of: " << occupancy_distance_voxelsize_factor_); } // Setup E/TsdfIntegratorBase::Config amd object separately (also called in // e/tsdf_server_ ctor) tsdf_integrator_config_ = voxblox::getTsdfIntegratorConfigFromRosParam(nh_private); esdf_integrator_config_ = voxblox::getEsdfIntegratorConfigFromRosParam(nh_private); } template <typename SDFServerType, typename SDFVoxelType> double MapManagerVoxblox<SDFServerType, SDFVoxelType>::getResolution() const { return sdf_layer_->voxel_size(); } template <typename SDFServerType, typename SDFVoxelType> bool MapManagerVoxblox<SDFServerType, SDFVoxelType>::getStatus() const { return true; } // TSDF template <typename SDFServerType, typename SDFVoxelType> bool MapManagerVoxblox<SDFServerType, SDFVoxelType>::checkUnknownStatus( const SDFVoxelType* voxel) const { if (voxel == nullptr || voxel->weight < 1e-6) { return true; } return false; } // ESDF template <> bool MapManagerVoxblox<voxblox::EsdfServer, voxblox::EsdfVoxel>:: checkUnknownStatus(const voxblox::EsdfVoxel* voxel) const { if (voxel == nullptr || !voxel->observed) { return true; } return false; } template <typename SDFServerType, typename SDFVoxelType> typename MapManagerVoxblox<SDFServerType, SDFVoxelType>::VoxelStatus MapManagerVoxblox<SDFServerType, SDFVoxelType>::getVoxelStatus( const Eigen::Vector3d& position) const { SDFVoxelType* voxel = sdf_layer_->getVoxelPtrByCoordinates( position.cast<voxblox::FloatingPoint>()); if (checkUnknownStatus(voxel)) { return VoxelStatus::kUnknown; } const float distance_thres = occupancy_distance_voxelsize_factor_ * sdf_layer_->voxel_size() + 1e-6; if (voxel->distance <= distance_thres) { return VoxelStatus::kOccupied; } return VoxelStatus::kFree; } template <typename SDFServerType, typename SDFVoxelType> typename MapManagerVoxblox<SDFServerType, SDFVoxelType>::VoxelStatus MapManagerVoxblox<SDFServerType, SDFVoxelType>::getRayStatus( const Eigen::Vector3d& view_point, const Eigen::Vector3d& voxel_to_test, bool stop_at_unknown_voxel) const { // This involves doing a raycast from view point to voxel to test. // Let's get the global voxel coordinates of both. float voxel_size = sdf_layer_->voxel_size(); float voxel_size_inv = 1.0 / voxel_size; const voxblox::Point start_scaled = view_point.cast<voxblox::FloatingPoint>() * voxel_size_inv; const voxblox::Point end_scaled = voxel_to_test.cast<voxblox::FloatingPoint>() * voxel_size_inv; voxblox::LongIndexVector global_voxel_indices; voxblox::castRay(start_scaled, end_scaled, &global_voxel_indices); const float distance_thres = occupancy_distance_voxelsize_factor_ * sdf_layer_->voxel_size() + 1e-6; // Iterate over the ray. for (const voxblox::GlobalIndex& global_index : global_voxel_indices) { SDFVoxelType* voxel = sdf_layer_->getVoxelPtrByGlobalIndex(global_index); if (checkUnknownStatus(voxel)) { if (stop_at_unknown_voxel) { return VoxelStatus::kUnknown; } } else if (voxel->distance <= distance_thres) { return VoxelStatus::kOccupied; } } return VoxelStatus::kFree; } template <typename SDFServerType, typename SDFVoxelType> typename MapManagerVoxblox<SDFServerType, SDFVoxelType>::VoxelStatus MapManagerVoxblox<SDFServerType, SDFVoxelType>::getBoxStatus( const Eigen::Vector3d& center, const Eigen::Vector3d& size, bool stop_at_unknown_voxel) const { float voxel_size = sdf_layer_->voxel_size(); float voxel_size_inv = 1.0 / voxel_size; // Get the center of the bounding box as a global index. voxblox::LongIndex center_voxel_index = voxblox::getGridIndexFromPoint<voxblox::LongIndex>( center.cast<voxblox::FloatingPoint>(), voxel_size_inv); // Get the bounding box size in terms of voxels. voxblox::AnyIndex box_voxels(std::ceil(size.x() * voxel_size_inv), std::ceil(size.y() * voxel_size_inv), std::ceil(size.z() * voxel_size_inv)); // Iterate over all voxels in the bounding box. return getBoxStatusInVoxels(center_voxel_index, box_voxels, stop_at_unknown_voxel); } template <typename SDFServerType, typename SDFVoxelType> typename MapManagerVoxblox<SDFServerType, SDFVoxelType>::VoxelStatus MapManagerVoxblox<SDFServerType, SDFVoxelType>::getBoxStatusInVoxels( const voxblox::LongIndex& box_center, const voxblox::AnyIndex& box_voxels, bool stop_at_unknown_voxel) const { VoxelStatus current_status = VoxelStatus::kFree; const float distance_thres = occupancy_distance_voxelsize_factor_ * sdf_layer_->voxel_size() + 1e-6; voxblox::LongIndex voxel_index = box_center; for (voxel_index.x() = box_center.x() - box_voxels.x() / 2; voxel_index.x() <= box_center.x() + box_voxels.x() / 2; voxel_index.x()++) { for (voxel_index.y() = box_center.y() - box_voxels.y() / 2; voxel_index.y() <= box_center.y() + box_voxels.y() / 2; voxel_index.y()++) { for (voxel_index.z() = box_center.z() - box_voxels.z() / 2; voxel_index.z() <= box_center.z() + box_voxels.z() / 2; voxel_index.z()++) { SDFVoxelType* voxel = sdf_layer_->getVoxelPtrByGlobalIndex(voxel_index); if (checkUnknownStatus(voxel)) { if (stop_at_unknown_voxel) { return VoxelStatus::kUnknown; } current_status = VoxelStatus::kUnknown; } else if (voxel->distance <= distance_thres) { return VoxelStatus::kOccupied; } } } } return current_status; } template <typename SDFServerType, typename SDFVoxelType> typename MapManagerVoxblox<SDFServerType, SDFVoxelType>::VoxelStatus MapManagerVoxblox<SDFServerType, SDFVoxelType>::getPathStatus( const Eigen::Vector3d& start, const Eigen::Vector3d& end, const Eigen::Vector3d& box_size, bool stop_at_unknown_voxel) const { // Cast ray along the center to make sure we don't miss anything. float voxel_size = sdf_layer_->voxel_size(); float voxel_size_inv = 1.0 / voxel_size; const voxblox::Point start_scaled = start.cast<voxblox::FloatingPoint>() * voxel_size_inv; const voxblox::Point end_scaled = end.cast<voxblox::FloatingPoint>() * voxel_size_inv; voxblox::LongIndexVector global_voxel_indices; voxblox::castRay(start_scaled, end_scaled, &global_voxel_indices); // Get the bounding box size in terms of voxels. voxblox::AnyIndex box_voxels(std::ceil(box_size.x() * voxel_size_inv), std::ceil(box_size.y() * voxel_size_inv), std::ceil(box_size.z() * voxel_size_inv)); // Iterate over the ray. VoxelStatus current_status = VoxelStatus::kFree; for (const voxblox::GlobalIndex& global_index : global_voxel_indices) { VoxelStatus box_status = getBoxStatusInVoxels(global_index, box_voxels, stop_at_unknown_voxel); if (box_status == VoxelStatus::kOccupied) { return box_status; } if (stop_at_unknown_voxel && box_status == VoxelStatus::kUnknown) { return box_status; } current_status = box_status; } return current_status; } // TSDF template <typename SDFServerType, typename SDFVoxelType> void MapManagerVoxblox<SDFServerType, SDFVoxelType>::clearIfUnknown( SDFVoxelType& voxel) { static constexpr float visualizeDistanceIntensityTsdfVoxels_kMinWeight = 1e-3 + 1e-6; // value for points to appear with // visualizeDistanceIntensityTsdfVoxels if (voxel.weight < 1e-6) { voxel.weight = visualizeDistanceIntensityTsdfVoxels_kMinWeight; voxel.distance = tsdf_integrator_config_.default_truncation_distance; } } // ESDF template <> void MapManagerVoxblox<voxblox::EsdfServer, voxblox::EsdfVoxel>::clearIfUnknown( voxblox::EsdfVoxel& voxel) { if (!voxel.observed) { voxel.observed = true; voxel.hallucinated = true; voxel.distance = esdf_integrator_config_.default_distance_m; } } template <typename SDFServerType, typename SDFVoxelType> bool MapManagerVoxblox<SDFServerType, SDFVoxelType>::augmentFreeBox( const Eigen::Vector3d& position, const Eigen::Vector3d& box_size) { voxblox::HierarchicalIndexMap block_voxel_list; voxblox::utils::getAndAllocateBoxAroundPoint( position.cast<voxblox::FloatingPoint>(), box_size, sdf_layer_, &block_voxel_list); for (const std::pair<voxblox::BlockIndex, voxblox::VoxelIndexList>& kv : block_voxel_list) { // Get block. typename voxblox::Block<SDFVoxelType>::Ptr block_ptr = sdf_layer_->getBlockPtrByIndex(kv.first); for (const voxblox::VoxelIndex& voxel_index : kv.second) { if (!block_ptr->isValidVoxelIndex(voxel_index)) { continue; } SDFVoxelType& voxel = block_ptr->getVoxelByVoxelIndex(voxel_index); // Clear voxels that haven't been cleared yet clearIfUnknown(voxel); } } return true; } template <typename SDFServerType, typename SDFVoxelType> void MapManagerVoxblox<SDFServerType, SDFVoxelType>::getFreeSpacePointCloud( std::vector<Eigen::Vector3d> multiray_endpoints, StateVec state, pcl::PointCloud<pcl::PointXYZ>::Ptr cloud) { pcl::PointCloud<pcl::PointXYZ> free_cloud; Eigen::Vector3d state_vec(state[0], state[1], state[2]); for (auto ep : multiray_endpoints) { VoxelStatus vs = getRayStatus(state_vec, ep, false); if (vs != VoxelStatus::kOccupied) { pcl::PointXYZ data; Eigen::Matrix3d rot_W2B; rot_W2B = Eigen::AngleAxisd(state[3], Eigen::Vector3d::UnitZ()) * Eigen::AngleAxisd(0.0, Eigen::Vector3d::UnitY()) * Eigen::AngleAxisd(0.0, Eigen::Vector3d::UnitX()); Eigen::Matrix3d rot_B2W; rot_B2W = rot_W2B.inverse(); Eigen::Vector3d origin(state[0], state[1], state[2]); Eigen::Vector3d epb = rot_B2W * (ep - origin); // Eigen::Vector3d epb = ep; data.x = epb(0); data.y = epb(1); data.z = epb(2); cloud->points.push_back(data); } } } template <typename SDFServerType, typename SDFVoxelType> void MapManagerVoxblox<SDFServerType, SDFVoxelType>::getScanStatus( Eigen::Vector3d& pos, std::vector<Eigen::Vector3d>& multiray_endpoints, std::tuple<int, int, int>& gain_log, std::vector<std::pair<Eigen::Vector3d, VoxelStatus>>& voxel_log) { unsigned int num_unknown_voxels = 0, num_free_voxels = 0, num_occupied_voxels = 0; const float voxel_size = sdf_layer_->voxel_size(); const float voxel_size_inv = 1.0 / voxel_size; const voxblox::Point start_scaled = pos.cast<voxblox::FloatingPoint>() * voxel_size_inv; const float distance_thres = occupancy_distance_voxelsize_factor_ * sdf_layer_->voxel_size() + 1e-6; // GBPLANNER_NOTES: no optimization / no twice-counting considerations // possible without refactoring planning strategy here // Iterate for every endpoint, insert unknown voxels found over every ray into // a set to avoid double-counting Important: do not use <VoxelIndex> type // directly, will break voxblox's implementations // Move away from std::unordered_set and work with std::vector + std::unique // count at the end (works best for now) voxel_log.reserve(multiray_endpoints.size() * tsdf_integrator_config_.max_ray_length_m * voxel_size_inv); // optimize for number of rays for (size_t i = 0; i < multiray_endpoints.size(); ++i) { const voxblox::Point end_scaled = multiray_endpoints[i].cast<voxblox::FloatingPoint>() * voxel_size_inv; voxblox::LongIndexVector global_voxel_indices; voxblox::castRay(start_scaled, end_scaled, &global_voxel_indices); // Iterate over the ray. for (size_t k = 0; k < global_voxel_indices.size(); ++k) { const voxblox::GlobalIndex& global_index = global_voxel_indices[k]; SDFVoxelType* voxel = sdf_layer_->getVoxelPtrByGlobalIndex(global_index); // Unknown if (checkUnknownStatus(voxel)) { ++num_unknown_voxels; voxel_log.push_back(std::make_pair( voxblox::getCenterPointFromGridIndex(global_index, voxel_size) .cast<double>(), VoxelStatus::kUnknown)); continue; } // Free if (voxel->distance > distance_thres) { ++num_free_voxels; voxel_log.push_back(std::make_pair( voxblox::getCenterPointFromGridIndex(global_index, voxel_size) .cast<double>(), VoxelStatus::kFree)); continue; } // Occupied ++num_occupied_voxels; voxel_log.push_back(std::make_pair( voxblox::getCenterPointFromGridIndex(global_index, voxel_size) .cast<double>(), VoxelStatus::kOccupied)); break; } } gain_log = std::make_tuple(num_unknown_voxels, num_free_voxels, num_occupied_voxels); } template <typename SDFServerType, typename SDFVoxelType> void MapManagerVoxblox<SDFServerType, SDFVoxelType>::augmentFreeFrustum() { ROS_WARN_THROTTLE(5.0, "MapManagerVoxblox::augmentFreeFrustum: N/A"); } template <typename SDFServerType, typename SDFVoxelType> void MapManagerVoxblox<SDFServerType, SDFVoxelType>::extractLocalMap( const Eigen::Vector3d& center, const Eigen::Vector3d& bounding_box_size, std::vector<Eigen::Vector3d>& occupied_voxels, std::vector<Eigen::Vector3d>& free_voxels) { ROS_WARN_THROTTLE(5.0, "MapManagerVoxblox::extractLocalMap --> Temporary solution " "to be consistent with Octomap interface."); occupied_voxels.clear(); free_voxels.clear(); double resolution = getResolution(); int Nx = std::ceil(bounding_box_size.x() / (2 * resolution)) * 2; // always even number int Ny = std::ceil(bounding_box_size.y() / (2 * resolution)) * 2; int Nz = std::ceil(bounding_box_size.z() / (2 * resolution)) * 2; // Correct center voxel depeding on the resolution of the map. const Eigen::Vector3d center_corrected( resolution * std::floor(center.x() / resolution) + resolution / 2.0, resolution * std::floor(center.y() / resolution) + resolution / 2.0, resolution * std::floor(center.z() / resolution) + resolution / 2.0); Eigen::Vector3d origin_offset; origin_offset = center_corrected - Eigen::Vector3d(Nx * resolution / 2, Ny * resolution / 2, Nz * resolution / 2); for (double x_ind = 0; x_ind <= Nx; ++x_ind) { for (double y_ind = 0; y_ind <= Ny; ++y_ind) { for (double z_ind = 0; z_ind <= Nz; ++z_ind) { Eigen::Vector3d pos(x_ind * resolution, y_ind * resolution, z_ind * resolution); pos = pos + origin_offset; VoxelStatus vs = getVoxelStatus(pos); if (vs == VoxelStatus::kFree) { free_voxels.push_back(pos); } else if (vs == VoxelStatus::kOccupied) { occupied_voxels.push_back(pos); } } } } } template <typename SDFServerType, typename SDFVoxelType> void MapManagerVoxblox<SDFServerType, SDFVoxelType>::extractLocalMapAlongAxis( const Eigen::Vector3d& center, const Eigen::Vector3d& axis, const Eigen::Vector3d& bounding_box_size, std::vector<Eigen::Vector3d>& occupied_voxels, std::vector<Eigen::Vector3d>& free_voxels) { occupied_voxels.clear(); free_voxels.clear(); double resolution = getResolution(); int Nx = std::ceil(bounding_box_size.x() / (2 * resolution)) * 2; // always even number int Ny = std::ceil(bounding_box_size.y() / (2 * resolution)) * 2; int Nz = std::ceil(bounding_box_size.z() / (2 * resolution)) * 2; // Correct center voxel depeding on the resolution of the map. const Eigen::Vector3d center_corrected( resolution * std::floor(center.x() / resolution) + resolution / 2.0, resolution * std::floor(center.y() / resolution) + resolution / 2.0, resolution * std::floor(center.z() / resolution) + resolution / 2.0); Eigen::Vector3d origin_offset; Eigen::Vector3d half_box(Nx * resolution / 2, Ny * resolution / 2, Nz * resolution / 2); origin_offset = center_corrected - half_box; Eigen::Vector3d x_axis(1.0, 0.0, 0.0); Eigen::Quaternion<double> quat_W2S; quat_W2S.setFromTwoVectors(x_axis, axis.normalized()); for (double x_ind = 0; x_ind <= Nx; ++x_ind) { for (double y_ind = 0; y_ind <= Ny; ++y_ind) { for (double z_ind = 0; z_ind <= Nz; ++z_ind) { Eigen::Vector3d pos(x_ind * resolution, y_ind * resolution, z_ind * resolution); pos = pos - half_box; pos = quat_W2S * pos + center_corrected; VoxelStatus vs = getVoxelStatus(pos); if (vs == VoxelStatus::kFree) { free_voxels.push_back(pos); } else if (vs == VoxelStatus::kOccupied) { occupied_voxels.push_back(pos); } } } } } } // namespace gbplanner } // namespace explorer
39.094017
80
0.690807
[ "object", "vector" ]
b9dcff5906dd22133ad30fe73591eebb98ce753e
1,220
cpp
C++
framework/gef_common_message/gef_common_message_processor.cpp
paladin-t/game-editor-framework
99520db6502bc632a8dbb19fa86aa38e494f7bc7
[ "MIT" ]
4
2017-05-30T15:33:15.000Z
2020-06-02T15:38:57.000Z
framework/gef_common_message/gef_common_message_processor.cpp
paladin-t/game-editor-framework
99520db6502bc632a8dbb19fa86aa38e494f7bc7
[ "MIT" ]
null
null
null
framework/gef_common_message/gef_common_message_processor.cpp
paladin-t/game-editor-framework
99520db6502bc632a8dbb19fa86aa38e494f7bc7
[ "MIT" ]
1
2020-05-02T06:13:19.000Z
2020-05-02T06:13:19.000Z
/** * @version: 1.0 * @author: Wang Renxin, * https://github.com/paladin-t/game_editor_framework * mailto:hellotony521@qq.com * @file: This file is a part of GEF, for copyright detail * information, see the LICENSE file. */ #define GEF_MSG_DOTNET_COMPILE #include "gef_common_message_processor.h" namespace gef { MessageProcessor::MessageProcessor() { msgDict = gcnew MsgDict(); } MessageProcessor::~MessageProcessor() { msgDict = nullptr; } Boolean MessageProcessor::RegMsgProc(UInt32 g, UInt32 t, MsgEventHandler^ proc) { if(proc == nullptr) return false; if(!msgDict->ContainsKey(MsgKey(g, t))) msgDict->Add(MsgKey(g, t), nullptr); msgDict[MsgKey(g, t)] += proc; return true; } Boolean MessageProcessor::UnregMsgProc(UInt32 g, UInt32 t, MsgEventHandler^ proc) { if(proc == nullptr) return false; if(msgDict->ContainsKey(MsgKey(g, t))) msgDict[MsgKey(g, t)] -= proc; else return false; return true; } Void MessageProcessor::Raise(UInt32 g, UInt32 t, List<Object^>^ p) { if(!msgDict->ContainsKey(MsgKey(g, t))) return; if(msgDict[MsgKey(g, t)]) msgDict[MsgKey(g, t)]->Invoke(g, t, p); } } #undef GEF_MSG_DOTNET_COMPILE
23.921569
84
0.67377
[ "object" ]
b9e6a1c2c08b7ebaf0a1603f1d52e734bc669b2a
3,208
hpp
C++
src/main/resources/Type.hpp
HarvardPL/formulog
508c7688bbe826a6951cc8c3e70026e57548e044
[ "Apache-2.0" ]
109
2019-05-10T16:51:36.000Z
2022-03-13T02:39:31.000Z
src/main/resources/Type.hpp
HarvardPL/formulog
508c7688bbe826a6951cc8c3e70026e57548e044
[ "Apache-2.0" ]
11
2020-12-03T18:37:29.000Z
2022-02-14T17:11:34.000Z
src/main/resources/Type.hpp
HarvardPL/formulog
508c7688bbe826a6951cc8c3e70026e57548e044
[ "Apache-2.0" ]
5
2019-10-08T10:00:27.000Z
2021-02-22T17:06:05.000Z
#pragma once #include <atomic> #include <cassert> #include <cstdlib> #include <map> #include <utility> #include <vector> #include "Symbol.hpp" namespace flg { using namespace std; struct Type; struct TypeSubst; typedef pair<vector<Type>, Type> functor_type; struct Type { string name; bool is_var; vector<Type> args; static functor_type lookup(const Symbol& sym); static functor_type i32; static functor_type i64; static functor_type fp32; static functor_type fp64; static functor_type string_; static functor_type bool_; private: static functor_type make_prim(const string& name); static functor_type make_prim(const string& name, const vector<Type>& args); static Type make_index(const string& name); static Type new_var(); static atomic_size_t cnt; }; inline bool operator<(const Type& lhs, const Type& rhs) { return lhs.name < rhs.name; } struct TypeSubst { void put(const Type var, const Type other); Type apply(const Type& type); void clear(); private: map<Type, Type> m; }; void TypeSubst::put(const Type var, const Type other) { assert(var.is_var); if (other.is_var) { if (var < other) { m.emplace(var, other); } else if (other < var) { m.emplace(other, var); } } else { m.emplace(var, other); } } Type TypeSubst::apply(const Type& ty) { if (ty.is_var) { auto v = m.find(ty); if (v == m.end()) { return ty; } else { return apply(v->second); } } vector<Type> newArgs; for (auto& arg : ty.args) { newArgs.push_back(apply(arg)); } return Type{ty.name, ty.is_var, newArgs}; } void TypeSubst::clear() { m.clear(); } ostream& operator<<(ostream& out, const Type& type) { auto args = type.args; if (!args.empty()) { out << "("; } out << type.name; for (auto& arg : args) { out << " " << arg; } if (!args.empty()) { out << ")"; } return out; } functor_type Type::make_prim(const string& name, const vector<Type>& args) { return make_pair(vector<Type>(), Type{name, false, args}); } functor_type Type::make_prim(const string& name) { return make_prim(name, {}); } Type Type::make_index(const string& name) { return Type{name, false, {}}; } functor_type Type::bool_ = make_prim("Bool"); functor_type Type::i32 = make_prim("_ BitVec", { make_index("32") }); functor_type Type::i64 = make_prim("_ BitVec", { make_index("64") }); functor_type Type::fp32 = make_prim("_ FloatingPoint", { make_index("8"), make_index("24") }); functor_type Type::fp64 = make_prim("_ FloatingPoint", { make_index("11"), make_index("53") }); functor_type Type::string_ = make_prim("String"); atomic_size_t Type::cnt; Type Type::new_var() { return Type{"x" + to_string(cnt++), true, {}}; } functor_type Type::lookup(const Symbol& sym) { switch (sym) { case Symbol::min_term: case Symbol::max_term: abort(); case Symbol::boxed_bool: return bool_; case Symbol::boxed_i32: return i32; case Symbol::boxed_i64: return i64; case Symbol::boxed_fp32: return fp32; case Symbol::boxed_fp64: return fp64; case Symbol::boxed_string: return string_; /* INSERT 0 */ } __builtin_unreachable(); } } // namespace flg
21.972603
95
0.65586
[ "vector" ]
b9e82e5c9b9a56b81083f2b05e746c9665dfef20
1,128
hpp
C++
server/src/grid/grid.hpp
p-mercury/gridlock
d3c458fa0c74fe776df489ed82a860eaf5dc1abe
[ "MIT" ]
1
2020-06-11T13:28:32.000Z
2020-06-11T13:28:32.000Z
server/src/grid/grid.hpp
JustinZal/gridlock
d3c458fa0c74fe776df489ed82a860eaf5dc1abe
[ "MIT" ]
1
2020-06-14T07:54:53.000Z
2020-06-14T07:54:53.000Z
server/src/grid/grid.hpp
JustinZal/gridlock
d3c458fa0c74fe776df489ed82a860eaf5dc1abe
[ "MIT" ]
1
2021-08-24T09:22:18.000Z
2021-08-24T09:22:18.000Z
#ifndef GRIDLOCK_GRID_HPP #define GRIDLOCK_GRID_HPP #include <stdexcept> #include <iostream> #include <fstream> #include <memory> #include <mutex> #include <vector> #include <json.hpp> #include <sys/types.h> #include <pwd.h> #include <unistd.h> #include <nlohmann/json.hpp> #include "constants.hpp" #include "player.hpp" #include "node.hpp" #include "material.hpp" #include "blueprint.hpp" #include "module.hpp" #include "item.hpp" #include "grid.hpp" class Grid{ private: // This mutex synchronizes all access to we socket sessions std::mutex mutex_; // List of players std::vector<std::shared_ptr<Player>> players; // Array of nodes, main grid std::vector<std::vector<std::shared_ptr<Node>>> grid; //---- Grid mode std::vector<std::shared_ptr<Material>> materials; std::vector<std::shared_ptr<Blueprint>> blueprints; std::vector<std::shared_ptr<Module>> modules; std::vector<std::shared_ptr<Item>> items; bool parseGameMode(std::string _file); public: Grid( unsigned long _seed, unsigned int _size=20, unsigned int _playerCount=4, std::string _file="standard"); void Turn(); }; #endif
17.904762
60
0.718085
[ "vector" ]
b9ed532c215a3ebf166c7e55d671d40f62393e9d
14,884
cpp
C++
third_party/SimpleDBus/src/base/Holder.cpp
BrainAlive/brainflow
1b939c342f4052d6de99623a67385a86dd66bd56
[ "MIT" ]
1
2022-01-08T15:25:46.000Z
2022-01-08T15:25:46.000Z
third_party/SimpleDBus/src/base/Holder.cpp
HDPNC/brainflow
ede79fbd5fcc823c1c64bcc3af3e88b4d12177bf
[ "MIT" ]
null
null
null
third_party/SimpleDBus/src/base/Holder.cpp
HDPNC/brainflow
ede79fbd5fcc823c1c64bcc3af3e88b4d12177bf
[ "MIT" ]
null
null
null
#include <simpledbus/base/Holder.h> #include <iomanip> #include <iostream> #include <sstream> #include "dbus/dbus-protocol.h" using namespace SimpleDBus; Holder::Holder() {} Holder::~Holder() {} Holder::Type Holder::type() { return _type; } std::string Holder::_represent_simple() { std::ostringstream output; output << std::boolalpha; switch (_type) { case BOOLEAN: output << get_boolean(); break; case BYTE: output << (int)get_byte(); break; case INT16: output << (int)get_int16(); break; case UINT16: output << (int)get_uint16(); break; case INT32: output << get_int32(); break; case UINT32: output << get_uint32(); break; case INT64: output << get_int64(); break; case UINT64: output << get_uint64(); break; case DOUBLE: output << get_double(); break; case STRING: case OBJ_PATH: case SIGNATURE: output << get_string(); break; } return output.str(); } std::vector<std::string> Holder::_represent_container() { std::vector<std::string> output_lines; switch (_type) { case BOOLEAN: case BYTE: case INT16: case UINT16: case INT32: case UINT32: case INT64: case UINT64: case DOUBLE: case STRING: case OBJ_PATH: case SIGNATURE: output_lines.push_back(_represent_simple()); break; case ARRAY: { output_lines.push_back("Array:"); std::vector<std::string> additional_lines; if (holder_array.size() > 0 && holder_array[0]._type == BYTE) { // Dealing with an array of bytes, use custom print functionality. std::string temp_line = ""; for (int i = 0; i < holder_array.size(); i++) { // Represent each byte as a hex string std::stringstream stream; stream << std::setfill('0') << std::setw(2) << std::hex << ((int)holder_array[i].get_byte()); temp_line += (stream.str() + " "); if ((i + 1) % 32 == 0) { additional_lines.push_back(temp_line); temp_line = ""; } } additional_lines.push_back(temp_line); } else { for (int i = 0; i < holder_array.size(); i++) { for (auto& line : holder_array[i]._represent_container()) { additional_lines.push_back(line); } } } for (auto& line : additional_lines) { output_lines.push_back(" " + line); } break; } case DICT: output_lines.push_back("Dictionary:"); for (auto& [key_type_internal, key, value] : holder_dict) { output_lines.push_back(_represent_type(key_type_internal, key) + ":"); auto additional_lines = value._represent_container(); for (auto& line : additional_lines) { output_lines.push_back(" " + line); } } break; } return output_lines; } std::string Holder::represent() { std::ostringstream output; auto output_lines = _represent_container(); for (auto& output_line : output_lines) { output << output_line << std::endl; } return output.str(); } std::string Holder::_signature_simple() { switch (_type) { case BOOLEAN: return DBUS_TYPE_BOOLEAN_AS_STRING; case BYTE: return DBUS_TYPE_BYTE_AS_STRING; case INT16: return DBUS_TYPE_INT16_AS_STRING; case UINT16: return DBUS_TYPE_UINT16_AS_STRING; case INT32: return DBUS_TYPE_INT32_AS_STRING; case UINT32: return DBUS_TYPE_UINT32_AS_STRING; case INT64: return DBUS_TYPE_INT64_AS_STRING; case UINT64: return DBUS_TYPE_UINT64_AS_STRING; case DOUBLE: return DBUS_TYPE_DOUBLE_AS_STRING; case STRING: return DBUS_TYPE_STRING_AS_STRING; case OBJ_PATH: return DBUS_TYPE_OBJECT_PATH_AS_STRING; case SIGNATURE: return DBUS_TYPE_SIGNATURE_AS_STRING; } return ""; } std::string Holder::_signature_type(Type type) { switch (type) { case BOOLEAN: return DBUS_TYPE_BOOLEAN_AS_STRING; case BYTE: return DBUS_TYPE_BYTE_AS_STRING; case INT16: return DBUS_TYPE_INT16_AS_STRING; case UINT16: return DBUS_TYPE_UINT16_AS_STRING; case INT32: return DBUS_TYPE_INT32_AS_STRING; case UINT32: return DBUS_TYPE_UINT32_AS_STRING; case INT64: return DBUS_TYPE_INT64_AS_STRING; case UINT64: return DBUS_TYPE_UINT64_AS_STRING; case DOUBLE: return DBUS_TYPE_DOUBLE_AS_STRING; case STRING: return DBUS_TYPE_STRING_AS_STRING; case OBJ_PATH: return DBUS_TYPE_OBJECT_PATH_AS_STRING; case SIGNATURE: return DBUS_TYPE_SIGNATURE_AS_STRING; } return ""; } std::string Holder::_represent_type(Type type, std::any value) { std::ostringstream output; output << std::boolalpha; switch (type) { case BOOLEAN: output << std::any_cast<bool>(value); break; case BYTE: output << std::any_cast<uint8_t>(value); break; case INT16: output << std::any_cast<int16_t>(value); break; case UINT16: output << std::any_cast<uint16_t>(value); break; case INT32: output << std::any_cast<int32_t>(value); break; case UINT32: output << std::any_cast<uint32_t>(value); break; case INT64: output << std::any_cast<int64_t>(value); break; case UINT64: output << std::any_cast<uint64_t>(value); break; case DOUBLE: output << std::any_cast<double>(value); break; case STRING: case OBJ_PATH: case SIGNATURE: output << std::any_cast<std::string>(value); break; } return output.str(); } std::string Holder::signature() { std::string output; switch (_type) { case BOOLEAN: case BYTE: case INT16: case UINT16: case INT32: case UINT32: case INT64: case UINT64: case DOUBLE: case STRING: case OBJ_PATH: case SIGNATURE: output = _signature_simple(); break; case ARRAY: output = DBUS_TYPE_ARRAY_AS_STRING; if (holder_array.size() == 0) { output += DBUS_TYPE_VARIANT_AS_STRING; } else { // Check if all elements of holder_array are the same type auto first_type = holder_array[0]._type; bool all_same_type = true; for (auto& element : holder_array) { if (element._type != first_type) { all_same_type = false; break; } } if (all_same_type) { output += holder_array[0]._signature_simple(); } else { output += DBUS_TYPE_VARIANT_AS_STRING; } } break; case DICT: output = DBUS_TYPE_ARRAY_AS_STRING; output += DBUS_DICT_ENTRY_BEGIN_CHAR_AS_STRING; if (holder_dict.size() == 0) { output += DBUS_TYPE_STRING_AS_STRING; output += DBUS_TYPE_VARIANT_AS_STRING; } else { // Check if all keys of holder_dict are the same type auto first_key_type = std::get<0>(holder_dict[0]); bool all_same_key_type = true; for (auto& [key_type_internal, key, value] : holder_dict) { if (key_type_internal != first_key_type) { all_same_key_type = false; break; } } if (all_same_key_type) { output += _signature_type(first_key_type); } else { output += DBUS_TYPE_VARIANT_AS_STRING; } // Check if all values of holder_dict are the same type auto first_value_type = std::get<2>(holder_dict[0])._type; bool all_same_value_type = true; for (auto& [key_type_internal, key, value] : holder_dict) { if (value._type != first_value_type) { all_same_value_type = false; break; } } if (all_same_value_type) { output += std::get<2>(holder_dict[0])._signature_simple(); } else { output += DBUS_TYPE_VARIANT_AS_STRING; } } output += DBUS_DICT_ENTRY_END_CHAR_AS_STRING; break; } return output; } Holder Holder::create_byte(uint8_t value) { Holder h; h._type = BYTE; h.holder_integer = value; return h; } Holder Holder::create_boolean(bool value) { Holder h; h._type = BOOLEAN; h.holder_boolean = value; return h; } Holder Holder::create_int16(int16_t value) { Holder h; h._type = INT16; h.holder_integer = value; return h; } Holder Holder::create_uint16(uint16_t value) { Holder h; h._type = UINT16; h.holder_integer = value; return h; } Holder Holder::create_int32(int32_t value) { Holder h; h._type = INT32; h.holder_integer = value; return h; } Holder Holder::create_uint32(uint32_t value) { Holder h; h._type = UINT32; h.holder_integer = value; return h; } Holder Holder::create_int64(int64_t value) { Holder h; h._type = INT64; h.holder_integer = value; return h; } Holder Holder::create_uint64(uint64_t value) { Holder h; h._type = UINT64; h.holder_integer = value; return h; } Holder Holder::create_double(double value) { Holder h; h._type = DOUBLE; h.holder_double = value; return h; } Holder Holder::create_string(const char* str) { Holder h; h._type = STRING; h.holder_string = std::string(str); return h; } Holder Holder::create_object_path(const char* str) { Holder h; h._type = OBJ_PATH; h.holder_string = std::string(str); return h; } Holder Holder::create_signature(const char* str) { Holder h; h._type = SIGNATURE; h.holder_string = std::string(str); return h; } Holder Holder::create_array() { Holder h; h._type = ARRAY; h.holder_array.clear(); return h; } Holder Holder::create_dict() { Holder h; h._type = DICT; h.holder_dict.clear(); return h; } std::any Holder::get_contents() { // Only return the contents for simple types switch (_type) { case BOOLEAN: return get_boolean(); case BYTE: return get_byte(); case INT16: return get_int16(); case UINT16: return get_uint16(); case INT32: return get_int32(); case UINT32: return get_uint32(); case INT64: return get_int64(); case UINT64: return get_uint64(); case DOUBLE: return get_double(); case STRING: return get_string(); case OBJ_PATH: return get_object_path(); case SIGNATURE: return get_signature(); default: return std::any(); } } bool Holder::get_boolean() { return holder_boolean; } uint8_t Holder::get_byte() { return (uint8_t)(holder_integer & 0x00000000000000FFL); } int16_t Holder::get_int16() { return (int16_t)(holder_integer & 0x000000000000FFFFL); } uint16_t Holder::get_uint16() { return (uint16_t)(holder_integer & 0x000000000000FFFFL); } int32_t Holder::get_int32() { return (int32_t)(holder_integer & 0x00000000FFFFFFFFL); } uint32_t Holder::get_uint32() { return (uint32_t)(holder_integer & 0x00000000FFFFFFFFL); } int64_t Holder::get_int64() { return (int64_t)holder_integer; } uint64_t Holder::get_uint64() { return holder_integer; } double Holder::get_double() { return holder_double; } std::string Holder::get_string() { return holder_string; } std::string Holder::get_object_path() { return holder_string; } std::string Holder::get_signature() { return holder_string; } std::vector<Holder> Holder::get_array() { return holder_array; } std::map<uint8_t, Holder> Holder::get_dict_uint8() { return _get_dict<uint8_t>(BYTE); } std::map<uint16_t, Holder> Holder::get_dict_uint16() { return _get_dict<uint16_t>(UINT16); } std::map<uint32_t, Holder> Holder::get_dict_uint32() { return _get_dict<uint32_t>(UINT32); } std::map<uint64_t, Holder> Holder::get_dict_uint64() { return _get_dict<uint64_t>(UINT64); } std::map<int16_t, Holder> Holder::get_dict_int16() { return _get_dict<int16_t>(INT16); } std::map<int32_t, Holder> Holder::get_dict_int32() { return _get_dict<int32_t>(INT32); } std::map<int64_t, Holder> Holder::get_dict_int64() { return _get_dict<int64_t>(INT64); } std::map<std::string, Holder> Holder::get_dict_string() { return _get_dict<std::string>(STRING); } std::map<std::string, Holder> Holder::get_dict_object_path() { return _get_dict<std::string>(OBJ_PATH); } std::map<std::string, Holder> Holder::get_dict_signature() { return _get_dict<std::string>(SIGNATURE); } void Holder::array_append(Holder holder) { holder_array.push_back(holder); } void Holder::dict_append(Type key_type, std::any key, Holder value) { if (key.type() == typeid(const char*)) { key = std::string(std::any_cast<const char*>(key)); } // TODO : VALIDATE THAT THE SPECIFIED KEY TYPE IS CORRECT holder_dict.push_back(std::make_tuple(key_type, key, value)); } template <typename T> std::map<T, Holder> Holder::_get_dict(Type key_type) { std::map<T, Holder> output; for (auto& [key_type_internal, key, value] : holder_dict) { if (key_type_internal == key_type) { output[std::any_cast<T>(key)] = value; } } return output; }
29.947686
113
0.560736
[ "vector" ]
b9ee9ed2aac97c37d48bb63955f62a1f47f1b2fe
23,160
cpp
C++
arangod/Aql/OutputAqlItemRow.cpp
Mu-L/arangodb
a6bd3ccd6f622fab2a288d2e3a06ab8e338d3ec1
[ "BSL-1.0", "Apache-2.0" ]
null
null
null
arangod/Aql/OutputAqlItemRow.cpp
Mu-L/arangodb
a6bd3ccd6f622fab2a288d2e3a06ab8e338d3ec1
[ "BSL-1.0", "Apache-2.0" ]
null
null
null
arangod/Aql/OutputAqlItemRow.cpp
Mu-L/arangodb
a6bd3ccd6f622fab2a288d2e3a06ab8e338d3ec1
[ "BSL-1.0", "Apache-2.0" ]
null
null
null
//////////////////////////////////////////////////////////////////////////////// /// DISCLAIMER /// /// Copyright 2014-2021 ArangoDB GmbH, Cologne, Germany /// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany /// /// Licensed under the Apache License, Version 2.0 (the "License"); /// you may not use this file except in compliance with the License. /// You may obtain a copy of the License at /// /// http://www.apache.org/licenses/LICENSE-2.0 /// /// Unless required by applicable law or agreed to in writing, software /// distributed under the License is distributed on an "AS IS" BASIS, /// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. /// See the License for the specific language governing permissions and /// limitations under the License. /// /// Copyright holder is ArangoDB GmbH, Cologne, Germany /// /// @author Tobias Gödderz /// @author Michael Hackstein /// @author Heiko Kernbach /// @author Jan Christoph Uhde //////////////////////////////////////////////////////////////////////////////// /* The following conditions need to hold true, we need to add c++ tests for this. output.isFull() == output.numRowsLeft() > 0; output.numRowsLeft() <= output.allocatedRows() - output.numRowsWritten(); output.numRowsLeft() <= output.softLimit(); output.softLimit() <= output.hardLimit(); */ #include "OutputAqlItemRow.h" #include "Aql/AqlItemBlock.h" #include "Aql/AqlValue.h" #include "Aql/RegisterInfos.h" #include "Aql/ShadowAqlItemRow.h" #include "Basics/Exceptions.h" #include <velocypack/Builder.h> #include <velocypack/velocypack-aliases.h> using namespace arangodb; using namespace arangodb::aql; OutputAqlItemRow::OutputAqlItemRow(SharedAqlItemBlockPtr block, RegIdSet const& outputRegisters, RegIdFlatSetStack const& registersToKeep, RegIdFlatSet const& registersToClear, AqlCall clientCall, CopyRowBehavior copyRowBehavior) : _block(std::move(block)), _baseIndex(0), _lastBaseIndex(0), _inputRowCopied(false), _doNotCopyInputRow(copyRowBehavior == CopyRowBehavior::DoNotCopyInputRows), #ifdef ARANGODB_ENABLE_MAINTAINER_MODE _setBaseIndexNotUsed(true), #endif _allowSourceRowUninitialized(false), _lastSourceRow{CreateInvalidInputRowHint{}}, _numValuesWritten(0), _call(clientCall), _outputRegisters(outputRegisters), _registersToKeep(registersToKeep), _registersToClear(registersToClear) { #ifdef ARANGODB_ENABLE_MAINTAINER_MODE if (_block != nullptr) { for (auto const& reg : _outputRegisters) { TRI_ASSERT(reg.isConstRegister() || reg < _block->numRegisters()); } // the block must have enough columns for the registers of both data rows, // and all the different shadow row depths if (_doNotCopyInputRow) { // pass-through case, we won't use _registersToKeep for (auto const& reg : _registersToClear) { TRI_ASSERT(reg < _block->numRegisters()); } } else { // copying (non-pass-through) case, we won't use _registersToClear for (auto const& stackEntry : _registersToKeep) { for (auto const& reg : stackEntry) { TRI_ASSERT(reg < _block->numRegisters()); } } } } // We cannot create an output row if we still have unreported skipCount // in the call. TRI_ASSERT(_call.getSkipCount() == 0); #endif } bool OutputAqlItemRow::isInitialized() const noexcept { return _block != nullptr; } template<class ItemRowType> void OutputAqlItemRow::cloneValueInto(RegisterId registerId, ItemRowType const& sourceRow, AqlValue const& value) { bool mustDestroy = true; AqlValue clonedValue = value.clone(); AqlValueGuard guard{clonedValue, mustDestroy}; moveValueInto(registerId, sourceRow, guard); } template<class ItemRowType, class ValueType> void OutputAqlItemRow::moveValueWithoutRowCopy(RegisterId registerId, ValueType& value) { TRI_ASSERT(isOutputRegister(registerId)); // This is already implicitly asserted by isOutputRegister: TRI_ASSERT(registerId.isRegularRegister()); TRI_ASSERT(registerId < getNumRegisters()); TRI_ASSERT(_numValuesWritten < numRegistersToWrite()); TRI_ASSERT(block().getValueReference(_baseIndex, registerId).isNone()); if constexpr (std::is_same_v<std::decay_t<ValueType>, AqlValueGuard>) { block().setValue(_baseIndex, registerId, value.value()); value.steal(); } else if constexpr ( // all inlined values std::is_same_v<std::decay_t<ValueType>, AqlValueHintDouble> || std::is_same_v<std::decay_t<ValueType>, AqlValueHintInt> || std::is_same_v<std::decay_t<ValueType>, AqlValueHintUInt> || std::is_same_v<std::decay_t<ValueType>, AqlValueHintZero> || std::is_same_v<std::decay_t<ValueType>, AqlValueHintNone> || std::is_same_v<std::decay_t<ValueType>, AqlValueHintNull> || std::is_same_v<std::decay_t<ValueType>, AqlValueHintEmptyArray> || std::is_same_v<std::decay_t<ValueType>, AqlValueHintEmptyObject> || std::is_same_v<std::decay_t<ValueType>, AqlValueHintBool>) { block().emplaceValue(_baseIndex, registerId.value(), value); } else { static_assert(std::is_same_v<std::decay_t<ValueType>, VPackSlice>); block().emplaceValue(_baseIndex, registerId.value(), value); } _numValuesWritten++; } template<class ItemRowType, class ValueType> void OutputAqlItemRow::moveValueInto(RegisterId registerId, ItemRowType const& sourceRow, ValueType& value) { moveValueWithoutRowCopy<ItemRowType, ValueType>(registerId, value); // allValuesWritten() must be called only *after* moveValueWithoutRowCopy(), // because it increases _numValuesWritten. if (allValuesWritten()) { copyRow(sourceRow); } } void OutputAqlItemRow::consumeShadowRow(RegisterId registerId, ShadowAqlItemRow& sourceRow, AqlValueGuard& guard) { TRI_ASSERT(sourceRow.isRelevant()); moveValueWithoutRowCopy<ShadowAqlItemRow>(registerId, guard); TRI_ASSERT(allValuesWritten()); copyOrMoveRow<ShadowAqlItemRow, CopyOrMove::MOVE, AdaptRowDepth::DecreaseDepth>(sourceRow, false); TRI_ASSERT(produced()); block().makeDataRow(_baseIndex); } bool OutputAqlItemRow::reuseLastStoredValue(RegisterId registerId, InputAqlItemRow const& sourceRow) { TRI_ASSERT(isOutputRegister(registerId)); if (_lastBaseIndex == _baseIndex) { return false; } // Do not clone the value, we explicitly want to recycle it. AqlValue ref = block().getValue(_lastBaseIndex, registerId); // The initial row is still responsible AqlValueGuard guard{ref, false}; moveValueInto(registerId, sourceRow, guard); return true; } void OutputAqlItemRow::moveRow(ShadowAqlItemRow& sourceRow, bool ignoreMissing) { copyOrMoveRow<ShadowAqlItemRow, CopyOrMove::MOVE>(sourceRow, ignoreMissing); } template<class ItemRowType> void OutputAqlItemRow::copyRow(ItemRowType const& sourceRow, bool ignoreMissing) { copyOrMoveRow<ItemRowType const, CopyOrMove::COPY>(sourceRow, ignoreMissing); } template<class ItemRowType, OutputAqlItemRow::CopyOrMove copyOrMove, OutputAqlItemRow::AdaptRowDepth adaptRowDepth> void OutputAqlItemRow::copyOrMoveRow(ItemRowType& sourceRow, bool ignoreMissing) { // While violating the following asserted states would do no harm, the // implementation as planned should only copy a row after all values have // been set, and copyRow should only be called once. TRI_ASSERT(!_inputRowCopied); // We either have a shadowRow, or we need to have all values written TRI_ASSERT((std::is_same_v<ItemRowType, ShadowAqlItemRow>) || allValuesWritten()); if (_inputRowCopied) { _lastBaseIndex = _baseIndex; return; } // This may only be set if the input block is the same as the output block, // because it is passed through. if (_doNotCopyInputRow) { TRI_ASSERT(sourceRow.isInitialized()); #ifdef ARANGODB_ENABLE_MAINTAINER_MODE TRI_ASSERT(sourceRow.internalBlockIs(_block, _baseIndex)); #endif _inputRowCopied = true; memorizeRow(sourceRow); return; } doCopyOrMoveRow<ItemRowType, copyOrMove, adaptRowDepth>(sourceRow, ignoreMissing); } auto OutputAqlItemRow::fastForwardAllRows(InputAqlItemRow const& sourceRow, size_t rows) -> void { #ifdef ARANGODB_ENABLE_MAINTAINER_MODE TRI_ASSERT(sourceRow.internalBlockIs(_block, _baseIndex)); #endif TRI_ASSERT(_doNotCopyInputRow); TRI_ASSERT(_call.getLimit() >= rows); TRI_ASSERT(rows > 0); // We have the guarantee that we have all data in our block. // We only need to adjust internal indexes. #ifdef ARANGODB_ENABLE_MAINTAINER_MODE // Safely assert that the API is not missused. TRI_ASSERT(_baseIndex + rows <= _block->numRows()); for (size_t i = _baseIndex; i < _baseIndex + rows; ++i) { TRI_ASSERT(!_block->isShadowRow(i)); } #endif _baseIndex += rows; TRI_ASSERT(_baseIndex > 0); _lastBaseIndex = _baseIndex - 1; _lastSourceRow = InputAqlItemRow{_block, _lastBaseIndex}; _call.didProduce(rows); } void OutputAqlItemRow::copyBlockInternalRegister( InputAqlItemRow const& sourceRow, RegisterId input, RegisterId output) { // This method is only allowed if the block of the input row is the same as // the block of the output row! #ifdef ARANGODB_ENABLE_MAINTAINER_MODE TRI_ASSERT(sourceRow.internalBlockIs(_block, _baseIndex)); #endif TRI_ASSERT(isOutputRegister(output)); // This is already implicitly asserted by isOutputRegister: TRI_ASSERT(output < getNumRegisters()); TRI_ASSERT(_numValuesWritten < numRegistersToWrite()); TRI_ASSERT(block().getValueReference(_baseIndex, output).isNone()); AqlValue const& value = sourceRow.getValue(input); block().setValue(_baseIndex, output, value); _numValuesWritten++; // allValuesWritten() must be called only *after* _numValuesWritten was // increased. if (allValuesWritten()) { copyRow(sourceRow); } } size_t OutputAqlItemRow::numRowsWritten() const noexcept { #ifdef ARANGODB_ENABLE_MAINTAINER_MODE TRI_ASSERT(_setBaseIndexNotUsed); #endif // If the current line was fully written, the number of fully written rows // is the index plus one. if (produced()) { return _baseIndex + 1; } // If the current line was not fully written, the last one was, so the // number of fully written rows is (_baseIndex - 1) + 1. return _baseIndex; // Disregarding unsignedness, we could also write: // lastWrittenIndex = produced() // ? _baseIndex // : _baseIndex - 1; // return lastWrittenIndex + 1; } void OutputAqlItemRow::advanceRow() { TRI_ASSERT(produced()); TRI_ASSERT(allValuesWritten()); TRI_ASSERT(_inputRowCopied); if (!_block->isShadowRow(_baseIndex)) { // We have written a data row into the output. // Need to count it. _call.didProduce(1); } ++_baseIndex; _inputRowCopied = false; _numValuesWritten = 0; } void OutputAqlItemRow::toVelocyPack(velocypack::Options const* options, VPackBuilder& builder) { TRI_ASSERT(produced()); block().rowToSimpleVPack(_baseIndex, options, builder); } AqlCall::Limit OutputAqlItemRow::softLimit() const { return _call.softLimit; } AqlCall::Limit OutputAqlItemRow::hardLimit() const { return _call.hardLimit; } AqlCall const& OutputAqlItemRow::getClientCall() const { return _call; } AqlCall& OutputAqlItemRow::getModifiableClientCall() { return _call; } AqlCall&& OutputAqlItemRow::stealClientCall() { return std::move(_call); } void OutputAqlItemRow::setCall(AqlCall call) { // We cannot create an output row if we still have unreported skipCount // in the call. TRI_ASSERT(_call.getSkipCount() == 0); _call = std::move(call); } SharedAqlItemBlockPtr OutputAqlItemRow::stealBlock() { // numRowsWritten() inspects _block, so save this before resetting it! auto const numRows = numRowsWritten(); // Release our hold on the block now SharedAqlItemBlockPtr block = std::move(_block); if (numRows == 0) { // blocks may not be empty block = nullptr; } else { // numRowsWritten() returns the exact number of rows that were fully // written and takes into account whether the current row was written. block->shrink(numRows); if (!registersToClear().empty()) { block->clearRegisters(registersToClear()); } } return block; } void OutputAqlItemRow::setBaseIndex(std::size_t index) { #ifdef ARANGODB_ENABLE_MAINTAINER_MODE _setBaseIndexNotUsed = false; #endif _baseIndex = index; } void OutputAqlItemRow::setMaxBaseIndex(std::size_t index) { #ifdef ARANGODB_ENABLE_MAINTAINER_MODE _setBaseIndexNotUsed = true; #endif _baseIndex = index; } void OutputAqlItemRow::createShadowRow(InputAqlItemRow const& sourceRow) { TRI_ASSERT(!_inputRowCopied); // A shadow row can only be created on blocks that DO NOT write additional // output. This assertion is not a hard requirement and could be softened, but // it makes the logic much easier to understand, we have a shadow-row producer // that does not produce anything else. TRI_ASSERT(numRegistersToWrite() == 0); // This is the hard requirement, if we decide to remove the no-write policy. // This has te be in place. However no-write implies this. TRI_ASSERT(allValuesWritten()); TRI_ASSERT(sourceRow.isInitialized()); #ifdef ARANGODB_ENABLE_MAINTAINER_MODE // We can only add shadow rows if source and this are different blocks TRI_ASSERT(!sourceRow.internalBlockIs(_block, _baseIndex)); #endif block().makeShadowRow(_baseIndex, 0); doCopyOrMoveRow<InputAqlItemRow const, CopyOrMove::COPY, AdaptRowDepth::IncreaseDepth>(sourceRow, true); } void OutputAqlItemRow::increaseShadowRowDepth(ShadowAqlItemRow& sourceRow) { size_t newDepth = sourceRow.getDepth() + 1; doCopyOrMoveRow<ShadowAqlItemRow, CopyOrMove::MOVE, AdaptRowDepth::IncreaseDepth>(sourceRow, false); block().makeShadowRow(_baseIndex, newDepth); // We need to fake produced state _numValuesWritten = numRegistersToWrite(); TRI_ASSERT(produced()); } void OutputAqlItemRow::decreaseShadowRowDepth(ShadowAqlItemRow& sourceRow) { doCopyOrMoveRow<ShadowAqlItemRow, CopyOrMove::MOVE, AdaptRowDepth::DecreaseDepth>(sourceRow, false); TRI_ASSERT(!sourceRow.isRelevant()); TRI_ASSERT(sourceRow.getDepth() > 0); block().makeShadowRow(_baseIndex, sourceRow.getDepth() - 1); // We need to fake produced state _numValuesWritten = numRegistersToWrite(); TRI_ASSERT(produced()); } template<> void OutputAqlItemRow::memorizeRow<InputAqlItemRow>( InputAqlItemRow const& sourceRow) { _lastSourceRow = sourceRow; _lastBaseIndex = _baseIndex; } template<> void OutputAqlItemRow::memorizeRow<ShadowAqlItemRow>( ShadowAqlItemRow const& sourceRow) {} template<> bool OutputAqlItemRow::testIfWeMustClone<InputAqlItemRow>( InputAqlItemRow const& sourceRow) const { return _baseIndex == 0 || !_lastSourceRow.isSameBlockAndIndex(sourceRow); } template<> bool OutputAqlItemRow::testIfWeMustClone<ShadowAqlItemRow>( ShadowAqlItemRow const& sourceRow) const { return true; } template<> void OutputAqlItemRow::adjustShadowRowDepth<InputAqlItemRow>( InputAqlItemRow const& sourceRow) {} template<> void OutputAqlItemRow::adjustShadowRowDepth<ShadowAqlItemRow>( ShadowAqlItemRow const& sourceRow) { block().makeShadowRow(_baseIndex, sourceRow.getShadowDepthValue()); } template<class T> struct dependent_false : std::false_type {}; template<class ItemRowType, OutputAqlItemRow::CopyOrMove copyOrMove, OutputAqlItemRow::AdaptRowDepth adaptRowDepth> void OutputAqlItemRow::doCopyOrMoveRow(ItemRowType& sourceRow, bool ignoreMissing) { // Note that _lastSourceRow is invalid right after construction. However, when // _baseIndex > 0, then we must have seen one row already. TRI_ASSERT(!_doNotCopyInputRow); bool constexpr createShadowRow = adaptRowDepth == AdaptRowDepth::IncreaseDepth; bool mustClone = testIfWeMustClone(sourceRow) || createShadowRow; // Indexes (reversely) which entry in the registersToKeep() stack we need to // use. // Usually, for all InputAqlItemRows, it is zero, respectively the top of the // stack or the back of the vector. // Similarly, for all ShadowAqlItemRows, it is their respective shadow row // depth plus one. // The exceptions are SubqueryStart and SubqueryEnd nodes, where the depth // of all rows increases or decreases, respectively. In these cases, we have // to adapt the depth by plus one or minus one, respectively. static bool constexpr isShadowRow = std::is_same_v<std::decay_t<ItemRowType>, ShadowAqlItemRow>; size_t baseRowDepth = 0; if constexpr (isShadowRow) { baseRowDepth = sourceRow.getDepth() + 1; } auto constexpr delta = depthDelta(adaptRowDepth); size_t const rowDepth = baseRowDepth + delta; auto const roffset = rowDepth + 1; TRI_ASSERT(roffset <= registersToKeep().size()); auto idx = registersToKeep().size() - roffset; auto const& regsToKeep = registersToKeep().at(idx); if (mustClone) { for (auto const& itemId : regsToKeep) { #ifdef ARANGODB_ENABLE_MAINTAINER_MODE if (!_allowSourceRowUninitialized) { TRI_ASSERT(sourceRow.isInitialized()); } #endif TRI_ASSERT(itemId.isRegularRegister()); if (ignoreMissing && itemId.value() >= sourceRow.getNumRegisters()) { continue; } if (ADB_LIKELY(!_allowSourceRowUninitialized || sourceRow.isInitialized())) { doCopyOrMoveValue<ItemRowType, copyOrMove>(sourceRow, itemId); } } adjustShadowRowDepth(sourceRow); } else { TRI_ASSERT(_baseIndex > 0); if (ADB_LIKELY(!_allowSourceRowUninitialized || sourceRow.isInitialized())) { block().referenceValuesFromRow(_baseIndex, regsToKeep, _lastBaseIndex); } } _inputRowCopied = true; memorizeRow(sourceRow); } template<class ItemRowType, OutputAqlItemRow::CopyOrMove copyOrMove> void OutputAqlItemRow::doCopyOrMoveValue(ItemRowType& sourceRow, RegisterId itemId) { if constexpr (copyOrMove == CopyOrMove::COPY) { auto const& value = sourceRow.getValue(itemId); if (!value.isEmpty()) { AqlValue clonedValue = value.clone(); AqlValueGuard guard(clonedValue, true); TRI_IF_FAILURE("OutputAqlItemRow::copyRow") { THROW_ARANGO_EXCEPTION(TRI_ERROR_DEBUG); } TRI_IF_FAILURE("ExecutionBlock::inheritRegisters") { THROW_ARANGO_EXCEPTION(TRI_ERROR_DEBUG); } block().setValue(_baseIndex, itemId, clonedValue); guard.steal(); } } else if constexpr (copyOrMove == CopyOrMove::MOVE) { // This is only compiled for ShadowRows auto stolenValue = sourceRow.stealAndEraseValue(itemId); if (!stolenValue.isEmpty()) { AqlValueGuard guard(stolenValue, true); TRI_IF_FAILURE("OutputAqlItemRow::copyRow") { THROW_ARANGO_EXCEPTION(TRI_ERROR_DEBUG); } TRI_IF_FAILURE("ExecutionBlock::inheritRegisters") { THROW_ARANGO_EXCEPTION(TRI_ERROR_DEBUG); } block().setValue(_baseIndex, itemId, stolenValue); guard.steal(); } } else { static_assert(dependent_false<ItemRowType>::value, "Unhandled value"); } } auto constexpr OutputAqlItemRow::depthDelta(AdaptRowDepth adaptRowDepth) -> std::underlying_type_t<OutputAqlItemRow::AdaptRowDepth> { return static_cast<std::underlying_type_t<AdaptRowDepth>>(adaptRowDepth); } RegisterCount OutputAqlItemRow::getNumRegisters() const { return block().numRegisters(); } template void OutputAqlItemRow::copyRow<InputAqlItemRow>( InputAqlItemRow const& sourceRow, bool ignoreMissing); template void OutputAqlItemRow::copyRow<ShadowAqlItemRow>( ShadowAqlItemRow const& sourceRow, bool ignoreMissing); template void OutputAqlItemRow::cloneValueInto<InputAqlItemRow>( RegisterId registerId, const InputAqlItemRow& sourceRow, AqlValue const& value); template void OutputAqlItemRow::cloneValueInto<ShadowAqlItemRow>( RegisterId registerId, const ShadowAqlItemRow& sourceRow, AqlValue const& value); template void OutputAqlItemRow::moveValueInto<InputAqlItemRow, AqlValueGuard>( RegisterId registerId, InputAqlItemRow const& sourceRow, AqlValueGuard& guard); template void OutputAqlItemRow::moveValueInto<InputAqlItemRow, AqlValueHintBool const>( RegisterId registerId, InputAqlItemRow const& sourceRow, AqlValueHintBool const&); template void OutputAqlItemRow::moveValueInto<InputAqlItemRow, AqlValueHintDouble const>( RegisterId registerId, InputAqlItemRow const& sourceRow, AqlValueHintDouble const&); template void OutputAqlItemRow::moveValueInto<InputAqlItemRow, AqlValueHintInt const>( RegisterId registerId, InputAqlItemRow const& sourceRow, AqlValueHintInt const&); template void OutputAqlItemRow::moveValueInto<InputAqlItemRow, AqlValueHintUInt const>( RegisterId registerId, InputAqlItemRow const& sourceRow, AqlValueHintUInt const&); template void OutputAqlItemRow::moveValueInto<InputAqlItemRow, AqlValueHintZero const>( RegisterId registerId, InputAqlItemRow const& sourceRow, AqlValueHintZero const&); template void OutputAqlItemRow::moveValueInto<InputAqlItemRow, AqlValueHintNone const>( RegisterId registerId, InputAqlItemRow const& sourceRow, AqlValueHintNone const&); template void OutputAqlItemRow::moveValueInto<InputAqlItemRow, AqlValueHintNull const>( RegisterId registerId, InputAqlItemRow const& sourceRow, AqlValueHintNull const&); template void OutputAqlItemRow::moveValueInto<InputAqlItemRow, AqlValueHintEmptyArray const>( RegisterId registerId, InputAqlItemRow const& sourceRow, AqlValueHintEmptyArray const&); template void OutputAqlItemRow::moveValueInto<InputAqlItemRow, AqlValueHintEmptyObject const>( RegisterId registerId, InputAqlItemRow const& sourceRow, AqlValueHintEmptyObject const&); template void OutputAqlItemRow::moveValueInto<ShadowAqlItemRow, AqlValueGuard>( RegisterId registerId, ShadowAqlItemRow const& sourceRow, AqlValueGuard& guard); template void OutputAqlItemRow::moveValueInto<InputAqlItemRow, VPackSlice const>( RegisterId registerId, InputAqlItemRow const& sourceRow, VPackSlice const& guard); template void OutputAqlItemRow::moveValueInto<ShadowAqlItemRow, VPackSlice const>( RegisterId registerId, ShadowAqlItemRow const& sourceRow, VPackSlice const& guard);
37.415186
80
0.714249
[ "vector" ]
b9f3db21cb99b69c31f2c112b000180ff056b52b
1,650
hpp
C++
libs/MPILib/include/MiindTvbModelAbstract.hpp
dekamps/miind
4b321c62c2bd27eb0d5d8336a16a9e840ba63856
[ "MIT" ]
13
2015-09-15T17:28:25.000Z
2022-03-22T20:26:47.000Z
libs/MPILib/include/MiindTvbModelAbstract.hpp
dekamps/miind
4b321c62c2bd27eb0d5d8336a16a9e840ba63856
[ "MIT" ]
41
2015-08-25T07:50:55.000Z
2022-03-21T16:20:37.000Z
libs/MPILib/include/MiindTvbModelAbstract.hpp
dekamps/miind
4b321c62c2bd27eb0d5d8336a16a9e840ba63856
[ "MIT" ]
9
2015-09-14T20:52:07.000Z
2022-03-08T12:18:18.000Z
#include <vector> #include <boost/timer/timer.hpp> #include <GeomLib/GeomLib.hpp> #include <TwoDLib/TwoDLib.hpp> #include <MPILib/include/MPINetworkCode.hpp> #include <MPILib/include/RateAlgorithmCode.hpp> #include <MPILib/include/SimulationRunParameter.hpp> #include <MPILib/include/DelayAlgorithmCode.hpp> #include <MPILib/include/utilities/ProgressBar.hpp> #include <MPILib/include/BasicDefinitions.hpp> #include <MPILib/include/report/handler/AbstractReportHandler.hpp> #ifndef MPILIB_MIINDTVBMODELABSTRACT_HPP_ #define MPILIB_MIINDTVBMODELABSTRACT_HPP_ namespace MPILib { template<class Weight, class NodeDistribution> class MiindTvbModelAbstract { public: MiindTvbModelAbstract(int num_nodes, double simulation_length) : _num_nodes(num_nodes), _simulation_length(simulation_length){ } ~MiindTvbModelAbstract() { } virtual void init() {}; virtual void startSimulation() { pb = new utilities::ProgressBar(network.startSimulation()); } virtual std::vector<double> evolveSingleStep(std::vector<double> activity) { (*pb)++; return network.evolveSingleStep(activity); } virtual void endSimulation() { network.endSimulation(); t.stop(); t.report(); } double getTimeStep() { return _time_step; } double getSimulationLength() { return _simulation_length; } int getNumNodes() { return _num_nodes; } protected: MPINetwork<Weight, NodeDistribution> network; report::handler::AbstractReportHandler *report_handler; boost::timer::auto_cpu_timer t; utilities::ProgressBar *pb; double _simulation_length; // ms double _time_step; // ms int _num_nodes; }; } #endif // MPILIB_MIINDTVBMODELABSTRACT_HPP_
23.239437
77
0.774545
[ "vector" ]
b9f43089dd7e4a1aa2cb3aa944881de89485bfdb
1,930
cpp
C++
ablateLibrary/monitors/hdf5Monitor.cpp
pakserep/ablate
8c8443de8a252b03b3535f7c48b7a50aac1e56e4
[ "BSD-3-Clause" ]
null
null
null
ablateLibrary/monitors/hdf5Monitor.cpp
pakserep/ablate
8c8443de8a252b03b3535f7c48b7a50aac1e56e4
[ "BSD-3-Clause" ]
null
null
null
ablateLibrary/monitors/hdf5Monitor.cpp
pakserep/ablate
8c8443de8a252b03b3535f7c48b7a50aac1e56e4
[ "BSD-3-Clause" ]
null
null
null
#include "hdf5Monitor.hpp" #include <petscviewerhdf5.h> #include <environment/runEnvironment.hpp> #include "generators.hpp" #include "utilities/petscError.hpp" ablate::monitors::Hdf5Monitor::~Hdf5Monitor() { if (petscViewer) { PetscViewerDestroy(&petscViewer) >> checkError; } // If this is the root process generate the xdmf file int rank; MPI_Comm_rank(PETSC_COMM_WORLD, &rank); if (rank == 0 && !outputFilePath.empty() && std::filesystem::exists(outputFilePath)) { petscXdmfGenerator::Generate(outputFilePath); } } void ablate::monitors::Hdf5Monitor::Register(std::shared_ptr<Monitorable> object) { // cast the object and check if it is viewable viewableObject = std::dynamic_pointer_cast<Viewable>(object); // build the file name outputFilePath = environment::RunEnvironment::Get().GetOutputDirectory() / (viewableObject->GetName() + extension); // setup the petsc viewer PetscViewerHDF5Open(PETSC_COMM_WORLD, outputFilePath.string().c_str(), FILE_MODE_WRITE, &petscViewer) >> checkError; } PetscErrorCode ablate::monitors::Hdf5Monitor::OutputHdf5(TS ts, PetscInt steps, PetscReal time, Vec u, void *mctx) { PetscFunctionBeginUser; auto monitor = (ablate::monitors::Hdf5Monitor *)mctx; auto monitorObject = monitor->viewableObject; if (steps == 0 || monitor->interval == 0 || (steps % monitor->interval == 0)) try { monitorObject->View(monitor->petscViewer, steps, time, u); } catch (std::exception &e) { SETERRQ(PETSC_COMM_SELF, PETSC_ERR_LIB, e.what()); } PetscFunctionReturn(0); } ablate::monitors::Hdf5Monitor::Hdf5Monitor(int interval) : interval(interval) {} #include "parser/registrar.hpp" REGISTER(ablate::monitors::Monitor, ablate::monitors::Hdf5Monitor, "writes the viewable object to an hdf5", ARG(int, "interval", "how often to write the HDF5 file (default is every timestep)"));
42.888889
194
0.70829
[ "object" ]
b9f52f1a7069c456c3f30824702ec9a14a15a2ae
1,967
cpp
C++
src/tools.cpp
aliasaswad/CarND-Extended-Kalman-Filter-P5
fd61964c8afea8c7d7823cc562b45bcfd7654c8a
[ "MIT" ]
null
null
null
src/tools.cpp
aliasaswad/CarND-Extended-Kalman-Filter-P5
fd61964c8afea8c7d7823cc562b45bcfd7654c8a
[ "MIT" ]
null
null
null
src/tools.cpp
aliasaswad/CarND-Extended-Kalman-Filter-P5
fd61964c8afea8c7d7823cc562b45bcfd7654c8a
[ "MIT" ]
null
null
null
#include "tools.h" #include <iostream> using Eigen::VectorXd; using Eigen::MatrixXd; using std::vector; using std::cout; using std::endl; Tools::Tools() {} Tools::~Tools() {} VectorXd Tools::CalculateRMSE(const vector<VectorXd> &estimations, const vector<VectorXd> &ground_truth) { /** *Calculate the RMSE here. */ VectorXd rmse(4); rmse << 0,0,0,0; if(estimations.size() == 0){ cout << "ERROR: CalculateRMSE-Est. vec. is empty" << endl; return rmse; } if(ground_truth.size() == 0){ cout << "ERROR: CalculateRMSE-Grnd-truth vec. is empty" << endl; return rmse; } unsigned int est_size = estimations.size(); if(est_size != ground_truth.size()){ cout << "ERROR: CalculateRMSE-Grnd-truth & est. vec. must be same size." << endl; return rmse; } for(unsigned int i=0; i < estimations.size(); ++i){ VectorXd diff = estimations[i] - ground_truth[i]; diff = diff.array()*diff.array(); rmse += diff; } rmse = rmse / est_size; rmse = rmse.array().sqrt(); return rmse; } MatrixXd Tools::CalculateJacobian(const VectorXd& x_state) { /** * Calculate a Jacobian here. */ MatrixXd Jac(3,4); if(x_state.size() != 4) { cout << "ERROR: CalculateJacobian-State vec. must be size 4." << endl; return Jac; } //Recover state parameters double px = x_state(0); double py = x_state(1); double vx = x_state(2); double vy = x_state(3); //Precompute a set of terms to avoid repeated calculation double c1 = px*px+py*py; double c2 = sqrt(c1); double c3 = (c1*c2); //check division by zero if(fabs(c1) < 0.0001){ cout << "ERROR: CalculateJacobian()-Division by Zero" << endl; return Jac; } //compute the Jacobian matrix Jac << (px/c2) , (py/c2) , 0 , 0, -(py/c1) , (px/c1) , 0 , 0, py*(vx*py - vy*px)/c3, px*(px*vy - py*vx)/c3, px/c2 , py/c2; return Jac; }
24.283951
85
0.591764
[ "vector" ]
b9f726d352fa646a0a054cea22c22d3099395b26
15,265
cxx
C++
Base/QTGUI/qSlicerIOManager.cxx
TheInterventionCentre/NorMIT-Plan-App
765ed9a5dccc1cc134b65ccabe93fc132baeb2ea
[ "MIT" ]
null
null
null
Base/QTGUI/qSlicerIOManager.cxx
TheInterventionCentre/NorMIT-Plan-App
765ed9a5dccc1cc134b65ccabe93fc132baeb2ea
[ "MIT" ]
null
null
null
Base/QTGUI/qSlicerIOManager.cxx
TheInterventionCentre/NorMIT-Plan-App
765ed9a5dccc1cc134b65ccabe93fc132baeb2ea
[ "MIT" ]
null
null
null
/// Qt includes #include <QDebug> #include <QDragEnterEvent> #include <QDropEvent> #include <QFileDialog> #include <QInputDialog> #include <QMetaProperty> #include <QProgressDialog> #include <QSettings> // CTK includes #include "ctkScreenshotDialog.h" /// SlicerQt includes #include "qSlicerIOManager.h" #include "qSlicerDataDialog.h" #include "qSlicerModelsDialog.h" #include "qSlicerSaveDataDialog.h" #include "qSlicerApplication.h" #include "qSlicerLayoutManager.h" #include "qSlicerModuleManager.h" #include "qSlicerAbstractCoreModule.h" /// MRML includes #include <vtkMRMLNode.h> #include <vtkMRMLScene.h> /// VTK includes #include <vtkCollection.h> //----------------------------------------------------------------------------- class qSlicerIOManagerPrivate { Q_DECLARE_PUBLIC(qSlicerIOManager); protected: qSlicerIOManager* const q_ptr; public: qSlicerIOManagerPrivate(qSlicerIOManager& object); vtkMRMLScene* currentScene()const; /// Return true if a dialog is created, false if a dialog already existed bool startProgressDialog(int steps = 1); void stopProgressDialog(); void readSettings(); void writeSettings(); QString createUniqueDialogName(qSlicerIO::IOFileType, qSlicerFileDialog::IOAction, const qSlicerIO::IOProperties&); qSlicerFileDialog* findDialog(qSlicerIO::IOFileType fileType, qSlicerFileDialog::IOAction)const; QStringList History; QList<QUrl> Favorites; QList<qSlicerFileDialog*> ReadDialogs; QList<qSlicerFileDialog*> WriteDialogs; QSharedPointer<ctkScreenshotDialog> ScreenshotDialog; QProgressDialog* ProgressDialog; }; //----------------------------------------------------------------------------- // qSlicerIOManagerPrivate methods //----------------------------------------------------------------------------- qSlicerIOManagerPrivate::qSlicerIOManagerPrivate(qSlicerIOManager& object) :q_ptr(&object) { this->ProgressDialog = 0; } //----------------------------------------------------------------------------- vtkMRMLScene* qSlicerIOManagerPrivate::currentScene()const { return qSlicerCoreApplication::application()->mrmlScene(); } //----------------------------------------------------------------------------- bool qSlicerIOManagerPrivate::startProgressDialog(int steps) { Q_Q(qSlicerIOManager); if (this->ProgressDialog) { return false; } int max = (steps != 1 ? steps : 100); this->ProgressDialog = new QProgressDialog("Loading file... ", "Cancel", 0, max); this->ProgressDialog->setWindowTitle(QString("Loading ...")); if (steps == 1) { // We only support cancelling a load action if we can have control over it this->ProgressDialog->setCancelButton(0); } this->ProgressDialog->setWindowModality(Qt::WindowModal); this->ProgressDialog->setMinimumDuration(1000); this->ProgressDialog->setValue(0); if (steps == 1) { q->qvtkConnect(qSlicerCoreApplication::application()->mrmlScene(), vtkMRMLScene::NodeAddedEvent, q, SLOT(updateProgressDialog())); } return true; } //----------------------------------------------------------------------------- void qSlicerIOManagerPrivate::stopProgressDialog() { Q_Q(qSlicerIOManager); if (!this->ProgressDialog) { return; } this->ProgressDialog->setValue(this->ProgressDialog->maximum()); q->qvtkDisconnect(qSlicerCoreApplication::application()->mrmlScene(), vtkMRMLScene::NodeAddedEvent, q, SLOT(updateProgressDialog())); delete this->ProgressDialog; this->ProgressDialog = 0; } //----------------------------------------------------------------------------- void qSlicerIOManagerPrivate::readSettings() { QSettings settings; settings.beginGroup("ioManager"); if (!settings.value("favoritesPaths").toList().isEmpty()) { foreach (const QString& varUrl, settings.value("favoritesPaths").toStringList()) { this->Favorites << QUrl(varUrl); } } else { this->Favorites << QUrl::fromLocalFile(QDir::homePath()); } settings.endGroup(); } //----------------------------------------------------------------------------- void qSlicerIOManagerPrivate::writeSettings() { Q_Q(qSlicerIOManager); QSettings settings; settings.beginGroup("ioManager"); QStringList list; foreach (const QUrl& url, q->favorites()) { list << url.toString(); } settings.setValue("favoritesPaths", QVariant(list)); settings.endGroup(); } //----------------------------------------------------------------------------- QString qSlicerIOManagerPrivate:: createUniqueDialogName(qSlicerIO::IOFileType fileType, qSlicerFileDialog::IOAction action, const qSlicerIO::IOProperties& ioProperties) { QString objectName; objectName += action == qSlicerFileDialog::Read ? "Add" : "Save"; objectName += fileType; objectName += ioProperties["multipleFiles"].toBool() ? "s" : ""; objectName += "Dialog"; return objectName; } //----------------------------------------------------------------------------- qSlicerFileDialog* qSlicerIOManagerPrivate ::findDialog(qSlicerIO::IOFileType fileType, qSlicerFileDialog::IOAction action)const { const QList<qSlicerFileDialog*>& dialogs = (action == qSlicerFileDialog::Read)? this->ReadDialogs : this->WriteDialogs; foreach(qSlicerFileDialog* dialog, dialogs) { if (dialog->fileType() == fileType) { return dialog; } } return 0; } //----------------------------------------------------------------------------- // qSlicerIOManager methods //----------------------------------------------------------------------------- qSlicerIOManager::qSlicerIOManager(QObject* _parent):Superclass(_parent) , d_ptr(new qSlicerIOManagerPrivate(*this)) { Q_D(qSlicerIOManager); d->readSettings(); } //----------------------------------------------------------------------------- qSlicerIOManager::~qSlicerIOManager() { Q_D(qSlicerIOManager); d->writeSettings(); } //----------------------------------------------------------------------------- bool qSlicerIOManager::openLoadSceneDialog() { qSlicerIO::IOProperties properties; properties["clear"] = true; return this->openDialog(QString("SceneFile"), qSlicerFileDialog::Read, properties); } //----------------------------------------------------------------------------- bool qSlicerIOManager::openAddSceneDialog() { qSlicerIO::IOProperties properties; properties["clear"] = false; return this->openDialog(QString("SceneFile"), qSlicerFileDialog::Read, properties); } //----------------------------------------------------------------------------- bool qSlicerIOManager::openDialog(qSlicerIO::IOFileType fileType, qSlicerFileDialog::IOAction action, qSlicerIO::IOProperties properties, vtkCollection* loadedNodes) { Q_D(qSlicerIOManager); bool deleteDialog = false; if (properties["objectName"].toString().isEmpty()) { QString name = d->createUniqueDialogName(fileType, action, properties); properties["objectName"] = name; } qSlicerFileDialog* dialog = d->findDialog(fileType, action); if (dialog == 0) { deleteDialog = true; qSlicerStandardFileDialog* standardDialog = new qSlicerStandardFileDialog(this); standardDialog->setFileType(fileType); standardDialog->setAction(action); dialog = standardDialog; } bool res = dialog->exec(properties); if (loadedNodes) { foreach(const QString& nodeID, dialog->loadedNodes()) { vtkMRMLNode* node = d->currentScene()->GetNodeByID(nodeID.toLatin1()); if (node) { loadedNodes->AddItem(node); } } } if (deleteDialog) { delete dialog; } return res; } //--------------------------------------------------------------------------- void qSlicerIOManager::dragEnterEvent(QDragEnterEvent *event) { Q_D(qSlicerIOManager); foreach(qSlicerFileDialog* dialog, d->ReadDialogs) { if (dialog->isMimeDataAccepted(event->mimeData())) { event->accept(); break; } } } //----------------------------------------------------------------------------- void qSlicerIOManager::dropEvent(QDropEvent *event) { Q_D(qSlicerIOManager); QStringList supportedReaders; QStringList genericReaders; // those must be last in the choice menu foreach(qSlicerFileDialog* dialog, d->ReadDialogs) { if (dialog->isMimeDataAccepted(event->mimeData())) { QString supportedReader = dialog->description(); if (dialog->fileType() == "NoFile") { genericReaders << supportedReader; } else { supportedReaders << supportedReader; } } } supportedReaders << genericReaders; QString selectedReader; if (supportedReaders.size() > 1) { QString title = tr("Select a reader"); QString label = tr("Select a reader to use for your data?"); int current = 0; bool editable = false; bool ok = false; selectedReader = QInputDialog::getItem(0, title, label, supportedReaders, current, editable, &ok); if (!ok) { selectedReader = QString(); } } else if (supportedReaders.size() ==1) { selectedReader = supportedReaders[0]; } if (selectedReader.isEmpty()) { return; } foreach(qSlicerFileDialog* dialog, d->ReadDialogs) { if (dialog->description() == selectedReader) { dialog->dropEvent(event); if (event->isAccepted()) { dialog->exec(); break; } } } } //----------------------------------------------------------------------------- void qSlicerIOManager::addHistory(const QString& path) { Q_D(qSlicerIOManager); d->History << path; } //----------------------------------------------------------------------------- const QStringList& qSlicerIOManager::history()const { Q_D(const qSlicerIOManager); return d->History; } //----------------------------------------------------------------------------- void qSlicerIOManager::setFavorites(const QList<QUrl>& urls) { Q_D(qSlicerIOManager); QList<QUrl> newFavorites; foreach(const QUrl& url, urls) { newFavorites << url; } d->Favorites = newFavorites; } //----------------------------------------------------------------------------- const QList<QUrl>& qSlicerIOManager::favorites()const { Q_D(const qSlicerIOManager); return d->Favorites; } //----------------------------------------------------------------------------- void qSlicerIOManager::registerDialog(qSlicerFileDialog* dialog) { Q_D(qSlicerIOManager); Q_ASSERT(dialog); qSlicerFileDialog* existingDialog = d->findDialog(dialog->fileType(), dialog->action()); if (existingDialog) { d->ReadDialogs.removeAll(existingDialog); d->WriteDialogs.removeAll(existingDialog); existingDialog->deleteLater(); } if (dialog->action() == qSlicerFileDialog::Read) { d->ReadDialogs.prepend(dialog); } else if (dialog->action() == qSlicerFileDialog::Write) { d->WriteDialogs.prepend(dialog); } else { Q_ASSERT(dialog->action() == qSlicerFileDialog::Read || dialog->action() == qSlicerFileDialog::Write); } dialog->setParent(this); } //----------------------------------------------------------------------------- bool qSlicerIOManager::loadNodes(const qSlicerIO::IOFileType& fileType, const qSlicerIO::IOProperties& parameters, vtkCollection* loadedNodes) { Q_D(qSlicerIOManager); bool needStop = d->startProgressDialog(1); d->ProgressDialog->setLabelText( "Loading file " + parameters.value("fileName").toString() + " ..."); if (needStop) { d->ProgressDialog->setValue(25); } bool res = this->qSlicerCoreIOManager::loadNodes(fileType, parameters, loadedNodes); if (needStop) { d->stopProgressDialog(); } return res; } //----------------------------------------------------------------------------- bool qSlicerIOManager::loadNodes(const QList<qSlicerIO::IOProperties>& files, vtkCollection* loadedNodes) { Q_D(qSlicerIOManager); bool needStop = d->startProgressDialog(files.count()); bool res = true; foreach(qSlicerIO::IOProperties fileProperties, files) { res = this->loadNodes( static_cast<qSlicerIO::IOFileType>(fileProperties["fileType"].toString()), fileProperties, loadedNodes) && res; this->updateProgressDialog(); if (d->ProgressDialog->wasCanceled()) { res = false; break; } } if (needStop) { d->stopProgressDialog(); } return res; } //----------------------------------------------------------------------------- void qSlicerIOManager::updateProgressDialog() { Q_D(qSlicerIOManager); if (!d->ProgressDialog) { return; } int progress = d->ProgressDialog->value(); d->ProgressDialog->setValue(qMin(progress + 1, d->ProgressDialog->maximum() - 1) ); // Give time to process graphic events including the progress dialog if needed // TBD: Not needed ? //qApp->processEvents(); } //----------------------------------------------------------------------------- void qSlicerIOManager::openScreenshotDialog() { Q_D(qSlicerIOManager); // try opening the Annotation module's screen shot qSlicerModuleManager *moduleManager = qSlicerApplication::application()->moduleManager(); qSlicerAbstractCoreModule *modulePointer = NULL; if (moduleManager) { modulePointer = moduleManager->module("Annotations"); } if (modulePointer) { QMetaObject::invokeMethod(modulePointer, "showScreenshotDialog"); } else { qWarning() << "qSlicerIOManager::openScreenshotDialog: Unable to get Annotations module (annotations), using the CTK screen shot dialog."; // use the ctk one if (!d->ScreenshotDialog) { d->ScreenshotDialog = QSharedPointer<ctkScreenshotDialog>( new ctkScreenshotDialog()); d->ScreenshotDialog->setWidgetToGrab( qSlicerApplication::application()->layoutManager()->viewport()); } d->ScreenshotDialog->show(); } } //----------------------------------------------------------------------------- void qSlicerIOManager::openSceneViewsDialog() { // Q_D(qSlicerIOManager); qSlicerModuleManager *moduleManager = qSlicerApplication::application()->moduleManager(); if (!moduleManager) { qWarning() << "qSlicerIOManager::openSceneViewsDialog: unable to get module manager, can't get at the Scene Views module"; return; } qSlicerAbstractCoreModule *modulePointer = moduleManager->module("SceneViews"); if (modulePointer == NULL) { qWarning() << "qSlicerIOManager::openSceneViewsDialog: Unable to get at the SceneViews module (sceneviews)."; return; } QMetaObject::invokeMethod(modulePointer, "showSceneViewDialog"); }
28.965844
142
0.572355
[ "object" ]
b9fa2742e7256f77fe0f8500997830cfdbb391cf
5,847
cpp
C++
src_code/AdvancedQt/pagedesigner1/boxitem.cpp
yanrong/book_demo
20cd13f3c3507a11e826ebbf22bd1c7bcb36e06f
[ "Apache-2.0" ]
null
null
null
src_code/AdvancedQt/pagedesigner1/boxitem.cpp
yanrong/book_demo
20cd13f3c3507a11e826ebbf22bd1c7bcb36e06f
[ "Apache-2.0" ]
null
null
null
src_code/AdvancedQt/pagedesigner1/boxitem.cpp
yanrong/book_demo
20cd13f3c3507a11e826ebbf22bd1c7bcb36e06f
[ "Apache-2.0" ]
null
null
null
/* Copyright (c) 2009-10 Qtrac Ltd. All rights reserved. This program or module is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. It is provided for educational purposes and 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. */ #include "alt_key.hpp" #include "aqp.hpp" #include "boxitem.hpp" #include "global.hpp" #include <QGraphicsScene> #include <QGraphicsSceneMouseEvent> #include <QKeyEvent> BoxItem::BoxItem(const QRect &rect_, QGraphicsScene *scene) : QObject(), QGraphicsRectItem(), m_resizing(false), m_angle(0.0), m_shearHorizontal(0.0), m_shearVertical(0.0) { setFlags(QGraphicsItem::ItemIsSelectable| #if QT_VERSION >= 0x040600 QGraphicsItem::ItemSendsGeometryChanges| #endif QGraphicsItem::ItemIsMovable| QGraphicsItem::ItemIsFocusable); setPos(rect_.center()); setRect(QRectF(QPointF(-rect_.width() / 2.0, -rect_.height() / 2.0), rect_.size())); scene->clearSelection(); scene->addItem(this); setSelected(true); setFocus(); } void BoxItem::setPen(const QPen &pen_) { if (isSelected() && pen_ != pen()) { QGraphicsRectItem::setPen(pen_); emit dirty(); } } void BoxItem::setBrush(const QBrush &brush_) { if (isSelected() && brush_ != brush()) { QGraphicsRectItem::setBrush(brush_); emit dirty(); } } void BoxItem::setAngle(double angle) { if (isSelected() && !qFuzzyCompare(m_angle, angle)) { m_angle = angle; updateTransform(); } } void BoxItem::setShear(double shearHorizontal, double shearVertical) { if (isSelected() && (!qFuzzyCompare(m_shearHorizontal, shearHorizontal) || !qFuzzyCompare(m_shearVertical, shearVertical))) { m_shearHorizontal = shearHorizontal; m_shearVertical = shearVertical; updateTransform(); } } void BoxItem::updateTransform() { QTransform transform; transform.shear(m_shearHorizontal, m_shearVertical); transform.rotate(m_angle); setTransform(transform); } QVariant BoxItem::itemChange(GraphicsItemChange change, const QVariant &value) { if (isDirtyChange(change)) emit dirty(); return QGraphicsRectItem::itemChange(change, value); } void BoxItem::keyPressEvent(QKeyEvent *event) { if (event->modifiers() & Qt::ShiftModifier || event->modifiers() & Qt::ControlModifier) { bool move = event->modifiers() & Qt::ControlModifier; bool changed = true; double dx1 = 0.0; double dy1 = 0.0; double dx2 = 0.0; double dy2 = 0.0; switch (event->key()) { case Qt::Key_Left: if (move) dx1 = -1.0; dx2 = -1.0; break; case Qt::Key_Right: if (move) dx1 = 1.0; dx2 = 1.0; break; case Qt::Key_Up: if (move) dy1 = -1.0; dy2 = -1.0; break; case Qt::Key_Down: if (move) dy1 = 1.0; dy2 = 1.0; break; default: changed = false; } if (changed) { setRect(rect().adjusted(dx1, dy1, dx2, dy2)); event->accept(); emit dirty(); return; } } QGraphicsRectItem::keyPressEvent(event); } void BoxItem::mousePressEvent(QGraphicsSceneMouseEvent *event) { if (event->modifiers() & Qt::ShiftModifier) { m_resizing = true; setCursor(Qt::SizeAllCursor); } else QGraphicsRectItem::mousePressEvent(event); } void BoxItem::mouseMoveEvent(QGraphicsSceneMouseEvent *event) { if (m_resizing) { #ifdef ALTERNATIVE_RESIZING qreal dx = event->pos().x() - event->lastPos().x(); qreal dy = event->pos().y() - event->lastPos().y(); setRect(rect().adjusted(0, 0, dx, dy).normalized()); #else QRectF rectangle(rect()); if (event->pos().x() < rectangle.x()) rectangle.setBottomLeft(event->pos()); else rectangle.setBottomRight(event->pos()); setRect(rectangle); #endif scene()->update(); } else QGraphicsRectItem::mouseMoveEvent(event); } void BoxItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) { if (m_resizing) { m_resizing = false; setCursor(Qt::ArrowCursor); emit dirty(); } else QGraphicsRectItem::mouseReleaseEvent(event); } QDataStream &operator<<(QDataStream &out, const BoxItem &boxItem) { out << boxItem.pos() << boxItem.angle() << boxItem.shearHorizontal() << boxItem.shearVertical() << boxItem.zValue() << boxItem.rect() << boxItem.pen() << boxItem.brush(); return out; } QDataStream &operator>>(QDataStream &in, BoxItem &boxItem) { QPointF position; double angle; double shearHorizontal; double shearVertical; double z; QRectF rect; QPen pen; QBrush brush; in >> position >> angle >> shearHorizontal >> shearVertical >> z >> rect >> pen >> brush; boxItem.setPos(position); boxItem.setAngle(angle); boxItem.setShear(shearHorizontal, shearVertical); boxItem.setZValue(z); boxItem.setRect(rect); boxItem.setPen(pen); boxItem.setBrush(brush); return in; }
26.457014
72
0.596374
[ "transform" ]
b9fb03fbb243bead03600b5aa07b7daa208a799f
112,931
cpp
C++
ToolSrc/cximage600_full_3/demo/demoDoc.cpp
openlastchaos/lastchaos-source-client
3d88594dba7347b1bb45378136605e31f73a8555
[ "Apache-2.0" ]
1
2022-02-14T15:46:44.000Z
2022-02-14T15:46:44.000Z
ToolSrc/cximage600_full_3/demo/demoDoc.cpp
openlastchaos/lastchaos-source-client
3d88594dba7347b1bb45378136605e31f73a8555
[ "Apache-2.0" ]
null
null
null
ToolSrc/cximage600_full_3/demo/demoDoc.cpp
openlastchaos/lastchaos-source-client
3d88594dba7347b1bb45378136605e31f73a8555
[ "Apache-2.0" ]
2
2022-01-10T22:17:06.000Z
2022-01-17T09:34:08.000Z
// demoDoc.cpp : implementation of the CDemoDoc class // #include "stdafx.h" #include "demo.h" #include "MainFrm.h" #include "demoDoc.h" #include "demoView.h" #include "DlgRotate.h" #include "DlgResample.h" #include "DlgDecBpp.h" #include "DlgIncBpp.h" #include "DlgOptions.h" #include "DlgDither.h" #include "DlgThreshold.h" #include "DlgColorize.h" #include "Quantize.h" #include "DlgOpacity.h" #include "DlgGamma.h" #include "DlgPalette.h" #include "DlgCombine.h" #include "DlgFFT.h" #include "DlgRepair.h" #include "DlgText.h" #include "DlgMix.h" #include "DlgSkew.h" #include "DlgJpeg.h" #include "DlgDataExt.h" #include "DlgCustomFilter.h" #include "DlgExpand.h" #include "DlgFloodFill.h" #include "DlgShadow.h" #include "ximage.h" #include <math.h> #include <process.h> extern DlgDataExtInfo dlgDataExtInfos; #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ////////////////////////////////////////////////////////////////////////////// // CDemoDoc IMPLEMENT_DYNCREATE(CDemoDoc, CDocument) BEGIN_MESSAGE_MAP(CDemoDoc, CDocument) //{{AFX_MSG_MAP(CDemoDoc) ON_UPDATE_COMMAND_UI(ID_FILE_SAVE_AS, OnUpdateFileSaveAs) ON_UPDATE_COMMAND_UI(ID_FILE_SAVE, OnUpdateFileSave) ON_COMMAND(ID_STRETCH_MODE, OnStretchMode) ON_UPDATE_COMMAND_UI(ID_STRETCH_MODE, OnUpdateStretchMode) ON_COMMAND(ID_TRANSFORM_ELLIPSE, OnTransformEllipse) ON_COMMAND(ID_WINDOW_DUPLICATE, OnWindowDuplicate) ON_COMMAND(ID_EDIT_COPY, OnEditCopy) ON_COMMAND(ID_CXIMAGE_FLIP, OnCximageFlip) ON_COMMAND(ID_CXIMAGE_MIRROR, OnCximageMirror) ON_COMMAND(ID_CXIMAGE_NEGATIVE, OnCximageNegative) ON_COMMAND(ID_CXIMAGE_GRAYSCALE, OnCximageGrayscale) ON_COMMAND(ID_CXIMAGE_ROTATE, OnCximageRotate) ON_UPDATE_COMMAND_UI(ID_EDIT_UNDO, OnUpdateEditUndo) ON_COMMAND(ID_EDIT_REDO, OnEditRedo) ON_COMMAND(ID_EDIT_UNDO, OnEditUndo) ON_UPDATE_COMMAND_UI(ID_EDIT_REDO, OnUpdateEditRedo) ON_COMMAND(ID_VIEW_ZOOMIN, OnViewZoomin) ON_COMMAND(ID_VIEW_ZOOMOUT, OnViewZoomout) ON_UPDATE_COMMAND_UI(ID_VIEW_ZOOMIN, OnUpdateViewZoomin) ON_UPDATE_COMMAND_UI(ID_VIEW_ZOOMOUT, OnUpdateViewZoomout) ON_COMMAND(ID_VIEW_NORMALVIEWING11, OnViewNormalviewing11) ON_UPDATE_COMMAND_UI(ID_VIEW_NORMALVIEWING11, OnUpdateViewNormalviewing11) ON_COMMAND(ID_CXIMAGE_SETTRANSPARENCY, OnCximageSettransparency) ON_UPDATE_COMMAND_UI(ID_CXIMAGE_SETTRANSPARENCY, OnUpdateCximageSettransparency) ON_COMMAND(ID_CXIMAGE_REMOVETRANSPARENCY, OnCximageRemovetransparency) ON_UPDATE_COMMAND_UI(ID_CXIMAGE_REMOVETRANSPARENCY, OnUpdateCximageRemovetransparency) ON_COMMAND(ID_CXIMAGE_RESAMPLE, OnCximageResample) ON_UPDATE_COMMAND_UI(ID_EDIT_COPY, OnUpdateEditCopy) ON_UPDATE_COMMAND_UI(ID_CXIMAGE_FLIP, OnUpdateCximageFlip) ON_UPDATE_COMMAND_UI(ID_CXIMAGE_GRAYSCALE, OnUpdateCximageGrayscale) ON_UPDATE_COMMAND_UI(ID_CXIMAGE_MIRROR, OnUpdateCximageMirror) ON_UPDATE_COMMAND_UI(ID_CXIMAGE_NEGATIVE, OnUpdateCximageNegative) ON_UPDATE_COMMAND_UI(ID_CXIMAGE_RESAMPLE, OnUpdateCximageResample) ON_UPDATE_COMMAND_UI(ID_CXIMAGE_ROTATE, OnUpdateCximageRotate) ON_UPDATE_COMMAND_UI(ID_TRANSFORM_ELLIPSE, OnUpdateTransformEllipse) ON_COMMAND(ID_CXIMAGE_DECREASEBPP, OnCximageDecreasebpp) ON_COMMAND(ID_CXIMAGE_INCREASEBPP, OnCximageIncreasebpp) ON_COMMAND(ID_CXIMAGE_OPTIONS, OnCximageOptions) ON_COMMAND(ID_CXIMAGE_DITHER, OnCximageDither) ON_UPDATE_COMMAND_UI(ID_CXIMAGE_DITHER, OnUpdateCximageDither) ON_COMMAND(ID_CXIMAGE_THRESHOLD, OnCximageThreshold) ON_UPDATE_COMMAND_UI(ID_CXIMAGE_THRESHOLD, OnUpdateCximageThreshold) ON_COMMAND(ID_CXIMAGE_SPLITRGB, OnCximageSplitrgb) ON_UPDATE_COMMAND_UI(ID_CXIMAGE_SPLITRGB, OnUpdateCximageSplitrgb) ON_COMMAND(ID_CXIMAGE_SPLITYUV, OnCximageSplityuv) ON_UPDATE_COMMAND_UI(ID_CXIMAGE_SPLITYUV, OnUpdateCximageSplityuv) ON_COMMAND(ID_CXIMAGE_SPLITHSL, OnCximageSplithsl) ON_UPDATE_COMMAND_UI(ID_CXIMAGE_SPLITHSL, OnUpdateCximageSplithsl) ON_COMMAND(ID_CXIMAGE_PSEUDOCOLORS, OnCximagePseudocolors) ON_UPDATE_COMMAND_UI(ID_CXIMAGE_PSEUDOCOLORS, OnUpdateCximagePseudocolors) ON_UPDATE_COMMAND_UI(ID_CXIMAGE_COLORIZE, OnUpdateCximageFiltersColorize) ON_COMMAND(ID_CXIMAGE_COLORIZE, OnCximageFiltersColorize) ON_COMMAND(ID_CXIMAGE_DARKEN, OnCximageDarken) ON_UPDATE_COMMAND_UI(ID_CXIMAGE_DARKEN, OnUpdateCximageDarken) ON_COMMAND(ID_CXIMAGE_LIGHTEN, OnCximageLighten) ON_UPDATE_COMMAND_UI(ID_CXIMAGE_LIGHTEN, OnUpdateCximageLighten) ON_COMMAND(ID_CXIMAGE_CONTRAST, OnCximageContrast) ON_UPDATE_COMMAND_UI(ID_CXIMAGE_CONTRAST, OnUpdateCximageContrast) ON_COMMAND(ID_CXIMAGE_EMBOSS, OnCximageEmboss) ON_UPDATE_COMMAND_UI(ID_CXIMAGE_EMBOSS, OnUpdateCximageEmboss) ON_COMMAND(ID_CXIMAGE_BLUR, OnCximageBlur) ON_UPDATE_COMMAND_UI(ID_CXIMAGE_BLUR, OnUpdateCximageBlur) ON_COMMAND(ID_CXIMAGE_DILATE, OnCximageDilate) ON_UPDATE_COMMAND_UI(ID_CXIMAGE_DILATE, OnUpdateCximageDilate) ON_COMMAND(ID_CXIMAGE_EDGE, OnCximageEdge) ON_UPDATE_COMMAND_UI(ID_CXIMAGE_EDGE, OnUpdateCximageEdge) ON_COMMAND(ID_CXIMAGE_ERODE, OnCximageErode) ON_UPDATE_COMMAND_UI(ID_CXIMAGE_ERODE, OnUpdateCximageErode) ON_COMMAND(ID_CXIMAGE_SHARPEN, OnCximageSharpen) ON_UPDATE_COMMAND_UI(ID_CXIMAGE_SHARPEN, OnUpdateCximageSharpen) ON_COMMAND(ID_CXIMAGE_SOFTEN, OnCximageSoften) ON_UPDATE_COMMAND_UI(ID_CXIMAGE_SOFTEN, OnUpdateCximageSoften) ON_UPDATE_COMMAND_UI(ID_CXIMAGE_CROP, OnUpdateCximageCrop) ON_COMMAND(ID_CXIMAGE_CROP, OnCximageCrop) ON_UPDATE_COMMAND_UI(ID_CXIMAGE_REMOVEALPHACHANNEL, OnUpdateCximageRemovealphachannel) ON_COMMAND(ID_CXIMAGE_REMOVEALPHACHANNEL, OnCximageRemovealphachannel) ON_COMMAND(ID_CXIMAGE_OPACITY, OnCximageOpacity) ON_COMMAND(ID_CXIMAGE_INVETALPHA, OnCximageInvetalpha) ON_UPDATE_COMMAND_UI(ID_CXIMAGE_INVETALPHA, OnUpdateCximageInvetalpha) ON_COMMAND(ID_CXIMAGE_ALPHAPALETTETOGGLE, OnCximageAlphapalettetoggle) ON_UPDATE_COMMAND_UI(ID_CXIMAGE_ALPHAPALETTETOGGLE, OnUpdateCximageAlphapalettetoggle) ON_COMMAND(ID_CXIMAGE_ALPHASTRIP, OnCximageAlphastrip) ON_UPDATE_COMMAND_UI(ID_CXIMAGE_ALPHASTRIP, OnUpdateCximageAlphastrip) ON_COMMAND(ID_CXIMAGE_ROTATEL, OnCximageRotatel) ON_UPDATE_COMMAND_UI(ID_CXIMAGE_ROTATEL, OnUpdateCximageRotatel) ON_UPDATE_COMMAND_UI(ID_CXIMAGE_ROTATER, OnUpdateCximageRotater) ON_COMMAND(ID_CXIMAGE_ROTATER, OnCximageRotater) ON_UPDATE_COMMAND_UI(ID_CXIMAGE_GAMMA, OnUpdateCximageGamma) ON_COMMAND(ID_CXIMAGE_GAMMA, OnCximageGamma) ON_UPDATE_COMMAND_UI(ID_CXIMAGE_MEDIAN, OnUpdateCximageMedian) ON_COMMAND(ID_CXIMAGE_MEDIAN, OnCximageMedian) ON_COMMAND(ID_CXIMAGE_ADDNOISE, OnCximageAddnoise) ON_UPDATE_COMMAND_UI(ID_CXIMAGE_ADDNOISE, OnUpdateCximageAddnoise) ON_UPDATE_COMMAND_UI(ID_VIEW_TOOLS_MOVE, OnUpdateViewToolsMove) ON_COMMAND(ID_VIEW_TOOLS_MOVE, OnViewToolsMove) ON_COMMAND(ID_VIEW_TOOLS_SELECT, OnViewToolsSelect) ON_UPDATE_COMMAND_UI(ID_VIEW_TOOLS_SELECT, OnUpdateViewToolsSelect) ON_COMMAND(ID_VIEW_TOOLS_ZOOM, OnViewToolsZoom) ON_UPDATE_COMMAND_UI(ID_VIEW_TOOLS_ZOOM, OnUpdateViewToolsZoom) ON_UPDATE_COMMAND_UI(ID_VIEW_PALETTE, OnUpdateViewPalette) ON_COMMAND(ID_VIEW_PALETTE, OnViewPalette) ON_COMMAND(ID_CXIMAGE_COMBINE, OnCximageCombine) ON_UPDATE_COMMAND_UI(ID_CXIMAGE_COMBINE, OnUpdateCximageCombine) ON_COMMAND(ID_CXIMAGE_FFT, OnCximageFft) ON_UPDATE_COMMAND_UI(ID_CXIMAGE_FFT, OnUpdateCximageFft) ON_COMMAND(ID_CXIMAGE_SPLITYIQ, OnCximageSplityiq) ON_UPDATE_COMMAND_UI(ID_CXIMAGE_SPLITYIQ, OnUpdateCximageSplityiq) ON_COMMAND(ID_CXIMAGE_SPLITXYZ, OnCximageSplitxyz) ON_UPDATE_COMMAND_UI(ID_CXIMAGE_SPLITXYZ, OnUpdateCximageSplitxyz) ON_COMMAND(ID_CXIMAGE_REPAIR, OnCximageRepair) ON_UPDATE_COMMAND_UI(ID_CXIMAGE_REPAIR, OnUpdateCximageRepair) ON_UPDATE_COMMAND_UI(ID_CXIMAGE_ALPHACHANNEL_SPLIT, OnUpdateCximageAlphachannelSplit) ON_COMMAND(ID_CXIMAGE_ALPHACHANNEL_SPLIT, OnCximageAlphachannelSplit) ON_COMMAND(ID_VIEW_TOOLS_TEXT, OnViewToolsText) ON_UPDATE_COMMAND_UI(ID_VIEW_TOOLS_TEXT, OnUpdateViewToolsText) ON_COMMAND(ID_CXIMAGE_SPLITCMYK, OnCximageSplitcmyk) ON_UPDATE_COMMAND_UI(ID_CXIMAGE_SPLITCMYK, OnUpdateCximageSplitcmyk) ON_COMMAND(ID_CXIMAGE_ALPHACREATE, OnCximageAlphaCreate) ON_COMMAND(ID_CXIMAGE_HISTOGRAM_LOG, OnCximageFiltersLog) ON_UPDATE_COMMAND_UI(ID_CXIMAGE_HISTOGRAM_LOG, OnUpdateCximageFiltersLog) ON_COMMAND(ID_CXIMAGE_HISTOGRAM_ROOT, OnCximageFiltersRoot) ON_UPDATE_COMMAND_UI(ID_CXIMAGE_HISTOGRAM_ROOT, OnUpdateCximageFiltersRoot) ON_COMMAND(ID_CXIMAGE_HISTOGRAM_EQUALIZE, OnCximageHistogramEqualize) ON_UPDATE_COMMAND_UI(ID_CXIMAGE_HISTOGRAM_EQUALIZE, OnUpdateCximageHistogramEqualize) ON_COMMAND(ID_CXIMAGE_HISTOGRAM_NORMALIZE, OnCximageHistogramNormalize) ON_UPDATE_COMMAND_UI(ID_CXIMAGE_HISTOGRAM_NORMALIZE, OnUpdateCximageHistogramNormalize) ON_COMMAND(ID_CXIMAGE_HISTOGRAM_STRETCH, OnCximageHistogramStretch) ON_UPDATE_COMMAND_UI(ID_CXIMAGE_HISTOGRAM_STRETCH, OnUpdateCximageHistogramStretch) ON_COMMAND(ID_CXIMAGE_GAUSSIAN3X3, OnCximageGaussian3x3) ON_UPDATE_COMMAND_UI(ID_CXIMAGE_GAUSSIAN3X3, OnUpdateCximageGaussian3x3) ON_COMMAND(ID_CXIMAGE_GAUSSIAN5X5, OnCximageGaussian5x5) ON_UPDATE_COMMAND_UI(ID_CXIMAGE_GAUSSIAN5X5, OnUpdateCximageGaussian5x5) ON_COMMAND(ID_CXIMAGE_CONTOUR, OnCximageContour) ON_UPDATE_COMMAND_UI(ID_CXIMAGE_CONTOUR, OnUpdateCximageContour) ON_COMMAND(ID_CXIMAGE_LESSCONTRAST, OnCximageLesscontrast) ON_UPDATE_COMMAND_UI(ID_CXIMAGE_LESSCONTRAST, OnUpdateCximageLesscontrast) ON_COMMAND(ID_CXIMAGE_JITTER, OnCximageJitter) ON_UPDATE_COMMAND_UI(ID_CXIMAGE_JITTER, OnUpdateCximageJitter) ON_UPDATE_COMMAND_UI(ID_WINDOW_DUPLICATE, OnUpdateWindowDuplicate) ON_UPDATE_COMMAND_UI(ID_FILTERS_MIX, OnUpdateFiltersMix) ON_COMMAND(ID_FILTERS_MIX, OnFiltersMix) ON_COMMAND(ID_CXIMAGE_CIRCLETRANSFORM_CYLINDER, OnCximageCircletransformCylinder) ON_UPDATE_COMMAND_UI(ID_CXIMAGE_CIRCLETRANSFORM_CYLINDER, OnUpdateCximageCircletransformCylinder) ON_COMMAND(ID_CXIMAGE_CIRCLETRANSFORM_PINCH, OnCximageCircletransformPinch) ON_UPDATE_COMMAND_UI(ID_CXIMAGE_CIRCLETRANSFORM_PINCH, OnUpdateCximageCircletransformPinch) ON_COMMAND(ID_CXIMAGE_CIRCLETRANSFORM_PUNCH, OnCximageCircletransformPunch) ON_UPDATE_COMMAND_UI(ID_CXIMAGE_CIRCLETRANSFORM_PUNCH, OnUpdateCximageCircletransformPunch) ON_COMMAND(ID_CXIMAGE_CIRCLETRANSFORM_SWIRL, OnCximageCircletransformSwirl) ON_UPDATE_COMMAND_UI(ID_CXIMAGE_CIRCLETRANSFORM_SWIRL, OnUpdateCximageCircletransformSwirl) ON_COMMAND(ID_CXIMAGE_CIRCLETRANSFORM_BATHROOM, OnCximageCircletransformBathroom) ON_UPDATE_COMMAND_UI(ID_CXIMAGE_CIRCLETRANSFORM_BATHROOM, OnUpdateCximageCircletransformBathroom) ON_COMMAND(ID_CXIMAGE_HISTOGRAM_STRETCH1, OnCximageHistogramStretch1) ON_COMMAND(ID_CXIMAGE_HISTOGRAM_STRETCH2, OnCximageHistogramStretch2) ON_UPDATE_COMMAND_UI(ID_CXIMAGE_HISTOGRAM_STRETCH1, OnUpdateCximageHistogramStretch1) ON_UPDATE_COMMAND_UI(ID_CXIMAGE_HISTOGRAM_STRETCH2, OnUpdateCximageHistogramStretch2) ON_COMMAND(ID_FILTERS_NONLINEAR_EDGE, OnFiltersNonlinearEdge) ON_UPDATE_COMMAND_UI(ID_FILTERS_NONLINEAR_EDGE, OnUpdateFiltersNonlinearEdge) ON_COMMAND(ID_CXIMAGE_SKEW, OnCximageSkew) ON_UPDATE_COMMAND_UI(ID_CXIMAGE_SKEW, OnUpdateCximageSkew) ON_COMMAND(ID_VIEW_TOOLS_TRACKER, OnViewToolsTracker) ON_UPDATE_COMMAND_UI(ID_VIEW_TOOLS_TRACKER, OnUpdateViewToolsTracker) ON_COMMAND(ID_FILTERS_JPEGCOMPRESSION, OnJpegcompression) ON_UPDATE_COMMAND_UI(ID_FILTERS_JPEGCOMPRESSION, OnUpdateJpegcompression) ON_COMMAND(ID_VIEW_SMOOTH, OnViewSmooth) ON_UPDATE_COMMAND_UI(ID_VIEW_SMOOTH, OnUpdateViewSmooth) ON_UPDATE_COMMAND_UI(ID_FILTERS_DATAEXT, OnUpdateFiltersDataext) ON_COMMAND(ID_FILTERS_DATAEXT, OnFiltersDataext) ON_UPDATE_COMMAND_UI(ID_CXIMAGE_UNSHARPMASK, OnUpdateCximageUnsharpmask) ON_COMMAND(ID_CXIMAGE_UNSHARPMASK, OnCximageUnsharpmask) ON_COMMAND(ID_CXIMAGE_TEXTBLUR, OnCximageTextblur) ON_UPDATE_COMMAND_UI(ID_CXIMAGE_TEXTBLUR, OnUpdateCximageTextblur) ON_UPDATE_COMMAND_UI(ID_CXIMAGE_REDEYEREMOVE, OnUpdateCximageRedeyeremove) ON_COMMAND(ID_CXIMAGE_REDEYEREMOVE, OnCximageRedeyeremove) ON_COMMAND(ID_CXIMAGE_BLURSELBORDER, OnCximageBlurselborder) ON_UPDATE_COMMAND_UI(ID_CXIMAGE_BLURSELBORDER, OnUpdateCximageBlurselborder) ON_COMMAND(ID_CXIMAGE_SELECTIVEBLUR, OnCximageSelectiveblur) ON_UPDATE_COMMAND_UI(ID_CXIMAGE_SELECTIVEBLUR, OnUpdateCximageSelectiveblur) ON_UPDATE_COMMAND_UI(ID_CXIMAGE_GETTRANSPARENCYMASK, OnUpdateCximageGettransparencymask) ON_COMMAND(ID_CXIMAGE_GETTRANSPARENCYMASK, OnCximageGettransparencymask) ON_COMMAND(ID_COLORS_COUNTCOLORS, OnColorsCountcolors) ON_UPDATE_COMMAND_UI(ID_COLORS_COUNTCOLORS, OnUpdateColorsCountcolors) ON_COMMAND(ID_FILTERS_LINEAR_CUSTOM, OnFiltersLinearCustom) ON_UPDATE_COMMAND_UI(ID_FILTERS_LINEAR_CUSTOM, OnUpdateFiltersLinearCustom) ON_COMMAND(ID_CXIMAGE_CANVASSIZE, OnCximageCanvassize) ON_UPDATE_COMMAND_UI(ID_CXIMAGE_CANVASSIZE, OnUpdateCximageCanvassize) ON_COMMAND(ID_VIEW_TOOLS_FLOODFILL, OnViewToolsFloodfill) ON_UPDATE_COMMAND_UI(ID_VIEW_TOOLS_FLOODFILL, OnUpdateViewToolsFloodfill) ON_COMMAND(ID_CXIMAGE_REMOVESELECTION, OnCximageRemoveselection) ON_UPDATE_COMMAND_UI(ID_CXIMAGE_REMOVESELECTION, OnUpdateCximageRemoveselection) ON_COMMAND(ID_COLORS_MORESATURATIONHSL, OnColorsMoresaturationhsl) ON_UPDATE_COMMAND_UI(ID_COLORS_MORESATURATIONHSL, OnUpdateColorsMoresaturationhsl) ON_COMMAND(ID_COLORS_MORESATURATIONYUV, OnColorsMoresaturationyuv) ON_UPDATE_COMMAND_UI(ID_COLORS_MORESATURATIONYUV, OnUpdateColorsMoresaturationyuv) ON_COMMAND(ID_COLORS_LESSSATURATION, OnColorsLesssaturation) ON_UPDATE_COMMAND_UI(ID_COLORS_LESSSATURATION, OnUpdateColorsLesssaturation) ON_COMMAND(ID_COLORS_HISTOGRAM_FULLSATURATION, OnColorsHistogramFullsaturation) ON_UPDATE_COMMAND_UI(ID_COLORS_HISTOGRAM_FULLSATURATION, OnUpdateColorsHistogramFullsaturation) ON_COMMAND(ID_COLORS_HISTOGRAM_HALFSATURATION, OnColorsHistogramHalfsaturation) ON_UPDATE_COMMAND_UI(ID_COLORS_HISTOGRAM_HALFSATURATION, OnUpdateColorsHistogramHalfsaturation) ON_COMMAND(ID_CXIMAGE_HISTOGRAM_STRETCHT0, OnCximageHistogramStretcht0) ON_UPDATE_COMMAND_UI(ID_CXIMAGE_HISTOGRAM_STRETCHT0, OnUpdateCximageHistogramStretcht0) ON_COMMAND(ID_CXIMAGE_HISTOGRAM_STRETCHT1, OnCximageHistogramStretcht1) ON_UPDATE_COMMAND_UI(ID_CXIMAGE_HISTOGRAM_STRETCHT1, OnUpdateCximageHistogramStretcht1) ON_COMMAND(ID_CXIMAGE_HISTOGRAM_STRETCHT2, OnCximageHistogramStretcht2) ON_UPDATE_COMMAND_UI(ID_CXIMAGE_HISTOGRAM_STRETCHT2, OnUpdateCximageHistogramStretcht2) ON_COMMAND(ID_COLORS_ADAPTIVETHRESHOLD, OnColorsAdaptivethreshold) ON_UPDATE_COMMAND_UI(ID_COLORS_ADAPTIVETHRESHOLD, OnUpdateColorsAdaptivethreshold) ON_UPDATE_COMMAND_UI(ID_VIEW_PREVIOUSFRAME, OnUpdateViewPreviousframe) ON_COMMAND(ID_VIEW_PREVIOUSFRAME, OnViewPreviousframe) ON_UPDATE_COMMAND_UI(ID_VIEW_NEXTFRAME, OnUpdateViewNextframe) ON_COMMAND(ID_VIEW_NEXTFRAME, OnViewNextframe) ON_UPDATE_COMMAND_UI(ID_VIEW_PLAYANIMATION, OnUpdateViewPlayanimation) ON_COMMAND(ID_VIEW_PLAYANIMATION, OnViewPlayanimation) ON_UPDATE_COMMAND_UI(ID_FILTERS_ADDSHADOW, OnUpdateFiltersAddshadow) ON_COMMAND(ID_FILTERS_ADDSHADOW, OnFiltersAddshadow) //}}AFX_MSG_MAP END_MESSAGE_MAP() ////////////////////////////////////////////////////////////////////////////// // CDemoDoc construction/destruction CDemoDoc::CDemoDoc() { image = NULL; m_WaitingClick = stretchMode = m_bSmoothDisplay = FALSE; for (int i=0;i<MAX_UNDO_LEVELS;i++) imageUndo[i]=NULL; m_UndoLevel=0; m_ZoomFactor=1; QueryPerformanceFrequency(&m_swFreq); m_etime = 0.0; hThread=hProgress=0; m_NumSel=0; m_tool=0; m_playanimation = 0; m_hmax=0; #ifndef VATI_EXTENSIONS memset(&m_font,0,sizeof(m_font)); m_color=0; m_text=_T("text"); #endif } ////////////////////////////////////////////////////////////////////////////// CDemoDoc::~CDemoDoc() { // stop the elaborations if (image) image->SetEscape(1); // stop the progress bar if (hProgress){ ResumeThread(hProgress); //wake up! WaitForSingleObject(hProgress,INFINITE); CloseHandle(hProgress); } if (hThread){ WaitForSingleObject(hThread,INFINITE); CloseHandle(hThread); } // free objects delete image; for (int i=0;i<MAX_UNDO_LEVELS;i++) delete imageUndo[i]; } ////////////////////////////////////////////////////////////////////////////// BOOL CDemoDoc::OnNewDocument() { if (!CDocument::OnNewDocument()) return FALSE; // TODO: add reinitialization code here // (SDI documents will reuse this document) image = NULL; return TRUE; } ////////////////////////////////////////////////////////////////////////////// // CDemoDoc serialization void CDemoDoc::Serialize(CArchive& ar) { if (ar.IsStoring()) { } else { } } ////////////////////////////////////////////////////////////////////////////// // CDemoDoc diagnostics #ifdef _DEBUG void CDemoDoc::AssertValid() const { CDocument::AssertValid(); } ////////////////////////////////////////////////////////////////////////////// void CDemoDoc::Dump(CDumpContext& dc) const { CDocument::Dump(dc); } #endif //_DEBUG ////////////////////////////////////////////////////////////////////////////// // CDemoDoc commands CString CDemoDoc::FindExtension(const CString& name) { int len = name.GetLength(); int i; for (i = len-1; i >= 0; i--){ if (name[i] == '.'){ return name.Mid(i+1); } } return CString(_T("")); } ////////////////////////////////////////////////////////////////////////////// CString CDemoDoc::RemoveExtension(const CString& name) { int len = name.GetLength(); int i; for (i = len-1; i >= 0; i--){ if (name[i] == '.'){ return name.Mid(0,i); } } return name; } ////////////////////////////////////////////////////////////////////////////// int CDemoDoc::FindType(const CString& ext) { return CxImage::GetTypeIdFromName(ext); } ////////////////////////////////////////////////////////////////////////////// BOOL CDemoDoc::OnOpenDocument(LPCTSTR lpszPathName) { CString filename(lpszPathName); CString ext(FindExtension(filename)); ext.MakeLower(); if (ext == _T("")) return FALSE; int type = FindType(ext); /* CxImage iinfo; CxIOFile file; file.Open(filename,"rb"); bool bOk = iinfo.CheckFormat(&file); long t = iinfo.GetType(); long w = iinfo.GetWidth(); long h = iinfo.GetHeight(); */ Stopwatch(0); image = new CxImage(filename, type); Stopwatch(1); if (!image->IsValid()){ CString s = image->GetLastError(); AfxMessageBox(s); delete image; image = NULL; return FALSE; } UpdateStatusBar(); UpdateAllViews(NULL,WM_USER_NEWIMAGE); //multiple images (TIFF/ICO) if (image->GetNumFrames()>1){ CString s; s.Format(_T("File with %d images. Read all?"),image->GetNumFrames()); if (AfxMessageBox(s,MB_OKCANCEL)==IDOK){ int j; // points to the document name for(j=_tcslen(filename)-1;j>=0;j--){ if (filename[j]=='\\'){ j++; break; } } // create the documents for the other images for(int i=1;i<image->GetNumFrames();i++){ CDemoDoc *NewDoc=(CDemoDoc*)((CDemoApp*)AfxGetApp())->demoTemplate->OpenDocumentFile(NULL); if (NewDoc) { CxImage *newImage = new CxImage(); newImage->SetFrame(i); newImage->Load(filename,type); NewDoc->image = newImage; CString s; s.Format(_T("%s (%d)"),filename.Mid(j),i+1); NewDoc->SetTitle(s); NewDoc->UpdateAllViews(NULL,WM_USER_NEWIMAGE); } } } else { if (type == CXIMAGE_FORMAT_GIF || type == CXIMAGE_FORMAT_LC_TEX){ image->SetRetreiveAllFrames(true); image->SetFrame(image->GetNumFrames()-1); image->Load(filename, type); s = _T("Play animation?"); if (AfxMessageBox(s,MB_YESNO)==IDYES){ OnViewPlayanimation(); } } } } // EXIF jpegs if (image->GetType() == CXIMAGE_FORMAT_JPG){ FILE* hfile = _tfopen(filename,_T("rb")); m_exif.DecodeExif(hfile); fclose(hfile); } return TRUE; } ////////////////////////////////////////////////////////////////////////////// BOOL CDemoDoc::OnSaveDocument(LPCTSTR lpszPathName) { CString filename(lpszPathName); CString ext(FindExtension(filename)); ext.MakeLower(); if (ext == _T("")) return FALSE; int type = FindType(ext); if (type == CXIMAGE_FORMAT_UNKNOWN) return FALSE; if (type == CXIMAGE_FORMAT_LC_TEX) { AfxMessageBox(_T("not supported")); return TRUE; } if (type == CXIMAGE_FORMAT_GIF && image->GetBpp()>8){ AfxMessageBox(_T("The image will be saved as a true color GIF!\nThis is ok for CxImage, but not for many other programs.\nFor better compatibility, please use DecreaseBpp to 8 bits or less."),MB_ICONINFORMATION); } bool retval; Stopwatch(0); retval = image->Save(filename, type); Stopwatch(1); UpdateStatusBar(); if (retval) return TRUE; CString s = image->GetLastError(); AfxMessageBox(s); return FALSE; } ////////////////////////////////////////////////////////////////////////////// BOOL CDemoDoc::DoSave(LPCTSTR pszPathName, BOOL bReplace /*=TRUE*/) { if (!image) return FALSE; CString newName = pszPathName; BOOL bModified = IsModified(); BOOL bSaveAs = FALSE; if (newName.IsEmpty()) bSaveAs = TRUE; else if (!theApp.GetWritableType(image->GetType())) bSaveAs = TRUE; if (bSaveAs){ newName = m_strPathName; newName = RemoveExtension(newName); if (bReplace && newName.IsEmpty()){ newName = m_strTitle; newName = RemoveExtension(newName); int iBad = newName.FindOneOf(_T("#%;/\\")); // dubious filename if (iBad != -1) //newName.ReleaseBuffer(iBad); newName = _T("UntitledImage"); // append the default suffix if there is one //if (image->GetType()) newName += theApp.GetExtFromType(image->GetType()).Mid(1,4); } if (image->GetType()) theApp.nDocType = image->GetType(); if (!theApp.PromptForFileName(newName, bReplace ? AFX_IDS_SAVEFILE : AFX_IDS_SAVEFILECOPY, OFN_HIDEREADONLY | OFN_PATHMUSTEXIST, FALSE, &theApp.nDocType)) { return FALSE; // don't even try to save } } BeginWaitCursor(); if (!OnSaveDocument(newName)){ if (pszPathName == NULL){ // be sure to delete the file TRY { CFile::Remove(newName); } CATCH_ALL(e) { TRACE0("Warning: failed to delete file after failed SaveAs\n"); } END_CATCH_ALL } EndWaitCursor(); return FALSE; } EndWaitCursor(); if (bReplace) { // Reset the title and change the document name SetPathName(newName, TRUE); ASSERT(m_strPathName == newName); // must be set } else // SaveCopyAs { SetModifiedFlag(bModified); } return TRUE; // success } ////////////////////////////////////////////////////////////////////////////// #define EPSILON (0.0000001) int CDemoDoc::ComputePixel(float x, float y, float &x1, float &y1) { double r, nn; if (x==0 && y==0) { x1 = x; y1 = y; return 1; } nn = sqrt(x*x + y*y); r = (fabs(x) > fabs(y)) ? fabs(nn/x): fabs(nn/y); x1 = (float)(r*x); y1 = (float)(r*y); return 1; } ////////////////////////////////////////////////////////////////////////////// void CDemoDoc::OnUpdateFileSaveAs(CCmdUI* pCmdUI) { pCmdUI->Enable(!(image==0 || hThread)); } ////////////////////////////////////////////////////////////////////////////// void CDemoDoc::OnUpdateFileSave(CCmdUI* pCmdUI) { pCmdUI->Enable(0); // pCmdUI->Enable((image != NULL)); //&& theApp.GetWritableType(image->GetType())); } ////////////////////////////////////////////////////////////////////////////// void CDemoDoc::OnStretchMode() { stretchMode = !stretchMode; UpdateAllViews(NULL); } ////////////////////////////////////////////////////////////////////////////// void CDemoDoc::OnUpdateStretchMode(CCmdUI* pCmdUI) { pCmdUI->SetCheck(stretchMode); } ////////////////////////////////////////////////////////////////////////////// void CDemoDoc::OnUpdateCximageFlip(CCmdUI* pCmdUI) { if(image==0 || hThread) pCmdUI->Enable(0); } void CDemoDoc::OnUpdateCximageGrayscale(CCmdUI* pCmdUI) { if(image==0 || hThread) pCmdUI->Enable(0);} void CDemoDoc::OnUpdateCximageMirror(CCmdUI* pCmdUI) { if(image==0 || hThread) pCmdUI->Enable(0);} void CDemoDoc::OnUpdateCximageNegative(CCmdUI* pCmdUI) { if(image==0 || hThread) pCmdUI->Enable(0);} void CDemoDoc::OnUpdateCximageResample(CCmdUI* pCmdUI) { if(image==0 || hThread) pCmdUI->Enable(0);} void CDemoDoc::OnUpdateCximageRotate(CCmdUI* pCmdUI) { if(image==0 || hThread) pCmdUI->Enable(0);} void CDemoDoc::OnUpdateCximageRotater(CCmdUI* pCmdUI) { if(image==0 || hThread) pCmdUI->Enable(0);} void CDemoDoc::OnUpdateCximageRotatel(CCmdUI* pCmdUI) { if(image==0 || hThread) pCmdUI->Enable(0);} void CDemoDoc::OnUpdateCximageDither(CCmdUI* pCmdUI) { if(image==0 || hThread) pCmdUI->Enable(0);} void CDemoDoc::OnUpdateCximageThreshold(CCmdUI* pCmdUI) { if(image==0 || hThread) pCmdUI->Enable(0);} void CDemoDoc::OnUpdateCximageSplityuv(CCmdUI* pCmdUI) { if(image==0 || hThread) pCmdUI->Enable(0);} void CDemoDoc::OnUpdateCximageSplitrgb(CCmdUI* pCmdUI) { if(image==0 || hThread) pCmdUI->Enable(0);} void CDemoDoc::OnUpdateCximageSplithsl(CCmdUI* pCmdUI) { if(image==0 || hThread) pCmdUI->Enable(0);} void CDemoDoc::OnUpdateCximageSplityiq(CCmdUI* pCmdUI) { if(image==0 || hThread) pCmdUI->Enable(0);} void CDemoDoc::OnUpdateCximageSplitxyz(CCmdUI* pCmdUI) { if(image==0 || hThread) pCmdUI->Enable(0);} void CDemoDoc::OnUpdateCximageSplitcmyk(CCmdUI* pCmdUI) { if(image==0 || hThread) pCmdUI->Enable(0);} void CDemoDoc::OnUpdateCximagePseudocolors(CCmdUI* pCmdUI) { if(image==0 || hThread) pCmdUI->Enable(0);} void CDemoDoc::OnUpdateCximageFiltersColorize(CCmdUI* pCmdUI) { if(image==0 || hThread) pCmdUI->Enable(0);} void CDemoDoc::OnUpdateCximageLighten(CCmdUI* pCmdUI) { if(image==0 || hThread) pCmdUI->Enable(0);} void CDemoDoc::OnUpdateCximageDarken(CCmdUI* pCmdUI) { if(image==0 || hThread) pCmdUI->Enable(0);} void CDemoDoc::OnUpdateCximageContrast(CCmdUI* pCmdUI) { if(image==0 || hThread) pCmdUI->Enable(0);} void CDemoDoc::OnUpdateCximageEmboss(CCmdUI* pCmdUI) { if(image==0 || hThread) pCmdUI->Enable(0);} void CDemoDoc::OnUpdateCximageBlur(CCmdUI* pCmdUI) { if(image==0 || hThread) pCmdUI->Enable(0);} void CDemoDoc::OnUpdateCximageDilate(CCmdUI* pCmdUI) { if(image==0 || hThread) pCmdUI->Enable(0);} void CDemoDoc::OnUpdateCximageEdge(CCmdUI* pCmdUI) { if(image==0 || hThread) pCmdUI->Enable(0);} void CDemoDoc::OnUpdateCximageErode(CCmdUI* pCmdUI) { if(image==0 || hThread) pCmdUI->Enable(0);} void CDemoDoc::OnUpdateCximageSharpen(CCmdUI* pCmdUI) { if(image==0 || hThread) pCmdUI->Enable(0);} void CDemoDoc::OnUpdateCximageSoften(CCmdUI* pCmdUI) { if(image==0 || hThread) pCmdUI->Enable(0);} void CDemoDoc::OnUpdateCximageCrop(CCmdUI* pCmdUI) { if(image==0 || hThread || !image->SelectionIsValid()) pCmdUI->Enable(0);} void CDemoDoc::OnUpdateCximageRemovealphachannel(CCmdUI* pCmdUI) { if(image==0 || hThread || !image->AlphaIsValid()) pCmdUI->Enable(0);} void CDemoDoc::OnUpdateCximageInvetalpha(CCmdUI* pCmdUI) { if(image==0 || hThread || !image->AlphaIsValid()) pCmdUI->Enable(0);} void CDemoDoc::OnUpdateCximageAlphapalettetoggle(CCmdUI* pCmdUI) { if(image==0 || hThread || !image->AlphaPaletteIsValid()) pCmdUI->Enable(0);} void CDemoDoc::OnUpdateCximageAlphastrip(CCmdUI* pCmdUI) { if(image==0 || hThread || (!image->AlphaIsValid() && !image->AlphaPaletteIsValid())) pCmdUI->Enable(0);} void CDemoDoc::OnUpdateCximageRemovetransparency(CCmdUI* pCmdUI) { if(image==0 || hThread || image->GetTransIndex()<0) pCmdUI->Enable(0);} void CDemoDoc::OnUpdateCximageGamma(CCmdUI* pCmdUI) { if(image==0 || hThread) pCmdUI->Enable(0);} void CDemoDoc::OnUpdateCximageMedian(CCmdUI* pCmdUI) { if(image==0 || hThread) pCmdUI->Enable(0);} void CDemoDoc::OnUpdateCximageAddnoise(CCmdUI* pCmdUI) { if(image==0 || hThread) pCmdUI->Enable(0);} void CDemoDoc::OnUpdateCximageCombine(CCmdUI* pCmdUI) { if(image==0 || hThread) pCmdUI->Enable(0);} void CDemoDoc::OnUpdateCximageFft(CCmdUI* pCmdUI) { if(image==0 || hThread) pCmdUI->Enable(0);} void CDemoDoc::OnUpdateCximageRepair(CCmdUI* pCmdUI) { if(image==0 || hThread) pCmdUI->Enable(0);} void CDemoDoc::OnUpdateCximageAlphachannelSplit(CCmdUI* pCmdUI) { if(image==0 || hThread || !image->AlphaIsValid()) pCmdUI->Enable(0);} void CDemoDoc::OnUpdateCximageFiltersLog(CCmdUI* pCmdUI) { if(image==0 || hThread) pCmdUI->Enable(0);} void CDemoDoc::OnUpdateCximageFiltersRoot(CCmdUI* pCmdUI) { if(image==0 || hThread) pCmdUI->Enable(0);} void CDemoDoc::OnUpdateCximageHistogramEqualize(CCmdUI* pCmdUI) { if(image==0 || hThread) pCmdUI->Enable(0);} void CDemoDoc::OnUpdateCximageHistogramNormalize(CCmdUI* pCmdUI) { if(image==0 || hThread) pCmdUI->Enable(0);} void CDemoDoc::OnUpdateCximageHistogramStretch(CCmdUI* pCmdUI) { if(image==0 || hThread) pCmdUI->Enable(0);} void CDemoDoc::OnUpdateCximageGaussian3x3(CCmdUI* pCmdUI) { if(image==0 || hThread) pCmdUI->Enable(0);} void CDemoDoc::OnUpdateCximageGaussian5x5(CCmdUI* pCmdUI) { if(image==0 || hThread) pCmdUI->Enable(0);} void CDemoDoc::OnUpdateCximageContour(CCmdUI* pCmdUI) { if(image==0 || hThread) pCmdUI->Enable(0);} void CDemoDoc::OnUpdateCximageLesscontrast(CCmdUI* pCmdUI) { if(image==0 || hThread) pCmdUI->Enable(0);} void CDemoDoc::OnUpdateCximageJitter(CCmdUI* pCmdUI) { if(image==0 || hThread) pCmdUI->Enable(0);} void CDemoDoc::OnUpdateWindowDuplicate(CCmdUI* pCmdUI) { if(image==0 || hThread) pCmdUI->Enable(0);} void CDemoDoc::OnUpdateFiltersMix(CCmdUI* pCmdUI) { if(image==0 || hThread) pCmdUI->Enable(0);} void CDemoDoc::OnUpdateCximageCircletransformCylinder(CCmdUI* pCmdUI) { if(image==0 || hThread) pCmdUI->Enable(0);} void CDemoDoc::OnUpdateCximageCircletransformPinch(CCmdUI* pCmdUI) { if(image==0 || hThread) pCmdUI->Enable(0);} void CDemoDoc::OnUpdateCximageCircletransformPunch(CCmdUI* pCmdUI) { if(image==0 || hThread) pCmdUI->Enable(0);} void CDemoDoc::OnUpdateCximageCircletransformSwirl(CCmdUI* pCmdUI) { if(image==0 || hThread) pCmdUI->Enable(0);} void CDemoDoc::OnUpdateCximageCircletransformBathroom(CCmdUI* pCmdUI) { if(image==0 || hThread) pCmdUI->Enable(0);} void CDemoDoc::OnUpdateCximageHistogramStretch1(CCmdUI* pCmdUI) { if(image==0 || hThread) pCmdUI->Enable(0);} void CDemoDoc::OnUpdateCximageHistogramStretch2(CCmdUI* pCmdUI) { if(image==0 || hThread) pCmdUI->Enable(0);} void CDemoDoc::OnUpdateFiltersNonlinearEdge(CCmdUI* pCmdUI) { if(image==0 || hThread) pCmdUI->Enable(0);} void CDemoDoc::OnUpdateCximageSkew(CCmdUI* pCmdUI) { if(image==0 || hThread) pCmdUI->Enable(0);} void CDemoDoc::OnUpdateJpegcompression(CCmdUI* pCmdUI) { if(image==0 || hThread) pCmdUI->Enable(0);} void CDemoDoc::OnUpdateFiltersDataext(CCmdUI* pCmdUI) { if(image==0 || hThread) pCmdUI->Enable(0);} void CDemoDoc::OnUpdateCximageUnsharpmask(CCmdUI* pCmdUI) { if(image==0 || hThread) pCmdUI->Enable(0);} void CDemoDoc::OnUpdateCximageTextblur(CCmdUI* pCmdUI) { if(image==0 || hThread) pCmdUI->Enable(0);} void CDemoDoc::OnUpdateCximageRedeyeremove(CCmdUI* pCmdUI) { if(image==0 || hThread || !image->SelectionIsValid()) pCmdUI->Enable(0);} void CDemoDoc::OnUpdateCximageBlurselborder(CCmdUI* pCmdUI) { if(image==0 || hThread || !image->SelectionIsValid()) pCmdUI->Enable(0);} void CDemoDoc::OnUpdateCximageSelectiveblur(CCmdUI* pCmdUI) { if(image==0 || hThread) pCmdUI->Enable(0);} void CDemoDoc::OnUpdateCximageGettransparencymask(CCmdUI* pCmdUI) { if(image==0 || hThread || (image->GetTransIndex()<0 && !image->AlphaIsValid())) pCmdUI->Enable(0);} void CDemoDoc::OnUpdateColorsCountcolors(CCmdUI* pCmdUI) { if(image==0 || hThread) pCmdUI->Enable(0);} void CDemoDoc::OnUpdateFiltersLinearCustom(CCmdUI* pCmdUI) { if(image==0 || hThread) pCmdUI->Enable(0);} void CDemoDoc::OnUpdateCximageCanvassize(CCmdUI* pCmdUI) { if(image==0 || hThread) pCmdUI->Enable(0);} void CDemoDoc::OnUpdateCximageRemoveselection(CCmdUI* pCmdUI) { if(image==0 || hThread || !image->SelectionIsValid()) pCmdUI->Enable(0);} void CDemoDoc::OnUpdateColorsMoresaturationhsl(CCmdUI* pCmdUI) { if(image==0 || hThread) pCmdUI->Enable(0);} void CDemoDoc::OnUpdateColorsMoresaturationyuv(CCmdUI* pCmdUI) { if(image==0 || hThread) pCmdUI->Enable(0);} void CDemoDoc::OnUpdateColorsLesssaturation(CCmdUI* pCmdUI) { if(image==0 || hThread) pCmdUI->Enable(0);} void CDemoDoc::OnUpdateColorsHistogramHalfsaturation(CCmdUI* pCmdUI) { if(image==0 || hThread) pCmdUI->Enable(0);} void CDemoDoc::OnUpdateColorsHistogramFullsaturation(CCmdUI* pCmdUI) { if(image==0 || hThread) pCmdUI->Enable(0);} void CDemoDoc::OnUpdateCximageHistogramStretcht0(CCmdUI* pCmdUI) { if(image==0 || hThread) pCmdUI->Enable(0);} void CDemoDoc::OnUpdateCximageHistogramStretcht1(CCmdUI* pCmdUI) { if(image==0 || hThread) pCmdUI->Enable(0);} void CDemoDoc::OnUpdateCximageHistogramStretcht2(CCmdUI* pCmdUI) { if(image==0 || hThread) pCmdUI->Enable(0);} void CDemoDoc::OnUpdateColorsAdaptivethreshold(CCmdUI* pCmdUI) { if(image==0 || hThread) pCmdUI->Enable(0);} void CDemoDoc::OnUpdateViewPreviousframe(CCmdUI* pCmdUI) { if(image==0 || hThread || image->GetFrame(0)==0) pCmdUI->Enable(0);} void CDemoDoc::OnUpdateViewNextframe(CCmdUI* pCmdUI) { if(image==0 || hThread || image->GetFrame(0)==0) pCmdUI->Enable(0);} void CDemoDoc::OnUpdateFiltersAddshadow(CCmdUI* pCmdUI) { if(image==0 || hThread) pCmdUI->Enable(0);} ////////////////////////////////////////////////////////////////////////////// void CDemoDoc::OnUpdateTransformEllipse(CCmdUI* pCmdUI) { if (image==NULL) pCmdUI->Enable(0); } ////////////////////////////////////////////////////////////////////////////// void CDemoDoc::OnTransformEllipse() { SubmitUndo(); DWORD x, y; float x1, y1; //***bd*** use float source with GetPixelColorInterpolated float fx, fy, xmid, ymid, ar; CxImage *image2 = new CxImage(*image,false,false,true); xmid = (float) (image->GetWidth()/2.0); ymid = (float) (image->GetHeight()/2.0); ar = (float)(image->GetHeight())/(float)(image->GetWidth()); for (y=0; y<image->GetHeight(); y++) { for (x=0; x<image->GetWidth(); x++) { ComputePixel(ar*(x-xmid), y-ymid, fx, fy); x1 = xmid+fx/ar; y1 = ymid+fy; //correct method to use would be GetAreaColorAveraged (but I guess there's not that much aliasing here) image2->SetPixelColor(x, y, image->GetPixelColorInterpolated(x1, y1, CxImage::IM_BILINEAR, CxImage::OM_BACKGROUND)); //image2->SetPixelColor(x, y, image->GetPixelColor(x1, y1)); } } delete image; image = image2; UpdateAllViews(NULL); } ////////////////////////////////////////////////////////////////////////////// void CDemoDoc::OnWindowDuplicate() { CDemoDoc *NewDoc=(CDemoDoc*)((CDemoApp*)AfxGetApp())->demoTemplate->OpenDocumentFile(NULL); if (NewDoc) { CxImage *newImage = new CxImage(*image); NewDoc->image = newImage; CString s; s.Format(_T("Copy %d of %s"),((CDemoApp*)AfxGetApp())->m_nDocCount++,GetTitle()); NewDoc->SetTitle(s); NewDoc->UpdateAllViews(0,WM_USER_NEWIMAGE); } } ////////////////////////////////////////////////////////////////////////////// void CDemoDoc::OnUpdateEditCopy(CCmdUI* pCmdUI) { if (image==NULL) pCmdUI->Enable(0); } ////////////////////////////////////////////////////////////////////////////// void CDemoDoc::OnEditCopy() { CxImage* iSrc = image; //copy only the selected region box CxImage iSel; if (image->SelectionIsValid()){ RECT r; image->SelectionGetBox(r); r.bottom = image->GetHeight() - 1 -r.bottom; r.top = image->GetHeight() - 1 -r.top; image->Crop(r, &iSel); iSrc = &iSel; } // standard DIB image HANDLE hDIB=iSrc->CopyToHandle(); #define USE_CF_CXIMAGE 1 #if USE_CF_CXIMAGE //custom CXIMAGE object HANDLE hMem=NULL; if (iSrc->IsValid() && (iSrc->AlphaIsValid() || iSrc->SelectionIsValid() || iSrc->IsTransparent())){ hMem= GlobalAlloc(GHND, iSrc->DumpSize()); if (hMem){ BYTE* pDst=(BYTE*)GlobalLock(hMem); iSrc->Dump(pDst); GlobalUnlock(hMem); } } #endif //USE_CF_CXIMAGE if (::OpenClipboard(AfxGetApp()->m_pMainWnd->GetSafeHwnd())) { if(::EmptyClipboard()) { if (::SetClipboardData(CF_DIB,hDIB) == NULL ) { AfxMessageBox( _T("Unable to set DIB clipboard data") ); } #if USE_CF_CXIMAGE if (hMem){ UINT cf = ((CDemoApp*)AfxGetApp())->GetCF(); if (::SetClipboardData(cf,hMem) == NULL ) { AfxMessageBox( _T("Unable to set CXIMAGE clipboard data") ); } } #endif //USE_CF_CXIMAGE } } CloseClipboard(); } ////////////////////////////////////////////////////////////////////////////// void CDemoDoc::OnUpdateEditUndo(CCmdUI* pCmdUI) { if(image==0 || hThread) pCmdUI->Enable(0); else pCmdUI->Enable(m_UndoLevel>0); CString s; s.Format(_T("Undo (%d)\tCtrl+Z"),m_UndoLevel); pCmdUI->SetText(s); } ////////////////////////////////////////////////////////////////////////////// void CDemoDoc::OnUpdateEditRedo(CCmdUI* pCmdUI) { if(image==0 || hThread) pCmdUI->Enable(0); else pCmdUI->Enable((m_UndoLevel<(MAX_UNDO_LEVELS))&& (imageUndo[m_UndoLevel]!=0)); } ////////////////////////////////////////////////////////////////////////////// void CDemoDoc::OnEditUndo() { m_UndoLevel--; CxImage* tmp = image; image=imageUndo[m_UndoLevel]; imageUndo[m_UndoLevel]=tmp; UpdateAllViews(0,WM_USER_NEWIMAGE); UpdateStatusBar(); } ////////////////////////////////////////////////////////////////////////////// void CDemoDoc::OnEditRedo() { CxImage* tmp = image; image=imageUndo[m_UndoLevel]; imageUndo[m_UndoLevel]=tmp; m_UndoLevel++; UpdateAllViews(0,WM_USER_NEWIMAGE); UpdateStatusBar(); } ////////////////////////////////////////////////////////////////////////////// void CDemoDoc::SubmitUndo() { if (m_UndoLevel>=MAX_UNDO_LEVELS){ // Max Undo reached delete imageUndo[0]; // discard the early undo for(int i=1;i<MAX_UNDO_LEVELS;i++){ imageUndo[i-1]=imageUndo[i]; //shift the history } imageUndo[MAX_UNDO_LEVELS-1]=0; // clear the undo slot m_UndoLevel=MAX_UNDO_LEVELS-1; // reposition at last level } // we must clear the "redo" history when a new action is performed for (int i=m_UndoLevel;i<MAX_UNDO_LEVELS;i++){ if (imageUndo[i]){ delete imageUndo[i]; imageUndo[i]=0; } } // save the actual image in the undo history if (image->IsValid()){ imageUndo[m_UndoLevel] = new CxImage(); imageUndo[m_UndoLevel]->Copy(*image); m_UndoLevel++; } } ////////////////////////////////////////////////////////////////////////////// void /*unsigned long _stdcall*/ RunProgressThread(void *lpParam) { CDemoDoc *pDoc = (CDemoDoc *)lpParam; POSITION pos; CView *pView; while(pDoc->hThread){ Sleep(333); if(!pDoc->image) break; if(pDoc->image->GetEscape()) break; long n=pDoc->image->GetProgress(); pos = pDoc->GetFirstViewPosition(); pView = pDoc->GetNextView(pos); if (pView) SendMessage(pView->m_hWnd, WM_USER_PROGRESS,n,0); } pos = pDoc->GetFirstViewPosition(); pView = pDoc->GetNextView(pos); if (pView) SendMessage(pView->m_hWnd, WM_USER_PROGRESS,100,0); Sleep(111); pos = pDoc->GetFirstViewPosition(); pView = pDoc->GetNextView(pos); if (pView) SendMessage(pView->m_hWnd, WM_USER_NEWIMAGE,0,0); pDoc->hProgress = 0; _endthread(); return; } ////////////////////////////////////////////////////////////////////////////// void /*unsigned long _stdcall*/ RunCxImageThread(void *lpParam) { CDemoDoc *pDoc = (CDemoDoc *)lpParam; if (pDoc==NULL) return; if (pDoc->image==NULL){ pDoc->hThread=0; return; } //prepare for elaboration pDoc->image->SetProgress(0); pDoc->image->SetEscape(0); pDoc->SubmitUndo(); // auxilary thread for progress bar pDoc->hProgress = (HANDLE)_beginthread(RunProgressThread,0,pDoc); pDoc->Stopwatch(0); bool status = true; switch (pDoc->m_MenuCommand) { // case ID_FILE_OPEN: // status = pDoc->image->ReadFile(theApp.m_filename,theApp.m_filetype); // break; case ID_CXIMAGE_FLIP: status = pDoc->image->Flip(); break; case ID_CXIMAGE_MIRROR: status = pDoc->image->Mirror(); break; case ID_CXIMAGE_NEGATIVE: status = pDoc->image->Negative(); break; case ID_CXIMAGE_GRAYSCALE: status = pDoc->image->GrayScale(); break; case ID_CXIMAGE_DITHER: status = pDoc->image->Dither(theApp.m_Filters.DitherMethod); break; case ID_CXIMAGE_THRESHOLD: if (theApp.m_Filters.ThreshPreserveColors){ RGBQUAD c = {255,255,255,0}; status = pDoc->image->Threshold2(theApp.m_Filters.ThreshLevel,true,c,true); } else { status = pDoc->image->Threshold(theApp.m_Filters.ThreshLevel); } break; case ID_COLORS_ADAPTIVETHRESHOLD: { /* CxImage iContrastMask; iContrastMask.Copy(*pDoc->image,true,false,false); if (!iContrastMask.IsValid()) break; iContrastMask.GrayScale(); long edge[]={-1,-1,-1,-1,8,-1,-1,-1,-1}; iContrastMask.Filter(edge,3,1,0); long blur[]={1,1,1,1,1,1,1,1,1}; iContrastMask.Filter(blur,3,9,0); status = pDoc->image->AdaptiveThreshold(0,64,&iContrastMask); */ status = pDoc->image->AdaptiveThreshold(); } break; case ID_CXIMAGE_COLORIZE: switch (theApp.m_Filters.ColorMode) { case 1: status = pDoc->image->Colorize(theApp.m_Filters.ColorHSL.rgbRed,theApp.m_Filters.ColorHSL.rgbGreen,theApp.m_Filters.ColorHSL.rgbBlue/100.0f); break; case 2: status = pDoc->image->Solarize(theApp.m_Filters.ColorSolarLevel,theApp.m_Filters.ColorSolarLink!=0); break; default: status = pDoc->image->ShiftRGB(theApp.m_Filters.ColorRed,theApp.m_Filters.ColorGreen,theApp.m_Filters.ColorBlue); } break; case ID_CXIMAGE_LIGHTEN: status = pDoc->image->Light(10); break; case ID_CXIMAGE_DARKEN: status = pDoc->image->Light(-10); break; case ID_CXIMAGE_CONTRAST: status = pDoc->image->Light(0,10); break; case ID_CXIMAGE_LESSCONTRAST: status = pDoc->image->Light(0,-10); break; case ID_COLORS_MORESATURATIONHSL: status = pDoc->image->Saturate(25,1); break; case ID_COLORS_MORESATURATIONYUV: status = pDoc->image->Saturate(25,2); break; case ID_COLORS_LESSSATURATION: status = pDoc->image->Saturate(-20,2); break; case ID_CXIMAGE_DILATE: status = pDoc->image->Dilate(3); break; case ID_CXIMAGE_ERODE: status = pDoc->image->Erode(3); break; case ID_CXIMAGE_CONTOUR: status = pDoc->image->Contour(); break; case ID_CXIMAGE_ADDNOISE: status = pDoc->image->Noise(25); break; case ID_CXIMAGE_JITTER: status = pDoc->image->Jitter(); break; case ID_CXIMAGE_TEXTBLUR: status = pDoc->image->TextBlur(100,2,3,true,true); break; case ID_CXIMAGE_BLURSELBORDER: { CxImage iSel1,iSel2; pDoc->image->SelectionSplit(&iSel1); pDoc->image->SelectionSplit(&iSel2); iSel2.Edge(); //iSel2.Erode(); iSel2.Negative(); pDoc->image->SelectionSet(iSel2); pDoc->image->GaussianBlur(); pDoc->image->SelectionSet(iSel1); break; } case ID_CXIMAGE_SELECTIVEBLUR: status = pDoc->image->SelectiveBlur(1,25); break; case ID_CXIMAGE_REDEYEREMOVE: status = pDoc->image->RedEyeRemove(); break; case ID_FILTERS_NONLINEAR_EDGE: status = pDoc->image->Edge(); break; case ID_CXIMAGE_CIRCLETRANSFORM_CYLINDER: status = pDoc->image->CircleTransform(3,0,100); break; case ID_CXIMAGE_CIRCLETRANSFORM_PINCH: status = pDoc->image->CircleTransform(1,0,100); break; case ID_CXIMAGE_CIRCLETRANSFORM_PUNCH: status = pDoc->image->CircleTransform(0,0,100); break; case ID_CXIMAGE_CIRCLETRANSFORM_SWIRL: status = pDoc->image->CircleTransform(2,0,100); break; case ID_CXIMAGE_CIRCLETRANSFORM_BATHROOM: status = pDoc->image->CircleTransform(4); break; case ID_CXIMAGE_EMBOSS: { long kernel[]={0,0,-1,0,0,0,1,0,0}; status = pDoc->image->Filter(kernel,3,-1,127); break; } case ID_CXIMAGE_BLUR: { long kernel[]={1,1,1,1,1,1,1,1,1}; status = pDoc->image->Filter(kernel,3,9,0); break; } case ID_CXIMAGE_GAUSSIAN3X3: { //long kernel[]={1,2,1,2,4,2,1,2,1}; //status = pDoc->image->Filter(kernel,3,16,0); status = pDoc->image->GaussianBlur(1.0f); break; } case ID_CXIMAGE_GAUSSIAN5X5: { //long kernel[]={0,1,2,1,0,1,3,4,3,1,2,4,8,4,2,1,3,4,3,1,0,1,2,1,0}; //status = pDoc->image->Filter(kernel,5,52,0); status = pDoc->image->GaussianBlur(2.0f); break; } case ID_CXIMAGE_SOFTEN: { long kernel[]={1,1,1,1,8,1,1,1,1}; status = pDoc->image->Filter(kernel,3,16,0); break; } case ID_CXIMAGE_SHARPEN: { long kernel[]={-1,-1,-1,-1,15,-1,-1,-1,-1}; status = pDoc->image->Filter(kernel,3,7,0); break; } case ID_CXIMAGE_EDGE: { long kernel[]={-1,-1,-1,-1,8,-1,-1,-1,-1}; status = pDoc->image->Filter(kernel,3,-1,255); break; } case ID_FILTERS_LINEAR_CUSTOM: // [Priyank Bolia] { if(theApp.m_Filters.kSize==3) pDoc->image->Filter(theApp.m_Filters.Kernel3x3,3,theApp.m_Filters.kDivisor,theApp.m_Filters.kBias); else pDoc->image->Filter(theApp.m_Filters.Kernel5x5,5,theApp.m_Filters.kDivisor,theApp.m_Filters.kBias); break; } case ID_CXIMAGE_MEDIAN: status = pDoc->image->Median(3); break; case ID_CXIMAGE_UNSHARPMASK: status = pDoc->image->UnsharpMask(); break; case ID_CXIMAGE_GAMMA: if (theApp.m_Filters.GammaLink){ status = pDoc->image->GammaRGB(theApp.m_Filters.GammaR,theApp.m_Filters.GammaG,theApp.m_Filters.GammaB); } else { status = pDoc->image->Gamma(theApp.m_Filters.GammaLevel); } break; case ID_CXIMAGE_HISTOGRAM_LOG: status = pDoc->image->HistogramLog(); break; case ID_CXIMAGE_HISTOGRAM_ROOT: status = pDoc->image->HistogramRoot(); break; case ID_CXIMAGE_HISTOGRAM_EQUALIZE: status = pDoc->image->HistogramEqualize(); break; case ID_CXIMAGE_HISTOGRAM_NORMALIZE: status = pDoc->image->HistogramNormalize(); break; case ID_CXIMAGE_HISTOGRAM_STRETCH: status = pDoc->image->HistogramStretch(); break; case ID_CXIMAGE_HISTOGRAM_STRETCH1: status = pDoc->image->HistogramStretch(1); break; case ID_CXIMAGE_HISTOGRAM_STRETCH2: status = pDoc->image->HistogramStretch(2); break; case ID_CXIMAGE_HISTOGRAM_STRETCHT0: status = pDoc->image->HistogramStretch(0,0.005f); break; case ID_CXIMAGE_HISTOGRAM_STRETCHT1: status = pDoc->image->HistogramStretch(1,0.005f); break; case ID_CXIMAGE_HISTOGRAM_STRETCHT2: status = pDoc->image->HistogramStretch(2,0.005f); break; case ID_COLORS_HISTOGRAM_FULLSATURATION: { CxImage tmp; tmp.Copy(*(pDoc->image),true,false,false); tmp.ConvertColorSpace(2,0); long u[256]; long v[256]; tmp.Histogram(0,u,v,0,0); int umin = 255; int umax = 0; int vmin = 255; int vmax = 0; for (int i = 0; i<255; i++){ if (u[i]) umin = i; if (u[255-i]) umax = i; if (v[i]) vmin = i; if (v[255-i]) vmax = i; } float cmin = (float)min(umin,vmin); float cmax = (float)max(umax,vmax); if (cmin<128) cmin = 128.0f/(128-cmin); else cmin = 128.0f; if (cmax>128) cmax = 128.0f/(cmax-128); else cmax = 128.0f; int sat = (int)(100.0f*(min(cmin,cmax)-1.0f)); pDoc->image->Saturate(sat,2); } break; case ID_COLORS_HISTOGRAM_HALFSATURATION: { CxImage tmp; tmp.Copy(*(pDoc->image),true,false,false); tmp.ConvertColorSpace(2,0); long u[256]; long v[256]; tmp.Histogram(0,u,v,0,0); int umin = 255; int umax = 0; int vmin = 255; int vmax = 0; for (int i = 0; i<255; i++){ if (u[i]) umin = i; if (u[255-i]) umax = i; if (v[i]) vmin = i; if (v[255-i]) vmax = i; } float cmin = (float)min(umin,vmin); float cmax = (float)max(umax,vmax); if (cmin<128) cmin = 128.0f/(128-cmin); else cmin = 128.0f; if (cmax>128) cmax = 128.0f/(cmax-128); else cmax = 128.0f; int sat = (int)(50.0f*(min(cmin,cmax)-1.0f)); pDoc->image->Saturate(sat,2); } break; case ID_CXIMAGE_SKEW: status = pDoc->image->Skew(theApp.m_Filters.SkewSlopeX,theApp.m_Filters.SkewSlopeY, theApp.m_Filters.SkewPivotX,theApp.m_Filters.SkewPivotY, theApp.m_Filters.SkewInterp!=0); break; case ID_CXIMAGE_ROTATE: //***bd*** more rotation options CxImage::InterpolationMethod intm; CxImage::OverflowMethod overm; switch (theApp.m_Filters.RotateMethod) { case 0: intm=CxImage::IM_NEAREST_NEIGHBOUR; break; case 1: intm=CxImage::IM_BILINEAR; break; case 2: intm=CxImage::IM_BICUBIC; break; case 3: intm=CxImage::IM_BICUBIC2; break; case 4: intm=CxImage::IM_BSPLINE; break; case 5: intm=CxImage::IM_LANCZOS; break; case 6: intm=CxImage::IM_HERMITE; break; default: throw(0); }//switch switch (theApp.m_Filters.RotateOverflow) { case 0: overm=CxImage::OM_BACKGROUND; break; case 1: overm=CxImage::OM_BACKGROUND; break; case 2: overm=CxImage::OM_BACKGROUND; break; case 3: overm=CxImage::OM_WRAP; break; case 4: overm=CxImage::OM_REPEAT; break; case 5: overm=CxImage::OM_MIRROR; break; case 6: overm=CxImage::OM_TRANSPARENT; break; }//switch switch (theApp.m_Filters.RotateOverflow) { case 0: { RGBQUAD bkg = pDoc->image->GetPixelColor(0,0); status = pDoc->image->Rotate2(theApp.m_Filters.RotateAngle, 0, intm, overm, &bkg,true,theApp.m_Filters.RotateKeepsize!=0); break; } case 1: { RGBQUAD bkg = {0,0,0,0}; status = pDoc->image->Rotate2(theApp.m_Filters.RotateAngle, 0, intm, overm, &bkg,true,theApp.m_Filters.RotateKeepsize!=0); break; } default: status = pDoc->image->Rotate2(theApp.m_Filters.RotateAngle, 0, intm, overm, 0,true,theApp.m_Filters.RotateKeepsize!=0); } break; case ID_CXIMAGE_ROTATEL: status = pDoc->image->RotateLeft(); if (status) pDoc->RegionRotateLeft(); break; case ID_CXIMAGE_ROTATER: status = pDoc->image->RotateRight(); if (status) pDoc->RegionRotateRight(); break; case ID_CXIMAGE_RESAMPLE: //***bd*** more resample options CxImage::InterpolationMethod rintm; switch (theApp.m_Filters.ResampleMethod) { case 0: rintm=CxImage::IM_NEAREST_NEIGHBOUR; break; case 1: rintm=CxImage::IM_BILINEAR; break; case 2: rintm=CxImage::IM_BILINEAR; break; case 3: rintm=CxImage::IM_BICUBIC; break; case 4: rintm=CxImage::IM_BICUBIC2; break; case 5: rintm=CxImage::IM_BSPLINE; break; case 6: rintm=CxImage::IM_LANCZOS; break; case 7: rintm=CxImage::IM_HERMITE; break; default: throw(0); }//switch switch (theApp.m_Filters.ResampleMethod) { case 0: status = pDoc->image->Resample(theApp.m_Filters.ResampleW,theApp.m_Filters.ResampleH,1); break; case 1: status = pDoc->image->Resample(theApp.m_Filters.ResampleW,theApp.m_Filters.ResampleH,0); break; case 2: if ((long)pDoc->image->GetWidth()>theApp.m_Filters.ResampleW && (long)pDoc->image->GetHeight()>theApp.m_Filters.ResampleH) status = pDoc->image->QIShrink(theApp.m_Filters.ResampleW,theApp.m_Filters.ResampleH); else status = pDoc->image->Resample2(theApp.m_Filters.ResampleW,theApp.m_Filters.ResampleH,rintm,CxImage::OM_REPEAT); break; default: status = pDoc->image->Resample2(theApp.m_Filters.ResampleW,theApp.m_Filters.ResampleH,rintm,CxImage::OM_REPEAT); } break; case ID_CXIMAGE_CANVASSIZE: { RGBQUAD color = CxImage::RGBtoRGBQUAD(theApp.m_Filters.CanvasBkg); if (theApp.m_Filters.CanvasUseImageBkg) color = pDoc->image->GetTransColor(); RECT r; if (theApp.m_Filters.CanvasMode == 0){ r.top = 0; r.left = 0; r.right = theApp.m_Filters.CanvasW - pDoc->image->GetWidth(); r.bottom = theApp.m_Filters.CanvasH - pDoc->image->GetHeight(); if (theApp.m_Filters.CanvasCenterH){ r.left = (theApp.m_Filters.CanvasW - pDoc->image->GetWidth()) / 2; r.right = theApp.m_Filters.CanvasW - pDoc->image->GetWidth() - r.left; } if (theApp.m_Filters.CanvasCenterV){ r.top = (theApp.m_Filters.CanvasH - pDoc->image->GetHeight()) / 2; r.bottom = theApp.m_Filters.CanvasH - pDoc->image->GetHeight() - r.top; } } else { r.top = theApp.m_Filters.CanvasTop; r.left = theApp.m_Filters.CanvasLeft; r.right = theApp.m_Filters.CanvasRight; r.bottom = theApp.m_Filters.CanvasBottom; } status = pDoc->image->Expand(r.left, r.top, r.right, r.bottom, color); } break; case ID_CXIMAGE_INCREASEBPP: status = pDoc->image->IncreaseBpp(theApp.m_Filters.IncBppBPP); break; case ID_CXIMAGE_DECREASEBPP: { long bit = theApp.m_Filters.DecBppBPP; long method = theApp.m_Filters.DecBppPalMethod; bool errordiffusion = theApp.m_Filters.DecBppErrDiff!=0; long colors = theApp.m_Filters.DecBppMaxColors; //pDoc->image->IncreaseBpp(24); RGBQUAD c = pDoc->image->GetTransColor(); RGBQUAD* ppal = NULL; if (method==1){ switch (bit){ /*case 1: { CQuantizer q(2,8); q.ProcessImage(pDoc->image->GetDIB()); ppal=(RGBQUAD*)calloc(2*sizeof(RGBQUAD),1); q.SetColorTable(ppal); break; }*/ case 4: { CQuantizer q(colors,8); q.ProcessImage(pDoc->image->GetDIB()); ppal=(RGBQUAD*)calloc(16*sizeof(RGBQUAD),1); q.SetColorTable(ppal); break; } case 8: { CQuantizer q(colors,(colors>16?7:8)); q.ProcessImage(pDoc->image->GetDIB()); ppal=(RGBQUAD*)calloc(256*sizeof(RGBQUAD),1); q.SetColorTable(ppal); } } status = pDoc->image->DecreaseBpp(bit,errordiffusion,ppal,colors); } else status = pDoc->image->DecreaseBpp(bit,errordiffusion,0); if (!pDoc->image->AlphaPaletteIsValid()) pDoc->image->AlphaPaletteEnable(0); if (pDoc->image->IsTransparent()){ pDoc->image->SetTransIndex(pDoc->image->GetNearestIndex(c)); } if (ppal) free(ppal); break; } } pDoc->Stopwatch(1); pDoc->image->SetProgress(100); if (!status){ CString s = pDoc->image->GetLastError(); AfxMessageBox(s); } pDoc->hThread=0; _endthread(); return ; } ////////////////////////////////////////////////////////////////////////////// void CDemoDoc::OnCximageFlip() { m_MenuCommand=ID_CXIMAGE_FLIP; hThread=(HANDLE)_beginthread(RunCxImageThread,0,this); } ////////////////////////////////////////////////////////////////////////////// void CDemoDoc::OnCximageMirror() { m_MenuCommand=ID_CXIMAGE_MIRROR; hThread=(HANDLE)_beginthread(RunCxImageThread,0,this); } ////////////////////////////////////////////////////////////////////////////// void CDemoDoc::OnCximageNegative() { m_MenuCommand=ID_CXIMAGE_NEGATIVE; hThread=(HANDLE)_beginthread(RunCxImageThread,0,this); } ////////////////////////////////////////////////////////////////////////////// void CDemoDoc::OnCximageGrayscale() { m_MenuCommand=ID_CXIMAGE_GRAYSCALE; hThread=(HANDLE)_beginthread(RunCxImageThread,0,this); } ////////////////////////////////////////////////////////////////////////////// void CDemoDoc::OnCximageDecreasebpp() { if (image==NULL) return; DlgDecBpp dlg; dlg.m_bit = theApp.m_Filters.DecBppBPP; dlg.m_method = theApp.m_Filters.DecBppPalMethod; dlg.m_errordiffusion = theApp.m_Filters.DecBppErrDiff; dlg.m_bLimitColors = theApp.m_Filters.DecBppLimitColors; dlg.m_maxcolors = theApp.m_Filters.DecBppMaxColors; if (dlg.DoModal()==IDOK){ m_MenuCommand=ID_CXIMAGE_DECREASEBPP; theApp.m_Filters.DecBppBPP = dlg.m_bit; theApp.m_Filters.DecBppPalMethod = dlg.m_method; theApp.m_Filters.DecBppErrDiff = dlg.m_errordiffusion; theApp.m_Filters.DecBppLimitColors = dlg.m_bLimitColors; theApp.m_Filters.DecBppMaxColors = dlg.m_maxcolors; hThread=(HANDLE)_beginthread(RunCxImageThread,0,this); } } ////////////////////////////////////////////////////////////////////////////// void CDemoDoc::OnCximageIncreasebpp() { if (image==NULL) return; DlgIncBpp dlg; dlg.m_bit = theApp.m_Filters.IncBppBPP; if (dlg.DoModal()==IDOK){ m_MenuCommand=ID_CXIMAGE_INCREASEBPP; theApp.m_Filters.IncBppBPP = dlg.m_bit; hThread=(HANDLE)_beginthread(RunCxImageThread,0,this); } } ////////////////////////////////////////////////////////////////////////////// void CDemoDoc::OnCximageRotatel() { m_MenuCommand=ID_CXIMAGE_ROTATEL; hThread=(HANDLE)_beginthread(RunCxImageThread,0,this); } ////////////////////////////////////////////////////////////////////////////// void CDemoDoc::OnCximageRotater() { m_MenuCommand=ID_CXIMAGE_ROTATER; hThread=(HANDLE)_beginthread(RunCxImageThread,0,this); } ////////////////////////////////////////////////////////////////////////////// void CDemoDoc::OnCximageRotate() { if (image==NULL) return; DlgRotate dlg; dlg.m_angle = theApp.m_Filters.RotateAngle; dlg.m_method = theApp.m_Filters.RotateMethod; dlg.m_overflow = theApp.m_Filters.RotateOverflow; dlg.m_keepsize = theApp.m_Filters.RotateKeepsize; if (dlg.DoModal()==IDOK){ m_MenuCommand=ID_CXIMAGE_ROTATE; theApp.m_Filters.RotateAngle = dlg.m_angle; theApp.m_Filters.RotateMethod = dlg.m_method; theApp.m_Filters.RotateOverflow = dlg.m_overflow; theApp.m_Filters.RotateKeepsize = dlg.m_keepsize; hThread=(HANDLE)_beginthread(RunCxImageThread,0,this); } } ////////////////////////////////////////////////////////////////////////////// void CDemoDoc::OnCximageResample() { if (image==NULL) return; DlgResample dlg; dlg.m_w = image->GetWidth(); dlg.m_h = image->GetHeight(); dlg.m_ratio = ((float)image->GetWidth())/((float)image->GetHeight()); dlg.m_sizemode = theApp.m_Filters.ResampleSizemode; dlg.m_factor = theApp.m_Filters.ResampleFactor; dlg.m_newwidth = theApp.m_Filters.ResampleW; dlg.m_newheight = theApp.m_Filters.ResampleH; dlg.m_bKeepRatio = theApp.m_Filters.ResampleKeepRatio; dlg.m_mode = theApp.m_Filters.ResampleMethod; if (dlg.m_bKeepRatio) dlg.m_newheight = (DWORD)(dlg.m_newwidth/dlg.m_ratio); if (dlg.DoModal()==IDOK){ m_MenuCommand=ID_CXIMAGE_RESAMPLE; if (dlg.m_sizemode==1){ dlg.m_newwidth = (DWORD)(dlg.m_w * fabs(dlg.m_factor)); dlg.m_newheight = (DWORD)(dlg.m_h * fabs(dlg.m_factor)); } theApp.m_Filters.ResampleSizemode = dlg.m_sizemode; theApp.m_Filters.ResampleFactor = dlg.m_factor; theApp.m_Filters.ResampleW = dlg.m_newwidth; theApp.m_Filters.ResampleH = dlg.m_newheight; theApp.m_Filters.ResampleKeepRatio = dlg.m_bKeepRatio; theApp.m_Filters.ResampleMethod = dlg.m_mode; hThread=(HANDLE)_beginthread(RunCxImageThread,0,this); } } ////////////////////////////////////////////////////////////////////////////// void CDemoDoc::UpdateStatusBar() { if (image){ CStatusBar& statusBar = ((CMainFrame *)(AfxGetApp()->m_pMainWnd))->GetStatusBar(); CString s,t; t = theApp.GetDescFromType(image->GetType()); s.Format(_T("(%dx%dx%d)"),image->GetWidth(),image->GetHeight(),image->GetBpp()); statusBar.SetPaneText(4, s); statusBar.SetPaneText(3,t.Mid(0,3)); s.Format(_T("Time (s): %.3f"),m_etime); statusBar.SetPaneText(2, s); // ((CMainFrame *)(AfxGetApp()->m_pMainWnd))->GetProgressBar().SetPos(0); } } ////////////////////////////////////////////////////////////////////////////// void CDemoDoc::OnViewZoomin() { if (m_ZoomFactor>=16) return; if (m_ZoomFactor == 0.50f) m_ZoomFactor = 0.75f; else if (m_ZoomFactor == 0.75f) m_ZoomFactor = 1.00f; else if (m_ZoomFactor == 1.00f) m_ZoomFactor = 1.50f; else if (m_ZoomFactor == 1.50f) m_ZoomFactor = 2.00f; else m_ZoomFactor*=2; CStatusBar& statusBar = ((CMainFrame *)(AfxGetApp()->m_pMainWnd))->GetStatusBar(); CString s; s.Format(_T("%4.0f %%"),m_ZoomFactor*100); statusBar.SetPaneText(2, s); UpdateAllViews(NULL,WM_USER_NEWIMAGE); } ////////////////////////////////////////////////////////////////////////////// void CDemoDoc::OnViewZoomout() { if (m_ZoomFactor<=0.0625) return; if (m_ZoomFactor == 2.00f) m_ZoomFactor = 1.50f; else if (m_ZoomFactor == 1.50f) m_ZoomFactor = 1.00f; else if (m_ZoomFactor == 1.00f) m_ZoomFactor = 0.75f; else if (m_ZoomFactor == 0.75f) m_ZoomFactor = 0.50f; else m_ZoomFactor/=2; CStatusBar& statusBar = ((CMainFrame *)(AfxGetApp()->m_pMainWnd))->GetStatusBar(); CString s; s.Format(_T("%4.1f %%"),m_ZoomFactor*100); statusBar.SetPaneText(2, s); UpdateAllViews(NULL,WM_USER_NEWIMAGE); } ////////////////////////////////////////////////////////////////////////////// void CDemoDoc::OnUpdateViewZoomin(CCmdUI* pCmdUI) { if (stretchMode) pCmdUI->Enable(0); if (m_ZoomFactor>=16) pCmdUI->Enable(0); } ////////////////////////////////////////////////////////////////////////////// void CDemoDoc::OnUpdateViewZoomout(CCmdUI* pCmdUI) { if (stretchMode) pCmdUI->Enable(0); if (m_ZoomFactor<=0.125) pCmdUI->Enable(0); } ////////////////////////////////////////////////////////////////////////////// void CDemoDoc::OnViewNormalviewing11() { m_ZoomFactor=1; UpdateAllViews(NULL,WM_USER_NEWIMAGE); } ////////////////////////////////////////////////////////////////////////////// void CDemoDoc::OnUpdateViewNormalviewing11(CCmdUI* pCmdUI) { if (stretchMode) pCmdUI->Enable(0); if (m_ZoomFactor==1) pCmdUI->Enable(0); } ////////////////////////////////////////////////////////////////////////////// void CDemoDoc::OnUpdateCximageSettransparency(CCmdUI* pCmdUI) { if (image && hThread==0) pCmdUI->Enable(1); else pCmdUI->Enable(0); } ////////////////////////////////////////////////////////////////////////////// void CDemoDoc::OnCximageRemovetransparency() { SubmitUndo(); if (image) image->SetTransIndex(-1); UpdateAllViews(NULL); } ////////////////////////////////////////////////////////////////////////////// void CDemoDoc::OnCximageSettransparency() { m_WaitingClick=TRUE; } ////////////////////////////////////////////////////////////////////////////// void CDemoDoc::Stopwatch(int start0stop1) { if (start0stop1==0) QueryPerformanceCounter(&m_swStart); else { QueryPerformanceCounter(&m_swStop); if (m_swFreq.LowPart==0 && m_swFreq.HighPart==0) m_etime = -1; else { m_etime = (float)(m_swStop.LowPart - m_swStart.LowPart); if (m_etime < 0) m_etime += 2^32; m_etime /= (m_swFreq.LowPart+m_swFreq.HighPart * 2^32); } } } ////////////////////////////////////////////////////////////////////////////// void CDemoDoc::OnCximageOptions() { if (image==NULL) return; DlgOptions dlg; dlg.m_jpeg_quality = image->GetJpegQualityF(); dlg.m_xres = image->GetXDPI(); dlg.m_yres = image->GetYDPI(); #if CXIMAGE_SUPPORT_TIF dlg.m_Opt_tif = image->GetCodecOption(CXIMAGE_FORMAT_TIF); #endif #if CXIMAGE_SUPPORT_GIF dlg.m_Opt_gif = image->GetCodecOption(CXIMAGE_FORMAT_GIF); #endif #if CXIMAGE_SUPPORT_JPG dlg.m_Opt_jpg = image->GetCodecOption(CXIMAGE_FORMAT_JPG); #endif #if CXIMAGE_SUPPORT_PNG dlg.m_Opt_png = image->GetCodecOption(CXIMAGE_FORMAT_PNG); #endif #if CXIMAGE_SUPPORT_RAW dlg.m_Opt_raw = image->GetCodecOption(CXIMAGE_FORMAT_RAW); #endif dlg.m_exif = &m_exif; if (dlg.DoModal()==IDOK){ image->SetJpegQualityF(dlg.m_jpeg_quality); image->SetXDPI(dlg.m_xres); image->SetYDPI(dlg.m_yres); #if CXIMAGE_SUPPORT_TIF image->SetCodecOption(dlg.m_Opt_tif, CXIMAGE_FORMAT_TIF); #endif #if CXIMAGE_SUPPORT_GIF image->SetCodecOption(dlg.m_Opt_gif, CXIMAGE_FORMAT_GIF); #endif #if CXIMAGE_SUPPORT_JPG image->SetCodecOption(dlg.m_Opt_jpg, CXIMAGE_FORMAT_JPG); #endif #if CXIMAGE_SUPPORT_PNG image->SetCodecOption(dlg.m_Opt_png, CXIMAGE_FORMAT_PNG); #endif #if CXIMAGE_SUPPORT_RAW image->SetCodecOption(dlg.m_Opt_raw, CXIMAGE_FORMAT_RAW); #endif #ifdef VATI_EXTENSIONS theApp.m_optJpegQuality = dlg.m_jpeg_quality; theApp.m_optJpegOptions = dlg.m_Opt_jpg; theApp.m_optRawOptions = dlg.m_Opt_raw; #endif } } ////////////////////////////////////////////////////////////////////////////// void CDemoDoc::OnCximageDither() { if (image==NULL) return; DlgDither dlg; dlg.m_method = theApp.m_Filters.DitherMethod; if (dlg.DoModal()==IDOK){ m_MenuCommand=ID_CXIMAGE_DITHER; theApp.m_Filters.DitherMethod = dlg.m_method; hThread=(HANDLE)_beginthread(RunCxImageThread,0,this); } } ////////////////////////////////////////////////////////////////////////////// void CDemoDoc::OnCximageThreshold() { if (image==NULL) return; DlgThreshold dlg; CxImage iContrastMask; iContrastMask.Copy(*image,true,false,false); if (!iContrastMask.IsValid()){ AfxMessageBox(_T("cannot create ContrastMask")); return; } iContrastMask.GrayScale(); long edge[]={-1,-1,-1,-1,8,-1,-1,-1,-1}; iContrastMask.Filter(edge,3,1,0); long blur[]={1,1,1,1,1,1,1,1,1}; iContrastMask.Filter(blur,3,9,0); if (image->IsGrayScale()){ dlg.m_thresh1 = (long)image->OptimalThreshold(0,0); dlg.m_thresh2 = (long)image->OptimalThreshold(0,0,&iContrastMask); } else { CxImage iGray; iGray.Copy(*image,true,false,false); iGray.GrayScale(); dlg.m_thresh1 = (long)iGray.OptimalThreshold(0,0); dlg.m_thresh2 = (long)iGray.OptimalThreshold(0,0,&iContrastMask); } dlg.m_mean = (BYTE)image->Mean(); dlg.m_bPreserve = theApp.m_Filters.ThreshPreserveColors; dlg.m_level = theApp.m_Filters.ThreshLevel; if (dlg.DoModal()==IDOK){ m_MenuCommand=ID_CXIMAGE_THRESHOLD; theApp.m_Filters.ThreshLevel = dlg.m_level; theApp.m_Filters.ThreshPreserveColors = dlg.m_bPreserve; hThread=(HANDLE)_beginthread(RunCxImageThread,0,this); } } ////////////////////////////////////////////////////////////////////////////// void CDemoDoc::OnCximageSplitrgb() { if (image==NULL) return; CxImage *newr = new CxImage(); CxImage *newg = new CxImage(); CxImage *newb = new CxImage(); Stopwatch(0); image->SplitRGB(newr,newg,newb); Stopwatch(1); UpdateStatusBar(); ((CDemoApp*)AfxGetApp())->m_nDocCount++; CDemoDoc *NewDocr=(CDemoDoc*)((CDemoApp*)AfxGetApp())->demoTemplate->OpenDocumentFile(NULL); if (NewDocr) { NewDocr->image = newr; CString s; s.Format(_T("Red Channel %d from %s"),((CDemoApp*)AfxGetApp())->m_nDocCount,GetTitle()); NewDocr->SetTitle(s); NewDocr->UpdateAllViews(0,WM_USER_NEWIMAGE); } CDemoDoc *NewDocg=(CDemoDoc*)((CDemoApp*)AfxGetApp())->demoTemplate->OpenDocumentFile(NULL); if (NewDocg) { NewDocg->image = newg; CString s; s.Format(_T("Green Channel %d from %s"),((CDemoApp*)AfxGetApp())->m_nDocCount,GetTitle()); NewDocg->SetTitle(s); NewDocg->UpdateAllViews(0,WM_USER_NEWIMAGE); } CDemoDoc *NewDocb=(CDemoDoc*)((CDemoApp*)AfxGetApp())->demoTemplate->OpenDocumentFile(NULL); if (NewDocb) { NewDocb->image = newb; CString s; s.Format(_T("Blue Channel %d from %s"),((CDemoApp*)AfxGetApp())->m_nDocCount,GetTitle()); NewDocb->SetTitle(s); NewDocb->UpdateAllViews(0,WM_USER_NEWIMAGE); } } ////////////////////////////////////////////////////////////////////////////// void CDemoDoc::OnCximageSplityuv() { if (image==NULL) return; CxImage *newr = new CxImage(); CxImage *newg = new CxImage(); CxImage *newb = new CxImage(); Stopwatch(0); image->SplitYUV(newr,newg,newb); Stopwatch(1); UpdateStatusBar(); ((CDemoApp*)AfxGetApp())->m_nDocCount++; CDemoDoc *NewDocr=(CDemoDoc*)((CDemoApp*)AfxGetApp())->demoTemplate->OpenDocumentFile(NULL); if (NewDocr) { NewDocr->image = newr; CString s; s.Format(_T("Y Channel %d from %s"),((CDemoApp*)AfxGetApp())->m_nDocCount,GetTitle()); NewDocr->SetTitle(s); NewDocr->UpdateAllViews(0,WM_USER_NEWIMAGE); } CDemoDoc *NewDocg=(CDemoDoc*)((CDemoApp*)AfxGetApp())->demoTemplate->OpenDocumentFile(NULL); if (NewDocg) { NewDocg->image = newg; CString s; s.Format(_T("U Channel %d from %s"),((CDemoApp*)AfxGetApp())->m_nDocCount,GetTitle()); NewDocg->SetTitle(s); NewDocg->UpdateAllViews(0,WM_USER_NEWIMAGE); } CDemoDoc *NewDocb=(CDemoDoc*)((CDemoApp*)AfxGetApp())->demoTemplate->OpenDocumentFile(NULL); if (NewDocb) { NewDocb->image = newb; CString s; s.Format(_T("V Channel %d from %s"),((CDemoApp*)AfxGetApp())->m_nDocCount,GetTitle()); NewDocb->SetTitle(s); NewDocb->UpdateAllViews(0,WM_USER_NEWIMAGE); } } ////////////////////////////////////////////////////////////////////////////// void CDemoDoc::OnCximageSplithsl() { if (image==NULL) return; CxImage *newr = new CxImage(); CxImage *newg = new CxImage(); CxImage *newb = new CxImage(); Stopwatch(0); image->SplitHSL(newr,newg,newb); Stopwatch(1); UpdateStatusBar(); ((CDemoApp*)AfxGetApp())->m_nDocCount++; CDemoDoc *NewDocr=(CDemoDoc*)((CDemoApp*)AfxGetApp())->demoTemplate->OpenDocumentFile(NULL); if (NewDocr) { NewDocr->image = newr; CString s; s.Format(_T("Hue Channel %d from %s"),((CDemoApp*)AfxGetApp())->m_nDocCount,GetTitle()); NewDocr->SetTitle(s); NewDocr->UpdateAllViews(0,WM_USER_NEWIMAGE); } CDemoDoc *NewDocg=(CDemoDoc*)((CDemoApp*)AfxGetApp())->demoTemplate->OpenDocumentFile(NULL); if (NewDocg) { NewDocg->image = newg; CString s; s.Format(_T("Saturation Channel %d from %s"),((CDemoApp*)AfxGetApp())->m_nDocCount,GetTitle()); NewDocg->SetTitle(s); NewDocg->UpdateAllViews(0,WM_USER_NEWIMAGE); } CDemoDoc *NewDocb=(CDemoDoc*)((CDemoApp*)AfxGetApp())->demoTemplate->OpenDocumentFile(NULL); if (NewDocb) { NewDocb->image = newb; CString s; s.Format(_T("Lightness Channel %d from %s"),((CDemoApp*)AfxGetApp())->m_nDocCount,GetTitle()); NewDocb->SetTitle(s); NewDocb->UpdateAllViews(0,WM_USER_NEWIMAGE); } } ////////////////////////////////////////////////////////////////////////////// void CDemoDoc::OnCximageSplitcmyk() { if (image==NULL) return; CxImage *newc = new CxImage(); CxImage *newm = new CxImage(); CxImage *newy = new CxImage(); CxImage *newk = new CxImage(); Stopwatch(0); image->SplitCMYK(newc,newm,newy,newk); Stopwatch(1); UpdateStatusBar(); ((CDemoApp*)AfxGetApp())->m_nDocCount++; CDemoDoc *NewDocr=(CDemoDoc*)((CDemoApp*)AfxGetApp())->demoTemplate->OpenDocumentFile(NULL); if (NewDocr) { NewDocr->image = newc; CString s; s.Format(_T("C Channel %d from %s"),((CDemoApp*)AfxGetApp())->m_nDocCount,GetTitle()); NewDocr->SetTitle(s); NewDocr->UpdateAllViews(0,WM_USER_NEWIMAGE); } CDemoDoc *NewDocg=(CDemoDoc*)((CDemoApp*)AfxGetApp())->demoTemplate->OpenDocumentFile(NULL); if (NewDocg) { NewDocg->image = newm; CString s; s.Format(_T("M Channel %d from %s"),((CDemoApp*)AfxGetApp())->m_nDocCount,GetTitle()); NewDocg->SetTitle(s); NewDocg->UpdateAllViews(0,WM_USER_NEWIMAGE); } CDemoDoc *NewDocb=(CDemoDoc*)((CDemoApp*)AfxGetApp())->demoTemplate->OpenDocumentFile(NULL); if (NewDocb) { NewDocb->image = newy; CString s; s.Format(_T("Y Channel %d from %s"),((CDemoApp*)AfxGetApp())->m_nDocCount,GetTitle()); NewDocb->SetTitle(s); NewDocb->UpdateAllViews(0,WM_USER_NEWIMAGE); } CDemoDoc *NewDock=(CDemoDoc*)((CDemoApp*)AfxGetApp())->demoTemplate->OpenDocumentFile(NULL); if (NewDock) { NewDock->image = newk; CString s; s.Format(_T("K Channel %d from %s"),((CDemoApp*)AfxGetApp())->m_nDocCount,GetTitle()); NewDock->SetTitle(s); NewDock->UpdateAllViews(0,WM_USER_NEWIMAGE); } } ////////////////////////////////////////////////////////////////////////////// void CDemoDoc::OnCximagePseudocolors() { if (image==NULL) return; SubmitUndo(); if (!image->IsGrayScale()) image->GrayScale(); image->HuePalette(); /* POSITION pos = GetFirstViewPosition(); CDemoView* pView = (CDemoView*)GetNextView(pos); HDC srcDC = ::GetDC(pView->GetSafeHwnd()); HDC memDC = ::CreateCompatibleDC(srcDC); // copy the screen to the bitmap CSize sz(image->GetWidth(), image->GetHeight()); int xshift = 0, yshift = 0; HBITMAP bm =::CreateCompatibleBitmap(srcDC, sz.cx, sz.cy); HBITMAP oldbm = (HBITMAP)::SelectObject(memDC,bm); ::BitBlt(memDC, 0, 0, sz.cx, sz.cy, srcDC, xshift, yshift, SRCCOPY); // image->SetTransIndex(-1); // image->Draw(memDC); ::TextOut(memDC,10,10,_T("test"),4); CxImage newima; newima.CreateFromHBITMAP(bm); image->Transfer(newima); // free objects SelectObject(memDC,oldbm); DeleteObject(memDC);*/ UpdateAllViews(NULL,WM_USER_NEWIMAGE); } ////////////////////////////////////////////////////////////////////////////// void CDemoDoc::OnCximageFiltersColorize() { if (image==NULL) return; DlgColorize dlg; dlg.m_bHSL = theApp.m_Filters.ColorMode; dlg.m_blend = theApp.m_Filters.ColorHSL.rgbBlue; dlg.m_sat = theApp.m_Filters.ColorHSL.rgbGreen; dlg.m_hue = theApp.m_Filters.ColorHSL.rgbRed; dlg.m_b = theApp.m_Filters.ColorBlue; dlg.m_g = theApp.m_Filters.ColorGreen; dlg.m_r = theApp.m_Filters.ColorRed; dlg.m_sol = theApp.m_Filters.ColorSolarLevel; dlg.m_bLinked = theApp.m_Filters.ColorSolarLink; if (dlg.DoModal()==IDOK){ m_MenuCommand=ID_CXIMAGE_COLORIZE; theApp.m_Filters.ColorMode = dlg.m_bHSL; theApp.m_Filters.ColorHSL.rgbBlue = dlg.m_blend; theApp.m_Filters.ColorHSL.rgbGreen = dlg.m_sat; theApp.m_Filters.ColorHSL.rgbRed = dlg.m_hue; theApp.m_Filters.ColorBlue = dlg.m_b; theApp.m_Filters.ColorGreen = dlg.m_g; theApp.m_Filters.ColorRed = dlg.m_r; theApp.m_Filters.ColorSolarLevel = dlg.m_sol; theApp.m_Filters.ColorSolarLink = dlg.m_bLinked; hThread=(HANDLE)_beginthread(RunCxImageThread,0,this); } } ////////////////////////////////////////////////////////////////////////////// void CDemoDoc::OnCximageDarken() { m_MenuCommand=ID_CXIMAGE_DARKEN; hThread=(HANDLE)_beginthread(RunCxImageThread,0,this); } ////////////////////////////////////////////////////////////////////////////// void CDemoDoc::OnCximageLighten() { m_MenuCommand=ID_CXIMAGE_LIGHTEN; hThread=(HANDLE)_beginthread(RunCxImageThread,0,this); } ////////////////////////////////////////////////////////////////////////////// void CDemoDoc::OnCximageContrast() { m_MenuCommand=ID_CXIMAGE_CONTRAST; hThread=(HANDLE)_beginthread(RunCxImageThread,0,this); } ////////////////////////////////////////////////////////////////////////////// void CDemoDoc::OnCximageEmboss() { m_MenuCommand=ID_CXIMAGE_EMBOSS; hThread=(HANDLE)_beginthread(RunCxImageThread,0,this); } ////////////////////////////////////////////////////////////////////////////// void CDemoDoc::OnCximageBlur() { m_MenuCommand=ID_CXIMAGE_BLUR; hThread=(HANDLE)_beginthread(RunCxImageThread,0,this); } ////////////////////////////////////////////////////////////////////////////// void CDemoDoc::OnCximageDilate() { m_MenuCommand=ID_CXIMAGE_DILATE; hThread=(HANDLE)_beginthread(RunCxImageThread,0,this); } ////////////////////////////////////////////////////////////////////////////// void CDemoDoc::OnCximageEdge() { m_MenuCommand=ID_CXIMAGE_EDGE; hThread=(HANDLE)_beginthread(RunCxImageThread,0,this); } ////////////////////////////////////////////////////////////////////////////// void CDemoDoc::OnCximageErode() { m_MenuCommand=ID_CXIMAGE_ERODE; hThread=(HANDLE)_beginthread(RunCxImageThread,0,this); } ////////////////////////////////////////////////////////////////////////////// void CDemoDoc::OnCximageSharpen() { m_MenuCommand=ID_CXIMAGE_SHARPEN; hThread=(HANDLE)_beginthread(RunCxImageThread,0,this); } ////////////////////////////////////////////////////////////////////////////// void CDemoDoc::OnCximageSoften() { m_MenuCommand=ID_CXIMAGE_SOFTEN; hThread=(HANDLE)_beginthread(RunCxImageThread,0,this); } ////////////////////////////////////////////////////////////////////////////// void CDemoDoc::OnCximageCrop() { SubmitUndo(); RECT r; #ifdef VATI_EXTENSIONS // if there is a valid rectangle selection, then call the CropRotatedRectangle instead original Crop if (m_isRectSel && m_NumSel==5 ) { CPoint top; long height, width; float angle; int topcorner = -1; // get upperleft corner top.x = 999999; top.y = 999999; for(int i=0; i<4; i++) { if ( top.y >= m_Sel[i].y ) { if ( top.y == m_Sel[i].y && top.x < m_Sel[i].x ) continue; top.x = m_Sel[i].x; top.y = m_Sel[i].y; topcorner = i; } } // get side lengths (-1st and +1st indexes points to 2 sides) if ( topcorner > 0 && topcorner < 4 ) height = (long)LEN2D( top.x - m_Sel[topcorner-1].x, top.y - m_Sel[topcorner-1].y ); else if ( topcorner == 0 ) height = (long)LEN2D( top.x - m_Sel[3].x, top.y - m_Sel[3].y ); else return; // fatal prog error width = (long)LEN2D( top.x - m_Sel[topcorner+1].x, top.y - m_Sel[topcorner+1].y ); angle = (float)atan2( (float)(m_Sel[topcorner+1].y - top.y), (float)(m_Sel[topcorner+1].x - top.x) ); image->CropRotatedRectangle( top.x, top.y, width, height, angle ); } else // freehand selection { image->SelectionGetBox(r); r.bottom = image->GetHeight() - 1 -r.bottom; r.top = image->GetHeight() - 1 -r.top; image->Crop(r); } #else image->SelectionGetBox(r); r.bottom = image->GetHeight() - 1 -r.bottom; r.top = image->GetHeight() - 1 -r.top; image->Crop(r); #endif UpdateStatusBar(); // VAti - to refresh image size in the status bar UpdateAllViews(NULL,WM_USER_NEWIMAGE); } ////////////////////////////////////////////////////////////////////////////// void CDemoDoc::OnCximageRemovealphachannel() { SubmitUndo(); image->AlphaDelete(); image->AlphaSetMax(255); UpdateAllViews(NULL); } ////////////////////////////////////////////////////////////////////////////// void CDemoDoc::OnCximageOpacity() { if (image==NULL) return; DlgOpacity dlg; dlg.m_level=image->AlphaGetMax(); if (dlg.DoModal()==IDOK){ SubmitUndo(); if (!image->AlphaIsValid()){ image->AlphaCreate(); } image->AlphaSetMax(dlg.m_level); } UpdateAllViews(NULL); } ////////////////////////////////////////////////////////////////////////////// void CDemoDoc::OnCximageInvetalpha() { SubmitUndo(); image->AlphaInvert(); UpdateAllViews(NULL); } ////////////////////////////////////////////////////////////////////////////// void CDemoDoc::OnCximageAlphapalettetoggle() { SubmitUndo(); image->AlphaPaletteEnable(!image->AlphaPaletteIsEnabled()); UpdateAllViews(NULL); } ////////////////////////////////////////////////////////////////////////////// void CDemoDoc::OnCximageAlphastrip() { SubmitUndo(); SetCursor(LoadCursor(0,IDC_WAIT)); Stopwatch(0); RGBQUAD c={255,255,255,0}; image->SetTransColor(c); image->AlphaStrip(); Stopwatch(1); SetCursor(LoadCursor(0,IDC_ARROW)); UpdateStatusBar(); UpdateAllViews(NULL,WM_USER_NEWIMAGE); } ////////////////////////////////////////////////////////////////////////////// void CDemoDoc::OnCximageGamma() { if (image==NULL) return; DlgGamma dlg; dlg.m_gamma = theApp.m_Filters.GammaLevel; dlg.m_gammaR = theApp.m_Filters.GammaR; dlg.m_gammaG = theApp.m_Filters.GammaG; dlg.m_gammaB = theApp.m_Filters.GammaB; dlg.m_bGammaMode = theApp.m_Filters.GammaLink; if (dlg.DoModal()==IDOK){ m_MenuCommand=ID_CXIMAGE_GAMMA; theApp.m_Filters.GammaLevel = dlg.m_gamma; theApp.m_Filters.GammaR = dlg.m_gammaR; theApp.m_Filters.GammaG = dlg.m_gammaG; theApp.m_Filters.GammaB = dlg.m_gammaB; theApp.m_Filters.GammaLink = dlg.m_bGammaMode; hThread=(HANDLE)_beginthread(RunCxImageThread,0,this); } } ////////////////////////////////////////////////////////////////////////////// void CDemoDoc::OnCximageMedian() { m_MenuCommand=ID_CXIMAGE_MEDIAN; hThread=(HANDLE)_beginthread(RunCxImageThread,0,this); } ////////////////////////////////////////////////////////////////////////////// void CDemoDoc::OnCximageAddnoise() { m_MenuCommand=ID_CXIMAGE_ADDNOISE; hThread=(HANDLE)_beginthread(RunCxImageThread,0,this); } ////////////////////////////////////////////////////////////////////////////// void CDemoDoc::OnViewToolsMove() { m_tool=0; } ////////////////////////////////////////////////////////////////////////////// void CDemoDoc::OnUpdateViewToolsMove(CCmdUI* pCmdUI) { pCmdUI->SetCheck(m_tool==0); } ////////////////////////////////////////////////////////////////////////////// void CDemoDoc::OnViewToolsSelect() { m_tool=1; } ////////////////////////////////////////////////////////////////////////////// void CDemoDoc::OnUpdateViewToolsSelect(CCmdUI* pCmdUI) { pCmdUI->SetCheck(m_tool==1); } ////////////////////////////////////////////////////////////////////////////// void CDemoDoc::OnViewToolsZoom() { m_tool=2; } ////////////////////////////////////////////////////////////////////////////// void CDemoDoc::OnUpdateViewToolsZoom(CCmdUI* pCmdUI) { pCmdUI->SetCheck(m_tool==2); } ////////////////////////////////////////////////////////////////////////////// void CDemoDoc::OnViewToolsText() { if (image==NULL) return; DlgText dlg; #ifndef VATI_EXTENSIONS memcpy(&(dlg.m_font),&m_font,sizeof(m_font)); dlg.m_text=m_text; dlg.m_color=m_color; if (dlg.DoModal()==IDOK){ m_text=dlg.m_text; m_color=dlg.m_color; memcpy(&m_font,&(dlg.m_font),sizeof(m_font)); m_tool=3; } #else //pass all data about text memcpy( &(dlg.m_textdata), &theApp.m_text, sizeof(CxImage::CXTEXTINFO) ); if (dlg.DoModal()==IDOK) { //retrieve all data about text memcpy( &theApp.m_text, &(dlg.m_textdata), sizeof(CxImage::CXTEXTINFO) ); m_tool=3; } #endif } ////////////////////////////////////////////////////////////////////////////// void CDemoDoc::OnUpdateViewToolsText(CCmdUI* pCmdUI) { pCmdUI->SetCheck(m_tool==3); } ////////////////////////////////////////////////////////////////////////////// void CDemoDoc::OnUpdateViewPalette(CCmdUI* pCmdUI) { if(image==0 || hThread || image->GetNumColors()==0) pCmdUI->Enable(0); } ////////////////////////////////////////////////////////////////////////////// void CDemoDoc::OnViewPalette() { if (image==NULL) return; DlgPalette dlg; dlg.m_numcolors=image->GetNumColors(); memcpy(dlg.m_pal,image->GetPalette(),dlg.m_numcolors*sizeof(RGBQUAD)); if (dlg.DoModal()==IDOK){ if (dlg.m_changed){ SubmitUndo(); switch (dlg.m_replace){ case 1: { image->SetPalette(dlg.m_pal,dlg.m_numcolors); break; } case 2: { int bpp=image->GetBpp(); image->IncreaseBpp(24); image->DecreaseBpp(bpp,false,dlg.m_pal); break; } case 3: { int bpp=image->GetBpp(); image->IncreaseBpp(24); image->DecreaseBpp(bpp,true,dlg.m_pal); break; } } UpdateAllViews(NULL,WM_USER_NEWIMAGE); } } } ////////////////////////////////////////////////////////////////////////////// void CDemoDoc::OnCximageCombine() { if (image==NULL) return; DlgCombine dlg; if (dlg.DoModal()==IDOK){ SetCursor(LoadCursor(0,IDC_WAIT)); Stopwatch(0); CxImage *newr,*newg,*newb,*newa; newr=newg=newb=newa=NULL; newr = new CxImage(); switch(dlg.pChR){ case 0: newr->Copy(*(dlg.pDocR->GetImage()),1,0,0); newr->GrayScale(); break; case 1: dlg.pDocR->GetImage()->SplitRGB(newr,0,0); break; case 2: dlg.pDocR->GetImage()->SplitRGB(0,newr,0); break; case 3: dlg.pDocR->GetImage()->SplitRGB(0,0,newr); break; } newg = new CxImage(); switch(dlg.pChG){ case 0: newg->Copy(*(dlg.pDocG->GetImage()),1,0,0); newg->GrayScale(); break; case 1: dlg.pDocG->GetImage()->SplitRGB(newg,0,0); break; case 2: dlg.pDocG->GetImage()->SplitRGB(0,newg,0); break; case 3: dlg.pDocG->GetImage()->SplitRGB(0,0,newg); break; } newb = new CxImage(); switch(dlg.pChB){ case 0: newb->Copy(*(dlg.pDocB->GetImage()),1,0,0); newb->GrayScale(); break; case 1: dlg.pDocB->GetImage()->SplitRGB(newb,0,0); break; case 2: dlg.pDocB->GetImage()->SplitRGB(0,newb,0); break; case 3: dlg.pDocB->GetImage()->SplitRGB(0,0,newb); break; } if (dlg.pDocA){ newa = new CxImage(); switch(dlg.pChA){ case 0: newa->Copy(*(dlg.pDocA->GetImage()),1,0,0); newa->GrayScale(); break; case 1: dlg.pDocA->GetImage()->SplitRGB(newa,0,0); break; case 2: dlg.pDocA->GetImage()->SplitRGB(0,newa,0); break; case 3: dlg.pDocA->GetImage()->SplitRGB(0,0,newa); break; } } CxImage *mix = new CxImage(); mix->Combine(newr,newg,newb,newa,dlg.pChS); CDemoDoc *NewDocr=(CDemoDoc*)((CDemoApp*)AfxGetApp())->demoTemplate->OpenDocumentFile(NULL); if (NewDocr) { NewDocr->image = mix; CString s; s.Format(_T("NewImage%d"),((CDemoApp*)AfxGetApp())->m_nDocCount++); NewDocr->SetTitle(s); NewDocr->UpdateAllViews(0,WM_USER_NEWIMAGE); } delete newr; delete newg; delete newb; delete newa; Stopwatch(1); UpdateStatusBar(); SetCursor(LoadCursor(0,IDC_ARROW)); } } ////////////////////////////////////////////////////////////////////////////// void CDemoDoc::OnCximageFft() { if (image==NULL) return; DlgFFT dlg; if (dlg.DoModal()==IDOK){ SetCursor(LoadCursor(0,IDC_WAIT)); Stopwatch(0); CxImage *srcr,*srci,*dstr,*dsti,tmp; srcr = (dlg.pDocReal) ? dlg.pDocReal->GetImage() : 0; srci = (dlg.pDocImag) ? dlg.pDocImag->GetImage() : 0; if (srcr==0 && srci==0) return; if (srcr) dstr = new CxImage(*srcr,true,false,false); else dstr=0; if (srci) dsti = new CxImage(*srci,true,false,false); else dsti=0; if (dstr==0){ dstr = new CxImage(dsti->GetWidth(),dsti->GetHeight(),8); dstr->Clear(0); dstr->SetGrayPalette(); } if (dsti==0){ dsti = new CxImage(dstr->GetWidth(),dstr->GetHeight(),8); dsti->Clear(0); dsti->SetGrayPalette(); } tmp.FFT2(dstr,dsti,0,0,dlg.bInverse,dlg.bForceFFT!=0,dlg.bMagnitude!=0); ((CDemoApp*)AfxGetApp())->m_nDocCount++; CDemoDoc *NewDoci=(CDemoDoc*)((CDemoApp*)AfxGetApp())->demoTemplate->OpenDocumentFile(NULL); if (NewDoci) { NewDoci->image = dsti; CString s; if (dlg.bMagnitude){ s.Format(_T("FFT Phase %d"),((CDemoApp*)AfxGetApp())->m_nDocCount); } else { s.Format(_T("FFT Imag %d"),((CDemoApp*)AfxGetApp())->m_nDocCount); } NewDoci->SetTitle(s); NewDoci->UpdateAllViews(0,WM_USER_NEWIMAGE); } CDemoDoc *NewDocr=(CDemoDoc*)((CDemoApp*)AfxGetApp())->demoTemplate->OpenDocumentFile(NULL); if (NewDocr) { NewDocr->image = dstr; CString s; if (dlg.bMagnitude){ s.Format(_T("FFT Magnitude %d"),((CDemoApp*)AfxGetApp())->m_nDocCount); } else { s.Format(_T("FFT Real %d"),((CDemoApp*)AfxGetApp())->m_nDocCount); } NewDocr->SetTitle(s); NewDocr->UpdateAllViews(0,WM_USER_NEWIMAGE); } Stopwatch(1); UpdateStatusBar(); SetCursor(LoadCursor(0,IDC_ARROW)); } } ////////////////////////////////////////////////////////////////////////////// void CDemoDoc::OnCximageSplityiq() { if (image==NULL) return; CxImage *newr = new CxImage(); CxImage *newg = new CxImage(); CxImage *newb = new CxImage(); Stopwatch(0); image->SplitYIQ(newr,newg,newb); Stopwatch(1); UpdateStatusBar(); ((CDemoApp*)AfxGetApp())->m_nDocCount++; CDemoDoc *NewDocr=(CDemoDoc*)((CDemoApp*)AfxGetApp())->demoTemplate->OpenDocumentFile(NULL); if (NewDocr) { NewDocr->image = newr; CString s; s.Format(_T("Y Channel %d from %s"),((CDemoApp*)AfxGetApp())->m_nDocCount,GetTitle()); NewDocr->SetTitle(s); NewDocr->UpdateAllViews(0,WM_USER_NEWIMAGE); } CDemoDoc *NewDocg=(CDemoDoc*)((CDemoApp*)AfxGetApp())->demoTemplate->OpenDocumentFile(NULL); if (NewDocg) { NewDocg->image = newg; CString s; s.Format(_T("I Channel %d from %s"),((CDemoApp*)AfxGetApp())->m_nDocCount,GetTitle()); NewDocg->SetTitle(s); NewDocg->UpdateAllViews(0,WM_USER_NEWIMAGE); } CDemoDoc *NewDocb=(CDemoDoc*)((CDemoApp*)AfxGetApp())->demoTemplate->OpenDocumentFile(NULL); if (NewDocb) { NewDocb->image = newb; CString s; s.Format(_T("Q Channel %d from %s"),((CDemoApp*)AfxGetApp())->m_nDocCount,GetTitle()); NewDocb->SetTitle(s); NewDocb->UpdateAllViews(0,WM_USER_NEWIMAGE); } } ////////////////////////////////////////////////////////////////////////////// void CDemoDoc::OnCximageSplitxyz() { if (image==NULL) return; CxImage *newr = new CxImage(); CxImage *newg = new CxImage(); CxImage *newb = new CxImage(); Stopwatch(0); image->SplitXYZ(newr,newg,newb); Stopwatch(1); UpdateStatusBar(); ((CDemoApp*)AfxGetApp())->m_nDocCount++; CDemoDoc *NewDocr=(CDemoDoc*)((CDemoApp*)AfxGetApp())->demoTemplate->OpenDocumentFile(NULL); if (NewDocr) { NewDocr->image = newr; CString s; s.Format(_T("X Channel %d from %s"),((CDemoApp*)AfxGetApp())->m_nDocCount,GetTitle()); NewDocr->SetTitle(s); NewDocr->UpdateAllViews(0,WM_USER_NEWIMAGE); } CDemoDoc *NewDocg=(CDemoDoc*)((CDemoApp*)AfxGetApp())->demoTemplate->OpenDocumentFile(NULL); if (NewDocg) { NewDocg->image = newg; CString s; s.Format(_T("Y Channel %d from %s"),((CDemoApp*)AfxGetApp())->m_nDocCount,GetTitle()); NewDocg->SetTitle(s); NewDocg->UpdateAllViews(0,WM_USER_NEWIMAGE); } CDemoDoc *NewDocb=(CDemoDoc*)((CDemoApp*)AfxGetApp())->demoTemplate->OpenDocumentFile(NULL); if (NewDocb) { NewDocb->image = newb; CString s; s.Format(_T("Z Channel %d from %s"),((CDemoApp*)AfxGetApp())->m_nDocCount,GetTitle()); NewDocb->SetTitle(s); NewDocb->UpdateAllViews(0,WM_USER_NEWIMAGE); } } ////////////////////////////////////////////////////////////////////////////// void CDemoDoc::OnCximageRepair() { if (image==NULL) return; DlgRepair dlg; dlg.m_iterations = 2; dlg.m_radius = (float)0.25; if (dlg.DoModal()==IDOK){ SubmitUndo(); SetCursor(LoadCursor(0,IDC_WAIT)); Stopwatch(0); image->Repair(dlg.m_radius,dlg.m_iterations,dlg.m_ncs); Stopwatch(1); UpdateAllViews(NULL); UpdateStatusBar(); SetCursor(LoadCursor(0,IDC_ARROW)); } } ////////////////////////////////////////////////////////////////////////////// void CDemoDoc::OnCximageAlphachannelSplit() { if (image==NULL) return; CxImage *newa = new CxImage(); Stopwatch(0); image->AlphaSplit(newa); Stopwatch(1); UpdateStatusBar(); ((CDemoApp*)AfxGetApp())->m_nDocCount++; CDemoDoc *NewDocr=(CDemoDoc*)((CDemoApp*)AfxGetApp())->demoTemplate->OpenDocumentFile(NULL); if (NewDocr) { NewDocr->image = newa; CString s; s.Format(_T("Alpha Channel %d from %s"),((CDemoApp*)AfxGetApp())->m_nDocCount,GetTitle()); NewDocr->SetTitle(s); NewDocr->UpdateAllViews(0,WM_USER_NEWIMAGE); } } ////////////////////////////////////////////////////////////////////////////// void CDemoDoc::OnCximageAlphaCreate() { if (image==NULL) return; CxImage gray(*image,true,false,false); gray.IncreaseBpp(8); gray.Negative(); gray.GrayScale(); image->AlphaSet(gray); UpdateAllViews(NULL); } ////////////////////////////////////////////////////////////////////////////// void CDemoDoc::OnCximageFiltersLog() { m_MenuCommand=ID_CXIMAGE_HISTOGRAM_LOG; hThread=(HANDLE)_beginthread(RunCxImageThread,0,this); } ////////////////////////////////////////////////////////////////////////////// void CDemoDoc::OnCximageFiltersRoot() { m_MenuCommand=ID_CXIMAGE_HISTOGRAM_ROOT; hThread=(HANDLE)_beginthread(RunCxImageThread,0,this); } ////////////////////////////////////////////////////////////////////////////// void CDemoDoc::OnCximageHistogramEqualize() { m_MenuCommand=ID_CXIMAGE_HISTOGRAM_EQUALIZE; hThread=(HANDLE)_beginthread(RunCxImageThread,0,this); } ////////////////////////////////////////////////////////////////////////////// void CDemoDoc::OnCximageHistogramNormalize() { m_MenuCommand=ID_CXIMAGE_HISTOGRAM_NORMALIZE; hThread=(HANDLE)_beginthread(RunCxImageThread,0,this); } ////////////////////////////////////////////////////////////////////////////// void CDemoDoc::OnCximageHistogramStretch() { m_MenuCommand=ID_CXIMAGE_HISTOGRAM_STRETCH; hThread=(HANDLE)_beginthread(RunCxImageThread,0,this); } ////////////////////////////////////////////////////////////////////////////// void CDemoDoc::OnCximageGaussian3x3() { m_MenuCommand=ID_CXIMAGE_GAUSSIAN3X3; hThread=(HANDLE)_beginthread(RunCxImageThread,0,this); } ////////////////////////////////////////////////////////////////////////////// void CDemoDoc::OnCximageGaussian5x5() { m_MenuCommand=ID_CXIMAGE_GAUSSIAN5X5; hThread=(HANDLE)_beginthread(RunCxImageThread,0,this); } ////////////////////////////////////////////////////////////////////////////// void CDemoDoc::OnCximageContour() { m_MenuCommand=ID_CXIMAGE_CONTOUR; hThread=(HANDLE)_beginthread(RunCxImageThread,0,this); } ////////////////////////////////////////////////////////////////////////////// void CDemoDoc::OnCximageLesscontrast() { m_MenuCommand=ID_CXIMAGE_LESSCONTRAST; hThread=(HANDLE)_beginthread(RunCxImageThread,0,this); } ////////////////////////////////////////////////////////////////////////////// void CDemoDoc::OnCximageJitter() { m_MenuCommand=ID_CXIMAGE_JITTER; hThread=(HANDLE)_beginthread(RunCxImageThread,0,this); } ////////////////////////////////////////////////////////////////////////////// void CDemoDoc::OnFiltersMix() { if (image==NULL) return; DlgMix dlg; if (dlg.DoModal()==IDOK){ SetCursor(LoadCursor(0,IDC_WAIT)); Stopwatch(0); CxImage *src, *dst, *tmp; src = (dlg.pDocSrc) ? dlg.pDocSrc->GetImage() : 0; dst = (dlg.pDocDst) ? dlg.pDocDst->GetImage() : 0; if (src==0 && dst==0) return; tmp = new CxImage(*dst); tmp->Mix(*src,(CxImage::ImageOpType)dlg.OpType,dlg.m_xoffset,dlg.m_yoffset,dlg.m_mixalpha!=0); ((CDemoApp*)AfxGetApp())->m_nDocCount++; CDemoDoc *NewDoci=(CDemoDoc*)((CDemoApp*)AfxGetApp())->demoTemplate->OpenDocumentFile(NULL); if (NewDoci) { NewDoci->image = tmp; CString s; s.Format(_T("Mix %d"),((CDemoApp*)AfxGetApp())->m_nDocCount); NewDoci->SetTitle(s); NewDoci->UpdateAllViews(0,WM_USER_NEWIMAGE); } Stopwatch(1); UpdateStatusBar(); SetCursor(LoadCursor(0,IDC_ARROW)); } } ////////////////////////////////////////////////////////////////////////////// void CDemoDoc::OnCximageCircletransformCylinder() { m_MenuCommand=ID_CXIMAGE_CIRCLETRANSFORM_CYLINDER; hThread=(HANDLE)_beginthread(RunCxImageThread,0,this); } ////////////////////////////////////////////////////////////////////////////// void CDemoDoc::OnCximageCircletransformPinch() { m_MenuCommand=ID_CXIMAGE_CIRCLETRANSFORM_PINCH; hThread=(HANDLE)_beginthread(RunCxImageThread,0,this); } ////////////////////////////////////////////////////////////////////////////// void CDemoDoc::OnCximageCircletransformPunch() { m_MenuCommand=ID_CXIMAGE_CIRCLETRANSFORM_PUNCH; hThread=(HANDLE)_beginthread(RunCxImageThread,0,this); } ////////////////////////////////////////////////////////////////////////////// void CDemoDoc::OnCximageCircletransformSwirl() { m_MenuCommand=ID_CXIMAGE_CIRCLETRANSFORM_SWIRL; hThread=(HANDLE)_beginthread(RunCxImageThread,0,this); } ////////////////////////////////////////////////////////////////////////////// void CDemoDoc::OnCximageCircletransformBathroom() { m_MenuCommand=ID_CXIMAGE_CIRCLETRANSFORM_BATHROOM; hThread=(HANDLE)_beginthread(RunCxImageThread,0,this); } ////////////////////////////////////////////////////////////////////////////// void CDemoDoc::OnCximageHistogramStretch1() { m_MenuCommand=ID_CXIMAGE_HISTOGRAM_STRETCH1; hThread=(HANDLE)_beginthread(RunCxImageThread,0,this); } ////////////////////////////////////////////////////////////////////////////// void CDemoDoc::OnCximageHistogramStretch2() { m_MenuCommand=ID_CXIMAGE_HISTOGRAM_STRETCH2; hThread=(HANDLE)_beginthread(RunCxImageThread,0,this); } ////////////////////////////////////////////////////////////////////////////// void CDemoDoc::OnFiltersNonlinearEdge() { m_MenuCommand=ID_FILTERS_NONLINEAR_EDGE; hThread=(HANDLE)_beginthread(RunCxImageThread,0,this); } ////////////////////////////////////////////////////////////////////////////// void CDemoDoc::OnCximageSkew() { if (image==NULL) return; DlgSkew dlg; dlg.m_w = image->GetWidth(); dlg.m_h = image->GetHeight(); dlg.m_skewx = theApp.m_Filters.SkewX; dlg.m_skewy = theApp.m_Filters.SkewY; dlg.m_pivotx = theApp.m_Filters.SkewPivotX; dlg.m_pivoty = theApp.m_Filters.SkewPivotY; dlg.m_bEnableInterpolation = theApp.m_Filters.SkewInterp; if (dlg.DoModal()==IDOK){ m_MenuCommand=ID_CXIMAGE_SKEW; theApp.m_Filters.SkewX = dlg.m_skewx; theApp.m_Filters.SkewY = dlg.m_skewy; theApp.m_Filters.SkewSlopeX = dlg.m_slopex; theApp.m_Filters.SkewSlopeY = dlg.m_slopey; theApp.m_Filters.SkewPivotX = dlg.m_pivotx; theApp.m_Filters.SkewPivotY = dlg.m_pivoty; theApp.m_Filters.SkewInterp = dlg.m_bEnableInterpolation; hThread=(HANDLE)_beginthread(RunCxImageThread,0,this); } } ////////////////////////////////////////////////////////////////////////////// void CDemoDoc::OnUpdateViewToolsTracker(CCmdUI* pCmdUI) { pCmdUI->SetCheck(m_tool==4); } ////////////////////////////////////////////////////////////////////////////// void CDemoDoc::OnViewToolsTracker() { m_tool=4; } ////////////////////////////////////////////////////////////////////////////// void CDemoDoc::OnJpegcompression() { if (image==NULL) return; DlgJpeg dlg; dlg.m_quality=50.0f; if (dlg.DoModal()==IDOK){ SetCursor(LoadCursor(0,IDC_WAIT)); Stopwatch(0); CxImage *tmp; tmp = new CxImage(*image); if (!tmp->IsGrayScale()) tmp->IncreaseBpp(24); tmp->SetTransIndex(-1); tmp->SetJpegQualityF(dlg.m_quality); DWORD imagetype = 0; #if CXIMAGE_SUPPORT_JPG if (dlg.m_format==0) imagetype = CXIMAGE_FORMAT_JPG; #endif #if CXIMAGE_SUPPORT_JPC if (dlg.m_format==1) imagetype = CXIMAGE_FORMAT_JPC; #endif CxMemFile tmpFile; tmpFile.Open(); if (tmp->Encode(&tmpFile,imagetype)){ tmpFile.Seek(0,SEEK_SET); if (tmp->Decode(&tmpFile,imagetype)){ ((CDemoApp*)AfxGetApp())->m_nDocCount++; CDemoDoc *NewDoc=(CDemoDoc*)((CDemoApp*)AfxGetApp())->demoTemplate->OpenDocumentFile(NULL); if (NewDoc) { NewDoc->image = tmp; CString s; s.Format(_T("Jpeg compr. %d, q = %.3f, size = %d"), ((CDemoApp*)AfxGetApp())->m_nDocCount, (double)dlg.m_quality, tmpFile.Size()); NewDoc->SetTitle(s); NewDoc->UpdateAllViews(0,WM_USER_NEWIMAGE); } } else { CString s = tmp->GetLastError(); AfxMessageBox(s); delete tmp; } } else { CString s = tmp->GetLastError(); AfxMessageBox(s); delete tmp; } Stopwatch(1); UpdateStatusBar(); SetCursor(LoadCursor(0,IDC_ARROW)); } } ////////////////////////////////////////////////////////////////////////////// void CDemoDoc::OnViewSmooth() { m_bSmoothDisplay = !m_bSmoothDisplay; UpdateAllViews(NULL); } ////////////////////////////////////////////////////////////////////////////// void CDemoDoc::OnUpdateViewSmooth(CCmdUI* pCmdUI) { pCmdUI->SetCheck(m_bSmoothDisplay); } ////////////////////////////////////////////////////////////////////////////// void CDemoDoc::OnFiltersDataext() { if (image==NULL) return; DlgDataExt dlg; dlg.m_image = image; dlg.m_Ymin = dlgDataExtInfos.fYmin; dlg.m_Ymax = dlgDataExtInfos.fYmax; dlg.m_Xmin = dlgDataExtInfos.fXmin; dlg.m_Xmax = dlgDataExtInfos.fXmax; dlg.m_thresh = dlgDataExtInfos.nThresh; dlg.m_color = dlgDataExtInfos.cColor; dlg.m_bMinmax = dlgDataExtInfos.bMinmax; dlg.m_bAvg = dlgDataExtInfos.bAvg; dlg.m_bDetect = dlgDataExtInfos.bDetect; dlg.m_bLogXaxis = dlgDataExtInfos.bLogXaxis; dlg.m_bLogYaxis = dlgDataExtInfos.bLogYaxis; if (dlg.DoModal()==IDOK){ dlgDataExtInfos.fYmin = dlg.m_Ymin; dlgDataExtInfos.fYmax = dlg.m_Ymax; dlgDataExtInfos.fXmin = dlg.m_Xmin; dlgDataExtInfos.fXmax = dlg.m_Xmax ; dlgDataExtInfos.nThresh = dlg.m_thresh; dlgDataExtInfos.cColor = dlg.m_color; dlgDataExtInfos.bMinmax = dlg.m_bMinmax; dlgDataExtInfos.bAvg = dlg.m_bAvg; dlgDataExtInfos.bDetect = dlg.m_bDetect; dlgDataExtInfos.bLogXaxis = dlg.m_bLogXaxis; dlgDataExtInfos.bLogYaxis = dlg.m_bLogYaxis; } } ////////////////////////////////////////////////////////////////////////////// void CDemoDoc::OnCximageUnsharpmask() { m_MenuCommand=ID_CXIMAGE_UNSHARPMASK; hThread=(HANDLE)_beginthread(RunCxImageThread,0,this); } ////////////////////////////////////////////////////////////////////////////// void CDemoDoc::RegionRotateLeft() { long i,n; long h=image->GetHeight(); for(i=0;i<m_NumSel;i++){ n = m_Sel[i].x; m_Sel[i].x = m_Sel[i].y; m_Sel[i].y = h-1-n; } } ////////////////////////////////////////////////////////////////////////////// void CDemoDoc::RegionRotateRight() { long i,n; long w=image->GetWidth(); for(i=0;i<m_NumSel;i++){ n = m_Sel[i].y; m_Sel[i].y = m_Sel[i].x; m_Sel[i].x = w-1-n; } } ////////////////////////////////////////////////////////////////////////////// void CDemoDoc::OnCximageTextblur() { m_MenuCommand=ID_CXIMAGE_TEXTBLUR; hThread=(HANDLE)_beginthread(RunCxImageThread,0,this); } ////////////////////////////////////////////////////////////////////////////// void CDemoDoc::OnCximageRedeyeremove() { m_MenuCommand=ID_CXIMAGE_REDEYEREMOVE; hThread=(HANDLE)_beginthread(RunCxImageThread,0,this); } ////////////////////////////////////////////////////////////////////////////// void CDemoDoc::OnCximageBlurselborder() { m_MenuCommand=ID_CXIMAGE_BLURSELBORDER; hThread=(HANDLE)_beginthread(RunCxImageThread,0,this); } ////////////////////////////////////////////////////////////////////////////// void CDemoDoc::OnCximageSelectiveblur() { m_MenuCommand=ID_CXIMAGE_SELECTIVEBLUR; hThread=(HANDLE)_beginthread(RunCxImageThread,0,this); } ////////////////////////////////////////////////////////////////////////////// /*void CDemoDoc::OnFiltersSka280x350() { if (image==NULL) return; SubmitUndo(); image->IncreaseBpp(24); if (image->GetWidth()<280 && image->GetHeight()<350){ image->Resample2((image->GetWidth()*350)/image->GetHeight(),350); } RGBQUAD canvas = {0,0,0,0}; image->Thumbnail(280,350,canvas); long colors=232; RGBQUAD* ppal = NULL; CQuantizer q(colors,(colors>16?7:8)); q.ProcessImage(image->GetDIB()); ppal=(RGBQUAD*)calloc(256*sizeof(RGBQUAD),1); q.SetColorTable(ppal); int idx=0; for(; colors>0;colors--){ ppal[colors+23]=ppal[colors]; idx++; } const BYTE data[96] = { 0x00,0x00,0x00,0x00, 0xA8,0x00,0x00,0x00, 0x00,0xA8,0x00,0x00, 0xA8,0xA8,0x00,0x00, 0x00,0x00,0xA8,0x00, 0xA8,0x00,0xA8,0x00, 0x00,0x54,0xA8,0x00, 0xA8,0xA8,0xA8,0x00, 0x54,0x54,0x54,0x00, 0xFF,0x54,0x54,0x00, 0x54,0xFF,0x54,0x00, 0xFF,0xFF,0x54,0x00, 0x54,0x54,0xFF,0x00, 0xFF,0x54,0xFF,0x00, 0x54,0xFF,0xFF,0x00, 0xFF,0xFF,0xFF,0x00, 0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00 }; memcpy(ppal,data,96); image->DecreaseBpp(8,1,ppal,256); free(ppal); image->SetType(CXIMAGE_FORMAT_SKA); UpdateAllViews(0,WM_USER_NEWIMAGE); UpdateStatusBar(); }*/ ////////////////////////////////////////////////////////////////////////////// void CDemoDoc::OnCximageGettransparencymask() { if (image==NULL) return; CxImage *newa = new CxImage(); Stopwatch(0); image->GetTransparentMask(newa); Stopwatch(1); UpdateStatusBar(); ((CDemoApp*)AfxGetApp())->m_nDocCount++; CDemoDoc *NewDocr=(CDemoDoc*)((CDemoApp*)AfxGetApp())->demoTemplate->OpenDocumentFile(NULL); if (NewDocr) { NewDocr->image = newa; CString s; s.Format(_T("Transparency mask %d from %s"),((CDemoApp*)AfxGetApp())->m_nDocCount,GetTitle()); NewDocr->SetTitle(s); NewDocr->UpdateAllViews(0,WM_USER_NEWIMAGE); } } ////////////////////////////////////////////////////////////////////////////// void CDemoDoc::OnColorsCountcolors() { if (image==NULL) return; SetCursor(LoadCursor(0,IDC_WAIT)); Stopwatch(0); CQuantizer q(16777216,8); q.ProcessImage(image->GetDIB()); Stopwatch(1); UpdateStatusBar(); SetCursor(LoadCursor(0,IDC_ARROW)); CString s; s.Format(_T("The number of colors in the active image is: %d"), q.GetColorCount()); AfxMessageBox(s); } ////////////////////////////////////////////////////////////////////////////// void CDemoDoc::OnFiltersLinearCustom() { // <Priyank Bolia> priyank_bolia@yahoo.com // TODO: Add your command handler code here if (image==NULL) return; DlgCustomFilter dlg; memcpy(dlg.dlgkernel,theApp.m_Filters.Kernel5x5,25*sizeof(long)); dlg.m_kSize = theApp.m_Filters.kSize; dlg.m_EditBias = theApp.m_Filters.kBias; dlg.m_EditDivisor = theApp.m_Filters.kDivisor; if (dlg.DoModal()==IDOK){ m_MenuCommand=ID_FILTERS_LINEAR_CUSTOM; theApp.m_Filters.kDivisor = dlg.m_EditDivisor; theApp.m_Filters.kBias = dlg.m_EditBias; theApp.m_Filters.kSize = dlg.m_kSize; memcpy(theApp.m_Filters.Kernel5x5,dlg.dlgkernel,25*sizeof(long)); theApp.m_Filters.Kernel3x3[0]=(long)dlg.dlgkernel[6]; theApp.m_Filters.Kernel3x3[1]=(long)dlg.dlgkernel[7]; theApp.m_Filters.Kernel3x3[2]=(long)dlg.dlgkernel[8]; theApp.m_Filters.Kernel3x3[3]=(long)dlg.dlgkernel[11]; theApp.m_Filters.Kernel3x3[4]=(long)dlg.dlgkernel[12]; theApp.m_Filters.Kernel3x3[5]=(long)dlg.dlgkernel[13]; theApp.m_Filters.Kernel3x3[6]=(long)dlg.dlgkernel[16]; theApp.m_Filters.Kernel3x3[7]=(long)dlg.dlgkernel[17]; theApp.m_Filters.Kernel3x3[8]=(long)dlg.dlgkernel[18]; hThread=(HANDLE)_beginthread(RunCxImageThread,0,this); } } ////////////////////////////////////////////////////////////////////////////// void CDemoDoc::OnCximageCanvassize() { if (image==NULL) return; DlgExpand dlg; dlg.m_Mode = theApp.m_Filters.CanvasMode; dlg.m_CenterH = theApp.m_Filters.CanvasCenterH; dlg.m_CenterV = theApp.m_Filters.CanvasCenterV; dlg.m_KeepRatio = theApp.m_Filters.CanvasKeepRatio; dlg.m_UseImageBkg = theApp.m_Filters.CanvasUseImageBkg; dlg.m_color = theApp.m_Filters.CanvasBkg; dlg.m_newwidth = theApp.m_Filters.CanvasW; dlg.m_newheight = theApp.m_Filters.CanvasH; dlg.m_left = theApp.m_Filters.CanvasLeft; dlg.m_right = theApp.m_Filters.CanvasRight; dlg.m_top = theApp.m_Filters.CanvasTop; dlg.m_bottom = theApp.m_Filters.CanvasBottom; if (dlg.m_newwidth < (long)image->GetWidth()) dlg.m_newwidth = (long)image->GetWidth(); if (dlg.m_newheight < (long)image->GetHeight()) dlg.m_newheight = (long)image->GetHeight(); dlg.m_ratio = ((float)image->GetWidth())/((float)image->GetHeight()); if (dlg.DoModal()==IDOK){ m_MenuCommand=ID_CXIMAGE_CANVASSIZE; theApp.m_Filters.CanvasMode = dlg.m_Mode; theApp.m_Filters.CanvasCenterH = dlg.m_CenterH; theApp.m_Filters.CanvasCenterV = dlg.m_CenterV; theApp.m_Filters.CanvasKeepRatio = dlg.m_KeepRatio; theApp.m_Filters.CanvasUseImageBkg = dlg.m_UseImageBkg; theApp.m_Filters.CanvasBkg = dlg.m_color; theApp.m_Filters.CanvasW = dlg.m_newwidth; theApp.m_Filters.CanvasH = dlg.m_newheight; theApp.m_Filters.CanvasLeft = dlg.m_left; theApp.m_Filters.CanvasRight = dlg.m_right; theApp.m_Filters.CanvasTop = dlg.m_top; theApp.m_Filters.CanvasBottom = dlg.m_bottom; if (dlg.m_Mode == 0 && ((dlg.m_newwidth < (long)image->GetWidth()) || (dlg.m_newheight < (long)image->GetHeight()))){ AfxMessageBox(_T("New canvas size must be greater than the original")); return; } if (dlg.m_Mode == 1 && (dlg.m_left<0 || dlg.m_right<0 || dlg.m_top<0 || dlg.m_bottom<0)){ AfxMessageBox(_T("New canvas size must be greater than the original")); return; } hThread=(HANDLE)_beginthread(RunCxImageThread,0,this); } } ////////////////////////////////////////////////////////////////////////////// void CDemoDoc::OnUpdateViewToolsFloodfill(CCmdUI* pCmdUI) { pCmdUI->SetCheck(m_tool==5); DlgFloodFill* pDlg = ((CMainFrame *)(AfxGetApp()->m_pMainWnd))->m_pDlgFlood; if (pDlg && pDlg->GetSafeHwnd() && m_tool!=5){ pDlg->ShowWindow(SW_HIDE); } } ////////////////////////////////////////////////////////////////////////////// void CDemoDoc::OnViewToolsFloodfill() { m_tool=5; DlgFloodFill* pDlg = ((CMainFrame *)(AfxGetApp()->m_pMainWnd))->m_pDlgFlood; if (pDlg){ if (pDlg->GetSafeHwnd()==0){ pDlg->m_color = RGB(theApp.m_FloodColor.rgbRed, theApp.m_FloodColor.rgbGreen, theApp.m_FloodColor.rgbBlue); pDlg->m_tol = theApp.m_FloodTolerance; pDlg->m_opacity = theApp.m_FloodOpacity; pDlg->m_select = theApp.m_FloodSelect; pDlg->Create(); } else { pDlg->ShowWindow(SW_SHOW); } } } ////////////////////////////////////////////////////////////////////////////// void CDemoDoc::OnCximageRemoveselection() { if (image==NULL) return; image->SelectionDelete(); POSITION pos = GetFirstViewPosition(); CDemoView *pView = (CDemoView *)GetNextView(pos); if (pView) pView->KillTimer(1); pView->m_SelShift=0; m_NumSel=0; UpdateAllViews(NULL); } ////////////////////////////////////////////////////////////////////////////// void CDemoDoc::OnColorsMoresaturationhsl() { m_MenuCommand=ID_COLORS_MORESATURATIONHSL; hThread=(HANDLE)_beginthread(RunCxImageThread,0,this); } ////////////////////////////////////////////////////////////////////////////// void CDemoDoc::OnColorsMoresaturationyuv() { m_MenuCommand=ID_COLORS_MORESATURATIONYUV; hThread=(HANDLE)_beginthread(RunCxImageThread,0,this); } ////////////////////////////////////////////////////////////////////////////// void CDemoDoc::OnColorsLesssaturation() { m_MenuCommand=ID_COLORS_LESSSATURATION; hThread=(HANDLE)_beginthread(RunCxImageThread,0,this); } ////////////////////////////////////////////////////////////////////////////// void CDemoDoc::OnColorsHistogramFullsaturation() { m_MenuCommand=ID_COLORS_HISTOGRAM_FULLSATURATION; hThread=(HANDLE)_beginthread(RunCxImageThread,0,this); } ////////////////////////////////////////////////////////////////////////////// void CDemoDoc::OnColorsHistogramHalfsaturation() { m_MenuCommand=ID_COLORS_HISTOGRAM_HALFSATURATION; hThread=(HANDLE)_beginthread(RunCxImageThread,0,this); } ////////////////////////////////////////////////////////////////////////////// void CDemoDoc::OnCximageHistogramStretcht0() { m_MenuCommand=ID_CXIMAGE_HISTOGRAM_STRETCHT0; hThread=(HANDLE)_beginthread(RunCxImageThread,0,this); } ////////////////////////////////////////////////////////////////////////////// void CDemoDoc::OnCximageHistogramStretcht1() { m_MenuCommand=ID_CXIMAGE_HISTOGRAM_STRETCHT1; hThread=(HANDLE)_beginthread(RunCxImageThread,0,this); } ////////////////////////////////////////////////////////////////////////////// void CDemoDoc::OnCximageHistogramStretcht2() { m_MenuCommand=ID_CXIMAGE_HISTOGRAM_STRETCHT2; hThread=(HANDLE)_beginthread(RunCxImageThread,0,this); } ////////////////////////////////////////////////////////////////////////////// void CDemoDoc::OnColorsAdaptivethreshold() { m_MenuCommand=ID_COLORS_ADAPTIVETHRESHOLD; hThread=(HANDLE)_beginthread(RunCxImageThread,0,this); } ////////////////////////////////////////////////////////////////////////////// void CDemoDoc::OnViewPreviousframe() { long m = image->GetNumFrames(); long n = image->GetFrame()-1; if (n<0) n=m-1; if (image->GetFrame(n)) image->Copy(*image->GetFrame(n)); image->SetFrame(n); UpdateAllViews(NULL); } ////////////////////////////////////////////////////////////////////////////// void CDemoDoc::OnViewNextframe() { long m = image->GetNumFrames(); long n = image->GetFrame()+1; if (n>=m) n=0; if (image->GetFrame(n)) image->Copy(*image->GetFrame(n)); image->SetFrame(n); UpdateAllViews(NULL); } ////////////////////////////////////////////////////////////////////////////// void CDemoDoc::OnUpdateViewPlayanimation(CCmdUI* pCmdUI) { if(image==0 || hThread || image->GetFrame(0)==0) pCmdUI->Enable(0); pCmdUI->SetCheck(m_playanimation); } ////////////////////////////////////////////////////////////////////////////// void CDemoDoc::OnViewPlayanimation() { m_playanimation = 1-m_playanimation; POSITION pos = GetFirstViewPosition(); CDemoView *pView = (CDemoView *)GetNextView(pos); if (pView){ if (m_playanimation){ pView->SetTimer(2,200,NULL); } else { pView->KillTimer(2); } } } ////////////////////////////////////////////////////////////////////////////// void CDemoDoc::PlayNextFrame() { POSITION pos = GetFirstViewPosition(); CDemoView *pView = (CDemoView *)GetNextView(pos); if (pView && image){ pView->KillTimer(2); pView->SetTimer(2,10*max(1,image->GetFrameDelay()),NULL); } OnViewNextframe(); } ////////////////////////////////////////////////////////////////////////////// void CDemoDoc::OnFiltersAddshadow() { if (image==NULL) return; DlgShadow dlg; dlg.m_x = theApp.m_Filters.ShadowX; dlg.m_y = theApp.m_Filters.ShadowY; dlg.m_radius = theApp.m_Filters.ShadowR; dlg.m_shadow = theApp.m_Filters.ShadowColor; dlg.m_bkg = theApp.m_Filters.ShadowBkg; dlg.m_intensity = theApp.m_Filters.ShadowIntensity; dlg.m_relative = theApp.m_Filters.ShadowRelative; if (dlg.DoModal()==IDOK){ theApp.m_Filters.ShadowX = dlg.m_x; theApp.m_Filters.ShadowY = dlg.m_y; theApp.m_Filters.ShadowR = dlg.m_radius; theApp.m_Filters.ShadowColor = dlg.m_shadow; theApp.m_Filters.ShadowBkg = dlg.m_bkg; theApp.m_Filters.ShadowIntensity = dlg.m_intensity; theApp.m_Filters.ShadowRelative = dlg.m_relative; SetCursor(LoadCursor(0,IDC_WAIT)); Stopwatch(0); RGBQUAD c0 = CxImage::RGBtoRGBQUAD(theApp.m_Filters.ShadowColor); RGBQUAD c1 = CxImage::RGBtoRGBQUAD(theApp.m_Filters.ShadowBkg); CxImage *mix = new CxImage(*image); mix->IncreaseBpp(24); mix->SelectionClear(); mix->SelectionAddColor(c1); CxImage iShadow; mix->SelectionSplit(&iShadow); mix->SelectionDelete(); if (theApp.m_Filters.ShadowRelative){ CxImage gray(*image); gray.GrayScale(); iShadow.Mix(gray,CxImage::OpOr); } iShadow.GaussianBlur(theApp.m_Filters.ShadowR); for (int n = 0; n<256; n++){ BYTE r = (BYTE)(c1.rgbRed + ((theApp.m_Filters.ShadowIntensity*n*((long)c0.rgbRed - (long)c1.rgbRed))>>16)); BYTE g = (BYTE)(c1.rgbGreen + ((theApp.m_Filters.ShadowIntensity*n*((long)c0.rgbGreen - (long)c1.rgbGreen))>>16)); BYTE b = (BYTE)(c1.rgbBlue + ((theApp.m_Filters.ShadowIntensity*n*((long)c0.rgbBlue - (long)c1.rgbBlue))>>16)); iShadow.SetPaletteColor((BYTE)(255-n),r,g,b); } mix->SetTransColor(c1); mix->SetTransIndex(0); mix->Mix(iShadow,CxImage::OpSrcCopy,theApp.m_Filters.ShadowX,theApp.m_Filters.ShadowY); //mix->Transfer(iShadow); mix->SetTransIndex(-1); CDemoDoc *NewDocr=(CDemoDoc*)((CDemoApp*)AfxGetApp())->demoTemplate->OpenDocumentFile(NULL); if (NewDocr) { NewDocr->image = mix; CString s; s.Format(_T("NewImage%d"),((CDemoApp*)AfxGetApp())->m_nDocCount++); NewDocr->SetTitle(s); NewDocr->UpdateAllViews(0,WM_USER_NEWIMAGE); } Stopwatch(1); UpdateStatusBar(); SetCursor(LoadCursor(0,IDC_ARROW)); } } //////////////////////////////////////////////////////////////////////////////
33.069107
214
0.657517
[ "object" ]
6a001923900f609a0049c88af77ccf8c45271f5c
5,635
cpp
C++
solutions/LeetCode/C++/1032.cpp
timxor/leetcode-journal
5f1cb6bcc44a5bc33d88fb5cdb4126dfc6f4232a
[ "MIT" ]
854
2018-11-09T08:06:16.000Z
2022-03-31T06:05:53.000Z
solutions/LeetCode/C++/1032.cpp
timxor/leetcode-journal
5f1cb6bcc44a5bc33d88fb5cdb4126dfc6f4232a
[ "MIT" ]
29
2019-06-02T05:02:25.000Z
2021-11-15T04:09:37.000Z
solutions/LeetCode/C++/1032.cpp
timxor/leetcode-journal
5f1cb6bcc44a5bc33d88fb5cdb4126dfc6f4232a
[ "MIT" ]
347
2018-12-23T01:57:37.000Z
2022-03-12T14:51:21.000Z
__________________________________________________________________________________________________ sample 160 ms submission class TrieNode { public: bool is_word; TrieNode * children[26]; TrieNode(): is_word(false) { memset(children, 0, sizeof children); } }; class StreamChecker { TrieNode * root; string q; public: StreamChecker(vector<string>& words) { q = ""; root = new TrieNode(); for(string word : words) { TrieNode * cur = root; int m = word.length(); for(int i = m - 1; i >= 0; --i) { if (cur->children[word[i] - 'a'] == nullptr) { cur->children[word[i] - 'a'] = new TrieNode(); } cur = cur->children[word[i] - 'a']; } cur->is_word = true; } } bool query(char letter) { q += letter; int m = q.length(); TrieNode * cur = root; for(int i = m - 1; i >= 0; --i) { cur = cur->children[q[i] - 'a']; if (cur == nullptr) return false; if (cur->is_word) return true; } return false; } }; /** * Your StreamChecker object will be instantiated and called as such: * StreamChecker* obj = new StreamChecker(words); * bool param_1 = obj->query(letter); */ __________________________________________________________________________________________________ sample 184 ms submission struct Node { bool isLast; Node* next[26]; Node(bool isLast):isLast(isLast) { memset(next, 0, sizeof(next)); } }; class StreamChecker { public: Node* trie[26]; StreamChecker(vector<string>& words) { memset(trie, 0, sizeof(trie)); for (string& s : words) { Node* cur; int ssz = s.size(); int lastIdx = ssz-1; for (int i = lastIdx; i >= 0; --i) { int c = s[i] - 'a'; if (i == lastIdx) { if (!trie[c]) trie[c] = new Node(false); cur = trie[c]; } else { if (!cur->next[c]) cur->next[c] = new Node(false); cur = cur->next[c]; } if (i == 0) cur->isLast = true; } } } vector<int> Q; bool query(char letter) { Q.push_back(letter - 'a'); Node* cur; int qsz = Q.size(); int lastIdx = qsz-1; for (int i = lastIdx; i >= 0; --i) { int c = Q[i]; if (i == lastIdx) cur = trie[c]; else cur = cur->next[c]; if (cur == NULL) return false; if (cur->isLast) return true; } return false; } }; static int fast = [](){cin.tie(0);ios::sync_with_stdio(0);return 0;}(); __________________________________________________________________________________________________ sample 192 ms submission #include <vector> #include <iostream> #include <string> #include <algorithm> #include <queue> using namespace std; class StreamChecker { public: StreamChecker(const vector<string>& words) { initialize_trie(words); build_dictionary_automaton(); } bool query(char letter) { current = nodes[current].next[letter - 'a']; return nodes[current].terminal; } private: int current; void build_dictionary_automaton() { queue<pair<int, int>> Q; for (int i = 0; i < ALPHABET_SIZE; ++i) { if (nodes[root].next[i] == -1) { nodes[root].next[i] = root; } else { Q.push(make_pair(root, nodes[root].next[i])); } } while (!Q.empty()) { auto p = Q.front(); Q.pop(); if (nodes[p.first].terminal) { nodes[p.second].terminal = true; } for (int i = 0; i < ALPHABET_SIZE; ++i) { int x = nodes[p.first].next[i]; int y = nodes[p.second].next[i]; if (y == -1) { nodes[p.second].next[i] = x; } else { Q.push(make_pair(x, y)); } } } current = 0; } void initialize_trie(const vector<string>& words) { root = 0; nodes.push_back(TrieNode()); for (auto& word : words) { auto current = root; for (char c : word) { int offset = c - 'a'; if (nodes[current].next[offset] == -1) { nodes[current].next[offset] = nodes.size(); nodes.push_back(TrieNode()); } current = nodes[current].next[offset]; } nodes[current].terminal = true; } } static const int ALPHABET_SIZE = 26; struct TrieNode { int next[ALPHABET_SIZE]; bool terminal; TrieNode() { fill(next, next + ALPHABET_SIZE, -1); terminal = false; } }; vector<TrieNode> nodes; int root; }; static const int accelerate = []() { ios::sync_with_stdio(false); cin.tie(nullptr); return 0; }(); /** * Your StreamChecker object will be instantiated and called as such: * StreamChecker* obj = new StreamChecker(words); * bool param_1 = obj->query(letter); */
25.497738
98
0.480568
[ "object", "vector" ]
6a04879a529e9f957e3dfc835d1e8fb711b37366
16,349
cc
C++
caffe2/core/workspace.cc
Mathpix/caffe2
6687f8447545250cdeb63a4a9baaa6e25c32ad0d
[ "MIT" ]
1
2021-04-22T00:07:58.000Z
2021-04-22T00:07:58.000Z
caffe2/core/workspace.cc
ZhaoJ9014/caffe2
40a1ae36afd2d1b6126f171209c83a4a5b95737c
[ "MIT" ]
null
null
null
caffe2/core/workspace.cc
ZhaoJ9014/caffe2
40a1ae36afd2d1b6126f171209c83a4a5b95737c
[ "MIT" ]
null
null
null
#include "caffe2/core/workspace.h" #include <algorithm> #include <ctime> #include <mutex> #include "caffe2/core/logging.h" #include "caffe2/core/operator.h" #include "caffe2/core/net.h" #include "caffe2/core/timer.h" #include "caffe2/proto/caffe2.pb.h" CAFFE2_DEFINE_bool( caffe2_handle_executor_threads_exceptions, false, "If used we will handle exceptions in executor threads. " "This avoids SIGABRT but may cause process to deadlock"); #if CAFFE2_MOBILE // Threadpool restrictions // Whether or not threadpool caps apply to Android CAFFE2_DEFINE_int(caffe2_threadpool_android_cap, true, ""); // Whether or not threadpool caps apply to iOS CAFFE2_DEFINE_int(caffe2_threadpool_ios_cap, false, ""); #endif // CAFFE2_MOBILE namespace caffe2 { namespace { // try to get the should_stop signal, a scalar bool blob value. // if the blob doesn't exist or is not initiaized, return false inline const bool getShouldStop(const Blob* b) { if (!b || !b->meta().id()) { // not exist or uninitialized return false; } const auto& t = b->Get<TensorCPU>(); CAFFE_ENFORCE(t.IsType<bool>() && t.size() == 1, "expects a scalar boolean"); return *(t.template data<bool>()); } // Returns a function that returns `true` if we should continue // iterating, given the current iteration count. std::function<bool(int64_t)> getContinuationTest( Workspace* ws, const ExecutionStep& step) { if (step.has_should_stop_blob()) { CAFFE_ENFORCE( !step.has_num_iter(), "Must not specify num_iter if should_stop_blob is set"); } if (!step.has_should_stop_blob()) { // control by iteration CAFFE_ENFORCE(!step.has_only_once(), "not supported"); int64_t iterations = step.has_num_iter() ? step.num_iter() : 1; VLOG(1) << "Will execute step " << step.name() << " for " << iterations << " iterations."; return [=](int64_t i) { return i < iterations; }; } else { // control by signal blob bool onlyOnce = step.has_only_once() && step.only_once(); VLOG(1) << "Will execute step" << step.name() << (onlyOnce ? " once " : "") << " until stopped by blob " << step.should_stop_blob(); if (onlyOnce) { return [](int64_t i) { return i == 0; }; } else { return [](int64_t i) { return true; }; } } }; } // namespace struct CompiledExecutionStep { typedef std::function<bool(int)> ShouldContinue; CompiledExecutionStep( const ExecutionStep* mainStep, Workspace* ws, ShouldContinue externalShouldContinue) : step(mainStep) { CAFFE_ENFORCE( (step->substep_size() == 0 || step->network_size() == 0), "An ExecutionStep should either have substep or networks" "but not both."); if (step->has_should_stop_blob()) { shouldStop = ws->GetBlob(step->should_stop_blob()); CAFFE_ENFORCE( shouldStop, "blob ", step->should_stop_blob(), " does not exist"); } if (step->substep_size()) { ShouldContinue substepShouldContinue; if (!step->concurrent_substeps() || step->substep().size() <= 1) { substepShouldContinue = externalShouldContinue; } else { substepShouldContinue = [this, externalShouldContinue](int64_t it) { return !gotFailure && externalShouldContinue(it); }; } for (const auto& ss : step->substep()) { auto compiledSubstep = std::make_shared<CompiledExecutionStep>( &ss, ws, substepShouldContinue); if (ss.has_run_every_ms()) { reportSubsteps.push_back(compiledSubstep); } else { recurringSubsteps.push_back(compiledSubstep); } } } else { for (const string& network_name : step->network()) { auto* net = ws->GetNet(network_name); CAFFE_ENFORCE(net != nullptr, "Network ", network_name, " not found."); networks.push_back(net); } } netShouldContinue = getContinuationTest(ws, *step); shouldContinue = [this, externalShouldContinue](int64_t iter) { return externalShouldContinue(iter) && this->netShouldContinue(iter); }; } const ExecutionStep* step; vector<std::shared_ptr<CompiledExecutionStep>> reportSubsteps; vector<std::shared_ptr<CompiledExecutionStep>> recurringSubsteps; vector<NetBase*> networks; Blob* shouldStop{nullptr}; ShouldContinue netShouldContinue; ShouldContinue shouldContinue; std::atomic<bool> gotFailure{false}; }; vector<string> Workspace::LocalBlobs() const { vector<string> names; for (auto& entry : blob_map_) { names.push_back(entry.first); } return names; } vector<string> Workspace::Blobs() const { vector<string> names; for (auto& entry : blob_map_) { names.push_back(entry.first); } if (shared_) { vector<string> shared_blobs = shared_->Blobs(); names.insert(names.end(), shared_blobs.begin(), shared_blobs.end()); } return names; } Blob* Workspace::CreateBlob(const string& name) { if (HasBlob(name)) { VLOG(1) << "Blob " << name << " already exists. Skipping."; } else { VLOG(1) << "Creating blob " << name; blob_map_[name] = unique_ptr<Blob>(new Blob()); } return GetBlob(name); } bool Workspace::RemoveBlob(const string& name) { auto it = blob_map_.find(name); if (it != blob_map_.end()) { VLOG(1) << "Removing blob " << name << " from this workspace."; blob_map_.erase(it); return true; } // won't go into share_ here VLOG(1) << "Blob " << name << " not exists. Skipping."; return false; } const Blob* Workspace::GetBlob(const string& name) const { if (blob_map_.count(name)) { return blob_map_.at(name).get(); } else if (shared_ && shared_->HasBlob(name)) { return shared_->GetBlob(name); } else { LOG(WARNING) << "Blob " << name << " not in the workspace."; // TODO(Yangqing): do we want to always print out the list of blobs here? // LOG(WARNING) << "Current blobs:"; // for (const auto& entry : blob_map_) { // LOG(WARNING) << entry.first; // } return nullptr; } } Blob* Workspace::GetBlob(const string& name) { return const_cast<Blob*>( static_cast<const Workspace*>(this)->GetBlob(name)); } NetBase* Workspace::CreateNet(const NetDef& net_def) { CAFFE_ENFORCE(net_def.has_name(), "Net definition should have a name."); if (net_map_.count(net_def.name()) > 0) { LOG(WARNING) << "Overwriting existing network of the same name."; // Note(Yangqing): Why do we explicitly erase it here? Some components of // the old network, such as a opened LevelDB, may prevent us from creating a // new network before the old one is deleted. Thus we will need to first // erase the old one before the new one can be constructed. net_map_.erase(net_def.name()); } // Create a new net with its name. VLOG(1) << "Initializing network " << net_def.name(); net_map_[net_def.name()] = unique_ptr<NetBase>(caffe2::CreateNet(net_def, this)); if (net_map_[net_def.name()].get() == nullptr) { LOG(ERROR) << "Error when creating the network."; net_map_.erase(net_def.name()); return nullptr; } return net_map_[net_def.name()].get(); } NetBase* Workspace::GetNet(const string& name) { if (!net_map_.count(name)) { return nullptr; } else { return net_map_[name].get(); } } void Workspace::DeleteNet(const string& name) { if (net_map_.count(name)) { net_map_.erase(name); } } bool Workspace::RunNet(const string& name) { if (!net_map_.count(name)) { LOG(ERROR) << "Network " << name << " does not exist yet."; return false; } return net_map_[name]->Run(); } bool Workspace::RunOperatorOnce(const OperatorDef& op_def) { std::unique_ptr<OperatorBase> op(CreateOperator(op_def, this)); if (op.get() == nullptr) { LOG(ERROR) << "Cannot create operator of type " << op_def.type(); return false; } if (!op->Run()) { LOG(ERROR) << "Error when running operator " << op_def.type(); return false; } return true; } bool Workspace::RunNetOnce(const NetDef& net_def) { std::unique_ptr<NetBase> net(caffe2::CreateNet(net_def, this)); if (!net->Run()) { LOG(ERROR) << "Error when running network " << net_def.name(); return false; } return true; } bool Workspace::RunPlan(const PlanDef& plan, ShouldContinue shouldContinue) { LOG(INFO) << "Started executing plan."; if (plan.execution_step_size() == 0) { LOG(WARNING) << "Nothing to run - did you define a correct plan?"; // We will do nothing, but the plan is still legal so we will return true. return true; } LOG(INFO) << "Initializing networks."; for (const NetDef& net_def : plan.network()) { if (!CreateNet(net_def)) { LOG(ERROR) << "Failed initializing the networks."; return false; } } Timer plan_timer; for (const ExecutionStep& step : plan.execution_step()) { Timer step_timer; CompiledExecutionStep compiledStep(&step, this, shouldContinue); if (!ExecuteStepRecursive(compiledStep)) { LOG(ERROR) << "Failed initializing step " << step.name(); return false; } LOG(INFO) << "Step " << step.name() << " took " << step_timer.Seconds() << " seconds."; } LOG(INFO) << "Total plan took " << plan_timer.Seconds() << " seconds."; LOG(INFO) << "Plan executed successfully."; return true; } #if CAFFE2_MOBILE ThreadPool* Workspace::GetThreadPool() { std::lock_guard<std::mutex> guard(thread_pool_creation_mutex_); if (!thread_pool_) { int numThreads = std::thread::hardware_concurrency(); bool applyCap = false; #if CAFFE2_ANDROID applyCap = caffe2::FLAGS_caffe2_threadpool_android_cap; #elif CAFFE2_IOS applyCap = caffe2::FLAGS_caffe2_threadpool_ios_cap; #else #error Undefined architecture #endif if (applyCap) { // 1 core -> 1 thread // 2 cores -> 2 threads // 4 cores -> 3 threads // 8 cores -> 4 threads // more, continue limiting to half of available cores if (numThreads <= 3) { // no change } else if (numThreads <= 5) { // limit to 3 numThreads = 3; } else { // Use half the cores numThreads = numThreads / 2; } } LOG(INFO) << "Constructing thread pool with " << numThreads << " threads"; thread_pool_.reset(new ThreadPool(numThreads)); } return thread_pool_.get(); } #endif // CAFFE2_MOBILE namespace { struct Reporter { struct ReporterInstance { std::mutex report_mutex; std::condition_variable report_cv; std::thread report_thread; ReporterInstance(int intervalMillis, bool* done, std::function<void()> f) { auto interval = std::chrono::milliseconds(intervalMillis); auto reportWorker = [=]() { std::unique_lock<std::mutex> lk(report_mutex); do { report_cv.wait_for(lk, interval, [&]() { return *done; }); f(); } while (!*done); }; report_thread = std::thread(reportWorker); } }; void start(int64_t intervalMillis, std::function<void()> f) { instances_.emplace_back(new ReporterInstance(intervalMillis, &done, f)); } ~Reporter() { done = true; for (auto& instance : instances_) { if (!instance->report_thread.joinable()) { continue; } instance->report_cv.notify_all(); instance->report_thread.join(); } } private: std::vector<std::unique_ptr<ReporterInstance>> instances_; bool done{false}; }; } #define CHECK_SHOULD_STOP(step, shouldStop) \ if (getShouldStop(shouldStop)) { \ VLOG(1) << "Execution step " << step.name() << " stopped by " \ << step.should_stop_blob(); \ return true; \ } bool Workspace::ExecuteStepRecursive(CompiledExecutionStep& compiledStep) { const auto& step = *(compiledStep.step); VLOG(1) << "Running execution step " << step.name(); std::unique_ptr<Reporter> reporter; if (step.has_report_net() || compiledStep.reportSubsteps.size() > 0) { reporter = caffe2::make_unique<Reporter>(); if (step.has_report_net()) { CAFFE_ENFORCE( step.has_report_interval(), "A report_interval must be provided if report_net is set."); if (net_map_.count(step.report_net()) == 0) { LOG(ERROR) << "Report net " << step.report_net() << " not found."; } VLOG(1) << "Starting reporter net"; auto* net = net_map_[step.report_net()].get(); reporter->start(step.report_interval() * 1000, [=]() { if (!net->Run()) { LOG(WARNING) << "Error running report_net."; } }); } for (auto& compiledSubstep : compiledStep.reportSubsteps) { reporter->start(compiledSubstep->step->run_every_ms(), [=]() { if (!ExecuteStepRecursive(*compiledSubstep)) { LOG(WARNING) << "Error running report step."; } }); } } const Blob* shouldStop = compiledStep.shouldStop; if (step.substep_size()) { bool sequential = !step.concurrent_substeps() || step.substep().size() <= 1; for (int64_t iter = 0; compiledStep.shouldContinue(iter); ++iter) { if (sequential) { VLOG(1) << "Executing step " << step.name() << " iteration " << iter; for (auto& compiledSubstep : compiledStep.recurringSubsteps) { if (!ExecuteStepRecursive(*compiledSubstep)) { return false; } CHECK_SHOULD_STOP(step, shouldStop); } } else { VLOG(1) << "Executing step " << step.name() << " iteration " << iter << " with " << step.substep().size() << " concurrent substeps"; std::atomic<int> next_substep{0}; std::mutex exception_mutex; string first_exception; auto worker = [&]() { while (true) { int substep_id = next_substep++; if (compiledStep.gotFailure || (substep_id >= compiledStep.recurringSubsteps.size())) { break; } try { if (!ExecuteStepRecursive( *compiledStep.recurringSubsteps.at(substep_id))) { compiledStep.gotFailure = true; } } catch (const std::exception& ex) { std::lock_guard<std::mutex> guard(exception_mutex); if (!first_exception.size()) { first_exception = GetExceptionString(ex); LOG(ERROR) << "Parallel worker exception:\n" << first_exception; } compiledStep.gotFailure = true; if (!FLAGS_caffe2_handle_executor_threads_exceptions) { // In complex plans other threads might get stuck if another // one fails. So we let exception to go out of thread which // causes SIGABRT. In local setup one might use this flag // in order to use Python debugger after a failure throw; } } } }; std::vector<std::thread> threads; for (int64_t i = 0; i < step.substep().size(); ++i) { if (!step.substep().Get(i).has_run_every_ms()) { threads.emplace_back(worker); } } for (auto& thread: threads) { thread.join(); } if (compiledStep.gotFailure) { LOG(ERROR) << "One of the workers failed."; if (first_exception.size()) { CAFFE_THROW( "One of the workers died with an unhandled exception ", first_exception); } return false; } // concurrent substeps should be careful about setting should_stop_blob CHECK_SHOULD_STOP(step, shouldStop); } } return true; } else { // If this ExecutionStep just contains nets, we can directly run it. for (int64_t iter = 0; compiledStep.shouldContinue(iter); ++iter) { VLOG(1) << "Executing networks " << step.name() << " iteration " << iter; for (NetBase* network : compiledStep.networks) { if (!network->Run()) { return false; } CHECK_SHOULD_STOP(step, shouldStop); } } } return true; } #undef CHECK_SHOULD_STOP } // namespace caffe2
31.931641
80
0.614778
[ "vector" ]
6a050e7a5216b068824902c3e168b82d6f32efc8
1,005
cpp
C++
source/112.cpp
narikbi/LeetCode
835215c21d1bd6820b20c253026bcb6f889ed3fc
[ "MIT" ]
2
2017-02-28T11:39:13.000Z
2019-12-07T17:23:20.000Z
source/112.cpp
narikbi/LeetCode
835215c21d1bd6820b20c253026bcb6f889ed3fc
[ "MIT" ]
null
null
null
source/112.cpp
narikbi/LeetCode
835215c21d1bd6820b20c253026bcb6f889ed3fc
[ "MIT" ]
null
null
null
// // 112.cpp // LeetCode // // Created by Narikbi on 01.04.17. // Copyright © 2017 app.leetcode.kz. All rights reserved. // #include <stdio.h> #include <iostream> #include <vector> #include <string> #include <algorithm> #include <deque> #include <queue> #include <set> #include <map> #include <stack> #include <cmath> #include <numeric> #include <unordered_map> #include <sstream> using namespace std; struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; bool rec(TreeNode *root, int sum, int current) { if (root == NULL) { return false; } if (root->left == NULL && root->right == NULL && sum == current + root->val) { return true; } return rec(root->left, sum, root->val + current) || rec(root->right, sum, root->val + current); } bool hasPathSum(TreeNode* root, int sum) { if (root == NULL) return false; return rec(root, sum, 0); }
17.946429
99
0.60199
[ "vector" ]
6a0cb2a718584cc7f64d655bd14c7794a3ee2928
1,537
cc
C++
mindspore/ccsrc/plugin/device/cpu/kernel/environ/environ_cpu_destroy_all.cc
zhz44/mindspore
6044d34074c8505dd4b02c0a05419cbc32a43f86
[ "Apache-2.0" ]
1
2022-03-05T02:59:21.000Z
2022-03-05T02:59:21.000Z
mindspore/ccsrc/plugin/device/cpu/kernel/environ/environ_cpu_destroy_all.cc
zhz44/mindspore
6044d34074c8505dd4b02c0a05419cbc32a43f86
[ "Apache-2.0" ]
null
null
null
mindspore/ccsrc/plugin/device/cpu/kernel/environ/environ_cpu_destroy_all.cc
zhz44/mindspore
6044d34074c8505dd4b02c0a05419cbc32a43f86
[ "Apache-2.0" ]
null
null
null
/** * Copyright 2022 Huawei Technologies Co., Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "plugin/device/cpu/kernel/environ/environ_cpu_destroy_all.h" #include "kernel/environ_manager.h" namespace mindspore { namespace kernel { void EnvironDestroyAllCpuKernelMod::InitKernel(const CNodePtr &node) { MS_EXCEPTION_IF_NULL(node); // Check the output type. auto output_type = AnfAlgo::GetOutputDeviceDataType(node, 0); if (output_type != TypeId::kNumberTypeBool) { MS_LOG(EXCEPTION) << "The output type is invalid: " << output_type; } output_size_list_.push_back(sizeof(bool)); } bool EnvironDestroyAllCpuKernelMod::Launch(const std::vector<AddressPtr> &, const std::vector<AddressPtr> &, const std::vector<AddressPtr> &) { MS_LOG(INFO) << "Clear the global environ data."; // Clear the global data which are generated in the kernel running. EnvironMgr::GetInstance().Clear(); return true; } } // namespace kernel } // namespace mindspore
35.744186
108
0.722837
[ "vector" ]
6a0d4884093463fc5a3aa6b3298ead344d193b4d
1,894
cc
C++
src/procedure_geometry.cc
tunneln/Virtual_Mannequin
5b0994631a56f55fcc80d5662081f2db5961d95d
[ "BSL-1.0" ]
2
2019-01-28T16:22:31.000Z
2020-03-23T19:09:52.000Z
src/procedure_geometry.cc
tunneln/virtual-mannequin
5b0994631a56f55fcc80d5662081f2db5961d95d
[ "BSL-1.0" ]
null
null
null
src/procedure_geometry.cc
tunneln/virtual-mannequin
5b0994631a56f55fcc80d5662081f2db5961d95d
[ "BSL-1.0" ]
null
null
null
#include "procedure_geometry.h" #include "bone_geometry.h" #include "config.h" void create_floor(std::vector<glm::vec4>& floor_vertices, std::vector<glm::uvec3>& floor_faces) { floor_faces.push_back(glm::uvec3(0, 1, 2)); floor_faces.push_back(glm::uvec3(2, 3, 0)); floor_vertices.push_back(glm::vec4(kFloorXMin, kFloorY, kFloorZMax, 1.0f)); floor_vertices.push_back(glm::vec4(kFloorXMax, kFloorY, kFloorZMax, 1.0f)); floor_vertices.push_back(glm::vec4(kFloorXMax, kFloorY, kFloorZMin, 1.0f)); floor_vertices.push_back(glm::vec4(kFloorXMin, kFloorY, kFloorZMin, 1.0f)); } void create_bone_mesh(Skeleton* skeleton) {} void create_lattice_lines(std::vector<glm::vec4>& vertices, std::vector<glm::uvec2>& lines, size_t branch) { size_t n = vertices.size(); float step = 1.0f / (float)branch; for (size_t i = 0; i <= branch; i++) { for (size_t j = 0; j <= branch; j++) { vertices.push_back(glm::vec4(0.0f, i * step, j * step, 1)); size_t adj = n + j + i * (branch + 1); if (i < branch) lines.push_back(glm::uvec2(adj, adj + branch + 1)); if (j < branch) lines.push_back(glm::uvec2(adj, adj + 1)); } } } void create_lattice_cylinders(std::vector<glm::vec4>& vertices, std::vector<glm::vec4>& norm, std::vector<glm::uvec3>& faces, size_t branch) { size_t n = vertices.size(); float step = 1.0f / (float)(branch - 1); for (size_t i = 0; i < branch - 1; i++) { for (size_t j = 0; j < branch - 1; j++) { size_t a = n + j + i * branch; size_t b = n + j + (i + 1) * branch; size_t c = n + (j + 1) + i * branch; size_t d = n + (j + 1) + (i + 1) * branch; faces.push_back(glm::uvec3(a, c, b)); faces.push_back(glm::uvec3(c, d, b)); } } for (size_t i = 0; i < branch; i++) { for (size_t j = 0; j < branch; j++) { vertices.push_back(glm::vec4(0.0f, i * step, j * step, 1)); norm.push_back(glm::vec4(-1.0f, 0.0f, 0.0f, 0.0f)); } } }
31.566667
95
0.627772
[ "vector" ]
6a0f037212adda6e0d977e94997e71bce5574e68
3,509
hpp
C++
timer/Texture/Texture.hpp
MaticVrtacnik/ProceduralnaAnimacija
bc47ccc721d1bedb31ed5949eb740892f094897a
[ "MIT" ]
null
null
null
timer/Texture/Texture.hpp
MaticVrtacnik/ProceduralnaAnimacija
bc47ccc721d1bedb31ed5949eb740892f094897a
[ "MIT" ]
null
null
null
timer/Texture/Texture.hpp
MaticVrtacnik/ProceduralnaAnimacija
bc47ccc721d1bedb31ed5949eb740892f094897a
[ "MIT" ]
null
null
null
/* MIT License Copyright (c) 2019 MaticVrtacnik 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 TEXTURE_HPP #define TEXTURE_HPP #include <GL\glew.h> #include <SDL2\SDL_image.h> #include <string> #include <vector> #include "TextureTypes.hpp" namespace Engine{ namespace Textures{ static const float DEFAULT_ANISOTROPY = 16.0f; //first layer...0 void setActiveTextureLayer(GLint layer); void bind1DTexture(unsigned int texture); void bind1DTexture(unsigned int texture, GLint layer); void unbind1DTexture(); void bind2DTexture(unsigned int texture); void bind2DTexture(unsigned int texture, GLint layer); void unbind2DTexture(); void unbind2DTexture(GLint layer); void bind2DTextureArray(unsigned int texture); void bind2DTextureArray(unsigned int texture, GLint layer); void unbind2DTextureArray(); void bind3DTexture(unsigned int texture); void bind3DTexture(unsigned int texture, GLint layer); void unbind3DTexture(); void removeTexture(unsigned int texture); SDL_Surface *getTextureData(const std::string &path); unsigned int load2DTexture( const std::string &path, bool mipmap, GLint format = GL_RGBA, GLint wrap = GL_REPEAT ); unsigned int create2DTextureArray( const std::vector<unsigned int> &textures, GLint width, unsigned int height, GLint format = GL_RGBA ); unsigned int load1DTexture( const std::string &path, bool mipmap, GLint format = GL_RGBA, GLint wrap = GL_REPEAT ); unsigned int createEmptyTexture( GLsizei width, GLsizei height, bool depthTexture, GLint format, GLint filter = GL_NEAREST, GLint internalFormat = GL_RGBA, GLenum dataType = GL_FLOAT ); struct Texture{ public: TextureType m_type = TEXTURE_UNKNOWN; std::string m_path = ""; unsigned int m_textureId = 0; GLint m_format = GL_RGBA; GLint m_wrap = GL_REPEAT; GLint m_filter; //TODO GLfloat m_anisotrophy = DEFAULT_ANISOTROPY; bool m_mipmap = false; public: Texture(); Texture(const Texture &texture); Texture(Texture &&texture); Texture(unsigned int texture, TextureType type = TEXTURE_DIFFUSE); Texture(const std::string &path, bool mipmap, TextureType type = TEXTURE_DIFFUSE, GLint format = GL_RGBA, GLint wrap = GL_REPEAT); ~Texture(); Texture &operator=(const Texture &texture); Texture &operator=(Texture &&texture); void bind(); void bind(GLint layer); void unbind(); }; } } #endif //TEXTURE_HPP
22.49359
84
0.737532
[ "vector" ]
6a13bd428694e5c83398473073880f8674ebb848
1,357
hpp
C++
include/networkit/io/NetworkitBinaryWriter.hpp
angriman/network
3a4c5fd32eb2be8d5b34eaee17f8fe4e6e141894
[ "MIT" ]
366
2019-06-27T18:48:18.000Z
2022-03-29T08:36:49.000Z
include/networkit/io/NetworkitBinaryWriter.hpp
angriman/network
3a4c5fd32eb2be8d5b34eaee17f8fe4e6e141894
[ "MIT" ]
387
2019-06-24T11:30:39.000Z
2022-03-31T10:37:28.000Z
include/networkit/io/NetworkitBinaryWriter.hpp
angriman/network
3a4c5fd32eb2be8d5b34eaee17f8fe4e6e141894
[ "MIT" ]
131
2019-07-04T15:40:13.000Z
2022-03-29T12:34:23.000Z
/* * NetworkitBinaryWriter.hpp * * Author: Charmaine Ndolo <charmaine.ndolo@hu-berlin.de> */ #ifndef NETWORKIT_IO_NETWORKIT_BINARY_WRITER_HPP_ #define NETWORKIT_IO_NETWORKIT_BINARY_WRITER_HPP_ #include <networkit/graph/Graph.hpp> #include <networkit/io/GraphWriter.hpp> namespace NetworKit { enum class NetworkitBinaryWeights { none, unsignedFormat, signedFormat, doubleFormat, floatFormat, autoDetect }; enum class NetworkitBinaryEdgeIDs { noEdgeIDs, writeEdgeIDs, autoDetect }; /** * @ingroup io * * Writes a graph in the custom Networkit format documented in cpp/io/NetworkitGraph.md */ class NetworkitBinaryWriter final : public GraphWriter { public: NetworkitBinaryWriter(uint64_t chunks = 32, NetworkitBinaryWeights weightsType = NetworkitBinaryWeights::autoDetect, NetworkitBinaryEdgeIDs edgeIndex = NetworkitBinaryEdgeIDs::autoDetect); void write(const Graph &G, const std::string &path) override; std::vector<uint8_t> writeToBuffer(const Graph &G); private: count chunks; NetworkitBinaryWeights weightsType; NetworkitBinaryEdgeIDs edgeIndex; bool preserveEdgeIndex; template <class T> void writeData(T &outStream, const Graph &G); }; } // namespace NetworKit #endif // NETWORKIT_IO_NETWORKIT_BINARY_WRITER_HPP_
25.12963
98
0.734709
[ "vector" ]
6a1899e841fe91830b5c38218e7fefaf6ced7030
17,597
cc
C++
src/bin/d2/d2_process.cc
telekom/dt-kea-netconf
f347df353d58827d6deb09f281d3680ab089e7af
[ "Apache-2.0" ]
2
2021-06-29T09:56:34.000Z
2021-06-29T09:56:39.000Z
src/bin/d2/d2_process.cc
telekom/dt-kea-netconf
f347df353d58827d6deb09f281d3680ab089e7af
[ "Apache-2.0" ]
null
null
null
src/bin/d2/d2_process.cc
telekom/dt-kea-netconf
f347df353d58827d6deb09f281d3680ab089e7af
[ "Apache-2.0" ]
null
null
null
// Copyright (C) 2013-2020 Internet Systems Consortium, Inc. ("ISC") // // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. #include <config.h> #include <asiolink/asio_wrapper.h> #include <cc/command_interpreter.h> #include <config/command_mgr.h> #include <d2/d2_log.h> #include <d2/d2_cfg_mgr.h> #include <d2/d2_controller.h> #include <d2/d2_process.h> using namespace isc::process; namespace isc { namespace d2 { // Setting to 80% for now. This is an arbitrary choice and should probably // be configurable. const unsigned int D2Process::QUEUE_RESTART_PERCENT = 80; D2Process::D2Process(const char* name, const asiolink::IOServicePtr& io_service) : DProcessBase(name, io_service, DCfgMgrBasePtr(new D2CfgMgr())), reconf_queue_flag_(false), shutdown_type_(SD_NORMAL) { // Instantiate queue manager. Note that queue manager does not start // listening at this point. That can only occur after configuration has // been received. This means that until we receive the configuration, // D2 will neither receive nor process NameChangeRequests. // Pass in IOService for NCR IO event processing. queue_mgr_.reset(new D2QueueMgr(getIoService())); // Instantiate update manager. // Pass in both queue manager and configuration manager. // Pass in IOService for DNS update transaction IO event processing. D2CfgMgrPtr tmp = getD2CfgMgr(); update_mgr_.reset(new D2UpdateMgr(queue_mgr_, tmp, getIoService())); }; void D2Process::init() { // CommandMgr uses IO service to run asynchronous socket operations. isc::config::CommandMgr::instance().setIOService(getIoService()); }; void D2Process::run() { LOG_INFO(d2_logger, DHCP_DDNS_STARTED).arg(VERSION); D2ControllerPtr controller = std::dynamic_pointer_cast<D2Controller>(D2Controller::instance()); try { // Now logging was initialized so commands can be registered. controller->registerCommands(); // Loop forever until we are allowed to shutdown. while (!canShutdown()) { // Check on the state of the request queue. Take any // actions necessary regarding it. checkQueueStatus(); // Give update manager a time slice to queue new jobs and // process finished ones. update_mgr_->sweep(); // Wait on IO event(s) - block until one or more of the following // has occurred: // a. NCR message has been received // b. Transaction IO has completed // c. Interval timer expired // d. Control channel event // e. Something stopped IO service (runIO returns 0) if (runIO() == 0) { // Pretty sure this amounts to an unexpected stop and we // should bail out now. Normal shutdowns do not utilize // stopping the IOService. isc_throw(DProcessBaseError, "Primary IO service stopped unexpectedly"); } } } catch (const std::exception& ex) { LOG_FATAL(d2_logger, DHCP_DDNS_FAILED).arg(ex.what()); controller->deregisterCommands(); isc_throw (DProcessBaseError, "Process run method failed: " << ex.what()); } // @todo - if queue isn't empty, we may need to persist its contents // this might be the place to do it, once there is a persistence mgr. // This may also be better in checkQueueStatus. controller->deregisterCommands(); LOG_DEBUG(d2_logger, isc::log::DBGLVL_START_SHUT, DHCP_DDNS_RUN_EXIT); }; size_t D2Process::runIO() { // We want to block until at least one handler is called. We'll use // boost::asio::io_service directly for two reasons. First off // asiolink::IOService::run_one is a void and boost::asio::io_service::stopped // is not present in older versions of boost. We need to know if any // handlers ran or if the io_service was stopped. That latter represents // some form of error and the application cannot proceed with a stopped // service. Secondly, asiolink::IOService does not provide the poll // method. This is a handy method which runs all ready handlers without // blocking. asiolink::IOServicePtr& io = getIoService(); boost::asio::io_service& asio_io_service = io->get_io_service(); // Poll runs all that are ready. If none are ready it returns immediately // with a count of zero. size_t cnt = asio_io_service.poll(); if (!cnt) { // Poll ran no handlers either none are ready or the service has been // stopped. Either way, call run_one to wait for a IO event. If the // service is stopped it will return immediately with a cnt of zero. cnt = asio_io_service.run_one(); } return (cnt); } bool D2Process::canShutdown() const { bool all_clear = false; // If we have been told to shutdown, find out if we are ready to do so. if (shouldShutdown()) { switch (shutdown_type_) { case SD_NORMAL: // For a normal shutdown we need to stop the queue manager but // wait until we have finished all the transactions in progress. all_clear = (((queue_mgr_->getMgrState() != D2QueueMgr::RUNNING) && (queue_mgr_->getMgrState() != D2QueueMgr::STOPPING)) && (update_mgr_->getTransactionCount() == 0)); break; case SD_DRAIN_FIRST: // For a drain first shutdown we need to stop the queue manager but // process all of the requests in the receive queue first. all_clear = (((queue_mgr_->getMgrState() != D2QueueMgr::RUNNING) && (queue_mgr_->getMgrState() != D2QueueMgr::STOPPING)) && (queue_mgr_->getQueueSize() == 0) && (update_mgr_->getTransactionCount() == 0)); break; case SD_NOW: // Get out right now, no niceties. all_clear = true; break; default: // shutdown_type_ is an enum and should only be one of the above. // if its getting through to this, something is whacked. break; } if (all_clear) { LOG_DEBUG(d2_logger, isc::log::DBGLVL_START_SHUT, DHCP_DDNS_CLEARED_FOR_SHUTDOWN) .arg(getShutdownTypeStr(shutdown_type_)); } } return (all_clear); } isc::data::ElementPtr D2Process::shutdown(isc::data::ElementPtr args) { LOG_DEBUG(d2_logger, isc::log::DBGLVL_START_SHUT, DHCP_DDNS_SHUTDOWN_COMMAND) .arg(args ? args->str() : "(no arguments)"); // Default shutdown type is normal. std::string type_str(getShutdownTypeStr(SD_NORMAL)); shutdown_type_ = SD_NORMAL; if (args) { if ((args->getType() == isc::data::Element::map) && args->contains("type")) { type_str = args->get("type")->stringValue(); if (type_str == getShutdownTypeStr(SD_NORMAL)) { shutdown_type_ = SD_NORMAL; } else if (type_str == getShutdownTypeStr(SD_DRAIN_FIRST)) { shutdown_type_ = SD_DRAIN_FIRST; } else if (type_str == getShutdownTypeStr(SD_NOW)) { shutdown_type_ = SD_NOW; } else { setShutdownFlag(false); return (isc::config::createAnswer(1, "Invalid Shutdown type: " + type_str)); } } } // Set the base class's shutdown flag. setShutdownFlag(true); return (isc::config::createAnswer(0, "Shutdown initiated, type is: " + type_str)); } isc::data::ElementPtr D2Process::configure(isc::data::ElementPtr config_set, bool check_only) { LOG_DEBUG(d2_logger, isc::log::DBGLVL_TRACE_BASIC, DHCP_DDNS_CONFIGURE) .arg(check_only ? "check" : "update") .arg(config_set->str()); isc::data::ElementPtr answer; answer = getCfgMgr()->simpleParseConfig(config_set, check_only, std::bind(&D2Process::reconfigureCommandChannel, this)); if (check_only) { return (answer); } int rcode = 0; isc::data::ElementPtr comment; comment = isc::config::parseAnswer(rcode, answer); if (rcode) { // Non-zero means we got an invalid configuration, take no further // action. In integrated mode, this will send a failed response back // to the configuration backend. reconf_queue_flag_ = false; return (answer); } // Set the reconf_queue_flag to indicate that we need to reconfigure // the queue manager. Reconfiguring the queue manager may be asynchronous // and require one or more events to occur, therefore we set a flag // indicating it needs to be done but we cannot do it here. It must // be done over time, while events are being processed. Remember that // the method we are in now is invoked as part of the configuration event // callback. This means you can't wait for events here, you are already // in one. // (@todo NOTE This could be turned into a bitmask of flags if we find other // things that need reconfiguration. It might also be useful if we // did some analysis to decide what if anything we need to do.) reconf_queue_flag_ = true; // If we are here, configuration was valid, at least it parsed correctly // and therefore contained no invalid values. // Return the success answer from above. return (answer); } void D2Process::checkQueueStatus() { switch (queue_mgr_->getMgrState()){ case D2QueueMgr::RUNNING: if (reconf_queue_flag_ || shouldShutdown()) { // If we need to reconfigure the queue manager or we have been // told to shutdown, then stop listening first. Stopping entails // canceling active listening which may generate an IO event, so // instigate the stop and get out. try { LOG_DEBUG(d2_logger, isc::log::DBGLVL_START_SHUT, DHCP_DDNS_QUEUE_MGR_STOPPING) .arg(reconf_queue_flag_ ? "reconfiguration" : "shutdown"); queue_mgr_->stopListening(); } catch (const isc::Exception& ex) { // It is very unlikely that we would experience an error // here, but theoretically possible. LOG_ERROR(d2_logger, DHCP_DDNS_QUEUE_MGR_STOP_ERROR) .arg(ex.what()); } } break; case D2QueueMgr::STOPPED_QUEUE_FULL: { // Resume receiving once the queue has decreased by twenty // percent. This is an arbitrary choice. @todo this value should // probably be configurable. size_t threshold = (((queue_mgr_->getMaxQueueSize() * QUEUE_RESTART_PERCENT)) / 100); if (queue_mgr_->getQueueSize() <= threshold) { LOG_INFO (d2_logger, DHCP_DDNS_QUEUE_MGR_RESUMING) .arg(threshold).arg(queue_mgr_->getMaxQueueSize()); try { queue_mgr_->startListening(); } catch (const isc::Exception& ex) { LOG_ERROR(d2_logger, DHCP_DDNS_QUEUE_MGR_RESUME_ERROR) .arg(ex.what()); } } break; } case D2QueueMgr::STOPPED_RECV_ERROR: // If the receive error is not due to some fallout from shutting // down then we will attempt to recover by reconfiguring the listener. // This will close and destruct the current listener and make a new // one with new resources. // @todo This may need a safety valve such as retry count or a timer // to keep from endlessly retrying over and over, with little time // in between. if (!shouldShutdown()) { LOG_INFO (d2_logger, DHCP_DDNS_QUEUE_MGR_RECOVERING); reconfigureQueueMgr(); } break; case D2QueueMgr::STOPPING: // We are waiting for IO to cancel, so this is a NOP. // @todo Possible timer for self-defense? We could conceivably // get into a condition where we never get the event, which would // leave us stuck in stopping. This is hugely unlikely but possible? break; default: // If the reconfigure flag is set, then we are in a state now where // we can do the reconfigure. In other words, we aren't RUNNING or // STOPPING. if (reconf_queue_flag_) { LOG_DEBUG(d2_logger, isc::log::DBGLVL_TRACE_BASIC, DHCP_DDNS_QUEUE_MGR_RECONFIGURING); reconfigureQueueMgr(); } break; } } void D2Process::reconfigureQueueMgr() { // Set reconfigure flag to false. We are only here because we have // a valid configuration to work with so if we fail below, it will be // an operational issue, such as a busy IP address. That will leave // queue manager in INITTED state, which is fine. // What we don't want is to continually attempt to reconfigure so set // the flag false now. // @todo This method assumes only 1 type of listener. This will change // to support at least a TCP version, possibly some form of RDBMS listener // as well. reconf_queue_flag_ = false; try { // Wipe out the current listener. queue_mgr_->removeListener(); // Get the configuration parameters that affect Queue Manager. const D2ParamsPtr& d2_params = getD2CfgMgr()->getD2Params(); // Warn the user if the server address is not the loopback. /// @todo Remove this once we provide a secure mechanism. std::string ip_address = d2_params->getIpAddress().toText(); if (ip_address != "127.0.0.1" && ip_address != "::1") { LOG_WARN(d2_logger, DHCP_DDNS_NOT_ON_LOOPBACK).arg(ip_address); } // Instantiate the listener. if (d2_params->getNcrProtocol() == dhcp_ddns::NCR_UDP) { queue_mgr_->initUDPListener(d2_params->getIpAddress(), d2_params->getPort(), d2_params->getNcrFormat(), true); } else { /// @todo Add TCP/IP once it's supported // We should never get this far but if we do deal with it. isc_throw(DProcessBaseError, "Unsupported NCR listener protocol:" << dhcp_ddns::ncrProtocolToString(d2_params-> getNcrProtocol())); } // Now start it. This assumes that starting is a synchronous, // blocking call that executes quickly. @todo Should that change then // we will have to expand the state model to accommodate this. queue_mgr_->startListening(); } catch (const isc::Exception& ex) { // Queue manager failed to initialize and therefore not listening. // This is most likely due to an unavailable IP address or port, // which is a configuration issue. LOG_ERROR(d2_logger, DHCP_DDNS_QUEUE_MGR_START_ERROR).arg(ex.what()); } } D2Process::~D2Process() { }; D2CfgMgrPtr D2Process::getD2CfgMgr() { // The base class gives a base class pointer to our configuration manager. // Since we are D2, and we need D2 specific extensions, we need a pointer // to D2CfgMgr for some things. return (std::dynamic_pointer_cast<D2CfgMgr>(getCfgMgr())); } const char* D2Process::getShutdownTypeStr(const ShutdownType& type) { const char* str = "invalid"; switch (type) { case SD_NORMAL: str = "normal"; break; case SD_DRAIN_FIRST: str = "drain_first"; break; case SD_NOW: str = "now"; break; default: break; } return (str); } void D2Process::reconfigureCommandChannel() { // Get new socket configuration. isc::data::ElementPtr sock_cfg = getD2CfgMgr()->getControlSocketInfo(); // Determine if the socket configuration has changed. It has if // both old and new configuration is specified but respective // data elements aren't equal. bool sock_changed = (sock_cfg && current_control_socket_ && !sock_cfg->equals(*current_control_socket_)); // If the previous or new socket configuration doesn't exist or // the new configuration differs from the old configuration we // close the existing socket and open a new socket as appropriate. // Note that closing an existing socket means the client will not // receive the configuration result. if (!sock_cfg || !current_control_socket_ || sock_changed) { // Close the existing socket. if (current_control_socket_) { isc::config::CommandMgr::instance().closeCommandSocket(); current_control_socket_.reset(); } // Open the new socket. if (sock_cfg) { isc::config::CommandMgr::instance().openCommandSocket(sock_cfg); } } // Commit the new socket configuration. current_control_socket_ = sock_cfg; } }; // namespace isc::d2 }; // namespace isc
39.632883
82
0.621242
[ "model" ]
6a1c28119f6796346944bf543befcc356f80cb09
2,057
cpp
C++
pxr/usd/lib/usdRi/typeUtils.cpp
YuqiaoZhang/USD
bf3a21e6e049486441440ebf8c0387db2538d096
[ "BSD-2-Clause" ]
88
2018-07-13T01:22:00.000Z
2022-01-16T22:15:27.000Z
pxr/usd/lib/usdRi/typeUtils.cpp
YuqiaoZhang/USD
bf3a21e6e049486441440ebf8c0387db2538d096
[ "BSD-2-Clause" ]
1
2021-08-14T23:57:51.000Z
2021-08-14T23:57:51.000Z
pxr/usd/lib/usdRi/typeUtils.cpp
YuqiaoZhang/USD
bf3a21e6e049486441440ebf8c0387db2538d096
[ "BSD-2-Clause" ]
26
2018-06-06T03:39:22.000Z
2021-08-28T23:02:42.000Z
// // Copyright 2016 Pixar // // Licensed under the Apache License, Version 2.0 (the "Apache License") // with the following modification; you may not use this file except in // compliance with the Apache License and the following modification to it: // Section 6. Trademarks. is deleted and replaced with: // // 6. Trademarks. This License does not grant permission to use the trade // names, trademarks, service marks, or product names of the Licensor // and its affiliates, except as required to comply with Section 4(c) of // the License and to reproduce the content of the NOTICE file. // // You may obtain a copy of the Apache License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the Apache License with the above modification is // distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the Apache License for the specific // language governing permissions and limitations under the Apache License. // #include "pxr/pxr.h" #include "typeUtils.h" #include "pxr/usd/sdf/schema.h" #include "pxr/usd/sdf/types.h" PXR_NAMESPACE_OPEN_SCOPE using std::string; string UsdRi_GetRiType(const SdfValueTypeName &usdType) { // TODO return ""; } SdfValueTypeName UsdRi_GetUsdType(const string &riType) { struct Entry { const char* riName; SdfValueTypeName usdType; }; static Entry map[] = { { "color", SdfValueTypeNames->Color3f }, { "vector", SdfValueTypeNames->Vector3d }, { "normal", SdfValueTypeNames->Normal3d }, { "point", SdfValueTypeNames->Point3d }, { "matrix", SdfValueTypeNames->Matrix4d } }; static const size_t mapLen = sizeof(map)/sizeof(map[0]); for (size_t i = 0; i != mapLen; ++i) { if (riType.find(map[i].riName) != string::npos) return map[i].usdType; } // XXX -- Really? return SdfSchema::GetInstance().FindOrCreateType(riType); } PXR_NAMESPACE_CLOSE_SCOPE
32.140625
75
0.699076
[ "vector" ]
6a206e7e57b67eeb32acff4e8035d21476c25906
4,626
cpp
C++
SDK2013/Template/client/template/clientmode_sdk.cpp
reepblue/SourceSDKContent
32c4340f598ff0c1f129f014a1c5defb5fca756d
[ "Artistic-2.0" ]
15
2016-06-24T11:36:27.000Z
2021-09-04T03:29:42.000Z
SDK2013/Template/client/template/clientmode_sdk.cpp
reepblue/SourceSDKContent
32c4340f598ff0c1f129f014a1c5defb5fca756d
[ "Artistic-2.0" ]
null
null
null
SDK2013/Template/client/template/clientmode_sdk.cpp
reepblue/SourceSDKContent
32c4340f598ff0c1f129f014a1c5defb5fca756d
[ "Artistic-2.0" ]
3
2017-02-02T23:19:54.000Z
2018-04-26T13:36:39.000Z
//========= Copyright Valve Corporation, All rights reserved. ============// // // Purpose: Draws the normal TF2 or HL2 HUD. // //============================================================================= #include "cbase.h" #include "clientmode_sdk.h" #include "clientmode_shared.h" #include "ivmodemanager.h" #include "panelmetaclassmgr.h" // memdbgon must be the last include file in a .cpp file!!! #include "tier0/memdbgon.h" ConVar fov_desired( "fov_desired", "75", FCVAR_ARCHIVE | FCVAR_USERINFO, "Sets the base field-of-view.", true, 75.0, true, 90.0 ); ConVar default_fov( "default_fov", "90", FCVAR_CHEAT ); #if defined( GLOWS_ENABLE ) #include "clienteffectprecachesystem.h" CLIENTEFFECT_REGISTER_BEGIN( PrecachePostProcessingEffectsGlow ) CLIENTEFFECT_MATERIAL( "dev/glow_color" ) CLIENTEFFECT_MATERIAL( "dev/halo_add_to_screen" ) CLIENTEFFECT_REGISTER_END_CONDITIONAL( engine->GetDXSupportLevel() >= 90 ) #endif // Instance the singleton and expose the interface to it. IClientMode *GetClientModeNormal() { static ClientModeSDKNormal g_ClientModeNormal; return &g_ClientModeNormal; } //----------------------------------------------------------------------------- // Purpose: this is the viewport that contains all the hud elements //----------------------------------------------------------------------------- class CHudViewport : public CBaseViewport { private: DECLARE_CLASS_SIMPLE( CHudViewport, CBaseViewport ); protected: virtual void ApplySchemeSettings( vgui::IScheme *pScheme ) { BaseClass::ApplySchemeSettings( pScheme ); gHUD.InitColors( pScheme ); SetPaintBackgroundEnabled( false ); } virtual void CreateDefaultPanels( void ) { /* don't create any panels yet*/ }; }; //----------------------------------------------------------------------------- // ClientModeHLNormal implementation //----------------------------------------------------------------------------- ClientModeSDKNormal::ClientModeSDKNormal() { m_pViewport = new CHudViewport(); m_pViewport->Start( gameuifuncs, gameeventmanager ); } //----------------------------------------------------------------------------- // Purpose: Use of glow render effect. //----------------------------------------------------------------------------- #ifdef ASW_ENGINE bool ClientModeSDKNormal::DoPostScreenSpaceEffects( const CViewSetup *pSetup ) { CMatRenderContextPtr pRenderContext( materials ); g_GlowObjectManager.RenderGlowEffects( pSetup, 0 /*GetSplitScreenPlayerSlot()*/ ); return true; } #endif //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- ClientModeSDKNormal::~ClientModeSDKNormal() { } //----------------------------------------------------------------------------- // Purpose: Use of glow render effect. //----------------------------------------------------------------------------- bool ClientModeSDKNormal::DoPostScreenSpaceEffects( const CViewSetup *pSetup ) { #if defined( GLOWS_ENABLE ) g_GlowObjectManager.RenderGlowEffects( pSetup, 0 ); #endif return true; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void ClientModeSDKNormal::Init() { BaseClass::Init(); } // The current client mode. Always ClientModeNormal in HL. IClientMode *g_pClientMode = NULL; #define SCREEN_FILE "scripts/vgui_screens.txt" class CSDKModeManager : public IVModeManager { public: CSDKModeManager( void ); virtual ~CSDKModeManager( void ); virtual void Init( void ); virtual void SwitchMode( bool commander, bool force ); virtual void OverrideView( CViewSetup *pSetup ); virtual void CreateMove( float flInputSampleTime, CUserCmd *cmd ); virtual void LevelInit( const char *newmap ); virtual void LevelShutdown( void ); }; CSDKModeManager::CSDKModeManager( void ) { } CSDKModeManager::~CSDKModeManager( void ) { } void CSDKModeManager::Init( void ) { g_pClientMode = GetClientModeNormal(); PanelMetaClassMgr()->LoadMetaClassDefinitionFile( SCREEN_FILE ); } void CSDKModeManager::SwitchMode( bool commander, bool force ) { } void CSDKModeManager::OverrideView( CViewSetup *pSetup ) { } void CSDKModeManager::CreateMove( float flInputSampleTime, CUserCmd *cmd ) { } void CSDKModeManager::LevelInit( const char *newmap ) { g_pClientMode->LevelInit( newmap ); } void CSDKModeManager::LevelShutdown( void ) { g_pClientMode->LevelShutdown(); } static CSDKModeManager g_SDKModeManager; IVModeManager *modemanager = &g_SDKModeManager;
28.555556
130
0.590575
[ "render" ]
6a20fa6442a81ee95ab2a0a4e0c7e4a2f3e9e696
3,852
cpp
C++
Systems/Physics/ConstraintRanges.cpp
jodavis42/ZeroPhysicsTestbed
e84a3f6faf16b7a4242dc049121b5338e80039f8
[ "MIT" ]
52
2018-09-11T17:18:35.000Z
2022-03-13T15:28:21.000Z
Systems/Physics/ConstraintRanges.cpp
jodavis42/ZeroPhysicsTestbed
e84a3f6faf16b7a4242dc049121b5338e80039f8
[ "MIT" ]
1,409
2018-09-19T18:03:43.000Z
2021-06-09T08:33:33.000Z
Systems/Physics/ConstraintRanges.cpp
jodavis42/ZeroPhysicsTestbed
e84a3f6faf16b7a4242dc049121b5338e80039f8
[ "MIT" ]
26
2018-09-11T17:16:32.000Z
2021-11-22T06:21:19.000Z
/////////////////////////////////////////////////////////////////////////////// /// /// Authors: Joshua Davis /// Copyright 2011-2017, DigiPen Institute of Technology /// /////////////////////////////////////////////////////////////////////////////// #include "Precompiled.hpp" namespace Zero { //-------------------------------------------------------------------ContactGraphEdge ZilchDefineType(ContactGraphEdge, builder, type) { ZilchBindDefaultCopyDestructor(); ZeroBindDocumented(); ZilchBindGetterProperty(Object); ZilchBindGetterProperty(OtherObject); ZilchBindGetterProperty(IsGhost); ZilchBindGetterProperty(ContactPointCount); ZilchBindGetterProperty(ContactPoints); //ZilchBindGetterProperty(IsNew); ZilchBindGetterProperty(FirstPoint); } ContactGraphEdge::ContactGraphEdge(EdgeType* edge) : BaseType(edge) { } bool ContactGraphEdge::GetIsGhost() { return BaseType::GetIsGhost(); } uint ContactGraphEdge::GetContactPointCount() { return mConstraint->GetContactCount(); } ContactPointRange ContactGraphEdge::GetContactPoints() { // Find out if we're object 0 or object 1 in the manifold uint objectIndex = 0; if(mConstraint->mManifold->Objects[0] != GetCollider()) objectIndex = 1; ContactPointRange range; range.Set(mConstraint->mManifold, objectIndex); return range; } ContactPoint ContactGraphEdge::GetFirstPoint() { // Find out if we're object 0 or object 1 in the manifold uint objectIndex = 0; if(mConstraint->mManifold->Objects[0] != GetCollider()) objectIndex = 1; ContactPoint proxyPoint; proxyPoint.Set(mConstraint->mManifold, &mConstraint->mManifold->Contacts[0], objectIndex); return proxyPoint; } bool ContactGraphEdge::GetIsNew() { return mConstraint->GetIsNew(); } bool ContactGraphEdge::GetSkipsResolution() { return mConstraint->GetSkipResolution(); } Physics::Contact& ContactGraphEdge::GetContact() { return GetConstraint(); } //-------------------------------------------------------------------JointGraphEdge ZilchDefineType(JointGraphEdge, builder, type) { ZilchBindDefaultCopyDestructor(); ZeroBindDocumented(); ZilchBindGetterProperty(Object); ZilchBindGetterProperty(OtherObject); ZilchBindGetterProperty(Valid); ZilchBindGetterProperty(Joint); ZilchBindGetterProperty(Owner); } //-------------------------------------------------------------------JointBodyFilter typedef BodyFilterPolicy<Joint> JointBodyFilter; JointBodyFilter::GraphEdgeType JointBodyFilter::CreateGraphEdge(EdgeType* edge) { return GraphEdgeType(edge); } void JointBodyFilter::SkipDead(RangeType& range) { while(!range.Empty()) { RigidBody* body = range.Front().mOther->GetActiveBody(); if(body && mBodies.Find(body).Empty()) { mBodies.Insert(body); break; } range.PopFront(); } } //-------------------------------------------------------------------ContactBodyFilter typedef BodyFilterPolicy<Physics::Contact> ContactBodyFilter; ContactBodyFilter::GraphEdgeType ContactBodyFilter::CreateGraphEdge(EdgeType* edge) { return GraphEdgeType(edge); } void ContactBodyFilter::SkipDead(RangeType& range) { while(!range.Empty()) { RigidBody* body = range.Front().mOther->GetActiveBody(); if(body && mBodies.Find(body).Empty()) { mBodies.Insert(body); break; } range.PopFront(); } } //-------------------------------------------------------------------Helper functions InList<JointEdge, &JointEdge::ColliderLink>::range GetJointEdges(Collider* collider) { return collider->mJointEdges.All(); } ContactRange FilterContactRange(Collider* collider) { return ContactRange(collider->mContactEdges.All()); } }//namespace Zero
25.342105
93
0.622015
[ "object" ]
6a2414b0205600f359d1ee1832283b0935c8ad98
2,761
cc
C++
third_party/blink/renderer/core/css/resolver/cascade_interpolations_test.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
14,668
2015-01-01T01:57:10.000Z
2022-03-31T23:33:32.000Z
third_party/blink/renderer/core/css/resolver/cascade_interpolations_test.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
113
2015-05-04T09:58:14.000Z
2022-01-31T19:35:03.000Z
third_party/blink/renderer/core/css/resolver/cascade_interpolations_test.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "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 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "third_party/blink/renderer/core/css/resolver/cascade_interpolations.h" #include <gtest/gtest.h> namespace blink { TEST(CascadeInterpolationsTest, Limit) { constexpr size_t max = std::numeric_limits<uint8_t>::max(); static_assert(CascadeInterpolations::kMaxEntryIndex == max, "Unexpected max. If the limit increased, evaluate whether it " "still makes sense to run this test"); ActiveInterpolationsMap map; CascadeInterpolations interpolations; for (size_t i = 0; i <= max; ++i) interpolations.Add(&map, CascadeOrigin::kAuthor); // At maximum EXPECT_FALSE(interpolations.IsEmpty()); interpolations.Add(&map, CascadeOrigin::kAuthor); // Maximum + 1 EXPECT_TRUE(interpolations.IsEmpty()); } TEST(CascadeInterpolationsTest, Reset) { ActiveInterpolationsMap map; CascadeInterpolations interpolations; EXPECT_TRUE(interpolations.IsEmpty()); interpolations.Add(&map, CascadeOrigin::kAuthor); EXPECT_FALSE(interpolations.IsEmpty()); interpolations.Reset(); EXPECT_TRUE(interpolations.IsEmpty()); } TEST(CascadeInterpolationsTest, EncodeDecodeInterpolationPropertyID) { for (CSSPropertyID id : CSSPropertyIDList()) { EXPECT_EQ(id, DecodeInterpolationPropertyID( EncodeInterpolationPosition(id, 0u, false))); EXPECT_EQ(id, DecodeInterpolationPropertyID( EncodeInterpolationPosition(id, 255u, false))); EXPECT_EQ(id, DecodeInterpolationPropertyID( EncodeInterpolationPosition(id, 255u, true))); } } TEST(CascadeInterpolationsTest, EncodeDecodeInterpolationIndex) { CSSPropertyID id = kLastCSSProperty; for (uint8_t index : Vector<uint8_t>({0u, 1u, 15u, 51u, 254u, 255u})) { EXPECT_EQ(index, DecodeInterpolationIndex( EncodeInterpolationPosition(id, index, false))); } } TEST(CascadeInterpolationsTest, EncodeDecodeIsPresentationAttribute) { CSSPropertyID id = kLastCSSProperty; EXPECT_FALSE(DecodeIsPresentationAttribute( EncodeInterpolationPosition(id, 0u, false))); EXPECT_FALSE(DecodeIsPresentationAttribute( EncodeInterpolationPosition(id, 13u, false))); EXPECT_FALSE(DecodeIsPresentationAttribute( EncodeInterpolationPosition(id, 255u, false))); EXPECT_TRUE( DecodeIsPresentationAttribute(EncodeInterpolationPosition(id, 0u, true))); EXPECT_TRUE(DecodeIsPresentationAttribute( EncodeInterpolationPosition(id, 13u, true))); EXPECT_TRUE(DecodeIsPresentationAttribute( EncodeInterpolationPosition(id, 255u, true))); } } // namespace blink
33.670732
80
0.737776
[ "vector" ]
6a260a7397c88340218a3af99687e4a9a29d05ef
7,276
cpp
C++
sandbox/SVM/softmargin/svm.cpp
convexbrain/studynote
a2b1b53474eee1a5a1de58fc682c100ae19f2633
[ "MIT" ]
3
2018-04-23T14:38:41.000Z
2021-09-09T16:57:35.000Z
sandbox/SVM/softmargin/svm.cpp
convexbrain/studynote
a2b1b53474eee1a5a1de58fc682c100ae19f2633
[ "MIT" ]
3
2019-11-04T15:19:31.000Z
2021-02-13T12:27:15.000Z
sandbox/SVM/softmargin/svm.cpp
convexbrain/studynotes
b562c8ce3c21cda389ae4973452e1b7c0f46a67d
[ "MIT" ]
null
null
null
#include "svm.h" #include <algorithm> #include <vector> #include <math.h> static SCALAR product(SCALAR *x0, SCALAR *x1, int dim) { SCALAR r = 0.0; for(int i = 0; i < dim; i++) { r += *x0++ * *x1++; } return r; } static SCALAR polynomial(SCALAR *x0, SCALAR *x1, int dim, SCALAR c, int d) { SCALAR r = 0.0; for(int i = 0; i < dim; i++) { r += *x0++ * *x1++; } SCALAR rr = 1.0; for(int i = 0; i < d; i++) { rr *= (r + c); } return rr; } static SCALAR gaussian(SCALAR *x0, SCALAR *x1, int dim, SCALAR sigma2) { SCALAR r = 0.0; for(int i = 0; i < dim; i++) { r += (*x0 - *x1) * (*x0 - *x1); x0++; x1++; } return exp(-r / sigma2); } SCALAR SVM::kernel(SCALAR *x0, SCALAR *x1) const { //return product(x0, x1, dim); //return polynomial(x0, x1, dim, 1.0, 2); return gaussian(x0, x1, dim, 1.0/8); } SCALAR SVM::w(SCALAR *x) const { SCALAR wx = 0.0; for(SVector *ptr_v = sv; ptr_v < sv + num; ptr_v++) { if(ptr_v->a > 0.0) { wx += ptr_v->a * ptr_v->y * kernel(ptr_v->x, x); } } return wx; } void SVM::calc_bias(void) { SCALAR min_wx_p = 0.0; SCALAR max_wx_n = 0.0; bool first_p = true; bool first_n = true; for(SVector *ptr_v = sv; ptr_v < sv + num; ptr_v++) { if( (0.0 < ptr_v->a) && (ptr_v->a < m_a) ) { if(ptr_v->y > 0) { if(first_p) { first_p = false; min_wx_p = w(ptr_v->x); } else { min_wx_p = min(min_wx_p, w(ptr_v->x)); } } else { if(first_n) { first_n = false; max_wx_n = w(ptr_v->x); } else { max_wx_n = max(max_wx_n, w(ptr_v->x)); } } } } b = - ( max_wx_n + min_wx_p ) / 2.0; } bool SVM::smo_update(SVector *v0, SVector *v1) { if((v0 == v1) || (v0 == NULL) || (v1 == NULL)) return false; SCALAR e0 = w(v0->x) /* + b */ - v0->y; SCALAR e1 = w(v1->x) /* + b */ - v1->y; SCALAR k = kernel(v0->x, v0->x) + kernel(v1->x, v1->x) - 2.0 * kernel(v0->x, v1->x); SCALAR a0 = v0->a + v0->y * (e1 - e0) / k; SCALAR u; SCALAR v; if(v0->y != v1->y) { u = max(0.0, v0->a - v1->a); v = min(m_a, v0->a - v1->a + m_a); } else { u = max(0.0, v0->a + v1->a - m_a); v = min(m_a, v0->a + v1->a); } a0 = max(u, a0); a0 = min(v, a0); if(a0 < 0.0 + EPSILON) a0 = 0.0; if(a0 > m_a - EPSILON) a0 = m_a; SCALAR a1 = v1->a + v0->y * v1->y * (v0->a - a0); if(a1 < 0.0 + EPSILON) a1 = 0.0; if(a1 > m_a - EPSILON) a1 = m_a; if( isnan(a0) || isnan(a1) ) return false; if( (abs(v0->a - a0) < EPSILON) && (abs(v1->a - a1) < EPSILON) ) return false; //cerr << v0 << " " << v1 << " "; //cerr << abs(v0->a - a0) << " " << abs(v1->a - a1) << " "; //cerr << a0 << " " << a1 << endl; v0->a = a0; v1->a = a1; return true; } bool SVM::smo_iteration(bool scanall) { vector<SVector*> cand0; for(SVector *ptr_v = sv; ptr_v < sv + num; ptr_v++) { SCALAR c = 1.0 - ptr_v->y * (w(ptr_v->x) + b); if(ptr_v->a < 0.0 + EPSILON) { if(scanall && (c > 0.0) ) { cand0.push_back(ptr_v); } } else if(ptr_v->a > m_a - EPSILON) { if(scanall && (c < 0.0) ) { cand0.push_back(ptr_v); } } else { if(abs(c) > EPSILON) { cand0.push_back(ptr_v); } } } random_shuffle ( cand0.begin(), cand0.end() ); while(!cand0.empty()) { vector<SVector*> cand1_2nd, cand1_3rd; SVector *v0 = cand0.back(); SVector *v1 = NULL; SCALAR maxe = 0.0; SCALAR e0 = w(v0->x) /* + b */ - v0->y; for(SVector *ptr_v = sv; ptr_v < sv + num; ptr_v++) { if( (0.0 < ptr_v->a) && (ptr_v->a < m_a) ) { SCALAR e1 = w(ptr_v->x) /* + b */ - ptr_v->y; if(abs(e0 - e1) > maxe) { if(v1 != NULL) cand1_2nd.push_back(v1); v1 = ptr_v; maxe = abs(e0 - e1); } else { cand1_2nd.push_back(ptr_v); } } else { cand1_3rd.push_back(ptr_v); } } if(smo_update(v0, v1)) return true; random_shuffle ( cand1_2nd.begin(), cand1_2nd.end() ); while(!cand1_2nd.empty()) { v1 = cand1_2nd.back(); if(smo_update(v0, v1)) return true; cand1_2nd.pop_back(); } random_shuffle ( cand1_3rd.begin(), cand1_3rd.end() ); while(!cand1_3rd.empty()) { v1 = cand1_3rd.back(); if(smo_update(v0, v1)) return true; cand1_3rd.pop_back(); } cand0.pop_back(); } return false; } void SVM::operator<<(const SCALAR &d) { //cerr << d << endl; if(input < sv + num) { if(cnt_x < dim) { input->x[cnt_x] = d; cnt_x++; } else { input->y = (d > 0.0)? 1: -1; input->a = 0.0; input++; cnt_x = 0; } } else { cerr << "Error: input data overflow!" << endl; } } void SVM::dprint(ostream &ofs) const { if(input < sv + num) { cerr << "Error: lack of input data!" << endl; return; } /* for(SVector *ptr_v = sv; ptr_v < sv + num; ptr_v++) { SCALAR *x = ptr_v->x; for(int i = 0; i < dim; i++) ofs << (*x++) << " "; ofs << " " << (ptr_v->a) << " " << (w(ptr_v->x) + b) << endl; } ofs << endl << endl; return; */ ofs << "# 1 : lower boundaries, positive" << endl; for(SVector *ptr_v = sv; ptr_v < sv + num; ptr_v++) { if((ptr_v->y > 0) && (ptr_v->a < 0.0 + EPSILON)) { SCALAR *x = ptr_v->x; ofs << "1 "; for(int i = 0; i < dim; i++) ofs << (*x++) << " "; ofs << " " << (ptr_v->a) << " " << (w(ptr_v->x) + b) << endl; } } ofs << "# 2 : lower boundaries, negative" << endl; for(SVector *ptr_v = sv; ptr_v < sv + num; ptr_v++) { if((ptr_v->y < 0) && (ptr_v->a < 0.0 + EPSILON)) { SCALAR *x = ptr_v->x; ofs << "2 "; for(int i = 0; i < dim; i++) ofs << (*x++) << " "; ofs << " " << (ptr_v->a) << " " << (w(ptr_v->x) + b) << endl; } } ofs << "# 3 : upper boundaries, positive" << endl; for(SVector *ptr_v = sv; ptr_v < sv + num; ptr_v++) { if((ptr_v->y > 0) && (ptr_v->a > m_a - EPSILON)) { SCALAR *x = ptr_v->x; ofs << "3 "; for(int i = 0; i < dim; i++) ofs << (*x++) << " "; ofs << " " << (ptr_v->a) << " " << (w(ptr_v->x) + b) << endl; } } ofs << "# 4 : upper boundaries, negative" << endl; for(SVector *ptr_v = sv; ptr_v < sv + num; ptr_v++) { if((ptr_v->y < 0) && (ptr_v->a > m_a - EPSILON)) { SCALAR *x = ptr_v->x; ofs << "4 "; for(int i = 0; i < dim; i++) ofs << (*x++) << " "; ofs << " " << (ptr_v->a) << " " << (w(ptr_v->x) + b) << endl; } } ofs << "# 5 : support vectors, positive" << endl; for(SVector *ptr_v = sv; ptr_v < sv + num; ptr_v++) { if((ptr_v->y > 0) && (0.0 < ptr_v->a) && (ptr_v->a < m_a)) { SCALAR *x = ptr_v->x; ofs << "5 "; for(int i = 0; i < dim; i++) ofs << (*x++) << " "; ofs << " " << (ptr_v->a) << " " << (w(ptr_v->x) + b) << endl; } } ofs << "# 6 : support vectors, negaitive" << endl; for(SVector *ptr_v = sv; ptr_v < sv + num; ptr_v++) { if((ptr_v->y < 0) && (0.0 < ptr_v->a) && (ptr_v->a < m_a)) { SCALAR *x = ptr_v->x; ofs << "6 "; for(int i = 0; i < dim; i++) ofs << (*x++) << " "; ofs << " " << (ptr_v->a) << " " << (w(ptr_v->x) + b) << endl; } } ofs << endl << endl; } int SVM::learn(int n_iterate) { if(input < sv + num) { cerr << "Error: lack of input data!" << endl; } bool scanall = true; int i; for(i = 0; i != n_iterate; i++) { bool changed = smo_iteration(scanall); calc_bias(); if(scanall) { if(!changed) break; scanall = false; } else { if(!changed) scanall = true; } } return i; }
21.4
85
0.491754
[ "vector" ]
6a2aa195ca6ac7768187ffff4a96dd3d4e966387
1,139
cpp
C++
Easy/645_findErrorNums/645_findErrorNums/main.cpp
yangbingjie/Leetcode
2f1e386cfb8b2d7d49cf0e7dcf0bce1c936e1916
[ "MIT" ]
1
2020-10-08T06:15:37.000Z
2020-10-08T06:15:37.000Z
Easy/645_findErrorNums/645_findErrorNums/main.cpp
yangbingjie/Leetcode
2f1e386cfb8b2d7d49cf0e7dcf0bce1c936e1916
[ "MIT" ]
null
null
null
Easy/645_findErrorNums/645_findErrorNums/main.cpp
yangbingjie/Leetcode
2f1e386cfb8b2d7d49cf0e7dcf0bce1c936e1916
[ "MIT" ]
null
null
null
// // main.cpp // 645_findErrorNums // // Created by bella on 2020/8/11. // Copyright © 2020 bella. All rights reserved. // #include <iostream> #include <vector> using namespace std; class Solution { public: vector<int> findErrorNums(vector<int>& nums) { vector<int>result; int i = 0; while (i < nums.size()) { if (nums[i] != i + 1) { if (nums[i] == nums[nums[i] - 1]) { break; } swap(nums[i], nums[nums[i] - 1]); }else{ ++i; } } result.push_back(nums[i]); int miss = nums[0]; for (int i = 1; i < nums.size(); ++i) { miss ^= i; miss ^= nums[i]; } miss ^= nums.size(); miss ^= result[0]; result.push_back(miss); return result; } }; int main(int argc, const char * argv[]) { // const int LEN = 8; // int arr[LEN] = {8,7,3,5,3,6,1,4}; const int LEN = 4; int arr[LEN] = {1,2,2,4}; vector<int>nums(arr, arr +LEN); Solution s; s.findErrorNums(nums); return 0; }
23.244898
51
0.460931
[ "vector" ]
6a353613f5953f110f4a1349f24793469a591ffe
1,633
cpp
C++
android-29/android/telephony/CellInfoCdma.cpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
12
2020-03-26T02:38:56.000Z
2022-03-14T08:17:26.000Z
android-29/android/telephony/CellInfoCdma.cpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
1
2021-01-27T06:07:45.000Z
2021-11-13T19:19:43.000Z
android-29/android/telephony/CellInfoCdma.cpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
3
2021-02-02T12:34:55.000Z
2022-03-08T07:45:57.000Z
#include "../os/Parcel.hpp" #include "./CellIdentityCdma.hpp" #include "./CellSignalStrengthCdma.hpp" #include "../../JObject.hpp" #include "../../JString.hpp" #include "./CellInfoCdma.hpp" namespace android::telephony { // Fields JObject CellInfoCdma::CREATOR() { return getStaticObjectField( "android.telephony.CellInfoCdma", "CREATOR", "Landroid/os/Parcelable$Creator;" ); } // QJniObject forward CellInfoCdma::CellInfoCdma(QJniObject obj) : android::telephony::CellInfo(obj) {} // Constructors // Methods jint CellInfoCdma::describeContents() const { return callMethod<jint>( "describeContents", "()I" ); } jboolean CellInfoCdma::equals(JObject arg0) const { return callMethod<jboolean>( "equals", "(Ljava/lang/Object;)Z", arg0.object<jobject>() ); } android::telephony::CellIdentityCdma CellInfoCdma::getCellIdentity() const { return callObjectMethod( "getCellIdentity", "()Landroid/telephony/CellIdentityCdma;" ); } android::telephony::CellSignalStrengthCdma CellInfoCdma::getCellSignalStrength() const { return callObjectMethod( "getCellSignalStrength", "()Landroid/telephony/CellSignalStrengthCdma;" ); } jint CellInfoCdma::hashCode() const { return callMethod<jint>( "hashCode", "()I" ); } JString CellInfoCdma::toString() const { return callObjectMethod( "toString", "()Ljava/lang/String;" ); } void CellInfoCdma::writeToParcel(android::os::Parcel arg0, jint arg1) const { callMethod<void>( "writeToParcel", "(Landroid/os/Parcel;I)V", arg0.object(), arg1 ); } } // namespace android::telephony
20.4125
87
0.690753
[ "object" ]
6a3794d647cc94cfbc5ee9bb92742db15971bd42
2,718
cpp
C++
AdventOfCode/2020/j.cpp
onexmaster/cp
b78b0f1e586d6977d86c97b32f48fed33f1469af
[ "Apache-2.0", "MIT" ]
null
null
null
AdventOfCode/2020/j.cpp
onexmaster/cp
b78b0f1e586d6977d86c97b32f48fed33f1469af
[ "Apache-2.0", "MIT" ]
null
null
null
AdventOfCode/2020/j.cpp
onexmaster/cp
b78b0f1e586d6977d86c97b32f48fed33f1469af
[ "Apache-2.0", "MIT" ]
null
null
null
// Created by Tanuj Jain #include<bits/stdc++.h> #include<ext/pb_ds/assoc_container.hpp> #include<ext/pb_ds/tree_policy.hpp> using namespace std; using namespace __gnu_pbds; #define pb push_back #define mp make_pair # define M_PI 3.14159265358979323846 /* pi */ #define FIO ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL); typedef long long ll; typedef pair<int,int> pii; typedef pair<ll,ll>pll; template<class T> using oset=tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>; const int INF = 0x3f3f3f3f; int knight_moves[8][2]={{-2,-1},{-1,-2},{1,-2},{2,-1},{-2,1},{-1,2},{1,2},{2,1}}; int moves[4][2]={{0,1},{0,-1},{1,0},{-1,0}}; struct custom_hash { static uint64_t splitmix64(uint64_t x) { // http://xorshift.di.unimi.it/splitmix64.c x += 0x9e3779b97f4a7c15; x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9; x = (x ^ (x >> 27)) * 0x94d049bb133111eb; return x ^ (x >> 31); } size_t operator()(uint64_t x) const { static const uint64_t FIXED_RANDOM = chrono::steady_clock::now().time_since_epoch().count(); return splitmix64(x + FIXED_RANDOM); } }; set<int>st; ll found; int looking; map<int,ll>dp; ll solve(int prev,set<int>st) { if(prev==looking) return 1; if(dp.count(prev)>0) return dp[prev]; //check the transitions states ll ways=0; if(st.find(prev+1)!=st.end()) { ways+=solve(prev+1,st); } if(st.find(prev+2)!=st.end()) { ways+=solve(prev+2,st); } if(st.find(prev+3)!=st.end()) { ways+=solve(prev+3,st); } return dp[prev]=ways; } int main() { FIO; #ifndef ONLINE_JUDGE freopen("input.txt","r",stdin); freopen("output.txt","w",stdout); #endif vector<ll>temp; ll x; while(cin>>x) { temp.pb(x); } sort(temp.begin(),temp.end()); vector<int>init(4,0); int prev=0; for(int i=0;i<temp.size();i++) { if(temp[i]-prev==0) { init[0]++; prev=temp[i]; } else if(temp[i]-prev==1) { init[1]++; prev=temp[i]; } else if(temp[i]-prev==2) { init[2]++; prev=temp[i]; } else if(temp[i]-prev==3) { init[3]++; prev=temp[i]; } else { break; } } found=0; looking=temp[temp.size()-1]+3; temp.pb(looking); set<int>st(temp.begin(),temp.end()); solve(0,st); cout<<dp[0]; return 0; }
24.267857
106
0.513245
[ "vector" ]
6a3c829b583c2f65d1d230889451fe3c5ef0073a
13,249
cpp
C++
Tracing/MDL2/new_mst_try.cpp
tostathaina/farsight
7e9d6d15688735f34f7ca272e4e715acd11473ff
[ "Apache-2.0" ]
8
2016-07-22T11:24:19.000Z
2021-04-10T04:22:31.000Z
Tracing/MDL2/new_mst_try.cpp
YanXuHappygela/Farsight
1711b2a1458c7e035edd21fe0019a1f7d23fcafa
[ "Apache-2.0" ]
null
null
null
Tracing/MDL2/new_mst_try.cpp
YanXuHappygela/Farsight
1711b2a1458c7e035edd21fe0019a1f7d23fcafa
[ "Apache-2.0" ]
7
2016-07-21T07:39:17.000Z
2020-01-29T02:03:27.000Z
#include <stdio.h> #include <time.h> #include <vector> #include <algorithm> #include <itkImageFileReader.h> #include <itkImageFileWriter.h> #include <itkImageRegionIterator.h> #include <itkImageRegionConstIterator.h> #include <itkImageSliceConstIteratorWithIndex.h> #include <itkImageLinearIteratorWithIndex.h> #include <itkConstNeighborhoodIterator.h> #include <itkMedianImageFilter.h> #include <itkMeanImageFilter.h> #include <itkBinaryThresholdImageFilter.h> #include <itkBinaryMedianImageFilter.h> #include <itkOtsuThresholdImageFilter.h> #include <itkShiftScaleImageFilter.h> #include <itkConnectedComponentImageFilter.h> #include <itkRelabelComponentImageFilter.h> #include <itkBinaryErodeImageFilter.h> #include <itkBinaryDilateImageFilter.h> #include <itkBinaryBallStructuringElement.h> #include <itkDanielssonDistanceMapImageFilter.h> #include <itkVector.h> #include <itkVTKImageExport.h> #include <itkVTKImageImport.h> #include <vnl/vnl_matrix.h> #include <vnl/vnl_hungarian_algorithm.h> #include <itkFastMarchingImageFilter.h> #include "itkHessian3DToVesselnessMeasureImageFilter.h" #include "itkMultiScaleHessianBasedMeasureImageFilter.h" #include "itkSymmetricSecondRankTensor.h" #include "itkGrayscaleErodeImageFilter.h" #include "itkGrayscaleDilateImageFilter.h" #include "mdlMST.h" #include "mdlUtils.h" #define MAX(a,b) (((a) > (b))?(a):(b)) #define MIN(a,b) (((a) < (b))?(a):(b)) //typedefs typedef unsigned char InputPixelType; typedef unsigned char OutputPixelType; typedef itk::Vector<unsigned char, 3> VectorPixelType; typedef itk::Image<VectorPixelType, 3> ColorImageType; typedef itk::Image<VectorPixelType, 2> Color2DImageType; typedef itk::Image<InputPixelType,3> InputImageType; typedef itk::Image<float,3> FloatImageType; typedef itk::Image<OutputPixelType,3> OutputImageType; typedef itk::Image<short int,3> LabelImageType; typedef itk::Image<InputPixelType,2> Input2DImageType; typedef itk::Image<InputPixelType,2> Output2DImageType; typedef itk::ImageRegionConstIterator<InputImageType> ConstIteratorType; typedef itk::ImageRegionIterator<InputImageType> IteratorType; typedef itk::ImageRegionConstIterator<LabelImageType> ConstLabelIteratorType; typedef itk::ImageRegionIterator<LabelImageType> LabelIteratorType; typedef itk::ImageRegionConstIterator<Input2DImageType> Const2DIteratorType; typedef itk::ImageRegionIterator<Input2DImageType> twoDIteratorType; typedef itk::ImageRegionConstIterator<ColorImageType> ConstColorIteratorType; typedef itk::ImageRegionIterator<ColorImageType> ColorIteratorType; typedef itk::ImageLinearIteratorWithIndex< Input2DImageType > LinearIteratorType; typedef itk::ImageSliceConstIteratorWithIndex< InputImageType > SliceIteratorType; typedef itk::ImageLinearIteratorWithIndex< Color2DImageType > LinearColorIteratorType; typedef itk::ImageSliceConstIteratorWithIndex< ColorImageType > SliceColorIteratorType; typedef itk::ConstNeighborhoodIterator<InputImageType> NeighborhoodIteratorType; typedef itk::MedianImageFilter<InputImageType,InputImageType> MedianFilterType; typedef itk::BinaryMedianImageFilter<InputImageType,InputImageType> BinaryMedianFilterType; typedef itk::Image<bool,3> BoolImageType; typedef itk::BinaryThresholdImageFilter<InputImageType,OutputImageType> ThresholdFilterType; typedef itk::OtsuThresholdImageFilter<InputImageType,OutputImageType> OtsuThresholdFilterType; typedef itk::Image<short int,3> DistanceImageType; typedef itk::DanielssonDistanceMapImageFilter<InputImageType,DistanceImageType> DistanceMapFilterType; typedef DistanceMapFilterType::VectorImageType OffsetImageType; typedef itk::ConnectedComponentImageFilter<InputImageType,LabelImageType> ConnectedFilterType; typedef itk::RelabelComponentImageFilter<LabelImageType,LabelImageType> RelabelFilterType; template <typename T> typename T::Pointer readImage(const char *filename) { printf("Reading %s ... ",filename); typedef typename itk::ImageFileReader<T> ReaderType; typename ReaderType::Pointer reader = ReaderType::New(); ReaderType::GlobalWarningDisplayOff(); reader->SetFileName(filename); try { reader->Update(); } catch(itk::ExceptionObject &err) { std::cout << "ExceptionObject caught!" <<std::endl; std::cout << err << std::endl; //return EXIT_FAILURE; } printf("Done.\n"); return reader->GetOutput(); } template <typename T> int writeImage(typename T::Pointer im, const char* filename) { printf("Writing %s ... ",filename); typedef typename itk::ImageFileWriter<T> WriterType; typename WriterType::Pointer writer = WriterType::New(); writer->SetFileName(filename); writer->SetInput(im); try { writer->Update(); } catch(itk::ExceptionObject &err) { std::cout << "ExceptionObject caught!" <<std::endl; std::cout << err << std::endl; return EXIT_FAILURE; } printf("Done.\n"); return EXIT_SUCCESS; } void get_tiles(InputImageType::RegionType inputr, int tilesizex, int tilesizey, int tilesizez, int borderx, int bordery, int borderz, std::vector<InputImageType::RegionType> &in1, std::vector<InputImageType::RegionType> &in2, std::vector<InputImageType::RegionType> &out1, std::vector<InputImageType::RegionType> &out2) { int xsize = inputr.GetSize()[0]; int ysize = inputr.GetSize()[1]; int zsize = inputr.GetSize()[2]; int kx = 0;int ky = 0;int kz = 0; kx = xsize /(tilesizex-borderx); ky = ysize /(tilesizey-bordery); kz = zsize /(tilesizez-borderz); int remx = xsize % (tilesizex-borderx); int remy = ysize % (tilesizey-bordery); int remz = zsize % (tilesizez-borderz); if ( remx > 0 ) kx ++; if ( remy > 0 ) ky ++; if ( remz > 0 ) kz ++; for(int xco = 0; xco < kx; xco++) { for(int yco = 0; yco < ky; yco++) { for(int zco = 0; zco < kz; zco++) { InputImageType::SizeType imsize = inputr.GetSize(); InputImageType::IndexType index; InputImageType::SizeType size; index.Fill(0); size[0] = MIN((xco)*(tilesizex-borderx)+tilesizex-1,imsize[0]-1) - xco * (tilesizex-borderx) +1; size[1] = MIN((yco)*(tilesizey-bordery)+tilesizey-1,imsize[1]-1) - yco * (tilesizey-bordery) +1; size[2] = MIN((zco)*(tilesizez-borderz)+tilesizez-1,imsize[2]-1) - zco * (tilesizez-borderz) +1; InputImageType::RegionType region; region.SetIndex(index); region.SetSize(size); in2.push_back(region); InputImageType::RegionType region1; index[0] = xco *(tilesizex-borderx); index[1] = yco *(tilesizey-bordery); index[2] = zco *(tilesizez-borderz); region1.SetIndex(index); region1.SetSize(size); in1.push_back(region1); if(xco != 0) { size[0] = size[0] - borderx/2; index[0] = borderx/2; } if(xco != kx-1) { size[0] = size[0] - borderx/2; } if(yco != 0) { size[1] = size[1] - bordery/2; index[1] = bordery/2; } if(yco != ky-1) { size[1] = size[1] - bordery/2; } if(zco != 0) { size[2] = size[2] - borderz/2; index[2] = borderz/2; } if(zco != kz-1) { size[2] = size[2] - borderz/2; } region.SetIndex(index); region.SetSize(size); out2.push_back(region); if(xco!=0) { index[0] = xco *(tilesizex-borderx)+borderx/2; } if(yco!=0) { index[1] = yco *(tilesizey-bordery)+bordery/2; } if(zco!=0) { index[2] = zco *(tilesizez-borderz)+borderz/2; } region1.SetIndex(index); region1.SetSize(size); out1.push_back(region1); } } } } int transfer_function1(int val) { float factor = 1.0/2/40/40; return 255*exp(float(-(val-255)*(val-255)*factor)); } int main() { InputImageType::Pointer im = readImage<InputImageType>("C:/Users/arun/Research/Farsight/exe/bin/CF_1_inverted_bg_sub.tif"); FILE *fp = fopen("C:/Users/arun/Research/Farsight/exe/bin/seeds.txt","r"); //IteratorType initer(im,im->GetLargestPossibleRegion()); //initer.GoToBegin(); // //for(;!initer.IsAtEnd(); ++initer) //{ // initer.Set(transfer_function1(initer.Get())); //} // //writeImage<InputImageType>(im,"C:/Users/arun/Research/Farsight/exe/bin/hp2_cropped2_filtered.tif"); // //return 0; typedef itk::SymmetricSecondRankTensor<double,3> HessianType; typedef itk::Hessian3DToVesselnessMeasureImageFilter<float> MeasureType; typedef itk::Image<HessianType,3> HessianImageType; typedef itk::MultiScaleHessianBasedMeasureImageFilter< InputImageType, HessianImageType, FloatImageType> VesselnessFilterType; std::vector<InputImageType::RegionType> in1,in2,out1,out2; get_tiles(im->GetLargestPossibleRegion().GetSize(),1500,1500,1500,100,100,10,in1,in2,out1,out2); InputImageType::Pointer om; /* om = InputImageType::New(); om->SetRegions(im->GetLargestPossibleRegion()); om->Allocate(); for(int counter = 0; counter < in1.size(); counter++) { InputImageType::Pointer imtile = InputImageType::New();// imtile->SetRegions(in2[counter]); imtile->Allocate(); in1[counter].Print(std::cout); in2[counter].Print(std::cout); IteratorType iter1(im,in1[counter]); IteratorType iter2(imtile,in2[counter]); for(iter1.GoToBegin(),iter2.GoToBegin();!iter1.IsAtEnd(); ++iter1,++iter2) { iter2.Set(iter1.Get()); } VesselnessFilterType::Pointer vfilt = VesselnessFilterType::New(); MeasureType::Superclass::Pointer measure = MeasureType::New(); vfilt->SetInput(imtile); vfilt->SetHessianToMeasureFilter((VesselnessFilterType::HessianToMeasureFilterType *)measure); vfilt->SetSigmaMinimum(3.0); vfilt->SetSigmaMaximum(5.0); vfilt->SetNumberOfSigmaSteps(3); vfilt->SetSigmaStepMethod(VesselnessFilterType::EquispacedSigmaSteps); vfilt->Update(); FloatImageType::Pointer omtile = vfilt->GetOutput(); typedef itk::ImageRegionIterator<FloatImageType> FloatIteratorType; FloatIteratorType iter3; iter1 = IteratorType(om,out1[counter]); iter3 = FloatIteratorType(omtile,out2[counter]); for(iter1.GoToBegin(),iter3.GoToBegin();!iter1.IsAtEnd();++iter1,++iter3) { iter1.Set(iter3.Get()); } } writeImage<InputImageType>(om,"C:/Users/arun/Research/Farsight/exe/bin/vesselnesstest.tif"); */ om = readImage<InputImageType>("C:/Users/arun/Research/Farsight/exe/bin/vesselnesstest.tif"); typedef itk::BinaryBallStructuringElement<InputImageType::PixelType,3> StructElementType; typedef itk::GrayscaleDilateImageFilter<InputImageType,InputImageType,StructElementType> FilterType1; FilterType1::Pointer minfilt = FilterType1::New(); minfilt->SetInput(om); FilterType1::RadiusType radius; radius[0] = 1; radius[1] = 1; radius[2] = 1; StructElementType strel; strel.SetRadius(radius); minfilt->SetKernel(strel); minfilt->Update(); InputImageType::Pointer seed_out = InputImageType::New(); seed_out->SetRegions(om->GetLargestPossibleRegion()); seed_out->Allocate(); seed_out->FillBuffer(0); int thresh_value = 6; int number_of_seeds = 200; int tnum_seeds = 0; typedef itk::ImageRegionIteratorWithIndex<InputImageType> IndexIteratorType; IndexIteratorType it1(minfilt->GetOutput(),minfilt->GetOutput()->GetLargestPossibleRegion()); IteratorType it2(om,om->GetLargestPossibleRegion()); for(it2.GoToBegin();!it2.IsAtEnd(); ++it2) { if(it2.Get()>thresh_value) tnum_seeds++; } printf("tnum_seeds = %d\n",tnum_seeds); IteratorType it3(seed_out,seed_out->GetLargestPossibleRegion()); IteratorType it4(im,im->GetLargestPossibleRegion()); std::vector<mdl::fPoint3D> seeds; seeds.clear(); /*for(it1.GoToBegin(),it2.GoToBegin(),it3.GoToBegin(),it4.GoToBegin();!it1.IsAtEnd();++it1,++it2,++it3,++it4) { if(it1.Get()==it2.Get() && it4.Get() > 150) { it3.Set(255); InputImageType::IndexType index = it1.GetIndex(); mdl::fPoint3D seed1; seed1.x = index[0]; seed1.y = index[1]; seed1.z = index[2]; seeds.push_back(seed1); } }*/ seeds.clear(); while(!feof(fp)) { mdl::fPoint3D seed1; fscanf(fp,"%f %f %f",&seed1.x,&seed1.y,&seed1.z); if(feof(fp)) break; seed1.x*=1; seed1.y*=1; seeds.push_back(seed1); } fclose(fp); printf("Seeds.size = %d\n",seeds.size()); //scanf("%*d"); mdl::vtkFileHandler * fhd1 = new mdl::vtkFileHandler(); fhd1->SetNodes(&seeds); std::vector<mdl::pairE> nullpairs; fhd1->SetLines(&nullpairs); std::string outFilename1 = "C:/Users/arun/Research/Farsight/exe/bin/mst_input.vtk"; fhd1->Write(outFilename1.c_str()); delete fhd1; int edgeRange = 50; int morphStrength = 0; mdl::MST *mst = new mdl::MST( im ); mst->SetDebug(false); mst->SetUseVoxelRounding(false); mst->SetEdgeRange(edgeRange); mst->SetPower(1); mst->SetSkeletonPoints( &seeds ); // can choose different weight //mst->CreateGraphAndMST(1); mst->CreateGraphAndMST(5); mst->ErodeAndDialateNodeDegree(morphStrength); std::vector<mdl::fPoint3D> nodes = mst->GetNodes(); std::vector<mdl::pairE> bbpairs = mst->BackboneExtract(); delete mst; std::cerr << "Saving\n"; //**************************************************************** // TREE WRITER mdl::vtkFileHandler * fhd2 = new mdl::vtkFileHandler(); fhd2->SetNodes(&nodes); fhd2->SetLines(&bbpairs); std::string outFilename2 = "C:/Users/arun/Research/Farsight/exe/bin/mst_tree.vtk"; fhd2->Write(outFilename2.c_str()); delete fhd2; scanf("%*d"); writeImage<InputImageType>(seed_out,"C:/Users/arun/Research/Farsight/exe/bin/seedimage.tif"); }
30.598152
319
0.724809
[ "vector" ]
6a45f93d0c587bdf0b476e08c33e92020e0e5ecd
3,944
cc
C++
examples/EchoClient.cc
sroycode/zqrpc
aa2eee8b794f71998e0861f40f0a4e9895d2c527
[ "MIT" ]
6
2015-01-08T17:09:43.000Z
2022-01-28T01:45:57.000Z
examples/EchoClient.cc
sroycode/zqrpc
aa2eee8b794f71998e0861f40f0a4e9895d2c527
[ "MIT" ]
null
null
null
examples/EchoClient.cc
sroycode/zqrpc
aa2eee8b794f71998e0861f40f0a4e9895d2c527
[ "MIT" ]
3
2016-03-04T10:54:42.000Z
2022-01-28T01:45:59.000Z
/** * @project zqrpc * @file examples/EchoClient.cc * @author S Roychowdhury <sroycode @ gmail DOT com> * @version 0.1 * * @section LICENSE * * Copyright (c) 2014 S Roychowdhury * * 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. * * @section DESCRIPTION * * EchoClient.cc : Echo Client * */ #include <iostream> #include <vector> #include "zqrpc.hpp" #include "echo.pb.h" #include "echo.zqrpc.h" #include "EchoEndpoint.hh" struct Basket { zqrpc::ZController controller; echo::EchoRequest request; echo::EchoResponse response; bool use_one; long waitfor; Basket(const char* message,bool use_echo_one, long wait_time) : use_one(use_echo_one),waitfor(wait_time) { request.set_message(message); } virtual ~Basket() {} }; int main(int argc, char *argv[]) { google::InitGoogleLogging(argv[0]); zmq::context_t* context = 0; typedef std::vector<struct Basket> BasketVecT; try { context = new zmq::context_t(1); zqrpc::RpcChannel rpc_channel(context,ECHO_ENDPOINT_PORT); echo::EchoService::Stub stub(&rpc_channel); BasketVecT bask; // 0-1 bask.push_back(Basket("The foolish race of mankind",false,-1)); bask.push_back(Basket("Are swarming below in the night;",false,-1)); // 2-3 bask.push_back(Basket("They shriek and rage and quarrel-",true,-1)); bask.push_back(Basket("And all of them are right.",true,-1)); // Send All for (std::size_t i=0; i<bask.size(); ++i) { if (bask[i].use_one) stub.Echo1_Send(&bask[i].controller, &bask[i].request); else stub.Echo2_Send(&bask[i].controller, &bask[i].request); std::cerr << "Request " << i << ":" << bask[i].request.DebugString() << std::endl; } // Receive 2-3 std::cerr << "RECEIVING 2-end" << std::endl; for (std::size_t i=2; i<bask.size(); ++i) { if (bask[i].use_one) stub.Echo1_Recv(&bask[i].controller, &bask[i].response,bask[i].waitfor); else stub.Echo2_Recv(&bask[i].controller, &bask[i].response,bask[i].waitfor); if (bask[i].controller.ok()) std::cerr << "Response" << i << ":" << bask[i].response.DebugString() << std::endl; else std::cerr << "Error in Response " << i << std::endl; } // Receive 0-1 std::cerr << "RECEIVING 0-1" << std::endl; for (std::size_t i=0; i<2; ++i) { if (bask[i].use_one) stub.Echo1_Recv(&bask[i].controller, &bask[i].response,bask[i].waitfor); else stub.Echo2_Recv(&bask[i].controller, &bask[i].response,bask[i].waitfor); if (bask[i].controller.ok()) std::cerr << "Response" << i << ":" << bask[i].response.DebugString() << std::endl; else std::cerr << "Error in Response " << i << std::endl; } } catch (zmq::error_t& e) { std::cerr << "ZMQ EXCEPTION : " << e.what() << std::endl; } catch (std::exception& e) { std::cerr << "STD EXCEPTION : " << e.what() << std::endl; } catch (...) { std::cerr << " UNTRAPPED EXCEPTION " << std::endl; } if (context) delete context; return 0; }
31.806452
87
0.671146
[ "vector" ]
6a484f8153a9d4592e2dbee7bdc8539c080990f8
1,921
hpp
C++
include/ResourceManager.hpp
bitDaft/Project-TE
f0e0ec184d42b46799d48d69eb4eb9d369cbfcc3
[ "MIT" ]
1
2020-06-24T16:16:49.000Z
2020-06-24T16:16:49.000Z
include/ResourceManager.hpp
bitDaft/Project-TE
f0e0ec184d42b46799d48d69eb4eb9d369cbfcc3
[ "MIT" ]
null
null
null
include/ResourceManager.hpp
bitDaft/Project-TE
f0e0ec184d42b46799d48d69eb4eb9d369cbfcc3
[ "MIT" ]
null
null
null
/* * File: ResourceManager.hpp * Project: Project-TE * Created Date: Wednesday June 12th 2019 * Author: bitDaft * ----- * Last Modified: Thursday September 5th 2019 2:01:39 pm * Modified By: bitDaft at <ajaxhis@tutanota.com> * ----- * Copyright (c) 2019 bitDaft coorp. */ #ifndef RESOURCEMANAGER_HPP #define RESOURCEMANAGER_HPP #include <SFML/Graphics.hpp> #include <unordered_map> #include <vector> #include "Animation.hpp" #include "ResourceLoader.hpp" #include "Tileset.hpp" class ResourceManager { public: ResourceManager(); ~ResourceManager(); static void init(); static sf::Texture &getTexture(const int); static bool loadTextureFromFile(const int, const char *); static bool loadTexture(const int, const sf::Texture *); static void unloadTexture(const int); static Animation &getAnimation(const int); static bool loadAnimation(const int, const int, const std::vector<sf::IntRect *> &); static bool loadAnimation(const int, const int, const int, const std::vector<int> &); static void unloadAnimation(const int); static Tileset &getTileset(const int); static bool loadTileset(const int, const std::vector<sf::IntRect *> &); static bool loadTileset(const int, const int, sf::IntRect &, const sf::Vector2i &); static void unloadTileset(const int); static ResourceLoader &getLoader(const int); static bool loadLoader(const int, const char *path); static void unloadLoader(const int); private: typedef std::unique_ptr<sf::Texture> _texPtr; // typedef std::unique_ptr<Animation> _animPtr; // ^Using unordered map as it provides 'near' O(1) lookup albeit memory hog static std::unordered_map<int, _texPtr> _resourceMap; static std::unordered_map<int, Tileset *> _tilesetMap; static std::unordered_map<int, Animation *> _animMap; static std::unordered_map<int, ResourceLoader *> _loaderMap; }; #endif
30.983871
89
0.714732
[ "vector" ]
6a4b26004d7b15a70b315b6db1827c77e2ea1780
2,520
cpp
C++
aws-cpp-sdk-elasticmapreduce/source/model/InstanceFleetModifyConfig.cpp
capeanalytics/aws-sdk-cpp
e88f75add5a9433601b6d46fe738e493da56ac3b
[ "Apache-2.0" ]
null
null
null
aws-cpp-sdk-elasticmapreduce/source/model/InstanceFleetModifyConfig.cpp
capeanalytics/aws-sdk-cpp
e88f75add5a9433601b6d46fe738e493da56ac3b
[ "Apache-2.0" ]
null
null
null
aws-cpp-sdk-elasticmapreduce/source/model/InstanceFleetModifyConfig.cpp
capeanalytics/aws-sdk-cpp
e88f75add5a9433601b6d46fe738e493da56ac3b
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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 <aws/elasticmapreduce/model/InstanceFleetModifyConfig.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::Utils::Json; using namespace Aws::Utils; namespace Aws { namespace EMR { namespace Model { InstanceFleetModifyConfig::InstanceFleetModifyConfig() : m_instanceFleetIdHasBeenSet(false), m_targetOnDemandCapacity(0), m_targetOnDemandCapacityHasBeenSet(false), m_targetSpotCapacity(0), m_targetSpotCapacityHasBeenSet(false) { } InstanceFleetModifyConfig::InstanceFleetModifyConfig(const JsonValue& jsonValue) : m_instanceFleetIdHasBeenSet(false), m_targetOnDemandCapacity(0), m_targetOnDemandCapacityHasBeenSet(false), m_targetSpotCapacity(0), m_targetSpotCapacityHasBeenSet(false) { *this = jsonValue; } InstanceFleetModifyConfig& InstanceFleetModifyConfig::operator =(const JsonValue& jsonValue) { if(jsonValue.ValueExists("InstanceFleetId")) { m_instanceFleetId = jsonValue.GetString("InstanceFleetId"); m_instanceFleetIdHasBeenSet = true; } if(jsonValue.ValueExists("TargetOnDemandCapacity")) { m_targetOnDemandCapacity = jsonValue.GetInteger("TargetOnDemandCapacity"); m_targetOnDemandCapacityHasBeenSet = true; } if(jsonValue.ValueExists("TargetSpotCapacity")) { m_targetSpotCapacity = jsonValue.GetInteger("TargetSpotCapacity"); m_targetSpotCapacityHasBeenSet = true; } return *this; } JsonValue InstanceFleetModifyConfig::Jsonize() const { JsonValue payload; if(m_instanceFleetIdHasBeenSet) { payload.WithString("InstanceFleetId", m_instanceFleetId); } if(m_targetOnDemandCapacityHasBeenSet) { payload.WithInteger("TargetOnDemandCapacity", m_targetOnDemandCapacity); } if(m_targetSpotCapacityHasBeenSet) { payload.WithInteger("TargetSpotCapacity", m_targetSpotCapacity); } return payload; } } // namespace Model } // namespace EMR } // namespace Aws
24.466019
92
0.765873
[ "model" ]
6a4cea39fbf698d5270edff12f93b92bd2216197
4,352
cc
C++
sandbox/linux/seccomp-bpf/bpf_tests_unittest.cc
Fusion-Rom/android_external_chromium_org
d8b126911c6ea9753e9f526bee5654419e1d0ebd
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2015-08-13T21:04:58.000Z
2015-08-13T21:04:58.000Z
sandbox/linux/seccomp-bpf/bpf_tests_unittest.cc
Fusion-Rom/android_external_chromium_org
d8b126911c6ea9753e9f526bee5654419e1d0ebd
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
sandbox/linux/seccomp-bpf/bpf_tests_unittest.cc
Fusion-Rom/android_external_chromium_org
d8b126911c6ea9753e9f526bee5654419e1d0ebd
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2020-11-04T06:34:36.000Z
2020-11-04T06:34:36.000Z
// Copyright 2014 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 "sandbox/linux/seccomp-bpf/bpf_tests.h" #include <errno.h> #include <sys/ptrace.h> #include <sys/syscall.h> #include <sys/types.h> #include <unistd.h> #include "base/logging.h" #include "base/memory/scoped_ptr.h" #include "build/build_config.h" #include "sandbox/linux/seccomp-bpf/sandbox_bpf.h" #include "sandbox/linux/services/linux_syscalls.h" #include "sandbox/linux/tests/unit_tests.h" #include "testing/gtest/include/gtest/gtest.h" namespace sandbox { namespace { class FourtyTwo { public: static const int kMagicValue = 42; FourtyTwo() : value_(kMagicValue) {} int value() { return value_; } private: int value_; DISALLOW_COPY_AND_ASSIGN(FourtyTwo); }; class EmptyClassTakingPolicy : public SandboxBPFPolicy { public: explicit EmptyClassTakingPolicy(FourtyTwo* fourty_two) { BPF_ASSERT(fourty_two); BPF_ASSERT(FourtyTwo::kMagicValue == fourty_two->value()); } virtual ~EmptyClassTakingPolicy() {} virtual ErrorCode EvaluateSyscall(SandboxBPF* sandbox, int sysno) const OVERRIDE { DCHECK(SandboxBPF::IsValidSyscallNumber(sysno)); return ErrorCode(ErrorCode::ERR_ALLOWED); } }; BPF_TEST(BPFTest, BPFAUXPointsToClass, EmptyClassTakingPolicy, FourtyTwo /* *BPF_AUX */) { // BPF_AUX should point to an instance of FourtyTwo. BPF_ASSERT(BPF_AUX); BPF_ASSERT(FourtyTwo::kMagicValue == BPF_AUX->value()); } void DummyTestFunction(FourtyTwo *fourty_two) { } TEST(BPFTest, BPFTesterCompatibilityDelegateLeakTest) { // Don't do anything, simply gives dynamic tools an opportunity to detect // leaks. { BPFTesterCompatibilityDelegate<EmptyClassTakingPolicy, FourtyTwo> simple_delegate(DummyTestFunction); } { // Test polymorphism. scoped_ptr<BPFTesterDelegate> simple_delegate( new BPFTesterCompatibilityDelegate<EmptyClassTakingPolicy, FourtyTwo>( DummyTestFunction)); } } class EnosysPtracePolicy : public SandboxBPFPolicy { public: EnosysPtracePolicy() { my_pid_ = syscall(__NR_getpid); } virtual ~EnosysPtracePolicy() { // Policies should be able to bind with the process on which they are // created. They should never be created in a parent process. BPF_ASSERT_EQ(my_pid_, syscall(__NR_getpid)); } virtual ErrorCode EvaluateSyscall(SandboxBPF* sandbox_compiler, int system_call_number) const OVERRIDE { if (!SandboxBPF::IsValidSyscallNumber(system_call_number)) { return ErrorCode(ENOSYS); } else if (system_call_number == __NR_ptrace) { // The EvaluateSyscall function should run in the process that created // the current object. BPF_ASSERT_EQ(my_pid_, syscall(__NR_getpid)); return ErrorCode(ENOSYS); } else { return ErrorCode(ErrorCode::ERR_ALLOWED); } } private: pid_t my_pid_; DISALLOW_COPY_AND_ASSIGN(EnosysPtracePolicy); }; class BasicBPFTesterDelegate : public BPFTesterDelegate { public: BasicBPFTesterDelegate() {} virtual ~BasicBPFTesterDelegate() {} virtual scoped_ptr<SandboxBPFPolicy> GetSandboxBPFPolicy() OVERRIDE { return scoped_ptr<SandboxBPFPolicy>(new EnosysPtracePolicy()); } virtual void RunTestFunction() OVERRIDE { errno = 0; int ret = ptrace(PTRACE_TRACEME, -1, NULL, NULL); BPF_ASSERT(-1 == ret); BPF_ASSERT(ENOSYS == errno); } private: DISALLOW_COPY_AND_ASSIGN(BasicBPFTesterDelegate); }; // This is the most powerful and complex way to create a BPF test, but it // requires a full class definition (BasicBPFTesterDelegate). BPF_TEST_D(BPFTest, BPFTestWithDelegateClass, BasicBPFTesterDelegate); // This is the simplest form of BPF tests. BPF_TEST_C(BPFTest, BPFTestWithInlineTest, EnosysPtracePolicy) { errno = 0; int ret = ptrace(PTRACE_TRACEME, -1, NULL, NULL); BPF_ASSERT(-1 == ret); BPF_ASSERT(ENOSYS == errno); } const char kHelloMessage[] = "Hello"; BPF_DEATH_TEST_C(BPFTest, BPFDeathTestWithInlineTest, DEATH_MESSAGE(kHelloMessage), EnosysPtracePolicy) { LOG(ERROR) << kHelloMessage; _exit(1); } } // namespace } // namespace sandbox
28.631579
78
0.714384
[ "object" ]
6a4d0368727ba8e68257c312966fe7f21b6eb222
8,885
hpp
C++
include/internal/catch_commandline.hpp
pugby/Catch
b10825bc45a21090af56c687c70d0c42f489fba7
[ "BSL-1.0" ]
1
2020-01-04T01:46:06.000Z
2020-01-04T01:46:06.000Z
include/internal/catch_commandline.hpp
pugby/Catch
b10825bc45a21090af56c687c70d0c42f489fba7
[ "BSL-1.0" ]
null
null
null
include/internal/catch_commandline.hpp
pugby/Catch
b10825bc45a21090af56c687c70d0c42f489fba7
[ "BSL-1.0" ]
null
null
null
/* * catch_commandline.hpp * Catch * * Created by Phil on 02/11/2010. * Copyright 2010 Two Blue Cubes Ltd. All rights reserved. * * Distributed under the Boost Software License, Version 1.0. (See accompanying * file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) * */ #ifndef TWOBLUECUBES_CATCH_COMMANDLINE_HPP_INCLUDED #define TWOBLUECUBES_CATCH_COMMANDLINE_HPP_INCLUDED #include "catch_config.hpp" #include "catch_runner_impl.hpp" namespace Catch { // !TBD: This could be refactored to be more "declarative" // have a table up front that relates the mode, option strings, # arguments, names of arguments // - may not be worth it at this scale // -l, --list tests [xml] lists available tests (optionally in xml) // -l, --list reporters [xml] lists available reports (optionally in xml) // -l, --list all [xml] lists available tests and reports (optionally in xml) // -t, --test "testspec" ["testspec", ...] // -r, --reporter <type> // -o, --out filename to write to // -s, --success report successful cases too // -b, --break breaks into debugger on test failure // -n, --name specifies an optional name for the test run class ArgParser : NonCopyable { enum Mode { modeNone, modeList, modeTest, modeReport, modeOutput, modeSuccess, modeBreak, modeName, modeHelp, modeError }; public: /////////////////////////////////////////////////////////////////////// ArgParser ( int argc, char * const argv[], Config& config ) : m_mode( modeNone ), m_config( config ) { for( int i=1; i < argc; ++i ) { if( argv[i][0] == '-' ) { std::string cmd = ( argv[i] ); if( cmd == "-l" || cmd == "--list" ) changeMode( cmd, modeList ); else if( cmd == "-t" || cmd == "--test" ) changeMode( cmd, modeTest ); else if( cmd == "-r" || cmd == "--reporter" ) changeMode( cmd, modeReport ); else if( cmd == "-o" || cmd == "--out" ) changeMode( cmd, modeOutput ); else if( cmd == "-s" || cmd == "--success" ) changeMode( cmd, modeSuccess ); else if( cmd == "-b" || cmd == "--break" ) changeMode( cmd, modeBreak ); else if( cmd == "-n" || cmd == "--name" ) changeMode( cmd, modeName ); else if( cmd == "-h" || cmd == "-?" || cmd == "--help" ) changeMode( cmd, modeHelp ); } else { m_args.push_back( argv[i] ); } if( m_mode == modeError ) return; } changeMode( "", modeNone ); } private: /////////////////////////////////////////////////////////////////////// std::string argsAsString () { std::ostringstream oss; std::vector<std::string>::const_iterator it = m_args.begin(); std::vector<std::string>::const_iterator itEnd = m_args.end(); for( bool first = true; it != itEnd; ++it, first = false ) { if( !first ) oss << " "; oss << *it; } return oss.str(); } /////////////////////////////////////////////////////////////////////// void changeMode ( const std::string& cmd, Mode mode ) { m_command = cmd; switch( m_mode ) { case modeNone: if( m_args.size() > 0 ) return setErrorMode( "Unexpected arguments before " + m_command + ": " + argsAsString() ); break; case modeList: if( m_args.size() > 2 ) { return setErrorMode( m_command + " expected upto 2 arguments but recieved: " + argsAsString() ); } else { Config::List::What listSpec = Config::List::All; if( m_args.size() >= 1 ) { if( m_args[0] == "tests" ) listSpec = Config::List::Tests; else if( m_args[0] == "reporters" ) listSpec = Config::List::Reports; else return setErrorMode( m_command + " expected [tests] or [reporters] but recieved: [" + m_args[0] + "]" ); } if( m_args.size() >= 2 ) { if( m_args[1] == "xml" ) listSpec = static_cast<Config::List::What>( listSpec | Config::List::AsXml ); else if( m_args[1] == "text" ) listSpec = static_cast<Config::List::What>( listSpec | Config::List::AsText ); else return setErrorMode( m_command + " expected [xml] or [text] but recieved: [" + m_args[1] + "]" ); } m_config.setListSpec( static_cast<Config::List::What>( m_config.getListSpec() | listSpec ) ); } break; case modeTest: if( m_args.size() == 0 ) return setErrorMode( m_command + " expected at least 1 argument but recieved none" ); { std::vector<std::string>::const_iterator it = m_args.begin(); std::vector<std::string>::const_iterator itEnd = m_args.end(); for(; it != itEnd; ++it ) m_config.addTestSpec( *it ); } break; case modeReport: if( m_args.size() != 1 ) return setErrorMode( m_command + " expected one argument, recieved: " + argsAsString() ); m_config.setReporter( m_args[0] ); break; case modeOutput: if( m_args.size() == 0 ) return setErrorMode( m_command + " expected filename" ); if( m_args[0][0] == '%' ) m_config.useStream( m_args[0].substr( 1 ) ); else m_config.setFilename( m_args[0] ); break; case modeSuccess: if( m_args.size() != 0 ) return setErrorMode( m_command + " does not accept arguments" ); m_config.setIncludeWhat( Config::Include::SuccessfulResults ); break; case modeBreak: if( m_args.size() != 0 ) return setErrorMode( m_command + " does not accept arguments" ); m_config.setShouldDebugBreak( true ); break; case modeName: if( m_args.size() != 1 ) return setErrorMode( m_command + " requires exactly one argument (a name)" ); m_config.setName( m_args[0] ); break; case modeHelp: if( m_args.size() != 0 ) return setErrorMode( m_command + " does not accept arguments" ); m_config.setShowHelp( true ); break; default: break; } m_args.clear(); m_mode = mode; } /////////////////////////////////////////////////////////////////////// void setErrorMode ( const std::string& errorMessage ) { m_mode = modeError; m_command = ""; m_config.setError( errorMessage ); } private: Mode m_mode; std::string m_command; std::vector<std::string> m_args; Config& m_config; }; } // end namespace Catch #endif // TWOBLUECUBES_CATCH_COMMANDLINE_HPP_INCLUDED
39.140969
160
0.407991
[ "vector" ]
c69fdf695919f4f5a086953a829e882443127c57
7,242
cpp
C++
Code/BasicFilters/btkGroundReactionWrenchFilter.cpp
opensim-org/BTKCore
6d787d0be223851a8f454f2ee8c7d9e47b84cbbe
[ "Barr", "Unlicense" ]
1
2017-12-27T20:19:17.000Z
2017-12-27T20:19:17.000Z
Code/BasicFilters/btkGroundReactionWrenchFilter.cpp
opensim-org/BTKCore
6d787d0be223851a8f454f2ee8c7d9e47b84cbbe
[ "Barr", "Unlicense" ]
2
2018-02-22T22:49:11.000Z
2018-05-07T20:50:06.000Z
Code/BasicFilters/btkGroundReactionWrenchFilter.cpp
opensim-org/BTKCore
6d787d0be223851a8f454f2ee8c7d9e47b84cbbe
[ "Barr", "Unlicense" ]
4
2019-04-05T07:40:42.000Z
2020-01-24T23:59:58.000Z
/* * The Biomechanical ToolKit * Copyright (c) 2009-2014, Arnaud Barré * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above * copyright notice, this list of conditions and the following * disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials * provided with the distribution. * * Neither the name(s) of the copyright holders nor the names * of its contributors may be used to endorse or promote products * derived from this software without specific prior written * permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include "btkGroundReactionWrenchFilter.h" #include "btkConvert.h" namespace btk { /** * @class GroundReactionWrenchFilter btkGroundReactionWrenchFilter.h * @brief Transform force platform data into ground reaction wrenches. * * Theses wrenches are expressed in the global frame. The point of application (PWA) * of each wrench is calculated from Shimba (1984). * Compared to the center of pressure (COP), the PWA take into account all the forces * and moments (and does not assume any null forces). * * Note: For gait analysis, the COP and PWA are very similar. * * Because the computation of the PWA (as the COP) is sensitive to small (vertical) forces, the methods * SetThresholdValue and SetThresholdState() are provided to not compute the PWA if the vertical forces is * the threshold. You first need to set the value and then activate the threshold method. * By default, this threshold is not activated and the values is set to 0. * As for example: * @code * btk::GroundReactionWrenchFilter::Pointer grwf = btk::GroundReactionWrenchFilter::New() * grwf->SetThresholdValue(5.0); // 5 newtons * grwf->SetThresholdState(true); * @endcode * * Finally, you can also use the method SetTransformToGlobalFrame() to have the wrench expressed in the frame of the force platform. * * @par Reference * Shimba T.@n * <em>An estimation of center of gravity from force platform data</em>.@n * Journal of Biomechanics, <b>1984</b>, 17(1), 53–60. * * @ingroup BTKBasicFilters */ /** * @typedef GroundReactionWrenchFilter::Pointer * Smart pointer associated with a GroundReactionWrenchFilter object. */ /** * @typedef GroundReactionWrenchFilter::ConstPointer * Smart pointer associated with a const GroundReactionWrenchFilter object. */ /** * @fn static Pointer GroundReactionWrenchFilter::New(); * Creates a smart pointer associated with a GroundReactionWrenchFilter object. */ /** * @fn bool GroundReactionWrenchFilter::GetThresholdState() const * Returns the state of the threshold used to suppress false PWA. */ /** * Sets the threshold state. */ void GroundReactionWrenchFilter::SetThresholdState(bool activated) { if (this->m_ThresholdActivated == activated) return; this->m_ThresholdActivated = activated; this->Modified(); }; /** * @fn double GroundReactionWrenchFilter::GetThresholdValue() const * Returns the value used to suppress PWA computed with a Fz value lower or equal than it. * * The threshold must be activated (see GroundReactionWrenchFilter::SetThresholdState) to be used during the computation of the PWA. */ /** * Sets the threshold value. * * The threshold must be activated (see GroundReactionWrenchFilter::SetThresholdState) to be used during the computation of the PWA. */ void GroundReactionWrenchFilter::SetThresholdValue(double v) { if (fabs(this->m_ThresholdValue - v) <= std::numeric_limits<double>::epsilon()) return; if (v < 0.0) btkWarningMacro("Negative threshold has no effect on the algorithm because it compares the threshold value with the absolute value of Fz."); this->m_ThresholdValue = v; this->Modified(); }; /** * Constructor. Sets the number of inputs and outputs to 1. */ GroundReactionWrenchFilter::GroundReactionWrenchFilter() : ForcePlatformWrenchFilter() { this->SetInputNumber(1); this->SetOutputNumber(1); this->m_ThresholdActivated = false; this->m_ThresholdValue = 0.0; setLocation(Origin); }; /** * Finish the computation of the ground reaction wrench for the force platform type I (nothing to do). */ void GroundReactionWrenchFilter::FinishTypeI(Wrench::Pointer /* wrh */, ForcePlatform::Pointer /* fp */, int /* index */) { /* ForcePlatform::Origin origin; origin << 0, 0, fp->GetOrigin().z(); if (origin.z() > 0) { btkWarningMacro("Vertical offset between the origin of the force platform #" + ToString(index + " and the center of the working surface seems to be misconfigured (positive value). The opposite of this offset is used."); origin.z() *= -1; } */ //this->FinishGRWComputation(grw, origin); }; /** * Finish the computation of the ground reaction wrench for the AMTI force platforms. */ void GroundReactionWrenchFilter::FinishAMTI(Wrench::Pointer wrh, ForcePlatform::Pointer fp, int index) { ForcePlatform::Origin origin = fp->GetOrigin(); if (origin.z() > 0) { btkWarningMacro("Origin for the force platform #" + ToString(index) + " seems to be located from the center of the working surface instead of the inverse. Data are inverted to locate the center of the working surface from the platform's origin."); origin *= -1; } this->FinishGRWComputation(wrh, origin); }; /** * Finish the computation of the ground reaction wrench for the Kislter force platform. */ void GroundReactionWrenchFilter::FinishKistler(Wrench::Pointer wrh, ForcePlatform::Pointer fp, int index) { ForcePlatform::Origin origin; origin << 0, 0, fp->GetOrigin().z(); if (origin.z() > 0) { btkWarningMacro("Vertical offset between the origin of the force platform #" + ToString(index) + " and the center of the working surface seems to be misconfigured (positive value). The opposite of this offset is used."); origin.z() *= -1; } this->FinishGRWComputation(wrh, origin); }; };
38.727273
253
0.704916
[ "object", "transform" ]
c6a3e075ffcd12e6872c77aa2f9c470e5d6b6737
2,117
hh
C++
TFM/click-2.0.1/elements/grid/lookuplocalgridroute2.hh
wangyang2013/TFM
cabca56229a7e4dafc76da8d631980fc453c9493
[ "BSD-3-Clause" ]
3
2018-04-14T14:43:31.000Z
2019-12-06T13:09:58.000Z
TFM/click-2.0.1/elements/grid/lookuplocalgridroute2.hh
nfvproject/TFM
cabca56229a7e4dafc76da8d631980fc453c9493
[ "BSD-3-Clause" ]
null
null
null
TFM/click-2.0.1/elements/grid/lookuplocalgridroute2.hh
nfvproject/TFM
cabca56229a7e4dafc76da8d631980fc453c9493
[ "BSD-3-Clause" ]
null
null
null
#ifndef LOCALROUTE2_HH #define LOCALROUTE2_HH /* * =c * LookupLocalGridRoute2(ETH, IP, GenericGridRouteTable, I<KEYWORDS>) * * =s Grid * * =d * * Forward packets according to the tables accumulated by the * GenericGridRouteTable element. * * ETH and IP are this node's ethernet and IP addresses, respectively. * * Inputs must be GRID_NBR_ENCAP packets with MAC headers, with the * destination IP address annotation set. Output packets have their * source ethernet address set to ETH, their destination ethernet * address set according to the routing table entry corresponding to * the destination IP annotation, and their Grid tx_ip set to IP. * Packets also have their paint annotation set to the output * interface number, e.g. for use with PaintSwitch. * * Packets for which no route exists are dropped. * * Keywords are: * * =over 8 * * =item LOG * * GridGenericLogger element. Object to log events to. * * =item VERBOSE * * Boolean. Be verbose about drops due to no route. Defaults to false. * * =back * * =a LookupLocalGridroute, LookupGeographicGridRoute, * GenericGridRouteTable, DSDVRouteTable, GridLogger, Paint, * PaintSwitch */ #include <click/element.hh> #include <click/glue.hh> #include <click/etheraddress.hh> #include <click/ipaddress.hh> #include <click/task.hh> #include <elements/grid/gridroutecb.hh> CLICK_DECLS class GridGenericLogger; class GridGenericRouteTable; class LookupLocalGridRoute2 : public Element, public GridRouteActor { public: LookupLocalGridRoute2(); ~LookupLocalGridRoute2(); const char *class_name() const { return "LookupLocalGridRoute2"; } void *cast(const char *); const char *port_count() const { return PORTS_1_1; } const char *processing() const { return AGNOSTIC; } int configure(Vector<String> &, ErrorHandler *); int initialize(ErrorHandler *); Packet *simple_action(Packet *); private: Packet *forward_grid_packet(Packet *packet, IPAddress dest_ip); GridGenericRouteTable *_rtes; GridGenericLogger *_log; EtherAddress _eth; IPAddress _ip; bool _verbose; }; CLICK_ENDDECLS #endif
24.616279
72
0.741615
[ "object", "vector" ]
c6a501daf1025a475ff38f56e8d6db64c617df8b
2,738
cpp
C++
leetcode/weekly/170.cpp
bvbasavaraju/competitive_programming
a82ffc1b639588a84f4273b44285d57cdc2f4b11
[ "Apache-2.0" ]
1
2020-05-05T13:06:51.000Z
2020-05-05T13:06:51.000Z
leetcode/weekly/170.cpp
bvbasavaraju/competitive_programming
a82ffc1b639588a84f4273b44285d57cdc2f4b11
[ "Apache-2.0" ]
null
null
null
leetcode/weekly/170.cpp
bvbasavaraju/competitive_programming
a82ffc1b639588a84f4273b44285d57cdc2f4b11
[ "Apache-2.0" ]
null
null
null
/**************************************************** Date: Jan 5, 2020 Successful submissions : 1 Time expiration : 1 Not Solved : 1 Wrong Answer/ Partial result : 1 link: https://leetcode.com/contest/biweekly-contest-170 ****************************************************/ #include <iostream> #include <vector> #include <algorithm> #include <string> #include <stack> #include <queue> #include <map> #include <unordered_map> using namespace std; /* Q: 1309. Decrypt String from Alphabet to Integer Mapping - Accepted! */ class Solution1_t { public: string freqAlphabets(string s) { string letters = "0abcdefghijklmnopqrstuvwxyz"; string retVal = ""; int ls = s.size(); for (int i = 0; i < ls; i++) { if (s[i] == '#') { continue; } int p = s[i] - '0'; if ((i + 2 < ls) && s[i + 2] == '#') { i++; p = p * 10 + s[i++] - '0'; } retVal += letters[p]; } return retVal; } }; /* Q: 1310. XOR Queries of a Subarray - Time Limit Exceeded */ class Solution2_t { private: int GetXoredValue(vector<int> &a, int l, int h) { int retVal = 0; while (l < h) { retVal ^= a[l++]; } retVal ^= a[h]; return retVal; } public: vector<int> xorQueries(vector<int> &a, vector<vector<int>> &q) { int lq = q.size(); vector<int> r; for (int i = 0; i < lq; i++) { r.push_back(GetXoredValue(a, q[i][0], q[i][1])); } return r; } }; /* Q: 1311. Get Watched Videos by Your Friends */ class Solution3_t { public: vector<string> watchedVideosByFriends(vector<vector<string>> &watchedVideos, vector<vector<int>> &friends, int id, int level) { } }; /* Q: 1312. Minimum Insertion Steps to Make a String Palindrome - Wrong answer */ class Solution4_t { private: int GetInsertCount(string s, bool atEnd) { int retVal = 0; int l = 0; int h = s.size() - 1; while (h > 0 && l <= h) { if (s[l] == s[h]) { l++; h--; } else { if (atEnd) { s.insert(h, 1, s[l++]); } else { s.insert(l, 1, s[h--]); } retVal++; } } return retVal; } public: int minInsertions(string s) { return min(GetInsertCount(s, true), GetInsertCount(s, false)); } };
19.146853
129
0.440467
[ "vector" ]
c6b214bf1bb8edb97fd2e8b9116c400a002bb561
18,766
cpp
C++
Ligne_transitique_MONTRAC/V-Rep/programming/mtbServer/robotLanguageInterpreter.cpp
keke02/Fast-reconfiguration-of-robotic-production-systems
44ffe14b8a4a4798b559eede9b3766acb55f294e
[ "CC0-1.0" ]
null
null
null
Ligne_transitique_MONTRAC/V-Rep/programming/mtbServer/robotLanguageInterpreter.cpp
keke02/Fast-reconfiguration-of-robotic-production-systems
44ffe14b8a4a4798b559eede9b3766acb55f294e
[ "CC0-1.0" ]
null
null
null
Ligne_transitique_MONTRAC/V-Rep/programming/mtbServer/robotLanguageInterpreter.cpp
keke02/Fast-reconfiguration-of-robotic-production-systems
44ffe14b8a4a4798b559eede9b3766acb55f294e
[ "CC0-1.0" ]
null
null
null
// Copyright 2006-2015 Coppelia Robotics GmbH. All rights reserved. // marc@coppeliarobotics.com // www.coppeliarobotics.com // // ------------------------------------------------------------------- // THIS FILE IS DISTRIBUTED "AS IS", WITHOUT ANY EXPRESS OR IMPLIED // WARRANTY. THE USER WILL USE IT AT HIS/HER OWN RISK. THE ORIGINAL // AUTHORS AND COPPELIA ROBOTICS GMBH WILL NOT BE LIABLE FOR DATA LOSS, // DAMAGES, LOSS OF PROFITS OR ANY OTHER KIND OF LOSS WHILE USING OR // MISUSING THIS SOFTWARE. // // You are free to use/modify/distribute this file for whatever purpose! // ------------------------------------------------------------------- // // This file was automatically created for V-REP release V3.2.3 rev4 on December 21st 2015 /***************************************************** This file represents the robot language interpreter which is only provided as a very very simple example. Following commands/instructions are recognized (one command per line): ------------------------------------ REM this is a comment section SETLINVEL v SETROTVEL v MOVE p1 p2 p3 p4 WAIT x SETBIT y CLEARBIT y IFBITGOTO y label IFNBITGOTO y label GOTO label label ------------------------------------ SETLINVEL: sets the linear joint velocities for next movement to v (m/sec) SETROTVEL: sets the angular joint velocities for next movement to v (deg/sec) MOVE: moves the 4 robot joints to positions (p1 (deg), p2 (deg), p3 (m), p4 (deg)) (at constant velocity v) WAIT: waits x miliseconds SETBIT: set the bit at position y in the robot output (1-32) CLEARBIT: clears the bit at position y in the robot output (1-32) IFBITGOTO: if bit y in the robot input (1-32) is set, then jump to label IFNBITGOTO: if bit y in the robot input (1-32) is NOT set, then jump to label GOTO: jumps to label. A label is any string different from REM, SETVEL, MOVE, WAIT or GOTO **************************************************/ #include "robotLanguageInterpreter.h" #include <boost/lexical_cast.hpp> #include <math.h> const float piValue=3.14159265f; SMtbRobotState robotState; std::vector<SCompiledProgramLine> _compiledRobotLanguageProgram; bool _extractOneLine(std::string& inputString,std::string& extractedLine) { // Extracts one line from a multi-line string extractedLine=""; while (inputString.length()!=0) { char c=inputString[0]; inputString.erase(inputString.begin()); if ( (c==char(13))||(c==char(10)) ) { if (c==char(10)) break; } else extractedLine+=c; } return(extractedLine.length()!=0); } bool _extractOneWord(std::string& line,std::string& extractedWord) { // Extracts one word from a string (words are delimited by spaces) extractedWord=""; while (line.length()!=0) { char c=line[0]; line.erase(line.begin()); if (c==' ') { if (extractedWord.length()!=0) return(extractedWord.length()!=0); } else extractedWord+=c; } return(extractedWord.length()!=0); } bool _getCommandFromWord(const std::string& word,int& command) { // returns the command index for a string command command=-1; // label if (word.compare("MOVE")==0) command=0; if (word.compare("WAIT")==0) command=1; if (word.compare("GOTO")==0) command=2; if (word.compare("SETROTVEL")==0) command=3; if (word.compare("REM")==0) command=4; if (word.compare("SETBIT")==0) command=5; if (word.compare("CLEARBIT")==0) command=6; if (word.compare("IFBITGOTO")==0) command=7; if (word.compare("IFNBITGOTO")==0) command=8; if (word.compare("SETLINVEL")==0) command=9; return(command!=-1); } bool _getIntegerFromWord(const std::string& word,int& theInteger) { // returns the integer value corresponding to a string try { theInteger=boost::lexical_cast<int>(word); return(true); } catch (boost::bad_lexical_cast &) { return(false); } } bool _getFloatFromWord(const std::string& word,float& theFloat) { // returns the float value corresponding to a string try { theFloat=boost::lexical_cast<float>(word); return(true); } catch (boost::bad_lexical_cast &) { return(false); } } void _removeFrontAndBackSpaces(std::string& word) { // removes spaces at the front and at the back of a string while ( (word.length()!=0)&&(word[0]==' ') ) word.erase(word.begin()); while ( (word.length()!=0)&&(word[word.length()-1]==' ') ) word.erase(word.begin()+word.length()-1); } std::string compileCode(const std::string& inputCode,float initialJointPosition[4],float initialJointVelocityWhenMoving[2]) { // This function "compiles" the robot language code // A return value different from "" indicates a compilation error for (int i=0;i<4;i++) robotState.currentJointPosition[i]=initialJointPosition[i]; robotState.jointVelocityWhenMoving[0]=initialJointVelocityWhenMoving[0]; robotState.jointVelocityWhenMoving[1]=initialJointVelocityWhenMoving[1]; robotState.currentProgramLine=0; std::vector<std::string> labels; std::vector<int> labelLocations; _compiledRobotLanguageProgram.clear(); std::string code(inputCode); int errorOnLineNumber=-1; // no error for now std::string codeLine; int currentCodeLineNb=0; while (_extractOneLine(code,codeLine)) { // get one code line currentCodeLineNb++; _removeFrontAndBackSpaces(codeLine); if (codeLine.length()!=0) { std::string originalLine(codeLine); std::string codeWord; if (_extractOneWord(codeLine,codeWord)) { // get the first word in the code line int cmd; _getCommandFromWord(codeWord,cmd); // get the equivalent command index for the word if (cmd==-1) { // we have a label here _removeFrontAndBackSpaces(codeLine); if (codeLine.length()==0) { // the line is ok. labels.push_back(codeWord); labelLocations.push_back(int(_compiledRobotLanguageProgram.size())); } else { // there shouldn't be more text on this line! errorOnLineNumber=currentCodeLineNb; break; } } if (cmd==0) { // we have a MOVE here bool error=true; if (_extractOneWord(codeLine,codeWord)) { float p1; if (_getFloatFromWord(codeWord,p1)) { if (_extractOneWord(codeLine,codeWord)) { float p2; if (_getFloatFromWord(codeWord,p2)) { if (_extractOneWord(codeLine,codeWord)) { float p3; if (_getFloatFromWord(codeWord,p3)) { if (_extractOneWord(codeLine,codeWord)) { float p4; if (_getFloatFromWord(codeWord,p4)) { if (p1>160.0f) p1=160.0f; if (p1<-160.0f) p1=-160.0f; if (p2>160.0f) p2=160.0f; if (p2<-160.0f) p2=-160.0f; if (p3>0.2f) p3=0.2f; if (p3<0.0f) p3=0.0f; if (!_extractOneWord(codeLine,codeWord)) { error=false; SCompiledProgramLine a; a.command=cmd; a.correspondingUncompiledCode=originalLine; a.floatParameter[0]=p1*piValue/180.0f; // convert from deg to rad a.floatParameter[1]=p2*piValue/180.0f; // convert from deg to rad a.floatParameter[2]=p3; // prismatic actuator a.floatParameter[3]=p4*piValue/180.0f; // convert from deg to rad _compiledRobotLanguageProgram.push_back(a); } } } } } } } } } if (error) { errorOnLineNumber=currentCodeLineNb; break; } } if (cmd==1) { // we have a WAIT here bool error=true; if (_extractOneWord(codeLine,codeWord)) { int t; if (_getIntegerFromWord(codeWord,t)) { if (t>0) { if (!_extractOneWord(codeLine,codeWord)) { error=false; SCompiledProgramLine a; a.command=cmd; a.correspondingUncompiledCode=originalLine; a.floatParameter[0]=float(t)/1000.0f; // convert from ms to s _compiledRobotLanguageProgram.push_back(a); } } } } if (error) { errorOnLineNumber=currentCodeLineNb; break; } } if (cmd==2) { // we have a GOTO here bool error=true; if (_extractOneWord(codeLine,codeWord)) { std::string label(codeWord); if (!_extractOneWord(codeLine,codeWord)) { error=false; SCompiledProgramLine a; a.command=cmd; a.correspondingUncompiledCode=originalLine; a.tmpLabel=label; a.intParameter[0]=currentCodeLineNb; // the line number to jumo to is set in the second compilation pass _compiledRobotLanguageProgram.push_back(a); } } if (error) { errorOnLineNumber=currentCodeLineNb; break; } } if (cmd==3) { // we have a SETROTVEL here bool error=true; if (_extractOneWord(codeLine,codeWord)) { float v; if (_getFloatFromWord(codeWord,v)) { if (v>0.0001f) { if (!_extractOneWord(codeLine,codeWord)) { error=false; SCompiledProgramLine a; a.command=cmd; a.correspondingUncompiledCode=originalLine; a.floatParameter[0]=v*piValue/180.0f; // convert from deg/s to rad/s _compiledRobotLanguageProgram.push_back(a); } } } } if (error) { errorOnLineNumber=currentCodeLineNb; break; } } if (cmd==9) { // we have a SETLINVEL here bool error=true; if (_extractOneWord(codeLine,codeWord)) { float v; if (_getFloatFromWord(codeWord,v)) { if (v>0.0001f) { if (!_extractOneWord(codeLine,codeWord)) { error=false; SCompiledProgramLine a; a.command=cmd; a.correspondingUncompiledCode=originalLine; a.floatParameter[0]=v; _compiledRobotLanguageProgram.push_back(a); } } } } if (error) { errorOnLineNumber=currentCodeLineNb; break; } } if (cmd==4) { // we have a comment here } if ((cmd==5)||(cmd==6)) { // we have a SETBIT or CLEARBIT here bool error=true; if (_extractOneWord(codeLine,codeWord)) { int bitPos; if (_getIntegerFromWord(codeWord,bitPos)) { if ((bitPos>0)&&(bitPos<33)) { if (!_extractOneWord(codeLine,codeWord)) { error=false; SCompiledProgramLine a; a.command=cmd; a.correspondingUncompiledCode=originalLine; a.intParameter[0]=bitPos; _compiledRobotLanguageProgram.push_back(a); } } } } if (error) { errorOnLineNumber=currentCodeLineNb; break; } } if ((cmd==7)||(cmd==8)) { // we have a IFBITGOTO or IFNBITGOTO here bool error=true; if (_extractOneWord(codeLine,codeWord)) { int bitPos; if (_getIntegerFromWord(codeWord,bitPos)) { if ((bitPos>0)&&(bitPos<33)) { if (_extractOneWord(codeLine,codeWord)) { std::string label=codeWord; if (!_extractOneWord(codeLine,codeWord)) { error=false; SCompiledProgramLine a; a.command=cmd; a.correspondingUncompiledCode=originalLine; a.tmpLabel=label; a.intParameter[0]=bitPos; a.intParameter[1]=currentCodeLineNb; // the line number to jumo to is set in the second compilation pass _compiledRobotLanguageProgram.push_back(a); } } } } } if (error) { errorOnLineNumber=currentCodeLineNb; break; } } } } } if (errorOnLineNumber!=-1) { // we return an error message std::string retString("Error on line "); retString+=boost::lexical_cast<std::string>(currentCodeLineNb); retString+="."; return(retString); } else { // we have a second pass where we need to set the line number where to jump to! for (unsigned int i=0;i<_compiledRobotLanguageProgram.size();i++) { if (_compiledRobotLanguageProgram[i].command==2) { // this is a GOTO command. bool found=false; for (unsigned int j=0;j<labels.size();j++) { if (labels[j].compare(_compiledRobotLanguageProgram[i].tmpLabel)==0) { _compiledRobotLanguageProgram[i].intParameter[0]=labelLocations[j]; found=true; } } if (!found) { std::string retString("Error on line "); retString+=boost::lexical_cast<std::string>(_compiledRobotLanguageProgram[i].intParameter[0]); retString+="."; return(retString); } } if ((_compiledRobotLanguageProgram[i].command==7)||(_compiledRobotLanguageProgram[i].command==8)) { // this is a IFBITGOTO or IFNBITGOTO command. bool found=false; for (unsigned int j=0;j<labels.size();j++) { if (labels[j].compare(_compiledRobotLanguageProgram[i].tmpLabel)==0) { _compiledRobotLanguageProgram[i].intParameter[1]=labelLocations[j]; found=true; } } if (!found) { std::string retString("Error on line "); retString+=boost::lexical_cast<std::string>(_compiledRobotLanguageProgram[i].intParameter[1]); retString+="."; return(retString); } } } return(""); // no error! } } std::string runProgram(unsigned char inputData[4],float deltaTime) { // This function runs the compiled robot language program for "deltaTime" seconds // return value "" means program ended! if (int(_compiledRobotLanguageProgram.size())<=robotState.currentProgramLine) return(""); // program end int cmd=_compiledRobotLanguageProgram[robotState.currentProgramLine].command; // get the current command int loopCnt=0; while (true) { if (cmd==0) { // MOVE // We arrive at the same time at the desired positions for each joint float deltaTimeLeft; float biggestT=0.0f; for (int i=0;i<4;i++) { float dj=_compiledRobotLanguageProgram[robotState.currentProgramLine].floatParameter[i]-robotState.currentJointPosition[i]; float vv=robotState.jointVelocityWhenMoving[1]; if (i==2) vv=robotState.jointVelocityWhenMoving[0]; // This is a linear joint float t=fabs(dj)/vv; if (t>biggestT) biggestT=t; } for (int i=0;i<4;i++) { if (biggestT>deltaTime) { float dj=_compiledRobotLanguageProgram[robotState.currentProgramLine].floatParameter[i]-robotState.currentJointPosition[i]; if (dj!=0.0f) { float vv=fabs(dj)/biggestT; robotState.currentJointPosition[i]+=vv*deltaTime*dj/fabs(dj); } deltaTimeLeft=0.0f; } else { robotState.currentJointPosition[i]=_compiledRobotLanguageProgram[robotState.currentProgramLine].floatParameter[i]; deltaTimeLeft=deltaTime-biggestT; } } deltaTime=deltaTimeLeft; if (deltaTime>0.0f) robotState.currentProgramLine++; else break; } if (cmd==1) { // WAIT float timeToWait=_compiledRobotLanguageProgram[robotState.currentProgramLine].floatParameter[0]; timeToWait-=robotState.timeAlreadySpentAtCurrentProgramLine; if (timeToWait>deltaTime) { robotState.timeAlreadySpentAtCurrentProgramLine+=deltaTime; break; } else { deltaTime-=timeToWait; robotState.currentProgramLine++; } } if (cmd==2) { // GOTO robotState.currentProgramLine=_compiledRobotLanguageProgram[robotState.currentProgramLine].intParameter[0]; // we jump } if (cmd==3) { // SETROTVEL robotState.jointVelocityWhenMoving[1]=_compiledRobotLanguageProgram[robotState.currentProgramLine].floatParameter[0]; robotState.currentProgramLine++; } if (cmd==9) { // SETLINVEL robotState.jointVelocityWhenMoving[0]=_compiledRobotLanguageProgram[robotState.currentProgramLine].floatParameter[0]; robotState.currentProgramLine++; } if (cmd==5) { // SETBIT int pos=_compiledRobotLanguageProgram[robotState.currentProgramLine].intParameter[0]; int bytePos=(pos-1)/8; // 0-3 int bitPos=(pos-1)%8; //0-7 robotState.outputData[bytePos]|=1<<bitPos; robotState.currentProgramLine++; } if (cmd==6) { // CLEARBIT int pos=_compiledRobotLanguageProgram[robotState.currentProgramLine].intParameter[0]; int bytePos=(pos-1)/8; // 0-3 int bitPos=(pos-1)%8; //0-7 robotState.outputData[bytePos]&=255-(1<<bitPos); robotState.currentProgramLine++; } if (cmd==7) { // IFBITGOTO int pos=_compiledRobotLanguageProgram[robotState.currentProgramLine].intParameter[0]; int bytePos=(pos-1)/8; // 0-3 int bitPos=(pos-1)%8; //0-7 if (inputData[bytePos]&(1<<bitPos)) { // we have to jump robotState.currentProgramLine=_compiledRobotLanguageProgram[robotState.currentProgramLine].intParameter[1]; // we jump } else robotState.currentProgramLine++; } if (cmd==8) { // IFNBITGOTO int pos=_compiledRobotLanguageProgram[robotState.currentProgramLine].intParameter[0]; int bytePos=(pos-1)/8; // 0-3 int bitPos=(pos-1)%8; //0-7 if ((inputData[bytePos]&(1<<bitPos))==0) { // we have to jump robotState.currentProgramLine=_compiledRobotLanguageProgram[robotState.currentProgramLine].intParameter[1]; // we jump } else robotState.currentProgramLine++; } robotState.timeAlreadySpentAtCurrentProgramLine=0.0f; if (int(_compiledRobotLanguageProgram.size())<=robotState.currentProgramLine) return(""); // program end loopCnt++; if (loopCnt>1000) break; // We looped too often... maybe waiting for an input signal or simply infinite loop! we leave here cmd=_compiledRobotLanguageProgram[robotState.currentProgramLine].command; } return(_compiledRobotLanguageProgram[robotState.currentProgramLine].correspondingUncompiledCode); // return the string command that is being executed now } void getJointsAndOutputData(float jointPosition[4],unsigned char outputData[4]) { for (int i=0;i<4;i++) jointPosition[i]=robotState.currentJointPosition[i]; for (int i=0;i<4;i++) outputData[i]=robotState.outputData[i]; }
30.31664
155
0.615688
[ "vector" ]
c6b8d9388ccd0a4cf1067890f645646ab232318c
3,325
hpp
C++
include/armadillo_bits/op_roots_meat.hpp
getfiit/armadillo-code
3a896deca12a0f596b52d84185ebfad65df650b7
[ "Apache-2.0" ]
3
2020-03-23T04:31:14.000Z
2021-01-17T09:03:09.000Z
include/armadillo_bits/op_roots_meat.hpp
getfiit/armadillo-code
3a896deca12a0f596b52d84185ebfad65df650b7
[ "Apache-2.0" ]
null
null
null
include/armadillo_bits/op_roots_meat.hpp
getfiit/armadillo-code
3a896deca12a0f596b52d84185ebfad65df650b7
[ "Apache-2.0" ]
3
2018-03-28T20:53:27.000Z
2020-04-27T07:03:02.000Z
// SPDX-License-Identifier: Apache-2.0 // // Copyright 2008-2016 Conrad Sanderson (http://conradsanderson.id.au) // Copyright 2008-2016 National ICT Australia (NICTA) // // 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. // ------------------------------------------------------------------------ //! \addtogroup op_roots //! @{ template<typename T1> inline void op_roots::apply(Mat< std::complex<typename T1::pod_type> >& out, const mtOp<std::complex<typename T1::pod_type>, T1, op_roots>& expr) { arma_extra_debug_sigprint(); const bool status = op_roots::apply_direct(out, expr.m); if(status == false) { out.soft_reset(); arma_stop_runtime_error("roots(): eigen decomposition failed"); } } template<typename T1> inline bool op_roots::apply_direct(Mat< std::complex<typename T1::pod_type> >& out, const Base<typename T1::elem_type, T1>& X) { arma_extra_debug_sigprint(); typedef std::complex<typename T1::pod_type> out_eT; const quasi_unwrap<T1> U(X.get_ref()); bool status = false; if(U.is_alias(out)) { Mat<out_eT> tmp; status = op_roots::apply_noalias(tmp, U.M); out.steal_mem(tmp); } else { status = op_roots::apply_noalias(out, U.M); } return status; } template<typename eT> inline bool op_roots::apply_noalias(Mat< std::complex<typename get_pod_type<eT>::result> >& out, const Mat<eT>& X) { arma_extra_debug_sigprint(); typedef typename get_pod_type<eT>::result T; typedef std::complex<typename get_pod_type<eT>::result> out_eT; arma_debug_check( (X.is_vec() == false), "roots(): given object must be a vector" ); if(X.is_finite() == false) { return false; } // treat X as a column vector const Col<eT> Y( const_cast<eT*>(X.memptr()), X.n_elem, false, false); const T Y_max = (Y.is_empty() == false) ? T(max(abs(Y))) : T(0); if(Y_max == T(0)) { out.set_size(1,0); return true; } const uvec indices = find( Y / Y_max ); const uword n_tail_zeros = (indices.n_elem > 0) ? uword( (Y.n_elem-1) - indices[indices.n_elem-1] ) : uword(0); const Col<eT> Z = Y.subvec( indices[0], indices[indices.n_elem-1] ); if(Z.n_elem >= uword(2)) { Mat<eT> tmp; if(Z.n_elem == uword(2)) { tmp.set_size(1,1); tmp[0] = -Z[1] / Z[0]; } else { tmp = diagmat(ones< Col<eT> >(Z.n_elem - 2), -1); tmp.row(0) = strans(-Z.subvec(1, Z.n_elem-1) / Z[0]); } Mat<out_eT> junk; const bool status = auxlib::eig_gen(out, junk, false, tmp); if(status == false) { return false; } if(n_tail_zeros > 0) { out.resize(out.n_rows + n_tail_zeros, 1); } } else { out.zeros(n_tail_zeros,1); } return true; } //! @}
23.58156
133
0.614436
[ "object", "vector" ]
c6ba72a8efbd3212b81ca7bc9e0eb524a6e1e6b1
10,689
cpp
C++
src/main.cpp
kt10aan/gazetool
87232dcb8baa38e4498ce03ded9fd4f88692741f
[ "MIT" ]
18
2016-03-09T00:19:16.000Z
2021-01-15T23:38:58.000Z
src/main.cpp
kt10aan/gazetool
87232dcb8baa38e4498ce03ded9fd4f88692741f
[ "MIT" ]
8
2015-09-29T10:13:01.000Z
2018-01-15T14:04:33.000Z
src/main.cpp
kt10aan/gazetool
87232dcb8baa38e4498ce03ded9fd4f88692741f
[ "MIT" ]
13
2015-09-29T09:48:54.000Z
2021-01-19T10:24:31.000Z
#include <iostream> #include <stdexcept> #include <boost/program_options.hpp> #include <boost/algorithm/string.hpp> #include <QApplication> #include <QThread> #include "workerthread.h" #include "gazergui.h" using namespace std; namespace po = boost::program_options; class OptionParser : public QThread { public: po::variables_map options; OptionParser(int argc, char** argv, WorkerThread& worker, GazerGui& gui) : argc(argc), argv(argv), worker(worker), gui(gui) {} private: int argc; char** argv; WorkerThread& worker; GazerGui& gui; template<typename T> void copyCheckArg(const string& name, T& target) { if (options.count(name)) { target = options[name].as<T>(); } } template<typename T> void copyCheckArg(const string& name, boost::optional<T>& target) { if (options.count(name)) { target = options[name].as<T>(); } } TrainingParameters parseTrainingOpts() { TrainingParameters params; map<string, FeatureSetConfig> m = { {"all", FeatureSetConfig::ALL}, {"posrel", FeatureSetConfig::POSREL}, {"relational", FeatureSetConfig::RELATIONAL}, {"hogrel", FeatureSetConfig::HOGREL}, {"hogpos", FeatureSetConfig::HOGPOS}, {"positional", FeatureSetConfig::POSITIONAL}, {"hog", FeatureSetConfig::HOG}}; if (options.count("feature-set")) { string featuresetname = options["feature-set"].as<string>(); std::transform(featuresetname.begin(), featuresetname.end(), featuresetname.begin(), ::tolower); if (m.count(featuresetname)) { params.featureSet = m[featuresetname]; } else { throw po::error("unknown feature-set provided: " + featuresetname); } } copyCheckArg("svm-c", params.c); copyCheckArg("svm-epsilon", params.epsilon); copyCheckArg("svm-epsilon-insensitivity", params.epsilon_insensitivity); copyCheckArg("pca-epsilon", params.pca_epsilon); return params; } void run() { po::options_description allopts("\n*** dlibgazer options"); po::options_description desc("general options"); desc.add_options() ("help,h", "show help messages") ("model,m", po::value<string>()->required(), "read models from file arg") ("threads", po::value<int>(), "set number of threads per processing step") ("noquit", "do not quit after processing") ("novis", "do not display frames") ("quiet,q", "do not print statistics") ("limitfps", po::value<double>(), "slow down display fps to arg") ("streamppm", po::value<string>(), "stream ppm files to arg. e.g. " ">(ffmpeg -f image2pipe -vcodec ppm -r 30 -i - -r 30 -preset ultrafast out.mp4)") ("dump-estimates", po::value<string>(), "dump estimated values to file") ("mirror", "mirror output"); po::options_description inputops("input options"); inputops.add_options() ("camera,c", po::value<string>(), "use camera number arg") ("video,v", po::value<string>(), "process video file arg") ("image,i", po::value<string>(), "process single image arg") ("port,p", po::value<string>(), "expect image on yarp port arg") ("batch,b", po::value<string>(), "batch process image filenames from arg") ("size", po::value<string>(), "request image size arg and scale if required") ("fps", po::value<int>(), "request video with arg frames per second"); po::options_description classifyopts("classification options"); classifyopts.add_options() ("classify-gaze", po::value<string>(), "load classifier from arg") ("train-gaze-classifier", po::value<string>(), "train gaze classifier and save to arg") ("classify-lid", po::value<string>(), "load classifier from arg") ("estimate-lid", po::value<string>(), "load classifier from arg") ("train-lid-classifier", po::value<string>(), "train lid classifier and save to arg") ("train-lid-estimator", po::value<string>(), "train lid estimator and save to arg") ("estimate-gaze", po::value<string>(), "estimate gaze") ("estimate-verticalgaze", po::value<string>(), "estimate vertical gaze") ("horizontal-gaze-tolerance", po::value<double>(), "mutual gaze tolerance in deg") ("vertical-gaze-tolerance", po::value<double>(), "mutual gaze tolerance in deg") ("train-gaze-estimator", po::value<string>(), "train gaze estimator and save to arg") ("train-verticalgaze-estimator", po::value<string>(), "train vertical gaze estimator and save to arg"); po::options_description trainopts("parameters applied to all active trainers"); trainopts.add_options() ("svm-c", po::value<double>(), "svm c parameter") ("svm-epsilon", po::value<double>(), "svm epsilon parameter") ("svm-epsilon-insensitivity", po::value<double>(), "svmr insensitivity parameter") ("feature-set", po::value<string>(), "use feature set arg") ("pca-epsilon", po::value<double>(), "pca dimension reduction depending on arg"); allopts.add(desc).add(inputops).add(classifyopts).add(trainopts); try { po::store(po::parse_command_line(argc, argv, allopts), options); if (options.count("help")) { allopts.print(cout); std::exit(0); } po::notify(options); for (const auto& s : { "camera", "image", "video", "port", "batch"}) { if (options.count(s)) { if (worker.inputType.empty()) { worker.inputParam = options[s].as<string>(); worker.inputType = s; } else { throw po::error("More than one input option provided"); } } } if (worker.inputType.empty()) { throw po::error("No input option provided"); } if (options.count("size")) { auto sizestr = options["size"].as<string>(); vector<string> args; boost::split(args, sizestr, boost::is_any_of(":x ")); if (args.size() != 2) throw po::error("invalid size " + sizestr); worker.inputSize = cv::Size(boost::lexical_cast<int>(args[0]), boost::lexical_cast<int>(args[1])); } copyCheckArg("fps", worker.desiredFps); copyCheckArg("threads", worker.threadcount); copyCheckArg("streamppm", worker.streamppm); copyCheckArg("model", worker.modelfile); copyCheckArg("classify-gaze", worker.classifyGaze); copyCheckArg("train-gaze-classifier", worker.trainGaze); copyCheckArg("train-lid-classifier", worker.trainLid); copyCheckArg("train-lid-estimator", worker.trainLidEstimator); copyCheckArg("classify-lid", worker.classifyLid); copyCheckArg("estimate-lid", worker.estimateLid); copyCheckArg("estimate-gaze", worker.estimateGaze); copyCheckArg("estimate-verticalgaze", worker.estimateVerticalGaze); copyCheckArg("train-gaze-estimator", worker.trainGazeEstimator); copyCheckArg("train-verticalgaze-estimator", worker.trainVerticalGazeEstimator); copyCheckArg("limitfps", worker.limitFps); copyCheckArg("dump-estimates", worker.dumpEstimates); copyCheckArg("horizontal-gaze-tolerance", worker.horizGazeTolerance); copyCheckArg("vertical-gaze-tolerance", worker.verticalGazeTolerance); if (options.count("quiet")) worker.showstats = false; gui.setHorizGazeTolerance(worker.horizGazeTolerance); gui.setVerticalGazeTolerance(worker.verticalGazeTolerance); bool mirror = false; copyCheckArg("mirror", mirror); worker.trainingParameters = parseTrainingOpts(); gui.setMirror(mirror); } catch(po::error& e) { cerr << "Error parsing command line:" << endl << e.what() << endl; std::exit(1); } } }; int main(int argc, char** argv) { qRegisterMetaType<GazeHypsPtr>(); qRegisterMetaType<std::string>(); WorkerThread gazer; QApplication app(argc, argv); GazerGui gui; //trying to write to cerr, cout, or throw an exception leads to deadlock in this function. //the reason is currently a mystery. //As a workaround a new thread is started. This does not make much sense but it works. OptionParser optparser(argc, argv, gazer, gui); optparser.start(); optparser.wait(); if (!optparser.options.count("novis")) gui.show(); QThread thread; gazer.moveToThread(&thread); QObject::connect(&app, SIGNAL(lastWindowClosed()), &gazer, SLOT(stop())); QObject::connect(&gazer, SIGNAL(finished()), &thread, SLOT(quit())); if (!optparser.options.count("novis")) { QObject::connect(&gazer, SIGNAL(imageProcessed(GazeHypsPtr)), &gui, SLOT(displayGazehyps(GazeHypsPtr)), Qt::QueuedConnection); } QObject::connect(&gazer, SIGNAL(statusmsg(std::string)), &gui, SLOT(setStatusmsg(std::string))); QObject::connect(&thread, SIGNAL(started()), &gazer, SLOT(process())); QObject::connect(&gui, SIGNAL(horizGazeToleranceChanged(double)), &gazer, SLOT(setHorizGazeTolerance(double))); QObject::connect(&gui, SIGNAL(verticalGazeToleranceChanged(double)), &gazer, SLOT(setVerticalGazeTolerance(double))); QObject::connect(&gui, SIGNAL(smoothingChanged(bool)), &gazer, SLOT(setSmoothing(bool))); if (!optparser.options.count("noquit")) { QObject::connect(&gazer, SIGNAL(finished()), &app, SLOT(quit())); } thread.start(); app.exec(); //process events after event loop terminates allowing unfinished threads to send signals while (thread.isRunning()) { thread.wait(10); QCoreApplication::processEvents(); } }
49.486111
132
0.582936
[ "vector", "model", "transform" ]
c6baa19a4b78306d644057c25430caff0a9c03bd
895
cpp
C++
RUEngine/Demos/main.cpp
rutgerklamer/Rugine
39b7c60cfc54629ac76da33bc0e61ca9b82f7483
[ "Unlicense" ]
4
2017-11-10T07:57:36.000Z
2021-04-04T15:34:23.000Z
RUEngine/Demos/main.cpp
rutgerklamer/Rugine
39b7c60cfc54629ac76da33bc0e61ca9b82f7483
[ "Unlicense" ]
null
null
null
RUEngine/Demos/main.cpp
rutgerklamer/Rugine
39b7c60cfc54629ac76da33bc0e61ca9b82f7483
[ "Unlicense" ]
null
null
null
#include <iostream> #include <GL/glew.h> #include "glfw3.h" #include <vector> #include "Engine/Display.h" #include "Demos/Scene.h" #include "Demos/Scene0.h" #include "Demos/Scene1.h" #include "Demos/Scene2.h" #include "Demos/Scene3.h" Display* display; Scene* scene; Scene0* scene0; Scene1* scene1; Scene2* scene2; Scene3* scene3; int main() { display = new Display(); scene = new Scene(display->input); scene0 = new Scene0(display->input); scene1 = new Scene1(display->input); scene2 = new Scene2(display->input); scene3 = new Scene3(display->input); display->addScene(scene); display->addScene(scene0); display->addScene(scene1); display->addScene(scene2); display->addScene(scene3); display->gameLoop(); delete scene; delete scene0; delete scene1; delete scene2; delete scene3; delete display; std::cout << "Window closed" << std::endl; return 0; }
20.813953
44
0.696089
[ "vector" ]
c6bb09184904694fc6fed509714d7e2dcbbe1813
2,701
hpp
C++
Trab2/include/util.hpp
nogenem/Compiladores-2016-1
32ae2840c562a32a4b11902818eec8b0c0e4df54
[ "MIT" ]
1
2018-03-23T00:05:48.000Z
2018-03-23T00:05:48.000Z
Trab2/include/util.hpp
nogenem/UFSC_Compiladores-2016-1
32ae2840c562a32a4b11902818eec8b0c0e4df54
[ "MIT" ]
1
2016-05-08T14:53:27.000Z
2016-05-08T15:35:14.000Z
Trab2/include/util.hpp
nogenem/UFSC_Compiladores-2016-1
32ae2840c562a32a4b11902818eec8b0c0e4df54
[ "MIT" ]
null
null
null
/* * util.hpp * * Created on: 10 de jun de 2016 * Author: Gilne */ #pragma once #include <vector> namespace Ops { enum Operation {plus, b_minus, times, division, assign, eq, neq, grt, grteq, lst, lsteq, b_and, b_or, u_not, u_minus, u_paren}; const std::vector<bool> masculineOp = { false, //soma inteira false, //subtracao inteira false, //multiplicacao inteira false, //divisao inteira false, //atribuicao intera (nunca usado) true, //igual inteiro true, //diferente inteiro true, //maior inteiro true, //maior ou igual inteiro true, //menor inteiro true, //menor ou igual inteiro true, //e booleano true, //ou booleano true, //nao booleano true, //menos unario inteiro false //parenteses inteiro (nunca usado) }; const std::vector<const char*> opName = { "soma", "subtracao", "multiplicacao", "divisao", "atribuicao", "igual", "diferente", "maior", "maior ou igual", "menor", "menor ou igual", "e", "ou", "nao", "menos unario", "parenteses" }; } namespace Types { enum Type{unknown_t, int_t, bool_t, arr_t, func_t}; const std::vector<const char*> mascType = { "desconhecido", "inteiro", "booleano", "arranjo", "funcao" }; const std::vector<const char*> femType = { "desconhecida", "inteira", "booleana", "arranjo", "funcao" }; Type unType(Ops::Operation op, Type right); Type binType(Type left, Ops::Operation op, Type right); } namespace Errors { const std::vector<const char*> messages = { "syntax error",//syntax_error "lexico: simbolo desconhecido: %c.",//unknown_symbol "semantico: variavel %s sem declaracao.",//without_declaration "semantico: variavel %s sofrendo redefinicao.",//redefinition "semantico: operacao %s espera %s mas recebeu %s.",//op_wrong_type "semantico: divisao por zero.",//div_zero "semantico: tentativa de indexar variavel %s (um valor %s).",//attempt_index "semantico: indice de tipo %s.",//index_wrong_type "semantico: arranjo espera valor inteiro, booleano ou desconhecido mas recebeu %s.",//arr_type_not_allowed "semantico: operacao %s espera tipos iguais mas recebeu %s e %s.",//different_types "semantico: tentativa de chamar variavel %s (um valor %s).",//attempt_call "semantico: funcao espera retornar inteiro, booleano ou desconhecido mas retornou %s.",//func_type_not_allowed }; enum ErrorType{ syntax_error, unknown_symbol, without_declaration, redefinition, op_wrong_type, div_zero, attempt_index, index_wrong_type, arr_type_not_allowed, different_types, attempt_call, func_type_not_allowed }; void throwErr(ErrorType error, ...); }
31.045977
113
0.676416
[ "vector" ]
c6be630ab04f97ed87f2d0d21f9fa573af20c269
418
cpp
C++
practice/maxSumWithoutAdjEle.cpp
ANONYMOUS609/Competitive-Programming
d3753eeee24a660963f1d8911bf887c8f41f5677
[ "MIT" ]
2
2019-01-30T12:45:18.000Z
2021-05-06T19:02:51.000Z
practice/maxSumWithoutAdjEle.cpp
ANONYMOUS609/Competitive-Programming
d3753eeee24a660963f1d8911bf887c8f41f5677
[ "MIT" ]
null
null
null
practice/maxSumWithoutAdjEle.cpp
ANONYMOUS609/Competitive-Programming
d3753eeee24a660963f1d8911bf887c8f41f5677
[ "MIT" ]
3
2020-10-02T15:42:04.000Z
2022-03-27T15:14:16.000Z
//INterview Bit int Solution::adjacent(vector<vector<int> > &A) { int n=A[0].size();//size of arr for(int i=0;i<n;i++) //store max for each coloum A[0][i]=max(A[0][i],A[1][i]); A[0][1]=max(A[0][0],A[0][1]); //for 2nd element choose max among first end second for(int i=2;i<n;i++) A[0][i]=max(A[0][i-1],A[0][i-2]+A[0][i]); return max(A[0][n-1],A[0][n-2]); }
26.125
85
0.497608
[ "vector" ]
c6c6ce0da845c0ff5f22e6987dd1ba45c0885f33
13,137
cc
C++
src/AST/ASTVerificationVisitor.cc
dburkart/check-sieve
667f0e9670e8820e37a8162ec09e794e6e4f1cb4
[ "MIT" ]
20
2015-09-06T04:16:04.000Z
2022-03-24T16:34:56.000Z
src/AST/ASTVerificationVisitor.cc
dburkart/check-sieve
667f0e9670e8820e37a8162ec09e794e6e4f1cb4
[ "MIT" ]
23
2015-09-06T00:48:52.000Z
2021-05-23T04:14:49.000Z
src/AST/ASTVerificationVisitor.cc
dburkart/check-sieve
667f0e9670e8820e37a8162ec09e794e6e4f1cb4
[ "MIT" ]
3
2015-09-08T05:24:08.000Z
2019-04-01T00:15:29.000Z
#include <algorithm> #include <iostream> #include <vector> #include "ASTVerificationVisitor.hh" namespace sieve { ASTVerificationVisitor::ASTVerificationVisitor(struct parse_options options) : _verification_result() , _command() , _test() , _tag() , _options( options ) , _required_capabilities( nullptr ) { _init(); } void ASTVerificationVisitor::walk( ASTSieve *root ) { this->_traverse_tree( root ); } void ASTVerificationVisitor::_traverse_tree( sieve::ASTNode *node ) { node->accept(*this); if (result().status) return; std::vector<sieve::ASTNode *> children = node->children(); for (auto child : children) { _traverse_tree(child); } } void ASTVerificationVisitor::visit( ASTBlock* node ) { } void ASTVerificationVisitor::visit( ASTBoolean* node ) { } void ASTVerificationVisitor::visit( ASTBranch* node ) { } void ASTVerificationVisitor::visit( ASTCommand* node ) { std::string value_lower = node->value(); std::transform(value_lower.begin(), value_lower.end(), value_lower.begin(), ::tolower); if (!_command_map[value_lower]) { _verification_result = {1, node->location(), "Unrecognized command \"" + node->value() + "\"."}; } else if (!_command.validate(node)) { _verification_result = { 1, node->location(), "Incorrect syntax for command \"" + node->value() + "\".", _command.usage(node) }; } } void ASTVerificationVisitor::visit( ASTCondition* node ) { } void ASTVerificationVisitor::visit( ASTNoOp* ) { // No Op } void ASTVerificationVisitor::visit( ASTNumeric* node ) { } void ASTVerificationVisitor::visit( ASTRequire* node ) { std::vector<sieve::ASTNode *> children = node->children(); // If we are requiring multiple modules, we need our grandchildren if (dynamic_cast<ASTStringList *>(children[0]) != nullptr) { _required_capabilities = dynamic_cast<ASTStringList *>(children[0]); children = children[0]->children(); } for (auto & it : children) { auto *child = dynamic_cast<ASTString *>(it); _capability_map[child->value()] = 1; _enable_capability(child->value()); } } void ASTVerificationVisitor::visit( ASTSieve* node ) { } void ASTVerificationVisitor::visit( ASTString* node ) { } void ASTVerificationVisitor::visit( ASTStringList* node ) { if ( _options.string_list_max_length ) { if ( node->length() > _options.string_list_max_length ) { _verification_result = {1, node->location(), "String list length is " + std::to_string(node->length()) + ", but the configured maximum is " + std::to_string(_options.string_list_max_length)}; } } } void ASTVerificationVisitor::visit( ASTTag* node ) { std::string value_lower = node->value(); std::transform(value_lower.begin(), value_lower.end(), value_lower.begin(), ::tolower); if (!_tag_map[value_lower]) { _verification_result = {1, node->location(), "Unrecognized tag \"" + node->value() + "\"."}; } if (!_tag.validate(node)) { _verification_result = { 1, node->location(), "Incorrect syntax for tag \"" + node->value() + "\".", _tag.usage(node) }; } } void ASTVerificationVisitor::visit( ASTTest* node ) { std::vector<sieve::ASTNode *> children = node->children(); std::string value_lower = node->value(); std::transform(value_lower.begin(), value_lower.end(), value_lower.begin(), ::tolower); const ASTTag *first_match_tag = nullptr; const ASTTag *second_match_tag = nullptr; if (!_test_map[value_lower]) { _verification_result = {1, node->location(), "Unrecognized test \"" + node->value() + "\"."}; } for (auto & it : children) { // Are we an ASTTag? const ASTTag *child = dynamic_cast<ASTTag*>(it); if (child != nullptr) { // Ensure that we have only _one_ of :is, :contains, or :matches if (child->value() == ":is" || child->value() == ":contains" || child->value() == ":matches") { if (first_match_tag == nullptr) first_match_tag = child; else if (second_match_tag == nullptr) second_match_tag = child; } } // If it's an "ihave" test, we need to enable any specified capabilities if (value_lower == "ihave") { const ASTString *capability = dynamic_cast<ASTString*>(it); if (capability != nullptr) { _enable_capability(capability->value()); } } } if (second_match_tag != nullptr) { _verification_result = {1, second_match_tag->location(), "Only one match type tag is allowed; first match type tag was \"" + first_match_tag->value() + "\"."}; } if (!_test.validate(node)) { _verification_result = { 1, node->location(), "Incorrect syntax for test \"" + node->value() + "\".", _test.usage(node) }; } } //-- Private methods void ASTVerificationVisitor::_init() { _command_map["addheader"] = true; _command_map["keep"] = true; _command_map["deleteheader"] = true; _command_map["discard"] = true; _command_map["redirect"] = true; _command_map["stop"] = true; _test_map["allof"] = true; _test_map["anyof"] = true; _test_map["address"] = true; _test_map["envelope"] = true; _test_map["header"] = true; _test_map["size"] = true; _test_map["not"] = true; _test_map["exists"] = true; _test_map["$command_result"] = true; // Special test indicating the result of a command _tag_map[":is"] = true; _tag_map[":contains"] = true; _tag_map[":matches"] = true; _tag_map[":last"] = true; _tag_map[":localpart"] = true; _tag_map[":domain"] = true; _tag_map[":all"] = true; _tag_map[":over"] = true; _tag_map[":under"] = true; // TODO: "Comparators other than "i;octet" and "i;ascii-casemap" must be // declared with require, as they are extensions" _tag_map[":comparator"] = true; // Set up references to this visitor for introspection _command.set_visitor(this); _test.set_visitor(this); _tag.set_visitor(this); } void ASTVerificationVisitor::_enable_capability(const std::string& capability) { if (!_options.all_supported_capabilities && !_options.capabilities[capability]) { _verification_result = { 1, yy::location(), "Capability \"" + capability + "\" was requested, but does not seem to be supported by your mail server." }; return; } // "copy" // RFC 3894 if (capability == "copy") { _tag_map[":copy"] = true; } // "body" // RFC 5173 if (capability == "body") { _test_map["body"] = true; _tag_map[":raw"] = true; _tag_map[":content"] = true; _tag_map[":text"] = true; } // "environment" // RFC 5183 if (capability == "environment") { _test_map["environment"] = true; } // "fileinto" // RFC 5228 if (capability == "fileinto") { _command_map["fileinto"] = true; } // "reject" // RFC 5228 if (capability == "reject") { _command_map["reject"] = true; } // "variables" // RFC 5229 if (capability == "variables") { _command_map["set"] = true; _test_map["string"] = true; _tag_map[":lower"] = true; _tag_map[":upper"] = true; _tag_map[":lowerfirst"] = true; _tag_map[":upperfirst"] = true; _tag_map[":quotewildcard"] = true; _tag_map[":length"] = true; } // "vacation" // RFC 5230 if (capability == "vacation") { _command_map["vacation"] = true; _tag_map[":days"] = true; _tag_map[":from"] = true; _tag_map[":subject"] = true; _tag_map[":addresses"] = true; _tag_map[":mime"] = true; _tag_map[":handle"] = true; } // "relational" // RFC 5231 if (capability == "relational") { _tag_map[":count"] = true; _tag_map[":value"] = true; } // "imap4flags" // RFC 5232 if (capability == "imap4flags") { _command_map["setflag"] = true; _command_map["addflag"] = true; _command_map["removeflag"] = true; _test_map["hasflag"] = true; _tag_map[":flags"] = true; } // "subaddress" // RFC 5233 if (capability == "subaddress") { _tag_map[":user"] = true; _tag_map[":detail"] = true; } // "date" // RFC 5260 if (capability == "date") { _test_map["date"] = true; _test_map["currentdate"] = true; _tag_map[":zone"] = true; _tag_map[":originalzone"] = true; } // "index" // RFC 5260 if (capability == "index") { _tag_map[":index"] = true; _tag_map[":last"] = true; } // "spamtest" or "spamtestplus" // RFC 5235 if (capability == "spamtest" || capability == "spamtestplus") { _test_map["spamtest"] = true; _tag_map[":percent"] = true; } // "virustest" // RFC 5235 if (capability == "virustest") { _test_map["virustest"] = true; } // "ereject" // RFC 5429 if (capability == "ereject") { _command_map["ereject"] = true; } // "enotify" // RFC 5435 if (capability == "enotify") { _command_map["notify"] = true; _tag_map[":from"] = true; _tag_map[":importance"] = true; _tag_map[":options"] = true; _tag_map[":message"] = true; _test_map["valid_notify_method"] = true; _test_map["notify_method_capability"] = true; // The :encodeurl tag can only be used if both "enotify" and // "variables" are required if (_required_capabilities != nullptr && _required_capabilities->find(ASTString("variables")) != _required_capabilities->children().end()) { _tag_map[":encodeurl"] = true; } } // "ihave" // RFC 5463 if (capability == "ihave") { _command_map["error"] = true; _test_map["ihave"] = true; } // "mailbox" // RFC 5490 if (capability == "mailbox") { _test_map["mailboxexists"] = true; _tag_map[":create"] = true; } // "mboxmetadata" // RFC 5490 if (capability == "mboxmetadata") { _test_map["metadata"] = true; _test_map["metadataexists"] = true; } // "servermetadata" // RFC 5490 if (capability == "servermetadata") { _test_map["servermetadata"] = true; _test_map["servermetadataexists"] = true; } // "foreverypart" // RFC 5703 if (capability == "foreverypart") { _command_map["foreverypart"] = true; _command_map["break"] = true; _tag_map[":name"] = true; } // "mime" // RFC 5703 if (capability == "mime") { _tag_map[":mime"] = true; _tag_map[":type"] = true; _tag_map[":subtype"] = true; _tag_map[":contenttype"] = true; _tag_map[":param"] = true; _tag_map[":anychild"] = true; } // "extracttext" // RFC 5703 if (capability == "extracttext") { _command_map["extracttext"] = true; _tag_map[":first"] = true; } // "replace" // RFC 5703 if (capability == "replace") { _command_map["replace"] = true; _tag_map[":subject"] = true; _tag_map[":from"] = true; } // "enclose" // RFC 5703 if (capability == "enclose") { _command_map["enclose"] = true; _tag_map[":subject"] = true; _tag_map[":headers"] = true; } // "include" // RFC 6609 if (capability == "include") { _command_map["include"] = true; _command_map["return"] = true; _tag_map[":once"] = true; _tag_map[":optional"] = true; _tag_map[":personal"] = true; _tag_map[":global"] = true; // The "global" command can only be used if both "include" and // "variables" are required if (_required_capabilities != nullptr && _required_capabilities->find(ASTString("variables")) != _required_capabilities->children().end()) { _command_map["global"] = true; } } // "convert" // RFC 6658 if (capability == "convert") { _command_map["convert"] = true; } // DRAFT RFCs // "regex" // (https://tools.ietf.org/html/draft-ietf-sieve-regex-01) if (capability == "regex") { _tag_map[":regex"] = true; // The ":quoteregex" command is supported if both "regex" and // "variables" are required if (_required_capabilities != nullptr && _required_capabilities->find(ASTString("variables")) != _required_capabilities->children().end()) { _tag_map[":quoteregex"] = true; } } } } // namespace sieve
27.656842
203
0.566339
[ "vector", "transform" ]
c6ccc2adc659fda60115f26f6a2e797a19fe3471
22,433
cc
C++
paddle/fluid/framework/executor_thread_worker.cc
L-Net-1992/Paddle
4d0ca02ba56760b456f3d4b42a538555b9b6c307
[ "Apache-2.0" ]
11
2016-08-29T07:43:26.000Z
2016-08-29T07:51:24.000Z
paddle/fluid/framework/executor_thread_worker.cc
L-Net-1992/Paddle
4d0ca02ba56760b456f3d4b42a538555b9b6c307
[ "Apache-2.0" ]
null
null
null
paddle/fluid/framework/executor_thread_worker.cc
L-Net-1992/Paddle
4d0ca02ba56760b456f3d4b42a538555b9b6c307
[ "Apache-2.0" ]
1
2021-09-24T11:23:36.000Z
2021-09-24T11:23:36.000Z
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "paddle/fluid/framework/executor_thread_worker.h" #include <algorithm> #include <utility> #include "gflags/gflags.h" #include "google/protobuf/io/zero_copy_stream_impl.h" #include "google/protobuf/message.h" #include "google/protobuf/text_format.h" #include "paddle/fluid/framework/convert_utils.h" #include "paddle/fluid/framework/feed_fetch_method.h" #include "paddle/fluid/framework/feed_fetch_type.h" #include "paddle/fluid/framework/lod_rank_table.h" #include "paddle/fluid/framework/lod_tensor_array.h" #include "paddle/fluid/framework/op_registry.h" #include "paddle/fluid/framework/reader.h" #include "paddle/fluid/framework/variable_helper.h" #include "paddle/fluid/inference/io.h" #include "paddle/fluid/platform/cpu_helper.h" #include "paddle/fluid/platform/place.h" #include "paddle/fluid/platform/timer.h" #include "paddle/fluid/pybind/pybind.h" // phi #include "paddle/phi/kernels/declarations.h" namespace paddle { namespace framework { #ifdef PADDLE_WITH_PSLIB int DensePullThread::start() { _running = true; _t = std::thread(&DensePullThread::run, this); return 0; } void DensePullThread::run() { while (_running) { _pull_dense_status.resize(0); for (auto& t : _dense_variable_name) { if (check_update_param(t.first)) { auto status = pull_dense(t.first); _pull_dense_status.emplace_back(std::move(status)); reset_thread_version(t.first); } } if (_pull_dense_status.size() != 0) { wait_all(); } usleep(_sleep_time_ms * 1000); } } bool DensePullThread::check_update_param(uint64_t table_id) { { std::lock_guard<std::mutex> lock(_mutex_for_version); auto& version = _training_versions[table_id]; _current_version[table_id] = *(std::min_element(version.begin(), version.end())); } if (_current_version[table_id] - _last_versions[table_id] < _threshold) { return false; } return true; } void DensePullThread::reset_thread_version(uint64_t table_id) { std::lock_guard<std::mutex> lock(_mutex_for_version); _last_versions[table_id] = _current_version[table_id]; } std::future<int32_t> DensePullThread::pull_dense(uint64_t table_id) { auto& regions = _regions[table_id]; regions.clear(); auto& variables = _dense_variable_name[table_id]; regions.resize(variables.size()); for (auto i = 0u; i < variables.size(); ++i) { auto& t = variables[i]; Variable* var = _root_scope->FindVar(t); LoDTensor* tensor = var->GetMutable<LoDTensor>(); float* w = tensor->data<float>(); paddle::ps::Region reg(w, tensor->numel()); regions[i] = std::move(reg); } return _ps_client->pull_dense(regions.data(), regions.size(), table_id); } void DensePullThread::wait_all() { for (auto& t : _pull_dense_status) { t.wait(); auto status = t.get(); if (status != 0) { LOG(WARNING) << "pull dense failed times:" << ++_pull_dense_fail_times; } } if (_pull_dense_fail_times > 20) { PADDLE_THROW( platform::errors::Fatal("Pull dense failed more than 20 times.")); exit(-1); } _pull_dense_status.resize(0); } void DensePullThread::increase_thread_version(int thread_id, uint64_t table_id) { std::lock_guard<std::mutex> lock(_mutex_for_version); _training_versions[table_id][thread_id]++; } #endif void ExecutorThreadWorker::CreateThreadOperators(const ProgramDesc& program) { auto& block = program.Block(0); op_names_.clear(); for (auto& op_desc : block.AllOps()) { std::unique_ptr<OperatorBase> local_op = OpRegistry::CreateOp(*op_desc); op_names_.push_back(op_desc->Type()); OperatorBase* local_op_ptr = local_op.release(); ops_.push_back(local_op_ptr); continue; } } void ExecutorThreadWorker::CreateThreadResource( const framework::ProgramDesc& program, const paddle::platform::Place& place) { CreateThreadScope(program); CreateThreadOperators(program); SetMainProgram(program); SetPlace(place); } void ExecutorThreadWorker::CreateThreadScope(const ProgramDesc& program) { auto& block = program.Block(0); PADDLE_ENFORCE_NOT_NULL( root_scope_, platform::errors::PreconditionNotMet( "root_scope should be set before creating thread scope.")); thread_scope_ = &root_scope_->NewScope(); for (auto& var : block.AllVars()) { if (var->Persistable()) { auto* ptr = root_scope_->Var(var->Name()); InitializeVariable(ptr, var->GetType()); } else { auto* ptr = thread_scope_->Var(var->Name()); InitializeVariable(ptr, var->GetType()); } } } void ExecutorThreadWorker::SetDataFeed( const std::shared_ptr<DataFeed>& datafeed) { thread_reader_ = datafeed; } void ExecutorThreadWorker::BindingDataFeedMemory() { const std::vector<std::string>& input_feed = thread_reader_->GetUseSlotAlias(); for (auto name : input_feed) { thread_reader_->AddFeedVar(thread_scope_->Var(name), name); } } void ExecutorThreadWorker::SetFetchVarNames( const std::vector<std::string>& fetch_var_names) { fetch_var_names_.clear(); fetch_var_names_.insert(fetch_var_names_.end(), fetch_var_names.begin(), fetch_var_names.end()); } void ExecutorThreadWorker::SetDevice() { #if defined _WIN32 || defined __APPLE__ return; #else static unsigned concurrency_cap = std::thread::hardware_concurrency(); LOG(WARNING) << "concurrency capacity " << concurrency_cap; int thread_id = this->thread_id_; if (static_cast<unsigned>(thread_id) < concurrency_cap) { unsigned proc = thread_id; cpu_set_t mask; CPU_ZERO(&mask); CPU_SET(proc, &mask); if (-1 == sched_setaffinity(0, sizeof(mask), &mask)) { VLOG(1) << "WARNING: Failed to set thread affinity for thread " << thread_id; } else { CPU_ZERO(&mask); if ((0 != sched_getaffinity(0, sizeof(mask), &mask)) || (CPU_ISSET(proc, &mask) == 0)) { VLOG(3) << "WARNING: Failed to set thread affinity for thread " << thread_id; } } } else { VLOG(1) << "WARNING: Failed to set thread affinity for thread " << thread_id; } #endif } template <typename T> void print_lod_tensor(std::string var_name, const LoDTensor& lod_tensor) { auto inspect = lod_tensor.data<T>(); auto element_num = lod_tensor.numel(); std::ostringstream sstream; sstream << var_name << " (element num " << element_num << "): ["; sstream << inspect[0]; for (int j = 1; j < element_num; ++j) { sstream << " " << inspect[j]; } sstream << "]"; std::cout << sstream.str() << std::endl; } static void print_fetch_var(Scope* scope, const std::string& var_name) { auto& tensor = scope->FindVar(var_name)->Get<LoDTensor>(); #define PrintLoDTensorCallback(cpp_type, proto_type) \ do { \ if (framework::TransToProtoVarType(tensor.dtype()) == proto_type) { \ print_lod_tensor<cpp_type>(var_name, tensor); \ return; \ } \ } while (0) _ForEachDataType_(PrintLoDTensorCallback); VLOG(1) << "print_fetch_var: unrecognized data type:" << tensor.dtype(); } void ExecutorThreadWorker::TrainFilesWithTimer() { platform::SetNumThreads(1); SetDevice(); thread_reader_->Start(); std::vector<double> op_total_time; std::vector<std::string> op_name; for (auto& op : ops_) { op_name.push_back(op->Type()); } op_total_time.resize(ops_.size()); for (size_t i = 0; i < op_total_time.size(); ++i) { op_total_time[i] = 0.0; } platform::Timer timeline; double total_time = 0.0; double read_time = 0.0; int cur_batch; int batch_cnt = 0; timeline.Start(); while ((cur_batch = thread_reader_->Next()) > 0) { timeline.Pause(); read_time += timeline.ElapsedSec(); total_time += timeline.ElapsedSec(); for (size_t i = 0; i < ops_.size(); ++i) { timeline.Start(); ops_[i]->Run(*thread_scope_, place_); timeline.Pause(); op_total_time[i] += timeline.ElapsedSec(); total_time += timeline.ElapsedSec(); } ++batch_cnt; thread_scope_->DropKids(); if (thread_id_ == 0) { if (batch_cnt > 0 && batch_cnt % 100 == 0) { for (size_t i = 0; i < ops_.size(); ++i) { fprintf(stderr, "op_name:[%zu][%s], op_mean_time:[%fs]\n", i, op_name[i].c_str(), op_total_time[i] / batch_cnt); } fprintf(stderr, "mean read time: %fs\n", read_time / batch_cnt); int fetch_var_num = fetch_var_names_.size(); for (int i = 0; i < fetch_var_num; ++i) { print_fetch_var(thread_scope_, fetch_var_names_[i]); } fprintf(stderr, "IO percent: %f\n", read_time / total_time); } } timeline.Start(); } } void ExecutorThreadWorker::TrainFiles() { platform::SetNumThreads(1); // todo: configurable // SetDevice(); int fetch_var_num = fetch_var_names_.size(); fetch_values_.clear(); fetch_values_.resize(fetch_var_num); thread_reader_->Start(); int cur_batch; int batch_cnt = 0; while ((cur_batch = thread_reader_->Next()) > 0) { // executor run here for (auto& op : ops_) { op->Run(*thread_scope_, place_); } ++batch_cnt; thread_scope_->DropKids(); if (debug_ == false || thread_id_ != 0) { continue; } for (int i = 0; i < fetch_var_num; ++i) { print_fetch_var(thread_scope_, fetch_var_names_[i]); } // end for (int i = 0...) } // end while () } void ExecutorThreadWorker::SetThreadId(int tid) { thread_id_ = tid; } void ExecutorThreadWorker::SetPlace(const platform::Place& place) { place_ = place; } void ExecutorThreadWorker::SetMainProgram( const ProgramDesc& main_program_desc) { main_program_.reset(new ProgramDesc(main_program_desc)); } void ExecutorThreadWorker::SetRootScope(Scope* g_scope) { root_scope_ = g_scope; } #ifdef PADDLE_WITH_PSLIB // AsyncExecutor void AsyncExecutorThreadWorker::TrainFiles() { SetDevice(); int fetch_var_num = fetch_var_names_.size(); fetch_values_.clear(); fetch_values_.resize(fetch_var_num); thread_reader_->Start(); int cur_batch; int batch_cnt = 0; while ((cur_batch = thread_reader_->Next()) > 0) { // executor run here TrainOneNetwork(); ++batch_cnt; thread_scope_->DropKids(); if (debug_ == false || thread_id_ != 0) { continue; } for (int i = 0; i < fetch_var_num; ++i) { print_fetch_var(thread_scope_, fetch_var_names_[i]); } // end for (int i = 0...) } // end while () } void AsyncExecutorThreadWorker::SetPSlibPtr( std::shared_ptr<paddle::distributed::PSlib> pslib_ptr) { _pslib_ptr = pslib_ptr; } void AsyncExecutorThreadWorker::SetPullDenseThread( std::shared_ptr<DensePullThread> dpt) { _pull_dense_thread = dpt; } void AsyncExecutorThreadWorker::TrainOneNetwork() { PrepareParams(); for (auto& op : ops_) { if (op->Type().find("sgd") != std::string::npos) { continue; } bool need_skip = false; for (auto t = 0u; t < _param_config->skip_op.size(); ++t) { if (op->Type().find(_param_config->skip_op[t]) != std::string::npos) { need_skip = true; break; } } if (!need_skip) { op->Run(*thread_scope_, place_); } } UpdateParams(); } void AsyncExecutorThreadWorker::SetParamConfig( AsyncWorkerParamConfig* param_config) { _param_config = param_config; } void AsyncExecutorThreadWorker::PrepareParams() { for (auto table_id : _param_config->sparse_table_id) { PullSparse(table_id); for (auto& t : _pull_sparse_status) { t.wait(); auto status = t.get(); if (status != 0) { LOG(ERROR) << "pull sparse failed, status[" << status << "]"; exit(-1); } } } _pull_sparse_status.resize(0); for (auto table_id : _param_config->sparse_table_id) { FillSparse(table_id); } } void AsyncExecutorThreadWorker::UpdateParams() { for (auto i : _param_config->sparse_table_id) { PushSparse(i); } for (auto i : _param_config->dense_table_id) { PushDense(i); } int32_t tmp_push_dense_wait_times = -1; int32_t tmp_push_sparse_wait_times = -1; static uint32_t push_dense_wait_times = static_cast<uint32_t>(tmp_push_dense_wait_times); static uint32_t push_sparse_wait_times = static_cast<uint32_t>(tmp_push_sparse_wait_times); if (_push_dense_status.size() >= push_dense_wait_times) { for (auto& t : _push_dense_status) { t.wait(); } _push_dense_status.resize(0); } if (tmp_push_dense_wait_times == -1) { _push_dense_status.resize(0); } if (_push_sparse_status.size() >= push_sparse_wait_times) { for (auto& t : _push_sparse_status) { t.wait(); } _push_sparse_status.resize(0); } if (tmp_push_sparse_wait_times == -1) { _push_sparse_status.resize(0); } for (auto dense_table_id : _param_config->dense_table_id) { _pull_dense_thread->increase_thread_version(thread_id_, dense_table_id); } } void AsyncExecutorThreadWorker::PushDense(int table_id) { std::vector<paddle::ps::Region> regions; for (auto& t : _param_config->dense_gradient_variable_name[table_id]) { Variable* var = thread_scope_->FindVar(t); CHECK(var != nullptr) << "var[" << t << "] not found"; LoDTensor* tensor = var->GetMutable<LoDTensor>(); int count = tensor->numel(); float* g = tensor->data<float>(); paddle::ps::Region reg(g, count); regions.emplace_back(std::move(reg)); } auto status = _pslib_ptr->_worker_ptr->push_dense(regions.data(), regions.size(), table_id); _push_dense_status.push_back(std::move(status)); } void AsyncExecutorThreadWorker::PullSparse(int table_id) { auto& features = _features[table_id]; auto& feature_value = _feature_value[table_id]; auto fea_dim = _param_config->fea_dim; // slot id starts from 1 features.clear(); features.resize(0); features.reserve(MAX_FEASIGN_NUM); const std::vector<std::string>& feed_vec = thread_reader_->GetUseSlotAlias(); // slot_idx = 0 is label TODO for (auto slot_idx = 1u; slot_idx < feed_vec.size(); ++slot_idx) { Variable* var = thread_scope_->FindVar(feed_vec[slot_idx]); LoDTensor* tensor = var->GetMutable<LoDTensor>(); int64_t* ids = tensor->data<int64_t>(); int len = tensor->numel(); for (auto i = 0u; i < len; ++i) { // todo(colourful-tree): current trick - filter feasign=use_slot_mod( // bug: datafeed fill use_slot_mod for empty slot) if (ids[i] == 0u) { continue; } features.push_back(static_cast<uint64_t>(ids[i])); } } check_pull_push_memory(features, &feature_value, fea_dim); std::vector<float*> pull_feature_value; for (auto i = 0u; i < features.size(); ++i) { pull_feature_value.push_back(feature_value[i].data()); } auto status = _pslib_ptr->_worker_ptr->pull_sparse( pull_feature_value.data(), table_id, features.data(), features.size()); _pull_sparse_status.push_back(std::move(status)); auto& push_g = _feature_push_value[table_id]; check_pull_push_memory(features, &push_g, fea_dim); collect_feasign_info(table_id); } void AsyncExecutorThreadWorker::FillSparse(int table_id) { auto slot_dim = _param_config->slot_dim; auto fea_dim = _param_config->fea_dim; auto& features = _features[table_id]; auto& fea_value = _feature_value[table_id]; CHECK(features.size() > 0) << "feature size check failed"; auto fea_idx = 0u; std::vector<float> init_value(fea_dim); const std::vector<std::string>& feed_vec = thread_reader_->GetUseSlotAlias(); // slot_idx = 0 is label TODO for (auto slot_idx = 1u; slot_idx < feed_vec.size(); ++slot_idx) { Variable* var = thread_scope_->FindVar(feed_vec[slot_idx]); LoDTensor* tensor = var->GetMutable<LoDTensor>(); int64_t* ids = tensor->data<int64_t>(); int len = tensor->numel(); Variable* var_emb = thread_scope_->FindVar( _param_config->slot_input_vec[table_id][slot_idx - 1]); LoDTensor* tensor_emb = var_emb->GetMutable<LoDTensor>(); float* ptr = tensor_emb->mutable_data<float>({len, slot_dim}, platform::CPUPlace()); memset(ptr, 0, sizeof(float) * len * slot_dim); auto& tensor_lod = tensor->lod()[0]; LoD data_lod{tensor_lod}; tensor_emb->set_lod(data_lod); for (auto index = 0u; index < len; ++index) { if (ids[index] == 0u) { memcpy(ptr + slot_dim * index, init_value.data() + 2, sizeof(float) * slot_dim); continue; } memcpy(ptr + slot_dim * index, fea_value[fea_idx].data() + 2, sizeof(float) * slot_dim); fea_idx++; } } } void AsyncExecutorThreadWorker::PushSparse(int table_id) { auto slot_dim = _param_config->slot_dim; auto fea_dim = _param_config->fea_dim; auto& features = _features[table_id]; auto& push_g = _feature_push_value[table_id]; check_pull_push_memory(features, &push_g, fea_dim); CHECK(push_g.size() == features.size() + 1) << "push_g size:" << push_g.size() << " features size:" << features.size(); uint64_t fea_idx = 0u; auto& fea_info = _fea_info[table_id]; int offset = 2; const std::vector<std::string>& feed_vec = thread_reader_->GetUseSlotAlias(); // slot_idx = 0 is label for (auto slot_idx = 1u; slot_idx < feed_vec.size(); ++slot_idx) { if (_param_config->slot_alias_to_table.find(feed_vec[slot_idx]) == _param_config->slot_alias_to_table.end()) { LOG(ERROR) << "ERROR slot_idx:" << slot_idx << " name:" << feed_vec[slot_idx]; } else if (_param_config->slot_alias_to_table[feed_vec[slot_idx]] != table_id) { continue; } Variable* g_var = thread_scope_->FindVar( _param_config->gradient_var[table_id][slot_idx - 1]); CHECK(g_var != nullptr) << "var[" << _param_config->gradient_var[table_id][slot_idx - 1] << "] not found"; LoDTensor* g_tensor = g_var->GetMutable<LoDTensor>(); if (g_tensor == NULL) { LOG(ERROR) << "var[" << _param_config->gradient_var[table_id][slot_idx - 1] << "] not found"; exit(-1); } float* g = g_tensor->data<float>(); Variable* var = thread_scope_->FindVar(feed_vec[slot_idx]); CHECK(var != nullptr) << "var[" << feed_vec[slot_idx] << "] not found"; LoDTensor* tensor = var->GetMutable<LoDTensor>(); if (tensor == NULL) { LOG(ERROR) << "var[" << feed_vec[slot_idx] << "] not found"; exit(-1); } int len = tensor->numel(); CHECK(slot_dim * len == g_tensor->numel()) << "len:" << len << " g_numel:" << g_tensor->numel(); CHECK(len == tensor->numel()) << "len:" << len << "t_numel:" << tensor->numel(); int64_t* ids = tensor->data<int64_t>(); for (auto id_idx = 0u; id_idx < len; ++id_idx) { if (ids[id_idx] == 0) { g += slot_dim; continue; } memcpy(push_g[fea_idx].data() + offset, g, sizeof(float) * slot_dim); push_g[fea_idx][0] = 1.0f; CHECK(fea_idx < fea_info.size()) << "fea_idx:" << fea_idx << " size:" << fea_info.size(); push_g[fea_idx][1] = static_cast<float>(fea_info[fea_idx].label); g += slot_dim; fea_idx++; } } CHECK(fea_idx == features.size()) << "fea_idx:" << fea_idx << " features size:" << features.size(); CHECK_GT(features.size(), 0); std::vector<float*> push_g_vec; for (auto i = 0u; i < features.size(); ++i) { push_g_vec.push_back(push_g[i].data()); } auto status = _pslib_ptr->_worker_ptr->push_sparse( table_id, features.data(), (const float**)push_g_vec.data(), features.size()); _push_sparse_status.push_back(std::move(status)); } void AsyncExecutorThreadWorker::collect_feasign_info(int table_id) { auto& fea_info = _fea_info[table_id]; auto& feature = _features[table_id]; fea_info.resize(feature.size()); const std::vector<std::string>& feed_vec = thread_reader_->GetUseSlotAlias(); Variable* var = thread_scope_->FindVar(feed_vec[0]); LoDTensor* tensor = var->GetMutable<LoDTensor>(); int64_t* label = tensor->data<int64_t>(); int global_index = 0; for (auto slot_idx = 1u; slot_idx < feed_vec.size(); ++slot_idx) { Variable* var = thread_scope_->FindVar(feed_vec[slot_idx]); LoDTensor* tensor = var->GetMutable<LoDTensor>(); int64_t* ids = tensor->data<int64_t>(); int fea_idx = 0; for (auto ins_idx = 1u; ins_idx < tensor->lod()[0].size(); ++ins_idx) { for (; fea_idx < tensor->lod()[0][ins_idx]; ++fea_idx) { if (ids[fea_idx] == 0u) { continue; } FeasignInfo info{slot_idx, ins_idx, label[ins_idx - 1]}; fea_info[global_index++] = std::move(info); } } } CHECK(global_index == feature.size()) << "expect fea info size:" << feature.size() << " real:" << global_index; } void AsyncExecutorThreadWorker::check_pull_push_memory( const std::vector<uint64_t>& features, std::vector<std::vector<float>>* push_g, int dim) { push_g->resize(features.size() + 1); for (auto& t : *push_g) { t.resize(dim); } } void AsyncExecutorThreadWorker::check_pull_push_memory( const std::vector<uint64_t>& features, std::vector<float*>* push_g, int dim) { if (features.size() > push_g->size()) { push_g->reserve(features.size() + 1); auto size = features.size() - push_g->size() + 1; for (auto i = 0u; i < size; ++i) { float* ptr = new float[dim]; push_g->push_back(ptr); } } } #endif } // namespace framework } // end namespace paddle
31.729844
79
0.649534
[ "vector" ]
c6d06ad1d95ad91494e99b4db1d13713f6c99d3f
3,467
cpp
C++
framework/egl/egluConfigFilter.cpp
AdvantechRISC/apq8016_external_deqp
cb5a98dbe818223be8786a1792954da8aeb72225
[ "Apache-2.0" ]
2
2016-07-19T13:05:30.000Z
2016-07-19T13:05:32.000Z
framework/egl/egluConfigFilter.cpp
AdvantechRISC/apq8016_external_deqp
cb5a98dbe818223be8786a1792954da8aeb72225
[ "Apache-2.0" ]
null
null
null
framework/egl/egluConfigFilter.cpp
AdvantechRISC/apq8016_external_deqp
cb5a98dbe818223be8786a1792954da8aeb72225
[ "Apache-2.0" ]
null
null
null
/*------------------------------------------------------------------------- * drawElements Quality Program Tester Core * ---------------------------------------- * * Copyright 2014 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *//*! * \file * \brief EGL Config selection helper. *//*--------------------------------------------------------------------*/ #include "egluConfigFilter.hpp" #include "egluUtil.hpp" #include "egluConfigInfo.hpp" #include "eglwEnums.hpp" #include <algorithm> using std::vector; namespace eglu { using namespace eglw; CandidateConfig::CandidateConfig (const eglw::Library& egl, eglw::EGLDisplay display, eglw::EGLConfig config) : m_type(TYPE_EGL_OBJECT) { m_cfg.object.egl = &egl; m_cfg.object.display = display; m_cfg.object.config = config; } CandidateConfig::CandidateConfig (const ConfigInfo& configInfo) : m_type(TYPE_CONFIG_INFO) { m_cfg.configInfo = &configInfo; } int CandidateConfig::get (deUint32 attrib) const { if (m_type == TYPE_CONFIG_INFO) return m_cfg.configInfo->getAttribute(attrib); else return getConfigAttribInt(*m_cfg.object.egl, m_cfg.object.display, m_cfg.object.config, attrib); } int CandidateConfig::id (void) const { return get(EGL_CONFIG_ID); } int CandidateConfig::redSize (void) const { return get(EGL_RED_SIZE); } int CandidateConfig::greenSize (void) const { return get(EGL_GREEN_SIZE); } int CandidateConfig::blueSize (void) const { return get(EGL_BLUE_SIZE); } int CandidateConfig::alphaSize (void) const { return get(EGL_ALPHA_SIZE); } int CandidateConfig::depthSize (void) const { return get(EGL_DEPTH_SIZE); } int CandidateConfig::stencilSize (void) const { return get(EGL_STENCIL_SIZE); } int CandidateConfig::samples (void) const { return get(EGL_SAMPLES); } deUint32 CandidateConfig::renderableType (void) const { return (deUint32)get(EGL_RENDERABLE_TYPE); } deUint32 CandidateConfig::surfaceType (void) const { return (deUint32)get(EGL_SURFACE_TYPE); } FilterList& FilterList::operator<< (ConfigFilter filter) { m_rules.push_back(filter); return *this; } FilterList& FilterList::operator<< (const FilterList& other) { size_t oldEnd = m_rules.size(); m_rules.resize(m_rules.size()+other.m_rules.size()); std::copy(other.m_rules.begin(), other.m_rules.end(), m_rules.begin()+oldEnd); return *this; } bool FilterList::match (const Library& egl, EGLDisplay display, EGLConfig config) const { return match(CandidateConfig(egl, display, config)); } bool FilterList::match (const ConfigInfo& configInfo) const { return match(CandidateConfig(configInfo)); } bool FilterList::match (const CandidateConfig& candidate) const { for (vector<ConfigFilter>::const_iterator filterIter = m_rules.begin(); filterIter != m_rules.end(); filterIter++) { ConfigFilter filter = *filterIter; if (!filter(candidate)) return false; } return true; } } // eglu
31.234234
115
0.696568
[ "object", "vector" ]
c6d16c9de35afb60b900f30a30952e8d37e8e817
7,124
cpp
C++
src/pairwise/0_GEN/Cmdline.cpp
JaneliaSciComp/TileAlignment
64f6732445f0c965122c143c8ca285428a371dc8
[ "Unlicense" ]
2
2018-07-02T17:20:40.000Z
2019-04-10T15:03:26.000Z
src/pairwise/0_GEN/Cmdline.cpp
JaneliaSciComp/TileAlignment
64f6732445f0c965122c143c8ca285428a371dc8
[ "Unlicense" ]
null
null
null
src/pairwise/0_GEN/Cmdline.cpp
JaneliaSciComp/TileAlignment
64f6732445f0c965122c143c8ca285428a371dc8
[ "Unlicense" ]
null
null
null
#include "Cmdline.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include <curl/curl.h> #include <sstream> #include <iostream> /* --------------------------------------------------------------- */ /* IsArg --------------------------------------------------------- */ /* --------------------------------------------------------------- */ // Return true if matched command line parameter. // // Example usage: // // for( int i = 1; i < argc; ++i ) { // if( argv[i][0] != '-' ) // noa.push_back( argv[i] ); // else if( IsArg( "-nf", argv[i] ) ) // NoFolds = true; // } // bool IsArg( const char *pat, const char *argv ) { return !strcmp( argv, pat ); } /* --------------------------------------------------------------- */ /* GetArg -------------------------------------------------------- */ /* --------------------------------------------------------------- */ // Read argument from command line. // // Example usage: // // for( int i = 1; i < argc; ++i ) { // if( argv[i][0] != '-' ) // noa.push_back( argv[i] ); // else if( GetArg( &ApproxScale, "-SCALE=%lf", argv[i] ) ) // ; // else if( GetArg( &Order, "-ORDER=%d", argv[i] ) ) // ; // } // bool GetArg( void *v, const char *pat, const char *argv ) { return 1 == sscanf( argv, pat, v ); } /* --------------------------------------------------------------- */ /* GetArgStr -------------------------------------------------------- */ /* --------------------------------------------------------------- */ // Point at string argument on command line. // // Example usage: // // char *dirptr; // // for( int i = 1; i < argc; ++i ) { // if( argv[i][0] != '-' ) // noa.push_back( argv[i] ); // else if( GetArgStr( dirptr, "-d=", argv[i] ) ) // ; // } // bool GetArgStr( const char* &s, const char *pat, char *argv ) { int len = strlen( pat ); bool ok = false; if( !strncmp( argv, pat, len ) ) { s = argv + len; ok = true; } return ok; } /* --------------------------------------------------------------- */ /* GetArgList ---------------------------------------------------- */ /* --------------------------------------------------------------- */ // Read integer argument list from command line. // // Example usage: ... -List=2,5,7 ... // // vector<int> I; // // for( int i = 1; i < argc; ++i ) { // if( argv[i][0] != '-' ) // noa.push_back( argv[i] ); // else if( GetArgList( I, "-List=", argv[i] ) ) // ; // } // bool GetArgList( vector<int> &v, const char *pat, char *argv ) { int len = strlen( pat ); bool ok = false; if( !strncmp( argv, pat, len ) ) { char *s = strtok( argv + len, ":;, " ); v.clear(); while( s ) { v.push_back( atoi( s ) ); s = strtok( NULL, ":;, " ); } ok = true; } return ok; } // Read double argument list from command line. // // Example usage: ... -List=2.7,5,1.8e7 ... // // vector<double> D; // // for( int i = 1; i < argc; ++i ) { // if( argv[i][0] != '-' ) // noa.push_back( argv[i] ); // else if( GetArgList( D, "-List=", argv[i] ) ) // ; // } // bool GetArgList( vector<double> &v, const char *pat, char *argv ) { int len = strlen( pat ); bool ok = false; if( strstr(argv, "http:") == NULL && !strncmp( argv, pat, len ) ) { char *s = strtok( argv + len, ":;, " ); v.clear(); while( s ) { v.push_back( atof( s ) ); s = strtok( NULL, ":;, " ); } ok = true; } return ok; } void Tokenize(const string& str, vector<string>& tokens, const string& delimiters = "\n") { // Skip delimiters at beginning. string::size_type lastPos = str.find_first_not_of(delimiters, 0); // Find first "non-delimiter". string::size_type pos = str.find_first_of(delimiters, lastPos); while (string::npos != pos || string::npos != lastPos) { // Found a token, add it to the vector. tokens.push_back(str.substr(lastPos, pos - lastPos)); // Skip delimiters. Note the "not_of" lastPos = str.find_first_not_of(delimiters, pos); // Find next "non-delimiter" pos = str.find_first_of(delimiters, lastPos); } } static size_t WriteCallback(void *contents, size_t size, size_t nmemb, void *userp) { ((std::string*)userp)->append((char*)contents, size * nmemb); return size * nmemb; } bool GetArgListFromURL( vector<double> &v, const char *pat, char *argv ) { int len = strlen( pat ); bool ok = false; if ( strstr(argv, "http:") != NULL && !strncmp( argv, pat, len ) ) { char *url = argv + len; static std::string readBuffer; if (strstr(url, "http:") == NULL) return false; CURL *easy_handle; CURLcode res; easy_handle = curl_easy_init(); // curl_easy_setopt(easy_handle, CURLOPT_VERBOSE, 1L); curl_easy_setopt(easy_handle, CURLOPT_URL, url); readBuffer.clear(); curl_easy_setopt(easy_handle, CURLOPT_WRITEFUNCTION, WriteCallback); curl_easy_setopt(easy_handle, CURLOPT_WRITEDATA, &readBuffer); res = curl_easy_perform(easy_handle); curl_easy_cleanup(easy_handle); vector<string> tokens; int read_images_from_URLs = 0; double coeffs[] = {0., 0., 0., 0., 0, 0.}; Tokenize(std::string(readBuffer), tokens, "\n"); for (int i=0; i<tokens.size(); i++) { vector<string> tokens2; Tokenize(tokens[i], tokens2, " "); if ( tokens2[0].find("imageRow") != std::string::npos ) { const char *my_str = tokens2[2].c_str(); char *pEnd; double value = strtod(my_str, &pEnd); coeffs[3] = value; } if ( tokens2[0].find("imageCol") != std::string::npos ) { const char *my_str = tokens2[2].c_str(); char *pEnd; double value = strtod(my_str, &pEnd); coeffs[0] = value; } if ( tokens2[0].find("minX") != std::string::npos ) { const char *my_str = tokens2[2].c_str(); char *pEnd; double value = strtod(my_str, &pEnd); coeffs[1] = value; } if ( tokens2[0].find("minY") != std::string::npos ) { const char *my_str = tokens2[2].c_str(); char *pEnd; double value = strtod(my_str, &pEnd); coeffs[4] = value; } if ( tokens2[0].find("stageX") != std::string::npos ) { const char *my_str = tokens2[2].c_str(); char *pEnd; double value = strtod(my_str, &pEnd); coeffs[2] = value; } if ( tokens2[0].find("stageY") != std::string::npos ) { const char *my_str = tokens2[2].c_str(); char *pEnd; double value = strtod(my_str, &pEnd); coeffs[5] = value; } } v.assign (coeffs,coeffs+6); readBuffer.clear(); ok = true; } return ok; }
25.905455
83
0.459714
[ "vector" ]
c6d33fe6ce5b01bca5372bba3c7c683094165a0e
3,691
cpp
C++
Samples/SkinnedMesh/main.cpp
maz-1/Ogre_glTF
71dd9e67ecdd6704634e08ba14d35f5335c4d8b4
[ "MIT" ]
null
null
null
Samples/SkinnedMesh/main.cpp
maz-1/Ogre_glTF
71dd9e67ecdd6704634e08ba14d35f5335c4d8b4
[ "MIT" ]
null
null
null
Samples/SkinnedMesh/main.cpp
maz-1/Ogre_glTF
71dd9e67ecdd6704634e08ba14d35f5335c4d8b4
[ "MIT" ]
null
null
null
#include "SamplesCommon.h" Ogre::CompositorWorkspace* SetupCompositor(Ogre::Root* root, Ogre::Window* const window, Ogre::SceneManager* smgr, Ogre::Camera* camera) { //Setup rendering pipeline auto compositor = root->getCompositorManager2(); const char workspaceName[] = "workspace0"; compositor->createBasicWorkspaceDef(workspaceName, Ogre::ColourValue { 0.2f, 0.3f, 0.4f }); auto workspace = compositor->addWorkspace(smgr, window->getTexture(), camera, workspaceName, true); return workspace; } int main() { #ifdef Ogre_glTF_STATIC // Must instantiate before Root so that it'll be destroyed afterwards. // Otherwise we get a crash on Ogre::Root::shutdownPlugins() #if __linux__ auto glPlugin = std::make_unique<Ogre::GL3PlusPlugin>(); #endif #endif //Init Ogre auto root = std::make_unique<Ogre::Root>(); Ogre::LogManager::getSingleton().setLogDetail(Ogre::LoggingLevel::LL_BOREME); /* #ifdef Ogre_glTF_STATIC #if __linux__ root->installPlugin(glPlugin.get()); #endif #else root->loadPlugin(GL_RENDER_PLUGIN); #ifdef _WIN32 root->loadPlugin(D3D11_RENDER_PLUGIN); #endif #endif */ if(!root->showConfigDialog()) return -1; Ogre::Window* window = root->initialise(true, "Gltf loader sample"); auto smgr = root->createSceneManager(Ogre::ST_GENERIC, 2); smgr->setForward3D(true, 4, 4, 5, 96, 3, 200); auto camera = smgr->createCamera("cam"); camera->setNearClipDistance(0.001f); camera->setFarClipDistance(100); camera->setAutoAspectRatio(true); camera->setPosition(2, 2, 2); camera->lookAt(0, 1, 0); //Load workspace and hlms auto workspace = SetupCompositor(root.get(), window, smgr, camera); DeclareHlmsLibrary("../Data"); Ogre::ResourceGroupManager::getSingleton().addResourceLocation("../../Media/gltfFiles.zip", "Zip"); Ogre::ResourceGroupManager::getSingleton().initialiseAllResourceGroups(true); auto gltf = std::make_unique<Ogre_glTF::glTFLoader>(); Ogre::SceneNode* objectNode = nullptr; try { auto adapter = gltf->loadGlbResource("CesiumMan.glb"); objectNode = adapter.getFirstSceneNode(smgr); } catch(std::exception& e) { Ogre::LogManager::getSingleton().logMessage(e.what()); return -1; } //Add light auto light = smgr->createLight(); light->setType(Ogre::Light::LightTypes::LT_POINT); light->setPowerScale(5); auto lightNode = smgr->getRootSceneNode()->createChildSceneNode(); lightNode->attachObject(light); lightNode->setPosition(1, 1, 1); //Setup animation and update it over time Ogre::SkeletonAnimation* animation = nullptr; // Find a node that contains an item that contains an skeleton auto childIt = objectNode->getChildIterator(); while(childIt.hasMoreElements()) { auto sceneNode = static_cast<Ogre::SceneNode*>(childIt.getNext()); if(sceneNode->numAttachedObjects() > 0) { auto itemIt = sceneNode->getAttachedObjectIterator(); while(itemIt.hasMoreElements()) { auto item = static_cast<Ogre::Item*>(itemIt.getNext()); auto skeleton = item->getSkeletonInstance(); if(skeleton) { const auto animationName = (skeleton->getAnimations().front().getName()); animation = item->getSkeletonInstance()->getAnimation(animationName); animation->setEnabled(true); animation->setLoop(true); break; } } } } auto timer = root->getTimer(); auto now = timer->getMilliseconds(); auto last = now; auto duration = now - last; //Update while(!window->isClosed()) { //Add time to animation now = timer->getMilliseconds(); duration = (now - last); animation->addTime(Ogre::Real(duration) / 1000.0f); last = now; //Render root->renderOneFrame(); Ogre::WindowEventUtilities::messagePump(); } return 0; }
27.962121
136
0.712273
[ "render" ]
c6d532aac5f41cf14a00c4423fe0fb6be6c9bfe6
4,016
cc
C++
src/kk-block.cc
hailongz/kk-surface
d87cd8f26682f7c96dc4becc6e6f705d60e8941a
[ "MIT" ]
null
null
null
src/kk-block.cc
hailongz/kk-surface
d87cd8f26682f7c96dc4becc6e6f705d60e8941a
[ "MIT" ]
null
null
null
src/kk-block.cc
hailongz/kk-surface
d87cd8f26682f7c96dc4becc6e6f705d60e8941a
[ "MIT" ]
null
null
null
// // kk-block.cpp // app // // Created by hailong11 on 2018/7/30. // Copyright © 2018年 kkmofang.cn. All rights reserved. // #include "kk-config.h" #include "kk-block.h" namespace kk { Block::Block(BlockType type,kk::Object * object):_type(type),_object(object),_data(nullptr),_size(0),_dealloc(nullptr) { if(type == BlockTypeRetain) { if(object) { object->retain(); } } else if(type == BlockTypeWeak) { if(object) { object->weak(&_object); } } else { assert(0); } } Block::Block(void * data,size_t size):_type(BlockTypeCopy),_object(nullptr),_size(0),_dealloc(nullptr) { _data = malloc(size); memcpy(_data, data, size); } Block::Block(void * ptr,BlockPtrDeallocFunc dealloc):_type(BlockTypePtr),_object(nullptr),_size(0),_data(ptr),_dealloc(dealloc) { } Block::~Block() { if(_type == BlockTypeRetain) { if(_object) { _object->release(); } } else if(_type == BlockTypeWeak) { if(_object) { _object->unWeak(&_object); } } else if(_type == BlockTypeCopy){ if(_data) { free(_data); } } else if(_type == BlockTypePtr) { if(_dealloc) { (*_dealloc)(_data); } } } BlockType Block::type() { return _type; } void * Block::ptr() { return _data; } void * Block::data(size_t * n) { if(n) { *n = _size; } return _data; } kk::Object * Block::object() { return _object; } BlockContext::BlockContext() { } BlockContext::~BlockContext() { std::map<std::string,Block *>::iterator i = _blocks.begin(); while(i != _blocks.end()) { i->second->release(); i ++; } } void BlockContext::add(kk::CString name,Block * block) { std::map<std::string,Block *>::iterator i = _blocks.find(name); block->retain(); if(i != _blocks.end()) { i->second->release(); } _blocks[name] = block; } void BlockContext::add(kk::CString name,BlockType type,kk::Object * object) { add(name, new Block(type,object)); } void BlockContext::add(kk::CString name,void * data,size_t size) { add(name, new Block(data,size)); } void BlockContext::add(kk::CString name,void * ptr,BlockPtrDeallocFunc dealloc) { add(name, new Block(ptr,dealloc)); } kk::Object * BlockContext::object(kk::CString name) { std::map<std::string,Block *>::iterator i = _blocks.find(name); if(i != _blocks.end()) { return i->second->object(); } return nullptr; } void * BlockContext::data(kk::CString name,size_t * n) { std::map<std::string,Block *>::iterator i = _blocks.find(name); if(i != _blocks.end()) { return i->second->data(n); } return nullptr; } void * BlockContext::ptr(kk::CString name) { std::map<std::string,Block *>::iterator i = _blocks.find(name); if(i != _blocks.end()) { return i->second->ptr(); } return nullptr; } void * BlockContext::get(kk::CString name) { std::map<std::string,Block *>::iterator i = _blocks.find(name); if(i != _blocks.end()) { Block * b = i->second; switch (b->type()) { case BlockTypePtr: return b->ptr(); case BlockTypeCopy: return b->data(nullptr); default: return b->object(); } return nullptr; } return nullptr; } }
26.077922
133
0.486056
[ "object" ]
c6e0e0fc3267d3c39898ff0c217ac4677f5b8c83
10,608
cpp
C++
Sources/MouCaLab/source/MouCaLab.cpp
Rominitch/MouCaLab
d8c24de479b1bc11509df8456e0071d394fbeab9
[ "Unlicense" ]
null
null
null
Sources/MouCaLab/source/MouCaLab.cpp
Rominitch/MouCaLab
d8c24de479b1bc11509df8456e0071d394fbeab9
[ "Unlicense" ]
null
null
null
Sources/MouCaLab/source/MouCaLab.cpp
Rominitch/MouCaLab
d8c24de479b1bc11509df8456e0071d394fbeab9
[ "Unlicense" ]
null
null
null
/// https://github.com/Rominitch/MouCaLab /// \author Rominitch /// \license No license #include "Dependencies.h" #include "include/MouCaLab.h" #include <LibGLFW/include/GLFWWindow.h> #include <LibVulkan/include/VKCommandBuffer.h> #include <LibVulkan/include/VKContextWindow.h> #include <LibRT/include/RTImage.h> #include <LibRT/include/RTRenderDialog.h> MouCaLabTest::MouCaLabTest() { _core.getResourceManager().addResourceFolder(MouCaEnvironment::getWorkingPath(), MouCaCore::ResourceManager::Executable); _core.getResourceManager().addResourceFolder(MouCaEnvironment::getWorkingPath() / ".." / ".." / "MouCaLab" / "UnitTests" / "GLSL", MouCaCore::ResourceManager::ShadersSource); _core.getResourceManager().addResourceFolder(MouCaEnvironment::getWorkingPath() / ".." / ".." / "MouCaLab" / "UnitTests" / "Renderer", MouCaCore::ResourceManager::Renderer); _core.getResourceManager().addResourceFolder(MouCaEnvironment::getInputPath() / "Configuration", MouCaCore::ResourceManager::Configuration); _core.getResourceManager().addResourceFolder(MouCaEnvironment::getInputPath() / "fonts", MouCaCore::ResourceManager::Fonts); _core.getResourceManager().addResourceFolder(MouCaEnvironment::getInputPath() / "mesh", MouCaCore::ResourceManager::Meshes); _core.getResourceManager().addResourceFolder(MouCaEnvironment::getInputPath() / "textures", MouCaCore::ResourceManager::Textures); _core.getResourceManager().addResourceFolder(MouCaEnvironment::getInputPath() / ".." / "SpirV", MouCaCore::ResourceManager::Shaders); _core.getResourceManager().addResourceFolder(MouCaEnvironment::getInputPath() / "references", MouCaCore::ResourceManager::References); } void MouCaLabTest::SetUp() { _core.getLoaderManager().initialize(); _graphic.initialize(); } void MouCaLabTest::TearDown() { _graphic.release(); _core.getLoaderManager().release(); } void MouCaLabTest::configureEventManager() { _eventManager = std::make_shared<EventManager3D>(); } void MouCaLabTest::releaseEventManager() { _eventManager.reset(); } void MouCaLabTest::loadEngine(MouCaGraphic::VulkanManager& manager, const Core::String& fileName) { // Build path Core::Path pathFile = _core.getResourceManager().getResourceFolder(MouCaCore::ResourceManager::Renderer) / fileName; // Read resource XML::ParserSPtr xmlFile = _core.getResourceManager().openXML(pathFile); xmlFile->openXMLFile(); ASSERT_TRUE(xmlFile->isLoaded()) << "Impossible to read XML"; // Let go !! MouCaGraphic::Engine3DXMLLoader loader(manager); MouCaGraphic::Engine3DXMLLoader::ContextLoading context(_graphic, *xmlFile, _core.getResourceManager()); ASSERT_NO_THROW(loader.load(context)); // Release resource (no needed anymore) _core.getResourceManager().releaseResource(std::move(xmlFile)); } void MouCaLabTest::loadEngine(MouCaGraphic::Engine3DXMLLoader& loader, const Core::String& fileName) { // Build path Core::Path pathFile = _core.getResourceManager().getResourceFolder(MouCaCore::ResourceManager::Renderer) / fileName; // Read resource XML::ParserSPtr xmlFile; ASSERT_NO_THROW(xmlFile = _core.getResourceManager().openXML(pathFile)); ASSERT_NO_THROW(xmlFile->openXMLFile()); ASSERT_TRUE(xmlFile->isLoaded()) << u8"Impossible to read XML"; // Let go !! MouCaGraphic::Engine3DXMLLoader::ContextLoading context(_graphic, *xmlFile, _core.getResourceManager()); try { loader.load(context); // Release resource (no needed anymore) _core.getResourceManager().releaseResource(std::move(xmlFile)); } catch (const Core::Exception& exception) { // Merge all messages Core::String message; for (size_t id = 0; id < exception.getNbErrors(); ++id) { const auto& error = exception.read(id); message += error.getLibraryLabel() + u8" " + error.getErrorLabel() + u8":\n" + _core.getExceptionManager().getError(error) + u8"\n\n"; } // Release resource (no needed anymore) _core.getResourceManager().releaseResource(std::move(xmlFile)); FAIL() << u8"XML loading error:\n" << message << u8"\nXML file: " << pathFile; } catch (...) { // Release resource (no needed anymore) _core.getResourceManager().releaseResource(std::move(xmlFile)); FAIL() << u8"XML loading error - Unknown error - XML file: " << pathFile; } } void MouCaLabTest::mainLoop(MouCaGraphic::VulkanManager& manager, const Core::String& title, const std::function<void(const double timer)>& afterRender) { // Enable tracking enableFileTracking(manager); // Execute draw into another thread uint32_t lastFPS = 0; // Frame counter to display fps uint32_t frameCounter = 0; std::chrono::time_point<std::chrono::high_resolution_clock> lastTimestamp; // Force to show dialog { manager.getSurfaces().at(0)->_linkWindow.lock()->setVisibility(true); } double timer = 0.0; // Execute main event loop while (_graphic.getRTPlatform().isWindowsActive()) { const auto tStart = std::chrono::high_resolution_clock::now(); // Draw Frame { manager.execute(0, 0, false); } // Show FPS frameCounter++; const auto tEnd = std::chrono::high_resolution_clock::now(); const auto tDiff = std::chrono::duration<double, std::milli>(tEnd - tStart).count(); timer += tDiff / 1000.0; afterRender(timer); // Avoid to change FPS quickly (bad effect on window reactivity) const double fpsTimer = std::chrono::duration<double, std::milli>(tEnd - lastTimestamp).count(); if (fpsTimer > 1000.0) { lastFPS = static_cast<uint32_t>((double)frameCounter * (1000.0 / fpsTimer)); frameCounter = 0; lastTimestamp = tEnd; // Use FPS on Dialog title (can be dangerous if too quick) auto window = manager.getSurfaces().at(0)->_linkWindow.lock(); if (window->getStateSize() == RT::Window::Normal) { std::stringstream ss; ss << title << lastFPS << u8" FPS"; window->setWindowTitle(ss.str()); } } // Pool now _graphic.getRTPlatform().pollEvents(); } // Enable tracking disableFileTracking(manager); } void MouCaLabTest::takeScreenshot(MouCaGraphic::VulkanManager& manager, const Core::Path& imageFile, const size_t nbMaxDefectPixels, const double maxDistance4D) { // Make screenshot const Core::Path path = MouCaEnvironment::getOutputPath() / imageFile; RT::ImageImportSPtr diskImage = _core.getResourceManager().createImage(path); ASSERT_NO_THROW(manager.takeScreenshot(path, diskImage, 0)); auto& resourceManager = _core.getResourceManager(); // Read reference (first time top because don't exist) const Core::Path reference = resourceManager.getResourceFolder(MouCaCore::ResourceManager::References) / imageFile; EXPECT_TRUE(std::filesystem::exists(reference)) << "Missing: " << reference; // DEV Issue: no reference existing ! auto refImage = resourceManager.openImage(reference); { auto& loaderManager = _core.getLoaderManager(); MouCaCore::LoadingItems loadingItems = { MouCaCore::LoadingItem(refImage, MouCaCore::LoadingItem::Direct), }; loaderManager.loadResources(loadingItems); } // Compare images size_t nbDefect; double maxFoundDistance; const bool compare = diskImage->getImage().lock()->compare(*refImage->getImage().lock(), nbMaxDefectPixels, maxDistance4D, &nbDefect, &maxFoundDistance); if (!compare) // Have you update the reference ? Or bug ? { const std::filesystem::path sourceFile(MouCaEnvironment::getOutputPath() / imageFile); const std::filesystem::path targetParent(MouCaEnvironment::getOutputPath() / L".." / L".." / L".." / L"Report"); const std::filesystem::path targetFile(targetParent / imageFile); // Duplicate result into failure folder if (!std::filesystem::exists(targetParent)) ASSERT_NO_THROW(std::filesystem::create_directories(targetParent)); // Recursively create target directory if not existing. ASSERT_NO_THROW(std::filesystem::copy_file(sourceFile, targetFile, std::filesystem::copy_options::overwrite_existing)); EXPECT_TRUE(compare) << u8"Image comparison failed: " << imageFile << u8"\n" << u8"Defect pixel: " << nbDefect << " > " << nbMaxDefectPixels << u8"\n" << u8"With tolerance of " << maxDistance4D << u8"(max found: " << maxFoundDistance << u8")"; } _core.getResourceManager().releaseResource(std::move(diskImage)); _core.getResourceManager().releaseResource(std::move(refImage)); } void MouCaLabTest::enableFileTracking(MouCaGraphic::VulkanManager& manager) { auto& fileTracker = _core.getResourceManager().getTracker(); MOUCA_PRE_CONDITION(!fileTracker.signalFileChanged().isConnected(&manager)); fileTracker.signalFileChanged().connectMember(&manager, &MouCaGraphic::VulkanManager::afterShaderEdition); fileTracker.startTracking(); } void MouCaLabTest::disableFileTracking(MouCaGraphic::VulkanManager& manager) { auto& fileTracker = _core.getResourceManager().getTracker(); MOUCA_PRE_CONDITION(fileTracker.signalFileChanged().isConnected(&manager)); fileTracker.stopTracking(); fileTracker.signalFileChanged().disconnect(&manager); } void MouCaLabTest::clearDialog(MouCaGraphic::VulkanManager& manager) { // Clean allocate dialog bool empty = manager.getSurfaces().empty(); while (!empty) { auto& surface = *manager.getSurfaces().begin(); { GLFW::WindowWPtr windowWeak = std::dynamic_pointer_cast<GLFW::Window>(surface->_linkWindow.lock()); _graphic.getRTPlatform().releaseWindow(windowWeak); } empty = manager.getSurfaces().empty(); } } void MouCaLabTest::updateCommandBuffers(MouCaGraphic::Engine3DXMLLoader& loader, const VkCommandBufferResetFlags reset) { // Execute Command for(auto cmdBuffer : loader._commandBuffers) { cmdBuffer.second.lock()->execute(reset); } } void MouCaLabTest::updateCommandBuffersSurface(MouCaGraphic::Engine3DXMLLoader& loader, const VkCommandBufferResetFlags reset) { // Execute commands loader._surfaces[0].lock()->updateCommandBuffer(reset); }
38.857143
183
0.686652
[ "mesh" ]
c6e4f49311c268421ed44c09de010bc83880d684
1,159
cpp
C++
src/PlantArchitect/Curve.cpp
edisonlee0212/PlantArchitect
f01e48fb67291947407a45494178db982b9be0e3
[ "BSD-3-Clause" ]
1
2021-08-25T06:25:00.000Z
2021-08-25T06:25:00.000Z
src/PlantArchitect/Curve.cpp
edisonlee0212/PlantArchitect-dev
f01e48fb67291947407a45494178db982b9be0e3
[ "BSD-3-Clause" ]
null
null
null
src/PlantArchitect/Curve.cpp
edisonlee0212/PlantArchitect-dev
f01e48fb67291947407a45494178db982b9be0e3
[ "BSD-3-Clause" ]
1
2022-02-07T02:54:05.000Z
2022-02-07T02:54:05.000Z
#include <Curve.hpp> using namespace PlantArchitect; void PlantArchitect::Curve::GetUniformCurve(size_t pointAmount, std::vector<glm::vec3> &points) const { float step = 1.0f / (pointAmount - 1); for (size_t i = 0; i <= pointAmount; i++) { points.push_back(GetPoint(step * i)); } } BezierCurve::BezierCurve(glm::vec3 cp0, glm::vec3 cp1, glm::vec3 cp2, glm::vec3 cp3) : Curve(), m_p0(cp0), m_p1(cp1), m_p2(cp2), m_p3(cp3) { } glm::vec3 BezierCurve::GetPoint(float t) const { t = glm::clamp(t, 0.f, 1.f); return m_p0 * (1.0f - t) * (1.0f - t) * (1.0f - t) + m_p1 * 3.0f * t * (1.0f - t) * (1.0f - t) + m_p2 * 3.0f * t * t * (1.0f - t) + m_p3 * t * t * t; } glm::vec3 BezierCurve::GetAxis(float t) const { t = glm::clamp(t, 0.f, 1.f); float mt = 1.0f - t; return (m_p1 - m_p0) * 3.0f * mt * mt + 6.0f * t * mt * (m_p2 - m_p1) + 3.0f * t * t * (m_p3 - m_p2); } glm::vec3 BezierCurve::GetStartAxis() const { return glm::normalize(m_p1 - m_p0); } glm::vec3 BezierCurve::GetEndAxis() const { return glm::normalize(m_p3 - m_p2); }
28.268293
105
0.547023
[ "vector" ]
c6e5e50c76f5576ece3d9cb78595dcab3b7b55ff
5,787
hxx
C++
src/include/sk/win32/error.hxx
sikol/sk-async
fc8fb2dbfa119b8b8d68c203459b8ca676576076
[ "BSL-1.0" ]
3
2021-04-08T12:47:39.000Z
2021-09-25T11:43:41.000Z
src/include/sk/win32/error.hxx
sikol/sk-cio
fc8fb2dbfa119b8b8d68c203459b8ca676576076
[ "BSL-1.0" ]
null
null
null
src/include/sk/win32/error.hxx
sikol/sk-cio
fc8fb2dbfa119b8b8d68c203459b8ca676576076
[ "BSL-1.0" ]
null
null
null
/* * Copyright (c) 2019, 2020, 2021 SiKol Ltd. * * Boost Software License - Version 1.0 - August 17th, 2003 * * Permission is hereby granted, free of charge, to any person or organization * obtaining a copy of the software and accompanying documentation covered by * this license (the "Software") to use, reproduce, display, distribute, * execute, and transmit the Software, and to prepare derivative works of the * Software, and to permit third-parties to whom the Software is furnished to * do so, all subject to the following: * * The copyright notices in the Software and this entire statement, including * the above license grant, this restriction and the following disclaimer, * must be included in all copies of the Software, in whole or in part, and * all derivative works of the Software, unless such copies or derivative * works are solely in the form of machine-executable object code generated by * a source language processor. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT * SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE * FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ #ifndef SK_CIO_WIN32_ERROR_HXX_INCLUDED #define SK_CIO_WIN32_ERROR_HXX_INCLUDED #include <system_error> #include <sk/channel/error.hxx> #include <sk/win32/windows.hxx> /* * Error handling support for Win32. */ namespace sk::win32 { /* * Win32 error category - this corresponds to FORMAT_MESSAGE_FROM_SYSTEM. */ enum struct error : DWORD { success = ERROR_SUCCESS, // 0 }; } // namespace sk::win32 namespace std { template <> struct is_error_code_enum<sk::win32::error> : true_type { }; }; // namespace std namespace sk::win32 { namespace detail { struct win32_errc_category : std::error_category { auto name() const noexcept -> char const * { return "win32"; } auto message(int c) const -> std::string { LPSTR msgbuf; auto len = ::FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, nullptr, c, 0, reinterpret_cast<LPSTR>(&msgbuf), 0, nullptr); if (len == 0) return "[FormatMessageA() failed]"; // FormatMessage() sometimes puts newline character on the end // of the string. Why? Who knows. while (msgbuf[len - 1] == '\r' || msgbuf[len - 1] == '\n') len--; std::string ret(msgbuf, len); ::LocalFree(msgbuf); return ret; } }; } // namespace detail inline auto win32_errc_category() -> detail::win32_errc_category const & { static detail::win32_errc_category c; return c; } inline auto make_error_code(error e) -> std::error_code { switch (static_cast<DWORD>(e)) { case ERROR_HANDLE_EOF: return sk::error::end_of_file; default: return {static_cast<int>(e), win32_errc_category()}; } } inline auto make_win32_error(int e) -> std::error_code { return make_error_code(static_cast<error>(e)); } inline auto make_win32_error(DWORD e) -> std::error_code { return make_error_code(static_cast<error>(e)); } inline auto make_win32_error(LSTATUS e) -> std::error_code { return make_error_code(static_cast<error>(e)); } // Not safe to call across a coroutine suspend point, because the error // value is thread-specific. inline auto get_last_error() -> std::error_code { return make_win32_error(::GetLastError()); } inline auto get_last_winsock_error() -> std::error_code { return make_win32_error(::WSAGetLastError()); } // Convert a Win32 error into a std::generic_category error if // there's an appropriate conversion. This is used by the portable // I/O parts of the library so that the user only has to test for // a single error code. inline auto win32_to_generic_error(std::error_code ec) -> std::error_code { // If it's not a Win32 error to begin with, return it as-is. if (&ec.category() != &win32_errc_category()) return ec; switch (ec.value()) { case ERROR_HANDLE_EOF: return sk::error::end_of_file; case ERROR_FILE_NOT_FOUND: case ERROR_PATH_NOT_FOUND: return std::make_error_code(std::errc::no_such_file_or_directory); case ERROR_TOO_MANY_OPEN_FILES: return std::make_error_code( std::errc::too_many_files_open_in_system); case ERROR_ACCESS_DENIED: return std::make_error_code(std::errc::permission_denied); case ERROR_NOT_ENOUGH_MEMORY: case ERROR_OUTOFMEMORY: return std::make_error_code(std::errc::not_enough_memory); default: return ec; } } } // namespace sk::win32 #endif // SK_CIO_WIN32_ERROR_HXX_INCLUDED
32.15
78
0.607223
[ "object" ]
c6eac994730c1f9a1ae2a1f7b56d6c86aff019bd
128
cpp
C++
Ge/Model/Implementation/ModelLoader.cpp
DexterDreeeam/DxtSdk2021
2dd8807b4ebe1d65221095191eaa7938bc5e9e78
[ "MIT" ]
1
2021-11-18T03:57:54.000Z
2021-11-18T03:57:54.000Z
Ge/Model/Implementation/ModelLoader.cpp
DexterDreeeam/P9
2dd8807b4ebe1d65221095191eaa7938bc5e9e78
[ "MIT" ]
null
null
null
Ge/Model/Implementation/ModelLoader.cpp
DexterDreeeam/P9
2dd8807b4ebe1d65221095191eaa7938bc5e9e78
[ "MIT" ]
null
null
null
#include "../Interface.hpp" namespace ge { ref<model> model_loader::load(const string& path) { return ref<model>(); } }
9.846154
49
0.648438
[ "model" ]
c6ef714da82cea291d8b1d2f2367f7cbcd1df69b
34,315
cpp
C++
src/client_one.cpp
gautam1858/Parallel-Sharing-C-
2eec18c2cbc40019e6d4cdd15c3928650d1302a4
[ "MIT" ]
11
2020-07-05T05:52:50.000Z
2021-09-07T17:26:53.000Z
src/client_one.cpp
gautam1858/Parallel-Sharing-C-
2eec18c2cbc40019e6d4cdd15c3928650d1302a4
[ "MIT" ]
1
2020-07-06T04:14:18.000Z
2020-07-06T04:14:18.000Z
src/client_one.cpp
gautam1858/Parallel-Sharing-C-
2eec18c2cbc40019e6d4cdd15c3928650d1302a4
[ "MIT" ]
2
2020-07-05T18:41:56.000Z
2020-07-05T19:13:02.000Z
/* client_one.cpp file client Functions */ #include <cstdlib> #include <iostream> #include <cstdio> #include <unistd.h> #include <errno.h> #include <cstring> #include <climits> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <netdb.h> #include <sys/stat.h> #include <arpa/inet.h> #include <sys/wait.h> #include <signal.h> #include <fcntl.h> #include <ctime> #include <sys/epoll.h> #include <fstream> #include <errno.h> #include "../include/server.h" #include "../include/client.h" #include <iomanip> #include <cstring> #define BACKLOG 10 // how many pending connections queue will hold #define maxPeers 10 //Maximum number of peers allowed to be connected to server extern const char * server_port; //Listening port of the server #define default_server "timberlake.cse.buffalo.edu" //Assignmnet operator for class host_info host_info & host_info::operator = (const host_info b) { file_descriptor = b.file_descriptor; strcpy(hostname, b.hostname); strcpy(ipstr, b.ipstr); strcpy(port, b.port); return *this; } client_operations::client_operations() { peer_idx = 0; peer_list.resize(10); connected_list.resize(10); connected_list_idx = 0; } //Extracts and fills info about connected peer in connection_list void client_operations::add_connection_list(int file_desc, const char * port) { //Sock Addr struct sockaddr_storage addr; socklen_t len = sizeof addr; //Hostname char hostname[MAXMSGSIZE]; //Ip address char ipstr[INET6_ADDRSTRLEN]; //Service name char service[20]; //Fill addr with info //Used examples from beej.us guide on getpeername, getnameinfo functions getpeername(file_desc, (struct sockaddr * ) & addr, & len); if (addr.ss_family == AF_INET) { struct sockaddr_in * s = (struct sockaddr_in * ) & addr; inet_ntop(AF_INET, & s -> sin_addr, ipstr, sizeof ipstr); } else { // AF_INET6 struct sockaddr_in6 * s = (struct sockaddr_in6 * ) & addr; inet_ntop(AF_INET6, & s -> sin6_addr, ipstr, sizeof ipstr); } //Fill out the vector conncted_list getnameinfo((struct sockaddr * ) & addr, sizeof addr, hostname, sizeof hostname, service, sizeof service, 0); std::cout << "connected to " << hostname << std::endl; connected_list.at(connected_list_idx).hostname = new char[strlen(hostname)]; strcpy(connected_list.at(connected_list_idx).hostname, hostname); connected_list.at(connected_list_idx).port = new char[strlen(port)]; strcpy(connected_list.at(connected_list_idx).port, port); strcpy(connected_list.at(connected_list_idx).ipstr, ipstr); connected_list.at(connected_list_idx).file_descriptor = file_desc; connected_list.at(connected_list_idx).connection_on = false; connected_list.at(connected_list_idx).download_st_time = 0.0; connected_list_idx++; } //Sends download command to the given file_desc peer void client_operations::send_download_command(int file_desc, const char * send_cmd) { //set connection on with this peer to true set_connection_on(file_desc, true); //send the command to the peer int count = sendall(file_desc, (unsigned char * ) send_cmd, MAXMSGSIZE); if (count != 0) { perror("send"); } } //Remove the peer from connection list and fill out it's host name char * client_operations::remove_from_connected_list(int file_desc, char * host) { for (int i = 0; i < connected_list_idx; i++) { if (connected_list.at(i).file_descriptor == file_desc) { strcpy(host, connected_list.at(i).hostname); connected_list.at(i) = connected_list.at(--connected_list_idx); } } return (char * ) host; } //Set connection on to value val for the peer void client_operations::set_connection_on(int clientfd, bool val) { for (int i = 0; i < connected_list_idx; i++) { if (connected_list.at(i).file_descriptor == clientfd) { connected_list.at(i).connection_on = val; } } } //check if download is on with this peer bool client_operations::is_download_on(int clientfd) { for (int i = 0; i < connected_list_idx; i++) { if (connected_list.at(i).file_descriptor == clientfd) { return connected_list.at(i).connection_on; } } return false; } //check if connection exists with the peer to avoid duplicate connections bool client_operations::is_connection_present(const char * host, const char * port) { for (int i = 0; i < connected_list_idx; i++) { if (!strcmp(connected_list.at(i).hostname, host) && !strcmp(connected_list.at(i).port, port)) { return true; } } return false; } //Is given peer a valid peer to connect to checks against peer list received form the server bool client_operations::is_valid_peer(const char * host) { char temp_host[46] = "::ffff:"; strcat(temp_host, host); for (int i = 0; i < peer_idx; i++) { //for some reason I keep getting some garbage along with hostname for highgate.cse.buffalo.edu e.g. highgate.cse.buffalo.edu1 or !highgate.cse.buffalo.edu //so added this strstr check to see if hostname in peer_list is contained within hostname. char * str = strstr(peer_list.at(i).hostname, host); if ((!strcmp(peer_list.at(i).hostname, host)) || (!strcmp(peer_list.at(i).ipstr, host)) || (!strcmp(peer_list.at(i).ipstr, temp_host) || str)) { return true; } } return false; } //connect to host specified by host at port port //copied from http://beej.us/guide/bgnet/output/html/multipage/clientserver.html int client_operations::connect_to_port(const char * host, const char * port) { int sockfd, numbytes; char hostname[MAXMSGSIZE]; char service[20]; struct addrinfo hints, * servinfo, * p; int rv; int error; char s[INET6_ADDRSTRLEN]; memset( & hints, 0, sizeof hints); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; //Avoid duplicate connection if (is_connection_present(host, port)) { fprintf(stderr, "Connection is already present between peers"); return -1; } if ((rv = getaddrinfo(host, port, & hints, & servinfo)) != 0) { fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv)); return 2; } // loop through all the results and connect to the first we can //Usual connect call for (p = servinfo; p != NULL; p = p -> ai_next) { if ((sockfd = socket(p -> ai_family, p -> ai_socktype, p -> ai_protocol)) == -1) { perror("client: socket"); continue; } error = connect(sockfd, p -> ai_addr, p -> ai_addrlen); if (error == -1) { close(sockfd); perror("client: connect"); continue; } break; } if (p == NULL) { fprintf(stderr, "client: failed to connect\n"); return 2; } inet_ntop(p -> ai_family, get_in_addr((struct sockaddr * ) p -> ai_addr), s, sizeof s); printf("client: connecting to %s\n", s); //add socket to connected_list add_connection_list(sockfd, port); freeaddrinfo(servinfo); // all done with this structure return sockfd; } //client's version of list to requets function //Client overrides the server method due to small peculiarities of the client //again socket part is copied from beej.us void client_operations::listen_to_requests(int sfd) { //Epoll eventfd int eventfd; //epoll event handler to add events to struct epoll_event event; struct epoll_event * event_array = new epoll_event[10]; struct sockaddr_storage in_addr; struct sigaction sa; //listen if (listen(sfd, BACKLOG) == -1) { perror("listen"); exit(1); } sa.sa_handler = sigchld_handler; // reap all dead processes sigemptyset( & sa.sa_mask); sa.sa_flags = SA_RESTART; if (sigaction(SIGCHLD, & sa, NULL) == -1) { perror("sigaction"); exit(1); } //create epoll eventfd eventfd = epoll_create(maxPeers); if (eventfd == -1) { perror("epoll_create"); abort(); } //Listen to stdin events make_entry_to_epoll(0, eventfd); //listen to own socket make_entry_to_epoll(sfd, eventfd); printf("client: waiting for connections...\n"); wait_for_event(eventfd, event_array, sfd); delete event_array; close(sfd); } //Sends any download commands remaining for the given peer void client_operations::handle_rem_downloads(int clientfd) { set_connection_on(clientfd, false); while (!is_download_on(clientfd) && !(send_cmd_buffer.empty())) { send_download_command(clientfd, send_cmd_buffer.front().c_str()); send_cmd_buffer.erase(send_cmd_buffer.begin()); } } //Adds start time of download to connected list. void client_operations::add_st_time(int file_desc, double st_time) { for (int i = 0; i < connected_list_idx; i++) { if (connected_list.at(i).file_descriptor == file_desc) { connected_list.at(i).download_st_time = st_time; } } } //returns start time from the connected list double client_operations::st_time(int file_desc) { for (int i = 0; i < connected_list_idx; i++) { if (connected_list.at(i).file_descriptor == file_desc) { return connected_list.at(i).download_st_time; } } return 0.0; } //returns index of first occurrence of a char c in the str int client_operations::return_first_occr(const char * str, char c) { for (int i = 0; i < PACKET_SIZE; i++) { if (str[i] == c) { return i; } } return -1; } //puts the string into token until char c is encountered void client_operations::split_return(const char * str, char c, char * token) { int i = 0; int j = 0; while ((str[i] != c)) { *(token + j) = str[i++]; j++; } token[j] = '\0'; } //send the file over socket void client_operations::send_file_over_socket(int clientfd, const char * filename) { //cont of the bytes sent etc. from return values of fread, send etc. int count; //data buffer unsigned char data_buffer[PACKET_SIZE]; //count the total bytes sent int total = 0; //count of header length int header_count = 0; //file_size size_t file_size; struct stat filestatus; //http://www.cplusplus.com/forum/unices/3386/ stat(filename, & filestatus); file_size = filestatus.st_size; char file_head[initial_header_len] = "File"; //find time spent in upload struct timespec tstart = { 0, 0 }, tend = { 0, 0 }; //http://stackoverflow.com/questions/16275444/c-how-to-print-time-difference-in-accuracy-of-milliseconds-and-nanoseconds clock_gettime(CLOCK_MONOTONIC, & tstart); //File pointer open in binary mode. FILE * File = fopen(filename, "rb"); if (!File) { //If file is not present then let the other side know by sending file size=-1 perror("Error opening file"); //header to be sent to the receiver sprintf((char * ) data_buffer, "File %s %d \r", filename, -1); data_buffer[PACKET_SIZE - 1] = '\0'; count = sendall(clientfd, data_buffer, sizeof(data_buffer)); if (count != 0) { perror("send"); close(clientfd); } return; } fprintf(stderr, "\nSending file now...\n"); //while sending it is useful to make socket blocking as it will block until it is possible to send make_socket_blocking(clientfd); //First packet has header "File" while (total < filestatus.st_size) { //find length of header if (filestatus.st_size - (total) > PACKET_SIZE - header_count - 1 && total != 0) { // filestatus.st_size-total is the data remaining to be sent, // Remaining data > space in data packet, then this is an intermediate packet and not last packet. strcpy(file_head, "Pfil"); } else if (filestatus.st_size - (total) <= PACKET_SIZE - header_count - 1) { //this is the last packet let the receiver know strcpy(file_head, "Endf"); } //create file header appropriately sprintf((char * ) data_buffer, "%4s %s %d \r", file_head, filename, (int) file_size); header_count = strlen((char * ) data_buffer); //read in data in the buffer of quantity PACKET_SIZE-header_count-1, make space for \0 count = fread(data_buffer + header_count, 1, PACKET_SIZE - header_count - 1, File); total += count; data_buffer[count + header_count] = '\0'; //send the data count = sendall(clientfd, data_buffer, count + header_count + 1); if (count != 0) { perror("send"); close(clientfd); return; } } //find end time clock_gettime(CLOCK_MONOTONIC, & tend); //find time difference double time = ((double) tend.tv_sec + 1.0e-9 * tend.tv_nsec) - ((double) tstart.tv_sec + 1.0e-9 * tstart.tv_nsec); //find file size in bits file_size = 8 * filestatus.st_size; fprintf(stderr, "\nFile %s sent successfully...\n", filename); //speed in bps double speed = (double) file_size / time; if (speed < 1024) { //speed in bps fprintf(stderr, "\nThe file uploaded at rate of %.2fbits per second...\n", speed); } else if (speed < 1048000) { //speed in Kbps speed = (double) speed / 1024; fprintf(stderr, "\nThe file uploaded at rate of %.2fKbps...\n", speed); } else { //speed in Mbps speed = (double) speed / (1024 * 1024); fprintf(stderr, "\nThe file uploaded at rate of %.2fMbps...\n", speed); } fclose(File); make_socket_non_blocking(clientfd); } //Receive the file packet from given client. void client_operations::recv_and_write_file(int clientfd, unsigned char * rem_buf) { //size of the file int size; //count of the bytes received int count; //filename char filename[MAXMSGSIZE]; //file size retried from the packet header char file_size[MAXMSGSIZE]; //Buffer for the data unsigned char data_buf[PACKET_SIZE]; //File pointer FILE * File; //is it last packet for this file bool last_packet = false; //Find time taken for download struct timespec tstart = { 0, 0 }, tend = { 0, 0 }; //recieve packet from the client count = recv(clientfd, data_buf, PACKET_SIZE - initial_header_len, 0); data_buf[count - 1] = '\0'; //Puts filename from the header to filename split_return((char * )(data_buf), ' ', filename); //Puts file_size fromt the heade to file_size split_return((char * )(data_buf + strlen(filename) + 1), ' ', file_size); //convert char * size to int size size = strtoull(file_size, NULL, 0); if (!strcmp((char * ) rem_buf, "File")) { fprintf(stderr, "\nReceiving file now...\n"); //if rem_buf is File that means this is first packet for this file //Therefore open file in write mode thus overwriting previous contents. File = fopen(filename, "wb"); //Start the clock clock_gettime(CLOCK_MONOTONIC, & tstart); //http://stackoverflow.com/questions/16275444/c-how-to-print-time-difference-in-accuracy-of-milliseconds-and-nanoseconds add_st_time(clientfd, (double) tstart.tv_sec + 1.0e-9 * tstart.tv_nsec); //everything related to finding time difference I got from here^. } else if (!strcmp((char * ) rem_buf, "Pfil")) { //Otherwise the packet is any other packet than first packet thus file will be appended. File = fopen(filename, "ab"); } else if (!strcmp((char * ) rem_buf, "Endf")) { File = fopen(filename, "ab"); last_packet = true; } if (size == -1) { //If size is -1(it's part of the protocol) then file was not found fprintf(stderr, "\nFile %s not found at the peer\n", filename); fclose(File); //handle any remaining downloads. handle_rem_downloads(clientfd); return; } if (count > 0) { //if count > 0 then write content to the file fwrite(data_buf + (return_first_occr((char * ) data_buf, '\r') + 1), 1, count - 4 - strlen(filename) - strlen(file_size), File); } if (!last_packet) { //if this is not the last packet exit. fclose(File); return; } else { //reached here means file download is complete clock_gettime(CLOCK_MONOTONIC, & tend); double time = ((double) tend.tv_sec + 1.0e-9 * tend.tv_nsec) - (double) st_time(clientfd); //convert file size to bits size = 8 * size; fprintf(stderr, "\nFile %s received successfully...\n", filename); //find speed of transfer double speed = (double) size / time; if (speed < 1024) { //speed in bps fprintf(stderr, "\nThe file downloaded at rate of %.2fbits per second...\n", speed); } else if (speed < 1048000) { //speed in Kbps speed = (double) speed / 1024; fprintf(stderr, "\nThe file downloaded at rate of %.2fKbps...\n", speed); } else { //speed in Mbps speed = (double) speed / (1024 * 1024); fprintf(stderr, "\nThe file downloaded at rate of %.2fMbps...\n", speed); } fclose(File); //handle any remaining downloads handle_rem_downloads(clientfd); return; } } //Requests from peers processed in this function //some part is copied form http://beej.us/guide/bgnet/output/html/multipage/clientserver.html //and https://banu.com/blog/2/how-to-use-epoll-a-complete-example-in-c/ void client_operations::recv_requests_client(int clientfd) { //token from buf char split_token[MAXMSGSIZE]; int done = 0; ssize_t count; unsigned char buf[MAXMSGSIZE]; //token array used for holding part of token char token_arr[MAXMSGSIZE]; char * token = & token_arr[0]; //read first 5 charcters to determine which type of packet is this count = recv(clientfd, buf, 5, 0); buf[count - 1] = '\0'; if (count == -1) { /* If errno == EAGAIN, that means we have read all data. So go back to the main loop. */ if (errno != EAGAIN) { perror("read"); } } else if (count == 0) { /* End of file. The remote has closed the connection. */ //remove the clientfd from connected_list strcpy((char * ) buf, remove_from_connected_list(clientfd, (char * ) buf)); fprintf(stderr, "\n%s closed the connection.\n", buf); close(clientfd); } else { if (buf) { if (!strcmp((char * ) buf, "Peer")) { //peer list shared by the server char host_arr[MAXMSGSIZE]; char ipstr[MAXMSGSIZE]; char port[20]; char * host = & host_arr[0]; //receive remaining message count = recv(clientfd, buf, MAXMSGSIZE - 5, 0); //token contains whole info for a given peer strcpy(token, strtok((char * ) buf, "\n")); //host contains hostname of the peer host = strtok(token, "|"); //reset peer_idx to zero. peer_idx = 0; while (host != NULL) { //ip address strcpy(ipstr, strtok(NULL, "|")); strcpy(port, strtok(NULL, "|\n")); // put in peer_list all the info about the peer strcpy(peer_list.at(peer_idx).ipstr, ipstr); peer_list.at(peer_idx).port = new char[strlen(port)]; strcpy(peer_list.at(peer_idx).port, port); peer_list.at(peer_idx).hostname = new char[strlen(host)]; strcpy(peer_list.at(peer_idx).hostname, host); peer_list.at(peer_idx).file_descriptor = -1; peer_idx++; host = strtok(NULL, "|\n"); } } else if (!strcmp((char * ) buf, "File") || !strcmp((char * ) buf, "Pfil") || !strcmp((char * ) buf, "Endf")) { //File packet received from the peer recv_and_write_file(clientfd, buf); } else if (!strcmp((char * ) buf, "Send")) { //Send command means other peer asking this peer to send a certain file, send command may be triggered by download command on other peer count = recv(clientfd, buf, MAXMSGSIZE - 5, 0); //file name of the file strcpy(split_token, strtok((char * ) buf, "\n")); //send file to the peer send_file_over_socket(clientfd, split_token); } else { fprintf(stderr, "The server does not recognize %s command\n", token); } } } } //handle commands from the terminal void inline client_operations::recv_stdin_client(int eventfd) { //clientfd that may be will be retried in case of some commands int clientfd; //count returned by read etc. ssize_t count; //buf to receive data in char buf[MAXMSGSIZE]; //send cmd buffer char send_cmd[MAXMSGSIZE]; //capture first argument in this array char firstarg_arr[MAXMSGSIZE]; //capture second argument in this array char secondarg_arr[MAXMSGSIZE]; //using this pointer to point to the arrays in case strtok returns null. char * firstarg = firstarg_arr; char * secondarg = secondarg_arr; char token_arr[MAXMSGSIZE]; char * token = token_arr; errno = 0; count = read(0, buf, sizeof buf); if (count == -1) { /* If errno == EAGAIN, that means we have read all data. So go back to the main loop. */ if (errno != EAGAIN) { perror("read"); } } else { if (buf != NULL) { //if buf not null token = strtok(buf, " \r\n"); //if token not null if (token != NULL) { //convert to uppercase server_operations::toupper(token); firstarg = strtok(NULL, " \r\n"); secondarg = strtok(NULL, " \r\n"); if (!strcmp(token, "HELP")) { //help menu std::cout << "Command Help" << std::endl; std::cout << "Help" << std::setw(10) << "Displays this help" << std::endl; std::cout << "MYIP" << std::setw(10) << "Display the IP address of this process." << std::endl; std::cout << "MYPORT" << std::setw(10) << "MYPORT Display the port on which this process is listening for incoming connections." << std::endl; std::cout << "REGISTER <server IP> <port_no>" << std::setw(10) << "Register the client to the server at timberlake at port_no ." << std::endl; std::cout << "CONNECT <destination> <port no>" << std::setw(10) << "Connect to the destination at port_no ." << std::endl; std::cout << "LIST" << std::setw(10) << "LIST all the available peers of the connection" << std::endl; std::cout << "TERMINATE <connection id>" << std::setw(10) << "Terminate the connection " << std::endl; std::cout << "EXIT" << std::setw(10) << "Exit the process" << std::endl; std::cout << "UPLOAD <connection id> <file name>" << std::setw(10) << "Upload file file_name to peer" << std::endl; std::cout << "DOWNLOAD <connection id 1> <file1>" << std::setw(10) << "Download file file_name from peer" << std::endl; std::cout << "CREATOR" << std::setw(10) << "Display creator's name and relevant info." << std::endl; } else if (!strcmp(token, "REGISTER")) { //Register to server if (firstarg != NULL) { //Register to server at the port specified by firstarg //connect to server int server_sock = connect_to_port(default_server, firstarg); if (server_sock > 2) { strcpy(send_cmd, "REGISTER "); strcat(send_cmd, server_port); strcat(send_cmd, "\n"); //make socket non blocking make_socket_non_blocking(server_sock); make_entry_to_epoll(server_sock, eventfd); //send server request to register this peer count = sendall(server_sock, (unsigned char * ) send_cmd, sizeof send_cmd); if (count != 0) { perror("send"); } } } else { //error handling fprintf(stderr, "Invalid command; use help for command help\n"); } return; } else if (!strcmp(token, "MYPORT")) { //myport fprintf(stderr, "MY listening port is %s\n", server_port); } else if (!strcmp(token, "MYIP")) { //myip strcpy(buf, my_ip(buf)); if (strcmp(buf, "error")) { fprintf(stderr, "MY IP is %s\n", buf); } else { //error handling fprintf(stderr, "Error occurred while retrieving IP\n"); } return; } else if (!strcmp(token, "UPLOAD")) { //upload command if (firstarg != NULL && secondarg != NULL) { char * endptr; //convert firstarg to integer int connection_id = strtol(firstarg, & endptr, 10); //taken this from man page of strtol if ((errno == ERANGE && (connection_id == INT_MAX || connection_id == INT_MIN)) || (errno != 0 && connection_id == 0)) { perror("strtol"); } if (endptr == firstarg) { //error handling fprintf(stderr, "No digits were found\n"); fprintf(stderr, "Invalid command use help for command help\n"); } else { //make sure connection_id is valid if (connection_id <= connected_list_idx && connection_id != 1) { clientfd = connected_list.at(connection_id - 1).file_descriptor; } else { fprintf(stderr, "The connection id specified by you either does not exist or trying to download from server\n"); return; } //send file to the peer send_file_over_socket(clientfd, secondarg); } } else { //error handling fprintf(stderr, "Invalid command use help for command help\n"); } return; } else if (!strcmp(token, "DOWNLOAD")) { //download command char * filename; if (firstarg != NULL && secondarg != NULL) { redo_loop: char * endptr; //convert firstarg to integer int connection_id = strtol(firstarg, & endptr, 10); if ((errno == ERANGE && (connection_id == INT_MAX || connection_id == INT_MIN)) || (errno != 0 && connection_id == 0)) { perror("strtol"); } if (endptr == firstarg) { fprintf(stderr, "No digits were found\n"); fprintf(stderr, "Invalid command use help for command help\n"); } //get filename from secondarg filename = secondarg; if (connection_id <= connected_list_idx && connection_id != 1) { //send request for file strcpy(send_cmd, "Send "); strcat(send_cmd, filename); strcat(send_cmd, "\n"); //get the file desc. from the connection_id clientfd = connected_list.at(connection_id - 1).file_descriptor; if (!is_download_on(clientfd)) { //make sure no download with this peer is in progress send_download_command(clientfd, send_cmd); } else { //if download is in progress simply add the request to buffer and process later in recv_file function std::string str(send_cmd); send_cmd_buffer.push_back(str); } firstarg = strtok(NULL, " \r\n"); secondarg = strtok(NULL, " \r\n"); //see if any other download request is present if (firstarg != NULL && secondarg != NULL) { goto redo_loop; } } else { //error handling fprintf(stderr, "The connection id specified by you either does not exist or trying to download from server\n"); return; } } else { //error handling fprintf(stderr, "Invalid command use help for command help\n"); } return; } else if (!strcmp(token, "CONNECT")) { if (firstarg != NULL && secondarg != NULL) { //connect to peer if (connected_list_idx == 4) { //Max limit for peers reached std::cout << "\nReached limit of maximum connections terminate some connections first to add a new connection\n"; return; } if (is_valid_peer(firstarg)) { //make sure that peer is a valid peer //connect to peer clientfd = connect_to_port(firstarg, secondarg); if (clientfd <= 2) { return; } else { //make entry of the connection to clientfd make_entry_to_epoll(clientfd, eventfd); make_socket_non_blocking(clientfd); } } else { //error handling fprintf(stderr, "\nThe peer specified is not a valid peer \n"); } } else { //error handling fprintf(stderr, "Invalid command use help for command help\n"); } return; } else if (!strcmp(token, "TERMINATE")) { if (firstarg != NULL) { //termiante the connection with the peer char * endptr; //convert firstarg to integer used strtol as it handles error better than atoi() int connection_id = strtol(firstarg, & endptr, 10); if ((errno == ERANGE && (connection_id == INT_MAX || connection_id == INT_MIN)) || (errno != 0 && connection_id == 0)) { perror("strtol"); return; } if (endptr == firstarg) { fprintf(stderr, "No digits were found\n"); std::cout << "Invalid command use help for command help\n"; return; } if (connection_id <= connected_list_idx && connection_id != 1) { //if connection is valid and not server then termainte terminate_client(connection_id - 1); } else { //error handling fprintf(stderr, "Connection id entered is either not valid or you trying to terminate connection with server\n"); } } else { //error handling fprintf(stderr, "Invalid command use help for command help\n"); } return; } else if (!strcmp(token, "LIST")) { //print list of peers connected t the client std::cout << "\nConnected peers are:\n"; for (int i = 0; i < connected_list_idx; i++) { std::cout << i + 1 << "\t" << connected_list.at(i).hostname << "\t" << connected_list.at(i).ipstr << "\t\t" << connected_list.at(i).port << "\n"; } return; } else if (!strcmp(token, "EXIT")) { //exit fprintf(stderr, "The Client is exiting..\n"); exit(0); } else { //error handling fprintf(stderr, "Invalid command use help for command help\n"); } } } } } //terminate the client if terminate command is used void client_operations::terminate_client(int i) { close(connected_list.at(i).file_descriptor); connected_list.at(i) = connected_list.at(--connected_list_idx); fprintf(stderr, "Terminated client at connection id %d\n", i + 1); } //for the given peer find its port number from the peer_list, so that it can be displayed in LIST command. char * client_operations::return_port_from_peer_list(int peer_fd) { struct sockaddr_storage addr; socklen_t len = sizeof addr; char hostname[MAXMSGSIZE]; char ipstr[INET6_ADDRSTRLEN]; char service[20]; getpeername(peer_fd, (struct sockaddr * ) & addr, & len); if (addr.ss_family == AF_INET) { struct sockaddr_in * s = (struct sockaddr_in * ) & addr; inet_ntop(AF_INET, & s -> sin_addr, ipstr, sizeof ipstr); } else { // AF_INET6 struct sockaddr_in6 * s = (struct sockaddr_in6 * ) & addr; inet_ntop(AF_INET6, & s -> sin6_addr, ipstr, sizeof ipstr); } getnameinfo((struct sockaddr * ) & addr, sizeof addr, hostname, sizeof hostname, service, sizeof service, 0); for (int i = 0; i < peer_idx; i++) { //for some reason I keep getting some garbage along with hostname for highgate.cse.buffalo.edu e.g. highgate.cse.buffalo.edu1 or !highgate.cse.buffalo.edu //so added this strstr check to see if hostname in peer_list is contained within hostname. char * str = strstr(peer_list.at(i).hostname, hostname); if ((!strcmp(peer_list.at(i).hostname, hostname)) || str) { return peer_list.at(i).port; } } return NULL; } //wait for event //similar to server function void inline client_operations::wait_for_event(int eventfd, struct epoll_event * event_array, int sfd) { struct sockaddr_storage in_addr; char port_arr[20]; char * port = port_arr; while (1) { int n, i; int infd; n = epoll_wait(eventfd, event_array, maxPeers, -1); for (i = 0; i < n; i++) { if (event_array[i].events & EPOLLRDHUP) { //*********** char hostname[265]; strcpy(hostname, remove_from_connected_list(event_array[i].data.fd, hostname)); fprintf(stderr, "\nThe client %s closed connection", hostname); continue; } else if ((event_array[i].events & EPOLLERR) || (event_array[i].events & EPOLLHUP) || (!(event_array[i].events & EPOLLIN))) { /* An error has occured on this fd, or the socket is not ready for reading (why were we notified then?) */ fprintf(stderr, "epoll error\n"); close(event_array[i].data.fd); continue; } else if (sfd == event_array[i].data.fd) { /* We have a notification on the listening socket, which means one or more incoming connections. */ socklen_t in_len; in_len = sizeof in_addr; infd = accept(sfd, (struct sockaddr * ) & in_addr, & in_len); if (infd == -1) { perror("accept"); continue; } port = return_port_from_peer_list(infd); if (!port) { fprintf(stderr, "Invalid connection rejected\n"); close(infd); continue; } // add peer to connection_list add_connection_list(infd, port); //make entries make_socket_non_blocking(infd); make_entry_to_epoll(infd, eventfd); continue; } else if (event_array[i].data.fd == 0) { //handle stdin input recv_stdin_client(eventfd); } else { /* We have data on the fd waiting to be read.*/ //handle the data from peers and server. recv_requests_client(event_array[i].data.fd); } } } }
30.858813
166
0.615766
[ "vector" ]
c6f4ee589166e1fdeed412cca4d780c158d28770
2,163
hpp
C++
src/ackward/datetime/TZInfo.hpp
abingham/ackward
f1a45293de570f4b4429d9eaeb3f6c4da7d245bf
[ "MIT" ]
null
null
null
src/ackward/datetime/TZInfo.hpp
abingham/ackward
f1a45293de570f4b4429d9eaeb3f6c4da7d245bf
[ "MIT" ]
null
null
null
src/ackward/datetime/TZInfo.hpp
abingham/ackward
f1a45293de570f4b4429d9eaeb3f6c4da7d245bf
[ "MIT" ]
null
null
null
#ifndef INCLUDE_ACKWARD_DATETIME_TZINFO_HPP #define INCLUDE_ACKWARD_DATETIME_TZINFO_HPP #include <Python.h> #include <boost/shared_ptr.hpp> #include <boost/python/extract.hpp> #include <boost/python/make_function.hpp> #include <ackward/core/Object.hpp> #include <ackward/core/Util.hpp> #include <ackward/datetime/DateTime.hpp> #include <ackward/datetime/Module.hpp> #include <ackward/datetime/TimeDelta.hpp> using namespace boost::python; namespace ackward { namespace datetime { class DateTime; class TimeDelta; class TZInfo : private core::Object { public: TZInfo(boost::python::object); virtual TimeDelta dst(const DateTime&) const; virtual DateTime fromutc(const DateTime&) const; virtual std::wstring tzname() const; virtual TimeDelta utcoffset(const DateTime&) const; using Object::obj; }; template <class Impl> class TZInfo_ : public TZInfo { public: TZInfo_() : TZInfo ( module().attr("tzinfo")() ) { obj().attr("dst") = boost::python::make_function( TZInfo_<Impl>::dst_impl); obj().attr("fromutc") = boost::python::make_function( TZInfo_<Impl>::fromutc_impl); obj().attr("tzname") = boost::python::make_function( TZInfo_<Impl>::tzname_impl); obj().attr("utcoffset") = boost::python::make_function( TZInfo_<Impl>::utcoffset_impl); } private: static boost::python::object dst_impl(boost::python::object o) { DateTime dt(o); return Impl::dst(dt).obj(); } static boost::python::object fromutc_impl(boost::python::object o) { DateTime dt(o); return Impl::fromutc(dt).obj(); } static boost::python::object tzname_impl() { return boost::python::object(Impl::tzname()); } static boost::python::object utcoffset_impl(boost::python::object o) { DateTime dt(o); return Impl::utcoffset(dt).obj(); } }; }} #endif
22.298969
72
0.59362
[ "object" ]
0501f3050f009cba5bd0340c7113712c97a6853f
8,308
cpp
C++
src/energyplus/ReverseTranslator/ReverseTranslateShadowCalculation.cpp
mehrdad-shokri/OpenStudio
1773b54ce1cb660818ac0114dd7eefae6639ca36
[ "blessing" ]
null
null
null
src/energyplus/ReverseTranslator/ReverseTranslateShadowCalculation.cpp
mehrdad-shokri/OpenStudio
1773b54ce1cb660818ac0114dd7eefae6639ca36
[ "blessing" ]
null
null
null
src/energyplus/ReverseTranslator/ReverseTranslateShadowCalculation.cpp
mehrdad-shokri/OpenStudio
1773b54ce1cb660818ac0114dd7eefae6639ca36
[ "blessing" ]
null
null
null
/*********************************************************************************************************************** * OpenStudio(R), Copyright (c) 2008-2020, Alliance for Sustainable Energy, LLC, and other contributors. All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the * following conditions are met: * * (1) Redistributions of source code must retain the above copyright notice, this list of conditions and the following * disclaimer. * * (2) Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided with the distribution. * * (3) Neither the name of the copyright holder nor the names of any contributors may be used to endorse or promote products * derived from this software without specific prior written permission from the respective party. * * (4) Other than as required in clauses (1) and (2), distributions in any form of modifications or other derivative works * may not use the "OpenStudio" trademark, "OS", "os", or any other confusingly similar designation without specific prior * written permission from Alliance for Sustainable Energy, LLC. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER(S) AND ANY 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(S), ANY CONTRIBUTORS, THE UNITED STATES GOVERNMENT, OR THE UNITED * STATES DEPARTMENT OF ENERGY, NOR ANY OF THEIR EMPLOYEES, BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ***********************************************************************************************************************/ #include "../ReverseTranslator.hpp" #include "../../model/ShadowCalculation.hpp" #include "../../model/ShadowCalculation_Impl.hpp" #include "../../model/ThermalZone.hpp" #include "../../model/Space.hpp" #include "../../model/Space_Impl.hpp" #include "../../utilities/idf/IdfExtensibleGroup.hpp" #include "../../utilities/idf/WorkspaceExtensibleGroup.hpp" #include <utilities/idd/ShadowCalculation_FieldEnums.hxx> #include <utilities/idd/ZoneList_FieldEnums.hxx> #include <utilities/idd/IddEnums.hxx> #include "../../utilities/core/Assert.hpp" #include "../../utilities/core/Optional.hpp" using namespace openstudio::model; namespace openstudio { namespace energyplus { boost::optional<model::ModelObject> ReverseTranslator::translateShadowCalculation( const WorkspaceObject& workspaceObject) { OS_ASSERT(workspaceObject.iddObject().type() == IddObjectType::ShadowCalculation); ShadowCalculation sc = m_model.getUniqueModelObject<ShadowCalculation>(); OptionalString _s; OptionalInt _i; // Shading Calculation Method if ( (_s = workspaceObject.getString(ShadowCalculationFields::ShadingCalculationMethod)) && !_s->empty() ) { sc.setShadingCalculationMethod(_s.get()); } // Shading Calculation Update Frequency Method if ( (_s = workspaceObject.getString(ShadowCalculationFields::ShadingCalculationUpdateFrequencyMethod)) && !_s->empty() ) { sc.setShadingCalculationUpdateFrequencyMethod(_s.get()); } // Shading Calculation Update Frequency if ( (_i = workspaceObject.getInt(ShadowCalculationFields::ShadingCalculationUpdateFrequency)) ) { sc.setShadingCalculationUpdateFrequency(_i.get()); } // Maximum Figures in Shadow Overlap Calculations if ( (_i = workspaceObject.getInt(ShadowCalculationFields::MaximumFiguresinShadowOverlapCalculations)) ) { sc.setMaximumFiguresInShadowOverlapCalculations(_i.get()); } // Polygon Clipping Algorithm if ( (_s = workspaceObject.getString(ShadowCalculationFields::PolygonClippingAlgorithm)) && !_s->empty() ) { sc.setPolygonClippingAlgorithm(_s.get()); } // Sky Diffuse Modeling Algorithm if ( (_s = workspaceObject.getString(ShadowCalculationFields::SkyDiffuseModelingAlgorithm)) && !_s->empty() ) { sc.setSkyDiffuseModelingAlgorithm(_s.get()); } // Pixel Counting Resolution if ( (_i = workspaceObject.getInt(ShadowCalculationFields::PixelCountingResolution)) ) { sc.setPixelCountingResolution(_i.get()); } // Output External Shading Calculation Results if ( (_s = workspaceObject.getString(ShadowCalculationFields::OutputExternalShadingCalculationResults)) ) { if (istringEqual("Yes", _s.get())) { sc.setOutputExternalShadingCalculationResults(true); } else if (istringEqual("No", _s.get())) { sc.setOutputExternalShadingCalculationResults(false); } } // Disable Self-Shading Within Shading Zone Groups if ( (_s = workspaceObject.getString(ShadowCalculationFields::DisableSelfShadingWithinShadingZoneGroups)) ) { if (istringEqual("Yes", _s.get())) { sc.setDisableSelfShadingWithinShadingZoneGroups(true); } else if (istringEqual("No", _s.get())) { sc.setDisableSelfShadingWithinShadingZoneGroups(false); } } // Disable Self-Shading From Shading Zone Groups to Other Zones if ( (_s = workspaceObject.getString(ShadowCalculationFields::DisableSelfShadingFromShadingZoneGroupstoOtherZones)) ) { if (istringEqual("Yes", _s.get())) { sc.setDisableSelfShadingFromShadingZoneGroupstoOtherZones(true); } else if (istringEqual("No", _s.get())) { sc.setDisableSelfShadingFromShadingZoneGroupstoOtherZones(false); } } // Shading Zone Group (E+: Shading Zone Group 1 ZoneList Name) // **Extensible** for ZoneLists for (const IdfExtensibleGroup& eg: workspaceObject.extensibleGroups()) { OptionalWorkspaceObject target = eg.cast<WorkspaceExtensibleGroup>().getTarget(ShadowCalculationExtensibleFields::ShadingZoneGroupZoneListName); if (target) { // We populate a vector of WorkspaceObject (which are 'Zone'), // so we handle the case when it's a Zone and the case when it's a ZoneList in the same way later down std::vector<WorkspaceObject> i_zones; if (target->iddObject().type() == IddObjectType::Zone) { i_zones.push_back(target.get()); } else if (target->iddObject().type() == IddObjectType::ZoneList) { // ZoneLists are translated back to a space type, which isn't even something we do want to do here, except it'll still be default RT'ed. // Anyways, using the returned spacetype is useless since if a zone is referenced by multiple ZoneLists, then the sapcetype assigned for that // zone is the last ZoneList found... for (const IdfExtensibleGroup& zeg: target->extensibleGroups()) { OptionalWorkspaceObject target_zone = zeg.cast<WorkspaceExtensibleGroup>().getTarget(ZoneListExtensibleFields::ZoneName); if (target_zone) { i_zones.push_back(target_zone.get()); } } } else { LOG(Error, "For ShadowCalculation, an extensible group entry is neither a Zone or ZoneList, skipping."); continue; } // Now we translate all of these WorkspaceObjects, and get corresponding (Model) ThermalZones in a vector std::vector<ThermalZone> thermalZones; for (const WorkspaceObject& i_zone: i_zones) { // Zone is translated, and a Space is returned instead OptionalModelObject _mo = translateAndMapWorkspaceObject(i_zone); if (_mo) { if (boost::optional<Space> _space = _mo->optionalCast<Space>()) { if (auto _zone = _space->thermalZone()) { thermalZones.push_back(_zone.get()); } } } } // And now we add that as a Shading Zone Group if (!thermalZones.empty()) { sc.addShadingZoneGroup(thermalZones); } } } return sc.cast<ModelObject>(); } } // energyplus } // openstuio
45.648352
149
0.708955
[ "vector", "model" ]
050484915f7734c91abf910f068c17b22ae25e84
2,294
cpp
C++
CSE331/2020_Fall/HW2/hw2.cpp
abdcelik/GTU
bba79ea7e48fa38753f08391bdc4ddc10931ccf6
[ "MIT" ]
2
2020-01-04T15:17:48.000Z
2020-10-21T12:50:22.000Z
CSE331/2020_Fall/HW2/hw2.cpp
abdcelik/GTU
bba79ea7e48fa38753f08391bdc4ddc10931ccf6
[ "MIT" ]
null
null
null
CSE331/2020_Fall/HW2/hw2.cpp
abdcelik/GTU
bba79ea7e48fa38753f08391bdc4ddc10931ccf6
[ "MIT" ]
3
2021-05-03T10:12:52.000Z
2021-12-06T13:43:37.000Z
#include <iostream> using namespace std; typedef struct { int *arr; int size; int capacity; }Vector; Vector in; Vector out; int CheckSumPossibility(int num, int arr[], int size); int getNonNegIntWithText(const char*,const char*); void printArray(int*,int); void initializeVector(Vector*,int); void addItemToVector(Vector*,int); void freeMemory(Vector*); int main() { int size = getNonNegIntWithText("Size: ", "Number should be non-negative! Please enter non-negative integer: "); int num = getNonNegIntWithText("Target number: ", "Number should be non-negative! Please enter non-negative integer: "); int returnVal; initializeVector(&in,size); initializeVector(&out,0); for(int i=0 ; i < in.capacity ; ++i) { cout << i+1; addItemToVector(&in,getNonNegIntWithText(". element: ", "Number should be non-negative! Please enter non-negative integer: ")); } returnVal = CheckSumPossibility(num,in.arr,in.size); if(returnVal == 1) cout << "Possible!"; else cout << "Not possible!"; printArray(out.arr,out.size); cout << endl; freeMemory(&in); freeMemory(&out); return 0; } int CheckSumPossibility(int num, int arr[], int size) { if(num == 0) return 1; if(size == 0) return 0; if(num - *arr >= 0 && CheckSumPossibility(num - *arr, arr+1, size-1)) { addItemToVector(&out,*arr); return 1; } return CheckSumPossibility(num, arr+1, size-1); } int getNonNegIntWithText(const char* t1, const char* t2) { int var; cout << t1; cin >> var; while(var < 0) { cout << t2; cin >> var; } return var; } void printArray(int* arr, int size) { for(int i=0 ; i < size ; ++i) cout << " " << arr[i]; } void initializeVector(Vector* vec, int capacity) { if(capacity <= 0) capacity = 1; vec->arr = new int[capacity]; vec->size = 0; vec->capacity = capacity; } void addItemToVector(Vector* vec, int item) { if(vec->size == vec->capacity) { vec->capacity *= 2; int* arr = new int[vec->capacity]; for(int i=0 ; i < vec->size ; ++i) arr[i] = vec->arr[i]; delete[] vec->arr; vec->arr = arr; } vec->arr[vec->size] = item; ++(vec->size); } void freeMemory(Vector* vec) { delete[] vec->arr; }
19.116667
130
0.612031
[ "vector" ]
050a7e775bc6e15608b1d72c8c5d94ff6ec0dccf
7,096
cpp
C++
twoThree.cpp
wordnall/415project3
b611f1ddd4de8814ce605c28fb779511514fa392
[ "MIT" ]
null
null
null
twoThree.cpp
wordnall/415project3
b611f1ddd4de8814ce605c28fb779511514fa392
[ "MIT" ]
null
null
null
twoThree.cpp
wordnall/415project3
b611f1ddd4de8814ce605c28fb779511514fa392
[ "MIT" ]
null
null
null
#include "twoThree.h" #include "time.h" #include <iomanip> #include <sstream> TTT::TTT() { root = NULL; } bool TTT::isEmpty() { return root == NULL; } void TTT::contains() const { string input; node* foundNode = NULL; cout << "Search word: "; cin >> input; vector<int> lines; if (findhelp(root, input, lines)) { cout << "Line Numbers: " << lines[0]; for (int i = 1; i < lines.size(); i++) cout << ", " << lines[i]; cout << endl; } else cout << '\"' << input << "\" is not in the document\n"; } void TTT::searchAllTree(ifstream& input) { vector<int> lines; stringstream tempWord; double totalTime, finishTime, startTime = clock(); while (!input.eof()) { string tempLine, tempWord; //Read a whole line of text from the file getline(input, tempLine); for (int i = 0; i < tempLine.length(); i++) { //Insert valid chars into tempWord until a delimiter( newline or space) is found while (tempLine[i] != ' ' && tempLine[i] != '\n' && i < tempLine.length()) { tempWord.insert(tempWord.end(), tempLine[i]); i++; } //Trim any punctuation off end of word. Will leave things like apostrophes //and decimal points while (tempWord.length() > 0 && !isalnum(tempWord[tempWord.length() - 1])) tempWord.resize(tempWord.size() - 1); if (tempWord.length() > 0) { findhelp(root, tempWord, lines); //Clear out tempWord so we can use it again tempWord.clear(); } } } //Do time and height calculation finishTime = clock(); totalTime = (double)(finishTime - startTime) / CLOCKS_PER_SEC; //Print output cout << setw(40) << std::left << "Total time taken by 2-3 Tree: " << totalTime << endl; } void TTT::printTreeHelper(node* t, ostream& out) const { if (t == NULL) return; else { printTreeHelper(t->left, out); if (t->llines.size() != 0) { out << setw(30) << std::left; out << t->lkey << " " << t->llines[0]; for (int i = 1; i < t->llines.size(); i++) out << ", " << t->llines[i]; out << endl; } printTreeHelper(t->center, out); if (t->rkey != "" && t->rlines.size() != 0) { out << setw(30) << std::left; out << t->rkey << " " << t->rlines[0]; for (int i = 1; i < t->rlines.size(); i++) out << ", " << t->rlines[i]; out << endl; } printTreeHelper(t->right, out); } } void TTT::printTree(ostream& out) const { out << "2-3 Tree Index:\n--------------\n"; printTreeHelper(root, out); } void TTT::buildTree(ifstream& input, bool output) { int line = 1, numWords = 0, distWords = 0, treeHeight = 0; stringstream tempWord; double totalTime, finishTime, startTime = clock(); while (!input.eof()) { string tempLine, tempWord; //Read a whole line of text from the file getline(input, tempLine); for (int i = 0; i < tempLine.length(); i++) { //Insert valid chars into tempWord until a delimiter( newline or space) is found while (tempLine[i] != ' ' && tempLine[i] != '\n' && i < tempLine.length()) { tempWord.insert(tempWord.end(), tempLine[i]); i++; } //Trim any punctuation off end of word. Will leave things like apostrophes //and decimal points while (tempWord.length() > 0 && !isalnum(tempWord[tempWord.length() - 1])) tempWord.resize(tempWord.size() - 1); if (tempWord.length() > 0) { //Once word is formatted,call insert with the word, the line of the input //file it came from, the root of our tree, and the distinct word counter root = inserthelp(root, tempWord, line, distWords); //Increment our total number of words inserted numWords++; //Clear out tempWord so we can use it again tempWord.clear(); } } line++; } //Do time and height calculation finishTime = clock(); totalTime = (double)(finishTime - startTime) / CLOCKS_PER_SEC; treeHeight = findHeight(root); //Print output if (output) { cout << setw(40) << std::left; cout << "Total number of words: " << numWords << endl; cout << setw(40) << std::left << "Total number of distinct words: " << distWords << endl; cout << setw(40) << std::left << "Total time spent building index: " << totalTime << endl; cout << setw(40) << std::left << "Height of 2-3 Tree is : " << treeHeight << endl; } } bool TTT::findhelp(node* root, const string& k, vector<int>& lineNums) const{ if (root == NULL) return false; // val not found if (k.compare(root->lkey) == 0) { lineNums = root->llines; return true; } if ((root->rkey != "") && (k.compare(root->rkey) == 0)) { lineNums = root->rlines; return true; } if (k.compare(root->lkey) < 0) // Search left return findhelp(root->left, k, lineNums); else if (root->rkey == "") // Search center return findhelp(root->center, k, lineNums); else if (k.compare(root->rkey) < 0) // Search center return findhelp(root->center, k, lineNums); else return findhelp(root->right, k, lineNums); // Search right } TTT::node* TTT::inserthelp(node*& rt, const string &k, int line, int& distWords) { node* retval; if (rt == NULL) { // Empty tree: create a leaf node for root node * temp = new node(k, "", NULL, NULL, NULL); temp->llines.push_back(line); distWords++; return temp; } if (rt->lkey == k) { rt->llines.push_back(line); return rt; } else if (rt->rkey == k) { rt->rlines.push_back(line); return rt; } if (rt->isLeaf()) { // At leaf node: insert here node* temp = new node(k, "", NULL, NULL, NULL); temp->llines.push_back(line); distWords++; return rt->add(temp); } // Add to internal node if (k.compare(rt->lkey) < 0) { // Insert left retval = inserthelp(rt->left, k, line, distWords); if (retval == rt->left) return rt; else { return rt->add(retval); } } else if((rt->rkey == "") || (k.compare(rt->rkey) < 0)) { retval = inserthelp(rt->center, k, line, distWords); if (retval == rt->center) return rt; else { return rt->add(retval); } } else { // Insert right retval = inserthelp(rt->right, k, line, distWords); if (retval == rt->right) return rt; else { return rt->add(retval); } } } // Add a new key/value pair to the node. There might be a subtree // associated with the record being added. This information comes // in the form of a 2-3 tree node with one key and a (possibly null) // subtree through the center pointer field. //Returns height of tree. If tree has only one node, height is 1 int TTT::findHeight(node* t) { if (t == NULL) return 0; else { int leftHeight = findHeight(t->left), centerHeight = findHeight(t->center), rightHeight = findHeight(t->right); if (leftHeight >= rightHeight && leftHeight >= centerHeight) return(leftHeight + 1); else if (centerHeight >= leftHeight && centerHeight >= rightHeight) return(centerHeight + 1); else return(rightHeight + 1); } }
29.201646
114
0.58991
[ "vector" ]
050c6e0b64b5cdd742f1e8587dcb77adaed0ff37
9,233
cc
C++
src/meshexp/main.cc
codeka/ravaged-planets
ab20247b3829414e71b58c9a6e926bddf41f1da5
[ "Apache-2.0" ]
null
null
null
src/meshexp/main.cc
codeka/ravaged-planets
ab20247b3829414e71b58c9a6e926bddf41f1da5
[ "Apache-2.0" ]
null
null
null
src/meshexp/main.cc
codeka/ravaged-planets
ab20247b3829414e71b58c9a6e926bddf41f1da5
[ "Apache-2.0" ]
3
2017-07-17T22:24:17.000Z
2019-10-15T18:37:15.000Z
#include <iostream> #include <boost/program_options.hpp> #include <boost/algorithm/string.hpp> #include <framework/bitmap.h> #include <framework/settings.h> #include <framework/framework.h> #include <framework/logging.h> #include <framework/exception.h> #include <framework/model.h> #include <framework/model_node.h> #include <framework/model_writer.h> #include <assimp/scene.h> #include <assimp/postprocess.h> #include <assimp/Importer.hpp> #include <assimp/DefaultLogger.hpp> namespace po = boost::program_options; //----------------------------------------------------------------------------- void settings_initialize(int argc, char** argv); void display_exception(std::string const &msg); bool export_scene(aiScene const *scene, std::string const &filename); bool add_mesh(fw::model &mdl, aiMesh *mesh); std::shared_ptr<fw::model_node> add_node(fw::model &mdl, aiNode *node, int level); //----------------------------------------------------------------------------- void meshexp(std::string input_filename, std::string output_filename) { Assimp::Importer importer; fw::debug << "reading file: " << input_filename << std::endl; // set the list of things we want the importer to ignore (COLORS is the most important) importer.SetPropertyInteger(AI_CONFIG_PP_RVC_FLAGS, aiComponent_TANGENTS_AND_BITANGENTS | aiComponent_COLORS | aiComponent_LIGHTS | aiComponent_CAMERAS); // set the maximum number of vertices and faces we'll put in a single mesh importer.SetPropertyInteger(AI_CONFIG_PP_SLM_VERTEX_LIMIT, 35535); importer.SetPropertyInteger(AI_CONFIG_PP_SLM_TRIANGLE_LIMIT, 35535); // set the maximum number of bones we want per vertex importer.SetPropertyInteger(AI_CONFIG_PP_LBW_MAX_WEIGHTS, 4); // import the scene! aiScene const *scene = importer.ReadFile(input_filename.c_str(), aiProcess_Triangulate | aiProcess_JoinIdenticalVertices /*aiProcess_LimitBoneWeights */ | aiProcess_SortByPType | aiProcess_RemoveComponent | aiProcess_SplitLargeMeshes | aiProcess_ImproveCacheLocality | aiProcess_RemoveRedundantMaterials | aiProcess_GenUVCoords | aiProcess_OptimizeMeshes | aiProcess_OptimizeGraph | aiProcess_GenNormals | aiProcess_FlipWindingOrder | aiProcess_ValidateDataStructure | aiProcess_FindInvalidData); if (scene == nullptr) { fw::debug << "-- ERROR --" << std::endl; fw::debug << importer.GetErrorString() << std::endl; return; } export_scene(scene, output_filename); } bool export_scene(aiScene const *scene, std::string const &filename) { fw::debug << "- writing file: " << filename << std::endl; // build up the fw::model first, and then use the fw::model_writer to // write it to disk. fw::model mdl; for (unsigned int i = 0; i < scene->mNumMeshes; i++) { if (!add_mesh(mdl, scene->mMeshes[i])) return false; } // add the root node (and recursively find all it's children as well) mdl.root_node = add_node(mdl, scene->mRootNode, 0); if (scene->mAnimations != 0) { // add animations for (unsigned int i = 0; i < scene->mNumAnimations; i++) { fw::debug << " adding animation: (\"" << scene->mAnimations[0]->mName.data << "\")" << std::endl; } } fw::model_writer writer; writer.write(filename, mdl); return true; } // adds the given aiMesh to the given fw::model bool add_mesh(fw::model &mdl, aiMesh *mesh) { fw::debug << " adding mesh (" << mesh->mNumBones << " bone(s), " << mesh->mNumVertices << " vertex(es), " << mesh->mNumFaces << " face(s))" << std::endl; // create a vector of xyz_n_uv vertices and set it to zero initially std::shared_ptr<fw::model_mesh_noanim> mm(new fw::model_mesh_noanim(mesh->mNumVertices, mesh->mNumFaces * 3)); memset(&mm->vertices[0], 0, sizeof(fw::vertex::xyz_n_uv) * mesh->mNumVertices); memset(&mm->indices[0], 0, sizeof(uint16_t) * mesh->mNumFaces * 3); // copy each of the vertices from the mesh into our own array for (unsigned int i = 0; i < mesh->mNumVertices; i++) { mm->vertices[i].x = mesh->mVertices[i].x; mm->vertices[i].y = mesh->mVertices[i].y; mm->vertices[i].z = mesh->mVertices[i].z; if (mesh->mNormals != 0) { mm->vertices[i].nx = mesh->mNormals[i].x; mm->vertices[i].ny = mesh->mNormals[i].y; mm->vertices[i].nz = mesh->mNormals[i].z; } // we currently only support one set of texture coords if (mesh->mTextureCoords[0] != 0) { mm->vertices[i].u = mesh->mTextureCoords[0][i].x; mm->vertices[i].v = 1.0f - mesh->mTextureCoords[0][i].y; } } // copy each of the faces from the mesh into our array, since we passed aiProcess_Triangulate, // each face should be a nice triangle for us for (unsigned int i = 0; i < mesh->mNumFaces; i++) { if (mesh->mFaces[i].mNumIndices != 3) { fw::debug << "PANIC! face is not a triangle! mNumIndices = " << mesh->mFaces[i].mNumIndices << std::endl; return false; } for (int j = 0; j < 3; j++) { if (mesh->mFaces[i].mIndices[j] > 0xffff) { fw::debug << "PANIC! face index is bigger than that supported by a 16-bit value: " << mesh->mFaces[i].mIndices[j] << std::endl; return false; } mm->indices[i * 3 + j] = static_cast<uint16_t>(mesh->mFaces[i].mIndices[j]); } } mdl.meshes.push_back(std::dynamic_pointer_cast<fw::model_mesh>(mm)); return true; } std::shared_ptr<fw::model_node> add_node(fw::model &mdl, aiNode *node, int level) { fw::debug << " " << std::string(level * 2, ' ') << "adding node \"" << node->mName.data << "\"" << " (" << node->mNumChildren << " child(ren), " << node->mNumMeshes << " meshe(s))" << std::endl; std::shared_ptr<fw::model_node> root_node; if (node->mNumMeshes == 1) { // if there's just one mesh (this is the most common case), then we just copy // the vertex_buffer, index_buffer and so on to the scenegraph node root_node = std::shared_ptr<fw::model_node>(new fw::model_node()); root_node->mesh_index = node->mMeshes[0]; } else { root_node = std::shared_ptr<fw::model_node>(new fw::model_node()); root_node->mesh_index = -1; // we create one child node for each of our meshes for (unsigned int index = 0; index < node->mNumMeshes; index++) { std::shared_ptr<fw::model_node> child_node(new fw::model_node()); child_node->mesh_index = node->mMeshes[index]; root_node->add_child(std::dynamic_pointer_cast<fw::sg::node>(child_node)); } } // copy the matrix from the aiNode to our new node as well fw::matrix matrix; for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { matrix(i, j) = node->mTransformation[j][i]; } } // add the mesh_scale factor, if there is one... // if (mesh_scale != 1.0f) { // matrix = fw::scale(mesh_scale) * matrix; // } root_node->transform = matrix; for (unsigned int i = 0; i < node->mNumChildren; i++) { std::shared_ptr<fw::model_node> child_node = add_node(mdl, node->mChildren[i], level + 1); root_node->add_child(std::dynamic_pointer_cast<fw::sg::node>(child_node)); } return root_node; } //----------------------------------------------------------------------------- class LogStream : public Assimp::LogStream { public: void write(const char* message) { std::string msg(message); boost::trim(msg); fw::debug << " assimp : " << msg << std::endl; } }; //----------------------------------------------------------------------------- int main(int argc, char** argv) { try { settings_initialize(argc, argv); Assimp::DefaultLogger::create(nullptr, Assimp::Logger::VERBOSE, 0, nullptr); Assimp::DefaultLogger::get()->attachStream(new LogStream()); fw::tool_application app; new fw::framework(&app); fw::framework::get_instance()->initialize("Meshexp"); fw::settings stg; meshexp(stg.get_value<std::string>("input"), stg.get_value<std::string>("output")); } catch (std::exception &e) { std::string msg = boost::diagnostic_information(e); fw::debug << "--------------------------------------------------------------------------------" << std::endl; fw::debug << "UNHANDLED EXCEPTION!" << std::endl; fw::debug << msg << std::endl; display_exception(e.what()); } catch (...) { fw::debug << "--------------------------------------------------------------------------------" << std::endl; fw::debug << "UNHANDLED EXCEPTION! (unknown exception)" << std::endl; } return 0; } void display_exception(std::string const &msg) { std::stringstream ss; ss << "An error has occurred. Please send your log file (below) to dean@codeka.com.au for diagnostics." << std::endl; ss << std::endl; ss << fw::debug.get_filename() << std::endl; ss << std::endl; ss << msg; } void settings_initialize(int argc, char** argv) { po::options_description options("Additional options"); options.add_options()("input", po::value<std::string>()->default_value(""), "The input file to load, must be a supported mesh type."); options.add_options()("output", po::value<std::string>()->default_value(""), "The output file to save as, must end with '.mesh'."); fw::settings::initialize(options, argc, argv, "meshexp.conf"); }
37.685714
136
0.62764
[ "mesh", "vector", "model", "transform" ]
052015dbb80b78cf3a82f176bd7ec811e900b6ec
5,150
cpp
C++
CO2_Tracker/receipt_info.cpp
cgneo/CarbonTracker
40603fbde05a65db900756d7077c65b46a3a4a8e
[ "Apache-2.0" ]
null
null
null
CO2_Tracker/receipt_info.cpp
cgneo/CarbonTracker
40603fbde05a65db900756d7077c65b46a3a4a8e
[ "Apache-2.0" ]
null
null
null
CO2_Tracker/receipt_info.cpp
cgneo/CarbonTracker
40603fbde05a65db900756d7077c65b46a3a4a8e
[ "Apache-2.0" ]
null
null
null
#include <QGraphicsWidget> #include <QApplication> #include "food_api.h" #include <string> #include <iostream> #include <fstream> #include <vector> #include <tesseract/baseapi.h> #include <leptonica/allheaders.h> bool check_digit(char c) { vector<char> digit_vec = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'}; if (find(digit_vec.begin(), digit_vec.end(), c) != digit_vec.end()) { return true; } return false; } // Checks that a string "str" is only made of numeric characters // This function is used to know which part of the file corresponds to a product's id. bool is_id(string str) { char space = ' '; if (!check_digit(str.at(str.length() - 1)) and (str.at(str.length() - 1) != space)) { return false; } for (int i = 0; i < int(str.length()) - 1; i++) { if (!check_digit(str.at(i))) { return false; } } return true; } // Helper function that check that a string "str" is only made of numeric characters bool num_str(string str) { for (char c : str) { if (!check_digit(c) and c != ',' and c != '.') { return false; } } return true; } // Helper function that takes a string "line" and returns a vector "words" containing the words within the line // Here a word is defined as a non-empty string between two spaces. vector<string> decompose_line(string line) { string space_delimiter = " "; vector<string> words{}; size_t pos = 0; while ((pos = line.find(space_delimiter)) != string::npos) { words.push_back(line.substr(0, pos)); line.erase(0, pos + space_delimiter.length()); } return words; } // Helper function that takes a vector of words (corresponding to a line in the file) and returns a size-2 vector // Hhere the first element in a reference number for a product (its id) and the second element is the quantity vector<string> extract_id_quant(vector<string> words) { string id = words[0]; // The id is always the first word in a line (by observation) string quantity = words[words.size() - 5]; vector<string> res; res.push_back(id); res.push_back(quantity); return res; } // This function takes a file "filename" as input and returns "res_vector" a vector of vectors of the form {id, quantity} // i.e each element of res_vector is a vector containing the reference number of a product and its quantity. // The returned vector will later be used to send queries to the data base and calculate the carbon footprint of the receipt given in the file. vector<vector<string>> file_to_vector(string filename) { ifstream myfile(filename); // Open file in read mode vector<vector<string>> id_quant_pairs; if (myfile.is_open()) { string line; while (getline(myfile, line)) { // Read file line by line if (!line.empty()) { string potential_id = line.substr(0, 13); bool id = is_id(potential_id); if (id) { // If the line begins with an id vector<string> words = decompose_line(line); // Decompose the line into a vector of words vector<string> pair = extract_id_quant(words); // Extract the id and the quantity of the product in the line id_quant_pairs.push_back(pair); // Append this pair to res_vector } } } myfile.close(); } else cout << "Unable to open file"; // Error handling message return id_quant_pairs; } vector<vector<string>> get_receipt_info(string filepath) { char *outText; tesseract::TessBaseAPI *api = new tesseract::TessBaseAPI(); // Initialize tesseract-ocr with French, without specifying tessdata path if (api->Init(NULL, "fra")) { std::cerr << "Could not initialize tesseract.\n"; //exit(1); } // Open input image with leptonica library Pix *image = pixRead(filepath.c_str()); api->SetImage(image); // Get OCR result outText = api->GetUTF8Text(); // Put OCR result in a file string filename = "/tmp/ocr_result.txt"; ofstream file(filename); file << string(outText); file.close(); // Call file_to_vector on the file vector<vector<string>> id_quant_pairs = file_to_vector(filename); // Destroy used object and release memory api->End(); delete api; delete[] outText; pixDestroy(&image); // simulate a vector of pairs {product_id, quantity} //vector<vector<string>> id_quant_pairs = {{"8076809578257", "1"}, {"8076809530668", "1"}, {"8076809513388", "1"}}; // initialise empty vector to store all product_info vectors vector<vector<string>> receipt_info = {}; // loop over id_quant_pairs and append each product_info to receipt_info for (vector<string> pair : id_quant_pairs) { food_api api(pair[0], pair[1]); api.get_reply(); receipt_info.push_back(api.get_product_info()); } return receipt_info; }
31.987578
143
0.620971
[ "object", "vector" ]
05239184ee1f7145542ff982030c1f8d8972eb28
4,759
cpp
C++
private/shell/ext/settings/folder.cpp
King0987654/windows2000
01f9c2e62c4289194e33244aade34b7d19e7c9b8
[ "MIT" ]
11
2017-09-02T11:27:08.000Z
2022-01-02T15:25:24.000Z
private/shell/ext/settings/folder.cpp
King0987654/windows2000
01f9c2e62c4289194e33244aade34b7d19e7c9b8
[ "MIT" ]
null
null
null
private/shell/ext/settings/folder.cpp
King0987654/windows2000
01f9c2e62c4289194e33244aade34b7d19e7c9b8
[ "MIT" ]
14
2019-01-16T01:01:23.000Z
2022-02-20T15:54:27.000Z
// // This module was originally designed to provide category and topic extensibility // through the registry and COM objects. You could add new categories by adding // the CLSID of a COM object to the registry. The standard 3 categories were // in fact implemented as the "standard" extension. // This code would enumerate these CLSIDs // and instantiate the corresponding settings folder extension objects which // in turn enumerate the topics that they provide. This extensibility // was found to be unnecessary so I removed the registry-reading code // to reduce code size. However, I left much of the // characteristics untouched in case the need for this flexibility returns // at some future date. BrianAu - 1/13/97 // #include "precomp.hxx" #pragma hdrstop #include "folder.h" #include "stdext.h" SettingsFolder::SettingsFolder( VOID ) : m_iCurrentTopic(0) { DebugMsg(DM_CONSTRUCT, TEXT("SettingsFolder::SettingsFolder, 0x%08X"), this); } SettingsFolder::~SettingsFolder( VOID ) { PSETTINGS_FOLDER_TOPIC pITopic = NULL; // // Release the topic objects. // while(m_lstTopics.Remove((LPVOID *)&pITopic, 0)) { Assert(NULL != pITopic); pITopic->Release(); pITopic = NULL; } } // // For each extension specified in the registry, // load the categories and topics supplied by the extension. // HRESULT SettingsFolder::LoadTopics( VOID ) throw(OutOfMemory) { HRESULT hResult = NO_ERROR; PointerList Extensions; PSETTINGS_FOLDER_EXT pExt = NULL; try { hResult = LoadExtensions(Extensions); if (SUCCEEDED(hResult)) { UINT cExtensions = Extensions.Count(); while(Extensions.Remove((LPVOID *)&pExt, 0)) { Assert(NULL != pExt); hResult = LoadExtensionTopics(pExt); // Can throw OutOfMemory. pExt->Release(); // Release extension from list. } } if (E_OUTOFMEMORY == hResult) { // // The callers of this are set up to expect an // OutOfMemory exception when we're out of memory. // throw OutOfMemory(); } } catch(...) { // // Clean up after exception. // while(Extensions.Remove((LPVOID *)&pExt, 0)) { Assert(NULL != pExt); pExt->Release(); } throw; } return hResult; } HRESULT SettingsFolder::LoadExtensions( PointerList& list ) throw(OutOfMemory) { PSETTINGS_FOLDER_EXT pExt = NULL;; try { pExt = new SettingsFolderExt(); pExt->AddRef(); // // Transfer ref count of 1 to list. // list.Append((LPVOID)pExt); // Add extension to our list. // Can throw OutOfMemory. } catch(...) { if (NULL != pExt) pExt->Release(); throw; } return NO_ERROR; } // // Load all individual topics supplied by the extension. // HRESULT SettingsFolder::LoadExtensionTopics( PSETTINGS_FOLDER_EXT pExt ) throw(OutOfMemory) { Assert(NULL != pExt); PENUM_SETTINGS_TOPICS pEnum = NULL; HRESULT hResult = NO_ERROR; hResult = pExt->EnumTopics(&pEnum); if (SUCCEEDED(hResult)) { PSETTINGS_FOLDER_TOPIC pITopic = NULL; try { while(SUCCEEDED(hResult) && S_OK == pEnum->Next(1, &pITopic, NULL)) { // // Transfer ref count of 1 to topic descriptor. // hResult = AddTopic(pITopic); pITopic = NULL; } pEnum->Release(); } catch(...) { if (NULL != pITopic) pITopic->Release(); pEnum->Release(); throw; } } return hResult; } // // Assumes caller has AddRef'd pITopic. // HRESULT SettingsFolder::AddTopic( PSETTINGS_FOLDER_TOPIC pITopic ) throw(OutOfMemory) { Assert(NULL != pITopic); m_lstTopics.Append((LPVOID)pITopic); return NO_ERROR; } PSETTINGS_FOLDER_TOPIC SettingsFolder::GetTopic( INT iTopic ) { HRESULT hResult = NO_ERROR; PSETTINGS_FOLDER_TOPIC pITopic = NULL; if (m_lstTopics.Retrieve((LPVOID *)&pITopic, iTopic)) { // // AddRef interface pointer before returning copy. // Assert(NULL != pITopic); pITopic->AddRef(); } return pITopic; } BOOL SettingsFolder::SetCurrentTopicIndex( INT iTopic ) { if (iTopic < (INT)m_lstTopics.Count()) { m_iCurrentTopic = iTopic; return TRUE; } return FALSE; }
21.436937
83
0.580794
[ "object" ]
05248776a20f974c90591ee2299cd82e6a2f9586
1,711
cpp
C++
trainingregional2018/contest1/P4.cpp
Victoralin10/ACMSolutions
6d6e50da87b2bc455e953629737215b74b10269c
[ "MIT" ]
null
null
null
trainingregional2018/contest1/P4.cpp
Victoralin10/ACMSolutions
6d6e50da87b2bc455e953629737215b74b10269c
[ "MIT" ]
null
null
null
trainingregional2018/contest1/P4.cpp
Victoralin10/ACMSolutions
6d6e50da87b2bc455e953629737215b74b10269c
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> #define REP(i, n) for(int i = 0; i < n; i++) #define REPR(i, a, b) for (int i = a; i < b; i++) #define clr(t, val) memset(t, val, sizeof(t)) #define all(v) v.begin(), v.end() #define SZ(v) ((int)(v).size()) #define TEST(x) cerr << "test " << #x << " " << x << endl; using namespace std; clock_t _inicio = clock(); typedef long long Long; typedef vector <int> vInt; typedef pair <int, int> Pair; Pair A[10004]; int main(int nargs, char **args) { int n, l; while (cin >> n >> l) { REP(i, n) cin >> A[i].second >> A[i].first; sort(A, A + n); priority_queue <int> st1, st2; int d = 0, ans = 0, j = 0; REP(i, 10001) { if (j == n) break; while (j < n && A[j].first <= i) { st2.push(A[j++].second); } int cl = l; while (cl > 0 && !st2.empty()) { int tp = st2.top(); st2.pop(); ans += tp; cl--; st1.push(-tp); } while (d > 0 && !st2.empty()) { int tp = st2.top(); st2.pop(); ans += tp; d--; st1.push(-tp); } while (!st2.empty()) { int tp = st2.top(); st2.pop(); if (st1.empty()) continue; int xtp = st1.top(); if (tp > -xtp) { ans += tp + xtp; st1.pop(); st1.push(-tp); } } d += cl; } cout << ans << endl; } // cerr << "Time elapsed: " << (clock() - _inicio)/1000 << " ms" << endl; return 0; }
26.734375
77
0.385739
[ "vector" ]
0528ad377b606d88daaa9f650f43efe91c03a89c
8,664
cc
C++
protocol/Greenstack/libgreenstack/Message.cc
daverigby/memcached
197cca992d5f1f8d7382a936969c8db999478c19
[ "BSD-3-Clause" ]
null
null
null
protocol/Greenstack/libgreenstack/Message.cc
daverigby/memcached
197cca992d5f1f8d7382a936969c8db999478c19
[ "BSD-3-Clause" ]
null
null
null
protocol/Greenstack/libgreenstack/Message.cc
daverigby/memcached
197cca992d5f1f8d7382a936969c8db999478c19
[ "BSD-3-Clause" ]
null
null
null
/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */ /* * Copyright 2015 Couchbase, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <libgreenstack/Message.h> #include <libgreenstack/Frame.h> #include <libgreenstack/Opcodes.h> #include <libgreenstack/Response.h> #include <libgreenstack/Request.h> #include <libgreenstack/core/Hello.h> #include <libgreenstack/Reader.h> #include <libgreenstack/core/SaslAuth.h> #include <libgreenstack/Writer.h> #include <iostream> #include <iomanip> #include <cassert> #include <stdexcept> #include <libgreenstack/memcached/Mutation.h> #include <libgreenstack/memcached/AssumeRole.h> #include <libgreenstack/memcached/CreateBucket.h> #include <libgreenstack/memcached/DeleteBucket.h> #include <libgreenstack/memcached/ListBuckets.h> #include <libgreenstack/memcached/SelectBucket.h> #include <libgreenstack/memcached/Get.h> Greenstack::Message::Message(bool response) : opaque(std::numeric_limits<uint32_t>::max()), opcode(Opcode::InvalidOpcode) { memset(&flags, 0, sizeof(flags)); flags.response = response; } Greenstack::Message::~Message() { } void Greenstack::Message::setOpaque(uint32_t value) { opaque = value; } uint32_t Greenstack::Message::getOpaque() const { return opaque; } void Greenstack::Message::setOpcode(const Opcode& value) { opcode = value; } Greenstack::Opcode Greenstack::Message::getOpcode() const { return opcode; } void Greenstack::Message::setFenceBit(bool enable) { flags.fence = enable; } bool Greenstack::Message::isFenceBitSet() const { return flags.fence; } void Greenstack::Message::setMoreBit(bool enable) { flags.more = enable; } bool Greenstack::Message::isMoreBitSet() const { return flags.more; } void Greenstack::Message::setQuietBit(bool enable) { flags.quiet = enable; } bool Greenstack::Message::isQuietBitSet() const { return flags.quiet; } Greenstack::FlexHeader& Greenstack::Message::getFlexHeader() { return flexHeader; } const Greenstack::FlexHeader& Greenstack::Message::getFlexHeader() const { return flexHeader; } void Greenstack::Message::setPayload(std::vector<uint8_t>& data) { payload.assign(data.begin(), data.end()); } void Greenstack::Message::validate() { // Empty } /** * Encode the message into the byte array. The format of the packet is * * 0 1 2 3 * +---------+---------+---------+---------+ * | Opaque | * +---------+---------+---------+---------+ * | Opcode | Flags | * +---------+---------+---------+ * 7 bytes * * If the response bit in the flag section is set then the * following layout follows * * 0 1 * +---------+---------+ * | Status | * +---------+---------+ * * If the flex header bit in the flag section is set the following * layout follows: * * 0 1 2 3 * +---------+---------+---------+---------+ * | Flex header length | * +---------+---------+---------+---------+ * | N bytes with flex header data | * +---------+---------+---------+---------+ * 4 + n bytes * * Finally the actual data payload for the command follows */ size_t Greenstack::Message::encode(std::vector<uint8_t>& vector, size_t offset) const { VectorWriter writer(vector, offset); writer.write(opaque); writer.write(uint16_t(opcode)); Flags theFlags = flags; theFlags.flexHeaderPresent = !flexHeader.isEmpty(); // This is a hack to convert my bitfield to a byte writer.write(reinterpret_cast<uint8_t*>(&theFlags), 1); // move offset past the fixed size header: offset += 7; if (flags.response) { const Response* r = dynamic_cast<const Response*>(this); assert(r); writer.write(uint16_t(r->getStatus())); offset += 2; } if (theFlags.flexHeaderPresent) { // the header should be written after the length field offset += 4; VectorWriter out(vector, offset); size_t nbytes = flexHeader.encode(out); writer.write(static_cast<uint32_t>(nbytes)); writer.skip(nbytes); } if (payload.size() > 0) { writer.write(payload.data(), payload.size()); } return writer.getOffset(); } Greenstack::Message* Greenstack::Message::create(Greenstack::Reader& reader, size_t size) { Message* ret; size_t endOffset = reader.getOffset() + size; uint32_t opaque; uint16_t opc; struct Flags flags; reader.read(opaque); reader.read(opc); Opcode opcode = to_opcode(opc); if (opcode == Opcode::InvalidOpcode) { throw std::runtime_error("Unknown opcode: " + std::to_string(opc)); } reader.read(reinterpret_cast<uint8_t*>(&flags), 1); if (flags.next) { throw std::runtime_error("Only one flag byte is defined"); } if (flags.unassigned) { throw std::runtime_error("Do not use unassigned bits"); } ret = createInstance(flags.response, opcode); ret->opaque = opaque; ret->opcode = opcode; ret->flags = flags; if (flags.response) { Response* r = dynamic_cast<Response*>(ret); uint16_t status; reader.read(status); r->setStatus(to_status(status)); if (r->getStatus() == Status::InvalidStatusCode) { delete ret; throw std::runtime_error( "Invalid status code " + std::to_string(status)); } } if (flags.flexHeaderPresent) { uint32_t nbytes; reader.read(nbytes); std::vector<uint8_t> data; data.resize(nbytes); reader.read(data.data(), nbytes); ByteArrayReader in(data); auto flex = FlexHeader::create(in); ret->flexHeader = flex; } // Set the content size_t payloadSize = endOffset - reader.getOffset(); ret->payload.resize(payloadSize); reader.read(ret->payload.data(), payloadSize); try { ret->validate(); } catch (std::runtime_error& err) { delete ret; throw err; } return ret; } Greenstack::Message* Greenstack::Message::createInstance(bool response, const Greenstack::Opcode& opcode) { switch (opcode) { case Greenstack::Opcode::Hello: if (response) { return new HelloResponse; } else { return new HelloRequest; } case Greenstack::Opcode::SaslAuth: if (response) { return new SaslAuthResponse; } else { return new SaslAuthRequest; } case Greenstack::Opcode::Mutation: if (response) { return new MutationResponse; } else { return new MutationRequest; } case Greenstack::Opcode::AssumeRole: if (response) { return new AssumeRoleResponse; } else { return new AssumeRoleRequest; } case Greenstack::Opcode::CreateBucket: if (response) { return new CreateBucketResponse; } else { return new CreateBucketRequest; } case Greenstack::Opcode::DeleteBucket: if (response) { return new DeleteBucketResponse; } else { return new DeleteBucketRequest; } case Greenstack::Opcode::SelectBucket: if (response) { return new SelectBucketResponse; } else { return new SelectBucketRequest; } case Greenstack::Opcode::ListBuckets: if (response) { return new ListBucketsResponse; } else { return new ListBucketsRequest; } case Greenstack::Opcode::Get: if (response) { return new GetResponse; } else { return new GetRequest; } default: if (response) { return new Response; } else { return new Request; } } }
27.504762
92
0.591413
[ "vector" ]
0529cb8a137a14b4baf1f36d5a2d7ddc67de8206
1,589
cpp
C++
TAO/DevGuideExamples/SmartProxies/Smart_Messenger_Proxy.cpp
cflowe/ACE
5ff60b41adbe1772372d1a43bcc1f2726ff8f810
[ "DOC" ]
36
2015-01-10T07:27:33.000Z
2022-03-07T03:32:08.000Z
TAO/DevGuideExamples/SmartProxies/Smart_Messenger_Proxy.cpp
cflowe/ACE
5ff60b41adbe1772372d1a43bcc1f2726ff8f810
[ "DOC" ]
2
2018-08-13T07:30:51.000Z
2019-02-25T03:04:31.000Z
TAO/DevGuideExamples/SmartProxies/Smart_Messenger_Proxy.cpp
cflowe/ACE
5ff60b41adbe1772372d1a43bcc1f2726ff8f810
[ "DOC" ]
38
2015-01-08T14:12:06.000Z
2022-01-19T08:33:00.000Z
// $Id: Smart_Messenger_Proxy.cpp 91816 2010-09-17 08:35:56Z johnnyw $ // Smart_Messenger_Proxy.cpp #include "Smart_Messenger_Proxy.h" #include <iostream> Smart_Messenger_Proxy_Factory::Smart_Messenger_Proxy_Factory( CORBA::ORB_ptr orb) { std::cout << "Creating smart proxy factory" << std::endl; // Convert the contents of the Logger.ior file to an object reference. CORBA::Object_var obj = orb->string_to_object("file://Logger.ior"); if (CORBA::is_nil(obj.in())) { std::cerr << "Nil Logger reference" << std::endl; throw 0; } // Narrow the object reference to a Logger object reference. logger_ = Logger::_narrow(obj.in()); if (CORBA::is_nil(logger_.in ())) { std::cerr << "Not a Logger object reference" << std::endl; throw 0; } } Messenger_ptr Smart_Messenger_Proxy_Factory::create_proxy ( Messenger_ptr proxy) { Messenger_ptr smart_proxy = 0; if (CORBA::is_nil(proxy) == 0) smart_proxy = new Smart_Messenger_Proxy(proxy, logger_.in()); return smart_proxy; } Smart_Messenger_Proxy::Smart_Messenger_Proxy( Messenger_ptr proxy, Logger_ptr logger) : TAO_Smart_Proxy_Base(proxy), logger_(Logger::_duplicate(logger)) { std::cout << "Creating smart proxy" << std::endl; } CORBA::Boolean Smart_Messenger_Proxy::send_message ( const char * user_name, const char * subject, char *& message) { logger_->log_message("Before send_message()"); CORBA::Boolean ret_val = TAO_Messenger_Smart_Proxy_Base::send_message(user_name, subject, message); logger_->log_message("After send_message()"); return ret_val; }
26.483333
78
0.714915
[ "object" ]