text
string
size
int64
token_count
int64
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "beatsaber-hook/shared/utils/typedefs.h" #include "beatsaber-hook/shared/utils/byref.hpp" // Including type: NoteJumpDurationTypeSettings #include "GlobalNamespace/NoteJumpDurationTypeSettings.hpp" // Including type: EnvironmentEffectsFilterPreset #include "GlobalNamespace/EnvironmentEffectsFilterPreset.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp" #include "beatsaber-hook/shared/utils/utils.h" // Completed includes // Begin forward declares // Forward declaring namespace: System namespace System { // Forward declaring type: Nullable`1<T> template<typename T> struct Nullable_1; } // Forward declaring namespace: GlobalNamespace namespace GlobalNamespace { // Forward declaring type: BeatmapDifficulty struct BeatmapDifficulty; } // Completed forward declares // Type namespace: namespace GlobalNamespace { // Forward declaring type: PlayerSpecificSettings class PlayerSpecificSettings; } #include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp" NEED_NO_BOX(::GlobalNamespace::PlayerSpecificSettings); DEFINE_IL2CPP_ARG_TYPE(::GlobalNamespace::PlayerSpecificSettings*, "", "PlayerSpecificSettings"); // Type namespace: namespace GlobalNamespace { // Size: 0x44 #pragma pack(push, 1) // Autogenerated type: PlayerSpecificSettings // [TokenAttribute] Offset: FFFFFFFF class PlayerSpecificSettings : public ::Il2CppObject { public: #ifdef USE_CODEGEN_FIELDS public: #else #ifdef CODEGEN_FIELD_ACCESSIBILITY CODEGEN_FIELD_ACCESSIBILITY: #else protected: #endif #endif // private System.Boolean _leftHanded // Size: 0x1 // Offset: 0x10 bool leftHanded; // Field size check static_assert(sizeof(bool) == 0x1); // Padding between fields: leftHanded and: playerHeight char __padding0[0x3] = {}; // private System.Single _playerHeight // Size: 0x4 // Offset: 0x14 float playerHeight; // Field size check static_assert(sizeof(float) == 0x4); // private System.Boolean _automaticPlayerHeight // Size: 0x1 // Offset: 0x18 bool automaticPlayerHeight; // Field size check static_assert(sizeof(bool) == 0x1); // Padding between fields: automaticPlayerHeight and: sfxVolume char __padding2[0x3] = {}; // private System.Single _sfxVolume // Size: 0x4 // Offset: 0x1C float sfxVolume; // Field size check static_assert(sizeof(float) == 0x4); // private System.Boolean _reduceDebris // Size: 0x1 // Offset: 0x20 bool reduceDebris; // Field size check static_assert(sizeof(bool) == 0x1); // private System.Boolean _noTextsAndHuds // Size: 0x1 // Offset: 0x21 bool noTextsAndHuds; // Field size check static_assert(sizeof(bool) == 0x1); // private System.Boolean _noFailEffects // Size: 0x1 // Offset: 0x22 bool noFailEffects; // Field size check static_assert(sizeof(bool) == 0x1); // private System.Boolean _advancedHud // Size: 0x1 // Offset: 0x23 bool advancedHud; // Field size check static_assert(sizeof(bool) == 0x1); // private System.Boolean _autoRestart // Size: 0x1 // Offset: 0x24 bool autoRestart; // Field size check static_assert(sizeof(bool) == 0x1); // Padding between fields: autoRestart and: saberTrailIntensity char __padding8[0x3] = {}; // private System.Single _saberTrailIntensity // Size: 0x4 // Offset: 0x28 float saberTrailIntensity; // Field size check static_assert(sizeof(float) == 0x4); // private NoteJumpDurationTypeSettings _noteJumpDurationTypeSettings // Size: 0x4 // Offset: 0x2C ::GlobalNamespace::NoteJumpDurationTypeSettings noteJumpDurationTypeSettings; // Field size check static_assert(sizeof(::GlobalNamespace::NoteJumpDurationTypeSettings) == 0x4); // private System.Single _noteJumpFixedDuration // Size: 0x4 // Offset: 0x30 float noteJumpFixedDuration; // Field size check static_assert(sizeof(float) == 0x4); // private System.Single _noteJumpStartBeatOffset // Size: 0x4 // Offset: 0x34 float noteJumpStartBeatOffset; // Field size check static_assert(sizeof(float) == 0x4); // private System.Boolean _hideNoteSpawnEffect // Size: 0x1 // Offset: 0x38 bool hideNoteSpawnEffect; // Field size check static_assert(sizeof(bool) == 0x1); // private System.Boolean _adaptiveSfx // Size: 0x1 // Offset: 0x39 bool adaptiveSfx; // Field size check static_assert(sizeof(bool) == 0x1); // Padding between fields: adaptiveSfx and: environmentEffectsFilterDefaultPreset char __padding14[0x2] = {}; // private EnvironmentEffectsFilterPreset _environmentEffectsFilterDefaultPreset // Size: 0x4 // Offset: 0x3C ::GlobalNamespace::EnvironmentEffectsFilterPreset environmentEffectsFilterDefaultPreset; // Field size check static_assert(sizeof(::GlobalNamespace::EnvironmentEffectsFilterPreset) == 0x4); // private EnvironmentEffectsFilterPreset _environmentEffectsFilterExpertPlusPreset // Size: 0x4 // Offset: 0x40 ::GlobalNamespace::EnvironmentEffectsFilterPreset environmentEffectsFilterExpertPlusPreset; // Field size check static_assert(sizeof(::GlobalNamespace::EnvironmentEffectsFilterPreset) == 0x4); public: // Get instance field reference: private System.Boolean _leftHanded bool& dyn__leftHanded(); // Get instance field reference: private System.Single _playerHeight float& dyn__playerHeight(); // Get instance field reference: private System.Boolean _automaticPlayerHeight bool& dyn__automaticPlayerHeight(); // Get instance field reference: private System.Single _sfxVolume float& dyn__sfxVolume(); // Get instance field reference: private System.Boolean _reduceDebris bool& dyn__reduceDebris(); // Get instance field reference: private System.Boolean _noTextsAndHuds bool& dyn__noTextsAndHuds(); // Get instance field reference: private System.Boolean _noFailEffects bool& dyn__noFailEffects(); // Get instance field reference: private System.Boolean _advancedHud bool& dyn__advancedHud(); // Get instance field reference: private System.Boolean _autoRestart bool& dyn__autoRestart(); // Get instance field reference: private System.Single _saberTrailIntensity float& dyn__saberTrailIntensity(); // Get instance field reference: private NoteJumpDurationTypeSettings _noteJumpDurationTypeSettings ::GlobalNamespace::NoteJumpDurationTypeSettings& dyn__noteJumpDurationTypeSettings(); // Get instance field reference: private System.Single _noteJumpFixedDuration float& dyn__noteJumpFixedDuration(); // Get instance field reference: private System.Single _noteJumpStartBeatOffset float& dyn__noteJumpStartBeatOffset(); // Get instance field reference: private System.Boolean _hideNoteSpawnEffect bool& dyn__hideNoteSpawnEffect(); // Get instance field reference: private System.Boolean _adaptiveSfx bool& dyn__adaptiveSfx(); // Get instance field reference: private EnvironmentEffectsFilterPreset _environmentEffectsFilterDefaultPreset ::GlobalNamespace::EnvironmentEffectsFilterPreset& dyn__environmentEffectsFilterDefaultPreset(); // Get instance field reference: private EnvironmentEffectsFilterPreset _environmentEffectsFilterExpertPlusPreset ::GlobalNamespace::EnvironmentEffectsFilterPreset& dyn__environmentEffectsFilterExpertPlusPreset(); // public System.Boolean get_leftHanded() // Offset: 0x1372B30 bool get_leftHanded(); // public System.Single get_playerHeight() // Offset: 0x1372B38 float get_playerHeight(); // public System.Boolean get_automaticPlayerHeight() // Offset: 0x1372B40 bool get_automaticPlayerHeight(); // public System.Single get_sfxVolume() // Offset: 0x1372B48 float get_sfxVolume(); // public System.Boolean get_reduceDebris() // Offset: 0x1372B50 bool get_reduceDebris(); // public System.Boolean get_noTextsAndHuds() // Offset: 0x1372B58 bool get_noTextsAndHuds(); // public System.Boolean get_noFailEffects() // Offset: 0x1372B60 bool get_noFailEffects(); // public System.Boolean get_advancedHud() // Offset: 0x1372B68 bool get_advancedHud(); // public System.Boolean get_autoRestart() // Offset: 0x1372B70 bool get_autoRestart(); // public System.Single get_saberTrailIntensity() // Offset: 0x1372B78 float get_saberTrailIntensity(); // public NoteJumpDurationTypeSettings get_noteJumpDurationTypeSettings() // Offset: 0x1372B80 ::GlobalNamespace::NoteJumpDurationTypeSettings get_noteJumpDurationTypeSettings(); // public System.Single get_noteJumpFixedDuration() // Offset: 0x1372B88 float get_noteJumpFixedDuration(); // public System.Single get_noteJumpStartBeatOffset() // Offset: 0x1372B90 float get_noteJumpStartBeatOffset(); // public System.Boolean get_hideNoteSpawnEffect() // Offset: 0x1372B98 bool get_hideNoteSpawnEffect(); // public System.Boolean get_adaptiveSfx() // Offset: 0x1372BA0 bool get_adaptiveSfx(); // public EnvironmentEffectsFilterPreset get_environmentEffectsFilterDefaultPreset() // Offset: 0x1372BA8 ::GlobalNamespace::EnvironmentEffectsFilterPreset get_environmentEffectsFilterDefaultPreset(); // public EnvironmentEffectsFilterPreset get_environmentEffectsFilterExpertPlusPreset() // Offset: 0x1372BB0 ::GlobalNamespace::EnvironmentEffectsFilterPreset get_environmentEffectsFilterExpertPlusPreset(); // public System.Void .ctor(System.Boolean leftHanded, System.Single playerHeight, System.Boolean automaticPlayerHeight, System.Single sfxVolume, System.Boolean reduceDebris, System.Boolean noTextsAndHuds, System.Boolean noFailEffects, System.Boolean advancedHud, System.Boolean autoRestart, System.Single saberTrailIntensity, NoteJumpDurationTypeSettings noteJumpDurationTypeSettings, System.Single noteJumpFixedDuration, System.Single noteJumpStartBeatOffset, System.Boolean hideNoteSpawnEffect, System.Boolean adaptiveSfx, EnvironmentEffectsFilterPreset environmentEffectsFilterDefaultPreset, EnvironmentEffectsFilterPreset environmentEffectsFilterExpertPlusPreset) // Offset: 0x1372C2C template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary> static PlayerSpecificSettings* New_ctor(bool leftHanded, float playerHeight, bool automaticPlayerHeight, float sfxVolume, bool reduceDebris, bool noTextsAndHuds, bool noFailEffects, bool advancedHud, bool autoRestart, float saberTrailIntensity, ::GlobalNamespace::NoteJumpDurationTypeSettings noteJumpDurationTypeSettings, float noteJumpFixedDuration, float noteJumpStartBeatOffset, bool hideNoteSpawnEffect, bool adaptiveSfx, ::GlobalNamespace::EnvironmentEffectsFilterPreset environmentEffectsFilterDefaultPreset, ::GlobalNamespace::EnvironmentEffectsFilterPreset environmentEffectsFilterExpertPlusPreset) { static auto ___internal__logger = ::Logger::get().WithContext("::GlobalNamespace::PlayerSpecificSettings::.ctor"); return THROW_UNLESS((::il2cpp_utils::New<PlayerSpecificSettings*, creationType>(leftHanded, playerHeight, automaticPlayerHeight, sfxVolume, reduceDebris, noTextsAndHuds, noFailEffects, advancedHud, autoRestart, saberTrailIntensity, noteJumpDurationTypeSettings, noteJumpFixedDuration, noteJumpStartBeatOffset, hideNoteSpawnEffect, adaptiveSfx, environmentEffectsFilterDefaultPreset, environmentEffectsFilterExpertPlusPreset))); } // public PlayerSpecificSettings CopyWith(System.Nullable`1<System.Boolean> leftHanded, System.Nullable`1<System.Single> playerHeight, System.Nullable`1<System.Boolean> automaticPlayerHeight, System.Nullable`1<System.Single> sfxVolume, System.Nullable`1<System.Boolean> reduceDebris, System.Nullable`1<System.Boolean> noTextsAndHuds, System.Nullable`1<System.Boolean> noFailEffects, System.Nullable`1<System.Boolean> advancedHud, System.Nullable`1<System.Boolean> autoRestart, System.Nullable`1<System.Single> saberTrailIntensity, System.Nullable`1<NoteJumpDurationTypeSettings> noteJumpDurationTypeSettings, System.Nullable`1<System.Single> noteJumpFixedDuration, System.Nullable`1<System.Single> noteJumpStartBeatOffset, System.Nullable`1<System.Boolean> hideNoteSpawnEffect, System.Nullable`1<System.Boolean> adaptiveSfx, System.Nullable`1<EnvironmentEffectsFilterPreset> environmentEffectsFilterDefaultPreset, System.Nullable`1<EnvironmentEffectsFilterPreset> environmentEffectsFilterExpertPlusPreset) // Offset: 0x1371A10 ::GlobalNamespace::PlayerSpecificSettings* CopyWith(::System::Nullable_1<bool> leftHanded, ::System::Nullable_1<float> playerHeight, ::System::Nullable_1<bool> automaticPlayerHeight, ::System::Nullable_1<float> sfxVolume, ::System::Nullable_1<bool> reduceDebris, ::System::Nullable_1<bool> noTextsAndHuds, ::System::Nullable_1<bool> noFailEffects, ::System::Nullable_1<bool> advancedHud, ::System::Nullable_1<bool> autoRestart, ::System::Nullable_1<float> saberTrailIntensity, ::System::Nullable_1<::GlobalNamespace::NoteJumpDurationTypeSettings> noteJumpDurationTypeSettings, ::System::Nullable_1<float> noteJumpFixedDuration, ::System::Nullable_1<float> noteJumpStartBeatOffset, ::System::Nullable_1<bool> hideNoteSpawnEffect, ::System::Nullable_1<bool> adaptiveSfx, ::System::Nullable_1<::GlobalNamespace::EnvironmentEffectsFilterPreset> environmentEffectsFilterDefaultPreset, ::System::Nullable_1<::GlobalNamespace::EnvironmentEffectsFilterPreset> environmentEffectsFilterExpertPlusPreset); // public EnvironmentEffectsFilterPreset GetEnvironmentEffectsFilterPreset(BeatmapDifficulty difficulty) // Offset: 0x1372D4C ::GlobalNamespace::EnvironmentEffectsFilterPreset GetEnvironmentEffectsFilterPreset(::GlobalNamespace::BeatmapDifficulty difficulty); // public System.Void .ctor() // Offset: 0x1372BB8 // Implemented from: System.Object // Base method: System.Void Object::.ctor() template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary> static PlayerSpecificSettings* New_ctor() { static auto ___internal__logger = ::Logger::get().WithContext("::GlobalNamespace::PlayerSpecificSettings::.ctor"); return THROW_UNLESS((::il2cpp_utils::New<PlayerSpecificSettings*, creationType>())); } }; // PlayerSpecificSettings #pragma pack(pop) static check_size<sizeof(PlayerSpecificSettings), 64 + sizeof(::GlobalNamespace::EnvironmentEffectsFilterPreset)> __GlobalNamespace_PlayerSpecificSettingsSizeCheck; static_assert(sizeof(PlayerSpecificSettings) == 0x44); } #include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" // Writing MetadataGetter for method: GlobalNamespace::PlayerSpecificSettings::get_leftHanded // Il2CppName: get_leftHanded template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (GlobalNamespace::PlayerSpecificSettings::*)()>(&GlobalNamespace::PlayerSpecificSettings::get_leftHanded)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::PlayerSpecificSettings*), "get_leftHanded", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: GlobalNamespace::PlayerSpecificSettings::get_playerHeight // Il2CppName: get_playerHeight template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<float (GlobalNamespace::PlayerSpecificSettings::*)()>(&GlobalNamespace::PlayerSpecificSettings::get_playerHeight)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::PlayerSpecificSettings*), "get_playerHeight", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: GlobalNamespace::PlayerSpecificSettings::get_automaticPlayerHeight // Il2CppName: get_automaticPlayerHeight template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (GlobalNamespace::PlayerSpecificSettings::*)()>(&GlobalNamespace::PlayerSpecificSettings::get_automaticPlayerHeight)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::PlayerSpecificSettings*), "get_automaticPlayerHeight", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: GlobalNamespace::PlayerSpecificSettings::get_sfxVolume // Il2CppName: get_sfxVolume template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<float (GlobalNamespace::PlayerSpecificSettings::*)()>(&GlobalNamespace::PlayerSpecificSettings::get_sfxVolume)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::PlayerSpecificSettings*), "get_sfxVolume", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: GlobalNamespace::PlayerSpecificSettings::get_reduceDebris // Il2CppName: get_reduceDebris template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (GlobalNamespace::PlayerSpecificSettings::*)()>(&GlobalNamespace::PlayerSpecificSettings::get_reduceDebris)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::PlayerSpecificSettings*), "get_reduceDebris", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: GlobalNamespace::PlayerSpecificSettings::get_noTextsAndHuds // Il2CppName: get_noTextsAndHuds template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (GlobalNamespace::PlayerSpecificSettings::*)()>(&GlobalNamespace::PlayerSpecificSettings::get_noTextsAndHuds)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::PlayerSpecificSettings*), "get_noTextsAndHuds", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: GlobalNamespace::PlayerSpecificSettings::get_noFailEffects // Il2CppName: get_noFailEffects template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (GlobalNamespace::PlayerSpecificSettings::*)()>(&GlobalNamespace::PlayerSpecificSettings::get_noFailEffects)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::PlayerSpecificSettings*), "get_noFailEffects", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: GlobalNamespace::PlayerSpecificSettings::get_advancedHud // Il2CppName: get_advancedHud template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (GlobalNamespace::PlayerSpecificSettings::*)()>(&GlobalNamespace::PlayerSpecificSettings::get_advancedHud)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::PlayerSpecificSettings*), "get_advancedHud", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: GlobalNamespace::PlayerSpecificSettings::get_autoRestart // Il2CppName: get_autoRestart template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (GlobalNamespace::PlayerSpecificSettings::*)()>(&GlobalNamespace::PlayerSpecificSettings::get_autoRestart)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::PlayerSpecificSettings*), "get_autoRestart", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: GlobalNamespace::PlayerSpecificSettings::get_saberTrailIntensity // Il2CppName: get_saberTrailIntensity template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<float (GlobalNamespace::PlayerSpecificSettings::*)()>(&GlobalNamespace::PlayerSpecificSettings::get_saberTrailIntensity)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::PlayerSpecificSettings*), "get_saberTrailIntensity", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: GlobalNamespace::PlayerSpecificSettings::get_noteJumpDurationTypeSettings // Il2CppName: get_noteJumpDurationTypeSettings template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::GlobalNamespace::NoteJumpDurationTypeSettings (GlobalNamespace::PlayerSpecificSettings::*)()>(&GlobalNamespace::PlayerSpecificSettings::get_noteJumpDurationTypeSettings)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::PlayerSpecificSettings*), "get_noteJumpDurationTypeSettings", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: GlobalNamespace::PlayerSpecificSettings::get_noteJumpFixedDuration // Il2CppName: get_noteJumpFixedDuration template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<float (GlobalNamespace::PlayerSpecificSettings::*)()>(&GlobalNamespace::PlayerSpecificSettings::get_noteJumpFixedDuration)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::PlayerSpecificSettings*), "get_noteJumpFixedDuration", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: GlobalNamespace::PlayerSpecificSettings::get_noteJumpStartBeatOffset // Il2CppName: get_noteJumpStartBeatOffset template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<float (GlobalNamespace::PlayerSpecificSettings::*)()>(&GlobalNamespace::PlayerSpecificSettings::get_noteJumpStartBeatOffset)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::PlayerSpecificSettings*), "get_noteJumpStartBeatOffset", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: GlobalNamespace::PlayerSpecificSettings::get_hideNoteSpawnEffect // Il2CppName: get_hideNoteSpawnEffect template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (GlobalNamespace::PlayerSpecificSettings::*)()>(&GlobalNamespace::PlayerSpecificSettings::get_hideNoteSpawnEffect)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::PlayerSpecificSettings*), "get_hideNoteSpawnEffect", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: GlobalNamespace::PlayerSpecificSettings::get_adaptiveSfx // Il2CppName: get_adaptiveSfx template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (GlobalNamespace::PlayerSpecificSettings::*)()>(&GlobalNamespace::PlayerSpecificSettings::get_adaptiveSfx)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::PlayerSpecificSettings*), "get_adaptiveSfx", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: GlobalNamespace::PlayerSpecificSettings::get_environmentEffectsFilterDefaultPreset // Il2CppName: get_environmentEffectsFilterDefaultPreset template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::GlobalNamespace::EnvironmentEffectsFilterPreset (GlobalNamespace::PlayerSpecificSettings::*)()>(&GlobalNamespace::PlayerSpecificSettings::get_environmentEffectsFilterDefaultPreset)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::PlayerSpecificSettings*), "get_environmentEffectsFilterDefaultPreset", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: GlobalNamespace::PlayerSpecificSettings::get_environmentEffectsFilterExpertPlusPreset // Il2CppName: get_environmentEffectsFilterExpertPlusPreset template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::GlobalNamespace::EnvironmentEffectsFilterPreset (GlobalNamespace::PlayerSpecificSettings::*)()>(&GlobalNamespace::PlayerSpecificSettings::get_environmentEffectsFilterExpertPlusPreset)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::PlayerSpecificSettings*), "get_environmentEffectsFilterExpertPlusPreset", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: GlobalNamespace::PlayerSpecificSettings::New_ctor // Il2CppName: .ctor // Cannot get method pointer of value based method overload from template for constructor! // Try using FindMethod instead! // Writing MetadataGetter for method: GlobalNamespace::PlayerSpecificSettings::CopyWith // Il2CppName: CopyWith template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::GlobalNamespace::PlayerSpecificSettings* (GlobalNamespace::PlayerSpecificSettings::*)(::System::Nullable_1<bool>, ::System::Nullable_1<float>, ::System::Nullable_1<bool>, ::System::Nullable_1<float>, ::System::Nullable_1<bool>, ::System::Nullable_1<bool>, ::System::Nullable_1<bool>, ::System::Nullable_1<bool>, ::System::Nullable_1<bool>, ::System::Nullable_1<float>, ::System::Nullable_1<::GlobalNamespace::NoteJumpDurationTypeSettings>, ::System::Nullable_1<float>, ::System::Nullable_1<float>, ::System::Nullable_1<bool>, ::System::Nullable_1<bool>, ::System::Nullable_1<::GlobalNamespace::EnvironmentEffectsFilterPreset>, ::System::Nullable_1<::GlobalNamespace::EnvironmentEffectsFilterPreset>)>(&GlobalNamespace::PlayerSpecificSettings::CopyWith)> { static const MethodInfo* get() { static auto* leftHanded = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System", "Nullable`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("System", "Boolean")})->byval_arg; static auto* playerHeight = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System", "Nullable`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("System", "Single")})->byval_arg; static auto* automaticPlayerHeight = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System", "Nullable`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("System", "Boolean")})->byval_arg; static auto* sfxVolume = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System", "Nullable`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("System", "Single")})->byval_arg; static auto* reduceDebris = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System", "Nullable`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("System", "Boolean")})->byval_arg; static auto* noTextsAndHuds = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System", "Nullable`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("System", "Boolean")})->byval_arg; static auto* noFailEffects = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System", "Nullable`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("System", "Boolean")})->byval_arg; static auto* advancedHud = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System", "Nullable`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("System", "Boolean")})->byval_arg; static auto* autoRestart = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System", "Nullable`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("System", "Boolean")})->byval_arg; static auto* saberTrailIntensity = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System", "Nullable`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("System", "Single")})->byval_arg; static auto* noteJumpDurationTypeSettings = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System", "Nullable`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("", "NoteJumpDurationTypeSettings")})->byval_arg; static auto* noteJumpFixedDuration = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System", "Nullable`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("System", "Single")})->byval_arg; static auto* noteJumpStartBeatOffset = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System", "Nullable`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("System", "Single")})->byval_arg; static auto* hideNoteSpawnEffect = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System", "Nullable`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("System", "Boolean")})->byval_arg; static auto* adaptiveSfx = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System", "Nullable`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("System", "Boolean")})->byval_arg; static auto* environmentEffectsFilterDefaultPreset = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System", "Nullable`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("", "EnvironmentEffectsFilterPreset")})->byval_arg; static auto* environmentEffectsFilterExpertPlusPreset = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System", "Nullable`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("", "EnvironmentEffectsFilterPreset")})->byval_arg; return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::PlayerSpecificSettings*), "CopyWith", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{leftHanded, playerHeight, automaticPlayerHeight, sfxVolume, reduceDebris, noTextsAndHuds, noFailEffects, advancedHud, autoRestart, saberTrailIntensity, noteJumpDurationTypeSettings, noteJumpFixedDuration, noteJumpStartBeatOffset, hideNoteSpawnEffect, adaptiveSfx, environmentEffectsFilterDefaultPreset, environmentEffectsFilterExpertPlusPreset}); } }; // Writing MetadataGetter for method: GlobalNamespace::PlayerSpecificSettings::GetEnvironmentEffectsFilterPreset // Il2CppName: GetEnvironmentEffectsFilterPreset template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::GlobalNamespace::EnvironmentEffectsFilterPreset (GlobalNamespace::PlayerSpecificSettings::*)(::GlobalNamespace::BeatmapDifficulty)>(&GlobalNamespace::PlayerSpecificSettings::GetEnvironmentEffectsFilterPreset)> { static const MethodInfo* get() { static auto* difficulty = &::il2cpp_utils::GetClassFromName("", "BeatmapDifficulty")->byval_arg; return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::PlayerSpecificSettings*), "GetEnvironmentEffectsFilterPreset", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{difficulty}); } }; // Writing MetadataGetter for method: GlobalNamespace::PlayerSpecificSettings::New_ctor // Il2CppName: .ctor // Cannot get method pointer of value based method overload from template for constructor! // Try using FindMethod instead!
32,004
10,070
#include "ConfirmQuitCommandProcessor.h" void ConfirmQuitCommandProcessor::OnCommand(const Command& command) { switch (command) { case Command::UP: case Command::DOWN: confirmState = (confirmState==ConfirmState::YES) ? (ConfirmState::NO) : (ConfirmState::YES); return; case Command::BACK: SetUIState(UIState::MAIN_MENU); return; case Command::GREEN: switch (confirmState) { case ConfirmState::YES: SetUIState(UIState::QUIT); return; case ConfirmState::NO: SetUIState(UIState::MAIN_MENU); return; default: return; } } } ConfirmQuitCommandProcessor::ConfirmQuitCommandProcessor ( UIState& uiState, ConfirmState& confirmState ) : BaseCommandProcessor(uiState) , confirmState(confirmState) { }
741
289
#pragma once #include "pch.h" #include "./batch_file_adapter.h" #include "../../exception/unsupported_operation_exception.h" // NewAdapter is the constructor for Adapter. BatchFileAdapter* BatchFileAdapter :: NewAdapter(string file_path) { BatchFileAdapter* adapter = new BatchFileAdapter; adapter->file_path = file_path; adapter->filtered = false; return adapter; } void BatchFileAdapter :: AddPolicies(string sec, string p_type, vector<vector<string>> rules) { throw UnsupportedOperationException("not implemented hello"); } void BatchFileAdapter :: RemovePolicies(string sec, string p_type, vector<vector<string>> rules) { throw UnsupportedOperationException("not implemented"); }
712
205
// Copyright (c) 2009 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. // This is a simple allocator based on the windows heap. extern "C" { HANDLE win_heap; bool win_heap_init(bool use_lfh) { win_heap = HeapCreate(0, 0, 0); if (win_heap == NULL) return false; if (use_lfh) { ULONG enable_lfh = 2; HeapSetInformation(win_heap, HeapCompatibilityInformation, &enable_lfh, sizeof(enable_lfh)); // NOTE: Setting LFH may fail. Vista already has it enabled. // And under the debugger, it won't use LFH. So we // ignore any errors. } return true; } void* win_heap_malloc(size_t size) { return HeapAlloc(win_heap, 0, size); } void win_heap_free(void* size) { HeapFree(win_heap, 0, size); } void* win_heap_realloc(void* ptr, size_t size) { if (!ptr) return win_heap_malloc(size); if (!size) { win_heap_free(ptr); return NULL; } return HeapReAlloc(win_heap, 0, ptr, size); } size_t win_heap_msize(void* ptr) { return HeapSize(win_heap, 0, ptr); } } // extern "C"
1,160
469
#include <math.h> #include <stdlib.h> #include <stdio.h> #include <memory.h> #include <string.h> #include "math/mmath.h" #include "AudioDef.h" #include "AudioUtil.h" #include "AudioRecog.h" #include "AudioConfig.h" /* signal normalization */ void sig_normalize( AUD_Int16s *pInBuf, AUD_Int16s *pOutBuf, AUD_Int32s len ) { AUD_Int32s i, v; AUD_Double mean = 0; for ( i = 0; i < len; i++ ) { mean += pInBuf[i]; } mean /= len; for ( i = 0; i < len; i++ ) { v = (AUD_Int32s)round( pInBuf[i] - mean ); v = SATURATE_16s( v ); pOutBuf[i] = (AUD_Int16s)v; } #if 1 AUD_Double x = 0; AUD_Double tmp; for ( i = 0; i < len; i++ ) { x += (AUD_Double)pOutBuf[i] * pOutBuf[i]; } x /= len; // x = sqrt( x ); if ( x < 1024 ) { for ( i = 0; i < len; i++ ) { // tmp = pOutBuf[i] / x * 8192; tmp = pOutBuf[i] * 256; tmp = SATURATE_16s( tmp ); pOutBuf[i] = (AUD_Int16s)tmp; } } #endif #if 0 AUD_Int16s maxMag = 0, mag = 0; for ( i = 0; i < len; i++ ) { mag = abs( pOutBuf[i] ); if ( maxMag < mag ) { maxMag = mag; } } for ( i = 0; i < len; i++ ) { pOutBuf[i] = (AUD_Int16s)( (AUD_Double)pOutBuf[i] / maxMag * 0.25 * 32768. ); } #endif return; } /* signal pre-emphasis */ void sig_preemphasis( AUD_Int16s *pInBuf, AUD_Int16s *pOutBuf, AUD_Int32s len ) { AUD_Int16s x0, x1; AUD_Double out; AUD_Int32s i; x1 = pInBuf[0]; for ( i = 1; i < len; i++ ) { x0 = pInBuf[i]; out = x0 - PREEMPHASIS_FACTOR * x1; out = SATURATE_16s( out ); pOutBuf[i] = (AUD_Int16s)out; x1 = x0; } pOutBuf[0] = (AUD_Int16s)( ( 1 - PREEMPHASIS_FACTOR ) * pInBuf[0] ); return; } /* signal de-emphasis */ void sig_deemphasis( AUD_Int16s *pInBuf, AUD_Int16s *pOutBuf, AUD_Int32s len ) { AUD_Int16s y1; AUD_Double out; AUD_Int32s i; y1 = 0; for ( i = 0; i < len; i++ ) { out = pInBuf[i] + PREEMPHASIS_FACTOR * y1; out = SATURATE_16s( out ); pOutBuf[i] = (AUD_Int16s)out; y1 = pOutBuf[i]; } return; }
2,290
1,131
// Copyright (C) 2013-2015 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/. /// @file /// @brief Full callout library /// /// This is source of a test library for various test (LibraryManager and /// HooksManager). The characteristics of the library produced from this /// file are: /// /// The characteristics of this library are: /// /// - All three framework functions are supplied (version(), load() and /// unload()), with unload() creating a marker file. The test code checks /// for the presence of this file, so verifying that unload() has been run. /// /// - One standard and two non-standard callouts are supplied, with the latter /// being registered by the load() function. /// /// All callouts do trivial calculations, the result of all being called in /// sequence being /// /// @f[ ((7 * data_1) - data_2) * data_3 @f] /// /// ...where data_1, data_2 and data_3 are the values passed in arguments of /// the same name to the three callouts (data_1 passed to hookpt_one, data_2 /// to hookpt_two etc.) and the result is returned in the argument "result". #include <config.h> #include <hooks/hooks.h> #include <hooks/tests/marker_file.h> #include <fstream> using namespace isc::hooks; extern "C" { // Callouts int context_create(CalloutHandle& handle) { handle.setContext("result", static_cast<int>(7)); handle.setArgument("result", static_cast<int>(7)); return (0); } // First callout adds the passed "data_1" argument to the initialized context // value of 7. (Note that the value set by context_create is accessed through // context and not the argument, so checking that context is correctly passed // between callouts in the same library.) int hookpt_one(CalloutHandle& handle) { int data; handle.getArgument("data_1", data); int result; handle.getArgument("result", result); result *= data; handle.setArgument("result", result); return (0); } // Second callout subtracts the passed value of data_2 from the current // running total. static int hook_nonstandard_two(CalloutHandle& handle) { int data; handle.getArgument("data_2", data); int result; handle.getArgument("result", result); result -= data; handle.setArgument("result", result); return (0); } // Final callout multiplies the current running total by data_3. static int hook_nonstandard_three(CalloutHandle& handle) { int data; handle.getArgument("data_3", data); int result; handle.getArgument("result", result); result *= data; handle.setArgument("result", result); return (0); } // Framework functions int version() { return (KEA_HOOKS_VERSION); } int load(LibraryHandle& handle) { // Initialize if the main image was statically linked #ifdef USE_STATIC_LINK hooksStaticLinkInit(); #endif // Register the non-standard functions handle.registerCallout("hookpt_two", hook_nonstandard_two); handle.registerCallout("hookpt_three", hook_nonstandard_three); return (0); } int unload() { // Create the marker file. std::fstream marker; marker.open(MARKER_FILE, std::fstream::out); marker.close(); return (0); } };
3,382
1,033
#include <render_toy.h> #include <ROOT_PATH.h> using namespace platinum; using namespace glm; using namespace std; const static string root_path(ROOT_PATH); const static string assets_path = root_path + "/assets/"; void random_scene(Scene &world) { int n = 500; shared_ptr<Object> sph; sph = make_shared<Sphere>(vec3(0, -1000, 0), 1000, make_shared<Lambertian>(vec3(0.5, 0.5, 0.5))); world.AddObject(sph); int i = 1; for (int a = -11; a < 11; a++) { for (int b = -11; b < 11; b++) { float choose_mat = Random::RandomInUnitFloat(); vec3 center(a + 0.9 * Random::RandomInUnitFloat(), 0.2, b + 0.9 * Random::RandomInUnitFloat()); if (length(center - vec3(4, 0.2, 0)) > 0.9) { if (choose_mat < 0.8) { // diffuse sph = make_shared<MovingSphere>(center, center + vec3(0, 0.5 * Random::RandomInUnitFloat(), 0), 0.0, 1.0, 0.2, make_shared<Lambertian>(vec3(Random::RandomInUnitFloat() * Random::RandomInUnitFloat(), Random::RandomInUnitFloat() * Random::RandomInUnitFloat(), Random::RandomInUnitFloat() * Random::RandomInUnitFloat()))); } else if (choose_mat < 0.95) { // metal sph = make_shared<Sphere>(center, 0.2f, make_shared<Metal>(vec3(0.5 * (1 + Random::RandomInUnitFloat()), 0.5 * (1 + Random::RandomInUnitFloat()), 0.5 * (1 + Random::RandomInUnitFloat())), 0.5 * Random::RandomInUnitFloat())); } else { // glass sph = make_shared<Sphere>(center, 0.2f, make_shared<Dielectric>(1.5)); } world.AddObject(sph); } } } world.AddObject(make_shared<Sphere>(vec3(0, 1, 0), 1.0, make_shared<Dielectric>(1.5))); world.AddObject(make_shared<Sphere>(vec3(-4, 1, 0), 1.0, make_shared<Lambertian>(vec3(0.4, 0.2, 0.1)))); world.AddObject(make_shared<Sphere>(vec3(4, 1, 0), 1.0, make_shared<Metal>(vec3(0.7, 0.6, 0.5), 0.0))); } int main() { int nx = 1200; int ny = 800; int ns = 100; Scene world(true,false); random_scene(world); vec3 lookfrom(13, 2, 3); vec3 lookat(0, 0, 0); float dist_to_focus = 10.0f; float aperture = 0.1f; Camera cam(lookfrom, lookat, vec3(0, -1, 0), 45, static_cast<float>(nx) / static_cast<float>(ny), aperture, dist_to_focus); Renderer render(nx, ny, 3, "motion.png", ns); render.Render(world, cam); world.Reset(); return 0; }
3,167
1,047
// // Created by nhy20 on 2020-11-01. // #include "LuaCommandViewer.h" #include "imgui.h" void LuaCommandViewer::Render(std::shared_ptr<Base::Interface::Provider> provider_ptr, std::shared_ptr<UI::Structure::UIEventProtocol> protocol_ptr) { ImGui::Begin("Lua Command Viewer"); if (ImGui::Button("Reload")) { protocol_ptr->AddEvent("Lua:Reload"); } if (ImGui::Button("Execute")) { protocol_ptr->AddEvent("Lua:Execute"); } ImGui::End(); }
463
199
#pragma once #ifndef BASICCAMERACONTROLLER_HPP #define BASICCAMERACONTROLLER_HPP #include "../World/World.hpp" #include "../Platform/KeyCodes.hpp" namespace Mona { class BasicPerspectiveCamera : public GameObject { public: BasicPerspectiveCamera() = default; virtual void UserStartUp(World& world) noexcept override { m_transform = world.AddComponent<TransformComponent>(*this); m_camera = world.AddComponent<CameraComponent>(*this); m_transform->Translate(glm::vec3(0.0f, -5.0f, 0.0f)); auto& input = world.GetInput(); glm::vec2 res = world.GetWindow().GetWindowDimensions(); screenPos = glm::vec2(1 / res.x, 1 / res.y) * glm::vec2(input.GetMousePosition()); } void SetActive(bool active) { m_active = active; } virtual void UserUpdate(World& world, float timeStep) noexcept override { auto& input = world.GetInput(); if(m_active) { if (input.IsKeyPressed(MONA_KEY_A)) { glm::vec3 right = m_transform->GetRightVector(); m_transform->Translate(-m_cameraSpeed * timeStep * right); } else if (input.IsKeyPressed(MONA_KEY_D)) { glm::vec3 right = m_transform->GetRightVector(); m_transform->Translate(m_cameraSpeed * timeStep * right); } if (input.IsKeyPressed(MONA_KEY_W)) { glm::vec3 front = m_transform->GetFrontVector(); m_transform->Translate(m_cameraSpeed * timeStep * front); } else if (input.IsKeyPressed(MONA_KEY_S)) { glm::vec3 front = m_transform->GetFrontVector(); m_transform->Translate(-m_cameraSpeed * timeStep * front); } if (input.IsKeyPressed(MONA_KEY_E)) { m_transform->Rotate(glm::vec3(0.0f,1.0f,0.0f), m_rollSpeed * timeStep); } else if (input.IsKeyPressed(MONA_KEY_Q)) { m_transform->Rotate(glm::vec3(0.0f, 1.0f, 0.0f), -m_rollSpeed * timeStep); } } glm::vec2 res = world.GetWindow().GetWindowDimensions(); glm::vec2 newScreenPos = glm::vec2(1/res.x, 1/res.y) * glm::vec2(input.GetMousePosition()); glm::vec2 delta = newScreenPos - screenPos; if (glm::length2(delta) != 0.0f && m_active) { float amountX = delta.x * m_rotationSpeed; float amountY = delta.y * m_rotationSpeed; m_transform->Rotate(glm::vec3(0.0f,0.0f,-1.0f), amountX); m_transform->Rotate(glm::vec3(-1.0, 0.0f, 0.0f), amountY); } screenPos = newScreenPos; } private: bool m_active = true; float m_cameraSpeed = 2.0f; float m_rollSpeed = 1.5f; float m_rotationSpeed = 1.5f; TransformHandle m_transform; CameraHandle m_camera; glm::vec2 screenPos; }; } #endif
2,599
1,100
// // Created by Cheng Li on 17-12-19. // #pragma once #include <cassert> #include <dal/utilities/noncopyable.hpp> #include <memory> #include <utility> #ifdef MIN #undef MIN #endif #ifdef MAX #undef MAX #endif using std::make_pair; using std::pair; template <class T_> using scoped_ptr = const std::unique_ptr<T_>; namespace Dal { using Time_ = double; template <class = double> class Vector_; template <class = double> class Matrix_; template <class = double> class SquareMatrix_; class Dictionary_; constexpr const double EPSILON = 2e-14; constexpr const double INF = 1e29; constexpr const double PI = 3.1415926535897932; constexpr const double M_SQRT_2 = 1.4142135623730951; template <class T_> inline bool IsZero(const T_& x) { return x < Dal::EPSILON && -x < Dal::EPSILON; } template <class T_> inline bool IsPositive(const T_& x) { return x >= Dal::EPSILON; } template <class T_> inline bool IsNegative(const T_& x) { return x <= -Dal::EPSILON; } template <class T_> inline T_ Square(const T_& x) { return x * x; } template <class T_> inline T_ Cube(const T_& x) { return x * x * x; } template <class T_> inline T_ Max(const T_& a, const T_& b) { return a > b ? a : b; } template <class T_> inline T_ Min(const T_& a, const T_& b) { return a < b ? a : b; } struct Empty_ {}; template <class T_> class Handle_ : public std::shared_ptr<const T_> { typedef typename std::shared_ptr<const T_> base_t; public: Handle_() : base_t() {} explicit Handle_(const T_* src) : base_t(src) {} explicit Handle_(const base_t& src) : base_t(src) {} bool IsEmpty() const { return !base_t::get(); } }; template <class T_, class U_> Handle_<T_> handle_cast(const std::shared_ptr<U_>& src) { return Handle_<T_>(std::dynamic_pointer_cast<const T_>(src)); }; } // namespace Dal #define RETURN_STATIC(...) \ static __VA_ARGS__ RETVAL; \ return RETVAL #define DYN_PTR(n, t, s) t* n = dynamic_cast<t*>(s) #define LENGTH(a) (sizeof(a) / sizeof(a[0])) #define VALUE_TYPE_OF(expr) std::remove_const_t<std::remove_reference_t<decltype(expr)>>
2,372
853
// // Copyright (c) 2017 The Khronos Group 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 "harness/compat.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <sys/stat.h> #include "procs.h" static const char *rgba16_write_kernel_code = "__kernel void test_rgba16_write(__global unsigned short *src, write_only image2d_t dstimg)\n" "{\n" " int tid_x = get_global_id(0);\n" " int tid_y = get_global_id(1);\n" " int indx = tid_y * get_image_width(dstimg) + tid_x;\n" " float4 color;\n" "\n" " indx *= 4;\n" " color = (float4)((float)src[indx+0], (float)src[indx+1], (float)src[indx+2], (float)src[indx+3]);\n" " color /= 65535.0f;\n" " write_imagef(dstimg, (int2)(tid_x, tid_y), color);\n" "\n" "}\n"; static unsigned short * generate_16bit_image(int w, int h, MTdata d) { cl_ushort *ptr = (cl_ushort*)malloc(w * h * 4 * sizeof(cl_ushort)); int i; for (i=0; i<w*h*4; i++) ptr[i] = (cl_ushort)genrand_int32(d); return ptr; } // normalized 16bit ints ... get dived by 64k then muled by 64k... // give the poor things some tolerance #define MAX_ERR 1 static int verify_16bit_image(const char *string, cl_ushort *image, cl_ushort *outptr, int w, int h) { int i; for (i=0; i<w*h*4; i++) { if (abs(outptr[i] - image[i]) > MAX_ERR) { log_error("%s failed\n", string); return -1; } } log_info("%s passed\n", string); return 0; } int test_writeimage_int16(cl_device_id device, cl_context context, cl_command_queue queue, int num_elements) { cl_mem streams[3]; cl_program program; cl_kernel kernel[2]; cl_image_format img_format; cl_ushort *input_ptr, *output_ptr; size_t threads[2]; int img_width = 512; int img_height = 512; int i, err, any_err = 0; size_t origin[3] = {0, 0, 0}; size_t region[3] = {img_width, img_height, 1}; size_t length = img_width * img_height * 4 * sizeof(cl_ushort); PASSIVE_REQUIRE_IMAGE_SUPPORT( device ) MTdata d = init_genrand( gRandomSeed ); input_ptr = generate_16bit_image(img_width, img_height, d); free_mtdata(d); d = NULL; output_ptr = (cl_ushort*)malloc(length); img_format.image_channel_order = CL_RGBA; img_format.image_channel_data_type = CL_UNORM_INT16; streams[0] = create_image_2d(context, CL_MEM_READ_WRITE, &img_format, img_width, img_height, 0, NULL, NULL); if (!streams[0]) { log_error("create_image_2d failed\n"); return -1; } img_format.image_channel_order = CL_RGBA; img_format.image_channel_data_type = CL_UNORM_INT16; streams[1] = create_image_2d(context, CL_MEM_WRITE_ONLY, &img_format, img_width, img_height, 0, NULL, NULL); if (!streams[1]) { log_error("create_image_2d failed\n"); return -1; } streams[2] = clCreateBuffer(context, CL_MEM_READ_WRITE, length, NULL, NULL); if (!streams[2]) { log_error("clCreateArray failed\n"); return -1; } err = clEnqueueWriteBuffer(queue, streams[2], CL_TRUE, 0, length, input_ptr, 0, NULL, NULL); if (err != CL_SUCCESS) { log_error("clEnqueueWriteBuffer failed\n"); return -1; } err = create_single_kernel_helper(context, &program, &kernel[0], 1, &rgba16_write_kernel_code, "test_rgba16_write" ); if (err) return -1; kernel[1] = clCreateKernel(program, "test_rgba16_write", NULL); if (!kernel[1]) { log_error("clCreateKernel failed\n"); return -1; } err = clSetKernelArg(kernel[0], 0, sizeof streams[2], &streams[2]); err |= clSetKernelArg(kernel[0], 1, sizeof streams[0], &streams[0]); if (err != CL_SUCCESS) { log_error("clSetKernelArgs failed\n"); return -1; } err = clSetKernelArg(kernel[1], 0, sizeof streams[2], &streams[2]); err |= clSetKernelArg(kernel[1], 1, sizeof streams[1], &streams[1]); if (err != CL_SUCCESS) { log_error("clSetKernelArgs failed\n"); return -1; } threads[0] = (unsigned int)img_width; threads[1] = (unsigned int)img_height; for (i=0; i<2; i++) { err = clEnqueueNDRangeKernel(queue, kernel[i], 2, NULL, threads, NULL, 0, NULL, NULL); if (err != CL_SUCCESS) { log_error("clExecuteKernel failed\n"); return -1; } err = clEnqueueReadImage(queue, streams[i], CL_TRUE, origin, region, 0, 0, output_ptr, 0, NULL, NULL); if (err != CL_SUCCESS) { log_error("clReadImage failed\n"); return -1; } err = verify_16bit_image((i == 0) ? "WRITE_IMAGE_RGBA_UNORM_INT16 test with memflags = CL_MEM_READ_WRITE" : "WRITE_IMAGE_RGBA_UNORM_INT16 test with memflags = CL_MEM_WRITE_ONLY", input_ptr, output_ptr, img_width, img_height); any_err |= err; } // cleanup clReleaseMemObject(streams[0]); clReleaseMemObject(streams[1]); clReleaseMemObject(streams[2]); clReleaseKernel(kernel[0]); clReleaseKernel(kernel[1]); clReleaseProgram(program); free(input_ptr); free(output_ptr); return any_err; }
5,812
2,215
/* Copyright 2017 R. Thomas * Copyright 2017 Quarkslab * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef LIEF_ABSTRACT_JSON_H_ #define LIEF_ABSTRACT_JSON_H_ #include "LIEF/config.h" #ifdef LIEF_JSON_SUPPORT #include "LIEF/visibility.h" #include "LIEF/visitors/json.hpp" #include "LIEF/Abstract.hpp" namespace LIEF { LIEF_API json to_json_from_abstract(const Object& v); LIEF_API std::string to_json_str_from_abstract(const Object& v); class LIEF_API AbstractJsonVisitor : public LIEF::JsonVisitor { public: using LIEF::JsonVisitor::JsonVisitor; public: virtual void visit(const Binary& binary) override; virtual void visit(const Header& header) override; virtual void visit(const Section& section) override; virtual void visit(const Symbol& symbol) override; virtual void visit(const Relocation& relocation) override; virtual void visit(const Function& f) override; }; } #endif // LIEF_JSON_SUPPORT #endif
1,497
485
/*********** ROS_Helpers.cpp James Watson , 2018 June Common ROS Functions & Tasks Template Version: 2017-09-23 ***********/ #include "ROS_Helpers.h" // === Classes and Structs ================================================================================================================= // ___ End Classes _________________________________________________________________________________________________________________________ // === Functions =========================================================================================================================== void ros_log( string msg , LogLevel level ){ switch( level ) { case WARN : { ROS_WARN_STREAM( msg ); break; } case ERROR : { ROS_ERROR_STREAM( msg ); break; } default: { ROS_INFO_STREAM( msg ); break; } } } // ___ End Func ____________________________________________________________________________________________________________________________ /* === Spare Parts ========================================================================================================================= ___ End Parts ___________________________________________________________________________________________________________________________ */
1,333
309
#include "Precomp_OpenGL.h" #include "Simulation.hpp" #include "Resources.hpp" #include "ParamUtils.hpp" #include "ocl/OCLUtils.hpp" #include "SOIL.h" #define _USE_MATH_DEFINES #include <math.h> #include <cmath> #include <sstream> #include <algorithm> using namespace std; cl::Memory Simulation::CreateCachedBuffer(cl::ImageFormat& format, int elements) { if (format.image_channel_order != CL_RGBA) throw "Image type is not supported"; // Choose what type should be created if (Params.EnableCachedBuffers) return cl::Image2D(mCLContext, CL_MEM_READ_WRITE, format, 2048, DivCeil(elements, 2048)); else return cl::Buffer(mCLContext, CL_MEM_READ_WRITE, elements * sizeof(float) * 4); } void OCL_InitMemory(cl::CommandQueue& queue, cl::Memory& mem, void* pData = NULL, int nDataSize = 0) { // Get buffer size int memSize = mem.getInfo<CL_MEM_SIZE>(); // Create memory char* pBuf = new char[memSize]; memset(pBuf, 0, memSize); // Fill with data if ((pData != NULL) && (nDataSize > 0)) for (int i = 0; i < memSize; i++) pBuf[i] = ((char*)pData)[i % nDataSize]; // Choose the way to transfer the data switch (mem.getInfo<CL_MEM_TYPE>()) { case CL_MEM_OBJECT_BUFFER: queue.enqueueWriteBuffer(*((cl::Buffer*)&mem), CL_TRUE, 0, memSize, pBuf); break; } // Release memory delete[] pBuf; } Simulation::Simulation(const cl::Context &clContext, const cl::Device &clDevice) : mCLContext(clContext), mCLDevice(clDevice), bDumpParticlesData(false) { // Create Queue mQueue = cl::CommandQueue(mCLContext, mCLDevice, CL_QUEUE_PROFILING_ENABLE); } Simulation::~Simulation() { glFinish(); mQueue.finish(); } void Simulation::CreateParticles() { // Create buffers cl_float4* positions = new cl_float4[Params.particleCount]; // Compute particle count per axis int ParticlesPerAxis = (int)ceil(pow(Params.particleCount, 1 / 3.0)); // Build particles blcok float d = Params.h * Params.setupSpacing; float offsetX = (1.0f - ParticlesPerAxis * d) / 2.0f; float offsetY = 0.3f; float offsetZ = (1.0f - ParticlesPerAxis * d) / 2.0f; for (cl_uint i = 0; i < Params.particleCount; i++) { cl_uint x = ((cl_uint)(i / pow(ParticlesPerAxis, 1)) % ParticlesPerAxis); cl_uint y = ((cl_uint)(i / pow(ParticlesPerAxis, 0)) % ParticlesPerAxis); cl_uint z = ((cl_uint)(i / pow(ParticlesPerAxis, 2)) % ParticlesPerAxis); positions[i].s[0] = offsetX + (x /*+ (y % 2) * .5*/) * d; positions[i].s[1] = offsetY + (y) * d; positions[i].s[2] = offsetZ + (z /*+ (y % 2) * .5*/) * d; positions[i].s[3] = 0; } // Copy data from Host to GPU OCL_InitMemory(mQueue, mPositionsPingBuffer, positions , sizeof(positions[0]) * Params.particleCount); OCL_InitMemory(mQueue, mVelocitiesBuffer); delete[] positions; } const std::string *Simulation::KernelFileList() { static const std::string kernels[] = { "hesp.hpp", "parameters.hpp", "logging.cl", "utilities.cl", "predict_positions.cl", "update_cells.cl", "build_friends_list.cl", "reset_grid.cl", "compute_scaling.cl", "compute_delta.cl", "update_predicted.cl", "pack_data.cl", "update_velocities.cl", "apply_viscosity.cl", "apply_vorticity.cl", "radixsort.cl", "" }; return kernels; } bool Simulation::InitKernels() { // Setup OpenCL Ranges const cl_uint globalSize = (cl_uint)ceil(Params.particleCount / 32.0f) * 32; mGlobalRange = cl::NDRange(globalSize); mLocalRange = cl::NullRange; // Notify OCL logging that we're about to start new kernel processing oclLog.StartKernelProcessing(mCLContext, mCLDevice, 4096); // setup kernel sources OCLUtils clSetup; vector<string> kernelSources; // Load kernel sources const std::string *pKernels = KernelFileList(); for (int iSrc = 0; pKernels[iSrc] != ""; iSrc++) { // Read source from disk string source = getKernelSource(pKernels[iSrc]); // Patch kernel for logging if (pKernels[iSrc] != "logging.cl") source = oclLog.PatchKernel(source); // Load into compile list kernelSources.push_back(source); } // Setup kernel compiler flags std::ostringstream clflags; clflags << "-cl-mad-enable -cl-no-signed-zeros -cl-fast-relaxed-math "; // Vendor related flags string devVendor = mCLDevice.getInfo<CL_DEVICE_VENDOR>(); if (devVendor.find("NVIDIA") != std::string::npos) clflags << "-cl-nv-verbose "; clflags << std::showpoint; clflags << "-DLOG_SIZE=" << (int)1024 << " "; clflags << "-DEND_OF_CELL_LIST=" << (int)(-1) << " "; clflags << "-DMAX_PARTICLES_COUNT=" << (int)(Params.particleCount) << " "; clflags << "-DMAX_FRIENDS_CIRCLES=" << (int)(Params.friendsCircles) << " "; clflags << "-DMAX_FRIENDS_IN_CIRCLE=" << (int)(Params.particlesPerCircle) << " "; clflags << "-DFRIENDS_BLOCK_SIZE=" << (int)(Params.particleCount * Params.friendsCircles) << " "; clflags << "-DGRID_BUF_SIZE=" << (int)(Params.gridBufSize) << " "; clflags << "-DPOLY6_FACTOR=" << 315.0f / (64.0f * M_PI * pow(Params.h, 9)) << "f "; clflags << "-DGRAD_SPIKY_FACTOR=" << 45.0f / (M_PI * pow(Params.h, 6)) << "f "; if (Params.EnableCachedBuffers) clflags << "-DENABLE_CACHED_BUFFERS "; // Compile kernels cl::Program program = clSetup.createProgram(kernelSources, mCLContext, mCLDevice, clflags.str()); if (program() == 0) return false; // save BuildLog string buildLog = program.getBuildInfo<CL_PROGRAM_BUILD_LOG>(mCLDevice); ofstream f("build.log", ios::out | ios::trunc); f << buildLog; f.close(); // Build kernels table mKernels = clSetup.createKernelsMap(program); // Write kernel info cout << "CL_KERNEL_WORK_GROUP_SIZE=" << mKernels["computeDelta"].getWorkGroupInfo<CL_KERNEL_WORK_GROUP_SIZE>(mCLDevice) << endl; cout << "CL_KERNEL_LOCAL_MEM_SIZE =" << mKernels["computeDelta"].getWorkGroupInfo<CL_KERNEL_LOCAL_MEM_SIZE>(mCLDevice) << endl; return true; } void Simulation::InitBuffers() { // Create buffers mPositionsPingBuffer = cl::BufferGL(mCLContext, CL_MEM_READ_WRITE, mSharedPingBufferID); // buffer could be changed to be CL_MEM_WRITE_ONLY but for debugging also reading it might be helpful mPositionsPongBuffer = cl::BufferGL(mCLContext, CL_MEM_READ_WRITE, mSharedPongBufferID); // buffer could be changed to be CL_MEM_WRITE_ONLY but for debugging also reading it might be helpful mParticlePosImg = cl::Image2DGL(mCLContext, CL_MEM_READ_WRITE, GL_TEXTURE_2D, 0, mSharedParticlesPos); mPredictedPingBuffer = CreateCachedBuffer(cl::ImageFormat(CL_RGBA, CL_FLOAT), Params.particleCount); mPredictedPongBuffer = CreateCachedBuffer(cl::ImageFormat(CL_RGBA, CL_FLOAT), Params.particleCount); mVelocitiesBuffer = cl::Buffer(mCLContext, CL_MEM_READ_WRITE, Params.particleCount * sizeof(cl_float4)); mDeltaBuffer = cl::Buffer(mCLContext, CL_MEM_READ_WRITE, Params.particleCount * sizeof(cl_float4)); mOmegaBuffer = cl::Buffer(mCLContext, CL_MEM_READ_WRITE, Params.particleCount * sizeof(cl_float4)); mDensityBuffer = cl::Buffer(mCLContext, CL_MEM_READ_WRITE, Params.particleCount * sizeof(cl_float)); mLambdaBuffer = cl::Buffer(mCLContext, CL_MEM_READ_WRITE, Params.particleCount * sizeof(cl_float)); mParameters = cl::Buffer(mCLContext, CL_MEM_READ_ONLY, sizeof(Params)); // Radix buffers mKeysCount = IntCeil(Params.particleCount, _ITEMS * _GROUPS); mInKeysBuffer = cl::Buffer(mCLContext, CL_MEM_READ_WRITE, sizeof(cl_uint) * mKeysCount); mInPermutationBuffer = cl::Buffer(mCLContext, CL_MEM_READ_WRITE, sizeof(cl_uint) * mKeysCount); mOutKeysBuffer = cl::Buffer(mCLContext, CL_MEM_READ_WRITE, sizeof(cl_uint) * mKeysCount); mOutPermutationBuffer = cl::Buffer(mCLContext, CL_MEM_READ_WRITE, sizeof(cl_uint) * mKeysCount); mHistogramBuffer = cl::Buffer(mCLContext, CL_MEM_READ_WRITE, sizeof(cl_uint) * _RADIX * _GROUPS * _ITEMS); mGlobSumBuffer = cl::Buffer(mCLContext, CL_MEM_READ_WRITE, sizeof(cl_uint) * _HISTOSPLIT); mHistoTempBuffer = cl::Buffer(mCLContext, CL_MEM_READ_WRITE, sizeof(cl_uint) * _HISTOSPLIT); // Update OpenGL lock list mGLLockList.push_back(mPositionsPingBuffer); mGLLockList.push_back(mPositionsPongBuffer); mGLLockList.push_back(mParticlePosImg); // Update mPositionsPingBuffer and mVelocitiesBuffer LockGLObjects(); CreateParticles(); UnlockGLObjects(); // Copy Params (Host) => mParams (GPU) mQueue.enqueueWriteBuffer(mParameters, CL_TRUE, 0, sizeof(Params), &Params); } void Simulation::InitCells() { // Write buffer for cells mCellsBuffer = cl::Buffer(mCLContext, CL_MEM_READ_WRITE, Params.gridBufSize * 2 * sizeof(cl_uint)); OCL_InitMemory(mQueue, mCellsBuffer, (void*)&END_OF_CELL_LIST, sizeof(END_OF_CELL_LIST)); // Init Friends list buffer mFriendsListBuffer = cl::Buffer(mCLContext, CL_MEM_READ_WRITE, Params.particleCount * Params.friendsCircles * (1 + Params.particlesPerCircle) * sizeof(cl_uint)); OCL_InitMemory(mQueue, mFriendsListBuffer); } void Simulation::LoadForceMasks() { // Load file int width = 0, height = 0, channels = 0; byte* data = SOIL_load_image(getPathForTexture(string("Scene_fp_mask.png")).c_str(), &width, &height, &channels, 4); // Clear alpha for (int i = 0; i < width * height * 4; i+=4) { data[i+1] = 0; data[i+2] = 0; data[i+3] = 0; } // Create OpenCL image mSurfacesMask = cl::Image2D(mCLContext, CL_MEM_READ_WRITE, cl::ImageFormat(CL_R, CL_UNSIGNED_INT32), width, height); // Write data cl::size_t<3> org, region; region[0] = width; region[1] = height; region[2] = 1; mQueue.enqueueWriteImage(mSurfacesMask, true, org, region, 0, 0, data); //mQueue.enqueueReadImage(mSurfacesMask, true, org, region, 0, 0, data); // Release image data SOIL_free_image_data(data); } int dumpSession = 0; int dumpCounter = 0; int cycleCounter = 0; void SaveFile(cl::CommandQueue queue, cl::Buffer buffer, const char *szFilename) { // Exit if dump session is disabled if (dumpSession == 0) return; // Get buffer size int bufSize = buffer.getInfo<CL_MEM_SIZE>(); // Read data from GPU char *buf = new char[bufSize]; queue.enqueueReadBuffer(buffer, CL_TRUE, 0, bufSize, buf); queue.finish(); // Compose file name dumpCounter++; char szTarget[256]; sprintf(szTarget, "%s/dump%d/%d_%d_%s.bin", getRootPath().c_str(), dumpSession, dumpCounter, cycleCounter, szFilename); // Save to disk ofstream f(szTarget, ios::out | ios::trunc | ios::binary); f.seekp(0); f.write((const char *)buf, bufSize); f.close(); delete[] buf; } void Simulation::updateVelocities() { int param = 0; cl::Kernel kernel = mKernels["updateVelocities"]; kernel.setArg(param++, mParameters); kernel.setArg(param++, mPositionsPingBuffer); kernel.setArg(param++, mPredictedPingBuffer); kernel.setArg(param++, mParticlePosImg); kernel.setArg(param++, mVelocitiesBuffer); kernel.setArg(param++, Params.particleCount); mQueue.enqueueNDRangeKernel(kernel, 0, mGlobalRange, mLocalRange, NULL, PerfData.GetTrackerEvent("updateVelocities")); } void Simulation::applyViscosity() { int param = 0; cl::Kernel kernel = mKernels["applyViscosity"]; kernel.setArg(param++, mParameters); kernel.setArg(param++, mPredictedPingBuffer); kernel.setArg(param++, mVelocitiesBuffer); kernel.setArg(param++, mOmegaBuffer); kernel.setArg(param++, mFriendsListBuffer); kernel.setArg(param++, Params.particleCount); mQueue.enqueueNDRangeKernel(kernel, 0, mGlobalRange, mLocalRange, NULL, PerfData.GetTrackerEvent("applyViscosity")); } void Simulation::applyVorticity() { int param = 0; cl::Kernel kernel = mKernels["applyVorticity"]; kernel.setArg(param++, mParameters); kernel.setArg(param++, mPredictedPingBuffer); kernel.setArg(param++, mVelocitiesBuffer); kernel.setArg(param++, mOmegaBuffer); kernel.setArg(param++, mFriendsListBuffer); kernel.setArg(param++, Params.particleCount); mQueue.enqueueNDRangeKernel(kernel, 0, mGlobalRange, mLocalRange, NULL, PerfData.GetTrackerEvent("applyVorticity")); } void Simulation::predictPositions() { int param = 0; cl::Kernel kernel = mKernels["predictPositions"]; kernel.setArg(param++, mParameters); kernel.setArg(param++, (cl_uint)bPauseSim); kernel.setArg(param++, mPositionsPingBuffer); kernel.setArg(param++, mPredictedPingBuffer); kernel.setArg(param++, mVelocitiesBuffer); kernel.setArg(param++, Params.particleCount); mQueue.enqueueNDRangeKernel(kernel, 0, mGlobalRange, mLocalRange, NULL, PerfData.GetTrackerEvent("predictPositions")); } void Simulation::buildFriendsList() { int param = 0; cl::Kernel kernel = mKernels["buildFriendsList"]; kernel.setArg(param++, mParameters); kernel.setArg(param++, mPredictedPingBuffer); kernel.setArg(param++, mCellsBuffer); kernel.setArg(param++, mFriendsListBuffer); kernel.setArg(param++, Params.particleCount); mQueue.enqueueNDRangeKernel(kernel, 0, mGlobalRange, mLocalRange, NULL, PerfData.GetTrackerEvent("buildFriendsList")); param = 0; kernel = mKernels["resetGrid"]; kernel.setArg(param++, mParameters); kernel.setArg(param++, mInKeysBuffer); kernel.setArg(param++, mCellsBuffer); kernel.setArg(param++, Params.particleCount); mQueue.enqueueNDRangeKernel(kernel, 0, mGlobalRange, mLocalRange, NULL, PerfData.GetTrackerEvent("resetPartList")); } void Simulation::updatePredicted(int iterationIndex) { int param = 0; cl::Kernel kernel = mKernels["updatePredicted"]; kernel.setArg(param++, mPredictedPingBuffer); kernel.setArg(param++, mPredictedPongBuffer); kernel.setArg(param++, mDeltaBuffer); kernel.setArg(param++, Params.particleCount); mQueue.enqueueNDRangeKernel(kernel, 0, mGlobalRange, mLocalRange, NULL, PerfData.GetTrackerEvent("updatePredicted", iterationIndex)); SWAP(cl::Memory, mPredictedPingBuffer, mPredictedPongBuffer); } void Simulation::packData(cl::Memory& sourceImg, cl::Memory& pongImg, cl::Buffer packSource, int iterationIndex) { int param = 0; cl::Kernel kernel = mKernels["packData"]; kernel.setArg(param++, pongImg); kernel.setArg(param++, sourceImg); kernel.setArg(param++, packSource); kernel.setArg(param++, Params.particleCount); mQueue.enqueueNDRangeKernel(kernel, 0, mGlobalRange, mLocalRange, NULL, PerfData.GetTrackerEvent("packData", iterationIndex)); // Swap between source and pong SWAP(cl::Memory, sourceImg, pongImg); } void Simulation::computeDelta(int iterationIndex) { int param = 0; cl::Kernel kernel = mKernels["computeDelta"]; kernel.setArg(param++, mParameters); kernel.setArg(param++, oclLog.GetDebugBuffer()); kernel.setArg(param++, mDeltaBuffer); kernel.setArg(param++, mPositionsPingBuffer); kernel.setArg(param++, mPredictedPingBuffer); // xyz=Predicted z=Scaling kernel.setArg(param++, mFriendsListBuffer); kernel.setArg(param++, fWavePos); kernel.setArg(param++, mSurfacesMask); kernel.setArg(param++, Params.particleCount); #ifdef LOCALMEM mQueue.enqueueNDRangeKernel(kernel, 0, cl::NDRange(DivCeil(Params.particleCount, 256)*256), cl::NDRange(256), NULL, PerfData.GetTrackerEvent("computeDelta", iterationIndex)); #else mQueue.enqueueNDRangeKernel(kernel, 0, mGlobalRange, mLocalRange, NULL, PerfData.GetTrackerEvent("computeDelta", iterationIndex)); #endif } void Simulation::computeScaling(int iterationIndex) { int param = 0; cl::Kernel kernel = mKernels["computeScaling"]; kernel.setArg(param++, mParameters); kernel.setArg(param++, mPredictedPingBuffer); kernel.setArg(param++, mDensityBuffer); kernel.setArg(param++, mLambdaBuffer); kernel.setArg(param++, mFriendsListBuffer); kernel.setArg(param++, Params.particleCount); mQueue.enqueueNDRangeKernel(kernel, 0, mGlobalRange, mLocalRange, NULL, PerfData.GetTrackerEvent("computeScaling", iterationIndex)); // mQueue.enqueueNDRangeKernel(kernel, 0, cl::NDRange(((Params.particleCount + 399) / 400) * 400), cl::NDRange(400), NULL, PerfData.GetTrackerEvent("computeScaling", iterationIndex)); } void Simulation::updateCells() { int param = 0; cl::Kernel kernel = mKernels["updateCells"]; kernel.setArg(param++, mParameters); kernel.setArg(param++, mInKeysBuffer); kernel.setArg(param++, mCellsBuffer); kernel.setArg(param++, Params.particleCount); mQueue.enqueueNDRangeKernel(kernel, 0, mGlobalRange, mLocalRange, NULL, PerfData.GetTrackerEvent("updateCells")); } void Simulation::radixsort() { int param = 0; cl::Kernel kernel = mKernels["computeKeys"]; kernel.setArg(param++, mParameters); kernel.setArg(param++, mPredictedPingBuffer); kernel.setArg(param++, mInKeysBuffer); kernel.setArg(param++, mInPermutationBuffer); kernel.setArg(param++, Params.particleCount); mQueue.enqueueNDRangeKernel(kernel, 0, cl::NDRange(mKeysCount), mLocalRange, NULL, PerfData.GetTrackerEvent("computeKeys")); for (size_t pass = 0; pass < _PASS; pass++) { // Histogram(pass); const size_t h_nblocitems = _ITEMS; const size_t h_nbitems = _GROUPS * _ITEMS; param = 0; kernel = mKernels["histogram"]; kernel.setArg(param++, mInKeysBuffer); kernel.setArg(param++, mHistogramBuffer); kernel.setArg(param++, pass); kernel.setArg(param++, sizeof(cl_uint) * _RADIX * _ITEMS, NULL); kernel.setArg(param++, mKeysCount); mQueue.enqueueNDRangeKernel(kernel, 0, cl::NDRange(h_nbitems), cl::NDRange(h_nblocitems), NULL, PerfData.GetTrackerEvent("histogram", pass)); // ScanHistogram(); param = 0; kernel = mKernels["scanhistograms"]; const size_t sh1_nbitems = _RADIX * _GROUPS * _ITEMS / 2; const size_t sh1_nblocitems = sh1_nbitems / _HISTOSPLIT ; const int maxmemcache = max(_HISTOSPLIT, _ITEMS * _GROUPS * _RADIX / _HISTOSPLIT); kernel.setArg(param++, mHistogramBuffer); kernel.setArg(param++, sizeof(cl_uint)* maxmemcache, NULL); kernel.setArg(param++, mGlobSumBuffer); mQueue.enqueueNDRangeKernel(kernel, 0, cl::NDRange(sh1_nbitems), cl::NDRange(sh1_nblocitems), NULL, PerfData.GetTrackerEvent("scanhistograms1", pass)); mQueue.finish(); param = 0; kernel = mKernels["scanhistograms"]; const size_t sh2_nbitems = _HISTOSPLIT / 2; const size_t sh2_nblocitems = sh2_nbitems; kernel.setArg(0, mGlobSumBuffer); kernel.setArg(2, mHistoTempBuffer); mQueue.enqueueNDRangeKernel(kernel, 0, cl::NDRange(sh2_nbitems), cl::NDRange(sh2_nblocitems), NULL, PerfData.GetTrackerEvent("scanhistograms2", pass)); param = 0; kernel = mKernels["pastehistograms"]; const size_t ph_nbitems = _RADIX * _GROUPS * _ITEMS / 2; const size_t ph_nblocitems = ph_nbitems / _HISTOSPLIT; kernel.setArg(param++, mHistogramBuffer); kernel.setArg(param++, mGlobSumBuffer); mQueue.enqueueNDRangeKernel(kernel, 0, cl::NDRange(ph_nbitems), cl::NDRange(ph_nblocitems), NULL, PerfData.GetTrackerEvent("pastehistograms", pass)); // Reorder(pass); param = 0; kernel = mKernels["reorder"]; const size_t r_nblocitems = _ITEMS; const size_t r_nbitems = _GROUPS * _ITEMS; kernel.setArg(param++, mInKeysBuffer); kernel.setArg(param++, mOutKeysBuffer); kernel.setArg(param++, mHistogramBuffer); kernel.setArg(param++, pass); kernel.setArg(param++, mInPermutationBuffer); kernel.setArg(param++, mOutPermutationBuffer); kernel.setArg(param++, sizeof(cl_uint)* _RADIX * _ITEMS, NULL); kernel.setArg(param++, mKeysCount); mQueue.enqueueNDRangeKernel(kernel, 0, cl::NDRange(r_nbitems), cl::NDRange(r_nblocitems), NULL, PerfData.GetTrackerEvent("reorder", pass)); SWAP(cl::Buffer, mInKeysBuffer, mOutKeysBuffer); SWAP(cl::Buffer, mInPermutationBuffer, mOutPermutationBuffer); } // Execute particle reposition param = 0; kernel = mKernels["sortParticles"]; kernel.setArg(param++, mInPermutationBuffer); kernel.setArg(param++, mPositionsPingBuffer); kernel.setArg(param++, mPositionsPongBuffer); kernel.setArg(param++, mPredictedPingBuffer); kernel.setArg(param++, mPredictedPongBuffer); kernel.setArg(param++, Params.particleCount); mQueue.enqueueNDRangeKernel(kernel, 0, mGlobalRange, mLocalRange, NULL, PerfData.GetTrackerEvent("sortParticles")); // Double buffering of positions and velocity buffers SWAP(cl::BufferGL, mPositionsPingBuffer, mPositionsPongBuffer); SWAP(cl::Memory, mPredictedPingBuffer, mPredictedPongBuffer); SWAP(GLuint, mSharedPingBufferID, mSharedPongBufferID); } void Simulation::LockGLObjects() { // Make sure OpenGL finish doing things (This is required according to OpenCL spec, see enqueueAcquireGLObjects) glFinish(); // Request lock mQueue.enqueueAcquireGLObjects(&mGLLockList); } void Simulation::UnlockGLObjects() { // Release lock mQueue.enqueueReleaseGLObjects(&mGLLockList); mQueue.finish(); } void Simulation::Step() { // Lock OpenGL objects LockGLObjects(); // Inc sample counter cycleCounter++; // Predicit positions this->predictPositions(); // sort particles buffer if (!bPauseSim) this->radixsort(); // Update cells this->updateCells(); // Build friends list this->buildFriendsList(); for (unsigned int i = 0; i < Params.simIterations; ++i) { // Compute scaling value this->computeScaling(i); // Place lambda in "mPredictedPingBuffer[x].w" this->packData(mPredictedPingBuffer, mPredictedPongBuffer, mLambdaBuffer, i); // Compute position delta this->computeDelta(i); // Update predicted position this->updatePredicted(i); } // Place density in "mPredictedPingBuffer[x].w" this->packData(mPredictedPingBuffer, mPredictedPongBuffer, mDensityBuffer, -1); // Recompute velocities this->updateVelocities(); // Update vorticity and Viscosity this->applyViscosity(); this->applyVorticity(); // [DEBUG] Read back friends information (if needed) //if (bReadFriendsList || bDumpParticlesData) // TODO: Get frients list to host // [DEBUG] Do we need to dump particle data if (bDumpParticlesData) { // Turn off flag bDumpParticlesData = false; // TODO: Dump particles to disk } // Release OpenGL shared object, allowing openGL do to it's thing... UnlockGLObjects(); // Collect performance data PerfData.UpdateTimings(); // Allow OpenCL logger to process oclLog.CycleExecute(mQueue); }
23,489
8,170
// import header files #include <KNeighborsClassifier.hpp> #include <matplotlibcpp.hpp> #include <model_selection.hpp> namespace plt = matplotlibcpp; // Example program // Read csv files to get a Matrix object. // Slice the Matrix object to a suitable size. // Plot known data points // Run KNeighborsClustering and predict the cluster label for a Matrix // Print score and plot necessary graphs int main() { // Specify backend renderer for matplotlib plt::backend("GTK3Agg"); // create dataset with two feature Matrix mat = read_csv("./datasets/blobs/blobs.csv"); Matrix X = mat.slice(1, mat.row_length(), 0, 2); Matrix Y = mat.slice(1, mat.row_length(), 2, 3); X.to_double(); Y.to_double(); // Split the data and targets into training/testing sets auto [X_train, X_test, Y_train, Y_test] = model_selection.train_test_split(X, Y, 0); // plot training dataset plt::figure_size(800, 600); plt::title("KNeighbors Known Dataset"); plt::plot(matrix.slice_select(X_train, Y_train, 0.0, 0).get_col(0), matrix.slice_select(X_train, Y_train, 0.0, 1).get_col(0), "ro"); plt::plot(matrix.slice_select(X_train, Y_train, 1.0, 0).get_col(0), matrix.slice_select(X_train, Y_train, 1.0, 1).get_col(0), "g^"); plt::plot(matrix.slice_select(X_train, Y_train, 2.0, 0).get_col(0), matrix.slice_select(X_train, Y_train, 2.0, 1).get_col(0), "bD"); plt::save("./build/plots/KNeighbors Known Dataset.png"); plt::show(); // plot test data plt::figure_size(800, 600); plt::title("KNeighbors Unknown Dataset"); plt::plot(X_test.get_col(0), X_test.get_col(1), "mo"); plt::save("./build/plots/KNeighbors Unknown Dataset.png"); plt::show(); // create KMeans object with k and epochs as parameters KNeighborsClassifier knn(1); knn.fit(X_train, Y_train); std::cout << "K Neighbors Clustering Algorithm: " << std::endl; Matrix Y_pred = knn.predict(X_test); // plot predicted dataset plt::figure_size(800, 600); plt::title("KNeighbors Predicted Dataset along with Known Dataset"); plt::named_plot("Known red", matrix.slice_select(X_train, Y_train, 0.0, 0).get_col(0), matrix.slice_select(X_train, Y_train, 0.0, 1).get_col(0), "ro"); plt::named_plot("Known green", matrix.slice_select(X_train, Y_train, 1.0, 0).get_col(0), matrix.slice_select(X_train, Y_train, 1.0, 1).get_col(0), "g^"); plt::named_plot("Known blue", matrix.slice_select(X_train, Y_train, 2.0, 0).get_col(0), matrix.slice_select(X_train, Y_train, 2.0, 1).get_col(0), "bD"); plt::named_plot("Predicted red", matrix.slice_select(X_test, Y_pred, 0.0, 0).get_col(0), matrix.slice_select(X_test, Y_pred, 0.0, 1).get_col(0), "rP"); plt::named_plot("Predicted green", matrix.slice_select(X_test, Y_pred, 1.0, 0).get_col(0), matrix.slice_select(X_test, Y_pred, 1.0, 1).get_col(0), "gP"); plt::named_plot("Predicted blue", matrix.slice_select(X_test, Y_pred, 2.0, 0).get_col(0), matrix.slice_select(X_test, Y_pred, 2.0, 1).get_col(0), "bP"); plt::legend(); plt::save("./build/plots/KNeighbors Predicted Dataset.png"); plt::show(); // Comparison of predicted and actual cluster label std::cout << "KNN Model Score: " << knn.score(Y_pred, Y_test) << std::endl; return 0; }
3,446
1,321
#ifndef GRAPHMAP_H #define GRAPHMAP_H #include <list> #include "../include/gmapping/utils/point.h" #include "../include/gmapping/grid/map.h" #include <utils/graph.h> /* * 这个地方感觉像是用用来做图优化的。 * 不过不知道为什么最终没有用来做这个。 */ namespace GMapping { class RasterMap; struct GraphMapPatch { typedef typename std::list<IntPoint> PointList; /**Renders the map relatively to the center of the patch*/ //void render(RenderMap rmap); /**returns the lower left corner of the patch, relative to the center*/ //Point minBoundary() const; /**returns the upper right corner of the patch, relative to the center*/ //Point maxBoundary() const; // OrientedPoint center; PointList m_points; }; struct Covariance3 { double sxx, sxy, sxt, syy, syt ,stt; }; struct GraphMapEdge { Covariance3 covariance; GraphMapPatch* first, *second; inline operator double() const { return sqrt((first->center-second->center)*(first->center-second->center)); } }; struct GraphPatchGraph: public Graph<GraphMapPatch, Covariance3> { void addEdge(Vertex* v1, Vertex* v2, const Covariance3& covariance); }; void GraphPatchGraph::addEdge(GraphPatchGraph::Vertex* v1, GraphPatchGraph::VertexVertex* v2, const Covariance3& cov) { GraphMapEdge gme; gme.covariance=cov; gme.first=v1; gme.second=v2; return Graph<GraphMapPatch, Covariance3>::addEdge(v1,v2,gme); } struct GraphPatchDirectoryCell: public std::set<GraphMapPatch::Vertex*> { GraphPatchDirectoryCell(double); }; typedef Map<GraphPatchDirectoryCell>, Array2D::set<GraphPatchDirectoryCell> > }; #endif
1,559
609
// Ivan Carvalho // Solution to https://www.urionlinejudge.com.br/judge/problems/view/1544 #include <cstdio> int main(){ long long a,b; while(scanf("%lld %lld",&a,&b) != EOF){ long long resp = 1; for(long long i = a - b + 1;i <= a;i++){ resp *= i; while(resp % 10LL == 0LL) resp /= 10LL; resp %= 100000000000LL; } printf("%lld\n",resp%10); } return 0; }
375
197
#include <iostream> //#include <ctime> using namespace std; int main(){ ios::sync_with_stdio(false); long long answer = 0; int x,y,z,w; cin >> x >> y >> z >> w; //double be = clock(); for(int i = w/x; i>=0;i--) { for(int j = (w-x*i)/y; j>=0; j--) { for(int k = (w-x*i-y*j)/z; k>=0; k--) { if(w==x*i+y*j+z*k) { answer++; } } } } //double en = clock(); cout << answer; //cout << (en-be)/CLOCKS_PER_SEC; return 0; }
484
256
/* * The MIT License (MIT) * * Copyright © 2016 Franklin "Snaipe" Mathieu <http://snai.pe/> * * 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 CRITERION_INTERNAL_ASSERT_OP_HXX_ #define CRITERION_INTERNAL_ASSERT_OP_HXX_ #include <cwchar> /* *INDENT-OFF* */ namespace criterion { namespace internal { namespace operators { /* *INDENT-ON* */ #define CRI_DEFINE_MEMBER_DETECTOR(Member) \ template <class T> \ class HasMember_ ## Member { \ private: \ using yes = char[2]; \ using no = char[1]; \ struct fallback { int Member; }; \ struct derived : T, fallback {}; \ template <class U> static no &test(decltype (U::Member) *); \ template <typename U> static yes &test(U *); \ public: \ static constexpr bool result = sizeof (test<derived>(nullptr)) == sizeof (yes); \ }; \ template <class T> \ struct has_member_ ## Member : public std::integral_constant<bool, HasMember_ ## Member<T>::result> {} CRI_DEFINE_MEMBER_DETECTOR(empty); template <typename T> bool zero(const T *t) { return !t; } template <typename T> bool zero(const typename std::enable_if<!std::is_pointer<T>::value, T>::type &t) { return !t; } template <typename T, typename = typename has_member_empty<T>::type> bool zero(const T &t) { return t.empty(); } template <> inline bool zero<>(const char *t) { return !*t; } template <> inline bool zero<>(const wchar_t *t) { return !*t; } /* relops without const */ template <typename T, typename U> inline bool operator!= (T& t, U& u) { return !(t == u); } template <typename T, typename U> inline bool operator<= (T& t, U& u) { return t < u || t == u; } template <typename T, typename U> inline bool operator> (T& t, U& u) { return !(t <= u); } template <typename T, typename U> inline bool operator>= (T& t, U& u) { return !(t < u); } /* *INDENT-OFF* */ }}} /* *INDENT-ON* */ #endif /* !CRITERION_INTERNAL_ASSERT_OP_HXX_ */
3,699
1,072
#include "dynet/saxe-init.h" #include "dynet/tensor.h" #include "dynet/tensor-eigen.h" #include "dynet/globals.h" #include <random> #include <cstring> #include <Eigen/SVD> using namespace std; namespace dynet { void orthonormal_random(unsigned dd, float g, Tensor& x) { Tensor t; t.d = Dim({dd, dd}); t.v = new float[dd * dd]; normal_distribution<float> distribution(0, 0.01); auto b = [&] () {return distribution(*rndeng);}; generate(t.v, t.v + dd*dd, b); Eigen::JacobiSVD<Eigen::MatrixXf> svd(mat(t), Eigen::ComputeFullU); mat(x) = svd.matrixU(); delete[] t.v; } }
592
260
#include "salaries_workshop.h" #include <iostream> #include <vector> void pay_some_salaries() { std::vector<double> all_salaries{}; double tax_1{handle_money_stuff(3, 240.0, "Joe", all_salaries)}; double tax_2{handle_money_stuff(5, 240.0, "Jack", all_salaries)}; double tax_3{handle_money_stuff(6, 260.0, "Jill", all_salaries)}; double tax_4{handle_money_stuff(6, 800.0, "Jane", all_salaries)}; std::cout << "Taxes:" << tax_1 << ", " << tax_2 << ", " << tax_3 << ", " << tax_4 << "\n"; } int main() { std::cout << "Salaries original\n\n"; pay_some_salaries(); }
610
263
#include "ImageTile.hpp" #include <cstring> #include <fstream> ImageTile::ImageTile(unsigned int minX, unsigned int maxX, unsigned int minY, unsigned int maxY) : minX_(minX), maxX_(maxX), minY_(minY), maxY_(maxY) { if (maxX < minX || maxY < minY) { throw std::runtime_error("Improper ImageTile bounds!"); } width_ = maxX_ - minX_; height_ = maxY_ - minY_; len_ = 3 * width_ * height_; pixels_ = std::make_unique<float[]>(len_); memset(pixels_.get(), 0, len_ * sizeof(float)); } ImageTile::ImageTile(const ImageTile& other) { minX_ = other.minX_; maxX_ = other.maxX_; minY_ = other.minY_; maxY_ = other.maxY_; width_ = other.width_; height_ = other.height_; len_ = other.len_; pixels_ = std::make_unique<float[]>(len_); memcpy(pixels_.get(), other.pixels_.get(), len_ * sizeof(float)); } ImageTile::ImageTile(ImageTile&& other) { minX_ = other.minX_; maxX_ = other.maxX_; minY_ = other.minY_; maxY_ = other.maxY_; width_ = other.width_; height_ = other.height_; len_ = other.len_; pixels_ = std::move(other.pixels_); } ImageTile& ImageTile::operator=(const ImageTile& other) { if (&other != this) { minX_ = other.minX_; maxX_ = other.maxX_; minY_ = other.minY_; maxY_ = other.maxY_; width_ = other.width_; height_ = other.height_; len_ = other.len_; pixels_ = std::make_unique<float[]>(len_); memcpy(pixels_.get(), other.pixels_.get(), len_ * sizeof(float)); } return *this; } ImageTile& ImageTile::operator=(ImageTile&& other) { if (&other != this) { minX_ = other.minX_; maxX_ = other.maxX_; minY_ = other.minY_; maxY_ = other.maxY_; width_ = other.width_; height_ = other.height_; len_ = other.len_; pixels_ = std::move(other.pixels_); } return *this; } void ImageTile::clear(const Color& color) { for (unsigned int i = 0; i < len_;) { pixels_[i++] = color.r; pixels_[i++] = color.g; pixels_[i++] = color.b; } }
1,978
801
#include <library.h> #include "../../os_host/source/framework/Console.h" #include "../../os_host/source/framework/SimpleApp.h" #include "hunter.h" #include "framework/shapes.h" #include "framework/layout.h" using namespace BIOS; class CHunterInterface { public: void StartZone(int zone, int minutes) { CONSOLE::Print("Starting zone %d for %d minutes.\n", zone, minutes); HunterStart(zone, minutes); } void StopZone(int zone) { CONSOLE::Print("Stopping zone %d.\n", zone); HunterStop(zone); } void RunProgram(int program) { CONSOLE::Print("Running program %c.\n", 'A' - 1 + program); HunterProgram(program); } }; class CAppPage : public CWnd, public CHunterInterface { public: int mX{0}; int mY{0}; int mnPage{0}; int mnRunZone{1}; int mnRunFor{10}; int mnRunProgram{3}; bool mDemo{false}; int mDemoZone{0}; void DrawMenu() { const char* mPages[] = {"Control"}; CRect rcControls(0, 14+14*10, BIOS::LCD::Width, 14+14*10+14+4); LCD::Bar(rcControls, CONSOLE::colorBack); rcControls.top += 4; int x = 8; for (int i=0; i<COUNT(mPages); i++) { if (mnPage != i) { x += BIOS::LCD::Draw(x, rcControls.top, RGB565(4040b0), RGBTRANS, CShapes_tab_left); x += BIOS::LCD::Print(x, rcControls.top, RGB565(b0b0b0), RGB565(4040b0), mPages[i]); x += BIOS::LCD::Draw(x, rcControls.top, RGB565(4040b0), RGBTRANS, CShapes_tab_right); } else if (mY != -1) { x += BIOS::LCD::Draw(x, rcControls.top, RGB565(404040), RGBTRANS, CShapes_tab_left); x += BIOS::LCD::Print(x, rcControls.top, RGB565(ffffff), RGB565(404040), mPages[i]); x += BIOS::LCD::Draw(x, rcControls.top, RGB565(404040), RGBTRANS, CShapes_tab_right); } else { x += BIOS::LCD::Draw(x, rcControls.top, RGB565(ffffff), RGBTRANS, CShapes_tab_left); x += BIOS::LCD::Print(x, rcControls.top, RGB565(000000), RGB565(ffffff), mPages[i]); x += BIOS::LCD::Draw(x, rcControls.top, RGB565(ffffff), RGBTRANS, CShapes_tab_right); } x += 8; } } void Draw(Layout::Render& r) { using namespace Layout; GUI::Background(r.GetRectangle(), RGB565(404040), RGB565(404040)); r << Padding(4, 4, 4, 2); Color def(RGB565(b0b0b0)); Color hig(RGB565(ffffff)); #define S(x, y) Select(mX == x && mY == y) r << S(0, 0) << RadioButton(true, "Run") << "zone" << S(1, 0) << RadioButton(false, "\x11") << toString(mnRunZone) << S(2, 0) << RadioButton(false, "\x10") << "for" << S(3, 0) << RadioButton(false, "\x11") << toString(mnRunFor) << S(4, 0) << RadioButton(false, "\x10") << "minutes" << NewLine(); r << S(0, 1) << RadioButton(true, "Stop") << "zone " << toString(mnRunZone) << NewLine(); r << S(0, 2) << RadioButton(true, "Run") << "program" << S(1, 2) << RadioButton(false, "\x11") << toChar(mnRunProgram) << S(2, 2) << RadioButton(false, "\x10") << Spacer(64) << S(3, 2) << Radio(mDemo, "Demo"); #undef S } void DrawPage() { CRect rcControls(0, 14+14*10+14+4, BIOS::LCD::Width, BIOS::LCD::Height-14); Layout::Render r(rcControls); Draw(r); } virtual void OnKey(int key) override { if (key == BIOS::KEY::Enter) { switch (mY*16 + mX) { // 1st row case 0x00: StartZone(mnRunZone, mnRunFor); break; case 0x01: if (mnRunZone > 1) mnRunZone--; break; case 0x02: if (mnRunZone < 48) mnRunZone++; break; case 0x03: if (mnRunFor > 5) mnRunFor-=5; break; case 0x04: if (mnRunFor <= 240-5) mnRunFor+=5; break; // 2nd row case 0x10: StopZone(mnRunZone); break; // 3rd row case 0x20: RunProgram(mnRunProgram); break; case 0x21: if (mnRunProgram > 1) mnRunProgram--; break; case 0x22: if (mnRunProgram < 4) mnRunProgram++; break; case 0x23: mDemo = !mDemo; if (!mDemo) StopDemo(); break; } } switch (mY) { case 0: mX = max(0, min(mX, 4)); break; case 1: mX = max(0, min(mX, 0)); break; case 2: mX = max(0, min(mX, 3)); break; case 3: mY = 2; break; } } virtual void OnTimer() override { if (mDemo) DoDemo(); } void DoDemo() { if (++mDemoZone > 4) mDemoZone = 1; StartZone(mDemoZone, 30); } void StopDemo() { StopZone(mDemoZone); } private: char* toString(int n) { static char temp[16]; sprintf(temp, "%d", n); return temp; } char* toChar(int n) { static char temp[2]; sprintf(temp, "%c", 'A'-1+n); return temp; } }; class CApp : public CAppPage { public: //CApp() : CAppPage() {} void Create() { CWnd::Create("application", CWnd::WsVisible, CRect(0, 0, BIOS::LCD::Width, BIOS::LCD::Height), nullptr); CONSOLE::colorBack = RGB565(4040b0); CONSOLE::colorFront = RGB565(aaaaaa); APP::Init("Hunter X-Core controller"); CONSOLE::window = CRect(8, 14, BIOS::LCD::Width-8, 14+14*10); CONSOLE::cursor = CONSOLE::window.TopLeft(); DrawLayout(); APP::Status("AC1: n/c, AC2: +3V, REM: P1"); HunterInit(); SetTimer(5000); } void Destroy() { HunterDeinit(); } void DrawLayout() { DrawMenu(); DrawPage(); } virtual void OnKey(int key) override { if (key == BIOS::KEY::Up && mY > 0) mY--; if (key == BIOS::KEY::Down) mY++; if (key == BIOS::KEY::Left) mX--; if (key == BIOS::KEY::Right) mX++; CAppPage::OnKey(key); DrawPage(); } }; CApp app; #ifdef _ARM __attribute__((__section__(".entry"))) #endif int _main(void) { app.Create(); BIOS::KEY::EKey key; while ((key = KEY::GetKey()) != BIOS::KEY::EKey::Escape) { if (key != BIOS::KEY::EKey::None) app.OnKey(key); app.WindowMessage(CWnd::WmTick); } app.Destroy(); return 0; } void _HandleAssertion(const char* file, int line, const char* cond) { CONSOLE::Color(RGB565(ffff00)); CONSOLE::Print("Assertion failed in "); CONSOLE::Print(file); CONSOLE::Print(" [%d]: %s\n", line, cond); #ifdef __APPLE__ //kill(getpid(), SIGSTOP); #endif while (1); }
7,562
2,764
// // Copyright (c) 2017 Advanced Micro Devices, Inc. All rights reserved. // // 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 "PCH.h" #include "SuAlgorithm.h" #include "SuAnimationSet.h" #include "SuAreaLight.h" #include "SuDirectionalLight.h" #include "SuHashMap.h" #include "SuLight.h" #include "SuLightController.h" #include "SuLightManager.h" #include "SuPointLight.h" #include "SuSpotLight.h" #include "SuVolumeLight.h" /// Light manager singleton instance SuLightManager* SuLightManager::ms_pInstance = NULL; //================================================================================================================================= // // Constructor(s) / Destructor(s) Block // //================================================================================================================================= //================================================================================================================================= /// Default constructor //================================================================================================================================= SuLightManager::SuLightManager() {} //================================================================================================================================= /// Destructor //================================================================================================================================= SuLightManager::~SuLightManager() { for (LightNameMap::iterator itr = m_lights.begin(); itr != m_lights.end(); ++itr) { SU_SAFE_DELETE(itr->second); } } //================================================================================================================================= // // Public methods block // //================================================================================================================================= //================================================================================================================================= /// \return A pointer to the light manager //================================================================================================================================= SuLightManager* SuLightManager::GetPtr() { if (ms_pInstance) { return ms_pInstance; } ms_pInstance = new SuLightManager(); return ms_pInstance; } //================================================================================================================================= /// \return A reference to the light manager //================================================================================================================================= SuLightManager& SuLightManager::GetRef() { return *GetPtr(); } //================================================================================================================================= /// Destroys the light manager and all managed lights //================================================================================================================================= void SuLightManager::ShutDown() { SU_SAFE_DELETE(ms_pInstance); } //================================================================================================================================= /// \param rLightName The name to assign to the point light /// /// \return A point light. Returns NULL if another light with the given name already exists. The /// light manager retains ownership /// of the returned camera. //================================================================================================================================= SuPointLight* SuLightManager::CreatePointLight(const SuString& rLightName) { if (SuLight* pExisting = GetLightByName(rLightName)) { if (pExisting->GetType() != SuLight::POINT_LIGHT) { SuLogError("Light \"%s\" already exists and is not a point light.", static_cast<const char8*>(rLightName)); return NULL; } else { SuLogWarning("Point light \"%s\" already exists. Returning existing point light.", static_cast<const char8*>(rLightName)); return (SuPointLight*)pExisting; } } SuPointLight* pLight = new SuPointLight(rLightName); m_lights.insert(rLightName, pLight); m_lightArray.push_back(pLight); // pLight->SetIndex(m_lightArray.size()-1); return pLight; } //================================================================================================================================= /// \param rLightName The name to assign to the directional light /// /// \return A directional light. Returns NULL if another light with the given name already exists. /// The light manager retains /// ownership of the returned camera. //================================================================================================================================= SuDirectionalLight* SuLightManager::CreateDirectionalLight(const SuString& rLightName) { if (SuLight* pExisting = GetLightByName(rLightName)) { if (pExisting->GetType() != SuLight::DIRECTIONAL_LIGHT) { SuLogError("Light \"%s\" already exists and is not a directional light.", static_cast<const char8*>(rLightName)); return NULL; } else { SuLogWarning( "Directional light \"%s\" already exists. Returning existing directional light.", static_cast<const char8*>(rLightName)); return (SuDirectionalLight*)pExisting; } } SuDirectionalLight* pLight = new SuDirectionalLight(rLightName); m_lights.insert(rLightName, pLight); m_lightArray.push_back(pLight); // pLight->SetIndex(m_lightArray.size()-1); return pLight; } //================================================================================================================================= /// \param rLightName The name to assign to the spot light /// /// \return A spot light. Returns NULL if another light with the given name already exists. The /// light manager retains ownership /// of the returned camera. //================================================================================================================================= SuSpotLight* SuLightManager::CreateSpotLight(const SuString& rLightName) { if (SuLight* pExisting = GetLightByName(rLightName)) { if (pExisting->GetType() != SuLight::SPOT_LIGHT) { SuLogError("Light \"%s\" already exists and is not a spotlight.", static_cast<const char8*>(rLightName)); return NULL; } else { SuLogWarning("Spotlight \"%s\" already exists. Returning existing spotlight.", static_cast<const char8*>(rLightName)); return (SuSpotLight*)pExisting; } } SuSpotLight* pLight = new SuSpotLight(rLightName); m_lights.insert(rLightName, pLight); m_lightArray.push_back(pLight); // pLight->SetIndex(m_lightArray.size()-1); return pLight; } //================================================================================================================================= /// \param rLightName The name to assign to the volume light /// /// \return A volume light. Returns NULL or the original camera if another light with the given /// name already exists. //================================================================================================================================= SuVolumeLight* SuLightManager::CreateVolumeLight(const SuString& rLightName) { if (SuLight* pExisting = GetLightByName(rLightName)) { if (pExisting->GetType() != SuLight::VOLUME_LIGHT) { SuLogError("Light \"%s\" already exists and is not a volume light.", static_cast<const char8*>(rLightName)); return NULL; } else { SuLogWarning("Volume light \"%s\" already exists. Returning existing volume light.", static_cast<const char8*>(rLightName)); return (SuVolumeLight*)pExisting; } } SuVolumeLight* pLight = new SuVolumeLight(rLightName); m_lights.insert(rLightName, pLight); m_lightArray.push_back(pLight); // pLight->SetIndex(m_lightArray.size()-1); return pLight; } //================================================================================================================================= /// \param rLightName The name to assign to the area light /// /// \return A area light. Returns NULL if another light with the given name already exists. The /// light manager retains ownership /// of the returned camera. //================================================================================================================================= SuAreaLight* SuLightManager::CreateAreaLight(const SuString& rLightName) { if (SuLight* pExisting = GetLightByName(rLightName)) { if (pExisting->GetType() != SuLight::AREA_LIGHT) { SuLogError("Light \"%s\" already exists and is not an area light.", static_cast<const char8*>(rLightName)); return NULL; } else { SuLogWarning("Area light \"%s\" already exists. Returning existing area light.", static_cast<const char8*>(rLightName)); return (SuAreaLight*)pExisting; } } SuAreaLight* pLight = new SuAreaLight(rLightName); m_lights.insert(rLightName, pLight); m_lightArray.push_back(pLight); // pLight->SetIndex(m_lightArray.size()-1); return pLight; } //================================================================================================================================= /// \param rLightName The name of the desired light /// /// \return A pointer to the light with the given name. NULL if no such light exists. //================================================================================================================================= SuLight* SuLightManager::GetLightByName(const SuString& rLightName) const { LightNameMap::iterator itr = m_lights.find(rLightName); if (itr != m_lights.end()) { return itr->second; } return NULL; } //================================================================================================================================= /// Loads a light set file /// /// \param rFileName The light set file name /// /// \return true on success, false otherwise //================================================================================================================================= bool SuLightManager::LoadLightSet(const SuString& rFileName) { return LoadLightSet(rFileName, 0, NULL); } //================================================================================================================================= /// Loads a light set file /// /// \param rFileName The light set file name /// \param nNumProperties Number of properties in properties array /// \param pProperties Array of properties to assign to the lights in the set /// /// \return true on success, false otherwise //================================================================================================================================= bool SuLightManager::LoadLightSet(const SuString& rFileName, uint32 nNumProperties, const SuString* pProperties) { SuAnimationSet* pAnimSet = SuAnimationSet::CreateFromFile(rFileName); if (pAnimSet == NULL) { return false; } // extract light types and names from the animation set SuArray<SuString> lightNames; SuArray<uint8> lightTypes; ExtractLightsFromLightSet(lightNames, lightTypes, pAnimSet); // create a LightSetInfo structure for this light set m_lightSets.push_back(SuLightSetInfo()); SuLightSetInfo& rSetInfo = m_lightSets.back(); rSetInfo.animationFile = rFileName; rSetInfo.properties.reserve(nNumProperties); for (uint32 iProperty = 0; iProperty < nNumProperties; ++iProperty) { rSetInfo.properties.push_back(pProperties[iProperty]); } // create lights for (uint32 i = 0; i < lightNames.size(); i++) { SuLight* pLight = CreateLightFromLightSet(lightNames[i], lightTypes[i], pAnimSet); if (pLight) { rSetInfo.lights.insert(lightNames[i], pLight); } for (uint32 n = 0; n < nNumProperties; n++) { pLight->AddProperty(pProperties[n]); } } SU_SAFE_DELETE(pAnimSet); return true; } //================================================================================================================================= /// Reloads all light sets that were loaded through a call to LoadLightSet() /// /// This method cannot support changing light types. If a light-set reload would cause light types /// to change, /// then re-loading of that particular light is skipped. /// /// \return True if successful, false if any lightsets were skipped due to light type changes //================================================================================================================================= bool SuLightManager::ReloadLightSets() { bool bErrors = false; // attempt to re-load each of the light sets that was loaded previously for (SuList<SuLightSetInfo>::iterator itr = m_lightSets.begin(); itr != m_lightSets.end(); itr++) { SuLogInfo("Reloading light set from file: %s ", itr->animationFile.GetBuffer()); // re-open animation set const SuAnimationSet* pSet = SuAnimationSet::CreateFromFile(itr->animationFile); if (!pSet) { SuLogError("Unable to create animation set from file: %s ", itr->animationFile.GetBuffer()); bErrors = true; continue; } // extract light information SuArray<SuString> lightNames; SuArray<uint8> lightTypes; ExtractLightsFromLightSet(lightNames, lightTypes, pSet); // modify existing lights, and create new lights if specified for (uint32 i = 0; i < lightNames.size(); i++) { SuLight* pLight = GetLightByName(lightNames[i]); if (pLight) { // existing light. Type specified in animation set must match actual type if (pLight->GetType() != lightTypes[i]) { SuLogError( "Light type in lightset '%s' for light named: '%s' does not match type of existing light. To change light types, you must restart the demo.", itr->animationFile.GetBuffer(), lightNames[i].GetBuffer()); continue; } // light types match for existing light, make a new controller SuLightControllerPtr pCtrl = CreateLightController(pLight, lightNames[i], *pSet); pLight->SetController(pCtrl); } else { // create new light for this light set SuLight* pLight = CreateLightFromLightSet(lightNames[i], lightTypes[i], pSet); if (pLight) { size_t nProperties = itr->properties.size(); for (size_t iProperty = 0; iProperty < nProperties; ++iProperty) { pLight->AddProperty(itr->properties[iProperty]); } itr->lights.insert(lightNames[i], pLight); } else { bErrors = true; } } } SU_SAFE_DELETE(pSet); } if (bErrors) { SuLogError("Reloaded lightsets with errors!!!"); } else { SuLogInfo("Reloaded lightsets."); } return bErrors; } //================================================================================================================================= // // Private methods block // //================================================================================================================================= //================================================================================================================================= /// \param rLightName Name of light to create /// \param nLightType Type of light to create /// \param pAnimSet Animation set containing light parameter curves /// \return A pointer to the created light, or NULL //================================================================================================================================= SuLight* SuLightManager::CreateLightFromLightSet(const SuString& rLightName, uint8 nLightType, const SuAnimationSet* pAnimSet) { SuLight* pLight = NULL; switch (nLightType) { case SuLight::POINT_LIGHT: { pLight = CreatePointLight(rLightName); if (!pLight) { SuLogWarning("Unable to create point light!"); } } break; case SuLight::DIRECTIONAL_LIGHT: { pLight = CreateDirectionalLight(rLightName); if (!pLight) { SuLogWarning("Unable to create directional light!"); } } break; case SuLight::SPOT_LIGHT: { pLight = CreateSpotLight(rLightName); if (!pLight) { SuLogWarning("Unable to create spot light!"); } } break; case SuLight::VOLUME_LIGHT: { pLight = CreateVolumeLight(rLightName); if (!pLight) { SuLogWarning("Unable to create volume light!"); } } break; case SuLight::AREA_LIGHT: { pLight = CreateAreaLight(rLightName); if (!pLight) { SuLogWarning(" Unable to create area light!"); } } break; default: { SuLogError("Unidentified light type!"); return NULL; } } if (!pLight) { return NULL; } SuLightControllerPtr pCtrl = CreateLightController(pLight, rLightName, *pAnimSet); pLight->SetController(pCtrl); return pLight; } //================================================================================================================================= /// Extracts an array of light names and types from an animation set /// This is done by parsing the curve names and looking for the prefixes 'point', 'directional' or /// 'spot' /// \param rLightNames An array that will be filled with light names /// \param rLightTypes An array that will be filled with light types /// \param pAnimSet The animation set to parse //================================================================================================================================= void SuLightManager::ExtractLightsFromLightSet(SuArray<SuString>& rLightNames, SuArray<uint8>& rLightTypes, const SuAnimationSet* pAnimSet) { SuStringList animNames = pAnimSet->GetAllCurveNames(); typedef SuHashMap<SuString, bool, SuStringHasher, SuHashComparer<SuString> > LightNameSet; LightNameSet pointLightNames; LightNameSet dirLightNames; LightNameSet spotLightNames; LightNameSet volumeLightNames; LightNameSet areaLightNames; // get all unique lights in the set for (SuStringList::iterator it = animNames.begin(); it != animNames.end(); ++it) { SuStringList tokens = it->Split("."); if (tokens.size() != 3) { SuLogWarning("Unrecognized animation in light set: " + *it); continue; } if (tokens.front() == "point") { tokens.pop_front(); pointLightNames.insert(tokens.front(), true); } else if (tokens.front() == "directional") { tokens.pop_front(); dirLightNames.insert(tokens.front(), true); } else if (tokens.front() == "spot") { tokens.pop_front(); spotLightNames.insert(tokens.front(), true); } else if (tokens.front() == "volume") { tokens.pop_front(); volumeLightNames.insert(tokens.front(), true); } else if (tokens.front() == "area") { tokens.pop_front(); areaLightNames.insert(tokens.front(), true); } else { SuLogWarning("Unrecognized light type in light set: " + tokens.front()); continue; } } // count lights uint32 nLights = pointLightNames.size() + dirLightNames.size() + spotLightNames.size() + volumeLightNames.size() + areaLightNames.size(); // initialize array of light types rLightTypes.reserve(nLights); rLightTypes.insert(rLightTypes.end(), pointLightNames.size(), SuLight::POINT_LIGHT); rLightTypes.insert(rLightTypes.end(), dirLightNames.size(), SuLight::DIRECTIONAL_LIGHT); rLightTypes.insert(rLightTypes.end(), spotLightNames.size(), SuLight::SPOT_LIGHT); rLightTypes.insert(rLightTypes.end(), volumeLightNames.size(), SuLight::VOLUME_LIGHT); rLightTypes.insert(rLightTypes.end(), areaLightNames.size(), SuLight::AREA_LIGHT); // initialize array of light names rLightNames.reserve(nLights); for (LightNameSet::iterator it = pointLightNames.begin(); it != pointLightNames.end(); ++it) { rLightNames.push_back(it->first); } for (LightNameSet::iterator it = dirLightNames.begin(); it != dirLightNames.end(); ++it) { rLightNames.push_back(it->first); } for (LightNameSet::iterator it = spotLightNames.begin(); it != spotLightNames.end(); ++it) { rLightNames.push_back(it->first); } for (LightNameSet::iterator it = volumeLightNames.begin(); it != volumeLightNames.end(); ++it) { rLightNames.push_back(it->first); } for (LightNameSet::iterator it = areaLightNames.begin(); it != areaLightNames.end(); ++it) { rLightNames.push_back(it->first); } } //================================================================================================================================= /// \param pLight Light to create a controller for /// \param rLightName Light name /// \param rAnimSet Animation set that contains the animation curves for the light /// /// \return Smart pointer to a light controller with the relevant animation curves from the /// animation set //================================================================================================================================= SuLightControllerPtr SuLightManager::CreateLightController(SuLight* pLight, const SuString& rLightName, const SuAnimationSet& rAnimSet) { SU_ASSERT(pLight != NULL); SuString curveNamePrefix; switch (pLight->GetType()) { case SuLight::POINT_LIGHT: curveNamePrefix = "point."; break; case SuLight::DIRECTIONAL_LIGHT: curveNamePrefix = "directional."; break; case SuLight::SPOT_LIGHT: curveNamePrefix = "spot."; break; case SuLight::VOLUME_LIGHT: curveNamePrefix = "volume."; break; case SuLight::AREA_LIGHT: curveNamePrefix = "area."; break; default: SU_ASSERT(!"Unsupported light type"); break; } curveNamePrefix += rLightName; // Common attributes SuString curveName = curveNamePrefix + ".vColor"; SuAnimationCurvePtr pColorCurve = rAnimSet.GetCurve(curveName); curveName = curveNamePrefix + ".fIntensity"; SuAnimationCurvePtr pIntensityCurve = rAnimSet.GetCurve(curveName); curveName = curveNamePrefix + ".bEmitDiffuse"; SuAnimationCurvePtr pDiffuseCurve = rAnimSet.GetCurve(curveName); curveName = curveNamePrefix + ".bEmitSpecular"; SuAnimationCurvePtr pSpecularCurve = rAnimSet.GetCurve(curveName); curveName = curveNamePrefix + ".nDecayRate"; SuAnimationCurvePtr pFalloffCurve = rAnimSet.GetCurve(curveName); curveName = curveNamePrefix + ".visibility"; SuAnimationCurvePtr pVisibilityCurve = rAnimSet.GetCurve(curveName); SuAnimationCurvePtr pRadiusCurve; SuAnimationCurvePtr pPosCurve; SuAnimationCurvePtr pOrientationCurve; SuAnimationCurvePtr pScaleCurve; SuAnimationCurvePtr pConeAngleCurve; SuAnimationCurvePtr pPenumbraAngleCurve; SuAnimationCurvePtr pDropOffCurve; SuAnimationCurvePtr pLightShapeCurve; SuAnimationCurvePtr pSushiLightIndirectCurve; if (pLight->GetType() == SuLight::POINT_LIGHT) { // point light curveName = curveNamePrefix + ".fRadius"; pRadiusCurve = rAnimSet.GetCurve(curveName); } if (pLight->GetType() == SuLight::POINT_LIGHT || pLight->GetType() == SuLight::SPOT_LIGHT || pLight->GetType() == SuLight::VOLUME_LIGHT || pLight->GetType() == SuLight::AREA_LIGHT) { // point and spot light curveName = curveNamePrefix + ".vPosition"; pPosCurve = rAnimSet.GetCurve(curveName); } if (pLight->GetType() == SuLight::DIRECTIONAL_LIGHT || pLight->GetType() == SuLight::SPOT_LIGHT || pLight->GetType() == SuLight::VOLUME_LIGHT || pLight->GetType() == SuLight::AREA_LIGHT) { // directional, splot light and vollume light curveName = curveNamePrefix + ".qOrientation"; pOrientationCurve = rAnimSet.GetCurve(curveName); } if (pLight->GetType() == SuLight::SPOT_LIGHT) { // spotlight curveName = curveNamePrefix + ".fConeAngle"; pConeAngleCurve = rAnimSet.GetCurve(curveName); curveName = curveNamePrefix + ".fPenumbraAngle"; pPenumbraAngleCurve = rAnimSet.GetCurve(curveName); curveName = curveNamePrefix + ".fDropOff"; pDropOffCurve = rAnimSet.GetCurve(curveName); } if (pLight->GetType() == SuLight::VOLUME_LIGHT || pLight->GetType() == SuLight::AREA_LIGHT) { curveName = curveNamePrefix + ".vScale"; pScaleCurve = rAnimSet.GetCurve(curveName); } if (pLight->GetType() == SuLight::VOLUME_LIGHT) { curveName = curveNamePrefix + ".nLightShape"; pLightShapeCurve = rAnimSet.GetCurve(curveName); curveName = curveNamePrefix + ".bSushiLightIndirect"; pSushiLightIndirectCurve = rAnimSet.GetCurve(curveName); } // create controller SuLightControllerPtr pController = SuLightControllerPtr(new SuLightController(pColorCurve, pIntensityCurve, pDiffuseCurve, pSpecularCurve, pFalloffCurve, pRadiusCurve, pPosCurve, pOrientationCurve, pScaleCurve, pConeAngleCurve, pPenumbraAngleCurve, pDropOffCurve, pVisibilityCurve, pLightShapeCurve, pSushiLightIndirectCurve)); SU_ASSERT(pController != NULL); return pController; }
30,223
7,796
/*************************************************************************/ /* ip_unix.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */ /* */ /* 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 "ip_unix.h" #if defined(UNIX_ENABLED) || defined(WINDOWS_ENABLED) #ifdef WINDOWS_ENABLED #include <ws2tcpip.h> #include <winsock2.h> #include <windows.h> #else #include <netdb.h> #endif IP_Address IP_Unix::_resolve_hostname(const String& p_hostname) { struct hostent *he; if ((he=gethostbyname(p_hostname.utf8().get_data())) == NULL) { // get the host info ERR_PRINT("gethostbyname failed!"); return IP_Address(); } IP_Address ip; ip.host= *((unsigned long*)he->h_addr); return ip; } void IP_Unix::make_default() { _create=_create_unix; } IP* IP_Unix::_create_unix() { return memnew( IP_Unix ); } IP_Unix::IP_Unix() { } #endif
2,789
800
#include <iostream> #include <vector> int main(){ const int cap = 10; long n; std::cin >> n; std::string s; std::cin >> s; std::vector<int> a(cap, 0); for(long p = 0; p < n; p++){ if(s[p] == 'L'){for(long u = 0; u < cap; u++){if(!a[u]){a[u] = 1; break;}}} else if(s[p] == 'R'){for(long u = cap - 1; u >= 0; u--){if(!a[u]){a[u] = 1; break;}}} else{a[s[p] - '0'] = 0;} } for(long p = 0; p < cap; p++){std::cout << a[p];} std::cout << std::endl; return 0; }
520
246
/* * Copyright 2019 Xilinx, 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 "xf_blas.hpp" #define IDX2R(i, j, ld) (((i) * (ld)) + (j)) #define m 5 // a - mxk matrix #define n 5 // b - kxn matrix #define k 5 // c - mxn matrix using namespace std; int main(int argc, char** argv) { if (argc < 3) { cerr << " usage: \n" << " gemm_common_test.exe gemx.xclbin config_info.dat 1\n" << " gemm_common_test.exe gemx.xclbin config_info.dat\n"; return EXIT_FAILURE; } unsigned int l_argIdx = 1; string l_xclbinFile(argv[l_argIdx++]); string l_configFile(argv[l_argIdx++]); string l_logFile; ofstream logFile("xrt_report.txt"); logFile.close(); l_logFile = "xrt_report.txt"; int l_numKernel = 1; if (argc == 4) { cout << "read custom number of kernels\n"; l_numKernel = stoi(argv[l_argIdx++]); } int i, j; // i-row index ,j- column index XFBLAS_dataType *a, *b, *c; a = (XFBLAS_dataType*)malloc(m * k * sizeof(XFBLAS_dataType)); // host memory for a b = (XFBLAS_dataType*)malloc(k * n * sizeof(XFBLAS_dataType)); c = (XFBLAS_dataType*)malloc(m * n * sizeof(XFBLAS_dataType)); int ind = 1; for (i = 0; i < m; i++) { for (j = 0; j < k; j++) { a[IDX2R(i, j, k)] = (XFBLAS_dataType)ind++; } } for (i = 0; i < k; i++) { for (j = 0; j < n; j++) { b[IDX2R(i, j, n)] = (XFBLAS_dataType)ind++; } } for (i = 0; i < m; i++) { for (j = 0; j < n; j++) { c[IDX2R(i, j, n)] = 0; } } XFBLAS_dataType *d_a, *d_b, *d_c; xfblasEngine_t engineName = XFBLAS_ENGINE_GEMM; xfblasStatus_t status = XFBLAS_STATUS_SUCCESS; status = xfblasCreate(l_xclbinFile.c_str(), l_configFile, l_logFile.c_str(), engineName, l_numKernel); if (status != XFBLAS_STATUS_SUCCESS) { cout << "Create Handle failed with error code: " << status << "\n"; return EXIT_FAILURE; } status = xfblasMalloc(&d_a, m, k, sizeof(*a), l_numKernel - 1); if (status != XFBLAS_STATUS_SUCCESS) { cout << "Malloc memory for matrix A failed with error code: " << status << "\n"; return EXIT_FAILURE; } status = xfblasMalloc(&d_b, k, n, sizeof(*b), l_numKernel - 1); if (status != XFBLAS_STATUS_SUCCESS) { cout << "Malloc memory for matrix B failed with error code: " << status << "\n"; return EXIT_FAILURE; } status = xfblasMalloc(&d_c, m, n, sizeof(*c), l_numKernel - 1); if (status != XFBLAS_STATUS_SUCCESS) { cout << "Malloc memory for matrix C failed with error code: " << status << "\n"; return EXIT_FAILURE; } status = xfblasSetMatrix(m, k, sizeof(*a), a, k, d_a, l_numKernel - 1); status = xfblasSetMatrix(k, n, sizeof(*b), b, n, d_b, l_numKernel - 1); status = xfblasSetMatrix(m, n, sizeof(*c), c, n, d_c, l_numKernel - 1); if (status != XFBLAS_STATUS_SUCCESS) { cout << "Set Matrix failed with error code: " << status << "\n"; return EXIT_FAILURE; } status = xfblasGemm(XFBLAS_OP_N, XFBLAS_OP_N, m, n, k, 1, d_a, k, d_b, n, 1, d_c, n, l_numKernel - 1); if (status != XFBLAS_STATUS_SUCCESS) { cout << "Matrix Multiplication failed with error code: " << status << "\n"; return EXIT_FAILURE; } status = xfblasGetMatrix(m, n, sizeof(*c), d_c, c, n, l_numKernel - 1); if (status != XFBLAS_STATUS_SUCCESS) { cout << "Get Matirx failed with error code: " << status << "\n"; return EXIT_FAILURE; } for (i = 0; i < m; i++) { for (j = 0; j < n; j++) { cout << (c[IDX2R(i, j, k)]) << " "; } cout << "\n"; } // 590 605 620 635 650 // 1490 1530 1570 1610 1650 // 2390 2455 2520 2585 2650 // 3290 3380 3470 3560 3650 // 4190 4305 4420 4535 4650 xfblasFree(d_a, l_numKernel - 1); xfblasFree(d_b, l_numKernel - 1); xfblasFree(d_c, l_numKernel - 1); xfblasDestroy(l_numKernel); free(a); free(b); free(c); }
4,626
1,946
#include "LineCutterProjectile.h" #include "Net/UnrealNetwork.h" #include "Particles/ParticleSystemComponent.h" #include "DamageComponent.h" #include "Components/SceneComponent.h" void ALineCutterProjectile::UpdateBeamLocations() { } void ALineCutterProjectile::TerrainSweep(const FVector& Left, const FVector& Right) { } void ALineCutterProjectile::SpawnDecal(FHitResult& Result) { } void ALineCutterProjectile::Server_RemoveDebris_Implementation(int32 instance, int32 Component) { } bool ALineCutterProjectile::Server_RemoveDebris_Validate(int32 instance, int32 Component) { return true; } void ALineCutterProjectile::OnRep_LineRotation() { } void ALineCutterProjectile::Fire(const FVector& Origin, const FVector& Direction, float Distance) { } void ALineCutterProjectile::GetLifetimeReplicatedProps(TArray<FLifetimeProperty>& OutLifetimeProps) const { Super::GetLifetimeReplicatedProps(OutLifetimeProps); DOREPLIFETIME(ALineCutterProjectile, LineRotation); DOREPLIFETIME(ALineCutterProjectile, RotationMode); } ALineCutterProjectile::ALineCutterProjectile() { this->SwipeRadius = 5.00f; this->DoubleLineDistanceMultiplier = 2.00f; this->OverlapRadius = 5.00f; this->DestroyOnTerrainCollision = true; this->IsDead = false; this->bHasReversedDirection = false; this->FlyStraighTime = 0.20f; this->EletricDecalSize = EImpactDecalSize::Small; this->ImpactDecalSize = EImpactDecalSize::Small; this->LineRoot = CreateDefaultSubobject<USceneComponent>(TEXT("LineRoot")); this->LeftSphere = NULL; this->RightSphere = NULL; this->LeftSphere2 = NULL; this->RightSphere2 = NULL; this->LeftSphere3 = NULL; this->RightSphere3 = NULL; this->BeamParticle = NULL; this->BeamParticle2 = NULL; this->BeamParticle3 = NULL; this->LeftHitParticles = CreateDefaultSubobject<UParticleSystemComponent>(TEXT("LeftImpact")); this->RightHitParticles = CreateDefaultSubobject<UParticleSystemComponent>(TEXT("RightImpact")); this->RotationSpeed = 400.00f; this->RotationMode = ELineRotation::None; this->ShouldExplode = false; this->OnlyOne = false; this->IsDoubleLine = false; this->HasPlasmaTrail = false; this->LineMaxSize = 150.00f; this->LineExpansionDelay = 0.25f; this->TimeToLineExpansion = 0.35f; this->FireRate = 0.01f; this->DamageComponent = CreateDefaultSubobject<UDamageComponent>(TEXT("DamageComponent")); this->InitialDamageComponent = CreateDefaultSubobject<UDamageComponent>(TEXT("InitialDamageComponent")); this->InitialHitDamageMultiplier = 5; this->InhibitImpactDecalsTime = 0.00f; this->MinTimeBetweenImpactDecals = 0.15f; }
2,697
948
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "extern/beatsaber-hook/shared/utils/typedefs.h" #include "extern/beatsaber-hook/shared/utils/byref.hpp" // Including type: IRemoteProcedureCall #include "GlobalNamespace/IRemoteProcedureCall.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp" #include "extern/beatsaber-hook/shared/utils/utils.h" // Completed includes // Begin forward declares // Forward declaring namespace: GlobalNamespace namespace GlobalNamespace { } // Forward declaring namespace: LiteNetLib::Utils namespace LiteNetLib::Utils { // Forward declaring type: NetDataWriter class NetDataWriter; // Forward declaring type: NetDataReader class NetDataReader; } // Completed forward declares // Type namespace: namespace GlobalNamespace { // Size: 0x14 #pragma pack(push, 1) // Autogenerated type: RemoteProcedureCall // [TokenAttribute] Offset: FFFFFFFF class RemoteProcedureCall : public ::Il2CppObject/*, public GlobalNamespace::IRemoteProcedureCall*/ { public: // Nested type: GlobalNamespace::RemoteProcedureCall::TypeWrapper_1<T> template<typename T> struct TypeWrapper_1; // private System.Single <syncTime>k__BackingField // Size: 0x4 // Offset: 0x10 float syncTime; // Field size check static_assert(sizeof(float) == 0x4); // Creating value type constructor for type: RemoteProcedureCall RemoteProcedureCall(float syncTime_ = {}) noexcept : syncTime{syncTime_} {} // Creating interface conversion operator: operator GlobalNamespace::IRemoteProcedureCall operator GlobalNamespace::IRemoteProcedureCall() noexcept { return *reinterpret_cast<GlobalNamespace::IRemoteProcedureCall*>(this); } // Creating conversion operator: operator float constexpr operator float() const noexcept { return syncTime; } // Get instance field: private System.Single <syncTime>k__BackingField float _get_$syncTime$k__BackingField(); // Set instance field: private System.Single <syncTime>k__BackingField void _set_$syncTime$k__BackingField(float value); // public System.Single get_syncTime() // Offset: 0x23CEFB0 float get_syncTime(); // public System.Void set_syncTime(System.Single value) // Offset: 0x23CEFB8 void set_syncTime(float value); // protected System.Void SerializeData(LiteNetLib.Utils.NetDataWriter writer) // Offset: 0x23CEFC0 void SerializeData(LiteNetLib::Utils::NetDataWriter* writer); // protected System.Void DeserializeData(LiteNetLib.Utils.NetDataReader reader) // Offset: 0x23CEFC4 void DeserializeData(LiteNetLib::Utils::NetDataReader* reader); // private System.Void LiteNetLib.Utils.INetSerializable.Serialize(LiteNetLib.Utils.NetDataWriter writer) // Offset: 0x23CEFC8 void LiteNetLib_Utils_INetSerializable_Serialize(LiteNetLib::Utils::NetDataWriter* writer); // private System.Void LiteNetLib.Utils.INetSerializable.Deserialize(LiteNetLib.Utils.NetDataReader reader) // Offset: 0x23CF010 void LiteNetLib_Utils_INetSerializable_Deserialize(LiteNetLib::Utils::NetDataReader* reader); // public System.Void Release() // Offset: 0x23CF058 void Release(); // public IRemoteProcedureCall Init(System.Single syncTime) // Offset: 0x23CF178 GlobalNamespace::IRemoteProcedureCall* Init(float syncTime); // protected System.Void .ctor() // Offset: 0x23CF180 // Implemented from: System.Object // Base method: System.Void Object::.ctor() template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary> static RemoteProcedureCall* New_ctor() { static auto ___internal__logger = ::Logger::get().WithContext("GlobalNamespace::RemoteProcedureCall::.ctor"); return THROW_UNLESS((::il2cpp_utils::New<RemoteProcedureCall*, creationType>())); } }; // RemoteProcedureCall #pragma pack(pop) static check_size<sizeof(RemoteProcedureCall), 16 + sizeof(float)> __GlobalNamespace_RemoteProcedureCallSizeCheck; static_assert(sizeof(RemoteProcedureCall) == 0x14); } DEFINE_IL2CPP_ARG_TYPE(GlobalNamespace::RemoteProcedureCall*, "", "RemoteProcedureCall"); #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" // Writing MetadataGetter for method: GlobalNamespace::RemoteProcedureCall::get_syncTime // Il2CppName: get_syncTime template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<float (GlobalNamespace::RemoteProcedureCall::*)()>(&GlobalNamespace::RemoteProcedureCall::get_syncTime)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::RemoteProcedureCall*), "get_syncTime", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: GlobalNamespace::RemoteProcedureCall::set_syncTime // Il2CppName: set_syncTime template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::RemoteProcedureCall::*)(float)>(&GlobalNamespace::RemoteProcedureCall::set_syncTime)> { static const MethodInfo* get() { static auto* value = &::il2cpp_utils::GetClassFromName("System", "Single")->byval_arg; return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::RemoteProcedureCall*), "set_syncTime", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value}); } }; // Writing MetadataGetter for method: GlobalNamespace::RemoteProcedureCall::SerializeData // Il2CppName: SerializeData template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::RemoteProcedureCall::*)(LiteNetLib::Utils::NetDataWriter*)>(&GlobalNamespace::RemoteProcedureCall::SerializeData)> { static const MethodInfo* get() { static auto* writer = &::il2cpp_utils::GetClassFromName("LiteNetLib.Utils", "NetDataWriter")->byval_arg; return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::RemoteProcedureCall*), "SerializeData", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{writer}); } }; // Writing MetadataGetter for method: GlobalNamespace::RemoteProcedureCall::DeserializeData // Il2CppName: DeserializeData template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::RemoteProcedureCall::*)(LiteNetLib::Utils::NetDataReader*)>(&GlobalNamespace::RemoteProcedureCall::DeserializeData)> { static const MethodInfo* get() { static auto* reader = &::il2cpp_utils::GetClassFromName("LiteNetLib.Utils", "NetDataReader")->byval_arg; return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::RemoteProcedureCall*), "DeserializeData", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{reader}); } }; // Writing MetadataGetter for method: GlobalNamespace::RemoteProcedureCall::LiteNetLib_Utils_INetSerializable_Serialize // Il2CppName: LiteNetLib.Utils.INetSerializable.Serialize template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::RemoteProcedureCall::*)(LiteNetLib::Utils::NetDataWriter*)>(&GlobalNamespace::RemoteProcedureCall::LiteNetLib_Utils_INetSerializable_Serialize)> { static const MethodInfo* get() { static auto* writer = &::il2cpp_utils::GetClassFromName("LiteNetLib.Utils", "NetDataWriter")->byval_arg; return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::RemoteProcedureCall*), "LiteNetLib.Utils.INetSerializable.Serialize", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{writer}); } }; // Writing MetadataGetter for method: GlobalNamespace::RemoteProcedureCall::LiteNetLib_Utils_INetSerializable_Deserialize // Il2CppName: LiteNetLib.Utils.INetSerializable.Deserialize template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::RemoteProcedureCall::*)(LiteNetLib::Utils::NetDataReader*)>(&GlobalNamespace::RemoteProcedureCall::LiteNetLib_Utils_INetSerializable_Deserialize)> { static const MethodInfo* get() { static auto* reader = &::il2cpp_utils::GetClassFromName("LiteNetLib.Utils", "NetDataReader")->byval_arg; return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::RemoteProcedureCall*), "LiteNetLib.Utils.INetSerializable.Deserialize", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{reader}); } }; // Writing MetadataGetter for method: GlobalNamespace::RemoteProcedureCall::Release // Il2CppName: Release template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (GlobalNamespace::RemoteProcedureCall::*)()>(&GlobalNamespace::RemoteProcedureCall::Release)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::RemoteProcedureCall*), "Release", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: GlobalNamespace::RemoteProcedureCall::Init // Il2CppName: Init template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<GlobalNamespace::IRemoteProcedureCall* (GlobalNamespace::RemoteProcedureCall::*)(float)>(&GlobalNamespace::RemoteProcedureCall::Init)> { static const MethodInfo* get() { static auto* syncTime = &::il2cpp_utils::GetClassFromName("System", "Single")->byval_arg; return ::il2cpp_utils::FindMethod(classof(GlobalNamespace::RemoteProcedureCall*), "Init", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{syncTime}); } }; // Writing MetadataGetter for method: GlobalNamespace::RemoteProcedureCall::New_ctor // Il2CppName: .ctor // Cannot get method pointer of value based method overload from template for constructor! // Try using FindMethod instead!
10,080
3,201
// TrackSummary is a persistable class to communicate track // reconstruction results to physics analyses. // // Andrei Gaponenko, 2014 #ifndef RecoDataProducts_TrackSummary_hh #define RecoDataProducts_TrackSummary_hh #include "CLHEP/Vector/ThreeVector.h" #include "CLHEP/Matrix/SymMatrix.h" #include <ostream> class TrkSimpTraj; // BaBar class namespace mu2e { class TrackSummary { public: //================================================================ class HelixParams { public: // See docdb-781 for parameter definitions double d0() const { return d0_; } double phi0() const { return phi0_; } double omega() const { return omega_; } double z0() const { return z0_; } double tanDip() const { return tanDip_; } // Picked from BTrk/BaBar/BTrk/TrkBase/include/HelixParams.hh enum ParIndex {d0Index=0, phi0Index, omegaIndex, z0Index, tanDipIndex, NHLXPRM}; const CLHEP::HepSymMatrix& covariance() const { return covariance_; } //Not yet implemented - commented out until it is. //double parErr(ParIndex i); // Some derived quantities double dOut() const; // max distance to Z axis, opposite to d0() double radius() const; // of the helix double wavelength() const; // of the helix explicit HelixParams(const TrkSimpTraj& ltraj); // Default constructor is required by ROOT persistency HelixParams() : d0_(), phi0_(), omega_(), z0_(), tanDip_(), covariance_(NHLXPRM) {} private: double d0_; double phi0_; double omega_; double z0_; double tanDip_; CLHEP::HepSymMatrix covariance_; }; //================================================================ class TrackStateAtPoint { public: const HelixParams& helix() const { return helix_; } const CLHEP::Hep3Vector& position() const { return position_; } const CLHEP::Hep3Vector& momentum() const { return momentum_; } const CLHEP::HepSymMatrix& momentumCovariance() const { return momentumCovariance_; } double arrivalTime() const { return arrivalTime_; } double flightLength() const { return flightLength_; } // Derived quantities double momentumError() const; double costh() const; // momentum vector cosine to the Z axis TrackStateAtPoint(const HelixParams& h, const CLHEP::Hep3Vector& pos, const CLHEP::Hep3Vector& mom, const CLHEP::HepSymMatrix& momCov, double arrivalTime, double flightLength) : helix_(h) , position_(pos), momentum_(mom) , momentumCovariance_(momCov) , arrivalTime_(arrivalTime), flightLength_(flightLength) {} // Default constructor is required by ROOT persistency TrackStateAtPoint() : arrivalTime_(), flightLength_() {} private: // Converting (pos,mom) to a helix depends on B field and we want // to decouple from that. Therefore we store redundant info here. HelixParams helix_; CLHEP::Hep3Vector position_; CLHEP::Hep3Vector momentum_; CLHEP::HepSymMatrix momentumCovariance_; double arrivalTime_; double flightLength_; }; //================================================================ int fitstatus() const { return fitstatus_; } int charge() const { return charge_; } int nactive() const { return nactive_; } int ndof() const { return ndof_; } double chi2() const { return chi2_; } double fitcon() const; double t0() const { return t0_; } double t0Err() const { return t0Err_; } // flight length associated with t0. double flt0() const { return flt0_; } const std::vector<TrackStateAtPoint>& states() const { return states_; } TrackSummary(int fitstatus, int charge, int nactive, int ndof, double chi2, double t0, double t0Err, double flt0) : fitstatus_(fitstatus), charge_(charge), nactive_(nactive) , ndof_(ndof), chi2_(chi2) , t0_(t0), t0Err_(t0Err), flt0_(flt0) {} void addState(const TrackStateAtPoint& st); // Default constructor is required by ROOT persistency TrackSummary() : fitstatus_(), charge_(), nactive_(), ndof_(), chi2_(), t0_(), t0Err_(), flt0_() {} private: std::vector<TrackStateAtPoint> states_; int fitstatus_; int charge_; int nactive_; int ndof_; double chi2_; double t0_; double t0Err_; double flt0_; }; //================================================================ typedef std::vector<TrackSummary> TrackSummaryCollection; std::ostream& operator<<(std::ostream& os, const TrackSummary::TrackStateAtPoint& st); std::ostream& operator<<(std::ostream& os, const TrackSummary& sum); std::ostream& operator<<(std::ostream& os, const TrackSummaryCollection& sc); } // namespace mu2e #endif /* RecoDataProducts_TrackSummary_hh */
4,966
1,487
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /// @project Open Space Toolkit ▸ Core /// @file OpenSpaceToolkit/Core/Types/Integer.cpp /// @author Lucas Brémond <lucas@loftorbital.com> /// @license Apache License 2.0 //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #include <OpenSpaceToolkit/Core/Types/Integer.hpp> #include <OpenSpaceToolkit/Core/Error.hpp> #include <boost/lexical_cast.hpp> #include <limits> #include <iostream> //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// namespace ostk { namespace core { namespace types { //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// Integer::Integer ( Integer::ValueType anInteger ) : type_(Integer::Type::Defined), value_(anInteger) { } Integer& Integer::operator = ( Integer::ValueType anInteger ) { type_ = Integer::Type::Defined ; value_ = anInteger ; return *this ; } bool Integer::operator == ( const Integer& anInteger ) const { return (type_ == Integer::Type::Defined) && (anInteger.type_ == Integer::Type::Defined) && (value_ == anInteger.value_) ; } bool Integer::operator != ( const Integer& anInteger ) const { return (type_ == Integer::Type::Defined) && (anInteger.type_ == Integer::Type::Defined) && (value_ != anInteger.value_) ; } bool Integer::operator < ( const Integer& anInteger ) const { return (type_ == Integer::Type::Defined) && (anInteger.type_ == Integer::Type::Defined) && (value_ < anInteger.value_) ; } bool Integer::operator <= ( const Integer& anInteger ) const { return (type_ == Integer::Type::Defined) && (anInteger.type_ == Integer::Type::Defined) && (value_ <= anInteger.value_) ; } bool Integer::operator > ( const Integer& anInteger ) const { return (type_ == Integer::Type::Defined) && (anInteger.type_ == Integer::Type::Defined) && (value_ > anInteger.value_) ; } bool Integer::operator >= ( const Integer& anInteger ) const { return (type_ == Integer::Type::Defined) && (anInteger.type_ == Integer::Type::Defined) && (value_ >= anInteger.value_) ; } bool Integer::operator == ( const Integer::ValueType& anInteger ) const { return (type_ == Integer::Type::Defined) && (value_ == anInteger) ; } bool Integer::operator != ( const Integer::ValueType& anInteger ) const { return (type_ == Integer::Type::Defined) && (value_ != anInteger) ; } bool Integer::operator < ( const Integer::ValueType& anInteger ) const { return (type_ == Integer::Type::Defined) && (value_ < anInteger) ; } bool Integer::operator <= ( const Integer::ValueType& anInteger ) const { return (type_ == Integer::Type::Defined) && (value_ <= anInteger) ; } bool Integer::operator > ( const Integer::ValueType& anInteger ) const { return (type_ == Integer::Type::Defined) && (value_ > anInteger) ; } bool Integer::operator >= ( const Integer::ValueType& anInteger ) const { return (type_ == Integer::Type::Defined) && (value_ >= anInteger) ; } Integer Integer::operator + ( const Integer& anInteger ) const { if ((type_ != Integer::Type::Undefined) && (anInteger.type_ != Integer::Type::Undefined)) { if ((type_ == Integer::Type::PositiveInfinity) && (anInteger.type_ == Integer::Type::PositiveInfinity)) { return Integer::PositiveInfinity() ; } else if ((type_ == Integer::Type::NegativeInfinity) && (anInteger.type_ == Integer::Type::NegativeInfinity)) { return Integer::NegativeInfinity() ; } else if ((type_ == Integer::Type::Defined) || (anInteger.type_ == Integer::Type::Defined)) { if (type_ != Integer::Type::Defined) { return *this ; } else if (anInteger.type_ != Integer::Type::Defined) { return anInteger ; } // [TBC] Use __builtin_add_overflow instead? if ((anInteger.value_ > 0) && (value_ > (std::numeric_limits<Integer::ValueType>::max() - anInteger.value_))) // Addition would overflow { return Integer::PositiveInfinity() ; } if ((anInteger.value_ < 0) && (value_ < (std::numeric_limits<Integer::ValueType>::min() - anInteger.value_))) // Addition would underflow { return Integer::NegativeInfinity() ; } return Integer(value_ + anInteger.value_) ; } } return Integer::Undefined() ; } Integer Integer::operator - ( const Integer& anInteger ) const { if ((type_ != Integer::Type::Undefined) && (anInteger.type_ != Integer::Type::Undefined)) { if ((type_ == Integer::Type::PositiveInfinity) && (anInteger.type_ == Integer::Type::NegativeInfinity)) { return Integer::PositiveInfinity() ; } else if ((type_ == Integer::Type::NegativeInfinity) && (anInteger.type_ == Integer::Type::PositiveInfinity)) { return Integer::NegativeInfinity() ; } else if ((type_ == Integer::Type::Defined) || (anInteger.type_ == Integer::Type::Defined)) { if (type_ != Integer::Type::Defined) { return *this ; } else if (anInteger.type_ != Integer::Type::Defined) { if (anInteger.type_ == Integer::Type::PositiveInfinity) { return Integer::NegativeInfinity() ; } return Integer::PositiveInfinity() ; } if ((anInteger.value_ < 0) && (value_ > (std::numeric_limits<Integer::ValueType>::max() + anInteger.value_))) // Subtraction would overflow { return Integer::PositiveInfinity() ; } if ((anInteger.value_ > 0) && (value_ < (std::numeric_limits<Integer::ValueType>::min() + anInteger.value_))) // Subtraction would underflow { return Integer::NegativeInfinity() ; } return Integer(value_ - anInteger.value_) ; } } return Integer::Undefined() ; } Integer Integer::operator * ( const Integer& anInteger ) const { if ((type_ != Integer::Type::Undefined) && (anInteger.type_ != Integer::Type::Undefined)) { if (type_ == Integer::Type::PositiveInfinity) { if (anInteger.isStrictlyPositive()) { return Integer::PositiveInfinity() ; } else if (anInteger.isStrictlyNegative()) { return Integer::NegativeInfinity() ; } return Integer::Undefined() ; } else if (type_ == Integer::Type::NegativeInfinity) { if (anInteger.isStrictlyPositive()) { return Integer::NegativeInfinity() ; } else if (anInteger.isStrictlyNegative()) { return Integer::PositiveInfinity() ; } return Integer::Undefined() ; } else if (anInteger.type_ == Integer::Type::PositiveInfinity) { if (this->isStrictlyPositive()) { return Integer::PositiveInfinity() ; } else if (this->isStrictlyNegative()) { return Integer::NegativeInfinity() ; } return Integer::Undefined() ; } else if (anInteger.type_ == Integer::Type::NegativeInfinity) { if (this->isStrictlyPositive()) { return Integer::NegativeInfinity() ; } else if (this->isStrictlyNegative()) { return Integer::PositiveInfinity() ; } return Integer::Undefined() ; } else { if (this->isZero() || anInteger.isZero()) { return Integer::Zero() ; } // Check for -1 for two's complement machines if ((value_ < 0) && (anInteger.value_ == std::numeric_limits<Integer::ValueType>::min())) // Multiplication can overflow { return Integer::PositiveInfinity() ; } if ((anInteger.value_ < 0) && (value_ == std::numeric_limits<Integer::ValueType>::min())) // Multiplication can overflow { return Integer::PositiveInfinity() ; } if ((this->getSign() == anInteger.getSign()) && (std::abs(value_) > (std::numeric_limits<Integer::ValueType>::max() / std::abs(anInteger.value_)))) // Multiplication would overflow { return Integer::PositiveInfinity() ; } if ((value_ == +1) && (anInteger.value_ == std::numeric_limits<Integer::ValueType>::min())) { return Integer(std::numeric_limits<Integer::ValueType>::min()) ; } if ((value_ == -1) && (anInteger.value_ == std::numeric_limits<Integer::ValueType>::min())) { return Integer::PositiveInfinity() ; } if ((anInteger.value_ != -1) && (this->getSign() != anInteger.getSign()) && ((-std::abs(value_)) < (std::numeric_limits<Integer::ValueType>::min() / std::abs(anInteger.value_)))) // Multiplication would underflow { return Integer::NegativeInfinity() ; } return Integer(value_ * anInteger.value_) ; } } return Integer::Undefined() ; } Integer Integer::operator / ( const Integer& anInteger ) const { if (anInteger.isZero()) { return Integer::Undefined() ; } if ((type_ != Integer::Type::Undefined) && (anInteger.type_ != Integer::Type::Undefined)) { if (type_ == Integer::Type::PositiveInfinity) { if (anInteger.isInfinity()) { return Integer::Undefined() ; } else if (anInteger.isStrictlyPositive()) { return Integer::PositiveInfinity() ; } else if (anInteger.isStrictlyNegative()) { return Integer::NegativeInfinity() ; } return Integer::Undefined() ; } else if (type_ == Integer::Type::NegativeInfinity) { if (anInteger.isInfinity()) { return Integer::Undefined() ; } else if (anInteger.isStrictlyPositive()) { return Integer::NegativeInfinity() ; } else if (anInteger.isStrictlyNegative()) { return Integer::PositiveInfinity() ; } return Integer::Undefined() ; } else { if (this->isZero() || anInteger.isInfinity()) { return Integer::Zero() ; } else { if ((value_ == std::numeric_limits<Integer::ValueType>::min()) && (anInteger.value_ == -1)) { return Integer::PositiveInfinity() ; } return Integer(value_ / anInteger.value_) ; } } } return Integer::Undefined() ; } Integer Integer::operator % ( const Integer& anInteger ) const { if (anInteger.isZero()) { return Integer::Undefined() ; } if ((type_ != Integer::Type::Undefined) && (anInteger.type_ != Integer::Type::Undefined)) { if (this->isZero()) { return Integer::Zero() ; } else if (!this->isInfinity() && anInteger.isInfinity()) { return *this ; } else if ((!this->isInfinity()) && this->isStrictlyPositive() && (!anInteger.isInfinity()) && (anInteger.value_ == std::numeric_limits<Integer::ValueType>::min())) { return *this ; } else if ((!anInteger.isInfinity()) && (std::abs(anInteger.value_) == 1)) { return Integer::Zero() ; } else if (this->isInfinity()) { return Integer::Undefined() ; } else { return Integer(value_ % anInteger.value_) ; } } return Integer::Undefined() ; } Integer Integer::operator + ( const Integer::ValueType& anInteger ) const { return (*this) + Integer(anInteger) ; } Integer Integer::operator - ( const Integer::ValueType& anInteger ) const { return (*this) - Integer(anInteger) ; } Integer Integer::operator * ( const Integer::ValueType& anInteger ) const { return (*this) * Integer(anInteger) ; } Integer Integer::operator / ( const Integer::ValueType& anInteger ) const { return (*this) / Integer(anInteger) ; } Integer Integer::operator % ( const Integer::ValueType& anInteger ) const { return (*this) % Integer(anInteger) ; } Integer& Integer::operator += ( const Integer& anInteger ) { (*this) = (*this) + anInteger ; return *this ; } Integer& Integer::operator -= ( const Integer& anInteger ) { (*this) = (*this) - anInteger ; return *this ; } Integer& Integer::operator *= ( const Integer& anInteger ) { (*this) = (*this) * anInteger ; return *this ; } Integer& Integer::operator /= ( const Integer& anInteger ) { (*this) = (*this) / anInteger ; return *this ; } Integer& Integer::operator %= ( const Integer& anInteger ) { (*this) = (*this) % anInteger ; return *this ; } Integer& Integer::operator += ( const Integer::ValueType& anInteger ) { (*this) = (*this) + Integer(anInteger) ; return *this ; } Integer& Integer::operator -= ( const Integer::ValueType& anInteger ) { (*this) = (*this) - Integer(anInteger) ; return *this ; } Integer& Integer::operator *= ( const Integer::ValueType& anInteger ) { (*this) = (*this) * Integer(anInteger) ; return *this ; } Integer& Integer::operator /= ( const Integer::ValueType& anInteger ) { (*this) = (*this) / Integer(anInteger) ; return *this ; } Integer& Integer::operator %= ( const Integer::ValueType& anInteger ) { (*this) = (*this) % Integer(anInteger) ; return *this ; } Integer operator + ( const Integer::ValueType& anInt, const Integer& anInteger ) { return Integer(anInt) + anInteger ; } Integer operator - ( const Integer::ValueType& anInt, const Integer& anInteger ) { return Integer(anInt) - anInteger ; } Integer operator * ( const Integer::ValueType& anInt, const Integer& anInteger ) { return Integer(anInt) * anInteger ; } Integer operator / ( const Integer::ValueType& anInt, const Integer& anInteger ) { return Integer(anInt) / anInteger ; } Integer operator % ( const Integer::ValueType& anInt, const Integer& anInteger ) { return Integer(anInt) % anInteger ; } Integer Integer::operator + ( ) const { return *this ; } Integer Integer::operator - ( ) const { switch (type_) { case Integer::Type::Defined: { if (value_ == std::numeric_limits<Integer::ValueType>::min()) { return Integer::PositiveInfinity() ; } return Integer(-value_) ; } case Integer::Type::Undefined: return Integer::Undefined() ; case Integer::Type::PositiveInfinity: return Integer::NegativeInfinity() ; case Integer::Type::NegativeInfinity: return Integer::PositiveInfinity() ; default: break ; } return Integer::Undefined() ; } Integer& Integer::operator ++ ( ) { switch (type_) { case Integer::Type::Defined: { if (value_ == std::numeric_limits<Integer::ValueType>::max()) { type_ = Integer::Type::PositiveInfinity ; } else { ++value_ ; } break ; } case Integer::Type::Undefined: case Integer::Type::PositiveInfinity: case Integer::Type::NegativeInfinity: default: break ; } return *this ; } Integer& Integer::operator -- ( ) { switch (type_) { case Integer::Type::Defined: { if (value_ == std::numeric_limits<Integer::ValueType>::min()) { type_ = Integer::Type::NegativeInfinity ; } else { --value_ ; } break ; } case Integer::Type::Undefined: case Integer::Type::PositiveInfinity: case Integer::Type::NegativeInfinity: default: break ; } return *this ; } Integer Integer::operator ++ ( int anInteger ) { (void) anInteger ; Integer integerCopy(*this) ; switch (type_) { case Integer::Type::Defined: { if (value_ == std::numeric_limits<Integer::ValueType>::max()) { type_ = Integer::Type::PositiveInfinity ; } else { value_++ ; } break ; } case Integer::Type::Undefined: case Integer::Type::PositiveInfinity: case Integer::Type::NegativeInfinity: default: break ; } return integerCopy ; } Integer Integer::operator -- ( int anInteger ) { (void) anInteger ; Integer integerCopy(*this) ; switch (type_) { case Integer::Type::Defined: { if (value_ == std::numeric_limits<Integer::ValueType>::min()) { type_ = Integer::Type::NegativeInfinity ; } else { value_-- ; } break ; } case Integer::Type::Undefined: case Integer::Type::PositiveInfinity: case Integer::Type::NegativeInfinity: default: break ; } return integerCopy ; } Integer::operator Integer::ValueType ( ) const { if (type_ != Integer::Type::Defined) { throw ostk::core::error::runtime::Undefined("Integer") ; } return value_ ; } std::ostream& operator << ( std::ostream& anOutputStream, const Integer& anInteger ) { (void) anInteger ; switch (anInteger.type_) { case Integer::Type::Undefined: anOutputStream << "Undefined" ; break ; case Integer::Type::Defined: anOutputStream << anInteger.value_ ; break ; case Integer::Type::PositiveInfinity: anOutputStream << "+Inf" ; break ; case Integer::Type::NegativeInfinity: anOutputStream << "-Inf" ; break ; } // ostk::core::utilities::Output::Header(anOutputStream, "Integer") ; // ostk::core::utilities::Output::Line(anOutputStream) << "Type:" << anInteger.type_ ; // ostk::core::utilities::Output::Line(anOutputStream) << "Value:" << anInteger.value_ ; // ostk::core::utilities::Output::Footer(anOutputStream) ; return anOutputStream ; } bool Integer::isDefined ( ) const { return type_ != Integer::Type::Undefined ; } bool Integer::isZero ( ) const { return (type_ == Integer::Type::Defined) && (value_ == 0) ; } bool Integer::isPositive ( ) const { return ((type_ == Integer::Type::Defined) && (value_ >= 0)) || this->isPositiveInfinity() ; } bool Integer::isNegative ( ) const { return ((type_ == Integer::Type::Defined) && (value_ <= 0)) || this->isNegativeInfinity() ; } bool Integer::isStrictlyPositive ( ) const { return ((type_ == Integer::Type::Defined) && (value_ > 0)) || this->isPositiveInfinity() ; } bool Integer::isStrictlyNegative ( ) const { return ((type_ == Integer::Type::Defined) && (value_ < 0)) || this->isNegativeInfinity() ; } bool Integer::isInfinity ( ) const { return this->isPositiveInfinity() || this->isNegativeInfinity() ; } bool Integer::isPositiveInfinity ( ) const { return type_ == Integer::Type::PositiveInfinity ; } bool Integer::isNegativeInfinity ( ) const { return type_ == Integer::Type::NegativeInfinity ; } bool Integer::isFinite ( ) const { return type_ == Integer::Type::Defined ; } bool Integer::isEven ( ) const { return this->isFinite() && (value_ % 2 == 0) ; } bool Integer::isOdd ( ) const { return this->isFinite() && (value_ % 2 != 0) ; } types::Sign Integer::getSign ( ) const { switch (type_) { case Integer::Type::Undefined: return types::Sign::Undefined ; case Integer::Type::Defined: { if (value_ > 0) { return types::Sign::Positive ; } else if (value_ < 0) { return types::Sign::Negative ; } return types::Sign::None ; } case Integer::Type::PositiveInfinity: return types::Sign::Positive ; case Integer::Type::NegativeInfinity: return types::Sign::Negative ; default: return types::Sign::Undefined ; } return types::Sign::Undefined ; } types::String Integer::toString ( ) const { switch (type_) { case Integer::Type::Undefined: return "Undefined" ; case Integer::Type::Defined: return boost::lexical_cast<std::string>(value_) ; case Integer::Type::PositiveInfinity: return "+Inf" ; case Integer::Type::NegativeInfinity: return "-Inf" ; } return types::String::Empty() ; } Integer Integer::Undefined ( ) { return Integer(Integer::Type::Undefined, 0) ; } Integer Integer::Zero ( ) { return Integer(Integer::Type::Defined, 0) ; } Integer Integer::PositiveInfinity ( ) { return Integer(Integer::Type::PositiveInfinity, std::numeric_limits<Integer::ValueType>::max()) ; } Integer Integer::NegativeInfinity ( ) { return Integer(Integer::Type::NegativeInfinity, std::numeric_limits<Integer::ValueType>::min()) ; } Integer Integer::Int8 ( types::Int8 anInteger ) { return Integer(Integer::Type::Defined, static_cast<Integer::ValueType>(anInteger)) ; } Integer Integer::Int16 ( types::Int16 anInteger ) { return Integer(Integer::Type::Defined, static_cast<Integer::ValueType>(anInteger)) ; } Integer Integer::Int32 ( types::Int32 anInteger ) { return Integer(Integer::Type::Defined, static_cast<Integer::ValueType>(anInteger)) ; } Integer Integer::Int64 ( types::Int64 anInteger ) { if ((anInteger < static_cast<types::Int64>(std::numeric_limits<Integer::ValueType>::min())) || (anInteger > static_cast<types::Int64>(std::numeric_limits<Integer::ValueType>::max()))) { throw ostk::core::error::RuntimeError("Int64 value [" + boost::lexical_cast<std::string>(anInteger) + "] is out of Integer supported range [" + boost::lexical_cast<std::string>(std::numeric_limits<Integer::ValueType>::min()) + ", " + boost::lexical_cast<std::string>(std::numeric_limits<Integer::ValueType>::max()) + "].") ; } return Integer(Integer::Type::Defined, static_cast<Integer::ValueType>(anInteger)) ; } Integer Integer::Uint8 ( types::Uint8 anInteger ) { return Integer(Integer::Type::Defined, static_cast<Integer::ValueType>(anInteger)) ; } Integer Integer::Uint16 ( types::Uint16 anInteger ) { return Integer(Integer::Type::Defined, static_cast<Integer::ValueType>(anInteger)) ; } Integer Integer::Uint32 ( types::Uint32 anInteger ) { if (anInteger > static_cast<types::Uint32>(std::numeric_limits<Integer::ValueType>::max())) { throw ostk::core::error::RuntimeError("Uint32 value [" + boost::lexical_cast<std::string>(anInteger) + "] is out of Integer supported range [" + boost::lexical_cast<std::string>(std::numeric_limits<Integer::ValueType>::min()) + ", " + boost::lexical_cast<std::string>(std::numeric_limits<Integer::ValueType>::max()) + "].") ; } return Integer(Integer::Type::Defined, static_cast<Integer::ValueType>(anInteger)) ; } Integer Integer::Uint64 ( types::Uint64 anInteger ) { if (anInteger > static_cast<types::Uint64>(std::numeric_limits<Integer::ValueType>::max())) { throw ostk::core::error::RuntimeError("Uint64 value [" + boost::lexical_cast<std::string>(anInteger) + "] is out of Integer supported range [" + boost::lexical_cast<std::string>(std::numeric_limits<Integer::ValueType>::min()) + ", " + boost::lexical_cast<std::string>(std::numeric_limits<Integer::ValueType>::max()) + "].") ; } return Integer(Integer::Type::Defined, static_cast<Integer::ValueType>(anInteger)) ; } Integer Integer::Index ( const types::Index& anIndex ) { if (!(anIndex < std::numeric_limits<Integer::ValueType>::max())) { throw ostk::core::error::RuntimeError("Index out of bounds.") ; } return Integer(Integer::Type::Defined, static_cast<Integer::ValueType>(anIndex)) ; } Integer Integer::Size ( const types::Size& aSize ) { if (!(aSize < std::numeric_limits<Integer::ValueType>::max())) { throw ostk::core::error::RuntimeError("Size out of bounds.") ; } return Integer(Integer::Type::Defined, static_cast<Integer::ValueType>(aSize)) ; } bool Integer::CanParse ( char aCharacter ) { return std::isdigit(aCharacter) ; } bool Integer::CanParse ( const types::String& aString ) { if (aString.isEmpty()) { return false ; } if ((aString == "Undefined") || (aString == "Inf") || (aString == "+Inf") || (aString == "-Inf")) { return true ; } Integer::ValueType integer ; return boost::conversion::try_lexical_convert<Integer::ValueType>(aString, integer) ; } Integer Integer::Parse ( char aCharacter ) { try { return Integer(boost::lexical_cast<Integer::ValueType>(aCharacter)) ; } catch (const boost::bad_lexical_cast&) { throw ostk::core::error::RuntimeError("Cannot cast character [" + String::Char(aCharacter) + "] to Integer.") ; } return Integer::Undefined() ; } Integer Integer::Parse ( const types::String& aString ) { if (aString.isEmpty()) { throw ostk::core::error::runtime::Undefined("String") ; } if (aString == "Undefined") { return Integer::Undefined() ; } if ((aString == "Inf") || (aString == "+Inf")) { return Integer::PositiveInfinity() ; } if (aString == "-Inf") { return Integer::NegativeInfinity() ; } try { return Integer(boost::lexical_cast<Integer::ValueType>(aString)) ; } catch (const boost::bad_lexical_cast&) { throw ostk::core::error::RuntimeError("Cannot cast string [" + aString + "] to Integer.") ; } return Integer::Undefined() ; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// Integer::Integer ( const Integer::Type& aType, const Integer::ValueType& anInteger ) : type_(aType), value_(anInteger) { } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// } } } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
35,836
8,861
/* * app_camera.hpp * * Created on: Feb 8, 2019 * Author: andri */ #ifndef MAIN_APP_CAMERA_HPP_ #define MAIN_APP_CAMERA_HPP_ #include "esp_err.h" #include "esp_camera.h" #include "sdkconfig.h" /** * PIXFORMAT_RGB565, // 2BPP/RGB565 * PIXFORMAT_YUV422, // 2BPP/YUV422 * PIXFORMAT_GRAYSCALE, // 1BPP/GRAYSCALE * PIXFORMAT_JPEG, // JPEG/COMPRESSED * PIXFORMAT_RGB888, // 3BPP/RGB888 */ #define CAMERA_PIXEL_FORMAT PIXFORMAT_JPEG /* * FRAMESIZE_QQVGA, // 160x120 * FRAMESIZE_QQVGA2, // 128x160 * FRAMESIZE_QCIF, // 176x144 * FRAMESIZE_HQVGA, // 240x176 * FRAMESIZE_QVGA, // 320x240 * FRAMESIZE_CIF, // 400x296 * FRAMESIZE_VGA, // 640x480 * FRAMESIZE_SVGA, // 800x600 * FRAMESIZE_XGA, // 1024x768 * FRAMESIZE_SXGA, // 1280x1024 * FRAMESIZE_UXGA, // 1600x1200 */ #define CAMERA_FRAME_SIZE FRAMESIZE_QVGA #if CONFIG_CAMERA_BOARD_WROVER //WROVER-KIT PIN Map #define PWDN_GPIO_NUM -1 #define RESET_GPIO_NUM -1 #define XCLK_GPIO_NUM 21 #define SIOD_GPIO_NUM 26 #define SIOC_GPIO_NUM 27 #define Y9_GPIO_NUM 35 #define Y8_GPIO_NUM 34 #define Y7_GPIO_NUM 39 #define Y6_GPIO_NUM 36 #define Y5_GPIO_NUM 19 #define Y4_GPIO_NUM 18 #define Y3_GPIO_NUM 5 #define Y2_GPIO_NUM 4 #define VSYNC_GPIO_NUM 25 #define HREF_GPIO_NUM 23 #define PCLK_GPIO_NUM 22 //Specific #define USER_BUTTON_1_PIN_NUM 34 #define XCLK_FREQ 20000000 #elif CONFIG_CAMERA_BOARD_EYE //ESP-EYE Pin Map #define PWDN_GPIO_NUM -1 #define RESET_GPIO_NUM -1 #define XCLK_GPIO_NUM 4 #define SIOD_GPIO_NUM 18 #define SIOC_GPIO_NUM 23 #define Y9_GPIO_NUM 36 #define Y8_GPIO_NUM 37 #define Y7_GPIO_NUM 38 #define Y6_GPIO_NUM 39 #define Y5_GPIO_NUM 35 #define Y4_GPIO_NUM 14 #define Y3_GPIO_NUM 13 #define Y2_GPIO_NUM 34 #define VSYNC_GPIO_NUM 5 #define HREF_GPIO_NUM 27 #define PCLK_GPIO_NUM 25 #define XCLK_FREQ 20000000 #else //CAMERA_BOARD_TTGO_TCAM //TTGO_T-CAM #define PWDN_GPIO_NUM 26 #define RESET_GPIO_NUM -1 #define XCLK_GPIO_NUM 32 #define SIOD_GPIO_NUM 13 #define SIOC_GPIO_NUM 12 #define Y9_GPIO_NUM 39 #define Y8_GPIO_NUM 36 #define Y7_GPIO_NUM 23 #define Y6_GPIO_NUM 18 #define Y5_GPIO_NUM 15 #define Y4_GPIO_NUM 4 #define Y3_GPIO_NUM 14 #define Y2_GPIO_NUM 5 #define VSYNC_GPIO_NUM 27 #define HREF_GPIO_NUM 25 #define PCLK_GPIO_NUM 19 //Specific #define AS312_PIN_NUM 33 #define USER_BUTTON_1_PIN_NUM 34 #define I2C_SDA_PIN_NUM 21 #define I2C_SCL_PIN_NUM 22 #define XCLK_FREQ 20000000 #endif esp_err_t camera_init() { gpio_config_t conf; conf.mode = GPIO_MODE_INPUT; conf.pull_up_en = GPIO_PULLUP_ENABLE; conf.pull_down_en = GPIO_PULLDOWN_DISABLE; conf.intr_type = GPIO_INTR_DISABLE; conf.pin_bit_mask = 1LL << 13; gpio_config(&conf); conf.pin_bit_mask = 1LL << 14; gpio_config(&conf); camera_config_t config; config.ledc_channel = LEDC_CHANNEL_0; config.ledc_timer = LEDC_TIMER_0; config.pin_d0 = Y2_GPIO_NUM; config.pin_d1 = Y3_GPIO_NUM; config.pin_d2 = Y4_GPIO_NUM; config.pin_d3 = Y5_GPIO_NUM; config.pin_d4 = Y6_GPIO_NUM; config.pin_d5 = Y7_GPIO_NUM; config.pin_d6 = Y8_GPIO_NUM; config.pin_d7 = Y9_GPIO_NUM; config.pin_xclk = XCLK_GPIO_NUM; config.pin_pclk = PCLK_GPIO_NUM; config.pin_vsync = VSYNC_GPIO_NUM; config.pin_href = HREF_GPIO_NUM; config.pin_sscb_sda = SIOD_GPIO_NUM; config.pin_sscb_scl = SIOC_GPIO_NUM; config.pin_pwdn = PWDN_GPIO_NUM; config.pin_reset = RESET_GPIO_NUM; config.xclk_freq_hz = XCLK_FREQ; config.pixel_format = CAMERA_PIXEL_FORMAT; //init with high specs to pre-allocate larger buffers config.frame_size = FRAMESIZE_UXGA; config.jpeg_quality = 10; config.fb_count = 2; esp_err_t res = esp_camera_init(&config); if (res == ESP_OK) { //drop down frame size for higher initial frame rate sensor_t * s = esp_camera_sensor_get(); s->set_framesize(s, CAMERA_FRAME_SIZE); #if CONFIG_CAMERA_BOARD_TTGO_TCAM s->set_vflip(s, 1); #endif } return res; } #endif /* MAIN_APP_CAMERA_HPP_ */
4,156
2,263
#include "CppUnitLite/TestHarness.h" #include <string> static inline SimpleString StringFrom(const std::string& value) { return SimpleString(value.c_str()); } TEST( Hello, world ) { std::string s1("Hello"), s2("Hello"), s3("world"); CHECK_EQUAL(s1, s2); CHECK_EQUAL(s2, s1); CHECK(s1 != s3); }
308
128
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "extern/beatsaber-hook/shared/utils/typedefs.h" // Including type: System.Net.Http.Headers.HttpHeaders #include "System/Net/Http/Headers/HttpHeaders.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp" #include "extern/beatsaber-hook/shared/utils/utils.h" // Completed includes // Begin forward declares // Forward declaring namespace: System::Collections::Generic namespace System::Collections::Generic { // Forward declaring type: List`1<T> template<typename T> class List_1; } // Forward declaring namespace: System namespace System { // Forward declaring type: Func`2<T, TResult> template<typename T, typename TResult> class Func_2; } // Completed forward declares // Type namespace: System.Net.Http.Headers namespace System::Net::Http::Headers { // Size: 0x28 #pragma pack(push, 1) // Autogenerated type: System.Net.Http.Headers.HttpHeaders/HeaderBucket class HttpHeaders::HeaderBucket : public ::Il2CppObject { public: // public System.Object Parsed // Size: 0x8 // Offset: 0x10 ::Il2CppObject* Parsed; // Field size check static_assert(sizeof(::Il2CppObject*) == 0x8); // private System.Collections.Generic.List`1<System.String> values // Size: 0x8 // Offset: 0x18 System::Collections::Generic::List_1<::Il2CppString*>* values; // Field size check static_assert(sizeof(System::Collections::Generic::List_1<::Il2CppString*>*) == 0x8); // public readonly System.Func`2<System.Object,System.String> CustomToString // Size: 0x8 // Offset: 0x20 System::Func_2<::Il2CppObject*, ::Il2CppString*>* CustomToString; // Field size check static_assert(sizeof(System::Func_2<::Il2CppObject*, ::Il2CppString*>*) == 0x8); // Creating value type constructor for type: HeaderBucket HeaderBucket(::Il2CppObject* Parsed_ = {}, System::Collections::Generic::List_1<::Il2CppString*>* values_ = {}, System::Func_2<::Il2CppObject*, ::Il2CppString*>* CustomToString_ = {}) noexcept : Parsed{Parsed_}, values{values_}, CustomToString{CustomToString_} {} // public System.Void .ctor(System.Object parsed, System.Func`2<System.Object,System.String> converter) // Offset: 0x157A55C template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary> static HttpHeaders::HeaderBucket* New_ctor(::Il2CppObject* parsed, System::Func_2<::Il2CppObject*, ::Il2CppString*>* converter) { static auto ___internal__logger = ::Logger::get().WithContext("System::Net::Http::Headers::HttpHeaders::HeaderBucket::.ctor"); return THROW_UNLESS((::il2cpp_utils::New<HttpHeaders::HeaderBucket*, creationType>(parsed, converter))); } // public System.Boolean get_HasStringValues() // Offset: 0x157B15C bool get_HasStringValues(); // public System.Collections.Generic.List`1<System.String> get_Values() // Offset: 0x157A598 System::Collections::Generic::List_1<::Il2CppString*>* get_Values(); // public System.Void set_Values(System.Collections.Generic.List`1<System.String> value) // Offset: 0x157B64C void set_Values(System::Collections::Generic::List_1<::Il2CppString*>* value); // public System.String ParsedToString() // Offset: 0x157B0D8 ::Il2CppString* ParsedToString(); }; // System.Net.Http.Headers.HttpHeaders/HeaderBucket #pragma pack(pop) static check_size<sizeof(HttpHeaders::HeaderBucket), 32 + sizeof(System::Func_2<::Il2CppObject*, ::Il2CppString*>*)> __System_Net_Http_Headers_HttpHeaders_HeaderBucketSizeCheck; static_assert(sizeof(HttpHeaders::HeaderBucket) == 0x28); } DEFINE_IL2CPP_ARG_TYPE(System::Net::Http::Headers::HttpHeaders::HeaderBucket*, "System.Net.Http.Headers", "HttpHeaders/HeaderBucket");
4,122
1,417
#include "PlatisSolutionsBenchmarker.hpp" #include <chrono> #include <curl/curl.h> // You probably want to remove this after refactoring #include <string> namespace { const auto kUrl = "https://platis.solutions/assets/images/smartcar_featured.jpg"; const auto kFilePath = "/dev/null"; } // namespace namespace before { std::optional<std::chrono::milliseconds> PlatisSolutionsBenchmarker::getResponseTime() const { const auto start = std::chrono::system_clock::now(); auto downloadSuccessful = false; if (auto curl = curl_easy_init()) { auto fp = fopen(kFilePath, "wb"); curl_easy_setopt(curl, CURLOPT_URL, kUrl); curl_easy_setopt(curl, CURLOPT_FAILONERROR, 1L); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, NULL); curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp); downloadSuccessful = curl_easy_perform(curl) == CURLE_OK; fclose(fp); curl_easy_cleanup(curl); } const auto end = std::chrono::system_clock::now(); if (downloadSuccessful) { const auto elapsedTime = std::chrono::duration_cast<std::chrono::milliseconds>(end - start); return std::make_optional(elapsedTime); } return std::nullopt; } } // namespace before namespace after { PlatisSolutionsBenchmarker::PlatisSolutionsBenchmarker(Downloader& downloader) : mDownloader{downloader} { } std::optional<std::chrono::milliseconds> PlatisSolutionsBenchmarker::getResponseTime() const { const auto start = std::chrono::system_clock::now(); const auto downloadSuccessful = mDownloader.download(kUrl, kFilePath); const auto end = std::chrono::system_clock::now(); if (downloadSuccessful) { const auto elapsedTime = std::chrono::duration_cast<std::chrono::milliseconds>(end - start); return std::make_optional(elapsedTime); } return std::nullopt; } } // namespace after
2,095
634
void test() { /* Field testing: UVa 978, UVa 1513, UVa 12049, Kattis turbo */ int cnt = 10000, range = 1000; avl_tree<int> t1; set<int> t2; assert_equal(0, t1.size()); for (int i = 0; i < cnt; i++) { int n = rand() % range; avl_tree<int>::node *p = t1.insert(n); assert_equal(n, p->item); t2.insert(n); assert_equal((int)size(t2), (int)size(t1)); int n1 = rand() % range; avl_tree<int>::node *b = t1.find(n1); if (b) assert_equal(n1, b->item); assert_equal(b == NULL, t2.find(n1) == t2.end()); int n2 = rand() % range; t1.erase(n2); t2.erase(n2); assert_equal((int)size(t2), (int)size(t1)); } t1.clear(); t2.clear(); assert_equal(0, t1.size()); for (int i = 0; i < cnt; i++) { int n = rand() % range; avl_tree<int>::node *p = t1.insert(n); assert_equal(n, p->item); t2.insert(n); assert_equal((int)size(t2), (int)size(t1)); int n1 = rand() % range; avl_tree<int>::node *b = t1.find(n1); if (b) assert_equal(n1, b->item); assert_equal(b == NULL, t2.find(n1) == t2.end()); int n2 = rand() % range; t1.erase(n2); t2.erase(n2); assert_equal((int)size(t2), (int)size(t1)); } for (int i = 0; i < range; i++) { t1.erase(i); t2.erase(i); assert_equal((int)size(t2), (int)size(t1)); } assert_equal(0, t1.size()); } // vim: cc=60 ts=2 sts=2 sw=2:
1,400
678
/* Do not remove this header/ copyright information. * * Copyright © Trilobyte Software Engineering GmbH, Berlin, Germany 2010-2011. * You are allowed to modify and use the source code from * Trilobyte Software Engineering GmbH, Berlin, Germany for free if you are not * making profit with it or its adaption. Else you may contact Trilobyte SE. */ //"For compilers that support precompilation, includes "wx/wx.h"." #include "wx/wxprec.h" #ifdef __BORLANDC__ #pragma hdrstop #endif // for all others, include the necessary headers (this file is usually all you // need because it includes almost all "standard" wxWidgets headers) #ifndef WX_PRECOMP #include "wx/wx.h" #endif #include "MainFrame.hpp" //wxWidgets include files #include <wx/defs.h> //for wxBG_STYLE_CUSTOM #include <wx/dcbuffer.h> //for class wxBufferedPaintDC #include <wx/dynlib.h> //wxDynamicLibrary::GetDllExt() #include <wx/filename.h> //wxFileName::GetPathSeparator(...) #include "wx/frame.h" //for base class wxFrame //#include <wx/icon.h> //for class wxIcon #include <wx/menu.h> //for class wxMenu, class wxMenuBar #include <wx/menuitem.h> //class wxMenuItem #include <wx/numdlg.h> //for ::wxGetNumberFromUser(...) #include <wx/stattext.h> //for wxStaticText #include <wx/string.h> //for wxString::Format(...) #include <wx/timer.h> //for EVT_TIMER (,...?) //#include <wx/tooltip.h> //for wxToolTip::SetDelay(...) #include <wx/wx.h> //for wxMessageBox(...) (,etc.) //#include "wx/window.h" //#include <wx/menubar.h> //#include "../Controller/RunAsService.h" //for MyServiceStart etc. #include "FreqAndVoltageSettingDlg.hpp" //SUPPRESS_UNUSED_VARIABLE_WARNING(...) #include <compiler/GCC/suppress_unused_variable.h> #include <Controller/CalculationThreadProc.h> //for GetInterpolatedVoltageFromFreq( // WORD wFreqInMHzToGetVoltageFrom // , float & r_fVoltageInVolt // , const std::set<VoltageAndFreq> & r_stdsetvoltageandfreq // ); #include <Controller/CPU-related/GetInterpolatedVoltageFromFreq.hpp> //::wxGetApp().mp_cpucoreusagegetter #include <Controller/CPU-related/ICPUcoreUsageGetter.hpp> #include <Controller/CPU-related/I_CPUcontroller.hpp> ////GetFilenameWithoutExtension(const std::string &) //#include <Controller/FileSystem/GetFilenameWithoutExtension/\_ //GetFilenameWithoutExtension.hpp> ////for ::GetErrorMessageFromLastErrorCodeA(...) //#include <Controller/GetErrorMessageFromLastErrorCode.hpp> #include <Controller/IDynFreqScalingAccess.hpp> #include <Controller/I_CPUaccess.hpp> //class I_CPUaccess //WriteFileContent(...) #include <InputOutput/WriteFileContent/WriteFileContent.hpp> //for member m_stdmapwmenuid2i_cpucontrolleraction #include <Controller/I_CPUcontrollerAction.hpp>//class I_CPUcontrollerAction #include <Controller/IPC/I_IPC.hpp> //enum IPCcontrolCodes #include <Controller/character_string/stdtstr.hpp> //Getstdtstring(...) //DISable g++ "deprecated conversion from string constant to 'char*'" warning, //from //http://stackoverflow.com/questions/59670/how-to-get-rid-of-deprecated-conversion-from-string-constant-to-char-warning // : "I believe passing -Wno-write-strings to gcc will suppress this warning." #pragma GCC diagnostic ignored "-Wwrite-strings" #include <x86IandC.xpm> //ENable g++ "deprecated conversion from string constant to 'char*'" warning #pragma GCC diagnostic warning "-Wwrite-strings" #include <ModelData/ModelData.hpp> //class CPUcoreData #include <ModelData/PerCPUcoreAttributes.hpp> //class PerCPUcoreAttributes #include <ModelData/RegisterData.hpp> //#include <ModelData/HighLoadThreadAttributes.hpp> #include <ModelData/SpecificCPUcoreActionAttributes.hpp> #include <preprocessor_macros/logging_preprocessor_macros.h> //LOGN(...) //Pre-defined preprocessor macro under MSVC, MinGW for 32 and 64 bit Windows. #ifdef _WIN32 //Built-in macro for MSVC, MinGW (also for 64 bit Windows) //#include <Windows/CalculationThread.hpp> #include <OperatingSystem/Windows/DLLloadError.hpp> #include <OperatingSystem/Windows/ErrorCode/ErrorCodeFromGetLastErrorToString.h> #include <OperatingSystem/Windows/ErrorCode/LocalLanguageMessageFromErrorCode.h> #include <OperatingSystem/Windows/Service/ServiceBase.hpp> #endif #include <wxWidgets/App.hpp> //for wxGetApp() / DECLARE_APP #include <wxWidgets/Controller/wxDynLibCPUcontroller.hpp> #include <wxWidgets/Controller/wxDynLibCPUcoreUsageGetter.hpp> //#include <wxWidgets/wxStringHelper.h> //getwxString(const std::string &) / getwxString(const std::wstring &) #include <wxWidgets/Controller/character_string/wxStringHelper.hpp> //class NonBlocking::wxServiceSocketClient #include <wxWidgets/Controller/non-blocking_socket/client/\ wxServiceSocketClient.hpp> #include <wxWidgets/DynFreqScalingThread.hpp> #include <wxWidgets/icon/CreateTextIcon.hpp> //CreateTextIcon(...) #include <wxWidgets/ModelData/wxCPUcoreID.hpp> //#ifdef COMPILE_WITH_SYSTEM_TRAY_ICON #include <wxWidgets/UserInterface/TaskBarIcon.hpp>//class TaskBarIcon //#endif #include <wxWidgets/UserInterface/AboutDialog.hpp> //class AboutDialog #include <wxWidgets/UserInterface/DynFreqScalingDlg.hpp> #include <Xerces/XMLAccess.hpp> #include "wxExamineCPUregistersDialog.hpp" #ifdef COMPILE_WITH_MSR_EXAMINATION #include "CPUregisterReadAndWriteDialog.hpp" #endif //COMPILE_WITH_MSR_EXAMINATION //#include <limits.h> #ifndef MAXWORD #define MAXWORD 65535 #endif //#ifndef MAXWORD #include <map> //std::map #include <set> //std::set #include <valarray> //class std::valarray //#include <xercesc/framework/MemBufInputSource.hpp> #include <hardware/CPU/fastest_data_type.h> //typedef #ifdef USE_WINDOWS_API_DIRECTLY_FOR_SYSTEM_TRAY_ICON #include "SystemTrayAccess.hpp" #endif //#ifdef USE_WINDOWS_API_DIRECTLY_FOR_SYSTEM_TRAY_ICON #ifdef _MSC_VER #define __FLT_MIN__ FLT_MIN #endif class wxObject ; extern CPUcontrolBase * gp_cpucontrolbase ; //Static class variables must (also) be declared/ defined in the source file. float * MainFrame::s_arfTemperatureInDegreesCelsius = NULL ; wxIcon MainFrame::s_wxiconTemperature ; wxIcon MainFrame::s_wxiconCPUcoreUsages; wxIcon MainFrame::s_wxiconCPUcoresMultipliers; wxString MainFrame::s_wxstrHighestCPUcoreTemperative ; wxString MainFrame::s_wxstrTaskBarIconToolTip = wxT("x86IandC--highest CPU core temperature [°C]") ; DEFINE_LOCAL_EVENT_TYPE( wxEVT_COMMAND_REDRAW_EVERYTHING ) BEGIN_EVENT_TABLE(MainFrame, wxFrame) EVT_COMMAND(wxID_ANY, wxEVT_COMMAND_REDRAW_EVERYTHING, MainFrame::OnRedrawEverything) //"Cross-Platform GUI Programming with wxWidgets" // (Copyright © 2006 Pearson Education, Inc.) // ISBN 0-13-147381-6 "First printing, July 2005" //"CHAPTER 5 Drawing and Printing" -> //"UNDERSTANDING DEVICE CONTEXTS" -> "Drawing on Windows with wxPaintDC" : // "[...] another thing you can do to make // drawing smoother (particularly when resizing) is to paint the background in // your paint handler, and not in an erase background handler. All the painting // will then be done in your buffered paint handler, so you don’t see the back- // ground being erased before the paint handler is called. Add an empty erase // background handler, and call SetBackgroundStyle with wxBG_STYLE_CUSTOM to // hint to some systems not to clear the background automatically." EVT_ERASE_BACKGROUND(MainFrame::OnEraseBackground) EVT_MENU(ID_Quit, MainFrame::OnQuit) EVT_MENU(ID_About, MainFrame::OnAbout) EVT_MENU(ID_AttachCPUcontrollerDynLib, MainFrame::OnAttachCPUcontrollerDLL) EVT_MENU(ID_DetachCPUcontrollerDynamicLibrary, MainFrame::OnDetachCPUcontrollerDLL) EVT_MENU(ID_AttachCPUusageGetterDynLib, MainFrame::OnAttachCPUcoreUsageGetterDLL) EVT_MENU(ID_DetachCPUusageGetterDynLib, MainFrame::OnDetachCPUcoreUsageGetterDLL) //Pre-defined preprocessor macro under MSVC, MinGW for 32 and 64 bit Windows. #ifdef _WIN32 //Built-in macro for MSVC, MinGW (also for 64 bit Windows) EVT_MENU(ID_MinimizeToSystemTray, MainFrame::OnMinimizeToSystemTray) #endif #ifdef COMPILE_WITH_MSR_EXAMINATION EVT_MENU(ID_ShowExamineCPUregistersDialog, MainFrame::OnShowExamineCPUregistersDialog) EVT_MENU(ID_WriteToMSRdialog, MainFrame::OnShowCPUregistersReadAndWriteDialog) #endif //EVT_MENU( ID_MinAndMaxCPUcoreFreqInPercentOfMaxFreq , // MainFrame::OnDynamicallyCreatedUIcontrol ) EVT_MENU( ID_DisableOtherVoltageOrFrequencyAccess , MainFrame::OnDisableOtherVoltageOrFrequencyAccess ) EVT_MENU( ID_EnableOtherVoltageOrFrequencyAccess , MainFrame::OnEnableOtherVoltageOrFrequencyAccess ) EVT_MENU( ID_EnableOrDisableOwnDVFS , MainFrame::OnOwnDynFreqScaling ) EVT_MENU( ID_LoadDetectInstableCPUcoreVoltageDynLib, MainFrame::OnLoadDetectInstableCPUcoreVoltageDynLib) EVT_MENU( ID_UnloadDetectInstableCPUcoreVoltageDynLib, MainFrame::OnUnloadDetectInstableCPUcoreVoltageDynLib) EVT_MENU( ID_UpdateViewInterval , MainFrame::OnUpdateViewInterval ) EVT_MENU( ID_SetCPUcontrollerDynLibForThisCPU , MainFrame::OnSaveAsCPUcontrollerDynLibForThisCPU ) EVT_MENU( ID_SaveAsDefaultPstates , MainFrame::OnSaveVoltageForFrequencySettings ) EVT_MENU( ID_FindDifferentPstates , MainFrame::OnFindDifferentPstates ) EVT_MENU( ID_Collect_As_Default_Voltage_PerfStates , MainFrame::OnCollectAsDefaultVoltagePerfStates ) EVT_MENU( ID_ShowVoltageAndFrequencySettingsDialog , MainFrame:://OnShowVoltageAndFrequencySettingsDialog OnVoltageAndFrequencySettingsDialog) #ifdef COMPILE_WITH_SERVICE_PROCESS_CONTROL EVT_MENU( ID_ContinueService , MainFrame::OnContinueService ) EVT_MENU( ID_PauseService , MainFrame::OnPauseService ) EVT_MENU( ID_StartService , MainFrame::OnStartService ) EVT_MENU( ID_StopService , MainFrame::OnStopService ) EVT_MENU( ID_ConnectToService , MainFrame::OnConnectToService ) EVT_MENU( ID_ConnectToOrDisconnectFromService , MainFrame::OnConnectToOrDisconnectFromService ) EVT_MENU( ID_DisconnectFromService , MainFrame::OnDisconnectFromService ) #endif //#ifdef COMPILE_WITH_SERVICE_PROCESS_CONTROL //#endif //#ifdef _WINDOWS #ifdef COMPILE_WITH_SERVICE_CAPABILITY EVT_MENU(ID_Service, MainFrame::OnStartService) #endif //EVT_MENU(ID_SetPstate0ForBothCores, MyFrame::OnSetPstate0ForBothCores) //EVT_MENU(ID_SetPstate1ForBothCores, MyFrame::OnSetPstate1ForBothCores) //EVT_MENU(ID_SetPstate2ForBothCores, MyFrame::OnSetPstate2ForBothCores) //EVT_MENU(ID_FindLowestOperatingVoltage, MainFrame::OnFindLowestOperatingVoltage) #ifdef PRIVATE_RELEASE //hide the other possibilities EVT_MENU(ID_IncreaseVoltageForCurrentPstate, MainFrame::OnIncreaseVoltageForCurrentPstate) #endif //#ifdef PRIVATE_RELEASE //hide the other possibilities #ifdef wxHAS_POWER_EVENTS EVT_POWER_RESUME(MainFrame::OnResume) EVT_POWER_SUSPENDING(MainFrame::OnSuspending) EVT_POWER_SUSPENDED(MainFrame::OnSuspended) EVT_POWER_SUSPEND_CANCEL(MainFrame::OnSuspendCancel) #endif // wxHAS_POWER_EVENTS //For stopping the DynVoltAndFreqScal thread that accesses the wxApp. //So stop the DVFS thread before destroying the wxApp object to avoid //crashes. EVT_CLOSE( MainFrame::OnClose ) // EVT_INIT_DIALOG(MainFrame::OnInitDialog) //If no EVT_PAINT macro and Connect(wxEVT_PAINT, // wxPaintEventHandler(MyFrame::OnPaint)); // : 100% CPU load. EVT_PAINT (MainFrame::OnPaint) EVT_SIZE(MainFrame::OnSize) EVT_SIZING(MainFrame::OnSizing) EVT_MOTION(MainFrame::OnMoveMouse) EVT_LEFT_DOWN(MainFrame::OnLeftMouseButtonDown) //EVT_TIMER(-1,MainFrame::OnTimerEvent) EVT_TIMER(TIMER_ID, MainFrame::OnTimerEvent) //EVT_COMMAND_RIGHT_CLICK(FIRST_TRAYNOTIFY_ID, MainFrame::OnSysTrayIconClick) // EVT_MOUSE_EVENTS(FIRST_TRAYNOTIFY_ID, MainFrame::OnSysTrayIconClick) END_EVENT_TABLE() #define ATTACH_CPU_CONTROLLER_DYNAMIC_LIBRARY_T_STRING \ _T("Attach CPU &controller dynamic library...") #define ATTACH_CPU_CORE_USAGE_GETTER_DYNAMIC_LIBRARY_T_STRING \ _T("Attach CPU &usage getter dynamic library...") #define DETACH_CPU_CONTROLLER_DYNAMIC_LIBRARY_T_STRING \ _T("Detach CPU controller dynamic library") #define DETACH_CPU_CORE_USAGE_GETTER_DYNAMIC_LIBRARY_T_STRING \ _T("Detach CPU usage getter dynamic library") //for CPU_TEMP_IS_BELOW_CRITICAL, CPU_TEMP_IS_CRITICAL #include <Controller/CPU-related/CPU_core_temperature_defs.h> inline void MainFrame::CreateFileMenu() { LOGN(/*"CreateFileMenu()"*/ "begin") wxMenuItem * p_wxmenuitem ; mp_wxmenuFile = new wxMenu; //wxMenu * p_wxmenuCore1 = new wxMenu; // wxMenu * p_wxmenuNorthBridge = new wxMenu; mp_wxmenuFile->Append( ID_About, _T("&About...") ); mp_wxmenuFile->AppendSeparator(); p_wxmenuitem = mp_wxmenuFile->Append( ID_AttachCPUcontrollerDynLib, ATTACH_CPU_CONTROLLER_DYNAMIC_LIBRARY_T_STRING ); if( ! mp_wxx86infoandcontrolapp->GetCPUaccess() ) p_wxmenuitem->SetHelp ( //TODO more imformative/ user-friendly message (but may not be too long) wxT("No CPU access. See log file/ start this program as admin.") ) ; mp_wxmenuFile->Append( ID_DetachCPUcontrollerDynamicLibrary, DETACH_CPU_CONTROLLER_DYNAMIC_LIBRARY_T_STRING ); mp_wxmenuFile->Append( ID_SetCPUcontrollerDynLibForThisCPU, wxString::Format( wxT("save as CPU controller dynamic library for this CPU " "(vendor:%s family:%u model:%u stepping:%u)") , wxWidgets::getwxString( mp_model->m_cpucoredata.m_strVendorID.c_str() ).c_str() , mp_model->m_cpucoredata.m_wFamily , (WORD) mp_model->m_cpucoredata.m_byModel , (WORD) mp_model->m_cpucoredata.m_byStepping ) ); if( ! //gp_cpucontrolbase->mp_wxdynlibcpucontroller mp_wxx86infoandcontrolapp->m_p_cpucontrollerDynLib ) { mp_wxmenuFile->Enable( ID_SetCPUcontrollerDynLibForThisCPU, false ) ; mp_wxmenuFile->Enable( ID_DetachCPUcontrollerDynamicLibrary, false ) ; } mp_wxmenuFile->AppendSeparator(); p_wxmenuitem = mp_wxmenuFile->Append( ID_AttachCPUusageGetterDynLib, ATTACH_CPU_CORE_USAGE_GETTER_DYNAMIC_LIBRARY_T_STRING ); if( ! mp_wxx86infoandcontrolapp->GetCPUaccess() ) p_wxmenuitem->SetHelp ( //TODO more imformative/ user-friendly message (but may not be too long) wxT("No CPU access. See log file/ start this program as admin.") ) ; mp_wxmenuFile->Append( ID_DetachCPUusageGetterDynLib, DETACH_CPU_CORE_USAGE_GETTER_DYNAMIC_LIBRARY_T_STRING ); if( ! //gp_cpucontrolbase->mp_wxdynlibcpucoreusagegetter mp_wxx86infoandcontrolapp->m_p_cpucoreusagegetterDynLib ) mp_wxmenuFile->Enable( ID_DetachCPUusageGetterDynLib, false ) ; mp_wxmenuFile->AppendSeparator(); mp_wxmenuFile->Append( ID_SaveAsDefaultPstates, //wxT("Save &performance states settings...") wxT("Save \"&voltage at/for frequency\" settings...") ); //Only add menu item if creating the system tray icon succeeded: else one // can hide the window but can not restore it: if this process started //elevated one can't even close it! if( mp_wxx86infoandcontrolapp->ShowTaskBarIcon(this) ) { mp_wxmenuFile->AppendSeparator(); // mp_wxx86infoandcontrolapp->ShowTaskBarIcon(this) ; mp_wxmenuFile->Append( ID_MinimizeToSystemTray, _T("minimize this window to the " //"system tray" "task bar") ); } //#endif //COMPILE_WITH_TASKBAR mp_wxmenuFile->AppendSeparator(); //mp_wxmenuFile->Append( ID_Service, _T("Run As Service") ); mp_wxmenuFile->Append( ID_Quit, _T("E&xit") ); //p_wxmenuBar->Append( mp_wxmenuFile, _T("&File") ); //m_wxmenubar.Append( mp_wxmenuFile, _T("&File") ); mp_wxmenubar->Append( mp_wxmenuFile, _T("&File") ); LOG("after file menu creation"//\n" ) } /** @brief creates menu items for the "GUI" menu. */ inline void MainFrame::CreateGUImenuItems() { m_p_wxmenuGUI = NULL ; //#ifdef COMPILE_WITH_SERVICE_CONTROL #ifdef COMPILE_WITH_OTHER_DVFS_ACCESS if( ! m_p_wxmenuGUI ) m_p_wxmenuGUI = new wxMenu; mp_wxmenuitemOtherDVFS = m_p_wxmenuGUI->Append( //ID_MinAndMaxCPUcoreFreqInPercentOfMaxFreq ID_DisableOtherVoltageOrFrequencyAccess //_T("&CPU % min and max.") //_T("enable or disable OS's dynamic frequency scaling") , wxT("DISable OS's dynamic frequency scaling") ); mp_wxmenuitemOtherDVFS = m_p_wxmenuGUI->Append( ID_EnableOtherVoltageOrFrequencyAccess , wxT("ENable OS's dynamic frequency scaling") ); LOGN("after appending menu item \"disable OS's dynamic frequency scaling\"") //If one can not change the power scheme (Windows) etc. if( //mp_i_cpucontroller->mp_dynfreqscalingaccess-> mp_wxx86infoandcontrolapp->mp_dynfreqscalingaccess-> ChangeOtherDVFSaccessPossible() ) LOGN("Changing other DVFS is possible." ) else { LOGN("Changing other DVFS is not possible." ) mp_wxmenuitemOtherDVFS->Enable(false); mp_wxmenuitemOtherDVFS->SetHelp ( wxT("Start e.g. as administrator to gain access") ) ; //mp_wxmenuitemOtherDVFS->SetItemLabel (wxT("dd") ) ; LOGN("changing other DVFS not possible") } if( //mp_i_cpucontroller->mp_dynfreqscalingaccess->EnablingIsPossible() mp_wxx86infoandcontrolapp->mp_dynfreqscalingaccess->EnablingIsPossible() ) { LOGN("enabling other DVFS is possible") // std::tstring stdtstr = p_wxx86infoandcontrolapp->mp_dynfreqscalingaccess-> // GetEnableDescription() ; std::wstring stdwstr = mp_wxx86infoandcontrolapp->mp_dynfreqscalingaccess-> GetEnableDescription() ; mp_wxmenuitemOtherDVFS = m_p_wxmenuGUI->Append( ID_EnableOtherVoltageOrFrequencyAccess //_T("enable OS's dynamic frequency scaling") //GetDisableDescrpition() under Windows may return "activate 'performance' power scheme ". //Use GetwxString(...) because GetEnableDescription() may return // -std::wstring although wxString uses char strings. // -std::string although wxString uses wchar_t strings. , wxWidgets::getwxString( //mp_i_cpucontroller->mp_dynfreqscalingaccess->GetEnableDescription() // stdtstr stdwstr ) ); LOGN("after appending menu item \"" << GetStdString(stdwstr) << "\"") } #endif //#ifdef COMPILE_WITH_OTHER_DVFS_ACCESS LOG("after extras menu creation"//\n" ) if( ! m_p_wxmenuGUI ) m_p_wxmenuGUI = new wxMenu; std::string stdstr = "set update view interval" ; LOGN("before appending menu item " << stdstr ) m_p_wxmenuGUI->Append( ID_UpdateViewInterval, //_T("&CPU % min and max.") wxWidgets::getwxString( stdstr ) ); stdstr = "collect p-states as default voltage p-states" ; LOGN("before appending menu item " << stdstr ) mp_wxmenuitemCollectAsDefaultVoltagePerfStates = m_p_wxmenuGUI-> AppendCheckItem( ID_Collect_As_Default_Voltage_PerfStates, //_T("&CPU % min and max.") wxWidgets::getwxString( stdstr ) ); //#ifdef _WIN32 //Built-in macro for MSVC, MinGW (also for 64 bit Windows) //wxMenu * m_p_wxmenuGUI = new wxMenu; //#endif //if( ! p_cpucontroller->mp_model->m_cpucoredata. // m_stdsetvoltageandfreqDefault.empty() // ) { if( ! m_p_wxmenuGUI ) m_p_wxmenuGUI = new wxMenu;//(wxT("Graphical User Interface")); stdstr = "enable own Dynamic Voltage and Frequency Scaling" ; LOGN("before appending menu item " << stdstr ) mp_wxmenuitemOwnDVFS = m_p_wxmenuGUI->Append( ID_EnableOrDisableOwnDVFS , wxWidgets::getwxString( stdstr ) ); if( //p_cpucontroller->mp_model->m_cpucoredata. mp_model->m_cpucoredata. m_stdsetvoltageandfreqWanted.empty() ) { //Does not work. // mp_wxmenuitemOwnDVFS->Enable(false) ; // m_p_wxmenuGUI->Enable(ID_EnableOrDisableOwnDVFS , false ) ; // mp_wxmenuitemOwnDVFS->Enable(false) ; mp_wxmenuitemOwnDVFS->SetHelp( wxT("no desired voltages for frequencies" " available->no DVFS possible") ) ; } } //#endif //#ifdef _WIN32 #ifdef COMPILE_WITH_MSR_EXAMINATION if( ! m_p_wxmenuGUI ) m_p_wxmenuGUI = new wxMenu; m_p_wxmenuGUI->Append(ID_ShowExamineCPUregistersDialog, wxT("e&xamine CPUID and MSR CPU registers...") ); m_p_wxmenuGUI->Append(ID_WriteToMSRdialog, wxT("read from and write to MSR dialog...") ); #endif m_p_wxmenuGUI->Append( ID_LoadDetectInstableCPUcoreVoltageDynLib, wxT("Load dynamic library for detecting an instable CPU core voltage...") ); m_p_wxmenuitemUnloadDetectInstableCPUcoreVoltageDynLib = m_p_wxmenuGUI-> Append( ID_UnloadDetectInstableCPUcoreVoltageDynLib, wxT("Unload dynamic library for detecting an instable CPU core voltage") ); if( m_p_wxmenuGUI ) { LOGN("before adding menu \"GUI\"") mp_wxmenubar->Append(m_p_wxmenuGUI, //_T("E&xtras") wxT("&GUI") ); } } MainFrame::MainFrame( const wxString & cr_wxstrTitle, const wxPoint & cr_wxpointTopLeftCornerPosition, const wxSize & cr_wxsize , I_CPUcontroller * p_cpucontroller //, CPUcoreData * p_cpucoredata , Model * p_model , wxX86InfoAndControlApp * p_wxx86infoandcontrolapp ) : wxFrame( (wxFrame *) NULL, -1, cr_wxstrTitle, cr_wxpointTopLeftCornerPosition, cr_wxsize //http://docs.wxwidgets.org/2.6/wx_wxwindow.html#wxwindow: //"Use this style to force a complete redraw of the window whenever it is //resized instead of redrawing just the part of the window affected by //resizing. Note that this was the behaviour by default before 2.5.1 //release and that if you experience redraw problems with code which //previously used to work you may want to try this. Currently this style //applies on GTK+ 2 and Windows only, and full repainting is always done //on other platforms." //kurz: Stil ist notwendig, um das ganze Diagramm neu zu zeichnen , wxFULL_REPAINT_ON_RESIZE //| wxCLIP_CHILDREN //Necessary for showing a title bar | wxDEFAULT_FRAME_STYLE ) //, mp_cpucoredata(p_cpucoredata) //Initialize in the same order as textual in the declaration? //(to avoid g++ warnings) , m_bAllowCPUcontrollerAccess ( true ) , m_bCPUcoreUsageConsumed( true ) , m_bDiagramNotDrawn(true) , mp_ar_voltage_and_multi( NULL ) , m_bNotFirstTime(false) , m_bRangeBeginningFromMinVoltage ( true ) // , s_arfTemperatureInDegreesCelsius( NULL ) #ifdef COMPILE_WITH_CALC_THREAD , mp_calculationthread( NULL ) #endif , mp_cpucoredata( & p_model->m_cpucoredata ) , m_dwTimerIntervalInMilliseconds (1000) // , m_fPreviousCPUusage(0.0f) // , mp_freqandvoltagesettingdlg(NULL) , m_arp_freqandvoltagesettingdlg ( NULL ) , m_p_freqandvoltagesettingsdialog(NULL) , mp_i_cpucontroller ( p_cpucontroller) , mp_model ( p_model ) //, m_bConfirmedYet(true) , m_vbAnotherWindowIsActive(false) , m_wMaximumCPUcoreFrequency ( 0 ) , m_wMaxFreqInMHzTextWidth ( 0 ) , m_wMaxVoltageInVoltTextWidth ( 0 ) , m_wMaxTemperatureTextWidth ( 0 ) //, m_wxbufferedpaintdcStatic( this ) //Necessary for the timer to run: , mp_wxbitmap(NULL) , mp_wxbitmapStatic (NULL) , mp_wxbufferedpaintdcStatic( NULL) // , m_wxicon_drawer(16,16//,8 //// ,wxBITMAP_SCREEN_DEPTH // ) //, mp_wxdynlibcpucontroller ( NULL ) //, mp_wxdynlibcpucoreusagegetter ( NULL ) , m_wxstrTitle(cr_wxstrTitle) , m_wxtimer(this) , mp_wxx86infoandcontrolapp ( p_wxx86infoandcontrolapp ) // , m_xerces_voltage_for_frequency_configuration( p_model ) { LOGN("begin of main frame creation"//\n" ) wxIcon wxicon; if( p_wxx86infoandcontrolapp->GetX86IandCiconFromFile(wxicon) ) { SetIcon( wxicon); } else { // p_wxx86infoandcontrolapp->MessageWithTimeStamp( // GetStdWstring( wxT("setting icon for the main frame failed") ) // ); LOGN("setting icon from file for the main frame failed") wxIcon wxiconThisDialog( x86IandC_xpm ) ; SetIcon(x86IandC_xpm); } LOGN("# CPU cores: " << (WORD) mp_model->m_cpucoredata.m_byNumberOfCPUCores) // m_p_wxtimer = new wxTimer( this ) ; mp_ar_voltage_and_multi = new VoltageAndMulti[ mp_model->m_cpucoredata.m_byNumberOfCPUCores ] ; //"Cross-Platform GUI Programming with wxWidgets" // (Copyright © 2006 Pearson Education, Inc.) // ISBN 0-13-147381-6 "First printing, July 2005" //"CHAPTER 5 Drawing and Printing" -> //"UNDERSTANDING DEVICE CONTEXTS" -> "Drawing on Windows with wxPaintDC" : //"[...] call SetBackgroundStyle with wxBG_STYLE_CUSTOM to // hint to some systems not to clear the background automatically." SetBackgroundStyle(wxBG_STYLE_CUSTOM ); // m_bConfirmedYet = true ; mp_wxmenubar = new wxMenuBar; CreateFileMenu() ; //#ifdef COMPILE_WITH_OTHER_DVFS_ACCESS #ifdef COMPILE_WITH_SERVICE_PROCESS_CONTROL CreateServiceMenuItems() ; #endif // CreateAndInitMenuItemPointers() ; //p_wxmenuCore0->Append( ID_FindLowestOperatingVoltage, // _T("find lowest operating voltage") ); //p_wxmenuAllCores->Append( ID_FindLowestOperatingVoltage, //_T("find lowest operating voltage") ); //#ifdef PRIVATE_RELEASE //hide the other possibilities // p_wxmenuCore0->Append( ID_IncreaseVoltageForCurrentPstate, // _T("increase voltage for current p-state (stabilize machine)") ); //#endif //#ifdef PRIVATE_RELEASE //hide the other possibilities //UpdatePowerSettings(wxPOWER_UNKNOWN, wxBATTERY_UNKNOWN_STATE); CreateGUImenuItems(); if( mp_i_cpucontroller != NULL ) { CreateDynamicMenus(); } //#ifdef COMPILE_WITH_VISTA_POWERPROFILE_ACCESS // ////Connect the action, that is a class derived from class xx directly // ////with the menu item so that it is ensured to be the correct action // ////(calling the action in an event function is more error-prone) // ////TODO release memory // ////, new CalculationThread(byCoreID, HighALUloadThreadProc) // //, wxCommandEventHandler( MainFrame::OnOwnDynFreqScaling ) // //) ; // mp_wxmenubar->Append(m_p_wxmenuGUI, _T("E&xtras") ); //#endif //mp_wxmenubar->Append( p_wxmenuNorthBridge, _T("&NorthBridge") ); //TODO program crash here for unicode versions (for working versions // an OnSize() event was intermediate) LOGN("before setting menu bar " << mp_wxmenubar) //Just for testing. // wxSleep(5) ; //SetMenuBar( p_wxmenuBar ); //SetMenuBar( & m_wxmenubar ); SetMenuBar( mp_wxmenubar ); LOGN("before creating status bar") CreateStatusBar(); // const char bits [] = { // 0,0,0,0, // 1,1,1,1, // 0,0,0,0, // 1,1,1,1 // } ; // wxIcon wxicon(bits,4,4) ; // SetIcon(wxicon); // Connect(wxEVT_PAINT, wxPaintEventHandler(MainFrame::OnPaint)); //SetStatusText( _T("Welcome to wxWidgets!") ); LOGN("before starting the update view timer") //m_wxtimer.Start(1000); m_wxtimer.Start(m_dwTimerIntervalInMilliseconds); // m_p_wxtimer->Start(m_dwTimerIntervalInMilliseconds); //http://docs.wxwidgets.org/stable/wx_wxtimer.html#wxtimersetowner: //"Associates the timer with the given owner object. When the timer is //running, the owner will receive timer events with id equal to id //specified here." m_wxtimer.SetOwner(this, TIMER_ID) ; // Connect(wxEVT_SIZE, wxSizeEventHandler(MainFrame::OnSize)); if( mp_wxx86infoandcontrolapp->//mp_wxdynlibcpucontroller m_p_cpucontrollerDynLib ) { wxString wxstrCPUcontrollerDynLibPath( // //Use getwxString() to enable to compile with both unicode and ANSI. // getwxString( // mp_model->m_stdstrCPUcontrollerDynLibPath ) // ) ; //http://wiki.wxwidgets.org/Converting_everything_to_and_from_wxString#std::string_to_wxString: mp_model->m_stdstrCPUcontrollerDynLibPath.c_str(), wxConvUTF8 ); #if wxUSE_UNICODE == 1 DEBUGWN_WSPRINTF(L"CPU controller path as wide string:%ls", //wxstrCPUcontrollerDynLibPath.c_str() wxstrCPUcontrollerDynLibPath.wc_str() ) ; #endif CPUcontrollerDynLibAttached(wxstrCPUcontrollerDynLibPath) ; } if( mp_wxx86infoandcontrolapp->//mp_wxdynlibcpucoreusagegetter m_p_cpucoreusagegetterDynLib ) { wxString wxstrCPUcoreUsageGetterDynLibPath( //Use getwxString() to enable to compile with both unicode and ANSI. wxWidgets::getwxString( mp_model->m_stdstrCPUcoreUsageGetterDynLibPath) ) ; CPUcoreUsageGetterAttached(wxstrCPUcoreUsageGetterDynLibPath) ; } // mp_wxx86infoandcontrolapp->ShowTaskBarIcon(this) ; LOGN("end of main frame creation"//\n" ) // RedrawEverything() ; // Refresh() ; // InitDialog() ; } MainFrame::~MainFrame() { LOGN("begin" /*" of main frame's destructor"*/ ) //TODO Error here.the problem was with destructor of wxMenuBar.->create //wxMenuBar via "new"? //for(BYTE byCoreID = 0 ; byCoreID < //m_byCoreNumber // mp_cpucoredata->m_byNumberOfCPUCores ; ++ byCoreID ) //{ // //Release memory from the heap. // delete m_vecp_wxmenuCore.at(byCoreID) ; //} //Release memory for array of pointers. // delete [] m_arp_wxmenuitemPstate ; // delete [] marp_wxmenuItemHighLoadThread ; #ifdef COMPILE_WITH_CALC_THREAD if( mp_calculationthread ) delete mp_calculationthread ; #endif //Only terminates correctly when deleted from here (is also deleted in //the wxTopLevelWindow's (wxDialog's) destructor in wxWidgets' "tbtest.cpp" //from the "taskbar" sample. mp_wxx86infoandcontrolapp->DeleteTaskBarIcons(); LOGN("end" /*" of main frame's destructor"*/ ) } //void MyFrame::AddMenu() //{ // //wxEventTableEntry(type, winid, idLast, fn, obj) // EVT_MENU(ID_LastStaticEventID+1,MyFrame::OnDynamicMenu); //} // //void MyFrame::OnDynamicMenu(wxCommandEvent &event) //{ // //} //wxString MainFrame::BuildHighLoadThreadMenuText( // std::string str, // BYTE byPreviousAction) //{ // wxString wxstr = byPreviousAction == //ENDED ? // ICalculationThread::ended ? // //We need a _T() macro (wide char-> L"", char->"") for EACH // //line to make it compatible between char and wide char. // _T("Start") : // //We need a _T() macro (wide char-> L"", char->"") for EACH // //line to make it compatible between char and wide char. // _T("End") ; // ////Invert the menu item's checked state. // //marp_wxmenuItemHighLoadThread[byCoreID]->Check( // // ! marp_wxmenuItemHighLoadThread[byCoreID]->IsChecked () ) ; //// marp_wxmenuItemHighLoadThread[byCoreID]->SetText( //// wxstr + //// str //// ); // return wxstr + wxString( // //TODO this conversion may not work // (const wxChar*) str.c_str() ) ; //} //bool MainFrame::Confirm(const std::string & str) //{ // //::AfxMessageBox(str.c_str()); // // //To not show too many dialogs that the timer would bring up. //// if( m_bConfirmedYet ) //// { //// m_bConfirmedYet = false ; //// ::wxMessageBox(wxString( //// //TODO this conversion may not work //// (const wxChar * ) str.c_str() ) //// ); //// m_bConfirmedYet = true ; //// } // //m_bConfirmedYet = true ; // return true; //} //bool MainFrame::Confirm(std::ostrstream & r_ostrstream // //std::ostream & r_ostream // ) //{ // bool bReturn = true ; // DEBUGN("begin"); // //Must set this, else text may follow after the string we want. // //I had program crashes with the following method: // //pch[r_ostrstream.pcount()] = '\0' ; // //r_ostrstream.ends(); // r_ostrstream.put('\0'); //the same as "ends()" does. //// char *pch = r_ostrstream.str() ; // //r_ostrstream.flush(); // //To not show too many dialogs that the timer would bring up. //// if( m_bConfirmedYet ) //// { //// m_bConfirmedYet = false ; //// int nReturn = ::wxMessageBox( wxString( //// //TODO this conversion may not work //// (const wxChar * ) pch ) , //// //We need a _T() macro (wide char-> L"", char->"") for EACH //// //line to make it compatible between char and wide char. //// wxString( _T("Message") ) , wxCANCEL | wxOK ) ; //// if( nReturn == wxCANCEL ) //// bReturn = false ; //// m_bConfirmedYet = true ; //// } // //return true; // DEBUGN("end"); // return bReturn ; //} inline void MainFrame::ConnectToDataProvider_Inline() { mp_wxx86infoandcontrolapp->ConnectToDataProviderAndShowResult() ; } #ifdef COMPILE_WITH_SERVICE_PROCESS_CONTROL void MainFrame::CreateServiceMenuItems() { wxString wxstrConnectOrDisconnect ; p_wxmenuService = new wxMenu ; //TODO: set bitmap for item //http://docs.wxwidgets.org/trunk/classwx_menu_item.html#a2b5d6bcb820b992b1e4709facbf6d4fb: //"SetBitmap() must be called before the item is appended to the menu" // wxMenuItem * p_wxmenuitem = new wxMenuItem(); // p_wxmenuitem->SetBitmap(); if( ServiceBase::CanStartService() ) { p_wxmenuService->Append( ID_StartService , wxT("&start"), wxT("start the x86I&C service via the Service Control Manager") ) ; } else p_wxmenuService->Append( ID_StartService , wxT("&start"), wxT("insufficient rights to start the x86I&C service via the Service " "Control Manager") ) ; //Stopping a service can be done via Inter Process Communication. (Else if //via Service Control manager then needs the same? rights/ privileges as //starting a service). p_wxmenuService->Append( ID_StopService , wxT("s&top"), wxT("stop the x86I&C service via InterProcess Communication or via " "Service Control Manager") ); #ifdef COMPILE_WITH_NAMED_WINDOWS_PIPE p_wxmenuService->Append( ID_ConnectToService, wxT("connect..."), wxT("connect to an arbitrary address to the (x86IandC) " "CPU core data provider/ server/ service") ); // if( mp_wxx86infoandcontrolapp->m_ipcclient.IsConnected() ) // wxstrConnectOrDisconnect = wxT("disconnect") ; // else wxstrConnectOrDisconnect = wxT("c&onnect to ") + wxWidgets::getwxString( mp_model->m_userinterfaceattributes.m_std_wstrServiceAddress); p_wxmenuService->Append( ID_ConnectToOrDisconnectFromService, wxstrConnectOrDisconnect, wxT("connect to the (x86IandC) " "CPU core data provider/ server/ service" // " specified in the x86IandC " // "config file" ) ); p_wxmenuService->Append( ID_DisconnectFromService, wxT("&DISCOnnect"), wxT("DISconnect from the (x86IandC) " "CPU core data provider/ server/ service if currently connected") ); #endif //#ifdef COMPILE_WITH_NAMED_WINDOWS_PIPE //pause and continue is possible via service ctrl mgr p_wxmenuService->Append( ID_ContinueService, wxT("&Continue"), wxT("continue " "the Dynamic Voltage and Frequency Scaling done by the x86IandC service/ " "server") ); p_wxmenuService->Append( ID_PauseService , wxT("&Pause"), wxT("pause " "the Dynamic Voltage and Frequency Scaling done by the x86IandC service/ " "server") ); // p_wxmenuService->Append( ID_StartService , _T("&Start") ); // p_wxmenuService->Append( ID_StopService , _T("Sto&p") ); mp_wxmenubar->Append( p_wxmenuService, wxT("&Service") ) ; LOGN("end" /*" of CreateServiceMenuItems"*/ ) } #endif //#ifdef COMPILE_WITH_SERVICE_PROCESS_CONTROL ////void //wxMenuItem * MainFrame::AddDynamicallyCreatedMenu( // wxMenu * p_wxmenu, // WORD & r_wMenuID, // const wxString & r_wxstr // ) //{ // wxMenuItem * p_wxmenuitemAppended = p_wxmenu->Append(r_wMenuID, r_wxstr ); // Connect( r_wMenuID ++ , //wxID_ANY, // wxEVT_COMMAND_MENU_SELECTED , // wxCommandEventHandler(MainFrame::OnDynamicallyCreatedUIcontrol) // ); // return p_wxmenuitemAppended ; //} //wxMenuItem * MainFrame::AddDynamicallyCreatedMenu( // wxMenu * p_wxmenu, // WORD & r_wMenuID, // const wxString & r_wxstr // , //void (wxEvtHandler::*wxEventFunction)(wxEvent&) // wxObjectEventFunction wxeee // , SpecificCPUcoreActionAttributes * p_scaa // ) //{ // m_stdmapwxuicontroldata.insert( // std::make_pair( // r_wMenuID , // //TODO release memory // p_scaa // ) // ) ; // wxMenuItem * p_wxmenuitemAppended = p_wxmenu->Append(r_wMenuID, r_wxstr ); // Connect( r_wMenuID ++ , //wxID_ANY, // wxEVT_COMMAND_MENU_SELECTED , // //wxCommandEventHandler( // //wxEventFunction //) // wxeee // ); // return p_wxmenuitemAppended ; //} //wxMenuItem * MainFrame::AddDynamicallyCreatedMenu( // wxMenu * p_wxmenu, // WORD & r_wMenuID, // const wxString & r_wxstr, // //Use a concrete class as parameter because this is more flexible than // //using a function with (a) fixed parameter type(s). // //Another option: use C functions: then parameter here would be: // //"void func(PVOID)" // //function A (PVOID pv) // //{ ActionAParamStruct * paramstr = (ActionAParamStruct) // // ActionAParamStruct: necessary parameters for execution (like CPU core ID) // // pv ; } // // // I_CPUcontrollerAction * icpuca // ) //{ // wxMenuItem * p_wxmenuitemAppended = p_wxmenu->Append(r_wMenuID, r_wxstr ); // m_stdmapwmenuid2i_cpucontrolleraction.insert( // std::make_pair (r_wMenuID,icpuca) // ) ; // Connect( r_wMenuID ++, wxID_ANY, wxEVT_COMMAND_MENU_SELECTED, // wxCommandEventHandler(MainFrame::OnDynamicallyCreatedUIcontrol) // ); // return p_wxmenuitemAppended ; //} //void MainFrame::CreateAndInitMenuItemPointers() //{ // marp_wxmenuItemHighLoadThread = new wxMenuItem * [ // mp_cpucoredata->m_byNumberOfCPUCores ] ; // for( BYTE byIndex = 0 ; byIndex < mp_cpucoredata->m_byNumberOfCPUCores ; // ++ byIndex ) // marp_wxmenuItemHighLoadThread[ byIndex ] = NULL ; //} // ////void ////Return: TRUE: success. //BYTE MainFrame::AddSetPstateMenuItem( // wxMenu * p_wxmenuCore // , BYTE byCoreID // , BYTE byPstateID // //Must be a reference because changes to the variable should be // //maintained OUTside this function. // , WORD & r_wMenuID // ) //{ // BYTE byReturnValue = FALSE ; // return byReturnValue ; //} void MainFrame::Create1DialogAndMenuForAllCores() { wxMenu * p_wxmenuCore ; p_wxmenuCore = new wxMenu; if( p_wxmenuCore ) { m_p_wxmenuCore = p_wxmenuCore; p_wxmenuCore->Append(//ID_LastStaticEventID ID_ShowVoltageAndFrequencySettingsDialog, _T("set frequency and voltage ") ); mp_wxmenubar->Append( p_wxmenuCore, //We need a wxT() macro (wide char-> L"", char->"") for EACH //line to make it compatible between char and wide char. wxT("core(s)") ); // Connect( ID_LastStaticEventID, wxID_ANY, wxEVT_COMMAND_MENU_SELECTED, // wxCommandEventHandler( // MainFrame::OnVoltageAndFrequencySettingsDialog ) // ); // LOGN("Connected event ID" << ID_LastStaticEventID << " to" << // "MainFrame::OnPstateDialog.") } } void MainFrame::CreateDialogAndMenuForEveryCore() { // BYTE byReturnValue ; WORD wMenuID = ID_LastStaticEventID; wxMenu * p_wxmenuCore ; m_arp_freqandvoltagesettingdlg = new FreqAndVoltageSettingDlg * [ mp_cpucoredata->m_byNumberOfCPUCores]; if(m_arp_freqandvoltagesettingdlg) { BYTE byPointerSize = sizeof( m_arp_freqandvoltagesettingdlg[0] ) ; //important: init pointers with NULL memset( m_arp_freqandvoltagesettingdlg , //NULL 0 , byPointerSize * mp_cpucoredata->m_byNumberOfCPUCores ); //TRACE("sizeof: %u\n", sizeof(m_arp_freqandvoltagesettingdlg)); #ifdef _DEBUG // int i = sizeof(m_arp_freqandvoltagesettingdlg) ; #endif for( BYTE byCoreID = 0 ; byCoreID < //m_byCoreNumber mp_cpucoredata->m_byNumberOfCPUCores ; ++ byCoreID ) { p_wxmenuCore = new wxMenu; //Memorize dynamically created menus in order to delete them of a // CPU controller DLL is attached more than once (else the wxWindows // are deleted automatically when the superordinate window is closed). m_vecp_wxmenuCore.push_back(p_wxmenuCore); p_wxmenuCore->Append(wMenuID, _T("set frequency and voltage ") ); //for(BYTE byDivisorID = 0 ; byDivisorID < FIRST_RESERVED_DIVISOR_ID ; // ++ byDivisorID ) //{ // Connect( wMenuID ++, wxID_ANY, wxEVT_COMMAND_MENU_SELECTED, // wxCommandEventHandler(MyFrame::OnRuntimeCreatedMenu)//, & m_vecwxstring.back() // ); //} if( byCoreID == 0 ) m_nLowestIDForSetVIDnFIDnDID = wMenuID ; // wxCPUcoreID wxcpucoreid(byCoreID) ; // m_stdvectorwxuicontroldata.push_back( //wxCPUcoreID(byCoreID) // wxcpucoreid // //wxObject() // ) ; m_stdmapwxuicontroldata.insert( std::make_pair( wMenuID , //TODO release memory //new wxCPUcoreID(byCoreID) new SpecificCPUcoreActionAttributes(byCoreID) //wxcpucoreid //wxObject() ) ) ; #ifdef _DEBUG // wxCPUcoreID * p_wxcpucoreid = (wxCPUcoreID *) //wxevent.m_callbackUserData ; //& m_stdmapwxuicontroldata.find( wMenuID )->second ; //wxCPUcoreID & r_wxcpucoreid = (wxCPUcoreID &) //wxevent.m_callbackUserData ; // m_stdmapwxuicontroldata.find( wMenuID )->second ; #endif // Connect( wMenuID ++, wxID_ANY, wxEVT_COMMAND_MENU_SELECTED, // wxCommandEventHandler( // //MainFrame::OnDynamicallyCreatedUIcontrol // MainFrame::OnVoltageAndFrequencySettingsDialog )//, & m_vecwxstring.back() // //new wx // //, & m_stdvectorwxuicontroldata.back() // ); // LOGN("connected event ID" << wMenuID - 1 << " to" << // "MainFrame::OnPstateDialog") p_wxmenuCore->Append(wMenuID, _T("find different p-states") ); Connect( wMenuID ++, wxID_ANY, wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler( MainFrame::OnFindDifferentPstates ) ); LOGN("connected event ID" << wMenuID - 1 << " to" << "MainFrame::OnFindDifferentPstates") #ifdef COMPILE_WITH_CALC_THREAD marp_wxmenuItemHighLoadThread[byCoreID] = AddDynamicallyCreatedMenu( p_wxmenuCore, wMenuID, //_T("high load thread (for stability check)") BuildHighLoadThreadMenuText( "high FPU load thread (for stability check)" ) //Connect the action, that is a class derived from class xx directly //with the menu item so that it is ensured to be the correct action //(calling the action in an event function is more error-prone) //TODO release memory //, new CalculationThread(byCoreID, FPUcalculationThreadProc) , wxCommandEventHandler( MainFrame::OnHighLoadThread ) , new CalculationThread( byCoreID , FPUcalculationThreadProc , & ::wxGetApp() , ::wxGetApp().GetCPUcontroller() ) ) ; //#endif //#ifdef COMPILE_WITH_CALC_THREAD marp_wxmenuItemHighLoadThread[byCoreID] = AddDynamicallyCreatedMenu( p_wxmenuCore,wMenuID, //_T("high load thread (for stability check)") BuildHighLoadThreadMenuText( std::string( "high ALU load thread (for stability check)" ) ) //Connect the action, that is a class derived from class xx directly //with the menu item so that it is ensured to be the correct action //(calling the action in an event function is more error-prone) //TODO release memory //, new CalculationThread(byCoreID, HighALUloadThreadProc) , wxCommandEventHandler( MainFrame::OnHighLoadThread ) , new CalculationThread( byCoreID , HighALUloadThreadProc , & ::wxGetApp() , ::wxGetApp().GetCPUcontroller() ) ) ; #endif // #ifdef COMPILE_WITH_CALC_THREAD //marp_wxmenuItemHighLoadThread[byCoreID] = AddDynamicallyCreatedMenu( // p_wxmenuCore, // wMenuID, //_T("high load thread (for stability check)") // _T("own DVFS") // //Connect the action, that is a class derived from class xx directly // //with the menu item so that it is ensured to be the correct action // //(calling the action in an event function is more error-prone) // //TODO release memory // //, new CalculationThread(byCoreID, HighALUloadThreadProc) // , wxCommandEventHandler( MainFrame::OnOwnDynFreqScaling ) // , new SpecificCPUcoreActionAttributes(byCoreID) // ) ; //OnOwnDynFreqScaling //m_arp_wxmenuitemPstate[byCoreID * NUMBER_OF_PSTATES + 1] = // AddDynamicallyCreatedMenu(p_wxmenuCore,wMenuID, _T("Set p-state &1")) ; m_byNumberOfSettablePstatesPerCore = //NUMBER_OF_PSTATES ; 0 ; if( byCoreID == 0 ) m_byMenuIndexOf1stPstate = wMenuID - m_nLowestIDForSetVIDnFIDnDID ; //if( typeid (mp_i_cpucontroller ) == typeid(GriffinController) ) //{ // for( byPstateID = 0 ; byPstateID < //3 // m_byNumberOfSettablePstatesPerCore ; ++ byPstateID && // //if == TRUE // byReturnValue // ) // byReturnValue = AddSetPstateMenuItem( // p_wxmenuCore, byCoreID, byPstateID, wMenuID ) ; //} // if( byReturnValue ) { if( byCoreID == 0 ) { m_nNumberOfMenuIDsPerCPUcore = wMenuID - ID_LastStaticEventID ; //For removing per-core menus after unloading a CPU controller. m_byIndexOf1stCPUcontrollerRelatedMenu = mp_wxmenubar->GetMenuCount() ; } //marp_wxmenuItemHighLoadThread[byCoreID] = AddDynamicallyCreatedMenu( // p_wxmenuCore,wMenuID, _T("high load thread (for stability check)")) ; //m_wxmenubar.Append(p_wxmenuCore, _T("for core &")+ byCoreID); mp_wxmenubar->Append( p_wxmenuCore, wxString::Format( //We need a _T() macro (wide char-> L"", char->"") for EACH //line to make it compatible between char and wide char. _T("%s%u") //, _T("for core &") , _T("core &") , //_T('0'+byCoreID) byCoreID ) ); //marp_wxmenuItemHighLoadThread[byCoreID]->Check(true) ; //marp_wxmenuItemHighLoadThread[byCoreID]->Enable(false); } } //for-loop } } //void //Return value: BYTE MainFrame::CreateDynamicMenus() { // BYTE byPstateID = 0 ; BYTE byReturnValue = //Needs to be TRUE for the 1st loop condition evaluation. TRUE ; // WORD wMenuID = ID_LastStaticEventID; //m_vecwxstring.push_back(wxString) // wxMenu * p_wxmenuCore ; LOGN("CPU core menu creation--number of CPU cores: " << (WORD) mp_cpucoredata->m_byNumberOfCPUCores ) // byReturnValue = // CreateDialogAndMenuForEveryCore() ; Create1DialogAndMenuForAllCores() ; //SetMenuBar(&m_wxmenubar); return byReturnValue ; } void MainFrame::AllowCPUcontrollerAccess() { wxCriticalSectionLocker wxcriticalsectionlocker( m_wxcriticalsectionCPUctlAccess ) ; m_bAllowCPUcontrollerAccess = true ; } void MainFrame::DenyCPUcontrollerAccess() { DEBUGN("MainFrame::DenyCPUcontrollerAccess() begin" ) wxCriticalSectionLocker wxcriticalsectionlocker( m_wxcriticalsectionCPUctlAccess ) ; m_bAllowCPUcontrollerAccess = false ; DEBUGN("MainFrame::DenyCPUcontrollerAccess() end" ) } void MainFrame::DisableWindowsDynamicFreqScalingHint() { wxMessageBox( //We need a _T() macro (wide char-> L"", char->"") for EACH //line to make it compatible between char and wide char. _T("Remember: the OS' dynamic frequency scaling should be ") _T("deactivated the change to take effect\n") _T("see help/ disable by: ") _T("Start->control panel->energy options") _T("->change the current power plan") _T("->change extended energy options") _T("->set minimal and maximal CPU load to the same percentage") ); } void MainFrame::OnClose(wxCloseEvent & event ) { LOGN("begin" /*"Requested to close the main frame"*/) //Stop the timer (indirectly calls OnPaint()-> so another IPC thread could //be spawned). m_wxtimer.Stop() ; LOGN("Stopped the \"update view\" timer") // m_p_wxtimer->Stop() ; mp_wxx86infoandcontrolapp->EndGetCPUcoreDataViaIPCthread() ; //May be NULL at startup. if( mp_cpucoredata->m_arp_percpucoreattributes // CPU cores > 0 && mp_cpucoredata->m_byNumberOfCPUCores ) { PerCPUcoreAttributes * p_percpucoreattributes = & mp_cpucoredata-> m_arp_percpucoreattributes[ //p_atts->m_byCoreID 0 ] ; if ( p_percpucoreattributes->mp_dynfreqscalingthread ) { p_percpucoreattributes->mp_dynfreqscalingthread->Stop() ; LOGN("stopped the Dynamic Voltage and Frequency Scaling thread") //p_percpucoreattributes->mp_dynfreqscalingthread->Delete() ; p_percpucoreattributes->mp_dynfreqscalingthread = NULL ; } } mp_wxx86infoandcontrolapp->CheckForChangedVoltageForFrequencyConfiguration(); mp_wxx86infoandcontrolapp->DeleteTaskBarIcons(); LOGN("before destroying the mainframe") //see http://docs.wxwidgets.org/2.8/wx_windowdeletionoverview.html: this->Destroy() ; LOGN("after destroying the mainframe") } void MainFrame::OnCollectAsDefaultVoltagePerfStates( wxCommandEvent & WXUNUSED(event) ) { mp_model->m_bCollectPstatesAsDefault = mp_wxmenuitemCollectAsDefaultVoltagePerfStates->IsChecked () ; } void MainFrame::OnConnectToService( wxCommandEvent & WXUNUSED(event) ) { wxString wxstrTextFromUser = ::wxGetTextFromUser( wxT("enter server address") //const wxString & message, //const wxString & caption = "Input text", //const wxString & default_value = "", //wxWindow * parent = NULL, //int x = wxDefaultCoord, //int y = wxDefaultCoord, //bool centre = true ) ; // std::string strstrMessage ; mp_wxx86infoandcontrolapp->ConnectIPCclient( wxstrTextFromUser //, //strstrMessage ) ; } void MainFrame::OnConnectToOrDisconnectFromService( wxCommandEvent & WXUNUSED(event) ) { #ifdef COMPILE_WITH_NAMED_WINDOWS_PIPE if( //::wxGetApp().m_ipcclient.IsConnected() mp_wxx86infoandcontrolapp->IPC_ClientIsConnected() ) ::wxMessageBox( //Use wxT() to enable to compile with both unicode and ANSI. wxT("already connected to the service") ) ; else { // if( ::wxGetApp().m_ipcclient.ConnectToDataProvider() ) // p_wxmenuService->SetLabel( ID_ConnectToOrDisconnectFromService , // wxT( "disconnect" ) // ) ; ConnectToDataProvider_Inline() ; } #endif } void MainFrame::OnContinueService(wxCommandEvent & WXUNUSED(event)) { LOGN(//"OnContinueService--" "begin") //ServiceBase::ContinueService( //mp_model->m_strServiceName.c_str() // "CPUcontrolService" ); #ifdef COMPILE_WITH_NAMED_WINDOWS_PIPE wxString wxstrMessageFromDataProvider; if( ! mp_wxx86infoandcontrolapp-> ContinueServiceViaIPC(wxstrMessageFromDataProvider) ) // ::wxMessageBox( wxT("message from the service:\n") + // wxstrMessageFromDataProvider ) ; // else ::wxMessageBox( //Use wxT() to enable to compile with both unicode and ANSI. wxT("could not continue because not connected to the service") ) ; #endif //#ifdef COMPILE_WITH_NAMED_WINDOWS_PIPE } void MainFrame::OnDisableOtherVoltageOrFrequencyAccess( wxCommandEvent & WXUNUSED(event) ) { #ifdef COMPILE_WITH_OTHER_DVFS_ACCESS ::wxGetApp().mp_dynfreqscalingaccess->DisableFrequencyScalingByOS() ; #endif //#ifdef COMPILE_WITH_OTHER_DVFS_ACCESS } void MainFrame::OnDisconnectFromService( wxCommandEvent & WXUNUSED(event) ) { #ifdef COMPILE_WITH_NAMED_WINDOWS_PIPE if( //mp_wxx86infoandcontrolapp->m_ipcclient.IsConnected() mp_wxx86infoandcontrolapp->IPC_ClientIsConnected() ) //mp_wxx86infoandcontrolapp->m_ipcclient.Disconnect_Inline() ; mp_wxx86infoandcontrolapp->IPCclientDisconnect() ; else { ::wxMessageBox( //Use wxT() to enable to compile with both unicode and ANSI. wxT("NOT connected to the service") ) ; } #endif } void MainFrame::OnEnableOtherVoltageOrFrequencyAccess( wxCommandEvent & WXUNUSED(event) ) { #ifdef COMPILE_WITH_OTHER_DVFS_ACCESS ::wxGetApp().mp_dynfreqscalingaccess->EnableFrequencyScalingByOS() ; #endif //#ifdef COMPILE_WITH_OTHER_DVFS_ACCESS } void MainFrame::OnFindDifferentPstates( wxCommandEvent & WXUNUSED(event) ) { //May be NULL at startup (before a controller DLL becomes attached). if( mp_i_cpucontroller ) { //wxString wxstrInput = ::wxGetTextFromUser( wxstrMessage , wxT("input"), // wxT("1000") ) ; ////::wxGetNumberFromUser ////If the user has input text (and has NOT pressed "cancel") //if( ! wxstrInput.empty() ) //{ // unsigned long ulMs ; // bool bSuccess = wxstrInput.ToULong(& ulMs) ; // if ( bSuccess ) // { // //ReadMsrEx() returned false results if used with a time and a 10 ms interval. // if( ulMs < 100 ) // wxMessageBox( wxT("the number is too low. " // "Getting the current CPU frequency returned wrong values with < 100 ms") ) ; // else // { // m_dwTimerIntervalInMilliseconds = ulMs ; // m_wxtimer.Stop() ; // m_wxtimer.Start(ulMs) ; // } // } // else // { // wxMessageBox( wxT("You did not enter a valid integer number") ) ; // } //} //Must create dynamically, else the CalculationThread is destroyed after leaving //this block. //if( ! mp_calculationthread ) //{ // mp_calculationthread = new CalculationThread( // 0 // , FindDifferentPstatesThreadProc // , & ::wxGetApp() // , ::wxGetApp().GetCPUcontroller() // ) ; //} //if( mp_calculationthread ) // mp_calculationthread->Execute() ; long lMin = ::wxGetNumberFromUser( wxT("input mininum frequency:"), wxT("prompt:"), wxT("caption:"), mp_i_cpucontroller->GetMinimumFrequencyInMHz() , 0 , mp_i_cpucontroller->GetMaximumFrequencyInMHz() ) ; //If the user enters an invalid value or cancels the dialog, the function will return -1. if( lMin == -1 ) ::wxMessageBox(wxT("either invalid value or cancel") ) ; else { long lMax = ::wxGetNumberFromUser( wxT("input maxinum frequency:"), wxT("prompt:"), wxT("caption:"), mp_i_cpucontroller->GetMaximumFrequencyInMHz() , lMin , mp_i_cpucontroller->GetMaximumFrequencyInMHz() ) ; if( lMax == -1 ) ::wxMessageBox(wxT("either invalid value or cancel") ) ; else { //TODO use available _mulipliers_ and call GetVoltageAndFrequency( // voltage, multiplier, refclock, ) //instead of frequencies // std::set<VoltageAndFreq> stdsetvoltageandfreq ; // std::set<VoltageAndFreq>::iterator iter ; // mp_i_cpucontroller->GetAllPossibleFrequencies( stdsetvoltageandfreq ) ; // //iter = stdsetvoltageandfreq.find(lMin) ; // iter = stdsetvoltageandfreq.begin() ; // while( iter != stdsetvoltageandfreq.end() ) // { // if( lMin >= iter->m_wFreqInMHz ) // break ; // iter ++ ; // } // // // //if( iter != stdsetvoltageandfreq.end() ) // { // float fVolt ; // WORD wFreq ; // //for( WORD wFreq = lMin ; wFreq < lMax ; wFreq += 50 ) // while( iter != stdsetvoltageandfreq.end() ) // { // //mp_i_cpucontroller->GetNearestHigherPossibleFreqInMHz( lMin ) ; // mp_i_cpucontroller->SetFreqAndVoltageFromFreq( //wFreq, // iter->m_wFreqInMHz , // mp_model->m_cpucoredata.m_stdsetvoltageandfreqDefault // //mp_model->m_cpucoredata.m_stdsetvoltageandfreqPossibleByCPU // //stdsetvoltageandfreq // , 0 ) ; // ::wxMilliSleep(100) ; // mp_i_cpucontroller->GetCurrentPstate( //wFreq, // wFreq , // fVolt // , 0 ) ; // if( wFreq == iter->m_wFreqInMHz ) // if( mp_model->m_cpucoredata.AddDefaultVoltageForFreq( fVolt, wFreq ) ) // RedrawEverything() ; // ++ iter ; // } // } } } //::wxMilliSleep() } //if( mp_i_cpucontroller ) } void MainFrame::OnLoadDetectInstableCPUcoreVoltageDynLib(wxCommandEvent & event) { #ifdef _WIN32 mp_wxx86infoandcontrolapp->LoadDetectInstableCPUcoreVoltageDynLib(); #endif } void MainFrame::OnUnloadDetectInstableCPUcoreVoltageDynLib(wxCommandEvent & event) { #ifdef _WIN32 mp_wxx86infoandcontrolapp->UnloadDetectInstableCPUcoreVoltageDynLib(); #endif } void MainFrame::OnMinimizeToSystemTray(wxCommandEvent & WXUNUSED(event)) { Hide() ; } void MainFrame::OnMoveMouse(wxMouseEvent & r_wxmouseevent) { LOGN( "begin") wxPoint wxpoint = r_wxmouseevent.GetPosition(); float fReferenceClockInMHz; const float fMultiplier = GetClosestMultiplier(wxpoint.x, fReferenceClockInMHz); const float fClosestFrequency = fMultiplier * fReferenceClockInMHz; const float fClosestVoltageToYcoordinate = GetClosestVoltageForYcoordinate( wxpoint.y); SetStatusText( wxString::Format( wxT("(%f Volt,%f MHz)"), fClosestVoltageToYcoordinate, fClosestFrequency ) ); LOGN( "end") } void MainFrame::OnLeftMouseButtonDown(wxMouseEvent & r_wxmouseevent) { const wxPoint & c_r_wxpointPos = r_wxmouseevent.GetPosition(); if( m_p_freqandvoltagesettingsdialog ) { float fVoltageInVolt = GetClosestVoltageForYcoordinate(c_r_wxpointPos.y); float fReferenceClockInMHz; float fMultiplier = GetClosestMultiplier(c_r_wxpointPos.x, fReferenceClockInMHz); m_p_freqandvoltagesettingsdialog->SetMultiplierSliderToClosestValue( fMultiplier); m_p_freqandvoltagesettingsdialog->HandleMultiplierValueChanged() ; BYTE byIndexForClosestVoltage = m_p_freqandvoltagesettingsdialog-> SetVoltageSliderToClosestValue(fVoltageInVolt) ; m_p_freqandvoltagesettingsdialog->ChangeVoltageSliderValue( byIndexForClosestVoltage) ; m_p_freqandvoltagesettingsdialog = NULL; SetCursor(wxNullCursor); } } void MainFrame::OnPauseService(wxCommandEvent & WXUNUSED(event)) { LOGN( //"OnPauseService" "begin") #ifdef COMPILE_WITH_NAMED_WINDOWS_PIPE wxString wxstrMessageFromService; mp_wxx86infoandcontrolapp->PauseService(wxstrMessageFromService); // ::wxMessageBox( wxT("message from the service:\n") + wxstrMessageFromService // ) ; #endif //#ifdef COMPILE_WITH_NAMED_WINDOWS_PIPE } //void MainFrame::OnShowVoltageAndFrequencySettingsDialog( // wxCommandEvent & WXUNUSED(event) ) //{ // //} void MainFrame::OnStartService(wxCommandEvent & WXUNUSED(event)) { #ifdef COMPILE_WITH_SERVICE_PROCESS_CONTROL mp_wxx86infoandcontrolapp->StartService() ; #endif //#ifdef COMPILE_WITH_SERVICE_PROCESS_CONTROL } void MainFrame::OnStopService(wxCommandEvent & WXUNUSED(event)) { #ifdef COMPILE_WITH_SERVICE_PROCESS_CONTROL //ServiceBase::StopService( //mp_model->m_strServiceName.c_str() // "CPUcontrolService" ); mp_wxx86infoandcontrolapp->StopService() ; #endif //#ifdef COMPILE_WITH_SERVICE_PROCESS_CONTROL } void MainFrame::OnSysTrayIconClick(wxCommandEvent & WXUNUSED(event)) { ::wxMessageBox( wxT("OnSysTrayIconClick") ) ; } void MainFrame::OnAbout(wxCommandEvent& WXUNUSED(event)) { // wxString wxstrMessage ; // GetAboutMessage(wxstrMessage) ; // ::wxMessageBox( // wxstrMessage , // _T("About ") //_T(PROGRAM_NAME) // //+ mp_i_cpucontroller->mp_model->m_stdtstrProgramName // + mp_model->m_stdtstrProgramName // , // wxOK | wxICON_INFORMATION //, //// this // ); AboutDialog * p_aboutdialog = new AboutDialog( * mp_model, wxWidgets::getwxString( mp_model->m_stdtstrProgramName) ) ; p_aboutdialog->//Show() ; ShowModal(); p_aboutdialog->Destroy() ; } void MainFrame::OnAttachCPUcontrollerDLL (wxCommandEvent & event) { wxString wxstrExtension = wxT("") ; //Under Windows it returns ".dll" //wxstrExtension = wxDynamicLibrary::CanonicalizeName(wxstrExtension) ; wxstrExtension = wxDynamicLibrary::GetDllExt() ; //Get rid of the leading ".". wxstrExtension = wxstrExtension.Right( wxstrExtension.length() - 1 ) ; wxString wxstrCPUcontrollerDynLibFilePath = ::wxFileSelector( wxT("Select dynamic library for CPU info and/or control") , wxEmptyString //default_path , wxEmptyString //default_filename , wxstrExtension //default_extension , wxT("Dynamic Library files|*.") + wxstrExtension + wxT("|all files|*.*")//wildcard , wxFD_OPEN ) ; if ( ! wxstrCPUcontrollerDynLibFilePath.empty() ) { try { //wxDynLibCPUcontroller * p_wxdynlibcpucontroller = new //wxDynLibCPUcontroller( LOGN("before creating dyn lib controller object") DEBUGN("address of model: " << mp_model ) DEBUGN("address of cpucoredata: " << & mp_model->m_cpucoredata ) //Before creating a new controller the old one should be deleted. gp_cpucontrolbase->PossiblyDeleteCPUcontrollerDynLib() ; // gp_cpucontrolbase->mp_wxdynlibcpucontroller = new wxDynLibCPUcontroller( // wxstrFilePath // , mp_wxx86infoandcontrolapp->GetCPUaccess() // , mp_wxx86infoandcontrolapp // ) ; // mp_wxx86infoandcontrolapp->CreateDynLibCPUcontroller( //TODO ANSI string may fail if Chinese localization (->use wchar_t) std::string stdstrCPUcontrollerDynLibFilePath = wxWidgets::GetStdString( wxstrCPUcontrollerDynLibFilePath ) ; wxGetApp().m_wxstrCPUcontrollerDynLibFilePath = wxstrCPUcontrollerDynLibFilePath ; if( mp_wxx86infoandcontrolapp->m_dynlibhandler.CreateDynLibCPUcontroller( stdstrCPUcontrollerDynLibFilePath ) ) { LOGN("before setting dyn lib controller as CPU controller") mp_wxx86infoandcontrolapp->SetCPUcontroller( //p_wxdynlibcpucontroller // gp_cpucontrolbase->mp_wxdynlibcpucontroller mp_wxx86infoandcontrolapp->m_p_cpucontrollerDynLib ) ; LOGN("after setting dyn lib controller as CPU controller") CreateDynamicMenus() ; LOGN("after creating per CPU core menus " ) CPUcontrollerDynLibAttached(wxstrCPUcontrollerDynLibFilePath) ; //(Re-)start the "update view" timer. m_wxtimer.Start(m_dwTimerIntervalInMilliseconds); } } catch( const CPUaccessException & ex ) { ::wxMessageBox( wxT("Error message: ") + //wxString( //Use getwxString() to enable to compile with both unicode and ANSI. wxWidgets::getwxString( ex.m_stdstrErrorMessage) // ) , wxT("DLL error") ) ; } LOGN(//"OnAttachCPUcontrollerDLL " "end" ) } } void MainFrame::OnAttachCPUcoreUsageGetterDLL (wxCommandEvent & event) { wxString wxstrExtension = wxT("") ; //Under Windows it returns ".dll" //wxstrExtension = wxDynamicLibrary::CanonicalizeName(wxstrExtension) ; wxstrExtension = wxDynamicLibrary::GetDllExt() ; //Get rid of the leading ".". wxstrExtension = wxstrExtension.Right( wxstrExtension.length() - 1 ) ; wxString wxstrFilePath = ::wxFileSelector( wxT("Select CPU core usage getter dynamic library") , wxEmptyString , wxEmptyString , wxstrExtension , wxT("Dynamic Library files|*.") + wxstrExtension + wxT("|all files|*.*")//wildcard , wxFD_OPEN ) ; if ( ! wxstrFilePath.empty() ) { try { gp_cpucontrolbase->PossiblyDeleteCPUcoreUsageGetter() ; //wxDynLibCPUcontroller * p_wxdynlibcpucontroller = new wxDynLibCPUcontroller( // gp_cpucontrolbase->mp_wxdynlibcpucoreusagegetter = new // wxDynLibCPUcoreUsageGetter( // //std::string( // wxstrFilePath // //.//fn_str() // //c_str() ) // , mp_wxx86infoandcontrolapp->GetCPUaccess() // , * mp_cpucoredata // ) ; // mp_wxx86infoandcontrolapp->CreateDynLibCPUcoreUsageGetter( std::string stdstr = wxWidgets::GetStdString( wxstrFilePath) ; if( mp_wxx86infoandcontrolapp->m_dynlibhandler.CreateDynLibCPUcoreUsageGetter( stdstr ) ) { mp_wxx86infoandcontrolapp->//SetCPUcoreUsageGetter( //p_wxdynlibcpucontroller //mp_wxdynlibcpucoreusagegetter ) ; mp_cpucoreusagegetter = //gp_cpucontrolbase->mp_wxdynlibcpucoreusagegetter ; mp_wxx86infoandcontrolapp->m_p_cpucoreusagegetterDynLib ; //CreateDynamicMenus() ; CPUcoreUsageGetterAttached(wxstrFilePath) ; //TODO necessary? (because the CPU core number got from the usage //getter may change ) RedrawEverything() ; } } catch( CPUaccessException & ex ) { wxMessageBox( wxT("Error message: ") + //wxString( //Use getwxString() to enable to compile with both unicode and ANSI. wxWidgets::getwxString( ex.m_stdstrErrorMessage) , wxT("DLL error") ) ; } } } void MainFrame::CPUcontrollerDynLibAttached(const wxString & wxstrFilePath ) { // if( ! mp_ar_voltage_and_multi ) // mp_ar_voltage_and_multi = new VoltageAndMulti[ // mp_model->m_cpucoredata.m_byNumberOfCPUCores ] ; mp_wxmenuFile->Enable( ID_DetachCPUcontrollerDynamicLibrary , //const bool enable true ) ; mp_wxmenuFile->SetLabel( ID_DetachCPUcontrollerDynamicLibrary , wxT( //"detach" //"unload" is a better word because it expresses that the Dynamic //library is removed from the memory(?) "unload" " CPU controller ") + wxstrFilePath ) ; mp_wxmenuFile->Enable( ID_SetCPUcontrollerDynLibForThisCPU, true ) ; //If both CPU controller and the CPU usage getter exist, DVFS is possible. if( mp_wxx86infoandcontrolapp->mp_cpucoreusagegetter ) m_p_wxmenuGUI->Enable( ID_EnableOrDisableOwnDVFS , //const bool enable true ) ; } void MainFrame::CPUcontrollerDeleted() { mp_i_cpucontroller = NULL; PossiblyReleaseMemForCPUcontrollerUIcontrols() ; //mp_model->m_cpucoredata.ClearCPUcontrollerSpecificAtts() ; mp_wxmenuFile->Enable( ID_DetachCPUcontrollerDynamicLibrary , //const bool enable false ) ; m_p_wxmenuGUI->Enable( ID_EnableOrDisableOwnDVFS , //const bool enable false ) ; } void MainFrame::CPUcoreUsageGetterAttached(const wxString & wxstrFilePath) { mp_wxmenuFile->Enable( ID_DetachCPUusageGetterDynLib , //const bool enable true ) ; mp_wxmenuFile->SetLabel( ID_DetachCPUusageGetterDynLib , wxT( //"detach" //"unload" is a better word because it expresses that the Dynamic //library is removed from the memory(?) "unload " " core usage getter ") + wxstrFilePath ) ; if( mp_wxx86infoandcontrolapp->GetCPUcontroller() ) m_p_wxmenuGUI->Enable( ID_EnableOrDisableOwnDVFS , //const bool enable true ) ; //TODO do the folowing in base class (CPUcontrolBase) WORD wNumberOfLogicalCPUcores = mp_wxx86infoandcontrolapp-> mp_cpucoreusagegetter->GetNumberOfLogicalCPUcores() ; if( wNumberOfLogicalCPUcores == 0 && ! mp_cpucoredata->m_byNumberOfCPUCores ) { wNumberOfLogicalCPUcores = 1 ; LOGN("setting # CPU cores to " << wNumberOfLogicalCPUcores) //TODO correct CPU core number //Set -> allocate array for OnPaint() mp_cpucoredata->SetCPUcoreNumber(wNumberOfLogicalCPUcores) ; } } void MainFrame::CPUcoreUsageGetterDeleted() { mp_wxmenuFile->Enable( ID_DetachCPUusageGetterDynLib , //const bool enable false ) ; m_p_wxmenuGUI->Enable( ID_EnableOrDisableOwnDVFS , //const bool enable false ) ; } void MainFrame::OnDetachCPUcontrollerDLL (wxCommandEvent & event) { gp_cpucontrolbase->PossiblyDeleteCPUcontrollerDynLib() ; } void MainFrame::OnDetachCPUcoreUsageGetterDLL (wxCommandEvent & event) { gp_cpucontrolbase->PossiblyDeleteCPUcoreUsageGetter() ; } void MainFrame::OnHighLoadThread( wxCommandEvent & //WXUNUSED(wxevent) wxevent ) { // WORD wEventID = wxevent.GetId() ; #ifdef COMPILE_WITH_CALC_THREAD // HighLoadThreadAttributes p_hlta = (HighLoadThreadAttributes * ) // m_stdmapwxuicontroldata.find( wEventID )->second ; CalculationThread * p_ct = (CalculationThread *) m_stdmapwxuicontroldata.find( wEventID )->second ; if( p_ct ) p_ct->Execute() ; #endif //#ifdef COMPILE_WITH_CALC_THREAD } void MainFrame::OnOwnDynFreqScaling( wxCommandEvent & //WXUNUSED(wxevent) wxevent ) { mp_wxx86infoandcontrolapp->StartDynamicVoltageAndFrequencyScaling() ; } void MainFrame::Show1VoltnFreqSettingsDialogForEveryCPUcore(wxCommandEvent & wxevent ) { WORD wEventID = wxevent.GetId() ; //wxCPUcoreID * p_wxcpucoreid = (wxCPUcoreID *) //wxevent.m_callbackUserData ; // & m_stdmapwxuicontroldata.find( wxevent.GetId() )->second ; //wxCPUcoreID & r_wxcpucoreid = (wxCPUcoreID &) //wxevent.m_callbackUserData ; // m_stdmapwxuicontroldata.find( wxevent.GetId() )->second ; //const wxObject & wxobj = //wxevent.m_callbackUserData ; // m_stdmapwxuicontroldata.find( wxevent.GetId() )->second ; //wxCPUcoreID & r_wxcpucoreid2 = (wxCPUcoreID &) wxobj ; //const wxCPUcoreID * p_wxcpucoreid2 = (const wxCPUcoreID *) & wxobj ; //std::map <WORD, wxObject> :: iterator iter = // m_stdmapwxuicontroldata.find( wxevent.GetId() ) ; //wxCPUcoreID wxcpucoreid = (wxCPUcoreID ) iter->second ; // wxCPUcoreID * p_wxcpucoreid = (wxCPUcoreID *) //wxevent.m_callbackUserData ; // //& // m_stdmapwxuicontroldata.find( wEventID )->second ; SpecificCPUcoreActionAttributes * p = (SpecificCPUcoreActionAttributes *) m_stdmapwxuicontroldata.find( wEventID )->second ; BYTE byCoreID = //p_wxcpucoreid->m_byID p->m_byCoreID ; //BYTE byCoreID = 0 ; if( m_arp_freqandvoltagesettingdlg[byCoreID] ) m_arp_freqandvoltagesettingdlg[byCoreID]->Show(true); else { //If created as local vaiable on stack the dialog would disappear //immediately. m_arp_freqandvoltagesettingdlg[byCoreID] = new FreqAndVoltageSettingDlg( this , mp_i_cpucontroller , byCoreID ); //Allocating succeeded. if( m_arp_freqandvoltagesettingdlg[byCoreID] ) m_arp_freqandvoltagesettingdlg[byCoreID]->Show(true); } } void MainFrame::OnVoltageAndFrequencySettingsDialog( wxCommandEvent & //WXUNUSED(event) wxevent ) { LOGN(/*"OnVoltageAndFrequencySettingsDialog"*/ "begin" ) //May be NULL at startup. if( mp_i_cpucontroller ) { #ifdef ONE_P_STATE_DIALOG_FOR_EVERY_CPU_CORE Show1VoltnFreqSettingsDialogForEveryCPUcore(); #else FreqAndVoltageSettingDlg * p_freqandvoltagesettingdlg = new FreqAndVoltageSettingDlg( this , mp_i_cpucontroller , 0 ); //Allocating succeeded. if( p_freqandvoltagesettingdlg ) { #ifdef USE_CRIT_SEC_FOR_FREQ_AND_VOLT_SETTINGS_DLG_CONTAINER m_crit_secVoltAndFreqDlgs.Enter(); m_stdvec_p_freqandvoltagesettingdlg.push_back( p_freqandvoltagesettingdlg) ; m_crit_secVoltAndFreqDlgs.Leave(); #endif //#ifdef USE_CRIT_SEC_FOR_FREQ_AND_VOLT_SETTINGS_DLG_CONTAINER p_freqandvoltagesettingdlg->Show(true); LOGN( "after showing the volt n freq dialog") } #endif } } void MainFrame::OnQuit(wxCommandEvent& //WXUNUSED(event) event) { Close(TRUE); } void MainFrame::DrawAllPossibleOperatingPoints( wxDC & r_wxdcDrawOn ) { //May be NULL at startup. if( mp_i_cpucontroller ) { //float fCurrentVoltageInVolt ; //WORD wXcoordinate ; //WORD wYcoordinate ; // WORD wMaxFreqInMHz = // mp_i_cpucontroller->mp_model->m_cpucoredata. // m_wMaxFreqInMHz ; // WORD wCurrentFreqInMHz = // mp_i_cpucontroller->mp_model->m_cpucoredata.m_wMaxFreqInMHz ; // BYTE byMinVoltageID = mp_cpucoredata->m_byMinVoltageID ; // BYTE byMaxVoltageID = mp_cpucoredata->m_byMaxVoltageID ; //BYTE byCurrentVoltageID ; //do //{ // for( byCurrentVoltageID = byMinVoltageID ; // byCurrentVoltageID <= byMaxVoltageID ; ++ byCurrentVoltageID ) // { // fCurrentVoltageInVolt = PState::GetVoltageInVolt( byCurrentVoltageID ) ; // wXcoordinate = // m_wXcoordOfBeginOfYaxis + // (float) wCurrentFreqInMHz / // (float) wMaxFreqInMHz * m_wDiagramWidth ; // wYcoordinate = // m_wDiagramHeight - fCurrentVoltageInVolt // / m_fMaxVoltage * m_wDiagramHeight ; // r_wxdcDrawOn.DrawLine( // //wCurrentXcoordinateInDiagram + m_wXcoordOfBeginOfYaxis, // wXcoordinate // , wYcoordinate // , //wCurrentXcoordinateInDiagram + m_wXcoordOfBeginOfYaxis // wXcoordinate // //"+ 1" because: http://docs.wxwidgets.org/stable/wx_wxdc.html#wxdcdrawline: // //"Note that the point (x2, y2) is not part of the line and is // //not drawn by this function (this is consistent with the // //behaviour of many other toolkits)." // + 1 // , //(200-fVoltage*100) // wYcoordinate // //"+ 1" because: http://docs.wxwidgets.org/stable/wx_wxdc.html#wxdcdrawline: // //"Note that the point (x2, y2) is not part of the line and is // //not drawn by this function (this is consistent with the // //behaviour of many other toolkits)." // + 1 // ) ; // } // mp_cpucontroller->GetNearestHigherPossibleFreqInMHz( // wCurrentFreqInMHz + 1 ) ; //} while( wCurrentFreqInMHz != mp_cpucoredata->m_wMaxFreqInMHz ) ; } } void MainFrame::DrawPerformanceStatesCrosses( wxDC & r_wxdc , const std::set<VoltageAndFreq> & cr_stdsetmaxvoltageforfreq , const wxColor * cp_wxcolor ) { LOGN(//"DrawPerformanceStatesCrosses " "begin") const wxPen wxpenCurrent = r_wxdc.GetPen() ; #ifdef _DEBUG const wxColor wxcolor = wxpenCurrent.GetColour() ; int nPenWidth = wxpenCurrent.GetWidth() ; #endif std::set<VoltageAndFreq>::const_iterator iter = cr_stdsetmaxvoltageforfreq.begin() ; while( iter != cr_stdsetmaxvoltageforfreq.end() ) { DrawVoltageFreqCross( r_wxdc , iter->m_fVoltageInVolt , iter->m_wFreqInMHz , cp_wxcolor ) ; ++ iter ; } #ifdef _DEBUG if( nPenWidth == 3 ) nPenWidth = 3 ; #endif //Restore the pen. r_wxdc.SetPen( wxpenCurrent ) ; } void MainFrame::DrawDiagramScale( wxDC & r_wxdc , //std::set<MaxVoltageForFreq>::iterator & iterstdsetmaxvoltageforfreq std::set<VoltageAndFreq>::iterator & r_iterstdsetvoltageandfreq ) { LOGN_DEBUG(//"DrawDiagramScale " "mp_i_cpucontroller:" << mp_i_cpucontroller) LOGN(//"DrawDiagramScale " "m_wMaximumCPUcoreFrequency:" << m_wMaximumCPUcoreFrequency) //May be NULL at startup. if( //mp_i_cpucontroller m_wMaximumCPUcoreFrequency ) { // WORD wXcoordinate = 0, wYcoordinate = 0; //float fMinVoltage ; //float fMaxMinusMinVoltage ; std::set<VoltageAndFreq> & r_stdsetvoltageandfreq = //mp_i_cpucontroller-> mp_model->m_cpucoredata.m_stdsetvoltageandfreqDefault ; //Prevents a concurrent modification e.g. by // "mp_model->m_cpucoredata.AddDefaultVoltageForFreq(...)" // in wxDynLibCPUcontroller::GetCurrentVoltageAndFrequency(...) wxCriticalSectionLocker wxcriticalsectionlockerVoltageAndFreq( mp_model->m_cpucoredata.m_wxcriticalsection) ; // std::set<WORD> setRightEndOfFreqString ; r_iterstdsetvoltageandfreq = r_stdsetvoltageandfreq.begin() ; #ifdef _DEBUG const wxPen & wxpenCurrent = r_wxdc.GetPen() ; const wxColor wxcolor = wxpenCurrent.GetColour() ; // int nPenWidth = wxpenCurrent.GetWidth() ; #endif LOGN( //"DrawDiagramScale " "m_wDiagramWidth:" << m_wDiagramWidth ) //fMinVoltage = mp_i_cpucontroller->GetMinimumVoltageInVolt() ; //fMaxMinusMinVoltage = m_fMaxVoltage - fMinVoltage ; // for( ; r_iterstdsetvoltageandfreq != // //mp_i_cpucontroller->mp_model-> // //m_setmaxvoltageforfreq.end() ; //++ iterstdvecmaxvoltageforfreq // r_stdsetvoltageandfreq.end() ; // //++ iterstdsetmaxvoltageforfreq // ++ r_iterstdsetvoltageandfreq // ) // { //// DrawFrequency( //// r_wxdc, //// //wFrequencyInMHz //// r_iterstdsetvoltageandfreq->m_wFreqInMHz , //// wxcoordWidth , //// wxcoordHeight , //// wLeftEndOfCurrFreqText , //// wxstrFreq , //// wXcoordinate , //// wYcoordinate , //// r_iterstdmapYcoord2RightEndOfFreqString , //// stdmapYcoord2RightEndOfFreqString , //// r_iterstdmap_ycoord2rightendoffreqstringToUse //// ) ; // wXcoordinate = GetXcoordinateForFrequency( r_iterstdsetvoltageandfreq-> // m_wFreqInMHz) ; //// wYcoordinate = r_iterstdmap_ycoord2rightendoffreqstringToUse->first ; // LOGN( "DrawDiagramScale //x coord:" << wXcoordinate // << "y coord:" << wYcoordinate ) // //mapRightEndOfFreqString2yCoord.insert( // // std::pair<WORD,WORD> ( wLeftEndOfCurrFreqText + wxcoordWidth, wYcoordinate ) ) ; // //Draw vertical line for current frequency mark. // //p_wxpaintdc->DrawLine(wXcoordinate, 0, wXcoordinate, wDiagramHeight) ; // //wxmemorydc.DrawLine(wXcoordinate, 0, wXcoordinate, wDiagramHeight) ; // r_wxdc.DrawLine(wXcoordinate, 0, wXcoordinate, m_wDiagramHeight // //wYcoordinate // ) ; //// DrawVoltage( //// r_wxdc , //// ( * r_iterstdsetvoltageandfreq).m_fVoltageInVolt //// ) ; // //Draw horizontal line for current voltage mark. // //p_wxpaintdc->DrawLine(wXcoordOfBeginOfYaxis, wYcoordinate, // //wxmemorydc.DrawLine(wXcoordOfBeginOfYaxis, wYcoordinate, // r_wxdc.DrawLine(m_wXcoordOfBeginOfYaxis, wYcoordinate, // m_wDiagramWidth + m_wXcoordOfBeginOfYaxis, wYcoordinate ) ; // } } //if( m_wMaximumCPUcoreFrequency ) // else //m_wMaximumCPUcoreFrequency = 0 // { // } WORD wMaximumYcoordinateForFrequency = 0; WORD wMaximumHeightForFrequencyMarks = 0; wxCoord wxcoordTextWidth, wxcoordTextHeight; r_wxdc.GetTextExtent( wxT("I") , & wxcoordTextWidth , & wxcoordTextHeight //, wxCoord *descent = NULL, wxCoord *externalLeading = NULL, wxFont *font = NULL ) ; // int nHalfTextHeightInPixels = wxcoordTextHeight / 2; if( mp_i_cpucontroller->m_fReferenceClockInMHz ) { //Do not draw: only calculate the max. (text) height of the frequency //scale. DrawFrequencyMarksAndLines(r_wxdc, wMaximumYcoordinateForFrequency); wMaximumHeightForFrequencyMarks = wMaximumYcoordinateForFrequency - m_wDiagramHeight //For the 1st line. + wxcoordTextHeight; } //->line for min./ lowest voltage/ 0V directly above frequency marks. m_wDiagramHeight += 50 - wMaximumHeightForFrequencyMarks //- //nHalfTextHeightInPixels ; DrawVoltageScale(r_wxdc); // //The frequency should start under min. voltage. // m_wDiagramHeight += nHalfTextHeightInPixels; if( mp_i_cpucontroller->m_fReferenceClockInMHz ) { //Now do really draw. DrawFrequencyMarksAndLines(r_wxdc, wMaximumYcoordinateForFrequency); } LOGN(//"DrawDiagramScale " "end") } void MainFrame::DrawLowestStableVoltageCurve( wxDC & wxdc , float fMaxVoltage ) { //May be NULL at startup. if( mp_i_cpucontroller ) { std::set<VoltageAndFreq>::const_iterator ciLower = mp_cpucoredata->m_stdsetvoltageandfreqLowestStable.begin() ; ////because of the "MaxVoltageForFreq::<" operator the set is sorted in ////DESCENDING order. ////Points BEYOND the last element now. //mp_cpucoredata->m_stdsetvoltageandfreqLowestStable.end() ; ////Now it should point to the last element. //-- ciLower ; if( ciLower != mp_cpucoredata->m_stdsetvoltageandfreqLowestStable.end() ) { std::set<VoltageAndFreq>::const_iterator ciHigher = ciLower ; ciHigher ++ ; //ciHigher -- ; if( ciHigher != mp_cpucoredata->m_stdsetvoltageandfreqLowestStable.end() ) { float fVoltage ; WORD wYcoordinate ; WORD wMaxFreqInMHz = //mp_i_cpucontroller->mp_model->m_cpucoredata.m_wMaxFreqInMHz ; m_wMaximumCPUcoreFrequency ; WORD wCurrentFreqInMHz ; for( WORD wCurrentXcoordinateInDiagram = //wXcoordOfBeginOfYaxis //0 //Begin with 1 to avoid div by zero. 1 ; wCurrentXcoordinateInDiagram < //wxcoordWidth m_wDiagramWidth ; ++ wCurrentXcoordinateInDiagram ) { wCurrentFreqInMHz = //Explicit cast to avoid (g++) warning. (WORD) ( (float) wMaxFreqInMHz / ( (float) m_wDiagramWidth / (float) wCurrentXcoordinateInDiagram ) ) ; if( ciHigher->m_wFreqInMHz < wCurrentFreqInMHz ) { std::set<VoltageAndFreq>::const_iterator ciBeyondHigher = ciHigher ; ++ ciBeyondHigher ; if( ciBeyondHigher != mp_cpucoredata-> m_stdsetvoltageandfreqLowestStable.end() ) { ++ ciLower ; ++ ciHigher ; //-- ciLower ; //-- ciHigher ; } } //If current freq is in between. if( ciHigher != mp_cpucoredata->m_stdsetvoltageandfreqLowestStable.end() && ciLower->m_wFreqInMHz <= wCurrentFreqInMHz && ciHigher->m_wFreqInMHz >= wCurrentFreqInMHz ) { //mp_i_cpucontroller->GetInterpolatedVoltageFromFreq( // wCurrentFreqInMHz // , *ciHigher // , *ciLower // , fVoltage // ) ; //mp_i_cpucontroller-> GetInterpolatedVoltageFromFreq( wCurrentFreqInMHz , fVoltage , mp_cpucoredata->m_stdsetvoltageandfreqLowestStable ) ; wYcoordinate = GetYcoordinateForVoltage(fVoltage); //p_wxpaintdc->DrawLine( wxdc.DrawLine( wCurrentXcoordinateInDiagram + m_wXcoordOfBeginOfYaxis, //wDiagramHeight - //fVoltage/ (*iterstdvecmaxvoltageforfreq).m_fVoltageInVolt //* wDiagramHeight , wYcoordinate , wCurrentXcoordinateInDiagram + m_wXcoordOfBeginOfYaxis //"+ 1" because: http://docs.wxwidgets.org/stable/wx_wxdc.html#wxdcdrawline: //"Note that the point (x2, y2) is not part of the line and is //not drawn by this function (this is consistent with the //behaviour of many other toolkits)." + 1 , wYcoordinate //"+ 1" because: http://docs.wxwidgets.org/stable/wx_wxdc.html#wxdcdrawline: //"Note that the point (x2, y2) is not part of the line and is //not drawn by this function (this is consistent with the //behaviour of many other toolkits)." + 1 ) ; } }// for } } } } void MainFrame::DrawVoltageGraph( //wxPaintDC * p_wxpaintdc wxDC & wxdc // , WORD wDiagramWidth // , WORD wDiagramHeight , float fMaxVoltage // , WORD wXcoordOfBeginOfYaxis , const std::set<VoltageAndFreq> & c_r_stdsetvoltageandfreq ) { LOGN(//"DrawOvervoltageProtectionCurve " "begin" ) //May be NULL at startup. if( mp_i_cpucontroller //and ref clock <> 0 && mp_i_cpucontroller->m_fReferenceClockInMHz ) { float fVoltage ; WORD wYcoordinate ; // std::set<float> & r_stdset_fMultipliers = mp_model->m_cpucoredata. // m_stdset_floatAvailableMultipliers ; // std::set<float>::const_reverse_iterator c_iter_stdset_fMultipliers = // r_stdset_fMultipliers.rbegin() ; // if( c_iter_stdset_fMultipliers != r_stdset_fMultipliers.rend() ) // float fMaxMulti = mp_model->m_cpucoredata.GetMaximumMultiplier() ; // if( fMaxMulti ) { WORD wMaxFreqInMHz = //mp_i_cpucontroller-> //mp_model->m_cpucoredata.m_wMaxFreqInMHz ; //max. freq = max. multi * ref clock //*c_iter_stdset_fMultipliers //fMaxMulti * mp_i_cpucontroller->m_fReferenceClockInMHz ; m_wMaximumCPUcoreFrequency ; for( WORD wCurrentXcoordinateInDiagram = //wXcoordOfBeginOfYaxis //0 //Begin with 1 to avoid div by zero. 1 ; wCurrentXcoordinateInDiagram < //wxcoordWidth m_wDiagramWidth ; ++ wCurrentXcoordinateInDiagram ) { //mp_i_cpucontroller-> GetInterpolatedVoltageFromFreq( //Explicit cast to avoid (g++) compiler warning. (WORD) ( (float) wMaxFreqInMHz / ( (float) m_wDiagramWidth / (float) wCurrentXcoordinateInDiagram ) ) , fVoltage , c_r_stdsetvoltageandfreq ) ; wYcoordinate = GetYcoordinateForVoltage(fVoltage); //p_wxpaintdc->DrawLine( //TODO draw lines from last point to current point. So gaps are avoided if //the angle is > 45 degrees wxdc.DrawLine( wCurrentXcoordinateInDiagram + m_wXcoordOfBeginOfYaxis, //wDiagramHeight - //fVoltage/ (*iterstdvecmaxvoltageforfreq).m_fVoltageInVolt //* wDiagramHeight , wYcoordinate , wCurrentXcoordinateInDiagram + m_wXcoordOfBeginOfYaxis //"+ 1" because: //http://docs.wxwidgets.org/stable/wx_wxdc.html#wxdcdrawline: //"Note that the point (x2, y2) is not part of the line and is //not drawn by this function (this is consistent with the //behaviour of many other toolkits)." + 1 , wYcoordinate //"+ 1" because: //http://docs.wxwidgets.org/stable/wx_wxdc.html#wxdcdrawline: //"Note that the point (x2, y2) is not part of the line and is //not drawn by this function (this is consistent with the //behaviour of many other toolkits)." + 1 ) ; } } } //if( mp_i_cpucontroller ) } //Purpose: the output for _all_ cores should be (left-)aligned. //So the max. width for the attribute values of the same attribute type //(MHz,...) needs to be known. void MainFrame::StoreCurrentVoltageAndFreqInArray( wxDC & r_wxdc // VoltageAndFreq * & r_ar_voltageandfreq , wxString r_ar_wxstrFreqInMHz [] , wxString r_ar_wxstrVoltageInVolt [] // , float r_ar_fTempInCelsius [] , wxString r_ar_wxstrTempInCelsius [] , I_CPUcontroller * p_cpucontroller ) { LOGN(//"StoreCurrentVoltageAndFreqInArray" "begin") if( //mp_i_cpucontroller p_cpucontroller ) { int nWidth ; PerCPUcoreAttributes * arp_percpucoreattributes = mp_model->m_cpucoredata. m_arp_percpucoreattributes ; // WORD wFreqInMHz = 0 ; wxCoord wxcoordWidth, wxcoordHeight ; wxString wxstr ; wxSize wxsize ; float fVoltageInVolt = 0.0f ; float fTempInCelsius ; float fThrottleLevel; float fMultiplier ; float fReferenceClockInMHz ; WORD wFrequencyInMHz ; // WORD wCoreID ; //mp_cpucoredata-> //respect # of cpu cores for( fastestUnsignedDataType CPUcoreID = 0 ; CPUcoreID < mp_cpucoredata->m_byNumberOfCPUCores ; ++ CPUcoreID ) { // wFreqInMHz = 0 ; // fVoltageInVolt = 0.0f ; // if( mp_i_cpucontroller->GetCurrentPstate(wFreqInMHz, fVoltageInVolt, // byCPUcoreID ) if( //mp_i_cpucontroller->GetCurrentVoltageAndFrequency( p_cpucontroller->//GetCurrentVoltageAndFrequency( //Storing in the array is needed for showing the multis in the task //bar icon. GetCurrentVoltageAndFrequencyAndStoreValues( // fVoltageInVolt // , fMultiplier // , fReferenceClockInMHz //, CPUcoreID ) ) { fVoltageInVolt = arp_percpucoreattributes[CPUcoreID].m_fVoltageInVolt; fThrottleLevel = arp_percpucoreattributes[CPUcoreID].m_fThrottleLevel; fMultiplier = arp_percpucoreattributes[CPUcoreID].m_fMultiplier; fReferenceClockInMHz = arp_percpucoreattributes[CPUcoreID]. m_fReferenceClockInMhz; wFrequencyInMHz = (WORD) ( fReferenceClockInMHz * fMultiplier ) ; // arp_percpucoreattributes[CPUcoreID].GetFreqInMHz(); if( wFrequencyInMHz > m_wMaximumCPUcoreFrequency ) m_wMaximumCPUcoreFrequency = wFrequencyInMHz ; LOGN("fMultiplier:" << fMultiplier ) mp_ar_voltage_and_multi[CPUcoreID ].m_fMultiplier = fMultiplier ; mp_ar_voltage_and_multi[CPUcoreID ].m_fVoltageInVolt = fVoltageInVolt; if(fThrottleLevel == -1.0f) r_ar_wxstrFreqInMHz[ CPUcoreID ] = wxT("?*"); else r_ar_wxstrFreqInMHz[ CPUcoreID ] = wxString::Format( wxT("%.3f*"), fThrottleLevel); { if( fMultiplier == 0.0f) r_ar_wxstrFreqInMHz[ CPUcoreID ] += wxString::Format( wxT("?*%.3fMHz=? MHz "), fThrottleLevel, fReferenceClockInMHz); else if( fReferenceClockInMHz == 0.0f ) r_ar_wxstrFreqInMHz[ CPUcoreID ] += wxString::Format( wxT("%.3f*?MHz=? MHz "), fThrottleLevel, fMultiplier); else { if(fThrottleLevel == -1.0f) r_ar_wxstrFreqInMHz[ CPUcoreID ] += wxString::Format( //Use wxT() to enable to compile with both unicode and ANSI. // wxT("%u MHz "), // wFreqInMHz ) ; wxT("%.3f*%.3fMHz=%.3f?MHz "), // wxT("%.3g*%.3gMHz=%.3gMHz "), // fThrottleLevel, fMultiplier , fReferenceClockInMHz , fMultiplier * fReferenceClockInMHz ) ; else r_ar_wxstrFreqInMHz[ CPUcoreID ] += wxString::Format( //Use wxT() to enable to compile with both unicode and ANSI. // wxT("%u MHz "), // wFreqInMHz ) ; wxT("%.3f*%.3fMHz=%.3fMHz "), // wxT("%.3g*%.3gMHz=%.3gMHz "), // fThrottleLevel, fMultiplier , fReferenceClockInMHz , fThrottleLevel * fMultiplier * fReferenceClockInMHz ) ; } } LOGN( "frequency string:\"" << wxWidgets::GetStdString( r_ar_wxstrFreqInMHz[ CPUcoreID ]) << "\"") // LOGN("r_ar_wxstrFreqInMHz[ CPUcoreID ]:" << GetStdString( // r_ar_wxstrFreqInMHz[ CPUcoreID ]) ) // wxstr = wxString::Format( wxT("%u"), wFreqInMHz ) ; // wxsize = r_wxdc.GetTextExtent(//wxstr // r_ar_wxstrFreqInMHz[ CPUcoreID ] ) ; // nWidth = wxsize.GetWidth() ; r_wxdc.GetTextExtent( r_ar_wxstrFreqInMHz[ CPUcoreID ] , & wxcoordWidth, & wxcoordHeight ) ; nWidth = wxcoordWidth ; //The max freq text widthcan not easyily be determined at startup: //if e.g. the documented max. multiplier is "10" and the reference //clock is 100MHz, then the freq can also get > 1000 MHz because the //reference clock can be a bittle higher frequented or increased via // BIOS etc. //So it's best to determine it at runtime. if( nWidth > m_wMaxFreqInMHzTextWidth ) m_wMaxFreqInMHzTextWidth = nWidth ; if( fVoltageInVolt == 0.0 ) r_ar_wxstrVoltageInVolt[ CPUcoreID ] = wxT("?V ") ; else r_ar_wxstrVoltageInVolt[ CPUcoreID ] = wxString::Format( //Use wxT() to enable to compile with both unicode and ANSI. wxT("%.4f" //"%.3g" "V "), fVoltageInVolt ) ; wxsize = r_wxdc.GetTextExtent(//wxstr r_ar_wxstrVoltageInVolt[ CPUcoreID ] ) ; nWidth = wxsize.GetWidth() ; if( nWidth > m_wMaxVoltageInVoltTextWidth ) m_wMaxVoltageInVoltTextWidth = nWidth ; // r_ar_voltageandfreq[byCPUcoreID].m_fVoltageInVolt = fVoltageInVolt ; // r_ar_voltageandfreq[byCPUcoreID].m_wFreqInMHz = wFreqInMHz ; } else { LOGN_ERROR("error getting the current CPU core voltage and frequency " "CPU controller via the CPU controller->not using their results" ) } fTempInCelsius = //mp_i_cpucontroller-> p_cpucontroller-> GetTemperatureInCelsius(CPUcoreID) ; s_arfTemperatureInDegreesCelsius[ CPUcoreID ] = fTempInCelsius ; // switch(fTempInCelsius) // { // case __FLT_MIN__ : // r_ar_wxstrTempInCelsius[ CPUcoreID ] = wxT("?°C "); // break; // case CPU_TEMP_IS_CRITICAL: // r_ar_wxstrTempInCelsius[ CPUcoreID ] = wxT("<C "); // break; // case CPU_TEMP_IS_BELOW_CRITICAL: // r_ar_wxstrTempInCelsius[ CPUcoreID ] = wxT(">C "); // break; // default: // //http://www.cplusplus.com/reference/clibrary/cstdio/printf/: // //"Use the shorter of %e or %f" // //-> if "%.3g" (max 3 digits after decimal point): // // for "60.0" it is "60" // // for "60.1755" it is "60.175" // r_ar_wxstrTempInCelsius[ CPUcoreID ] = wxString::Format( // //Use wxT() to enable to compile with both unicode and ANSI. // wxT("%.3g°C "), // fTempInCelsius ) ; // } wxGetApp().GetTemperatureString(fTempInCelsius, r_ar_wxstrTempInCelsius[ CPUcoreID ]); r_ar_wxstrTempInCelsius[ CPUcoreID ] += wxT(" "); // LOGN("r_ar_wxstrTempInCelsius[ CPUcoreID ]:" << GetStdString( // r_ar_wxstrTempInCelsius[ CPUcoreID ]) ) wxsize = r_wxdc.GetTextExtent(//wxstr r_ar_wxstrTempInCelsius[ CPUcoreID ] ) ; nWidth = wxsize.GetWidth() ; if( nWidth > m_wMaxTemperatureTextWidth ) m_wMaxTemperatureTextWidth = nWidth ; } } LOGN( "end") } void MainFrame::DrawCPUcoreIDs( wxDC & r_wxdc, wxCoord & wxcoordX, //must be call by reference wxCoord wxcoordTextHeight ) { LOGN("before drawing the CPU core numbers") static wxString wxstr; int nWidth ; wxSize wxsize ; WORD wMaxCoreNumberTextWidth = 0 ; for ( WORD wCoreID = 0 ; wCoreID < mp_cpucoredata->m_byNumberOfCPUCores ; ++ wCoreID ) { wxstr = wxString::Format( //We need a _T() macro (wide char-> L"", char->"") for EACH //line to make it compatible between char and wide char. wxT("core%u:") , wCoreID ) ; wxsize = r_wxdc.GetTextExtent( wxstr ) ; nWidth = wxsize.GetWidth() ; if( nWidth > wMaxCoreNumberTextWidth ) wMaxCoreNumberTextWidth = nWidth ; r_wxdc.DrawText( wxstr , wxcoordX //x-coord , wCoreID * //m_wTextHeight //y-coord wxcoordTextHeight ) ; } wxcoordX += wMaxCoreNumberTextWidth ; } void MainFrame::DrawCurrentCPUcoreFrequency( wxDC & r_wxdc, const wxString ar_wxstrFreqInMHz [], wxCoord & wxcoordX, wxCoord wxcoordTextHeight ) { LOGN("before drawing the CPU core frequency") for ( fastestUnsignedDataType wCoreID = 0 ; wCoreID < mp_cpucoredata->m_byNumberOfCPUCores ; ++ wCoreID ) { #ifdef _DEBUG const wxString & r_wxstr = ar_wxstrFreqInMHz[ wCoreID ] ; //Avoid g++ warning "unused variable ‘r_wxstr’" SUPPRESS_UNUSED_VARIABLE_WARNING(r_wxstr) #endif r_wxdc.DrawText( ar_wxstrFreqInMHz[ wCoreID ] , wxcoordX //x-coord , wCoreID * //m_wTextHeight //y-coord wxcoordTextHeight ) ; } wxcoordX += m_wMaxFreqInMHzTextWidth ; } void MainFrame::DrawCurrentCPUcoreTemperature( wxDC & r_wxdc, const wxString ar_wxstrCPUcoreTemperature [], wxCoord & wxcoordX, wxCoord wxcoordTextHeight ) { for ( WORD wCoreID = 0 ; wCoreID < mp_cpucoredata->m_byNumberOfCPUCores ; ++ wCoreID ) { r_wxdc.DrawText( ar_wxstrCPUcoreTemperature[ wCoreID ] , wxcoordX //x-coord , wCoreID * //m_wTextHeight //y-coord wxcoordTextHeight ) ; } wxcoordX += m_wMaxTemperatureTextWidth ; } void MainFrame::DrawCPUcoreVoltage( wxDC & r_wxdc, const wxString ar_wxstrCPUcoreVoltageInVolt [], wxCoord & wxcoordX, wxCoord wxcoordTextHeight ) { LOGN("before drawing the CPU core voltage") for ( WORD wCoreID = 0 ; wCoreID < mp_cpucoredata->m_byNumberOfCPUCores ; ++ wCoreID ) { r_wxdc.DrawText( ar_wxstrCPUcoreVoltageInVolt[ wCoreID ] , wxcoordX //x-coord , wCoreID * //m_wTextHeight //y-coord wxcoordTextHeight ) ; } wxcoordX += m_wMaxVoltageInVoltTextWidth ; } void MainFrame::DrawCPUcoreUsages( wxDC & r_wxdc, const ICPUcoreUsageGetter * p_cpucoreusagegetter, wxCoord wxcoordX, wxCoord wxcoordTextHeight ) { //mp_i_cpucontroller-> if( //mp_wxx86infoandcontrolapp->mp_cpucoreusagegetter p_cpucoreusagegetter ) { float fCPUload ; wxSize wxsize ; fCPUload = -1.0 ; static wxString wxstr; for ( WORD wCoreID = 0 ; wCoreID < mp_cpucoredata->m_byNumberOfCPUCores ; ++ wCoreID ) { fCPUload = mp_cpucoredata->m_arfCPUcoreLoadInPercent[ wCoreID ] ; wxstr = wxString::Format( //#ifdef _WINDOWS #ifdef _MSC_VER //If MicroSoft compiler. _T("%.3f percent usage") #else //when compiled with MSVC and running under WinXP the executable //crashes with this format string (surely because of the 1st "%") //http://www.cplusplus.com/reference/clibrary/cstdio/printf/: //" A % followed by another % character will write % to stdout." wxT("%.3f%% usage") #endif , fCPUload * 100.0f ) ; r_wxdc.DrawText( wxstr , wxcoordX //x-coord , wCoreID * //m_wTextHeight //y-coord wxcoordTextHeight ) ; } } } /** * Draws current CPU core data onto a wxDC: * -core ID * -frequency * -voltage * -temperature * -usage */ void MainFrame::DrawCurrentCPUcoreInfo( wxDC & r_wxdc ) { LOGN(//"DrawCurrentCPUcoreData" "begin") // wxString wxstrCPUcoreUsage ; wxString wxstrCPUcoreVoltage ; wxString wxstrTemperature ; wxString wxstrFreqInMHz ; ICPUcoreUsageGetter * p_cpucoreusagegetter ; I_CPUcontroller * p_cpucontroller ; if( GetCPUcoreInfoDirectlyOrFromService( p_cpucoreusagegetter, p_cpucontroller //, // wxstrCPUcoreUsage , true ) ) { // DEBUGN("DrawCurrentCPUcoreInfo--Number of CPU cores:" << // (WORD) mp_cpucoredata->m_byNumberOfCPUCores ) //TODO do not create arrays every time this func is called wxString ar_wxstrCPUcoreVoltage [ mp_cpucoredata->m_byNumberOfCPUCores] ; wxString ar_wxstrCPUcoreTemperature [ mp_cpucoredata->m_byNumberOfCPUCores] ; wxString ar_wxstrCPUcoreFreqInMHz [ mp_cpucoredata->m_byNumberOfCPUCores] ; const wxFont & wxfont = r_wxdc.GetFont(); // int nFontPointSize = wxfont.GetPointSize(); if( mp_model->m_userinterfaceattributes.mainframe. m_nCurrentCPUcoreInfoSizeInPoint) { //TODO make font a member var and move font creation to the c'to wxFont wxfont2(wxfont); wxfont2.SetPointSize(mp_model->m_userinterfaceattributes.mainframe. m_nCurrentCPUcoreInfoSizeInPoint); r_wxdc.SetFont(wxfont2); } //if( m_wxfontCPUcoreInfo.GetPointSize() ) if( //mp_i_cpucontroller p_cpucontroller ) { // VoltageAndFreq ar_voltageandfreq[mp_cpucoredata->m_byNumberOfCPUCores] ; // float ar_fTempInDegCelsius [ mp_cpucoredata->m_byNumberOfCPUCores] ; LOGN(//"DrawCurrentCPUcoreData " "before StoreCurrentVoltageAndFreqInArray" ) StoreCurrentVoltageAndFreqInArray( // ar_voltageandfreq, // ar_fTempInDegCelsius r_wxdc , ar_wxstrCPUcoreFreqInMHz , ar_wxstrCPUcoreVoltage , ar_wxstrCPUcoreTemperature , p_cpucontroller ) ; // float fHighestTemperature = GetHighestTemperature( // s_arfTemperatureInDegreesCelsius) ; #ifdef _WIN32 //TODO use correct icon size for (both Windows and) Linux. ShowHighestCPUcoreTemperatureInTaskBar(p_cpucontroller) ; ShowCPUcoreUsagesInTaskBar(p_cpucontroller); ShowCPUcoresMultipliersInTaskBar(p_cpucontroller); #endif LOGN(//"DrawCurrentCPUcoreData " "after StoreCurrentVoltageAndFreqInArray" ) } else { for ( WORD wCoreID = 0 ; wCoreID < mp_cpucoredata->m_byNumberOfCPUCores ; ++ wCoreID ) { ar_wxstrCPUcoreVoltage [ wCoreID ] = wxT("?"); ar_wxstrCPUcoreTemperature [ wCoreID ] = wxT("?"); ar_wxstrCPUcoreFreqInMHz [ wCoreID ] = wxT("?"); } } LOGN(//"DrawCurrentCPUcoreData " "leaving IPC 2 in-program data crit sec") mp_cpucoredata->wxconditionIPC2InProgramData.Leave() ; LOGN(//"DrawCurrentCPUcoreData " "after leaving IPC 2 in-program data crit sec") //#ifdef _DEBUG // if ( fCPUload == 0.0 ) // { //// //Breakpoint possibility //// int i = 0 ; // } //#endif //wxmemorydc wxString wxstr ; wxCoord wxcoordX ; wxcoordX = //45 ; m_uiRightmostEndOfVoltageString; wxCoord wxcoordTextWidth, wxcoordTextHeight; r_wxdc.GetTextExtent( wxT("I") , & wxcoordTextWidth , & wxcoordTextHeight //, wxCoord *descent = NULL, wxCoord *externalLeading = NULL, wxFont *font = NULL ) ; DrawCPUcoreIDs(r_wxdc, wxcoordX, wxcoordTextHeight); if( //mp_i_cpucontroller p_cpucontroller ) { DrawCPUcoreVoltage(r_wxdc, ar_wxstrCPUcoreVoltage, wxcoordX, wxcoordTextHeight); DrawCurrentCPUcoreFrequency(r_wxdc, ar_wxstrCPUcoreFreqInMHz, wxcoordX, wxcoordTextHeight); DrawCurrentCPUcoreTemperature(r_wxdc, ar_wxstrCPUcoreTemperature, wxcoordX, wxcoordTextHeight); } DrawCPUcoreUsages(r_wxdc, p_cpucoreusagegetter, wxcoordX, wxcoordTextHeight); // } //for-loop if( mp_model->m_userinterfaceattributes.mainframe.m_nCurrentCPUcoreInfoSizeInPoint) { // wxfont.SetPointSize(nFontPointSize); r_wxdc.SetFont(wxfont); } } else { LOGN(//"DrawCurrentCPUcoreData " "before leaving IPC 2 in-program data crit sec") mp_cpucoredata->wxconditionIPC2InProgramData.Leave() ; LOGN(//"DrawCurrentCPUcoreData " "After leaving IPC 2 in-program data crit sec") } LOGN(//"DrawCurrentCPUcoreData " "end") } void MainFrame::DrawCurrentVoltageSettingsCurve( wxDC & wxdc , float fMaxVoltage ) { //May be NULL at startup. if( mp_i_cpucontroller ) { float fVoltage ; WORD wYcoordinate ; WORD wMaxFreqInMHz = //mp_i_cpucontroller-> //mp_model->m_cpucoredata.m_wMaxFreqInMHz ; m_wMaximumCPUcoreFrequency ; if( //If max. freq is assigned wMaxFreqInMHz != 0 ) for( WORD wCurrentXcoordinateInDiagram = //wXcoordOfBeginOfYaxis //0 //Begin with 1 to avoid div by zero. 1 ; wCurrentXcoordinateInDiagram < //wxcoordWidth m_wDiagramWidth ; ++ wCurrentXcoordinateInDiagram ) { //mp_i_cpucontroller->GetMinFreqToPreventOvervoltage( iter ) ; if( //mp_i_cpucontroller-> GetInterpolatedVoltageFromFreq( //Explicit cast to avoid (g++) compiler warning. (WORD) ( (float) wMaxFreqInMHz / ( (float) m_wDiagramWidth / (float) wCurrentXcoordinateInDiagram ) ) , fVoltage , mp_cpucoredata->m_stdsetvoltageandfreqWanted ) ) { wYcoordinate = GetYcoordinateForVoltage(fVoltage); //p_wxpaintdc->DrawLine( wxdc.DrawLine( wCurrentXcoordinateInDiagram + m_wXcoordOfBeginOfYaxis, //wDiagramHeight - //fVoltage/ (*iterstdvecmaxvoltageforfreq).m_fVoltageInVolt //* wDiagramHeight , wYcoordinate , wCurrentXcoordinateInDiagram + m_wXcoordOfBeginOfYaxis //"+ 1" because: http://docs.wxwidgets.org/stable/wx_wxdc.html // #wxdcdrawline: //"Note that the point (x2, y2) is not part of the line and is //not drawn by this function (this is consistent with the //behaviour of many other toolkits)." + 1 , wYcoordinate //"+ 1" because: http://docs.wxwidgets.org/stable/wx_wxdc.html // #wxdcdrawline: //"Note that the point (x2, y2) is not part of the line and is //not drawn by this function (this is consistent with the //behaviour of many other toolkits)." + 1 ) ; } }//for-loop } // if( mp_i_cpucontroller ) } void MainFrame::DrawFrequency( wxDC & r_wxdc , WORD wFrequencyInMHz , // WORD wMaxFreqInMHz , wxCoord wxcoordWidth , wxCoord wxcoordHeight , WORD wLeftEndOfCurrFreqText , wxString wxstrFreq , WORD & wXcoordinate , WORD & wYcoordinate , // stdmapYcoord2RightEndOfFreqString // std::set<WORD> & setRightEndOfFreqString // std::map<WORD,WORD> & mapRightEndOfFreqString2yCoord , // std::map<WORD,WORD>::const_reverse_iterator // r_iterstdmapRightEndOfFreqString2yCoord , std::map<WORD,WORD>::iterator & r_iterstdmapYcoord2RightEndOfFreqString , std::map<WORD,WORD> & stdmapYcoord2RightEndOfFreqString , std::map<WORD,WORD>::iterator & r_iterstdmap_ycoord2rightendoffreqstringToUse , bool bCalculateMaxTextHeight ) { wXcoordinate = GetXcoordinateForFrequency(wFrequencyInMHz) ; //Draw frequency mark. //p_wxpaintdc->DrawText( //wxmemorydc.DrawText( wxstrFreq = wxString::Format( //We need a _T() macro (wide char-> L"", char->"") for EACH //line to make it compatible between char and wide char. wxT("%u") , // (*r_iterstdsetvoltageandfreq).m_wFreqInMHz wFrequencyInMHz ) ; r_wxdc.GetTextExtent( wxstrFreq , & wxcoordWidth , & wxcoordHeight //, wxCoord *descent = NULL, wxCoord *externalLeading = NULL, wxFont *font = NULL ) ; wLeftEndOfCurrFreqText = wXcoordinate //Position the line at the horizontal middle of the text. - ( wxcoordWidth / 2 ) ; //If the iterator is not set::end() then there is at least 1 strings that would //overlap with the current string if all were drawn with the same y coordinate. //iterstdsetword = setRightEndOfFreqString. // //Finds the first element whose key greater than k. // upper_bound(wLeftEndOfCurrFreqText) ; //r_iterstdmapRightEndOfFreqString2yCoord = // mapRightEndOfFreqString2yCoord.rbegin() ; //while( r_iterstdmapRightEndOfFreqString2yCoord != // mapRightEndOfFreqString2yCoord.rend() // ) //{ // //If space between the right end is of a prev string and the left end // //of this string. // if( r_iterstdmapRightEndOfFreqString2yCoord->first < // wLeftEndOfCurrFreqText ) // break ; // ++ r_iterstdmapRightEndOfFreqString2yCoord ; //} ////Avoid overlapping of frequency strings. ////if( wLeftEndOfCurrFreqText < wRightEndOfPrevFreqText ) //// wYcoordinate = m_wDiagramHeight + wxcoordHeight ; //if( r_iterstdmapRightEndOfFreqString2yCoord != // mapRightEndOfFreqString2yCoord.rend() // ) // wYcoordinate = r_iterstdmapRightEndOfFreqString2yCoord->second ; //else // if( mapRightEndOfFreqString2yCoord.empty() ) // wYcoordinate = m_wDiagramHeight ; // else // no right text end that is left from the current text to draw. // { // //wYcoordinate = m_wDiagramHeight + wxcoordHeight ; // //e.g.: 500 // // 600 // // 650 // //Draw 1 line below the previous freq text. // wYcoordinate = mapRightEndOfFreqString2yCoord.rbegin()->second + // wxcoordHeight ; // } r_iterstdmapYcoord2RightEndOfFreqString = stdmapYcoord2RightEndOfFreqString.begin() ; r_iterstdmap_ycoord2rightendoffreqstringToUse = stdmapYcoord2RightEndOfFreqString.end() ; while( r_iterstdmapYcoord2RightEndOfFreqString != stdmapYcoord2RightEndOfFreqString.end() ) { //If space between the right end is of a prev string and the left end //of this string. //The first entry is the topmost. This is also the entry if( r_iterstdmapYcoord2RightEndOfFreqString->second < wLeftEndOfCurrFreqText ) { r_iterstdmap_ycoord2rightendoffreqstringToUse = r_iterstdmapYcoord2RightEndOfFreqString ; break ; } ++ r_iterstdmapYcoord2RightEndOfFreqString ; } if( r_iterstdmap_ycoord2rightendoffreqstringToUse != stdmapYcoord2RightEndOfFreqString.end() ) { //Update the new right end of string to draw. r_iterstdmap_ycoord2rightendoffreqstringToUse->second = wLeftEndOfCurrFreqText + wxcoordWidth ; wYcoordinate = r_iterstdmap_ycoord2rightendoffreqstringToUse->first ; } else { if( stdmapYcoord2RightEndOfFreqString.empty() ) wYcoordinate = m_wDiagramHeight ; else // no right text end that is left from the current text to draw. { //wYcoordinate = m_wDiagramHeight + wxcoordHeight ; //e.g.: 500 // 600 // 650 //Draw 1 line below the previous freq text. wYcoordinate = stdmapYcoord2RightEndOfFreqString.rbegin()->first + wxcoordHeight ; } stdmapYcoord2RightEndOfFreqString.insert( std::pair<WORD,WORD> ( wYcoordinate , wLeftEndOfCurrFreqText + wxcoordWidth ) ) ; } LOGN(//"DrawDiagramScale " "drawing " << wxWidgets::GetStdString( wxstrFreq ) << " at " << wLeftEndOfCurrFreqText << "," << wYcoordinate ) if( ! bCalculateMaxTextHeight) r_wxdc.DrawText( wxstrFreq , //wXcoordOfBeginOfYaxis + //(float) wMaxFreqInMHz * wDiagramWidth wLeftEndOfCurrFreqText , //m_wDiagramHeight wYcoordinate ) ; } void MainFrame::DrawFrequencyMarksAndLines(wxDC & r_wxdc, //0=calculate max height WORD & wMaximumYcoordinateForFrequency) { LOGN_DEBUG( "begin") WORD wInitialMaximumYcoordinateForFrequency = wMaximumYcoordinateForFrequency; wMaximumYcoordinateForFrequency = 0; //Initialize to avoid g++ warnings like //"'wLeftEndOfCurrFreqText' might be used uninitialized in this function" wxCoord wxcoordWidth = 0 ; wxCoord wxcoordHeight = 0 ; wxString wxstrFreq ; fastestUnsignedDataType wLeftEndOfCurrFreqText = 0 ; WORD wXcoordinate ; //Initialize to avoid g++ warning //"'wYcoordinate' may be used uninitialized in this function" WORD wYcoordinate = 0; std::map<WORD,WORD>::iterator r_iterstdmapYcoord2RightEndOfFreqString ; std::map<WORD,WORD> stdmapYcoord2RightEndOfFreqString ; std::map<WORD,WORD>::iterator r_iterstdmap_ycoord2rightendoffreqstringToUse ; float fReferenceClockInMHz = mp_i_cpucontroller->m_fReferenceClockInMHz ; WORD wFrequencyInMHz ; wxPen penLine( * wxLIGHT_GREY, 1); // pen of width 1 const wxPen & c_r_penCurrent = r_wxdc.GetPen(); const wxFont & wxfont = r_wxdc.GetFont(); // int nFontPointSize = wxfont.GetPointSize(); if( mp_model->m_userinterfaceattributes.mainframe. m_nCPUcoreFrequencyScaleSizeInPoint) { //TODO possibly create font in c'tor and not for every call to this function wxFont wxfont2(wxfont); wxfont2.SetPointSize(mp_model->m_userinterfaceattributes.mainframe. m_nCPUcoreFrequencyScaleSizeInPoint); r_wxdc.SetFont(wxfont2); } // wxCoord wxcoordTextWidth, wxcoordTextHeight; // r_wxdc.GetTextExtent( // wxT("I") // , & wxcoordTextWidth // , & wxcoordTextHeight // //, wxCoord *descent = NULL, wxCoord *externalLeading = NULL, wxFont *font = NULL // ) ; const fastestSignedDataType numMultipliers = mp_cpucoredata-> m_stdset_floatAvailableMultipliers.size(); for( fastestUnsignedDataType multiplierArrayIndex = 0 ; multiplierArrayIndex < numMultipliers ; ++ multiplierArrayIndex ) { wFrequencyInMHz = //Avoid g++ warning "converting to `WORD' from `float'" . (WORD) ( mp_cpucoredata->m_arfAvailableMultipliers[ multiplierArrayIndex ] * fReferenceClockInMHz ) ; LOGN("should draw frequency " << wFrequencyInMHz << " for frequency scale") DrawFrequency( r_wxdc, wFrequencyInMHz , wxcoordWidth , wxcoordHeight , wLeftEndOfCurrFreqText , wxstrFreq , wXcoordinate , wYcoordinate , r_iterstdmapYcoord2RightEndOfFreqString , stdmapYcoord2RightEndOfFreqString , r_iterstdmap_ycoord2rightendoffreqstringToUse, ! wInitialMaximumYcoordinateForFrequency ) ; if( wYcoordinate > wMaximumYcoordinateForFrequency ) wMaximumYcoordinateForFrequency = wYcoordinate; if( wInitialMaximumYcoordinateForFrequency > 0) { r_wxdc.SetPen(penLine); r_wxdc.DrawLine( wXcoordinate, 0, wXcoordinate, wYcoordinate); r_wxdc.SetPen(c_r_penCurrent); } } if( mp_model->m_userinterfaceattributes.mainframe. m_nCPUcoreFrequencyScaleSizeInPoint) { // wxfont.SetPointSize(nFontPointSize); r_wxdc.SetFont(wxfont); } } void MainFrame::DrawVoltage(wxDC & r_wxdc , float fVoltageInVolt) { // WORD wYcoordinate ; if( m_bRangeBeginningFromMinVoltage ) m_wYcoordinate = //Explicit cast to avoid (g++) warning. (WORD) ( m_wDiagramHeight - ( fVoltageInVolt - m_fMinVoltage ) / m_fMaxMinusMinVoltage * m_wDiagramHeight ) ; else m_wYcoordinate = //Explicit cast to avoid (g++) warning. (WORD) ( m_wDiagramHeight - //(*iterstdsetmaxvoltageforfreq).m_fVoltageInVolt fVoltageInVolt / m_fMaxVoltage * m_wDiagramHeight + m_wMinYcoordInDiagram ) ; //Draw voltage mark. //p_wxpaintdc->DrawText( //wxmemorydc.DrawText( r_wxdc.DrawText( wxString::Format( //We need a _T() macro (wide char-> L"", char->"") for EACH //line to make it compatible between char and wide char. _T("%.3f") , fVoltageInVolt ), 5 , //wDiagramHeight - /// fMaxVoltage * wDiagramHeight m_wYcoordinate ) ; } unsigned MainFrame::GetYcoordinateForVoltage(float fVoltageInVolt//, // unsigned uiHalfTextHeightInPixels ) { WORD wYcoordinate ; if( m_bRangeBeginningFromMinVoltage ) wYcoordinate = //Explicit cast to avoid (g++) warning. (WORD) ( m_wDiagramHeight - ( fVoltageInVolt - m_fMinVoltage ) / m_fMaxMinusMinVoltage * (m_wDiagramHeight //The highest voltage should start at the half pixel height of the //voltage string. - m_wMinYcoordInDiagram) // + //uiHalfTextHeightInPixels // m_wMinYcoordInDiagram ) ; else wYcoordinate = //Explicit cast to avoid (g++) warning. (WORD) ( m_wDiagramHeight - //(*iterstdsetmaxvoltageforfreq).m_fVoltageInVolt fVoltageInVolt / m_fMaxVoltage * (m_wDiagramHeight //The highest voltage should start at the half pixel height of the //voltage string. - m_wMinYcoordInDiagram) // + m_wMinYcoordInDiagram ) ; return wYcoordinate; } wxCoord MainFrame::DrawVoltage( wxDC & r_wxdc , float fVoltageInVolt, WORD wYcoordinate, unsigned uiXcoordinateInPixels ) { static wxCoord wxcoordTextWidth, wxcoordTextHeight; wxString wxstrVoltage = wxString::Format( //We need a _T() macro (wide char-> L"", char->"") for EACH //line to make it compatible between char and wide char. wxT("%.3f") , fVoltageInVolt ); unsigned uiBeginOfVoltageString = 3 + uiXcoordinateInPixels; //Draw voltage mark. //p_wxpaintdc->DrawText( //wxmemorydc.DrawText( r_wxdc.DrawText( wxstrVoltage , uiBeginOfVoltageString , //wDiagramHeight - /// fMaxVoltage * wDiagramHeight wYcoordinate ) ; r_wxdc.GetTextExtent( wxstrVoltage , & wxcoordTextWidth , & wxcoordTextHeight //, wxCoord *descent = NULL, wxCoord *externalLeading = NULL, wxFont *font = NULL ) ; return wxcoordTextWidth + uiBeginOfVoltageString; } void MainFrame::DrawVoltageFreqCross( wxDC & r_wxdc , float fVoltageInVolt , WORD wFreqInMHz , const wxColor * cp_wxcolor ) { LOGN("begin") WORD wXcoordinate = //Explicit cast to avoid (g++) warning. (WORD) ( m_wXcoordOfBeginOfYaxis + (float) //(*iterstdvecmaxvoltageforfreq).m_wFreqInMHz / //(*iterstdvecmaxvoltageforfreq).m_wFreqInMHz / wFreqInMHz / (float) //mp_cpucoredata->m_wMaxFreqInMHz m_wMaximumCPUcoreFrequency * m_wDiagramWidth ) ; WORD wYcoordinate = GetYcoordinateForVoltage(fVoltageInVolt); //wxPen pen(*wxBLUE, 3); // pen of width 3 wxPen pen(*cp_wxcolor, 3); // pen of width 3 r_wxdc.SetPen(pen); //Draw Cursor: r_wxdc.DrawLine( wXcoordinate - 3, wYcoordinate , wXcoordinate + 4, wYcoordinate ) ; r_wxdc.DrawLine( wXcoordinate , wYcoordinate - 3, wXcoordinate , wYcoordinate + 4 ) ; } void MainFrame::DrawVoltageScale(wxDC & r_wxdc ) { LOGN_DEBUG( "begin") WORD wPreviousYcoordinateForVoltage = MAXWORD ; const wxPen & c_r_penCurrent = r_wxdc.GetPen(); //TODO possibly create pen in c'tor and not for every call to this function wxPen penLine( * wxLIGHT_GREY, 1); // pen of width 1 r_wxdc.SetPen(penLine); const wxFont & cr_wxfontBefore = r_wxdc.GetFont(); //wxWidgets runtime error when calling GetPointSize. // int nFontPointSize = cr_wxfontBefore.GetPointSize(); if( mp_model->m_userinterfaceattributes.mainframe.m_nVoltageScaleSizeInPoint) { // cr_wxfontBefore.SetPointSize(mp_model->m_userinterfaceattributes. // m_nVoltageScaleSizeInPoint); //TODO possibly create font in c'tor and not for every call to this function //wxFont copy c'tor uses reference counting. wxFont wxfont(cr_wxfontBefore//.GetNativeFontInfoDesc() ); wxfont.SetPointSize(mp_model->m_userinterfaceattributes.mainframe. m_nVoltageScaleSizeInPoint); r_wxdc.SetFont(//cr_wxfontBefore wxfont); } wxCoord wxcoordTextWidth, wxcoordTextHeight; wxCoord wxcoordVoltageStringWidth = 0; r_wxdc.GetTextExtent( wxT("I") , & wxcoordTextWidth , & wxcoordTextHeight //, wxCoord *descent = NULL, wxCoord *externalLeading = NULL, wxFont *font = NULL ) ; int nHalfTextHeightInPixels = wxcoordTextHeight/2; m_wMinYcoordInDiagram = nHalfTextHeightInPixels; unsigned uiBeginOfVoltageString = 0; m_uiRightmostEndOfVoltageString = 0; for( WORD wVoltageIndex = 0 ; wVoltageIndex < mp_cpucoredata-> m_stdset_floatAvailableVoltagesInVolt.size() ; ++ wVoltageIndex ) { LOGN("should draw voltage " << mp_cpucoredata->m_arfAvailableVoltagesInVolt[ wVoltageIndex ] << " for voltage scale") m_wYcoordinate = GetYcoordinateForVoltage( mp_cpucoredata->m_arfAvailableVoltagesInVolt[ wVoltageIndex ]//, nHalfTextHeightInPixels ); // wYoordinate = m_wYoordinate ; if( //If y coord of current voltage <= y coord of prev voltage - text h //=if the voltage string _does not overlap_ with the previous voltage //string. m_wYcoordinate <= wPreviousYcoordinateForVoltage - //m_wTextHeight wxcoordTextHeight) { //uiBeginOfVoltageString = wxcoordVoltageStringWidth; // //Next time start at x pos 0. // wxcoordVoltageStringWidth = 0; //Draw at x pos 0. wxcoordVoltageStringWidth = 0; } else //Strings would overlap-> place right of previous voltage string. { // wxcoordVoltageStringWidth = 0; // uiBeginOfVoltageString = 0; // uiBeginOfVoltageString // wxcoordVoltageStringWidth = DrawVoltage( // r_wxdc, // mp_cpucoredata->m_arfAvailableVoltagesInVolt[ wVoltageIndex ] // , m_wYcoordinate - nHalfTextHeightInPixels // , //wXcoordinateForVoltageStringBegin // wxcoordVoltageStringWidth //// 0 // ) ; } //Next time start with x pos of end of this string. // wxcoordVoltageStringWidth = uiBeginOfVoltageString = DrawVoltage( r_wxdc, mp_cpucoredata->m_arfAvailableVoltagesInVolt[ wVoltageIndex ] , m_wYcoordinate - nHalfTextHeightInPixels , //wXcoordinateForVoltageStringBegin // 0 wxcoordVoltageStringWidth // uiBeginOfVoltageString ) ; if( wxcoordVoltageStringWidth ) //Next time start with x pos 0. wxcoordVoltageStringWidth = 0; else wxcoordVoltageStringWidth = uiBeginOfVoltageString; wPreviousYcoordinateForVoltage = m_wYcoordinate ; if( uiBeginOfVoltageString //wxcoordVoltageStringWidth > m_uiRightmostEndOfVoltageString) m_uiRightmostEndOfVoltageString = uiBeginOfVoltageString; //wxcoordVoltageStringWidth; r_wxdc.DrawLine( // m_wXcoordOfBeginOfYaxis, // wxcoordVoltageStringWidth, uiBeginOfVoltageString, m_wYcoordinate, //+ nHalfTextHeightInPixels, m_wXcoordOfBeginOfYaxis + m_wDiagramWidth, m_wYcoordinate //+ nHalfTextHeightInPixels ); if( uiBeginOfVoltageString) //Start at x pos 0 the next time. uiBeginOfVoltageString = 0; } r_wxdc.SetPen(c_r_penCurrent); if( mp_model->m_userinterfaceattributes.mainframe.m_nVoltageScaleSizeInPoint) { // cr_wxfontBefore.SetPointSize(nFontPointSize); r_wxdc.SetFont(cr_wxfontBefore); } LOGN_DEBUG( "end") } float MainFrame::GetClosestMultiplier(int nXcoordionate, float & fReferenceClockInMHz) { LOGN( "begin--mp_i_cpucontroller:" << mp_i_cpucontroller) if( mp_i_cpucontroller && nXcoordionate >= m_wXcoordOfBeginOfYaxis ) { unsigned uiFreqInMHz = (unsigned) ( (float) (nXcoordionate - m_wXcoordOfBeginOfYaxis) / (float) m_wDiagramWidth * (float) m_wMaximumCPUcoreFrequency ); // float fReferenceClockInMHz = mp_i_cpucontroller->m_fReferenceClockInMHz ; fReferenceClockInMHz = mp_i_cpucontroller->m_fReferenceClockInMHz ; float fMultiplierForYcoordinate = (float) uiFreqInMHz / fReferenceClockInMHz; float fAvailableMultiplier; float fLowerMultiplier = FLT_MIN, fHigherMultiplier = FLT_MAX; for( WORD wMultiplierIndex = 0 ; wMultiplierIndex < mp_cpucoredata-> m_stdset_floatAvailableMultipliers.size() ; ++ wMultiplierIndex ) { fAvailableMultiplier = mp_cpucoredata->m_arfAvailableMultipliers[ wMultiplierIndex ] ; if( fAvailableMultiplier < fMultiplierForYcoordinate) fLowerMultiplier = fAvailableMultiplier; else { fHigherMultiplier = fAvailableMultiplier; break; } } float fClosestAvailabeMultiplier = (fMultiplierForYcoordinate - fLowerMultiplier) < fHigherMultiplier - fMultiplierForYcoordinate ? fLowerMultiplier : fHigherMultiplier; return fClosestAvailabeMultiplier; } return -1.0; } float MainFrame::GetClosestVoltageForYcoordinate( //Y coordinate starts at 0,0 at top left corner. int nYcoordinate) { if( ! mp_cpucoredata->m_stdset_floatAvailableVoltagesInVolt.empty() ) { const std::set<float> & c_r_std_set_float = mp_cpucoredata-> m_stdset_floatAvailableVoltagesInVolt; // const float fLowestVoltage = * c_r_std_set_float.begin(); // const float fHighestVoltage = * ( -- c_r_std_set_float.end() ); // const float fVoltageDiff = fHighestVoltage - fLowestVoltage; // const float fYposToDiagramHeightRatio = (float) nYcoordinate / (float) // m_wDiagramHeight; // const float fVoltageAccordingToYcoordinate = // //The maximum voltage is at the top left corner. // m_fMaxVoltage - // ( fYposToDiagramHeightRatio * m_fMaxMinusMinVoltage) //fVoltageDiff // ; // GetVoltageAccordignToYcoordinate(); // { // uiYcoordinateForAvailableVoltage = GetYcoordinateForVoltage(* c_iter); // } // c_r_std_set_float.lower_bound(); upper_bound() float fClosestLowerVoltage = FLT_MIN, fClosestHigherVoltage = //If no voltage higher than "fVoltageAccordingToYcoordinate": then //fClosestHigherVoltage - fVoltageAccordingToYcoordinate is a very big //number. //http://www.cplusplus.com/reference/clibrary/cfloat/: FLT_MAX; std::set<float>::const_iterator c_iter = c_r_std_set_float.begin(); unsigned uiYcoordinateForAvailableVoltage = 0; unsigned uiClosestLowerYcoordinate = 0; unsigned uiClosestHigherYcoordinate = 0; while( c_iter != c_r_std_set_float.end() ) { uiYcoordinateForAvailableVoltage = GetYcoordinateForVoltage(* c_iter); if( //* c_iter < fVoltageAccordingToYcoordinate //Higher coordinates=lower voltages. uiYcoordinateForAvailableVoltage > nYcoordinate ) { uiClosestHigherYcoordinate = uiYcoordinateForAvailableVoltage; fClosestLowerVoltage = * c_iter; } else { fClosestHigherVoltage = * c_iter; uiClosestLowerYcoordinate = uiYcoordinateForAvailableVoltage; break; } ++ c_iter; } if( uiClosestHigherYcoordinate) { if( uiClosestLowerYcoordinate) { const float fClosestVoltageToYcoordinate = // ( fVoltageAccordingToYcoordinate - fClosestLowerVoltage ) < // ( fClosestHigherVoltage - fVoltageAccordingToYcoordinate ) ? //Distance (in pixels) to higher voltage. ( nYcoordinate - uiClosestLowerYcoordinate ) > //Distance (in pixels) to lower voltage. ( uiClosestHigherYcoordinate - nYcoordinate ) ? fClosestLowerVoltage : fClosestHigherVoltage; return fClosestVoltageToYcoordinate; } else return fClosestLowerVoltage; } else return //Lowest voltage. * c_r_std_set_float.begin(); } return -1.0; } /** * data provider: usually the x86I&C Windows service */ void MainFrame::GetCPUcoreInfoFromDataProvider( ICPUcoreUsageGetter * & p_cpucoreusagegetter , I_CPUcontroller * & p_cpucontroller //, ) { LOGN("begin") // LOGN("DrawCurrentPstateInfo: connected to the service") //TODO possibly make IPC communication into a separate thread because it // may freeze the whole GUI. // ::wxGetApp().m_ipcclient.SendCommandAndGetResponse(get_current_CPU_data) ; // ::wxGetApp().m_ipcclient.SendCommand(get_current_CPU_data) ; LOGN(//"MainFrame::DrawCurrentPstateInfo " "m_bCPUcoreUsageConsumed" #ifdef _DEBUG ": " << m_bCPUcoreUsageConsumed #endif ) LOGN("mp_wxx86infoandcontrolapp->m_vbGotCPUcoreData:" << mp_wxx86infoandcontrolapp->m_vbGotCPUcoreData ) //Do not run it more than once concurrently. // if( //m_bCPUcoreUsageConsumed // true // // if( // // //Do not call/ wait on the IPC thread if it is running right now. // // && mp_wxx86infoandcontrolapp->m_vbGotCPUcoreData // ) // { // //set to true when the thread has finished. // mp_wxx86infoandcontrolapp->m_vbGotCPUcoreData = false ; mp_wxx86infoandcontrolapp->GetCurrentCPUcoreDataViaIPCNonBlocking() ; m_bCPUcoreUsageConsumed = false ; // } // if( ::wxGetApp().m_ipcclient.m_arbyIPCdata ) // { #ifdef COMPILE_WITH_INTER_PROCESS_COMMUNICATION p_cpucontroller = & mp_wxx86infoandcontrolapp-> m_sax2_ipc_current_cpu_data_handler ; p_cpucoreusagegetter = & mp_wxx86infoandcontrolapp-> m_sax2_ipc_current_cpu_data_handler ; #endif //#ifdef COMPILE_WITH_INTER_PROCESS_COMMUNICATION //Prevent the modification of in-program data of either the the CPU core usage // or CPU controller data // else this may happen: // for some cores data may be from the previous retrieval. // or even the CPU usage may be from previous and so not match the CPU // controller data LOGN(//"DrawCurrent CPU core info: " "entering IPC 2 in-program data crit sec") //Prevent the concurrent modification of the # of log(ical?). cores in the //IPC data 2 in-program data thread. mp_cpucoredata->wxconditionIPC2InProgramData.Enter() ; LOGN(//"DrawCurrent CPU core info: " "After entering IPC 2 in-program data crit sec") //The number of CPU cores is known if the IPC data were got at first. WORD wNumCPUcores = p_cpucoreusagegetter->GetNumberOfLogicalCPUcores() ; LOGN(//"DrawCurrentCPUcoreData " "after GetNumberOfLogicalCPUcores" ) // if( wNumCPUcores > mp_cpucoredata->m_byNumberOfCPUCores ) mp_cpucoredata->SetCPUcoreNumber( wNumCPUcores ) ; wxString wxstrTitle = mp_wxx86infoandcontrolapp->m_wxstrDataProviderURL + (p_cpucontroller->m_bDVFSfromServiceIsRunning ? wxT(" [DVFS]--") : wxT(" [no DVFS]--") ); SetTitle( //wxT("--values from service") wxstrTitle + m_wxstrTitle ) ; } bool MainFrame::GetCPUcoreInfoDirectlyOrFromService( ICPUcoreUsageGetter * & p_cpucoreusagegetter , I_CPUcontroller * & p_cpucontroller //, // wxString & wxstrCPUcoreUsage , bool bGetCPUcoreUsage ) { LOGN("begin") bool bReturn = false ; p_cpucoreusagegetter = mp_wxx86infoandcontrolapp->mp_cpucoreusagegetter ; p_cpucontroller = mp_i_cpucontroller ; // LOGN("DrawCurrentCPUcoreInfo") #ifdef COMPILE_WITH_NAMED_WINDOWS_PIPE // #ifdef _DEBUG // bool bIsGettingCPUcoreData = mp_wxx86infoandcontrolapp->m_ipcclient. // m_vbIsGettingCPUcoreData ; // SUPPRESS_UNUSED_VARIABLE_WARNING(bIsGettingCPUcoreData) // #endif if( //::wxGetApp().m_ipcclient.IsConnected() mp_wxx86infoandcontrolapp->IPC_ClientIsConnected() //This flag should be (set to) "true" as long as writing and reading data //to the service is successful. // mp_wxx86infoandcontrolapp->m_ipcclient.m_vbIsGettingCPUcoreData // false ) { GetCPUcoreInfoFromDataProvider( p_cpucoreusagegetter, p_cpucontroller //, ); } else #endif //#ifdef COMPILE_WITH_NAMED_WINDOWS_PIPE { SetTitle( m_wxstrTitle //+ wxT("--values from CPU controller") ) ; p_cpucoreusagegetter = mp_wxx86infoandcontrolapp->mp_cpucoreusagegetter ; //Prevent the modification of in-program data of either the the CPU core usage // or CPU controller data // else this may happen: // for some cores data may be from the previous retrieval. // or even the CPU usage may be from previous and so not match the CPU // controller data LOGN(//"DrawCurrent CPU core info: " "entering IPC 2 in-program data crit sec") mp_cpucoredata->wxconditionIPC2InProgramData.Enter() ; LOGN(//"DrawCurrent CPU core info: " "After entering IPC 2 in-program data crit sec") } // LOGN( p_cpucoreusagegetter << p_cpucontroller) // DEBUGN("DrawCurrentCPUcoreInfo CPU controller address:" << mp_i_cpucontroller ) //::wxGetApp().mp_cpucoreusagegetter-> if( //mp_wxx86infoandcontrolapp->mp_cpucoreusagegetter p_cpucoreusagegetter // >= 1 CPU core && mp_cpucoredata->m_byNumberOfCPUCores ) { PerCPUcoreAttributes * p_percpucoreattributes = & mp_cpucoredata-> m_arp_percpucoreattributes[ //p_atts->m_byCoreID 0 ] ; //DynFreqScalingThread * p_dynfreqscalingthread //If the drawing thread and the dyn freq scaling thread both try to get //the CPU usage they could interfere/ the delay between the usage retrieval //could be too short-> So only try to get usage here if no DVFS thread. if ( ! p_percpucoreattributes->mp_dynfreqscalingthread ) { LOGN(//"DrawCurrentCPUcoreData " "before GetPercentalUsageForAllCores" ) if( bGetCPUcoreUsage ) // mp_wxx86infoandcontrolapp->mp_cpucoreusagegetter-> p_cpucoreusagegetter-> GetPercentalUsageForAllCores( mp_cpucoredata->m_arfCPUcoreLoadInPercent) ; m_bCPUcoreUsageConsumed = true ; // DEBUGN("DrawCurrentCPUcoreInfo after GetPercentalUsageForAllCores" ) } } // else // wxstrCPUcoreUsage = wxT("usage in percent: ?") ; #ifdef _DEBUG //::wxGetApp().mp_cpucoreusagegetter->Init() ; #endif //May be NULL at startup. if( //mp_i_cpucontroller ( p_cpucontroller || //mp_wxx86infoandcontrolapp->mp_cpucoreusagegetter p_cpucoreusagegetter ) // >= 1 CPU core && mp_cpucoredata->m_byNumberOfCPUCores ) { LOGN_WARNING( "before recreating the temperature array: mustn't be from another " "thread accessed during this time") if( s_arfTemperatureInDegreesCelsius ) delete [] s_arfTemperatureInDegreesCelsius ; s_arfTemperatureInDegreesCelsius = new float[ mp_cpucoredata-> m_byNumberOfCPUCores ] ; bReturn = true ; } LOGN("return " << bReturn << " I_CPUcontroller *:" << p_cpucontroller) return bReturn ; } WORD MainFrame::GetXcoordinateForFrequency(WORD wFrequencyInMHz) { LOGN(//"GetXcoordinateForFrequency(" << wFrequencyInMHz //<< ")" ) return //Explicit cast to avoid (g++) warning. (WORD) ( m_wXcoordOfBeginOfYaxis + (float) //(*iterstdvecmaxvoltageforfreq).m_wFreqInMHz / //(*iterstdvecmaxvoltageforfreq).m_wFreqInMHz / //(*iterstdsetmaxvoltageforfreq).m_wFreqInMHz / // (*r_iterstdsetvoltageandfreq).m_wFreqInMHz / wFrequencyInMHz / (float) m_wMaximumCPUcoreFrequency * m_wDiagramWidth ) ; } //"Cross-Platform GUI Programming with wxWidgets" // (Copyright © 2006 Pearson Education, Inc.) // ISBN 0-13-147381-6 "First printing, July 2005" //"CHAPTER 5 Drawing and Printing" -> //"UNDERSTANDING DEVICE CONTEXTS" -> "Drawing on Windows with wxPaintDC" : // "[...] another thing you can do to make // drawing smoother (particularly when resizing) is to paint the background in // your paint handler, and not in an erase background handler. All the painting // will then be done in your buffered paint handler, so you don’t see the back- // ground being erased before the paint handler is called. // Add an empty erase background handler [...]" // ->Empty implementation, to prevent flicker void MainFrame::OnEraseBackground(wxEraseEvent& event) { } void MainFrame::HandleResumeForAllVoltAndFreqDlgs() { LOGN( "begin") #ifdef USE_CRIT_SEC_FOR_FREQ_AND_VOLT_SETTINGS_DLG_CONTAINER m_crit_secVoltAndFreqDlgs.Enter(); std::vector<FreqAndVoltageSettingDlg * >::const_iterator c_iter = m_stdvec_p_freqandvoltagesettingdlg.begin(); // wxPowerEvent evt; while( c_iter != m_stdvec_p_freqandvoltagesettingdlg.end() ) { ( * c_iter)->ResumendFromStandByOrHibernate(); ++ c_iter; } m_crit_secVoltAndFreqDlgs.Leave(); #endif //#ifdef USE_CRIT_SEC_FOR_FREQ_AND_VOLT_SETTINGS_DLG_CONTAINER LOGN( "end") } void MainFrame::OnPaint(wxPaintEvent & r_wx_paint_event) { LOGN("begin") // DEBUGN("OnPaint CPU controller address:" << mp_i_cpucontroller << // "usage getter addr.:" << mp_wxx86infoandcontrolapp->mp_cpucoreusagegetter // << "mp_wxbitmap:" << mp_wxbitmap ) I_CPUcontroller * p_cpucontroller ; ICPUcoreUsageGetter * p_cpucoreusagegetter ; #ifdef COMPILE_WITH_NAMED_WINDOWS_PIPE if( //::wxGetApp().m_ipcclient.IsConnected() mp_wxx86infoandcontrolapp->IPC_ClientIsConnected() ) { p_cpucontroller = & mp_wxx86infoandcontrolapp->m_sax2_ipc_current_cpu_data_handler ; p_cpucoreusagegetter = & mp_wxx86infoandcontrolapp->m_sax2_ipc_current_cpu_data_handler ; } else #endif //#ifdef COMPILE_WITH_NAMED_WINDOWS_PIPE { p_cpucontroller = mp_i_cpucontroller ; p_cpucoreusagegetter = mp_wxx86infoandcontrolapp->mp_cpucoreusagegetter ; } //May be NULL at startup. if( ( //mp_i_cpucontroller || p_cpucontroller || //mp_wxx86infoandcontrolapp->mp_cpucoreusagegetter p_cpucoreusagegetter ) && //Is NULL if CPUcontroller is NULL at startup. mp_wxbitmap ) { //Control access to m_bAllowCPUcontrollerAccess between threads. //m_wxCriticalSectionCPUctlAccess.Enter() ; //wxCriticalSectionLocker wxcriticalsectionlocker( // m_wxcriticalsectionCPUctlAccess ) ; // bool bAllowCPUcontrollerAccess = IsCPUcontrollerAccessAllowedThreadSafe() ; // if( //m_bAllowCPUcontrollerAccess // bAllowCPUcontrollerAccess ) //TODO http://docs.wxwidgets.org/2.8/wx_wxbuffereddc.html: //"GTK+ 2.0 as well as OS X provide double buffering themselves natively" //if( IsDoubleBuffered() ) wxPaintDC * p_wxpaintdc = new wxPaintDC(this); //wxMemoryDC wxmemorydc(wxbitmap) ; wxBufferedPaintDC wxmemorydc( this //, wxbitmap , *mp_wxbitmap ) ; //"Cross-Platform GUI Programming with wxWidgets" // (Copyright © 2006 Pearson Education, Inc.) // ISBN 0-13-147381-6 "First printing, July 2005" //"CHAPTER 5 Drawing and Printing" -> //"UNDERSTANDING DEVICE CONTEXTS" -> "Drawing on Windows with wxPaintDC" : // "Shifts the device origin so we don’t have to worry // about the current scroll position ourselves" PrepareDC(wxmemorydc); //http://docs.wxwidgets.org/stable/wx_wxmemorydc.html#wxmemorydc: //"Use the IsOk member to test whether the constructor was //successful in creating a usable device context." if( wxmemorydc.IsOk() ) { wxCoord wxcoordCanvasWidth ; wxCoord wxcoordCanvasHeight ; // DEBUGN("OnPaint wxmemorydc.IsOk()" ) p_wxpaintdc->GetSize( & wxcoordCanvasWidth , & wxcoordCanvasHeight ) ; //Clears the device context using the current background brush. //(else black background?) wxmemorydc.Clear(); //TODO maybe "dc.Blit(dcDiagramScaleAndCurves)" is faster than DrawBitmap. //wxmemorydc.Blit(0, 0, wxcoordCanvasWidth , wxcoordCanvasHeight, // & m_wxbufferedpaintdcStatic, 0, 0 ); //if( mp_wxbufferedpaintdcStatic ) wxmemorydc.Blit(0, 0, wxcoordCanvasWidth , wxcoordCanvasHeight, //mp_wxbufferedpaintdcStatic & m_wxmemorydcStatic , 0, 0 ); //wxmemorydc.DrawBitmap( //mp_wxbitmapDiagramScaleAndCurves // *mp_wxbitmapStatic , 0, 0) ; // DrawCurrentVoltageSettingsCurve( // wxmemorydc , // m_fMaxVoltage // ) ; #ifdef __WXGTK__ /** The following lines are needed under Linux GTK for getting the text * extent correctly? (else the text extent width is to small-> * if e.g. drawing multiple text from left to right then the text * overlaps. */ // wxFont wxfont ; /** This line caused a runtime error in wxDC::GetTextExtent() within * DrawCurrentCPUcoreInfo(...) : * "../src/gtk/dcclient.cpp(1480): assert "fontToUse->IsOk()" failed in DoGetTextExtent(): invalid font" * respectively then it did not show any CPU * information like CPU core frequency. */ // wxmemorydc.SetFont( wxfont) ; #endif //#ifdef __WXGTK__ DrawCurrentCPUcoreInfo(wxmemorydc) ; //Just for testing: //wXcoordinate = wYcoordinate = 50 ; if( mp_i_cpucontroller ) { bool bAllowCPUcontrollerAccess = IsCPUcontrollerAccessAllowedThreadSafe() ; if( //m_bAllowCPUcontrollerAccess bAllowCPUcontrollerAccess ) { if( //m_bDrawFreqAndVoltagePointForCurrCoreSettings m_vbAnotherWindowIsActive ) { DrawVoltageFreqCross( wxmemorydc , m_fVoltageInVoltOfCurrentActiveCoreSettings , m_wFreqInMHzOfCurrentActiveCoreSettings , wxBLUE ) ; } else { // float fVoltageInVolt ; // WORD wFreqInMHz ; WORD wNumCPUcores = mp_cpucoredata->GetNumberOfCPUcores() ; float fRefClock = mp_i_cpucontroller->m_fReferenceClockInMHz ; for( //Use WORD data type for guaranteed future (if > 256 logical //CPU cores) WORD wCPUcoreID = 0 ; wCPUcoreID < wNumCPUcores ; ++ wCPUcoreID ) { // mp_i_cpucontroller->GetCurrentPstate(wFreqInMHz, // fVoltageInVolt, byCoreID); // PerCPUcoreAttributes & r_percpucoreattributes = mp_cpucoredata-> // m_arp_percpucoreattributes[ byCoreID] ; DrawVoltageFreqCross( wxmemorydc //, r_percpucoreattributes.m_fVoltageInVoltCalculatedFromCPUload , //fVoltageInVolt mp_ar_voltage_and_multi[wCPUcoreID ].m_fVoltageInVolt //, r_percpucoreattributes.m_wFreqInMHzCalculatedFromCPUload , //wFreqInMHz (WORD) ( mp_ar_voltage_and_multi[wCPUcoreID ].m_fMultiplier * fRefClock ) , wxBLUE ) ; } } } //if( bAllowCPUcontrollerAccess) } //m_bDrawFreqAndVoltagePointForCurrCoreSettings = // ! m_bDrawFreqAndVoltagePointForCurrCoreSettings ; //} }//if( wxmemorydc.IsOk() ) else { DEBUGN("NOT wxmemorydc.IsOk()" ) } delete p_wxpaintdc; //m_wxCriticalSectionCPUctlAccess.Leave() ; } // if( mp_i_cpucontroller ) else { wxPaintDC wxpaintdc(this); //Clears the device context using the current background brush. //(else black background?) wxpaintdc.Clear(); wxpaintdc.DrawText( wxT("no CPU controller available->e.g. attach a DLL") , 0 , 0 ) ; } LOGN("end") } //order of submenus/ menu items of "core x" menus. enum { Settings = 0, highLoadThread , highFPUloadThread }; void MainFrame::DynVoltnFreqScalingEnabled() { ////Stop the timer (else the timer redraws additionally to the scaling thread). //m_wxtimer.Stop() ; mp_wxmenuitemOwnDVFS->/*SetText*/SetItemLabel( /** We need a _T() macro (wide char-> L"", char->"") for EACH * line to make it compatible between char and wide char. */ wxT("disable Own Dynamic Voltage and Frequency Scaling") ) ; } void MainFrame::EndDynVoltAndFreqScalingThread( PerCPUcoreAttributes * p_percpucoreattributes ) { // LOGN("ending Dynamic Voltage and Frequency scaling thread") LOGN("begin") p_percpucoreattributes->mp_dynfreqscalingthread->Stop() ; //p_percpucoreattributes->mp_dynfreqscalingthread->Delete() ; p_percpucoreattributes->mp_dynfreqscalingthread = NULL ; ////Start the timer (it should have been stopped before else the timer had redrawn ////additonally to the scaling thread). // m_wxtimer.Start() ; mp_wxmenuitemOwnDVFS->/*SetText*/SetItemLabel( //We need a _T() macro (wide char-> L"", char->"") for EACH //line to make it compatible between char and wide char. wxT("enable Own DVFS") ) ; LOGN( "end") } void MainFrame::Notify() //overrides wxTimer::Notify() { LOGN(/*"Notify"*/ "begin") m_bDrawFreqAndVoltagePointForCurrCoreSettings = ! m_bDrawFreqAndVoltagePointForCurrCoreSettings ; Refresh() ; } //Called by the destructor and by OnDetachCPUcontrollerDLL() void MainFrame::PossiblyReleaseMemForCPUcontrollerUIcontrols() { // BYTE byMenuPosFor1stCPUcore = //2 // m_byIndexOf1stCPUcontrollerRelatedMenu ; LOGN(//"PossiblyReleaseMemForCPUcontrollerUIcontrols " "begin") #ifdef ONE_P_STATE_DIALOG_FOR_EVERY_CPU_CORE //May be NULL if the CPU controller is NULL. if( m_arp_freqandvoltagesettingdlg ) { //Release dynamically allocated memory (inside OnInit() ) : for( BYTE byCPUcoreID = 0 ; byCPUcoreID < mp_cpucoredata-> m_byNumberOfCPUCores ; ++ byCPUcoreID ) { if ( m_arp_freqandvoltagesettingdlg[ byCPUcoreID ] ) { m_arp_freqandvoltagesettingdlg[ byCPUcoreID ]-> //http://docs.wxwidgets.org/2.6/wx_wxwindow.html#wxwindowdestroy: //"Use this function instead of the delete operator[...]" //"true if the window has either been successfully deleted, or it //has been added to the list of windows pending real deletion." Destroy() ; } } //Delete the array containing the pointers delete [] m_arp_freqandvoltagesettingdlg ; m_arp_freqandvoltagesettingdlg = NULL ; LOGN(//"PossiblyReleaseMemForCPUcontrollerUIcontrols " "end") } //for( std::vector<wxMenu *>::const_iterator c_i = m_vecp_wxmenuCore.begin() // ; c_i != m_vecp_wxmenuCore.end() ; ++ c_i ) //{ // //(*c_i)->Destroy() ; // mp_wxmenubar->Remove(2) ; // delete (*c_i) ; //} //if( ! m_vecp_wxmenuCore.empty() ) for( BYTE byCoreID = mp_cpucoredata->m_byNumberOfCPUCores - 1 ; byCoreID != //gets 255 if it was 0 before and then 1 is subtracted. 255 ; -- byCoreID ) { wxMenu * p_wxmenu = mp_wxmenubar->Remove( byMenuPosFor1stCPUcore + byCoreID ) ; delete p_wxmenu ; } //for( std::vector<wxMenu *>::const_iterator c_i = m_stdvecp_wxmenuCore.begin() // ; c_i != m_vecp_wxmenuCore.end() ; ++ c_i // ) //{ //} #else //ONE_P_STATE_DIALOG_FOR_EVERY_CPU_CORE m_stdvec_p_freqandvoltagesettingdlg.clear() ; //TODO runtime error in Linux debug version const int numMenus = mp_wxmenubar->GetMenuCount(); wxMenu * p_wxmenu = mp_wxmenubar->Remove( //Linux does not have a "service menu"-> 1 index less than under Windows. //Remove the "core(s)" menu. // 3 numMenus - 1 ) ; delete p_wxmenu ; #endif //ONE_P_STATE_DIALOG_FOR_EVERY_CPU_CORE m_vecp_wxmenuCore.clear() ; } void MainFrame::PossiblyAskForOSdynFreqScalingDisabling() { LOGN("begin") #ifdef COMPILE_WITH_OTHER_DVFS_ACCESS bool bOtherDVFSisEnabled = //mp_i_cpucontroller->mp_dynfreqscalingaccess->OtherDVFSisEnabled() //mp_i_cpucontroller->OtherPerfCtrlMSRwriteIsActive() mp_wxx86infoandcontrolapp->mp_dynfreqscalingaccess->OtherDVFSisEnabled(); LOGN("bOtherDVFSisEnabled: " << bOtherDVFSisEnabled) if( bOtherDVFSisEnabled ) { if (::wxMessageBox( //We need a _T() macro (wide char-> L"", char->"") for EACH //line to make it compatible between char and wide char. _T("The OS's dynamic frequency scaling must be disabled ") _T("in order that the p-state isn' changed by the OS afterwards.") _T("If the OS's dynamic frequency isn't disabled, should it be done now?") , //We need a _T() macro (wide char-> L"", char->"") for EACH //line to make it compatible between char and wide char. _T("Question") , wxYES_NO | wxICON_QUESTION ) == wxYES ) //mp_i_cpucontroller->DisableFrequencyScalingByOS(); mp_wxx86infoandcontrolapp->mp_dynfreqscalingaccess-> DisableFrequencyScalingByOS() ; } #endif //#ifdef COMPILE_WITH_OTHER_DVFS_ACCESS LOGN("end") } //#ifdef _TEST_PENTIUM_M #ifdef COMPILE_WITH_MSR_EXAMINATION void MainFrame::OnShowExamineCPUregistersDialog(wxCommandEvent& WXUNUSED(event)) { ////May be NULL at startup. //if( mp_i_cpucontroller ) //{ wxExamineCPUregistersDialog * p_wxdlg = new wxExamineCPUregistersDialog( this , //msrdata //*mp_i_cpucontroller->mp_model, //mp_i_cpucontroller //mp_wxx86infoandcontrolapp->GetCPUaccess() //, mp_wxx86infoandcontrolapp ); //p_wxdlg->ShowModal() ; p_wxdlg->Show(true) ; //} // if( mp_i_cpucontroller ) } #endif void MainFrame::OnDynamicallyCreatedUIcontrol(wxCommandEvent & wxevent) { LOGN(//"on dyn created control" "begin") int nMenuEventID = wxevent.GetId() ; #ifdef COMPILE_WITH_OTHER_DVFS_ACCESS // if( nMenuEventID == ID_MinAndMaxCPUcoreFreqInPercentOfMaxFreq ) // { // //wxMessageDialog(); // //wxMessageBox("hh") ; // //wxString strCurrentValue = wxT("50") ; // //wxString sNewValue = wxGetTextFromUser(wxT("Enter min CPU %for // CURRENT power profile (scheme)"), ////#ifndef _DEBUG // // wxT("title"), strCurrentValue); // if( ::wxGetApp().mp_dynfreqscalingaccess->OtherDVFSisEnabled() // ) ////#endif // ::wxGetApp().mp_dynfreqscalingaccess->DisableFrequencyScalingByOS() ; ////#ifndef _DEBUG // else // ::wxGetApp().mp_dynfreqscalingaccess->EnableFrequencyScalingByOS() ; ////#endif //#ifdef _DEBUG // mp_wxmenuitemOtherDVFS->SetText(//_T("") // wxString::Format( // //We need a _T() macro (wide char-> L"", char->"") for EACH // //line to make it compatible between char and wide char. // _T("%sable DVFS") , // ::wxGetApp().mp_dynfreqscalingaccess->OtherDVFSisEnabled() ? // //We need a _T() macro (wide char-> L"", char->"") for EACH // //line to make it compatible between char and wide char. // _T("dis") : // //We need a _T() macro (wide char-> L"", char->"") for EACH // //line to make it compatible between char and wide char. // _T("en") // ) // ) ; // return ; //} #endif //#ifdef COMPILE_WITH_OTHER_DVFS_ACCESS //#endif BYTE byCoreID = ( nMenuEventID - m_nLowestIDForSetVIDnFIDnDID ) / m_nNumberOfMenuIDsPerCPUcore ; //EventIDToDivisorIDandFrequencyID(nMenuEventID); if( //Array was successfully allocated. m_arp_freqandvoltagesettingdlg //&& ////menu item "set frequency and voltage" for any CPU core menu was selected. //( nMenuEventID - m_nLowestIDForSetVIDnFIDnDID ) % //m_nNumberOfMenuIDsPerCPUcore == 0 ) { //FreqAndVoltageSettingDlg freqandvoltagesettingdlg(this); //freqandvoltagesettingdlg.Show(true); //if( mp_freqandvoltagesettingdlg ) //{ // //if(mp_freqandvoltagesettingdlg ) // mp_freqandvoltagesettingdlg->Show(true); //} //else //{ // //If created as local variable on stack the dialog would disappear // //immediately. // mp_freqandvoltagesettingdlg = new FreqAndVoltageSettingDlg(this); // if(mp_freqandvoltagesettingdlg ) // mp_freqandvoltagesettingdlg->Show(true); //} BYTE bySubmenuIndexWithinPerCoreMenu = ( nMenuEventID - m_nLowestIDForSetVIDnFIDnDID ) % m_nNumberOfMenuIDsPerCPUcore ; switch( bySubmenuIndexWithinPerCoreMenu ) { case //0: Settings : if( mp_cpucoredata->m_arfAvailableMultipliers && mp_cpucoredata->m_arfAvailableVoltagesInVolt ) { if( m_arp_freqandvoltagesettingdlg[byCoreID] ) m_arp_freqandvoltagesettingdlg[byCoreID]->Show(true); } else { //TODO the dialog may be shown, but writing the p-state must be //prevented if there are no voltages and/ or multipliers because //_usually_ (voltage not for Nehalem/ i7 720 qm ) both are needed. if( ! mp_cpucoredata->m_arfAvailableMultipliers ) wxMessageBox( wxT("no multipliers available->no setting possible") ) ; if( ! mp_cpucoredata->m_arfAvailableVoltagesInVolt ) wxMessageBox( wxT("no multipliers available->no setting possible") ) ; } // else // { // //If created as local variable on stack the dialog would disappear // //immediately. // if( m_arp_freqandvoltagesettingdlg[byCoreID] ) // m_arp_freqandvoltagesettingdlg[byCoreID]->Show(true); // } break; // case setp_state2: // PossiblyAskForOSdynFreqScalingDisabling(); // Set the register where the VID and multiplier values for p-state 2 // reside as current (works at least for AMD Griffin) // mp_i_cpucontroller->SetPstate(2, // //1 = 1bin // 1 << // //=core ID: // //difference between current menu ID first menu ID for // //core settings // ( nMenuEventID - m_nLowestIDForSetVIDnFIDnDID ) // / m_nNumberOfMenuIDsPerCPUcore); // break; case highLoadThread: { //m_byNumberOfSettablePstatesPerCore + 1: // BYTE byCoreID = // //=core ID: // //difference between current menu ID first menu ID for // //core settings // ( nMenuEventID - m_nLowestIDForSetVIDnFIDnDID ) // / m_nNumberOfMenuIDsPerCPUcore ; //mp_i_cpucontroller->mp_calculationthread->StartCalculationThread( // //=core ID: // //difference between current menu ID first menu ID for // //core settings // ( nMenuEventID - m_nLowestIDForSetVIDnFIDnDID ) // / m_nNumberOfMenuIDsPerCPUcore // ); //TODO uncomment //BYTE byAction = mp_i_cpucontroller->StartOrStopCalculationThread( // byCoreID // ); //BuildHighLoadThreadMenuText( // " high load thread (e.g. for stability check)" , byAction ) ; } break; default: m_stdmapwmenuid2i_cpucontrolleraction.find(nMenuEventID)-> second->Execute() ; //if( bySubmenuIndexWithinPerCoreMenu == m_byNumberOfSettablePstatesPerCore + 1) //{ //BYTE byCoreID = // //=core ID: // //difference between current menu ID first menu ID for // //core settings // ( nMenuEventID - m_nLowestIDForSetVIDnFIDnDID ) // / m_nNumberOfMenuIDsPerCPUcore ; ////mp_i_cpucontroller->mp_calculationthread->StartCalculationThread( //// //=core ID: //// //difference between current menu ID first menu ID for //// //core settings //// ( nMenuEventID - m_nLowestIDForSetVIDnFIDnDID ) //// / m_nNumberOfMenuIDsPerCPUcore //// ); //BYTE byAction = mp_i_cpucontroller->StartOrStopCalculationThread( // byCoreID // ); //wxString wxstr = byAction == ENDED ? "Start" : "End" ; //////Invert the menu item's checked state. ////marp_wxmenuItemHighLoadThread[byCoreID]->Check( //// ! marp_wxmenuItemHighLoadThread[byCoreID]->IsChecked () ) ; //marp_wxmenuItemHighLoadThread[byCoreID]->SetText( // wxstr + // " high load thread (e.g. for stability check)" // ); //} if( bySubmenuIndexWithinPerCoreMenu //> 0 >= m_byMenuIndexOf1stPstate && bySubmenuIndexWithinPerCoreMenu < //bySubmenuIndexWithinPerCoreMenu m_byMenuIndexOf1stPstate + m_byNumberOfSettablePstatesPerCore ) { // BYTE byCoreID = // //=core ID: // //difference between current menu ID first menu ID for // //core settings // ( nMenuEventID - m_nLowestIDForSetVIDnFIDnDID ) // / m_nNumberOfMenuIDsPerCPUcore ; // BYTE byCoreBitMask = // //1 = 1bin // 1 << byCoreID ; PossiblyAskForOSdynFreqScalingDisabling(); //mp_i_cpucontroller->SetPstate( // bySubmenuIndexWithinPerCoreMenu - m_byMenuIndexOf1stPstate , // //byCoreBitMask // byCoreID // ); } break; } } } void MainFrame::OnFindLowestOperatingVoltage(wxCommandEvent& WXUNUSED(event)) { //TODO uncomment //mp_i_cpucontroller->FindLowestOperatingVoltage( // mp_i_cpucontroller->GetCurrentPstate(1),0); } #ifdef PRIVATE_RELEASE //hide the other possibilities void MainFrame::OnIncreaseVoltageForCurrentPstate(wxCommandEvent& WXUNUSED(event)) { mp_i_cpucontroller->IncreaseVoltageForCurrentPstate(); } #endif //#ifdef PRIVATE_RELEASE //hide the other possibilities void MainFrame::OnRedrawEverything(wxCommandEvent & evt ) { LOGN( "begin") RedrawEverything(); } #ifdef wxHAS_POWER_EVENTS void MainFrame::OnResume(wxPowerEvent & WXUNUSED(event) ) { LOGN( "resumed from standby/ hibernate") // HandleResumeForAllVoltAndFreqDlgs(); //May be NULL at startup. if( mp_i_cpucontroller ) { //mp_pumastatectrl->ApplyAllPStates() ; mp_i_cpucontroller->ResumeFromS3orS4() ; //After a resume (from standby) the counter value for CPU core 1 did not //change. //So re-initialize it now. if(::wxGetApp().mp_cpucoreusagegetter) ::wxGetApp().mp_cpucoreusagegetter->Init() ; //wxLogMessage(_T("System resumed from suspend.")); } // if( mp_i_cpucontroller ) LOGN( "end") } #endif // wxHAS_POWER_EVENTS //void MainFrame::OnInitDialog(wxInitDialogEvent& event ) //{ // LOGN("OnInitDialog") //// RedrawEverything() ; //// Update() ; //// Refresh() ; //} void MainFrame::OnSaveVoltageForFrequencySettings(wxCommandEvent & WXUNUSED(event) ) { std::string std_strCPUtypeRelativeDirPath; if( //wxGetApp().m_maincontroller.GetPstatesDirPath( mp_wxx86infoandcontrolapp->m_maincontroller.GetPstatesDirPath( std_strCPUtypeRelativeDirPath ) ) mp_wxx86infoandcontrolapp->SaveVoltageForFrequencySettings( std_strCPUtypeRelativeDirPath); } void MainFrame::OnSaveAsCPUcontrollerDynLibForThisCPU( wxCommandEvent & WXUNUSED(event) ) { mp_wxx86infoandcontrolapp->SaveAsCPUcontrollerDynLibForThisCPU(); } void MainFrame::OnSize( wxSizeEvent & //WXUNUSED( sizeevent//) ) { LOGN( "begin" ) RedrawEverything() ; } void MainFrame::OnSizing(wxSizeEvent & wxSizeEvent) { LOGN("begin") } #ifdef wxHAS_POWER_EVENTS void MainFrame::OnSuspending(wxPowerEvent & WXUNUSED(event)) { LOGN( "suspending power event") } void MainFrame::OnSuspended(wxPowerEvent & WXUNUSED(event)) { LOGN( "suspended power event") } void MainFrame::OnSuspendCancel(wxPowerEvent & WXUNUSED(event)) { LOGN("cancelled suspend power event") } #endif //#ifdef wxHAS_POWER_EVENTS //void GetCurrentPstateAndAddDefaultVoltage() //{ // //Do something // bool bNewVoltageAndFreqPair = false ; // float fVoltageInVolt ; // WORD wFreqInMHz ; // std::pair <std::set<VoltageAndFreq>::iterator, bool> // stdpairstdsetvoltageandfreq ; // for ( BYTE byCPUcoreID = 0 ; byCPUcoreID < // mp_cpucoredata->m_byNumberOfCPUCores ; ++ byCPUcoreID ) // { // if( mp_i_cpucontroller->GetCurrentPstate(wFreqInMHz, fVoltageInVolt, // byCPUcoreID ) ) // { // #ifdef _DEBUG // if( wFreqInMHz > 1800 ) // wFreqInMHz = wFreqInMHz ; // #endif // //stdpairstdsetvoltageandfreq = mp_model->m_cpucoredata. // // m_stdsetvoltageandfreqDefault.insert( // // VoltageAndFreq ( fVoltageInVolt , wFreqInMHz ) // // ) ; // if( mp_model->m_bCollectPstatesAsDefault ) // bNewVoltageAndFreqPair = mp_model->m_cpucoredata. // AddDefaultVoltageForFreq( // fVoltageInVolt , wFreqInMHz ) ; // ////New p-state inserted. // //if( stdpairstdsetvoltageandfreq.second ) // // bNewVoltageAndFreqPair = true ; // } // } // if( bNewVoltageAndFreqPair ) // { // std::set<VoltageAndFreq>::reverse_iterator reviter = // mp_model->m_cpucoredata.m_stdsetvoltageandfreqDefault.rbegin() ; // //Need to set the max freq. Else (all) the operating points are // // drawn at x-coord. "0". // mp_cpucoredata->m_wMaxFreqInMHz = (*reviter).m_wFreqInMHz ; // if( mp_model->m_cpucoredata.m_stdsetvoltageandfreqDefault.size() > 1 // //&& ! mp_wxmenuitemOwnDVFS->IsEnabled() // ) // mp_wxmenuitemOwnDVFS->Enable(true) ; // RedrawEverything() ; // } // else //} void MainFrame::OnTimerEvent(wxTimerEvent & event) { LOGN( "begin") // DEBUGN("OnTimerEvent CPU controller pointer:" << mp_i_cpucontroller ) // LOGN("OnTimerEvent " // "CPU controller pointer:" << mp_i_cpucontroller ) //May be NULL at startup. I_CPUcontroller * p_cpucontroller ; // ICPUcoreUsageGetter * p_cpucoreusagegetter ; #ifdef COMPILE_WITH_NAMED_WINDOWS_PIPE if( //::wxGetApp().m_ipcclient.IsConnected() mp_wxx86infoandcontrolapp->IPC_ClientIsConnected() ) { p_cpucontroller = & mp_wxx86infoandcontrolapp->m_sax2_ipc_current_cpu_data_handler ; // p_cpucoreusagegetter = & // mp_wxx86infoandcontrolapp->m_sax2_ipc_current_cpu_data_handler ; if( ! mp_wxbitmap ) RecreateDisplayBuffers() ; } else #endif //#ifdef COMPILE_WITH_NAMED_WINDOWS_PIPE { p_cpucontroller = mp_i_cpucontroller ; // p_cpucoreusagegetter = mp_wxx86infoandcontrolapp->mp_cpucoreusagegetter ; } if( //mp_i_cpucontroller p_cpucontroller ) { bool bAllowCPUcontrollerAccess = IsCPUcontrollerAccessAllowedThreadSafe() ; // DEBUGN("CPU controller access allowed:" << bAllowCPUcontrollerAccess ) if( //m_bAllowCPUcontrollerAccess bAllowCPUcontrollerAccess ) { static bool isIconized, isVisible; isIconized = IsIconized(); //TODO: returns true even if not visible (hidden bei other frames) -> // get window client update regions to decide whether to redraw. isVisible = IsVisible(); //Even if this window is not visible (iconized/ hidden) the highest //temperature should be shown in the task bar/ system tray. if( //If the window is hidden, "IsIconized()" returns "false"? isIconized || // ! // //"Returns true if this window is currently active, i.e. if the user // //is currently working with it." // IsActive() ! //IsVisible() returns true (even) if the window is iconized. isVisible ) { //If this window is iconized then OnPaint(...) isn't called and so //"StoreCurrentVoltageAndFreqInArray(...)" is _not_ being called //(indirectly), so get the current temperature here. // if( s_arfTemperatureInDegreesCelsius ) // delete [] s_arfTemperatureInDegreesCelsius ; // s_arfTemperatureInDegreesCelsius = new float[ mp_cpucoredata-> // m_byNumberOfCPUCores ] ; ICPUcoreUsageGetter * p_cpucoreusagegetter ; I_CPUcontroller * p_cpucontroller ; if( GetCPUcoreInfoDirectlyOrFromService( p_cpucoreusagegetter, p_cpucontroller //, // wxstrCPUcoreUsage , //bool bGetCPUcoreUsage // false mp_model->m_userinterfaceattributes. m_bShowCPUcoreUsagesIconInTaskBar ) ) { LOGN(//"DrawCurrentCPUcoreData " "leaving IPC 2 in-program data crit sec") mp_cpucoredata->wxconditionIPC2InProgramData.Leave() ; LOGN(//"DrawCurrentCPUcoreData " "after leaving IPC 2 in-program data crit sec") #ifdef COMPILE_WITH_SYSTEM_TRAY_ICON if( mp_wxx86infoandcontrolapp->m_p_HighestCPUcoreTemperatureTaskBarIcon ) { //respect # of cpu cores for ( WORD wCPUcoreID = 0 ; wCPUcoreID < mp_cpucoredata->m_byNumberOfCPUCores ; ++ wCPUcoreID ) { s_arfTemperatureInDegreesCelsius[ wCPUcoreID ] = p_cpucontroller-> GetTemperatureInCelsius(wCPUcoreID) ; } ShowHighestCPUcoreTemperatureInTaskBar(p_cpucontroller) ; } #endif //#ifdef COMPILE_WITH_SYSTEM_TRAY_ICON ShowCPUcoreUsagesInTaskBar(p_cpucontroller); if( mp_model->m_userinterfaceattributes.m_bShowCPUcoreUsagesIconInTaskBar ) { //respect # of cpu cores for ( WORD wCPUcoreID = 0 ; wCPUcoreID < mp_cpucoredata->m_byNumberOfCPUCores ; ++ wCPUcoreID ) p_cpucontroller->GetCurrentVoltageAndFrequencyAndStoreValues( wCPUcoreID); ShowCPUcoresMultipliersInTaskBar(p_cpucontroller); } } } else // !IsIconized() && IsVisible() { // GetCurrentPstateAndAddDefaultVoltage(); if( m_bDiagramNotDrawn //&& mp_i_cpucontroller && //mp_i_cpucontroller->m_fReferenceClockInMHz p_cpucontroller->m_fReferenceClockInMHz ) { LOGN("diagram not already drawn and reference clock <> 0 ") // bool bAllowCPUcontrollerAccess = // IsCPUcontrollerAccessAllowedThreadSafe() ; // if( //bAllowCPUcontrollerAccess && // mp_i_cpucontroller-> // m_fReferenceClockInMHz ) // { //The diagram is based on the CPU core frequency and can be drawn at //first when the reference clock is known. RedrawEverything() ; m_bDiagramNotDrawn = false ; // } } else //http://docs.wxwidgets.org/trunk/classwx_window.html // #29dc7251746154c821b17841b9877830: //"Causes this window, and all of its children recursively (except //under wxGTK1 where this is not implemented), to be repainted. //Note that repainting doesn't happen immediately but only during the //next event loop iteration, if you need to update the window //immediately you should use Update() instead." // -> EVT_PAINT -> MainFrame::OnPaint(...) is called. Refresh() ; } } //TRACE("OnTimerEvent\n") ; } // if( mp_i_cpucontroller ) else //if( mp_i_cpucontroller ) { if( mp_wxx86infoandcontrolapp->mp_cpucoreusagegetter ) //Also refresh if just a core usage getter (for showing the usage per //core) Refresh() ; } LOGN( "end") } void MainFrame::OnUpdateViewInterval(wxCommandEvent & WXUNUSED(event)) { wxString wxstrMessage = wxT("Input update view interval in milliseconds") ; wxString wxstrInput = ::wxGetTextFromUser( wxstrMessage , wxT("input"), wxT("1000") ) ; //::wxGetNumberFromUser //If the user has input text (and has NOT pressed "cancel") if( ! wxstrInput.empty() ) { unsigned long ulMs ; bool bSuccess = wxstrInput.ToULong(& ulMs) ; if ( bSuccess ) { //ReadMsrEx() returned false results if used with a time and a 10 ms interval. if( ulMs < 100 ) wxMessageBox( wxT("the number is too low. ") wxT("Getting the current CPU frequency returned wrong values with < 100 ms") ) ; else { m_dwTimerIntervalInMilliseconds = ulMs ; m_wxtimer.Stop() ; m_wxtimer.Start(ulMs) ; // m_p_wxtimer->Stop() ; // m_p_wxtimer->Start(ulMs) ; } } else { wxMessageBox( wxT("You did not enter a valid integer number") ) ; } } } void MainFrame::OnShowCPUregistersReadAndWriteDialog( wxCommandEvent & WXUNUSED(event) ) { #ifndef _DEBUG //May be NULL at startup. if( mp_i_cpucontroller ) #endif { #ifdef COMPILE_WITH_MSR_EXAMINATION CPUregisterReadAndWriteDialog * p_wxdlg = new CPUregisterReadAndWriteDialog( this , //msrdata //*mp_i_cpucontroller->mp_model, * mp_model , mp_i_cpucontroller //mp_i_cpucontroller->mp_cpuaccess //, mp_wxx86infoandcontrolapp ); //p_wxdlg->ShowModal() ; p_wxdlg->Show(true) ; #endif //#ifdef COMPILE_WITH_MSR_EXAMINATION } //if( mp_i_cpucontroller ) } void MainFrame::RecreateDisplayBuffers() { LOGN(//"RecreateDisplayBuffers " "begin") if( mp_wxbitmap ) delete mp_wxbitmap ; wxRect rect = GetClientRect(); //wxCoord wxcoordCanvasWidth ; //wxCoord wxcoordCanvasHeight ; //p_wxpaintdc->GetSize( & wxcoordCanvasWidth , & wxcoordCanvasHeight ) ; m_wDiagramHeight = rect.height //Space for drawing scale and scale values below the x-axis. - 50 ; //WORD wXcoordOfBeginOfYaxis = 50 ; m_wXcoordOfBeginOfYaxis = 50 ; //WORD wDiagramWidth = wxcoordCanvasWidth - wXcoordOfBeginOfYaxis - 30 ; m_wDiagramWidth = rect.width - m_wXcoordOfBeginOfYaxis - 30 ; mp_wxbitmap = new wxBitmap( rect.width, rect.height , //http://docs.wxwidgets.org/stable/wx_wxbitmap.html#wxbitmapctor: //"A depth of -1 indicates the depth of the current screen or visual." -1) ; //if( mp_wxbufferedpaintdcStatic ) // delete mp_wxbufferedpaintdcStatic ; //create new objet so it uses internally an bitmap with the new client size. //mp_wxbufferedpaintdcStatic = new wxBufferedPaintDC(this) ; if( mp_wxbitmapStatic ) delete mp_wxbitmapStatic ; mp_wxbitmapStatic = new wxBitmap( rect.width, rect.height , //http://docs.wxwidgets.org/stable/wx_wxbitmap.html#wxbitmapctor: //"A depth of -1 indicates the depth of the current screen or visual." -1) ; m_wxmemorydcStatic.SelectObject(*mp_wxbitmapStatic) ; //Clears the device context using the current background brush. //(else black background?) m_wxmemorydcStatic.Clear(); m_wMinYcoordInDiagram = //Let the diagram begin at the vertical middle of the topmost voltage value. m_wxmemorydcStatic.GetCharHeight() / 2 ; } //in order to draw voltage and freq aligned if more than 1 core/ to draw at //the same pos for many intervals: //core 0: 0.9 V 1100 MHz //core 1: 1.11 V 550 MHz void MainFrame::DetermineMaxVoltageAndMaxFreqDrawWidth(wxDC & r_wxdc) { wxString wxstrMaxFreq = wxString::Format( //Use wxT() to enable to compile with both unicode and ANSI. wxT("%u"), mp_cpucoredata->m_wMaxFreqInMHz ) ; //the max. freq. usually has the max draw width. m_wMaxFreqWidth = r_wxdc.GetTextExtent(wxstrMaxFreq).GetWidth() ; //Because max. voltage ID is lowest voltage for AMD Griffin but highest //voltage for Pentium M. float fVoltageForMaxVoltageID = mp_i_cpucontroller->GetVoltageInVolt( mp_cpucoredata->m_byMaxVoltageID ) ; float fVoltageForMinVoltageID = mp_i_cpucontroller->GetVoltageInVolt( mp_cpucoredata->m_byMinVoltageID ) ; float fMaxVoltage = fVoltageForMaxVoltageID > fVoltageForMinVoltageID ? fVoltageForMaxVoltageID : fVoltageForMinVoltageID ; wxString wxstrMaxVolt = wxString::Format( //Use wxT() to enable to compile with both unicode and ANSI. wxT("%f"), fMaxVoltage ) ; //the max. voltage usually has the max draw width. m_wMaxVoltageWidth = r_wxdc.GetTextExtent(wxstrMaxFreq).GetWidth() ; } void MainFrame::DetermineTextHeight(wxDC & r_wxdc) { wxCoord wxcoordWidth ; wxCoord wxcoordHeight ; wxCoord wxcoordDescent ; r_wxdc.GetTextExtent( wxT("|"), & wxcoordWidth , //wxCoord *w, & wxcoordHeight , //wxCoord *h, & wxcoordDescent //wxCoord *descent = NULL, //wxCoord *externalLeading = NULL, wxFont *font = NULL ) ; m_wTextHeight = wxcoordHeight + wxcoordDescent ; } void MainFrame::RedrawEverything() { LOGN(//"RedrawEverything " "mp_i_cpucontroller:" << mp_i_cpucontroller) DetermineTextHeight(m_wxmemorydcStatic) ; //May be NULL at startup. if( mp_i_cpucontroller ) // I_CPUcontroller * p_cpucontroller ; // if( ::wxGetApp().m_ipcclient.IsConnected() ) // { // p_cpucontroller = & // mp_wxx86infoandcontrolapp->m_sax2_ipc_current_cpu_data_handler ; // if( !mp_wxbitmap ) // RecreateDisplayBuffers() ; // } // else // { // p_cpucontroller = mp_i_cpucontroller ; // } // if( p_cpucontroller ) { DetermineMaxVoltageAndMaxFreqDrawWidth(m_wxmemorydcStatic) ; //Control access to m_bAllowCPUcontrollerAccess between threads. //m_wxCriticalSectionCPUctlAccess.Enter() ; //wxCriticalSectionLocker wxcriticalsectionlocker( // m_wxcriticalsectionCPUctlAccess ) ; bool bAllowCPUcontrollerAccess = IsCPUcontrollerAccessAllowedThreadSafe() ; LOGN(//"RedrawEverything " "bAllowCPUcontrollerAccess:" << bAllowCPUcontrollerAccess) if( //m_bAllowCPUcontrollerAccess bAllowCPUcontrollerAccess ) { // int i = 0 ; m_fMinVoltage = //mp_i_cpucontroller->GetMinimumVoltageInVolt() ; mp_model->m_cpucoredata.GetMinimumVoltage() ; float fMaxMulti = mp_model->m_cpucoredata.GetMaximumMultiplier() ; m_wMaximumCPUcoreFrequency = (WORD) ( fMaxMulti * mp_i_cpucontroller->m_fReferenceClockInMHz ) ; LOGN(//"RedrawEverything " "m_wMaximumCPUcoreFrequency=" << m_wMaximumCPUcoreFrequency << "=" << mp_i_cpucontroller->m_fReferenceClockInMHz << "*" << fMaxMulti ) RecreateDisplayBuffers(//m_wxmemorydcStatic ) ; //m_wxbufferedpaintdcStatic.SelectObject(mp_wxbitmapStatic) ; // if( mp_wxbufferedpaintdc // wxBufferedPaintDC mp_wxbufferedpaintdc ( this ) ; //Drawing the curves (calculate and draw ~ 400 points) takes some time. //So do it only when the client size changes and store the drawn curves //into a image and DrawBitmap() or do "Blit()" with the DC drawn to and //the DC that shows it in the window. //if( mp_wxbufferedpaintdcStatic ) { std::set<VoltageAndFreq> & r_setvoltageforfreq = //mp_i_cpucontroller-> mp_model->m_cpucoredata.m_stdsetvoltageandfreqDefault ; // std::set<MaxVoltageForFreq>::iterator iterstdsetmaxvoltageforfreq = // std::set<VoltageAndFreq>::reverse_iterator iterstdsetvoltageandfreq = // //m_setmaxvoltageforfreq.begin() ; // r_setvoltageforfreq.rbegin() ; if( //mp_i_cpucontroller->mp_model-> //m_setmaxvoltageforfreq.end() // iterstdsetvoltageandfreq != // r_setvoltageforfreq.rend() ! mp_cpucoredata->m_stdset_floatAvailableVoltagesInVolt.empty() ) { m_fMaxVoltage = //(*iterstdvecmaxvoltageforfreq).m_fVoltageInVolt ; ////P-state 0 usually has the highest voltage. //(*iterstdsetvoltageandfreq).m_fVoltageInVolt ; mp_cpucoredata->m_arfAvailableVoltagesInVolt[ mp_cpucoredata-> //Last element/ highest voltage. m_stdset_floatAvailableVoltagesInVolt.size() - 1 ] ; //for g++: assign value to created iterator and pass this to the arg std::set<VoltageAndFreq>::iterator iter = r_setvoltageforfreq.begin() ; DrawDiagramScale( m_wxmemorydcStatic , //iterstdsetvoltageandfreq //r_setvoltageforfreq.begin() iter ) ; } m_fMaxMinusMinVoltage = m_fMaxVoltage - m_fMinVoltage ; DrawVoltageGraph( //m_wxbufferedpaintdcStatic //*mp_wxbufferedpaintdcStatic m_wxmemorydcStatic , m_fMaxVoltage , mp_cpucoredata->m_stdsetvoltageandfreqDefault ) ; DrawCurrentVoltageSettingsCurve( //m_wxbufferedpaintdcStatic //*mp_wxbufferedpaintdcStatic m_wxmemorydcStatic , m_fMaxVoltage //, mp_cpucoredata->m_stdsetvoltageandfreqWanted ) ; DrawLowestStableVoltageCurve( //m_wxbufferedpaintdcStatic //*mp_wxbufferedpaintdcStatic m_wxmemorydcStatic , m_fMaxVoltage ) ; // DrawAllPossibleOperatingPoints( m_wxmemorydcStatic ) ; DrawPerformanceStatesCrosses( m_wxmemorydcStatic , mp_cpucoredata->m_stdsetvoltageandfreqDefault , wxBLACK ) ; DrawPerformanceStatesCrosses( m_wxmemorydcStatic , mp_cpucoredata->m_stdsetvoltageandfreqWanted //The wanted voltage may be above the default voltage because the //default voltage may be too low (e.g. for AMD Turion X2 Ultra //2400 MHz) , wxGREEN ) ; DrawPerformanceStatesCrosses( m_wxmemorydcStatic , mp_cpucoredata->m_stdsetvoltageandfreqLowestStable , wxRED ) ; } } //if( bAllowCPUcontrollerAccess) //m_wxcriticalsectionCPUctlAccess.Leave() ; } // if( mp_i_cpucontroller ) else { if( #ifdef COMPILE_WITH_NAMED_WINDOWS_PIPE //::wxGetApp().m_ipcclient.IsConnected() mp_wxx86infoandcontrolapp->IPC_ClientIsConnected() || #endif //#ifdef COMPILE_WITH_NAMED_WINDOWS_PIPE mp_wxx86infoandcontrolapp->mp_cpucoreusagegetter ) //Necessary for OnPaint() ; RecreateDisplayBuffers() ; } LOGN(//"RedrawEverything #" "end") } //Also called when CPU controller was changed. void MainFrame::SetCPUcontroller(I_CPUcontroller * p_cpucontroller ) { LOGN(//"SetCPUcontroller " "begin") mp_i_cpucontroller = p_cpucontroller ; m_wMaxFreqInMHzTextWidth = 0 ; m_wMaxVoltageInVoltTextWidth = 0 ; m_wMaxTemperatureTextWidth = 0 ; } void MainFrame::ShowCPUcoreUsagesInTaskBar( I_CPUcontroller * p_i_cpucontroller) { #ifdef COMPILE_WITH_SYSTEM_TRAY_ICON if( mp_model->m_userinterfaceattributes.m_bShowCPUcoreUsagesIconInTaskBar ) { LOGN_DEBUG("mp_taskbaricon:" << mp_wxx86infoandcontrolapp->m_p_CPUcoreUsagesTaskbarIcon ) if( mp_wxx86infoandcontrolapp->m_p_CPUcoreUsagesTaskbarIcon ) { //TODO make wxIcon (and other params) member variables of class TaskBarIcon //or wxicondrawer mp_wxx86infoandcontrolapp->m_p_CPUcoreUsagesTaskbarIcon-> m_p_wxicon_drawer->DrawColouredBarsIcon( s_wxiconCPUcoreUsages, mp_cpucoredata->m_arfCPUcoreLoadInPercent, mp_cpucoredata->m_byNumberOfCPUCores ); if( mp_wxx86infoandcontrolapp->m_p_CPUcoreUsagesTaskbarIcon->SetIcon( s_wxiconCPUcoreUsages, wxT("x86IandC--CPU cores usages") ) ) { #ifdef _DEBUG wxBitmap & wxbmp //(s_wxiconCPUcoreUsages); = * mp_wxx86infoandcontrolapp->m_p_CPUcoreUsagesTaskbarIcon-> m_p_wxicon_drawer->m_p_wxbitmapToDrawOn; wxbmp.SaveFile( // const wxString& name wxT("CPUcoreUsages.bmp") //wxBitmapType type , //wxBITMAP_TYPE_XPM did work on Windows wxBITMAP_TYPE_BMP ); #endif // if( ! mp_wxmenuFile->IsEnabled() ) //The menu item may be disabled if setting the icon failed for the //1st time (if started via the service on logon and the the task bar //was not ready). //TODO wx assert here if no menu item with ID "ID_MinimizeToSystemTray" //was added. // mp_wxmenuFile->Enable(ID_MinimizeToSystemTray, true); } else { //::wxMessageBox( wxT("Could not set task bar icon."), // getwxString(mp_wxx86infoandcontrolapp->m_stdtstrProgramName) ) ; // LOGN("Could not set task bar icon.") mp_wxmenuFile->Enable(ID_MinimizeToSystemTray, false); } } } #endif //#ifdef COMPILE_WITH_SYSTEM_TRAY_ICON } void MainFrame::ShowCPUcoresMultipliersInTaskBar( I_CPUcontroller * p_i_cpucontroller) { #ifdef COMPILE_WITH_SYSTEM_TRAY_ICON if( mp_model->m_userinterfaceattributes. m_bShowCPUcoresMultipliersIconInTaskBar ) { LOGN_DEBUG("mp_taskbaricon:" << mp_wxx86infoandcontrolapp-> m_p_CPUcoresMultipliersTaskbarIcon ) if( mp_wxx86infoandcontrolapp->m_p_CPUcoresMultipliersTaskbarIcon ) { BYTE byNumberOfCPUcores = mp_cpucoredata->m_byNumberOfCPUCores; float * CPUcoreMultipliersInPercentOfMinAndMax = new float [ byNumberOfCPUcores]; LOGN( "Number Of CPU cores:" << (WORD) byNumberOfCPUcores << "CPUcoreMultipliersInPercentOfMinAndMax:" << CPUcoreMultipliersInPercentOfMinAndMax) if( CPUcoreMultipliersInPercentOfMinAndMax ) { float fMaximumCPUcoreMultiplier = mp_cpucoredata->GetMaximumMultiplier(); float fMinimumCPUcoreMultiplier = mp_cpucoredata->GetMinimumMultiplier(); float fMaxMultiMinusMinMulti = fMaximumCPUcoreMultiplier - fMinimumCPUcoreMultiplier; // float fVoltageInVolt; float fMultiplier; // float fReferenceClockInMHz; // WORD wCPUcoreID; float currentMultiMinusMinMulti; float CPUcoreMultiplierInPercentOfMinAndMax; for( WORD wCPUcoreID = 0; wCPUcoreID < byNumberOfCPUcores; ++ wCPUcoreID) { fMultiplier = mp_cpucoredata->m_arp_percpucoreattributes[ wCPUcoreID].m_fMultiplier; //GetCurrentVoltageAndFrequency(...) should have been called right before. // if( p_i_cpucontroller->GetCurrentVoltageAndFrequency( // fVoltageInVolt // , fMultiplier // , fReferenceClockInMHz // , wCPUcoreID // ) // ) { //possible_multis: [min_multi ... max_multi]. //current_multi is_element_of possible_multis. // max_minus_min_multi = max_multi - min_multi = 1.0 = 100% // current_multi_minus_min_multi = current_multi - min_multi. currentMultiMinusMinMulti = fMultiplier - fMinimumCPUcoreMultiplier; // current_multi in percent of possible_multis = // current_multi_minus_min_multi / max_minus_min_multi CPUcoreMultiplierInPercentOfMinAndMax = // fMinimumCPUcoreMultiplier / currentMultiMinusMinMulti; currentMultiMinusMinMulti / fMaxMultiMinusMinMulti; if( currentMultiMinusMinMulti == 0.0f) // x / 0 = infinite CPUcoreMultipliersInPercentOfMinAndMax[wCPUcoreID] = 0; else CPUcoreMultipliersInPercentOfMinAndMax[wCPUcoreID] = CPUcoreMultiplierInPercentOfMinAndMax; LOGN( "multiplier for CPU core # " << (WORD) wCPUcoreID << " in percent in range of " "min and max=" << fMaxMultiMinusMinMulti << " / (" << fMultiplier << " - " << fMinimumCPUcoreMultiplier << " ) = " << currentMultiMinusMinMulti << " / " << fMaxMultiMinusMinMulti << " = " << CPUcoreMultiplierInPercentOfMinAndMax) } } mp_wxx86infoandcontrolapp->m_p_CPUcoresMultipliersTaskbarIcon-> m_p_wxicon_drawer->DrawColouredBarsIcon( s_wxiconCPUcoresMultipliers, CPUcoreMultipliersInPercentOfMinAndMax, mp_cpucoredata->m_byNumberOfCPUCores ); delete [] CPUcoreMultipliersInPercentOfMinAndMax; } if( mp_wxx86infoandcontrolapp->m_p_CPUcoresMultipliersTaskbarIcon-> SetIcon(s_wxiconCPUcoresMultipliers, wxT("x86IandC--CPU cores multipliers in % of max - min multiplier") ) ) { #ifdef _DEBUG wxBitmap & wxbmp //(s_wxiconCPUcoreUsages); = * mp_wxx86infoandcontrolapp->m_p_CPUcoresMultipliersTaskbarIcon-> m_p_wxicon_drawer->m_p_wxbitmapToDrawOn; wxbmp.SaveFile( // const wxString& name wxT("CPUcoreMultipliers.bmp") //wxBitmapType type , //wxBITMAP_TYPE_XPM did work on Windows wxBITMAP_TYPE_BMP ); #endif // if( ! mp_wxmenuFile->IsEnabled() ) //The menu item may be disabled if setting the icon failed for the //1st time (if started via the service on logon and the the task bar //was not ready). //TODO wxWidgets debug alert ("no such ID "ID_MinimizeToSystemTray"??) //here?! // mp_wxmenuFile->Enable(ID_MinimizeToSystemTray, true); } else { //::wxMessageBox( wxT("Could not set task bar icon."), // getwxString(mp_wxx86infoandcontrolapp->m_stdtstrProgramName) ) ; // LOGN("Could not set task bar icon.") mp_wxmenuFile->Enable(ID_MinimizeToSystemTray, false); } } } #endif //#ifdef COMPILE_WITH_SYSTEM_TRAY_ICON } void MainFrame::ShowHighestCPUcoreTemperatureInTaskBar( I_CPUcontroller * p_i_cpucontroller) { #ifdef COMPILE_WITH_SYSTEM_TRAY_ICON LOGN_DEBUG("mp_taskbaricon:" << mp_wxx86infoandcontrolapp->m_p_HighestCPUcoreTemperatureTaskBarIcon) if( mp_wxx86infoandcontrolapp->m_p_HighestCPUcoreTemperatureTaskBarIcon ) { static wxLongLong_t wxlonglong_tLocalTimeMillis; wxlonglong_tLocalTimeMillis = ::wxGetLocalTimeMillis(). GetValue(); static long long llDiffInMillis; llDiffInMillis = wxlonglong_tLocalTimeMillis - // mp_cpucoredata->m_llLastTimeTooHot; p_i_cpucontroller->m_llLastTimeTooHot; static std::basic_string<LOGGING_CHARACTER_TYPE> str; MAKE_STRING_FROM_STRING_STREAM( str, "diff between current time and last time too hot=" << wxlonglong_tLocalTimeMillis << "-" << p_i_cpucontroller->m_llLastTimeTooHot << "=" << llDiffInMillis ) // g_logger.Log_inline( //FULL_FUNC_NAME, // str); LOGN_DEBUG( str) //Adapted from http://www.cppreference.com/wiki/valarray/max: std::valarray<float> stdvalarray_float(s_arfTemperatureInDegreesCelsius, mp_cpucoredata->m_byNumberOfCPUCores); float fHighestTemperature = stdvalarray_float.max() ; mp_wxx86infoandcontrolapp->GetTemperatureString(fHighestTemperature, s_wxstrHighestCPUcoreTemperative); //TODO // const wxFont & wxfontBefore = r_wxdc.GetFont(); //// int nFontPointSize = wxfont.GetPointSize(); // if( mp_model->m_userinterfaceattributes.m_nCurrentCPUcoreInfoSizeInPoint) // { // wxFont wxfont2(wxfont); // wxfont2.SetPointSize(mp_model->m_userinterfaceattributes. // m_nCurrentCPUcoreInfoSizeInPoint); // mp_wxx86infoandcontrolapp->m_p_HighestCPUcoreTemperatureTaskBarIcon-> // m_wxdc.SetFont(wxfont2); // } if( llDiffInMillis < 5000 ) mp_wxx86infoandcontrolapp->m_p_HighestCPUcoreTemperatureTaskBarIcon->//m_wxicon_drawer.DrawText( DrawText( s_wxiconTemperature, s_wxstrHighestCPUcoreTemperative, wxRED//, //wxWHITE ); else // CreateTextIcon( s_wxiconTemperature, s_wxstrHighestCPUcoreTemperative ) ; mp_wxx86infoandcontrolapp->m_p_HighestCPUcoreTemperatureTaskBarIcon->//m_wxicon_drawer.DrawText( DrawText( s_wxiconTemperature, s_wxstrHighestCPUcoreTemperative, wxBLACK//, // wxWHITE ); //TODO runtime error: "../src/gtk/bitmap.cpp(1328): assert "IsOk()" failed // in wxBitmap::GetPixbuf(): invalid bitmap" if( mp_wxx86infoandcontrolapp->m_p_HighestCPUcoreTemperatureTaskBarIcon->SetIcon( s_wxiconTemperature, s_wxstrTaskBarIconToolTip ) ) { // if( ! mp_wxmenuFile->IsEnabled() ) //The menu item may be disabled if setting the icon failed for the //1st time (if started via the service on logon and the the task bar //was not ready). //TODO wxWidgets debug alert ("no such ID "ID_MinimizeToSystemTray"??) //here?! // mp_wxmenuFile->Enable(ID_MinimizeToSystemTray, true); } else { //::wxMessageBox( wxT("Could not set task bar icon."), // getwxString(mp_wxx86infoandcontrolapp->m_stdtstrProgramName) ) ; // LOGN("Could not set task bar icon.") mp_wxmenuFile->Enable(ID_MinimizeToSystemTray, false); } } LOGN("end") #endif //#ifdef COMPILE_WITH_SYSTEM_TRAY_ICON } //void MainFrame::UpdatePowerSettings( // wxPowerType powerType, // wxBatteryState batteryState // ) //{ // LOGN("UpdatePowerSettings") // wxString powerStr; // switch ( m_powerType = powerType ) // { // case wxPOWER_SOCKET: // powerStr = _T("wall"); // break; // case wxPOWER_BATTERY: // powerStr = _T("battery"); // break; // default: // wxFAIL_MSG(_T("unknown wxPowerType value")); // // fall through // case wxPOWER_UNKNOWN: // powerStr = _T("psychic"); // break; // } // // wxString batteryStr; // switch ( m_batteryState = batteryState ) // { // case wxBATTERY_NORMAL_STATE: // batteryStr = _T("charged"); // break; // case wxBATTERY_LOW_STATE: // batteryStr = _T("low"); // break; // case wxBATTERY_CRITICAL_STATE: // batteryStr = _T("critical"); // break; // case wxBATTERY_SHUTDOWN_STATE: // batteryStr = _T("empty"); // break; // default: // wxFAIL_MSG(_T("unknown wxBatteryState value")); // // fall through // case wxBATTERY_UNKNOWN_STATE: // batteryStr = _T("unknown"); // break; // } // SetStatusText( wxString::Format ( // _T("System is on %s power, battery state is %s"), // powerStr.c_str(), // batteryStr.c_str() // ) // ); //}
187,622
67,439
#include "VirtualFileSystem.hpp" #include <FileSystem/BsFileSystem.h> #include <exception/Throw.hpp> #include <log/logging.hpp> #include <vdfs/fileIndex.h> using namespace REGoth; class REGoth::InternalVirtualFileSystem { public: InternalVirtualFileSystem() = default; virtual ~InternalVirtualFileSystem() = default; VDFS::FileIndex fileIndex; bool isFinalized = false; bool isReadyToReadFiles() { if (!isFinalized) { return false; } else { return true; } } void finalizeFileIndex() { fileIndex.finalizeLoad(); isFinalized = true; } }; void VirtualFileSystem::setPathToEngineExecutable(const bs::String& argv0) { VDFS::FileIndex::initVDFS(argv0.c_str()); mInternal = bs::bs_shared_ptr_new<InternalVirtualFileSystem>(); } void VirtualFileSystem::mountDirectory(const bs::Path& path) { throwOnMissingInternalState(); if (mInternal->isFinalized) { REGOTH_THROW(InvalidStateException, "Cannot mount directories on finalized file index."); } REGOTH_LOG(Info, Uncategorized, "[VDFS] Mounting directory (recursive): {0}", path.toString()); auto onDirectory = [&](const bs::Path& p) { bs::Path relative = p.getRelative(path); REGOTH_LOG(Info, Uncategorized, "[VDFS] - {0}", relative.toString()); mInternal->fileIndex.mountFolder(p.toString().c_str()); return true; }; enum { Recursive = true, NonRecursive = false, }; bs::FileSystem::iterate(path, nullptr, onDirectory, Recursive); } bool VirtualFileSystem::loadPackage(const bs::Path& package) { throwOnMissingInternalState(); if (mInternal->isFinalized) { REGOTH_THROW(InvalidStateException, "Cannot load packages on finalized file index."); } return mInternal->fileIndex.loadVDF(package.toString().c_str()); } bs::Vector<bs::String> VirtualFileSystem::listAllFiles() { std::vector<std::string> allStl = mInternal->fileIndex.getKnownFiles(); bs::Vector<bs::String> all(allStl.size()); for (size_t i = 0; i < allStl.size(); i++) { all[i] = allStl[i].c_str(); // Internal file index will return the files in the casing they were stored in. // To be consistent, convert them all to uppercase here. bs::StringUtil::toUpperCase(all[i]); } return all; } bs::Vector<bs::String> REGoth::VirtualFileSystem::listByExtension(const bs::String& ext) { bs::Vector<bs::String> allFilesUpperCase = listAllFiles(); // Convert extension to UPPERCASE since all files returned by listAllFiles() are also // uppercase. That way, we make the extension-parameter case insensitive. bs::String extUpper = ext; bs::StringUtil::toUpperCase(extUpper); enum { RespectCase = false, LowerCase = true, }; bs::Vector<bs::String> result; for (const auto& fileName : allFilesUpperCase) { // Respect case here since our only option is converting everything to lower case // with endsWith(). Since all our input strings are known to be uppercase, we can // just compare them without changing cases. if (bs::StringUtil::endsWith(fileName, extUpper, RespectCase)) { result.push_back(fileName); } } return result; } bs::Vector<bs::UINT8> VirtualFileSystem::readFile(const bs::String& file) const { throwOnMissingInternalState(); if (!mInternal->isFinalized) { mInternal->finalizeFileIndex(); } if (!mInternal->isReadyToReadFiles()) { REGOTH_THROW(InvalidStateException, "VDFS is not ready to read files yet."); } std::vector<uint8_t> stlData; mInternal->fileIndex.getFileData(file.c_str(), stlData); // FIXME: Need some other way to get the file data so we don't have to copy the data here return bs::Vector<bs::UINT8>(stlData.begin(), stlData.end()); } bool REGoth::VirtualFileSystem::hasFile(const bs::String& file) const { if (!mInternal) { REGOTH_THROW(InvalidStateException, "VDFS internal state not available, call setPathToEngineExecutable()"); } return mInternal->fileIndex.hasFile(file.c_str()); } void REGoth::VirtualFileSystem::throwIfFileIsMissing(const bs::String& file, const bs::String& message) const { if (!hasFile(file)) { if (message.empty()) { REGOTH_THROW( InvalidStateException, bs::StringUtil::format("Expected file {0} inside VDFS, but it could not be found!", file)); } else { REGOTH_THROW(InvalidStateException, message); } } } bool REGoth::VirtualFileSystem::hasFoundGameFiles() const { throwOnMissingInternalState(); return mInternal->fileIndex.getKnownFiles().size() > 0; } const VDFS::FileIndex& VirtualFileSystem::getFileIndex() { throwOnMissingInternalState(); if (!mInternal->isFinalized) { mInternal->finalizeFileIndex(); } return mInternal->fileIndex; } void VirtualFileSystem::throwOnMissingInternalState() const { if (!mInternal) { REGOTH_THROW(InvalidStateException, "VDFS internal state not available, call setPathToEngineExecutable()"); } } VirtualFileSystem& REGoth::gVirtualFileSystem() { static VirtualFileSystem vdfs; return vdfs; }
5,187
1,715
/** * @file HybridMultiFractal.hpp * @date 12. nov. 2012 * @author Johan Klokkhammer Helsing */ #ifndef HYBRIDMULTIFRACTAL_HPP #define HYBRIDMULTIFRACTAL_HPP #include <ptg/Continuous2DSignal.hpp> #include <vector> namespace ptg { /** @brief Fractal noise generated using hybrid fractional brownian motion * * As described in this paper: * http://www8.cs.umu.se/kurser/TDBD12/HT01/papers/MusgraveTerrain00.pdf * * THIS IS THE DOCUMENTATION FOR FRACTIONAL BROWNIAN MOTION. The hybrid fractal is a slightly modified version * * The algorithm takes a Continuous2DSignal as its source to create a fractal noise * The noise is scaled to different frequencies and amplitudes, and these are added together. * * The algorithm is an easy way to create more interesting noise out of simple smoothed white noise, * such as Perlin noise or value noise. * * Complexity * ---------- * The complexity depends greatly on the choice of noise function. * If the noise function's complexity is f(n), the complexity of fbm is: * * THETA(WIDTH^2*octaves*f(n)) * * Where octaves is the number "layers" added together. This will usually be a number between 3 and 9. * * Limitations and Artifacts when used as terrain * ---------------------------------------------- * Depending on the choice of noise function, there may be a number of visible artifacts. * If your noise signal is repeating over a relatively short period, there will be visible artifacts in * the resulting terrain. The reason for this, is that when we are shading terrain, the diffuse lighting * depends on the derivative of the terrain, and therefore small changes will be visible. * * To solve this, you might either: * * Adjust gain so it's low enough that the highest octaves barely change the terrain values. * * Reduce the number of octaves, so the terrain won't repeat itself too much in the visible distance. * * Add a post-filter with diamond-square displacement to do the smallest levels of displacement, * as diamond square doesn't repeat itself, even on the smallest layers. * * Reduce specular/diffuse lighting and rely more on textures to show the tiniest bumps in the terrain. */ class HybridMultiFractal: public ptg::Continuous2DSignal { public: explicit HybridMultiFractal(unsigned int seed=0); virtual ~HybridMultiFractal(); virtual float get(float x, float y); virtual void onReSeed(unsigned int seed); /** @brief Sets the base noise function for the algorithm * suitable choices are ValueNoise or Perlin Noise */ virtual void setBaseNoise(Continuous2DSignal* signal){baseNoise=signal;} /** @brief Set the "depth" of the fractal noise. * Sets how many "layers" of noise we are going to add together. * Typical values lie between 3 and 9. */ virtual void setOctaves(unsigned int octaves){this->octaves=octaves; initExponents();} // @brief Gets number of octaves, see setOctaves virtual unsigned int getOctaves() const {return octaves;} /** @brief sets the lacunarity * this is the relation between the frequency of succesive layers in fbm-like algorithms */ virtual void setLacunarity(float lacunarity){this->lacunarity=lacunarity; initExponents();} virtual float getLacunarity() const {return lacunarity;} /** @brief sets the offset. This value is added to the noise before multiplications * * Assuming the noise value varies from -1 to 1, 0.7 will probably be a decent value */ virtual void setOffset(float offset){this->offset=offset;} virtual float getOffset() const {return offset;} /** @brief sets the H value * * This value controls how the amplitude changes from octave to octave. * A high value means the amplitude will decrease faster * 0.25 will probably be a decent value */ virtual void setH(float H){this->H = H; initExponents();} virtual float getH() const {return H;} HybridMultiFractal(const HybridMultiFractal&) = default; //copies will share the same base noise, this means that seeding one, will seed both. HybridMultiFractal & operator=(const HybridMultiFractal&) = default; private: void initExponents(); Continuous2DSignal* baseNoise; unsigned int octaves; float lacunarity; float offset; float H; std::vector<float> exponents; }; } // namespace ptg #endif // HYBRIDMULTIFRACTAL_HPP
4,289
1,300
/* * C Driver file Template by Bram Rodgers. * Original Draft Dated: 25, Feb 2018 */ /* * Macros and Includes go here: (Some common ones listed) */ #include<stdio.h> #include<stdlib.h> #include"../src/numples.h" #ifndef NULL #define NULL 0 #endif #define MIN_ALLOWED_ARGS 4 /* * Function declarations go here: */ using namespace numples; /* * Template main: */ int main(int argc, char** argv){ // Variable Declarations: // int, double, etc // Pre Built argv parsing: (argv[0] is executable title. e.g. "./a.out") char* pEnd = NULL; //Points to end of a parsed string /* * (intger) = atoi(argv[index]); * (double) = strtod(argv[index], &pEnd); * (long int) = strtol(argv[index], &pEnd, base_val) */ srand(time(NULL)); lapack_int m, n, numSV;//matrix dimensions and loop iterators. if(argc < MIN_ALLOWED_ARGS){ printf("\nA small script to test the various matrix products."); printf("\n==================================================="); printf("\n%s [m] [n] [numSV]",argv[0]); printf("\nDoes a test of SVD, obtaining only numSV singular vectors,\n" "and Schur Decomposition.\n"); exit(1); } m = (lapack_int) strtol(argv[1], &pEnd, 0); n = (lapack_int) strtol(argv[2], &pEnd, 0); numSV = (lapack_int) strtol(argv[3], &pEnd, 0); Matrix A = Matrix(m , n, 'U');//generate uniform random matrix. Matrix R, Z;//Schur decomposition matrices Matrix U, sig, Vt;//SVD matrices Matrix Resid; double residNorm, traceVal; A.svd(U, sig, Vt); Resid = A - U * sig.diag() * Vt; residNorm = Resid.norm2(); printf("\nSVD Residual: %le\n", residNorm); Z = A.getLeftSV(numSV); traceVal = (Z.transp() * U).trace(); residNorm = numSV - ABS(traceVal); printf("\n%le\n",residNorm); if(residNorm <= (double)numSV){ printf("\nGet Left Singular Vectors passed within eps_mach: 1\n"); }else{ printf("\nGet Left Singular Vectors failed within eps_mach: 0\n"); } A.schur(Z,R); Resid = A*Z - Z*R; residNorm = Resid.norm2(); printf("\nSchur Residual: %le\n", residNorm); printf("\n%s\n\n", argv[0]); return 0; }
2,054
841
#include "leviathan_config.hpp" #include <exception> #include <algorithm> #include <glog/logging.h> #include <yaml-cpp/yaml.h> // TODO: Cleaner normalization LineFunction slope_function(const Point &a, const Point &b) { const auto ys = b.y - a.y; const auto xs = b.x - a.x; if (xs == 0) { throw std::runtime_error("Infinite slope detected"); } const auto slope = ys / xs; const auto bFac = b.y - (slope * b.x); return [slope, bFac](int32_t x) { const auto newY = (slope * x) + bFac; // Normalize to a multiple of 5 const auto evenDiff = newY % 5; return newY - evenDiff; // hit it on the nose == 0 }; } std::map<int32_t, LineFunction> configure_profile( const YAML::Node &fan_profile) { CHECK(fan_profile.IsSequence()) << "Expecting a sequence of pairs"; const auto point_compare = [](const Point &p, const Point &u) { return p.x > u.x; }; std::vector<Point> dataPoints { Point(0, 30) }; for (const auto &i : fan_profile.as<std::vector<std::vector<uint32_t>>>()) { CHECK(i.size() == 2) << "Expecting array of pairs for fan/pump profile"; CHECK(i.back() % 5 == 0) << "Fan/pump profile values must be divisible by 5"; dataPoints.emplace_back(i.front(), i.back()); } dataPoints.emplace_back(100, 100); std::sort(dataPoints.begin(), dataPoints.end(), point_compare); std::map<int32_t, LineFunction> temp_to_slope; for (auto i = 0; i < dataPoints.size() - 1; ++i) { const Point &cur_pt = dataPoints[i]; const Point &next_pt = dataPoints[i + 1]; temp_to_slope[cur_pt.x] = slope_function(cur_pt, next_pt); } return temp_to_slope; } leviathan_config parse_config_file(const char *const path) { leviathan_config options; try { YAML::Node config = YAML::LoadFile(path); options.temp_source_ = stringToTempSource(config["temperature_source"].as<std::string>()); options.fan_profile_ = configure_profile(config["fan_profile"]); options.pump_profile_ = config["pump_profile"] ? configure_profile(config["pump_profile"]) : options.fan_profile_; options.main_color_ = config["main_color"].as<uint32_t>(); options.interval_ = config["interval"].as<uint32_t>(); } catch (std::exception &e) { LOG(FATAL) << "Yaml parsing error: " << e.what(); } return options; }
2,290
858
#ifdef CH_LANG_CC /* * _______ __ * / ___/ / ___ __ _ / / ___ * / /__/ _ \/ _ \/ V \/ _ \/ _ \ * \___/_//_/\___/_/_/_/_.__/\___/ * Please refer to Copyright.txt, in Chombo's root directory. */ #endif // #include <cstdio> //this one has getNearPeriodic #include "PiecewiseLinearFillPatch.H" #include "NWOQuadCFInterp.H" #include "IntVectSet.H" #include "DebugOut.H" #include "NamespaceHeader.H" void NWOQuadCFInterp:: define(/// layout at this level const DisjointBoxLayout& a_thisDisjointBoxLayout, /// layout at coarser level const DisjointBoxLayout& a_coarserDisjointBoxLayout, /// number of variables const int& a_numStates, /// problem domain on the coarser level const ProblemDomain& a_coarseDomain, /// refinement ratio between this level and the coarser level const int& a_refineCoarse, /// number of layers of ghost cells to fill by interpolation const int& a_interpRadius) { // Cache data m_numStates = a_numStates; m_coarseDomain = a_coarseDomain; m_refineCoarse = a_refineCoarse; m_interpRadius = a_interpRadius; m_layout = a_thisDisjointBoxLayout; m_coarseLayout = a_coarserDisjointBoxLayout; m_refineVect = m_refineCoarse * IntVect::Unit; ProblemDomain fineDomain = refine(m_coarseDomain, m_refineVect); coarsen(m_layoutCoarsened, m_layout, m_refineVect); int coarseGhost = a_interpRadius/a_refineCoarse + 2; m_coarsenedFineData.define(m_layoutCoarsened, m_numStates, coarseGhost*IntVect::Unit); m_cfivs.define(m_layout); for(DataIterator dit = m_layout.dataIterator(); dit.ok(); ++dit) { Box ghostBox = m_layout[dit()]; ghostBox.grow(a_interpRadius); ghostBox &= fineDomain; m_cfivs[dit].define(dit(), m_layout, ghostBox); } // Everything is defined now. m_defined = true; } ////////////////////////////////////////////////////////////////////////////// void NWOQuadCFInterp:: coarseFineInterp(/// interpolated solution on this level LevelData<FArrayBox>& a_fineData, /// solution on coarser level const LevelData<FArrayBox>& a_coarseData, /// starting coarse data component int a_srcComp, /// starting fine data component int a_dstComp, /// number of data components to interpolate int a_numComp) { CH_assert(m_defined); const Interval srcInterval(a_srcComp, a_srcComp + a_numComp-1); const Interval dstInterval(a_dstComp, a_dstComp + a_numComp-1); a_coarseData.copyTo(srcInterval, m_coarsenedFineData, dstInterval); int ibox = 0; for (DataIterator dit = m_layout.dataIterator();dit.ok(); ++dit) { interpOnPatch(a_fineData[dit()], m_coarsenedFineData[dit()], dit(), a_srcComp, a_dstComp, a_numComp); ibox++; } } ////////////////////////////////////////////////////////////////////////////// void NWOQuadCFInterp:: homogeneousCoarseFineInterp(/// interpolated solution on this level LevelData<FArrayBox>& a_fineData, /// solution on coarser level int a_srcComp, /// starting fine data component int a_dstComp, /// number of data components to interpolate int a_numComp) { CH_assert(m_defined); for(DataIterator dit = m_coarsenedFineData.dataIterator(); dit.ok(); ++dit) { m_coarsenedFineData[dit()].setVal(0.); } for (DataIterator dit = m_layout.dataIterator();dit.ok(); ++dit) { interpOnPatch(a_fineData[dit()], m_coarsenedFineData[dit()], dit(), a_srcComp, a_dstComp, a_numComp); } } ///////////// void NWOQuadCFInterp:: interpOnPatch(FArrayBox& a_fineData, const FArrayBox& a_coarseData, const DataIndex& a_dit, int a_srcComp, int a_dstComp, int a_numComp) { const IntVectSet& cfivsFine = m_cfivs[a_dit].getIVS(); //dumpIVS(&cfivsFine); Real dxFine = 1; Real dxCoar = m_refineCoarse; for(IVSIterator ivsit(cfivsFine); ivsit.ok(); ++ivsit) { const IntVect& ivFine = ivsit(); int ideb = 0; if((ivFine[0]==16) && (ivFine[1]==8)) { ideb = 1; } IntVect ivCoar = coarsen(ivFine, m_refineCoarse); RealVect fineLoc, coarLoc; for(int idir = 0; idir < SpaceDim; idir++) { fineLoc[idir] = dxFine*(ivFine[idir] + 0.5); coarLoc[idir] = dxCoar*(ivCoar[idir] + 0.5); } for(int icomp = 0; icomp < a_numComp; icomp++) { int srcComp = a_srcComp + icomp; int dstComp = a_dstComp + icomp; RealVect firstDerivs, secondDerivs, mixedDerivs; getDerivs(firstDerivs, secondDerivs, mixedDerivs, a_coarseData, ivCoar, dxCoar, icomp); Real coarValue = a_coarseData(ivCoar, srcComp); RealVect distance = fineLoc - coarLoc; Real fineValue; extrapolateValue(fineValue, coarValue, firstDerivs, secondDerivs, mixedDerivs, distance); a_fineData(ivFine, dstComp) = fineValue; } } } void NWOQuadCFInterp:: getDerivs(RealVect& firstDerivs, RealVect& secondDerivs, RealVect& mixedDerivs, const FArrayBox & a_data, const IntVect& a_ivCoar, const Real & a_dx, const int & a_icomp) { const IntVect& iv = a_ivCoar; int icomp = a_icomp; Real dx = a_dx; //single direction derivs--use centered diffs if possible, one-sided otherwise for(int idir = 0; idir < SpaceDim; idir++) { IntVect ivhi = iv + BASISV(idir); IntVect ivlo = iv - BASISV(idir); bool hasHi = m_coarseDomain.contains(ivhi); bool hasLo = m_coarseDomain.contains(ivlo); if(hasHi && hasLo) { firstDerivs[idir] = (a_data(ivhi, icomp) - a_data(ivlo, icomp))/(2.*a_dx); secondDerivs[idir] = (a_data(ivhi, icomp) + a_data(ivlo, icomp) - 2*a_data(iv, icomp))/(a_dx*a_dx); } else if(hasHi) { IntVect ivVeryHi = ivhi + BASISV(idir); firstDerivs[idir] = (a_data(ivhi, icomp) - a_data(iv , icomp))/(a_dx); secondDerivs[idir] = (a_data(ivVeryHi, icomp) + a_data(iv , icomp) - 2*a_data(ivhi, icomp))/(a_dx*a_dx); } else if(hasLo) { IntVect ivVeryLo = ivlo - BASISV(idir); firstDerivs[idir] = (a_data(iv , icomp) - a_data(ivlo, icomp))/(a_dx); secondDerivs[idir] = (a_data(ivVeryLo, icomp) + a_data(iv , icomp) - 2*a_data(ivlo, icomp))/(a_dx*a_dx); } else { firstDerivs[idir] = 0; secondDerivs[idir] = 0; } } //now for that evil mixed deriv stuff --- 2d only has one, 3d has 3 //this is to keep from doing each pair twice Vector<int> doneThisPair(SpaceDim, 0); for(int idir = 0; idir < SpaceDim; idir++) { for(int jdir = 0; jdir < SpaceDim; jdir++) { if(idir != jdir) { int index = getMixedIndex(idir, jdir); if(doneThisPair[index] == 0) { doneThisPair[index] = 1; IntVect ivhiI = iv + BASISV(idir); IntVect ivloI = iv - BASISV(idir); IntVect ivhiJ = iv + BASISV(jdir); IntVect ivloJ = iv - BASISV(jdir); IntVect ivhiIhiJ = iv + BASISV(idir) + BASISV(jdir); IntVect ivloIloJ = iv - BASISV(idir) - BASISV(jdir); IntVect ivloIhiJ = iv - BASISV(idir) + BASISV(jdir); IntVect ivhiIloJ = iv + BASISV(idir) - BASISV(jdir); bool hasIvhiIhiJ = m_coarseDomain.contains(ivhiIhiJ); bool hasIvloIloJ = m_coarseDomain.contains(ivloIloJ); bool hasIvloIhiJ = m_coarseDomain.contains(ivloIhiJ); bool hasIvhiIloJ = m_coarseDomain.contains(ivhiIloJ); //just go through the corners and compute each mixed deriv that you have Real derivSum = 0; int numDerivs = 0; if(hasIvhiIhiJ) { Real dathiIhiJ = a_data(ivhiIhiJ, icomp); Real dathiI = a_data(ivhiI , icomp); Real dathiJ = a_data(ivhiJ , icomp); Real datcen = a_data(iv , icomp); Real mixedD = ((dathiIhiJ - dathiJ) - (dathiI - datcen))/dx/dx; derivSum += mixedD; numDerivs++; } if(hasIvloIloJ) { Real datloIloJ = a_data(ivloIloJ, icomp); Real datloI = a_data(ivloI , icomp); Real datloJ = a_data(ivloJ , icomp); Real datcen = a_data(iv , icomp); Real mixedD = ((datcen - datloI) - (datloJ - datloIloJ))/dx/dx; derivSum += mixedD; numDerivs++; } if(hasIvhiIloJ) { Real dathiIloJ = a_data(ivhiIloJ, icomp); Real dathiI = a_data(ivhiI , icomp); Real datloJ = a_data(ivloJ , icomp); Real datcen = a_data(iv , icomp); Real mixedD = ((dathiI - datcen) - (dathiIloJ - datloJ))/dx/dx; derivSum += mixedD; numDerivs++; } if(hasIvloIhiJ) { Real datloIhiJ = a_data(ivloIhiJ, icomp); Real datloI = a_data(ivloI , icomp); Real dathiJ = a_data(ivhiJ , icomp); Real datcen = a_data(iv , icomp); Real mixedD = ((dathiJ - datloIhiJ) - (datcen - datloI))/dx/dx; derivSum += mixedD; numDerivs++; } Real derivAvg = 0; if(numDerivs > 0) { derivAvg = derivSum/numDerivs; } mixedDerivs[index] = derivAvg; } } } } } void NWOQuadCFInterp:: extrapolateValue(Real & a_fineValue, const Real & a_coarValue, const RealVect & a_firstDerivs, const RealVect & a_secondDerivs, const RealVect & a_mixedDerivs, const RealVect & a_distance) { a_fineValue = a_coarValue; //add in first and second derivative contributions for(int idir = 0; idir < SpaceDim; idir++) { Real dx = a_distance[idir]; a_fineValue += dx*a_firstDerivs[idir]; a_fineValue += (dx*dx/2.)*a_secondDerivs[idir]; } //now for the evil mixed derivatives #if CH_SPACEDIM==2 Real dxdy = a_distance[0]*a_distance[1]; a_fineValue += dxdy*a_mixedDerivs[0]; #else for(int iindex = 0; iindex < SpaceDim; iindex++) { int idir, jdir; getMixedDerivDirections(idir, jdir, iindex); Real dx = a_distance[idir]; Real dy = a_distance[jdir]; a_fineValue += dx*dy*a_mixedDerivs[iindex]; } #endif } #include "NamespaceFooter.H"
12,019
4,164
// gram_Visitor.inl // #ifdef LZZ_ENABLE_INLINE #define LZZ_INLINE inline #else #define LZZ_INLINE #endif namespace gram { LZZ_INLINE Visitor::Visitor (bool slippery) : m_slippery (slippery) {} } #undef LZZ_INLINE
225
105
#include "Log.h" #include "Random.h" #include "VariableTypedefs.h" #include "GameObject.h" #include "Component.h" Component::Component(GameObject* owner, COMPONENT_TYPE type, bool is_active) : id (Random::LCG::GetRandomUint()), type (type), owner (owner), is_active (is_active) { } Component::~Component() { } bool Component::Update() { return true; } bool Component::CleanUp() { return true; } bool Component::SaveState(ParsonNode& root) const { return true; } bool Component::LoadState(ParsonNode& root) { return true; } // --- COMPONENT METHODS --- const char* Component::GetNameFromType() const { switch (type) { case COMPONENT_TYPE::NONE: { return "NONE"; } break; case COMPONENT_TYPE::TRANSFORM: { return "Transform"; } break; case COMPONENT_TYPE::MESH: { return "Mesh"; } break; case COMPONENT_TYPE::MATERIAL: { return "Material"; } break; case COMPONENT_TYPE::LIGHT: { return "Light"; } break; case COMPONENT_TYPE::CAMERA: { return "Camera"; } break; case COMPONENT_TYPE::ANIMATOR: { return "Animator"; } break; case COMPONENT_TYPE::ANIMATION: { return "Animation"; } break; } return "NONE"; } uint32 Component::GetID() const { return id; } void Component::ResetID() { id = Random::LCG::GetRandomUint(); } bool Component::IsActive() const { return is_active; } void Component::SetIsActive(const bool& set_to) { is_active = set_to; } GameObject* Component::GetOwner() const { return owner; }
1,462
593
// // Created by yryang on 2019/9/15. // #include "iostream" #include "string.h" #include "string" #include "stdlib.h" #include "stdio.h" #include "map" #include "vector" #include "set" #include "math.h" #include "queue" #include "algorithm" #include "unordered_map" using namespace std; struct node{ double ton; double totalpri; double pri; }nodes[10005]; double total; double price=0; double now=0; int N; int cmp(node a, node b){ return a.pri > b.pri; } int main(){ cin >> N >> total; for (int i = 0; i < N; ++i) { cin >> nodes[i].ton; } for (int j = 0; j < N; ++j) { cin >> nodes[j].totalpri; nodes[j].pri = nodes[j].totalpri / nodes[j].ton; } sort(nodes, nodes+N, cmp); for (int k = 0; k < N; ++k) { if(now + nodes[k].ton >= total){ price += (total-now)*nodes[k].pri; break; }else{ price += nodes[k].totalpri; now += nodes[k].ton; } } printf("%.2lf\n", price); return 0; }
1,036
415
/* Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists. Example: Input: 1->2->4, 1->3->4 Output: 1->1->2->3->4->4 */ class Solution { public: ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) { ListNode head(0), *l3 = &head; while (l1 && l2) { if (l1->val < l2->val) { l3->next = l1; l1 = l1->next; } else { l3->next = l2; l2 = l2->next; } l3 = l3->next; } if (l1) { l3->next = l1; } else { l3->next = l2; } return head.next; } void test() { assert(listNodeToString(mergeTwoLists(stringToListNode("[1,2,4]"), stringToListNode("[1,3,4]"))) == "[1, 1, 2, 3, 4, 4]"); } };
895
324
#include <c10/util/Optional.h> #include <torch/csrc/jit/script/lexer.h> #include <torch/csrc/jit/script/parse_string_literal.h> #include <torch/csrc/jit/script/parser.h> #include <torch/csrc/jit/script/tree.h> #include <torch/csrc/jit/script/tree_views.h> namespace torch { namespace jit { namespace script { Decl mergeTypesFromTypeComment( const Decl& decl, const Decl& type_annotation_decl, bool is_method) { auto expected_num_annotations = decl.params().size(); if (is_method) { // `self` argument expected_num_annotations -= 1; } if (expected_num_annotations != type_annotation_decl.params().size()) { throw ErrorReport(type_annotation_decl.range()) << "Number of type annotations (" << type_annotation_decl.params().size() << ") did not match the number of " << "function parameters (" << expected_num_annotations << ")"; } auto old = decl.params(); auto _new = type_annotation_decl.params(); // Merge signature idents and ranges with annotation types std::vector<Param> new_params; size_t i = is_method ? 1 : 0; size_t j = 0; if (is_method) { new_params.push_back(old[0]); } for (; i < decl.params().size(); ++i, ++j) { new_params.emplace_back(old[i].withType(_new[j].type())); } return Decl::create( decl.range(), List<Param>::create(decl.range(), new_params), type_annotation_decl.return_type()); } struct ParserImpl { explicit ParserImpl(const std::string& str) : L(str), shared(sharedParserData()) {} Ident parseIdent() { auto t = L.expect(TK_IDENT); // whenever we parse something that has a TreeView type we always // use its create method so that the accessors and the constructor // of the Compound tree are in the same place. return Ident::create(t.range, t.text()); } TreeRef createApply(const Expr& expr) { TreeList attributes; auto range = L.cur().range; TreeList inputs; parseOperatorArguments(inputs, attributes); return Apply::create( range, expr, List<Expr>(makeList(range, std::move(inputs))), List<Attribute>(makeList(range, std::move(attributes)))); } static bool followsTuple(int kind) { switch (kind) { case TK_PLUS_EQ: case TK_MINUS_EQ: case TK_TIMES_EQ: case TK_DIV_EQ: case TK_NEWLINE: case '=': case ')': return true; default: return false; } } // exp | expr, | expr, expr, ... Expr parseExpOrExpTuple() { auto prefix = parseExp(); if (L.cur().kind == ',') { std::vector<Expr> exprs = {prefix}; while (L.nextIf(',')) { if (followsTuple(L.cur().kind)) break; exprs.push_back(parseExp()); } auto list = List<Expr>::create(prefix.range(), exprs); prefix = TupleLiteral::create(list.range(), list); } return prefix; } // things like a 1.0 or a(4) that are not unary/binary expressions // and have higher precedence than all of them TreeRef parseBaseExp() { TreeRef prefix; switch (L.cur().kind) { case TK_NUMBER: { prefix = parseConst(); } break; case TK_TRUE: case TK_FALSE: case TK_NONE: { auto k = L.cur().kind; auto r = L.cur().range; prefix = c(k, r, {}); L.next(); } break; case '(': { L.next(); if (L.nextIf(')')) { /// here we have the empty tuple case std::vector<Expr> vecExpr; List<Expr> listExpr = List<Expr>::create(L.cur().range, vecExpr); prefix = TupleLiteral::create(L.cur().range, listExpr); break; } prefix = parseExpOrExpTuple(); L.expect(')'); } break; case '[': { auto list = parseList('[', ',', ']', &ParserImpl::parseExp); prefix = ListLiteral::create(list.range(), List<Expr>(list)); } break; case TK_STRINGLITERAL: { prefix = parseConcatenatedStringLiterals(); } break; default: { Ident name = parseIdent(); prefix = Var::create(name.range(), name); } break; } while (true) { if (L.nextIf('.')) { const auto name = parseIdent(); prefix = Select::create(name.range(), Expr(prefix), Ident(name)); } else if (L.cur().kind == '(') { prefix = createApply(Expr(prefix)); } else if (L.cur().kind == '[') { prefix = parseSubscript(prefix); } else { break; } } return prefix; } TreeRef parseAssignmentOp() { auto r = L.cur().range; switch (L.cur().kind) { case TK_PLUS_EQ: case TK_MINUS_EQ: case TK_TIMES_EQ: case TK_DIV_EQ: { int modifier = L.next().text()[0]; return c(modifier, r, {}); } break; default: { L.expect('='); return c('=', r, {}); // no reduction } break; } } TreeRef parseTrinary( TreeRef true_branch, const SourceRange& range, int binary_prec) { auto cond = parseExp(); L.expect(TK_ELSE); auto false_branch = parseExp(binary_prec); return c(TK_IF_EXPR, range, {cond, std::move(true_branch), false_branch}); } // parse the longest expression whose binary operators have // precedence strictly greater than 'precedence' // precedence == 0 will parse _all_ expressions // this is the core loop of 'top-down precedence parsing' Expr parseExp() { return parseExp(0); } Expr parseExp(int precedence) { TreeRef prefix = nullptr; int unary_prec; if (shared.isUnary(L.cur().kind, &unary_prec)) { auto kind = L.cur().kind; auto pos = L.cur().range; L.next(); auto unary_kind = kind == '*' ? TK_STARRED : kind == '-' ? TK_UNARY_MINUS : kind; auto subexp = parseExp(unary_prec); // fold '-' into constant numbers, so that attributes can accept // things like -1 if (unary_kind == TK_UNARY_MINUS && subexp.kind() == TK_CONST) { prefix = Const::create(subexp.range(), "-" + Const(subexp).text()); } else { prefix = c(unary_kind, pos, {subexp}); } } else { prefix = parseBaseExp(); } int binary_prec; while (shared.isBinary(L.cur().kind, &binary_prec)) { if (binary_prec <= precedence) // not allowed to parse something which is // not greater than 'precedence' break; int kind = L.cur().kind; auto pos = L.cur().range; L.next(); if (shared.isRightAssociative(kind)) binary_prec--; // special case for trinary operator if (kind == TK_IF) { prefix = parseTrinary(prefix, pos, binary_prec); continue; } prefix = c(kind, pos, {prefix, parseExp(binary_prec)}); } return Expr(prefix); } template <typename T> List<T> parseList(int begin, int sep, int end, T (ParserImpl::*parse)()) { auto r = L.cur().range; if (begin != TK_NOTHING) L.expect(begin); std::vector<T> elements; if (L.cur().kind != end) { do { elements.push_back((this->*parse)()); } while (L.nextIf(sep)); } if (end != TK_NOTHING) L.expect(end); return List<T>::create(r, elements); } Const parseConst() { auto range = L.cur().range; auto t = L.expect(TK_NUMBER); return Const::create(t.range, t.text()); } StringLiteral parseConcatenatedStringLiterals() { auto range = L.cur().range; std::stringstream ss; while (L.cur().kind == TK_STRINGLITERAL) { auto literal_range = L.cur().range; ss << parseStringLiteral(literal_range, L.next().text()); } return StringLiteral::create(range, ss.str()); } Expr parseAttributeValue() { return parseExp(); } void parseOperatorArguments(TreeList& inputs, TreeList& attributes) { L.expect('('); if (L.cur().kind != ')') { do { if (L.cur().kind == TK_IDENT && L.lookahead().kind == '=') { auto ident = parseIdent(); L.expect('='); auto v = parseAttributeValue(); attributes.push_back( Attribute::create(ident.range(), Ident(ident), v)); } else { inputs.push_back(parseExp()); } } while (L.nextIf(',')); } L.expect(')'); } // Parse expr's of the form [a:], [:b], [a:b], [:] Expr parseSubscriptExp() { TreeRef first, second; auto range = L.cur().range; if (L.cur().kind != ':') { first = parseExp(); } if (L.nextIf(':')) { if (L.cur().kind != ',' && L.cur().kind != ']') { second = parseExp(); } auto maybe_first = first ? Maybe<Expr>::create(range, Expr(first)) : Maybe<Expr>::create(range); auto maybe_second = second ? Maybe<Expr>::create(range, Expr(second)) : Maybe<Expr>::create(range); return SliceExpr::create(range, maybe_first, maybe_second); } else { return Expr(first); } } TreeRef parseSubscript(const TreeRef& value) { const auto range = L.cur().range; auto subscript_exprs = parseList('[', ',', ']', &ParserImpl::parseSubscriptExp); return Subscript::create(range, Expr(value), subscript_exprs); } TreeRef parseParam() { auto ident = parseIdent(); TreeRef type; if (L.nextIf(':')) { type = parseExp(); } else { type = Var::create(L.cur().range, Ident::create(L.cur().range, "Tensor")); } TreeRef def; if (L.nextIf('=')) { def = Maybe<Expr>::create(L.cur().range, parseExp()); } else { def = Maybe<Expr>::create(L.cur().range); } return Param::create( type->range(), Ident(ident), Expr(type), Maybe<Expr>(def)); } Param parseBareTypeAnnotation() { auto type = parseExp(); return Param::create( type.range(), Ident::create(type.range(), ""), type, Maybe<Expr>::create(type.range())); } Decl parseTypeComment() { auto range = L.cur().range; L.expect(TK_TYPE_COMMENT); auto param_types = parseList('(', ',', ')', &ParserImpl::parseBareTypeAnnotation); TreeRef return_type; if (L.nextIf(TK_ARROW)) { auto return_type_range = L.cur().range; return_type = Maybe<Expr>::create(return_type_range, parseExp()); } else { return_type = Maybe<Expr>::create(L.cur().range); } return Decl::create(range, param_types, Maybe<Expr>(return_type)); } // 'first' has already been parsed since expressions can exist // alone on a line: // first[,other,lhs] = rhs TreeRef parseAssign(const Expr& lhs) { auto op = parseAssignmentOp(); auto rhs = parseExpOrExpTuple(); L.expect(TK_NEWLINE); if (op->kind() == '=') { return Assign::create(lhs.range(), lhs, Expr(rhs)); } else { // this is an augmented assignment if (lhs.kind() == TK_TUPLE_LITERAL) { throw ErrorReport(lhs.range()) << " augmented assignment can only have one LHS expression"; } return AugAssign::create(lhs.range(), lhs, AugAssignKind(op), Expr(rhs)); } } TreeRef parseStmt() { switch (L.cur().kind) { case TK_IF: return parseIf(); case TK_WHILE: return parseWhile(); case TK_FOR: return parseFor(); case TK_GLOBAL: { auto range = L.next().range; auto idents = parseList(TK_NOTHING, ',', TK_NOTHING, &ParserImpl::parseIdent); L.expect(TK_NEWLINE); return Global::create(range, idents); } case TK_RETURN: { auto range = L.next().range; Expr value = L.cur().kind != TK_NEWLINE ? parseExpOrExpTuple() : Expr(c(TK_NONE, range, {})); L.expect(TK_NEWLINE); return Return::create(range, value); } case TK_RAISE: { auto range = L.next().range; auto expr = parseExp(); L.expect(TK_NEWLINE); return Raise::create(range, expr); } case TK_ASSERT: { auto range = L.next().range; auto cond = parseExp(); Maybe<Expr> maybe_first = Maybe<Expr>::create(range); if (L.nextIf(',')) { auto msg = parseExp(); maybe_first = Maybe<Expr>::create(range, Expr(msg)); } L.expect(TK_NEWLINE); return Assert::create(range, cond, maybe_first); } case TK_PASS: { auto range = L.next().range; L.expect(TK_NEWLINE); return Pass::create(range); } case TK_DEF: { return parseFunction(/*is_method=*/false); } default: { auto lhs = parseExpOrExpTuple(); if (L.cur().kind != TK_NEWLINE) { return parseAssign(lhs); } else { L.expect(TK_NEWLINE); return ExprStmt::create(lhs.range(), lhs); } } } } TreeRef parseOptionalIdentList() { TreeRef list = nullptr; if (L.cur().kind == '(') { list = parseList('(', ',', ')', &ParserImpl::parseIdent); } else { list = c(TK_LIST, L.cur().range, {}); } return list; } TreeRef parseIf(bool expect_if = true) { auto r = L.cur().range; if (expect_if) L.expect(TK_IF); auto cond = parseExp(); L.expect(':'); auto true_branch = parseStatements(); auto false_branch = makeList(L.cur().range, {}); if (L.nextIf(TK_ELSE)) { L.expect(':'); false_branch = parseStatements(); } else if (L.nextIf(TK_ELIF)) { // NB: this needs to be a separate statement, since the call to parseIf // mutates the lexer state, and thus causes a heap-use-after-free in // compilers which evaluate argument expressions LTR auto range = L.cur().range; false_branch = makeList(range, {parseIf(false)}); } return If::create( r, Expr(cond), List<Stmt>(true_branch), List<Stmt>(false_branch)); } TreeRef parseWhile() { auto r = L.cur().range; L.expect(TK_WHILE); auto cond = parseExp(); L.expect(':'); auto body = parseStatements(); return While::create(r, Expr(cond), List<Stmt>(body)); } TreeRef parseFor() { auto r = L.cur().range; L.expect(TK_FOR); auto targets = parseList(TK_NOTHING, ',', TK_NOTHING, &ParserImpl::parseExp); L.expect(TK_IN); auto itrs = parseList(TK_NOTHING, ',', TK_NOTHING, &ParserImpl::parseExp); L.expect(':'); auto body = parseStatements(); return For::create(r, targets, itrs, body); } TreeRef parseStatements(bool expect_indent = true) { auto r = L.cur().range; if (expect_indent) { L.expect(TK_INDENT); } TreeList stmts; do { stmts.push_back(parseStmt()); } while (!L.nextIf(TK_DEDENT)); return c(TK_LIST, r, std::move(stmts)); } Maybe<Expr> parseReturnAnnotation() { if (L.nextIf(TK_ARROW)) { // Exactly one expression for return type annotation auto return_type_range = L.cur().range; return Maybe<Expr>::create(return_type_range, parseExp()); } else { return Maybe<Expr>::create(L.cur().range); } } Decl parseDecl() { auto paramlist = parseList('(', ',', ')', &ParserImpl::parseParam); // Parse return type annotation TreeRef return_type; Maybe<Expr> return_annotation = parseReturnAnnotation(); L.expect(':'); return Decl::create( paramlist.range(), List<Param>(paramlist), return_annotation); } TreeRef parseFunction(bool is_method) { L.expect(TK_DEF); auto name = parseIdent(); auto decl = parseDecl(); // Handle type annotations specified in a type comment as the first line of // the function. L.expect(TK_INDENT); if (L.cur().kind == TK_TYPE_COMMENT) { auto type_annotation_decl = Decl(parseTypeComment()); L.expect(TK_NEWLINE); decl = mergeTypesFromTypeComment(decl, type_annotation_decl, is_method); } auto stmts_list = parseStatements(false); return Def::create( name.range(), Ident(name), Decl(decl), List<Stmt>(stmts_list)); } Lexer& lexer() { return L; } private: // short helpers to create nodes TreeRef c(int kind, const SourceRange& range, TreeList&& trees) { return Compound::create(kind, range, std::move(trees)); } TreeRef makeList(const SourceRange& range, TreeList&& trees) { return c(TK_LIST, range, std::move(trees)); } Lexer L; SharedParserData& shared; }; Parser::Parser(const std::string& src) : pImpl(new ParserImpl(src)) {} Parser::~Parser() = default; TreeRef Parser::parseFunction(bool is_method) { return pImpl->parseFunction(is_method); } Lexer& Parser::lexer() { return pImpl->lexer(); } Decl Parser::parseTypeComment() { return pImpl->parseTypeComment(); } } // namespace script } // namespace jit } // namespace torch
16,838
5,639
/*! * @copyright * Copyright (c) 2015-2017 Intel Corporation * * @copyright * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * @copyright * http://www.apache.org/licenses/LICENSE-2.0 * * @copyright * 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 network.hpp * @brief string enums for model classes, see enum_builder.hpp for more info * */ #pragma once #include "enum_builder.hpp" namespace agent_framework { namespace model { namespace enums { /*! * @brief ENUM SwitchTechnology for Switch class member * * */ ENUM(SwitchTechnology, uint32_t, Ethernet, PCIe); /*! * @brief ENUM Switch role in the network * */ ENUM(SwitchRole, uint32_t, TOR, EOR, Drawer, Unknown); /*! * @brief ENUM PortType for Switch Port class member * * */ ENUM(PortType, uint32_t, Upstream, Downstream, MeshPort, Unknown); /*! * @brief ENUM PortClass for Switch Port class member * * */ ENUM(PortClass, uint32_t, Physical, Logical, Reserved); /*! * @brief ENUM PortMode for Switch Port class member * * */ ENUM(PortMode, uint32_t, Unknown, LinkAggregationStatic, LinkAggregationDynamic); /*! * @brief ENUM LinkTechnology for Switch Port class member * * */ ENUM(LinkTechnology, uint32_t, Ethernet, PCIe, Unknown); /*! * @brief ENUM OperationalState for Switch Port class member * * */ ENUM(OperationalState, uint32_t, Up, Down, Unknown); /*! * @brief ENUM AdministrativeState for Switch Port class member * * */ ENUM(AdministrativeState, uint32_t, Up, Down); /*! * @brief ENUM NetworkServiceName for Manager class Network Service subclass * member * */ ENUM(NetworkServiceName, uint32_t, HTTP, HTTPS, SNMP, VirtualMedia, Telnet, SSDP, IPMI, SSH, KVMIP); /*! * @brief ENUM AclAction for Acl rule * */ ENUM(AclAction, uint32_t, Permit, Deny, Forward, Mirror); /*! * @brief ENUM AclMirrorType for Acl mirror rule * */ ENUM(AclMirrorType, uint32_t, Egress, Ingress, Bidirectional, Redirect); } } }
2,361
821
/** $lic$ * Copyright (C) 2012-2015 by Massachusetts Institute of Technology * Copyright (C) 2010-2013 by The Board of Trustees of Stanford University * * This file is part of zsim. * * zsim 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, version 2. * * If you use this software in your research, we request that you reference * the zsim paper ("ZSim: Fast and Accurate Microarchitectural Simulation of * Thousand-Core Systems", Sanchez and Kozyrakis, ISCA-40, June 2013) as the * source of the simulator in any publications that use this software, and that * you send us a citation of your work. * * zsim is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see <http://www.gnu.org/licenses/>. */ #include "partitioner.h" // UMon UMonMonitor::UMonMonitor(uint32_t _numLines, uint32_t _umonLines, uint32_t _umonBuckets, uint32_t _numPartitions, uint32_t _buckets) : PartitionMonitor(_buckets) , missCache(nullptr) , missCacheValid(false) , monitors(_numPartitions, nullptr) { assert(_numPartitions > 0); missCache = gm_calloc<uint32_t>(_buckets * _numPartitions); for (auto& monitor : monitors) { monitor = new UMon(_numLines, _umonLines, _umonBuckets); } } UMonMonitor::~UMonMonitor() { for (auto monitor : monitors) { delete monitor; } gm_free(missCache); monitors.clear(); } void UMonMonitor::access(uint32_t partition, Address lineAddr) { assert(partition < monitors.size()); monitors[partition]->access(lineAddr); // check optimization assumption -- we shouldn't cache all misses // if they are getting accessed while they are updated! -nzb assert(!missCacheValid); missCacheValid = false; } uint32_t UMonMonitor::getNumAccesses(uint32_t partition) const { assert(partition < monitors.size()); auto monitor = monitors[partition]; return monitor->getNumAccesses(); } uint32_t UMonMonitor::get(uint32_t partition, uint32_t bucket) const { assert(partition < monitors.size()); if (!missCacheValid) { getMissCurves(); missCacheValid = true; } return missCache[partition*buckets+bucket]; } void UMonMonitor::getMissCurves() const { for (uint32_t partition = 0; partition < getNumPartitions(); partition++) { getMissCurve(&missCache[partition*buckets], partition); } } void UMonMonitor::getMissCurve(uint32_t* misses, uint32_t partition) const { assert(partition < monitors.size()); auto monitor = monitors[partition]; uint32_t umonBuckets = monitor->getBuckets(); uint64_t umonMisses[ umonBuckets ]; monitor->getMisses(umonMisses); // Upsample or downsample // We have an odd number of elements; the last one is the one that // should not be aliased, as it is the one without buckets if (umonBuckets >= buckets) { uint32_t downsampleRatio = umonBuckets/buckets; assert(umonBuckets % buckets == 0); //info("Downsampling (or keeping sampling), ratio %d", downsampleRatio); for (uint32_t j = 0; j < buckets; j++) { misses[j] = umonMisses[j*downsampleRatio]; } misses[buckets] = umonMisses[umonBuckets]; } else { uint32_t upsampleRatio = buckets/umonBuckets; assert(buckets % umonBuckets == 0); //info("Upsampling , ratio %d", upsampleRatio); for (uint32_t j = 0; j < umonBuckets; j++) { misses[upsampleRatio*j] = umonMisses[j]; double m0 = umonMisses[j]; double m1 = umonMisses[j+1]; for (uint32_t k = 1; k < upsampleRatio; k++) { double frac = ((double)k)/((double)upsampleRatio); double m = m0*(1-frac) + m1*(frac); misses[upsampleRatio*j + k] = (uint64_t)m; } misses[buckets] = umonMisses[umonBuckets]; } } /*info("Miss utility curves %d:", partition); for (uint32_t j = 0; j <= buckets; j++) info(" misses[%d] = %ld", j, misses[j]); for (uint32_t j = 0; j <= umonBuckets; j++) info(" umonMisses[%d] = %ld", j, umonMisses[j]); */ } void UMonMonitor::reset() { for (auto monitor : monitors) { monitor->startNextInterval(); } missCacheValid = false; }
4,653
1,577
#pragma once #include <map> #include "cereal/gen/cpp/log.capnp.h" #if defined(QCOM) || defined(QCOM2) #include <SLES/OpenSLES.h> #include <SLES/OpenSLES_Android.h> #endif typedef cereal::CarControl::HUDControl::AudibleAlert AudibleAlert; class Sound { public: Sound() = default; bool init(int volume); bool play(AudibleAlert alert); void stop(); void setVolume(int volume); ~Sound(); #if defined(QCOM) || defined(QCOM2) private: SLObjectItf engine_ = nullptr; SLObjectItf outputMix_ = nullptr; int last_volume_ = 0; double last_set_volume_time_ = 0.; AudibleAlert currentSound_ = AudibleAlert::NONE; struct Player; std::map<AudibleAlert, Player *> player_; friend void SLAPIENTRY slplay_callback(SLPlayItf playItf, void *context, SLuint32 event); #endif };
791
299
#include <AppBox/AppBox.h> #include <AppBox/ArgsParser.h> #include <Instance/Instance.h> #include <stdexcept> #include <glm/gtx/transform.hpp> #include <Utilities/Common.h> int main(int argc, char* argv[]) { Settings settings = ParseArgs(argc, argv); AppBox app("CoreDxrTriangle", settings); AppRect rect = app.GetAppRect(); std::shared_ptr<Instance> instance = CreateInstance(settings.api_type); std::shared_ptr<Adapter> adapter = std::move(instance->EnumerateAdapters()[settings.required_gpu_index]); app.SetGpuName(adapter->GetName()); std::shared_ptr<Device> device = adapter->CreateDevice(); if (!device->IsDxrSupported()) throw std::runtime_error("Ray Tracing is not supported"); std::shared_ptr<CommandQueue> command_queue = device->GetCommandQueue(CommandListType::kGraphics); std::shared_ptr<CommandQueue> upload_command_queue = device->GetCommandQueue(CommandListType::kGraphics); constexpr uint32_t frame_count = 3; std::shared_ptr<Swapchain> swapchain = device->CreateSwapchain(app.GetNativeWindow(), rect.width, rect.height, frame_count, settings.vsync); uint64_t fence_value = 0; std::shared_ptr<Fence> fence = device->CreateFence(fence_value); std::vector<uint32_t> index_data = { 0, 1, 2 }; std::shared_ptr<Resource> index_buffer = device->CreateBuffer(BindFlag::kIndexBuffer | BindFlag::kCopyDest, sizeof(uint32_t) * index_data.size()); index_buffer->CommitMemory(MemoryType::kDefault); index_buffer->SetName("index_buffer"); std::vector<glm::vec3> vertex_data = { glm::vec3(-0.5, -0.5, 0.0), glm::vec3(0.0, 0.5, 0.0), glm::vec3(0.5, -0.5, 0.0) }; std::shared_ptr<Resource> vertex_buffer = device->CreateBuffer(BindFlag::kVertexBuffer | BindFlag::kCopyDest, sizeof(vertex_data.front()) * vertex_data.size()); vertex_buffer->CommitMemory(MemoryType::kDefault); vertex_buffer->SetName("vertex_buffer"); std::shared_ptr<Resource> upload_buffer = device->CreateBuffer(BindFlag::kCopySource, index_buffer->GetWidth() + vertex_buffer->GetWidth()); upload_buffer->CommitMemory(MemoryType::kUpload); upload_buffer->SetName("upload_buffer"); upload_buffer->UpdateUploadBuffer(0, index_data.data(), sizeof(index_data.front()) * index_data.size()); upload_buffer->UpdateUploadBuffer(index_buffer->GetWidth(), vertex_data.data(), sizeof(vertex_data.front()) * vertex_data.size()); std::shared_ptr<CommandList> upload_command_list = device->CreateCommandList(CommandListType::kGraphics); upload_command_list->CopyBuffer(upload_buffer, index_buffer, { { 0, 0, index_buffer->GetWidth() } }); upload_command_list->CopyBuffer(upload_buffer, vertex_buffer, { { index_buffer->GetWidth(), 0, vertex_buffer->GetWidth() } }); upload_command_list->ResourceBarrier({ { index_buffer, ResourceState::kCopyDest, ResourceState::kNonPixelShaderResource } }); upload_command_list->ResourceBarrier({ { vertex_buffer, ResourceState::kCopyDest, ResourceState::kNonPixelShaderResource } }); RaytracingGeometryDesc raytracing_geometry_desc = { { vertex_buffer, gli::format::FORMAT_RGB32_SFLOAT_PACK32, 3 }, { index_buffer, gli::format::FORMAT_R32_UINT_PACK32, 3 }, RaytracingGeometryFlags::kOpaque }; const uint32_t bottom_count = 2; auto blas_prebuild_info = device->GetBLASPrebuildInfo({ raytracing_geometry_desc }, BuildAccelerationStructureFlags::kAllowCompaction); auto tlas_prebuild_info = device->GetTLASPrebuildInfo(bottom_count, BuildAccelerationStructureFlags::kNone); uint64_t acceleration_structures_size = Align(blas_prebuild_info.acceleration_structure_size, kAccelerationStructureAlignment) + tlas_prebuild_info.acceleration_structure_size; std::shared_ptr<Resource> acceleration_structures_memory = device->CreateBuffer(BindFlag::kAccelerationStructure, acceleration_structures_size); acceleration_structures_memory->CommitMemory(MemoryType::kDefault); acceleration_structures_memory->SetName("acceleration_structures_memory"); std::shared_ptr<Resource> bottom = device->CreateAccelerationStructure( AccelerationStructureType::kBottomLevel, acceleration_structures_memory, 0 ); auto scratch = device->CreateBuffer(BindFlag::kRayTracing, std::max(blas_prebuild_info.build_scratch_data_size, tlas_prebuild_info.build_scratch_data_size)); scratch->CommitMemory(MemoryType::kDefault); scratch->SetName("scratch"); auto blas_compacted_size_buffer = device->CreateBuffer(BindFlag::kCopyDest, sizeof(uint64_t)); blas_compacted_size_buffer->CommitMemory(MemoryType::kReadback); blas_compacted_size_buffer->SetName("blas_compacted_size_buffer"); auto query_heap = device->CreateQueryHeap(QueryHeapType::kAccelerationStructureCompactedSize, 1); upload_command_list->BuildBottomLevelAS({}, bottom, scratch, 0, { raytracing_geometry_desc }, BuildAccelerationStructureFlags::kAllowCompaction); upload_command_list->UAVResourceBarrier(bottom); upload_command_list->WriteAccelerationStructuresProperties({ bottom }, query_heap, 0); upload_command_list->ResolveQueryData(query_heap, 0, 1, blas_compacted_size_buffer, 0); upload_command_list->Close(); upload_command_queue->ExecuteCommandLists({ upload_command_list }); upload_command_queue->Signal(fence, ++fence_value); fence->Wait(fence_value); uint64_t blas_compacted_size = *reinterpret_cast<uint64_t*>(blas_compacted_size_buffer->Map()); blas_compacted_size_buffer->Unmap(); upload_command_list->Reset(); upload_command_list->CopyAccelerationStructure(bottom, bottom, CopyAccelerationStructureMode::kCompact); std::vector<std::pair<std::shared_ptr<Resource>, glm::mat4x4>> geometry = { { bottom, glm::transpose(glm::translate(glm::vec3(-0.5f, 0.0f, 0.0f))) }, { bottom, glm::transpose(glm::translate(glm::vec3(0.5f, 0.0f, 0.0f))) }, }; assert(geometry.size() == bottom_count); std::vector<RaytracingGeometryInstance> instances; for (const auto& mesh : geometry) { RaytracingGeometryInstance& instance = instances.emplace_back(); memcpy(&instance.transform, &mesh.second, sizeof(instance.transform)); instance.instance_offset = static_cast<uint32_t>(instances.size() - 1); instance.instance_mask = 0xff; instance.acceleration_structure_handle = mesh.first->GetAccelerationStructureHandle(); } std::shared_ptr<Resource> top = device->CreateAccelerationStructure( AccelerationStructureType::kTopLevel, acceleration_structures_memory, Align(blas_compacted_size, kAccelerationStructureAlignment) ); auto instance_data = device->CreateBuffer(BindFlag::kRayTracing, instances.size() * sizeof(instances.back())); instance_data->CommitMemory(MemoryType::kUpload); instance_data->SetName("instance_data"); instance_data->UpdateUploadBuffer(0, instances.data(), instances.size() * sizeof(instances.back())); upload_command_list->BuildTopLevelAS({}, top, scratch, 0, instance_data, 0, instances.size(), BuildAccelerationStructureFlags::kNone); upload_command_list->UAVResourceBarrier(top); std::shared_ptr<Resource> uav = device->CreateTexture(TextureType::k2D, BindFlag::kUnorderedAccess | BindFlag::kCopySource, swapchain->GetFormat(), 1, rect.width, rect.height, 1, 1); uav->CommitMemory(MemoryType::kDefault); uav->SetName("uav"); upload_command_list->ResourceBarrier({ { uav, uav->GetInitialState(), ResourceState::kUnorderedAccess } }); upload_command_list->Close(); upload_command_queue->ExecuteCommandLists({ upload_command_list }); upload_command_queue->Signal(fence, ++fence_value); command_queue->Wait(fence, fence_value); ViewDesc top_view_desc = {}; top_view_desc.view_type = ViewType::kAccelerationStructure; std::shared_ptr<View> top_view = device->CreateView(top, top_view_desc); ViewDesc uav_view_desc = {}; uav_view_desc.view_type = ViewType::kRWTexture; uav_view_desc.dimension = ViewDimension::kTexture2D; std::shared_ptr<View> uav_view = device->CreateView(uav, uav_view_desc); std::shared_ptr<Shader> library = device->CompileShader({ ASSETS_PATH"shaders/CoreDxrTriangle/RayTracing.hlsl", "", ShaderType::kLibrary, "6_3" }); std::shared_ptr<Shader> library_hit = device->CompileShader({ ASSETS_PATH"shaders/CoreDxrTriangle/RayTracingHit.hlsl", "", ShaderType::kLibrary, "6_3" }); std::shared_ptr<Shader> library_callable = device->CompileShader({ ASSETS_PATH"shaders/CoreDxrTriangle/RayTracingCallable.hlsl", "", ShaderType::kLibrary, "6_3" }); std::shared_ptr<Program> program = device->CreateProgram({ library, library_hit, library_callable }); BindKey geometry_key = library->GetBindKey("geometry"); BindKey result_key = library->GetBindKey("result"); std::shared_ptr<BindingSetLayout> layout = device->CreateBindingSetLayout({ geometry_key, result_key }); std::shared_ptr<BindingSet> binding_set = device->CreateBindingSet(layout); binding_set->WriteBindings({ { geometry_key, top_view }, { result_key, uav_view } }); std::vector<RayTracingShaderGroup> groups; groups.push_back({ RayTracingShaderGroupType::kGeneral, library->GetId("ray_gen") }); groups.push_back({ RayTracingShaderGroupType::kGeneral, library->GetId("miss") }); groups.push_back({ RayTracingShaderGroupType::kTrianglesHitGroup, 0, library_hit->GetId("closest_red") }); groups.push_back({ RayTracingShaderGroupType::kTrianglesHitGroup, 0, library_hit->GetId("closest_green") }); groups.push_back({ RayTracingShaderGroupType::kGeneral, library_callable->GetId("callable") }); std::shared_ptr<Pipeline> pipeline = device->CreateRayTracingPipeline({ program, layout, groups }); std::shared_ptr<Resource> shader_table = device->CreateBuffer(BindFlag::kShaderTable, device->GetShaderTableAlignment() * groups.size()); shader_table->CommitMemory(MemoryType::kUpload); shader_table->SetName("shader_table"); decltype(auto) shader_handles = pipeline->GetRayTracingShaderGroupHandles(0, groups.size()); for (size_t i = 0; i < groups.size(); ++i) { shader_table->UpdateUploadBuffer(i * device->GetShaderTableAlignment(), shader_handles.data() + i * device->GetShaderGroupHandleSize(), device->GetShaderGroupHandleSize()); } RayTracingShaderTables shader_tables = {}; shader_tables.raygen = { shader_table, 0 * device->GetShaderTableAlignment(), device->GetShaderTableAlignment(), device->GetShaderTableAlignment() }; shader_tables.miss = { shader_table, 1 * device->GetShaderTableAlignment(), device->GetShaderTableAlignment(), device->GetShaderTableAlignment() }; shader_tables.hit = { shader_table, 2 * device->GetShaderTableAlignment(), 2 * device->GetShaderTableAlignment(), device->GetShaderTableAlignment() }; shader_tables.callable = { shader_table, 4 * device->GetShaderTableAlignment(), device->GetShaderTableAlignment(), device->GetShaderTableAlignment() }; std::array<uint64_t, frame_count> fence_values = {}; std::vector<std::shared_ptr<CommandList>> command_lists; for (uint32_t i = 0; i < frame_count; ++i) { std::shared_ptr<Resource> back_buffer = swapchain->GetBackBuffer(i); ViewDesc back_buffer_view_desc = {}; back_buffer_view_desc.view_type = ViewType::kRenderTarget; back_buffer_view_desc.dimension = ViewDimension::kTexture2D; std::shared_ptr<View> back_buffer_view = device->CreateView(back_buffer, back_buffer_view_desc); command_lists.emplace_back(device->CreateCommandList(CommandListType::kGraphics)); std::shared_ptr<CommandList> command_list = command_lists[i]; command_list->BindPipeline(pipeline); command_list->BindBindingSet(binding_set); command_list->DispatchRays(shader_tables, rect.width, rect.height, 1); command_list->ResourceBarrier({ { back_buffer, ResourceState::kPresent, ResourceState::kCopyDest } }); command_list->ResourceBarrier({ { uav, ResourceState::kUnorderedAccess, ResourceState::kCopySource } }); command_list->CopyTexture(uav, back_buffer, { { rect.width, rect.height, 1 } }); command_list->ResourceBarrier({ { uav, ResourceState::kCopySource, ResourceState::kUnorderedAccess } }); command_list->ResourceBarrier({ { back_buffer, ResourceState::kCopyDest, ResourceState::kPresent } }); command_list->Close(); } while (!app.PollEvents()) { uint32_t frame_index = swapchain->NextImage(fence, ++fence_value); command_queue->Wait(fence, fence_value); fence->Wait(fence_values[frame_index]); command_queue->ExecuteCommandLists({ command_lists[frame_index] }); command_queue->Signal(fence, fence_values[frame_index] = ++fence_value); swapchain->Present(fence, fence_values[frame_index]); } command_queue->Signal(fence, ++fence_value); fence->Wait(fence_value); return 0; }
13,023
4,226
#include <sstream> #include <boost/tokenizer.hpp> #include "opcode_func.h" #include "BaseDatapath.h" BaseDatapath::BaseDatapath(std::string bench, string trace_file, string config_file, float cycle_t) { benchName = (char*) bench.c_str(); cycleTime = cycle_t; DDDG *dddg; dddg = new DDDG(this, trace_file); /*Build Initial DDDG*/ if (dddg->build_initial_dddg()) { std::cerr << "-------------------------------" << std::endl; std::cerr << " Aladdin Ends.. " << std::endl; std::cerr << "-------------------------------" << std::endl; exit(0); } delete dddg; std::cerr << "-------------------------------" << std::endl; std::cerr << " Initializing BaseDatapath " << std::endl; std::cerr << "-------------------------------" << std::endl; numTotalNodes = microop.size(); BGL_FORALL_VERTICES(v, graph_, Graph) nameToVertex[get(boost::vertex_index, graph_, v)] = v; vertexToName = get(boost::vertex_index, graph_); std::vector<std::string> dynamic_methodid(numTotalNodes, ""); initDynamicMethodID(dynamic_methodid); for (auto dynamic_func_it = dynamic_methodid.begin(), E = dynamic_methodid.end(); dynamic_func_it != E; dynamic_func_it++) { char func_id[256]; int count; sscanf((*dynamic_func_it).c_str(), "%[^-]-%d\n", func_id, &count); if (functionNames.find(func_id) == functionNames.end()) functionNames.insert(func_id); } parse_config(bench, config_file); num_cycles = 0; } BaseDatapath::~BaseDatapath() {} void BaseDatapath::addDddgEdge(unsigned int from, unsigned int to, uint8_t parid) { if (from != to) add_edge(from, to, EdgeProperty(parid), graph_); } //optimizationFunctions void BaseDatapath::setGlobalGraph() { std::cerr << "=============================================" << std::endl; std::cerr << " Optimizing... " << benchName << std::endl; std::cerr << "=============================================" << std::endl; finalIsolated.assign(numTotalNodes, 1); } void BaseDatapath::memoryAmbiguation() { std::cerr << "-------------------------------" << std::endl; std::cerr << " Memory Ambiguation " << std::endl; std::cerr << "-------------------------------" << std::endl; std::unordered_multimap<std::string, std::string> pair_per_load; std::unordered_set<std::string> paired_store; std::unordered_map<std::string, bool> store_load_pair; std::vector<std::string> instid(numTotalNodes, ""); std::vector<std::string> dynamic_methodid(numTotalNodes, ""); std::vector<std::string> prev_basic_block(numTotalNodes, ""); initInstID(instid); initDynamicMethodID(dynamic_methodid); initPrevBasicBlock(prev_basic_block); std::vector< Vertex > topo_nodes; boost::topological_sort(graph_, std::back_inserter(topo_nodes)); //nodes with no incoming edges to first for (auto vi = topo_nodes.rbegin(); vi != topo_nodes.rend(); ++vi) { unsigned node_id = vertexToName[*vi]; int node_microop = microop.at(node_id); if (!is_store_op(node_microop)) continue; //iterate its children to find a load op out_edge_iter out_edge_it, out_edge_end; for (tie(out_edge_it, out_edge_end) = out_edges(*vi, graph_); out_edge_it != out_edge_end; ++out_edge_it) { int child_id = vertexToName[target(*out_edge_it, graph_)]; int child_microop = microop.at(child_id); if (!is_load_op(child_microop)) continue; std::string node_dynamic_methodid = dynamic_methodid.at(node_id); std::string load_dynamic_methodid = dynamic_methodid.at(child_id); if (node_dynamic_methodid.compare(load_dynamic_methodid) != 0) continue; std::string store_unique_id (node_dynamic_methodid + "-" + instid.at(node_id) + "-" + prev_basic_block.at(node_id)); std::string load_unique_id (load_dynamic_methodid+ "-" + instid.at(child_id) + "-" + prev_basic_block.at(child_id)); if (store_load_pair.find(store_unique_id + "-" + load_unique_id ) != store_load_pair.end()) continue; //add to the pair store_load_pair[store_unique_id + "-" + load_unique_id] = 1; paired_store.insert(store_unique_id); auto load_range = pair_per_load.equal_range(load_unique_id); bool found_store = 0; for (auto store_it = load_range.first; store_it != load_range.second; store_it++) { if (store_unique_id.compare(store_it->second) == 0) { found_store = 1; break; } } if (!found_store) { pair_per_load.insert(make_pair(load_unique_id,store_unique_id)); } } } if (store_load_pair.size() == 0) return; std::vector<newEdge> to_add_edges; std::unordered_map<std::string, unsigned> last_store; for (unsigned node_id = 0; node_id < numTotalNodes; node_id++) { int node_microop = microop.at(node_id); if (!is_memory_op(node_microop)) continue; std::string unique_id (dynamic_methodid.at(node_id) + "-" + instid.at(node_id) + "-" + prev_basic_block.at(node_id)); if (is_store_op(node_microop)) { auto store_it = paired_store.find(unique_id); if (store_it == paired_store.end()) continue; last_store[unique_id] = node_id; } else { assert(is_load_op(node_microop)); auto load_range = pair_per_load.equal_range(unique_id); if (std::distance(load_range.first, load_range.second) == 1) continue; for (auto load_store_it = load_range.first; load_store_it != load_range.second; ++load_store_it) { assert(paired_store.find(load_store_it->second) != paired_store.end()); auto prev_store_it = last_store.find(load_store_it->second); if (prev_store_it == last_store.end()) continue; unsigned prev_store_id = prev_store_it->second; if (!doesEdgeExist(prev_store_id, node_id)) { to_add_edges.push_back({prev_store_id, node_id, -1}); dynamicMemoryOps.insert(load_store_it->second + "-" + prev_basic_block.at(prev_store_id)); dynamicMemoryOps.insert(load_store_it->first + "-" + prev_basic_block.at(node_id)); } } } } updateGraphWithNewEdges(to_add_edges); } /* * Read: graph_, microop * Modify: graph_ */ void BaseDatapath::removePhiNodes() { std::cerr << "-------------------------------" << std::endl; std::cerr << " Remove PHI and BitCast Nodes " << std::endl; std::cerr << "-------------------------------" << std::endl; EdgeNameMap edge_to_parid = get(boost::edge_name, graph_); std::set<Edge> to_remove_edges; std::vector<newEdge> to_add_edges; vertex_iter vi, vi_end; int removed_phi = 0; for (tie(vi, vi_end) = vertices(graph_); vi != vi_end; ++vi) { unsigned node_id = vertexToName[*vi]; int node_microop = microop.at(node_id); if (node_microop != LLVM_IR_PHI && node_microop != LLVM_IR_BitCast) continue; //find its children std::vector< pair<unsigned, int> > phi_child; out_edge_iter out_edge_it, out_edge_end; for (tie(out_edge_it, out_edge_end) = out_edges(*vi, graph_); out_edge_it != out_edge_end; ++out_edge_it) { to_remove_edges.insert(*out_edge_it); phi_child.push_back(make_pair(vertexToName[target(*out_edge_it, graph_)], edge_to_parid[*out_edge_it])); } if (phi_child.size() == 0) continue; //find its parents in_edge_iter in_edge_it, in_edge_end; for (tie(in_edge_it, in_edge_end) = in_edges(*vi, graph_); in_edge_it != in_edge_end; ++in_edge_it) { unsigned parent_id = vertexToName[source(*in_edge_it, graph_)]; to_remove_edges.insert(*in_edge_it); for (auto child_it = phi_child.begin(), chil_E = phi_child.end(); child_it != chil_E; ++child_it) to_add_edges.push_back({parent_id, child_it->first, child_it->second}); } std::vector<pair<unsigned, int> >().swap(phi_child); removed_phi++; } updateGraphWithIsolatedEdges(to_remove_edges); updateGraphWithNewEdges(to_add_edges); cleanLeafNodes(); } /* * Read: lineNum.gz, flattenConfig, microop * Modify: graph_ */ void BaseDatapath::loopFlatten() { std::unordered_set<int> flatten_config; if (!readFlattenConfig(flatten_config)) return; std::cerr << "-------------------------------" << std::endl; std::cerr << " Loop Flatten " << std::endl; std::cerr << "-------------------------------" << std::endl; std::vector<int> lineNum(numTotalNodes, -1); initLineNum(lineNum); std::vector<unsigned> to_remove_nodes; for(unsigned node_id = 0; node_id < numTotalNodes; node_id++) { int node_linenum = lineNum.at(node_id); auto it = flatten_config.find(node_linenum); if (it == flatten_config.end()) continue; if (is_compute_op(microop.at(node_id))) microop.at(node_id) = LLVM_IR_Move; else if (is_branch_op(microop.at(node_id))) to_remove_nodes.push_back(node_id); } updateGraphWithIsolatedNodes(to_remove_nodes); cleanLeafNodes(); } void BaseDatapath::cleanLeafNodes() { EdgeNameMap edge_to_parid = get(boost::edge_name, graph_); /*track the number of children each node has*/ std::vector<int> num_of_children(numTotalNodes, 0); std::vector<unsigned> to_remove_nodes; std::vector< Vertex > topo_nodes; boost::topological_sort(graph_, std::back_inserter(topo_nodes)); //bottom nodes first for (auto vi = topo_nodes.begin(); vi != topo_nodes.end(); ++vi) { Vertex node_vertex = *vi; if (boost::degree(node_vertex, graph_) == 0) continue; unsigned node_id = vertexToName[node_vertex]; int node_microop = microop.at(node_id); if (num_of_children.at(node_id) == boost::out_degree(node_vertex, graph_) && node_microop != LLVM_IR_SilentStore && node_microop != LLVM_IR_Store && node_microop != LLVM_IR_Ret && !is_branch_op(node_microop)) { to_remove_nodes.push_back(node_id); //iterate its parents in_edge_iter in_edge_it, in_edge_end; for (tie(in_edge_it, in_edge_end) = in_edges(node_vertex, graph_); in_edge_it != in_edge_end; ++in_edge_it) { int parent_id = vertexToName[source(*in_edge_it, graph_)]; num_of_children.at(parent_id)++; } } else if (is_branch_op(node_microop)) { //iterate its parents in_edge_iter in_edge_it, in_edge_end; for (tie(in_edge_it, in_edge_end) = in_edges(node_vertex, graph_); in_edge_it != in_edge_end; ++in_edge_it) { if (edge_to_parid[*in_edge_it] == CONTROL_EDGE) { int parent_id = vertexToName[source(*in_edge_it, graph_)]; num_of_children.at(parent_id)++; } } } } updateGraphWithIsolatedNodes(to_remove_nodes); } /* * Read: graph_, instid, microop * Modify: microop */ void BaseDatapath::removeInductionDependence() { //set graph std::cerr << "-------------------------------" << std::endl; std::cerr << " Remove Induction Dependence " << std::endl; std::cerr << "-------------------------------" << std::endl; std::vector<std::string> instid(numTotalNodes, ""); initInstID(instid); std::vector< Vertex > topo_nodes; boost::topological_sort(graph_, std::back_inserter(topo_nodes)); //nodes with no incoming edges to first for (auto vi = topo_nodes.rbegin(); vi != topo_nodes.rend(); ++vi) { unsigned node_id = vertexToName[*vi]; std::string node_instid = instid.at(node_id); if (node_instid.find("indvars") == std::string::npos) continue; if (microop.at(node_id) == LLVM_IR_Add ) microop.at(node_id) = LLVM_IR_IndexAdd; } } //called in the end of the whole flow void BaseDatapath::dumpStats() { clearGraph(); dumpGraph(); writeMicroop(microop); writeFinalLevel(); writeGlobalIsolated(); } void BaseDatapath::loopPipelining() { if (!readPipeliningConfig()) { std::cerr << "Loop Pipelining is not ON." << std::endl; return ; } std::unordered_map<int, int > unrolling_config; if (!readUnrollingConfig(unrolling_config)) { std::cerr << "Loop Unrolling is not defined. " << std::endl; std::cerr << "Loop pipelining is only applied to unrolled loops." << std::endl; return ; } if (loopBound.size() <= 2) return; std::cerr << "-------------------------------" << std::endl; std::cerr << " Loop Pipelining " << std::endl; std::cerr << "-------------------------------" << std::endl; EdgeNameMap edge_to_parid = get(boost::edge_name, graph_); vertex_iter vi, vi_end; std::set<Edge> to_remove_edges; std::vector<newEdge> to_add_edges; //After loop unrolling, we define strict control dependences between basic block, //where all the instructions in the following basic block depend on the prev branch instruction //To support loop pipelining, which allows the next iteration //starting without waiting until the prev iteration finish, we move the control dependences //between last branch node in the prev basic block and instructions in the next basic block //to first non isolated instruction in the prev basic block and instructions in the next basic block... std::map<unsigned, unsigned> first_non_isolated_node; auto bound_it = loopBound.begin(); unsigned node_id = *bound_it; //skip first region bound_it++; while ( (unsigned)node_id < numTotalNodes) { assert(is_branch_op(microop.at(*bound_it))); while (node_id < *bound_it && (unsigned) node_id < numTotalNodes) { if (nameToVertex.find(node_id) == nameToVertex.end() || boost::degree(nameToVertex[node_id], graph_) == 0 || is_branch_op(microop.at(node_id)) ) { node_id++; continue; } else { first_non_isolated_node[*bound_it] = node_id; node_id = *bound_it; break; } } if (first_non_isolated_node.find(*bound_it) == first_non_isolated_node.end()) first_non_isolated_node[*bound_it] = *bound_it; bound_it++; if (bound_it == loopBound.end() - 1 ) break; } int prev_branch = -1; int prev_first = -1; for(auto first_it = first_non_isolated_node.begin(), E = first_non_isolated_node.end(); first_it != E; ++first_it) { unsigned br_node = first_it->first; unsigned first_id = first_it->second; if (is_call_op(microop.at(br_node))) { prev_branch = -1; continue; } if (prev_branch != -1) { //adding dependence between prev_first and first_id if (!doesEdgeExist(prev_first, first_id)) to_add_edges.push_back({(unsigned)prev_first, first_id, CONTROL_EDGE}); //adding dependence between first_id and prev_branch's children out_edge_iter out_edge_it, out_edge_end; for (tie(out_edge_it, out_edge_end) = out_edges(nameToVertex[prev_branch], graph_); out_edge_it != out_edge_end; ++out_edge_it) { Vertex child_vertex = target(*out_edge_it, graph_); unsigned child_id = vertexToName[child_vertex]; if (child_id <= first_id || edge_to_parid[*out_edge_it] != CONTROL_EDGE) continue; if (!doesEdgeExist(first_id, child_id)) to_add_edges.push_back({first_id, child_id, 1}); } } //update first_id's parents, dependence become strict control dependence in_edge_iter in_edge_it, in_edge_end; for (tie(in_edge_it, in_edge_end) = in_edges(nameToVertex[first_id], graph_); in_edge_it != in_edge_end; ++in_edge_it) { Vertex parent_vertex = source(*in_edge_it, graph_); unsigned parent_id = vertexToName[parent_vertex]; if (is_branch_op(microop.at(parent_id))) continue; to_remove_edges.insert(*in_edge_it); to_add_edges.push_back({parent_id, first_id, CONTROL_EDGE}); } //remove control dependence between br node to its children out_edge_iter out_edge_it, out_edge_end; for (tie(out_edge_it, out_edge_end) = out_edges(nameToVertex[br_node], graph_); out_edge_it != out_edge_end; ++out_edge_it) { if (is_call_op(microop.at(vertexToName[target(*out_edge_it, graph_)]))) continue; if (edge_to_parid[*out_edge_it] != CONTROL_EDGE) continue; to_remove_edges.insert(*out_edge_it); } prev_branch = br_node; prev_first = first_id; } updateGraphWithIsolatedEdges(to_remove_edges); updateGraphWithNewEdges(to_add_edges); cleanLeafNodes(); } /* * Read: graph_, lineNum.gz, unrollingConfig, microop * Modify: graph_ * Write: loop_bound */ void BaseDatapath::loopUnrolling() { std::unordered_map<int, int > unrolling_config; readUnrollingConfig(unrolling_config); std::cerr << "-------------------------------" << std::endl; std::cerr << " Loop Unrolling " << std::endl; std::cerr << "-------------------------------" << std::endl; std::vector<unsigned> to_remove_nodes; std::unordered_map<std::string, unsigned> inst_dynamic_counts; std::vector<unsigned> nodes_between; std::vector<newEdge> to_add_edges; std::vector<int> lineNum(numTotalNodes, -1); initLineNum(lineNum); bool first = false; int iter_counts = 0; int prev_branch = -1; for(unsigned node_id = 0; node_id < numTotalNodes; node_id++) { if (nameToVertex.find(node_id) == nameToVertex.end()) continue; Vertex node_vertex = nameToVertex[node_id]; if (boost::degree(node_vertex, graph_) == 0 && !is_call_op(microop.at(node_id))) continue; if (!first) { first = true; loopBound.push_back(node_id); prev_branch = node_id; } assert(prev_branch != -1); if (prev_branch != node_id && !(is_dma_op(microop.at(prev_branch)) && is_dma_op(microop.at(node_id))) ) { to_add_edges.push_back({(unsigned)prev_branch, node_id, CONTROL_EDGE}); } if (!is_branch_op(microop.at(node_id))) nodes_between.push_back(node_id); else { //for the case that the first non-isolated node is also a call node; if (is_call_op(microop.at(node_id)) && *loopBound.rbegin() != node_id) { loopBound.push_back(node_id); prev_branch = node_id; } int node_linenum = lineNum.at(node_id); auto unroll_it = unrolling_config.find(node_linenum); //not unrolling branch if (unroll_it == unrolling_config.end()) { if (!is_call_op(microop.at(node_id))) { nodes_between.push_back(node_id); continue; } // Enforce dependences between branch nodes, including call nodes // Except for the case that both two branches are DMA operations. // (Two DMA operations can go in parallel.) if (!doesEdgeExist(prev_branch, node_id) && !( is_dma_op(microop.at(prev_branch)) && is_dma_op(microop.at(node_id)) ) ) to_add_edges.push_back({(unsigned)prev_branch, node_id, CONTROL_EDGE}); for (auto prev_node_it = nodes_between.begin(), E = nodes_between.end(); prev_node_it != E; prev_node_it++) { if (!doesEdgeExist(*prev_node_it, node_id) && !( is_dma_op(microop.at(*prev_node_it)) && is_dma_op(microop.at(node_id)) ) ) { to_add_edges.push_back({*prev_node_it, node_id, CONTROL_EDGE}); } } nodes_between.clear(); nodes_between.push_back(node_id); prev_branch = node_id; } else { int factor = unroll_it->second; int node_microop = microop.at(node_id); char unique_inst_id[256]; sprintf(unique_inst_id, "%d-%d", node_microop, node_linenum); auto it = inst_dynamic_counts.find(unique_inst_id); if (it == inst_dynamic_counts.end()) { inst_dynamic_counts[unique_inst_id] = 1; it = inst_dynamic_counts.find(unique_inst_id); } else it->second++; if (it->second % factor == 0) { loopBound.push_back(node_id); iter_counts++; for (auto prev_node_it = nodes_between.begin(), E = nodes_between.end(); prev_node_it != E; prev_node_it++) { if (!doesEdgeExist(*prev_node_it, node_id)) { to_add_edges.push_back({*prev_node_it, node_id, CONTROL_EDGE}); } } nodes_between.clear(); nodes_between.push_back(node_id); prev_branch = node_id; } else to_remove_nodes.push_back(node_id); } } } loopBound.push_back(numTotalNodes); if (iter_counts == 0 && unrolling_config.size() != 0 ) { std::cerr << "-------------------------------" << std::endl; std::cerr << "Loop Unrolling Factor is Larger than the Loop Trip Count." << std::endl; std::cerr << "Loop Unrolling is NOT applied. Please choose a smaller " << "unrolling factor." << std::endl; std::cerr << "-------------------------------" << std::endl; } updateGraphWithNewEdges(to_add_edges); updateGraphWithIsolatedNodes(to_remove_nodes); cleanLeafNodes(); } /* * Read: loop_bound, flattenConfig, graph, actualAddress, microop * Modify: graph_ */ void BaseDatapath::removeSharedLoads() { std::unordered_set<int> flatten_config; if (!readFlattenConfig(flatten_config)&& loopBound.size() <= 2) return; std::cerr << "-------------------------------" << std::endl; std::cerr << " Load Buffer " << std::endl; std::cerr << "-------------------------------" << std::endl; EdgeNameMap edge_to_parid = get(boost::edge_name, graph_); std::unordered_map<unsigned, long long int> address; initAddress(address); vertex_iter vi, vi_end; std::set<Edge> to_remove_edges; std::vector<newEdge> to_add_edges; int shared_loads = 0; auto bound_it = loopBound.begin(); unsigned node_id = 0; while ( (unsigned)node_id < numTotalNodes) { std::unordered_map<unsigned, unsigned> address_loaded; while (node_id < *bound_it && (unsigned) node_id < numTotalNodes) { if (nameToVertex.find(node_id) == nameToVertex.end()) { node_id++; continue; } if (boost::degree(nameToVertex[node_id], graph_) == 0) { node_id++; continue; } int node_microop = microop.at(node_id); long long int node_address = address[node_id]; auto addr_it = address_loaded.find(node_address); if (is_store_op(node_microop) && addr_it != address_loaded.end()) address_loaded.erase(addr_it); else if (is_load_op(node_microop)) { if (addr_it == address_loaded.end()) address_loaded[node_address] = node_id; else { shared_loads++; microop.at(node_id) = LLVM_IR_Move; unsigned prev_load = addr_it->second; //iterate through its children Vertex load_node = nameToVertex[node_id]; out_edge_iter out_edge_it, out_edge_end; for (tie(out_edge_it, out_edge_end) = out_edges(load_node, graph_); out_edge_it != out_edge_end; ++out_edge_it) { Edge curr_edge = *out_edge_it; Vertex child_vertex = target(curr_edge, graph_); unsigned child_id = vertexToName[child_vertex]; Vertex prev_load_vertex = nameToVertex[prev_load]; if (!doesEdgeExistVertex(prev_load_vertex, child_vertex)) to_add_edges.push_back({prev_load, child_id, edge_to_parid[curr_edge]}); to_remove_edges.insert(*out_edge_it); } in_edge_iter in_edge_it, in_edge_end; for (tie(in_edge_it, in_edge_end) = in_edges(load_node, graph_); in_edge_it != in_edge_end; ++in_edge_it) to_remove_edges.insert(*in_edge_it); } } node_id++; } bound_it++; if (bound_it == loopBound.end() ) break; } updateGraphWithIsolatedEdges(to_remove_edges); updateGraphWithNewEdges(to_add_edges); cleanLeafNodes(); } /* * Read: loopBound, flattenConfig, graph_, instid, dynamicMethodID, * prevBasicBlock * Modify: graph_ */ void BaseDatapath::storeBuffer() { if (loopBound.size() <= 2) return; std::cerr << "-------------------------------" << std::endl; std::cerr << " Store Buffer " << std::endl; std::cerr << "-------------------------------" << std::endl; EdgeNameMap edge_to_parid = get(boost::edge_name, graph_); std::vector<std::string> instid(numTotalNodes, ""); std::vector<std::string> dynamic_methodid(numTotalNodes, ""); std::vector<std::string> prev_basic_block(numTotalNodes, ""); initInstID(instid); initDynamicMethodID(dynamic_methodid); initPrevBasicBlock(prev_basic_block); std::vector<newEdge> to_add_edges; std::vector<unsigned> to_remove_nodes; auto bound_it = loopBound.begin(); unsigned node_id = 0; while (node_id < numTotalNodes) { while (node_id < *bound_it && node_id < numTotalNodes) { if (nameToVertex.find(node_id) == nameToVertex.end() || boost::degree(nameToVertex[node_id], graph_) == 0) { ++node_id; continue; } if (is_store_op(microop.at(node_id))) { //remove this store std::string store_unique_id (dynamic_methodid.at(node_id) + "-" + instid.at(node_id) + "-" + prev_basic_block.at(node_id)); //dynamic stores, cannot disambiguated in the static time, cannot remove if (dynamicMemoryOps.find(store_unique_id) != dynamicMemoryOps.end()) { ++node_id; continue; } Vertex node = nameToVertex[node_id]; out_edge_iter out_edge_it, out_edge_end; std::vector<Vertex> store_child; for (tie(out_edge_it, out_edge_end) = out_edges(node, graph_); out_edge_it != out_edge_end; ++out_edge_it) { Vertex child_vertex = target(*out_edge_it, graph_); int child_id = vertexToName[child_vertex]; if (is_load_op(microop.at(child_id))) { std::string load_unique_id (dynamic_methodid.at(child_id) + "-" + instid.at(child_id) + "-" + prev_basic_block.at(child_id)); if (dynamicMemoryOps.find(load_unique_id) != dynamicMemoryOps.end() || child_id >= (unsigned)*bound_it ) continue; else store_child.push_back(child_vertex); } } if (store_child.size() > 0) { bool parent_found = false; Vertex store_parent; in_edge_iter in_edge_it, in_edge_end; for (tie(in_edge_it, in_edge_end) = in_edges(node, graph_); in_edge_it != in_edge_end; ++in_edge_it) { //parent node that generates value if (edge_to_parid[*in_edge_it] == 1) { parent_found = true; store_parent = source(*in_edge_it, graph_); break; } } if (parent_found) { for (auto load_it = store_child.begin(), E = store_child.end(); load_it != E; ++load_it) { Vertex load_node = *load_it; to_remove_nodes.push_back(vertexToName[load_node]); out_edge_iter out_edge_it, out_edge_end; for (tie(out_edge_it, out_edge_end) = out_edges(load_node, graph_); out_edge_it != out_edge_end; ++out_edge_it) to_add_edges.push_back({(unsigned)vertexToName[store_parent], (unsigned)vertexToName[target(*out_edge_it, graph_)], edge_to_parid[*out_edge_it]}); } } } } ++node_id; } ++bound_it; if (bound_it == loopBound.end() ) break; } updateGraphWithNewEdges(to_add_edges); updateGraphWithIsolatedNodes(to_remove_nodes); cleanLeafNodes(); } /* * Read: loopBound, flattenConfig, graph_, address, instid, dynamicMethodID, * prevBasicBlock * Modify: graph_ */ void BaseDatapath::removeRepeatedStores() { std::unordered_set<int> flatten_config; if (!readFlattenConfig(flatten_config)&& loopBound.size() <= 2) return; std::cerr << "-------------------------------" << std::endl; std::cerr << " Remove Repeated Store " << std::endl; std::cerr << "-------------------------------" << std::endl; std::unordered_map<unsigned, long long int> address; initAddress(address); std::vector<std::string> instid(numTotalNodes, ""); std::vector<std::string> dynamic_methodid(numTotalNodes, ""); std::vector<std::string> prev_basic_block(numTotalNodes, ""); initInstID(instid); initDynamicMethodID(dynamic_methodid); initPrevBasicBlock(prev_basic_block); int shared_stores = 0; int node_id = numTotalNodes - 1; auto bound_it = loopBound.end(); bound_it--; bound_it--; while (node_id >=0 ) { unordered_map<unsigned, int> address_store_map; while (node_id >= *bound_it && node_id >= 0) { if (nameToVertex.find(node_id) == nameToVertex.end() || boost::degree(nameToVertex[node_id], graph_) == 0 || !is_store_op(microop.at(node_id))) { --node_id; continue; } long long int node_address = address[node_id]; auto addr_it = address_store_map.find(node_address); if (addr_it == address_store_map.end()) address_store_map[node_address] = node_id; else { //remove this store std::string store_unique_id (dynamic_methodid.at(node_id) + "-" + instid.at(node_id) + "-" + prev_basic_block.at(node_id)); //dynamic stores, cannot disambiguated in the run time, cannot remove if (dynamicMemoryOps.find(store_unique_id) == dynamicMemoryOps.end() && boost::out_degree(nameToVertex[node_id], graph_)== 0) { microop.at(node_id) = LLVM_IR_SilentStore; shared_stores++; } } --node_id; } if (--bound_it == loopBound.begin()) break; } cleanLeafNodes(); } /* * Read: loopBound, flattenConfig, graph_, microop * Modify: graph_ */ void BaseDatapath::treeHeightReduction() { if (loopBound.size() <= 2) return; std::cerr << "-------------------------------" << std::endl; std::cerr << " Tree Height Reduction " << std::endl; std::cerr << "-------------------------------" << std::endl; EdgeNameMap edge_to_parid = get(boost::edge_name, graph_); std::vector<bool> updated(numTotalNodes, 0); std::vector<int> bound_region(numTotalNodes, 0); int region_id = 0; unsigned node_id = 0; auto bound_it = loopBound.begin(); while (node_id < *bound_it) { bound_region.at(node_id) = region_id; node_id++; if (node_id == *bound_it) { region_id++; bound_it++; if (bound_it == loopBound.end()) break; } } std::set<Edge> to_remove_edges; std::vector<newEdge> to_add_edges; //nodes with no outgoing edges to first (bottom nodes first) for(int node_id = numTotalNodes -1; node_id >= 0; node_id--) { if (nameToVertex.find(node_id) == nameToVertex.end() || boost::degree(nameToVertex[node_id], graph_) == 0 || updated.at(node_id) || !is_associative(microop.at(node_id)) ) continue; updated.at(node_id) = 1; int node_region = bound_region.at(node_id); std::list<unsigned> nodes; std::vector<Edge> tmp_remove_edges; std::vector<pair<int, bool> > leaves; std::vector<int> associative_chain; associative_chain.push_back(node_id); int chain_id = 0; while (chain_id < associative_chain.size()) { int chain_node_id = associative_chain.at(chain_id); int chain_node_microop = microop.at(chain_node_id); if (is_associative(chain_node_microop)) { updated.at(chain_node_id) = 1; int num_of_chain_parents = 0; in_edge_iter in_edge_it, in_edge_end; for (tie(in_edge_it, in_edge_end) = in_edges(nameToVertex[chain_node_id] , graph_); in_edge_it != in_edge_end; ++in_edge_it) { int parent_id = vertexToName[source(*in_edge_it, graph_)]; if (is_branch_op(microop.at(parent_id))) continue; num_of_chain_parents++; } if (num_of_chain_parents == 2) { nodes.push_front(chain_node_id); for (tie(in_edge_it, in_edge_end) = in_edges(nameToVertex[chain_node_id] , graph_); in_edge_it != in_edge_end; ++in_edge_it) { Vertex parent_node = source(*in_edge_it, graph_); int parent_id = vertexToName[parent_node]; assert(parent_id < chain_node_id); int parent_region = bound_region.at(parent_id); int parent_microop = microop.at(parent_id); if (is_branch_op(parent_microop)) continue; Edge curr_edge = *in_edge_it; tmp_remove_edges.push_back(curr_edge); if (parent_region == node_region) { updated.at(parent_id) = 1; if (!is_associative(parent_microop)) leaves.push_back(make_pair(parent_id, 0)); else { out_edge_iter out_edge_it, out_edge_end; int num_of_children = 0; for (tie(out_edge_it, out_edge_end) = out_edges(parent_node, graph_); out_edge_it != out_edge_end; ++out_edge_it) { if (edge_to_parid[*out_edge_it] != CONTROL_EDGE) num_of_children++; } if (num_of_children == 1) associative_chain.push_back(parent_id); else leaves.push_back(make_pair(parent_id, 0)); } } else leaves.push_back(make_pair(parent_id, 1)); } } else leaves.push_back(make_pair(chain_node_id, 0)); } else leaves.push_back(make_pair(chain_node_id, 0)); chain_id++; } //build the tree if (nodes.size() < 3) continue; for(auto it = tmp_remove_edges.begin(), E = tmp_remove_edges.end(); it != E; it++) to_remove_edges.insert(*it); std::map<unsigned, unsigned> rank_map; auto leaf_it = leaves.begin(); while (leaf_it != leaves.end()) { if (leaf_it->second == 0) rank_map[leaf_it->first] = 0; else rank_map[leaf_it->first] = numTotalNodes; ++leaf_it; } //reconstruct the rest of the balanced tree auto node_it = nodes.begin(); while (node_it != nodes.end()) { unsigned node1, node2; if (rank_map.size() == 2) { node1 = rank_map.begin()->first; node2 = (++rank_map.begin())->first; } else findMinRankNodes(node1, node2, rank_map); assert((node1 != numTotalNodes) && (node2 != numTotalNodes)); to_add_edges.push_back({node1, *node_it, 1}); to_add_edges.push_back({node2, *node_it, 1}); //place the new node in the map, remove the two old nodes rank_map[*node_it] = max(rank_map[node1], rank_map[node2]) + 1; rank_map.erase(node1); rank_map.erase(node2); ++node_it; } } updateGraphWithIsolatedEdges(to_remove_edges); updateGraphWithNewEdges(to_add_edges); cleanLeafNodes(); } void BaseDatapath::findMinRankNodes(unsigned &node1, unsigned &node2, std::map<unsigned, unsigned> &rank_map) { unsigned min_rank = numTotalNodes; for (auto it = rank_map.begin(); it != rank_map.end(); ++it) { int node_rank = it->second; if (node_rank < min_rank) { node1 = it->first; min_rank = node_rank; } } min_rank = numTotalNodes; for (auto it = rank_map.begin(); it != rank_map.end(); ++it) { int node_rank = it->second; if ((it->first != node1) && (node_rank < min_rank)) { node2 = it->first; min_rank = node_rank; } } } void BaseDatapath::updateGraphWithNewEdges(std::vector<newEdge> &to_add_edges) { for(auto it = to_add_edges.begin(); it != to_add_edges.end(); ++it) { if (it->from != it->to && !doesEdgeExist(it->from, it->to)) get(boost::edge_name, graph_)[add_edge(it->from, it->to, graph_).first] = it->parid; } } void BaseDatapath::updateGraphWithIsolatedNodes(std::vector<unsigned> &to_remove_nodes) { for(auto it = to_remove_nodes.begin(); it != to_remove_nodes.end(); ++it) clear_vertex(nameToVertex[*it], graph_); } void BaseDatapath::updateGraphWithIsolatedEdges(std::set<Edge> &to_remove_edges) { for (auto it = to_remove_edges.begin(), E = to_remove_edges.end(); it!=E; ++it) remove_edge(*it, graph_); } /* * Write per cycle activity to bench_stats. The format is: * cycle_num,num-of-muls,num-of-adds,num-of-bitwise-ops,num-of-reg-reads,num-of-reg-writes * If it is called from ScratchpadDatapath, it also outputs per cycle memory * activity for each partitioned array. */ void BaseDatapath::writePerCycleActivity() { std::string bn(benchName); activity_map mul_activity, add_activity, bit_activity; activity_map ld_activity, st_activity; max_activity_map max_mul_per_function; max_activity_map max_add_per_function; max_activity_map max_bit_per_function; std::vector<std::string> comp_partition_names; std::vector<std::string> mem_partition_names; registers.getRegisterNames(comp_partition_names); getMemoryBlocks(mem_partition_names); initPerCycleActivity(comp_partition_names, mem_partition_names, ld_activity, st_activity, mul_activity, add_activity, bit_activity, max_mul_per_function, max_add_per_function, max_bit_per_function, num_cycles); updatePerCycleActivity(ld_activity, st_activity, mul_activity, add_activity, bit_activity, max_mul_per_function, max_add_per_function, max_bit_per_function); outputPerCycleActivity(comp_partition_names, mem_partition_names, ld_activity, st_activity, mul_activity, add_activity, bit_activity, max_mul_per_function, max_add_per_function, max_bit_per_function); } void BaseDatapath::initPerCycleActivity( std::vector<std::string> &comp_partition_names, std::vector<std::string> &mem_partition_names, activity_map &ld_activity, activity_map &st_activity, activity_map &mul_activity, activity_map &add_activity, activity_map &bit_activity, max_activity_map &max_mul_per_function, max_activity_map &max_add_per_function, max_activity_map &max_bit_per_function, int num_cycles) { for (auto it = comp_partition_names.begin(); it != comp_partition_names.end() ; ++it) { ld_activity.insert({*it, make_vector(num_cycles)}); st_activity.insert({*it, make_vector(num_cycles)}); } for (auto it = mem_partition_names.begin(); it != mem_partition_names.end() ; ++it) { ld_activity.insert({*it, make_vector(num_cycles)}); st_activity.insert({*it, make_vector(num_cycles)}); } for (auto it = functionNames.begin(); it != functionNames.end() ; ++it) { mul_activity.insert({*it, make_vector(num_cycles)}); add_activity.insert({*it, make_vector(num_cycles)}); bit_activity.insert({*it, make_vector(num_cycles)}); max_mul_per_function.insert({*it, 0}); max_add_per_function.insert({*it, 0}); max_bit_per_function.insert({*it, 0}); } } void BaseDatapath::updatePerCycleActivity( activity_map &ld_activity, activity_map &st_activity, activity_map &mul_activity, activity_map &add_activity, activity_map &bit_activity, max_activity_map &max_mul_per_function, max_activity_map &max_add_per_function, max_activity_map &max_bit_per_function) { /*We use two ways to count the number of functional units in accelerators: one * assumes that functional units can be reused in the same region; the other * assumes no reuse of functional units. The advantage of reusing is that it * elimates the cost of duplicating functional units which can lead to high * leakage power and area. However, additional wires and muxes may need to be * added for reusing. * In the current model, we assume that multipliers can be reused, since the * leakage power and area of multipliers are relatively significant, and no * reuse for adders. This way of modeling is consistent with our observation * of accelerators generated with Vivado.*/ std::vector<std::string> dynamic_methodid(numTotalNodes, ""); initDynamicMethodID(dynamic_methodid); int num_adds_so_far = 0, num_bits_so_far = 0; auto bound_it = loopBound.begin(); for(unsigned node_id = 0; node_id < numTotalNodes; ++node_id) { char func_id[256]; int count; sscanf(dynamic_methodid.at(node_id).c_str(), "%[^-]-%d\n", func_id, &count); if (node_id == *bound_it) { if (max_add_per_function[func_id] < num_adds_so_far) max_add_per_function[func_id] = num_adds_so_far; if (max_bit_per_function[func_id] < num_bits_so_far) max_bit_per_function[func_id] = num_bits_so_far; num_adds_so_far = 0; num_bits_so_far = 0; bound_it++; } if (finalIsolated.at(node_id)) continue; int node_level = newLevel.at(node_id); int node_microop = microop.at(node_id); if (is_mul_op(node_microop)) mul_activity[func_id].at(node_level) +=1; else if (is_add_op(node_microop)) { add_activity[func_id].at(node_level) +=1; num_adds_so_far +=1; } else if (is_bit_op(node_microop)) { bit_activity[func_id].at(node_level) +=1; num_bits_so_far +=1; } else if (is_load_op(node_microop)) { std::string base_addr = baseAddress[node_id].first; if (ld_activity.find(base_addr) != ld_activity.end()) ld_activity[base_addr].at(node_level) += 1; } else if (is_store_op(node_microop)) { std::string base_addr = baseAddress[node_id].first; if (st_activity.find(base_addr) != st_activity.end()) st_activity[base_addr].at(node_level) += 1; } } for (auto it = functionNames.begin(); it != functionNames.end() ; ++it) max_mul_per_function[*it] = *(std::max_element(mul_activity[*it].begin(), mul_activity[*it].end())); } void BaseDatapath::outputPerCycleActivity( std::vector<std::string> &comp_partition_names, std::vector<std::string> &mem_partition_names, activity_map &ld_activity, activity_map &st_activity, activity_map &mul_activity, activity_map &add_activity, activity_map &bit_activity, max_activity_map &max_mul_per_function, max_activity_map &max_add_per_function, max_activity_map &max_bit_per_function) { ofstream stats, power_stats; std::string bn(benchName); std::string file_name = bn + "_stats"; stats.open(file_name.c_str()); file_name += "_power"; power_stats.open(file_name.c_str()); stats << "cycles," << num_cycles << "," << numTotalNodes << std::endl; power_stats << "cycles," << num_cycles << "," << numTotalNodes << std::endl; stats << num_cycles << "," ; power_stats << num_cycles << "," ; /*Start writing the second line*/ for (auto it = functionNames.begin(); it != functionNames.end() ; ++it) { stats << *it << "-mul," << *it << "-add," << *it << "-bit,"; power_stats << *it << "-mul," << *it << "-add," << *it << "-bit,"; } stats << "reg,"; power_stats << "reg,"; for (auto it = mem_partition_names.begin(); it != mem_partition_names.end() ; ++it) { stats << *it << "-read," << *it << "-write,"; } stats << std::endl; power_stats << std::endl; /*Finish writing the second line*/ /*Caculating the number of FUs and leakage power*/ int max_reg_read = 0, max_reg_write = 0; for (unsigned level_id = 0; ((int) level_id) < num_cycles; ++level_id) { if (max_reg_read < regStats.at(level_id).reads ) max_reg_read = regStats.at(level_id).reads ; if (max_reg_write < regStats.at(level_id).writes ) max_reg_write = regStats.at(level_id).writes ; } int max_reg = max_reg_read + max_reg_write; int max_add = 0, max_bit = 0, max_mul = 0; for (auto it = functionNames.begin(); it != functionNames.end() ; ++it) { max_bit += max_bit_per_function[*it]; max_add += max_add_per_function[*it]; max_mul += max_mul_per_function[*it]; } float add_leakage_power = ADD_leak_power * max_add; float mul_leakage_power = MUL_leak_power * max_mul; float reg_leakage_power = registers.getTotalLeakagePower() + REG_leak_power * 32 * max_reg; float fu_leakage_power = mul_leakage_power + add_leakage_power + reg_leakage_power; /*Finish caculating the number of FUs and leakage power*/ float fu_dynamic_energy = 0; /*Start writing per cycle activity */ for (unsigned curr_level = 0; ((int)curr_level) < num_cycles ; ++curr_level) { stats << curr_level << "," ; power_stats << curr_level << ","; //For FUs for (auto it = functionNames.begin(); it != functionNames.end() ; ++it) { float curr_mul_dynamic_power = (MUL_switch_power + MUL_int_power) * mul_activity[*it].at(curr_level); float curr_add_dynamic_power = (ADD_switch_power + ADD_int_power) * add_activity[*it].at(curr_level); fu_dynamic_energy += ( curr_mul_dynamic_power + curr_add_dynamic_power ) * cycleTime; stats << mul_activity[*it].at(curr_level) << "," << add_activity[*it].at(curr_level) << "," << bit_activity[*it].at(curr_level) << ","; power_stats << curr_mul_dynamic_power + mul_leakage_power << "," << curr_add_dynamic_power + add_leakage_power << "," << "0," ; } //For regs int curr_reg_reads = regStats.at(curr_level).reads; int curr_reg_writes = regStats.at(curr_level).writes; float curr_reg_dynamic_energy = (REG_int_power + REG_sw_power) *(curr_reg_reads + curr_reg_writes) * 32 * cycleTime; for (auto it = comp_partition_names.begin(); it != comp_partition_names.end() ; ++it) { curr_reg_reads += ld_activity.at(*it).at(curr_level); curr_reg_writes += st_activity.at(*it).at(curr_level); curr_reg_dynamic_energy += registers.getReadEnergy(*it) * ld_activity.at(*it).at(curr_level) + registers.getWriteEnergy(*it) * st_activity.at(*it).at(curr_level); } fu_dynamic_energy += curr_reg_dynamic_energy; stats << curr_reg_reads << "," << curr_reg_writes << "," ; power_stats << curr_reg_dynamic_energy / cycleTime + reg_leakage_power; for (auto it = mem_partition_names.begin(); it != mem_partition_names.end() ; ++it) stats << ld_activity.at(*it).at(curr_level) << "," << st_activity.at(*it).at(curr_level) << ","; stats << std::endl; power_stats << std::endl; } stats.close(); power_stats.close(); float avg_mem_power =0, avg_mem_dynamic_power = 0, mem_leakage_power = 0; getAverageMemPower(num_cycles, &avg_mem_power, &avg_mem_dynamic_power, &mem_leakage_power); float avg_fu_dynamic_power = fu_dynamic_energy / (cycleTime * num_cycles); float avg_fu_power = avg_fu_dynamic_power + fu_leakage_power; float avg_power = avg_fu_power + avg_mem_power; float mem_area = getTotalMemArea(); unsigned mem_size = getTotalMemSize(); float fu_area = registers.getTotalArea() + ADD_area * max_add + MUL_area * max_mul + REG_area * 32 * max_reg; float total_area = mem_area + fu_area; //Summary output: //Cycle, Avg Power, Avg FU Power, Avg MEM Power, Total Area, FU Area, MEM Area std::cerr << "===============================" << std::endl; std::cerr << " Aladdin Results " << std::endl; std::cerr << "===============================" << std::endl; std::cerr << "Running : " << benchName << std::endl; std::cerr << "Cycle : " << num_cycles << " cycles" << std::endl; std::cerr << "Avg Power: " << avg_power << " mW" << std::endl; std::cerr << "Avg FU Power: " << avg_fu_power << " mW" << std::endl; std::cerr << "Avg FU Dynamic Power: " << avg_fu_dynamic_power << " mW" << std::endl; std::cerr << "Avg FU leakage Power: " << fu_leakage_power << " mW" << std::endl; std::cerr << "Avg SRAM Power: " << avg_mem_power << " mW" << std::endl; std::cerr << "Avg SRAM Dynamic Power: " << avg_mem_dynamic_power << " mW" << std::endl; std::cerr << "Avg SRAM Leakage Power: " << mem_leakage_power << " mW" << std::endl; std::cerr << "Total Area: " << total_area << " uM^2" << std::endl; std::cerr << "FU Area: " << fu_area << " uM^2" << std::endl; std::cerr << "SRAM Area: " << mem_area << " uM^2" << std::endl; std::cerr << "SRAM size: " << mem_size / 1024 << " KB" << std::endl; std::cerr << "Num of Multipliers (32-bit): " << max_mul << std::endl; std::cerr << "Num of Adders (32-bit): " << max_add << std::endl; std::cerr << "===============================" << std::endl; std::cerr << " Aladdin Results " << std::endl; std::cerr << "===============================" << std::endl; ofstream summary; file_name = bn + "_summary"; summary.open(file_name.c_str()); summary << "===============================" << std::endl; summary << " Aladdin Results " << std::endl; summary << "===============================" << std::endl; summary << "Running : " << benchName << std::endl; summary << "Cycle : " << num_cycles << " cycles" << std::endl; summary << "Avg Power: " << avg_power << " mW" << std::endl; summary << "Avg FU Power: " << avg_fu_power << " mW" << std::endl; summary << "Avg FU Dynamic Power: " << avg_fu_dynamic_power << " mW" << std::endl; summary << "Avg FU leakage Power: " << fu_leakage_power << " mW" << std::endl; summary << "Avg SRAM Power: " << avg_mem_power << " mW" << std::endl; summary << "Avg SRAM Dynamic Power: " << avg_mem_dynamic_power << " mW" << std::endl; summary << "Avg SRAM Leakage Power: " << mem_leakage_power << " mW" << std::endl; summary << "Total Area: " << total_area << " uM^2" << std::endl; summary << "FU Area: " << fu_area << " uM^2" << std::endl; summary << "SRAM Area: " << mem_area << " uM^2" << std::endl; summary << "SRAM size: " << mem_size << " B" << std::endl; summary << "Num of Multipliers (32-bit): " << max_mul << std::endl; summary << "Num of Adders (32-bit): " << max_add << std::endl; summary << "===============================" << std::endl; summary << " Aladdin Results " << std::endl; summary << "===============================" << std::endl; summary.close(); } void BaseDatapath::writeGlobalIsolated() { std::string file_name(benchName); file_name += "_isolated.gz"; write_gzip_bool_file(file_name, finalIsolated.size(), finalIsolated); } void BaseDatapath::writeBaseAddress() { ostringstream file_name; file_name << benchName << "_baseAddr.gz"; gzFile gzip_file; gzip_file = gzopen(file_name.str().c_str(), "w"); for (auto it = baseAddress.begin(), E = baseAddress.end(); it != E; ++it) gzprintf(gzip_file, "node:%u,part:%s,base:%lld\n", it->first, it->second.first.c_str(), it->second.second); gzclose(gzip_file); } void BaseDatapath::writeFinalLevel() { std::string file_name(benchName); file_name += "_level.gz"; write_gzip_file(file_name, newLevel.size(), newLevel); } void BaseDatapath::writeMicroop(std::vector<int> &microop) { std::string file_name(benchName); file_name += "_microop.gz"; write_gzip_file(file_name, microop.size(), microop); } void BaseDatapath::initPrevBasicBlock(std::vector<std::string> &prevBasicBlock) { std::string file_name(benchName); file_name += "_prevBasicBlock.gz"; read_gzip_string_file(file_name, prevBasicBlock.size(), prevBasicBlock); } void BaseDatapath::initDynamicMethodID(std::vector<std::string> &methodid) { std::string file_name(benchName); file_name += "_dynamic_funcid.gz"; read_gzip_string_file(file_name, methodid.size(), methodid); } void BaseDatapath::initMethodID(std::vector<int> &methodid) { std::string file_name(benchName); file_name += "_methodid.gz"; read_gzip_file(file_name, methodid.size(), methodid); } void BaseDatapath::initInstID(std::vector<std::string> &instid) { std::string file_name(benchName); file_name += "_instid.gz"; read_gzip_string_file(file_name, instid.size(), instid); } void BaseDatapath::initAddress(std::unordered_map<unsigned, long long int> &address) { std::string file_name(benchName); file_name += "_memaddr.gz"; gzFile gzip_file; gzip_file = gzopen(file_name.c_str(), "r"); while (!gzeof(gzip_file)) { char buffer[256]; if (gzgets(gzip_file, buffer, 256) == NULL) break; unsigned node_id, size; long long int addr; sscanf(buffer, "%d,%lld,%d\n", &node_id, &addr, &size); address[node_id] = addr; } gzclose(gzip_file); } void BaseDatapath::initAddressAndSize(std::unordered_map<unsigned, pair<long long int, unsigned> > &address) { std::string file_name(benchName); file_name += "_memaddr.gz"; gzFile gzip_file; gzip_file = gzopen(file_name.c_str(), "r"); while (!gzeof(gzip_file)) { char buffer[256]; if (gzgets(gzip_file, buffer, 256) == NULL) break; unsigned node_id, size; long long int addr; sscanf(buffer, "%d,%lld,%d\n", &node_id, &addr, &size); address[node_id] = make_pair(addr, size); } gzclose(gzip_file); } void BaseDatapath::initLineNum(std::vector<int> &line_num) { ostringstream file_name; file_name << benchName << "_linenum.gz"; read_gzip_file(file_name.str(), line_num.size(), line_num); } void BaseDatapath::initGetElementPtr(std::unordered_map<unsigned, pair<std::string, long long int> > &get_element_ptr) { ostringstream file_name; file_name << benchName << "_getElementPtr.gz"; gzFile gzip_file; gzip_file = gzopen(file_name.str().c_str(), "r"); while (!gzeof(gzip_file)) { char buffer[256]; if (gzgets(gzip_file, buffer, 256) == NULL) break; unsigned node_id; long long int address; char label[256]; sscanf(buffer, "%d,%[^,],%lld\n", &node_id, label, &address); get_element_ptr[node_id] = make_pair(label, address); } gzclose(gzip_file); } //stepFunctions //multiple function, each function is a separate graph void BaseDatapath::setGraphForStepping() { std::cerr << "=============================================" << std::endl; std::cerr << " Scheduling... " << benchName << std::endl; std::cerr << "=============================================" << std::endl; newLevel.assign(numTotalNodes, 0); edgeToParid = get(boost::edge_name, graph_); numTotalEdges = boost::num_edges(graph_); numParents.assign(numTotalNodes, 0); latestParents.assign(numTotalNodes, 0); executedNodes = 0; totalConnectedNodes = 0; for (unsigned node_id = 0; node_id < numTotalNodes; node_id++) { Vertex node = nameToVertex[node_id]; if (boost::degree(node, graph_) != 0 || is_dma_op(microop.at(node_id))) { finalIsolated.at(node_id) = 0; numParents.at(node_id) = boost::in_degree(node, graph_); totalConnectedNodes++; } } executingQueue.clear(); readyToExecuteQueue.clear(); initExecutingQueue(); } void BaseDatapath::dumpGraph() { std::string bn(benchName); std::ofstream out(bn + "_graph.dot"); write_graphviz(out, graph_); } int BaseDatapath::clearGraph() { std::vector< Vertex > topo_nodes; boost::topological_sort(graph_, std::back_inserter(topo_nodes)); //bottom nodes first std::vector<int> earliest_child(numTotalNodes, num_cycles); for (auto vi = topo_nodes.begin(); vi != topo_nodes.end(); ++vi) { unsigned node_id = vertexToName[*vi]; if (finalIsolated.at(node_id)) continue; unsigned node_microop = microop.at(node_id); if (!is_memory_op(node_microop) && ! is_branch_op(node_microop)) if ((earliest_child.at(node_id) - 1 ) > newLevel.at(node_id)) newLevel.at(node_id) = earliest_child.at(node_id) - 1; in_edge_iter in_i, in_end; for (tie(in_i, in_end) = in_edges(*vi , graph_); in_i != in_end; ++in_i) { int parent_id = vertexToName[source(*in_i, graph_)]; if (earliest_child.at(parent_id) > newLevel.at(node_id)) earliest_child.at(parent_id) = newLevel.at(node_id); } } updateRegStats(); return num_cycles; } void BaseDatapath::updateRegStats() { regStats.assign(num_cycles, {0, 0, 0}); for(unsigned node_id = 0; node_id < numTotalNodes; node_id++) { if (finalIsolated.at(node_id)) continue; if (is_control_op(microop.at(node_id)) || is_index_op(microop.at(node_id))) continue; int node_level = newLevel.at(node_id); int max_children_level = node_level; Vertex node = nameToVertex[node_id]; out_edge_iter out_edge_it, out_edge_end; std::set<int> children_levels; for (tie(out_edge_it, out_edge_end) = out_edges(node, graph_); out_edge_it != out_edge_end; ++out_edge_it) { int child_id = vertexToName[target(*out_edge_it, graph_)]; int child_microop = microop.at(child_id); if (is_control_op(child_microop)) continue; if (is_load_op(child_microop)) continue; int child_level = newLevel.at(child_id); if (child_level > max_children_level) max_children_level = child_level; if (child_level > node_level && child_level != num_cycles - 1) children_levels.insert(child_level); } for (auto it = children_levels.begin(); it != children_levels.end(); it++) regStats.at(*it).reads++; if (max_children_level > node_level && node_level != 0 ) regStats.at(node_level).writes++; } } void BaseDatapath::copyToExecutingQueue() { auto it = readyToExecuteQueue.begin(); while (it != readyToExecuteQueue.end()) { executingQueue.push_back(*it); it = readyToExecuteQueue.erase(it); } } bool BaseDatapath::step() { stepExecutingQueue(); copyToExecutingQueue(); num_cycles++; if (executedNodes == totalConnectedNodes) return 1; return 0; } // Marks a node as completed and advances the executing queue iterator. void BaseDatapath::markNodeCompleted( std::vector<unsigned>::iterator& executingQueuePos, int& advance_to) { unsigned node_id = *executingQueuePos; executedNodes++; newLevel.at(node_id) = num_cycles; executingQueue.erase(executingQueuePos); updateChildren(node_id); executingQueuePos = executingQueue.begin(); std::advance(executingQueuePos, advance_to); } void BaseDatapath::updateChildren(unsigned node_id) { Vertex node = nameToVertex[node_id]; out_edge_iter out_edge_it, out_edge_end; for (tie(out_edge_it, out_edge_end) = out_edges(node, graph_); out_edge_it != out_edge_end; ++out_edge_it) { unsigned child_id = vertexToName[target(*out_edge_it, graph_)]; int edge_parid = edgeToParid[*out_edge_it]; if (numParents[child_id] > 0) { numParents[child_id]--; if (numParents[child_id] == 0) { unsigned child_microop = microop.at(child_id); if ( (node_latency(child_microop) == 0 || node_latency(microop.at(node_id))== 0) && edge_parid != CONTROL_EDGE ) executingQueue.push_back(child_id); else readyToExecuteQueue.push_back(child_id); numParents[child_id] = -1; } } } } void BaseDatapath::initExecutingQueue() { for(unsigned i = 0; i < numTotalNodes; i++) { if (numParents[i] == 0 && finalIsolated[i] != 1) executingQueue.push_back(i); } } int BaseDatapath::shortestDistanceBetweenNodes(unsigned int from, unsigned int to) { std::list<pair<unsigned int, unsigned int> > queue; queue.push_back({from, 0}); while(queue.size() != 0) { unsigned int curr_node = queue.front().first; unsigned int curr_dist = queue.front().second; out_edge_iter out_edge_it, out_edge_end; for (tie(out_edge_it, out_edge_end) = out_edges(nameToVertex[curr_node], graph_); out_edge_it != out_edge_end; ++out_edge_it) { if (get(boost::edge_name, graph_, *out_edge_it) != CONTROL_EDGE) { int child_id = vertexToName[target(*out_edge_it, graph_)]; if (child_id == to) return curr_dist + 1; queue.push_back({child_id, curr_dist + 1}); } } queue.pop_front(); } return -1; } //readConfigs bool BaseDatapath::readPipeliningConfig() { ifstream config_file; std::string file_name(benchName); file_name += "_pipelining_config"; config_file.open(file_name.c_str()); if (!config_file.is_open()) return 0; std::string wholeline; getline(config_file, wholeline); if (wholeline.size() == 0) return 0; bool flag = atoi(wholeline.c_str()); return flag; } bool BaseDatapath::readUnrollingConfig(std::unordered_map<int, int > &unrolling_config) { ifstream config_file; std::string file_name(benchName); file_name += "_unrolling_config"; config_file.open(file_name.c_str()); if (!config_file.is_open()) return 0; while(!config_file.eof()) { std::string wholeline; getline(config_file, wholeline); if (wholeline.size() == 0) break; char func[256]; int line_num, factor; sscanf(wholeline.c_str(), "%[^,],%d,%d\n", func, &line_num, &factor); unrolling_config[line_num] =factor; } config_file.close(); return 1; } bool BaseDatapath::readFlattenConfig(std::unordered_set<int> &flatten_config) { ifstream config_file; std::string file_name(benchName); file_name += "_flatten_config"; config_file.open(file_name.c_str()); if (!config_file.is_open()) return 0; while(!config_file.eof()) { std::string wholeline; getline(config_file, wholeline); if (wholeline.size() == 0) break; char func[256]; int line_num; sscanf(wholeline.c_str(), "%[^,],%d\n", func, &line_num); flatten_config.insert(line_num); } config_file.close(); return 1; } bool BaseDatapath::readCompletePartitionConfig(std::unordered_map<std::string, unsigned> &config) { std::string comp_partition_file(benchName); comp_partition_file += "_complete_partition_config"; if (!fileExists(comp_partition_file)) return 0; ifstream config_file; config_file.open(comp_partition_file); std::string wholeline; while(!config_file.eof()) { getline(config_file, wholeline); if (wholeline.size() == 0) break; unsigned size; char type[256]; char base_addr[256]; sscanf(wholeline.c_str(), "%[^,],%[^,],%d\n", type, base_addr, &size); config[base_addr] = size; } config_file.close(); return 1; } bool BaseDatapath::readPartitionConfig(std::unordered_map<std::string, partitionEntry> & partition_config) { ifstream config_file; std::string file_name(benchName); file_name += "_partition_config"; if (!fileExists(file_name)) return 0; config_file.open(file_name.c_str()); std::string wholeline; while (!config_file.eof()) { getline(config_file, wholeline); if (wholeline.size() == 0) break; unsigned size, p_factor, wordsize; char type[256]; char base_addr[256]; sscanf(wholeline.c_str(), "%[^,],%[^,],%d,%d,%d\n", type, base_addr, &size, &wordsize, &p_factor); std::string p_type(type); partition_config[base_addr] = {p_type, size, wordsize, p_factor}; } config_file.close(); return 1; } void BaseDatapath::parse_config(std::string bench, std::string config_file_name) { ifstream config_file; config_file.open(config_file_name); std::string wholeline; std::vector<std::string> flatten_config; std::vector<std::string> unrolling_config; std::vector<std::string> partition_config; std::vector<std::string> comp_partition_config; std::vector<std::string> pipelining_config; while(!config_file.eof()) { wholeline.clear(); getline(config_file, wholeline); if (wholeline.size() == 0) break; string type, rest_line; int pos_end_tag = wholeline.find(","); if (pos_end_tag == -1) break; type = wholeline.substr(0, pos_end_tag); rest_line = wholeline.substr(pos_end_tag + 1); if (!type.compare("flatten")) flatten_config.push_back(rest_line); else if (!type.compare("unrolling")) unrolling_config.push_back(rest_line); else if (!type.compare("partition")) if (wholeline.find("complete") == std::string::npos) partition_config.push_back(rest_line); else comp_partition_config.push_back(rest_line); else if (!type.compare("pipelining")) pipelining_config.push_back(rest_line); else { cerr << "what else? " << wholeline << endl; exit(0); } } config_file.close(); if (flatten_config.size() != 0) { string file_name(bench); file_name += "_flatten_config"; ofstream output; output.open(file_name); for (unsigned i = 0; i < flatten_config.size(); ++i) output << flatten_config.at(i) << endl; output.close(); } if (unrolling_config.size() != 0) { string file_name(bench); file_name += "_unrolling_config"; ofstream output; output.open(file_name); for (unsigned i = 0; i < unrolling_config.size(); ++i) output << unrolling_config.at(i) << endl; output.close(); } if (pipelining_config.size() != 0) { string pipelining(bench); pipelining += "_pipelining_config"; ofstream pipe_config; pipe_config.open(pipelining); for (unsigned i = 0; i < pipelining_config.size(); ++i) pipe_config << pipelining_config.at(i) << endl; pipe_config.close(); } if (partition_config.size() != 0) { string partition(bench); partition += "_partition_config"; ofstream part_config; part_config.open(partition); for (unsigned i = 0; i < partition_config.size(); ++i) part_config << partition_config.at(i) << endl; part_config.close(); } if (comp_partition_config.size() != 0) { string complete_partition(bench); complete_partition += "_complete_partition_config"; ofstream comp_config; comp_config.open(complete_partition); for (unsigned i = 0; i < comp_partition_config.size(); ++i) comp_config << comp_partition_config.at(i) << endl; comp_config.close(); } } /* Tokenizes an input string and returns a vector. */ void BaseDatapath::tokenizeString(std::string input, std::vector<int>& tokenized_list) { using namespace boost; tokenizer<> tok(input); for(tokenizer<>::iterator beg = tok.begin(); beg != tok.end(); ++beg) { int value; istringstream(*beg) >> value; tokenized_list.push_back(value); } }
67,124
23,955
#include <bits/stdc++.h> using namespace std; int solution(vector<vector<int> > land) { ios_base::sync_with_stdio(false); for (int i = 1; i < land.size(); i++) { land[i][0] += max(land[i-1][1], max(land[i-1][2], land[i-1][3])); land[i][1] += max(land[i-1][0], max(land[i-1][2], land[i-1][3])); land[i][2] += max(land[i-1][0], max(land[i-1][1], land[i-1][3])); land[i][3] += max(land[i-1][1], max(land[i-1][2], land[i-1][0])); } return max(max(land[land.size()-1][0], land[land.size()-1][1]), max(land[land.size()-1][2], land[land.size()-1][3])); }
595
275
/* * Abstract Nonlinear Least-Squares Solver Class * * nlls_solver.h * * Created on: Nov 5, 2012 * Author: cforster */ #ifndef LM_SOLVER_IMPL_HPP_ #define LM_SOLVER_IMPL_HPP_ #include <stdexcept> template <int D, typename T> void vk::NLLSSolver<D, T>::optimize(ModelType& model) { if(method_ == GaussNewton) optimizeGaussNewton(); else if(method_ == LevenbergMarquardt) optimizeLevenbergMarquardt(model); } template <int D, typename T> void vk::NLLSSolver<D, T>::optimizeGaussNewton() { // Compute weight scale if(use_weights_) computeResiduals(false, true); // perform iterative estimation for (iter_ = 0; iter_<n_iter_; ++iter_) { rho_ = 0; n_meas_ = 0; double new_chi2 = computeResiduals(true, false); // solve the linear system if(!solve()) { // matrix was singular and could not be computed if(verbose_)std::cerr << "Matrix is close to singular! Stop Optimizing." << std::endl; stop_ = true; } // check if error increased since last optimization if((iter_ > 0 && new_chi2 > chi2_) || stop_) { if(verbose_) { std::cerr << "It. " << iter_ << "\t Failure" << "\t new_chi2 = " << new_chi2 << "\t Error increased. Stop optimizing.\n"; } break; } // update the model update(); chi2_ = new_chi2; if(verbose_) { std::cerr << "It. " << iter_ << "\t Success" << "\t new_chi2 = " << new_chi2 << "\t x_norm = " << vk::norm_max(x_)<<'\n'; } // stop when converged, i.e. update step too small if(vk::norm_max(x_)<=eps_) break; } } template <int D, typename T> void vk::NLLSSolver<D, T>::optimizeLevenbergMarquardt(ModelType& model) { // Compute weight scale if(use_weights_) computeResiduals(model, false, true); // compute the initial error chi2_ = computeResiduals(model, true, false); if(verbose_) cout << "init chi2 = " << chi2_ << "\t n_meas = " << n_meas_ << endl; // TODO: compute initial lambda // Hartley and Zisserman: "A typical init value of lambda is 10^-3 times the // average of the diagonal elements of J'J" // Compute Initial Lambda if(mu_ < 0) { double H_max_diag = 0; double tau = 1e-4; for(size_t j=0; j<D; ++j) H_max_diag = max(H_max_diag, fabs(H_(j,j))); mu_ = tau*H_max_diag; } // perform iterative estimation for (iter_ = 0; iter_<n_iter_; ++iter_) { rho_ = 0; startIteration(); bool sign=false; // try to compute and update, if it fails, try with increased mu n_trials_ = 0; do { // init variables ModelType new_model; double new_chi2 = -1; H_.setZero(); //H_ = mu_ * Matrix<double,D,D>::Identity(D,D); Jres_.setZero(); // compute initial error n_meas_ = 0; computeResiduals(model, true, false); // add damping term: H_ += (H_.diagonal()*mu_).asDiagonal(); // add prior if(have_prior_) applyPrior(model); // solve the linear system if(solve()) { // update the model update(model, new_model); // compute error with new model and compare to old error n_meas_ = 0; new_chi2 = computeResiduals(new_model, true, false); rho_ = chi2_-new_chi2; } else { // matrix was singular and could not be computed cout << "Matrix is close to singular!" << endl; cout << "H = " << H_ << endl; cout << "Jres = " << Jres_ << endl; rho_ = -1; } if(rho_>0) { // update decrased the error -> success model = new_model; chi2_ = new_chi2; stop_ = vk::norm_max(x_)<=eps_ ? true : false; mu_ *= max(1./3., min(1.-pow(2*rho_-1,3), 2./3.)); nu_ = 2.; if(verbose_) { cout << "It. " << iter_ << "\t Trial " << n_trials_ << "\t Success" << "\t n_meas = " << n_meas_ << "\t new_chi2 = " << new_chi2 << "\t mu = " << mu_ << "\t nu = " << nu_ << "\t x_norm = " << vk::norm_max(x_) << endl; } } else { if(sign){ if(verbose_) { cout << "It. " << iter_ << "\t Trial " << n_trials_ << "\t Failure" << "\t n_meas = " << n_meas_ << "\t new_chi2 = " << new_chi2 << "\t mu = " << mu_ << "\t nu = " << nu_ << "\t x_norm = " << vk::norm_max(x_) << endl; } mu_ /= nu_; nu_ /= 2.; ++n_trials_; if (n_trials_ >= n_trials_max_) stop_ = true; sign=false; }else{ if(verbose_) { cout << "It. " << iter_ << "\t Trial " << n_trials_ << "\t Failure" << "\t n_meas = " << n_meas_ << "\t new_chi2 = " << new_chi2 << "\t mu = " << mu_ << "\t nu = " << nu_ << "\t x_norm = " << vk::norm_max(x_) << endl; } mu_ *= nu_; nu_ *= 2.; ++n_trials_; if (n_trials_ >= n_trials_max_) stop_ = true; sign=true; } } finishTrial(); } while(!(rho_>0 || stop_)); if (stop_) break; finishIteration(); } } template <int D, typename T> void vk::NLLSSolver<D, T>::setRobustCostFunction( ScaleEstimatorType scale_estimator, WeightFunctionType weight_function) { switch(scale_estimator) { case TDistScale: if(verbose_) printf("Using TDistribution Scale Estimator\n"); scale_estimator_.reset(new robust_cost::TDistributionScaleEstimator()); use_weights_=true; break; case MADScale: if(verbose_) printf("Using MAD Scale Estimator\n"); scale_estimator_.reset(new robust_cost::MADScaleEstimator()); use_weights_=true; break; case NormalScale: if(verbose_) printf("Using Normal Scale Estimator\n"); scale_estimator_.reset(new robust_cost::NormalDistributionScaleEstimator()); use_weights_=true; break; default: if(verbose_) printf("Using Unit Scale Estimator\n"); scale_estimator_.reset(new robust_cost::UnitScaleEstimator()); use_weights_=false; } switch(weight_function) { case TDistWeight: if(verbose_) printf("Using TDistribution Weight Function\n"); weight_function_.reset(new robust_cost::TDistributionWeightFunction()); break; case TukeyWeight: if(verbose_) printf("Using Tukey Weight Function\n"); weight_function_.reset(new robust_cost::TukeyWeightFunction()); break; case HuberWeight: if(verbose_) printf("Using Huber Weight Function\n"); weight_function_.reset(new robust_cost::HuberWeightFunction()); break; default: if(verbose_) printf("Using Unit Weight Function\n"); weight_function_.reset(new robust_cost::UnitWeightFunction()); } } template <int D, typename T> void vk::NLLSSolver<D, T>::setPrior( const T& prior, const Matrix<double, D, D>& Information) { have_prior_ = true; prior_ = prior; I_prior_ = Information; } template <int D, typename T> void vk::NLLSSolver<D, T>::reset() { have_prior_ = false; chi2_ = 1e10; mu_ = mu_init_; nu_ = nu_init_; n_meas_ = 0; n_iter_ = n_iter_init_; iter_ = 0; stop_ = false; } template <int D, typename T> inline const double& vk::NLLSSolver<D, T>::getChi2() const { return chi2_; } template <int D, typename T> inline const vk::Matrix<double, D, D>& vk::NLLSSolver<D, T>::getInformationMatrix() const { return H_; } #endif /* LM_SOLVER_IMPL_HPP_ */
8,153
2,857
#pragma once #include "Map.hpp" #include "Directions.hpp" #define DEFAULT_ROAD_WIDTH 3 class RoadGenerator { public: RoadGenerator(const int width=DEFAULT_ROAD_WIDTH); RoadGenerator(const CardinalDirection direction, const int width=DEFAULT_ROAD_WIDTH); virtual MapPtr generate(MapPtr map); protected: void generate_road(MapPtr map); const int ROAD_WIDTH; const CardinalDirection ROAD_DIRECTION; };
432
137
#include "systems/BufferResourceCache.hpp" #include "core/ShaderResource.hpp" #include "resource/Buffer.hpp" namespace vpsk { BufferResourceCache::BufferResourceCache(const vpr::Device* dvc) : device(dvc) { } BufferResourceCache::~BufferResourceCache() {} void BufferResourceCache::AddResources(const std::vector<const st::ShaderResource*>& resources) { createResources(resources); } void BufferResourceCache::AddResource(const st::ShaderResource* resource) { if (!HasResource(resource->ParentGroupName(), resource->Name())) { createResource(resource); } } vpr::Buffer* BufferResourceCache::at(const std::string& group, const std::string& name) { return buffers.at(group).at(name).get(); } vpr::Buffer* BufferResourceCache::find(const std::string& group, const std::string& name) noexcept { auto group_iter = buffers.find(group); if (group_iter != buffers.end()) { auto rsrc_iter = group_iter->second.find(name); if (rsrc_iter != group_iter->second.end()) { return rsrc_iter->second.get(); } else { return nullptr; } } else { return nullptr; } } bool BufferResourceCache::HasResource(const std::string& group, const std::string& name) const noexcept { if (buffers.count(group) == 0) { return false; } else if (buffers.at(group).count(name) != 0) { return true; } else { return false; } } void BufferResourceCache::createTexelBuffer(const st::ShaderResource* texel_buffer, bool storage) { auto& group = buffers[texel_buffer->ParentGroupName()]; auto buffer = std::make_unique<vpr::Buffer>(device); auto flags = storage ? VK_BUFFER_USAGE_STORAGE_TEXEL_BUFFER_BIT : VK_BUFFER_USAGE_UNIFORM_TEXEL_BUFFER_BIT; buffer->CreateBuffer(flags, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, texel_buffer->MemoryRequired()); buffer->CreateView(texel_buffer->Format(), buffer->Size(), 0); group.emplace(texel_buffer->Name(), std::move(buffer)); } void BufferResourceCache::createUniformBuffer(const st::ShaderResource* uniform_buffer) { auto& group = buffers[uniform_buffer->ParentGroupName()]; auto buffer = std::make_unique<vpr::Buffer>(device); auto flags = VK_MEMORY_PROPERTY_HOST_COHERENT_BIT | VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT; buffer->CreateBuffer(VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, flags, uniform_buffer->MemoryRequired()); group.emplace(uniform_buffer->Name(), std::move(buffer)); } void BufferResourceCache::createStorageBuffer(const st::ShaderResource* storage_buffer) { auto& group = buffers[storage_buffer->ParentGroupName()]; auto buffer = std::make_unique<vpr::Buffer>(device); buffer->CreateBuffer(VK_BUFFER_USAGE_STORAGE_BUFFER_BIT, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, storage_buffer->MemoryRequired()); group.emplace(storage_buffer->Name(), std::move(buffer)); } void BufferResourceCache::createResources(const std::vector<const st::ShaderResource*>& resources) { for (const auto& rsrc : resources) { if (!HasResource(rsrc->ParentGroupName(), rsrc->Name())) { createResource(rsrc); } } } void BufferResourceCache::createResource(const st::ShaderResource* rsrc) { switch (rsrc->DescriptorType()) { case VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER: createTexelBuffer(rsrc, false); break; case VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER: createTexelBuffer(rsrc, true); break; case VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER: createUniformBuffer(rsrc); break; case VK_DESCRIPTOR_TYPE_STORAGE_BUFFER: createStorageBuffer(rsrc); break; case VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC: createUniformBuffer(rsrc); break; case VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC: createStorageBuffer(rsrc); break; default: break; } } }
4,279
1,304
#pragma once #include "Person.h" namespace assignment2 { class Vehicle { public: Vehicle(unsigned int maxPassengersCount); ~Vehicle(); virtual unsigned int GetMaxSpeed() const = 0; bool AddPassenger(const Person* person); bool RemovePassenger(unsigned int i); const Person* GetPassenger(unsigned int i) const; unsigned int GetPassengersCount() const; unsigned int GetMaxPassengersCount() const; }; }
424
144
#include "camera.h" #include <glm/gtc/matrix_transform.hpp> namespace Shadow { Camera::Camera(float left, float right, float bottom, float top) : mProjectionMatrix(glm::ortho(left, right, bottom, top, -1.0f, 1.0f)), mViewMatrix(1.0f), mPosition(0.0f) { mViewProjectionMatrix = mProjectionMatrix * mViewMatrix; } void Camera::SetProjection(float left, float right, float bottom, float top) { mProjectionMatrix = glm::ortho(left, right, bottom, top, -1.0f, 1.0f); Recalculate(); } void Camera::Recalculate() { glm::mat4 transform = glm::translate(glm::mat4(1.0f), mPosition) * glm::rotate(glm::mat4(1.0f), glm::radians(mRotation), glm::vec3(0, 0, 1)); mViewMatrix = glm::inverse(transform); mViewProjectionMatrix = mProjectionMatrix * mViewMatrix; } }
822
309
// Schrodinger1DItem.cpp: implementation of the CSchrodinger1DItem class. // ////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "Schrodinger1DItem.h" #include "Schrodinger1D.h" ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// void CSchrodinger1DItem::Assign(CSchrodinger1D* pS, int& i) { iequ = i; x = &(pS->x[iequ]); h = &(pS->h[iequ]); L = &(pS->L[iequ]); v = &(pS->v[iequ]); q = &(pS->q[iequ]); dq = &(pS->dq[iequ]); d = &(pS->T.d(iequ)); s = 0; if (iequ) s = &(pS->T.s(iequ)); d1 = &(pS->d1[iequ]); E = pS->E; Z = pS->Z; W1 = pS->W1; W2 = pS->W2; ne = &(pS->ne); i += get_m(); } void CSchrodingerBC::MakeMatrix() { double M1,M2,dE1,dE2; if (Prev) { M1 = ((CSchrodinger1DLayer*)Prev)->Mz; dE1 = ((CSchrodinger1DLayer*)Prev)->dE; } if (Next) { M2 = ((CSchrodinger1DLayer*)Next)->Mz; dE2 = ((CSchrodinger1DLayer*)Next)->dE; } switch (btype) { case box: if (s) { *s = -1/M1/(*L)/(*(L-1))/(*(h-1)); *d1 = 2/M1/(*h)/(*(h-1)) + dE1 + 1e100; } else { *d1 = 2/M2/(*(h+1))/(*h) + dE2 + 1e100; } break; case transmit: if (s) { *s = -1/M1/(*L)/(*(L-1))/(*(h-1)); *d1 = 1/M1/(*h)/(*h) + dE1; } else { *d1 = 1/M2/(*h)/(*h) + dE2; } break; case cont: int i=0; s[i] = -1/M1/L[i]/L[i-1]/h[i-1]; d1[i] = 1/L[i]/L[i]*(1/M2/h[i] + 1/M1/h[i-1]) + dE2; break; } } void CSchrodingerBC::CalcQ() { double M, absM; if (Prev) { M = ((CSchrodinger1DLayer*)Prev)->Md; } if (Next) { M = ((CSchrodinger1DLayer*)Next)->Md; } absM = fabs(M); int k; switch (btype) { case box: break; case transmit: for(k=0; k<*ne; k++) { double z = Z[k][iequ]; *q -= M*z*W1[k]; *dq += absM*z*W2[k]; } break; case cont: for(k=0; k<*ne; k++) { double z = Z[k][iequ]; *q -= M*z*W1[k]; *dq += absM*z*W2[k]; } break; } } double CSchrodingerBC::get_Md() { double M; if (Prev) { M = ((CSchrodinger1DLayer*)Prev)->Md; } if (Next) { M = ((CSchrodinger1DLayer*)Next)->Md; } return M; } void CSchrodinger1DLayer::MakeMatrix() { int m = get_m(); for(int i=0; i<m; i++) { s[i] = -1/Mz/L[i]/L[i-1]/h[i-1]; d1[i] = 2/Mz/h[i]/h[i-1] + dE; } } void CSchrodinger1DLayer::CalcQ() { double absMd = fabs(Md); int m = get_m(); for(int i =0; i<m; i++) { for(int k=0; k<*ne; k++) { double z = Z[k][iequ+i]; q[i] -= Md*z*W1[k]; dq[i] += absMd*z*W2[k]; } } } void CSchrodinger1DLayer::CalcBounds(double& lbound, double& ubound, double eps) { int sign = 1; if (Md<0) sign=-1; double qriterion = sign*(log(sign*Md) - log(eps)); int m = get_m(); if (sign==1) { double vmin = *(v-1); for(int i = 0; i<=m; i++) if (v[i]<vmin) vmin = v[i]; vmin += dE; if (lbound==0. && ubound==0.) { lbound=vmin; ubound=qriterion; } else { if (vmin < lbound) lbound = vmin; if (qriterion > ubound) ubound = qriterion; } } else { double vmax = *(v-1); for(int i = 0; i<=m; i++) if (v[i]>vmax) vmax = v[i]; vmax += dE; if (lbound==0. && ubound==0.) { lbound=qriterion; ubound=vmax; } else { if (vmax > ubound) ubound = vmax; if (qriterion < lbound) lbound = qriterion; } } } void CSchrodinger1DLayer::Dump(ostream& s) { int m = get_m(); for(int i = -1; i<m; i++) { s << x[i] << "\t"; s << (v[i]+dE)/beta << "\t"; s << fabs(q[i]/beta*N0) << "\t"; s << dq[i]/beta*N0 << "\n"; } }
3,690
2,005
// C++. #include <cassert> // Qt. #include <QWidget> #include <QDialog> #include <QSignalMapper> #include <QPainter> // Local. #include <RadeonGPUAnalyzerGUI/include/qt/rgUnsavedItemsDialog.h> #include <RadeonGPUAnalyzerGUI/include/rgUtils.h> #include <RadeonGPUAnalyzerGUI/include/rgDefinitions.h> rgUnsavedItemsDialog::rgUnsavedItemsDialog(QWidget *parent) : QDialog(parent) { // Setup the UI. ui.setupUi(this); // Disable the help button in the titlebar. setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint); // Connect the signals. ConnectSignals(); // Create item delegate for the list widget. m_pItemDelegate = new rgUnsavedFileItemDelegate(); bool isDelegateValid = (m_pItemDelegate != nullptr); assert(isDelegateValid); if (isDelegateValid) { // Set custom delegate for the list widget. ui.fileListWidget->setItemDelegate(m_pItemDelegate); } // Disable selection of items. ui.fileListWidget->setSelectionMode(QAbstractItemView::NoSelection); } rgUnsavedItemsDialog::~rgUnsavedItemsDialog() { if (m_pItemDelegate != nullptr) { delete m_pItemDelegate; } } void rgUnsavedItemsDialog::ConnectSignals() { // Create a signal mapper to map the button clicks to the done(int) slot // with appropriate result values. QSignalMapper* pButtonSignalMapper = new QSignalMapper(this); // Yes button. bool isConnected = connect(ui.yesPushButton, SIGNAL(clicked()), pButtonSignalMapper, SLOT(map())); assert(isConnected); pButtonSignalMapper->setMapping(ui.yesPushButton, UnsavedFileDialogResult::Yes); // No button. isConnected = connect(ui.noPushButton, SIGNAL(clicked()), pButtonSignalMapper, SLOT(map())); assert(isConnected); pButtonSignalMapper->setMapping(ui.noPushButton, UnsavedFileDialogResult::No); // Cancel button. isConnected = connect(ui.cancelPushButton, SIGNAL(clicked()), pButtonSignalMapper, SLOT(map())); assert(isConnected); pButtonSignalMapper->setMapping(ui.cancelPushButton, UnsavedFileDialogResult::Cancel); // Signal mapper. isConnected = connect(pButtonSignalMapper, SIGNAL(mapped(int)), this, SLOT(done(int))); assert(isConnected); } void rgUnsavedItemsDialog::AddFile(QString filename) { ui.fileListWidget->addItem(filename); } void rgUnsavedItemsDialog::AddFiles(QStringList filenames) { foreach(const QString& filename, filenames) { AddFile(filename); } } void rgUnsavedFileItemDelegate::drawDisplay(QPainter* pPainter, const QStyleOptionViewItem& option, const QRect &rect, const QString& text) const { bool isPainterValid = (pPainter != nullptr); assert(isPainterValid); if (isPainterValid) { // Truncate string so it fits within rect. QString truncatedString = rgUtils::TruncateString(text.toStdString(), gs_TEXT_TRUNCATE_LENGTH_FRONT, gs_TEXT_TRUNCATE_LENGTH_BACK, rect.width(), pPainter->font(), rgUtils::EXPAND_BACK).c_str(); // Draw text within rect. pPainter->drawText(rect, Qt::AlignVCenter, truncatedString); } } QSize rgUnsavedFileItemDelegate::sizeHint(const QStyleOptionViewItem& option, const QModelIndex& index) const { // Use standard size hint implementation, but with a fixed width of 0 (width will be determined by view width). QSize adjustedHint = QItemDelegate::sizeHint(option, index); adjustedHint.setWidth(0); return adjustedHint; }
3,490
1,135
// ====================================================================== /*! * \file * \brief Interface of class TextGen::IdGenerator */ // ====================================================================== #include "IdGenerator.h" #include <boost/atomic.hpp> namespace TextGen { // ---------------------------------------------------------------------- /*! * \brief Return a new ID * * \return The generated ID */ // ---------------------------------------------------------------------- long IdGenerator::generate() { static boost::atomic<long> id; return ++id; } } // namespace TextGen // ======================================================================
686
152
// Copyright 2017 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 "components/digital_asset_links/digital_asset_links_handler.h" #include <vector> #include "base/bind.h" #include "base/json/json_reader.h" #include "base/logging.h" #include "base/strings/stringprintf.h" #include "base/values.h" #include "content/public/browser/web_contents.h" #include "net/http/http_response_headers.h" #include "net/http/http_status_code.h" #include "net/http/http_util.h" #include "net/traffic_annotation/network_traffic_annotation.h" #include "services/network/public/cpp/resource_request.h" #include "services/network/public/cpp/shared_url_loader_factory.h" #include "services/network/public/cpp/simple_url_loader.h" #include "services/network/public/mojom/url_response_head.mojom.h" #include "third_party/blink/public/mojom/devtools/console_message.mojom.h" #include "url/origin.h" namespace { // In some cases we get a network change while fetching the digital asset // links file. See https://crbug.com/987329. const int kNumNetworkRetries = 1; // Location on a website where the asset links file can be found, see // https://developers.google.com/digital-asset-links/v1/getting-started. const char kAssetLinksAbsolutePath[] = ".well-known/assetlinks.json"; GURL GetUrlForAssetLinks(const url::Origin& origin) { return origin.GetURL().Resolve(kAssetLinksAbsolutePath); } // An example, well formed asset links file for reference: // [{ // "relation": ["delegate_permission/common.handle_all_urls"], // "target": { // "namespace": "android_app", // "package_name": "com.peter.trustedpetersactivity", // "sha256_cert_fingerprints": [ // "FA:2A:03: ... :9D" // ] // } // }, { // "relation": ["delegate_permission/common.handle_all_urls"], // "target": { // "namespace": "android_app", // "package_name": "com.example.firstapp", // "sha256_cert_fingerprints": [ // "64:2F:D4: ... :C1" // ] // } // }] bool StatementHasMatchingRelationship(const base::Value& statement, const std::string& target_relation) { const base::Value* relations = statement.FindKeyOfType("relation", base::Value::Type::LIST); if (!relations) return false; for (const auto& relation : relations->GetList()) { if (relation.is_string() && relation.GetString() == target_relation) return true; } return false; } bool StatementHasMatchingTargetValue( const base::Value& statement, const std::string& target_key, const std::set<std::string>& target_value) { const base::Value* package = statement.FindPathOfType( {"target", target_key}, base::Value::Type::STRING); return package && target_value.find(package->GetString()) != target_value.end(); } bool StatementHasMatchingFingerprint(const base::Value& statement, const std::string& target_fingerprint) { const base::Value* fingerprints = statement.FindPathOfType( {"target", "sha256_cert_fingerprints"}, base::Value::Type::LIST); if (!fingerprints) return false; for (const auto& fingerprint : fingerprints->GetList()) { if (fingerprint.is_string() && fingerprint.GetString() == target_fingerprint) { return true; } } return false; } // Shows a warning message in the DevTools console. void AddMessageToConsole(content::WebContents* web_contents, const std::string& message) { if (web_contents) { web_contents->GetMainFrame()->AddMessageToConsole( blink::mojom::ConsoleMessageLevel::kWarning, message); return; } // Fallback to LOG. LOG(WARNING) << message; } } // namespace namespace digital_asset_links { const char kDigitalAssetLinksCheckResponseKeyLinked[] = "linked"; DigitalAssetLinksHandler::DigitalAssetLinksHandler( scoped_refptr<network::SharedURLLoaderFactory> factory, content::WebContents* web_contents) : shared_url_loader_factory_(std::move(factory)) { if (web_contents) { web_contents_ = web_contents->GetWeakPtr(); } } DigitalAssetLinksHandler::~DigitalAssetLinksHandler() = default; void DigitalAssetLinksHandler::OnURLLoadComplete( std::string relationship, absl::optional<std::string> fingerprint, std::map<std::string, std::set<std::string>> target_values, std::unique_ptr<std::string> response_body) { int response_code = -1; if (url_loader_->ResponseInfo() && url_loader_->ResponseInfo()->headers) response_code = url_loader_->ResponseInfo()->headers->response_code(); if (!response_body || response_code != net::HTTP_OK) { int net_error = url_loader_->NetError(); if (net_error == net::ERR_INTERNET_DISCONNECTED || net_error == net::ERR_NAME_NOT_RESOLVED) { AddMessageToConsole(web_contents_.get(), "Digital Asset Links connection failed."); std::move(callback_).Run(RelationshipCheckResult::kNoConnection); return; } AddMessageToConsole( web_contents_.get(), base::StringPrintf( "Digital Asset Links endpoint responded with code %d.", response_code)); std::move(callback_).Run(RelationshipCheckResult::kFailure); return; } data_decoder::DataDecoder::ParseJsonIsolated( *response_body, base::BindOnce(&DigitalAssetLinksHandler::OnJSONParseResult, weak_ptr_factory_.GetWeakPtr(), std::move(relationship), std::move(fingerprint), std::move(target_values))); url_loader_.reset(nullptr); } void DigitalAssetLinksHandler::OnJSONParseResult( std::string relationship, absl::optional<std::string> fingerprint, std::map<std::string, std::set<std::string>> target_values, data_decoder::DataDecoder::ValueOrError result) { if (!result.value) { AddMessageToConsole( web_contents_.get(), "Digital Asset Links response parsing failed with message: " + *result.error); std::move(callback_).Run(RelationshipCheckResult::kFailure); return; } auto& statement_list = *result.value; if (!statement_list.is_list()) { std::move(callback_).Run(RelationshipCheckResult::kFailure); AddMessageToConsole(web_contents_.get(), "Statement List is not a list."); return; } // We only output individual statement failures if none match. std::vector<std::string> failures; for (const auto& statement : statement_list.GetList()) { if (!statement.is_dict()) { failures.push_back("Statement is not a dictionary."); continue; } if (!StatementHasMatchingRelationship(statement, relationship)) { failures.push_back("Statement failure matching relationship."); continue; } if (fingerprint && !StatementHasMatchingFingerprint(statement, *fingerprint)) { failures.push_back("Statement failure matching fingerprint."); continue; } bool failed_target_check = false; for (const auto& key_value : target_values) { if (!StatementHasMatchingTargetValue(statement, key_value.first, key_value.second)) { failures.push_back("Statement failure matching " + key_value.first + "."); failed_target_check = true; break; } } if (failed_target_check) continue; std::move(callback_).Run(RelationshipCheckResult::kSuccess); return; } for (const auto& failure_reason : failures) AddMessageToConsole(web_contents_.get(), failure_reason); std::move(callback_).Run(RelationshipCheckResult::kFailure); } bool DigitalAssetLinksHandler::CheckDigitalAssetLinkRelationshipForAndroidApp( const std::string& web_domain, const std::string& relationship, const std::string& fingerprint, const std::string& package, RelationshipCheckResultCallback callback) { // TODO(rayankans): Should we also check the namespace here? return CheckDigitalAssetLinkRelationship( web_domain, relationship, fingerprint, {{"package_name", {package}}}, std::move(callback)); } bool DigitalAssetLinksHandler::CheckDigitalAssetLinkRelationshipForWebApk( const std::string& web_domain, const std::string& manifest_url, RelationshipCheckResultCallback callback) { return CheckDigitalAssetLinkRelationship( web_domain, "delegate_permission/common.query_webapk", absl::nullopt, {{"namespace", {"web"}}, {"site", {manifest_url}}}, std::move(callback)); } bool DigitalAssetLinksHandler::CheckDigitalAssetLinkRelationship( const std::string& web_domain, const std::string& relationship, const absl::optional<std::string>& fingerprint, const std::map<std::string, std::set<std::string>>& target_values, RelationshipCheckResultCallback callback) { // TODO(peconn): Propagate the use of url::Origin backwards to clients. GURL request_url = GetUrlForAssetLinks(url::Origin::Create(GURL(web_domain))); if (!request_url.is_valid()) return false; // Resetting both the callback and SimpleURLLoader here to ensure // that any previous requests will never get a // OnURLLoadComplete. This effectively cancels any checks that was // done over this handler. callback_ = std::move(callback); net::NetworkTrafficAnnotationTag traffic_annotation = net::DefineNetworkTrafficAnnotation("digital_asset_links", R"( semantics { sender: "Digital Asset Links Handler" description: "Digital Asset Links APIs allows any caller to check pre declared" "relationships between two assets which can be either web domains" "or native applications. This requests checks for a specific " "relationship declared by a web site with an Android application" trigger: "When the related application makes a claim to have the queried" "relationship with the web domain" data: "None" destination: WEBSITE } policy { cookies_allowed: YES cookies_store: "user" setting: "Not user controlled. But the verification is a trusted API" "that doesn't use user data" policy_exception_justification: "Not implemented, considered not useful as no content is being " "uploaded; this request merely downloads the resources on the web." })"); auto request = std::make_unique<network::ResourceRequest>(); request->url = request_url; // Exclude credentials (specifically client certs) from the request. request->credentials_mode = network::mojom::CredentialsMode::kOmitBug_775438_Workaround; url_loader_ = network::SimpleURLLoader::Create(std::move(request), traffic_annotation); url_loader_->SetRetryOptions( kNumNetworkRetries, network::SimpleURLLoader::RetryMode::RETRY_ON_NETWORK_CHANGE); url_loader_->SetTimeoutDuration(timeout_duration_); url_loader_->DownloadToStringOfUnboundedSizeUntilCrashAndDie( shared_url_loader_factory_.get(), base::BindOnce(&DigitalAssetLinksHandler::OnURLLoadComplete, weak_ptr_factory_.GetWeakPtr(), relationship, fingerprint, target_values)); return true; } void DigitalAssetLinksHandler::SetTimeoutDuration( base::TimeDelta timeout_duration) { timeout_duration_ = timeout_duration; } } // namespace digital_asset_links
11,565
3,444
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/sagemaker/model/OfflineStoreStatus.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::Utils::Json; using namespace Aws::Utils; namespace Aws { namespace SageMaker { namespace Model { OfflineStoreStatus::OfflineStoreStatus() : m_status(OfflineStoreStatusValue::NOT_SET), m_statusHasBeenSet(false), m_blockedReasonHasBeenSet(false) { } OfflineStoreStatus::OfflineStoreStatus(JsonView jsonValue) : m_status(OfflineStoreStatusValue::NOT_SET), m_statusHasBeenSet(false), m_blockedReasonHasBeenSet(false) { *this = jsonValue; } OfflineStoreStatus& OfflineStoreStatus::operator =(JsonView jsonValue) { if(jsonValue.ValueExists("Status")) { m_status = OfflineStoreStatusValueMapper::GetOfflineStoreStatusValueForName(jsonValue.GetString("Status")); m_statusHasBeenSet = true; } if(jsonValue.ValueExists("BlockedReason")) { m_blockedReason = jsonValue.GetString("BlockedReason"); m_blockedReasonHasBeenSet = true; } return *this; } JsonValue OfflineStoreStatus::Jsonize() const { JsonValue payload; if(m_statusHasBeenSet) { payload.WithString("Status", OfflineStoreStatusValueMapper::GetNameForOfflineStoreStatusValue(m_status)); } if(m_blockedReasonHasBeenSet) { payload.WithString("BlockedReason", m_blockedReason); } return payload; } } // namespace Model } // namespace SageMaker } // namespace Aws
1,564
553
// Copyright Carl Philipp Reh 2006 - 2019. // 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 SGE_RENDERER_TEXTURE_VOLUME_SHARED_PTR_HPP_INCLUDED #define SGE_RENDERER_TEXTURE_VOLUME_SHARED_PTR_HPP_INCLUDED #include <sge/renderer/texture/volume_fwd.hpp> #include <fcppt/shared_ptr_impl.hpp> namespace sge { namespace renderer { namespace texture { typedef fcppt::shared_ptr<texture::volume> volume_shared_ptr; } } } #endif
562
241
#include "fps.hpp" #include <sstream> #include "../../io/io.hpp" #include "../transform.hpp" FPS::FPS(float panSpeed, float rotationSpeed) : Component("FPS"), __pan_speed(panSpeed), __rotation_speed(rotationSpeed) {} FPS::FPS(const FPS& fps) : Component(fps), __pan_speed(fps.__pan_speed), __rotation_speed(fps.__rotation_speed) {} std::shared_ptr<FPS> FPS::make_fps(float panSpeed, float rotationSpeed) { std::shared_ptr<FPS> fps(new FPS(panSpeed, rotationSpeed)); return fps; } std::shared_ptr<FPS> pepng::make_fps(float panSpeed, float rotationSpeed) { return FPS::make_fps(panSpeed, rotationSpeed); } FPS* FPS::clone_implementation() { return new FPS(*this); } void FPS::update(std::shared_ptr<WithComponents> parent) { if(!this->_is_active) { return; } auto transform = parent->get_component<Transform>(); if (transform == nullptr) { std::stringstream ss; ss << *parent << " has an FPS but no Transform."; std::cout << ss.str() << std::endl; std::runtime_error(ss.str()); } auto input = Input::get(); auto mouseDelta = glm::vec2(input->axis("mouseX"), input->axis("mouseY")); if (input->button("pan")) { transform->position += transform->up() * mouseDelta.y * this->__pan_speed + transform->right() * mouseDelta.x * this->__pan_speed; } auto rotation = glm::vec3(mouseDelta.y, mouseDelta.x, 0.0f); if(input->button("rotate") && glm::length(rotation) > 0.25f) { transform->delta_rotate(rotation * this->__rotation_speed); } transform->position -= transform->forward() * input->axis("zoom") * this->__pan_speed; } #ifdef IMGUI void FPS::imgui() { Component::imgui(); ImGui::InputFloat("Pan Speed", &this->__pan_speed); ImGui::InputFloat("Rotation Speed", &this->__rotation_speed); } #endif
1,875
667
/* * stream_feeder.hpp * * Created on: Jan 27, 2016 * Author: zmij */ #ifndef WIRE_UTIL_CONCATENATE_HPP_ #define WIRE_UTIL_CONCATENATE_HPP_ #include <sstream> #include <string> #include <typeinfo> namespace wire { namespace util { namespace detail { struct __io_meta_function_helper { template <typename T> __io_meta_function_helper(T const&); }; ::std::false_type operator << (::std::ostream const&, __io_meta_function_helper const&); template <typename T> struct has_output_operator { private: static ::std::false_type test(::std::false_type); static ::std::true_type test(::std::ostream&); static ::std::ostream& os; static T const& val; public: static constexpr bool value = ::std::is_same< decltype( test( os << val) ), ::std::true_type >::type::value; }; template < typename T, bool > struct output_impl { static void output(::std::ostream& os, T const& arg) { os << arg; } }; template < typename T > struct output_impl<T, false> { static void output(::std::ostream& os, T const&) { os << typeid(T).name(); } }; template < typename T > void concatenate( ::std::ostream& os, T const& arg) { using output = output_impl<T, has_output_operator<T>::value>; output::output(os, arg); } template < typename T, typename ... Y > void concatenate( ::std::ostream& os, T const& arg, Y const& ... args ) { using output = output_impl<T, has_output_operator<T>::value>; output::output(os, arg); concatenate(os, args ...); } template < typename T > void delim_concatenate( ::std::ostream& os, ::std::string const& delim, T const& arg) { using output = output_impl<T, has_output_operator<T>::value>; output::output(os, arg); } template < typename T, typename ... Y > void delim_concatenate( ::std::ostream& os, ::std::string const& delim, T const& arg, Y const& ... args ) { using output = output_impl<T, has_output_operator<T>::value>; output::output(os, arg); os << delim; delim_concatenate(os, delim, args ...); } } // namespace detail template < typename ... T > ::std::string concatenate( T const& ... args) { ::std::ostringstream os; detail::concatenate(os, args ...); return os.str(); } template < typename ... T > ::std::string delim_concatenate(::std::string const& delim, T const& ... args) { ::std::ostringstream os; detail::delim_concatenate(os, delim, args ...); return os.str(); } } // namespace util } // namespace wire #endif /* WIRE_UTIL_CONCATENATE_HPP_ */
2,547
912
//===--- Task.cpp - Task object and management ----------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2020 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // // Object management routines for asynchronous task objects. // //===----------------------------------------------------------------------===// #include "swift/Runtime/Concurrency.h" #include "swift/ABI/Task.h" #include "swift/ABI/Metadata.h" #include "swift/Runtime/HeapObject.h" #include "TaskPrivate.h" using namespace swift; SWIFT_CC(swift) static void destroySimpleTask(SWIFT_CONTEXT HeapObject *_obj) { auto obj = static_cast<AsyncTask*>(_obj); assert(!obj->isFuture()); // The task execution itself should always hold a reference to it, so // if we get here, we know the task has finished running, which means // swift_task_complete should have been run, which will have torn down // the task-local allocator. There's actually nothing else to clean up // here. free(obj); } /// Heap metadata for a simple asynchronous task that does not /// include a future. static FullMetadata<HeapMetadata> simpleTaskHeapMetadata = { { { &destroySimpleTask }, { /*value witness table*/ nullptr } }, { MetadataKind::SimpleTask } }; /// The function that we put in the context of a simple task /// (one with no future) to handle the final return. SWIFT_CC(swift) static void completeTask(AsyncTask *task, ExecutorRef executor, AsyncContext *context) { // Tear down the task-local allocator immediately; there's no need // to wait for the object to be destroyed. _swift_task_alloc_destroy(task); // TODO: set something in the status? // TODO: notify the parent somehow? // TODO: remove this task from the child-task chain? // TODO: notify tasks waiting on the future? // Release the task, balancing the retain that a running task // has on itself. swift_release(task); } AsyncTaskAndContext swift::swift_task_create(JobFlags flags, AsyncTask *parent, const AsyncFunctionPointer<void()> *function) { return swift_task_create_f(flags, parent, function->Function.get(), function->ExpectedContextSize); } AsyncTaskAndContext swift::swift_task_create_f(JobFlags flags, AsyncTask *parent, AsyncFunctionType<void()> *function, size_t initialContextSize) { assert(!flags.task_isFuture() && "function doesn't support creating futures"); assert((parent != nullptr) == flags.task_isChildTask()); // Figure out the size of the header. size_t headerSize = sizeof(AsyncTask); if (parent) headerSize += sizeof(AsyncTask::ChildFragment); // Allocate the initial context together with the job. // This means that we never get rid of this allocation. size_t amountToAllocate = headerSize + initialContextSize; assert(amountToAllocate % MaximumAlignment == 0); void *allocation = malloc(amountToAllocate); AsyncContext *initialContext = reinterpret_cast<AsyncContext*>( reinterpret_cast<char*>(allocation) + headerSize); // Initialize the task so that resuming it will run the given // function on the initial context. AsyncTask *task = new(allocation) AsyncTask(&simpleTaskHeapMetadata, flags, function, initialContext); // Initialize the child fragment if applicable. // TODO: propagate information from the parent? if (parent) { auto childFragment = task->childFragment(); new (childFragment) AsyncTask::ChildFragment(parent); } // Configure the initial context. // // FIXME: if we store a null pointer here using the standard ABI for // signed null pointers, then we'll have to authenticate context pointers // as if they might be null, even though the only time they ever might // be is the final hop. Store a signed null instead. initialContext->Parent = nullptr; initialContext->ResumeParent = &completeTask; initialContext->ResumeParentExecutor = ExecutorRef::noPreference(); initialContext->Flags = AsyncContextKind::Ordinary; initialContext->Flags.setShouldNotDeallocateInCallee(true); // Initialize the task-local allocator. _swift_task_alloc_initialize(task); return {task, initialContext}; }
4,650
1,283
/* * qtui.cc * Copyright 2014 Michał Lipski * * 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 * provided with the distribution. * * This software is provided "as is" and without any warranty, express or * implied. In no event shall the authors be liable for any damages arising from * the use of this software. */ #include <QApplication> #include <libaudcore/i18n.h> #include <libaudcore/plugin.h> #include <libaudcore/plugins.h> #include "main_window.h" static MainWindow * window; static bool_t init () { return true; } static void cleanup () { } static void run () { int dummy_argc = 0; QApplication qapp (dummy_argc, 0); window = new MainWindow; window->show (); qapp.exec (); delete window; } static void show (bool_t show) { } static void quit () { qApp->quit(); } #define AUD_PLUGIN_NAME N_("Qt Interface") #define AUD_PLUGIN_INIT init #define AUD_PLUGIN_CLEANUP cleanup #define AUD_IFACE_RUN run #define AUD_IFACE_SHOW show #define AUD_IFACE_QUIT quit #define AUD_DECLARE_IFACE #include <libaudcore/plugin-declare.h>
1,517
503
#pragma once #include "vcl_base.h" #include "Buttons.hpp" #include "Classes.hpp" #include "Controls.hpp" #include "Forms.hpp" #include "Graphics.hpp" #include "Menus.hpp" #include "Messages.hpp" #include "StdCtrls.hpp" #include "SysUtils.hpp"
244
97
#include "shared.h" using namespace scene_graph; /* ParticleEmitter implementation */ typedef xtl::signal<void (ParticleEmitter& sender, ParticleEmitterEvent event)> ParticleEmitterSignal; struct ParticleEmitter::Impl: public xtl::instance_counter<ParticleEmitter> { stl::string particle_system_id; //particle system identifier (as loaded in media::ParticleSystemLibrary) xtl::auto_connection particles_parent_destroy_connection; //particles parent node's destroy connection ParticleEmitterSignal signals [ParticleEmitterEvent_Num]; //signals Node* particles_parent; //particles are emitted in coordinate space of this node scene_graph::SpriteMode sprite_mode; //sprite mode bool is_playing; //is emitter emits particles now Impl (const char* in_particle_system_id, Node* in_particles_parent, scene_graph::SpriteMode in_sprite_mode) : particles_parent (in_particles_parent) , sprite_mode (in_sprite_mode) , is_playing (true) { if (!in_particle_system_id) throw xtl::make_null_argument_exception ("scene_graph::ParticleEmitter::Impl::Impl", "particle_system_id"); particle_system_id = in_particle_system_id; particles_parent_destroy_connection = particles_parent->RegisterEventHandler (NodeEvent_BeforeDestroy, xtl::bind (&ParticleEmitter::Impl::OnBaseNodeDestroy, this)); } void OnBaseNodeDestroy () { particles_parent = 0; } ///Notify about event void Notify (ParticleEmitter& emitter, ParticleEmitterEvent event) { //ignore if we have no handlers for this event if (!signals [event]) return; //call event handlers try { signals [event] (emitter, event); } catch (...) { //suppress all exceptions } } }; /* Constructor / destructor */ ParticleEmitter::ParticleEmitter (const char* particle_system_id, Node::Pointer particles_parent, scene_graph::SpriteMode sprite_mode) : impl (new Impl (particle_system_id, particles_parent ? particles_parent.get () : this, sprite_mode)) {} ParticleEmitter::~ParticleEmitter () { delete impl; } /* Emitter creation */ ParticleEmitter::Pointer ParticleEmitter::Create (const char* particle_system_id, Node::Pointer particles_parent, scene_graph::SpriteMode sprite_mode) { return Pointer (new ParticleEmitter (particle_system_id, particles_parent, sprite_mode), false); } /* Particle system identifier (as loaded in media::ParticleSystemLibrary) */ const char* ParticleEmitter::ParticleSystemId () const { return impl->particle_system_id.c_str (); } /* Particles are emitted in coordinate space of this node */ Node::Pointer ParticleEmitter::ParticlesParent () const { return impl->particles_parent; } /* Sprite mode */ scene_graph::SpriteMode ParticleEmitter::SpriteMode () const { return impl->sprite_mode; } /* Control simualtion process */ void ParticleEmitter::Play () { if (impl->is_playing) return; impl->is_playing = true; impl->Notify (*this, ParticleEmitterEvent_OnPlay); } bool ParticleEmitter::IsPlaying () const { return impl->is_playing; } void ParticleEmitter::Pause () { if (!impl->is_playing) return; impl->is_playing = false; impl->Notify (*this, ParticleEmitterEvent_OnPause); } /* Registration for ParticleEmitter events */ xtl::connection ParticleEmitter::RegisterEventHandler (ParticleEmitterEvent event, const EventHandler& handler) const { if (event < 0 || event >= ParticleEmitterEvent_Num) throw xtl::make_argument_exception ("scene_graph::ParticleEmitter::Event", "event", event); return impl->signals [event].connect (handler); } /* Method which is called when this node is visited */ void ParticleEmitter::AcceptCore (Visitor& visitor) { if (!TryAccept (*this, visitor)) VisualModel::AcceptCore (visitor); }
4,118
1,371
#include <iostream> #include "../../src/referee.cpp" using namespace std; int main() { Referee referee; referee.readGameInfo(); Referee refereeCopy(referee); cout << refereeCopy.toString(); }
204
72
// https://www.hackerrank.com/challenges/swap-nodes-algo #include "common/stl/base.h" #include <functional> int main_swap_nodes_algo() { unsigned N; cin >> N; vector<int> vl(N + 1, -1), vr(N + 1, -1), vd(N + 1, -1); vector<bool> vh(N + 1, true); for (unsigned i = 1; i <= N; ++i) { int l, r; cin >> l >> r; vl[i] = l; vr[i] = r; if (l != -1) vh[l] = false; if (r != -1) vh[r] = false; } unsigned h = 0; for (unsigned i = 1; i < N; ++i) { if (vh[i]) { h = i; break; } } std::function<void(int, int)> InitD = [&](int c, int cd) -> void { if (c != -1) { vd[c] = cd; InitD(vl[c], cd + 1); InitD(vr[c], cd + 1); } }; std::function<void(int)> Print = [&](int c) -> void { if (c != -1) { Print(vl[c]); cout << c << " "; Print(vr[c]); } }; InitD(h, 1); unsigned T; cin >> T; for (unsigned iT = 0; iT < T; ++iT) { int d; cin >> d; for (unsigned i = 1; i <= N; ++i) { if ((vd[i] % d) == 0) swap(vl[i], vr[i]); } Print(h); cout << endl; } return 0; }
1,110
529
// // Copyright (c) 2021- anjisuan783 // // SPDX-License-Identifier: MIT // #include "handler/media_mux.h" #include "common/media_kernel_error.h" #include "utils/json.h" #include "connection/http_conn.h" #include "http/http_stack.h" #include "http/h/http_message.h" #include "connection/h/media_conn_mgr.h" #include "rtmp/media_req.h" #include "handler/media_live_handler.h" #include "handler/media_rtc_handler.h" #include "handler/media_file_handler.h" namespace ma { MediaHttpServeMux::MediaHttpServeMux() : rtc_sevice_{new MediaHttpRtcServeMux}, flv_sevice_{new MediaFlvPlayHandler}, file_sevice_{new MediaFileHandler} { g_conn_mgr_.signal_destroy_conn_.connect(this, &MediaHttpServeMux::conn_destroy); } MediaHttpServeMux::~MediaHttpServeMux() = default; srs_error_t MediaHttpServeMux::init() { return rtc_sevice_->init(); } srs_error_t MediaHttpServeMux::serve_http( std::shared_ptr<IHttpResponseWriter> writer, std::shared_ptr<ISrsHttpMessage> msg) { std::string path = msg->path(); if (path == RTC_PUBLISH_PREFIX || path == RTC_PALY_PREFIX) { return rtc_sevice_->serve_http(std::move(writer), std::move(msg)); } if (path == HTTP_TEST) { return file_sevice_->serve_http(std::move(writer), std::move(msg)); } return flv_sevice_->serve_http(std::move(writer), std::move(msg)); } srs_error_t MediaHttpServeMux::mount_service( std::shared_ptr<MediaSource> s, std::shared_ptr<MediaRequest> r) { srs_error_t err = srs_success; if ((err = rtc_sevice_->mount_service(s, r)) != srs_success) { return srs_error_wrap(err, "rtc mount service"); } return flv_sevice_->mount_service(std::move(s), std::move(r)); } void MediaHttpServeMux::unmount_service( std::shared_ptr<MediaSource> s, std::shared_ptr<MediaRequest> r) { rtc_sevice_->unmount_service(s, r); flv_sevice_->unmount_service(std::move(s), std::move(r)); } void MediaHttpServeMux::conn_destroy(std::shared_ptr<IMediaConnection> conn) { flv_sevice_->conn_destroy(conn); file_sevice_->conn_destroy(conn); } std::unique_ptr<IMediaHttpHandler> ServerHandlerFactor::Create() { return std::make_unique<MediaHttpServeMux>(); } }
2,176
862
/***************************************************************************** * * Copyright (c) 2003-2020 by The University of Queensland * http://www.uq.edu.au * * Primary Business: Queensland, Australia * Licensed under the Apache License, version 2.0 * http://www.apache.org/licenses/LICENSE-2.0 * * Development until 2012 by Earth Systems Science Computational Center (ESSCC) * Development 2012-2013 by School of Earth Sciences * Development from 2014-2017 by Centre for Geoscience Computing (GeoComp) * Development from 2019 by School of Earth and Environmental Sciences ** *****************************************************************************/ #include "Data.h" #include "WrappedArray.h" #include "DataException.h" #if ESYS_HAVE_NUMPY_H #define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION #include <numpy/ndarrayobject.h> #endif #include <iostream> #include <boost/python/tuple.hpp> using namespace escript; using namespace boost::python; using DataTypes::cplx_t; using DataTypes::real_t; namespace { void checkFeatures(const boost::python::object& obj) { using namespace std; boost::python::object o2; try { /*int len=*/ extract<int>(obj.attr("__len__")()); } catch (...) { PyErr_Clear(); throw DataException("Object passed to WrappedArray must support __len__"); } try { o2=obj.attr("__getitem__"); } catch (...) { PyErr_Clear(); throw DataException("Object passed to WrappedArray must support __getitem__"); } } // This should not be called on anything which does // not have a __len__ bool checkForComplex(const boost::python::object& obj) { try { int len=extract<int>(obj.attr("__len__")()); for (int i=0;i<len;++i) { const boost::python::object t=obj[i]; bool haslen=false; try { extract<int>(t.attr("__len__")()); haslen=true; } catch(...) { PyErr_Clear(); } // If it has a length, we dig down // if not, we test for complex if (haslen) { if (checkForComplex(t)) { return true; } } else { extract<DataTypes::real_t> er(t); if (!er.check()) { // unfortunately, if this was a numpy object, that check my fail // even if it should succeed (eg numpy.int64 on python3) // instead, we will try to call __float__ and see what happens try { t.attr("__float__")(); return false; // if this check succeeds it isn't complex } catch (...) { PyErr_Clear(); // at this point, we have no apparent way to get a real out so // we assume it must be complex return true; } } } } return false; } catch(...) { PyErr_Clear(); return false; } return false; } void getObjShape(const boost::python::object& obj, DataTypes::ShapeType& s) { int len=0; try { len=extract<int>(obj.attr("__len__")()); } catch(...) { PyErr_Clear(); // tell python the error isn't there anymore return; } if (len<1) { throw DataException("Array filter - no empty components in arrays please."); } s.push_back(len); if (s.size()>ESCRIPT_MAX_DATA_RANK) { throw DataException("Array filter - Maximum rank exceeded in array"); } getObjShape(obj[0],s); } } WrappedArray::WrappedArray(const boost::python::object& obj_in) :obj(obj_in),converted(false),iscomplex(false),scalar_r(nan("")),scalar_c(nan("")) { dat_r=0; dat_c=0; // First we check for scalars try { extract<DataTypes::cplx_t> ec(obj_in); extract<real_t> er(obj_in); if (er.check()) // check for real_t first because complex will fail this { scalar_r=er(); } else { scalar_c=ec(); iscomplex=true; } rank=0; return; } catch (...) { // so we clear the failure PyErr_Clear(); } try { const boost::python::object obj_in_t=obj_in[make_tuple()]; extract<DataTypes::cplx_t> ec(obj_in_t); extract<real_t> er(obj_in_t); if (er.check()) { scalar_r=er(); } else { scalar_c=ec(); iscomplex=true; } rank=0; return; } catch (...) { // so we clear the failure PyErr_Clear(); } scalar_c=0; scalar_r=0; checkFeatures(obj_in); getObjShape(obj,shape); rank=shape.size(); iscomplex=checkForComplex(obj_in); #if ESYS_HAVE_NUMPY_H // if obj is a numpy array it is much faster to copy the array through the // __array_struct__ interface instead of extracting single values from the // components via getElt(). For this to work we check below that // (1) this is a valid PyArrayInterface instance // (2) the data is stored as a contiguous C array // (3) the data type is suitable (correct type and byte size) try { object o = (extract<object>(obj.attr("__array_struct__"))); #ifdef ESPYTHON3 if (PyCapsule_CheckExact(o.ptr())) #else if (PyCObject_Check(o.ptr())) #endif { PyObject* cobj=(PyObject*)o.ptr(); #ifdef ESPYTHON3 const char* name = PyCapsule_GetName(cobj); PyArrayInterface* arr=(PyArrayInterface*)PyCapsule_GetPointer(cobj, name); #else PyArrayInterface* arr=(PyArrayInterface*)PyCObject_AsVoidPtr(cobj); #endif #ifndef NPY_1_7_API_VERSION #define NPY_ARRAY_IN_ARRAY NPY_IN_ARRAY #define NPY_ARRAY_NOTSWAPPED NPY_NOTSWAPPED #endif if (arr->two==2 && arr->flags&NPY_ARRAY_IN_ARRAY && arr->flags&NPY_ARRAY_NOTSWAPPED) { std::vector<int> strides; // convert #bytes to #elements for (int i=0; i<arr->nd; i++) { strides.push_back(arr->strides[i]/arr->itemsize); } if (arr->typekind == 'f') { if (arr->itemsize==sizeof(real_t)) { convertNumpyArray<real_t>((const real_t*)arr->data, strides); } else if (arr->itemsize==sizeof(float)) { convertNumpyArray<float>((const float*)arr->data, strides); } } else if (arr->typekind == 'i') { if (arr->itemsize==sizeof(int)) { convertNumpyArray<int>((const int*)arr->data, strides); } else if (arr->itemsize==sizeof(long)) { convertNumpyArray<long>((const long*)arr->data, strides); } } else if (arr->typekind == 'u') { if (arr->itemsize==sizeof(unsigned)) { convertNumpyArray<unsigned>((const unsigned*)arr->data, strides); } else if (arr->itemsize==sizeof(unsigned long)) { convertNumpyArray<unsigned long>((const unsigned long*)arr->data, strides); } } else if (arr->typekind == 'c') { if (arr->itemsize==sizeof(cplx_t)) { convertNumpyArrayC<DataTypes::cplx_t>((const cplx_t*)arr->data, strides); iscomplex=true; } // not accomodating other types of complex values } } } } catch (...) { PyErr_Clear(); } #endif } template<typename T> void WrappedArray::convertNumpyArrayC(const T* array, const std::vector<int>& strides) const { // this method is only called by the constructor above which does the // necessary checks and initialisations int size=DataTypes::noValues(shape); dat_c=new cplx_t[size]; switch (rank) { case 1: #pragma omp parallel for for (int i=0;i<shape[0];i++) { dat_c[i]=array[i*strides[0]]; } break; case 2: #pragma omp parallel for for (int i=0;i<shape[0];i++) { for (int j=0;j<shape[1];j++) { dat_c[DataTypes::getRelIndex(shape,i,j)]=array[i*strides[0]+j*strides[1]]; } } break; case 3: #pragma omp parallel for for (int i=0;i<shape[0];i++) { for (int j=0;j<shape[1];j++) { for (int k=0;k<shape[2];k++) { dat_c[DataTypes::getRelIndex(shape,i,j,k)]=array[i*strides[0]+j*strides[1]+k*strides[2]]; } } } break; case 4: #pragma omp parallel for for (int i=0;i<shape[0];i++) { for (int j=0;j<shape[1];j++) { for (int k=0;k<shape[2];k++) { for (int m=0;m<shape[3];m++) { dat_c[DataTypes::getRelIndex(shape,i,j,k,m)]=array[i*strides[0]+j*strides[1]+k*strides[2]+m*strides[3]]; } } } } break; } } template<typename T> void WrappedArray::convertNumpyArray(const T* array, const std::vector<int>& strides) const { // this method is only called by the constructor above which does the // necessary checks and initialisations int size=DataTypes::noValues(shape); dat_r=new real_t[size]; switch (rank) { case 1: #pragma omp parallel for for (int i=0;i<shape[0];i++) { dat_r[i]=array[i*strides[0]]; } break; case 2: #pragma omp parallel for for (int i=0;i<shape[0];i++) { for (int j=0;j<shape[1];j++) { dat_r[DataTypes::getRelIndex(shape,i,j)]=array[i*strides[0]+j*strides[1]]; } } break; case 3: #pragma omp parallel for for (int i=0;i<shape[0];i++) { for (int j=0;j<shape[1];j++) { for (int k=0;k<shape[2];k++) { dat_r[DataTypes::getRelIndex(shape,i,j,k)]=array[i*strides[0]+j*strides[1]+k*strides[2]]; } } } break; case 4: #pragma omp parallel for for (int i=0;i<shape[0];i++) { for (int j=0;j<shape[1];j++) { for (int k=0;k<shape[2];k++) { for (int m=0;m<shape[3];m++) { dat_r[DataTypes::getRelIndex(shape,i,j,k,m)]=array[i*strides[0]+j*strides[1]+k*strides[2]+m*strides[3]]; } } } } break; } } void WrappedArray::convertArrayR() const { if ((converted) || (rank<=0) || (rank>4)) // checking illegal rank here to avoid memory issues later { // yes the failure is silent here but not doing the copy return; // will just cause an error to be raised later } int size=DataTypes::noValues(shape); real_t* tdat=new real_t[size]; switch (rank) { case 1: for (int i=0;i<shape[0];i++) { tdat[i]=getElt(i); } break; case 2: for (int i=0;i<shape[0];i++) { for (int j=0;j<shape[1];j++) { tdat[DataTypes::getRelIndex(shape,i,j)]=getElt(i,j); } } break; case 3: for (int i=0;i<shape[0];i++) { for (int j=0;j<shape[1];j++) { for (int k=0;k<shape[2];k++) { tdat[DataTypes::getRelIndex(shape,i,j,k)]=getElt(i,j,k); } } } break; case 4: for (int i=0;i<shape[0];i++) { for (int j=0;j<shape[1];j++) { for (int k=0;k<shape[2];k++) { for (int m=0;m<shape[3];m++) { tdat[DataTypes::getRelIndex(shape,i,j,k,m)]=getElt(i,j,k,m); } } } } break; default: ; // do nothing // can't happen. We've already checked the bounds above } dat_r=tdat; converted=true; } void WrappedArray::convertArrayC() const { if ((converted) || (rank<=0) || (rank>4)) // checking illegal rank here to avoid memory issues later { // yes the failure is silent here but not doing the copy return; // will just cause an error to be raised later } int size=DataTypes::noValues(shape); cplx_t* tdat=new cplx_t[size]; switch (rank) { case 1: for (int i=0;i<shape[0];i++) { tdat[i]=getElt(i); } break; case 2: for (int i=0;i<shape[0];i++) { for (int j=0;j<shape[1];j++) { tdat[DataTypes::getRelIndex(shape,i,j)]=getElt(i,j); } } break; case 3: for (int i=0;i<shape[0];i++) { for (int j=0;j<shape[1];j++) { for (int k=0;k<shape[2];k++) { tdat[DataTypes::getRelIndex(shape,i,j,k)]=getElt(i,j,k); } } } break; case 4: for (int i=0;i<shape[0];i++) { for (int j=0;j<shape[1];j++) { for (int k=0;k<shape[2];k++) { for (int m=0;m<shape[3];m++) { tdat[DataTypes::getRelIndex(shape,i,j,k,m)]=getElt(i,j,k,m); } } } } break; default: ; // do nothing // can't happen. We've already checked the bounds above } dat_c=tdat; converted=true; } void WrappedArray::convertArray() const { if (iscomplex) { convertArrayC(); } else { convertArrayR(); } } WrappedArray::~WrappedArray() { if (dat_r!=0) { delete[] dat_r; } if (dat_c!=0) { delete[] dat_c; } }
12,031
5,439
// Copyright Ryan Schmidt 2011. // Distributed under the Boost Software License, Version 1.0. // (See copy at http://www.boost.org/LICENSE_1_0.txt) #include "VertexWeights.h" #include "VectorUtil.h" #include "rmsdebug.h" using namespace rms; void VertexWeights::Uniform( VFTriangleMesh & mesh, IMesh::VertexID vID, std::vector<IMesh::VertexID> & vNeighbourhood, std::vector<float> & vWeights, bool bNormalize ) { size_t nNbrs = vNeighbourhood.size(); vWeights.resize(nNbrs); for ( unsigned int k = 0; k < nNbrs; ++k ) vWeights[k] = 1.0f; if ( bNormalize ) { float fWeightSum = (float)nNbrs; for ( unsigned int k = 0; k < nNbrs; ++k ) vWeights[k] /= fWeightSum; } } void VertexWeights::InverseDistance( VFTriangleMesh & mesh, IMesh::VertexID vID, std::vector<IMesh::VertexID> & vNeighbourhood, std::vector<float> & vWeights, float fPow, float fEps, bool bNormalize ) { Wml::Vector3f vVtx, vNbr; mesh.GetVertex(vID, vVtx); float fWeightSum = 0.0f; size_t nNbrs = vNeighbourhood.size(); vWeights.resize(nNbrs); for ( unsigned int k = 0; k < nNbrs; ++k ) { mesh.GetVertex( vNeighbourhood[k], vNbr ); float fDist = (vNbr - vVtx).Length(); vWeights[k] = 1.0f / (fEps + pow(fDist,fPow)); fWeightSum += vWeights[k]; } if ( bNormalize ) { float fWeightSum = (float)nNbrs; for ( unsigned int k = 0; k < nNbrs; ++k ) vWeights[k] /= fWeightSum; } } //! assumes one-ring is ordered void VertexWeights::Cotangent( VFTriangleMesh & mesh, IMesh::VertexID vID, std::vector<IMesh::VertexID> & vOneRing, std::vector<float> & vWeights, bool bNormalize ) { Wml::Vector3f vVtx, vOpp, vPrev, vNext; size_t nNbrs = vOneRing.size(); mesh.GetVertex(vID, vVtx); mesh.GetVertex(vOneRing[0], vOpp); mesh.GetVertex(vOneRing[nNbrs-1], vPrev); vWeights.resize(nNbrs); float fWeightSum = 0.0f; for ( unsigned int k = 0; k < nNbrs; ++k ) { IMesh::VertexID nNext = vOneRing[(k+1)%nNbrs]; mesh.GetVertex(nNext, vNext); Wml::Vector3f a1(vVtx - vPrev); a1.Normalize(); Wml::Vector3f a2(vOpp - vPrev); a2.Normalize(); float fADot = a1.Dot(a2); double fAlpha = acos( rms::Clamp(fADot, -1.0f, 1.0f) ); Wml::Vector3f b1(vVtx - vNext); b1.Normalize(); Wml::Vector3f b2(vOpp - vNext); b2.Normalize(); float fBDot = b1.Dot(b2); double fBeta = acos( rms::Clamp(fBDot, -1.0f, 1.0f) ); vWeights[k] = (float)( 1/tan(fAlpha) + 1/tan(fBeta) ); if ( ! _finite(vWeights[k]) ) _RMSInfo("MeshUtils::CotangentWeights():: non-finite weight at vertex %d [%d/%d] alpha d/a: %f/%f beta d/a: %f/%f\n", vOneRing[k], k, nNbrs, fADot,fAlpha, fBDot, fBeta); fWeightSum += vWeights[k]; vPrev = vOpp; vOpp = vNext; } if ( bNormalize ) { for ( unsigned int k = 0; k < nNbrs; ++k ) vWeights[k] /= fWeightSum; } }
2,945
1,437
// -*- mode: c++ -*- /********************************************************************* * Software License Agreement (BSD License) * * Copyright (c) 2014, JSK Lab * 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/o2r other materials provided * with the distribution. * * Neither the name of the JSK Lab 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. *********************************************************************/ #define BOOST_PARAMETER_MAX_ARITY 7 #include "jsk_recognition_utils/geo/cylinder.h" #include "jsk_recognition_utils/geo_util.h" namespace jsk_recognition_utils { Cylinder::Cylinder(Eigen::Vector3f point, Eigen::Vector3f direction, double radius): point_(point), direction_(direction), radius_(radius) { } void Cylinder::filterPointCloud(const pcl::PointCloud<pcl::PointXYZ>& cloud, const double threshold, pcl::PointIndices& output) { Line line(direction_, point_); output.indices.clear(); for (size_t i = 0; i < cloud.points.size(); i++) { Eigen::Vector3f p = cloud.points[i].getVector3fMap(); double d = line.distanceToPoint(p); if (d < radius_ + threshold && d > radius_ - threshold) { output.indices.push_back(i); } } } void Cylinder::estimateCenterAndHeight(const pcl::PointCloud<pcl::PointXYZ>& cloud, const pcl::PointIndices& indices, Eigen::Vector3f& center, double& height) { Line line(direction_, point_); Vertices points; for (size_t i = 0; i < indices.indices.size(); i++) { int point_index = indices.indices[i]; points.push_back(cloud.points[point_index].getVector3fMap()); } PointPair min_max = line.findEndPoints(points); Eigen::Vector3f min_point = min_max.get<0>(); Eigen::Vector3f max_point = min_max.get<1>(); Eigen::Vector3f min_point_projected, max_point_projected; line.foot(min_point, min_point_projected); line.foot(max_point, max_point_projected); height = (min_point_projected - max_point_projected).norm(); center = (min_point_projected + max_point_projected) / 2.0; } void Cylinder::toMarker(visualization_msgs::Marker& marker, const Eigen::Vector3f& center, const Eigen::Vector3f& uz, const double height) { marker.type = visualization_msgs::Marker::CYLINDER; marker.pose.position.x = center[0]; marker.pose.position.y = center[1]; marker.pose.position.z = center[2]; Eigen::Vector3f orig_z(0, 0, 1); Eigen::Quaternionf q; q.setFromTwoVectors(orig_z, uz); marker.pose.orientation.x = q.x(); marker.pose.orientation.y = q.y(); marker.pose.orientation.z = q.z(); marker.pose.orientation.w = q.w(); marker.scale.x = radius_ * 2; marker.scale.y = radius_ * 2; marker.scale.z = height; marker.color.a = 1.0; marker.color.g = 1.0; marker.color.b = 1.0; } Eigen::Vector3f Cylinder::getDirection() { return direction_; } }
4,542
1,525
#ifndef SRC_CLIENT_ENVIADORESCLIENTE_ENVIADORCREDENCIALES_HPP_ #define SRC_CLIENT_ENVIADORESCLIENTE_ENVIADORCREDENCIALES_HPP_ #include "src/Utils/Enviador.hpp" class EnviadorCredenciales:public Enviador{ public: explicit EnviadorCredenciales(Socket* socket); void enviar()override; void dejarInformacion(void* informacion)override; private: credencial_t credenciales; }; #endif /* SRC_CLIENT_ENVIADORESCLIENTE_ENVIADORCREDENCIALES_HPP_ */
454
204
/** * @file GeminiClient.cpp * @brief implementation * * @author Niccolò Pieretti * @date 02 Apr 2021 * **************************************************************************** * * _ _ o __ __ __ _ o _ ,_ _ * / |/ | | / / / \_|/ \_| |/ / | |/ * | |_/|_/\__/\___/\__/ |__/ |_/|__/ |_/|__/ * /| * \| ****************************************************************************/ #include "GeminiClient.hpp" #include "Exception.hpp" #include "Protocol.hpp" #include "TslSocket.hpp" #include "Utils.hpp" #include <iostream> #include <errno.h> #include <netdb.h> #include <openssl/err.h> #include <resolv.h> #include <string.h> #include <unistd.h> // ~~~~~ ~~~~~ ~~~~~ // Implementation // ~~~~~ ~~~~~ ~~~~~ std::unique_ptr<gemini::Response> gemini::GeminiClient::getResponse(std::string request, std::unique_ptr<Socket> connection) { // Send request auto sendRes = connection->send(request); if (sendRes <= 0) { throw connection_error("Error in send request"); } // Read <STATUS><SPACE> const auto statusSize = response::HEADER_STATUS_SIZE + response::HEADER_SPACE_SIZE; char statusBuffer[statusSize + 1]; auto statusRes = connection->read(statusBuffer, statusSize); if ((size_t)statusRes < statusSize) { throw protocol_response_error("Empty response"); } if (!(response::isHeaderStatusFirstValid(statusBuffer[0]) && response::isHeaderStatusSecondValid(statusBuffer[1]))) { throw protocol_response_error("Invalid status --- response"); } if (statusBuffer[2] != ' ') { throw protocol_response_error("Invalid status response"); } std::unique_ptr<Response> response(new Response); response->statusCodeFirst = statusBuffer[0] - '0'; response->statusCodeSecond = statusBuffer[1] - '0'; // Read <META><CR><FL> const auto metaSize = response::HEADER_META_SIZE + 2; char metaBuffer[metaSize + 1]; auto metaRes = connection->read(metaBuffer, metaSize); // Check header termination if (metaRes < 2) { throw protocol_response_error("Empty header"); } // Assure metaBuffer terminates metaBuffer[metaRes > metaSize ? metaSize : metaRes] = '\0'; // Find terminators auto pos = strstr(metaBuffer, "\r\n"); if (pos == nullptr) { throw protocol_response_error("Invalid header termination"); } if ((size_t)(pos - metaBuffer) > response::HEADER_META_SIZE) { throw protocol_response_error("Invalid meta size"); } // Save meta response->meta = std::string(metaBuffer, pos); // Read <BODY> if (response->statusCodeFirst == response::HEADER_STATUS_FIRST::SUCCESS) { const auto bodyChunkSize = response::BODY_CHUNK_SIZE; char bodyBuffer[bodyChunkSize + 1]; // Copy previous part if (pos + 2 < metaBuffer + metaRes) { response->body += std::string(pos + 2, metaBuffer + metaRes); } auto bodyRes = connection->read(bodyBuffer, bodyChunkSize); while (bodyRes > 0) { // Set string terminator bodyBuffer[(size_t)bodyRes > bodyChunkSize ? bodyChunkSize : bodyRes] = '\0'; response->body += std::string(bodyBuffer); bodyRes = connection->read(bodyBuffer, bodyChunkSize); } } return response; } std::unique_ptr<gemini::Response> gemini::GeminiClient::request(const std::string url, const std::string port) { // Check url if (url.length() > request::URL_MAX_SIZE) { throw std::invalid_argument("Invalid url length: expected max " + std::to_string(request::URL_MAX_SIZE)); } // Open socket const std::string hostname = getHostnameFromUrl(url); std::unique_ptr<Socket> socket = std::unique_ptr<Socket>(new TslSocket(hostname, port)); // Build request: <URL><CR><LF> std::string request(url + gemini::CR + gemini::LF); return getResponse(request, std::move(socket)); }
3,994
1,284
#include <stdapp/stdappSplash.hpp> #define IMAGECLASS UPP_LogoImg #define IMAGEFILE <stdapp/UPP_Logo_033.iml> #include <Draw/iml_source.h> Splash::Splash(const int language, const int ms) { SetLanguage(language); SetRect(GetWorkArea().CenterRect(MakeSplash(*this, widgets) + 2)); SetFrame(BlackFrame()); PopUp(NULL, false, false, true); SetTimeCallback(ms, THISBACK(CloseSplash)); } Size Splash::MakeSplash(Ctrl& parent, Array<Ctrl>& widgets) { Image logo = UPP_LogoImg::AppLogo(); Size logo_size = logo.GetSize(); Size rect_size; rect_size.cx = max(SPLASH_RECT_CX, logo_size.cx); rect_size.cy = max(SPLASH_RECT_CY, logo_size.cy); parent.Add(widgets.Create<StaticRect>().Color(SPLASH_PAPER_COLOR).SizePos()); ImageCtrl& image = widgets.Create<ImageCtrl>(); image.SetImage(logo); image.LeftPos(0, logo_size.cx).VSizePos(); parent.Add(image); Label& label_1 = widgets.Create<Label>(); label_1.SetFont(SPLASH_FONT_1(SPLASH_FONT_SIZE_1).Bold()); label_1.SetInk(SPLASH_INK_COLOR_1); label_1 = APP_TITLE; label_1.SetAlign(ALIGN_CENTER); label_1.RightPos(0, rect_size.cx - logo_size.cx).TopPos(rect_size.cy * 1 / 9, 20); parent.Add(label_1); Label& label_2 = widgets.Create<Label>(); label_2.SetFont(SPLASH_FONT_2(SPLASH_FONT_SIZE_2).Bold()); label_2.SetInk(SPLASH_INK_COLOR_2); label_2 = APP_VERSION; label_2.SetAlign(ALIGN_CENTER); label_2.RightPos(0, rect_size.cx - logo_size.cx).TopPos(rect_size.cy * 3 / 9, 20); parent.Add(label_2); Label& label_3 = widgets.Create<Label>(); label_3.SetFont(SPLASH_FONT_3(SPLASH_FONT_SIZE_3).Italic()); label_3.SetInk(SPLASH_INK_COLOR_3); label_3 = APP_SUBTITLE; label_3.SetAlign(ALIGN_CENTER); label_3.RightPos(0, rect_size.cx - logo_size.cx).TopPos(rect_size.cy * 5 / 9, 20); parent.Add(label_3); Label& label_4 = widgets.Create<Label>(); label_4.SetFont(SPLASH_FONT_4(SPLASH_FONT_SIZE_4)); label_4.SetInk(SPLASH_INK_COLOR_4); label_4 = APP_COPYRIGHT; label_4.SetAlign(ALIGN_CENTER); label_4.RightPos(0, rect_size.cx - logo_size.cx).TopPos(rect_size.cy * 7 / 9, 20); parent.Add(label_4); return rect_size; } void Splash::CloseSplash() { Close(); }
2,343
1,026
#pragma once //SELF #include "object_model/object_internal.hpp" #include "object_model/scope.hpp" #include "object_model/call_stack.hpp" namespace element { static const std::string intrinsic_qualifier = "intrinsic"; static const std::string namespace_qualifier = "namespace"; static const std::string constraint_qualifier = "constraint"; static const std::string struct_qualifier = "struct"; static const std::string function_qualifier; //empty string static const std::string return_keyword = "return"; static const std::string unidentifier = "_"; class declaration : public object { public: explicit declaration(identifier name, const scope* parent); [[nodiscard]] std::string get_name() const final; [[nodiscard]] std::string get_qualified_name() const; [[nodiscard]] bool has_inputs() const { return !inputs.empty(); } [[nodiscard]] bool has_constraint() const { return false; } //TODO: JM - nonsense, this needs to be a constraint::something OR constraint::any [[nodiscard]] bool has_scope() const; [[nodiscard]] bool virtual is_intrinsic() const = 0; [[nodiscard]] virtual bool is_variadic() const { return false; } [[nodiscard]] const std::vector<port>& get_inputs() const override { return inputs; } [[nodiscard]] const scope* get_scope() const override { return our_scope.get(); } [[nodiscard]] const port& get_output() const override { return output; } [[nodiscard]] virtual bool serializable(const compilation_context& context) const { return false; } [[nodiscard]] virtual bool deserializable(const compilation_context& context) const { return false; } [[nodiscard]] virtual object_const_shared_ptr generate_placeholder(const compilation_context& context, std::size_t& placeholder_index, std::size_t boundary_scope) const; [[nodiscard]] virtual std::string location() const; std::string qualifier; identifier name; std::vector<port> inputs; std::unique_ptr<scope> our_scope; port output; protected: //the wrapper is used to return declarations within the object model std::shared_ptr<const declaration_wrapper> wrapper; }; } // namespace element
2,154
617
// Copyright (c) 2007-2013 Hartmut Kaiser // Copyright (c) 2011 Bryce Lelbach // // 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) /// \file hpx_fwd.hpp #if !defined(HPX_HPX_FWD_MAR_24_2008_1119AM) #define HPX_HPX_FWD_MAR_24_2008_1119AM #include <hpx/config.hpp> #include <cstdlib> #include <vector> #include <boost/config.hpp> #include <boost/version.hpp> #if BOOST_VERSION < 104200 // Please update your Boost installation (see www.boost.org for details). #error HPX cannot be compiled with a Boost version earlier than V1.42. #endif #if defined(BOOST_WINDOWS) #include <winsock2.h> #include <windows.h> #endif #include <boost/shared_ptr.hpp> #include <boost/intrusive_ptr.hpp> #include <boost/cstdint.hpp> #include <boost/thread/mutex.hpp> #include <boost/detail/scoped_enum_emulation.hpp> #include <boost/system/error_code.hpp> #include <hpx/config/function.hpp> #include <hpx/traits.hpp> #include <hpx/lcos/local/once_fwd.hpp> #include <hpx/util/unused.hpp> #include <hpx/util/move.hpp> #include <hpx/util/remove_reference.hpp> #include <hpx/util/coroutine/coroutine.hpp> #include <hpx/runtime/threads/detail/tagged_thread_state.hpp> /// \namespace hpx /// /// The namespace \a hpx is the main namespace of the HPX library. All classes /// functions and variables are defined inside this namespace. namespace hpx { /// \cond NOINTERNAL class error_code; HPX_EXCEPTION_EXPORT extern error_code throws; /// \namespace applier /// /// The namespace \a applier contains all definitions needed for the /// class \a hpx#applier#applier and its related functionality. This /// namespace is part of the HPX core module. namespace applier { class HPX_API_EXPORT applier; /// The function \a get_applier returns a reference to the (thread /// specific) applier instance. HPX_API_EXPORT applier& get_applier(); HPX_API_EXPORT applier* get_applier_ptr(); } namespace agas { struct HPX_API_EXPORT addressing_service; enum service_mode { service_mode_invalid = -1, service_mode_bootstrap = 0, service_mode_hosted = 1 }; } /// \namespace naming /// /// The namespace \a naming contains all definitions needed for the AGAS /// (Active Global Address Space) service. namespace naming { typedef agas::addressing_service resolver_client; struct HPX_API_EXPORT gid_type; struct HPX_API_EXPORT id_type; struct HPX_API_EXPORT address; class HPX_API_EXPORT locality; HPX_API_EXPORT resolver_client& get_agas_client(); } /////////////////////////////////////////////////////////////////////////// /// \namespace parcelset namespace parcelset { enum connection_type { connection_unknown = -1, connection_tcpip = 0, connection_shmem = 1, connection_portals4 = 2, connection_ibverbs = 3, connection_mpi = 4, connection_last }; class HPX_API_EXPORT parcel; class HPX_API_EXPORT parcelport; class HPX_API_EXPORT parcelhandler; namespace server { class parcelport_queue; } struct parcelhandler_queue_base; namespace policies { struct global_parcelhandler_queue; typedef global_parcelhandler_queue parcelhandler_queue; struct message_handler; } HPX_API_EXPORT std::string get_connection_type_name(connection_type); HPX_API_EXPORT connection_type get_connection_type_from_name(std::string const&); HPX_API_EXPORT policies::message_handler* get_message_handler( parcelhandler* ph, char const* name, char const* type, std::size_t num, std::size_t interval, naming::locality const& l, connection_type t, error_code& ec = throws); HPX_API_EXPORT void do_background_work(); } /// \namespace threads /// /// The namespace \a threadmanager contains all the definitions required /// for the scheduling, execution and general management of \a /// hpx#threadmanager#thread's. namespace threads { namespace policies { struct scheduler_base; #if defined(HPX_GLOBAL_SCHEDULER) class HPX_EXPORT global_queue_scheduler; #endif #if defined(HPX_STATIC_PRIORITY_SCHEDULER) template <typename Mutex = boost::mutex> class HPX_API_EXPORT static_priority_queue_scheduler; #endif #if defined(HPX_ABP_SCHEDULER) struct HPX_EXPORT abp_queue_scheduler; #endif #if defined(HPX_ABP_PRIORITY_SCHEDULER) class HPX_EXPORT abp_priority_queue_scheduler; #endif template <typename Mutex = boost::mutex> class HPX_EXPORT local_queue_scheduler; template <typename Mutex = boost::mutex> class HPX_EXPORT local_priority_queue_scheduler; #if defined(HPX_HIERARCHY_SCHEDULER) class HPX_EXPORT hierarchy_scheduler; #endif #if defined(HPX_PERIODIC_PRIORITY_SCHEDULER) class HPX_EXPORT periodic_priority_scheduler; #endif class HPX_EXPORT callback_notifier; // define the default scheduler to use typedef local_priority_queue_scheduler<> queue_scheduler; } struct HPX_EXPORT threadmanager_base; class HPX_EXPORT thread_data; template < typename SchedulingPolicy, typename NotificationPolicy = threads::policies::callback_notifier> class HPX_EXPORT threadmanager_impl; /// \enum thread_state_enum /// /// The \a thread_state_enum enumerator encodes the current state of a /// \a thread instance enum thread_state_enum { unknown = 0, active = 1, /*!< thread is currently active (running, has resources) */ pending = 2, /*!< thread is pending (ready to run, but no hardware resource available) */ suspended = 3, /*!< thread has been suspended (waiting for synchronization event, but still known and under control of the threadmanager) */ depleted = 4, /*!< thread has been depleted (deeply suspended, it is not known to the thread manager) */ terminated = 5, /*!< thread has been stopped an may be garbage collected */ staged = 6 /*!< this is not a real thread state, but allows to reference staged task descriptions, which eventually will be converted into thread objects */ }; /// \ cond NODETAIL /// Please note that if you change the value of threads::terminated /// above, you will need to adjust do_call(dummy<1> = 1) in /// util/coroutine/detail/coroutine_impl.hpp as well. /// \ endcond /// \enum thread_priority enum thread_priority { thread_priority_unknown = -1, thread_priority_default = 0, ///< use default priority thread_priority_low = 1, ///< low thread priority thread_priority_normal = 2, ///< normal thread priority (default) thread_priority_critical = 3 ///< high thread priority }; typedef threads::detail::tagged_thread_state<thread_state_enum> thread_state; HPX_API_EXPORT char const* get_thread_state_name(thread_state_enum state); HPX_API_EXPORT char const* get_thread_priority_name(thread_priority priority); /// \enum thread_state_ex_enum /// /// The \a thread_state_ex_enum enumerator encodes the reason why a /// thread is being restarted enum thread_state_ex_enum { wait_unknown = -1, wait_signaled = 0, ///< The thread has been signaled wait_timeout = 1, ///< The thread has been reactivated after a timeout wait_terminate = 2, ///< The thread needs to be terminated wait_abort = 3 ///< The thread needs to be aborted }; typedef threads::detail::tagged_thread_state<thread_state_ex_enum> thread_state_ex; typedef thread_state_enum thread_function_type(thread_state_ex_enum); /// \enum thread_stacksize enum thread_stacksize { thread_stacksize_small = 1, ///< use small stack size thread_stacksize_medium = 2, ///< use medium sized stack size thread_stacksize_large = 3, ///< use large stack size thread_stacksize_huge = 4, ///< use very large stack size thread_stacksize_nostack = 5, ///< this thread does not suspend (does not need a stack) thread_stacksize_default = thread_stacksize_small, ///< use default stack size thread_stacksize_minimal = thread_stacksize_small, ///< use minimally possible stack size thread_stacksize_maximal = thread_stacksize_huge, ///< use maximally possible stack size }; /////////////////////////////////////////////////////////////////////// /// \ cond NODETAIL namespace detail { template <typename CoroutineImpl> struct coroutine_allocator; } /// \ endcond typedef util::coroutines::coroutine< thread_function_type, detail::coroutine_allocator> coroutine_type; typedef coroutine_type::thread_id_type thread_id_type; typedef coroutine_type::self thread_self; /////////////////////////////////////////////////////////////////////// /// \ cond NODETAIL thread_id_type const invalid_thread_id = reinterpret_cast<thread_id_type>(-1); /// \ endcond /// The function \a get_self returns a reference to the (OS thread /// specific) self reference to the current PX thread. HPX_API_EXPORT thread_self& get_self(); /// The function \a get_self_ptr returns a pointer to the (OS thread /// specific) self reference to the current PX thread. HPX_API_EXPORT thread_self* get_self_ptr(); /// The function \a get_ctx_ptr returns a pointer to the internal data /// associated with each coroutine. HPX_API_EXPORT thread_self::impl_type* get_ctx_ptr(); /// The function \a get_self_ptr_checked returns a pointer to the (OS /// thread specific) self reference to the current HPX thread. HPX_API_EXPORT thread_self* get_self_ptr_checked(error_code& ec = throws); /// The function \a get_self_id returns the HPX thread id of the current /// thread (or zero if the current thread is not a PX thread). HPX_API_EXPORT thread_id_type get_self_id(); /// The function \a get_parent_id returns the HPX thread id of the /// current's thread parent (or zero if the current thread is not a /// PX thread). /// /// \note This function will return a meaningful value only if the /// code was compiled with HPX_THREAD_MAINTAIN_PARENT_REFERENCE /// being defined. HPX_API_EXPORT thread_id_type get_parent_id(); /// The function \a get_parent_phase returns the HPX phase of the /// current's thread parent (or zero if the current thread is not a /// PX thread). /// /// \note This function will return a meaningful value only if the /// code was compiled with HPX_THREAD_MAINTAIN_PARENT_REFERENCE /// being defined. HPX_API_EXPORT std::size_t get_parent_phase(); /// The function \a get_parent_locality_id returns the id of the locality of /// the current's thread parent (or zero if the current thread is not a /// PX thread). /// /// \note This function will return a meaningful value only if the /// code was compiled with HPX_THREAD_MAINTAIN_PARENT_REFERENCE /// being defined. HPX_API_EXPORT boost::uint32_t get_parent_locality_id(); /// The function \a get_self_component_id returns the lva of the /// component the current thread is acting on /// /// \note This function will return a meaningful value only if the /// code was compiled with HPX_THREAD_MAINTAIN_TARGET_ADDRESS /// being defined. HPX_API_EXPORT boost::uint64_t get_self_component_id(); /// The function \a get_thread_manager returns a reference to the /// current thread manager. HPX_API_EXPORT threadmanager_base& get_thread_manager(); /// The function \a get_thread_count returns the number of currently /// known threads. /// /// \note If state == unknown this function will not only return the /// number of currently existing threads, but will add the number /// of registered task descriptions (which have not been /// converted into threads yet). HPX_API_EXPORT boost::int64_t get_thread_count( thread_state_enum state = unknown); /// \copydoc get_thread_count(thread_state_enum state) HPX_API_EXPORT boost::int64_t get_thread_count( thread_priority priority, thread_state_enum state = unknown); } /// \namespace actions /// /// The namespace \a actions contains all definitions needed for the /// class \a hpx#action_manager#action_manager and its related /// functionality. This namespace is part of the HPX core module. namespace actions { struct HPX_API_EXPORT base_action; typedef boost::shared_ptr<base_action> action_type; class HPX_API_EXPORT continuation; typedef boost::shared_ptr<continuation> continuation_type; class HPX_API_EXPORT action_manager; template <typename Component, typename Result, typename Arguments, typename Derived> struct action; } class HPX_API_EXPORT runtime; class HPX_API_EXPORT thread; /// A HPX runtime can be executed in two different modes: console mode /// and worker mode. enum runtime_mode { runtime_mode_invalid = -1, runtime_mode_console = 0, ///< The runtime is the console locality runtime_mode_worker = 1, ///< The runtime is a worker locality runtime_mode_connect = 2, ///< The runtime is a worker locality ///< connecting late runtime_mode_default = 3, ///< The runtime mode will be determined ///< based on the command line arguments runtime_mode_last }; /// Get the readable string representing the name of the given runtime_mode /// constant. HPX_API_EXPORT char const* get_runtime_mode_name(runtime_mode state); HPX_API_EXPORT runtime_mode get_runtime_mode_from_name(std::string const& mode); /////////////////////////////////////////////////////////////////////////// /// Retrieve the string value of a configuration entry as given by \p key. HPX_API_EXPORT std::string get_config_entry(std::string const& key, std::string const& dflt); /// Retrieve the integer value of a configuration entry as given by \p key. HPX_API_EXPORT std::string get_config_entry(std::string const& key, std::size_t dflt); /////////////////////////////////////////////////////////////////////////// template < typename SchedulingPolicy, typename NotificationPolicy = threads::policies::callback_notifier> class HPX_API_EXPORT runtime_impl; /// The function \a get_runtime returns a reference to the (thread /// specific) runtime instance. HPX_API_EXPORT runtime& get_runtime(); HPX_API_EXPORT runtime* get_runtime_ptr(); /// The function \a get_locality returns a reference to the locality HPX_API_EXPORT naming::locality const& get_locality(); /// The function \a get_runtime_instance_number returns a unique number /// associated with the runtime instance the current thread is running in. HPX_API_EXPORT std::size_t get_runtime_instance_number(); HPX_API_EXPORT void report_error(std::size_t num_thread , boost::exception_ptr const& e); HPX_API_EXPORT void report_error(boost::exception_ptr const& e); /// Register a function to be called during system shutdown HPX_API_EXPORT bool register_on_exit(HPX_STD_FUNCTION<void()> const&); enum logging_destination { destination_hpx = 0, destination_timing = 1, destination_agas = 2, destination_app = 3 }; /// \namespace components namespace components { enum factory_state_enum { factory_enabled = 0, factory_disabled = 1, factory_check = 2 }; /// \ cond NODETAIL namespace detail { struct this_type {}; struct fixed_component_tag {}; struct simple_component_tag {}; struct managed_component_tag {}; } /// \ endcond /////////////////////////////////////////////////////////////////////// typedef boost::int32_t component_type; enum component_enum_type { component_invalid = -1, // Runtime support component (provides system services such as // component creation, etc). One per locality. component_runtime_support = 0, // Pseudo-component for direct access to local virtual memory. component_memory = 1, // Generic memory blocks. component_memory_block = 2, // Base component for LCOs that do not produce a value. component_base_lco = 3, // Base component for LCOs that do produce values. component_base_lco_with_value = 4, // Synchronization barrier LCO. component_barrier = ((5 << 16) | component_base_lco), // An LCO representing a value which may not have been computed yet. component_promise = ((6 << 16) | component_base_lco_with_value), // AGAS locality services. component_agas_locality_namespace = 7, // AGAS primary address resolution services. component_agas_primary_namespace = 8, // AGAS global type system. component_agas_component_namespace = 9, // AGAS symbolic naming services. component_agas_symbol_namespace = 10, #if defined(HPX_HAVE_SODIUM) // root CA, subordinate CA component_root_certificate_authority = 11, component_subordinate_certificate_authority = 12, #endif component_last, component_first_dynamic = component_last, // Force this enum type to be at least 32 bits. component_upper_bound = 0x7fffffffL //-V112 }; /////////////////////////////////////////////////////////////////////// template <typename Component = detail::this_type> class fixed_component_base; template <typename Component> class fixed_component; template <typename Component = detail::this_type> class abstract_simple_component_base; template <typename Component = detail::this_type> class simple_component_base; template <typename Component> class simple_component; template <typename Component, typename Derived = detail::this_type> class abstract_managed_component_base; template <typename Component, typename Wrapper = detail::this_type, typename CtorPolicy = traits::construct_without_back_ptr, typename DtorPolicy = traits::managed_object_controls_lifetime> class managed_component_base; template <typename Component, typename Derived = detail::this_type> class managed_component; struct HPX_API_EXPORT component_factory_base; template <typename Component> struct component_factory; class runtime_support; class memory; class memory_block; namespace stubs { struct runtime_support; struct memory; struct memory_block; } namespace server { class HPX_API_EXPORT runtime_support; class HPX_API_EXPORT memory; class HPX_API_EXPORT memory_block; } HPX_EXPORT void console_logging(logging_destination dest, std::size_t level, std::string const& msg); HPX_EXPORT void cleanup_logging(); HPX_EXPORT void activate_logging(); } HPX_EXPORT components::server::runtime_support* get_runtime_support_ptr(); /// \namespace lcos namespace lcos { class base_lco; template <typename Result, typename RemoteResult = Result> class base_lco_with_value; template <typename Result, typename RemoteResult = typename traits::promise_remote_result<Result>::type> class promise; template <typename Action, typename Result = typename traits::promise_local_result< typename Action::result_type>::type, typename DirectExecute = typename Action::direct_execution> class packaged_action; template <typename Action, typename Result = typename traits::promise_local_result< typename Action::result_type>::type, typename DirectExecute = typename Action::direct_execution> class deferred_packaged_task; template <typename Result> class future; template <typename ValueType> struct object_semaphore; namespace stubs { template <typename ValueType> struct object_semaphore; } namespace server { template <typename ValueType> struct object_semaphore; } } /// \namespace util namespace util { struct binary_filter; class HPX_EXPORT section; class HPX_EXPORT runtime_configuration; class HPX_EXPORT io_service_pool; /// \brief Expand INI variables in a string HPX_API_EXPORT std::string expand(std::string const& expand); /// \brief Expand INI variables in a string HPX_API_EXPORT void expand(std::string& expand); } namespace performance_counters { struct counter_info; } /////////////////////////////////////////////////////////////////////////// // Launch policy for \a hpx::async BOOST_SCOPED_ENUM_START(launch) { async = 0x01, deferred = 0x02, task = 0x04, // see N3632 sync = 0x08, all = 0x0f // async | deferred | task | sync }; BOOST_SCOPED_ENUM_END inline bool operator&(BOOST_SCOPED_ENUM(launch) lhs, BOOST_SCOPED_ENUM(launch) rhs) { return static_cast<int>(lhs) & static_cast<int>(rhs) ? true : false; } /////////////////////////////////////////////////////////////////////////// /// \brief Return the number of OS-threads running in the runtime instance /// the current HPX-thread is associated with. HPX_API_EXPORT std::size_t get_os_thread_count(); /////////////////////////////////////////////////////////////////////////// HPX_API_EXPORT bool is_scheduler_numa_sensitive(); /////////////////////////////////////////////////////////////////////////// HPX_API_EXPORT util::runtime_configuration const& get_config(); /////////////////////////////////////////////////////////////////////////// HPX_API_EXPORT hpx::util::io_service_pool* get_thread_pool(char const* name); /////////////////////////////////////////////////////////////////////////// // Pulling important types into the main namespace using naming::id_type; using lcos::future; using lcos::promise; /// \endcond } namespace hpx { /////////////////////////////////////////////////////////////////////////// /// \brief Return the global id representing this locality /// /// The function \a find_here() can be used to retrieve the global id /// usable to refer to the current locality. /// /// \param ec [in,out] this represents the error status on exit, if this /// is pre-initialized to \a hpx#throws the function will throw /// on error instead. /// /// \note Generally, the id of a locality can be used for instance to /// create new instances of components and to invoke plain actions /// (global functions). /// /// \returns The global id representing the locality this function has /// been called on. /// /// \note As long as \a ec is not pre-initialized to \a hpx::throws this /// function doesn't throw but returns the result code using the /// parameter \a ec. Otherwise it throws an instance of /// hpx::exception. /// /// \note This function will return meaningful results only if called /// from an HPX-thread. It will return \a hpx::naming::invalid_id /// otherwise. /// /// \see \a hpx::find_all_localities(), \a hpx::find_locality() HPX_API_EXPORT naming::id_type find_here(error_code& ec = throws); /////////////////////////////////////////////////////////////////////////// /// \brief Return the global id representing the root locality /// /// The function \a find_root_locality() can be used to retrieve the global /// id usable to refer to the root locality. The root locality is the /// locality where the main AGAS service is hosted. /// /// \param ec [in,out] this represents the error status on exit, if this /// is pre-initialized to \a hpx#throws the function will throw /// on error instead. /// /// \note Generally, the id of a locality can be used for instance to /// create new instances of components and to invoke plain actions /// (global functions). /// /// \returns The global id representing the root locality for this /// application. /// /// \note As long as \a ec is not pre-initialized to \a hpx::throws this /// function doesn't throw but returns the result code using the /// parameter \a ec. Otherwise it throws an instance of /// hpx::exception. /// /// \note This function will return meaningful results only if called /// from an HPX-thread. It will return \a hpx::naming::invalid_id /// otherwise. /// /// \see \a hpx::find_all_localities(), \a hpx::find_locality() HPX_API_EXPORT naming::id_type find_root_locality(error_code& ec = throws); /////////////////////////////////////////////////////////////////////////// /// \brief Return the list of global ids representing all localities /// available to this application. /// /// The function \a find_all_localities() can be used to retrieve the /// global ids of all localities currently available to this application. /// /// \param ec [in,out] this represents the error status on exit, if this /// is pre-initialized to \a hpx#throws the function will throw /// on error instead. /// /// \note Generally, the id of a locality can be used for instance to /// create new instances of components and to invoke plain actions /// (global functions). /// /// \returns The global ids representing the localities currently /// available to this application. /// /// \note As long as \a ec is not pre-initialized to \a hpx::throws this /// function doesn't throw but returns the result code using the /// parameter \a ec. Otherwise it throws an instance of /// hpx::exception. /// /// \note This function will return meaningful results only if called /// from an HPX-thread. It will return an empty vector otherwise. /// /// \see \a hpx::find_here(), \a hpx::find_locality() HPX_API_EXPORT std::vector<naming::id_type> find_all_localities( error_code& ec = throws); /////////////////////////////////////////////////////////////////////////// /// \brief Return the list of global ids representing all localities /// available to this application which support the given component /// type. /// /// The function \a find_all_localities() can be used to retrieve the /// global ids of all localities currently available to this application /// which support the creation of instances of the given component type. /// /// \note Generally, the id of a locality can be used for instance to /// create new instances of components and to invoke plain actions /// (global functions). /// /// \param type [in] The type of the components for which the function should /// return the available localities. /// \param ec [in,out] this represents the error status on exit, if this /// is pre-initialized to \a hpx#throws the function will throw /// on error instead. /// /// \returns The global ids representing the localities currently /// available to this application which support the creation of /// instances of the given component type. If no localities /// supporting the given component type are currently available, /// this function will return an empty vector. /// /// \note As long as \a ec is not pre-initialized to \a hpx::throws this /// function doesn't throw but returns the result code using the /// parameter \a ec. Otherwise it throws an instance of /// hpx::exception. /// /// \note This function will return meaningful results only if called /// from an HPX-thread. It will return an empty vector otherwise. /// /// \see \a hpx::find_here(), \a hpx::find_locality() HPX_API_EXPORT std::vector<naming::id_type> find_all_localities( components::component_type type, error_code& ec = throws); /// \brief Return the list of locality ids of remote localities supporting /// the given component type. By default this function will return /// the list of all remote localities (all but the current locality). /// /// The function \a find_remote_localities() can be used to retrieve the /// global ids of all remote localities currently available to this /// application (i.e. all localities except the current one). /// /// \param ec [in,out] this represents the error status on exit, if this /// is pre-initialized to \a hpx#throws the function will throw /// on error instead. /// /// \note Generally, the id of a locality can be used for instance to /// create new instances of components and to invoke plain actions /// (global functions). /// /// \returns The global ids representing the remote localities currently /// available to this application. /// /// \note As long as \a ec is not pre-initialized to \a hpx::throws this /// function doesn't throw but returns the result code using the /// parameter \a ec. Otherwise it throws an instance of /// hpx::exception. /// /// \note This function will return meaningful results only if called /// from an HPX-thread. It will return an empty vector otherwise. /// /// \see \a hpx::find_here(), \a hpx::find_locality() HPX_API_EXPORT std::vector<naming::id_type> find_remote_localities( error_code& ec = throws); /// \brief Return the list of locality ids of remote localities supporting /// the given component type. By default this function will return /// the list of all remote localities (all but the current locality). /// /// The function \a find_remote_localities() can be used to retrieve the /// global ids of all remote localities currently available to this /// application (i.e. all localities except the current one) which /// support the creation of instances of the given component type. /// /// \param type [in] The type of the components for which the function should /// return the available remote localities. /// \param ec [in,out] this represents the error status on exit, if this /// is pre-initialized to \a hpx#throws the function will throw /// on error instead. /// /// \note Generally, the id of a locality can be used for instance to /// create new instances of components and to invoke plain actions /// (global functions). /// /// \returns The global ids representing the remote localities currently /// available to this application. /// /// \note As long as \a ec is not pre-initialized to \a hpx::throws this /// function doesn't throw but returns the result code using the /// parameter \a ec. Otherwise it throws an instance of /// hpx::exception. /// /// \note This function will return meaningful results only if called /// from an HPX-thread. It will return an empty vector otherwise. /// /// \see \a hpx::find_here(), \a hpx::find_locality() HPX_API_EXPORT std::vector<naming::id_type> find_remote_localities( components::component_type type, error_code& ec = throws); /////////////////////////////////////////////////////////////////////////// /// \brief Return the global id representing an arbitrary locality which /// supports the given component type. /// /// The function \a find_locality() can be used to retrieve the /// global id of an arbitrary locality currently available to this /// application which supports the creation of instances of the given /// component type. /// /// \note Generally, the id of a locality can be used for instance to /// create new instances of components and to invoke plain actions /// (global functions). /// /// \param type [in] The type of the components for which the function should /// return any available locality. /// \param ec [in,out] this represents the error status on exit, if this /// is pre-initialized to \a hpx#throws the function will throw /// on error instead. /// /// \returns The global id representing an arbitrary locality currently /// available to this application which supports the creation of /// instances of the given component type. If no locality /// supporting the given component type is currently available, /// this function will return \a hpx::naming::invalid_id. /// /// \note As long as \a ec is not pre-initialized to \a hpx::throws this /// function doesn't throw but returns the result code using the /// parameter \a ec. Otherwise it throws an instance of /// hpx::exception. /// /// \note This function will return meaningful results only if called /// from an HPX-thread. It will return \a hpx::naming::invalid_id /// otherwise. /// /// \see \a hpx::find_here(), \a hpx::find_all_localities() HPX_API_EXPORT naming::id_type find_locality(components::component_type type, error_code& ec = throws); /////////////////////////////////////////////////////////////////////////// /// \brief Return the number of localities which are currently registered /// for the running application. /// /// The function \a get_num_localities returns the number of localities /// currently connected to the console. /// /// \note This function will return meaningful results only if called /// from an HPX-thread. It will return 0 otherwise. /// /// \note As long as \a ec is not pre-initialized to \a hpx::throws this /// function doesn't throw but returns the result code using the /// parameter \a ec. Otherwise it throws an instance of /// hpx::exception. /// /// \see \a hpx::find_all_localities_sync, \a hpx::get_num_localities HPX_API_EXPORT boost::uint32_t get_num_localities_sync(error_code& ec = throws); /// \brief Return the number of localities which were registered at startup /// for the running application. /// /// The function \a get_initial_num_localities returns the number of localities /// which were connected to the console at application startup. /// /// \note As long as \a ec is not pre-initialized to \a hpx::throws this /// function doesn't throw but returns the result code using the /// parameter \a ec. Otherwise it throws an instance of /// hpx::exception. /// /// \see \a hpx::find_all_localities, \a hpx::get_num_localities HPX_API_EXPORT boost::uint32_t get_initial_num_localities(); /////////////////////////////////////////////////////////////////////////// /// \brief Asynchronously return the number of localities which are /// currently registered for the running application. /// /// The function \a get_num_localities asynchronously returns the /// number of localities currently connected to the console. The returned /// future represents the actual result. /// /// \note This function will return meaningful results only if called /// from an HPX-thread. It will return 0 otherwise. /// /// \see \a hpx::find_all_localities, \a hpx::get_num_localities HPX_API_EXPORT lcos::future<boost::uint32_t> get_num_localities(); /// \brief Return the number of localities which are currently registered /// for the running application. /// /// The function \a get_num_localities returns the number of localities /// currently connected to the console which support the creation of the /// given component type. /// /// \param t The component type for which the number of connected /// localities should be retrieved. /// \param ec [in,out] this represents the error status on exit, if this /// is pre-initialized to \a hpx#throws the function will throw /// on error instead. /// /// \note This function will return meaningful results only if called /// from an HPX-thread. It will return 0 otherwise. /// /// \note As long as \a ec is not pre-initialized to \a hpx::throws this /// function doesn't throw but returns the result code using the /// parameter \a ec. Otherwise it throws an instance of /// hpx::exception. /// /// \see \a hpx::find_all_localities, \a hpx::get_num_localities HPX_API_EXPORT boost::uint32_t get_num_localities_sync( components::component_type t, error_code& ec = throws); /// \brief Asynchronously return the number of localities which are /// currently registered for the running application. /// /// The function \a get_num_localities asynchronously returns the /// number of localities currently connected to the console which support /// the creation of the given component type. The returned future represents /// the actual result. /// /// \param t The component type for which the number of connected /// localities should be retrieved. /// /// \note This function will return meaningful results only if called /// from an HPX-thread. It will return 0 otherwise. /// /// \see \a hpx::find_all_localities, \a hpx::get_num_localities HPX_API_EXPORT lcos::future<boost::uint32_t> get_num_localities( components::component_type t); /////////////////////////////////////////////////////////////////////////// /// The type of a function which is registered to be executed as a /// startup or pre-startup function. typedef HPX_STD_FUNCTION<void()> startup_function_type; /////////////////////////////////////////////////////////////////////////// /// \brief Add a function to be executed by a HPX thread before hpx_main /// but guaranteed before any startup function is executed (system-wide). /// /// Any of the functions registered with \a register_pre_startup_function /// are guaranteed to be executed by an HPX thread before any of the /// registered startup functions are executed (see /// \a hpx::register_startup_function()). /// /// \param f [in] The function to be registered to run by an HPX thread as /// a pre-startup function. /// /// \note If this function is called while the pre-startup functions are /// being executed or after that point, it will raise a invalid_status /// exception. /// /// This function is one of the few API functions which can be called /// before the runtime system has been fully initialized. It will /// automatically stage the provided startup function to the runtime /// system during its initialization (if necessary). /// /// \see \a hpx::register_startup_function() HPX_API_EXPORT void register_pre_startup_function(startup_function_type const& f); /////////////////////////////////////////////////////////////////////////// /// \brief Add a function to be executed by a HPX thread before hpx_main /// but guaranteed after any pre-startup function is executed (system-wide). /// /// Any of the functions registered with \a register_startup_function /// are guaranteed to be executed by an HPX thread after any of the /// registered pre-startup functions are executed (see: /// \a hpx::register_pre_startup_function()), but before \a hpx_main is /// being called. /// /// \param f [in] The function to be registered to run by an HPX thread as /// a startup function. /// /// \note If this function is called while the startup functions are /// being executed or after that point, it will raise a invalid_status /// exception. /// /// This function is one of the few API functions which can be called /// before the runtime system has been fully initialized. It will /// automatically stage the provided startup function to the runtime /// system during its initialization (if necessary). /// /// \see \a hpx::register_pre_startup_function() HPX_API_EXPORT void register_startup_function(startup_function_type const& f); /// The type of a function which is registered to be executed as a /// shutdown or pre-shutdown function. typedef HPX_STD_FUNCTION<void()> shutdown_function_type; /// \brief Add a function to be executed by a HPX thread during /// \a hpx::finalize() but guaranteed before any shutdown function is /// executed (system-wide) /// /// Any of the functions registered with \a register_pre_shutdown_function /// are guaranteed to be executed by an HPX thread during the execution of /// \a hpx::finalize() before any of the registered shutdown functions are /// executed (see: \a hpx::register_shutdown_function()). /// /// \param f [in] The function to be registered to run by an HPX thread as /// a pre-shutdown function. /// /// \note If this function is called before the runtime system is /// initialized, or while the pre-shutdown functions are /// being executed, or after that point, it will raise a invalid_status /// exception. /// /// \see \a hpx::register_shutdown_function() HPX_API_EXPORT void register_pre_shutdown_function(shutdown_function_type const& f); /// \brief Add a function to be executed by a HPX thread during /// \a hpx::finalize() but guaranteed after any pre-shutdown function is /// executed (system-wide) /// /// Any of the functions registered with \a register_shutdown_function /// are guaranteed to be executed by an HPX thread during the execution of /// \a hpx::finalize() after any of the registered pre-shutdown functions /// are executed (see: \a hpx::register_pre_shutdown_function()). /// /// \param f [in] The function to be registered to run by an HPX thread as /// a shutdown function. /// /// \note If this function is called before the runtime system is /// initialized, or while the shutdown functions are /// being executed, or after that point, it will raise a invalid_status /// exception. /// /// \see \a hpx::register_pre_shutdown_function() HPX_API_EXPORT void register_shutdown_function(shutdown_function_type const& f); /////////////////////////////////////////////////////////////////////////// /// \brief Return the number of the current OS-thread running in the /// runtime instance the current HPX-thread is executed with. /// /// This function returns the zero based index of the OS-thread which /// executes the current HPX-thread. /// /// \note The returned value is zero based and it's maximum value is /// smaller than the overall number of OS-threads executed (as /// returned by \a get_os_thread_count(). /// /// \note This function needs to be executed on a HPX-thread. It will /// fail otherwise (it will return -1). HPX_API_EXPORT std::size_t get_worker_thread_num(); /////////////////////////////////////////////////////////////////////////// /// \brief Return the number of the locality this function is being called /// from. /// /// This function returns the id of the current locality. /// /// \param ec [in,out] this represents the error status on exit, if this /// is pre-initialized to \a hpx#throws the function will throw /// on error instead. /// /// \note The returned value is zero based and it's maximum value is /// smaller than the overall number of localities the current /// application is running on (as returned by /// \a get_num_localities()). /// /// \note As long as \a ec is not pre-initialized to \a hpx::throws this /// function doesn't throw but returns the result code using the /// parameter \a ec. Otherwise it throws an instance of /// hpx::exception. /// /// \note This function needs to be executed on a HPX-thread. It will /// fail otherwise (it will return -1). HPX_API_EXPORT boost::uint32_t get_locality_id(error_code& ec = throws); /////////////////////////////////////////////////////////////////////////// /// \brief Test whether the runtime system is currently running. /// /// This function returns whether the runtime system is currently running /// or not, e.g. whether the current state of the runtime system is /// \a hpx::runtime::running /// /// \note This function needs to be executed on a HPX-thread. It will /// return false otherwise. HPX_API_EXPORT bool is_running(); /////////////////////////////////////////////////////////////////////////// /// \brief Return the name of the calling thread. /// /// This function returns the name of the calling thread. This name uniquely /// identifies the thread in the context of HPX. If the function is called /// while no HPX runtime system is active, the result will be "<unknown>". HPX_API_EXPORT std::string get_thread_name(); /////////////////////////////////////////////////////////////////////////// /// \brief Return the number of worker OS- threads used to execute HPX /// threads /// /// This function returns the number of OS-threads used to execute HPX /// threads. If the function is called while no HPX runtime system is active, /// it will return zero. HPX_API_EXPORT std::size_t get_num_worker_threads(); /////////////////////////////////////////////////////////////////////////// /// \brief Return the system uptime measure on the thread executing this call. /// /// This function returns the system uptime measured in nanoseconds for the /// thread executing this call. If the function is called while no HPX /// runtime system is active, it will return zero. HPX_API_EXPORT boost::uint64_t get_system_uptime(); /////////////////////////////////////////////////////////////////////////// /// \brief Return the id of the locality where the object referenced by the /// given id is currently located on /// /// The function hpx::get_colocation_id() returns the id of the locality /// where the given object is currently located. /// /// \param id [in] The id of the object to locate. /// \param ec [in,out] this represents the error status on exit, if this /// is pre-initialized to \a hpx#throws the function will throw /// on error instead. /// /// \note As long as \a ec is not pre-initialized to \a hpx::throws this /// function doesn't throw but returns the result code using the /// parameter \a ec. Otherwise it throws an instance of /// hpx::exception. /// /// \see \a hpx::get_colocation_id() HPX_API_EXPORT naming::id_type get_colocation_id_sync( naming::id_type const& id, error_code& ec = throws); /// \brief Asynchronously return the id of the locality where the object /// referenced by the given id is currently located on /// /// \see \a hpx::get_colocation_id_sync() HPX_API_EXPORT lcos::future<naming::id_type> get_colocation_id( naming::id_type const& id); /////////////////////////////////////////////////////////////////////////// /// \brief Return the name of the referenced locality. /// /// This function returns a future referring to the name for the locality /// of the given id. /// /// \param id [in] The global id of the locality for which the name should /// be retrievd /// /// \returns This function returns the name for the locality of the given /// id. The name is retrieved from the underlying networking layer /// and may be different for different parcelports. /// HPX_API_EXPORT future<std::string> get_locality_name( naming::id_type const& id); /////////////////////////////////////////////////////////////////////////// /// \brief Trigger the LCO referenced by the given id /// /// \param id [in] this represents the id of the LCO which should be /// triggered. HPX_API_EXPORT void trigger_lco_event(naming::id_type const& id); /// \brief Set the result value for the LCO referenced by the given id /// /// \param id [in] this represents the id of the LCO which should /// receive the given value. /// \param t [in] this is the value which should be sent to the LCO. template <typename T> void set_lco_value(naming::id_type const& id, BOOST_FWD_REF(T) t); /// \brief Set the error state for the LCO referenced by the given id /// /// \param id [in] this represents the id of the LCO which should /// eceive the error value. /// \param e [in] this is the error value which should be sent to /// the LCO. HPX_API_EXPORT void set_lco_error(naming::id_type const& id, boost::exception_ptr const& e); /// \copydoc hpx::set_lco_error(naming::id_type const& id, boost::exception_ptr const& e) HPX_API_EXPORT void set_lco_error(naming::id_type const& id, BOOST_RV_REF(boost::exception_ptr) e); /////////////////////////////////////////////////////////////////////////// /// \brief Start all active performance counters, optionally naming the /// section of code /// /// \param ec [in,out] this represents the error status on exit, if this /// is pre-initialized to \a hpx#throws the function will throw /// on error instead. /// /// \note As long as \a ec is not pre-initialized to \a hpx::throws this /// function doesn't throw but returns the result code using the /// parameter \a ec. Otherwise it throws an instance of /// hpx::exception. /// /// \note The active counters are those which have been specified on /// the command line while executing the application (see command /// line option \--hpx:print-counter) HPX_API_EXPORT void start_active_counters(error_code& ec = throws); /// \brief Resets all active performance counters. /// /// \param ec [in,out] this represents the error status on exit, if this /// is pre-initialized to \a hpx#throws the function will throw /// on error instead. /// /// \note As long as \a ec is not pre-initialized to \a hpx::throws this /// function doesn't throw but returns the result code using the /// parameter \a ec. Otherwise it throws an instance of /// hpx::exception. /// /// \note The active counters are those which have been specified on /// the command line while executing the application (see command /// line option \--hpx:print-counter) HPX_API_EXPORT void reset_active_counters(error_code& ec = throws); /// \brief Stop all active performance counters. /// /// \param ec [in,out] this represents the error status on exit, if this /// is pre-initialized to \a hpx#throws the function will throw /// on error instead. /// /// \note As long as \a ec is not pre-initialized to \a hpx::throws this /// function doesn't throw but returns the result code using the /// parameter \a ec. Otherwise it throws an instance of /// hpx::exception. /// /// \note The active counters are those which have been specified on /// the command line while executing the application (see command /// line option \--hpx:print-counter) HPX_API_EXPORT void stop_active_counters(error_code& ec = throws); /// \brief Evaluate and output all active performance counters, optionally /// naming the point in code marked by this function. /// /// \param reset [in] this is an optional flag allowing to reset /// the counter value after it has been evaluated. /// \param description [in] this is an optional value naming the point in /// the code marked by the call to this function. /// \param ec [in,out] this represents the error status on exit, if this /// is pre-initialized to \a hpx#throws the function will throw /// on error instead. /// /// \note As long as \a ec is not pre-initialized to \a hpx::throws this /// function doesn't throw but returns the result code using the /// parameter \a ec. Otherwise it throws an instance of /// hpx::exception. /// /// \note The output generated by this function is redirected to the /// destination specified by the corresponding command line /// options (see \--hpx:print-counter-destination). /// /// \note The active counters are those which have been specified on /// the command line while executing the application (see command /// line option \--hpx:print-counter) HPX_API_EXPORT void evaluate_active_counters(bool reset = false, char const* description = 0, error_code& ec = throws); /////////////////////////////////////////////////////////////////////////// /// \brief Create an instance of a message handler plugin /// /// The function hpx::create_message_handler() creates an instance of a /// message handler plugin based on the parameters specified. /// /// \param message_handler_type /// \param action /// \param pp /// \param num_messages /// \param interval /// \param ec [in,out] this represents the error status on exit, if this /// is pre-initialized to \a hpx#throws the function will throw /// on error instead. /// /// \note As long as \a ec is not pre-initialized to \a hpx::throws this /// function doesn't throw but returns the result code using the /// parameter \a ec. Otherwise it throws an instance of /// hpx::exception. HPX_API_EXPORT parcelset::policies::message_handler* create_message_handler( char const* message_handler_type, char const* action, parcelset::parcelport* pp, std::size_t num_messages, std::size_t interval, error_code& ec = throws); /////////////////////////////////////////////////////////////////////////// /// \brief Create an instance of a binary filter plugin /// /// \param ec [in,out] this represents the error status on exit, if this /// is pre-initialized to \a hpx#throws the function will throw /// on error instead. /// /// \note As long as \a ec is not pre-initialized to \a hpx::throws this /// function doesn't throw but returns the result code using the /// parameter \a ec. Otherwise it throws an instance of /// hpx::exception. HPX_API_EXPORT util::binary_filter* create_binary_filter( char const* binary_filter_type, bool compress, util::binary_filter* next_filter = 0, error_code& ec = throws); #if defined(HPX_HAVE_SODIUM) namespace components { namespace security { class certificate; class certificate_signing_request; class parcel_suffix; class hash; template <typename T> class signed_type; typedef signed_type<certificate> signed_certificate; typedef signed_type<certificate_signing_request> signed_certificate_signing_request; typedef signed_type<parcel_suffix> signed_parcel_suffix; }} #if defined(HPX_HAVE_SECURITY) /// \brief Return the certificate for this locality /// /// \returns This function returns the signed certificate for this locality. HPX_API_EXPORT components::security::signed_certificate const& get_locality_certificate(error_code& ec = throws); /// \brief Return the certificate for the given locality /// /// \param id The id representing the locality for which to retrieve /// the signed certificate. /// /// \returns This function returns the signed certificate for the locality /// identified by the parameter \a id. HPX_API_EXPORT components::security::signed_certificate const& get_locality_certificate(boost::uint32_t locality_id, error_code& ec = throws); /// \brief Add the given certificate to the certificate store of this locality. /// /// \param cert The certificate to add to the certificate store of this /// locality HPX_API_EXPORT void add_locality_certificate( components::security::signed_certificate const& cert, error_code& ec = throws); #endif #endif } #include <hpx/lcos/async_fwd.hpp> #endif
61,082
16,227
// https://leetcode.com/problems/all-nodes-distance-k-in-binary-tree/submissions/ #include<iostream> #include<vector> using namespace std; struct TreeNode{ int val; struct TreeNode *left, *right; TreeNode(int x){ val = x; left=NULL; right=NULL; } }; bool findUntil(TreeNode* root, TreeNode* target,vector<TreeNode* >& v){ if(root == NULL) return false; if(root->val == target->val) { v.push_back(root); return true; } bool b = findUntil(root->left,target,v); if(b){ v.push_back(root); return true; } bool c = findUntil(root->right,target,v); if(c){ v.push_back(root); return true; } return false; } vector<TreeNode*> findNode(TreeNode* root, TreeNode* target){ vector<TreeNode* > v; findUntil(root, target, v); return v; } void GetNodes(TreeNode* root,int k, TreeNode* p, vector<int>& store){ if(root==NULL || root==p || k<0) return; if(k==0){ store.push_back(root->val); } GetNodes(root->left, k-1, p, store); GetNodes(root->right, k-1, p, store); } vector<int> distanceK(TreeNode* root, TreeNode* target, int k) { vector<TreeNode* > v = findNode(root, target); int n = v.size(); vector<int> store; for(int i=0;i<n;i++){ GetNodes(v[i],k-i, i==0?NULL:v[i-1], store); } return store; } int main(){ /* 3 / \ 5 1 / \ / \ 6 2 0 8 / \ 7 4 */ struct TreeNode* root = new TreeNode(3); root->left = new TreeNode(5); root->right = new TreeNode(1); root->left->left = new TreeNode(6); root->left->right = new TreeNode(2); root->right->left = new TreeNode(0); root->right->right = new TreeNode(8); root->left->right->left = new TreeNode(7); root->left->right->right = new TreeNode(4); vector<int> v = distanceK(root, root->left->right->right,2); for(int e : v) cout<<e<<" "; }
2,158
761
#include "Item.hpp" #include "ActorPlayer.hpp" // REMOVE: #include "../Graphics/Color.hpp" #include "../Utility/Rng.hpp" #include "../Utility/Utility.hpp" // Items #include "Items/Potion.hpp" #include "Items/Scroll.hpp" #include "Items/Weapon.hpp" #include "Items/Armor.hpp" #include "Items/Ring.hpp" #include "Items/Stick.hpp" #include <sstream> #include <cassert> namespace { /* extern.c */ std::vector<Item::Info> things = { { L"potion", 26, L'!' }, { L"sroll", 36, L'?' }, { L"food", 16, L'%' }, { L"weapon", 7, L')' }, { L"armor", 7, L'[' }, { L"ring", 4, L'=' }, { L"stick", 4, L'/' }, { L"gold", 0, L'*' }, { L"amulet", 0, L'"' }, }; const std::wstring fruit = L"slime-mold"; } int Item::Group = 2; Item::Item(ItemType type) : Entity(things[static_cast<int>(type)].worth) // glyph , type(type) { setColor(Color::Yellow); } std::wstring Item::getAName() const { std::wostringstream oss; switch (type) { case ItemType::Food: if (which == 1) { if (count == 1) oss << (isVowel(fruit) ? L"an " : L"a ") << fruit; else oss << count << L" " << fruit << L"s"; } else { if (count == 1) oss << L"some food"; else oss << count << L" rations of food"; } break; case ItemType::Gold: oss << count << L" gold pieces"; break; case ItemType::Amulet: oss << L"the Amulet of Yendor"; break; } return oss.str(); } ItemType Item::getType() const { return type; } bool Item::hasFlag(Flags flag) const { return flags & flag; } void Item::addFlag(Flags flag) { flags |= flag; } void Item::removeFlag(Flags flag) { flags &= ~flag; } void Item::setCount(int count) { this->count = count; } int Item::getCount() const { return count; } void Item::addCount(int count) { assert(count > 0); this->count += count; } void Item::reduceCount(int count) { assert(count > 0); this->count -= count; } int Item::getWhich() const { return which; } int Item::getGroup() const { return group; } int Item::getLaunch() const { return -1; } std::string Item::getDamage() const { return ""; } std::string Item::getDamageThrown() const { return ""; } int Item::getHitPlus() const { return 0; } int Item::getDamagePlus() const { return 0; } int Item::getArmor() const { return 0; } int Item::getRingPower() const { return 0; } bool Item::isSame(ItemType type, int which) const { return this->type == type && this->which == which; } bool Item::isSame(Item& item) const { return type == item.type && which == item.which; } bool Item::use(Actor& actor) { if (type == ItemType::Food) { eat(actor); playSound(SoundID::Eat); } return true; } void Item::enchant() { // Do nothing by default } void Item::degrade() { // Do nothing by default } int Item::ringEat() const { return 0; } void Item::eat(Actor& actor) { // HACK: Avoid dynamic_cast dynamic_cast<ActorPlayer&>(actor).eatFood(); if (which == 1) message(L"my, that was a yummy " + fruit + L".", Color::White); else { if (randomInt(100) > 70) { message(actor.chooseStr(L"bummer", L"yuk") + L", this food tastes awful.", Color::White); actor.gainExp(1); } else message(actor.chooseStr(L"oh, wow", L"yum") + L", that tasted good.", Color::White); } --count; } void Item::identify() { addFlag(Item::IsKnow); } bool Item::isIdentified() const { switch (type) { case ItemType::Weapon: case ItemType::Armor: case ItemType::Ring: case ItemType::Stick: return hasFlag(Item::IsKnow); } return true; } bool Item::isMagic() const { /* potion.c */ // is_magic: Returns true if an object radiates magic switch (type) { case ItemType::Potion: case ItemType::Scroll: case ItemType::Stick: // TODO: empty staff or wand? case ItemType::Ring: case ItemType::Amulet: return true; case ItemType::Weapon: return getHitPlus() > 0 || getDamagePlus() > 0; case ItemType::Armor: return hasFlag(Item::IsProtected) || getArmor() < 0; } return false; } bool Item::dropCheck(Actor& actor) const { /* things.c */ // dropcheck: Do special checks for dropping or unweilding|unwearing|unringing for (int i = 0; i < Actor::MaxSlot; ++i) { auto slot = static_cast<Actor::Slot>(i); if (actor.getEquipment(slot) == this) { if (hasFlag(Item::IsCursed)) { Item* item = actor.getEquipment(slot); // message(L"you can't. It appears to be cursed.", Color::White); message(L"you can't. Your " + item->getName() + L" appears to be cursed.", Color::White); return false; } else actor.setEquipment(slot, nullptr); // unequip break; } } return true; } void Item::repaint() { setChar(things[static_cast<int>(type)].worth); setColor(Color::Yellow); } void Item::initItems(Rng& rng) { Potion::initColors(rng); Scroll::initNames(rng); Stick::initMaterials(rng); Ring::initStones(rng); // Group = 2; } Item::Ptr Item::detachOne() { assert(count > 1); count -= 1; // Potion, scroll, food auto item = createItem(type, which); item->count = 1; item->flags = flags; return item; } Item::Ptr Item::createItem(ItemType type, int which) { Item::Ptr item = nullptr; switch (type) { case ItemType::Potion: item = std::make_unique<Potion>(type); item->which = which; break; case ItemType::Scroll: item = std::make_unique<Scroll>(type); item->which = which; break; case ItemType::Food: item = std::make_unique<Item>(type); item->which = which; break; case ItemType::Weapon: item = Weapon::createWeapon(which); break; case ItemType::Armor: item = Armor::createArmor(which); break; case ItemType::Ring: item = Ring::createRing(which); break; case ItemType::Stick: item = Stick::createStick(which); break; } return item; } Item::Ptr Item::createItem(Rng& rng, int& noFood) { /* things.c */ // new_thing: Return a new thing auto type = noFood > 3 ? ItemType::Food : static_cast<ItemType>(pickOne(rng, things)); Item::Ptr item = nullptr; switch (type) { case ItemType::Potion: item = std::make_unique<Potion>(type); item->which = Potion::pickOne(rng); break; case ItemType::Scroll: item = std::make_unique<Scroll>(type); item->which = Scroll::pickOne(rng); break; case ItemType::Food: noFood = 0; item = std::make_unique<Item>(type); item->which = rng.getInt(10) > 0 ? 0 : 1; break; case ItemType::Weapon: { int r = rng.getInt(100); int hitPlus = 0; if (r < 20) // 10 > 20 (10% > 20%) hitPlus -= rng.getInt(3) + 1; else if (r < 35) // 15 > 35 (5% > 15%) hitPlus += rng.getInt(3) + 1; item = Weapon::createWeapon(Weapon::pickOne(rng), hitPlus); } break; case ItemType::Armor: { int r = rng.getInt(100); int ac = 0; if (r < 25) // 20 > 25 (20% > 25%) ac += rng.getInt(3) + 1; else if (r < 43) // 28 > 43 (8% > 18%) ac -= rng.getInt(3) + 1; item = Armor::createArmor(Armor::pickOne(rng), ac); } break; case ItemType::Ring: { int power = 0; int which = Ring::pickOne(rng); switch (which) { case Ring::Protect: case Ring::AddStrength: case Ring::AddHit: case Ring::AddDamage: if ((power = rng.getInt(3)) == 0) power = -1; break; case Ring::Aggravate: case Ring::Teleport: power = -1; break; } item = Ring::createRing(which, power); } break; case ItemType::Stick: item = Stick::createStick(Stick::pickOne(rng)); break; } return item; } Item::Ptr Item::createGold(int value) { auto item = std::make_unique<Item>(ItemType::Gold); item->count = value; item->addFlag(Item::IsMany); item->group = 1; // GOLDGRP 1 return item; } std::wstring Item::getFruit() { return fruit; } wchar_t Item::getRandomChar() { // TODO: Add stairs return things[randomInt(things.size())].worth; } int Item::pickOne(Rng& rng, std::vector<Info>& items) { int totalProb = 0; for (const auto& item : items) totalProb += item.prob; int i = rng.getInt(totalProb); // 100 for (std::size_t j = 0; j < items.size(); ++j) { i -= items[j].prob; if (i < 0) return j; } return -1; // error }
8,529
3,786
#include "widget.h" #include <QApplication> #include <QDebug> int main(int argc, char *argv[]) { QApplication a(argc, argv); a.setQuitOnLastWindowClosed(true); Widget *w = new Widget; w->setAttribute(Qt::WA_DeleteOnClose); if (argc > 1) { if (!w->loadFile(argv[1])) { qWarning() << "Failed to load" << argv[1]; return 1; } } else { if (!w->loadFile()) { return 1; } } w->show(); return a.exec(); }
505
183
/* Copyright (c) 2021 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/platform/device/ipu/ipu_info.h" #include "paddle/fluid/platform/device/ipu/ipu_backend.h" namespace paddle { namespace platform { //! Get a list of device ids from environment variable or use all. std::vector<int> GetSelectedIPUDevices() { std::shared_ptr<platform::ipu::IpuBackend> ipu_backend = platform::ipu::IpuBackend::GetInstance(); return ipu_backend->GetDeviceIds(); } //! Get the total number of IPU devices in system. int GetIPUDeviceCount() { std::shared_ptr<platform::ipu::IpuBackend> ipu_backend = platform::ipu::IpuBackend::GetInstance(); return ipu_backend->GetNumDevices(); } } // namespace platform } // namespace paddle
1,277
403
/* * TcpServer.cpp * * Created on: Aug 22, 2017 */ #include "TcpServer.h" namespace network{ TcpServer::TcpServer(boost::asio::io_service& io_service, unsigned short port, std::function<int(TcpConnection *conn, message_t *msg)> callback) : acceptor_(io_service, tcp::endpoint(tcp::v4(), port)), callback(callback) { start_accept(); } void TcpServer::start_accept() { TcpConnection::ptr new_connection = TcpConnection::create(acceptor_.get_io_service()); acceptor_.async_accept(new_connection->socket(), boost::bind(&TcpServer::handle_accept, this, new_connection, boost::asio::placeholders::error)); } void TcpServer::handle_accept(TcpConnection::ptr new_connection, const boost::system::error_code& error) { if (!error) { new_connection->receive_msg(callback); } start_accept(); } } // namespace
905
295
#include <bits/stdc++.h> using namespace std; int solve(int N, string const& S) { map<int, int> count; vector<int> next(N, -1); for (int i = 0; i < N; ++i) { int j; for (j = i + 1; j < N; ++j) { if (S[i] != S[j]) break; } if (j > i + 1) { count[i] = j - i; } next[i] = j; i = j - 1; } int ans = 0; for (int i = 0; i < N;) { ++ans; if (count.empty()) { i = next[i]; if (i < N) i = next[i]; } else { auto it = count.begin(); --it->second; if (it->second == 1 || it->first < next[i]) count.erase(it); i = next[i]; } } return ans; } int main() { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); int T, N; string S; cin >> T; for (int tt = 0; tt < T; ++tt) { cin >> N >> S; cout << solve(N, S) << endl; } return 0; }
997
402
// Copyright (c) 2021 James Huxtable. All rights reserved. // // This work is licensed under the terms of the MIT license. // // 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. /** * @file * @brief Struct @ref ASGE::SpriteBounds */ #ifndef ASGE_SPRITEBOUNDS_HPP #define ASGE_SPRITEBOUNDS_HPP #include "Point2D.hpp" namespace ASGE { /** * @brief Four vertices defining a sprites bound. * * Used to conveniently store 4 points together. These 4 points * typically define the for vertices defining the bounding rectangle * of a sprite. Note:There is no guarantee that the bounds stored here * are axis-aligned or ordered. */ struct SpriteBounds { Point2D v1 = { 0, 0 }; /**< The first vertex position. */ Point2D v2 = { 0, 0 }; /**< The second vertex position */ Point2D v3 = { 0, 0 }; /**< The third vertex position. */ Point2D v4 = { 0, 0 }; /**< The fourth vertex position. */ }; using TextBounds = SpriteBounds; } // namespace ASGE #endif // ASGE_SPRITEBOUNDS_HPP
1,461
552
#include "hook_test.h" void winp::test::hook::run(int cmd_show){ winp::window::object ws; ws.set_caption(L"Test Window"); ws.set_position(30, 30); ws.set_size(1500, 800); ws.create(); ws.show(cmd_show); ws.get_grid([](winp::grid::object &grd){ grd.add_object([](winp::grid::row &row){ row.add_object([](winp::grid::column &col){ col.add_object([&](control::push_button &btn){ btn.set_text(L"Top-Left Aligned"); btn.insert_hook<ui::placement_hook>(ui::placement_hook::alignment_type::top_left); }); col.add_object([&](control::push_button &btn){ btn.set_text(L"Top-Center Aligned"); btn.insert_hook<ui::placement_hook>(ui::placement_hook::alignment_type::top_center); }); col.add_object([&](control::push_button &btn){ btn.set_text(L"Top-Right Aligned"); btn.insert_hook<ui::placement_hook>(ui::placement_hook::alignment_type::top_right); }); col.add_object([&](control::push_button &btn){ btn.set_text(L"Center-Right Aligned"); btn.insert_hook<ui::placement_hook>(ui::placement_hook::alignment_type::center_right); }); col.add_object([&](control::push_button &btn){ btn.set_text(L"Center Aligned"); btn.insert_hook<ui::placement_hook>(ui::placement_hook::alignment_type::center); }); col.add_object([&](control::push_button &btn){ btn.set_text(L"Center-Left Aligned"); btn.insert_hook<ui::placement_hook>(ui::placement_hook::alignment_type::center_left); }); col.add_object([&](control::push_button &btn){ btn.set_text(L"Bottom-Left Aligned"); btn.insert_hook<ui::placement_hook>(ui::placement_hook::alignment_type::bottom_left); }); col.add_object([&](control::push_button &btn){ btn.set_text(L"Bottom-Center Aligned"); btn.insert_hook<ui::placement_hook>(ui::placement_hook::alignment_type::bottom_center); }); col.add_object([&](control::push_button &btn){ btn.set_text(L"Bottom-Right Aligned"); btn.insert_hook<ui::placement_hook>(ui::placement_hook::alignment_type::bottom_right); }); col.add_object([&](control::push_button &btn){ btn.set_text(L"Drag-Hooked"); btn.set_position(200, 90); btn.insert_hook<ui::drag_hook>(); }); col.add_object([&](control::push_button &btn){ btn.set_text(L"Sibling Aligned"); btn.insert_hook<ui::sibling_placement_hook>(ui::sibling_placement_hook::sibling_type::previous, ui::sibling_placement_hook::alignment_type::center_right, POINT{ 5, 0 }); }); }); row.add_object([](winp::grid::column &col){ col.add_object([](winp::window::object &cw){ cw.set_caption(L"Children Contain Window"); cw.insert_hook<ui::children_contain_hook>(SIZE{ 30, 30 }); cw.set_position(30, 30); cw.set_size(900, 500); cw.create(); cw.show(); cw.add_object([](winp::window::object &ccw){ ccw.set_caption(L"Contained Child Window"); ccw.set_position(30, 30); ccw.set_size(450, 250); ccw.create(); ccw.show(); }); }); }); }); }); app::object::run(); }
3,083
1,422
#include "ofApp.h" //-------------------------------------------------------------- void ofApp::setup(){ ofSetFrameRate(60); for (int i = 0; i < 5; i++) { auto b = make_shared<Ball>(); b->init(); balls.push_back(b); } phase = 0; int bufferSize = 512; volume = 0.6f; pan =0.5f; ofSoundStreamSettings settings; settings.setOutListener(this); settings.sampleRate = sampleRate; settings.numOutputChannels = 2; settings.numInputChannels = 0; settings.bufferSize = bufferSize; soundStream.setup(settings); lAudio.assign(bufferSize, 0.0); rAudio.assign(bufferSize, 0.0); } //-------------------------------------------------------------- void ofApp::update(){ for (int i = 0; i < 5; i++) { for (int j = 0; j < 5; j++) if (i != j) balls[i]->update(balls[j]); } } //-------------------------------------------------------------- void ofApp::draw(){ ofBackground(34, 34, 34); ofSetColor(225); ofDrawBitmapString("press 's' to unpause the audio\npress 'e' to pause the audio", 31, 92); ofNoFill(); // draw the left channel: ofPushStyle(); ofPushMatrix(); ofTranslate(32, 150, 0); ofSetColor(225); ofDrawBitmapString("Left Channel", 4, 18); ofSetLineWidth(1); ofDrawRectangle(0, 0, 450, 200); ofSetColor(245, 58, 135); ofSetLineWidth(1.5); ofBeginShape(); for (unsigned int i = 0; i < lAudio.size(); i++){ float l = ofMap(i, 0, lAudio.size(), 0, 450, true); ofVertex(l, 100 -lAudio[i]*180.0f); } ofEndShape(false); ofPopMatrix(); ofPopStyle(); // draw the right channel: ofPushStyle(); ofPushMatrix(); ofTranslate(500, 150, 0); ofSetColor(225); ofDrawBitmapString("Right Channel", 4, 18); ofSetLineWidth(1); ofDrawRectangle(0, 0, 450, 200); ofSetColor(245, 58, 135); ofSetLineWidth(1.5); ofBeginShape(); for (unsigned int i = 0; i < rAudio.size(); i++){ float l = ofMap(i, 0, rAudio.size(), 0, 450, true); ofVertex(l, 100 -rAudio[i]*180.0f); } ofEndShape(false); ofPopMatrix(); ofPopStyle(); for (int i = 0; i < 5; i++) balls[i]->draw(); } void ofApp::audioOut(ofSoundBuffer &outBuffer){ float leftScale = 1 - pan; float rightScale = pan; while (phase > TWO_PI){ phase -= TWO_PI; } for(int i = 0; i < outBuffer.size(); i += 2) { auto cooin = generateSample(phase, balls[0]); float sample = cooin * (ofMap(balls[0]->vel.length(), 0, 10, 0, .8)+.2); // generating a sine wave sample float x = balls[0]->pos.x; float w = ofGetWidth(); float rightOffset = ofMap(x - w/2.0, -w/2.0 , w/2.0, -1, 1); rightOffset = (-1 * abs(rightOffset)) + 1; float leftOffset = 1 - abs(rightOffset); rAudio[i]= sample * volume*leftOffset; lAudio[i]= sample * volume*rightOffset; outBuffer[i] = sample * volume*rightOffset; // writing/drawing to the left channel outBuffer[i+1] = sample * volume*leftOffset; // writing/drawing to the right channel //memorize this equation! phaseOffset = freq / sampleRate float phaseOffset = ((float)2000 / ofMap(balls[0]->preAcc.length(), 0, 80/balls[0]->r, 60, 2500)); phase += phaseOffset; } } float ofApp::generateSample(float phase, shared_ptr<Ball> ball){ auto waveType = waveTypeGenerator(ball->pos); switch (waveType) { case 1://sine return sin(phase*TWO_PI); break; case 2://square return sin(phase*TWO_PI) > 0 ? .5 : -.5; case 3://sawtooth return fmod(phase,TWO_PI); case 4://triangle return abs(sin(phase*TWO_PI)); default: break; } } int ofApp::waveTypeGenerator(ofVec2f ballPos){ if (ballPos.x >= 0 && ballPos.x < ofGetWidth()/2){ if (ballPos.y >= 0 && ballPos.y < ofGetHeight()/2){ return 1; } else { return 2; } } else { if (ballPos.y >= 0 && ballPos.y < ofGetHeight()/2){ return 3; } else { return 4; } } } //-------------------------------------------------------------- void ofApp::keyPressed(int key){ if( key == 's' ){ soundStream.start(); } if( key == 'e' ){ soundStream.stop(); } } //-------------------------------------------------------------- void ofApp::keyReleased(int key){ } //-------------------------------------------------------------- void ofApp::mouseMoved(int x, int y ){ } //-------------------------------------------------------------- void ofApp::mouseDragged(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mousePressed(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mouseReleased(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mouseEntered(int x, int y){ } //-------------------------------------------------------------- void ofApp::mouseExited(int x, int y){ } //-------------------------------------------------------------- void ofApp::windowResized(int w, int h){ } //-------------------------------------------------------------- void ofApp::gotMessage(ofMessage msg){ } //-------------------------------------------------------------- void ofApp::dragEvent(ofDragInfo dragInfo){ }
5,731
1,946
// 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 "cc/test/fake_external_begin_frame_source.h" #include "base/location.h" #include "base/message_loop/message_loop.h" #include "base/time/time.h" #include "cc/test/begin_frame_args_test.h" namespace cc { FakeExternalBeginFrameSource::FakeExternalBeginFrameSource(double refresh_rate) : milliseconds_per_frame_(1000.0 / refresh_rate), is_ready_(false), weak_ptr_factory_(this) { DetachFromThread(); } FakeExternalBeginFrameSource::~FakeExternalBeginFrameSource() { DCHECK(CalledOnValidThread()); } void FakeExternalBeginFrameSource::SetClientReady() { DCHECK(CalledOnValidThread()); is_ready_ = true; } void FakeExternalBeginFrameSource::OnNeedsBeginFramesChange( bool needs_begin_frames) { DCHECK(CalledOnValidThread()); if (needs_begin_frames) { PostTestOnBeginFrame(); } } void FakeExternalBeginFrameSource::TestOnBeginFrame() { DCHECK(CalledOnValidThread()); CallOnBeginFrame(CreateBeginFrameArgsForTesting(BEGINFRAME_FROM_HERE)); if (NeedsBeginFrames()) { PostTestOnBeginFrame(); } } void FakeExternalBeginFrameSource::PostTestOnBeginFrame() { base::MessageLoop::current()->PostDelayedTask( FROM_HERE, base::Bind(&FakeExternalBeginFrameSource::TestOnBeginFrame, weak_ptr_factory_.GetWeakPtr()), base::TimeDelta::FromMilliseconds(milliseconds_per_frame_)); } } // namespace cc
1,556
514
#include<bits/stdc++.h> using namespace std; int gcd1(int a, int b){ //worst cse:O(min(a,b)) int small = std::min(a,b); while(small > 0){ if(a%small == 0 && b%small == 0){ break; } small--; } return small; } //Euclid algo int gcd2(int a, int b){ while(a != b){ if(a>b) a -= b; else b -= a; } return a; } //optimized Euclid aligo int gcd3(int a, int b){ //Best approach O(log(min(a,b))) if(b == 0) return a; return gcd3(b,a%b); } int main(){ cout<<gcd1(4,6)<<endl; cout<<gcd2(4,6)<<endl; cout<<gcd3(4,6)<<endl; return 0; }
684
291
// Copyright (C) 2019-2020 Zilliz. 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 "db/snapshot/Operations.h" #include <chrono> #include <sstream> #include "db/snapshot/OperationExecutor.h" #include "db/snapshot/Snapshots.h" namespace milvus { namespace engine { namespace snapshot { static ID_TYPE UID = 1; std::ostream& operator<<(std::ostream& out, const Operations& operation) { out << operation.ToString(); return out; } Operations::Operations(const OperationContext& context, ScopedSnapshotT prev_ss, const OperationsType& type) : context_(context), prev_ss_(prev_ss), uid_(UID++), status_(SS_OPERATION_PENDING, "Operation Pending"), type_(type) { } Operations::Operations(const OperationContext& context, ID_TYPE collection_id, ID_TYPE commit_id, const OperationsType& type) : context_(context), uid_(UID++), status_(SS_OPERATION_PENDING, "Operation Pending"), type_(type) { auto status = Snapshots::GetInstance().GetSnapshot(prev_ss_, collection_id, commit_id); if (!status.ok()) prev_ss_ = ScopedSnapshotT(); } std::string Operations::SuccessString() const { return status_.ToString(); } std::string Operations::FailureString() const { return status_.ToString(); } std::string Operations::GetRepr() const { std::stringstream ss; ss << "<" << GetName() << ":" << GetID() << ">"; return ss.str(); } std::string Operations::ToString() const { std::stringstream ss; ss << GetRepr(); ss << (done_ ? " | DONE" : " | PENDING"); if (done_) { if (status_.ok()) { ss << " | " << SuccessString(); } else { ss << " | " << FailureString(); } } return ss.str(); } ID_TYPE Operations::GetID() const { return uid_; } Status Operations::operator()(Store& store) { auto status = PreCheck(); if (!status.ok()) return status; return ApplyToStore(store); } void Operations::SetStatus(const Status& status) { status_ = status; } Status Operations::WaitToFinish() { std::unique_lock<std::mutex> lock(finish_mtx_); finish_cond_.wait(lock, [this] { return done_; }); return status_; } void Operations::Done() { std::unique_lock<std::mutex> lock(finish_mtx_); done_ = true; if (GetType() == OperationsType::W_Compound) { std::cout << ToString() << std::endl; } finish_cond_.notify_all(); } Status Operations::PreCheck() { return Status::OK(); } Status Operations::Push(bool sync) { auto status = PreCheck(); if (!status.ok()) return status; return OperationExecutor::GetInstance().Submit(shared_from_this(), sync); } Status Operations::DoCheckStale(ScopedSnapshotT& latest_snapshot) const { return Status::OK(); } Status Operations::CheckStale(const CheckStaleFunc& checker) const { decltype(prev_ss_) latest_ss; auto status = Snapshots::GetInstance().GetSnapshotNoLoad(latest_ss, prev_ss_->GetCollection()->GetID()); if (!status.ok()) return status; if (prev_ss_->GetID() != latest_ss->GetID()) { if (checker) { status = checker(latest_ss); } else { status = DoCheckStale(latest_ss); } } return status; } Status Operations::DoneRequired() const { Status status; if (!done_) { status = Status(SS_CONSTRAINT_CHECK_ERROR, "Operation is expected to be done"); } return status; } Status Operations::IDSNotEmptyRequried() const { Status status; if (ids_.size() == 0) status = Status(SS_CONSTRAINT_CHECK_ERROR, "No Snapshot is available"); return status; } Status Operations::PrevSnapshotRequried() const { Status status; if (!prev_ss_) { status = Status(SS_CONSTRAINT_CHECK_ERROR, "Prev snapshot is requried"); } return status; } Status Operations::GetSnapshot(ScopedSnapshotT& ss) const { auto status = PrevSnapshotRequried(); if (!status.ok()) return status; status = DoneRequired(); if (!status.ok()) return status; status = IDSNotEmptyRequried(); if (!status.ok()) return status; status = Snapshots::GetInstance().GetSnapshot(ss, prev_ss_->GetCollectionId(), ids_.back()); return status; } Status Operations::ApplyToStore(Store& store) { if (GetType() == OperationsType::W_Compound) { std::cout << ToString() << std::endl; } if (done_) { Done(); return status_; } auto status = OnExecute(store); SetStatus(status); Done(); return status_; } Status Operations::OnExecute(Store& store) { auto status = PreExecute(store); if (!status.ok()) { return status; } status = DoExecute(store); if (!status.ok()) { return status; } return PostExecute(store); } Status Operations::PreExecute(Store& store) { return Status::OK(); } Status Operations::DoExecute(Store& store) { return Status::OK(); } Status Operations::PostExecute(Store& store) { return store.DoCommitOperation(*this); } Status Operations::RollBack() { // TODO: Implement here // Spwarn a rollback operation or re-use this operation return Status::OK(); } Status Operations::ApplyRollBack(Store& store) { // TODO: Implement rollback to remove all resources in steps_ return Status::OK(); } Operations::~Operations() { // TODO: Prefer to submit a rollback operation if status is not ok } } // namespace snapshot } // namespace engine } // namespace milvus
6,059
1,925
/* file: pooling1d_layer_backward.cpp */ /******************************************************************************* * Copyright 2014-2018 Intel Corporation * All Rights Reserved. * * If this software was obtained under the Intel Simplified Software License, * the following terms apply: * * The source code, information and material ("Material") contained herein is * owned by Intel Corporation or its suppliers or licensors, and title to such * Material remains with Intel Corporation or its suppliers or licensors. The * Material contains proprietary information of Intel or its suppliers and * licensors. The Material is protected by worldwide copyright laws and treaty * provisions. No part of the Material may be used, copied, reproduced, * modified, published, uploaded, posted, transmitted, distributed or disclosed * in any way without Intel's prior express written permission. No license under * any patent, copyright or other intellectual property rights in the Material * is granted to or conferred upon you, either expressly, by implication, * inducement, estoppel or otherwise. Any license under such intellectual * property rights must be express and approved by Intel in writing. * * Unless otherwise agreed by Intel in writing, you may not remove or alter this * notice or any other notice embedded in Materials by Intel or Intel's * suppliers or licensors in any way. * * * If this software was obtained under the Apache License, Version 2.0 (the * "License"), the following terms apply: * * 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. *******************************************************************************/ /* //++ // Implementation of pooling1d calculation algorithm and types methods. //-- */ #include "pooling1d_layer_backward_types.h" #include "pooling1d_layer_types.h" #include "daal_strings.h" using namespace daal::services; namespace daal { namespace algorithms { namespace neural_networks { namespace layers { namespace pooling1d { namespace backward { namespace interface1 { /** Default constructor */ Input::Input() {} Input::Input(const Input& other) : super(other) {} /** * Return the collection with gradient size * \return The collection with gradient size */ services::Collection<size_t> Input::getGradientSize() const { services::Collection<size_t> dims; data_management::NumericTablePtr inputDims = getAuxInputDimensions(); if(!data_management::checkNumericTable(inputDims.get(), auxInputDimensionsStr())) { return dims; } data_management::BlockDescriptor<int> block; inputDims->getBlockOfRows(0, 1, data_management::readOnly, block); int *inputDimsArray = block.getBlockPtr(); for(size_t i = 0; i < inputDims->getNumberOfColumns(); i++) { dims.push_back((size_t) inputDimsArray[i]); } inputDims->releaseBlockOfRows(block); return dims; } services::Collection<size_t> Input::getInputGradientSize(const pooling1d::Parameter *parameter) const { const Parameter *param = static_cast<const Parameter *>(parameter); services::Collection<size_t> inputDims = getGradientSize(); inputDims[param->index.size[0]] = computeInputDimension(inputDims[param->index.size[0]], param->kernelSize.size[0], param->padding.size[0], param->stride.size[0]); return inputDims; } size_t Input::computeInputDimension(size_t maskDim, size_t kernelSize, size_t padding, size_t stride) const { size_t inputDim = (maskDim + 2 * padding - kernelSize + stride) / stride; return inputDim; } /** Default constructor */ Result::Result() {} /** * Checks the result of the backward 1D pooling layer * \param[in] input %Input object for the layer * \param[in] parameter %Parameter of the layer * \param[in] method Computation method */ services::Status Result::check(const daal::algorithms::Input *input, const daal::algorithms::Parameter *parameter, int method) const { const Parameter *param = static_cast<const Parameter *>(parameter); if (!param->propagateGradient) { return services::Status(); } services::Status s; DAAL_CHECK_STATUS(s, layers::backward::Result::check(input, parameter, method)); const Input *algInput = static_cast<const Input *>(input); //get expected gradient dimensions services::Collection<size_t> gradientDims = algInput->getGradientSize(); DAAL_CHECK_STATUS(s, data_management::checkTensor(get(layers::backward::gradient).get(), gradientStr(), &gradientDims)); DAAL_CHECK_EX(param->stride.size[0] != 0, services::ErrorIncorrectParameter, services::ParameterName, stridesStr()); size_t index = param->index.size[0]; DAAL_CHECK_EX(index <= gradientDims.size() - 1, services::ErrorIncorrectParameter, services::ParameterName, indicesStr()); DAAL_CHECK_EX((param->kernelSize.size[0] != 0 && param->kernelSize.size[0] <= gradientDims[index] + 2 * param->padding.size[0]), services::ErrorIncorrectParameter, services::ParameterName, kernelSizesStr()); return s; } }// namespace interface1 }// namespace backward }// namespace pooling1d }// namespace layers }// namespace neural_networks }// namespace algorithms }// namespace daal
5,723
1,685
#include "heap.h" #include "macro.h" #include <assert.h> #include <cmath> #include "tools.h" Heap::Heap(bool maxHeapify /* = true */) : ContinueContainer(), m_isMaxHeapify(maxHeapify) { } Heap::Heap(int *data, int len, bool maxHeapify /* = true */) : ContinueContainer(data, len), m_isMaxHeapify(maxHeapify) { Heapify(); } Heap::~Heap() { } void Heap::PushBack(const int v) { ContinueContainer::PushBack(v); TrackUp(m_len - 1); } int Heap::PopFront() { Swap(m_data, 0, (m_len - 1)); int value = ContinueContainer::Erase(m_len - 1); TrackDown(0); return value; } void Heap::Sort() { int len = m_len; int *buf = new int[len]; int idx = 0; while (m_len > 0) { buf[idx++] = PopFront(); } Resize(buf, len); } void Heap::Heapify() { int height = (int)log2(m_len); for (int i = height - 1; i >= 0; i--) { for (int j = pow(2, i); j < pow(2, i + 1); j++) { TrackDown(j - 1); } } } void Heap::TrackDown(const int node) { int left = node * 2 + 1; int right = node * 2 + 2; if (left >= m_len) { return; } int sid; int value; if (m_isMaxHeapify) { value = m_data[node] < m_data[left] ? m_data[left] : m_data[node]; if (right < m_len) { value = value < m_data[right] ? m_data[right] : value; } } else { value = m_data[node] > m_data[left] ? m_data[left] : m_data[node]; if (right < m_len) { value = value > m_data[right] ? m_data[right] : value; } } if (value == m_data[node]) { return; } if (value == m_data[left]) { Swap(m_data, node, left); TrackDown(left); } if ((right < m_len) && (value == m_data[right])) { Swap(m_data, node, right); TrackDown(right); } } void Heap::TrackUp(const int node) { if (0 == node) { return; } int parent = (node - 1) / 2; if (m_isMaxHeapify) { if (m_data[parent] < m_data[node]) { Swap(m_data, parent, node); TrackDown(parent); TrackUp(parent); } } else { if (m_data[parent] > m_data[node]) { Swap(m_data, parent, node); TrackDown(parent); TrackUp(parent); } } }
2,415
961
#include <iostream> #include <regex> #include <sstream> #include <map> using namespace std; int main() { int n; cin >> n; cin.ignore(11000, '\n'); string str, strdict, animal, goes, sound; regex e("[A-Za-z]+"); for (int i = 0; i < n; i++) { map<string, int> maptoanimal; getline(cin, str); while (true) { getline(cin, strdict); if (strdict == "what does the fox say?") { break; } stringstream ss(strdict); ss >> animal >> goes >> sound; maptoanimal[sound] = 1; } for (sregex_iterator i = sregex_iterator(str.begin(), str.end(), e); i != sregex_iterator(); ++i) { smatch m = *i; string a = m.str(); if(maptoanimal[a]==0){ cout<<a<<' '; } } cout<<'\n'; } return 0; }
944
317
#include <gtest/gtest.h> #include "metrics.h" #include "utiltime.h" TEST(Metrics, AtomicTimer) { AtomicTimer t; SetMockTime(100); EXPECT_FALSE(t.running()); t.start(); EXPECT_TRUE(t.running()); t.start(); EXPECT_TRUE(t.running()); t.stop(); EXPECT_TRUE(t.running()); t.stop(); EXPECT_FALSE(t.running()); // Additional calls to stop() are ignored. t.stop(); EXPECT_FALSE(t.running()); t.start(); EXPECT_TRUE(t.running()); AtomicCounter c; EXPECT_EQ(0, t.rate(c)); c.increment(); EXPECT_EQ(0, t.rate(c)); SetMockTime(101); EXPECT_EQ(1, t.rate(c)); c.decrement(); EXPECT_EQ(0, t.rate(c)); SetMockTime(102); EXPECT_EQ(0, t.rate(c)); c.increment(); EXPECT_EQ(0.5, t.rate(c)); t.stop(); EXPECT_FALSE(t.running()); EXPECT_EQ(0.5, t.rate(c)); } TEST(Metrics, GetLocalSolPS) { SetMockTime(100); miningTimer.start(); // No time has passed EXPECT_EQ(0, GetLocalSolPS()); // Increment time SetMockTime(101); EXPECT_EQ(0, GetLocalSolPS()); // Increment solutions solutionTargetChecks.increment(); EXPECT_EQ(1, GetLocalSolPS()); // Increment time SetMockTime(102); EXPECT_EQ(0.5, GetLocalSolPS()); // Increment solutions solutionTargetChecks.increment(); solutionTargetChecks.increment(); EXPECT_EQ(1.5, GetLocalSolPS()); // Stop timing miningTimer.stop(); EXPECT_EQ(1.5, GetLocalSolPS()); // Increment time SetMockTime(103); EXPECT_EQ(1.5, GetLocalSolPS()); // Start timing again miningTimer.start(); EXPECT_EQ(1.5, GetLocalSolPS()); // Increment time SetMockTime(104); EXPECT_EQ(1, GetLocalSolPS()); }
1,757
714
#include "Xe.h" // Xe Xe::Xe(double tocdoXang0Tai, double tocdoXangHH) { m_xang = 0; m_duong = 0; m_hang = 0; m_tocdoXang0Tai = tocdoXang0Tai; m_tocdoXangHH = tocdoXangHH; m_xangTieuThu = m_tocdoXang0Tai * m_duong + m_tocdoXangHH * m_hang; } void Xe::themHang(double hang) { m_hang += hang; m_xangTieuThu += m_tocdoXangHH * hang; } void Xe::botHang(double hang) { hang = hang <= m_hang ? hang : m_hang; themHang(-hang); } void Xe::themXang(double xang) { m_xang += xang; } void Xe::chay(double duong) { m_duong += duong; m_xangTieuThu += m_tocdoXang0Tai * duong; m_xang -= m_xangTieuThu; } bool Xe::hetXang() { return m_xang <= 0; } double Xe::xang() { return m_xang; }
693
386
/////////////////////////////////////////////////////////////////////////////// // Copyright (c) Lewis Baker // Licenced under MIT license. See LICENSE.txt for details. /////////////////////////////////////////////////////////////////////////////// #include <cppcoro/when_all.hpp> #include <cppcoro/config.hpp> #include <cppcoro/async_manual_reset_event.hpp> #include <cppcoro/async_mutex.hpp> #include <cppcoro/fmap.hpp> #include <cppcoro/shared_task.hpp> #include <cppcoro/sync_wait.hpp> #include <cppcoro/task.hpp> #include "counted.hpp" #include <functional> #include <string> #include <vector> #include <ostream> #include "doctest/cppcoro_doctest.h" TEST_SUITE_BEGIN("when_all"); namespace { template<template<typename T> class TASK, typename T> TASK<T> when_event_set_return(cppcoro::async_manual_reset_event& event, T value) { co_await event; co_return std::move(value); } } TEST_CASE("when_all() with no args completes immediately") { [[maybe_unused]] std::tuple<> result = cppcoro::sync_wait(cppcoro::when_all()); } TEST_CASE("when_all() with one arg") { bool started = false; bool finished = false; auto f = [&](cppcoro::async_manual_reset_event& event) -> cppcoro::task<std::string> { started = true; co_await event; finished = true; co_return "foo"; }; cppcoro::async_manual_reset_event event; auto whenAllTask = cppcoro::when_all(f(event)); CHECK(!started); cppcoro::sync_wait(cppcoro::when_all_ready( [&]() -> cppcoro::task<> { auto[s] = co_await whenAllTask; CHECK(s == "foo"); }(), [&]() -> cppcoro::task<> { CHECK(started); CHECK(!finished); event.set(); CHECK(finished); co_return; }())); } TEST_CASE("when_all() with awaitables") { cppcoro::sync_wait([]() -> cppcoro::task<> { auto makeTask = [](int x) -> cppcoro::task<int> { co_return x; }; cppcoro::async_manual_reset_event event; event.set(); cppcoro::async_mutex mutex; auto[eventResult, mutexLock, number] = co_await cppcoro::when_all( std::ref(event), mutex.scoped_lock_async(), makeTask(123) | cppcoro::fmap([](int x) { return x + 1; })); (void)eventResult; (void)mutexLock; CHECK(number == 124); CHECK(!mutex.try_lock()); }()); } TEST_CASE("when_all() with all task types") { counted::reset_counts(); auto run = [](cppcoro::async_manual_reset_event& event) -> cppcoro::task<> { using namespace std::string_literals; auto[a, b] = co_await cppcoro::when_all( when_event_set_return<cppcoro::task>(event, "foo"s), when_event_set_return<cppcoro::shared_task>(event, counted{})); CHECK(a == "foo"); CHECK(b.id == 0); // GCC 10.1 fails this check: at this point there are 3 objects alive // * One will be destructed later // * One object is completely leaked #if CPPCORO_COMPILER_GCC && CPPCORO_COMPILER_GCC <= 10'02'00 WARN("GCC <= 10.02 is known to produce memory leaks !!!"); #else CHECK(counted::active_count() == 1); #endif }; cppcoro::async_manual_reset_event event; cppcoro::sync_wait(cppcoro::when_all_ready( run(event), [&]() -> cppcoro::task<> { event.set(); co_return; }())); } TEST_CASE("when_all() throws if any task throws") { struct X {}; struct Y {}; int startedCount = 0; auto makeTask = [&](int value) -> cppcoro::task<int> { ++startedCount; if (value == 0) throw X{}; else if (value == 1) throw Y{}; else co_return value; }; cppcoro::sync_wait([&]() -> cppcoro::task<> { try { // This could either throw X or Y exception. // The exact exception that is thrown is not defined if multiple tasks throw an exception. // TODO: Consider throwing some kind of aggregate_exception that collects all of the exceptions together. (void)co_await cppcoro::when_all(makeTask(0), makeTask(1), makeTask(2)); } catch (const X&) { } catch (const Y&) { } }()); } TEST_CASE("when_all() with task<void>") { int voidTaskCount = 0; auto makeVoidTask = [&]() -> cppcoro::task<> { ++voidTaskCount; co_return; }; auto makeIntTask = [](int x) -> cppcoro::task<int> { co_return x; }; // Single void task in when_all() auto[x] = cppcoro::sync_wait(cppcoro::when_all(makeVoidTask())); (void)x; CHECK(voidTaskCount == 1); // Multiple void tasks in when_all() auto[a, b] = cppcoro::sync_wait(cppcoro::when_all( makeVoidTask(), makeVoidTask())); (void)a; (void)b; CHECK(voidTaskCount == 3); // Mixing void and non-void tasks in when_all() auto[v1, i, v2] = cppcoro::sync_wait(cppcoro::when_all( makeVoidTask(), makeIntTask(123), makeVoidTask())); (void)v1; (void)v2; CHECK(voidTaskCount == 5); CHECK(i == 123); } TEST_CASE("when_all() with vector<task<>>") { int startedCount = 0; auto makeTask = [&](cppcoro::async_manual_reset_event& event) -> cppcoro::task<> { ++startedCount; co_await event; }; cppcoro::async_manual_reset_event event1; cppcoro::async_manual_reset_event event2; bool finished = false; auto run = [&]() -> cppcoro::task<> { std::vector<cppcoro::task<>> tasks; tasks.push_back(makeTask(event1)); tasks.push_back(makeTask(event2)); tasks.push_back(makeTask(event1)); auto allTask = cppcoro::when_all(std::move(tasks)); CHECK(startedCount == 0); co_await allTask; finished = true; }; cppcoro::sync_wait(cppcoro::when_all_ready( run(), [&]() -> cppcoro::task<> { CHECK(startedCount == 3); CHECK(!finished); event1.set(); CHECK(!finished); event2.set(); CHECK(finished); co_return; }())); } TEST_CASE("when_all() with vector<shared_task<>>") { int startedCount = 0; auto makeTask = [&](cppcoro::async_manual_reset_event& event) -> cppcoro::shared_task<> { ++startedCount; co_await event; }; cppcoro::async_manual_reset_event event1; cppcoro::async_manual_reset_event event2; bool finished = false; auto run = [&]() -> cppcoro::task<> { std::vector<cppcoro::shared_task<>> tasks; tasks.push_back(makeTask(event1)); tasks.push_back(makeTask(event2)); tasks.push_back(makeTask(event1)); auto allTask = cppcoro::when_all(std::move(tasks)); CHECK(startedCount == 0); co_await allTask; finished = true; }; cppcoro::sync_wait(cppcoro::when_all_ready( run(), [&]() -> cppcoro::task<> { CHECK(startedCount == 3); CHECK(!finished); event1.set(); CHECK(!finished); event2.set(); CHECK(finished); co_return; }())); } namespace { template<template<typename T> class TASK> void check_when_all_vector_of_task_value() { cppcoro::async_manual_reset_event event1; cppcoro::async_manual_reset_event event2; bool whenAllCompleted = false; cppcoro::sync_wait(cppcoro::when_all_ready( [&]() -> cppcoro::task<> { std::vector<TASK<int>> tasks; tasks.emplace_back(when_event_set_return<TASK>(event1, 1)); tasks.emplace_back(when_event_set_return<TASK>(event2, 2)); auto whenAllTask = cppcoro::when_all(std::move(tasks)); auto values = co_await whenAllTask; REQUIRE(values.size() == 2); CHECK(values[0] == 1); CHECK(values[1] == 2); whenAllCompleted = true; }(), [&]() -> cppcoro::task<> { CHECK(!whenAllCompleted); event2.set(); CHECK(!whenAllCompleted); event1.set(); CHECK(whenAllCompleted); co_return; }())); } } #if defined(CPPCORO_RELEASE_OPTIMISED) constexpr bool isOptimised = true; #else constexpr bool isOptimised = false; #endif // Disable test on MSVC x86 optimised due to bad codegen bug in // `co_await whenAllTask` expression under MSVC 15.7 (Preview 2) and earlier. TEST_CASE("when_all() with vector<task<T>>" * doctest::skip(CPPCORO_COMPILER_MSVC && CPPCORO_COMPILER_MSVC <= 191426316 && CPPCORO_CPU_X86 && isOptimised)) { check_when_all_vector_of_task_value<cppcoro::task>(); } // Disable test on MSVC x64 optimised due to bad codegen bug in // 'co_await whenAllTask' expression. // Issue reported to MS on 19/11/2017. TEST_CASE("when_all() with vector<shared_task<T>>" * doctest::skip(CPPCORO_COMPILER_MSVC && CPPCORO_COMPILER_MSVC <= 191225805 && isOptimised && CPPCORO_CPU_X64)) { check_when_all_vector_of_task_value<cppcoro::shared_task>(); } namespace { template<template<typename T> class TASK> void check_when_all_vector_of_task_reference() { cppcoro::async_manual_reset_event event1; cppcoro::async_manual_reset_event event2; int value1 = 1; int value2 = 2; auto makeTask = [](cppcoro::async_manual_reset_event& event, int& value) -> TASK<int&> { co_await event; co_return value; }; bool whenAllComplete = false; cppcoro::sync_wait(cppcoro::when_all_ready( [&]() -> cppcoro::task<> { std::vector<TASK<int&>> tasks; tasks.emplace_back(makeTask(event1, value1)); tasks.emplace_back(makeTask(event2, value2)); auto whenAllTask = cppcoro::when_all(std::move(tasks)); std::vector<std::reference_wrapper<int>> values = co_await whenAllTask; REQUIRE(values.size() == 2); CHECK(&values[0].get() == &value1); CHECK(&values[1].get() == &value2); whenAllComplete = true; }(), [&]() -> cppcoro::task<> { CHECK(!whenAllComplete); event2.set(); CHECK(!whenAllComplete); event1.set(); CHECK(whenAllComplete); co_return; }())); } } // Disable test on MSVC x64 optimised due to bad codegen bug in // 'co_await whenAllTask' expression. // Issue reported to MS on 19/11/2017. TEST_CASE("when_all() with vector<task<T&>>" * doctest::skip(CPPCORO_COMPILER_MSVC && CPPCORO_COMPILER_MSVC <= 191225805 && isOptimised && CPPCORO_CPU_X64)) { check_when_all_vector_of_task_reference<cppcoro::task>(); } // Disable test on MSVC x64 optimised due to bad codegen bug in // 'co_await whenAllTask' expression. // Issue reported to MS on 19/11/2017. TEST_CASE("when_all() with vector<shared_task<T&>>" * doctest::skip(CPPCORO_COMPILER_MSVC && CPPCORO_COMPILER_MSVC <= 191225805 && isOptimised && CPPCORO_CPU_X64)) { check_when_all_vector_of_task_reference<cppcoro::shared_task>(); } TEST_SUITE_END();
9,925
4,271
#include<iostream> #include<math.h> using namespace std; int main() { double i=0, a=1,sign=1; double sum=0; while (fabs(a) >= 1e-8) { sum = sum + (sign *a); i++; a = 1/(2 * i + 1); sign = -sign; } cout << "steps=" << i<<" " << "PI=" << sum*4.0; }
305
135