hexsha
stringlengths
40
40
size
int64
19
11.4M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
3
270
max_stars_repo_name
stringlengths
5
110
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
3
270
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
9
max_issues_count
float64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
3
270
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
listlengths
1
9
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
19
11.4M
avg_line_length
float64
1.93
229k
max_line_length
int64
12
688k
alphanum_fraction
float64
0.07
0.99
matches
listlengths
1
10
5ee76979613793f217872c2c91ada51ab9951b18
22,615
cpp
C++
Engine/Plugins/2D/Paper2D/Source/Paper2DEditor/Private/TileMapEditing/STileLayerList.cpp
windystrife/UnrealEngine_NVIDIAGameWork
b50e6338a7c5b26374d66306ebc7807541ff815e
[ "MIT" ]
1
2022-01-29T18:36:12.000Z
2022-01-29T18:36:12.000Z
Engine/Plugins/2D/Paper2D/Source/Paper2DEditor/Private/TileMapEditing/STileLayerList.cpp
windystrife/UnrealEngine_NVIDIAGameWork
b50e6338a7c5b26374d66306ebc7807541ff815e
[ "MIT" ]
null
null
null
Engine/Plugins/2D/Paper2D/Source/Paper2DEditor/Private/TileMapEditing/STileLayerList.cpp
windystrife/UnrealEngine_NVIDIAGameWork
b50e6338a7c5b26374d66306ebc7807541ff815e
[ "MIT" ]
null
null
null
// Copyright 1998-2017 Epic Games, Inc. All Rights Reserved. #include "TileMapEditing/STileLayerList.h" #include "PaperTileLayer.h" #include "UObject/PropertyPortFlags.h" #include "Misc/NotifyHook.h" #include "Framework/MultiBox/MultiBoxDefs.h" #include "Framework/MultiBox/MultiBoxBuilder.h" #include "Widgets/Views/SListView.h" #include "Exporters/Exporter.h" #include "Editor.h" #include "PaperTileMapComponent.h" #include "TileMapEditing/STileLayerItem.h" #include "PaperStyle.h" #include "HAL/PlatformApplicationMisc.h" #include "ScopedTransaction.h" #include "TileMapEditing/TileMapEditorCommands.h" #include "Framework/Commands/GenericCommands.h" #include "UnrealExporter.h" #include "Factories.h" #define LOCTEXT_NAMESPACE "Paper2D" ////////////////////////////////////////////////////////////////////////// // FLayerTextFactory // Text object factory for pasting layers struct FLayerTextFactory : public FCustomizableTextObjectFactory { public: TArray<UPaperTileLayer*> CreatedLayers; public: FLayerTextFactory() : FCustomizableTextObjectFactory(GWarn) { } // FCustomizableTextObjectFactory interface virtual bool CanCreateClass(UClass* ObjectClass, bool& bOmitSubObjs) const override { // Only allow layers to be created return ObjectClass->IsChildOf(UPaperTileLayer::StaticClass()); } virtual void ProcessConstructedObject(UObject* NewObject) override { CreatedLayers.Add(CastChecked<UPaperTileLayer>(NewObject)); } // End of FCustomizableTextObjectFactory interface }; ////////////////////////////////////////////////////////////////////////// // STileLayerList void STileLayerList::Construct(const FArguments& InArgs, UPaperTileMap* InTileMap, FNotifyHook* InNotifyHook, TSharedPtr<class FUICommandList> InParentCommandList) { OnSelectedLayerChanged = InArgs._OnSelectedLayerChanged; TileMapPtr = InTileMap; NotifyHook = InNotifyHook; FTileMapEditorCommands::Register(); FGenericCommands::Register(); const FTileMapEditorCommands& TileMapCommands = FTileMapEditorCommands::Get(); const FGenericCommands& GenericCommands = FGenericCommands::Get(); CommandList = MakeShareable(new FUICommandList); InParentCommandList->Append(CommandList.ToSharedRef()); CommandList->MapAction( TileMapCommands.AddNewLayerAbove, FExecuteAction::CreateSP(this, &STileLayerList::AddNewLayerAbove)); CommandList->MapAction( TileMapCommands.AddNewLayerBelow, FExecuteAction::CreateSP(this, &STileLayerList::AddNewLayerBelow)); CommandList->MapAction( GenericCommands.Cut, FExecuteAction::CreateSP(this, &STileLayerList::CutLayer), FCanExecuteAction::CreateSP(this, &STileLayerList::CanExecuteActionNeedingSelectedLayer)); CommandList->MapAction( GenericCommands.Copy, FExecuteAction::CreateSP(this, &STileLayerList::CopyLayer), FCanExecuteAction::CreateSP(this, &STileLayerList::CanExecuteActionNeedingSelectedLayer)); CommandList->MapAction( GenericCommands.Paste, FExecuteAction::CreateSP(this, &STileLayerList::PasteLayerAbove), FCanExecuteAction::CreateSP(this, &STileLayerList::CanPasteLayer)); CommandList->MapAction( GenericCommands.Duplicate, FExecuteAction::CreateSP(this, &STileLayerList::DuplicateLayer), FCanExecuteAction::CreateSP(this, &STileLayerList::CanExecuteActionNeedingSelectedLayer)); CommandList->MapAction( GenericCommands.Delete, FExecuteAction::CreateSP(this, &STileLayerList::DeleteLayer), FCanExecuteAction::CreateSP(this, &STileLayerList::CanExecuteActionNeedingSelectedLayer)); CommandList->MapAction( GenericCommands.Rename, FExecuteAction::CreateSP(this, &STileLayerList::RenameLayer), FCanExecuteAction::CreateSP(this, &STileLayerList::CanExecuteActionNeedingSelectedLayer)); CommandList->MapAction( TileMapCommands.MergeLayerDown, FExecuteAction::CreateSP(this, &STileLayerList::MergeLayerDown), FCanExecuteAction::CreateSP(this, &STileLayerList::CanExecuteActionNeedingLayerBelow)); CommandList->MapAction( TileMapCommands.MoveLayerUp, FExecuteAction::CreateSP(this, &STileLayerList::MoveLayerUp, /*bForceToTop=*/ false), FCanExecuteAction::CreateSP(this, &STileLayerList::CanExecuteActionNeedingLayerAbove)); CommandList->MapAction( TileMapCommands.MoveLayerDown, FExecuteAction::CreateSP(this, &STileLayerList::MoveLayerDown, /*bForceToBottom=*/ false), FCanExecuteAction::CreateSP(this, &STileLayerList::CanExecuteActionNeedingLayerBelow)); CommandList->MapAction( TileMapCommands.MoveLayerToTop, FExecuteAction::CreateSP(this, &STileLayerList::MoveLayerUp, /*bForceToTop=*/ true), FCanExecuteAction::CreateSP(this, &STileLayerList::CanExecuteActionNeedingLayerAbove)); CommandList->MapAction( TileMapCommands.MoveLayerToBottom, FExecuteAction::CreateSP(this, &STileLayerList::MoveLayerDown, /*bForceToBottom=*/ true), FCanExecuteAction::CreateSP(this, &STileLayerList::CanExecuteActionNeedingLayerBelow)); CommandList->MapAction( TileMapCommands.SelectLayerAbove, FExecuteAction::CreateSP(this, &STileLayerList::SelectLayerAbove, /*bTopmost=*/ false)); CommandList->MapAction( TileMapCommands.SelectLayerBelow, FExecuteAction::CreateSP(this, &STileLayerList::SelectLayerBelow, /*bBottommost=*/ false)); // FToolBarBuilder ToolbarBuilder(CommandList, FMultiBoxCustomization("TileLayerBrowserToolbar"), TSharedPtr<FExtender>(), Orient_Horizontal, /*InForceSmallIcons=*/ true); ToolbarBuilder.SetLabelVisibility(EVisibility::Collapsed); ToolbarBuilder.AddToolBarButton(TileMapCommands.AddNewLayerAbove); ToolbarBuilder.AddToolBarButton(TileMapCommands.MoveLayerUp); ToolbarBuilder.AddToolBarButton(TileMapCommands.MoveLayerDown); FSlateIcon DuplicateIcon(FPaperStyle::GetStyleSetName(), "TileMapEditor.DuplicateLayer"); ToolbarBuilder.AddToolBarButton(GenericCommands.Duplicate, NAME_None, TAttribute<FText>(), TAttribute<FText>(), DuplicateIcon); FSlateIcon DeleteIcon(FPaperStyle::GetStyleSetName(), "TileMapEditor.DeleteLayer"); ToolbarBuilder.AddToolBarButton(GenericCommands.Delete, NAME_None, TAttribute<FText>(), TAttribute<FText>(), DeleteIcon); TSharedRef<SWidget> Toolbar = ToolbarBuilder.MakeWidget(); ListViewWidget = SNew(SPaperLayerListView) .SelectionMode(ESelectionMode::Single) .ClearSelectionOnClick(false) .ListItemsSource(&MirrorList) .OnSelectionChanged(this, &STileLayerList::OnSelectionChanged) .OnGenerateRow(this, &STileLayerList::OnGenerateLayerListRow) .OnContextMenuOpening(this, &STileLayerList::OnConstructContextMenu); RefreshMirrorList(); // Restore the selection InTileMap->ValidateSelectedLayerIndex(); if (InTileMap->TileLayers.IsValidIndex(InTileMap->SelectedLayerIndex)) { UPaperTileLayer* SelectedLayer = InTileMap->TileLayers[InTileMap->SelectedLayerIndex]; SetSelectedLayer(SelectedLayer); } ChildSlot [ SNew(SVerticalBox) +SVerticalBox::Slot() [ SNew(SBox) .HeightOverride(115.0f) [ ListViewWidget.ToSharedRef() ] ] +SVerticalBox::Slot() .AutoHeight() [ Toolbar ] ]; GEditor->RegisterForUndo(this); } TSharedRef<ITableRow> STileLayerList::OnGenerateLayerListRow(FMirrorEntry Item, const TSharedRef<STableViewBase>& OwnerTable) { typedef STableRow<FMirrorEntry> RowType; TSharedRef<RowType> NewRow = SNew(RowType, OwnerTable) .Style(&FPaperStyle::Get()->GetWidgetStyle<FTableRowStyle>("TileMapEditor.LayerBrowser.TableViewRow")); FIsSelected IsSelectedDelegate = FIsSelected::CreateSP(NewRow, &RowType::IsSelectedExclusively); NewRow->SetContent(SNew(STileLayerItem, *Item, TileMapPtr.Get(), IsSelectedDelegate)); return NewRow; } UPaperTileLayer* STileLayerList::GetSelectedLayer() const { if (UPaperTileMap* TileMap = TileMapPtr.Get()) { if (ListViewWidget->GetNumItemsSelected() > 0) { FMirrorEntry SelectedItem = ListViewWidget->GetSelectedItems()[0]; const int32 SelectedIndex = *SelectedItem; if (TileMap->TileLayers.IsValidIndex(SelectedIndex)) { return TileMap->TileLayers[SelectedIndex]; } } } return nullptr; } FText STileLayerList::GenerateDuplicatedLayerName(const FString& InputNameRaw, UPaperTileMap* TileMap) { // Create a set of existing names bool bFoundName = false; TSet<FString> ExistingNames; for (UPaperTileLayer* ExistingLayer : TileMap->TileLayers) { const FString LayerName = ExistingLayer->LayerName.ToString(); ExistingNames.Add(LayerName); if (LayerName == InputNameRaw) { bFoundName = true; } } // If the name doesn't already exist, then we're done (can happen when pasting a cut layer, etc...) if (!bFoundName) { return FText::FromString(InputNameRaw); } FString BaseName = InputNameRaw; int32 TestIndex = 0; bool bAddNumber = false; // See if this is the result of a previous duplication operation, and change the desired name accordingly int32 SpaceIndex; if (InputNameRaw.FindLastChar(' ', /*out*/ SpaceIndex)) { FString PossibleDuplicationSuffix = InputNameRaw.Mid(SpaceIndex + 1); if (PossibleDuplicationSuffix == TEXT("copy")) { bAddNumber = true; BaseName = InputNameRaw.Left(SpaceIndex); TestIndex = 2; } else { int32 ExistingIndex = FCString::Atoi(*PossibleDuplicationSuffix); const FString TestSuffix = FString::Printf(TEXT(" copy %d"), ExistingIndex); if (InputNameRaw.EndsWith(TestSuffix)) { bAddNumber = true; BaseName = InputNameRaw.Left(InputNameRaw.Len() - TestSuffix.Len()); TestIndex = ExistingIndex + 1; } } } // Find a good name FString TestLayerName = BaseName + TEXT(" copy"); if (bAddNumber || ExistingNames.Contains(TestLayerName)) { do { TestLayerName = FString::Printf(TEXT("%s copy %d"), *BaseName, TestIndex++); } while (ExistingNames.Contains(TestLayerName)); } return FText::FromString(TestLayerName); } UPaperTileLayer* STileLayerList::AddLayer(int32 InsertionIndex) { UPaperTileLayer* NewLayer = nullptr; if (UPaperTileMap* TileMap = TileMapPtr.Get()) { const FScopedTransaction Transaction(LOCTEXT("TileMapAddLayer", "Add New Layer")); TileMap->SetFlags(RF_Transactional); TileMap->Modify(); NewLayer = TileMap->AddNewLayer(InsertionIndex); PostEditNotfications(); // Change the selection set to select it SetSelectedLayer(NewLayer); } return NewLayer; } void STileLayerList::ChangeLayerOrdering(int32 OldIndex, int32 NewIndex) { if (UPaperTileMap* TileMap = TileMapPtr.Get()) { if (TileMap->TileLayers.IsValidIndex(OldIndex) && TileMap->TileLayers.IsValidIndex(NewIndex)) { const FScopedTransaction Transaction(LOCTEXT("TileMapReorderLayer", "Reorder Layer")); TileMap->SetFlags(RF_Transactional); TileMap->Modify(); UPaperTileLayer* LayerToMove = TileMap->TileLayers[OldIndex]; TileMap->TileLayers.RemoveAt(OldIndex); TileMap->TileLayers.Insert(LayerToMove, NewIndex); if (TileMap->SelectedLayerIndex == OldIndex) { TileMap->SelectedLayerIndex = NewIndex; SetSelectedLayer(LayerToMove); } PostEditNotfications(); } } } void STileLayerList::AddNewLayerAbove() { AddLayer(GetSelectionIndex()); } void STileLayerList::AddNewLayerBelow() { AddLayer(GetSelectionIndex() + 1); } int32 STileLayerList::GetSelectionIndex() const { int32 SelectionIndex = INDEX_NONE; if (UPaperTileMap* TileMap = TileMapPtr.Get()) { if (UPaperTileLayer* SelectedLayer = GetSelectedLayer()) { TileMap->TileLayers.Find(SelectedLayer, /*out*/ SelectionIndex); } else { SelectionIndex = TileMap->TileLayers.Num() - 1; } } return SelectionIndex; } void STileLayerList::DeleteSelectedLayerWithNoTransaction() { if (UPaperTileMap* TileMap = TileMapPtr.Get()) { const int32 DeleteIndex = GetSelectionIndex(); if (DeleteIndex != INDEX_NONE) { TileMap->TileLayers.RemoveAt(DeleteIndex); PostEditNotfications(); // Select the item below the one that just got deleted const int32 NewSelectionIndex = FMath::Min<int32>(DeleteIndex, TileMap->TileLayers.Num() - 1); if (TileMap->TileLayers.IsValidIndex(NewSelectionIndex)) { SetSelectedLayer(TileMap->TileLayers[NewSelectionIndex]); } } } } void STileLayerList::DeleteLayer() { if (UPaperTileMap* TileMap = TileMapPtr.Get()) { const FScopedTransaction Transaction(LOCTEXT("TileMapDeleteLayer", "Delete Layer")); TileMap->SetFlags(RF_Transactional); TileMap->Modify(); DeleteSelectedLayerWithNoTransaction(); } } void STileLayerList::RenameLayer() { if (UPaperTileMap* TileMap = TileMapPtr.Get()) { const int32 RenameIndex = GetSelectionIndex(); if (MirrorList.IsValidIndex(RenameIndex)) { TSharedPtr<ITableRow> LayerRowWidget = ListViewWidget->WidgetFromItem(MirrorList[RenameIndex]); if (LayerRowWidget.IsValid()) { TSharedPtr<SWidget> RowContent = LayerRowWidget->GetContent(); if (RowContent.IsValid()) { TSharedPtr<STileLayerItem> LayerWidget = StaticCastSharedPtr<STileLayerItem>(RowContent); LayerWidget->BeginEditingName(); } } } } } void STileLayerList::DuplicateLayer() { if (UPaperTileMap* TileMap = TileMapPtr.Get()) { const int32 DuplicateIndex = GetSelectionIndex(); if (DuplicateIndex != INDEX_NONE) { const FScopedTransaction Transaction(LOCTEXT("TileMapDuplicateLayer", "Duplicate Layer")); TileMap->SetFlags(RF_Transactional); TileMap->Modify(); UPaperTileLayer* NewLayer = DuplicateObject<UPaperTileLayer>(TileMap->TileLayers[DuplicateIndex], TileMap); TileMap->TileLayers.Insert(NewLayer, DuplicateIndex); NewLayer->LayerName = GenerateDuplicatedLayerName(NewLayer->LayerName.ToString(), TileMap); PostEditNotfications(); // Select the duplicated layer SetSelectedLayer(NewLayer); } } } void STileLayerList::MergeLayerDown() { if (UPaperTileMap* TileMap = TileMapPtr.Get()) { const int32 SourceIndex = GetSelectionIndex(); const int32 TargetIndex = SourceIndex + 1; if ((SourceIndex != INDEX_NONE) && (TargetIndex != INDEX_NONE)) { const FScopedTransaction Transaction(LOCTEXT("TileMapMergeLayerDown", "Merge Layer Down")); TileMap->SetFlags(RF_Transactional); TileMap->Modify(); UPaperTileLayer* SourceLayer = TileMap->TileLayers[SourceIndex]; UPaperTileLayer* TargetLayer = TileMap->TileLayers[TargetIndex]; TargetLayer->SetFlags(RF_Transactional); TargetLayer->Modify(); // Copy the non-empty tiles from the source to the target layer for (int32 Y = 0; Y < SourceLayer->GetLayerHeight(); ++Y) { for (int32 X = 0; X < SourceLayer->GetLayerWidth(); ++X) { FPaperTileInfo TileInfo = SourceLayer->GetCell(X, Y); if (TileInfo.IsValid()) { TargetLayer->SetCell(X, Y, TileInfo); } } } // Remove the source layer TileMap->TileLayers.RemoveAt(SourceIndex); // Update viewers PostEditNotfications(); } } } void STileLayerList::MoveLayerUp(bool bForceToTop) { const int32 SelectedIndex = GetSelectionIndex(); const int32 NewIndex = bForceToTop ? 0 : (SelectedIndex - 1); ChangeLayerOrdering(SelectedIndex, NewIndex); } void STileLayerList::MoveLayerDown(bool bForceToBottom) { const int32 SelectedIndex = GetSelectionIndex(); const int32 NewIndex = bForceToBottom ? (GetNumLayers() - 1) : (SelectedIndex + 1); ChangeLayerOrdering(SelectedIndex, NewIndex); } void STileLayerList::SelectLayerAbove(bool bTopmost) { const int32 SelectedIndex = GetSelectionIndex(); const int32 NumLayers = GetNumLayers(); const int32 NewIndex = bTopmost ? 0 : ((NumLayers + SelectedIndex - 1) % NumLayers); SetSelectedLayerIndex(NewIndex); } void STileLayerList::SelectLayerBelow(bool bBottommost) { const int32 SelectedIndex = GetSelectionIndex(); const int32 NumLayers = GetNumLayers(); const int32 NewIndex = bBottommost ? (NumLayers - 1) : ((SelectedIndex + 1) % NumLayers); SetSelectedLayerIndex(NewIndex); } void STileLayerList::CutLayer() { CopyLayer(); if (UPaperTileMap* TileMap = TileMapPtr.Get()) { const FScopedTransaction Transaction(LOCTEXT("TileMapCutLayer", "Cut Layer")); TileMap->SetFlags(RF_Transactional); TileMap->Modify(); DeleteSelectedLayerWithNoTransaction(); } } void STileLayerList::CopyLayer() { if (UPaperTileLayer* SelectedLayer = GetSelectedLayer()) { UnMarkAllObjects(EObjectMark(OBJECTMARK_TagExp | OBJECTMARK_TagImp)); FStringOutputDevice ExportArchive; const FExportObjectInnerContext Context; UExporter::ExportToOutputDevice(&Context, SelectedLayer, nullptr, ExportArchive, TEXT("copy"), 0, PPF_Copy, false, nullptr); FPlatformApplicationMisc::ClipboardCopy(*ExportArchive); } } void STileLayerList::PasteLayerAbove() { if (UPaperTileMap* TileMap = TileMapPtr.Get()) { FString ClipboardContent; FPlatformApplicationMisc::ClipboardPaste(ClipboardContent); if (!ClipboardContent.IsEmpty()) { const FScopedTransaction Transaction(LOCTEXT("TileMapPasteLayer", "Paste Layer")); TileMap->SetFlags(RF_Transactional); TileMap->Modify(); // Turn the text buffer into objects FLayerTextFactory Factory; Factory.ProcessBuffer(TileMap, RF_Transactional, ClipboardContent); // Add them to the map and select them (there will currently only ever be 0 or 1) for (UPaperTileLayer* NewLayer : Factory.CreatedLayers) { NewLayer->LayerName = GenerateDuplicatedLayerName(NewLayer->LayerName.ToString(), TileMap); TileMap->AddExistingLayer(NewLayer, GetSelectionIndex()); PostEditNotfications(); SetSelectedLayer(NewLayer); } } } } bool STileLayerList::CanPasteLayer() const { FString ClipboardContent; FPlatformApplicationMisc::ClipboardPaste(ClipboardContent); return !ClipboardContent.IsEmpty(); } void STileLayerList::SetSelectedLayerIndex(int32 NewIndex) { if (UPaperTileMap* TileMap = TileMapPtr.Get()) { if (TileMap->TileLayers.IsValidIndex(NewIndex)) { SetSelectedLayer(TileMap->TileLayers[NewIndex]); PostEditNotfications(); } } } int32 STileLayerList::GetNumLayers() const { if (UPaperTileMap* TileMap = TileMapPtr.Get()) { return TileMap->TileLayers.Num(); } return 0; } bool STileLayerList::CanExecuteActionNeedingLayerAbove() const { return GetSelectionIndex() > 0; } bool STileLayerList::CanExecuteActionNeedingLayerBelow() const { const int32 SelectedLayer = GetSelectionIndex(); return (SelectedLayer != INDEX_NONE) && (SelectedLayer + 1 < GetNumLayers()); } bool STileLayerList::CanExecuteActionNeedingSelectedLayer() const { return GetSelectionIndex() != INDEX_NONE; } void STileLayerList::SetSelectedLayer(UPaperTileLayer* SelectedLayer) { if (UPaperTileMap* TileMap = TileMapPtr.Get()) { int32 NewIndex; if (TileMap->TileLayers.Find(SelectedLayer, /*out*/ NewIndex)) { if (MirrorList.IsValidIndex(NewIndex)) { ListViewWidget->SetSelection(MirrorList[NewIndex]); } } } } void STileLayerList::OnSelectionChanged(FMirrorEntry ItemChangingState, ESelectInfo::Type SelectInfo) { if (UPaperTileMap* TileMap = TileMapPtr.Get()) { TileMap->SelectedLayerIndex = GetSelectionIndex(); PostEditNotfications(); } } TSharedPtr<SWidget> STileLayerList::OnConstructContextMenu() { const bool bShouldCloseWindowAfterMenuSelection = true; FMenuBuilder MenuBuilder(bShouldCloseWindowAfterMenuSelection, CommandList); const FTileMapEditorCommands& TileMapCommands = FTileMapEditorCommands::Get(); const FGenericCommands& GenericCommands = FGenericCommands::Get(); FSlateIcon DummyIcon(NAME_None, NAME_None); MenuBuilder.BeginSection("BasicOperations", LOCTEXT("BasicOperationsHeader", "Layer actions")); { MenuBuilder.AddMenuEntry(GenericCommands.Cut, NAME_None, TAttribute<FText>(), TAttribute<FText>(), DummyIcon); MenuBuilder.AddMenuEntry(GenericCommands.Copy, NAME_None, TAttribute<FText>(), TAttribute<FText>(), DummyIcon); MenuBuilder.AddMenuEntry(GenericCommands.Paste, NAME_None, TAttribute<FText>(), TAttribute<FText>(), DummyIcon); MenuBuilder.AddMenuEntry(GenericCommands.Duplicate, NAME_None, TAttribute<FText>(), TAttribute<FText>(), DummyIcon); MenuBuilder.AddMenuEntry(GenericCommands.Delete, NAME_None, TAttribute<FText>(), TAttribute<FText>(), DummyIcon); MenuBuilder.AddMenuEntry(GenericCommands.Rename, NAME_None, TAttribute<FText>(), TAttribute<FText>(), DummyIcon); MenuBuilder.AddMenuEntry(TileMapCommands.MergeLayerDown, NAME_None, TAttribute<FText>(), TAttribute<FText>(), DummyIcon); MenuBuilder.AddMenuSeparator(); MenuBuilder.AddMenuEntry(TileMapCommands.SelectLayerAbove, NAME_None, TAttribute<FText>(), TAttribute<FText>(), DummyIcon); MenuBuilder.AddMenuEntry(TileMapCommands.SelectLayerBelow, NAME_None, TAttribute<FText>(), TAttribute<FText>(), DummyIcon); } MenuBuilder.EndSection(); MenuBuilder.BeginSection("OrderingOperations", LOCTEXT("OrderingOperationsHeader", "Order actions")); { MenuBuilder.AddMenuEntry(TileMapCommands.MoveLayerToTop, NAME_None, TAttribute<FText>(), TAttribute<FText>(), DummyIcon); MenuBuilder.AddMenuEntry(TileMapCommands.MoveLayerUp, NAME_None, TAttribute<FText>(), TAttribute<FText>(), DummyIcon); MenuBuilder.AddMenuEntry(TileMapCommands.MoveLayerDown, NAME_None, TAttribute<FText>(), TAttribute<FText>(), DummyIcon); MenuBuilder.AddMenuEntry(TileMapCommands.MoveLayerToBottom, NAME_None, TAttribute<FText>(), TAttribute<FText>(), DummyIcon); } MenuBuilder.EndSection(); return MenuBuilder.MakeWidget(); } void STileLayerList::PostEditNotfications() { RefreshMirrorList(); if (UPaperTileMap* TileMap = TileMapPtr.Get()) { TileMap->PostEditChange(); } if (NotifyHook != nullptr) { UProperty* TileMapProperty = FindFieldChecked<UProperty>(UPaperTileMapComponent::StaticClass(), GET_MEMBER_NAME_CHECKED(UPaperTileMapComponent, TileMap)); NotifyHook->NotifyPreChange(TileMapProperty); NotifyHook->NotifyPostChange(FPropertyChangedEvent(TileMapProperty), TileMapProperty); } OnSelectedLayerChanged.Execute(); } void STileLayerList::RefreshMirrorList() { if (UPaperTileMap* TileMap = TileMapPtr.Get()) { const int32 NumEntriesToAdd = TileMap->TileLayers.Num() - MirrorList.Num(); if (NumEntriesToAdd < 0) { MirrorList.RemoveAt(TileMap->TileLayers.Num(), -NumEntriesToAdd); } else if (NumEntriesToAdd > 0) { for (int32 Count = 0; Count < NumEntriesToAdd; ++Count) { TSharedPtr<int32> NewEntry = MakeShareable(new int32); *NewEntry = MirrorList.Num(); MirrorList.Add(NewEntry); } } } else { MirrorList.Empty(); } ListViewWidget->RequestListRefresh(); } void STileLayerList::PostUndo(bool bSuccess) { RefreshMirrorList(); } void STileLayerList::PostRedo(bool bSuccess) { RefreshMirrorList(); } STileLayerList::~STileLayerList() { GEditor->UnregisterForUndo(this); } ////////////////////////////////////////////////////////////////////////// #undef LOCTEXT_NAMESPACE
30.315013
169
0.757462
[ "object" ]
5eeca86a59ceb28ac73e795f94b0f15bda986cff
12,772
cpp
C++
xs/src/libslic3r/BridgeDetector.cpp
bharralure49/Slic3r
ac2b6de62bd38e6f9dd87f26f2a0394d7b6b41c7
[ "CC-BY-3.0" ]
1
2015-03-29T21:35:34.000Z
2015-03-29T21:35:34.000Z
xs/src/libslic3r/BridgeDetector.cpp
bharralure49/Slic3r
ac2b6de62bd38e6f9dd87f26f2a0394d7b6b41c7
[ "CC-BY-3.0" ]
null
null
null
xs/src/libslic3r/BridgeDetector.cpp
bharralure49/Slic3r
ac2b6de62bd38e6f9dd87f26f2a0394d7b6b41c7
[ "CC-BY-3.0" ]
null
null
null
#include "BridgeDetector.hpp" #include "ClipperUtils.hpp" #include "Geometry.hpp" #include <algorithm> namespace Slic3r { class BridgeDirectionComparator { public: std::map<double,double> dir_coverage, dir_avg_length; // angle => score BridgeDirectionComparator(double _extrusion_width) : extrusion_width(_extrusion_width) {}; // the best direction is the one causing most lines to be bridged (thus most coverage) // and shortest max line length bool operator() (double a, double b) { double coverage_diff = this->dir_coverage[a] - this->dir_coverage[b]; if (fabs(coverage_diff) < this->extrusion_width) { return (this->dir_avg_length[b] > this->dir_avg_length[a]); } else { return (coverage_diff > 0); } }; private: double extrusion_width; }; BridgeDetector::BridgeDetector(const ExPolygon &_expolygon, const ExPolygonCollection &_lower_slices, coord_t _extrusion_width) : expolygon(_expolygon), lower_slices(_lower_slices), extrusion_width(_extrusion_width), angle(-1), resolution(PI/36.0) { /* outset our bridge by an arbitrary amout; we'll use this outer margin for detecting anchors */ Polygons grown; offset((Polygons)this->expolygon, &grown, this->extrusion_width); // detect what edges lie on lower slices for (ExPolygons::const_iterator lower = this->lower_slices.expolygons.begin(); lower != this->lower_slices.expolygons.end(); ++lower) { /* turn bridge contour and holes into polylines and then clip them with each lower slice's contour */ intersection(grown, lower->contour, &this->_edges); } #ifdef SLIC3R_DEBUG printf(" bridge has %zu support(s)\n", this->_edges.size()); #endif // detect anchors as intersection between our bridge expolygon and the lower slices // safety offset required to avoid Clipper from detecting empty intersection while Boost actually found some edges intersection(grown, this->lower_slices, &this->_anchors, true); /* if (0) { require "Slic3r/SVG.pm"; Slic3r::SVG::output("bridge.svg", expolygons => [ $self->expolygon ], red_expolygons => $self->lower_slices, polylines => $self->_edges, ); } */ } bool BridgeDetector::detect_angle() { if (this->_edges.empty() || this->_anchors.empty()) return false; /* Outset the bridge expolygon by half the amount we used for detecting anchors; we'll use this one to clip our test lines and be sure that their endpoints are inside the anchors and not on their contours leading to false negatives. */ Polygons clip_area; offset(this->expolygon, &clip_area, +this->extrusion_width/2); /* we'll now try several directions using a rudimentary visibility check: bridge in several directions and then sum the length of lines having both endpoints within anchors */ // we test angles according to configured resolution std::vector<double> angles; for (int i = 0; i <= PI/this->resolution; ++i) angles.push_back(i * this->resolution); // we also test angles of each bridge contour { Polygons pp = this->expolygon; for (Polygons::const_iterator p = pp.begin(); p != pp.end(); ++p) { Lines lines; p->lines(&lines); for (Lines::const_iterator line = lines.begin(); line != lines.end(); ++line) angles.push_back(line->direction()); } } /* we also test angles of each open supporting edge (this finds the optimal angle for C-shaped supports) */ for (Polylines::const_iterator edge = this->_edges.begin(); edge != this->_edges.end(); ++edge) { if (edge->first_point().coincides_with(edge->last_point())) continue; angles.push_back(Line(edge->first_point(), edge->last_point()).direction()); } // remove duplicates double min_resolution = PI/180.0; // 1 degree std::sort(angles.begin(), angles.end()); for (size_t i = 1; i < angles.size(); ++i) { if (Slic3r::Geometry::directions_parallel(angles[i], angles[i-1], min_resolution)) { angles.erase(angles.begin() + i); --i; } } /* compare first value with last one and remove the greatest one (PI) in case they are parallel (PI, 0) */ if (Slic3r::Geometry::directions_parallel(angles.front(), angles.back(), min_resolution)) angles.pop_back(); BridgeDirectionComparator bdcomp(this->extrusion_width); double line_increment = this->extrusion_width; bool have_coverage = false; for (std::vector<double>::const_iterator angle = angles.begin(); angle != angles.end(); ++angle) { Polygons my_clip_area = clip_area; ExPolygons my_anchors = this->_anchors; // rotate everything - the center point doesn't matter for (Polygons::iterator it = my_clip_area.begin(); it != my_clip_area.end(); ++it) it->rotate(-*angle, Point(0,0)); for (ExPolygons::iterator it = my_anchors.begin(); it != my_anchors.end(); ++it) it->rotate(-*angle, Point(0,0)); // generate lines in this direction BoundingBox bb; for (ExPolygons::const_iterator it = my_anchors.begin(); it != my_anchors.end(); ++it) bb.merge((Points)*it); Lines lines; for (coord_t y = bb.min.y; y <= bb.max.y; y += line_increment) lines.push_back(Line(Point(bb.min.x, y), Point(bb.max.x, y))); Lines clipped_lines; intersection(lines, my_clip_area, &clipped_lines); // remove any line not having both endpoints within anchors for (size_t i = 0; i < clipped_lines.size(); ++i) { Line &line = clipped_lines[i]; if (!Slic3r::Geometry::contains(my_anchors, line.a) || !Slic3r::Geometry::contains(my_anchors, line.b)) { clipped_lines.erase(clipped_lines.begin() + i); --i; } } std::vector<double> lengths; double total_length = 0; for (Lines::const_iterator line = clipped_lines.begin(); line != clipped_lines.end(); ++line) { double len = line->length(); lengths.push_back(len); total_length += len; } if (total_length) have_coverage = true; // sum length of bridged lines bdcomp.dir_coverage[*angle] = total_length; /* The following produces more correct results in some cases and more broken in others. TODO: investigate, as it looks more reliable than line clipping. */ // $directions_coverage{$angle} = sum(map $_->area, @{$self->coverage($angle)}) // 0; // max length of bridged lines bdcomp.dir_avg_length[*angle] = !lengths.empty() ? *std::max_element(lengths.begin(), lengths.end()) : 0; } // if no direction produced coverage, then there's no bridge direction if (!have_coverage) return false; // sort directions by score std::sort(angles.begin(), angles.end(), bdcomp); this->angle = angles.front(); if (this->angle >= PI) this->angle -= PI; #ifdef SLIC3R_DEBUG printf(" Optimal infill angle is %d degrees\n", (int)Slic3r::Geometry::rad2deg(this->angle)); #endif return true; } void BridgeDetector::coverage(Polygons* coverage) const { if (this->angle == -1) return; return this->coverage(angle, coverage); } void BridgeDetector::coverage(double angle, Polygons* coverage) const { // Clone our expolygon and rotate it so that we work with vertical lines. ExPolygon expolygon = this->expolygon; expolygon.rotate(PI/2.0 - angle, Point(0,0)); /* Outset the bridge expolygon by half the amount we used for detecting anchors; we'll use this one to generate our trapezoids and be sure that their vertices are inside the anchors and not on their contours leading to false negatives. */ ExPolygons grown; offset(expolygon, &grown, this->extrusion_width/2.0); // Compute trapezoids according to a vertical orientation Polygons trapezoids; for (ExPolygons::const_iterator it = grown.begin(); it != grown.end(); ++it) it->get_trapezoids2(&trapezoids, PI/2.0); // get anchors, convert them to Polygons and rotate them too Polygons anchors; for (ExPolygons::const_iterator anchor = this->_anchors.begin(); anchor != this->_anchors.end(); ++anchor) { Polygons pp = *anchor; for (Polygons::iterator p = pp.begin(); p != pp.end(); ++p) p->rotate(PI/2.0 - angle, Point(0,0)); anchors.insert(anchors.end(), pp.begin(), pp.end()); } Polygons covered; for (Polygons::const_iterator trapezoid = trapezoids.begin(); trapezoid != trapezoids.end(); ++trapezoid) { Lines lines = trapezoid->lines(); Lines supported; intersection(lines, anchors, &supported); // not nice, we need a more robust non-numeric check for (size_t i = 0; i < supported.size(); ++i) { if (supported[i].length() < this->extrusion_width) { supported.erase(supported.begin() + i); i--; } } if (supported.size() >= 2) covered.push_back(*trapezoid); } // merge trapezoids and rotate them back Polygons _coverage; union_(covered, &_coverage); for (Polygons::iterator p = _coverage.begin(); p != _coverage.end(); ++p) p->rotate(-(PI/2.0 - angle), Point(0,0)); // intersect trapezoids with actual bridge area to remove extra margins // and append it to result intersection(_coverage, this->expolygon, coverage); /* if (0) { my @lines = map @{$_->lines}, @$trapezoids; $_->rotate(-(PI/2 - $angle), [0,0]) for @lines; require "Slic3r/SVG.pm"; Slic3r::SVG::output( "coverage_" . rad2deg($angle) . ".svg", expolygons => [$self->expolygon], green_expolygons => $self->_anchors, red_expolygons => $coverage, lines => \@lines, ); } */ } /* This method returns the bridge edges (as polylines) that are not supported but would allow the entire bridge area to be bridged with detected angle if supported too */ void BridgeDetector::unsupported_edges(Polylines* unsupported) const { if (this->angle == -1) return; return this->unsupported_edges(this->angle, unsupported); } void BridgeDetector::unsupported_edges(double angle, Polylines* unsupported) const { // get bridge edges (both contour and holes) Polylines bridge_edges; { Polygons pp = this->expolygon; bridge_edges.insert(bridge_edges.end(), pp.begin(), pp.end()); // this uses split_at_first_point() } // get unsupported edges Polygons grown_lower; offset(this->lower_slices, &grown_lower, +this->extrusion_width); Polylines _unsupported; diff(bridge_edges, grown_lower, &_unsupported); /* Split into individual segments and filter out edges parallel to the bridging angle TODO: angle tolerance should probably be based on segment length and flow width, so that we build supports whenever there's a chance that at least one or two bridge extrusions would be anchored within such length (i.e. a slightly non-parallel bridging direction might still benefit from anchors if long enough) */ double angle_tolerance = PI / 180.0 * 5.0; for (Polylines::const_iterator polyline = _unsupported.begin(); polyline != _unsupported.end(); ++polyline) { Lines lines = polyline->lines(); for (Lines::const_iterator line = lines.begin(); line != lines.end(); ++line) { if (!Slic3r::Geometry::directions_parallel(line->direction(), angle)) unsupported->push_back(*line); } } /* if (0) { require "Slic3r/SVG.pm"; Slic3r::SVG::output( "unsupported_" . rad2deg($angle) . ".svg", expolygons => [$self->expolygon], green_expolygons => $self->_anchors, red_expolygons => union_ex($grown_lower), no_arrows => 1, polylines => \@bridge_edges, red_polylines => $unsupported, ); } */ } #ifdef SLIC3RXS REGISTER_CLASS(BridgeDetector, "BridgeDetector"); #endif }
38.46988
118
0.615096
[ "geometry", "vector" ]
5eecc9735a7c23440f4f2e7f477793e464e05700
1,499
cc
C++
src/objects/Object.cc
JamesHoltom/TermEngine
7149322c15a66547d6e6ae8b8c76ec925fe5bbf5
[ "MIT" ]
1
2021-01-22T19:24:08.000Z
2021-01-22T19:24:08.000Z
src/objects/Object.cc
JamesHoltom/TermEngine
7149322c15a66547d6e6ae8b8c76ec925fe5bbf5
[ "MIT" ]
null
null
null
src/objects/Object.cc
JamesHoltom/TermEngine
7149322c15a66547d6e6ae8b8c76ec925fe5bbf5
[ "MIT" ]
null
null
null
#include "Object.h" #include "../logging/Logger.h" namespace term_engine::objects { Object::Object(const glm::vec2& position, const glm::ivec2& size) : object_id_(Object::object_next_id_++), position_(position), size_(size) { size_t data_size = (size_t)size.x * (size_t)size.y; data_.reserve(data_size); data_.resize(data_size); logging::logger->debug("Created {}x{} object with {} elements.", size.x, size.y, data_size); } glm::vec2 Object::GetPosition() const { return position_; } glm::ivec2 Object::GetSize() const { return size_; } GlyphData& Object::GetData() { return data_; } bool Object::IsActive() const { return is_active_; } void Object::SetPosition(const glm::vec2& position) { position_ = position; Object::is_dirty_ = true; } void Object::SetSize(const glm::ivec2& size) { size_t old_data_size = (size_t)size_.x * (size_t)size_.y; size_t new_data_size = (size_t)size.x * (size_t)size.y; if (old_data_size < new_data_size) { data_.reserve(new_data_size); } data_.resize(new_data_size); data_.shrink_to_fit(); size_ = size; Object::is_dirty_ = true; } void Object::SetActive(const bool& flag) { is_active_ = flag; } bool Object::IsDirty() { return Object::is_dirty_; } void Object::SetDirty(const bool& flag) { Object::is_dirty_ = flag; } int Object::object_next_id_ = 0; bool Object::is_dirty_ = true; }
19.467532
96
0.641761
[ "object" ]
5eef3f97ba4c75295e9350e2660265375d96c12c
4,729
hpp
C++
app/tenncor/include/graph/connector/iconnector.hpp
mingkaic/rocnnet
b0e6b9ef1b80ee3d33d68f48dd051a99c2df39ab
[ "MIT" ]
3
2017-01-18T20:42:56.000Z
2018-11-07T12:56:15.000Z
app/tenncor/include/graph/connector/iconnector.hpp
mingkaic/rocnnet
b0e6b9ef1b80ee3d33d68f48dd051a99c2df39ab
[ "MIT" ]
10
2016-12-01T08:15:28.000Z
2018-09-28T17:16:32.000Z
app/tenncor/include/graph/connector/iconnector.hpp
mingkaic/rocnnet
b0e6b9ef1b80ee3d33d68f48dd051a99c2df39ab
[ "MIT" ]
null
null
null
/*! * * iconnector.hpp * cnnet * * Purpose: * graph connector interface * manages graph information * * Created by Mingkai Chen on 2016-12-01. * Copyright © 2016 Mingkai Chen. All rights reserved. * */ #include "graph/varptr.hpp" #include "graph/leaf/constant.hpp" #pragma once #ifndef TENNCOR_ICONNECTOR_HPP #define TENNCOR_ICONNECTOR_HPP namespace nnet { //! backward transfer function, get gradient nodes; F: Nf -> Nb template <typename T> using BACK_MAP = std::function<varptr<T>(std::vector<std::pair<inode<T>*,inode<T>*> >)>; template <typename T> using NODE_MAN = std::function<inode<T>*(inode<T>*)>; //! jacobian transfer function template <typename T> using JTRANSFER = std::function<inode<T>*(inode<T>*,std::vector<inode<T>*>,std::vector<inode<T>*>)>; //! calculate output shape from argument shapes using SHAPER = std::function<tensorshape(std::vector<tensorshape>)>; template <typename T> class iconnector : public inode<T>, public iobserver { public: //! iconnector summary struct conn_summary { conn_summary (std::string id, SHAPER shaper, TRANSFER_FUNC<T> forward, BACK_MAP<T> back) : id_(id), shaper_(shaper), Nf_(forward), ginit_(back) {} std::string id_; SHAPER shaper_; TRANSFER_FUNC<T> Nf_; BACK_MAP<T> ginit_; std::vector<std::string> arg_ids_; }; using summary_series = std::vector<typename iconnector<T>::conn_summary>; virtual ~iconnector (void); // >>>> CLONER & ASSIGNMENT OPERATORS <<<< //! clone function iconnector<T>* clone (void) const; //! move function iconnector<T>* move (void); //! declare copy assignment to enforce proper g_man_ copy over virtual iconnector<T>& operator = (const iconnector<T>& other); //! declare move assignment to enforce proper g_man_ copy over virtual iconnector<T>& operator = (iconnector<T>&& other); // >>>> IDENTIFICATION <<<< //! get unique label with arguments virtual std::string get_name (void) const; //! get the distance between this node and the furthest dependent leaf (maximum spanning tree height) virtual size_t get_depth (void) const; // >>>> OBSERVER & OBSERVABLE INFO <<<< //! get all observerables virtual std::vector<inode<T>*> get_arguments (void) const; //! get the number of observables virtual size_t n_arguments (void) const; // >>>> FORWARD & BACKWARD DATA <<<< //! grab a temporary value traversing top-down virtual void temporary_eval (const iconnector<T>* target, inode<T>*& out) const = 0; //! get forward passing value, (pull data if necessary) virtual const tensor<T>* eval (void); // >>>> GRAPH STATUS <<<< //! check if other connector is in the same graph as this bool is_same_graph (const iconnector<T>* other) const; //! check if connector n is a potential descendent of this node //! will return false negatives if nodes are in a pipeline of a non-variable leaf virtual bool potential_descendent (const iconnector<T>* n) const; // >>>> NODE STATUS <<<< //! add jacobian to the front of the list mapped by leaves void set_jacobian_front (JTRANSFER<T> jac, std::vector<variable<T>*> leaves); //! add jacobian to the back of the list mapped by leaves void set_jacobian_back (JTRANSFER<T> jac, std::vector<variable<T>*> leaves); //! freeze or unfreeze the current node //! freeze prevents this from updating temporarily instead update is queued to g_man_ void freeze_status (bool freeze); protected: //! list of jacobian transfer function //! to be executed on resulting root node //! execution order: top-down struct JList; //! graph info shareable between connectors struct graph_manager; // >>>> CONSTRUCTORS <<<< //! Set dependencies iconnector (std::vector<inode<T>*> dependencies, std::string label); //! Declare copy constructor to enforce proper g_man_ copy over iconnector (const iconnector<T>& other); //! Declare move constructor to enforce proper g_man_ copy over iconnector (iconnector<T>&& other); // >>>> MANAGE GRAPH INFO <<<< //! Update g_man_ by updating all argument variables virtual void update_graph (std::vector<iconnector<T>*> args); varptr<T> jacobian_call (varptr<T> out, variable<T>* leaf) const; //! specialized operator: jacobian operators for each variable, //! executed in derive std::unordered_map<variable<T>*,JList> jacobians_; //! graph meta_data/manager graph_manager* g_man_ = nullptr; private: void copy_helper (const iconnector<T>& other); void move_helper (iconnector<T>&& other); void jacobian_correction (const inode<T>* other); //! the distance between this node and the furthest dependent leaf (maximum spanning tree height) size_t depth_ = 0; }; } #include "../../../src/graph/connector/iconnector.ipp" #endif /* TENNCOR_ICONNECTOR_HPP */
29.01227
102
0.714527
[ "shape", "vector" ]
d6734f157da2e276ae901626c5a98c19776993ad
3,198
cc
C++
waf-openapi/src/model/ModifyProtectionRuleStatusRequest.cc
aliyun/aliyun-openapi-cpp-sdk
0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36
[ "Apache-2.0" ]
89
2018-02-02T03:54:39.000Z
2021-12-13T01:32:55.000Z
waf-openapi/src/model/ModifyProtectionRuleStatusRequest.cc
aliyun/aliyun-openapi-cpp-sdk
0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36
[ "Apache-2.0" ]
89
2018-03-14T07:44:54.000Z
2021-11-26T07:43:25.000Z
waf-openapi/src/model/ModifyProtectionRuleStatusRequest.cc
aliyun/aliyun-openapi-cpp-sdk
0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36
[ "Apache-2.0" ]
69
2018-01-22T09:45:52.000Z
2022-03-28T07:58:38.000Z
/* * Copyright 2009-2017 Alibaba Cloud All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <alibabacloud/waf-openapi/model/ModifyProtectionRuleStatusRequest.h> using AlibabaCloud::Waf_openapi::Model::ModifyProtectionRuleStatusRequest; ModifyProtectionRuleStatusRequest::ModifyProtectionRuleStatusRequest() : RpcServiceRequest("waf-openapi", "2018-01-17", "ModifyProtectionRuleStatus") { setMethod(HttpRequest::Method::Post); } ModifyProtectionRuleStatusRequest::~ModifyProtectionRuleStatusRequest() {} long ModifyProtectionRuleStatusRequest::getLockVersion()const { return lockVersion_; } void ModifyProtectionRuleStatusRequest::setLockVersion(long lockVersion) { lockVersion_ = lockVersion; setParameter("LockVersion", std::to_string(lockVersion)); } std::string ModifyProtectionRuleStatusRequest::getSourceIp()const { return sourceIp_; } void ModifyProtectionRuleStatusRequest::setSourceIp(const std::string& sourceIp) { sourceIp_ = sourceIp; setParameter("SourceIp", sourceIp); } std::string ModifyProtectionRuleStatusRequest::getDefense()const { return defense_; } void ModifyProtectionRuleStatusRequest::setDefense(const std::string& defense) { defense_ = defense; setParameter("Defense", defense); } long ModifyProtectionRuleStatusRequest::getId()const { return id_; } void ModifyProtectionRuleStatusRequest::setId(long id) { id_ = id; setParameter("Id", std::to_string(id)); } std::string ModifyProtectionRuleStatusRequest::getLang()const { return lang_; } void ModifyProtectionRuleStatusRequest::setLang(const std::string& lang) { lang_ = lang; setParameter("Lang", lang); } int ModifyProtectionRuleStatusRequest::getRuleStatus()const { return ruleStatus_; } void ModifyProtectionRuleStatusRequest::setRuleStatus(int ruleStatus) { ruleStatus_ = ruleStatus; setParameter("RuleStatus", std::to_string(ruleStatus)); } std::string ModifyProtectionRuleStatusRequest::getInstanceId()const { return instanceId_; } void ModifyProtectionRuleStatusRequest::setInstanceId(const std::string& instanceId) { instanceId_ = instanceId; setParameter("InstanceId", instanceId); } std::string ModifyProtectionRuleStatusRequest::getDomain()const { return domain_; } void ModifyProtectionRuleStatusRequest::setDomain(const std::string& domain) { domain_ = domain; setParameter("Domain", domain); } std::string ModifyProtectionRuleStatusRequest::getRegion()const { return region_; } void ModifyProtectionRuleStatusRequest::setRegion(const std::string& region) { region_ = region; setParameter("Region", region); }
24.790698
85
0.761726
[ "model" ]
d674cda409235841207097ba85022229b97235de
99,137
cpp
C++
unit_tests/command_stream/aub_command_stream_receiver_tests.cpp
cmey/compute-runtime
118bad16dfe523724dfaf8016bfa6fbe6896348b
[ "MIT" ]
null
null
null
unit_tests/command_stream/aub_command_stream_receiver_tests.cpp
cmey/compute-runtime
118bad16dfe523724dfaf8016bfa6fbe6896348b
[ "MIT" ]
null
null
null
unit_tests/command_stream/aub_command_stream_receiver_tests.cpp
cmey/compute-runtime
118bad16dfe523724dfaf8016bfa6fbe6896348b
[ "MIT" ]
null
null
null
/* * Copyright (c) 2017 - 2018, Intel Corporation * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ #include "runtime/aub_mem_dump/aub_mem_dump.h" #include "runtime/command_stream/aub_command_stream_receiver_hw.h" #include "runtime/helpers/array_count.h" #include "runtime/helpers/dispatch_info.h" #include "runtime/helpers/flat_batch_buffer_helper_hw.h" #include "runtime/helpers/hw_info.h" #include "runtime/memory_manager/memory_manager.h" #include "runtime/os_interface/debug_settings_manager.h" #include "test.h" #include "unit_tests/fixtures/device_fixture.h" #include "unit_tests/helpers/debug_manager_state_restore.h" #include "unit_tests/mocks/mock_aub_subcapture_manager.h" #include "unit_tests/mocks/mock_csr.h" #include "unit_tests/mocks/mock_gmm.h" #include "unit_tests/mocks/mock_kernel.h" #include "unit_tests/mocks/mock_mdi.h" #include <memory> #if defined(__clang__) #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winconsistent-missing-override" #endif using namespace OCLRT; using ::testing::_; using ::testing::Invoke; using ::testing::Return; typedef Test<DeviceFixture> AubCommandStreamReceiverTests; template <typename GfxFamily> struct MockAubCsr : public AUBCommandStreamReceiverHw<GfxFamily> { MockAubCsr(const HardwareInfo &hwInfoIn, const std::string &fileName, bool standalone, ExecutionEnvironment &executionEnvironment) : AUBCommandStreamReceiverHw<GfxFamily>(hwInfoIn, fileName, standalone, executionEnvironment){}; DispatchMode peekDispatchMode() const { return this->dispatchMode; } GraphicsAllocation *getTagAllocation() const { return this->tagAllocation; } void setLatestSentTaskCount(uint32_t latestSentTaskCount) { this->latestSentTaskCount = latestSentTaskCount; } void flushBatchedSubmissions() override { flushBatchedSubmissionsCalled = true; } void initProgrammingFlags() override { initProgrammingFlagsCalled = true; } bool flushBatchedSubmissionsCalled = false; bool initProgrammingFlagsCalled = false; void initFile(const std::string &fileName) override { fileIsOpen = true; openFileName = fileName; } void closeFile() override { fileIsOpen = false; openFileName = ""; } bool isFileOpen() override { return fileIsOpen; } const std::string &getFileName() override { return openFileName; } bool fileIsOpen = false; std::string openFileName = ""; MOCK_METHOD0(addPatchInfoComments, bool(void)); }; template <typename GfxFamily> struct MockAubCsrToTestDumpAubNonWritable : public AUBCommandStreamReceiverHw<GfxFamily> { using AUBCommandStreamReceiverHw<GfxFamily>::AUBCommandStreamReceiverHw; using AUBCommandStreamReceiverHw<GfxFamily>::dumpAubNonWritable; bool writeMemory(GraphicsAllocation &gfxAllocation) override { return true; } }; struct MockAubFileStream : public AUBCommandStreamReceiver::AubFileStream { void flush() override { flushCalled = true; } bool flushCalled = false; }; struct GmockAubFileStream : public AUBCommandStreamReceiver::AubFileStream { MOCK_METHOD1(addComment, bool(const char *message)); }; struct AubExecutionEnvironment { std::unique_ptr<ExecutionEnvironment> executionEnvironment; GraphicsAllocation *commandBuffer = nullptr; template <typename CsrType> CsrType *getCsr() { return static_cast<CsrType *>(executionEnvironment->commandStreamReceiver.get()); } ~AubExecutionEnvironment() { if (commandBuffer) { executionEnvironment->memoryManager->freeGraphicsMemory(commandBuffer); } } }; template <typename CsrType> std::unique_ptr<AubExecutionEnvironment> getEnvironment(bool createTagAllocation, bool allocateCommandBuffer, bool standalone) { std::unique_ptr<ExecutionEnvironment> executionEnvironment(new ExecutionEnvironment); executionEnvironment->commandStreamReceiver.reset(new CsrType(*platformDevices[0], "", standalone, *executionEnvironment)); executionEnvironment->memoryManager.reset(executionEnvironment->commandStreamReceiver->createMemoryManager(false)); executionEnvironment->commandStreamReceiver->setMemoryManager(executionEnvironment->memoryManager.get()); if (createTagAllocation) { executionEnvironment->commandStreamReceiver->initializeTagAllocation(); } std::unique_ptr<AubExecutionEnvironment> aubExecutionEnvironment(new AubExecutionEnvironment); if (allocateCommandBuffer) { aubExecutionEnvironment->commandBuffer = executionEnvironment->memoryManager->allocateGraphicsMemory(4096); } aubExecutionEnvironment->executionEnvironment = std::move(executionEnvironment); return aubExecutionEnvironment; } TEST_F(AubCommandStreamReceiverTests, givenStructureWhenMisalignedUint64ThenUseSetterGetterFunctionsToSetGetValue) { const uint64_t value = 0x0123456789ABCDEFu; AubMemDump::AubCaptureBinaryDumpHD aubCaptureBinaryDumpHD{}; aubCaptureBinaryDumpHD.setBaseAddr(value); EXPECT_EQ(value, aubCaptureBinaryDumpHD.getBaseAddr()); aubCaptureBinaryDumpHD.setWidth(value); EXPECT_EQ(value, aubCaptureBinaryDumpHD.getWidth()); aubCaptureBinaryDumpHD.setHeight(value); EXPECT_EQ(value, aubCaptureBinaryDumpHD.getHeight()); aubCaptureBinaryDumpHD.setPitch(value); EXPECT_EQ(value, aubCaptureBinaryDumpHD.getPitch()); AubMemDump::AubCmdDumpBmpHd aubCmdDumpBmpHd{}; aubCmdDumpBmpHd.setBaseAddr(value); EXPECT_EQ(value, aubCmdDumpBmpHd.getBaseAddr()); AubMemDump::CmdServicesMemTraceDumpCompress cmdServicesMemTraceDumpCompress{}; cmdServicesMemTraceDumpCompress.setSurfaceAddress(value); EXPECT_EQ(value, cmdServicesMemTraceDumpCompress.getSurfaceAddress()); } TEST_F(AubCommandStreamReceiverTests, givenAubCommandStreamReceiverWhenItIsCreatedWithWrongGfxCoreFamilyThenNullPointerShouldBeReturned) { HardwareInfo hwInfo = *platformDevices[0]; GFXCORE_FAMILY family = hwInfo.pPlatform->eRenderCoreFamily; const_cast<PLATFORM *>(hwInfo.pPlatform)->eRenderCoreFamily = GFXCORE_FAMILY_FORCE_ULONG; // wrong gfx core family CommandStreamReceiver *aubCsr = AUBCommandStreamReceiver::create(hwInfo, "", true, *pDevice->executionEnvironment); EXPECT_EQ(nullptr, aubCsr); const_cast<PLATFORM *>(hwInfo.pPlatform)->eRenderCoreFamily = family; } TEST_F(AubCommandStreamReceiverTests, givenAubCommandStreamReceiverWhenTypeIsCheckedThenAubCsrIsReturned) { HardwareInfo hwInfo = *platformDevices[0]; std::unique_ptr<CommandStreamReceiver> aubCsr(AUBCommandStreamReceiver::create(hwInfo, "", true, *pDevice->executionEnvironment)); EXPECT_NE(nullptr, aubCsr); EXPECT_EQ(CommandStreamReceiverType::CSR_AUB, aubCsr->getType()); } HWTEST_F(AubCommandStreamReceiverTests, givenAubCsrWhenItIsCreatedWithDefaultSettingsThenItHasBatchedDispatchModeEnabled) { DebugManagerStateRestore stateRestore; DebugManager.flags.CsrDispatchMode.set(0); std::unique_ptr<MockAubCsr<FamilyType>> aubCsr(new MockAubCsr<FamilyType>(*platformDevices[0], "", true, *pDevice->executionEnvironment)); EXPECT_EQ(DispatchMode::BatchedDispatch, aubCsr->peekDispatchMode()); } HWTEST_F(AubCommandStreamReceiverTests, givenAubCsrWhenItIsCreatedWithDebugSettingsThenItHasProperDispatchModeEnabled) { DebugManagerStateRestore stateRestore; DebugManager.flags.CsrDispatchMode.set(static_cast<uint32_t>(DispatchMode::ImmediateDispatch)); std::unique_ptr<MockAubCsr<FamilyType>> aubCsr(new MockAubCsr<FamilyType>(*platformDevices[0], "", true, *pDevice->executionEnvironment)); EXPECT_EQ(DispatchMode::ImmediateDispatch, aubCsr->peekDispatchMode()); } HWTEST_F(AubCommandStreamReceiverTests, givenAubCommandStreamReceiverWhenItIsCreatedThenMemoryManagerIsNotNull) { std::unique_ptr<AUBCommandStreamReceiverHw<FamilyType>> aubCsr(new AUBCommandStreamReceiverHw<FamilyType>(**platformDevices, "", true, *pDevice->executionEnvironment)); std::unique_ptr<MemoryManager> memoryManager(aubCsr->createMemoryManager(false)); EXPECT_NE(nullptr, memoryManager.get()); aubCsr->setMemoryManager(nullptr); } HWTEST_F(AubCommandStreamReceiverTests, givenAubCommandStreamReceiverInSubCaptureModeWhenItIsCreatedThenFileIsNotCreated) { DebugManagerStateRestore stateRestore; DebugManager.flags.AUBDumpSubCaptureMode.set(static_cast<int32_t>(AubSubCaptureManager::SubCaptureMode::Filter)); HardwareInfo hwInfo = *platformDevices[0]; std::string fileName = "file_name.aub"; std::unique_ptr<AUBCommandStreamReceiverHw<FamilyType>> aubCsr(reinterpret_cast<AUBCommandStreamReceiverHw<FamilyType> *>(AUBCommandStreamReceiver::create(hwInfo, fileName, true, *pDevice->executionEnvironment))); EXPECT_NE(nullptr, aubCsr); EXPECT_FALSE(aubCsr->isFileOpen()); } HWTEST_F(AubCommandStreamReceiverTests, givenAubCsrInSubCaptureModeWhenItIsCreatedWithoutDebugFilterSettingsThenItInitializesSubCaptureFiltersWithDefaults) { DebugManagerStateRestore stateRestore; DebugManager.flags.AUBDumpSubCaptureMode.set(static_cast<int32_t>(AubSubCaptureManager::SubCaptureMode::Filter)); std::unique_ptr<MockAubCsr<FamilyType>> aubCsr(new MockAubCsr<FamilyType>(*platformDevices[0], "", true, *pDevice->executionEnvironment)); EXPECT_EQ(0u, aubCsr->subCaptureManager->subCaptureFilter.dumpKernelStartIdx); EXPECT_EQ(static_cast<uint32_t>(-1), aubCsr->subCaptureManager->subCaptureFilter.dumpKernelEndIdx); EXPECT_STREQ("", aubCsr->subCaptureManager->subCaptureFilter.dumpKernelName.c_str()); } HWTEST_F(AubCommandStreamReceiverTests, givenAubCsrInSubCaptureModeWhenItIsCreatedWithDebugFilterSettingsThenItInitializesSubCaptureFiltersWithDebugFilterSettings) { DebugManagerStateRestore stateRestore; DebugManager.flags.AUBDumpSubCaptureMode.set(static_cast<int32_t>(AubSubCaptureManager::SubCaptureMode::Filter)); DebugManager.flags.AUBDumpFilterKernelStartIdx.set(10); DebugManager.flags.AUBDumpFilterKernelEndIdx.set(100); DebugManager.flags.AUBDumpFilterKernelName.set("kernel_name"); std::unique_ptr<MockAubCsr<FamilyType>> aubCsr(new MockAubCsr<FamilyType>(*platformDevices[0], "", true, *pDevice->executionEnvironment)); EXPECT_EQ(static_cast<uint32_t>(DebugManager.flags.AUBDumpFilterKernelStartIdx.get()), aubCsr->subCaptureManager->subCaptureFilter.dumpKernelStartIdx); EXPECT_EQ(static_cast<uint32_t>(DebugManager.flags.AUBDumpFilterKernelEndIdx.get()), aubCsr->subCaptureManager->subCaptureFilter.dumpKernelEndIdx); EXPECT_STREQ(DebugManager.flags.AUBDumpFilterKernelName.get().c_str(), aubCsr->subCaptureManager->subCaptureFilter.dumpKernelName.c_str()); } HWTEST_F(AubCommandStreamReceiverTests, givenAubCommandStreamReceiverWhenInitFileIsCalledWithInvalidFileNameThenFileIsNotOpened) { std::unique_ptr<AUBCommandStreamReceiverHw<FamilyType>> aubCsr(new AUBCommandStreamReceiverHw<FamilyType>(**platformDevices, "", true, *pDevice->executionEnvironment)); std::string invalidFileName = ""; aubCsr->initFile(invalidFileName); EXPECT_FALSE(aubCsr->isFileOpen()); } HWTEST_F(AubCommandStreamReceiverTests, givenAubCommandStreamReceiverWhenInitFileIsCalledThenFileIsOpenedAndFileNameIsStored) { std::unique_ptr<AUBCommandStreamReceiverHw<FamilyType>> aubCsr(new AUBCommandStreamReceiverHw<FamilyType>(**platformDevices, "", true, *pDevice->executionEnvironment)); std::string fileName = "file_name.aub"; aubCsr->initFile(fileName); EXPECT_TRUE(aubCsr->isFileOpen()); EXPECT_STREQ(fileName.c_str(), aubCsr->getFileName().c_str()); aubCsr->closeFile(); EXPECT_FALSE(aubCsr->isFileOpen()); EXPECT_TRUE(aubCsr->getFileName().empty()); } HWTEST_F(AubCommandStreamReceiverTests, givenGraphicsAllocationWhenMakeResidentCalledMultipleTimesAffectsResidencyOnce) { std::unique_ptr<MemoryManager> memoryManager(nullptr); std::unique_ptr<AUBCommandStreamReceiverHw<FamilyType>> aubCsr(new AUBCommandStreamReceiverHw<FamilyType>(*platformDevices[0], "", true, *pDevice->executionEnvironment)); memoryManager.reset(aubCsr->createMemoryManager(false)); auto gfxAllocation = memoryManager->allocateGraphicsMemory(sizeof(uint32_t), sizeof(uint32_t), false, false); // First makeResident marks the allocation resident aubCsr->makeResident(*gfxAllocation); EXPECT_NE(ObjectNotResident, gfxAllocation->residencyTaskCount); EXPECT_EQ((int)aubCsr->peekTaskCount() + 1, gfxAllocation->residencyTaskCount); EXPECT_EQ(1u, memoryManager->getResidencyAllocations().size()); // Second makeResident should have no impact aubCsr->makeResident(*gfxAllocation); EXPECT_NE(ObjectNotResident, gfxAllocation->residencyTaskCount); EXPECT_EQ((int)aubCsr->peekTaskCount() + 1, gfxAllocation->residencyTaskCount); EXPECT_EQ(1u, memoryManager->getResidencyAllocations().size()); // First makeNonResident marks the allocation as nonresident aubCsr->makeNonResident(*gfxAllocation); EXPECT_EQ(ObjectNotResident, gfxAllocation->residencyTaskCount); EXPECT_EQ(1u, memoryManager->getEvictionAllocations().size()); // Second makeNonResident should have no impact aubCsr->makeNonResident(*gfxAllocation); EXPECT_EQ(ObjectNotResident, gfxAllocation->residencyTaskCount); EXPECT_EQ(1u, memoryManager->getEvictionAllocations().size()); memoryManager->freeGraphicsMemoryImpl(gfxAllocation); } HWTEST_F(AubCommandStreamReceiverTests, givenAubCommandStreamReceiverWhenFlushIsCalledThenItShouldInitializeEngineInfoTable) { auto aubExecutionEnvironment = getEnvironment<AUBCommandStreamReceiverHw<FamilyType>>(true, true, true); auto aubCsr = aubExecutionEnvironment->template getCsr<AUBCommandStreamReceiverHw<FamilyType>>(); LinearStream cs(aubExecutionEnvironment->commandBuffer); BatchBuffer batchBuffer{cs.getGraphicsAllocation(), 0, 0, nullptr, false, false, QueueThrottle::MEDIUM, cs.getUsed(), &cs}; auto engineType = OCLRT::ENGINE_RCS; ResidencyContainer allocationsForResidency = {}; aubCsr->flush(batchBuffer, engineType, &allocationsForResidency); EXPECT_NE(nullptr, aubCsr->engineInfoTable[engineType].pLRCA); EXPECT_NE(nullptr, aubCsr->engineInfoTable[engineType].pGlobalHWStatusPage); EXPECT_NE(nullptr, aubCsr->engineInfoTable[engineType].pRingBuffer); } HWTEST_F(AubCommandStreamReceiverTests, givenAubCommandStreamReceiverInSubCaptureModeWhenFlushIsCalledButSubCaptureIsDisabledThenItShouldntInitializeEngineInfoTable) { auto aubExecutionEnvironment = getEnvironment<AUBCommandStreamReceiverHw<FamilyType>>(true, true, true); auto aubCsr = aubExecutionEnvironment->template getCsr<AUBCommandStreamReceiverHw<FamilyType>>(); LinearStream cs(aubExecutionEnvironment->commandBuffer); auto aubSubCaptureManagerMock = new AubSubCaptureManagerMock(""); aubSubCaptureManagerMock->subCaptureMode = AubSubCaptureManager::SubCaptureMode::Toggle; aubSubCaptureManagerMock->disableSubCapture(); aubCsr->subCaptureManager.reset(aubSubCaptureManagerMock); ASSERT_FALSE(aubCsr->subCaptureManager->isSubCaptureEnabled()); BatchBuffer batchBuffer{cs.getGraphicsAllocation(), 0, 0, nullptr, false, false, QueueThrottle::MEDIUM, cs.getUsed(), &cs}; auto engineType = OCLRT::ENGINE_RCS; ResidencyContainer allocationsForResidency = {}; aubCsr->flush(batchBuffer, engineType, &allocationsForResidency); EXPECT_EQ(nullptr, aubCsr->engineInfoTable[engineType].pLRCA); EXPECT_EQ(nullptr, aubCsr->engineInfoTable[engineType].pGlobalHWStatusPage); EXPECT_EQ(nullptr, aubCsr->engineInfoTable[engineType].pRingBuffer); } HWTEST_F(AubCommandStreamReceiverTests, givenAubCommandStreamReceiverWhenFlushIsCalledThenItShouldLeaveProperRingTailAlignment) { auto aubExecutionEnvironment = getEnvironment<AUBCommandStreamReceiverHw<FamilyType>>(true, true, true); auto aubCsr = aubExecutionEnvironment->template getCsr<AUBCommandStreamReceiverHw<FamilyType>>(); LinearStream cs(aubExecutionEnvironment->commandBuffer); auto engineType = OCLRT::ENGINE_RCS; auto ringTailAlignment = sizeof(uint64_t); BatchBuffer batchBuffer{cs.getGraphicsAllocation(), 0, 0, nullptr, false, false, QueueThrottle::MEDIUM, cs.getUsed(), &cs}; // First flush typically includes a preamble and chain to command buffer aubCsr->overrideDispatchPolicy(DispatchMode::ImmediateDispatch); aubCsr->flush(batchBuffer, engineType, nullptr); EXPECT_EQ(0ull, aubCsr->engineInfoTable[engineType].tailRingBuffer % ringTailAlignment); // Second flush should just submit command buffer cs.getSpace(sizeof(uint64_t)); aubCsr->flush(batchBuffer, engineType, nullptr); EXPECT_EQ(0ull, aubCsr->engineInfoTable[engineType].tailRingBuffer % ringTailAlignment); } HWTEST_F(AubCommandStreamReceiverTests, givenAubCommandStreamReceiverInNonStandaloneModeWhenFlushIsCalledThenItShouldNotUpdateHwTagWithLatestSentTaskCount) { auto aubExecutionEnvironment = getEnvironment<MockAubCsr<FamilyType>>(true, true, false); auto aubCsr = aubExecutionEnvironment->template getCsr<MockAubCsr<FamilyType>>(); LinearStream cs(aubExecutionEnvironment->commandBuffer); BatchBuffer batchBuffer{cs.getGraphicsAllocation(), 0, 0, nullptr, false, false, QueueThrottle::MEDIUM, cs.getUsed(), &cs}; auto engineType = OCLRT::ENGINE_RCS; ResidencyContainer allocationsForResidency = {}; EXPECT_EQ(initialHardwareTag, *aubCsr->getTagAddress()); aubCsr->setLatestSentTaskCount(aubCsr->peekTaskCount() + 1); EXPECT_NE(aubCsr->peekLatestSentTaskCount(), *aubCsr->getTagAddress()); aubCsr->flush(batchBuffer, engineType, &allocationsForResidency); EXPECT_NE(aubCsr->peekLatestSentTaskCount(), *aubCsr->getTagAddress()); EXPECT_EQ(initialHardwareTag, *aubCsr->getTagAddress()); } HWTEST_F(AubCommandStreamReceiverTests, givenAubCommandStreamReceiverInStandaloneModeWhenFlushIsCalledThenItShouldUpdateHwTagWithLatestSentTaskCount) { auto aubExecutionEnvironment = getEnvironment<MockAubCsr<FamilyType>>(true, true, true); auto aubCsr = aubExecutionEnvironment->template getCsr<MockAubCsr<FamilyType>>(); LinearStream cs(aubExecutionEnvironment->commandBuffer); BatchBuffer batchBuffer{cs.getGraphicsAllocation(), 0, 0, nullptr, false, false, QueueThrottle::MEDIUM, cs.getUsed(), &cs}; auto engineType = OCLRT::ENGINE_RCS; ResidencyContainer allocationsForResidency = {}; EXPECT_EQ(initialHardwareTag, *aubCsr->getTagAddress()); aubCsr->setLatestSentTaskCount(aubCsr->peekTaskCount() + 1); EXPECT_NE(aubCsr->peekLatestSentTaskCount(), *aubCsr->getTagAddress()); aubCsr->flush(batchBuffer, engineType, &allocationsForResidency); EXPECT_EQ(aubCsr->peekLatestSentTaskCount(), *aubCsr->getTagAddress()); } HWTEST_F(AubCommandStreamReceiverTests, givenAubCommandStreamReceiverInStandaloneAndSubCaptureModeWhenFlushIsCalledButSubCaptureIsDisabledThenItShouldUpdateHwTagWithLatestSentTaskCount) { DebugManagerStateRestore stateRestore; auto aubExecutionEnvironment = getEnvironment<MockAubCsr<FamilyType>>(true, true, true); auto aubCsr = aubExecutionEnvironment->template getCsr<MockAubCsr<FamilyType>>(); LinearStream cs(aubExecutionEnvironment->commandBuffer); auto aubSubCaptureManagerMock = new AubSubCaptureManagerMock(""); aubSubCaptureManagerMock->subCaptureMode = AubSubCaptureManager::SubCaptureMode::Toggle; aubSubCaptureManagerMock->disableSubCapture(); aubCsr->subCaptureManager.reset(aubSubCaptureManagerMock); ASSERT_FALSE(aubCsr->subCaptureManager->isSubCaptureEnabled()); BatchBuffer batchBuffer{cs.getGraphicsAllocation(), 0, 0, nullptr, false, false, QueueThrottle::MEDIUM, cs.getUsed(), &cs}; auto engineType = OCLRT::ENGINE_RCS; ResidencyContainer allocationsForResidency = {}; aubCsr->setLatestSentTaskCount(aubCsr->peekTaskCount() + 1); EXPECT_NE(aubCsr->peekLatestSentTaskCount(), *aubCsr->getTagAddress()); aubCsr->flush(batchBuffer, engineType, &allocationsForResidency); EXPECT_EQ(aubCsr->peekLatestSentTaskCount(), *aubCsr->getTagAddress()); } HWTEST_F(AubCommandStreamReceiverTests, givenAubCommandStreamReceiverInNonStandaloneAndSubCaptureModeWhenFlushIsCalledButSubCaptureIsDisabledThenItShouldNotUpdateHwTagWithLatestSentTaskCount) { DebugManagerStateRestore stateRestore; auto aubExecutionEnvironment = getEnvironment<MockAubCsr<FamilyType>>(true, true, false); auto aubCsr = aubExecutionEnvironment->template getCsr<MockAubCsr<FamilyType>>(); LinearStream cs(aubExecutionEnvironment->commandBuffer); auto aubSubCaptureManagerMock = new AubSubCaptureManagerMock(""); aubSubCaptureManagerMock->subCaptureMode = AubSubCaptureManager::SubCaptureMode::Toggle; aubSubCaptureManagerMock->disableSubCapture(); aubCsr->subCaptureManager.reset(aubSubCaptureManagerMock); ASSERT_FALSE(aubCsr->subCaptureManager->isSubCaptureEnabled()); BatchBuffer batchBuffer{cs.getGraphicsAllocation(), 0, 0, nullptr, false, false, QueueThrottle::MEDIUM, cs.getUsed(), &cs}; auto engineType = OCLRT::ENGINE_RCS; ResidencyContainer allocationsForResidency = {}; aubCsr->setLatestSentTaskCount(aubCsr->peekTaskCount() + 1); EXPECT_NE(aubCsr->peekLatestSentTaskCount(), *aubCsr->getTagAddress()); aubCsr->flush(batchBuffer, engineType, &allocationsForResidency); EXPECT_NE(aubCsr->peekLatestSentTaskCount(), *aubCsr->getTagAddress()); EXPECT_EQ(initialHardwareTag, *aubCsr->getTagAddress()); } HWTEST_F(AubCommandStreamReceiverTests, givenAubCommandStreamReceiverInSubCaptureModeWhenFlushIsCalledAndSubCaptureIsEnabledThenItShouldDeactivateSubCapture) { DebugManagerStateRestore stateRestore; auto aubExecutionEnvironment = getEnvironment<MockAubCsr<FamilyType>>(true, true, false); auto aubCsr = aubExecutionEnvironment->template getCsr<MockAubCsr<FamilyType>>(); LinearStream cs(aubExecutionEnvironment->commandBuffer); const DispatchInfo dispatchInfo; MultiDispatchInfo multiDispatchInfo; multiDispatchInfo.push(dispatchInfo); auto aubSubCaptureManagerMock = new AubSubCaptureManagerMock(""); aubSubCaptureManagerMock->subCaptureMode = AubSubCaptureManager::SubCaptureMode::Toggle; aubSubCaptureManagerMock->setSubCaptureToggleActive(true); aubSubCaptureManagerMock->activateSubCapture(multiDispatchInfo); aubCsr->subCaptureManager.reset(aubSubCaptureManagerMock); ASSERT_TRUE(aubCsr->subCaptureManager->isSubCaptureEnabled()); BatchBuffer batchBuffer{cs.getGraphicsAllocation(), 0, 0, nullptr, false, false, QueueThrottle::MEDIUM, cs.getUsed(), &cs}; auto engineType = OCLRT::ENGINE_RCS; ResidencyContainer allocationsForResidency = {}; aubCsr->flush(batchBuffer, engineType, &allocationsForResidency); EXPECT_FALSE(aubCsr->subCaptureManager->isSubCaptureEnabled()); } HWTEST_F(AubCommandStreamReceiverTests, givenAubCommandStreamReceiverInStandaloneModeWhenFlushIsCalledThenItShouldCallMakeResidentOnCommandBufferAllocation) { auto aubExecutionEnvironment = getEnvironment<MockAubCsr<FamilyType>>(true, true, true); auto aubCsr = aubExecutionEnvironment->template getCsr<MockAubCsr<FamilyType>>(); auto commandBuffer = aubExecutionEnvironment->commandBuffer; LinearStream cs(commandBuffer); BatchBuffer batchBuffer{cs.getGraphicsAllocation(), 0, 0, nullptr, false, false, QueueThrottle::MEDIUM, cs.getUsed(), &cs}; auto engineType = OCLRT::ENGINE_RCS; EXPECT_EQ(ObjectNotResident, commandBuffer->residencyTaskCount); aubCsr->overrideDispatchPolicy(DispatchMode::ImmediateDispatch); aubCsr->flush(batchBuffer, engineType, nullptr); EXPECT_NE(ObjectNotResident, commandBuffer->residencyTaskCount); EXPECT_EQ((int)aubCsr->peekTaskCount() + 1, commandBuffer->residencyTaskCount); aubCsr->makeSurfacePackNonResident(nullptr); EXPECT_EQ(ObjectNotResident, commandBuffer->residencyTaskCount); } HWTEST_F(AubCommandStreamReceiverTests, givenAubCommandStreamReceiverInNoneStandaloneModeWhenFlushIsCalledThenItShouldNotCallMakeResidentOnCommandBufferAllocation) { auto aubExecutionEnvironment = getEnvironment<AUBCommandStreamReceiverHw<FamilyType>>(false, true, false); auto aubCsr = aubExecutionEnvironment->template getCsr<AUBCommandStreamReceiverHw<FamilyType>>(); LinearStream cs(aubExecutionEnvironment->commandBuffer); BatchBuffer batchBuffer{cs.getGraphicsAllocation(), 0, 0, nullptr, false, false, QueueThrottle::MEDIUM, cs.getUsed(), &cs}; auto engineType = OCLRT::ENGINE_RCS; EXPECT_EQ(ObjectNotResident, aubExecutionEnvironment->commandBuffer->residencyTaskCount); aubCsr->flush(batchBuffer, engineType, nullptr); EXPECT_EQ(ObjectNotResident, aubExecutionEnvironment->commandBuffer->residencyTaskCount); } HWTEST_F(AubCommandStreamReceiverTests, givenAubCommandStreamReceiverInStandaloneModeWhenFlushIsCalledThenItShouldCallMakeResidentOnResidencyAllocations) { auto aubExecutionEnvironment = getEnvironment<MockAubCsr<FamilyType>>(true, true, true); auto aubCsr = aubExecutionEnvironment->template getCsr<MockAubCsr<FamilyType>>(); auto memoryManager = aubExecutionEnvironment->executionEnvironment->memoryManager.get(); auto commandBuffer = aubExecutionEnvironment->commandBuffer; LinearStream cs(commandBuffer); auto gfxAllocation = memoryManager->allocateGraphicsMemory(sizeof(uint32_t), sizeof(uint32_t), false, false); ASSERT_NE(nullptr, gfxAllocation); BatchBuffer batchBuffer{cs.getGraphicsAllocation(), 0, 0, nullptr, false, false, QueueThrottle::MEDIUM, cs.getUsed(), &cs}; auto engineType = OCLRT::ENGINE_RCS; ResidencyContainer allocationsForResidency = {gfxAllocation}; EXPECT_EQ(ObjectNotResident, gfxAllocation->residencyTaskCount); EXPECT_EQ(ObjectNotResident, commandBuffer->residencyTaskCount); aubCsr->overrideDispatchPolicy(DispatchMode::BatchedDispatch); aubCsr->flush(batchBuffer, engineType, &allocationsForResidency); EXPECT_NE(ObjectNotResident, gfxAllocation->residencyTaskCount); EXPECT_EQ((int)aubCsr->peekTaskCount() + 1, gfxAllocation->residencyTaskCount); EXPECT_NE(ObjectNotResident, commandBuffer->residencyTaskCount); EXPECT_EQ((int)aubCsr->peekTaskCount() + 1, commandBuffer->residencyTaskCount); aubCsr->makeSurfacePackNonResident(&allocationsForResidency); EXPECT_EQ(ObjectNotResident, gfxAllocation->residencyTaskCount); EXPECT_EQ(ObjectNotResident, commandBuffer->residencyTaskCount); memoryManager->freeGraphicsMemory(gfxAllocation); } HWTEST_F(AubCommandStreamReceiverTests, givenAubCommandStreamReceiverInNoneStandaloneModeWhenFlushIsCalledThenItShouldNotCallMakeResidentOnResidencyAllocations) { auto aubExecutionEnvironment = getEnvironment<AUBCommandStreamReceiverHw<FamilyType>>(true, true, false); auto aubCsr = aubExecutionEnvironment->template getCsr<AUBCommandStreamReceiverHw<FamilyType>>(); auto memoryManager = aubExecutionEnvironment->executionEnvironment->memoryManager.get(); auto commandBuffer = aubExecutionEnvironment->commandBuffer; LinearStream cs(commandBuffer); auto gfxAllocation = memoryManager->allocateGraphicsMemory(sizeof(uint32_t), sizeof(uint32_t), false, false); BatchBuffer batchBuffer{cs.getGraphicsAllocation(), 0, 0, nullptr, false, false, QueueThrottle::MEDIUM, cs.getUsed(), &cs}; auto engineType = OCLRT::ENGINE_RCS; ResidencyContainer allocationsForResidency = {gfxAllocation}; EXPECT_EQ(ObjectNotResident, gfxAllocation->residencyTaskCount); EXPECT_EQ(ObjectNotResident, commandBuffer->residencyTaskCount); aubCsr->flush(batchBuffer, engineType, &allocationsForResidency); EXPECT_EQ(ObjectNotResident, gfxAllocation->residencyTaskCount); EXPECT_EQ(ObjectNotResident, commandBuffer->residencyTaskCount); memoryManager->freeGraphicsMemoryImpl(gfxAllocation); } HWTEST_F(AubCommandStreamReceiverTests, givenAubCommandStreamReceiverInStandaloneAndSubCaptureModeWhenFlushIsCalledAndSubCaptureIsEnabledThenItShouldCallMakeResidentOnCommandBufferAndResidencyAllocations) { DebugManagerStateRestore stateRestore; auto aubExecutionEnvironment = getEnvironment<MockAubCsr<FamilyType>>(true, true, true); auto aubCsr = aubExecutionEnvironment->template getCsr<MockAubCsr<FamilyType>>(); auto memoryManager = aubExecutionEnvironment->executionEnvironment->memoryManager.get(); auto commandBuffer = aubExecutionEnvironment->commandBuffer; LinearStream cs(commandBuffer); const DispatchInfo dispatchInfo; MultiDispatchInfo multiDispatchInfo; multiDispatchInfo.push(dispatchInfo); auto aubSubCaptureManagerMock = new AubSubCaptureManagerMock(""); aubSubCaptureManagerMock->subCaptureMode = AubSubCaptureManager::SubCaptureMode::Toggle; aubSubCaptureManagerMock->setSubCaptureToggleActive(true); aubSubCaptureManagerMock->activateSubCapture(multiDispatchInfo); aubCsr->subCaptureManager.reset(aubSubCaptureManagerMock); ASSERT_TRUE(aubCsr->subCaptureManager->isSubCaptureEnabled()); auto gfxAllocation = memoryManager->allocateGraphicsMemory(sizeof(uint32_t), sizeof(uint32_t), false, false); ASSERT_NE(nullptr, gfxAllocation); BatchBuffer batchBuffer{cs.getGraphicsAllocation(), 0, 0, nullptr, false, false, QueueThrottle::MEDIUM, cs.getUsed(), &cs}; auto engineType = OCLRT::ENGINE_RCS; ResidencyContainer allocationsForResidency = {gfxAllocation}; EXPECT_EQ(ObjectNotResident, gfxAllocation->residencyTaskCount); EXPECT_EQ(ObjectNotResident, commandBuffer->residencyTaskCount); aubCsr->overrideDispatchPolicy(DispatchMode::BatchedDispatch); aubCsr->flush(batchBuffer, engineType, &allocationsForResidency); EXPECT_NE(ObjectNotResident, gfxAllocation->residencyTaskCount); EXPECT_EQ((int)aubCsr->peekTaskCount() + 1, gfxAllocation->residencyTaskCount); EXPECT_NE(ObjectNotResident, commandBuffer->residencyTaskCount); EXPECT_EQ((int)aubCsr->peekTaskCount() + 1, commandBuffer->residencyTaskCount); aubCsr->makeSurfacePackNonResident(&allocationsForResidency); EXPECT_EQ(ObjectNotResident, gfxAllocation->residencyTaskCount); EXPECT_EQ(ObjectNotResident, commandBuffer->residencyTaskCount); memoryManager->freeGraphicsMemory(gfxAllocation); } HWTEST_F(AubCommandStreamReceiverTests, givenAubCommandStreamReceiverWhenGraphicsAllocationIsCreatedThenItDoesntHaveTypeNonAubWritable) { auto aubExecutionEnvironment = getEnvironment<AUBCommandStreamReceiverHw<FamilyType>>(false, false, true); auto memoryManager = aubExecutionEnvironment->executionEnvironment->memoryManager.get(); auto gfxAllocation = memoryManager->allocateGraphicsMemory(sizeof(uint32_t), sizeof(uint32_t), false, false); EXPECT_TRUE(gfxAllocation->isAubWritable()); memoryManager->freeGraphicsMemory(gfxAllocation); } HWTEST_F(AubCommandStreamReceiverTests, givenAubCommandStreamReceiverWhenProcessResidencyIsCalledOnDefaultAllocationThenAllocationTypeShouldNotBeMadeNonAubWritable) { auto aubExecutionEnvironment = getEnvironment<AUBCommandStreamReceiverHw<FamilyType>>(false, false, true); auto aubCsr = aubExecutionEnvironment->template getCsr<AUBCommandStreamReceiverHw<FamilyType>>(); auto memoryManager = aubExecutionEnvironment->executionEnvironment->memoryManager.get(); auto gfxDefaultAllocation = memoryManager->allocateGraphicsMemory(sizeof(uint32_t), sizeof(uint32_t), false, false); ResidencyContainer allocationsForResidency = {gfxDefaultAllocation}; aubCsr->processResidency(&allocationsForResidency); EXPECT_TRUE(gfxDefaultAllocation->isAubWritable()); memoryManager->freeGraphicsMemory(gfxDefaultAllocation); } HWTEST_F(AubCommandStreamReceiverTests, givenAubCommandStreamReceiverWhenWriteMemoryIsCalledOnBufferAndImageTypeAllocationsThenAllocationsHaveAubWritableSetToFalse) { std::unique_ptr<MemoryManager> memoryManager(nullptr); std::unique_ptr<AUBCommandStreamReceiverHw<FamilyType>> aubCsr(new AUBCommandStreamReceiverHw<FamilyType>(*platformDevices[0], "", true, *pDevice->executionEnvironment)); memoryManager.reset(aubCsr->createMemoryManager(false)); auto gfxAllocation = memoryManager->allocateGraphicsMemory(sizeof(uint32_t), sizeof(uint32_t), false, false); GraphicsAllocation::AllocationType onlyOneTimeAubWritableTypes[] = { GraphicsAllocation::AllocationType::BUFFER, GraphicsAllocation::AllocationType::BUFFER_HOST_MEMORY, GraphicsAllocation::AllocationType::BUFFER_COMPRESSED, GraphicsAllocation::AllocationType::IMAGE}; for (size_t i = 0; i < arrayCount(onlyOneTimeAubWritableTypes); i++) { gfxAllocation->setAubWritable(true); gfxAllocation->setAllocationType(onlyOneTimeAubWritableTypes[i]); aubCsr->writeMemory(*gfxAllocation); EXPECT_FALSE(gfxAllocation->isAubWritable()); } memoryManager->freeGraphicsMemory(gfxAllocation); } HWTEST_F(AubCommandStreamReceiverTests, givenAubCommandStreamReceiverWhenProcessResidencyIsCalledOnBufferAndImageAllocationsThenAllocationsTypesShouldBeMadeNonAubWritable) { std::unique_ptr<MemoryManager> memoryManager(nullptr); std::unique_ptr<AUBCommandStreamReceiverHw<FamilyType>> aubCsr(new AUBCommandStreamReceiverHw<FamilyType>(*platformDevices[0], "", true, *pDevice->executionEnvironment)); memoryManager.reset(aubCsr->createMemoryManager(false)); auto gfxBufferAllocation = memoryManager->allocateGraphicsMemory(sizeof(uint32_t), sizeof(uint32_t), false, false); gfxBufferAllocation->setAllocationType(GraphicsAllocation::AllocationType::BUFFER); auto gfxImageAllocation = memoryManager->allocateGraphicsMemory(sizeof(uint32_t), sizeof(uint32_t), false, false); gfxImageAllocation->setAllocationType(GraphicsAllocation::AllocationType::IMAGE); ResidencyContainer allocationsForResidency = {gfxBufferAllocation, gfxImageAllocation}; aubCsr->processResidency(&allocationsForResidency); EXPECT_FALSE(gfxBufferAllocation->isAubWritable()); EXPECT_FALSE(gfxImageAllocation->isAubWritable()); memoryManager->freeGraphicsMemory(gfxBufferAllocation); memoryManager->freeGraphicsMemory(gfxImageAllocation); } HWTEST_F(AubCommandStreamReceiverTests, givenAubCommandStreamReceiverInSubCaptureModWhenProcessResidencyIsCalledWithDumpAubNonWritableFlagThenAllocationsTypesShouldBeMadeAubWritable) { DebugManagerStateRestore stateRestore; std::unique_ptr<MemoryManager> memoryManager(nullptr); std::unique_ptr<MockAubCsrToTestDumpAubNonWritable<FamilyType>> aubCsr(new MockAubCsrToTestDumpAubNonWritable<FamilyType>(*platformDevices[0], "", true, *pDevice->executionEnvironment)); memoryManager.reset(aubCsr->createMemoryManager(false)); auto gfxBufferAllocation = memoryManager->allocateGraphicsMemory(sizeof(uint32_t), sizeof(uint32_t), false, false); gfxBufferAllocation->setAllocationType(GraphicsAllocation::AllocationType::BUFFER); gfxBufferAllocation->setAubWritable(false); auto gfxImageAllocation = memoryManager->allocateGraphicsMemory(sizeof(uint32_t), sizeof(uint32_t), false, false); gfxImageAllocation->setAllocationType(GraphicsAllocation::AllocationType::IMAGE); gfxImageAllocation->setAubWritable(false); aubCsr->dumpAubNonWritable = true; ResidencyContainer allocationsForResidency = {gfxBufferAllocation, gfxImageAllocation}; aubCsr->processResidency(&allocationsForResidency); EXPECT_TRUE(gfxBufferAllocation->isAubWritable()); EXPECT_TRUE(gfxImageAllocation->isAubWritable()); memoryManager->freeGraphicsMemory(gfxBufferAllocation); memoryManager->freeGraphicsMemory(gfxImageAllocation); } HWTEST_F(AubCommandStreamReceiverTests, givenAubCommandStreamReceiverWhenProcessResidencyIsCalledWithoutDumpAubWritableFlagThenAllocationsTypesShouldBeKeptNonAubWritable) { DebugManagerStateRestore stateRestore; std::unique_ptr<MemoryManager> memoryManager(nullptr); std::unique_ptr<MockAubCsrToTestDumpAubNonWritable<FamilyType>> aubCsr(new MockAubCsrToTestDumpAubNonWritable<FamilyType>(*platformDevices[0], "", true, *pDevice->executionEnvironment)); memoryManager.reset(aubCsr->createMemoryManager(false)); auto gfxBufferAllocation = memoryManager->allocateGraphicsMemory(sizeof(uint32_t), sizeof(uint32_t), false, false); gfxBufferAllocation->setAllocationType(GraphicsAllocation::AllocationType::BUFFER); gfxBufferAllocation->setAubWritable(false); auto gfxImageAllocation = memoryManager->allocateGraphicsMemory(sizeof(uint32_t), sizeof(uint32_t), false, false); gfxImageAllocation->setAllocationType(GraphicsAllocation::AllocationType::IMAGE); gfxImageAllocation->setAubWritable(false); aubCsr->dumpAubNonWritable = false; ResidencyContainer allocationsForResidency = {gfxBufferAllocation, gfxImageAllocation}; aubCsr->processResidency(&allocationsForResidency); EXPECT_FALSE(gfxBufferAllocation->isAubWritable()); EXPECT_FALSE(gfxImageAllocation->isAubWritable()); memoryManager->freeGraphicsMemory(gfxBufferAllocation); memoryManager->freeGraphicsMemory(gfxImageAllocation); } HWTEST_F(AubCommandStreamReceiverTests, givenAubCommandStreamReceiverWhenGraphicsAllocationTypeIsntNonAubWritableThenWriteMemoryIsAllowed) { std::unique_ptr<MemoryManager> memoryManager(nullptr); std::unique_ptr<AUBCommandStreamReceiverHw<FamilyType>> aubCsr(new AUBCommandStreamReceiverHw<FamilyType>(*platformDevices[0], "", true, *pDevice->executionEnvironment)); memoryManager.reset(aubCsr->createMemoryManager(false)); auto gfxAllocation = memoryManager->allocateGraphicsMemory(sizeof(uint32_t), sizeof(uint32_t), false, false); EXPECT_TRUE(aubCsr->writeMemory(*gfxAllocation)); memoryManager->freeGraphicsMemory(gfxAllocation); } HWTEST_F(AubCommandStreamReceiverTests, givenAubCommandStreamReceiverWhenGraphicsAllocationTypeIsNonAubWritableThenWriteMemoryIsNotAllowed) { std::unique_ptr<MemoryManager> memoryManager(nullptr); std::unique_ptr<AUBCommandStreamReceiverHw<FamilyType>> aubCsr(new AUBCommandStreamReceiverHw<FamilyType>(*platformDevices[0], "", true, *pDevice->executionEnvironment)); memoryManager.reset(aubCsr->createMemoryManager(false)); auto gfxAllocation = memoryManager->allocateGraphicsMemory(sizeof(uint32_t), sizeof(uint32_t), false, false); gfxAllocation->setAubWritable(false); EXPECT_FALSE(aubCsr->writeMemory(*gfxAllocation)); memoryManager->freeGraphicsMemory(gfxAllocation); } HWTEST_F(AubCommandStreamReceiverTests, givenAubCommandStreamReceiverWhenGraphicsAllocationSizeIsZeroThenWriteMemoryIsNotAllowed) { std::unique_ptr<AUBCommandStreamReceiverHw<FamilyType>> aubCsr(new AUBCommandStreamReceiverHw<FamilyType>(*platformDevices[0], "", true, *pDevice->executionEnvironment)); GraphicsAllocation gfxAllocation((void *)0x1234, 0); EXPECT_FALSE(aubCsr->writeMemory(gfxAllocation)); } HWTEST_F(AubCommandStreamReceiverTests, givenAubCommandStreamReceiverWhenAllocationDataIsPassedInAllocationViewThenWriteMemoryIsAllowed) { auto aubCsr = std::make_unique<AUBCommandStreamReceiverHw<FamilyType>>(*platformDevices[0], "", true, *pDevice->executionEnvironment); size_t size = 100; auto ptr = std::make_unique<char[]>(size); auto addr = reinterpret_cast<uint64_t>(ptr.get()); AllocationView allocationView(addr, size); EXPECT_TRUE(aubCsr->writeMemory(allocationView)); } HWTEST_F(AubCommandStreamReceiverTests, givenAubCommandStreamReceiverWhenAllocationSizeInAllocationViewIsZeroThenWriteMemoryIsNotAllowed) { auto aubCsr = std::make_unique<AUBCommandStreamReceiverHw<FamilyType>>(*platformDevices[0], "", true, *pDevice->executionEnvironment); AllocationView allocationView(0x1234, 0); EXPECT_FALSE(aubCsr->writeMemory(allocationView)); } HWTEST_F(AubCommandStreamReceiverTests, givenAubCommandStreamReceiverWhenAUBDumpCaptureFileNameHasBeenSpecifiedThenItShouldBeUsedToOpenTheFileWithAubCapture) { DebugManagerStateRestore stateRestore; DebugManager.flags.AUBDumpCaptureFileName.set("file_name.aub"); std::unique_ptr<MockAubCsr<FamilyType>> aubCsr(static_cast<MockAubCsr<FamilyType> *>(AUBCommandStreamReceiver::create(*platformDevices[0], "", true, *pDevice->executionEnvironment))); EXPECT_NE(nullptr, aubCsr); EXPECT_TRUE(aubCsr->isFileOpen()); EXPECT_STREQ(DebugManager.flags.AUBDumpCaptureFileName.get().c_str(), aubCsr->getFileName().c_str()); } HWTEST_F(AubCommandStreamReceiverTests, givenAubCommandStreamReceiverInSubCaptureModeWhenAubSubCaptureIsActivatedThenFileIsOpened) { DebugManagerStateRestore stateRestore; std::unique_ptr<MockAubCsr<FamilyType>> aubCsr(new MockAubCsr<FamilyType>(*platformDevices[0], "", false, *pDevice->executionEnvironment)); auto subCaptureManagerMock = new AubSubCaptureManagerMock(""); subCaptureManagerMock->subCaptureMode = AubSubCaptureManager::SubCaptureMode::Toggle; subCaptureManagerMock->setSubCaptureIsActive(false); subCaptureManagerMock->setSubCaptureToggleActive(true); aubCsr->subCaptureManager.reset(subCaptureManagerMock); MockKernelWithInternals kernelInternals(*pDevice); Kernel *kernel = kernelInternals.mockKernel; MockMultiDispatchInfo multiDispatchInfo(kernel); ASSERT_FALSE(aubCsr->isFileOpen()); aubCsr->activateAubSubCapture(multiDispatchInfo); EXPECT_TRUE(aubCsr->isFileOpen()); } HWTEST_F(AubCommandStreamReceiverTests, givenAubCommandStreamReceiverInSubCaptureModeWhenAubSubCaptureRemainsActivedThenTheSameFileShouldBeKeptOpened) { DebugManagerStateRestore stateRestore; std::unique_ptr<MockAubCsr<FamilyType>> aubCsr(new MockAubCsr<FamilyType>(*platformDevices[0], "", false, *pDevice->executionEnvironment)); auto subCaptureManagerMock = new AubSubCaptureManagerMock(""); subCaptureManagerMock->subCaptureMode = AubSubCaptureManager::SubCaptureMode::Toggle; subCaptureManagerMock->setSubCaptureIsActive(false); subCaptureManagerMock->setSubCaptureToggleActive(true); aubCsr->subCaptureManager.reset(subCaptureManagerMock); MockKernelWithInternals kernelInternals(*pDevice); Kernel *kernel = kernelInternals.mockKernel; MockMultiDispatchInfo multiDispatchInfo(kernel); std::string fileName = aubCsr->subCaptureManager->getSubCaptureFileName(multiDispatchInfo); aubCsr->initFile(fileName); ASSERT_TRUE(aubCsr->isFileOpen()); aubCsr->activateAubSubCapture(multiDispatchInfo); EXPECT_TRUE(aubCsr->isFileOpen()); EXPECT_STREQ(fileName.c_str(), aubCsr->getFileName().c_str()); } HWTEST_F(AubCommandStreamReceiverTests, givenAubCommandStreamReceiverInSubCaptureModeWhenAubSubCaptureIsActivatedWithNewFileNameThenNewFileShouldBeReOpened) { DebugManagerStateRestore stateRestore; std::unique_ptr<MockAubCsr<FamilyType>> aubCsr(new MockAubCsr<FamilyType>(*platformDevices[0], "", false, *pDevice->executionEnvironment)); std::string newFileName = "new_file_name.aub"; auto subCaptureManagerMock = new AubSubCaptureManagerMock(""); subCaptureManagerMock->subCaptureMode = AubSubCaptureManager::SubCaptureMode::Toggle; subCaptureManagerMock->setSubCaptureIsActive(false); subCaptureManagerMock->setSubCaptureToggleActive(true); subCaptureManagerMock->setExternalFileName(newFileName); aubCsr->subCaptureManager.reset(subCaptureManagerMock); MockKernelWithInternals kernelInternals(*pDevice); Kernel *kernel = kernelInternals.mockKernel; MockMultiDispatchInfo multiDispatchInfo(kernel); std::string fileName = "file_name.aub"; aubCsr->initFile(fileName); ASSERT_TRUE(aubCsr->isFileOpen()); ASSERT_STREQ(fileName.c_str(), aubCsr->getFileName().c_str()); aubCsr->activateAubSubCapture(multiDispatchInfo); EXPECT_TRUE(aubCsr->isFileOpen()); EXPECT_STRNE(fileName.c_str(), aubCsr->getFileName().c_str()); EXPECT_STREQ(newFileName.c_str(), aubCsr->getFileName().c_str()); } HWTEST_F(AubCommandStreamReceiverTests, givenAubCommandStreamReceiverInSubCaptureModeWhenAubSubCaptureIsActivatedForNewFileThenOldEngineInfoTableShouldBeFreed) { DebugManagerStateRestore stateRestore; std::unique_ptr<MockAubCsr<FamilyType>> aubCsr(new MockAubCsr<FamilyType>(*platformDevices[0], "", false, *pDevice->executionEnvironment)); std::string newFileName = "new_file_name.aub"; auto subCaptureManagerMock = new AubSubCaptureManagerMock(""); subCaptureManagerMock->subCaptureMode = AubSubCaptureManager::SubCaptureMode::Toggle; subCaptureManagerMock->setSubCaptureIsActive(false); subCaptureManagerMock->setSubCaptureToggleActive(true); subCaptureManagerMock->setExternalFileName(newFileName); aubCsr->subCaptureManager.reset(subCaptureManagerMock); MockKernelWithInternals kernelInternals(*pDevice); Kernel *kernel = kernelInternals.mockKernel; MockMultiDispatchInfo multiDispatchInfo(kernel); std::string fileName = "file_name.aub"; aubCsr->initFile(fileName); ASSERT_STREQ(fileName.c_str(), aubCsr->getFileName().c_str()); aubCsr->activateAubSubCapture(multiDispatchInfo); ASSERT_STREQ(newFileName.c_str(), aubCsr->getFileName().c_str()); for (auto &engineInfo : aubCsr->engineInfoTable) { EXPECT_EQ(nullptr, engineInfo.pLRCA); EXPECT_EQ(nullptr, engineInfo.pGlobalHWStatusPage); EXPECT_EQ(nullptr, engineInfo.pRingBuffer); } } HWTEST_F(AubCommandStreamReceiverTests, givenAubCommandStreamReceiverInSubCaptureModeWhenAubSubCaptureIsActivatedThenForceDumpingAllocationsAubNonWritable) { DebugManagerStateRestore stateRestore; std::unique_ptr<MockAubCsrToTestDumpAubNonWritable<FamilyType>> aubCsr(new MockAubCsrToTestDumpAubNonWritable<FamilyType>(*platformDevices[0], "", false, *pDevice->executionEnvironment)); auto subCaptureManagerMock = new AubSubCaptureManagerMock(""); subCaptureManagerMock->subCaptureMode = AubSubCaptureManager::SubCaptureMode::Toggle; subCaptureManagerMock->setSubCaptureIsActive(false); subCaptureManagerMock->setSubCaptureToggleActive(true); aubCsr->subCaptureManager.reset(subCaptureManagerMock); MockKernelWithInternals kernelInternals(*pDevice); Kernel *kernel = kernelInternals.mockKernel; MockMultiDispatchInfo multiDispatchInfo(kernel); aubCsr->activateAubSubCapture(multiDispatchInfo); EXPECT_TRUE(aubCsr->dumpAubNonWritable); } HWTEST_F(AubCommandStreamReceiverTests, givenAubCommandStreamReceiverInSubCaptureModeWhenAubSubCaptureRemainsActivatedThenDontForceDumpingAllocationsAubNonWritable) { DebugManagerStateRestore stateRestore; std::unique_ptr<MockAubCsrToTestDumpAubNonWritable<FamilyType>> aubCsr(new MockAubCsrToTestDumpAubNonWritable<FamilyType>(*platformDevices[0], "", false, *pDevice->executionEnvironment)); auto subCaptureManagerMock = new AubSubCaptureManagerMock(""); subCaptureManagerMock->subCaptureMode = AubSubCaptureManager::SubCaptureMode::Toggle; subCaptureManagerMock->setSubCaptureIsActive(false); subCaptureManagerMock->setSubCaptureToggleActive(true); aubCsr->subCaptureManager.reset(subCaptureManagerMock); MockKernelWithInternals kernelInternals(*pDevice); Kernel *kernel = kernelInternals.mockKernel; MockMultiDispatchInfo multiDispatchInfo(kernel); aubCsr->initFile(aubCsr->subCaptureManager->getSubCaptureFileName(multiDispatchInfo)); aubCsr->activateAubSubCapture(multiDispatchInfo); EXPECT_FALSE(aubCsr->dumpAubNonWritable); } HWTEST_F(AubCommandStreamReceiverTests, givenAubCommandStreamReceiverInSubCaptureModeWhenSubCaptureModeRemainsDeactivatedThenSubCaptureIsDisabled) { DebugManagerStateRestore stateRestore; std::unique_ptr<MockAubCsr<FamilyType>> aubCsr(new MockAubCsr<FamilyType>(*platformDevices[0], "", false, *pDevice->executionEnvironment)); auto subCaptureManagerMock = new AubSubCaptureManagerMock(""); subCaptureManagerMock->subCaptureMode = AubSubCaptureManager::SubCaptureMode::Toggle; subCaptureManagerMock->setSubCaptureIsActive(false); subCaptureManagerMock->setSubCaptureToggleActive(false); aubCsr->subCaptureManager.reset(subCaptureManagerMock); const DispatchInfo dispatchInfo; MultiDispatchInfo multiDispatchInfo; multiDispatchInfo.push(dispatchInfo); aubCsr->activateAubSubCapture(multiDispatchInfo); EXPECT_FALSE(aubCsr->subCaptureManager->isSubCaptureEnabled()); } HWTEST_F(AubCommandStreamReceiverTests, givenAubCommandStreamReceiverInSubCaptureModeWhenSubCaptureIsToggledOnThenSubCaptureGetsEnabled) { DebugManagerStateRestore stateRestore; std::unique_ptr<MockAubCsr<FamilyType>> aubCsr(new MockAubCsr<FamilyType>(*platformDevices[0], "", false, *pDevice->executionEnvironment)); auto subCaptureManagerMock = new AubSubCaptureManagerMock(""); subCaptureManagerMock->subCaptureMode = AubSubCaptureManager::SubCaptureMode::Toggle; subCaptureManagerMock->setSubCaptureIsActive(false); subCaptureManagerMock->setSubCaptureToggleActive(true); aubCsr->subCaptureManager.reset(subCaptureManagerMock); MockKernelWithInternals kernelInternals(*pDevice); Kernel *kernel = kernelInternals.mockKernel; MockMultiDispatchInfo multiDispatchInfo(kernel); aubCsr->activateAubSubCapture(multiDispatchInfo); EXPECT_TRUE(aubCsr->subCaptureManager->isSubCaptureEnabled()); } HWTEST_F(AubCommandStreamReceiverTests, givenAubCommandStreamReceiverInStandaloneAndSubCaptureModeWhenSubCaptureRemainsDeactivatedThenNeitherProgrammingFlagsAreInitializedNorCsrIsFlushed) { DebugManagerStateRestore stateRestore; std::unique_ptr<MockAubCsr<FamilyType>> aubCsr(new MockAubCsr<FamilyType>(*platformDevices[0], "", true, *pDevice->executionEnvironment)); auto subCaptureManagerMock = new AubSubCaptureManagerMock(""); subCaptureManagerMock->subCaptureMode = AubSubCaptureManager::SubCaptureMode::Toggle; subCaptureManagerMock->setSubCaptureIsActive(false); subCaptureManagerMock->setSubCaptureToggleActive(false); aubCsr->subCaptureManager.reset(subCaptureManagerMock); MockKernelWithInternals kernelInternals(*pDevice); Kernel *kernel = kernelInternals.mockKernel; MockMultiDispatchInfo multiDispatchInfo(kernel); aubCsr->activateAubSubCapture(multiDispatchInfo); EXPECT_FALSE(aubCsr->flushBatchedSubmissionsCalled); EXPECT_FALSE(aubCsr->initProgrammingFlagsCalled); } HWTEST_F(AubCommandStreamReceiverTests, givenAubCommandStreamReceiverInStandaloneAndSubCaptureModeWhenSubCaptureRemainsActivatedThenNeitherProgrammingFlagsAreInitializedNorCsrIsFlushed) { DebugManagerStateRestore stateRestore; std::unique_ptr<MockAubCsr<FamilyType>> aubCsr(new MockAubCsr<FamilyType>(*platformDevices[0], "", true, *pDevice->executionEnvironment)); auto subCaptureManagerMock = new AubSubCaptureManagerMock(""); subCaptureManagerMock->subCaptureMode = AubSubCaptureManager::SubCaptureMode::Toggle; subCaptureManagerMock->setSubCaptureIsActive(true); subCaptureManagerMock->setSubCaptureToggleActive(true); aubCsr->subCaptureManager.reset(subCaptureManagerMock); MockKernelWithInternals kernelInternals(*pDevice); Kernel *kernel = kernelInternals.mockKernel; MockMultiDispatchInfo multiDispatchInfo(kernel); aubCsr->activateAubSubCapture(multiDispatchInfo); EXPECT_FALSE(aubCsr->flushBatchedSubmissionsCalled); EXPECT_FALSE(aubCsr->initProgrammingFlagsCalled); } HWTEST_F(AubCommandStreamReceiverTests, givenAubCommandStreamReceiverInStandaloneAndSubCaptureModeWhenSubCaptureGetsActivatedThenProgrammingFlagsAreInitialized) { DebugManagerStateRestore stateRestore; std::unique_ptr<MockAubCsr<FamilyType>> aubCsr(new MockAubCsr<FamilyType>(*platformDevices[0], "", true, *pDevice->executionEnvironment)); auto subCaptureManagerMock = new AubSubCaptureManagerMock(""); subCaptureManagerMock->subCaptureMode = AubSubCaptureManager::SubCaptureMode::Toggle; subCaptureManagerMock->setSubCaptureIsActive(false); subCaptureManagerMock->setSubCaptureToggleActive(true); aubCsr->subCaptureManager.reset(subCaptureManagerMock); MockKernelWithInternals kernelInternals(*pDevice); Kernel *kernel = kernelInternals.mockKernel; MockMultiDispatchInfo multiDispatchInfo(kernel); aubCsr->activateAubSubCapture(multiDispatchInfo); EXPECT_FALSE(aubCsr->flushBatchedSubmissionsCalled); EXPECT_TRUE(aubCsr->initProgrammingFlagsCalled); } HWTEST_F(AubCommandStreamReceiverTests, givenAubCommandStreamReceiverInStandaloneAndSubCaptureModeWhenSubCaptureGetsDeactivatedThenCsrIsFlushed) { DebugManagerStateRestore stateRestore; std::unique_ptr<MockAubCsr<FamilyType>> aubCsr(new MockAubCsr<FamilyType>(*platformDevices[0], "", true, *pDevice->executionEnvironment)); auto subCaptureManagerMock = new AubSubCaptureManagerMock(""); subCaptureManagerMock->subCaptureMode = AubSubCaptureManager::SubCaptureMode::Toggle; subCaptureManagerMock->setSubCaptureIsActive(true); subCaptureManagerMock->setSubCaptureToggleActive(false); aubCsr->subCaptureManager.reset(subCaptureManagerMock); MockKernelWithInternals kernelInternals(*pDevice); Kernel *kernel = kernelInternals.mockKernel; MockMultiDispatchInfo multiDispatchInfo(kernel); aubCsr->activateAubSubCapture(multiDispatchInfo); EXPECT_TRUE(aubCsr->flushBatchedSubmissionsCalled); EXPECT_FALSE(aubCsr->initProgrammingFlagsCalled); } HWTEST_F(AubCommandStreamReceiverTests, givenAubCommandStreamReceiverWhenForcedBatchBufferFlatteningInImmediateDispatchModeThenNewCombinedBatchBufferIsCreated) { std::unique_ptr<MemoryManager> memoryManager(nullptr); std::unique_ptr<AUBCommandStreamReceiverHw<FamilyType>> aubCsr(new AUBCommandStreamReceiverHw<FamilyType>(*platformDevices[0], "", true, *pDevice->executionEnvironment)); memoryManager.reset(aubCsr->createMemoryManager(false)); auto flatBatchBufferHelper = new FlatBatchBufferHelperHw<FamilyType>(memoryManager.get()); aubCsr->overwriteFlatBatchBufferHelper(flatBatchBufferHelper); auto chainedBatchBuffer = memoryManager->allocateGraphicsMemory(128u, 64u, false, false); auto otherAllocation = memoryManager->allocateGraphicsMemory(128u, 64u, false, false); ASSERT_NE(nullptr, chainedBatchBuffer); GraphicsAllocation *commandBuffer = memoryManager->allocateGraphicsMemory(4096); ASSERT_NE(nullptr, commandBuffer); LinearStream cs(commandBuffer); BatchBuffer batchBuffer{cs.getGraphicsAllocation(), 0, 128u, chainedBatchBuffer, false, false, QueueThrottle::MEDIUM, cs.getUsed(), &cs}; size_t sizeBatchBuffer = 0xffffu; std::unique_ptr<void, std::function<void(void *)>> flatBatchBuffer(flatBatchBufferHelper->flattenBatchBuffer(batchBuffer, sizeBatchBuffer, DispatchMode::ImmediateDispatch), [&](void *ptr) { memoryManager->alignedFreeWrapper(ptr); }); EXPECT_NE(nullptr, flatBatchBuffer.get()); EXPECT_EQ(alignUp(128u + 128u, 0x1000), sizeBatchBuffer); memoryManager->freeGraphicsMemory(commandBuffer); memoryManager->freeGraphicsMemory(chainedBatchBuffer); memoryManager->freeGraphicsMemory(otherAllocation); } HWTEST_F(AubCommandStreamReceiverTests, givenAubCommandStreamReceiverWhenForcedBatchBufferInImmediateDispatchModeAndNoChainedBatchBufferThenCombinedBatchBufferIsNotCreated) { std::unique_ptr<MemoryManager> memoryManager(nullptr); std::unique_ptr<AUBCommandStreamReceiverHw<FamilyType>> aubCsr(new AUBCommandStreamReceiverHw<FamilyType>(*platformDevices[0], "", true, *pDevice->executionEnvironment)); memoryManager.reset(aubCsr->createMemoryManager(false)); auto flatBatchBufferHelper = new FlatBatchBufferHelperHw<FamilyType>(memoryManager.get()); aubCsr->overwriteFlatBatchBufferHelper(flatBatchBufferHelper); GraphicsAllocation *commandBuffer = memoryManager->allocateGraphicsMemory(4096); ASSERT_NE(nullptr, commandBuffer); LinearStream cs(commandBuffer); BatchBuffer batchBuffer{cs.getGraphicsAllocation(), 0, 128u, nullptr, false, false, QueueThrottle::MEDIUM, cs.getUsed(), &cs}; size_t sizeBatchBuffer = 0xffffu; std::unique_ptr<void, std::function<void(void *)>> flatBatchBuffer(flatBatchBufferHelper->flattenBatchBuffer(batchBuffer, sizeBatchBuffer, DispatchMode::ImmediateDispatch), [&](void *ptr) { memoryManager->alignedFreeWrapper(ptr); }); EXPECT_EQ(nullptr, flatBatchBuffer.get()); EXPECT_EQ(0xffffu, sizeBatchBuffer); memoryManager->freeGraphicsMemory(commandBuffer); } HWTEST_F(AubCommandStreamReceiverTests, givenAubCommandStreamReceiverWhenForcedBatchBufferAndNotImmediateOrBatchedDispatchModeThenCombinedBatchBufferIsNotCreated) { std::unique_ptr<MemoryManager> memoryManager(nullptr); std::unique_ptr<AUBCommandStreamReceiverHw<FamilyType>> aubCsr(new AUBCommandStreamReceiverHw<FamilyType>(*platformDevices[0], "", true, *pDevice->executionEnvironment)); memoryManager.reset(aubCsr->createMemoryManager(false)); auto flatBatchBufferHelper = new FlatBatchBufferHelperHw<FamilyType>(memoryManager.get()); aubCsr->overwriteFlatBatchBufferHelper(flatBatchBufferHelper); auto chainedBatchBuffer = memoryManager->allocateGraphicsMemory(128u, 64u, false, false); auto otherAllocation = memoryManager->allocateGraphicsMemory(128u, 64u, false, false); ASSERT_NE(nullptr, chainedBatchBuffer); GraphicsAllocation *commandBuffer = memoryManager->allocateGraphicsMemory(4096); ASSERT_NE(nullptr, commandBuffer); LinearStream cs(commandBuffer); BatchBuffer batchBuffer{cs.getGraphicsAllocation(), 0, 128u, chainedBatchBuffer, false, false, QueueThrottle::MEDIUM, cs.getUsed(), &cs}; size_t sizeBatchBuffer = 0xffffu; std::unique_ptr<void, std::function<void(void *)>> flatBatchBuffer(flatBatchBufferHelper->flattenBatchBuffer(batchBuffer, sizeBatchBuffer, DispatchMode::AdaptiveDispatch), [&](void *ptr) { memoryManager->alignedFreeWrapper(ptr); }); EXPECT_EQ(nullptr, flatBatchBuffer.get()); EXPECT_EQ(0xffffu, sizeBatchBuffer); memoryManager->freeGraphicsMemory(commandBuffer); memoryManager->freeGraphicsMemory(chainedBatchBuffer); memoryManager->freeGraphicsMemory(otherAllocation); } HWTEST_F(AubCommandStreamReceiverTests, givenAubCommandStreamReceiverWhenRegisterCommandChunkIsCalledThenNewChunkIsAddedToTheList) { typedef typename FamilyType::MI_BATCH_BUFFER_START MI_BATCH_BUFFER_START; auto aubExecutionEnvironment = getEnvironment<AUBCommandStreamReceiverHw<FamilyType>>(false, true, true); auto aubCsr = aubExecutionEnvironment->template getCsr<AUBCommandStreamReceiverHw<FamilyType>>(); LinearStream cs(aubExecutionEnvironment->commandBuffer); BatchBuffer batchBuffer{cs.getGraphicsAllocation(), 0, 128u, nullptr, false, false, QueueThrottle::MEDIUM, cs.getUsed(), &cs}; aubCsr->getFlatBatchBufferHelper().registerCommandChunk(batchBuffer, sizeof(MI_BATCH_BUFFER_START)); ASSERT_EQ(1u, aubCsr->getFlatBatchBufferHelper().getCommandChunkList().size()); EXPECT_EQ(128u + sizeof(MI_BATCH_BUFFER_START), aubCsr->getFlatBatchBufferHelper().getCommandChunkList()[0].endOffset); CommandChunk chunk; chunk.endOffset = 0x123; aubCsr->getFlatBatchBufferHelper().registerCommandChunk(chunk); ASSERT_EQ(2u, aubCsr->getFlatBatchBufferHelper().getCommandChunkList().size()); EXPECT_EQ(0x123u, aubCsr->getFlatBatchBufferHelper().getCommandChunkList()[1].endOffset); } HWTEST_F(AubCommandStreamReceiverTests, givenAubCommandStreamReceiverWhenRemovePatchInfoDataIsCalledThenElementIsRemovedFromPatchInfoList) { auto aubExecutionEnvironment = getEnvironment<AUBCommandStreamReceiverHw<FamilyType>>(false, true, true); auto aubCsr = aubExecutionEnvironment->template getCsr<AUBCommandStreamReceiverHw<FamilyType>>(); PatchInfoData patchInfoData(0xA000, 0x0, PatchInfoAllocationType::KernelArg, 0xB000, 0x0, PatchInfoAllocationType::Default); aubCsr->getFlatBatchBufferHelper().setPatchInfoData(patchInfoData); EXPECT_EQ(1u, aubCsr->getFlatBatchBufferHelper().getPatchInfoCollection().size()); EXPECT_TRUE(aubCsr->getFlatBatchBufferHelper().removePatchInfoData(0xC000)); EXPECT_EQ(1u, aubCsr->getFlatBatchBufferHelper().getPatchInfoCollection().size()); EXPECT_TRUE(aubCsr->getFlatBatchBufferHelper().removePatchInfoData(0xB000)); EXPECT_EQ(0u, aubCsr->getFlatBatchBufferHelper().getPatchInfoCollection().size()); } HWTEST_F(AubCommandStreamReceiverTests, givenAubCommandStreamReceiverWhenAddGucStartMessageIsCalledThenBatchBufferAddressIsStoredInPatchInfoCollection) { DebugManagerStateRestore dbgRestore; DebugManager.flags.AddPatchInfoCommentsForAUBDump.set(true); auto aubExecutionEnvironment = getEnvironment<AUBCommandStreamReceiverHw<FamilyType>>(false, false, true); auto aubCsr = aubExecutionEnvironment->template getCsr<AUBCommandStreamReceiverHw<FamilyType>>(); LinearStream cs(aubExecutionEnvironment->commandBuffer); std::unique_ptr<char> batchBuffer(new char[1024]); aubCsr->addGUCStartMessage(static_cast<uint64_t>(reinterpret_cast<std::uintptr_t>(batchBuffer.get())), EngineType::ENGINE_RCS); auto &patchInfoCollection = aubCsr->getFlatBatchBufferHelper().getPatchInfoCollection(); ASSERT_EQ(1u, patchInfoCollection.size()); EXPECT_EQ(patchInfoCollection[0].sourceAllocation, reinterpret_cast<uint64_t>(batchBuffer.get())); EXPECT_EQ(patchInfoCollection[0].targetType, PatchInfoAllocationType::GUCStartMessage); } HWTEST_F(AubCommandStreamReceiverTests, givenAubCommandStreamReceiverWhenForcedBatchBufferFlatteningInBatchedDispatchModeThenNewCombinedBatchBufferIsCreated) { DebugManagerStateRestore dbgRestore; DebugManager.flags.FlattenBatchBufferForAUBDump.set(true); DebugManager.flags.AddPatchInfoCommentsForAUBDump.set(true); DebugManager.flags.CsrDispatchMode.set(static_cast<uint32_t>(DispatchMode::BatchedDispatch)); auto aubExecutionEnvironment = getEnvironment<AUBCommandStreamReceiverHw<FamilyType>>(false, true, true); auto aubCsr = aubExecutionEnvironment->template getCsr<AUBCommandStreamReceiverHw<FamilyType>>(); auto memoryManager = aubExecutionEnvironment->executionEnvironment->memoryManager.get(); LinearStream cs(aubExecutionEnvironment->commandBuffer); CommandChunk chunk1; CommandChunk chunk2; CommandChunk chunk3; std::unique_ptr<char> commands1(new char[0x100u]); commands1.get()[0] = 0x1; chunk1.baseAddressCpu = chunk1.baseAddressGpu = reinterpret_cast<uint64_t>(commands1.get()); chunk1.startOffset = 0u; chunk1.endOffset = 0x50u; std::unique_ptr<char> commands2(new char[0x100u]); commands2.get()[0] = 0x2; chunk2.baseAddressCpu = chunk2.baseAddressGpu = reinterpret_cast<uint64_t>(commands2.get()); chunk2.startOffset = 0u; chunk2.endOffset = 0x50u; aubCsr->getFlatBatchBufferHelper().registerBatchBufferStartAddress(reinterpret_cast<uint64_t>(commands2.get() + 0x40), reinterpret_cast<uint64_t>(commands1.get())); std::unique_ptr<char> commands3(new char[0x100u]); commands3.get()[0] = 0x3; chunk3.baseAddressCpu = chunk3.baseAddressGpu = reinterpret_cast<uint64_t>(commands3.get()); chunk3.startOffset = 0u; chunk3.endOffset = 0x50u; aubCsr->getFlatBatchBufferHelper().registerBatchBufferStartAddress(reinterpret_cast<uint64_t>(commands3.get() + 0x40), reinterpret_cast<uint64_t>(commands2.get())); aubCsr->getFlatBatchBufferHelper().registerCommandChunk(chunk1); aubCsr->getFlatBatchBufferHelper().registerCommandChunk(chunk2); aubCsr->getFlatBatchBufferHelper().registerCommandChunk(chunk3); ASSERT_EQ(3u, aubCsr->getFlatBatchBufferHelper().getCommandChunkList().size()); PatchInfoData patchInfoData1(0xAAAu, 0xAu, PatchInfoAllocationType::IndirectObjectHeap, chunk1.baseAddressGpu, 0x10, PatchInfoAllocationType::Default); PatchInfoData patchInfoData2(0xBBBu, 0xAu, PatchInfoAllocationType::IndirectObjectHeap, chunk1.baseAddressGpu, 0x60, PatchInfoAllocationType::Default); PatchInfoData patchInfoData3(0xCCCu, 0xAu, PatchInfoAllocationType::IndirectObjectHeap, 0x0, 0x10, PatchInfoAllocationType::Default); aubCsr->getFlatBatchBufferHelper().setPatchInfoData(patchInfoData1); aubCsr->getFlatBatchBufferHelper().setPatchInfoData(patchInfoData2); aubCsr->getFlatBatchBufferHelper().setPatchInfoData(patchInfoData3); ASSERT_EQ(3u, aubCsr->getFlatBatchBufferHelper().getPatchInfoCollection().size()); BatchBuffer batchBuffer{cs.getGraphicsAllocation(), 0, 128u, nullptr, false, false, QueueThrottle::MEDIUM, cs.getUsed(), &cs}; size_t sizeBatchBuffer = 0u; std::unique_ptr<void, std::function<void(void *)>> flatBatchBuffer(aubCsr->getFlatBatchBufferHelper().flattenBatchBuffer(batchBuffer, sizeBatchBuffer, DispatchMode::BatchedDispatch), [&](void *ptr) { memoryManager->alignedFreeWrapper(ptr); }); EXPECT_NE(nullptr, flatBatchBuffer.get()); EXPECT_EQ(alignUp(0x50u + 0x40u + 0x40u + CSRequirements::csOverfetchSize, 0x1000u), sizeBatchBuffer); ASSERT_EQ(1u, aubCsr->getFlatBatchBufferHelper().getPatchInfoCollection().size()); EXPECT_EQ(0xAAAu, aubCsr->getFlatBatchBufferHelper().getPatchInfoCollection()[0].sourceAllocation); EXPECT_EQ(0u, aubCsr->getFlatBatchBufferHelper().getCommandChunkList().size()); EXPECT_EQ(0x3, static_cast<char *>(flatBatchBuffer.get())[0]); EXPECT_EQ(0x2, static_cast<char *>(flatBatchBuffer.get())[0x40]); EXPECT_EQ(0x1, static_cast<char *>(flatBatchBuffer.get())[0x40 + 0x40]); } HWTEST_F(AubCommandStreamReceiverTests, givenAubCommandStreamReceiverWhenDefaultDebugConfigThenExpectFlattenBatchBufferIsNotCalled) { auto aubExecutionEnvironment = getEnvironment<MockAubCsr<FamilyType>>(true, true, true); auto aubCsr = aubExecutionEnvironment->template getCsr<MockAubCsr<FamilyType>>(); LinearStream cs(aubExecutionEnvironment->commandBuffer); auto mockHelper = new MockFlatBatchBufferHelper<FamilyType>(aubCsr->getMemoryManager()); aubCsr->overwriteFlatBatchBufferHelper(mockHelper); BatchBuffer batchBuffer{cs.getGraphicsAllocation(), 0, 0, nullptr, false, false, QueueThrottle::MEDIUM, cs.getUsed(), &cs}; auto engineType = OCLRT::ENGINE_RCS; ResidencyContainer allocationsForResidency = {}; EXPECT_CALL(*mockHelper, flattenBatchBuffer(::testing::_, ::testing::_, ::testing::_)).Times(0); aubCsr->flush(batchBuffer, engineType, &allocationsForResidency); } HWTEST_F(AubCommandStreamReceiverTests, givenAubCommandStreamReceiverWhenForcedFlattenBatchBufferAndImmediateDispatchModeThenExpectFlattenBatchBufferIsCalled) { DebugManagerStateRestore dbgRestore; DebugManager.flags.FlattenBatchBufferForAUBDump.set(true); DebugManager.flags.CsrDispatchMode.set(static_cast<uint32_t>(DispatchMode::ImmediateDispatch)); auto aubExecutionEnvironment = getEnvironment<MockAubCsr<FamilyType>>(true, true, true); auto aubCsr = aubExecutionEnvironment->template getCsr<MockAubCsr<FamilyType>>(); LinearStream cs(aubExecutionEnvironment->commandBuffer); auto mockHelper = new MockFlatBatchBufferHelper<FamilyType>(aubCsr->getMemoryManager()); aubCsr->overwriteFlatBatchBufferHelper(mockHelper); auto chainedBatchBuffer = aubExecutionEnvironment->executionEnvironment->memoryManager->allocateGraphicsMemory(128u, 64u, false, false); ASSERT_NE(nullptr, chainedBatchBuffer); BatchBuffer batchBuffer{cs.getGraphicsAllocation(), 0, 128u, chainedBatchBuffer, false, false, QueueThrottle::MEDIUM, cs.getUsed(), &cs}; auto engineType = OCLRT::ENGINE_RCS; aubCsr->makeResident(*chainedBatchBuffer); std::unique_ptr<void, decltype(alignedFree) *> ptr(alignedMalloc(4096, 4096), alignedFree); EXPECT_CALL(*mockHelper, flattenBatchBuffer(::testing::_, ::testing::_, ::testing::_)).WillOnce(::testing::Return(ptr.release())); aubCsr->flush(batchBuffer, engineType, nullptr); aubExecutionEnvironment->executionEnvironment->memoryManager->freeGraphicsMemory(chainedBatchBuffer); } HWTEST_F(AubCommandStreamReceiverTests, givenAubCommandStreamReceiverWhenForcedFlattenBatchBufferAndImmediateDispatchModeAndThereIsNoChainedBatchBufferThenExpectFlattenBatchBufferIsCalledAnyway) { DebugManagerStateRestore dbgRestore; DebugManager.flags.FlattenBatchBufferForAUBDump.set(true); DebugManager.flags.CsrDispatchMode.set(static_cast<uint32_t>(DispatchMode::ImmediateDispatch)); auto aubExecutionEnvironment = getEnvironment<MockAubCsr<FamilyType>>(true, true, true); auto aubCsr = aubExecutionEnvironment->template getCsr<MockAubCsr<FamilyType>>(); LinearStream cs(aubExecutionEnvironment->commandBuffer); auto mockHelper = new MockFlatBatchBufferHelper<FamilyType>(aubCsr->getMemoryManager()); aubCsr->overwriteFlatBatchBufferHelper(mockHelper); BatchBuffer batchBuffer{cs.getGraphicsAllocation(), 0, 128u, nullptr, false, false, QueueThrottle::MEDIUM, cs.getUsed(), &cs}; auto engineType = OCLRT::ENGINE_RCS; EXPECT_CALL(*mockHelper, flattenBatchBuffer(::testing::_, ::testing::_, ::testing::_)).Times(1); aubCsr->flush(batchBuffer, engineType, nullptr); } HWTEST_F(AubCommandStreamReceiverTests, givenAubCommandStreamReceiverWhenForcedFlattenBatchBufferAndBatchedDispatchModeThenExpectFlattenBatchBufferIsCalledAnyway) { DebugManagerStateRestore dbgRestore; DebugManager.flags.FlattenBatchBufferForAUBDump.set(true); DebugManager.flags.CsrDispatchMode.set(static_cast<uint32_t>(DispatchMode::BatchedDispatch)); auto aubExecutionEnvironment = getEnvironment<MockAubCsr<FamilyType>>(true, true, true); auto aubCsr = aubExecutionEnvironment->template getCsr<MockAubCsr<FamilyType>>(); LinearStream cs(aubExecutionEnvironment->commandBuffer); auto mockHelper = new MockFlatBatchBufferHelper<FamilyType>(aubCsr->getMemoryManager()); aubCsr->overwriteFlatBatchBufferHelper(mockHelper); ResidencyContainer allocationsForResidency; BatchBuffer batchBuffer{cs.getGraphicsAllocation(), 0, 128u, nullptr, false, false, QueueThrottle::MEDIUM, cs.getUsed(), &cs}; auto engineType = OCLRT::ENGINE_RCS; EXPECT_CALL(*mockHelper, flattenBatchBuffer(::testing::_, ::testing::_, ::testing::_)).Times(1); aubCsr->flush(batchBuffer, engineType, &allocationsForResidency); } HWTEST_F(AubCommandStreamReceiverTests, givenAubCommandStreamReceiverWhenAddPatchInfoCommentsForAUBDumpIsSetThenAddPatchInfoCommentsIsCalled) { DebugManagerStateRestore dbgRestore; DebugManager.flags.AddPatchInfoCommentsForAUBDump.set(true); auto aubExecutionEnvironment = getEnvironment<MockAubCsr<FamilyType>>(true, true, true); auto aubCsr = aubExecutionEnvironment->template getCsr<MockAubCsr<FamilyType>>(); LinearStream cs(aubExecutionEnvironment->commandBuffer); BatchBuffer batchBuffer{cs.getGraphicsAllocation(), 0, 0, nullptr, false, false, QueueThrottle::MEDIUM, cs.getUsed(), &cs}; auto engineType = OCLRT::ENGINE_RCS; ResidencyContainer allocationsForResidency; EXPECT_CALL(*aubCsr, addPatchInfoComments()).Times(1); aubCsr->flush(batchBuffer, engineType, &allocationsForResidency); } HWTEST_F(AubCommandStreamReceiverTests, givenAubCommandStreamReceiverWhenAddPatchInfoCommentsForAUBDumpIsNotSetThenAddPatchInfoCommentsIsNotCalled) { auto aubExecutionEnvironment = getEnvironment<MockAubCsr<FamilyType>>(true, true, true); auto aubCsr = aubExecutionEnvironment->template getCsr<MockAubCsr<FamilyType>>(); LinearStream cs(aubExecutionEnvironment->commandBuffer); BatchBuffer batchBuffer{cs.getGraphicsAllocation(), 0, 0, nullptr, false, false, QueueThrottle::MEDIUM, cs.getUsed(), &cs}; auto engineType = OCLRT::ENGINE_RCS; ResidencyContainer allocationsForResidency; EXPECT_CALL(*aubCsr, addPatchInfoComments()).Times(0); aubCsr->flush(batchBuffer, engineType, &allocationsForResidency); } HWTEST_F(AubCommandStreamReceiverTests, givenAddPatchInfoCommentsCalledWhenNoPatchInfoDataObjectsThenCommentsAreEmpty) { auto aubExecutionEnvironment = getEnvironment<AUBCommandStreamReceiverHw<FamilyType>>(false, true, true); auto aubCsr = aubExecutionEnvironment->template getCsr<AUBCommandStreamReceiverHw<FamilyType>>(); LinearStream cs(aubExecutionEnvironment->commandBuffer); BatchBuffer batchBuffer{cs.getGraphicsAllocation(), 0, 128u, nullptr, false, false, QueueThrottle::MEDIUM, cs.getUsed(), &cs}; std::unique_ptr<AUBCommandStreamReceiver::AubFileStream> mockAubFileStream(new GmockAubFileStream()); GmockAubFileStream *mockAubFileStreamPtr = static_cast<GmockAubFileStream *>(mockAubFileStream.get()); ASSERT_NE(nullptr, mockAubFileStreamPtr); mockAubFileStream.swap(aubCsr->stream); std::vector<std::string> comments; EXPECT_CALL(*mockAubFileStreamPtr, addComment(_)).Times(2).WillRepeatedly(::testing::Invoke([&](const char *str) -> bool { comments.push_back(std::string(str)); return true; })); bool result = aubCsr->addPatchInfoComments(); EXPECT_TRUE(result); ASSERT_EQ(2u, comments.size()); EXPECT_EQ("PatchInfoData\n", comments[0]); EXPECT_EQ("AllocationsList\n", comments[1]); mockAubFileStream.swap(aubCsr->stream); } HWTEST_F(AubCommandStreamReceiverTests, givenAubCommandStreamReceiverWhenFlushIsCalledThenFileStreamShouldBeFlushed) { auto aubExecutionEnvironment = getEnvironment<AUBCommandStreamReceiverHw<FamilyType>>(true, true, true); auto aubCsr = aubExecutionEnvironment->template getCsr<AUBCommandStreamReceiverHw<FamilyType>>(); LinearStream cs(aubExecutionEnvironment->commandBuffer); std::unique_ptr<AUBCommandStreamReceiver::AubFileStream> mockAubFileStream(new MockAubFileStream()); MockAubFileStream *mockAubFileStreamPtr = static_cast<MockAubFileStream *>(mockAubFileStream.get()); ASSERT_NE(nullptr, mockAubFileStreamPtr); mockAubFileStream.swap(aubCsr->stream); BatchBuffer batchBuffer{cs.getGraphicsAllocation(), 0, 0, nullptr, false, false, QueueThrottle::MEDIUM, cs.getUsed(), &cs}; auto engineType = OCLRT::ENGINE_RCS; ResidencyContainer allocationsForResidency = {}; aubCsr->flush(batchBuffer, engineType, &allocationsForResidency); EXPECT_TRUE(mockAubFileStreamPtr->flushCalled); mockAubFileStream.swap(aubCsr->stream); } HWTEST_F(AubCommandStreamReceiverTests, givenAddPatchInfoCommentsCalledWhenFirstAddCommentsFailsThenFunctionReturnsFalse) { auto aubExecutionEnvironment = getEnvironment<AUBCommandStreamReceiverHw<FamilyType>>(false, true, true); auto aubCsr = aubExecutionEnvironment->template getCsr<AUBCommandStreamReceiverHw<FamilyType>>(); LinearStream cs(aubExecutionEnvironment->commandBuffer); BatchBuffer batchBuffer{cs.getGraphicsAllocation(), 0, 128u, nullptr, false, false, QueueThrottle::MEDIUM, cs.getUsed(), &cs}; std::unique_ptr<AUBCommandStreamReceiver::AubFileStream> mockAubFileStream(new GmockAubFileStream()); GmockAubFileStream *mockAubFileStreamPtr = static_cast<GmockAubFileStream *>(mockAubFileStream.get()); ASSERT_NE(nullptr, mockAubFileStreamPtr); mockAubFileStream.swap(aubCsr->stream); EXPECT_CALL(*mockAubFileStreamPtr, addComment(_)).Times(1).WillOnce(Return(false)); bool result = aubCsr->addPatchInfoComments(); EXPECT_FALSE(result); mockAubFileStream.swap(aubCsr->stream); } HWTEST_F(AubCommandStreamReceiverTests, givenAddPatchInfoCommentsCalledWhenSecondAddCommentsFailsThenFunctionReturnsFalse) { auto aubExecutionEnvironment = getEnvironment<AUBCommandStreamReceiverHw<FamilyType>>(false, true, true); auto aubCsr = aubExecutionEnvironment->template getCsr<AUBCommandStreamReceiverHw<FamilyType>>(); LinearStream cs(aubExecutionEnvironment->commandBuffer); BatchBuffer batchBuffer{cs.getGraphicsAllocation(), 0, 128u, nullptr, false, false, QueueThrottle::MEDIUM, cs.getUsed(), &cs}; std::unique_ptr<AUBCommandStreamReceiver::AubFileStream> mockAubFileStream(new GmockAubFileStream()); GmockAubFileStream *mockAubFileStreamPtr = static_cast<GmockAubFileStream *>(mockAubFileStream.get()); ASSERT_NE(nullptr, mockAubFileStreamPtr); mockAubFileStream.swap(aubCsr->stream); EXPECT_CALL(*mockAubFileStreamPtr, addComment(_)).Times(2).WillOnce(Return(true)).WillOnce(Return(false)); bool result = aubCsr->addPatchInfoComments(); EXPECT_FALSE(result); mockAubFileStream.swap(aubCsr->stream); } HWTEST_F(AubCommandStreamReceiverTests, givenAddPatchInfoCommentsCalledWhenPatchInfoDataObjectsAddedThenCommentsAreNotEmpty) { auto aubExecutionEnvironment = getEnvironment<AUBCommandStreamReceiverHw<FamilyType>>(false, true, true); auto aubCsr = aubExecutionEnvironment->template getCsr<AUBCommandStreamReceiverHw<FamilyType>>(); LinearStream cs(aubExecutionEnvironment->commandBuffer); BatchBuffer batchBuffer{cs.getGraphicsAllocation(), 0, 128u, nullptr, false, false, QueueThrottle::MEDIUM, cs.getUsed(), &cs}; std::unique_ptr<AUBCommandStreamReceiver::AubFileStream> mockAubFileStream(new GmockAubFileStream()); GmockAubFileStream *mockAubFileStreamPtr = static_cast<GmockAubFileStream *>(mockAubFileStream.get()); ASSERT_NE(nullptr, mockAubFileStreamPtr); mockAubFileStream.swap(aubCsr->stream); PatchInfoData patchInfoData[2] = {{0xAAAAAAAA, 128u, PatchInfoAllocationType::Default, 0xBBBBBBBB, 256u, PatchInfoAllocationType::Default}, {0xBBBBBBBB, 128u, PatchInfoAllocationType::Default, 0xDDDDDDDD, 256u, PatchInfoAllocationType::Default}}; EXPECT_TRUE(aubCsr->getFlatBatchBufferHelper().setPatchInfoData(patchInfoData[0])); EXPECT_TRUE(aubCsr->getFlatBatchBufferHelper().setPatchInfoData(patchInfoData[1])); std::vector<std::string> comments; EXPECT_CALL(*mockAubFileStreamPtr, addComment(_)).Times(2).WillRepeatedly(::testing::Invoke([&](const char *str) -> bool { comments.push_back(std::string(str)); return true; })); bool result = aubCsr->addPatchInfoComments(); EXPECT_TRUE(result); ASSERT_EQ(2u, comments.size()); EXPECT_EQ("PatchInfoData", comments[0].substr(0, 13)); EXPECT_EQ("AllocationsList", comments[1].substr(0, 15)); std::string line; std::istringstream input1; input1.str(comments[0]); uint32_t lineNo = 0; while (std::getline(input1, line)) { if (line.substr(0, 13) == "PatchInfoData") { continue; } std::ostringstream ss; ss << std::hex << patchInfoData[lineNo].sourceAllocation << ";" << patchInfoData[lineNo].sourceAllocationOffset << ";" << patchInfoData[lineNo].sourceType << ";"; ss << patchInfoData[lineNo].targetAllocation << ";" << patchInfoData[lineNo].targetAllocationOffset << ";" << patchInfoData[lineNo].targetType << ";"; EXPECT_EQ(ss.str(), line); lineNo++; } std::vector<std::string> expectedAddresses = {"aaaaaaaa", "bbbbbbbb", "cccccccc", "dddddddd"}; lineNo = 0; std::istringstream input2; input2.str(comments[1]); while (std::getline(input2, line)) { if (line.substr(0, 15) == "AllocationsList") { continue; } bool foundAddr = false; for (auto &addr : expectedAddresses) { if (line.substr(0, 8) == addr) { foundAddr = true; break; } } EXPECT_TRUE(foundAddr); EXPECT_TRUE(line.size() > 9); lineNo++; } mockAubFileStream.swap(aubCsr->stream); } HWTEST_F(AubCommandStreamReceiverTests, givenAddPatchInfoCommentsCalledWhenSourceAllocationIsNullThenDoNotAddToAllocationsList) { auto aubExecutionEnvironment = getEnvironment<AUBCommandStreamReceiverHw<FamilyType>>(false, true, true); auto aubCsr = aubExecutionEnvironment->template getCsr<AUBCommandStreamReceiverHw<FamilyType>>(); LinearStream cs(aubExecutionEnvironment->commandBuffer); BatchBuffer batchBuffer{cs.getGraphicsAllocation(), 0, 128u, nullptr, false, false, QueueThrottle::MEDIUM, cs.getUsed(), &cs}; std::unique_ptr<AUBCommandStreamReceiver::AubFileStream> mockAubFileStream(new GmockAubFileStream()); GmockAubFileStream *mockAubFileStreamPtr = static_cast<GmockAubFileStream *>(mockAubFileStream.get()); ASSERT_NE(nullptr, mockAubFileStreamPtr); mockAubFileStream.swap(aubCsr->stream); PatchInfoData patchInfoData = {0x0, 0u, PatchInfoAllocationType::Default, 0xBBBBBBBB, 0u, PatchInfoAllocationType::Default}; EXPECT_TRUE(aubCsr->getFlatBatchBufferHelper().setPatchInfoData(patchInfoData)); std::vector<std::string> comments; EXPECT_CALL(*mockAubFileStreamPtr, addComment(_)).Times(2).WillRepeatedly(::testing::Invoke([&](const char *str) -> bool { comments.push_back(std::string(str)); return true; })); bool result = aubCsr->addPatchInfoComments(); EXPECT_TRUE(result); ASSERT_EQ(2u, comments.size()); ASSERT_EQ("PatchInfoData", comments[0].substr(0, 13)); ASSERT_EQ("AllocationsList", comments[1].substr(0, 15)); std::string line; std::istringstream input; input.str(comments[1]); uint32_t lineNo = 0; std::vector<std::string> expectedAddresses = {"bbbbbbbb"}; while (std::getline(input, line)) { if (line.substr(0, 15) == "AllocationsList") { continue; } bool foundAddr = false; for (auto &addr : expectedAddresses) { if (line.substr(0, 8) == addr) { foundAddr = true; break; } } EXPECT_TRUE(foundAddr); EXPECT_TRUE(line.size() > 9); lineNo++; } mockAubFileStream.swap(aubCsr->stream); } HWTEST_F(AubCommandStreamReceiverTests, givenAddPatchInfoCommentsCalledWhenTargetAllocationIsNullThenDoNotAddToAllocationsList) { auto aubExecutionEnvironment = getEnvironment<AUBCommandStreamReceiverHw<FamilyType>>(false, true, true); auto aubCsr = aubExecutionEnvironment->template getCsr<AUBCommandStreamReceiverHw<FamilyType>>(); LinearStream cs(aubExecutionEnvironment->commandBuffer); BatchBuffer batchBuffer{cs.getGraphicsAllocation(), 0, 128u, nullptr, false, false, QueueThrottle::MEDIUM, cs.getUsed(), &cs}; std::unique_ptr<AUBCommandStreamReceiver::AubFileStream> mockAubFileStream(new GmockAubFileStream()); GmockAubFileStream *mockAubFileStreamPtr = static_cast<GmockAubFileStream *>(mockAubFileStream.get()); ASSERT_NE(nullptr, mockAubFileStreamPtr); mockAubFileStream.swap(aubCsr->stream); PatchInfoData patchInfoData = {0xAAAAAAAA, 0u, PatchInfoAllocationType::Default, 0x0, 0u, PatchInfoAllocationType::Default}; EXPECT_TRUE(aubCsr->getFlatBatchBufferHelper().setPatchInfoData(patchInfoData)); std::vector<std::string> comments; EXPECT_CALL(*mockAubFileStreamPtr, addComment(_)).Times(2).WillRepeatedly(::testing::Invoke([&](const char *str) -> bool { comments.push_back(std::string(str)); return true; })); bool result = aubCsr->addPatchInfoComments(); EXPECT_TRUE(result); ASSERT_EQ(2u, comments.size()); ASSERT_EQ("PatchInfoData", comments[0].substr(0, 13)); ASSERT_EQ("AllocationsList", comments[1].substr(0, 15)); std::string line; std::istringstream input; input.str(comments[1]); uint32_t lineNo = 0; std::vector<std::string> expectedAddresses = {"aaaaaaaa"}; while (std::getline(input, line)) { if (line.substr(0, 15) == "AllocationsList") { continue; } bool foundAddr = false; for (auto &addr : expectedAddresses) { if (line.substr(0, 8) == addr) { foundAddr = true; break; } } EXPECT_TRUE(foundAddr); EXPECT_TRUE(line.size() > 9); lineNo++; } mockAubFileStream.swap(aubCsr->stream); } HWTEST_F(AubCommandStreamReceiverTests, givenAubCommandStreamReceiverWhenGetIndirectPatchCommandsIsCalledForEmptyPatchInfoListThenIndirectPatchCommandBufferIsNotCreated) { auto aubExecutionEnvironment = getEnvironment<AUBCommandStreamReceiverHw<FamilyType>>(false, false, true); auto aubCsr = aubExecutionEnvironment->template getCsr<AUBCommandStreamReceiverHw<FamilyType>>(); size_t indirectPatchCommandsSize = 0u; std::vector<PatchInfoData> indirectPatchInfo; std::unique_ptr<char> commandBuffer(aubCsr->getFlatBatchBufferHelper().getIndirectPatchCommands(indirectPatchCommandsSize, indirectPatchInfo)); EXPECT_EQ(0u, indirectPatchCommandsSize); EXPECT_EQ(0u, indirectPatchInfo.size()); } HWTEST_F(AubCommandStreamReceiverTests, givenAubCommandStreamReceiverWhenGetIndirectPatchCommandsIsCalledForNonEmptyPatchInfoListThenIndirectPatchCommandBufferIsCreated) { typedef typename FamilyType::MI_STORE_DATA_IMM MI_STORE_DATA_IMM; std::unique_ptr<MemoryManager> memoryManager(nullptr); std::unique_ptr<AUBCommandStreamReceiverHw<FamilyType>> aubCsr(new AUBCommandStreamReceiverHw<FamilyType>(*platformDevices[0], "", true, *pDevice->executionEnvironment)); memoryManager.reset(aubCsr->createMemoryManager(false)); PatchInfoData patchInfo1(0xA000, 0u, PatchInfoAllocationType::KernelArg, 0x6000, 0x100, PatchInfoAllocationType::IndirectObjectHeap); PatchInfoData patchInfo2(0xB000, 0u, PatchInfoAllocationType::KernelArg, 0x6000, 0x200, PatchInfoAllocationType::IndirectObjectHeap); PatchInfoData patchInfo3(0xC000, 0u, PatchInfoAllocationType::IndirectObjectHeap, 0x1000, 0x100, PatchInfoAllocationType::Default); PatchInfoData patchInfo4(0xC000, 0u, PatchInfoAllocationType::Default, 0x2000, 0x100, PatchInfoAllocationType::GUCStartMessage); aubCsr->getFlatBatchBufferHelper().setPatchInfoData(patchInfo1); aubCsr->getFlatBatchBufferHelper().setPatchInfoData(patchInfo2); aubCsr->getFlatBatchBufferHelper().setPatchInfoData(patchInfo3); aubCsr->getFlatBatchBufferHelper().setPatchInfoData(patchInfo4); size_t indirectPatchCommandsSize = 0u; std::vector<PatchInfoData> indirectPatchInfo; std::unique_ptr<char> commandBuffer(aubCsr->getFlatBatchBufferHelper().getIndirectPatchCommands(indirectPatchCommandsSize, indirectPatchInfo)); EXPECT_EQ(4u, indirectPatchInfo.size()); EXPECT_EQ(2u * sizeof(MI_STORE_DATA_IMM), indirectPatchCommandsSize); } HWTEST_F(AubCommandStreamReceiverTests, givenAubCommandStreamReceiverWhenAddBatchBufferStartCalledAndBatchBUfferFlatteningEnabledThenBatchBufferStartAddressIsRegistered) { typedef typename FamilyType::MI_BATCH_BUFFER_START MI_BATCH_BUFFER_START; DebugManagerStateRestore dbgRestore; DebugManager.flags.FlattenBatchBufferForAUBDump.set(true); std::unique_ptr<MemoryManager> memoryManager(nullptr); std::unique_ptr<AUBCommandStreamReceiverHw<FamilyType>> aubCsr(new AUBCommandStreamReceiverHw<FamilyType>(*platformDevices[0], "", true, *pDevice->executionEnvironment)); memoryManager.reset(aubCsr->createMemoryManager(false)); MI_BATCH_BUFFER_START bbStart; aubCsr->addBatchBufferStart(&bbStart, 0xA000u, false); std::map<uint64_t, uint64_t> &batchBufferStartAddressSequence = aubCsr->getFlatBatchBufferHelper().getBatchBufferStartAddressSequence(); ASSERT_EQ(1u, batchBufferStartAddressSequence.size()); std::pair<uint64_t, uint64_t> addr = *batchBufferStartAddressSequence.begin(); EXPECT_EQ(reinterpret_cast<uint64_t>(&bbStart), addr.first); EXPECT_EQ(0xA000u, addr.second); } HWTEST_F(AubCommandStreamReceiverTests, givenFlatBatchBufferHelperWhenSettingSroreQwordOnSDICommandThenAppropriateBitIsSet) { typedef typename FamilyType::MI_STORE_DATA_IMM MI_STORE_DATA_IMM; std::unique_ptr<AUBCommandStreamReceiverHw<FamilyType>> aubCsr(new AUBCommandStreamReceiverHw<FamilyType>(*platformDevices[0], "", true, *pDevice->executionEnvironment)); MI_STORE_DATA_IMM cmd; cmd.init(); FlatBatchBufferHelperHw<FamilyType>::sdiSetStoreQword(&cmd, false); EXPECT_EQ(0u, static_cast<uint32_t>(cmd.getStoreQword())); FlatBatchBufferHelperHw<FamilyType>::sdiSetStoreQword(&cmd, true); EXPECT_EQ(1u, static_cast<uint32_t>(cmd.getStoreQword())); } class OsAgnosticMemoryManagerForImagesWithNoHostPtr : public OsAgnosticMemoryManager { public: GraphicsAllocation *allocateGraphicsMemoryForImage(ImageInfo &imgInfo, Gmm *gmm) override { auto imageAllocation = OsAgnosticMemoryManager::allocateGraphicsMemoryForImage(imgInfo, gmm); cpuPtr = imageAllocation->getUnderlyingBuffer(); imageAllocation->setCpuPtrAndGpuAddress(nullptr, imageAllocation->getGpuAddress()); return imageAllocation; }; void freeGraphicsMemoryImpl(GraphicsAllocation *imageAllocation) override { imageAllocation->setCpuPtrAndGpuAddress(cpuPtr, imageAllocation->getGpuAddress()); OsAgnosticMemoryManager::freeGraphicsMemoryImpl(imageAllocation); }; void *lockResource(GraphicsAllocation *imageAllocation) override { lockResourceParam.wasCalled = true; lockResourceParam.inImageAllocation = imageAllocation; lockCpuPtr = alignedMalloc(imageAllocation->getUnderlyingBufferSize(), MemoryConstants::pageSize); lockResourceParam.retCpuPtr = lockCpuPtr; return lockResourceParam.retCpuPtr; }; void unlockResource(GraphicsAllocation *imageAllocation) override { unlockResourceParam.wasCalled = true; unlockResourceParam.inImageAllocation = imageAllocation; alignedFree(lockCpuPtr); }; struct LockResourceParam { bool wasCalled = false; GraphicsAllocation *inImageAllocation = nullptr; void *retCpuPtr = nullptr; } lockResourceParam; struct UnlockResourceParam { bool wasCalled = false; GraphicsAllocation *inImageAllocation = nullptr; } unlockResourceParam; protected: void *cpuPtr = nullptr; void *lockCpuPtr = nullptr; }; HWTEST_F(AubCommandStreamReceiverTests, givenAubCommandStreamReceiverWhenWriteMemoryIsCalledOnImageWithNoHostPtrThenResourceShouldBeLockedToGetCpuAddress) { std::unique_ptr<OsAgnosticMemoryManagerForImagesWithNoHostPtr> memoryManager(nullptr); std::unique_ptr<AUBCommandStreamReceiverHw<FamilyType>> aubCsr(new AUBCommandStreamReceiverHw<FamilyType>(*platformDevices[0], "", true, *pDevice->executionEnvironment)); memoryManager.reset(new OsAgnosticMemoryManagerForImagesWithNoHostPtr); aubCsr->setMemoryManager(memoryManager.get()); cl_image_desc imgDesc = {}; imgDesc.image_width = 512; imgDesc.image_height = 1; imgDesc.image_type = CL_MEM_OBJECT_IMAGE2D; auto imgInfo = MockGmm::initImgInfo(imgDesc, 0, nullptr); auto queryGmm = MockGmm::queryImgParams(imgInfo); auto imageAllocation = memoryManager->allocateGraphicsMemoryForImage(imgInfo, queryGmm.get()); ASSERT_NE(nullptr, imageAllocation); EXPECT_TRUE(aubCsr->writeMemory(*imageAllocation)); EXPECT_TRUE(memoryManager->lockResourceParam.wasCalled); EXPECT_EQ(imageAllocation, memoryManager->lockResourceParam.inImageAllocation); EXPECT_NE(nullptr, memoryManager->lockResourceParam.retCpuPtr); EXPECT_TRUE(memoryManager->unlockResourceParam.wasCalled); EXPECT_EQ(imageAllocation, memoryManager->unlockResourceParam.inImageAllocation); queryGmm.release(); memoryManager->freeGraphicsMemory(imageAllocation); } HWTEST_F(AubCommandStreamReceiverTests, givenNoDbgDeviceIdFlagWhenAubCsrIsCreatedThenUseDefaultDeviceId) { const HardwareInfo &hwInfoIn = *platformDevices[0]; std::unique_ptr<MockAubCsr<FamilyType>> aubCsr(new MockAubCsr<FamilyType>(hwInfoIn, "", true, *pDevice->executionEnvironment)); EXPECT_EQ(hwInfoIn.capabilityTable.aubDeviceId, aubCsr->aubDeviceId); } HWTEST_F(AubCommandStreamReceiverTests, givenDbgDeviceIdFlagIsSetWhenAubCsrIsCreatedThenUseDebugDeviceId) { DebugManagerStateRestore stateRestore; DebugManager.flags.OverrideAubDeviceId.set(9); //this is Hsw, not used const HardwareInfo &hwInfoIn = *platformDevices[0]; std::unique_ptr<MockAubCsr<FamilyType>> aubCsr(new MockAubCsr<FamilyType>(hwInfoIn, "", true, *pDevice->executionEnvironment)); EXPECT_EQ(9u, aubCsr->aubDeviceId); } HWTEST_F(AubCommandStreamReceiverTests, givenAubCommandStreamReceiverWhenGetGTTDataIsCalledThenLocalMemoryShouldBeDisabled) { const HardwareInfo &hwInfoIn = *platformDevices[0]; std::unique_ptr<MockAubCsr<FamilyType>> aubCsr(new MockAubCsr<FamilyType>(hwInfoIn, "", true, *pDevice->executionEnvironment)); AubGTTData data = {}; aubCsr->getGTTData(nullptr, data); EXPECT_TRUE(data.present); EXPECT_FALSE(data.localMemory); } HWTEST_F(AubCommandStreamReceiverTests, givenPhysicalAddressWhenSetGttEntryIsCalledThenGttEntrysBitFieldsShouldBePopulated) { typedef typename AUBFamilyMapper<FamilyType>::AUB AUB; AubMemDump::MiGttEntry entry = {}; uint64_t address = 0x0123456789; AubGTTData data = {true, false}; AUB::setGttEntry(entry, address, data); EXPECT_EQ(entry.pageConfig.PhysicalAddress, address / 4096); EXPECT_TRUE(entry.pageConfig.Present); EXPECT_FALSE(entry.pageConfig.LocalMemory); } template <typename GfxFamily> struct MockAubCsrToTestExternalAllocations : public AUBCommandStreamReceiverHw<GfxFamily> { using AUBCommandStreamReceiverHw<GfxFamily>::AUBCommandStreamReceiverHw; using AUBCommandStreamReceiverHw<GfxFamily>::externalAllocations; bool writeMemory(AllocationView &allocationView) override { writeMemoryParametrization.wasCalled = true; writeMemoryParametrization.receivedAllocationView = allocationView; writeMemoryParametrization.statusToReturn = (0 != allocationView.second) ? true : false; return writeMemoryParametrization.statusToReturn; } struct WriteMemoryParametrization { bool wasCalled = false; AllocationView receivedAllocationView = {}; bool statusToReturn = false; } writeMemoryParametrization; }; HWTEST_F(AubCommandStreamReceiverTests, givenAubCommandStreamReceiverWhenMakeResidentExternalIsCalledThenGivenAllocationViewShouldBeAddedToExternalAllocations) { auto aubCsr = std::make_unique<MockAubCsrToTestExternalAllocations<FamilyType>>(*platformDevices[0], "", true, *pDevice->executionEnvironment); size_t size = 100; auto ptr = std::make_unique<char[]>(size); auto addr = reinterpret_cast<uint64_t>(ptr.get()); AllocationView externalAllocation(addr, size); ASSERT_EQ(0u, aubCsr->externalAllocations.size()); aubCsr->makeResidentExternal(externalAllocation); EXPECT_EQ(1u, aubCsr->externalAllocations.size()); EXPECT_EQ(addr, aubCsr->externalAllocations[0].first); EXPECT_EQ(size, aubCsr->externalAllocations[0].second); } HWTEST_F(AubCommandStreamReceiverTests, givenAubCommandStreamReceiverWhenMakeNonResidentExternalIsCalledThenMatchingAllocationViewShouldBeRemovedFromExternalAllocations) { auto aubCsr = std::make_unique<MockAubCsrToTestExternalAllocations<FamilyType>>(*platformDevices[0], "", true, *pDevice->executionEnvironment); size_t size = 100; auto ptr = std::make_unique<char[]>(size); auto addr = reinterpret_cast<uint64_t>(ptr.get()); AllocationView externalAllocation(addr, size); aubCsr->makeResidentExternal(externalAllocation); ASSERT_EQ(1u, aubCsr->externalAllocations.size()); aubCsr->makeNonResidentExternal(addr); EXPECT_EQ(0u, aubCsr->externalAllocations.size()); } HWTEST_F(AubCommandStreamReceiverTests, givenAubCommandStreamReceiverWhenMakeNonResidentExternalIsCalledThenNonMatchingAllocationViewShouldNotBeRemovedFromExternalAllocations) { auto aubCsr = std::make_unique<MockAubCsrToTestExternalAllocations<FamilyType>>(*platformDevices[0], "", true, *pDevice->executionEnvironment); size_t size = 100; auto ptr = std::make_unique<char[]>(size); auto addr = reinterpret_cast<uint64_t>(ptr.get()); AllocationView externalAllocation(addr, size); aubCsr->makeResidentExternal(externalAllocation); ASSERT_EQ(1u, aubCsr->externalAllocations.size()); aubCsr->makeNonResidentExternal(0); EXPECT_EQ(1u, aubCsr->externalAllocations.size()); } HWTEST_F(AubCommandStreamReceiverTests, givenAubCommandStreamReceiverWhenProcessResidencyIsCalledThenExternalAllocationsShouldBeMadeResident) { auto aubCsr = std::make_unique<MockAubCsrToTestExternalAllocations<FamilyType>>(*platformDevices[0], "", true, *pDevice->executionEnvironment); size_t size = 100; auto ptr = std::make_unique<char[]>(size); auto addr = reinterpret_cast<uint64_t>(ptr.get()); AllocationView externalAllocation(addr, size); aubCsr->makeResidentExternal(externalAllocation); ASSERT_EQ(1u, aubCsr->externalAllocations.size()); ResidencyContainer allocationsForResidency; aubCsr->processResidency(&allocationsForResidency); EXPECT_TRUE(aubCsr->writeMemoryParametrization.wasCalled); EXPECT_EQ(addr, aubCsr->writeMemoryParametrization.receivedAllocationView.first); EXPECT_EQ(size, aubCsr->writeMemoryParametrization.receivedAllocationView.second); EXPECT_TRUE(aubCsr->writeMemoryParametrization.statusToReturn); } HWTEST_F(AubCommandStreamReceiverTests, givenAubCommandStreamReceiverWhenProcessResidencyIsCalledThenExternalAllocationWithZeroSizeShouldNotBeMadeResident) { auto aubCsr = std::make_unique<MockAubCsrToTestExternalAllocations<FamilyType>>(*platformDevices[0], "", true, *pDevice->executionEnvironment); AllocationView externalAllocation(0, 0); aubCsr->makeResidentExternal(externalAllocation); ASSERT_EQ(1u, aubCsr->externalAllocations.size()); ResidencyContainer allocationsForResidency; aubCsr->processResidency(&allocationsForResidency); EXPECT_TRUE(aubCsr->writeMemoryParametrization.wasCalled); EXPECT_EQ(0u, aubCsr->writeMemoryParametrization.receivedAllocationView.first); EXPECT_EQ(0u, aubCsr->writeMemoryParametrization.receivedAllocationView.second); EXPECT_FALSE(aubCsr->writeMemoryParametrization.statusToReturn); } #if defined(__clang__) #pragma clang diagnostic pop #endif
52.067752
247
0.79264
[ "vector" ]
d6759f1313a8bab9e80a4321b8407e73b8428683
13,055
cpp
C++
Models/src/partmap.cpp
aaronvincent/gambit_aaron
a38bd6fc10d781e71f2adafd401c76e1e3476b05
[ "Unlicense" ]
2
2020-09-08T20:05:27.000Z
2021-04-26T07:57:56.000Z
Models/src/partmap.cpp
aaronvincent/gambit_aaron
a38bd6fc10d781e71f2adafd401c76e1e3476b05
[ "Unlicense" ]
9
2020-10-19T09:56:17.000Z
2021-05-28T06:12:03.000Z
Models/src/partmap.cpp
aaronvincent/gambit_aaron
a38bd6fc10d781e71f2adafd401c76e1e3476b05
[ "Unlicense" ]
5
2020-09-08T02:23:34.000Z
2021-03-23T08:48:04.000Z
// GAMBIT: Global and Modular BSM Inference Tool // ********************************************* /// \file /// /// Class definitions for GAMBIT particle /// database. /// /// ********************************************* /// /// Authors (add name and date if you modify): /// /// \author Pat Scott /// (p.scott@imperial.ac.uk) /// \date 2015 Jan /// /// ********************************************* #include <sstream> #include "gambit/Models/partmap.hpp" #include "gambit/Utils/standalone_error_handlers.hpp" #include "gambit/Utils/stream_overloads.hpp" namespace Gambit { namespace Models { /// Database accessor function partmap& ParticleDB() { static partmap local; return local; } /// Declare redirected constructor extern void define_particles(partmap*); /// Constructor partmap::partmap() { define_particles(this); } /// Add a new particle to the database void partmap::add(str long_name, std::pair<int, int> pdgpr) { if (has_particle(long_name)) { model_error().raise(LOCAL_INFO,"Particle "+long_name+" is multiply defined."); } long_name_to_pdg_pair[long_name] = pdgpr; pdg_pair_to_long_name[pdgpr] = long_name; } /// Add a new Standard Model particle to the database void partmap::add_SM(str long_name, std::pair<int, int> pdgpr) { add(long_name, pdgpr); SM.push_back(pdgpr); } /// Add a new generic particle class to the database void partmap::add_generic(str long_name, std::pair<int, int> pdgpr) { add(long_name, pdgpr); generic.push_back(pdgpr); } /// Add a new particle to the database with a short name and an index void partmap::add_with_short_pair(str long_name, std::pair<int, int> pdgpr, std::pair<str, int> shortpr) { add(long_name, pdgpr); short_name_pair_to_pdg_pair[shortpr] = pdgpr; short_name_pair_to_long_name[shortpr] = long_name; pdg_pair_to_short_name_pair[pdgpr] = shortpr; long_name_to_short_name_pair[long_name] = shortpr; } /// Add a new Standard Model particle to the database with a short name and an index void partmap::add_SM_with_short_pair(str long_name, std::pair<int, int> pdgpr, std::pair<str, int> shortpr) { add_with_short_pair(long_name, pdgpr, shortpr); SM.push_back(pdgpr); } /// Retrieve the PDG code and context integer, from the long name std::pair<int, int> partmap::pdg_pair(str long_name) const { if (not has_particle(long_name)) { model_error().raise(LOCAL_INFO,"Particle long name "+long_name+" is not in the particle database."); } return long_name_to_pdg_pair.at(long_name); } /// Retrieve the PDG code and context integer, from the short name and index pair std::pair<int, int> partmap::pdg_pair(std::pair<str,int> shortpr) const { return pdg_pair(shortpr.first,shortpr.second); } /// Retrieve the PDG code and context integer, from the short name and index std::pair<int, int> partmap::pdg_pair(str short_name, int i) const { std::pair<str, int> shortpr(short_name, i); if (not has_particle(shortpr)) { std::ostringstream ss; ss << "Short name " << short_name << " and index " << i << " are not in the particle database."; model_error().raise(LOCAL_INFO,ss.str()); } return short_name_pair_to_pdg_pair.at(shortpr); } /// Retrieve the long name, from the short name and index str partmap::long_name(str short_name, int i) const { std::pair<str, int> shortpr(short_name, i); if (not has_particle(std::pair<str, int>(short_name, i))) { std::ostringstream ss; ss << "Short name " << short_name << " and index " << i << " are not in the particle database."; model_error().raise(LOCAL_INFO,ss.str()); } return short_name_pair_to_long_name.at(shortpr); } /// Retrieve the long name, from the PDG code and context integer str partmap::long_name(std::pair<int, int> pdgpr) const { if (not has_particle(pdgpr)) { std::ostringstream ss; ss << "Particle with PDG code " << pdgpr.first << " and context integer " << pdgpr.second << " is not in the particle database."; model_error().raise(LOCAL_INFO,ss.str()); } return pdg_pair_to_long_name.at(pdgpr); } /// Retrieve the long name, from the PDG code and context integer str partmap::long_name(int pdg_code, int context) const { return long_name(std::make_pair(pdg_code,context)); } /// Retrieve the short name and index, from the long name std::pair<str, int> partmap::short_name_pair(str long_name) const { if (not has_particle(long_name)) { model_error().raise(LOCAL_INFO,"Particle "+long_name+" is not in the particle database."); } if (not has_short_name(long_name)) { model_error().raise(LOCAL_INFO,"Particle "+long_name+" does not have a short name."); } return long_name_to_short_name_pair.at(long_name); } /// Retrieve the short name and index, from the PDG code and context integer std::pair<str, int> partmap::short_name_pair(std::pair<int, int> pdgpr) const { if (not has_particle(pdgpr)) { std::ostringstream ss; ss << "Particle with PDG code " << pdgpr.first << " and context integer " << pdgpr.second << " is not in the particle database."; model_error().raise(LOCAL_INFO,ss.str()); } if (not has_short_name(pdgpr)) { std::ostringstream ss; ss << "Particle with PDG code " << pdgpr.first << " and context integer " << pdgpr.second << " does not have a short name."; model_error().raise(LOCAL_INFO,ss.str()); } return pdg_pair_to_short_name_pair.at(pdgpr); } /// Retrieve the short name and index, from the PDG code and context integer std::pair<str, int> partmap::short_name_pair(int pdg_code, int context) const { return short_name_pair(std::make_pair(pdg_code,context)); } /// Get a vector of PDG codes and context integers of Standard Model particles in the database const std::vector<std::pair<int, int> >& partmap::get_SM_particles() const { return SM; } /// Get a vector of PDG codes and context integers of generic particle classes in the database const std::vector<std::pair<int, int> >& partmap::get_generic_particles() const { return generic; } /// Check if a particle is in the database, using the long name bool partmap::has_particle(str long_name) const { return (long_name_to_pdg_pair.find(long_name) != long_name_to_pdg_pair.end()); } /// Check if a particle is in the database, using the short name and index bool partmap::has_particle(str short_name, int i) const { return has_particle(std::make_pair(short_name,i)); } bool partmap::has_particle(std::pair<str, int> shortpr) const { return (short_name_pair_to_pdg_pair.find(shortpr) != short_name_pair_to_pdg_pair.end()); } /// Check if a particle is in the database, using the PDG code and context integer bool partmap::has_particle(std::pair<int, int> pdgpr) const { return (pdg_pair_to_long_name.find(pdgpr) != pdg_pair_to_long_name.end()); } /// Check if a particle has a short name, using the long name bool partmap::has_short_name(str long_name) const { return (long_name_to_short_name_pair.find(long_name) != long_name_to_short_name_pair.end()); } /// Check if a particle has a short name, using the PDG code and context integer bool partmap::has_short_name(std::pair<int, int> pdgpr) const { return (pdg_pair_to_short_name_pair.find(pdgpr) != pdg_pair_to_short_name_pair.end()); } /// Get the matching anti-particle long name for a particle in the database, using the long name str partmap::get_antiparticle(str lname) const { return long_name(get_antiparticle(pdg_pair(lname))); } /// Get the matching anti-particle short name and index for a particle in the database, using the short name and index /// @{ std::pair<str, int> partmap::get_antiparticle(std::pair<str, int> shortpr) const { return short_name_pair(get_antiparticle(pdg_pair(shortpr))); } std::pair<str, int> partmap::get_antiparticle(str name, int index) const { return get_antiparticle(std::make_pair(name,index)); } /// @} /// Get the matching anti-particle PDG code and index for a particle in the database, using the PDG code and index /// @{ std::pair<int, int> partmap::get_antiparticle(std::pair<int, int> pdgpr) const { if (has_antiparticle(pdgpr)) { /// Antiparticles are identified by having the opposite sign PDG code to a particle pdgpr.first = -pdgpr.first; } /// Else assume particle is its own antiparticle /// (if this may not be true, use has_anti_particle to check explicitly for match) return pdgpr; } std::pair<int, int> partmap::get_antiparticle(int pdgcode, int context) const { return get_antiparticle(std::make_pair(pdgcode,context)); } /// @} /// Check if a particle has a matching anti-particle in the database, using the long name /// Note: will throw an error if the particle itself is not in the database! bool partmap::has_antiparticle(str long_name) const { return has_antiparticle(pdg_pair(long_name)); } /// Check if a particle has a matching anti-particle in the database, using the short name and index /// @{ bool partmap::has_antiparticle(std::pair<str, int> shortpr) const { return has_antiparticle(pdg_pair(shortpr)); } bool partmap::has_antiparticle(str name, int index) const { return has_antiparticle(std::make_pair(name,index)); } /// @} /// Check if a particle has a matching anti-particle in the database, using the PDG code and context integer /// @{ bool partmap::has_antiparticle(std::pair<int, int> pdgpr) const { /// Antiparticles are identified by having the opposite sign PDG code to a particle pdgpr.first = -pdgpr.first; return has_particle(pdgpr); } bool partmap::has_antiparticle(int pdgcode, int context) const { return has_antiparticle(std::make_pair(pdgcode,context)); } /// @} /// For debugging: use to check the contents of the particle database void partmap::check_contents() const { // Check that long and short names retrieve same information (when short name exists) typedef std::map<str, std::pair<int, int> >::const_iterator it_long_name_to_pdg_pair; typedef std::map<std::pair<int, int>, str>::const_iterator it_pdg_pair_to_long_name; typedef std::map<std::pair<str, int>, str>::const_iterator it_short_name_pair_to_long_name; //typedef std::map<std::pair<str, int>, std::pair<int, int> >::const_iterator it_short_name_pair_to_pdg_pair; //typedef std::map<std::pair<int, int>, std::pair<str, int> >::const_iterator it_pdg_pair_to_short_name_pair; //typedef std::map<str, std::pair<str, int> >::const_iterator it_long_name_to_short_name_pair; cout << "PDB: long name as key" << endl; for(it_long_name_to_pdg_pair it = long_name_to_pdg_pair.begin(); it != long_name_to_pdg_pair.end(); it++) { cout << " long_name_to_pdg_pair [" << it->first << "] => " << it->second << endl; if(has_short_name(it->first)) { cout << " long_name_to_short_name_pair[" << it->first << "] => " << long_name_to_short_name_pair.at(it->first) << endl; } else { cout << " long_name_to_short_name_pair[" << it->first << "] => " << "Has no short name!" << endl; } } cout << endl << "PDB: pdg_pair as key" << endl; for(it_pdg_pair_to_long_name it = pdg_pair_to_long_name.begin(); it != pdg_pair_to_long_name.end(); it++) { cout << " pdg_pair_to_long_name [" << it->first << "] => " << it->second << endl; if(has_short_name(it->second)) { cout << " pdg_pair_to_short_name[" << it->first << "] => " << pdg_pair_to_short_name_pair.at(it->first) << endl; } else { cout << " pdg_pair_to_short_name[" << it->first << "] => " << "Has no short name!" << endl; } } cout << endl << "PDB: short name pair as key" << endl; for(it_short_name_pair_to_long_name it = short_name_pair_to_long_name.begin(); it != short_name_pair_to_long_name.end(); it++) { cout << " short_name_pair_to_long_name[" << it->first << "] => " << it->second << endl; cout << " short_name_pair_to_pdg_pair [" << it->first << "] => " << short_name_pair_to_pdg_pair.at(it->first) << endl; } } } }
38.510324
137
0.63807
[ "vector", "model" ]
d67c782288d685416d3aaac93c88d12f66f21b56
2,191
cpp
C++
src/arch/android/input/GyroController.cpp
nebular/PixEngine_core
fc5f928641ed8c0d14254fdfc68973b3b144297f
[ "BSD-3-Clause" ]
1
2020-10-23T21:16:49.000Z
2020-10-23T21:16:49.000Z
src/arch/android/input/GyroController.cpp
nebular/PixEngine_core
fc5f928641ed8c0d14254fdfc68973b3b144297f
[ "BSD-3-Clause" ]
2
2020-03-02T22:43:09.000Z
2020-03-02T22:46:44.000Z
src/arch/android/input/GyroController.cpp
nebular/PixFu
fc5f928641ed8c0d14254fdfc68973b3b144297f
[ "BSD-3-Clause" ]
null
null
null
// // Created by rodo on 2020-02-13. // #include "GyroController.hpp" namespace Pix { const int LOOPER_ID_USER = 3; GyroController *GyroController::pCurrentInstance = nullptr; GyroController::GyroController(bool autoStart) : AxisController({-1,1,-1,1}) { sensorManager = AcquireASensorManagerInstance(); if (sensorManager == nullptr) throw std::runtime_error("No sensor manager"); rotation = ASensorManager_getDefaultSensor(sensorManager, ASENSOR_TYPE_GAME_ROTATION_VECTOR); if (rotation == nullptr) throw std::runtime_error("No rotation sensor"); looper = ALooper_prepare(ALOOPER_PREPARE_ALLOW_NON_CALLBACKS); if (looper == nullptr) throw std::runtime_error("Cannot get a looper"); rotationEventQueue = ASensorManager_createEventQueue(sensorManager, looper, LOOPER_ID_USER, nullptr, nullptr); if (rotationEventQueue == nullptr) throw std::runtime_error("Cannot get sensor event queue"); if (autoStart) enable(true); } GyroController::~GyroController() { enable(false); } bool GyroController::enable(bool stat) { if (stat) { auto status = ASensorEventQueue_enableSensor(rotationEventQueue, rotation); return status > 0; } else { ASensorEventQueue_disableSensor(rotationEventQueue, rotation); return true; } } ASensorManager *GyroController::AcquireASensorManagerInstance() { typedef ASensorManager *(*PF_GETINSTANCEFORPACKAGE)(const char *name); void *androidHandle = dlopen("libandroid.so", RTLD_NOW); auto getInstanceForPackageFunc = (PF_GETINSTANCEFORPACKAGE) dlsym(androidHandle, "ASensorManager_getInstanceForPackage"); if (getInstanceForPackageFunc) { return getInstanceForPackageFunc(kPackageName); } typedef ASensorManager *(*PF_GETINSTANCE)(); auto getInstanceFunc = (PF_GETINSTANCE) dlsym(androidHandle, "ASensorManager_getInstance"); // by all means at this point, ASensorManager_getInstance should be available assert(getInstanceFunc); return getInstanceFunc(); } void GyroController::poll() { ASensorEventQueue_getEvents(rotationEventQueue, &tCurrentEvent, 1); inputGyroscope(tCurrentEvent.vector.azimuth, tCurrentEvent.vector.pitch); } }
29.608108
93
0.754906
[ "vector" ]
d690a208b2f432f1426f7dcbe94941285f146f7b
1,362
cpp
C++
caffe/src/caffe/layers/label_switch_layer.cpp
sagardsaxena/CoGAN
6a0fbdb850c9ee78a8c83631aab8ded26195822b
[ "FSFAP" ]
285
2016-09-22T19:48:44.000Z
2022-03-11T03:30:07.000Z
caffe/src/caffe/layers/label_switch_layer.cpp
IsChristina/CoGAN
f940c28330ace09b3471d8745bfad7d891dbf095
[ "FSFAP" ]
12
2016-12-08T03:43:42.000Z
2020-06-04T05:42:52.000Z
caffe/src/caffe/layers/label_switch_layer.cpp
IsChristina/CoGAN
f940c28330ace09b3471d8745bfad7d891dbf095
[ "FSFAP" ]
76
2016-10-03T21:26:24.000Z
2022-03-28T12:05:57.000Z
#include <algorithm> #include <vector> #include "caffe/util/math_functions.hpp" #include "caffe/layers/label_switch_layer.hpp" namespace caffe { template <typename Dtype> void LabelSwitchLayer<Dtype>::LayerSetUp( const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) { update_base_ = this->layer_param().label_switch_param().update_base(); update_bin_ = this->layer_param().label_switch_param().update_bin(); count_ = 0; } template <typename Dtype> void LabelSwitchLayer<Dtype>::Reshape(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) { top[0]->Reshape(bottom[0]->num(),1,1,1); // label } template <typename Dtype> void LabelSwitchLayer<Dtype>::Forward_cpu(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) { const int iter = count_%update_base_; if( iter == update_bin_) { caffe_set<Dtype>(top[0]->count(),0,top[0]->mutable_cpu_data()); } else { caffe_copy<Dtype>(top[0]->count(),bottom[0]->mutable_cpu_data(),top[0]->mutable_cpu_data()); } count_++; } template <typename Dtype> void LabelSwitchLayer<Dtype>::Backward_cpu(const vector<Blob<Dtype>*>& top, const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom) { } #ifdef CPU_ONLY STUB_GPU(LabelSwitchLayer); #endif INSTANTIATE_CLASS(LabelSwitchLayer); REGISTER_LAYER_CLASS(LabelSwitch); } // namespace caffe
30.954545
150
0.732746
[ "vector" ]
d699f1fe8c26a7bd568b512278ec58015432b0cc
3,889
cpp
C++
GLMesh.cpp
ffhighwind/DeferredShading
c8b765c5d1126ef8f337047db50e2eb63308baf9
[ "Apache-2.0" ]
1
2019-10-18T13:45:05.000Z
2019-10-18T13:45:05.000Z
GLMesh.cpp
ffhighwind/DeferredShading
c8b765c5d1126ef8f337047db50e2eb63308baf9
[ "Apache-2.0" ]
1
2019-10-18T13:44:49.000Z
2019-11-29T23:26:27.000Z
GLMesh.cpp
ffhighwind/DeferredShading
c8b765c5d1126ef8f337047db50e2eb63308baf9
[ "Apache-2.0" ]
null
null
null
//SOURCE: https://learnopengl.com/code_viewer_gh.php?code=includes/learnopengl/mesh.h #include "GLMesh.hpp" namespace opengl { void GLMesh::Draw(GLuint shaderID) const { // bind appropriate textures unsigned int diffuseNr = 1; unsigned int specularNr = 1; unsigned int normalNr = 1; unsigned int heightNr = 1; for (unsigned int i = 0; i < _textures.size(); ++i) { glActiveTexture(GL_TEXTURE0 + i); // active proper texture unit before binding // retrieve texture number (the N in diffuse_textureN) std::string name; if (_textures[i].type == TextureType::Diffuse) { name = "texture_diffuse" + std::to_string(diffuseNr); diffuseNr++; } else if (_textures[i].type == TextureType::Specular) { name = "texture_specular" + std::to_string(specularNr); specularNr++; } else if (_textures[i].type == TextureType::Normal) { name = "texture_normal" + std::to_string(normalNr); normalNr++; } else if (_textures[i].type == TextureType::Height) { //name = "texture_height" + std::to_string(heightNr); //heightNr++; continue; } else { continue; //invalid texture } // now set the sampler to the correct texture unit glUniform1i(glGetUniformLocation(shaderID, name.c_str()), i); // and finally bind the texture glBindTexture(GL_TEXTURE_2D, _textures[i].id); } // draw mesh glBindVertexArray(_vao); glDrawElements(GL_TRIANGLES, _numTriangles, GL_UNSIGNED_INT, 0); glBindVertexArray(0); // set everything back to defaults for (unsigned int i = 0; i < _textures.size(); ++i) { glActiveTexture(_textures[i].id); glBindTexture(GL_TEXTURE_2D, 0); // default black texture } //glActiveTexture(GL_TEXTURE0); } void GLMesh::Load(const std::vector<GLVertex> &vertices, const std::vector<GLuint> &indices, const std::vector<GLTexture> &textures) { //this->vertices = vertices; //this->indices = indices; _textures = textures; _numTriangles = indices.size(); // create buffers/arrays glGenVertexArrays(1, &_vao); glGenBuffers(1, &_vbo); glGenBuffers(1, &_ebo); glBindVertexArray(_vao); // load data into vertex buffers glBindBuffer(GL_ARRAY_BUFFER, _vbo); // A great thing about structs is that their memory layout is sequential for all its items. // The effect is that we can simply pass a pointer to the struct and it translates perfectly to a glm::vec3/2 array which // again translates to 3/2 floats which translates to a byte array. glBufferData(GL_ARRAY_BUFFER, vertices.size() * sizeof(GLVertex), &vertices[0], GL_STATIC_DRAW); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, _ebo); glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.size() * sizeof(unsigned int), &indices[0], GL_STATIC_DRAW); // set the vertex attribute pointers // vertex Positions glEnableVertexAttribArray(0); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(GLVertex), (void*)0); // vertex normals glEnableVertexAttribArray(1); glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, sizeof(GLVertex), (void*)offsetof(GLVertex, Normal)); // vertex texture coords glEnableVertexAttribArray(2); glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, sizeof(GLVertex), (void*)offsetof(GLVertex, TexCoords)); // vertex tangent glEnableVertexAttribArray(3); glVertexAttribPointer(3, 3, GL_FLOAT, GL_FALSE, sizeof(GLVertex), (void*)offsetof(GLVertex, Tangent)); // vertex bitangent glEnableVertexAttribArray(4); glVertexAttribPointer(4, 3, GL_FLOAT, GL_FALSE, sizeof(GLVertex), (void*)offsetof(GLVertex, Bitangent)); glBindVertexArray(0); } void GLMesh::Unload() { glDeleteVertexArrays(1, &_vao); glDeleteBuffers(1, &_vbo); glDeleteBuffers(1, &_ebo); //glDeleteTextures } GLuint GLMesh::Id() const { return _vao; } bool GLMesh::HasTextureMap(TextureType type) const { for (auto iter = _textures.begin(); iter != _textures.end(); iter++) { if (iter->type == type) { return true; } } return false; } } // namespace opengl
31.362903
132
0.725379
[ "mesh", "vector" ]
d6a32418875168b8d97e24f398f09f771924f7e2
74,458
cpp
C++
core/sql/executor/ex_send_top.cpp
CoderSong2015/Apache-Trafodion
889631aae9cdcd38fca92418d633f2dedc0be619
[ "Apache-2.0" ]
148
2015-06-18T21:26:04.000Z
2017-12-25T01:47:01.000Z
core/sql/executor/ex_send_top.cpp
CoderSong2015/Apache-Trafodion
889631aae9cdcd38fca92418d633f2dedc0be619
[ "Apache-2.0" ]
1,352
2015-06-20T03:05:01.000Z
2017-12-25T14:13:18.000Z
core/sql/executor/ex_send_top.cpp
CoderSong2015/Apache-Trafodion
889631aae9cdcd38fca92418d633f2dedc0be619
[ "Apache-2.0" ]
166
2015-06-19T18:52:10.000Z
2017-12-27T06:19:32.000Z
/********************************************************************** // @@@ START COPYRIGHT @@@ // // Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. // // @@@ END COPYRIGHT @@@ **********************************************************************/ /* -*-C++-*- ***************************************************************************** * * File: ex_send_top.C * Description: Send top node (client part of client-server connection) * * * Created: 12/11/95 * Language: C++ * * * * ***************************************************************************** */ // ----------------------------------------------------------------------- #include "BaseTypes.h" #include "ex_stdh.h" #include "ex_exe_stmt_globals.h" #include "ComTdb.h" #include "ex_tcb.h" #include "ex_expr.h" #include "str.h" #include "ex_send_top.h" #include "ex_send_bottom.h" #include "ex_split_bottom.h" #include "ex_io_control.h" #include "ex_frag_rt.h" #include "Ex_esp_msg.h" #include "ComDiags.h" #include "ExStats.h" #include "ComTdb.h" #include "logmxevent.h" #include "ExCextdecs.h" #include "Context.h" #include "seabed/int/opts.h" static THREAD_P short sv_max_parallel_opens = 0; #include "ExSMTrace.h" #include "SMConnection.h" #include "ExSMQueue.h" #define ex_assert_both_sides( assert_test, assert_msg ) \ if (!(assert_test)) \ { \ if (connection_) \ connection_->dumpAndStopOtherEnd(true, false); \ ex_assert(0, assert_msg); \ } // ----------------------------------------------------------------------- // Methods for class ex_send_top_tdb // ----------------------------------------------------------------------- ex_tcb * ex_send_top_tdb::build(ex_globals * glob) { // seems like no split top node is above us, assume that we // are building only a single instance ex_assert(0,"send top w/o split top not used at this time"); return buildInstance(glob->castToExExeStmtGlobals(), 0, 0); } ex_tcb * ex_send_top_tdb::buildInstance(ExExeStmtGlobals * glob, Lng32 myInstanceNum, Lng32 childInstanceNum) { ex_tcb * result; // find out what type of connection is needed to communicate with the // corresponding send bottom node // do a lookup in the fragment table for the process id that // has the send bottom node // if this is extract consumer, create a processId from the esp phandle stored in tdb IpcProcessId dummyProcId; IpcProcessId &sendBottomProcId = dummyProcId; if (getExtractConsumerFlag()) { sendBottomProcId = *(IpcProcessId *) new (glob->getSpace()) IpcProcessId(getExtractEsp()); } else // normal case { sendBottomProcId = glob->getInstanceProcessId(childFragId_, childInstanceNum); } result = new(glob->getSpace()) ex_send_top_tcb(*this, glob, sendBottomProcId, myInstanceNum, childInstanceNum); result->registerSubtasks(); return result; } // ----------------------------------------------------------------------- // Methods for class ex_send_top_tcb // ----------------------------------------------------------------------- ///////////////////////////////////////////////////////////////////////////// // Constructor ex_send_top_tcb::ex_send_top_tcb(const ex_send_top_tdb& sendTopTdb, ExExeStmtGlobals* glob, const IpcProcessId& sendBottomProcId, Lng32 myInstanceNum, Lng32 childInstanceNum) : ex_tcb(sendTopTdb,1,glob), ipcBroken_(FALSE), workAtp_(NULL), myInstanceNum_(myInstanceNum), childInstanceNum_(childInstanceNum), currentBufferNumber_(1), currentSendBuffer_(NULL), currentReceiveBuffer_(NULL), ioSubtask_(NULL), ioCancelSubtask_(NULL), connection_(NULL), msgStream_(NULL), cancelMessageStream_(NULL), mySendTopTcbIndex_(NULL_COLL_INDEX), childFragHandle_(NullFragInstanceHandle), bottomProcId_(sendBottomProcId) { CollHeap * space = glob->getSpace(); ExMasterStmtGlobals *masterGlob = glob->castToExMasterStmtGlobals(); ExEspStmtGlobals *espGlob = glob->castToExEspStmtGlobals(); // We cannot build the SeaMonster target structure until fixup. In // the master executor The target process ID and tag is not yet // known. We will zero out the structure for now and populate it // later inside fixup(). smTarget_.node = 0; smTarget_.pid = 0; smTarget_.tag = 0; smTarget_.id = 0; // for non master ESPs, the trace cannot be initialized until fixup // if tracing is turned on using set session default. // trace file and level are set in the ms.env file will enable us to // trace from this point.. // If we are in the master executor and this is a parallel extract // producer query then we need to register the top-level ESP if (masterGlob != NULL && sendTopTdb.getExtractProducerFlag()) masterGlob->insertExtractEsp(sendBottomProcId); // Allocate the queues to communicate with parent qParent_.down = new(space) ex_queue(ex_queue::DOWN_QUEUE, sendTopTdb.queueSizeDown_, sendTopTdb.criDescDown_, space); // Allocate the private state in each entry of the down queue ex_send_top_private_state *p = new(space) ex_send_top_private_state(this); qParent_.down->allocatePstate(p, this); delete p; qParent_.up = new(space) ex_queue(ex_queue::UP_QUEUE, sendTopTdb.queueSizeUp_, sendTopTdb.criDescUp_, space); workAtp_ = allocateAtp(sendTopTdb.workCriDesc_, space); // fixup expressions if (moveInputValues()) (void) moveInputValues()->fixup(0, getExpressionMode(), this, glob->getSpace(), glob->getDefaultHeap(), FALSE, glob); nextToSendDown_ = qParent_.down->getHeadIndex(); stTidx_ = 0; for (int idx = 0; idx < NumSendTopTraceElements; idx++) { // initialize the trace buffer. setStState(INVALID, __LINE__); } setStState(NOT_OPENED, __LINE__); sendBufferSize_ = sendTopTdb.getSendBufferSize(); receiveBufferSize_ = sendTopTdb.getRecvBufferSize(); IpcMessageObjSize maxBufSize = sendBufferSize_ > receiveBufferSize_ ? sendBufferSize_ : receiveBufferSize_; maxBufSize += (sizeof(TupMsgBuffer) + sizeof(ExEspInputDataReqHeader) + sizeof(ExEspOpenReqHeader)); // temporary: ??? Larry Schumacher ??? // Old class IpcMessageStream cannot route multi-buffer messages originating // from new class IpcBufferedMsgStream so we add padding to ensure that the // message fits in one buffer. When routing message streams have been updated // to class IpcBufferedMsgStream we can remove the pad. The size of the // message sent to send bottom is a fixed length except for a variable // portion consisting of ComDiagsArea entries. Hopefully they won't exceed // the amount of padding added (1000 bytes)! Response messages from send // bottom are not routed through an old IpcMessageStream so they do not need // padding (unless ComDiagsArea responses become normal traffic in which case // we should optimize by expanding buffer size to include them). // Note also that a few bytes of padding will be needed because the // SqlBuffer inside the TupMsgBuffer gets aligned on an 8 byte boundary. // If class TupMsgBuffer has a size that is not a multiple of 8, then // the size of that space is 8 - (sizeof(TupMsgBuffer) mod 8). maxBufSize += 1000; // allocate a message stream to talk to send_bottom msgStream_ = new(glob->getSpace()) ExSendTopMsgStream(glob, getNumSendBuffers(), getNumRecvBuffers(), maxBufSize, this); if (sendTopTdb.getExchangeUsesSM()) msgStream_->setSMContinueProtocol(TRUE); // are the send bottom and send top nodes in the same process? if (masterGlob && masterGlob->getRtFragTable()->isLocal(sendBottomProcId)) // || espGlob && $$$$ TBD: check for ESP whether it's local { // get child tdb from global fragment instance map //ex_tdb *childTdb = (ex_tdb *)glob->getInstanceMap()->childPtr_; // build the child (for now $$$) //guiChildTcb_ = childTdb->build(glob); // get the send bottom node // (assume only one local send bottom node $$$$) //localChild_ = (ex_local_send_bottom_tcb *) // ((ex_split_bottom_tcb *)guiChildTcb_)->getSendNode(0); //msgStream_->setRecipient(localChild_->msgStream_); setStState(OPEN_COMPLETE, __LINE__); ABORT("local send bottom not implemented yet!"); } if (espGlob) { // the ESP keeps track of all send tops in a given fragment instance // for deadlock detection related to cancels mySendTopTcbIndex_ = espGlob->registerSendTopTcb(this); } } ///////////////////////////////////////////////////////////////////////////// // destructor ex_send_top_tcb::~ex_send_top_tcb() { freeResources(); } ///////////////////////////////////////////////////////////////////////////// // free all resources void ex_send_top_tcb::freeResources() { delete qParent_.up; qParent_.up = NULL; delete qParent_.down; qParent_.down = NULL; if (workAtp_) { deallocateAtp(workAtp_, getSpace()); workAtp_ = NULL; } // We must delete the connection before deleting the message // stream. This will guarantee that any outstanding I/O // associated with the message stream over the connection // will be cleaned up. If we do it in the reverse order, // and there is an I/O outstanding, all sorts of dangling // pointer scenarios are possible, resulting in abends or // other unpredictable behavior. delete connection_; delete msgStream_; delete cancelMessageStream_; } ///////////////////////////////////////////////////////////////////////////// ExWorkProcRetcode ex_send_top_tcb::sCancel(ex_tcb *tcb) { return ((ex_send_top_tcb *) tcb)->processCancel(); } ///////////////////////////////////////////////////////////////////////////// // register tcb for work void ex_send_top_tcb::registerSubtasks() { ExScheduler *sched = getGlobals()->getScheduler(); // register events for parent queues ex_assert(qParent_.down && qParent_.up,"Parent queues must exist"); sched->registerInsertSubtask(ex_tcb::sWork, this, qParent_.down, "WK"); sched->registerCancelSubtask(sCancel, this, qParent_.down,"CN"); sched->registerUnblockSubtask(ex_tcb::sWork,this, qParent_.up); // register a non-queue event for the IPC with the send top node ioSubtask_ = sched->registerNonQueueSubtask(sWork,this); ioCancelSubtask_ = sched->registerNonQueueSubtask(sCancel,this); } ///////////////////////////////////////////////////////////////////////////// // TCB fixup Int32 ex_send_top_tcb::fixup() { if (sendTopTdb().getExchangeUsesSM()) { // The purpose of this block is to populate the SeaMonster target // structure. In the master executor the process ID is not known // during the TCB constructor so we discover the value here. ExExeStmtGlobals *glob = getGlobals()->castToExExeStmtGlobals(); ExEspStmtGlobals *espGlob = glob->castToExEspStmtGlobals(); // Find the SeaMonster query ID and tag. A lookup is performed // with the child fragment number and the send top's instance // number int myFrag = (espGlob ? (int) espGlob->getMyFragId() : 0); int myInstNum = (int) myInstanceNum_; int childFrag = (int) sendTopTdb().getChildFragId(); int childInstNum = (int) childInstanceNum_; int smTag = (int) sendTopTdb().getSMTag(); Int64 smQueryID = glob->getSMQueryID(); // Find the send bottom's node and pid const GuaProcessHandle &phandle = bottomProcId_.getPhandle(); Int32 otherCPU, otherPID, otherNode; SB_Int64_Type seqNum = 0; phandle.decompose2(otherCPU, otherPID, otherNode , seqNum ); // Store SeaMonster information in the TCB and in IPC objects // Seaquest NodeId == NV CpuNum smTarget_.node = ExSM_GetNodeID(otherCPU); smTarget_.pid = otherPID; smTarget_.tag = smTag; smTarget_.id = smQueryID; ex_assert(smTarget_.id > 0, "Invalid SeaMonster query ID"); int downRowLen = (int) sendTopTdb().getDownRecordLength(); int upRowLen = (int) sendTopTdb().getUpRecordLength(); int downQueueLen = (int) sendTopTdb().queueSizeDown_; int upQueueLen = (int) sendTopTdb().queueSizeUp_; EXSM_TRACE(EXSM_TRACE_INIT|EXSM_TRACE_TAG, "SNDT FIXUP %p", this); EXSM_TRACE(EXSM_TRACE_INIT|EXSM_TRACE_TAG, "SNDT frag %d inst %d", myFrag, myInstNum); EXSM_TRACE(EXSM_TRACE_INIT|EXSM_TRACE_TAG, "SNDT child frag %d inst %d", childFrag, childInstNum); // regress/executor/TEST123 expects this line of output when // tracing is reduced to tags only EXSM_TRACE(EXSM_TRACE_INIT|EXSM_TRACE_TAG, "SNDT tgt %d:%d:%" PRId64 ":%d", (int) smTarget_.node, (int) smTarget_.pid, smTarget_.id, (int) smTarget_.tag); EXSM_TRACE(EXSM_TRACE_INIT, "SNDT work stream %p", msgStream_); EXSM_TRACE(EXSM_TRACE_INIT, "SNDT cancel stream %p", cancelMessageStream_); EXSM_TRACE(EXSM_TRACE_INIT, "SNDT send limit %d, in use limit %d", (int) msgStream_->getSendBufferLimit(), (int) msgStream_->getInUseBufferLimit()); EXSM_TRACE(EXSM_TRACE_INIT, "SNDT send size %d", (int) sendBufferSize_); EXSM_TRACE(EXSM_TRACE_INIT, "SNDT recv size %d", (int) receiveBufferSize_); EXSM_TRACE(EXSM_TRACE_INIT, "SNDT stream max buf %d", (int) msgStream_->getBufferSize()); EXSM_TRACE(EXSM_TRACE_INIT, "SNDT send bufs %d recv bufs %d", (int) getNumSendBuffers(), (int) getNumRecvBuffers()); EXSM_TRACE(EXSM_TRACE_INIT, "SNDT row len %d down, %d up", downRowLen, upRowLen); EXSM_TRACE(EXSM_TRACE_INIT, "SNDT down queue %d, up queue %d", downQueueLen, upQueueLen); } // if exchange uses SM return 0; } ///////////////////////////////////////////////////////////////////////////// // tcb work method for queue processing short ex_send_top_tcb::work() { EXSM_TRACE(EXSM_TRACE_WORK,"SNDT %p BEGIN WORK", this); short result = WORK_OK; if (ipcBroken_) { result = WORK_BAD_ERROR; } else { result = checkReceive(); EXSM_TRACE(EXSM_TRACE_WORK,"SNDT %p checkReceive rc %s", this, ExWorkProcRetcodeToString(result)); if (result == WORK_OK) { result = checkSend(); EXSM_TRACE(EXSM_TRACE_WORK,"SNDT %p checkSend rc %s", this, ExWorkProcRetcodeToString(result)); } if (sendTopState_ != WAITING_FOR_OPEN_COMPLETION) { if (result == WORK_OK) { result = continueRequest(); EXSM_TRACE(EXSM_TRACE_WORK,"SNDT %p continueRequest rc %s", this, ExWorkProcRetcodeToString(result)); } if (qParent_.down->isEmpty()) { msgStream_->releaseBuffers(); // do final garbage collection if (sendTopTdb().getExchangeUsesSM()) { ExExeStmtGlobals *glob = getGlobals()->castToExExeStmtGlobals(); EXSM_TRACE(EXSM_TRACE_WORK,"SNDT %p down queue empty", this); EXSM_TRACE(EXSM_TRACE_WORK,"SNDT %p glob msgs %d cancels %d", this, (int) glob->numSendTopMsgesOut(), (int) glob->numCancelMsgesOut()); if (msgStream_) EXSM_TRACE(EXSM_TRACE_WORK,"SNDT %p data resp pend %d", this, (int) msgStream_->numOfResponsesPending()); if (cancelMessageStream_) EXSM_TRACE(EXSM_TRACE_WORK,"SNDT %p cancel resp pend %d", this, (int) cancelMessageStream_->numOfResponsesPending()); } } } } EXSM_TRACE(EXSM_TRACE_WORK, "SNDT %p END WORK %s %s", this, ExWorkProcRetcodeToString(result), getExSendTopStateString(sendTopState_)); return result; } ///////////////////////////////////////////////////////////////////////////// // check for response data from send bottom and put in up queue short ex_send_top_tcb::checkReceive() { ExOperStats *statsEntry; ExESPStats *espStats; while (NOT qParent_.up->isFull()) { // process data from send bottom if (ipcBroken_) return WORK_BAD_ERROR; if (qParent_.down->isEmpty()) { // No more requests from the parent. This should mean // that there are no more data from the send bottom. // Clean up any remaining exhausted or empty receive buffers. do { if (currentReceiveBuffer_) { SqlBuffer* sqlBuf = currentReceiveBuffer_->get_sql_buffer(); ex_assert_both_sides(sqlBuf->atEOTD(), "Receiving extra rows from send bottom"); } currentReceiveBuffer_ = getReceiveBuffer(); } while (currentReceiveBuffer_); // done, we might be called again if more empty receive buffers or // new requests arrive return WORK_OK; } // the corresponding request entry in the down queue queue_index rindex = qParent_.down->getHeadIndex(); ex_queue_entry *rentry = qParent_.down->getQueueEntry(rindex); ex_send_top_private_state & pstate = *((ex_send_top_private_state *) rentry->pstate); // get sql buffer from message stream if (currentReceiveBuffer_ == NULL) { currentReceiveBuffer_ = getReceiveBuffer(); if (currentReceiveBuffer_ == NULL) { if (ipcBroken_) return WORK_BAD_ERROR; else return WORK_OK; } SqlBuffer *sb = currentReceiveBuffer_->get_sql_buffer(); ex_assert(sb, "Invalid SqlBuffer pointer"); sb->driveUnpack(); EXSM_TRACE(EXSM_TRACE_WORK, "SNDT %p tupps arrived %d", this, (int) sb->getTotalTuppDescs()); statsEntry = getStatsEntry(); if (statsEntry) espStats = statsEntry->castToExESPStats(); else espStats = NULL; // we got a buffer. Update statistics if (espStats) { espStats->bufferStats()->totalRecdBytes() += sb->getSendBufferSize(); espStats->bufferStats()->recdBuffers().addEntry( sb->get_used_size()); } } int numRowsReturned = 0; SqlBuffer* currSqlBuffer = currentReceiveBuffer_->get_sql_buffer(); currSqlBuffer->driveUnpack(); statsEntry = getStatsEntry(); while (NOT qParent_.up->isFull()) { // move data from sql buffer to up queue // data describing the row coming back tupp nextTupp; ControlInfo *ci; NABoolean currBufferIsEmpty; ComDiagsArea* diagsArea; // the entry in the up-queue to be filled ex_queue_entry* pentry = qParent_.up->getTailEntry(); // get the next row out of currSqlBuffer currBufferIsEmpty = currSqlBuffer->moveOutSendOrReplyData( FALSE, &(pentry->upState), nextTupp, &ci, &diagsArea, // will never be set not a non-NULL value NULL); if (currBufferIsEmpty) { currentReceiveBuffer_ = NULL; if (sendTopTdb().logDiagnostics()) { // 2^18 = about .25M, just needs to be // very infrequent and efficient if (((pstate.matchCount_++) % 2^18) == 0) { char msg[1024]; str_sprintf(msg, "Send top returning row # %d.", (Lng32) pstate.matchCount_); SQLMXLoggingArea::logExecRtInfo(NULL, 0, msg, sendTopTdb().getExplainNodeId()); } } break; } // check for a diags area coming back with this row if (ci->getIsExtDiagsAreaPresent()) { IpcMessageObjType msgType; ex_assert_both_sides(msgStream_->getNextObjType(msgType) AND msgType == IPC_SQL_DIAG_AREA, "no diags areas in message"); // construct a copy of diags area from message object // and put it in the up queue entry diagsArea = ComDiagsArea::allocate (getGlobals()->getDefaultHeap()); *msgStream_ >> *diagsArea; } else diagsArea = NULL; if ((rentry->downState.request == ex_queue::GET_NOMORE) && (pentry->upState.status != ex_queue::Q_NO_DATA)) { // Don't reply to up-queue. This request has been canceled. // Ignore replies until Q_NO_DATA. continue; } // fix index fields in the up state (state has already been set) pentry->upState.downIndex = rindex; pentry->upState.parentIndex = rentry->downState.parentIndex; // no need to fiddle with matchNo, the sender of the message // has done the right thing already // pass the Tupp up to the parent queue: copy request ATP and // append the tupp that we got from the message pentry->copyAtp(rentry); pentry->getTupp(rentry->criDesc()->noTuples()) = nextTupp; pentry->setDiagsArea(diagsArea); nextTupp.release(); // if stats were returned, unpack and merge them to the // stat area. if (ci->getIsExtStatsAreaPresent()) { IpcMessageObjType msgType; ex_assert_both_sides(msgStream_->getNextObjType(msgType) AND msgType == IPC_SQL_STATS_AREA, "no stats area in message"); CollHeap * defaultHeap = getGlobals()->getDefaultHeap(); ExStatisticsArea* statArea = new(defaultHeap) ExStatisticsArea(defaultHeap, 0, ((ComTdb*)getTdb())->getCollectStatsType()); *msgStream_ >> *statArea; if ( getGlobals()->statsEnabled() ) mergeStats(statArea); EXSM_TRACE(EXSM_TRACE_WORK,"SNDT %p merged stats", this); // we can get rid of the received area now NADELETE(statArea, ExStatisticsArea, defaultHeap); } // If statistics are being collected, update the number of // rows returned now. if(pentry->upState.status != ex_queue::Q_NO_DATA) { if(statsEntry) statsEntry->incActualRowsReturned(); } qParent_.up->insert(); numRowsReturned++; // if this is EOF then we are done with the request if (pentry->upState.status == ex_queue::Q_NO_DATA) { EXSM_TRACE(EXSM_TRACE_WORK,"SNDT %p returned Q_NO_DATA", this); ex_assert_both_sides( (pstate.step_ == STARTED_) || (pstate.step_ == CANCELED_AFTER_SENT_), "Send top responding incorrectly!"); pstate.step_ = NOT_STARTED_; qParent_.down->removeHead(); // rentry and pstate have become invalid, exit to outer loop break; } } // while parent up queue not full EXSM_TRACE(EXSM_TRACE_WORK, "SNDT %p queue entries returned: %d", this, numRowsReturned); if (qParent_.up->isFull()) EXSM_TRACE(EXSM_TRACE_WORK, "SNDT %p up queue is full", this); } // while parent down queue not empty and parent up queue not full // At this point we are either waiting for another buffer from the // send bottom node or the up queue is full. In both cases an event // will wake us up if there is more work. return WORK_OK; } ///////////////////////////////////////////////////////////////////////////// // get a receive buffer from the message stream TupMsgBuffer* ex_send_top_tcb::getReceiveBuffer() { IpcMessageObjType msgType; while (msgStream_->getNextReceiveMsg(msgType)) { ex_assert_both_sides(msgType == IPC_MSG_SQLESP_DATA_REPLY, "received message from unknown message stream"); while (msgStream_->getNextObjType(msgType)) { if (msgType == ESP_RETURN_STATUS_HDR) { // reply to open message, save child ExFragInstanceHandle // only a reply to an OPEN can be of this message type ex_assert_both_sides(sendTopState_ == WAITING_FOR_OPEN_REPLY, "received status reply after opening send bottom"); ExEspReturnStatusReplyHeader* statHdr = new(msgStream_->receiveMsgObj()) ExEspReturnStatusReplyHeader(msgStream_); childFragHandle_ = statHdr->handle_; setStState(OPEN_COMPLETE, __LINE__); } // check for a diagnostics area, returned from server during OPEN else if (msgType == ESP_DIAGNOSTICS_AREA) { // construct a copy of diags area from message object ComDiagsArea* diagsArea = ComDiagsArea::allocate (getGlobals()->getDefaultHeap()); Lng32 objSize = msgStream_->getNextObjSize(); // The diagsArea could have come packed from buffered or unbuffered stream. // If the sender used unbuffered stream, it will send only the header first, // followed by the actual diagsArea. If the sender used buffered stream, // it will only send the actual diags area. if (objSize == sizeof(IpcMessageObj)) { IpcMessageObj* packedObj = msgStream_->receiveMsgObj(); // ignore the header packedObj = msgStream_->receiveMsgObj(); ex_assert_both_sides(packedObj, "error receiving diags area from unbuffered stream"); diagsArea->unpackObj(packedObj->getType(), packedObj->getVersion(), TRUE, packedObj->getObjLength(), (const char *)packedObj); } else { *msgStream_ >> *diagsArea; } // check for connection errors if (diagsArea->getNumber(DgSqlCode::ERROR_) > 0) { ipcBroken_ = TRUE; } // merge the returned diagnostics area with the main one if (getGlobals()->castToExExeStmtGlobals()->getDiagsArea()) { getGlobals()->castToExExeStmtGlobals()-> getDiagsArea()->mergeAfter(*diagsArea); // clean up diagsArea->deAllocate(); } else { getGlobals()->castToExExeStmtGlobals()-> setGlobDiagsArea(diagsArea); diagsArea->decrRefCount(); } } else if (msgType == ESP_RETURN_DATA_HDR) { // reply data header, get sql buffer and return for processing ExEspReturnDataReplyHeader* dataHdr = new(msgStream_->receiveMsgObj()) ExEspReturnDataReplyHeader(msgStream_); ex_assert_both_sides(msgStream_->getNextObjType(msgType) AND msgType == ESP_OUTPUT_SQL_BUFFER, "output data header w/o output data buffer received"); if (dataHdr->stopSendingData_) setStState(SERVER_SATURATED, __LINE__); else setStState(OPEN_COMPLETE, __LINE__); TupMsgBuffer *buffer = new(msgStream_->receiveMsgObj()) TupMsgBuffer(msgStream_); return buffer; } else { ex_assert_both_sides(0, "Unexpected reply received from ESP"); } } } return NULL; } ///////////////////////////////////////////////////////////////////////////// // check for data in the down queue to send to send bottom short ex_send_top_tcb::checkSend() { ExEspStmtGlobals *espGlobals = getGlobals()->castToExExeStmtGlobals()->castToExEspStmtGlobals(); // free up any receive buffers no longer in use msgStream_->cleanupBuffers(); if (sendTopState_ == SERVER_SATURATED OR sendTopState_ == WAITING_FOR_OPEN_REPLY) return WORK_OK; // send continue messages only while (qParent_.down->entryExists(nextToSendDown_)) { // build sql buffers and send to send bottom if (ipcBroken_) return WORK_BAD_ERROR; // Need to handle canceled entries here in the outer loop // (which executes on the first queue entry, and whenever // we get a new buffer), as well as in the inner loop (which // handles all the queue entries that fit in one buffer) below. ex_queue_entry* pentry = qParent_.down->getQueueEntry(nextToSendDown_); ex_send_top_private_state & pstate = *((ex_send_top_private_state *) pentry->pstate); ex_assert(pstate.step_ == NOT_STARTED_, "Message shoulda been NOT_STARTED_"); if (espGlobals) espGlobals->setSendTopTcbActivated(mySendTopTcbIndex_); // NOTE: the down request we are working on may be a GET_NOMORE // request. We could optimize the logic here by not sending a // GET_NOMORE request down. However, that would just trigger // some "late cancel" logic in the split bottom node above us // (if applicable). Cancels in this parallel data stream are // best dealt with in the split bottom node below us, therefore // we'll send this request down even if it is a cancel. // flow control: don't send any more requests down if // there are too many outstanding requests or if we // have too many buffers in use if (msgStream_->sendLimitReached()) return WORK_OK; if (msgStream_->inUseLimitReached()) return WORK_POOL_BLOCKED; // Am I being asked to refrain from new I/O? if (getGlobals()->castToExExeStmtGlobals()->noNewRequest()) { // If my root is split_bottom, it will use its list of // activated send tops reschedule me when I/O can resume. // See the call to setSendTopTcbActivated above. return WORK_OK; } // get sql buffer from message stream currentSendBuffer_ = getSendBuffer(); if (currentSendBuffer_ == NULL) { if (ipcBroken_) { return WORK_BAD_ERROR; } else { if (sendTopState_ == WAITING_FOR_OPEN_COMPLETION) return WORK_OK; else return WORK_POOL_BLOCKED; } } SqlBuffer* sqlBuf = currentSendBuffer_->get_sql_buffer(); NABoolean sendSpaceAvailable = TRUE; do // fill sql buffer with data from down queue { ex_queue_entry* pentry = qParent_.down->getQueueEntry(nextToSendDown_); ex_send_top_private_state & pstate = *((ex_send_top_private_state *) pentry->pstate); ex_assert(pstate.step_ == NOT_STARTED_, "Message shoulda been NOT_STARTED_"); // // Allocate space in buffer for control info (down state) and // input row, if one is present // tupp_descriptor* controlInfoAsTupp = sqlBuf->add_tuple_desc((unsigned short) sizeof(ControlInfo)); NABoolean isInputRowToBeSent = (moveInputValues() != NULL); tupp_descriptor* rowToSend = isInputRowToBeSent ? sqlBuf->add_tuple_desc(sendTopTdb().getDownRecordLength()) : NULL; NABoolean isDiagsAreaToBeSent = pentry->getDiagsArea() != NULL; // // Check that there was sufficient space in buffer. // sendSpaceAvailable = (controlInfoAsTupp != NULL) AND (!isInputRowToBeSent OR rowToSend != NULL); if (!sendSpaceAvailable) { // // Sufficient space is not available in buffer. Deallocate // control info tupp_descriptor, if non-null. // if (controlInfoAsTupp) sqlBuf->remove_tuple_desc(); if (rowToSend) sqlBuf->remove_tuple_desc(); } else { // // There was space in the send buffer --- copy the current input // row into it and advance to the next input queue entry. // ControlInfo msgControlInfo; // // Copy the down state and flags into first tupp allocated // in the message buffer. // msgControlInfo.getDownState() = pentry->downState; msgControlInfo.getDownState().parentIndex = nextToSendDown_; msgControlInfo.setIsDataRowPresent(isInputRowToBeSent); msgControlInfo.setIsExtDiagsAreaPresent(isDiagsAreaToBeSent); str_cpy_all(controlInfoAsTupp->getTupleAddress(), (char *) &msgControlInfo, sizeof(ControlInfo)); // SqlBuffer::findAndCancel may need this. controlInfoAsTupp->setControlTupleType(); if (isInputRowToBeSent) { // SqlBuffer::findAndCancel may need this. controlInfoAsTupp->setDataTupleType(); // // Evaluate the move input expression, copying the // actual input row into the second tupp allocated // in the message buffer. // workAtp_->getTupp((unsigned short) sendTopTdb().moveExprTuppIndex_) = rowToSend; ex_expr::exp_return_type retval = moveInputValues()->eval(pentry->getAtp(),workAtp_); ex_assert(retval != ex_expr::EXPR_ERROR, "Add error handling"); // release the tupp_descriptor in the buffer workAtp_->getTupp((unsigned short) sendTopTdb().moveExprTuppIndex_) = NULL; } // // If there is a diagnostics area to send, then add // it to the message following the sql buffer. // if (isDiagsAreaToBeSent) { // construct a copy of ComDiagsArea in message *msgStream_ << *(pentry->getDiagsArea()); } // this one is sent down (ok, packed into the buffer), // so remember its state and buffer number (in case // we cancel later) and advance to the next down queue entry pstate.step_ = STARTED_; pstate.bufferNumber_ = currentBufferNumber_; pstate.matchCount_ = 0; nextToSendDown_++; } } while (sendSpaceAvailable AND qParent_.down->entryExists(nextToSendDown_)); // send sql buffer even if not completely full ex_assert(NOT currentSendBuffer_->get_sql_buffer()->isEmpty(), "Send top's sql buffer is empty"); // indicate if stats are enabled or not sqlBuf->setStatsEnabled(getGlobals()->statsEnabled()); currentSendBuffer_ = NULL; ExOperStats *statsEntry; if ((statsEntry = getStatsEntry()) != NULL) { ExESPStats *stats = statsEntry->castToExESPStats(); if (stats) { stats->bufferStats()->totalSentBytes() += sqlBuf->getSendBufferSize(); stats->bufferStats()->sentBuffers().addEntry(sqlBuf->get_used_size()); } } // pack sql buffer sqlBuf->drivePack(); EXSM_TRACE(EXSM_TRACE_WORK,"SNDT %p SEND data %d tupps", this, (int) sqlBuf->getTotalTuppDescs()); msgStream_->sendRequest(); currentBufferNumber_++; } return WORK_OK; } ///////////////////////////////////////////////////////////////////////////// // get a send buffer from the message stream TupMsgBuffer* ex_send_top_tcb::getSendBuffer() { if (sendTopState_ == NOT_OPENED || sendTopState_ == WAITING_FOR_OPEN_COMPLETION) { // Don't even try to open the connection before the child process // isn't ready. If this is the master, check for the run-time fragment // directory to be in the "READY" state. If this is an ESP, it's ok // to go ahead and open, the other ESP must have received the load // message for its fragment instance by now, since the master has // already sent us data via its send top nodes. // The above argument does not apply for parallel extract consumer. ExExeStmtGlobals* glob = getGlobals()->castToExExeStmtGlobals(); ExMasterStmtGlobals* masterGlob = glob->castToExMasterStmtGlobals(); if (sendTopState_ == NOT_OPENED) { if (!sendTopTdb().getExtractConsumerFlag()) { if (masterGlob AND masterGlob->getRtFragTable() AND masterGlob->getRtFragTable()->getState() != ExRtFragTable::READY) return NULL; // retry later } // the connection may already be created thru late cancel. // if so, there is no need to create another one. if (connection_ == NULL) if (createConnectionToSendBottom() != 0 || #ifdef NA_LINUX_DISABLE // multi fragment esp sendTopState_ == NOT_OPENED || #endif sendTopState_ == WAITING_FOR_OPEN_COMPLETION) return NULL; } if (sendTopState_ == WAITING_FOR_OPEN_COMPLETION) { if (createConnectionToSendBottom() != 0) // Finish creating connection return NULL; } EXSM_TRACE(EXSM_TRACE_BUFFER, "SNDT %p about to allocate msg buffer", this); msgStream_->addRecipient(connection_); // construct open request in message, // ask child ESP to respond with ExFragInstanceHandle ExEspOpenReqHeader *openReq = new(*msgStream_) ExEspOpenReqHeader((NAMemory *) NULL); if (openReq == NULL) return NULL; // if this is parallel extract consumer sendTop, send the security info too if (sendTopTdb().getExtractConsumerFlag()) { openReq->myInstanceNum_ = 0; openReq->statID_ = 0; openReq->setOpenType(ExEspOpenReqHeader::PARALLEL_EXTRACT); // Send the securityInfo object along with the OPEN // message. The user name we put in the message must not have // a ",<password>" suffix. If the user name we get from the // context does have the password suffix, we strip it off. IpcEnvironment *ipcEnv = getGlobals()->castToExExeStmtGlobals()->getIpcEnvironment(); CollHeap *ipcHeap = ipcEnv->getHeap(); ExMsgSecurityInfo *secInfo = new (ipcHeap) ExMsgSecurityInfo(ipcHeap); const char *key = sendTopTdb().getExtractSecurityKey(); Int32 len = str_len(key); char *copyOfKey = (char *) ipcHeap->allocateMemory(len + 1); str_cpy_all(copyOfKey, key, len + 1); secInfo->setSecurityKey(copyOfKey); ContextCli *context = masterGlob->getContext(); ex_assert(context, "Invalid ContextCli pointer"); // We need to retrieve a user identifier from ContextCli. On // Linux it will be the 32-bit integer and we will send the // string representation of that integer. On other platforms // it will be a user name. // NOTE: The user ID for the extract security check is // currently sent and compared as a C string. On Linux it is // possible to send and compare integers which would lead to // simpler code. The code to send/compare strings is still // used because it works on all platforms. const char *idToSend = NULL; Int32 *userID = context->getDatabaseUserID(); Int32 userAsInt = *((Int32 *) userID); char userIDBuf[32]; sprintf(userIDBuf, "%d", (int) userAsInt); idToSend = &(userIDBuf[0]); ex_assert(idToSend, "Could not retrieve user ID from ContextCli"); char *copyOfId = NULL; // On platforms other than Linux the user identifer can be a // "username,password" string. We only want to send the // characters before the comma. char *locationOfComma = NULL; if (locationOfComma == NULL) { len = str_len(idToSend); copyOfId = (char *) ipcHeap->allocateMemory(len + 1); str_cpy_all(copyOfId, idToSend, len + 1); secInfo->setAuthID(copyOfId); } else { len = locationOfComma - idToSend; copyOfId = (char *) ipcHeap->allocateMemory(len + 1); str_cpy_all(copyOfId, idToSend, len); copyOfId[len] = 0; secInfo->setAuthID(copyOfId); } *msgStream_ << *secInfo; secInfo->decrRefCount(); secInfo = NULL; } else // normal case, this is not an extract consumer { openReq->key_ = glob->getFragmentKey(sendTopTdb().getChildFragId()); openReq->myInstanceNum_ = getMyInstanceNum(); openReq->statID_ = 0; // not used at this point } setStState(WAITING_FOR_OPEN_REPLY, __LINE__); } else if ((sendTopState_ == OPEN_COMPLETE) && (msgStream_->getRecipients().isEmpty())) { // This can happen if query has been executed once before and this // send_top did a late cancel. msgStream_->addRecipient(connection_); } // construct Input data request header in message, // include child ExFragInstanceHandle for fast routing ExEspInputDataReqHeader *hdr = new(*msgStream_) ExEspInputDataReqHeader((NAMemory *) NULL); if (hdr == NULL) return NULL; hdr->handle_ = childFragHandle_; hdr->myInstanceNum_ = getMyInstanceNum(); hdr->injectErrorAtQueueFreq_ = getGlobals()->getInjectErrorAtQueue(); #ifdef _DEBUG if (getenv("TEST_ERROR_AT_QUEUE_NO_ESP")) hdr->injectErrorAtQueueFreq_ = 0; #endif // construct sql buffer(TupMsgBuffer) directly in message to avoid copy TupMsgBuffer *result = new(*msgStream_, sendBufferSize_) TupMsgBuffer(sendBufferSize_, TupMsgBuffer::MSG_IN, msgStream_); if (result == NULL) ABORT("mismatched send top buffer size"); return result; } ///////////////////////////////////////////////////////////////////////////// // pre-send continue requests in anticipation of many reply data messages short ex_send_top_tcb::continueRequest() { if (qParent_.down->isEmpty() OR sendTopState_ == WAITING_FOR_OPEN_REPLY OR sendTopState_ == NOT_OPENED OR sendTopState_ == WAITING_FOR_OPEN_COMPLETION) return WORK_OK; if (msgStream_->sendLimitReached()) EXSM_TRACE(EXSM_TRACE_CONTINUE,"SNDT %p send limit reached, rp %d", this, (int) msgStream_->numOfResponsesPending()); // send continue requests until the limit for outstanding requests // or for incoming and used buffers is reached while (NOT msgStream_->sendLimitReached()) { if (ipcBroken_) return WORK_BAD_ERROR; if (msgStream_->inUseLimitReached()) { EXSM_TRACE(EXSM_TRACE_CONTINUE, "SNDT %p CREQ in use limit reached, rp %d", this, (int) msgStream_->numOfResponsesPending()); // We can't send another continue request down because there // is no room up here to take the reply. Return a status that // causes this task to be rescheduled. Next time, methods // cleanupBuffers() and checkReceive() can reduce the number // of in-use buffers and of unread buffers in the receive // queue. return WORK_POOL_BLOCKED; } // Am I being asked to refrain from new I/O? if (getGlobals()->castToExExeStmtGlobals()->noNewRequest()) { ExEspStmtGlobals *espGlobals = getGlobals()-> castToExExeStmtGlobals()->castToExEspStmtGlobals(); if (espGlobals) { // Make sure my root (split_bottom) knows to schedule me // when I/O can resume. espGlobals->setSendTopTcbActivated(mySendTopTcbIndex_); } return WORK_OK; } // construct continue request header in message, // include child ExFragInstanceHandle for fast routing ExEspContinueReqHeader *hdr = new(*msgStream_) ExEspContinueReqHeader((NAMemory *) NULL); if (hdr == NULL) return WORK_POOL_BLOCKED; hdr->handle_ = childFragHandle_; hdr->myInstanceNum_ = getMyInstanceNum(); EXSM_TRACE(EXSM_TRACE_CONTINUE, "SNDT %p CREQ sending continue", this); msgStream_->sendRequest(); } return WORK_OK; } void ex_send_top_tcb::checkCancelReply() { if (!cancelMessageStream_) { // no replies yet if no message stream yet. } else { IpcMessageObjType msgType; while (cancelMessageStream_->getNextReceiveMsg(msgType)) { ex_assert_both_sides(msgType == IPC_MSG_SQLESP_CANCEL_REPLY, "received message from unknown message stream"); while (cancelMessageStream_->getNextObjType(msgType)) { ex_assert_both_sides(msgType == ESP_RETURN_CANCEL_HDR, "Wrong type of message received by cancelMessageStream!"); EXSM_TRACE(EXSM_TRACE_CANCEL, "SNDT %p recv ESP_RETURN_CANCEL_HDR", this); EXSM_TRACE(EXSM_TRACE_CANCEL,"SNDT %p state %s", this, getExSendTopStateString(sendTopState_)); ExEspCancelReplyHeader *dataHdr = new(cancelMessageStream_->receiveMsgObj()) ExEspCancelReplyHeader(cancelMessageStream_); // if CANCELED_BEFORE_OPENED, only the late cancel message // was sent, not the open message. Go back to NOT_OPENED // state so that the open message could be sent. // See the state transition diagram in the header file. if (sendTopState_ == CANCELED_BEFORE_OPENED) { setStState(NOT_OPENED, __LINE__); } } } // free up any receive buffers no longer in use cancelMessageStream_->cleanupBuffers(); } // if cancelMessageStream_ ... else ... } ///////////////////////////////////////////////////////////////////////////// // ExWorkProcRetcode ex_send_top_tcb::processCancel() { EXSM_TRACE(EXSM_TRACE_CANCEL,"SNDT %p BEGIN processCancel", this); ExWorkProcRetcode result = processCancelHelper(); if (sendTopTdb().getExchangeUsesSM()) { ExExeStmtGlobals *glob = getGlobals()->castToExExeStmtGlobals(); EXSM_TRACE(EXSM_TRACE_CANCEL,"SNDT %p glob msgs %d cancels %d", this, (int) glob->numSendTopMsgesOut(), (int) glob->numCancelMsgesOut()); if (cancelMessageStream_) EXSM_TRACE(EXSM_TRACE_CANCEL,"SNDT %p cancel resp pend %d", this, (int) cancelMessageStream_->numOfResponsesPending()); EXSM_TRACE(EXSM_TRACE_CANCEL,"SNDT %p END processCancel rc %s", this, ExWorkProcRetcodeToString(result)); } return result; } ExWorkProcRetcode ex_send_top_tcb::processCancelHelper() { if (ipcBroken_) return WORK_BAD_ERROR; checkCancelReply(); // Are there any messages still waiting to be canceled? Am I too late? if (qParent_.down->isEmpty()) { EXSM_TRACE(EXSM_TRACE_CANCEL,"SNDT %p down queue is empty", this); return WORK_OK; } TupMsgBuffer * cancelSendBuffer = NULL; queue_index pindex = qParent_.down->getHeadIndex(); while (pindex != nextToSendDown_) { ex_queue_entry *pentry = qParent_.down->getQueueEntry(pindex); ex_send_top_private_state & pstate = *((ex_send_top_private_state *) pentry->pstate); SqlBuffer *sqlBuf = NULL; if ((pentry->downState.request == ex_queue::GET_NOMORE) && (pstate.step_ == STARTED_)) { // Am I being asked to refrain from new I/O? if (getGlobals()->castToExExeStmtGlobals()->noNewRequest()) { ExEspStmtGlobals *espGlobals = getGlobals()-> castToExExeStmtGlobals()->castToExEspStmtGlobals(); if (espGlobals) { // Make sure my root (split_bottom) knows to schedule me // when I/O can resume. espGlobals->setSendTopTcbActivated(mySendTopTcbIndex_); } EXSM_TRACE(EXSM_TRACE_CANCEL, "SNDT %p must refrain from new I/O", this); return WORK_OK; } if (cancelSendBuffer == NULL) { if (cancelMessageStream_) if (cancelMessageStream_->sendLimitReached() || cancelMessageStream_->inUseLimitReached()) { EXSM_TRACE(EXSM_TRACE_CANCEL, "SNDT %p stream limits prevent new I/O", this); return WORK_OK; } // cancelMessageStream_ may be NULL, but it's OK // getCancelSendBuffer can establish the stream and // connection_ should be already created. cancelSendBuffer = getCancelSendBuffer(FALSE); if (cancelSendBuffer == NULL) { EXSM_TRACE(EXSM_TRACE_CANCEL, "SNDT %p send buffer not available", this); return WORK_POOL_BLOCKED; } sqlBuf = cancelSendBuffer->get_sql_buffer(); } // Allocate space in buffer for control info (down state). // tupp_descriptor *controlInfoAsTupp = sqlBuf->add_tuple_desc((unsigned short) sizeof(ControlInfo)); // Check that there was sufficient space in buffer. // if (controlInfoAsTupp == NULL) { // // Sufficient space is not available in buffer. // Will cancel more later. Will rely on actOnReceive // to schedule me, after reply from ESP. EXSM_TRACE(EXSM_TRACE_CANCEL, "SNDT %p no room in buffer for ControlInfo", this); break; } else { // // There was space in the send buffer --- copy the current input // row into it and advance to the next input queue entry. // ControlInfo msgControlInfo; // // Copy the down state and flags into first tupp allocated // in the message buffer. // msgControlInfo.getDownState() = pentry->downState; msgControlInfo.getDownState().parentIndex = pindex; msgControlInfo.setIsDataRowPresent(FALSE); msgControlInfo.setIsExtDiagsAreaPresent(FALSE); msgControlInfo.setBufferSequenceNumber(pstate.bufferNumber_); str_cpy_all(controlInfoAsTupp->getTupleAddress(), (char *) &msgControlInfo, sizeof(ControlInfo)); // Now the pentry's pstate.step_ does its transition.... pstate.step_ = CANCELED_AFTER_SENT_; } } // if GET_NOMORE && STARTED_ pindex++; } // while pindex != nextToSendDown_ if (cancelSendBuffer) { SqlBuffer *sqlBuf = cancelSendBuffer->get_sql_buffer(); sqlBuf->drivePack(); EXSM_TRACE(EXSM_TRACE_CANCEL,"SNDT %p SEND cancel %d tupps", this, (int) sqlBuf->getTotalTuppDescs()); cancelMessageStream_->sendRequest(); } else { if (sendTopTdb().getExchangeUsesSM() && pindex == nextToSendDown_) EXSM_TRACE(EXSM_TRACE_CANCEL, "SNDT %p no outstanding entries to cancel", this); } return WORK_OK; } ///////////////////////////////////////////////////////////////////////////// // short ex_send_top_tcb::createConnectionToSendBottom(NABoolean nowaitedCompleted) { short retcode = 0; if (sendTopTdb().getExchangeUsesSM()) retcode = createSMConnection(); else retcode = createIpcGuardianConnection(nowaitedCompleted); return retcode; } short ex_send_top_tcb::createSMConnection() { short retcode = 0; IpcEnvironment *env = getGlobals()->castToExExeStmtGlobals()->getIpcEnvironment(); // The numBufs variable represents the number of pre-allocated // receive buffers. The connection will need N batches of M buffers // where: // N = getNumSendBuffers() // M = getNumRecvBuffers() // // And we add one for cancel replies UInt32 numBufs = (getNumSendBuffers() * getNumRecvBuffers()) + 1; ExMasterStmtGlobals *masterGlobals = getGlobals()->castToExExeStmtGlobals()->castToExMasterStmtGlobals(); connection_ = new (env->getHeap()) SMConnection(env, smTarget_, numBufs, msgStream_->getBufferSize(), this, masterGlobals); EXSM_TRACE(EXSM_TRACE_PROTOCOL,"SNDT %p created conn %p", this, connection_); ex_assert(connection_, "SM connection allocation failed"); SMConnection *smConn = (SMConnection *) connection_->castToSMConnection(); ex_assert(smConn, "Invalid SM connection pointer"); smConn->setDataStream(msgStream_); smConn->setCancelStream(cancelMessageStream_); return retcode; } ///////////////////////////////////////////////////////////////////////////// // short ex_send_top_tcb::createIpcGuardianConnection(NABoolean nowaitedCompleted) { short retcode; IpcEnvironment *env = getGlobals()->castToExExeStmtGlobals()->getIpcEnvironment(); static THREAD_P bool sv_env_multiple_fragments_checked = false; static THREAD_P bool sv_multiple_fragments = true; Lng32 nowaitDepth = 4; if (getStatsEntry() && sendTopTdb().getUseOldStatsNoWaitDepth()) nowaitDepth = 2; if (sendTopState_ == NOT_OPENED)//added { NABoolean espParallelDcOpens; char * espParallelDcOpensEnvvar = getenv("ESP_PARALLEL_DC_OPENS"); if (espParallelDcOpensEnvvar != NULL && *espParallelDcOpensEnvvar == '0') espParallelDcOpens = FALSE; else { // multi fragment esp #ifdef USE_SB_FILE_DYN_THREADS sv_max_parallel_opens = FS_MAX_CONCUR_NOWAIT_OPENS; #else sv_max_parallel_opens = 8; #endif if (espParallelDcOpensEnvvar) { sv_max_parallel_opens = atoi(espParallelDcOpensEnvvar); } espParallelDcOpens = TRUE; } if (!sv_env_multiple_fragments_checked) { char *lv_espMultipleFragmentsEnvvar = getenv("ESP_MULTI_FRAGMENTS"); if ((lv_espMultipleFragmentsEnvvar != NULL) && (*lv_espMultipleFragmentsEnvvar == '0')) { sv_multiple_fragments = false; } sv_env_multiple_fragments_checked = true; } if (sv_multiple_fragments) { if ((env->getNumOpensInProgress() >= sv_max_parallel_opens) && nowaitedCompleted == false) { Int32 lv_err; struct timespec lv_tv; lv_tv.tv_sec = 0; lv_tv.tv_nsec = 100 * 1000; lv_err = nanosleep(&lv_tv, NULL); return 1; } } // Open the bottom ESP by creating a connection to // it. createConnectionToServer() can return NULL if bottomProcId_ // does not refer to a running server. connection_ = bottomProcId_.createConnectionToServer( env, FALSE, // transactions are sent via the control connection nowaitDepth, espParallelDcOpens, ioSubtask_->getScheduledAddr() , TRUE // data connection to ESP ); if (connection_ && connection_->getState() == IpcConnection::OPENING) { if (nowaitedCompleted) { connection_->openPhandle(NULL, TRUE); if (connection_->getState() == IpcConnection::ESTABLISHED) { setStState(OPEN_COMPLETE, __LINE__); return 0; } } else { //connection_->openPhandle(NULL, FALSE); // Temporarily setStState(WAITING_FOR_OPEN_COMPLETION, __LINE__); return 0; } } if (connection_ && connection_->getState() == IpcConnection::ESTABLISHED) { #ifdef NA_LINUX_DISABLE // multi fragment esp experiment setStState(OPEN_COMPLETE, __LINE__); #endif return 0; } } // if (state == NOT_OPENED) else { ex_assert(sendTopState_ == WAITING_FOR_OPEN_COMPLETION, "ex_send_top_tcb::createConnectionToSendBottom was called in an invalid sendTopState_"); } // If the connection is NULL or the connection encountered errors, // add diagnostics to the statement globals diags area. Also set the // TCB's ipcBroken flag and set retcode to indicate an error. if (connection_ == NULL || (connection_ && connection_->getErrorInfo())) { ComDiagsArea* da = getGlobals()->castToExExeStmtGlobals()->getDiagsArea(); // If da is NULL, allocate a new diags area and attach to // statement globals if (da == NULL) { da = ComDiagsArea::allocate(getHeap()); getGlobals()->castToExExeStmtGlobals()->setGlobDiagsArea(da); da->decrRefCount(); } // Two cases to consider // // a. connection_ is NULL. This can happen when the ESP phandle // does not represent a running server. For an extract consumer // query the phandle comes from query text so we report an error // to the application. Otherwise the phandle is managed // internally and should always be valid, so it's a bug if we // come here and we raise an assertion failure. // // b. connection is not NULL and contains error information. Add // the error information to the statement globals diags area. if (connection_ == NULL) { if (sendTopTdb().getExtractConsumerFlag()) { const char *stringForDiags = sendTopTdb().getExtractEsp(); *da << DgSqlCode(-EXE_PARALLEL_EXTRACT_CONNECT_ERROR) << DgString0(stringForDiags); } else { ex_assert(FALSE, "createConnectionToSendBottom failed to connect"); } } else { connection_->populateDiagsArea(da, getHeap()); } setIpcBroken(); retcode = -1; } else { retcode = 0; } return retcode; } ///////////////////////////////////////////////////////////////////////////// // ex_queue_pair ex_send_top_tcb::getParentQueue() const { return qParent_; } ///////////////////////////////////////////////////////////////////////////// // const ex_tcb* ex_send_top_tcb::getChild(Int32 pos) const { ex_assert((pos >= 0), ""); return NULL; } ///////////////////////////////////////////////////////////////////////////// // Int32 ex_send_top_tcb::numChildren() const { return 0; } ExOperStats * ex_send_top_tcb::doAllocateStatsEntry(CollHeap *heap, ComTdb *tdb) { ExOperStats * stat = NULL; if (tdb->getCollectStatsType() == ComTdb::OPERATOR_STATS) { // check to see if entry for this node exists. This could happen if // multuiple send top tcbs are constructed for the same table(like, by // a split top node). stat = getGlobals()->getStatsArea()->get(ExOperStats::EX_OPER_STATS, tdb->getTdbId()); if (stat) { setStatsEntry(stat); stat->incDop(); return NULL; } stat = ex_tcb::doAllocateStatsEntry(heap, tdb); } else { stat = new(heap) ExESPStats(heap, sendTopTdb().getSendBufferSize(), sendTopTdb().getRecvBufferSize(), getChildInstanceNum(), this, tdb); } if (stat) { // Assuming parent Tdb is the one above this Tdb stat->setParentTdbId(tdb->getTdbId()+1); // Set SplitBottom as the left child TdbId stat->setLeftChildTdbId(tdb->getTdbId()-1); } return stat; } ///////////////////////////////////////////////////////////////////////////// // short ex_send_top_tcb::notifyProducerThatWeCanceled() { ExEspStmtGlobals *espGlobals = getGlobals()->castToExExeStmtGlobals()->castToExEspStmtGlobals(); if (espGlobals->noNewRequest()) { // sol 10-090220-9443. after esp receives release work msg, it sets the // no-new-request flag that prevents this esp from propagating any msgs // further down the esp chain. the msg can be any of the following: // // - data request: see checkSend() // - continue msg: see continueRequest() // - cancel msg: see processCancel() // - late cancel msg: see notifyProducerThatWeCanceled() // // Make sure my root (split_bottom) knows to schedule me // when I/O can resume. espGlobals->setSendTopTcbActivated(mySendTopTcbIndex_); return WORK_OK; } if (connection_ == NULL) if (createConnectionToSendBottom(TRUE) != 0) return -1; TupMsgBuffer *tmb = getCancelSendBuffer(TRUE); SqlBuffer *sqlBuf = tmb->get_sql_buffer(); tupp_descriptor *controlInfoAsTupp = sqlBuf->add_tuple_desc((unsigned short) sizeof(ControlInfo)); ControlInfo msgControlInfo; msgControlInfo.getDownState().request = ex_queue::GET_NOMORE; msgControlInfo.setBufferSequenceNumber(9999999); msgControlInfo.getDownState().parentIndex = 9999999; // manage this later msgControlInfo.setIsDataRowPresent(FALSE); msgControlInfo.setIsExtDiagsAreaPresent(FALSE); str_cpy_all(controlInfoAsTupp->getTupleAddress(), (char *) &msgControlInfo, sizeof(ControlInfo)); ex_assert(espGlobals, "Master does not use notifyProducerThatWeCanceled() right now"); // make sure we wait for the late cancel to complete espGlobals->setSendTopTcbLateCancelling(); if (sendTopState_ == NOT_OPENED OR sendTopState_ == WAITING_FOR_OPEN_COMPLETION) setStState(CANCELED_BEFORE_OPENED, __LINE__); EXSM_TRACE(EXSM_TRACE_CANCEL,"SNDT %p SEND late cancel", this); cancelMessageStream_->setLateCancel(); cancelMessageStream_->sendRequest(); return 0; } ///////////////////////////////////////////////////////////////////////////// // TupMsgBuffer * ex_send_top_tcb::getCancelSendBuffer(NABoolean lateCancel) { ex_assert((sendTopState_ != NOT_OPENED AND sendTopState_ != WAITING_FOR_OPEN_COMPLETION) || lateCancel, "Canceling too soon!"); if (!cancelMessageStream_) { IpcMessageObjSize maxBufSize = MAXOF(sendBufferSize_,500); IpcMessageBuffer::alignOffset(maxBufSize); maxBufSize += sizeof(TupMsgBuffer); IpcMessageBuffer::alignOffset(maxBufSize); maxBufSize += MAXOF(sizeof(ExEspCancelReqHeader), sizeof(ExEspLateCancelReqHeader)); IpcMessageBuffer::alignOffset(maxBufSize); cancelMessageStream_ = new(getGlobals()->getSpace()) ExSendTopCancelMessageStream( getGlobals()->castToExExeStmtGlobals(), 1, //sendBufferLimit, 1, //inUseBufferLimit, maxBufSize, this); ex_assert(connection_ != NULL, "Connection not created!"); cancelMessageStream_->addRecipient(connection_); if (sendTopTdb().getExchangeUsesSM()) { SMConnection *smConn = (SMConnection *) connection_->castToSMConnection(); ex_assert(smConn, "Invalid SM connection pointer"); smConn->setCancelStream(cancelMessageStream_); } } else { ex_assert( !cancelMessageStream_->sendLimitReached() && !cancelMessageStream_->inUseLimitReached(), "getCancelSendBuffer called at the wrong time!"); } // construct cancel request header in message, if (lateCancel) { ExEspLateCancelReqHeader *hdr = new(*cancelMessageStream_) ExEspLateCancelReqHeader((NAMemory *) NULL); if (hdr == NULL) return NULL; // a late cancel message may not know the ExFragInstanceHandle yet hdr->key_ = getGlobals()->castToExExeStmtGlobals()->getFragmentKey( sendTopTdb().getChildFragId()); hdr->myInstanceNum_ = getMyInstanceNum(); } else { // include child ExFragInstanceHandle for fast routing ExEspCancelReqHeader *hdr = new(*cancelMessageStream_) ExEspCancelReqHeader((NAMemory *) NULL); if (hdr == NULL) return NULL; hdr->handle_ = childFragHandle_; hdr->myInstanceNum_ = getMyInstanceNum(); } // construct sql buffer(TupMsgBuffer) directly in message to avoid copy Lng32 sqlBufferLen = sendBufferSize_; // The TupMsgBuffer for a late cancel is for only one queue entry and // doesn't have a data record in it. Note that it may be routed through // a non-buffered message stream at the producer ESP (the new incoming // message stream in case we also send an open request). Therefore // we must not send a multi-buffer message, because only buffered message // streams know how to route that. Therefore we keep the buffer length of // the TupMsgBuffer small. Sorry for the arbitrary choice of 500. It // includes a very generous reserve as long as we work with single // cancel requests with no records. if (lateCancel) sqlBufferLen = MAXOF(sqlBufferLen,500); TupMsgBuffer *result = new(*cancelMessageStream_, sqlBufferLen) TupMsgBuffer(sqlBufferLen, TupMsgBuffer::MSG_IN, cancelMessageStream_); if (result == NULL) ABORT("mismatched send top buffer size"); return result; } void ex_send_top_tcb::incReqMsg(Int64 msgBytes) { ExStatisticsArea *statsArea; if ((statsArea = getGlobals()->getStatsArea()) != NULL) statsArea->incReqMsg(msgBytes); } ///////////////////////////////////////////////////////////////////////////// void ex_send_top_tcb::setStState( enum ExSendTopState newState, int linenum) { if (newState != sendTopState_) { if (stTidx_ >= NumSendTopTraceElements) stTidx_ = 0; sendTopState_ = newState; stStateTrace_[stTidx_].stState_ = sendTopState_; stStateTrace_[stTidx_].lineNum_ = linenum; stTidx_++; } } const char *ex_send_top_tcb::getExSendTopStateString(ExSendTopState s) { switch (s) { case INVALID: return "INVALID"; case NOT_OPENED: return "NOT_OPENED"; case WAITING_FOR_OPEN_COMPLETION: return "WAITING_FOR_OPEN_COMPLETION"; case WAITING_FOR_OPEN_REPLY: return "WAITING_FOR_OPEN_REPLY"; case CANCELED_BEFORE_OPENED: return "CANCELED_BEFORE_OPENED"; case OPEN_COMPLETE: return "OPEN_COMPLETE"; case SERVER_SATURATED: return "SERVER_SATURATED"; default: return ComRtGetUnknownString((Int32) s); } } // ----------------------------------------------------------------------- // Methods for class ExSendTopMessageStream // ----------------------------------------------------------------------- ///////////////////////////////////////////////////////////////////////////// // constructor ExSendTopMsgStream::ExSendTopMsgStream(ExExeStmtGlobals* glob, Lng32 sendBufferLimit, Lng32 inUseBufferLimit, IpcMessageObjSize bufferSize, ex_send_top_tcb* sendTopTcb) : IpcClientMsgStream(glob->getIpcEnvironment(), IPC_MSG_SQLESP_DATA_REQUEST, CurrEspRequestMessageVersion, sendBufferLimit, inUseBufferLimit, bufferSize), sendTopTcb_(sendTopTcb) { } /////////////////////////////////////////////////////////////////////////////// // method called upon send complete void ExSendTopMsgStream::actOnSend(IpcConnection* connection) { EXSM_TRACE(EXSM_TRACE_PROTOCOL, "SNDT %p ACTS D s %p c %p", sendTopTcb_, this, connection); if (connection) { // we always use this message with the same connection // ex_assert(connection == sendTopTcb_->connection_, // "A send top message is associated with the wrong connection"); if (getErrorInfo()) { ComDiagsArea* da = sendTopTcb_->getGlobals()-> castToExExeStmtGlobals()->getDiagsArea(); ComDiagsArea* oldDa = da; connection->populateDiagsArea( da, sendTopTcb_->getHeap()); if ((!oldDa) && (da)) { sendTopTcb_->getGlobals()->castToExExeStmtGlobals()-> setGlobDiagsArea(da); da->decrRefCount(); } sendTopTcb_->setIpcBroken(); sendTopTcb_->tickleSchedulerWork(); EXSM_TRACE(EXSM_TRACE_PROTOCOL,"SNDT %p IPC broken", sendTopTcb_); EXSM_TRACE(EXSM_TRACE_PROTOCOL,"SNDT %p tcb scheduled", sendTopTcb_); } else { sendTopTcb_->incReqMsg(connection->getLastSentMsg()->getMessageLength()); } } ExExeStmtGlobals *stmtGlob = sendTopTcb_->getGlobals()->castToExExeStmtGlobals(); stmtGlob->incrementSendTopMsgesOut(); EXSM_TRACE(EXSM_TRACE_PROTOCOL, "SNDT %p ACTS D glob msgs %d", sendTopTcb_, (int) stmtGlob->numSendTopMsgesOut()); } ///////////////////////////////////////////////////////////////////////////// // method called upon receive complete void ExSendTopMsgStream::actOnReceive(IpcConnection* connection) { EXSM_TRACE(EXSM_TRACE_PROTOCOL, "SNDT %p ACTR D s %p c %p", sendTopTcb_, this, connection); if (connection) { // we always use this message with the same connection // ex_assert(connection == sendTopTcb_->connection_, // "A send top message is associated with the wrong connection"); if (getErrorInfo()) { ComDiagsArea* da = sendTopTcb_->getGlobals()-> castToExExeStmtGlobals()->getDiagsArea(); ComDiagsArea* oldDa = da; connection->populateDiagsArea( da, sendTopTcb_->getHeap()); if ((!oldDa) && (da)) { sendTopTcb_->getGlobals()->castToExExeStmtGlobals()-> setGlobDiagsArea(da); da->decrRefCount(); } sendTopTcb_->setIpcBroken(); } } ExExeStmtGlobals *stmtGlob = sendTopTcb_->getGlobals()->castToExExeStmtGlobals(); if (getSMContinueProtocol()) { if (getSMBatchIsComplete()) stmtGlob->decrementSendTopMsgesOut(); } else { stmtGlob->decrementSendTopMsgesOut(); } EXSM_TRACE(EXSM_TRACE_PROTOCOL, "SNDT %p ACTR D glob msgs %d rp %d", sendTopTcb_, (int) stmtGlob->numSendTopMsgesOut(), (int) numOfResponsesPending()); // wake up the work procedure sendTopTcb_->tickleSchedulerWork(TRUE); EXSM_TRACE(EXSM_TRACE_PROTOCOL,"SNDT %p tcb scheduled", sendTopTcb_); } // ----------------------------------------------------------------------- // Methods for class ExSendTopCancelMessageStream // ----------------------------------------------------------------------- ExSendTopCancelMessageStream::ExSendTopCancelMessageStream( ExExeStmtGlobals *glob, Lng32 sendBufferLimit, Lng32 inUseBufferLimit, IpcMessageObjSize bufferSize, ex_send_top_tcb *sendTopTcb) : IpcClientMsgStream(glob->getIpcEnvironment(), IPC_MSG_SQLESP_CANCEL_REQUEST, CurrEspRequestMessageVersion, sendBufferLimit, inUseBufferLimit, bufferSize), sendTopTcb_(sendTopTcb), lateCancel_(FALSE) {} ///////////////////////////////////////////////////////////////////////////// // method called upon send complete void ExSendTopCancelMessageStream::actOnSend(IpcConnection *connection) { EXSM_TRACE(EXSM_TRACE_PROTOCOL, "SNDT %p ACTS C %p c %p", sendTopTcb_, this, connection); if (connection) { if (getErrorInfo()) { ComDiagsArea* da = sendTopTcb_->getGlobals()-> castToExExeStmtGlobals()->getDiagsArea(); ComDiagsArea* oldDa = da; connection->populateDiagsArea( da, sendTopTcb_->getHeap()); if ((!oldDa) && (da)) { sendTopTcb_->getGlobals()->castToExExeStmtGlobals()-> setGlobDiagsArea(da); da->decrRefCount(); } sendTopTcb_->setIpcBroken(); sendTopTcb_->tickleSchedulerCancel(); EXSM_TRACE(EXSM_TRACE_PROTOCOL,"SNDT %p IPC broken", sendTopTcb_); EXSM_TRACE(EXSM_TRACE_PROTOCOL,"SNDT %p tcb scheduled", sendTopTcb_); } } ExExeStmtGlobals *stmtGlob = sendTopTcb_->getGlobals()->castToExExeStmtGlobals(); stmtGlob->incrementCancelMsgesOut(); EXSM_TRACE(EXSM_TRACE_PROTOCOL, "SNDT %p ACTS C glob cancel %d", sendTopTcb_, (int) stmtGlob->numCancelMsgesOut()); } void ExSendTopCancelMessageStream::actOnReceive(IpcConnection *connection) { EXSM_TRACE(EXSM_TRACE_PROTOCOL, "SNDT %p ACTR %s %p c %p", sendTopTcb_, (lateCancel_ ? "LC" : "C"), this, connection); if (connection) { if (getErrorInfo()) { ComDiagsArea *da = sendTopTcb_->getGlobals()-> castToExExeStmtGlobals()->getDiagsArea(); ComDiagsArea *oldDa = da; connection->populateDiagsArea( da, sendTopTcb_->getHeap()); if ((!oldDa) && (da)) { sendTopTcb_->getGlobals()->castToExExeStmtGlobals()-> setGlobDiagsArea(da); da->decrRefCount(); } sendTopTcb_->setIpcBroken(); } } ExExeStmtGlobals *stmtGlob = sendTopTcb_->getGlobals()->castToExExeStmtGlobals(); stmtGlob->decrementCancelMsgesOut(); if (lateCancel_) { // do the bookkeeping here and let the cancel method clean // up the message stream lateCancel_ = FALSE; ExEspStmtGlobals *espGlobals = sendTopTcb_->getGlobals()-> castToExExeStmtGlobals()->castToExEspStmtGlobals(); if (espGlobals) espGlobals->resetSendTopTcbLateCancelling(); } EXSM_TRACE(EXSM_TRACE_PROTOCOL, "SNDT %p ACTR %s glob cancel %d rp %d", sendTopTcb_, (lateCancel_ ? "LC" : "C"), (int) stmtGlob->numCancelMsgesOut(), (int) numOfResponsesPending()); // wake up the cancel procedure. It might be awaiting this // receive so it can send somemore. sendTopTcb_->tickleSchedulerCancel(); EXSM_TRACE(EXSM_TRACE_PROTOCOL,"SNDT %p tcb scheduled", sendTopTcb_); } /////////////////////////////////////////////// // class ex_send_top_private_state /////////////////////////////////////////////// ex_send_top_private_state::ex_send_top_private_state( const ex_send_top_tcb * /*tcb*/) { step_ = ex_send_top_tcb::NOT_STARTED_; } ex_send_top_private_state::~ex_send_top_private_state() { } ex_tcb_private_state * ex_send_top_private_state::allocate_new( const ex_tcb *tcb) { return new(((ex_tcb *)tcb)->getSpace()) ex_send_top_private_state((ex_send_top_tcb *) tcb); }
33.7678
105
0.619275
[ "object" ]
d6a540c09fae8b6aacbc81bed90713eeda4efc42
18,739
cpp
C++
glr/obj.cpp
jackm97/GLR
46e29519021ae25699bade7d957cf21335ca8bde
[ "MIT" ]
null
null
null
glr/obj.cpp
jackm97/GLR
46e29519021ae25699bade7d957cf21335ca8bde
[ "MIT" ]
null
null
null
glr/obj.cpp
jackm97/GLR
46e29519021ae25699bade7d957cf21335ca8bde
[ "MIT" ]
null
null
null
#include <glr/obj.h> #ifdef GLRENDER_STATIC #include <glad/glad.h> #endif namespace glr { GLRENDER_INLINE OBJ::OBJ(std::string obj_path, std::string base_dir, std::string obj_name, bool calc_normals, bool flip_normals) { loadFromObj(obj_path, base_dir, obj_name, calc_normals, flip_normals); } GLRENDER_INLINE OBJ::OBJ(const OBJ &src) { *this = src; } GLRENDER_INLINE void OBJ::operator=(const OBJ &src) { loadFromObj(src.obj_path_, src.base_dir_, src.name_, src.is_calc_normals_, src.is_flip_normals_); this->shader_list_ = src.shader_list_; this->texture_list_ = src.texture_list_; this->textures_assigned_ = src.textures_assigned_; this->use_vert_colors_ = src.use_vert_colors_; this->attrib_ = src.attrib_; this->shapes_ = src.shapes_; this->materials_ = src.materials_; initGLBuffers(src.is_calc_normals_, src.is_calc_normals_); } GLRENDER_INLINE void OBJ::loadFromObj(std::string obj_path, std::string base_dir, std::string obj_name, bool calc_normals, bool flip_normals) { this->name_ = obj_name; this->obj_path_ = obj_path; if (base_dir[base_dir.length() - 1] != '/') base_dir += "/"; this->base_dir_ = base_dir; std::string warn; std::string err; bool ret = tinyobj::LoadObj(&this->attrib_, &this->shapes_, &this->materials_, &warn, &err, obj_path.c_str(), base_dir.c_str()); if (this->materials_.size() == 0) { tinyobj::material_t default_mat; default_mat.name = "default"; default_mat.ambient[0] = 1; default_mat.ambient[1] = 1; default_mat.ambient[2] = 1; default_mat.diffuse[0] = 1; default_mat.diffuse[1] = 1; default_mat.diffuse[2] = 1; default_mat.specular[0] = 1; default_mat.specular[1] = 1; default_mat.specular[2] = 1; default_mat.emission[0] = 0; default_mat.emission[1] = 0; default_mat.emission[2] = 0; default_mat.shininess = 1000; materials_.push_back(default_mat); for (int s = 0; s < shapes_.size(); s++) { shapes_[s].mesh.material_ids.clear(); shapes_[s].mesh.material_ids.push_back(0); } } if (!warn.empty()) { std::cout << warn << std::endl; } if (!err.empty()) { std::cerr << err << std::endl; } if (!ret) { exit(1); } shader_list_.clear(); texture_list_.clear(); textures_assigned_.clear(); for (int s = 0; s < shapes_.size(); s++) { shader_list_.push_back(NULL); texture_list_.push_back(NULL); textures_assigned_.push_back(false); } this->no_uv_map_.resize(this->shapes_.size()); initGLBuffers(calc_normals, flip_normals); calcCenters(); aabb_tree_.assignObj(this); if (aabb_tree_enabled_) aabb_tree_.calcTree(); obb_tree_.assignObj(this); if (obb_tree_enabled_) obb_tree_.calcTree(); this->use_vert_colors_.clear(); for (int s = 0; s < shapes_.size(); s++) { this->use_vert_colors_.push_back(false); } } GLRENDER_INLINE void OBJ::setVertColor(float color[3]) { for (int s = 0; s < shapes_.size(); s++) setVertColorForShape(shapes_[s].name, color); } GLRENDER_INLINE void OBJ::setVertColorForShape(std::string shapeName, float color[3]) { tinyobj::attrib_t &attrib = this->attrib_; int s; for (s = 0; s < this->shapes_.size(); s++) if (shapeName == this->shapes_[s].name) break; // loop over faces size_t index_offset = 0; for (size_t f = 0; f < this->shapes_[s].mesh.num_face_vertices.size(); f++) { if (this->shapes_[s].mesh.num_face_vertices[f] != 3) { index_offset += this->shapes_[s].mesh.num_face_vertices[f]; continue; } // Loop over vertices in the face. for (size_t v = 0; v < 3; v++) { tinyobj::index_t idx = this->shapes_[s].mesh.indices[index_offset + v]; attrib.colors[3 * idx.vertex_index + 0] = color[0]; attrib.colors[3 * idx.vertex_index + 1] = color[1]; attrib.colors[3 * idx.vertex_index + 2] = color[2]; } index_offset += 3; } initGLBuffers(is_calc_normals_, is_flip_normals_); } GLRENDER_INLINE void OBJ::useVertColor(bool use) { for (int s = 0; s < shapes_.size(); s++) use_vert_colors_[s] = use; } GLRENDER_INLINE void OBJ::useVertColorForShape(std::string shape_name, bool use) { for (int s = 0; s < shapes_.size(); s++) if (shapes_[s].name == shape_name) use_vert_colors_[s] = use; } GLRENDER_INLINE void OBJ::setShader(shader *shader_ptr) { for (int s = 0; s < shapes_.size(); s++) shader_list_[s] = shader_ptr; } GLRENDER_INLINE void OBJ::setShaderForShape(std::string shape_name, shader *shader_ptr) { for (int s = 0; s < shapes_.size(); s++) if (shapes_[s].name == shape_name) shader_list_[s] = shader_ptr; } GLRENDER_INLINE void OBJ::setTexture(texture *texture_ptr) { for (int s = 0; s < shapes_.size(); s++) { texture_list_[s] = texture_ptr; if (texture_ptr != NULL) textures_assigned_[s] = true; else textures_assigned_[s] = false; } } GLRENDER_INLINE void OBJ::setTextureForShape(std::string shape_name, texture *texture_ptr) { for (int s = 0; s < shapes_.size(); s++) if (shapes_[s].name == shape_name) { texture_list_[s] = texture_ptr; if (texture_ptr != NULL) textures_assigned_[s] = true; else textures_assigned_[s] = false; } } GLRENDER_INLINE glm::mat4 OBJ::modelMatrix() { return model_matrix_; } GLRENDER_INLINE void OBJ::modelMatrix(glm::mat4 mat) { model_matrix_ = mat; } GLRENDER_INLINE void OBJ::enableAABB(bool use) { if (use) { enableOBB(false); displayOBB(false); aabb_tree_.calcTree(); } else aabb_tree_.clearTree(); aabb_tree_enabled_ = use; } GLRENDER_INLINE void OBJ::displayAABB(bool use) { if (use && aabb_tree_enabled_) { display_aabb_tree_ = use; aabb_tree_.initGLBuffers(); } else display_aabb_tree_ = false; } GLRENDER_INLINE void OBJ::enableOBB(bool use) { if (use) { enableAABB(false); displayAABB(false); obb_tree_.calcTree(); } else obb_tree_.clearTree(); obb_tree_enabled_ = use; } GLRENDER_INLINE void OBJ::displayOBB(bool use) { if (use && obb_tree_enabled_) { display_obb_tree_ = use; obb_tree_.initGLBuffers(); } else display_obb_tree_ = false; } GLRENDER_INLINE bool OBJ::isIntersect(OBJ* other_obj) { bool is_intersect = false; if (aabb_tree_enabled_) { is_intersect = this->aabb_tree_.intersectTest( &(other_obj->aabb_tree_) ); this->displayAABB(this->display_aabb_tree_); other_obj->displayAABB(other_obj->display_aabb_tree_); } else if (obb_tree_enabled_) { is_intersect = this->obb_tree_.intersectTest( &(other_obj->obb_tree_) ); this->displayOBB(this->display_obb_tree_); other_obj->displayOBB(other_obj->display_obb_tree_); } return is_intersect; } GLRENDER_INLINE void OBJ::draw() { int shape_num = shapes_.size(); for (int s = 0; s < shape_num; s++) { // skip meshes with no faces (i.e. a point) if (shapes_[s].mesh.num_face_vertices.size() == 0) continue; //enable shader shader_list_[s]->use(); // enable texture if there is one and if a uvmap exists if (texture_list_[s] != NULL) texture_list_[s]->bind(); int texture_assigned = (!textures_assigned_[s]) ? 0 : 1; // if the user tried to assign a texture to a shape // with no UVMap, "empty" texture is assigned // if they texture map in a shader, they will // get white if (this->no_uv_map_[s]) texture_assigned = 0; glUniform1i(glGetUniformLocation(shader_list_[s]->ID_, "textureAssigned"), texture_assigned); // enable vertex shading if specified int useVertColor = (this->use_vert_colors_[s]) ? 1 : 0; glUniform1i(glGetUniformLocation(shader_list_[s]->ID_, "useVertColor"), useVertColor); // set up uniforms tinyobj::material_t mat = materials_[shapes_[s].mesh.material_ids[0]]; setUniforms(s, mat, shader_list_[s]); // draw glBindVertexArray(vao_list_[s]); glDrawArrays(GL_TRIANGLES, 0, 3 * shapes_[s].mesh.num_face_vertices.size()); glBindVertexArray(0); } if (display_aabb_tree_) { AABBTree::aabb_shader_.use(); aabb_tree_.draw(); } else if (display_obb_tree_) { OBBTree::obb_shader_.use(); obb_tree_.draw(); } } GLRENDER_INLINE void OBJ::glRelease() { if (!is_loaded_into_gl_) return; glDeleteBuffers(this->vbo_list_.size(), this->vbo_list_.data()); glDeleteVertexArrays(this->vao_list_.size(), this->vao_list_.data()); this->vao_list_.clear(); this->vbo_list_.clear(); is_loaded_into_gl_ = false; } GLRENDER_INLINE OBJ::~OBJ() { glRelease(); } GLRENDER_INLINE void OBJ::setUniforms(unsigned int shape_idx, tinyobj::material_t &mat, shader *shader_ptr) { // model matrix int u_location = glGetUniformLocation(shader_ptr->ID_, "m"); glUniformMatrix4fv(u_location, 1, GL_FALSE, glm::value_ptr(this->model_matrix_)); // material info shader_ptr->setVec3("Ka", mat.ambient); shader_ptr->setVec3("Kd", mat.diffuse); shader_ptr->setVec3("Ks", mat.specular); shader_ptr->setVec3("Ke", mat.emission); shader_ptr->setFloat("Ns", mat.shininess); // model matrix if (display_aabb_tree_) { shader* aabb_shader_ptr = &AABBTree::aabb_shader_; aabb_shader_ptr->use(); int uLocation = glGetUniformLocation(aabb_shader_ptr->ID_, "m"); glUniformMatrix4fv(uLocation, 1, GL_FALSE, glm::value_ptr(model_matrix_)); } else if (display_obb_tree_) { shader* obb_shader_ptr = &OBBTree::obb_shader_; obb_shader_ptr->use(); int uLocation = glGetUniformLocation(obb_shader_ptr->ID_, "m"); glUniformMatrix4fv(uLocation, 1, GL_FALSE, glm::value_ptr(model_matrix_)); } shader_ptr->use(); } GLRENDER_INLINE void OBJ::initGLBuffers(bool calc_normals, bool flip_normals) { this->is_calc_normals_ = calc_normals; this->is_flip_normals_ = flip_normals; if (this->is_loaded_into_gl_) this->glRelease(); std::string baseDir = this->base_dir_; int shape_num = shapes_.size(); std::vector<float> vertex_data; vao_list_.clear(); vao_list_.resize(shape_num); vbo_list_.clear(); unsigned int VBO; // generate vertex arrays glGenVertexArrays(shape_num, vao_list_.data()); // loop over shapes size_t v_count = 0; for (int s = 0; s < shape_num; s++) { vertex_data.clear(); v_count = 0; // loop over faces size_t index_offset = 0; for (size_t f = 0; f < shapes_[s].mesh.num_face_vertices.size(); f++) { if (shapes_[s].mesh.num_face_vertices[f] != 3) { index_offset += shapes_[s].mesh.num_face_vertices[f]; continue; } // Loop over vertices in the face. for (size_t v = 0; v < 3; v++) { // access to vertex tinyobj::index_t idx = shapes_[s].mesh.indices[index_offset + v]; tinyobj::real_t vx = attrib_.vertices[3 * idx.vertex_index + 0]; tinyobj::real_t vy = attrib_.vertices[3 * idx.vertex_index + 1]; tinyobj::real_t vz = attrib_.vertices[3 * idx.vertex_index + 2]; tinyobj::real_t nx; tinyobj::real_t ny; tinyobj::real_t nz; if (idx.normal_index != -1) { nx = ((int)flip_normals * -2 + 1) * attrib_.normals[3 * idx.normal_index + 0]; ny = ((int)flip_normals * -2 + 1) * attrib_.normals[3 * idx.normal_index + 1]; nz = ((int)flip_normals * -2 + 1) * attrib_.normals[3 * idx.normal_index + 2]; } else { is_calc_normals_ = true; calc_normals = true; } tinyobj::real_t tx; tinyobj::real_t ty; if (idx.texcoord_index != -1) { tx = attrib_.texcoords[2 * idx.texcoord_index + 0]; ty = attrib_.texcoords[2 * idx.texcoord_index + 1]; } else { tx = 0; ty = 0; this->no_uv_map_[s] = true; } // Optional: vertex colors tinyobj::real_t r = attrib_.colors[3 * idx.vertex_index + 0]; tinyobj::real_t g = attrib_.colors[3 * idx.vertex_index + 1]; tinyobj::real_t b = attrib_.colors[3 * idx.vertex_index + 2]; vertex_data.push_back(vx); vertex_data.push_back(vy); vertex_data.push_back(vz); vertex_data.push_back(nx); vertex_data.push_back(ny); vertex_data.push_back(nz); vertex_data.push_back(r); vertex_data.push_back(g); vertex_data.push_back(b); vertex_data.push_back(tx); vertex_data.push_back(ty); v_count++; } if (calc_normals) { glm::vec3 v3(vertex_data[11 * (v_count - 3) + 0], vertex_data[11 * (v_count - 3) + 1], vertex_data[11 * (v_count - 3) + 2]); glm::vec3 v2(vertex_data[11 * (v_count - 2) + 0], vertex_data[11 * (v_count - 2) + 1], vertex_data[11 * (v_count - 2) + 2]); glm::vec3 v1(vertex_data[11 * (v_count - 1) + 0], vertex_data[11 * (v_count - 1) + 1], vertex_data[11 * (v_count - 1) + 2]); glm::vec3 v12 = v2 - v1; glm::vec3 v13 = v3 - v2; glm::vec3 n = glm::normalize(glm::cross(v13, v12)); n *= ((int)flip_normals * -2 + 1); (vertex_data[11 * (v_count - 3) + 3 + 0]) = n.x; (vertex_data[11 * (v_count - 3) + 3 + 1]) = n.y; (vertex_data[11 * (v_count - 3) + 3 + 2]) = n.z; (vertex_data[11 * (v_count - 2) + 3 + 0]) = n.x; (vertex_data[11 * (v_count - 2) + 3 + 1]) = n.y; (vertex_data[11 * (v_count - 2) + 3 + 2]) = n.z; (vertex_data[11 * (v_count - 1) + 3 + 0]) = n.x; (vertex_data[11 * (v_count - 1) + 3 + 1]) = n.y; (vertex_data[11 * (v_count - 1) + 3 + 2]) = n.z; } index_offset += 3; } // this->shapeCenters.push_back(getShapeCenter(obj, s)); glBindVertexArray(vao_list_[s]); glGenBuffers(1, &VBO); this->vbo_list_.push_back(VBO); glBindBuffer(GL_ARRAY_BUFFER, VBO); glBufferData(GL_ARRAY_BUFFER, sizeof(float) * vertex_data.size(), vertex_data.data(), GL_DYNAMIC_DRAW); // position attribute glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 11 * sizeof(float), (void *)0); glEnableVertexAttribArray(0); // normal attribute glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 11 * sizeof(float), (void *)(3 * sizeof(float))); glEnableVertexAttribArray(1); // color attribute glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, 11 * sizeof(float), (void *)(6 * sizeof(float))); glEnableVertexAttribArray(2); // uv coord attribute glVertexAttribPointer(3, 2, GL_FLOAT, GL_FALSE, 11 * sizeof(float), (void *)(9 * sizeof(float))); glEnableVertexAttribArray(3); glBindVertexArray(0); } this->is_loaded_into_gl_ = true; } GLRENDER_INLINE void OBJ::calcCenters() { float x_bounds[2]; float y_bounds[2]; float z_bounds[2]; x_bounds[0] = attrib_.vertices[0]; x_bounds[1] = attrib_.vertices[0]; y_bounds[0] = attrib_.vertices[1]; y_bounds[1] = attrib_.vertices[1]; z_bounds[0] = attrib_.vertices[2]; z_bounds[1] = attrib_.vertices[2]; shape_centers_.clear(); shape_radii_.clear(); for (int s = 0; s < shapes_.size(); s++) { float x_bounds_shape[2]; float y_bounds_shape[2]; float z_bounds_shape[2]; tinyobj::index_t idx = shapes_[s].mesh.indices[0]; tinyobj::real_t vx = attrib_.vertices[3 * idx.vertex_index + 0]; tinyobj::real_t vy = attrib_.vertices[3 * idx.vertex_index + 1]; tinyobj::real_t vz = attrib_.vertices[3 * idx.vertex_index + 2]; x_bounds_shape[0] = vx; x_bounds_shape[1] = vx; y_bounds_shape[0] = vy; y_bounds_shape[1] = vy; z_bounds_shape[0] = vz; z_bounds_shape[1] = vz; // loop over faces size_t index_offset = 0; for (size_t f = 0; f < shapes_[s].mesh.num_face_vertices.size(); f++) { if (shapes_[s].mesh.num_face_vertices[f] != 3) { index_offset += shapes_[s].mesh.num_face_vertices[f]; continue; } // Loop over vertices in the face. for (size_t v = 0; v < 3; v++) { // access to vertex idx = shapes_[s].mesh.indices[index_offset + v]; vx = attrib_.vertices[3 * idx.vertex_index + 0]; vy = attrib_.vertices[3 * idx.vertex_index + 1]; vz = attrib_.vertices[3 * idx.vertex_index + 2]; if (vx < x_bounds_shape[0]) x_bounds_shape[0] = vx; if (vx > x_bounds_shape[1]) x_bounds_shape[1] = vx; if (vy < y_bounds_shape[0]) y_bounds_shape[0] = vy; if (vy > y_bounds_shape[1]) y_bounds_shape[1] = vy; if (vz < z_bounds_shape[0]) z_bounds_shape[0] = vz; if (vz > z_bounds_shape[1]) z_bounds_shape[1] = vz; if (vx < x_bounds[0]) x_bounds[0] = vx; if (vx > x_bounds[1]) x_bounds[1] = vx; if (vy < y_bounds[0]) y_bounds[0] = vy; if (vy > y_bounds[1]) y_bounds[1] = vy; if (vz < z_bounds[0]) z_bounds[0] = vz; if (vz > z_bounds[1]) z_bounds[1] = vz; } index_offset += 3; } glm::vec3 shape_center; shape_center.x = (x_bounds_shape[0] + x_bounds_shape[1]) / 2; shape_center.y = (y_bounds_shape[0] + y_bounds_shape[1]) / 2; shape_center.z = (z_bounds_shape[0] + z_bounds_shape[1]) / 2; shape_centers_.push_back(shape_center); index_offset = 0; float radius = 0; for (size_t f = 0; f < shapes_[s].mesh.num_face_vertices.size(); f++) { if (shapes_[s].mesh.num_face_vertices[f] != 3) { index_offset += shapes_[s].mesh.num_face_vertices[f]; continue; } // Loop over vertices in the face. for (size_t v = 0; v < 3; v++) { // access to vertex idx = shapes_[s].mesh.indices[index_offset + v]; vx = attrib_.vertices[3 * idx.vertex_index + 0]; vy = attrib_.vertices[3 * idx.vertex_index + 1]; vz = attrib_.vertices[3 * idx.vertex_index + 2]; } index_offset += 3; glm::vec3 v = glm::vec3(vx, vy, vz); float tmp = glm::length(v - shape_center); if (tmp > radius) radius = tmp; } shape_radii_.push_back(radius); } center_.x = (x_bounds[0] + x_bounds[1]) / 2; center_.y = (y_bounds[0] + y_bounds[1]) / 2; center_.z = (z_bounds[0] + z_bounds[1]) / 2; radius_ = 0; for (int s = 0; s < shapes_.size(); s++) { tinyobj::index_t idx; tinyobj::real_t vx; tinyobj::real_t vy; tinyobj::real_t vz; // loop over faces size_t index_offset = 0; for (size_t f = 0; f < shapes_[s].mesh.num_face_vertices.size(); f++) { if (shapes_[s].mesh.num_face_vertices[f] != 3) { index_offset += shapes_[s].mesh.num_face_vertices[f]; continue; } // Loop over vertices in the face. for (size_t v = 0; v < 3; v++) { // access to vertex idx = shapes_[s].mesh.indices[index_offset + v]; vx = attrib_.vertices[3 * idx.vertex_index + 0]; vy = attrib_.vertices[3 * idx.vertex_index + 1]; vz = attrib_.vertices[3 * idx.vertex_index + 2]; } index_offset += 3; glm::vec3 v = glm::vec3(vx, vy, vz); float tmp = glm::length(v - center_); if (tmp > radius_) radius_ = tmp; } } } } // namespace glr
26.392958
142
0.64123
[ "mesh", "shape", "vector", "model" ]
d6a81d52337e8952b292d3d43f69408d011c135b
29,641
cpp
C++
enduser/speech/sapi/cpl/ttsdlg.cpp
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
enduser/speech/sapi/cpl/ttsdlg.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
enduser/speech/sapi/cpl/ttsdlg.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
#include "stdafx.h" #include "resource.h" #include <sapi.h> #include <string.h> #include "TTSDlg.h" #include "audiodlg.h" #include <spddkhlp.h> #include "helpresource.h" #include "srdlg.h" #include "richedit.h" #include <SPCollec.h> #include "SAPIINT.h" #include "SpATL.h" #include "SpAutoHandle.h" #include "SpAutoMutex.h" #include "SpAutoEvent.h" #include "spvoice.h" #include <richedit.h> #include <richole.h> #include "tom.h" static DWORD aKeywordIds[] = { // Control ID // Help Context ID IDC_COMBO_VOICES, IDH_LIST_TTS, IDC_TTS_ADV, IDH_TTS_ADV, IDC_OUTPUT_SETTINGS, IDH_OUTPUT_SETTINGS, IDC_SLIDER_SPEED, IDH_SLIDER_SPEED, IDC_EDIT_SPEAK, IDH_EDIT_SPEAK, IDC_SPEAK, IDH_SPEAK, IDC_TTS_ICON, IDH_NOHELP, IDC_DIRECTIONS, IDH_NOHELP, IDC_TTS_CAP, IDH_NOHELP, IDC_SLOW, IDH_NOHELP, IDC_NORMAL, IDH_NOHELP, IDC_FAST, IDH_NOHELP, IDC_GROUP_VOICESPEED, IDH_NOHELP, IDC_GROUP_PREVIEWVOICE, IDH_NOHELP, 0, 0 }; // Address of the TrackBar's WNDPROC WNDPROC g_TrackBarWindowProc; // Our own internal TrackBar WNDPROC used to intercept and process VK_UP and VK_DOWN messages LRESULT CALLBACK MyTrackBarWindowProc( HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam ); /***************************************************************************** * TTSDlgProc * *------------* * Description: * DLGPROC for the TTS ****************************************************************** MIKEAR ***/ INT_PTR CALLBACK TTSDlgProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { SPDBG_FUNC( "TTSDlgProc" ); USES_CONVERSION; switch (uMsg) { case WM_INITDIALOG: { g_pTTSDlg->OnInitDialog(hWnd); break; } case WM_DESTROY: { g_pTTSDlg->OnDestroy(); break; } // Handle the context sensitive help case WM_CONTEXTMENU: { WinHelp((HWND) wParam, CPL_HELPFILE, HELP_CONTEXTMENU, (DWORD_PTR)(LPSTR) aKeywordIds); break; } case WM_HELP: { WinHelp((HWND)((LPHELPINFO) lParam)->hItemHandle, CPL_HELPFILE, HELP_WM_HELP,(DWORD_PTR)(LPSTR) aKeywordIds); break; } case WM_HSCROLL: { g_pTTSDlg->ChangeSpeed(); break; } case WM_NOTIFY: switch (((NMHDR*)lParam)->code) { case PSN_APPLY: { g_pTTSDlg->OnApply(); break; } case PSN_KILLACTIVE: { // if the voice is speaking, stop it before switching tabs if (g_pTTSDlg->m_bIsSpeaking) { g_pTTSDlg->Speak(); } break; } case PSN_QUERYCANCEL: // user clicks the Cancel button { if ( g_pSRDlg ) { g_pSRDlg->OnCancel(); } break; } } break; case WM_COMMAND: switch ( LOWORD(wParam) ) { case IDC_COMBO_VOICES: { if ( CBN_SELCHANGE == HIWORD(wParam) ) { HRESULT hr = g_pTTSDlg->DefaultVoiceChange(false); if ( SUCCEEDED( hr ) ) { g_pTTSDlg->Speak(); } } break; } case IDC_OUTPUT_SETTINGS: { // if it's speaking make it stop g_pTTSDlg->StopSpeak(); ::SetFocus(GetDlgItem(g_pTTSDlg->m_hDlg, IDC_OUTPUT_SETTINGS)); // The m_pAudioDlg will be non-NULL only if the audio dialog // has been previously brough up. // Otherwise, we need a newly-initialized one if ( !g_pTTSDlg->m_pAudioDlg ) { g_pTTSDlg->m_pAudioDlg = new CAudioDlg(eOUTPUT ); } if (g_pTTSDlg->m_pAudioDlg != NULL) { ::DialogBoxParam( _Module.GetResourceInstance(), MAKEINTRESOURCE( IDD_AUDIO_DEFAULT ), hWnd, AudioDlgProc, (LPARAM) g_pTTSDlg->m_pAudioDlg ); if ( g_pTTSDlg->m_pAudioDlg->IsAudioDeviceChangedSinceLastTime() ) { // Warn the user that he needs to apply the changes WCHAR szWarning[MAX_LOADSTRING]; szWarning[0] = 0; LoadString( _Module.GetResourceInstance(), IDS_AUDIOOUT_CHANGE_WARNING, szWarning, MAX_LOADSTRING); MessageBox( g_pTTSDlg->GetHDlg(), szWarning, g_pTTSDlg->m_szCaption, MB_ICONWARNING | g_dwIsRTLLayout ); } } g_pTTSDlg->KickCPLUI(); break; } case IDC_EDIT_SPEAK: { if (HIWORD(wParam) == EN_CHANGE) // user is changing text { g_pTTSDlg->SetEditModified(true); } break; } case IDC_SPEAK: { g_pTTSDlg->Speak(); break; } case IDC_TTS_ADV: { // convert the title of the window to wide chars CSpDynamicString dstrTitle; WCHAR szTitle[256]; szTitle[0] = '\0'; LoadString(_Module.GetResourceInstance(), IDS_ENGINE_SETTINGS, szTitle, sp_countof(szTitle)); dstrTitle = szTitle; HRESULT hr = g_pTTSDlg->m_cpCurVoiceToken->DisplayUI( hWnd, dstrTitle, SPDUI_EngineProperties, NULL, 0, NULL ); if ( FAILED( hr ) ) { WCHAR szError[ MAX_LOADSTRING ]; ::LoadString( _Module.GetResourceInstance(), IDS_TTSUI_ERROR, szError, sp_countof( szError ) ); ::MessageBox( hWnd, szError, g_pTTSDlg->m_szCaption, MB_ICONEXCLAMATION | g_dwIsRTLLayout ); ::EnableWindow( ::GetDlgItem( hWnd, IDC_TTS_ADV ), FALSE ); } break; } } break; } return FALSE; } /* TTSDlgProc */ /***************************************************************************** * MyTrackBarWindowProc * *------------* * Description: * This is our own privately sub-classed WNDPROC for the rate TrackBar. We * tell the TTS dialog to use this one so we can pre-process the VK_UP and * VK_DOWN messages before the TrackBar's WNDPROC "incorrectly" handles them * on it's own. All other messages we just pass through to the TrackBar's * WNDPROC. ****************************************************************** Leonro ***/ LRESULT CALLBACK MyTrackBarWindowProc( HWND hwnd, // handle to window UINT uMsg, // message identifier WPARAM wParam, // first message parameter LPARAM lParam // second message parameter ) { switch( uMsg ) { case WM_KEYDOWN: case WM_KEYUP: if( wParam == VK_UP ) { wParam = VK_RIGHT; } else if( wParam == VK_DOWN ) { wParam = VK_LEFT; } break; } return CallWindowProc( g_TrackBarWindowProc, hwnd, uMsg, wParam, lParam ); } /***************************************************************************** * CTTSDlg::SetEditModified( bool fModify ) * *-----------------------* * Description: * Access method for m_fTextModified ****************************************************************** BRENTMID ***/ void CTTSDlg::SetEditModified( bool fModify ) { m_fTextModified = fModify; } /***************************************************************************** * CTTSDlg::OnInitDialog * *-----------------------* * Description: * Dialog Initialization ****************************************************************** BECKYW ***/ void CTTSDlg::OnInitDialog(HWND hWnd) { USES_CONVERSION; SPDBG_FUNC( "CTTSDlg::OnInitDialog" ); SPDBG_ASSERT(IsWindow(hWnd)); m_hDlg = hWnd; // Put text on the speak button ChangeSpeakButton(); // This is to be the caption for error messages m_szCaption[0] = 0; ::LoadString( _Module.GetResourceInstance(), IDS_CAPTION, m_szCaption, sp_countof( m_szCaption ) ); // Initialize the TTS personality list InitTTSList( hWnd ); // Set the range on the slider HWND hSlider = ::GetDlgItem( hWnd, IDC_SLIDER_SPEED ); ::SendMessage( hSlider, TBM_SETRANGE, true, MAKELONG( VOICE_MIN_SPEED, VOICE_MAX_SPEED ) ); // Retrieve address of the TrackBar's WNDPROC so we can sub-class it and intercept // and process the VK_UP and VK_DOWN messages before it handle's them on it's // own "incorrectly" g_TrackBarWindowProc = (WNDPROC)GetWindowLongPtr( hSlider, GWLP_WNDPROC ); // Set the WNDPROC of the TrackBar to MyTrackBarWindowProc SetWindowLongPtr( hSlider, GWLP_WNDPROC, (LONG_PTR)MyTrackBarWindowProc ); // Limit the text in the preview pane ::SendDlgItemMessage( hWnd, IDC_EDIT_SPEAK, EM_LIMITTEXT, MAX_EDIT_TEXT - 1, 0 ); // Find the original default token SpGetDefaultTokenFromCategoryId( SPCAT_VOICES, &m_cpOriginalDefaultVoiceToken ); // Set the appropriate voice DefaultVoiceChange(true); } /* CTTSDlg::OnInitDialog */ /***************************************************************************** * CTTSDlg::InitTTSList * *----------------------* * Description: * Initializes the list control for the TTS dialog box. *******************************************************************BECKYW****/ void CTTSDlg::InitTTSList( HWND hWnd ) { m_hTTSCombo = ::GetDlgItem( hWnd, IDC_COMBO_VOICES ); SpInitTokenComboBox( m_hTTSCombo, SPCAT_VOICES ); } /***************************************************************************** * CTTSDlg::OnDestroy * *--------------------* * Description: * Destruction ****************************************************************** MIKEAR ***/ void CTTSDlg::OnDestroy() { SPDBG_FUNC( "CTTSDlg::OnDestroy" ); if (m_cpVoice) { m_cpVoice->SetNotifySink(NULL); m_cpVoice.Release(); } // Let go of the tokens in the combo box SpDestroyTokenComboBox( m_hTTSCombo ); } /* CTTSDlg::OnDestroy */ /***************************************************************************** * CTTSDlg::OnApply * *------------------* * Description: * Set user specified options ****************************************************************** BECKYW ***/ void CTTSDlg::OnApply() { // SOFTWARE ENGINEERING OPPORTUNITY (BeckyW 7/28/00): This needs to // return an error code SPDBG_FUNC( "CTTSDlg::OnApply" ); m_bApplied = true; // Store the current voice HRESULT hr = E_FAIL; if (m_cpCurVoiceToken) { hr = SpSetDefaultTokenForCategoryId(SPCAT_VOICES, m_cpCurVoiceToken ); } if ( SUCCEEDED( hr ) ) { m_cpOriginalDefaultVoiceToken = m_cpCurVoiceToken; } // Store the current audio out hr = S_OK; if ( m_pAudioDlg ) { hr = m_pAudioDlg->OnApply(); if ( FAILED( hr ) ) { WCHAR szError[256]; szError[0] = '\0'; LoadString(_Module.GetResourceInstance(), IDS_AUDIO_CHANGE_FAILED, szError, sp_countof(szError)); MessageBox(m_hDlg, szError, m_szCaption, MB_ICONWARNING | g_dwIsRTLLayout); } // Kill the audio dialog, as we are done with it. delete m_pAudioDlg; m_pAudioDlg = NULL; // Re-create the voice, since we have audio changes to pick up DefaultVoiceChange(false); } // Store the voice rate in the registry int iCurRate = 0; HWND hSlider = ::GetDlgItem( m_hDlg, IDC_SLIDER_SPEED ); iCurRate = (int)::SendMessage( hSlider, TBM_GETPOS, 0, 0 ); CComPtr<ISpObjectTokenCategory> cpCategory; if (SUCCEEDED(SpGetCategoryFromId(SPCAT_VOICES, &cpCategory))) { CComPtr<ISpDataKey> cpDataKey; if (SUCCEEDED(cpCategory->GetDataKey(SPDKL_CurrentUser, &cpDataKey))) { cpDataKey->SetDWORD(SPVOICECATEGORY_TTSRATE, iCurRate); } } // Keep around the slider position for determining UI state later m_iOriginalRateSliderPos = iCurRate; KickCPLUI(); } /* CTTSDlg::OnApply */ /***************************************************************************** * CTTSDlg::PopulateEditCtrl * *---------------------------* * Description: * Populates the edit control with the name of the default voice. ****************************************************************** MIKEAR ***/ void CTTSDlg::PopulateEditCtrl( ISpObjectToken * pToken ) { SPDBG_FUNC( "CTTSDlg::PopulateEditCtrl" ); HRESULT hr = S_OK; // Richedit/TOM CComPtr<IRichEditOle> cpRichEdit; // OLE interface to the rich edit control CComPtr<ITextDocument> cpTextDoc; CComPtr<ITextRange> cpTextRange; LANGID langId; WCHAR text[128], editText[MAX_PATH]; HWND hWndEdit = ::GetDlgItem(m_hDlg, IDC_EDIT_SPEAK); CSpDynamicString dstrDescription; if ((SUCCEEDED(SpGetLanguageFromVoiceToken(pToken, &langId))) && (!m_fTextModified)) { CComPtr<ISpObjectTokenCategory> cpCategory; CComPtr<ISpDataKey> cpAttributesKey; CComPtr<ISpDataKey> cpPreviewKey; CComPtr<ISpDataKey> cpVoicesKey; int len; // First get language of voice from token. hr = SpGetDescription(pToken, &dstrDescription, langId); // Now get hold of preview key to try and find the appropriate text. if (SUCCEEDED(hr)) { hr = SpGetCategoryFromId(SPCAT_VOICES, &cpCategory); } if (SUCCEEDED(hr)) { hr = cpCategory->GetDataKey(SPDKL_LocalMachine, &cpVoicesKey); } if (SUCCEEDED(hr)) { hr = cpVoicesKey->OpenKey(L"Preview", &cpPreviewKey); } if (SUCCEEDED(hr)) { CSpDynamicString dstrText; swprintf(text, L"%x", langId); hr = cpPreviewKey->GetStringValue(text, &dstrText); if (SUCCEEDED(hr)) { wcsncpy(text, dstrText, 127); text[127] = 0; } } // If preview key did not contain appropriate text, fall back to the hard-coded (and // potentially localized) text in the cpl resources. if (FAILED(hr)) { len = LoadString( _Module.GetResourceInstance(), IDS_DEF_VOICE_TEXT, text, 128); if (len != 0) { hr = S_OK; } } if(SUCCEEDED(hr)) { WCHAR *pFirstP = wcschr(text, L'%'); WCHAR *pLastP = wcsrchr(text, L'%'); // Preview string with no %s or one %s is valid. Other kinds are not so just use description string if(!pFirstP || (pFirstP == pLastP && ((*(pFirstP + 1) == L's' || *(pFirstP + 1) == L'S')))) { _snwprintf( editText, MAX_PATH, text, dstrDescription ); } else { _snwprintf( editText, MAX_PATH, L"%s", dstrDescription ); } // truncate string if too long editText[MAX_PATH - 1] = L'\0'; ::SendMessage( hWndEdit, EM_GETOLEINTERFACE, 0, (LPARAM)(LPVOID FAR *)&cpRichEdit ); if ( !cpRichEdit ) { hr = E_FAIL; } if (SUCCEEDED(hr)) { hr = cpRichEdit->QueryInterface( IID_ITextDocument, (void**)&cpTextDoc ); } if (SUCCEEDED(hr)) { hr = cpTextDoc->Range(0, MAX_EDIT_TEXT-1, &cpTextRange); } if (SUCCEEDED(hr)) { BSTR bstrText = SysAllocString(editText); hr = cpTextRange->SetText(bstrText); SysFreeString(bstrText); } if (FAILED(hr)) { // Do best we can with this API - unicode languages not equal to the OS language will be replaced with ???'s. SetWindowText(hWndEdit, editText ); } } } } /* CTTSDlg::PopulateEditCtrl */ /***************************************************************************** * CTTSDlg::DefaultVoiceChange * *-----------------------------* * Description: * Changes the current default voice. * If there is already a default voice in effect (i.e., if this is * not the first time we are calling this function), removes the * checkmark from the appropriate item in the list. * Sets the checkmark to the appropriate item in the list. * Sets the voice with the appropriate token. * Return: * S_OK * E_UNEXPECTED if there is no token currently selected in the voice list * failure codes of SAPI voice initialization functions ******************************************************************* BECKYW ***/ HRESULT CTTSDlg::DefaultVoiceChange(bool fUsePersistentRate) { SPDBG_FUNC( "CTTSDlg::DefaultVoiceChange" ); if ( m_bIsSpeaking ) { // This forces the voice to stop speaking m_cpVoice->Speak( NULL, SPF_PURGEBEFORESPEAK, NULL ); m_bIsSpeaking = false; ChangeSpeakButton(); } if (m_cpVoice) { m_cpVoice->SetNotifySink(NULL); m_cpVoice.Release(); } // Find out what is selected int iSelIndex = (int) ::SendMessage( m_hTTSCombo, CB_GETCURSEL, 0, 0 ); m_cpCurVoiceToken = (ISpObjectToken *) ::SendMessage( m_hTTSCombo, CB_GETITEMDATA, iSelIndex, 0 ); if ( CB_ERR == (LRESULT) m_cpCurVoiceToken.p ) { m_cpCurVoiceToken = NULL; } HRESULT hr = E_UNEXPECTED; if (m_cpCurVoiceToken) { BOOL fSupported = FALSE; hr = m_cpCurVoiceToken->IsUISupported(SPDUI_EngineProperties, NULL, 0, NULL, &fSupported); if ( FAILED( hr ) ) { fSupported = FALSE; } ::EnableWindow(::GetDlgItem(m_hDlg, IDC_TTS_ADV), fSupported); // Get the voice from the SR Dlg's recognizer, if possible. // Otherwise just CoCreate the voice ISpRecoContext *pRecoContext = g_pSRDlg ? g_pSRDlg->GetRecoContext() : NULL; if ( pRecoContext ) { hr = pRecoContext->GetVoice( &m_cpVoice ); // Since the recocontext might not have changed, but we might have // changed the default audio object, just to be sure, we // go and get the default audio out token and SetOutput CComPtr<ISpObjectToken> cpAudioToken; if ( SUCCEEDED( hr ) ) { hr = SpGetDefaultTokenFromCategoryId( SPCAT_AUDIOOUT, &cpAudioToken ); } else { hr = m_cpVoice.CoCreateInstance(CLSID_SpVoice); } if ( SUCCEEDED( hr ) ) { hr = m_cpVoice->SetOutput( cpAudioToken, TRUE ); } } else { hr = m_cpVoice.CoCreateInstance(CLSID_SpVoice); } if( SUCCEEDED( hr ) ) { hr = m_cpVoice->SetVoice(m_cpCurVoiceToken); } if (SUCCEEDED(hr)) { CComPtr<ISpNotifyTranslator> cpNotify; cpNotify.CoCreateInstance(CLSID_SpNotifyTranslator); cpNotify->InitSpNotifyCallback(this, 0, 0); m_cpVoice->SetInterest(SPFEI(SPEI_WORD_BOUNDARY) | SPFEI(SPEI_END_INPUT_STREAM), 0); m_cpVoice->SetNotifySink(cpNotify); // Set the appropriate speed on the slider if (fUsePersistentRate) { CComPtr<ISpObjectTokenCategory> cpCategory; ULONG ulCurRate=0; if (SUCCEEDED(SpGetCategoryFromId(SPCAT_VOICES, &cpCategory))) { CComPtr<ISpDataKey> cpDataKey; if (SUCCEEDED(cpCategory->GetDataKey(SPDKL_CurrentUser, &cpDataKey))) { cpDataKey->GetDWORD(SPVOICECATEGORY_TTSRATE, (ULONG*)&ulCurRate); } } m_iOriginalRateSliderPos = ulCurRate; } else { m_iOriginalRateSliderPos = m_iSpeed; } HWND hSlider = ::GetDlgItem( m_hDlg, IDC_SLIDER_SPEED ); ::SendMessage( hSlider, TBM_SETPOS, true, m_iOriginalRateSliderPos ); // Enable the Preview Voice button ::EnableWindow( ::GetDlgItem( g_pTTSDlg->GetHDlg(), IDC_SPEAK ), TRUE ); } else { // Warn the user of failure WCHAR szError[MAX_LOADSTRING]; szError[0] = 0; LoadString( _Module.GetResourceInstance(), IDS_TTS_ERROR, szError, MAX_LOADSTRING); MessageBox( GetHDlg(), szError, m_szCaption, MB_ICONEXCLAMATION | g_dwIsRTLLayout ); // Disable the Preview Voice button ::EnableWindow( ::GetDlgItem( GetHDlg(), IDC_SPEAK ), FALSE ); } // Put text corresponding to this voice into the edit control PopulateEditCtrl(m_cpCurVoiceToken); // Kick the UI KickCPLUI(); } return hr; } /* CTTSDlg::DefaultVoiceChange */ /***************************************************************************** * CTTSDlg::SetCheckmark * *-----------------------* * Description: * Sets the specified item in the list control to be either checked * or unchecked (as the default voice) ******************************************************************************/ void CTTSDlg::SetCheckmark( HWND hList, int iIndex, bool bCheck ) { m_fForceCheckStateChange = true; ListView_SetCheckState( hList, iIndex, bCheck ); m_fForceCheckStateChange = false; } /* CTTSDlg::SetCheckmark */ /***************************************************************************** * CTTSDlg::KickCPLUI * *--------------------* * Description: * Determines if there is anything to apply right now ******************************************************************************/ void CTTSDlg::KickCPLUI() { bool fChanged = false; // Compare IDs CSpDynamicString dstrSelTokenID; CSpDynamicString dstrOriginalDefaultTokenID; HRESULT hr = E_FAIL; if ( m_cpOriginalDefaultVoiceToken && m_cpCurVoiceToken ) { hr = m_cpCurVoiceToken->GetId( &dstrSelTokenID ); } if ( SUCCEEDED( hr ) ) { hr = m_cpOriginalDefaultVoiceToken->GetId( &dstrOriginalDefaultTokenID ); } if ( SUCCEEDED( hr ) && ( 0 != wcsicmp( dstrOriginalDefaultTokenID, dstrSelTokenID ) ) ) { fChanged = true; } // Check the audio device if ( m_pAudioDlg && m_pAudioDlg->IsAudioDeviceChanged() ) { fChanged = true; } // Check the voice rate int iSpeed = (int) ::SendDlgItemMessage( m_hDlg, IDC_SLIDER_SPEED, TBM_GETPOS, 0, 0 ); if ( m_iOriginalRateSliderPos != iSpeed ) { fChanged = true; } // Tell the main propsheet HWND hwndParent = ::GetParent( m_hDlg ); ::SendMessage( hwndParent, fChanged ? PSM_CHANGED : PSM_UNCHANGED, (WPARAM)(m_hDlg), 0 ); } /* CTTSDlg::KickCPLUI */ /***************************************************************************** * CTTSDlg::ChangeSpeed * *----------------------* * Description: * Called when the slider has moved. * Adjusts the speed of the voice ****************************************************************** BECKYW ***/ void CTTSDlg::ChangeSpeed() { HWND hSlider = ::GetDlgItem( m_hDlg, IDC_SLIDER_SPEED ); m_iSpeed = (int)::SendMessage( hSlider, TBM_GETPOS, 0, 0 ); m_cpVoice->SetRate( m_iSpeed ); KickCPLUI(); } /* CTTSDlg::ChangeSpeed */ /***************************************************************************** * CTTSDlg::ChangeSpeakButton * *----------------------------* * Description: * Changes the text in the "Preview Voice" button in order to * reflect whether there is currently a speak happening. ****************************************************************** BECKYW ***/ void CTTSDlg::ChangeSpeakButton() { WCHAR pszButtonCaption[ MAX_LOADSTRING ]; HWND hButton = ::GetDlgItem( m_hDlg, IDC_SPEAK ); ::LoadString( _Module.GetResourceInstance(), m_bIsSpeaking ? IDS_STOP_PREVIEW : IDS_PREVIEW, pszButtonCaption, MAX_LOADSTRING ); ::SendMessage( hButton, WM_SETTEXT, 0, (LPARAM) pszButtonCaption ); if (!m_bIsSpeaking) { ::SetFocus(GetDlgItem(m_hDlg, IDC_SPEAK)); } } /* CTTSDlg::ChangeSpeakButton */ /***************************************************************************** * CTTSDlg::Speak * *----------------* * Description: * Speaks the contents of the edit control. * If it is already speaking, shuts up. ****************************************************************** BECKYW ***/ void CTTSDlg::Speak() { SPDBG_FUNC( "CTTSDlg::Speak" ); if ( m_bIsSpeaking ) { // This forces the voice to stop speaking m_cpVoice->Speak( NULL, SPF_PURGEBEFORESPEAK, NULL ); m_bIsSpeaking = false; ChangeSpeakButton(); } else { ChangeSpeed(); GETTEXTEX gtex = { sp_countof(m_wszCurSpoken), GT_DEFAULT, 1200, NULL, NULL }; m_wszCurSpoken[0] = 0; LRESULT cChars = ::SendDlgItemMessage(m_hDlg, IDC_EDIT_SPEAK, EM_GETTEXTEX, (WPARAM)&gtex, (LPARAM)m_wszCurSpoken); if (cChars) { HRESULT hr = m_cpVoice->Speak(m_wszCurSpoken, SPF_ASYNC | SPF_PURGEBEFORESPEAK, NULL); if ( SUCCEEDED( hr ) ) { m_bIsSpeaking = true; ::SetFocus(GetDlgItem(m_hDlg, IDC_EDIT_SPEAK)); ChangeSpeakButton(); } else { // Warn the user that he needs to apply the changes WCHAR szError[MAX_LOADSTRING]; szError[0] = 0; LoadString( _Module.GetResourceInstance(), IDS_SPEAK_ERROR, szError, MAX_LOADSTRING); MessageBox( GetHDlg(), szError, m_szCaption, MB_ICONWARNING | g_dwIsRTLLayout ); } } } } /* CTTSDlg::Speak */ /***************************************************************************** * CTTSDlg::StopSpeak * *----------------* * Description: * Stops the voice from speaking. * If it is already speaking, shuts up. ****************************************************************** BECKYW ***/ void CTTSDlg::StopSpeak() { SPDBG_FUNC( "CTTSDlg::StopSpeak" ); if ( m_bIsSpeaking ) { // This forces the voice to stop speaking m_cpVoice->Speak( NULL, SPF_PURGEBEFORESPEAK, NULL ); m_bIsSpeaking = false; } ChangeSpeakButton(); } /* CTTSDlg::StopSpeak */ /***************************************************************************** * CTTSDlg::NotifyCallback * *-------------------------* * Description: * Callback function that highlights words as they are spoken. ****************************************************************** MIKEAR ***/ STDMETHODIMP CTTSDlg::NotifyCallback(WPARAM /* wParam */, LPARAM /* lParam */) { SPDBG_FUNC( "CTTSDlg::NotifyCallback" ); SPVOICESTATUS Stat; m_cpVoice->GetStatus(&Stat, NULL); WPARAM nStart; LPARAM nEnd; if (Stat.dwRunningState & SPRS_DONE) { nStart = nEnd = 0; m_bIsSpeaking = false; ChangeSpeakButton(); // Set the selection to an IP at the start of the text to speak ::SendDlgItemMessage( m_hDlg, IDC_EDIT_SPEAK, EM_SETSEL, 0, 0 ); } else { nStart = (LPARAM)Stat.ulInputWordPos; nEnd = nStart + Stat.ulInputWordLen; CHARRANGE cr; cr.cpMin = (LONG)nStart; cr.cpMax = (LONG)nEnd; ::SendDlgItemMessage( m_hDlg, IDC_EDIT_SPEAK, EM_EXSETSEL, 0, (LPARAM) &cr ); } return S_OK; } /* CTTSDlg::NotifyCallback */
33.530543
133
0.50474
[ "object" ]
d6aa76a5d91df3bc5df00dc0da36f652caf9ea46
2,199
cpp
C++
LeetCode/C++/338. Counting Bits.cpp
shreejitverma/GeeksforGeeks
d7bcb166369fffa9a031a258e925b6aff8d44e6c
[ "MIT" ]
2
2022-02-18T05:14:28.000Z
2022-03-08T07:00:08.000Z
LeetCode/C++/338. Counting Bits.cpp
shivaniverma1/Competitive-Programming-1
d7bcb166369fffa9a031a258e925b6aff8d44e6c
[ "MIT" ]
6
2022-01-13T04:31:04.000Z
2022-03-12T01:06:16.000Z
LeetCode/C++/338. Counting Bits.cpp
shivaniverma1/Competitive-Programming-1
d7bcb166369fffa9a031a258e925b6aff8d44e6c
[ "MIT" ]
2
2022-02-14T19:53:53.000Z
2022-02-18T05:14:30.000Z
/** Given a non negative integer number num. For every numbers i in the range 0 ≤ i ≤ num calculate the number of 1's in their binary representation and return them as an array. Example 1: Input: 2 Output: [0,1,1] Example 2: Input: 5 Output: [0,1,1,2,1,2] Follow up: It is very easy to come up with a solution with run time O(n*sizeof(integer)). But can you do it in linear time O(n) /possibly in a single pass? Space complexity should be O(n). Can you do it like a boss? Do it without using any builtin function like __builtin_popcount in c++ or in any other language. **/ //Your runtime beats 60.09 % of cpp submissions. class Solution { public: vector<int> countBits(int num) { vector<int> ans; for(int i=0;i<=num;i++){ int count = 0; int j = i; while(j!=0){ count+=j%2; j/=2; } ans.push_back(count); } return ans; } }; //Your runtime beats 43.45 % of cpp submissions. class Solution { public: vector<int> countBits(int num) { vector<int> ans; for(int i=0;i<=num;i++){ ans.push_back(__builtin_popcount(i)); } return ans; } }; //from hint, suboptimal //Runtime: 8 ms, faster than 99.05% of C++ online submissions for Counting Bits. //Memory Usage: 7.8 MB, less than 100.00% of C++ online submissions for Counting Bits. class Solution { public: vector<int> countBits(int num) { vector<int> ans(num+1, 0); for(int i = 1; i < num+1; i++){ ans[i] = ans[i/2] + i%2; } return ans; } }; //Your runtime beats 97.98 % of cpp submissions. class Solution { public: vector<int> countBits(int num) { vector<int> ret(num+1, 0); for (int i = 1; i <= num; ++i) ret[i] = ret[i&(i-1)] + 1; //by @fengcc // ret[i] = ret[i/2] + i % 2; //by @sijiec return ret; } }; /** by @fengcc i&(i-1) drops the lowest set bit. For example: i = 14, its binary representation is 1110, so i-1 is 1101, i&(i-1) = 1100, the number of "1" in its binary representation decrease one, so ret[i] = ret[i&(i-1)] + 1. **/
26.817073
212
0.576171
[ "vector" ]
d6b7dec7aa84aa52f5168695d8a012cbaa417be2
405
hpp
C++
include/config.hpp
ElectrodeYT/basic-init
0012a5f3d75f280fb8a5b962df638afb6b6caa75
[ "MIT" ]
null
null
null
include/config.hpp
ElectrodeYT/basic-init
0012a5f3d75f280fb8a5b962df638afb6b6caa75
[ "MIT" ]
1
2019-05-27T20:05:10.000Z
2019-05-27T20:05:10.000Z
include/config.hpp
ElectrodeYT/basic-init
0012a5f3d75f280fb8a5b962df638afb6b6caa75
[ "MIT" ]
null
null
null
#ifndef CONFIG_HPP #define CONFIG_HPP // Things for config files #include <string> #include <vector> class ConfigFile { public: // Names of the entries. std::vector<std::string> config_names; // Values of the entries. std::vector<std::string> config_values; }; class Config { public: static ConfigFile readConfigFile(std::string file); // TODO: static ConfigFile generateDefaultBoot(); }; #endif
18.409091
52
0.738272
[ "vector" ]
d6ba256b4d3ee4d44f4be95bf7809254757f5185
11,851
hpp
C++
vpp/algorithms/line_tracker_4_sfm/hough_extruder/unscented_kalman_filter.hpp
WLChopSticks/vpp
2e17b21c56680bcfa94292ef5117f73572bf277d
[ "MIT" ]
624
2015-01-05T16:40:41.000Z
2022-03-01T03:09:43.000Z
vpp/algorithms/line_tracker_4_sfm/hough_extruder/unscented_kalman_filter.hpp
WLChopSticks/vpp
2e17b21c56680bcfa94292ef5117f73572bf277d
[ "MIT" ]
10
2015-01-22T20:50:13.000Z
2018-05-15T10:41:34.000Z
vpp/algorithms/line_tracker_4_sfm/hough_extruder/unscented_kalman_filter.hpp
WLChopSticks/vpp
2e17b21c56680bcfa94292ef5117f73572bf277d
[ "MIT" ]
113
2015-01-19T11:58:35.000Z
2022-03-28T05:15:20.000Z
#include "unscented_kalman_filter.hh" #include "Eigen/Dense" #include <iostream> using namespace std; using Eigen::MatrixXd; using Eigen::VectorXd; using std::vector; /** * Initializes Unscented Kalman filter */ unscented_kalman_filter::unscented_kalman_filter() { // Set initialization to false initially is_initialized_ = false; ///* State dimension state_dimension = 5; ///* Augmented state dimension augmented_state_dimension = 7; //* radar measurement dimension measurement_dimension = 2; ///* Sigma point spreading parameter sigma_point_spreading_parameter = 3 - augmented_state_dimension; // initial state vector state_vector = VectorXd(5); // initial covariance matrix covariance_matrix = MatrixXd::Zero(5, 5); // initialize the sigma points matrix with zeroes predicted_sigmas_matrix = MatrixXd::Zero(state_dimension, 2 * augmented_state_dimension + 1); ///* time when the state is true, in us previous_timestamp_ = 0; // Process noise standard deviation longitudinal acceleration in m/s^2 standard_deviation_longit_acc = 3; // Process noise standard deviation yaw acceleration in rad/s^2 standard_deviation_yaw = 0.7; // Laser measurement noise standard deviation position1 in m standard_deviation_noise1 = 0.15; // Laser measurement noise standard deviation position2 in m standard_deviation_noise2 = 0.15; ///* Weights of sigma points weights_ = VectorXd::Zero(2*augmented_state_dimension+1); // set weights double weight_0 = sigma_point_spreading_parameter/(sigma_point_spreading_parameter+augmented_state_dimension); weights_(0) = weight_0; for (int i=1; i<2*augmented_state_dimension+1; i++) { //2n+1 weights double weight = 0.5/(augmented_state_dimension+sigma_point_spreading_parameter); weights_(i) = weight; } return; } unscented_kalman_filter::~unscented_kalman_filter() {} void unscented_kalman_filter::add_new_dectection(const vint2 values, float dt) { cout << "ajouter un nouveau point " << endl; if (!is_initialized_) { // Initialize the state x_,state covariance matrix P_ initialize_the_track(values,dt); //previous_timestamp_ = meas_package.timestamp_; is_initialized_ = true; return; } double delta_t = dt; prediction(delta_t); //mean predicted measurement VectorXd z_pred = VectorXd::Zero(measurement_dimension); //measurement covariance matrix S MatrixXd S = MatrixXd::Zero(measurement_dimension,measurement_dimension); // cross-correlation matrix Tc MatrixXd Tc = MatrixXd::Zero(state_dimension, measurement_dimension); // get predictions for x,S and Tc in Lidar space predict_measurement(z_pred, S, Tc); cout << "la prediction " << z_pred[0] << " " << z_pred[1] << endl; // update the state using the LIDAR measurement update(values,dt, z_pred, Tc, S); cout << "la vraie valeur " << values[0] << " " << values[1] << endl; // update the time return; } void unscented_kalman_filter::only_update_track(float dt) { double delta_t = dt; prediction(delta_t); //mean predicted measurement VectorXd z_pred = VectorXd::Zero(measurement_dimension); //measurement covariance matrix S MatrixXd S = MatrixXd::Zero(measurement_dimension,measurement_dimension); // cross-correlation matrix Tc MatrixXd Tc = MatrixXd::Zero(state_dimension, measurement_dimension); // get predictions for x,S and Tc in Lidar space predict_measurement(z_pred, S, Tc); cout << "la prediction " << z_pred[0] << " " << z_pred[1] << endl; return; } void unscented_kalman_filter::initialize_the_track(const vint2 values,float dt) { cout << "initialisation du filtre " << endl; // initialize state covariance matrix P covariance_matrix = MatrixXd(5, 5); covariance_matrix << 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1; // Initialize state. state_vector << values[0],values[1],0,0,0; return; } /** * @param MatrixXd &Xsig_out. Computes augmented sigma points in state space */ void unscented_kalman_filter::augmented_sigma_points(MatrixXd &Xsig_out){ //create augmented mean vector static VectorXd x_aug = VectorXd(augmented_state_dimension); //create augmented state covariance static MatrixXd P_aug = MatrixXd(augmented_state_dimension, augmented_state_dimension); //create sigma point matrix static MatrixXd Xsig_aug = MatrixXd(augmented_state_dimension, 2 * augmented_state_dimension + 1); //create augmented mean state x_aug.head(5) = state_vector; x_aug(5) = 0; x_aug(6) = 0; //create augmented covariance matrix P_aug.fill(0.0); P_aug.topLeftCorner(5,5) = covariance_matrix; P_aug(5,5) = pow(standard_deviation_longit_acc,2); P_aug(6,6) = pow(standard_deviation_yaw,2); //create square root matrix MatrixXd L = P_aug.llt().matrixL(); //create augmented sigma points Xsig_aug.col(0) = x_aug; for (int i = 0; i< augmented_state_dimension; i++) { Xsig_aug.col(i+1) = x_aug + sqrt(sigma_point_spreading_parameter+augmented_state_dimension) * L.col(i); Xsig_aug.col(i+1+augmented_state_dimension) = x_aug - sqrt(sigma_point_spreading_parameter+augmented_state_dimension) * L.col(i); } Xsig_out = Xsig_aug; return; } /** * @param MatrixXd &Xsig_out. predicts augmented sigma points */ void unscented_kalman_filter::sigma_point_prediction(const MatrixXd &Xsig_aug, const double delta_t, MatrixXd &Xsig_out){ //create matrix with predicted sigma points as columns static MatrixXd Xsig_pred = MatrixXd(state_dimension, 2 * augmented_state_dimension + 1); //predict sigma points for (int i = 0; i< 2*augmented_state_dimension+1; i++) { //extract values for better readability double p_x = Xsig_aug(0,i); double p_y = Xsig_aug(1,i); double v = Xsig_aug(2,i); double yaw = Xsig_aug(3,i); double yawd = Xsig_aug(4,i); double nu_a = Xsig_aug(5,i); double nu_yawdd = Xsig_aug(6,i); //predicted state values double px_p, py_p; //avoid division by zero if (fabs(yawd) > 0.001) { px_p = p_x + v/yawd * ( sin (yaw + yawd*delta_t) - sin(yaw)); py_p = p_y + v/yawd * ( cos(yaw) - cos(yaw+yawd*delta_t) ); } else { px_p = p_x + v*delta_t*cos(yaw); py_p = p_y + v*delta_t*sin(yaw); } double v_p = v; double yaw_p = yaw + yawd*delta_t; double yawd_p = yawd; //add noise px_p = px_p + 0.5*nu_a*delta_t*delta_t * cos(yaw); py_p = py_p + 0.5*nu_a*delta_t*delta_t * sin(yaw); v_p = v_p + nu_a*delta_t; yaw_p = yaw_p + 0.5*nu_yawdd*delta_t*delta_t; yawd_p = yawd_p + nu_yawdd*delta_t; //write predicted sigma point into right column Xsig_pred(0,i) = px_p; Xsig_pred(1,i) = py_p; Xsig_pred(2,i) = v_p; Xsig_pred(3,i) = yaw_p; Xsig_pred(4,i) = yawd_p; } Xsig_out = Xsig_pred; return; } void unscented_kalman_filter::predict_mean_and_covariance(const MatrixXd &Xsig_pred, VectorXd &x_out, MatrixXd &P_out) { //create vector for predicted state static VectorXd x = VectorXd(state_dimension); //create covariance matrix for prediction static MatrixXd P = MatrixXd(state_dimension, state_dimension); //predicted state mean x.fill(0.0); for (int i = 0; i < 2 * augmented_state_dimension + 1; i++) { //iterate over sigma points x = x + weights_(i) * Xsig_pred.col(i); } //predicted state covariance matrix P.fill(0.0); for (int i = 0; i < 2 * augmented_state_dimension + 1; i++) { //iterate over sigma points // state difference VectorXd x_diff = Xsig_pred.col(i) - x; //angle normalization if (x_diff(3)> M_PI) { //cout << "normalisation " << x_diff(3) << endl; x_diff(3) = atan2(sin(x_diff(3)),cos(x_diff(3))); } P = P + weights_(i) * x_diff * x_diff.transpose() ; } //print result //std::cout << "Predicted state px,py,v,psi,psi_dot" << std::endl; //std::cout << x << std::endl; //std::cout << "Predicted covariance matrix P " << std::endl; //std::cout << P << std::endl; //write result x_out = x; P_out = P; return; } void unscented_kalman_filter::predict_measurement(VectorXd &z_out, MatrixXd &S_out, MatrixXd &Tc_out) { //create matrix for sigma points in measurement space static MatrixXd Zsig = MatrixXd(measurement_dimension, 2 * augmented_state_dimension + 1); //transform sigma points into measurement space for (int i = 0; i < 2 * augmented_state_dimension + 1; i++) { //2n+1 sigma points // measurement model Zsig(0,i) = predicted_sigmas_matrix(0,i); //px Zsig(1,i) = predicted_sigmas_matrix(1,i); //py } //mean predicted measurement static VectorXd z_pred = VectorXd(measurement_dimension); z_pred.fill(0.0); for (int i=0; i < 2*augmented_state_dimension+1; i++) { z_pred = z_pred + weights_(i) * Zsig.col(i); } //measurement covariance matrix S static MatrixXd S = MatrixXd(measurement_dimension,measurement_dimension); S.fill(0.0); //create matrix for cross correlation Tc static MatrixXd Tc = MatrixXd(state_dimension, measurement_dimension); Tc.fill(0.0); for (int i = 0; i < 2 * augmented_state_dimension + 1; i++) { //2n+1 simga points //residual VectorXd z_diff = Zsig.col(i) - z_pred; S = S + weights_(i) * z_diff * z_diff.transpose(); // state difference VectorXd x_diff = predicted_sigmas_matrix.col(i) - state_vector; Tc = Tc + weights_(i) * x_diff * z_diff.transpose(); } //add measurement noise covariance matrix static MatrixXd R = MatrixXd(measurement_dimension,measurement_dimension); R << pow(standard_deviation_noise1,2), 0, 0, pow(standard_deviation_noise2,2); S = S + R; //write result z_out = z_pred; S_out = S; Tc_out = Tc; return; } void unscented_kalman_filter::prediction(double delta_t) { static MatrixXd Xsig_aug = MatrixXd(2*augmented_state_dimension + 1, augmented_state_dimension); //create example matrix with predicted sigma points static MatrixXd Xsig_pred = MatrixXd(state_dimension, 2 * augmented_state_dimension + 1); // compute augmented sigma points augmented_sigma_points(Xsig_aug); // predict augmented sigma points //insert timer sigma_point_prediction(Xsig_aug, delta_t, Xsig_pred); static VectorXd x_pred = VectorXd(state_dimension); static MatrixXd P_pred = MatrixXd(state_dimension, state_dimension); predict_mean_and_covariance(Xsig_pred,x_pred, P_pred); state_vector = x_pred; covariance_matrix = P_pred; predicted_sigmas_matrix = Xsig_pred; return; } void unscented_kalman_filter::update(vint2 values, float dt, VectorXd &z_pred, MatrixXd &Tc, MatrixXd &S) { //mean predicted measurement static VectorXd z = VectorXd::Zero(measurement_dimension); z << values[0],values[1]; //Kalman gain K; static MatrixXd K = MatrixXd::Zero(state_dimension,measurement_dimension); K = Tc * S.inverse(); //residual static VectorXd z_diff = VectorXd::Zero(measurement_dimension); z_diff = z - z_pred; //update state mean and covariance matrix state_vector = state_vector + K * z_diff; covariance_matrix = covariance_matrix - K*S*K.transpose(); return; }
31.518617
137
0.66121
[ "vector", "model", "transform" ]
d6ba3f7cb4672fcd84e51c8a544e7c5f4d368bfa
23,263
cc
C++
unittest/contract_test.cc
chuffa/ITensor
7dceab2347cd0b4c0c8ef659480efdafa18dddc3
[ "Apache-2.0" ]
313
2015-03-06T21:58:52.000Z
2022-03-29T08:58:06.000Z
unittest/contract_test.cc
chuffa/ITensor
7dceab2347cd0b4c0c8ef659480efdafa18dddc3
[ "Apache-2.0" ]
267
2015-02-26T12:52:57.000Z
2022-02-04T20:21:52.000Z
unittest/contract_test.cc
chuffa/ITensor
7dceab2347cd0b4c0c8ef659480efdafa18dddc3
[ "Apache-2.0" ]
169
2015-01-12T01:27:56.000Z
2022-03-24T08:24:55.000Z
#include "test.h" #include "itensor/util/cputime.h" #include "itensor/util/iterate.h" #include "itensor/tensor/contract.h" #include "itensor/util/set_scoped.h" #include "itensor/util/args.h" #include "itensor/global.h" using namespace itensor; TEST_CASE("Contract Test") { auto randomize = [](TensorRef t) { for(auto& elt : t) elt = Global::random(); }; SECTION("Contract Reshape Basic") { Tensor A(2,2), B(2,2), C(2,2); A(0,0) = 1; A(0,1) = 2; A(1,0) = 3; A(1,1) = 4; B(0,0) = 5; B(0,1) = 6; B(1,0) = 7; B(1,1) = 8; SECTION("Case 1") { // // 1 2 5 6 19 22 // 3 4 7 8 43 50 // contract(A,{1,2},B,{2,3},C,{1,3}); for(auto r : range(2)) for(auto c : range(2)) { Real val = 0; for(int k = 0; k < 2; ++k) { //printfln("A(%d,%d)*B(%d,%d)=%d*%d=%d",r,k,k,c,A(r,k),B(k,c),A(r,k)*B(k,c)); val += A(r,k)*B(k,c); } REQUIRE(C(r,c) == val); } } SECTION("Case 2") { // // 1 2 5 7 17 23 // 3 4 6 8 39 53 // //println("Case 2:"); contract(A,{1,2},B,{3,2},C,{1,3}); for(auto r : range(2)) for(auto c : range(2)) { Real val = 0; for(auto k : range(2)) { val += A(r,k)*B(c,k); } REQUIRE(C(r,c) == val); } } SECTION("Case 3") { contract(A,{1,2},B,{2,3},C,{3,1}); for(auto r : range(2)) for(auto c : range(2)) { Real val = 0; for(auto k : range(2)) { val += A(r,k)*B(k,c); } REQUIRE(C(c,r) == val); } } SECTION("Case 4") { contract(A,{1,2},B,{3,2},C,{3,1}); for(auto r : range(2)) for(auto c : range(2)) { Real val = 0; for(auto k : range(2)) { val += A(r,k)*B(c,k); } REQUIRE(C(c,r) == val); } } SECTION("Case 5") { contract(A,{2,1},B,{2,3},C,{1,3}); for(auto r : range(2)) for(auto c : range(2)) { Real val = 0; for(auto k : range(2)) { val += A(k,r)*B(k,c); } REQUIRE(C(r,c) == val); } } SECTION("Case 6") { contract(A,{2,1},B,{3,2},C,{1,3}); for(auto r : range(2)) for(auto c : range(2)) { Real val = 0; for(auto k : range(2)) { val += A(k,r)*B(c,k); } REQUIRE(C(r,c) == val); } } SECTION("Case 7") { contract(A,{2,1},B,{2,3},C,{3,1}); for(auto r : range(2)) for(auto c : range(2)) { Real val = 0; for(auto k : range(2)) { val += A(k,r)*B(k,c); } REQUIRE(C(c,r) == val); } } SECTION("Case 8") { contract(A,{2,1},B,{3,2},C,{3,1}); for(auto r : range(2)) for(auto c : range(2)) { Real val = 0; for(auto k : range(2)) { val += A(k,r)*B(c,k); } REQUIRE(C(c,r) == val); } } } SECTION("Contract Reshape Non-Matrix") { SECTION("Case 1") { Tensor A(2,3,4), B(3,7,2), C(4,7); randomize(A); randomize(B); contract(A,{2,3,4},B,{3,7,2},C,{4,7}); for(auto i4 : range(4)) for(auto i7 : range(7)) { Real val = 0; for(auto i2 : range(2)) for(auto i3 : range(3)) { val += A(i2,i3,i4)*B(i3,i7,i2); } CHECK_CLOSE(C(i4,i7),val); } } SECTION("Case 2") { Tensor A(2,3,4), B(3,7,2), C(7,4); randomize(A); randomize(B); Global::debug3() = true; contract(A,{2,3,4},B,{3,7,2},C,{7,4}); Global::debug3() = false; for(auto i4 : range(4)) for(auto i7 : range(7)) { Real val = 0; for(auto i2 : range(2)) for(auto i3 : range(3)) { val += A(i2,i3,i4)*B(i3,i7,i2); } CHECK_CLOSE(C(i7,i4),val); } } SECTION("Case 3") { Tensor A(2,4,3), B(3,7,2), C(7,4); randomize(A); randomize(B); contract(A,{2,4,3},B,{3,7,2},C,{7,4}); for(auto i4 : range(4)) for(auto i7 : range(7)) { Real val = 0; for(auto i2 : range(2)) for(auto i3 : range(3)) { val += A(i2,i4,i3)*B(i3,i7,i2); } CHECK_CLOSE(C(i7,i4),val); } } SECTION("Case 4") { Tensor A(2,4,3), B(3,7,2), C(4,7); randomize(A); randomize(B); contract(A,{2,4,3},B,{3,7,2},C,{4,7}); for(auto i4 : range(4)) for(auto i7 : range(7)) { Real val = 0; for(auto i2 : range(2)) for(auto i3 : range(3)) { val += A(i2,i4,i3)*B(i3,i7,i2); } CHECK_CLOSE(C(i4,i7),val); } } SECTION("Case NM1") { Tensor A(2,3,4), B(7,3,2), C(4,7); randomize(A); randomize(B); contract(A,{2,3,4},B,{7,3,2},C,{4,7}); for(auto i4 : range(4)) for(auto i7 : range(7)) { Real val = 0; for(auto i2 : range(2)) for(auto i3 : range(3)) { val += A(i2,i3,i4)*B(i7,i3,i2); } CHECK_CLOSE(C(i4,i7),val); } } SECTION("Case NM2") { Tensor A(2,3,4,5), B(7,6,3,2), C(5,4,6,7); randomize(A); randomize(B); contract(A,{2,3,4,5},B,{7,6,3,2},C,{5,4,6,7}); REQUIRE(C.extent(0) == 5); REQUIRE(C.extent(1) == 4); REQUIRE(C.extent(2) == 6); REQUIRE(C.extent(3) == 7); for(auto i4 : range(4)) for(auto i5 : range(5)) for(auto i6 : range(6)) for(auto i7 : range(7)) { Real val = 0; for(auto i2 : range(2)) for(auto i3 : range(3)) { val += A(i2,i3,i4,i5)*B(i7,i6,i3,i2); } CHECK_CLOSE(C(i5,i4,i6,i7),val); } } SECTION("Case NM3") { Tensor A(2,3,4,5), B(7,6,3,2), C(5,4,6,7); randomize(A); randomize(B); contract(B,{7,6,3,2},A,{2,3,4,5},C,{5,4,6,7}); REQUIRE(C.extent(0) == 5); REQUIRE(C.extent(1) == 4); REQUIRE(C.extent(2) == 6); REQUIRE(C.extent(3) == 7); for(auto i4 : range(4)) for(auto i5 : range(5)) for(auto i6 : range(6)) for(auto i7 : range(7)) { Real val = 0; for(auto i2 : range(2)) for(auto i3 : range(3)) { val += A(i2,i3,i4,i5)*B(i7,i6,i3,i2); } CHECK_CLOSE(C(i5,i4,i6,i7),val); } } SECTION("Case NM4") { Tensor A(2,3,4,5,6,7), B(8,7,5,6,9), C(2,8,4,3,9); randomize(A); randomize(B); contract(B,{8,7,5,6,9},A,{2,3,4,5,6,7},C,{2,8,4,3,9}); for(auto i2 : range(2)) for(auto i3 : range(3)) for(auto i4 : range(4)) for(auto i8 : range(8)) for(auto i9 : range(9)) { Real val = 0; for(auto i5 : range(5)) for(auto i6 : range(6)) for(auto i7 : range(7)) { val += A(i2,i3,i4,i5,i6,i7)*B(i8,i7,i5,i6,i9); } CHECK_CLOSE(C(i2,i8,i4,i3,i9),val); } } SECTION("Case NM5") { SET_SCOPED(Global::debug1()) = true; Tensor A(2,3,4,5,6,7), B(8,7,5,6,9), C(4,9,2,3,8); randomize(A); randomize(B); contract(B,{8,7,5,6,9},A,{2,3,4,5,6,7},C,{4,9,2,3,8}); for(auto i2 : range(2)) for(auto i3 : range(3)) for(auto i4 : range(4)) for(auto i8 : range(8)) for(auto i9 : range(9)) { Real val = 0; for(auto i5 : range(5)) for(auto i6 : range(6)) for(auto i7 : range(7)) { val += A(i2,i3,i4,i5,i6,i7)*B(i8,i7,i5,i6,i9); } CHECK_CLOSE(C(i4,i9,i2,i3,i8),val); } } } // Contract Reshape Non-Matrix SECTION("Contract Reshape Matrix") { SECTION("Case M1") { Tensor A(2,3,4), B(7,2,3), C(4,7); randomize(A); randomize(B); contract(A,{2,3,4},B,{7,2,3},C,{4,7}); for(auto i4 : range(4)) for(auto i7 : range(7)) { Real val = 0; for(auto i2 : range(2)) for(auto i3 : range(3)) { val += A(i2,i3,i4)*B(i7,i2,i3); } CHECK_CLOSE(C(i4,i7),val); } } SECTION("Case M2") { Tensor A(4,2,3), B(7,2,3), C(4,7); randomize(A); randomize(B); contract(A,{4,2,3},B,{7,2,3},C,{4,7}); for(auto i4 : range(4)) for(auto i7 : range(7)) { Real val = 0; for(auto i2 : range(2)) for(auto i3 : range(3)) { val += A(i4,i2,i3)*B(i7,i2,i3); } CHECK_CLOSE(C(i4,i7),val); } } SECTION("Case M3") { Tensor A(4,2,3), B(2,3,7), C(4,7); randomize(A); randomize(B); contract(A,{4,2,3},B,{2,3,7},C,{4,7}); for(auto i4 : range(4)) for(auto i7 : range(7)) { Real val = 0; for(auto i2 : range(2)) for(auto i3 : range(3)) { val += A(i4,i2,i3)*B(i2,i3,i7); } CHECK_CLOSE(C(i4,i7),val); } } SECTION("Case M4") { Tensor A(2,3,4), B(2,3,7), C(4,7); randomize(A); randomize(B); contract(A,{2,3,4},B,{2,3,7},C,{4,7}); for(auto i4 : range(4)) for(auto i7 : range(7)) { Real val = 0; for(auto i2 : range(2)) for(auto i3 : range(3)) { val += A(i2,i3,i4)*B(i2,i3,i7); } CHECK_CLOSE(C(i4,i7),val); } } SECTION("Regression Test 1") { Tensor A(4,3,2), B(5,4,3,2), C(5); randomize(A); randomize(B); contract(A,{4,3,2},B,{5,4,3,2},C,{5}); REQUIRE(C.extent(0) == 5); for(auto i5 : range(5)) { Real val = 0; for(auto i2 : range(2)) for(auto i3 : range(3)) for(auto i4 : range(4)) { val += A(i4,i3,i2)*B(i5,i4,i3,i2); } CHECK_CLOSE(C(i5),val); } } } // Contract Reshape Matrix SECTION("Zero Rank Cases") { SECTION("Case 1") { Tensor A(4,3,2), C(2,4,3); randomize(A); auto Bval = 2.; std::vector<Real> Bdat(1,Bval); Range Br; auto B = makeTenRef(Bdat.data(),Bdat.size(),&Br); contract(makeRefc(A),{4,3,2},makeRefc(B),{},makeRef(C),{2,4,3}); for(auto i2 : range(2)) for(auto i3 : range(3)) for(auto i4 : range(4)) { CHECK_CLOSE(C(i2,i4,i3),Bval * A(i4,i3,i2)); } } SECTION("Case 2") { Tensor A(2,3,4), C(2,4,3); randomize(A); auto Bval = Global::random(); std::vector<Real> Bdat(1,Bval); Range Br; auto B = makeTenRef(Bdat.data(),Bdat.size(),&Br); contract(B,{},makeRef(A),{2,3,4},makeRef(C),{2,4,3}); for(auto i2 : range(2)) for(auto i3 : range(3)) for(auto i4 : range(4)) { CHECK_CLOSE(C(i2,i4,i3),Bval * A(i2,i3,i4)); } } } SECTION("Contract Loop") { SECTION("Case 1: Bik Akj = Cij") { int m1 = 10, m2 = 20, m3 = 30; Tensor A(m1,m2,4,5), B(m3,m1,4,6), C(m3,m2,5,6); randomize(A); randomize(B); contractloop<Range>(A,{1,2,4,5},B,{3,1,4,6},C,{3,2,5,6}); for(auto i2 : range(m2)) for(auto i3 : range(m3)) for(auto i5 : range(5)) for(auto i6 : range(6)) { Real val = 0; for(auto i1 : range(m1)) for(auto i4 : range(4)) { val += A(i1,i2,i4,i5)*B(i3,i1,i4,i6); } CHECK_CLOSE(C(i3,i2,i5,i6),val); } } SECTION("Case 2: Bki Akj = C_ij") { int m1 = 10, m2 = 20, m3 = 30; Tensor A(m1,m2,4,5), B(m1,m3,4,6), C(m3,m2,5,6); randomize(A); randomize(B); contractloop(A,{1,2,4,5},B,{1,3,4,6},C,{3,2,5,6}); for(auto i2 : range(m2)) for(auto i3 : range(m3)) for(auto i5 : range(5)) for(auto i6 : range(6)) { Real val = 0; for(auto i1 : range(m1)) for(auto i4 : range(4)) { val += A(i1,i2,i4,i5)*B(i1,i3,i4,i6); } CHECK_CLOSE(C(i3,i2,i5,i6),val); } } SECTION("Case 3: Aki Bjk = Cij") { int m1 = 10, m2 = 20, m3 = 30; Tensor A(m1,m2,4,5), B(m3,m1,4,6), C(m2,m3,5,6); randomize(A); randomize(B); contractloop(A,{1,2,4,5},B,{3,1,4,6},C,{2,3,5,6}); for(auto i2 : range(m2)) for(auto i3 : range(m3)) for(auto i5 : range(5)) for(auto i6 : range(6)) { Real val = 0; for(auto i1 : range(m1)) for(auto i4 : range(4)) { val += A(i1,i2,i4,i5)*B(i3,i1,i4,i6); } CHECK_CLOSE(C(i2,i3,i5,i6),val); } } SECTION("Case 4: Aki Bkj = Cij") { int m1 = 10, m2 = 20, m3 = 30; Tensor A(m1,m2,4,5), B(m1,m3,4,6), C(m2,m3,5,6); randomize(A); randomize(B); contractloop(A,{1,2,4,5},B,{1,3,4,6},C,{2,3,5,6}); for(auto i2 : range(m2)) for(auto i3 : range(m3)) for(auto i5 : range(5)) for(auto i6 : range(6)) { Real val = 0; for(auto i1 : range(m1)) for(auto i4 : range(4)) { val += A(i1,i2,i4,i5)*B(i1,i3,i4,i6); } CHECK_CLOSE(C(i2,i3,i5,i6),val); } } SECTION("Case 5: Bik Ajk = Cij") { int m1 = 10, m2 = 20, m3 = 30; Tensor A(m3,m1,4,5), B(m2,m1,4,6), C(m2,m3,5,6); randomize(A); randomize(B); contractloop(A,{3,1,4,5},B,{2,1,4,6},C,{2,3,5,6}); for(auto i2 : range(m2)) for(auto i3 : range(m3)) for(auto i5 : range(5)) for(auto i6 : range(6)) { Real val = 0; for(auto i1 : range(m1)) for(auto i4 : range(4)) { val += A(i3,i1,i4,i5)*B(i2,i1,i4,i6); } CHECK_CLOSE(C(i2,i3,i5,i6),val); } } SECTION("Case 6: Aik Bjk = Cij") { int m1 = 10, m2 = 20, m3 = 30; Tensor A(m2,m1,4,5), B(m3,m1,4,6), C(m2,m3,5,6); randomize(A); randomize(B); contractloop(A,{2,1,4,5},B,{3,1,4,6},C,{2,3,5,6}); for(auto i2 : range(m2)) for(auto i3 : range(m3)) for(auto i5 : range(5)) for(auto i6 : range(6)) { Real val = 0; for(auto i1 : range(m1)) for(auto i4 : range(4)) { val += A(i2,i1,i4,i5)*B(i3,i1,i4,i6); } CHECK_CLOSE(C(i2,i3,i5,i6),val); } } SECTION("Case 7: Bki Ajk = Cij") { int m1 = 10, m2 = 20, m3 = 30; Tensor A(m3,m1,4,5), B(m1,m2,4,6), C(m2,m3,5,6); randomize(A); randomize(B); contractloop(A,{3,1,4,5},B,{1,2,4,6},C,{2,3,5,6}); for(auto i2 : range(m2)) for(auto i3 : range(m3)) for(auto i5 : range(5)) for(auto i6 : range(6)) { Real val = 0; for(auto i1 : range(m1)) for(auto i4 : range(4)) { val += A(i3,i1,i4,i5)*B(i1,i2,i4,i6); } CHECK_CLOSE(C(i2,i3,i5,i6),val); } Tensor Ap(m2,m1,4,5), Bp(m1,m3,4,6), Cp(m3,m2,5,6); randomize(A); randomize(B); contractloop(Ap,{2,1,4,5},Bp,{1,3,4,6},Cp,{3,2,5,6}); for(auto i2 : range(m2)) for(auto i3 : range(m3)) for(auto i5 : range(5)) for(auto i6 : range(6)) { Real val = 0; for(auto i1 : range(m1)) for(auto i4 : range(4)) { val += Ap(i2,i1,i4,i5)*Bp(i1,i3,i4,i6); } CHECK_CLOSE(Cp(i3,i2,i5,i6),val); } } SECTION("Case 8: Aik Bkj = Cij") { int m1 = 10, m2 = 20, m3 = 30; Tensor A(m2,m1,4,5), B(m1,m3,4,6), C(m2,m3,5,6); randomize(A); randomize(B); contractloop(A,{2,1,4,5},B,{1,3,4,6},C,{2,3,5,6}); for(auto i2 : range(m2)) for(auto i3 : range(m3)) for(auto i5 : range(5)) for(auto i6 : range(6)) { Real val = 0; for(auto i1 : range(m1)) for(auto i4 : range(4)) { val += A(i2,i1,i4,i5)*B(i1,i3,i4,i6); } CHECK_CLOSE(C(i2,i3,i5,i6),val); } } //#define DO_TIMING #ifdef DO_TIMING SECTION("Timing") { int m1 = 100, m2 = 200, m3 = 30, m4 = 4, m5 = 5, m6 = 6; Tensor A(m1,m2,m4,m5), B(m1,m3,m4,m6), C(m2,m3,m5,m6); randomize(A); randomize(B); cpu_time cpu; contractloop(A,{1,2,4,5},B,{1,3,4,6},C,{2,3,5,6}); println("Time = ",cpu.sincemark()); for(auto i2 : range(m2)) for(auto i3 : range(m3)) for(auto i5 : range(5)) for(auto i6 : range(6)) { Real val = 0; for(auto i1 : range(m1)) for(auto i4 : range(4)) { val += A(i1,i2,i4,i5)*B(i1,i3,i4,i6); } CHECK_CLOSE(C(i2,i3,i5,i6),val); } } #endif } // Contract Loop }
29.224874
97
0.31505
[ "vector" ]
d6bbb3847504fa51b7a5a097315614a59dac06b4
487
hpp
C++
core/src/runtime/object/class_obj.hpp
moe-org/zscript
4722fa7c55edbc959efa8988e96995ec3f4a3537
[ "MIT" ]
null
null
null
core/src/runtime/object/class_obj.hpp
moe-org/zscript
4722fa7c55edbc959efa8988e96995ec3f4a3537
[ "MIT" ]
null
null
null
core/src/runtime/object/class_obj.hpp
moe-org/zscript
4722fa7c55edbc959efa8988e96995ec3f4a3537
[ "MIT" ]
null
null
null
//* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // this file is under MIT License. // See https://opensource.org/licenses/MIT for license information. // Copyright (c) 2020-2022 moe-org All rights reserved. //* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * #pragma once #include "object.hpp" #include "map_obj.hpp" namespace zscript { ZSCRIPT_OBJECT_HEADER ClassObject{ ObjectBase head{}; MapObject* value{ nullptr }; }; }
25.631579
75
0.50308
[ "object" ]
d6bc9b46e6a90dd4db24dc5534c23bcb346b17f2
719
cc
C++
CondFormats/CSCObjects/src/CSCBadChambers.cc
nistefan/cmssw
ea13af97f7f2117a4f590a5e654e06ecd9825a5b
[ "Apache-2.0" ]
3
2018-08-24T19:10:26.000Z
2019-02-19T11:45:32.000Z
CondFormats/CSCObjects/src/CSCBadChambers.cc
nistefan/cmssw
ea13af97f7f2117a4f590a5e654e06ecd9825a5b
[ "Apache-2.0" ]
3
2018-08-23T13:40:24.000Z
2019-12-05T21:16:03.000Z
CondFormats/CSCObjects/src/CSCBadChambers.cc
nistefan/cmssw
ea13af97f7f2117a4f590a5e654e06ecd9825a5b
[ "Apache-2.0" ]
5
2018-08-21T16:37:52.000Z
2020-01-09T13:33:17.000Z
#include "CondFormats/CSCObjects/interface/CSCBadChambers.h" #include <algorithm> bool CSCBadChambers::isInBadChamber( IndexType ichamber ) const { if ( numberOfChambers() == 0 ) return false; std::vector<int>::const_iterator badbegin = chambers.begin(); std::vector<int>::const_iterator badend = chambers.end(); std::vector<int>::const_iterator it = std::find( badbegin, badend, ichamber ); if ( it != badend ) return true; // ichamber is in the list of bad chambers else return false; } bool CSCBadChambers::isInBadChamber( const CSCDetId& id ) const { if ( numberOfChambers() == 0 ) return false; return isInBadChamber( chamberIndex( id.endcap(), id.station(), id.ring(), id.chamber() ) ); }
34.238095
94
0.7121
[ "vector" ]
d6c0befe7bec34d6d273993361bd4fbe0a478f65
14,761
cpp
C++
test/se2/gtest_se2_map.cpp
mindbeast/manif
8b4fdc3c18fe3f98cf60bb9a405f2bb393bd6a40
[ "MIT" ]
876
2019-01-15T19:04:25.000Z
2022-03-29T21:52:12.000Z
test/se2/gtest_se2_map.cpp
mindbeast/manif
8b4fdc3c18fe3f98cf60bb9a405f2bb393bd6a40
[ "MIT" ]
191
2019-01-17T17:14:18.000Z
2022-03-21T09:08:26.000Z
test/se2/gtest_se2_map.cpp
mindbeast/manif
8b4fdc3c18fe3f98cf60bb9a405f2bb393bd6a40
[ "MIT" ]
148
2019-01-17T12:50:08.000Z
2022-03-27T15:24:00.000Z
#include <gtest/gtest.h> #include "../common_tester.h" #include "manif/SE2.h" using namespace manif; TEST(TEST_SE2, TEST_SE2_MAP_CONSTRUCTOR) { double data[4] = {4,2,-1,0}; Eigen::Map<SE2d> se2(data); EXPECT_DOUBLE_EQ(4, se2.x()); EXPECT_DOUBLE_EQ(2, se2.y()); EXPECT_DOUBLE_EQ(MANIF_PI, se2.angle()); } TEST(TEST_SE2, TEST_SE2_MAP_COEFFS) { double data[4] = {4,2,1,0}; Eigen::Map<SE2d> se2(data); EXPECT_DOUBLE_EQ(4, se2.coeffs()(0)); EXPECT_DOUBLE_EQ(2, se2.coeffs()(1)); EXPECT_DOUBLE_EQ(1, se2.coeffs()(2)); EXPECT_DOUBLE_EQ(0, se2.coeffs()(3)); } TEST(TEST_SE2, TEST_SE2_MAP_DATA) { double data[4] = {4,2,1,0}; Eigen::Map<SE2d> se2(data); double * data_ptr = se2.data(); ASSERT_NE(nullptr, data_ptr); EXPECT_EQ(data, data_ptr); EXPECT_DOUBLE_EQ(4, *data_ptr); ++data_ptr; EXPECT_DOUBLE_EQ(2, *data_ptr); ++data_ptr; EXPECT_DOUBLE_EQ(1, *data_ptr); ++data_ptr; EXPECT_DOUBLE_EQ(0, *data_ptr); } TEST(TEST_SE2, TEST_SE2_MAP_CAST) { double data[4] = {4,2,-1,0}; Eigen::Map<SE2d> se2d(data); EXPECT_DOUBLE_EQ(4, se2d.x()); EXPECT_DOUBLE_EQ(2, se2d.y()); EXPECT_DOUBLE_EQ(MANIF_PI, se2d.angle()); SE2f se2f = se2d.cast<float>(); EXPECT_FLOAT_EQ(4, se2f.x()); EXPECT_FLOAT_EQ(2, se2f.y()); EXPECT_FLOAT_EQ(MANIF_PI, se2f.angle()); } TEST(TEST_SE2, TEST_SE2_MAP_IDENTITY) { double data[4] = {4,2,1,0}; Eigen::Map<SE2d> se2(data); se2.setIdentity(); EXPECT_DOUBLE_EQ(0, se2.x()); EXPECT_DOUBLE_EQ(0, se2.y()); EXPECT_DOUBLE_EQ(0, se2.angle()); EXPECT_DOUBLE_EQ(0, data[0]); EXPECT_DOUBLE_EQ(0, data[1]); EXPECT_DOUBLE_EQ(1, data[2]); EXPECT_DOUBLE_EQ(0, data[3]); } TEST(TEST_SE2, TEST_SE2_MAP_IDENTITY2) { double data[4] = {4,2,1,0}; Eigen::Map<SE2d> se2(data); se2 = SE2d::Identity(); EXPECT_DOUBLE_EQ(0, se2.x()); EXPECT_DOUBLE_EQ(0, se2.y()); EXPECT_DOUBLE_EQ(0, se2.angle()); EXPECT_DOUBLE_EQ(0, data[0]); EXPECT_DOUBLE_EQ(0, data[1]); EXPECT_DOUBLE_EQ(1, data[2]); EXPECT_DOUBLE_EQ(0, data[3]); } TEST(TEST_SE2, TEST_SE2_MAP_RANDOM) { double data[4] = {4,2,1,0}; Eigen::Map<SE2d> se2(data); se2.setRandom(); const auto complex = se2.coeffs().block<2,1>(2,0); EXPECT_DOUBLE_EQ(1, complex.norm()); } TEST(TEST_SE2, TEST_SE2_MAP_RANDOM2) { double data[4] = {4,2,1,0}; Eigen::Map<SE2d> se2(data); se2 = SE2d::Random(); const auto complex = se2.coeffs().block<2,1>(2,0); EXPECT_DOUBLE_EQ(1, complex.norm()); } TEST(TEST_SE2, TEST_SE2_MAP_MATRIX) { double data[4] = {4,2,1,0}; Eigen::Map<SE2d> se2(data); SE2d::Transformation t = se2.transform(); EXPECT_EQ(3, t.rows()); EXPECT_EQ(3, t.cols()); /// @todo Eigen matrix comparison } TEST(TEST_SE2, TEST_SE2_MAP_ROTATION) { double data[4] = {4,2,1,0}; Eigen::Map<SE2d> se2(data); SE2d::Rotation r = se2.rotation(); EXPECT_EQ(2, r.rows()); EXPECT_EQ(2, r.cols()); /// @todo Eigen matrix comparison } TEST(TEST_SE2, TEST_SE2_MAP_ASSIGN_OP) { double dataa[4] = {4,2,1,0}; Eigen::Map<SE2d> se2a(dataa); double datab[4] = {-4,-2,-1,0}; Eigen::Map<SE2d>se2b(datab); se2a = se2b; EXPECT_DOUBLE_EQ(-4, se2a.x()); EXPECT_DOUBLE_EQ(-2, se2a.y()); EXPECT_ANGLE_NEAR(-MANIF_PI, se2a.angle(), 1e-15); EXPECT_DOUBLE_EQ(datab[0], dataa[0]); EXPECT_DOUBLE_EQ(datab[1], dataa[1]); EXPECT_DOUBLE_EQ(datab[2], dataa[2]); EXPECT_DOUBLE_EQ(datab[3], dataa[3]); } TEST(TEST_SE2, TEST_SE2_MAP_INVERSE) { double data[4] = {0,0,1,0}; Eigen::Map<SE2d> se2(data); auto se2_inv = se2.inverse(); EXPECT_DOUBLE_EQ(0, se2_inv.x()); EXPECT_DOUBLE_EQ(0, se2_inv.y()); EXPECT_DOUBLE_EQ(0, se2_inv.angle()); EXPECT_DOUBLE_EQ(1, se2_inv.real()); EXPECT_DOUBLE_EQ(0, se2_inv.imag()); se2 = SE2d(1, 1, MANIF_PI); se2_inv = se2.inverse(); EXPECT_DOUBLE_EQ( 1, se2_inv.x()); EXPECT_DOUBLE_EQ( 1, se2_inv.y()); EXPECT_ANGLE_NEAR(-MANIF_PI, se2_inv.angle(), 1e-15); EXPECT_DOUBLE_EQ(-1, se2_inv.real()); EXPECT_NEAR(0, se2_inv.imag(), 1e-15); se2 = SE2d(0.7, 2.3, MANIF_PI/3.); se2_inv = se2.inverse(); EXPECT_DOUBLE_EQ(-2.341858428704209, se2_inv.x()); EXPECT_DOUBLE_EQ(-0.543782217350893, se2_inv.y()); EXPECT_ANGLE_NEAR(-1.04719755119660, se2_inv.angle(), 3e-15); } TEST(TEST_SE2, TEST_SE2_MAP_RPLUS_ZERO) { double data[4] = {1,1,-1,0}; Eigen::Map<SE2d> se2(data); SE2Tangentd se2t(0, 0, 0); auto se2c = se2.rplus(se2t); EXPECT_DOUBLE_EQ(1, se2c.x()); EXPECT_DOUBLE_EQ(1, se2c.y()); EXPECT_ANGLE_NEAR(-MANIF_PI, se2c.angle(), 1e-15); } /* TEST(TEST_SE2, TEST_SE2_MAP_RPLUS) { Eigen::Map<SE2d> se2a(1, 1, MANIF_PI / 2.); SE2Tangentd se2b(1, 1, MANIF_PI / 2.); auto se2c = se2a.rplus(se2b); /// @todo what to expect here ?? :S // EXPECT_DOUBLE_EQ(0, se2c.x()); // EXPECT_DOUBLE_EQ(2, se2c.y()); EXPECT_DOUBLE_EQ(MANIF_PI, se2c.angle()); } TEST(TEST_SE2, TEST_SE2_MAP_LPLUS_ZERO) { Eigen::Map<SE2d>se2a(1, 1, MANIF_PI / 2.); SE2Tangentd se2b(0, 0, 0); auto se2c = se2a.lplus(se2b); EXPECT_DOUBLE_EQ(1, se2c.x()); EXPECT_DOUBLE_EQ(1, se2c.y()); EXPECT_DOUBLE_EQ(MANIF_PI / 2., se2c.angle()); } TEST(TEST_SE2, TEST_SE2_MAP_LPLUS) { Eigen::Map<SE2d>se2a(1, 1, MANIF_PI / 2.); SE2Tangentd se2b(1, 1, MANIF_PI / 2.); auto se2c = se2a.lplus(se2b); /// @todo what to expect here ?? :S // EXPECT_DOUBLE_EQ(1, se2c.x()); // EXPECT_DOUBLE_EQ(1, se2c.y()); EXPECT_DOUBLE_EQ(MANIF_PI, se2c.angle()); } TEST(TEST_SE2, TEST_SE2_MAP_PLUS) { Eigen::Map<SE2d>se2a(1, 1, MANIF_PI / 2.); SE2Tangentd se2b(1, 1, MANIF_PI / 2.); auto se2c = se2a.plus(se2b); /// @todo what to expect here ?? :S // EXPECT_DOUBLE_EQ(0, se2c.x()); // EXPECT_DOUBLE_EQ(2, se2c.y()); EXPECT_DOUBLE_EQ(MANIF_PI, se2c.angle()); } TEST(TEST_SE2, TEST_SE2_MAP_OP_PLUS) { Eigen::Map<SE2d>se2a(1, 1, MANIF_PI / 2.); SE2Tangentd se2b(1, 1, MANIF_PI / 2.); auto se2c = se2a + se2b; /// @todo what to expect here ?? :S // EXPECT_DOUBLE_EQ(0, se2c.x()); // EXPECT_DOUBLE_EQ(2, se2c.y()); EXPECT_DOUBLE_EQ(MANIF_PI, se2c.angle()); } TEST(TEST_SE2, TEST_SE2_MAP_OP_PLUS_EQ) { Eigen::Map<SE2d>se2a(1, 1, MANIF_PI / 2.); SE2Tangentd se2b(1, 1, MANIF_PI / 2.); se2a += se2b; /// @todo what to expect here ?? :S // EXPECT_DOUBLE_EQ(0, se2a.x()); // EXPECT_DOUBLE_EQ(2, se2a.y()); EXPECT_DOUBLE_EQ(MANIF_PI, se2a.angle()); } TEST(TEST_SE2, TEST_SE2_MAP_RMINUS_ZERO) { Eigen::Map<SE2d>se2a(0, 0, 0); Eigen::Map<SE2d>se2b(0, 0, 0); auto se2c = se2a.rminus(se2b); // EXPECT_DOUBLE_EQ(0, se2c.x()); EXPECT_NEAR(0, se2c.x(), 1e-15); // EXPECT_DOUBLE_EQ(0, se2c.y()); EXPECT_NEAR(0, se2c.y(), 1e-15); EXPECT_DOUBLE_EQ(0, se2c.angle()); } TEST(TEST_SE2, TEST_SE2_MAP_RMINUS_I) { Eigen::Map<SE2d>se2a(1, 1, MANIF_PI); Eigen::Map<SE2d>se2b(1, 1, MANIF_PI); auto se2c = se2a.rminus(se2b); /// @todo // EXPECT_DOUBLE_EQ(0, se2c.x()); // EXPECT_NEAR(0, se2c.x(), 1e-15); // EXPECT_DOUBLE_EQ(0, se2c.y()); // EXPECT_NEAR(0, se2c.y(), 1e-15); EXPECT_DOUBLE_EQ(0, se2c.angle()); } TEST(TEST_SE2, TEST_SE2_MAP_RMINUS) { Eigen::Map<SE2d>se2a(1, 1, MANIF_PI); Eigen::Map<SE2d>se2b(2, 2, MANIF_PI_2); auto se2c = se2a.rminus(se2b); /// @todo // EXPECT_DOUBLE_EQ(1, se2c.x()); // EXPECT_DOUBLE_EQ(1, se2c.y()); EXPECT_DOUBLE_EQ(MANIF_PI_2, se2c.angle()); } TEST(TEST_SE2, TEST_SE2_MAP_LMINUS_IDENTITY) { Eigen::Map<SE2d>se2a(0,0,0); Eigen::Map<SE2d>se2b(0,0,0); auto se2c = se2a.lminus(se2b); /// @todo EXPECT_DOUBLE_EQ(0, se2c.x()); EXPECT_DOUBLE_EQ(0, se2c.y()); EXPECT_DOUBLE_EQ(0, se2c.angle()); } TEST(TEST_SE2, TEST_SE2_MAP_LMINUS) { Eigen::Map<SE2d>se2a(1,1,MANIF_PI); Eigen::Map<SE2d>se2b(2,2,MANIF_PI_2); auto se2c = se2a.lminus(se2b); /// @todo // EXPECT_DOUBLE_EQ(0, se2c.x()); // EXPECT_DOUBLE_EQ(0, se2c.y()); EXPECT_DOUBLE_EQ(-MANIF_PI_2, se2c.angle()); } TEST(TEST_SE2, TEST_SE2_MAP_MINUS) { Eigen::Map<SE2d>se2a(1, 1, MANIF_PI); Eigen::Map<SE2d>se2b(2, 2, MANIF_PI_2); auto se2c = se2a.minus(se2b); /// @todo // EXPECT_DOUBLE_EQ(1, se2c.x()); // EXPECT_DOUBLE_EQ(1, se2c.y()); EXPECT_DOUBLE_EQ(MANIF_PI_2, se2c.angle()); } TEST(TEST_SE2, TEST_SE2_MAP_LIFT) { Eigen::Map<SE2d>se2(1,1,MANIF_PI); auto se2_log = se2.log(); /// @todo // EXPECT_DOUBLE_EQ(1, se2_log.x()); // EXPECT_DOUBLE_EQ(1, se2_log.y()); EXPECT_DOUBLE_EQ(MANIF_PI, se2_log.angle()); } TEST(TEST_SE2, TEST_SE2_MAP_COMPOSE) { Eigen::Map<SE2d>se2a(1,1,MANIF_PI_2); Eigen::Map<SE2d>se2b(2,2,MANIF_PI_2); auto se2c = se2a.compose(se2b); EXPECT_DOUBLE_EQ(-1, se2c.x()); EXPECT_DOUBLE_EQ(+3, se2c.y()); EXPECT_DOUBLE_EQ(MANIF_PI, se2c.angle()); } TEST(TEST_SE2, TEST_SE2_MAP_OP_COMPOSE) { Eigen::Map<SE2d>se2a(1,1,MANIF_PI_2); Eigen::Map<SE2d>se2b(2,2,MANIF_PI_2); auto se2c = se2a * se2b; EXPECT_DOUBLE_EQ(-1, se2c.x()); EXPECT_DOUBLE_EQ(+3, se2c.y()); EXPECT_DOUBLE_EQ(MANIF_PI, se2c.angle()); } TEST(TEST_SE2, TEST_SE2_MAP_OP_COMPOSE_EQ) { Eigen::Map<SE2d>se2a(1,1,MANIF_PI_2); Eigen::Map<SE2d>se2b(2,2,MANIF_PI_2); se2a *= se2b; EXPECT_DOUBLE_EQ(-1, se2a.x()); EXPECT_DOUBLE_EQ(+3, se2a.y()); EXPECT_DOUBLE_EQ(MANIF_PI, se2a.angle()); } TEST(TEST_SE2, TEST_SE2_MAP_BETWEEN_I) { Eigen::Map<SE2d>se2a(1,1,MANIF_PI); Eigen::Map<SE2d>se2b(1,1,MANIF_PI); auto se2c = se2a.between(se2b); EXPECT_DOUBLE_EQ(0, se2c.x()); EXPECT_DOUBLE_EQ(0, se2c.y()); EXPECT_DOUBLE_EQ(0, se2c.angle()); } TEST(TEST_SE2, TEST_SE2_MAP_BETWEEN) { Eigen::Map<SE2d>se2a(1,1,MANIF_PI); Eigen::Map<SE2d>se2b(2,2,MANIF_PI_2); auto se2c = se2a.between(se2b); EXPECT_DOUBLE_EQ(-1, se2c.x()); EXPECT_DOUBLE_EQ(-1, se2c.y()); EXPECT_DOUBLE_EQ(-MANIF_PI_2, se2c.angle()); } */ /* /// with Jacs TEST(TEST_SE2, TEST_SE2_MAP_INVERSE_JAC) { Eigen::Map<SE2d>se2 = SE2d::Identity(); Eigen::Map<SE2d>se2_inv; SE2d::Jacobian J_inv; se2.inverse(se2_inv, J_inv); EXPECT_DOUBLE_EQ(se2.angle(), se2_inv.angle()); EXPECT_DOUBLE_EQ(1, se2_inv.real()); EXPECT_DOUBLE_EQ(0, se2_inv.imag()); EXPECT_EQ(1, J_inv.rows()); EXPECT_EQ(1, J_inv.cols()); EXPECT_DOUBLE_EQ(-1, J_inv(0)); se2 = SE2d(MANIF_PI); se2.inverse(se2_inv, J_inv); EXPECT_DOUBLE_EQ(-MANIF_PI, se2_inv.angle()); EXPECT_EQ(1, J_inv.rows()); EXPECT_EQ(1, J_inv.cols()); EXPECT_DOUBLE_EQ(-1, J_inv(0)); } TEST(TEST_SE2, TEST_SE2_MAP_LIFT_JAC) { Eigen::Map<SE2d>se2(MANIF_PI); SE2d::Tangent se2_log; SE2d::Tangent::Jacobian J_log; se2.log(se2_log, J_log); EXPECT_DOUBLE_EQ(MANIF_PI, se2_log.angle()); /// @todo check this J EXPECT_EQ(1, J_log.rows()); EXPECT_EQ(1, J_log.cols()); EXPECT_DOUBLE_EQ(1, J_log(0)); } TEST(TEST_SE2, TEST_SE2_MAP_COMPOSE_JAC) { Eigen::Map<SE2d>se2a(MANIF_PI_2); Eigen::Map<SE2d>se2b(MANIF_PI_2); Eigen::Map<SE2d>se2c; SE2d::Jacobian J_c_a, J_c_b; se2a.compose(se2b, se2c, J_c_a, J_c_b); EXPECT_DOUBLE_EQ(MANIF_PI, se2c.angle()); EXPECT_EQ(1, J_c_a.rows()); EXPECT_EQ(1, J_c_a.cols()); EXPECT_DOUBLE_EQ(1, J_c_a(0)); EXPECT_EQ(1, J_c_b.rows()); EXPECT_EQ(1, J_c_b.cols()); EXPECT_DOUBLE_EQ(1, J_c_b(0)); } TEST(TEST_SE2, TEST_SE2_MAP_RPLUS_JAC) { Eigen::Map<SE2d>se2a(MANIF_PI / 2.); SE2Tangentd se2b(MANIF_PI / 2.); Eigen::Map<SE2d>se2c; SE2d::Jacobian J_rplus_m; SE2d::Jacobian J_rplus_t; se2a.rplus(se2b, se2c, J_rplus_m, J_rplus_t); EXPECT_DOUBLE_EQ(MANIF_PI, se2c.angle()); EXPECT_EQ(1, J_rplus_m.rows()); EXPECT_EQ(1, J_rplus_m.cols()); EXPECT_DOUBLE_EQ(1, J_rplus_m(0)); EXPECT_EQ(1, J_rplus_t.rows()); EXPECT_EQ(1, J_rplus_t.cols()); EXPECT_DOUBLE_EQ(1, J_rplus_t(0)); } TEST(TEST_SE2, TEST_SE2_MAP_LPLUS_JAC) { Eigen::Map<SE2d>se2a(MANIF_PI / 2.); SE2Tangentd se2b(MANIF_PI / 2.); Eigen::Map<SE2d>se2c; SE2d::Jacobian J_lplus_t; SE2d::Jacobian J_lplus_m; se2a.lplus(se2b, se2c, J_lplus_t, J_lplus_m); EXPECT_DOUBLE_EQ(MANIF_PI, se2c.angle()); EXPECT_EQ(1, J_lplus_t.rows()); EXPECT_EQ(1, J_lplus_t.cols()); EXPECT_DOUBLE_EQ(1, J_lplus_t(0)); EXPECT_EQ(1, J_lplus_m.rows()); EXPECT_EQ(1, J_lplus_m.cols()); EXPECT_DOUBLE_EQ(1, J_lplus_m(0)); } TEST(TEST_SE2, TEST_SE2_MAP_PLUS_JAC) { Eigen::Map<SE2d>se2a(MANIF_PI / 2.); SE2Tangentd se2b(MANIF_PI / 2.); Eigen::Map<SE2d>se2c; SE2d::Jacobian J_plus_m; SE2d::Jacobian J_plus_t; se2a.plus(se2b, se2c, J_plus_m, J_plus_t); EXPECT_DOUBLE_EQ(MANIF_PI, se2c.angle()); EXPECT_EQ(1, J_plus_m.rows()); EXPECT_EQ(1, J_plus_m.cols()); EXPECT_DOUBLE_EQ(1, J_plus_m(0)); EXPECT_EQ(1, J_plus_t.rows()); EXPECT_EQ(1, J_plus_t.cols()); EXPECT_DOUBLE_EQ(1, J_plus_t(0)); } TEST(TEST_SE2, TEST_SE2_MAP_RMINUS_JAC) { Eigen::Map<SE2d>se2a(MANIF_PI); Eigen::Map<SE2d>se2b(MANIF_PI_2); SE2Tangentd se2c; SE2d::Jacobian J_rminus_a, J_rminus_b; se2a.rminus(se2b, se2c, J_rminus_a, J_rminus_b); EXPECT_DOUBLE_EQ(MANIF_PI_2, se2c.angle()); EXPECT_EQ(1, J_rminus_a.rows()); EXPECT_EQ(1, J_rminus_a.cols()); EXPECT_DOUBLE_EQ(1, J_rminus_a(0)); EXPECT_EQ(1, J_rminus_b.rows()); EXPECT_EQ(1, J_rminus_b.cols()); EXPECT_DOUBLE_EQ(-1, J_rminus_b(0)); } TEST(TEST_SE2, TEST_SE2_MAP_LMINUS_JAC) { Eigen::Map<SE2d>se2a(MANIF_PI); Eigen::Map<SE2d>se2b(MANIF_PI_2); SE2Tangentd se2c; SE2d::Jacobian J_lminus_a, J_lminus_b; se2a.lminus(se2b, se2c, J_lminus_a, J_lminus_b); EXPECT_DOUBLE_EQ(-MANIF_PI_2, se2c.angle()); EXPECT_EQ(1, J_lminus_a.rows()); EXPECT_EQ(1, J_lminus_a.cols()); EXPECT_DOUBLE_EQ(-1, J_lminus_a(0)); EXPECT_EQ(1, J_lminus_b.rows()); EXPECT_EQ(1, J_lminus_b.cols()); EXPECT_DOUBLE_EQ(1, J_lminus_b(0)); } TEST(TEST_SE2, TEST_SE2_MAP_MINUS_JAC) { Eigen::Map<SE2d>se2a(MANIF_PI); Eigen::Map<SE2d>se2b(MANIF_PI_2); SE2Tangentd se2c; SE2d::Jacobian J_minus_a, J_minus_b; se2a.minus(se2b, se2c, J_minus_a, J_minus_b); EXPECT_DOUBLE_EQ(MANIF_PI_2, se2c.angle()); EXPECT_EQ(1, J_minus_a.rows()); EXPECT_EQ(1, J_minus_a.cols()); EXPECT_DOUBLE_EQ(1, J_minus_a(0)); EXPECT_EQ(1, J_minus_b.rows()); EXPECT_EQ(1, J_minus_b.cols()); EXPECT_DOUBLE_EQ(-1, J_minus_b(0)); } TEST(TEST_SE2, TEST_SE2_MAP_BETWEEN_JAC) { Eigen::Map<SE2d>se2a(MANIF_PI); Eigen::Map<SE2d>se2b(MANIF_PI_2); SE2d::Jacobian J_between_a, J_between_b; Eigen::Map<SE2d>se2c; se2a.between(se2b, se2c, J_between_a, J_between_b); EXPECT_DOUBLE_EQ(-MANIF_PI_2, se2c.angle()); EXPECT_EQ(1, J_between_a.rows()); EXPECT_EQ(1, J_between_a.cols()); EXPECT_DOUBLE_EQ(-1, J_between_a(0)); EXPECT_EQ(1, J_between_b.rows()); EXPECT_EQ(1, J_between_b.cols()); EXPECT_DOUBLE_EQ(1, J_between_b(0)); } */ int main(int argc, char** argv) { testing::InitGoogleTest(&argc, argv); // ::testing::GTEST_FLAG(filter) = "TEST_SE2.TEST_SE2_MAP_INVERSE"; return RUN_ALL_TESTS(); }
21.99851
68
0.676174
[ "transform" ]
d6c0bfe7f543340fd3a954c920d756f2419c45f7
464
cpp
C++
triangle/triangle.cpp
aydinsimsek/exercism-solutions-cpp
6d7c8d37f628840559509d7f6e5b7788c8c637b6
[ "MIT" ]
1
2022-02-04T19:22:58.000Z
2022-02-04T19:22:58.000Z
triangle/triangle.cpp
aydinsimsek/exercism-solutions-cpp
6d7c8d37f628840559509d7f6e5b7788c8c637b6
[ "MIT" ]
null
null
null
triangle/triangle.cpp
aydinsimsek/exercism-solutions-cpp
6d7c8d37f628840559509d7f6e5b7788c8c637b6
[ "MIT" ]
null
null
null
#include "triangle.h" #include <stdexcept> using namespace std; namespace triangle { int kind(double a, double b, double c) { if (a <= 0 || b <= 0 || c <= 0 || a + b < c || a + c < b || b + c < a) { throw domain_error("This shape is not a triangle"); } if (a == b && b == c) { return 0; } else if (a == b || a == c || b == c) { return 1; } else if (a != b && a != c && b != c) { return 2; } } } // namespace triangle
17.185185
72
0.471983
[ "shape" ]
d6c4332d9634fe62bec4412e75dc5e31cf71abd8
3,182
cpp
C++
codes/CSES/CSES_2111.cpp
chessbot108/solved-problems
0945be829a8ea9f0d5896c89331460d70d076691
[ "MIT" ]
null
null
null
codes/CSES/CSES_2111.cpp
chessbot108/solved-problems
0945be829a8ea9f0d5896c89331460d70d076691
[ "MIT" ]
null
null
null
codes/CSES/CSES_2111.cpp
chessbot108/solved-problems
0945be829a8ea9f0d5896c89331460d70d076691
[ "MIT" ]
null
null
null
//chtholly and emilia will carry me to cm #include <complex> #include <iostream> #include <cstdio> #include <cstring> #include <cstdlib> #include <string> #include <utility> #include <cassert> #include <algorithm> #include <vector> #include <random> #include <chrono> #include <queue> #include <set> #include <map> using namespace std; #define rep(i, a, b) for(int i = a; i < (b); ++i) #define all(x) begin(x), end(x) #define sz(x) (int)(x).size() #define ll __int128 #define lb long double #define lp std::complex<double> #define hsb(x) (31 - __builtin_clz(x)) const int D = 19; const int NN = (1 << D); const lb tau = 4.0 * acos(0); //this function returns the reversed version of x with b bits int rev(unsigned int x, int b){ //lots of trust x = (((x & 0xaaaaaaaa) >> 1) | ((x & 0x55555555) << 1)); x = (((x & 0xcccccccc) >> 2) | ((x & 0x33333333) << 2)); x = (((x & 0xf0f0f0f0) >> 4) | ((x & 0x0f0f0f0f) << 4)); x = (((x & 0xff00ff00) >> 8) | ((x & 0x00ff00ff) << 8)); //https://aticleworld.com/5-way-to-reverse-bits-of-an-integer/ method 4 return((x >> 16) | (x << 16)) >> (32 - b); } //evaluates the roots of unity of poly //if op == 1, reverses it as well vector<lp> halfft(const vector<lp>& poly, const vector<lp>& rt, int op = 0){ vector<lp> ans(sz(poly)); if(sz(poly) == 1){ ans[0] = poly[0]; return ans; } int p2 = hsb(sz(poly)); for(int i = 0; i<sz(poly); i++){ ans[rev(i, p2)] = poly[i]; } for(int k = 1, n = 2; k<=p2; k++, n *= 2){ for(int pos = 0; pos < sz(poly); pos += n){ for(int i = 0; i<n/2; i++){ int i1 = i, i2 = i + n/2; lp r1 = ans[pos + i] + rt[i1 * (1 << (p2 - k))] * ans[pos + n/2 + i]; lp r2 = ans[pos + i] + rt[i2 * (1 << (p2 - k))] * ans[pos + n/2 + i]; ans[pos + i1] = r1; ans[pos + i2] = r2; } } } if(op) //reverse the roots reverse(1 + all(ans)); return ans; } vector<lp> fft(const vector<int>& a, const vector<int>& b){ int s; for(s = 1; s<(sz(a) +sz(b)); s*=2); vector<lp> A(s, 0), B(s, 0), rt(s); for (int i = 0; i < sz(a); i++) { A[i] = a[i]; } for (int i = 0; i < sz(b); i++) { B[i] = b[i]; } for(int i = 0; i<s; i++){ rt[i] = exp(lp(0, tau*(lb)i/(lb)(s))); } //make the two size 2^k polynomials A and B vector<lp> aa = halfft(A, rt), bb = halfft(B, rt); //halfft A and B for(int i = 0; i<sz(aa); i++){ aa[i] *= bb[i]; //multiply them together } vector<lp> ans = halfft(aa, rt, 1); for(int i = 0; i<s; i++){ ans[i] /= (lb)s; //divide by s and write into the answer } ans.resize(sz(a) + sz(b) - 1); return ans; } signed main() { cin.tie(0)->sync_with_stdio(0); cin.exceptions(cin.failbit); signed n, m, k; cin >> k >> n >> m; //signed lg = (long)(ceil(log2(k+1))); vector<int> a(k + 1, 0), b(k + 1, 0); for(int i = 0; i<n; i++){ signed x; cin >> x; a[x] = a[x] + 1; } for(int i = 0; i<m; i++){ signed x; cin >> x; b[x] = b[x] + 1; } /** for(int i = 0; i<=k; i++){ cout << (long long)a[i] << " "; } cout << "\n"; for(int i = 0; i<=k; i++){ cout << (long long)b[i] << " "; } cout << "\n"; **/ vector<lp> ans = fft(a, b); for(int i = 2; i<=2*k; i++){ cout << (long long)(round(real(ans[i]))) << " "; } return 0; }
24.290076
76
0.529227
[ "vector" ]
d6d22e613ff06972216a971df43cf00b0103366c
19,989
cpp
C++
ext/Internal/api-handle.cpp
creativemindplus/skybison
d1740e08d8de85a0a56b650675717da67de171a0
[ "CNRI-Python-GPL-Compatible" ]
278
2021-08-31T00:46:51.000Z
2022-02-13T19:43:28.000Z
ext/Internal/api-handle.cpp
creativemindplus/skybison
d1740e08d8de85a0a56b650675717da67de171a0
[ "CNRI-Python-GPL-Compatible" ]
9
2021-11-05T22:28:43.000Z
2021-11-23T08:39:04.000Z
ext/Internal/api-handle.cpp
tekknolagi/skybison
bea8fc2af0a70e7203b4c19f36c14a745512a335
[ "CNRI-Python-GPL-Compatible" ]
12
2021-08-31T07:49:54.000Z
2021-10-08T01:09:01.000Z
// Copyright (c) Facebook, Inc. and its affiliates. (http://www.facebook.com) #include "api-handle.h" #include <cstdint> #include "cpython-data.h" #include "cpython-func.h" #include "cpython-types.h" #include "capi-state.h" #include "capi.h" #include "debugging.h" #include "event.h" #include "globals.h" #include "object-builtins.h" #include "objects.h" #include "runtime.h" #include "scavenger.h" #include "thread.h" #include "visitor.h" namespace py { static const int32_t kEmptyIndex = -1; static const int32_t kTombstoneIndex = -2; struct IndexProbe { word index; word mask; uword perturb; }; // Compute hash value suitable for `RawObject::operator==` (aka `a is b`) // equality tests. static inline uword handleHash(RawObject obj) { if (obj.isHeapObject()) { return obj.raw() >> kObjectAlignmentLog2; } return obj.raw(); } static int32_t indexAt(int32_t* indices, word index) { return indices[index]; } static void indexAtPut(int32_t* indices, word index, int32_t item_index) { indices[index] = item_index; } static void indexAtPutTombstone(int32_t* indices, word index) { indices[index] = kTombstoneIndex; } static void itemAtPut(RawObject* keys, void** values, int32_t index, RawObject key, void* value) { DCHECK(key != SmallInt::fromWord(0), "0 represents empty and tombstone"); DCHECK(value != nullptr, "key must be associated with a C-API handle"); keys[index] = key; values[index] = value; } static void itemAtPutTombstone(RawObject* keys, void** values, int32_t index) { keys[index] = SmallInt::fromWord(0); values[index] = nullptr; } static RawObject itemKeyAt(RawObject* keys, int32_t index) { return keys[index]; } static void* itemValueAt(void** values, int32_t index) { return values[index]; } static int32_t maxCapacity(word num_indices) { DCHECK(num_indices <= kMaxInt32, "cannot fit %ld indices into 4-byte int", num_indices); return static_cast<int32_t>((num_indices * 2) / 3); } static int32_t* newIndices(word num_indices) { word size = num_indices * sizeof(int32_t); void* result = std::malloc(size); DCHECK(result != nullptr, "malloc failed"); std::memset(result, -1, size); // fill with kEmptyIndex return reinterpret_cast<int32_t*>(result); } static RawObject* newKeys(int32_t capacity) { void* result = std::calloc(capacity, sizeof(RawObject)); DCHECK(result != nullptr, "malloc failed"); return reinterpret_cast<RawObject*>(result); } static void** newValues(int32_t capacity) { void* result = std::malloc(static_cast<size_t>(capacity) * kPointerSize); DCHECK(result != nullptr, "malloc failed"); return reinterpret_cast<void**>(result); } static bool nextItem(RawObject* keys, void** values, int32_t* idx, int32_t end, RawObject* key_out, void** value_out) { for (int32_t i = *idx; i < end; i++) { RawObject key = itemKeyAt(keys, i); if (key == SmallInt::fromWord(0)) continue; *key_out = key; *value_out = itemValueAt(values, i); *idx = i + 1; return true; } *idx = end; return false; } static IndexProbe probeBegin(word num_indices, uword hash) { DCHECK(num_indices > 0 && Utils::isPowerOfTwo(num_indices), "number of indices must be a power of two, got %ld", num_indices); word mask = num_indices - 1; return {static_cast<word>(hash) & mask, mask, hash}; } static void probeNext(IndexProbe* probe) { // Note that repeated calls to this function guarantee a permutation of all // indices when the number of indices is power of two. See // https://en.wikipedia.org/wiki/Linear_congruential_generator#c_%E2%89%A0_0. probe->perturb >>= 5; probe->index = (probe->index * 5 + 1 + probe->perturb) & probe->mask; } void* ApiHandleDict::at(RawObject key) { word index; int32_t item_index; if (lookup(key, &index, &item_index)) { return itemValueAt(values(), item_index); } return nullptr; } inline void* ApiHandleDict::atIndex(int32_t item_index) { return itemValueAt(values(), item_index); } void ApiHandleDict::atPut(RawObject key, void* value) { int32_t item_index; atPutLookup(key, &item_index); atPutValue(item_index, value); } ALWAYS_INLINE bool ApiHandleDict::atPutLookup(RawObject key, int32_t* item_index) { DCHECK(key != SmallInt::fromWord(0), "0 key not allowed (used for tombstone)"); uword hash = handleHash(key); int32_t* indices = this->indices(); RawObject* keys = this->keys(); word num_indices = this->numIndices(); word next_free_index = -1; for (IndexProbe probe = probeBegin(num_indices, hash);; probeNext(&probe)) { int32_t current_item_index = indexAt(indices, probe.index); if (current_item_index >= 0) { if (itemKeyAt(keys, current_item_index) == key) { *item_index = current_item_index; return false; } continue; } if (next_free_index == -1) { next_free_index = probe.index; } if (current_item_index == kEmptyIndex) { word new_item_index = nextIndex(); indexAtPut(indices, next_free_index, new_item_index); keys[new_item_index] = key; setNextIndex(new_item_index + 1); incrementNumItems(); *item_index = new_item_index; return true; } } } ALWAYS_INLINE void ApiHandleDict::atPutValue(int32_t item_index, void* value) { DCHECK(value != nullptr, "key cannot be associated with nullptr"); values()[item_index] = value; // Maintain the invariant that we have space for at least one more item. if (!hasUsableItem()) { grow(); } } NEVER_INLINE void ApiHandleDict::grow() { // If at least half of the items in the dense array are tombstones, removing // them will free up plenty of space. Otherwise, the dict must be grown. word growth_factor = (numItems() < capacity() / 2) ? 1 : kGrowthFactor; word new_num_indices = numIndices() * growth_factor; rehash(new_num_indices); DCHECK(hasUsableItem(), "dict must have space for another item"); } void ApiHandleDict::initialize(word num_indices) { setIndices(newIndices(num_indices)); setNumIndices(num_indices); int32_t capacity = maxCapacity(num_indices); setCapacity(capacity); setKeys(newKeys(capacity)); setValues(newValues(capacity)); } bool ApiHandleDict::lookup(RawObject key, word* sparse, int32_t* dense) { uword hash = handleHash(key); int32_t* indices = this->indices(); RawObject* keys = this->keys(); word num_indices = this->numIndices(); for (IndexProbe probe = probeBegin(num_indices, hash);; probeNext(&probe)) { int32_t item_index = indexAt(indices, probe.index); if (item_index >= 0) { if (itemKeyAt(keys, item_index) == key) { *sparse = probe.index; *dense = item_index; return true; } continue; } if (item_index == kEmptyIndex) { return false; } } } void ApiHandleDict::rehash(word new_num_indices) { int32_t end = nextIndex(); int32_t* indices = this->indices(); RawObject* keys = this->keys(); void** values = this->values(); int32_t new_capacity = maxCapacity(new_num_indices); int32_t* new_indices = newIndices(new_num_indices); RawObject* new_keys = newKeys(new_capacity); void** new_values = newValues(new_capacity); // Re-insert items RawObject key = NoneType::object(); void* value; for (int32_t i = 0, count = 0; nextItem(keys, values, &i, end, &key, &value); count++) { uword hash = handleHash(key); for (IndexProbe probe = probeBegin(new_num_indices, hash);; probeNext(&probe)) { if (indexAt(new_indices, probe.index) == kEmptyIndex) { indexAtPut(new_indices, probe.index, count); itemAtPut(new_keys, new_values, count, key, value); break; } } } setCapacity(new_capacity); setIndices(new_indices); setKeys(new_keys); setNextIndex(numItems()); setNumIndices(new_num_indices); setValues(new_values); std::free(indices); std::free(keys); std::free(values); } void* ApiHandleDict::remove(RawObject key) { word index; int32_t item_index; if (!lookup(key, &index, &item_index)) { return nullptr; } void** values = this->values(); void* result = itemValueAt(values, item_index); indexAtPutTombstone(indices(), index); itemAtPutTombstone(keys(), values, item_index); decrementNumItems(); return result; } void ApiHandleDict::visitKeys(PointerVisitor* visitor) { RawObject* keys = this->keys(); if (keys == nullptr) return; word keys_length = capacity(); for (word i = 0; i < keys_length; i++) { visitor->visitPointer(&keys[i], PointerKind::kRuntime); } } // Reserves a new handle in the given runtime's handle buffer. static ApiHandle* allocateHandle(Runtime* runtime) { FreeListNode** free_handles = capiFreeHandles(runtime); ApiHandle* result = reinterpret_cast<ApiHandle*>(*free_handles); FreeListNode* next = (*free_handles)->next; if (next != nullptr) { *free_handles = next; } else { // No handles left to recycle; advance the frontier *free_handles = reinterpret_cast<FreeListNode*>(result + 1); } return result; } // Frees the handle for future re-use by the given runtime. static void freeHandle(Runtime* runtime, ApiHandle* handle) { FreeListNode** free_handles = capiFreeHandles(runtime); FreeListNode* node = reinterpret_cast<FreeListNode*>(handle); node->next = *free_handles; *free_handles = node; } RawNativeProxy ApiHandle::asNativeProxy() { DCHECK(!isImmediate() && reference_ != 0, "expected extension object handle"); return RawObject{reference_}.rawCast<RawNativeProxy>(); } ApiHandle* ApiHandle::newReference(Runtime* runtime, RawObject obj) { if (isEncodeableAsImmediate(obj)) { return handleFromImmediate(obj); } if (runtime->isInstanceOfNativeProxy(obj)) { ApiHandle* result = static_cast<ApiHandle*>( Int::cast(obj.rawCast<RawNativeProxy>().native()).asCPtr()); result->increfNoImmediate(); return result; } return ApiHandle::newReferenceWithManaged(runtime, obj); } ApiHandle* ApiHandle::newReferenceWithManaged(Runtime* runtime, RawObject obj) { DCHECK(!isEncodeableAsImmediate(obj), "immediates not handled here"); DCHECK(!runtime->isInstanceOfNativeProxy(obj), "native proxy not handled here"); // Get the handle of a builtin instance ApiHandleDict* handles = capiHandles(runtime); int32_t index; if (!handles->atPutLookup(obj, &index)) { ApiHandle* result = reinterpret_cast<ApiHandle*>(handles->atIndex(index)); result->increfNoImmediate(); return result; } // Initialize an ApiHandle for a builtin object or runtime instance EVENT_ID(AllocateCAPIHandle, obj.layoutId()); ApiHandle* handle = allocateHandle(runtime); handle->reference_ = SmallInt::fromWord(0).raw(); handle->ob_refcnt = 1; handles->atPutValue(index, handle); handle->reference_ = obj.raw(); return handle; } ApiHandle* ApiHandle::borrowedReference(Runtime* runtime, RawObject obj) { if (isEncodeableAsImmediate(obj)) { return handleFromImmediate(obj); } if (runtime->isInstanceOfNativeProxy(obj)) { ApiHandle* result = static_cast<ApiHandle*>( Int::cast(obj.rawCast<RawNativeProxy>().native()).asCPtr()); result->ob_refcnt |= kBorrowedBit; return result; } ApiHandle* result = ApiHandle::newReferenceWithManaged(runtime, obj); result->ob_refcnt |= kBorrowedBit; result->ob_refcnt--; return result; } RawObject ApiHandle::checkFunctionResult(Thread* thread, PyObject* result) { bool has_pending_exception = thread->hasPendingException(); if (result == nullptr) { if (has_pending_exception) return Error::exception(); return thread->raiseWithFmt(LayoutId::kSystemError, "NULL return without exception set"); } RawObject result_obj = stealReference(result); if (has_pending_exception) { // TODO(T53569173): set the currently pending exception as the cause of the // newly raised SystemError thread->clearPendingException(); return thread->raiseWithFmt(LayoutId::kSystemError, "non-NULL return with exception set"); } return result_obj; } void* ApiHandle::cache(Runtime* runtime) { // Only managed objects can have a cached value DCHECK(!isImmediate(), "immediate handles do not have caches"); ApiHandleDict* caches = capiCaches(runtime); RawObject obj = asObjectNoImmediate(); DCHECK(!runtime->isInstanceOfNativeProxy(obj), "cache must not be called on extension object"); return caches->at(obj); } NEVER_INLINE void ApiHandle::dispose() { disposeWithRuntime(Thread::current()->runtime()); } void ApiHandle::disposeWithRuntime(Runtime* runtime) { // TODO(T46009838): If a module handle is being disposed, this should register // a weakref to call the module's m_free once's the module is collected RawObject obj = asObjectNoImmediate(); DCHECK(!runtime->isInstanceOfNativeProxy(obj), "Dispose must not be called on extension object"); capiHandles(runtime)->remove(obj); void* cache = capiCaches(runtime)->remove(obj); std::free(cache); freeHandle(runtime, this); } // TODO(T58710656): Allow immediate handles for SmallStr // TODO(T58710677): Allow immediate handles for SmallBytes bool ApiHandle::isEncodeableAsImmediate(RawObject obj) { // SmallStr and SmallBytes require solutions for C-API functions that read // out char* whose lifetimes depend on the lifetimes of the PyObject*s. return !obj.isHeapObject() && !obj.isSmallStr() && !obj.isSmallBytes(); } void ApiHandle::setCache(Runtime* runtime, void* value) { ApiHandleDict* caches = capiCaches(runtime); RawObject obj = asObjectNoImmediate(); caches->atPut(obj, value); } void ApiHandle::setRefcnt(Py_ssize_t count) { if (isImmediate()) return; DCHECK((count & kBorrowedBit) == 0, "count must not have high bits set"); Py_ssize_t flags = ob_refcnt & kBorrowedBit; ob_refcnt = count | flags; } void disposeApiHandles(Runtime* runtime) { ApiHandleDict* handles = capiHandles(runtime); int32_t end = handles->nextIndex(); RawObject* keys = handles->keys(); void** values = handles->values(); RawObject key = NoneType::object(); void* value; for (int32_t i = 0; nextItem(keys, values, &i, end, &key, &value);) { ApiHandle* handle = reinterpret_cast<ApiHandle*>(value); handle->disposeWithRuntime(runtime); } } word numApiHandles(Runtime* runtime) { return capiHandles(runtime)->numItems(); } void visitApiHandles(Runtime* runtime, HandleVisitor* visitor) { ApiHandleDict* handles = capiHandles(runtime); int32_t end = handles->nextIndex(); RawObject* keys = handles->keys(); void** values = handles->values(); RawObject key = NoneType::object(); void* value; for (int32_t i = 0; nextItem(keys, values, &i, end, &key, &value);) { visitor->visitHandle(value, key); } } void visitIncrementedApiHandles(Runtime* runtime, PointerVisitor* visitor) { // Report handles with a refcount > 0 as roots. We deliberately do not visit // other handles and do not update dictionary keys yet. ApiHandleDict* handles = capiHandles(runtime); int32_t end = handles->nextIndex(); RawObject* keys = handles->keys(); void** values = handles->values(); RawObject key = NoneType::object(); void* value; for (int32_t i = 0; nextItem(keys, values, &i, end, &key, &value);) { ApiHandle* handle = reinterpret_cast<ApiHandle*>(value); if (handle->refcntNoImmediate() > 0) { visitor->visitPointer(&key, PointerKind::kApiHandle); // We do not write back the changed `key` to the dictionary yet but leave // that to `visitNotIncrementedBorrowedApiHandles` because we still need // the old `key` to access `capiCaches` there). } } } void visitNotIncrementedBorrowedApiHandles(Runtime* runtime, Scavenger* scavenger, PointerVisitor* visitor) { // This function: // - Rebuilds the handle dictionary: The GC may have moved object around so // we have to adjust the dictionary keys to the new references and updated // hash values. As a side effect this also clears tombstones and shrinks // the dictionary if possible. // - Remove (or rather not insert into the new dictionary) entries with // refcount zero, that are not referenced from any other live object // (object is "white" after GC tri-coloring). // - Rebuild cache dictionary to adjust for moved `key` addresses. ApiHandleDict* caches = capiCaches(runtime); ApiHandleDict* handles = capiHandles(runtime); int32_t end = handles->nextIndex(); int32_t* indices = handles->indices(); RawObject* keys = handles->keys(); void** values = handles->values(); word old_num_items = handles->numItems(); word new_num_indices = Utils::nextPowerOfTwo((old_num_items * 3) / 2 + 1); int32_t new_capacity = maxCapacity(new_num_indices); int32_t* new_indices = newIndices(new_num_indices); RawObject* new_keys = newKeys(new_capacity); void** new_values = newValues(new_capacity); RawObject key = NoneType::object(); void* value; int32_t count = 0; for (int32_t i = 0; nextItem(keys, values, &i, end, &key, &value);) { ApiHandle* handle = reinterpret_cast<ApiHandle*>(value); if (handle->refcntNoImmediate() == 0) { DCHECK(handle->isBorrowedNoImmediate(), "non-borrowed object should already be disposed"); if (key.isHeapObject() && isWhiteObject(scavenger, HeapObject::cast(key))) { // Lookup associated cache data. Note that `key` and the keys in the // `caches` array both use addressed from before GC movement. // `caches.rehash()` happens is delayed until the end of this function. void* cache = caches->remove(key); freeHandle(runtime, handle); std::free(cache); continue; } } visitor->visitPointer(&key, PointerKind::kApiHandle); handle->reference_ = reinterpret_cast<uintptr_t>(key.raw()); // Insert into new handle dictionary. uword hash = handleHash(key); for (IndexProbe probe = probeBegin(new_num_indices, hash);; probeNext(&probe)) { if (indexAt(new_indices, probe.index) == kEmptyIndex) { indexAtPut(new_indices, probe.index, count); itemAtPut(new_keys, new_values, count, key, value); break; } } count++; } handles->setCapacity(new_capacity); handles->setIndices(new_indices); handles->setKeys(new_keys); handles->setNextIndex(count); handles->setNumIndices(new_num_indices); handles->setValues(new_values); std::free(indices); std::free(keys); std::free(values); // Re-hash caches dictionary. caches->visitKeys(visitor); caches->rehash(caches->numIndices()); } RawObject objectGetMember(Thread* thread, RawObject ptr, RawObject name) { ApiHandle* value = *reinterpret_cast<ApiHandle**>(Int::cast(ptr).asCPtr()); if (value != nullptr) { return value->asObject(); } if (name.isNoneType()) { return NoneType::object(); } HandleScope scope(thread); Str name_str(&scope, name); return thread->raiseWithFmt(LayoutId::kAttributeError, "Object attribute '%S' is nullptr", &name_str); } bool objectHasHandleCache(Runtime* runtime, RawObject obj) { return ApiHandle::borrowedReference(runtime, obj)->cache(runtime) != nullptr; } void* objectNewReference(Runtime* runtime, RawObject obj) { return ApiHandle::newReference(runtime, obj); } void objectSetMember(Runtime* runtime, RawObject old_ptr, RawObject new_val) { ApiHandle** old = reinterpret_cast<ApiHandle**>(Int::cast(old_ptr).asCPtr()); (*old)->decref(); *old = ApiHandle::newReference(runtime, new_val); } void dump(PyObject* obj) { if (obj == nullptr) { std::fprintf(stderr, "<nullptr>\n"); return; } dump(ApiHandle::fromPyObject(obj)->asObject()); } } // namespace py
32.768852
80
0.689979
[ "object" ]
d6f3e9e48053a62c536de7083c562e339db44384
8,908
cpp
C++
src/gromacs/math/tests/paddedvector.cpp
hejamu/gromacs
4f4b9e4b197ae78456faada74c9f4cab7d128de6
[ "BSD-2-Clause" ]
384
2015-01-02T19:44:15.000Z
2022-03-27T15:13:15.000Z
src/gromacs/math/tests/paddedvector.cpp
hejamu/gromacs
4f4b9e4b197ae78456faada74c9f4cab7d128de6
[ "BSD-2-Clause" ]
9
2015-04-07T20:48:00.000Z
2022-01-24T21:29:26.000Z
src/gromacs/math/tests/paddedvector.cpp
hejamu/gromacs
4f4b9e4b197ae78456faada74c9f4cab7d128de6
[ "BSD-2-Clause" ]
258
2015-01-19T11:19:57.000Z
2022-03-18T08:59:52.000Z
/* * This file is part of the GROMACS molecular simulation package. * * Copyright (c) 2018,2019,2020,2021, by the GROMACS development team, led by * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl, * and including many others, as listed in the AUTHORS file in the * top-level source directory and at http://www.gromacs.org. * * GROMACS is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; either version 2.1 * of the License, or (at your option) any later version. * * GROMACS is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with GROMACS; if not, see * http://www.gnu.org/licenses, or write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * If you want to redistribute modifications to GROMACS, please * consider that scientific software is very special. Version * control is crucial - bugs must be traceable. We will be happy to * consider code for inclusion in the official distribution, but * derived work must not be called official GROMACS. Details are found * in the README & COPYING files - if they are missing, get the * official version at http://www.gromacs.org. * * To help us fund GROMACS development, we humbly ask that you cite * the research papers on the package. Check out http://www.gromacs.org. */ /*! \internal \file * \brief * Tests implementation of gmx::PaddedVector * * In particular we need to check that the padding works, and that * unpadded_end() is maintained correctly. * * \author Mark Abraham <mark.j.abraham@gmail.com> * \ingroup module_math */ #include "gmxpre.h" #include "gromacs/math/paddedvector.h" #include <memory> #include <vector> #include <gtest/gtest.h> #include "gromacs/math/vec.h" #include "gromacs/math/vectypes.h" #include "gromacs/utility/alignedallocator.h" #include "gromacs/utility/basedefinitions.h" #include "gromacs/math/tests/testarrayrefs.h" namespace gmx { namespace test { //! Typed test fixture template<typename T> class PaddedVectorTest : public ::testing::Test { public: }; //! The types used in testing using Implementations = ::testing::Types<std::allocator<int32_t>, std::allocator<float>, std::allocator<double>, std::allocator<BasicVector<float>>, std::allocator<BasicVector<double>>, AlignedAllocator<int32_t>, AlignedAllocator<float>, AlignedAllocator<double>, AlignedAllocator<BasicVector<float>>, AlignedAllocator<BasicVector<double>>>; TYPED_TEST_SUITE(PaddedVectorTest, Implementations); TYPED_TEST(PaddedVectorTest, DefaultConstructorWorks) { using VectorType = PaddedVector<typename TypeParam::value_type, TypeParam>; VectorType v; EXPECT_EQ(v.size(), 0); EXPECT_EQ(v.paddedSize(), 0); EXPECT_TRUE(v.empty()); EXPECT_EQ(v.begin(), v.end()); EXPECT_EQ(v.cbegin(), v.cend()); } TYPED_TEST(PaddedVectorTest, ResizeWorks) { using VectorType = PaddedVector<typename TypeParam::value_type, TypeParam>; VectorType v; resizeAndFillInput(&v, 3, 1); EXPECT_EQ(v.size(), 3); EXPECT_GE(v.paddedSize(), 3); EXPECT_EQ(v.paddedSize(), v.arrayRefWithPadding().size()); EXPECT_LE(v.size(), v.arrayRefWithPadding().size()); } TYPED_TEST(PaddedVectorTest, ReserveWorks) { using VectorType = PaddedVector<typename TypeParam::value_type, TypeParam>; VectorType vReserved; vReserved.reserveWithPadding(5); resizeAndFillInput(&vReserved, 3, 1); EXPECT_EQ(vReserved.paddedSize(), vReserved.arrayRefWithPadding().size()); EXPECT_LE(vReserved.size(), vReserved.arrayRefWithPadding().size()); } TYPED_TEST(PaddedVectorTest, ReserveWorksTheSameAsNoReserve) { using VectorType = PaddedVector<typename TypeParam::value_type, TypeParam>; VectorType v; resizeAndFillInput(&v, 3, 1); { SCOPED_TRACE("Test when the reservation is larger than needed"); VectorType vReserved; vReserved.reserveWithPadding(5); resizeAndFillInput(&vReserved, 3, 1); EXPECT_EQ(v.size(), vReserved.size()); EXPECT_LE(v.paddedSize(), vReserved.paddedSize()); } { SCOPED_TRACE("Test when the reservation is smaller than needed"); VectorType vReserved; vReserved.reserveWithPadding(1); resizeAndFillInput(&vReserved, 3, 1); EXPECT_EQ(v.size(), vReserved.size()); EXPECT_GE(v.paddedSize(), vReserved.paddedSize()); } } TYPED_TEST(PaddedVectorTest, MoveConstructorWorks) { using VectorType = PaddedVector<typename TypeParam::value_type, TypeParam>; VectorType vOriginal; resizeAndFillInput(&vOriginal, 3, 1); VectorType v(std::move(vOriginal)); EXPECT_EQ(v.size(), 3); EXPECT_GE(v.paddedSize(), 3); EXPECT_EQ(v.paddedSize(), v.arrayRefWithPadding().size()); EXPECT_LE(v.size(), v.arrayRefWithPadding().size()); } TYPED_TEST(PaddedVectorTest, MoveConstructorWithAllocatorWorks) { using VectorType = PaddedVector<typename TypeParam::value_type, TypeParam>; VectorType vOriginal; resizeAndFillInput(&vOriginal, 3, 1); TypeParam allocatorToTest; VectorType v(std::move(vOriginal), allocatorToTest); EXPECT_EQ(v.size(), 3); EXPECT_GE(v.paddedSize(), 3); EXPECT_EQ(v.paddedSize(), v.arrayRefWithPadding().size()); EXPECT_LE(v.size(), v.arrayRefWithPadding().size()); } TYPED_TEST(PaddedVectorTest, MoveAssignmentWorks) { using VectorType = PaddedVector<typename TypeParam::value_type, TypeParam>; VectorType vOriginal; resizeAndFillInput(&vOriginal, 3, 1); VectorType v; v = std::move(vOriginal); EXPECT_EQ(v.size(), 3); EXPECT_GE(v.paddedSize(), 3); EXPECT_EQ(v.paddedSize(), v.arrayRefWithPadding().size()); EXPECT_LE(v.size(), v.arrayRefWithPadding().size()); } TYPED_TEST(PaddedVectorTest, ArrayRefConversionsAreIdentical) { using VectorType = PaddedVector<typename TypeParam::value_type, TypeParam>; VectorType v; resizeAndFillInput(&v, 3, 1); SCOPED_TRACE("Comparing different paths to create identical unpadded views"); compareViews(makeArrayRef(v), v.arrayRefWithPadding().unpaddedArrayRef()); compareViews(makeConstArrayRef(v), v.constArrayRefWithPadding().unpaddedConstArrayRef()); compareViews(makeConstArrayRef(v), v.constArrayRefWithPadding().unpaddedArrayRef()); compareViews(makeConstArrayRef(v), v.arrayRefWithPadding().unpaddedConstArrayRef()); SCOPED_TRACE("Comparing const to non-const unpadded views"); compareViewsIgnoreConst(makeArrayRef(v), makeConstArrayRef(v)); } TYPED_TEST(PaddedVectorTest, CanCopyAssign) { using VectorType = PaddedVector<typename TypeParam::value_type, TypeParam>; VectorType v, w; resizeAndFillInput(&v, 3, 1); resizeAndFillInput(&w, 3, 2); w = v; compareViews(v.arrayRefWithPadding().unpaddedArrayRef(), w.arrayRefWithPadding().unpaddedArrayRef()); compareViews(makeArrayRef(v), makeArrayRef(w)); } TYPED_TEST(PaddedVectorTest, CanMoveAssign) { using VectorType = PaddedVector<typename TypeParam::value_type, TypeParam>; VectorType v, w, x; resizeAndFillInput(&v, 3, 1); resizeAndFillInput(&w, 3, 2); resizeAndFillInput(&x, 3, 1); SCOPED_TRACE("Comparing padded views before move"); compareViews(v.arrayRefWithPadding().unpaddedArrayRef(), x.arrayRefWithPadding().unpaddedArrayRef()); SCOPED_TRACE("Comparing unpadded views before move"); compareViews(makeArrayRef(v), makeArrayRef(x)); w = std::move(x); SCOPED_TRACE("Comparing padded views"); compareViews(v.arrayRefWithPadding().unpaddedArrayRef(), w.arrayRefWithPadding().unpaddedArrayRef()); SCOPED_TRACE("Comparing unpadded views"); compareViews(makeArrayRef(v), makeArrayRef(w)); } TYPED_TEST(PaddedVectorTest, CanSwap) { using VectorType = PaddedVector<typename TypeParam::value_type, TypeParam>; VectorType v, w, x; resizeAndFillInput(&v, 3, 1); resizeAndFillInput(&w, 3, 2); resizeAndFillInput(&x, 3, 1); std::swap(w, x); compareViews(v.arrayRefWithPadding().unpaddedArrayRef(), w.arrayRefWithPadding().unpaddedArrayRef()); compareViews(makeArrayRef(v), makeArrayRef(w)); } } // namespace test } // namespace gmx
34
105
0.696677
[ "vector" ]
d6f5ec6ddb2cab21da8fe3c825b8ece459e60f10
28,123
cc
C++
components/arc/session/arc_vm_client_adapter.cc
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
components/arc/session/arc_vm_client_adapter.cc
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
components/arc/session/arc_vm_client_adapter.cc
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
// Copyright 2018 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/arc/session/arc_vm_client_adapter.h" #include <time.h> #include <set> #include <string> #include <utility> #include <vector> #include "base/bind.h" #include "base/bind_helpers.h" #include "base/feature_list.h" #include "base/files/file_path.h" #include "base/files/file_util.h" #include "base/logging.h" #include "base/macros.h" #include "base/memory/weak_ptr.h" #include "base/optional.h" #include "base/process/launch.h" #include "base/strings/string_number_conversions.h" #include "base/strings/string_split.h" #include "base/strings/string_util.h" #include "base/strings/stringprintf.h" #include "base/system/sys_info.h" #include "base/task/post_task.h" #include "base/task/task_traits.h" #include "base/task/thread_pool.h" #include "base/time/time.h" #include "chromeos/constants/chromeos_switches.h" #include "chromeos/cryptohome/cryptohome_parameters.h" #include "chromeos/dbus/concierge_client.h" #include "chromeos/dbus/dbus_method_call_status.h" #include "chromeos/dbus/dbus_thread_manager.h" #include "chromeos/dbus/debug_daemon/debug_daemon_client.h" #include "chromeos/dbus/upstart/upstart_client.h" #include "chromeos/system/statistics_provider.h" #include "components/arc/arc_features.h" #include "components/arc/arc_util.h" #include "components/arc/session/arc_session.h" #include "components/arc/session/file_system_status.h" #include "components/version_info/version_info.h" namespace arc { namespace { // The "_2d" in job names below corresponds to "-". Upstart escapes characters // that aren't valid in D-Bus object paths with underscore followed by its // ascii code in hex. So "arc_2dcreate_2ddata" becomes "arc-create-data". constexpr const char kArcCreateDataJobName[] = "arc_2dcreate_2ddata"; constexpr const char kArcKeymasterJobName[] = "arc_2dkeymasterd"; constexpr const char kArcVmServerProxyJobName[] = "arcvm_2dserver_2dproxy"; constexpr const char kArcVmPerBoardFeaturesJobName[] = "arcvm_2dper_2dboard_2dfeatures"; constexpr const char kCrosSystemPath[] = "/usr/bin/crossystem"; constexpr const char kHomeDirectory[] = "/home"; constexpr int64_t kInvalidCid = -1; chromeos::ConciergeClient* GetConciergeClient() { return chromeos::DBusThreadManager::Get()->GetConciergeClient(); } std::string GetChromeOsChannelFromLsbRelease() { constexpr const char kChromeOsReleaseTrack[] = "CHROMEOS_RELEASE_TRACK"; constexpr const char kUnknown[] = "unknown"; const std::string kChannelSuffix = "-channel"; std::string value; base::SysInfo::GetLsbReleaseValue(kChromeOsReleaseTrack, &value); if (!base::EndsWith(value, kChannelSuffix, base::CompareCase::SENSITIVE)) { LOG(ERROR) << "Unknown ChromeOS channel: \"" << value << "\""; return kUnknown; } return value.erase(value.find(kChannelSuffix), kChannelSuffix.size()); } // TODO(pliard): Export host-side /data to the VM, and remove the function. vm_tools::concierge::CreateDiskImageRequest CreateArcDiskRequest( const std::string& user_id_hash, int64_t free_disk_bytes) { DCHECK(!user_id_hash.empty()); vm_tools::concierge::CreateDiskImageRequest request; request.set_cryptohome_id(user_id_hash); request.set_disk_path("arcvm"); // The type of disk image to be created. request.set_image_type(vm_tools::concierge::DISK_IMAGE_AUTO); request.set_storage_location(vm_tools::concierge::STORAGE_CRYPTOHOME_ROOT); // The logical size of the new disk image, in bytes. request.set_disk_size(free_disk_bytes / 2); return request; } std::string MonotonicTimestamp() { struct timespec ts; const int ret = clock_gettime(CLOCK_BOOTTIME, &ts); DPCHECK(ret == 0); const int64_t time = ts.tv_sec * base::Time::kNanosecondsPerSecond + ts.tv_nsec; return base::NumberToString(time); } ArcBinaryTranslationType IdentifyBinaryTranslationType( const StartParams& start_params) { const auto* command_line = base::CommandLine::ForCurrentProcess(); bool is_houdini_available = command_line->HasSwitch(chromeos::switches::kEnableHoudini) || command_line->HasSwitch(chromeos::switches::kEnableHoudini64); bool is_ndk_translation_available = command_line->HasSwitch(chromeos::switches::kEnableNdkTranslation); if (!is_houdini_available && !is_ndk_translation_available) return ArcBinaryTranslationType::NONE; const bool prefer_ndk_translation = !is_houdini_available || start_params.native_bridge_experiment; if (is_ndk_translation_available && prefer_ndk_translation) return ArcBinaryTranslationType::NDK_TRANSLATION; return ArcBinaryTranslationType::HOUDINI; } std::vector<std::string> GenerateKernelCmdline( const StartParams& start_params, const UpgradeParams& upgrade_params, const FileSystemStatus& file_system_status, bool is_dev_mode, bool is_host_on_vm, const std::string& channel, const std::string& serial_number) { DCHECK(!serial_number.empty()); std::string native_bridge; switch (IdentifyBinaryTranslationType(start_params)) { case ArcBinaryTranslationType::NONE: native_bridge = "0"; break; case ArcBinaryTranslationType::HOUDINI: native_bridge = "libhoudini.so"; break; case ArcBinaryTranslationType::NDK_TRANSLATION: native_bridge = "libndk_translation.so"; break; } std::vector<std::string> result = { "androidboot.hardware=bertha", "androidboot.container=1", base::StringPrintf("androidboot.native_bridge=%s", native_bridge.c_str()), base::StringPrintf("androidboot.dev_mode=%d", is_dev_mode), base::StringPrintf("androidboot.disable_runas=%d", !is_dev_mode), base::StringPrintf("androidboot.vm=%d", is_host_on_vm), base::StringPrintf("androidboot.debuggable=%d", file_system_status.is_android_debuggable()), base::StringPrintf("androidboot.lcd_density=%d", start_params.lcd_density), base::StringPrintf("androidboot.arc_file_picker=%d", start_params.arc_file_picker_experiment), base::StringPrintf("androidboot.arc_custom_tabs=%d", start_params.arc_custom_tabs_experiment), base::StringPrintf("androidboot.arc_print_spooler=%d", start_params.arc_print_spooler_experiment), base::StringPrintf("androidboot.disable_system_default_app=%d", start_params.arc_disable_system_default_app), "androidboot.chromeos_channel=" + channel, "androidboot.boottime_offset=" + MonotonicTimestamp(), // TODO(yusukes): remove this once arcvm supports SELinux. "androidboot.selinux=permissive", // Since we don't do mini VM yet, set not only |start_params| but also // |upgrade_params| here for now. base::StringPrintf("androidboot.disable_boot_completed=%d", upgrade_params.skip_boot_completed_broadcast), base::StringPrintf("androidboot.copy_packages_cache=%d", static_cast<int>(upgrade_params.packages_cache_mode)), base::StringPrintf("androidboot.skip_gms_core_cache=%d", upgrade_params.skip_gms_core_cache), base::StringPrintf("androidboot.arc_demo_mode=%d", upgrade_params.is_demo_session), base::StringPrintf( "androidboot.supervision.transition=%d", static_cast<int>(upgrade_params.supervision_transition)), "androidboot.serialno=" + serial_number, }; // TODO(yusukes): Check if we need to set ro.boot.container_boot_type and // ro.boot.enable_adb_sideloading for ARCVM. // Conditionally sets some properties based on |start_params|. switch (start_params.play_store_auto_update) { case StartParams::PlayStoreAutoUpdate::AUTO_UPDATE_DEFAULT: break; case StartParams::PlayStoreAutoUpdate::AUTO_UPDATE_ON: result.push_back("androidboot.play_store_auto_update=1"); break; case StartParams::PlayStoreAutoUpdate::AUTO_UPDATE_OFF: result.push_back("androidboot.play_store_auto_update=0"); break; } // Conditionally sets more properties based on |upgrade_params|. if (!upgrade_params.locale.empty()) { result.push_back("androidboot.locale=" + upgrade_params.locale); if (!upgrade_params.preferred_languages.empty()) { result.push_back( "androidboot.preferred_languages=" + base::JoinString(upgrade_params.preferred_languages, ",")); } } // TODO(yusukes): Handle |is_account_managed| in |upgrade_params| when we // implement apk sideloading for ARCVM. return result; } vm_tools::concierge::StartArcVmRequest CreateStartArcVmRequest( const std::string& user_id_hash, uint32_t cpus, const base::FilePath& data_disk_path, const base::FilePath& demo_session_apps_path, const FileSystemStatus& file_system_status, std::vector<std::string> kernel_cmdline) { vm_tools::concierge::StartArcVmRequest request; request.set_name(kArcVmName); request.set_owner_id(user_id_hash); request.add_params("root=/dev/vda"); if (file_system_status.is_host_rootfs_writable() && file_system_status.is_system_image_ext_format()) { request.add_params("rw"); } request.add_params("init=/init"); // TIP: When you want to see all dmesg logs from the Android system processes // such as init, uncomment the following line. By default, the guest kernel // rate-limits the logging and you might not be able to see all LOGs from // them. The logs could be silently dropped. This is useful when modifying // init.bertha.rc, for example. // // request.add_params("printk.devkmsg=on"); for (auto& entry : kernel_cmdline) request.add_params(std::move(entry)); vm_tools::concierge::VirtualMachineSpec* vm = request.mutable_vm(); vm->set_kernel(file_system_status.guest_kernel_path().value()); // Add / as /dev/vda. vm->set_rootfs(file_system_status.system_image_path().value()); request.set_rootfs_writable(file_system_status.is_host_rootfs_writable() && file_system_status.is_system_image_ext_format()); // Add /data as /dev/vdb. vm_tools::concierge::DiskImage* disk_image = request.add_disks(); disk_image->set_path(data_disk_path.value()); disk_image->set_image_type(vm_tools::concierge::DISK_IMAGE_AUTO); disk_image->set_writable(true); disk_image->set_do_mount(true); // Add /vendor as /dev/vdc. disk_image = request.add_disks(); disk_image->set_path(file_system_status.vendor_image_path().value()); disk_image->set_image_type(vm_tools::concierge::DISK_IMAGE_AUTO); disk_image->set_writable(false); disk_image->set_do_mount(true); // Add /run/imageloader/.../android_demo_apps.squash as /dev/vdd if needed. // TODO(b/144542975): Do this on upgrade instead. if (!demo_session_apps_path.empty()) { disk_image = request.add_disks(); disk_image->set_path(demo_session_apps_path.value()); disk_image->set_image_type(vm_tools::concierge::DISK_IMAGE_AUTO); disk_image->set_writable(false); disk_image->set_do_mount(true); } // Add Android fstab. request.set_fstab(file_system_status.fstab_path().value()); // Add cpus. request.set_cpus(cpus); return request; } // Gets a system property managed by crossystem. This function can be called // only with base::MayBlock(). int GetSystemPropertyInt(const std::string& property) { std::string output; if (!base::GetAppOutput({kCrosSystemPath, property}, &output)) return -1; int output_int; return base::StringToInt(output, &output_int) ? output_int : -1; } } // namespace class ArcVmClientAdapter : public ArcClientAdapter, public chromeos::ConciergeClient::VmObserver, public chromeos::ConciergeClient::Observer { public: // Initializing |is_host_on_vm_| and |is_dev_mode_| is not always very fast. // Try to initialize them in the constructor and in StartMiniArc respectively. // They usually run when the system is not busy. ArcVmClientAdapter() : ArcVmClientAdapter(FileSystemStatusRewriter{}) {} // For testing purposes and the internal use (by the other ctor) only. explicit ArcVmClientAdapter(const FileSystemStatusRewriter& rewriter) : is_host_on_vm_(chromeos::system::StatisticsProvider::GetInstance() ->IsRunningOnVm()), file_system_status_rewriter_for_testing_(rewriter) { auto* client = GetConciergeClient(); client->AddVmObserver(this); client->AddObserver(this); } ~ArcVmClientAdapter() override { auto* client = GetConciergeClient(); client->RemoveObserver(this); client->RemoveVmObserver(this); } // chromeos::ConciergeClient::VmObserver overrides: void OnVmStarted( const vm_tools::concierge::VmStartedSignal& signal) override { if (signal.name() == kArcVmName) VLOG(1) << "OnVmStarted: ARCVM cid=" << signal.vm_info().cid(); } void OnVmStopped( const vm_tools::concierge::VmStoppedSignal& signal) override { if (signal.name() != kArcVmName) return; const int64_t cid = signal.cid(); if (cid != current_cid_) { VLOG(1) << "Ignoring VmStopped signal: current CID=" << current_cid_ << ", stopped CID=" << cid; return; } VLOG(1) << "OnVmStopped: ARCVM cid=" << cid; current_cid_ = kInvalidCid; OnArcInstanceStopped(); } // ArcClientAdapter overrides: void StartMiniArc(StartParams params, chromeos::VoidDBusMethodCallback callback) override { // TODO(yusukes): Support mini ARC. VLOG(2) << "Mini ARCVM instance is not supported."; // Save the parameters for the later call to UpgradeArc. start_params_ = std::move(params); base::ThreadPool::PostTaskAndReplyWithResult( FROM_HERE, {base::MayBlock(), base::TaskPriority::USER_VISIBLE}, base::BindOnce( []() { return GetSystemPropertyInt("cros_debug") == 1; }), base::BindOnce(&ArcVmClientAdapter::OnIsDevMode, weak_factory_.GetWeakPtr(), std::move(callback))); } void UpgradeArc(UpgradeParams params, chromeos::VoidDBusMethodCallback callback) override { VLOG(1) << "Starting Concierge service"; chromeos::DBusThreadManager::Get()->GetDebugDaemonClient()->StartConcierge( base::BindOnce(&ArcVmClientAdapter::OnConciergeStarted, weak_factory_.GetWeakPtr(), std::move(params), std::move(callback))); } void StopArcInstance(bool on_shutdown, bool backup_log) override { if (on_shutdown) { // Do nothing when |on_shutdown| is true because either vm_concierge.conf // job (in case of user session termination) or session_manager (in case // of browser-initiated exit on e.g. chrome://flags or UI language change) // will stop all VMs including ARCVM right after the browser exits. VLOG(1) << "StopArcInstance is called during browser shutdown. Do nothing."; return; } if (backup_log) { // TODO(b/149874690): Call debugd to back up the log. } VLOG(1) << "Stopping arcvm"; vm_tools::concierge::StopVmRequest request; request.set_name(kArcVmName); request.set_owner_id(user_id_hash_); GetConciergeClient()->StopVm( request, base::BindOnce(&ArcVmClientAdapter::OnStopVmReply, weak_factory_.GetWeakPtr())); } void SetUserInfo(const cryptohome::Identification& cryptohome_id, const std::string& hash, const std::string& serial_number) override { DCHECK(cryptohome_id_.id().empty()); DCHECK(user_id_hash_.empty()); DCHECK(serial_number_.empty()); if (cryptohome_id.id().empty()) LOG(WARNING) << "cryptohome_id is empty"; if (hash.empty()) LOG(WARNING) << "hash is empty"; if (serial_number.empty()) LOG(WARNING) << "serial_number is empty"; cryptohome_id_ = cryptohome_id; user_id_hash_ = hash; serial_number_ = serial_number; } // chromeos::ConciergeClient::Observer overrides: void ConciergeServiceStopped() override { VLOG(1) << "vm_concierge stopped"; // At this point, all crosvm processes are gone. Notify the observer of the // event. OnArcInstanceStopped(); } void ConciergeServiceRestarted() override {} private: void OnIsDevMode(chromeos::VoidDBusMethodCallback callback, bool is_dev_mode) { VLOG(1) << "Starting arcvm-per-board-features"; // Note: the Upstart job is a task, and the callback for the start request // won't be called until the task finishes. When the callback is called with // true, it is ensured that the per-board features files exist. chromeos::UpstartClient::Get()->StartJob( kArcVmPerBoardFeaturesJobName, /*environment=*/{}, base::BindOnce(&ArcVmClientAdapter::OnArcVmPerBoardFeaturesStarted, weak_factory_.GetWeakPtr(), std::move(callback))); is_dev_mode_ = is_dev_mode; } void OnArcVmPerBoardFeaturesStarted(chromeos::VoidDBusMethodCallback callback, bool result) { if (!result) { LOG(ERROR) << "Failed to start arcvm-per-board-features"; // TODO(yusukes): Record UMA for this case. std::move(callback).Run(result); return; } // Make sure to kill a stale arcvm-server-proxy job (if any). chromeos::UpstartClient::Get()->StopJob( kArcVmServerProxyJobName, /*environment=*/{}, base::BindOnce(&ArcVmClientAdapter::OnArcVmServerProxyJobStopped, weak_factory_.GetWeakPtr(), std::move(callback))); } void OnArcVmServerProxyJobStopped(chromeos::VoidDBusMethodCallback callback, bool result) { VLOG(1) << "OnArcVmServerProxyJobStopped: job " << (result ? "stopped" : "not running?"); should_notify_observers_ = true; // Make sure to stop arc-keymasterd if it's already started. Always move // |callback| as is and ignore |result|. chromeos::UpstartClient::Get()->StopJob( kArcKeymasterJobName, /*environment=*/{}, base::BindOnce(&ArcVmClientAdapter::OnArcKeymasterJobStopped, weak_factory_.GetWeakPtr(), std::move(callback))); } void OnArcKeymasterJobStopped(chromeos::VoidDBusMethodCallback callback, bool result) { VLOG(1) << "OnArcKeymasterJobStopped: arc-keymasterd job " << (result ? "stopped" : "not running?"); // Start arc-keymasterd. Always move |callback| as is and ignore |result|. VLOG(1) << "Starting arc-keymasterd"; chromeos::UpstartClient::Get()->StartJob( kArcKeymasterJobName, /*environment=*/{}, base::BindOnce(&ArcVmClientAdapter::OnArcKeymasterJobStarted, weak_factory_.GetWeakPtr(), std::move(callback))); } void OnArcKeymasterJobStarted(chromeos::VoidDBusMethodCallback callback, bool result) { if (!result) LOG(ERROR) << "Failed to start arc-keymasterd job"; std::move(callback).Run(result); } void OnConciergeStarted(UpgradeParams params, chromeos::VoidDBusMethodCallback callback, bool success) { if (!success) { LOG(ERROR) << "Failed to start Concierge service for arcvm"; std::move(callback).Run(false); return; } VLOG(1) << "Starting arcvm-server-proxy"; chromeos::UpstartClient::Get()->StartJob( kArcVmServerProxyJobName, /*environment=*/{}, base::BindOnce(&ArcVmClientAdapter::OnArcVmServerProxyJobStarted, weak_factory_.GetWeakPtr(), std::move(params), std::move(callback))); } void OnArcVmServerProxyJobStarted(UpgradeParams params, chromeos::VoidDBusMethodCallback callback, bool result) { if (!result) { LOG(ERROR) << "Failed to start arcvm-server-proxy job"; std::move(callback).Run(false); return; } VLOG(1) << "Starting arc-create-data"; const std::string account_id = cryptohome::CreateAccountIdentifierFromIdentification(cryptohome_id_) .account_id(); chromeos::UpstartClient::Get()->StartJob( kArcCreateDataJobName, {"CHROMEOS_USER=" + account_id}, base::BindOnce(&ArcVmClientAdapter::OnArcCreateDataJobStarted, weak_factory_.GetWeakPtr(), std::move(params), std::move(callback))); } void OnArcCreateDataJobStarted(UpgradeParams params, chromeos::VoidDBusMethodCallback callback, bool result) { if (!result) { LOG(ERROR) << "Failed to start arc-create-data job"; std::move(callback).Run(false); return; } // TODO(pliard): Export host-side /data to the VM, and remove the call. Note // that ArcSessionImpl checks low disk conditions before calling UpgradeArc. base::ThreadPool::PostTaskAndReplyWithResult( FROM_HERE, {base::MayBlock(), base::TaskPriority::USER_VISIBLE}, base::BindOnce(&base::SysInfo::AmountOfFreeDiskSpace, base::FilePath(kHomeDirectory)), base::BindOnce(&ArcVmClientAdapter::CreateDiskImageAfterSizeCheck, weak_factory_.GetWeakPtr(), std::move(params), std::move(callback))); } void CreateDiskImageAfterSizeCheck(UpgradeParams params, chromeos::VoidDBusMethodCallback callback, int64_t free_disk_bytes) { VLOG(2) << "Got free disk size: " << free_disk_bytes; if (user_id_hash_.empty()) { LOG(ERROR) << "User ID hash is not set"; std::move(callback).Run(false); return; } // TODO(pliard): Export host-side /data to the VM, and remove the call. GetConciergeClient()->CreateDiskImage( CreateArcDiskRequest(user_id_hash_, free_disk_bytes), base::BindOnce(&ArcVmClientAdapter::OnDiskImageCreated, weak_factory_.GetWeakPtr(), std::move(params), std::move(callback))); } // TODO(pliard): Export host-side /data to the VM, and remove the first half // of the function. void OnDiskImageCreated( UpgradeParams params, chromeos::VoidDBusMethodCallback callback, base::Optional<vm_tools::concierge::CreateDiskImageResponse> reply) { if (!reply.has_value()) { LOG(ERROR) << "Failed to create disk image. Empty response."; std::move(callback).Run(false); return; } const vm_tools::concierge::CreateDiskImageResponse& response = reply.value(); if (response.status() != vm_tools::concierge::DISK_STATUS_EXISTS && response.status() != vm_tools::concierge::DISK_STATUS_CREATED) { LOG(ERROR) << "Failed to create disk image: " << response.failure_reason(); std::move(callback).Run(false); return; } VLOG(1) << "Disk image for arcvm ready. status=" << response.status() << ", disk=" << response.disk_path(); base::ThreadPool::PostTaskAndReplyWithResult( FROM_HERE, {base::MayBlock(), base::TaskPriority::USER_VISIBLE}, base::BindOnce(&FileSystemStatus::GetFileSystemStatusBlocking), base::BindOnce(&ArcVmClientAdapter::OnFileSystemStatus, weak_factory_.GetWeakPtr(), std::move(params), std::move(callback), base::FilePath(response.disk_path()))); } void OnFileSystemStatus(UpgradeParams params, chromeos::VoidDBusMethodCallback callback, const base::FilePath& data_disk_path, FileSystemStatus file_system_status) { VLOG(2) << "Got file system status"; if (file_system_status_rewriter_for_testing_) file_system_status_rewriter_for_testing_.Run(&file_system_status); if (serial_number_.empty()) { LOG(ERROR) << "Serial number is not set"; std::move(callback).Run(false); return; } const int32_t cpus = base::SysInfo::NumberOfProcessors() - start_params_.num_cores_disabled; DCHECK_LT(0, cpus); DCHECK(is_dev_mode_); std::vector<std::string> kernel_cmdline = GenerateKernelCmdline( start_params_, params, file_system_status, *is_dev_mode_, is_host_on_vm_, GetChromeOsChannelFromLsbRelease(), serial_number_); auto start_request = CreateStartArcVmRequest( user_id_hash_, cpus, data_disk_path, params.demo_session_apps_path, file_system_status, std::move(kernel_cmdline)); GetConciergeClient()->StartArcVm( start_request, base::BindOnce(&ArcVmClientAdapter::OnStartArcVmReply, weak_factory_.GetWeakPtr(), std::move(callback))); } void OnStartArcVmReply( chromeos::VoidDBusMethodCallback callback, base::Optional<vm_tools::concierge::StartVmResponse> reply) { if (!reply.has_value()) { LOG(ERROR) << "Failed to start arcvm. Empty response."; std::move(callback).Run(false); return; } const vm_tools::concierge::StartVmResponse& response = reply.value(); if (response.status() != vm_tools::concierge::VM_STATUS_RUNNING) { LOG(ERROR) << "Failed to start arcvm: status=" << response.status() << ", reason=" << response.failure_reason(); std::move(callback).Run(false); return; } current_cid_ = response.vm_info().cid(); VLOG(1) << "ARCVM started cid=" << current_cid_; std::move(callback).Run(true); } void OnArcInstanceStopped() { VLOG(1) << "ARCVM stopped. Stopping arcvm-server-proxy"; // TODO(yusukes): Consider removing this stop call once b/142140355 is // implemented. chromeos::UpstartClient::Get()->StopJob( kArcVmServerProxyJobName, /*environment=*/{}, base::DoNothing()); // If this method is called before even mini VM is started (e.g. very early // vm_concierge crash), or this method is called twice (e.g. crosvm crash // followed by vm_concierge crash), do nothing. if (!should_notify_observers_) return; should_notify_observers_ = false; for (auto& observer : observer_list_) observer.ArcInstanceStopped(); } void OnStopVmReply( base::Optional<vm_tools::concierge::StopVmResponse> reply) { // If the reply indicates the D-Bus call is successfully done, do nothing. // Concierge will call OnVmStopped() eventually. if (reply.has_value() && reply.value().success()) return; // We likely tried to stop mini VM which doesn't exist today. Notify // observers. // TODO(yusukes): Remove the fallback once we implement mini VM. OnArcInstanceStopped(); } base::Optional<bool> is_dev_mode_; // True when the *host* is running on a VM. const bool is_host_on_vm_; // A cryptohome ID of the primary profile. cryptohome::Identification cryptohome_id_; // A hash of the primary profile user ID. std::string user_id_hash_; // A serial number for the current profile. std::string serial_number_; StartParams start_params_; bool should_notify_observers_ = false; int64_t current_cid_ = kInvalidCid; FileSystemStatusRewriter file_system_status_rewriter_for_testing_; // For callbacks. base::WeakPtrFactory<ArcVmClientAdapter> weak_factory_{this}; DISALLOW_COPY_AND_ASSIGN(ArcVmClientAdapter); }; std::unique_ptr<ArcClientAdapter> CreateArcVmClientAdapter() { return std::make_unique<ArcVmClientAdapter>(); } std::unique_ptr<ArcClientAdapter> CreateArcVmClientAdapterForTesting( const FileSystemStatusRewriter& rewriter) { return std::make_unique<ArcVmClientAdapter>(rewriter); } } // namespace arc
39.114047
80
0.685026
[ "object", "vector" ]
d6f953375af0ef1c5a8606b59913bf57b86338b4
1,261
cpp
C++
cpp/leetcode/155.min-stack.cpp
Gerrard-YNWA/piece_of_code
ea8c9f05a453c893cc1f10e9b91d4393838670c1
[ "MIT" ]
1
2021-11-02T05:17:24.000Z
2021-11-02T05:17:24.000Z
cpp/leetcode/155.min-stack.cpp
Gerrard-YNWA/code
546230593c33ff322d3205499fe17cd6a9a437c1
[ "MIT" ]
null
null
null
cpp/leetcode/155.min-stack.cpp
Gerrard-YNWA/code
546230593c33ff322d3205499fe17cd6a9a437c1
[ "MIT" ]
null
null
null
/* * @lc app=leetcode id=155 lang=cpp * * [155] Min Stack */ #include <climits> #include <iostream> #include <stack> using namespace std; // @lc code=start class MinStack { public: /** initialize your data structure here. */ MinStack() { _min = INT_MAX; } void push(int val) { if (_min >= val) { _stack.push(_min); _min = val; } _stack.push(val); } void pop() { int top = _stack.top(); if (top == _min) { _stack.pop(); _min = _stack.top(); } _stack.pop(); } int top() { return _stack.top(); } int getMin() { return _min; } private: int _min; stack<int> _stack; }; /** * Your MinStack object will be instantiated and called as such: * MinStack* obj = new MinStack(); * obj->push(val); * obj->pop(); * int param_3 = obj->top(); * int param_4 = obj->getMin(); */ // @lc code=end int main() { MinStack *minStack = new MinStack(); minStack->push(-2); minStack->push(0); minStack->push(-3); cout << minStack->getMin() << endl; minStack->pop(); cout << minStack->top() << endl; cout << minStack->getMin() << endl; return 0; }
17.760563
64
0.513878
[ "object" ]
d6fd4cef0344fff572cffe6a8ecbbd94012cb6a2
7,809
cpp
C++
tests/cefclient/uiplugin.cpp
Sharathsukash/cef
bf0acb75b9c1f3bfa49883abcb3f9af6f0017d67
[ "BSD-3-Clause" ]
1
2017-01-18T17:04:40.000Z
2017-01-18T17:04:40.000Z
tests/cefclient/uiplugin.cpp
Sharathsukash/cef
bf0acb75b9c1f3bfa49883abcb3f9af6f0017d67
[ "BSD-3-Clause" ]
null
null
null
tests/cefclient/uiplugin.cpp
Sharathsukash/cef
bf0acb75b9c1f3bfa49883abcb3f9af6f0017d67
[ "BSD-3-Clause" ]
1
2015-07-14T02:36:29.000Z
2015-07-14T02:36:29.000Z
// Copyright (c) 2009 The Chromium Embedded Framework Authors. // Portions copyright (c) 2006-2008 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 "uiplugin.h" #include "cefclient.h" #include <gl/gl.h> #include <sstream> #if defined(OS_WIN) // Initialized in NP_Initialize. NPNetscapeFuncs* g_uibrowser = NULL; namespace { // Global values. float g_rotationspeed = 0.0f; float g_theta = 0.0f; // Class holding pointers for the client plugin window. class ClientPlugin { public: ClientPlugin() { hWnd = NULL; hDC = NULL; hRC = NULL; } HWND hWnd; HDC hDC; HGLRC hRC; }; // Forward declarations of functions included in this code module: LRESULT CALLBACK PluginWndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam); void EnableOpenGL(HWND hWnd, HDC * hDC, HGLRC * hRC); void DisableOpenGL(HWND hWnd, HDC hDC, HGLRC hRC); NPError NPP_NewImpl(NPMIMEType plugin_type, NPP instance, uint16 mode, int16 argc, char* argn[], char* argv[], NPSavedData* saved) { if (instance == NULL) return NPERR_INVALID_INSTANCE_ERROR; ClientPlugin *plugin = new ClientPlugin; instance->pdata = reinterpret_cast<void*>(plugin); return NPERR_NO_ERROR; } NPError NPP_DestroyImpl(NPP instance, NPSavedData** save) { ClientPlugin *plugin = reinterpret_cast<ClientPlugin*>(instance->pdata); if (plugin) { if(plugin->hWnd) { DestroyWindow(plugin->hWnd); DisableOpenGL(plugin->hWnd, plugin->hDC, plugin->hRC); } delete plugin; g_rotationspeed = 0.0f; g_theta = 0.0f; } return NPERR_NO_ERROR; } NPError NPP_SetWindowImpl(NPP instance, NPWindow* window_info) { if (instance == NULL) return NPERR_INVALID_INSTANCE_ERROR; if (window_info == NULL) return NPERR_GENERIC_ERROR; ClientPlugin *plugin = reinterpret_cast<ClientPlugin*>(instance->pdata); HWND parent_hwnd = reinterpret_cast<HWND>(window_info->window); if (plugin->hWnd == NULL) { WNDCLASS wc; HINSTANCE hInstance = GetModuleHandle(NULL); // Register the window class. wc.style = CS_OWNDC; wc.lpfnWndProc = PluginWndProc; wc.cbClsExtra = 0; wc.cbWndExtra = 0; wc.hInstance = hInstance; wc.hIcon = LoadIcon(NULL, IDI_APPLICATION); wc.hCursor = LoadCursor(NULL, IDC_ARROW); wc.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH); wc.lpszMenuName = NULL; wc.lpszClassName = L"ClientUIPlugin"; RegisterClass(&wc); // Create the main window. plugin->hWnd = CreateWindow(L"ClientUIPlugin", L"Client UI Plugin", WS_CHILD, 0, 0, 0, 0, parent_hwnd, NULL, hInstance, NULL); SetWindowLongPtr(plugin->hWnd, GWLP_USERDATA, reinterpret_cast<LONG_PTR>(plugin)); // Enable OpenGL drawing for the window. EnableOpenGL(plugin->hWnd, &(plugin->hDC), &(plugin->hRC)); } // Position the window and make sure it's visible. RECT parent_rect; GetClientRect(parent_hwnd, &parent_rect); SetWindowPos(plugin->hWnd, NULL, parent_rect.left, parent_rect.top, parent_rect.right - parent_rect.left, parent_rect.bottom - parent_rect.top, SWP_SHOWWINDOW); UpdateWindow(plugin->hWnd); ShowWindow(plugin->hWnd, SW_SHOW); return NPERR_NO_ERROR; } // Send the notification to the browser as a JavaScript function call. static void NotifyNewRotation(float value) { std::stringstream buf; buf << "notifyNewRotation(" << value << ");"; AppGetBrowser()->GetMainFrame()->ExecuteJavaScript(buf.str(), CefString(), 0); } // Nice little fly polygon borrowed from the OpenGL Red Book. const GLubyte fly[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x80, 0x01, 0xC0, 0x06, 0xC0, 0x03, 0x60, 0x04, 0x60, 0x06, 0x20, 0x04, 0x30, 0x0C, 0x20, 0x04, 0x18, 0x18, 0x20, 0x04, 0x0C, 0x30, 0x20, 0x04, 0x06, 0x60, 0x20, 0x44, 0x03, 0xC0, 0x22, 0x44, 0x01, 0x80, 0x22, 0x44, 0x01, 0x80, 0x22, 0x44, 0x01, 0x80, 0x22, 0x44, 0x01, 0x80, 0x22, 0x44, 0x01, 0x80, 0x22, 0x44, 0x01, 0x80, 0x22, 0x66, 0x01, 0x80, 0x66, 0x33, 0x01, 0x80, 0xCC, 0x19, 0x81, 0x81, 0x98, 0x0C, 0xC1, 0x83, 0x30, 0x07, 0xe1, 0x87, 0xe0, 0x03, 0x3f, 0xfc, 0xc0, 0x03, 0x31, 0x8c, 0xc0, 0x03, 0x33, 0xcc, 0xc0, 0x06, 0x64, 0x26, 0x60, 0x0c, 0xcc, 0x33, 0x30, 0x18, 0xcc, 0x33, 0x18, 0x10, 0xc4, 0x23, 0x08, 0x10, 0x63, 0xC6, 0x08, 0x10, 0x30, 0x0c, 0x08, 0x10, 0x18, 0x18, 0x08, 0x10, 0x00, 0x00, 0x08}; // Plugin window procedure. LRESULT CALLBACK PluginWndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { ClientPlugin* plugin = reinterpret_cast<ClientPlugin*>(GetWindowLongPtr(hWnd, GWLP_USERDATA)); switch(message) { case WM_CREATE: // Start the timer that's used for redrawing. SetTimer(hWnd, 1, 1, NULL); return 0; case WM_DESTROY: // Stop the timer that's used for redrawing. KillTimer(hWnd, 1); return 0; case WM_LBUTTONDOWN: // Decrement rotation speed. ModifyRotation(-2.0f); return 0; case WM_RBUTTONDOWN: // Increment rotation speed. ModifyRotation(2.0f); return 0; case WM_SIZE: if (plugin) { // Resize the OpenGL viewport to match the window size. int width = LOWORD(lParam); int height = HIWORD(lParam); wglMakeCurrent(plugin->hDC, plugin->hRC); glViewport(0, 0, width, height); } break; case WM_ERASEBKGND: return 0; case WM_TIMER: wglMakeCurrent(plugin->hDC, plugin->hRC); // Adjust the theta value and redraw the display when the timer fires. glClearColor(1.0f, 1.0f, 1.0f, 0.0f); glClear(GL_COLOR_BUFFER_BIT); glPushMatrix(); glEnable(GL_POLYGON_STIPPLE); glPolygonStipple(fly); glRotatef(g_theta, 0.0f, 0.0f, 1.0f); glBegin(GL_QUADS); glColor3f(1.0f, 0.0f, 0.0f); glVertex2f(0.7f, 0.7f); glColor3f(0.0f, 1.0f, 0.0f); glVertex2f(0.7f, -0.7f); glColor3f(0.0f, 0.0f, 1.0f); glVertex2f(-0.7f, -0.7f); glColor3f(1.0f, 0.0f, 1.0f); glVertex2f(-0.7f, 0.7f); glEnd(); glDisable(GL_POLYGON_STIPPLE); glPopMatrix(); SwapBuffers(plugin->hDC); g_theta -= g_rotationspeed; } return DefWindowProc(hWnd, message, wParam, lParam); } // Enable OpenGL. void EnableOpenGL(HWND hWnd, HDC * hDC, HGLRC * hRC) { PIXELFORMATDESCRIPTOR pfd; int format; // Get the device context. *hDC = GetDC(hWnd); // Set the pixel format for the DC. ZeroMemory(&pfd, sizeof(pfd)); pfd.nSize = sizeof(pfd); pfd.nVersion = 1; pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER; pfd.iPixelType = PFD_TYPE_RGBA; pfd.cColorBits = 24; pfd.cDepthBits = 16; pfd.iLayerType = PFD_MAIN_PLANE; format = ChoosePixelFormat(*hDC, &pfd); SetPixelFormat(*hDC, format, &pfd); // Create and enable the render contex. *hRC = wglCreateContext(*hDC); } // Disable OpenGL. void DisableOpenGL(HWND hWnd, HDC hDC, HGLRC hRC) { wglMakeCurrent(NULL, NULL); wglDeleteContext(hRC); ReleaseDC(hWnd, hDC); } } // namespace NPError API_CALL NP_UIGetEntryPoints(NPPluginFuncs* pFuncs) { pFuncs->newp = NPP_NewImpl; pFuncs->destroy = NPP_DestroyImpl; pFuncs->setwindow = NPP_SetWindowImpl; return NPERR_NO_ERROR; } NPError API_CALL NP_UIInitialize(NPNetscapeFuncs* pFuncs) { g_uibrowser = pFuncs; return NPERR_NO_ERROR; } NPError API_CALL NP_UIShutdown(void) { g_uibrowser = NULL; return NPERR_NO_ERROR; } void ModifyRotation(float value) { g_rotationspeed += value; NotifyNewRotation(g_rotationspeed); } void ResetRotation() { g_rotationspeed = 0.0; NotifyNewRotation(g_rotationspeed); } #endif // OS_WIN
26.561224
78
0.675759
[ "render" ]
d900c2b2846ca7fee474e1bb5d36092a7afee330
22,758
cpp
C++
android/android_9/hardware/qcom/neuralnetworks/hvxservice/1.0/HexagonOperationsCheck.cpp
yakuizhao/intel-vaapi-driver
b2bb0383352694941826543a171b557efac2219b
[ "MIT" ]
null
null
null
android/android_9/hardware/qcom/neuralnetworks/hvxservice/1.0/HexagonOperationsCheck.cpp
yakuizhao/intel-vaapi-driver
b2bb0383352694941826543a171b557efac2219b
[ "MIT" ]
null
null
null
android/android_9/hardware/qcom/neuralnetworks/hvxservice/1.0/HexagonOperationsCheck.cpp
yakuizhao/intel-vaapi-driver
b2bb0383352694941826543a171b557efac2219b
[ "MIT" ]
null
null
null
/* * Copyright (C) 2017 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #define LOG_TAG "android.hardware.neuralnetworks@1.0-impl-hvx" #include "HexagonModel.h" #include "HexagonOperations.h" #include "OperationsUtils.h" namespace android { namespace hardware { namespace neuralnetworks { namespace V1_0 { namespace implementation { namespace hexagon { using android::nn::Shape; namespace { bool addMul(const std::vector<uint32_t>& ins, const std::vector<uint32_t>& outs, HexagonModel* model, OperationType op) { HEXAGON_SOFT_ASSERT_EQ(3, ins.size(), "Need 3 inputs for " << toString(op)); HEXAGON_SOFT_ASSERT_EQ(1, outs.size(), "Need 1 output for " << toString(op)); // get output size const Shape in1Shape = model->getShape(ins[0]); const Shape in2Shape = model->getShape(ins[1]); Shape outShape = model->getShape(outs[0]); HEXAGON_SOFT_ASSERT(addMulPrepare(in1Shape, in2Shape, &outShape), "Error getting shape"); HEXAGON_SOFT_ASSERT(model->setShape(outs[0], outShape), "Error setting shape"); return true; } bool add(const std::vector<uint32_t>& ins, const std::vector<uint32_t>& outs, HexagonModel* model) { return addMul(ins, outs, model, OperationType::ADD); } bool mul(const std::vector<uint32_t>& ins, const std::vector<uint32_t>& outs, HexagonModel* model) { return addMul(ins, outs, model, OperationType::MUL); } bool pool(const std::vector<uint32_t>& ins, const std::vector<uint32_t>& outs, HexagonModel* model, OperationType op) { HEXAGON_SOFT_ASSERT(ins.size() == 10 || ins.size() == 7, "Need 7 or 10 inputs for " << toString(op)); // get parameters const Shape inShape = model->getShape(ins[0]); // setup parameters int32_t padding_left; int32_t padding_right; int32_t padding_top; int32_t padding_bottom; int32_t stride_width; int32_t stride_height; int32_t filter_width; int32_t filter_height; // get parameters if (ins.size() == 10) { padding_left = model->getScalar<int32_t>(ins[1]); padding_right = model->getScalar<int32_t>(ins[2]); padding_top = model->getScalar<int32_t>(ins[3]); padding_bottom = model->getScalar<int32_t>(ins[4]); stride_width = model->getScalar<int32_t>(ins[5]); stride_height = model->getScalar<int32_t>(ins[6]); filter_width = model->getScalar<int32_t>(ins[7]); filter_height = model->getScalar<int32_t>(ins[8]); HEXAGON_SOFT_ASSERT_NE(getPadding(inShape.dimensions[2], inShape.dimensions[1], stride_width, stride_height, filter_width, filter_height, padding_left, padding_right, padding_top, padding_bottom), NN_PAD_NA, "Unknown padding"); } else { const int32_t padding_implicit = model->getScalar<int32_t>(ins[1]); stride_width = model->getScalar<int32_t>(ins[2]); stride_height = model->getScalar<int32_t>(ins[3]); filter_width = model->getScalar<int32_t>(ins[4]); filter_height = model->getScalar<int32_t>(ins[5]); nn::calculateExplicitPadding(inShape.dimensions[2], stride_width, filter_width, padding_implicit, &padding_left, &padding_right); nn::calculateExplicitPadding(inShape.dimensions[1], stride_height, filter_height, padding_implicit, &padding_top, &padding_bottom); } // get output size Shape outShape = model->getShape(outs[0]); HEXAGON_SOFT_ASSERT( genericPoolingPrepare(inShape, padding_left, padding_right, padding_top, padding_bottom, stride_width, stride_height, filter_width, filter_height, &outShape), "Error getting shape"); HEXAGON_SOFT_ASSERT(model->setShape(outs[0], outShape), "Error setting shape"); return true; } bool average_pool_2d(const std::vector<uint32_t>& ins, const std::vector<uint32_t>& outs, HexagonModel* model) { return pool(ins, outs, model, OperationType::AVERAGE_POOL_2D); } bool l2_pool_2d(const std::vector<uint32_t>& ins, const std::vector<uint32_t>& outs, HexagonModel* model) { return pool(ins, outs, model, OperationType::L2_POOL_2D); } bool max_pool_2d(const std::vector<uint32_t>& ins, const std::vector<uint32_t>& outs, HexagonModel* model) { return pool(ins, outs, model, OperationType::MAX_POOL_2D); } bool concatenation(const std::vector<uint32_t>& ins, const std::vector<uint32_t>& outs, HexagonModel* model) { std::string name = toString(OperationType::CONCATENATION); HEXAGON_SOFT_ASSERT_LE(3, ins.size(), "Need at least 3 inputs for " << name); HEXAGON_SOFT_ASSERT_EQ(1, outs.size(), "Need 1 output for " << name); const size_t numInputTensors = ins.size() - 1; const int32_t axis = model->getScalar<int32_t>(ins[numInputTensors]); // get output size std::vector<Shape> inShapes(numInputTensors); for (size_t i = 0; i < numInputTensors; ++i) { inShapes[i] = model->getShape(ins[i]); } Shape outShape = model->getShape(outs[0]); HEXAGON_SOFT_ASSERT(concatenationPrepare(inShapes, axis, &outShape), "Error getting shape"); HEXAGON_SOFT_ASSERT(model->setShape(outs[0], outShape), "Error setting shape"); return true; } bool conv_2d(const std::vector<uint32_t>& ins, const std::vector<uint32_t>& outs, HexagonModel* model) { std::string name = toString(OperationType::CONV_2D); HEXAGON_SOFT_ASSERT(ins.size() == 10 || ins.size() == 7, "Need 7 or 10 inputs for " << name); HEXAGON_SOFT_ASSERT_EQ(1, outs.size(), "Need 1 output for " << name); // setup shapes const Shape inputShape = model->getShape(ins[0]); const Shape filterShape = model->getShape(ins[1]); const Shape biasShape = model->getShape(ins[2]); // setup parameters int32_t padding_left; int32_t padding_right; int32_t padding_top; int32_t padding_bottom; int32_t stride_width; int32_t stride_height; // get parameters if (ins.size() == 10) { padding_left = model->getScalar<int32_t>(ins[3]); padding_right = model->getScalar<int32_t>(ins[4]); padding_top = model->getScalar<int32_t>(ins[5]); padding_bottom = model->getScalar<int32_t>(ins[6]); stride_width = model->getScalar<int32_t>(ins[7]); stride_height = model->getScalar<int32_t>(ins[8]); HEXAGON_SOFT_ASSERT_NE( getPadding(inputShape.dimensions[2], inputShape.dimensions[1], stride_width, stride_height, filterShape.dimensions[2], filterShape.dimensions[1], padding_left, padding_right, padding_top, padding_bottom), NN_PAD_NA, "Unknown padding"); } else { const int32_t padding_implicit = model->getScalar<int32_t>(ins[3]); stride_width = model->getScalar<int32_t>(ins[4]); stride_height = model->getScalar<int32_t>(ins[5]); nn::calculateExplicitPadding(inputShape.dimensions[2], stride_width, filterShape.dimensions[2], padding_implicit, &padding_left, &padding_right); nn::calculateExplicitPadding(inputShape.dimensions[1], stride_height, filterShape.dimensions[1], padding_implicit, &padding_top, &padding_bottom); } // get output size Shape outShape = model->getShape(outs[0]); HEXAGON_SOFT_ASSERT( convPrepare(inputShape, filterShape, biasShape, padding_left, padding_right, padding_top, padding_bottom, stride_width, stride_height, &outShape), "Error getting shape"); HEXAGON_SOFT_ASSERT(model->setShape(outs[0], outShape), "Error setting shape"); // enforce filter is a constant HEXAGON_SOFT_ASSERT(model->isConstant(ins[1]), name << "requires filter to be constant data"); return true; } bool depthwise_conv_2d(const std::vector<uint32_t>& ins, const std::vector<uint32_t>& outs, HexagonModel* model) { std::string name = toString(OperationType::DEPTHWISE_CONV_2D); HEXAGON_SOFT_ASSERT(ins.size() == 8 || ins.size() == 11, "Need 8 or 11 inputs for " << name); HEXAGON_SOFT_ASSERT_EQ(1, outs.size(), "Need 1 output for " << name); // setup shapes const Shape inputShape = model->getShape(ins[0]); const Shape filterShape = model->getShape(ins[1]); const Shape biasShape = model->getShape(ins[2]); // setup parameters int32_t padding_left; int32_t padding_right; int32_t padding_top; int32_t padding_bottom; int32_t stride_width; int32_t stride_height; // get parameters if (ins.size() == 11) { padding_left = model->getScalar<int32_t>(ins[3]); padding_right = model->getScalar<int32_t>(ins[4]); padding_top = model->getScalar<int32_t>(ins[5]); padding_bottom = model->getScalar<int32_t>(ins[6]); stride_width = model->getScalar<int32_t>(ins[7]); stride_height = model->getScalar<int32_t>(ins[8]); HEXAGON_SOFT_ASSERT_NE( getPadding(inputShape.dimensions[2], inputShape.dimensions[1], stride_width, stride_height, filterShape.dimensions[2], filterShape.dimensions[1], padding_left, padding_right, padding_top, padding_bottom), NN_PAD_NA, "Unknown padding"); } else { const int32_t padding_implicit = model->getScalar<int32_t>(ins[3]); stride_width = model->getScalar<int32_t>(ins[4]); stride_height = model->getScalar<int32_t>(ins[5]); nn::calculateExplicitPadding(inputShape.dimensions[2], stride_width, filterShape.dimensions[2], padding_implicit, &padding_left, &padding_right); nn::calculateExplicitPadding(inputShape.dimensions[1], stride_height, filterShape.dimensions[1], padding_implicit, &padding_top, &padding_bottom); } // get output size Shape outShape = model->getShape(outs[0]); HEXAGON_SOFT_ASSERT( depthwiseConvPrepare(inputShape, filterShape, biasShape, padding_left, padding_right, padding_top, padding_bottom, stride_width, stride_height, &outShape), "Error getting shape"); HEXAGON_SOFT_ASSERT(model->setShape(outs[0], outShape), "Error setting shape"); // enforce filter is a constant HEXAGON_SOFT_ASSERT(model->isConstant(ins[1]), name << " requires filter to be constant data"); return true; } bool dequantize(const std::vector<uint32_t>& ins, const std::vector<uint32_t>& outs, HexagonModel* model) { std::string name = toString(OperationType::DEQUANTIZE); HEXAGON_SOFT_ASSERT_EQ(1, ins.size(), "Need 1 input for " << name); HEXAGON_SOFT_ASSERT_EQ(1, outs.size(), "Need 1 output for " << name); // get output size const Shape inputShape = model->getShape(ins[0]); Shape outShape = model->getShape(outs[0]); HEXAGON_SOFT_ASSERT(dequantizePrepare(inputShape, &outShape), "Error getting shape"); HEXAGON_SOFT_ASSERT(model->setShape(outs[0], outShape), "Error setting shape"); return true; } bool fully_connected(const std::vector<uint32_t>& ins, const std::vector<uint32_t>& outs, HexagonModel* model) { std::string name = toString(OperationType::FULLY_CONNECTED); HEXAGON_SOFT_ASSERT_EQ(4, ins.size(), "Need 4 inputs for " << name); HEXAGON_SOFT_ASSERT_EQ(1, outs.size(), "Need 1 output for " << name); // get output size const Shape inputShape = model->getShape(ins[0]); const Shape weightsShape = model->getShape(ins[1]); const Shape biasShape = model->getShape(ins[2]); Shape outShape = model->getShape(outs[0]); HEXAGON_SOFT_ASSERT(fullyConnectedPrepare(inputShape, weightsShape, biasShape, &outShape), "Error getting shape"); HEXAGON_SOFT_ASSERT(model->setShape(outs[0], outShape), "Error setting shape"); // enforce weight is a constant HEXAGON_SOFT_ASSERT(model->isConstant(ins[1]), name << "requires weight to be constant data"); return true; } bool local_response_normalization(const std::vector<uint32_t>& ins, const std::vector<uint32_t>& outs, HexagonModel* model) { std::string name = toString(OperationType::LOCAL_RESPONSE_NORMALIZATION); HEXAGON_SOFT_ASSERT_EQ(5, ins.size(), "Need 5 inputs for " << name); HEXAGON_SOFT_ASSERT_EQ(1, outs.size(), "Need 1 output for " << name); // get output size const Shape inShape = model->getShape(ins[0]); Shape outShape = model->getShape(outs[0]); HEXAGON_SOFT_ASSERT(genericNormalizationPrepare(inShape, &outShape), "Error getting shape"); HEXAGON_SOFT_ASSERT(model->setShape(outs[0], outShape), "Error setting shape"); return true; } bool activation(const std::vector<uint32_t>& ins, const std::vector<uint32_t>& outs, HexagonModel* model, uint32_t numInputs, OperationType op) { HEXAGON_SOFT_ASSERT_EQ(numInputs, ins.size(), "Need " << numInputs << " input for " << toString(op)); HEXAGON_SOFT_ASSERT_EQ(1, outs.size(), "Need 1 output for " << toString(op)); // get output size const Shape inShape = model->getShape(ins[0]); Shape outShape = model->getShape(outs[0]); HEXAGON_SOFT_ASSERT(genericActivationPrepare(inShape, &outShape), "Error getting shape"); HEXAGON_SOFT_ASSERT(model->setShape(outs[0], outShape), "Error setting shape"); return true; } bool logistic(const std::vector<uint32_t>& ins, const std::vector<uint32_t>& outs, HexagonModel* model) { return activation(ins, outs, model, 1, OperationType::LOGISTIC); } bool relu(const std::vector<uint32_t>& ins, const std::vector<uint32_t>& outs, HexagonModel* model) { return activation(ins, outs, model, 1, OperationType::RELU); } bool relu1(const std::vector<uint32_t>& ins, const std::vector<uint32_t>& outs, HexagonModel* model) { return activation(ins, outs, model, 1, OperationType::RELU1); } bool relu6(const std::vector<uint32_t>& ins, const std::vector<uint32_t>& outs, HexagonModel* model) { return activation(ins, outs, model, 1, OperationType::RELU6); } bool softmax(const std::vector<uint32_t>& ins, const std::vector<uint32_t>& outs, HexagonModel* model) { return activation(ins, outs, model, 2, OperationType::SOFTMAX); } bool tanh(const std::vector<uint32_t>& ins, const std::vector<uint32_t>& outs, HexagonModel* model) { return activation(ins, outs, model, 1, OperationType::TANH); } bool reshape(const std::vector<uint32_t>& ins, const std::vector<uint32_t>& outs, HexagonModel* model) { std::string name = toString(OperationType::RESHAPE); HEXAGON_SOFT_ASSERT_EQ(2, ins.size(), "Need 2 inputs for " << name); HEXAGON_SOFT_ASSERT_EQ(1, outs.size(), "Need 1 output for " << name); // get output size const Shape inShape = model->getShape(ins[0]); const Shape targetShape = model->getShape(ins[1]); const int32_t* targetShapePtr = model->getPointer(ins[1]); int32_t targetShapeNumElem = ::android::nn::getNumberOfElements(targetShape); Shape outShape = model->getShape(outs[0]); HEXAGON_SOFT_ASSERT(targetShapePtr != nullptr, "pointer value is currently nullptr"); HEXAGON_SOFT_ASSERT(reshapePrepare(inShape, targetShapePtr, targetShapeNumElem, &outShape), "Error getting shape"); HEXAGON_SOFT_ASSERT(model->setShape(outs[0], outShape), "Error setting shape"); return true; } bool resize_bilinear(const std::vector<uint32_t>& ins, const std::vector<uint32_t>& outs, HexagonModel* model) { std::string name = toString(OperationType::RESIZE_BILINEAR); HEXAGON_SOFT_ASSERT_EQ(3, ins.size(), "Need 3 inputs for " << name); HEXAGON_SOFT_ASSERT_EQ(1, outs.size(), "Need 1 output for " << name); // get parameters const int32_t width = model->getScalar<int32_t>(ins[1]); const int32_t height = model->getScalar<int32_t>(ins[2]); // get output size const Shape inShape = model->getShape(ins[0]); Shape outShape = model->getShape(outs[0]); HEXAGON_SOFT_ASSERT(resizeBilinearPrepare(inShape, width, height, &outShape), "Error getting shape"); HEXAGON_SOFT_ASSERT(model->setShape(outs[0], outShape), "Error setting shape"); return true; } } // namespace OperationTable& getOperationCheckTable() { static OperationTable table = { // NOTE: the operations that are commented out via inline represent // operations that are valid for the Android O NNAPI release, but are // currently not implemented in HVX. // -------------------------- 32-BIT FLOAT ---------------------------- // HVX is only performant when running on quantized values. Further, as // an optimization, the current HVX driver will convert some floating // point tensors into quantized values, perform the operation, and then // convert them back to floating point. This results in a loss in // precision causing some tests to fail. For these reasons, the FLOAT32 // operations are being temporarily disabled. /* {{OperationType::ADD, OperandType::TENSOR_FLOAT32}, add}, {{OperationType::AVERAGE_POOL_2D, OperandType::TENSOR_FLOAT32}, average_pool_2d}, {{OperationType::CONCATENATION, OperandType::TENSOR_FLOAT32}, concatenation}, {{OperationType::CONV_2D, OperandType::TENSOR_FLOAT32}, conv_2d}, {{OperationType::DEPTHWISE_CONV_2D, OperandType::TENSOR_FLOAT32}, depthwise_conv_2d}, //{{OperationType::DEPTH_TO_SPACE, OperandType::TENSOR_FLOAT32}, depth_to_space}, //{{OperationType::EMBEDDING_LOOKUP, OperandType::TENSOR_FLOAT32}, embedding_lookup}, //{{OperationType::FLOOR, OperandType::TENSOR_FLOAT32}, floor}, {{OperationType::FULLY_CONNECTED, OperandType::TENSOR_FLOAT32}, fully_connected}, //{{OperationType::HASHTABLE_LOOKUP, OperandType::TENSOR_FLOAT32}, hashtable_lookup}, //{{OperationType::L2_NORMALIZATION, OperandType::TENSOR_FLOAT32}, l2_normalization}, {{OperationType::L2_POOL_2D, OperandType::TENSOR_FLOAT32}, l2_pool_2d}, {{OperationType::LOCAL_RESPONSE_NORMALIZATION, OperandType::TENSOR_FLOAT32}, local_response_normalization}, {{OperationType::LOGISTIC, OperandType::TENSOR_FLOAT32}, logistic}, //{{OperationType::LSH_PROJECTION, OperandType::TENSOR_FLOAT32}, lsh_projection}, //{{OperationType::LSTM, OperandType::TENSOR_FLOAT32}, lstm }, {{OperationType::MAX_POOL_2D, OperandType::TENSOR_FLOAT32}, max_pool_2d}, {{OperationType::MUL, OperandType::TENSOR_FLOAT32}, mul}, {{OperationType::RELU, OperandType::TENSOR_FLOAT32}, relu}, {{OperationType::RELU1, OperandType::TENSOR_FLOAT32}, relu1}, {{OperationType::RELU6, OperandType::TENSOR_FLOAT32}, relu6}, {{OperationType::RESHAPE, OperandType::TENSOR_FLOAT32}, reshape}, {{OperationType::RESIZE_BILINEAR, OperandType::TENSOR_FLOAT32}, resize_bilinear}, //{{OperationType::RNN, OperandType::TENSOR_FLOAT32}, rnn}, {{OperationType::SOFTMAX, OperandType::TENSOR_FLOAT32}, softmax}, //{{OperationType::SPACE_TO_DEPTH, OperandType::TENSOR_FLOAT32}, space_to_depth}, //{{OperationType::SVDF, OperandType::TENSOR_FLOAT32}, svdf }, {{OperationType::TANH, OperandType::TENSOR_FLOAT32}, tanh}, */ // -------------------- QUANTIZED 8-BIT ASYMMETRICAL ------------------ {{OperationType::ADD, OperandType::TENSOR_QUANT8_ASYMM}, add}, {{OperationType::AVERAGE_POOL_2D, OperandType::TENSOR_QUANT8_ASYMM}, average_pool_2d}, {{OperationType::CONCATENATION, OperandType::TENSOR_QUANT8_ASYMM}, concatenation}, {{OperationType::CONV_2D, OperandType::TENSOR_QUANT8_ASYMM}, conv_2d}, {{OperationType::DEPTHWISE_CONV_2D, OperandType::TENSOR_QUANT8_ASYMM}, depthwise_conv_2d}, //{{OperationType::DEPTH_TO_SPACE, OperandType::TENSOR_QUANT8_ASYMM}, depth_to_space}, {{OperationType::DEQUANTIZE, OperandType::TENSOR_QUANT8_ASYMM}, dequantize}, //{{OperationType::EMBEDDING_LOOKUP, OperandType::TENSOR_QUANT8_ASYMM}, embedding_lookup}, {{OperationType::FULLY_CONNECTED, OperandType::TENSOR_QUANT8_ASYMM}, fully_connected}, //{{OperationType::HASHTABLE_LOOKUP, OperandType::TENSOR_QUANT8_ASYMM}, hashtable_lookup}, {{OperationType::LOGISTIC, OperandType::TENSOR_QUANT8_ASYMM}, logistic}, //{{OperationType::LSH_PROJECTION, OperandType::TENSOR_QUANT8_ASYMM}, lsh_projection}, {{OperationType::MAX_POOL_2D, OperandType::TENSOR_QUANT8_ASYMM}, max_pool_2d}, {{OperationType::MUL, OperandType::TENSOR_QUANT8_ASYMM}, mul}, {{OperationType::RELU, OperandType::TENSOR_QUANT8_ASYMM}, relu}, {{OperationType::RELU1, OperandType::TENSOR_QUANT8_ASYMM}, relu1}, {{OperationType::RELU6, OperandType::TENSOR_QUANT8_ASYMM}, relu6}, {{OperationType::RESHAPE, OperandType::TENSOR_QUANT8_ASYMM}, reshape}, {{OperationType::SOFTMAX, OperandType::TENSOR_QUANT8_ASYMM}, softmax}, //{{OperationType::SPACE_TO_DEPTH, OperandType::TENSOR_QUANT8_ASYMM}, space_to_depth}, }; // The following functions are normally used by float32, but those // operations have been temporarily disabled. Void explicitly marks them as // unused, and prevents the compiler from throwing an error. (void)l2_pool_2d; (void)local_response_normalization; (void)tanh; (void)resize_bilinear; return table; } } // namespace hexagon } // namespace implementation } // namespace V1_0 } // namespace neuralnetworks } // namespace hardware } // namespace android
45.790744
100
0.671193
[ "shape", "vector", "model" ]
d905b248bd83917a06e807c8b3c5fcbe12326c04
9,340
cpp
C++
src/main.cpp
sn0opy/pogo-proto-dumper
e622093823c346ea89d3f2236a4e5a89e1255b75
[ "MIT" ]
null
null
null
src/main.cpp
sn0opy/pogo-proto-dumper
e622093823c346ea89d3f2236a4e5a89e1255b75
[ "MIT" ]
null
null
null
src/main.cpp
sn0opy/pogo-proto-dumper
e622093823c346ea89d3f2236a4e5a89e1255b75
[ "MIT" ]
1
2019-09-13T23:41:41.000Z
2019-09-13T23:41:41.000Z
#include <cstdint> #include <fstream> #include <iostream> #include <set> #include <map> #include <string> #include <vector> #include "il2cpp.hpp" using namespace std; using namespace il2cpp; bool is_little_endian() { auto number = 0x1; auto ptr = reinterpret_cast<char *>(&number); return ptr[0] == 1; } bool str_ends_with(string const& fullString, string const& ending) { if (fullString.length() >= ending.length()) { return (0 == fullString.compare(fullString.length() - ending.length(), ending.length(), ending)); } else { return false; } } int main(int argc, char* argv[]) { try { if (!is_little_endian()) { throw runtime_error("System must be little-endian"); } if (argc != 2) { throw runtime_error("Usage: umd path/to/global-metadata.dat"); } ifstream global_metdata(argv[1], ios::binary); metadata metadata(global_metdata); // All of the game's data can be found in the "Assembly-CSharp.dll" image Il2CppImageDefinition* game_image = nullptr; for (unsigned i = 0; i < COUNT(metadata, images); i++) { if (STRING(metadata, metadata.images[i].nameIndex) == "Assembly-CSharp.dll") { game_image = &metadata.images[i]; break; } } if (game_image == nullptr) { throw runtime_error("Unable to find \"Assembly-CSharp.dll\" image"); } // Keep track of types referenced by fields to find nested enumerations set<TypeDefinitionIndex> referenced_types; // Create a mapping of TypeIndexes to TypeDefinitionIndexes in order to // get the type of Il2CppMethodDefinition::returnType std::map<TypeIndex, TypeDefinitionIndex> type_index_mapping; for (unsigned i = 0; i < COUNT(metadata, images); i++) { auto image = &metadata.images[i]; for (unsigned j = image->typeStart; j < image->typeStart + image->typeCount; j++) { auto type = &metadata.typeDefinitions[j]; type_index_mapping.emplace(type->byvalTypeIndex, j); } } // Enumerate every type in the image for (unsigned i = game_image->typeStart; i < game_image->typeStart + game_image->typeCount; i++) { auto type = &metadata.typeDefinitions[i]; // Filter out non-protobuf namespaces if (STRING(metadata, type->namespaceIndex) != "Holoholo.Rpc") continue; // If our type is an enum if (type->enum_type) { cout << "enum " << STRING(metadata, type->nameIndex) << " {" << endl; // Skip the first field which will always be "__value" for (auto j = type->fieldStart + 1; j < type->fieldStart + type->field_count; j++) { auto field = metadata.fields[j]; auto element_name = STRING(metadata, field.nameIndex); auto element_value = 0; // Get value from the default value of the field for (unsigned k = 0; k < COUNT(metadata, fieldDefaultValues); k++) { auto field_default_value = &metadata.fieldDefaultValues[k]; if (field_default_value->fieldIndex != j) continue; if (STRING(metadata, metadata.typeDefinitions[field_default_value->typeIndex].nameIndex) != "Byte") { throw runtime_error(("Field default value is not a byte (typeIndex=" + to_string(field_default_value->typeIndex) + ")").c_str()); } element_value = metadata.fieldAndParameterDefaultValueData[field_default_value->dataIndex]; break; } cout << "\t" << element_name << " = " << element_value << ";" << endl; } cout << "}" << endl << endl; continue; } // If our type is a protobuf message auto has_parser_field = false; for (unsigned j = type->fieldStart; j < type->fieldStart + type->field_count; j++) { if (STRING(metadata, metadata.fields[j].nameIndex) == "_parser") { has_parser_field = true; break; } } if (has_parser_field) { referenced_types.clear(); cout << "message " << STRING(metadata, type->nameIndex) << " { " << endl; for (unsigned j = type->fieldStart; j < type->fieldStart + type->field_count; j++) { auto field = metadata.fields[j]; auto field_name = STRING(metadata, field.nameIndex); if (!str_ends_with(field_name, "FieldNumber")) continue; string proto_type_name = ""; auto proto_field_name = field_name.substr(0, field_name.length() - 11); auto proto_field_number = 0; // Get protobuf field number from the default value of the field for (unsigned k = 0; k < COUNT(metadata, fieldDefaultValues); k++) { auto field_default_value = &metadata.fieldDefaultValues[k]; if (field_default_value->fieldIndex != j) continue; if (STRING(metadata, metadata.typeDefinitions[field_default_value->typeIndex].nameIndex) != "Byte") { throw runtime_error(("Field default value is not a byte (typeIndex=" + to_string(field_default_value->typeIndex) + ")").c_str()); } proto_field_number = metadata.fieldAndParameterDefaultValueData[field_default_value->dataIndex]; break; } // Get the proto field type from the return type of the generated getter for (unsigned k = type->methodStart; k < type->methodStart + type->method_count; k++) { auto method = &metadata.methods[k]; if (STRING(metadata, method->nameIndex) != "get_" + proto_field_name) continue; // Identify the return type from the mapping of byval type indexes if (type_index_mapping.find(method->returnType) != type_index_mapping.end()) { auto definition_index = type_index_mapping.at(method->returnType); proto_type_name = STRING(metadata, metadata.typeDefinitions[definition_index].nameIndex); // Map C# types to Protobuf types for conversion const map<string, string> csharp_to_protobuf_types = { {"Int32", "int32"}, {"Int64", "int64"}, {"UInt64", "fixed64"}, {"UInt32", "fixed32"}, {"Single", "float"}, {"Boolean", "bool"}, {"Double", "double"}, {"String", "string"}, {"ByteString", "bytes"} }; if (csharp_to_protobuf_types.find(proto_type_name) != csharp_to_protobuf_types.end()) { proto_type_name = csharp_to_protobuf_types.at(proto_type_name); } referenced_types.insert(definition_index); } // If it's not there, it's a generic type, e.g. a RepeatedField<T> or List<T> else { //TODO resolve generic types proto_type_name = "Generic" + to_string(method->returnType); } } cout << "\t" << proto_type_name << " " << proto_field_name << " = " << proto_field_number << ";" << endl; } for (auto referenced_type_index : referenced_types) { auto referenced_type = &metadata.typeDefinitions[referenced_type_index]; // If the referenced type is a child of the current type if (type_index_mapping.find(referenced_type->declaringTypeIndex) == type_index_mapping.end()) continue; if (type_index_mapping.at(referenced_type->declaringTypeIndex) - 1 != i) continue; cout << endl << "\tenum " << STRING(metadata, referenced_type->nameIndex) << " {" << endl; // Skip the first field which will always be "__value" for (auto j = referenced_type->fieldStart + 1; j < referenced_type->fieldStart + referenced_type->field_count; j++) { auto field = metadata.fields[j]; auto element_name = STRING(metadata, field.nameIndex); auto element_value = 0; // Get value from the default value of the field for (unsigned k = 0; k < COUNT(metadata, fieldDefaultValues); k++) { auto field_default_value = &metadata.fieldDefaultValues[k]; if (field_default_value->fieldIndex != j) continue; if (STRING(metadata, metadata.typeDefinitions[field_default_value->typeIndex].nameIndex) != "Byte") { throw runtime_error(("Field default value is not a byte (typeIndex=" + to_string(field_default_value->typeIndex) + ")").c_str()); } element_value = metadata.fieldAndParameterDefaultValueData[field_default_value->dataIndex]; break; } cout << "\t\t" << element_name << " = " << element_value << ";" << endl; } cout << "\t}" << endl; } cout << "}" << endl << endl; continue; } } } catch (exception& e) { cerr << e.what() << endl; return EXIT_FAILURE; } }
37.66129
146
0.574197
[ "vector" ]
d90718af230c479f455dc52209de27e8659f0621
6,976
hpp
C++
Versionen/2021_06_15/rmf_ws/install/rmf_task_msgs/include/rmf_task_msgs/msg/detail/tow__struct.hpp
flitzmo-hso/flitzmo_agv_control_system
99e8006920c03afbd93e4c7d38b4efff514c7069
[ "MIT" ]
null
null
null
Versionen/2021_06_15/rmf_ws/install/rmf_task_msgs/include/rmf_task_msgs/msg/detail/tow__struct.hpp
flitzmo-hso/flitzmo_agv_control_system
99e8006920c03afbd93e4c7d38b4efff514c7069
[ "MIT" ]
null
null
null
Versionen/2021_06_15/rmf_ws/install/rmf_task_msgs/include/rmf_task_msgs/msg/detail/tow__struct.hpp
flitzmo-hso/flitzmo_agv_control_system
99e8006920c03afbd93e4c7d38b4efff514c7069
[ "MIT" ]
2
2021-06-21T07:32:09.000Z
2021-08-17T03:05:38.000Z
// generated from rosidl_generator_cpp/resource/idl__struct.hpp.em // with input from rmf_task_msgs:msg/Tow.idl // generated code does not contain a copyright notice #ifndef RMF_TASK_MSGS__MSG__DETAIL__TOW__STRUCT_HPP_ #define RMF_TASK_MSGS__MSG__DETAIL__TOW__STRUCT_HPP_ #include <rosidl_runtime_cpp/bounded_vector.hpp> #include <rosidl_runtime_cpp/message_initialization.hpp> #include <algorithm> #include <array> #include <memory> #include <string> #include <vector> #ifndef _WIN32 # define DEPRECATED__rmf_task_msgs__msg__Tow __attribute__((deprecated)) #else # define DEPRECATED__rmf_task_msgs__msg__Tow __declspec(deprecated) #endif namespace rmf_task_msgs { namespace msg { // message struct template<class ContainerAllocator> struct Tow_ { using Type = Tow_<ContainerAllocator>; explicit Tow_(rosidl_runtime_cpp::MessageInitialization _init = rosidl_runtime_cpp::MessageInitialization::ALL) { if (rosidl_runtime_cpp::MessageInitialization::ALL == _init || rosidl_runtime_cpp::MessageInitialization::ZERO == _init) { this->task_id = ""; this->object_type = ""; this->is_object_id_known = false; this->object_id = ""; this->pickup_place_name = ""; this->is_dropoff_place_known = false; this->dropoff_place_name = ""; } } explicit Tow_(const ContainerAllocator & _alloc, rosidl_runtime_cpp::MessageInitialization _init = rosidl_runtime_cpp::MessageInitialization::ALL) : task_id(_alloc), object_type(_alloc), object_id(_alloc), pickup_place_name(_alloc), dropoff_place_name(_alloc) { if (rosidl_runtime_cpp::MessageInitialization::ALL == _init || rosidl_runtime_cpp::MessageInitialization::ZERO == _init) { this->task_id = ""; this->object_type = ""; this->is_object_id_known = false; this->object_id = ""; this->pickup_place_name = ""; this->is_dropoff_place_known = false; this->dropoff_place_name = ""; } } // field types and members using _task_id_type = std::basic_string<char, std::char_traits<char>, typename ContainerAllocator::template rebind<char>::other>; _task_id_type task_id; using _object_type_type = std::basic_string<char, std::char_traits<char>, typename ContainerAllocator::template rebind<char>::other>; _object_type_type object_type; using _is_object_id_known_type = bool; _is_object_id_known_type is_object_id_known; using _object_id_type = std::basic_string<char, std::char_traits<char>, typename ContainerAllocator::template rebind<char>::other>; _object_id_type object_id; using _pickup_place_name_type = std::basic_string<char, std::char_traits<char>, typename ContainerAllocator::template rebind<char>::other>; _pickup_place_name_type pickup_place_name; using _is_dropoff_place_known_type = bool; _is_dropoff_place_known_type is_dropoff_place_known; using _dropoff_place_name_type = std::basic_string<char, std::char_traits<char>, typename ContainerAllocator::template rebind<char>::other>; _dropoff_place_name_type dropoff_place_name; // setters for named parameter idiom Type & set__task_id( const std::basic_string<char, std::char_traits<char>, typename ContainerAllocator::template rebind<char>::other> & _arg) { this->task_id = _arg; return *this; } Type & set__object_type( const std::basic_string<char, std::char_traits<char>, typename ContainerAllocator::template rebind<char>::other> & _arg) { this->object_type = _arg; return *this; } Type & set__is_object_id_known( const bool & _arg) { this->is_object_id_known = _arg; return *this; } Type & set__object_id( const std::basic_string<char, std::char_traits<char>, typename ContainerAllocator::template rebind<char>::other> & _arg) { this->object_id = _arg; return *this; } Type & set__pickup_place_name( const std::basic_string<char, std::char_traits<char>, typename ContainerAllocator::template rebind<char>::other> & _arg) { this->pickup_place_name = _arg; return *this; } Type & set__is_dropoff_place_known( const bool & _arg) { this->is_dropoff_place_known = _arg; return *this; } Type & set__dropoff_place_name( const std::basic_string<char, std::char_traits<char>, typename ContainerAllocator::template rebind<char>::other> & _arg) { this->dropoff_place_name = _arg; return *this; } // constant declarations // pointer types using RawPtr = rmf_task_msgs::msg::Tow_<ContainerAllocator> *; using ConstRawPtr = const rmf_task_msgs::msg::Tow_<ContainerAllocator> *; using SharedPtr = std::shared_ptr<rmf_task_msgs::msg::Tow_<ContainerAllocator>>; using ConstSharedPtr = std::shared_ptr<rmf_task_msgs::msg::Tow_<ContainerAllocator> const>; template<typename Deleter = std::default_delete< rmf_task_msgs::msg::Tow_<ContainerAllocator>>> using UniquePtrWithDeleter = std::unique_ptr<rmf_task_msgs::msg::Tow_<ContainerAllocator>, Deleter>; using UniquePtr = UniquePtrWithDeleter<>; template<typename Deleter = std::default_delete< rmf_task_msgs::msg::Tow_<ContainerAllocator>>> using ConstUniquePtrWithDeleter = std::unique_ptr<rmf_task_msgs::msg::Tow_<ContainerAllocator> const, Deleter>; using ConstUniquePtr = ConstUniquePtrWithDeleter<>; using WeakPtr = std::weak_ptr<rmf_task_msgs::msg::Tow_<ContainerAllocator>>; using ConstWeakPtr = std::weak_ptr<rmf_task_msgs::msg::Tow_<ContainerAllocator> const>; // pointer types similar to ROS 1, use SharedPtr / ConstSharedPtr instead // NOTE: Can't use 'using' here because GNU C++ can't parse attributes properly typedef DEPRECATED__rmf_task_msgs__msg__Tow std::shared_ptr<rmf_task_msgs::msg::Tow_<ContainerAllocator>> Ptr; typedef DEPRECATED__rmf_task_msgs__msg__Tow std::shared_ptr<rmf_task_msgs::msg::Tow_<ContainerAllocator> const> ConstPtr; // comparison operators bool operator==(const Tow_ & other) const { if (this->task_id != other.task_id) { return false; } if (this->object_type != other.object_type) { return false; } if (this->is_object_id_known != other.is_object_id_known) { return false; } if (this->object_id != other.object_id) { return false; } if (this->pickup_place_name != other.pickup_place_name) { return false; } if (this->is_dropoff_place_known != other.is_dropoff_place_known) { return false; } if (this->dropoff_place_name != other.dropoff_place_name) { return false; } return true; } bool operator!=(const Tow_ & other) const { return !this->operator==(other); } }; // struct Tow_ // alias to use template instance with default allocator using Tow = rmf_task_msgs::msg::Tow_<std::allocator<void>>; // constant definitions } // namespace msg } // namespace rmf_task_msgs #endif // RMF_TASK_MSGS__MSG__DETAIL__TOW__STRUCT_HPP_
31.853881
148
0.726778
[ "vector" ]
d90c9b68648e49dcffe253f86eed3c7ce8558ebe
3,623
cpp
C++
test_package/tests/unit/geom/CoordinateListTest.cpp
insaneFactory/conan-geos
2d682cf59eafe8567e8e5c87897f051355dbb1ca
[ "MIT" ]
null
null
null
test_package/tests/unit/geom/CoordinateListTest.cpp
insaneFactory/conan-geos
2d682cf59eafe8567e8e5c87897f051355dbb1ca
[ "MIT" ]
null
null
null
test_package/tests/unit/geom/CoordinateListTest.cpp
insaneFactory/conan-geos
2d682cf59eafe8567e8e5c87897f051355dbb1ca
[ "MIT" ]
null
null
null
// // Test Suite for geos::geom::CoordinateList class. // tut #include <tut/tut.hpp> // geos #include <geos/geom/Coordinate.h> #include <geos/geom/CoordinateList.h> #include <geos/geom/CoordinateArraySequence.h> // std #include <memory> #include <string> #include <vector> namespace tut { // // Test Group // // Common data used by tests struct test_coordinatelist_data { test_coordinatelist_data() {} }; typedef test_group<test_coordinatelist_data> group; typedef group::object object; group test_coordinatelist_group("geos::geom::CoordinateList"); // // Test Cases // // Test insert and erase template<> template<> void object::test<1> () { using geos::geom::Coordinate; const Coordinate a(0, 0); const Coordinate b(10, 10); const Coordinate c(20, 20); const Coordinate d(5, 5); geos::geom::CoordinateList::iterator it, it2; std::unique_ptr< std::vector<Coordinate> > col(new std::vector<Coordinate>()); col->push_back(a); col->push_back(b); col->push_back(c); // coordinates are copied geos::geom::CoordinateList clist(*col); ensure_equals(clist.size(), 3u); it = clist.begin(); clist.insert(++it, d); ensure_equals(clist.size(), 4u); it = clist.begin(); ensure_equals(*it, a); ++it; ensure_equals(*it, d); ++it; ensure_equals(*it, b); ++it; ensure_equals(*it, c); it = clist.begin(); ++it; ++it; clist.erase(it); ensure_equals(clist.size(), 3u); it = clist.begin(); ensure_equals(*it, a); ++it; ensure_equals(*it, d); ++it; ensure_equals(*it, c); clist.insert(clist.end(), b); ensure_equals(clist.size(), 4u); it = clist.begin(); ++it; it2 = it; ++it2; ++it2; clist.erase(it, it2); ensure_equals(clist.size(), 2u); it = clist.begin(); ensure_equals(*it, a); ++it; ensure_equals(*it, b); } // Test insert with and without duplicates template<> template<> void object::test<2> () { using geos::geom::Coordinate; geos::geom::CoordinateList clist; ensure_equals(clist.size(), 0u); clist.insert(clist.end(), Coordinate(0, 0)); ensure_equals(clist.size(), 1u); clist.insert(clist.end(), Coordinate(0, 0), false); ensure_equals(clist.size(), 1u); clist.insert(clist.end(), Coordinate(0, 0), true); ensure_equals(clist.size(), 2u); clist.insert(clist.end(), Coordinate(1, 1), true); ensure_equals(clist.size(), 3u); geos::geom::CoordinateList::iterator it = clist.end(); --it; clist.insert(it, Coordinate(0, 0), false); ensure_equals(clist.size(), 3u); } //Test to check the functioning of closeRing() method. template<> template<> void object::test<3> () { using geos::geom::Coordinate; const Coordinate a(0, 0); const Coordinate b(10, 10); const Coordinate c(45, 60); const Coordinate d(100, 0); std::unique_ptr< std::vector<Coordinate> > v(new std::vector<Coordinate>()); v->push_back(a); v->push_back(b); v->push_back(c); v->push_back(d); geos::geom::CoordinateList coordlist(*v); coordlist.closeRing(); geos::geom::CoordinateList::iterator it1, it2; it1 = coordlist.begin(); it2 = --coordlist.end(); ensure_equals(*it1, *it2); /* for(CoordinateList::iterator it=coordlist.begin() ; it!=coordlist.end() ; ++it) { cout << (*it).x << " " << (*it).y << endl; }*/ //If the list is empty:: coordlist.erase(coordlist.begin(), coordlist.end()); coordlist.closeRing(); ensure_equals(coordlist.empty(), true); } } // namespace tut
20.585227
86
0.620204
[ "object", "vector" ]
d90f0ae37732322d546f2baba34745ed8bc9c726
1,600
cpp
C++
C Plus Plus/Graph/Breadth_First_Search.cpp
Nilesh-10/DS-Algo
c3a312bea6d49709f317dbf42d515cf12abd5f74
[ "MIT" ]
1
2021-07-03T18:20:38.000Z
2021-07-03T18:20:38.000Z
C Plus Plus/Graph/Breadth_First_Search.cpp
Nilesh-10/DS-Algo
c3a312bea6d49709f317dbf42d515cf12abd5f74
[ "MIT" ]
null
null
null
C Plus Plus/Graph/Breadth_First_Search.cpp
Nilesh-10/DS-Algo
c3a312bea6d49709f317dbf42d515cf12abd5f74
[ "MIT" ]
null
null
null
/* Breadth first search is a graph traversal algorithm that starts traversing the graph from root node and explores all the neighbouring nodes. Then, it selects the nearest node and explore all the unexplored nodes. The algorithm follows the same process for each of the nearest node until it finds the goal. */ #include <iostream> #include <vector> #include <queue> using namespace std; void addEdge(vector<int> graph[], int u, int v) { graph[u].emplace_back(v); graph[v].emplace_back(u); } void bfs(vector<int> graph[], int start) { vector<bool> visited(graph->size(), false); queue<int> q; q.push(start); visited[start] = true; while (!q.empty()) { int v = q.front(); cout << v << " "; q.pop(); // Insert all adjacent nodes of v and mark them visited to avoid cycles. for (auto i = graph[v].begin(); i != graph[v].end(); i++) { if (!visited[*i]) { q.push(*i); visited[*i] = true; } } } } int main() { int V = 9; vector<int> graph[V]; //Pair of Nodes addEdge(graph, 0, 1); addEdge(graph, 0, 3); addEdge(graph, 1, 2); addEdge(graph, 2, 3); addEdge(graph, 2, 5); addEdge(graph, 3, 4); addEdge(graph, 4, 5); addEdge(graph, 4, 6); addEdge(graph, 5, 7); addEdge(graph, 6, 7); //Print BFS Traversal cout << "BFS traversal:" << " "; bfs(graph, 0); } /* Time complexity - O(V + E) Space complexity - O(|V|) Where E is number of edges and V is number of vertices. */
25
144
0.571875
[ "vector" ]
d91de006f057b2d88dc8ff97059767ecdab7b0bd
6,560
cpp
C++
Pepper/ListEx/src/CListExHdr.cpp
zhuhuibeishadiao/Pepper
00f5891e5c05b1da6dd52a136c4715cb8803e1af
[ "MIT" ]
null
null
null
Pepper/ListEx/src/CListExHdr.cpp
zhuhuibeishadiao/Pepper
00f5891e5c05b1da6dd52a136c4715cb8803e1af
[ "MIT" ]
null
null
null
Pepper/ListEx/src/CListExHdr.cpp
zhuhuibeishadiao/Pepper
00f5891e5c05b1da6dd52a136c4715cb8803e1af
[ "MIT" ]
1
2021-01-11T15:10:34.000Z
2021-01-11T15:10:34.000Z
/**************************************************************************************** * Copyright © 2018-2020 Jovibor https://github.com/jovibor/ * * This is very extended and featured version of CMFCListCtrl class. * * Official git repository: https://github.com/jovibor/ListEx/ * * This class is available under the "MIT License". * * For more information visit the project's official repository. * ****************************************************************************************/ #include "stdafx.h" #include "../ListEx.h" #include "CListExHdr.h" using namespace LISTEX; using namespace LISTEX::INTERNAL; /**************************************************** * CListExHdr class implementation. * ****************************************************/ BEGIN_MESSAGE_MAP(CListExHdr, CMFCHeaderCtrl) ON_MESSAGE(HDM_LAYOUT, &CListExHdr::OnLayout) ON_WM_HSCROLL() ON_WM_DESTROY() END_MESSAGE_MAP() CListExHdr::CListExHdr() { NONCLIENTMETRICSW ncm { }; ncm.cbSize = sizeof(NONCLIENTMETRICSW); SystemParametersInfoW(SPI_GETNONCLIENTMETRICS, ncm.cbSize, &ncm, 0); ncm.lfMessageFont.lfHeight = 16; //For some weird reason above func returns this value as MAX_LONG. m_fontHdr.CreateFontIndirectW(&ncm.lfMessageFont); m_penGrid.CreatePen(PS_SOLID, 2, RGB(220, 220, 220)); m_penLight.CreatePen(PS_SOLID, 1, GetSysColor(COLOR_3DHILIGHT)); m_penShadow.CreatePen(PS_SOLID, 1, GetSysColor(COLOR_3DSHADOW)); } void CListExHdr::OnDrawItem(CDC* pDC, int iItem, CRect rect, BOOL bIsPressed, BOOL bIsHighlighted) { if (iItem < 0) //Non working area, after last column. { pDC->FillSolidRect(&rect, m_clrBkNWA); return; } CMemDC memDC(*pDC, rect); CDC& rDC = memDC.GetDC(); COLORREF clrBk, clrText; if (m_umapClrColumn.find(iItem) != m_umapClrColumn.end()) clrText = m_umapClrColumn[iItem].clrText; else clrText = m_clrText; if (bIsHighlighted) clrBk = bIsPressed ? m_clrHglActive : m_clrHglInactive; else { if (m_umapClrColumn.find(iItem) != m_umapClrColumn.end()) clrBk = m_umapClrColumn[iItem].clrBk; else clrBk = m_clrBk; } rDC.FillSolidRect(&rect, clrBk); rDC.SetTextColor(clrText); rDC.SelectObject(m_fontHdr); //Set item's text buffer first char to zero, //then getting item's text and Draw it. static WCHAR warrHdrText[MAX_PATH] { }; warrHdrText[0] = L'\0'; static HDITEMW hdItem { HDI_FORMAT | HDI_TEXT }; hdItem.cchTextMax = MAX_PATH; hdItem.pszText = warrHdrText; GetItem(iItem, &hdItem); UINT uFormat { }; switch (hdItem.fmt) { case (HDF_STRING | HDF_LEFT): uFormat = DT_LEFT; break; case (HDF_STRING | HDF_CENTER): uFormat = DT_CENTER; break; case (HDF_STRING | HDF_RIGHT): uFormat = DT_RIGHT; break; } constexpr long lOffset = 4; rect.left += lOffset; rect.right -= lOffset; if (StrStrW(warrHdrText, L"\n")) { //If it's multiline text, first — calculate rect for the text, //with DT_CALCRECT flag (not drawing anything), //and then calculate rect for final vertical text alignment. CRect rcText; rDC.DrawTextW(warrHdrText, &rcText, DT_CENTER | DT_CALCRECT); rect.top = rect.Height() / 2 - rcText.Height() / 2; rDC.DrawTextW(warrHdrText, &rect, uFormat); } else rDC.DrawTextW(warrHdrText, &rect, uFormat | DT_VCENTER | DT_SINGLELINE); rect.left -= lOffset; rect.right += lOffset; //Draw sortable triangle (arrow). if (m_fSortable && iItem == m_iSortColumn) { rDC.SelectObject(m_penLight); const auto iOffset = rect.Height() / 4; if (m_fSortAscending) { //Draw the UP arrow. rDC.MoveTo(rect.right - 2 * iOffset, iOffset); rDC.LineTo(rect.right - iOffset, rect.bottom - iOffset - 1); rDC.LineTo(rect.right - 3 * iOffset - 2, rect.bottom - iOffset - 1); rDC.SelectObject(m_penShadow); rDC.MoveTo(rect.right - 3 * iOffset - 1, rect.bottom - iOffset - 1); rDC.LineTo(rect.right - 2 * iOffset, iOffset - 1); } else { //Draw the DOWN arrow. rDC.MoveTo(rect.right - iOffset - 1, iOffset); rDC.LineTo(rect.right - 2 * iOffset - 1, rect.bottom - iOffset); rDC.SelectObject(m_penShadow); rDC.MoveTo(rect.right - 2 * iOffset - 2, rect.bottom - iOffset); rDC.LineTo(rect.right - 3 * iOffset - 1, iOffset); rDC.LineTo(rect.right - iOffset - 1, iOffset); } } //rDC.DrawEdge(&rect, EDGE_RAISED, BF_RECT); //3D look edges. rDC.SelectObject(m_penGrid); rDC.MoveTo(rect.TopLeft()); rDC.LineTo(rect.left, rect.bottom); if (iItem == GetItemCount() - 1) //Last item. { rDC.MoveTo(rect.right, rect.top); rDC.LineTo(rect.BottomRight()); } } LRESULT CListExHdr::OnLayout(WPARAM /*wParam*/, LPARAM lParam) { CMFCHeaderCtrl::DefWindowProcW(HDM_LAYOUT, 0, lParam); auto pHDL = reinterpret_cast<LPHDLAYOUT>(lParam); pHDL->pwpos->cy = m_dwHeaderHeight; //New header height. pHDL->prc->top = m_dwHeaderHeight; //Decreasing list's height begining by the new header's height. return 0; } void CListExHdr::SetHeight(DWORD dwHeight) { m_dwHeaderHeight = dwHeight; } void CListExHdr::SetColor(const LISTEXCOLORS& lcs) { m_clrText = lcs.clrHdrText; m_clrBk = lcs.clrHdrBk; m_clrBkNWA = lcs.clrNWABk; m_clrHglInactive = lcs.clrHdrHglInact; m_clrHglActive = lcs.clrHdrHglAct; RedrawWindow(); } void CListExHdr::SetColumnColor(int iColumn, COLORREF clrBk, COLORREF clrText) { if (clrText == -1) clrText = m_clrText; m_umapClrColumn[iColumn] = SHDRCOLOR { clrBk, clrText }; RedrawWindow(); } void CListExHdr::SetSortable(bool fSortable) { m_fSortable = fSortable; RedrawWindow(); } void CListExHdr::SetSortArrow(int iColumn, bool fAscending) { m_iSortColumn = iColumn; m_fSortAscending = fAscending; RedrawWindow(); } void CListExHdr::SetFont(const LOGFONTW* pLogFontNew) { if (!pLogFontNew) return; m_fontHdr.DeleteObject(); m_fontHdr.CreateFontIndirectW(pLogFontNew); //If new font's height is higher than current height (m_dwHeaderHeight) //we adjust current height as well. TEXTMETRICW tm; CDC* pDC = GetDC(); pDC->SelectObject(m_fontHdr); pDC->GetTextMetricsW(&tm); ReleaseDC(pDC); DWORD dwHeightFont = tm.tmHeight + tm.tmExternalLeading + 1; if (dwHeightFont > m_dwHeaderHeight) SetHeight(dwHeightFont); } void CListExHdr::OnDestroy() { CMFCHeaderCtrl::OnDestroy(); m_umapClrColumn.clear(); }
29.683258
101
0.649695
[ "3d" ]
0bbb392033c509ead0aef61448999105fd2ae876
2,133
cpp
C++
Extensions/ResourceIO/src/XMLMapObjectSerializer.cpp
bkmsstudio/minecraftserver
fd42ab6e4cc986d32b31f3a13d6200778570bf51
[ "MIT" ]
null
null
null
Extensions/ResourceIO/src/XMLMapObjectSerializer.cpp
bkmsstudio/minecraftserver
fd42ab6e4cc986d32b31f3a13d6200778570bf51
[ "MIT" ]
null
null
null
Extensions/ResourceIO/src/XMLMapObjectSerializer.cpp
bkmsstudio/minecraftserver
fd42ab6e4cc986d32b31f3a13d6200778570bf51
[ "MIT" ]
null
null
null
#include SAMPEDGENGINE_EXT_RESOURCEIO_PCH #include <SAMP-EDGEngine/Ext/ResourceIO/XMLMapObjectSerializer.hpp> #include <SAMP-EDGEngine/Ext/ResourceIO/XMLHelperFunctions.hpp> #include <SAMP-EDGEngine/Ext/ResourceIO/XMLNames.hpp> #include <SAMP-EDGEngine/Ext/ResourceIO/XMLMapObjectMaterialSerializer.hpp> #include <SAMP-EDGEngine/Ext/ResourceIO/XMLTextureMaterialSerializer.hpp> #include <SAMP-EDGEngine/Ext/ResourceIO/XMLTextMaterialSerializer.hpp> #include <SAMP-EDGEngine/Ext/ResourceIO/Logging.hpp> #include <iostream> namespace samp_edgengine::ext::resource_io { //////////////////////////////////////////////////////////////////////////////////////////////// void XMLMapObjectSerializer::serializeMaterials(xml::xml_node<>& node_) const { auto const& materials = object.getMaterials(); for (std::size_t i = 0; i < materials.size(); i++) { // # Assertion note: // There is code inconsistency which allows settings a material with index >= MaxMaterialCount. Fix your code. assert(i < IMapObject::MaxMaterialCount); if (materials[i]) { if (const_a textMat = dynamic_cast<IMapObject::Text*>(materials[i].get())) { XMLTextMaterialSerializer serializer{ *materials[i], static_cast<Uint8>( i ), node_ }; if (!serializer.serialize()) { std::clog << ModuleLogPrefix << "(Warning): Failed to serialize text material #" << i << "." << std::endl; } } else if (const_a textureMat = dynamic_cast<IMapObject::Texture*>(materials[i].get())) { XMLTextureMaterialSerializer serializer{ *materials[i], static_cast<Uint8>( i ), node_ }; if (!serializer.serialize()) { std::clog << ModuleLogPrefix << "(Warning): Failed to serialize texture material #" << i << "." << std::endl; } } } } } //////////////////////////////////////////////////////////////////////////////////////////////// std::string_view XMLMapObjectSerializer::stringifyType(IMapObject::Type type_) { switch (type_) { case IMapObject::Global: return "Global"; case IMapObject::Personal: return "Personal"; case IMapObject::Universal: return "Universal"; default: return "Unknown"; } } }
33.328125
114
0.654477
[ "object" ]
0bc0d9fd4ca2185b12d20dfb01347406f247b4b3
1,974
hpp
C++
src/MotionConstraint.hpp
rock-control/trajectory_generation
efaaeca345613ff13047056fb54791c81258fb96
[ "BSD-3-Clause" ]
null
null
null
src/MotionConstraint.hpp
rock-control/trajectory_generation
efaaeca345613ff13047056fb54791c81258fb96
[ "BSD-3-Clause" ]
null
null
null
src/MotionConstraint.hpp
rock-control/trajectory_generation
efaaeca345613ff13047056fb54791c81258fb96
[ "BSD-3-Clause" ]
null
null
null
#ifndef MOTION_CONSTRAINT_HPP #define MOTION_CONSTRAINT_HPP #include <base/NamedVector.hpp> #include <base/Float.hpp> namespace joint_control_base { /** Motion constraints to define the dynamic behavior of the trajectories generated by this component*/ struct MotionConstraint{ struct upperLimit{ double position; /** Maximum joint or Cartesian position. In rad or m. (only reflexxes TypeIV, has to be > min. position!) */ double speed; /** Maximum joint or Cartesian velocity. In rad/s or m/s. (has to be > 0) */ double acceleration; /** Maximum joint or Cartesian acceleration. In rad/ss or m/ss. (has to be > 0) */ }; struct lowerLimit{ double position; /** Minimum joint or Cartesian position. In rad or m. (only reflexxes TypeIV, has to be < max. position!) */ }; double max_jerk; /** Maximum joint or Cartesian jerk (derivative of acceleration). In rad/sss or m/sss. (has to be > 0) */ upperLimit max; lowerLimit min; MotionConstraint(); bool hasMaxPosition() const {return !base::isUnset(max.position);} bool hasMinPosition() const {return !base::isUnset(min.position);} bool hasMaxVelocity() const {return !base::isUnset(max.speed);} bool hasMaxAcceleration() const {return !base::isUnset(max.acceleration);} bool hasMaxJerk() const {return !base::isUnset(max_jerk);} void validatePositionLimits() const; void validateVelocityLimit() const; void validateAccelerationLimit() const; void validateJerkLimit() const; void applyDefaultIfUnset(const MotionConstraint& default_constraints); }; /** For backward compatibility */ typedef MotionConstraint JointMotionConstraints; /** Named vector of MotionConstraints, i.e. motion constraints for all the joints of a robot*/ struct MotionConstraints : base::NamedVector<MotionConstraint>{ }; /** For backward compatibility */ typedef MotionConstraints JointsMotionConstraints; } #endif
37.245283
137
0.715805
[ "vector" ]
0bc27220e8073c12d7f9708a5e40bc4ebc9a58da
18,274
cpp
C++
Sources/Overload/OvCore/src/OvCore/Helpers/GUIDrawer.cpp
kmqwerty/Overload
f3b8c751a05815400ed35dd2be20a3900f3454fd
[ "MIT" ]
null
null
null
Sources/Overload/OvCore/src/OvCore/Helpers/GUIDrawer.cpp
kmqwerty/Overload
f3b8c751a05815400ed35dd2be20a3900f3454fd
[ "MIT" ]
null
null
null
Sources/Overload/OvCore/src/OvCore/Helpers/GUIDrawer.cpp
kmqwerty/Overload
f3b8c751a05815400ed35dd2be20a3900f3454fd
[ "MIT" ]
null
null
null
/** * @project: Overload * @author: Overload Tech. * @licence: MIT */ #include <array> #include <OvTools/Utils/PathParser.h> #include <OvUI/Widgets/Texts/TextColored.h> #include <OvUI/Widgets/Drags/DragSingleScalar.h> #include <OvUI/Widgets/Drags/DragMultipleScalars.h> #include <OvUI/Widgets/InputFields/InputText.h> #include <OvUI/Widgets/Selection/ColorEdit.h> #include <OvUI/Widgets/Layout/Group.h> #include <OvUI/Widgets/Layout/Columns.h> #include <OvUI/Widgets/Selection/CheckBox.h> #include <OvUI/Widgets/Buttons/Button.h> #include <OvUI/Widgets/Buttons/ButtonSmall.h> #include <OvUI/Plugins/DDTarget.h> #include <OvCore/Global/ServiceLocator.h> #include <OvCore/ResourceManagement/ModelManager.h> #include <OvCore/ResourceManagement/TextureManager.h> #include <OvCore/ResourceManagement/ShaderManager.h> #include <OvCore/ResourceManagement/MaterialManager.h> #include <OvCore/ResourceManagement/SoundManager.h> #include "OvCore/Helpers/GUIDrawer.h" const OvUI::Types::Color OvCore::Helpers::GUIDrawer::TitleColor = { 0.85f, 0.65f, 0.0f }; const OvUI::Types::Color OvCore::Helpers::GUIDrawer::ClearButtonColor = { 0.5f, 0.0f, 0.0f }; const float OvCore::Helpers::GUIDrawer::_MIN_FLOAT = -999999999.f; const float OvCore::Helpers::GUIDrawer::_MAX_FLOAT = +999999999.f; OvRendering::Resources::Texture* OvCore::Helpers::GUIDrawer::__EMPTY_TEXTURE = nullptr; void OvCore::Helpers::GUIDrawer::ProvideEmptyTexture(OvRendering::Resources::Texture& p_emptyTexture) { __EMPTY_TEXTURE = &p_emptyTexture; } void OvCore::Helpers::GUIDrawer::CreateTitle(OvUI::Internal::WidgetContainer& p_root, const std::string & p_name) { p_root.CreateWidget<OvUI::Widgets::Texts::TextColored>(p_name, TitleColor); } void OvCore::Helpers::GUIDrawer::DrawBoolean(OvUI::Internal::WidgetContainer & p_root, const std::string & p_name, bool & p_data) { CreateTitle(p_root, p_name); auto& widget = p_root.CreateWidget<OvUI::Widgets::Selection::CheckBox>(); auto& dispatcher = widget.AddPlugin<OvUI::Plugins::DataDispatcher<bool>>(); dispatcher.RegisterReference(reinterpret_cast<bool&>(p_data)); } void OvCore::Helpers::GUIDrawer::DrawVec2(OvUI::Internal::WidgetContainer & p_root, const std::string & p_name, OvMaths::FVector2 & p_data, float p_step, float p_min, float p_max) { CreateTitle(p_root, p_name); auto& widget = p_root.CreateWidget<OvUI::Widgets::Drags::DragMultipleScalars<float, 2>>(GetDataType<float>(), p_min, p_max, 0.f, p_step, "", GetFormat<float>()); auto& dispatcher = widget.AddPlugin<OvUI::Plugins::DataDispatcher<std::array<float, 2>>>(); dispatcher.RegisterReference(reinterpret_cast<std::array<float, 2>&>(p_data)); } void OvCore::Helpers::GUIDrawer::DrawVec3(OvUI::Internal::WidgetContainer & p_root, const std::string & p_name, OvMaths::FVector3 & p_data, float p_step, float p_min, float p_max) { CreateTitle(p_root, p_name); auto& widget = p_root.CreateWidget<OvUI::Widgets::Drags::DragMultipleScalars<float, 3>>(GetDataType<float>(), p_min, p_max, 0.f, p_step, "", GetFormat<float>()); auto& dispatcher = widget.AddPlugin<OvUI::Plugins::DataDispatcher<std::array<float, 3>>>(); dispatcher.RegisterReference(reinterpret_cast<std::array<float, 3>&>(p_data)); } void OvCore::Helpers::GUIDrawer::DrawVec4(OvUI::Internal::WidgetContainer & p_root, const std::string & p_name, OvMaths::FVector4& p_data, float p_step, float p_min, float p_max) { CreateTitle(p_root, p_name); auto& widget = p_root.CreateWidget<OvUI::Widgets::Drags::DragMultipleScalars<float, 4>>(GetDataType<float>(), p_min, p_max, 0.f, p_step, "", GetFormat<float>()); auto& dispatcher = widget.AddPlugin<OvUI::Plugins::DataDispatcher<std::array<float, 4>>>(); dispatcher.RegisterReference(reinterpret_cast<std::array<float, 4>&>(p_data)); } void OvCore::Helpers::GUIDrawer::DrawQuat(OvUI::Internal::WidgetContainer & p_root, const std::string & p_name, OvMaths::FQuaternion & p_data, float p_step, float p_min, float p_max) { CreateTitle(p_root, p_name); auto& widget = p_root.CreateWidget<OvUI::Widgets::Drags::DragMultipleScalars<float, 4>>(GetDataType<float>(), p_min, p_max, 0.f, p_step, "", GetFormat<float>()); auto& dispatcher = widget.AddPlugin<OvUI::Plugins::DataDispatcher<std::array<float, 4>>>(); dispatcher.RegisterReference(reinterpret_cast<std::array<float, 4>&>(p_data)); } void OvCore::Helpers::GUIDrawer::DrawString(OvUI::Internal::WidgetContainer & p_root, const std::string & p_name, std::string & p_data) { CreateTitle(p_root, p_name); auto& widget = p_root.CreateWidget<OvUI::Widgets::InputFields::InputText>(""); auto& dispatcher = widget.AddPlugin<OvUI::Plugins::DataDispatcher<std::string>>(); dispatcher.RegisterReference(p_data); } void OvCore::Helpers::GUIDrawer::DrawColor(OvUI::Internal::WidgetContainer & p_root, const std::string & p_name, OvUI::Types::Color & p_color, bool p_hasAlpha) { CreateTitle(p_root, p_name); auto& widget = p_root.CreateWidget<OvUI::Widgets::Selection::ColorEdit>(p_hasAlpha); auto& dispatcher = widget.AddPlugin<OvUI::Plugins::DataDispatcher<OvUI::Types::Color>>(); dispatcher.RegisterReference(p_color); } OvUI::Widgets::Texts::Text& OvCore::Helpers::GUIDrawer::DrawMesh(OvUI::Internal::WidgetContainer & p_root, const std::string & p_name, OvRendering::Resources::Model *& p_data, OvTools::Eventing::Event<>* p_updateNotifier) { CreateTitle(p_root, p_name); std::string displayedText = (p_data ? p_data->path : std::string("Empty")); auto& rightSide = p_root.CreateWidget<OvUI::Widgets::Layout::Group>(); auto& widget = rightSide.CreateWidget<OvUI::Widgets::Texts::Text>(displayedText); widget.AddPlugin<OvUI::Plugins::DDTarget<std::pair<std::string, OvUI::Widgets::Layout::Group*>>>("File").DataReceivedEvent += [&widget, &p_data, p_updateNotifier](auto p_receivedData) { if (OvTools::Utils::PathParser::GetFileType(p_receivedData.first) == OvTools::Utils::PathParser::EFileType::MODEL) { if (auto resource = OVSERVICE(OvCore::ResourceManagement::ModelManager).GetResource(p_receivedData.first); resource) { p_data = resource; widget.content = p_receivedData.first; if (p_updateNotifier) p_updateNotifier->Invoke(); } } }; widget.lineBreak = false; auto& resetButton = rightSide.CreateWidget<OvUI::Widgets::Buttons::ButtonSmall>("Clear"); resetButton.idleBackgroundColor = ClearButtonColor; resetButton.ClickedEvent += [&widget, &p_data, p_updateNotifier] { p_data = nullptr; widget.content = "Empty"; if (p_updateNotifier) p_updateNotifier->Invoke(); }; return widget; } OvUI::Widgets::Visual::Image& OvCore::Helpers::GUIDrawer::DrawTexture(OvUI::Internal::WidgetContainer & p_root, const std::string & p_name, OvRendering::Resources::Texture *& p_data, OvTools::Eventing::Event<>* p_updateNotifier) { CreateTitle(p_root, p_name); std::string displayedText = (p_data ? p_data->path : std::string("Empty")); auto& rightSide = p_root.CreateWidget<OvUI::Widgets::Layout::Group>(); auto& widget = rightSide.CreateWidget<OvUI::Widgets::Visual::Image>(p_data ? p_data->id : (__EMPTY_TEXTURE ? __EMPTY_TEXTURE->id : 0), OvMaths::FVector2{ 75, 75 }); widget.AddPlugin<OvUI::Plugins::DDTarget<std::pair<std::string, OvUI::Widgets::Layout::Group*>>>("File").DataReceivedEvent += [&widget, &p_data, p_updateNotifier](auto p_receivedData) { if (OvTools::Utils::PathParser::GetFileType(p_receivedData.first) == OvTools::Utils::PathParser::EFileType::TEXTURE) { if (auto resource = OVSERVICE(OvCore::ResourceManagement::TextureManager).GetResource(p_receivedData.first); resource) { p_data = resource; widget.textureID.id = resource->id; if (p_updateNotifier) p_updateNotifier->Invoke(); } } }; widget.lineBreak = false; auto& resetButton = rightSide.CreateWidget<OvUI::Widgets::Buttons::Button>("Clear"); resetButton.idleBackgroundColor = ClearButtonColor; resetButton.ClickedEvent += [&widget, &p_data, p_updateNotifier] { p_data = nullptr; widget.textureID.id = (__EMPTY_TEXTURE ? __EMPTY_TEXTURE->id : 0); if (p_updateNotifier) p_updateNotifier->Invoke(); }; return widget; } OvUI::Widgets::Texts::Text& OvCore::Helpers::GUIDrawer::DrawShader(OvUI::Internal::WidgetContainer & p_root, const std::string & p_name, OvRendering::Resources::Shader *& p_data, OvTools::Eventing::Event<>* p_updateNotifier) { CreateTitle(p_root, p_name); std::string displayedText = (p_data ? p_data->path : std::string("Empty")); auto& rightSide = p_root.CreateWidget<OvUI::Widgets::Layout::Group>(); auto& widget = rightSide.CreateWidget<OvUI::Widgets::Texts::Text>(displayedText); widget.AddPlugin<OvUI::Plugins::DDTarget<std::pair<std::string, OvUI::Widgets::Layout::Group*>>>("File").DataReceivedEvent += [&widget, &p_data, p_updateNotifier](auto p_receivedData) { if (OvTools::Utils::PathParser::GetFileType(p_receivedData.first) == OvTools::Utils::PathParser::EFileType::SHADER) { if (auto resource = OVSERVICE(OvCore::ResourceManagement::ShaderManager).GetResource(p_receivedData.first); resource) { p_data = resource; widget.content = p_receivedData.first; if (p_updateNotifier) p_updateNotifier->Invoke(); } } }; widget.lineBreak = false; auto& resetButton = rightSide.CreateWidget<OvUI::Widgets::Buttons::ButtonSmall>("Clear"); resetButton.idleBackgroundColor = ClearButtonColor; resetButton.ClickedEvent += [&widget, &p_data, p_updateNotifier] { p_data = nullptr; widget.content = "Empty"; if (p_updateNotifier) p_updateNotifier->Invoke(); }; return widget; } OvUI::Widgets::Texts::Text& OvCore::Helpers::GUIDrawer::DrawMaterial(OvUI::Internal::WidgetContainer & p_root, const std::string & p_name, OvCore::Resources::Material *& p_data, OvTools::Eventing::Event<>* p_updateNotifier) { CreateTitle(p_root, p_name); std::string displayedText = (p_data ? p_data->path : std::string("Empty")); auto& rightSide = p_root.CreateWidget<OvUI::Widgets::Layout::Group>(); auto& widget = rightSide.CreateWidget<OvUI::Widgets::Texts::Text>(displayedText); widget.AddPlugin<OvUI::Plugins::DDTarget<std::pair<std::string, OvUI::Widgets::Layout::Group*>>>("File").DataReceivedEvent += [&widget, &p_data, p_updateNotifier](auto p_receivedData) { if (OvTools::Utils::PathParser::GetFileType(p_receivedData.first) == OvTools::Utils::PathParser::EFileType::MATERIAL) { if (auto resource = OVSERVICE(OvCore::ResourceManagement::MaterialManager).GetResource(p_receivedData.first); resource) { p_data = resource; widget.content = p_receivedData.first; if (p_updateNotifier) p_updateNotifier->Invoke(); } } }; widget.lineBreak = false; auto& resetButton = rightSide.CreateWidget<OvUI::Widgets::Buttons::ButtonSmall>("Clear"); resetButton.idleBackgroundColor = ClearButtonColor; resetButton.ClickedEvent += [&widget, &p_data, p_updateNotifier] { p_data = nullptr; widget.content = "Empty"; if (p_updateNotifier) p_updateNotifier->Invoke(); }; return widget; } OvUI::Widgets::Texts::Text& OvCore::Helpers::GUIDrawer::DrawSound(OvUI::Internal::WidgetContainer& p_root, const std::string& p_name, OvAudio::Resources::Sound*& p_data, OvTools::Eventing::Event<>* p_updateNotifier) { CreateTitle(p_root, p_name); std::string displayedText = (p_data ? p_data->path : std::string("Empty")); auto & rightSide = p_root.CreateWidget<OvUI::Widgets::Layout::Group>(); auto & widget = rightSide.CreateWidget<OvUI::Widgets::Texts::Text>(displayedText); widget.AddPlugin<OvUI::Plugins::DDTarget<std::pair<std::string, OvUI::Widgets::Layout::Group*>>>("File").DataReceivedEvent += [&widget, &p_data, p_updateNotifier](auto p_receivedData) { if (OvTools::Utils::PathParser::GetFileType(p_receivedData.first) == OvTools::Utils::PathParser::EFileType::SOUND) { if (auto resource = OVSERVICE(OvCore::ResourceManagement::SoundManager).GetResource(p_receivedData.first); resource) { p_data = resource; widget.content = p_receivedData.first; if (p_updateNotifier) p_updateNotifier->Invoke(); } } }; widget.lineBreak = false; auto & resetButton = rightSide.CreateWidget<OvUI::Widgets::Buttons::ButtonSmall>("Clear"); resetButton.idleBackgroundColor = ClearButtonColor; resetButton.ClickedEvent += [&widget, &p_data, p_updateNotifier] { p_data = nullptr; widget.content = "Empty"; if (p_updateNotifier) p_updateNotifier->Invoke(); }; return widget; } void OvCore::Helpers::GUIDrawer::DrawBoolean(OvUI::Internal::WidgetContainer & p_root, const std::string & p_name, std::function<bool(void)> p_gatherer, std::function<void(bool)> p_provider) { CreateTitle(p_root, p_name); auto& widget = p_root.CreateWidget<OvUI::Widgets::Selection::CheckBox>(); auto& dispatcher = widget.AddPlugin<OvUI::Plugins::DataDispatcher<bool>>(); dispatcher.RegisterGatherer([p_gatherer]() { bool value = p_gatherer(); return reinterpret_cast<bool&>(value); }); dispatcher.RegisterProvider([p_provider](bool p_value) { p_provider(reinterpret_cast<bool&>(p_value)); }); } void OvCore::Helpers::GUIDrawer::DrawVec2(OvUI::Internal::WidgetContainer & p_root, const std::string & p_name, std::function<OvMaths::FVector2(void)> p_gatherer, std::function<void(OvMaths::FVector2)> p_provider, float p_step, float p_min, float p_max) { CreateTitle(p_root, p_name); auto& widget = p_root.CreateWidget<OvUI::Widgets::Drags::DragMultipleScalars<float, 2>>(GetDataType<float>(), p_min, p_max, 0.f, p_step, "", GetFormat<float>()); auto& dispatcher = widget.AddPlugin<OvUI::Plugins::DataDispatcher<std::array<float, 2>>>(); dispatcher.RegisterGatherer([p_gatherer]() { OvMaths::FVector2 value = p_gatherer(); return reinterpret_cast<const std::array<float, 2>&>(value); }); dispatcher.RegisterProvider([p_provider](std::array<float, 2> p_value) { p_provider(reinterpret_cast<OvMaths::FVector2&>(p_value)); }); } void OvCore::Helpers::GUIDrawer::DrawVec3(OvUI::Internal::WidgetContainer & p_root, const std::string & p_name, std::function<OvMaths::FVector3(void)> p_gatherer, std::function<void(OvMaths::FVector3)> p_provider, float p_step, float p_min, float p_max) { CreateTitle(p_root, p_name); auto& widget = p_root.CreateWidget<OvUI::Widgets::Drags::DragMultipleScalars<float, 3>>(GetDataType<float>(), p_min, p_max, 0.f, p_step, "", GetFormat<float>()); auto& dispatcher = widget.AddPlugin<OvUI::Plugins::DataDispatcher<std::array<float, 3>>>(); dispatcher.RegisterGatherer([p_gatherer]() { OvMaths::FVector3 value = p_gatherer(); return reinterpret_cast<const std::array<float, 3>&>(value); }); dispatcher.RegisterProvider([p_provider](std::array<float, 3> p_value) { p_provider(reinterpret_cast<OvMaths::FVector3&>(p_value)); }); } void OvCore::Helpers::GUIDrawer::DrawVec4(OvUI::Internal::WidgetContainer & p_root, const std::string & p_name, std::function<OvMaths::FVector4(void)> p_gatherer, std::function<void(OvMaths::FVector4)> p_provider, float p_step, float p_min, float p_max) { CreateTitle(p_root, p_name); auto& widget = p_root.CreateWidget<OvUI::Widgets::Drags::DragMultipleScalars<float, 4>>(GetDataType<float>(), p_min, p_max, 0.f, p_step, "", GetFormat<float>()); auto& dispatcher = widget.AddPlugin<OvUI::Plugins::DataDispatcher<std::array<float, 4>>>(); dispatcher.RegisterGatherer([p_gatherer]() { OvMaths::FVector4 value = p_gatherer(); return reinterpret_cast<const std::array<float, 4>&>(value); }); dispatcher.RegisterProvider([p_provider](std::array<float, 4> p_value) { p_provider(reinterpret_cast<OvMaths::FVector4&>(p_value)); }); } void OvCore::Helpers::GUIDrawer::DrawQuat(OvUI::Internal::WidgetContainer & p_root, const std::string & p_name, std::function<OvMaths::FQuaternion(void)> p_gatherer, std::function<void(OvMaths::FQuaternion)> p_provider, float p_step, float p_min, float p_max) { CreateTitle(p_root, p_name); auto& widget = p_root.CreateWidget<OvUI::Widgets::Drags::DragMultipleScalars<float, 4>>(GetDataType<float>(), p_min, p_max, 0.f, p_step, "", GetFormat<float>()); auto& dispatcher = widget.AddPlugin<OvUI::Plugins::DataDispatcher<std::array<float, 4>>>(); dispatcher.RegisterGatherer([p_gatherer]() { OvMaths::FQuaternion value = p_gatherer(); return reinterpret_cast<const std::array<float, 4>&>(value); }); dispatcher.RegisterProvider([&dispatcher, p_provider](std::array<float, 4> p_value) { p_provider(OvMaths::FQuaternion::Normalize(reinterpret_cast<OvMaths::FQuaternion&>(p_value))); }); } void OvCore::Helpers::GUIDrawer::DrawDDString(OvUI::Internal::WidgetContainer& p_root, const std::string& p_name, std::function<std::string()> p_gatherer, std::function<void(std::string)> p_provider, const std::string& p_identifier) { CreateTitle(p_root, p_name); auto& widget = p_root.CreateWidget<OvUI::Widgets::InputFields::InputText>(""); auto& dispatcher = widget.AddPlugin<OvUI::Plugins::DataDispatcher<std::string>>(); dispatcher.RegisterGatherer(p_gatherer); dispatcher.RegisterProvider(p_provider); auto& ddTarget = widget.AddPlugin<OvUI::Plugins::DDTarget<std::pair<std::string, OvUI::Widgets::Layout::Group*>>>(p_identifier); ddTarget.DataReceivedEvent += [&widget, &dispatcher](std::pair<std::string, OvUI::Widgets::Layout::Group*> p_data) { widget.content = p_data.first; dispatcher.NotifyChange(); }; } void OvCore::Helpers::GUIDrawer::DrawString(OvUI::Internal::WidgetContainer & p_root, const std::string & p_name, std::function<std::string(void)> p_gatherer, std::function<void(std::string)> p_provider) { CreateTitle(p_root, p_name); auto& widget = p_root.CreateWidget<OvUI::Widgets::InputFields::InputText>(""); auto& dispatcher = widget.AddPlugin<OvUI::Plugins::DataDispatcher<std::string>>(); dispatcher.RegisterGatherer(p_gatherer); dispatcher.RegisterProvider(p_provider); } void OvCore::Helpers::GUIDrawer::DrawColor(OvUI::Internal::WidgetContainer & p_root, const std::string & p_name, std::function<OvUI::Types::Color(void)> p_gatherer, std::function<void(OvUI::Types::Color)> p_provider, bool p_hasAlpha) { CreateTitle(p_root, p_name); auto& widget = p_root.CreateWidget<OvUI::Widgets::Selection::ColorEdit>(p_hasAlpha); auto& dispatcher = widget.AddPlugin<OvUI::Plugins::DataDispatcher<OvUI::Types::Color>>(); dispatcher.RegisterGatherer(p_gatherer); dispatcher.RegisterProvider(p_provider); }
43.613365
259
0.743406
[ "model" ]
0bc3ce8644b4cd3a446f426032722305af459bdc
1,547
cc
C++
src/aho-corasick/t.cc
thinkoid/hacks
7c5887860bf9177e487e2f2f041629ddbd3c38fb
[ "MIT" ]
null
null
null
src/aho-corasick/t.cc
thinkoid/hacks
7c5887860bf9177e487e2f2f041629ddbd3c38fb
[ "MIT" ]
null
null
null
src/aho-corasick/t.cc
thinkoid/hacks
7c5887860bf9177e487e2f2f041629ddbd3c38fb
[ "MIT" ]
null
null
null
#include <cassert> #include <cstring> #include <algorithm> #include <iomanip> #include <iostream> #include <map> #include <memory> #include <string> #include <vector> using namespace std; #include <hacks/aho-corasick.hh> #if 0 int main (int, char** argv) { const vector< string > arr { "he", "she", "his", "hers" }; const string text = "uSHers"; using alphabet_type = english_icase_alphabet_t< char >; aho_corasick_t< alphabet_type > a (arr.begin (), arr.end ()); const auto v = a (text.begin (), text.end ()); for (const auto& p : v) cout << p.first << ":" << p.second << " "; cout << endl; return 0; } #else int main () { size_t n; cin >> n; vector< string > g; g.reserve (n); copy_n (istream_iterator< string > (cin), n, back_inserter (g)); vector< int > h; h.reserve (n); copy_n (istream_iterator< size_t > (cin), n, back_inserter (h)); aho_corasick_t< english_lowercase_alphabet_t< char > > aho_corasick ( g.begin (), g.end ()); string text; size_t j, k; cin >> n; size_t min_ = size_t (-1), max_ = 0; for (string text; cin >> j >> k >> text;) { size_t value = 0; aho_corasick (text.begin (), text.end (), [&](auto i, auto) { if (j <= i && i <= k) value += h [i]; }); if (value > max_) max_ = value; if (value < min_) min_ = value; } cout << min_ << " " << max_ << endl; return 0; } #endif // 0
18.865854
73
0.529412
[ "vector" ]
0bd1a7455fa66b0015e02722a0e39404e8426aa0
1,557
cpp
C++
cpp/godot-cpp/src/gen/ResourceFormatSaver.cpp
GDNative-Gradle/proof-of-concept
162f467430760cf959f68f1638adc663fd05c5fd
[ "MIT" ]
1
2021-03-16T09:51:00.000Z
2021-03-16T09:51:00.000Z
cpp/godot-cpp/src/gen/ResourceFormatSaver.cpp
GDNative-Gradle/proof-of-concept
162f467430760cf959f68f1638adc663fd05c5fd
[ "MIT" ]
null
null
null
cpp/godot-cpp/src/gen/ResourceFormatSaver.cpp
GDNative-Gradle/proof-of-concept
162f467430760cf959f68f1638adc663fd05c5fd
[ "MIT" ]
null
null
null
#include "ResourceFormatSaver.hpp" #include <core/GodotGlobal.hpp> #include <core/CoreTypes.hpp> #include <core/Ref.hpp> #include <core/Godot.hpp> #include "__icalls.hpp" #include "Resource.hpp" namespace godot { ResourceFormatSaver::___method_bindings ResourceFormatSaver::___mb = {}; void ResourceFormatSaver::___init_method_bindings() { ___mb.mb_get_recognized_extensions = godot::api->godot_method_bind_get_method("ResourceFormatSaver", "get_recognized_extensions"); ___mb.mb_recognize = godot::api->godot_method_bind_get_method("ResourceFormatSaver", "recognize"); ___mb.mb_save = godot::api->godot_method_bind_get_method("ResourceFormatSaver", "save"); } ResourceFormatSaver *ResourceFormatSaver::_new() { return (ResourceFormatSaver *) godot::nativescript_1_1_api->godot_nativescript_get_instance_binding_data(godot::_RegisterState::language_index, godot::api->godot_get_class_constructor((char *)"ResourceFormatSaver")()); } PoolStringArray ResourceFormatSaver::get_recognized_extensions(const Ref<Resource> resource) { return ___godot_icall_PoolStringArray_Object(___mb.mb_get_recognized_extensions, (const Object *) this, resource.ptr()); } bool ResourceFormatSaver::recognize(const Ref<Resource> resource) { return ___godot_icall_bool_Object(___mb.mb_recognize, (const Object *) this, resource.ptr()); } int64_t ResourceFormatSaver::save(const String path, const Ref<Resource> resource, const int64_t flags) { return ___godot_icall_int_String_Object_int(___mb.mb_save, (const Object *) this, path, resource.ptr(), flags); } }
37.071429
219
0.804753
[ "object" ]
0bd5e99b481b7db2159faced4381dc61e5399d5f
2,830
cc
C++
oos/src/model/SetServiceSettingsRequest.cc
aliyun/aliyun-openapi-cpp-sdk
0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36
[ "Apache-2.0" ]
89
2018-02-02T03:54:39.000Z
2021-12-13T01:32:55.000Z
oos/src/model/SetServiceSettingsRequest.cc
aliyun/aliyun-openapi-cpp-sdk
0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36
[ "Apache-2.0" ]
89
2018-03-14T07:44:54.000Z
2021-11-26T07:43:25.000Z
oos/src/model/SetServiceSettingsRequest.cc
aliyun/aliyun-openapi-cpp-sdk
0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36
[ "Apache-2.0" ]
69
2018-01-22T09:45:52.000Z
2022-03-28T07:58:38.000Z
/* * Copyright 2009-2017 Alibaba Cloud All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <alibabacloud/oos/model/SetServiceSettingsRequest.h> using AlibabaCloud::Oos::Model::SetServiceSettingsRequest; SetServiceSettingsRequest::SetServiceSettingsRequest() : RpcServiceRequest("oos", "2019-06-01", "SetServiceSettings") { setMethod(HttpRequest::Method::Post); } SetServiceSettingsRequest::~SetServiceSettingsRequest() {} bool SetServiceSettingsRequest::getDeliverySlsEnabled()const { return deliverySlsEnabled_; } void SetServiceSettingsRequest::setDeliverySlsEnabled(bool deliverySlsEnabled) { deliverySlsEnabled_ = deliverySlsEnabled; setParameter("DeliverySlsEnabled", deliverySlsEnabled ? "true" : "false"); } std::string SetServiceSettingsRequest::getDeliveryOssKeyPrefix()const { return deliveryOssKeyPrefix_; } void SetServiceSettingsRequest::setDeliveryOssKeyPrefix(const std::string& deliveryOssKeyPrefix) { deliveryOssKeyPrefix_ = deliveryOssKeyPrefix; setParameter("DeliveryOssKeyPrefix", deliveryOssKeyPrefix); } bool SetServiceSettingsRequest::getDeliveryOssEnabled()const { return deliveryOssEnabled_; } void SetServiceSettingsRequest::setDeliveryOssEnabled(bool deliveryOssEnabled) { deliveryOssEnabled_ = deliveryOssEnabled; setParameter("DeliveryOssEnabled", deliveryOssEnabled ? "true" : "false"); } std::string SetServiceSettingsRequest::getRegionId()const { return regionId_; } void SetServiceSettingsRequest::setRegionId(const std::string& regionId) { regionId_ = regionId; setParameter("RegionId", regionId); } std::string SetServiceSettingsRequest::getDeliverySlsProjectName()const { return deliverySlsProjectName_; } void SetServiceSettingsRequest::setDeliverySlsProjectName(const std::string& deliverySlsProjectName) { deliverySlsProjectName_ = deliverySlsProjectName; setParameter("DeliverySlsProjectName", deliverySlsProjectName); } std::string SetServiceSettingsRequest::getDeliveryOssBucketName()const { return deliveryOssBucketName_; } void SetServiceSettingsRequest::setDeliveryOssBucketName(const std::string& deliveryOssBucketName) { deliveryOssBucketName_ = deliveryOssBucketName; setParameter("DeliveryOssBucketName", deliveryOssBucketName); }
29.479167
101
0.789046
[ "model" ]
0bec61496eb528d1c29b3c146b53f149e622229e
2,880
cc
C++
src/agent/array_expression_evaluator.cc
goelnitin0887/Testing-Production-debug
5c3cb42b827fdf16de68b3b086b3ad89f9bea314
[ "Apache-2.0" ]
null
null
null
src/agent/array_expression_evaluator.cc
goelnitin0887/Testing-Production-debug
5c3cb42b827fdf16de68b3b086b3ad89f9bea314
[ "Apache-2.0" ]
null
null
null
src/agent/array_expression_evaluator.cc
goelnitin0887/Testing-Production-debug
5c3cb42b827fdf16de68b3b086b3ad89f9bea314
[ "Apache-2.0" ]
null
null
null
/** * Copyright 2015 Google Inc. 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 "array_expression_evaluator.h" #include "jni_utils.h" #include "array_reader.h" #include "model.h" #include "messages.h" #include "numeric_cast_evaluator.h" #include "readers_factory.h" #include "type_util.h" namespace devtools { namespace cdbg { ArrayExpressionEvaluator::ArrayExpressionEvaluator( std::unique_ptr<ExpressionEvaluator> source_array, std::unique_ptr<ExpressionEvaluator> source_index) : source_array_(std::move(source_array)), source_index_(std::move(source_index)) { } ArrayExpressionEvaluator::~ArrayExpressionEvaluator() { } bool ArrayExpressionEvaluator::Compile( ReadersFactory* readers_factory, FormatMessageModel* error_message) { if (!source_array_->Compile(readers_factory, error_message) || !source_index_->Compile(readers_factory, error_message)) { return false; } if (!IsArrayObjectType(source_array_->GetStaticType())) { *error_message = { ArrayTypeExpected, { TypeNameFromSignature(source_array_->GetStaticType()) } }; return false; } return_type_ = GetArrayElementJSignature(source_array_->GetStaticType()); if (return_type_.type == JType::Void) { *error_message = INTERNAL_ERROR_MESSAGE; return false; } array_reader_ = readers_factory->CreateArrayReader( source_array_->GetStaticType()); if (array_reader_ == nullptr) { *error_message = INTERNAL_ERROR_MESSAGE; return false; } if (!IsIntegerType(source_index_->GetStaticType().type)) { *error_message = { ArrayIndexNotInteger, { TypeNameFromSignature(source_index_->GetStaticType()) } }; return false; } if (!ApplyNumericCast<jlong>(&source_index_, error_message)) { *error_message = INTERNAL_ERROR_MESSAGE; return false; } return true; } ErrorOr<JVariant> ArrayExpressionEvaluator::Evaluate( const EvaluationContext& evaluation_context) const { ErrorOr<JVariant> array = source_array_->Evaluate(evaluation_context); if (array.is_error()) { return array; } ErrorOr<JVariant> index = source_index_->Evaluate(evaluation_context); if (index.is_error()) { return index; } return array_reader_->ReadValue(array.value(), index.value()); } } // namespace cdbg } // namespace devtools
26.915888
75
0.727778
[ "model" ]
0becc035f6ddd0485ab3de9339347a55661a81b3
1,079
cc
C++
countingBound/cliqueCounter/SubsetIterator.cc
joshtburdick/misc
7bb103b4f9d850e3279eb675c6df420aa7b8da22
[ "MIT" ]
null
null
null
countingBound/cliqueCounter/SubsetIterator.cc
joshtburdick/misc
7bb103b4f9d850e3279eb675c6df420aa7b8da22
[ "MIT" ]
null
null
null
countingBound/cliqueCounter/SubsetIterator.cc
joshtburdick/misc
7bb103b4f9d850e3279eb675c6df420aa7b8da22
[ "MIT" ]
null
null
null
#include "SubsetIterator.h" #include <vector> using namespace std; /** Constructor. n: size of set to iterate over k: number of things to pick */ SubsetIterator::SubsetIterator(int n, int k) { n_ = n; k_ = k; // initialize to the "first" set for(int i=0; i<k_; i++) a_.push_back(i); } /** Gets the current set. */ vector<int> & SubsetIterator::getSet() { return a_; } /** Advances to the next set. Returns: true iff the next set is defined. If not, it returns false (and the value of getSet() is not defined). */ bool SubsetIterator::next() { // remove elements of a_ which are "maxed out" int max = n_ - 1; for(int i = k_-1; i >= 0; --i) { if (a_[i] == max) a_.pop_back(); --max; } // if a_ is empty, everything was "maxed out", and we're done if (a_.empty()) return false; // increment the top element of a_ ++a_.back(); // initialize anything after that while (int(a_.size()) < k_) a_.push_back( a_.back() + 1 ); return true; }
23.456522
65
0.572753
[ "vector" ]
0bf0f4302f385054b729bf3c35f6f473febe6b16
16,949
cpp
C++
OpenTESArena/src/Interface/OptionsPanel.cpp
AnotherFoxGuy/OpenTESArena
38d2fe72b0ef7e0e838e525bf135f7ef4a7858d7
[ "MIT" ]
742
2016-03-09T17:18:55.000Z
2022-03-21T07:23:47.000Z
OpenTESArena/src/Interface/OptionsPanel.cpp
AnotherFoxGuy/OpenTESArena
38d2fe72b0ef7e0e838e525bf135f7ef4a7858d7
[ "MIT" ]
196
2016-06-07T15:19:21.000Z
2021-12-12T16:50:58.000Z
OpenTESArena/src/Interface/OptionsPanel.cpp
AnotherFoxGuy/OpenTESArena
38d2fe72b0ef7e0e838e525bf135f7ef4a7858d7
[ "MIT" ]
85
2016-04-17T13:25:16.000Z
2022-03-25T06:45:15.000Z
#include <algorithm> #include <limits> #include <optional> #include "SDL.h" #include "OptionsPanel.h" #include "OptionsUiController.h" #include "OptionsUiView.h" #include "PauseMenuPanel.h" #include "../Audio/AudioManager.h" #include "../Entities/Player.h" #include "../Game/Game.h" #include "../Game/GameState.h" #include "../Game/Options.h" #include "../Game/PlayerInterface.h" #include "../Input/InputActionName.h" #include "../Media/Color.h" #include "../Media/TextureManager.h" #include "../Rendering/ArenaRenderUtils.h" #include "../Rendering/Renderer.h" #include "../UI/CursorAlignment.h" #include "../UI/CursorData.h" #include "../UI/FontLibrary.h" #include "../UI/TextAlignment.h" #include "../UI/Texture.h" #include "components/debug/Debug.h" #include "components/utilities/String.h" namespace { void TryIncrementOption(OptionsUiModel::Option &option) { const OptionsUiModel::OptionType optionType = option.getType(); if (optionType == OptionsUiModel::OptionType::Bool) { OptionsUiModel::BoolOption &boolOpt = static_cast<OptionsUiModel::BoolOption&>(option); boolOpt.toggle(); } else if (optionType == OptionsUiModel::OptionType::Int) { OptionsUiModel::IntOption &intOpt = static_cast<OptionsUiModel::IntOption&>(option); intOpt.set(intOpt.getNext()); } else if (optionType == OptionsUiModel::OptionType::Double) { OptionsUiModel::DoubleOption &doubleOpt = static_cast<OptionsUiModel::DoubleOption&>(option); doubleOpt.set(doubleOpt.getNext()); } else if (optionType == OptionsUiModel::OptionType::String) { // Do nothing. static_cast<void>(option); } else { throw DebugException("Invalid type \"" + std::to_string(static_cast<int>(optionType)) + "\"."); } } void TryDecrementOption(OptionsUiModel::Option &option) { const OptionsUiModel::OptionType optionType = option.getType(); if (optionType == OptionsUiModel::OptionType::Bool) { OptionsUiModel::BoolOption &boolOpt = static_cast<OptionsUiModel::BoolOption&>(option); boolOpt.toggle(); } else if (optionType == OptionsUiModel::OptionType::Int) { OptionsUiModel::IntOption &intOpt = static_cast<OptionsUiModel::IntOption&>(option); intOpt.set(intOpt.getPrev()); } else if (optionType == OptionsUiModel::OptionType::Double) { OptionsUiModel::DoubleOption &doubleOpt = static_cast<OptionsUiModel::DoubleOption&>(option); doubleOpt.set(doubleOpt.getPrev()); } else if (optionType == OptionsUiModel::OptionType::String) { // Do nothing. static_cast<void>(option); } else { throw DebugException("Invalid type \"" + std::to_string(static_cast<int>(optionType)) + "\"."); } } } OptionsPanel::OptionsPanel(Game &game) : Panel(game) { } bool OptionsPanel::init() { auto &game = this->getGame(); auto &renderer = game.getRenderer(); const auto &fontLibrary = game.getFontLibrary(); const std::string titleText = OptionsUiModel::OptionsTitleText; const TextBox::InitInfo titleTextBoxInitInfo = OptionsUiView::getTitleTextBoxInitInfo(titleText, fontLibrary); if (!this->titleTextBox.init(titleTextBoxInitInfo, titleText, renderer)) { DebugLogError("Couldn't init title text box."); return false; } const std::string backToPauseMenuText = OptionsUiModel::BackToPauseMenuText; const TextBox::InitInfo backToPauseMenuTextBoxInitInfo = OptionsUiView::getBackToPauseMenuTextBoxInitInfo(backToPauseMenuText, fontLibrary); if (!this->backToPauseMenuTextBox.init(backToPauseMenuTextBoxInitInfo, backToPauseMenuText, renderer)) { DebugLogError("Couldn't init back to pause menu text box."); return false; } auto initTabTextBox = [&renderer, &fontLibrary](TextBox &textBox, int tabIndex, const std::string &text) { const Rect &graphicsTabRect = OptionsUiView::GraphicsTabRect; const Int2 &tabsDimensions = OptionsUiView::TabsDimensions; const Int2 initialTabTextCenter( graphicsTabRect.getLeft() + (graphicsTabRect.getWidth() / 2), graphicsTabRect.getTop() + (graphicsTabRect.getHeight() / 2)); const Int2 tabOffset(0, tabsDimensions.y * tabIndex); const Int2 center = initialTabTextCenter + tabOffset; const TextBox::InitInfo textBoxInitInfo = TextBox::InitInfo::makeWithCenter( text, center, OptionsUiView::TabFontName, OptionsUiView::getTabTextColor(), OptionsUiView::TabTextAlignment, fontLibrary); if (!textBox.init(textBoxInitInfo, text, renderer)) { DebugCrash("Couldn't init text box " + std::to_string(tabIndex) + "."); } }; // @todo: should make this iterable initTabTextBox(this->graphicsTextBox, 0, OptionsUiModel::GRAPHICS_TAB_NAME); initTabTextBox(this->audioTextBox, 1, OptionsUiModel::AUDIO_TAB_NAME); initTabTextBox(this->inputTextBox, 2, OptionsUiModel::INPUT_TAB_NAME); initTabTextBox(this->miscTextBox, 3, OptionsUiModel::MISC_TAB_NAME); initTabTextBox(this->devTextBox, 4, OptionsUiModel::DEV_TAB_NAME); // Button proxies are added later. this->backToPauseMenuButton = Button<Game&>( OptionsUiView::BackToPauseMenuButtonCenterPoint, OptionsUiView::BackToPauseMenuButtonWidth, OptionsUiView::BackToPauseMenuButtonHeight, OptionsUiController::onBackToPauseMenuButtonSelected); this->tabButton = Button<OptionsPanel&, OptionsUiModel::Tab*, OptionsUiModel::Tab>( OptionsUiController::onTabButtonSelected); this->addInputActionListener(InputActionName::Back, [this](const InputActionCallbackValues &values) { if (values.performed) { this->backToPauseMenuButton.click(values.game); } }); // Create graphics options. this->graphicsOptions.emplace_back(OptionsUiModel::makeWindowModeOption(game)); this->graphicsOptions.emplace_back(OptionsUiModel::makeFpsLimitOption(game)); this->graphicsOptions.emplace_back(OptionsUiModel::makeResolutionScaleOption(game)); this->graphicsOptions.emplace_back(OptionsUiModel::makeVerticalFovOption(game)); this->graphicsOptions.emplace_back(OptionsUiModel::makeLetterboxModeOption(game)); this->graphicsOptions.emplace_back(OptionsUiModel::makeCursorScaleOption(game)); this->graphicsOptions.emplace_back(OptionsUiModel::makeModernInterfaceOption(game)); this->graphicsOptions.emplace_back(OptionsUiModel::makeRenderThreadsModeOption(game)); // Create audio options. this->audioOptions.emplace_back(OptionsUiModel::makeSoundChannelsOption(game)); this->audioOptions.emplace_back(OptionsUiModel::makeSoundResamplingOption(game)); this->audioOptions.emplace_back(OptionsUiModel::makeIs3dAudioOption(game)); // Create input options. this->inputOptions.emplace_back(OptionsUiModel::makeHorizontalSensitivityOption(game)); this->inputOptions.emplace_back(OptionsUiModel::makeVerticalSensitivityOption(game)); this->inputOptions.emplace_back(OptionsUiModel::makeCameraPitchLimitOption(game)); this->inputOptions.emplace_back(OptionsUiModel::makePixelPerfectSelectionOption(game)); // Create miscellaneous options. this->miscOptions.emplace_back(OptionsUiModel::makeShowCompassOption(game)); this->miscOptions.emplace_back(OptionsUiModel::makeShowIntroOption(game)); this->miscOptions.emplace_back(OptionsUiModel::makeTimeScaleOption(game)); this->miscOptions.emplace_back(OptionsUiModel::makeChunkDistanceOption(game)); this->miscOptions.emplace_back(OptionsUiModel::makeStarDensityOption(game)); this->miscOptions.emplace_back(OptionsUiModel::makePlayerHasLightOption(game)); // Create developer options. this->devOptions.emplace_back(OptionsUiModel::makeCollisionOption(game)); this->devOptions.emplace_back(OptionsUiModel::makeProfilerLevelOption(game)); // Set initial tab. this->tab = OptionsUiModel::Tab::Graphics; // Initialize all option text boxes and buttons for the initial tab. this->updateVisibleOptions(); return true; } std::vector<std::unique_ptr<OptionsUiModel::Option>> &OptionsPanel::getVisibleOptions() { if (this->tab == OptionsUiModel::Tab::Graphics) { return this->graphicsOptions; } else if (this->tab == OptionsUiModel::Tab::Audio) { return this->audioOptions; } else if (this->tab == OptionsUiModel::Tab::Input) { return this->inputOptions; } else if (this->tab == OptionsUiModel::Tab::Misc) { return this->miscOptions; } else if (this->tab == OptionsUiModel::Tab::Dev) { return this->devOptions; } else { throw DebugException("Invalid tab \"" + std::to_string(static_cast<int>(this->tab)) + "\"."); } } void OptionsPanel::initOptionTextBox(int index) { auto &game = this->getGame(); const auto &fontLibrary = game.getFontLibrary(); const std::string &fontName = OptionsUiView::OptionTextBoxFontName; int fontDefIndex; if (!fontLibrary.tryGetDefinitionIndex(fontName.c_str(), &fontDefIndex)) { DebugCrash("Couldn't get font definition for \"" + fontName + "\"."); } const FontDefinition &fontDef = fontLibrary.getDefinition(fontDefIndex); const std::string dummyText(28, TextRenderUtils::LARGEST_CHAR); const TextRenderUtils::TextureGenInfo textureGenInfo = TextRenderUtils::makeTextureGenInfo(dummyText, fontDef); const Int2 &point = OptionsUiView::ListOrigin; const int yOffset = textureGenInfo.height * index; const TextBox::InitInfo textBoxInitInfo = TextBox::InitInfo::makeWithXY( dummyText, point.x, point.y + yOffset, fontName, OptionsUiView::getOptionTextBoxColor(), OptionsUiView::OptionTextBoxTextAlignment, fontLibrary); DebugAssertIndex(this->currentTabTextBoxes, index); TextBox &textBox = this->currentTabTextBoxes[index]; if (!textBox.init(textBoxInitInfo, game.getRenderer())) { DebugCrash("Couldn't init tab text box " + std::to_string(index) + "."); } } void OptionsPanel::updateOptionTextBoxText(int index) { auto &game = this->getGame(); const auto &visibleOptions = this->getVisibleOptions(); DebugAssertIndex(visibleOptions, index); const auto &visibleOption = visibleOptions[index]; const std::string text = visibleOption->getName() + ": " + visibleOption->getDisplayedValue(); DebugAssertIndex(this->currentTabTextBoxes, index); TextBox &textBox = this->currentTabTextBoxes[index]; textBox.setText(text); } void OptionsPanel::updateVisibleOptions() { auto &game = this->getGame(); const auto &visibleOptions = this->getVisibleOptions(); this->currentTabTextBoxes.clear(); this->currentTabTextBoxes.resize(visibleOptions.size()); // Remove all button proxies, including the static ones. this->clearButtonProxies(); auto addTabButtonProxy = [this](OptionsUiModel::Tab tab, const Rect &rect) { this->addButtonProxy(MouseButtonType::Left, rect, [this, tab]() { this->tabButton.click(*this, &this->tab, tab); }); }; // Add the static button proxies. addTabButtonProxy(OptionsUiModel::Tab::Graphics, OptionsUiView::GraphicsTabRect); addTabButtonProxy(OptionsUiModel::Tab::Audio, OptionsUiView::AudioTabRect); addTabButtonProxy(OptionsUiModel::Tab::Input, OptionsUiView::InputTabRect); addTabButtonProxy(OptionsUiModel::Tab::Misc, OptionsUiView::MiscTabRect); addTabButtonProxy(OptionsUiModel::Tab::Dev, OptionsUiView::DevTabRect); this->addButtonProxy(MouseButtonType::Left, this->backToPauseMenuButton.getRect(), [this, &game]() { this->backToPauseMenuButton.click(game); }); auto addOptionButtonProxies = [this](int index) { DebugAssertIndex(this->currentTabTextBoxes, index); const TextBox &optionTextBox = this->currentTabTextBoxes[index]; const int optionTextBoxHeight = optionTextBox.getRect().getHeight(); const Rect optionRect( OptionsUiView::ListOrigin.x, OptionsUiView::ListOrigin.y + (optionTextBoxHeight * index), OptionsUiView::ListDimensions.x, optionTextBoxHeight); auto buttonFunc = [this, index](bool isLeftClick) { auto &visibleOptions = this->getVisibleOptions(); DebugAssertIndex(visibleOptions, index); std::unique_ptr<OptionsUiModel::Option> &optionPtr = visibleOptions[index]; OptionsUiModel::Option &option = *optionPtr; // Modify the option based on which button was pressed. if (isLeftClick) { TryIncrementOption(option); } else { TryDecrementOption(option); } this->updateOptionTextBoxText(index); }; this->addButtonProxy(MouseButtonType::Left, optionRect, [buttonFunc]() { buttonFunc(true); }); this->addButtonProxy(MouseButtonType::Right, optionRect, [buttonFunc]() { buttonFunc(false); }); }; for (int i = 0; i < static_cast<int>(visibleOptions.size()); i++) { this->initOptionTextBox(i); this->updateOptionTextBoxText(i); addOptionButtonProxies(i); } } std::optional<CursorData> OptionsPanel::getCurrentCursor() const { return this->getDefaultCursor(); } void OptionsPanel::drawReturnButtonsAndTabs(Renderer &renderer) { auto &textureManager = this->getGame().getTextureManager(); const Rect &graphicsTabRect = OptionsUiView::GraphicsTabRect; Texture tabBackground = TextureUtils::generate( OptionsUiView::TabBackgroundPatternType, graphicsTabRect.getWidth(), graphicsTabRect.getHeight(), textureManager, renderer); // @todo: this loop condition should be driven by actual tab count for (int i = 0; i < 5; i++) { const int tabX = graphicsTabRect.getLeft(); const int tabY = graphicsTabRect.getTop() + (tabBackground.getHeight() * i); renderer.drawOriginal(tabBackground, tabX, tabY); } Texture returnBackground = TextureUtils::generate( OptionsUiView::TabBackgroundPatternType, this->backToPauseMenuButton.getWidth(), this->backToPauseMenuButton.getHeight(), textureManager, renderer); renderer.drawOriginal(returnBackground, this->backToPauseMenuButton.getX(), this->backToPauseMenuButton.getY()); } void OptionsPanel::drawText(Renderer &renderer) { auto drawTextBox = [&renderer](TextBox &textBox) { const Rect &textBoxRect = textBox.getRect(); renderer.drawOriginal(textBox.getTexture(), textBoxRect.getLeft(), textBoxRect.getTop()); }; drawTextBox(this->titleTextBox); drawTextBox(this->backToPauseMenuTextBox); drawTextBox(this->graphicsTextBox); drawTextBox(this->audioTextBox); drawTextBox(this->inputTextBox); drawTextBox(this->miscTextBox); drawTextBox(this->devTextBox); } void OptionsPanel::drawTextOfOptions(Renderer &renderer) { const auto &visibleOptions = this->getVisibleOptions(); std::optional<int> highlightedOptionIndex; for (int i = 0; i < static_cast<int>(visibleOptions.size()); i++) { auto &optionTextBox = this->currentTabTextBoxes.at(i); const int optionTextBoxHeight = optionTextBox.getRect().getHeight(); const Rect optionRect( OptionsUiView::ListOrigin.x, OptionsUiView::ListOrigin.y + (optionTextBoxHeight * i), OptionsUiView::ListDimensions.x, optionTextBoxHeight); const auto &inputManager = this->getGame().getInputManager(); const Int2 mousePosition = inputManager.getMousePosition(); const Int2 originalPosition = renderer.nativeToOriginal(mousePosition); const bool optionRectContainsMouse = optionRect.contains(originalPosition); // If the options rect contains the mouse cursor, highlight it before drawing text. if (optionRectContainsMouse) { renderer.fillOriginalRect(OptionsUiView::HighlightColor, optionRect.getLeft(), optionRect.getTop(), optionRect.getWidth(), optionRect.getHeight()); // Store the highlighted option index for tooltip drawing. highlightedOptionIndex = i; } // Draw option text. const Rect &optionTextBoxRect = optionTextBox.getRect(); renderer.drawOriginal(optionTextBox.getTexture(), optionTextBoxRect.getLeft(), optionTextBoxRect.getTop()); // Draw description if hovering over an option with a non-empty tooltip. if (highlightedOptionIndex.has_value()) { DebugAssertIndex(visibleOptions, *highlightedOptionIndex); const auto &visibleOption = visibleOptions[*highlightedOptionIndex]; const std::string &tooltip = visibleOption->getTooltip(); // Only draw if the tooltip has text. if (!tooltip.empty()) { this->drawDescription(tooltip, renderer); } } } } void OptionsPanel::drawDescription(const std::string &text, Renderer &renderer) { auto &game = this->getGame(); const auto &fontLibrary = game.getFontLibrary(); const Int2 &point = OptionsUiView::DescriptionOrigin; const TextBox::InitInfo textBoxInitInfo = TextBox::InitInfo::makeWithXY( text, point.x, point.y, OptionsUiView::DescriptionTextFontName, OptionsUiView::getDescriptionTextColor(), OptionsUiView::DescriptionTextAlignment, fontLibrary); TextBox descriptionTextBox; if (!descriptionTextBox.init(textBoxInitInfo, text, renderer)) { DebugCrash("Couldn't init description text box."); } const Rect &descriptionTextBoxRect = descriptionTextBox.getRect(); renderer.drawOriginal(descriptionTextBox.getTexture(), descriptionTextBoxRect.getLeft(), descriptionTextBoxRect.getTop()); } void OptionsPanel::render(Renderer &renderer) { // Clear full screen. renderer.clear(); // Draw solid background. renderer.clearOriginal(OptionsUiView::BackgroundColor); // Draw elements. this->drawReturnButtonsAndTabs(renderer); this->drawText(renderer); this->drawTextOfOptions(renderer); }
34.240404
113
0.758275
[ "render", "vector", "solid" ]
0bf18cd022bfffc9646cd32b63a6f7d69814a970
3,447
cpp
C++
Corvus/Source/Corvus/Core/CoreLayer.cpp
sltn011/Corvus
4ca8cd05298deafe7fafa43790d7481685ee2983
[ "Apache-2.0" ]
1
2022-03-27T16:53:24.000Z
2022-03-27T16:53:24.000Z
Corvus/Source/Corvus/Core/CoreLayer.cpp
sltn011/Corvus
4ca8cd05298deafe7fafa43790d7481685ee2983
[ "Apache-2.0" ]
null
null
null
Corvus/Source/Corvus/Core/CoreLayer.cpp
sltn011/Corvus
4ca8cd05298deafe7fafa43790d7481685ee2983
[ "Apache-2.0" ]
null
null
null
#include "CorvusPCH.h" #include "Corvus/Core/CoreLayer.h" #include "Corvus/Core/Application.h" #include "Corvus/Events/Event.h" #include "Corvus/Renderer/Renderer.h" #include "Corvus/Time/TimeDelta.h" namespace Corvus { CoreLayer::CoreLayer() : Layer{ "Corvus Core Layer", true } { } void CoreLayer::OnPushed() { Super::OnPushed(); } void CoreLayer::OnPoped() { Super::OnPoped(); } void CoreLayer::OnUpdate(TimeDelta ElapsedTime) { } void CoreLayer::OnEvent(Event &Event) { if (Event.IsInCategory(Event::ECategory::Application)) { OnApplicationEvent(Event); } if (Event.IsInCategory(Event::ECategory::Keyboard)) { OnKeyboardEvent(Event); } if (Event.IsInCategory(Event::ECategory::Mouse)) { OnMouseEvent(Event); } } void CoreLayer::Render() { } void CoreLayer::OnApplicationEvent(Event &Event) { switch (Event.GetEventType()) { case Event::EType::WindowResize: OnWindowResize(Event); break; case Event::EType::WindowClose: OnWindowClose(Event); break; case Event::EType::WindowChangeFocus: OnWindowChangeFocus(Event); break; default: break; } } void CoreLayer::OnKeyboardEvent(Event &Event) { switch (Event.GetEventType()) { case Event::EType::KeyPress: OnKeyPressed(Event); break; case Event::EType::KeyRelease: OnKeyReleased(Event); break; default: break; } } void CoreLayer::OnMouseEvent(Event &Event) { switch (Event.GetEventType()) { case Event::EType::MouseButtonPress: OnMouseButtonPressed(Event); break; case Event::EType::MouseButtonRelease: OnMouseButtonReleased(Event); break; case Event::EType::MouseCursorMove: OnMouseCursorMove(Event); break; case Event::EType::MouseScroll: OnMouseScroll(Event); break; default: break; } } void CoreLayer::OnWindowResize(Event &Event) { WindowResizeEvent &WREvent = static_cast<WindowResizeEvent&>(Event); Renderer::ViewportResize(WREvent.NewWidth, WREvent.NewHeight); Event.SetHandled(); } void CoreLayer::OnWindowClose(Event &Event) { Application::GetInstance().GetWindow().SetShouldClose(); Event.SetHandled(); } void CoreLayer::OnWindowChangeFocus(Event &Event) { } void CoreLayer::OnKeyPressed(Event &Event) { KeyPressEvent &KPEvent = static_cast<KeyPressEvent &>(Event); if (KPEvent.Key == Key::F1) { bool b = Application::GetInstance().GetWindow().IsFullScreen(); Application::GetInstance().GetWindow().SetFullScreen(!b); } } void CoreLayer::OnKeyReleased(Event &Event) { } void CoreLayer::OnMouseButtonPressed(Event &Event) { } void CoreLayer::OnMouseButtonReleased(Event &Event) { } void CoreLayer::OnMouseCursorMove(Event &Event) { } void CoreLayer::OnMouseScroll(Event &Event) { } }
21.277778
76
0.562518
[ "render" ]
0bf2236223a25be427aabdcb49133b4172e675ae
2,796
cpp
C++
449. Serialize and Deserialize BST.cpp
yuyangh/LeetCode
5d81cbd975c0c1f2bbca0cb25cefe361a169e460
[ "MIT" ]
1
2020-10-11T08:10:53.000Z
2020-10-11T08:10:53.000Z
449. Serialize and Deserialize BST.cpp
yuyangh/LeetCode
5d81cbd975c0c1f2bbca0cb25cefe361a169e460
[ "MIT" ]
null
null
null
449. Serialize and Deserialize BST.cpp
yuyangh/LeetCode
5d81cbd975c0c1f2bbca0cb25cefe361a169e460
[ "MIT" ]
null
null
null
#include "LeetCodeLib.h" /* * 449. Serialize and Deserialize BST * * https://leetcode.com/problems/serialize-and-deserialize-bst/description/ * * algorithms * Medium * * Serialization is the process of converting a binaryIndexTree structure or object into a * sequence of bits so that it can be stored in a file or memory buffer, or * transmitted across a network connection link to be reconstructed later in * the same or another computer environment. * * Design an algorithm to serialize and deserialize a binary search tree. There * is no restriction on how your serialization/deserialization algorithm should * work. You just need to ensure that a binary search tree can be serialized to * a string and this string can be deserialized to the original tree * structure. * * The encoded string should be as compact as possible. * * Note: Do not use class member/global/static variables to store states. Your * serialize and deserialize algorithms should be stateless. * */ /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Codec { public: // Encodes a tree to a single string. // pre order traversal to copy the structure // pre order: self, left, right string serialize(TreeNode *root) { string str; if (root == nullptr) { return str; } else { str += (to_string(root->val) + " "); } str += (serialize(root->left)); str += (serialize(root->right)); return str; } // Decodes your encoded binaryIndexTree to tree. TreeNode *deserialize(string data) { if (data.empty()) { return nullptr; } queue<int> nums; int num; stringstream ss(data); while (ss >> num) { nums.push(num); } stack<TreeNode *> parents; TreeNode *result = preOrder(nums, parents); return result; } // pre order traversal to restore the structure TreeNode *preOrder(queue<int> &nums, stack<TreeNode *> &parents) { if (nums.empty()) { return nullptr; } TreeNode *root = new TreeNode(nums.front()); nums.pop(); parents.push(root); TreeNode *temp, *parent; while (!nums.empty()) { parent = parents.top(); temp = new TreeNode(nums.front()); nums.pop(); // append either left or right if (temp->val < parents.top()->val) { parent->left = temp; parents.push(temp); } else { // pop the stack to get the parent while (!parents.empty() && parents.top()->val < temp->val) { parent = parents.top(); parents.pop(); } parent->right = temp; parents.push(temp); } } return root; } }; // Your Codec object will be instantiated and called as such: // Codec codec; // codec.deserialize(codec.serialize(root));
25.189189
90
0.66309
[ "object" ]
0bf2bcd1f48959fc292a09b83cd1e69de287e542
1,646
cpp
C++
src/use/mesh_cache.cpp
RedcraneStudio/redcrane-engine
4da8a7caedd6da5ffb7eda7da8c9a42396273bf6
[ "BSD-3-Clause" ]
5
2017-05-16T22:25:59.000Z
2020-02-10T20:19:35.000Z
src/use/mesh_cache.cpp
RedCraneStudio/redcrane-engine
4da8a7caedd6da5ffb7eda7da8c9a42396273bf6
[ "BSD-3-Clause" ]
1
2017-10-13T00:35:56.000Z
2017-10-13T00:35:56.000Z
src/use/mesh_cache.cpp
RedCraneStudio/redcrane-engine
4da8a7caedd6da5ffb7eda7da8c9a42396273bf6
[ "BSD-3-Clause" ]
2
2017-10-07T04:40:52.000Z
2021-09-27T05:59:05.000Z
/* * Copyright (C) 2015 Luke San Antonio * All rights reserved. */ #include "mesh_cache.h" #include "../common/debugging.h" #include "../gfx/mesh_data.h" #include "../gfx/extra/load_wavefront.h" #include "../gfx/extra/mesh_conversion.h" #include "../gfx/extra/allocate.h" #include "../gfx/extra/format.h" #include "../gfx/extra/write_data_to_mesh.h" namespace redc { namespace gfx { Mesh_Cache::Mesh_Cache(assets::fs::path source_path, assets::fs::path cache_dir) : Fs_Cache{{source_path, "obj", false}, {cache_dir, "obj.cache", true}} {} Indexed_Mesh_Data Mesh_Cache::load_from_source_stream(std::istream& st) { // Load .obj file auto split_mesh = gfx::load_wavefront(st); // Return combined return gfx::to_indexed_mesh_data(split_mesh); } Indexed_Mesh_Data Mesh_Cache::load_from_cache_stream(std::istream& st) { // Load it in with msgpack, because that's how we wrote it! msgpack::unpacker unpacker; constexpr std::size_t read_size = 4096; while(!st.eof()) { unpacker.reserve_buffer(read_size); st.read(unpacker.buffer(), read_size); unpacker.buffer_consumed(st.gcount()); } msgpack::unpacked object; bool found = unpacker.next(object); REDC_ASSERT(found); Indexed_Mesh_Data mesh; REDC_ASSERT_NO_THROW(mesh = object.get().as<Indexed_Mesh_Data>()); return mesh; } void Mesh_Cache::write_cache(Indexed_Mesh_Data const& msh, std::ostream& str) { // Write the stuff to the file msgpack::pack(str, msh); } } }
27.433333
73
0.638518
[ "mesh", "object" ]
0bf9280b8127984101cc024878d86232e87c5e37
7,370
cpp
C++
Engine/Src/Engine/Render/Shader/HIBLConvert.cpp
helluvamesh/OpenGLRenderer
c1dbc6da3cbb4639284242de176d4f4fb383da30
[ "Apache-2.0" ]
null
null
null
Engine/Src/Engine/Render/Shader/HIBLConvert.cpp
helluvamesh/OpenGLRenderer
c1dbc6da3cbb4639284242de176d4f4fb383da30
[ "Apache-2.0" ]
null
null
null
Engine/Src/Engine/Render/Shader/HIBLConvert.cpp
helluvamesh/OpenGLRenderer
c1dbc6da3cbb4639284242de176d4f4fb383da30
[ "Apache-2.0" ]
null
null
null
#include "Engine\pch.h" #include "HIBLConvert.h" #include "Engine\Render\RenderUtil\GLMath.h" #include "Engine\Util\SEngine.h" void HIBLConvert::Load() { this->Loaded = true; this->UnitCubeMesh = MakeShared<HStaticMesh>(); this->UnitCubeMesh->SetFilepath(SEngine::ContentPath + TX("Meshes/UnitCube.asset")); this->UnitCubeMesh->Load(); this->UnitCube = MakeShared<HStaticMeshNode>(); this->UnitCube->SetMesh(this->UnitCubeMesh); // ------------ IRRADIANCE ---------------- DSurfaceShaderSettings irrShaderSettings; irrShaderSettings.SourceFilepaths = { SEngine::ContentPath + TX("Shaders/Environment.vert"), SEngine::ContentPath + TX("Shaders/EnvironmentIrradiance.frag") }; irrShaderSettings.Unlit = true; this->IrrShader = MakeShared<HSurfaceShader>(); this->IrrShader->SetName(TX("IrrShader")); this->IrrShader->Load(irrShaderSettings); DSurfaceMaterialSettings irrMaterialSettings; irrMaterialSettings.Shader = this->IrrShader; irrMaterialSettings.DoubleSided = true; this->IrrMaterial = MakeShared<HSurfaceMaterial>(); this->IrrMaterial->Load(irrMaterialSettings); this->UnitCube->SetMaterialOverride(0, this->IrrMaterial); this->IrrTarget = MakeShared<HFrameBuffer>(); // ------------ REFLECTION ---------------- DSurfaceShaderSettings refShaderSettings; refShaderSettings.SourceFilepaths = { SEngine::ContentPath + TX("Shaders/Environment.vert"), SEngine::ContentPath + TX("Shaders/EnvironmentReflection.frag") }; refShaderSettings.Unlit = true; this->RefShader = MakeShared<HSurfaceShader>(); this->RefShader->SetName(TX("RefShader")); this->RefShader->Load(refShaderSettings); DSurfaceMaterialSettings refMaterialSettings; refMaterialSettings.Shader = this->RefShader; refMaterialSettings.DoubleSided = true; this->RefMaterial = MakeShared<HSurfaceMaterial>(); this->RefMaterial->Load(refMaterialSettings); this->RefTarget = MakeShared<HFrameBuffer>(); } void HIBLConvert::GenerateLightmaps( const DArray<shared<HRenderTargetCube>>& Cubemaps, int32 IrradianceDim, int32 ReflectionDim, DArray<shared<HRenderTargetCube>>& OutIrradianceMaps, DArray<shared<HRenderTargetCube>>& OutReflectionMaps, bool VFlip ) { if (this->Loaded == false) { SLog::Error("IBLConvert is not loaded"); return; } this->IrrMaterial->SetIntParam(TX("VFlip"), VFlip == false); this->RefMaterial->SetIntParam(TX("VFlip"), VFlip == false); DCameraRenderData cam; cam.ProjectionMatrix = GLMath::PerspectiveMatrix(FMath::DegToRad(90), 1, .1f, 10); // ------------ IRRADIANCE ---------------- OutIrradianceMaps.Reserve(Cubemaps.Length()); this->IrrTarget->Prepare(IrradianceDim, IrradianceDim, 1, 1); this->IrrShader->Use(); for (int32 i = 0; i < Cubemaps.Length(); i++) { DRenderTargetCubeSettings irrTextureSettings; irrTextureSettings.Format = ERenderTargetCubeFormat::RGB16F; irrTextureSettings.Width = IrradianceDim; irrTextureSettings.Height = IrradianceDim; irrTextureSettings.GenerateMipMaps = false; irrTextureSettings.Wrap = ETextureWrap::CLAMP_TO_EDGE; shared<HRenderTargetCube> irrTexture = MakeShared<HRenderTargetCube>(); irrTexture->Load(irrTextureSettings); this->IrrTarget->SetColorAttachment(0, irrTexture); this->IrrMaterial->SetTextureParam(TX("EnvMap"), Cubemaps[i]); this->IrrMaterial->ApplyStateOnShader(); // left this->IrrTarget->AttachCubemapSide(0, 0); this->IrrTarget->Bind(true); cam.ViewMatrix = HRenderTargetCube::CubeSideViews[0]; this->IrrMaterial->ApplyNodeStateOnShader(cam, this->UnitCube->GetRenderData()); this->UnitCubeMesh->DrawStandalone(); // right this->IrrTarget->AttachCubemapSide(1, 0); this->IrrTarget->Bind(true); cam.ViewMatrix = HRenderTargetCube::CubeSideViews[1]; this->IrrMaterial->ApplyNodeStateOnShader(cam, this->UnitCube->GetRenderData()); this->UnitCubeMesh->DrawStandalone(); // top this->IrrTarget->AttachCubemapSide(2, 0); this->IrrTarget->Bind(true); cam.ViewMatrix = HRenderTargetCube::CubeSideViews[2]; this->IrrMaterial->ApplyNodeStateOnShader(cam, this->UnitCube->GetRenderData()); this->UnitCubeMesh->DrawStandalone(); // bottom this->IrrTarget->AttachCubemapSide(3, 0); this->IrrTarget->Bind(true); cam.ViewMatrix = HRenderTargetCube::CubeSideViews[3]; this->IrrMaterial->ApplyNodeStateOnShader(cam, this->UnitCube->GetRenderData()); this->UnitCubeMesh->DrawStandalone(); // back this->IrrTarget->AttachCubemapSide(4, 0); this->IrrTarget->Bind(true); cam.ViewMatrix = HRenderTargetCube::CubeSideViews[4]; this->IrrMaterial->ApplyNodeStateOnShader(cam, this->UnitCube->GetRenderData()); this->UnitCubeMesh->DrawStandalone(); // front this->IrrTarget->AttachCubemapSide(5, 0); this->IrrTarget->Bind(true); cam.ViewMatrix = HRenderTargetCube::CubeSideViews[5]; this->IrrMaterial->ApplyNodeStateOnShader(cam, this->UnitCube->GetRenderData()); this->UnitCubeMesh->DrawStandalone(); OutIrradianceMaps.Add(irrTexture); } this->IrrTarget->BindNone(); // ------------ REFLECTION ---------------- this->UnitCube->SetMaterialOverride(0, this->RefMaterial); this->RefShader->Use(); OutReflectionMaps.Reserve(Cubemaps.Length()); for (int32 i = 0; i < Cubemaps.Length(); i++) { DRenderTargetCubeSettings refTextureSettings; refTextureSettings.Format = ERenderTargetCubeFormat::RGB16F; refTextureSettings.Width = ReflectionDim; refTextureSettings.Height = ReflectionDim; refTextureSettings.FixedMipCount = 4; refTextureSettings.Wrap = ETextureWrap::CLAMP_TO_EDGE; shared<HRenderTargetCube> refTexture = MakeShared<HRenderTargetCube>(); refTexture->Load(refTextureSettings); this->RefTarget->SetColorAttachment(0, refTexture); this->RefMaterial->SetTextureParam(TX("EnvMap"), Cubemaps[i]); int32 mipCount = 5; for (int32 mip_i = 0; mip_i < mipCount; mip_i++) { int32 divider = (int32)FMath::Pow(2.0, (float)mip_i); int32 width = refTexture->GetWidth() / divider; int32 height = refTexture->GetHeight() / divider; this->RefTarget->Prepare(width, height, 1, 1); this->RefMaterial->SetFloatParam(TX("Roughness"), (float)mip_i / (float)(mipCount - 1)); this->RefMaterial->ApplyStateOnShader(); for (int32 side_i = 0; side_i < 6; side_i++) { this->RefTarget->AttachCubemapSide(side_i, mip_i); this->RefTarget->Bind(true); cam.ViewMatrix = HRenderTargetCube::CubeSideViews[side_i]; this->RefMaterial->ApplyNodeStateOnShader(cam, this->UnitCube->GetRenderData()); this->UnitCubeMesh->DrawStandalone(); } } OutReflectionMaps.Add(refTexture); } this->RefTarget->BindNone(); }
35.776699
100
0.656581
[ "render" ]
0bf98606ea62dd6d493e6e495bbcfd35a80792a5
3,882
cpp
C++
src/arkanoid/block.cpp
razorbeard/classic-games
01130f35d5d7538b17a9d447d63227a3cee00111
[ "MIT" ]
null
null
null
src/arkanoid/block.cpp
razorbeard/classic-games
01130f35d5d7538b17a9d447d63227a3cee00111
[ "MIT" ]
null
null
null
src/arkanoid/block.cpp
razorbeard/classic-games
01130f35d5d7538b17a9d447d63227a3cee00111
[ "MIT" ]
null
null
null
#include "arkanoid/block.hpp" #include "data_tables.hpp" #include "resources/resource_holder.hpp" #include "utility.hpp" #include "arkanoid/power_up.hpp" #include "commands/command_queue.hpp" #include <SFML/Graphics/RenderTarget.hpp> namespace { const std::vector<BlockData> Table = initializeBlockData(); } Block::Block(Color color, const TextureHolder& textures, Grid* grid) : Entity(Table[color].hitpoints, grid) , mColor(color) , mSpriteAnimation(textures.get(Table[color].texture), Table[color].textureRect) , mDropPowerUpCommand() , mGrid(grid) , mOldHitpoints(Table[color].hitpoints) , mRemovalFlag(false) , mShowShinning(false) , mCanDropPowerUp(true) , mSpawnedPowerUp(false) { mSpriteAnimation.setFrameSize(Table[color].frameSize); mSpriteAnimation.setNumFrames(Table[color].numFrames); mSpriteAnimation.setDuration(Table[color].duration); mSpriteAnimation.setSpacing(Table[color].spacing); mDropPowerUpCommand.category = Category::DefaultLayer; mDropPowerUpCommand.action = [this, &textures](SceneNode& node, sf::Time) { createPowerUp(node, textures); }; centerOrigin(mSpriteAnimation); } void Block::drawCurrent(sf::RenderTarget& target, sf::RenderStates states) const { target.draw(mSpriteAnimation, states); } void Block::updateCurrent(sf::Time dt, CommandQueue& commands) { // Block has been destroyed : random power up drop and mark for removal // If not marked for removal, this step is not checked ! Careful if (isDestroyed()) { checkPowerUpDrop(commands); return; } // The block has take a hit : replay the animation from start // Gives a shinning effect for gold and silver blocks if (mOldHitpoints > getHitpoints()) { mSpriteAnimation.restart(); mOldHitpoints = getHitpoints(); } mSpriteAnimation.update(dt); } void Block::canDropPowerUp(bool flag) noexcept { mCanDropPowerUp = flag; } void Block::checkPowerUpDrop(CommandQueue& commands) { // A block has 1/8 chance to drop a power up if (randomInt(8) == 0 && !mRemovalFlag && mCanDropPowerUp) { // When a block has drop a power up, we cannot drop more power ups // until it is destroyed or catched by the Vaus Command command{}; command.category = Category::Block; command.action = derivedAction<Block>([](Block& block, sf::Time) { block.canDropPowerUp(false); }); commands.push(command); commands.push(mDropPowerUpCommand); } mRemovalFlag = true; } void Block::remove() { // Calling a remove on a block avoids the creation of a power up mRemovalFlag = true; Entity::remove(); } bool Block::isMarkedForRemoval() const { return isDestroyed() && mRemovalFlag; } unsigned int Block::getCategory() const { return Category::Block; } int Block::getValue() const { return Table[mColor].value; } Block::Color Block::getColor() const { return mColor; } sf::FloatRect Block::getBoundingRect() const { return getWorldTransform().transformRect(mSpriteAnimation.getGlobalBounds()); } void Block::createPowerUp(SceneNode& node, const TextureHolder& textures) const { // Choose a random number between 0 and 99, then select a power up int const randomNum{ randomInt(100) }; PowerUp::Type type{ PowerUp::Enlarge }; // By default if (randomNum <= 4) type = PowerUp::Break; else if (5 <= randomNum && randomNum <= 12) type = PowerUp::Player; else if (13 <= randomNum && randomNum <= 25) type = PowerUp::Disruption; else if (26 <= randomNum && randomNum <= 42) type = PowerUp::Catch; else if (43 <= randomNum && randomNum <= 59) type = PowerUp::Reverse; else if (60 <= randomNum && randomNum <= 79) type = PowerUp::Laser; else if (80 <= randomNum && randomNum <= 99) type = PowerUp::Enlarge; std::unique_ptr<PowerUp> powerUp{ new PowerUp(type, textures, mGrid) }; powerUp->setPosition(getWorldPosition()); powerUp->setVelocity(0.0f, 200.0f); node.attachChild(std::move(powerUp)); }
26.958333
81
0.723338
[ "vector" ]
0401ba507209e1e057f0a590806770a40cc8b108
534
cc
C++
static_assert/main.cc
mocsy/playground
326d2dfaeb47a4e7f2b6787487fcde32e4cdf8b6
[ "BSD-3-Clause" ]
null
null
null
static_assert/main.cc
mocsy/playground
326d2dfaeb47a4e7f2b6787487fcde32e4cdf8b6
[ "BSD-3-Clause" ]
null
null
null
static_assert/main.cc
mocsy/playground
326d2dfaeb47a4e7f2b6787487fcde32e4cdf8b6
[ "BSD-3-Clause" ]
null
null
null
#include <iostream> #include <vector> #include <algorithm> #include <fstream> #include "static_assert.hpp" using namespace std; #define GCC_VERSION (__GNUC__ * 10000 \ + __GNUC_MINOR__ * 100 \ + __GNUC_PATCHLEVEL__) int main(int argc, const char* argv[]) { //cout << GCC_VERSION <<endl; //unsigned int i = 0xFFFFFFFF; //int i = 0x7FFFFFFF; //cout << i << endl; //i += 1; //i -= 2; //cout << i << endl; int i = -9; //BOOST_STATIC_ASSERT< sizeof(int) == 1 >; BOOST_STATIC_ASSERT(sizeof(int) == 0); }
18.413793
45
0.61985
[ "vector" ]
0402df8678a2a2587fd856ffa37c4251022238e1
11,571
cpp
C++
source/core/commandcontroller/commandcontroller.cpp
efedo/Utilogeny
03b7e7d2650c326f8493df35c14470f21de3be78
[ "MIT" ]
null
null
null
source/core/commandcontroller/commandcontroller.cpp
efedo/Utilogeny
03b7e7d2650c326f8493df35c14470f21de3be78
[ "MIT" ]
null
null
null
source/core/commandcontroller/commandcontroller.cpp
efedo/Utilogeny
03b7e7d2650c326f8493df35c14470f21de3be78
[ "MIT" ]
null
null
null
// Copyright 2017-20 Eric Fedosejevs // //#include "source/core/stdafx.h" #include "Utilogeny/source/core/precomp.h" #include "Utilogeny/source/core/utilogeny.h" #include "Utilogeny/source/core/exceptions.h" #include "Utilogeny/source/core/utilities.h" #include "Utilogeny/source/core/commandcontroller/commandqueue.h" #include "Utilogeny/source/core/commandcontroller/commandcontroller.h" #include "Utilogeny/source/core/commandcontroller/consolecontroller.h" //#include "source/core/commandcontroller/commands/commands.h" //#include "source/core/commandcontroller/settings/settings.h" //#include "source/core/globals.h" //#include "source/core/datatable/datatable.h" //#include "source/core/utils/bioutils.h" //#include "source/core/stats/statistics.h" //#include "source/core/correlnet/correlnet_graph.h" //#include "source/core/signal/signalrelay.h" //#include "source/core/neuralnet/commands/nncmdmanager.h" // Command/setting utility functions bool wrongArgNum(const std::vector<std::string> & args, unsigned int min, unsigned int max) { if ((args.size() < min) || (args.size() > max)) { std::cerr << "Incorrect number of arguments.\n"; return true; } return false; } bool wrongArgNum(const std::vector<std::string> & args, unsigned int num) { if (args.size() != num) { std::cerr << "Incorrect number of arguments.\n"; return true; } return false; } cCommand::cCommand(const std::string & tmpKeyword, void(*tmpFuncPtr)(cQueuedCommand &) ) : cCommand(tmpKeyword, tmpFuncPtr, "No description of command provided") {} cCommand::cCommand(const std::string & tmpKeyword, void(*tmpFuncPtr)(cQueuedCommand &), const std::string & tmpDescript) : keyword(tmpKeyword), execute(tmpFuncPtr), description(tmpDescript) {} cSetting::cSetting(const std::string & tmpKeyword, bool(*tmpFuncPtr)(cQueuedCommand &, bool)) : cSetting(tmpKeyword, tmpFuncPtr, "No description of setting provided") {} cSetting::cSetting(const std::string & tmpKeyword, bool(*tmpFuncPtr)(cQueuedCommand &, bool), const std::string & tmpDescript) : keyword(tmpKeyword), set(tmpFuncPtr), description(tmpDescript) {} cCommandController* cCommandController::myInstance = 0; cCommandController* cCommandController::get() { if (!myInstance) throwl("Command controller not initialized"); return myInstance; } void cCommandController::init() { //std::mutex cmdControllerTerminationMutex; myInstance = new cCommandController(0, 0); } void cCommandController::terminate() { if (myInstance) { myInstance->keepRunning = false; } } void cCommandController::wait_for_termination() { if (myInstance) { // Shutdown procedure begins once you have a lock on the termination mutex myInstance->cmdControllerTerminationMutex.lock(); myInstance->cmdControllerTerminationMutex.unlock(); delete myInstance; } } cCommandController::cCommandController(void (*tmpSignalSettingFailurePtr)(cQueuedCommand&), void (*tmpSignalCommandFailurePtr)(cQueuedCommand&)) : scriptrecursiondepth(0), commandConsoleLoopThread(0), commandProcessLoopThread(0), signalSettingFailurePtr(tmpSignalSettingFailurePtr), signalCommandFailurePtr(tmpSignalCommandFailurePtr) { //if (!cmdControllerTerminationMutex) throwl("Termination mutex not supplied by main application"); // If you try to load more than one command controller, throw if (myInstance) throwl("Tried to load multiple command controllers"); // If you already have a command controller thread, something has gone wrong; throw if (commandConsoleLoopThread) { std::cerr << "Already have a command console thread!\n"; throwl("Bad thread flow!\n"); } std::cout << "Initializing console.\n"; // Make a new command input loop thread (gets user console inputs) commandConsoleLoopThread = new std::thread(&cCommandController::commandConsoleLoop, this); if (commandProcessLoopThread) { std::cerr << "Already have a command processing thread!\n"; throwl("Bad thread flow!\n"); } // Make a new command processing loop thread commandProcessLoopThread = new std::thread(&cCommandController::commandProcLoop, this); // Need to wait until procLoop has the termination mutex lock to prevent premature termination while (!procLoopRunning) { std::this_thread::sleep_for(std::chrono::milliseconds(10)); } } cCommandController::~cCommandController() { keepRunning = false; if (commandConsoleLoopThread) { //commandConsoleLoopThread->join(); // Note that this will never happen unless you trigger cin commandConsoleLoopThread->detach(); // Throw it into the abyss delete commandConsoleLoopThread; } if (commandProcessLoopThread) { commandProcessLoopThread->join(); // Should be fine delete commandProcessLoopThread; } } // Clears list of available commands void cCommandController::clearCommandsSettings() { _commands.clear(); _settings.clear(); } void cCommandController::addCommand(std::string tmpCommandString, void(*tmpFunc)(cQueuedCommand &)) { _commands.emplace(tmpCommandString, cCommand(tmpCommandString, tmpFunc)); } void cCommandController::addCommand(std::string tmpCommandString, void(*tmpFunc)(cQueuedCommand &), const std::string & tmpDescript) { _commands.emplace(tmpCommandString, cCommand(tmpCommandString, tmpFunc, tmpDescript)); } void cCommandController::removeCommand(std::string tmpCommandString) { if (_commands.count(tmpCommandString)) { _commands.erase(tmpCommandString); } else { std::cerr << "Could not remove command \"" << tmpCommandString << "\"\n"; } } void cCommandController::removeCommandIfPresent(std::string tmpCommandString) { if (_commands.count(tmpCommandString)) { _commands.erase(tmpCommandString); } } void cCommandController::addSetting(std::string tmpCommandString, bool(*tmpFunc)(cQueuedCommand &, bool)) { _settings.emplace(tmpCommandString, cSetting(tmpCommandString, tmpFunc)); } void cCommandController::addSetting(std::string tmpCommandString, bool(*tmpFunc)(cQueuedCommand &, bool), const std::string & tmpDescript) { _settings.emplace(tmpCommandString, cSetting(tmpCommandString, tmpFunc, tmpDescript)); } void cCommandController::removeSetting(std::string tmpCommandString) { if (_settings.count(tmpCommandString)) _settings.erase(tmpCommandString); } // Prints a list of commands void cCommandController::printCommands() { std::cout << "Available commands are currently as follows:" << std::endl; for (std::map<std::string, cCommand>::iterator it = _commands.begin(); it != _commands.end(); ++it) { std::cout << '\t' << it->first << std::endl; } } // Prints a list of settings void cCommandController::printSettings() { std::cout << "Available settings are currently as follows:" << std::endl; for (std::map<std::string, cSetting>::iterator it = _settings.begin(); it != _settings.end(); ++it) { std::cout << '\t' << it->first << std::endl; } } // Prints help for a specific command or settings void cCommandController::printItemHelp(std::string keyword) { if (_commands.count(keyword)) { _commands.at(keyword).printhelp(); } else if (_settings.count(keyword)) { _settings.at(keyword).printhelp(); } else { std::cout << "Command or setting \"" << keyword << "\" does not exist.\n"; } } // User command loop void cCommandController::commandConsoleLoop() { while (keepRunning) { std::cout << "\n>"; commandConsoleStep(); } } // Command input loop inline void cCommandController::commandConsoleStep() { std::string commandline; std::getline(std::cin, commandline); // Blocking! queueConsoleCommand(commandline); } // Command processing loop void cCommandController::commandProcLoop() { // Lock the termination mutex to indicate that you are not terminated cmdControllerTerminationMutex.lock(); procLoopRunning = true; cQueuedCommand nextCmd; while (keepRunning) { if (queuedCmds.getNextCmd(nextCmd)) { procLine(nextCmd); } else { std::this_thread::sleep_for(std::chrono::milliseconds(10)); } } // Lock the termination mutex to indicate that you are not terminated cmdControllerTerminationMutex.unlock(); } void cCommandController::setDependentCompletion(const tCommandNum & delayedCmd, const tCommandNum & delayingCmd) { queuedCmds.setDefCompletion(delayedCmd, delayingCmd); } // Add GUI command to command queue tCommandNum cCommandController::queueGUICommand(const std::string & line) { return queuedCmds.addGUICmdToQueue(line); } // Add console command to command queue tCommandNum cCommandController::queueConsoleCommand(const std::string & line) { return queuedCmds.addConsoleCmdToQueue(line); } // Add run command to command queue tCommandNum cCommandController::queueScriptCommand(const std::string & line) { return queuedCmds.addScriptCmdToQueue(line); } bool cCommandController::isCommandComplete(const tCommandNum & tmpCmdNum) const { return queuedCmds.isCommandComplete(tmpCmdNum); } // Process command line void cCommandController::procLine(cQueuedCommand & cmd) { if (cmd.splitCommand.size() > 0) { // If run command, determine whether to mirror based on setting std::cout << "\b#exec: " << cmd.commandText << "\n\n"; if (_commands.count(cmd.keyword)) { try { _commands.at(cmd.keyword).execute(cmd); } catch (...) { std::cerr << "\nException in command:\n" << "\tCommand num: " << cmd.getCommandNumber() << "\n" << "\tCommand string: " << cmd.commandText << "\n\n"; try { throw; } catch (const cException & e) { _print_exception_func(e); } catch (const std::exception& e) { _print_exception_func(cException("Uncaught standard library exception", e)); } catch (...) { std::cerr << "Exception was not traceable.\n"; } // Pop-up in GUI if (signalCommandFailurePtr) signalCommandFailurePtr(cmd); } } else { std::cerr << "Invalid command: " << cmd.keyword << ".\n"; } queuedCmds.completeCommand(cmd); // Set as complete regardless so that execution can continue std::cout << "\n"; } // Unmute the console (if muted for script input etc.) at the appropriate time if (Utilogeny::log::muteConsole && queuedCmds.isCommandComplete(Utilogeny::log::unmuteConsoleAfterCommand)) { unMuteConsole(); std::cout << "\n"; } std::cout << ">"; std::cout.flush(); } // Proc setting void cCommandController::changeSetting(cQueuedCommand & cmd) { std::string settingKeyword = cmd.splitCommand.at(1); to_lower(settingKeyword); if (_settings.count(settingKeyword)) { if (cmd.splitCommand.size() > 2) { if (!_settings.at(settingKeyword).set(cmd, true)) { // If command failed and it was a GUI command if (cmd.cmdSource == tCommandSource::GUI) { //if (globals::guiSignallerPtr) { // globals::guiSignallerPtr->sig_settingFailure(cmd); //} signalSettingFailurePtr(cmd); //else { // throwl("GUI updater pointer missing."); // If it was a GUI command but you don't have a GUI updater pointer // // something went horribly wrong //} } } } else { if (cmd.cmdSource == tCommandSource::GUI) throwl("GUI should not be asking to output settings to console"); // GUI should not need to ask for settings to display _settings.at(cmd.splitCommand.at(1)).set(cmd, false); } } else { if (cmd.cmdSource == tCommandSource::GUI) { //if (globals::guiSignallerPtr) { // globals::guiSignallerPtr->sig_settingFailure(cmd); //} //else { // throw; // If it was a GUI command but you don't have a GUI updater pointer // // something went horribly wrong //} signalSettingFailurePtr(cmd); } else { std::cerr << "Invalid setting." << std::endl; } } }
31.876033
164
0.727854
[ "vector" ]
0407ed5f59bd261e2b2700e13787e88ded816467
24,308
cpp
C++
src/CreateDatabaseDialog.cpp
metiscus/tarrasch-chess-gui
5bb37ad1279aa107f927a4e783f89624d89c74a7
[ "MIT" ]
null
null
null
src/CreateDatabaseDialog.cpp
metiscus/tarrasch-chess-gui
5bb37ad1279aa107f927a4e783f89624d89c74a7
[ "MIT" ]
null
null
null
src/CreateDatabaseDialog.cpp
metiscus/tarrasch-chess-gui
5bb37ad1279aa107f927a4e783f89624d89c74a7
[ "MIT" ]
null
null
null
/**************************************************************************** * Custom dialog - Maintenance Dialog * Author: Bill Forster * License: MIT license. Full text of license is in associated file LICENSE * Copyright 2010-2014, Bill Forster <billforsternz at gmail dot com> ****************************************************************************/ #include "wx/wx.h" #include "wx/valtext.h" #include "wx/valgen.h" #include "wx/file.h" #include "wx/filename.h" #include "wx/filepicker.h" #include "DebugPrintf.h" #include "Portability.h" #include "Appdefs.h" #include "Repository.h" #include "PgnRead.h" #include "ProgressBar.h" #include "DbMaintenance.h" #include "DbPrimitives.h" #include "PackedGameBinDb.h" #include "BinDb.h" #include "CreateDatabaseDialog.h" // CreateDatabaseDialog type definition IMPLEMENT_CLASS( CreateDatabaseDialog, wxDialog ) // CreateDatabaseDialog event table definition BEGIN_EVENT_TABLE( CreateDatabaseDialog, wxDialog ) EVT_BUTTON( wxID_OK, CreateDatabaseDialog::OnOk ) EVT_BUTTON( wxID_HELP, CreateDatabaseDialog::OnHelpClick ) EVT_FILEPICKER_CHANGED( ID_CREATE_DB_PICKER_DB, CreateDatabaseDialog::OnDbFilePicked ) EVT_FILEPICKER_CHANGED( ID_CREATE_DB_PICKER1, CreateDatabaseDialog::OnPgnFile1Picked ) EVT_FILEPICKER_CHANGED( ID_CREATE_DB_PICKER2, CreateDatabaseDialog::OnPgnFile2Picked ) EVT_FILEPICKER_CHANGED( ID_CREATE_DB_PICKER3, CreateDatabaseDialog::OnPgnFile3Picked ) END_EVENT_TABLE() CreateDatabaseDialog::CreateDatabaseDialog( wxWindow* parent, wxWindowID id, bool create_mode, const wxPoint& pos, const wxSize& size, long style ) { db_created_ok = false; this->create_mode = create_mode; Create(parent, id, create_mode?"Create Database":"Add Games to Database", pos, size, style); } // Dialog create bool CreateDatabaseDialog::Create( wxWindow* parent, wxWindowID id, const wxString& caption, const wxPoint& pos, const wxSize& size, long style ) { bool okay=true; // We have to set extra styles before creating the dialog SetExtraStyle( wxWS_EX_BLOCK_EVENTS/*|wxDIALOG_EX_CONTEXTHELP*/ ); if( !wxDialog::Create( parent, id, caption, pos, size, style ) ) okay = false; else { CreateControls(); SetDialogHelp(); SetDialogValidators(); // This fits the dialog to the minimum size dictated by the sizers GetSizer()->Fit(this); // This ensures that the dialog cannot be sized smaller than the minimum size GetSizer()->SetSizeHints(this); // Centre the dialog on the parent or (if none) screen Centre(); } return okay; } // Control creation for CreateDatabaseDialog void CreateDatabaseDialog::CreateControls() { // A top-level sizer wxBoxSizer* top_sizer = new wxBoxSizer(wxVERTICAL); this->SetSizer(top_sizer); // A second box sizer to give more space around the controls wxBoxSizer* box_sizer = new wxBoxSizer(wxVERTICAL); top_sizer->Add(box_sizer, 0, wxALIGN_CENTER_HORIZONTAL|wxALL, 5); // A friendly message wxStaticText* descr = new wxStaticText( this, wxID_STATIC, create_mode? "To create a new database from scratch, name the new database and select\n" "one or more .pgn files with the games to go into the database.\n" : "To add games to an existing database, select the database and one or\n" "more .pgn files with the additional games to go into the database.\n" , wxDefaultPosition, wxDefaultSize, 0 ); box_sizer->Add(descr, 0, wxALIGN_LEFT|wxALL, 5); // Spacer box_sizer->Add(5, 5, 0, wxALIGN_CENTER_HORIZONTAL|wxALL, 5); // Label for file wxStaticText* db_file_label = new wxStaticText ( this, wxID_STATIC, create_mode ? wxT("&Name a new database file") : wxT("&Choose an existing database file"), wxDefaultPosition, wxDefaultSize, 0 ); box_sizer->Add(db_file_label, 0, wxALIGN_LEFT|wxALL, 5); // File picker controls wxFilePickerCtrl *picker_db = new wxFilePickerCtrl( this, ID_CREATE_DB_PICKER_DB, db_filename, create_mode ? wxT("Locate and name a database to create") : wxT("Select database to add games to"), "*.tdb", wxDefaultPosition, wxDefaultSize, create_mode ? wxFLP_USE_TEXTCTRL|wxFLP_SAVE : wxFLP_USE_TEXTCTRL|wxFLP_FILE_MUST_EXIST ); box_sizer->Add(picker_db, 1, wxALIGN_LEFT|wxEXPAND|wxLEFT|wxBOTTOM|wxRIGHT, 5); // Label for file wxStaticText* pgn_file_label = new wxStaticText ( this, wxID_STATIC, wxT("&Select one or more .pgn files to add to the database"), wxDefaultPosition, wxDefaultSize, 0 ); box_sizer->Add(pgn_file_label, 0, wxALIGN_LEFT|wxALL, 5); wxFilePickerCtrl *picker1 = new wxFilePickerCtrl( this, ID_CREATE_DB_PICKER1, pgn_filename1, wxT("Select 1st .pgn"), "*.pgn", wxDefaultPosition, wxDefaultSize, wxFLP_USE_TEXTCTRL|wxFLP_OPEN|wxFLP_FILE_MUST_EXIST ); //|wxFLP_CHANGE_DIR ); box_sizer->Add(picker1, 1, wxALIGN_LEFT|wxEXPAND|wxLEFT|wxBOTTOM|wxRIGHT, 5); wxFilePickerCtrl *picker2 = new wxFilePickerCtrl( this, ID_CREATE_DB_PICKER2, pgn_filename2, wxT("Select 2nd .pgn"), "*.pgn", wxDefaultPosition, wxDefaultSize, wxFLP_USE_TEXTCTRL|wxFLP_OPEN|wxFLP_FILE_MUST_EXIST ); //|wxFLP_CHANGE_DIR ); box_sizer->Add(picker2, 1, wxALIGN_LEFT|wxEXPAND|wxLEFT|wxBOTTOM|wxRIGHT, 5); if( create_mode ) { wxFilePickerCtrl *picker3 = new wxFilePickerCtrl( this, ID_CREATE_DB_PICKER3, pgn_filename3, wxT("Select next .pgn"), "*.pgn", wxDefaultPosition, wxDefaultSize, wxFLP_USE_TEXTCTRL|wxFLP_OPEN|wxFLP_FILE_MUST_EXIST ); //|wxFLP_CHANGE_DIR ); box_sizer->Add(picker3, 1, wxALIGN_LEFT|wxEXPAND|wxLEFT|wxBOTTOM|wxRIGHT, 5); wxFilePickerCtrl *picker4 = new wxFilePickerCtrl( this, ID_CREATE_DB_PICKER4, pgn_filename4, wxT("Select next .pgn"), "*.pgn", wxDefaultPosition, wxDefaultSize, wxFLP_USE_TEXTCTRL|wxFLP_OPEN|wxFLP_FILE_MUST_EXIST ); //|wxFLP_CHANGE_DIR ); box_sizer->Add(picker4, 1, wxALIGN_LEFT|wxEXPAND|wxLEFT|wxBOTTOM|wxRIGHT, 5); wxFilePickerCtrl *picker5 = new wxFilePickerCtrl( this, ID_CREATE_DB_PICKER5, pgn_filename5, wxT("Select next .pgn"), "*.pgn", wxDefaultPosition, wxDefaultSize, wxFLP_USE_TEXTCTRL|wxFLP_OPEN|wxFLP_FILE_MUST_EXIST ); //|wxFLP_CHANGE_DIR ); box_sizer->Add(picker5, 1, wxALIGN_LEFT|wxEXPAND|wxLEFT|wxBOTTOM|wxRIGHT, 5); wxFilePickerCtrl *picker6 = new wxFilePickerCtrl( this, ID_CREATE_DB_PICKER6, pgn_filename6, wxT("Select next .pgn"), "*.pgn", wxDefaultPosition, wxDefaultSize, wxFLP_USE_TEXTCTRL|wxFLP_OPEN|wxFLP_FILE_MUST_EXIST ); //|wxFLP_CHANGE_DIR ); box_sizer->Add(picker6, 1, wxALIGN_LEFT|wxEXPAND|wxLEFT|wxBOTTOM|wxRIGHT, 5); } wxBoxSizer* h1 = new wxBoxSizer(wxHORIZONTAL); wxBoxSizer* v1 = new wxBoxSizer(wxVERTICAL); wxBoxSizer* v2 = new wxBoxSizer(wxVERTICAL); wxBoxSizer* v3 = new wxBoxSizer(wxVERTICAL); wxBoxSizer* v4 = new wxBoxSizer(wxVERTICAL); // Label for elo cutoff wxStaticText* elo_cutoff_label = new wxStaticText ( this, wxID_STATIC, "Elo cutoff", wxDefaultPosition, wxDefaultSize, 0 ); v1->Add(elo_cutoff_label, 0, wxALL, 5); // A spin control for the elo cutoff elo_cutoff_spin = new wxSpinCtrl ( this, ID_CREATE_ELO_CUTOFF, wxEmptyString, wxDefaultPosition, wxSize(60, -1), wxSP_ARROW_KEYS, 0, 4000, 2000 ); elo_cutoff_spin->SetValue( objs.repository->database.m_elo_cutoff ); v1->Add(elo_cutoff_spin, 0, wxALL, 5); // Radio options ignore = new wxRadioButton( this, wxID_ANY, "Ignore Elo cutoff", wxDefaultPosition, wxDefaultSize, wxRB_GROUP ); ignore->SetValue( objs.repository->database.m_elo_cutoff_ignore ); at_least_one = new wxRadioButton( this, wxID_ANY, "At least one player", wxDefaultPosition, wxDefaultSize, 0 ); at_least_one->SetValue( objs.repository->database.m_elo_cutoff_one ); both = new wxRadioButton( this, wxID_ANY, "Both players", wxDefaultPosition, wxDefaultSize, 0 ); both->SetValue( objs.repository->database.m_elo_cutoff_both ); // Unrated players fail = new wxRadioButton( this, wxID_ANY, "Unrated players fail Elo cutoff", wxDefaultPosition, wxDefaultSize, wxRB_GROUP ); fail->SetValue( objs.repository->database.m_elo_cutoff_fail ); pass = new wxRadioButton( this, wxID_ANY, "Unrated players pass Elo cutoff", wxDefaultPosition, wxDefaultSize, 0 ); pass->SetValue( objs.repository->database.m_elo_cutoff_pass ); pass_before = new wxRadioButton( this, wxID_ANY, "Unrated pass if game played before", wxDefaultPosition, wxDefaultSize, 0 ); pass_before->SetValue( objs.repository->database.m_elo_cutoff_pass_before ); wxStaticText* spacer1 = new wxStaticText ( this, wxID_ANY, " ", wxDefaultPosition, wxDefaultSize, 0 ); wxStaticText* spacer2 = new wxStaticText ( this, wxID_ANY, " ", wxDefaultPosition, wxDefaultSize, 0 ); before_year = new wxSpinCtrl ( this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxSize(60, -1), wxSP_ARROW_KEYS, 1400, 2500, 1990 ); before_year->SetValue( objs.repository->database.m_elo_cutoff_before_year ); v2->Add(ignore, 0, wxALL, 5); v2->Add(at_least_one, 0, wxALL, 5); v2->Add(both, 0, wxALL, 5); v3->Add(fail, 0, wxALL, 5); v3->Add(pass, 0, wxALL, 5); v3->Add(pass_before, 0, wxALL, 5); v4->Add(spacer1, 0, wxALL, 5); v4->Add(spacer2, 0, wxALL, 5); v4->Add(before_year, 0, wxALL, 0); h1->Add(v1, 0, wxGROW|wxALL, 5); h1->Add(v2, 0, wxGROW|wxALL, 5); h1->Add(v3, 0, wxGROW|wxALL, 5); h1->Add(v4, 0, wxGROW|wxALL, 5); box_sizer->Add(h1, 0, wxGROW|wxALL, 5); // A dividing line before the OK and Cancel buttons wxStaticLine* line2 = new wxStaticLine ( this, wxID_STATIC, wxDefaultPosition, wxDefaultSize, wxLI_HORIZONTAL ); box_sizer->Add(line2, 0, wxGROW|wxALL, 5); // A horizontal box sizer to contain Reset, OK, Cancel and Help wxBoxSizer* okCancelBox = new wxBoxSizer(wxHORIZONTAL); box_sizer->Add(okCancelBox, 0, wxALIGN_CENTER_HORIZONTAL|wxALL, 15); // The OK button wxButton* ok = new wxButton ( this, wxID_OK, wxT("&OK"), wxDefaultPosition, wxDefaultSize, 0 ); okCancelBox->Add(ok, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5); // The Cancel button wxButton* cancel = new wxButton ( this, wxID_CANCEL, wxT("&Cancel"), wxDefaultPosition, wxDefaultSize, 0 ); okCancelBox->Add(cancel, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5); // The Help button wxButton* help = new wxButton( this, wxID_HELP, wxT("&Help"), wxDefaultPosition, wxDefaultSize, 0 ); okCancelBox->Add(help, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5); } // Set the validators for the dialog controls void CreateDatabaseDialog::SetDialogValidators() { } // Sets the help text for the dialog controls void CreateDatabaseDialog::SetDialogHelp() { } // wxID_OK handler void CreateDatabaseDialog::OnOk( wxCommandEvent& WXUNUSED(event) ) { objs.repository->database.m_elo_cutoff = elo_cutoff_spin->GetValue(); objs.repository->database.m_elo_cutoff_ignore = ignore->GetValue(); objs.repository->database.m_elo_cutoff_one = at_least_one->GetValue(); objs.repository->database.m_elo_cutoff_both = both->GetValue(); objs.repository->database.m_elo_cutoff_fail = fail->GetValue(); objs.repository->database.m_elo_cutoff_pass = pass->GetValue(); objs.repository->database.m_elo_cutoff_pass_before = pass_before->GetValue(); objs.repository->database.m_elo_cutoff_before_year = before_year->GetValue(); if( create_mode ) OnCreateDatabase(); else OnAppendDatabase(); } // Create void CreateDatabaseDialog::OnCreateDatabase() { bool ok=true; bool created_new_db_file = false; std::string files[6]; int cnt=0; std::string error_msg; db_primitive_error_msg(); // clear error reporting mechanism // Collect files for( int i=1; i<=6; i++ ) { bool exists = false; std::string filename; switch(i) { case 1: exists = wxFile::Exists(pgn_filename1); filename = std::string(pgn_filename1.c_str()); break; case 2: exists = wxFile::Exists(pgn_filename2); filename = std::string(pgn_filename2.c_str()); break; case 3: exists = wxFile::Exists(pgn_filename3); filename = std::string(pgn_filename3.c_str()); break; case 4: exists = wxFile::Exists(pgn_filename4); filename = std::string(pgn_filename4.c_str()); break; case 5: exists = wxFile::Exists(pgn_filename5); filename = std::string(pgn_filename5.c_str()); break; case 6: exists = wxFile::Exists(pgn_filename6); filename = std::string(pgn_filename6.c_str()); break; } if( exists ) { files[cnt++] = filename; } } bool exists = wxFile::Exists(db_filename); db_name = std::string( db_filename.c_str() ); if( exists ) { error_msg = "Tarrasch database file " + db_name + " already exists"; ok = false; } else if( db_name.length() == 0 ) { error_msg = "No Tarrasch database file specified"; ok = false; } else if( cnt == 0 ) { error_msg = "No usable pgn files specified"; ok = false; } // TODO DatabaseClear(); FILE *ofile=NULL; if( ok ) { ok = false; BinDbReadBegin(); wxString fullpath = db_filename; wxFileName wfn(db_filename); if( wfn.IsOk() && wfn.HasName() ) { wxString cwd = wxGetCwd(); wfn.SetExt("tdb"); wxString path = wxPathOnly(db_filename); bool no_path = (path==""); if( no_path ) wfn.SetPath(cwd); fullpath = wfn.GetFullPath(); db_name = std::string( fullpath.c_str() ); ofile = fopen( fullpath.c_str(), "wb" ); if( ofile ) { created_new_db_file = true; ok = true; } } if( !ok ) { error_msg = "Cannot create "; error_msg += fullpath; } } for( int i=0; ok && i<cnt; i++ ) { FILE *ifile = fopen( files[i].c_str(), "rt" ); if( !ifile ) { error_msg = "Cannot open "; error_msg += files[i]; ok = false; } else { std::string title( "Creating database, step 1 of 4"); std::string desc("Reading file #"); char buf[80]; sprintf( buf, "%d of %d", i+1, cnt ); desc += buf; ProgressBar progress_bar( title, desc, true, this, ifile ); uint32_t begin = BinDbGetGamesSize(); PgnRead pgn('B',&progress_bar); bool aborted = pgn.Process(ifile); uint32_t end = BinDbGetGamesSize(); BinDbNormaliseOrder( begin, end ); if( aborted ) { error_msg = "cancel"; ok = false; } fclose(ifile); } } if( ok ) { std::string title( "Creating database"); // Step 2,3 and 4 of 4 int step=2; ok = BinDbRemoveDuplicatesAndWrite(title,step,ofile,this); } if( ofile ) { wxSafeYield(); fclose(ofile); ofile = NULL; } if( ok ) { wxSafeYield(); AcceptAndClose(); db_created_ok = true; } else { if( error_msg == "" ) error_msg = db_primitive_error_msg(); if( error_msg == "cancel" ) error_msg = "Database creation cancelled"; wxMessageBox( error_msg.c_str(), "Database creation failed", wxOK|wxICON_ERROR ); if( created_new_db_file ) #ifdef THC_UNIX unlink(db_filename.c_str()); #else _unlink(db_filename.c_str()); #endif } BinDbCreationEnd(); } void CreateDatabaseDialog::OnAppendDatabase() { bool ok=true; bool created_new_db_file = false; std::string files[6]; int cnt=0; std::string error_msg; db_primitive_error_msg(); // clear error reporting mechanism // Collect files for( int i=1; i<=6; i++ ) { bool exists = false; std::string filename; switch(i) { case 1: exists = wxFile::Exists(pgn_filename1); filename = std::string(pgn_filename1.c_str()); break; case 2: exists = wxFile::Exists(pgn_filename2); filename = std::string(pgn_filename2.c_str()); break; case 3: exists = wxFile::Exists(pgn_filename3); filename = std::string(pgn_filename3.c_str()); break; case 4: exists = wxFile::Exists(pgn_filename4); filename = std::string(pgn_filename4.c_str()); break; case 5: exists = wxFile::Exists(pgn_filename5); filename = std::string(pgn_filename5.c_str()); break; case 6: exists = wxFile::Exists(pgn_filename6); filename = std::string(pgn_filename6.c_str()); break; } if( exists ) { files[cnt++] = filename; } } if( cnt == 0 ) { error_msg = "No usable pgn files specified"; ok = false; } if( ok ) { bool exists = wxFile::Exists(db_filename); db_name = std::string( db_filename.c_str() ); if( !exists ) { error_msg = "Tarrasch database file " + db_name + " doesn't exist"; ok = false; } } if( ok ) { ok = BinDbOpen( db_filename.c_str(), error_msg ); } if( ok ) { bool dummyb=false; int dummyi=false; std::string title( "Appending to database, step 1 of 5"); std::string desc("Reading existing database"); ProgressBar progress_bar( title, desc, true, this ); std::vector< smart_ptr<ListableGame> > &mega_cache = BinDbLoadAllGamesGetVector(); cprintf( "Appending to database, step 1 of 5 begin\n" ); bool killed = BinDbLoadAllGames( true, mega_cache, dummyi, dummyb, &progress_bar ); cprintf( "Appending to database, step 1 of 5 end, killed=%s\n", killed?"true":"false" ); if( killed ) ok=false; BinDbClose(); } FILE *ofile=NULL; if( ok ) { ofile = fopen( db_name.c_str(), "wb" ); if( ofile ) created_new_db_file = true; else { error_msg = "Cannot open "; error_msg += db_name; ok = false; } } for( int i=0; ok && i<cnt; i++ ) { FILE *ifile = fopen( files[i].c_str(), "rt" ); if( !ifile ) { error_msg = "Cannot open "; error_msg += files[i]; ok = false; } else { std::string title2( "Appending to database, step 2 of 5"); std::string desc2("Reading file #"); char buf[80]; sprintf( buf, "%d of %d", i+1, cnt ); desc2 += buf; ProgressBar progress_bar2( title2, desc2, true, this, ifile ); uint32_t begin = BinDbGetGamesSize(); PgnRead pgn('B',&progress_bar2); bool aborted = pgn.Process(ifile); uint32_t end = BinDbGetGamesSize(); BinDbNormaliseOrder( begin, end ); if( aborted ) { error_msg = "cancel"; ok = false; } fclose(ifile); } } if( ok ) { std::string title3( "Appending to database"); // Step 3,4 and 5 of 5 int step=3; ok = BinDbRemoveDuplicatesAndWrite(title3,step,ofile,this); } if( ofile ) { fclose(ofile); ofile = NULL; } if( ok ) { wxSafeYield(); AcceptAndClose(); db_created_ok = true; } else { if( error_msg == "" ) error_msg = db_primitive_error_msg(); if( error_msg == "cancel" ) error_msg = "Database creation cancelled"; wxMessageBox( error_msg.c_str(), "Database creation failed", wxOK|wxICON_ERROR ); if( created_new_db_file ) #ifdef THC_UNIX unlink(db_filename.c_str()); #else _unlink(db_filename.c_str()); #endif } BinDbCreationEnd(); } void CreateDatabaseDialog::OnDbFilePicked( wxFileDirPickerEvent& event ) { wxString file = event.GetPath(); db_filename = file; } void CreateDatabaseDialog::OnPgnFile1Picked( wxFileDirPickerEvent& event ) { wxString file = event.GetPath(); pgn_filename1 = file; } void CreateDatabaseDialog::OnPgnFile2Picked( wxFileDirPickerEvent& event ) { wxString file = event.GetPath(); pgn_filename2 = file; } void CreateDatabaseDialog::OnPgnFile3Picked( wxFileDirPickerEvent& event ) { wxString file = event.GetPath(); pgn_filename3 = file; } void CreateDatabaseDialog::OnHelpClick( wxCommandEvent& WXUNUSED(event) ) { // Normally we would wish to display proper online help. // For this example, we're just using a message box. /* wxGetApp().GetHelpController().DisplaySection(wxT("Personal record dialog")); */ wxString helpText = wxT("\nTarrasch database files (.tdb files) are compact game collections. ") wxT("At the moment only complete games are supported (i.e. no game fragments). ") wxT("Similarly no comments or variations are supported at this time. ") wxT("Tarrasch uses one database file at a time (the current database). ") wxT("Tarrasch can search the current database quickly and efficiently ") wxT("for any position or for piece patterns or material balances. ") wxT("Tarrasch databases are created from .pgn files.") wxT("\n\n") wxT("The only way Tarrasch databases can be modified (at this time) is by ") wxT("appending more games to them with the Append to database command. ") wxT("Tarrasch automatically rejects duplicate games and games played by ") wxT("players with insufficiently high Elo ratings. ") wxT("Rejected duplicate games are saved in file TarraschDbDuplicatesFile.pgn. ") wxT("Games can be rejected based on ") wxT("rating if desired. ") wxT("For best results, create databases with older .pgn files first, and ") wxT("append newer games as you collect them. ") wxT("Tarrasch will try to present most recent games first." ); wxMessageBox(helpText, wxT("Create database / Append to database help"), wxOK|wxICON_INFORMATION, this); }
38.645469
149
0.592809
[ "vector" ]
04081354384266360047f3ed99874b2acbfaffec
8,518
cpp
C++
Engine/Code/Engine/RHI/RHIOutput.cpp
cugone/Abrams2022
54efe5fdd7d2d9697f005ee45a171ecea68d0df8
[ "MIT" ]
null
null
null
Engine/Code/Engine/RHI/RHIOutput.cpp
cugone/Abrams2022
54efe5fdd7d2d9697f005ee45a171ecea68d0df8
[ "MIT" ]
20
2021-11-29T14:09:33.000Z
2022-03-26T20:12:44.000Z
Engine/Code/Engine/RHI/RHIOutput.cpp
cugone/Abrams2022
54efe5fdd7d2d9697f005ee45a171ecea68d0df8
[ "MIT" ]
null
null
null
#include "Engine/RHI/RHIOutput.hpp" #include "Engine/Core/BuildConfig.hpp" #include "Engine/Core/ErrorWarningAssert.hpp" #include "Engine/Core/Rgba.hpp" #include "Engine/Core/StringUtils.hpp" #include "Engine/Math/IntVector2.hpp" #include "Engine/RHI/RHIDevice.hpp" #include "Engine/RHI/RHIDeviceContext.hpp" #include "Engine/Renderer/DirectX/DX11.hpp" #include "Engine/Renderer/Renderer.hpp" #include "Engine/Renderer/Texture.hpp" #include "Engine/Renderer/Texture2D.hpp" #include "Engine/Renderer/Window.hpp" #include <sstream> RHIOutput::RHIOutput(const RHIDevice& parent, std::unique_ptr<Window> wnd) noexcept : m_parent_device(parent) , m_window(std::move(wnd)) { SetDisplayMode(m_window->GetDisplayMode()); CreateBuffers(); } const RHIDevice& RHIOutput::GetParentDevice() const noexcept { return m_parent_device; } const Window* RHIOutput::GetWindow() const noexcept { return m_window.get(); } Window* RHIOutput::GetWindow() noexcept { return m_window.get(); } Texture* RHIOutput::GetBackBuffer() const noexcept { return m_back_buffer.get(); } Texture* RHIOutput::GetDepthStencil() const noexcept { return m_depthstencil.get(); } IntVector2 RHIOutput::GetDimensions() const noexcept { if(m_window) { return m_window->GetClientDimensions(); } else { return IntVector2::Zero; } } IntVector2 RHIOutput::GetCenter() const noexcept { const auto dims = GetDimensions(); return dims / 2.0f; } float RHIOutput::GetAspectRatio() const noexcept { if(m_window) { const auto& dims = GetDimensions(); if(dims.y < dims.x) { return dims.x / static_cast<float>(dims.y); } else { return dims.y / static_cast<float>(dims.x); } } return 0.0f; } void RHIOutput::SetDisplayMode(const RHIOutputMode& newMode) noexcept { m_window->SetDisplayMode(newMode); } void RHIOutput::SetDimensions(const IntVector2& clientSize) noexcept { m_window->SetDimensions(clientSize); } void RHIOutput::Present(bool vsync) noexcept { DXGI_PRESENT_PARAMETERS present_params{}; present_params.DirtyRectsCount = 0; present_params.pDirtyRects = nullptr; present_params.pScrollOffset = nullptr; present_params.pScrollRect = nullptr; const auto should_tear = m_parent_device.IsAllowTearingSupported(); const auto is_vsync_off = !vsync; const auto use_no_sync_interval = should_tear && is_vsync_off; const auto sync_interval = use_no_sync_interval ? 0u : 1u; const auto present_flags = use_no_sync_interval ? DXGI_PRESENT_ALLOW_TEARING : 0ul; if(const auto hr_present = m_parent_device.GetDxSwapChain()->Present1(sync_interval, present_flags, &present_params); FAILED(hr_present)) { switch(hr_present) { case DXGI_ERROR_DEVICE_REMOVED: /** FALLTHROUGH **/ case DXGI_ERROR_DEVICE_RESET: { m_parent_device.HandleDeviceLost(); const auto hr_removed_reset = m_parent_device.GetDxDevice()->GetDeviceRemovedReason(); const auto err_str = std::string{"Your GPU device has been lost. Please restart the application. The returned error message follows:\n"} + StringUtils::FormatWindowsMessage(hr_removed_reset); ERROR_AND_DIE(err_str.c_str()); break; } default: #ifdef RENDER_DEBUG const auto err_str = std::string{"Present call failed: "} + StringUtils::FormatWindowsMessage(hr_present); this->GetWindow()->Hide(); GUARANTEE_OR_DIE(SUCCEEDED(hr_present), err_str.c_str()); #else this->GetWindow()->Hide(); GUARANTEE_OR_DIE(SUCCEEDED(hr_present), "Present call failed."); #endif break; } } } void RHIOutput::CreateBuffers() noexcept { m_back_buffer = CreateBackbuffer(); m_back_buffer->SetDebugName("__back_buffer"); m_depthstencil = CreateDepthStencil(); m_depthstencil->SetDebugName("__default_depthstencil"); } std::unique_ptr<Texture> RHIOutput::CreateBackbuffer() noexcept { Microsoft::WRL::ComPtr<ID3D11Texture2D> back_buffer{}; m_parent_device.GetDxSwapChain()->GetBuffer(0, __uuidof(ID3D11Texture2D), static_cast<void**>(&back_buffer)); return std::make_unique<Texture2D>(m_parent_device, back_buffer); } std::unique_ptr<Texture> RHIOutput::CreateDepthStencil() noexcept { Microsoft::WRL::ComPtr<ID3D11Texture2D> depthstencil{}; D3D11_TEXTURE2D_DESC descDepth{}; const IntVector3& dims = GetBackBuffer()->GetDimensions(); const auto width = dims.x; const auto height = dims.y; descDepth.Width = width; descDepth.Height = height; descDepth.MipLevels = 1; descDepth.ArraySize = 1; descDepth.Format = ImageFormatToDxgiFormat(ImageFormat::D24_UNorm_S8_UInt); descDepth.SampleDesc.Count = 1; descDepth.SampleDesc.Quality = 0; descDepth.Usage = BufferUsageToD3DUsage(BufferUsage::Default); descDepth.BindFlags = BufferBindUsageToD3DBindFlags(BufferBindUsage::Depth_Stencil); descDepth.CPUAccessFlags = 0; descDepth.MiscFlags = 0; auto hr_texture = m_parent_device.GetDxDevice()->CreateTexture2D(&descDepth, nullptr, &depthstencil); { const auto error_msg = [&]() { std::string msg{"Fatal Error: Failed to create depthstencil for window. Reason:\n"}; msg += StringUtils::FormatWindowsMessage(hr_texture); return msg; }(); //IIIL GUARANTEE_OR_DIE(SUCCEEDED(hr_texture), error_msg.c_str()); } return std::make_unique<Texture2D>(m_parent_device, depthstencil); } std::unique_ptr<Texture> RHIOutput::CreateFullscreenTexture() noexcept { D3D11_TEXTURE2D_DESC tex_desc{}; const IntVector3& dims = GetBackBuffer()->GetDimensions(); const auto width = dims.x; const auto height = dims.y; tex_desc.Width = width; tex_desc.Height = height; tex_desc.MipLevels = 1; tex_desc.ArraySize = 1; const auto bufferUsage = BufferUsage::Gpu; const auto imageFormat = ImageFormat::R8G8B8A8_UNorm; tex_desc.Usage = BufferUsageToD3DUsage(bufferUsage); tex_desc.Format = ImageFormatToDxgiFormat(imageFormat); const auto bindUsage = BufferBindUsage::Render_Target | BufferBindUsage::Shader_Resource; tex_desc.BindFlags = BufferBindUsageToD3DBindFlags(bindUsage); //Make every texture a target and shader resource tex_desc.BindFlags |= BufferBindUsageToD3DBindFlags(BufferBindUsage::Shader_Resource); tex_desc.CPUAccessFlags = CPUAccessFlagFromUsage(bufferUsage); //Force specific usages for unordered access if((bindUsage & BufferBindUsage::Unordered_Access) == BufferBindUsage::Unordered_Access) { tex_desc.Usage = BufferUsageToD3DUsage(BufferUsage::Gpu); tex_desc.CPUAccessFlags = CPUAccessFlagFromUsage(BufferUsage::Staging); } if((bufferUsage & BufferUsage::Staging) == BufferUsage::Staging) { tex_desc.BindFlags = 0; } tex_desc.MiscFlags = 0; tex_desc.SampleDesc.Count = 1; tex_desc.SampleDesc.Quality = 0; // Setup Initial Data D3D11_SUBRESOURCE_DATA subresource_data{}; auto data = std::vector<Rgba>(static_cast<std::size_t>(dims.x) * static_cast<std::size_t>(dims.y), Rgba::Magenta); subresource_data.pSysMem = data.data(); subresource_data.SysMemPitch = width * sizeof(Rgba); subresource_data.SysMemSlicePitch = width * height * sizeof(Rgba); Microsoft::WRL::ComPtr<ID3D11Texture2D> dx_tex{}; //If IMMUTABLE or not multi-sampled, must use initial data. const auto isMultiSampled = tex_desc.SampleDesc.Count != 1 || tex_desc.SampleDesc.Quality != 0; const auto isImmutable = bufferUsage == BufferUsage::Static; const auto mustUseInitialData = isImmutable || isMultiSampled; auto hr = m_parent_device.GetDxDevice()->CreateTexture2D(&tex_desc, (mustUseInitialData ? &subresource_data : nullptr), &dx_tex); { const auto error_msg = [&]() { std::string msg{"Fatal Error: Failed to create fullscreen texture. Reason:\n"}; msg += StringUtils::FormatWindowsMessage(hr); return msg; }(); //IIIL GUARANTEE_OR_DIE(SUCCEEDED(hr), error_msg.c_str()); } return std::make_unique<Texture2D>(m_parent_device, dx_tex); } void RHIOutput::SetTitle(const std::string& newTitle) const noexcept { m_window->SetTitle(newTitle); } void RHIOutput::ResetBackbuffer() noexcept { m_back_buffer.reset(); m_depthstencil.reset(); m_parent_device.ResetSwapChainForHWnd(); CreateBuffers(); }
37.857778
203
0.711787
[ "vector" ]
040c0be4413e5cd49ec42f59029e94b9c3ff6b9f
7,640
cpp
C++
common/stack/stackObject.cpp
doctorsrn/manipulator_torque_controller
c276afe950448ecd03867498524f94b251f5238d
[ "MIT" ]
11
2020-01-12T19:50:43.000Z
2022-01-27T20:15:24.000Z
common/stack/stackObject.cpp
doctorsrn/manipulator_torque_controller
c276afe950448ecd03867498524f94b251f5238d
[ "MIT" ]
2
2022-01-23T06:46:27.000Z
2022-02-21T06:17:01.000Z
coppeliaSim-client/common/stack/stackObject.cpp
mhsitu/welding_robot
03a1a5f83049311777f948715d7bf5399dc2dbbb
[ "MIT" ]
2
2021-12-23T00:30:10.000Z
2021-12-31T06:24:27.000Z
#include "stackObject.h" #include "stackNull.h" #include "stackNumber.h" #include "stackBool.h" #include "stackString.h" #include "stackArray.h" #include "stackMap.h" CStackObject::CStackObject() { } CStackObject::~CStackObject() { } int CStackObject::getObjectType() const { return(_objectType); } CStackObject* CStackObject::copyYourself() { return(NULL); } void CStackObject::buildItemOntoStack(int stackId,CStackObject* obj) { if (obj->getObjectType()==STACK_NULL) simPushNullOntoStack(stackId); // NULL else if (obj->getObjectType()==STACK_BOOL) simPushBoolOntoStack(stackId,((CStackBool*)obj)->getValue()); // Bool else if (obj->getObjectType()==STACK_NUMBER) simPushDoubleOntoStack(stackId,((CStackNumber*)obj)->getValue()); // number else if (obj->getObjectType()==STACK_STRING) { // string std::string str(((CStackString*)obj)->getValue()); simPushStringOntoStack(stackId,str.c_str(),int(str.length())); } else if (obj->getObjectType()==STACK_ARRAY) { CStackArray* arr=(CStackArray*)obj; if (arr->getSize()==0) simPushTableOntoStack(stackId); // empty array else if (arr->getSize()>0) { if (arr->isNumberArray()) simPushDoubleTableOntoStack(stackId,&arr->getDoubles()->at(0),int(arr->getDoubles()->size())); // number array else { // mixed array simPushTableOntoStack(stackId); const std::vector<CStackObject*>* objs=arr->getObjects(); for (size_t i=0;i<objs->size();i++) { simPushInt32OntoStack(stackId,int(i+1)); // the key CStackObject::buildItemOntoStack(stackId,objs->at(i)); // the value simInsertDataIntoStackTable(stackId); } } } } else if (obj->getObjectType()==STACK_MAP) { CStackMap* map=(CStackMap*)obj; std::map<std::string,CStackObject*>* keyValues=map->getKeyValuePairs(); simPushTableOntoStack(stackId); for (std::map<std::string,CStackObject*>::iterator it=keyValues->begin();it!=keyValues->end();it++) { simPushStringOntoStack(stackId,it->first.c_str(),0); // the key CStackObject::buildItemOntoStack(stackId,it->second); // the value simInsertDataIntoStackTable(stackId); } } } CStackObject* CStackObject::buildItemFromTopStackPosition(int stackId) { // this also clears the item from the stack CStackObject* retVal=NULL; simBool bv; double dv; if (1==simIsStackValueNull(stackId)) { // NULL retVal=new CStackNull(); simPopStackItem(stackId,1); } else if (1==simGetStackBoolValue(stackId,&bv)) { // bool retVal=new CStackBool(bv!=0); simPopStackItem(stackId,1); } else if (1==simGetStackDoubleValue(stackId,&dv)) { // number retVal=new CStackNumber(dv); simPopStackItem(stackId,1); } else { int sl; char* str=simGetStackStringValue(stackId,&sl); if (str!=NULL) { // string retVal=new CStackString(str,sl); simReleaseBuffer(str); simPopStackItem(stackId,1); } else { // the item is not a NULL, bool, number or string. So it must be an array or a map: int s=simGetStackTableInfo(stackId,0); if (s==sim_stack_table_circular_ref) { // A map/array in a circular reference CStackArray* arr=new CStackArray(); arr->setCircularRef(); retVal=arr; simPopStackItem(stackId,1); } else if (s==sim_stack_table_empty) { // Empty Array retVal=new CStackArray(); simPopStackItem(stackId,1); } else if (s>0) { // Array if (1==simGetStackTableInfo(stackId,2)) { // Array of numbers: CStackArray* arr=new CStackArray(); std::vector<double> numbers; numbers.resize(s); simGetStackDoubleTable(stackId,&numbers[0],s); arr->setDoubleArray(&numbers[0],s); retVal=arr; simPopStackItem(stackId,1); } else { // Array of items that are not all numbers CStackArray* arr=new CStackArray(); int oi=simGetStackSize(stackId)-1; simUnfoldStackTable(stackId); // This puts value-key pairs onto the stack s=(simGetStackSize(stackId)-oi)/2; for (int i=0;i<s;i++) { simMoveStackItemToTop(stackId,oi); // that's the key simPopStackItem(stackId,1); simMoveStackItemToTop(stackId,oi); // that's the value arr->appendTopStackItem(stackId); // will also pop it } retVal=arr; } } else if (s==sim_stack_table_map) { // Map CStackMap* map=new CStackMap(); int oi=simGetStackSize(stackId)-1; simUnfoldStackTable(stackId); // This puts value-key pairs onto the stack s=(simGetStackSize(stackId)-oi)/2; for (int i=0;i<s;i++) { simMoveStackItemToTop(stackId,oi); // that's the key char* str=simGetStackStringValue(stackId,NULL); bool isbool=simGetStackBoolValue(stackId,&bv)==1; bool isnum=simGetStackDoubleValue(stackId,&dv)==1; simPopStackItem(stackId,1); simMoveStackItemToTop(stackId,oi); // that's the value if(isnum) map->appendTopStackItem(int(dv),stackId); // will also pop it else if(isbool) map->appendTopStackItem(bv,stackId); // will also pop it else map->appendTopStackItem(str,stackId); // will also pop it if(str) simReleaseBuffer(str); } retVal=map; } } } return(retVal); } CStackNull* CStackObject::asNull() { if(_objectType==STACK_NULL) return(static_cast<CStackNull*>(this)); else return(NULL); } CStackNumber* CStackObject::asNumber() { if(_objectType==STACK_NUMBER) return(static_cast<CStackNumber*>(this)); else return(NULL); } CStackBool* CStackObject::asBool() { if(_objectType==STACK_BOOL) return(static_cast<CStackBool*>(this)); else return(NULL); } CStackString* CStackObject::asString() { if(_objectType==STACK_STRING) return(static_cast<CStackString*>(this)); else return(NULL); } CStackArray* CStackObject::asArray() { if(_objectType==STACK_ARRAY) return(static_cast<CStackArray*>(this)); else return(NULL); } CStackMap* CStackObject::asMap() { if(_objectType==STACK_MAP) return(static_cast<CStackMap*>(this)); else return(NULL); } std::string CStackObject::getObjectTypeString() const { switch(_objectType) { case STACK_NULL: return "null"; case STACK_NUMBER: return "number"; case STACK_BOOL: return "bool"; case STACK_STRING: return "string"; case STACK_ARRAY: return "array"; case STACK_MAP: return "map"; default: return "object"; } }
33.508772
125
0.564136
[ "object", "vector" ]
0412a84d814e40b9823170243e1691835dab3b37
4,857
cpp
C++
ref-impl/src/impl/ImplAAFDescriptiveClip.cpp
Phygon/aaf
faef720e031f501190481e1d1fc1870a7dc8f98b
[ "Linux-OpenIB" ]
null
null
null
ref-impl/src/impl/ImplAAFDescriptiveClip.cpp
Phygon/aaf
faef720e031f501190481e1d1fc1870a7dc8f98b
[ "Linux-OpenIB" ]
null
null
null
ref-impl/src/impl/ImplAAFDescriptiveClip.cpp
Phygon/aaf
faef720e031f501190481e1d1fc1870a7dc8f98b
[ "Linux-OpenIB" ]
null
null
null
//=---------------------------------------------------------------------= // // // $Id$ $Name$ // // The contents of this file are subject to the AAF SDK Public Source // License Agreement Version 2.0 (the "License"); You may not use this // file except in compliance with the License. The License is available // in AAFSDKPSL.TXT, or you may obtain a copy of the License from the // Advanced Media Workflow Association, Inc., or its successor. // // Software distributed under the License is distributed on an "AS IS" // basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See // the License for the specific language governing rights and limitations // under the License. Refer to Section 3.3 of the License for proper use // of this Exhibit. // // WARNING: Please contact the Advanced Media Workflow Association, // Inc., for more information about any additional licenses to // intellectual property covering the AAF Standard that may be required // to create and distribute AAF compliant products. // (http://www.amwa.tv/policies). // // Copyright Notices: // The Original Code of this file is Copyright 1998-2009, licensor of the // Advanced Media Workflow Association. All rights reserved. // // The Initial Developer of the Original Code of this file and the // licensor of the Advanced Media Workflow Association is // Avid Technology. // All rights reserved. // //=---------------------------------------------------------------------= #include "AAFStoredObjectIDs.h" #ifndef __ImplAAFDescriptiveClip_h__ #include "ImplAAFDescriptiveClip.h" #endif #include "AAFPropertyIDs.h" #include <string.h> ImplAAFDescriptiveClip::ImplAAFDescriptiveClip () : _describedSlotIDs( PID_DescriptiveClip_DescribedSlotIDs, L"DescribedSlotIDs" ) { _persistentProperties.put( _describedSlotIDs.address() ); } ImplAAFDescriptiveClip::~ImplAAFDescriptiveClip () {} AAFRESULT STDMETHODCALLTYPE ImplAAFDescriptiveClip::Initialize (ImplAAFDataDef * pDataDef, const aafLength_t & length, const aafSourceRef_t & sourceRef) { if( isInitialized() ) { return AAFRESULT_ALREADY_INITIALIZED; } // Call parent class' Initialize. AAFRESULT ar = ImplAAFSourceClip::Initialize(pDataDef, length, sourceRef); // Initialize this class required properties // and set the object initialized. if( ar == AAFRESULT_SUCCESS ) { setInitialized(); } return ar; } AAFRESULT STDMETHODCALLTYPE ImplAAFDescriptiveClip::CountDescribedSlotIDs ( aafUInt32* pCount) { if (NULL == pCount) { return AAFRESULT_NULL_PARAM; } if (!_describedSlotIDs.isPresent()) { return AAFRESULT_PROP_NOT_PRESENT; } *pCount = _describedSlotIDs.count(); return AAFRESULT_SUCCESS; } AAFRESULT STDMETHODCALLTYPE ImplAAFDescriptiveClip::GetDescribedSlotIDs ( aafUInt32 maxDescribedSlotIDCount, aafUInt32 * pDescribedSlotIDs) { if (!pDescribedSlotIDs) { return AAFRESULT_NULL_PARAM; } if (_describedSlotIDs.count() > maxDescribedSlotIDCount) { return AAFRESULT_SMALLBUF; } if (!_describedSlotIDs.isPresent()) { return AAFRESULT_PROP_NOT_PRESENT; } aafUInt32* pNextDescribedSlotID = pDescribedSlotIDs; OMSetPropertyIterator<aafUInt32> iter( _describedSlotIDs, OMBefore ); while (++iter) { *pNextDescribedSlotID = iter.value(); pNextDescribedSlotID++; } return AAFRESULT_SUCCESS; } AAFRESULT STDMETHODCALLTYPE ImplAAFDescriptiveClip::IsDescribedSlotIDPresent ( aafUInt32 describedSlotID, aafBoolean_t* pIsPresent) { if (NULL == pIsPresent) { return AAFRESULT_NULL_PARAM; } if (!_describedSlotIDs.isPresent()) { return AAFRESULT_PROP_NOT_PRESENT; } *pIsPresent = _describedSlotIDs.contains(describedSlotID) ? kAAFTrue : kAAFFalse; return AAFRESULT_SUCCESS; } AAFRESULT STDMETHODCALLTYPE ImplAAFDescriptiveClip::AddDescribedSlotID ( aafUInt32 describedSlotID) { if (_describedSlotIDs.isPresent()) { if (_describedSlotIDs.contains(describedSlotID)) return AAFRESULT_INVALID_PARAM; } _describedSlotIDs.insert(describedSlotID); return AAFRESULT_SUCCESS; } AAFRESULT STDMETHODCALLTYPE ImplAAFDescriptiveClip::RemoveDescribedSlotID ( aafUInt32 describedSlotID) { if (!_describedSlotIDs.isPresent()) return AAFRESULT_PROP_NOT_PRESENT; if (!_describedSlotIDs.contains(describedSlotID)) return AAFRESULT_INVALID_PARAM; _describedSlotIDs.remove(describedSlotID); if (_describedSlotIDs.count() == 0) { _describedSlotIDs.removeProperty(); } return AAFRESULT_SUCCESS; }
25.698413
80
0.682314
[ "object" ]
04135fc45065734292590f77763d831b45698513
5,072
cpp
C++
TinyEngine/src/gltf/HelperAnimate.cpp
Kimau/KhronosSandbox
e06caed3ab85e620ac2c5860fd31cef6ed6418c3
[ "Apache-2.0" ]
68
2020-04-14T11:03:26.000Z
2020-06-11T16:17:29.000Z
TinyEngine/src/gltf/HelperAnimate.cpp
Kimau/KhronosSandbox
e06caed3ab85e620ac2c5860fd31cef6ed6418c3
[ "Apache-2.0" ]
5
2020-05-16T05:32:16.000Z
2020-05-21T11:09:52.000Z
TinyEngine/src/gltf/HelperAnimate.cpp
Kimau/KhronosSandbox
e06caed3ab85e620ac2c5860fd31cef6ed6418c3
[ "Apache-2.0" ]
1
2021-03-19T22:47:00.000Z
2021-03-19T22:47:00.000Z
#include "HelperAnimate.h" #include "../activity/Interpolator.h" bool HelperAnimate::update(GLTF& glTF, const AnimationChannel& channel, int32_t startIndex, int32_t stopIndex, float currentTime) { const AnimationSampler& sampler = *channel.targetSampler; float t = 0.0f; if (stopIndex != -1) { t = (currentTime - sampler.inputTime[startIndex]) / (sampler.inputTime[stopIndex] - sampler.inputTime[startIndex]); } Node& node = *channel.target.targetNode; const float* x = nullptr; const float* y = nullptr; const float* xout = nullptr; const float* yin = nullptr; uint32_t typeCount = 1; if (channel.target.path == translation || channel.target.path == scale) { typeCount = 3; } else if (channel.target.path == rotation) { typeCount = 4; } else { typeCount = static_cast<uint32_t>(node.weights.size()); } uint32_t elementCount = 1; uint32_t elementOffset = 0; if (sampler.interpolation == CUBICSPLINE) { elementCount = 3; elementOffset = typeCount; } uint32_t offset = typeCount * elementCount; x = &sampler.outputValues[startIndex * offset + elementOffset]; if (sampler.interpolation == CUBICSPLINE) { xout = &sampler.outputValues[startIndex * offset + elementOffset * 2]; } if (stopIndex != -1) { y = &sampler.outputValues[stopIndex * offset + elementOffset]; if (sampler.interpolation == CUBICSPLINE) { yin = &sampler.outputValues[stopIndex * offset]; } } // if (channel.target.path == translation || channel.target.path == scale) { glm::vec3 value(x[0], x[1], x[2]); if (stopIndex != -1) { if (sampler.interpolation == CUBICSPLINE) { value = Interpolator::cubicspline(glm::vec3(x[0], x[1], x[2]), glm::vec3(xout[0], xout[1], xout[2]), glm::vec3(yin[0], yin[1], yin[2]), glm::vec3(y[0], y[1], y[2]), t); } else if (sampler.interpolation == LINEAR) { value = Interpolator::linear(glm::vec3(x[0], x[1], x[2]), glm::vec3(y[0], y[1], y[2]), t); } else { value = Interpolator::step(glm::vec3(x[0], x[1], x[2]), glm::vec3(y[0], y[1], y[2]), t); } } if (channel.target.path == translation) { node.translation = value; } else if (channel.target.path == scale) { node.scale = value; } } else if (channel.target.path == rotation) { glm::quat value(x[3], x[0], x[1], x[2]); if (stopIndex != -1) { if (sampler.interpolation == CUBICSPLINE) { value = Interpolator::cubicspline(glm::quat(x[3], x[0], x[1], x[2]), glm::quat(xout[3], xout[0], xout[1], xout[2]), glm::quat(yin[3], yin[0], yin[1], yin[2]), glm::quat(y[3], y[0], y[1], y[2]), t); } else if (sampler.interpolation == LINEAR) { value = Interpolator::linear(glm::quat(x[3], x[0], x[1], x[2]), glm::quat(y[3], y[0], y[1], y[2]), t); } else { value = Interpolator::step(glm::quat(x[3], x[0], x[1], x[2]), glm::quat(y[3], y[0], y[1], y[2]), t); } } node.rotation = value; } else { for (size_t i = 0; i < node.weights.size(); i++) { float value = x[i]; if (stopIndex != -1) { if (sampler.interpolation == CUBICSPLINE) { value = Interpolator::cubicspline(x[i], xout[i], yin[i], y[i], t); } else if (sampler.interpolation == LINEAR) { value = Interpolator::linear(x[i], y[i], t); } else { value = Interpolator::step(x[i], y[i], t); } } node.weights[i] = value; } } return true; } bool HelperAnimate::gatherStop(float& stop, const GLTF& glTF, uint32_t animationIndex) { if (animationIndex >= static_cast<uint32_t>(glTF.animations.size())) { return false; } const Animation& animation = glTF.animations[animationIndex]; if (animation.samplers.size() == 0 || animation.samplers[0].inputTime.size() == 0) { return false; } stop = animation.samplers[0].inputTime.back(); for (uint32_t i = 1; i < animation.samplers.size(); i++) { if (animation.samplers[i].inputTime.size() == 0) { return false; } stop = glm::max(stop, animation.samplers[i].inputTime.back()); } return true; } bool HelperAnimate::update(GLTF& glTF, uint32_t animationIndex, float currentTime) { if (animationIndex >= static_cast<uint32_t>(glTF.animations.size())) { return false; } const Animation& animation = glTF.animations[animationIndex]; for (uint32_t i = 0; i < animation.channels.size(); i++) { const AnimationChannel& channel = animation.channels[i]; const AnimationSampler& sampler = *channel.targetSampler; const std::vector<float>& inputTime = sampler.inputTime; if (inputTime.size() == 0) { return false; } if (currentTime < inputTime.front()) { update(glTF, channel, 0, -1, currentTime); } else if (currentTime >= inputTime.back()) { update(glTF, channel, static_cast<int32_t>(inputTime.size() - 1), -1, currentTime); } else { for (int32_t startIndex = 0; startIndex < static_cast<int32_t>(inputTime.size()); startIndex++) { if (currentTime < inputTime[startIndex]) { update(glTF, channel, startIndex - 1, startIndex, currentTime); break; } } } } return true; }
23.590698
201
0.626972
[ "vector" ]
54b6e0419d3ed425af4158f2975ab849022ff16c
4,395
hpp
C++
src/io/ordered_sparse_bin.hpp
mindis/LightGBM
888e2b181a870297a7e33ef15102500bceabf839
[ "MIT" ]
null
null
null
src/io/ordered_sparse_bin.hpp
mindis/LightGBM
888e2b181a870297a7e33ef15102500bceabf839
[ "MIT" ]
null
null
null
src/io/ordered_sparse_bin.hpp
mindis/LightGBM
888e2b181a870297a7e33ef15102500bceabf839
[ "MIT" ]
1
2018-12-14T19:07:00.000Z
2018-12-14T19:07:00.000Z
#ifndef LIGHTGBM_IO_ORDERED_SPARSE_BIN_HPP_ #define LIGHTGBM_IO_ORDERED_SPARSE_BIN_HPP_ #include <LightGBM/bin.h> #include <cstring> #include <cstdint> #include <vector> #include <mutex> #include <algorithm> namespace LightGBM { /*! * \brief Ordered bin for sparse feature . efficient for construct histogram, especally for sparse bin * There are 2 advantages for using ordered bin. * 1. group the data by leaf, improve the cache hit. * 2. only store the non-zero bin, which can speed up the histogram cconsturction for sparse feature. * But it has a additional cost, it need re-order the bins after leaf split, which will cost much for dense feature. * So we only use ordered bin for sparse features now. */ template <typename VAL_T> class OrderedSparseBin:public OrderedBin { public: /*! \brief Pair to store one bin entry */ struct SparsePair { data_size_t ridx; // data(row) index VAL_T bin; // bin for this data SparsePair(data_size_t r, VAL_T b) : ridx(r), bin(b) {} }; OrderedSparseBin(const std::vector<uint8_t>& delta, const std::vector<VAL_T>& vals) :delta_(delta), vals_(vals) { data_size_t cur_pos = 0; for (size_t i = 0; i < vals_.size(); ++i) { cur_pos += delta_[i]; if (vals_[i] > 0) { ordered_pair_.emplace_back(cur_pos, vals_[i]); } } ordered_pair_.shrink_to_fit(); } ~OrderedSparseBin() { } void Init(const char* used_idices, int num_leaves) override { // initialize the leaf information leaf_start_ = std::vector<data_size_t>(num_leaves, 0); leaf_cnt_ = std::vector<data_size_t>(num_leaves, 0); if (used_idices == nullptr) { // if using all data, copy all non-zero pair data_size_t cur_pos = 0; data_size_t j = 0; for (size_t i = 0; i < vals_.size(); ++i) { cur_pos += delta_[i]; if (vals_[i] > 0) { ordered_pair_[j].ridx = cur_pos; ordered_pair_[j].bin = vals_[i]; ++j; } } leaf_cnt_[0] = static_cast<data_size_t>(ordered_pair_.size()); } else { // if using part of data(bagging) data_size_t j = 0; data_size_t cur_pos = 0; for (size_t i = 0; i < vals_.size(); ++i) { cur_pos += delta_[i]; if (vals_[i] > 0 && used_idices[cur_pos] != 0) { ordered_pair_[j].ridx = cur_pos; ordered_pair_[j].bin = vals_[i]; ++j; } } leaf_cnt_[0] = j; } } void ConstructHistogram(int leaf, const score_t* gradient, const score_t* hessian, HistogramBinEntry* out) const override { // get current leaf boundary const data_size_t start = leaf_start_[leaf]; const data_size_t end = start + leaf_cnt_[leaf]; // use data on current leaf to construct histogram for (data_size_t i = start; i < end; ++i) { const VAL_T bin = ordered_pair_[i].bin; const data_size_t idx = ordered_pair_[i].ridx; out[bin].sum_gradients += gradient[idx]; out[bin].sum_hessians += hessian[idx]; ++out[bin].cnt; } } void Split(int leaf, int right_leaf, const char* left_indices) override { // get current leaf boundary const data_size_t l_start = leaf_start_[leaf]; const data_size_t l_end = l_start + leaf_cnt_[leaf]; // new left leaf end after split data_size_t new_left_end = l_start; for (data_size_t i = l_start; i < l_end; ++i) { if (left_indices[ordered_pair_[i].ridx] != 0) { std::swap(ordered_pair_[new_left_end], ordered_pair_[i]); ++new_left_end; } } leaf_start_[right_leaf] = new_left_end; leaf_cnt_[leaf] = new_left_end - l_start; leaf_cnt_[right_leaf] = l_end - new_left_end; } /*! \brief Disable copy */ OrderedSparseBin<VAL_T>& operator=(const OrderedSparseBin<VAL_T>&) = delete; /*! \brief Disable copy */ OrderedSparseBin<VAL_T>(const OrderedSparseBin<VAL_T>&) = delete; private: const std::vector<uint8_t>& delta_; const std::vector<VAL_T>& vals_; /*! \brief Store non-zero pair , group by leaf */ std::vector<SparsePair> ordered_pair_; /*! \brief leaf_start_[i] means data in i-th leaf start from */ std::vector<data_size_t> leaf_start_; /*! \brief leaf_cnt_[i] means number of data in i-th leaf */ std::vector<data_size_t> leaf_cnt_; }; } // namespace LightGBM #endif // LightGBM_IO_ORDERED_SPARSE_BIN_HPP_
33.045113
115
0.646871
[ "vector" ]
54bb19979ec39d8e6b14f8547bad59075351c4ec
7,554
cpp
C++
src/lib/rtm/OutPortCorbaCdrConsumer.cpp
n-kawauchi/pipeline-test
aa29d84f177c7d8cefc81adab29abc06fccd61cb
[ "RSA-MD" ]
15
2019-01-08T15:34:04.000Z
2022-03-01T08:36:17.000Z
src/lib/rtm/OutPortCorbaCdrConsumer.cpp
n-kawauchi/pipeline-test
aa29d84f177c7d8cefc81adab29abc06fccd61cb
[ "RSA-MD" ]
448
2018-12-27T03:13:56.000Z
2022-03-24T09:57:03.000Z
src/lib/rtm/OutPortCorbaCdrConsumer.cpp
n-kawauchi/pipeline-test
aa29d84f177c7d8cefc81adab29abc06fccd61cb
[ "RSA-MD" ]
31
2018-12-26T04:34:22.000Z
2021-11-25T04:39:51.000Z
// -*- C++ -*- /*! * @file OutPortCorbaCdrConsumer.cpp * @brief OutPortCorbaCdrConsumer class * @date $Date: 2008-01-13 10:28:27 $ * @author Noriaki Ando <n-ando@aist.go.jp> * * Copyright (C) 2009-2010 * Noriaki Ando * Task-intelligence Research Group, * Intelligent Systems Research Institute, * National Institute of * Advanced Industrial Science and Technology (AIST), Japan * All rights reserved. * * $Id: OutPortCorbaCdrConsumer.h 1254 2009-04-07 01:09:35Z kurihara $ * */ #include <rtm/Manager.h> #include <rtm/OutPortCorbaCdrConsumer.h> #include <rtm/NVUtil.h> namespace RTC { /*! * @if jp * @brief コンストラクタ * @else * @brief Constructor * @endif */ OutPortCorbaCdrConsumer::OutPortCorbaCdrConsumer() { rtclog.setName("OutPortCorbaCdrConsumer"); } /*! * @if jp * @brief デストラクタ * @else * @brief Destructor * @endif */ OutPortCorbaCdrConsumer::~OutPortCorbaCdrConsumer() = default; /*! * @if jp * @brief 設定初期化 * @else * @brief Initializing configuration * @endif */ void OutPortCorbaCdrConsumer::init(coil::Properties& /*prop*/) { RTC_TRACE(("OutPortCorbaCdrConsumer::init()")); } /*! * @if jp * @brief バッファをセットする * @else * @brief Setting outside buffer's pointer * @endif */ void OutPortCorbaCdrConsumer::setBuffer(CdrBufferBase* buffer) { RTC_TRACE(("OutPortCorbaCdrConsumer::setBuffer()")); m_buffer = buffer; } /*! * @if jp * @brief リスナを設定する。 * @else * @brief Set the listener. * @endif */ void OutPortCorbaCdrConsumer::setListener(ConnectorInfo& info, ConnectorListenersBase* listeners) { RTC_TRACE(("OutPortCorbaCdrConsumer::setListener()")); m_listeners = listeners; m_profile = info; } /*! * @if jp * @brief データを読み出す * @else * @brief Read data * @endif */ DataPortStatus OutPortCorbaCdrConsumer::get(ByteData& data) { RTC_TRACE(("OutPortCorbaCdrConsumer::get()")); ::OpenRTM::CdrData_var cdr_data; try { ::OpenRTM::PortStatus ret(_ptr()->get(cdr_data.out())); if (ret == ::OpenRTM::PORT_OK) { RTC_DEBUG(("get() successful")); #ifdef ORB_IS_ORBEXPRESS data.writeData(static_cast<unsigned char*>(cdr_data.get_buffer()), static_cast<CORBA::ULong>(cdr_data.length())); #elif defined(ORB_IS_TAO) data.writeData(static_cast<unsigned char*>(cdr_data->get_buffer()), static_cast<CORBA::ULong>(cdr_data->length())); #elif defined(ORB_IS_RTORB) data.writeData(reinterpret_cast<unsigned char*>(&(cdr_data[0])), static_cast<CORBA::ULong>(cdr_data->length())); #else data.writeData(static_cast<unsigned char*>(&(cdr_data[0])), static_cast<CORBA::ULong>(cdr_data->length())); #endif RTC_PARANOID(("CDR data length: %d", cdr_data->length())); onReceived(data); onBufferWrite(data); if (m_buffer->full()) { RTC_INFO(("InPort buffer is full.")); onBufferFull(data); onReceiverFull(data); } m_buffer->put(data); m_buffer->advanceWptr(); m_buffer->advanceRptr(); return DataPortStatus::PORT_OK; } return convertReturn(ret, data); } catch (...) { RTC_WARN(("Exception caought from OutPort::get().")); return DataPortStatus::CONNECTION_LOST; } } /*! * @if jp * @brief データ受信通知への登録 * @else * @brief Subscribe the data receive notification * @endif */ bool OutPortCorbaCdrConsumer:: subscribeInterface(const SDOPackage::NVList& properties) { RTC_TRACE(("OutPortCorbaCdrConsumer::subscribeInterface()")); CORBA::Long index; index = NVUtil::find_index(properties, "dataport.corba_cdr.outport_ior"); if (index < 0) { RTC_DEBUG(("dataport.corba_cdr.outport_ior not found.")); return false; } if (NVUtil::isString(properties, "dataport.corba_cdr.outport_ior")) { RTC_DEBUG(("dataport.corba_cdr.outport_ior found.")); const char* ior(nullptr); properties[index].value >>= ior; CORBA::ORB_var orb = ::RTC::Manager::instance().getORB(); CORBA::Object_var var = orb->string_to_object(ior); bool ret(setObject(var.in())); if (ret) { RTC_DEBUG(("CorbaConsumer was set successfully.")); } else { RTC_ERROR(("Invalid object reference.")); } return ret; } return false; } /*! * @if jp * @brief データ受信通知からの登録解除 * @else * @brief Unsubscribe the data receive notification * @endif */ void OutPortCorbaCdrConsumer:: unsubscribeInterface(const SDOPackage::NVList& properties) { RTC_TRACE(("OutPortCorbaCdrConsumer::unsubscribeInterface()")); CORBA::Long index; index = NVUtil::find_index(properties, "dataport.corba_cdr.outport_ior"); if (index < 0) { RTC_DEBUG(("dataport.corba_cdr.outport_ior not found.")); return; } const char* ior; if (properties[index].value >>= ior) { RTC_DEBUG(("dataport.corba_cdr.outport_ior found.")); CORBA::ORB_var orb = ::RTC::Manager::instance().getORB(); CORBA::Object_var var = orb->string_to_object(ior); if (_ptr()->_is_equivalent(var)) { releaseObject(); RTC_DEBUG(("CorbaConsumer's reference was released.")); return; } RTC_ERROR(("hmm. Inconsistent object reference.")); } } /*! * @if jp * @brief リターンコード変換 (DataPortStatus -> BufferStatus) * @else * @brief Return codes conversion * @endif */ DataPortStatus OutPortCorbaCdrConsumer::convertReturn(::OpenRTM::PortStatus status, ByteData& /*data*/) { switch (status) { case ::OpenRTM::PORT_OK: // never comes here return DataPortStatus::PORT_OK; break; case ::OpenRTM::PORT_ERROR: onSenderError(); return DataPortStatus::PORT_ERROR; break; case ::OpenRTM::BUFFER_FULL: // never comes here return DataPortStatus::BUFFER_FULL; break; case ::OpenRTM::BUFFER_EMPTY: onSenderEmpty(); return DataPortStatus::BUFFER_EMPTY; break; case ::OpenRTM::BUFFER_TIMEOUT: onSenderTimeout(); return DataPortStatus::BUFFER_TIMEOUT; break; case ::OpenRTM::UNKNOWN_ERROR: onSenderError(); return DataPortStatus::UNKNOWN_ERROR; break; default: onSenderError(); return DataPortStatus::UNKNOWN_ERROR; } } } // namespace RTC extern "C" { /*! * @if jp * @brief モジュール初期化関数 * @else * @brief Module initialization * @endif */ void OutPortCorbaCdrConsumerInit(void) { RTC::OutPortConsumerFactory& factory(RTC::OutPortConsumerFactory::instance()); factory.addFactory("corba_cdr", ::coil::Creator< ::RTC::OutPortConsumer, ::RTC::OutPortCorbaCdrConsumer>, ::coil::Destructor< ::RTC::OutPortConsumer, ::RTC::OutPortCorbaCdrConsumer>); } }
25.60678
127
0.582208
[ "object" ]
54c010d1119c4861ab7c31a8d93559e3b724a27c
1,775
cpp
C++
test/salt.cpp
nabijaczleweli/Cpponfiguration
71bd501b47834c86ebd4a0d167e0175a1b4ab9c5
[ "MIT" ]
null
null
null
test/salt.cpp
nabijaczleweli/Cpponfiguration
71bd501b47834c86ebd4a0d167e0175a1b4ab9c5
[ "MIT" ]
9
2015-01-28T19:19:17.000Z
2016-03-20T13:04:26.000Z
test/salt.cpp
nabijaczleweli/Cpponfiguration
71bd501b47834c86ebd4a0d167e0175a1b4ab9c5
[ "MIT" ]
null
null
null
// The MIT License (MIT) // Copyright (c) 2015 nabijaczleweli // 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 "util/salt.hpp" #include "catch.hpp" using namespace std; using namespace cpponfig; TEST_CASE("salt") { SECTION("randomize_salt") { REQUIRE(salt{} != salt{}); const auto randomize_salt = salt::randomize_salt; salt::randomize_salt = false; REQUIRE(salt{} == salt{}); salt::randomize_salt = randomize_salt; REQUIRE(salt{} != salt{}); } for(int i = 0; i < 10; ++i) REQUIRE(salt{} != salt{}); vector<salt> salts(1000000); REQUIRE(accumulate(salts.begin(), salts.end(), size_t(0)) == Approx(numeric_limits<size_t>::max() / 2).epsilon(numeric_limits<size_t>::max() / salts.size())); }
34.134615
159
0.719437
[ "vector" ]
54ca08f23c876f95cebecb1efba0bfb392dbc5cc
6,455
cpp
C++
extsrc/mesa/src/gallium/state_trackers/d3d1x/progs/d3d11spikysphere/d3d11spikysphere.cpp
MauroArgentino/RSXGL
bd206e11894f309680f48740346c17efe49755ba
[ "BSD-2-Clause" ]
2,151
2020-04-18T07:31:17.000Z
2022-03-31T08:39:18.000Z
extsrc/mesa/src/gallium/state_trackers/d3d1x/progs/d3d11spikysphere/d3d11spikysphere.cpp
MauroArgentino/RSXGL
bd206e11894f309680f48740346c17efe49755ba
[ "BSD-2-Clause" ]
395
2020-04-18T08:22:18.000Z
2021-12-08T13:04:49.000Z
extsrc/mesa/src/gallium/state_trackers/d3d1x/progs/d3d11spikysphere/d3d11spikysphere.cpp
MauroArgentino/RSXGL
bd206e11894f309680f48740346c17efe49755ba
[ "BSD-2-Clause" ]
338
2020-04-18T08:03:10.000Z
2022-03-29T12:33:22.000Z
/************************************************************************** * * Copyright 2010 Luca Barbieri * * 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 (including the * next paragraph) 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 COPYRIGHT OWNER(S) AND/OR ITS SUPPLIERS 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. * **************************************************************************/ #define _USE_MATH_DEFINES #include "d3d11app.h" #include "d3d11spikysphere.hlsl.vs.h" #include "d3d11spikysphere.hlsl.hs.h" #include "d3d11spikysphere.hlsl.ds.h" #include "d3d11spikysphere.hlsl.ps.h" #include <stdlib.h> #include <stdio.h> #include <math.h> #include <float.h> #include <D3DX10math.h> struct cb_frame_t { D3DXMATRIX model; D3DXMATRIX view_proj; float disp_scale; float disp_freq; float tess_factor; }; static float vertex_data[] = { 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 1.0, 0.0, -1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, -1.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, -1.0, 0.0, 0.0, 0.0, -1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 1.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, -1.0, -1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, -1.0, 1.0, 0.0, 0.0, 0.0, -1.0, 0.0, 0.0, 0.0, -1.0, 0.0, -1.0, 0.0, -1.0, 0.0, 0.0, 0.0, 0.0, -1.0, }; struct d3d11spikysphere : public d3d11_application { ID3D11Device* dev; ID3D11PixelShader* ps; ID3D11DomainShader* ds; ID3D11HullShader* hs; ID3D11VertexShader* vs; ID3D11InputLayout* layout; ID3D11Buffer* vb; ID3D11RenderTargetView* rtv; ID3D11DepthStencilView* zsv; ID3D11Buffer* cb_frame; int cur_width; int cur_height; d3d11spikysphere() : cur_width(-1), cur_height(-1), zsv(0) {} bool init(ID3D11Device* dev, int argc, char** argv) { this->dev = dev; ensure(dev->CreateVertexShader(g_vs, sizeof(g_vs), NULL, &vs)); ensure(dev->CreateHullShader(g_hs, sizeof(g_hs), NULL, &hs)); ensure(dev->CreateDomainShader(g_ds, sizeof(g_ds), NULL, &ds)); ensure(dev->CreatePixelShader(g_ps, sizeof(g_ps), NULL, &ps)); D3D11_INPUT_ELEMENT_DESC elements[1] = { {"POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0}, }; ensure(dev->CreateInputLayout(elements, 1, g_vs, sizeof(g_vs), &layout)); D3D11_BUFFER_DESC bufferd; bufferd.ByteWidth = sizeof(vertex_data); bufferd.Usage = D3D11_USAGE_IMMUTABLE; bufferd.BindFlags = D3D11_BIND_VERTEX_BUFFER; bufferd.CPUAccessFlags = 0; bufferd.MiscFlags = 0; bufferd.StructureByteStride = 0; D3D11_SUBRESOURCE_DATA buffersd; buffersd.pSysMem = vertex_data; ensure(dev->CreateBuffer(&bufferd, &buffersd, &vb)); D3D11_BUFFER_DESC cbd; cbd.ByteWidth = (sizeof(cb_frame_t) + 15) & ~15; cbd.Usage = D3D11_USAGE_DYNAMIC; cbd.BindFlags = D3D11_BIND_CONSTANT_BUFFER; cbd.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; cbd.MiscFlags = 0; cbd.StructureByteStride = 0; ensure(dev->CreateBuffer(&cbd, NULL, &cb_frame)); return true; } void draw(ID3D11DeviceContext* ctx, ID3D11RenderTargetView* rtv, unsigned width, unsigned height, double time) { D3D11_VIEWPORT vp; memset(&vp, 0, sizeof(vp)); vp.Width = (float)width; vp.Height = (float)height; vp.MaxDepth = 1.0f; if(width != cur_width || height != cur_height) { if(zsv) zsv->Release(); ID3D11Texture2D* zsbuf; D3D11_TEXTURE2D_DESC zsbufd; memset(&zsbufd, 0, sizeof(zsbufd)); zsbufd.Width = width; zsbufd.Height = height; zsbufd.Format = DXGI_FORMAT_D32_FLOAT; zsbufd.ArraySize = 1; zsbufd.MipLevels = 1; zsbufd.SampleDesc.Count = 1; zsbufd.BindFlags = D3D11_BIND_DEPTH_STENCIL; ensure(dev->CreateTexture2D(&zsbufd, 0, &zsbuf)); ensure(dev->CreateDepthStencilView(zsbuf, 0, &zsv)); zsbuf->Release(); } float black[4] = {0, 0, 0, 0}; D3D11_MAPPED_SUBRESOURCE map; ensure(ctx->Map(cb_frame, 0, D3D11_MAP_WRITE_DISCARD, 0, &map)); cb_frame_t* cb_frame_data = (cb_frame_t*)map.pData; D3DXMatrixIdentity(&cb_frame_data->model); D3DXMATRIX view; D3DXVECTOR3 eye(2.0f * (float)sin(time), 0.0f, 2.0f * (float)cos(time)); D3DXVECTOR3 at(0, 0, 0); D3DXVECTOR3 up(0, 1, 0); D3DXMatrixLookAtLH(&view, &eye, &at, &up); D3DXMATRIX proj; D3DXMatrixPerspectiveLH(&proj, 1.1f, 1.1f, 1.0f, 3.0f); cb_frame_data->view_proj = view * proj; float min_tess_factor = 1.0f; cb_frame_data->tess_factor = (1.0f - (float)cos(time)) * ((64.0f - min_tess_factor) / 2.0f) + min_tess_factor; cb_frame_data->disp_scale = 0.9f; //cb_frame_data->disp_scale = (sin(time) + 1.0) / 2.0; cb_frame_data->disp_freq = 5.0f * (float)M_PI; //cb_frame_data->disp_freq = (4.0 + 4.0 * cos(time / 5.0)) * PI; ctx->Unmap(cb_frame, 0); ctx->HSSetConstantBuffers(0, 1, &cb_frame); ctx->DSSetConstantBuffers(0, 1, &cb_frame); //ctx->OMSetBlendState(bs, black, ~0); //ctx->OMSetDepthStencilState(dss, 0); ctx->OMSetRenderTargets(1, &rtv, zsv); //ctx->RSSetState(rs); ctx->RSSetViewports(1, &vp); ctx->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_3_CONTROL_POINT_PATCHLIST); ctx->IASetInputLayout(layout); unsigned stride = 3 * 4; unsigned offset = 0; ctx->IASetVertexBuffers(0, 1, &vb, &stride, &offset); ctx->VSSetShader(vs, NULL, 0); ctx->HSSetShader(hs, NULL, 0); ctx->DSSetShader(ds, NULL, 0); ctx->GSSetShader(NULL, NULL, 0); ctx->PSSetShader(ps, NULL, 0); ctx->ClearRenderTargetView(rtv, black); ctx->ClearDepthStencilView(zsv, D3D11_CLEAR_DEPTH, 1.0f, 0); ctx->Draw(3 * 8, 0); } }; d3d11_application* d3d11_application_create() { return new d3d11spikysphere(); }
28.311404
112
0.677304
[ "model" ]
54cf6de9742d33a15691f82b92df8acbc25b3e89
12,326
cpp
C++
experimental/graphite/src/ContextUtils.cpp
mktitov/skia
e8e1b79976f2fd6102b7295336441ddd2016e0ce
[ "BSD-3-Clause" ]
null
null
null
experimental/graphite/src/ContextUtils.cpp
mktitov/skia
e8e1b79976f2fd6102b7295336441ddd2016e0ce
[ "BSD-3-Clause" ]
null
null
null
experimental/graphite/src/ContextUtils.cpp
mktitov/skia
e8e1b79976f2fd6102b7295336441ddd2016e0ce
[ "BSD-3-Clause" ]
1
2021-12-23T06:18:04.000Z
2021-12-23T06:18:04.000Z
/* * Copyright 2021 Google LLC * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "experimental/graphite/src/ContextUtils.h" #include <string> #include "experimental/graphite/src/DrawList.h" // TODO: split PaintParams out into their own header #include "experimental/graphite/src/DrawTypes.h" #include "experimental/graphite/src/Uniform.h" #include "experimental/graphite/src/UniformCache.h" #include "experimental/graphite/src/UniformManager.h" #include "include/core/SkPaint.h" namespace skgpu { namespace { // TODO: For the sprint we only support 4 stops in the gradients static constexpr int kMaxStops = 4; // TODO: For the sprint we unify all the gradient uniforms into a standard set of 6: // kMaxStops colors // kMaxStops offsets // 2 points // 2 radii static constexpr int kNumGradientUniforms = 6; static constexpr Uniform kGradientUniforms[kNumGradientUniforms] { {"colors", SLType::kHalf4 , kMaxStops }, {"offsets", SLType::kFloat, kMaxStops }, {"point0", SLType::kFloat2 }, {"point1", SLType::kFloat2 }, {"radius0", SLType::kFloat }, {"radius1", SLType::kFloat }, }; static constexpr int kNumSolidUniforms = 1; static constexpr Uniform kSolidUniforms[kNumSolidUniforms] { {"color", SLType::kFloat4 } }; sk_sp<UniformData> make_gradient_uniform_data_common(void* srcs[kNumGradientUniforms]) { UniformManager mgr(Layout::kMetal); // TODO: Given that, for the sprint, we always know the uniforms we could cache 'dataSize' // for each layout and skip the first call. size_t dataSize = mgr.writeUniforms(SkSpan<const Uniform>(kGradientUniforms, kNumGradientUniforms), nullptr, nullptr, nullptr); sk_sp<UniformData> result = UniformData::Make(kNumGradientUniforms, kGradientUniforms, dataSize); mgr.writeUniforms(SkSpan<const Uniform>(kGradientUniforms, kNumGradientUniforms), srcs, result->offsets(), result->data()); return result; } sk_sp<UniformData> make_linear_gradient_uniform_data(SkPoint startPoint, SkPoint endPoint, SkColor4f colors[kMaxStops], float offsets[kMaxStops]) { float unusedRadii[2] = { 0.0f, 0.0f }; void* srcs[kNumGradientUniforms] = { colors, offsets, &startPoint, &endPoint, &unusedRadii[0], &unusedRadii[1], }; return make_gradient_uniform_data_common(srcs); }; sk_sp<UniformData> make_radial_gradient_uniform_data(SkPoint point, float radius, SkColor4f colors[kMaxStops], float offsets[kMaxStops]) { SkPoint unusedPoint = {0.0f, 0.0f}; float unusedRadius = 0.0f; void* srcs[kNumGradientUniforms] = { colors, offsets, &point, &unusedPoint, &radius, &unusedRadius, }; return make_gradient_uniform_data_common(srcs); }; sk_sp<UniformData> make_sweep_gradient_uniform_data(SkPoint point, SkColor4f colors[kMaxStops], float offsets[kMaxStops]) { SkPoint unusedPoint = {0.0f, 0.0f}; float unusedRadii[2] = {0.0f, 0.0f}; void* srcs[kNumGradientUniforms] = { colors, offsets, &point, &unusedPoint, &unusedRadii[0], &unusedRadii[1], }; return make_gradient_uniform_data_common(srcs); }; sk_sp<UniformData> make_conical_gradient_uniform_data(SkPoint point0, SkPoint point1, float radius0, float radius1, SkColor4f colors[kMaxStops], float offsets[kMaxStops]) { void* srcs[kNumGradientUniforms] = { colors, offsets, &point0, &point1, &radius0, &radius1, }; return make_gradient_uniform_data_common(srcs); }; void to_color4fs(int numColors, SkColor colors[kMaxStops], SkColor4f color4fs[kMaxStops]) { SkASSERT(numColors >= 2 && numColors <= kMaxStops); int i; for (i = 0; i < numColors; ++i) { color4fs[i] = SkColor4f::FromColor(colors[i]); } for ( ; i < kMaxStops; ++i) { color4fs[i] = color4fs[numColors-1]; } } void expand_stops(int numStops, float offsets[kMaxStops]) { SkASSERT(numStops >= 2 && numStops <= kMaxStops); for (int i = numStops ; i < kMaxStops; ++i) { offsets[i] = offsets[numStops-1]; } } sk_sp<UniformData> make_solid_uniform_data(SkColor4f color) { UniformManager mgr(Layout::kMetal); size_t dataSize = mgr.writeUniforms(SkSpan<const Uniform>(kSolidUniforms, kNumSolidUniforms), nullptr, nullptr, nullptr); sk_sp<UniformData> result = UniformData::Make(kNumSolidUniforms, kSolidUniforms, dataSize); void* srcs[kNumSolidUniforms] = { &color }; mgr.writeUniforms(SkSpan<const Uniform>(kSolidUniforms, kNumSolidUniforms), srcs, result->offsets(), result->data()); return result; } } // anonymous namespace sk_sp<UniformData> UniformData::Make(int count, const Uniform* uniforms, size_t dataSize) { // TODO: the offsets and data should just be allocated right after UniformData in an arena uint32_t* offsets = new uint32_t[count]; char* data = new char[dataSize]; return sk_sp<UniformData>(new UniformData(count, uniforms, offsets, data, dataSize)); } std::tuple<Combination, sk_sp<UniformData>> ExtractCombo(UniformCache* cache, const PaintParams& p) { Combination result; sk_sp<UniformData> uniforms; if (auto s = p.shader()) { SkColor colors[kMaxStops]; SkColor4f color4fs[kMaxStops]; float offsets[kMaxStops]; SkShader::GradientInfo gradInfo; gradInfo.fColorCount = kMaxStops; gradInfo.fColors = colors; gradInfo.fColorOffsets = offsets; SkShader::GradientType type = s->asAGradient(&gradInfo); if (gradInfo.fColorCount > kMaxStops) { type = SkShader::GradientType::kNone_GradientType; } switch (type) { case SkShader::kLinear_GradientType: { to_color4fs(gradInfo.fColorCount, colors, color4fs); expand_stops(gradInfo.fColorCount, offsets); result.fShaderType = ShaderCombo::ShaderType::kLinearGradient; result.fTileMode = gradInfo.fTileMode; uniforms = make_linear_gradient_uniform_data(gradInfo.fPoint[0], gradInfo.fPoint[1], color4fs, offsets); } break; case SkShader::kRadial_GradientType: { to_color4fs(gradInfo.fColorCount, colors, color4fs); expand_stops(gradInfo.fColorCount, offsets); result.fShaderType = ShaderCombo::ShaderType::kRadialGradient; result.fTileMode = gradInfo.fTileMode; uniforms = make_radial_gradient_uniform_data(gradInfo.fPoint[0], gradInfo.fRadius[0], color4fs, offsets); } break; case SkShader::kSweep_GradientType: to_color4fs(gradInfo.fColorCount, colors, color4fs); expand_stops(gradInfo.fColorCount, offsets); result.fShaderType = ShaderCombo::ShaderType::kSweepGradient; result.fTileMode = gradInfo.fTileMode; uniforms = make_sweep_gradient_uniform_data(gradInfo.fPoint[0], color4fs, offsets); break; case SkShader::GradientType::kConical_GradientType: to_color4fs(gradInfo.fColorCount, colors, color4fs); expand_stops(gradInfo.fColorCount, offsets); result.fShaderType = ShaderCombo::ShaderType::kConicalGradient; result.fTileMode = gradInfo.fTileMode; uniforms = make_conical_gradient_uniform_data(gradInfo.fPoint[0], gradInfo.fPoint[1], gradInfo.fRadius[0], gradInfo.fRadius[1], color4fs, offsets); break; case SkShader::GradientType::kColor_GradientType: case SkShader::GradientType::kNone_GradientType: default: result.fShaderType = ShaderCombo::ShaderType::kSolidColor; result.fTileMode = SkTileMode::kClamp; uniforms = make_solid_uniform_data(p.color()); break; } } else { // Solid colored paint result.fShaderType = ShaderCombo::ShaderType::kSolidColor; result.fTileMode = SkTileMode::kClamp; uniforms = make_solid_uniform_data(p.color()); } result.fBlendMode = p.blendMode(); sk_sp<UniformData> trueUD = cache->findOrCreate(std::move(uniforms)); return { result, std::move(trueUD) }; } namespace { // TODO: use a SkSpan for the parameters std::string emit_MSL_uniform_struct(const Uniform *uniforms, int numUniforms) { std::string result; result.append("struct FragmentUniforms {\n"); for (int i = 0; i < numUniforms; ++i) { // TODO: this is sufficient for the sprint but should be changed to use SkSL's // machinery switch (uniforms[i].type()) { case SLType::kFloat4: result.append("vector_float4"); break; case SLType::kFloat2: result.append("vector_float2"); break; case SLType::kFloat: result.append("float"); break; case SLType::kHalf4: result.append("vector_half4"); break; default: SkASSERT(0); } result.append(" "); result.append(uniforms[i].name()); if (uniforms[i].count()) { result.append("["); result.append(std::to_string(uniforms[i].count())); result.append("]"); } result.append(";\n"); } result.append("};\n"); return result; } } // anonymous namespace std::string GetMSLUniformStruct(ShaderCombo::ShaderType shaderType) { switch (shaderType) { case ShaderCombo::ShaderType::kLinearGradient: case ShaderCombo::ShaderType::kRadialGradient: case ShaderCombo::ShaderType::kSweepGradient: case ShaderCombo::ShaderType::kConicalGradient: return emit_MSL_uniform_struct(kGradientUniforms, kNumGradientUniforms); case ShaderCombo::ShaderType::kNone: return ""; case ShaderCombo::ShaderType::kSolidColor: default: return emit_MSL_uniform_struct(kSolidUniforms, kNumSolidUniforms); } } } // namespace skgpu
37.015015
100
0.546812
[ "solid" ]
54d22b3986e580003bbc6fd3f19d17952d75ccb6
1,430
cpp
C++
algo/swap1.cpp
yijingbai/STL_practice
f2cbfd978966d29f9d179d1abc34b9e1ccd3661d
[ "FSFAP" ]
null
null
null
algo/swap1.cpp
yijingbai/STL_practice
f2cbfd978966d29f9d179d1abc34b9e1ccd3661d
[ "FSFAP" ]
null
null
null
algo/swap1.cpp
yijingbai/STL_practice
f2cbfd978966d29f9d179d1abc34b9e1ccd3661d
[ "FSFAP" ]
null
null
null
/* The following code example is taken from the book * "The C++ Standard Library - A Tutorial and Reference" * by Nicolai M. Josuttis, Addison-Wesley, 1999 * * (C) Copyright Nicolai M. Josuttis 1999. * Permission to copy, use, modify, sell and distribute this software * is granted provided this copyright notice appears in all copies. * This software is provided "as is" without express or implied * warranty, and with no claim as to its suitability for any purpose. */ #include "algostuff.hpp" using namespace std; int main() { vector<int> coll1; deque<int> coll2; INSERT_ELEMENTS(coll1,1,9); INSERT_ELEMENTS(coll2,11,23); PRINT_ELEMENTS(coll1,"coll1: "); PRINT_ELEMENTS(coll2,"coll2: "); // swap elements of coll1 with corresponding elements of coll2 deque<int>::iterator pos; pos = swap_ranges (coll1.begin(), coll1.end(), // first range coll2.begin()); // second range PRINT_ELEMENTS(coll1,"\ncoll1: "); PRINT_ELEMENTS(coll2,"coll2: "); if (pos != coll2.end()) { cout << "first element not modified: " << *pos << endl; } // mirror first three with last three elements in coll2 swap_ranges (coll2.begin(), coll2.begin()+3, // first range coll2.rbegin()); // second range PRINT_ELEMENTS(coll2,"\ncoll2: "); }
33.255814
70
0.616783
[ "vector" ]
54d95ed5bf9d0b33d628ac9410c73f6e0aa54f0f
6,522
cxx
C++
VideoIO/qSlicerVideoIOModuleWidget.cxx
Sunderlandkyl/SlicerIGSIO
289276c90994fc39a7fb0daa32531220d95117eb
[ "BSD-3-Clause" ]
null
null
null
VideoIO/qSlicerVideoIOModuleWidget.cxx
Sunderlandkyl/SlicerIGSIO
289276c90994fc39a7fb0daa32531220d95117eb
[ "BSD-3-Clause" ]
null
null
null
VideoIO/qSlicerVideoIOModuleWidget.cxx
Sunderlandkyl/SlicerIGSIO
289276c90994fc39a7fb0daa32531220d95117eb
[ "BSD-3-Clause" ]
null
null
null
/*============================================================================== Copyright (c) Laboratory for Percutaneous Surgery (PerkLab) Queen's University, Kingston, ON, Canada. All Rights Reserved. See COPYRIGHT.txt or http://www.slicer.org/copyright/copyright.txt for details. Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. This file was originally developed by Kyle Sunderland, PerkLab, Queen's University and was supported through CANARIE's Research Software Program, and Cancer Care Ontario. ==============================================================================*/ // Qt includes #include <QDebug> #include <QStandardItemModel> #include <QTreeView> #include <QTextEdit> // SlicerQt includes #include "qSlicerVideoIOModuleWidget.h" #include "ui_qSlicerVideoIOModule.h" // vtkAddon includes #include <vtkStreamingVolumeCodecFactory.h> // SequenceMRML includes #include <vtkMRMLSequenceNode.h> // SlicerIGSIOCommon includes #include "vtkSlicerIGSIOCommon.h" // qMRMLWidgets includes #include <qMRMLNodeFactory.h> enum { PARAMETER_VALUE_COLUMN=0, PARAMETER_DESCRIPTION_COLUMN, }; //----------------------------------------------------------------------------- /// \ingroup Slicer_QtModules_VideoIO class qSlicerVideoIOModuleWidgetPrivate: public Ui_qSlicerVideoIOModule { Q_DECLARE_PUBLIC(qSlicerVideoIOModuleWidget); protected: qSlicerVideoIOModuleWidget* const q_ptr; public: qSlicerVideoIOModuleWidgetPrivate(qSlicerVideoIOModuleWidget& object); ~qSlicerVideoIOModuleWidgetPrivate(); }; //----------------------------------------------------------------------------- // qSlicerVideoIOModuleWidgetPrivate methods //----------------------------------------------------------------------------- qSlicerVideoIOModuleWidgetPrivate::qSlicerVideoIOModuleWidgetPrivate(qSlicerVideoIOModuleWidget& object) : q_ptr(&object) { } //----------------------------------------------------------------------------- qSlicerVideoIOModuleWidgetPrivate::~qSlicerVideoIOModuleWidgetPrivate() { } //----------------------------------------------------------------------------- // qSlicerVideoIOModuleWidget methods //----------------------------------------------------------------------------- qSlicerVideoIOModuleWidget::qSlicerVideoIOModuleWidget(QWidget* _parent) : Superclass( _parent ) , d_ptr( new qSlicerVideoIOModuleWidgetPrivate(*this) ) { } //----------------------------------------------------------------------------- qSlicerVideoIOModuleWidget::~qSlicerVideoIOModuleWidget() { } //----------------------------------------------------------------------------- void qSlicerVideoIOModuleWidget::setup() { Q_D(qSlicerVideoIOModuleWidget); d->setupUi(this); this->Superclass::setup(); connect(d->EncodeButton, SIGNAL(clicked()), this, SLOT(encodeVideo())); connect(d->CodecSelector, SIGNAL(currentIndexChanged(const QString &)), this, SLOT(onCodecChanged(QString))); std::vector<std::string> codecFourCCs = vtkStreamingVolumeCodecFactory::GetInstance()->GetStreamingCodecFourCCs(); QStringList codecs; for (std::vector<std::string>::iterator codecIt = codecFourCCs.begin(); codecIt != codecFourCCs.end(); ++codecIt) { codecs << QString::fromStdString(*codecIt); } d->CodecSelector->addItems(codecs); } //----------------------------------------------------------------------------- void qSlicerVideoIOModuleWidget::onCodecChanged(const QString &codecFourCC) { Q_D(qSlicerVideoIOModuleWidget); d->EncodingParameterTable->setRowCount(0); vtkSmartPointer<vtkStreamingVolumeCodec> codec = vtkSmartPointer<vtkStreamingVolumeCodec> ::Take( vtkStreamingVolumeCodecFactory::GetInstance()->CreateCodecByFourCC(codecFourCC.toStdString())); if (!codec) { return; } std::vector<std::string> parameterNames = codec->GetAvailiableParameterNames(); QStringList parameters; for (std::vector<std::string>::iterator parameterIt = parameterNames.begin(); parameterIt != parameterNames.end(); ++parameterIt) { parameters << QString::fromStdString(*parameterIt); } d->EncodingParameterTable->setRowCount(parameterNames.size()); d->EncodingParameterTable->setVerticalHeaderLabels(parameters); int currentRow = 0; for (std::vector<std::string>::iterator parameterIt = parameterNames.begin(); parameterIt != parameterNames.end(); ++parameterIt) { std::string value; codec->GetParameter(*parameterIt, value); QTextEdit* textEdit = new QTextEdit(d->EncodingParameterTable); textEdit->setText(QString::fromStdString(value)); d->EncodingParameterTable->setCellWidget(currentRow, PARAMETER_VALUE_COLUMN, textEdit); QString description = QString::fromStdString(codec->GetParameterDescription(*parameterIt)); QLabel* descriptionLabel = new QLabel(d->EncodingParameterTable); descriptionLabel->setText(description); d->EncodingParameterTable->setCellWidget(currentRow, PARAMETER_DESCRIPTION_COLUMN, descriptionLabel); ++currentRow; } } //----------------------------------------------------------------------------- void qSlicerVideoIOModuleWidget::encodeVideo() { Q_D(qSlicerVideoIOModuleWidget); vtkMRMLSequenceNode* sequenceNode = vtkMRMLSequenceNode::SafeDownCast(d->VideoNodeSelector->currentNode()); if (!sequenceNode) { return; } std::map<std::string, std::string> parameters; for (int i = 0; i < d->EncodingParameterTable->rowCount(); ++i) { std::string parameterName = d->EncodingParameterTable->verticalHeaderItem(i)->text().toStdString(); QTextEdit* valueTextEdit = qobject_cast<QTextEdit*>(d->EncodingParameterTable->cellWidget(i, PARAMETER_VALUE_COLUMN)); std::string parameterValue = valueTextEdit->toPlainText().toStdString(); if (parameterValue == "") { continue; } parameters[parameterName] = parameterValue; } std::string encoding = d->CodecSelector->currentText().toStdString(); vtkSlicerIGSIOCommon::ReEncodeVideoSequence(sequenceNode, 0, -1, encoding, parameters, true); } //----------------------------------------------------------------------------- void qSlicerVideoIOModuleWidget::setMRMLScene(vtkMRMLScene* scene) { Q_D(qSlicerVideoIOModuleWidget); this->Superclass::setMRMLScene(scene); if (scene == NULL) { return; } }
34.326316
131
0.648574
[ "object", "vector" ]
54dc4a06080c6055c52b58ef1e2fb80cefb0a3e7
1,454
cpp
C++
CountAndSay.cpp
hgfeaon/leetcode
1e2a562bd8341fc57a02ecff042379989f3361ea
[ "BSD-3-Clause" ]
null
null
null
CountAndSay.cpp
hgfeaon/leetcode
1e2a562bd8341fc57a02ecff042379989f3361ea
[ "BSD-3-Clause" ]
null
null
null
CountAndSay.cpp
hgfeaon/leetcode
1e2a562bd8341fc57a02ecff042379989f3361ea
[ "BSD-3-Clause" ]
null
null
null
#include <iostream> #include <cstdlib> #include <vector> #include <string> using namespace std; class Solution { public: string countAndSay(int n) { vector<int> num; num2digit(1, num); vector<int> tmp; for (int i = 1; i<n; i++) { int last = num[0]; int cur = last; int count= 1; for (int i=1; i < num.size(); i++) { cur = num[i]; if (cur != last) { num2digit(count, tmp); tmp.push_back(last); last = cur; count = 1; } else { count++; } } num2digit(count, tmp); tmp.push_back(cur); swap(num, tmp); tmp.clear(); } string res; for (int i=0; i<num.size(); i++) { res.push_back((char)(num[i] + '0')); } return res; } void num2digit(int n, vector<int> &digits) { vector<int> res; if (n < 0) { n = -n; } do { res.push_back(n % 10); n /= 10; } while (n != 0); for (int i=res.size() - 1; i >= 0; i--) { digits.push_back(res[i]); } } }; int main() { Solution s; string res = s.countAndSay(3); cout<<res<<endl; system("pause"); return 0; }
19.917808
49
0.388583
[ "vector" ]
54de205289407e05cb71d5dafcae65b9213443bf
2,446
cpp
C++
P5589.cpp
AndrewWayne/OI_Learning
0fe8580066704c8d120a131f6186fd7985924dd4
[ "MIT" ]
null
null
null
P5589.cpp
AndrewWayne/OI_Learning
0fe8580066704c8d120a131f6186fd7985924dd4
[ "MIT" ]
null
null
null
P5589.cpp
AndrewWayne/OI_Learning
0fe8580066704c8d120a131f6186fd7985924dd4
[ "MIT" ]
null
null
null
/* * Author: xiaohei_AWM * Date: 10.13 * Motto: Face to the weakness, expect for the strength. */ #include<cstdio> #include<cstring> #include<algorithm> #include<iostream> #include<cstdlib> #include<ctime> #include<utility> #include<functional> #include<cmath> #include<vector> #include<assert.h> using namespace std; #define reg register #define endfile fclose(stdin);fclose(stdout); typedef long long ll; typedef unsigned long long ull; typedef double db; typedef std::pair<int,int> pii; typedef std::pair<ll,ll> pll; namespace IO{ char buf[1<<15],*S,*T; inline char gc(){ if (S==T){ T=(S=buf)+fread(buf,1,1<<15,stdin); if (S==T)return EOF; } return *S++; } inline int read(){ reg int x;reg bool f;reg char c; for(f=0;(c=gc())<'0'||c>'9';f=c=='-'); for(x=c^'0';(c=gc())>='0'&&c<='9';x=(x<<3)+(x<<1)+(c^'0')); return f?-x:x; } inline ll readll(){ reg ll x;reg bool f;reg char c; for(f=0;(c=gc())<'0'||c>'9';f=c=='-'); for(x=c^'0';(c=gc())>='0'&&c<='9';x=(x<<3)+(x<<1)+(c^'0')); return f?-x:x; } } using namespace IO; const long long llINF = 9223372036854775807; const int INF = 2147483647; /* ll mul(ll a, ll b, ll p){ asm( "mul %%ebx\n" "div %%ecx" : "=d"(a) : "a"(a), "b"(b), "c"(p) ); return a; } */ bool visited[1000010]; int t, n; int val[40]; int main(){ val[1] = 0; for(int i = 2; i <= 40; i++){ val[i]++; for(int j = 2; j <= 40 && i * j <= 40; j++){ val[i * j]++; } //cerr << i << ": " << val[i] << endl; } t = read(); while(t--){ memset(visited, 0, sizeof(visited)); n = read(); int sn = sqrt(n); int more = 0; db ans = 0.0; ans = 1.0; //int k = floor(log10(n)/log(k)); for(int i = 2; i <= sn; i++){ if(visited[i]) continue; ll res = i; //cerr << i << ": "; for(int j = 1; res <= n; j++, res = res*i){ if(res > sn) more++; if(res <= sn) visited[res] = true; ans = ans + 1.0 / (db)(1.0 + val[j]); //cerr << res << " "; //cerr << "$: " << val[j] << endl; } //cerr << endl; } ans = ans + n - sn - more; printf("%.6f\n", ans); } return 0; }
24.46
67
0.449714
[ "vector" ]
54e353a840852d9111a1c0928b2aea4d0e5f34f0
11,014
hxx
C++
rutil/SharedCount.hxx
dulton/reSipServer
ac4241df81c1e3eef2e678271ffef4dda1fc6747
[ "Apache-2.0" ]
1
2019-04-15T14:10:58.000Z
2019-04-15T14:10:58.000Z
rutil/SharedCount.hxx
dulton/reSipServer
ac4241df81c1e3eef2e678271ffef4dda1fc6747
[ "Apache-2.0" ]
null
null
null
rutil/SharedCount.hxx
dulton/reSipServer
ac4241df81c1e3eef2e678271ffef4dda1fc6747
[ "Apache-2.0" ]
2
2019-10-31T09:11:09.000Z
2021-09-17T01:00:49.000Z
#if !defined(RESIP_SHAREDCOUNT_HXX) #define RESIP_SHAREDCOUNT_HXX /** @file @brief Defines a threadsafe (shared) reference-count object. @note This implementation is a modified version of shared_count from Boost.org */ #include <memory> // std::auto_ptr, std::allocator #include <functional> // std::less #include <exception> // std::exception #include <new> // std::bad_alloc #include <typeinfo> // std::type_info in get_deleter #include <cstddef> // std::size_t #include "rutil/Lock.hxx" #include "rutil/Mutex.hxx" //#include "rutil/Logger.hxx" #ifdef __BORLANDC__ # pragma warn -8026 // Functions with excep. spec. are not expanded inline # pragma warn -8027 // Functions containing try are not expanded inline #endif namespace resip { // verify that types are complete for increased safety template<class T> inline void checked_delete(T * x) { // intentionally complex - simplification causes regressions typedef char type_must_be_complete[ sizeof(T)? 1: -1 ]; (void) sizeof(type_must_be_complete); delete x; }; template<class T> struct checked_deleter { typedef void result_type; typedef T * argument_type; void operator()(T * x) const { // resip:: disables ADL resip::checked_delete(x); } }; // The standard library that comes with Borland C++ 5.5.1 // defines std::exception and its members as having C calling // convention (-pc). When the definition of bad_weak_ptr // is compiled with -ps, the compiler issues an error. // Hence, the temporary #pragma option -pc below. The version // check is deliberately conservative. #if defined(__BORLANDC__) && __BORLANDC__ == 0x551 # pragma option push -pc #endif class bad_weak_ptr: public std::exception { public: virtual char const * what() const throw() { return "resip::bad_weak_ptr"; } }; #if defined(__BORLANDC__) && __BORLANDC__ == 0x551 # pragma option pop #endif class sp_counted_base { private: public: sp_counted_base(): use_count_(1), weak_count_(1) { } virtual ~sp_counted_base() // nothrow { } // dispose() is called when use_count_ drops to zero, to release // the resources managed by *this. virtual void dispose() = 0; // nothrow // destruct() is called when weak_count_ drops to zero. virtual void destruct() // nothrow { delete this; } virtual void * get_deleter(std::type_info const & ti) = 0; void add_ref_copy() { Lock lock(mMutex); (void)lock; ++use_count_; //GenericLog(Subsystem::SIP, resip::Log::Info, << "********* SharedCount::add_ref_copy: " << use_count_); } void add_ref_lock() { Lock lock(mMutex); (void)lock; // if(use_count_ == 0) throw(resip::bad_weak_ptr()); if (use_count_ == 0) throw resip::bad_weak_ptr(); ++use_count_; //GenericLog(Subsystem::SIP, resip::Log::Info, << "********* SharedCount::add_ref_lock: " << use_count_); } void release() // nothrow { { Lock lock(mMutex); (void)lock; long new_use_count = --use_count_; //GenericLog(Subsystem::SIP, resip::Log::Info, << "********* SharedCount::release: " << use_count_); if(new_use_count != 0) return; } dispose(); weak_release(); } void weak_add_ref() // nothrow { Lock lock(mMutex); (void)lock; ++weak_count_; } void weak_release() // nothrow { long new_weak_count; { Lock lock(mMutex); (void)lock; new_weak_count = --weak_count_; } if(new_weak_count == 0) { destruct(); } } long use_count() const // nothrow { Lock lock(mMutex); (void)lock; return use_count_; } private: sp_counted_base(sp_counted_base const &); sp_counted_base & operator= (sp_counted_base const &); long use_count_; // #shared long weak_count_; // #weak + (#shared != 0) mutable Mutex mMutex; }; // // Borland's Codeguard trips up over the -Vx- option here: // #ifdef __CODEGUARD__ # pragma option push -Vx- #endif template<class P, class D> class sp_counted_base_impl: public sp_counted_base { private: P ptr; // copy constructor must not throw D del; // copy constructor must not throw sp_counted_base_impl(sp_counted_base_impl const &); sp_counted_base_impl & operator= (sp_counted_base_impl const &); typedef sp_counted_base_impl<P, D> this_type; public: // pre: initial_use_count <= initial_weak_count, d(p) must not throw sp_counted_base_impl(P p, D d): ptr(p), del(d) { } virtual void dispose() // nothrow { del(ptr); } virtual void * get_deleter(std::type_info const & ti) { return ti == typeid(D)? &del: 0; } void * operator new(size_t) { return std::allocator<this_type>().allocate(1, static_cast<this_type *>(0)); } void operator delete(void * p) { std::allocator<this_type>().deallocate(static_cast<this_type *>(p), 1); } }; class shared_count { private: sp_counted_base * pi_; public: shared_count(): pi_(0) // nothrow { } template<class P, class D> shared_count(P p, D d): pi_(0) { try { pi_ = new sp_counted_base_impl<P, D>(p, d); } catch(...) { d(p); // delete p throw; } } // auto_ptr<Y> is special cased to provide the strong guarantee template<class Y> explicit shared_count(std::auto_ptr<Y> & r): pi_(new sp_counted_base_impl< Y *, checked_deleter<Y> >(r.get(), checked_deleter<Y>())) { r.release(); } ~shared_count() // nothrow { if(pi_ != 0) pi_->release(); } shared_count(shared_count const & r): pi_(r.pi_) // nothrow { if(pi_ != 0) pi_->add_ref_copy(); } shared_count & operator= (shared_count const & r) // nothrow { sp_counted_base * tmp = r.pi_; if(tmp != 0) tmp->add_ref_copy(); if(pi_ != 0) pi_->release(); pi_ = tmp; return *this; } void swap(shared_count & r) // nothrow { sp_counted_base * tmp = r.pi_; r.pi_ = pi_; pi_ = tmp; } long use_count() const // nothrow { return pi_ != 0? pi_->use_count(): 0; } bool unique() const // nothrow { return use_count() == 1; } friend inline bool operator==(shared_count const & a, shared_count const & b) { return a.pi_ == b.pi_; } friend inline bool operator<(shared_count const & a, shared_count const & b) { return std::less<sp_counted_base *>()(a.pi_, b.pi_); } void * get_deleter(std::type_info const & ti) const { return pi_? pi_->get_deleter(ti): 0; } }; #ifdef __CODEGUARD__ # pragma option pop #endif } // namespace resip #ifdef __BORLANDC__ # pragma warn .8027 // Functions containing try are not expanded inline # pragma warn .8026 // Functions with excep. spec. are not expanded inline #endif #endif // Note: This implementation is a modified version of shared_count from // Boost.org // /* ==================================================================== * * Boost Software License - Version 1.0 - August 17th, 2003 * * Permission is hereby granted, free of charge, to any person or organization * obtaining a copy of the software and accompanying documentation covered by * this license (the "Software") to use, reproduce, display, distribute, * execute, and transmit the Software, and to prepare derivative works of the * Software, and to permit third-parties to whom the Software is furnished to * do so, all subject to the following: * * The copyright notices in the Software and this entire statement, including * the above license grant, this restriction and the following disclaimer, * must be included in all copies of the Software, in whole or in part, and * all derivative works of the Software, unless such copies or derivative * works are solely in the form of machine-executable object code generated by * a source language processor. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT * SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE * FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. * * ==================================================================== */ /* ==================================================================== * The Vovida Software License, Version 1.0 * * Copyright (c) 2000 Vovida Networks, Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The names "VOCAL", "Vovida Open Communication Application Library", * and "Vovida Open Communication Application Library (VOCAL)" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact vocal@vovida.org. * * 4. Products derived from this software may not be called "VOCAL", nor * may "VOCAL" appear in their name, without prior written * permission of Vovida Networks, Inc. * * THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE AND * NON-INFRINGEMENT ARE DISCLAIMED. IN NO EVENT SHALL VOVIDA * NETWORKS, INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT DAMAGES * IN EXCESS OF $1,000, NOR FOR ANY 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. * * ==================================================================== * * This software consists of voluntary contributions made by Vovida * Networks, Inc. and many individuals on behalf of Vovida Networks, * Inc. For more information on Vovida Networks, Inc., please see * <http://www.vovida.org/>. * */
27.60401
135
0.649628
[ "object" ]
54ef55fc504cb262fdd4ddc3c47fbd6404b1d972
7,195
cpp
C++
bin/src/bytrace_impl.cpp
openharmony-gitee-mirror/developtools_bytrace_standard
df3265cebddf04c95fbaad5f8d433362eb7ed1a3
[ "Apache-2.0" ]
null
null
null
bin/src/bytrace_impl.cpp
openharmony-gitee-mirror/developtools_bytrace_standard
df3265cebddf04c95fbaad5f8d433362eb7ed1a3
[ "Apache-2.0" ]
null
null
null
bin/src/bytrace_impl.cpp
openharmony-gitee-mirror/developtools_bytrace_standard
df3265cebddf04c95fbaad5f8d433362eb7ed1a3
[ "Apache-2.0" ]
null
null
null
/* * Copyright (C) 2021 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <atomic> #include <climits> #include <fcntl.h> #include <fstream> #include <mutex> #include <thread> #include <unistd.h> #include <vector> #include "bytrace.h" #include "hilog/log.h" #include "parameter.h" #include "parameters.h" using namespace std; using namespace OHOS::HiviewDFX; #define EXPECTANTLY(exp) (__builtin_expect(!!(exp), true)) #define UNEXPECTANTLY(exp) (__builtin_expect(!!(exp), false)) namespace { int g_markerFd = -1; std::once_flag g_onceFlag; std::atomic<bool> g_isBytraceInit(false); std::atomic<uint64_t> g_tagsProperty(BYTRACE_TAG_NOT_READY); const std::string KEY_TRACE_TAG = "debug.bytrace.tags.enableflags"; const std::string KEY_APP_NUMBER = "debug.bytrace.app_number"; const std::string KEY_RO_DEBUGGABLE = "ro.debuggable"; constexpr int NAME_MAX_SIZE = 1000; static std::vector<std::string> g_markTypes = {"B", "E", "S", "F", "C"}; enum MarkerType { MARKER_BEGIN, MARKER_END, MARKER_ASYNC_BEGIN, MARKER_ASYNC_END, MARKER_INT, MARKER_MAX }; constexpr uint64_t BYTRACE_TAG = 0xd03301; constexpr OHOS::HiviewDFX::HiLogLabel LABEL = {LOG_CORE, BYTRACE_TAG, "BytraceCore"}; static void ParameterChange(const char* key, const char* value, void* context) { HiLog::Info(LABEL, "ParameterChange %{public}s", key); UpdateTraceLabel(); } bool IsAppValid() { // Judge if application-level tracing is enabled. if (OHOS::system::GetBoolParameter(KEY_RO_DEBUGGABLE, 0)) { std::ifstream fs; fs.open("/proc/self/cmdline"); if (!fs.is_open()) { fprintf(stderr, "IsAppValid, open /proc/self/cmdline failed.\n"); return false; } std::string lineStr; std::getline(fs, lineStr); std::string keyPrefix = "debug.bytrace.app_"; int nums = OHOS::system::GetIntParameter<int>(KEY_APP_NUMBER, 0); for (int i = 0; i < nums; i++) { std::string keyStr = keyPrefix + std::to_string(i); std::string val = OHOS::system::GetParameter(keyStr, ""); if (val == "*" || val == lineStr) { fs.close(); return true; } } } return false; } uint64_t GetSysParamTags() { // Get the system parameters of KEY_TRACE_TAG. uint64_t tags = OHOS::system::GetUintParameter<uint64_t>(KEY_TRACE_TAG, 0); if (tags == 0) { fprintf(stderr, "GetUintParameter %s error.\n", KEY_TRACE_TAG.c_str()); return 0; } IsAppValid(); return (tags | BYTRACE_TAG_ALWAYS) & BYTRACE_TAG_VALID_MASK; } // open file "trace_marker". void OpenTraceMarkerFile() { const std::string debugFile = "/sys/kernel/debug/tracing/trace_marker"; const std::string traceFile = "/sys/kernel/tracing/trace_marker"; g_markerFd = open(debugFile.c_str(), O_WRONLY | O_CLOEXEC); if (g_markerFd == -1) { g_markerFd = open(traceFile.c_str(), O_WRONLY | O_CLOEXEC); if (g_markerFd == -1) { HiLog::Error(LABEL, "open trace file %{public}s failed: %{public}s", traceFile.c_str(), strerror(errno)); g_tagsProperty = 0; return; } } g_tagsProperty = GetSysParamTags(); if (WatchParameter(KEY_TRACE_TAG.c_str(), ParameterChange, nullptr) != 0) { HiLog::Error(LABEL, "WatchParameter %{public}s failed", KEY_TRACE_TAG.c_str()); return; } g_isBytraceInit = true; } }; // namespace inline void AddBytraceMarker(MarkerType type, uint64_t tag, std::string name, std::string value) { if (UNEXPECTANTLY(!g_isBytraceInit)) { std::call_once(g_onceFlag, OpenTraceMarkerFile); } if (UNEXPECTANTLY(g_tagsProperty & tag)) { // record fomart: "type|pid|name value". std::string record = g_markTypes[type] + "|"; record += std::to_string(getpid()) + "|"; record += (name.size() < NAME_MAX_SIZE) ? name : name.substr(0, NAME_MAX_SIZE); record += " " + value; write(g_markerFd, record.c_str(), record.size()); } } void UpdateTraceLabel() { if (!g_isBytraceInit) { return; } g_tagsProperty = GetSysParamTags(); } void StartTrace(uint64_t label, const string& value, float limit) { string traceName = "H:" + value; AddBytraceMarker(MARKER_BEGIN, label, traceName, ""); } void StartTraceDebug(uint64_t label, const string& value, float limit) { #if (TRACE_LEVEL >= DEBUG_LEVEL) string traceName = "H:" + value + GetHiTraceInfo(); AddBytraceMarker(MARKER_BEGIN, label, traceName, ""); #endif } void FinishTrace(uint64_t label) { AddBytraceMarker(MARKER_END, label, "", ""); } void FinishTraceDebug(uint64_t label) { #if (TRACE_LEVEL >= DEBUG_LEVEL) AddBytraceMarker(MARKER_END, label, "", ""); #endif } void StartAsyncTrace(uint64_t label, const string& value, int32_t taskId, float limit) { string traceName = "H:" + value; AddBytraceMarker(MARKER_ASYNC_BEGIN, label, traceName, std::to_string(taskId)); } void StartAsyncTraceDebug(uint64_t label, const string& value, int32_t taskId, float limit) { #if (TRACE_LEVEL >= DEBUG_LEVEL) string traceName = "H:" + value; AddBytraceMarker(MARKER_ASYNC_BEGIN, label, traceName, std::to_string(taskId)); #endif } void FinishAsyncTrace(uint64_t label, const string& value, int32_t taskId) { string traceName = "H:" + value; AddBytraceMarker(MARKER_ASYNC_END, label, traceName, std::to_string(taskId)); } void FinishAsyncTraceDebug(uint64_t label, const string& value, int32_t taskId) { #if (TRACE_LEVEL >= DEBUG_LEVEL) string traceName = "H:" + value; AddBytraceMarker(MARKER_ASYNC_END, label, traceName, std::to_string(taskId)); #endif } void MiddleTrace(uint64_t label, const string& beforeValue, const std::string& afterValue) { string traceName = "H:" + afterValue; AddBytraceMarker(MARKER_END, label, "", ""); AddBytraceMarker(MARKER_BEGIN, label, traceName, ""); } void MiddleTraceDebug(uint64_t label, const string& beforeValue, const std::string& afterValue) { #if (TRACE_LEVEL >= DEBUG_LEVEL) string traceName = "H:" + afterValue + GetTraceInfo(); AddBytraceMarker(MARKER_END, label, "", ""); AddBytraceMarker(MARKER_BEGIN, label, traceName, ""); #endif } void CountTrace(uint64_t label, const string& name, int64_t count) { string traceName = "H:" + name; AddBytraceMarker(MARKER_INT, label, traceName, std::to_string(count)); } void CountTraceDebug(uint64_t label, const string& name, int64_t count) { #if (TRACE_LEVEL >= DEBUG_LEVEL) string traceName = "H:" + name; AddBytraceMarker(MARKER_INT, label, traceName, std::to_string(count)); #endif }
31.557018
117
0.679639
[ "vector" ]
54fb3440bfeb6f876aeb28b01067aef932ed47d2
5,540
cpp
C++
algorithm/heapsort.cpp
LiuqingYang/simple-algorithm
729a9736c2fbcee9c14a041dbcdc04af4fc94155
[ "Apache-2.0" ]
2
2015-03-28T18:39:25.000Z
2015-04-19T16:04:59.000Z
algorithm/heapsort.cpp
LiuqingYang/simple-algorithm
729a9736c2fbcee9c14a041dbcdc04af4fc94155
[ "Apache-2.0" ]
null
null
null
algorithm/heapsort.cpp
LiuqingYang/simple-algorithm
729a9736c2fbcee9c14a041dbcdc04af4fc94155
[ "Apache-2.0" ]
null
null
null
/* Refer to: Introduction to Algorithms Chapter 6 Heap relate functions Liuqing Yang<yllqq#outlook.com> Compile with VS2010+ or gcc(-std=c++11) */ #include <stdio.h> #include <vector> #include <list> #include <algorithm> #include <assert.h> using namespace std; template<class T> class Heap { public: Heap(vector<T> in = vector<T>()) : vt(in) , heapsize(in.size()) { } size_t parent(size_t i) {return i / 2;} size_t left(size_t i) {i <<= 1; return i;} size_t right(size_t i) {i <<= 1; return ++i;} void max_heapify(size_t i); void min_heapify(size_t i); void build_max_heap(); void build_min_heap(); void heapsort(); //以下5个适用于最大堆 T heap_maximum(); T heap_extract_max(); void heap_increase_key(size_t i, T key); void max_heap_insert(T key); void heap_delete(size_t i); //以下4个适用于最小堆 T heap_minimum(); T heap_extract_min(); void heap_decrease_key(size_t i, T key); void min_heap_insert(T key); T& operator[](size_t i) {return vt[i-1];} size_t size() {return heapsize;} private: vector<T> vt; size_t heapsize; }; template<class T> void Heap<T>::max_heapify(size_t i) { assert(i <= size()); while(1) { size_t l = left(i); size_t r = right(i); size_t largest; if(l <= size() && (*this)[l] > (*this)[i]) largest = l; else largest = i; if(r <= size() && (*this)[r] > (*this)[largest]) largest = r; if(largest == i) return; swap((*this)[i], (*this)[largest]); i = largest; } } template<class T> void Heap<T>::min_heapify(size_t i) { assert(i <= size()); while(1) { size_t l = left(i); size_t r = right(i); size_t smallest; if(l <= size() && (*this)[l] < (*this)[i]) smallest = l; else smallest = i; if(r <= size() && (*this)[r] < (*this)[smallest]) smallest = r; if(smallest == i) return; swap((*this)[i], (*this)[smallest]); i = smallest; } } template<class T> void Heap<T>::build_max_heap() { for(size_t i = size() / 2; i > 0; i--) max_heapify(i); } template<class T> void Heap<T>::build_min_heap() { for(size_t i = size() / 2; i > 0; i--) min_heapify(i); } template<class T> void Heap<T>::heapsort() { build_max_heap(); for(int i = size(); i >= 2; i--) { swap((*this)[1], (*this)[i]); heapsize--; max_heapify(1); } } template<class T> T Heap<T>::heap_maximum() { return (*this)[1]; } template<class T> T Heap<T>::heap_extract_max() { assert(size()); T maxele = (*this)[1]; (*this)[1] = (*this)[size()]; heapsize--; vt.pop_back(); max_heapify(1); return maxele; } template<class T> void Heap<T>::heap_increase_key(size_t i, T key) { assert(key >= (*this)[i]); (*this)[i] = key; while(i > 1 && (*this)[parent(i)] < (*this)[i]) { swap((*this)[i], (*this)[parent(i)]); i = parent(i); } } template<class T> void Heap<T>::max_heap_insert(T key) { size_t i = ++heapsize; vt.push_back(key); while(i > 1 && (*this)[parent(i)] < (*this)[i]) { swap((*this)[i], (*this)[parent(i)]); i = parent(i); } } template<class T> void Heap<T>::heap_delete(size_t i) { assert(i != 0 && i <= size()); (*this)[i] = (*this)[size()]; vt.pop_back(); heapsize--; max_heapify(i); } template<class T> T Heap<T>::heap_minimum() { return (*this)[1]; } template<class T> T Heap<T>::heap_extract_min() { assert(size()); T minele = (*this)[1]; (*this)[1] = (*this)[size()]; heapsize--; vt.pop_back(); if(heapsize) min_heapify(1); return minele; } template<class T> void Heap<T>::heap_decrease_key(size_t i, T key) { assert(key <= (*this)[i]); (*this)[i] = key; while(i > 1 && (*this)[parent(i)] > (*this)[i]) { swap((*this)[i], (*this)[parent(i)]); i = parent(i); } } template<class T> void Heap<T>::min_heap_insert(T key) { size_t i = ++heapsize; vt.push_back(key); while(i > 1 && (*this)[parent(i)] > (*this)[i]) { swap((*this)[i], (*this)[parent(i)]); i = parent(i); } } template<class T> class mergelists { public: struct tkpair { T data; size_t pos; tkpair(T& in, size_t p) : data(in), pos(p) { } bool operator< (const tkpair& sec) {return data < sec.data;} bool operator> (const tkpair& sec) {return data > sec.data;} tkpair& operator=(const tkpair& in) { if(&in == this) return *this; data = in.data; pos = in.pos; return *this; } }; mergelists(vector<list<T>>& in) : vl(in) { it = vector<typename list<T>::iterator>(in.size()); for(size_t i = 0; i < vl.size(); i++) { it[i] = vl[i].begin(); if(it[i] != vl[i].end()){ hp.min_heap_insert(tkpair(*it[i], i)); ++it[i];; } } } bool pop(T& val) { if(hp.size() == 0) return false; tkpair tmp = hp.heap_extract_min(); if(it[tmp.pos] != vl[tmp.pos].end()){ hp.min_heap_insert(tkpair(*it[tmp.pos], tmp.pos)); ++it[tmp.pos]; } val = tmp.data; return true; } private: vector<list<T>>& vl; vector<typename list<T>::iterator> it; Heap<tkpair> hp; }; void f() { list<int> after; vector<list<int>> li(88); for(int i = 0; i < 100; i++) for(size_t j = 0; j < li.size(); j++) li[j].push_back(rand()); for(size_t j = 0; j < li.size(); j++) li[j].sort(); mergelists<int> ml(li); int tmp; while(ml.pop(tmp)) after.push_back(tmp); } int main(int argc, char* argv[]) { f(); vector<int> vi(20); for(int i = 0; i < 20; i++) vi[i] = i; Heap<int> hp(vi); hp.build_max_heap(); int j =hp.heap_maximum(); j = hp.heap_extract_max(); hp.heap_increase_key(5, 22); hp.max_heap_insert(67); hp.heap_delete(3); hp.heap_delete(3); hp.build_min_heap(); j = hp.heap_minimum(); j = hp.heap_extract_min(); hp.heap_decrease_key(5, -2); hp.min_heap_insert(-66); }
18.528428
68
0.597292
[ "vector" ]
070e75ab97319acb541573993cb1864e5378ed8b
4,445
hpp
C++
src/common/comm/l0/comm_context.hpp
xwu99/oneCCL
6a98d9d1883c134fd03e825f41db508cc38bf251
[ "Apache-2.0" ]
2
2021-09-23T04:56:36.000Z
2021-11-12T11:51:55.000Z
src/common/comm/l0/comm_context.hpp
xwu99/oneCCL
6a98d9d1883c134fd03e825f41db508cc38bf251
[ "Apache-2.0" ]
null
null
null
src/common/comm/l0/comm_context.hpp
xwu99/oneCCL
6a98d9d1883c134fd03e825f41db508cc38bf251
[ "Apache-2.0" ]
null
null
null
/* Copyright 2016-2020 Intel Corporation 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 "oneapi/ccl/aliases.hpp" #include "oneapi/ccl/device_types.hpp" #include "oneapi/ccl/type_traits.hpp" #include "oneapi/ccl/types_policy.hpp" #include "oneapi/ccl/comm_split_attr_ids.hpp" #include "oneapi/ccl/comm_split_attr_ids_traits.hpp" #include "oneapi/ccl/comm_split_attr.hpp" #include "oneapi/ccl/coll_attr_ids.hpp" #include "oneapi/ccl/coll_attr_ids_traits.hpp" #include "oneapi/ccl/coll_attr.hpp" #include "oneapi/ccl/stream_attr_ids.hpp" #include "oneapi/ccl/stream_attr_ids_traits.hpp" #include "oneapi/ccl/stream.hpp" #include "oneapi/ccl/event.hpp" #include "oneapi/ccl/communicator.hpp" #include "common/comm/l0/comm_context_id.hpp" #include "common/comm/comm_interface.hpp" namespace ccl { namespace detail { class environment; } class host_communicator; struct gpu_comm_attr; using shared_communicator_t = std::shared_ptr<host_communicator>; class comm_group { public: friend class ccl::detail::environment; friend struct group_context; using context_t = typename unified_context_type::ccl_native_t; ~comm_group(); /** * Device Communicator creation API: single communicator creation, based on @device */ template <class DeviceType, class ContextType, typename std::enable_if<not std::is_same<typename std::remove_cv<DeviceType>::type, ccl::device_index_type>::value, int>::type = 0> ccl::communicator_interface_ptr create_communicator_from_group( const DeviceType& device, const ContextType& context, const comm_split_attr& attr = ccl_empty_attr()); /** * Device Communicator creation API: single communicator creation, based on index @device_id */ template <class DeviceType, class ContextType, typename std::enable_if<std::is_same<typename std::remove_cv<DeviceType>::type, ccl::device_index_type>::value, int>::type = 0> ccl::communicator_interface_ptr create_communicator_from_group( const DeviceType& device_id, const ContextType& context, const comm_split_attr& attr = ccl_empty_attr()); /** * Device Communicator creation vectorized API: * multiple communicator creation, based on devices iterator @InputIt */ template <class InputIt, class ContextType> std::vector<communicator> create_communicators_group(InputIt first, InputIt last, const ContextType& context, comm_split_attr attr = ccl_empty_attr()); /** * Device Communicator creation vectorized API: * multiple communicator creation, based on devices of @Type, packed into container @Container */ template <template <class...> class Container, class Type, class ContextType> std::vector<communicator> create_communicators_group(const Container<Type>& device_ids, const ContextType& context, comm_split_attr attr = ccl_empty_attr()); /** * Return device context allocated during group creation */ //context_native_const_reference_t get_context() const; bool sync_group_size(size_t device_group_size); /* std::string to_string() const; */ const group_unique_key& get_unique_id() const; private: comm_group(ccl::shared_communicator_t comm, size_t current_device_group_size, size_t process_device_group_size, group_unique_key id); std::unique_ptr<gpu_comm_attr> pimpl; }; } // namespace ccl
37.352941
98
0.658043
[ "vector" ]
070f32b6a8656c4ce90bdb36d02269f7d3546be6
6,121
cpp
C++
src/driver.cpp
STEllAR-GROUP/octopus
a1f910d63380e4ebf91198ac2bc2896505ce6146
[ "BSL-1.0" ]
4
2016-01-30T14:47:21.000Z
2017-11-19T19:03:19.000Z
src/driver.cpp
STEllAR-GROUP/octopus
a1f910d63380e4ebf91198ac2bc2896505ce6146
[ "BSL-1.0" ]
null
null
null
src/driver.cpp
STEllAR-GROUP/octopus
a1f910d63380e4ebf91198ac2bc2896505ce6146
[ "BSL-1.0" ]
null
null
null
//////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2012 Bryce Adelstein-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) //////////////////////////////////////////////////////////////////////////////// #include <stdlib.h> #include <hpx/hpx_fwd.hpp> #include <hpx/hpx_init.hpp> #include <hpx/runtime.hpp> #include <hpx/runtime/components/stubs/runtime_support.hpp> #include <hpx/lcos/future.hpp> #include <hpx/lcos/future_wait.hpp> #include <hpx/util/plugin.hpp> //#include <octopus/driver.hpp> #include <octopus/engine/engine_server.hpp> #include <octopus/engine/engine_interface.hpp> using boost::program_options::options_description; using boost::program_options::variables_map; using boost::program_options::value; using hpx::components::stubs::runtime_support; // namespace octopus { extern OCTOPUS_EXPORT int default_main(variables_map& vm); } OCTOPUS_EXPORT int main(int argc, char** argv); int hpx_main(variables_map& vm) { int result = 0; { // For great justice. std::cout << " ___ \n" " ( \\ \\ \n" " / \\ \\ | \\ Octopus: a scalable HPX framework for AMR\n" " \\__(0 0)_/ / \n" " _//||\\\\__/ Copyright (c) 2012 Bryce Adelstein-Lelbach\n" " / | |\\ \\___/ Zach Byerly\n" " \\ | \\ \\__ Dominic Marcello\n" " \\_ \\_ \n" "\n" ; std::cout << "Launching AMR driver...\n" "\n"; /////////////////////////////////////////////////////////////////////// // Read configuration. octopus::config_data cfg = octopus::config_from_ini(); std::cout << cfg << "\n" "\n"; /////////////////////////////////////////////////////////////////////// // Initialize the Octopus engine. hpx::components::component_type type = hpx::components::get_component_type<octopus::engine_server>(); // Find all localities supporting Octopus (except for us). std::vector<hpx::id_type> localities = hpx::find_all_localities(type); OCTOPUS_ASSERT_MSG(!localities.empty(), "no localities supporting Octopus found"); std::cout << "Found " << localities.size() << " usable localities, deploying infrastructure...\n"; // FIXME: Sadly, distributing factory doesn't support constructor args // yet, so we have to do this by hand. std::vector<hpx::future<hpx::id_type> > engines; engines.reserve(localities.size()); /////////////////////////////////////////////////////////////////////// // Define the problem. typedef void (*define_function)( variables_map& , octopus::science_table& ); typedef int (*main_function)( variables_map& ); typedef boost::function<void(define_function)> define_deleter; typedef boost::function<void(main_function)> main_deleter; // Figure out where we are. hpx::util::plugin::dll this_exe(hpx::util::get_executable_filename()); std::pair<define_function, define_deleter> define_p; std::pair<main_function, main_deleter> main_p; try { main_p = this_exe.get<main_function, main_deleter> ("octopus_main"); } catch (std::logic_error& le) { // Ignore the failure. } try { define_p = this_exe.get<define_function, define_deleter> ("octopus_define_problem"); } catch (std::logic_error& le) { // Ignore the failure. } OCTOPUS_ASSERT_MSG(main_p.first, "octopus_main must be defined"); /////////////////////////////////////////////////////////////////////// // Initialize the science table. std::cout << "Initializing science table...\n" << "\n"; hpx::id_type const here = hpx::find_here(); engines.emplace_back( runtime_support::create_component<octopus::engine_server> (here, cfg, octopus::default_science_table(), localities)); // octopus_define_problem(vm, octopus::science()); if (define_p.first) (*define_p.first)(vm, octopus::science()); /////////////////////////////////////////////////////////////////////// // Create an engine on every locality. std::cout << "Creating system components...\n"; bool found_here = false; for (std::size_t i = 0; i < localities.size(); ++i) { if (localities[i] == here) { found_here = true; continue; } engines.emplace_back( runtime_support::create_component_async<octopus::engine_server> (localities[i], octopus::config(), octopus::science(), localities)); } OCTOPUS_ASSERT(found_here); hpx::wait(engines); /////////////////////////////////////////////////////////////////////// // Invoke user entry point or default main. std::cout << "Executing application...\n" "\n"; // result = octopus_main(vm); result = (*main_p.first)(vm); } hpx::finalize(); return result; } int main(int argc, char** argv) { options_description cmdline("Octopus AMR Driver"); /////////////////////////////////////////////////////////////////////////// // Initialize HPX. int r = hpx::init(cmdline, argc, argv); #if !defined(BOOST_MSVC) // We call C99 _Exit to work around problems with 3rd-party libraries using // atexit (HDF5 and visit). ::_Exit(r); #else return r; #endif }
31.880208
83
0.495834
[ "vector" ]
07117ed4fc1927a71a075740f2a0fbb6f10ec461
1,784
hpp
C++
src/Microsoft.DotNet.Wpf/src/WpfGfx/common/DirectXLayer/interfaces/extensions.hpp
txlos/wpf
4004b4e8c8d5c0d5e9de0f1be1fd929c3dee6fa1
[ "MIT" ]
5,937
2018-12-04T16:32:50.000Z
2022-03-31T09:48:37.000Z
src/Microsoft.DotNet.Wpf/src/WpfGfx/common/DirectXLayer/interfaces/extensions.hpp
txlos/wpf
4004b4e8c8d5c0d5e9de0f1be1fd929c3dee6fa1
[ "MIT" ]
4,151
2018-12-04T16:38:19.000Z
2022-03-31T18:41:14.000Z
src/Microsoft.DotNet.Wpf/src/WpfGfx/common/DirectXLayer/interfaces/extensions.hpp
txlos/wpf
4004b4e8c8d5c0d5e9de0f1be1fd929c3dee6fa1
[ "MIT" ]
1,084
2018-12-04T16:24:21.000Z
2022-03-30T13:52:03.000Z
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #pragma once #include "vector3_t.hpp" #include "vector4_t.hpp" #include "quaternion_t.hpp" #include "matrix_t.hpp" #include <vector> #include <type_traits> namespace dxlayer { // Miscellaneous methods that either do not fit well as a member of a vector or matrix // types, or cannot be implemented in one of those types directly due to circular // (header file) inclusion problems arising form the fact that full definitions of // some of these types would be needed at points where they wouldn't yet be available. // These problems could well have been avoided by using pointers instead of objects, but // we choose to take the approach of having a small utility class (this class) // to work around the header-inclusion and definition-availability problems. template<dxapi apiset> class math_extensions_t { public: static quaternion_t<apiset> make_quaternion_from_rotaion_matrix(const matrix_t<apiset>& matrix); static vector3_t<apiset> transform_coord(const vector3_t<apiset>& vector, const matrix_t<apiset>& matrix); static vector3_t<apiset> transform_normal(const vector3_t<apiset>& vector, const matrix_t<apiset>& matrix); static std::vector<vector4_t<apiset>> transform_array( unsigned int out_stride, const std::vector<vector4_t<apiset>>& in, unsigned int in_stride, const matrix_t<apiset>& transformation, unsigned int n); template<typename T> static T to_radian(T degree); static float get_pi(); }; }
40.545455
115
0.714686
[ "vector" ]
0714bc315aaa51df2e8039fb7662328d3255b9b4
634
hpp
C++
src/common/low_precision_transformations/include/low_precision/rt_info/attribute_parameters.hpp
ryanloney/openvino-1
4e0a740eb3ee31062ba0df88fcf438564f67edb7
[ "Apache-2.0" ]
1,127
2018-10-15T14:36:58.000Z
2020-04-20T09:29:44.000Z
src/common/low_precision_transformations/include/low_precision/rt_info/attribute_parameters.hpp
ryanloney/openvino-1
4e0a740eb3ee31062ba0df88fcf438564f67edb7
[ "Apache-2.0" ]
439
2018-10-20T04:40:35.000Z
2020-04-19T05:56:25.000Z
src/common/low_precision_transformations/include/low_precision/rt_info/attribute_parameters.hpp
ryanloney/openvino-1
4e0a740eb3ee31062ba0df88fcf438564f67edb7
[ "Apache-2.0" ]
414
2018-10-17T05:53:46.000Z
2020-04-16T17:29:53.000Z
// Copyright (C) 2018-2022 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #pragma once #include <ngraph/type/element_type.hpp> #include "low_precision/lpt_visibility.hpp" class LP_TRANSFORMATIONS_API AttributeParameters { public: AttributeParameters( const ngraph::element::Type deqPrecision = ngraph::element::f32, const std::vector<ngraph::element::Type> defaultPrecisions = { ngraph::element::u8, ngraph::element::i8 }) : deqPrecision(deqPrecision), defaultPrecisions(defaultPrecisions) {} ngraph::element::Type deqPrecision; std::vector<ngraph::element::Type> defaultPrecisions; };
33.368421
114
0.742902
[ "vector" ]
0716bfc923f821964184c809d98b308a7192db11
5,591
cxx
C++
src/mlio-py/mlio/core/tensor.cxx
ericangelokim/ml-io
b559896ad690f037272c7beedc97af4433134445
[ "Apache-2.0" ]
null
null
null
src/mlio-py/mlio/core/tensor.cxx
ericangelokim/ml-io
b559896ad690f037272c7beedc97af4433134445
[ "Apache-2.0" ]
2
2020-04-08T01:37:44.000Z
2020-04-14T20:14:07.000Z
src/mlio-py/mlio/core/tensor.cxx
ericangelokim/ml-io
b559896ad690f037272c7beedc97af4433134445
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You * may not use this file except in compliance with the License. A copy of * the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file is * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF * ANY KIND, either express or implied. See the License for the specific * language governing permissions and limitations under the License. */ #include "module.h" #include <cstddef> #include <memory> #include <vector> #include "py_buffer.h" #include "py_device_array.h" namespace py = pybind11; using namespace mlio; using namespace pybind11::literals; namespace pymlio { namespace { intrusive_ptr<dense_tensor> make_dense_tensor(size_vector shape, py::buffer &data, std::optional<ssize_vector> strides, bool cpy) { std::unique_ptr<device_array> arr = make_device_array(data, cpy); ssize_vector strds{}; if (strides) { strds = std::move(*strides); } return make_intrusive<dense_tensor>( std::move(shape), std::move(arr), std::move(strds)); } intrusive_ptr<coo_tensor> make_coo_tensor(size_vector shape, py::buffer &data, std::vector<py::buffer> &coords, bool cpy) { std::unique_ptr<device_array> arr = make_device_array(data, cpy); std::vector<std::unique_ptr<device_array>> coordinates{}; coordinates.reserve(coords.size()); for (py::buffer &indices : coords) { coordinates.emplace_back(make_device_array(indices, cpy)); } return make_intrusive<coo_tensor>( std::move(shape), std::move(arr), std::move(coordinates)); } py::buffer_info to_py_buffer(dense_tensor &tsr) { auto buf = py::cast(tsr).attr("data").cast<py::buffer>(); py::buffer_info info = buf.request(/*writable*/ true); info.ndim = static_cast<py::ssize_t>(tsr.shape().size()); info.shape.clear(); info.shape.reserve(tsr.shape().size()); for (auto dim : tsr.shape()) { info.shape.push_back(static_cast<py::ssize_t>(dim)); } info.strides.clear(); info.strides.reserve(tsr.strides().size()); for (auto stride : tsr.strides()) { info.strides.push_back(info.itemsize * stride); } return info; } } // namespace void register_tensors(py::module &m) { py::enum_<data_type>(m, "DataType") .value("SIZE", data_type::size) .value("FLOAT16", data_type::float16) .value("FLOAT32", data_type::float32) .value("FLOAT64", data_type::float64) .value("SINT8", data_type::sint8) .value("SINT16", data_type::sint16) .value("SINT32", data_type::sint32) .value("SINT64", data_type::sint64) .value("UINT8", data_type::uint8) .value("UINT16", data_type::uint16) .value("UINT32", data_type::uint32) .value("UINT64", data_type::uint64) .value("STRING", data_type::string); py::class_<tensor, intrusive_ptr<tensor>>(m, "Tensor", R"( Represents a multi-dimensional array. This is an abstract class that only defines the data type and shape of a tensor. Derived types specify how the tensor data is laid out in memory. )") .def("__repr__", &tensor::repr) .def_property_readonly( "dtype", &tensor::dtype, "Gets the data type of the tensor.") .def_property_readonly( "shape", [](tensor &self) -> py::tuple { return py::cast(self.shape()); }, "Gets the shape of the tensor.") .def_property_readonly( "strides", [](tensor &self) -> py::tuple { return py::cast(self.strides()); }, "Gets the strides of the tensor."); py::class_<dense_tensor, tensor, intrusive_ptr<dense_tensor>>( m, "DenseTensor", py::buffer_protocol(), "Represents a tensor that stores its data in a contiguous memory " "block.") .def(py::init<>(&make_dense_tensor), "shape"_a, "data"_a, "strides"_a = std::nullopt, "copy"_a = true) .def_property_readonly( "data", [](dense_tensor &self) { return py_device_array{wrap_intrusive(&self), self.data()}; }, "Gets the data of the tensor.") .def_buffer(&to_py_buffer); py::class_<coo_tensor, tensor, intrusive_ptr<coo_tensor>>( m, "CooTensor", "Represents a tensor that stores its data in coordinate format.") .def(py::init<>(&make_coo_tensor), "shape"_a, "data"_a, "coords"_a, "copy"_a = true) .def_property_readonly( "data", [](coo_tensor &self) { return py_device_array{wrap_intrusive(&self), self.data()}; }, "Gets the data of the tensor.") .def( "indices", [](coo_tensor &self, std::size_t dim) { return py_device_array{wrap_intrusive(&self), self.indices(dim)}; }, "dim"_a, "Gets the indices for the specified dimension."); } } // namespace pymlio
30.551913
75
0.577535
[ "shape", "vector" ]
0719f871e28373eb50614b0268b70de765df85f1
655
cpp
C++
UVa/uva 11159.cpp
Xi-Plus/OJ-Code
7ff6d691f34c9553d53dc9cddf90ad7dc7092349
[ "MIT" ]
null
null
null
UVa/uva 11159.cpp
Xi-Plus/OJ-Code
7ff6d691f34c9553d53dc9cddf90ad7dc7092349
[ "MIT" ]
null
null
null
UVa/uva 11159.cpp
Xi-Plus/OJ-Code
7ff6d691f34c9553d53dc9cddf90ad7dc7092349
[ "MIT" ]
null
null
null
// By KRT girl xiplus #include <bits/stdc++.h> #define endl '\n' using namespace std; struct T{ int a,b; bool visit; }; int main(){ // ios::sync_with_stdio(false); // cin.tie(0); int t,n; cin>>t; int lsz,rsz; for(int cas=1;cas<=t;cas++){ cin>>lsz; vector<int> l; for(int q=0;q<lsz;q++){ cin>>n; l.push_back(n); } cin>>rsz; vector<int> r; for(int q=0;q<rsz;q++){ cin>>n; r.push_back(n); } vector<T> v; for(int q=0;q<lsz;q++){ for(int w=0;w<rsz;w++){ if(l[q]==0)continue; if(r[w]%l[q]==0){ v.push_back({l[q],r[w],false}); } } } cout<<"Case #"<<cas<<": "<<min(li.size(),ri.size())<<endl; } }
16.375
60
0.523664
[ "vector" ]
071a9424a983ee17e77e954ee17b16e8118caf6c
458,297
cpp
C++
src/main_3600.cpp
v0idp/virtuoso-codegen
6f560f04822c67f092d438a3f484249072c1d21d
[ "Unlicense" ]
null
null
null
src/main_3600.cpp
v0idp/virtuoso-codegen
6f560f04822c67f092d438a3f484249072c1d21d
[ "Unlicense" ]
null
null
null
src/main_3600.cpp
v0idp/virtuoso-codegen
6f560f04822c67f092d438a3f484249072c1d21d
[ "Unlicense" ]
1
2022-03-30T21:07:35.000Z
2022-03-30T21:07:35.000Z
// Autogenerated from CppSourceCreator // Created by Sc2ad // ========================================================================= // Begin includes #include "beatsaber-hook/shared/utils/typedefs.h" // Including type: System.Runtime.CompilerServices.DateTimeConstantAttribute #include "System/Runtime/CompilerServices/DateTimeConstantAttribute.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils.hpp" #include "beatsaber-hook/shared/utils/utils.h" // Completed includes // Autogenerated instance field getter // Get instance field: private System.DateTime date [[deprecated("Use field access instead!")]] ::System::DateTime& System::Runtime::CompilerServices::DateTimeConstantAttribute::dyn_date() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::CompilerServices::DateTimeConstantAttribute::dyn_date"); auto ___internal__instance = this; static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "date"))->offset; return *reinterpret_cast<::System::DateTime*>(reinterpret_cast<char*>(this) + ___internal__field__offset); } // Autogenerated method: System.Runtime.CompilerServices.DateTimeConstantAttribute.get_Value ::Il2CppObject* System::Runtime::CompilerServices::DateTimeConstantAttribute::get_Value() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::CompilerServices::DateTimeConstantAttribute::get_Value"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Runtime::CompilerServices::CustomConstantAttribute*), 7)); return ::il2cpp_utils::RunMethodRethrow<::Il2CppObject*, false>(this, ___internal__method); } // Autogenerated from CppSourceCreator // Created by Sc2ad // ========================================================================= // Begin includes // Including type: System.Runtime.CompilerServices.DecimalConstantAttribute #include "System/Runtime/CompilerServices/DecimalConstantAttribute.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils.hpp" #include "beatsaber-hook/shared/utils/utils.h" // Completed includes // Autogenerated instance field getter // Get instance field: private System.Decimal dec [[deprecated("Use field access instead!")]] ::System::Decimal& System::Runtime::CompilerServices::DecimalConstantAttribute::dyn_dec() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::CompilerServices::DecimalConstantAttribute::dyn_dec"); auto ___internal__instance = this; static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "dec"))->offset; return *reinterpret_cast<::System::Decimal*>(reinterpret_cast<char*>(this) + ___internal__field__offset); } // Autogenerated method: System.Runtime.CompilerServices.DecimalConstantAttribute.get_Value ::System::Decimal System::Runtime::CompilerServices::DecimalConstantAttribute::get_Value() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::CompilerServices::DecimalConstantAttribute::get_Value"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "get_Value", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); return ::il2cpp_utils::RunMethodRethrow<::System::Decimal, false>(this, ___internal__method); } // Autogenerated from CppSourceCreator // Created by Sc2ad // ========================================================================= // Begin includes // Including type: System.Runtime.CompilerServices.ExtensionAttribute #include "System/Runtime/CompilerServices/ExtensionAttribute.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils.hpp" #include "beatsaber-hook/shared/utils/utils.h" // Completed includes // Autogenerated from CppSourceCreator // Created by Sc2ad // ========================================================================= // Begin includes // Including type: System.Runtime.CompilerServices.FixedBufferAttribute #include "System/Runtime/CompilerServices/FixedBufferAttribute.hpp" // Including type: System.Type #include "System/Type.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils.hpp" #include "beatsaber-hook/shared/utils/utils.h" // Completed includes // Autogenerated instance field getter // Get instance field: private System.Type elementType [[deprecated("Use field access instead!")]] ::System::Type*& System::Runtime::CompilerServices::FixedBufferAttribute::dyn_elementType() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::CompilerServices::FixedBufferAttribute::dyn_elementType"); auto ___internal__instance = this; static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "elementType"))->offset; return *reinterpret_cast<::System::Type**>(reinterpret_cast<char*>(this) + ___internal__field__offset); } // Autogenerated instance field getter // Get instance field: private System.Int32 length [[deprecated("Use field access instead!")]] int& System::Runtime::CompilerServices::FixedBufferAttribute::dyn_length() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::CompilerServices::FixedBufferAttribute::dyn_length"); auto ___internal__instance = this; static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "length"))->offset; return *reinterpret_cast<int*>(reinterpret_cast<char*>(this) + ___internal__field__offset); } // Autogenerated method: System.Runtime.CompilerServices.FixedBufferAttribute.get_ElementType ::System::Type* System::Runtime::CompilerServices::FixedBufferAttribute::get_ElementType() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::CompilerServices::FixedBufferAttribute::get_ElementType"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "get_ElementType", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); return ::il2cpp_utils::RunMethodRethrow<::System::Type*, false>(this, ___internal__method); } // Autogenerated method: System.Runtime.CompilerServices.FixedBufferAttribute.get_Length int System::Runtime::CompilerServices::FixedBufferAttribute::get_Length() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::CompilerServices::FixedBufferAttribute::get_Length"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "get_Length", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); return ::il2cpp_utils::RunMethodRethrow<int, false>(this, ___internal__method); } // Autogenerated from CppSourceCreator // Created by Sc2ad // ========================================================================= // Begin includes // Including type: System.Runtime.CompilerServices.InternalsVisibleToAttribute #include "System/Runtime/CompilerServices/InternalsVisibleToAttribute.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils.hpp" #include "beatsaber-hook/shared/utils/utils.h" // Completed includes // Autogenerated instance field getter // Get instance field: private System.String _assemblyName [[deprecated("Use field access instead!")]] ::StringW& System::Runtime::CompilerServices::InternalsVisibleToAttribute::dyn__assemblyName() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::CompilerServices::InternalsVisibleToAttribute::dyn__assemblyName"); auto ___internal__instance = this; static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "_assemblyName"))->offset; return *reinterpret_cast<::StringW*>(reinterpret_cast<char*>(this) + ___internal__field__offset); } // Autogenerated instance field getter // Get instance field: private System.Boolean _allInternalsVisible [[deprecated("Use field access instead!")]] bool& System::Runtime::CompilerServices::InternalsVisibleToAttribute::dyn__allInternalsVisible() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::CompilerServices::InternalsVisibleToAttribute::dyn__allInternalsVisible"); auto ___internal__instance = this; static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "_allInternalsVisible"))->offset; return *reinterpret_cast<bool*>(reinterpret_cast<char*>(this) + ___internal__field__offset); } // Autogenerated method: System.Runtime.CompilerServices.InternalsVisibleToAttribute.get_AssemblyName ::StringW System::Runtime::CompilerServices::InternalsVisibleToAttribute::get_AssemblyName() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::CompilerServices::InternalsVisibleToAttribute::get_AssemblyName"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "get_AssemblyName", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); return ::il2cpp_utils::RunMethodRethrow<::StringW, false>(this, ___internal__method); } // Autogenerated method: System.Runtime.CompilerServices.InternalsVisibleToAttribute.get_AllInternalsVisible bool System::Runtime::CompilerServices::InternalsVisibleToAttribute::get_AllInternalsVisible() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::CompilerServices::InternalsVisibleToAttribute::get_AllInternalsVisible"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "get_AllInternalsVisible", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); return ::il2cpp_utils::RunMethodRethrow<bool, false>(this, ___internal__method); } // Autogenerated method: System.Runtime.CompilerServices.InternalsVisibleToAttribute.set_AllInternalsVisible void System::Runtime::CompilerServices::InternalsVisibleToAttribute::set_AllInternalsVisible(bool value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::CompilerServices::InternalsVisibleToAttribute::set_AllInternalsVisible"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "set_AllInternalsVisible", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(value)}))); ::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, value); } // Autogenerated from CppSourceCreator // Created by Sc2ad // ========================================================================= // Begin includes // Including type: System.Runtime.CompilerServices.FriendAccessAllowedAttribute #include "System/Runtime/CompilerServices/FriendAccessAllowedAttribute.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils.hpp" #include "beatsaber-hook/shared/utils/utils.h" // Completed includes // Autogenerated from CppSourceCreator // Created by Sc2ad // ========================================================================= // Begin includes // Including type: System.Runtime.CompilerServices.TypeDependencyAttribute #include "System/Runtime/CompilerServices/TypeDependencyAttribute.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils.hpp" #include "beatsaber-hook/shared/utils/utils.h" // Completed includes // Autogenerated instance field getter // Get instance field: private System.String typeName [[deprecated("Use field access instead!")]] ::StringW& System::Runtime::CompilerServices::TypeDependencyAttribute::dyn_typeName() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::CompilerServices::TypeDependencyAttribute::dyn_typeName"); auto ___internal__instance = this; static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "typeName"))->offset; return *reinterpret_cast<::StringW*>(reinterpret_cast<char*>(this) + ___internal__field__offset); } // Autogenerated from CppSourceCreator // Created by Sc2ad // ========================================================================= // Begin includes // Including type: System.Runtime.CompilerServices.UnsafeValueTypeAttribute #include "System/Runtime/CompilerServices/UnsafeValueTypeAttribute.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils.hpp" #include "beatsaber-hook/shared/utils/utils.h" // Completed includes // Autogenerated from CppSourceCreator // Created by Sc2ad // ========================================================================= // Begin includes // Including type: System.Runtime.CompilerServices.StringFreezingAttribute #include "System/Runtime/CompilerServices/StringFreezingAttribute.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils.hpp" #include "beatsaber-hook/shared/utils/utils.h" // Completed includes // Autogenerated from CppSourceCreator // Created by Sc2ad // ========================================================================= // Begin includes #include "beatsaber-hook/shared/utils/typedefs.h" // Including type: System.Runtime.CompilerServices.JitHelpers #include "System/Runtime/CompilerServices/JitHelpers.hpp" // Including type: System.ValueType #include "System/ValueType.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils.hpp" #include "beatsaber-hook/shared/utils/utils.h" // Completed includes // Autogenerated from CppSourceCreator // Created by Sc2ad // ========================================================================= // Begin includes #include "beatsaber-hook/shared/utils/typedefs.h" // Including type: System.Runtime.CompilerServices.RuntimeHelpers #include "System/Runtime/CompilerServices/RuntimeHelpers.hpp" // Including type: System.Array #include "System/Array.hpp" // Including type: System.IntPtr #include "System/IntPtr.hpp" // Including type: System.RuntimeFieldHandle #include "System/RuntimeFieldHandle.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils.hpp" #include "beatsaber-hook/shared/utils/utils.h" // Completed includes // Autogenerated method: System.Runtime.CompilerServices.RuntimeHelpers.get_OffsetToStringData int System::Runtime::CompilerServices::RuntimeHelpers::get_OffsetToStringData() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::CompilerServices::RuntimeHelpers::get_OffsetToStringData"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Runtime.CompilerServices", "RuntimeHelpers", "get_OffsetToStringData", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); return ::il2cpp_utils::RunMethodRethrow<int, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method); } // Autogenerated method: System.Runtime.CompilerServices.RuntimeHelpers.InitializeArray void System::Runtime::CompilerServices::RuntimeHelpers::InitializeArray(::System::Array* array, ::System::IntPtr fldHandle) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::CompilerServices::RuntimeHelpers::InitializeArray"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Runtime.CompilerServices", "RuntimeHelpers", "InitializeArray", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(array), ::il2cpp_utils::ExtractType(fldHandle)}))); ::il2cpp_utils::RunMethodRethrow<void, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method, array, fldHandle); } // Autogenerated method: System.Runtime.CompilerServices.RuntimeHelpers.InitializeArray void System::Runtime::CompilerServices::RuntimeHelpers::InitializeArray(::System::Array* array, ::System::RuntimeFieldHandle fldHandle) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::CompilerServices::RuntimeHelpers::InitializeArray"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Runtime.CompilerServices", "RuntimeHelpers", "InitializeArray", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(array), ::il2cpp_utils::ExtractType(fldHandle)}))); ::il2cpp_utils::RunMethodRethrow<void, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method, array, fldHandle); } // Autogenerated method: System.Runtime.CompilerServices.RuntimeHelpers.GetHashCode int System::Runtime::CompilerServices::RuntimeHelpers::GetHashCode(::Il2CppObject* o) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::CompilerServices::RuntimeHelpers::GetHashCode"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Runtime.CompilerServices", "RuntimeHelpers", "GetHashCode", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(o)}))); return ::il2cpp_utils::RunMethodRethrow<int, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method, o); } // Autogenerated method: System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue ::Il2CppObject* System::Runtime::CompilerServices::RuntimeHelpers::GetObjectValue(::Il2CppObject* obj) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::CompilerServices::RuntimeHelpers::GetObjectValue"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Runtime.CompilerServices", "RuntimeHelpers", "GetObjectValue", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(obj)}))); return ::il2cpp_utils::RunMethodRethrow<::Il2CppObject*, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method, obj); } // Autogenerated method: System.Runtime.CompilerServices.RuntimeHelpers.SufficientExecutionStack bool System::Runtime::CompilerServices::RuntimeHelpers::SufficientExecutionStack() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::CompilerServices::RuntimeHelpers::SufficientExecutionStack"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Runtime.CompilerServices", "RuntimeHelpers", "SufficientExecutionStack", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); return ::il2cpp_utils::RunMethodRethrow<bool, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method); } // Autogenerated method: System.Runtime.CompilerServices.RuntimeHelpers.TryEnsureSufficientExecutionStack bool System::Runtime::CompilerServices::RuntimeHelpers::TryEnsureSufficientExecutionStack() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::CompilerServices::RuntimeHelpers::TryEnsureSufficientExecutionStack"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Runtime.CompilerServices", "RuntimeHelpers", "TryEnsureSufficientExecutionStack", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); return ::il2cpp_utils::RunMethodRethrow<bool, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method); } // Autogenerated method: System.Runtime.CompilerServices.RuntimeHelpers.PrepareConstrainedRegions void System::Runtime::CompilerServices::RuntimeHelpers::PrepareConstrainedRegions() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::CompilerServices::RuntimeHelpers::PrepareConstrainedRegions"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Runtime.CompilerServices", "RuntimeHelpers", "PrepareConstrainedRegions", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); ::il2cpp_utils::RunMethodRethrow<void, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method); } // Autogenerated from CppSourceCreator // Created by Sc2ad // ========================================================================= // Begin includes #include "beatsaber-hook/shared/utils/typedefs.h" // Including type: System.Runtime.CompilerServices.Unsafe #include "System/Runtime/CompilerServices/Unsafe.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils.hpp" #include "beatsaber-hook/shared/utils/utils.h" // Completed includes // Autogenerated from CppSourceCreator // Created by Sc2ad // ========================================================================= // Begin includes // Including type: System.Runtime.InteropServices.UnmanagedFunctionPointerAttribute #include "System/Runtime/InteropServices/UnmanagedFunctionPointerAttribute.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils.hpp" #include "beatsaber-hook/shared/utils/utils.h" // Completed includes // Autogenerated instance field getter // Get instance field: private System.Runtime.InteropServices.CallingConvention m_callingConvention [[deprecated("Use field access instead!")]] ::System::Runtime::InteropServices::CallingConvention& System::Runtime::InteropServices::UnmanagedFunctionPointerAttribute::dyn_m_callingConvention() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::UnmanagedFunctionPointerAttribute::dyn_m_callingConvention"); auto ___internal__instance = this; static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "m_callingConvention"))->offset; return *reinterpret_cast<::System::Runtime::InteropServices::CallingConvention*>(reinterpret_cast<char*>(this) + ___internal__field__offset); } // Autogenerated instance field getter // Get instance field: public System.Runtime.InteropServices.CharSet CharSet [[deprecated("Use field access instead!")]] ::System::Runtime::InteropServices::CharSet& System::Runtime::InteropServices::UnmanagedFunctionPointerAttribute::dyn_CharSet() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::UnmanagedFunctionPointerAttribute::dyn_CharSet"); auto ___internal__instance = this; static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "CharSet"))->offset; return *reinterpret_cast<::System::Runtime::InteropServices::CharSet*>(reinterpret_cast<char*>(this) + ___internal__field__offset); } // Autogenerated instance field getter // Get instance field: public System.Boolean BestFitMapping [[deprecated("Use field access instead!")]] bool& System::Runtime::InteropServices::UnmanagedFunctionPointerAttribute::dyn_BestFitMapping() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::UnmanagedFunctionPointerAttribute::dyn_BestFitMapping"); auto ___internal__instance = this; static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "BestFitMapping"))->offset; return *reinterpret_cast<bool*>(reinterpret_cast<char*>(this) + ___internal__field__offset); } // Autogenerated instance field getter // Get instance field: public System.Boolean ThrowOnUnmappableChar [[deprecated("Use field access instead!")]] bool& System::Runtime::InteropServices::UnmanagedFunctionPointerAttribute::dyn_ThrowOnUnmappableChar() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::UnmanagedFunctionPointerAttribute::dyn_ThrowOnUnmappableChar"); auto ___internal__instance = this; static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "ThrowOnUnmappableChar"))->offset; return *reinterpret_cast<bool*>(reinterpret_cast<char*>(this) + ___internal__field__offset); } // Autogenerated instance field getter // Get instance field: public System.Boolean SetLastError [[deprecated("Use field access instead!")]] bool& System::Runtime::InteropServices::UnmanagedFunctionPointerAttribute::dyn_SetLastError() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::UnmanagedFunctionPointerAttribute::dyn_SetLastError"); auto ___internal__instance = this; static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "SetLastError"))->offset; return *reinterpret_cast<bool*>(reinterpret_cast<char*>(this) + ___internal__field__offset); } // Autogenerated from CppSourceCreator // Created by Sc2ad // ========================================================================= // Begin includes // Including type: System.Runtime.InteropServices.DispIdAttribute #include "System/Runtime/InteropServices/DispIdAttribute.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils.hpp" #include "beatsaber-hook/shared/utils/utils.h" // Completed includes // Autogenerated instance field getter // Get instance field: System.Int32 _val [[deprecated("Use field access instead!")]] int& System::Runtime::InteropServices::DispIdAttribute::dyn__val() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::DispIdAttribute::dyn__val"); auto ___internal__instance = this; static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "_val"))->offset; return *reinterpret_cast<int*>(reinterpret_cast<char*>(this) + ___internal__field__offset); } // Autogenerated from CppSourceCreator // Created by Sc2ad // ========================================================================= // Begin includes // Including type: System.Runtime.InteropServices.ComInterfaceType #include "System/Runtime/InteropServices/ComInterfaceType.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils.hpp" #include "beatsaber-hook/shared/utils/utils.h" // Completed includes // Autogenerated static field getter // Get static field: static public System.Runtime.InteropServices.ComInterfaceType InterfaceIsDual ::System::Runtime::InteropServices::ComInterfaceType System::Runtime::InteropServices::ComInterfaceType::_get_InterfaceIsDual() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::ComInterfaceType::_get_InterfaceIsDual"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<::System::Runtime::InteropServices::ComInterfaceType>("System.Runtime.InteropServices", "ComInterfaceType", "InterfaceIsDual")); } // Autogenerated static field setter // Set static field: static public System.Runtime.InteropServices.ComInterfaceType InterfaceIsDual void System::Runtime::InteropServices::ComInterfaceType::_set_InterfaceIsDual(::System::Runtime::InteropServices::ComInterfaceType value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::ComInterfaceType::_set_InterfaceIsDual"); THROW_UNLESS(il2cpp_utils::SetFieldValue("System.Runtime.InteropServices", "ComInterfaceType", "InterfaceIsDual", value)); } // Autogenerated static field getter // Get static field: static public System.Runtime.InteropServices.ComInterfaceType InterfaceIsIUnknown ::System::Runtime::InteropServices::ComInterfaceType System::Runtime::InteropServices::ComInterfaceType::_get_InterfaceIsIUnknown() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::ComInterfaceType::_get_InterfaceIsIUnknown"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<::System::Runtime::InteropServices::ComInterfaceType>("System.Runtime.InteropServices", "ComInterfaceType", "InterfaceIsIUnknown")); } // Autogenerated static field setter // Set static field: static public System.Runtime.InteropServices.ComInterfaceType InterfaceIsIUnknown void System::Runtime::InteropServices::ComInterfaceType::_set_InterfaceIsIUnknown(::System::Runtime::InteropServices::ComInterfaceType value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::ComInterfaceType::_set_InterfaceIsIUnknown"); THROW_UNLESS(il2cpp_utils::SetFieldValue("System.Runtime.InteropServices", "ComInterfaceType", "InterfaceIsIUnknown", value)); } // Autogenerated static field getter // Get static field: static public System.Runtime.InteropServices.ComInterfaceType InterfaceIsIDispatch ::System::Runtime::InteropServices::ComInterfaceType System::Runtime::InteropServices::ComInterfaceType::_get_InterfaceIsIDispatch() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::ComInterfaceType::_get_InterfaceIsIDispatch"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<::System::Runtime::InteropServices::ComInterfaceType>("System.Runtime.InteropServices", "ComInterfaceType", "InterfaceIsIDispatch")); } // Autogenerated static field setter // Set static field: static public System.Runtime.InteropServices.ComInterfaceType InterfaceIsIDispatch void System::Runtime::InteropServices::ComInterfaceType::_set_InterfaceIsIDispatch(::System::Runtime::InteropServices::ComInterfaceType value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::ComInterfaceType::_set_InterfaceIsIDispatch"); THROW_UNLESS(il2cpp_utils::SetFieldValue("System.Runtime.InteropServices", "ComInterfaceType", "InterfaceIsIDispatch", value)); } // [ComVisibleAttribute] Offset: 0x689178 // Autogenerated static field getter // Get static field: static public System.Runtime.InteropServices.ComInterfaceType InterfaceIsIInspectable ::System::Runtime::InteropServices::ComInterfaceType System::Runtime::InteropServices::ComInterfaceType::_get_InterfaceIsIInspectable() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::ComInterfaceType::_get_InterfaceIsIInspectable"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<::System::Runtime::InteropServices::ComInterfaceType>("System.Runtime.InteropServices", "ComInterfaceType", "InterfaceIsIInspectable")); } // Autogenerated static field setter // Set static field: static public System.Runtime.InteropServices.ComInterfaceType InterfaceIsIInspectable void System::Runtime::InteropServices::ComInterfaceType::_set_InterfaceIsIInspectable(::System::Runtime::InteropServices::ComInterfaceType value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::ComInterfaceType::_set_InterfaceIsIInspectable"); THROW_UNLESS(il2cpp_utils::SetFieldValue("System.Runtime.InteropServices", "ComInterfaceType", "InterfaceIsIInspectable", value)); } // Autogenerated instance field getter // Get instance field: public System.Int32 value__ [[deprecated("Use field access instead!")]] int& System::Runtime::InteropServices::ComInterfaceType::dyn_value__() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::ComInterfaceType::dyn_value__"); auto ___internal__instance = *this; static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "value__"))->offset; return *reinterpret_cast<int*>(reinterpret_cast<char*>(this) + ___internal__field__offset); } // Autogenerated from CppSourceCreator // Created by Sc2ad // ========================================================================= // Begin includes // Including type: System.Runtime.InteropServices.InterfaceTypeAttribute #include "System/Runtime/InteropServices/InterfaceTypeAttribute.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils.hpp" #include "beatsaber-hook/shared/utils/utils.h" // Completed includes // Autogenerated instance field getter // Get instance field: System.Runtime.InteropServices.ComInterfaceType _val [[deprecated("Use field access instead!")]] ::System::Runtime::InteropServices::ComInterfaceType& System::Runtime::InteropServices::InterfaceTypeAttribute::dyn__val() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::InterfaceTypeAttribute::dyn__val"); auto ___internal__instance = this; static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "_val"))->offset; return *reinterpret_cast<::System::Runtime::InteropServices::ComInterfaceType*>(reinterpret_cast<char*>(this) + ___internal__field__offset); } // Autogenerated from CppSourceCreator // Created by Sc2ad // ========================================================================= // Begin includes // Including type: System.Runtime.InteropServices.ComDefaultInterfaceAttribute #include "System/Runtime/InteropServices/ComDefaultInterfaceAttribute.hpp" // Including type: System.Type #include "System/Type.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils.hpp" #include "beatsaber-hook/shared/utils/utils.h" // Completed includes // Autogenerated instance field getter // Get instance field: System.Type _val [[deprecated("Use field access instead!")]] ::System::Type*& System::Runtime::InteropServices::ComDefaultInterfaceAttribute::dyn__val() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::ComDefaultInterfaceAttribute::dyn__val"); auto ___internal__instance = this; static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "_val"))->offset; return *reinterpret_cast<::System::Type**>(reinterpret_cast<char*>(this) + ___internal__field__offset); } // Autogenerated from CppSourceCreator // Created by Sc2ad // ========================================================================= // Begin includes // Including type: System.Runtime.InteropServices.ClassInterfaceType #include "System/Runtime/InteropServices/ClassInterfaceType.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils.hpp" #include "beatsaber-hook/shared/utils/utils.h" // Completed includes // Autogenerated static field getter // Get static field: static public System.Runtime.InteropServices.ClassInterfaceType None ::System::Runtime::InteropServices::ClassInterfaceType System::Runtime::InteropServices::ClassInterfaceType::_get_None() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::ClassInterfaceType::_get_None"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<::System::Runtime::InteropServices::ClassInterfaceType>("System.Runtime.InteropServices", "ClassInterfaceType", "None")); } // Autogenerated static field setter // Set static field: static public System.Runtime.InteropServices.ClassInterfaceType None void System::Runtime::InteropServices::ClassInterfaceType::_set_None(::System::Runtime::InteropServices::ClassInterfaceType value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::ClassInterfaceType::_set_None"); THROW_UNLESS(il2cpp_utils::SetFieldValue("System.Runtime.InteropServices", "ClassInterfaceType", "None", value)); } // Autogenerated static field getter // Get static field: static public System.Runtime.InteropServices.ClassInterfaceType AutoDispatch ::System::Runtime::InteropServices::ClassInterfaceType System::Runtime::InteropServices::ClassInterfaceType::_get_AutoDispatch() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::ClassInterfaceType::_get_AutoDispatch"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<::System::Runtime::InteropServices::ClassInterfaceType>("System.Runtime.InteropServices", "ClassInterfaceType", "AutoDispatch")); } // Autogenerated static field setter // Set static field: static public System.Runtime.InteropServices.ClassInterfaceType AutoDispatch void System::Runtime::InteropServices::ClassInterfaceType::_set_AutoDispatch(::System::Runtime::InteropServices::ClassInterfaceType value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::ClassInterfaceType::_set_AutoDispatch"); THROW_UNLESS(il2cpp_utils::SetFieldValue("System.Runtime.InteropServices", "ClassInterfaceType", "AutoDispatch", value)); } // Autogenerated static field getter // Get static field: static public System.Runtime.InteropServices.ClassInterfaceType AutoDual ::System::Runtime::InteropServices::ClassInterfaceType System::Runtime::InteropServices::ClassInterfaceType::_get_AutoDual() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::ClassInterfaceType::_get_AutoDual"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<::System::Runtime::InteropServices::ClassInterfaceType>("System.Runtime.InteropServices", "ClassInterfaceType", "AutoDual")); } // Autogenerated static field setter // Set static field: static public System.Runtime.InteropServices.ClassInterfaceType AutoDual void System::Runtime::InteropServices::ClassInterfaceType::_set_AutoDual(::System::Runtime::InteropServices::ClassInterfaceType value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::ClassInterfaceType::_set_AutoDual"); THROW_UNLESS(il2cpp_utils::SetFieldValue("System.Runtime.InteropServices", "ClassInterfaceType", "AutoDual", value)); } // Autogenerated instance field getter // Get instance field: public System.Int32 value__ [[deprecated("Use field access instead!")]] int& System::Runtime::InteropServices::ClassInterfaceType::dyn_value__() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::ClassInterfaceType::dyn_value__"); auto ___internal__instance = *this; static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "value__"))->offset; return *reinterpret_cast<int*>(reinterpret_cast<char*>(this) + ___internal__field__offset); } // Autogenerated from CppSourceCreator // Created by Sc2ad // ========================================================================= // Begin includes // Including type: System.Runtime.InteropServices.ClassInterfaceAttribute #include "System/Runtime/InteropServices/ClassInterfaceAttribute.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils.hpp" #include "beatsaber-hook/shared/utils/utils.h" // Completed includes // Autogenerated instance field getter // Get instance field: System.Runtime.InteropServices.ClassInterfaceType _val [[deprecated("Use field access instead!")]] ::System::Runtime::InteropServices::ClassInterfaceType& System::Runtime::InteropServices::ClassInterfaceAttribute::dyn__val() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::ClassInterfaceAttribute::dyn__val"); auto ___internal__instance = this; static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "_val"))->offset; return *reinterpret_cast<::System::Runtime::InteropServices::ClassInterfaceType*>(reinterpret_cast<char*>(this) + ___internal__field__offset); } // Autogenerated from CppSourceCreator // Created by Sc2ad // ========================================================================= // Begin includes // Including type: System.Runtime.InteropServices.ComVisibleAttribute #include "System/Runtime/InteropServices/ComVisibleAttribute.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils.hpp" #include "beatsaber-hook/shared/utils/utils.h" // Completed includes // Autogenerated instance field getter // Get instance field: System.Boolean _val [[deprecated("Use field access instead!")]] bool& System::Runtime::InteropServices::ComVisibleAttribute::dyn__val() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::ComVisibleAttribute::dyn__val"); auto ___internal__instance = this; static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "_val"))->offset; return *reinterpret_cast<bool*>(reinterpret_cast<char*>(this) + ___internal__field__offset); } // Autogenerated from CppSourceCreator // Created by Sc2ad // ========================================================================= // Begin includes // Including type: System.Runtime.InteropServices.VarEnum #include "System/Runtime/InteropServices/VarEnum.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils.hpp" #include "beatsaber-hook/shared/utils/utils.h" // Completed includes // Autogenerated static field getter // Get static field: static public System.Runtime.InteropServices.VarEnum VT_EMPTY ::System::Runtime::InteropServices::VarEnum System::Runtime::InteropServices::VarEnum::_get_VT_EMPTY() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::VarEnum::_get_VT_EMPTY"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<::System::Runtime::InteropServices::VarEnum>("System.Runtime.InteropServices", "VarEnum", "VT_EMPTY")); } // Autogenerated static field setter // Set static field: static public System.Runtime.InteropServices.VarEnum VT_EMPTY void System::Runtime::InteropServices::VarEnum::_set_VT_EMPTY(::System::Runtime::InteropServices::VarEnum value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::VarEnum::_set_VT_EMPTY"); THROW_UNLESS(il2cpp_utils::SetFieldValue("System.Runtime.InteropServices", "VarEnum", "VT_EMPTY", value)); } // Autogenerated static field getter // Get static field: static public System.Runtime.InteropServices.VarEnum VT_NULL ::System::Runtime::InteropServices::VarEnum System::Runtime::InteropServices::VarEnum::_get_VT_NULL() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::VarEnum::_get_VT_NULL"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<::System::Runtime::InteropServices::VarEnum>("System.Runtime.InteropServices", "VarEnum", "VT_NULL")); } // Autogenerated static field setter // Set static field: static public System.Runtime.InteropServices.VarEnum VT_NULL void System::Runtime::InteropServices::VarEnum::_set_VT_NULL(::System::Runtime::InteropServices::VarEnum value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::VarEnum::_set_VT_NULL"); THROW_UNLESS(il2cpp_utils::SetFieldValue("System.Runtime.InteropServices", "VarEnum", "VT_NULL", value)); } // Autogenerated static field getter // Get static field: static public System.Runtime.InteropServices.VarEnum VT_I2 ::System::Runtime::InteropServices::VarEnum System::Runtime::InteropServices::VarEnum::_get_VT_I2() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::VarEnum::_get_VT_I2"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<::System::Runtime::InteropServices::VarEnum>("System.Runtime.InteropServices", "VarEnum", "VT_I2")); } // Autogenerated static field setter // Set static field: static public System.Runtime.InteropServices.VarEnum VT_I2 void System::Runtime::InteropServices::VarEnum::_set_VT_I2(::System::Runtime::InteropServices::VarEnum value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::VarEnum::_set_VT_I2"); THROW_UNLESS(il2cpp_utils::SetFieldValue("System.Runtime.InteropServices", "VarEnum", "VT_I2", value)); } // Autogenerated static field getter // Get static field: static public System.Runtime.InteropServices.VarEnum VT_I4 ::System::Runtime::InteropServices::VarEnum System::Runtime::InteropServices::VarEnum::_get_VT_I4() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::VarEnum::_get_VT_I4"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<::System::Runtime::InteropServices::VarEnum>("System.Runtime.InteropServices", "VarEnum", "VT_I4")); } // Autogenerated static field setter // Set static field: static public System.Runtime.InteropServices.VarEnum VT_I4 void System::Runtime::InteropServices::VarEnum::_set_VT_I4(::System::Runtime::InteropServices::VarEnum value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::VarEnum::_set_VT_I4"); THROW_UNLESS(il2cpp_utils::SetFieldValue("System.Runtime.InteropServices", "VarEnum", "VT_I4", value)); } // Autogenerated static field getter // Get static field: static public System.Runtime.InteropServices.VarEnum VT_R4 ::System::Runtime::InteropServices::VarEnum System::Runtime::InteropServices::VarEnum::_get_VT_R4() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::VarEnum::_get_VT_R4"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<::System::Runtime::InteropServices::VarEnum>("System.Runtime.InteropServices", "VarEnum", "VT_R4")); } // Autogenerated static field setter // Set static field: static public System.Runtime.InteropServices.VarEnum VT_R4 void System::Runtime::InteropServices::VarEnum::_set_VT_R4(::System::Runtime::InteropServices::VarEnum value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::VarEnum::_set_VT_R4"); THROW_UNLESS(il2cpp_utils::SetFieldValue("System.Runtime.InteropServices", "VarEnum", "VT_R4", value)); } // Autogenerated static field getter // Get static field: static public System.Runtime.InteropServices.VarEnum VT_R8 ::System::Runtime::InteropServices::VarEnum System::Runtime::InteropServices::VarEnum::_get_VT_R8() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::VarEnum::_get_VT_R8"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<::System::Runtime::InteropServices::VarEnum>("System.Runtime.InteropServices", "VarEnum", "VT_R8")); } // Autogenerated static field setter // Set static field: static public System.Runtime.InteropServices.VarEnum VT_R8 void System::Runtime::InteropServices::VarEnum::_set_VT_R8(::System::Runtime::InteropServices::VarEnum value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::VarEnum::_set_VT_R8"); THROW_UNLESS(il2cpp_utils::SetFieldValue("System.Runtime.InteropServices", "VarEnum", "VT_R8", value)); } // Autogenerated static field getter // Get static field: static public System.Runtime.InteropServices.VarEnum VT_CY ::System::Runtime::InteropServices::VarEnum System::Runtime::InteropServices::VarEnum::_get_VT_CY() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::VarEnum::_get_VT_CY"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<::System::Runtime::InteropServices::VarEnum>("System.Runtime.InteropServices", "VarEnum", "VT_CY")); } // Autogenerated static field setter // Set static field: static public System.Runtime.InteropServices.VarEnum VT_CY void System::Runtime::InteropServices::VarEnum::_set_VT_CY(::System::Runtime::InteropServices::VarEnum value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::VarEnum::_set_VT_CY"); THROW_UNLESS(il2cpp_utils::SetFieldValue("System.Runtime.InteropServices", "VarEnum", "VT_CY", value)); } // Autogenerated static field getter // Get static field: static public System.Runtime.InteropServices.VarEnum VT_DATE ::System::Runtime::InteropServices::VarEnum System::Runtime::InteropServices::VarEnum::_get_VT_DATE() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::VarEnum::_get_VT_DATE"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<::System::Runtime::InteropServices::VarEnum>("System.Runtime.InteropServices", "VarEnum", "VT_DATE")); } // Autogenerated static field setter // Set static field: static public System.Runtime.InteropServices.VarEnum VT_DATE void System::Runtime::InteropServices::VarEnum::_set_VT_DATE(::System::Runtime::InteropServices::VarEnum value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::VarEnum::_set_VT_DATE"); THROW_UNLESS(il2cpp_utils::SetFieldValue("System.Runtime.InteropServices", "VarEnum", "VT_DATE", value)); } // Autogenerated static field getter // Get static field: static public System.Runtime.InteropServices.VarEnum VT_BSTR ::System::Runtime::InteropServices::VarEnum System::Runtime::InteropServices::VarEnum::_get_VT_BSTR() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::VarEnum::_get_VT_BSTR"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<::System::Runtime::InteropServices::VarEnum>("System.Runtime.InteropServices", "VarEnum", "VT_BSTR")); } // Autogenerated static field setter // Set static field: static public System.Runtime.InteropServices.VarEnum VT_BSTR void System::Runtime::InteropServices::VarEnum::_set_VT_BSTR(::System::Runtime::InteropServices::VarEnum value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::VarEnum::_set_VT_BSTR"); THROW_UNLESS(il2cpp_utils::SetFieldValue("System.Runtime.InteropServices", "VarEnum", "VT_BSTR", value)); } // Autogenerated static field getter // Get static field: static public System.Runtime.InteropServices.VarEnum VT_DISPATCH ::System::Runtime::InteropServices::VarEnum System::Runtime::InteropServices::VarEnum::_get_VT_DISPATCH() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::VarEnum::_get_VT_DISPATCH"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<::System::Runtime::InteropServices::VarEnum>("System.Runtime.InteropServices", "VarEnum", "VT_DISPATCH")); } // Autogenerated static field setter // Set static field: static public System.Runtime.InteropServices.VarEnum VT_DISPATCH void System::Runtime::InteropServices::VarEnum::_set_VT_DISPATCH(::System::Runtime::InteropServices::VarEnum value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::VarEnum::_set_VT_DISPATCH"); THROW_UNLESS(il2cpp_utils::SetFieldValue("System.Runtime.InteropServices", "VarEnum", "VT_DISPATCH", value)); } // Autogenerated static field getter // Get static field: static public System.Runtime.InteropServices.VarEnum VT_ERROR ::System::Runtime::InteropServices::VarEnum System::Runtime::InteropServices::VarEnum::_get_VT_ERROR() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::VarEnum::_get_VT_ERROR"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<::System::Runtime::InteropServices::VarEnum>("System.Runtime.InteropServices", "VarEnum", "VT_ERROR")); } // Autogenerated static field setter // Set static field: static public System.Runtime.InteropServices.VarEnum VT_ERROR void System::Runtime::InteropServices::VarEnum::_set_VT_ERROR(::System::Runtime::InteropServices::VarEnum value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::VarEnum::_set_VT_ERROR"); THROW_UNLESS(il2cpp_utils::SetFieldValue("System.Runtime.InteropServices", "VarEnum", "VT_ERROR", value)); } // Autogenerated static field getter // Get static field: static public System.Runtime.InteropServices.VarEnum VT_BOOL ::System::Runtime::InteropServices::VarEnum System::Runtime::InteropServices::VarEnum::_get_VT_BOOL() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::VarEnum::_get_VT_BOOL"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<::System::Runtime::InteropServices::VarEnum>("System.Runtime.InteropServices", "VarEnum", "VT_BOOL")); } // Autogenerated static field setter // Set static field: static public System.Runtime.InteropServices.VarEnum VT_BOOL void System::Runtime::InteropServices::VarEnum::_set_VT_BOOL(::System::Runtime::InteropServices::VarEnum value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::VarEnum::_set_VT_BOOL"); THROW_UNLESS(il2cpp_utils::SetFieldValue("System.Runtime.InteropServices", "VarEnum", "VT_BOOL", value)); } // Autogenerated static field getter // Get static field: static public System.Runtime.InteropServices.VarEnum VT_VARIANT ::System::Runtime::InteropServices::VarEnum System::Runtime::InteropServices::VarEnum::_get_VT_VARIANT() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::VarEnum::_get_VT_VARIANT"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<::System::Runtime::InteropServices::VarEnum>("System.Runtime.InteropServices", "VarEnum", "VT_VARIANT")); } // Autogenerated static field setter // Set static field: static public System.Runtime.InteropServices.VarEnum VT_VARIANT void System::Runtime::InteropServices::VarEnum::_set_VT_VARIANT(::System::Runtime::InteropServices::VarEnum value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::VarEnum::_set_VT_VARIANT"); THROW_UNLESS(il2cpp_utils::SetFieldValue("System.Runtime.InteropServices", "VarEnum", "VT_VARIANT", value)); } // Autogenerated static field getter // Get static field: static public System.Runtime.InteropServices.VarEnum VT_UNKNOWN ::System::Runtime::InteropServices::VarEnum System::Runtime::InteropServices::VarEnum::_get_VT_UNKNOWN() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::VarEnum::_get_VT_UNKNOWN"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<::System::Runtime::InteropServices::VarEnum>("System.Runtime.InteropServices", "VarEnum", "VT_UNKNOWN")); } // Autogenerated static field setter // Set static field: static public System.Runtime.InteropServices.VarEnum VT_UNKNOWN void System::Runtime::InteropServices::VarEnum::_set_VT_UNKNOWN(::System::Runtime::InteropServices::VarEnum value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::VarEnum::_set_VT_UNKNOWN"); THROW_UNLESS(il2cpp_utils::SetFieldValue("System.Runtime.InteropServices", "VarEnum", "VT_UNKNOWN", value)); } // Autogenerated static field getter // Get static field: static public System.Runtime.InteropServices.VarEnum VT_DECIMAL ::System::Runtime::InteropServices::VarEnum System::Runtime::InteropServices::VarEnum::_get_VT_DECIMAL() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::VarEnum::_get_VT_DECIMAL"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<::System::Runtime::InteropServices::VarEnum>("System.Runtime.InteropServices", "VarEnum", "VT_DECIMAL")); } // Autogenerated static field setter // Set static field: static public System.Runtime.InteropServices.VarEnum VT_DECIMAL void System::Runtime::InteropServices::VarEnum::_set_VT_DECIMAL(::System::Runtime::InteropServices::VarEnum value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::VarEnum::_set_VT_DECIMAL"); THROW_UNLESS(il2cpp_utils::SetFieldValue("System.Runtime.InteropServices", "VarEnum", "VT_DECIMAL", value)); } // Autogenerated static field getter // Get static field: static public System.Runtime.InteropServices.VarEnum VT_I1 ::System::Runtime::InteropServices::VarEnum System::Runtime::InteropServices::VarEnum::_get_VT_I1() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::VarEnum::_get_VT_I1"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<::System::Runtime::InteropServices::VarEnum>("System.Runtime.InteropServices", "VarEnum", "VT_I1")); } // Autogenerated static field setter // Set static field: static public System.Runtime.InteropServices.VarEnum VT_I1 void System::Runtime::InteropServices::VarEnum::_set_VT_I1(::System::Runtime::InteropServices::VarEnum value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::VarEnum::_set_VT_I1"); THROW_UNLESS(il2cpp_utils::SetFieldValue("System.Runtime.InteropServices", "VarEnum", "VT_I1", value)); } // Autogenerated static field getter // Get static field: static public System.Runtime.InteropServices.VarEnum VT_UI1 ::System::Runtime::InteropServices::VarEnum System::Runtime::InteropServices::VarEnum::_get_VT_UI1() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::VarEnum::_get_VT_UI1"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<::System::Runtime::InteropServices::VarEnum>("System.Runtime.InteropServices", "VarEnum", "VT_UI1")); } // Autogenerated static field setter // Set static field: static public System.Runtime.InteropServices.VarEnum VT_UI1 void System::Runtime::InteropServices::VarEnum::_set_VT_UI1(::System::Runtime::InteropServices::VarEnum value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::VarEnum::_set_VT_UI1"); THROW_UNLESS(il2cpp_utils::SetFieldValue("System.Runtime.InteropServices", "VarEnum", "VT_UI1", value)); } // Autogenerated static field getter // Get static field: static public System.Runtime.InteropServices.VarEnum VT_UI2 ::System::Runtime::InteropServices::VarEnum System::Runtime::InteropServices::VarEnum::_get_VT_UI2() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::VarEnum::_get_VT_UI2"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<::System::Runtime::InteropServices::VarEnum>("System.Runtime.InteropServices", "VarEnum", "VT_UI2")); } // Autogenerated static field setter // Set static field: static public System.Runtime.InteropServices.VarEnum VT_UI2 void System::Runtime::InteropServices::VarEnum::_set_VT_UI2(::System::Runtime::InteropServices::VarEnum value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::VarEnum::_set_VT_UI2"); THROW_UNLESS(il2cpp_utils::SetFieldValue("System.Runtime.InteropServices", "VarEnum", "VT_UI2", value)); } // Autogenerated static field getter // Get static field: static public System.Runtime.InteropServices.VarEnum VT_UI4 ::System::Runtime::InteropServices::VarEnum System::Runtime::InteropServices::VarEnum::_get_VT_UI4() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::VarEnum::_get_VT_UI4"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<::System::Runtime::InteropServices::VarEnum>("System.Runtime.InteropServices", "VarEnum", "VT_UI4")); } // Autogenerated static field setter // Set static field: static public System.Runtime.InteropServices.VarEnum VT_UI4 void System::Runtime::InteropServices::VarEnum::_set_VT_UI4(::System::Runtime::InteropServices::VarEnum value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::VarEnum::_set_VT_UI4"); THROW_UNLESS(il2cpp_utils::SetFieldValue("System.Runtime.InteropServices", "VarEnum", "VT_UI4", value)); } // Autogenerated static field getter // Get static field: static public System.Runtime.InteropServices.VarEnum VT_I8 ::System::Runtime::InteropServices::VarEnum System::Runtime::InteropServices::VarEnum::_get_VT_I8() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::VarEnum::_get_VT_I8"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<::System::Runtime::InteropServices::VarEnum>("System.Runtime.InteropServices", "VarEnum", "VT_I8")); } // Autogenerated static field setter // Set static field: static public System.Runtime.InteropServices.VarEnum VT_I8 void System::Runtime::InteropServices::VarEnum::_set_VT_I8(::System::Runtime::InteropServices::VarEnum value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::VarEnum::_set_VT_I8"); THROW_UNLESS(il2cpp_utils::SetFieldValue("System.Runtime.InteropServices", "VarEnum", "VT_I8", value)); } // Autogenerated static field getter // Get static field: static public System.Runtime.InteropServices.VarEnum VT_UI8 ::System::Runtime::InteropServices::VarEnum System::Runtime::InteropServices::VarEnum::_get_VT_UI8() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::VarEnum::_get_VT_UI8"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<::System::Runtime::InteropServices::VarEnum>("System.Runtime.InteropServices", "VarEnum", "VT_UI8")); } // Autogenerated static field setter // Set static field: static public System.Runtime.InteropServices.VarEnum VT_UI8 void System::Runtime::InteropServices::VarEnum::_set_VT_UI8(::System::Runtime::InteropServices::VarEnum value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::VarEnum::_set_VT_UI8"); THROW_UNLESS(il2cpp_utils::SetFieldValue("System.Runtime.InteropServices", "VarEnum", "VT_UI8", value)); } // Autogenerated static field getter // Get static field: static public System.Runtime.InteropServices.VarEnum VT_INT ::System::Runtime::InteropServices::VarEnum System::Runtime::InteropServices::VarEnum::_get_VT_INT() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::VarEnum::_get_VT_INT"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<::System::Runtime::InteropServices::VarEnum>("System.Runtime.InteropServices", "VarEnum", "VT_INT")); } // Autogenerated static field setter // Set static field: static public System.Runtime.InteropServices.VarEnum VT_INT void System::Runtime::InteropServices::VarEnum::_set_VT_INT(::System::Runtime::InteropServices::VarEnum value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::VarEnum::_set_VT_INT"); THROW_UNLESS(il2cpp_utils::SetFieldValue("System.Runtime.InteropServices", "VarEnum", "VT_INT", value)); } // Autogenerated static field getter // Get static field: static public System.Runtime.InteropServices.VarEnum VT_UINT ::System::Runtime::InteropServices::VarEnum System::Runtime::InteropServices::VarEnum::_get_VT_UINT() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::VarEnum::_get_VT_UINT"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<::System::Runtime::InteropServices::VarEnum>("System.Runtime.InteropServices", "VarEnum", "VT_UINT")); } // Autogenerated static field setter // Set static field: static public System.Runtime.InteropServices.VarEnum VT_UINT void System::Runtime::InteropServices::VarEnum::_set_VT_UINT(::System::Runtime::InteropServices::VarEnum value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::VarEnum::_set_VT_UINT"); THROW_UNLESS(il2cpp_utils::SetFieldValue("System.Runtime.InteropServices", "VarEnum", "VT_UINT", value)); } // Autogenerated static field getter // Get static field: static public System.Runtime.InteropServices.VarEnum VT_VOID ::System::Runtime::InteropServices::VarEnum System::Runtime::InteropServices::VarEnum::_get_VT_VOID() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::VarEnum::_get_VT_VOID"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<::System::Runtime::InteropServices::VarEnum>("System.Runtime.InteropServices", "VarEnum", "VT_VOID")); } // Autogenerated static field setter // Set static field: static public System.Runtime.InteropServices.VarEnum VT_VOID void System::Runtime::InteropServices::VarEnum::_set_VT_VOID(::System::Runtime::InteropServices::VarEnum value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::VarEnum::_set_VT_VOID"); THROW_UNLESS(il2cpp_utils::SetFieldValue("System.Runtime.InteropServices", "VarEnum", "VT_VOID", value)); } // Autogenerated static field getter // Get static field: static public System.Runtime.InteropServices.VarEnum VT_HRESULT ::System::Runtime::InteropServices::VarEnum System::Runtime::InteropServices::VarEnum::_get_VT_HRESULT() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::VarEnum::_get_VT_HRESULT"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<::System::Runtime::InteropServices::VarEnum>("System.Runtime.InteropServices", "VarEnum", "VT_HRESULT")); } // Autogenerated static field setter // Set static field: static public System.Runtime.InteropServices.VarEnum VT_HRESULT void System::Runtime::InteropServices::VarEnum::_set_VT_HRESULT(::System::Runtime::InteropServices::VarEnum value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::VarEnum::_set_VT_HRESULT"); THROW_UNLESS(il2cpp_utils::SetFieldValue("System.Runtime.InteropServices", "VarEnum", "VT_HRESULT", value)); } // Autogenerated static field getter // Get static field: static public System.Runtime.InteropServices.VarEnum VT_PTR ::System::Runtime::InteropServices::VarEnum System::Runtime::InteropServices::VarEnum::_get_VT_PTR() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::VarEnum::_get_VT_PTR"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<::System::Runtime::InteropServices::VarEnum>("System.Runtime.InteropServices", "VarEnum", "VT_PTR")); } // Autogenerated static field setter // Set static field: static public System.Runtime.InteropServices.VarEnum VT_PTR void System::Runtime::InteropServices::VarEnum::_set_VT_PTR(::System::Runtime::InteropServices::VarEnum value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::VarEnum::_set_VT_PTR"); THROW_UNLESS(il2cpp_utils::SetFieldValue("System.Runtime.InteropServices", "VarEnum", "VT_PTR", value)); } // Autogenerated static field getter // Get static field: static public System.Runtime.InteropServices.VarEnum VT_SAFEARRAY ::System::Runtime::InteropServices::VarEnum System::Runtime::InteropServices::VarEnum::_get_VT_SAFEARRAY() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::VarEnum::_get_VT_SAFEARRAY"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<::System::Runtime::InteropServices::VarEnum>("System.Runtime.InteropServices", "VarEnum", "VT_SAFEARRAY")); } // Autogenerated static field setter // Set static field: static public System.Runtime.InteropServices.VarEnum VT_SAFEARRAY void System::Runtime::InteropServices::VarEnum::_set_VT_SAFEARRAY(::System::Runtime::InteropServices::VarEnum value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::VarEnum::_set_VT_SAFEARRAY"); THROW_UNLESS(il2cpp_utils::SetFieldValue("System.Runtime.InteropServices", "VarEnum", "VT_SAFEARRAY", value)); } // Autogenerated static field getter // Get static field: static public System.Runtime.InteropServices.VarEnum VT_CARRAY ::System::Runtime::InteropServices::VarEnum System::Runtime::InteropServices::VarEnum::_get_VT_CARRAY() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::VarEnum::_get_VT_CARRAY"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<::System::Runtime::InteropServices::VarEnum>("System.Runtime.InteropServices", "VarEnum", "VT_CARRAY")); } // Autogenerated static field setter // Set static field: static public System.Runtime.InteropServices.VarEnum VT_CARRAY void System::Runtime::InteropServices::VarEnum::_set_VT_CARRAY(::System::Runtime::InteropServices::VarEnum value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::VarEnum::_set_VT_CARRAY"); THROW_UNLESS(il2cpp_utils::SetFieldValue("System.Runtime.InteropServices", "VarEnum", "VT_CARRAY", value)); } // Autogenerated static field getter // Get static field: static public System.Runtime.InteropServices.VarEnum VT_USERDEFINED ::System::Runtime::InteropServices::VarEnum System::Runtime::InteropServices::VarEnum::_get_VT_USERDEFINED() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::VarEnum::_get_VT_USERDEFINED"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<::System::Runtime::InteropServices::VarEnum>("System.Runtime.InteropServices", "VarEnum", "VT_USERDEFINED")); } // Autogenerated static field setter // Set static field: static public System.Runtime.InteropServices.VarEnum VT_USERDEFINED void System::Runtime::InteropServices::VarEnum::_set_VT_USERDEFINED(::System::Runtime::InteropServices::VarEnum value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::VarEnum::_set_VT_USERDEFINED"); THROW_UNLESS(il2cpp_utils::SetFieldValue("System.Runtime.InteropServices", "VarEnum", "VT_USERDEFINED", value)); } // Autogenerated static field getter // Get static field: static public System.Runtime.InteropServices.VarEnum VT_LPSTR ::System::Runtime::InteropServices::VarEnum System::Runtime::InteropServices::VarEnum::_get_VT_LPSTR() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::VarEnum::_get_VT_LPSTR"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<::System::Runtime::InteropServices::VarEnum>("System.Runtime.InteropServices", "VarEnum", "VT_LPSTR")); } // Autogenerated static field setter // Set static field: static public System.Runtime.InteropServices.VarEnum VT_LPSTR void System::Runtime::InteropServices::VarEnum::_set_VT_LPSTR(::System::Runtime::InteropServices::VarEnum value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::VarEnum::_set_VT_LPSTR"); THROW_UNLESS(il2cpp_utils::SetFieldValue("System.Runtime.InteropServices", "VarEnum", "VT_LPSTR", value)); } // Autogenerated static field getter // Get static field: static public System.Runtime.InteropServices.VarEnum VT_LPWSTR ::System::Runtime::InteropServices::VarEnum System::Runtime::InteropServices::VarEnum::_get_VT_LPWSTR() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::VarEnum::_get_VT_LPWSTR"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<::System::Runtime::InteropServices::VarEnum>("System.Runtime.InteropServices", "VarEnum", "VT_LPWSTR")); } // Autogenerated static field setter // Set static field: static public System.Runtime.InteropServices.VarEnum VT_LPWSTR void System::Runtime::InteropServices::VarEnum::_set_VT_LPWSTR(::System::Runtime::InteropServices::VarEnum value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::VarEnum::_set_VT_LPWSTR"); THROW_UNLESS(il2cpp_utils::SetFieldValue("System.Runtime.InteropServices", "VarEnum", "VT_LPWSTR", value)); } // Autogenerated static field getter // Get static field: static public System.Runtime.InteropServices.VarEnum VT_RECORD ::System::Runtime::InteropServices::VarEnum System::Runtime::InteropServices::VarEnum::_get_VT_RECORD() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::VarEnum::_get_VT_RECORD"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<::System::Runtime::InteropServices::VarEnum>("System.Runtime.InteropServices", "VarEnum", "VT_RECORD")); } // Autogenerated static field setter // Set static field: static public System.Runtime.InteropServices.VarEnum VT_RECORD void System::Runtime::InteropServices::VarEnum::_set_VT_RECORD(::System::Runtime::InteropServices::VarEnum value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::VarEnum::_set_VT_RECORD"); THROW_UNLESS(il2cpp_utils::SetFieldValue("System.Runtime.InteropServices", "VarEnum", "VT_RECORD", value)); } // Autogenerated static field getter // Get static field: static public System.Runtime.InteropServices.VarEnum VT_FILETIME ::System::Runtime::InteropServices::VarEnum System::Runtime::InteropServices::VarEnum::_get_VT_FILETIME() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::VarEnum::_get_VT_FILETIME"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<::System::Runtime::InteropServices::VarEnum>("System.Runtime.InteropServices", "VarEnum", "VT_FILETIME")); } // Autogenerated static field setter // Set static field: static public System.Runtime.InteropServices.VarEnum VT_FILETIME void System::Runtime::InteropServices::VarEnum::_set_VT_FILETIME(::System::Runtime::InteropServices::VarEnum value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::VarEnum::_set_VT_FILETIME"); THROW_UNLESS(il2cpp_utils::SetFieldValue("System.Runtime.InteropServices", "VarEnum", "VT_FILETIME", value)); } // Autogenerated static field getter // Get static field: static public System.Runtime.InteropServices.VarEnum VT_BLOB ::System::Runtime::InteropServices::VarEnum System::Runtime::InteropServices::VarEnum::_get_VT_BLOB() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::VarEnum::_get_VT_BLOB"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<::System::Runtime::InteropServices::VarEnum>("System.Runtime.InteropServices", "VarEnum", "VT_BLOB")); } // Autogenerated static field setter // Set static field: static public System.Runtime.InteropServices.VarEnum VT_BLOB void System::Runtime::InteropServices::VarEnum::_set_VT_BLOB(::System::Runtime::InteropServices::VarEnum value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::VarEnum::_set_VT_BLOB"); THROW_UNLESS(il2cpp_utils::SetFieldValue("System.Runtime.InteropServices", "VarEnum", "VT_BLOB", value)); } // Autogenerated static field getter // Get static field: static public System.Runtime.InteropServices.VarEnum VT_STREAM ::System::Runtime::InteropServices::VarEnum System::Runtime::InteropServices::VarEnum::_get_VT_STREAM() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::VarEnum::_get_VT_STREAM"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<::System::Runtime::InteropServices::VarEnum>("System.Runtime.InteropServices", "VarEnum", "VT_STREAM")); } // Autogenerated static field setter // Set static field: static public System.Runtime.InteropServices.VarEnum VT_STREAM void System::Runtime::InteropServices::VarEnum::_set_VT_STREAM(::System::Runtime::InteropServices::VarEnum value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::VarEnum::_set_VT_STREAM"); THROW_UNLESS(il2cpp_utils::SetFieldValue("System.Runtime.InteropServices", "VarEnum", "VT_STREAM", value)); } // Autogenerated static field getter // Get static field: static public System.Runtime.InteropServices.VarEnum VT_STORAGE ::System::Runtime::InteropServices::VarEnum System::Runtime::InteropServices::VarEnum::_get_VT_STORAGE() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::VarEnum::_get_VT_STORAGE"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<::System::Runtime::InteropServices::VarEnum>("System.Runtime.InteropServices", "VarEnum", "VT_STORAGE")); } // Autogenerated static field setter // Set static field: static public System.Runtime.InteropServices.VarEnum VT_STORAGE void System::Runtime::InteropServices::VarEnum::_set_VT_STORAGE(::System::Runtime::InteropServices::VarEnum value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::VarEnum::_set_VT_STORAGE"); THROW_UNLESS(il2cpp_utils::SetFieldValue("System.Runtime.InteropServices", "VarEnum", "VT_STORAGE", value)); } // Autogenerated static field getter // Get static field: static public System.Runtime.InteropServices.VarEnum VT_STREAMED_OBJECT ::System::Runtime::InteropServices::VarEnum System::Runtime::InteropServices::VarEnum::_get_VT_STREAMED_OBJECT() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::VarEnum::_get_VT_STREAMED_OBJECT"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<::System::Runtime::InteropServices::VarEnum>("System.Runtime.InteropServices", "VarEnum", "VT_STREAMED_OBJECT")); } // Autogenerated static field setter // Set static field: static public System.Runtime.InteropServices.VarEnum VT_STREAMED_OBJECT void System::Runtime::InteropServices::VarEnum::_set_VT_STREAMED_OBJECT(::System::Runtime::InteropServices::VarEnum value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::VarEnum::_set_VT_STREAMED_OBJECT"); THROW_UNLESS(il2cpp_utils::SetFieldValue("System.Runtime.InteropServices", "VarEnum", "VT_STREAMED_OBJECT", value)); } // Autogenerated static field getter // Get static field: static public System.Runtime.InteropServices.VarEnum VT_STORED_OBJECT ::System::Runtime::InteropServices::VarEnum System::Runtime::InteropServices::VarEnum::_get_VT_STORED_OBJECT() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::VarEnum::_get_VT_STORED_OBJECT"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<::System::Runtime::InteropServices::VarEnum>("System.Runtime.InteropServices", "VarEnum", "VT_STORED_OBJECT")); } // Autogenerated static field setter // Set static field: static public System.Runtime.InteropServices.VarEnum VT_STORED_OBJECT void System::Runtime::InteropServices::VarEnum::_set_VT_STORED_OBJECT(::System::Runtime::InteropServices::VarEnum value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::VarEnum::_set_VT_STORED_OBJECT"); THROW_UNLESS(il2cpp_utils::SetFieldValue("System.Runtime.InteropServices", "VarEnum", "VT_STORED_OBJECT", value)); } // Autogenerated static field getter // Get static field: static public System.Runtime.InteropServices.VarEnum VT_BLOB_OBJECT ::System::Runtime::InteropServices::VarEnum System::Runtime::InteropServices::VarEnum::_get_VT_BLOB_OBJECT() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::VarEnum::_get_VT_BLOB_OBJECT"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<::System::Runtime::InteropServices::VarEnum>("System.Runtime.InteropServices", "VarEnum", "VT_BLOB_OBJECT")); } // Autogenerated static field setter // Set static field: static public System.Runtime.InteropServices.VarEnum VT_BLOB_OBJECT void System::Runtime::InteropServices::VarEnum::_set_VT_BLOB_OBJECT(::System::Runtime::InteropServices::VarEnum value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::VarEnum::_set_VT_BLOB_OBJECT"); THROW_UNLESS(il2cpp_utils::SetFieldValue("System.Runtime.InteropServices", "VarEnum", "VT_BLOB_OBJECT", value)); } // Autogenerated static field getter // Get static field: static public System.Runtime.InteropServices.VarEnum VT_CF ::System::Runtime::InteropServices::VarEnum System::Runtime::InteropServices::VarEnum::_get_VT_CF() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::VarEnum::_get_VT_CF"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<::System::Runtime::InteropServices::VarEnum>("System.Runtime.InteropServices", "VarEnum", "VT_CF")); } // Autogenerated static field setter // Set static field: static public System.Runtime.InteropServices.VarEnum VT_CF void System::Runtime::InteropServices::VarEnum::_set_VT_CF(::System::Runtime::InteropServices::VarEnum value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::VarEnum::_set_VT_CF"); THROW_UNLESS(il2cpp_utils::SetFieldValue("System.Runtime.InteropServices", "VarEnum", "VT_CF", value)); } // Autogenerated static field getter // Get static field: static public System.Runtime.InteropServices.VarEnum VT_CLSID ::System::Runtime::InteropServices::VarEnum System::Runtime::InteropServices::VarEnum::_get_VT_CLSID() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::VarEnum::_get_VT_CLSID"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<::System::Runtime::InteropServices::VarEnum>("System.Runtime.InteropServices", "VarEnum", "VT_CLSID")); } // Autogenerated static field setter // Set static field: static public System.Runtime.InteropServices.VarEnum VT_CLSID void System::Runtime::InteropServices::VarEnum::_set_VT_CLSID(::System::Runtime::InteropServices::VarEnum value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::VarEnum::_set_VT_CLSID"); THROW_UNLESS(il2cpp_utils::SetFieldValue("System.Runtime.InteropServices", "VarEnum", "VT_CLSID", value)); } // Autogenerated static field getter // Get static field: static public System.Runtime.InteropServices.VarEnum VT_VECTOR ::System::Runtime::InteropServices::VarEnum System::Runtime::InteropServices::VarEnum::_get_VT_VECTOR() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::VarEnum::_get_VT_VECTOR"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<::System::Runtime::InteropServices::VarEnum>("System.Runtime.InteropServices", "VarEnum", "VT_VECTOR")); } // Autogenerated static field setter // Set static field: static public System.Runtime.InteropServices.VarEnum VT_VECTOR void System::Runtime::InteropServices::VarEnum::_set_VT_VECTOR(::System::Runtime::InteropServices::VarEnum value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::VarEnum::_set_VT_VECTOR"); THROW_UNLESS(il2cpp_utils::SetFieldValue("System.Runtime.InteropServices", "VarEnum", "VT_VECTOR", value)); } // Autogenerated static field getter // Get static field: static public System.Runtime.InteropServices.VarEnum VT_ARRAY ::System::Runtime::InteropServices::VarEnum System::Runtime::InteropServices::VarEnum::_get_VT_ARRAY() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::VarEnum::_get_VT_ARRAY"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<::System::Runtime::InteropServices::VarEnum>("System.Runtime.InteropServices", "VarEnum", "VT_ARRAY")); } // Autogenerated static field setter // Set static field: static public System.Runtime.InteropServices.VarEnum VT_ARRAY void System::Runtime::InteropServices::VarEnum::_set_VT_ARRAY(::System::Runtime::InteropServices::VarEnum value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::VarEnum::_set_VT_ARRAY"); THROW_UNLESS(il2cpp_utils::SetFieldValue("System.Runtime.InteropServices", "VarEnum", "VT_ARRAY", value)); } // Autogenerated static field getter // Get static field: static public System.Runtime.InteropServices.VarEnum VT_BYREF ::System::Runtime::InteropServices::VarEnum System::Runtime::InteropServices::VarEnum::_get_VT_BYREF() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::VarEnum::_get_VT_BYREF"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<::System::Runtime::InteropServices::VarEnum>("System.Runtime.InteropServices", "VarEnum", "VT_BYREF")); } // Autogenerated static field setter // Set static field: static public System.Runtime.InteropServices.VarEnum VT_BYREF void System::Runtime::InteropServices::VarEnum::_set_VT_BYREF(::System::Runtime::InteropServices::VarEnum value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::VarEnum::_set_VT_BYREF"); THROW_UNLESS(il2cpp_utils::SetFieldValue("System.Runtime.InteropServices", "VarEnum", "VT_BYREF", value)); } // Autogenerated instance field getter // Get instance field: public System.Int32 value__ [[deprecated("Use field access instead!")]] int& System::Runtime::InteropServices::VarEnum::dyn_value__() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::VarEnum::dyn_value__"); auto ___internal__instance = *this; static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "value__"))->offset; return *reinterpret_cast<int*>(reinterpret_cast<char*>(this) + ___internal__field__offset); } // Autogenerated from CppSourceCreator // Created by Sc2ad // ========================================================================= // Begin includes // Including type: System.Runtime.InteropServices.UnmanagedType #include "System/Runtime/InteropServices/UnmanagedType.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils.hpp" #include "beatsaber-hook/shared/utils/utils.h" // Completed includes // Autogenerated static field getter // Get static field: static public System.Runtime.InteropServices.UnmanagedType Bool ::System::Runtime::InteropServices::UnmanagedType System::Runtime::InteropServices::UnmanagedType::_get_Bool() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::UnmanagedType::_get_Bool"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<::System::Runtime::InteropServices::UnmanagedType>("System.Runtime.InteropServices", "UnmanagedType", "Bool")); } // Autogenerated static field setter // Set static field: static public System.Runtime.InteropServices.UnmanagedType Bool void System::Runtime::InteropServices::UnmanagedType::_set_Bool(::System::Runtime::InteropServices::UnmanagedType value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::UnmanagedType::_set_Bool"); THROW_UNLESS(il2cpp_utils::SetFieldValue("System.Runtime.InteropServices", "UnmanagedType", "Bool", value)); } // Autogenerated static field getter // Get static field: static public System.Runtime.InteropServices.UnmanagedType I1 ::System::Runtime::InteropServices::UnmanagedType System::Runtime::InteropServices::UnmanagedType::_get_I1() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::UnmanagedType::_get_I1"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<::System::Runtime::InteropServices::UnmanagedType>("System.Runtime.InteropServices", "UnmanagedType", "I1")); } // Autogenerated static field setter // Set static field: static public System.Runtime.InteropServices.UnmanagedType I1 void System::Runtime::InteropServices::UnmanagedType::_set_I1(::System::Runtime::InteropServices::UnmanagedType value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::UnmanagedType::_set_I1"); THROW_UNLESS(il2cpp_utils::SetFieldValue("System.Runtime.InteropServices", "UnmanagedType", "I1", value)); } // Autogenerated static field getter // Get static field: static public System.Runtime.InteropServices.UnmanagedType U1 ::System::Runtime::InteropServices::UnmanagedType System::Runtime::InteropServices::UnmanagedType::_get_U1() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::UnmanagedType::_get_U1"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<::System::Runtime::InteropServices::UnmanagedType>("System.Runtime.InteropServices", "UnmanagedType", "U1")); } // Autogenerated static field setter // Set static field: static public System.Runtime.InteropServices.UnmanagedType U1 void System::Runtime::InteropServices::UnmanagedType::_set_U1(::System::Runtime::InteropServices::UnmanagedType value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::UnmanagedType::_set_U1"); THROW_UNLESS(il2cpp_utils::SetFieldValue("System.Runtime.InteropServices", "UnmanagedType", "U1", value)); } // Autogenerated static field getter // Get static field: static public System.Runtime.InteropServices.UnmanagedType I2 ::System::Runtime::InteropServices::UnmanagedType System::Runtime::InteropServices::UnmanagedType::_get_I2() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::UnmanagedType::_get_I2"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<::System::Runtime::InteropServices::UnmanagedType>("System.Runtime.InteropServices", "UnmanagedType", "I2")); } // Autogenerated static field setter // Set static field: static public System.Runtime.InteropServices.UnmanagedType I2 void System::Runtime::InteropServices::UnmanagedType::_set_I2(::System::Runtime::InteropServices::UnmanagedType value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::UnmanagedType::_set_I2"); THROW_UNLESS(il2cpp_utils::SetFieldValue("System.Runtime.InteropServices", "UnmanagedType", "I2", value)); } // Autogenerated static field getter // Get static field: static public System.Runtime.InteropServices.UnmanagedType U2 ::System::Runtime::InteropServices::UnmanagedType System::Runtime::InteropServices::UnmanagedType::_get_U2() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::UnmanagedType::_get_U2"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<::System::Runtime::InteropServices::UnmanagedType>("System.Runtime.InteropServices", "UnmanagedType", "U2")); } // Autogenerated static field setter // Set static field: static public System.Runtime.InteropServices.UnmanagedType U2 void System::Runtime::InteropServices::UnmanagedType::_set_U2(::System::Runtime::InteropServices::UnmanagedType value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::UnmanagedType::_set_U2"); THROW_UNLESS(il2cpp_utils::SetFieldValue("System.Runtime.InteropServices", "UnmanagedType", "U2", value)); } // Autogenerated static field getter // Get static field: static public System.Runtime.InteropServices.UnmanagedType I4 ::System::Runtime::InteropServices::UnmanagedType System::Runtime::InteropServices::UnmanagedType::_get_I4() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::UnmanagedType::_get_I4"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<::System::Runtime::InteropServices::UnmanagedType>("System.Runtime.InteropServices", "UnmanagedType", "I4")); } // Autogenerated static field setter // Set static field: static public System.Runtime.InteropServices.UnmanagedType I4 void System::Runtime::InteropServices::UnmanagedType::_set_I4(::System::Runtime::InteropServices::UnmanagedType value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::UnmanagedType::_set_I4"); THROW_UNLESS(il2cpp_utils::SetFieldValue("System.Runtime.InteropServices", "UnmanagedType", "I4", value)); } // Autogenerated static field getter // Get static field: static public System.Runtime.InteropServices.UnmanagedType U4 ::System::Runtime::InteropServices::UnmanagedType System::Runtime::InteropServices::UnmanagedType::_get_U4() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::UnmanagedType::_get_U4"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<::System::Runtime::InteropServices::UnmanagedType>("System.Runtime.InteropServices", "UnmanagedType", "U4")); } // Autogenerated static field setter // Set static field: static public System.Runtime.InteropServices.UnmanagedType U4 void System::Runtime::InteropServices::UnmanagedType::_set_U4(::System::Runtime::InteropServices::UnmanagedType value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::UnmanagedType::_set_U4"); THROW_UNLESS(il2cpp_utils::SetFieldValue("System.Runtime.InteropServices", "UnmanagedType", "U4", value)); } // Autogenerated static field getter // Get static field: static public System.Runtime.InteropServices.UnmanagedType I8 ::System::Runtime::InteropServices::UnmanagedType System::Runtime::InteropServices::UnmanagedType::_get_I8() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::UnmanagedType::_get_I8"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<::System::Runtime::InteropServices::UnmanagedType>("System.Runtime.InteropServices", "UnmanagedType", "I8")); } // Autogenerated static field setter // Set static field: static public System.Runtime.InteropServices.UnmanagedType I8 void System::Runtime::InteropServices::UnmanagedType::_set_I8(::System::Runtime::InteropServices::UnmanagedType value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::UnmanagedType::_set_I8"); THROW_UNLESS(il2cpp_utils::SetFieldValue("System.Runtime.InteropServices", "UnmanagedType", "I8", value)); } // Autogenerated static field getter // Get static field: static public System.Runtime.InteropServices.UnmanagedType U8 ::System::Runtime::InteropServices::UnmanagedType System::Runtime::InteropServices::UnmanagedType::_get_U8() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::UnmanagedType::_get_U8"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<::System::Runtime::InteropServices::UnmanagedType>("System.Runtime.InteropServices", "UnmanagedType", "U8")); } // Autogenerated static field setter // Set static field: static public System.Runtime.InteropServices.UnmanagedType U8 void System::Runtime::InteropServices::UnmanagedType::_set_U8(::System::Runtime::InteropServices::UnmanagedType value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::UnmanagedType::_set_U8"); THROW_UNLESS(il2cpp_utils::SetFieldValue("System.Runtime.InteropServices", "UnmanagedType", "U8", value)); } // Autogenerated static field getter // Get static field: static public System.Runtime.InteropServices.UnmanagedType R4 ::System::Runtime::InteropServices::UnmanagedType System::Runtime::InteropServices::UnmanagedType::_get_R4() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::UnmanagedType::_get_R4"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<::System::Runtime::InteropServices::UnmanagedType>("System.Runtime.InteropServices", "UnmanagedType", "R4")); } // Autogenerated static field setter // Set static field: static public System.Runtime.InteropServices.UnmanagedType R4 void System::Runtime::InteropServices::UnmanagedType::_set_R4(::System::Runtime::InteropServices::UnmanagedType value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::UnmanagedType::_set_R4"); THROW_UNLESS(il2cpp_utils::SetFieldValue("System.Runtime.InteropServices", "UnmanagedType", "R4", value)); } // Autogenerated static field getter // Get static field: static public System.Runtime.InteropServices.UnmanagedType R8 ::System::Runtime::InteropServices::UnmanagedType System::Runtime::InteropServices::UnmanagedType::_get_R8() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::UnmanagedType::_get_R8"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<::System::Runtime::InteropServices::UnmanagedType>("System.Runtime.InteropServices", "UnmanagedType", "R8")); } // Autogenerated static field setter // Set static field: static public System.Runtime.InteropServices.UnmanagedType R8 void System::Runtime::InteropServices::UnmanagedType::_set_R8(::System::Runtime::InteropServices::UnmanagedType value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::UnmanagedType::_set_R8"); THROW_UNLESS(il2cpp_utils::SetFieldValue("System.Runtime.InteropServices", "UnmanagedType", "R8", value)); } // Autogenerated static field getter // Get static field: static public System.Runtime.InteropServices.UnmanagedType Currency ::System::Runtime::InteropServices::UnmanagedType System::Runtime::InteropServices::UnmanagedType::_get_Currency() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::UnmanagedType::_get_Currency"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<::System::Runtime::InteropServices::UnmanagedType>("System.Runtime.InteropServices", "UnmanagedType", "Currency")); } // Autogenerated static field setter // Set static field: static public System.Runtime.InteropServices.UnmanagedType Currency void System::Runtime::InteropServices::UnmanagedType::_set_Currency(::System::Runtime::InteropServices::UnmanagedType value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::UnmanagedType::_set_Currency"); THROW_UNLESS(il2cpp_utils::SetFieldValue("System.Runtime.InteropServices", "UnmanagedType", "Currency", value)); } // Autogenerated static field getter // Get static field: static public System.Runtime.InteropServices.UnmanagedType BStr ::System::Runtime::InteropServices::UnmanagedType System::Runtime::InteropServices::UnmanagedType::_get_BStr() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::UnmanagedType::_get_BStr"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<::System::Runtime::InteropServices::UnmanagedType>("System.Runtime.InteropServices", "UnmanagedType", "BStr")); } // Autogenerated static field setter // Set static field: static public System.Runtime.InteropServices.UnmanagedType BStr void System::Runtime::InteropServices::UnmanagedType::_set_BStr(::System::Runtime::InteropServices::UnmanagedType value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::UnmanagedType::_set_BStr"); THROW_UNLESS(il2cpp_utils::SetFieldValue("System.Runtime.InteropServices", "UnmanagedType", "BStr", value)); } // Autogenerated static field getter // Get static field: static public System.Runtime.InteropServices.UnmanagedType LPStr ::System::Runtime::InteropServices::UnmanagedType System::Runtime::InteropServices::UnmanagedType::_get_LPStr() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::UnmanagedType::_get_LPStr"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<::System::Runtime::InteropServices::UnmanagedType>("System.Runtime.InteropServices", "UnmanagedType", "LPStr")); } // Autogenerated static field setter // Set static field: static public System.Runtime.InteropServices.UnmanagedType LPStr void System::Runtime::InteropServices::UnmanagedType::_set_LPStr(::System::Runtime::InteropServices::UnmanagedType value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::UnmanagedType::_set_LPStr"); THROW_UNLESS(il2cpp_utils::SetFieldValue("System.Runtime.InteropServices", "UnmanagedType", "LPStr", value)); } // Autogenerated static field getter // Get static field: static public System.Runtime.InteropServices.UnmanagedType LPWStr ::System::Runtime::InteropServices::UnmanagedType System::Runtime::InteropServices::UnmanagedType::_get_LPWStr() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::UnmanagedType::_get_LPWStr"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<::System::Runtime::InteropServices::UnmanagedType>("System.Runtime.InteropServices", "UnmanagedType", "LPWStr")); } // Autogenerated static field setter // Set static field: static public System.Runtime.InteropServices.UnmanagedType LPWStr void System::Runtime::InteropServices::UnmanagedType::_set_LPWStr(::System::Runtime::InteropServices::UnmanagedType value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::UnmanagedType::_set_LPWStr"); THROW_UNLESS(il2cpp_utils::SetFieldValue("System.Runtime.InteropServices", "UnmanagedType", "LPWStr", value)); } // Autogenerated static field getter // Get static field: static public System.Runtime.InteropServices.UnmanagedType LPTStr ::System::Runtime::InteropServices::UnmanagedType System::Runtime::InteropServices::UnmanagedType::_get_LPTStr() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::UnmanagedType::_get_LPTStr"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<::System::Runtime::InteropServices::UnmanagedType>("System.Runtime.InteropServices", "UnmanagedType", "LPTStr")); } // Autogenerated static field setter // Set static field: static public System.Runtime.InteropServices.UnmanagedType LPTStr void System::Runtime::InteropServices::UnmanagedType::_set_LPTStr(::System::Runtime::InteropServices::UnmanagedType value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::UnmanagedType::_set_LPTStr"); THROW_UNLESS(il2cpp_utils::SetFieldValue("System.Runtime.InteropServices", "UnmanagedType", "LPTStr", value)); } // Autogenerated static field getter // Get static field: static public System.Runtime.InteropServices.UnmanagedType ByValTStr ::System::Runtime::InteropServices::UnmanagedType System::Runtime::InteropServices::UnmanagedType::_get_ByValTStr() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::UnmanagedType::_get_ByValTStr"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<::System::Runtime::InteropServices::UnmanagedType>("System.Runtime.InteropServices", "UnmanagedType", "ByValTStr")); } // Autogenerated static field setter // Set static field: static public System.Runtime.InteropServices.UnmanagedType ByValTStr void System::Runtime::InteropServices::UnmanagedType::_set_ByValTStr(::System::Runtime::InteropServices::UnmanagedType value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::UnmanagedType::_set_ByValTStr"); THROW_UNLESS(il2cpp_utils::SetFieldValue("System.Runtime.InteropServices", "UnmanagedType", "ByValTStr", value)); } // Autogenerated static field getter // Get static field: static public System.Runtime.InteropServices.UnmanagedType IUnknown ::System::Runtime::InteropServices::UnmanagedType System::Runtime::InteropServices::UnmanagedType::_get_IUnknown() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::UnmanagedType::_get_IUnknown"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<::System::Runtime::InteropServices::UnmanagedType>("System.Runtime.InteropServices", "UnmanagedType", "IUnknown")); } // Autogenerated static field setter // Set static field: static public System.Runtime.InteropServices.UnmanagedType IUnknown void System::Runtime::InteropServices::UnmanagedType::_set_IUnknown(::System::Runtime::InteropServices::UnmanagedType value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::UnmanagedType::_set_IUnknown"); THROW_UNLESS(il2cpp_utils::SetFieldValue("System.Runtime.InteropServices", "UnmanagedType", "IUnknown", value)); } // Autogenerated static field getter // Get static field: static public System.Runtime.InteropServices.UnmanagedType IDispatch ::System::Runtime::InteropServices::UnmanagedType System::Runtime::InteropServices::UnmanagedType::_get_IDispatch() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::UnmanagedType::_get_IDispatch"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<::System::Runtime::InteropServices::UnmanagedType>("System.Runtime.InteropServices", "UnmanagedType", "IDispatch")); } // Autogenerated static field setter // Set static field: static public System.Runtime.InteropServices.UnmanagedType IDispatch void System::Runtime::InteropServices::UnmanagedType::_set_IDispatch(::System::Runtime::InteropServices::UnmanagedType value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::UnmanagedType::_set_IDispatch"); THROW_UNLESS(il2cpp_utils::SetFieldValue("System.Runtime.InteropServices", "UnmanagedType", "IDispatch", value)); } // Autogenerated static field getter // Get static field: static public System.Runtime.InteropServices.UnmanagedType Struct ::System::Runtime::InteropServices::UnmanagedType System::Runtime::InteropServices::UnmanagedType::_get_Struct() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::UnmanagedType::_get_Struct"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<::System::Runtime::InteropServices::UnmanagedType>("System.Runtime.InteropServices", "UnmanagedType", "Struct")); } // Autogenerated static field setter // Set static field: static public System.Runtime.InteropServices.UnmanagedType Struct void System::Runtime::InteropServices::UnmanagedType::_set_Struct(::System::Runtime::InteropServices::UnmanagedType value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::UnmanagedType::_set_Struct"); THROW_UNLESS(il2cpp_utils::SetFieldValue("System.Runtime.InteropServices", "UnmanagedType", "Struct", value)); } // Autogenerated static field getter // Get static field: static public System.Runtime.InteropServices.UnmanagedType Interface ::System::Runtime::InteropServices::UnmanagedType System::Runtime::InteropServices::UnmanagedType::_get_Interface() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::UnmanagedType::_get_Interface"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<::System::Runtime::InteropServices::UnmanagedType>("System.Runtime.InteropServices", "UnmanagedType", "Interface")); } // Autogenerated static field setter // Set static field: static public System.Runtime.InteropServices.UnmanagedType Interface void System::Runtime::InteropServices::UnmanagedType::_set_Interface(::System::Runtime::InteropServices::UnmanagedType value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::UnmanagedType::_set_Interface"); THROW_UNLESS(il2cpp_utils::SetFieldValue("System.Runtime.InteropServices", "UnmanagedType", "Interface", value)); } // Autogenerated static field getter // Get static field: static public System.Runtime.InteropServices.UnmanagedType SafeArray ::System::Runtime::InteropServices::UnmanagedType System::Runtime::InteropServices::UnmanagedType::_get_SafeArray() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::UnmanagedType::_get_SafeArray"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<::System::Runtime::InteropServices::UnmanagedType>("System.Runtime.InteropServices", "UnmanagedType", "SafeArray")); } // Autogenerated static field setter // Set static field: static public System.Runtime.InteropServices.UnmanagedType SafeArray void System::Runtime::InteropServices::UnmanagedType::_set_SafeArray(::System::Runtime::InteropServices::UnmanagedType value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::UnmanagedType::_set_SafeArray"); THROW_UNLESS(il2cpp_utils::SetFieldValue("System.Runtime.InteropServices", "UnmanagedType", "SafeArray", value)); } // Autogenerated static field getter // Get static field: static public System.Runtime.InteropServices.UnmanagedType ByValArray ::System::Runtime::InteropServices::UnmanagedType System::Runtime::InteropServices::UnmanagedType::_get_ByValArray() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::UnmanagedType::_get_ByValArray"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<::System::Runtime::InteropServices::UnmanagedType>("System.Runtime.InteropServices", "UnmanagedType", "ByValArray")); } // Autogenerated static field setter // Set static field: static public System.Runtime.InteropServices.UnmanagedType ByValArray void System::Runtime::InteropServices::UnmanagedType::_set_ByValArray(::System::Runtime::InteropServices::UnmanagedType value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::UnmanagedType::_set_ByValArray"); THROW_UNLESS(il2cpp_utils::SetFieldValue("System.Runtime.InteropServices", "UnmanagedType", "ByValArray", value)); } // Autogenerated static field getter // Get static field: static public System.Runtime.InteropServices.UnmanagedType SysInt ::System::Runtime::InteropServices::UnmanagedType System::Runtime::InteropServices::UnmanagedType::_get_SysInt() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::UnmanagedType::_get_SysInt"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<::System::Runtime::InteropServices::UnmanagedType>("System.Runtime.InteropServices", "UnmanagedType", "SysInt")); } // Autogenerated static field setter // Set static field: static public System.Runtime.InteropServices.UnmanagedType SysInt void System::Runtime::InteropServices::UnmanagedType::_set_SysInt(::System::Runtime::InteropServices::UnmanagedType value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::UnmanagedType::_set_SysInt"); THROW_UNLESS(il2cpp_utils::SetFieldValue("System.Runtime.InteropServices", "UnmanagedType", "SysInt", value)); } // Autogenerated static field getter // Get static field: static public System.Runtime.InteropServices.UnmanagedType SysUInt ::System::Runtime::InteropServices::UnmanagedType System::Runtime::InteropServices::UnmanagedType::_get_SysUInt() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::UnmanagedType::_get_SysUInt"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<::System::Runtime::InteropServices::UnmanagedType>("System.Runtime.InteropServices", "UnmanagedType", "SysUInt")); } // Autogenerated static field setter // Set static field: static public System.Runtime.InteropServices.UnmanagedType SysUInt void System::Runtime::InteropServices::UnmanagedType::_set_SysUInt(::System::Runtime::InteropServices::UnmanagedType value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::UnmanagedType::_set_SysUInt"); THROW_UNLESS(il2cpp_utils::SetFieldValue("System.Runtime.InteropServices", "UnmanagedType", "SysUInt", value)); } // Autogenerated static field getter // Get static field: static public System.Runtime.InteropServices.UnmanagedType VBByRefStr ::System::Runtime::InteropServices::UnmanagedType System::Runtime::InteropServices::UnmanagedType::_get_VBByRefStr() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::UnmanagedType::_get_VBByRefStr"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<::System::Runtime::InteropServices::UnmanagedType>("System.Runtime.InteropServices", "UnmanagedType", "VBByRefStr")); } // Autogenerated static field setter // Set static field: static public System.Runtime.InteropServices.UnmanagedType VBByRefStr void System::Runtime::InteropServices::UnmanagedType::_set_VBByRefStr(::System::Runtime::InteropServices::UnmanagedType value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::UnmanagedType::_set_VBByRefStr"); THROW_UNLESS(il2cpp_utils::SetFieldValue("System.Runtime.InteropServices", "UnmanagedType", "VBByRefStr", value)); } // Autogenerated static field getter // Get static field: static public System.Runtime.InteropServices.UnmanagedType AnsiBStr ::System::Runtime::InteropServices::UnmanagedType System::Runtime::InteropServices::UnmanagedType::_get_AnsiBStr() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::UnmanagedType::_get_AnsiBStr"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<::System::Runtime::InteropServices::UnmanagedType>("System.Runtime.InteropServices", "UnmanagedType", "AnsiBStr")); } // Autogenerated static field setter // Set static field: static public System.Runtime.InteropServices.UnmanagedType AnsiBStr void System::Runtime::InteropServices::UnmanagedType::_set_AnsiBStr(::System::Runtime::InteropServices::UnmanagedType value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::UnmanagedType::_set_AnsiBStr"); THROW_UNLESS(il2cpp_utils::SetFieldValue("System.Runtime.InteropServices", "UnmanagedType", "AnsiBStr", value)); } // Autogenerated static field getter // Get static field: static public System.Runtime.InteropServices.UnmanagedType TBStr ::System::Runtime::InteropServices::UnmanagedType System::Runtime::InteropServices::UnmanagedType::_get_TBStr() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::UnmanagedType::_get_TBStr"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<::System::Runtime::InteropServices::UnmanagedType>("System.Runtime.InteropServices", "UnmanagedType", "TBStr")); } // Autogenerated static field setter // Set static field: static public System.Runtime.InteropServices.UnmanagedType TBStr void System::Runtime::InteropServices::UnmanagedType::_set_TBStr(::System::Runtime::InteropServices::UnmanagedType value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::UnmanagedType::_set_TBStr"); THROW_UNLESS(il2cpp_utils::SetFieldValue("System.Runtime.InteropServices", "UnmanagedType", "TBStr", value)); } // Autogenerated static field getter // Get static field: static public System.Runtime.InteropServices.UnmanagedType VariantBool ::System::Runtime::InteropServices::UnmanagedType System::Runtime::InteropServices::UnmanagedType::_get_VariantBool() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::UnmanagedType::_get_VariantBool"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<::System::Runtime::InteropServices::UnmanagedType>("System.Runtime.InteropServices", "UnmanagedType", "VariantBool")); } // Autogenerated static field setter // Set static field: static public System.Runtime.InteropServices.UnmanagedType VariantBool void System::Runtime::InteropServices::UnmanagedType::_set_VariantBool(::System::Runtime::InteropServices::UnmanagedType value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::UnmanagedType::_set_VariantBool"); THROW_UNLESS(il2cpp_utils::SetFieldValue("System.Runtime.InteropServices", "UnmanagedType", "VariantBool", value)); } // Autogenerated static field getter // Get static field: static public System.Runtime.InteropServices.UnmanagedType FunctionPtr ::System::Runtime::InteropServices::UnmanagedType System::Runtime::InteropServices::UnmanagedType::_get_FunctionPtr() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::UnmanagedType::_get_FunctionPtr"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<::System::Runtime::InteropServices::UnmanagedType>("System.Runtime.InteropServices", "UnmanagedType", "FunctionPtr")); } // Autogenerated static field setter // Set static field: static public System.Runtime.InteropServices.UnmanagedType FunctionPtr void System::Runtime::InteropServices::UnmanagedType::_set_FunctionPtr(::System::Runtime::InteropServices::UnmanagedType value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::UnmanagedType::_set_FunctionPtr"); THROW_UNLESS(il2cpp_utils::SetFieldValue("System.Runtime.InteropServices", "UnmanagedType", "FunctionPtr", value)); } // Autogenerated static field getter // Get static field: static public System.Runtime.InteropServices.UnmanagedType AsAny ::System::Runtime::InteropServices::UnmanagedType System::Runtime::InteropServices::UnmanagedType::_get_AsAny() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::UnmanagedType::_get_AsAny"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<::System::Runtime::InteropServices::UnmanagedType>("System.Runtime.InteropServices", "UnmanagedType", "AsAny")); } // Autogenerated static field setter // Set static field: static public System.Runtime.InteropServices.UnmanagedType AsAny void System::Runtime::InteropServices::UnmanagedType::_set_AsAny(::System::Runtime::InteropServices::UnmanagedType value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::UnmanagedType::_set_AsAny"); THROW_UNLESS(il2cpp_utils::SetFieldValue("System.Runtime.InteropServices", "UnmanagedType", "AsAny", value)); } // Autogenerated static field getter // Get static field: static public System.Runtime.InteropServices.UnmanagedType LPArray ::System::Runtime::InteropServices::UnmanagedType System::Runtime::InteropServices::UnmanagedType::_get_LPArray() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::UnmanagedType::_get_LPArray"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<::System::Runtime::InteropServices::UnmanagedType>("System.Runtime.InteropServices", "UnmanagedType", "LPArray")); } // Autogenerated static field setter // Set static field: static public System.Runtime.InteropServices.UnmanagedType LPArray void System::Runtime::InteropServices::UnmanagedType::_set_LPArray(::System::Runtime::InteropServices::UnmanagedType value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::UnmanagedType::_set_LPArray"); THROW_UNLESS(il2cpp_utils::SetFieldValue("System.Runtime.InteropServices", "UnmanagedType", "LPArray", value)); } // Autogenerated static field getter // Get static field: static public System.Runtime.InteropServices.UnmanagedType LPStruct ::System::Runtime::InteropServices::UnmanagedType System::Runtime::InteropServices::UnmanagedType::_get_LPStruct() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::UnmanagedType::_get_LPStruct"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<::System::Runtime::InteropServices::UnmanagedType>("System.Runtime.InteropServices", "UnmanagedType", "LPStruct")); } // Autogenerated static field setter // Set static field: static public System.Runtime.InteropServices.UnmanagedType LPStruct void System::Runtime::InteropServices::UnmanagedType::_set_LPStruct(::System::Runtime::InteropServices::UnmanagedType value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::UnmanagedType::_set_LPStruct"); THROW_UNLESS(il2cpp_utils::SetFieldValue("System.Runtime.InteropServices", "UnmanagedType", "LPStruct", value)); } // Autogenerated static field getter // Get static field: static public System.Runtime.InteropServices.UnmanagedType CustomMarshaler ::System::Runtime::InteropServices::UnmanagedType System::Runtime::InteropServices::UnmanagedType::_get_CustomMarshaler() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::UnmanagedType::_get_CustomMarshaler"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<::System::Runtime::InteropServices::UnmanagedType>("System.Runtime.InteropServices", "UnmanagedType", "CustomMarshaler")); } // Autogenerated static field setter // Set static field: static public System.Runtime.InteropServices.UnmanagedType CustomMarshaler void System::Runtime::InteropServices::UnmanagedType::_set_CustomMarshaler(::System::Runtime::InteropServices::UnmanagedType value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::UnmanagedType::_set_CustomMarshaler"); THROW_UNLESS(il2cpp_utils::SetFieldValue("System.Runtime.InteropServices", "UnmanagedType", "CustomMarshaler", value)); } // Autogenerated static field getter // Get static field: static public System.Runtime.InteropServices.UnmanagedType Error ::System::Runtime::InteropServices::UnmanagedType System::Runtime::InteropServices::UnmanagedType::_get_Error() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::UnmanagedType::_get_Error"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<::System::Runtime::InteropServices::UnmanagedType>("System.Runtime.InteropServices", "UnmanagedType", "Error")); } // Autogenerated static field setter // Set static field: static public System.Runtime.InteropServices.UnmanagedType Error void System::Runtime::InteropServices::UnmanagedType::_set_Error(::System::Runtime::InteropServices::UnmanagedType value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::UnmanagedType::_set_Error"); THROW_UNLESS(il2cpp_utils::SetFieldValue("System.Runtime.InteropServices", "UnmanagedType", "Error", value)); } // [ComVisibleAttribute] Offset: 0x68918C // Autogenerated static field getter // Get static field: static public System.Runtime.InteropServices.UnmanagedType IInspectable ::System::Runtime::InteropServices::UnmanagedType System::Runtime::InteropServices::UnmanagedType::_get_IInspectable() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::UnmanagedType::_get_IInspectable"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<::System::Runtime::InteropServices::UnmanagedType>("System.Runtime.InteropServices", "UnmanagedType", "IInspectable")); } // Autogenerated static field setter // Set static field: static public System.Runtime.InteropServices.UnmanagedType IInspectable void System::Runtime::InteropServices::UnmanagedType::_set_IInspectable(::System::Runtime::InteropServices::UnmanagedType value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::UnmanagedType::_set_IInspectable"); THROW_UNLESS(il2cpp_utils::SetFieldValue("System.Runtime.InteropServices", "UnmanagedType", "IInspectable", value)); } // [ComVisibleAttribute] Offset: 0x6891A0 // Autogenerated static field getter // Get static field: static public System.Runtime.InteropServices.UnmanagedType HString ::System::Runtime::InteropServices::UnmanagedType System::Runtime::InteropServices::UnmanagedType::_get_HString() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::UnmanagedType::_get_HString"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<::System::Runtime::InteropServices::UnmanagedType>("System.Runtime.InteropServices", "UnmanagedType", "HString")); } // Autogenerated static field setter // Set static field: static public System.Runtime.InteropServices.UnmanagedType HString void System::Runtime::InteropServices::UnmanagedType::_set_HString(::System::Runtime::InteropServices::UnmanagedType value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::UnmanagedType::_set_HString"); THROW_UNLESS(il2cpp_utils::SetFieldValue("System.Runtime.InteropServices", "UnmanagedType", "HString", value)); } // [ComVisibleAttribute] Offset: 0x6891B4 // Autogenerated static field getter // Get static field: static public System.Runtime.InteropServices.UnmanagedType LPUTF8Str ::System::Runtime::InteropServices::UnmanagedType System::Runtime::InteropServices::UnmanagedType::_get_LPUTF8Str() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::UnmanagedType::_get_LPUTF8Str"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<::System::Runtime::InteropServices::UnmanagedType>("System.Runtime.InteropServices", "UnmanagedType", "LPUTF8Str")); } // Autogenerated static field setter // Set static field: static public System.Runtime.InteropServices.UnmanagedType LPUTF8Str void System::Runtime::InteropServices::UnmanagedType::_set_LPUTF8Str(::System::Runtime::InteropServices::UnmanagedType value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::UnmanagedType::_set_LPUTF8Str"); THROW_UNLESS(il2cpp_utils::SetFieldValue("System.Runtime.InteropServices", "UnmanagedType", "LPUTF8Str", value)); } // Autogenerated instance field getter // Get instance field: public System.Int32 value__ [[deprecated("Use field access instead!")]] int& System::Runtime::InteropServices::UnmanagedType::dyn_value__() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::UnmanagedType::dyn_value__"); auto ___internal__instance = *this; static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "value__"))->offset; return *reinterpret_cast<int*>(reinterpret_cast<char*>(this) + ___internal__field__offset); } // Autogenerated from CppSourceCreator // Created by Sc2ad // ========================================================================= // Begin includes // Including type: System.Runtime.InteropServices.ComImportAttribute #include "System/Runtime/InteropServices/ComImportAttribute.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils.hpp" #include "beatsaber-hook/shared/utils/utils.h" // Completed includes // Autogenerated from CppSourceCreator // Created by Sc2ad // ========================================================================= // Begin includes // Including type: System.Runtime.InteropServices.GuidAttribute #include "System/Runtime/InteropServices/GuidAttribute.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils.hpp" #include "beatsaber-hook/shared/utils/utils.h" // Completed includes // Autogenerated instance field getter // Get instance field: System.String _val [[deprecated("Use field access instead!")]] ::StringW& System::Runtime::InteropServices::GuidAttribute::dyn__val() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::GuidAttribute::dyn__val"); auto ___internal__instance = this; static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "_val"))->offset; return *reinterpret_cast<::StringW*>(reinterpret_cast<char*>(this) + ___internal__field__offset); } // Autogenerated from CppSourceCreator // Created by Sc2ad // ========================================================================= // Begin includes // Including type: System.Runtime.InteropServices.PreserveSigAttribute #include "System/Runtime/InteropServices/PreserveSigAttribute.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils.hpp" #include "beatsaber-hook/shared/utils/utils.h" // Completed includes // Autogenerated from CppSourceCreator // Created by Sc2ad // ========================================================================= // Begin includes // Including type: System.Runtime.InteropServices.InAttribute #include "System/Runtime/InteropServices/InAttribute.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils.hpp" #include "beatsaber-hook/shared/utils/utils.h" // Completed includes // Autogenerated from CppSourceCreator // Created by Sc2ad // ========================================================================= // Begin includes // Including type: System.Runtime.InteropServices.OutAttribute #include "System/Runtime/InteropServices/OutAttribute.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils.hpp" #include "beatsaber-hook/shared/utils/utils.h" // Completed includes // Autogenerated from CppSourceCreator // Created by Sc2ad // ========================================================================= // Begin includes // Including type: System.Runtime.InteropServices.OptionalAttribute #include "System/Runtime/InteropServices/OptionalAttribute.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils.hpp" #include "beatsaber-hook/shared/utils/utils.h" // Completed includes // Autogenerated from CppSourceCreator // Created by Sc2ad // ========================================================================= // Begin includes // Including type: System.Runtime.InteropServices.DllImportSearchPath #include "System/Runtime/InteropServices/DllImportSearchPath.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils.hpp" #include "beatsaber-hook/shared/utils/utils.h" // Completed includes // Autogenerated static field getter // Get static field: static public System.Runtime.InteropServices.DllImportSearchPath UseDllDirectoryForDependencies ::System::Runtime::InteropServices::DllImportSearchPath System::Runtime::InteropServices::DllImportSearchPath::_get_UseDllDirectoryForDependencies() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::DllImportSearchPath::_get_UseDllDirectoryForDependencies"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<::System::Runtime::InteropServices::DllImportSearchPath>("System.Runtime.InteropServices", "DllImportSearchPath", "UseDllDirectoryForDependencies")); } // Autogenerated static field setter // Set static field: static public System.Runtime.InteropServices.DllImportSearchPath UseDllDirectoryForDependencies void System::Runtime::InteropServices::DllImportSearchPath::_set_UseDllDirectoryForDependencies(::System::Runtime::InteropServices::DllImportSearchPath value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::DllImportSearchPath::_set_UseDllDirectoryForDependencies"); THROW_UNLESS(il2cpp_utils::SetFieldValue("System.Runtime.InteropServices", "DllImportSearchPath", "UseDllDirectoryForDependencies", value)); } // Autogenerated static field getter // Get static field: static public System.Runtime.InteropServices.DllImportSearchPath ApplicationDirectory ::System::Runtime::InteropServices::DllImportSearchPath System::Runtime::InteropServices::DllImportSearchPath::_get_ApplicationDirectory() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::DllImportSearchPath::_get_ApplicationDirectory"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<::System::Runtime::InteropServices::DllImportSearchPath>("System.Runtime.InteropServices", "DllImportSearchPath", "ApplicationDirectory")); } // Autogenerated static field setter // Set static field: static public System.Runtime.InteropServices.DllImportSearchPath ApplicationDirectory void System::Runtime::InteropServices::DllImportSearchPath::_set_ApplicationDirectory(::System::Runtime::InteropServices::DllImportSearchPath value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::DllImportSearchPath::_set_ApplicationDirectory"); THROW_UNLESS(il2cpp_utils::SetFieldValue("System.Runtime.InteropServices", "DllImportSearchPath", "ApplicationDirectory", value)); } // Autogenerated static field getter // Get static field: static public System.Runtime.InteropServices.DllImportSearchPath UserDirectories ::System::Runtime::InteropServices::DllImportSearchPath System::Runtime::InteropServices::DllImportSearchPath::_get_UserDirectories() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::DllImportSearchPath::_get_UserDirectories"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<::System::Runtime::InteropServices::DllImportSearchPath>("System.Runtime.InteropServices", "DllImportSearchPath", "UserDirectories")); } // Autogenerated static field setter // Set static field: static public System.Runtime.InteropServices.DllImportSearchPath UserDirectories void System::Runtime::InteropServices::DllImportSearchPath::_set_UserDirectories(::System::Runtime::InteropServices::DllImportSearchPath value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::DllImportSearchPath::_set_UserDirectories"); THROW_UNLESS(il2cpp_utils::SetFieldValue("System.Runtime.InteropServices", "DllImportSearchPath", "UserDirectories", value)); } // Autogenerated static field getter // Get static field: static public System.Runtime.InteropServices.DllImportSearchPath System32 ::System::Runtime::InteropServices::DllImportSearchPath System::Runtime::InteropServices::DllImportSearchPath::_get_System32() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::DllImportSearchPath::_get_System32"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<::System::Runtime::InteropServices::DllImportSearchPath>("System.Runtime.InteropServices", "DllImportSearchPath", "System32")); } // Autogenerated static field setter // Set static field: static public System.Runtime.InteropServices.DllImportSearchPath System32 void System::Runtime::InteropServices::DllImportSearchPath::_set_System32(::System::Runtime::InteropServices::DllImportSearchPath value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::DllImportSearchPath::_set_System32"); THROW_UNLESS(il2cpp_utils::SetFieldValue("System.Runtime.InteropServices", "DllImportSearchPath", "System32", value)); } // Autogenerated static field getter // Get static field: static public System.Runtime.InteropServices.DllImportSearchPath SafeDirectories ::System::Runtime::InteropServices::DllImportSearchPath System::Runtime::InteropServices::DllImportSearchPath::_get_SafeDirectories() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::DllImportSearchPath::_get_SafeDirectories"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<::System::Runtime::InteropServices::DllImportSearchPath>("System.Runtime.InteropServices", "DllImportSearchPath", "SafeDirectories")); } // Autogenerated static field setter // Set static field: static public System.Runtime.InteropServices.DllImportSearchPath SafeDirectories void System::Runtime::InteropServices::DllImportSearchPath::_set_SafeDirectories(::System::Runtime::InteropServices::DllImportSearchPath value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::DllImportSearchPath::_set_SafeDirectories"); THROW_UNLESS(il2cpp_utils::SetFieldValue("System.Runtime.InteropServices", "DllImportSearchPath", "SafeDirectories", value)); } // Autogenerated static field getter // Get static field: static public System.Runtime.InteropServices.DllImportSearchPath AssemblyDirectory ::System::Runtime::InteropServices::DllImportSearchPath System::Runtime::InteropServices::DllImportSearchPath::_get_AssemblyDirectory() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::DllImportSearchPath::_get_AssemblyDirectory"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<::System::Runtime::InteropServices::DllImportSearchPath>("System.Runtime.InteropServices", "DllImportSearchPath", "AssemblyDirectory")); } // Autogenerated static field setter // Set static field: static public System.Runtime.InteropServices.DllImportSearchPath AssemblyDirectory void System::Runtime::InteropServices::DllImportSearchPath::_set_AssemblyDirectory(::System::Runtime::InteropServices::DllImportSearchPath value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::DllImportSearchPath::_set_AssemblyDirectory"); THROW_UNLESS(il2cpp_utils::SetFieldValue("System.Runtime.InteropServices", "DllImportSearchPath", "AssemblyDirectory", value)); } // Autogenerated static field getter // Get static field: static public System.Runtime.InteropServices.DllImportSearchPath LegacyBehavior ::System::Runtime::InteropServices::DllImportSearchPath System::Runtime::InteropServices::DllImportSearchPath::_get_LegacyBehavior() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::DllImportSearchPath::_get_LegacyBehavior"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<::System::Runtime::InteropServices::DllImportSearchPath>("System.Runtime.InteropServices", "DllImportSearchPath", "LegacyBehavior")); } // Autogenerated static field setter // Set static field: static public System.Runtime.InteropServices.DllImportSearchPath LegacyBehavior void System::Runtime::InteropServices::DllImportSearchPath::_set_LegacyBehavior(::System::Runtime::InteropServices::DllImportSearchPath value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::DllImportSearchPath::_set_LegacyBehavior"); THROW_UNLESS(il2cpp_utils::SetFieldValue("System.Runtime.InteropServices", "DllImportSearchPath", "LegacyBehavior", value)); } // Autogenerated instance field getter // Get instance field: public System.Int32 value__ [[deprecated("Use field access instead!")]] int& System::Runtime::InteropServices::DllImportSearchPath::dyn_value__() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::DllImportSearchPath::dyn_value__"); auto ___internal__instance = *this; static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "value__"))->offset; return *reinterpret_cast<int*>(reinterpret_cast<char*>(this) + ___internal__field__offset); } // Autogenerated from CppSourceCreator // Created by Sc2ad // ========================================================================= // Begin includes // Including type: System.Runtime.InteropServices.DefaultDllImportSearchPathsAttribute #include "System/Runtime/InteropServices/DefaultDllImportSearchPathsAttribute.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils.hpp" #include "beatsaber-hook/shared/utils/utils.h" // Completed includes // Autogenerated instance field getter // Get instance field: System.Runtime.InteropServices.DllImportSearchPath _paths [[deprecated("Use field access instead!")]] ::System::Runtime::InteropServices::DllImportSearchPath& System::Runtime::InteropServices::DefaultDllImportSearchPathsAttribute::dyn__paths() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::DefaultDllImportSearchPathsAttribute::dyn__paths"); auto ___internal__instance = this; static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "_paths"))->offset; return *reinterpret_cast<::System::Runtime::InteropServices::DllImportSearchPath*>(reinterpret_cast<char*>(this) + ___internal__field__offset); } // Autogenerated from CppSourceCreator // Created by Sc2ad // ========================================================================= // Begin includes // Including type: System.Runtime.InteropServices.DllImportAttribute #include "System/Runtime/InteropServices/DllImportAttribute.hpp" // Including type: System.Reflection.RuntimeMethodInfo #include "System/Reflection/RuntimeMethodInfo.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils.hpp" #include "beatsaber-hook/shared/utils/utils.h" // Completed includes // Autogenerated instance field getter // Get instance field: System.String _val [[deprecated("Use field access instead!")]] ::StringW& System::Runtime::InteropServices::DllImportAttribute::dyn__val() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::DllImportAttribute::dyn__val"); auto ___internal__instance = this; static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "_val"))->offset; return *reinterpret_cast<::StringW*>(reinterpret_cast<char*>(this) + ___internal__field__offset); } // Autogenerated instance field getter // Get instance field: public System.String EntryPoint [[deprecated("Use field access instead!")]] ::StringW& System::Runtime::InteropServices::DllImportAttribute::dyn_EntryPoint() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::DllImportAttribute::dyn_EntryPoint"); auto ___internal__instance = this; static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "EntryPoint"))->offset; return *reinterpret_cast<::StringW*>(reinterpret_cast<char*>(this) + ___internal__field__offset); } // Autogenerated instance field getter // Get instance field: public System.Runtime.InteropServices.CharSet CharSet [[deprecated("Use field access instead!")]] ::System::Runtime::InteropServices::CharSet& System::Runtime::InteropServices::DllImportAttribute::dyn_CharSet() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::DllImportAttribute::dyn_CharSet"); auto ___internal__instance = this; static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "CharSet"))->offset; return *reinterpret_cast<::System::Runtime::InteropServices::CharSet*>(reinterpret_cast<char*>(this) + ___internal__field__offset); } // Autogenerated instance field getter // Get instance field: public System.Boolean SetLastError [[deprecated("Use field access instead!")]] bool& System::Runtime::InteropServices::DllImportAttribute::dyn_SetLastError() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::DllImportAttribute::dyn_SetLastError"); auto ___internal__instance = this; static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "SetLastError"))->offset; return *reinterpret_cast<bool*>(reinterpret_cast<char*>(this) + ___internal__field__offset); } // Autogenerated instance field getter // Get instance field: public System.Boolean ExactSpelling [[deprecated("Use field access instead!")]] bool& System::Runtime::InteropServices::DllImportAttribute::dyn_ExactSpelling() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::DllImportAttribute::dyn_ExactSpelling"); auto ___internal__instance = this; static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "ExactSpelling"))->offset; return *reinterpret_cast<bool*>(reinterpret_cast<char*>(this) + ___internal__field__offset); } // Autogenerated instance field getter // Get instance field: public System.Boolean PreserveSig [[deprecated("Use field access instead!")]] bool& System::Runtime::InteropServices::DllImportAttribute::dyn_PreserveSig() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::DllImportAttribute::dyn_PreserveSig"); auto ___internal__instance = this; static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "PreserveSig"))->offset; return *reinterpret_cast<bool*>(reinterpret_cast<char*>(this) + ___internal__field__offset); } // Autogenerated instance field getter // Get instance field: public System.Runtime.InteropServices.CallingConvention CallingConvention [[deprecated("Use field access instead!")]] ::System::Runtime::InteropServices::CallingConvention& System::Runtime::InteropServices::DllImportAttribute::dyn_CallingConvention() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::DllImportAttribute::dyn_CallingConvention"); auto ___internal__instance = this; static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "CallingConvention"))->offset; return *reinterpret_cast<::System::Runtime::InteropServices::CallingConvention*>(reinterpret_cast<char*>(this) + ___internal__field__offset); } // Autogenerated instance field getter // Get instance field: public System.Boolean BestFitMapping [[deprecated("Use field access instead!")]] bool& System::Runtime::InteropServices::DllImportAttribute::dyn_BestFitMapping() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::DllImportAttribute::dyn_BestFitMapping"); auto ___internal__instance = this; static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "BestFitMapping"))->offset; return *reinterpret_cast<bool*>(reinterpret_cast<char*>(this) + ___internal__field__offset); } // Autogenerated instance field getter // Get instance field: public System.Boolean ThrowOnUnmappableChar [[deprecated("Use field access instead!")]] bool& System::Runtime::InteropServices::DllImportAttribute::dyn_ThrowOnUnmappableChar() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::DllImportAttribute::dyn_ThrowOnUnmappableChar"); auto ___internal__instance = this; static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "ThrowOnUnmappableChar"))->offset; return *reinterpret_cast<bool*>(reinterpret_cast<char*>(this) + ___internal__field__offset); } // Autogenerated method: System.Runtime.InteropServices.DllImportAttribute.get_Value ::StringW System::Runtime::InteropServices::DllImportAttribute::get_Value() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::DllImportAttribute::get_Value"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "get_Value", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); return ::il2cpp_utils::RunMethodRethrow<::StringW, false>(this, ___internal__method); } // Autogenerated method: System.Runtime.InteropServices.DllImportAttribute.GetCustomAttribute ::System::Attribute* System::Runtime::InteropServices::DllImportAttribute::GetCustomAttribute(::System::Reflection::RuntimeMethodInfo* method) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::DllImportAttribute::GetCustomAttribute"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Runtime.InteropServices", "DllImportAttribute", "GetCustomAttribute", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(method)}))); return ::il2cpp_utils::RunMethodRethrow<::System::Attribute*, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method, method); } // Autogenerated method: System.Runtime.InteropServices.DllImportAttribute.IsDefined bool System::Runtime::InteropServices::DllImportAttribute::IsDefined(::System::Reflection::RuntimeMethodInfo* method) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::DllImportAttribute::IsDefined"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Runtime.InteropServices", "DllImportAttribute", "IsDefined", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(method)}))); return ::il2cpp_utils::RunMethodRethrow<bool, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method, method); } // Autogenerated from CppSourceCreator // Created by Sc2ad // ========================================================================= // Begin includes // Including type: System.Runtime.InteropServices.FieldOffsetAttribute #include "System/Runtime/InteropServices/FieldOffsetAttribute.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils.hpp" #include "beatsaber-hook/shared/utils/utils.h" // Completed includes // Autogenerated instance field getter // Get instance field: System.Int32 _val [[deprecated("Use field access instead!")]] int& System::Runtime::InteropServices::FieldOffsetAttribute::dyn__val() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::FieldOffsetAttribute::dyn__val"); auto ___internal__instance = this; static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "_val"))->offset; return *reinterpret_cast<int*>(reinterpret_cast<char*>(this) + ___internal__field__offset); } // Autogenerated from CppSourceCreator // Created by Sc2ad // ========================================================================= // Begin includes // Including type: System.Runtime.InteropServices.ComCompatibleVersionAttribute #include "System/Runtime/InteropServices/ComCompatibleVersionAttribute.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils.hpp" #include "beatsaber-hook/shared/utils/utils.h" // Completed includes // Autogenerated instance field getter // Get instance field: System.Int32 _major [[deprecated("Use field access instead!")]] int& System::Runtime::InteropServices::ComCompatibleVersionAttribute::dyn__major() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::ComCompatibleVersionAttribute::dyn__major"); auto ___internal__instance = this; static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "_major"))->offset; return *reinterpret_cast<int*>(reinterpret_cast<char*>(this) + ___internal__field__offset); } // Autogenerated instance field getter // Get instance field: System.Int32 _minor [[deprecated("Use field access instead!")]] int& System::Runtime::InteropServices::ComCompatibleVersionAttribute::dyn__minor() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::ComCompatibleVersionAttribute::dyn__minor"); auto ___internal__instance = this; static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "_minor"))->offset; return *reinterpret_cast<int*>(reinterpret_cast<char*>(this) + ___internal__field__offset); } // Autogenerated instance field getter // Get instance field: System.Int32 _build [[deprecated("Use field access instead!")]] int& System::Runtime::InteropServices::ComCompatibleVersionAttribute::dyn__build() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::ComCompatibleVersionAttribute::dyn__build"); auto ___internal__instance = this; static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "_build"))->offset; return *reinterpret_cast<int*>(reinterpret_cast<char*>(this) + ___internal__field__offset); } // Autogenerated instance field getter // Get instance field: System.Int32 _revision [[deprecated("Use field access instead!")]] int& System::Runtime::InteropServices::ComCompatibleVersionAttribute::dyn__revision() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::ComCompatibleVersionAttribute::dyn__revision"); auto ___internal__instance = this; static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "_revision"))->offset; return *reinterpret_cast<int*>(reinterpret_cast<char*>(this) + ___internal__field__offset); } // Autogenerated from CppSourceCreator // Created by Sc2ad // ========================================================================= // Begin includes // Including type: System.Runtime.InteropServices.CallingConvention #include "System/Runtime/InteropServices/CallingConvention.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils.hpp" #include "beatsaber-hook/shared/utils/utils.h" // Completed includes // Autogenerated static field getter // Get static field: static public System.Runtime.InteropServices.CallingConvention Winapi ::System::Runtime::InteropServices::CallingConvention System::Runtime::InteropServices::CallingConvention::_get_Winapi() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::CallingConvention::_get_Winapi"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<::System::Runtime::InteropServices::CallingConvention>("System.Runtime.InteropServices", "CallingConvention", "Winapi")); } // Autogenerated static field setter // Set static field: static public System.Runtime.InteropServices.CallingConvention Winapi void System::Runtime::InteropServices::CallingConvention::_set_Winapi(::System::Runtime::InteropServices::CallingConvention value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::CallingConvention::_set_Winapi"); THROW_UNLESS(il2cpp_utils::SetFieldValue("System.Runtime.InteropServices", "CallingConvention", "Winapi", value)); } // Autogenerated static field getter // Get static field: static public System.Runtime.InteropServices.CallingConvention Cdecl ::System::Runtime::InteropServices::CallingConvention System::Runtime::InteropServices::CallingConvention::_get_Cdecl() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::CallingConvention::_get_Cdecl"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<::System::Runtime::InteropServices::CallingConvention>("System.Runtime.InteropServices", "CallingConvention", "Cdecl")); } // Autogenerated static field setter // Set static field: static public System.Runtime.InteropServices.CallingConvention Cdecl void System::Runtime::InteropServices::CallingConvention::_set_Cdecl(::System::Runtime::InteropServices::CallingConvention value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::CallingConvention::_set_Cdecl"); THROW_UNLESS(il2cpp_utils::SetFieldValue("System.Runtime.InteropServices", "CallingConvention", "Cdecl", value)); } // Autogenerated static field getter // Get static field: static public System.Runtime.InteropServices.CallingConvention StdCall ::System::Runtime::InteropServices::CallingConvention System::Runtime::InteropServices::CallingConvention::_get_StdCall() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::CallingConvention::_get_StdCall"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<::System::Runtime::InteropServices::CallingConvention>("System.Runtime.InteropServices", "CallingConvention", "StdCall")); } // Autogenerated static field setter // Set static field: static public System.Runtime.InteropServices.CallingConvention StdCall void System::Runtime::InteropServices::CallingConvention::_set_StdCall(::System::Runtime::InteropServices::CallingConvention value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::CallingConvention::_set_StdCall"); THROW_UNLESS(il2cpp_utils::SetFieldValue("System.Runtime.InteropServices", "CallingConvention", "StdCall", value)); } // Autogenerated static field getter // Get static field: static public System.Runtime.InteropServices.CallingConvention ThisCall ::System::Runtime::InteropServices::CallingConvention System::Runtime::InteropServices::CallingConvention::_get_ThisCall() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::CallingConvention::_get_ThisCall"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<::System::Runtime::InteropServices::CallingConvention>("System.Runtime.InteropServices", "CallingConvention", "ThisCall")); } // Autogenerated static field setter // Set static field: static public System.Runtime.InteropServices.CallingConvention ThisCall void System::Runtime::InteropServices::CallingConvention::_set_ThisCall(::System::Runtime::InteropServices::CallingConvention value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::CallingConvention::_set_ThisCall"); THROW_UNLESS(il2cpp_utils::SetFieldValue("System.Runtime.InteropServices", "CallingConvention", "ThisCall", value)); } // Autogenerated static field getter // Get static field: static public System.Runtime.InteropServices.CallingConvention FastCall ::System::Runtime::InteropServices::CallingConvention System::Runtime::InteropServices::CallingConvention::_get_FastCall() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::CallingConvention::_get_FastCall"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<::System::Runtime::InteropServices::CallingConvention>("System.Runtime.InteropServices", "CallingConvention", "FastCall")); } // Autogenerated static field setter // Set static field: static public System.Runtime.InteropServices.CallingConvention FastCall void System::Runtime::InteropServices::CallingConvention::_set_FastCall(::System::Runtime::InteropServices::CallingConvention value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::CallingConvention::_set_FastCall"); THROW_UNLESS(il2cpp_utils::SetFieldValue("System.Runtime.InteropServices", "CallingConvention", "FastCall", value)); } // Autogenerated instance field getter // Get instance field: public System.Int32 value__ [[deprecated("Use field access instead!")]] int& System::Runtime::InteropServices::CallingConvention::dyn_value__() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::CallingConvention::dyn_value__"); auto ___internal__instance = *this; static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "value__"))->offset; return *reinterpret_cast<int*>(reinterpret_cast<char*>(this) + ___internal__field__offset); } // Autogenerated from CppSourceCreator // Created by Sc2ad // ========================================================================= // Begin includes // Including type: System.Runtime.InteropServices.CharSet #include "System/Runtime/InteropServices/CharSet.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils.hpp" #include "beatsaber-hook/shared/utils/utils.h" // Completed includes // Autogenerated static field getter // Get static field: static public System.Runtime.InteropServices.CharSet None ::System::Runtime::InteropServices::CharSet System::Runtime::InteropServices::CharSet::_get_None() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::CharSet::_get_None"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<::System::Runtime::InteropServices::CharSet>("System.Runtime.InteropServices", "CharSet", "None")); } // Autogenerated static field setter // Set static field: static public System.Runtime.InteropServices.CharSet None void System::Runtime::InteropServices::CharSet::_set_None(::System::Runtime::InteropServices::CharSet value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::CharSet::_set_None"); THROW_UNLESS(il2cpp_utils::SetFieldValue("System.Runtime.InteropServices", "CharSet", "None", value)); } // Autogenerated static field getter // Get static field: static public System.Runtime.InteropServices.CharSet Ansi ::System::Runtime::InteropServices::CharSet System::Runtime::InteropServices::CharSet::_get_Ansi() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::CharSet::_get_Ansi"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<::System::Runtime::InteropServices::CharSet>("System.Runtime.InteropServices", "CharSet", "Ansi")); } // Autogenerated static field setter // Set static field: static public System.Runtime.InteropServices.CharSet Ansi void System::Runtime::InteropServices::CharSet::_set_Ansi(::System::Runtime::InteropServices::CharSet value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::CharSet::_set_Ansi"); THROW_UNLESS(il2cpp_utils::SetFieldValue("System.Runtime.InteropServices", "CharSet", "Ansi", value)); } // Autogenerated static field getter // Get static field: static public System.Runtime.InteropServices.CharSet Unicode ::System::Runtime::InteropServices::CharSet System::Runtime::InteropServices::CharSet::_get_Unicode() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::CharSet::_get_Unicode"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<::System::Runtime::InteropServices::CharSet>("System.Runtime.InteropServices", "CharSet", "Unicode")); } // Autogenerated static field setter // Set static field: static public System.Runtime.InteropServices.CharSet Unicode void System::Runtime::InteropServices::CharSet::_set_Unicode(::System::Runtime::InteropServices::CharSet value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::CharSet::_set_Unicode"); THROW_UNLESS(il2cpp_utils::SetFieldValue("System.Runtime.InteropServices", "CharSet", "Unicode", value)); } // Autogenerated static field getter // Get static field: static public System.Runtime.InteropServices.CharSet Auto ::System::Runtime::InteropServices::CharSet System::Runtime::InteropServices::CharSet::_get_Auto() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::CharSet::_get_Auto"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<::System::Runtime::InteropServices::CharSet>("System.Runtime.InteropServices", "CharSet", "Auto")); } // Autogenerated static field setter // Set static field: static public System.Runtime.InteropServices.CharSet Auto void System::Runtime::InteropServices::CharSet::_set_Auto(::System::Runtime::InteropServices::CharSet value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::CharSet::_set_Auto"); THROW_UNLESS(il2cpp_utils::SetFieldValue("System.Runtime.InteropServices", "CharSet", "Auto", value)); } // Autogenerated instance field getter // Get instance field: public System.Int32 value__ [[deprecated("Use field access instead!")]] int& System::Runtime::InteropServices::CharSet::dyn_value__() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::CharSet::dyn_value__"); auto ___internal__instance = *this; static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "value__"))->offset; return *reinterpret_cast<int*>(reinterpret_cast<char*>(this) + ___internal__field__offset); } // Autogenerated from CppSourceCreator // Created by Sc2ad // ========================================================================= // Begin includes // Including type: System.Runtime.InteropServices.COMException #include "System/Runtime/InteropServices/COMException.hpp" // Including type: System.Runtime.Serialization.SerializationInfo #include "System/Runtime/Serialization/SerializationInfo.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils.hpp" #include "beatsaber-hook/shared/utils/utils.h" // Completed includes // Autogenerated method: System.Runtime.InteropServices.COMException.ToString ::StringW System::Runtime::InteropServices::COMException::ToString() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::COMException::ToString"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Runtime::InteropServices::ExternalException*), 3)); return ::il2cpp_utils::RunMethodRethrow<::StringW, false>(this, ___internal__method); } // Autogenerated from CppSourceCreator // Created by Sc2ad // ========================================================================= // Begin includes // Including type: System.Runtime.InteropServices.ExternalException #include "System/Runtime/InteropServices/ExternalException.hpp" // Including type: System.Runtime.Serialization.SerializationInfo #include "System/Runtime/Serialization/SerializationInfo.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils.hpp" #include "beatsaber-hook/shared/utils/utils.h" // Completed includes // Autogenerated method: System.Runtime.InteropServices.ExternalException.ToString ::StringW System::Runtime::InteropServices::ExternalException::ToString() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::ExternalException::ToString"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Exception*), 3)); return ::il2cpp_utils::RunMethodRethrow<::StringW, false>(this, ___internal__method); } // Autogenerated from CppSourceCreator // Created by Sc2ad // ========================================================================= // Begin includes #include "beatsaber-hook/shared/utils/typedefs.h" // Including type: System.Runtime.InteropServices.HandleRef #include "System/Runtime/InteropServices/HandleRef.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils.hpp" #include "beatsaber-hook/shared/utils/utils.h" // Completed includes // Autogenerated instance field getter // Get instance field: System.Object m_wrapper [[deprecated("Use field access instead!")]] ::Il2CppObject*& System::Runtime::InteropServices::HandleRef::dyn_m_wrapper() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::HandleRef::dyn_m_wrapper"); auto ___internal__instance = *this; static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "m_wrapper"))->offset; return *reinterpret_cast<::Il2CppObject**>(reinterpret_cast<char*>(this) + ___internal__field__offset); } // Autogenerated instance field getter // Get instance field: System.IntPtr m_handle [[deprecated("Use field access instead!")]] ::System::IntPtr& System::Runtime::InteropServices::HandleRef::dyn_m_handle() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::HandleRef::dyn_m_handle"); auto ___internal__instance = *this; static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "m_handle"))->offset; return *reinterpret_cast<::System::IntPtr*>(reinterpret_cast<char*>(this) + ___internal__field__offset); } // Autogenerated method: System.Runtime.InteropServices.HandleRef.get_Handle ::System::IntPtr System::Runtime::InteropServices::HandleRef::get_Handle() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::HandleRef::get_Handle"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(*this, "get_Handle", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); return ::il2cpp_utils::RunMethodRethrow<::System::IntPtr, false>(this, ___internal__method); } // Autogenerated method: System.Runtime.InteropServices.HandleRef..ctor // ABORTED elsewhere. System::Runtime::InteropServices::HandleRef::HandleRef(::Il2CppObject* wrapper, ::System::IntPtr handle) // Autogenerated from CppSourceCreator // Created by Sc2ad // ========================================================================= // Begin includes #include "beatsaber-hook/shared/utils/typedefs.h" // Including type: System.Runtime.InteropServices.ICustomMarshaler #include "System/Runtime/InteropServices/ICustomMarshaler.hpp" // Including type: System.IntPtr #include "System/IntPtr.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils.hpp" #include "beatsaber-hook/shared/utils/utils.h" // Completed includes // Autogenerated method: System.Runtime.InteropServices.ICustomMarshaler.MarshalNativeToManaged ::Il2CppObject* System::Runtime::InteropServices::ICustomMarshaler::MarshalNativeToManaged(::System::IntPtr pNativeData) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::ICustomMarshaler::MarshalNativeToManaged"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Runtime::InteropServices::ICustomMarshaler*), -1)); return ::il2cpp_utils::RunMethodRethrow<::Il2CppObject*, false>(this, ___internal__method, pNativeData); } // Autogenerated method: System.Runtime.InteropServices.ICustomMarshaler.MarshalManagedToNative ::System::IntPtr System::Runtime::InteropServices::ICustomMarshaler::MarshalManagedToNative(::Il2CppObject* ManagedObj) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::ICustomMarshaler::MarshalManagedToNative"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Runtime::InteropServices::ICustomMarshaler*), -1)); return ::il2cpp_utils::RunMethodRethrow<::System::IntPtr, false>(this, ___internal__method, ManagedObj); } // Autogenerated method: System.Runtime.InteropServices.ICustomMarshaler.CleanUpNativeData void System::Runtime::InteropServices::ICustomMarshaler::CleanUpNativeData(::System::IntPtr pNativeData) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::ICustomMarshaler::CleanUpNativeData"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Runtime::InteropServices::ICustomMarshaler*), -1)); ::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, pNativeData); } // Autogenerated method: System.Runtime.InteropServices.ICustomMarshaler.CleanUpManagedData void System::Runtime::InteropServices::ICustomMarshaler::CleanUpManagedData(::Il2CppObject* ManagedObj) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::ICustomMarshaler::CleanUpManagedData"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Runtime::InteropServices::ICustomMarshaler*), -1)); ::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, ManagedObj); } // Autogenerated method: System.Runtime.InteropServices.ICustomMarshaler.GetNativeDataSize int System::Runtime::InteropServices::ICustomMarshaler::GetNativeDataSize() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::ICustomMarshaler::GetNativeDataSize"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Runtime::InteropServices::ICustomMarshaler*), -1)); return ::il2cpp_utils::RunMethodRethrow<int, false>(this, ___internal__method); } // Autogenerated from CppSourceCreator // Created by Sc2ad // ========================================================================= // Begin includes // Including type: System.Runtime.InteropServices.MarshalDirectiveException #include "System/Runtime/InteropServices/MarshalDirectiveException.hpp" // Including type: System.Runtime.Serialization.SerializationInfo #include "System/Runtime/Serialization/SerializationInfo.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils.hpp" #include "beatsaber-hook/shared/utils/utils.h" // Completed includes // Autogenerated from CppSourceCreator // Created by Sc2ad // ========================================================================= // Begin includes // Including type: System.Runtime.InteropServices.SafeHandle #include "System/Runtime/InteropServices/SafeHandle.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils.hpp" #include "beatsaber-hook/shared/utils/utils.h" // Completed includes // Autogenerated static field getter // Get static field: static private System.Int32 RefCount_Mask int System::Runtime::InteropServices::SafeHandle::_get_RefCount_Mask() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::SafeHandle::_get_RefCount_Mask"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<int>("System.Runtime.InteropServices", "SafeHandle", "RefCount_Mask")); } // Autogenerated static field setter // Set static field: static private System.Int32 RefCount_Mask void System::Runtime::InteropServices::SafeHandle::_set_RefCount_Mask(int value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::SafeHandle::_set_RefCount_Mask"); THROW_UNLESS(il2cpp_utils::SetFieldValue("System.Runtime.InteropServices", "SafeHandle", "RefCount_Mask", value)); } // Autogenerated static field getter // Get static field: static private System.Int32 RefCount_One int System::Runtime::InteropServices::SafeHandle::_get_RefCount_One() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::SafeHandle::_get_RefCount_One"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<int>("System.Runtime.InteropServices", "SafeHandle", "RefCount_One")); } // Autogenerated static field setter // Set static field: static private System.Int32 RefCount_One void System::Runtime::InteropServices::SafeHandle::_set_RefCount_One(int value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::SafeHandle::_set_RefCount_One"); THROW_UNLESS(il2cpp_utils::SetFieldValue("System.Runtime.InteropServices", "SafeHandle", "RefCount_One", value)); } // Autogenerated instance field getter // Get instance field: protected System.IntPtr handle [[deprecated("Use field access instead!")]] ::System::IntPtr& System::Runtime::InteropServices::SafeHandle::dyn_handle() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::SafeHandle::dyn_handle"); auto ___internal__instance = this; static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "handle"))->offset; return *reinterpret_cast<::System::IntPtr*>(reinterpret_cast<char*>(this) + ___internal__field__offset); } // Autogenerated instance field getter // Get instance field: private System.Int32 _state [[deprecated("Use field access instead!")]] int& System::Runtime::InteropServices::SafeHandle::dyn__state() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::SafeHandle::dyn__state"); auto ___internal__instance = this; static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "_state"))->offset; return *reinterpret_cast<int*>(reinterpret_cast<char*>(this) + ___internal__field__offset); } // Autogenerated instance field getter // Get instance field: private System.Boolean _ownsHandle [[deprecated("Use field access instead!")]] bool& System::Runtime::InteropServices::SafeHandle::dyn__ownsHandle() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::SafeHandle::dyn__ownsHandle"); auto ___internal__instance = this; static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "_ownsHandle"))->offset; return *reinterpret_cast<bool*>(reinterpret_cast<char*>(this) + ___internal__field__offset); } // Autogenerated instance field getter // Get instance field: private System.Boolean _fullyInitialized [[deprecated("Use field access instead!")]] bool& System::Runtime::InteropServices::SafeHandle::dyn__fullyInitialized() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::SafeHandle::dyn__fullyInitialized"); auto ___internal__instance = this; static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "_fullyInitialized"))->offset; return *reinterpret_cast<bool*>(reinterpret_cast<char*>(this) + ___internal__field__offset); } // Autogenerated method: System.Runtime.InteropServices.SafeHandle.get_IsClosed bool System::Runtime::InteropServices::SafeHandle::get_IsClosed() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::SafeHandle::get_IsClosed"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "get_IsClosed", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); return ::il2cpp_utils::RunMethodRethrow<bool, false>(this, ___internal__method); } // Autogenerated method: System.Runtime.InteropServices.SafeHandle.get_IsInvalid bool System::Runtime::InteropServices::SafeHandle::get_IsInvalid() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::SafeHandle::get_IsInvalid"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Runtime::InteropServices::SafeHandle*), -1)); return ::il2cpp_utils::RunMethodRethrow<bool, false>(this, ___internal__method); } // Autogenerated method: System.Runtime.InteropServices.SafeHandle.SetHandle void System::Runtime::InteropServices::SafeHandle::SetHandle(::System::IntPtr handle) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::SafeHandle::SetHandle"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "SetHandle", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(handle)}))); ::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, handle); } // Autogenerated method: System.Runtime.InteropServices.SafeHandle.DangerousGetHandle ::System::IntPtr System::Runtime::InteropServices::SafeHandle::DangerousGetHandle() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::SafeHandle::DangerousGetHandle"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "DangerousGetHandle", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); return ::il2cpp_utils::RunMethodRethrow<::System::IntPtr, false>(this, ___internal__method); } // Autogenerated method: System.Runtime.InteropServices.SafeHandle.Close void System::Runtime::InteropServices::SafeHandle::Close() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::SafeHandle::Close"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "Close", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); ::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method); } // Autogenerated method: System.Runtime.InteropServices.SafeHandle.Dispose void System::Runtime::InteropServices::SafeHandle::Dispose() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::SafeHandle::Dispose"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Runtime::InteropServices::SafeHandle*), 4)); ::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method); } // Autogenerated method: System.Runtime.InteropServices.SafeHandle.Dispose void System::Runtime::InteropServices::SafeHandle::Dispose(bool disposing) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::SafeHandle::Dispose"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Runtime::InteropServices::SafeHandle*), 6)); ::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, disposing); } // Autogenerated method: System.Runtime.InteropServices.SafeHandle.ReleaseHandle bool System::Runtime::InteropServices::SafeHandle::ReleaseHandle() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::SafeHandle::ReleaseHandle"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Runtime::InteropServices::SafeHandle*), -1)); return ::il2cpp_utils::RunMethodRethrow<bool, false>(this, ___internal__method); } // Autogenerated method: System.Runtime.InteropServices.SafeHandle.SetHandleAsInvalid void System::Runtime::InteropServices::SafeHandle::SetHandleAsInvalid() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::SafeHandle::SetHandleAsInvalid"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "SetHandleAsInvalid", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); ::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method); } // Autogenerated method: System.Runtime.InteropServices.SafeHandle.DangerousAddRef void System::Runtime::InteropServices::SafeHandle::DangerousAddRef(ByRef<bool> success) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::SafeHandle::DangerousAddRef"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "DangerousAddRef", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(success)}))); ::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, byref(success)); } // Autogenerated method: System.Runtime.InteropServices.SafeHandle.DangerousRelease void System::Runtime::InteropServices::SafeHandle::DangerousRelease() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::SafeHandle::DangerousRelease"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "DangerousRelease", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); ::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method); } // Autogenerated method: System.Runtime.InteropServices.SafeHandle.InternalDispose void System::Runtime::InteropServices::SafeHandle::InternalDispose() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::SafeHandle::InternalDispose"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "InternalDispose", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); ::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method); } // Autogenerated method: System.Runtime.InteropServices.SafeHandle.InternalFinalize void System::Runtime::InteropServices::SafeHandle::InternalFinalize() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::SafeHandle::InternalFinalize"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "InternalFinalize", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); ::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method); } // Autogenerated method: System.Runtime.InteropServices.SafeHandle.DangerousReleaseInternal void System::Runtime::InteropServices::SafeHandle::DangerousReleaseInternal(bool dispose) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::SafeHandle::DangerousReleaseInternal"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "DangerousReleaseInternal", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(dispose)}))); ::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, dispose); } // Autogenerated method: System.Runtime.InteropServices.SafeHandle.Finalize void System::Runtime::InteropServices::SafeHandle::Finalize() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::SafeHandle::Finalize"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Runtime::ConstrainedExecution::CriticalFinalizerObject*), 1)); ::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method); } // Autogenerated from CppSourceCreator // Created by Sc2ad // ========================================================================= // Begin includes #include "beatsaber-hook/shared/utils/typedefs.h" // Including type: System.Runtime.InteropServices.GCHandle #include "System/Runtime/InteropServices/GCHandle.hpp" // Including type: System.IntPtr #include "System/IntPtr.hpp" // Including type: System.Runtime.InteropServices.GCHandleType #include "System/Runtime/InteropServices/GCHandleType.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils.hpp" #include "beatsaber-hook/shared/utils/utils.h" // Completed includes // Autogenerated instance field getter // Get instance field: private System.Int32 handle [[deprecated("Use field access instead!")]] int& System::Runtime::InteropServices::GCHandle::dyn_handle() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::GCHandle::dyn_handle"); auto ___internal__instance = *this; static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "handle"))->offset; return *reinterpret_cast<int*>(reinterpret_cast<char*>(this) + ___internal__field__offset); } // Autogenerated method: System.Runtime.InteropServices.GCHandle.get_IsAllocated bool System::Runtime::InteropServices::GCHandle::get_IsAllocated() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::GCHandle::get_IsAllocated"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(*this, "get_IsAllocated", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); return ::il2cpp_utils::RunMethodRethrow<bool, false>(this, ___internal__method); } // Autogenerated method: System.Runtime.InteropServices.GCHandle.get_Target ::Il2CppObject* System::Runtime::InteropServices::GCHandle::get_Target() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::GCHandle::get_Target"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(*this, "get_Target", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); return ::il2cpp_utils::RunMethodRethrow<::Il2CppObject*, false>(this, ___internal__method); } // Autogenerated method: System.Runtime.InteropServices.GCHandle.set_Target void System::Runtime::InteropServices::GCHandle::set_Target(::Il2CppObject* value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::GCHandle::set_Target"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(*this, "set_Target", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(value)}))); ::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, value); } // Autogenerated method: System.Runtime.InteropServices.GCHandle..ctor System::Runtime::InteropServices::GCHandle::GCHandle(::System::IntPtr h) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::GCHandle::.ctor"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(*this, ".ctor", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(h)}))); ::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, h); } // Autogenerated method: System.Runtime.InteropServices.GCHandle..ctor System::Runtime::InteropServices::GCHandle::GCHandle(::Il2CppObject* obj) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::GCHandle::.ctor"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(*this, ".ctor", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(obj)}))); ::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, obj); } // Autogenerated method: System.Runtime.InteropServices.GCHandle..ctor System::Runtime::InteropServices::GCHandle::GCHandle(::Il2CppObject* value, ::System::Runtime::InteropServices::GCHandleType type) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::GCHandle::.ctor"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(*this, ".ctor", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(value), ::il2cpp_utils::ExtractType(type)}))); ::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, value, type); } // Autogenerated method: System.Runtime.InteropServices.GCHandle.AddrOfPinnedObject ::System::IntPtr System::Runtime::InteropServices::GCHandle::AddrOfPinnedObject() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::GCHandle::AddrOfPinnedObject"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(*this, "AddrOfPinnedObject", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); return ::il2cpp_utils::RunMethodRethrow<::System::IntPtr, false>(this, ___internal__method); } // Autogenerated method: System.Runtime.InteropServices.GCHandle.Alloc ::System::Runtime::InteropServices::GCHandle System::Runtime::InteropServices::GCHandle::Alloc(::Il2CppObject* value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::GCHandle::Alloc"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Runtime.InteropServices", "GCHandle", "Alloc", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(value)}))); return ::il2cpp_utils::RunMethodRethrow<::System::Runtime::InteropServices::GCHandle, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method, value); } // Autogenerated method: System.Runtime.InteropServices.GCHandle.Alloc ::System::Runtime::InteropServices::GCHandle System::Runtime::InteropServices::GCHandle::Alloc(::Il2CppObject* value, ::System::Runtime::InteropServices::GCHandleType type) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::GCHandle::Alloc"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Runtime.InteropServices", "GCHandle", "Alloc", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(value), ::il2cpp_utils::ExtractType(type)}))); return ::il2cpp_utils::RunMethodRethrow<::System::Runtime::InteropServices::GCHandle, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method, value, type); } // Autogenerated method: System.Runtime.InteropServices.GCHandle.Free void System::Runtime::InteropServices::GCHandle::Free() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::GCHandle::Free"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(*this, "Free", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); ::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method); } // Autogenerated method: System.Runtime.InteropServices.GCHandle.op_Explicit System::Runtime::InteropServices::GCHandle::operator ::System::IntPtr() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::GCHandle::op_Explicit"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Runtime.InteropServices", "GCHandle", "op_Explicit", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); return ::il2cpp_utils::RunMethodRethrow<::System::IntPtr, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method); } // Autogenerated method: System.Runtime.InteropServices.GCHandle.op_Explicit System::Runtime::InteropServices::GCHandle::GCHandle(::System::IntPtr& value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::GCHandle::op_Explicit"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Runtime.InteropServices", "GCHandle", "op_Explicit", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(value)}))); *this = ::il2cpp_utils::RunMethodRethrow<::System::Runtime::InteropServices::GCHandle, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method, value); } // Autogenerated method: System.Runtime.InteropServices.GCHandle.CheckCurrentDomain bool System::Runtime::InteropServices::GCHandle::CheckCurrentDomain(int handle) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::GCHandle::CheckCurrentDomain"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Runtime.InteropServices", "GCHandle", "CheckCurrentDomain", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(handle)}))); return ::il2cpp_utils::RunMethodRethrow<bool, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method, handle); } // Autogenerated method: System.Runtime.InteropServices.GCHandle.GetTarget ::Il2CppObject* System::Runtime::InteropServices::GCHandle::GetTarget(int handle) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::GCHandle::GetTarget"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Runtime.InteropServices", "GCHandle", "GetTarget", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(handle)}))); return ::il2cpp_utils::RunMethodRethrow<::Il2CppObject*, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method, handle); } // Autogenerated method: System.Runtime.InteropServices.GCHandle.GetTargetHandle int System::Runtime::InteropServices::GCHandle::GetTargetHandle(::Il2CppObject* obj, int handle, ::System::Runtime::InteropServices::GCHandleType type) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::GCHandle::GetTargetHandle"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Runtime.InteropServices", "GCHandle", "GetTargetHandle", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(obj), ::il2cpp_utils::ExtractType(handle), ::il2cpp_utils::ExtractType(type)}))); return ::il2cpp_utils::RunMethodRethrow<int, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method, obj, handle, type); } // Autogenerated method: System.Runtime.InteropServices.GCHandle.FreeHandle void System::Runtime::InteropServices::GCHandle::FreeHandle(int handle) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::GCHandle::FreeHandle"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Runtime.InteropServices", "GCHandle", "FreeHandle", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(handle)}))); ::il2cpp_utils::RunMethodRethrow<void, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method, handle); } // Autogenerated method: System.Runtime.InteropServices.GCHandle.GetAddrOfPinnedObject ::System::IntPtr System::Runtime::InteropServices::GCHandle::GetAddrOfPinnedObject(int handle) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::GCHandle::GetAddrOfPinnedObject"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Runtime.InteropServices", "GCHandle", "GetAddrOfPinnedObject", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(handle)}))); return ::il2cpp_utils::RunMethodRethrow<::System::IntPtr, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method, handle); } // Autogenerated method: System.Runtime.InteropServices.GCHandle.FromIntPtr ::System::Runtime::InteropServices::GCHandle System::Runtime::InteropServices::GCHandle::FromIntPtr(::System::IntPtr value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::GCHandle::FromIntPtr"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Runtime.InteropServices", "GCHandle", "FromIntPtr", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(value)}))); return ::il2cpp_utils::RunMethodRethrow<::System::Runtime::InteropServices::GCHandle, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method, value); } // Autogenerated method: System.Runtime.InteropServices.GCHandle.ToIntPtr ::System::IntPtr System::Runtime::InteropServices::GCHandle::ToIntPtr(::System::Runtime::InteropServices::GCHandle value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::GCHandle::ToIntPtr"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Runtime.InteropServices", "GCHandle", "ToIntPtr", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(value)}))); return ::il2cpp_utils::RunMethodRethrow<::System::IntPtr, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method, value); } // Autogenerated method: System.Runtime.InteropServices.GCHandle.Equals bool System::Runtime::InteropServices::GCHandle::Equals(::Il2CppObject* o) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::GCHandle::Equals"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(*this, classof(::System::ValueType*), 0)); return ::il2cpp_utils::RunMethodRethrow<bool, false>(this, ___internal__method, o); } // Autogenerated method: System.Runtime.InteropServices.GCHandle.GetHashCode int System::Runtime::InteropServices::GCHandle::GetHashCode() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::GCHandle::GetHashCode"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(*this, classof(::System::ValueType*), 2)); return ::il2cpp_utils::RunMethodRethrow<int, false>(this, ___internal__method); } // Autogenerated method: System.Runtime.InteropServices.GCHandle.op_Equality bool System::Runtime::InteropServices::operator ==(const ::System::Runtime::InteropServices::GCHandle& a, const ::System::Runtime::InteropServices::GCHandle& b) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::GCHandle::op_Equality"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Runtime.InteropServices", "GCHandle", "op_Equality", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(a), ::il2cpp_utils::ExtractType(b)}))); return ::il2cpp_utils::RunMethodRethrow<bool, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method, a, b); } // Autogenerated from CppSourceCreator // Created by Sc2ad // ========================================================================= // Begin includes // Including type: System.Runtime.InteropServices.GCHandleType #include "System/Runtime/InteropServices/GCHandleType.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils.hpp" #include "beatsaber-hook/shared/utils/utils.h" // Completed includes // Autogenerated static field getter // Get static field: static public System.Runtime.InteropServices.GCHandleType Weak ::System::Runtime::InteropServices::GCHandleType System::Runtime::InteropServices::GCHandleType::_get_Weak() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::GCHandleType::_get_Weak"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<::System::Runtime::InteropServices::GCHandleType>("System.Runtime.InteropServices", "GCHandleType", "Weak")); } // Autogenerated static field setter // Set static field: static public System.Runtime.InteropServices.GCHandleType Weak void System::Runtime::InteropServices::GCHandleType::_set_Weak(::System::Runtime::InteropServices::GCHandleType value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::GCHandleType::_set_Weak"); THROW_UNLESS(il2cpp_utils::SetFieldValue("System.Runtime.InteropServices", "GCHandleType", "Weak", value)); } // Autogenerated static field getter // Get static field: static public System.Runtime.InteropServices.GCHandleType WeakTrackResurrection ::System::Runtime::InteropServices::GCHandleType System::Runtime::InteropServices::GCHandleType::_get_WeakTrackResurrection() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::GCHandleType::_get_WeakTrackResurrection"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<::System::Runtime::InteropServices::GCHandleType>("System.Runtime.InteropServices", "GCHandleType", "WeakTrackResurrection")); } // Autogenerated static field setter // Set static field: static public System.Runtime.InteropServices.GCHandleType WeakTrackResurrection void System::Runtime::InteropServices::GCHandleType::_set_WeakTrackResurrection(::System::Runtime::InteropServices::GCHandleType value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::GCHandleType::_set_WeakTrackResurrection"); THROW_UNLESS(il2cpp_utils::SetFieldValue("System.Runtime.InteropServices", "GCHandleType", "WeakTrackResurrection", value)); } // Autogenerated static field getter // Get static field: static public System.Runtime.InteropServices.GCHandleType Normal ::System::Runtime::InteropServices::GCHandleType System::Runtime::InteropServices::GCHandleType::_get_Normal() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::GCHandleType::_get_Normal"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<::System::Runtime::InteropServices::GCHandleType>("System.Runtime.InteropServices", "GCHandleType", "Normal")); } // Autogenerated static field setter // Set static field: static public System.Runtime.InteropServices.GCHandleType Normal void System::Runtime::InteropServices::GCHandleType::_set_Normal(::System::Runtime::InteropServices::GCHandleType value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::GCHandleType::_set_Normal"); THROW_UNLESS(il2cpp_utils::SetFieldValue("System.Runtime.InteropServices", "GCHandleType", "Normal", value)); } // Autogenerated static field getter // Get static field: static public System.Runtime.InteropServices.GCHandleType Pinned ::System::Runtime::InteropServices::GCHandleType System::Runtime::InteropServices::GCHandleType::_get_Pinned() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::GCHandleType::_get_Pinned"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<::System::Runtime::InteropServices::GCHandleType>("System.Runtime.InteropServices", "GCHandleType", "Pinned")); } // Autogenerated static field setter // Set static field: static public System.Runtime.InteropServices.GCHandleType Pinned void System::Runtime::InteropServices::GCHandleType::_set_Pinned(::System::Runtime::InteropServices::GCHandleType value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::GCHandleType::_set_Pinned"); THROW_UNLESS(il2cpp_utils::SetFieldValue("System.Runtime.InteropServices", "GCHandleType", "Pinned", value)); } // Autogenerated instance field getter // Get instance field: public System.Int32 value__ [[deprecated("Use field access instead!")]] int& System::Runtime::InteropServices::GCHandleType::dyn_value__() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::GCHandleType::dyn_value__"); auto ___internal__instance = *this; static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "value__"))->offset; return *reinterpret_cast<int*>(reinterpret_cast<char*>(this) + ___internal__field__offset); } // Autogenerated from CppSourceCreator // Created by Sc2ad // ========================================================================= // Begin includes #include "beatsaber-hook/shared/utils/typedefs.h" // Including type: System.Runtime.InteropServices.Marshal #include "System/Runtime/InteropServices/Marshal.hpp" // Including type: System.Security.SecureString #include "System/Security/SecureString.hpp" // Including type: System.Array #include "System/Array.hpp" // Including type: System.Exception #include "System/Exception.hpp" // Including type: System.Type #include "System/Type.hpp" // Including type: System.Delegate #include "System/Delegate.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils.hpp" #include "beatsaber-hook/shared/utils/utils.h" // Completed includes // Autogenerated static field getter // Get static field: static public readonly System.Int32 SystemMaxDBCSCharSize int System::Runtime::InteropServices::Marshal::_get_SystemMaxDBCSCharSize() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::Marshal::_get_SystemMaxDBCSCharSize"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<int>("System.Runtime.InteropServices", "Marshal", "SystemMaxDBCSCharSize")); } // Autogenerated static field setter // Set static field: static public readonly System.Int32 SystemMaxDBCSCharSize void System::Runtime::InteropServices::Marshal::_set_SystemMaxDBCSCharSize(int value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::Marshal::_set_SystemMaxDBCSCharSize"); THROW_UNLESS(il2cpp_utils::SetFieldValue("System.Runtime.InteropServices", "Marshal", "SystemMaxDBCSCharSize", value)); } // Autogenerated static field getter // Get static field: static public readonly System.Int32 SystemDefaultCharSize int System::Runtime::InteropServices::Marshal::_get_SystemDefaultCharSize() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::Marshal::_get_SystemDefaultCharSize"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<int>("System.Runtime.InteropServices", "Marshal", "SystemDefaultCharSize")); } // Autogenerated static field setter // Set static field: static public readonly System.Int32 SystemDefaultCharSize void System::Runtime::InteropServices::Marshal::_set_SystemDefaultCharSize(int value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::Marshal::_set_SystemDefaultCharSize"); THROW_UNLESS(il2cpp_utils::SetFieldValue("System.Runtime.InteropServices", "Marshal", "SystemDefaultCharSize", value)); } // Autogenerated method: System.Runtime.InteropServices.Marshal..cctor void System::Runtime::InteropServices::Marshal::_cctor() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::Marshal::.cctor"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Runtime.InteropServices", "Marshal", ".cctor", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); ::il2cpp_utils::RunMethodRethrow<void, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method); } // Autogenerated method: System.Runtime.InteropServices.Marshal.AllocCoTaskMem ::System::IntPtr System::Runtime::InteropServices::Marshal::AllocCoTaskMem(int cb) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::Marshal::AllocCoTaskMem"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Runtime.InteropServices", "Marshal", "AllocCoTaskMem", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(cb)}))); return ::il2cpp_utils::RunMethodRethrow<::System::IntPtr, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method, cb); } // Autogenerated method: System.Runtime.InteropServices.Marshal.AllocHGlobal ::System::IntPtr System::Runtime::InteropServices::Marshal::AllocHGlobal(::System::IntPtr cb) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::Marshal::AllocHGlobal"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Runtime.InteropServices", "Marshal", "AllocHGlobal", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(cb)}))); return ::il2cpp_utils::RunMethodRethrow<::System::IntPtr, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method, cb); } // Autogenerated method: System.Runtime.InteropServices.Marshal.AllocHGlobal ::System::IntPtr System::Runtime::InteropServices::Marshal::AllocHGlobal(int cb) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::Marshal::AllocHGlobal"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Runtime.InteropServices", "Marshal", "AllocHGlobal", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(cb)}))); return ::il2cpp_utils::RunMethodRethrow<::System::IntPtr, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method, cb); } // Autogenerated method: System.Runtime.InteropServices.Marshal.copy_to_unmanaged void System::Runtime::InteropServices::Marshal::copy_to_unmanaged(::System::Array* source, int startIndex, ::System::IntPtr destination, int length) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::Marshal::copy_to_unmanaged"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Runtime.InteropServices", "Marshal", "copy_to_unmanaged", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(source), ::il2cpp_utils::ExtractType(startIndex), ::il2cpp_utils::ExtractType(destination), ::il2cpp_utils::ExtractType(length)}))); ::il2cpp_utils::RunMethodRethrow<void, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method, source, startIndex, destination, length); } // Autogenerated method: System.Runtime.InteropServices.Marshal.copy_from_unmanaged void System::Runtime::InteropServices::Marshal::copy_from_unmanaged(::System::IntPtr source, int startIndex, ::System::Array* destination, int length) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::Marshal::copy_from_unmanaged"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Runtime.InteropServices", "Marshal", "copy_from_unmanaged", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(source), ::il2cpp_utils::ExtractType(startIndex), ::il2cpp_utils::ExtractType(destination), ::il2cpp_utils::ExtractType(length)}))); ::il2cpp_utils::RunMethodRethrow<void, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method, source, startIndex, destination, length); } // Autogenerated method: System.Runtime.InteropServices.Marshal.Copy void System::Runtime::InteropServices::Marshal::Copy(::ArrayW<uint8_t> source, int startIndex, ::System::IntPtr destination, int length) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::Marshal::Copy"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Runtime.InteropServices", "Marshal", "Copy", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(source), ::il2cpp_utils::ExtractType(startIndex), ::il2cpp_utils::ExtractType(destination), ::il2cpp_utils::ExtractType(length)}))); ::il2cpp_utils::RunMethodRethrow<void, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method, source, startIndex, destination, length); } // Autogenerated method: System.Runtime.InteropServices.Marshal.Copy void System::Runtime::InteropServices::Marshal::Copy(::ArrayW<float> source, int startIndex, ::System::IntPtr destination, int length) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::Marshal::Copy"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Runtime.InteropServices", "Marshal", "Copy", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(source), ::il2cpp_utils::ExtractType(startIndex), ::il2cpp_utils::ExtractType(destination), ::il2cpp_utils::ExtractType(length)}))); ::il2cpp_utils::RunMethodRethrow<void, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method, source, startIndex, destination, length); } // Autogenerated method: System.Runtime.InteropServices.Marshal.Copy void System::Runtime::InteropServices::Marshal::Copy(::System::IntPtr source, ::ArrayW<uint8_t> destination, int startIndex, int length) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::Marshal::Copy"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Runtime.InteropServices", "Marshal", "Copy", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(source), ::il2cpp_utils::ExtractType(destination), ::il2cpp_utils::ExtractType(startIndex), ::il2cpp_utils::ExtractType(length)}))); ::il2cpp_utils::RunMethodRethrow<void, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method, source, destination, startIndex, length); } // Autogenerated method: System.Runtime.InteropServices.Marshal.Copy void System::Runtime::InteropServices::Marshal::Copy(::System::IntPtr source, ::ArrayW<::Il2CppChar> destination, int startIndex, int length) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::Marshal::Copy"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Runtime.InteropServices", "Marshal", "Copy", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(source), ::il2cpp_utils::ExtractType(destination), ::il2cpp_utils::ExtractType(startIndex), ::il2cpp_utils::ExtractType(length)}))); ::il2cpp_utils::RunMethodRethrow<void, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method, source, destination, startIndex, length); } // Autogenerated method: System.Runtime.InteropServices.Marshal.Copy void System::Runtime::InteropServices::Marshal::Copy(::System::IntPtr source, ::ArrayW<int16_t> destination, int startIndex, int length) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::Marshal::Copy"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Runtime.InteropServices", "Marshal", "Copy", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(source), ::il2cpp_utils::ExtractType(destination), ::il2cpp_utils::ExtractType(startIndex), ::il2cpp_utils::ExtractType(length)}))); ::il2cpp_utils::RunMethodRethrow<void, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method, source, destination, startIndex, length); } // Autogenerated method: System.Runtime.InteropServices.Marshal.Copy void System::Runtime::InteropServices::Marshal::Copy(::System::IntPtr source, ::ArrayW<float> destination, int startIndex, int length) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::Marshal::Copy"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Runtime.InteropServices", "Marshal", "Copy", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(source), ::il2cpp_utils::ExtractType(destination), ::il2cpp_utils::ExtractType(startIndex), ::il2cpp_utils::ExtractType(length)}))); ::il2cpp_utils::RunMethodRethrow<void, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method, source, destination, startIndex, length); } // Autogenerated method: System.Runtime.InteropServices.Marshal.FreeBSTR void System::Runtime::InteropServices::Marshal::FreeBSTR(::System::IntPtr ptr) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::Marshal::FreeBSTR"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Runtime.InteropServices", "Marshal", "FreeBSTR", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(ptr)}))); ::il2cpp_utils::RunMethodRethrow<void, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method, ptr); } // Autogenerated method: System.Runtime.InteropServices.Marshal.FreeCoTaskMem void System::Runtime::InteropServices::Marshal::FreeCoTaskMem(::System::IntPtr ptr) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::Marshal::FreeCoTaskMem"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Runtime.InteropServices", "Marshal", "FreeCoTaskMem", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(ptr)}))); ::il2cpp_utils::RunMethodRethrow<void, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method, ptr); } // Autogenerated method: System.Runtime.InteropServices.Marshal.FreeHGlobal void System::Runtime::InteropServices::Marshal::FreeHGlobal(::System::IntPtr hglobal) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::Marshal::FreeHGlobal"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Runtime.InteropServices", "Marshal", "FreeHGlobal", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(hglobal)}))); ::il2cpp_utils::RunMethodRethrow<void, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method, hglobal); } // Autogenerated method: System.Runtime.InteropServices.Marshal.ClearUnicode void System::Runtime::InteropServices::Marshal::ClearUnicode(::System::IntPtr ptr) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::Marshal::ClearUnicode"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Runtime.InteropServices", "Marshal", "ClearUnicode", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(ptr)}))); ::il2cpp_utils::RunMethodRethrow<void, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method, ptr); } // Autogenerated method: System.Runtime.InteropServices.Marshal.ZeroFreeGlobalAllocUnicode void System::Runtime::InteropServices::Marshal::ZeroFreeGlobalAllocUnicode(::System::IntPtr s) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::Marshal::ZeroFreeGlobalAllocUnicode"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Runtime.InteropServices", "Marshal", "ZeroFreeGlobalAllocUnicode", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(s)}))); ::il2cpp_utils::RunMethodRethrow<void, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method, s); } // Autogenerated method: System.Runtime.InteropServices.Marshal.GetHRForException int System::Runtime::InteropServices::Marshal::GetHRForException(::System::Exception* e) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::Marshal::GetHRForException"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Runtime.InteropServices", "Marshal", "GetHRForException", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(e)}))); return ::il2cpp_utils::RunMethodRethrow<int, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method, e); } // Autogenerated method: System.Runtime.InteropServices.Marshal.GetLastWin32Error int System::Runtime::InteropServices::Marshal::GetLastWin32Error() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::Marshal::GetLastWin32Error"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Runtime.InteropServices", "Marshal", "GetLastWin32Error", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); return ::il2cpp_utils::RunMethodRethrow<int, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method); } // Autogenerated method: System.Runtime.InteropServices.Marshal.OffsetOf ::System::IntPtr System::Runtime::InteropServices::Marshal::OffsetOf(::System::Type* t, ::StringW fieldName) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::Marshal::OffsetOf"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Runtime.InteropServices", "Marshal", "OffsetOf", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(t), ::il2cpp_utils::ExtractType(fieldName)}))); return ::il2cpp_utils::RunMethodRethrow<::System::IntPtr, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method, t, fieldName); } // Autogenerated method: System.Runtime.InteropServices.Marshal.PtrToStringAnsi ::StringW System::Runtime::InteropServices::Marshal::PtrToStringAnsi(::System::IntPtr ptr) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::Marshal::PtrToStringAnsi"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Runtime.InteropServices", "Marshal", "PtrToStringAnsi", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(ptr)}))); return ::il2cpp_utils::RunMethodRethrow<::StringW, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method, ptr); } // Autogenerated method: System.Runtime.InteropServices.Marshal.PtrToStringUni ::StringW System::Runtime::InteropServices::Marshal::PtrToStringUni(::System::IntPtr ptr) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::Marshal::PtrToStringUni"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Runtime.InteropServices", "Marshal", "PtrToStringUni", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(ptr)}))); return ::il2cpp_utils::RunMethodRethrow<::StringW, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method, ptr); } // Autogenerated method: System.Runtime.InteropServices.Marshal.PtrToStructure void System::Runtime::InteropServices::Marshal::PtrToStructure(::System::IntPtr ptr, ::Il2CppObject* structure) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::Marshal::PtrToStructure"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Runtime.InteropServices", "Marshal", "PtrToStructure", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(ptr), ::il2cpp_utils::ExtractType(structure)}))); ::il2cpp_utils::RunMethodRethrow<void, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method, ptr, structure); } // Autogenerated method: System.Runtime.InteropServices.Marshal.PtrToStructure ::Il2CppObject* System::Runtime::InteropServices::Marshal::PtrToStructure(::System::IntPtr ptr, ::System::Type* structureType) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::Marshal::PtrToStructure"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Runtime.InteropServices", "Marshal", "PtrToStructure", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(ptr), ::il2cpp_utils::ExtractType(structureType)}))); return ::il2cpp_utils::RunMethodRethrow<::Il2CppObject*, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method, ptr, structureType); } // Autogenerated method: System.Runtime.InteropServices.Marshal.ReadByte uint8_t System::Runtime::InteropServices::Marshal::ReadByte(::System::IntPtr ptr, int ofs) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::Marshal::ReadByte"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Runtime.InteropServices", "Marshal", "ReadByte", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(ptr), ::il2cpp_utils::ExtractType(ofs)}))); return ::il2cpp_utils::RunMethodRethrow<uint8_t, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method, ptr, ofs); } // Autogenerated method: System.Runtime.InteropServices.Marshal.ReadInt16 int16_t System::Runtime::InteropServices::Marshal::ReadInt16(::System::IntPtr ptr, int ofs) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::Marshal::ReadInt16"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Runtime.InteropServices", "Marshal", "ReadInt16", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(ptr), ::il2cpp_utils::ExtractType(ofs)}))); return ::il2cpp_utils::RunMethodRethrow<int16_t, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method, ptr, ofs); } // Autogenerated method: System.Runtime.InteropServices.Marshal.ReadInt32 int System::Runtime::InteropServices::Marshal::ReadInt32(::System::IntPtr ptr) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::Marshal::ReadInt32"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Runtime.InteropServices", "Marshal", "ReadInt32", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(ptr)}))); return ::il2cpp_utils::RunMethodRethrow<int, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method, ptr); } // Autogenerated method: System.Runtime.InteropServices.Marshal.ReadInt32 int System::Runtime::InteropServices::Marshal::ReadInt32(::System::IntPtr ptr, int ofs) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::Marshal::ReadInt32"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Runtime.InteropServices", "Marshal", "ReadInt32", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(ptr), ::il2cpp_utils::ExtractType(ofs)}))); return ::il2cpp_utils::RunMethodRethrow<int, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method, ptr, ofs); } // Autogenerated method: System.Runtime.InteropServices.Marshal.ReadInt64 int64_t System::Runtime::InteropServices::Marshal::ReadInt64(::System::IntPtr ptr) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::Marshal::ReadInt64"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Runtime.InteropServices", "Marshal", "ReadInt64", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(ptr)}))); return ::il2cpp_utils::RunMethodRethrow<int64_t, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method, ptr); } // Autogenerated method: System.Runtime.InteropServices.Marshal.ReadInt64 int64_t System::Runtime::InteropServices::Marshal::ReadInt64(::System::IntPtr ptr, int ofs) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::Marshal::ReadInt64"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Runtime.InteropServices", "Marshal", "ReadInt64", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(ptr), ::il2cpp_utils::ExtractType(ofs)}))); return ::il2cpp_utils::RunMethodRethrow<int64_t, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method, ptr, ofs); } // Autogenerated method: System.Runtime.InteropServices.Marshal.ReadIntPtr ::System::IntPtr System::Runtime::InteropServices::Marshal::ReadIntPtr(::System::IntPtr ptr) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::Marshal::ReadIntPtr"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Runtime.InteropServices", "Marshal", "ReadIntPtr", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(ptr)}))); return ::il2cpp_utils::RunMethodRethrow<::System::IntPtr, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method, ptr); } // Autogenerated method: System.Runtime.InteropServices.Marshal.ReadIntPtr ::System::IntPtr System::Runtime::InteropServices::Marshal::ReadIntPtr(::System::IntPtr ptr, int ofs) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::Marshal::ReadIntPtr"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Runtime.InteropServices", "Marshal", "ReadIntPtr", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(ptr), ::il2cpp_utils::ExtractType(ofs)}))); return ::il2cpp_utils::RunMethodRethrow<::System::IntPtr, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method, ptr, ofs); } // Autogenerated method: System.Runtime.InteropServices.Marshal.ReleaseInternal int System::Runtime::InteropServices::Marshal::ReleaseInternal(::System::IntPtr pUnk) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::Marshal::ReleaseInternal"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Runtime.InteropServices", "Marshal", "ReleaseInternal", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(pUnk)}))); return ::il2cpp_utils::RunMethodRethrow<int, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method, pUnk); } // Autogenerated method: System.Runtime.InteropServices.Marshal.Release int System::Runtime::InteropServices::Marshal::Release(::System::IntPtr pUnk) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::Marshal::Release"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Runtime.InteropServices", "Marshal", "Release", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(pUnk)}))); return ::il2cpp_utils::RunMethodRethrow<int, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method, pUnk); } // Autogenerated method: System.Runtime.InteropServices.Marshal.SizeOf int System::Runtime::InteropServices::Marshal::SizeOf(::Il2CppObject* structure) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::Marshal::SizeOf"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Runtime.InteropServices", "Marshal", "SizeOf", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(structure)}))); return ::il2cpp_utils::RunMethodRethrow<int, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method, structure); } // Autogenerated method: System.Runtime.InteropServices.Marshal.SizeOf int System::Runtime::InteropServices::Marshal::SizeOf(::System::Type* t) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::Marshal::SizeOf"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Runtime.InteropServices", "Marshal", "SizeOf", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(t)}))); return ::il2cpp_utils::RunMethodRethrow<int, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method, t); } // Autogenerated method: System.Runtime.InteropServices.Marshal.SecureStringToCoTaskMemUnicode ::System::IntPtr System::Runtime::InteropServices::Marshal::SecureStringToCoTaskMemUnicode(::System::Security::SecureString* s) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::Marshal::SecureStringToCoTaskMemUnicode"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Runtime.InteropServices", "Marshal", "SecureStringToCoTaskMemUnicode", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(s)}))); return ::il2cpp_utils::RunMethodRethrow<::System::IntPtr, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method, s); } // Autogenerated method: System.Runtime.InteropServices.Marshal.SecureStringToGlobalAllocUnicode ::System::IntPtr System::Runtime::InteropServices::Marshal::SecureStringToGlobalAllocUnicode(::System::Security::SecureString* s) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::Marshal::SecureStringToGlobalAllocUnicode"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Runtime.InteropServices", "Marshal", "SecureStringToGlobalAllocUnicode", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(s)}))); return ::il2cpp_utils::RunMethodRethrow<::System::IntPtr, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method, s); } // Autogenerated method: System.Runtime.InteropServices.Marshal.StructureToPtr void System::Runtime::InteropServices::Marshal::StructureToPtr(::Il2CppObject* structure, ::System::IntPtr ptr, bool fDeleteOld) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::Marshal::StructureToPtr"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Runtime.InteropServices", "Marshal", "StructureToPtr", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(structure), ::il2cpp_utils::ExtractType(ptr), ::il2cpp_utils::ExtractType(fDeleteOld)}))); ::il2cpp_utils::RunMethodRethrow<void, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method, structure, ptr, fDeleteOld); } // Autogenerated method: System.Runtime.InteropServices.Marshal.UnsafeAddrOfPinnedArrayElement ::System::IntPtr System::Runtime::InteropServices::Marshal::UnsafeAddrOfPinnedArrayElement(::System::Array* arr, int index) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::Marshal::UnsafeAddrOfPinnedArrayElement"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Runtime.InteropServices", "Marshal", "UnsafeAddrOfPinnedArrayElement", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(arr), ::il2cpp_utils::ExtractType(index)}))); return ::il2cpp_utils::RunMethodRethrow<::System::IntPtr, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method, arr, index); } // Autogenerated method: System.Runtime.InteropServices.Marshal.WriteInt16 void System::Runtime::InteropServices::Marshal::WriteInt16(::System::IntPtr ptr, int ofs, int16_t val) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::Marshal::WriteInt16"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Runtime.InteropServices", "Marshal", "WriteInt16", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(ptr), ::il2cpp_utils::ExtractType(ofs), ::il2cpp_utils::ExtractType(val)}))); ::il2cpp_utils::RunMethodRethrow<void, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method, ptr, ofs, val); } // Autogenerated method: System.Runtime.InteropServices.Marshal.WriteInt32 void System::Runtime::InteropServices::Marshal::WriteInt32(::System::IntPtr ptr, int val) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::Marshal::WriteInt32"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Runtime.InteropServices", "Marshal", "WriteInt32", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(ptr), ::il2cpp_utils::ExtractType(val)}))); ::il2cpp_utils::RunMethodRethrow<void, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method, ptr, val); } // Autogenerated method: System.Runtime.InteropServices.Marshal.GetFunctionPointerForDelegateInternal ::System::IntPtr System::Runtime::InteropServices::Marshal::GetFunctionPointerForDelegateInternal(::System::Delegate* d) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::Marshal::GetFunctionPointerForDelegateInternal"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Runtime.InteropServices", "Marshal", "GetFunctionPointerForDelegateInternal", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(d)}))); return ::il2cpp_utils::RunMethodRethrow<::System::IntPtr, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method, d); } // Autogenerated from CppSourceCreator // Created by Sc2ad // ========================================================================= // Begin includes // Including type: System.Runtime.InteropServices.MarshalAsAttribute #include "System/Runtime/InteropServices/MarshalAsAttribute.hpp" // Including type: System.Type #include "System/Type.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils.hpp" #include "beatsaber-hook/shared/utils/utils.h" // Completed includes // Autogenerated instance field getter // Get instance field: public System.String MarshalCookie [[deprecated("Use field access instead!")]] ::StringW& System::Runtime::InteropServices::MarshalAsAttribute::dyn_MarshalCookie() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::MarshalAsAttribute::dyn_MarshalCookie"); auto ___internal__instance = this; static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "MarshalCookie"))->offset; return *reinterpret_cast<::StringW*>(reinterpret_cast<char*>(this) + ___internal__field__offset); } // Autogenerated instance field getter // Get instance field: public System.String MarshalType [[deprecated("Use field access instead!")]] ::StringW& System::Runtime::InteropServices::MarshalAsAttribute::dyn_MarshalType() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::MarshalAsAttribute::dyn_MarshalType"); auto ___internal__instance = this; static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "MarshalType"))->offset; return *reinterpret_cast<::StringW*>(reinterpret_cast<char*>(this) + ___internal__field__offset); } // Autogenerated instance field getter // Get instance field: public System.Type MarshalTypeRef [[deprecated("Use field access instead!")]] ::System::Type*& System::Runtime::InteropServices::MarshalAsAttribute::dyn_MarshalTypeRef() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::MarshalAsAttribute::dyn_MarshalTypeRef"); auto ___internal__instance = this; static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "MarshalTypeRef"))->offset; return *reinterpret_cast<::System::Type**>(reinterpret_cast<char*>(this) + ___internal__field__offset); } // Autogenerated instance field getter // Get instance field: public System.Type SafeArrayUserDefinedSubType [[deprecated("Use field access instead!")]] ::System::Type*& System::Runtime::InteropServices::MarshalAsAttribute::dyn_SafeArrayUserDefinedSubType() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::MarshalAsAttribute::dyn_SafeArrayUserDefinedSubType"); auto ___internal__instance = this; static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "SafeArrayUserDefinedSubType"))->offset; return *reinterpret_cast<::System::Type**>(reinterpret_cast<char*>(this) + ___internal__field__offset); } // Autogenerated instance field getter // Get instance field: private System.Runtime.InteropServices.UnmanagedType utype [[deprecated("Use field access instead!")]] ::System::Runtime::InteropServices::UnmanagedType& System::Runtime::InteropServices::MarshalAsAttribute::dyn_utype() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::MarshalAsAttribute::dyn_utype"); auto ___internal__instance = this; static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "utype"))->offset; return *reinterpret_cast<::System::Runtime::InteropServices::UnmanagedType*>(reinterpret_cast<char*>(this) + ___internal__field__offset); } // Autogenerated instance field getter // Get instance field: public System.Runtime.InteropServices.UnmanagedType ArraySubType [[deprecated("Use field access instead!")]] ::System::Runtime::InteropServices::UnmanagedType& System::Runtime::InteropServices::MarshalAsAttribute::dyn_ArraySubType() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::MarshalAsAttribute::dyn_ArraySubType"); auto ___internal__instance = this; static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "ArraySubType"))->offset; return *reinterpret_cast<::System::Runtime::InteropServices::UnmanagedType*>(reinterpret_cast<char*>(this) + ___internal__field__offset); } // Autogenerated instance field getter // Get instance field: public System.Runtime.InteropServices.VarEnum SafeArraySubType [[deprecated("Use field access instead!")]] ::System::Runtime::InteropServices::VarEnum& System::Runtime::InteropServices::MarshalAsAttribute::dyn_SafeArraySubType() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::MarshalAsAttribute::dyn_SafeArraySubType"); auto ___internal__instance = this; static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "SafeArraySubType"))->offset; return *reinterpret_cast<::System::Runtime::InteropServices::VarEnum*>(reinterpret_cast<char*>(this) + ___internal__field__offset); } // Autogenerated instance field getter // Get instance field: public System.Int32 SizeConst [[deprecated("Use field access instead!")]] int& System::Runtime::InteropServices::MarshalAsAttribute::dyn_SizeConst() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::MarshalAsAttribute::dyn_SizeConst"); auto ___internal__instance = this; static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "SizeConst"))->offset; return *reinterpret_cast<int*>(reinterpret_cast<char*>(this) + ___internal__field__offset); } // Autogenerated instance field getter // Get instance field: public System.Int32 IidParameterIndex [[deprecated("Use field access instead!")]] int& System::Runtime::InteropServices::MarshalAsAttribute::dyn_IidParameterIndex() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::MarshalAsAttribute::dyn_IidParameterIndex"); auto ___internal__instance = this; static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "IidParameterIndex"))->offset; return *reinterpret_cast<int*>(reinterpret_cast<char*>(this) + ___internal__field__offset); } // Autogenerated instance field getter // Get instance field: public System.Int16 SizeParamIndex [[deprecated("Use field access instead!")]] int16_t& System::Runtime::InteropServices::MarshalAsAttribute::dyn_SizeParamIndex() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::MarshalAsAttribute::dyn_SizeParamIndex"); auto ___internal__instance = this; static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "SizeParamIndex"))->offset; return *reinterpret_cast<int16_t*>(reinterpret_cast<char*>(this) + ___internal__field__offset); } // Autogenerated method: System.Runtime.InteropServices.MarshalAsAttribute.Copy ::System::Runtime::InteropServices::MarshalAsAttribute* System::Runtime::InteropServices::MarshalAsAttribute::Copy() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::MarshalAsAttribute::Copy"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "Copy", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); return ::il2cpp_utils::RunMethodRethrow<::System::Runtime::InteropServices::MarshalAsAttribute*, false>(this, ___internal__method); } // Autogenerated from CppSourceCreator // Created by Sc2ad // ========================================================================= // Begin includes // Including type: System.Runtime.InteropServices.SafeBuffer #include "System/Runtime/InteropServices/SafeBuffer.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils.hpp" #include "beatsaber-hook/shared/utils/utils.h" // Completed includes // Autogenerated instance field getter // Get instance field: private System.Boolean inited [[deprecated("Use field access instead!")]] bool& System::Runtime::InteropServices::SafeBuffer::dyn_inited() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::SafeBuffer::dyn_inited"); auto ___internal__instance = this; static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "inited"))->offset; return *reinterpret_cast<bool*>(reinterpret_cast<char*>(this) + ___internal__field__offset); } // Autogenerated method: System.Runtime.InteropServices.SafeBuffer.AcquirePointer void System::Runtime::InteropServices::SafeBuffer::AcquirePointer(ByRef<uint8_t*> pointer) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::SafeBuffer::AcquirePointer"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "AcquirePointer", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(pointer)}))); ::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, byref(pointer)); } // Autogenerated method: System.Runtime.InteropServices.SafeBuffer.ReleasePointer void System::Runtime::InteropServices::SafeBuffer::ReleasePointer() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Runtime::InteropServices::SafeBuffer::ReleasePointer"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "ReleasePointer", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); ::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method); } // Autogenerated from CppSourceCreator // Created by Sc2ad // ========================================================================= // Begin includes #include "beatsaber-hook/shared/utils/typedefs.h" // Including type: System.Collections.DictionaryEntry #include "System/Collections/DictionaryEntry.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils.hpp" #include "beatsaber-hook/shared/utils/utils.h" // Completed includes // Autogenerated instance field getter // Get instance field: private System.Object _key [[deprecated("Use field access instead!")]] ::Il2CppObject*& System::Collections::DictionaryEntry::dyn__key() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::DictionaryEntry::dyn__key"); auto ___internal__instance = *this; static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "_key"))->offset; return *reinterpret_cast<::Il2CppObject**>(reinterpret_cast<char*>(this) + ___internal__field__offset); } // Autogenerated instance field getter // Get instance field: private System.Object _value [[deprecated("Use field access instead!")]] ::Il2CppObject*& System::Collections::DictionaryEntry::dyn__value() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::DictionaryEntry::dyn__value"); auto ___internal__instance = *this; static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "_value"))->offset; return *reinterpret_cast<::Il2CppObject**>(reinterpret_cast<char*>(this) + ___internal__field__offset); } // Autogenerated method: System.Collections.DictionaryEntry.get_Key ::Il2CppObject* System::Collections::DictionaryEntry::get_Key() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::DictionaryEntry::get_Key"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(*this, "get_Key", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); return ::il2cpp_utils::RunMethodRethrow<::Il2CppObject*, false>(this, ___internal__method); } // Autogenerated method: System.Collections.DictionaryEntry.get_Value ::Il2CppObject* System::Collections::DictionaryEntry::get_Value() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::DictionaryEntry::get_Value"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(*this, "get_Value", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); return ::il2cpp_utils::RunMethodRethrow<::Il2CppObject*, false>(this, ___internal__method); } // Autogenerated method: System.Collections.DictionaryEntry..ctor // ABORTED elsewhere. System::Collections::DictionaryEntry::DictionaryEntry(::Il2CppObject* key, ::Il2CppObject* value) // Autogenerated from CppSourceCreator // Created by Sc2ad // ========================================================================= // Begin includes #include "beatsaber-hook/shared/utils/typedefs.h" // Including type: System.Collections.LowLevelComparer #include "System/Collections/LowLevelComparer.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils.hpp" #include "beatsaber-hook/shared/utils/utils.h" // Completed includes // Autogenerated static field getter // Get static field: static readonly System.Collections.LowLevelComparer Default ::System::Collections::LowLevelComparer* System::Collections::LowLevelComparer::_get_Default() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::LowLevelComparer::_get_Default"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<::System::Collections::LowLevelComparer*>("System.Collections", "LowLevelComparer", "Default")); } // Autogenerated static field setter // Set static field: static readonly System.Collections.LowLevelComparer Default void System::Collections::LowLevelComparer::_set_Default(::System::Collections::LowLevelComparer* value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::LowLevelComparer::_set_Default"); THROW_UNLESS(il2cpp_utils::SetFieldValue("System.Collections", "LowLevelComparer", "Default", value)); } // Autogenerated method: System.Collections.LowLevelComparer..cctor void System::Collections::LowLevelComparer::_cctor() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::LowLevelComparer::.cctor"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Collections", "LowLevelComparer", ".cctor", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); ::il2cpp_utils::RunMethodRethrow<void, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method); } // Autogenerated method: System.Collections.LowLevelComparer.Compare int System::Collections::LowLevelComparer::Compare(::Il2CppObject* a, ::Il2CppObject* b) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::LowLevelComparer::Compare"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::LowLevelComparer*), 4)); return ::il2cpp_utils::RunMethodRethrow<int, false>(this, ___internal__method, a, b); } // Autogenerated from CppSourceCreator // Created by Sc2ad // ========================================================================= // Begin includes #include "beatsaber-hook/shared/utils/typedefs.h" // Including type: System.Collections.ArrayList #include "System/Collections/ArrayList.hpp" // Including type: System.Collections.ArrayList/System.Collections.IListWrapper #include "System/Collections/ArrayList_IListWrapper.hpp" // Including type: System.Collections.ArrayList/System.Collections.ReadOnlyList #include "System/Collections/ArrayList_ReadOnlyList.hpp" // Including type: System.Collections.ArrayList/System.Collections.ReadOnlyArrayList #include "System/Collections/ArrayList_ReadOnlyArrayList.hpp" // Including type: System.Collections.ArrayList/System.Collections.ArrayListEnumeratorSimple #include "System/Collections/ArrayList_ArrayListEnumeratorSimple.hpp" // Including type: System.Collections.ArrayList/System.Collections.ArrayListDebugView #include "System/Collections/ArrayList_ArrayListDebugView.hpp" // Including type: System.Collections.ICollection #include "System/Collections/ICollection.hpp" // Including type: System.Array #include "System/Array.hpp" // Including type: System.Collections.IEnumerator #include "System/Collections/IEnumerator.hpp" // Including type: System.Collections.IComparer #include "System/Collections/IComparer.hpp" // Including type: System.Type #include "System/Type.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils.hpp" #include "beatsaber-hook/shared/utils/utils.h" // Completed includes // Autogenerated static field getter // Get static field: static private System.Int32 _defaultCapacity int System::Collections::ArrayList::_get__defaultCapacity() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::ArrayList::_get__defaultCapacity"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<int>("System.Collections", "ArrayList", "_defaultCapacity")); } // Autogenerated static field setter // Set static field: static private System.Int32 _defaultCapacity void System::Collections::ArrayList::_set__defaultCapacity(int value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::ArrayList::_set__defaultCapacity"); THROW_UNLESS(il2cpp_utils::SetFieldValue("System.Collections", "ArrayList", "_defaultCapacity", value)); } // Autogenerated static field getter // Get static field: static private readonly System.Object[] emptyArray ::ArrayW<::Il2CppObject*> System::Collections::ArrayList::_get_emptyArray() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::ArrayList::_get_emptyArray"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<::ArrayW<::Il2CppObject*>>("System.Collections", "ArrayList", "emptyArray")); } // Autogenerated static field setter // Set static field: static private readonly System.Object[] emptyArray void System::Collections::ArrayList::_set_emptyArray(::ArrayW<::Il2CppObject*> value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::ArrayList::_set_emptyArray"); THROW_UNLESS(il2cpp_utils::SetFieldValue("System.Collections", "ArrayList", "emptyArray", value)); } // Autogenerated instance field getter // Get instance field: private System.Object[] _items [[deprecated("Use field access instead!")]] ::ArrayW<::Il2CppObject*>& System::Collections::ArrayList::dyn__items() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::ArrayList::dyn__items"); auto ___internal__instance = this; static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "_items"))->offset; return *reinterpret_cast<::ArrayW<::Il2CppObject*>*>(reinterpret_cast<char*>(this) + ___internal__field__offset); } // Autogenerated instance field getter // Get instance field: private System.Int32 _size [[deprecated("Use field access instead!")]] int& System::Collections::ArrayList::dyn__size() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::ArrayList::dyn__size"); auto ___internal__instance = this; static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "_size"))->offset; return *reinterpret_cast<int*>(reinterpret_cast<char*>(this) + ___internal__field__offset); } // Autogenerated instance field getter // Get instance field: private System.Int32 _version [[deprecated("Use field access instead!")]] int& System::Collections::ArrayList::dyn__version() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::ArrayList::dyn__version"); auto ___internal__instance = this; static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "_version"))->offset; return *reinterpret_cast<int*>(reinterpret_cast<char*>(this) + ___internal__field__offset); } // Autogenerated instance field getter // Get instance field: private System.Object _syncRoot [[deprecated("Use field access instead!")]] ::Il2CppObject*& System::Collections::ArrayList::dyn__syncRoot() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::ArrayList::dyn__syncRoot"); auto ___internal__instance = this; static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "_syncRoot"))->offset; return *reinterpret_cast<::Il2CppObject**>(reinterpret_cast<char*>(this) + ___internal__field__offset); } // Autogenerated method: System.Collections.ArrayList.set_Capacity void System::Collections::ArrayList::set_Capacity(int value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::ArrayList::set_Capacity"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::ArrayList*), 20)); ::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, value); } // Autogenerated method: System.Collections.ArrayList.get_Count int System::Collections::ArrayList::get_Count() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::ArrayList::get_Count"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::ArrayList*), 21)); return ::il2cpp_utils::RunMethodRethrow<int, false>(this, ___internal__method); } // Autogenerated method: System.Collections.ArrayList.get_IsFixedSize bool System::Collections::ArrayList::get_IsFixedSize() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::ArrayList::get_IsFixedSize"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::ArrayList*), 22)); return ::il2cpp_utils::RunMethodRethrow<bool, false>(this, ___internal__method); } // Autogenerated method: System.Collections.ArrayList.get_IsReadOnly bool System::Collections::ArrayList::get_IsReadOnly() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::ArrayList::get_IsReadOnly"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::ArrayList*), 23)); return ::il2cpp_utils::RunMethodRethrow<bool, false>(this, ___internal__method); } // Autogenerated method: System.Collections.ArrayList.get_SyncRoot ::Il2CppObject* System::Collections::ArrayList::get_SyncRoot() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::ArrayList::get_SyncRoot"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::ArrayList*), 24)); return ::il2cpp_utils::RunMethodRethrow<::Il2CppObject*, false>(this, ___internal__method); } // Autogenerated method: System.Collections.ArrayList.get_Item ::Il2CppObject* System::Collections::ArrayList::get_Item(int index) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::ArrayList::get_Item"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::ArrayList*), 25)); return ::il2cpp_utils::RunMethodRethrow<::Il2CppObject*, false>(this, ___internal__method, index); } // Autogenerated method: System.Collections.ArrayList.set_Item void System::Collections::ArrayList::set_Item(int index, ::Il2CppObject* value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::ArrayList::set_Item"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::ArrayList*), 26)); ::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, index, value); } // Autogenerated method: System.Collections.ArrayList..cctor void System::Collections::ArrayList::_cctor() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::ArrayList::.cctor"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Collections", "ArrayList", ".cctor", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); ::il2cpp_utils::RunMethodRethrow<void, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method); } // Autogenerated method: System.Collections.ArrayList.Adapter ::System::Collections::ArrayList* System::Collections::ArrayList::Adapter(::System::Collections::IList* list) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::ArrayList::Adapter"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Collections", "ArrayList", "Adapter", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(list)}))); return ::il2cpp_utils::RunMethodRethrow<::System::Collections::ArrayList*, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method, list); } // Autogenerated method: System.Collections.ArrayList.Add int System::Collections::ArrayList::Add(::Il2CppObject* value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::ArrayList::Add"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::ArrayList*), 27)); return ::il2cpp_utils::RunMethodRethrow<int, false>(this, ___internal__method, value); } // Autogenerated method: System.Collections.ArrayList.AddRange void System::Collections::ArrayList::AddRange(::System::Collections::ICollection* c) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::ArrayList::AddRange"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::ArrayList*), 28)); ::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, c); } // Autogenerated method: System.Collections.ArrayList.Clear void System::Collections::ArrayList::Clear() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::ArrayList::Clear"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::ArrayList*), 29)); ::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method); } // Autogenerated method: System.Collections.ArrayList.Clone ::Il2CppObject* System::Collections::ArrayList::Clone() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::ArrayList::Clone"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::ArrayList*), 30)); return ::il2cpp_utils::RunMethodRethrow<::Il2CppObject*, false>(this, ___internal__method); } // Autogenerated method: System.Collections.ArrayList.Contains bool System::Collections::ArrayList::Contains(::Il2CppObject* item) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::ArrayList::Contains"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::ArrayList*), 31)); return ::il2cpp_utils::RunMethodRethrow<bool, false>(this, ___internal__method, item); } // Autogenerated method: System.Collections.ArrayList.CopyTo void System::Collections::ArrayList::CopyTo(::System::Array* array) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::ArrayList::CopyTo"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::ArrayList*), 32)); ::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, array); } // Autogenerated method: System.Collections.ArrayList.CopyTo void System::Collections::ArrayList::CopyTo(::System::Array* array, int arrayIndex) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::ArrayList::CopyTo"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::ArrayList*), 33)); ::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, array, arrayIndex); } // Autogenerated method: System.Collections.ArrayList.CopyTo void System::Collections::ArrayList::CopyTo(int index, ::System::Array* array, int arrayIndex, int count) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::ArrayList::CopyTo"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::ArrayList*), 34)); ::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, index, array, arrayIndex, count); } // Autogenerated method: System.Collections.ArrayList.EnsureCapacity void System::Collections::ArrayList::EnsureCapacity(int min) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::ArrayList::EnsureCapacity"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "EnsureCapacity", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(min)}))); ::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, min); } // Autogenerated method: System.Collections.ArrayList.GetEnumerator ::System::Collections::IEnumerator* System::Collections::ArrayList::GetEnumerator() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::ArrayList::GetEnumerator"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::ArrayList*), 35)); return ::il2cpp_utils::RunMethodRethrow<::System::Collections::IEnumerator*, false>(this, ___internal__method); } // Autogenerated method: System.Collections.ArrayList.IndexOf int System::Collections::ArrayList::IndexOf(::Il2CppObject* value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::ArrayList::IndexOf"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::ArrayList*), 36)); return ::il2cpp_utils::RunMethodRethrow<int, false>(this, ___internal__method, value); } // Autogenerated method: System.Collections.ArrayList.Insert void System::Collections::ArrayList::Insert(int index, ::Il2CppObject* value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::ArrayList::Insert"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::ArrayList*), 37)); ::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, index, value); } // Autogenerated method: System.Collections.ArrayList.InsertRange void System::Collections::ArrayList::InsertRange(int index, ::System::Collections::ICollection* c) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::ArrayList::InsertRange"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::ArrayList*), 38)); ::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, index, c); } // Autogenerated method: System.Collections.ArrayList.ReadOnly ::System::Collections::IList* System::Collections::ArrayList::ReadOnly(::System::Collections::IList* list) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::ArrayList::ReadOnly"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Collections", "ArrayList", "ReadOnly", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(list)}))); return ::il2cpp_utils::RunMethodRethrow<::System::Collections::IList*, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method, list); } // Autogenerated method: System.Collections.ArrayList.ReadOnly ::System::Collections::ArrayList* System::Collections::ArrayList::ReadOnly(::System::Collections::ArrayList* list) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::ArrayList::ReadOnly"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Collections", "ArrayList", "ReadOnly", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(list)}))); return ::il2cpp_utils::RunMethodRethrow<::System::Collections::ArrayList*, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method, list); } // Autogenerated method: System.Collections.ArrayList.Remove void System::Collections::ArrayList::Remove(::Il2CppObject* obj) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::ArrayList::Remove"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::ArrayList*), 39)); ::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, obj); } // Autogenerated method: System.Collections.ArrayList.RemoveAt void System::Collections::ArrayList::RemoveAt(int index) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::ArrayList::RemoveAt"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::ArrayList*), 40)); ::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, index); } // Autogenerated method: System.Collections.ArrayList.RemoveRange void System::Collections::ArrayList::RemoveRange(int index, int count) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::ArrayList::RemoveRange"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::ArrayList*), 41)); ::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, index, count); } // Autogenerated method: System.Collections.ArrayList.Sort void System::Collections::ArrayList::Sort(::System::Collections::IComparer* comparer) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::ArrayList::Sort"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::ArrayList*), 42)); ::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, comparer); } // Autogenerated method: System.Collections.ArrayList.Sort void System::Collections::ArrayList::Sort(int index, int count, ::System::Collections::IComparer* comparer) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::ArrayList::Sort"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::ArrayList*), 43)); ::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, index, count, comparer); } // Autogenerated method: System.Collections.ArrayList.ToArray ::ArrayW<::Il2CppObject*> System::Collections::ArrayList::ToArray() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::ArrayList::ToArray"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::ArrayList*), 44)); return ::il2cpp_utils::RunMethodRethrow<::ArrayW<::Il2CppObject*>, false>(this, ___internal__method); } // Autogenerated method: System.Collections.ArrayList.ToArray ::System::Array* System::Collections::ArrayList::ToArray(::System::Type* type) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::ArrayList::ToArray"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::ArrayList*), 45)); return ::il2cpp_utils::RunMethodRethrow<::System::Array*, false>(this, ___internal__method, type); } // Autogenerated from CppSourceCreator // Created by Sc2ad // ========================================================================= // Begin includes #include "beatsaber-hook/shared/utils/typedefs.h" // Including type: System.Collections.ArrayList/System.Collections.IListWrapper #include "System/Collections/ArrayList_IListWrapper.hpp" // Including type: System.Collections.IList #include "System/Collections/IList.hpp" // Including type: System.Collections.ICollection #include "System/Collections/ICollection.hpp" // Including type: System.Array #include "System/Array.hpp" // Including type: System.Collections.IEnumerator #include "System/Collections/IEnumerator.hpp" // Including type: System.Collections.IComparer #include "System/Collections/IComparer.hpp" // Including type: System.Type #include "System/Type.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils.hpp" #include "beatsaber-hook/shared/utils/utils.h" // Completed includes // Autogenerated instance field getter // Get instance field: private System.Collections.IList _list [[deprecated("Use field access instead!")]] ::System::Collections::IList*& System::Collections::ArrayList::IListWrapper::dyn__list() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::ArrayList::IListWrapper::dyn__list"); auto ___internal__instance = this; static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "_list"))->offset; return *reinterpret_cast<::System::Collections::IList**>(reinterpret_cast<char*>(this) + ___internal__field__offset); } // Autogenerated method: System.Collections.ArrayList/System.Collections.IListWrapper.set_Capacity void System::Collections::ArrayList::IListWrapper::set_Capacity(int value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::ArrayList::IListWrapper::set_Capacity"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::ArrayList*), 20)); ::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, value); } // Autogenerated method: System.Collections.ArrayList/System.Collections.IListWrapper.get_Count int System::Collections::ArrayList::IListWrapper::get_Count() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::ArrayList::IListWrapper::get_Count"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::ArrayList*), 21)); return ::il2cpp_utils::RunMethodRethrow<int, false>(this, ___internal__method); } // Autogenerated method: System.Collections.ArrayList/System.Collections.IListWrapper.get_IsReadOnly bool System::Collections::ArrayList::IListWrapper::get_IsReadOnly() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::ArrayList::IListWrapper::get_IsReadOnly"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::ArrayList*), 23)); return ::il2cpp_utils::RunMethodRethrow<bool, false>(this, ___internal__method); } // Autogenerated method: System.Collections.ArrayList/System.Collections.IListWrapper.get_IsFixedSize bool System::Collections::ArrayList::IListWrapper::get_IsFixedSize() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::ArrayList::IListWrapper::get_IsFixedSize"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::ArrayList*), 22)); return ::il2cpp_utils::RunMethodRethrow<bool, false>(this, ___internal__method); } // Autogenerated method: System.Collections.ArrayList/System.Collections.IListWrapper.get_Item ::Il2CppObject* System::Collections::ArrayList::IListWrapper::get_Item(int index) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::ArrayList::IListWrapper::get_Item"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::ArrayList*), 25)); return ::il2cpp_utils::RunMethodRethrow<::Il2CppObject*, false>(this, ___internal__method, index); } // Autogenerated method: System.Collections.ArrayList/System.Collections.IListWrapper.set_Item void System::Collections::ArrayList::IListWrapper::set_Item(int index, ::Il2CppObject* value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::ArrayList::IListWrapper::set_Item"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::ArrayList*), 26)); ::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, index, value); } // Autogenerated method: System.Collections.ArrayList/System.Collections.IListWrapper.get_SyncRoot ::Il2CppObject* System::Collections::ArrayList::IListWrapper::get_SyncRoot() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::ArrayList::IListWrapper::get_SyncRoot"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::ArrayList*), 24)); return ::il2cpp_utils::RunMethodRethrow<::Il2CppObject*, false>(this, ___internal__method); } // Autogenerated method: System.Collections.ArrayList/System.Collections.IListWrapper.Add int System::Collections::ArrayList::IListWrapper::Add(::Il2CppObject* obj) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::ArrayList::IListWrapper::Add"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::ArrayList*), 27)); return ::il2cpp_utils::RunMethodRethrow<int, false>(this, ___internal__method, obj); } // Autogenerated method: System.Collections.ArrayList/System.Collections.IListWrapper.AddRange void System::Collections::ArrayList::IListWrapper::AddRange(::System::Collections::ICollection* c) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::ArrayList::IListWrapper::AddRange"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::ArrayList*), 28)); ::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, c); } // Autogenerated method: System.Collections.ArrayList/System.Collections.IListWrapper.Clear void System::Collections::ArrayList::IListWrapper::Clear() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::ArrayList::IListWrapper::Clear"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::ArrayList*), 29)); ::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method); } // Autogenerated method: System.Collections.ArrayList/System.Collections.IListWrapper.Clone ::Il2CppObject* System::Collections::ArrayList::IListWrapper::Clone() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::ArrayList::IListWrapper::Clone"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::ArrayList*), 30)); return ::il2cpp_utils::RunMethodRethrow<::Il2CppObject*, false>(this, ___internal__method); } // Autogenerated method: System.Collections.ArrayList/System.Collections.IListWrapper.Contains bool System::Collections::ArrayList::IListWrapper::Contains(::Il2CppObject* obj) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::ArrayList::IListWrapper::Contains"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::ArrayList*), 31)); return ::il2cpp_utils::RunMethodRethrow<bool, false>(this, ___internal__method, obj); } // Autogenerated method: System.Collections.ArrayList/System.Collections.IListWrapper.CopyTo void System::Collections::ArrayList::IListWrapper::CopyTo(::System::Array* array, int index) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::ArrayList::IListWrapper::CopyTo"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::ArrayList*), 33)); ::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, array, index); } // Autogenerated method: System.Collections.ArrayList/System.Collections.IListWrapper.CopyTo void System::Collections::ArrayList::IListWrapper::CopyTo(int index, ::System::Array* array, int arrayIndex, int count) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::ArrayList::IListWrapper::CopyTo"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::ArrayList*), 34)); ::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, index, array, arrayIndex, count); } // Autogenerated method: System.Collections.ArrayList/System.Collections.IListWrapper.GetEnumerator ::System::Collections::IEnumerator* System::Collections::ArrayList::IListWrapper::GetEnumerator() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::ArrayList::IListWrapper::GetEnumerator"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::ArrayList*), 35)); return ::il2cpp_utils::RunMethodRethrow<::System::Collections::IEnumerator*, false>(this, ___internal__method); } // Autogenerated method: System.Collections.ArrayList/System.Collections.IListWrapper.IndexOf int System::Collections::ArrayList::IListWrapper::IndexOf(::Il2CppObject* value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::ArrayList::IListWrapper::IndexOf"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::ArrayList*), 36)); return ::il2cpp_utils::RunMethodRethrow<int, false>(this, ___internal__method, value); } // Autogenerated method: System.Collections.ArrayList/System.Collections.IListWrapper.Insert void System::Collections::ArrayList::IListWrapper::Insert(int index, ::Il2CppObject* obj) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::ArrayList::IListWrapper::Insert"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::ArrayList*), 37)); ::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, index, obj); } // Autogenerated method: System.Collections.ArrayList/System.Collections.IListWrapper.InsertRange void System::Collections::ArrayList::IListWrapper::InsertRange(int index, ::System::Collections::ICollection* c) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::ArrayList::IListWrapper::InsertRange"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::ArrayList*), 38)); ::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, index, c); } // Autogenerated method: System.Collections.ArrayList/System.Collections.IListWrapper.Remove void System::Collections::ArrayList::IListWrapper::Remove(::Il2CppObject* value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::ArrayList::IListWrapper::Remove"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::ArrayList*), 39)); ::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, value); } // Autogenerated method: System.Collections.ArrayList/System.Collections.IListWrapper.RemoveAt void System::Collections::ArrayList::IListWrapper::RemoveAt(int index) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::ArrayList::IListWrapper::RemoveAt"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::ArrayList*), 40)); ::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, index); } // Autogenerated method: System.Collections.ArrayList/System.Collections.IListWrapper.RemoveRange void System::Collections::ArrayList::IListWrapper::RemoveRange(int index, int count) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::ArrayList::IListWrapper::RemoveRange"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::ArrayList*), 41)); ::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, index, count); } // Autogenerated method: System.Collections.ArrayList/System.Collections.IListWrapper.Sort void System::Collections::ArrayList::IListWrapper::Sort(int index, int count, ::System::Collections::IComparer* comparer) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::ArrayList::IListWrapper::Sort"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::ArrayList*), 43)); ::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, index, count, comparer); } // Autogenerated method: System.Collections.ArrayList/System.Collections.IListWrapper.ToArray ::ArrayW<::Il2CppObject*> System::Collections::ArrayList::IListWrapper::ToArray() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::ArrayList::IListWrapper::ToArray"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::ArrayList*), 44)); return ::il2cpp_utils::RunMethodRethrow<::ArrayW<::Il2CppObject*>, false>(this, ___internal__method); } // Autogenerated method: System.Collections.ArrayList/System.Collections.IListWrapper.ToArray ::System::Array* System::Collections::ArrayList::IListWrapper::ToArray(::System::Type* type) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::ArrayList::IListWrapper::ToArray"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::ArrayList*), 45)); return ::il2cpp_utils::RunMethodRethrow<::System::Array*, false>(this, ___internal__method, type); } // Autogenerated from CppSourceCreator // Created by Sc2ad // ========================================================================= // Begin includes #include "beatsaber-hook/shared/utils/typedefs.h" // Including type: System.Collections.ArrayList/System.Collections.ReadOnlyList #include "System/Collections/ArrayList_ReadOnlyList.hpp" // Including type: System.Array #include "System/Array.hpp" // Including type: System.Collections.IEnumerator #include "System/Collections/IEnumerator.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils.hpp" #include "beatsaber-hook/shared/utils/utils.h" // Completed includes // Autogenerated instance field getter // Get instance field: private System.Collections.IList _list [[deprecated("Use field access instead!")]] ::System::Collections::IList*& System::Collections::ArrayList::ReadOnlyList::dyn__list() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::ArrayList::ReadOnlyList::dyn__list"); auto ___internal__instance = this; static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "_list"))->offset; return *reinterpret_cast<::System::Collections::IList**>(reinterpret_cast<char*>(this) + ___internal__field__offset); } // Autogenerated method: System.Collections.ArrayList/System.Collections.ReadOnlyList.get_Count int System::Collections::ArrayList::ReadOnlyList::get_Count() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::ArrayList::ReadOnlyList::get_Count"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::ArrayList::ReadOnlyList*), 19)); return ::il2cpp_utils::RunMethodRethrow<int, false>(this, ___internal__method); } // Autogenerated method: System.Collections.ArrayList/System.Collections.ReadOnlyList.get_IsReadOnly bool System::Collections::ArrayList::ReadOnlyList::get_IsReadOnly() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::ArrayList::ReadOnlyList::get_IsReadOnly"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::ArrayList::ReadOnlyList*), 20)); return ::il2cpp_utils::RunMethodRethrow<bool, false>(this, ___internal__method); } // Autogenerated method: System.Collections.ArrayList/System.Collections.ReadOnlyList.get_IsFixedSize bool System::Collections::ArrayList::ReadOnlyList::get_IsFixedSize() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::ArrayList::ReadOnlyList::get_IsFixedSize"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::ArrayList::ReadOnlyList*), 21)); return ::il2cpp_utils::RunMethodRethrow<bool, false>(this, ___internal__method); } // Autogenerated method: System.Collections.ArrayList/System.Collections.ReadOnlyList.get_Item ::Il2CppObject* System::Collections::ArrayList::ReadOnlyList::get_Item(int index) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::ArrayList::ReadOnlyList::get_Item"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::ArrayList::ReadOnlyList*), 22)); return ::il2cpp_utils::RunMethodRethrow<::Il2CppObject*, false>(this, ___internal__method, index); } // Autogenerated method: System.Collections.ArrayList/System.Collections.ReadOnlyList.set_Item void System::Collections::ArrayList::ReadOnlyList::set_Item(int index, ::Il2CppObject* value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::ArrayList::ReadOnlyList::set_Item"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::ArrayList::ReadOnlyList*), 23)); ::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, index, value); } // Autogenerated method: System.Collections.ArrayList/System.Collections.ReadOnlyList.get_SyncRoot ::Il2CppObject* System::Collections::ArrayList::ReadOnlyList::get_SyncRoot() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::ArrayList::ReadOnlyList::get_SyncRoot"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::ArrayList::ReadOnlyList*), 24)); return ::il2cpp_utils::RunMethodRethrow<::Il2CppObject*, false>(this, ___internal__method); } // Autogenerated method: System.Collections.ArrayList/System.Collections.ReadOnlyList.Add int System::Collections::ArrayList::ReadOnlyList::Add(::Il2CppObject* obj) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::ArrayList::ReadOnlyList::Add"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::ArrayList::ReadOnlyList*), 25)); return ::il2cpp_utils::RunMethodRethrow<int, false>(this, ___internal__method, obj); } // Autogenerated method: System.Collections.ArrayList/System.Collections.ReadOnlyList.Clear void System::Collections::ArrayList::ReadOnlyList::Clear() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::ArrayList::ReadOnlyList::Clear"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::ArrayList::ReadOnlyList*), 26)); ::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method); } // Autogenerated method: System.Collections.ArrayList/System.Collections.ReadOnlyList.Contains bool System::Collections::ArrayList::ReadOnlyList::Contains(::Il2CppObject* obj) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::ArrayList::ReadOnlyList::Contains"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::ArrayList::ReadOnlyList*), 27)); return ::il2cpp_utils::RunMethodRethrow<bool, false>(this, ___internal__method, obj); } // Autogenerated method: System.Collections.ArrayList/System.Collections.ReadOnlyList.CopyTo void System::Collections::ArrayList::ReadOnlyList::CopyTo(::System::Array* array, int index) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::ArrayList::ReadOnlyList::CopyTo"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::ArrayList::ReadOnlyList*), 28)); ::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, array, index); } // Autogenerated method: System.Collections.ArrayList/System.Collections.ReadOnlyList.GetEnumerator ::System::Collections::IEnumerator* System::Collections::ArrayList::ReadOnlyList::GetEnumerator() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::ArrayList::ReadOnlyList::GetEnumerator"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::ArrayList::ReadOnlyList*), 29)); return ::il2cpp_utils::RunMethodRethrow<::System::Collections::IEnumerator*, false>(this, ___internal__method); } // Autogenerated method: System.Collections.ArrayList/System.Collections.ReadOnlyList.IndexOf int System::Collections::ArrayList::ReadOnlyList::IndexOf(::Il2CppObject* value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::ArrayList::ReadOnlyList::IndexOf"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::ArrayList::ReadOnlyList*), 30)); return ::il2cpp_utils::RunMethodRethrow<int, false>(this, ___internal__method, value); } // Autogenerated method: System.Collections.ArrayList/System.Collections.ReadOnlyList.Insert void System::Collections::ArrayList::ReadOnlyList::Insert(int index, ::Il2CppObject* obj) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::ArrayList::ReadOnlyList::Insert"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::ArrayList::ReadOnlyList*), 31)); ::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, index, obj); } // Autogenerated method: System.Collections.ArrayList/System.Collections.ReadOnlyList.Remove void System::Collections::ArrayList::ReadOnlyList::Remove(::Il2CppObject* value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::ArrayList::ReadOnlyList::Remove"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::ArrayList::ReadOnlyList*), 32)); ::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, value); } // Autogenerated method: System.Collections.ArrayList/System.Collections.ReadOnlyList.RemoveAt void System::Collections::ArrayList::ReadOnlyList::RemoveAt(int index) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::ArrayList::ReadOnlyList::RemoveAt"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::ArrayList::ReadOnlyList*), 33)); ::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, index); } // Autogenerated from CppSourceCreator // Created by Sc2ad // ========================================================================= // Begin includes #include "beatsaber-hook/shared/utils/typedefs.h" // Including type: System.Collections.ArrayList/System.Collections.ReadOnlyArrayList #include "System/Collections/ArrayList_ReadOnlyArrayList.hpp" // Including type: System.Collections.ICollection #include "System/Collections/ICollection.hpp" // Including type: System.Array #include "System/Array.hpp" // Including type: System.Collections.IEnumerator #include "System/Collections/IEnumerator.hpp" // Including type: System.Collections.IComparer #include "System/Collections/IComparer.hpp" // Including type: System.Type #include "System/Type.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils.hpp" #include "beatsaber-hook/shared/utils/utils.h" // Completed includes // Autogenerated instance field getter // Get instance field: private System.Collections.ArrayList _list [[deprecated("Use field access instead!")]] ::System::Collections::ArrayList*& System::Collections::ArrayList::ReadOnlyArrayList::dyn__list() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::ArrayList::ReadOnlyArrayList::dyn__list"); auto ___internal__instance = this; static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "_list"))->offset; return *reinterpret_cast<::System::Collections::ArrayList**>(reinterpret_cast<char*>(this) + ___internal__field__offset); } // Autogenerated method: System.Collections.ArrayList/System.Collections.ReadOnlyArrayList.get_Count int System::Collections::ArrayList::ReadOnlyArrayList::get_Count() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::ArrayList::ReadOnlyArrayList::get_Count"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::ArrayList*), 21)); return ::il2cpp_utils::RunMethodRethrow<int, false>(this, ___internal__method); } // Autogenerated method: System.Collections.ArrayList/System.Collections.ReadOnlyArrayList.get_IsReadOnly bool System::Collections::ArrayList::ReadOnlyArrayList::get_IsReadOnly() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::ArrayList::ReadOnlyArrayList::get_IsReadOnly"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::ArrayList*), 23)); return ::il2cpp_utils::RunMethodRethrow<bool, false>(this, ___internal__method); } // Autogenerated method: System.Collections.ArrayList/System.Collections.ReadOnlyArrayList.get_IsFixedSize bool System::Collections::ArrayList::ReadOnlyArrayList::get_IsFixedSize() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::ArrayList::ReadOnlyArrayList::get_IsFixedSize"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::ArrayList*), 22)); return ::il2cpp_utils::RunMethodRethrow<bool, false>(this, ___internal__method); } // Autogenerated method: System.Collections.ArrayList/System.Collections.ReadOnlyArrayList.get_Item ::Il2CppObject* System::Collections::ArrayList::ReadOnlyArrayList::get_Item(int index) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::ArrayList::ReadOnlyArrayList::get_Item"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::ArrayList*), 25)); return ::il2cpp_utils::RunMethodRethrow<::Il2CppObject*, false>(this, ___internal__method, index); } // Autogenerated method: System.Collections.ArrayList/System.Collections.ReadOnlyArrayList.set_Item void System::Collections::ArrayList::ReadOnlyArrayList::set_Item(int index, ::Il2CppObject* value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::ArrayList::ReadOnlyArrayList::set_Item"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::ArrayList*), 26)); ::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, index, value); } // Autogenerated method: System.Collections.ArrayList/System.Collections.ReadOnlyArrayList.get_SyncRoot ::Il2CppObject* System::Collections::ArrayList::ReadOnlyArrayList::get_SyncRoot() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::ArrayList::ReadOnlyArrayList::get_SyncRoot"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::ArrayList*), 24)); return ::il2cpp_utils::RunMethodRethrow<::Il2CppObject*, false>(this, ___internal__method); } // Autogenerated method: System.Collections.ArrayList/System.Collections.ReadOnlyArrayList.set_Capacity void System::Collections::ArrayList::ReadOnlyArrayList::set_Capacity(int value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::ArrayList::ReadOnlyArrayList::set_Capacity"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::ArrayList*), 20)); ::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, value); } // Autogenerated method: System.Collections.ArrayList/System.Collections.ReadOnlyArrayList.Add int System::Collections::ArrayList::ReadOnlyArrayList::Add(::Il2CppObject* obj) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::ArrayList::ReadOnlyArrayList::Add"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::ArrayList*), 27)); return ::il2cpp_utils::RunMethodRethrow<int, false>(this, ___internal__method, obj); } // Autogenerated method: System.Collections.ArrayList/System.Collections.ReadOnlyArrayList.AddRange void System::Collections::ArrayList::ReadOnlyArrayList::AddRange(::System::Collections::ICollection* c) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::ArrayList::ReadOnlyArrayList::AddRange"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::ArrayList*), 28)); ::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, c); } // Autogenerated method: System.Collections.ArrayList/System.Collections.ReadOnlyArrayList.Clear void System::Collections::ArrayList::ReadOnlyArrayList::Clear() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::ArrayList::ReadOnlyArrayList::Clear"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::ArrayList*), 29)); ::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method); } // Autogenerated method: System.Collections.ArrayList/System.Collections.ReadOnlyArrayList.Clone ::Il2CppObject* System::Collections::ArrayList::ReadOnlyArrayList::Clone() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::ArrayList::ReadOnlyArrayList::Clone"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::ArrayList*), 30)); return ::il2cpp_utils::RunMethodRethrow<::Il2CppObject*, false>(this, ___internal__method); } // Autogenerated method: System.Collections.ArrayList/System.Collections.ReadOnlyArrayList.Contains bool System::Collections::ArrayList::ReadOnlyArrayList::Contains(::Il2CppObject* obj) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::ArrayList::ReadOnlyArrayList::Contains"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::ArrayList*), 31)); return ::il2cpp_utils::RunMethodRethrow<bool, false>(this, ___internal__method, obj); } // Autogenerated method: System.Collections.ArrayList/System.Collections.ReadOnlyArrayList.CopyTo void System::Collections::ArrayList::ReadOnlyArrayList::CopyTo(::System::Array* array, int index) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::ArrayList::ReadOnlyArrayList::CopyTo"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::ArrayList*), 33)); ::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, array, index); } // Autogenerated method: System.Collections.ArrayList/System.Collections.ReadOnlyArrayList.CopyTo void System::Collections::ArrayList::ReadOnlyArrayList::CopyTo(int index, ::System::Array* array, int arrayIndex, int count) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::ArrayList::ReadOnlyArrayList::CopyTo"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::ArrayList*), 34)); ::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, index, array, arrayIndex, count); } // Autogenerated method: System.Collections.ArrayList/System.Collections.ReadOnlyArrayList.GetEnumerator ::System::Collections::IEnumerator* System::Collections::ArrayList::ReadOnlyArrayList::GetEnumerator() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::ArrayList::ReadOnlyArrayList::GetEnumerator"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::ArrayList*), 35)); return ::il2cpp_utils::RunMethodRethrow<::System::Collections::IEnumerator*, false>(this, ___internal__method); } // Autogenerated method: System.Collections.ArrayList/System.Collections.ReadOnlyArrayList.IndexOf int System::Collections::ArrayList::ReadOnlyArrayList::IndexOf(::Il2CppObject* value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::ArrayList::ReadOnlyArrayList::IndexOf"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::ArrayList*), 36)); return ::il2cpp_utils::RunMethodRethrow<int, false>(this, ___internal__method, value); } // Autogenerated method: System.Collections.ArrayList/System.Collections.ReadOnlyArrayList.Insert void System::Collections::ArrayList::ReadOnlyArrayList::Insert(int index, ::Il2CppObject* obj) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::ArrayList::ReadOnlyArrayList::Insert"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::ArrayList*), 37)); ::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, index, obj); } // Autogenerated method: System.Collections.ArrayList/System.Collections.ReadOnlyArrayList.InsertRange void System::Collections::ArrayList::ReadOnlyArrayList::InsertRange(int index, ::System::Collections::ICollection* c) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::ArrayList::ReadOnlyArrayList::InsertRange"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::ArrayList*), 38)); ::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, index, c); } // Autogenerated method: System.Collections.ArrayList/System.Collections.ReadOnlyArrayList.Remove void System::Collections::ArrayList::ReadOnlyArrayList::Remove(::Il2CppObject* value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::ArrayList::ReadOnlyArrayList::Remove"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::ArrayList*), 39)); ::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, value); } // Autogenerated method: System.Collections.ArrayList/System.Collections.ReadOnlyArrayList.RemoveAt void System::Collections::ArrayList::ReadOnlyArrayList::RemoveAt(int index) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::ArrayList::ReadOnlyArrayList::RemoveAt"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::ArrayList*), 40)); ::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, index); } // Autogenerated method: System.Collections.ArrayList/System.Collections.ReadOnlyArrayList.RemoveRange void System::Collections::ArrayList::ReadOnlyArrayList::RemoveRange(int index, int count) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::ArrayList::ReadOnlyArrayList::RemoveRange"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::ArrayList*), 41)); ::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, index, count); } // Autogenerated method: System.Collections.ArrayList/System.Collections.ReadOnlyArrayList.Sort void System::Collections::ArrayList::ReadOnlyArrayList::Sort(int index, int count, ::System::Collections::IComparer* comparer) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::ArrayList::ReadOnlyArrayList::Sort"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::ArrayList*), 43)); ::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, index, count, comparer); } // Autogenerated method: System.Collections.ArrayList/System.Collections.ReadOnlyArrayList.ToArray ::ArrayW<::Il2CppObject*> System::Collections::ArrayList::ReadOnlyArrayList::ToArray() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::ArrayList::ReadOnlyArrayList::ToArray"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::ArrayList*), 44)); return ::il2cpp_utils::RunMethodRethrow<::ArrayW<::Il2CppObject*>, false>(this, ___internal__method); } // Autogenerated method: System.Collections.ArrayList/System.Collections.ReadOnlyArrayList.ToArray ::System::Array* System::Collections::ArrayList::ReadOnlyArrayList::ToArray(::System::Type* type) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::ArrayList::ReadOnlyArrayList::ToArray"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::ArrayList*), 45)); return ::il2cpp_utils::RunMethodRethrow<::System::Array*, false>(this, ___internal__method, type); } // Autogenerated from CppSourceCreator // Created by Sc2ad // ========================================================================= // Begin includes #include "beatsaber-hook/shared/utils/typedefs.h" // Including type: System.Collections.ArrayList/System.Collections.ArrayListEnumeratorSimple #include "System/Collections/ArrayList_ArrayListEnumeratorSimple.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils.hpp" #include "beatsaber-hook/shared/utils/utils.h" // Completed includes // Autogenerated static field getter // Get static field: static private System.Object dummyObject ::Il2CppObject* System::Collections::ArrayList::ArrayListEnumeratorSimple::_get_dummyObject() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::ArrayList::ArrayListEnumeratorSimple::_get_dummyObject"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<::Il2CppObject*>("System.Collections", "ArrayList/ArrayListEnumeratorSimple", "dummyObject")); } // Autogenerated static field setter // Set static field: static private System.Object dummyObject void System::Collections::ArrayList::ArrayListEnumeratorSimple::_set_dummyObject(::Il2CppObject* value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::ArrayList::ArrayListEnumeratorSimple::_set_dummyObject"); THROW_UNLESS(il2cpp_utils::SetFieldValue("System.Collections", "ArrayList/ArrayListEnumeratorSimple", "dummyObject", value)); } // Autogenerated instance field getter // Get instance field: private System.Collections.ArrayList list [[deprecated("Use field access instead!")]] ::System::Collections::ArrayList*& System::Collections::ArrayList::ArrayListEnumeratorSimple::dyn_list() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::ArrayList::ArrayListEnumeratorSimple::dyn_list"); auto ___internal__instance = this; static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "list"))->offset; return *reinterpret_cast<::System::Collections::ArrayList**>(reinterpret_cast<char*>(this) + ___internal__field__offset); } // Autogenerated instance field getter // Get instance field: private System.Int32 index [[deprecated("Use field access instead!")]] int& System::Collections::ArrayList::ArrayListEnumeratorSimple::dyn_index() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::ArrayList::ArrayListEnumeratorSimple::dyn_index"); auto ___internal__instance = this; static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "index"))->offset; return *reinterpret_cast<int*>(reinterpret_cast<char*>(this) + ___internal__field__offset); } // Autogenerated instance field getter // Get instance field: private System.Int32 version [[deprecated("Use field access instead!")]] int& System::Collections::ArrayList::ArrayListEnumeratorSimple::dyn_version() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::ArrayList::ArrayListEnumeratorSimple::dyn_version"); auto ___internal__instance = this; static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "version"))->offset; return *reinterpret_cast<int*>(reinterpret_cast<char*>(this) + ___internal__field__offset); } // Autogenerated instance field getter // Get instance field: private System.Object currentElement [[deprecated("Use field access instead!")]] ::Il2CppObject*& System::Collections::ArrayList::ArrayListEnumeratorSimple::dyn_currentElement() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::ArrayList::ArrayListEnumeratorSimple::dyn_currentElement"); auto ___internal__instance = this; static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "currentElement"))->offset; return *reinterpret_cast<::Il2CppObject**>(reinterpret_cast<char*>(this) + ___internal__field__offset); } // Autogenerated instance field getter // Get instance field: private System.Boolean isArrayList [[deprecated("Use field access instead!")]] bool& System::Collections::ArrayList::ArrayListEnumeratorSimple::dyn_isArrayList() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::ArrayList::ArrayListEnumeratorSimple::dyn_isArrayList"); auto ___internal__instance = this; static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "isArrayList"))->offset; return *reinterpret_cast<bool*>(reinterpret_cast<char*>(this) + ___internal__field__offset); } // Autogenerated method: System.Collections.ArrayList/System.Collections.ArrayListEnumeratorSimple.get_Current ::Il2CppObject* System::Collections::ArrayList::ArrayListEnumeratorSimple::get_Current() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::ArrayList::ArrayListEnumeratorSimple::get_Current"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::ArrayList::ArrayListEnumeratorSimple*), 5)); return ::il2cpp_utils::RunMethodRethrow<::Il2CppObject*, false>(this, ___internal__method); } // Autogenerated method: System.Collections.ArrayList/System.Collections.ArrayListEnumeratorSimple..cctor void System::Collections::ArrayList::ArrayListEnumeratorSimple::_cctor() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::ArrayList::ArrayListEnumeratorSimple::.cctor"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Collections", "ArrayList/ArrayListEnumeratorSimple", ".cctor", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); ::il2cpp_utils::RunMethodRethrow<void, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method); } // Autogenerated method: System.Collections.ArrayList/System.Collections.ArrayListEnumeratorSimple.Clone ::Il2CppObject* System::Collections::ArrayList::ArrayListEnumeratorSimple::Clone() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::ArrayList::ArrayListEnumeratorSimple::Clone"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::ArrayList::ArrayListEnumeratorSimple*), 7)); return ::il2cpp_utils::RunMethodRethrow<::Il2CppObject*, false>(this, ___internal__method); } // Autogenerated method: System.Collections.ArrayList/System.Collections.ArrayListEnumeratorSimple.MoveNext bool System::Collections::ArrayList::ArrayListEnumeratorSimple::MoveNext() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::ArrayList::ArrayListEnumeratorSimple::MoveNext"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::ArrayList::ArrayListEnumeratorSimple*), 4)); return ::il2cpp_utils::RunMethodRethrow<bool, false>(this, ___internal__method); } // Autogenerated method: System.Collections.ArrayList/System.Collections.ArrayListEnumeratorSimple.Reset void System::Collections::ArrayList::ArrayListEnumeratorSimple::Reset() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::ArrayList::ArrayListEnumeratorSimple::Reset"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::ArrayList::ArrayListEnumeratorSimple*), 6)); ::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method); } // Autogenerated from CppSourceCreator // Created by Sc2ad // ========================================================================= // Begin includes #include "beatsaber-hook/shared/utils/typedefs.h" // Including type: System.Collections.BitArray #include "System/Collections/BitArray.hpp" // Including type: System.Collections.BitArray/System.Collections.BitArrayEnumeratorSimple #include "System/Collections/BitArray_BitArrayEnumeratorSimple.hpp" // Including type: System.Array #include "System/Array.hpp" // Including type: System.Collections.IEnumerator #include "System/Collections/IEnumerator.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils.hpp" #include "beatsaber-hook/shared/utils/utils.h" // Completed includes // Autogenerated instance field getter // Get instance field: private System.Int32[] m_array [[deprecated("Use field access instead!")]] ::ArrayW<int>& System::Collections::BitArray::dyn_m_array() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::BitArray::dyn_m_array"); auto ___internal__instance = this; static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "m_array"))->offset; return *reinterpret_cast<::ArrayW<int>*>(reinterpret_cast<char*>(this) + ___internal__field__offset); } // Autogenerated instance field getter // Get instance field: private System.Int32 m_length [[deprecated("Use field access instead!")]] int& System::Collections::BitArray::dyn_m_length() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::BitArray::dyn_m_length"); auto ___internal__instance = this; static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "m_length"))->offset; return *reinterpret_cast<int*>(reinterpret_cast<char*>(this) + ___internal__field__offset); } // Autogenerated instance field getter // Get instance field: private System.Int32 _version [[deprecated("Use field access instead!")]] int& System::Collections::BitArray::dyn__version() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::BitArray::dyn__version"); auto ___internal__instance = this; static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "_version"))->offset; return *reinterpret_cast<int*>(reinterpret_cast<char*>(this) + ___internal__field__offset); } // Autogenerated instance field getter // Get instance field: private System.Object _syncRoot [[deprecated("Use field access instead!")]] ::Il2CppObject*& System::Collections::BitArray::dyn__syncRoot() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::BitArray::dyn__syncRoot"); auto ___internal__instance = this; static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "_syncRoot"))->offset; return *reinterpret_cast<::Il2CppObject**>(reinterpret_cast<char*>(this) + ___internal__field__offset); } // Autogenerated method: System.Collections.BitArray.get_Item bool System::Collections::BitArray::get_Item(int index) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::BitArray::get_Item"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "get_Item", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(index)}))); return ::il2cpp_utils::RunMethodRethrow<bool, false>(this, ___internal__method, index); } // Autogenerated method: System.Collections.BitArray.set_Item void System::Collections::BitArray::set_Item(int index, bool value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::BitArray::set_Item"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "set_Item", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(index), ::il2cpp_utils::ExtractType(value)}))); ::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, index, value); } // Autogenerated method: System.Collections.BitArray.get_Length int System::Collections::BitArray::get_Length() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::BitArray::get_Length"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "get_Length", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); return ::il2cpp_utils::RunMethodRethrow<int, false>(this, ___internal__method); } // Autogenerated method: System.Collections.BitArray.set_Length void System::Collections::BitArray::set_Length(int value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::BitArray::set_Length"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "set_Length", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(value)}))); ::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, value); } // Autogenerated method: System.Collections.BitArray.get_Count int System::Collections::BitArray::get_Count() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::BitArray::get_Count"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::BitArray*), 5)); return ::il2cpp_utils::RunMethodRethrow<int, false>(this, ___internal__method); } // Autogenerated method: System.Collections.BitArray.get_SyncRoot ::Il2CppObject* System::Collections::BitArray::get_SyncRoot() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::BitArray::get_SyncRoot"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::BitArray*), 6)); return ::il2cpp_utils::RunMethodRethrow<::Il2CppObject*, false>(this, ___internal__method); } // Autogenerated method: System.Collections.BitArray.Get bool System::Collections::BitArray::Get(int index) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::BitArray::Get"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "Get", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(index)}))); return ::il2cpp_utils::RunMethodRethrow<bool, false>(this, ___internal__method, index); } // Autogenerated method: System.Collections.BitArray.Set void System::Collections::BitArray::Set(int index, bool value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::BitArray::Set"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "Set", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(index), ::il2cpp_utils::ExtractType(value)}))); ::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, index, value); } // Autogenerated method: System.Collections.BitArray.CopyTo void System::Collections::BitArray::CopyTo(::System::Array* array, int index) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::BitArray::CopyTo"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::BitArray*), 4)); ::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, array, index); } // Autogenerated method: System.Collections.BitArray.Clone ::Il2CppObject* System::Collections::BitArray::Clone() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::BitArray::Clone"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::BitArray*), 8)); return ::il2cpp_utils::RunMethodRethrow<::Il2CppObject*, false>(this, ___internal__method); } // Autogenerated method: System.Collections.BitArray.GetEnumerator ::System::Collections::IEnumerator* System::Collections::BitArray::GetEnumerator() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::BitArray::GetEnumerator"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::BitArray*), 7)); return ::il2cpp_utils::RunMethodRethrow<::System::Collections::IEnumerator*, false>(this, ___internal__method); } // Autogenerated method: System.Collections.BitArray.GetArrayLength int System::Collections::BitArray::GetArrayLength(int n, int div) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::BitArray::GetArrayLength"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Collections", "BitArray", "GetArrayLength", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(n), ::il2cpp_utils::ExtractType(div)}))); return ::il2cpp_utils::RunMethodRethrow<int, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method, n, div); } // Autogenerated from CppSourceCreator // Created by Sc2ad // ========================================================================= // Begin includes #include "beatsaber-hook/shared/utils/typedefs.h" // Including type: System.Collections.BitArray/System.Collections.BitArrayEnumeratorSimple #include "System/Collections/BitArray_BitArrayEnumeratorSimple.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils.hpp" #include "beatsaber-hook/shared/utils/utils.h" // Completed includes // Autogenerated instance field getter // Get instance field: private System.Collections.BitArray bitarray [[deprecated("Use field access instead!")]] ::System::Collections::BitArray*& System::Collections::BitArray::BitArrayEnumeratorSimple::dyn_bitarray() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::BitArray::BitArrayEnumeratorSimple::dyn_bitarray"); auto ___internal__instance = this; static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "bitarray"))->offset; return *reinterpret_cast<::System::Collections::BitArray**>(reinterpret_cast<char*>(this) + ___internal__field__offset); } // Autogenerated instance field getter // Get instance field: private System.Int32 index [[deprecated("Use field access instead!")]] int& System::Collections::BitArray::BitArrayEnumeratorSimple::dyn_index() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::BitArray::BitArrayEnumeratorSimple::dyn_index"); auto ___internal__instance = this; static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "index"))->offset; return *reinterpret_cast<int*>(reinterpret_cast<char*>(this) + ___internal__field__offset); } // Autogenerated instance field getter // Get instance field: private System.Int32 version [[deprecated("Use field access instead!")]] int& System::Collections::BitArray::BitArrayEnumeratorSimple::dyn_version() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::BitArray::BitArrayEnumeratorSimple::dyn_version"); auto ___internal__instance = this; static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "version"))->offset; return *reinterpret_cast<int*>(reinterpret_cast<char*>(this) + ___internal__field__offset); } // Autogenerated instance field getter // Get instance field: private System.Boolean currentElement [[deprecated("Use field access instead!")]] bool& System::Collections::BitArray::BitArrayEnumeratorSimple::dyn_currentElement() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::BitArray::BitArrayEnumeratorSimple::dyn_currentElement"); auto ___internal__instance = this; static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "currentElement"))->offset; return *reinterpret_cast<bool*>(reinterpret_cast<char*>(this) + ___internal__field__offset); } // Autogenerated method: System.Collections.BitArray/System.Collections.BitArrayEnumeratorSimple.get_Current ::Il2CppObject* System::Collections::BitArray::BitArrayEnumeratorSimple::get_Current() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::BitArray::BitArrayEnumeratorSimple::get_Current"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::BitArray::BitArrayEnumeratorSimple*), 9)); return ::il2cpp_utils::RunMethodRethrow<::Il2CppObject*, false>(this, ___internal__method); } // Autogenerated method: System.Collections.BitArray/System.Collections.BitArrayEnumeratorSimple.Clone ::Il2CppObject* System::Collections::BitArray::BitArrayEnumeratorSimple::Clone() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::BitArray::BitArrayEnumeratorSimple::Clone"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::BitArray::BitArrayEnumeratorSimple*), 7)); return ::il2cpp_utils::RunMethodRethrow<::Il2CppObject*, false>(this, ___internal__method); } // Autogenerated method: System.Collections.BitArray/System.Collections.BitArrayEnumeratorSimple.MoveNext bool System::Collections::BitArray::BitArrayEnumeratorSimple::MoveNext() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::BitArray::BitArrayEnumeratorSimple::MoveNext"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::BitArray::BitArrayEnumeratorSimple*), 8)); return ::il2cpp_utils::RunMethodRethrow<bool, false>(this, ___internal__method); } // Autogenerated method: System.Collections.BitArray/System.Collections.BitArrayEnumeratorSimple.Reset void System::Collections::BitArray::BitArrayEnumeratorSimple::Reset() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::BitArray::BitArrayEnumeratorSimple::Reset"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::BitArray::BitArrayEnumeratorSimple*), 6)); ::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method); } // Autogenerated from CppSourceCreator // Created by Sc2ad // ========================================================================= // Begin includes #include "beatsaber-hook/shared/utils/typedefs.h" // Including type: System.Collections.CaseInsensitiveComparer #include "System/Collections/CaseInsensitiveComparer.hpp" // Including type: System.Globalization.CompareInfo #include "System/Globalization/CompareInfo.hpp" // Including type: System.Globalization.CultureInfo #include "System/Globalization/CultureInfo.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils.hpp" #include "beatsaber-hook/shared/utils/utils.h" // Completed includes // Autogenerated instance field getter // Get instance field: private System.Globalization.CompareInfo m_compareInfo [[deprecated("Use field access instead!")]] ::System::Globalization::CompareInfo*& System::Collections::CaseInsensitiveComparer::dyn_m_compareInfo() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::CaseInsensitiveComparer::dyn_m_compareInfo"); auto ___internal__instance = this; static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "m_compareInfo"))->offset; return *reinterpret_cast<::System::Globalization::CompareInfo**>(reinterpret_cast<char*>(this) + ___internal__field__offset); } // Autogenerated method: System.Collections.CaseInsensitiveComparer.get_Default ::System::Collections::CaseInsensitiveComparer* System::Collections::CaseInsensitiveComparer::get_Default() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::CaseInsensitiveComparer::get_Default"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Collections", "CaseInsensitiveComparer", "get_Default", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); return ::il2cpp_utils::RunMethodRethrow<::System::Collections::CaseInsensitiveComparer*, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method); } // Autogenerated method: System.Collections.CaseInsensitiveComparer.Compare int System::Collections::CaseInsensitiveComparer::Compare(::Il2CppObject* a, ::Il2CppObject* b) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::CaseInsensitiveComparer::Compare"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::CaseInsensitiveComparer*), 4)); return ::il2cpp_utils::RunMethodRethrow<int, false>(this, ___internal__method, a, b); } // Autogenerated from CppSourceCreator // Created by Sc2ad // ========================================================================= // Begin includes #include "beatsaber-hook/shared/utils/typedefs.h" // Including type: System.Collections.CaseInsensitiveHashCodeProvider #include "System/Collections/CaseInsensitiveHashCodeProvider.hpp" // Including type: System.Globalization.TextInfo #include "System/Globalization/TextInfo.hpp" // Including type: System.Globalization.CultureInfo #include "System/Globalization/CultureInfo.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils.hpp" #include "beatsaber-hook/shared/utils/utils.h" // Completed includes // Autogenerated instance field getter // Get instance field: private System.Globalization.TextInfo m_text [[deprecated("Use field access instead!")]] ::System::Globalization::TextInfo*& System::Collections::CaseInsensitiveHashCodeProvider::dyn_m_text() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::CaseInsensitiveHashCodeProvider::dyn_m_text"); auto ___internal__instance = this; static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "m_text"))->offset; return *reinterpret_cast<::System::Globalization::TextInfo**>(reinterpret_cast<char*>(this) + ___internal__field__offset); } // Autogenerated method: System.Collections.CaseInsensitiveHashCodeProvider.get_Default ::System::Collections::CaseInsensitiveHashCodeProvider* System::Collections::CaseInsensitiveHashCodeProvider::get_Default() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::CaseInsensitiveHashCodeProvider::get_Default"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Collections", "CaseInsensitiveHashCodeProvider", "get_Default", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); return ::il2cpp_utils::RunMethodRethrow<::System::Collections::CaseInsensitiveHashCodeProvider*, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method); } // Autogenerated method: System.Collections.CaseInsensitiveHashCodeProvider.GetHashCode int System::Collections::CaseInsensitiveHashCodeProvider::GetHashCode(::Il2CppObject* obj) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::CaseInsensitiveHashCodeProvider::GetHashCode"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::CaseInsensitiveHashCodeProvider*), 4)); return ::il2cpp_utils::RunMethodRethrow<int, false>(this, ___internal__method, obj); } // Autogenerated from CppSourceCreator // Created by Sc2ad // ========================================================================= // Begin includes #include "beatsaber-hook/shared/utils/typedefs.h" // Including type: System.Collections.CollectionBase #include "System/Collections/CollectionBase.hpp" // Including type: System.Collections.ArrayList #include "System/Collections/ArrayList.hpp" // Including type: System.Array #include "System/Array.hpp" // Including type: System.Collections.IEnumerator #include "System/Collections/IEnumerator.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils.hpp" #include "beatsaber-hook/shared/utils/utils.h" // Completed includes // Autogenerated instance field getter // Get instance field: private System.Collections.ArrayList list [[deprecated("Use field access instead!")]] ::System::Collections::ArrayList*& System::Collections::CollectionBase::dyn_list() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::CollectionBase::dyn_list"); auto ___internal__instance = this; static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "list"))->offset; return *reinterpret_cast<::System::Collections::ArrayList**>(reinterpret_cast<char*>(this) + ___internal__field__offset); } // Autogenerated method: System.Collections.CollectionBase.get_InnerList ::System::Collections::ArrayList* System::Collections::CollectionBase::get_InnerList() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::CollectionBase::get_InnerList"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "get_InnerList", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); return ::il2cpp_utils::RunMethodRethrow<::System::Collections::ArrayList*, false>(this, ___internal__method); } // Autogenerated method: System.Collections.CollectionBase.get_List ::System::Collections::IList* System::Collections::CollectionBase::get_List() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::CollectionBase::get_List"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "get_List", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); return ::il2cpp_utils::RunMethodRethrow<::System::Collections::IList*, false>(this, ___internal__method); } // Autogenerated method: System.Collections.CollectionBase.get_Count int System::Collections::CollectionBase::get_Count() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::CollectionBase::get_Count"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::CollectionBase*), 16)); return ::il2cpp_utils::RunMethodRethrow<int, false>(this, ___internal__method); } // Autogenerated method: System.Collections.CollectionBase.System.Collections.IList.get_IsReadOnly bool System::Collections::CollectionBase::System_Collections_IList_get_IsReadOnly() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::CollectionBase::System.Collections.IList.get_IsReadOnly"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::CollectionBase*), 9)); return ::il2cpp_utils::RunMethodRethrow<bool, false>(this, ___internal__method); } // Autogenerated method: System.Collections.CollectionBase.System.Collections.IList.get_IsFixedSize bool System::Collections::CollectionBase::System_Collections_IList_get_IsFixedSize() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::CollectionBase::System.Collections.IList.get_IsFixedSize"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::CollectionBase*), 10)); return ::il2cpp_utils::RunMethodRethrow<bool, false>(this, ___internal__method); } // Autogenerated method: System.Collections.CollectionBase.System.Collections.ICollection.get_SyncRoot ::Il2CppObject* System::Collections::CollectionBase::System_Collections_ICollection_get_SyncRoot() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::CollectionBase::System.Collections.ICollection.get_SyncRoot"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::CollectionBase*), 17)); return ::il2cpp_utils::RunMethodRethrow<::Il2CppObject*, false>(this, ___internal__method); } // Autogenerated method: System.Collections.CollectionBase.System.Collections.IList.get_Item ::Il2CppObject* System::Collections::CollectionBase::System_Collections_IList_get_Item(int index) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::CollectionBase::System.Collections.IList.get_Item"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::CollectionBase*), 4)); return ::il2cpp_utils::RunMethodRethrow<::Il2CppObject*, false>(this, ___internal__method, index); } // Autogenerated method: System.Collections.CollectionBase.System.Collections.IList.set_Item void System::Collections::CollectionBase::System_Collections_IList_set_Item(int index, ::Il2CppObject* value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::CollectionBase::System.Collections.IList.set_Item"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::CollectionBase*), 5)); ::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, index, value); } // Autogenerated method: System.Collections.CollectionBase.Clear void System::Collections::CollectionBase::Clear() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::CollectionBase::Clear"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::CollectionBase*), 8)); ::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method); } // Autogenerated method: System.Collections.CollectionBase.RemoveAt void System::Collections::CollectionBase::RemoveAt(int index) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::CollectionBase::RemoveAt"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::CollectionBase*), 14)); ::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, index); } // Autogenerated method: System.Collections.CollectionBase.System.Collections.ICollection.CopyTo void System::Collections::CollectionBase::System_Collections_ICollection_CopyTo(::System::Array* array, int index) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::CollectionBase::System.Collections.ICollection.CopyTo"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::CollectionBase*), 15)); ::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, array, index); } // Autogenerated method: System.Collections.CollectionBase.System.Collections.IList.Contains bool System::Collections::CollectionBase::System_Collections_IList_Contains(::Il2CppObject* value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::CollectionBase::System.Collections.IList.Contains"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::CollectionBase*), 7)); return ::il2cpp_utils::RunMethodRethrow<bool, false>(this, ___internal__method, value); } // Autogenerated method: System.Collections.CollectionBase.System.Collections.IList.Add int System::Collections::CollectionBase::System_Collections_IList_Add(::Il2CppObject* value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::CollectionBase::System.Collections.IList.Add"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::CollectionBase*), 6)); return ::il2cpp_utils::RunMethodRethrow<int, false>(this, ___internal__method, value); } // Autogenerated method: System.Collections.CollectionBase.System.Collections.IList.Remove void System::Collections::CollectionBase::System_Collections_IList_Remove(::Il2CppObject* value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::CollectionBase::System.Collections.IList.Remove"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::CollectionBase*), 13)); ::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, value); } // Autogenerated method: System.Collections.CollectionBase.System.Collections.IList.IndexOf int System::Collections::CollectionBase::System_Collections_IList_IndexOf(::Il2CppObject* value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::CollectionBase::System.Collections.IList.IndexOf"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::CollectionBase*), 11)); return ::il2cpp_utils::RunMethodRethrow<int, false>(this, ___internal__method, value); } // Autogenerated method: System.Collections.CollectionBase.System.Collections.IList.Insert void System::Collections::CollectionBase::System_Collections_IList_Insert(int index, ::Il2CppObject* value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::CollectionBase::System.Collections.IList.Insert"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::CollectionBase*), 12)); ::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, index, value); } // Autogenerated method: System.Collections.CollectionBase.GetEnumerator ::System::Collections::IEnumerator* System::Collections::CollectionBase::GetEnumerator() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::CollectionBase::GetEnumerator"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::CollectionBase*), 18)); return ::il2cpp_utils::RunMethodRethrow<::System::Collections::IEnumerator*, false>(this, ___internal__method); } // Autogenerated method: System.Collections.CollectionBase.OnSet void System::Collections::CollectionBase::OnSet(int index, ::Il2CppObject* oldValue, ::Il2CppObject* newValue) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::CollectionBase::OnSet"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::CollectionBase*), 19)); ::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, index, oldValue, newValue); } // Autogenerated method: System.Collections.CollectionBase.OnInsert void System::Collections::CollectionBase::OnInsert(int index, ::Il2CppObject* value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::CollectionBase::OnInsert"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::CollectionBase*), 20)); ::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, index, value); } // Autogenerated method: System.Collections.CollectionBase.OnClear void System::Collections::CollectionBase::OnClear() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::CollectionBase::OnClear"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::CollectionBase*), 21)); ::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method); } // Autogenerated method: System.Collections.CollectionBase.OnRemove void System::Collections::CollectionBase::OnRemove(int index, ::Il2CppObject* value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::CollectionBase::OnRemove"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::CollectionBase*), 22)); ::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, index, value); } // Autogenerated method: System.Collections.CollectionBase.OnValidate void System::Collections::CollectionBase::OnValidate(::Il2CppObject* value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::CollectionBase::OnValidate"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::CollectionBase*), 23)); ::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, value); } // Autogenerated method: System.Collections.CollectionBase.OnSetComplete void System::Collections::CollectionBase::OnSetComplete(int index, ::Il2CppObject* oldValue, ::Il2CppObject* newValue) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::CollectionBase::OnSetComplete"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::CollectionBase*), 24)); ::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, index, oldValue, newValue); } // Autogenerated method: System.Collections.CollectionBase.OnInsertComplete void System::Collections::CollectionBase::OnInsertComplete(int index, ::Il2CppObject* value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::CollectionBase::OnInsertComplete"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::CollectionBase*), 25)); ::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, index, value); } // Autogenerated method: System.Collections.CollectionBase.OnClearComplete void System::Collections::CollectionBase::OnClearComplete() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::CollectionBase::OnClearComplete"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::CollectionBase*), 26)); ::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method); } // Autogenerated method: System.Collections.CollectionBase.OnRemoveComplete void System::Collections::CollectionBase::OnRemoveComplete(int index, ::Il2CppObject* value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::CollectionBase::OnRemoveComplete"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::CollectionBase*), 27)); ::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, index, value); } // Autogenerated from CppSourceCreator // Created by Sc2ad // ========================================================================= // Begin includes #include "beatsaber-hook/shared/utils/typedefs.h" // Including type: System.Collections.Comparer #include "System/Collections/Comparer.hpp" // Including type: System.Globalization.CompareInfo #include "System/Globalization/CompareInfo.hpp" // Including type: System.Globalization.CultureInfo #include "System/Globalization/CultureInfo.hpp" // Including type: System.Runtime.Serialization.SerializationInfo #include "System/Runtime/Serialization/SerializationInfo.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils.hpp" #include "beatsaber-hook/shared/utils/utils.h" // Completed includes // Autogenerated static field getter // Get static field: static public readonly System.Collections.Comparer Default ::System::Collections::Comparer* System::Collections::Comparer::_get_Default() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::Comparer::_get_Default"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<::System::Collections::Comparer*>("System.Collections", "Comparer", "Default")); } // Autogenerated static field setter // Set static field: static public readonly System.Collections.Comparer Default void System::Collections::Comparer::_set_Default(::System::Collections::Comparer* value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::Comparer::_set_Default"); THROW_UNLESS(il2cpp_utils::SetFieldValue("System.Collections", "Comparer", "Default", value)); } // Autogenerated static field getter // Get static field: static public readonly System.Collections.Comparer DefaultInvariant ::System::Collections::Comparer* System::Collections::Comparer::_get_DefaultInvariant() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::Comparer::_get_DefaultInvariant"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<::System::Collections::Comparer*>("System.Collections", "Comparer", "DefaultInvariant")); } // Autogenerated static field setter // Set static field: static public readonly System.Collections.Comparer DefaultInvariant void System::Collections::Comparer::_set_DefaultInvariant(::System::Collections::Comparer* value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::Comparer::_set_DefaultInvariant"); THROW_UNLESS(il2cpp_utils::SetFieldValue("System.Collections", "Comparer", "DefaultInvariant", value)); } // Autogenerated instance field getter // Get instance field: private System.Globalization.CompareInfo m_compareInfo [[deprecated("Use field access instead!")]] ::System::Globalization::CompareInfo*& System::Collections::Comparer::dyn_m_compareInfo() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::Comparer::dyn_m_compareInfo"); auto ___internal__instance = this; static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "m_compareInfo"))->offset; return *reinterpret_cast<::System::Globalization::CompareInfo**>(reinterpret_cast<char*>(this) + ___internal__field__offset); } // Autogenerated method: System.Collections.Comparer..cctor void System::Collections::Comparer::_cctor() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::Comparer::.cctor"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Collections", "Comparer", ".cctor", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); ::il2cpp_utils::RunMethodRethrow<void, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method); } // Autogenerated method: System.Collections.Comparer.Compare int System::Collections::Comparer::Compare(::Il2CppObject* a, ::Il2CppObject* b) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::Comparer::Compare"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::Comparer*), 4)); return ::il2cpp_utils::RunMethodRethrow<int, false>(this, ___internal__method, a, b); } // Autogenerated method: System.Collections.Comparer.GetObjectData void System::Collections::Comparer::GetObjectData(::System::Runtime::Serialization::SerializationInfo* info, ::System::Runtime::Serialization::StreamingContext context) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::Comparer::GetObjectData"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::Comparer*), 5)); ::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, info, context); } // Autogenerated from CppSourceCreator // Created by Sc2ad // ========================================================================= // Begin includes #include "beatsaber-hook/shared/utils/typedefs.h" // Including type: System.Collections.CompatibleComparer #include "System/Collections/CompatibleComparer.hpp" // Including type: System.Collections.IComparer #include "System/Collections/IComparer.hpp" // Including type: System.Collections.IHashCodeProvider #include "System/Collections/IHashCodeProvider.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils.hpp" #include "beatsaber-hook/shared/utils/utils.h" // Completed includes // Autogenerated instance field getter // Get instance field: private System.Collections.IComparer _comparer [[deprecated("Use field access instead!")]] ::System::Collections::IComparer*& System::Collections::CompatibleComparer::dyn__comparer() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::CompatibleComparer::dyn__comparer"); auto ___internal__instance = this; static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "_comparer"))->offset; return *reinterpret_cast<::System::Collections::IComparer**>(reinterpret_cast<char*>(this) + ___internal__field__offset); } // Autogenerated instance field getter // Get instance field: private System.Collections.IHashCodeProvider _hcp [[deprecated("Use field access instead!")]] ::System::Collections::IHashCodeProvider*& System::Collections::CompatibleComparer::dyn__hcp() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::CompatibleComparer::dyn__hcp"); auto ___internal__instance = this; static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "_hcp"))->offset; return *reinterpret_cast<::System::Collections::IHashCodeProvider**>(reinterpret_cast<char*>(this) + ___internal__field__offset); } // Autogenerated method: System.Collections.CompatibleComparer.get_Comparer ::System::Collections::IComparer* System::Collections::CompatibleComparer::get_Comparer() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::CompatibleComparer::get_Comparer"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "get_Comparer", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); return ::il2cpp_utils::RunMethodRethrow<::System::Collections::IComparer*, false>(this, ___internal__method); } // Autogenerated method: System.Collections.CompatibleComparer.get_HashCodeProvider ::System::Collections::IHashCodeProvider* System::Collections::CompatibleComparer::get_HashCodeProvider() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::CompatibleComparer::get_HashCodeProvider"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "get_HashCodeProvider", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); return ::il2cpp_utils::RunMethodRethrow<::System::Collections::IHashCodeProvider*, false>(this, ___internal__method); } // Autogenerated method: System.Collections.CompatibleComparer.Compare int System::Collections::CompatibleComparer::Compare(::Il2CppObject* a, ::Il2CppObject* b) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::CompatibleComparer::Compare"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "Compare", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(a), ::il2cpp_utils::ExtractType(b)}))); return ::il2cpp_utils::RunMethodRethrow<int, false>(this, ___internal__method, a, b); } // Autogenerated method: System.Collections.CompatibleComparer.Equals bool System::Collections::CompatibleComparer::Equals(::Il2CppObject* a, ::Il2CppObject* b) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::CompatibleComparer::Equals"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::CompatibleComparer*), 4)); return ::il2cpp_utils::RunMethodRethrow<bool, false>(this, ___internal__method, a, b); } // Autogenerated method: System.Collections.CompatibleComparer.GetHashCode int System::Collections::CompatibleComparer::GetHashCode(::Il2CppObject* obj) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::CompatibleComparer::GetHashCode"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::CompatibleComparer*), 5)); return ::il2cpp_utils::RunMethodRethrow<int, false>(this, ___internal__method, obj); } // Autogenerated from CppSourceCreator // Created by Sc2ad // ========================================================================= // Begin includes #include "beatsaber-hook/shared/utils/typedefs.h" // Including type: System.Collections.EmptyReadOnlyDictionaryInternal #include "System/Collections/EmptyReadOnlyDictionaryInternal.hpp" // Including type: System.Collections.EmptyReadOnlyDictionaryInternal/System.Collections.NodeEnumerator #include "System/Collections/EmptyReadOnlyDictionaryInternal_NodeEnumerator.hpp" // Including type: System.Collections.IEnumerator #include "System/Collections/IEnumerator.hpp" // Including type: System.Array #include "System/Array.hpp" // Including type: System.Collections.IDictionaryEnumerator #include "System/Collections/IDictionaryEnumerator.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils.hpp" #include "beatsaber-hook/shared/utils/utils.h" // Completed includes // Autogenerated method: System.Collections.EmptyReadOnlyDictionaryInternal.get_Count int System::Collections::EmptyReadOnlyDictionaryInternal::get_Count() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::EmptyReadOnlyDictionaryInternal::get_Count"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::EmptyReadOnlyDictionaryInternal*), 11)); return ::il2cpp_utils::RunMethodRethrow<int, false>(this, ___internal__method); } // Autogenerated method: System.Collections.EmptyReadOnlyDictionaryInternal.get_SyncRoot ::Il2CppObject* System::Collections::EmptyReadOnlyDictionaryInternal::get_SyncRoot() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::EmptyReadOnlyDictionaryInternal::get_SyncRoot"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::EmptyReadOnlyDictionaryInternal*), 12)); return ::il2cpp_utils::RunMethodRethrow<::Il2CppObject*, false>(this, ___internal__method); } // Autogenerated method: System.Collections.EmptyReadOnlyDictionaryInternal.get_Item ::Il2CppObject* System::Collections::EmptyReadOnlyDictionaryInternal::get_Item(::Il2CppObject* key) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::EmptyReadOnlyDictionaryInternal::get_Item"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::EmptyReadOnlyDictionaryInternal*), 4)); return ::il2cpp_utils::RunMethodRethrow<::Il2CppObject*, false>(this, ___internal__method, key); } // Autogenerated method: System.Collections.EmptyReadOnlyDictionaryInternal.set_Item void System::Collections::EmptyReadOnlyDictionaryInternal::set_Item(::Il2CppObject* key, ::Il2CppObject* value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::EmptyReadOnlyDictionaryInternal::set_Item"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::EmptyReadOnlyDictionaryInternal*), 5)); ::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, key, value); } // Autogenerated method: System.Collections.EmptyReadOnlyDictionaryInternal.get_Keys ::System::Collections::ICollection* System::Collections::EmptyReadOnlyDictionaryInternal::get_Keys() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::EmptyReadOnlyDictionaryInternal::get_Keys"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::EmptyReadOnlyDictionaryInternal*), 6)); return ::il2cpp_utils::RunMethodRethrow<::System::Collections::ICollection*, false>(this, ___internal__method); } // Autogenerated method: System.Collections.EmptyReadOnlyDictionaryInternal.System.Collections.IEnumerable.GetEnumerator ::System::Collections::IEnumerator* System::Collections::EmptyReadOnlyDictionaryInternal::System_Collections_IEnumerable_GetEnumerator() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::EmptyReadOnlyDictionaryInternal::System.Collections.IEnumerable.GetEnumerator"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::EmptyReadOnlyDictionaryInternal*), 13)); return ::il2cpp_utils::RunMethodRethrow<::System::Collections::IEnumerator*, false>(this, ___internal__method); } // Autogenerated method: System.Collections.EmptyReadOnlyDictionaryInternal.CopyTo void System::Collections::EmptyReadOnlyDictionaryInternal::CopyTo(::System::Array* array, int index) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::EmptyReadOnlyDictionaryInternal::CopyTo"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::EmptyReadOnlyDictionaryInternal*), 10)); ::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, array, index); } // Autogenerated method: System.Collections.EmptyReadOnlyDictionaryInternal.Contains bool System::Collections::EmptyReadOnlyDictionaryInternal::Contains(::Il2CppObject* key) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::EmptyReadOnlyDictionaryInternal::Contains"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::EmptyReadOnlyDictionaryInternal*), 7)); return ::il2cpp_utils::RunMethodRethrow<bool, false>(this, ___internal__method, key); } // Autogenerated method: System.Collections.EmptyReadOnlyDictionaryInternal.GetEnumerator ::System::Collections::IDictionaryEnumerator* System::Collections::EmptyReadOnlyDictionaryInternal::GetEnumerator() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::EmptyReadOnlyDictionaryInternal::GetEnumerator"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::EmptyReadOnlyDictionaryInternal*), 8)); return ::il2cpp_utils::RunMethodRethrow<::System::Collections::IDictionaryEnumerator*, false>(this, ___internal__method); } // Autogenerated method: System.Collections.EmptyReadOnlyDictionaryInternal.Remove void System::Collections::EmptyReadOnlyDictionaryInternal::Remove(::Il2CppObject* key) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::EmptyReadOnlyDictionaryInternal::Remove"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::EmptyReadOnlyDictionaryInternal*), 9)); ::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, key); } // Autogenerated from CppSourceCreator // Created by Sc2ad // ========================================================================= // Begin includes #include "beatsaber-hook/shared/utils/typedefs.h" // Including type: System.Collections.EmptyReadOnlyDictionaryInternal/System.Collections.NodeEnumerator #include "System/Collections/EmptyReadOnlyDictionaryInternal_NodeEnumerator.hpp" // Including type: System.Collections.DictionaryEntry #include "System/Collections/DictionaryEntry.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils.hpp" #include "beatsaber-hook/shared/utils/utils.h" // Completed includes // Autogenerated method: System.Collections.EmptyReadOnlyDictionaryInternal/System.Collections.NodeEnumerator.get_Current ::Il2CppObject* System::Collections::EmptyReadOnlyDictionaryInternal::NodeEnumerator::get_Current() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::EmptyReadOnlyDictionaryInternal::NodeEnumerator::get_Current"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::EmptyReadOnlyDictionaryInternal::NodeEnumerator*), 8)); return ::il2cpp_utils::RunMethodRethrow<::Il2CppObject*, false>(this, ___internal__method); } // Autogenerated method: System.Collections.EmptyReadOnlyDictionaryInternal/System.Collections.NodeEnumerator.get_Key ::Il2CppObject* System::Collections::EmptyReadOnlyDictionaryInternal::NodeEnumerator::get_Key() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::EmptyReadOnlyDictionaryInternal::NodeEnumerator::get_Key"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::EmptyReadOnlyDictionaryInternal::NodeEnumerator*), 4)); return ::il2cpp_utils::RunMethodRethrow<::Il2CppObject*, false>(this, ___internal__method); } // Autogenerated method: System.Collections.EmptyReadOnlyDictionaryInternal/System.Collections.NodeEnumerator.get_Value ::Il2CppObject* System::Collections::EmptyReadOnlyDictionaryInternal::NodeEnumerator::get_Value() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::EmptyReadOnlyDictionaryInternal::NodeEnumerator::get_Value"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::EmptyReadOnlyDictionaryInternal::NodeEnumerator*), 5)); return ::il2cpp_utils::RunMethodRethrow<::Il2CppObject*, false>(this, ___internal__method); } // Autogenerated method: System.Collections.EmptyReadOnlyDictionaryInternal/System.Collections.NodeEnumerator.get_Entry ::System::Collections::DictionaryEntry System::Collections::EmptyReadOnlyDictionaryInternal::NodeEnumerator::get_Entry() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::EmptyReadOnlyDictionaryInternal::NodeEnumerator::get_Entry"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::EmptyReadOnlyDictionaryInternal::NodeEnumerator*), 6)); return ::il2cpp_utils::RunMethodRethrow<::System::Collections::DictionaryEntry, false>(this, ___internal__method); } // Autogenerated method: System.Collections.EmptyReadOnlyDictionaryInternal/System.Collections.NodeEnumerator.MoveNext bool System::Collections::EmptyReadOnlyDictionaryInternal::NodeEnumerator::MoveNext() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::EmptyReadOnlyDictionaryInternal::NodeEnumerator::MoveNext"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::EmptyReadOnlyDictionaryInternal::NodeEnumerator*), 7)); return ::il2cpp_utils::RunMethodRethrow<bool, false>(this, ___internal__method); } // Autogenerated method: System.Collections.EmptyReadOnlyDictionaryInternal/System.Collections.NodeEnumerator.Reset void System::Collections::EmptyReadOnlyDictionaryInternal::NodeEnumerator::Reset() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::EmptyReadOnlyDictionaryInternal::NodeEnumerator::Reset"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::EmptyReadOnlyDictionaryInternal::NodeEnumerator*), 9)); ::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method); } // Autogenerated from CppSourceCreator // Created by Sc2ad // ========================================================================= // Begin includes #include "beatsaber-hook/shared/utils/typedefs.h" // Including type: System.Collections.Hashtable #include "System/Collections/Hashtable.hpp" // Including type: System.Collections.ICollection #include "System/Collections/ICollection.hpp" // Including type: System.Collections.Hashtable/System.Collections.KeyCollection #include "System/Collections/Hashtable_KeyCollection.hpp" // Including type: System.Collections.Hashtable/System.Collections.ValueCollection #include "System/Collections/Hashtable_ValueCollection.hpp" // Including type: System.Collections.Hashtable/System.Collections.SyncHashtable #include "System/Collections/Hashtable_SyncHashtable.hpp" // Including type: System.Collections.Hashtable/System.Collections.HashtableEnumerator #include "System/Collections/Hashtable_HashtableEnumerator.hpp" // Including type: System.Collections.Hashtable/System.Collections.HashtableDebugView #include "System/Collections/Hashtable_HashtableDebugView.hpp" // Including type: System.Collections.IEqualityComparer #include "System/Collections/IEqualityComparer.hpp" // Including type: System.String #include "System/String.hpp" // Including type: System.Collections.IHashCodeProvider #include "System/Collections/IHashCodeProvider.hpp" // Including type: System.Collections.IComparer #include "System/Collections/IComparer.hpp" // Including type: System.Runtime.Serialization.SerializationInfo #include "System/Runtime/Serialization/SerializationInfo.hpp" // Including type: System.Array #include "System/Array.hpp" // Including type: System.Collections.IEnumerator #include "System/Collections/IEnumerator.hpp" // Including type: System.Collections.IDictionaryEnumerator #include "System/Collections/IDictionaryEnumerator.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils.hpp" #include "beatsaber-hook/shared/utils/utils.h" // Completed includes // Autogenerated static field getter // Get static field: static System.Int32 HashPrime int System::Collections::Hashtable::_get_HashPrime() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::Hashtable::_get_HashPrime"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<int>("System.Collections", "Hashtable", "HashPrime")); } // Autogenerated static field setter // Set static field: static System.Int32 HashPrime void System::Collections::Hashtable::_set_HashPrime(int value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::Hashtable::_set_HashPrime"); THROW_UNLESS(il2cpp_utils::SetFieldValue("System.Collections", "Hashtable", "HashPrime", value)); } // Autogenerated static field getter // Get static field: static private System.Int32 InitialSize int System::Collections::Hashtable::_get_InitialSize() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::Hashtable::_get_InitialSize"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<int>("System.Collections", "Hashtable", "InitialSize")); } // Autogenerated static field setter // Set static field: static private System.Int32 InitialSize void System::Collections::Hashtable::_set_InitialSize(int value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::Hashtable::_set_InitialSize"); THROW_UNLESS(il2cpp_utils::SetFieldValue("System.Collections", "Hashtable", "InitialSize", value)); } // Autogenerated static field getter // Get static field: static private System.String LoadFactorName ::StringW System::Collections::Hashtable::_get_LoadFactorName() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::Hashtable::_get_LoadFactorName"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<::StringW>("System.Collections", "Hashtable", "LoadFactorName")); } // Autogenerated static field setter // Set static field: static private System.String LoadFactorName void System::Collections::Hashtable::_set_LoadFactorName(::StringW value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::Hashtable::_set_LoadFactorName"); THROW_UNLESS(il2cpp_utils::SetFieldValue("System.Collections", "Hashtable", "LoadFactorName", value)); } // Autogenerated static field getter // Get static field: static private System.String VersionName ::StringW System::Collections::Hashtable::_get_VersionName() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::Hashtable::_get_VersionName"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<::StringW>("System.Collections", "Hashtable", "VersionName")); } // Autogenerated static field setter // Set static field: static private System.String VersionName void System::Collections::Hashtable::_set_VersionName(::StringW value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::Hashtable::_set_VersionName"); THROW_UNLESS(il2cpp_utils::SetFieldValue("System.Collections", "Hashtable", "VersionName", value)); } // Autogenerated static field getter // Get static field: static private System.String ComparerName ::StringW System::Collections::Hashtable::_get_ComparerName() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::Hashtable::_get_ComparerName"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<::StringW>("System.Collections", "Hashtable", "ComparerName")); } // Autogenerated static field setter // Set static field: static private System.String ComparerName void System::Collections::Hashtable::_set_ComparerName(::StringW value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::Hashtable::_set_ComparerName"); THROW_UNLESS(il2cpp_utils::SetFieldValue("System.Collections", "Hashtable", "ComparerName", value)); } // Autogenerated static field getter // Get static field: static private System.String HashCodeProviderName ::StringW System::Collections::Hashtable::_get_HashCodeProviderName() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::Hashtable::_get_HashCodeProviderName"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<::StringW>("System.Collections", "Hashtable", "HashCodeProviderName")); } // Autogenerated static field setter // Set static field: static private System.String HashCodeProviderName void System::Collections::Hashtable::_set_HashCodeProviderName(::StringW value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::Hashtable::_set_HashCodeProviderName"); THROW_UNLESS(il2cpp_utils::SetFieldValue("System.Collections", "Hashtable", "HashCodeProviderName", value)); } // Autogenerated static field getter // Get static field: static private System.String HashSizeName ::StringW System::Collections::Hashtable::_get_HashSizeName() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::Hashtable::_get_HashSizeName"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<::StringW>("System.Collections", "Hashtable", "HashSizeName")); } // Autogenerated static field setter // Set static field: static private System.String HashSizeName void System::Collections::Hashtable::_set_HashSizeName(::StringW value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::Hashtable::_set_HashSizeName"); THROW_UNLESS(il2cpp_utils::SetFieldValue("System.Collections", "Hashtable", "HashSizeName", value)); } // Autogenerated static field getter // Get static field: static private System.String KeysName ::StringW System::Collections::Hashtable::_get_KeysName() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::Hashtable::_get_KeysName"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<::StringW>("System.Collections", "Hashtable", "KeysName")); } // Autogenerated static field setter // Set static field: static private System.String KeysName void System::Collections::Hashtable::_set_KeysName(::StringW value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::Hashtable::_set_KeysName"); THROW_UNLESS(il2cpp_utils::SetFieldValue("System.Collections", "Hashtable", "KeysName", value)); } // Autogenerated static field getter // Get static field: static private System.String ValuesName ::StringW System::Collections::Hashtable::_get_ValuesName() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::Hashtable::_get_ValuesName"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<::StringW>("System.Collections", "Hashtable", "ValuesName")); } // Autogenerated static field setter // Set static field: static private System.String ValuesName void System::Collections::Hashtable::_set_ValuesName(::StringW value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::Hashtable::_set_ValuesName"); THROW_UNLESS(il2cpp_utils::SetFieldValue("System.Collections", "Hashtable", "ValuesName", value)); } // Autogenerated static field getter // Get static field: static private System.String KeyComparerName ::StringW System::Collections::Hashtable::_get_KeyComparerName() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::Hashtable::_get_KeyComparerName"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<::StringW>("System.Collections", "Hashtable", "KeyComparerName")); } // Autogenerated static field setter // Set static field: static private System.String KeyComparerName void System::Collections::Hashtable::_set_KeyComparerName(::StringW value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::Hashtable::_set_KeyComparerName"); THROW_UNLESS(il2cpp_utils::SetFieldValue("System.Collections", "Hashtable", "KeyComparerName", value)); } // Autogenerated instance field getter // Get instance field: private System.Collections.Hashtable/System.Collections.bucket[] buckets [[deprecated("Use field access instead!")]] ::ArrayW<::System::Collections::Hashtable::bucket>& System::Collections::Hashtable::dyn_buckets() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::Hashtable::dyn_buckets"); auto ___internal__instance = this; static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "buckets"))->offset; return *reinterpret_cast<::ArrayW<::System::Collections::Hashtable::bucket>*>(reinterpret_cast<char*>(this) + ___internal__field__offset); } // Autogenerated instance field getter // Get instance field: private System.Int32 count [[deprecated("Use field access instead!")]] int& System::Collections::Hashtable::dyn_count() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::Hashtable::dyn_count"); auto ___internal__instance = this; static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "count"))->offset; return *reinterpret_cast<int*>(reinterpret_cast<char*>(this) + ___internal__field__offset); } // Autogenerated instance field getter // Get instance field: private System.Int32 occupancy [[deprecated("Use field access instead!")]] int& System::Collections::Hashtable::dyn_occupancy() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::Hashtable::dyn_occupancy"); auto ___internal__instance = this; static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "occupancy"))->offset; return *reinterpret_cast<int*>(reinterpret_cast<char*>(this) + ___internal__field__offset); } // Autogenerated instance field getter // Get instance field: private System.Int32 loadsize [[deprecated("Use field access instead!")]] int& System::Collections::Hashtable::dyn_loadsize() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::Hashtable::dyn_loadsize"); auto ___internal__instance = this; static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "loadsize"))->offset; return *reinterpret_cast<int*>(reinterpret_cast<char*>(this) + ___internal__field__offset); } // Autogenerated instance field getter // Get instance field: private System.Single loadFactor [[deprecated("Use field access instead!")]] float& System::Collections::Hashtable::dyn_loadFactor() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::Hashtable::dyn_loadFactor"); auto ___internal__instance = this; static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "loadFactor"))->offset; return *reinterpret_cast<float*>(reinterpret_cast<char*>(this) + ___internal__field__offset); } // Autogenerated instance field getter // Get instance field: private System.Int32 version [[deprecated("Use field access instead!")]] int& System::Collections::Hashtable::dyn_version() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::Hashtable::dyn_version"); auto ___internal__instance = this; static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "version"))->offset; return *reinterpret_cast<int*>(reinterpret_cast<char*>(this) + ___internal__field__offset); } // Autogenerated instance field getter // Get instance field: private System.Boolean isWriterInProgress [[deprecated("Use field access instead!")]] bool& System::Collections::Hashtable::dyn_isWriterInProgress() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::Hashtable::dyn_isWriterInProgress"); auto ___internal__instance = this; static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "isWriterInProgress"))->offset; return *reinterpret_cast<bool*>(reinterpret_cast<char*>(this) + ___internal__field__offset); } // Autogenerated instance field getter // Get instance field: private System.Collections.ICollection keys [[deprecated("Use field access instead!")]] ::System::Collections::ICollection*& System::Collections::Hashtable::dyn_keys() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::Hashtable::dyn_keys"); auto ___internal__instance = this; static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "keys"))->offset; return *reinterpret_cast<::System::Collections::ICollection**>(reinterpret_cast<char*>(this) + ___internal__field__offset); } // Autogenerated instance field getter // Get instance field: private System.Collections.ICollection values [[deprecated("Use field access instead!")]] ::System::Collections::ICollection*& System::Collections::Hashtable::dyn_values() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::Hashtable::dyn_values"); auto ___internal__instance = this; static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "values"))->offset; return *reinterpret_cast<::System::Collections::ICollection**>(reinterpret_cast<char*>(this) + ___internal__field__offset); } // Autogenerated instance field getter // Get instance field: private System.Collections.IEqualityComparer _keycomparer [[deprecated("Use field access instead!")]] ::System::Collections::IEqualityComparer*& System::Collections::Hashtable::dyn__keycomparer() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::Hashtable::dyn__keycomparer"); auto ___internal__instance = this; static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "_keycomparer"))->offset; return *reinterpret_cast<::System::Collections::IEqualityComparer**>(reinterpret_cast<char*>(this) + ___internal__field__offset); } // Autogenerated instance field getter // Get instance field: private System.Object _syncRoot [[deprecated("Use field access instead!")]] ::Il2CppObject*& System::Collections::Hashtable::dyn__syncRoot() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::Hashtable::dyn__syncRoot"); auto ___internal__instance = this; static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "_syncRoot"))->offset; return *reinterpret_cast<::Il2CppObject**>(reinterpret_cast<char*>(this) + ___internal__field__offset); } // Autogenerated method: System.Collections.Hashtable.get_Item ::Il2CppObject* System::Collections::Hashtable::get_Item(::Il2CppObject* key) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::Hashtable::get_Item"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::Hashtable*), 23)); return ::il2cpp_utils::RunMethodRethrow<::Il2CppObject*, false>(this, ___internal__method, key); } // Autogenerated method: System.Collections.Hashtable.set_Item void System::Collections::Hashtable::set_Item(::Il2CppObject* key, ::Il2CppObject* value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::Hashtable::set_Item"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::Hashtable*), 24)); ::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, key, value); } // Autogenerated method: System.Collections.Hashtable.get_Keys ::System::Collections::ICollection* System::Collections::Hashtable::get_Keys() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::Hashtable::get_Keys"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::Hashtable*), 28)); return ::il2cpp_utils::RunMethodRethrow<::System::Collections::ICollection*, false>(this, ___internal__method); } // Autogenerated method: System.Collections.Hashtable.get_Values ::System::Collections::ICollection* System::Collections::Hashtable::get_Values() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::Hashtable::get_Values"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::Hashtable*), 29)); return ::il2cpp_utils::RunMethodRethrow<::System::Collections::ICollection*, false>(this, ___internal__method); } // Autogenerated method: System.Collections.Hashtable.get_SyncRoot ::Il2CppObject* System::Collections::Hashtable::get_SyncRoot() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::Hashtable::get_SyncRoot"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::Hashtable*), 31)); return ::il2cpp_utils::RunMethodRethrow<::Il2CppObject*, false>(this, ___internal__method); } // Autogenerated method: System.Collections.Hashtable.get_Count int System::Collections::Hashtable::get_Count() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::Hashtable::get_Count"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::Hashtable*), 32)); return ::il2cpp_utils::RunMethodRethrow<int, false>(this, ___internal__method); } // Autogenerated method: System.Collections.Hashtable.InitHash uint System::Collections::Hashtable::InitHash(::Il2CppObject* key, int hashsize, ByRef<uint> seed, ByRef<uint> incr) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::Hashtable::InitHash"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "InitHash", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(key), ::il2cpp_utils::ExtractType(hashsize), ::il2cpp_utils::ExtractIndependentType<uint&>(), ::il2cpp_utils::ExtractIndependentType<uint&>()}))); return ::il2cpp_utils::RunMethodRethrow<uint, false>(this, ___internal__method, key, hashsize, byref(seed), byref(incr)); } // Autogenerated method: System.Collections.Hashtable.Add void System::Collections::Hashtable::Add(::Il2CppObject* key, ::Il2CppObject* value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::Hashtable::Add"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::Hashtable*), 17)); ::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, key, value); } // Autogenerated method: System.Collections.Hashtable.Clear void System::Collections::Hashtable::Clear() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::Hashtable::Clear"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::Hashtable*), 18)); ::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method); } // Autogenerated method: System.Collections.Hashtable.Clone ::Il2CppObject* System::Collections::Hashtable::Clone() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::Hashtable::Clone"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::Hashtable*), 19)); return ::il2cpp_utils::RunMethodRethrow<::Il2CppObject*, false>(this, ___internal__method); } // Autogenerated method: System.Collections.Hashtable.Contains bool System::Collections::Hashtable::Contains(::Il2CppObject* key) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::Hashtable::Contains"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::Hashtable*), 20)); return ::il2cpp_utils::RunMethodRethrow<bool, false>(this, ___internal__method, key); } // Autogenerated method: System.Collections.Hashtable.ContainsKey bool System::Collections::Hashtable::ContainsKey(::Il2CppObject* key) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::Hashtable::ContainsKey"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::Hashtable*), 21)); return ::il2cpp_utils::RunMethodRethrow<bool, false>(this, ___internal__method, key); } // Autogenerated method: System.Collections.Hashtable.CopyKeys void System::Collections::Hashtable::CopyKeys(::System::Array* array, int arrayIndex) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::Hashtable::CopyKeys"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "CopyKeys", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(array), ::il2cpp_utils::ExtractType(arrayIndex)}))); ::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, array, arrayIndex); } // Autogenerated method: System.Collections.Hashtable.CopyEntries void System::Collections::Hashtable::CopyEntries(::System::Array* array, int arrayIndex) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::Hashtable::CopyEntries"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "CopyEntries", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(array), ::il2cpp_utils::ExtractType(arrayIndex)}))); ::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, array, arrayIndex); } // Autogenerated method: System.Collections.Hashtable.CopyTo void System::Collections::Hashtable::CopyTo(::System::Array* array, int arrayIndex) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::Hashtable::CopyTo"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::Hashtable*), 22)); ::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, array, arrayIndex); } // Autogenerated method: System.Collections.Hashtable.CopyValues void System::Collections::Hashtable::CopyValues(::System::Array* array, int arrayIndex) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::Hashtable::CopyValues"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "CopyValues", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(array), ::il2cpp_utils::ExtractType(arrayIndex)}))); ::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, array, arrayIndex); } // Autogenerated method: System.Collections.Hashtable.expand void System::Collections::Hashtable::expand() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::Hashtable::expand"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "expand", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); ::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method); } // Autogenerated method: System.Collections.Hashtable.rehash void System::Collections::Hashtable::rehash() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::Hashtable::rehash"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "rehash", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); ::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method); } // Autogenerated method: System.Collections.Hashtable.UpdateVersion void System::Collections::Hashtable::UpdateVersion() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::Hashtable::UpdateVersion"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "UpdateVersion", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); ::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method); } // Autogenerated method: System.Collections.Hashtable.rehash void System::Collections::Hashtable::rehash(int newsize, bool forceNewHashCode) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::Hashtable::rehash"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "rehash", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(newsize), ::il2cpp_utils::ExtractType(forceNewHashCode)}))); ::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, newsize, forceNewHashCode); } // Autogenerated method: System.Collections.Hashtable.System.Collections.IEnumerable.GetEnumerator ::System::Collections::IEnumerator* System::Collections::Hashtable::System_Collections_IEnumerable_GetEnumerator() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::Hashtable::System.Collections.IEnumerable.GetEnumerator"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::Hashtable*), 13)); return ::il2cpp_utils::RunMethodRethrow<::System::Collections::IEnumerator*, false>(this, ___internal__method); } // Autogenerated method: System.Collections.Hashtable.GetEnumerator ::System::Collections::IDictionaryEnumerator* System::Collections::Hashtable::GetEnumerator() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::Hashtable::GetEnumerator"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::Hashtable*), 25)); return ::il2cpp_utils::RunMethodRethrow<::System::Collections::IDictionaryEnumerator*, false>(this, ___internal__method); } // Autogenerated method: System.Collections.Hashtable.GetHash int System::Collections::Hashtable::GetHash(::Il2CppObject* key) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::Hashtable::GetHash"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::Hashtable*), 26)); return ::il2cpp_utils::RunMethodRethrow<int, false>(this, ___internal__method, key); } // Autogenerated method: System.Collections.Hashtable.KeyEquals bool System::Collections::Hashtable::KeyEquals(::Il2CppObject* item, ::Il2CppObject* key) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::Hashtable::KeyEquals"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::Hashtable*), 27)); return ::il2cpp_utils::RunMethodRethrow<bool, false>(this, ___internal__method, item, key); } // Autogenerated method: System.Collections.Hashtable.Insert void System::Collections::Hashtable::Insert(::Il2CppObject* key, ::Il2CppObject* nvalue, bool add) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::Hashtable::Insert"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "Insert", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(key), ::il2cpp_utils::ExtractType(nvalue), ::il2cpp_utils::ExtractType(add)}))); ::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, key, nvalue, add); } // Autogenerated method: System.Collections.Hashtable.putEntry void System::Collections::Hashtable::putEntry(::ArrayW<::System::Collections::Hashtable::bucket> newBuckets, ::Il2CppObject* key, ::Il2CppObject* nvalue, int hashcode) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::Hashtable::putEntry"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(this, "putEntry", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(newBuckets), ::il2cpp_utils::ExtractType(key), ::il2cpp_utils::ExtractType(nvalue), ::il2cpp_utils::ExtractType(hashcode)}))); ::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, newBuckets, key, nvalue, hashcode); } // Autogenerated method: System.Collections.Hashtable.Remove void System::Collections::Hashtable::Remove(::Il2CppObject* key) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::Hashtable::Remove"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::Hashtable*), 30)); ::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, key); } // Autogenerated method: System.Collections.Hashtable.Synchronized ::System::Collections::Hashtable* System::Collections::Hashtable::Synchronized(::System::Collections::Hashtable* table) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::Hashtable::Synchronized"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Collections", "Hashtable", "Synchronized", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(table)}))); return ::il2cpp_utils::RunMethodRethrow<::System::Collections::Hashtable*, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method, table); } // Autogenerated method: System.Collections.Hashtable.GetObjectData void System::Collections::Hashtable::GetObjectData(::System::Runtime::Serialization::SerializationInfo* info, ::System::Runtime::Serialization::StreamingContext context) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::Hashtable::GetObjectData"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::Hashtable*), 33)); ::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, info, context); } // Autogenerated method: System.Collections.Hashtable.OnDeserialization void System::Collections::Hashtable::OnDeserialization(::Il2CppObject* sender) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::Hashtable::OnDeserialization"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::Hashtable*), 34)); ::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, sender); } // Autogenerated from CppSourceCreator // Created by Sc2ad // ========================================================================= // Begin includes #include "beatsaber-hook/shared/utils/typedefs.h" // Including type: System.Collections.Hashtable/System.Collections.KeyCollection #include "System/Collections/Hashtable_KeyCollection.hpp" // Including type: System.Array #include "System/Array.hpp" // Including type: System.Collections.IEnumerator #include "System/Collections/IEnumerator.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils.hpp" #include "beatsaber-hook/shared/utils/utils.h" // Completed includes // Autogenerated instance field getter // Get instance field: private System.Collections.Hashtable _hashtable [[deprecated("Use field access instead!")]] ::System::Collections::Hashtable*& System::Collections::Hashtable::KeyCollection::dyn__hashtable() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::Hashtable::KeyCollection::dyn__hashtable"); auto ___internal__instance = this; static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "_hashtable"))->offset; return *reinterpret_cast<::System::Collections::Hashtable**>(reinterpret_cast<char*>(this) + ___internal__field__offset); } // Autogenerated method: System.Collections.Hashtable/System.Collections.KeyCollection.get_SyncRoot ::Il2CppObject* System::Collections::Hashtable::KeyCollection::get_SyncRoot() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::Hashtable::KeyCollection::get_SyncRoot"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::Hashtable::KeyCollection*), 10)); return ::il2cpp_utils::RunMethodRethrow<::Il2CppObject*, false>(this, ___internal__method); } // Autogenerated method: System.Collections.Hashtable/System.Collections.KeyCollection.get_Count int System::Collections::Hashtable::KeyCollection::get_Count() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::Hashtable::KeyCollection::get_Count"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::Hashtable::KeyCollection*), 11)); return ::il2cpp_utils::RunMethodRethrow<int, false>(this, ___internal__method); } // Autogenerated method: System.Collections.Hashtable/System.Collections.KeyCollection.CopyTo void System::Collections::Hashtable::KeyCollection::CopyTo(::System::Array* array, int arrayIndex) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::Hashtable::KeyCollection::CopyTo"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::Hashtable::KeyCollection*), 8)); ::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, array, arrayIndex); } // Autogenerated method: System.Collections.Hashtable/System.Collections.KeyCollection.GetEnumerator ::System::Collections::IEnumerator* System::Collections::Hashtable::KeyCollection::GetEnumerator() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::Hashtable::KeyCollection::GetEnumerator"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::Hashtable::KeyCollection*), 9)); return ::il2cpp_utils::RunMethodRethrow<::System::Collections::IEnumerator*, false>(this, ___internal__method); } // Autogenerated from CppSourceCreator // Created by Sc2ad // ========================================================================= // Begin includes #include "beatsaber-hook/shared/utils/typedefs.h" // Including type: System.Collections.Hashtable/System.Collections.ValueCollection #include "System/Collections/Hashtable_ValueCollection.hpp" // Including type: System.Array #include "System/Array.hpp" // Including type: System.Collections.IEnumerator #include "System/Collections/IEnumerator.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils.hpp" #include "beatsaber-hook/shared/utils/utils.h" // Completed includes // Autogenerated instance field getter // Get instance field: private System.Collections.Hashtable _hashtable [[deprecated("Use field access instead!")]] ::System::Collections::Hashtable*& System::Collections::Hashtable::ValueCollection::dyn__hashtable() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::Hashtable::ValueCollection::dyn__hashtable"); auto ___internal__instance = this; static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "_hashtable"))->offset; return *reinterpret_cast<::System::Collections::Hashtable**>(reinterpret_cast<char*>(this) + ___internal__field__offset); } // Autogenerated method: System.Collections.Hashtable/System.Collections.ValueCollection.get_SyncRoot ::Il2CppObject* System::Collections::Hashtable::ValueCollection::get_SyncRoot() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::Hashtable::ValueCollection::get_SyncRoot"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::Hashtable::ValueCollection*), 10)); return ::il2cpp_utils::RunMethodRethrow<::Il2CppObject*, false>(this, ___internal__method); } // Autogenerated method: System.Collections.Hashtable/System.Collections.ValueCollection.get_Count int System::Collections::Hashtable::ValueCollection::get_Count() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::Hashtable::ValueCollection::get_Count"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::Hashtable::ValueCollection*), 11)); return ::il2cpp_utils::RunMethodRethrow<int, false>(this, ___internal__method); } // Autogenerated method: System.Collections.Hashtable/System.Collections.ValueCollection.CopyTo void System::Collections::Hashtable::ValueCollection::CopyTo(::System::Array* array, int arrayIndex) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::Hashtable::ValueCollection::CopyTo"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::Hashtable::ValueCollection*), 8)); ::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, array, arrayIndex); } // Autogenerated method: System.Collections.Hashtable/System.Collections.ValueCollection.GetEnumerator ::System::Collections::IEnumerator* System::Collections::Hashtable::ValueCollection::GetEnumerator() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::Hashtable::ValueCollection::GetEnumerator"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::Hashtable::ValueCollection*), 9)); return ::il2cpp_utils::RunMethodRethrow<::System::Collections::IEnumerator*, false>(this, ___internal__method); } // Autogenerated from CppSourceCreator // Created by Sc2ad // ========================================================================= // Begin includes #include "beatsaber-hook/shared/utils/typedefs.h" // Including type: System.Collections.Hashtable/System.Collections.SyncHashtable #include "System/Collections/Hashtable_SyncHashtable.hpp" // Including type: System.Collections.IEnumerator #include "System/Collections/IEnumerator.hpp" // Including type: System.Collections.ICollection #include "System/Collections/ICollection.hpp" // Including type: System.Runtime.Serialization.SerializationInfo #include "System/Runtime/Serialization/SerializationInfo.hpp" // Including type: System.Array #include "System/Array.hpp" // Including type: System.Collections.IDictionaryEnumerator #include "System/Collections/IDictionaryEnumerator.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils.hpp" #include "beatsaber-hook/shared/utils/utils.h" // Completed includes // Autogenerated instance field getter // Get instance field: protected System.Collections.Hashtable _table [[deprecated("Use field access instead!")]] ::System::Collections::Hashtable*& System::Collections::Hashtable::SyncHashtable::dyn__table() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::Hashtable::SyncHashtable::dyn__table"); auto ___internal__instance = this; static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "_table"))->offset; return *reinterpret_cast<::System::Collections::Hashtable**>(reinterpret_cast<char*>(this) + ___internal__field__offset); } // Autogenerated method: System.Collections.Hashtable/System.Collections.SyncHashtable.System.Collections.IEnumerable.GetEnumerator ::System::Collections::IEnumerator* System::Collections::Hashtable::SyncHashtable::System_Collections_IEnumerable_GetEnumerator() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::Hashtable::SyncHashtable::System.Collections.IEnumerable.GetEnumerator"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::Hashtable::SyncHashtable*), 13)); return ::il2cpp_utils::RunMethodRethrow<::System::Collections::IEnumerator*, false>(this, ___internal__method); } // Autogenerated method: System.Collections.Hashtable/System.Collections.SyncHashtable.get_Count int System::Collections::Hashtable::SyncHashtable::get_Count() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::Hashtable::SyncHashtable::get_Count"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::Hashtable*), 32)); return ::il2cpp_utils::RunMethodRethrow<int, false>(this, ___internal__method); } // Autogenerated method: System.Collections.Hashtable/System.Collections.SyncHashtable.get_Item ::Il2CppObject* System::Collections::Hashtable::SyncHashtable::get_Item(::Il2CppObject* key) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::Hashtable::SyncHashtable::get_Item"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::Hashtable*), 23)); return ::il2cpp_utils::RunMethodRethrow<::Il2CppObject*, false>(this, ___internal__method, key); } // Autogenerated method: System.Collections.Hashtable/System.Collections.SyncHashtable.set_Item void System::Collections::Hashtable::SyncHashtable::set_Item(::Il2CppObject* key, ::Il2CppObject* value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::Hashtable::SyncHashtable::set_Item"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::Hashtable*), 24)); ::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, key, value); } // Autogenerated method: System.Collections.Hashtable/System.Collections.SyncHashtable.get_SyncRoot ::Il2CppObject* System::Collections::Hashtable::SyncHashtable::get_SyncRoot() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::Hashtable::SyncHashtable::get_SyncRoot"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::Hashtable*), 31)); return ::il2cpp_utils::RunMethodRethrow<::Il2CppObject*, false>(this, ___internal__method); } // Autogenerated method: System.Collections.Hashtable/System.Collections.SyncHashtable.get_Keys ::System::Collections::ICollection* System::Collections::Hashtable::SyncHashtable::get_Keys() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::Hashtable::SyncHashtable::get_Keys"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::Hashtable*), 28)); return ::il2cpp_utils::RunMethodRethrow<::System::Collections::ICollection*, false>(this, ___internal__method); } // Autogenerated method: System.Collections.Hashtable/System.Collections.SyncHashtable.get_Values ::System::Collections::ICollection* System::Collections::Hashtable::SyncHashtable::get_Values() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::Hashtable::SyncHashtable::get_Values"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::Hashtable*), 29)); return ::il2cpp_utils::RunMethodRethrow<::System::Collections::ICollection*, false>(this, ___internal__method); } // Autogenerated method: System.Collections.Hashtable/System.Collections.SyncHashtable.GetObjectData void System::Collections::Hashtable::SyncHashtable::GetObjectData(::System::Runtime::Serialization::SerializationInfo* info, ::System::Runtime::Serialization::StreamingContext context) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::Hashtable::SyncHashtable::GetObjectData"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::Hashtable*), 33)); ::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, info, context); } // Autogenerated method: System.Collections.Hashtable/System.Collections.SyncHashtable.Add void System::Collections::Hashtable::SyncHashtable::Add(::Il2CppObject* key, ::Il2CppObject* value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::Hashtable::SyncHashtable::Add"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::Hashtable*), 17)); ::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, key, value); } // Autogenerated method: System.Collections.Hashtable/System.Collections.SyncHashtable.Clear void System::Collections::Hashtable::SyncHashtable::Clear() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::Hashtable::SyncHashtable::Clear"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::Hashtable*), 18)); ::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method); } // Autogenerated method: System.Collections.Hashtable/System.Collections.SyncHashtable.Contains bool System::Collections::Hashtable::SyncHashtable::Contains(::Il2CppObject* key) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::Hashtable::SyncHashtable::Contains"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::Hashtable*), 20)); return ::il2cpp_utils::RunMethodRethrow<bool, false>(this, ___internal__method, key); } // Autogenerated method: System.Collections.Hashtable/System.Collections.SyncHashtable.ContainsKey bool System::Collections::Hashtable::SyncHashtable::ContainsKey(::Il2CppObject* key) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::Hashtable::SyncHashtable::ContainsKey"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::Hashtable*), 21)); return ::il2cpp_utils::RunMethodRethrow<bool, false>(this, ___internal__method, key); } // Autogenerated method: System.Collections.Hashtable/System.Collections.SyncHashtable.CopyTo void System::Collections::Hashtable::SyncHashtable::CopyTo(::System::Array* array, int arrayIndex) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::Hashtable::SyncHashtable::CopyTo"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::Hashtable*), 22)); ::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, array, arrayIndex); } // Autogenerated method: System.Collections.Hashtable/System.Collections.SyncHashtable.Clone ::Il2CppObject* System::Collections::Hashtable::SyncHashtable::Clone() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::Hashtable::SyncHashtable::Clone"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::Hashtable*), 19)); return ::il2cpp_utils::RunMethodRethrow<::Il2CppObject*, false>(this, ___internal__method); } // Autogenerated method: System.Collections.Hashtable/System.Collections.SyncHashtable.GetEnumerator ::System::Collections::IDictionaryEnumerator* System::Collections::Hashtable::SyncHashtable::GetEnumerator() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::Hashtable::SyncHashtable::GetEnumerator"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::Hashtable*), 25)); return ::il2cpp_utils::RunMethodRethrow<::System::Collections::IDictionaryEnumerator*, false>(this, ___internal__method); } // Autogenerated method: System.Collections.Hashtable/System.Collections.SyncHashtable.Remove void System::Collections::Hashtable::SyncHashtable::Remove(::Il2CppObject* key) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::Hashtable::SyncHashtable::Remove"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::Hashtable*), 30)); ::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, key); } // Autogenerated method: System.Collections.Hashtable/System.Collections.SyncHashtable.OnDeserialization void System::Collections::Hashtable::SyncHashtable::OnDeserialization(::Il2CppObject* sender) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::Hashtable::SyncHashtable::OnDeserialization"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::Hashtable*), 34)); ::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, sender); } // Autogenerated from CppSourceCreator // Created by Sc2ad // ========================================================================= // Begin includes #include "beatsaber-hook/shared/utils/typedefs.h" // Including type: System.Collections.Hashtable/System.Collections.HashtableEnumerator #include "System/Collections/Hashtable_HashtableEnumerator.hpp" // Including type: System.Collections.DictionaryEntry #include "System/Collections/DictionaryEntry.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils.hpp" #include "beatsaber-hook/shared/utils/utils.h" // Completed includes // Autogenerated instance field getter // Get instance field: private System.Collections.Hashtable hashtable [[deprecated("Use field access instead!")]] ::System::Collections::Hashtable*& System::Collections::Hashtable::HashtableEnumerator::dyn_hashtable() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::Hashtable::HashtableEnumerator::dyn_hashtable"); auto ___internal__instance = this; static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "hashtable"))->offset; return *reinterpret_cast<::System::Collections::Hashtable**>(reinterpret_cast<char*>(this) + ___internal__field__offset); } // Autogenerated instance field getter // Get instance field: private System.Int32 bucket [[deprecated("Use field access instead!")]] int& System::Collections::Hashtable::HashtableEnumerator::dyn_bucket() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::Hashtable::HashtableEnumerator::dyn_bucket"); auto ___internal__instance = this; static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "bucket"))->offset; return *reinterpret_cast<int*>(reinterpret_cast<char*>(this) + ___internal__field__offset); } // Autogenerated instance field getter // Get instance field: private System.Int32 version [[deprecated("Use field access instead!")]] int& System::Collections::Hashtable::HashtableEnumerator::dyn_version() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::Hashtable::HashtableEnumerator::dyn_version"); auto ___internal__instance = this; static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "version"))->offset; return *reinterpret_cast<int*>(reinterpret_cast<char*>(this) + ___internal__field__offset); } // Autogenerated instance field getter // Get instance field: private System.Boolean current [[deprecated("Use field access instead!")]] bool& System::Collections::Hashtable::HashtableEnumerator::dyn_current() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::Hashtable::HashtableEnumerator::dyn_current"); auto ___internal__instance = this; static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "current"))->offset; return *reinterpret_cast<bool*>(reinterpret_cast<char*>(this) + ___internal__field__offset); } // Autogenerated instance field getter // Get instance field: private System.Int32 getObjectRetType [[deprecated("Use field access instead!")]] int& System::Collections::Hashtable::HashtableEnumerator::dyn_getObjectRetType() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::Hashtable::HashtableEnumerator::dyn_getObjectRetType"); auto ___internal__instance = this; static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "getObjectRetType"))->offset; return *reinterpret_cast<int*>(reinterpret_cast<char*>(this) + ___internal__field__offset); } // Autogenerated instance field getter // Get instance field: private System.Object currentKey [[deprecated("Use field access instead!")]] ::Il2CppObject*& System::Collections::Hashtable::HashtableEnumerator::dyn_currentKey() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::Hashtable::HashtableEnumerator::dyn_currentKey"); auto ___internal__instance = this; static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "currentKey"))->offset; return *reinterpret_cast<::Il2CppObject**>(reinterpret_cast<char*>(this) + ___internal__field__offset); } // Autogenerated instance field getter // Get instance field: private System.Object currentValue [[deprecated("Use field access instead!")]] ::Il2CppObject*& System::Collections::Hashtable::HashtableEnumerator::dyn_currentValue() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::Hashtable::HashtableEnumerator::dyn_currentValue"); auto ___internal__instance = this; static auto ___internal__field__offset = THROW_UNLESS(il2cpp_utils::FindField(___internal__instance, "currentValue"))->offset; return *reinterpret_cast<::Il2CppObject**>(reinterpret_cast<char*>(this) + ___internal__field__offset); } // Autogenerated method: System.Collections.Hashtable/System.Collections.HashtableEnumerator.get_Key ::Il2CppObject* System::Collections::Hashtable::HashtableEnumerator::get_Key() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::Hashtable::HashtableEnumerator::get_Key"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::Hashtable::HashtableEnumerator*), 11)); return ::il2cpp_utils::RunMethodRethrow<::Il2CppObject*, false>(this, ___internal__method); } // Autogenerated method: System.Collections.Hashtable/System.Collections.HashtableEnumerator.get_Entry ::System::Collections::DictionaryEntry System::Collections::Hashtable::HashtableEnumerator::get_Entry() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::Hashtable::HashtableEnumerator::get_Entry"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::Hashtable::HashtableEnumerator*), 13)); return ::il2cpp_utils::RunMethodRethrow<::System::Collections::DictionaryEntry, false>(this, ___internal__method); } // Autogenerated method: System.Collections.Hashtable/System.Collections.HashtableEnumerator.get_Current ::Il2CppObject* System::Collections::Hashtable::HashtableEnumerator::get_Current() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::Hashtable::HashtableEnumerator::get_Current"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::Hashtable::HashtableEnumerator*), 14)); return ::il2cpp_utils::RunMethodRethrow<::Il2CppObject*, false>(this, ___internal__method); } // Autogenerated method: System.Collections.Hashtable/System.Collections.HashtableEnumerator.get_Value ::Il2CppObject* System::Collections::Hashtable::HashtableEnumerator::get_Value() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::Hashtable::HashtableEnumerator::get_Value"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::Hashtable::HashtableEnumerator*), 15)); return ::il2cpp_utils::RunMethodRethrow<::Il2CppObject*, false>(this, ___internal__method); } // Autogenerated method: System.Collections.Hashtable/System.Collections.HashtableEnumerator.Clone ::Il2CppObject* System::Collections::Hashtable::HashtableEnumerator::Clone() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::Hashtable::HashtableEnumerator::Clone"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::Hashtable::HashtableEnumerator*), 10)); return ::il2cpp_utils::RunMethodRethrow<::Il2CppObject*, false>(this, ___internal__method); } // Autogenerated method: System.Collections.Hashtable/System.Collections.HashtableEnumerator.MoveNext bool System::Collections::Hashtable::HashtableEnumerator::MoveNext() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::Hashtable::HashtableEnumerator::MoveNext"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::Hashtable::HashtableEnumerator*), 12)); return ::il2cpp_utils::RunMethodRethrow<bool, false>(this, ___internal__method); } // Autogenerated method: System.Collections.Hashtable/System.Collections.HashtableEnumerator.Reset void System::Collections::Hashtable::HashtableEnumerator::Reset() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::Hashtable::HashtableEnumerator::Reset"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::Hashtable::HashtableEnumerator*), 16)); ::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method); } // Autogenerated from CppSourceCreator // Created by Sc2ad // ========================================================================= // Begin includes #include "beatsaber-hook/shared/utils/typedefs.h" // Including type: System.Collections.HashHelpers #include "System/Collections/HashHelpers.hpp" // Including type: System.Runtime.CompilerServices.ConditionalWeakTable`2 #include "System/Runtime/CompilerServices/ConditionalWeakTable_2.hpp" // Including type: System.Runtime.Serialization.SerializationInfo #include "System/Runtime/Serialization/SerializationInfo.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils.hpp" #include "beatsaber-hook/shared/utils/utils.h" // Completed includes // Autogenerated static field getter // Get static field: static public readonly System.Int32[] primes ::ArrayW<int> System::Collections::HashHelpers::_get_primes() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::HashHelpers::_get_primes"); return THROW_UNLESS(il2cpp_utils::GetFieldValue<::ArrayW<int>>("System.Collections", "HashHelpers", "primes")); } // Autogenerated static field setter // Set static field: static public readonly System.Int32[] primes void System::Collections::HashHelpers::_set_primes(::ArrayW<int> value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::HashHelpers::_set_primes"); THROW_UNLESS(il2cpp_utils::SetFieldValue("System.Collections", "HashHelpers", "primes", value)); } // Autogenerated static field getter // Get static field: static private System.Runtime.CompilerServices.ConditionalWeakTable`2<System.Object,System.Runtime.Serialization.SerializationInfo> s_SerializationInfoTable ::System::Runtime::CompilerServices::ConditionalWeakTable_2<::Il2CppObject*, ::System::Runtime::Serialization::SerializationInfo*>* System::Collections::HashHelpers::_get_s_SerializationInfoTable() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::HashHelpers::_get_s_SerializationInfoTable"); return THROW_UNLESS((il2cpp_utils::GetFieldValue<::System::Runtime::CompilerServices::ConditionalWeakTable_2<::Il2CppObject*, ::System::Runtime::Serialization::SerializationInfo*>*>("System.Collections", "HashHelpers", "s_SerializationInfoTable"))); } // Autogenerated static field setter // Set static field: static private System.Runtime.CompilerServices.ConditionalWeakTable`2<System.Object,System.Runtime.Serialization.SerializationInfo> s_SerializationInfoTable void System::Collections::HashHelpers::_set_s_SerializationInfoTable(::System::Runtime::CompilerServices::ConditionalWeakTable_2<::Il2CppObject*, ::System::Runtime::Serialization::SerializationInfo*>* value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::HashHelpers::_set_s_SerializationInfoTable"); THROW_UNLESS(il2cpp_utils::SetFieldValue("System.Collections", "HashHelpers", "s_SerializationInfoTable", value)); } // Autogenerated method: System.Collections.HashHelpers.get_SerializationInfoTable ::System::Runtime::CompilerServices::ConditionalWeakTable_2<::Il2CppObject*, ::System::Runtime::Serialization::SerializationInfo*>* System::Collections::HashHelpers::get_SerializationInfoTable() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::HashHelpers::get_SerializationInfoTable"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Collections", "HashHelpers", "get_SerializationInfoTable", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); return ::il2cpp_utils::RunMethodRethrow<::System::Runtime::CompilerServices::ConditionalWeakTable_2<::Il2CppObject*, ::System::Runtime::Serialization::SerializationInfo*>*, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method); } // Autogenerated method: System.Collections.HashHelpers..cctor void System::Collections::HashHelpers::_cctor() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::HashHelpers::.cctor"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Collections", "HashHelpers", ".cctor", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{}))); ::il2cpp_utils::RunMethodRethrow<void, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method); } // Autogenerated method: System.Collections.HashHelpers.IsPrime bool System::Collections::HashHelpers::IsPrime(int candidate) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::HashHelpers::IsPrime"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Collections", "HashHelpers", "IsPrime", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(candidate)}))); return ::il2cpp_utils::RunMethodRethrow<bool, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method, candidate); } // Autogenerated method: System.Collections.HashHelpers.GetPrime int System::Collections::HashHelpers::GetPrime(int min) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::HashHelpers::GetPrime"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Collections", "HashHelpers", "GetPrime", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(min)}))); return ::il2cpp_utils::RunMethodRethrow<int, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method, min); } // Autogenerated method: System.Collections.HashHelpers.ExpandPrime int System::Collections::HashHelpers::ExpandPrime(int oldSize) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::HashHelpers::ExpandPrime"); static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod("System.Collections", "HashHelpers", "ExpandPrime", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(oldSize)}))); return ::il2cpp_utils::RunMethodRethrow<int, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method, oldSize); } // Autogenerated from CppSourceCreator // Created by Sc2ad // ========================================================================= // Begin includes #include "beatsaber-hook/shared/utils/typedefs.h" // Including type: System.Collections.ICollection #include "System/Collections/ICollection.hpp" // Including type: System.Array #include "System/Array.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils.hpp" #include "beatsaber-hook/shared/utils/utils.h" // Completed includes // Autogenerated method: System.Collections.ICollection.get_Count int System::Collections::ICollection::get_Count() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::ICollection::get_Count"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::ICollection*), -1)); return ::il2cpp_utils::RunMethodRethrow<int, false>(this, ___internal__method); } // Autogenerated method: System.Collections.ICollection.get_SyncRoot ::Il2CppObject* System::Collections::ICollection::get_SyncRoot() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::ICollection::get_SyncRoot"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::ICollection*), -1)); return ::il2cpp_utils::RunMethodRethrow<::Il2CppObject*, false>(this, ___internal__method); } // Autogenerated method: System.Collections.ICollection.CopyTo void System::Collections::ICollection::CopyTo(::System::Array* array, int index) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::ICollection::CopyTo"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::ICollection*), -1)); ::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, array, index); } // Autogenerated from CppSourceCreator // Created by Sc2ad // ========================================================================= // Begin includes #include "beatsaber-hook/shared/utils/typedefs.h" // Including type: System.Collections.IComparer #include "System/Collections/IComparer.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils.hpp" #include "beatsaber-hook/shared/utils/utils.h" // Completed includes // Autogenerated method: System.Collections.IComparer.Compare int System::Collections::IComparer::Compare(::Il2CppObject* x, ::Il2CppObject* y) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::IComparer::Compare"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::IComparer*), -1)); return ::il2cpp_utils::RunMethodRethrow<int, false>(this, ___internal__method, x, y); } // Autogenerated from CppSourceCreator // Created by Sc2ad // ========================================================================= // Begin includes #include "beatsaber-hook/shared/utils/typedefs.h" // Including type: System.Collections.IDictionary #include "System/Collections/IDictionary.hpp" // Including type: System.Collections.IDictionaryEnumerator #include "System/Collections/IDictionaryEnumerator.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils.hpp" #include "beatsaber-hook/shared/utils/utils.h" // Completed includes // Autogenerated method: System.Collections.IDictionary.get_Item ::Il2CppObject* System::Collections::IDictionary::get_Item(::Il2CppObject* key) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::IDictionary::get_Item"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::IDictionary*), -1)); return ::il2cpp_utils::RunMethodRethrow<::Il2CppObject*, false>(this, ___internal__method, key); } // Autogenerated method: System.Collections.IDictionary.set_Item void System::Collections::IDictionary::set_Item(::Il2CppObject* key, ::Il2CppObject* value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::IDictionary::set_Item"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::IDictionary*), -1)); ::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, key, value); } // Autogenerated method: System.Collections.IDictionary.get_Keys ::System::Collections::ICollection* System::Collections::IDictionary::get_Keys() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::IDictionary::get_Keys"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::IDictionary*), -1)); return ::il2cpp_utils::RunMethodRethrow<::System::Collections::ICollection*, false>(this, ___internal__method); } // Autogenerated method: System.Collections.IDictionary.Contains bool System::Collections::IDictionary::Contains(::Il2CppObject* key) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::IDictionary::Contains"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::IDictionary*), -1)); return ::il2cpp_utils::RunMethodRethrow<bool, false>(this, ___internal__method, key); } // Autogenerated method: System.Collections.IDictionary.GetEnumerator ::System::Collections::IDictionaryEnumerator* System::Collections::IDictionary::GetEnumerator() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::IDictionary::GetEnumerator"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::IDictionary*), -1)); return ::il2cpp_utils::RunMethodRethrow<::System::Collections::IDictionaryEnumerator*, false>(this, ___internal__method); } // Autogenerated method: System.Collections.IDictionary.Remove void System::Collections::IDictionary::Remove(::Il2CppObject* key) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::IDictionary::Remove"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::IDictionary*), -1)); ::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, key); } // Autogenerated from CppSourceCreator // Created by Sc2ad // ========================================================================= // Begin includes #include "beatsaber-hook/shared/utils/typedefs.h" // Including type: System.Collections.IDictionaryEnumerator #include "System/Collections/IDictionaryEnumerator.hpp" // Including type: System.Collections.DictionaryEntry #include "System/Collections/DictionaryEntry.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils.hpp" #include "beatsaber-hook/shared/utils/utils.h" // Completed includes // Autogenerated method: System.Collections.IDictionaryEnumerator.get_Key ::Il2CppObject* System::Collections::IDictionaryEnumerator::get_Key() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::IDictionaryEnumerator::get_Key"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::IDictionaryEnumerator*), -1)); return ::il2cpp_utils::RunMethodRethrow<::Il2CppObject*, false>(this, ___internal__method); } // Autogenerated method: System.Collections.IDictionaryEnumerator.get_Value ::Il2CppObject* System::Collections::IDictionaryEnumerator::get_Value() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::IDictionaryEnumerator::get_Value"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::IDictionaryEnumerator*), -1)); return ::il2cpp_utils::RunMethodRethrow<::Il2CppObject*, false>(this, ___internal__method); } // Autogenerated method: System.Collections.IDictionaryEnumerator.get_Entry ::System::Collections::DictionaryEntry System::Collections::IDictionaryEnumerator::get_Entry() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::IDictionaryEnumerator::get_Entry"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::IDictionaryEnumerator*), -1)); return ::il2cpp_utils::RunMethodRethrow<::System::Collections::DictionaryEntry, false>(this, ___internal__method); } // Autogenerated from CppSourceCreator // Created by Sc2ad // ========================================================================= // Begin includes // Including type: System.Collections.IEnumerable #include "System/Collections/IEnumerable.hpp" // Including type: System.Collections.IEnumerator #include "System/Collections/IEnumerator.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils.hpp" #include "beatsaber-hook/shared/utils/utils.h" // Completed includes // Autogenerated method: System.Collections.IEnumerable.GetEnumerator ::System::Collections::IEnumerator* System::Collections::IEnumerable::GetEnumerator() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::IEnumerable::GetEnumerator"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::IEnumerable*), -1)); return ::il2cpp_utils::RunMethodRethrow<::System::Collections::IEnumerator*, false>(this, ___internal__method); } // Autogenerated from CppSourceCreator // Created by Sc2ad // ========================================================================= // Begin includes #include "beatsaber-hook/shared/utils/typedefs.h" // Including type: System.Collections.IEnumerator #include "System/Collections/IEnumerator.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils.hpp" #include "beatsaber-hook/shared/utils/utils.h" // Completed includes // Autogenerated method: System.Collections.IEnumerator.get_Current ::Il2CppObject* System::Collections::IEnumerator::get_Current() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::IEnumerator::get_Current"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::IEnumerator*), -1)); return ::il2cpp_utils::RunMethodRethrow<::Il2CppObject*, false>(this, ___internal__method); } // Autogenerated method: System.Collections.IEnumerator.MoveNext bool System::Collections::IEnumerator::MoveNext() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::IEnumerator::MoveNext"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::IEnumerator*), -1)); return ::il2cpp_utils::RunMethodRethrow<bool, false>(this, ___internal__method); } // Autogenerated method: System.Collections.IEnumerator.Reset void System::Collections::IEnumerator::Reset() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::IEnumerator::Reset"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::IEnumerator*), -1)); ::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method); } // Autogenerated from CppSourceCreator // Created by Sc2ad // ========================================================================= // Begin includes #include "beatsaber-hook/shared/utils/typedefs.h" // Including type: System.Collections.IEqualityComparer #include "System/Collections/IEqualityComparer.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils.hpp" #include "beatsaber-hook/shared/utils/utils.h" // Completed includes // Autogenerated method: System.Collections.IEqualityComparer.Equals bool System::Collections::IEqualityComparer::Equals(::Il2CppObject* x, ::Il2CppObject* y) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::IEqualityComparer::Equals"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::IEqualityComparer*), -1)); return ::il2cpp_utils::RunMethodRethrow<bool, false>(this, ___internal__method, x, y); } // Autogenerated method: System.Collections.IEqualityComparer.GetHashCode int System::Collections::IEqualityComparer::GetHashCode(::Il2CppObject* obj) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::IEqualityComparer::GetHashCode"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::IEqualityComparer*), -1)); return ::il2cpp_utils::RunMethodRethrow<int, false>(this, ___internal__method, obj); } // Autogenerated from CppSourceCreator // Created by Sc2ad // ========================================================================= // Begin includes #include "beatsaber-hook/shared/utils/typedefs.h" // Including type: System.Collections.IHashCodeProvider #include "System/Collections/IHashCodeProvider.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils.hpp" #include "beatsaber-hook/shared/utils/utils.h" // Completed includes // Autogenerated method: System.Collections.IHashCodeProvider.GetHashCode int System::Collections::IHashCodeProvider::GetHashCode(::Il2CppObject* obj) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::IHashCodeProvider::GetHashCode"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::IHashCodeProvider*), -1)); return ::il2cpp_utils::RunMethodRethrow<int, false>(this, ___internal__method, obj); } // Autogenerated from CppSourceCreator // Created by Sc2ad // ========================================================================= // Begin includes #include "beatsaber-hook/shared/utils/typedefs.h" // Including type: System.Collections.IList #include "System/Collections/IList.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils.hpp" #include "beatsaber-hook/shared/utils/utils.h" // Completed includes // Autogenerated method: System.Collections.IList.get_Item ::Il2CppObject* System::Collections::IList::get_Item(int index) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::IList::get_Item"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::IList*), -1)); return ::il2cpp_utils::RunMethodRethrow<::Il2CppObject*, false>(this, ___internal__method, index); } // Autogenerated method: System.Collections.IList.set_Item void System::Collections::IList::set_Item(int index, ::Il2CppObject* value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::IList::set_Item"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::IList*), -1)); ::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, index, value); } // Autogenerated method: System.Collections.IList.get_IsReadOnly bool System::Collections::IList::get_IsReadOnly() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::IList::get_IsReadOnly"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::IList*), -1)); return ::il2cpp_utils::RunMethodRethrow<bool, false>(this, ___internal__method); } // Autogenerated method: System.Collections.IList.get_IsFixedSize bool System::Collections::IList::get_IsFixedSize() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::IList::get_IsFixedSize"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::IList*), -1)); return ::il2cpp_utils::RunMethodRethrow<bool, false>(this, ___internal__method); } // Autogenerated method: System.Collections.IList.Add int System::Collections::IList::Add(::Il2CppObject* value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::IList::Add"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::IList*), -1)); return ::il2cpp_utils::RunMethodRethrow<int, false>(this, ___internal__method, value); } // Autogenerated method: System.Collections.IList.Contains bool System::Collections::IList::Contains(::Il2CppObject* value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::IList::Contains"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::IList*), -1)); return ::il2cpp_utils::RunMethodRethrow<bool, false>(this, ___internal__method, value); } // Autogenerated method: System.Collections.IList.Clear void System::Collections::IList::Clear() { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::IList::Clear"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::IList*), -1)); ::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method); } // Autogenerated method: System.Collections.IList.IndexOf int System::Collections::IList::IndexOf(::Il2CppObject* value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::IList::IndexOf"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::IList*), -1)); return ::il2cpp_utils::RunMethodRethrow<int, false>(this, ___internal__method, value); } // Autogenerated method: System.Collections.IList.Insert void System::Collections::IList::Insert(int index, ::Il2CppObject* value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::IList::Insert"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::IList*), -1)); ::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, index, value); } // Autogenerated method: System.Collections.IList.Remove void System::Collections::IList::Remove(::Il2CppObject* value) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::IList::Remove"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::IList*), -1)); ::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, value); } // Autogenerated method: System.Collections.IList.RemoveAt void System::Collections::IList::RemoveAt(int index) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Collections::IList::RemoveAt"); auto* ___internal__method = THROW_UNLESS(::il2cpp_utils::ResolveVtableSlot(this, classof(::System::Collections::IList*), -1)); ::il2cpp_utils::RunMethodRethrow<void, false>(this, ___internal__method, index); }
81.258333
368
0.781423
[ "object", "vector" ]
071c8a6076179ba92dc09486c2ada66b5a3bdc66
415
cpp
C++
src/engine/World.cpp
jjerome/Niski
58bcc1303cdb6676c051d55e9d7a248dfea65cde
[ "MIT" ]
1
2017-09-19T16:33:06.000Z
2017-09-19T16:33:06.000Z
src/engine/World.cpp
jjerome/Niski
58bcc1303cdb6676c051d55e9d7a248dfea65cde
[ "MIT" ]
null
null
null
src/engine/World.cpp
jjerome/Niski
58bcc1303cdb6676c051d55e9d7a248dfea65cde
[ "MIT" ]
null
null
null
#include "engine/World.h" using namespace Niski::Engine; World::World(Niski::Math::Rect2D& bounds) : Entity(nullptr, "gameWorld"), bounds_(bounds) {} World::~World(void) {} void World::setBounds(Niski::Math::Rect2D& bounds) { bounds_ = bounds; } Niski::Math::Rect2D World::getBounds(void) const { return bounds_; } void World::render(Niski::Renderer::Renderer& renderer) const { Entity::render(renderer); }
17.291667
89
0.713253
[ "render" ]
071f2e6e038999ff9795667708e7781d105114ad
10,959
cpp
C++
oldsrc/calcGammaOmega.cpp
ron2015schmitt/coildes
2583bc1beb6b5809ed75367970e4f32ba242894a
[ "MIT" ]
null
null
null
oldsrc/calcGammaOmega.cpp
ron2015schmitt/coildes
2583bc1beb6b5809ed75367970e4f32ba242894a
[ "MIT" ]
null
null
null
oldsrc/calcGammaOmega.cpp
ron2015schmitt/coildes
2583bc1beb6b5809ed75367970e4f32ba242894a
[ "MIT" ]
null
null
null
/************************************************************************* * * File Name : * Platform : gnu C++ compiler * Author : Ron Schmitt * Date : * * * SYNOPSIS * Stellarator COIL Design * This file finds the coil current from given plasma surface flux * * * VERSION NOTES: * **************************************************************************/ // Standard C libraries #include <cstdio> #include <cstring> #include <cstdlib> #include <cmath> // Standard C++ libraries #include <iostream> #include <complex> using namespace std; // coil libraries #include "coils.hpp" #include "coilio.hpp" #include "coils_cmdline.hpp" #include "surface.hpp" #include "gammamatrix.hpp" #include "omegamatrix.hpp" #include "gradfvector.hpp" #include "coilfft.hpp" // This is the file that defines the B field configuration // Main Function for code int main (int argc, char *argv[]) { disable_all_options(); enable_option(opt_pf); enable_option(opt_Nphi); enable_option(opt_Ntheta); enable_option(opt_Nnn); enable_option(opt_Nmm); enable_option(opt_Btf); enable_option(opt_Bpf); enable_option(opt_Nharm); enable_option(opt_Mharm); enable_option(opt_omegaf); enable_option(opt_gammaf); // parse command line input if (!parse_cmd(argc, argv)) return 1; // // ios_base::fmtflags flags = ios_base::right | ios_base::scientific; string fext = "txt"; string ftemp; p3vectorformat::textformat(text_nobraces); Vector <double> datavec("datavec"); datavec.perline(1); datavec.textformat(text_nobraces); Matrix <double> data("data"); data.perline(1); data.textformat(text_nobraces); string fname; // variables for measuring times struct tms tbuff; clock_t ckstart; // display Matricks mode cout << endl; display_execution_mode(); cout << endl; // Create angle grid const unsigned int Npts = Ntheta*Nphi; Vector<double> thetas(Npts,"thetas"); Vector<double> phis(Npts,"phis"); anglevectors(thetas, phis, Ntheta, Nphi); ostringstream strmtmp1; strmtmp1 <<Nnn; string Nnn_str(strmtmp1.str()); ostringstream strmtmp2; strmtmp2 <<Nmm; string Nmm_str(strmtmp2.str()); // Create Fourier Mode vectors Vector<double> nn("nn"); Vector<double> mm("mm"); unsigned int NF; bool mode00 = true; if ( (Nharm >1) ||(Mharm>1) ) modevectors(NF,nn,mm,Nnn,Nmm,Nharm,Mharm,mode00); else modevectors(NF,nn,mm,Nnn,Nmm,mode00); // these exclude the n=0,m=0 case Vector<double> nnR("nnR"); Vector<double> mmR("mmR"); unsigned int NFR; mode00 = false; if ( (Nharm >1) ||(Mharm>1) ) modevectors(NFR,nnR,mmR,Nnn,Nmm,Nharm,Mharm,mode00); else modevectors(NFR,nnR,mmR,Nnn,Nmm,mode00); // coefficient C is the integration coef for the fourier transform // C = dtheta*dphi // = (2*pi/Ntheta)*(2*pi/Nphi) // = (2*pi*2*pi/Npts) const double C = (2*PI*2*PI/double(Npts)); const double Csqr = C*C; // Create ortho normal series cout << endl; cout<<"$ Generate orthonormal series matrix ("<<Npts<<" x "<<NF<<")"<<endl; STARTTIME(tbuff,ckstart); Matrix<complex<double> > fs(Npts,NF,"fs"); fseries(nn,mm,thetas,phis,fs); STOPTIME(tbuff,ckstart); cout << endl; cout<<"$ Generate reduced orthonormal series matrix ("<<Npts<<" x "<<NFR<<")"<<endl; STARTTIME(tbuff,ckstart); Matrix<complex<double> > fsR(Npts,NFR,"fsR"); fseries(nnR,mmR,thetas,phis,fsR); STOPTIME(tbuff,ckstart); // load the plasma surface fourier coef's cout << "$ Loading PLASMA SURFACE fourier coefficients from " << plasma_filename << endl; FourierSurface plasmafourier; if (load_fourier_surface(plasma_filename,plasmafourier)) return 1; plasmafourier.RF().name("p.RF"); plasmafourier.ZF().name("p.ZF"); // print coef's // printfouriercoefs(plasmafourier.nn(),plasmafourier.mm(),plasmafourier.RF(),plasmafourier.ZF(),10,18); // lay plasma surface onto grid Vector<p3vector<double> > X(Npts, "X"); Vector<p3vector<double> > dA_dtdp(Npts, "dA_dtdp"); Vector<p3vector<double> > dx_dr(Npts, "dx_dr"); Vector<p3vector<double> > dx_dtheta(Npts,"dx_dtheta"); Vector<p3vector<double> > dx_dphi(Npts,"dx_dphi"); Vector<p3vector<double> > grad_r(Npts,"grad_r"); Vector<p3vector<double> > grad_theta(Npts,"grad_theta"); Vector<p3vector<double> > grad_phi(Npts,"grad_phi"); cout << endl; cout <<"$ Mapping plasma surface fourier coefficients to "<<Ntheta<<" x "<<Nphi<<" (theta by phi) grid"<<endl; STARTTIME(tbuff,ckstart); expandsurfaceandbases(X,dA_dtdp,dx_dr,dx_dtheta,dx_dphi,grad_r,grad_theta,grad_phi,plasmafourier,thetas,phis); STOPTIME(tbuff,ckstart); // Create Gamma Matrix Matrix<complex<double> > Gamma("Gamma"); // if gamma filename given, then load gamma (SVD form) from files if (!gamma_filename.empty()) { cout << endl; cout<<"$ Load Gamma matrix ("<<NFR<<"x"<<(2*NF)<<")"; cout << " from "<< gamma_filename <<".R.out"; cout << " and "<< gamma_filename <<".R.out"; cout<<endl; STARTTIME(tbuff,ckstart); data.perline(1); data.textformat(text_nobraces); data.resize(NFR,2*NF); fname = gamma_filename + ".R.out"; load(data,fname); Matrix <double> data2("data2"); data2.perline(1); data2.textformat(text_nobraces); data2.resize(NFR,2*NF); fname = gamma_filename + ".I.out"; load(data2,fname); Gamma = mcomplex(data,data2); data.clear(); data2.clear(); STOPTIME(tbuff,ckstart); /////////////////////////////////////////////////////// // ********DEBUG************************* // save Gamma printcr("$ Saving Gamma Matrix"); data.resize() = real(Gamma); fname = "gamma.Nn="+Nnn_str+".Nm="+Nmm_str+".R.debug.out"; dispcr(fname); save(data,fname); data.resize() = imag(Gamma); fname = "gamma.Nn="+Nnn_str+".Nm="+Nmm_str+".I.debug.out"; dispcr(fname); save(data,fname); ////////////////////////////////////////////////////// } else { // Calculate Gamma matrix cout << endl; cout<<"$ Generate Gamma matrix "<<endl; STARTTIME(tbuff,ckstart); fullgammamatrix(Gamma,nn,mm,fs,fsR,dA_dtdp,thetas,phis,Ntheta,Nphi); const unsigned int Ns = Gamma.Ncols(); dispcr(Gamma.Nrows()); dispcr(Gamma.Ncols()); dispcr(NFR); dispcr(Ns); STOPTIME(tbuff,ckstart); // save Gamma printcr("$ Saving Gamma Matrix"); data.resize() = real(Gamma); fname = "gamma.Nn="+Nnn_str+".Nm="+Nmm_str+".R.out"; dispcr(fname); save(data,fname); data.resize() = imag(Gamma); fname = "gamma.Nn="+Nnn_str+".Nm="+Nmm_str+".I.out"; dispcr(fname); save(data,fname); } Matrix<complex<double> > Omega(NFR,NFR,"Omega"); // if omega filename given, then load omega (SVD form) from files if (!omega_filename.empty()) { cout << endl; cout<<"$ Load Omega matrix ("<<NFR<<"x"<<NFR<<")"; cout << " from "<< omega_filename <<".R.out"; cout << " and "<< omega_filename <<".R.out"; cout<<endl; STARTTIME(tbuff,ckstart); data.perline(1); data.textformat(text_nobraces); data.resize(NFR,NFR); fname = omega_filename + ".R.out"; load(data,fname); Matrix <double> data2("data2"); data2.perline(1); data2.textformat(text_nobraces); data2.resize(NFR,NFR); fname = omega_filename + ".I.out"; load(data2,fname); Omega = mcomplex(data,data2); data.clear(); data2.clear(); STOPTIME(tbuff,ckstart); /////////////////////////////////////////////////////// // ********DEBUG************************* // save Omega printcr("$ Saving Omega Matrix"); data.resize() = real(Omega); fname = "omega.Nn="+Nnn_str+".Nm="+Nmm_str+".R.debug.out"; dispcr(fname); save(data,fname); data.resize() = imag(Omega); fname = "omega.Nn="+Nnn_str+".Nm="+Nmm_str+".I.debug.out"; dispcr(fname); save(data,fname); ////////////////////////////////////////////////////// } else { // Calculate Omega matrix // first we need to load B field cout << endl; cout<<"$ Load tangent B field "<<endl; STARTTIME(tbuff,ckstart); cout <<endl<< "$ Loading BTOTAL_theta fourier coefficients from " << Bt_filename << endl; cout <<endl<< "$ Loading BTOTAL_phi fourier coefficients from " << Bp_filename << endl; Vector<complex<double> > BtF(NF,"BtF"); if (load_coefs( Bt_filename,CoefFileFormat_sincos,nn,mm,BtF)) return 5; Vector<complex<double> > BpF(NF,"BpF"); if (load_coefs( Bp_filename,CoefFileFormat_sincos,nn,mm,BpF)) return 6; Vector<double> Bt(Npts, "Bt"); expandfunction(Bt,BtF,fs); Vector<double> Bp(Npts, "Bp"); expandfunction(Bp,BpF,fs); Vector<p3vector<double> > B(Npts, "B"); for (unsigned int j =0; j<Npts; j++) B[j] = Bt[j] * dx_dtheta[j] + Bp[j] * dx_dphi[j]; STOPTIME(tbuff,ckstart); cout << endl; cout<<"$ Calculate Omega matrix ("<<NFR<<"x"<<NFR<<")"<<endl; STARTTIME(tbuff,ckstart); Matrix<p3vector<complex<double> > > grad_fsR(Npts,NFR,"grad_fsR"); gradfvector(thetas,phis,mmR,nnR,grad_theta,grad_phi,grad_fsR); // omegamatrix(Omega,B,grad_fsR,f_delta,dx_dr,dx_dtheta,dx_dphi,grad_r,grad_theta,grad_phi); omegamatrix(Omega,B,grad_fsR,fsR,dx_dr,dx_dtheta,dx_dphi,grad_r,grad_theta,grad_phi); STOPTIME(tbuff,ckstart); } // save Omega printcr("$ Saving Omega Matrix"); data.resize() = real(Omega); fname = "omega.Nn="+Nnn_str+".Nm="+Nmm_str+".R.out"; dispcr(fname); save(data,fname); data.resize() = imag(Omega); fname = "omega.Nn="+Nnn_str+".Nm="+Nmm_str+".I.out"; dispcr(fname); save(data,fname); // clear some variables fsR.clear(); fs.clear(); // note that Gamma seems to always be real and Omega seems to always be imaginary. // using this symmetry would greatly reduce computation cout << endl; cout<<"$ Calculate (Omega|Gamma) matrix ("<<NFR<<"x"<<(2*NF)<<")"<<endl; STARTTIME(tbuff,ckstart); Matrix<complex<double> > OG(NFR,(2*NF),"OG"); OG=(Omega|Gamma); STOPTIME(tbuff,ckstart); // save OmegaGamma printcr("$ Saving OmegaGamma Matrix"); data.resize() = real(OG); fname = "omegagamma.Nn="+Nnn_str+".Nm="+Nmm_str+".R.out"; dispcr(fname); save(data,fname); data.resize() = imag(OG); fname = "omegagamma.Nn="+Nnn_str+".Nm="+Nmm_str+".I.out"; dispcr(fname); save(data,fname); return 0; } // main()
24.963554
113
0.591204
[ "vector", "transform" ]
0720813cd3e24e0e26e5c90cfcf6489dd8a09ae7
3,072
cpp
C++
compiler/luci/pass/src/RemoveUnnecessarySlicePass.cpp
chogba6/ONE
3d35259f89ee3109cfd35ab6f38c231904487f3b
[ "Apache-2.0" ]
255
2020-05-22T07:45:29.000Z
2022-03-29T23:58:22.000Z
compiler/luci/pass/src/RemoveUnnecessarySlicePass.cpp
chogba6/ONE
3d35259f89ee3109cfd35ab6f38c231904487f3b
[ "Apache-2.0" ]
5,102
2020-05-22T07:48:33.000Z
2022-03-31T23:43:39.000Z
compiler/luci/pass/src/RemoveUnnecessarySlicePass.cpp
chogba6/ONE
3d35259f89ee3109cfd35ab6f38c231904487f3b
[ "Apache-2.0" ]
120
2020-05-22T07:51:08.000Z
2022-02-16T19:08:05.000Z
/* * Copyright (c) 2020 Samsung Electronics Co., Ltd. All Rights Reserved * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "luci/Pass/RemoveUnnecessarySlicePass.h" #include <luci/IR/CircleNodes.h> namespace { /** * @brief Return value in CircleConst. * @details Return value in position on CircleConst with int64 format. * Begin must be larger than or equal to 0. Size must be larger * than or equal to -1. */ int64_t value_from_circle_const(const luci::CircleConst *node, uint32_t idx) { assert(node->rank() == 1 && node->dim(0).value() > idx); assert(node->dtype() == loco::DataType::S64 || node->dtype() == loco::DataType::S32); if (node->dtype() == loco::DataType::S64) return node->at<loco::DataType::S64>(idx); return static_cast<int64_t>(node->at<loco::DataType::S32>(idx)); } bool remove_no_effect_slice(luci::CircleNode *node) { auto target_node = dynamic_cast<luci::CircleSlice *>(node); if (target_node == nullptr) return false; auto begin_const = dynamic_cast<luci::CircleConst *>(target_node->begin()); if (begin_const == nullptr) return false; auto size_const = dynamic_cast<luci::CircleConst *>(target_node->size()); if (size_const == nullptr) return false; // Check input output shape. auto input_node = loco::must_cast<luci::CircleNode *>(target_node->input()); for (uint32_t i = 0; i < input_node->rank(); i++) { if (value_from_circle_const(begin_const, i) != 0) return false; int64_t size_value = value_from_circle_const(size_const, i); if (size_value == -1) continue; if (size_value != static_cast<int64_t>(input_node->dim(i).value())) return false; if (!input_node->dim(i).known()) return false; } replace(target_node).with(input_node); return true; } } // namespace namespace luci { /** * BEFORE * * [CircleNode] * | * [CircleSlice] * | * [CircleNode] * * AFTER * * [CircleNode] * | * [CircleNode] * * Slice OP has no effect if, * 1. Static Shape : begin_const[idx] is 0 AND size_const[idx] is (-1 OR input_dimension[idx]) * 2. Dynamic Shape : begin_const[idx] is 0 AND size_const[idx] is -1 */ bool RemoveUnnecessarySlicePass::run(loco::Graph *g) { bool changed = false; for (auto node : loco::active_nodes(loco::output_nodes(g))) { auto circle_node = loco::must_cast<luci::CircleNode *>(node); if (remove_no_effect_slice(circle_node)) { changed = true; } } return changed; } } // namespace luci
27.428571
97
0.666016
[ "shape" ]
0720e0d234a1ed864d4453eae903013b81f5082b
3,083
hh
C++
lib/spot-2.8.1/spot/kripke/kripke.hh
AlessandroCaste/SynkrisisJupyter
a9c2b21ec1ae7ac0c05ef5deebc63a369274650f
[ "Unlicense" ]
1
2018-03-02T14:29:57.000Z
2018-03-02T14:29:57.000Z
lib/spot-2.8.1/spot/kripke/kripke.hh
AlessandroCaste/SynkrisisJupyter
a9c2b21ec1ae7ac0c05ef5deebc63a369274650f
[ "Unlicense" ]
null
null
null
lib/spot-2.8.1/spot/kripke/kripke.hh
AlessandroCaste/SynkrisisJupyter
a9c2b21ec1ae7ac0c05ef5deebc63a369274650f
[ "Unlicense" ]
1
2015-06-05T12:42:07.000Z
2015-06-05T12:42:07.000Z
// -*- coding: utf-8 -*- // Copyright (C) 2009, 2010, 2013, 2014, 2016 Laboratoire de Recherche // et Developpement de l'Epita // // This file is part of Spot, a model checking library. // // Spot is free software; you can redistribute it and/or modify it // under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 3 of the License, or // (at your option) any later version. // // Spot 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/>. #pragma once #include <spot/kripke/fairkripke.hh> namespace spot { /// \ingroup kripke /// \brief Iterator code for Kripke structure /// /// This iterator can be used to simplify the writing /// of an iterator on a Kripke structure (or lookalike). /// /// If you inherit from this iterator, you should only /// redefine /// /// - kripke_succ_iterator::first() /// - kripke_succ_iterator::next() /// - kripke_succ_iterator::done() /// - kripke_succ_iterator::dst() /// /// This class implements kripke_succ_iterator::cond(), /// and kripke_succ_iterator::acc(). class SPOT_API kripke_succ_iterator : public twa_succ_iterator { public: /// \brief Constructor /// /// The \a cond argument will be the one returned /// by kripke_succ_iterator::cond(). kripke_succ_iterator(const bdd& cond) : cond_(cond) { } void recycle(const bdd& cond) { cond_ = cond; } virtual ~kripke_succ_iterator(); virtual bdd cond() const override; virtual acc_cond::mark_t acc() const override; protected: bdd cond_; }; /// \ingroup kripke /// \brief Interface for a Kripke structure /// /// A Kripke structure is a graph in which each node (=state) is /// labeled by a conjunction of atomic proposition. /// /// Such a structure can be seen as spot::tgba without /// any acceptance condition. /// /// A programmer that develops an instance of Kripke structure needs /// just provide an implementation for the following methods: /// /// - kripke::get_init_state() /// - kripke::succ_iter() /// - kripke::state_condition() /// - kripke::format_state() /// /// The other methods of the tgba interface (like those dealing with /// acceptance conditions) are supplied by this kripke class and /// need not be defined. /// /// See also spot::kripke_succ_iterator. class SPOT_API kripke: public fair_kripke { public: kripke(const bdd_dict_ptr& d) : fair_kripke(d) { } virtual ~kripke(); virtual acc_cond::mark_t state_acceptance_mark(const state*) const override; }; typedef std::shared_ptr<kripke> kripke_ptr; typedef std::shared_ptr<const kripke> const_kripke_ptr; }
28.813084
74
0.673694
[ "model" ]
07248ec3b6e042f14ec2d80e39303aa33ef2a469
875
hpp
C++
vendor/umappp/NeighborList.hpp
kojix2/umap
92404e3afe312393fb849227e0d6e91ad4355d8d
[ "MIT" ]
1
2022-03-11T11:08:30.000Z
2022-03-11T11:08:30.000Z
vendor/umappp/NeighborList.hpp
kojix2/umap
92404e3afe312393fb849227e0d6e91ad4355d8d
[ "MIT" ]
1
2022-01-31T05:04:40.000Z
2022-01-31T05:04:40.000Z
vendor/umappp/NeighborList.hpp
kojix2/umap
92404e3afe312393fb849227e0d6e91ad4355d8d
[ "MIT" ]
null
null
null
#ifndef UMAPPP_NEIGHBOR_LIST_HPP #define UMAPPP_NEIGHBOR_LIST_HPP /** * @file NeighborList.hpp * * @brief Defines the `NeighborList` typedef. */ namespace umappp { /** * @brief Neighbor specification based on index and distance. * * @tparam Float Floating-point type. * * The index refers to the position of the neighboring observation in the dataset. * The statistic can store some statistic related to the neighbor, e.g., distance or probabilities. */ template<typename Float = double> using Neighbor = std::pair<int, Float>; /** * @brief Lists of neighbors for each observation. * * @tparam Float Floating-point type. * * Each inner vector corresponds to an observation and contains the list of nearest neighbors for that observation. */ template<typename Float = double> using NeighborList = std::vector<std::vector<Neighbor<Float> > >; } #endif
24.305556
115
0.738286
[ "vector" ]
072ae549135b3a1117acae37d7e55d9b9ae0ec76
1,328
cpp
C++
source/Ch04/Drill/drill4-2.cpp
Gabszter/UDProg-Introduction
b3807d4e04b9bdc7b7e2f518be9cabb081d83b86
[ "CC0-1.0" ]
null
null
null
source/Ch04/Drill/drill4-2.cpp
Gabszter/UDProg-Introduction
b3807d4e04b9bdc7b7e2f518be9cabb081d83b86
[ "CC0-1.0" ]
null
null
null
source/Ch04/Drill/drill4-2.cpp
Gabszter/UDProg-Introduction
b3807d4e04b9bdc7b7e2f518be9cabb081d83b86
[ "CC0-1.0" ]
null
null
null
#include "../../std_lib_facilities.h" int main() { const double cm_per_inch=2.54; const double cm_per_m=100; const double ft_per_inc=12; int db=0; double n; double min=numeric_limits<double>::max(); double max=numeric_limits<double>::lowest(); double sum; string unit=" "; vector<double> numbers; while(cin >> n >> unit) { if(unit=="m") { n=n; } else if(unit=="cm") { n=n/cm_per_m; } else if(unit=="in") { n=(n*cm_per_inch)/cm_per_m; } else if(unit=="ft") { n=(n*ft_per_inc*cm_per_inch)/cm_per_m; } else { simple_error("Invalid values!"); } if(n<min) min=n; if(n>max) max=n; cout << n << " m\n"; numbers.push_back(n); sum+=n; db++; if(db>=2) { cout << "The smallest so far: " << min << "!\n"; cout << "The largest so far: " << max << "!\n"; } } cout << "The smallest: " << min << "!\n"; cout << "The largest: " << max << "!\n"; cout << "Number of values entered: " << db << "!\n"; cout << "The sum of values: " << sum << "!\n"; sort(numbers); cout << "The entered values in sorted order: "; for (auto num : numbers) { cout << num << " "; } cout << "\nThe smallest: " << numbers[0] << "!\n"; cout << "The largest: " << numbers[numbers.size()-1] << "!\n"; return 0; }
19.246377
66
0.521837
[ "vector" ]
0737cab60207d5734a2a3d9d375ed52df988b64c
545
cpp
C++
c/src/datastructs/var.cpp
regularApproximation/newton
ad6138fcf2e473446714cf31d77d0f86560dfdd8
[ "BSD-2-Clause" ]
8
2015-01-17T23:30:54.000Z
2018-08-13T20:42:54.000Z
c/src/datastructs/var.cpp
regularApproximation/newton
ad6138fcf2e473446714cf31d77d0f86560dfdd8
[ "BSD-2-Clause" ]
null
null
null
c/src/datastructs/var.cpp
regularApproximation/newton
ad6138fcf2e473446714cf31d77d0f86560dfdd8
[ "BSD-2-Clause" ]
3
2016-02-21T11:13:38.000Z
2018-11-11T03:50:09.000Z
#include "var.h" VarId Var::next_id_ = 0; std::unordered_map<std::string, VarId> Var::name_to_id_; std::unordered_map<VarId, std::unique_ptr<Var> > Var::id_to_var_; std::ostream& operator<<(std::ostream &out, const VarId &vid) { return out << Var::GetVar(vid); } std::ostream& operator<<(std::ostream &out, const std::vector<VarId> &vids) { out << "{"; for (auto iter = vids.begin(); iter != vids.end(); ++iter) { if (iter != vids.begin()) { out << ","; } out << Var::GetVar(*iter); } out << "}"; return out; }
23.695652
77
0.59633
[ "vector" ]
073afe2311b8db77ee40e664cc262309461dcdcd
8,913
cpp
C++
src/io/network/udpSocket.cpp
daid/SeriousProton2
6cc9c2291ea63ffc82427ed82f51a84611f7f45c
[ "MIT" ]
8
2018-01-26T20:21:08.000Z
2021-08-30T20:28:43.000Z
src/io/network/udpSocket.cpp
daid/SeriousProton2
6cc9c2291ea63ffc82427ed82f51a84611f7f45c
[ "MIT" ]
7
2018-10-28T14:52:25.000Z
2020-12-28T19:59:04.000Z
src/io/network/udpSocket.cpp
daid/SeriousProton2
6cc9c2291ea63ffc82427ed82f51a84611f7f45c
[ "MIT" ]
7
2017-05-27T16:33:37.000Z
2022-02-18T14:07:17.000Z
#include <sp2/io/network/udpSocket.h> #ifdef _WIN32 #include <winsock2.h> #include <ws2tcpip.h> static constexpr int flags = 0; #else #include <sys/types.h> #include <sys/socket.h> #include <unistd.h> #include <netinet/in.h> #include <arpa/inet.h> #include <string.h> #include <netdb.h> static constexpr int flags = MSG_NOSIGNAL; #endif namespace sp { namespace io { namespace network { UdpSocket::UdpSocket() { } UdpSocket::UdpSocket(UdpSocket&& socket) { handle = socket.handle; blocking = socket.blocking; socket.handle = -1; } UdpSocket::~UdpSocket() { close(); } bool UdpSocket::bind(int port) { close(); if (!createSocket()) return false; if (socket_is_ipv6) { socket_is_ipv6 = true; struct sockaddr_in6 server_addr; memset(&server_addr, 0, sizeof(server_addr)); server_addr.sin6_family = AF_INET6; server_addr.sin6_addr = in6addr_any; server_addr.sin6_port = htons(port); if (::bind(handle, reinterpret_cast<struct sockaddr*>(&server_addr), sizeof(server_addr)) < 0) { close(); return false; } } else { struct sockaddr_in server_addr; memset(&server_addr, 0, sizeof(server_addr)); server_addr.sin_family = AF_INET; server_addr.sin_addr.s_addr = htonl(INADDR_ANY); server_addr.sin_port = htons(port); if (::bind(handle, reinterpret_cast<struct sockaddr*>(&server_addr), sizeof(server_addr)) < 0) { close(); return false; } } return true; } bool UdpSocket::joinMulticast(int group_nr) { if (handle == -1) { if (!createSocket()) return false; } bool success = true; struct sockaddr_in server_addr; for(const auto& addr_info : Address::getLocalAddress().addr_info) { if (addr_info.family == AF_INET && addr_info.addr.length() == sizeof(server_addr)) { memcpy(&server_addr, addr_info.addr.data(), addr_info.addr.length()); struct ip_mreq mreq; mreq.imr_multiaddr.s_addr = htonl((239 << 24) | (192 << 16) | (group_nr)); mreq.imr_interface.s_addr = server_addr.sin_addr.s_addr; success = success && ::setsockopt(handle, IPPROTO_IP, IP_ADD_MEMBERSHIP, reinterpret_cast<const char*>(&mreq), sizeof(mreq)) == 0; } } return success; } void UdpSocket::close() { if (handle != -1) { #ifdef _WIN32 closesocket(handle); #else ::close(handle); #endif handle = -1; } } bool UdpSocket::send(const void* data, size_t size, const Address& address, int port) { if (handle == -1) { if (!createSocket()) return false; } if (socket_is_ipv6) { struct sockaddr_in6 server_addr; bool is_set = false; memset(&server_addr, 0, sizeof(server_addr)); for(auto& addr_info : address.addr_info) { if (addr_info.family == AF_INET6 && addr_info.addr.length() == sizeof(server_addr)) { memcpy(&server_addr, addr_info.addr.data(), addr_info.addr.length()); is_set = true; break; } } if (is_set) { server_addr.sin6_family = AF_INET6; server_addr.sin6_port = htons(port); int result = ::sendto(handle, static_cast<const char*>(data), size, flags, reinterpret_cast<const sockaddr*>(&server_addr), sizeof(server_addr)); return result == int(size); } } struct sockaddr_in server_addr; bool is_set = false; memset(&server_addr, 0, sizeof(server_addr)); for(auto& addr_info : address.addr_info) { if (addr_info.family == AF_INET && addr_info.addr.length() == sizeof(server_addr)) { memcpy(&server_addr, addr_info.addr.data(), addr_info.addr.length()); is_set = true; break; } } if (is_set) { server_addr.sin_family = AF_INET; server_addr.sin_port = htons(port); int result = ::sendto(handle, static_cast<const char*>(data), size, flags, reinterpret_cast<const sockaddr*>(&server_addr), sizeof(server_addr)); return result == int(size); } return false; } size_t UdpSocket::receive(void* data, size_t size, Address& address, int& port) { if (handle == -1) return 0; address.addr_info.clear(); if (socket_is_ipv6) { struct sockaddr_in6 from_addr; memset(&from_addr, 0, sizeof(from_addr)); socklen_t from_addr_len = sizeof(from_addr); int result = ::recvfrom(handle, static_cast<char*>(data), size, flags, reinterpret_cast<sockaddr*>(&from_addr), &from_addr_len); if (result >= 0) { if (from_addr_len == sizeof(from_addr)) { char buffer[128]; ::getnameinfo(reinterpret_cast<const sockaddr*>(&from_addr), from_addr_len, buffer, sizeof(buffer), nullptr, 0, NI_NUMERICHOST); address.addr_info.emplace_back(AF_INET6, buffer, &from_addr, from_addr_len); port = ntohs(from_addr.sin6_port); } else if (from_addr_len == sizeof(struct sockaddr_in)) { char buffer[128]; ::getnameinfo(reinterpret_cast<const sockaddr*>(&from_addr), from_addr_len, buffer, sizeof(buffer), nullptr, 0, NI_NUMERICHOST); address.addr_info.emplace_back(AF_INET, buffer, &from_addr, from_addr_len); port = ntohs(reinterpret_cast<struct sockaddr_in*>(&from_addr)->sin_port); } return result; } } else { struct sockaddr_in from_addr; memset(&from_addr, 0, sizeof(from_addr)); socklen_t from_addr_len = sizeof(from_addr); int result = ::recvfrom(handle, static_cast<char*>(data), size, flags, reinterpret_cast<sockaddr*>(&from_addr), &from_addr_len); if (result >= 0) { if (from_addr_len == sizeof(from_addr)) { char buffer[128]; ::getnameinfo(reinterpret_cast<const sockaddr*>(&from_addr), from_addr_len, buffer, sizeof(buffer), nullptr, 0, NI_NUMERICHOST); address.addr_info.emplace_back(AF_INET, buffer, &from_addr, from_addr_len); port = ntohs(from_addr.sin_port); } return result; } } return 0; } bool UdpSocket::send(const DataBuffer& buffer, const Address& address, int port) { return send(buffer.getData(), buffer.getDataSize(), address, port); } bool UdpSocket::receive(DataBuffer& buffer, Address& address, int& port) { uint8_t receive_buffer[4096]; size_t received_size = receive(receive_buffer, sizeof(receive_buffer), address, port); if (received_size > 0) { buffer = std::vector<uint8_t>(receive_buffer, receive_buffer + received_size); } return received_size > 0; } bool UdpSocket::sendMulticast(const void* data, size_t size, int group_nr, int port) { if (handle == -1) { createSocket(); } bool success = false; struct sockaddr_in server_addr; for(const auto& addr_info : Address::getLocalAddress().addr_info) { if (addr_info.family == AF_INET && addr_info.addr.length() == sizeof(server_addr)) { memcpy(&server_addr, addr_info.addr.data(), addr_info.addr.length()); ::setsockopt(handle, IPPROTO_IP, IP_MULTICAST_IF, reinterpret_cast<const char*>(&server_addr.sin_addr), sizeof(server_addr.sin_addr)); memset(&server_addr, 0, sizeof(server_addr)); server_addr.sin_addr.s_addr = htonl((239 << 24) | (192 << 16) | (group_nr)); server_addr.sin_family = AF_INET; server_addr.sin_port = htons(port); int result = ::sendto(handle, static_cast<const char*>(data), size, flags, reinterpret_cast<const sockaddr*>(&server_addr), sizeof(server_addr)); if (result == int(size)) success = true; } } return success; } bool UdpSocket::sendMulticast(const DataBuffer& buffer, int group_nr, int port) { return sendMulticast(buffer.getData(), buffer.getDataSize(), group_nr, port); } bool UdpSocket::createSocket() { close(); handle = ::socket(AF_INET6, SOCK_DGRAM, IPPROTO_UDP); socket_is_ipv6 = true; if (handle == -1) { handle = ::socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); socket_is_ipv6 = false; } else { int optval = 0; ::setsockopt(handle, IPPROTO_IPV6, IPV6_V6ONLY, reinterpret_cast<const char*>(&optval), sizeof(int)); } return handle != -1; } }//namespace network }//namespace io }//namespace sp
29.222951
157
0.602266
[ "vector" ]
073e4cbe06450a243603994830bbfd8a4bbb6954
15,148
cpp
C++
samples/cpp/object_detection_demo_yolov3_async/main.cpp
cgdougla/gst-video-analytics
003117484abff4d2b1ad5f053ac35e7fa00788f6
[ "MIT" ]
null
null
null
samples/cpp/object_detection_demo_yolov3_async/main.cpp
cgdougla/gst-video-analytics
003117484abff4d2b1ad5f053ac35e7fa00788f6
[ "MIT" ]
null
null
null
samples/cpp/object_detection_demo_yolov3_async/main.cpp
cgdougla/gst-video-analytics
003117484abff4d2b1ad5f053ac35e7fa00788f6
[ "MIT" ]
1
2020-12-04T07:22:57.000Z
2020-12-04T07:22:57.000Z
/******************************************************************************* * Copyright (C) 2018-2019 Intel Corporation * * SPDX-License-Identifier: MIT * * object_detection_demo_yolov3_async implementation based on object_detection_demo_yolov3_async * See https://github.com/opencv/open_model_zoo/tree/2018/demos/object_detection_demo_yolov3_async * Differences: * ParseYOLOV3Output function changed for working with gva tensors * Adapted code style to match with Video Analytics GStreamer* plugins project ******************************************************************************/ #include <dirent.h> #include <gio/gio.h> #include <gst/gst.h> #include <opencv2/opencv.hpp> #include <stdio.h> #include <stdlib.h> #include "coco_labels.h" #include "gva_tensor_meta.h" #define UNUSED(x) (void)(x) std::vector<std::string> SplitString(const std::string input, char delimiter = ':') { std::vector<std::string> tokens; std::string token; std::istringstream tokenStream(input); while (std::getline(tokenStream, token, delimiter)) { tokens.push_back(token); } return tokens; } void ExploreDir(std::string search_dir, const std::string &model_name, std::vector<std::string> &result) { if (auto dir_handle = opendir(search_dir.c_str())) { while (auto file_handle = readdir(dir_handle)) { if ((!file_handle->d_name) || (file_handle->d_name[0] == '.')) continue; if (file_handle->d_type == DT_DIR) ExploreDir(search_dir + file_handle->d_name + "/", model_name, result); if (file_handle->d_type == DT_REG) { std::string name(file_handle->d_name); if (name == model_name) result.push_back(search_dir + "/" + name); } } closedir(dir_handle); } } std::vector<std::string> FindModel(const std::vector<std::string> &search_dirs, const std::string &model_name) { std::vector<std::string> result = {}; for (const std::string &dir : search_dirs) { ExploreDir(dir + "/", model_name, result); } return result; } std::string to_upper_case(std::string str) { std::transform(str.begin(), str.end(), str.begin(), ::toupper); return str; } std::map<std::string, std::string> FindModels(const std::vector<std::string> &search_dirs, const std::vector<std::string> &model_names, const std::string &precision) { std::map<std::string, std::string> result; for (const std::string &model_name : model_names) { std::vector<std::string> model_paths = FindModel(search_dirs, model_name); if (model_paths.empty()) continue; result[model_name] = model_paths.front(); for (const auto &model_path : model_paths) // TODO extract precision from xml file if (to_upper_case(model_path).find(to_upper_case(precision)) != std::string::npos) { result[model_name] = model_path; break; } } if (result.empty()) throw std::runtime_error("Can't find file for model"); return result; } const std::string env_models_path = std::string() + (getenv("MODELS_PATH") != NULL ? getenv("MODELS_PATH") : getenv("INTEL_CVSDK_DIR") != NULL ? std::string() + getenv("INTEL_CVSDK_DIR") + "/deployment_tools/intel_models" + "/" : ""); const std::vector<std::string> default_detection_model_names = {"yolov3.xml", "frozen_darknet_yolov3_model.xml"}; gchar *input_file = NULL; gchar const *detection_model = NULL; gchar *extension = NULL; gchar const *device = "CPU"; gchar const *model_precision = "FP32"; gint batch_size = 1; gdouble threshold = 0.4; gboolean no_display = FALSE; static GOptionEntry opt_entries[] = { {"input", 'i', 0, G_OPTION_ARG_STRING, &input_file, "Path to input video file", NULL}, {"precision", 'p', 0, G_OPTION_ARG_STRING, &model_precision, "Models precision. Default: FP32", NULL}, {"detection", 'm', 0, G_OPTION_ARG_STRING, &detection_model, "Path to detection model file", NULL}, {"extension", 'e', 0, G_OPTION_ARG_STRING, &extension, "Path to custom layers extension library", NULL}, {"device", 'd', 0, G_OPTION_ARG_STRING, &device, "Device to run inference", NULL}, {"batch", 'b', 0, G_OPTION_ARG_INT, &batch_size, "Batch size", NULL}, {"threshold", 't', 0, G_OPTION_ARG_DOUBLE, &threshold, "Confidence threshold for detection (0 - 1)", NULL}, {"no-display", 'n', 0, G_OPTION_ARG_NONE, &no_display, "Run without display", NULL}, GOptionEntry()}; GstGVATensorMeta *gst_buffer_iterate_tensor_meta(GstBuffer *buffer, gpointer *state) { static GQuark gva_tensor_meta_tag = g_quark_from_static_string(GVA_TENSOR_META_TAG); while (GstMeta *meta = gst_buffer_iterate_meta(buffer, state)) { if (gst_meta_api_type_has_tag(meta->info->api, gva_tensor_meta_tag)) { return (GstGVATensorMeta *)meta; } } return NULL; } struct DetectionObject { int xmin, ymin, xmax, ymax, class_id; float confidence; DetectionObject(double x, double y, double h, double w, int class_id, float confidence, float h_scale, float w_scale) { this->xmin = static_cast<int>((x - w / 2) * w_scale); this->ymin = static_cast<int>((y - h / 2) * h_scale); this->xmax = static_cast<int>(this->xmin + w * w_scale); this->ymax = static_cast<int>(this->ymin + h * h_scale); this->class_id = class_id; this->confidence = confidence; } bool operator<(const DetectionObject &s2) const { return this->confidence < s2.confidence; } }; double IntersectionOverUnion(const DetectionObject &box_1, const DetectionObject &box_2) { double width_of_overlap_area = fmin(box_1.xmax, box_2.xmax) - fmax(box_1.xmin, box_2.xmin); double height_of_overlap_area = fmin(box_1.ymax, box_2.ymax) - fmax(box_1.ymin, box_2.ymin); double area_of_overlap; if (width_of_overlap_area < 0 || height_of_overlap_area < 0) area_of_overlap = 0; else area_of_overlap = width_of_overlap_area * height_of_overlap_area; double box_1_area = (box_1.ymax - box_1.ymin) * (box_1.xmax - box_1.xmin); double box_2_area = (box_2.ymax - box_2.ymin) * (box_2.xmax - box_2.xmin); double area_of_union = box_1_area + box_2_area - area_of_overlap; return area_of_overlap / area_of_union; } static int EntryIndex(int side, int lcoords, int lclasses, int location, int entry) { int n = location / (side * side); int loc = location % (side * side); return n * side * side * (lcoords + lclasses + 1) + entry * side * side + loc; } void ParseYOLOV3Output(GstGVATensorMeta *RegionYolo, int image_width, int image_height, std::vector<DetectionObject> &objects) { const int out_blob_h = RegionYolo->dims[2]; int coords = 4; int num = 3; int classes = 80; std::vector<float> anchors = {10.0, 13.0, 16.0, 30.0, 33.0, 23.0, 30.0, 61.0, 62.0, 45.0, 59.0, 119.0, 116.0, 90.0, 156.0, 198.0, 373.0, 326.0}; int side = out_blob_h; int anchor_offset = 0; switch (side) { case 13: anchor_offset = 2 * 6; break; case 26: anchor_offset = 2 * 3; break; case 52: anchor_offset = 2 * 0; break; default: throw std::runtime_error("Invalid output size"); } int side_square = side * side; const float *output_blob = (const float *)RegionYolo->data; for (int i = 0; i < side_square; ++i) { int row = i / side; int col = i % side; for (int n = 0; n < num; ++n) { int obj_index = EntryIndex(side, coords, classes, n * side * side + i, coords); int box_index = EntryIndex(side, coords, classes, n * side * side + i, 0); float scale = output_blob[obj_index]; if (scale < threshold) continue; double x = (col + output_blob[box_index + 0 * side_square]) / side * 416; double y = (row + output_blob[box_index + 1 * side_square]) / side * 416; double width = std::exp(output_blob[box_index + 2 * side_square]) * anchors[anchor_offset + 2 * n]; double height = std::exp(output_blob[box_index + 3 * side_square]) * anchors[anchor_offset + 2 * n + 1]; for (int j = 0; j < classes; ++j) { int class_index = EntryIndex(side, coords, classes, n * side_square + i, coords + 1 + j); float prob = scale * output_blob[class_index]; if (prob < threshold) continue; DetectionObject obj(x, y, height, width, j, prob, static_cast<float>(image_height) / static_cast<float>(416), static_cast<float>(image_width) / static_cast<float>(416)); objects.push_back(obj); } } } } void DrawObjects(std::vector<DetectionObject> &objects, cv::Mat &frame) { std::sort(objects.begin(), objects.end()); for (size_t i = 0; i < objects.size(); ++i) { if (objects[i].confidence == 0) continue; for (size_t j = i + 1; j < objects.size(); ++j) if (IntersectionOverUnion(objects[i], objects[j]) >= 0.4) objects[j].confidence = 0; } // Drawing boxes for (const auto &object : objects) { if (object.confidence < 0) continue; guint label = object.class_id; float confidence = object.confidence; if (confidence > 0) { /** Drawing only objects when >confidence_threshold probability **/ std::ostringstream conf; conf << ":" << std::fixed << std::setprecision(3) << confidence; cv::putText( frame, (label < labels.size() ? labels[label] : std::string("label #") + std::to_string(label)) + conf.str(), cv::Point2f(object.xmin, object.ymin - 5), cv::FONT_HERSHEY_COMPLEX_SMALL, 1, cv::Scalar(0, 0, 255)); cv::rectangle(frame, cv::Point2f(object.xmin, object.ymin), cv::Point2f(object.xmax, object.ymax), cv::Scalar(0, 0, 255)); } } } // This structure will be used to pass user data (such as memory type) to the callback function. static GstPadProbeReturn pad_probe_callback(GstPad *pad, GstPadProbeInfo *info, gpointer user_data) { UNUSED(user_data); auto buffer = GST_PAD_PROBE_INFO_BUFFER(info); if (buffer == NULL) return GST_PAD_PROBE_OK; // Get width and height gint width = 0, height = 0; auto caps = gst_pad_get_current_caps(pad); auto caps_str = gst_caps_get_structure(caps, 0); gst_structure_get_int(caps_str, "width", &width); gst_structure_get_int(caps_str, "height", &height); gst_caps_unref(caps); // Map buffer and create OpenCV image GstMapInfo map; if (!gst_buffer_map(buffer, &map, GST_MAP_READ)) return GST_PAD_PROBE_OK; cv::Mat mat(height, width, CV_8UC4, map.data); // Parse and draw outputs std::vector<DetectionObject> objects; gpointer state = NULL; while (GstGVATensorMeta *meta = gst_buffer_iterate_tensor_meta(buffer, &state)) { if (strstr(meta->model_name, "yolov3")) { ParseYOLOV3Output(meta, width, height, objects); } } DrawObjects(objects, mat); GST_PAD_PROBE_INFO_DATA(info) = buffer; gst_buffer_unmap(buffer, &map); return GST_PAD_PROBE_OK; } int main(int argc, char *argv[]) { // Parse arguments GOptionContext *context = g_option_context_new("sample"); g_option_context_add_main_entries(context, opt_entries, "sample"); g_option_context_add_group(context, gst_init_get_option_group()); GError *error = NULL; if (!g_option_context_parse(context, &argc, &argv, &error)) { g_print("option parsing failed: %s\n", error->message); return 1; } if (!input_file) { g_print("Please specify input file:\n%s\n", g_option_context_get_help(context, TRUE, NULL)); return 1; } if (env_models_path.empty()) { throw std::runtime_error("Enviroment variable MODELS_PATH is not set"); } if (detection_model == NULL) { std::map<std::string, std::string> model_paths = FindModels(SplitString(env_models_path), default_detection_model_names, model_precision); for (const std::string &default_model_name : default_detection_model_names) { if (!model_paths[default_model_name].empty()) detection_model = g_strdup(model_paths[default_model_name].c_str()); } } if (!detection_model) { g_print("Please specify detection model path:\n%s\n", g_option_context_get_help(context, TRUE, NULL)); return 1; } gchar const *preprocess_pipeline = "decodebin ! videoconvert n-threads=4 ! videoscale n-threads=4 "; gchar const *capfilter = "video/x-raw"; gchar const *sink = no_display ? "identity signal-handoffs=false ! fakesink sync=false" : "fpsdisplaysink video-sink=xvimagesink sync=false"; // Build the pipeline auto launch_str = g_strdup_printf("filesrc location=%s ! %s ! capsfilter caps=\"%s\" ! " "gvainference name=gvadetect model=%s device=%s batch-size=%d ! queue ! " "videoconvert n-threads=4 ! %s ", input_file, preprocess_pipeline, capfilter, detection_model, device, batch_size, sink); g_print("PIPELINE: %s \n", launch_str); GstElement *pipeline = gst_parse_launch(launch_str, NULL); g_free(launch_str); // set probe callback GstElement *gvadetect = gst_bin_get_by_name(GST_BIN(pipeline), "gvadetect"); GstPad *pad = gst_element_get_static_pad(gvadetect, "src"); gst_pad_add_probe(pad, GST_PAD_PROBE_TYPE_BUFFER, pad_probe_callback, NULL, NULL); gst_object_unref(pad); // Start playing gst_element_set_state(pipeline, GST_STATE_PLAYING); // Wait until error or EOS GstBus *bus = gst_element_get_bus(pipeline); int ret_code = 0; GstMessage *msg = gst_bus_poll(bus, (GstMessageType)(GST_MESSAGE_ERROR | GST_MESSAGE_EOS), -1); if (msg && GST_MESSAGE_TYPE(msg) == GST_MESSAGE_ERROR) { GError *err = NULL; gchar *dbg_info = NULL; gst_message_parse_error(msg, &err, &dbg_info); g_printerr("ERROR from element %s: %s\n", GST_OBJECT_NAME(msg->src), err->message); g_printerr("Debugging info: %s\n", (dbg_info) ? dbg_info : "none"); g_error_free(err); g_free(dbg_info); ret_code = -1; } if (msg) gst_message_unref(msg); // Free resources gst_object_unref(bus); gst_element_set_state(pipeline, GST_STATE_NULL); gst_object_unref(pipeline); return ret_code; }
39.863158
118
0.616847
[ "object", "vector", "model", "transform" ]
073f1100bd56cff0fa27a09319c9b313894c6ae9
16,613
cpp
C++
INFO6028/ILoveOpenGL/ILoveOpenGL/InputHandling.cpp
LordMichaelmort/GDP2021_22
0498a1b7a16a35e8d4e79591163937ebffc15f47
[ "MIT" ]
2
2021-09-10T17:43:58.000Z
2021-09-14T21:52:47.000Z
INFO6028/ILoveOpenGL/ILoveOpenGL/InputHandling.cpp
LordMichaelmort/GDP2021_22
0498a1b7a16a35e8d4e79591163937ebffc15f47
[ "MIT" ]
null
null
null
INFO6028/ILoveOpenGL/ILoveOpenGL/InputHandling.cpp
LordMichaelmort/GDP2021_22
0498a1b7a16a35e8d4e79591163937ebffc15f47
[ "MIT" ]
1
2021-09-14T18:07:06.000Z
2021-09-14T18:07:06.000Z
#include "GLCommon.h" #include "globalThings.h" #include <sstream> #include <iostream> #include "cWinContextMenu.h" // This is taken care of by the Entity Organizer class // This could go into the global.h file, too //iShip* g_findShipByName(std::string nameToFind); // Handle async IO (keyboard, joystick, mouse, etc.) // This is so the "fly camera" won't pay attention to the mouse if it's // not directly over the window. bool g_MouseIsInsideWindow = false; // HACK: Ship engine angle float g_DropShipEngineAngle = 0.0f; float g_DropShipEngineThrust = 0.0f; void handleAsyncKeyboard(GLFWwindow* pWindow, double deltaTime) { float cameraMoveSpeed = ::g_pFlyCamera->movementSpeed; float objectMovementSpeed = 0.1f; float lightMovementSpeed = 10.0f; if ( cGFLWKeyboardModifiers::areAllModsUp(pWindow) ) { // Move the drop ship engines const float SHIP_ENGINE_ROTATION_SPEED = 1.0f; if (glfwGetKey(pWindow, GLFW_KEY_J) == GLFW_PRESS) // Rotate the engines down { iShip* pSpikesShip = ::g_pEntityOrganizer->find_pShipByName("Spike"); // iShip* pSpikesShip = ::g_findShipByName("Spike"); if (pSpikesShip) { sMessage setEngine_Angle; setEngine_Angle.command = "Set Engine Angle"; float theAngle = ::g_DropShipEngineAngle; ::g_DropShipEngineAngle += SHIP_ENGINE_ROTATION_SPEED; unsigned int engineID = 0; // Move ALL the engines // unsigned int engineID = 5; // Move ALL the engines setEngine_Angle.vec_fData.push_back(glm::vec4( (float)engineID, glm::radians(theAngle), 0.0f, 1.0f)); pSpikesShip->RecieveMessage(setEngine_Angle); } }//if (glfwGetKey(pWindow, GLFW_KEY_J if (glfwGetKey(pWindow, GLFW_KEY_K) == GLFW_PRESS) // Rotate the engines down { iShip* pSpikesShip = ::g_pEntityOrganizer->find_pShipByName("Spike"); // iShip* pSpikesShip = ::g_findShipByName("Spike"); if (pSpikesShip) { sMessage setEngine_Angle; setEngine_Angle.command = "Set Engine Angle"; float theAngle = ::g_DropShipEngineAngle; ::g_DropShipEngineAngle -= SHIP_ENGINE_ROTATION_SPEED; unsigned int engineID = 0; // Move ALL the engines // unsigned int engineID = 5; // Move ALL the engines setEngine_Angle.vec_fData.push_back(glm::vec4( (float)engineID, glm::radians(theAngle), 0.0f, 1.0f)); pSpikesShip->RecieveMessage(setEngine_Angle); } }//if (glfwGetKey(pWindow, GLFW_KEY_K if (glfwGetKey(pWindow, GLFW_KEY_PAGE_UP) == GLFW_PRESS) // Increase engine thrust { iShip* pSpikesShip = ::g_pEntityOrganizer->find_pShipByName("Spike"); // iShip* pSpikesShip = ::g_findShipByName("Spike"); if (pSpikesShip) { sMessage setEngine_Thrust; setEngine_Thrust.command = "Set Engine Thrust"; ::g_DropShipEngineThrust += 1.0f; if (::g_DropShipEngineThrust > 100.0f) { ::g_DropShipEngineThrust = 100.0f; } setEngine_Thrust.vec_fData.push_back(glm::vec4(::g_DropShipEngineThrust, ::g_DropShipEngineThrust, ::g_DropShipEngineThrust, ::g_DropShipEngineThrust) ); pSpikesShip->RecieveMessage(setEngine_Thrust); } }//if (glfwGetKey(pWindow, GLFW_KEY_PAGE_UP if (glfwGetKey(pWindow, GLFW_KEY_PAGE_DOWN) == GLFW_PRESS) // Decrease engine thrust { iShip* pSpikesShip = ::g_pEntityOrganizer->find_pShipByName("Spike"); // iShip* pSpikesShip = ::g_findShipByName("Spike"); if (pSpikesShip) { sMessage setEngine_Thrust; setEngine_Thrust.command = "Set Engine Thrust"; ::g_DropShipEngineThrust -= 1.0f; // Clamp to 0.0f; if (::g_DropShipEngineThrust < 0.0f) { ::g_DropShipEngineThrust = 0.0f; } setEngine_Thrust.vec_fData.push_back(glm::vec4(::g_DropShipEngineThrust, ::g_DropShipEngineThrust, ::g_DropShipEngineThrust, ::g_DropShipEngineThrust) ); pSpikesShip->RecieveMessage(setEngine_Thrust); } }//if (glfwGetKey(pWindow, GLFW_KEY_PAGE_DOWN // Use "fly" camera (keyboard for movement, mouse for aim) if ( glfwGetKey(pWindow, GLFW_KEY_W) == GLFW_PRESS ) { ::g_pFlyCamera->MoveForward_Z(+cameraMoveSpeed); } if ( glfwGetKey(pWindow, GLFW_KEY_S) == GLFW_PRESS ) // "backwards" { ::g_pFlyCamera->MoveForward_Z(-cameraMoveSpeed); } if ( glfwGetKey(pWindow, GLFW_KEY_A) == GLFW_PRESS ) // "left" { ::g_pFlyCamera->MoveLeftRight_X(-cameraMoveSpeed); } if ( glfwGetKey(pWindow, GLFW_KEY_D) == GLFW_PRESS ) // "right" { ::g_pFlyCamera->MoveLeftRight_X(+cameraMoveSpeed); } if ( glfwGetKey(pWindow, GLFW_KEY_Q) == GLFW_PRESS ) // "up" { ::g_pFlyCamera->MoveUpDown_Y(-cameraMoveSpeed); } if ( glfwGetKey(pWindow, GLFW_KEY_E) == GLFW_PRESS ) // "down" { ::g_pFlyCamera->MoveUpDown_Y(+cameraMoveSpeed); } std::stringstream strTitle; // std::cout << glm::vec3 cameraEye = ::g_pFlyCamera->getEye(); strTitle << "Camera: " << cameraEye.x << ", " << cameraEye.y << ", " << cameraEye.z; //<< std::endl; ::g_TitleText = strTitle.str(); }//if ( cGFLWKeyboardModifiers::areAllModsUp(pWindow) ) // // Basic camera controls (if NONE of the control keys are pressed) // if ( cGFLWKeyboardModifiers::areAllModsUp(pWindow) ) // { // if ( glfwGetKey(pWindow, GLFW_KEY_A) == GLFW_PRESS ) { ::g_cameraEye.x -= cameraMoveSpeed; } // Go left // if ( glfwGetKey(pWindow, GLFW_KEY_D) == GLFW_PRESS ) { ::g_cameraEye.x += cameraMoveSpeed; } // Go right // if ( glfwGetKey(pWindow, GLFW_KEY_W) == GLFW_PRESS ) { ::g_cameraEye.z += cameraMoveSpeed; }// Go forward // if ( glfwGetKey(pWindow, GLFW_KEY_S) == GLFW_PRESS ) { ::g_cameraEye.z -= cameraMoveSpeed; }// Go backwards // if ( glfwGetKey(pWindow, GLFW_KEY_Q) == GLFW_PRESS ) { ::g_cameraEye.y -= cameraMoveSpeed; }// Go "Down" // if ( glfwGetKey(pWindow, GLFW_KEY_E) == GLFW_PRESS ) { ::g_cameraEye.y += cameraMoveSpeed; }// Go "Up" // // std::stringstream strTitle; // // std::cout << // strTitle << "Camera: " // << ::g_cameraEye.x << ", " // << ::g_cameraEye.y << ", " // << ::g_cameraEye.z; //<< std::endl; // // ::g_TitleText = strTitle.str(); // // }//if ( areAllModsUp(window) )... // If JUST the shift is down, move the "selected" object // if ( cGFLWKeyboardModifiers::isModifierDown(pWindow, true, false, false ) ) // { // if ( glfwGetKey(pWindow, GLFW_KEY_A) == GLFW_PRESS ) { ::g_vec_pMeshes[::g_selectedObject]->positionXYZ.x -= objectMovementSpeed; } // Go left // if ( glfwGetKey(pWindow, GLFW_KEY_D) == GLFW_PRESS ) { ::g_vec_pMeshes[::g_selectedObject]->positionXYZ.x += objectMovementSpeed; } // Go right // if ( glfwGetKey(pWindow, GLFW_KEY_W) == GLFW_PRESS ) { ::g_vec_pMeshes[::g_selectedObject]->positionXYZ.z += objectMovementSpeed; }// Go forward // if ( glfwGetKey(pWindow, GLFW_KEY_S) == GLFW_PRESS ) { ::g_vec_pMeshes[::g_selectedObject]->positionXYZ.z -= objectMovementSpeed; }// Go backwards // if ( glfwGetKey(pWindow, GLFW_KEY_Q) == GLFW_PRESS ) { ::g_vec_pMeshes[::g_selectedObject]->positionXYZ.y -= objectMovementSpeed; }// Go "Down" // if ( glfwGetKey(pWindow, GLFW_KEY_E) == GLFW_PRESS ) { ::g_vec_pMeshes[::g_selectedObject]->positionXYZ.y += objectMovementSpeed; }// Go "Up" // // std::stringstream strTitle; // // std::cout << // strTitle << "::g_vec_pMeshes[" << ::g_selectedObject << "].positionXYZ : " // << ::g_vec_pMeshes[::g_selectedObject]->positionXYZ.x << ", " // << ::g_vec_pMeshes[::g_selectedObject]->positionXYZ.y << ", " // << ::g_vec_pMeshes[::g_selectedObject]->positionXYZ.z;// << std::endl; // // ::g_TitleText = strTitle.str(); // // // TODO: Add some controls to change the "selected object" // // i.e. change the ::g_selectedObject value // // // }//if ( cGFLWKeyboardModifiers::... // If JUST the ALT is down, move the "selected" light if ( cGFLWKeyboardModifiers::isModifierDown(pWindow, false, false, true) ) { if ( glfwGetKey(pWindow, GLFW_KEY_A) == GLFW_PRESS ) { ::g_pTheLights->theLights[::g_selectedLight].position.x -= lightMovementSpeed; } // Go left if ( glfwGetKey(pWindow, GLFW_KEY_D) == GLFW_PRESS ) { ::g_pTheLights->theLights[::g_selectedLight].position.x += lightMovementSpeed; } // Go right if ( glfwGetKey(pWindow, GLFW_KEY_W) == GLFW_PRESS ) { ::g_pTheLights->theLights[::g_selectedLight].position.z += lightMovementSpeed; }// Go forward if ( glfwGetKey(pWindow, GLFW_KEY_S) == GLFW_PRESS ) { ::g_pTheLights->theLights[::g_selectedLight].position.z -= lightMovementSpeed; }// Go backwards if ( glfwGetKey(pWindow, GLFW_KEY_Q) == GLFW_PRESS ) { ::g_pTheLights->theLights[::g_selectedLight].position.y -= lightMovementSpeed; }// Go "Down" if ( glfwGetKey(pWindow, GLFW_KEY_E) == GLFW_PRESS ) { ::g_pTheLights->theLights[::g_selectedLight].position.y += lightMovementSpeed; }// Go "Up" // constant attenuation if ( glfwGetKey(pWindow, GLFW_KEY_1) == GLFW_PRESS ) { ::g_pTheLights->theLights[::g_selectedLight].atten.x *= 0.99f; // -1% less } if ( glfwGetKey(pWindow, GLFW_KEY_2) == GLFW_PRESS ) { // Is it at (or below) zero? if ( ::g_pTheLights->theLights[::g_selectedLight].atten.x <= 0.0f ) { // Set it to some really small initial attenuation ::g_pTheLights->theLights[::g_selectedLight].atten.x = 0.001f; } ::g_pTheLights->theLights[::g_selectedLight].atten.x *= 1.01f; // +1% more } // linear attenuation if ( glfwGetKey(pWindow, GLFW_KEY_3) == GLFW_PRESS ) { ::g_pTheLights->theLights[::g_selectedLight].atten.y *= 0.99f; // -1% less } if ( glfwGetKey(pWindow, GLFW_KEY_4) == GLFW_PRESS ) { // Is it at (or below) zero? if ( ::g_pTheLights->theLights[::g_selectedLight].atten.y <= 0.0f ) { // Set it to some really small initial attenuation ::g_pTheLights->theLights[::g_selectedLight].atten.y = 0.001f; } ::g_pTheLights->theLights[::g_selectedLight].atten.y *= 1.01f; // +1% more } // quadratic attenuation if ( glfwGetKey(pWindow, GLFW_KEY_5) == GLFW_PRESS ) { ::g_pTheLights->theLights[::g_selectedLight].atten.z *= 0.99f; // -1% less } if ( glfwGetKey(pWindow, GLFW_KEY_6) == GLFW_PRESS ) { // Is it at (or below) zero? if ( ::g_pTheLights->theLights[::g_selectedLight].atten.z <= 0.0f ) { // Set it to some really small initial attenuation ::g_pTheLights->theLights[::g_selectedLight].atten.z = 0.001f; } ::g_pTheLights->theLights[::g_selectedLight].atten.z *= 1.01f; // +1% more } if ( glfwGetKey(pWindow, GLFW_KEY_U) == GLFW_PRESS ) { ::g_pTheLights->theLights[0].param1.y -= 0.5f; } // Inner if ( glfwGetKey(pWindow, GLFW_KEY_I) == GLFW_PRESS ) { ::g_pTheLights->theLights[0].param1.y += 0.5f; } // Inner if ( glfwGetKey(pWindow, GLFW_KEY_O) == GLFW_PRESS ) { ::g_pTheLights->theLights[0].param1.z -= 0.5f; } // Outer if ( glfwGetKey(pWindow, GLFW_KEY_P) == GLFW_PRESS ) { ::g_pTheLights->theLights[0].param1.z += 0.5f; } // Outer // For the texture height map displacement example: const float TERRAIN_MAP_DISPLACEMENT_MOVEMENT_SPEED = 0.0005f; const float TERRAIN_MAP_DISPLACEMENT_ROTATION_SPEED = 0.0025f; if (glfwGetKey(pWindow, GLFW_KEY_UP) == GLFW_PRESS) { ::g_heightMapUVOffsetRotation.x -= TERRAIN_MAP_DISPLACEMENT_MOVEMENT_SPEED; } if (glfwGetKey(pWindow, GLFW_KEY_DOWN) == GLFW_PRESS) { ::g_heightMapUVOffsetRotation.x += TERRAIN_MAP_DISPLACEMENT_MOVEMENT_SPEED; } if (glfwGetKey(pWindow, GLFW_KEY_LEFT) == GLFW_PRESS) { ::g_heightMapUVOffsetRotation.y -= TERRAIN_MAP_DISPLACEMENT_MOVEMENT_SPEED; } if (glfwGetKey(pWindow, GLFW_KEY_RIGHT) == GLFW_PRESS) { ::g_heightMapUVOffsetRotation.y += TERRAIN_MAP_DISPLACEMENT_MOVEMENT_SPEED; } // Rotation with the num-pad "+" and "-" if (glfwGetKey(pWindow, GLFW_KEY_KP_0) == GLFW_PRESS) { ::g_heightMapUVOffsetRotation.z += TERRAIN_MAP_DISPLACEMENT_ROTATION_SPEED; } if (glfwGetKey(pWindow, GLFW_KEY_KP_DECIMAL) == GLFW_PRESS) { ::g_heightMapUVOffsetRotation.z -= TERRAIN_MAP_DISPLACEMENT_ROTATION_SPEED; } std::stringstream strTitle; // std::cout << strTitle << "Light # " << ::g_selectedLight << " positionXYZ : " << ::g_pTheLights->theLights[::g_selectedLight].position.x << ", " << ::g_pTheLights->theLights[::g_selectedLight].position.y << ", " << ::g_pTheLights->theLights[::g_selectedLight].position.z << " " << "attenuation (C, L, Q): " << ::g_pTheLights->theLights[::g_selectedLight].atten.x << ", " // Const << ::g_pTheLights->theLights[::g_selectedLight].atten.y << ", " // Linear << ::g_pTheLights->theLights[::g_selectedLight].atten.z << " " // Quadratic << (::g_pTheLights->theLights[::g_selectedLight].param2.x > 0.0f ? " is on" : " is off"); //<< std::endl; ::g_TitleText = strTitle.str(); }//if ( cGFLWKeyboardModifiers::... return; } // We call these every frame void handleAsyncMouse(GLFWwindow* window, double deltaTime) { double x, y; glfwGetCursorPos(window, &x, &y); ::g_pFlyCamera->setMouseXY(x, y); const float MOUSE_SENSITIVITY = 2.0f; // Mouse left (primary?) button pressed? // AND the mouse is inside the window... if ( (glfwGetMouseButton(window, GLFW_MOUSE_BUTTON_LEFT) == GLFW_PRESS) && ::g_MouseIsInsideWindow ) { // Mouse button is down so turn the camera ::g_pFlyCamera->Yaw_LeftRight( ::g_pFlyCamera->getDeltaMouseX() * MOUSE_SENSITIVITY, deltaTime ); ::g_pFlyCamera->Pitch_UpDown( -::g_pFlyCamera->getDeltaMouseY() * MOUSE_SENSITIVITY, deltaTime ); } // Adjust the mouse speed if ( ::g_MouseIsInsideWindow ) { const float MOUSE_WHEEL_SENSITIVITY = 0.1f; // Adjust the movement speed based on the wheel position ::g_pFlyCamera->movementSpeed -= ( ::g_pFlyCamera->getMouseWheel() * MOUSE_WHEEL_SENSITIVITY ); // Clear the mouse wheel delta (or it will increase constantly) ::g_pFlyCamera->clearMouseWheelValue(); if ( ::g_pFlyCamera->movementSpeed <= 0.0f ) { ::g_pFlyCamera->movementSpeed = 0.0f; } } return; } void GLFW_cursor_enter_callback(GLFWwindow* window, int entered) { if ( entered ) { std::cout << "Mouse cursor is over the window" << std::endl; ::g_MouseIsInsideWindow = true; } else { std::cout << "Mouse cursor is no longer over the window" << std::endl; ::g_MouseIsInsideWindow = false; } return; } // Called when the mouse scroll wheel is moved void GLFW_scroll_callback(GLFWwindow* window, double xoffset, double yoffset) { float mouseScrollWheelSensitivity = 0.1f; ::g_pFlyCamera->setMouseWheelDelta(yoffset * mouseScrollWheelSensitivity); return; } void GLFW_mouse_button_callback(GLFWwindow* window, int button, int action, int mods) { #ifdef YO_NERDS_WE_USING_WINDOWS_CONTEXT_MENUS_IN_THIS_THANG // Right button is pop-up if ( button == GLFW_MOUSE_BUTTON_RIGHT && action == GLFW_PRESS ) { ShowWindowsContextMenu(window, button, action, mods); } #endif return; } void GLFW_cursor_position_callback(GLFWwindow* window, double xpos, double ypos) { return; }
43.489529
169
0.614398
[ "object" ]
07421fda6be5c36e708708d1d0f898009ea31e1a
10,930
cc
C++
src/dfpnstat.cc
qhapaq-49/checkmate-gps-osl
1e54aa890f942c1e09525d44a0c18033a42bc952
[ "MIT" ]
null
null
null
src/dfpnstat.cc
qhapaq-49/checkmate-gps-osl
1e54aa890f942c1e09525d44a0c18033a42bc952
[ "MIT" ]
null
null
null
src/dfpnstat.cc
qhapaq-49/checkmate-gps-osl
1e54aa890f942c1e09525d44a0c18033a42bc952
[ "MIT" ]
null
null
null
#include "osl/checkmate/dfpn.h" #include "osl/checkmate/dfpnParallel.h" #include "osl/csa.h" #include "osl/misc/perfmon.h" #include "osl/misc/milliSeconds.h" #include "osl/checkmate/dfpnRecord.h" #include "osl/hash/hashRandomPair.h" #include "osl/oslConfig.h" #include <string> #include <iostream> #include <iomanip> #include <fstream> #include <cstdlib> #include <unistd.h> #include <utility> #include <vector> #include <bitset> using namespace osl; using namespace osl::checkmate; using namespace osl::misc; unsigned int dovetailing_seed = 0; unsigned int dovetailing_prob = 0; bool verbose = false; unsigned long long total_cycles = 0; bool show_escape_filename = false; bool force_attack = false; int num_checkmate = 0, num_nocheckmate = 0, num_escape = 0, num_unkown = 0; double total_nodes = 0, total_tables = 0; int limit = 100000; bool blocking_verify = true; size_t table_growth_limit = 8000000; bool debug = false; int forward_moves = 0; template <class DfpnSearch> void search(DfpnSearch &, const char *filename); void usage(const char *program_name) { std::cerr << "usage: " << program_name << " [-d] [-v] [-f] [-l limit] [-N] csa-files\n"; } int main(int argc, char **argv) { const char *program_name = argv[0]; bool error_flag = false; int parallel = 0; extern char *optarg; extern int optind; char c; while ((c = getopt(argc, argv, "dfl:N:F:s:p:t:vh")) != EOF) { switch (c) { case 's': dovetailing_seed = static_cast<unsigned int>(atoi(optarg)); break; case 'p': dovetailing_prob = static_cast<unsigned int>(atoi(optarg)); break; case 'd': debug = true; break; case 'f': force_attack = true; break; case 'F': forward_moves = atoi(optarg); break; case 'l': limit = atoi(optarg); break; case 'N': parallel = atoi(optarg); break; case 't': table_growth_limit = atoi(optarg); break; #if 0 case 'V': blocking_verify = false; break; #endif case 'v': verbose = true; break; default: error_flag = true; } } argc -= optind; argv += optind; if (error_flag || (argc < 1)) { usage(program_name); return 1; } osl::OslConfig::setUp(); OslConfig::setDfpnMaxDepth(1600); // sufficient for microcosmos if (dovetailing_prob > 0) HashRandomPair::setUp(dovetailing_seed, dovetailing_prob); try { for (int i = 0; i < argc; ++i) { if (parallel) { #ifdef OSL_DFPN_SMP DfpnParallel dfpn(parallel); search(dfpn, argv[i]); #else std::cerr << "to use parallel dfpn, try compile with -DOSL_SMP or -DOSL_DFPN_SMP\n"; return 1; #endif } else { Dfpn dfpn; search(dfpn, argv[i]); } total_cycles = 0; } std::cerr << "check " << num_checkmate << " nocheckmate " << num_nocheckmate << " escape " << num_escape << " unknown " << num_unkown << "\n"; std::cerr << "total nodes " << total_nodes << " tables " << total_tables << "\n"; } catch (std::exception &e) { std::cerr << e.what() << "\n"; return 1; } } double real_seconds = 0.0; template <class DfpnSearch> void analyzeCheckmatePV(DfpnSearch &searcher, const NumEffectState &state, Move checkmate_move) { Move ply_move = checkmate_move; NumEffectState new_state = state; while(1){ if(ply_move.isInvalid()){ break; } std::cerr <<ply_move <<" "; new_state.makeMove(ply_move); MoveVector moves; new_state.generateLegal(moves); if(moves.size()==0){ break; } HashKey key(new_state); const DfpnTable &table = searcher.currentTable(); DfpnRecordBase record = table.probe(key, PieceStand(WHITE, new_state)); ply_move = record.best_move; } std::cerr<<std::endl<<new_state<<std::endl; } template <class DfpnSearch> std::pair<int, std::vector<Move>> get_depth_reaction(DfpnSearch &searcher, const NumEffectState &state, Move checkmate_move, const int depth){ if ( checkmate_move.isInvalid()){ std::vector<Move> output; return {depth, output}; } NumEffectState new_state = state; new_state.makeMove(checkmate_move); MoveVector moves; new_state.generateLegal(moves); if(moves.size()==0){ std::vector<Move> output = {checkmate_move}; return {depth, output}; } int max_v = -1; Move max_move; std::vector<Move> best_pv; for (size_t i = 0; i < moves.size(); ++i) { NumEffectState tmp = new_state; tmp.makeMove(moves[i]); HashKey key(tmp); const DfpnTable &table = searcher.currentTable(); DfpnRecordBase record = table.probe(key, PieceStand(WHITE, tmp)); std::pair<int, std::vector<Move>> res = get_depth_reaction(searcher, tmp, record.best_move, depth + 1); int v = res.first; if(v > max_v){ max_v = v; best_pv = res.second; max_move = moves[i]; } } std::vector<Move> output = best_pv; output.push_back(max_move); output.push_back(checkmate_move); return {max_v, output}; } template <class DfpnSearch> void analyzeCheckmate3(DfpnSearch &searcher, const NumEffectState &state, Move checkmate_move) { std::pair<int, std::vector<Move>> out = get_depth_reaction(searcher, state, checkmate_move, 0); std::cout<<"maxdepth"<<out.second.size()<<std::endl; for(int i=0;i<out.second.size();++i){ std::cout<<out.second[out.second.size()-1-i]<<" "; } } template <class DfpnSearch> void analyzeCheckmate(DfpnSearch &searcher, const NumEffectState &state, Move checkmate_move) { NumEffectState new_state = state; std::cerr << state << " " << checkmate_move << "\n"; new_state.makeMove(checkmate_move); HashKey key(new_state); const DfpnTable &table = searcher.currentTable(); DfpnRecordBase record = table.probe(key, PieceStand(WHITE, new_state)); std::cerr << record.proof_disproof << " " << std::bitset<64>(record.solved) << "\n"; MoveVector moves; new_state.generateLegal(moves); for (size_t i = 0; i < moves.size(); ++i) { NumEffectState tmp = new_state; tmp.makeMove(moves[i]); DfpnRecordBase record = table.probe(key.newHashWithMove(moves[i]), PieceStand(WHITE, tmp)); std::cerr << moves[i] << " " << record.proof_disproof << " " << record.best_move << "\n"; } { Dfpn::DfpnMoveVector moves; if (state.turn() == BLACK) Dfpn::generateEscape<BLACK>(new_state, false, Square(), moves); else Dfpn::generateEscape<WHITE>(new_state, false, Square(), moves); std::cerr << "Escape " << moves.size() << "\n"; moves.clear(); if (state.turn() == BLACK) Dfpn::generateEscape<BLACK>(new_state, true, Square(), moves); else Dfpn::generateEscape<BLACK>(new_state, true, Square(), moves); std::cerr << "Escape full " << moves.size() << "\n"; } } template <class DfpnSearch> void testWinOrLose(const char *filename, DfpnSearch &searcher, const SimpleState &sstate, int limit, ProofDisproof &result, Move &best_move, const std::vector<Move> &moves) { const Player P = sstate.turn(); NumEffectState state(sstate); const PathEncoding path(state.turn()); const Square my_king = state.kingSquare(P); if ((!force_attack) && !my_king.isPieceStand() && state.inCheck(P)) { // 相手から王手がかかっている time_point timer = clock::now(); misc::PerfMon clock; result = searcher.hasEscapeMove(state, HashKey(state), path, limit, Move::PASS(alt(P))); total_cycles += clock.stop(); real_seconds = elapsedSeconds(timer); if (verbose) std::cerr << result << "\n"; if (result.isCheckmateSuccess()) { ++num_checkmate; } else { if (result.isCheckmateFail()) ++num_escape; else { assert(!result.isFinal()); ++num_unkown; } } return; } Move checkmate_move; std::vector<Move> pv; time_point timer = clock::now(); PerfMon clock; result = searcher.hasCheckmateMove(state, HashKey(state), path, limit, checkmate_move, Move(), &pv); total_cycles += clock.stop(); real_seconds = elapsedSeconds(timer); if (verbose) std::cerr << result << "\n"; if (result.isCheckmateSuccess()) { ++num_checkmate; best_move = checkmate_move; if (verbose) { std::cerr << checkmate_move << "\n"; for (size_t i = 0; i < pv.size(); ++i) { std::cerr << std::setw(4) << std::setfill(' ') << i + 1 << ' ' << csa::show(pv[i]) << " "; if (i % 6 == 5) std::cerr << "\n"; } if (pv.size() % 6 != 0) std::cerr << "\n"; } if (debug) { // analyzeCheckmatePV(searcher, state, checkmate_move); analyzeCheckmate3(searcher, state, checkmate_move); if (!moves.empty()) searcher.analyze(path, state, moves); } } else { if (result.isFinal()) ++num_nocheckmate; else ++num_unkown; if (debug) searcher.analyze(path, state, moves); } } template <class DfpnSearch> void search(DfpnSearch &searcher, const char *filename) { NumEffectState state; std::vector<Move> moves; try { CsaFileMinimal file(filename); state = file.initialState(); moves = file.moves(); int forward_here = std::min(forward_moves, (int)moves.size()); for (int i = 0; i < forward_here; ++i) state.makeMove(moves[i]); moves.erase(moves.begin(), moves.begin() + forward_here); } catch (CsaIOError &) { std::cerr << "\nskipping " << filename << "\n"; return; } if (verbose) std::cerr << "\nsolving " << filename << "\n"; // searcher.setBlockingVerify(blocking_verify); const bool attack = force_attack || state.kingSquare(state.turn()).isPieceStand() || !state.inCheck(state.turn()); DfpnTable table(attack ? state.turn() : alt(state.turn())); table.setGrowthLimit(table_growth_limit); searcher.setTable(&table); ProofDisproof result; Move best_move; testWinOrLose(filename, searcher, state, limit, result, best_move, moves); const size_t table_used = searcher.currentTable().size(); total_nodes += searcher.nodeCount(); total_tables += table_used; if (verbose) { PerfMon::message(total_cycles, "total ", searcher.nodeCount()); PerfMon::message(total_cycles, "unique", table_used); std::cerr << "real " << real_seconds << " sec. nps " << searcher.nodeCount() / real_seconds << "\n"; } std::cout << filename << "\t" << searcher.nodeCount() << "\t" << table_used << "\t" << real_seconds << " " << result; if (best_move.isNormal()) std::cout << " " << csa::show(best_move); std::cout << "\n" << std::flush; } /* ------------------------------------------------------------------------- */ // ;;; Local Variables: // ;;; mode:c++ // ;;; c-basic-offset:2 // ;;; coding:utf-8 // ;;; End:
27.531486
142
0.616102
[ "vector" ]
0744e5eecf220cbaa5f882e8e164bd2cc830a812
7,965
cpp
C++
third_party/WebKit/Source/core/loader/modulescript/ModuleScriptLoaderTest.cpp
metux/chromium-deb
3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
third_party/WebKit/Source/core/loader/modulescript/ModuleScriptLoaderTest.cpp
metux/chromium-deb
3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
third_party/WebKit/Source/core/loader/modulescript/ModuleScriptLoaderTest.cpp
metux/chromium-deb
3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
// 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 "core/loader/modulescript/ModuleScriptLoader.h" #include "bindings/core/v8/V8BindingForCore.h" #include "core/dom/Document.h" #include "core/dom/Modulator.h" #include "core/dom/ModuleScript.h" #include "core/loader/modulescript/ModuleScriptFetchRequest.h" #include "core/loader/modulescript/ModuleScriptLoaderClient.h" #include "core/loader/modulescript/ModuleScriptLoaderRegistry.h" #include "core/testing/DummyModulator.h" #include "core/testing/DummyPageHolder.h" #include "platform/heap/Handle.h" #include "platform/loader/fetch/ResourceFetcher.h" #include "platform/loader/testing/FetchTestingPlatformSupport.h" #include "platform/loader/testing/MockFetchContext.h" #include "platform/testing/URLTestHelpers.h" #include "platform/testing/UnitTestHelpers.h" #include "public/platform/Platform.h" #include "public/platform/WebURLLoaderMockFactory.h" #include "testing/gtest/include/gtest/gtest.h" namespace blink { namespace { class TestModuleScriptLoaderClient final : public GarbageCollectedFinalized<TestModuleScriptLoaderClient>, public ModuleScriptLoaderClient { USING_GARBAGE_COLLECTED_MIXIN(TestModuleScriptLoaderClient); public: TestModuleScriptLoaderClient() = default; ~TestModuleScriptLoaderClient() override {} DEFINE_INLINE_TRACE() { visitor->Trace(module_script_); } void NotifyNewSingleModuleFinished(ModuleScript* module_script) override { was_notify_finished_ = true; module_script_ = module_script; } bool WasNotifyFinished() const { return was_notify_finished_; } ModuleScript* GetModuleScript() { return module_script_; } private: bool was_notify_finished_ = false; Member<ModuleScript> module_script_; }; class ModuleScriptLoaderTestModulator final : public DummyModulator { public: ModuleScriptLoaderTestModulator(RefPtr<ScriptState> script_state, RefPtr<SecurityOrigin> security_origin) : script_state_(std::move(script_state)), security_origin_(std::move(security_origin)) {} ~ModuleScriptLoaderTestModulator() override {} SecurityOrigin* GetSecurityOrigin() override { return security_origin_.Get(); } ScriptState* GetScriptState() override { return script_state_.Get(); } ScriptModule CompileModule(const String& script, const String& url_str, AccessControlStatus access_control_status, const TextPosition& position, ExceptionState& exception_state) override { ScriptState::Scope scope(script_state_.Get()); return ScriptModule::Compile( script_state_->GetIsolate(), "export default 'foo';", "", access_control_status, TextPosition::MinimumPosition(), exception_state); } void SetModuleRequests(const Vector<String>& requests) { requests_.clear(); for (const String& request : requests) { requests_.emplace_back(request, TextPosition::MinimumPosition()); } } Vector<ModuleRequest> ModuleRequestsFromScriptModule(ScriptModule) override { return requests_; } ScriptModuleState GetRecordStatus(ScriptModule) override { return ScriptModuleState::kUninstantiated; } DECLARE_TRACE(); private: RefPtr<ScriptState> script_state_; RefPtr<SecurityOrigin> security_origin_; Vector<ModuleRequest> requests_; }; DEFINE_TRACE(ModuleScriptLoaderTestModulator) { DummyModulator::Trace(visitor); } } // namespace class ModuleScriptLoaderTest : public ::testing::Test { DISALLOW_COPY_AND_ASSIGN(ModuleScriptLoaderTest); public: ModuleScriptLoaderTest() = default; void SetUp() override; LocalFrame& GetFrame() { return dummy_page_holder_->GetFrame(); } Document& GetDocument() { return dummy_page_holder_->GetDocument(); } ResourceFetcher* Fetcher() { return fetcher_.Get(); } ModuleScriptLoaderTestModulator* GetModulator() { return modulator_.Get(); } protected: ScopedTestingPlatformSupport<FetchTestingPlatformSupport> platform_; std::unique_ptr<DummyPageHolder> dummy_page_holder_; Persistent<ResourceFetcher> fetcher_; Persistent<ModuleScriptLoaderTestModulator> modulator_; }; void ModuleScriptLoaderTest::SetUp() { platform_->AdvanceClockSeconds(1.); // For non-zero DocumentParserTimings dummy_page_holder_ = DummyPageHolder::Create(IntSize(500, 500)); GetDocument().SetURL(KURL(NullURL(), "https://example.test")); auto* context = MockFetchContext::Create(MockFetchContext::kShouldLoadNewResource); fetcher_ = ResourceFetcher::Create(context); modulator_ = new ModuleScriptLoaderTestModulator( ToScriptStateForMainWorld(&GetFrame()), GetDocument().GetSecurityOrigin()); } TEST_F(ModuleScriptLoaderTest, fetchDataURL) { ModuleScriptLoaderRegistry* registry = ModuleScriptLoaderRegistry::Create(); KURL url(NullURL(), "data:text/javascript,export default 'grapes';"); ModuleScriptFetchRequest module_request( url, String(), kParserInserted, WebURLRequest::kFetchCredentialsModeOmit); TestModuleScriptLoaderClient* client = new TestModuleScriptLoaderClient; registry->Fetch(module_request, ModuleGraphLevel::kTopLevelModuleFetch, GetModulator(), Fetcher(), client); EXPECT_TRUE(client->WasNotifyFinished()) << "ModuleScriptLoader should finish synchronously."; ASSERT_TRUE(client->GetModuleScript()); EXPECT_FALSE(client->GetModuleScript()->IsErrored()); } TEST_F(ModuleScriptLoaderTest, InvalidSpecifier) { ModuleScriptLoaderRegistry* registry = ModuleScriptLoaderRegistry::Create(); KURL url(NullURL(), "data:text/javascript,import 'invalid';export default 'grapes';"); ModuleScriptFetchRequest module_request( url, String(), kParserInserted, WebURLRequest::kFetchCredentialsModeOmit); TestModuleScriptLoaderClient* client = new TestModuleScriptLoaderClient; GetModulator()->SetModuleRequests({"invalid"}); registry->Fetch(module_request, ModuleGraphLevel::kTopLevelModuleFetch, GetModulator(), Fetcher(), client); EXPECT_TRUE(client->WasNotifyFinished()) << "ModuleScriptLoader should finish synchronously."; ASSERT_TRUE(client->GetModuleScript()); EXPECT_TRUE(client->GetModuleScript()->IsErrored()); } TEST_F(ModuleScriptLoaderTest, fetchInvalidURL) { ModuleScriptLoaderRegistry* registry = ModuleScriptLoaderRegistry::Create(); KURL url; EXPECT_FALSE(url.IsValid()); ModuleScriptFetchRequest module_request( url, String(), kParserInserted, WebURLRequest::kFetchCredentialsModeOmit); TestModuleScriptLoaderClient* client = new TestModuleScriptLoaderClient; registry->Fetch(module_request, ModuleGraphLevel::kTopLevelModuleFetch, GetModulator(), Fetcher(), client); EXPECT_TRUE(client->WasNotifyFinished()) << "ModuleScriptLoader should finish synchronously."; EXPECT_FALSE(client->GetModuleScript()); } TEST_F(ModuleScriptLoaderTest, fetchURL) { KURL url(kParsedURLString, "http://127.0.0.1:8000/module.js"); URLTestHelpers::RegisterMockedURLLoad( url, testing::CoreTestDataPath("module.js"), "text/javascript"); ModuleScriptLoaderRegistry* registry = ModuleScriptLoaderRegistry::Create(); ModuleScriptFetchRequest module_request( url, String(), kParserInserted, WebURLRequest::kFetchCredentialsModeOmit); TestModuleScriptLoaderClient* client = new TestModuleScriptLoaderClient; registry->Fetch(module_request, ModuleGraphLevel::kTopLevelModuleFetch, GetModulator(), Fetcher(), client); EXPECT_FALSE(client->WasNotifyFinished()) << "ModuleScriptLoader unexpectedly finished synchronously."; platform_->GetURLLoaderMockFactory()->ServeAsynchronousRequests(); EXPECT_TRUE(client->WasNotifyFinished()); EXPECT_FALSE(client->GetModuleScript()); } } // namespace blink
38.478261
80
0.758569
[ "vector" ]
0751ed55e3b3695c9b32c4fb24843def0361befd
38,110
cpp
C++
Benchmarks/Applications/AugmentedReality/AugmentedReality.cpp
jlclemon/MEVBench
da7621b9eb1e92eec37a77dd1c7b69320cffcee1
[ "BSD-3-Clause" ]
8
2015-03-16T18:16:35.000Z
2020-10-30T06:35:31.000Z
Benchmarks/Applications/AugmentedReality/AugmentedReality.cpp
jlclemon/MEVBench
da7621b9eb1e92eec37a77dd1c7b69320cffcee1
[ "BSD-3-Clause" ]
null
null
null
Benchmarks/Applications/AugmentedReality/AugmentedReality.cpp
jlclemon/MEVBench
da7621b9eb1e92eec37a77dd1c7b69320cffcee1
[ "BSD-3-Clause" ]
3
2016-03-17T08:27:13.000Z
2020-10-30T06:46:50.000Z
/* * AugmentedReality.cpp * * Created on: May 25, 2011 * Author: jlclemon */ #include "AugmentedReality.hpp" #ifdef USE_MARSS #warning "Using MARSS" #include "ptlcalls.h" #endif #ifdef USE_GEM5 #warning "Using GEM5" extern "C" { #include "m5op.h" } #endif #define TIMING_MAX_NUMBER_OF_THREADS 256 //#define TSC_TIMING #ifdef TSC_TIMING #include "tsc_class.hpp" #endif //#define CLOCK_GETTIME_TIMING #ifdef CLOCK_GETTIME_TIMING #include "time.h" #ifndef GET_TIME_WRAPPER #define GET_TIME_WRAPPER(dataStruct) clock_gettime(CLOCK_THREAD_CPUTIME_ID, &dataStruct) #endif #endif #ifdef TSC_TIMING vector<TSC_VAL_w> aug_timingVector; #endif #ifdef CLOCK_GETTIME_TIMING vector<struct timespec> aug_timeStructVector; #endif #ifdef TSC_TIMING void aug_writeTimingToFile(vector<TSC_VAL_w> timingVector) { ofstream outputFile; outputFile.open("timing.csv"); outputFile << "Thread,Start,Finish,Mid" << endl; for(int i = 0; i<(TIMING_MAX_NUMBER_OF_THREADS); i++) { outputFile << i << "," << timingVector[i] << "," << timingVector[i+TIMING_MAX_NUMBER_OF_THREADS]<< ","<< timingVector[i+2*TIMING_MAX_NUMBER_OF_THREADS] << endl; } outputFile.close(); } #endif #ifdef CLOCK_GETTIME_TIMING void aug_writeTimingToFile(vector<struct timespec> timingVector) { ofstream outputFile; outputFile.open("timing.csv"); outputFile << "Thread,Start sec, Start nsec,Finish sec, Finish nsec,Mid sec, Mid nsec" << endl; for(int i = 0; i<(TIMING_MAX_NUMBER_OF_THREADS); i++) { outputFile << i << "," << timingVector[i].tv_sec<<","<< timingVector[i].tv_nsec << "," << timingVector[i+TIMING_MAX_NUMBER_OF_THREADS].tv_sec<<","<< timingVector[i+TIMING_MAX_NUMBER_OF_THREADS].tv_nsec<< "," << timingVector[i+2*TIMING_MAX_NUMBER_OF_THREADS].tv_sec<<","<< timingVector[i+2*TIMING_MAX_NUMBER_OF_THREADS].tv_nsec <<endl; } outputFile.close(); } #endif void readFileListFromFile(string fileListFilename, string filesBaseDir,vector<string> &fileList) { ifstream fileListFile; fileListFile.open(fileListFilename.c_str(),ios::in); if(fileListFile.is_open()) { while(fileListFile.good()) { string currentLine; getline(fileListFile,currentLine); if(currentLine != "") { fileList.push_back(filesBaseDir+currentLine); } } fileListFile.close(); } } bool loadAugmentedRealityConfigFile(vector<string> &commandArgs, string filename) { std::ifstream configFile; int i = 3; string tmpString; bool returnVal = false; configFile.open(filename.c_str()); if(configFile.good()) { while(!configFile.eof()) { getline(configFile,tmpString); commandArgs.push_back(tmpString); } returnVal = true; cout << "Config file loaded!!!" << endl; } else { cout << "WARNING: Unable to open classification params config file" << endl; } return returnVal; } void parseAugmentedRealityConfigCommandVector(AugmentedRealityConfig & augmentedRealityConfig, vector<string> & commandStringVector) { vector<string>::iterator it_start = commandStringVector.begin(); vector<string>::iterator it_end = commandStringVector.end(); vector<string>::iterator it_current; stringstream stringBuffer; augmentedRealityConfig.cameraId[0] = 1; augmentedRealityConfig.cameraId[1] = 0; augmentedRealityConfig.inputMethod =AUGMENT_REAL_SINGLE_STREAM; augmentedRealityConfig.calibFilename = ""; augmentedRealityConfig.outputRawImageExt = ".png"; augmentedRealityConfig.outputRawImageBaseName = ""; augmentedRealityConfig.outputAugImageExt = ".png"; augmentedRealityConfig.outputAugImageBaseName = ""; augmentedRealityConfig.longList = false; augmentedRealityConfig.bufferedImageList = false; augmentedRealityConfig.showWindows = false; augmentedRealityConfig.noWaitKey = false; augmentedRealityConfig.pauseMode = false; augmentedRealityConfig.markerLostFrameCount = 10; augmentedRealityConfig.numberOfListLoops = 20; augmentedRealityConfig.tracking = false; //-desc sift -match knn_flann -classify linear_svm -queryDescFile test.yml -trainDescFile test.yml -loadClassificationStruct test.yml -loadMatchStruct test.yml for(it_current=it_start; it_current!=it_end; ++it_current) { if(!it_current->compare("-inputMethod") || !it_current->compare("-InputMethod")) { if(!(it_current+1)->compare("monoStream")) { augmentedRealityConfig.inputMethod=AUGMENT_REAL_SINGLE_STREAM; } if(!(it_current+1)->compare("stereoStream")) { augmentedRealityConfig.inputMethod=AUGMENT_REAL_STEREO_STREAM; } if(!(it_current+1)->compare("imageFileList")) { augmentedRealityConfig.useImageList = true; augmentedRealityConfig.inputMethod=AUGMENT_REAL_IMAGE_FILE_LIST; } if(!(it_current+1)->compare("videoFile")) { augmentedRealityConfig.inputMethod=AUGMENT_REAL_VIDEO_FILE; } } if(!it_current->compare("-camera0") || !it_current->compare("-Camera0")) { stringBuffer.str(""); stringBuffer << *(it_current+1); if((stringBuffer >> augmentedRealityConfig.cameraId[0]).fail()) { cout << "Camera0 Id could not be parsed." << endl; } } if(!it_current->compare("-camera1") || !it_current->compare("-Camera1")) { stringBuffer.str(""); stringBuffer << *(it_current+1); if((stringBuffer >> augmentedRealityConfig.cameraId[1]).fail()) { cout << "Camera0 Id could not be parsed." << endl; } } if(!it_current->compare("-imageList") || !it_current->compare("-ImageList")) { augmentedRealityConfig.imageListFilename = *(it_current+1); } if(!it_current->compare("-imageListBaseDir") || !it_current->compare("-ImageListBaseDir")) { augmentedRealityConfig.imageListBaseDir = *(it_current+1); } if(!it_current->compare("-markerLostFrameCount")) { stringBuffer.str(""); stringBuffer.clear(); stringBuffer << *(it_current+1); if((stringBuffer >> augmentedRealityConfig.markerLostFrameCount).fail()) { cout << "Number of missing frames before marker considered lost could not be parsed" << endl; } } if(!it_current->compare("-nVertCores")) { stringBuffer.str(""); stringBuffer.clear(); stringBuffer << *(it_current+1); cout << *(it_current+1) << endl; if((stringBuffer >> augmentedRealityConfig.numberOfVerticalProcs).fail()) { cout << "Number of vertical cores could not be parsed." << endl; } } if(!it_current->compare("-nHoriCores")) { stringBuffer.str(""); stringBuffer.clear(); stringBuffer << *(it_current+1); cout << *(it_current+1) << endl; if((stringBuffer >> augmentedRealityConfig.numberOfHorizontalProcs).fail()) { cout << "Number of horizontal cores could not be parsed." << endl; } } if(!it_current->compare("-calibFile")) { augmentedRealityConfig.calibFilename = *(it_current+1); } if( it_current->compare("-singleThreaded") == 0 || it_current->compare("-SingleThreaded") == 0) { augmentedRealityConfig.singleThreaded= true; } if( it_current->compare("-showWindows") == 0 || it_current->compare("-ShowWindows") == 0) { augmentedRealityConfig.showWindows = true; } if( it_current->compare("-noWaitKey") == 0 || it_current->compare("-NoWaitKey") == 0) { augmentedRealityConfig.noWaitKey = true; } if( it_current->compare("-bufferedImageList") == 0 || it_current->compare("-BufferedImageList") == 0) { augmentedRealityConfig.bufferedImageList = true; } if(!it_current->compare("-inputVideoFile") || !it_current->compare("-InputVideoFile")) { augmentedRealityConfig.inputVideoFilename = *(it_current+1); } if(!it_current->compare("-outputRawVideoFile") || !it_current->compare("-OutputRawVideoFile")) { augmentedRealityConfig.outputRawStreamFilename = *(it_current+1); } if(!it_current->compare("-outputAugmentedVideoFile") || !it_current->compare("-OutputAugmentedVideoFile")) { augmentedRealityConfig.outputAugmentedStreamFilename = *(it_current+1); } if(!it_current->compare("-outputRawImageBaseName") || !it_current->compare("-OutputRawImageBaseName")) { augmentedRealityConfig.outputRawImageBaseName = *(it_current+1); } if(!it_current->compare("-outputRawImageExt") || !it_current->compare("-OutputRawImageExt")) { augmentedRealityConfig.outputRawImageExt = *(it_current+1); } if(!it_current->compare("-outputAugImageBaseName") || !it_current->compare("-OutputAugImageBaseName")) { augmentedRealityConfig.outputAugImageBaseName = *(it_current+1); } if(!it_current->compare("-outputAugImageExt") || !it_current->compare("-OutputAugImageExt")) { augmentedRealityConfig.outputAugImageExt = *(it_current+1); } if(!it_current->compare("-pauseMode") || !it_current->compare("-PauseMode")) { augmentedRealityConfig.pauseMode = true; } if(!it_current->compare("-no-pauseMode") || !it_current->compare("-No-pauseMode")) { augmentedRealityConfig.pauseMode = false; } if(!it_current->compare("-no-tracking") || !it_current->compare("-No-tracking")) { augmentedRealityConfig.tracking = false; } if(!it_current->compare("-tracking") || !it_current->compare("-tracking")) { augmentedRealityConfig.tracking = true; } if(!it_current->compare("-longList") || !it_current->compare("-LongList")) { augmentedRealityConfig.longList = true; stringBuffer.str(""); stringBuffer.clear(); stringBuffer << *(it_current+1); cout << *(it_current+1) << endl; if((stringBuffer >> augmentedRealityConfig.numberOfListLoops).fail()) { cout << "Number of list Loops could not be parsed." << endl; } } } if(augmentedRealityConfig.numberOfVerticalProcs ==1 && augmentedRealityConfig.numberOfHorizontalProcs ==1) { augmentedRealityConfig.singleThreaded = true; } else { augmentedRealityConfig.singleThreaded = false; } augmentedRealityConfig.bufferedImageListBufferSize = 5; return; } void augmentedRealitySetupOutput( AugmentedRealityConfig &augmentedRealityConfig, AugmentedRealityData &augmentedRealityData) { if(augmentedRealityConfig.outputRawStreamFilename!= "") { augmentedRealityData.rawStreamWriter.open(augmentedRealityConfig.outputRawStreamFilename,CV_FOURCC('M','J','P','G'),30.0,augmentedRealityData.frameSize,true); } if(augmentedRealityConfig.outputAugmentedStreamFilename!= "") { augmentedRealityData.augmentedStreamWriter.open(augmentedRealityConfig.outputAugmentedStreamFilename,CV_FOURCC('P','I','M','1'),30.0,augmentedRealityData.frameSize, true); } if(augmentedRealityConfig.outputRawImageBaseName != "") { augmentedRealityData.currentOutputRawImageId = 0; } if(augmentedRealityConfig.outputAugImageBaseName != "") { augmentedRealityData.currentOutputAugImageId = 0; } } void augmentedRealityHandleWritingOutput( AugmentedRealityConfig &augmentedRealityConfig, AugmentedRealityData &augmentedRealityData) { if(augmentedRealityData.rawStreamWriter.isOpened()) { augmentedRealityData.rawStreamWriter << augmentedRealityData.currentFrame[0]; } if(augmentedRealityData.augmentedStreamWriter.isOpened()) { augmentedRealityData.augmentedStreamWriter << augmentedRealityData.currentAugmentedFrame[0]; } if(augmentedRealityConfig.outputRawImageBaseName != "") { stringstream streamForId; string currentOutputId; streamForId << "_" <<augmentedRealityData.currentOutputRawImageId; streamForId >> currentOutputId; string imageFileName = augmentedRealityConfig.outputRawImageBaseName + currentOutputId + augmentedRealityConfig.outputRawImageExt; imwrite(imageFileName,augmentedRealityData.currentFrame[0]); augmentedRealityData.currentOutputRawImageId++; } if(augmentedRealityConfig.outputAugImageBaseName != "") { stringstream streamForId; string currentOutputId; streamForId << "_" <<augmentedRealityData.currentOutputAugImageId; streamForId >> currentOutputId; string imageFileName = augmentedRealityConfig.outputAugImageBaseName + currentOutputId + augmentedRealityConfig.outputAugImageExt; imwrite(imageFileName,augmentedRealityData.currentAugmentedFrame[0]); augmentedRealityData.currentOutputAugImageId++; } } void augmentedRealitySetupInput( AugmentedRealityConfig &augmentedRealityConfig, AugmentedRealityData &augmentedRealityData) { switch(augmentedRealityConfig.inputMethod) { case AUGMENT_REAL_VIDEO_FILE: { break; } case AUGMENT_REAL_STEREO_STREAM: { break; } case AUGMENT_REAL_IMAGE_FILE_LIST: { if(augmentedRealityConfig.imageListFilename != "") { readFileListFromFile(augmentedRealityConfig.imageListFilename , augmentedRealityConfig.imageListBaseDir,augmentedRealityData.imageList); augmentedRealityData.currentInputImageId = 0; if(augmentedRealityConfig.bufferedImageList) { for(int i = augmentedRealityData.currentInputImageId; ((i < augmentedRealityConfig.bufferedImageListBufferSize)&& (i<augmentedRealityData.imageList.size())); i++) { augmentedRealityData.imageListBuffer[0].push_back(imread(augmentedRealityData.imageList[i])); } } } else { cout << "Invalid image list." << endl; exit(0); } Mat tmpFrameForSize = imread(augmentedRealityData.imageList[augmentedRealityData.currentInputImageId]); augmentedRealityData.frameSize.width = tmpFrameForSize.cols; augmentedRealityData.frameSize.height = tmpFrameForSize.rows; augmentedRealityData.currentListLoop = 0; break; } case AUGMENT_REAL_SINGLE_STREAM: default: { augmentedRealityData.capture[0].open(augmentedRealityConfig.cameraId[0]); if(!augmentedRealityData.capture[0].isOpened()) { cout << "Error: Unable to opeb input stream" << endl; exit(0); } augmentedRealityData.frameSize.width = augmentedRealityData.capture[0].get(CV_CAP_PROP_FRAME_WIDTH); augmentedRealityData.frameSize.height = augmentedRealityData.capture[0].get(CV_CAP_PROP_FRAME_HEIGHT); break; } }; } void setupAugmentedRealityCalibrationData(AugmentedRealityConfig &augmentedRealityConfig, AugmentedRealityData &augmentedRealityData) { augmentedRealityData.outOfImages = false; if(augmentedRealityConfig.calibFilename.compare("") != 0) { augmentedRealityData.cameraCalibration.loadCameraParams(augmentedRealityConfig.calibFilename,true,true,true); //initUndistortRectifyMap(cameraMatrix, distCoeffs, Mat(), getOptimalNewCameraMatrix(cameraMatrix, distCoeffs, imageSize, 1, imageSize, 0), imageSize, CV_16SC2, map1, map2); //initUndistortRectifyMap(augmentedRealityData.cameraCalibration.getCameraMatrix(), augmentedRealityData.cameraCalibration.getDistCoeffs(), Mat(), augmentedRealityData.cameraCalibration.getCameraMatrix(), augmentedRealityData.cameraCalibration.getImageSize(), CV_16SC2, augmentedRealityData.map1[0], augmentedRealityData.map2[0]); initUndistortRectifyMap(augmentedRealityData.cameraCalibration.getCameraMatrix(), augmentedRealityData.cameraCalibration.getDistCoeffs(), Mat(), augmentedRealityData.cameraCalibration.getCameraMatrix(), augmentedRealityData.frameSize, CV_16SC2, augmentedRealityData.map1[0], augmentedRealityData.map2[0]); cout << "Calibration file loaded" << endl; } else { cout << "Warning unable to load configuration file." << endl; } } void augmentedRealityGetNextFrames(AugmentedRealityConfig &augmentedRealityConfig, AugmentedRealityData &augmentedRealityData) { switch(augmentedRealityConfig.inputMethod) { case AUGMENT_REAL_VIDEO_FILE: { break; } case AUGMENT_REAL_STEREO_STREAM: { break; } case AUGMENT_REAL_IMAGE_FILE_LIST: { if(!augmentedRealityConfig.bufferedImageList) { if(augmentedRealityData.currentInputImageId < augmentedRealityData.imageList.size()) { augmentedRealityData.currentFrame[0] = imread(augmentedRealityData.imageList[augmentedRealityData.currentInputImageId]); } else { augmentedRealityData.currentFrame[0].release(); } } else { if(augmentedRealityData.imageListBuffer[0].size() <=0) { if(augmentedRealityData.currentInputImageId <augmentedRealityData.imageList.size()) { for(int i = augmentedRealityData.currentInputImageId; ((i < augmentedRealityConfig.bufferedImageListBufferSize)&& (i<augmentedRealityData.imageList.size())); i++) { augmentedRealityData.imageListBuffer[0].push_back(imread(augmentedRealityData.imageList[i])); } } else { if(augmentedRealityConfig.longList) { if(augmentedRealityData.currentListLoop< augmentedRealityConfig.numberOfListLoops) { augmentedRealityData.currentInputImageId = 0; for(int i = augmentedRealityData.currentInputImageId; ((i < augmentedRealityConfig.bufferedImageListBufferSize)&& (i<augmentedRealityData.imageList.size())); i++) { augmentedRealityData.imageListBuffer[0].push_back(imread(augmentedRealityData.imageList[i])); } } } else { augmentedRealityData.outOfImages = true; } } } augmentedRealityData.currentFrame[0]= augmentedRealityData.imageListBuffer[0].front(); augmentedRealityData.imageListBuffer[0].pop_front(); } augmentedRealityData.currentInputImageId++; if(augmentedRealityConfig.longList) { if(augmentedRealityData.currentInputImageId >= augmentedRealityData.imageList.size()) { augmentedRealityData.currentInputImageId = 0; augmentedRealityData.currentListLoop++; if(!(augmentedRealityData.currentListLoop< augmentedRealityConfig.numberOfListLoops)) { augmentedRealityData.outOfImages = true; } } } break; } case AUGMENT_REAL_SINGLE_STREAM: default: { augmentedRealityData.capture[0] >> augmentedRealityData.frameBuffer[0]; augmentedRealityData.currentFrame[0]=augmentedRealityData.frameBuffer[0].clone(); break; } }; if(augmentedRealityData.currentFrame[0].empty()) { augmentedRealityData.outOfImages = true; } } void getObject3DPoints(vector<Point3f> & objectPoints) { objectPoints.clear(); objectPoints.push_back(Point3f(0,0,0)); objectPoints.push_back(Point3f(0,19.6,0)); objectPoints.push_back(Point3f(19.6,19.6,0)); objectPoints.push_back(Point3f(19.6,0,0)); } void getObject3DPointsWithOrientation(vector<Point3f> & objectPoints,int normalizedOrientation) { switch(normalizedOrientation) { case 90: { objectPoints.clear(); objectPoints.push_back(Point3f(0,19.6,0)); objectPoints.push_back(Point3f(19.6,19.6,0)); objectPoints.push_back(Point3f(19.6,0,0)); objectPoints.push_back(Point3f(0,0,0)); } break; case 180: { objectPoints.clear(); objectPoints.push_back(Point3f(19.6,19.6,0)); objectPoints.push_back(Point3f(19.6,0,0)); objectPoints.push_back(Point3f(0,0,0)); objectPoints.push_back(Point3f(0,19.6,0)); } break; case 270: { objectPoints.clear(); objectPoints.push_back(Point3f(19.6,0,0)); objectPoints.push_back(Point3f(0,0,0)); objectPoints.push_back(Point3f(0,19.6,0)); objectPoints.push_back(Point3f(19.6,19.6,0)); } break; case 0: default: { objectPoints.clear(); objectPoints.push_back(Point3f(0,0,0)); objectPoints.push_back(Point3f(0,19.6,0)); objectPoints.push_back(Point3f(19.6,19.6,0)); objectPoints.push_back(Point3f(19.6,0,0)); } break; }; } void getMarkerNormalizationPoints(vector<Point2f> & normalizedPoints) { normalizedPoints.clear(); normalizedPoints.push_back(Point2f(0,0)); normalizedPoints.push_back(Point2f(0,196)); normalizedPoints.push_back(Point2f(196,196)); normalizedPoints.push_back(Point2f(196,0)); } int getNormalizedOrientationFromMarkerId(int markerId) { int returnVal = -1; if(markerId == 249) { returnVal = 0; } if(markerId == 159) { returnVal = 90; } if(markerId==318) { returnVal = 180; } if(markerId ==498) { returnVal = 270; } return returnVal; } int calculateMarkerIdAndNormalizedOrientation(Mat binaryNormalizedImage, int & normalizedOrientation) { int markerIdWidth = 3; int markerIdHeight = 3; int markerSquareIdLocationStepX = (binaryNormalizedImage.cols/2)/markerIdWidth; int markerSquareIdLocationStepY = (binaryNormalizedImage.rows/2)/markerIdHeight; int markerSquareIdLocationX = markerSquareIdLocationStepX/2 + binaryNormalizedImage.cols/4; int markerSquareIdLocationY = markerSquareIdLocationStepY/2 + binaryNormalizedImage.rows/4; Size idRegionSize(9,9); int markerId = 0x00; for(int i = 0; i <markerIdHeight; i++ ) { for(int j = 0;j <markerIdWidth; j++) { Mat idRegion = binaryNormalizedImage(Range(markerSquareIdLocationY-idRegionSize.height/2,markerSquareIdLocationY+idRegionSize.height/2+1),Range(markerSquareIdLocationX-idRegionSize.width/2,markerSquareIdLocationX+idRegionSize.width/2+1)); Scalar meanScalar = mean(idRegion); markerId = markerId << 1; if(meanScalar.val[0] <128) { markerId = (markerId |1); } markerSquareIdLocationX+=markerSquareIdLocationStepX; } markerSquareIdLocationY+=markerSquareIdLocationStepY; markerSquareIdLocationX = markerSquareIdLocationStepX/2 + binaryNormalizedImage.cols/4; } normalizedOrientation = getNormalizedOrientationFromMarkerId(markerId); return markerId; } bool checkForValidMarker (int markerId) { bool returnVal = false; if(markerId == 249 || markerId == 159 || markerId==318 || markerId ==498) { returnVal=true; } return returnVal; } void getAxes3DPoints(vector <Point3f> & axesPoints) { //order: Origin, X limit, Y Limit, Z limit axesPoints.clear(); axesPoints.push_back(Point3f(0,0,0)); axesPoints.push_back(Point3f(19.6,0,0)); axesPoints.push_back(Point3f(0,19.6,0)); axesPoints.push_back(Point3f(0,0,-19.6)); } void getBox3DPoints(vector<vector <Point3f> > & boxPoints) { float cubeEdgeLength = 9.8f; //in cm Point3f cubeOrigin(-9.8,0,0 ); //order: Origin, X limit, Y Limit, Z limit boxPoints.clear(); vector<Point3f> boxPoints1; boxPoints1.push_back(Point3f(0,0,0)); boxPoints1.push_back(Point3f(cubeEdgeLength,0,0)); boxPoints1.push_back(Point3f(0,cubeEdgeLength,0)); boxPoints1.push_back(Point3f(0,0,-cubeEdgeLength)); boxPoints.push_back(boxPoints1); vector<Point3f> boxPoints2; boxPoints2.push_back(Point3f(cubeEdgeLength,cubeEdgeLength,0)); boxPoints2.push_back(Point3f(0,cubeEdgeLength,0)); boxPoints2.push_back(Point3f(cubeEdgeLength,0,0)); boxPoints2.push_back(Point3f(cubeEdgeLength,cubeEdgeLength,-cubeEdgeLength)); boxPoints.push_back(boxPoints2); vector<Point3f> boxPoints3; boxPoints3.push_back(Point3f(0,cubeEdgeLength,-cubeEdgeLength)); boxPoints3.push_back(Point3f(cubeEdgeLength,cubeEdgeLength,-cubeEdgeLength)); boxPoints3.push_back(Point3f(0,0,-cubeEdgeLength)); boxPoints3.push_back(Point3f(0,cubeEdgeLength,0)); boxPoints.push_back(boxPoints3); vector<Point3f> boxPoints4; boxPoints4.push_back(Point3f(cubeEdgeLength,0,-cubeEdgeLength)); boxPoints4.push_back(Point3f(cubeEdgeLength,0,0)); boxPoints4.push_back(Point3f(cubeEdgeLength,cubeEdgeLength,-cubeEdgeLength)); boxPoints4.push_back(Point3f(0,0,-cubeEdgeLength)); boxPoints.push_back(boxPoints4); for(int i = 0; i < boxPoints.size(); i++) { for(int j=0; j<boxPoints[i].size(); j++) { boxPoints[i][j].x += cubeOrigin.x; boxPoints[i][j].y += cubeOrigin.y; boxPoints[i][j].z += cubeOrigin.z; } } } void projectBoxToImage(AugmentedRealityConfig &augmentedRealityConfig, AugmentedRealityData &augmentedRealityData, Mat & image) { vector<vector<Point3f> > boxPoints; vector<Point2f> currentBoxPointsInImage; getBox3DPoints(boxPoints); for(int i = 0; i < boxPoints.size(); i++) { currentBoxPointsInImage.clear(); projectPoints(Mat(boxPoints[i]),augmentedRealityData.rVec[0],augmentedRealityData.tVec[0],augmentedRealityData.cameraCalibration.getCameraMatrix(),augmentedRealityData.cameraCalibration.getDistCoeffs(),currentBoxPointsInImage); for(int j =1; j< currentBoxPointsInImage.size(); j++) { //x axis line(image, currentBoxPointsInImage[0], currentBoxPointsInImage[j], CV_RGB(255, 0, 0), 3, CV_AA, 0); } } } void projectAxisToImage(AugmentedRealityConfig &augmentedRealityConfig, AugmentedRealityData &augmentedRealityData, Mat & image) { vector <Point3f> axesPoints; getAxes3DPoints(axesPoints); vector<Point2f> axesPointsInImage; projectPoints(Mat(axesPoints),augmentedRealityData.rVec[0],augmentedRealityData.tVec[0],augmentedRealityData.cameraCalibration.getCameraMatrix(),augmentedRealityData.cameraCalibration.getDistCoeffs(),axesPointsInImage); //x axis line(image, axesPointsInImage[0], axesPointsInImage[1], CV_RGB(255, 0, 0), 3, CV_AA, 0); //y axis line(image, axesPointsInImage[0], axesPointsInImage[2], CV_RGB(0, 255, 0), 3, CV_AA, 0); //z axis line(image, axesPointsInImage[0], axesPointsInImage[3], CV_RGB(0, 0, 255), 3, CV_AA, 0); } int augmentedReality_main(int argc, const char * argv[]) { int key = -1; int lastKey = -1; AugmentedRealityConfig augmentedRealityConfig; AugmentedRealityData augmentedRealityData; cout << "Augmented Reality Application Starting" << endl; cout << "Beginning Setup" << endl; vector<string> commandLineArgs; for(int i = 0; i < argc; i++) { string currentString = argv[i]; commandLineArgs.push_back(currentString); } if((commandLineArgs[1].compare("-configFile") ==0) || (commandLineArgs[1].compare("-ConfigFile") ==0)) { loadAugmentedRealityConfigFile(commandLineArgs, commandLineArgs[2]); } parseAugmentedRealityConfigCommandVector(augmentedRealityConfig, commandLineArgs); augmentedRealitySetupInput( augmentedRealityConfig,augmentedRealityData); setupAugmentedRealityCalibrationData(augmentedRealityConfig, augmentedRealityData); cout << "Setup Complete" << endl; if(augmentedRealityConfig.inputMethod ==AUGMENT_REAL_SINGLE_STREAM) { cout << "Allowing stream to setup" << endl; namedWindow("Stream warmup"); key = -1; lastKey = -1; while(key != 27 && key != 'r' && key != 'd' && key != ' ') { augmentedRealityData.capture[0] >> augmentedRealityData.frameBuffer[0]; augmentedRealityData.currentFrame[0]=augmentedRealityData.frameBuffer[0].clone(); imshow("Stream warmup",augmentedRealityData.currentFrame[0]); key = waitKey(33) & 0xff; } destroyWindow("Stream warmup"); } augmentedRealitySetupOutput( augmentedRealityConfig,augmentedRealityData); if(augmentedRealityConfig.showWindows) { cout << "Creating display windows" << endl; namedWindow("Current Frame Original"); namedWindow("Current Frame Grayscale"); namedWindow("Current Frame Thresholded"); namedWindow("Current Frame Adaptive Thresholded"); namedWindow("Current Frame Contours"); namedWindow("Current Frame Approx Contours"); namedWindow("Current Frame Corners"); namedWindow("Current Frame Normalized"); namedWindow("Current Frame Augmented"); namedWindow("Tracking Corners"); } cout << "Beginning Main Loop" << endl; key = -1; lastKey = -1; bool done = false; Mat tmpBuffer; #ifdef USE_MARSS cout << "Switching to simulation in Augmented Reality." << endl; ptlcall_switch_to_sim(); //ptlcall_single_enqueue("-logfile augReality.log"); //ptlcall_single_enqueue("-stats augReality.stats"); ptlcall_single_flush("-stats augReality.stats"); //ptlcall_single_enqueue("-loglevel 0"); #endif #ifdef USE_GEM5 #ifdef GEM5_CHECKPOINT_WORK m5_checkpoint(0, 0); #endif #ifdef GEM5_SWITCHCPU_AT_WORK m5_switchcpu(); #endif m5_dumpreset_stats(0, 0); #endif #ifdef TSC_TIMING READ_TIMESTAMP_WITH_WRAPPER( aug_timingVector[0] ); #endif #ifdef CLOCK_GETTIME_TIMING GET_TIME_WRAPPER(aug_timeStructVector[0]); #endif int missingCorners = 0; bool trackingValid = false; int normalizedOrienation; while(!done) { #ifdef USE_GEM5 m5_dumpreset_stats(0, 0); #endif augmentedRealityGetNextFrames(augmentedRealityConfig, augmentedRealityData); if(augmentedRealityData.outOfImages == true) { break; } Mat unmodifiedFrames[2]; unmodifiedFrames[0] = augmentedRealityData.currentFrame[0].clone(); if(!augmentedRealityData.cameraCalibration.getDistCoeffs().empty()) { tmpBuffer = augmentedRealityData.currentFrame[0].clone(); remap(tmpBuffer, augmentedRealityData.currentFrame[0], augmentedRealityData.map1[0], augmentedRealityData.map2[0], INTER_LINEAR); } Mat augmentedImage[2]; augmentedImage[0] = augmentedRealityData.currentFrame[0].clone(); //unmodifiedFrames[1] = augmentedRealityData.currentFrame[1].clone(); Mat grayScaleFrames[2]; cvtColor(augmentedRealityData.currentFrame[0],grayScaleFrames[0], CV_BGR2GRAY); Mat adaptiveThresholdedFrames[2]; Mat thresholdedFrames[2]; // adaptiveThreshold(grayScaleFrames[0], adaptiveThresholdedFrames[0], 255, ADAPTIVE_THRESH_MEAN_C,THRESH_BINARY_INV, 65, 10); threshold(grayScaleFrames[0], thresholdedFrames[0], 128, 255, THRESH_BINARY_INV); Mat contourImage[2]; Mat approxContourImage[2]; vector<vector<Point> > contours; vector<Vec4i> hierarchy; Mat thresholdedFramesForContours = thresholdedFrames[0].clone(); #ifdef USE_GEM5 m5_dumpreset_stats(0, 0); #endif findContours(thresholdedFramesForContours, contours, hierarchy, CV_RETR_CCOMP,CV_CHAIN_APPROX_TC89_KCOS); contourImage[0].create(thresholdedFrames[0].rows,thresholdedFrames[0].cols,CV_8UC3); contourImage[0].setTo(Scalar(0)); approxContourImage[0].create(thresholdedFrames[0].rows,thresholdedFrames[0].cols,CV_8UC3); approxContourImage[0].setTo(Scalar(0)); int idx = 0; bool foundMarker = false; for( ; idx >= 0; idx = hierarchy[idx][0] ) { Scalar color( rand()&255, rand()&255, rand()&255 ); drawContours( contourImage[0], contours, idx, color, CV_FILLED, 8, hierarchy,0 ); Mat curve(contours[idx]); vector <vector<Point> >approxCurve(1); approxPolyDP(curve, approxCurve[0], 3.0, true); // drawContours( approxContourImage[0], approxCurve, 0, color, CV_FILLED, 8); // cout << "Contour Points Count: "<< contours[idx].size()<< endl; // cout << "Contour Points Count: "<< approxCurve[0].size()<< endl; if(approxCurve[0].size() ==4) { vector<Point2f> normalizedPoints; getMarkerNormalizationPoints(normalizedPoints); vector<Point2f> corners(approxCurve[0].size()); for(int i = 0; i < corners.size(); i++) { corners[i] = approxCurve[0][i]; // cout <<"Approx x: " <<corners[i].x << " y: "<<corners[i].y << endl; } Size subPixelSize(5,5); Size subPixelDeadZoneSize(-1,-1); cornerSubPix(grayScaleFrames[0], corners, subPixelSize, subPixelDeadZoneSize, TermCriteria( CV_TERMCRIT_EPS+CV_TERMCRIT_ITER, 30, 0.1 )); if(augmentedRealityData.prevCorners.size() > 0) { if( (abs(corners[0].x - augmentedRealityData.prevCorners[0].x) < 1) &&(abs(corners[0].y - augmentedRealityData.prevCorners[0].y) < 1) ) { corners = augmentedRealityData.prevCorners; } } // double areaVal = contourArea(Mat(corners)); // cout << "Area Val: "<<areaVal << endl; Mat srcPoints(corners); Mat dstPoints(normalizedPoints); Mat normalHom = findHomography(srcPoints, dstPoints); //Mat& status, int method=0, double ransacReprojThreshold=3) Mat preWarp = thresholdedFrames[0].clone(); Mat normalizedImage; normalizedImage.create(192,192,CV_8UC3); warpPerspective(preWarp, normalizedImage,normalHom, Size(192,192)); //int normalizedOrienation; int markerId = calculateMarkerIdAndNormalizedOrientation(normalizedImage,normalizedOrienation); //cout << "Current Marker Id: "<<markerId << endl; int tmpKey = -1;//waitKey(30) & 0xff; if(((!augmentedRealityData.map1[0].empty())&& (tmpKey =='d')) || checkForValidMarker(markerId)) { augmentedRealityData.normalizedOrientation = normalizedOrienation; augmentedRealityData.currentMarkerCorners = corners; foundMarker = true; missingCorners = 0; break; } // imshow ("Current Frame Normalized", normalizedImage); // waitKey(0); } // imshow("Current Frame Contours",contourImage[0]); // imshow("Current Frame Approx Contours",approxContourImage[0]); //waitKey(0); } if(!augmentedRealityData.prevFrame[0].empty() && augmentedRealityConfig.tracking) { vector<uchar> opticalFlowStatus; vector<float> opticalFlowErr; cout << "Calc Opt" << endl; calcOpticalFlowPyrLK(augmentedRealityData.prevFrame[0], grayScaleFrames[0], augmentedRealityData.prevCorners, augmentedRealityData.trackingCorners, opticalFlowStatus, opticalFlowErr, Size(15, 15), 3, TermCriteria( TermCriteria::COUNT+TermCriteria::EPS, 30, 0.01), 0.5, 0); int cornersFound = 0; for(unsigned int i =0; i < opticalFlowStatus.size(); i++) { cornersFound += opticalFlowStatus[i]; } Mat trackingDisplayMat = augmentedRealityData.currentFrame[0].clone(); for(int i = 0; i< augmentedRealityData.trackingCorners.size(); i++) { if(opticalFlowStatus[i] !=0) { circle(trackingDisplayMat,augmentedRealityData.trackingCorners[i],6,Scalar(0,0,255),-1); } } if(augmentedRealityConfig.showWindows) { imshow("Tracking Corners", trackingDisplayMat); } if(!foundMarker && cornersFound == 4) { augmentedRealityData.currentMarkerCorners = augmentedRealityData.trackingCorners; missingCorners++; Size subPixelSize(5,5); Size subPixelDeadZoneSize(-1,-1); //corners = augmentedRealityData.trackingCorners; cornerSubPix(grayScaleFrames[0], augmentedRealityData.currentMarkerCorners, subPixelSize, subPixelDeadZoneSize, TermCriteria( CV_TERMCRIT_EPS+CV_TERMCRIT_ITER, 30, 0.1 )); if(augmentedRealityData.prevCorners.size() > 0) { if( (abs(augmentedRealityData.currentMarkerCorners[0].x - augmentedRealityData.prevCorners[0].x) < 1) &&(abs(augmentedRealityData.currentMarkerCorners[0].y - augmentedRealityData.prevCorners[0].y) < 1) ) { augmentedRealityData.currentMarkerCorners = augmentedRealityData.prevCorners; } } augmentedRealityData.normalizedOrientation = augmentedRealityData.lastNormalizedOrientation; if(missingCorners >augmentedRealityConfig.markerLostFrameCount) { missingCorners = augmentedRealityConfig.markerLostFrameCount+1; trackingValid = false; } else { trackingValid = true; } } } else { trackingValid = false; } //int normalizedOrienation; //int markerId = calculateMarkerIdAndNormalizedOrientation(normalizedImage,normalizedOrienation); //cout << "Current Marker Id: "<<markerId << endl; //int tmpKey = -1;//waitKey(30) & 0xff; //if(((!augmentedRealityData.map1[0].empty())&& (tmpKey =='d')) || checkForValidMarker(markerId)) if(foundMarker || trackingValid) { Mat rvec; Mat tvec; vector<Point3f> objectPoints; //getObject3DPoints(objectPoints); getObject3DPointsWithOrientation(objectPoints,augmentedRealityData.normalizedOrientation); augmentedRealityData.prevFrame[0] = grayScaleFrames[0]; augmentedRealityData.prevCorners = augmentedRealityData.currentMarkerCorners; augmentedRealityData.lastNormalizedOrientation = augmentedRealityData.normalizedOrientation; solvePnP(Mat(objectPoints),Mat(augmentedRealityData.currentMarkerCorners),augmentedRealityData.cameraCalibration.getCameraMatrix(),augmentedRealityData.cameraCalibration.getDistCoeffs(),augmentedRealityData.rVec[0],augmentedRealityData.tVec[0],false); // cout << "RVec: " << augmentedRealityData.rVec[0] << "\n TVec: " << augmentedRealityData.tVec[0] << endl; projectAxisToImage(augmentedRealityConfig, augmentedRealityData, augmentedImage[0]); projectBoxToImage(augmentedRealityConfig, augmentedRealityData, augmentedImage[0]); //waitKey(0); } if(augmentedRealityConfig.showWindows) { imshow("Current Frame Augmented", augmentedImage[0]); imshow("Current Frame Original",unmodifiedFrames[0]); // imshow("Current Frame Grayscale",grayScaleFrames[0]); // imshow("Current Frame Thresholded",thresholdedFrames[0]); // imshow("Current Frame Adaptive Thresholded",adaptiveThresholdedFrames[0]); // imshow("Current Frame Contours",contourImage[0]); // imshow("Current Frame Corners",unmodifiedFrames[0]); } augmentedRealityData.currentAugmentedFrame[0] = augmentedImage[0]; augmentedRealityHandleWritingOutput( augmentedRealityConfig, augmentedRealityData); lastKey = key; if(!augmentedRealityConfig.noWaitKey) { if (augmentedRealityConfig.pauseMode) { key = waitKey(0); } else { key = waitKey(10) & 0xff; } } else { key = -1; } if(key == 'q' || key =='d' || key == 27) { done = true; } } #ifdef USE_MARSS ptlcall_kill(); #endif #ifdef USE_GEM5 m5_dumpreset_stats(0, 0); #ifdef GEM5_EXIT_AFTER_WORK m5_exit(0); #endif #endif #ifdef TSC_TIMING READ_TIMESTAMP_WITH_WRAPPER( aug_timingVector[0+ TIMING_MAX_NUMBER_OF_THREADS] ); #endif #ifdef CLOCK_GETTIME_TIMING GET_TIME_WRAPPER(aug_timeStructVector[0+ TIMING_MAX_NUMBER_OF_THREADS]); #endif #ifdef TSC_TIMING aug_writeTimingToFile(aug_timingVector); #endif #ifdef CLOCK_GETTIME_TIMING aug_writeTimingToFile(aug_timeStructVector); #endif cout << "Augmented Reality complete" << endl; return 0; } #ifndef AUGMENTED_REALITY_MODULE int main(int argc, const char * argv[]) { #ifdef TSC_TIMING aug_timingVector.resize(TIMING_MAX_NUMBER_OF_THREADS*3); //fe_timeStructVector.resize(TIMING_MAX_NUMBER_OF_THREADS*2); #endif #ifdef CLOCK_GETTIME_TIMING aug_timeStructVector.resize(TIMING_MAX_NUMBER_OF_THREADS*3); #endif return augmentedReality_main(argc, argv); } #endif
24.508039
338
0.72603
[ "vector" ]
07591b7774bdb0a5ef364a74328d589cbc4a0134
6,573
cpp
C++
Chapter01/Code/RigidbodyVolume.cpp
PacktPublishing/Game-Physics-Cookbook
abb0caa14433be5f83a43126122ac1ad44280552
[ "MIT" ]
45
2017-03-30T15:39:14.000Z
2022-03-09T08:32:57.000Z
Chapter02/Code/RigidbodyVolume.cpp
PacktPublishing/Game-Physics-Cookbook
abb0caa14433be5f83a43126122ac1ad44280552
[ "MIT" ]
1
2019-11-18T08:22:25.000Z
2019-11-18T08:22:25.000Z
Chapter01/Code/RigidbodyVolume.cpp
PacktPublishing/Game-Physics-Cookbook
abb0caa14433be5f83a43126122ac1ad44280552
[ "MIT" ]
14
2017-04-05T12:05:31.000Z
2021-08-09T20:40:07.000Z
#include "RigidbodyVolume.h" #include "Compare.h" #include "FixedFunctionPrimitives.h" void RigidbodyVolume::ApplyForces() { forces = GRAVITY_CONST * mass; } #ifndef LINEAR_ONLY void RigidbodyVolume::AddRotationalImpulse(const vec3& point, const vec3& impulse) { vec3 centerOfMass = position; vec3 torque = Cross(point - centerOfMass, impulse); vec3 angAccel = MultiplyVector(torque, InvTensor()); angVel = angVel + angAccel; } #endif void RigidbodyVolume::AddLinearImpulse(const vec3& impulse) { velocity = velocity + impulse; } float RigidbodyVolume::InvMass() { if (mass == 0.0f) { return 0.0f; } return 1.0f / mass; } void RigidbodyVolume::SynchCollisionVolumes() { sphere.position = position; box.position = position; #ifndef LINEAR_ONLY box.orientation = Rotation3x3( RAD2DEG(orientation.x), RAD2DEG(orientation.y), RAD2DEG(orientation.z) ); #endif } void RigidbodyVolume::Render() { SynchCollisionVolumes(); if (type == RIGIDBODY_TYPE_SPHERE) { ::Render(sphere); } else if (type == RIGIDBODY_TYPE_BOX) { ::Render(box); } } #ifndef LINEAR_ONLY mat4 RigidbodyVolume::InvTensor() { if (mass == 0) { return mat4( 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ); } float ix = 0.0f; float iy = 0.0f; float iz = 0.0f; float iw = 0.0f; if (mass != 0 && type == RIGIDBODY_TYPE_SPHERE) { float r2 = sphere.radius * sphere.radius; float fraction = (2.0f / 5.0f); ix = r2 * mass * fraction; iy = r2 * mass * fraction; iz = r2 * mass * fraction; iw = 1.0f; } else if (mass != 0 && type == RIGIDBODY_TYPE_BOX) { vec3 size = box.size * 2.0f; float fraction = (1.0f / 12.0f); float x2 = size.x * size.x; float y2 = size.y * size.y; float z2 = size.z * size.z; ix = (y2 + z2) * mass * fraction; iy = (x2 + z2) * mass * fraction; iz = (x2 + y2) * mass * fraction; iw = 1.0f; } return Inverse(mat4( ix, 0, 0, 0, 0, iy, 0, 0, 0, 0, iz, 0, 0, 0, 0, iw)); } #endif void RigidbodyVolume::Update(float dt) { // Integrate velocity const float damping = 0.98f; vec3 acceleration = forces * InvMass(); velocity = velocity + acceleration * dt; velocity = velocity * damping; if (fabsf(velocity.x) < 0.001f) { velocity.x = 0.0f; } if (fabsf(velocity.y) < 0.001f) { velocity.y = 0.0f; } if (fabsf(velocity.z) < 0.001f) { velocity.z = 0.0f; } #ifndef LINEAR_ONLY if (type == RIGIDBODY_TYPE_BOX) { vec3 angAccel = MultiplyVector(torques, InvTensor()); angVel = angVel + angAccel * dt; angVel = angVel * damping; if (fabsf(angVel.x) < 0.001f) { angVel.x = 0.0f; } if (fabsf(angVel.y) < 0.001f) { angVel.y = 0.0f; } if (fabsf(angVel.z) < 0.001f) { angVel.z = 0.0f; } } #endif // Integrate position position = position + velocity * dt; #ifndef LINEAR_ONLY if (type == RIGIDBODY_TYPE_BOX) { orientation = orientation + angVel * dt; } #endif SynchCollisionVolumes(); } CollisionManifold FindCollisionFeatures(RigidbodyVolume& ra, RigidbodyVolume& rb) { CollisionManifold result; ResetCollisionManifold(&result); if (ra.type == RIGIDBODY_TYPE_SPHERE) { if (rb.type == RIGIDBODY_TYPE_SPHERE) { result = FindCollisionFeatures(ra.sphere, rb.sphere); } else if (rb.type == RIGIDBODY_TYPE_BOX) { result = FindCollisionFeatures(rb.box, ra.sphere); result.normal = result.normal * -1.0f; } } else if (ra.type == RIGIDBODY_TYPE_BOX) { if (rb.type == RIGIDBODY_TYPE_BOX) { result = FindCollisionFeatures(ra.box, rb.box); } else if (rb.type == RIGIDBODY_TYPE_SPHERE) { result = FindCollisionFeatures(ra.box, rb.sphere); } } return result; } void ApplyImpulse(RigidbodyVolume& A, RigidbodyVolume& B, const CollisionManifold& M, int c) { // Linear impulse float invMass1 = A.InvMass(); float invMass2 = B.InvMass(); float invMassSum = invMass1 + invMass2; if (invMassSum == 0.0f) { return; // Both objects have infinate mass! } #ifndef LINEAR_ONLY vec3 r1 = M.contacts[c] - A.position; vec3 r2 = M.contacts[c] - B.position; mat4 i1 = A.InvTensor(); mat4 i2 = B.InvTensor(); #endif // Relative velocity #ifndef LINEAR_ONLY vec3 relativeVel = (B.velocity + Cross(B.angVel, r2)) - (A.velocity + Cross(A.angVel, r1)); #else vec3 relativeVel = B.velocity - A.velocity; #endif // Relative collision normal vec3 relativeNorm = M.normal; Normalize(relativeNorm); // Moving away from each other? Do nothing! if (Dot(relativeVel, relativeNorm) > 0.0f) { return; } float e = fminf(A.cor, B.cor); float numerator = (-(1.0f + e) * Dot(relativeVel, relativeNorm)); float d1 = invMassSum; #ifndef LINEAR_ONLY vec3 d2 = Cross(MultiplyVector(Cross(r1, relativeNorm), i1), r1); vec3 d3 = Cross(MultiplyVector(Cross(r2, relativeNorm), i2), r2); float denominator = d1 + Dot(relativeNorm, d2 + d3); #else float denominator = d1; #endif float j = (denominator == 0.0f) ? 0.0f : numerator / denominator; if (M.contacts.size() > 0.0f && j != 0.0f) { j /= (float)M.contacts.size(); } vec3 impulse = relativeNorm * j; A.velocity = A.velocity - impulse * invMass1; B.velocity = B.velocity + impulse * invMass2; #ifndef LINEAR_ONLY A.angVel = A.angVel - MultiplyVector(Cross(r1, impulse), i1); B.angVel = B.angVel + MultiplyVector(Cross(r2, impulse), i2); #endif // Friction vec3 t = relativeVel - (relativeNorm * Dot(relativeVel, relativeNorm)); if (CMP(MagnitudeSq(t), 0.0f)) { return; } Normalize(t); numerator = -Dot(relativeVel, t); d1 = invMassSum; #ifndef LINEAR_ONLY d2 = Cross(MultiplyVector(Cross(r1, t), i1), r1); d3 = Cross(MultiplyVector(Cross(r2, t), i2), r2); denominator = d1 + Dot(t, d2 + d3); #else denominator = d1; #endif float jt = (denominator == 0.0f) ? 0.0f : numerator / denominator; if (M.contacts.size() > 0.0f && jt != 0.0f) { jt /= (float)M.contacts.size(); } if (CMP(jt, 0.0f)) { return; } vec3 tangentImpuse; #ifdef DYNAMIC_FRICTION float sf = sqrtf(A.staticFriction * B.staticFriction); float df = sqrtf(A.dynamicFriction * B.dynamicFriction); if (fabsf(jt) < j * sf) { tangentImpuse = t * jt; } else { tangentImpuse = t * -j * df; } #else float friction = sqrtf(A.friction * B.friction); if (jt > j * friction) { jt = j * friction; } else if (jt < -j * friction) { jt = -j * friction; } tangentImpuse = t * jt; #endif A.velocity = A.velocity - tangentImpuse * invMass1; B.velocity = B.velocity + tangentImpuse * invMass2; #ifndef LINEAR_ONLY A.angVel = A.angVel - MultiplyVector(Cross(r1, tangentImpuse), i1); B.angVel = B.angVel + MultiplyVector(Cross(r2, tangentImpuse), i2); #endif }
22.982517
94
0.659212
[ "render" ]
0759549c8ba44e4ca80dc92b886e5efe4a1e44a1
4,483
cpp
C++
test/cpp/main.cpp
Soju06/waifu2x-lib
5a5ac85b5f424dc76f3b8665b5b46a6c97659c83
[ "MIT" ]
null
null
null
test/cpp/main.cpp
Soju06/waifu2x-lib
5a5ac85b5f424dc76f3b8665b5b46a6c97659c83
[ "MIT" ]
null
null
null
test/cpp/main.cpp
Soju06/waifu2x-lib
5a5ac85b5f424dc76f3b8665b5b46a6c97659c83
[ "MIT" ]
null
null
null
#include <stdio.h> #include <algorithm> #include <queue> #include <vector> #include <clocale> #include <iostream> #include <thread> #include <fs.h> #include <chrono> // ncnn #include "cpu.h" #include "gpu.h" #include "platform.h" #include <waifu2x.h> #if _WIN32 #define _CRTDBG_MAP_ALLOC #include <crtdbg.h> #endif #if _WIN32 #define _printf_a(a) printf_s(a) #define _printf_b(a, b) printf_s(a, b) #define _printf_c(a, b, c) printf_s(a, b, c) #define _printf_d(a, b, c, d) printf_s(a, b, c, d) #define _printf_e(a, b, c, d, e) printf_s(a, b, c, d, e) #define _printf_f(a, b, c, d, e, f) printf_s(a, b, c, d, e, f) #else #define _printf_a(a) printf(a) #define _printf_b(a, b) printf(a, b) #define _printf_c(a, b, c) printf(a, b, c) #define _printf_d(a, b, c, d) printf(a, b, c, d) #define _printf_e(a, b, c, d, e) printf(a, b, c, d, e) #define _printf_f(a, b, c, d, e, f) printf(a, b, c, d, e, f) #endif #define GET_7TH_ARG(a, b, c, d, e, f, g, ...) g #define _printf__(...) GET_7TH_ARG(__VA_ARGS__, _printf_f, _printf_e, _printf_d, _printf_c, _printf_b, _printf_a, ) #define _printf(...) _printf__(__VA_ARGS__)(__VA_ARGS__) bool ERRC(int err, const char* message) { if (err) { _printf("\n%8x - %s, %s\n", err, get_error_message(err), message); return false; } return true; } int main() { #if _WIN32 _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF); #endif { int noise = 2; int scale = 2; #if _WIN32 std::wstring #else std::string #endif inImage, outImage; _printf("source image path: "); std::getline( #if _WIN32 std::wcin, #else std::cin, #endif inImage); _printf("output image path: "); std::getline( #if _WIN32 std::wcin, #else std::cin, #endif outImage); outImage += PATH(".png"); _printf("processor: auto\n"); Waifu2xProcessor* processor = 0; if (!ERRC(Waifu2xProcessor::get_s(&processor, Waifu2xProcessors::Auto), "Failed to import processor.")) return -1; _printf("processor type: %s\n", processor->processor == Waifu2xProcessors::Gpu ? "GPU" : "CPU"); _printf("processor index: %d\n", processor->index); _printf("processor info:\n"); if (processor->processor == Waifu2xProcessors::Gpu) { _printf(Waifu2xEnvironment::get_gpu_name(processor->index)); _printf(" %dMB\n",Waifu2xEnvironment::get_gpu_heap_budget(processor->index)); } else { _printf("just CPU"); } _printf("model info:\nmodel name: CUnet\nnoise level: %d\nscale: %d\n", noise, scale); Waifu2xModel* model = 0; if (!ERRC(Waifu2xModel::load_s(&model, Waifu2xModels::CUnet, processor, noise, scale), "Failed to load model file.")) return -1; _printf("load model\n"); Waifu2x waifu2x(processor); if (!ERRC(waifu2x.loadModel(model), "Failed to load the model.")) return -1; _printf("open image\n"); Waifu2xMat* input = 0; if (!ERRC(Waifu2xMat::load_s(&input, inImage), "Failed to load image.")) return -1; bool is_success = false; Waifu2xProcessStatus status = { }; _printf("process image\n"); auto thread = std::thread([&is_success, &status]() { int current = -1; while (!is_success) { if (status.tile_count && current != status.tile_index) { current = status.tile_index; _printf("process status: %d/%d\n", current, status.tile_count); } std::this_thread::sleep_for(std::chrono::milliseconds(50)); } }); Waifu2xMat* out = 0; if (!ERRC(waifu2x.process_s(&out, input, scale, &status), "Failed to process image.")) return -1; is_success = true; thread.join(); _printf("image incoding\n"); if (!ERRC(out->save(outImage, Waifu2xImageFormat::Png), "Failed to save image.")) return -1; delete out; delete input; } ncnn::destroy_gpu_instance(); #if _WIN32 _CrtDumpMemoryLeaks(); #endif return 0; }
30.290541
125
0.556101
[ "vector", "model" ]
075a964186442363deb88181a38a3ef0eb028097
23,095
cpp
C++
src/recryption.cpp
msatyan/HElib
0553a60f809c13859f64935ec24c14447e8c9159
[ "Apache-2.0" ]
2
2018-05-22T00:27:17.000Z
2018-07-22T21:22:58.000Z
src/recryption.cpp
msatyan/HElib
0553a60f809c13859f64935ec24c14447e8c9159
[ "Apache-2.0" ]
6
2018-05-17T21:41:34.000Z
2018-05-18T21:37:26.000Z
src/recryption.cpp
msatyan/HElib
0553a60f809c13859f64935ec24c14447e8c9159
[ "Apache-2.0" ]
1
2020-06-03T15:41:14.000Z
2020-06-03T15:41:14.000Z
/* Copyright (C) 2012-2017 IBM Corp. * This program is Licensed under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. See accompanying LICENSE file. */ #include <NTL/BasicThreadPool.h> #include "recryption.h" #include "EncryptedArray.h" #include "EvalMap.h" #include "powerful.h" #include "CtPtrs.h" #include "intraSlot.h" /************* Some local functions *************/ static void x2iInSlots(ZZX& poly, long i, vector<ZZX>& xVec, const EncryptedArray& ea); // Make every entry of vec divisible by p^e by adding/subtracting multiples // of p^r and q, while keeping the added multiples small. template<class VecInt> long makeDivisible(VecInt& vec, long p2e, long p2r, long q, double alpha); static inline double pow(long a, long b) {return pow(double(a), double(b));} RecryptData::~RecryptData() { if (alMod!=NULL) delete alMod; if (ea!=NULL) delete ea; if (firstMap!=NULL) delete firstMap; if (secondMap!=NULL) delete secondMap; if (p2dConv!=NULL) delete p2dConv; } /** Computing the recryption parameters * * To get the smallest possible value of e-e', the params need to satisfy: * (p^e +1)/4 => * max { (t+1)( 1+ (alpha/2)*(p^e/p^{ceil(log_p(t+2))}) ) + noise } * { (t+1)( 1+ ((1-alpha)/2)*(p^e/p^{ceil(log_p(t+2))}) +p^r/2) +1 }, * * where noise is taken to be twice the mod-switching additive term, namely * noise = p^r *sqrt((t+1)*phi(m)/3). Denoting rho=(t+1)/p^{ceil(log_p(t+2))} * (and ignoring fome +1 terms), this is equivalent to: * * p^e > max { 4(t+noise)/(1-2*alpha*rho), 2(t+1)p^r/(1-2(1-alpha)rho) }. * * We first compute the optimal value for alpha (which must be in [0,1]), * that makes the two terms in the max{...} as close as possible, and * then compute the smallest value of e satisfying this constraint. * * If this value is too big then we try again with e-e' one larger, * which means that rho is a factor of p smaller. */ // Some convenience functions static double lowerBound1(long p, long r, long ePrime, long t, double alpha, double noise) { return (t+1)*(1+ alpha*pow(p,r+ePrime-1)/2)+noise; } static double lowerBound2(long p, long r, long ePrime, long t, double alpha) { return (t+1)*(1+ (1-alpha)*pow(p,r+ePrime-1)/2 + pow(p,r)/2)+1; } static void setAlphaE(double& alpha, long& e, double rho, double gamma, double noise, double logp, long p2r, long t) { alpha = (1 +gamma*(2*rho-1))/(2*rho*(1+gamma)); if (alpha<0) alpha=0; else if (alpha>1) alpha=1; if (alpha<1) { double ratio = 4*(t+noise)/(1-2*alpha*rho); e = floor(1+ log(ratio)/logp); } else e = floor(1+ log(2*(t+1)*p2r)/logp); } bool RecryptData::operator==(const RecryptData& other) const { if (mvec != other.mvec) return false; if (hwt != other.hwt) return false; if (conservative != other.conservative) return false; return true; } // The main method void RecryptData::init(const FHEcontext& context, const Vec<long>& mvec_, long t, bool consFlag, bool build_cache_, bool minimal) { if (alMod != NULL) { // were we called for a second time? cerr << "@Warning: multiple calls to RecryptData::init\n"; return; } assert(computeProd(mvec_) == (long)context.zMStar.getM()); // sanity check // Record the arguments to this function mvec = mvec_; conservative = consFlag; build_cache = build_cache_; if (t <= 0) t = defSkHwt+1; // recryption key Hwt hwt = t; long p = context.zMStar.getP(); long phim = context.zMStar.getPhiM(); long r = context.alMod.getR(); long p2r = context.alMod.getPPowR(); double logp = log((double)p); double noise = p2r * sqrt((t+1)*phim/3.0); double gamma = 2*(t+noise)/((t+1)*p2r); // ratio between numerators long logT = ceil(log((double)(t+2))/logp); // ceil(log_p(t+2)) double rho = (t+1)/pow(p,logT); if (!conservative) { // try alpha, e with this "aggresive" setting setAlphaE(alpha, e, rho, gamma, noise, logp, p2r, t); ePrime = e -r +1 -logT; // If e is too large, try again with rho/p instead of rho long bound = (1L << (context.bitsPerLevel-1)); // halfSizePrime/2 if (pow(p,e) > bound) { // try the conservative setting instead cerr << "* p^e="<<pow(p,e)<<" is too big (bound="<<bound<<")\n"; conservative = true; } } if (conservative) { // set alpha, e with a "conservative" rho/p setAlphaE(alpha, e, rho/p, gamma, noise, logp, p2r, t); ePrime = e -r -logT; } // Compute highest key-Hamming-weight that still works (not more than 256) double qOver4 = (pow(p,e)+1)/4; for (t-=10; qOver4>=lowerBound2(p,r,ePrime,t,alpha) && qOver4>=lowerBound1(p,r,ePrime,t,alpha,noise) && t<257; t++); skHwt = t-1; // First part of Bootstrapping works wrt plaintext space p^{r'} alMod = new PAlgebraMod(context.zMStar, e-ePrime+r); ea = new EncryptedArray(context, *alMod); // Polynomial defaults to F0, PAlgebraMod explicitly given p2dConv = new PowerfulDCRT(context, mvec); // Initialize the linear polynomial for unpacking the slots zz_pBak bak; bak.save(); ea->getAlMod().restoreContext(); long nslots = ea->size(); long d = ea->getDegree(); const Mat<zz_p>& CBi=ea->getDerived(PA_zz_p()).getNormalBasisMatrixInverse(); vector<ZZX> LM; LM.resize(d); for (long i = 0; i < d; i++) // prepare the linear polynomial LM[i] = rep(CBi[i][0]); vector<ZZX> C; ea->buildLinPolyCoeffs(C, LM); // "build" the linear polynomial unpackSlotEncoding.resize(d); // encode the coefficients for (long j = 0; j < d; j++) { vector<ZZX> v(nslots); for (long k = 0; k < nslots; k++) v[k] = C[j]; ea->encode(unpackSlotEncoding[j], v); } firstMap = new EvalMap(*ea, minimal, mvec, true, build_cache); secondMap = new EvalMap(*context.ea, minimal, mvec, false, build_cache); } /********************************************************************/ /********************************************************************/ #ifdef DEBUG_PRINTOUT #include "debugging.h" long printFlag = FLAG_PRINT_VEC; #endif // Extract digits from fully packed slots void extractDigitsPacked(Ctxt& ctxt, long botHigh, long r, long ePrime, const vector<ZZX>& unpackSlotEncoding); // bootstrap a ciphertext to reduce noise void FHEPubKey::reCrypt(Ctxt &ctxt) { FHE_TIMER_START; // Some sanity checks for dummy ciphertext long ptxtSpace = ctxt.getPtxtSpace(); if (ctxt.isEmpty()) return; if (ctxt.parts.size()==1 && ctxt.parts[0].skHandle.isOne()) { // Dummy encryption, just ensure that it is reduced mod p ZZX poly = to_ZZX(ctxt.parts[0]); for (long i=0; i<poly.rep.length(); i++) poly[i] = to_ZZ( rem(poly[i],ptxtSpace) ); poly.normalize(); ctxt.DummyEncrypt(poly); return; } assert(recryptKeyID>=0); // check that we have bootstrapping data long p = getContext().zMStar.getP(); long r = getContext().alMod.getR(); long p2r = getContext().alMod.getPPowR(); // the bootstrapping key is encrypted relative to plaintext space p^{e-e'+r}. long e = getContext().rcData.e; long ePrime = getContext().rcData.ePrime; long p2ePrime = power_long(p,ePrime); long q = power_long(p,e)+1; assert(e>=r); #ifdef DEBUG_PRINTOUT cerr << "reCrypt: p="<<p<<", r="<<r<<", e="<<e<<" ePrime="<<ePrime << ", q="<<q<<endl; #endif // can only bootstrap ciphertext with plaintext-space dividing p^r assert(p2r % ptxtSpace == 0); FHE_NTIMER_START(preProcess); // Make sure that this ciphertxt is in canonical form if (!ctxt.inCanonicalForm()) ctxt.reLinearize(); // Mod-switch down if needed IndexSet s = ctxt.getPrimeSet() / getContext().specialPrimes; // set minus if (s.card()>2) { // leave only bottom two primes long frst = s.first(); long scnd = s.next(frst); IndexSet s2(frst,scnd); s.retain(s2); // retain only first two primes } ctxt.modDownToSet(s); // key-switch to the bootstrapping key ctxt.reLinearize(recryptKeyID); // "raw mod-switch" to the bootstrapping mosulus q=p^e+1. vector<ZZX> zzParts; // the mod-switched parts, in ZZX format double noise = ctxt.rawModSwitch(zzParts, q); noise = sqrt(noise); // Add multiples of p2r and q to make the zzParts divisible by p^{e'} long maxU=0; for (long i=0; i<(long)zzParts.size(); i++) { // make divisible by p^{e'} long newMax = makeDivisible(zzParts[i].rep, p2ePrime, p2r, q, getContext().rcData.alpha); zzParts[i].normalize(); // normalize after working directly on the rep if (maxU < newMax) maxU = newMax; } // Check that the estimated noise is still low if (noise + maxU*p2r*(skHwts[recryptKeyID]+1) > q/2) cerr << " * noise/q after makeDivisible = " << ((noise + maxU*p2r*(skHwts[recryptKeyID]+1))/q) << endl; for (long i=0; i<(long)zzParts.size(); i++) zzParts[i] /= p2ePrime; // divide by p^{e'} // Multiply the post-processed cipehrtext by the encrypted sKey #ifdef DEBUG_PRINTOUT cerr << "+ Before recryption "; decryptAndPrint(cerr, recryptEkey, *dbgKey, *dbgEa, printFlag); #endif double p0size = to_double(coeffsL2Norm(zzParts[0])); double p1size = to_double(coeffsL2Norm(zzParts[1])); ctxt = recryptEkey; ctxt.multByConstant(zzParts[1], p1size*p1size); ctxt.addConstant(zzParts[0], p0size*p0size); #ifdef DEBUG_PRINTOUT cerr << "+ Before linearTrans1 "; decryptAndPrint(cerr, ctxt, *dbgKey, *dbgEa, printFlag); #endif FHE_NTIMER_STOP(preProcess); // Move the powerful-basis coefficients to the plaintext slots FHE_NTIMER_START(LinearTransform1); ctxt.getContext().rcData.firstMap->apply(ctxt); FHE_NTIMER_STOP(LinearTransform1); #ifdef DEBUG_PRINTOUT cerr << "+ After linearTrans1 "; decryptAndPrint(cerr, ctxt, *dbgKey, *dbgEa, printFlag); #endif // Extract the digits e-e'+r-1,...,e-e' (from fully packed slots) extractDigitsPacked(ctxt, e-ePrime, r, ePrime, context.rcData.unpackSlotEncoding); #ifdef DEBUG_PRINTOUT cerr << "+ Before linearTrans2 "; decryptAndPrint(cerr, ctxt, *dbgKey, *dbgEa, printFlag); #endif // Move the slots back to powerful-basis coefficients FHE_NTIMER_START(LinearTransform2); ctxt.getContext().rcData.secondMap->apply(ctxt); FHE_NTIMER_STOP(LinearTransform2); } /*********************************************************************/ /*********************************************************************/ // Return in poly a polynomial with X^i encoded in all the slots static void x2iInSlots(ZZX& poly, long i, vector<ZZX>& xVec, const EncryptedArray& ea) { xVec.resize(ea.size()); ZZX x2i = ZZX(i,1); for (long j=0; j<(long)xVec.size(); j++) xVec[j] = x2i; ea.encode(poly, xVec); } // Make every entry of vec divisible by p^e by adding/subtracting multiples // of p^r and q, while keeping the added multiples small. Specifically, for // e>=2, an integer z can be made divisible by p^e via // z' = z + u * p^r + v*p^r * q, // with // |u|<=ceil(alpha p^{r(e-1)}/2) and |v|<=0.5+floor(beta p^{r(e-1)}/2), // for any alpha+beta=1. We assume that r<e and that q-1 is divisible by p^e. // Returns the largest absolute values of the u's and the new entries. // // This code is more general than we need, for bootstrapping we will always // have e>r. template<class VecInt> long makeDivisible(VecInt& vec, long p2e, long p2r, long q, double alpha) { assert(((p2e % p2r == 0) && (q % p2e == 1)) || ((p2r % p2e == 0) && (q % p2r == 1))); long maxU =0; ZZ maxZ; for (long i=0; i<vec.length(); i++) { ZZ z, z2; conv(z, vec[i]); long u=0, v=0; long zMod1=0, zMod2=0; if (p2r < p2e && alpha>0) { zMod1 = rem(z,p2r); if (zMod1 > p2r/2) zMod1 -= p2r; // map to the symmetric interval // make z divisible by p^r by adding a multiple of q z2 = z - to_ZZ(zMod1)*q; zMod2 = rem(z2,p2e); // z mod p^e, still divisible by p^r if (zMod2 > p2e/2) zMod2 -= p2e; // map to the symmetric interval zMod2 /= -p2r; // now z+ p^r*zMod2=0 (mod p^e) and |zMod2|<=p^{r(e-1)}/2 u = ceil(alpha * zMod2); v = zMod2 - u; // = floor((1-alpha) * zMod2) z = z2 + u*p2r + to_ZZ(q)*v*p2r; } else { // r >= e or alpha==0, use only mulitples of q zMod1 = rem(z,p2e); if (zMod1 > p2e/2) zMod1 -= p2e; // map to the symmetric interval z -= to_ZZ(zMod1) * q; } if (abs(u) > maxU) maxU = abs(u); if (abs(z) > maxZ) maxZ = abs(z); if (rem(z,p2e) != 0) { // sanity check cerr << "**error: original z["<<i<<"]=" << vec[i] << std::dec << ", p^r="<<p2r << ", p^e="<<p2e << endl; cerr << "z' = z - "<<zMod1<<"*q = "<< z2<<endl; cerr << "z''=z' +" <<u<<"*p^r +"<<v<<"*p^r*q = "<<z<<endl; exit(1); } conv(vec[i], z); // convert back to native format } return maxU; } // explicit instantiation for vec_ZZ and vec_long template long makeDivisible<vec_ZZ>(vec_ZZ& v, long p2e, long p2r, long q, double alpha); // template long makeDivisible<vec_long>(vec_long& v, long p2e, // long p2r, long q, double alpha); #ifdef FHE_BOOT_THREADS // Extract digits from fully packed slots, multithreaded version void extractDigitsPacked(Ctxt& ctxt, long botHigh, long r, long ePrime, const vector<ZZX>& unpackSlotEncoding) { FHE_TIMER_START; // Step 1: unpack the slots of ctxt FHE_NTIMER_START(unpack); ctxt.cleanUp(); // Apply the d automorphisms and store them in scratch area long d = ctxt.getContext().zMStar.getOrdP(); vector<Ctxt> unpacked(d, Ctxt(ZeroCtxtLike, ctxt)); { // explicit scope to force all temporaries to be released vector< shared_ptr<DoubleCRT> > coeff_vector; coeff_vector.resize(d); FHE_NTIMER_START(unpack1); for (long i = 0; i < d; i++) coeff_vector[i] = shared_ptr<DoubleCRT>(new DoubleCRT(unpackSlotEncoding[i], ctxt.getContext(), ctxt.getPrimeSet()) ); FHE_NTIMER_STOP(unpack1); FHE_NTIMER_START(unpack2); vector<Ctxt> frob(d, Ctxt(ZeroCtxtLike, ctxt)); NTL_EXEC_RANGE(d, first, last) // FIXME: implement using hoisting! for (long j = first; j < last; j++) { // process jth Frobenius frob[j] = ctxt; frob[j].frobeniusAutomorph(j); frob[j].cleanUp(); // FIXME: not clear if we should call cleanUp here } NTL_EXEC_RANGE_END FHE_NTIMER_STOP(unpack2); FHE_NTIMER_START(unpack3); Ctxt tmp1(ZeroCtxtLike, ctxt); for (long i = 0; i < d; i++) { for (long j = 0; j < d; j++) { tmp1 = frob[j]; tmp1.multByConstant(*coeff_vector[mcMod(i+j, d)]); unpacked[i] += tmp1; } } FHE_NTIMER_STOP(unpack3); } FHE_NTIMER_STOP(unpack); // Step 2: extract the digits top-1,...,0 from the slots of unpacked[i] long p = ctxt.getContext().zMStar.getP(); long p2r = power_long(p,r); long topHigh = botHigh + r-1; #ifdef DEBUG_PRINTOUT cerr << "+ After unpack "; decryptAndPrint(cerr, unpacked[0], *dbgKey, *dbgEa, printFlag); cerr << " extracting "<<(topHigh+1)<<" digits\n"; #endif if (p==2 && r>2) topHigh--; // For p==2 we sometime get a bit for free FHE_NTIMER_START(extractDigits); NTL_EXEC_RANGE(d, first, last) for (long i = first; i < last; i++) { vector<Ctxt> scratch; if (topHigh<=0) { // extracting LSB = no-op scratch.assign(1,unpacked[i]); } else { // extract digits topHigh...0, store them in scratch extractDigits(scratch, unpacked[i], topHigh+1); } // set upacked[i] = -\sum_{j=botHigh}^{topHigh} scratch[j] * p^{j-botHigh} if (topHigh >= (long)scratch.size()) { topHigh = scratch.size() -1; cerr << " @ suspect: not enough digits in extractDigitsPacked\n"; } unpacked[i] = scratch[topHigh]; for (long j=topHigh-1; j>=botHigh; --j) { unpacked[i].multByP(); unpacked[i] += scratch[j]; } if (p==2 && botHigh>0) { // For p==2, subtract also the previous bit //cerr << scratch.size() << " " << botHigh-1 << "\n"; unpacked.at(i) += scratch.at(botHigh-1); } unpacked[i].negate(); if (r>ePrime) { // Add in digits from the bottom part, if any long topLow = r-1 - ePrime; Ctxt tmp = scratch[topLow]; for (long j=topLow-1; j>=0; --j) { tmp.multByP(); tmp += scratch[j]; } if (ePrime>0) tmp.multByP(ePrime); // multiply by p^e' unpacked[i] += tmp; } unpacked[i].reducePtxtSpace(p2r); // Our plaintext space is now mod p^r } NTL_EXEC_RANGE_END FHE_NTIMER_STOP(extractDigits); #ifdef DEBUG_PRINTOUT cerr << "+ Before repack "; decryptAndPrint(cerr, unpacked[0], *dbgKey, *dbgEa, printFlag); #endif // Step 3: re-pack the slots FHE_NTIMER_START(repack); const EncryptedArray& ea2 = *ctxt.getContext().ea; ZZX xInSlots; vector<ZZX> xVec(ea2.size()); ctxt = unpacked[0]; for (long i=1; i<d; i++) { x2iInSlots(xInSlots, i, xVec, ea2); unpacked[i].multByConstant(xInSlots); ctxt += unpacked[i]; } FHE_NTIMER_STOP(repack); #ifdef DEBUG_PRINTOUT cerr << "+ After repack "; decryptAndPrint(cerr, ctxt, *dbgKey, *dbgEa, printFlag); #endif } #else // Extract digits from fully packed slots void extractDigitsPacked(Ctxt& ctxt, long botHigh, long r, long ePrime, const vector<ZZX>& unpackSlotEncoding) { FHE_TIMER_START; // Step 1: unpack the slots of ctxt FHE_NTIMER_START(unpack); ctxt.cleanUp(); // Apply the d automorphisms and store them in scratch area long d = ctxt.getContext().zMStar.getOrdP(); vector<Ctxt> scratch; // used below vector<Ctxt> unpacked(d, Ctxt(ZeroCtxtLike, ctxt)); { // explicit scope to force all temporaries to be released vector< shared_ptr<DoubleCRT> > coeff_vector; coeff_vector.resize(d); for (long i = 0; i < d; i++) coeff_vector[i] = shared_ptr<DoubleCRT>(new DoubleCRT(unpackSlotEncoding[i], ctxt.getContext(), ctxt.getPrimeSet()) ); Ctxt tmp1(ZeroCtxtLike, ctxt); Ctxt tmp2(ZeroCtxtLike, ctxt); // FIXME: implement using hoisting! for (long j = 0; j < d; j++) { // process jth Frobenius tmp1 = ctxt; tmp1.frobeniusAutomorph(j); tmp1.cleanUp(); // FIXME: not clear if we should call cleanUp here for (long i = 0; i < d; i++) { tmp2 = tmp1; tmp2.multByConstant(*coeff_vector[mcMod(i+j, d)]); unpacked[i] += tmp2; } } } FHE_NTIMER_STOP(unpack); // Step 2: extract the digits top-1,...,0 from the slots of unpacked[i] long p = ctxt.getContext().zMStar.getP(); long p2r = power_long(p,r); long topHigh = botHigh + r-1; #ifdef DEBUG_PRINTOUT cerr << "+ After unpack "; decryptAndPrint(cerr, unpacked[0], *dbgKey, *dbgEa, printFlag); cerr << " extracting "<<(topHigh+1)<<" digits\n"; #endif if (p==2 && r>2) topHigh--; // For p==2 we sometime get a bit for free FHE_NTIMER_START(extractDigits); for (long i=0; i<(long)unpacked.size(); i++) { if (topHigh<=0) { // extracting LSB = no-op scratch.assign(1,unpacked[i]); } else { // extract digits topHigh...0, store them in scratch extractDigits(scratch, unpacked[i], topHigh+1); } // set upacked[i] = -\sum_{j=botHigh}^{topHigh} scratch[j] * p^{j-botHigh} if (topHigh >= (long)scratch.size()) { topHigh = scratch.size() -1; cerr << " @ suspect: not enough digits in extractDigitsPacked\n"; } unpacked[i] = scratch[topHigh]; for (long j=topHigh-1; j>=botHigh; --j) { unpacked[i].multByP(); unpacked[i] += scratch[j]; } if (p==2 && botHigh>0) // For p==2, subtract also the previous bit unpacked[i] += scratch[botHigh-1]; unpacked[i].negate(); if (r>ePrime) { // Add in digits from the bottom part, if any long topLow = r-1 - ePrime; Ctxt tmp = scratch[topLow]; for (long j=topLow-1; j>=0; --j) { tmp.multByP(); tmp += scratch[j]; } if (ePrime>0) tmp.multByP(ePrime); // multiply by p^e' unpacked[i] += tmp; } unpacked[i].reducePtxtSpace(p2r); // Our plaintext space is now mod p^r } FHE_NTIMER_STOP(extractDigits); #ifdef DEBUG_PRINTOUT cerr << "+ Before repack "; decryptAndPrint(cerr, unpacked[0], *dbgKey, *dbgEa, printFlag); #endif // Step 3: re-pack the slots FHE_NTIMER_START(repack); const EncryptedArray& ea2 = *ctxt.getContext().ea; ZZX xInSlots; vector<ZZX> xVec(ea2.size()); ctxt = unpacked[0]; for (long i=1; i<d; i++) { x2iInSlots(xInSlots, i, xVec, ea2); unpacked[i].multByConstant(xInSlots); ctxt += unpacked[i]; } FHE_NTIMER_STOP(repack); } #endif // Use packed bootstrapping, so we can bootstrap all in just one go. void packedRecrypt(const CtPtrs& cPtrs, const std::vector<zzX>& unpackConsts, const EncryptedArray& ea) { FHEPubKey& pKey = (FHEPubKey&)cPtrs[0]->getPubKey(); // Allocate temporary ciphertexts for the recryption int nPacked = divc(cPtrs.size(), ea.getDegree()); // ceil(totoalNum/d) std::vector<Ctxt> cts(nPacked, Ctxt(pKey)); repack(CtPtrs_vectorCt(cts), cPtrs, ea); // pack ciphertexts // cout << "@"<< lsize(cts)<<std::flush; for (Ctxt& c: cts) { // then recrypt them c.reducePtxtSpace(2); // we only have recryption data for binary ctxt #ifdef DEBUG_PRINTOUT ZZX ptxt; decryptAndPrint((cout<<" before recryption "), c, *dbgKey, *dbgEa); dbgKey->Decrypt(ptxt, c); c.DummyEncrypt(ptxt); decryptAndPrint((cout<<" after recryption "), c, *dbgKey, *dbgEa); #else pKey.reCrypt(c); #endif } unpack(cPtrs, CtPtrs_vectorCt(cts), ea, unpackConsts); } // recrypt all ctxt at level < belowLvl void packedRecrypt(const CtPtrs& array, const std::vector<zzX>& unpackConsts, const EncryptedArray& ea, long belowLvl) { std::vector<Ctxt*> v; for (long i=0; i<array.size(); i++) if ( array.isSet(i) && !array[i]->isEmpty() && array[i]->findBaseLevel()<belowLvl ) v.push_back(array[i]); packedRecrypt(CtPtrs_vectorPt(v), unpackConsts, ea); } void packedRecrypt(const CtPtrMat& m, const std::vector<zzX>& unpackConsts, const EncryptedArray& ea, long belowLvl) { std::vector<Ctxt*> v; for (long i=0; i<m.size(); i++) for (long j=0; j<m[i].size(); j++) if ( m[i].isSet(j) && !m[i][j]->isEmpty() && m[i][j]->findBaseLevel()<belowLvl ) v.push_back(m[i][j]); packedRecrypt(CtPtrs_vectorPt(v), unpackConsts, ea); }
32.89886
82
0.623382
[ "vector" ]
075c1893e8a3b1e6bce060a9caa6b7e6b5fa3522
17,792
cc
C++
wrspice/devlib/hisim-1.1.0/hsm1set.cc
wrcad/xictools
f46ba6d42801426739cc8b2940a809b74f1641e2
[ "Apache-2.0" ]
73
2017-10-26T12:40:24.000Z
2022-03-02T16:59:43.000Z
wrspice/devlib/hisim-1.1.0/hsm1set.cc
chris-ayala/xictools
4ea72c118679caed700dab3d49a8d36445acaec3
[ "Apache-2.0" ]
12
2017-11-01T10:18:22.000Z
2022-03-20T19:35:36.000Z
wrspice/devlib/hisim-1.1.0/hsm1set.cc
chris-ayala/xictools
4ea72c118679caed700dab3d49a8d36445acaec3
[ "Apache-2.0" ]
34
2017-10-06T17:04:21.000Z
2022-02-18T16:22:03.000Z
/*========================================================================* * * * Distributed by Whiteley Research Inc., Sunnyvale, California, USA * * http://wrcad.com * * Copyright (C) 2017 Whiteley Research Inc., all rights reserved. * * Author: Stephen R. Whiteley, except as indicated. * * * * As fully as possible recognizing licensing terms and conditions * * imposed by earlier work from which this work was derived, if any, * * this work is released under the Apache License, Version 2.0 (the * * "License"). You may not use this file except in compliance with * * the License, and compliance with inherited licenses which are * * specified in a sub-header below this one if applicable. A copy * * of the License is provided with this distribution, or you may * * obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * See the License for the specific language governing permissions * * and limitations under the 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 NON- * * INFRINGEMENT. IN NO EVENT SHALL WHITELEY RESEARCH INCORPORATED * * OR STEPHEN R. WHITELEY 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. * * * *========================================================================* * XicTools Integrated Circuit Design System * * * * WRspice Circuit Simulation and Analysis Tool: Device Library * * * *========================================================================* $Id:$ *========================================================================*/ /*********************************************************************** HiSIM v1.1.0 File: hsm1set.c of HiSIM v1.1.0 Copyright (C) 2002 STARC June 30, 2002: developed by Hiroshima University and STARC June 30, 2002: posted by Keiichi MORIKAWA, STARC Physical Design Group ***********************************************************************/ #include "hsm1defs.h" #include "gencurrent.h" #include <stdio.h> #define HSM1nextModel next() #define HSM1nextInstance next() #define HSM1instances inst() #define CKTnode sCKTnode #define HSM1states GENstate #define HSM1name GENname #define CKTmkVolt(a, b, c, d) (a)->mkVolt(b, c, d) #define CKTdltNNum(c, n) namespace { int get_node_ptr(sCKT *ckt, sHSM1instance *inst) { TSTALLOC(HSM1DdPtr, HSM1dNode, HSM1dNode) TSTALLOC(HSM1GgPtr, HSM1gNode, HSM1gNode) TSTALLOC(HSM1SsPtr, HSM1sNode, HSM1sNode) TSTALLOC(HSM1BbPtr, HSM1bNode, HSM1bNode) TSTALLOC(HSM1DPdpPtr, HSM1dNodePrime, HSM1dNodePrime) TSTALLOC(HSM1SPspPtr, HSM1sNodePrime, HSM1sNodePrime) TSTALLOC(HSM1DdpPtr, HSM1dNode, HSM1dNodePrime) TSTALLOC(HSM1GbPtr, HSM1gNode, HSM1bNode) TSTALLOC(HSM1GdpPtr, HSM1gNode, HSM1dNodePrime) TSTALLOC(HSM1GspPtr, HSM1gNode, HSM1sNodePrime) TSTALLOC(HSM1SspPtr, HSM1sNode, HSM1sNodePrime) TSTALLOC(HSM1BdpPtr, HSM1bNode, HSM1dNodePrime) TSTALLOC(HSM1BspPtr, HSM1bNode, HSM1sNodePrime) TSTALLOC(HSM1DPspPtr, HSM1dNodePrime, HSM1sNodePrime) TSTALLOC(HSM1DPdPtr, HSM1dNodePrime, HSM1dNode) TSTALLOC(HSM1BgPtr, HSM1bNode, HSM1gNode) TSTALLOC(HSM1DPgPtr, HSM1dNodePrime, HSM1gNode) TSTALLOC(HSM1SPgPtr, HSM1sNodePrime, HSM1gNode) TSTALLOC(HSM1SPsPtr, HSM1sNodePrime, HSM1sNode) TSTALLOC(HSM1DPbPtr, HSM1dNodePrime, HSM1bNode) TSTALLOC(HSM1SPbPtr, HSM1sNodePrime, HSM1bNode) TSTALLOC(HSM1SPdpPtr, HSM1sNodePrime, HSM1dNodePrime) return (OK); } } int HSM1dev::setup(sGENmodel *genmod, sCKT *ckt, int *states) { sHSM1model *model = static_cast<sHSM1model*>(genmod); sHSM1instance *here; int error; CKTnode *tmp; /* loop through all the HSM1 device models */ for ( ;model != NULL ;model = model->HSM1nextModel ) { /* Default value Processing for HSM1 MOSFET Models */ if ( !model->HSM1_type_Given ) model->HSM1_type = NMOS ; /***/ if ( !model->HSM1_info_Given ) model->HSM1_info = 0 ; if ( !model->HSM1_noise_Given) model->HSM1_noise = 5; /* select noise model 5 */ if ( !model->HSM1_version_Given) model->HSM1_version = 100; /* default 100 */ if ( !model->HSM1_corsrd_Given ) model->HSM1_corsrd = 0 ; if ( !model->HSM1_coiprv_Given ) model->HSM1_coiprv = 1 ; if ( !model->HSM1_copprv_Given ) model->HSM1_copprv = 1 ; if ( !model->HSM1_cocgso_Given ) model->HSM1_cocgso = 0 ; if ( !model->HSM1_cocgdo_Given ) model->HSM1_cocgdo = 0 ; if ( !model->HSM1_cocgbo_Given ) model->HSM1_cocgbo = 0 ; if ( !model->HSM1_coadov_Given ) model->HSM1_coadov = 1 ; if ( !model->HSM1_coxx08_Given ) model->HSM1_coxx08 = 0 ; if ( !model->HSM1_coxx09_Given ) model->HSM1_coxx09 = 0 ; if ( !model->HSM1_coisub_Given ) model->HSM1_coisub = 0 ; if ( !model->HSM1_coiigs_Given ) model->HSM1_coiigs = 0 ; if ( !model->HSM1_cogidl_Given ) model->HSM1_cogidl = 0 ; if ( !model->HSM1_coovlp_Given ) model->HSM1_coovlp = 0 ; if ( !model->HSM1_conois_Given ) model->HSM1_conois = 0 ; if ( model->HSM1_version == 110 ) {/* HiSIM1.1 */ if ( !model->HSM1_coisti_Given ) model->HSM1_coisti = 0 ; } /***/ if ( !model->HSM1_vmax_Given ) model->HSM1_vmax = 1.00e+7 ; if ( !model->HSM1_bgtmp1_Given ) model->HSM1_bgtmp1 = 9.03e-5 ; if ( !model->HSM1_bgtmp2_Given ) model->HSM1_bgtmp2 = 3.05e-7 ; if ( !model->HSM1_tox_Given ) model->HSM1_tox = 3.60e-9 ; if ( !model->HSM1_dl_Given ) model->HSM1_dl = 0.0 ; if ( !model->HSM1_dw_Given ) model->HSM1_dw = 0.0 ; if ( model->HSM1_version == 100 ) { /* HiSIM1.0 */ if ( !model->HSM1_xj_Given ) model->HSM1_xj = 0.0 ; if ( model->HSM1_xqy_Given ) { printf("warning(HiSIM): the model parameter XQY is only available in VERSION = 110.\n"); printf(" XQY = %f - ignored\n", model->HSM1_xqy); } } else if ( model->HSM1_version == 110 ) { /* HiSIM1.1 */ if ( !model->HSM1_xqy_Given ) model->HSM1_xqy = 0.0; if ( model->HSM1_xj_Given ) { printf("warning(HiSIM): the model parameter XJ is only available in VERSION = 100.\n"); printf(" XJ = %f - ignored\n", model->HSM1_xj); } } if ( !model->HSM1_rs_Given ) model->HSM1_rs = 0.0 ; if ( !model->HSM1_rd_Given ) model->HSM1_rd = 0.0 ; if ( !model->HSM1_vfbc_Given ) model->HSM1_vfbc = -0.722729 ; if ( !model->HSM1_nsubc_Given ) model->HSM1_nsubc = 5.94e+17 ; if ( !model->HSM1_parl1_Given ) model->HSM1_parl1 = 1.0 ; if ( !model->HSM1_parl2_Given ) model->HSM1_parl2 = 2.20e-8 ; if ( !model->HSM1_lp_Given ) model->HSM1_lp = 0.0 ; if ( !model->HSM1_nsubp_Given ) model->HSM1_nsubp = 5.94e+17 ; if ( !model->HSM1_scp1_Given ) model->HSM1_scp1 = 0.0 ; if ( !model->HSM1_scp2_Given ) model->HSM1_scp2 = 0.0 ; if ( !model->HSM1_scp3_Given ) model->HSM1_scp3 = 0.0 ; if ( !model->HSM1_sc1_Given ) model->HSM1_sc1 = 13.5 ; if ( !model->HSM1_sc2_Given ) model->HSM1_sc2 = 1.8 ; if ( !model->HSM1_sc3_Given ) model->HSM1_sc3 = 0.0 ; if ( !model->HSM1_pgd1_Given ) model->HSM1_pgd1 = 0.0 ; if ( !model->HSM1_pgd2_Given ) model->HSM1_pgd2 = 0.0 ; if ( !model->HSM1_pgd3_Given ) model->HSM1_pgd3 = 0.0 ; if ( !model->HSM1_ndep_Given ) model->HSM1_ndep = 1.0 ; if ( !model->HSM1_ninv_Given ) model->HSM1_ninv = 0.5 ; if ( !model->HSM1_ninvd_Given ) model->HSM1_ninvd = 0.0 ; if ( !model->HSM1_muecb0_Given ) model->HSM1_muecb0 = 300.0 ; if ( !model->HSM1_muecb1_Given ) model->HSM1_muecb1 = 30.0 ; if ( !model->HSM1_mueph1_Given ) model->HSM1_mueph1 = 1.00e+7 ; if ( !model->HSM1_mueph0_Given ) model->HSM1_mueph0 = 0.295 ; if ( !model->HSM1_mueph2_Given ) model->HSM1_mueph2 = 0.0 ; if ( !model->HSM1_w0_Given ) model->HSM1_w0 = 0.0 ; if ( !model->HSM1_muesr1_Given ) model->HSM1_muesr1 = 7.00e+8 ; if ( !model->HSM1_muesr0_Given ) model->HSM1_muesr0 = 1.0 ; if ( !model->HSM1_muetmp_Given ) model->HSM1_muetmp = 0.0 ; /***/ if ( !model->HSM1_bb_Given ) { if (model->HSM1_type == NMOS) model->HSM1_bb = 2.0 ; else model->HSM1_bb = 1.0 ; } /***/ if ( !model->HSM1_vds0_Given ) model->HSM1_vds0 = 0.05 ; if ( !model->HSM1_bc0_Given ) model->HSM1_bc0 = 0.0 ; if ( !model->HSM1_bc1_Given ) model->HSM1_bc1 = 0.0 ; if ( !model->HSM1_sub1_Given ) model->HSM1_sub1 = 0.0 ; if ( !model->HSM1_sub2_Given ) model->HSM1_sub2 = -70.0 ; if ( !model->HSM1_sub3_Given ) model->HSM1_sub3 = 1.0 ; if ( model->HSM1_version == 110) { /* HiSIM1.1 */ if ( !model->HSM1_wvthsc_Given ) model->HSM1_wvthsc = 0.0 ; if ( !model->HSM1_nsti_Given ) model->HSM1_nsti = 1.0e17 ; if ( !model->HSM1_wsti_Given ) model->HSM1_wsti = 0.0 ; } if ( !model->HSM1_tpoly_Given ) model->HSM1_tpoly = 0.0 ; if ( !model->HSM1_js0_Given ) model->HSM1_js0 = 1.0e-4 ; if ( !model->HSM1_js0sw_Given ) model->HSM1_js0sw = 0.0 ; if ( !model->HSM1_nj_Given ) model->HSM1_nj = 1.0 ; if ( !model->HSM1_njsw_Given ) model->HSM1_njsw = 1.0 ; if ( !model->HSM1_xti_Given ) model->HSM1_xti = 3.0 ; if ( !model->HSM1_cj_Given ) model->HSM1_cj = 8.397247e-04; if ( !model->HSM1_cjsw_Given ) model->HSM1_cjsw = 5.0e-10 ; if ( !model->HSM1_cjswg_Given ) model->HSM1_cjswg = 5.0e-10 ; if ( !model->HSM1_mj_Given ) model->HSM1_mj = 0.5 ; if ( !model->HSM1_mjsw_Given ) model->HSM1_mjsw = 0.33 ; if ( !model->HSM1_mjswg_Given ) model->HSM1_mjswg = 0.33 ; if ( !model->HSM1_pb_Given ) model->HSM1_pb = 1.0 ; if ( !model->HSM1_pbsw_Given ) model->HSM1_pbsw = 1.0 ; if ( !model->HSM1_pbswg_Given ) model->HSM1_pbswg = 1.0 ; if ( !model->HSM1_xpolyd_Given ) model->HSM1_xpolyd = 0.0 ; if ( !model->HSM1_clm1_Given ) model->HSM1_clm1 = 0.3e0 ; if ( !model->HSM1_clm2_Given ) model->HSM1_clm2 = 0.0 ; if ( !model->HSM1_clm3_Given ) model->HSM1_clm3 = 0.0 ; if ( !model->HSM1_rpock1_Given ) model->HSM1_rpock1 = 0.0 ; if ( !model->HSM1_rpock2_Given ) model->HSM1_rpock2 = 0.0 ; if ( model->HSM1_version == 110 ) { /* HiSIM1.1 */ if ( !model->HSM1_rpocp1_Given ) model->HSM1_rpocp1 = 0.0 ; if ( !model->HSM1_rpocp2_Given ) model->HSM1_rpocp2 = 0.0 ; } if ( !model->HSM1_vover_Given ) model->HSM1_vover = 0.0 ; if ( !model->HSM1_voverp_Given ) model->HSM1_voverp = 0.0 ; if ( !model->HSM1_wfc_Given ) model->HSM1_wfc = 0.0 ; if ( !model->HSM1_qme1_Given ) model->HSM1_qme1 = 0.0 ; if ( !model->HSM1_qme2_Given ) model->HSM1_qme2 = 0.0 ; if ( !model->HSM1_qme3_Given ) model->HSM1_qme3 = 0.0 ; if ( !model->HSM1_gidl1_Given ) model->HSM1_gidl1 = 0.0 ; if ( !model->HSM1_gidl2_Given ) model->HSM1_gidl2 = 0.0 ; if ( !model->HSM1_gidl3_Given ) model->HSM1_gidl3 = 0.0 ; if ( !model->HSM1_gleak1_Given ) model->HSM1_gleak1 = 0.0 ; if ( !model->HSM1_gleak2_Given ) model->HSM1_gleak2 = 0.0 ; if ( !model->HSM1_gleak3_Given ) model->HSM1_gleak3 = 0.0 ; if ( !model->HSM1_vzadd0_Given ) model->HSM1_vzadd0 = 1.0e-2 ; if ( !model->HSM1_pzadd0_Given ) model->HSM1_pzadd0 = 1.0e-3 ; if ( !model->HSM1_nftrp_Given ) model->HSM1_nftrp = 100e9 ; if ( !model->HSM1_nfalp_Given ) model->HSM1_nfalp = 2.00e-15 ; if ( !model->HSM1_cit_Given ) model->HSM1_cit = 0.0 ; /* for flicker noise the same as BSIM3 */ if ( !model->HSM1_ef_Given ) model->HSM1_ef = 0.0; if ( !model->HSM1_af_Given ) model->HSM1_af = 1.0; if ( !model->HSM1_kf_Given ) model->HSM1_kf = 0.0; /* loop through all the instances of the model */ for ( here = model->HSM1instances ;here != NULL ; here = here->HSM1nextInstance ) { /* allocate a chunk of the state vector */ here->HSM1states = *states; *states += HSM1numStates; /* perform the parameter defaulting */ /* if ( !here->HSM1_l_Given ) here->HSM1_l = 1.50e-4 ; if ( !here->HSM1_w_Given ) here->HSM1_w = 5.55e-4 ; */ if ( !here->HSM1_l_Given ) here->HSM1_l = ckt->mos_default_l(); if ( !here->HSM1_w_Given ) here->HSM1_w = ckt->mos_default_w(); if ( !here->HSM1_ad_Given ) here->HSM1_ad = ckt->mos_default_ad(); if ( !here->HSM1_as_Given ) here->HSM1_as = ckt->mos_default_as(); if ( !here->HSM1_pd_Given ) here->HSM1_pd = 0.0 ; if ( !here->HSM1_ps_Given ) here->HSM1_ps = 0.0 ; if ( !here->HSM1_nrd_Given ) here->HSM1_nrd = 0.0 ; if ( !here->HSM1_nrs_Given ) here->HSM1_nrs = 0.0 ; if ( !here->HSM1_temp_Given ) here->HSM1_temp = 300.15 ; if ( !here->HSM1_dtemp_Given ) here->HSM1_dtemp = 0.0 ; if ( !here->HSM1_icVBS_Given ) here->HSM1_icVBS = 0.0; if ( !here->HSM1_icVDS_Given ) here->HSM1_icVDS = 0.0; if ( !here->HSM1_icVGS_Given ) here->HSM1_icVGS = 0.0; /* added by K.M. */ here->HSM1_weff = here->HSM1_w - 2.0e0 * model->HSM1_dw; here->HSM1_leff = here->HSM1_l - 2.0e0 * model->HSM1_dl; /* process source/drain series resistance added by K.M. */ /* Drain and source conductances are always zero, because there is no sheet resistance in HSM1 model param. if ( model->HSM1_corsrd ) here->HSM1drainConductance = 0.0; else here->HSM1drainConductance = model->HSM1_rs / here->HSM1_weff; if ( here->HSM1drainConductance > 0.0 ) here->HSM1drainConductance = 1.0 / here->HSM1drainConductance; else here->HSM1drainConductance = 0.0; if ( model->HSM1_corsrd ) here->HSM1sourceConductance = 0.0; else here->HSM1sourceConductance = model->HSM1_rd / here->HSM1_weff; if ( here->HSM1sourceConductance > 0.0 ) here->HSM1sourceConductance = 1.0 / here->HSM1sourceConductance; else here->HSM1sourceConductance = 0.0; */ here->HSM1drainConductance = 0.0; here->HSM1sourceConductance = 0.0; /* process drain series resistance */ if( here->HSM1drainConductance > 0.0 && here->HSM1dNodePrime == 0 ) { error = CKTmkVolt(ckt, &tmp, here->HSM1name, "drain"); if (error) return(error); here->HSM1dNodePrime = tmp->number(); } else { here->HSM1dNodePrime = here->HSM1dNode; } /* process source series resistance */ if( here->HSM1sourceConductance > 0.0 && here->HSM1sNodePrime == 0 ) { if ( here->HSM1sNodePrime == 0 ) { error = CKTmkVolt(ckt, &tmp, here->HSM1name, "source"); if (error) return(error); here->HSM1sNodePrime = tmp->number(); } } else { here->HSM1sNodePrime = here->HSM1sNode; } /* set Sparse Matrix Pointers */ /* macro to make elements with built in test for out of memory */ /* SRW #define TSTALLOC(ptr,first,second) \ if((here->ptr = SMPmakeElt(matrix,here->first,here->second))==(double *)NULL){\ return(E_NOMEM);\ } */ error = get_node_ptr(ckt, here); if (error != OK) return (error); } } return(OK); } // SRW #undef inst #define HSM1model sHSM1model #define HSM1instance sHSM1instance int HSM1dev::unsetup(sGENmodel *inModel, sCKT*) { #ifndef HAS_BATCHSIM HSM1model *model; HSM1instance *here; for (model = (HSM1model *)inModel; model != NULL; model = model->HSM1nextModel) { for (here = model->HSM1instances; here != NULL; here=here->HSM1nextInstance) { if (here->HSM1dNodePrime && here->HSM1dNodePrime != here->HSM1dNode) { CKTdltNNum(ckt, here->HSM1dNodePrime); here->HSM1dNodePrime = 0; } if (here->HSM1sNodePrime && here->HSM1sNodePrime != here->HSM1sNode) { CKTdltNNum(ckt, here->HSM1sNodePrime); here->HSM1sNodePrime = 0; } } } #endif return OK; } // SRW - reset the matrix element pointers. // int HSM1dev::resetup(sGENmodel *inModel, sCKT *ckt) { for (sHSM1model *model = (sHSM1model*)inModel; model; model = model->next()) { for (sHSM1instance *here = model->inst(); here; here = here->next()) { int error = get_node_ptr(ckt, here); if (error != OK) return (error); } } return (OK); } HSM1adj::HSM1adj() { matrix = new dvaMatrix; } HSM1adj::~HSM1adj() { delete matrix; }
44.148883
96
0.580542
[ "vector", "model" ]
075ca88e1461b4df8cfae760f8cb436372c751e7
989
cpp
C++
source-code/Tbb/BackSubstitution/src/solver.cpp
gjbex/Scientific-C-
d7aeb88743ffa2a43b1df1569a9200b2447f401c
[ "CC-BY-4.0" ]
115
2015-03-23T13:34:42.000Z
2022-03-21T00:27:21.000Z
source-code/Tbb/BackSubstitution/src/solver.cpp
gjbex/Scientific-C-
d7aeb88743ffa2a43b1df1569a9200b2447f401c
[ "CC-BY-4.0" ]
56
2015-02-25T15:04:26.000Z
2022-01-03T07:42:48.000Z
source-code/Tbb/BackSubstitution/src/solver.cpp
gjbex/Scientific-C-
d7aeb88743ffa2a43b1df1569a9200b2447f401c
[ "CC-BY-4.0" ]
59
2015-11-26T11:44:51.000Z
2022-03-21T00:27:22.000Z
#include <cmath> #include "equations.h" std::vector<double> solve_serial(const Equations& eqns) { if (eqns.nr_eqns() == 0) throw std::invalid_argument("no equations in set"); std::vector<double> x; x.push_back(eqns.rhs(0)/eqns.coeff(0, 0)); for (size_t eq_nr = 1; eq_nr < eqns.nr_eqns(); ++eq_nr) { double sum {0.0}; for (size_t coeff_nr = 0; coeff_nr < eq_nr; ++coeff_nr) sum += eqns.coeff(eq_nr, coeff_nr)*x[coeff_nr]; x.push_back((eqns.rhs(eq_nr) - sum)/eqns.coeff(eq_nr, eq_nr)); } return x; } std::vector<double> check_serial(const Equations& eqns, const std::vector<double> x) { std::vector<double> delta; for (size_t eq_nr = 0; eq_nr < eqns.nr_eqns(); ++eq_nr) { double sum {0.0}; for (size_t coeff_nr = 0; coeff_nr <= eq_nr; ++coeff_nr) sum += eqns.coeff(eq_nr, coeff_nr)*x[coeff_nr]; delta.push_back(abs((sum - eqns.rhs(eq_nr))/x[eq_nr])); } return delta; }
35.321429
86
0.605662
[ "vector" ]
075d5898a984a1168ee88ad6576e896a4741611e
36,079
cpp
C++
src/ttauri/GFX/gfx_device_vulkan.cpp
benshurts/ttauri-gui
22eeb8f202dcfa0769653104f9b090030fbd9290
[ "BSL-1.0" ]
2
2021-09-21T00:07:50.000Z
2021-09-21T22:28:28.000Z
src/ttauri/GFX/gfx_device_vulkan.cpp
benshurts/ttauri-gui
22eeb8f202dcfa0769653104f9b090030fbd9290
[ "BSL-1.0" ]
null
null
null
src/ttauri/GFX/gfx_device_vulkan.cpp
benshurts/ttauri-gui
22eeb8f202dcfa0769653104f9b090030fbd9290
[ "BSL-1.0" ]
null
null
null
// Copyright Take Vos 2019-2021. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at https://www.boost.org/LICENSE_1_0.txt) #include "gfx_device_vulkan.hpp" #include "gfx_system_vulkan.hpp" #include "gfx_surface_vulkan.hpp" #include "pipeline_image.hpp" #include "pipeline_image_device_shared.hpp" #include "../GUI/gui_window.hpp" #include "../resource_view.hpp" #include <span> namespace tt { #define QUEUE_CAPABILITY_GRAPHICS 1 #define QUEUE_CAPABILITY_COMPUTE 2 #define QUEUE_CAPABILITY_PRESENT 4 #define QUEUE_CAPABILITY_GRAPHICS_AND_PRESENT (QUEUE_CAPABILITY_GRAPHICS | QUEUE_CAPABILITY_PRESENT) #define QUEUE_CAPABILITY_ALL (QUEUE_CAPABILITY_GRAPHICS | QUEUE_CAPABILITY_COMPUTE | QUEUE_CAPABILITY_PRESENT) static bool hasRequiredExtensions(const vk::PhysicalDevice &physicalDevice, const std::vector<const char *> &requiredExtensions) { auto availableExtensions = std::unordered_set<std::string>(); for (auto availableExtensionProperties : physicalDevice.enumerateDeviceExtensionProperties()) { availableExtensions.insert(std::string(availableExtensionProperties.extensionName.data())); } for (auto requiredExtension : requiredExtensions) { if (availableExtensions.count(requiredExtension) == 0) { return false; } } return true; } static bool meetsRequiredLimits(const vk::PhysicalDevice &physicalDevice, const vk::PhysicalDeviceLimits &requiredLimits) { return true; } static bool hasRequiredFeatures(const vk::PhysicalDevice &physicalDevice, const vk::PhysicalDeviceFeatures &requiredFeatures) { ttlet availableFeatures = physicalDevice.getFeatures(); auto meetsRequirements = true; meetsRequirements &= (requiredFeatures.robustBufferAccess == VK_TRUE) ? (availableFeatures.robustBufferAccess == VK_TRUE) : true; meetsRequirements &= (requiredFeatures.fullDrawIndexUint32 == VK_TRUE) ? (availableFeatures.fullDrawIndexUint32 == VK_TRUE) : true; meetsRequirements &= (requiredFeatures.imageCubeArray == VK_TRUE) ? (availableFeatures.imageCubeArray == VK_TRUE) : true; meetsRequirements &= (requiredFeatures.independentBlend == VK_TRUE) ? (availableFeatures.independentBlend == VK_TRUE) : true; meetsRequirements &= (requiredFeatures.geometryShader == VK_TRUE) ? (availableFeatures.geometryShader == VK_TRUE) : true; meetsRequirements &= (requiredFeatures.tessellationShader == VK_TRUE) ? (availableFeatures.tessellationShader == VK_TRUE) : true; meetsRequirements &= (requiredFeatures.sampleRateShading == VK_TRUE) ? (availableFeatures.sampleRateShading == VK_TRUE) : true; meetsRequirements &= (requiredFeatures.dualSrcBlend == VK_TRUE) ? (availableFeatures.dualSrcBlend == VK_TRUE) : true; meetsRequirements &= (requiredFeatures.logicOp == VK_TRUE) ? (availableFeatures.logicOp == VK_TRUE) : true; meetsRequirements &= (requiredFeatures.multiDrawIndirect == VK_TRUE) ? (availableFeatures.multiDrawIndirect == VK_TRUE) : true; meetsRequirements &= (requiredFeatures.drawIndirectFirstInstance == VK_TRUE) ? (availableFeatures.drawIndirectFirstInstance == VK_TRUE) : true; meetsRequirements &= (requiredFeatures.depthClamp == VK_TRUE) ? (availableFeatures.depthClamp == VK_TRUE) : true; meetsRequirements &= (requiredFeatures.depthBiasClamp == VK_TRUE) ? (availableFeatures.depthBiasClamp == VK_TRUE) : true; meetsRequirements &= (requiredFeatures.fillModeNonSolid == VK_TRUE) ? (availableFeatures.fillModeNonSolid == VK_TRUE) : true; meetsRequirements &= (requiredFeatures.depthBounds == VK_TRUE) ? (availableFeatures.depthBounds == VK_TRUE) : true; meetsRequirements &= (requiredFeatures.wideLines == VK_TRUE) ? (availableFeatures.wideLines == VK_TRUE) : true; meetsRequirements &= (requiredFeatures.largePoints == VK_TRUE) ? (availableFeatures.largePoints == VK_TRUE) : true; meetsRequirements &= (requiredFeatures.alphaToOne == VK_TRUE) ? (availableFeatures.alphaToOne == VK_TRUE) : true; meetsRequirements &= (requiredFeatures.multiViewport == VK_TRUE) ? (availableFeatures.multiViewport == VK_TRUE) : true; meetsRequirements &= (requiredFeatures.samplerAnisotropy == VK_TRUE) ? (availableFeatures.samplerAnisotropy == VK_TRUE) : true; meetsRequirements &= (requiredFeatures.textureCompressionETC2 == VK_TRUE) ? (availableFeatures.textureCompressionETC2 == VK_TRUE) : true; meetsRequirements &= (requiredFeatures.textureCompressionASTC_LDR == VK_TRUE) ? (availableFeatures.textureCompressionASTC_LDR == VK_TRUE) : true; meetsRequirements &= (requiredFeatures.textureCompressionBC == VK_TRUE) ? (availableFeatures.textureCompressionBC == VK_TRUE) : true; meetsRequirements &= (requiredFeatures.occlusionQueryPrecise == VK_TRUE) ? (availableFeatures.occlusionQueryPrecise == VK_TRUE) : true; meetsRequirements &= (requiredFeatures.pipelineStatisticsQuery == VK_TRUE) ? (availableFeatures.pipelineStatisticsQuery == VK_TRUE) : true; meetsRequirements &= (requiredFeatures.vertexPipelineStoresAndAtomics == VK_TRUE) ? (availableFeatures.vertexPipelineStoresAndAtomics == VK_TRUE) : true; meetsRequirements &= (requiredFeatures.fragmentStoresAndAtomics == VK_TRUE) ? (availableFeatures.fragmentStoresAndAtomics == VK_TRUE) : true; meetsRequirements &= (requiredFeatures.shaderTessellationAndGeometryPointSize == VK_TRUE) ? (availableFeatures.shaderTessellationAndGeometryPointSize == VK_TRUE) : true; meetsRequirements &= (requiredFeatures.shaderImageGatherExtended == VK_TRUE) ? (availableFeatures.shaderImageGatherExtended == VK_TRUE) : true; meetsRequirements &= (requiredFeatures.shaderStorageImageExtendedFormats == VK_TRUE) ? (availableFeatures.shaderStorageImageExtendedFormats == VK_TRUE) : true; meetsRequirements &= (requiredFeatures.shaderStorageImageMultisample == VK_TRUE) ? (availableFeatures.shaderStorageImageMultisample == VK_TRUE) : true; meetsRequirements &= (requiredFeatures.shaderStorageImageReadWithoutFormat == VK_TRUE) ? (availableFeatures.shaderStorageImageReadWithoutFormat == VK_TRUE) : true; meetsRequirements &= (requiredFeatures.shaderStorageImageWriteWithoutFormat == VK_TRUE) ? (availableFeatures.shaderStorageImageWriteWithoutFormat == VK_TRUE) : true; meetsRequirements &= (requiredFeatures.shaderUniformBufferArrayDynamicIndexing == VK_TRUE) ? (availableFeatures.shaderUniformBufferArrayDynamicIndexing == VK_TRUE) : true; meetsRequirements &= (requiredFeatures.shaderSampledImageArrayDynamicIndexing == VK_TRUE) ? (availableFeatures.shaderSampledImageArrayDynamicIndexing == VK_TRUE) : true; meetsRequirements &= (requiredFeatures.shaderStorageBufferArrayDynamicIndexing == VK_TRUE) ? (availableFeatures.shaderStorageBufferArrayDynamicIndexing == VK_TRUE) : true; meetsRequirements &= (requiredFeatures.shaderStorageImageArrayDynamicIndexing == VK_TRUE) ? (availableFeatures.shaderStorageImageArrayDynamicIndexing == VK_TRUE) : true; meetsRequirements &= (requiredFeatures.shaderClipDistance == VK_TRUE) ? (availableFeatures.shaderClipDistance == VK_TRUE) : true; meetsRequirements &= (requiredFeatures.shaderCullDistance == VK_TRUE) ? (availableFeatures.shaderCullDistance == VK_TRUE) : true; meetsRequirements &= (requiredFeatures.shaderFloat64 == VK_TRUE) ? (availableFeatures.shaderFloat64 == VK_TRUE) : true; meetsRequirements &= (requiredFeatures.shaderInt64 == VK_TRUE) ? (availableFeatures.shaderInt64 == VK_TRUE) : true; meetsRequirements &= (requiredFeatures.shaderInt16 == VK_TRUE) ? (availableFeatures.shaderInt16 == VK_TRUE) : true; meetsRequirements &= (requiredFeatures.shaderResourceResidency == VK_TRUE) ? (availableFeatures.shaderResourceResidency == VK_TRUE) : true; meetsRequirements &= (requiredFeatures.shaderResourceMinLod == VK_TRUE) ? (availableFeatures.shaderResourceMinLod == VK_TRUE) : true; meetsRequirements &= (requiredFeatures.sparseBinding == VK_TRUE) ? (availableFeatures.sparseBinding == VK_TRUE) : true; meetsRequirements &= (requiredFeatures.sparseResidencyBuffer == VK_TRUE) ? (availableFeatures.sparseResidencyBuffer == VK_TRUE) : true; meetsRequirements &= (requiredFeatures.sparseResidencyImage2D == VK_TRUE) ? (availableFeatures.sparseResidencyImage2D == VK_TRUE) : true; meetsRequirements &= (requiredFeatures.sparseResidencyImage3D == VK_TRUE) ? (availableFeatures.sparseResidencyImage3D == VK_TRUE) : true; meetsRequirements &= (requiredFeatures.sparseResidency2Samples == VK_TRUE) ? (availableFeatures.sparseResidency2Samples == VK_TRUE) : true; meetsRequirements &= (requiredFeatures.sparseResidency4Samples == VK_TRUE) ? (availableFeatures.sparseResidency4Samples == VK_TRUE) : true; meetsRequirements &= (requiredFeatures.sparseResidency8Samples == VK_TRUE) ? (availableFeatures.sparseResidency8Samples == VK_TRUE) : true; meetsRequirements &= (requiredFeatures.sparseResidency16Samples == VK_TRUE) ? (availableFeatures.sparseResidency16Samples == VK_TRUE) : true; meetsRequirements &= (requiredFeatures.sparseResidencyAliased == VK_TRUE) ? (availableFeatures.sparseResidencyAliased == VK_TRUE) : true; meetsRequirements &= (requiredFeatures.variableMultisampleRate == VK_TRUE) ? (availableFeatures.variableMultisampleRate == VK_TRUE) : true; meetsRequirements &= (requiredFeatures.inheritedQueries == VK_TRUE) ? (availableFeatures.inheritedQueries == VK_TRUE) : true; return meetsRequirements; } gfx_device_vulkan::gfx_device_vulkan(gfx_system &system, vk::PhysicalDevice physicalDevice) : gfx_device(system), physicalIntrinsic(std::move(physicalDevice)) { auto result = physicalIntrinsic.getProperties2KHR<vk::PhysicalDeviceProperties2, vk::PhysicalDeviceIDProperties>( narrow_cast<gfx_system_vulkan &>(system).loader()); auto resultDeviceProperties2 = result.get<vk::PhysicalDeviceProperties2>(); auto resultDeviceIDProperties = result.get<vk::PhysicalDeviceIDProperties>(); requiredExtensions.push_back(VK_KHR_GET_MEMORY_REQUIREMENTS_2_EXTENSION_NAME); requiredExtensions.push_back(VK_KHR_SWAPCHAIN_EXTENSION_NAME); requiredExtensions.push_back(VK_KHR_MAINTENANCE2_EXTENSION_NAME); requiredExtensions.push_back(VK_KHR_IMAGE_FORMAT_LIST_EXTENSION_NAME); deviceID = resultDeviceProperties2.properties.deviceID; vendorID = resultDeviceProperties2.properties.vendorID; deviceName = std::string(resultDeviceProperties2.properties.deviceName.data()); deviceUUID = uuid::from_big_endian(resultDeviceIDProperties.deviceUUID); physicalProperties = physicalIntrinsic.getProperties(); initialize_device(); } gfx_device_vulkan::~gfx_device_vulkan() { try { ttlet lock = std::scoped_lock(gfx_system_mutex); toneMapperPipeline->destroy(this); toneMapperPipeline = nullptr; SDFPipeline->destroy(this); SDFPipeline = nullptr; imagePipeline->destroy(this); imagePipeline = nullptr; boxPipeline->destroy(this); boxPipeline = nullptr; flatPipeline->destroy(this); flatPipeline = nullptr; destroy_quad_index_buffer(); vmaDestroyAllocator(allocator); for (ttlet &queue : _queues) { intrinsic.destroy(queue.command_pool); } intrinsic.destroy(); } catch (std::exception const &e) { tt_log_fatal("Could not properly destruct gfx_device_vulkan. '{}'", e.what()); } } /** Get a graphics queue. */ [[nodiscard]] gfx_queue_vulkan const &gfx_device_vulkan::get_graphics_queue() const noexcept { for (auto &queue : _queues) { if (queue.flags & vk::QueueFlagBits::eGraphics) { return queue; } } tt_no_default(); } [[nodiscard]] gfx_queue_vulkan const &gfx_device_vulkan::get_graphics_queue(gfx_surface const &surface) const noexcept { ttlet &surface_ = narrow_cast<gfx_surface_vulkan const &>(surface).intrinsic; // First try to find a graphics queue which can also present. gfx_queue_vulkan const *graphics_queue = nullptr; for (auto &queue : _queues) { if (queue.flags & vk::QueueFlagBits::eGraphics) { if (physicalIntrinsic.getSurfaceSupportKHR(queue.family_queue_index, surface_)) { return queue; } if (not graphics_queue) { graphics_queue = &queue; } } } tt_axiom(graphics_queue); return *graphics_queue; } [[nodiscard]] gfx_queue_vulkan const &gfx_device_vulkan::get_present_queue(gfx_surface const &surface) const noexcept { ttlet &surface_ = narrow_cast<gfx_surface_vulkan const &>(surface).intrinsic; // First try to find a graphics queue which can also present. gfx_queue_vulkan const *present_queue = nullptr; for (auto &queue : _queues) { if (physicalIntrinsic.getSurfaceSupportKHR(queue.family_queue_index, surface_)) { if (queue.flags & vk::QueueFlagBits::eGraphics) { return queue; } if (not present_queue) { present_queue = &queue; } } } tt_axiom(present_queue); return *present_queue; } [[nodiscard]] vk::SurfaceFormatKHR gfx_device_vulkan::get_surface_format(gfx_surface const &surface, int *score) const noexcept { ttlet &surface_ = narrow_cast<gfx_surface_vulkan const &>(surface).intrinsic; auto best_surface_format = vk::SurfaceFormatKHR{}; auto best_surface_format_score = 0; for (auto surface_format : physicalIntrinsic.getSurfaceFormatsKHR(surface_)) { auto surface_format_score = 0; switch (surface_format.colorSpace) { case vk::ColorSpaceKHR::eSrgbNonlinear: surface_format_score += 1; break; case vk::ColorSpaceKHR::eExtendedSrgbNonlinearEXT: surface_format_score += 10; break; default:; } switch (surface_format.format) { case vk::Format::eR16G16B16A16Sfloat: surface_format_score += 12; break; case vk::Format::eR16G16B16Sfloat: surface_format_score += 11; break; case vk::Format::eA2B10G10R10UnormPack32: // This is a wire format for HDR, the GPU will not automatically convert linear shader-space to this wire format. surface_format_score -= 100; break; case vk::Format::eR8G8B8A8Srgb: surface_format_score += 4; break; case vk::Format::eB8G8R8A8Srgb: surface_format_score += 4; break; case vk::Format::eR8G8B8Srgb: surface_format_score += 3; break; case vk::Format::eB8G8R8Srgb: surface_format_score += 3; break; case vk::Format::eB8G8R8A8Unorm: surface_format_score += 2; break; case vk::Format::eR8G8B8A8Unorm: surface_format_score += 2; break; case vk::Format::eB8G8R8Unorm: surface_format_score += 1; break; case vk::Format::eR8G8B8Unorm: surface_format_score += 1; break; default:; } if (score) { tt_log_info( " - color-space={}, format={}, score={}", vk::to_string(surface_format.colorSpace), vk::to_string(surface_format.format), surface_format_score); } if (surface_format_score > best_surface_format_score) { best_surface_format_score = surface_format_score; best_surface_format = surface_format; } } if (score) { *score = best_surface_format_score; } return best_surface_format; } [[nodiscard]] vk::PresentModeKHR gfx_device_vulkan::get_present_mode(gfx_surface const &surface, int *score) const noexcept { ttlet &surface_ = narrow_cast<gfx_surface_vulkan const &>(surface).intrinsic; auto best_present_mode = vk::PresentModeKHR{}; auto best_present_mode_score = 0; for (ttlet &present_mode : physicalIntrinsic.getSurfacePresentModesKHR(surface_)) { int present_mode_score = 0; switch (present_mode) { case vk::PresentModeKHR::eImmediate: present_mode_score += 1; break; case vk::PresentModeKHR::eFifoRelaxed: present_mode_score += 2; break; case vk::PresentModeKHR::eFifo: present_mode_score += 3; break; case vk::PresentModeKHR::eMailbox: present_mode_score += 1; break; // mailbox does not wait for vsync. default: continue; } if (score) { tt_log_info(" - present-mode={} score={}", vk::to_string(present_mode), present_mode_score); } if (present_mode_score > best_present_mode_score) { best_present_mode_score = present_mode_score; best_present_mode = present_mode; } } if (score) { *score = best_present_mode_score; } return best_present_mode; } int gfx_device_vulkan::score(gfx_surface const &surface) const { tt_axiom(gfx_system_mutex.recurse_lock_count()); ttlet &surface_ = narrow_cast<gfx_surface_vulkan const &>(surface).intrinsic; auto total_score = 0; tt_log_info("Scoring device: {}", string()); if (!hasRequiredFeatures(physicalIntrinsic, narrow_cast<gfx_system_vulkan &>(system).requiredFeatures)) { tt_log_info(" - Does not have the required features."); return -1; } if (!meetsRequiredLimits(physicalIntrinsic, narrow_cast<gfx_system_vulkan &>(system).requiredLimits)) { tt_log_info(" - Does not meet the required limits."); return -1; } if (!hasRequiredExtensions(physicalIntrinsic, requiredExtensions)) { tt_log_info(" - Does not have the required extensions."); return -1; } bool device_has_graphics = false; bool device_has_present = false; bool device_has_compute = false; bool device_shares_graphics_and_present = false; for (ttlet &queue: _queues) { ttlet has_present = static_cast<bool>(physicalIntrinsic.getSurfaceSupportKHR(queue.family_queue_index, surface_)); ttlet has_graphics = static_cast<bool>(queue.flags & vk::QueueFlagBits::eGraphics); ttlet has_compute = static_cast<bool>(queue.flags & vk::QueueFlagBits::eCompute); device_has_graphics |= has_graphics; device_has_present |= has_present; device_has_compute |= has_compute; if (has_present and has_graphics) { device_shares_graphics_and_present = true; } } if (not device_has_graphics) { tt_log_info(" - Does not have a graphics queue."); return -1; } if (not device_has_present) { tt_log_info(" - Does not have a present queue."); return -1; } if (device_has_compute) { tt_log_info(" - Device has compute queue."); total_score += 1; } if (device_shares_graphics_and_present) { tt_log_info(" - Device shares graphics and present on same queue."); total_score += 10; } tt_log_info(" - Surface formats:"); int surface_format_score = 0; [[maybe_unused]] auto surface_format = get_surface_format(surface, &surface_format_score); if (surface_format_score <= 0) { tt_log_info(" - Does not have a suitable surface format."); return -1; } total_score += surface_format_score; tt_log_info(" - Present modes:"); int present_mode_score = 0; [[maybe_unused]] auto present_mode = get_present_mode(surface, &present_mode_score); if (present_mode_score <= 0) { tt_log_info(" - Does not have a suitable present mode."); return -1; } total_score += present_mode_score; // Give score based on the performance of the device. auto device_type_score = 0; ttlet properties = physicalIntrinsic.getProperties(); switch (properties.deviceType) { case vk::PhysicalDeviceType::eCpu: device_type_score = 1; break; case vk::PhysicalDeviceType::eOther: device_type_score = 1; break; case vk::PhysicalDeviceType::eVirtualGpu: device_type_score = 2; break; case vk::PhysicalDeviceType::eIntegratedGpu: device_type_score = 3; break; case vk::PhysicalDeviceType::eDiscreteGpu: device_type_score = 4; break; } tt_log_info(" - device-type={}, score={}", vk::to_string(properties.deviceType), device_type_score); total_score += device_type_score; tt_log_info(" - total score {}", total_score); return total_score; } std::vector<vk::DeviceQueueCreateInfo> gfx_device_vulkan::make_device_queue_create_infos() const noexcept { ttlet default_queue_priority = std::array{1.0f}; uint32_t queue_family_index = 0; auto r = std::vector<vk::DeviceQueueCreateInfo>{}; for (auto queue_family_properties : physicalIntrinsic.getQueueFamilyProperties()) { ttlet num_queues = 1; tt_axiom(std::size(default_queue_priority) >= num_queues); r.emplace_back(vk::DeviceQueueCreateFlags(), queue_family_index++, num_queues, default_queue_priority.data()); } return r; } void gfx_device_vulkan::initialize_queues(std::vector<vk::DeviceQueueCreateInfo> const &device_queue_create_infos) noexcept { ttlet queue_family_properties = physicalIntrinsic.getQueueFamilyProperties(); for (ttlet &device_queue_create_info : device_queue_create_infos) { ttlet queue_family_index = device_queue_create_info.queueFamilyIndex; ttlet &queue_family_property = queue_family_properties[queue_family_index]; ttlet queue_flags = queue_family_property.queueFlags; for (uint32_t queue_index = 0; queue_index != device_queue_create_info.queueCount; ++queue_index) { ttlet queue = intrinsic.getQueue(queue_family_index, queue_index); ttlet command_pool = intrinsic.createCommandPool( {vk::CommandPoolCreateFlagBits::eTransient | vk::CommandPoolCreateFlagBits::eResetCommandBuffer, queue_family_index}); _queues.emplace_back(queue_family_index, queue_index, queue_flags, std::move(queue), std::move(command_pool)); } } } void gfx_device_vulkan::initialize_device() { ttlet device_queue_create_infos = make_device_queue_create_infos(); intrinsic = physicalIntrinsic.createDevice( {vk::DeviceCreateFlags(), narrow_cast<uint32_t>(device_queue_create_infos.size()), device_queue_create_infos.data(), 0, nullptr, narrow_cast<uint32_t>(requiredExtensions.size()), requiredExtensions.data(), &(narrow_cast<gfx_system_vulkan &>(system).requiredFeatures)}); VmaAllocatorCreateInfo allocatorCreateInfo = {}; allocatorCreateInfo.physicalDevice = physicalIntrinsic; allocatorCreateInfo.device = intrinsic; allocatorCreateInfo.instance = narrow_cast<gfx_system_vulkan &>(system).intrinsic; vmaCreateAllocator(&allocatorCreateInfo, &allocator); VmaAllocationCreateInfo lazyAllocationInfo = {}; lazyAllocationInfo.usage = VMA_MEMORY_USAGE_GPU_LAZILY_ALLOCATED; uint32_t typeIndexOut = 0; supportsLazyTransientImages = vmaFindMemoryTypeIndex(allocator, 0, &lazyAllocationInfo, &typeIndexOut) != VK_ERROR_FEATURE_NOT_PRESENT; if (supportsLazyTransientImages) { lazyMemoryUsage = VMA_MEMORY_USAGE_GPU_LAZILY_ALLOCATED; transientImageUsageFlags = vk::ImageUsageFlagBits::eTransientAttachment; } initialize_queues(device_queue_create_infos); initialize_quad_index_buffer(); flatPipeline = std::make_unique<pipeline_flat::device_shared>(*this); boxPipeline = std::make_unique<pipeline_box::device_shared>(*this); imagePipeline = std::make_unique<pipeline_image::device_shared>(*this); SDFPipeline = std::make_unique<pipeline_SDF::device_shared>(*this); toneMapperPipeline = std::make_unique<pipeline_tone_mapper::device_shared>(*this); } void gfx_device_vulkan::initialize_quad_index_buffer() { tt_axiom(gfx_system_mutex.recurse_lock_count()); using vertex_index_type = uint16_t; constexpr ssize_t maximum_number_of_vertices = 1 << (sizeof(vertex_index_type) * CHAR_BIT); constexpr ssize_t maximum_number_of_quads = maximum_number_of_vertices / 4; constexpr ssize_t maximum_number_of_triangles = maximum_number_of_quads * 2; constexpr ssize_t maximum_number_of_indices = maximum_number_of_triangles * 3; // Create vertex index buffer { vk::BufferCreateInfo const bufferCreateInfo = { vk::BufferCreateFlags(), sizeof(vertex_index_type) * maximum_number_of_indices, vk::BufferUsageFlagBits::eIndexBuffer | vk::BufferUsageFlagBits::eTransferDst, vk::SharingMode::eExclusive}; VmaAllocationCreateInfo allocationCreateInfo = {}; allocationCreateInfo.usage = VMA_MEMORY_USAGE_GPU_ONLY; std::tie(quadIndexBuffer, quadIndexBufferAllocation) = createBuffer(bufferCreateInfo, allocationCreateInfo); } // Fill in the vertex index buffer, using a staging buffer, then copying. { // Create staging vertex index buffer. vk::BufferCreateInfo const bufferCreateInfo = { vk::BufferCreateFlags(), sizeof(vertex_index_type) * maximum_number_of_indices, vk::BufferUsageFlagBits::eIndexBuffer | vk::BufferUsageFlagBits::eTransferSrc, vk::SharingMode::eExclusive}; VmaAllocationCreateInfo allocationCreateInfo = {}; allocationCreateInfo.usage = VMA_MEMORY_USAGE_CPU_ONLY; ttlet[stagingvertexIndexBuffer, stagingvertexIndexBufferAllocation] = createBuffer(bufferCreateInfo, allocationCreateInfo); // Initialize indices. ttlet stagingvertexIndexBufferData = mapMemory<vertex_index_type>(stagingvertexIndexBufferAllocation); for (size_t i = 0; i < maximum_number_of_indices; i++) { ttlet vertexInRectangle = i % 6; ttlet rectangleNr = i / 6; ttlet rectangleBase = rectangleNr * 4; switch (vertexInRectangle) { case 0: stagingvertexIndexBufferData[i] = narrow_cast<vertex_index_type>(rectangleBase + 0); break; case 1: stagingvertexIndexBufferData[i] = narrow_cast<vertex_index_type>(rectangleBase + 1); break; case 2: stagingvertexIndexBufferData[i] = narrow_cast<vertex_index_type>(rectangleBase + 2); break; case 3: stagingvertexIndexBufferData[i] = narrow_cast<vertex_index_type>(rectangleBase + 2); break; case 4: stagingvertexIndexBufferData[i] = narrow_cast<vertex_index_type>(rectangleBase + 1); break; case 5: stagingvertexIndexBufferData[i] = narrow_cast<vertex_index_type>(rectangleBase + 3); break; default: tt_no_default(); } } flushAllocation(stagingvertexIndexBufferAllocation, 0, VK_WHOLE_SIZE); unmapMemory(stagingvertexIndexBufferAllocation); // Copy indices to vertex index buffer. auto &queue = get_graphics_queue(); auto commands = allocateCommandBuffers({queue.command_pool, vk::CommandBufferLevel::ePrimary, 1}).at(0); commands.begin({vk::CommandBufferUsageFlagBits::eOneTimeSubmit}); commands.copyBuffer( stagingvertexIndexBuffer, quadIndexBuffer, {{0, 0, sizeof(vertex_index_type) * maximum_number_of_indices}}); commands.end(); std::vector<vk::CommandBuffer> const commandBuffersToSubmit = {commands}; std::vector<vk::SubmitInfo> const submitInfo = { {0, nullptr, nullptr, narrow_cast<uint32_t>(commandBuffersToSubmit.size()), commandBuffersToSubmit.data(), 0, nullptr}}; queue.queue.submit(submitInfo, vk::Fence()); queue.queue.waitIdle(); freeCommandBuffers(queue.command_pool, {commands}); destroyBuffer(stagingvertexIndexBuffer, stagingvertexIndexBufferAllocation); } } void gfx_device_vulkan::destroy_quad_index_buffer() { tt_axiom(gfx_system_mutex.recurse_lock_count()); destroyBuffer(quadIndexBuffer, quadIndexBufferAllocation); } std::pair<vk::Buffer, VmaAllocation> gfx_device_vulkan::createBuffer( const vk::BufferCreateInfo &bufferCreateInfo, const VmaAllocationCreateInfo &allocationCreateInfo) const { tt_axiom(gfx_system_mutex.recurse_lock_count()); VkBuffer buffer; VmaAllocation allocation; ttlet bufferCreateInfo_ = static_cast<VkBufferCreateInfo>(bufferCreateInfo); ttlet result = static_cast<vk::Result>( vmaCreateBuffer(allocator, &bufferCreateInfo_, &allocationCreateInfo, &buffer, &allocation, nullptr)); std::pair<vk::Buffer, VmaAllocation> const value = {buffer, allocation}; return vk::createResultValue(result, value, "tt::gfx_device_vulkan::createBuffer"); } void gfx_device_vulkan::destroyBuffer(const vk::Buffer &buffer, const VmaAllocation &allocation) const { tt_axiom(gfx_system_mutex.recurse_lock_count()); vmaDestroyBuffer(allocator, buffer, allocation); } std::pair<vk::Image, VmaAllocation> gfx_device_vulkan::createImage( const vk::ImageCreateInfo &imageCreateInfo, const VmaAllocationCreateInfo &allocationCreateInfo) const { tt_axiom(gfx_system_mutex.recurse_lock_count()); VkImage image; VmaAllocation allocation; ttlet imageCreateInfo_ = static_cast<VkImageCreateInfo>(imageCreateInfo); ttlet result = static_cast<vk::Result>( vmaCreateImage(allocator, &imageCreateInfo_, &allocationCreateInfo, &image, &allocation, nullptr)); std::pair<vk::Image, VmaAllocation> const value = {image, allocation}; return vk::createResultValue(result, value, "tt::gfx_device_vulkan::createImage"); } void gfx_device_vulkan::destroyImage(const vk::Image &image, const VmaAllocation &allocation) const { tt_axiom(gfx_system_mutex.recurse_lock_count()); vmaDestroyImage(allocator, image, allocation); } void gfx_device_vulkan::unmapMemory(const VmaAllocation &allocation) const { tt_axiom(gfx_system_mutex.recurse_lock_count()); vmaUnmapMemory(allocator, allocation); } vk::CommandBuffer gfx_device_vulkan::beginSingleTimeCommands() const { tt_axiom(gfx_system_mutex.recurse_lock_count()); ttlet &queue = get_graphics_queue(); ttlet commandBuffers = intrinsic.allocateCommandBuffers({queue.command_pool, vk::CommandBufferLevel::ePrimary, 1}); ttlet commandBuffer = commandBuffers.at(0); commandBuffer.begin({vk::CommandBufferUsageFlagBits::eOneTimeSubmit}); return commandBuffer; } void gfx_device_vulkan::endSingleTimeCommands(vk::CommandBuffer commandBuffer) const { tt_axiom(gfx_system_mutex.recurse_lock_count()); commandBuffer.end(); std::vector<vk::CommandBuffer> const commandBuffers = {commandBuffer}; ttlet &queue = get_graphics_queue(); queue.queue.submit( {{ 0, nullptr, nullptr, // wait semaphores, wait stages narrow_cast<uint32_t>(commandBuffers.size()), commandBuffers.data(), 0, nullptr // signal semaphores }}, vk::Fence()); queue.queue.waitIdle(); intrinsic.freeCommandBuffers(queue.command_pool, commandBuffers); } static std::pair<vk::AccessFlags, vk::PipelineStageFlags> access_and_stage_from_layout(vk::ImageLayout layout) noexcept { switch (layout) { case vk::ImageLayout::eUndefined: return {vk::AccessFlags(), vk::PipelineStageFlagBits::eTopOfPipe}; // GPU Texture Maps case vk::ImageLayout::eTransferDstOptimal: return {vk::AccessFlagBits::eTransferWrite, vk::PipelineStageFlagBits::eTransfer}; case vk::ImageLayout::eShaderReadOnlyOptimal: return {vk::AccessFlagBits::eShaderRead, vk::PipelineStageFlagBits::eFragmentShader}; // CPU Staging texture maps case vk::ImageLayout::eGeneral: return {vk::AccessFlagBits::eHostWrite, vk::PipelineStageFlagBits::eHost}; case vk::ImageLayout::eTransferSrcOptimal: return {vk::AccessFlagBits::eTransferRead, vk::PipelineStageFlagBits::eTransfer}; // If we are explicitly transferring an image for ePresentSrcKHR, then we are doing this // because we want to reuse the swapchain images in subsequent rendering. Make sure it // is ready for the fragment shader. case vk::ImageLayout::ePresentSrcKHR: return { vk::AccessFlagBits::eColorAttachmentRead | vk::AccessFlagBits::eColorAttachmentWrite, vk::PipelineStageFlagBits::eColorAttachmentOutput}; default: tt_no_default(); } } void gfx_device_vulkan::transition_layout( vk::CommandBuffer command_buffer, vk::Image image, vk::Format format, vk::ImageLayout srcLayout, vk::ImageLayout dstLayout) { tt_axiom(gfx_system_mutex.recurse_lock_count()); ttlet[srcAccessMask, srcStage] = access_and_stage_from_layout(srcLayout); ttlet[dstAccessMask, dstStage] = access_and_stage_from_layout(dstLayout); std::vector<vk::ImageMemoryBarrier> barriers = { {srcAccessMask, dstAccessMask, srcLayout, dstLayout, VK_QUEUE_FAMILY_IGNORED, VK_QUEUE_FAMILY_IGNORED, image, { vk::ImageAspectFlagBits::eColor, 0, // baseMipLevel 1, // levelCount 0, // baseArrayLayer 1 // layerCount }}}; command_buffer.pipelineBarrier( srcStage, dstStage, vk::DependencyFlags(), 0, nullptr, 0, nullptr, narrow_cast<uint32_t>(barriers.size()), barriers.data()); } void gfx_device_vulkan::transition_layout( vk::Image image, vk::Format format, vk::ImageLayout src_layout, vk::ImageLayout dst_layout) const { tt_axiom(gfx_system_mutex.recurse_lock_count()); ttlet command_buffer = beginSingleTimeCommands(); transition_layout(command_buffer, image, format, src_layout, dst_layout); endSingleTimeCommands(command_buffer); } void gfx_device_vulkan::copyImage( vk::Image srcImage, vk::ImageLayout srcLayout, vk::Image dstImage, vk::ImageLayout dstLayout, vk::ArrayProxy<vk::ImageCopy const> regions) const { tt_axiom(gfx_system_mutex.recurse_lock_count()); ttlet commandBuffer = beginSingleTimeCommands(); commandBuffer.copyImage(srcImage, srcLayout, dstImage, dstLayout, regions); endSingleTimeCommands(commandBuffer); } void gfx_device_vulkan::clearColorImage( vk::Image image, vk::ImageLayout layout, vk::ClearColorValue const &color, vk::ArrayProxy<const vk::ImageSubresourceRange> ranges) const { tt_axiom(gfx_system_mutex.recurse_lock_count()); ttlet commandBuffer = beginSingleTimeCommands(); commandBuffer.clearColorImage(image, layout, color, ranges); endSingleTimeCommands(commandBuffer); } vk::ShaderModule gfx_device_vulkan::loadShader(uint32_t const *data, size_t size) const { tt_axiom(gfx_system_mutex.recurse_lock_count()); tt_log_info("Loading shader"); // Check uint32_t alignment of pointer. tt_axiom((reinterpret_cast<std::uintptr_t>(data) & 3) == 0); return intrinsic.createShaderModule({vk::ShaderModuleCreateFlags(), size, data}); } vk::ShaderModule gfx_device_vulkan::loadShader(std::span<std::byte const> shaderObjectBytes) const { // no lock, only local variable. // Make sure the address is aligned to uint32_t; ttlet address = reinterpret_cast<uintptr_t>(shaderObjectBytes.data()); tt_assert((address & 2) == 0); ttlet shaderObjectBytes32 = reinterpret_cast<uint32_t const *>(shaderObjectBytes.data()); return loadShader(shaderObjectBytes32, shaderObjectBytes.size()); } vk::ShaderModule gfx_device_vulkan::loadShader(URL const &shaderObjectLocation) const { // no lock, only local variable. return loadShader(*shaderObjectLocation.loadView()); } } // namespace tt
42.646572
130
0.716483
[ "vector" ]
79e3d853716dc1db804950164522b8ca3442e0e3
19,086
cc
C++
webkit/tools/test_shell/event_sending_controller.cc
zachlatta/chromium
c4625eefca763df86471d798ee5a4a054b4716ae
[ "BSD-3-Clause" ]
1
2021-09-24T22:49:10.000Z
2021-09-24T22:49:10.000Z
webkit/tools/test_shell/event_sending_controller.cc
changbai1980/chromium
c4625eefca763df86471d798ee5a4a054b4716ae
[ "BSD-3-Clause" ]
null
null
null
webkit/tools/test_shell/event_sending_controller.cc
changbai1980/chromium
c4625eefca763df86471d798ee5a4a054b4716ae
[ "BSD-3-Clause" ]
null
null
null
// Copyright (c) 2006-2008 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 file contains the definition for EventSendingController. // // Some notes about drag and drop handling: // Windows drag and drop goes through a system call to DoDragDrop. At that // point, program control is given to Windows which then periodically makes // callbacks into the webview. This won't work for layout tests, so instead, // we queue up all the mouse move and mouse up events. When the test tries to // start a drag (by calling EvenSendingController::DoDragDrop), we take the // events in the queue and replay them. // The behavior of queuing events and replaying them can be disabled by a // layout test by setting eventSender.dragMode to false. #include "webkit/tools/test_shell/event_sending_controller.h" #include <queue> // TODO(darin): This is very wrong. We should not be including WebCore headers // directly like this!! #include "config.h" #include "KeyboardCodes.h" #include "base/compiler_specific.h" #include "base/logging.h" #include "base/message_loop.h" #include "base/string_util.h" #include "base/time.h" #include "webkit/api/public/WebDragData.h" #include "webkit/api/public/WebPoint.h" #include "webkit/glue/webview.h" #include "webkit/tools/test_shell/test_shell.h" #if defined(OS_WIN) #include "webkit/api/public/win/WebInputEventFactory.h" using WebKit::WebInputEventFactory; #endif // TODO(mpcomplete): layout before each event? // TODO(mpcomplete): do we need modifiers for mouse events? using base::Time; using base::TimeTicks; using WebKit::WebDragData; using WebKit::WebInputEvent; using WebKit::WebKeyboardEvent; using WebKit::WebMouseEvent; using WebKit::WebPoint; TestShell* EventSendingController::shell_ = NULL; gfx::Point EventSendingController::last_mouse_pos_; WebMouseEvent::Button EventSendingController::pressed_button_ = WebMouseEvent::ButtonNone; int EventSendingController::last_button_number_ = -1; namespace { static WebDragData current_drag_data; static bool replaying_saved_events = false; static std::queue<WebMouseEvent> mouse_event_queue; // Time and place of the last mouse up event. static double last_click_time_sec = 0; static gfx::Point last_click_pos; static int click_count = 0; // maximum distance (in space and time) for a mouse click // to register as a double or triple click static const double kMultiClickTimeSec = 1; static const int kMultiClickRadiusPixels = 5; inline bool outside_multiclick_radius(const gfx::Point &a, const gfx::Point &b) { return ((a.x() - b.x()) * (a.x() - b.x()) + (a.y() - b.y()) * (a.y() - b.y())) > kMultiClickRadiusPixels * kMultiClickRadiusPixels; } // Used to offset the time the event hander things an event happened. This is // done so tests can run without a delay, but bypass checks that are time // dependent (e.g., dragging has a timeout vs selection). static uint32 time_offset_ms = 0; double GetCurrentEventTimeSec() { return (TimeTicks::Now().ToInternalValue() / Time::kMicrosecondsPerMillisecond + time_offset_ms) / 1000.0; } void AdvanceEventTime(int32 delta_ms) { time_offset_ms += delta_ms; } void InitMouseEvent(WebInputEvent::Type t, WebMouseEvent::Button b, const gfx::Point& pos, WebMouseEvent* e) { e->type = t; e->button = b; e->modifiers = 0; e->x = pos.x(); e->y = pos.y(); e->globalX = pos.x(); e->globalY = pos.y(); e->timeStampSeconds = GetCurrentEventTimeSec(); e->clickCount = click_count; } void ApplyKeyModifier(const std::wstring& arg, WebKeyboardEvent* event) { const wchar_t* arg_string = arg.c_str(); if (!wcscmp(arg_string, L"ctrlKey")) { event->modifiers |= WebInputEvent::ControlKey; } else if (!wcscmp(arg_string, L"shiftKey")) { event->modifiers |= WebInputEvent::ShiftKey; } else if (!wcscmp(arg_string, L"altKey")) { event->modifiers |= WebInputEvent::AltKey; #if defined(OS_WIN) event->isSystemKey = true; #endif } else if (!wcscmp(arg_string, L"metaKey")) { event->modifiers |= WebInputEvent::MetaKey; } } void ApplyKeyModifiers(const CppVariant* arg, WebKeyboardEvent* event) { if (arg->isObject()) { std::vector<std::wstring> args = arg->ToStringVector(); for (std::vector<std::wstring>::const_iterator i = args.begin(); i != args.end(); ++i) { ApplyKeyModifier(*i, event); } } else if (arg->isString()) { ApplyKeyModifier(UTF8ToWide(arg->ToString()), event); } } } // anonymous namespace EventSendingController::EventSendingController(TestShell* shell) : ALLOW_THIS_IN_INITIALIZER_LIST(method_factory_(this)) { // Set static shell_ variable since we can't do it in an initializer list. // We also need to be careful not to assign shell_ to new windows which are // temporary. if (NULL == shell_) shell_ = shell; // Initialize the map that associates methods of this class with the names // they will use when called by JavaScript. The actual binding of those // names to their methods will be done by calling BindToJavaScript() (defined // by CppBoundClass, the parent to EventSendingController). BindMethod("mouseDown", &EventSendingController::mouseDown); BindMethod("mouseUp", &EventSendingController::mouseUp); BindMethod("contextClick", &EventSendingController::contextClick); BindMethod("mouseMoveTo", &EventSendingController::mouseMoveTo); BindMethod("leapForward", &EventSendingController::leapForward); BindMethod("keyDown", &EventSendingController::keyDown); BindMethod("dispatchMessage", &EventSendingController::dispatchMessage); BindMethod("enableDOMUIEventLogging", &EventSendingController::enableDOMUIEventLogging); BindMethod("fireKeyboardEventsToElement", &EventSendingController::fireKeyboardEventsToElement); BindMethod("clearKillRing", &EventSendingController::clearKillRing); BindMethod("textZoomIn", &EventSendingController::textZoomIn); BindMethod("textZoomOut", &EventSendingController::textZoomOut); BindMethod("zoomPageIn", &EventSendingController::zoomPageIn); BindMethod("zoomPageOut", &EventSendingController::zoomPageOut); BindMethod("scheduleAsynchronousClick", &EventSendingController::scheduleAsynchronousClick); // When set to true (the default value), we batch mouse move and mouse up // events so we can simulate drag & drop. BindProperty("dragMode", &dragMode); #if defined(OS_WIN) BindProperty("WM_KEYDOWN", &wmKeyDown); BindProperty("WM_KEYUP", &wmKeyUp); BindProperty("WM_CHAR", &wmChar); BindProperty("WM_DEADCHAR", &wmDeadChar); BindProperty("WM_SYSKEYDOWN", &wmSysKeyDown); BindProperty("WM_SYSKEYUP", &wmSysKeyUp); BindProperty("WM_SYSCHAR", &wmSysChar); BindProperty("WM_SYSDEADCHAR", &wmSysDeadChar); #endif } void EventSendingController::Reset() { // The test should have finished a drag and the mouse button state. DCHECK(current_drag_data.isNull()); current_drag_data.reset(); pressed_button_ = WebMouseEvent::ButtonNone; dragMode.Set(true); #if defined(OS_WIN) wmKeyDown.Set(WM_KEYDOWN); wmKeyUp.Set(WM_KEYUP); wmChar.Set(WM_CHAR); wmDeadChar.Set(WM_DEADCHAR); wmSysKeyDown.Set(WM_SYSKEYDOWN); wmSysKeyUp.Set(WM_SYSKEYUP); wmSysChar.Set(WM_SYSCHAR); wmSysDeadChar.Set(WM_SYSDEADCHAR); #endif last_click_time_sec = 0; click_count = 0; last_button_number_ = -1; } // static WebView* EventSendingController::webview() { return shell_->webView(); } // static void EventSendingController::DoDragDrop(const WebDragData& drag_data) { current_drag_data = drag_data; webview()->DragTargetDragEnter(drag_data, 0, WebPoint(), WebPoint()); // Finish processing events. ReplaySavedEvents(); } WebMouseEvent::Button EventSendingController::GetButtonTypeFromButtonNumber( int button_code) { if (button_code == 0) return WebMouseEvent::ButtonLeft; else if (button_code == 2) return WebMouseEvent::ButtonRight; return WebMouseEvent::ButtonMiddle; } // static int EventSendingController::GetButtonNumberFromSingleArg( const CppArgumentList& args) { int button_code = 0; if (args.size() > 0 && args[0].isNumber()) { button_code = args[0].ToInt32(); } return button_code; } // // Implemented javascript methods. // void EventSendingController::mouseDown( const CppArgumentList& args, CppVariant* result) { if (result) // Could be NULL if invoked asynchronously. result->SetNull(); webview()->Layout(); int button_number = GetButtonNumberFromSingleArg(args); DCHECK(button_number != -1); WebMouseEvent::Button button_type = GetButtonTypeFromButtonNumber( button_number); if ((GetCurrentEventTimeSec() - last_click_time_sec < kMultiClickTimeSec) && (!outside_multiclick_radius(last_mouse_pos_, last_click_pos)) && (button_number == last_button_number_)) { ++click_count; } else { click_count = 1; } last_button_number_ = button_number; WebMouseEvent event; pressed_button_ = button_type; InitMouseEvent(WebInputEvent::MouseDown, button_type, last_mouse_pos_, &event); webview()->HandleInputEvent(&event); } void EventSendingController::mouseUp( const CppArgumentList& args, CppVariant* result) { if (result) // Could be NULL if invoked asynchronously. result->SetNull(); webview()->Layout(); int button_number = GetButtonNumberFromSingleArg(args); DCHECK(button_number != -1); WebMouseEvent::Button button_type = GetButtonTypeFromButtonNumber( button_number); last_button_number_ = button_number; WebMouseEvent event; InitMouseEvent(WebInputEvent::MouseUp, button_type, last_mouse_pos_, &event); if (drag_mode() && !replaying_saved_events) { mouse_event_queue.push(event); ReplaySavedEvents(); } else { DoMouseUp(event); } last_click_time_sec = event.timeStampSeconds; last_click_pos = gfx::Point(event.x, event.y); } /* static */ void EventSendingController::DoMouseUp(const WebMouseEvent& e) { webview()->HandleInputEvent(&e); pressed_button_ = WebMouseEvent::ButtonNone; // If we're in a drag operation, complete it. if (!current_drag_data.isNull()) { WebPoint client_point(e.x, e.y); WebPoint screen_point(e.globalX, e.globalY); bool valid = webview()->DragTargetDragOver(client_point, screen_point); if (valid) { webview()->DragSourceEndedAt(client_point, screen_point); webview()->DragTargetDrop(client_point, screen_point); } else { webview()->DragSourceEndedAt(client_point, screen_point); webview()->DragTargetDragLeave(); } current_drag_data.reset(); } } void EventSendingController::mouseMoveTo( const CppArgumentList& args, CppVariant* result) { result->SetNull(); if (args.size() >= 2 && args[0].isNumber() && args[1].isNumber()) { webview()->Layout(); WebMouseEvent event; last_mouse_pos_.SetPoint(args[0].ToInt32(), args[1].ToInt32()); InitMouseEvent(WebInputEvent::MouseMove, pressed_button_, last_mouse_pos_, &event); if (drag_mode() && pressed_button_ != WebMouseEvent::ButtonNone && !replaying_saved_events) { mouse_event_queue.push(event); } else { DoMouseMove(event); } } } // static void EventSendingController::DoMouseMove(const WebMouseEvent& e) { webview()->HandleInputEvent(&e); if (pressed_button_ != WebMouseEvent::ButtonNone && !current_drag_data.isNull()) { WebPoint client_point(e.x, e.y); WebPoint screen_point(e.globalX, e.globalY); webview()->DragSourceMovedTo(client_point, screen_point); webview()->DragTargetDragOver(client_point, screen_point); } } void EventSendingController::keyDown( const CppArgumentList& args, CppVariant* result) { result->SetNull(); bool generate_char = false; if (args.size() >= 1 && args[0].isString()) { // TODO(mpcomplete): I'm not exactly sure how we should convert the string // to a key event. This seems to work in the cases I tested. // TODO(mpcomplete): Should we also generate a KEY_UP? std::wstring code_str = UTF8ToWide(args[0].ToString()); // Convert \n -> VK_RETURN. Some layout tests use \n to mean "Enter", when // Windows uses \r for "Enter". int code; bool needs_shift_key_modifier = false; if (L"\n" == code_str) { generate_char = true; code = WebCore::VKEY_RETURN; } else if (L"rightArrow" == code_str) { code = WebCore::VKEY_RIGHT; } else if (L"downArrow" == code_str) { code = WebCore::VKEY_DOWN; } else if (L"leftArrow" == code_str) { code = WebCore::VKEY_LEFT; } else if (L"upArrow" == code_str) { code = WebCore::VKEY_UP; } else if (L"delete" == code_str) { code = WebCore::VKEY_BACK; } else if (L"pageUp" == code_str) { code = WebCore::VKEY_PRIOR; } else if (L"pageDown" == code_str) { code = WebCore::VKEY_NEXT; } else { DCHECK(code_str.length() == 1); code = code_str[0]; needs_shift_key_modifier = NeedsShiftModifier(code); generate_char = true; } // For one generated keyboard event, we need to generate a keyDown/keyUp // pair; refer to EventSender.cpp in WebKit/WebKitTools/DumpRenderTree/win. // On Windows, we might also need to generate a char event to mimic the // Windows event flow; on other platforms we create a merged event and test // the event flow that that platform provides. WebKeyboardEvent event_down, event_up; #if defined(OS_WIN) event_down.type = WebInputEvent::RawKeyDown; #else event_down.type = WebInputEvent::KeyDown; #endif event_down.modifiers = 0; event_down.windowsKeyCode = code; if (generate_char) { event_down.text[0] = code; event_down.unmodifiedText[0] = code; } event_down.setKeyIdentifierFromWindowsKeyCode(); if (args.size() >= 2 && (args[1].isObject() || args[1].isString())) ApplyKeyModifiers(&(args[1]), &event_down); if (needs_shift_key_modifier) event_down.modifiers |= WebInputEvent::ShiftKey; event_up = event_down; event_up.type = WebInputEvent::KeyUp; // EventSendingController.m forces a layout here, with at least one // test (fast\forms\focus-control-to-page.html) relying on this. webview()->Layout(); webview()->HandleInputEvent(&event_down); #if defined(OS_WIN) if (generate_char) { WebKeyboardEvent event_char = event_down; event_char.type = WebInputEvent::Char; event_char.keyIdentifier[0] = '\0'; webview()->HandleInputEvent(&event_char); } #endif webview()->HandleInputEvent(&event_up); } } void EventSendingController::dispatchMessage( const CppArgumentList& args, CppVariant* result) { result->SetNull(); #if defined(OS_WIN) if (args.size() == 3) { // Grab the message id to see if we need to dispatch it. int msg = args[0].ToInt32(); // WebKit's version of this function stuffs a MSG struct and uses // TranslateMessage and DispatchMessage. We use a WebKeyboardEvent, which // doesn't need to receive the DeadChar and SysDeadChar messages. if (msg == WM_DEADCHAR || msg == WM_SYSDEADCHAR) return; webview()->Layout(); unsigned long lparam = static_cast<unsigned long>(args[2].ToDouble()); const WebKeyboardEvent& key_event = WebInputEventFactory::keyboardEvent( NULL, msg, args[1].ToInt32(), lparam); webview()->HandleInputEvent(&key_event); } else { NOTREACHED() << L"Wrong number of arguments"; } #endif } bool EventSendingController::NeedsShiftModifier(int key_code) { // If code is an uppercase letter, assign a SHIFT key to // event_down.modifier, this logic comes from // WebKit/WebKitTools/DumpRenderTree/Win/EventSender.cpp if ((key_code & 0xFF) >= 'A' && (key_code & 0xFF) <= 'Z') return true; return false; } void EventSendingController::leapForward( const CppArgumentList& args, CppVariant* result) { result->SetNull(); // TODO(mpcomplete): DumpRenderTree defers this under certain conditions. if (args.size() >=1 && args[0].isNumber()) { AdvanceEventTime(args[0].ToInt32()); } } // Apple's port of WebKit zooms by a factor of 1.2 (see // WebKit/WebView/WebView.mm) void EventSendingController::textZoomIn( const CppArgumentList& args, CppVariant* result) { webview()->ZoomIn(true); result->SetNull(); } void EventSendingController::textZoomOut( const CppArgumentList& args, CppVariant* result) { webview()->ZoomOut(true); result->SetNull(); } void EventSendingController::zoomPageIn( const CppArgumentList& args, CppVariant* result) { webview()->ZoomIn(false); result->SetNull(); } void EventSendingController::zoomPageOut( const CppArgumentList& args, CppVariant* result) { webview()->ZoomOut(false); result->SetNull(); } void EventSendingController::ReplaySavedEvents() { replaying_saved_events = true; while (!mouse_event_queue.empty()) { WebMouseEvent event = mouse_event_queue.front(); mouse_event_queue.pop(); switch (event.type) { case WebInputEvent::MouseUp: DoMouseUp(event); break; case WebInputEvent::MouseMove: DoMouseMove(event); break; default: NOTREACHED(); } } replaying_saved_events = false; } void EventSendingController::contextClick( const CppArgumentList& args, CppVariant* result) { result->SetNull(); webview()->Layout(); if (GetCurrentEventTimeSec() - last_click_time_sec >= 1) { click_count = 1; } else { ++click_count; } // Generate right mouse down and up. WebMouseEvent event; pressed_button_ = WebMouseEvent::ButtonRight; InitMouseEvent(WebInputEvent::MouseDown, WebMouseEvent::ButtonRight, last_mouse_pos_, &event); webview()->HandleInputEvent(&event); InitMouseEvent(WebInputEvent::MouseUp, WebMouseEvent::ButtonRight, last_mouse_pos_, &event); webview()->HandleInputEvent(&event); pressed_button_ = WebMouseEvent::ButtonNone; } void EventSendingController::scheduleAsynchronousClick( const CppArgumentList& args, CppVariant* result) { result->SetNull(); MessageLoop::current()->PostTask(FROM_HERE, method_factory_.NewRunnableMethod(&EventSendingController::mouseDown, args, static_cast<CppVariant*>(NULL))); MessageLoop::current()->PostTask(FROM_HERE, method_factory_.NewRunnableMethod(&EventSendingController::mouseUp, args, static_cast<CppVariant*>(NULL))); } // // Unimplemented stubs // void EventSendingController::enableDOMUIEventLogging( const CppArgumentList& args, CppVariant* result) { result->SetNull(); } void EventSendingController::fireKeyboardEventsToElement( const CppArgumentList& args, CppVariant* result) { result->SetNull(); } void EventSendingController::clearKillRing( const CppArgumentList& args, CppVariant* result) { result->SetNull(); }
31.863105
82
0.708163
[ "vector" ]
79e531b6664ead49fd332f831eff11f1db84c09a
16,913
cc
C++
demo/demo_pbr.cc
raptoravis/sigrlinn
37fd2f8c73e38e9c266301517f4292e0d6e536ef
[ "MIT" ]
140
2015-01-13T22:40:16.000Z
2022-01-15T00:53:47.000Z
demo/demo_pbr.cc
raptoravis/sigrlinn
37fd2f8c73e38e9c266301517f4292e0d6e536ef
[ "MIT" ]
17
2015-01-23T15:15:14.000Z
2019-03-16T20:30:52.000Z
demo/demo_pbr.cc
raptoravis/sigrlinn
37fd2f8c73e38e9c266301517f4292e0d6e536ef
[ "MIT" ]
22
2015-01-19T13:00:55.000Z
2021-03-27T09:04:34.000Z
/// The MIT License (MIT) /// /// Copyright (c) 2015 Kirill Bazhenov /// Copyright (c) 2015 BitBox, Ltd. /// /// Permission is hereby granted, free of charge, to any person obtaining a copy /// of this software and associated documentation files (the "Software"), to deal /// in the Software without restriction, including without limitation the rights /// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell /// copies of the Software, and to permit persons to whom the Software is /// furnished to do so, subject to the following conditions: /// /// The above copyright notice and this permission notice shall be included in /// all copies or substantial portions of the Software. /// /// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR /// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, /// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE /// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER /// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, /// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN /// THE SOFTWARE. #include "common/app.hh" #include "common/meshloader.hh" #include <memory> #include <glm/glm.hpp> #include <glm/ext.hpp> class Mesh { private: util::BufferHandle vertexBuffer; util::BufferHandle indexBuffer; uint32_t numIndices; public: inline Mesh() {} inline Mesh(const std::string& path) { load(path); } inline ~Mesh() {} void load(const std::string& path) { MeshData data; data.read(path); vertexBuffer = sgfx::createBuffer( sgfx::BufferFlags::VertexBuffer, data.getVertices().data(), data.getVertices().size() * sizeof(MeshData::Vertex), sizeof(MeshData::Vertex) ); indexBuffer = sgfx::createBuffer( sgfx::BufferFlags::IndexBuffer, data.getIndices().data(), data.getIndices().size() * sizeof(MeshData::Index), sizeof(MeshData::Index) ); numIndices = static_cast<uint32_t>(data.getIndices().size()); } inline sgfx::BufferHandle getVertexBuffer() const { return vertexBuffer; } inline sgfx::BufferHandle getIndexBuffer() const { return indexBuffer; } inline uint32_t getNumIndices() const { return numIndices; } }; struct Material { util::TextureHandle albedo; util::TextureHandle gloss; util::TextureHandle normal; util::TextureHandle spec; inline Material() {} inline ~Material() {} }; class DeferredScene { private: struct ConstantBuffer { float mvp[16]; }; Mesh akMesh; // our AK mesh Material akMaterial; // mesh material util::SamplerStateHandle samplerState; util::VertexFormatHandle vertexFormat; // constant buffer util::ConstantBufferHandle constantBuffer; // gbuffer pass data util::VertexShaderHandle vertexShaderGB; util::PixelShaderHandle pixelShaderGB; util::SurfaceShaderHandle surfaceShaderGB; util::PipelineStateHandle pipelineStateGB; util::DrawQueueHandle drawQueueGB; // gbuffer util::TextureHandle rtColorBuffer0GB; util::TextureHandle rtColorBuffer1GB; util::TextureHandle rtDepthBufferGB; util::RenderTargetHandle renderTargetGB; // deferred resolve data util::VertexShaderHandle vertexShaderDS; util::PixelShaderHandle pixelShaderDS; util::SurfaceShaderHandle surfaceShaderDS; util::PipelineStateHandle pipelineStateDS; util::DrawQueueHandle drawQueueDS; util::TextureHandle rtBackBufferDS; util::RenderTargetHandle renderTargetDS; public: inline DeferredScene() {} inline ~DeferredScene() { } void load(uint32_t width, uint32_t height, Application* app) { akMesh.load("data/ak/AKS74U1.mesh"); // create sampler state sgfx::SamplerStateDescriptor samplerDesc; samplerDesc.filter = sgfx::TextureFilter::MinMagMip_Linear; samplerDesc.addressU = sgfx::AddressMode::Clamp; samplerDesc.addressV = sgfx::AddressMode::Clamp; samplerDesc.addressW = sgfx::AddressMode::Clamp; samplerDesc.lodBias = 0.0F; samplerDesc.maxAnisotropy = 1; samplerDesc.comparisonFunc = sgfx::ComparisonFunc::Never; samplerDesc.borderColor = 0xFFFFFFFF; samplerDesc.minLod = -3.402823466e+38F; samplerDesc.maxLod = 3.402823466e+38F; samplerState = sgfx::createSamplerState(samplerDesc); // create vertex format const size_t stride1 = 0; // Position const size_t stride2 = stride1 + 3 * sizeof(float); // uv0 const size_t stride3 = stride2 + 2 * sizeof(float); // uv1 const size_t stride4 = stride3 + 2 * sizeof(float); // normal const size_t stride5 = stride4 + 3 * sizeof(float); // boneIDs const size_t stride6 = stride5 + 4 * sizeof(uint8_t); // boneWeights const size_t stride7 = stride6 + 4 * sizeof(float); // color sgfx::VertexElementDescriptor vfElements[] = { { "POSITION", 0, sgfx::DataFormat::RGB32F, 0, stride1 }, { "TEXCOORDA", 0, sgfx::DataFormat::RG32F, 0, stride2 }, { "TEXCOORDB", 0, sgfx::DataFormat::RG32F, 0, stride3 }, { "NORMAL", 0, sgfx::DataFormat::RGB32F, 0, stride4 }, { "BONEIDS", 0, sgfx::DataFormat::R32U, 0, stride5 }, { "BONEWEIGHTS", 0, sgfx::DataFormat::RGBA32F, 0, stride6 }, { "VCOLOR", 0, sgfx::DataFormat::R32U, 0, stride7 } }; size_t vfSize = sizeof(vfElements) / sizeof(sgfx::VertexElementDescriptor); vertexFormat = app->loadVF(vfElements, vfSize, "shaders/pbr_gbuffer.hlsl"); // load shaders vertexShaderGB = app->loadVS("shaders/pbr_gbuffer.hlsl"); pixelShaderGB = app->loadPS("shaders/pbr_gbuffer.hlsl"); vertexShaderDS = app->loadVS("shaders/pbr_resolve.hlsl"); pixelShaderDS = app->loadPS("shaders/pbr_resolve.hlsl"); if (vertexShaderGB.valid() && pixelShaderGB.valid()) { surfaceShaderGB = sgfx::linkSurfaceShader( vertexShaderGB, sgfx::HullShaderHandle::invalidHandle(), sgfx::DomainShaderHandle::invalidHandle(), sgfx::GeometryShaderHandle::invalidHandle(), pixelShaderGB ); } if (vertexShaderDS.valid() && pixelShaderDS.valid()) { surfaceShaderDS = sgfx::linkSurfaceShader( vertexShaderDS, sgfx::HullShaderHandle::invalidHandle(), sgfx::DomainShaderHandle::invalidHandle(), sgfx::GeometryShaderHandle::invalidHandle(), pixelShaderDS ); } // create draw queues if (surfaceShaderGB.valid()) { // gbuffer draw queue sgfx::PipelineStateDescriptor desc; desc.rasterizerState.fillMode = sgfx::FillMode::Solid; desc.rasterizerState.cullMode = sgfx::CullMode::Back; desc.rasterizerState.counterDirection = sgfx::CounterDirection::CW; desc.blendState.blendDesc.blendEnabled = false; desc.blendState.blendDesc.writeMask = sgfx::ColorWriteMask::All; desc.blendState.blendDesc.srcBlend = sgfx::BlendFactor::One; desc.blendState.blendDesc.dstBlend = sgfx::BlendFactor::Zero; desc.blendState.blendDesc.blendOp = sgfx::BlendOp::Add; desc.blendState.blendDesc.srcBlendAlpha = sgfx::BlendFactor::One; desc.blendState.blendDesc.dstBlendAlpha = sgfx::BlendFactor::Zero; desc.blendState.blendDesc.blendOpAlpha = sgfx::BlendOp::Add; desc.depthStencilState.depthEnabled = true; desc.depthStencilState.writeMask = sgfx::DepthWriteMask::All; desc.depthStencilState.depthFunc = sgfx::DepthFunc::Less; desc.depthStencilState.stencilEnabled = false; desc.depthStencilState.stencilRef = 0; desc.depthStencilState.stencilReadMask = 0; desc.depthStencilState.stencilWriteMask = 0; desc.depthStencilState.frontFaceStencilDesc.stencilFunc = sgfx::StencilFunc::Always; desc.depthStencilState.frontFaceStencilDesc.failOp = sgfx::StencilOp::Keep; desc.depthStencilState.frontFaceStencilDesc.depthFailOp = sgfx::StencilOp::Keep; desc.depthStencilState.frontFaceStencilDesc.passOp = sgfx::StencilOp::Keep; desc.depthStencilState.backFaceStencilDesc.stencilFunc = sgfx::StencilFunc::Always; desc.depthStencilState.backFaceStencilDesc.failOp = sgfx::StencilOp::Keep; desc.depthStencilState.backFaceStencilDesc.depthFailOp = sgfx::StencilOp::Keep; desc.depthStencilState.backFaceStencilDesc.passOp = sgfx::StencilOp::Keep; desc.shader = surfaceShaderGB; desc.vertexFormat = vertexFormat; pipelineStateGB = sgfx::createPipelineState(desc); if (pipelineStateGB.valid()) { drawQueueGB = sgfx::createDrawQueue(pipelineStateGB); } else { OutputDebugString("Failed to create pipeline state!"); } } if (surfaceShaderDS.valid()) { // resolve draw queue sgfx::PipelineStateDescriptor desc; desc.rasterizerState.fillMode = sgfx::FillMode::Solid; desc.rasterizerState.cullMode = sgfx::CullMode::Back; desc.rasterizerState.counterDirection = sgfx::CounterDirection::CW; desc.blendState.blendDesc.blendEnabled = false; desc.blendState.blendDesc.writeMask = sgfx::ColorWriteMask::All; desc.blendState.blendDesc.srcBlend = sgfx::BlendFactor::One; desc.blendState.blendDesc.dstBlend = sgfx::BlendFactor::Zero; desc.blendState.blendDesc.blendOp = sgfx::BlendOp::Add; desc.blendState.blendDesc.srcBlendAlpha = sgfx::BlendFactor::One; desc.blendState.blendDesc.dstBlendAlpha = sgfx::BlendFactor::Zero; desc.blendState.blendDesc.blendOpAlpha = sgfx::BlendOp::Add; desc.depthStencilState.depthEnabled = true; desc.depthStencilState.writeMask = sgfx::DepthWriteMask::All; desc.depthStencilState.depthFunc = sgfx::DepthFunc::Less; desc.depthStencilState.stencilEnabled = false; desc.depthStencilState.stencilRef = 0; desc.depthStencilState.stencilReadMask = 0; desc.depthStencilState.stencilWriteMask = 0; desc.depthStencilState.frontFaceStencilDesc.stencilFunc = sgfx::StencilFunc::Always; desc.depthStencilState.frontFaceStencilDesc.failOp = sgfx::StencilOp::Keep; desc.depthStencilState.frontFaceStencilDesc.depthFailOp = sgfx::StencilOp::Keep; desc.depthStencilState.frontFaceStencilDesc.passOp = sgfx::StencilOp::Keep; desc.depthStencilState.backFaceStencilDesc.stencilFunc = sgfx::StencilFunc::Always; desc.depthStencilState.backFaceStencilDesc.failOp = sgfx::StencilOp::Keep; desc.depthStencilState.backFaceStencilDesc.depthFailOp = sgfx::StencilOp::Keep; desc.depthStencilState.backFaceStencilDesc.passOp = sgfx::StencilOp::Keep; desc.shader = surfaceShaderDS; desc.vertexFormat = sgfx::VertexFormatHandle::invalidHandle(); pipelineStateDS = sgfx::createPipelineState(desc); if (pipelineStateDS.valid()) { drawQueueDS = sgfx::createDrawQueue(pipelineStateDS); } else { OutputDebugString("Failed to create pipeline state!"); } } // create constant buffer constantBuffer = sgfx::createConstantBuffer(nullptr, sizeof(ConstantBuffer)); // create gbuffer rtColorBuffer0GB = sgfx::createTexture2D( width, height, sgfx::DataFormat::RGBA8, 1, sgfx::TextureFlags::RenderTarget ); rtColorBuffer1GB = sgfx::createTexture2D( width, height, sgfx::DataFormat::RGBA8, 1, sgfx::TextureFlags::RenderTarget ); rtDepthBufferGB = sgfx::createTexture2D( width, height, sgfx::DataFormat::D32F, 1, sgfx::TextureFlags::DepthStencil ); sgfx::RenderTargetDescriptor rtDescDS; rtDescDS.colorTextures[0] = rtColorBuffer0GB; rtDescDS.colorTextures[1] = rtColorBuffer1GB; rtDescDS.depthStencilTexture = rtDepthBufferGB; rtDescDS.numColorTextures = 2; renderTargetGB = sgfx::createRenderTarget(rtDescDS); // create render target rtBackBufferDS = sgfx::getBackBuffer(); sgfx::RenderTargetDescriptor renderTargetDesc; renderTargetDesc.numColorTextures = 1; renderTargetDesc.colorTextures[0] = rtBackBufferDS; renderTargetDS = sgfx::createRenderTarget(renderTargetDesc); } void render(uint32_t width, uint32_t height) { // update our time static float t = 0.0f; static DWORD dwTimeStart = 0; DWORD dwTimeCur = GetTickCount(); if (dwTimeStart == 0) dwTimeStart = dwTimeCur; t = (dwTimeCur - dwTimeStart) / 1000.0f; // fill gbuffer sgfx::clearRenderTarget(renderTargetGB, 0x00000000); sgfx::clearDepthStencil(renderTargetGB, 1.0F, 0); sgfx::setRenderTarget(renderTargetGB); sgfx::setViewport(width, height, 0.0F, 1.0F); { glm::mat4 projection = glm::perspective(glm::pi<float>() / 2.0F, width / (FLOAT)height, 0.01f, 100.0f); glm::mat4 view = glm::lookAt(glm::vec3(0.0F, 1.0F, -25.0F), glm::vec3(0.0F, 1.0F, 0.0F), glm::vec3(0.0F, 1.0F, 0.0F)); glm::mat4 world = glm::rotate(glm::mat4(1.0F), t, glm::vec3(0.0F, 1.0F, 0.0F)); glm::mat4 mvp = projection * view * world; ConstantBuffer constants; std::memcpy(constants.mvp, glm::value_ptr(mvp), sizeof(constants.mvp)); sgfx::updateConstantBuffer(constantBuffer, &constants); // draw our scene { sgfx::setPrimitiveTopology(drawQueueGB, sgfx::PrimitiveTopology::TriangleList); sgfx::setConstantBuffer(drawQueueGB, 0, constantBuffer); sgfx::setVertexBuffer(drawQueueGB, akMesh.getVertexBuffer()); sgfx::setIndexBuffer(drawQueueGB, akMesh.getIndexBuffer()); sgfx::drawIndexed(drawQueueGB, akMesh.getNumIndices(), 0, 0); sgfx::submit(drawQueueGB); } } // resolve gbuffer sgfx::clearRenderTarget(renderTargetDS, 0xFFFFFFF); sgfx::setRenderTarget(renderTargetDS); sgfx::setViewport(width, height, 0.0F, 1.0F); { sgfx::setSamplerState(drawQueueDS, 0, samplerState); // resolve gbuffer { sgfx::setPrimitiveTopology(drawQueueDS, sgfx::PrimitiveTopology::TriangleList); sgfx::setResource(drawQueueDS, 0, rtColorBuffer0GB); sgfx::setResource(drawQueueDS, 1, rtColorBuffer1GB); sgfx::setResource(drawQueueDS, 2, rtDepthBufferGB); sgfx::draw(drawQueueDS, 3, 0); sgfx::submit(drawQueueDS); } } // present frame sgfx::present(1); } }; class CubeApplication : public Application { public: DeferredScene* scene; public: void* operator new(size_t size) { return _mm_malloc(size, 32); } void operator delete(void* ptr) { _mm_free(ptr); } virtual void loadSampleData() override { // setup Sigrlinn sgfx::initD3D11(g_pd3dDevice, g_pImmediateContext, g_pSwapChain); scene = new DeferredScene; scene->load(width, height, this); } virtual void releaseSampleData() override { OutputDebugString("Cleanup\n"); delete scene; sgfx::shutdown(); } virtual void renderSample() override { scene->render(width, height); } }; void sampleApplicationMain() { ApplicationInstance = new CubeApplication; }
39.516355
131
0.622716
[ "mesh", "render", "solid" ]
79e9d18566450f49966d189565c88f59137e5512
14,587
cpp
C++
src/pathfinder.cpp
DevasenaInupakutika/assn2
e533e0560241c81fa92a25b7058187562aa9fbfc
[ "Apache-2.0" ]
1
2015-03-06T05:33:39.000Z
2015-03-06T05:33:39.000Z
src/pathfinder.cpp
DevasenaInupakutika/assn2
e533e0560241c81fa92a25b7058187562aa9fbfc
[ "Apache-2.0" ]
null
null
null
src/pathfinder.cpp
DevasenaInupakutika/assn2
e533e0560241c81fa92a25b7058187562aa9fbfc
[ "Apache-2.0" ]
null
null
null
#include <ros/ros.h> #include <tf/transform_listener.h> #include <tf/transform_datatypes.h> #include "std_msgs/MultiArrayLayout.h" #include "std_msgs/MultiArrayDimension.h" #include "std_msgs/Float64MultiArray.h" #include "std_msgs/Float64.h" #include "nav_msgs/OccupancyGrid.h" #include <visualization_msgs/Marker.h> #include <tf/transform_listener.h> #include <tf/transform_datatypes.h> #include "assn2/NavGrid.h" #include "assn2/Point2d.h" #include "assn2/Path.h" using namespace std; //basic point class. thanks evan! class Point { public: double x; double y; Point() {} Point(double _x, double _y) {x=_x; y=_y;} //Point(double i,double x_dim, double y_dim) {x=i/y_dim; y=i%y_dim;} double dist(const Point &other_pt) const { return pow(pow(x - other_pt.x,2) +pow(y - other_pt.y,2),0.5); } }; class IntPoint { public: int x; int y; IntPoint() {} IntPoint(int _x, int _y) {x=_x; y=_y;} IntPoint(int i,int x_dim, int y_dim) {x=i/y_dim; y=i%y_dim;} double dist(const Point &other_pt) const { return pow(pow(x - other_pt.x,2) +pow(y - other_pt.y,2),0.5); } }; //global vars ros::Publisher path_pub; ros::Publisher marker_pub; assn2::NavGrid nav_grid; Point r_pos; Point g_pos; const double STEPSIZE = 0.8; tf::Vector3 getCostPosVector(IntPoint vertex); Point calcNormGrad(tf::Vector3 a, tf::Vector3 b, tf::Vector3 c); Point calcSquareNormGrad(tf::Vector3 bl,tf::Vector3 br,tf::Vector3 tr,tf::Vector3 tl); void test(){ nav_grid.width = 30; nav_grid.height = 30; nav_grid.resolution = 1.0; nav_grid.goalX = 0; nav_grid.goalY = 0; g_pos.x = 1.1; g_pos.y = 1.1; r_pos.x = 2.2; r_pos.y = 25.2; vector<double> costs(900); for(int i = 0; i < 900; i++) costs[i] = i; costs[0] = 32; nav_grid.costs = costs; } /* update the robot's goal in map coordinates * assumes that the goal pose is in the map frame * but not in map coordinates * */ void updateGoal(){ g_pos.x = nav_grid.goalX / nav_grid.resolution; g_pos.y = nav_grid.goalY / nav_grid.resolution; } /* * Call back function for the nav grid */ void navFnCallback(const assn2::NavGrid::ConstPtr &msg) { //populate nav_grid ROS_INFO("populating nav grid...."); nav_grid = *msg; updateGoal(); } void initMarker(visualization_msgs::Marker &marker, string name, int type) { marker.header.frame_id = "/map"; marker.header.stamp = ros::Time(); marker.ns = name; marker.id = 0; marker.type = type; marker.action = visualization_msgs::Marker::ADD; marker.pose.orientation.w = 1.0; marker.scale.x = .01; marker.scale.y = .01; marker.scale.z = .01; marker.color.a = 1.0; marker.color.r = 1.0; marker.color.g = 1.0; marker.color.b = 0.0; marker.lifetime = ros::Duration(1000); } /* * This function visualizes the gradient at each center point * */ void publishGradField(){ //uint32_t width = nav_grid.width; //uint32_t height = nav_grid.height; visualization_msgs::Marker marker; initMarker(marker, "grad_field", visualization_msgs::Marker::LINE_LIST); geometry_msgs::Point p; if (isinf(r_pos.x) || isnan(r_pos.x) || isinf(r_pos.y) || isnan(r_pos.y)) { return; } ROS_INFO("[publishGradField]\tx_min=%f,x_max=%f,y_min=%f,y_max=%f",r_pos.x - 10,r_pos.x + 10,r_pos.y - 10,r_pos.y + 10); for(uint32_t w = r_pos.x - 100; w < r_pos.x + 100; w ++){ for(uint32_t h = r_pos.y - 100; h < r_pos.y + 100; h++){ tf::Vector3 a = getCostPosVector(IntPoint(w,h)); tf::Vector3 b = getCostPosVector(IntPoint(w+1,h)); tf::Vector3 c = getCostPosVector(IntPoint(w,h+1)); tf::Vector3 d = getCostPosVector(IntPoint(w+1,h+1)); //Point grad = calcNormGrad(a, b, c); Point grad = calcSquareNormGrad(a,b,d,c); p.x = (w + 0.5)*nav_grid.resolution; p.y = (h + 0.5)*nav_grid.resolution; p.z = 0.0; marker.points.push_back(p); p.x = (w + 0.5 + grad.x)*nav_grid.resolution; p.y = (h + 0.5 + grad.y)*nav_grid.resolution; p.z = 0.0; marker.points.push_back(p); } } std::cout<<"[publishGradField]\tpublishing marker with " << marker.points.size()/2 << "lines."; marker_pub.publish(marker); } /* * This function publishes the path as a assn2::Path message * , which is in the normal map frame, not the map coordinates */ void publishPath(vector<Point> path, uint32_t length){ visualization_msgs::Marker marker; //initMarker(marker,"goal_path",visualization_msgs::Marker::LINE_STRIP); initMarker(marker,"goal_path",visualization_msgs::Marker::POINTS); geometry_msgs::Point geo_pt; // for vizualization assn2::Path p; p.length = length; vector<assn2::Point2d> ppath(length); for(uint32_t i = 0; i < length; i ++){ ppath[i].x = path[i].x * nav_grid.resolution; ppath[i].y = path[i].y * nav_grid.resolution; // visualization code geo_pt.x = ppath[i].x; geo_pt.y = ppath[i].y; geo_pt.z = 0.1; //ROS_INFO("x and y %f %f", geo_pt.x, geo_pt.y); marker.points.push_back(geo_pt); } p.path = ppath; marker_pub.publish(marker); path_pub.publish(p); } /* update the robot's pose in map coordinates */ void updateRobot(tf::StampedTransform map_bl_trans){ tf::Vector3 bl_origin = tf::Vector3(0.0, 0.0, 0.0); tf::Vector3 robotBase = map_bl_trans * bl_origin; ROS_INFO("rbase = (%f %f)", robotBase.getX(), robotBase.getY()); ROS_INFO("res = %f", nav_grid.resolution); r_pos.x = robotBase.getX() / nav_grid.resolution; r_pos.y = robotBase.getY() / nav_grid.resolution; ROS_INFO("rbase = (%f %f)", r_pos.x, r_pos.y); } //helper method to calculate distance between point and int point double calcPointDist(IntPoint a, Point b) { return pow(pow(a.x - b.x,2) +pow(a.y - b.y,2),0.5); } int getMapInd(IntPoint a){ //return nav_grid.height*(a.x) + a.y; return nav_grid.width*(a.y) + a.x; } Point calcSquareNormGrad(tf::Vector3 bl,tf::Vector3 br,tf::Vector3 tr,tf::Vector3 tl){ //ROS_INFO("[calcSquareNormGrad]\tentering..."); double dx = ((bl.getZ() - br.getZ()) + (tl.getZ() - tr.getZ()))/2.0; double dy = ((tl.getZ() - bl.getZ()) + (tr.getZ() - br.getZ()))/2.0; double total_dist = pow( pow(dx, 2) + pow(dy,2) , 0.5); if(total_dist != 0){ Point p = Point(0.5*dx/total_dist, 0.5*dy/total_dist); return p; } //if were on a plateau, just move a small distance towards the goal double xd = (g_pos.x - r_pos.x); double yd = (g_pos.y - r_pos.y); if(abs(xd) > 1.0) xd = xd/(abs(xd)); if(abs(yd) > 1.0) yd = yd/(abs(yd)); Point toreturn = Point(xd, yd); return toreturn; } tf::Vector3 getCostPosVector(IntPoint vertex){ tf::Vector3 v = tf::Vector3(1.0 * vertex.x, 1.0 * vertex.y, 0.0); //check if this vertex's point is in bounds if(((int)vertex.x) >= 0 && ((int)vertex.y) >= 0 && ((int)vertex.x) < nav_grid.width && ((int)vertex.y) < nav_grid.height){ v.setZ(nav_grid.costs[getMapInd(vertex)]); } else { //if it isn't, set the cost to be real high v.setZ(1000.0); } return v; } /* * Get the x and y distance to move if you're moving along the slope of * the plane defined by points a, b, and c */ Point calcNormGrad(tf::Vector3 a, tf::Vector3 b, tf::Vector3 c){ tf::Vector3 ab = b-a; tf::Vector3 ac = c-a; //ROS_INFO("ab %f %f %f", ab.getX(), ab.getY(), ab.getZ()); //ROS_INFO("ac %f %f %f", ac.getX(), ac.getY(), ac.getZ()); tf::Vector3 cross = ab.cross(ac); tf::Vector3 cross2 = ac.cross(ab); //ROS_INFO("cross %f %f %f", cross.getX(), cross.getY(), cross.getZ()); //ROS_INFO("cross2 %f %f %f", cross2.getX(), cross2.getY(), cross2.getZ()); //we want to use whichever cross product is sticking out positively in the y direction double xcomp = cross.getX() ; double ycomp = cross.getY() ; if(cross2.getZ() > 0){ xcomp = cross2.getX(); ycomp = cross2.getY(); } double normF = pow( pow(xcomp, 2) + pow(ycomp, 2) , 0.5); //ROS_INFO("%f %f %f", xcomp, ycomp, normF); if(normF != 0.0){ //if were not on a plateau Point toreturn = Point(STEPSIZE * xcomp/normF, STEPSIZE * ycomp/normF); return toreturn; } //if were on a plateau, just move a small distance towards the goal double xd = (g_pos.x - r_pos.x); double yd = (g_pos.y - r_pos.y); if(abs(xd) > 1.0) xd = xd/(abs(xd)); if(abs(yd) > 1.0) yd = yd/(abs(yd)); Point toreturn = Point(xd, yd); return toreturn; } /* * Find the next point along the gradient */ Point getNextPoint(Point curP){ IntPoint bl = IntPoint(floor(curP.x), floor(curP.y)); IntPoint br = IntPoint(ceil(curP.x), floor(curP.y)); IntPoint tr = IntPoint(ceil(curP.x), ceil(curP.y)); IntPoint tl = IntPoint(floor(curP.x), ceil(curP.y)); //if its right on the point if(ceil(curP.x) == curP.x){ br.x = br.x + 1; tr.x = tr.x + 1; } if(ceil(curP.y) == curP.y){ tr.y = tr.y + 1; tl.y = tl.y + 1; } tf::Vector3 a = getCostPosVector(bl); tf::Vector3 b = getCostPosVector(br); tf::Vector3 c = getCostPosVector(tl); tf::Vector3 d = getCostPosVector(tr); Point distToMove = calcSquareNormGrad(a,b,d,c); /* //find the 3 defining points and 2 defining border vectors //0 contains lower left, 1 lower right, 2 upper right, 3 upper left vector<double> node_dists(4); vector<IntPoint> adjacent_nodes(4); IntPoint ll(floor(curP.x), floor(curP.y)); IntPoint lr(ceil(curP.x), floor(curP.y)); IntPoint ur(ceil(curP.x), ceil(curP.y)); IntPoint ul(floor(curP.x), ceil(curP.y)); adjacent_nodes[0] = ll; adjacent_nodes[1] = lr; adjacent_nodes[2] = ur; adjacent_nodes[3] = ul; for(int i = 0; i < 4; i++) { node_dists[i] = calcPointDist(adjacent_nodes[i], curP); } //now, find highest distance in node_dists, and eliminate that double highest = -999999.9; int highestI = -1; for(int i = 0; i<4; i++){ if(node_dists[i] > highest){ highest = node_dists[i]; highestI = i; } } //ROS_INFO("curP = (%f %f), farthest=(%d %d)", curP.x, curP.y, adjacent_nodes[highestI].x, adjacent_nodes[highestI].y); //now, we can eliminate the index of the highest distance vector //and we have our defining 3 points of the plane adjacent_nodes[highestI] = adjacent_nodes[3]; adjacent_nodes.pop_back(); //finally, create the two bounding vectors of the //triangle plane and get the gradient of them! tf::Vector3 a = getCostPosVector(adjacent_nodes[0]); tf::Vector3 b = getCostPosVector(adjacent_nodes[1]); tf::Vector3 c = getCostPosVector(adjacent_nodes[2]); //ROS_INFO("a(%f %f %f)", a.getX(), a.getY(), a.getZ()); //ROS_INFO("b(%f %f %f)", b.getX(), b.getY(), b.getZ()); //ROS_INFO("c(%f %f %f)", c.getX(), c.getY(), c.getZ()); Point distToMove = calcNormGrad(a, b, c); */ //ROS_INFO("disttomove = %f %f", distToMove.x, distToMove.y); //return the next move Point nextMove = Point(curP.x + distToMove.x, curP.y + distToMove.y); return nextMove; } /* * main method to update the path * */ bool updatePath(){ //init path object //int maxPathSize = nav_grid.width*nav_grid.height; int maxPathSize = 1500; vector<Point> path(maxPathSize); Point curPoint(r_pos.x, r_pos.y); int curPos = 0; ROS_INFO("starting pos=(%f %f), goal pos=(%f %f)", r_pos.x, r_pos.y, g_pos.x, g_pos.y); if(r_pos.x > DBL_MAX || r_pos.y > DBL_MAX) return false; //iterate for a goal while cur point is more than 1 unit away while( curPoint.dist(g_pos) > 1.0 ) { //ROS_INFO("curpoint: (%f %f) distance to goal: %f",curPoint.x, curPoint.y, curPoint.dist(g_pos)); //find the next point in the path following the gradient curPoint = getNextPoint(curPoint); path[curPos].x = curPoint.x; path[curPos].y = curPoint.y; ROS_INFO("(after) curpoint: (%f %f) distance to goal: %f",curPoint.x, curPoint.y, curPoint.dist(g_pos)); curPos = curPos + 1; if(curPos >= maxPathSize) return false; } //if we've found something, publish it! ROS_INFO("about to publish the found path"); publishPath(path, curPos); return true; } int main(int argc, char** argv) { ////// TESTING CODE /////////// /* tf::Vector3 a = tf::Vector3(1.0, 1.0, 10.0); tf::Vector3 b = tf::Vector3(2.0, 1.0, 10.0); tf::Vector3 c = tf::Vector3(1.0, 2.0, 20.0); //tf::Vector3 a = tf::Vector3(23.0, 28.0, 863.0); //tf::Vector3 b = tf::Vector3(24.0, 28.0, 864.0); //tf::Vector3 c = tf::Vector3(23.0, 29.0, 893.0); tf::Vector3 d = tf::Vector3(1.0, 0.0, 0.0); Point t = calcNormGrad(b,c,a); ROS_INFO("%f %f", t.x, t.y); Point t2 = calcNormGrad(a,b,d); ROS_INFO("%f %f", t2.x, t2.y); test(); updatePath(); return 0; */ ////// END TESTING CODE /////////// ros::init(argc, argv, "pathfinder"); ros::NodeHandle nh; //init publishers/subscribers ros::Subscriber nav_fn_sub = nh.subscribe("/nav_grid", 1, navFnCallback); path_pub = nh.advertise<assn2::Path>("path",1); marker_pub = nh.advertise<visualization_msgs::Marker>( "visualization_marker", 0 ); //set up transform listeners tf::TransformListener listener; //set loop rate ros::Rate rate(10); while(ros::ok()){ //update the goal and nav function if there are new ones ros::spinOnce(); publishGradField(); //update transform from base_link to map tf::StampedTransform map_base_link_transform; try { ROS_INFO("getting transform...."); listener.lookupTransform("/map", "/base_link", ros::Time(0), map_base_link_transform); } catch (tf::TransformException ex) { ROS_ERROR("%s",ex.what()); } //update the robots position in map coordinates updateRobot(map_base_link_transform); //update the goals position in map coordinates updateGoal(); //create and update the path bool foundPath = updatePath(); if(!foundPath){ ROS_WARN("uh oh, we failed to find a path"); } rate.sleep(); } }
29.891393
126
0.60787
[ "object", "vector", "transform" ]
79eaca31f06a8ae3b9682508e1467bd43190b40c
5,896
cxx
C++
src/Menu.cxx
fermi-lat/gui
d2387b2d9f2bbde3a9310ff8f2cca038a339ebf6
[ "BSD-3-Clause" ]
null
null
null
src/Menu.cxx
fermi-lat/gui
d2387b2d9f2bbde3a9310ff8f2cca038a339ebf6
[ "BSD-3-Clause" ]
null
null
null
src/Menu.cxx
fermi-lat/gui
d2387b2d9f2bbde3a9310ff8f2cca038a339ebf6
[ "BSD-3-Clause" ]
null
null
null
// $Id: Menu.cxx,v 1.3 2001/10/06 04:22:14 burnett Exp $ // Author: Toby Burnett // // Menu class implementations, now just pass-through to GUI //#include "gui/Menu.h" #include "gui/SubMenu.h" #include "gui/SimpleCommand.h" #include <strstream> #include <string> #include <cstdio> // for sprintf #include <cstdlib> namespace gui { //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Menu::Menu(GUI& gui) :m_gui(gui) { // create the pull-down File menu, save a pointer for adding commands later m_fileMenu = &subMenu("File"); endMenu(); s_instance = this; } Menu::~Menu() { std::vector<SubMenu*>::iterator psm = m_sub_menus.begin(); while (psm != m_sub_menus.end()) delete (*psm++); ClientList::iterator it = m_clients.begin(); while (it != m_clients.end()) delete (*it++); std::vector<Command*>::iterator pcmd = m_commands.begin(); while( pcmd != m_commands.end()) { delete (*pcmd++); } } //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Menu* Menu::s_instance = 0; Menu* Menu::instance(Menu* m) { if(m) s_instance = m; return s_instance; } //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ void Menu::run(bool paused) // start up the application { // have all clients finish their setup ClientList::iterator it = m_clients.begin(); while (it != m_clients.end()) (*it++)->finishSetup(); // add quit to the file menu m_fileMenu->addSeparator(); m_fileMenu->addButton("Exit", new SimpleCommand<Menu>(this, &Menu::quit)); // run the gui message loop, or whatever it does if( !paused ) m_gui.start(); // if not paused else m_gui.run(); } void Menu::quit() { // have all clients quit ClientList::iterator it = m_clients.begin(); while (it != m_clients.end()) (*it++)->quit(); // then shut down message loop m_gui.quit(); } //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ void Menu::check_messages() { m_gui.processMessages(); } //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ void Menu::add_button(const std::string& title, Command* command) { m_gui.addToMenu( title.c_str(), command); m_commands.push_back(command); // save to maybe delete } //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ void Menu::addCommand(const std::string& title, Command* command) { m_gui.addToMenu( title.c_str(), command); m_commands.push_back(command); // save to maybe delete } //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ GUI::Toggle* Menu::addToggle(const std::string& title, bool state, Command* set, Command* unset) { GUI::Toggle* t =m_gui.addToggleToMenu(title.c_str(), state, set, unset); if( state ) set->execute(); else unset->execute(); m_commands.push_back(set); m_commands.push_back(unset); return t; } //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Menu::Node* Menu::beginMenu(const std::string& name, Menu::Node* subnode) { return (Menu::Node*)m_gui.beginPullDownMenu(name.c_str(), (GUI::Menu*) subnode); } //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ void Menu::setMenu(Node* m) { m_gui.restorePullDownMenu( (GUI::Menu*) m); } //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ SubMenu& Menu::file_menu() { return *m_fileMenu; } //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ void Menu::addSeparator() { m_gui.menuSeparator(); } //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ void Menu::endMenu() { m_gui.endPullDownMenu(); } //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // shortcut key implementations void Menu::register_key(char key, Command* cmd) { m_key_map[key]=cmd; } bool Menu::strike(char key) { KeyCommandMap::const_iterator it = m_key_map.find(key); if( it != m_key_map.end() ) { (*it).second->execute(); return true; } return false; } //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ void Menu::query(const std::string& ask, int* value) { char temp[20]; sprintf(temp,"%i", *value); char* answer = m_gui.askUser(ask.c_str(),temp ) ; if( answer && answer[0] ) *value =atoi(answer) ; } //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ void Menu::query(const std::string& ask, double* value, int n) { std::ostrstream temp; for(int i=0; i<n; ++i) { temp << value[i] ; if( i<n-1) temp << ", "; } temp << '\0'; std::string answer(m_gui.askUser(ask.c_str(), temp.str() ) ); #ifdef _MSC_VER // not defined otherwise? temp.rdbuf()->freeze(false); // allow delete #endif if( answer.size()==0 ) return; // check for cancel answer += ","; // for convenience //tokenize int p = 0; for(int j=0; j< n; ++j) { int q = answer.substr(p).find_first_of(","); if( q <0 ) break; if( q >0 ) value[j] = atof(answer.substr(p,q).c_str()); p += q+1; // skip to next field } } //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ void Menu::query(const std::string& ask, float* value) { char temp[20]; sprintf(temp,"%f", *value); char* answer = m_gui.askUser(ask.c_str(),temp ) ; if( answer && answer[0] ) *value =float(atof(answer)) ; } //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ void Menu::query(const std::string& ask, std::string* value) { std::string answer = m_gui.askUser(ask.c_str(),value->c_str() ) ; if( answer.length() >0 ) *value =answer ; } } // namespace gui
29.48
96
0.477951
[ "vector" ]
79ebf048e218cc93e2c272e105f54c75380aaf9d
940
cpp
C++
201-300/205-Isomorphic_Strings-e.cpp
ysmiles/leetcode-cpp
e7e6ef11224c7383071ed8efbe2feac313824a71
[ "BSD-3-Clause" ]
1
2018-10-02T22:44:52.000Z
2018-10-02T22:44:52.000Z
201-300/205-Isomorphic_Strings-e.cpp
ysmiles/leetcode-cpp
e7e6ef11224c7383071ed8efbe2feac313824a71
[ "BSD-3-Clause" ]
null
null
null
201-300/205-Isomorphic_Strings-e.cpp
ysmiles/leetcode-cpp
e7e6ef11224c7383071ed8efbe2feac313824a71
[ "BSD-3-Clause" ]
null
null
null
// Given two strings s and t, determine if they are isomorphic. // Two strings are isomorphic if the characters in s can be replaced to get t. // All occurrences of a character must be replaced with another character while // preserving the order of characters. No two characters may map to the same // character but a character may map to itself. // For example, // Given "egg", "add", return true. // Given "foo", "bar", return false. // Given "paper", "title", return true. // Note: // You may assume both s and t have the same length. class Solution { public: bool isIsomorphic(string s, string t) { vector<char> stot(128), ttos(128); // 128 basic ASCII for (int i = 0; i < s.size(); ++i) if (!stot[s[i]] && !ttos[t[i]]) { stot[s[i]] = t[i]; ttos[t[i]] = s[i]; } else if (s[i] != ttos[t[i]]) return false; return true; } };
30.322581
79
0.590426
[ "vector" ]
79f7fb5f290a798da6c26385cae740a3985c2d47
28,701
cc
C++
RecoVertex/BeamSpotProducer/src/BSFitter.cc
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
852
2015-01-11T21:03:51.000Z
2022-03-25T21:14:00.000Z
RecoVertex/BeamSpotProducer/src/BSFitter.cc
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
30,371
2015-01-02T00:14:40.000Z
2022-03-31T23:26:05.000Z
RecoVertex/BeamSpotProducer/src/BSFitter.cc
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
3,240
2015-01-02T05:53:18.000Z
2022-03-31T17:24:21.000Z
/**_________________________________________________________________ class: BSFitter.cc package: RecoVertex/BeamSpotProducer author: Francisco Yumiceva, Fermilab (yumiceva@fnal.gov) ________________________________________________________________**/ #include "Minuit2/VariableMetricMinimizer.h" #include "Minuit2/FunctionMinimum.h" #include "Minuit2/MnPrint.h" #include "Minuit2/MnMigrad.h" #include "Minuit2/MnUserParameterState.h" //#include "CLHEP/config/CLHEP.h" // C++ standard #include <vector> #include <cmath> // CMS #include "RecoVertex/BeamSpotProducer/interface/BSFitter.h" #include "FWCore/MessageLogger/interface/MessageLogger.h" #include "FWCore/Utilities/interface/Exception.h" #include "FWCore/Utilities/interface/isFinite.h" // ROOT #include "TMatrixD.h" #include "TMatrixDSym.h" #include "TDecompBK.h" #include "TH1.h" #include "TF1.h" #include "TMinuitMinimizer.h" using namespace ROOT::Minuit2; //_____________________________________________________________________ BSFitter::BSFitter() { fbeamtype = reco::BeamSpot::Unknown; //In order to make fitting ROOT histograms thread safe // one must call this undocumented function TMinuitMinimizer::UseStaticMinuit(false); } //_____________________________________________________________________ BSFitter::BSFitter(const std::vector<BSTrkParameters> &BSvector) { //In order to make fitting ROOT histograms thread safe // one must call this undocumented function TMinuitMinimizer::UseStaticMinuit(false); ffit_type = "default"; ffit_variable = "default"; fBSvector = BSvector; fsqrt2pi = sqrt(2. * TMath::Pi()); fpar_name[0] = "z0 "; fpar_name[1] = "SigmaZ0 "; fpar_name[2] = "X0 "; fpar_name[3] = "Y0 "; fpar_name[4] = "dxdz "; fpar_name[5] = "dydz "; fpar_name[6] = "SigmaBeam "; //if (theGausszFcn == 0 ) { thePDF = new BSpdfsFcn(); //} //if (theFitter == 0 ) { theFitter = new VariableMetricMinimizer(); //} fapplyd0cut = false; fapplychi2cut = false; ftmprow = 0; ftmp.ResizeTo(4, 1); ftmp.Zero(); fnthite = 0; fMaxZ = 50.; //cm fconvergence = 0.5; // stop fit when 50% of the input collection has been removed. fminNtrks = 100; finputBeamWidth = -1; // no input h1z = new TH1F("h1z", "z distribution", 200, -fMaxZ, fMaxZ); } //______________________________________________________________________ BSFitter::~BSFitter() { //delete fBSvector; delete thePDF; delete theFitter; } //______________________________________________________________________ reco::BeamSpot BSFitter::Fit() { return this->Fit(nullptr); } //______________________________________________________________________ reco::BeamSpot BSFitter::Fit(double *inipar = nullptr) { fbeamtype = reco::BeamSpot::Unknown; if (ffit_variable == "z") { if (ffit_type == "chi2") { return Fit_z_chi2(inipar); } else if (ffit_type == "likelihood") { return Fit_z_likelihood(inipar); } else if (ffit_type == "combined") { reco::BeamSpot tmp_beamspot = Fit_z_chi2(inipar); double tmp_par[2] = {tmp_beamspot.z0(), tmp_beamspot.sigmaZ()}; return Fit_z_likelihood(tmp_par); } else { throw cms::Exception("LogicError") << "Error in BeamSpotProducer/BSFitter: " << "Illegal fit type, options are chi2,likelihood or combined(ie. first chi2 then likelihood)"; } } else if (ffit_variable == "d") { if (ffit_type == "d0phi") { this->d0phi_Init(); return Fit_d0phi(); } else if (ffit_type == "likelihood") { return Fit_d_likelihood(inipar); } else if (ffit_type == "combined") { this->d0phi_Init(); reco::BeamSpot tmp_beamspot = Fit_d0phi(); double tmp_par[4] = {tmp_beamspot.x0(), tmp_beamspot.y0(), tmp_beamspot.dxdz(), tmp_beamspot.dydz()}; return Fit_d_likelihood(tmp_par); } else { throw cms::Exception("LogicError") << "Error in BeamSpotProducer/BSFitter: " << "Illegal fit type, options are d0phi, likelihood or combined"; } } else if (ffit_variable == "d*z" || ffit_variable == "default") { if (ffit_type == "likelihood" || ffit_type == "default") { reco::BeamSpot::CovarianceMatrix matrix; // we are now fitting Z inside d0phi fitter // first fit z distribution using a chi2 fit //reco::BeamSpot tmp_z = Fit_z_chi2(inipar); //for (int j = 2 ; j < 4 ; ++j) { //for(int k = j ; k < 4 ; ++k) { // matrix(j,k) = tmp_z.covariance()(j,k); //} //} // use d0-phi algorithm to extract transverse position this->d0phi_Init(); //reco::BeamSpot tmp_d0phi= Fit_d0phi(); // change to iterative procedure: this->Setd0Cut_d0phi(4.0); reco::BeamSpot tmp_d0phi = Fit_ited0phi(); //for (int j = 0 ; j < 2 ; ++j) { // for(int k = j ; k < 2 ; ++k) { // matrix(j,k) = tmp_d0phi.covariance()(j,k); //} //} // slopes //for (int j = 4 ; j < 6 ; ++j) { // for(int k = j ; k < 6 ; ++k) { // matrix(j,k) = tmp_d0phi.covariance()(j,k); // } //} // put everything into one object reco::BeamSpot spot(reco::BeamSpot::Point(tmp_d0phi.x0(), tmp_d0phi.y0(), tmp_d0phi.z0()), tmp_d0phi.sigmaZ(), tmp_d0phi.dxdz(), tmp_d0phi.dydz(), 0., tmp_d0phi.covariance(), fbeamtype); //reco::BeamSpot tmp_z = Fit_z_chi2(inipar); //reco::BeamSpot tmp_d0phi = Fit_d0phi(); // log-likelihood fit if (ffit_type == "likelihood") { double tmp_par[7] = { tmp_d0phi.x0(), tmp_d0phi.y0(), tmp_d0phi.z0(), tmp_d0phi.sigmaZ(), tmp_d0phi.dxdz(), tmp_d0phi.dydz(), 0.0}; double tmp_error_par[7]; for (int s = 0; s < 6; s++) { tmp_error_par[s] = pow(tmp_d0phi.covariance()(s, s), 0.5); } tmp_error_par[6] = 0.0; reco::BeamSpot tmp_lh = Fit_d_z_likelihood(tmp_par, tmp_error_par); if (edm::isNotFinite(ff_minimum)) { edm::LogWarning("BSFitter") << "BSFitter: Result is non physical. Log-Likelihood fit to extract beam width did not converge." << std::endl; tmp_lh.setType(reco::BeamSpot::Unknown); return tmp_lh; } return tmp_lh; } else { edm::LogInfo("BSFitter") << "default track-based fit does not extract beam width." << std::endl; return spot; } } else if (ffit_type == "resolution") { reco::BeamSpot tmp_z = Fit_z_chi2(inipar); this->d0phi_Init(); reco::BeamSpot tmp_d0phi = Fit_d0phi(); double tmp_par[7] = { tmp_d0phi.x0(), tmp_d0phi.y0(), tmp_z.z0(), tmp_z.sigmaZ(), tmp_d0phi.dxdz(), tmp_d0phi.dydz(), 0.0}; double tmp_error_par[7]; for (int s = 0; s < 6; s++) { tmp_error_par[s] = pow(tmp_par[s], 0.5); } tmp_error_par[6] = 0.0; reco::BeamSpot tmp_beam = Fit_d_z_likelihood(tmp_par, tmp_error_par); double tmp_par2[7] = {tmp_beam.x0(), tmp_beam.y0(), tmp_beam.z0(), tmp_beam.sigmaZ(), tmp_beam.dxdz(), tmp_beam.dydz(), tmp_beam.BeamWidthX()}; reco::BeamSpot tmp_lh = Fit_dres_z_likelihood(tmp_par2); if (edm::isNotFinite(ff_minimum)) { edm::LogWarning("BSFitter") << "Result is non physical. Log-Likelihood fit did not converge." << std::endl; tmp_lh.setType(reco::BeamSpot::Unknown); return tmp_lh; } return tmp_lh; } else { throw cms::Exception("LogicError") << "Error in BeamSpotProducer/BSFitter: " << "Illegal fit type, options are likelihood or resolution"; } } else { throw cms::Exception("LogicError") << "Error in BeamSpotProducer/BSFitter: " << "Illegal variable type, options are \"z\", \"d\", or \"d*z\""; } } //______________________________________________________________________ reco::BeamSpot BSFitter::Fit_z_likelihood(double *inipar) { //std::cout << "Fit_z(double *) called" << std::endl; //std::cout << "inipar[0]= " << inipar[0] << std::endl; //std::cout << "inipar[1]= " << inipar[1] << std::endl; std::vector<double> par(2, 0); std::vector<double> err(2, 0); par.push_back(0.0); par.push_back(7.0); err.push_back(0.0001); err.push_back(0.0001); //par[0] = 0.0; err[0] = 0.0; //par[1] = 7.0; err[1] = 0.0; thePDF->SetPDFs("PDFGauss_z"); thePDF->SetData(fBSvector); //std::cout << "data loaded"<< std::endl; //FunctionMinimum fmin = theFitter->Minimize(*theGausszFcn, par, err, 1, 500, 0.1); MnUserParameters upar; upar.Add("X0", 0., 0.); upar.Add("Y0", 0., 0.); upar.Add("Z0", inipar[0], 0.001); upar.Add("sigmaZ", inipar[1], 0.001); MnMigrad migrad(*thePDF, upar); FunctionMinimum fmin = migrad(); ff_minimum = fmin.Fval(); //std::cout << " eval= " << ff_minimum // << "/n params[0]= " << fmin.Parameters().Vec()(0) << std::endl; /* TMinuit *gmMinuit = new TMinuit(2); //gmMinuit->SetFCN(z_fcn); gmMinuit->SetFCN(myFitz_fcn); int ierflg = 0; double step[2] = {0.001,0.001}; for (int i = 0; i<2; i++) { gmMinuit->mnparm(i,fpar_name[i].c_str(),inipar[i],step[i],0,0,ierflg); } gmMinuit->Migrad(); */ reco::BeamSpot::CovarianceMatrix matrix; for (int j = 2; j < 4; ++j) { for (int k = j; k < 4; ++k) { matrix(j, k) = fmin.Error().Matrix()(j, k); } } return reco::BeamSpot(reco::BeamSpot::Point(0., 0., fmin.Parameters().Vec()(2)), fmin.Parameters().Vec()(3), 0., 0., 0., matrix, fbeamtype); } //______________________________________________________________________ reco::BeamSpot BSFitter::Fit_z_chi2(double *inipar) { // N.B. this fit is not performed anymore but now // Z is fitted in the same track set used in the d0-phi fit after // each iteration //std::cout << "Fit_z_chi2() called" << std::endl; // FIXME: include whole tracker z length for the time being // ==> add protection and z0 cut h1z = new TH1F("h1z", "z distribution", 200, -fMaxZ, fMaxZ); std::vector<BSTrkParameters>::const_iterator iparam = fBSvector.begin(); // HERE check size of track vector for (iparam = fBSvector.begin(); iparam != fBSvector.end(); ++iparam) { h1z->Fill(iparam->z0()); //std::cout<<"z0="<<iparam->z0()<<"; sigZ0="<<iparam->sigz0()<<std::endl; } //Use our own copy for thread safety // also do not add to global list of functions TF1 fgaus("fgaus", "gaus", 0., 1., TF1::EAddToList::kNo); h1z->Fit(&fgaus, "QLMN0 SERIAL"); //std::cout << "fitted "<< std::endl; //std::cout << "got function" << std::endl; double fpar[2] = {fgaus.GetParameter(1), fgaus.GetParameter(2)}; //std::cout<<"Debug fpar[2] = (" <<fpar[0]<<","<<fpar[1]<<")"<<std::endl; reco::BeamSpot::CovarianceMatrix matrix; // add matrix values. matrix(2, 2) = fgaus.GetParError(1) * fgaus.GetParError(1); matrix(3, 3) = fgaus.GetParError(2) * fgaus.GetParError(2); //delete h1z; return reco::BeamSpot(reco::BeamSpot::Point(0., 0., fpar[0]), fpar[1], 0., 0., 0., matrix, fbeamtype); } //______________________________________________________________________ reco::BeamSpot BSFitter::Fit_ited0phi() { this->d0phi_Init(); edm::LogInfo("BSFitter") << "number of total input tracks: " << fBSvector.size() << std::endl; reco::BeamSpot theanswer; if ((int)fBSvector.size() <= fminNtrks) { edm::LogWarning("BSFitter") << "need at least " << fminNtrks << " tracks to run beamline fitter." << std::endl; fbeamtype = reco::BeamSpot::Fake; theanswer.setType(fbeamtype); return theanswer; } theanswer = Fit_d0phi(); //get initial ftmp and ftmprow if (goodfit) fnthite++; //std::cout << "Initial tempanswer (iteration 0): " << theanswer << std::endl; reco::BeamSpot preanswer = theanswer; while (goodfit && ftmprow > fconvergence * fBSvector.size() && ftmprow > fminNtrks) { theanswer = Fit_d0phi(); fd0cut /= 1.5; fchi2cut /= 1.5; if (goodfit && ftmprow > fconvergence * fBSvector.size() && ftmprow > fminNtrks) { preanswer = theanswer; //std::cout << "Iteration " << fnthite << ": " << preanswer << std::endl; fnthite++; } } // FIXME: return fit results from previous iteration for both bad fit and for >50% tracks thrown away //std::cout << "The last iteration, theanswer: " << theanswer << std::endl; theanswer = preanswer; //std::cout << "Use previous results from iteration #" << ( fnthite > 0 ? fnthite-1 : 0 ) << std::endl; //if ( fnthite > 1 ) std::cout << theanswer << std::endl; edm::LogInfo("BSFitter") << "Total number of successful iterations = " << (goodfit ? (fnthite + 1) : fnthite) << std::endl; if (goodfit) { fbeamtype = reco::BeamSpot::Tracker; theanswer.setType(fbeamtype); } else { edm::LogWarning("BSFitter") << "Fit doesn't converge!!!" << std::endl; fbeamtype = reco::BeamSpot::Unknown; theanswer.setType(fbeamtype); } return theanswer; } //______________________________________________________________________ reco::BeamSpot BSFitter::Fit_d0phi() { //LogDebug ("BSFitter") << " we will use " << fBSvector.size() << " tracks."; if (fnthite > 0) edm::LogInfo("BSFitter") << " number of tracks used: " << ftmprow << std::endl; //std::cout << " ftmp = matrix("<<ftmp.GetNrows()<<","<<ftmp.GetNcols()<<")"<<std::endl; //std::cout << " ftmp(0,0)="<<ftmp(0,0)<<std::endl; //std::cout << " ftmp(1,0)="<<ftmp(1,0)<<std::endl; //std::cout << " ftmp(2,0)="<<ftmp(2,0)<<std::endl; //std::cout << " ftmp(3,0)="<<ftmp(3,0)<<std::endl; h1z->Reset(); TMatrixD x_result(4, 1); TMatrixDSym V_result(4); TMatrixDSym Vint(4); TMatrixD b(4, 1); //Double_t weightsum = 0; Vint.Zero(); b.Zero(); TMatrixD g(4, 1); TMatrixDSym temp(4); std::vector<BSTrkParameters>::iterator iparam = fBSvector.begin(); ftmprow = 0; //edm::LogInfo ("BSFitter") << " test"; //std::cout << "BSFitter: fit" << std::endl; for (iparam = fBSvector.begin(); iparam != fBSvector.end(); ++iparam) { //if(i->weight2 == 0) continue; //if (ftmprow==0) { //std::cout << "d0=" << iparam->d0() << " sigd0=" << iparam->sigd0() //<< " phi0="<< iparam->phi0() << " z0=" << iparam->z0() << std::endl; //std::cout << "d0phi_d0=" << iparam->d0phi_d0() << " d0phi_chi2="<<iparam->d0phi_chi2() << std::endl; //} g(0, 0) = sin(iparam->phi0()); g(1, 0) = -cos(iparam->phi0()); g(2, 0) = iparam->z0() * g(0, 0); g(3, 0) = iparam->z0() * g(1, 0); // average transverse beam width double sigmabeam2 = 0.006 * 0.006; if (finputBeamWidth > 0) sigmabeam2 = finputBeamWidth * finputBeamWidth; else { //edm::LogWarning("BSFitter") << "using in fit beam width = " << sqrt(sigmabeam2) << std::endl; } //double sigma2 = sigmabeam2 + (iparam->sigd0())* (iparam->sigd0()) / iparam->weight2; // this should be 2*sigmabeam2? double sigma2 = sigmabeam2 + (iparam->sigd0()) * (iparam->sigd0()); TMatrixD ftmptrans(1, 4); ftmptrans = ftmptrans.Transpose(ftmp); TMatrixD dcor = ftmptrans * g; double chi2tmp = (iparam->d0() - dcor(0, 0)) * (iparam->d0() - dcor(0, 0)) / sigma2; (*iparam) = BSTrkParameters( iparam->z0(), iparam->sigz0(), iparam->d0(), iparam->sigd0(), iparam->phi0(), iparam->pt(), dcor(0, 0), chi2tmp); bool pass = true; if (fapplyd0cut && fnthite > 0) { if (std::abs(iparam->d0() - dcor(0, 0)) > fd0cut) pass = false; } if (fapplychi2cut && fnthite > 0) { if (chi2tmp > fchi2cut) pass = false; } if (pass) { temp.Zero(); for (int j = 0; j < 4; ++j) { for (int k = j; k < 4; ++k) { temp(j, k) += g(j, 0) * g(k, 0); } } Vint += (temp * (1 / sigma2)); b += (iparam->d0() / sigma2 * g); //weightsum += sqrt(i->weight2); ftmprow++; h1z->Fill(iparam->z0()); } } Double_t determinant; TDecompBK bk(Vint); bk.SetTol(1e-11); //FIXME: find a better way to solve x_result if (!bk.Decompose()) { goodfit = false; edm::LogWarning("BSFitter") << "Decomposition failed, matrix singular ?" << std::endl << "condition number = " << bk.Condition() << std::endl; } else { V_result = Vint.InvertFast(&determinant); x_result = V_result * b; } // for(int j = 0 ; j < 4 ; ++j) { // for(int k = 0 ; k < 4 ; ++k) { // std::cout<<"V_result("<<j<<","<<k<<")="<<V_result(j,k)<<std::endl; // } // } // for (int j=0;j<4;++j){ // std::cout<<"x_result("<<j<<",0)="<<x_result(j,0)<<std::endl; // } //LogDebug ("BSFitter") << " d0-phi fit done."; //std::cout<< " d0-phi fit done." << std::endl; //Use our own copy for thread safety // also do not add to global list of functions TF1 fgaus("fgaus", "gaus", 0., 1., TF1::EAddToList::kNo); //returns 0 if OK //auto status = h1z->Fit(&fgaus,"QLM0","",h1z->GetMean() -2.*h1z->GetRMS(),h1z->GetMean() +2.*h1z->GetRMS()); auto status = h1z->Fit(&fgaus, "QLN0 SERIAL", "", h1z->GetMean() - 2. * h1z->GetRMS(), h1z->GetMean() + 2. * h1z->GetRMS()); //std::cout << "fitted "<< std::endl; //std::cout << "got function" << std::endl; if (status) { //edm::LogError("NoBeamSpotFit")<<"gaussian fit failed. no BS d0 fit"; goodfit = false; return reco::BeamSpot(); } double fpar[2] = {fgaus.GetParameter(1), fgaus.GetParameter(2)}; reco::BeamSpot::CovarianceMatrix matrix; // first two parameters for (int j = 0; j < 2; ++j) { for (int k = j; k < 2; ++k) { matrix(j, k) = V_result(j, k); } } // slope parameters for (int j = 4; j < 6; ++j) { for (int k = j; k < 6; ++k) { matrix(j, k) = V_result(j - 2, k - 2); } } // Z0 and sigmaZ matrix(2, 2) = fgaus.GetParError(1) * fgaus.GetParError(1); matrix(3, 3) = fgaus.GetParError(2) * fgaus.GetParError(2); ftmp = x_result; // x0 and y0 are *not* x,y at z=0, but actually at z=0 // to correct for this, we need to translate them to z=z0 // using the measured slopes // double x0tmp = x_result(0, 0); double y0tmp = x_result(1, 0); x0tmp += x_result(2, 0) * fpar[0]; y0tmp += x_result(3, 0) * fpar[0]; return reco::BeamSpot( reco::BeamSpot::Point(x0tmp, y0tmp, fpar[0]), fpar[1], x_result(2, 0), x_result(3, 0), 0., matrix, fbeamtype); } //______________________________________________________________________ void BSFitter::Setd0Cut_d0phi(double d0cut) { fapplyd0cut = true; //fBSforCuts = BSfitted; fd0cut = d0cut; } //______________________________________________________________________ void BSFitter::SetChi2Cut_d0phi(double chi2cut) { fapplychi2cut = true; //fBSforCuts = BSfitted; fchi2cut = chi2cut; } //______________________________________________________________________ reco::BeamSpot BSFitter::Fit_d_likelihood(double *inipar) { thePDF->SetPDFs("PDFGauss_d"); thePDF->SetData(fBSvector); MnUserParameters upar; upar.Add("X0", inipar[0], 0.001); upar.Add("Y0", inipar[1], 0.001); upar.Add("Z0", 0., 0.001); upar.Add("sigmaZ", 0., 0.001); upar.Add("dxdz", inipar[2], 0.001); upar.Add("dydz", inipar[3], 0.001); MnMigrad migrad(*thePDF, upar); FunctionMinimum fmin = migrad(); ff_minimum = fmin.Fval(); reco::BeamSpot::CovarianceMatrix matrix; for (int j = 0; j < 6; ++j) { for (int k = j; k < 6; ++k) { matrix(j, k) = fmin.Error().Matrix()(j, k); } } return reco::BeamSpot(reco::BeamSpot::Point(fmin.Parameters().Vec()(0), fmin.Parameters().Vec()(1), 0.), 0., fmin.Parameters().Vec()(4), fmin.Parameters().Vec()(5), 0., matrix, fbeamtype); } //______________________________________________________________________ double BSFitter::scanPDF(double *init_pars, int &tracksfixed, int option) { if (option == 1) init_pars[6] = 0.0005; //starting value for any given configuration //local vairables with initial values double fsqrt2pi = 0.0; double d_sig = 0.0; double d_dprime = 0.0; double d_result = 0.0; double z_sig = 0.0; double z_result = 0.0; double function = 0.0; double tot_pdf = 0.0; double last_minvalue = 1.0e+10; double init_bw = -99.99; int iters = 0; //used to remove tracks if far away from bs by this double DeltadCut = 0.1000; if (init_pars[6] < 0.0200) { DeltadCut = 0.0900; } //worked for high 2.36TeV if (init_pars[6] < 0.0100) { DeltadCut = 0.0700; } //just a guesss for 7 TeV but one should scan for actual values std::vector<BSTrkParameters>::const_iterator iparam = fBSvector.begin(); if (option == 1) iters = 500; if (option == 2) iters = 1; for (int p = 0; p < iters; p++) { if (iters == 500) init_pars[6] += 0.0002; tracksfixed = 0; for (iparam = fBSvector.begin(); iparam != fBSvector.end(); ++iparam) { fsqrt2pi = sqrt(2. * TMath::Pi()); d_sig = sqrt(init_pars[6] * init_pars[6] + (iparam->sigd0()) * (iparam->sigd0())); d_dprime = iparam->d0() - (((init_pars[0] + iparam->z0() * (init_pars[4])) * sin(iparam->phi0())) - ((init_pars[1] + iparam->z0() * (init_pars[5])) * cos(iparam->phi0()))); //***Remove tracks before the fit which gives low pdf values to blow up the pdf if (std::abs(d_dprime) < DeltadCut && option == 2) { fBSvectorBW.push_back(*iparam); } d_result = (exp(-(d_dprime * d_dprime) / (2.0 * d_sig * d_sig))) / (d_sig * fsqrt2pi); z_sig = sqrt(iparam->sigz0() * iparam->sigz0() + init_pars[3] * init_pars[3]); z_result = (exp(-((iparam->z0() - init_pars[2]) * (iparam->z0() - init_pars[2])) / (2.0 * z_sig * z_sig))) / (z_sig * fsqrt2pi); tot_pdf = z_result * d_result; //for those trcks which gives problems due to very tiny pdf_d values. //Update: This protection will NOT be used with the dprime cut above but still kept here to get // the intial value of beam width reasonably //A warning will appear if there were any tracks with < 10^-5 for pdf_d so that (d-dprime) cut can be lowered if (d_result < 1.0e-05) { tot_pdf = z_result * 1.0e-05; //if(option==2)std::cout<<"last Iter d-d' = "<<(std::abs(d_dprime))<<std::endl; tracksfixed++; } function = function + log(tot_pdf); } //loop over tracks function = -2.0 * function; if (function < last_minvalue) { init_bw = init_pars[6]; last_minvalue = function; } function = 0.0; } //loop over beam width if (init_bw > 0) { init_bw = init_bw + (0.20 * init_bw); //start with 20 % more } else { if (option == 1) { edm::LogWarning("BSFitter") << "scanPDF:====>>>> WARNING***: The initial guess value of Beam width is negative!!!!!!" << std::endl << "scanPDF:====>>>> Assigning beam width a starting value of " << init_bw << " cm" << std::endl; init_bw = 0.0200; } } return init_bw; } //________________________________________________________________________________ reco::BeamSpot BSFitter::Fit_d_z_likelihood(double *inipar, double *error_par) { int tracksFailed = 0; //estimate first guess of beam width and tame 20% extra of it to start inipar[6] = scanPDF(inipar, tracksFailed, 1); error_par[6] = (inipar[6]) * 0.20; //Here remove the tracks which give low pdf and fill into a new vector //std::cout<<"Size of Old vector = "<<(fBSvector.size())<<std::endl; /* double junk= */ scanPDF(inipar, tracksFailed, 2); //std::cout<<"Size of New vector = "<<(fBSvectorBW.size())<<std::endl; //Refill the fBSVector again with new sets of tracks fBSvector.clear(); std::vector<BSTrkParameters>::const_iterator iparamBW = fBSvectorBW.begin(); for (iparamBW = fBSvectorBW.begin(); iparamBW != fBSvectorBW.end(); ++iparamBW) { fBSvector.push_back(*iparamBW); } thePDF->SetPDFs("PDFGauss_d*PDFGauss_z"); thePDF->SetData(fBSvector); MnUserParameters upar; upar.Add("X0", inipar[0], error_par[0]); upar.Add("Y0", inipar[1], error_par[1]); upar.Add("Z0", inipar[2], error_par[2]); upar.Add("sigmaZ", inipar[3], error_par[3]); upar.Add("dxdz", inipar[4], error_par[4]); upar.Add("dydz", inipar[5], error_par[5]); upar.Add("BeamWidthX", inipar[6], error_par[6]); MnMigrad migrad(*thePDF, upar); FunctionMinimum fmin = migrad(); // std::cout<<"-----how the fit evoves------"<<std::endl; // std::cout<<fmin<<std::endl; ff_minimum = fmin.Fval(); bool ff_nfcn = fmin.HasReachedCallLimit(); bool ff_cov = fmin.HasCovariance(); bool testing = fmin.IsValid(); //Print WARNINGS if minimum did not converged if (!testing) { edm::LogWarning("BSFitter") << "===========>>>>>** WARNING: MINUIT DID NOT CONVERGES PROPERLY !!!!!!" << std::endl; if (ff_nfcn) edm::LogWarning("BSFitter") << "===========>>>>>** WARNING: No. of Calls Exhausted" << std::endl; if (!ff_cov) edm::LogWarning("BSFitter") << "===========>>>>>** WARNING: Covariance did not found" << std::endl; } edm::LogInfo("BSFitter") << "The Total # Tracks used for beam width fit = " << (fBSvectorBW.size()) << std::endl; //Checks after fit is performed double lastIter_pars[7]; for (int ip = 0; ip < 7; ip++) { lastIter_pars[ip] = fmin.Parameters().Vec()(ip); } tracksFailed = 0; /* double lastIter_scan= */ scanPDF(lastIter_pars, tracksFailed, 2); edm::LogWarning("BSFitter") << "WARNING: # of tracks which have very low pdf value (pdf_d < 1.0e-05) are = " << tracksFailed << std::endl; //std::cout << " eval= " << ff_minimum // << "/n params[0]= " << fmin.Parameters().Vec()(0) << std::endl; reco::BeamSpot::CovarianceMatrix matrix; for (int j = 0; j < 7; ++j) { for (int k = j; k < 7; ++k) { matrix(j, k) = fmin.Error().Matrix()(j, k); } } return reco::BeamSpot( reco::BeamSpot::Point(fmin.Parameters().Vec()(0), fmin.Parameters().Vec()(1), fmin.Parameters().Vec()(2)), fmin.Parameters().Vec()(3), fmin.Parameters().Vec()(4), fmin.Parameters().Vec()(5), fmin.Parameters().Vec()(6), matrix, fbeamtype); } //______________________________________________________________________ reco::BeamSpot BSFitter::Fit_dres_z_likelihood(double *inipar) { thePDF->SetPDFs("PDFGauss_d_resolution*PDFGauss_z"); thePDF->SetData(fBSvector); MnUserParameters upar; upar.Add("X0", inipar[0], 0.001); upar.Add("Y0", inipar[1], 0.001); upar.Add("Z0", inipar[2], 0.001); upar.Add("sigmaZ", inipar[3], 0.001); upar.Add("dxdz", inipar[4], 0.001); upar.Add("dydz", inipar[5], 0.001); upar.Add("BeamWidthX", inipar[6], 0.0001); upar.Add("c0", 0.0010, 0.0001); upar.Add("c1", 0.0090, 0.0001); // fix beam width upar.Fix("BeamWidthX"); // number of parameters in fit are 9-1 = 8 MnMigrad migrad(*thePDF, upar); FunctionMinimum fmin = migrad(); ff_minimum = fmin.Fval(); reco::BeamSpot::CovarianceMatrix matrix; for (int j = 0; j < 6; ++j) { for (int k = j; k < 6; ++k) { matrix(j, k) = fmin.Error().Matrix()(j, k); } } //std::cout << " fill resolution values" << std::endl; //std::cout << " matrix size= " << fmin.Error().Matrix().size() << std::endl; //std::cout << " vec(6)="<< fmin.Parameters().Vec()(6) << std::endl; //std::cout << " vec(7)="<< fmin.Parameters().Vec()(7) << std::endl; fresolution_c0 = fmin.Parameters().Vec()(6); fresolution_c1 = fmin.Parameters().Vec()(7); fres_c0_err = sqrt(fmin.Error().Matrix()(6, 6)); fres_c1_err = sqrt(fmin.Error().Matrix()(7, 7)); for (int j = 6; j < 8; ++j) { for (int k = 6; k < 8; ++k) { fres_matrix(j - 6, k - 6) = fmin.Error().Matrix()(j, k); } } return reco::BeamSpot( reco::BeamSpot::Point(fmin.Parameters().Vec()(0), fmin.Parameters().Vec()(1), fmin.Parameters().Vec()(2)), fmin.Parameters().Vec()(3), fmin.Parameters().Vec()(4), fmin.Parameters().Vec()(5), inipar[6], matrix, fbeamtype); }
33.142032
121
0.595101
[ "object", "vector" ]
79fb716318551ce2fed298ef36093741eaaa657e
15,232
cc
C++
extensions/renderer/messaging_bindings.cc
Wzzzx/chromium-crosswalk
768dde8efa71169f1c1113ca6ef322f1e8c9e7de
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
2
2019-01-28T08:09:58.000Z
2021-11-15T15:32:10.000Z
extensions/renderer/messaging_bindings.cc
Wzzzx/chromium-crosswalk
768dde8efa71169f1c1113ca6ef322f1e8c9e7de
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
extensions/renderer/messaging_bindings.cc
Wzzzx/chromium-crosswalk
768dde8efa71169f1c1113ca6ef322f1e8c9e7de
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
6
2020-09-23T08:56:12.000Z
2021-11-18T03:40:49.000Z
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "extensions/renderer/messaging_bindings.h" #include <stdint.h> #include <map> #include <string> #include "base/bind.h" #include "base/bind_helpers.h" #include "base/callback.h" #include "base/macros.h" #include "base/memory/weak_ptr.h" #include "base/message_loop/message_loop.h" #include "base/values.h" #include "components/guest_view/common/guest_view_constants.h" #include "content/public/child/v8_value_converter.h" #include "content/public/common/child_process_host.h" #include "content/public/renderer/render_frame.h" #include "content/public/renderer/render_thread.h" #include "extensions/common/api/messaging/message.h" #include "extensions/common/extension_messages.h" #include "extensions/common/manifest_handlers/externally_connectable.h" #include "extensions/renderer/event_bindings.h" #include "extensions/renderer/extension_frame_helper.h" #include "extensions/renderer/gc_callback.h" #include "extensions/renderer/object_backed_native_handler.h" #include "extensions/renderer/script_context.h" #include "extensions/renderer/script_context_set.h" #include "extensions/renderer/v8_helpers.h" #include "third_party/WebKit/public/web/WebDocument.h" #include "third_party/WebKit/public/web/WebLocalFrame.h" #include "third_party/WebKit/public/web/WebScopedUserGesture.h" #include "third_party/WebKit/public/web/WebScopedWindowFocusAllowedIndicator.h" #include "third_party/WebKit/public/web/WebUserGestureIndicator.h" #include "v8/include/v8.h" // Message passing API example (in a content script): // var extension = // new chrome.Extension('00123456789abcdef0123456789abcdef0123456'); // var port = runtime.connect(); // port.postMessage('Can you hear me now?'); // port.onmessage.addListener(function(msg, port) { // alert('response=' + msg); // port.postMessage('I got your reponse'); // }); using content::RenderThread; using content::V8ValueConverter; namespace extensions { using v8_helpers::ToV8String; using v8_helpers::ToV8StringUnsafe; using v8_helpers::IsEmptyOrUndefied; namespace { class ExtensionImpl : public ObjectBackedNativeHandler { public: explicit ExtensionImpl(ScriptContext* context) : ObjectBackedNativeHandler(context), weak_ptr_factory_(this) { RouteFunction( "CloseChannel", base::Bind(&ExtensionImpl::CloseChannel, base::Unretained(this))); RouteFunction( "PostMessage", base::Bind(&ExtensionImpl::PostMessage, base::Unretained(this))); // TODO(fsamuel, kalman): Move BindToGC out of messaging natives. RouteFunction("BindToGC", base::Bind(&ExtensionImpl::BindToGC, base::Unretained(this))); } ~ExtensionImpl() override {} private: // Sends a message along the given channel. void PostMessage(const v8::FunctionCallbackInfo<v8::Value>& args) { // Arguments are (int32_t port_id, string message). CHECK(args.Length() == 2 && args[0]->IsInt32() && args[1]->IsString()); int port_id = args[0].As<v8::Int32>()->Value(); content::RenderFrame* render_frame = context()->GetRenderFrame(); if (render_frame) { render_frame->Send(new ExtensionHostMsg_PostMessage( render_frame->GetRoutingID(), port_id, Message(*v8::String::Utf8Value(args[1]), blink::WebUserGestureIndicator::isProcessingUserGesture()))); } } // Close a port, optionally forcefully (i.e. close the whole channel instead // of just the given port). void CloseChannel(const v8::FunctionCallbackInfo<v8::Value>& args) { // Arguments are (int32_t port_id, bool force_close). CHECK_EQ(2, args.Length()); CHECK(args[0]->IsInt32()); CHECK(args[1]->IsBoolean()); int port_id = args[0].As<v8::Int32>()->Value(); bool force_close = args[1].As<v8::Boolean>()->Value(); ClosePort(port_id, force_close); } // void BindToGC(object, callback, port_id) // // Binds |callback| to be invoked *sometime after* |object| is garbage // collected. We don't call the method re-entrantly so as to avoid executing // JS in some bizarro undefined mid-GC state, nor do we then call into the // script context if it's been invalidated. // // If the script context *is* invalidated in the meantime, as a slight hack, // release the port with ID |port_id| if it's >= 0. void BindToGC(const v8::FunctionCallbackInfo<v8::Value>& args) { CHECK(args.Length() == 3 && args[0]->IsObject() && args[1]->IsFunction() && args[2]->IsInt32()); int port_id = args[2].As<v8::Int32>()->Value(); base::Closure fallback = base::Bind(&base::DoNothing); if (port_id >= 0) { // TODO(robwu): Falling back to closing the port shouldn't be needed. If // the script context is destroyed, then the frame has navigated. But that // is already detected by the browser, so this logic is redundant. Remove // this fallback (and move BindToGC out of messaging because it is also // used in other places that have nothing to do with messaging...). fallback = base::Bind(&ExtensionImpl::ClosePort, weak_ptr_factory_.GetWeakPtr(), port_id, false /* force_close */); } // Destroys itself when the object is GC'd or context is invalidated. new GCCallback(context(), args[0].As<v8::Object>(), args[1].As<v8::Function>(), fallback); } // See ExtensionImpl::CloseChannel for documentation. // TODO(robwu): Merge this logic with CloseChannel once the TODO in BindToGC // has been addressed. void ClosePort(int port_id, bool force_close) { content::RenderFrame* render_frame = context()->GetRenderFrame(); if (render_frame) { render_frame->Send(new ExtensionHostMsg_CloseMessagePort( render_frame->GetRoutingID(), port_id, force_close)); } } base::WeakPtrFactory<ExtensionImpl> weak_ptr_factory_; }; void HasMessagePort(int port_id, bool* has_port, ScriptContext* script_context) { if (*has_port) return; // Stop checking if the port was found. v8::Isolate* isolate = script_context->isolate(); v8::HandleScope handle_scope(isolate); v8::Local<v8::Value> port_id_handle = v8::Integer::New(isolate, port_id); v8::Local<v8::Value> v8_has_port = script_context->module_system()->CallModuleMethod("messaging", "hasPort", 1, &port_id_handle); if (IsEmptyOrUndefied(v8_has_port)) return; CHECK(v8_has_port->IsBoolean()); if (!v8_has_port.As<v8::Boolean>()->Value()) return; *has_port = true; } void DispatchOnConnectToScriptContext( int target_port_id, const std::string& channel_name, const ExtensionMsg_TabConnectionInfo* source, const ExtensionMsg_ExternalConnectionInfo& info, const std::string& tls_channel_id, bool* port_created, ScriptContext* script_context) { v8::Isolate* isolate = script_context->isolate(); v8::HandleScope handle_scope(isolate); std::unique_ptr<V8ValueConverter> converter(V8ValueConverter::create()); const std::string& source_url_spec = info.source_url.spec(); std::string target_extension_id = script_context->GetExtensionID(); const Extension* extension = script_context->extension(); v8::Local<v8::Value> tab = v8::Null(isolate); v8::Local<v8::Value> tls_channel_id_value = v8::Undefined(isolate); v8::Local<v8::Value> guest_process_id = v8::Undefined(isolate); v8::Local<v8::Value> guest_render_frame_routing_id = v8::Undefined(isolate); if (extension) { if (!source->tab.empty() && !extension->is_platform_app()) tab = converter->ToV8Value(&source->tab, script_context->v8_context()); ExternallyConnectableInfo* externally_connectable = ExternallyConnectableInfo::Get(extension); if (externally_connectable && externally_connectable->accepts_tls_channel_id) { v8::Local<v8::String> v8_tls_channel_id; if (ToV8String(isolate, tls_channel_id.c_str(), &v8_tls_channel_id)) tls_channel_id_value = v8_tls_channel_id; } if (info.guest_process_id != content::ChildProcessHost::kInvalidUniqueID) { guest_process_id = v8::Integer::New(isolate, info.guest_process_id); guest_render_frame_routing_id = v8::Integer::New(isolate, info.guest_render_frame_routing_id); } } v8::Local<v8::String> v8_channel_name; v8::Local<v8::String> v8_source_id; v8::Local<v8::String> v8_target_extension_id; v8::Local<v8::String> v8_source_url_spec; if (!ToV8String(isolate, channel_name.c_str(), &v8_channel_name) || !ToV8String(isolate, info.source_id.c_str(), &v8_source_id) || !ToV8String(isolate, target_extension_id.c_str(), &v8_target_extension_id) || !ToV8String(isolate, source_url_spec.c_str(), &v8_source_url_spec)) { NOTREACHED() << "dispatchOnConnect() passed non-string argument"; return; } v8::Local<v8::Value> arguments[] = { // portId v8::Integer::New(isolate, target_port_id), // channelName v8_channel_name, // sourceTab tab, // source_frame_id v8::Integer::New(isolate, source->frame_id), // guestProcessId guest_process_id, // guestRenderFrameRoutingId guest_render_frame_routing_id, // sourceExtensionId v8_source_id, // targetExtensionId v8_target_extension_id, // sourceUrl v8_source_url_spec, // tlsChannelId tls_channel_id_value, }; v8::Local<v8::Value> retval = script_context->module_system()->CallModuleMethod( "messaging", "dispatchOnConnect", arraysize(arguments), arguments); if (!IsEmptyOrUndefied(retval)) { CHECK(retval->IsBoolean()); *port_created |= retval.As<v8::Boolean>()->Value(); } else { LOG(ERROR) << "Empty return value from dispatchOnConnect."; } } void DeliverMessageToScriptContext(const Message& message, int target_port_id, ScriptContext* script_context) { v8::Isolate* isolate = script_context->isolate(); v8::HandleScope handle_scope(isolate); // Check to see whether the context has this port before bothering to create // the message. v8::Local<v8::Value> port_id_handle = v8::Integer::New(isolate, target_port_id); v8::Local<v8::Value> has_port = script_context->module_system()->CallModuleMethod("messaging", "hasPort", 1, &port_id_handle); // Could be empty/undefined if an exception was thrown. // TODO(kalman): Should this be built into CallModuleMethod? if (IsEmptyOrUndefied(has_port)) return; CHECK(has_port->IsBoolean()); if (!has_port.As<v8::Boolean>()->Value()) return; v8::Local<v8::String> v8_data; if (!ToV8String(isolate, message.data.c_str(), &v8_data)) return; std::vector<v8::Local<v8::Value>> arguments; arguments.push_back(v8_data); arguments.push_back(port_id_handle); std::unique_ptr<blink::WebScopedUserGesture> web_user_gesture; std::unique_ptr<blink::WebScopedWindowFocusAllowedIndicator> allow_window_focus; if (message.user_gesture) { web_user_gesture.reset(new blink::WebScopedUserGesture); if (script_context->web_frame()) { blink::WebDocument document = script_context->web_frame()->document(); allow_window_focus.reset(new blink::WebScopedWindowFocusAllowedIndicator( &document)); } } script_context->module_system()->CallModuleMethod( "messaging", "dispatchOnMessage", &arguments); } void DispatchOnDisconnectToScriptContext(int port_id, const std::string& error_message, ScriptContext* script_context) { v8::Isolate* isolate = script_context->isolate(); v8::HandleScope handle_scope(isolate); std::vector<v8::Local<v8::Value>> arguments; arguments.push_back(v8::Integer::New(isolate, port_id)); v8::Local<v8::String> v8_error_message; if (!error_message.empty()) ToV8String(isolate, error_message.c_str(), &v8_error_message); if (!v8_error_message.IsEmpty()) { arguments.push_back(v8_error_message); } else { arguments.push_back(v8::Null(isolate)); } script_context->module_system()->CallModuleMethod( "messaging", "dispatchOnDisconnect", &arguments); } } // namespace ObjectBackedNativeHandler* MessagingBindings::Get(ScriptContext* context) { return new ExtensionImpl(context); } void MessagingBindings::ValidateMessagePort( const ScriptContextSet& context_set, int port_id, content::RenderFrame* render_frame) { int routing_id = render_frame->GetRoutingID(); bool has_port = false; context_set.ForEach(render_frame, base::Bind(&HasMessagePort, port_id, &has_port)); // Note: HasMessagePort invokes a JavaScript function. If the runtime of the // extension bindings in JS have been compromised, then |render_frame| may be // invalid at this point. // A reply is only sent if the port is missing, because the port is assumed to // exist unless stated otherwise. if (!has_port) { content::RenderThread::Get()->Send( new ExtensionHostMsg_CloseMessagePort(routing_id, port_id, false)); } } // static void MessagingBindings::DispatchOnConnect( const ScriptContextSet& context_set, int target_port_id, const std::string& channel_name, const ExtensionMsg_TabConnectionInfo& source, const ExtensionMsg_ExternalConnectionInfo& info, const std::string& tls_channel_id, content::RenderFrame* restrict_to_render_frame) { int routing_id = restrict_to_render_frame ? restrict_to_render_frame->GetRoutingID() : MSG_ROUTING_NONE; bool port_created = false; context_set.ForEach( info.target_id, restrict_to_render_frame, base::Bind(&DispatchOnConnectToScriptContext, target_port_id, channel_name, &source, info, tls_channel_id, &port_created)); // Note: |restrict_to_render_frame| may have been deleted at this point! if (port_created) { content::RenderThread::Get()->Send( new ExtensionHostMsg_OpenMessagePort(routing_id, target_port_id)); } else { content::RenderThread::Get()->Send(new ExtensionHostMsg_CloseMessagePort( routing_id, target_port_id, false)); } } // static void MessagingBindings::DeliverMessage( const ScriptContextSet& context_set, int target_port_id, const Message& message, content::RenderFrame* restrict_to_render_frame) { context_set.ForEach( restrict_to_render_frame, base::Bind(&DeliverMessageToScriptContext, message, target_port_id)); } // static void MessagingBindings::DispatchOnDisconnect( const ScriptContextSet& context_set, int port_id, const std::string& error_message, content::RenderFrame* restrict_to_render_frame) { context_set.ForEach( restrict_to_render_frame, base::Bind(&DispatchOnDisconnectToScriptContext, port_id, error_message)); } } // namespace extensions
37.425061
80
0.700039
[ "object", "vector" ]
03047a725c74261678f8a08fa09ef1796d6a8bf4
452
hpp
C++
include/CodeExecutor/Linker.hpp
Megaxela/CodeExecutor
4d4f4e6ffb298e250e04edb23a29bf90c3e0d43a
[ "MIT" ]
3
2020-05-22T09:24:30.000Z
2020-11-06T15:16:04.000Z
include/CodeExecutor/Linker.hpp
Megaxela/CodeExecutor
4d4f4e6ffb298e250e04edb23a29bf90c3e0d43a
[ "MIT" ]
null
null
null
include/CodeExecutor/Linker.hpp
Megaxela/CodeExecutor
4d4f4e6ffb298e250e04edb23a29bf90c3e0d43a
[ "MIT" ]
2
2020-05-12T03:28:11.000Z
2020-11-18T09:48:27.000Z
#pragma once #include <memory> #include "Library.hpp" #include "Object.hpp" namespace CodeExecutor { class Linker; using LinkerPtr = std::shared_ptr<Linker>; /** * @brief Class, that describes linker. */ class Linker { public: /** * @brief Virtual destructor. */ virtual ~Linker() = default; virtual LibraryPtr link(const std::vector<ObjectPtr>& objects) = 0; }; }
15.586207
75
0.577434
[ "object", "vector" ]