text
stringlengths
9
39.2M
dir
stringlengths
26
295
lang
stringclasses
185 values
created_date
timestamp[us]
updated_date
timestamp[us]
repo_name
stringlengths
1
97
repo_full_name
stringlengths
7
106
star
int64
1k
183k
len_tokens
int64
1
13.8M
```objective-c #pragma once #include "UnrealEd.h" #include "PyFbxFactory.generated.h" UCLASS(hidecategories = Object) class UPyFbxFactory : public UFbxFactory { GENERATED_BODY() UPyFbxFactory(const FObjectInitializer& ObjectInitializer); virtual bool ConfigureProperties() override; virtual void PostInitProperties() override; virtual UObject * FactoryCreateFile(UClass* InClass, UObject* InParent, FName InName, EObjectFlags Flags, const FString& Filename, const TCHAR* Parms, FFeedbackContext* Warn, bool& bOutOperationCanceled) override; virtual UObject * FactoryCreateBinary ( UClass * InClass, UObject * InParent, FName InName, EObjectFlags Flags, UObject * Context, const TCHAR * Type, const uint8 *& Buffer, const uint8 * BufferEnd, FFeedbackContext * Warn, bool & bOutOperationCanceled) override; }; ```
/content/code_sandbox/Source/PythonConsole/Public/PyFbxFactory.h
objective-c
2016-08-07T05:00:51
2024-08-14T06:32:20
UnrealEnginePython
20tab/UnrealEnginePython
2,715
207
```objective-c #pragma once #include "UnrealEd.h" #include "PythonScriptFactory.generated.h" UCLASS() class UPythonScriptFactory : public UFactory { GENERATED_UCLASS_BODY() public: virtual UObject* FactoryCreateFile(UClass * Class, UObject *InParent, FName InName, EObjectFlags Flags, const FString& Filename, const TCHAR* Parms, FFeedbackContext *Warn, bool& bOutOperationCanceled) override; }; ```
/content/code_sandbox/Source/PythonConsole/Public/PythonScriptFactory.h
objective-c
2016-08-07T05:00:51
2024-08-14T06:32:20
UnrealEnginePython
20tab/UnrealEnginePython
2,715
94
```objective-c #pragma once #include "UnrealEd.h" #include "PyFactory.generated.h" UCLASS() class UPyFactory : public UFactory { GENERATED_BODY() public: virtual UObject* FactoryCreateFile(UClass * Class, UObject *InParent, FName InName, EObjectFlags Flags, const FString& Filename, const TCHAR* Parms, FFeedbackContext *Warn, bool& bOutOperationCanceled) override { return PyFactoryCreateFile(Class, InParent, InName.ToString(), Filename); } virtual UObject* FactoryCreateNew(UClass * Class, UObject *InParent, FName InName, EObjectFlags Flags, UObject *Context, FFeedbackContext *Warn) override { return PyFactoryCreateNew(Class, InParent, InName.ToString()); } virtual UClass* ResolveSupportedClass() override { if (SupportedClass) return SupportedClass; return PyResolveSupportedClass(); } virtual FText GetDisplayName() const override { if (!PyDisplayName.IsEmpty()) { return FText::FromString(PyDisplayName); } return FText::FromString(GetClass()->GetName().Replace(UTF8_TO_TCHAR("Factory"), UTF8_TO_TCHAR(""))); } virtual FText GetToolTip() const override { if (!PyToolTip.IsEmpty()) { return FText::FromString(PyToolTip); } return GetDisplayName(); } UFUNCTION(BlueprintImplementableEvent) UObject* PyFactoryCreateFile(class UClass * Class, UObject *InParent, const FString & InName, const FString & Filename); UFUNCTION(BlueprintImplementableEvent) UObject* PyFactoryCreateNew(class UClass * Class, UObject *InParent, const FString & InName); UFUNCTION(BlueprintImplementableEvent) UClass* PyResolveSupportedClass(); UPROPERTY(BlueprintReadWrite, Category = "PyFactory") FString PyDisplayName; UPROPERTY(BlueprintReadWrite, Category = "PyFactory") FString PyToolTip; }; ```
/content/code_sandbox/Source/PythonConsole/Public/PyFactory.h
objective-c
2016-08-07T05:00:51
2024-08-14T06:32:20
UnrealEnginePython
20tab/UnrealEnginePython
2,715
392
```objective-c #pragma once #include "Runtime/Slate/Public/SlateBasics.h" /** Style of the debug console */ namespace EPythonConsoleStyle { enum Type { /** Shows the debug console input line with tab completion only */ Compact, /** Shows a scrollable log window with the input line on the bottom */ WithLog, }; }; struct FPythonConsoleDelegates { FSimpleDelegate OnFocusLost; FSimpleDelegate OnConsoleCommandExecuted; }; class FPythonConsoleModule : public IModuleInterface { public: virtual void StartupModule(); virtual void ShutdownModule(); /** Generates a console input box widget. Remember, this widget will become invalid if the output log DLL is unloaded on the fly. */ virtual TSharedRef< SWidget > MakeConsoleInputBox( TSharedPtr< SEditableTextBox >& OutExposedEditableTextBox ) const; private: /** Weak pointer to a debug console that's currently open, if any */ TWeakPtr< SWidget > PythonConsole; }; ```
/content/code_sandbox/Source/PythonConsole/Public/PythonConsoleModule.h
objective-c
2016-08-07T05:00:51
2024-08-14T06:32:20
UnrealEnginePython
20tab/UnrealEnginePython
2,715
217
```c++ #include "SPythonLog.h" #include "Runtime/Slate/Public/Widgets/Layout/SScrollBorder.h" #include "GameFramework/GameMode.h" #include "Engine/LocalPlayer.h" #include "GameFramework/GameState.h" #include "Runtime/Slate/Public/Widgets/Input/SSearchBox.h" #include "Runtime/Launch/Resources/Version.h" #include "Runtime/Slate/Public/Framework/Text/SlateTextLayout.h" #include "Editor/EditorStyle/Public/Classes/EditorStyleSettings.h" #include "SlateBasics.h" #include "EditorStyle.h" #define LOCTEXT_NAMESPACE "PythonConsole" /** Custom console editable text box whose only purpose is to prevent some keys from being typed */ class SPythonConsoleEditableTextBox : public SEditableTextBox { public: SLATE_BEGIN_ARGS(SPythonConsoleEditableTextBox) {} /** Hint text that appears when there is no text in the text box */ SLATE_ATTRIBUTE(FText, HintText) /** Called whenever the text is changed interactively by the user */ SLATE_EVENT(FOnTextChanged, OnTextChanged) /** Called whenever the text is committed. This happens when the user presses enter or the text box loses focus. */ SLATE_EVENT(FOnTextCommitted, OnTextCommitted) SLATE_END_ARGS() void Construct(const FArguments& InArgs) { SetStyle(&FCoreStyle::Get().GetWidgetStyle< FEditableTextBoxStyle >("NormalEditableTextBox")); SBorder::Construct(SBorder::FArguments() .BorderImage(this, &SPythonConsoleEditableTextBox::GetConsoleBorder) .BorderBackgroundColor(Style->BackgroundColor) .ForegroundColor(Style->ForegroundColor) .Padding(Style->Padding) [ SAssignNew(EditableText, SPythonConsoleEditableText) .HintText(InArgs._HintText) .OnTextChanged(InArgs._OnTextChanged) .OnTextCommitted(InArgs._OnTextCommitted) ]); } void SetPythonBox(SPythonConsoleInputBox *box) { SPythonConsoleEditableText *PythonEditableText = (SPythonConsoleEditableText *)EditableText.Get(); box->HistoryPosition = 0; PythonEditableText->PythonConsoleInputBox = box; } private: class SPythonConsoleEditableText : public SEditableText { public: SPythonConsoleInputBox *PythonConsoleInputBox; SLATE_BEGIN_ARGS(SPythonConsoleEditableText) {} /** The text that appears when there is nothing typed into the search box */ SLATE_ATTRIBUTE(FText, HintText) /** Called whenever the text is changed interactively by the user */ SLATE_EVENT(FOnTextChanged, OnTextChanged) /** Called whenever the text is committed. This happens when the user presses enter or the text box loses focus. */ SLATE_EVENT(FOnTextCommitted, OnTextCommitted) SLATE_END_ARGS() void Construct(const FArguments& InArgs) { SEditableText::Construct ( SEditableText::FArguments() .HintText(InArgs._HintText) .OnTextChanged(InArgs._OnTextChanged) .OnTextCommitted(InArgs._OnTextCommitted) .ClearKeyboardFocusOnCommit(false) .IsCaretMovedWhenGainFocus(false) .MinDesiredWidth(400.0f) ); } virtual FReply OnKeyDown(const FGeometry& MyGeometry, const FKeyEvent& InKeyEvent) { // Special case handling. Intercept the tilde key. It is not suitable for typing in the console if (InKeyEvent.GetKey() == EKeys::Tilde) { return FReply::Unhandled(); } else if (InKeyEvent.GetKey() == EKeys::Up) { if (PythonConsoleInputBox->HistoryPosition > 0) { PythonConsoleInputBox->HistoryPosition--; this->SetText(FText::FromString(PythonConsoleInputBox->History[PythonConsoleInputBox->HistoryPosition])); } return FReply::Handled(); } else if (InKeyEvent.GetKey() == EKeys::Down) { if (PythonConsoleInputBox->HistoryPosition < PythonConsoleInputBox->History.Num() - 1) { PythonConsoleInputBox->HistoryPosition++; this->SetText(FText::FromString(PythonConsoleInputBox->History[PythonConsoleInputBox->HistoryPosition])); } return FReply::Handled(); } else { return SEditableText::OnKeyDown(MyGeometry, InKeyEvent); } } virtual FReply OnKeyChar(const FGeometry& MyGeometry, const FCharacterEvent& InCharacterEvent) { // Special case handling. Intercept the tilde key. It is not suitable for typing in the console if (InCharacterEvent.GetCharacter() != 0x60) { return SEditableText::OnKeyChar(MyGeometry, InCharacterEvent); } else { return FReply::Unhandled(); } } }; /** @return Border image for the text box based on the hovered and focused state */ const FSlateBrush* GetConsoleBorder() const { if (EditableText->HasKeyboardFocus()) { return &Style->BackgroundImageFocused; } else { if (EditableText->IsHovered()) { return &Style->BackgroundImageHovered; } else { return &Style->BackgroundImageNormal; } } } }; SPythonConsoleInputBox::SPythonConsoleInputBox() : bIgnoreUIUpdate(false) { FScopePythonGIL gil; } BEGIN_SLATE_FUNCTION_BUILD_OPTIMIZATION void SPythonConsoleInputBox::Construct(const FArguments& InArgs) { OnConsoleCommandExecuted = InArgs._OnConsoleCommandExecuted; ChildSlot [ SAssignNew(InputText, SPythonConsoleEditableTextBox) .OnTextCommitted(this, &SPythonConsoleInputBox::OnTextCommitted) .HintText(NSLOCTEXT("PythonConsole", "TypeInConsoleHint", "Enter python command")) ]; SPythonConsoleEditableTextBox *TextBox = (SPythonConsoleEditableTextBox *)InputText.Get(); TextBox->SetPythonBox(this); IsMultiline = false; } void SPythonConsoleInputBox::Tick(const FGeometry& AllottedGeometry, const double InCurrentTime, const float InDeltaTime) { if (!GIntraFrameDebuggingGameThread && !IsEnabled()) { SetEnabled(true); } else if (GIntraFrameDebuggingGameThread && IsEnabled()) { SetEnabled(false); } } void SPythonConsoleInputBox::OnTextCommitted(const FText& InText, ETextCommit::Type CommitInfo) { if (CommitInfo == ETextCommit::OnEnter) { if (!InText.IsEmpty()) { // Copy the exec text string out so we can clear the widget's contents. If the exec command spawns // a new window it can cause the text box to lose focus, which will result in this function being // re-entered. We want to make sure the text string is empty on re-entry, so we'll clear it out const FString ExecString = InText.ToString(); this->History.Add(ExecString); this->HistoryPosition = this->History.Num(); if (IsMultiline) { UE_LOG(LogTemp, Log, TEXT("... %s"), *ExecString); } else { UE_LOG(LogTemp, Log, TEXT(">>> %s"), *ExecString); } // Clear the console input area bIgnoreUIUpdate = true; InputText->SetText(FText::GetEmpty()); bIgnoreUIUpdate = false; // Here run the python code // FUnrealEnginePythonModule &PythonModule = FModuleManager::GetModuleChecked<FUnrealEnginePythonModule>("UnrealEnginePython"); if (IsMultiline) { if (ExecString.StartsWith(" ")) { MultilineString += FString("\n") + ExecString; } else { IsMultiline = false; PythonModule.RunString(TCHAR_TO_UTF8(*MultilineString)); } } else if (ExecString.EndsWith(":")) { IsMultiline = true; MultilineString = ExecString; } else { PythonModule.RunString(TCHAR_TO_UTF8(*ExecString)); } } else if (IsMultiline) { IsMultiline = false; FUnrealEnginePythonModule &PythonModule = FModuleManager::GetModuleChecked<FUnrealEnginePythonModule>("UnrealEnginePython"); PythonModule.RunString(TCHAR_TO_UTF8(*MultilineString)); } } OnConsoleCommandExecuted.ExecuteIfBound(); } TSharedRef< FPythonLogTextLayoutMarshaller > FPythonLogTextLayoutMarshaller::Create(TArray< TSharedPtr<FLogMessage> > InMessages) { return MakeShareable(new FPythonLogTextLayoutMarshaller(MoveTemp(InMessages))); } FPythonLogTextLayoutMarshaller::~FPythonLogTextLayoutMarshaller() { } void FPythonLogTextLayoutMarshaller::SetText(const FString& SourceString, FTextLayout& TargetTextLayout) { TextLayout = &TargetTextLayout; AppendMessagesToTextLayout(Messages); } void FPythonLogTextLayoutMarshaller::GetText(FString& TargetString, const FTextLayout& SourceTextLayout) { SourceTextLayout.GetAsText(TargetString); } bool FPythonLogTextLayoutMarshaller::AppendMessage(const TCHAR* InText, const ELogVerbosity::Type InVerbosity, const FName& InCategory) { TArray< TSharedPtr<FLogMessage> > NewMessages; if (SPythonLog::CreateLogMessages(InText, InVerbosity, InCategory, NewMessages)) { const bool bWasEmpty = Messages.Num() == 0; Messages.Append(NewMessages); if (TextLayout) { // If we were previously empty, then we'd have inserted a dummy empty line into the document // We need to remove this line now as it would cause the message indices to get out-of-sync with the line numbers, which would break auto-scrolling if (bWasEmpty) { TextLayout->ClearLines(); } // If we've already been given a text layout, then append these new messages rather than force a refresh of the entire document AppendMessagesToTextLayout(NewMessages); } else { MakeDirty(); } return true; } return false; } void FPythonLogTextLayoutMarshaller::AppendMessageToTextLayout(const TSharedPtr<FLogMessage>& InMessage) { const FTextBlockStyle& MessageTextStyle = FEditorStyle::Get().GetWidgetStyle<FTextBlockStyle>(InMessage->Style); TSharedRef<FString> LineText = InMessage->Message; TArray<TSharedRef<IRun>> Runs; Runs.Add(FSlateTextRun::Create(FRunInfo(), LineText, MessageTextStyle)); TextLayout->AddLine(FSlateTextLayout::FNewLineData(MoveTemp(LineText), MoveTemp(Runs))); } void FPythonLogTextLayoutMarshaller::AppendMessagesToTextLayout(const TArray<TSharedPtr<FLogMessage>>& InMessages) { TArray<FTextLayout::FNewLineData> LinesToAdd; LinesToAdd.Reserve(InMessages.Num()); for (const auto& CurrentMessage : InMessages) { const FTextBlockStyle& MessageTextStyle = FEditorStyle::Get().GetWidgetStyle<FTextBlockStyle>(CurrentMessage->Style); TSharedRef<FString> LineText = CurrentMessage->Message; TArray<TSharedRef<IRun>> Runs; Runs.Add(FSlateTextRun::Create(FRunInfo(), LineText, MessageTextStyle)); LinesToAdd.Emplace(MoveTemp(LineText), MoveTemp(Runs)); } TextLayout->AddLines(LinesToAdd); } void FPythonLogTextLayoutMarshaller::ClearMessages() { Messages.Empty(); MakeDirty(); } int32 FPythonLogTextLayoutMarshaller::GetNumMessages() const { return Messages.Num(); } FPythonLogTextLayoutMarshaller::FPythonLogTextLayoutMarshaller(TArray< TSharedPtr<FLogMessage> > InMessages) : Messages(MoveTemp(InMessages)) , TextLayout(nullptr) { } BEGIN_SLATE_FUNCTION_BUILD_OPTIMIZATION void SPythonLog::Construct(const FArguments& InArgs) { #if ENGINE_MINOR_VERSION < 18 MessagesTextMarshaller = FPythonLogTextLayoutMarshaller::Create(MoveTemp(InArgs._Messages)); #else MessagesTextMarshaller = FPythonLogTextLayoutMarshaller::Create(InArgs._Messages); #endif MessagesTextBox = SNew(SMultiLineEditableTextBox) .Style(FEditorStyle::Get(), "Log.TextBox") .TextStyle(FEditorStyle::Get(), "Log.Normal") .ForegroundColor(FLinearColor::Gray) .Marshaller(MessagesTextMarshaller) .IsReadOnly(true) .AlwaysShowScrollbars(true) .OnVScrollBarUserScrolled(this, &SPythonLog::OnUserScrolled) .ContextMenuExtender(this, &SPythonLog::ExtendTextBoxMenu); ChildSlot [ SNew(SVerticalBox) // Console output and filters + SVerticalBox::Slot() [ SNew(SBorder) .Padding(3) .BorderImage(FEditorStyle::GetBrush("ToolPanel.GroupBorder")) [ SNew(SVerticalBox) // Output log area + SVerticalBox::Slot() .FillHeight(1) [ MessagesTextBox.ToSharedRef() ] ] ] // The console input box + SVerticalBox::Slot() .AutoHeight() .Padding(FMargin(0.0f, 4.0f, 0.0f, 0.0f)) [ SNew(SPythonConsoleInputBox) .OnConsoleCommandExecuted(this, &SPythonLog::OnConsoleCommandExecuted) ]]; GLog->AddOutputDevice(this); bIsUserScrolled = false; RequestForceScroll(); } END_SLATE_FUNCTION_BUILD_OPTIMIZATION SPythonLog::~SPythonLog() { if (GLog != NULL) { GLog->RemoveOutputDevice(this); } } bool SPythonLog::CreateLogMessages(const TCHAR* V, ELogVerbosity::Type Verbosity, const class FName& Category, TArray< TSharedPtr<FLogMessage> >& OutMessages) { if (Verbosity == ELogVerbosity::SetColor) { // Skip Color Events return false; } else { FName Style; if (Category == NAME_Cmd) { Style = FName(TEXT("Log.Command")); } else if (Verbosity == ELogVerbosity::Error) { Style = FName(TEXT("Log.Error")); } else if (Verbosity == ELogVerbosity::Warning) { Style = FName(TEXT("Log.Warning")); } else { Style = FName(TEXT("Log.Normal")); } // Determine how to format timestamps static ELogTimes::Type LogTimestampMode = ELogTimes::None; if (UObjectInitialized() && !GExitPurge) { // Logging can happen very late during shutdown, even after the UObject system has been torn down, hence the init check above LogTimestampMode = GetDefault<UEditorStyleSettings>()->LogTimestampMode; } const int32 OldNumMessages = OutMessages.Num(); // handle multiline strings by breaking them apart by line TArray<FTextRange> LineRanges; FString CurrentLogDump = V; FTextRange::CalculateLineRangesFromString(CurrentLogDump, LineRanges); bool bIsFirstLineInMessage = true; for (const FTextRange& LineRange : LineRanges) { if (!LineRange.IsEmpty()) { FString Line = CurrentLogDump.Mid(LineRange.BeginIndex, LineRange.Len()); Line = Line.ConvertTabsToSpaces(4); OutMessages.Add(MakeShareable(new FLogMessage(MakeShareable(new FString(Line)), Style))); bIsFirstLineInMessage = false; } } return OldNumMessages != OutMessages.Num(); } } void SPythonLog::Serialize(const TCHAR* V, ELogVerbosity::Type Verbosity, const class FName& Category) { //UE_LOG(LogTemp, Warning, TEXT("%s"), Category.ToString()) if (MessagesTextMarshaller->AppendMessage(V, Verbosity, Category)) { // Don't scroll to the bottom automatically when the user is scrolling the view or has scrolled it away from the bottom. if (!bIsUserScrolled) { MessagesTextBox->ScrollTo(FTextLocation(MessagesTextMarshaller->GetNumMessages() - 1)); } } } void SPythonLog::ExtendTextBoxMenu(FMenuBuilder& Builder) { FUIAction ClearPythonLogAction( FExecuteAction::CreateRaw(this, &SPythonLog::OnClearLog), FCanExecuteAction::CreateSP(this, &SPythonLog::CanClearLog) ); Builder.AddMenuEntry( NSLOCTEXT("PythonConsole", "ClearLogLabel", "Clear Log"), NSLOCTEXT("PythonConsole", "ClearLogTooltip", "Clears all log messages"), FSlateIcon(), ClearPythonLogAction ); } void SPythonLog::OnClearLog() { // Make sure the cursor is back at the start of the log before we clear it MessagesTextBox->GoTo(FTextLocation(0)); MessagesTextMarshaller->ClearMessages(); MessagesTextBox->Refresh(); bIsUserScrolled = false; } void SPythonLog::OnUserScrolled(float ScrollOffset) { bIsUserScrolled = !FMath::IsNearlyEqual(ScrollOffset, 1.0f); } bool SPythonLog::CanClearLog() const { return MessagesTextMarshaller->GetNumMessages() > 0; } void SPythonLog::OnConsoleCommandExecuted() { RequestForceScroll(); } void SPythonLog::RequestForceScroll() { if (MessagesTextMarshaller->GetNumMessages() > 0) { MessagesTextBox->ScrollTo(FTextLocation(MessagesTextMarshaller->GetNumMessages() - 1)); bIsUserScrolled = false; } } #undef LOCTEXT_NAMESPACE ```
/content/code_sandbox/Source/PythonConsole/Private/SPythonLog.cpp
c++
2016-08-07T05:00:51
2024-08-14T06:32:20
UnrealEnginePython
20tab/UnrealEnginePython
2,715
4,125
```objective-c #pragma once #include "Runtime/SlateCore/Public/SlateCore.h" #include "EditorStyle.h" #include "PythonConsoleModule.h" /** * Debug console widget, designed to be summoned on top of a viewport or window */ class SPythonConsole : public SCompoundWidget { public: SLATE_BEGIN_ARGS(SPythonConsole) { } SLATE_END_ARGS() /** Constructs this widget */ void Construct(const FArguments& InArgs, const EPythonConsoleStyle::Type InStyle, FPythonConsoleModule* PythonConsoleModule, const FPythonConsoleDelegates* PythonConsoleDelegates); /** Call to set focus to this debug console's editable text box */ void SetFocusToEditableText(); /** Default constructor */ SPythonConsole(); protected: /** Returns EVisibility::Visible if style has log being shown, otherwise VIS_COLLAPSED */ EVisibility MakeVisibleIfLogIsShown() const; /** Returns a color and opacity value to use based on any current animation */ FLinearColor GetAnimatedColorAndOpacity() const; /** Returns a Slate color based on any current animation (same color as GetAnimatedColorAndOpacity) */ FSlateColor GetAnimatedSlateColor() const; FSlateColor GetFlashColor() const; private: /** Editable text box for this debug console's input line */ TSharedPtr< SEditableTextBox > EditableTextBox; /** Current style of the debug console. Can be changed on the fly. */ EPythonConsoleStyle::Type CurrentStyle; /** Intro/outro animation curve */ FCurveSequence AnimCurveSequence; FCurveHandle AnimCurve; FCurveHandle FlashCurve; }; ```
/content/code_sandbox/Source/PythonConsole/Private/SPythonConsole.h
objective-c
2016-08-07T05:00:51
2024-08-14T06:32:20
UnrealEnginePython
20tab/UnrealEnginePython
2,715
350
```c++ #include "PyFbxFactory.h" #include "FbxMeshUtils.h" #include "Runtime/Launch/Resources/Version.h" UPyFbxFactory::UPyFbxFactory(const FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer) { // disable automatic detection of the factory ImportPriority = -1; } bool UPyFbxFactory::ConfigureProperties() { bDetectImportTypeOnImport = false; bShowOption = false; return true; } void UPyFbxFactory::PostInitProperties() { Super::PostInitProperties(); ImportUI->MeshTypeToImport = FBXIT_MAX; } UObject * UPyFbxFactory::FactoryCreateFile(UClass* InClass, UObject* InParent, FName InName, EObjectFlags Flags, const FString& Filename, const TCHAR* Parms, FFeedbackContext* Warn, bool& bOutOperationCanceled) { #if ENGINE_MINOR_VERSION >= 20 if (ImportUI->MeshTypeToImport == FBXIT_MAX) { if (!DetectImportType(UFactory::CurrentFilename)) { return nullptr; } } FbxMeshUtils::SetImportOption(ImportUI); // ensure auto-detect is skipped bDetectImportTypeOnImport = false; #endif return Super::FactoryCreateFile(InClass, InParent, InName, Flags, Filename, Parms, Warn, bOutOperationCanceled); } UObject *UPyFbxFactory::FactoryCreateBinary ( UClass * InClass, UObject * InParent, FName InName, EObjectFlags Flags, UObject * Context, const TCHAR * Type, const uint8 *& Buffer, const uint8 * BufferEnd, FFeedbackContext * Warn, bool & bOutOperationCanceled) { if (ImportUI->MeshTypeToImport == FBXIT_MAX) { if (!DetectImportType(UFactory::CurrentFilename)) { return nullptr; } } FbxMeshUtils::SetImportOption(ImportUI); // ensure auto-detect is skipped bDetectImportTypeOnImport = false; return Super::FactoryCreateBinary(InClass, InParent, InName, Flags, Context, Type, Buffer, BufferEnd, Warn, bOutOperationCanceled); } ```
/content/code_sandbox/Source/PythonConsole/Private/PyFbxFactory.cpp
c++
2016-08-07T05:00:51
2024-08-14T06:32:20
UnrealEnginePython
20tab/UnrealEnginePython
2,715
478
```c++ #include "SPythonConsole.h" #include "PythonConsoleModule.h" #include "SPythonConsole.h" #include "SPythonLog.h" namespace PythonConsoleDefs { // How many seconds to animate when console is summoned static const float IntroAnimationDuration = 0.25f; } BEGIN_SLATE_FUNCTION_BUILD_OPTIMIZATION void SPythonConsole::Construct( const FArguments& InArgs, const EPythonConsoleStyle::Type InStyle, FPythonConsoleModule* PythonConsoleModule, const FPythonConsoleDelegates* PythonConsoleDelegates ) { CurrentStyle = InStyle; TSharedPtr<SPythonConsoleInputBox> ConsoleInputBox; check( PythonConsoleModule != NULL ); ChildSlot [ SNew( SVerticalBox ) +SVerticalBox::Slot() .AutoHeight() [ SNew( SVerticalBox ) .Visibility( this, &SPythonConsole::MakeVisibleIfLogIsShown ) +SVerticalBox::Slot() .AutoHeight() .Padding( 10.0f ) [ SNew(SBox) .HeightOverride( 200.0f ) [ SNew( SBorder ) .BorderImage( FEditorStyle::GetBrush( "ToolPanel.GroupBorder" ) ) .ColorAndOpacity( this, &SPythonConsole::GetAnimatedColorAndOpacity ) .BorderBackgroundColor( this, &SPythonConsole::GetAnimatedSlateColor ) [ SNew( SSpacer ) ] ] ] ] +SVerticalBox::Slot() .AutoHeight() .Padding( 10.0f ) [ SNew(SBox) .HeightOverride( 26.0f ) .HAlign( HAlign_Left ) [ SNew( SBorder ) .Padding( FMargin(2) ) .BorderImage( FEditorStyle::GetBrush( "PythonConsole.Background" ) ) .ColorAndOpacity( this, &SPythonConsole::GetAnimatedColorAndOpacity ) .BorderBackgroundColor( this, &SPythonConsole::GetAnimatedSlateColor ) [ SNew(SHorizontalBox) + SHorizontalBox::Slot() .AutoWidth() .Padding(3.0f) .VAlign(VAlign_Center) [ SNew(STextBlock) .Text(NSLOCTEXT("Console", "ConsoleLabel", "Console")) ] + SHorizontalBox::Slot() .Padding(5.0f, 2.0f) .VAlign(VAlign_Center) .MaxWidth(400.0f) [ SAssignNew(ConsoleInputBox, SPythonConsoleInputBox) .OnConsoleCommandExecuted(PythonConsoleDelegates->OnConsoleCommandExecuted) ] ] ] ] ]; EditableTextBox = ConsoleInputBox->GetEditableTextBox(); // Kick off intro animation AnimCurveSequence = FCurveSequence(); AnimCurve = AnimCurveSequence.AddCurve( 0.0f, PythonConsoleDefs::IntroAnimationDuration, ECurveEaseFunction::QuadOut ); FlashCurve = AnimCurveSequence.AddCurve( PythonConsoleDefs::IntroAnimationDuration, .15f, ECurveEaseFunction::QuadInOut ); AnimCurveSequence.Play(this->AsShared()); } END_SLATE_FUNCTION_BUILD_OPTIMIZATION SPythonConsole::SPythonConsole() : CurrentStyle( EPythonConsoleStyle::Compact ) { } void SPythonConsole::SetFocusToEditableText() { FSlateApplication::Get().SetKeyboardFocus( EditableTextBox.ToSharedRef(), EFocusCause::SetDirectly ); } EVisibility SPythonConsole::MakeVisibleIfLogIsShown() const { return CurrentStyle == EPythonConsoleStyle::WithLog ? EVisibility::Visible : EVisibility::Collapsed; } FLinearColor SPythonConsole::GetAnimatedColorAndOpacity() const { return FLinearColor( 1.0f, 1.0f, 1.0f, AnimCurve.GetLerp() ); } FSlateColor SPythonConsole::GetAnimatedSlateColor() const { return FSlateColor( GetAnimatedColorAndOpacity() ); } FSlateColor SPythonConsole::GetFlashColor() const { float FlashAlpha = 1.0f - FlashCurve.GetLerp(); if (FlashAlpha == 1.0f) { FlashAlpha = 0.0f; } return FLinearColor(1,1,1,FlashAlpha); } ```
/content/code_sandbox/Source/PythonConsole/Private/SPythonConsole.cpp
c++
2016-08-07T05:00:51
2024-08-14T06:32:20
UnrealEnginePython
20tab/UnrealEnginePython
2,715
985
```c++ #include "PythonScriptFactory.h" #include "PythonScript.h" UPythonScriptFactory::UPythonScriptFactory(const FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer) { Formats.Add(FString("py;Python Script")); bCreateNew = false; bEditAfterNew = true; bEditorImport = true; SupportedClass = UPythonScript::StaticClass(); } UObject* UPythonScriptFactory::FactoryCreateFile(UClass * Class, UObject *InParent, FName InName, EObjectFlags Flags, const FString& Filename, const TCHAR* Parms, FFeedbackContext *Warn, bool& bOutOperationCanceled) { UPythonScript *NewAsset = NewObject<UPythonScript>(InParent, Class, InName, Flags); NewAsset->ScriptPath = Filename; bOutOperationCanceled = false; return NewAsset; } ```
/content/code_sandbox/Source/PythonConsole/Private/PythonScriptFactory.cpp
c++
2016-08-07T05:00:51
2024-08-14T06:32:20
UnrealEnginePython
20tab/UnrealEnginePython
2,715
180
```c++ #include "PythonConsoleModule.h" #include "SPythonConsole.h" #include "SPythonLog.h" #include "Editor/WorkspaceMenuStructure/Public/WorkspaceMenuStructureModule.h" #include "Runtime/Slate/Public/Widgets/Docking/SDockTab.h" #include "Editor/WorkspaceMenuStructure/Public/WorkspaceMenuStructure.h" IMPLEMENT_MODULE( FPythonConsoleModule, PythonConsole ); namespace PythonConsoleModule { static const FName PythonLogTabName = FName(TEXT("PythonLog")); } /** This class is to capture all log output even if the log window is closed */ class FPythonLogHistory : public FOutputDevice { public: FPythonLogHistory() { GLog->AddOutputDevice(this); GLog->SerializeBacklog(this); } ~FPythonLogHistory() { // At shutdown, GLog may already be null if( GLog != NULL ) { GLog->RemoveOutputDevice(this); } } /** Gets all captured messages */ const TArray< TSharedPtr<FLogMessage> >& GetMessages() const { return Messages; } protected: virtual void Serialize( const TCHAR* V, ELogVerbosity::Type Verbosity, const class FName& Category ) override { // Capture all incoming messages and store them in history SPythonLog::CreateLogMessages(V, Verbosity, Category, Messages); } private: /** All log messsges since this module has been started */ TArray< TSharedPtr<FLogMessage> > Messages; }; /** Our global output log app spawner */ static TSharedPtr<FPythonLogHistory> PythonLogHistory; TSharedRef<SDockTab> SpawnPythonLog( const FSpawnTabArgs& Args ) { return SNew(SDockTab) .Icon(FEditorStyle::GetBrush("Log.TabIcon")) .TabRole( ETabRole::NomadTab ) .Label( NSLOCTEXT("PythonConsole", "TabTitle", "Python Console") ) [ SNew(SPythonLog).Messages( PythonLogHistory->GetMessages() ) ]; } void FPythonConsoleModule::StartupModule() { FGlobalTabmanager::Get()->RegisterNomadTabSpawner(PythonConsoleModule::PythonLogTabName, FOnSpawnTab::CreateStatic( &SpawnPythonLog ) ) .SetDisplayName(NSLOCTEXT("UnrealEditor", "PythonLogTab", "Python Console")) .SetTooltipText(NSLOCTEXT("UnrealEditor", "PythonLogTooltipText", "Open the Python Console tab.")) .SetGroup( WorkspaceMenu::GetMenuStructure().GetDeveloperToolsLogCategory() ) .SetIcon( FSlateIcon(FEditorStyle::GetStyleSetName(), "Log.TabIcon") ); PythonLogHistory = MakeShareable(new FPythonLogHistory); } void FPythonConsoleModule::ShutdownModule() { if (FSlateApplication::IsInitialized()) { FGlobalTabmanager::Get()->UnregisterNomadTabSpawner(PythonConsoleModule::PythonLogTabName); } } TSharedRef< SWidget > FPythonConsoleModule::MakeConsoleInputBox( TSharedPtr< SEditableTextBox >& OutExposedEditableTextBox ) const { TSharedRef< SPythonConsoleInputBox > NewConsoleInputBox = SNew( SPythonConsoleInputBox ); OutExposedEditableTextBox = NewConsoleInputBox->GetEditableTextBox(); return NewConsoleInputBox; } ```
/content/code_sandbox/Source/PythonConsole/Private/PythonConsoleModule.cpp
c++
2016-08-07T05:00:51
2024-08-14T06:32:20
UnrealEnginePython
20tab/UnrealEnginePython
2,715
729
```objective-c #pragma once #include "Runtime/Slate/Public/Framework/Text/BaseTextLayoutMarshaller.h" #include "Runtime/Core/Public/Misc/TextFilterExpressionEvaluator.h" #include "Runtime/SlateCore/Public/SlateCore.h" #include "UnrealEnginePython.h" #include "Runtime/Slate/Public/Widgets/Input/SMultiLineEditableTextBox.h" #include "Runtime/Slate/Public/Widgets/Input/SEditableTextBox.h" class FPythonLogTextLayoutMarshaller; class SSearchBox; /** * A single log message for the output log, holding a message and * a style, for color and bolding of the message. */ struct FLogMessage { TSharedRef<FString> Message; FName Style; FLogMessage(const TSharedRef<FString>& NewMessage, FName NewStyle = NAME_None) : Message(NewMessage) , Style(NewStyle) { } }; /** * Console input box with command-completion support */ class SPythonConsoleInputBox : public SCompoundWidget { public: SLATE_BEGIN_ARGS(SPythonConsoleInputBox) {} /** Called when a console command is executed */ SLATE_EVENT( FSimpleDelegate, OnConsoleCommandExecuted ) SLATE_END_ARGS() /** Protected console input box widget constructor, called by Slate */ SPythonConsoleInputBox(); /** * Construct this widget. Called by the SNew() Slate macro. * * @param InArgs Declaration used by the SNew() macro to construct this widget */ void Construct( const FArguments& InArgs ); /** Returns the editable text box associated with this widget. Used to set focus directly. */ TSharedRef< SEditableTextBox > GetEditableTextBox() { return InputText.ToSharedRef(); } /** SWidget interface */ virtual void Tick( const FGeometry& AllottedGeometry, const double InCurrentTime, const float InDeltaTime ) override; TArray<FString> History; int HistoryPosition; FString MultilineString; bool IsMultiline; protected: virtual bool SupportsKeyboardFocus() const override { return true; } /** Handles entering in a command */ void OnTextCommitted(const FText& InText, ETextCommit::Type CommitInfo); private: /** Editable text widget */ TSharedPtr< SEditableTextBox > InputText; /** Delegate to call when a console command is executed */ FSimpleDelegate OnConsoleCommandExecuted; /** to prevent recursive calls in UI callback */ bool bIgnoreUIUpdate; }; /** * Widget which holds a list view of logs of the program output * as well as a combo box for entering in new commands */ class SPythonLog : public SCompoundWidget, public FOutputDevice { public: SLATE_BEGIN_ARGS( SPythonLog ) : _Messages() {} /** All messages captured before this log window has been created */ SLATE_ARGUMENT( TArray< TSharedPtr<FLogMessage> >, Messages ) SLATE_END_ARGS() /** Destructor for output log, so we can unregister from notifications */ ~SPythonLog(); /** * Construct this widget. Called by the SNew() Slate macro. * * @param InArgs Declaration used by the SNew() macro to construct this widget */ void Construct( const FArguments& InArgs ); /** * Creates FLogMessage objects from FOutputDevice log callback * * @param V Message text * @param Verbosity Message verbosity * @param Category Message category * @param OutMessages Array to receive created FLogMessage messages * @param Filters [Optional] Filters to apply to Messages * * @return true if any messages have been created, false otherwise */ static bool CreateLogMessages(const TCHAR* V, ELogVerbosity::Type Verbosity, const class FName& Category, TArray< TSharedPtr<FLogMessage> >& OutMessages); protected: virtual void Serialize( const TCHAR* V, ELogVerbosity::Type Verbosity, const class FName& Category ) override; protected: /** * Extends the context menu used by the text box */ void ExtendTextBoxMenu(FMenuBuilder& Builder); /** * Called when delete all is selected */ void OnClearLog(); /** * Called when the user scrolls the log window vertically */ void OnUserScrolled(float ScrollOffset); /** * Called to determine whether delete all is currently a valid command */ bool CanClearLog() const; /** Called when a console command is entered for this output log */ void OnConsoleCommandExecuted(); /** Request we immediately force scroll to the bottom of the log */ void RequestForceScroll(); /** Converts the array of messages into something the text box understands */ TSharedPtr< FPythonLogTextLayoutMarshaller > MessagesTextMarshaller; /** The editable text showing all log messages */ TSharedPtr< SMultiLineEditableTextBox > MessagesTextBox; /** True if the user has scrolled the window upwards */ bool bIsUserScrolled; }; /** Output log text marshaller to convert an array of FLogMessages into styled lines to be consumed by an FTextLayout */ class FPythonLogTextLayoutMarshaller : public FBaseTextLayoutMarshaller { public: static TSharedRef< FPythonLogTextLayoutMarshaller > Create(TArray< TSharedPtr<FLogMessage> > InMessages); virtual ~FPythonLogTextLayoutMarshaller(); // ITextLayoutMarshaller virtual void SetText(const FString& SourceString, FTextLayout& TargetTextLayout) override; virtual void GetText(FString& TargetString, const FTextLayout& SourceTextLayout) override; bool AppendMessage(const TCHAR* InText, const ELogVerbosity::Type InVerbosity, const FName& InCategory); void ClearMessages(); int32 GetNumMessages() const; protected: FPythonLogTextLayoutMarshaller(TArray< TSharedPtr<FLogMessage> > InMessages); void AppendMessageToTextLayout(const TSharedPtr<FLogMessage>& InMessage); void AppendMessagesToTextLayout(const TArray<TSharedPtr<FLogMessage>>& InMessages); /** All log messages to show in the text box */ TArray< TSharedPtr<FLogMessage> > Messages; /** Holds cached numbers of messages to avoid unnecessary re-filtering */ int32 CachedNumMessages; /** Flag indicating the messages count cache needs rebuilding */ bool bNumMessagesCacheDirty; FTextLayout* TextLayout; }; ```
/content/code_sandbox/Source/PythonConsole/Private/SPythonLog.h
objective-c
2016-08-07T05:00:51
2024-08-14T06:32:20
UnrealEnginePython
20tab/UnrealEnginePython
2,715
1,369
```smalltalk using UnrealBuildTool; using System.IO; using System.Collections.Generic; public class UnrealEnginePython : ModuleRules { // leave this string as empty for triggering auto-discovery of python installations... private string pythonHome = ""; // otherwise specify the path of your python installation //private string pythonHome = "C:/Program Files/Python36"; // this is an example for Homebrew on Mac //private string pythonHome = "/usr/local/Cellar/python3/3.6.0/Frameworks/Python.framework/Versions/3.6/"; // on Linux an include;libs syntax is expected: //private string pythonHome = "/usr/local/include/python3.6;/usr/local/lib/libpython3.6.so"; private string[] windowsKnownPaths = { // "C:/Program Files/Python37", "C:/Program Files/Python36", "C:/Program Files/Python35", "C:/Python27", "C:/IntelPython35" }; private string[] macKnownPaths = { "/Library/Frameworks/Python.framework/Versions/3.7", "/Library/Frameworks/Python.framework/Versions/3.6", "/Library/Frameworks/Python.framework/Versions/3.5", "/Library/Frameworks/Python.framework/Versions/2.7", "/System/Library/Frameworks/Python.framework/Versions/3.7", "/System/Library/Frameworks/Python.framework/Versions/3.6", "/System/Library/Frameworks/Python.framework/Versions/3.5", "/System/Library/Frameworks/Python.framework/Versions/2.7" }; private string[] linuxKnownIncludesPaths = { "/usr/local/include/python3.7", "/usr/local/include/python3.7m", "/usr/local/include/python3.6", "/usr/local/include/python3.6m", "/usr/local/include/python3.5", "/usr/local/include/python3.5m", "/usr/local/include/python2.7", "/usr/include/python3.7", "/usr/include/python3.7m", "/usr/include/python3.6", "/usr/include/python3.6m", "/usr/include/python3.5", "/usr/include/python3.5m", "/usr/include/python2.7", }; private string[] linuxKnownLibsPaths = { "/usr/local/lib/libpython3.7.so", "/usr/local/lib/libpython3.7m.so", "/usr/local/lib/x86_64-linux-gnu/libpython3.7.so", "/usr/local/lib/x86_64-linux-gnu/libpython3.7m.so", "/usr/local/lib/libpython3.6.so", "/usr/local/lib/libpython3.6m.so", "/usr/local/lib/x86_64-linux-gnu/libpython3.6.so", "/usr/local/lib/x86_64-linux-gnu/libpython3.6m.so", "/usr/local/lib/libpython3.5.so", "/usr/local/lib/libpython3.5m.so", "/usr/local/lib/x86_64-linux-gnu/libpython3.5.so", "/usr/local/lib/x86_64-linux-gnu/libpython3.5m.so", "/usr/local/lib/libpython2.7.so", "/usr/local/lib/x86_64-linux-gnu/libpython2.7.so", "/usr/lib/libpython3.7.so", "/usr/lib/libpython3.7m.so", "/usr/lib/x86_64-linux-gnu/libpython3.7.so", "/usr/lib/x86_64-linux-gnu/libpython3.7m.so", "/usr/lib/libpython3.6.so", "/usr/lib/libpython3.6m.so", "/usr/lib/x86_64-linux-gnu/libpython3.6.so", "/usr/lib/x86_64-linux-gnu/libpython3.6m.so", "/usr/lib/libpython3.5.so", "/usr/lib/libpython3.5m.so", "/usr/lib/x86_64-linux-gnu/libpython3.5.so", "/usr/lib/x86_64-linux-gnu/libpython3.5m.so", "/usr/lib/libpython2.7.so", "/usr/lib/x86_64-linux-gnu/libpython2.7.so", }; #if WITH_FORWARDED_MODULE_RULES_CTOR public UnrealEnginePython(ReadOnlyTargetRules Target) : base(Target) #else public UnrealEnginePython(TargetInfo Target) #endif { PCHUsage = ModuleRules.PCHUsageMode.UseExplicitOrSharedPCHs; string enableUnityBuild = System.Environment.GetEnvironmentVariable("UEP_ENABLE_UNITY_BUILD"); bFasterWithoutUnity = string.IsNullOrEmpty(enableUnityBuild); PublicIncludePaths.AddRange( new string[] { // ... add public include paths required here ... } ); PrivateIncludePaths.AddRange( new string[] { // ... add other private include paths required here ... } ); PublicDependencyModuleNames.AddRange( new string[] { "Core", "Sockets", "Networking" // ... add other public dependencies that you statically link with here ... } ); PrivateDependencyModuleNames.AddRange( new string[] { "CoreUObject", "Engine", "InputCore", "Slate", "SlateCore", "MovieScene", "LevelSequence", "HTTP", "UMG", "AppFramework", "RHI", "Voice", "RenderCore", "MovieSceneCapture", "Landscape", "Foliage", "AIModule" // ... add private dependencies that you statically link with here ... } ); #if WITH_FORWARDED_MODULE_RULES_CTOR BuildVersion Version; if (BuildVersion.TryRead(BuildVersion.GetDefaultFileName(), out Version)) { if (Version.MinorVersion >= 18) { PrivateDependencyModuleNames.Add("ApplicationCore"); } } #endif DynamicallyLoadedModuleNames.AddRange( new string[] { // ... add any modules that your module loads dynamically here ... } ); #if WITH_FORWARDED_MODULE_RULES_CTOR if (Target.bBuildEditor) #else if (UEBuildConfiguration.bBuildEditor) #endif { PrivateDependencyModuleNames.AddRange(new string[]{ "UnrealEd", "LevelEditor", "BlueprintGraph", "Projects", "Sequencer", "SequencerWidgets", "AssetTools", "LevelSequenceEditor", "MovieSceneTools", "MovieSceneTracks", "CinematicCamera", "EditorStyle", "GraphEditor", "UMGEditor", "AIGraph", "RawMesh", "DesktopWidgets", "EditorWidgets", "FBX", "Persona", "PropertyEditor", "LandscapeEditor", "MaterialEditor" }); } if ((Target.Platform == UnrealTargetPlatform.Win64) || (Target.Platform == UnrealTargetPlatform.Win32)) { if (pythonHome == "") { pythonHome = DiscoverPythonPath(windowsKnownPaths, "Win64"); if (pythonHome == "") { throw new System.Exception("Unable to find Python installation"); } } System.Console.WriteLine("Using Python at: " + pythonHome); PublicIncludePaths.Add(pythonHome); string libPath = GetWindowsPythonLibFile(pythonHome); PublicLibraryPaths.Add(Path.GetDirectoryName(libPath)); PublicAdditionalLibraries.Add(libPath); } else if (Target.Platform == UnrealTargetPlatform.Mac) { if (pythonHome == "") { pythonHome = DiscoverPythonPath(macKnownPaths, "Mac"); if (pythonHome == "") { throw new System.Exception("Unable to find Python installation"); } } System.Console.WriteLine("Using Python at: " + pythonHome); PublicIncludePaths.Add(pythonHome); string libPath = GetMacPythonLibFile(pythonHome); PublicLibraryPaths.Add(Path.GetDirectoryName(libPath)); PublicDelayLoadDLLs.Add(libPath); } else if (Target.Platform == UnrealTargetPlatform.Linux) { if (pythonHome == "") { string includesPath = DiscoverLinuxPythonIncludesPath(); if (includesPath == null) { throw new System.Exception("Unable to find Python includes, please add a search path to linuxKnownIncludesPaths"); } string libsPath = DiscoverLinuxPythonLibsPath(); if (libsPath == null) { throw new System.Exception("Unable to find Python libs, please add a search path to linuxKnownLibsPaths"); } PublicIncludePaths.Add(includesPath); PublicAdditionalLibraries.Add(libsPath); } else { string[] items = pythonHome.Split(';'); PublicIncludePaths.Add(items[0]); PublicAdditionalLibraries.Add(items[1]); } } #if WITH_FORWARDED_MODULE_RULES_CTOR else if (Target.Platform == UnrealTargetPlatform.Android) { PublicIncludePaths.Add(System.IO.Path.Combine(ModuleDirectory, "../../android/python35/include")); PublicLibraryPaths.Add(System.IO.Path.Combine(ModuleDirectory, "../../android/armeabi-v7a")); PublicAdditionalLibraries.Add("python3.5m"); string APLName = "UnrealEnginePython_APL.xml"; string RelAPLPath = Utils.MakePathRelativeTo(System.IO.Path.Combine(ModuleDirectory, APLName), Target.RelativeEnginePath); AdditionalPropertiesForReceipt.Add(new ReceiptProperty("AndroidPlugin", RelAPLPath)); } #endif } private bool IsPathRelative(string Path) { bool IsRooted = Path.StartsWith("\\", System.StringComparison.Ordinal) || // Root of the current directory on Windows. Also covers "\\" for UNC or "network" paths. Path.StartsWith("/", System.StringComparison.Ordinal) || // Root of the current directory on Windows, root on UNIX-likes. // Also covers "\\", considering normalization replaces "\\" with "//". (Path.Length >= 2 && char.IsLetter(Path[0]) && Path[1] == ':'); // Starts with "<DriveLetter>:" return !IsRooted; } private string DiscoverPythonPath(string[] knownPaths, string binaryPath) { // insert the PYTHONHOME content as the first known path List<string> paths = new List<string>(knownPaths); paths.Insert(0, Path.Combine(ModuleDirectory, "../../Binaries", binaryPath)); string environmentPath = System.Environment.GetEnvironmentVariable("PYTHONHOME"); if (!string.IsNullOrEmpty(environmentPath)) paths.Insert(0, environmentPath); // look in an alternate custom location environmentPath = System.Environment.GetEnvironmentVariable("UNREALENGINEPYTHONHOME"); if (!string.IsNullOrEmpty(environmentPath)) paths.Insert(0, environmentPath); foreach (string path in paths) { string actualPath = path; if (IsPathRelative(actualPath)) { actualPath = Path.GetFullPath(Path.Combine(ModuleDirectory, actualPath)); } string headerFile = Path.Combine(actualPath, "include", "Python.h"); if (File.Exists(headerFile)) { return actualPath; } // this is mainly useful for OSX headerFile = Path.Combine(actualPath, "Headers", "Python.h"); if (File.Exists(headerFile)) { return actualPath; } } return ""; } private string DiscoverLinuxPythonIncludesPath() { List<string> paths = new List<string>(linuxKnownIncludesPaths); paths.Insert(0, Path.Combine(ModuleDirectory, "../../Binaries", "Linux", "include")); foreach (string path in paths) { string headerFile = Path.Combine(path, "Python.h"); if (File.Exists(headerFile)) { return path; } } return null; } private string DiscoverLinuxPythonLibsPath() { List<string> paths = new List<string>(linuxKnownLibsPaths); paths.Insert(0, Path.Combine(ModuleDirectory, "../../Binaries", "Linux", "lib")); paths.Insert(0, Path.Combine(ModuleDirectory, "../../Binaries", "Linux", "lib64")); foreach (string path in paths) { if (File.Exists(path)) { return path; } } return null; } private string GetMacPythonLibFile(string basePath) { // first try with python3 for (int i = 9; i >= 0; i--) { string fileName = string.Format("libpython3.{0}.dylib", i); string fullPath = Path.Combine(basePath, "lib", fileName); if (File.Exists(fullPath)) { return fullPath; } fileName = string.Format("libpython3.{0}m.dylib", i); fullPath = Path.Combine(basePath, "lib", fileName); if (File.Exists(fullPath)) { return fullPath; } } // then python2 for (int i = 9; i >= 0; i--) { string fileName = string.Format("libpython2.{0}.dylib", i); string fullPath = Path.Combine(basePath, "lib", fileName); if (File.Exists(fullPath)) { return fullPath; } fileName = string.Format("libpython2.{0}m.dylib", i); fullPath = Path.Combine(basePath, "lib", fileName); if (File.Exists(fullPath)) { return fullPath; } } throw new System.Exception("Invalid Python installation, missing .dylib files"); } private string GetWindowsPythonLibFile(string basePath) { // just for usability, report if the pythonHome is not in the system path string[] allPaths = System.Environment.GetEnvironmentVariable("PATH").Split(';'); // this will transform the slashes in backslashes... string checkedPath = Path.GetFullPath(basePath); if (checkedPath.EndsWith("\\")) { checkedPath = checkedPath.Remove(checkedPath.Length - 1); } bool found = false; foreach (string item in allPaths) { if (item == checkedPath || item == checkedPath + "\\") { found = true; break; } } if (!found) { System.Console.WriteLine("[WARNING] Your Python installation is not in the system PATH environment variable."); System.Console.WriteLine("[WARNING] Ensure your python paths are set in GlobalConfig (DefaultEngine.ini) so the path can be corrected at runtime."); } // first try with python3 for (int i = 9; i >= 0; i--) { string fileName = string.Format("python3{0}.lib", i); string fullPath = Path.Combine(basePath, "libs", fileName); if (File.Exists(fullPath)) { return fullPath; } } // then python2 for (int i = 9; i >= 0; i--) { string fileName = string.Format("python2{0}.lib", i); string fullPath = Path.Combine(basePath, "libs", fileName); if (File.Exists(fullPath)) { return fullPath; } } throw new System.Exception("Invalid Python installation, missing .lib files"); } } ```
/content/code_sandbox/Source/UnrealEnginePython/UnrealEnginePython.Build.cs
smalltalk
2016-08-07T05:00:51
2024-08-14T06:32:20
UnrealEnginePython
20tab/UnrealEnginePython
2,715
3,313
```objective-c #pragma once #include "UnrealEnginePython.h" #if WITH_EDITOR #include "Factories/Factory.h" #include "Runtime/SlateCore/Public/Widgets/SWindow.h" #endif class FPythonSmartDelegate : public TSharedFromThis<FPythonSmartDelegate> { public: FPythonSmartDelegate(); ~FPythonSmartDelegate(); void SetPyCallable(PyObject *callable); bool Tick(float DeltaTime); void Void(); #if WITH_EDITOR void PyFOnAssetPostImport(UFactory *factory, UObject *u_object); void PyFOnMainFrameCreationFinished(TSharedPtr<SWindow> InRootWindow, bool bIsNewProjectWindow); #endif protected: PyObject * py_callable; }; ```
/content/code_sandbox/Source/UnrealEnginePython/Public/PythonSmartDelegate.h
objective-c
2016-08-07T05:00:51
2024-08-14T06:32:20
UnrealEnginePython
20tab/UnrealEnginePython
2,715
144
```objective-c #pragma once #include "UObject/Class.h" #include "UnrealEnginePython.h" #include "Components/NativeWidgetHost.h" #include "PyNativeWidgetHost.generated.h" USTRUCT(BlueprintType) struct UNREALENGINEPYTHON_API FPythonSWidgetWrapper { GENERATED_USTRUCT_BODY() TSharedPtr<SWidget> Widget; }; template<> struct TStructOpsTypeTraits<FPythonSWidgetWrapper> : public TStructOpsTypeTraitsBase2<FPythonSWidgetWrapper> { enum { WithCopy = true, }; }; /** * */ UCLASS() class UNREALENGINEPYTHON_API UPyNativeWidgetHost : public UNativeWidgetHost { GENERATED_BODY() UPyNativeWidgetHost(const FObjectInitializer& ObjectInitializer); #if WITH_EDITOR virtual const FText GetPaletteCategory() override; #endif }; ```
/content/code_sandbox/Source/UnrealEnginePython/Public/PyNativeWidgetHost.h
objective-c
2016-08-07T05:00:51
2024-08-14T06:32:20
UnrealEnginePython
20tab/UnrealEnginePython
2,715
184
```objective-c #pragma once #include "GameFramework/Pawn.h" #include "UnrealEnginePython.h" #include "PyPawn.generated.h" UCLASS(BlueprintType, Blueprintable) class UNREALENGINEPYTHON_API APyPawn : public APawn { GENERATED_BODY() public: // Sets default values for this component's properties APyPawn(); ~APyPawn(); // Called whenever the Actor is instantiated (before begin play) virtual void PreInitializeComponents() override; virtual void PostInitializeComponents() override; // Called when the game starts virtual void BeginPlay() override; // Called every frame virtual void Tick(float DeltaSeconds) override; virtual void EndPlay(const EEndPlayReason::Type EndPlayReason) override; UPROPERTY(EditAnywhere , Category = "Python") FString PythonModule; UPROPERTY(EditAnywhere, Category = "Python") FString PythonClass; UPROPERTY(EditAnywhere, Category = "Python") bool PythonTickForceDisabled; UPROPERTY(EditAnywhere, Category = "Python") bool PythonDisableAutoBinding; UFUNCTION(BlueprintCallable, Category = "Python") void CallPythonPawnMethod(FString method_name); UFUNCTION(BlueprintCallable, Category = "Python") bool CallPythonPawnMethodBool(FString method_name); UFUNCTION(BlueprintCallable, Category = "Python") FString CallPythonPawnMethodString(FString method_name); private: PyObject *py_pawn_instance; // mapped uobject, required for debug and advanced reflection ue_PyUObject *py_uobject; }; ```
/content/code_sandbox/Source/UnrealEnginePython/Public/PyPawn.h
objective-c
2016-08-07T05:00:51
2024-08-14T06:32:20
UnrealEnginePython
20tab/UnrealEnginePython
2,715
310
```objective-c #pragma once #include "UnrealEnginePython.h" #include "UObject/UObjectGlobals.h" #include "UObject/WeakObjectPtr.h" #include "Widgets/SWidget.h" #include "Slate/UEPySlateDelegate.h" #include "Runtime/CoreUObject/Public/UObject/GCObject.h" #include "PythonDelegate.h" #include "PythonSmartDelegate.h" class FUnrealEnginePythonHouseKeeper : public FGCObject { struct FPythonUOjectTracker { FWeakObjectPtr Owner; ue_PyUObject *PyUObject; bool bPythonOwned; FPythonUOjectTracker(UObject *Object, ue_PyUObject *InPyUObject) { Owner = FWeakObjectPtr(Object); PyUObject = InPyUObject; bPythonOwned = false; } }; struct FPythonDelegateTracker { FWeakObjectPtr Owner; UPythonDelegate *Delegate; FPythonDelegateTracker(UPythonDelegate *DelegateToTrack, UObject *DelegateOwner) : Owner(DelegateOwner), Delegate(DelegateToTrack) { } ~FPythonDelegateTracker() { } }; struct FPythonSWidgetDelegateTracker { TWeakPtr<SWidget> Owner; TSharedPtr<FPythonSlateDelegate> Delegate; FPythonSWidgetDelegateTracker(TSharedRef<FPythonSlateDelegate> DelegateToTrack, TSharedRef<SWidget> DelegateOwner) : Owner(DelegateOwner), Delegate(DelegateToTrack) { } ~FPythonSWidgetDelegateTracker() { } }; public: virtual void AddReferencedObjects(FReferenceCollector& InCollector) override; static FUnrealEnginePythonHouseKeeper *Get(); int32 RunGC(); bool IsValidPyUObject(ue_PyUObject *PyUObject); void TrackUObject(UObject *Object); void UntrackUObject(UObject *Object); void RegisterPyUObject(UObject *Object, ue_PyUObject *InPyUObject); void UnregisterPyUObject(UObject *Object); ue_PyUObject *GetPyUObject(UObject *Object); UPythonDelegate *FindDelegate(UObject *Owner, PyObject *PyCallable); UPythonDelegate *NewDelegate(UObject *Owner, PyObject *PyCallable, UFunction *Signature); TSharedRef<FPythonSlateDelegate> NewSlateDelegate(TSharedRef<SWidget> Owner, PyObject *PyCallable); TSharedRef<FPythonSlateDelegate> NewDeferredSlateDelegate(PyObject *PyCallable); TSharedRef<FPythonSmartDelegate> NewPythonSmartDelegate(PyObject *PyCallable); void TrackDeferredSlateDelegate(TSharedRef<FPythonSlateDelegate> Delegate, TSharedRef<SWidget> Owner); TSharedRef<FPythonSlateDelegate> NewStaticSlateDelegate(PyObject *PyCallable); private: void RunGCDelegate(); uint32 PyUObjectsGC(); int32 DelegatesGC(); TMap<UObject *, FPythonUOjectTracker> UObjectPyMapping; TArray<FPythonDelegateTracker> PyDelegatesTracker; TArray<FPythonSWidgetDelegateTracker> PySlateDelegatesTracker; TArray<TSharedRef<FPythonSlateDelegate>> PyStaticSlateDelegatesTracker; TArray<TSharedRef<FPythonSmartDelegate>> PyStaticSmartDelegatesTracker; TArray<UObject *> PythonTrackedObjects; }; ```
/content/code_sandbox/Source/UnrealEnginePython/Public/PythonHouseKeeper.h
objective-c
2016-08-07T05:00:51
2024-08-14T06:32:20
UnrealEnginePython
20tab/UnrealEnginePython
2,715
720
```objective-c #pragma once #include "GameFramework/Actor.h" #include "UnrealEnginePython.h" #include "PyActor.generated.h" UCLASS(BlueprintType, Blueprintable) class UNREALENGINEPYTHON_API APyActor : public AActor { GENERATED_BODY() public: // Sets default values for this component's properties APyActor(); ~APyActor(); // Called whenever the Actor is instantiated (before begin play) virtual void PreInitializeComponents() override; virtual void PostInitializeComponents() override; // Called when the game starts virtual void BeginPlay() override; // Called every frame virtual void Tick(float DeltaSeconds) override; virtual void EndPlay(const EEndPlayReason::Type EndPlayReason) override; UPROPERTY(EditAnywhere, Category = "Python", BlueprintReadWrite, meta = (ExposeOnSpawn = true)) FString PythonModule; UPROPERTY(EditAnywhere, Category = "Python", BlueprintReadWrite, meta = (ExposeOnSpawn = true)) FString PythonClass; UPROPERTY(EditAnywhere, Category = "Python", BlueprintReadWrite, meta = (ExposeOnSpawn = true)) bool PythonTickForceDisabled; UPROPERTY(EditAnywhere, Category = "Python", BlueprintReadWrite, meta = (ExposeOnSpawn = true)) bool PythonDisableAutoBinding; UFUNCTION(BlueprintCallable, Category = "Python") void CallPythonActorMethod(FString method_name, FString args); UFUNCTION(BlueprintCallable, Category = "Python") bool CallPythonActorMethodBool(FString method_name, FString args); UFUNCTION(BlueprintCallable, Category = "Python") FString CallPythonActorMethodString(FString method_name, FString args); private: PyObject *py_actor_instance; // mapped uobject, required for debug and advanced reflection ue_PyUObject *py_uobject; }; ```
/content/code_sandbox/Source/UnrealEnginePython/Public/PyActor.h
objective-c
2016-08-07T05:00:51
2024-08-14T06:32:20
UnrealEnginePython
20tab/UnrealEnginePython
2,715
366
```objective-c #pragma once #if defined(__clang__) #pragma clang diagnostic ignored "-Wdelete-non-virtual-dtor" #endif //#define UEPY_MEMORY_DEBUG 1 #include "CoreMinimal.h" #include "Runtime/Core/Public/Modules/ModuleManager.h" #include "Runtime/SlateCore/Public/Styling/SlateStyle.h" #include "UObject/ScriptMacros.h" #include "Runtime/Launch/Resources/Version.h" #if PLATFORM_MAC #include <Headers/Python.h> #include <Headers/structmember.h> #elif PLATFORM_LINUX #include <Python.h> #include <structmember.h> #elif PLATFORM_ANDROID #include <Python.h> #include <structmember.h> #elif PLATFORM_WINDOWS #include <include/pyconfig.h> #ifndef SIZEOF_PID_T #define SIZEOF_PID_T 4 #endif #include <include/Python.h> #include <include/structmember.h> #endif typedef struct { PyObject_HEAD /* Type-specific fields go here. */ UObject *ue_object; // reference to proxy class (can be null) PyObject *py_proxy; // the __dict__ PyObject *py_dict; // if true RemoveFromRoot will be called at object destruction time int auto_rooted; // if owned the life of the UObject is related to the life of PyObject int owned; } ue_PyUObject; UNREALENGINEPYTHON_API void ue_py_register_magic_module(char *name, PyObject *(*)()); UNREALENGINEPYTHON_API PyObject *ue_py_register_module(const char *); #if ENGINE_MINOR_VERSION >= 18 #define FStringAssetReference FSoftObjectPath #endif #define ue_py_check(py_u) if (!FUnrealEnginePythonHouseKeeper::Get()->IsValidPyUObject(py_u))\ return PyErr_Format(PyExc_Exception, "PyUObject is in invalid state") #define ue_py_check_int(py_u) if (!FUnrealEnginePythonHouseKeeper::Get()->IsValidPyUObject(py_u))\ {\ PyErr_SetString(PyExc_Exception, "PyUObject is in invalid state");\ return -1;\ } const char *UEPyUnicode_AsUTF8(PyObject *py_str); #if PY_MAJOR_VERSION < 3 int PyGILState_Check(); #endif bool PyUnicodeOrString_Check(PyObject *py_obj); UNREALENGINEPYTHON_API void unreal_engine_py_log_error(); UNREALENGINEPYTHON_API ue_PyUObject *ue_get_python_uobject(UObject *); UNREALENGINEPYTHON_API ue_PyUObject *ue_get_python_uobject_inc(UObject *); #define Py_RETURN_UOBJECT(py_uobj) ue_PyUObject *ret = ue_get_python_uobject_inc(py_uobj);\ if (!ret)\ return PyErr_Format(PyExc_Exception, "uobject is in invalid state");\ return (PyObject *)ret; #define Py_RETURN_UOBJECT_NOINC(py_uobj) ue_PyUObject *ret = ue_get_python_uobject(py_uobj);\ if (!ret)\ return PyErr_Format(PyExc_Exception, "uobject is in invalid state");\ return (PyObject *)ret; #if ENGINE_MINOR_VERSION < 16 template<class CPPSTRUCT> struct TStructOpsTypeTraitsBase2 : TStructOpsTypeTraitsBase { }; #endif DECLARE_LOG_CATEGORY_EXTERN(LogPython, Log, All); class UNREALENGINEPYTHON_API FUnrealEnginePythonModule : public IModuleInterface { public: virtual void StartupModule() override; virtual void ShutdownModule() override; void RunString(char *); void RunFile(char *); #if PLATFORM_MAC void RunStringInMainThread(char *); void RunFileInMainThread(char *); #endif void UESetupPythonInterpreter(bool); TArray<FString> ScriptsPaths; FString ZipPath; FString AdditionalModulesPath; bool BrutalFinalize; // pep8ize a string using various strategy (currently only autopep8 is supported) FString Pep8ize(FString Code); private: void *ue_python_gil; // used by console void *main_dict; void *local_dict; void *main_module; TSharedPtr<FSlateStyleSet> StyleSet; }; struct FScopePythonGIL { PyGILState_STATE state; FScopePythonGIL() { state = PyGILState_Ensure(); } ~FScopePythonGIL() { PyGILState_Release(state); } }; ```
/content/code_sandbox/Source/UnrealEnginePython/Public/UnrealEnginePython.h
objective-c
2016-08-07T05:00:51
2024-08-14T06:32:20
UnrealEnginePython
20tab/UnrealEnginePython
2,715
915
```objective-c #pragma once #include "UnrealEnginePython.h" #include "PythonClass.generated.h" void unreal_engine_py_log_error(); UCLASS() class UPythonClass : public UClass { GENERATED_BODY() public: void SetPyConstructor(PyObject *callable) { py_constructor = callable; Py_INCREF(py_constructor); } void CallPyConstructor(ue_PyUObject *self) { if (!py_constructor) return; PyObject *ret = PyObject_CallObject(py_constructor, Py_BuildValue("(O)", self)); if (!ret) { unreal_engine_py_log_error(); return; } Py_DECREF(ret); } // __dict__ is stored here ue_PyUObject *py_uobject; private: PyObject * py_constructor; }; ```
/content/code_sandbox/Source/UnrealEnginePython/Public/PythonClass.h
objective-c
2016-08-07T05:00:51
2024-08-14T06:32:20
UnrealEnginePython
20tab/UnrealEnginePython
2,715
172
```objective-c #pragma once #include "UnrealEnginePython.h" #include "PythonFunction.generated.h" UCLASS() class UPythonFunction : public UFunction { GENERATED_BODY() public: ~UPythonFunction(); void SetPyCallable(PyObject *callable); DECLARE_FUNCTION(CallPythonCallable); PyObject *py_callable; }; ```
/content/code_sandbox/Source/UnrealEnginePython/Public/PythonFunction.h
objective-c
2016-08-07T05:00:51
2024-08-14T06:32:20
UnrealEnginePython
20tab/UnrealEnginePython
2,715
66
```objective-c #pragma once #include "Kismet/BlueprintFunctionLibrary.h" #include "UnrealEnginePython.h" #include "PythonBlueprintFunctionLibrary.generated.h" UCLASS() class UNREALENGINEPYTHON_API UPythonBlueprintFunctionLibrary : public UBlueprintFunctionLibrary { GENERATED_BODY() public: UFUNCTION(BlueprintCallable, Exec, Category = "Python") static void ExecutePythonScript(FString script); UFUNCTION(BlueprintCallable, Exec, Category = "Python") static void ExecutePythonString(const FString& PythonCmd); }; ```
/content/code_sandbox/Source/UnrealEnginePython/Public/PythonBlueprintFunctionLibrary.h
objective-c
2016-08-07T05:00:51
2024-08-14T06:32:20
UnrealEnginePython
20tab/UnrealEnginePython
2,715
107
```objective-c #pragma once #include "Components/ActorComponent.h" #include "UnrealEnginePython.h" #include "PythonComponent.generated.h" UCLASS(BlueprintType, Blueprintable, ClassGroup = (Python), meta = (BlueprintSpawnableComponent)) class UNREALENGINEPYTHON_API UPythonComponent : public UActorComponent { GENERATED_BODY() public: // Sets default values for this component's properties UPythonComponent(); ~UPythonComponent(); // Called when the game starts virtual void BeginPlay() override; virtual void EndPlay(const EEndPlayReason::Type EndPlayReason) override; // Called every frame virtual void TickComponent(float DeltaTime, ELevelTick TickType, FActorComponentTickFunction* ThisTickFunction) override; virtual void InitializeComponent() override; UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Python") FString PythonModule; UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Python") FString PythonClass; UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Python") bool PythonTickForceDisabled; UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Python") bool PythonDisableAutoBinding; UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Python") bool PythonTickEnableGenerator; UFUNCTION(BlueprintCallable, Category = "Python") void InitializePythonComponent(); UFUNCTION(BlueprintCallable, Category = "Python") void CallPythonComponentMethod(FString method_name, FString args); UFUNCTION(BlueprintCallable, Category = "Python") bool CallPythonComponentMethodBool(FString method_name, FString args); UFUNCTION(BlueprintCallable, Category = "Python") FString CallPythonComponentMethodString(FString method_name, FString args); UFUNCTION(BlueprintCallable, Category = "Python") TMap<FString, FString> CallPythonComponentMethodMap(FString method_name, FString args); UFUNCTION(BlueprintCallable, Category = "Python") void CallPythonComponentMethodStringArray(FString method_name, FString args, TArray<FString> &output_strings); UFUNCTION(BlueprintCallable, Category = "Python") float CallPythonComponentMethodFloat(FString method_name, FString args); UFUNCTION(BlueprintCallable, Category = "Python") int CallPythonComponentMethodInt(FString method_name, FString args); UFUNCTION(BlueprintCallable, Category = "Python") UObject *CallPythonComponentMethodObject(FString method_name, UObject *arg); UFUNCTION(BlueprintCallable, Category = "Python") void SetPythonAttrInt(FString attr, int Integer); UFUNCTION(BlueprintCallable, Category = "Python") void SetPythonAttrFloat(FString attr, float Float); UFUNCTION(BlueprintCallable, Category = "Python") void SetPythonAttrString(FString attr, FString String); UFUNCTION(BlueprintCallable, Category = "Python") void SetPythonAttrBool(FString attr, bool Boolean); UFUNCTION(BlueprintCallable, Category = "Python") void SetPythonAttrVector(FString attr, FVector Vector); UFUNCTION(BlueprintCallable, Category = "Python") void SetPythonAttrRotator(FString attr, FRotator Rotator); UFUNCTION(BlueprintCallable, Category = "Python") void SetPythonAttrObject(FString attr, UObject *Object); private: PyObject * py_component_instance; // mapped uobject, required for debug and advanced reflection ue_PyUObject *py_uobject; PyObject *py_generator; }; ```
/content/code_sandbox/Source/UnrealEnginePython/Public/PythonComponent.h
objective-c
2016-08-07T05:00:51
2024-08-14T06:32:20
UnrealEnginePython
20tab/UnrealEnginePython
2,715
681
```objective-c #pragma once #include "Commandlets/Commandlet.h" #include "PyCommandlet.generated.h" UCLASS() class UPyCommandlet : public UCommandlet { GENERATED_UCLASS_BODY() virtual int32 Main(const FString& Params) override; }; ```
/content/code_sandbox/Source/UnrealEnginePython/Public/PyCommandlet.h
objective-c
2016-08-07T05:00:51
2024-08-14T06:32:20
UnrealEnginePython
20tab/UnrealEnginePython
2,715
55
```objective-c #pragma once #include "GameFramework/Character.h" #include "UnrealEnginePython.h" #include "PyCharacter.generated.h" UCLASS() class UNREALENGINEPYTHON_API APyCharacter : public ACharacter { GENERATED_BODY() public: // Sets default values for this component's properties APyCharacter(); ~APyCharacter(); // Called whenever the Actor is instantiated (before begin play) virtual void PreInitializeComponents() override; virtual void PostInitializeComponents() override; // Called when the game starts virtual void BeginPlay() override; // Called every frame virtual void Tick(float DeltaSeconds) override; // Called to bind functionality to input virtual void SetupPlayerInputComponent(class UInputComponent* input) override; virtual void EndPlay(const EEndPlayReason::Type EndPlayReason) override; UPROPERTY(EditAnywhere, Category = "Python") FString PythonModule; UPROPERTY(EditAnywhere, Category = "Python") FString PythonClass; UPROPERTY(EditAnywhere, Category = "Python") bool PythonTickForceDisabled; UPROPERTY(EditAnywhere, Category = "Python") bool PythonDisableAutoBinding; UFUNCTION(BlueprintCallable, Category = "Python") void CallPyCharacterMethod(FString method_name, FString args); UFUNCTION(BlueprintCallable, Category = "Python") bool CallPyCharacterMethodBool(FString method_name, FString args); UFUNCTION(BlueprintCallable, Category = "Python") FString CallPyCharacterMethodString(FString method_name, FString args); UFUNCTION(BlueprintCallable, Category = "Python") float CallPyCharacterMethodFloat(FString method_name, FString args); UFUNCTION(BlueprintCallable, Category = "Python") void SetPythonAttrInt(FString attr, int Integer); UFUNCTION(BlueprintCallable, Category = "Python") void SetPythonAttrFloat(FString attr, float Float); UFUNCTION(BlueprintCallable, Category = "Python") void SetPythonAttrString(FString attr, FString String); UFUNCTION(BlueprintCallable, Category = "Python") void SetPythonAttrBool(FString attr, bool Boolean); UFUNCTION(BlueprintCallable, Category = "Python") void SetPythonAttrVector(FString attr, FVector Vector); UFUNCTION(BlueprintCallable, Category = "Python") void SetPythonAttrRotator(FString attr, FRotator Rotator); UFUNCTION(BlueprintCallable, Category = "Python") void SetPythonAttrObject(FString attr, UObject *Object); private: PyObject * py_character_instance; // mapped uobject, required for debug and advanced reflection ue_PyUObject *py_uobject; }; ```
/content/code_sandbox/Source/UnrealEnginePython/Public/PyCharacter.h
objective-c
2016-08-07T05:00:51
2024-08-14T06:32:20
UnrealEnginePython
20tab/UnrealEnginePython
2,715
527
```objective-c #pragma once #include "GameFramework/HUD.h" #include "UnrealEnginePython.h" #include "PyHUD.generated.h" UCLASS(BlueprintType, Blueprintable) class UNREALENGINEPYTHON_API APyHUD : public AHUD { GENERATED_BODY() public: // Sets default values for this component's properties APyHUD(); ~APyHUD(); // Called when the game starts virtual void BeginPlay() override; // Called every frame virtual void Tick(float DeltaSeconds) override; virtual void DrawHUD() override; UPROPERTY(EditAnywhere , Category = "Python") FString PythonModule; UPROPERTY(EditAnywhere, Category = "Python") FString PythonClass; UPROPERTY(EditAnywhere, Category = "Python") bool PythonTickForceDisabled; UPROPERTY(EditAnywhere, Category = "Python") bool PythonDisableAutoBinding; UFUNCTION(BlueprintCallable, Category = "Python") void CallPythonHUDMethod(FString method_name, FString args); UFUNCTION(BlueprintCallable, Category = "Python") bool CallPythonHUDMethodBool(FString method_name, FString args); UFUNCTION(BlueprintCallable, Category = "Python") FString CallPythonHUDMethodString(FString method_name, FString args); private: PyObject *py_hud_instance; // mapped uobject, required for debug and advanced reflection ue_PyUObject *py_uobject; }; ```
/content/code_sandbox/Source/UnrealEnginePython/Public/PyHUD.h
objective-c
2016-08-07T05:00:51
2024-08-14T06:32:20
UnrealEnginePython
20tab/UnrealEnginePython
2,715
280
```objective-c #pragma once #include "Runtime/UMG/Public/Blueprint/UserWidget.h" #include "UnrealEnginePython.h" #include "Runtime/Launch/Resources/Version.h" #include "PyUserWidget.generated.h" #if ENGINE_MINOR_VERSION < 20 #define NativePaintArgs FPaintContext & InContext #define NativePaintRetValue void #else #define NativePaintArgs const FPaintArgs& Args, const FGeometry& AllottedGeometry, const FSlateRect& MyCullingRect, FSlateWindowElementList& OutDrawElements, int32 LayerId, const FWidgetStyle& InWidgetStyle, bool bParentEnabled #define NativePaintRetValue int32 #endif UCLASS(BlueprintType, Blueprintable) class UNREALENGINEPYTHON_API UPyUserWidget : public UUserWidget { GENERATED_BODY() public: UPyUserWidget(const FObjectInitializer& ObjectInitializer); ~UPyUserWidget(); virtual void NativeConstruct() override; virtual void NativeDestruct() override; // Called every frame virtual void NativeTick(const FGeometry & MyGeometry, float InDeltaTime) override; virtual NativePaintRetValue NativePaint(NativePaintArgs) const override; virtual bool NativeIsInteractable() const override; virtual FReply NativeOnMouseButtonDown(const FGeometry & InGeometry, const FPointerEvent & InMouseEvent) override; virtual FReply NativeOnMouseButtonUp(const FGeometry & InGeometry, const FPointerEvent & InMouseEvent) override; virtual FReply NativeOnMouseWheel(const FGeometry & InGeometry, const FPointerEvent & InMouseEvent) override; virtual FReply NativeOnMouseMove(const FGeometry & InGeometry, const FPointerEvent & InMouseEvent) override; virtual FReply NativeOnKeyUp(const FGeometry & InGeometry, const FKeyEvent & InKeyEvent) override; virtual FReply NativeOnKeyDown(const FGeometry & InGeometry, const FKeyEvent & InKeyEvent) override; UPROPERTY(EditAnywhere, Category = "Python", BlueprintReadWrite, meta = (ExposeOnSpawn = true)) FString PythonModule; UPROPERTY(EditAnywhere, Category = "Python", BlueprintReadWrite, meta = (ExposeOnSpawn = true)) FString PythonClass; UPROPERTY(EditAnywhere, Category = "Python", BlueprintReadWrite, meta = (ExposeOnSpawn = true)) bool PythonTickForceDisabled; UPROPERTY(EditAnywhere, Category = "Python", BlueprintReadWrite, meta = (ExposeOnSpawn = true)) bool PythonPaintForceDisabled; UFUNCTION(BlueprintCallable, Category = "Python") void CallPythonUserWidgetMethod(FString method_name, FString args); UPROPERTY(EditAnywhere, Category = "Python", BlueprintReadWrite) TWeakObjectPtr<class UPyNativeWidgetHost> PyNativeWidgetHost; #if WITH_EDITOR virtual const FText GetPaletteCategory() override; #endif void SetSlateWidget(TSharedRef<SWidget> InContent); virtual void ReleaseSlateResources(bool bReleaseChildren) override; protected: // UWidget interface virtual TSharedRef<SWidget> RebuildWidget() override; // End of UWidget interface private: PyObject * py_user_widget_instance; // mapped uobject, required for debug and advanced reflection ue_PyUObject *py_uobject; }; ```
/content/code_sandbox/Source/UnrealEnginePython/Public/PyUserWidget.h
objective-c
2016-08-07T05:00:51
2024-08-14T06:32:20
UnrealEnginePython
20tab/UnrealEnginePython
2,715
664
```objective-c #pragma once #include "UObject/Object.h" #include "UObject/ScriptMacros.h" #include "PythonScript.generated.h" UCLASS(MinimalAPI) class UPythonScript : public UObject { GENERATED_BODY() public: UPROPERTY(EditAnywhere, Category = "Python") FString ScriptPath; UPROPERTY(EditAnywhere, Category = "Python") FString FunctionToCall; UPROPERTY(EditAnywhere, Category = "Python") TArray<FString> FunctionArgs; UFUNCTION() void Run(); void CallSpecificFunctionWithArgs(); }; ```
/content/code_sandbox/Source/UnrealEnginePython/Public/PythonScript.h
objective-c
2016-08-07T05:00:51
2024-08-14T06:32:20
UnrealEnginePython
20tab/UnrealEnginePython
2,715
113
```objective-c #pragma once #include "UnrealEnginePython.h" #include "PythonDelegate.generated.h" UCLASS() class UPythonDelegate : public UObject { GENERATED_BODY() public: UPythonDelegate(); ~UPythonDelegate(); virtual void ProcessEvent(UFunction *function, void *Parms) override; void SetPyCallable(PyObject *callable); bool UsesPyCallable(PyObject *callable); void SetSignature(UFunction *original_signature); void PyInputHandler(); void PyInputAxisHandler(float value); protected: UFunction * signature; bool signature_set; UFUNCTION() void PyFakeCallable(); PyObject *py_callable; }; ```
/content/code_sandbox/Source/UnrealEnginePython/Public/PythonDelegate.h
objective-c
2016-08-07T05:00:51
2024-08-14T06:32:20
UnrealEnginePython
20tab/UnrealEnginePython
2,715
128
```objective-c #pragma once #include "UEPyModule.h" typedef struct { PyObject_HEAD /* Type-specific fields go here. */ UScriptStruct *u_struct; uint8 *u_struct_ptr; // if set, the struct is responsible for freeing memory int u_struct_owned; } ue_PyUScriptStruct; PyObject *py_ue_new_uscriptstruct(UScriptStruct *, uint8 *); PyObject *py_ue_new_owned_uscriptstruct(UScriptStruct *, uint8 *); PyObject *py_ue_new_owned_uscriptstruct_zero_copy(UScriptStruct *, uint8 *); ue_PyUScriptStruct *py_ue_is_uscriptstruct(PyObject *); UProperty *ue_struct_get_field_from_name(UScriptStruct *, char *); void ue_python_init_uscriptstruct(PyObject *); ```
/content/code_sandbox/Source/UnrealEnginePython/Private/UEPyUScriptStruct.h
objective-c
2016-08-07T05:00:51
2024-08-14T06:32:20
UnrealEnginePython
20tab/UnrealEnginePython
2,715
162
```c++ #include "PyPawn.h" #include "UEPyModule.h" APyPawn::APyPawn() { PrimaryActorTick.bCanEverTick = true; PythonTickForceDisabled = false; PythonDisableAutoBinding = false; } void APyPawn::PostInitializeComponents() { Super::PostInitializeComponents(); if (!py_pawn_instance) return; FScopePythonGIL gil; if (!PyObject_HasAttrString(py_pawn_instance, (char *)"post_initialize_components")) return; PyObject *pic_ret = PyObject_CallMethod(py_pawn_instance, (char *)"post_initialize_components", NULL); if (!pic_ret) { unreal_engine_py_log_error(); return; } Py_DECREF(pic_ret); } // Called when the game starts void APyPawn::PreInitializeComponents() { Super::PreInitializeComponents(); if (PythonModule.IsEmpty()) return; FScopePythonGIL gil; py_uobject = ue_get_python_uobject(this); if (!py_uobject) { unreal_engine_py_log_error(); return; } PyObject *py_pawn_module = PyImport_ImportModule(TCHAR_TO_UTF8(*PythonModule)); if (!py_pawn_module) { unreal_engine_py_log_error(); return; } #if WITH_EDITOR // todo implement autoreload with a dictionary of module timestamps py_pawn_module = PyImport_ReloadModule(py_pawn_module); if (!py_pawn_module) { unreal_engine_py_log_error(); return; } #endif if (PythonClass.IsEmpty()) return; PyObject *py_pawn_module_dict = PyModule_GetDict(py_pawn_module); PyObject *py_pawn_class = PyDict_GetItemString(py_pawn_module_dict, TCHAR_TO_UTF8(*PythonClass)); if (!py_pawn_class) { UE_LOG(LogPython, Error, TEXT("Unable to find class %s in module %s"), *PythonClass, *PythonModule); return; } py_pawn_instance = PyObject_CallObject(py_pawn_class, NULL); if (!py_pawn_instance) { unreal_engine_py_log_error(); return; } py_uobject->py_proxy = py_pawn_instance; PyObject_SetAttrString(py_pawn_instance, (char *)"uobject", (PyObject *)py_uobject); // disable ticking if not required if (!PyObject_HasAttrString(py_pawn_instance, (char *)"tick") || PythonTickForceDisabled) { SetActorTickEnabled(false); } if (!PythonDisableAutoBinding) ue_autobind_events_for_pyclass(py_uobject, py_pawn_instance); ue_bind_events_for_py_class_by_attribute(this, py_pawn_instance); if (!PyObject_HasAttrString(py_pawn_instance, (char *)"pre_initialize_components")) return; PyObject *pic_ret = PyObject_CallMethod(py_pawn_instance, (char *)"pre_initialize_components", NULL); if (!pic_ret) { unreal_engine_py_log_error(); return; } Py_DECREF(pic_ret); } // Called when the game starts void APyPawn::BeginPlay() { Super::BeginPlay(); if (!py_pawn_instance) return; FScopePythonGIL gil; if (!PyObject_HasAttrString(py_pawn_instance, (char *)"begin_play")) return; PyObject *bp_ret = PyObject_CallMethod(py_pawn_instance, (char *)"begin_play", NULL); if (!bp_ret) { unreal_engine_py_log_error(); return; } Py_DECREF(bp_ret); } // Called every frame void APyPawn::Tick(float DeltaTime) { Super::Tick(DeltaTime); if (!py_pawn_instance) return; FScopePythonGIL gil; PyObject *ret = PyObject_CallMethod(py_pawn_instance, (char *)"tick", (char *)"f", DeltaTime); if (!ret) { unreal_engine_py_log_error(); return; } Py_DECREF(ret); } void APyPawn::EndPlay(const EEndPlayReason::Type EndPlayReason) { if (!py_pawn_instance) return; FScopePythonGIL gil; if (PyObject_HasAttrString(py_pawn_instance, (char *)"end_play")) { PyObject *ep_ret = PyObject_CallMethod(py_pawn_instance, (char *)"end_play", (char*)"i", (int)EndPlayReason); if (!ep_ret) { unreal_engine_py_log_error(); } Py_XDECREF(ep_ret); } Super::EndPlay(EndPlayReason); // ... } void APyPawn::CallPythonPawnMethod(FString method_name) { if (!py_pawn_instance) return; FScopePythonGIL gil; PyObject *ret = PyObject_CallMethod(py_pawn_instance, TCHAR_TO_UTF8(*method_name), NULL); if (!ret) { unreal_engine_py_log_error(); return; } Py_DECREF(ret); } bool APyPawn::CallPythonPawnMethodBool(FString method_name) { if (!py_pawn_instance) return false; FScopePythonGIL gil; PyObject *ret = PyObject_CallMethod(py_pawn_instance, TCHAR_TO_UTF8(*method_name), NULL); if (!ret) { unreal_engine_py_log_error(); return false; } if (PyObject_IsTrue(ret)) { Py_DECREF(ret); return true; } Py_DECREF(ret); return false; } FString APyPawn::CallPythonPawnMethodString(FString method_name) { if (!py_pawn_instance) return FString(); FScopePythonGIL gil; PyObject *ret = PyObject_CallMethod(py_pawn_instance, TCHAR_TO_UTF8(*method_name), NULL); if (!ret) { unreal_engine_py_log_error(); return FString(); } PyObject *py_str = PyObject_Str(ret); if (!py_str) { Py_DECREF(ret); return FString(); } const char *str_ret = UEPyUnicode_AsUTF8(py_str); FString ret_fstring = FString(UTF8_TO_TCHAR(str_ret)); Py_DECREF(py_str); return ret_fstring; } APyPawn::~APyPawn() { FScopePythonGIL gil; # #if defined(UEPY_MEMORY_DEBUG) UE_LOG(LogPython, Warning, TEXT("Python APawn (mapped to %p) wrapper XDECREF'ed"), py_uobject ? py_uobject->py_proxy : nullptr); #endif // this could trigger the distruction of the python/uobject mapper Py_XDECREF(py_uobject); FUnrealEnginePythonHouseKeeper::Get()->UnregisterPyUObject(this); } ```
/content/code_sandbox/Source/UnrealEnginePython/Private/PyPawn.cpp
c++
2016-08-07T05:00:51
2024-08-14T06:32:20
UnrealEnginePython
20tab/UnrealEnginePython
2,715
1,427
```c++ #include "PythonFunction.h" #include "UEPyModule.h" void UPythonFunction::SetPyCallable(PyObject *callable) { py_callable = callable; Py_INCREF(py_callable); } #if ENGINE_MINOR_VERSION > 18 void UPythonFunction::CallPythonCallable(UObject *Context, FFrame& Stack, RESULT_DECL) #else void UPythonFunction::CallPythonCallable(FFrame& Stack, RESULT_DECL) #endif { FScopePythonGIL gil; #if ENGINE_MINOR_VERSION <= 18 UObject *Context = Stack.Object; #endif UPythonFunction *function = static_cast<UPythonFunction *>(Stack.CurrentNativeFunction); bool on_error = false; bool is_static = function->HasAnyFunctionFlags(FUNC_Static); // count the number of arguments Py_ssize_t argn = (Context && !is_static) ? 1 : 0; TFieldIterator<UProperty> IArgs(function); for (; IArgs && ((IArgs->PropertyFlags & (CPF_Parm | CPF_ReturnParm)) == CPF_Parm); ++IArgs) { argn++; } #if defined(UEPY_MEMORY_DEBUG) UE_LOG(LogPython, Warning, TEXT("Initializing %d parameters"), argn); #endif PyObject *py_args = PyTuple_New(argn); argn = 0; if (Context && !is_static) { PyObject *py_obj = (PyObject *)ue_get_python_uobject(Context); if (!py_obj) { unreal_engine_py_log_error(); on_error = true; } else { Py_INCREF(py_obj); PyTuple_SetItem(py_args, argn++, py_obj); } } uint8 *frame = Stack.Locals; // is it a blueprint call ? if (*Stack.Code == EX_EndFunctionParms) { for (UProperty *prop = (UProperty *)function->Children; prop; prop = (UProperty *)prop->Next) { if (prop->PropertyFlags & CPF_ReturnParm) continue; if (!on_error) { PyObject *arg = ue_py_convert_property(prop, (uint8 *)Stack.Locals, 0); if (!arg) { unreal_engine_py_log_error(); on_error = true; } else { PyTuple_SetItem(py_args, argn++, arg); } } } } else { //UE_LOG(LogPython, Warning, TEXT("BLUEPRINT CALL")); frame = (uint8 *)FMemory_Alloca(function->PropertiesSize); FMemory::Memzero(frame, function->PropertiesSize); for (UProperty *prop = (UProperty *)function->Children; *Stack.Code != EX_EndFunctionParms; prop = (UProperty *)prop->Next) { Stack.Step(Stack.Object, prop->ContainerPtrToValuePtr<uint8>(frame)); if (prop->PropertyFlags & CPF_ReturnParm) continue; if (!on_error) { PyObject *arg = ue_py_convert_property(prop, frame, 0); if (!arg) { unreal_engine_py_log_error(); on_error = true; } else { PyTuple_SetItem(py_args, argn++, arg); } } } } Stack.Code++; if (on_error || !function->py_callable) { Py_DECREF(py_args); return; } PyObject *ret = PyObject_CallObject(function->py_callable, py_args); Py_DECREF(py_args); if (!ret) { unreal_engine_py_log_error(); return; } // get return value (if required) UProperty *return_property = function->GetReturnProperty(); if (return_property && function->ReturnValueOffset != MAX_uint16) { #if defined(UEPY_MEMORY_DEBUG) UE_LOG(LogPython, Warning, TEXT("FOUND RETURN VALUE")); #endif if (ue_py_convert_pyobject(ret, return_property, frame, 0)) { // copy value to stack result value FMemory::Memcpy(RESULT_PARAM, frame + function->ReturnValueOffset, return_property->ArrayDim * return_property->ElementSize); } else { UE_LOG(LogPython, Error, TEXT("Invalid return value type for function %s"), *function->GetFName().ToString()); } } Py_DECREF(ret); } UPythonFunction::~UPythonFunction() { FScopePythonGIL gil; Py_XDECREF(py_callable); FUnrealEnginePythonHouseKeeper::Get()->UnregisterPyUObject(this); #if defined(UEPY_MEMORY_DEBUG) UE_LOG(LogPython, Warning, TEXT("PythonFunction callable %p XDECREF'ed"), this); #endif } ```
/content/code_sandbox/Source/UnrealEnginePython/Private/PythonFunction.cpp
c++
2016-08-07T05:00:51
2024-08-14T06:32:20
UnrealEnginePython
20tab/UnrealEnginePython
2,715
1,001
```c++ #include "PyUserWidget.h" #include "PyNativeWidgetHost.h" #include "PythonDelegate.h" #include "Slate/UEPyFGeometry.h" #include "Slate/UEPyFPaintContext.h" #include "Widgets/Layout/SBox.h" #include "UMGStyle.h" #include "Runtime/UMG/Public/Blueprint/WidgetTree.h" #include "Slate/UEPyFKeyEvent.h" #include "Slate/UEPyFPointerEvent.h" void UPyUserWidget::NativeConstruct() { Super::NativeConstruct(); WidgetTree->ForEachWidget([&](UWidget* Widget) { if (Widget->IsA<UPyNativeWidgetHost>()) { PyNativeWidgetHost = Cast<UPyNativeWidgetHost>(Widget); } }); if (PythonModule.IsEmpty()) return; FScopePythonGIL gil; py_uobject = ue_get_python_uobject(this); if (!py_uobject) { unreal_engine_py_log_error(); return; } PyObject *py_user_widget_module = PyImport_ImportModule(TCHAR_TO_UTF8(*PythonModule)); if (!py_user_widget_module) { unreal_engine_py_log_error(); return; } #if WITH_EDITOR // todo implement autoreload with a dictionary of module timestamps py_user_widget_module = PyImport_ReloadModule(py_user_widget_module); if (!py_user_widget_module) { unreal_engine_py_log_error(); return; } #endif if (PythonClass.IsEmpty()) return; PyObject *py_user_widget_module_dict = PyModule_GetDict(py_user_widget_module); PyObject *py_user_widget_class = PyDict_GetItemString(py_user_widget_module_dict, TCHAR_TO_UTF8(*PythonClass)); if (!py_user_widget_class) { UE_LOG(LogPython, Error, TEXT("Unable to find class %s in module %s"), *PythonClass, *PythonModule); return; } py_user_widget_instance = PyObject_CallObject(py_user_widget_class, NULL); if (!py_user_widget_instance) { unreal_engine_py_log_error(); return; } py_uobject->py_proxy = py_user_widget_instance; PyObject_SetAttrString(py_user_widget_instance, (char*)"uobject", (PyObject *)py_uobject); if (PythonTickForceDisabled) #if ENGINE_MINOR_VERSION < 20 bCanEverTick = false; #else bHasScriptImplementedTick = false; #endif if (PythonPaintForceDisabled) #if ENGINE_MINOR_VERSION < 20 bCanEverPaint = false; #else bHasScriptImplementedPaint = false; #endif if (!PyObject_HasAttrString(py_user_widget_instance, (char *)"construct")) return; PyObject *bp_ret = PyObject_CallMethod(py_user_widget_instance, (char *)"construct", NULL); if (!bp_ret) { unreal_engine_py_log_error(); return; } Py_DECREF(bp_ret); } void UPyUserWidget::NativeDestruct() { Super::NativeDestruct(); if (!py_user_widget_instance) return; FScopePythonGIL gil; if (!PyObject_HasAttrString(py_user_widget_instance, (char *)"destruct")) return; PyObject *bp_ret = PyObject_CallMethod(py_user_widget_instance, (char *)"destruct", NULL); if (!bp_ret) { unreal_engine_py_log_error(); return; } Py_DECREF(bp_ret); } // Called every frame void UPyUserWidget::NativeTick(const FGeometry & MyGeometry, float InDeltaTime) { Super::NativeTick(MyGeometry, InDeltaTime); if (!py_user_widget_instance) return; FScopePythonGIL gil; if (!PyObject_HasAttrString(py_user_widget_instance, (char *)"tick")) return; PyObject *ret = PyObject_CallMethod(py_user_widget_instance, (char *)"tick", (char *)"Of", py_ue_new_fgeometry(MyGeometry), InDeltaTime); if (!ret) { unreal_engine_py_log_error(); return; } Py_DECREF(ret); } FReply UPyUserWidget::NativeOnMouseButtonDown(const FGeometry & InGeometry, const FPointerEvent & InMouseEvent) { Super::NativeOnMouseButtonDown(InGeometry, InMouseEvent); if (!py_user_widget_instance) return FReply::Unhandled(); FScopePythonGIL gil; if (!PyObject_HasAttrString(py_user_widget_instance, (char *)"on_mouse_button_down")) return FReply::Unhandled(); PyObject *ret = PyObject_CallMethod(py_user_widget_instance, (char *)"on_mouse_button_down", (char *)"OO", py_ue_new_fgeometry(InGeometry), py_ue_new_fpointer_event(InMouseEvent)); if (!ret) { unreal_engine_py_log_error(); return FReply::Unhandled(); } if (PyObject_IsTrue(ret)) { Py_DECREF(ret); return FReply::Handled(); } Py_DECREF(ret); return FReply::Unhandled(); } FReply UPyUserWidget::NativeOnMouseButtonUp(const FGeometry & InGeometry, const FPointerEvent & InMouseEvent) { Super::NativeOnMouseButtonUp(InGeometry, InMouseEvent); if (!py_user_widget_instance) return FReply::Unhandled(); FScopePythonGIL gil; if (!PyObject_HasAttrString(py_user_widget_instance, (char *)"on_mouse_button_up")) return FReply::Unhandled(); PyObject *ret = PyObject_CallMethod(py_user_widget_instance, (char *)"on_mouse_button_up", (char *)"OO", py_ue_new_fgeometry(InGeometry), py_ue_new_fpointer_event(InMouseEvent)); if (!ret) { unreal_engine_py_log_error(); return FReply::Unhandled(); } if (PyObject_IsTrue(ret)) { Py_DECREF(ret); return FReply::Handled(); } Py_DECREF(ret); return FReply::Unhandled(); } FReply UPyUserWidget::NativeOnKeyUp(const FGeometry & InGeometry, const FKeyEvent & InKeyEvent) { Super::NativeOnKeyUp(InGeometry, InKeyEvent); if (!py_user_widget_instance) return FReply::Unhandled(); FScopePythonGIL gil; if (!PyObject_HasAttrString(py_user_widget_instance, (char *)"on_key_up")) return FReply::Unhandled(); PyObject *ret = PyObject_CallMethod(py_user_widget_instance, (char *)"on_key_up", (char *)"OO", py_ue_new_fgeometry(InGeometry), py_ue_new_fkey_event(InKeyEvent)); if (!ret) { unreal_engine_py_log_error(); return FReply::Unhandled(); } if (PyObject_IsTrue(ret)) { Py_DECREF(ret); return FReply::Handled(); } Py_DECREF(ret); return FReply::Unhandled(); } FReply UPyUserWidget::NativeOnKeyDown(const FGeometry & InGeometry, const FKeyEvent & InKeyEvent) { Super::NativeOnKeyDown(InGeometry, InKeyEvent); if (!py_user_widget_instance) return FReply::Unhandled(); FScopePythonGIL gil; if (!PyObject_HasAttrString(py_user_widget_instance, (char *)"on_key_down")) return FReply::Unhandled(); PyObject *ret = PyObject_CallMethod(py_user_widget_instance, (char *)"on_key_down", (char *)"OO", py_ue_new_fgeometry(InGeometry), py_ue_new_fkey_event(InKeyEvent)); if (!ret) { unreal_engine_py_log_error(); return FReply::Unhandled(); } if (PyObject_IsTrue(ret)) { Py_DECREF(ret); return FReply::Handled(); } Py_DECREF(ret); return FReply::Unhandled(); } #if WITH_EDITOR const FText UPyUserWidget::GetPaletteCategory() { return NSLOCTEXT("Python", "Python", "Python"); } #endif void UPyUserWidget::SetSlateWidget(TSharedRef<SWidget> InContent) { if (PyNativeWidgetHost.IsValid()) { PyNativeWidgetHost->SetContent(InContent); } } void UPyUserWidget::ReleaseSlateResources(bool bReleaseChildren) { Super::ReleaseSlateResources(bReleaseChildren); } TSharedRef<SWidget> UPyUserWidget::RebuildWidget() { return Super::RebuildWidget(); } FReply UPyUserWidget::NativeOnMouseWheel(const FGeometry & InGeometry, const FPointerEvent & InMouseEvent) { Super::NativeOnMouseWheel(InGeometry, InMouseEvent); if (!py_user_widget_instance) return FReply::Unhandled(); FScopePythonGIL gil; if (!PyObject_HasAttrString(py_user_widget_instance, (char *)"on_mouse_wheel")) return FReply::Unhandled(); PyObject *ret = PyObject_CallMethod(py_user_widget_instance, (char *)"on_mouse_wheel", (char *)"OO", py_ue_new_fgeometry(InGeometry), py_ue_new_fpointer_event(InMouseEvent)); if (!ret) { unreal_engine_py_log_error(); return FReply::Unhandled(); } if (PyObject_IsTrue(ret)) { Py_DECREF(ret); return FReply::Handled(); } Py_DECREF(ret); return FReply::Unhandled(); } FReply UPyUserWidget::NativeOnMouseMove(const FGeometry & InGeometry, const FPointerEvent & InMouseEvent) { Super::NativeOnMouseMove(InGeometry, InMouseEvent); if (!py_user_widget_instance) return FReply::Unhandled(); FScopePythonGIL gil; if (!PyObject_HasAttrString(py_user_widget_instance, (char *)"on_mouse_move")) return FReply::Unhandled(); PyObject *ret = PyObject_CallMethod(py_user_widget_instance, (char *)"on_mouse_move", (char *)"OO", py_ue_new_fgeometry(InGeometry), py_ue_new_fpointer_event(InMouseEvent)); if (!ret) { unreal_engine_py_log_error(); return FReply::Unhandled(); } if (PyObject_IsTrue(ret)) { Py_DECREF(ret); return FReply::Handled(); } Py_DECREF(ret); return FReply::Unhandled(); } bool UPyUserWidget::NativeIsInteractable() const { if (!py_user_widget_instance) return false; FScopePythonGIL gil; if (!PyObject_HasAttrString(py_user_widget_instance, (char *)"is_interactable")) return false; PyObject *ret = PyObject_CallMethod(py_user_widget_instance, (char *)"is_interactable", nullptr); if (!ret) { unreal_engine_py_log_error(); return false; } if (PyObject_IsTrue(ret)) { Py_DECREF(ret); return true; } Py_DECREF(ret); return false; } #if ENGINE_MINOR_VERSION < 20 void UPyUserWidget::NativePaint(FPaintContext & InContext) const #else int32 UPyUserWidget::NativePaint(const FPaintArgs& Args, const FGeometry& AllottedGeometry, const FSlateRect& MyCullingRect, FSlateWindowElementList& OutDrawElements, int32 LayerId, const FWidgetStyle& InWidgetStyle, bool bParentEnabled) const #endif { #if ENGINE_MINOR_VERSION >= 20 FPaintContext InContext(AllottedGeometry, MyCullingRect, OutDrawElements, LayerId, InWidgetStyle, bParentEnabled); #endif if (!py_user_widget_instance) #if ENGINE_MINOR_VERSION >= 20 return -1; #else return; #endif FScopePythonGIL gil; if (!PyObject_HasAttrString(py_user_widget_instance, (char *)"paint")) #if ENGINE_MINOR_VERSION >= 20 return -1; #else return; #endif PyObject *ret = PyObject_CallMethod(py_user_widget_instance, (char *)"paint", (char *)"O", py_ue_new_fpaint_context(InContext)); if (!ret) { unreal_engine_py_log_error(); #if ENGINE_MINOR_VERSION >= 20 return -1; #else return; #endif } #if ENGINE_MINOR_VERSION >= 20 int32 RetValue = -1; if (PyNumber_Check(ret)) { PyObject *py_value = PyNumber_Long(ret); RetValue = PyLong_AsLong(py_value); Py_DECREF(py_value); } #endif Py_DECREF(ret); #if ENGINE_MINOR_VERSION >= 20 return RetValue; #endif } UPyUserWidget::UPyUserWidget(const FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer) {} UPyUserWidget::~UPyUserWidget() { FScopePythonGIL gil; Py_XDECREF(py_user_widget_instance); #if defined(UEPY_MEMORY_DEBUG) UE_LOG(LogPython, Warning, TEXT("Python UUserWidget %p (mapped to %p) wrapper XDECREF'ed"), this, py_uobject ? py_uobject->py_proxy : nullptr); #endif // this could trigger the distruction of the python/uobject mapper Py_XDECREF(py_uobject); FUnrealEnginePythonHouseKeeper::Get()->UnregisterPyUObject(this); } void UPyUserWidget::CallPythonUserWidgetMethod(FString method_name, FString args) { if (!py_user_widget_instance) return; FScopePythonGIL gil; PyObject *ret = nullptr; if (args.IsEmpty()) { ret = PyObject_CallMethod(py_user_widget_instance, TCHAR_TO_UTF8(*method_name), NULL); } else { ret = PyObject_CallMethod(py_user_widget_instance, TCHAR_TO_UTF8(*method_name), (char *)"s", TCHAR_TO_UTF8(*args)); } if (!ret) { unreal_engine_py_log_error(); return; } Py_DECREF(ret); } ```
/content/code_sandbox/Source/UnrealEnginePython/Private/PyUserWidget.cpp
c++
2016-08-07T05:00:51
2024-08-14T06:32:20
UnrealEnginePython
20tab/UnrealEnginePython
2,715
2,861
```c++ #include "UEPyCallable.h" // destructor static void ue_pycallable_dealloc(ue_PyCallable *self) { #if defined(UEPY_MEMORY_DEBUG) UE_LOG(LogPython, Warning, TEXT("Destroying ue_PyCallable %p mapped to UFunction %p"), self, self->u_function); #endif Py_TYPE(self)->tp_free((PyObject *)self); } static PyObject* ue_pycallable_call(ue_PyCallable *self, PyObject *args, PyObject *kw) { if (!self->u_function || !self->u_target || !self->u_function->IsValidLowLevel() || !self->u_target->IsValidLowLevel() || self->u_function->IsPendingKillOrUnreachable() || self->u_target->IsPendingKillOrUnreachable()) { return PyErr_Format(PyExc_Exception, "UFunction/UObject is in invalid state for python callable"); } return py_ue_ufunction_call(self->u_function, self->u_target, args, 0, kw); } static PyTypeObject ue_PyCallableType = { PyVarObject_HEAD_INIT(NULL, 0) "unreal_engine.Callable", /* tp_name */ sizeof(ue_PyCallable), /* tp_basicsize */ 0, /* tp_itemsize */ (destructor)ue_pycallable_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_reserved */ 0, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ (ternaryfunc)ue_pycallable_call, /* tp_call */ 0, /* tp_str */ 0, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT, /* tp_flags */ "Unreal Engine Python Callable", /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ 0, /* tp_methods */ 0, 0, }; void ue_python_init_callable(PyObject *ue_module) { ue_PyCallableType.tp_new = PyType_GenericNew; if (PyType_Ready(&ue_PyCallableType) < 0) return; Py_INCREF(&ue_PyCallableType); PyModule_AddObject(ue_module, "Callable", (PyObject *)&ue_PyCallableType); } PyObject *py_ue_new_callable(UFunction *u_function, UObject *u_target) { ue_PyCallable *ret = (ue_PyCallable *)PyObject_New(ue_PyCallable, &ue_PyCallableType); ret->u_function = u_function; ret->u_target = u_target; return (PyObject *)ret; } ue_PyCallable *py_ue_is_callable(PyObject *obj) { if (!PyObject_IsInstance(obj, (PyObject *)&ue_PyCallableType)) return nullptr; return (ue_PyCallable *)obj; } ```
/content/code_sandbox/Source/UnrealEnginePython/Private/UEPyCallable.cpp
c++
2016-08-07T05:00:51
2024-08-14T06:32:20
UnrealEnginePython
20tab/UnrealEnginePython
2,715
712
```c++ #include "UEPyAssetUserData.h" #if WITH_EDITOR PyObject *py_ue_asset_import_data(ue_PyUObject * self, PyObject * args) { ue_py_check(self); UStruct *u_struct = (UStruct *)self->ue_object->GetClass(); UClassProperty *u_property = (UClassProperty *)u_struct->FindPropertyByName(TEXT("AssetImportData")); if (!u_property) { return PyErr_Format(PyExc_Exception, "UObject does not have asset import data."); } UAssetImportData *import_data = (UAssetImportData *)u_property->GetPropertyValue_InContainer(self->ue_object); FAssetImportInfo *import_info = &import_data->SourceData; PyObject *ret = PyList_New(import_info->SourceFiles.Num()); for (int i = 0; i < import_info->SourceFiles.Num(); i++) { PyObject *py_source_file = PyDict_New(); PyDict_SetItemString(py_source_file, "absolute_filepath", PyUnicode_FromString(TCHAR_TO_UTF8(*import_data->ResolveImportFilename(import_info->SourceFiles[i].RelativeFilename, NULL)))); PyDict_SetItemString(py_source_file, "relative_filepath", PyUnicode_FromString(TCHAR_TO_UTF8(*import_info->SourceFiles[i].RelativeFilename))); PyDict_SetItemString(py_source_file, "timestamp", PyLong_FromLong(import_info->SourceFiles[i].Timestamp.ToUnixTimestamp())); #if ENGINE_MINOR_VERSION > 19 PyDict_SetItemString(py_source_file, "filehash", PyUnicode_FromString(TCHAR_TO_UTF8(*LexToString(import_info->SourceFiles[i].FileHash)))); #else PyDict_SetItemString(py_source_file, "filehash", PyUnicode_FromString(TCHAR_TO_UTF8(*LexicalConversion::ToString(import_info->SourceFiles[i].FileHash)))); #endif PyList_SetItem(ret, i, py_source_file); } return ret; } PyObject *py_ue_asset_import_data_set_sources(ue_PyUObject * self, PyObject * args) { ue_py_check(self); PyObject *py_files; if (!PyArg_ParseTuple(args, "O:asset_import_data_set_sources", &py_files)) { return nullptr; } TArray<FString> filenames; UStruct *u_struct = (UStruct *)self->ue_object->GetClass(); UClassProperty *u_property = (UClassProperty *)u_struct->FindPropertyByName(TEXT("AssetImportData")); if (!u_property) { return PyErr_Format(PyExc_Exception, "UObject does not have asset import data."); } if (PyUnicodeOrString_Check(py_files)) { filenames.Add(FString(UTF8_TO_TCHAR(UEPyUnicode_AsUTF8(py_files)))); } else { PyObject *py_iter = PyObject_GetIter(py_files); if (!py_iter) { return PyErr_Format(PyExc_Exception, "argument is not a string or an interable of strings"); } while (PyObject *py_item = PyIter_Next(py_iter)) { if (!PyUnicodeOrString_Check(py_item)) { Py_DECREF(py_iter); return PyErr_Format(PyExc_Exception, "argument is not a string or an interable of strings"); } filenames.Add(FString(UTF8_TO_TCHAR(UEPyUnicode_AsUTF8(py_item)))); } Py_DECREF(py_iter); } UAssetImportData *import_data = (UAssetImportData *)u_property->GetPropertyValue_InContainer(self->ue_object); FAssetImportInfo *import_info = &import_data->SourceData; TArray<FAssetImportInfo::FSourceFile> sources; for (FString filename : filenames) { sources.Add(FAssetImportInfo::FSourceFile(filename)); } import_info->SourceFiles = sources; Py_RETURN_NONE; } #endif ```
/content/code_sandbox/Source/UnrealEnginePython/Private/UEPyAssetUserData.cpp
c++
2016-08-07T05:00:51
2024-08-14T06:32:20
UnrealEnginePython
20tab/UnrealEnginePython
2,715
829
```c++ #include "UEPyIPlugin.h" #if WITH_EDITOR #include "Runtime/Projects/Public/Interfaces/IPluginManager.h" static PyObject *py_ue_iplugin_get_name(ue_PyIPlugin *self, PyObject * args) { return PyUnicode_FromString(TCHAR_TO_UTF8(*(self->plugin->GetName()))); } static PyObject *py_ue_iplugin_get_base_dir(ue_PyIPlugin *self, PyObject * args) { return PyUnicode_FromString(TCHAR_TO_UTF8(*(self->plugin->GetBaseDir()))); } static PyObject *py_ue_iplugin_get_content_dir(ue_PyIPlugin *self, PyObject * args) { return PyUnicode_FromString(TCHAR_TO_UTF8(*(self->plugin->GetContentDir()))); } static PyObject *py_ue_iplugin_get_descriptor_file_name(ue_PyIPlugin *self, PyObject * args) { return PyUnicode_FromString(TCHAR_TO_UTF8(*(self->plugin->GetDescriptorFileName()))); } static PyObject *py_ue_iplugin_get_mounted_asset_path(ue_PyIPlugin *self, PyObject * args) { return PyUnicode_FromString(TCHAR_TO_UTF8(*(self->plugin->GetMountedAssetPath()))); } static PyObject *py_ue_iplugin_can_contain_content(ue_PyIPlugin *self, PyObject * args) { if (self->plugin->CanContainContent()) { Py_INCREF(Py_True); return Py_True; } Py_INCREF(Py_False); return Py_False; } static PyObject *py_ue_iplugin_is_enabled(ue_PyIPlugin *self, PyObject * args) { if (self->plugin->IsEnabled()) { Py_INCREF(Py_True); return Py_True; } Py_INCREF(Py_False); return Py_False; } static PyObject *py_ue_iplugin_to_json(ue_PyIPlugin *self, PyObject * args) { PyObject *py_bool; if (!PyArg_ParseTuple(args, "O:to_json", &py_bool)) { return NULL; } bool enabled_by_default = false; if (PyObject_IsTrue(py_bool)) { enabled_by_default = true; } FPluginDescriptor descriptor = self->plugin->GetDescriptor(); FString text; #if ENGINE_MINOR_VERSION < 14 text = descriptor.ToString(); #elif ENGINE_MINOR_VERSION <= 17 descriptor.Write(text, enabled_by_default); #else descriptor.Write(text); #endif return PyUnicode_FromString(TCHAR_TO_UTF8(*text)); } static PyObject *py_ue_iplugin_from_json(ue_PyIPlugin *self, PyObject * args) { char *json; PyObject *py_bool; if (!PyArg_ParseTuple(args, "sO:from_json", &json, &py_bool)) { return NULL; } bool enabled_by_default = false; if (PyObject_IsTrue(py_bool)) { enabled_by_default = true; } FText error; FString text = FString(UTF8_TO_TCHAR(json)); FPluginDescriptor descriptor = self->plugin->GetDescriptor(); #if ENGINE_MINOR_VERSION < 14 if (!descriptor.Read(text, error)) #elif ENGINE_MINOR_VERSION <= 17 if (!descriptor.Read(text, enabled_by_default, error)) #else if (!descriptor.Read(text, error)) #endif { return PyErr_Format(PyExc_Exception, "unable to update descriptor from json"); } Py_INCREF(Py_None); return Py_None; } static PyMethodDef ue_PyIPlugin_methods[] = { { "get_name", (PyCFunction)py_ue_iplugin_get_name, METH_VARARGS, "" }, { "get_base_dir", (PyCFunction)py_ue_iplugin_get_base_dir, METH_VARARGS, "" }, { "get_content_dir", (PyCFunction)py_ue_iplugin_get_content_dir, METH_VARARGS, "" }, { "get_descriptor_file_name", (PyCFunction)py_ue_iplugin_get_descriptor_file_name, METH_VARARGS, "" }, { "get_mounted_asset_path", (PyCFunction)py_ue_iplugin_get_mounted_asset_path, METH_VARARGS, "" }, { "can_contain_content", (PyCFunction)py_ue_iplugin_can_contain_content, METH_VARARGS, "" }, { "is_enabled", (PyCFunction)py_ue_iplugin_is_enabled, METH_VARARGS, "" }, { "to_json", (PyCFunction)py_ue_iplugin_to_json, METH_VARARGS, "" }, { "from_json", (PyCFunction)py_ue_iplugin_from_json, METH_VARARGS, "" }, { NULL } /* Sentinel */ }; static PyObject *py_ue_iplugin_get_category(ue_PyIPlugin *self, void *closure) { return PyUnicode_FromString(TCHAR_TO_UTF8(*(self->plugin->GetDescriptor().Category))); } static PyObject *py_ue_iplugin_get_can_contain_content(ue_PyIPlugin *self, void *closure) { if (self->plugin->GetDescriptor().bCanContainContent) { Py_INCREF(Py_True); return Py_True; } Py_INCREF(Py_False); return Py_False; } static PyObject *py_ue_iplugin_get_enabled_by_default(ue_PyIPlugin *self, void *closure) { #if ENGINE_MINOR_VERSION < 18 if (self->plugin->GetDescriptor().bEnabledByDefault) #else if (self->plugin->GetDescriptor().EnabledByDefault == EPluginEnabledByDefault::Enabled) #endif { Py_INCREF(Py_True); return Py_True; } Py_INCREF(Py_False); return Py_False; } static PyObject *py_ue_iplugin_get_installed(ue_PyIPlugin *self, void *closure) { if (self->plugin->GetDescriptor().bInstalled) { Py_INCREF(Py_True); return Py_True; } Py_INCREF(Py_False); return Py_False; } static PyObject *py_ue_iplugin_get_is_beta_version(ue_PyIPlugin *self, void *closure) { if (self->plugin->GetDescriptor().bIsBetaVersion) { Py_INCREF(Py_True); return Py_True; } Py_INCREF(Py_False); return Py_False; } static PyObject *py_ue_iplugin_created_by(ue_PyIPlugin *self, void *closure) { return PyUnicode_FromString(TCHAR_TO_UTF8(*(self->plugin->GetDescriptor().CreatedBy))); } static PyObject *py_ue_iplugin_created_by_url(ue_PyIPlugin *self, void *closure) { return PyUnicode_FromString(TCHAR_TO_UTF8(*(self->plugin->GetDescriptor().CreatedByURL))); } static PyObject *py_ue_iplugin_description(ue_PyIPlugin *self, void *closure) { return PyUnicode_FromString(TCHAR_TO_UTF8(*(self->plugin->GetDescriptor().Description))); } static PyObject *py_ue_iplugin_docs_url(ue_PyIPlugin *self, void *closure) { return PyUnicode_FromString(TCHAR_TO_UTF8(*(self->plugin->GetDescriptor().DocsURL))); } static PyObject *py_ue_iplugin_friendly_name(ue_PyIPlugin *self, void *closure) { return PyUnicode_FromString(TCHAR_TO_UTF8(*(self->plugin->GetDescriptor().FriendlyName))); } static PyObject *py_ue_iplugin_marketplace_url(ue_PyIPlugin *self, void *closure) { return PyUnicode_FromString(TCHAR_TO_UTF8(*(self->plugin->GetDescriptor().MarketplaceURL))); } static PyObject *py_ue_iplugin_support_url(ue_PyIPlugin *self, void *closure) { return PyUnicode_FromString(TCHAR_TO_UTF8(*(self->plugin->GetDescriptor().SupportURL))); } static PyObject *py_ue_iplugin_version_name(ue_PyIPlugin *self, void *closure) { return PyUnicode_FromString(TCHAR_TO_UTF8(*(self->plugin->GetDescriptor().VersionName))); } static PyObject *py_ue_iplugin_file_version(ue_PyIPlugin *self, void *closure) { #if ENGINE_MINOR_VERSION < 18 return PyLong_FromLong(self->plugin->GetDescriptor().FileVersion); #else return PyLong_FromLong(self->plugin->GetDescriptor().Version); #endif } static PyObject *py_ue_iplugin_version(ue_PyIPlugin *self, void *closure) { return PyLong_FromLong(self->plugin->GetDescriptor().Version); } static PyObject *py_ue_iplugin_get_requires_build_platform(ue_PyIPlugin *self, void *closure) { if (self->plugin->GetDescriptor().bRequiresBuildPlatform) { Py_RETURN_TRUE; } Py_RETURN_FALSE; } static PyGetSetDef ue_PyIPlugin_getseters[] = { { (char*)"category", (getter)py_ue_iplugin_get_category, NULL, (char *)"", NULL }, { (char*)"can_contain_content", (getter)py_ue_iplugin_get_can_contain_content, NULL, (char *)"", NULL }, { (char*)"enabled_by_default", (getter)py_ue_iplugin_get_enabled_by_default, NULL, (char *)"", NULL }, { (char*)"installed", (getter)py_ue_iplugin_get_installed, NULL, (char *)"", NULL }, { (char*)"is_beta_version", (getter)py_ue_iplugin_get_is_beta_version, NULL, (char *)"", NULL }, { (char*)"requires_build_platform", (getter)py_ue_iplugin_get_requires_build_platform, NULL, (char *)"", NULL }, { (char*)"created_by", (getter)py_ue_iplugin_created_by, NULL, (char *)"", NULL }, { (char*)"created_by_url", (getter)py_ue_iplugin_created_by_url, NULL, (char *)"", NULL }, { (char*)"description", (getter)py_ue_iplugin_description, NULL, (char *)"", NULL }, { (char*)"docs_url", (getter)py_ue_iplugin_docs_url, NULL, (char *)"", NULL }, { (char*)"file_version", (getter)py_ue_iplugin_file_version, NULL, (char *)"", NULL }, { (char*)"friendly_name", (getter)py_ue_iplugin_friendly_name, NULL, (char *)"", NULL }, { (char*)"marketplace_url", (getter)py_ue_iplugin_marketplace_url, NULL, (char *)"", NULL }, { (char*)"support_url", (getter)py_ue_iplugin_support_url, NULL, (char *)"", NULL }, { (char*)"version", (getter)py_ue_iplugin_version, NULL, (char *)"", NULL }, { (char*)"version_name", (getter)py_ue_iplugin_version_name, NULL, (char *)"", NULL }, { NULL } /* Sentinel */ }; static PyObject *ue_PyIPlugin_str(ue_PyIPlugin *self) { return PyUnicode_FromFormat("<unreal_engine.IPlugin {'name': '%s'}>", TCHAR_TO_UTF8(*self->plugin->GetName())); } static PyTypeObject ue_PyIPluginType = { PyVarObject_HEAD_INIT(NULL, 0) "unreal_engine.IPlugin", /* tp_name */ sizeof(ue_PyIPlugin), /* tp_basicsize */ 0, /* tp_itemsize */ 0, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_reserved */ 0, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ (reprfunc)ue_PyIPlugin_str, /* tp_str */ 0, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT, /* tp_flags */ "Unreal Engine Editor IPlugin", /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ ue_PyIPlugin_methods, /* tp_methods */ 0, ue_PyIPlugin_getseters, }; void ue_python_init_iplugin(PyObject *ue_module) { ue_PyIPluginType.tp_new = PyType_GenericNew; if (PyType_Ready(&ue_PyIPluginType) < 0) return; Py_INCREF(&ue_PyIPluginType); PyModule_AddObject(ue_module, "IPlugin", (PyObject *)&ue_PyIPluginType); } PyObject *py_ue_new_iplugin(IPlugin *plugin) { ue_PyIPlugin *ret = (ue_PyIPlugin *)PyObject_New(ue_PyIPlugin, &ue_PyIPluginType); ret->plugin = plugin; return (PyObject *)ret; } #endif ```
/content/code_sandbox/Source/UnrealEnginePython/Private/UEPyIPlugin.cpp
c++
2016-08-07T05:00:51
2024-08-14T06:32:20
UnrealEnginePython
20tab/UnrealEnginePython
2,715
2,773
```objective-c #pragma once #include "UEPyModule.h" PyObject *py_ue_vlog(ue_PyUObject *, PyObject *); PyObject *py_ue_vlog_cylinder(ue_PyUObject *, PyObject *); ```
/content/code_sandbox/Source/UnrealEnginePython/Private/UEPyVisualLogger.h
objective-c
2016-08-07T05:00:51
2024-08-14T06:32:20
UnrealEnginePython
20tab/UnrealEnginePython
2,715
41
```c++ #include "UEPyUScriptStruct.h" static PyObject *py_ue_uscriptstruct_get_field(ue_PyUScriptStruct *self, PyObject * args) { char *name; int index = 0; if (!PyArg_ParseTuple(args, "s|i:get_field", &name, &index)) { return nullptr; } UProperty *u_property = self->u_struct->FindPropertyByName(FName(UTF8_TO_TCHAR(name))); if (!u_property) return PyErr_Format(PyExc_Exception, "unable to find property %s", name); return ue_py_convert_property(u_property, self->u_struct_ptr, index); } static PyObject *py_ue_uscriptstruct_get_field_array_dim(ue_PyUScriptStruct *self, PyObject * args) { char *name; if (!PyArg_ParseTuple(args, "s:get_field_array_dim", &name)) { return nullptr; } UProperty *u_property = self->u_struct->FindPropertyByName(FName(UTF8_TO_TCHAR(name))); if (!u_property) return PyErr_Format(PyExc_Exception, "unable to find property %s", name); return PyLong_FromLongLong(u_property->ArrayDim); } static PyObject *py_ue_uscriptstruct_set_field(ue_PyUScriptStruct *self, PyObject * args) { char *name; PyObject *value; int index = 0; if (!PyArg_ParseTuple(args, "sO|i:set_field", &name, &value, &index)) { return nullptr; } UProperty *u_property = self->u_struct->FindPropertyByName(FName(UTF8_TO_TCHAR(name))); if (!u_property) return PyErr_Format(PyExc_Exception, "unable to find property %s", name); if (!ue_py_convert_pyobject(value, u_property, self->u_struct_ptr, index)) { return PyErr_Format(PyExc_Exception, "unable to set property %s", name); } Py_RETURN_NONE; } static PyObject *py_ue_uscriptstruct_fields(ue_PyUScriptStruct *self, PyObject * args) { PyObject *ret = PyList_New(0); for (TFieldIterator<UProperty> PropIt(self->u_struct); PropIt; ++PropIt) { UProperty* property = *PropIt; PyObject *property_name = PyUnicode_FromString(TCHAR_TO_UTF8(*property->GetName())); PyList_Append(ret, property_name); Py_DECREF(property_name); } return ret; } static PyObject *py_ue_uscriptstruct_get_struct(ue_PyUScriptStruct *self, PyObject * args) { Py_RETURN_UOBJECT(self->u_struct); } static PyObject *py_ue_uscriptstruct_clone(ue_PyUScriptStruct *, PyObject *); PyObject *py_ue_uscriptstruct_as_dict(ue_PyUScriptStruct * self, PyObject * args) { PyObject *py_bool = nullptr; if (!PyArg_ParseTuple(args, "|O:as_dict", &py_bool)) { return nullptr; } static const FName DisplayNameKey(TEXT("DisplayName")); PyObject *py_struct_dict = PyDict_New(); TFieldIterator<UProperty> SArgs(self->u_struct); for (; SArgs; ++SArgs) { PyObject *struct_value = ue_py_convert_property(*SArgs, self->u_struct_ptr, 0); if (!struct_value) { Py_DECREF(py_struct_dict); return NULL; } FString prop_name = SArgs->GetName(); #if WITH_EDITOR if (py_bool && PyObject_IsTrue(py_bool)) { if (SArgs->HasMetaData(DisplayNameKey)) { FString display_name = SArgs->GetMetaData(DisplayNameKey); if (display_name.Len() > 0) prop_name = display_name; } } #endif PyDict_SetItemString(py_struct_dict, TCHAR_TO_UTF8(*prop_name), struct_value); } return py_struct_dict; } static PyObject *py_ue_uscriptstruct_ref(ue_PyUScriptStruct *, PyObject *); static PyMethodDef ue_PyUScriptStruct_methods[] = { { "get_field", (PyCFunction)py_ue_uscriptstruct_get_field, METH_VARARGS, "" }, { "set_field", (PyCFunction)py_ue_uscriptstruct_set_field, METH_VARARGS, "" }, { "get_field_array_dim", (PyCFunction)py_ue_uscriptstruct_get_field_array_dim, METH_VARARGS, "" }, { "fields", (PyCFunction)py_ue_uscriptstruct_fields, METH_VARARGS, "" }, { "get_struct", (PyCFunction)py_ue_uscriptstruct_get_struct, METH_VARARGS, "" }, { "clone", (PyCFunction)py_ue_uscriptstruct_clone, METH_VARARGS, "" }, { "as_dict", (PyCFunction)py_ue_uscriptstruct_as_dict, METH_VARARGS, "" }, { "ref", (PyCFunction)py_ue_uscriptstruct_ref, METH_VARARGS, "" }, { NULL } /* Sentinel */ }; static PyObject *ue_PyUScriptStruct_str(ue_PyUScriptStruct *self) { return PyUnicode_FromFormat("<unreal_engine.UScriptStruct {'struct': '%s', 'size': %d, 'ptr': %p}>", TCHAR_TO_UTF8(*self->u_struct->GetName()), self->u_struct->GetStructureSize(), self->u_struct_ptr); } static UProperty *get_field_from_name(UScriptStruct *u_struct, char *name) { FString attr = UTF8_TO_TCHAR(name); UProperty *u_property = u_struct->FindPropertyByName(FName(*attr)); if (u_property) return u_property; #if WITH_EDITOR static const FName DisplayNameKey(TEXT("DisplayName")); // if the property is not found, attempt to search for DisplayName for (TFieldIterator<UProperty> prop(u_struct); prop; ++prop) { UProperty *property = *prop; if (property->HasMetaData(DisplayNameKey)) { FString display_name = property->GetMetaData(DisplayNameKey); if (display_name.Len() > 0 && attr.Equals(display_name)) { return property; } } } #endif return nullptr; } UProperty *ue_struct_get_field_from_name(UScriptStruct *u_struct, char *name) { return get_field_from_name(u_struct, name); } static PyObject *ue_PyUScriptStruct_getattro(ue_PyUScriptStruct *self, PyObject *attr_name) { PyObject *ret = PyObject_GenericGetAttr((PyObject *)self, attr_name); if (!ret) { if (PyUnicodeOrString_Check(attr_name)) { const char *attr = UEPyUnicode_AsUTF8(attr_name); // first check for property UProperty *u_property = get_field_from_name(self->u_struct, (char *)attr); if (u_property) { // swallow previous exception PyErr_Clear(); return ue_py_convert_property(u_property, self->u_struct_ptr, 0); } } } return ret; } static int ue_PyUScriptStruct_setattro(ue_PyUScriptStruct *self, PyObject *attr_name, PyObject *value) { // first of all check for UProperty if (PyUnicodeOrString_Check(attr_name)) { const char *attr = UEPyUnicode_AsUTF8(attr_name); // first check for property UProperty *u_property = get_field_from_name(self->u_struct, (char *)attr); if (u_property) { if (ue_py_convert_pyobject(value, u_property, self->u_struct_ptr, 0)) { return 0; } PyErr_SetString(PyExc_ValueError, "invalid value for UProperty"); return -1; } } return PyObject_GenericSetAttr((PyObject *)self, attr_name, value); } // destructor static void ue_PyUScriptStruct_dealloc(ue_PyUScriptStruct *self) { #if defined(UEPY_MEMORY_DEBUG) UE_LOG(LogPython, Warning, TEXT("Destroying ue_PyUScriptStruct %p with size %d"), self, self->u_struct->GetStructureSize()); #endif if (self->u_struct_owned) { FMemory::Free(self->u_struct_ptr); } Py_TYPE(self)->tp_free((PyObject *)self); } static PyTypeObject ue_PyUScriptStructType = { PyVarObject_HEAD_INIT(NULL, 0) "unreal_engine.UScriptStruct", /* tp_name */ sizeof(ue_PyUScriptStruct), /* tp_basicsize */ 0, /* tp_itemsize */ (destructor)ue_PyUScriptStruct_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_reserved */ 0, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ (reprfunc)ue_PyUScriptStruct_str, /* tp_str */ (getattrofunc)ue_PyUScriptStruct_getattro, /* tp_getattro */ (setattrofunc)ue_PyUScriptStruct_setattro, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT, /* tp_flags */ "Unreal Engine Editor UScriptStruct", /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ ue_PyUScriptStruct_methods, /* tp_methods */ 0, 0, }; static int ue_py_uscriptstruct_init(ue_PyUScriptStruct *self, PyObject *args, PyObject *kwargs) { PyObject *py_struct; if (!PyArg_ParseTuple(args, "O", &py_struct)) return -1; if (!ue_is_pyuobject(py_struct)) { PyErr_SetString(PyExc_Exception, "argument is not a UScriptStruct"); return -1; } ue_PyUObject *py_u_obj = (ue_PyUObject *)py_struct; if (!py_u_obj->ue_object->IsA<UScriptStruct>()) { PyErr_SetString(PyExc_Exception, "argument is not a UScriptStruct"); return -1; } self->u_struct = (UScriptStruct *)py_u_obj->ue_object; self->u_struct_ptr = (uint8*)FMemory::Malloc(self->u_struct->GetStructureSize()); self->u_struct->InitializeStruct(self->u_struct_ptr); #if WITH_EDITOR self->u_struct->InitializeDefaultValue(self->u_struct_ptr); #endif self->u_struct_owned = 1; return 0; } // get the original pointer of a struct (dumb function for backward compatibility with older scripts from // a dark age where strctures were passed by value) static PyObject *py_ue_uscriptstruct_ref(ue_PyUScriptStruct *self, PyObject * args) { Py_INCREF(self); return (PyObject *)self; } static PyObject *ue_py_uscriptstruct_richcompare(ue_PyUScriptStruct *u_struct1, PyObject *py_obj, int op) { ue_PyUScriptStruct *u_struct2 = py_ue_is_uscriptstruct(py_obj); if (!u_struct2 || (op != Py_EQ && op != Py_NE)) { return PyErr_Format(PyExc_NotImplementedError, "can only compare with another UScriptStruct"); } bool equals = (u_struct1->u_struct == u_struct2->u_struct && !memcmp(u_struct1->u_struct_ptr, u_struct2->u_struct_ptr, u_struct1->u_struct->GetStructureSize())); if (op == Py_EQ) { if (equals) { Py_RETURN_TRUE; } Py_RETURN_FALSE; } if (equals) { Py_RETURN_FALSE; } Py_RETURN_TRUE; } void ue_python_init_uscriptstruct(PyObject *ue_module) { ue_PyUScriptStructType.tp_new = PyType_GenericNew; ue_PyUScriptStructType.tp_richcompare = (richcmpfunc)ue_py_uscriptstruct_richcompare; ue_PyUScriptStructType.tp_init = (initproc)ue_py_uscriptstruct_init; if (PyType_Ready(&ue_PyUScriptStructType) < 0) return; Py_INCREF(&ue_PyUScriptStructType); PyModule_AddObject(ue_module, "UScriptStruct", (PyObject *)&ue_PyUScriptStructType); } PyObject *py_ue_new_uscriptstruct(UScriptStruct *u_struct, uint8 *data) { ue_PyUScriptStruct *ret = (ue_PyUScriptStruct *)PyObject_New(ue_PyUScriptStruct, &ue_PyUScriptStructType); ret->u_struct = u_struct; ret->u_struct_ptr = data; ret->u_struct_owned = 0; return (PyObject *)ret; } PyObject *py_ue_new_owned_uscriptstruct(UScriptStruct *u_struct, uint8 *data) { ue_PyUScriptStruct *ret = (ue_PyUScriptStruct *)PyObject_New(ue_PyUScriptStruct, &ue_PyUScriptStructType); ret->u_struct = u_struct; uint8 *struct_data = (uint8*)FMemory::Malloc(u_struct->GetStructureSize()); ret->u_struct->InitializeStruct(struct_data); ret->u_struct->CopyScriptStruct(struct_data, data); ret->u_struct_ptr = struct_data; ret->u_struct_owned = 1; return (PyObject *)ret; } PyObject *py_ue_new_owned_uscriptstruct_zero_copy(UScriptStruct *u_struct, uint8 *data) { ue_PyUScriptStruct *ret = (ue_PyUScriptStruct *)PyObject_New(ue_PyUScriptStruct, &ue_PyUScriptStructType); ret->u_struct = u_struct; ret->u_struct_ptr = data; ret->u_struct_owned = 1; return (PyObject *)ret; } static PyObject *py_ue_uscriptstruct_clone(ue_PyUScriptStruct *self, PyObject * args) { ue_PyUScriptStruct *ret = (ue_PyUScriptStruct *)PyObject_New(ue_PyUScriptStruct, &ue_PyUScriptStructType); ret->u_struct = self->u_struct; uint8 *struct_data = (uint8*)FMemory::Malloc(self->u_struct->GetStructureSize()); ret->u_struct->InitializeStruct(struct_data); ret->u_struct->CopyScriptStruct(struct_data, self->u_struct_ptr); ret->u_struct_ptr = struct_data; ret->u_struct_owned = 1; return (PyObject *)ret; } ue_PyUScriptStruct *py_ue_is_uscriptstruct(PyObject *obj) { if (!PyObject_IsInstance(obj, (PyObject *)&ue_PyUScriptStructType)) return nullptr; return (ue_PyUScriptStruct *)obj; } ```
/content/code_sandbox/Source/UnrealEnginePython/Private/UEPyUScriptStruct.cpp
c++
2016-08-07T05:00:51
2024-08-14T06:32:20
UnrealEnginePython
20tab/UnrealEnginePython
2,715
3,320
```c++ #include "UEPyEditor.h" #if WITH_EDITOR #include "Developer/AssetTools/Public/AssetToolsModule.h" #include "Editor/UnrealEd/Classes/Factories/Factory.h" #include "Runtime/AssetRegistry/Public/AssetRegistryModule.h" #include "Kismet2/KismetEditorUtilities.h" #include "Editor/ContentBrowser/Public/ContentBrowserModule.h" #include "Editor/UnrealEd/Public/PackageTools.h" #include "UnrealEd.h" #include "FbxMeshUtils.h" #include "Kismet2/BlueprintEditorUtils.h" #include "Editor/LevelEditor/Public/LevelEditorActions.h" #include "Editor/UnrealEd/Public/EditorLevelUtils.h" #include "Runtime/Projects/Public/Interfaces/IPluginManager.h" #include "ObjectTools.h" #include "Developer/AssetTools/Public/IAssetTools.h" #include "Editor/ContentBrowser/Public/IContentBrowserSingleton.h" #include "Runtime/Engine/Classes/EdGraph/EdGraphPin.h" #include "Runtime/Engine/Classes/EdGraph/EdGraphSchema.h" #include "Toolkits/AssetEditorManager.h" #include "LevelEditor.h" #include "Editor/LandscapeEditor/Public/LandscapeEditorUtils.h" #include "Editor/LandscapeEditor/Public/LandscapeEditorModule.h" #include "Editor/LandscapeEditor/Public/LandscapeFileFormatInterface.h" #include "Developer/Settings/Public/ISettingsModule.h" #include "Engine/Blueprint.h" #include "Wrappers/UEPyFARFilter.h" #include "Wrappers/UEPyFVector.h" #include "Wrappers/UEPyFAssetData.h" #include "Wrappers/UEPyFEditorViewportClient.h" #include "Wrappers/UEPyIAssetEditorInstance.h" #include "Editor/MainFrame/Public/Interfaces/IMainFrameModule.h" #include "Runtime/Core/Public/HAL/ThreadHeartBeat.h" #include "Runtime/Engine/Public/EditorSupportDelegates.h" #include "UEPyIPlugin.h" PyObject *py_unreal_engine_redraw_all_viewports(PyObject * self, PyObject * args) { FEditorSupportDelegates::RedrawAllViewports.Broadcast(); Py_RETURN_NONE; } PyObject *py_unreal_engine_update_ui(PyObject * self, PyObject * args) { FEditorSupportDelegates::UpdateUI.Broadcast(); Py_RETURN_NONE; } PyObject *py_unreal_engine_editor_play_in_viewport(PyObject * self, PyObject * args) { PyObject *py_vector = nullptr; PyObject *py_rotator = nullptr; if (!PyArg_ParseTuple(args, "|OO:editor_play_in_viewport", &py_vector, &py_rotator)) { return NULL; } FVector v; FRotator r; if (py_vector) { ue_PyFVector *vector = py_ue_is_fvector(py_vector); if (!vector) return PyErr_Format(PyExc_Exception, "argument is not a FVector"); v = vector->vec; } if (py_rotator) { ue_PyFRotator *rotator = py_ue_is_frotator(py_rotator); if (!rotator) return PyErr_Format(PyExc_Exception, "argument is not a FRotator"); r = rotator->rot; } FLevelEditorModule &EditorModule = FModuleManager::LoadModuleChecked<FLevelEditorModule>("LevelEditor"); if (!EditorModule.GetFirstActiveViewport().IsValid()) return PyErr_Format(PyExc_Exception, "no active LevelEditor Viewport"); Py_BEGIN_ALLOW_THREADS; GEditor->RequestPlaySession(py_vector == nullptr, EditorModule.GetFirstActiveViewport(), true, &v, &r); Py_END_ALLOW_THREADS; Py_RETURN_NONE; } PyObject *py_unreal_engine_request_play_session(PyObject * self, PyObject * args) { PyObject *py_at_player_start = nullptr; PyObject *py_simulate_in_editor = nullptr; if (!PyArg_ParseTuple(args, "|OO:request_play_session", &py_at_player_start, &py_simulate_in_editor)) { return nullptr; } bool bAtPlayerStart = py_at_player_start && PyObject_IsTrue(py_at_player_start); bool bSimulate = py_simulate_in_editor && PyObject_IsTrue(py_simulate_in_editor); Py_BEGIN_ALLOW_THREADS; GEditor->RequestPlaySession(bAtPlayerStart, nullptr, bSimulate); Py_END_ALLOW_THREADS; Py_RETURN_NONE; } PyObject *py_unreal_engine_get_editor_world(PyObject * self, PyObject * args) { if (!GEditor) return PyErr_Format(PyExc_Exception, "no GEditor found"); UWorld *world = GEditor->GetEditorWorldContext().World(); Py_RETURN_UOBJECT(world); } PyObject *py_unreal_engine_console_exec(PyObject * self, PyObject * args) { char *command; if (!GEditor) return PyErr_Format(PyExc_Exception, "no GEditor found"); if (!PyArg_ParseTuple(args, "s:console_exec", &command)) { return NULL; } Py_BEGIN_ALLOW_THREADS; GEditor->Exec(GEditor->GetEditorWorldContext().World(), UTF8_TO_TCHAR(command), *GLog); Py_END_ALLOW_THREADS; Py_RETURN_NONE; } PyObject *py_unreal_engine_allow_actor_script_execution_in_editor(PyObject * self, PyObject * args) { if (!GEditor) return PyErr_Format(PyExc_Exception, "no GEditor found"); PyObject *obj = nullptr; if (!PyArg_ParseTuple(args, "O:allow_actor_script_execution_in_editor", &obj)) { return NULL; } bool enable = false; if (PyObject_IsTrue(obj)) enable = true; GAllowActorScriptExecutionInEditor = enable; Py_RETURN_NONE; } PyObject *py_unreal_engine_editor_get_selected_actors(PyObject * self, PyObject * args) { if (!GEditor) return PyErr_Format(PyExc_Exception, "no GEditor found"); PyObject *actors = PyList_New(0); USelection *selection = GEditor->GetSelectedActors(); int32 nums = selection->CountSelections<UObject>(); for (int32 i = 0; i < nums; i++) { UObject *obj = selection->GetSelectedObject(i); if (!obj->IsA<AActor>()) continue; AActor *actor = (AActor *)obj; ue_PyUObject *item = ue_get_python_uobject(actor); if (item) PyList_Append(actors, (PyObject *)item); } return actors; } PyObject *py_unreal_engine_editor_command_build(PyObject * self, PyObject * args) { if (!GEditor) return PyErr_Format(PyExc_Exception, "no GEditor found"); Py_BEGIN_ALLOW_THREADS; FLevelEditorActionCallbacks::Build_Execute(); Py_END_ALLOW_THREADS; Py_RETURN_NONE; } PyObject *py_unreal_engine_editor_command_save_current_level(PyObject * self, PyObject * args) { Py_BEGIN_ALLOW_THREADS; FLevelEditorActionCallbacks::Save(); Py_END_ALLOW_THREADS; Py_RETURN_NONE; } PyObject *py_unreal_engine_editor_command_save_all_levels(PyObject * self, PyObject * args) { Py_BEGIN_ALLOW_THREADS; FLevelEditorActionCallbacks::SaveAllLevels(); Py_END_ALLOW_THREADS; Py_RETURN_NONE; } PyObject *py_unreal_engine_editor_save_all(PyObject * self, PyObject * args) { Py_BEGIN_ALLOW_THREADS; FEditorFileUtils::SaveDirtyPackages(false, true, true, false, false, false); Py_END_ALLOW_THREADS; Py_RETURN_NONE; } PyObject *py_unreal_engine_editor_command_build_lighting(PyObject * self, PyObject * args) { Py_BEGIN_ALLOW_THREADS; FLevelEditorActionCallbacks::BuildLightingOnly_Execute(); Py_END_ALLOW_THREADS; Py_RETURN_NONE; } PyObject *py_unreal_engine_editor_deselect_actors(PyObject * self, PyObject * args) { GEditor->SelectNone(true, true, false); Py_RETURN_NONE; } PyObject *py_unreal_engine_editor_play(PyObject * self, PyObject * args) { PyObject *py_vector = nullptr; PyObject *py_rotator = nullptr; if (!PyArg_ParseTuple(args, "|OO:editor_play", &py_vector, &py_rotator)) { return NULL; } FVector v; FRotator r; if (py_vector) { ue_PyFVector *vector = py_ue_is_fvector(py_vector); if (!vector) return PyErr_Format(PyExc_Exception, "argument is not a FVector"); v = vector->vec; } if (py_rotator) { ue_PyFRotator *rotator = py_ue_is_frotator(py_rotator); if (!rotator) return PyErr_Format(PyExc_Exception, "argument is not a FRotator"); r = rotator->rot; } Py_BEGIN_ALLOW_THREADS; #if ENGINE_MINOR_VERSION >= 17 const FString mobile_device = FString(""); GEditor->RequestPlaySession(&v, &r, false, false, mobile_device); #else GEditor->RequestPlaySession(&v, &r, false, false); #endif Py_END_ALLOW_THREADS; Py_RETURN_NONE; } PyObject *py_unreal_engine_editor_select_actor(PyObject * self, PyObject * args) { if (!GEditor) return PyErr_Format(PyExc_Exception, "no GEditor found"); PyObject *obj; if (!PyArg_ParseTuple(args, "O:editor_select_actor", &obj)) { return nullptr; } AActor *actor = ue_py_check_type<AActor>(obj); if (!actor) return PyErr_Format(PyExc_Exception, "uobject is not an Actor"); GEditor->SelectActor(actor, true, true); Py_RETURN_NONE; } PyObject *py_unreal_engine_import_asset(PyObject * self, PyObject * args) { if (!GEditor) return PyErr_Format(PyExc_Exception, "no GEditor found"); //char *filename; PyObject * assetsObject = nullptr; char *destination; PyObject *obj = nullptr; PyObject *py_sync = nullptr; if (!PyArg_ParseTuple(args, "Os|OO:import_asset", &assetsObject, &destination, &obj, &py_sync)) { return nullptr; } FString Result; // avoid crash on wrong path if (!FPackageName::TryConvertLongPackageNameToFilename(UTF8_TO_TCHAR(destination), Result, "")) { return PyErr_Format(PyExc_Exception, "invalid asset root path"); } UClass *factory_class = nullptr; UFactory *factory = nullptr; bool sync_to_browser = false; if (!obj || obj == Py_None) { factory_class = nullptr; } else if (ue_is_pyuobject(obj)) { ue_PyUObject *py_factory = (ue_PyUObject *)obj; if (py_factory->ue_object->IsA<UClass>()) { factory_class = (UClass *)py_factory->ue_object; } else if (py_factory->ue_object->IsA<UFactory>()) { factory = (UFactory *)py_factory->ue_object; } else { return PyErr_Format(PyExc_Exception, "uobject is not a Class"); } } else if (PyUnicodeOrString_Check(obj)) { const char *class_name = UEPyUnicode_AsUTF8(obj); UClass *u_class = FindObject<UClass>(ANY_PACKAGE, UTF8_TO_TCHAR(class_name)); if (u_class) { ue_PyUObject *py_obj = ue_get_python_uobject(u_class); if (!py_obj) { return PyErr_Format(PyExc_Exception, "invalid uobject"); } factory_class = (UClass *)py_obj->ue_object; } } else { return PyErr_Format(PyExc_Exception, "invalid uobject"); } if (factory_class) { factory = NewObject<UFactory>(GetTransientPackage(), factory_class); if (!factory) { return PyErr_Format(PyExc_Exception, "unable to create factory"); } } TArray<FString> files; if (PyList_Check(assetsObject)) { // parse the list object int numLines = PyList_Size(assetsObject); if (numLines <= 0) { return PyErr_Format(PyExc_Exception, "Asset paths is not a valid list"); } for (int i = 0; i < numLines; ++i) { PyObject * strObj = PyList_GetItem(assetsObject, i); #if PY_MAJOR_VERSION >= 3 char * filename = PyBytes_AS_STRING(PyUnicode_AsEncodedString(strObj, "utf-8", "Error")); #else char * filename = PyString_AsString(PyObject_Str(strObj)); #endif files.Add(UTF8_TO_TCHAR(filename)); } } else if (PyUnicodeOrString_Check(assetsObject)) { #if PY_MAJOR_VERSION >= 3 char * filename = PyBytes_AS_STRING(PyUnicode_AsEncodedString(assetsObject, "utf-8", "Error")); #else char * filename = PyString_AsString(PyObject_Str(assetsObject)); #endif files.Add(UTF8_TO_TCHAR(filename)); } else { return PyErr_Format(PyExc_Exception, "Not a string nor valid list of string"); } if (py_sync && PyObject_IsTrue(py_sync)) { sync_to_browser = true; } TArray<UObject *> objects; Py_BEGIN_ALLOW_THREADS; FAssetToolsModule& AssetToolsModule = FModuleManager::LoadModuleChecked<FAssetToolsModule>("AssetTools"); objects = AssetToolsModule.Get().ImportAssets(files, UTF8_TO_TCHAR(destination), factory, sync_to_browser); Py_END_ALLOW_THREADS; if (objects.Num() == 1) { UObject *object = objects[0]; Py_RETURN_UOBJECT(object); } else if (objects.Num() > 1) { PyObject *assets_list = PyList_New(0); for (UObject *object : objects) { ue_PyUObject *ret = ue_get_python_uobject(object); if (!ret) { Py_DECREF(assets_list); return PyErr_Format(PyExc_Exception, "PyUObject is in invalid state"); } PyList_Append(assets_list, (PyObject *)ret); } return assets_list; } Py_RETURN_NONE; } PyObject *py_unreal_engine_editor_tick(PyObject * self, PyObject * args) { float delta_seconds = FApp::GetDeltaTime(); PyObject *py_idle = nullptr; if (!PyArg_ParseTuple(args, "|fO:editor_tick", &delta_seconds, &py_idle)) { return NULL; } bool bIdle = false; if (py_idle && PyObject_IsTrue(py_idle)) bIdle = true; Py_BEGIN_ALLOW_THREADS; GEditor->Tick(delta_seconds, bIdle); Py_END_ALLOW_THREADS; Py_RETURN_NONE; } PyObject *py_unreal_engine_message_dialog_open(PyObject * self, PyObject * args) { if (!GEditor) return PyErr_Format(PyExc_Exception, "no GEditor found"); int app_msg_type; char *text; if (!PyArg_ParseTuple(args, "is:message_dialog_open", &app_msg_type, &text)) { return nullptr; } EAppReturnType::Type ret; Py_BEGIN_ALLOW_THREADS; ret = FMessageDialog::Open((EAppMsgType::Type) app_msg_type, FText::FromString(UTF8_TO_TCHAR(text))); Py_END_ALLOW_THREADS; return PyLong_FromLong(ret); } PyObject *py_unreal_engine_create_modal_save_asset_dialog(PyObject * self, PyObject * args) { char *title = (char *)""; char *path = (char*)""; char *default_name = (char*)""; if (!PyArg_ParseTuple(args, "|sss:create_modal_save_asset_dialog", &title, &path, &default_name)) { return nullptr; } FString ret; Py_BEGIN_ALLOW_THREADS; FSaveAssetDialogConfig config; config.DialogTitleOverride = FText::FromString(FString(UTF8_TO_TCHAR(title))); config.DefaultPath = FString(UTF8_TO_TCHAR(path)); config.DefaultAssetName = FString(UTF8_TO_TCHAR(default_name)); config.ExistingAssetPolicy = ESaveAssetDialogExistingAssetPolicy::AllowButWarn; FContentBrowserModule &ContentBrowserModule = FModuleManager::LoadModuleChecked<FContentBrowserModule>("ContentBrowser"); ret = ContentBrowserModule.Get().CreateModalSaveAssetDialog(config); Py_END_ALLOW_THREADS; if (ret.IsEmpty()) { Py_RETURN_NONE; } return PyUnicode_FromString(TCHAR_TO_UTF8(*ret)); } PyObject *py_unreal_engine_get_asset(PyObject * self, PyObject * args) { char *path; if (!PyArg_ParseTuple(args, "s:get_asset", &path)) { return NULL; } if (!GEditor) return PyErr_Format(PyExc_Exception, "no GEditor found"); FAssetRegistryModule& AssetRegistryModule = FModuleManager::GetModuleChecked<FAssetRegistryModule>("AssetRegistry"); FAssetData asset = AssetRegistryModule.Get().GetAssetByObjectPath(UTF8_TO_TCHAR(path)); if (!asset.IsValid()) return PyErr_Format(PyExc_Exception, "unable to find asset %s", path); Py_RETURN_UOBJECT(asset.GetAsset()); } PyObject *py_unreal_engine_is_loading_assets(PyObject * self, PyObject * args) { if (!GEditor) return PyErr_Format(PyExc_Exception, "no GEditor found"); FAssetRegistryModule& AssetRegistryModule = FModuleManager::GetModuleChecked<FAssetRegistryModule>("AssetRegistry"); if (AssetRegistryModule.Get().IsLoadingAssets()) Py_RETURN_TRUE; Py_RETURN_FALSE; } PyObject *py_unreal_engine_wait_for_assets(PyObject * self, PyObject * args) { if (!GEditor) return PyErr_Format(PyExc_Exception, "no GEditor found"); FAssetRegistryModule& AssetRegistryModule = FModuleManager::GetModuleChecked<FAssetRegistryModule>("AssetRegistry"); while (AssetRegistryModule.Get().IsLoadingAssets()) { Py_BEGIN_ALLOW_THREADS; AssetRegistryModule.Get().Tick(-1.0f); FThreadHeartBeat::Get().HeartBeat(); FPlatformProcess::SleepNoStats(0.0001f); Py_END_ALLOW_THREADS; } Py_RETURN_NONE; } PyObject *py_unreal_engine_find_asset(PyObject * self, PyObject * args) { char *path; if (!PyArg_ParseTuple(args, "s:find_asset", &path)) { return NULL; } if (!GEditor) return PyErr_Format(PyExc_Exception, "no GEditor found"); FAssetRegistryModule& AssetRegistryModule = FModuleManager::GetModuleChecked<FAssetRegistryModule>("AssetRegistry"); FAssetData asset = AssetRegistryModule.Get().GetAssetByObjectPath(UTF8_TO_TCHAR(path)); if (!asset.IsValid()) { Py_RETURN_NONE; } Py_RETURN_UOBJECT(asset.GetAsset()); } PyObject *py_unreal_engine_create_asset(PyObject * self, PyObject * args) { char *asset_name; char *package_path; PyObject *py_class; PyObject *py_factory; if (!PyArg_ParseTuple(args, "ssOO:create_asset", &asset_name, &package_path, &py_class, &py_factory)) { return nullptr; } if (!GEditor) return PyErr_Format(PyExc_Exception, "no GEditor found"); UClass *uclass = ue_py_check_type<UClass>(py_class); if (!uclass) return PyErr_Format(PyExc_Exception, "argument is not a UClass"); UFactory *factory = ue_py_check_type<UFactory>(py_factory); if (!factory) return PyErr_Format(PyExc_Exception, "argument is not a UFactory"); FAssetToolsModule& AssetToolsModule = FModuleManager::LoadModuleChecked<FAssetToolsModule>("AssetTools"); UObject *uobject = AssetToolsModule.Get().CreateAsset(FString(UTF8_TO_TCHAR(asset_name)), FString(UTF8_TO_TCHAR(package_path)), uclass, factory); if (!uobject) return PyErr_Format(PyExc_Exception, "unable to create asset"); Py_RETURN_UOBJECT(uobject); } PyObject *py_unreal_engine_get_asset_referencers(PyObject * self, PyObject * args) { char *path; int depency_type = (int)EAssetRegistryDependencyType::All; if (!PyArg_ParseTuple(args, "s|i:get_asset_referencers", &path, &depency_type)) { return nullptr; } if (!GEditor) return PyErr_Format(PyExc_Exception, "no GEditor found"); FAssetRegistryModule& AssetRegistryModule = FModuleManager::GetModuleChecked<FAssetRegistryModule>("AssetRegistry"); TArray<FName> referencers; AssetRegistryModule.Get().GetReferencers(UTF8_TO_TCHAR(path), referencers, (EAssetRegistryDependencyType::Type) depency_type); PyObject *referencers_list = PyList_New(0); for (FName name : referencers) { PyList_Append(referencers_list, PyUnicode_FromString(TCHAR_TO_UTF8(*name.ToString()))); } return referencers_list; } PyObject *py_unreal_engine_get_asset_identifier_referencers(PyObject * self, PyObject * args) { char *path; int depency_type = (int)EAssetRegistryDependencyType::All; if (!PyArg_ParseTuple(args, "s|i:get_asset_identifier_referencers", &path, &depency_type)) { return nullptr; } if (!GEditor) return PyErr_Format(PyExc_Exception, "no GEditor found"); FAssetRegistryModule& AssetRegistryModule = FModuleManager::GetModuleChecked<FAssetRegistryModule>("AssetRegistry"); TArray<FAssetIdentifier> referencers; AssetRegistryModule.Get().GetReferencers(FAssetIdentifier::FromString(UTF8_TO_TCHAR(path)), referencers, (EAssetRegistryDependencyType::Type) depency_type); PyObject *referencers_list = PyList_New(0); for (FAssetIdentifier identifier : referencers) { PyList_Append(referencers_list, PyUnicode_FromString(TCHAR_TO_UTF8(*identifier.ToString()))); } return referencers_list; } PyObject *py_unreal_engine_get_asset_dependencies(PyObject * self, PyObject * args) { char *path; int depency_type = (int)EAssetRegistryDependencyType::All; if (!PyArg_ParseTuple(args, "s|i:get_asset_dependencies", &path, &depency_type)) { return NULL; } if (!GEditor) return PyErr_Format(PyExc_Exception, "no GEditor found"); FAssetRegistryModule& AssetRegistryModule = FModuleManager::GetModuleChecked<FAssetRegistryModule>("AssetRegistry"); TArray<FName> dependencies; AssetRegistryModule.Get().GetDependencies(UTF8_TO_TCHAR(path), dependencies, (EAssetRegistryDependencyType::Type) depency_type); PyObject *dependencies_list = PyList_New(0); for (FName name : dependencies) { PyList_Append(dependencies_list, PyUnicode_FromString(TCHAR_TO_UTF8(*name.ToString()))); } return dependencies_list; } PyObject *py_unreal_engine_get_long_package_path(PyObject * self, PyObject * args) { char *path; if (!PyArg_ParseTuple(args, "s:get_long_package_path", &path)) { return NULL; } const FString package_path = FPackageName::GetLongPackagePath(UTF8_TO_TCHAR(path)); return PyUnicode_FromString(TCHAR_TO_UTF8(*(package_path))); } PyObject *py_unreal_engine_get_long_package_asset_name(PyObject * self, PyObject * args) { char *path; if (!PyArg_ParseTuple(args, "s:get_long_package_asset_name", &path)) { return NULL; } const FString asset_name = FPackageName::GetLongPackageAssetName(UTF8_TO_TCHAR(path)); return PyUnicode_FromString(TCHAR_TO_UTF8(*(asset_name))); } PyObject *py_unreal_engine_rename_asset(PyObject * self, PyObject * args) { char *path; char *destination; PyObject *py_only_soft = nullptr; if (!PyArg_ParseTuple(args, "ss|O:rename_asset", &path, &destination, &py_only_soft)) { return nullptr; } if (!GEditor) return PyErr_Format(PyExc_Exception, "no GEditor found"); FAssetRegistryModule& AssetRegistryModule = FModuleManager::GetModuleChecked<FAssetRegistryModule>("AssetRegistry"); FAssetData asset = AssetRegistryModule.Get().GetAssetByObjectPath(UTF8_TO_TCHAR(path)); if (!asset.IsValid()) return PyErr_Format(PyExc_Exception, "unable to find asset %s", path); FAssetToolsModule& AssetToolsModule = FModuleManager::LoadModuleChecked<FAssetToolsModule>("AssetTools"); TArray<FAssetRenameData> AssetsAndNames; FString Destination = FString(UTF8_TO_TCHAR(destination)); #if ENGINE_MINOR_VERSION > 17 FAssetRenameData RenameData; RenameData.Asset = asset.GetAsset(); if (Destination.StartsWith("/")) { RenameData.NewPackagePath = FPackageName::GetLongPackagePath(Destination); RenameData.NewName = FPackageName::GetShortName(Destination); } else { RenameData.NewPackagePath = FPackageName::GetLongPackagePath(UTF8_TO_TCHAR(path)); RenameData.NewName = Destination; } if (py_only_soft && PyObject_IsTrue(py_only_soft)) { RenameData.bOnlyFixSoftReferences = true; } #else FAssetRenameData RenameData(TWeakObjectPtr<UObject>(asset.GetAsset()), FPackageName::GetLongPackagePath(UTF8_TO_TCHAR(path)), Destination.StartsWith("/") ? FPackageName::GetShortName(Destination) : Destination); #endif AssetsAndNames.Add(RenameData); #if ENGINE_MINOR_VERSION < 19 AssetToolsModule.Get().RenameAssets(AssetsAndNames); #else if (!AssetToolsModule.Get().RenameAssets(AssetsAndNames)) { return PyErr_Format(PyExc_Exception, "unable to rename asset %s", path); } #endif Py_RETURN_NONE; } PyObject *py_unreal_engine_duplicate_asset(PyObject * self, PyObject * args) { char *path; char *package_name; char *object_name; if (!PyArg_ParseTuple(args, "sss:duplicate_asset", &path, &package_name, &object_name)) { return NULL; } if (!GEditor) return PyErr_Format(PyExc_Exception, "no GEditor found"); FAssetRegistryModule& AssetRegistryModule = FModuleManager::GetModuleChecked<FAssetRegistryModule>("AssetRegistry"); FAssetData asset = AssetRegistryModule.Get().GetAssetByObjectPath(UTF8_TO_TCHAR(path)); if (!asset.IsValid()) return PyErr_Format(PyExc_Exception, "unable to find asset %s", path); UObject *u_object = asset.GetAsset(); ObjectTools::FPackageGroupName pgn; pgn.ObjectName = UTF8_TO_TCHAR(object_name); pgn.GroupName = FString(""); pgn.PackageName = UTF8_TO_TCHAR(package_name); TSet<UPackage *> refused_packages; FText error_text; #if ENGINE_MINOR_VERSION < 14 UObject *new_asset = ObjectTools::DuplicateSingleObject(u_object, pgn, refused_packages); #else UObject *new_asset = ObjectTools::DuplicateSingleObject(u_object, pgn, refused_packages, false); #endif if (!new_asset) { return PyErr_Format(PyExc_Exception, "unable to duplicate asset %s", path); } FAssetRegistryModule::AssetCreated(new_asset); Py_RETURN_UOBJECT(new_asset); } PyObject *py_unreal_engine_delete_asset(PyObject * self, PyObject * args) { char *path; PyObject *py_show_confirmation = nullptr; if (!PyArg_ParseTuple(args, "s|O:delete_asset", &path, &py_show_confirmation)) { return NULL; } if (!GEditor) return PyErr_Format(PyExc_Exception, "no GEditor found"); bool show_confirmation = false; if (py_show_confirmation && PyObject_IsTrue(py_show_confirmation)) { show_confirmation = true; } FAssetRegistryModule& AssetRegistryModule = FModuleManager::GetModuleChecked<FAssetRegistryModule>("AssetRegistry"); FAssetData asset = AssetRegistryModule.Get().GetAssetByObjectPath(UTF8_TO_TCHAR(path)); if (!asset.IsValid()) return PyErr_Format(PyExc_Exception, "unable to find asset %s", path); UObject *u_object = asset.GetAsset(); TArray<UObject *> objects; objects.Add(u_object); if (ObjectTools::DeleteObjects(objects, show_confirmation) < 1) { if (ObjectTools::ForceDeleteObjects(objects, show_confirmation) < 1) { return PyErr_Format(PyExc_Exception, "unable to delete asset %s", path); } } Py_RETURN_NONE; } PyObject *py_unreal_engine_delete_object(PyObject * self, PyObject * args) { PyObject *py_obj; PyObject *py_bool = nullptr; if (!PyArg_ParseTuple(args, "O|O:delete_object", &py_obj, &py_bool)) { return NULL; } if (!GEditor) return PyErr_Format(PyExc_Exception, "no GEditor found"); UObject *u_object = ue_py_check_type<UObject>(py_obj); if (!u_object) return PyErr_Format(PyExc_Exception, "argument is not a UObject"); TArray<UObject *> objects_to_delete; objects_to_delete.Add(u_object); if (py_bool && PyObject_IsTrue(py_bool)) { if (ObjectTools::ForceDeleteObjects(objects_to_delete, false) < 1) { return PyErr_Format(PyExc_Exception, "unable to delete object"); } } else { if (ObjectTools::DeleteObjects(objects_to_delete, false) < 1) { return PyErr_Format(PyExc_Exception, "unable to delete asset"); } } Py_RETURN_NONE; } PyObject *py_unreal_engine_get_assets(PyObject * self, PyObject * args) { char *path; PyObject *py_recursive = nullptr; if (!PyArg_ParseTuple(args, "s|O:get_assets", &path, &py_recursive)) { return NULL; } if (!GEditor) return PyErr_Format(PyExc_Exception, "no GEditor found"); bool recursive = false; if (py_recursive && PyObject_IsTrue(py_recursive)) recursive = true; TArray<FAssetData> assets; FAssetRegistryModule& AssetRegistryModule = FModuleManager::GetModuleChecked<FAssetRegistryModule>("AssetRegistry"); AssetRegistryModule.Get().GetAssetsByPath(UTF8_TO_TCHAR(path), assets, recursive); PyObject *assets_list = PyList_New(0); for (FAssetData asset : assets) { if (!asset.IsValid()) continue; ue_PyUObject *ret = ue_get_python_uobject(asset.GetAsset()); if (ret) { PyList_Append(assets_list, (PyObject *)ret); } } return assets_list; } PyObject *py_unreal_engine_get_assets_by_filter(PyObject * self, PyObject * args, PyObject *kwargs) { PyObject *pyfilter; PyObject *py_return_asset_data = nullptr; static char *kw_names[] = { (char *)"filter", (char *)"return_asset_data", NULL }; if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O|O:get_assets_by_filter", kw_names, &pyfilter, &py_return_asset_data)) { return nullptr; } ue_PyFARFilter *py_filter = py_ue_is_farfilter(pyfilter); if (!py_filter) return PyErr_Format(PyExc_Exception, "Arg is not a FARFilter"); FARFilter& Filter = py_filter->filter; py_ue_sync_farfilter((PyObject *)py_filter); TArray<FAssetData> assets; Py_BEGIN_ALLOW_THREADS; FAssetRegistryModule& AssetRegistryModule = FModuleManager::GetModuleChecked<FAssetRegistryModule>("AssetRegistry"); AssetRegistryModule.Get().SearchAllAssets(true); AssetRegistryModule.Get().GetAssets(Filter, assets); Py_END_ALLOW_THREADS; bool return_asset_data = false; if (py_return_asset_data && PyObject_IsTrue(py_return_asset_data)) return_asset_data = true; PyObject *assets_list = PyList_New(0); for (FAssetData asset : assets) { if (!asset.IsValid()) continue; PyObject *ret = nullptr; if (return_asset_data) { ret = py_ue_new_fassetdata(asset); } else { ret = (PyObject *)ue_get_python_uobject(asset.GetAsset()); } if (ret) { PyList_Append(assets_list, ret); } } return assets_list; } PyObject *py_unreal_engine_get_discovered_plugins(PyObject * self, PyObject * args) { PyObject *plugins_list = PyList_New(0); for (TSharedRef<IPlugin>plugin : IPluginManager::Get().GetDiscoveredPlugins()) { PyObject *ret = py_ue_new_iplugin(&plugin.Get()); if (ret) { PyList_Append(plugins_list, ret); } } return plugins_list; } PyObject *py_unreal_engine_get_enabled_plugins(PyObject * self, PyObject * args) { PyObject *plugins_list = PyList_New(0); for (TSharedRef<IPlugin>plugin : IPluginManager::Get().GetEnabledPlugins()) { PyObject *ret = py_ue_new_iplugin(&plugin.Get()); if (ret) { PyList_Append(plugins_list, ret); } } return plugins_list; } PyObject *py_unreal_engine_find_plugin(PyObject * self, PyObject * args) { char *name; if (!PyArg_ParseTuple(args, "s:find_plugin", &name)) { return NULL; } TSharedPtr<IPlugin> plugin = IPluginManager::Get().FindPlugin(FString(UTF8_TO_TCHAR(name))); if (!plugin.IsValid()) { Py_INCREF(Py_None); return Py_None; } PyObject *ret = py_ue_new_iplugin(plugin.Get()); if (!ret) return PyErr_Format(PyExc_Exception, "PyUObject is in invalid state"); Py_INCREF(ret); return (PyObject *)ret; } PyObject *py_unreal_engine_get_assets_by_class(PyObject * self, PyObject * args) { char *path; PyObject *py_recursive = nullptr; if (!PyArg_ParseTuple(args, "s|O:get_assets_by_class", &path, &py_recursive)) { return NULL; } if (!GEditor) return PyErr_Format(PyExc_Exception, "no GEditor found"); bool recursive = false; if (py_recursive && PyObject_IsTrue(py_recursive)) recursive = true; TArray<FAssetData> assets; FAssetRegistryModule& AssetRegistryModule = FModuleManager::GetModuleChecked<FAssetRegistryModule>("AssetRegistry"); AssetRegistryModule.Get().GetAssetsByClass(UTF8_TO_TCHAR(path), assets, recursive); PyObject *assets_list = PyList_New(0); for (FAssetData asset : assets) { if (!asset.IsValid()) continue; ue_PyUObject *ret = ue_get_python_uobject(asset.GetAsset()); if (ret) { PyList_Append(assets_list, (PyObject *)ret); } } return assets_list; } PyObject *py_unreal_engine_get_selected_assets(PyObject * self, PyObject * args) { if (!GEditor) return PyErr_Format(PyExc_Exception, "no GEditor found"); TArray<FAssetData> assets; FContentBrowserModule& ContentBrowserModule = FModuleManager::GetModuleChecked<FContentBrowserModule>("ContentBrowser"); ContentBrowserModule.Get().GetSelectedAssets(assets); PyObject *assets_list = PyList_New(0); for (FAssetData asset : assets) { if (!asset.IsValid()) continue; ue_PyUObject *ret = ue_get_python_uobject(asset.GetAsset()); if (ret) { PyList_Append(assets_list, (PyObject *)ret); } } return assets_list; } PyObject *py_unreal_engine_get_all_edited_assets(PyObject * self, PyObject * args) { TArray<UObject *> assets = FAssetEditorManager::Get().GetAllEditedAssets(); PyObject *assets_list = PyList_New(0); for (UObject *asset : assets) { ue_PyUObject *ret = ue_get_python_uobject(asset); if (ret) { PyList_Append(assets_list, (PyObject *)ret); } } return assets_list; } PyObject *py_unreal_engine_open_editor_for_asset(PyObject * self, PyObject * args) { PyObject *py_obj; if (!PyArg_ParseTuple(args, "O:open_editor_for_asset", &py_obj)) { return nullptr; } UObject *u_obj = ue_py_check_type<UObject>(py_obj); if (!u_obj) return PyErr_Format(PyExc_Exception, "argument is not a UObject"); if (FAssetEditorManager::Get().OpenEditorForAsset(u_obj)) { Py_RETURN_TRUE; } Py_RETURN_FALSE; } PyObject *py_unreal_engine_find_editor_for_asset(PyObject * self, PyObject * args) { PyObject *py_obj; PyObject *py_bool = nullptr; if (!PyArg_ParseTuple(args, "O|O:find_editor_for_asset", &py_obj, &py_bool)) { return nullptr; } UObject *u_obj = ue_py_check_type<UObject>(py_obj); if (!u_obj) return PyErr_Format(PyExc_Exception, "argument is not a UObject"); bool bFocus = false; if (py_bool && PyObject_IsTrue(py_bool)) bFocus = true; IAssetEditorInstance *instance = FAssetEditorManager::Get().FindEditorForAsset(u_obj, bFocus); if (!instance) return PyErr_Format(PyExc_Exception, "no editor found for asset"); return py_ue_new_iasset_editor_instance(instance); } PyObject *py_unreal_engine_close_editor_for_asset(PyObject * self, PyObject * args) { PyObject *py_obj; if (!PyArg_ParseTuple(args, "O:close_editor_for_asset", &py_obj)) { return nullptr; } UObject *u_obj = ue_py_check_type<UObject>(py_obj); if (!u_obj) return PyErr_Format(PyExc_Exception, "argument is not a UObject"); FAssetEditorManager::Get().CloseAllEditorsForAsset(u_obj); Py_RETURN_NONE; } PyObject *py_unreal_engine_close_all_asset_editors(PyObject * self, PyObject * args) { FAssetEditorManager::Get().CloseAllAssetEditors(); Py_RETURN_NONE; } PyObject *py_unreal_engine_set_fbx_import_option(PyObject * self, PyObject * args) { PyObject *obj; if (!PyArg_ParseTuple(args, "O:set_fbx_import_option", &obj)) { return NULL; } if (!GEditor) return PyErr_Format(PyExc_Exception, "no GEditor found"); if (!ue_is_pyuobject(obj)) return PyErr_Format(PyExc_Exception, "argument is not a UObject"); ue_PyUObject *py_obj = (ue_PyUObject *)obj; if (!py_obj->ue_object->IsA<UFbxImportUI>()) return PyErr_Format(PyExc_Exception, "object is not a FbxImportUI"); UFbxImportUI *ui = (UFbxImportUI *)py_obj->ue_object; FbxMeshUtils::SetImportOption(ui); Py_INCREF(Py_None); return Py_None; } PyObject *py_unreal_engine_create_blueprint(PyObject * self, PyObject * args) { PyObject *py_parent; char *name; if (!PyArg_ParseTuple(args, "Os:create_blueprint", &py_parent, &name)) { return nullptr; } UClass *parent = UObject::StaticClass(); if (py_parent != Py_None) { UClass *new_parent = ue_py_check_type<UClass>(py_parent); if (!new_parent) return PyErr_Format(PyExc_Exception, "uobject is not a UClass"); parent = new_parent; } if (name[0] != '/') { return PyErr_Format(PyExc_Exception, "path must start with a /"); } char *bp_name = strrchr(name, '/') + 1; if (strlen(bp_name) < 1) { return PyErr_Format(PyExc_Exception, "invalid blueprint name"); } UPackage *outer = CreatePackage(nullptr, UTF8_TO_TCHAR(name)); if (!outer) return PyErr_Format(PyExc_Exception, "unable to create package"); TArray<UPackage *> TopLevelPackages; TopLevelPackages.Add(outer); if (!PackageTools::HandleFullyLoadingPackages(TopLevelPackages, FText::FromString("Create a new object"))) return PyErr_Format(PyExc_Exception, "unable to fully load package"); if (FindObject<UBlueprint>(outer, UTF8_TO_TCHAR(bp_name)) != nullptr) return PyErr_Format(PyExc_Exception, "there is already a Blueprint with this name"); UBlueprint *bp = FKismetEditorUtilities::CreateBlueprint(parent, outer, UTF8_TO_TCHAR(bp_name), EBlueprintType::BPTYPE_Normal, UBlueprint::StaticClass(), UBlueprintGeneratedClass::StaticClass()); if (!bp) return PyErr_Format(PyExc_Exception, "unable to create Blueprint"); FAssetRegistryModule::AssetCreated(bp); outer->MarkPackageDirty(); Py_RETURN_UOBJECT(bp); } PyObject *py_unreal_engine_get_blueprint_hierarchy_from_class(PyObject * self, PyObject * args) { PyObject *py_class; if (!PyArg_ParseTuple(args, "O:get_blueprint_hierarchy_from_class", &py_class)) { return NULL; } UClass* u_class = ue_py_check_type<UClass>(py_class); if (!u_class) { return PyErr_Format(PyExc_Exception, "argument is not a UClass"); } TArray<UBlueprint*> outBPs; UBlueprint::GetBlueprintHierarchyFromClass(u_class, outBPs); PyObject *py_bpClasses = PyList_New(0); for (UBlueprint* bpClass : outBPs) { ue_PyUObject *item = ue_get_python_uobject(bpClass); if (item) PyList_Append(py_bpClasses, (PyObject *)item); } return py_bpClasses; } PyObject *py_unreal_engine_reload_blueprint(PyObject * self, PyObject * args) { PyObject *py_blueprint; if (!PyArg_ParseTuple(args, "O:reload_blueprint", &py_blueprint)) { return nullptr; } if (!ue_is_pyuobject(py_blueprint)) { return PyErr_Format(PyExc_Exception, "argument is not a UObject"); } UBlueprint *bp = ue_py_check_type<UBlueprint>(py_blueprint); if (!bp) return PyErr_Format(PyExc_Exception, "uobject is not a UBlueprint"); UBlueprint *reloaded_bp = nullptr; Py_BEGIN_ALLOW_THREADS reloaded_bp = FKismetEditorUtilities::ReloadBlueprint(bp); Py_END_ALLOW_THREADS Py_RETURN_UOBJECT(reloaded_bp); } PyObject *py_unreal_engine_compile_blueprint(PyObject * self, PyObject * args) { PyObject *py_blueprint; if (!PyArg_ParseTuple(args, "O:compile_blueprint", &py_blueprint)) { return nullptr; } UBlueprint *bp = ue_py_check_type<UBlueprint>(py_blueprint); if (!bp) return PyErr_Format(PyExc_Exception, "uobject is not a UBlueprint"); Py_BEGIN_ALLOW_THREADS FKismetEditorUtilities::CompileBlueprint(bp); Py_END_ALLOW_THREADS Py_RETURN_NONE; } PyObject *py_unreal_engine_replace_blueprint(PyObject * self, PyObject * args) { PyObject *py_blueprint; PyObject *py_blueprint_new; if (!PyArg_ParseTuple(args, "OO:replace_blueprint", &py_blueprint, &py_blueprint_new)) { return NULL; } if (!ue_is_pyuobject(py_blueprint)) { return PyErr_Format(PyExc_Exception, "argument is not a UObject"); } if (!ue_is_pyuobject(py_blueprint_new)) { return PyErr_Format(PyExc_Exception, "argument is not a UObject"); } ue_PyUObject *py_obj = (ue_PyUObject *)py_blueprint; if (!py_obj->ue_object->IsA<UBlueprint>()) return PyErr_Format(PyExc_Exception, "uobject is not a UBlueprint"); UBlueprint *bp = (UBlueprint *)py_obj->ue_object; py_obj = (ue_PyUObject *)py_blueprint_new; if (!py_obj->ue_object->IsA<UBlueprint>()) return PyErr_Format(PyExc_Exception, "uobject is not a UBlueprint"); UBlueprint *bp_new = (UBlueprint *)py_obj->ue_object; UBlueprint *replaced_bp = FKismetEditorUtilities::ReplaceBlueprint(bp, bp_new); Py_RETURN_UOBJECT(replaced_bp); } PyObject *py_unreal_engine_create_blueprint_from_actor(PyObject * self, PyObject * args) { PyObject *py_actor; char *name; if (!PyArg_ParseTuple(args, "sO:create_blueprint_from_actor", &name, &py_actor)) { return NULL; } if (name[0] != '/') { return PyErr_Format(PyExc_Exception, "path must start with a /"); } if (!ue_is_pyuobject(py_actor)) { return PyErr_Format(PyExc_Exception, "argument is not an Actor"); } ue_PyUObject *py_obj = (ue_PyUObject *)py_actor; if (!py_obj->ue_object->IsA<AActor>()) return PyErr_Format(PyExc_Exception, "uobject is not a UClass"); AActor *actor = (AActor *)py_obj->ue_object; UBlueprint *bp = FKismetEditorUtilities::CreateBlueprintFromActor(UTF8_TO_TCHAR(name), actor, true); Py_RETURN_UOBJECT(bp); } PyObject *py_unreal_engine_get_blueprint_components(PyObject * self, PyObject * args) { PyObject *py_blueprint; if (!PyArg_ParseTuple(args, "O|:add_component_to_blueprint", &py_blueprint)) { return nullptr; } UBlueprint *bp = ue_py_check_type<UBlueprint>(py_blueprint); if (!bp) return PyErr_Format(PyExc_Exception, "uobject is not a Blueprint"); PyObject *py_list = PyList_New(0); for (USCS_Node *node : bp->SimpleConstructionScript->GetAllNodes()) { ue_PyUObject *item = ue_get_python_uobject(node->ComponentTemplate); if (item) PyList_Append(py_list, (PyObject *)item); } return py_list; } PyObject *py_unreal_engine_remove_component_from_blueprint(PyObject *self, PyObject *args) { PyObject *py_blueprint; char *name; char *parentName = nullptr; if (!PyArg_ParseTuple(args, "Os|s:remove_component_from_blueprint", &py_blueprint, &name, &parentName)) { return NULL; } if (!ue_is_pyuobject(py_blueprint)) { return PyErr_Format(PyExc_Exception, "argument is not a UObject"); } ue_PyUObject *py_obj = (ue_PyUObject *)py_blueprint; if (!py_obj->ue_object->IsA<UBlueprint>()) return PyErr_Format(PyExc_Exception, "uobject is not a UBlueprint"); UBlueprint *bp = (UBlueprint *)py_obj->ue_object; bp->Modify(); USCS_Node *ComponentNode = bp->SimpleConstructionScript->FindSCSNode(UTF8_TO_TCHAR(name)); if (ComponentNode) { bp->SimpleConstructionScript->RemoveNode(ComponentNode); } Py_RETURN_NONE; } PyObject *py_unreal_engine_add_component_to_blueprint(PyObject * self, PyObject * args) { PyObject *py_blueprint; PyObject *py_component; char *name; char *parentName = nullptr; if (!PyArg_ParseTuple(args, "OOs|s:add_component_to_blueprint", &py_blueprint, &py_component, &name, &parentName)) { return NULL; } if (!ue_is_pyuobject(py_blueprint)) { return PyErr_Format(PyExc_Exception, "argument is not a UObject"); } if (!ue_is_pyuobject(py_component)) { return PyErr_Format(PyExc_Exception, "argument is not a UObject"); } ue_PyUObject *py_obj = (ue_PyUObject *)py_blueprint; if (!py_obj->ue_object->IsA<UBlueprint>()) return PyErr_Format(PyExc_Exception, "uobject is not a UBlueprint"); UBlueprint *bp = (UBlueprint *)py_obj->ue_object; py_obj = (ue_PyUObject *)py_component; if (!py_obj->ue_object->IsA<UClass>()) return PyErr_Format(PyExc_Exception, "uobject is not a UClass"); UClass *component_class = (UClass *)py_obj->ue_object; bp->Modify(); USCS_Node *node = bp->SimpleConstructionScript->CreateNode(component_class, UTF8_TO_TCHAR(name)); if (!node) { return PyErr_Format(PyExc_Exception, "unable to allocate new component"); } USCS_Node *parentNode = nullptr; if (component_class->IsChildOf<USceneComponent>()) { if (parentName) { FString strParentName = UTF8_TO_TCHAR(parentName); if (strParentName.IsEmpty()) { parentNode = bp->SimpleConstructionScript->GetDefaultSceneRootNode(); } else { parentNode = bp->SimpleConstructionScript->FindSCSNode(UTF8_TO_TCHAR(parentName)); } } else { parentNode = bp->SimpleConstructionScript->GetDefaultSceneRootNode(); } } if (parentNode) { parentNode->AddChildNode(node); } else { bp->SimpleConstructionScript->AddNode(node); } Py_RETURN_UOBJECT(node->ComponentTemplate); } PyObject *py_unreal_engine_blueprint_add_member_variable(PyObject * self, PyObject * args) { PyObject *py_blueprint; char *name; PyObject *py_type; PyObject *py_is_array = nullptr; char *default_value = nullptr; if (!PyArg_ParseTuple(args, "OsO|Os:blueprint_add_member_variable", &py_blueprint, &name, &py_type, &py_is_array, &default_value)) { return nullptr; } UBlueprint *bp = ue_py_check_type<UBlueprint>(py_blueprint); if (!bp) return PyErr_Format(PyExc_Exception, "uobject is not a Blueprint"); FEdGraphPinType pin; if (PyUnicodeOrString_Check(py_type)) { const char *in_type = UEPyUnicode_AsUTF8(py_type); bool is_array = false; if (py_is_array && PyObject_IsTrue(py_is_array)) is_array = true; #if ENGINE_MINOR_VERSION > 14 pin.PinCategory = UTF8_TO_TCHAR(in_type); #if ENGINE_MINOR_VERSION >= 17 pin.ContainerType = is_array ? EPinContainerType::Array : EPinContainerType::None; #else pin.bIsArray = is_array; #endif #else FEdGraphPinType pin2(UTF8_TO_TCHAR(in_type), FString(""), nullptr, is_array, false); pin = pin2; #endif } else { FEdGraphPinType *pinptr = ue_py_check_struct<FEdGraphPinType>(py_type); if (!pinptr) return PyErr_Format(PyExc_Exception, "argument is not a EdGraphPinType"); pin = *pinptr; } FString DefaultValue = FString(""); if (default_value) DefaultValue = FString(default_value); if (FBlueprintEditorUtils::AddMemberVariable(bp, UTF8_TO_TCHAR(name), pin, DefaultValue)) { Py_RETURN_TRUE; } Py_RETURN_FALSE; } PyObject *py_unreal_engine_blueprint_set_variable_visibility(PyObject * self, PyObject * args) { PyObject *py_blueprint; char *name; PyObject *visibility; if (!PyArg_ParseTuple(args, "OsO:blueprint_set_variable_visibility", &py_blueprint, &name, &visibility)) { return nullptr; } UBlueprint *bp = ue_py_check_type<UBlueprint>(py_blueprint); if (!bp) return PyErr_Format(PyExc_Exception, "uobject is not a Blueprint"); bool visible = false; if (PyObject_IsTrue(visibility)) { visible = true; } FBlueprintEditorUtils::SetBlueprintOnlyEditableFlag(bp, FName(UTF8_TO_TCHAR(name)), !visible); Py_RETURN_NONE; } PyObject *py_unreal_engine_blueprint_add_new_timeline(PyObject * self, PyObject * args) { PyObject *py_blueprint; char *name; if (!PyArg_ParseTuple(args, "Os:blueprint_add_new_timeline", &py_blueprint, &name)) { return NULL; } if (!ue_is_pyuobject(py_blueprint)) { return PyErr_Format(PyExc_Exception, "argument is not a UObject"); } ue_PyUObject *py_obj = (ue_PyUObject *)py_blueprint; if (!py_obj->ue_object->IsA<UBlueprint>()) return PyErr_Format(PyExc_Exception, "uobject is not a UBlueprint"); UBlueprint *bp = (UBlueprint *)py_obj->ue_object; UTimelineTemplate *timeline = FBlueprintEditorUtils::AddNewTimeline(bp, UTF8_TO_TCHAR(name)); if (!timeline) { return PyErr_Format(PyExc_Exception, "unable to add new timeline %s", name); } Py_RETURN_UOBJECT(timeline); } PyObject *py_unreal_engine_blueprint_add_function(PyObject * self, PyObject * args) { PyObject *py_blueprint; char *name; if (!PyArg_ParseTuple(args, "Os:blueprint_add_function", &py_blueprint, &name)) { return nullptr; } UBlueprint *bp = ue_py_check_type<UBlueprint>(py_blueprint); if (!bp) return PyErr_Format(PyExc_Exception, "argument is not a UBlueprint"); UEdGraph *graph = FBlueprintEditorUtils::CreateNewGraph(bp, FName(UTF8_TO_TCHAR(name)), UEdGraph::StaticClass(), UEdGraphSchema_K2::StaticClass()); FBlueprintEditorUtils::AddFunctionGraph<UClass>(bp, graph, true, nullptr); Py_RETURN_UOBJECT(graph); } PyObject *py_unreal_engine_blueprint_add_event_dispatcher(PyObject * self, PyObject * args) { PyObject *py_blueprint; char *name; if (!PyArg_ParseTuple(args, "Os:blueprint_add_event_dispatcher", &py_blueprint, &name)) { return NULL; } UBlueprint *bp = ue_py_check_type<UBlueprint>(py_blueprint); if (!bp) return PyErr_Format(PyExc_Exception, "argument is not a UBlueprint"); FName multicast_name = FName(UTF8_TO_TCHAR(name)); bp->Modify(); const UEdGraphSchema_K2 *state = GetDefault<UEdGraphSchema_K2>(); FEdGraphPinType multicast_type; multicast_type.PinCategory = state->PC_MCDelegate; if (!FBlueprintEditorUtils::AddMemberVariable(bp, multicast_name, multicast_type)) { return PyErr_Format(PyExc_Exception, "unable to create multicast variable"); } UEdGraph *graph = FBlueprintEditorUtils::CreateNewGraph(bp, multicast_name, UEdGraph::StaticClass(), UEdGraphSchema_K2::StaticClass()); if (!graph) { return PyErr_Format(PyExc_Exception, "unable to create graph"); } graph->bEditable = false; state->CreateDefaultNodesForGraph(*graph); state->CreateFunctionGraphTerminators(*graph, (UClass *)nullptr); state->AddExtraFunctionFlags(graph, (FUNC_BlueprintCallable | FUNC_BlueprintEvent | FUNC_Public)); state->MarkFunctionEntryAsEditable(graph, true); bp->DelegateSignatureGraphs.Add(graph); FBlueprintEditorUtils::MarkBlueprintAsStructurallyModified(bp); Py_RETURN_UOBJECT(graph); } PyObject *py_unreal_engine_blueprint_mark_as_structurally_modified(PyObject * self, PyObject * args) { PyObject *py_blueprint; if (!PyArg_ParseTuple(args, "O:blueprint_add_event_dispatcher", &py_blueprint)) { return NULL; } UBlueprint *bp = ue_py_check_type<UBlueprint>(py_blueprint); if (!bp) return PyErr_Format(PyExc_Exception, "argument is not a UBlueprint"); FBlueprintEditorUtils::MarkBlueprintAsStructurallyModified(bp); Py_INCREF(Py_None); return Py_None; } PyObject *py_unreal_engine_blueprint_add_ubergraph_page(PyObject * self, PyObject * args) { PyObject *py_blueprint; char *name; if (!PyArg_ParseTuple(args, "Os:blueprint_add_ubergraph_page", &py_blueprint, &name)) { return NULL; } if (!ue_is_pyuobject(py_blueprint)) { return PyErr_Format(PyExc_Exception, "argument is not a UObject"); } ue_PyUObject *py_obj = (ue_PyUObject *)py_blueprint; if (!py_obj->ue_object->IsA<UBlueprint>()) return PyErr_Format(PyExc_Exception, "uobject is not a UBlueprint"); UBlueprint *bp = (UBlueprint *)py_obj->ue_object; UEdGraph *graph = FBlueprintEditorUtils::CreateNewGraph(bp, FName(UTF8_TO_TCHAR(name)), UEdGraph::StaticClass(), UEdGraphSchema_K2::StaticClass()); FBlueprintEditorUtils::AddUbergraphPage(bp, graph); Py_RETURN_UOBJECT(graph); } PyObject *py_unreal_engine_blueprint_get_all_graphs(PyObject * self, PyObject * args) { PyObject *py_blueprint; if (!PyArg_ParseTuple(args, "O:blueprint_get_all_graphs", &py_blueprint)) { return nullptr; } UBlueprint *bp = ue_py_check_type<UBlueprint>(py_blueprint); if (!bp) return PyErr_Format(PyExc_Exception, "uobject is not a UBlueprint"); PyObject *py_graphs = PyList_New(0); TArray<UEdGraph*> graphs; bp->GetAllGraphs(graphs); for (UEdGraph *graph : graphs) { ue_PyUObject *item = ue_get_python_uobject(graph); if (item) PyList_Append(py_graphs, (PyObject *)item); } return py_graphs; } PyObject *py_unreal_engine_create_new_graph(PyObject * self, PyObject * args) { PyObject *py_object; char *name; PyObject *py_graph_class; PyObject *py_graph_schema; PyObject *py_bool = nullptr; if (!PyArg_ParseTuple(args, "OsOO|O:create_new_graph", &py_object, &name, &py_graph_class, &py_graph_schema, &py_bool)) { return NULL; } if (!ue_is_pyuobject(py_object)) { return PyErr_Format(PyExc_Exception, "argument is not a UObject"); } ue_PyUObject *py_obj = (ue_PyUObject *)py_object; if (!ue_is_pyuobject(py_graph_class)) { return PyErr_Format(PyExc_Exception, "argument is not a UObject"); } ue_PyUObject *py_class_obj = (ue_PyUObject *)py_graph_class; if (!py_class_obj->ue_object->IsA<UClass>()) { return PyErr_Format(PyExc_Exception, "argument is not a UClass"); } UClass *u_class = (UClass *)py_class_obj->ue_object; if (!u_class->IsChildOf<UEdGraph>()) { return PyErr_Format(PyExc_Exception, "argument is not a child of UEdGraph"); } if (!ue_is_pyuobject(py_graph_schema)) { return PyErr_Format(PyExc_Exception, "argument is not a UObject"); } ue_PyUObject *py_class_schema = (ue_PyUObject *)py_graph_schema; if (!py_class_schema->ue_object->IsA<UClass>()) { return PyErr_Format(PyExc_Exception, "argument is not a UClass"); } UClass *u_class_schema = (UClass *)py_class_schema->ue_object; if (!u_class_schema->IsChildOf<UEdGraphSchema>()) { return PyErr_Format(PyExc_Exception, "argument is not a child of UEdGraphSchema"); } UEdGraph *graph = FBlueprintEditorUtils::CreateNewGraph(py_obj->ue_object, FName(UTF8_TO_TCHAR(name)), u_class, u_class_schema); if (!graph) { return PyErr_Format(PyExc_Exception, "unable to create graph"); } if (py_bool && PyObject_IsTrue(py_bool)) { graph->GetSchema()->CreateDefaultNodesForGraph(*graph); } Py_RETURN_UOBJECT(graph); } PyObject *py_unreal_engine_editor_on_asset_post_import(PyObject * self, PyObject * args) { PyObject *py_callable; if (!PyArg_ParseTuple(args, "O:editor_on_asset_post_import", &py_callable)) { return NULL; } if (!PyCallable_Check(py_callable)) return PyErr_Format(PyExc_Exception, "object is not a callable"); TSharedRef<FPythonSmartDelegate> py_delegate = FUnrealEnginePythonHouseKeeper::Get()->NewPythonSmartDelegate(py_callable); #if ENGINE_MINOR_VERSION > 21 GEditor->GetEditorSubsystem<UImportSubsystem>()->OnAssetPostImport.AddSP(py_delegate, &FPythonSmartDelegate::PyFOnAssetPostImport); #else FEditorDelegates::OnAssetPostImport.AddSP(py_delegate, &FPythonSmartDelegate::PyFOnAssetPostImport); #endif Py_RETURN_NONE; } PyObject *py_unreal_engine_on_main_frame_creation_finished(PyObject * self, PyObject * args) { PyObject *py_callable; if (!PyArg_ParseTuple(args, "O:on_main_frame_creation_finished", &py_callable)) { return NULL; } if (!PyCallable_Check(py_callable)) return PyErr_Format(PyExc_Exception, "object is not a callable"); /* TSharedRef<FPythonSmartDelegate> py_delegate = FUnrealEnginePythonHouseKeeper::Get()->NewPythonSmartDelegate(py_callable); IMainFrameModule& MainFrameModule = FModuleManager::LoadModuleChecked<IMainFrameModule>(TEXT("MainFrame")); MainFrameModule.OnMainFrameCreationFinished().AddSP(py_delegate, &FPythonSmartDelegate::PyFOnMainFrameCreationFinished); */ FPythonSmartDelegate *py_delegate = new FPythonSmartDelegate(); py_delegate->SetPyCallable(py_callable); IMainFrameModule& MainFrameModule = FModuleManager::LoadModuleChecked<IMainFrameModule>(TEXT("MainFrame")); MainFrameModule.OnMainFrameCreationFinished().AddRaw(py_delegate, &FPythonSmartDelegate::PyFOnMainFrameCreationFinished); Py_RETURN_NONE; } PyObject *py_unreal_engine_create_material_instance(PyObject * self, PyObject * args) { PyObject *py_material; char *materialPacakgePath = nullptr; char *materialName = nullptr; if (!PyArg_ParseTuple(args, "O|ss:create_material_instance", &py_material, &materialPacakgePath, &materialName)) { return NULL; } if (!ue_is_pyuobject(py_material)) { return PyErr_Format(PyExc_Exception, "argument is not a UObject"); } ue_PyUObject *py_obj = (ue_PyUObject *)py_material; if (!py_obj->ue_object->IsA<UMaterialInterface>()) return PyErr_Format(PyExc_Exception, "uobject is not a UMaterialInterface"); UMaterialInterface *materialInterface = (UMaterialInterface *)py_obj->ue_object; FAssetToolsModule& AssetToolsModule = FModuleManager::LoadModuleChecked<FAssetToolsModule>("AssetTools"); // Determine an appropriate name FString Name; FString PackagePath; FString PackageName; // Create the factory used to generate the asset UMaterialInstanceConstantFactoryNew* Factory = NewObject<UMaterialInstanceConstantFactoryNew>(); Factory->InitialParent = materialInterface; if (materialPacakgePath && materialName) { Name = UTF8_TO_TCHAR(materialName); PackagePath = UTF8_TO_TCHAR(materialPacakgePath); } else { AssetToolsModule.Get().CreateUniqueAssetName(materialInterface->GetOutermost()->GetName(), UTF8_TO_TCHAR("_inst"), PackageName, Name); PackagePath = FPackageName::GetLongPackagePath(PackageName); } UObject* NewAsset = AssetToolsModule.Get().CreateAsset(Name, PackagePath, UMaterialInstanceConstant::StaticClass(), Factory); if (!NewAsset) return PyErr_Format(PyExc_Exception, "unable to create new asset"); Py_RETURN_UOBJECT(NewAsset); } PyObject *py_ue_factory_create_new(ue_PyUObject *self, PyObject * args) { ue_py_check(self); char *name; if (!PyArg_ParseTuple(args, "s:factory_create_new", &name)) { return nullptr; } UFactory *factory = ue_py_check_type<UFactory>(self); if (!factory) return PyErr_Format(PyExc_Exception, "uobject is not a Factory"); char *obj_name = strrchr(name, '/') + 1; if (strlen(obj_name) < 1) { return PyErr_Format(PyExc_Exception, "invalid object name"); } FString PackageName = PackageTools::SanitizePackageName(FString(UTF8_TO_TCHAR(name))); UPackage *outer = CreatePackage(nullptr, *PackageName); if (!outer) return PyErr_Format(PyExc_Exception, "unable to create package"); TArray<UPackage *> TopLevelPackages; TopLevelPackages.Add(outer); if (!PackageTools::HandleFullyLoadingPackages(TopLevelPackages, FText::FromString("Create a new object"))) return PyErr_Format(PyExc_Exception, "unable to fully load package"); UClass *u_class = factory->GetSupportedClass(); // avoid duplicates if (u_class->IsChildOf<UBlueprint>()) { if (FindObject<UBlueprint>(outer, UTF8_TO_TCHAR(obj_name))) { return PyErr_Format(PyExc_Exception, "a blueprint with this name already exists in the package"); } } if (u_class->IsChildOf<UUserDefinedStruct>()) { if (FindObject<UUserDefinedStruct>(outer, UTF8_TO_TCHAR(obj_name))) { return PyErr_Format(PyExc_Exception, "a structure with this name already exists in the package"); } } UObject *u_object = nullptr; Py_BEGIN_ALLOW_THREADS; u_object = factory->FactoryCreateNew(u_class, outer, FName(UTF8_TO_TCHAR(obj_name)), RF_Public | RF_Standalone, nullptr, GWarn); if (u_object) { FAssetRegistryModule::AssetCreated(u_object); outer->MarkPackageDirty(); } Py_END_ALLOW_THREADS; if (!u_object) { return PyErr_Format(PyExc_Exception, "unable to create new object from factory"); } Py_RETURN_UOBJECT(u_object); } PyObject *py_ue_factory_import_object(ue_PyUObject *self, PyObject * args) { ue_py_check(self); char *filename = nullptr; char *name = nullptr; if (!PyArg_ParseTuple(args, "ss:factory_import_object", &filename, &name)) { return NULL; } if (!self->ue_object->IsA<UFactory>()) return PyErr_Format(PyExc_Exception, "uobject is not a Factory"); UFactory *factory = (UFactory *)self->ue_object; FString object_name = ObjectTools::SanitizeObjectName(FPaths::GetBaseFilename(UTF8_TO_TCHAR(filename))); FString pkg_name = FString(UTF8_TO_TCHAR(name)) + TEXT("/") + object_name; UPackage *outer = CreatePackage(nullptr, *pkg_name); if (!outer) return PyErr_Format(PyExc_Exception, "unable to create package"); bool canceled = false; UObject *u_object = nullptr; Py_BEGIN_ALLOW_THREADS; u_object = factory->ImportObject(factory->ResolveSupportedClass(), outer, FName(*object_name), RF_Public | RF_Standalone, UTF8_TO_TCHAR(filename), nullptr, canceled); if (u_object) { FAssetRegistryModule::AssetCreated(u_object); outer->MarkPackageDirty(); } Py_END_ALLOW_THREADS; if (!u_object) return PyErr_Format(PyExc_Exception, "unable to create new object from factory"); Py_RETURN_UOBJECT(u_object); } PyObject *py_unreal_engine_add_level_to_world(PyObject *self, PyObject * args) { PyObject *py_world; char *name; PyObject *py_bool = nullptr; if (!PyArg_ParseTuple(args, "Os|O:add_level_to_world", &py_world, &name, &py_bool)) { return NULL; } UWorld *u_world = ue_py_check_type<UWorld>(py_world); if (!u_world) { return PyErr_Format(PyExc_Exception, "argument is not a UWorld"); } if (!FPackageName::DoesPackageExist(UTF8_TO_TCHAR(name), nullptr, nullptr)) return PyErr_Format(PyExc_Exception, "package does not exist"); UClass *streaming_mode_class = ULevelStreamingKismet::StaticClass(); if (py_bool && PyObject_IsTrue(py_bool)) { streaming_mode_class = ULevelStreamingAlwaysLoaded::StaticClass(); } #if ENGINE_MINOR_VERSION >= 17 ULevelStreaming *level_streaming = EditorLevelUtils::AddLevelToWorld(u_world, UTF8_TO_TCHAR(name), streaming_mode_class); #else ULevel *level_streaming = EditorLevelUtils::AddLevelToWorld(u_world, UTF8_TO_TCHAR(name), streaming_mode_class); #endif if (!level_streaming) { return PyErr_Format(PyExc_Exception, "unable to add \"%s\" to the world", name); } #if ENGINE_MINOR_VERSION >= 16 FEditorDelegates::RefreshLevelBrowser.Broadcast(); #endif Py_RETURN_UOBJECT(level_streaming); } PyObject *py_unreal_engine_move_selected_actors_to_level(PyObject *self, PyObject * args) { PyObject *py_level; if (!PyArg_ParseTuple(args, "O:move_selected_actors_to_level", &py_level)) { return NULL; } ULevel *level = ue_py_check_type<ULevel>(py_level); if (!level) return PyErr_Format(PyExc_Exception, "argument is not a ULevel"); #if ENGINE_MINOR_VERSION >= 17 UEditorLevelUtils::MoveSelectedActorsToLevel(level); #else GEditor->MoveSelectedActorsToLevel(level); #endif Py_RETURN_NONE; } PyObject *py_unreal_engine_move_actor_to_level(PyObject *self, PyObject * args) { PyObject *py_actor; PyObject *py_level; if (!PyArg_ParseTuple(args, "OO:move_actor_to_level", &py_actor, &py_level)) { return NULL; } AActor *actor = ue_py_check_type<AActor>(py_actor); if (!actor) return PyErr_Format(PyExc_Exception, "argument is not an Actor"); ULevel *level = ue_py_check_type<ULevel>(py_level); if (!level) return PyErr_Format(PyExc_Exception, "argument is not a ULevelStreaming"); TArray<AActor *> actors; actors.Add(actor); int out = 0; #if ENGINE_MINOR_VERSION >= 17 out = EditorLevelUtils::MoveActorsToLevel(actors, level); #endif if (out != 1) { return PyErr_Format(PyExc_Exception, "unable to move actor to level"); } Py_RETURN_NONE; } PyObject *py_unreal_engine_editor_take_high_res_screen_shots(PyObject * self, PyObject * args) { GEditor->TakeHighResScreenShots(); Py_RETURN_NONE; } PyObject *py_unreal_engine_begin_transaction(PyObject * self, PyObject * args) { if (!GEditor) return PyErr_Format(PyExc_Exception, "no GEditor found"); char *description; if (!PyArg_ParseTuple(args, "s:begin_transaction", &description)) { return NULL; } int ret = GEditor->BeginTransaction(FText::FromString(UTF8_TO_TCHAR(description))); return PyLong_FromLong(ret); } PyObject *py_unreal_engine_cancel_transaction(PyObject * self, PyObject * args) { if (!GEditor) return PyErr_Format(PyExc_Exception, "no GEditor found"); int tid; if (!PyArg_ParseTuple(args, "i:cancel_transaction", &tid)) { return nullptr; } GEditor->CancelTransaction(tid); Py_RETURN_NONE; } PyObject *py_unreal_engine_end_transaction(PyObject * self, PyObject * args) { if (!GEditor) return PyErr_Format(PyExc_Exception, "no GEditor found"); int ret = GEditor->EndTransaction(); return PyLong_FromLong(ret); } PyObject *py_unreal_engine_get_transaction_name(PyObject * self, PyObject * args) { if (!GEditor) return PyErr_Format(PyExc_Exception, "no GEditor found"); FText text = GEditor->GetTransactionName(); return PyUnicode_FromString(TCHAR_TO_UTF8(*(text.ToString()))); } PyObject *py_unreal_engine_is_transaction_active(PyObject * self, PyObject * args) { if (!GEditor) return PyErr_Format(PyExc_Exception, "no GEditor found"); bool is_active = GEditor->IsTransactionActive(); if (is_active) { Py_RETURN_TRUE; } Py_RETURN_FALSE; } PyObject *py_unreal_engine_redo_transaction(PyObject * self, PyObject * args) { if (!GEditor) return PyErr_Format(PyExc_Exception, "no GEditor found"); bool redo = GEditor->RedoTransaction(); if (redo) { Py_RETURN_TRUE; } Py_RETURN_FALSE; } PyObject *py_unreal_engine_reset_transaction(PyObject * self, PyObject * args) { if (!GEditor) return PyErr_Format(PyExc_Exception, "no GEditor found"); char *reason; if (!PyArg_ParseTuple(args, "s:reset_transaction", &reason)) { return NULL; } GEditor->ResetTransaction(FText::FromString(UTF8_TO_TCHAR(reason))); Py_RETURN_NONE; } PyObject *py_unreal_engine_editor_undo(PyObject * self, PyObject * args) { if (!GEditor || !GEditor->Trans) return PyErr_Format(PyExc_Exception, "no GEditor found"); bool bSuccess; Py_BEGIN_ALLOW_THREADS; bSuccess = GEditor->Trans->Undo(); Py_END_ALLOW_THREADS; if (bSuccess) { Py_RETURN_TRUE; } Py_RETURN_FALSE; } PyObject *py_unreal_engine_editor_redo(PyObject * self, PyObject * args) { if (!GEditor || !GEditor->Trans) return PyErr_Format(PyExc_Exception, "no GEditor found"); bool bSuccess; Py_BEGIN_ALLOW_THREADS; bSuccess = GEditor->Trans->Redo(); Py_END_ALLOW_THREADS; if (bSuccess) Py_RETURN_TRUE; Py_RETURN_FALSE; } PyObject *py_unreal_engine_transactions(PyObject * self, PyObject * args) { if (!GEditor || !GEditor->Trans) return PyErr_Format(PyExc_Exception, "no GEditor found"); PyObject *transactions = PyList_New(0); int32 nums = GEditor->Trans->GetQueueLength(); for (int32 i = 0; i < nums; i++) { const FTransaction *transaction = GEditor->Trans->GetTransaction(i); PyList_Append(transactions, PyUnicode_FromString(TCHAR_TO_UTF8(*transaction->GetTitle().ToString()))); } return transactions; } PyObject *py_unreal_engine_heightmap_expand(PyObject * self, PyObject * args) { Py_buffer buf; int width; int height; int new_width; int new_height; if (!PyArg_ParseTuple(args, "y*iiii:heightmap_expand", &buf, &width, &height, &new_width, &new_height)) return nullptr; uint16 *original_data_buf = (uint16 *)buf.buf; TArray<uint16> original_data; original_data.AddZeroed(buf.len / 2); FMemory::Memcpy(original_data.GetData(), original_data_buf, buf.len); int offset_x = (new_width - width) / 2; int offset_y = (new_height - height) / 2; TArray<uint16> data = LandscapeEditorUtils::ExpandData<uint16>(original_data, 0, 0, width - 1, height - 1, -offset_x, -offset_y, new_width - offset_x - 1, new_height - offset_y - 1); return PyByteArray_FromStringAndSize((char *)data.GetData(), data.Num() * sizeof(uint16)); } PyObject *py_unreal_engine_heightmap_import(PyObject * self, PyObject * args) { char *filename; int width = 0; int height = 0; if (!PyArg_ParseTuple(args, "s|ii:heightmap_import", &filename, &width, &height)) return nullptr; ILandscapeEditorModule & LandscapeModule = FModuleManager::GetModuleChecked<ILandscapeEditorModule>("LandscapeEditor"); const ILandscapeHeightmapFileFormat *format = LandscapeModule.GetHeightmapFormatByExtension(*FPaths::GetExtension(UTF8_TO_TCHAR(filename), true)); if (!format) { return PyErr_Format(PyExc_Exception, "invalid heightmap format"); } FLandscapeFileResolution resolution = { (uint32)width, (uint32)height }; if (width <= 0 || height <= 0) { FLandscapeHeightmapInfo info = format->Validate(UTF8_TO_TCHAR(filename)); if (info.ResultCode == ELandscapeImportResult::Error) { return PyErr_Format(PyExc_Exception, "unable to import heightmap: %s", TCHAR_TO_UTF8(*info.ErrorMessage.ToString())); } if (info.ResultCode == ELandscapeImportResult::Warning) { UE_LOG(LogPython, Warning, TEXT("%s"), *info.ErrorMessage.ToString()); } if (info.PossibleResolutions.Num() < 1) { return PyErr_Format(PyExc_Exception, "unable to retrieve heightmap resolution"); } resolution = info.PossibleResolutions[0]; } FLandscapeHeightmapImportData imported = format->Import(UTF8_TO_TCHAR(filename), resolution); if (imported.ResultCode == ELandscapeImportResult::Error) { return PyErr_Format(PyExc_Exception, "unable to import heightmap: %s", TCHAR_TO_UTF8(*imported.ErrorMessage.ToString())); } if (imported.ResultCode == ELandscapeImportResult::Warning) { UE_LOG(LogPython, Warning, TEXT("%s"), *imported.ErrorMessage.ToString()); } return Py_BuildValue((char *)"Oii", PyByteArray_FromStringAndSize((char *)imported.Data.GetData(), imported.Data.Num() * sizeof(uint16)), resolution.Width, resolution.Height); } PyObject *py_unreal_engine_play_preview_sound(PyObject * self, PyObject * args) { if (!GEditor) return PyErr_Format(PyExc_Exception, "no GEditor found"); PyObject *py_sound; if (!PyArg_ParseTuple(args, "O:play_preview_sound", &py_sound)) return nullptr; USoundBase *sound = ue_py_check_type<USoundBase>(py_sound); if (!sound) return PyErr_Format(PyExc_Exception, "argument is not a USoundBase"); Py_BEGIN_ALLOW_THREADS; GEditor->PlayPreviewSound(sound); Py_END_ALLOW_THREADS; Py_RETURN_NONE; } PyObject *py_unreal_engine_register_settings(PyObject * self, PyObject * args) { char *container_name; char *category_name; char *section_name; char *display_name; char *description; PyObject *py_uobject; if (!PyArg_ParseTuple(args, "sssssO:register_settings", &container_name, &category_name, &section_name, &display_name, &description, &py_uobject)) return nullptr; UObject *u_object = ue_py_check_type<UObject>(py_uobject); if (!u_object) return PyErr_Format(PyExc_Exception, "argument is not a UObject"); if (ISettingsModule* SettingsModule = FModuleManager::GetModulePtr<ISettingsModule>("Settings")) { TSharedPtr<ISettingsSection> section = SettingsModule->RegisterSettings(UTF8_TO_TCHAR(container_name), UTF8_TO_TCHAR(category_name), UTF8_TO_TCHAR(section_name), FText::FromString(UTF8_TO_TCHAR(display_name)), FText::FromString(UTF8_TO_TCHAR(description)), u_object); if (!section.IsValid()) return PyErr_Format(PyExc_Exception, "unable to register settings"); } else { return PyErr_Format(PyExc_Exception, "unable to find the Settings Module"); } Py_RETURN_NONE; } PyObject * py_unreal_engine_show_viewer(PyObject * self, PyObject * args) { char *container_name; char *category_name; char *section_name; if (!PyArg_ParseTuple(args, "sss:show_viewer", &container_name, &category_name, &section_name)) return nullptr; if (ISettingsModule* SettingsModule = FModuleManager::GetModulePtr<ISettingsModule>("Settings")) { Py_BEGIN_ALLOW_THREADS; SettingsModule->ShowViewer(container_name, category_name, section_name); Py_END_ALLOW_THREADS; } else { return PyErr_Format(PyExc_Exception, "unable to find the Settings Module"); } Py_RETURN_NONE; } PyObject *py_unreal_engine_unregister_settings(PyObject * self, PyObject * args) { char *container_name; char *category_name; char *section_name; if (!PyArg_ParseTuple(args, "sss:unregister_settings", &container_name, &category_name, &section_name)) return nullptr; if (ISettingsModule* SettingsModule = FModuleManager::GetModulePtr<ISettingsModule>("Settings")) { SettingsModule->UnregisterSettings(UTF8_TO_TCHAR(container_name), UTF8_TO_TCHAR(category_name), UTF8_TO_TCHAR(section_name)); } else { return PyErr_Format(PyExc_Exception, "unable to find the Settings Module"); } Py_RETURN_NONE; } PyObject *py_unreal_engine_all_viewport_clients(PyObject * self, PyObject * args) { #if ENGINE_MINOR_VERSION > 21 TArray<FEditorViewportClient *> clients = GEditor->GetAllViewportClients(); #else TArray<FEditorViewportClient *> clients = GEditor->AllViewportClients; #endif PyObject *py_list = PyList_New(0); for (FEditorViewportClient *client : clients) { PyList_Append(py_list, py_ue_new_feditor_viewport_client(TSharedRef<FEditorViewportClient>(client))); } return py_list; } PyObject *py_unreal_engine_editor_sync_browser_to_assets(PyObject * self, PyObject * args) { PyObject *py_items; PyObject *py_focus = nullptr; if (!PyArg_ParseTuple(args, "O|O:sync_browser_to_assets", &py_items, &py_focus)) return nullptr; PyObject *py_iter = PyObject_GetIter(py_items); if (!py_iter) { return PyErr_Format(PyExc_Exception, "argument is not an iterable of UObject or FAssetData"); } FContentBrowserModule& ContentBrowserModule = FModuleManager::Get().LoadModuleChecked<FContentBrowserModule>("ContentBrowser"); TArray<FAssetData> asset_data; TArray<UObject *> uobjects; while (PyObject *py_item = PyIter_Next(py_iter)) { ue_PyFAssetData *py_data = py_ue_is_fassetdata(py_item); if (py_data) { asset_data.Add(py_data->asset_data); } else { UObject *u_object = ue_py_check_type<UObject>(py_item); if (!u_object) { return PyErr_Format(PyExc_Exception, "invalid item in iterable, must be UObject or FAssetData"); } uobjects.Add(u_object); } } bool bFocus = false; if (py_focus && PyObject_IsTrue(py_focus)) bFocus = true; Py_BEGIN_ALLOW_THREADS; if (asset_data.Num() > 0) { ContentBrowserModule.Get().SyncBrowserToAssets(asset_data, false, bFocus); } if (uobjects.Num() > 0) { ContentBrowserModule.Get().SyncBrowserToAssets(uobjects, false, bFocus); } Py_END_ALLOW_THREADS; Py_DECREF(py_iter); Py_RETURN_NONE; } PyObject *py_unreal_engine_export_assets(PyObject * self, PyObject * args) { if (!GEditor) return PyErr_Format(PyExc_Exception, "no GEditor found"); PyObject * py_assets = nullptr; char *filename; if (!PyArg_ParseTuple(args, "Os:export_assets", &py_assets, &filename)) { return nullptr; } TArray<UObject *> UObjects; PyObject *py_iter = PyObject_GetIter(py_assets); if (!py_iter) { return PyErr_Format(PyExc_Exception, "argument is not an iterable of UObject"); } while (PyObject *py_item = PyIter_Next(py_iter)) { UObject *Object = ue_py_check_type<UObject>(py_item); if (!Object) { Py_DECREF(py_iter); return PyErr_Format(PyExc_Exception, "argument is not an iterable of UObject"); } UObjects.Add(Object); } Py_DECREF(py_iter); #if ENGINE_MINOR_VERSION > 16 Py_BEGIN_ALLOW_THREADS; FAssetToolsModule& AssetToolsModule = FModuleManager::LoadModuleChecked<FAssetToolsModule>("AssetTools"); AssetToolsModule.Get().ExportAssets(UObjects, FString(UTF8_TO_TCHAR(filename))); Py_END_ALLOW_THREADS; #else return PyErr_Format(PyExc_Exception, "Asset exporting not supported in this engine version"); #endif Py_RETURN_NONE; } #endif ```
/content/code_sandbox/Source/UnrealEnginePython/Private/UEPyEditor.cpp
c++
2016-08-07T05:00:51
2024-08-14T06:32:20
UnrealEnginePython
20tab/UnrealEnginePython
2,715
18,481
```c++ #include "PythonSmartDelegate.h" #include "UEPyModule.h" #if WITH_EDITOR #include "Slate/UEPySWindow.h" #endif FPythonSmartDelegate::FPythonSmartDelegate() { py_callable = nullptr; } void FPythonSmartDelegate::SetPyCallable(PyObject *callable) { // do not acquire the gil here as we set the callable in python call themselves py_callable = callable; Py_INCREF(py_callable); } bool FPythonSmartDelegate::Tick(float DeltaTime) { FScopePythonGIL gil; PyObject *ret = PyObject_CallFunction(py_callable, (char *)"f", DeltaTime); if (!ret) { unreal_engine_py_log_error(); return false; } if (PyObject_IsTrue(ret)) { Py_DECREF(ret); return true; } Py_DECREF(ret); return false; } void FPythonSmartDelegate::Void() { FScopePythonGIL gil; PyObject *ret = PyObject_CallFunction(py_callable, nullptr); if (!ret) { unreal_engine_py_log_error(); return; } Py_DECREF(ret); } #if WITH_EDITOR void FPythonSmartDelegate::PyFOnAssetPostImport(UFactory *factory, UObject *u_object) { FScopePythonGIL gil; PyObject *ret = PyObject_CallFunction(py_callable, (char *)"OO", ue_get_python_uobject((UObject *)factory), ue_get_python_uobject(u_object)); if (!ret) { unreal_engine_py_log_error(); return; } Py_DECREF(ret); } void FPythonSmartDelegate::PyFOnMainFrameCreationFinished(TSharedPtr<SWindow> InRootWindow, bool bIsNewProjectWindow) { FScopePythonGIL gil; PyObject *ret = PyObject_CallFunction(py_callable, (char *)"NO", py_ue_new_swidget<ue_PySWindow>(InRootWindow.ToSharedRef(), &ue_PySWindowType), bIsNewProjectWindow ? Py_True : Py_False); if (!ret) { unreal_engine_py_log_error(); return; } Py_DECREF(ret); } #endif FPythonSmartDelegate::~FPythonSmartDelegate() { FScopePythonGIL gil; Py_XDECREF(py_callable); #if defined(UEPY_MEMORY_DEBUG) UE_LOG(LogPython, Warning, TEXT("PythonSmartDelegate callable XDECREF'ed")); #endif } ```
/content/code_sandbox/Source/UnrealEnginePython/Private/PythonSmartDelegate.cpp
c++
2016-08-07T05:00:51
2024-08-14T06:32:20
UnrealEnginePython
20tab/UnrealEnginePython
2,715
509
```c++ #include "UEPyModule.h" #include "PythonClass.h" #include "UObject/UEPyObject.h" // hack for avoiding loops in class constructors (thanks to the Unreal.js project for the idea) UClass *ue_py_class_constructor_placeholder = nullptr; static void UEPyClassConstructor(UClass *u_class, const FObjectInitializer &ObjectInitializer) { if (UPythonClass *u_py_class_casted = Cast<UPythonClass>(u_class)) { ue_py_class_constructor_placeholder = u_class; } u_class->ClassConstructor(ObjectInitializer); ue_py_class_constructor_placeholder = nullptr; } int unreal_engine_py_init(ue_PyUObject *self, PyObject *args, PyObject *kwds) { // is it subclassing ? if (PyTuple_Size(args) == 3) { // TODO make it smarter on error checking UE_LOG(LogPython, Warning, TEXT("%s"), UTF8_TO_TCHAR(UEPyUnicode_AsUTF8(PyObject_Str(PyTuple_GetItem(args, 0))))); UE_LOG(LogPython, Warning, TEXT("%s"), UTF8_TO_TCHAR(UEPyUnicode_AsUTF8(PyObject_Str(PyTuple_GetItem(args, 1))))); UE_LOG(LogPython, Warning, TEXT("%s"), UTF8_TO_TCHAR(UEPyUnicode_AsUTF8(PyObject_Str(PyTuple_GetItem(args, 2))))); PyObject *parents = PyTuple_GetItem(args, 1); ue_PyUObject *parent = (ue_PyUObject *)PyTuple_GetItem(parents, 0); PyObject *class_attributes = PyTuple_GetItem(args, 2); PyObject *class_name = PyDict_GetItemString(class_attributes, (char *)"__qualname__"); const char *name = UEPyUnicode_AsUTF8(class_name); // check if parent is a uclass UClass *new_class = unreal_engine_new_uclass((char *)name, (UClass *)parent->ue_object); if (!new_class) return -1; // map the class to the python object self->ue_object = new_class; self->py_proxy = nullptr; self->auto_rooted = 0; self->py_dict = PyDict_New(); FUnrealEnginePythonHouseKeeper::Get()->RegisterPyUObject(new_class, self); PyObject *py_additional_properties = PyDict_New(); PyObject *class_attributes_keys = PyObject_GetIter(class_attributes); for (;;) { PyObject *key = PyIter_Next(class_attributes_keys); if (!key) { if (PyErr_Occurred()) return -1; break; } if (!PyUnicodeOrString_Check(key)) continue; const char *class_key = UEPyUnicode_AsUTF8(key); PyObject *value = PyDict_GetItem(class_attributes, key); if (strlen(class_key) > 2 && class_key[0] == '_' && class_key[1] == '_') { continue; } bool prop_added = false; if (UProperty *u_property = new_class->FindPropertyByName(FName(UTF8_TO_TCHAR(class_key)))) { UE_LOG(LogPython, Warning, TEXT("Found UProperty %s"), UTF8_TO_TCHAR(class_key)); PyDict_SetItem(py_additional_properties, key, value); prop_added = true; } // add simple property else if (ue_is_pyuobject(value)) { ue_PyUObject *py_obj = (ue_PyUObject *)value; if (py_obj->ue_object->IsA<UClass>()) { UClass *p_class = (UClass *)py_obj->ue_object; if (p_class->IsChildOf<UProperty>()) { if (!py_ue_add_property(self, Py_BuildValue("(Os)", value, class_key))) { unreal_engine_py_log_error(); return -1; } prop_added = true; } else { if (!py_ue_add_property(self, Py_BuildValue("(OsO)", (PyObject *)ue_get_python_uobject(UObjectProperty::StaticClass()), class_key, value))) { unreal_engine_py_log_error(); return -1; } prop_added = true; } } else if (py_obj->ue_object->IsA<UScriptStruct>()) { if (!py_ue_add_property(self, Py_BuildValue("(OsO)", (PyObject *)ue_get_python_uobject(UStructProperty::StaticClass()), class_key, value))) { unreal_engine_py_log_error(); return -1; } prop_added = true; } } // add array property else if (PyList_Check(value)) { if (PyList_Size(value) == 1) { PyObject *first_item = PyList_GetItem(value, 0); if (ue_is_pyuobject(first_item)) { ue_PyUObject *py_obj = (ue_PyUObject *)first_item; if (py_obj->ue_object->IsA<UClass>()) { UClass *p_class = (UClass *)py_obj->ue_object; if (p_class->IsChildOf<UProperty>()) { if (!py_ue_add_property(self, Py_BuildValue("(Os)", value, class_key))) { unreal_engine_py_log_error(); return -1; } prop_added = true; } else { if (!py_ue_add_property(self, Py_BuildValue("([O]sO)", (PyObject *)ue_get_python_uobject(UObjectProperty::StaticClass()), class_key, first_item))) { unreal_engine_py_log_error(); return -1; } prop_added = true; } } else if (py_obj->ue_object->IsA<UScriptStruct>()) { if (!py_ue_add_property(self, Py_BuildValue("([O]sO)", (PyObject *)ue_get_python_uobject(UStructProperty::StaticClass()), class_key, first_item))) { unreal_engine_py_log_error(); return -1; } prop_added = true; } } } } #if ENGINE_MINOR_VERSION >= 15 else if (PyDict_Check(value)) { if (PyDict_Size(value) == 1) { PyObject *py_key = nullptr; PyObject *py_value = nullptr; Py_ssize_t pos = 0; PyDict_Next(value, &pos, &py_key, &py_value); if (ue_is_pyuobject(py_key) && ue_is_pyuobject(py_value)) { PyObject *first_item = nullptr; PyObject *second_item = nullptr; ue_PyUObject *py_obj = (ue_PyUObject *)py_key; if (py_obj->ue_object->IsA<UClass>()) { UClass *p_class = (UClass *)py_obj->ue_object; if (p_class->IsChildOf<UProperty>()) { first_item = py_key; } else { first_item = (PyObject *)ue_get_python_uobject(UObjectProperty::StaticClass()); } } else if (py_obj->ue_object->IsA<UScriptStruct>()) { first_item = (PyObject *)ue_get_python_uobject(UStructProperty::StaticClass()); } ue_PyUObject *py_obj2 = (ue_PyUObject *)py_value; if (py_obj2->ue_object->IsA<UClass>()) { UClass *p_class = (UClass *)py_obj2->ue_object; if (p_class->IsChildOf<UProperty>()) { second_item = py_value; } else { second_item = (PyObject *)ue_get_python_uobject(UObjectProperty::StaticClass()); } } else if (py_obj2->ue_object->IsA<UScriptStruct>()) { second_item = (PyObject *)ue_get_python_uobject(UStructProperty::StaticClass()); } if (!py_ue_add_property(self, Py_BuildValue("([OO]sOO)", first_item, second_item, class_key, py_key, py_value))) { unreal_engine_py_log_error(); return -1; } prop_added = true; } } } #endif // function ? else if (PyCallable_Check(value) && class_key[0] >= 'A' && class_key[0] <= 'Z') { uint32 func_flags = FUNC_Native | FUNC_BlueprintCallable | FUNC_Public; PyObject *is_event = PyObject_GetAttrString(value, (char *)"event"); if (is_event && PyObject_IsTrue(is_event)) { func_flags |= FUNC_Event | FUNC_BlueprintEvent; } else if (!is_event) PyErr_Clear(); PyObject *is_multicast = PyObject_GetAttrString(value, (char *)"multicast"); if (is_multicast && PyObject_IsTrue(is_multicast)) { func_flags |= FUNC_NetMulticast; } else if (!is_multicast) PyErr_Clear(); PyObject *is_server = PyObject_GetAttrString(value, (char *)"server"); if (is_server && PyObject_IsTrue(is_server)) { func_flags |= FUNC_NetServer; } else if (!is_server) PyErr_Clear(); PyObject *is_client = PyObject_GetAttrString(value, (char *)"client"); if (is_client && PyObject_IsTrue(is_client)) { func_flags |= FUNC_NetClient; } else if (!is_client) PyErr_Clear(); PyObject *is_reliable = PyObject_GetAttrString(value, (char *)"reliable"); if (is_reliable && PyObject_IsTrue(is_reliable)) { func_flags |= FUNC_NetReliable; } else if (!is_reliable) PyErr_Clear(); PyObject *is_pure = PyObject_GetAttrString(value, (char *)"pure"); if (is_pure && PyObject_IsTrue(is_pure)) { func_flags |= FUNC_BlueprintPure; } else if (!is_pure) PyErr_Clear(); PyObject *is_static = PyObject_GetAttrString(value, (char *)"static"); if (is_static && PyObject_IsTrue(is_static)) { func_flags |= FUNC_Static; } else if (!is_static) PyErr_Clear(); PyObject *override_name = PyObject_GetAttrString(value, (char *)"override"); if (override_name && PyUnicodeOrString_Check(override_name)) { class_key = UEPyUnicode_AsUTF8(override_name); } else if (override_name && PyUnicodeOrString_Check(override_name)) { class_key = UEPyUnicode_AsUTF8(override_name); } else if (!override_name) PyErr_Clear(); if (!unreal_engine_add_function(new_class, (char *)class_key, value, func_flags)) { UE_LOG(LogPython, Error, TEXT("unable to add function %s"), UTF8_TO_TCHAR(class_key)); return -1; } prop_added = true; } if (!prop_added) { UE_LOG(LogPython, Warning, TEXT("Adding %s as attr"), UTF8_TO_TCHAR(class_key)); PyObject_SetAttr((PyObject *)self, key, value); } } if (PyDict_Size(py_additional_properties) > 0) { PyObject_SetAttrString((PyObject *)self, (char*)"__additional_uproperties__", py_additional_properties); } UPythonClass *new_u_py_class = (UPythonClass *)new_class; // TODO: check if we can use this to decref the ue_PyUbject mapped to the class new_u_py_class->py_uobject = self; new_u_py_class->ClassConstructor = [](const FObjectInitializer &ObjectInitializer) { FScopePythonGIL gil; UClass *u_class = ue_py_class_constructor_placeholder ? ue_py_class_constructor_placeholder : ObjectInitializer.GetClass(); ue_py_class_constructor_placeholder = nullptr; UEPyClassConstructor(u_class->GetSuperClass(), ObjectInitializer); if (UPythonClass *u_py_class_casted = Cast<UPythonClass>(u_class)) { ue_PyUObject *new_self = ue_get_python_uobject(ObjectInitializer.GetObj()); if (!new_self) { unreal_engine_py_log_error(); return; } // fill __dict__ from class if (u_py_class_casted->py_uobject && u_py_class_casted->py_uobject->py_dict) { PyObject *found_additional_props = PyDict_GetItemString(u_py_class_casted->py_uobject->py_dict, (char *)"__additional_uproperties__"); // manage UProperties (and automatically maps multicast properties) if (found_additional_props) { PyObject *keys = PyDict_Keys(found_additional_props); Py_ssize_t items_len = PyList_Size(keys); for (Py_ssize_t i = 0; i < items_len; i++) { PyObject *mc_key = PyList_GetItem(keys, i); PyObject *mc_value = PyDict_GetItem(found_additional_props, mc_key); const char *mc_name = UEPyUnicode_AsUTF8(mc_key); UProperty *u_property = ObjectInitializer.GetObj()->GetClass()->FindPropertyByName(FName(UTF8_TO_TCHAR(mc_name))); if (u_property) { if (auto casted_prop = Cast<UMulticastDelegateProperty>(u_property)) { #if ENGINE_MINOR_VERSION >= 23 FMulticastScriptDelegate multiscript_delegate = *casted_prop->GetMulticastDelegate(ObjectInitializer.GetObj()); #else FMulticastScriptDelegate multiscript_delegate = casted_prop->GetPropertyValue_InContainer(ObjectInitializer.GetObj()); #endif FScriptDelegate script_delegate; UPythonDelegate *py_delegate = FUnrealEnginePythonHouseKeeper::Get()->NewDelegate(ObjectInitializer.GetObj(), mc_value, casted_prop->SignatureFunction); // fake UFUNCTION for bypassing checks script_delegate.BindUFunction(py_delegate, FName("PyFakeCallable")); // add the new delegate multiscript_delegate.Add(script_delegate); // re-assign multicast delegate #if ENGINE_MINOR_VERSION >= 23 casted_prop->SetMulticastDelegate(ObjectInitializer.GetObj(), multiscript_delegate); #else casted_prop->SetPropertyValue_InContainer(ObjectInitializer.GetObj(), multiscript_delegate); #endif } else { PyObject_SetAttr((PyObject *)new_self, mc_key, mc_value); } } } Py_DECREF(keys); } else { PyErr_Clear(); } PyObject *keys = PyDict_Keys(u_py_class_casted->py_uobject->py_dict); Py_ssize_t keys_len = PyList_Size(keys); for (Py_ssize_t i = 0; i < keys_len; i++) { PyObject *key = PyList_GetItem(keys, i); PyObject *value = PyDict_GetItem(u_py_class_casted->py_uobject->py_dict, key); if (PyUnicodeOrString_Check(key)) { const char *key_name = UEPyUnicode_AsUTF8(key); if (!strcmp(key_name, (char *)"__additional_uproperties__")) continue; } // special case to bound function to method if (PyFunction_Check(value)) { PyObject *bound_function = PyObject_CallMethod(value, (char*)"__get__", (char*)"O", (PyObject *)new_self); if (bound_function) { PyObject_SetAttr((PyObject *)new_self, key, bound_function); Py_DECREF(bound_function); } else { unreal_engine_py_log_error(); } } else { PyObject_SetAttr((PyObject *)new_self, key, value); } } Py_DECREF(keys); } // call __init__ u_py_class_casted->CallPyConstructor(new_self); } }; if (self->py_dict) { ue_PyUObject *new_default_self = ue_get_python_uobject(new_u_py_class->ClassDefaultObject); if (!new_default_self) { unreal_engine_py_log_error(); UE_LOG(LogPython, Error, TEXT("unable to set dict on new ClassDefaultObject")); return -1; } PyObject *keys = PyDict_Keys(self->py_dict); Py_ssize_t keys_len = PyList_Size(keys); for (Py_ssize_t i = 0; i < keys_len; i++) { PyObject *key = PyList_GetItem(keys, i); PyObject *value = PyDict_GetItem(self->py_dict, key); // special case to bound function to method if (PyFunction_Check(value)) { PyObject *bound_function = PyObject_CallMethod(value, (char*)"__get__", (char*)"O", (PyObject *)new_default_self); if (bound_function) { PyObject_SetAttr((PyObject *)new_default_self, key, bound_function); Py_DECREF(bound_function); } else { unreal_engine_py_log_error(); } } else { PyObject_SetAttr((PyObject *)new_default_self, key, value); } } Py_DECREF(keys); } // add default uproperties values if (py_additional_properties) { ue_PyUObject *new_default_self = ue_get_python_uobject(new_u_py_class->ClassDefaultObject); if (!new_default_self) { unreal_engine_py_log_error(); UE_LOG(LogPython, Error, TEXT("unable to set properties on new ClassDefaultObject")); return -1; } PyObject *keys = PyDict_Keys(py_additional_properties); Py_ssize_t keys_len = PyList_Size(keys); for (Py_ssize_t i = 0; i < keys_len; i++) { PyObject *key = PyList_GetItem(keys, i); PyObject *value = PyDict_GetItem(py_additional_properties, key); PyObject_SetAttr((PyObject *)new_default_self, key, value); } Py_DECREF(keys); } // add custom constructor (__init__) PyObject *py_init = PyDict_GetItemString(class_attributes, (char *)"__init__"); if (py_init && PyCallable_Check(py_init)) { // fake initializer FObjectInitializer initializer(new_u_py_class->ClassDefaultObject, nullptr, false, true); new_u_py_class->SetPyConstructor(py_init); ue_PyUObject *new_default_self = ue_get_python_uobject(new_u_py_class->ClassDefaultObject); if (!new_default_self) { unreal_engine_py_log_error(); UE_LOG(LogPython, Error, TEXT("unable to call __init__ on new ClassDefaultObject")); return -1; } new_u_py_class->CallPyConstructor(new_default_self); } } return 0; } ```
/content/code_sandbox/Source/UnrealEnginePython/Private/UEPySubclassing.cpp
c++
2016-08-07T05:00:51
2024-08-14T06:32:20
UnrealEnginePython
20tab/UnrealEnginePython
2,715
4,375
```c++ #include "UEPyUStructsImporter.h" static PyObject *ue_PyUStructsImporter_getattro(ue_PyUStructsImporter *self, PyObject *attr_name) { PyObject *py_attr = PyObject_GenericGetAttr((PyObject *)self, attr_name); if (!py_attr) { if (PyUnicodeOrString_Check(attr_name)) { const char *attr = UEPyUnicode_AsUTF8(attr_name); if (attr[0] != '_') { UScriptStruct *u_struct = FindObject<UScriptStruct>(ANY_PACKAGE, UTF8_TO_TCHAR(attr)); if (u_struct) { // swallow old exception PyErr_Clear(); Py_RETURN_UOBJECT(u_struct); } } } } return py_attr; } static PyTypeObject ue_PyUStructsImporterType = { PyVarObject_HEAD_INIT(NULL, 0) "unreal_engine.UStructsImporter", /* tp_name */ sizeof(ue_PyUStructsImporter), /* tp_basicsize */ 0, /* tp_itemsize */ 0, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_reserved */ 0, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ (getattrofunc)ue_PyUStructsImporter_getattro, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT, /* tp_flags */ "Unreal Engine UStructs Importer", /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ 0, /* tp_methods */ 0, 0, }; void ue_python_init_ustructsimporter(PyObject *ue_module) { ue_PyUStructsImporterType.tp_new = PyType_GenericNew; if (PyType_Ready(&ue_PyUStructsImporterType) < 0) return; Py_INCREF(&ue_PyUStructsImporterType); PyModule_AddObject(ue_module, "UStructsImporter", (PyObject *)&ue_PyUStructsImporterType); } PyObject *py_ue_new_ustructsimporter() { ue_PyUStructsImporter *ret = (ue_PyUStructsImporter *)PyObject_New(ue_PyUStructsImporter, &ue_PyUStructsImporterType); return (PyObject *)ret; } ```
/content/code_sandbox/Source/UnrealEnginePython/Private/UEPyUStructsImporter.cpp
c++
2016-08-07T05:00:51
2024-08-14T06:32:20
UnrealEnginePython
20tab/UnrealEnginePython
2,715
651
```objective-c #pragma once #include "UEPyModule.h" typedef struct { PyObject_HEAD /* Type-specific fields go here. */ } ue_PyEnumsImporter; PyObject *py_ue_new_enumsimporter(); void ue_python_init_enumsimporter(PyObject *); ```
/content/code_sandbox/Source/UnrealEnginePython/Private/UEPyEnumsImporter.h
objective-c
2016-08-07T05:00:51
2024-08-14T06:32:20
UnrealEnginePython
20tab/UnrealEnginePython
2,715
57
```c++ #include "PythonScript.h" #include "UEPyModule.h" static void callback(void *arg) { UPythonScript *self = (UPythonScript *)arg; self->CallSpecificFunctionWithArgs(); } void UPythonScript::Run() { FUnrealEnginePythonModule &PythonModule = FModuleManager::GetModuleChecked<FUnrealEnginePythonModule>("UnrealEnginePython"); PythonModule.RunFile(TCHAR_TO_UTF8(*ScriptPath)); if (!FunctionToCall.IsEmpty()) { CallSpecificFunctionWithArgs(); } } void UPythonScript::CallSpecificFunctionWithArgs() { PyObject *function_to_call = PyDict_GetItemString(PyEval_GetGlobals(), TCHAR_TO_UTF8(*FunctionToCall)); if (!function_to_call) { UE_LOG(LogPython, Error, TEXT("unable to find function %s"), *FunctionToCall); return; } int n = FunctionArgs.Num(); PyObject *args = nullptr; if (n > 0) args = PyTuple_New(n); for (int i = 0; i < n; i++) { PyTuple_SetItem(args, i, PyUnicode_FromString(TCHAR_TO_UTF8(*FunctionArgs[i]))); } PyObject *ret = PyObject_Call(function_to_call, args, nullptr); Py_DECREF(args); if (!ret) { unreal_engine_py_log_error(); } else { Py_DECREF(ret); } } ```
/content/code_sandbox/Source/UnrealEnginePython/Private/PythonScript.cpp
c++
2016-08-07T05:00:51
2024-08-14T06:32:20
UnrealEnginePython
20tab/UnrealEnginePython
2,715
306
```objective-c #pragma once #include "UEPyModule.h" PyObject *py_unreal_engine_log(PyObject *, PyObject *); PyObject *py_unreal_engine_log_warning(PyObject *, PyObject *); PyObject *py_unreal_engine_log_error(PyObject *, PyObject *); PyObject *py_unreal_engine_add_on_screen_debug_message(PyObject *, PyObject *); PyObject *py_unreal_engine_print_string(PyObject *, PyObject *); PyObject *py_unreal_engine_get_forward_vector(PyObject *, PyObject *); PyObject *py_unreal_engine_get_right_vector(PyObject *, PyObject *); PyObject *py_unreal_engine_get_up_vector(PyObject *, PyObject *); PyObject *py_unreal_engine_clipboard_copy(PyObject *, PyObject *); PyObject *py_unreal_engine_clipboard_paste(PyObject *, PyObject *); PyObject *py_unreal_engine_set_random_seed(PyObject *, PyObject *); PyObject *py_unreal_engine_get_game_viewport_size(PyObject *, PyObject *); PyObject *py_unreal_engine_get_resolution(PyObject *, PyObject *); PyObject *py_unreal_engine_get_content_dir(PyObject *, PyObject *); PyObject *py_unreal_engine_get_game_saved_dir(PyObject *, PyObject *); PyObject *py_unreal_engine_get_game_user_developer_dir(PyObject *, PyObject *); PyObject *py_unreal_engine_find_object(PyObject *, PyObject *); PyObject *py_unreal_engine_find_class(PyObject *, PyObject *); PyObject *py_unreal_engine_find_struct(PyObject *, PyObject *); PyObject *py_unreal_engine_find_enum(PyObject *, PyObject *); PyObject *py_unreal_engine_load_object(PyObject *, PyObject *); PyObject *py_unreal_engine_load_class(PyObject *, PyObject *); PyObject *py_unreal_engine_load_struct(PyObject *, PyObject *); PyObject *py_unreal_engine_load_enum(PyObject *, PyObject *); PyObject *py_unreal_engine_load_package(PyObject *, PyObject *); #if WITH_EDITOR PyObject *py_unreal_engine_unload_package(PyObject *, PyObject *); PyObject *py_unreal_engine_get_package_filename(PyObject *, PyObject *); #endif PyObject *py_unreal_engine_string_to_guid(PyObject *, PyObject *); PyObject *py_unreal_engine_new_guid(PyObject *, PyObject *); PyObject *py_unreal_engine_guid_to_string(PyObject *, PyObject *); PyObject *py_unreal_engine_engine_tick(PyObject *, PyObject *); PyObject *py_unreal_engine_slate_tick(PyObject *, PyObject *); PyObject *py_unreal_engine_get_delta_time(PyObject *, PyObject *); PyObject *py_unreal_engine_tick_rendering_tickables(PyObject *, PyObject *); PyObject *py_unreal_engine_all_classes(PyObject *, PyObject *); PyObject *py_unreal_engine_all_worlds(PyObject *, PyObject *); PyObject *py_unreal_engine_tobject_iterator(PyObject *, PyObject *); PyObject *py_unreal_engine_all_worlds(PyObject *, PyObject *); PyObject *py_unreal_engine_tobject_iterator(PyObject *, PyObject *); PyObject *py_unreal_engine_new_object(PyObject *, PyObject *); PyObject *py_unreal_engine_new_class(PyObject *, PyObject *); PyObject *py_unreal_engine_get_mutable_default(PyObject *, PyObject *); PyObject *py_unreal_engine_create_and_dispatch_when_ready(PyObject *, PyObject *); PyObject *py_unreal_engine_convert_relative_path_to_full(PyObject *, PyObject *); PyObject *py_unreal_engine_get_viewport_screenshot(PyObject *, PyObject *); PyObject *py_unreal_engine_get_viewport_size(PyObject *, PyObject *); PyObject *py_unreal_engine_create_world(PyObject *, PyObject *); PyObject *py_unreal_engine_create_package(PyObject *, PyObject *); PyObject *py_unreal_engine_get_or_create_package(PyObject *, PyObject *); PyObject *py_unreal_engine_get_transient_package(PyObject *, PyObject *); PyObject *py_unreal_engine_object_path_to_package_name(PyObject *, PyObject *); PyObject *py_unreal_engine_get_path(PyObject *, PyObject *); PyObject *py_unreal_engine_get_base_filename(PyObject *, PyObject *); PyObject *py_unreal_engine_open_file_dialog(PyObject *, PyObject *); PyObject *py_unreal_engine_open_font_dialog(PyObject *, PyObject *); PyObject *py_unreal_engine_open_directory_dialog(PyObject *, PyObject *); PyObject *py_unreal_engine_save_file_dialog(PyObject *, PyObject *); PyObject *py_unreal_engine_copy_properties_for_unrelated_objects(PyObject *, PyObject *, PyObject *); #if WITH_EDITOR PyObject *py_unreal_engine_editor_get_active_viewport_screenshot(PyObject *, PyObject *); PyObject *py_unreal_engine_editor_get_pie_viewport_screenshot(PyObject *, PyObject *); PyObject *py_unreal_engine_editor_get_active_viewport_size(PyObject *, PyObject *); PyObject *py_unreal_engine_editor_get_pie_viewport_size(PyObject *, PyObject *); #endif #if PLATFORM_MAC PyObject *py_unreal_engine_main_thread_call(PyObject *, PyObject *); #endif ```
/content/code_sandbox/Source/UnrealEnginePython/Private/UEPyEngine.h
objective-c
2016-08-07T05:00:51
2024-08-14T06:32:20
UnrealEnginePython
20tab/UnrealEnginePython
2,715
870
```objective-c #pragma once #include "UEPyModule.h" #include "Runtime/Core/Public/Containers/Ticker.h" typedef struct { PyObject_HEAD /* Type-specific fields go here. */ FDelegateHandle dhandle; bool garbaged; TSharedPtr<FPythonSmartDelegate> delegate_ptr; } ue_PyFDelegateHandle; PyObject *py_unreal_engine_add_ticker(PyObject *, PyObject *); PyObject *py_unreal_engine_remove_ticker(PyObject *, PyObject *); void ue_python_init_fdelegatehandle(PyObject *); ```
/content/code_sandbox/Source/UnrealEnginePython/Private/UEPyTicker.h
objective-c
2016-08-07T05:00:51
2024-08-14T06:32:20
UnrealEnginePython
20tab/UnrealEnginePython
2,715
108
```c++ #include "UEPyTicker.h" // destructor static void ue_pyfdelegatehandle_dealloc(ue_PyFDelegateHandle *self) { if (!self->garbaged) { FTicker::GetCoreTicker().RemoveTicker(self->dhandle); // useless ;) self->garbaged = true; } if (self->delegate_ptr.IsValid()) { self->delegate_ptr.Reset(); } Py_TYPE(self)->tp_free((PyObject *)self); } static PyTypeObject ue_PyFDelegateHandleType = { PyVarObject_HEAD_INIT(NULL, 0) "unreal_engine.FDelegateHandle", /* tp_name */ sizeof(ue_PyFDelegateHandle), /* tp_basicsize */ 0, /* tp_itemsize */ (destructor)ue_pyfdelegatehandle_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_reserved */ 0, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ 0, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT, /* tp_flags */ "Unreal Engine FDelegateHandle", /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ 0, /* tp_methods */ }; void ue_python_init_fdelegatehandle(PyObject *ue_module) { ue_PyFDelegateHandleType.tp_new = PyType_GenericNew; if (PyType_Ready(&ue_PyFDelegateHandleType) < 0) return; Py_INCREF(&ue_PyFDelegateHandleType); PyModule_AddObject(ue_module, "FDelegateHandle", (PyObject *)&ue_PyFDelegateHandleType); } PyObject *py_unreal_engine_add_ticker(PyObject * self, PyObject * args) { PyObject *py_callable; float delay = 0; if (!PyArg_ParseTuple(args, "O|f:add_ticker", &py_callable, &delay)) { return nullptr; } if (!PyCallable_Check(py_callable)) return PyErr_Format(PyExc_Exception, "argument is not a callable"); ue_PyFDelegateHandle *ret = (ue_PyFDelegateHandle *)PyObject_New(ue_PyFDelegateHandle, &ue_PyFDelegateHandleType); if (!ret) { return PyErr_Format(PyExc_Exception, "unable to allocate FDelegateHandle python object"); } FTickerDelegate ticker_delegate; TSharedRef<FPythonSmartDelegate> py_delegate = MakeShareable(new FPythonSmartDelegate); py_delegate->SetPyCallable(py_callable); ticker_delegate.BindSP(py_delegate, &FPythonSmartDelegate::Tick); ret->dhandle = FTicker::GetCoreTicker().AddTicker(ticker_delegate, delay); if (!ret->dhandle.IsValid()) { Py_DECREF(ret); return PyErr_Format(PyExc_Exception, "unable to add FTicker"); } new(&ret->delegate_ptr) TSharedPtr<FPythonSmartDelegate>(py_delegate); ret->garbaged = false; return (PyObject *)ret; } PyObject *py_unreal_engine_remove_ticker(PyObject * self, PyObject * args) { PyObject *py_obj; if (!PyArg_ParseTuple(args, "O:remove_ticker", &py_obj)) { return NULL; } if (!PyObject_IsInstance(py_obj, (PyObject *)&ue_PyFDelegateHandleType)) return PyErr_Format(PyExc_Exception, "argument is not a PyFDelegateHandle"); ue_PyFDelegateHandle *py_handle = (ue_PyFDelegateHandle *)py_obj; if (!py_handle->garbaged) { FTicker::GetCoreTicker().RemoveTicker(py_handle->dhandle); py_handle->garbaged = true; if (py_handle->delegate_ptr.IsValid()) { py_handle->delegate_ptr.Reset(); } } Py_RETURN_NONE; } ```
/content/code_sandbox/Source/UnrealEnginePython/Private/UEPyTicker.cpp
c++
2016-08-07T05:00:51
2024-08-14T06:32:20
UnrealEnginePython
20tab/UnrealEnginePython
2,715
947
```c++ #include "PythonBlueprintFunctionLibrary.h" void UPythonBlueprintFunctionLibrary::ExecutePythonScript(FString script) { FUnrealEnginePythonModule &PythonModule = FModuleManager::GetModuleChecked<FUnrealEnginePythonModule>("UnrealEnginePython"); PythonModule.RunFile(TCHAR_TO_UTF8(*script)); } void UPythonBlueprintFunctionLibrary::ExecutePythonString(const FString& PythonCmd) { FUnrealEnginePythonModule &PythonModule = FModuleManager::GetModuleChecked<FUnrealEnginePythonModule>("UnrealEnginePython"); PythonModule.RunString(TCHAR_TO_UTF8(*PythonCmd)); } ```
/content/code_sandbox/Source/UnrealEnginePython/Private/PythonBlueprintFunctionLibrary.cpp
c++
2016-08-07T05:00:51
2024-08-14T06:32:20
UnrealEnginePython
20tab/UnrealEnginePython
2,715
129
```objective-c #pragma once #include "UnrealEnginePython.h" #include "PythonDelegate.h" #include "PythonSmartDelegate.h" #include "UEPyUScriptStruct.h" #include "PythonHouseKeeper.h" // common wrappersno #include "Wrappers/UEPyFVector.h" #include "Wrappers/UEPyFRotator.h" #include "Wrappers/UEPyFQuat.h" #include "Wrappers/UEPyFTransform.h" #include "Wrappers/UEPyFColor.h" #include "Wrappers/UEPyFLinearColor.h" // backward compatibility for UE4.20 TCHAR_TO_WCHAR #ifndef TCHAR_TO_WCHAR // SIZEOF_WCHAR_T is provided by pyconfig.h #if SIZEOF_WCHAR_T == (PLATFORM_TCHAR_IS_4_BYTES ? 4 : 2) #define TCHAR_TO_WCHAR(str) str #else #define TCHAR_TO_WCHAR(str) (wchar_t*)StringCast<wchar_t>(static_cast<const TCHAR*>(str)).Get() #endif #endif UWorld *ue_get_uworld(ue_PyUObject *); AActor *ue_get_actor(ue_PyUObject *); PyObject *ue_py_convert_property(UProperty *, uint8 *, int32); bool ue_py_convert_pyobject(PyObject *, UProperty *, uint8 *, int32); ue_PyUObject *ue_is_pyuobject(PyObject *); void ue_bind_events_for_py_class_by_attribute(UObject *, PyObject *); void ue_autobind_events_for_pyclass(ue_PyUObject *, PyObject *); PyObject *ue_bind_pyevent(ue_PyUObject *, FString, PyObject *, bool); PyObject *ue_unbind_pyevent(ue_PyUObject *, FString, PyObject *, bool); PyObject *py_ue_ufunction_call(UFunction *, UObject *, PyObject *, int, PyObject *); UClass *unreal_engine_new_uclass(char *, UClass *); UFunction *unreal_engine_add_function(UClass *, char *, PyObject *, uint32); template <typename T> T *ue_py_check_type(PyObject *py_obj) { ue_PyUObject *ue_py_obj = ue_is_pyuobject(py_obj); if (!ue_py_obj) { return nullptr; } if (!ue_py_obj->ue_object || !ue_py_obj->ue_object->IsValidLowLevel() || ue_py_obj->ue_object->IsPendingKillOrUnreachable()) { UE_LOG(LogPython, Error, TEXT("invalid UObject in ue_PyUObject %p"), ue_py_obj); return nullptr; } return Cast<T>(ue_py_obj->ue_object); } template <typename T> T *ue_py_check_type(ue_PyUObject *py_obj) { if (!py_obj->ue_object || !py_obj->ue_object->IsValidLowLevel() || py_obj->ue_object->IsPendingKillOrUnreachable()) { UE_LOG(LogPython, Error, TEXT("invalid UObject in ue_PyUObject %p"), py_obj); return nullptr; } return Cast<T>(py_obj->ue_object); } uint8 *do_ue_py_check_struct(PyObject *py_obj, UScriptStruct* chk_u_struct); template <typename T> T *ue_py_check_struct(PyObject *py_obj) { return (T*)do_ue_py_check_struct(py_obj, T::StaticStruct()); } bool do_ue_py_check_childstruct(PyObject *py_obj, UScriptStruct* parent_u_struct); template <typename T> bool ue_py_check_childstruct(PyObject *py_obj) { return do_ue_py_check_childstruct(py_obj, T::StaticStruct()); } FGuid *ue_py_check_fguid(PyObject *); ```
/content/code_sandbox/Source/UnrealEnginePython/Private/UEPyModule.h
objective-c
2016-08-07T05:00:51
2024-08-14T06:32:20
UnrealEnginePython
20tab/UnrealEnginePython
2,715
760
```c++ #include "PyCommandlet.h" #include "UEPyModule.h" #if WITH_EDITOR #include "Editor.h" #endif #include "Runtime/Core/Public/Internationalization/Regex.h" UPyCommandlet::UPyCommandlet(const FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer) { LogToConsole = 1; } int32 UPyCommandlet::Main(const FString& CommandLine) { FScopePythonGIL gil; #if WITH_EDITOR // this allows commandlet's to use factories GEditor->Trans = GEditor->CreateTrans(); #endif TArray<FString> Tokens, Switches; TMap<FString, FString> Params; ParseCommandLine(*CommandLine, Tokens, Switches, Params); FString Filepath = Tokens[0]; if (!FPaths::FileExists(*Filepath)) { UE_LOG(LogPython, Error, TEXT("Python file could not be found: %s"), *Filepath); return -1; } FString RegexString = FString::Printf(TEXT("(?<=%s).*"), *(Filepath.Replace(TEXT("\\"), TEXT("\\\\")))); const FRegexPattern myPattern(RegexString); FRegexMatcher myMatcher(myPattern, *CommandLine); myMatcher.FindNext(); #if ENGINE_MINOR_VERSION >= 18 FString PyCommandLine = myMatcher.GetCaptureGroup(0).TrimStart().TrimEnd(); #else FString PyCommandLine = myMatcher.GetCaptureGroup(0).Trim().TrimTrailing(); #endif TArray<FString> PyArgv; PyArgv.Add(FString()); bool escaped = false; for (int i = 0; i < PyCommandLine.Len(); i++) { if (PyCommandLine[i] == ' ') { PyArgv.Add(FString()); continue; } else if (PyCommandLine[i] == '\"' && !escaped) { i++; while (i < PyCommandLine.Len() && !(PyCommandLine[i] == '"')) { PyArgv[PyArgv.Num() - 1].AppendChar(PyCommandLine[i]); i++; if (i == PyCommandLine.Len()) { PyArgv[PyArgv.Num() - 1].InsertAt(0, "\""); } } } else { if (PyCommandLine[i] == '\\') escaped = true; else escaped = false; PyArgv[PyArgv.Num() - 1].AppendChar(PyCommandLine[i]); } } PyArgv.Insert(Filepath, 0); #if PY_MAJOR_VERSION >= 3 wchar_t **argv = (wchar_t **)malloc(PyArgv.Num() * sizeof(void*)); #else char **argv = (char **)malloc(PyArgv.Num() * sizeof(void*)); #endif for (int i = 0; i < PyArgv.Num(); i++) { #if PY_MAJOR_VERSION >= 3 argv[i] = (wchar_t*)malloc(PyArgv[i].Len() + 1); #if PLATFORM_MAC || PLATFORM_LINUX #if ENGINE_MINOR_VERSION >= 20 wcsncpy(argv[i], (const wchar_t *) TCHAR_TO_WCHAR(*PyArgv[i].ReplaceEscapedCharWithChar()), PyArgv[i].Len() + 1); #else wcsncpy(argv[i], *PyArgv[i].ReplaceEscapedCharWithChar(), PyArgv[i].Len() + 1); #endif #elif PLATFORM_ANDROID wcsncpy(argv[i], (const wchar_t *)*PyArgv[i].ReplaceEscapedCharWithChar(), PyArgv[i].Len() + 1); #else wcscpy_s(argv[i], PyArgv[i].Len() + 1, *PyArgv[i].ReplaceEscapedCharWithChar()); #endif #else argv[i] = (char*)malloc(PyArgv[i].Len() + 1); #if PLATFORM_MAC || PLATFORM_LINUX || PLATFORM_ANDROID strncpy(argv[i], TCHAR_TO_UTF8(*PyArgv[i].ReplaceEscapedCharWithChar()), PyArgv[i].Len() + 1); #else strcpy_s(argv[i], PyArgv[i].Len() + 1, TCHAR_TO_UTF8(*PyArgv[i].ReplaceEscapedCharWithChar())); #endif #endif } PySys_SetArgv(PyArgv.Num(), argv); Py_BEGIN_ALLOW_THREADS; FUnrealEnginePythonModule &PythonModule = FModuleManager::GetModuleChecked<FUnrealEnginePythonModule>("UnrealEnginePython"); PythonModule.BrutalFinalize = true; PythonModule.RunFile(TCHAR_TO_UTF8(*Filepath)); Py_END_ALLOW_THREADS; return 0; } ```
/content/code_sandbox/Source/UnrealEnginePython/Private/PyCommandlet.cpp
c++
2016-08-07T05:00:51
2024-08-14T06:32:20
UnrealEnginePython
20tab/UnrealEnginePython
2,715
1,006
```c++ #include "UEPyTimer.h" #include "Engine/World.h" #include "Runtime/Engine/Public/TimerManager.h" static PyObject *py_ue_ftimerhandle_clear(ue_PyFTimerHandle *self, PyObject * args) { if (!self->world.IsValid()) return PyErr_Format(PyExc_Exception, "World's timer is invalid"); self->world.Get()->GetTimerManager().ClearTimer(self->thandle); Py_RETURN_NONE; } static PyObject *py_ue_ftimerhandle_pause(ue_PyFTimerHandle *self, PyObject * args) { if (!self->world.IsValid()) return PyErr_Format(PyExc_Exception, "World's timer is invalid"); self->world.Get()->GetTimerManager().PauseTimer(self->thandle); Py_RETURN_NONE; } static PyObject *py_ue_ftimerhandle_unpause(ue_PyFTimerHandle *self, PyObject * args) { if (!self->world.IsValid()) return PyErr_Format(PyExc_Exception, "World's timer is invalid"); self->world.Get()->GetTimerManager().UnPauseTimer(self->thandle); Py_RETURN_NONE; } static PyMethodDef ue_PyFTimerHandle_methods[] = { // Transform { "clear", (PyCFunction)py_ue_ftimerhandle_clear, METH_VARARGS, "" }, { "pause", (PyCFunction)py_ue_ftimerhandle_pause, METH_VARARGS, "" }, { "unpause", (PyCFunction)py_ue_ftimerhandle_unpause, METH_VARARGS, "" }, { NULL } /* Sentinel */ }; // destructor static void ue_pyftimerhandle_dealloc(ue_PyFTimerHandle *self) { if (self->world.IsValid()) { self->world.Get()->GetTimerManager().ClearTimer(self->thandle); } if (self->delegate_ptr.IsValid()) { self->delegate_ptr.Reset(); } Py_TYPE(self)->tp_free((PyObject *)self); } static PyTypeObject ue_PyFTimerHandleType = { PyVarObject_HEAD_INIT(NULL, 0) "unreal_engine.FTimerHandle", /* tp_name */ sizeof(ue_PyFTimerHandle), /* tp_basicsize */ 0, /* tp_itemsize */ (destructor)ue_pyftimerhandle_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_reserved */ 0, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ 0, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT, /* tp_flags */ "Unreal Engine FTimerHandle", /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ ue_PyFTimerHandle_methods, /* tp_methods */ }; void ue_python_init_ftimerhandle(PyObject *ue_module) { ue_PyFTimerHandleType.tp_new = PyType_GenericNew; if (PyType_Ready(&ue_PyFTimerHandleType) < 0) return; Py_INCREF(&ue_PyFTimerHandleType); PyModule_AddObject(ue_module, "FTimerHandle", (PyObject *)&ue_PyFTimerHandleType); } PyObject *py_ue_set_timer(ue_PyUObject *self, PyObject * args) { ue_py_check(self); float rate; PyObject *py_callable; PyObject *py_loop = nullptr; float first_delay = -1; if (!PyArg_ParseTuple(args, "fO|Of:set_timer", &rate, &py_callable, &py_loop, &first_delay)) { return NULL; } if (!PyCallable_Check(py_callable)) return PyErr_Format(PyExc_Exception, "object is not a callable"); bool loop = false; if (py_loop && PyObject_IsTrue(py_loop)) loop = true; UWorld *world = ue_get_uworld(self); if (!world) return PyErr_Format(PyExc_Exception, "unable to retrieve UWorld from uobject"); ue_PyFTimerHandle *ret = (ue_PyFTimerHandle *)PyObject_New(ue_PyFTimerHandle, &ue_PyFTimerHandleType); if (!ret) { return PyErr_Format(PyExc_Exception, "unable to allocate FTimerHandle python object"); } new(&ret->thandle) FTimerHandle; FTimerDelegate timer_delegate; TSharedRef<FPythonSmartDelegate> py_delegate = MakeShareable(new FPythonSmartDelegate); py_delegate->SetPyCallable(py_callable); timer_delegate.BindSP(py_delegate, &FPythonSmartDelegate::Void); world->GetTimerManager().SetTimer(ret->thandle, timer_delegate, rate, loop, first_delay); new(&ret->delegate_ptr) TSharedPtr<FPythonSmartDelegate>(py_delegate); ret->world = TWeakObjectPtr<UWorld>(world); return (PyObject *)ret; } ```
/content/code_sandbox/Source/UnrealEnginePython/Private/UEPyTimer.cpp
c++
2016-08-07T05:00:51
2024-08-14T06:32:20
UnrealEnginePython
20tab/UnrealEnginePython
2,715
1,145
```c++ #include "UEPyUClassesImporter.h" static PyObject *ue_PyUClassesImporter_getattro(ue_PyUClassesImporter *self, PyObject *attr_name) { PyObject *py_attr = PyObject_GenericGetAttr((PyObject *)self, attr_name); if (!py_attr) { if (PyUnicodeOrString_Check(attr_name)) { const char *attr = UEPyUnicode_AsUTF8(attr_name); if (attr[0] != '_') { UClass *u_class = FindObject<UClass>(ANY_PACKAGE, UTF8_TO_TCHAR(attr)); if (u_class) { // swallow old exception PyErr_Clear(); Py_RETURN_UOBJECT(u_class); } } } } return py_attr; } static PyTypeObject ue_PyUClassesImporterType = { PyVarObject_HEAD_INIT(NULL, 0) "unreal_engine.UClassesImporter", /* tp_name */ sizeof(ue_PyUClassesImporter), /* tp_basicsize */ 0, /* tp_itemsize */ 0, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_reserved */ 0, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ (getattrofunc)ue_PyUClassesImporter_getattro, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT, /* tp_flags */ "Unreal Engine UClasses Importer", /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ 0, /* tp_methods */ 0, 0, }; void ue_python_init_uclassesimporter(PyObject *ue_module) { ue_PyUClassesImporterType.tp_new = PyType_GenericNew; if (PyType_Ready(&ue_PyUClassesImporterType) < 0) return; Py_INCREF(&ue_PyUClassesImporterType); PyModule_AddObject(ue_module, "UClassesImporter", (PyObject *)&ue_PyUClassesImporterType); } PyObject *py_ue_new_uclassesimporter() { ue_PyUClassesImporter *ret = (ue_PyUClassesImporter *)PyObject_New(ue_PyUClassesImporter, &ue_PyUClassesImporterType); return (PyObject *)ret; } ```
/content/code_sandbox/Source/UnrealEnginePython/Private/UEPyUClassesImporter.cpp
c++
2016-08-07T05:00:51
2024-08-14T06:32:20
UnrealEnginePython
20tab/UnrealEnginePython
2,715
611
```objective-c #pragma once #include "UEPyModule.h" typedef struct { PyObject_HEAD /* Type-specific fields go here. */ } ue_PyUStructsImporter; PyObject *py_ue_new_ustructsimporter(); void ue_python_init_ustructsimporter(PyObject *); ```
/content/code_sandbox/Source/UnrealEnginePython/Private/UEPyUStructsImporter.h
objective-c
2016-08-07T05:00:51
2024-08-14T06:32:20
UnrealEnginePython
20tab/UnrealEnginePython
2,715
62
```c++ #include "UnrealEnginePython.h" #include "UEPyModule.h" #include "PythonBlueprintFunctionLibrary.h" #include "HAL/IConsoleManager.h" #include "HAL/PlatformFilemanager.h" #if ENGINE_MINOR_VERSION < 13 #include "ClassIconFinder.h" #endif #include "Styling/SlateStyleRegistry.h" #if WITH_EDITOR #include "Interfaces/IPluginManager.h" #endif #if ENGINE_MINOR_VERSION >= 18 #define PROJECT_CONTENT_DIR FPaths::ProjectContentDir() #else #define PROJECT_CONTENT_DIR FPaths::GameContentDir() #endif #if PLATFORM_MAC #include "Runtime/Core/Public/Mac/CocoaThread.h" #endif void unreal_engine_init_py_module(); void init_unreal_engine_builtin(); #if PLATFORM_LINUX const char *ue4_module_options = "linux_global_symbols"; #endif #include "Runtime/Core/Public/Misc/CommandLine.h" #include "Runtime/Core/Public/Misc/ConfigCacheIni.h" #include "Runtime/Core/Public/GenericPlatform/GenericPlatformFile.h" #include "Runtime/Core/Public/GenericPlatform/GenericPlatformMisc.h" #include "Runtime/Core/Public/HAL/FileManagerGeneric.h" #if PLATFORM_WINDOWS #include <fcntl.h> #endif #if PLATFORM_ANDROID #include "Android/AndroidJNI.h" #include "Android/AndroidApplication.h" #endif const char *UEPyUnicode_AsUTF8(PyObject *py_str) { #if PY_MAJOR_VERSION < 3 if (PyUnicode_Check(py_str)) { PyObject *unicode = PyUnicode_AsUTF8String(py_str); if (unicode) { return PyString_AsString(unicode); } // just a hack to avoid crashes return (char *)"<invalid_string>"; } return (const char *)PyString_AsString(py_str); #elif PY_MINOR_VERSION < 7 return (const char *)PyUnicode_AsUTF8(py_str); #else return PyUnicode_AsUTF8(py_str); #endif } #if PY_MAJOR_VERSION < 3 int PyGILState_Check() { PyThreadState * tstate = _PyThreadState_Current; return tstate && (tstate == PyGILState_GetThisThreadState()); } #endif bool PyUnicodeOrString_Check(PyObject *py_obj) { if (PyUnicode_Check(py_obj)) { return true; } #if PY_MAJOR_VERSION < 3 else if (PyString_Check(py_obj)) { return true; } #endif return false; } #define LOCTEXT_NAMESPACE "FUnrealEnginePythonModule" void FUnrealEnginePythonModule::UESetupPythonInterpreter(bool verbose) { const TCHAR* CommandLine = FCommandLine::GetOriginal(); const SIZE_T CommandLineSize = FCString::Strlen(CommandLine) + 1; TCHAR* CommandLineCopy = new TCHAR[CommandLineSize]; FCString::Strcpy(CommandLineCopy, CommandLineSize, CommandLine); const TCHAR* ParsedCmdLine = CommandLineCopy; TArray<FString> Args; for (;;) { FString Arg = FParse::Token(ParsedCmdLine, 0); if (Arg.Len() <= 0) break; Args.Add(Arg); } #if PY_MAJOR_VERSION >= 3 wchar_t **argv = (wchar_t **)FMemory::Malloc(sizeof(wchar_t *) * (Args.Num() + 1)); #else char **argv = (char **)FMemory::Malloc(sizeof(char *) * (Args.Num() + 1)); #endif argv[Args.Num()] = nullptr; for (int32 i = 0; i < Args.Num(); i++) { #if PY_MAJOR_VERSION >= 3 #if ENGINE_MINOR_VERSION >= 20 argv[i] = (wchar_t *)(TCHAR_TO_WCHAR(*Args[i])); #else argv[i] = (wchar_t *)(*Args[i]); #endif #else argv[i] = TCHAR_TO_UTF8(*Args[i]); #endif } PySys_SetArgv(Args.Num(), argv); unreal_engine_init_py_module(); PyObject *py_sys = PyImport_ImportModule("sys"); PyObject *py_sys_dict = PyModule_GetDict(py_sys); PyObject *py_path = PyDict_GetItemString(py_sys_dict, "path"); char *zip_path = TCHAR_TO_UTF8(*ZipPath); PyObject *py_zip_path = PyUnicode_FromString(zip_path); PyList_Insert(py_path, 0, py_zip_path); int i = 0; for (FString ScriptsPath : ScriptsPaths) { char *scripts_path = TCHAR_TO_UTF8(*ScriptsPath); PyObject *py_scripts_path = PyUnicode_FromString(scripts_path); PyList_Insert(py_path, i++, py_scripts_path); if (verbose) { UE_LOG(LogPython, Log, TEXT("Python Scripts search path: %s"), UTF8_TO_TCHAR(scripts_path)); } } char *additional_modules_path = TCHAR_TO_UTF8(*AdditionalModulesPath); PyObject *py_additional_modules_path = PyUnicode_FromString(additional_modules_path); PyList_Insert(py_path, 0, py_additional_modules_path); if (verbose) { UE_LOG(LogPython, Log, TEXT("Python VM initialized: %s"), UTF8_TO_TCHAR(Py_GetVersion())); } } static void setup_stdout_stderr() { // Redirecting stdout char const* code = "import sys\n" "import unreal_engine\n" "class UnrealEngineOutput:\n" " def __init__(self, logger):\n" " self.logger = logger\n" " def write(self, buf):\n" " self.logger(buf)\n" " def flush(self):\n" " return\n" " def isatty(self):\n" " return False\n" "sys.stdout = UnrealEngineOutput(unreal_engine.log)\n" "sys.stderr = UnrealEngineOutput(unreal_engine.log_error)\n" "\n" "class event:\n" " def __init__(self, event_signature):\n" " self.event_signature = event_signature\n" " def __call__(self, f):\n" " f.ue_event = self.event_signature\n" " return f\n" "\n" "unreal_engine.event = event"; PyRun_SimpleString(code); } namespace { static void consoleExecScript(const TArray<FString>& Args) { if (Args.Num() != 1) { UE_LOG(LogPython, Warning, TEXT("Usage: 'py.exec <scriptname>'.")); UE_LOG(LogPython, Warning, TEXT(" scriptname: Name of script, must reside in Scripts folder. Ex: myscript.py")); } else { UPythonBlueprintFunctionLibrary::ExecutePythonScript(Args[0]); } } static void consoleExecString(const TArray<FString>& Args) { if (Args.Num() == 0) { UE_LOG(LogPython, Warning, TEXT("Usage: 'py.cmd <command string>'.")); UE_LOG(LogPython, Warning, TEXT(" scriptname: Name of script, must reside in Scripts folder. Ex: myscript.py")); } else { FString cmdString; for (const FString& argStr : Args) { cmdString += argStr.TrimQuotes() + '\n'; } UPythonBlueprintFunctionLibrary::ExecutePythonString(cmdString); } } } FAutoConsoleCommand ExecPythonScriptCommand( TEXT("py.exec"), *NSLOCTEXT("UnrealEnginePython", "CommandText_Exec", "Execute python script").ToString(), FConsoleCommandWithArgsDelegate::CreateStatic(consoleExecScript)); FAutoConsoleCommand ExecPythonStringCommand( TEXT("py.cmd"), *NSLOCTEXT("UnrealEnginePython", "CommandText_Cmd", "Execute python string").ToString(), FConsoleCommandWithArgsDelegate::CreateStatic(consoleExecString)); void FUnrealEnginePythonModule::StartupModule() { BrutalFinalize = false; // This code will execute after your module is loaded into memory; the exact timing is specified in the .uplugin file per-module FString PythonHome; if (GConfig->GetString(UTF8_TO_TCHAR("Python"), UTF8_TO_TCHAR("Home"), PythonHome, GEngineIni)) { #if PY_MAJOR_VERSION >= 3 wchar_t *home = (wchar_t *)*PythonHome; #else char *home = TCHAR_TO_UTF8(*PythonHome); #endif FPlatformMisc::SetEnvironmentVar(TEXT("PYTHONHOME"), *PythonHome); Py_SetPythonHome(home); } if (GConfig->GetString(UTF8_TO_TCHAR("Python"), UTF8_TO_TCHAR("RelativeHome"), PythonHome, GEngineIni)) { PythonHome = FPaths::Combine(*PROJECT_CONTENT_DIR, *PythonHome); FPaths::NormalizeFilename(PythonHome); PythonHome = FPaths::ConvertRelativePathToFull(PythonHome); #if PY_MAJOR_VERSION >= 3 wchar_t *home = (wchar_t *)*PythonHome; #else char *home = TCHAR_TO_UTF8(*PythonHome); #endif Py_SetPythonHome(home); } TArray<FString> ImportModules; FString IniValue; if (GConfig->GetString(UTF8_TO_TCHAR("Python"), UTF8_TO_TCHAR("ProgramName"), IniValue, GEngineIni)) { #if PY_MAJOR_VERSION >= 3 wchar_t *program_name = (wchar_t *)*IniValue; #else char *program_name = TCHAR_TO_UTF8(*IniValue); #endif Py_SetProgramName(program_name); } if (GConfig->GetString(UTF8_TO_TCHAR("Python"), UTF8_TO_TCHAR("RelativeProgramName"), IniValue, GEngineIni)) { IniValue = FPaths::Combine(*PROJECT_CONTENT_DIR, *IniValue); FPaths::NormalizeFilename(IniValue); IniValue = FPaths::ConvertRelativePathToFull(IniValue); #if PY_MAJOR_VERSION >= 3 wchar_t *program_name = (wchar_t *)*IniValue; #else char *program_name = TCHAR_TO_UTF8(*IniValue); #endif Py_SetProgramName(program_name); } if (GConfig->GetString(UTF8_TO_TCHAR("Python"), UTF8_TO_TCHAR("ScriptsPath"), IniValue, GEngineIni)) { ScriptsPaths.Add(IniValue); } if (GConfig->GetString(UTF8_TO_TCHAR("Python"), UTF8_TO_TCHAR("RelativeScriptsPath"), IniValue, GEngineIni)) { ScriptsPaths.Add(FPaths::Combine(*PROJECT_CONTENT_DIR, *IniValue)); } if (GConfig->GetString(UTF8_TO_TCHAR("Python"), UTF8_TO_TCHAR("AdditionalModulesPath"), IniValue, GEngineIni)) { AdditionalModulesPath = IniValue; } if (GConfig->GetString(UTF8_TO_TCHAR("Python"), UTF8_TO_TCHAR("RelativeAdditionalModulesPath"), IniValue, GEngineIni)) { AdditionalModulesPath = FPaths::Combine(*PROJECT_CONTENT_DIR, *IniValue); } if (GConfig->GetString(UTF8_TO_TCHAR("Python"), UTF8_TO_TCHAR("ZipPath"), IniValue, GEngineIni)) { ZipPath = IniValue; } if (GConfig->GetString(UTF8_TO_TCHAR("Python"), UTF8_TO_TCHAR("RelativeZipPath"), IniValue, GEngineIni)) { ZipPath = FPaths::Combine(*PROJECT_CONTENT_DIR, *IniValue); } if (GConfig->GetString(UTF8_TO_TCHAR("Python"), UTF8_TO_TCHAR("ImportModules"), IniValue, GEngineIni)) { const TCHAR* separators[] = { TEXT(" "), TEXT(";"), TEXT(",") }; IniValue.ParseIntoArray(ImportModules, separators, 3); } FString ProjectScriptsPath = FPaths::Combine(*PROJECT_CONTENT_DIR, UTF8_TO_TCHAR("Scripts")); if (!FPaths::DirectoryExists(ProjectScriptsPath)) { FPlatformFileManager::Get().GetPlatformFile().CreateDirectory(*ProjectScriptsPath); } ScriptsPaths.Add(ProjectScriptsPath); #if WITH_EDITOR for (TSharedRef<IPlugin>plugin : IPluginManager::Get().GetEnabledPlugins()) { FString PluginScriptsPath = FPaths::Combine(plugin->GetContentDir(), UTF8_TO_TCHAR("Scripts")); if (FPaths::DirectoryExists(PluginScriptsPath)) { ScriptsPaths.Add(PluginScriptsPath); } // allows third parties to include their code in the main plugin directory if (plugin->GetName() == "UnrealEnginePython") { ScriptsPaths.Add(plugin->GetBaseDir()); } } #endif if (ZipPath.IsEmpty()) { ZipPath = FPaths::Combine(*PROJECT_CONTENT_DIR, UTF8_TO_TCHAR("ue_python.zip")); } // To ensure there are no path conflicts, if we have a valid python home at this point, // we override the current environment entirely with the environment we want to use, // removing any paths to other python environments we aren't using. if (PythonHome.Len() > 0) { FPlatformMisc::SetEnvironmentVar(TEXT("PYTHONHOME"), *PythonHome); const int32 MaxPathVarLen = 32768; FString OrigPathVar = FString::ChrN(MaxPathVarLen, TEXT('\0')); #if ENGINE_MINOR_VERSION >= 21 OrigPathVar = FPlatformMisc::GetEnvironmentVariable(TEXT("PATH")); #else FPlatformMisc::GetEnvironmentVariable(TEXT("PATH"), OrigPathVar.GetCharArray().GetData(), MaxPathVarLen); #endif // Get the current path and remove elements with python in them, we don't want any conflicts const TCHAR* PathDelimiter = FPlatformMisc::GetPathVarDelimiter(); TArray<FString> PathVars; OrigPathVar.ParseIntoArray(PathVars, PathDelimiter, true); for (int32 PathRemoveIndex = PathVars.Num() - 1; PathRemoveIndex >= 0; --PathRemoveIndex) { if (PathVars[PathRemoveIndex].Contains(TEXT("python"), ESearchCase::IgnoreCase)) { UE_LOG(LogPython, Verbose, TEXT("Removing other python Path: '%s'"), *PathVars[PathRemoveIndex]); PathVars.RemoveAt(PathRemoveIndex); } } // Setup our own paths for PYTHONPATH TArray<FString> OurPythonPaths = { PythonHome, FPaths::Combine(PythonHome, TEXT("Lib")), FPaths::Combine(PythonHome, TEXT("Lib/site-packages")), }; FString PythonPathVars = FString::Join(OurPythonPaths, PathDelimiter); FPlatformMisc::SetEnvironmentVar(TEXT("PYTHONPATH"), *PythonPathVars); // Also add our paths to PATH, just so any searching will find our local python PathVars.Append(OurPythonPaths); FString ModifiedPath = FString::Join(PathVars, PathDelimiter); FPlatformMisc::SetEnvironmentVar(TEXT("PATH"), *ModifiedPath); } #if PY_MAJOR_VERSION >= 3 init_unreal_engine_builtin(); #if PLATFORM_ANDROID extern FString GOBBFilePathBase; extern FString GFilePathBase; extern FString GExternalFilePath; extern FString GPackageName; extern int32 GAndroidPackageVersion; FString OBBDir1 = GOBBFilePathBase + FString(TEXT("/Android/obb/") + GPackageName); FString OBBDir2 = GOBBFilePathBase + FString(TEXT("/obb/") + GPackageName); FString MainOBBName = FString::Printf(TEXT("main.%d.%s.obb"), GAndroidPackageVersion, *GPackageName); FString PatchOBBName = FString::Printf(TEXT("patch.%d.%s.obb"), GAndroidPackageVersion, *GPackageName); FString UnrealEnginePython_OBBPath; if (FPaths::FileExists(*(OBBDir1 / MainOBBName))) { UnrealEnginePython_OBBPath = OBBDir1 / MainOBBName / FApp::GetProjectName() / FString(TEXT("Content/Scripts")); } else if (FPaths::FileExists(*(OBBDir2 / MainOBBName))) { UnrealEnginePython_OBBPath = OBBDir2 / MainOBBName / FApp::GetProjectName() / FString(TEXT("Content/Scripts")); } if (FPaths::FileExists(*(OBBDir1 / PatchOBBName))) { UnrealEnginePython_OBBPath = OBBDir1 / PatchOBBName / FApp::GetProjectName() / FString(TEXT("Content/Scripts")); } else if (FPaths::FileExists(*(OBBDir2 / PatchOBBName))) { UnrealEnginePython_OBBPath = OBBDir1 / PatchOBBName / FApp::GetProjectName() / FString(TEXT("Content/Scripts")); } if (!UnrealEnginePython_OBBPath.IsEmpty()) { ScriptsPaths.Add(UnrealEnginePython_OBBPath); } FString FinalPath = GFilePathBase / FString("UE4Game") / FApp::GetProjectName() / FApp::GetProjectName() / FString(TEXT("Content/Scripts")); ScriptsPaths.Add(FinalPath); FString BasePythonPath = FinalPath / FString(TEXT("stdlib.zip")) + FString(":") + FinalPath; if (!UnrealEnginePython_OBBPath.IsEmpty()) { BasePythonPath += FString(":") + UnrealEnginePython_OBBPath; } UE_LOG(LogPython, Warning, TEXT("Setting Base Path to %s"), *BasePythonPath); Py_SetPath(Py_DecodeLocale(TCHAR_TO_UTF8(*BasePythonPath), NULL)); #endif #endif Py_Initialize(); #if PLATFORM_WINDOWS // Restore stdio state after Py_Initialize set it to O_BINARY, otherwise // everything that the engine will output is going to be encoded in UTF-16. // The behaviour is described here: path_to_url _setmode(_fileno(stdin), O_TEXT); _setmode(_fileno(stdout), O_TEXT); _setmode(_fileno(stderr), O_TEXT); // Also restore the user-requested UTF-8 flag if relevant (behaviour copied // from LaunchEngineLoop.cpp). if (FParse::Param(FCommandLine::Get(), TEXT("UTF8Output"))) { FPlatformMisc::SetUTF8Output(); } #endif PyEval_InitThreads(); #if WITH_EDITOR StyleSet = MakeShareable(new FSlateStyleSet("UnrealEnginePython")); StyleSet->SetContentRoot(IPluginManager::Get().FindPlugin("UnrealEnginePython")->GetBaseDir() / "Resources"); StyleSet->Set("ClassThumbnail.PythonScript", new FSlateImageBrush(StyleSet->RootToContentDir("Icon128.png"), FVector2D(128.0f, 128.0f))); FSlateStyleRegistry::RegisterSlateStyle(*StyleSet.Get()); #if ENGINE_MINOR_VERSION < 13 FClassIconFinder::RegisterIconSource(StyleSet.Get()); #endif #endif UESetupPythonInterpreter(true); main_module = PyImport_AddModule("__main__"); main_dict = PyModule_GetDict((PyObject*)main_module); local_dict = main_dict;// PyDict_New(); setup_stdout_stderr(); if (PyImport_ImportModule("ue_site")) { UE_LOG(LogPython, Log, TEXT("ue_site Python module successfully imported")); } else { #if PY_MAJOR_VERSION >= 3 && PY_MINOR_VERSION >= 6 if (PyErr_ExceptionMatches(PyExc_ModuleNotFoundError)) { UE_LOG(LogPython, Log, TEXT("ue_site Python module not found")); PyErr_Clear(); } else { unreal_engine_py_log_error(); } #else unreal_engine_py_log_error(); #endif } for (FString ImportModule : ImportModules) { if (PyImport_ImportModule(TCHAR_TO_UTF8(*ImportModule))) { UE_LOG(LogPython, Log, TEXT("%s Python module successfully imported"), *ImportModule); } else { unreal_engine_py_log_error(); } } // release the GIL PyThreadState *UEPyGlobalState = PyEval_SaveThread(); } void FUnrealEnginePythonModule::ShutdownModule() { // This function may be called during shutdown to clean up your module. For modules that support dynamic reloading, // we call this function before unloading the module. UE_LOG(LogPython, Log, TEXT("Goodbye Python")); if (!BrutalFinalize) { PyGILState_Ensure(); Py_Finalize(); } } void FUnrealEnginePythonModule::RunString(char *str) { FScopePythonGIL gil; PyObject *eval_ret = PyRun_String(str, Py_file_input, (PyObject *)main_dict, (PyObject *)local_dict); if (!eval_ret) { if (PyErr_ExceptionMatches(PyExc_SystemExit)) { PyErr_Clear(); return; } unreal_engine_py_log_error(); return; } Py_DECREF(eval_ret); } #if PLATFORM_MAC void FUnrealEnginePythonModule::RunStringInMainThread(char *str) { MainThreadCall(^{ RunString(str); }); } void FUnrealEnginePythonModule::RunFileInMainThread(char *filename) { MainThreadCall(^{ RunFile(filename); }); } #endif FString FUnrealEnginePythonModule::Pep8ize(FString Code) { FScopePythonGIL gil; PyObject *pep8izer_module = PyImport_ImportModule("autopep8"); if (!pep8izer_module) { unreal_engine_py_log_error(); UE_LOG(LogPython, Error, TEXT("unable to load autopep8 module, please install it")); // return the original string to avoid losing data return Code; } PyObject *pep8izer_func = PyObject_GetAttrString(pep8izer_module, (char*)"fix_code"); if (!pep8izer_func) { unreal_engine_py_log_error(); UE_LOG(LogPython, Error, TEXT("unable to get autopep8.fix_code function")); // return the original string to avoid losing data return Code; } PyObject *ret = PyObject_CallFunction(pep8izer_func, (char *)"s", TCHAR_TO_UTF8(*Code)); if (!ret) { unreal_engine_py_log_error(); // return the original string to avoid losing data return Code; } if (!PyUnicodeOrString_Check(ret)) { UE_LOG(LogPython, Error, TEXT("returned value is not a string")); // return the original string to avoid losing data return Code; } const char *pep8ized = UEPyUnicode_AsUTF8(ret); FString NewCode = FString(pep8ized); Py_DECREF(ret); return NewCode; } void FUnrealEnginePythonModule::RunFile(char *filename) { FScopePythonGIL gil; FString full_path = UTF8_TO_TCHAR(filename); FString original_path = full_path; bool foundFile = false; if (!FPaths::FileExists(filename)) { for (FString ScriptsPath : ScriptsPaths) { full_path = FPaths::Combine(*ScriptsPath, original_path); if (FPaths::FileExists(full_path)) { foundFile = true; break; } } } else { foundFile = true; } if (!foundFile) { UE_LOG(LogPython, Error, TEXT("Unable to find file %s"), UTF8_TO_TCHAR(filename)); return; } #if PY_MAJOR_VERSION >= 3 FILE *fd = nullptr; #if PLATFORM_WINDOWS if (fopen_s(&fd, TCHAR_TO_UTF8(*full_path), "r") != 0) { UE_LOG(LogPython, Error, TEXT("Unable to open file %s"), *full_path); return; } #else fd = fopen(TCHAR_TO_UTF8(*full_path), "r"); if (!fd) { UE_LOG(LogPython, Error, TEXT("Unable to open file %s"), *full_path); return; } #endif PyObject *eval_ret = PyRun_File(fd, TCHAR_TO_UTF8(*full_path), Py_file_input, (PyObject *)main_dict, (PyObject *)local_dict); fclose(fd); if (!eval_ret) { if (PyErr_ExceptionMatches(PyExc_SystemExit)) { PyErr_Clear(); return; } unreal_engine_py_log_error(); return; } Py_DECREF(eval_ret); #else // damn, this is horrible, but it is the only way i found to avoid the CRT error :( FString command = FString::Printf(TEXT("execfile(\"%s\")"), *full_path); PyObject *eval_ret = PyRun_String(TCHAR_TO_UTF8(*command), Py_file_input, (PyObject *)main_dict, (PyObject *)local_dict); if (!eval_ret) { if (PyErr_ExceptionMatches(PyExc_SystemExit)) { PyErr_Clear(); return; } unreal_engine_py_log_error(); return; } #endif } void ue_py_register_magic_module(char *name, PyObject *(*func)()) { PyObject *py_sys = PyImport_ImportModule("sys"); PyObject *py_sys_dict = PyModule_GetDict(py_sys); PyObject *py_sys_modules = PyDict_GetItemString(py_sys_dict, "modules"); PyObject *u_module = func(); Py_INCREF(u_module); PyDict_SetItemString(py_sys_modules, name, u_module); } PyObject *ue_py_register_module(const char *name) { return PyImport_AddModule(name); } #undef LOCTEXT_NAMESPACE IMPLEMENT_MODULE(FUnrealEnginePythonModule, UnrealEnginePython) ```
/content/code_sandbox/Source/UnrealEnginePython/Private/UnrealEnginePython.cpp
c++
2016-08-07T05:00:51
2024-08-14T06:32:20
UnrealEnginePython
20tab/UnrealEnginePython
2,715
5,654
```c++ #include "PyCharacter.h" #include "UEPyModule.h" #include "Components/InputComponent.h" APyCharacter::APyCharacter() { PrimaryActorTick.bCanEverTick = true; PythonTickForceDisabled = false; PythonDisableAutoBinding = false; } // Called when the game starts void APyCharacter::PreInitializeComponents() { Super::PreInitializeComponents(); // ... if (PythonModule.IsEmpty()) return; FScopePythonGIL gil; py_uobject = ue_get_python_uobject(this); if (!py_uobject) { unreal_engine_py_log_error(); return; } PyObject *py_character_module = PyImport_ImportModule(TCHAR_TO_UTF8(*PythonModule)); if (!py_character_module) { unreal_engine_py_log_error(); return; } #if WITH_EDITOR // todo implement autoreload with a dictionary of module timestamps py_character_module = PyImport_ReloadModule(py_character_module); if (!py_character_module) { unreal_engine_py_log_error(); return; } #endif if (PythonClass.IsEmpty()) return; PyObject *py_character_module_dict = PyModule_GetDict(py_character_module); PyObject *py_character_class = PyDict_GetItemString(py_character_module_dict, TCHAR_TO_UTF8(*PythonClass)); if (!py_character_class) { UE_LOG(LogPython, Error, TEXT("Unable to find class %s in module %s"), *PythonClass, *PythonModule); return; } py_character_instance = PyObject_CallObject(py_character_class, NULL); if (!py_character_instance) { unreal_engine_py_log_error(); return; } py_uobject->py_proxy = py_character_instance; PyObject_SetAttrString(py_character_instance, (char *)"uobject", (PyObject *)py_uobject); // disable ticking if no tick method is exposed if (!PyObject_HasAttrString(py_character_instance, (char *)"tick") || PythonTickForceDisabled) { SetActorTickEnabled(false); } if (!PythonDisableAutoBinding) ue_autobind_events_for_pyclass(py_uobject, py_character_instance); ue_bind_events_for_py_class_by_attribute(this, py_character_instance); if (!PyObject_HasAttrString(py_character_instance, (char *)"pre_initialize_components")) { return; } PyObject *pic_ret = PyObject_CallMethod(py_character_instance, (char *)"pre_initialize_components", NULL); if (!pic_ret) { unreal_engine_py_log_error(); return; } Py_DECREF(pic_ret); } void APyCharacter::PostInitializeComponents() { Super::PostInitializeComponents(); if (!py_character_instance) return; FScopePythonGIL gil; if (!PyObject_HasAttrString(py_character_instance, (char *)"post_initialize_components")) return; PyObject *pic_ret = PyObject_CallMethod(py_character_instance, (char *)"post_initialize_components", NULL); if (!pic_ret) { unreal_engine_py_log_error(); return; } Py_DECREF(pic_ret); } // Called when the game starts void APyCharacter::BeginPlay() { Super::BeginPlay(); if (!py_character_instance) return; FScopePythonGIL gil; if (!PyObject_HasAttrString(py_character_instance, (char *)"begin_play")) return; PyObject *bp_ret = PyObject_CallMethod(py_character_instance, (char *)"begin_play", NULL); if (!bp_ret) { unreal_engine_py_log_error(); return; } Py_DECREF(bp_ret); } // Called every frame void APyCharacter::Tick(float DeltaTime) { Super::Tick(DeltaTime); if (!py_character_instance) return; FScopePythonGIL gil; // no need to check for method availability, we did it in begin_play PyObject *ret = PyObject_CallMethod(py_character_instance, (char *)"tick", (char *)"f", DeltaTime); if (!ret) { unreal_engine_py_log_error(); return; } Py_DECREF(ret); } void APyCharacter::CallPyCharacterMethod(FString method_name, FString args) { if (!py_character_instance) return; FScopePythonGIL gil; PyObject *ret = nullptr; if (args.IsEmpty()) { ret = PyObject_CallMethod(py_character_instance, TCHAR_TO_UTF8(*method_name), NULL); } else { ret = PyObject_CallMethod(py_character_instance, TCHAR_TO_UTF8(*method_name), (char *)"s", TCHAR_TO_UTF8(*args)); } if (!ret) { unreal_engine_py_log_error(); return; } Py_DECREF(ret); } void APyCharacter::SetPythonAttrObject(FString attr, UObject *object) { if (!py_character_instance) return; FScopePythonGIL gil; ue_PyUObject *py_obj = ue_get_python_uobject(object); if (!py_obj) { PyErr_Format(PyExc_Exception, "PyUObject is in invalid state"); unreal_engine_py_log_error(); return; } if (PyObject_SetAttrString(py_character_instance, TCHAR_TO_UTF8(*attr), (PyObject *)py_obj) < 0) { UE_LOG(LogPython, Error, TEXT("Unable to set attribute %s"), *attr); } } void APyCharacter::SetPythonAttrString(FString attr, FString s) { if (!py_character_instance) return; FScopePythonGIL gil; if (PyObject_SetAttrString(py_character_instance, TCHAR_TO_UTF8(*attr), PyUnicode_FromString(TCHAR_TO_UTF8(*s))) < 0) { UE_LOG(LogPython, Error, TEXT("Unable to set attribute %s"), *attr); } } void APyCharacter::SetPythonAttrFloat(FString attr, float f) { if (!py_character_instance) return; FScopePythonGIL gil; if (PyObject_SetAttrString(py_character_instance, TCHAR_TO_UTF8(*attr), PyFloat_FromDouble(f)) < 0) { UE_LOG(LogPython, Error, TEXT("Unable to set attribute %s"), *attr); } } void APyCharacter::SetPythonAttrInt(FString attr, int n) { if (!py_character_instance) return; FScopePythonGIL gil; if (PyObject_SetAttrString(py_character_instance, TCHAR_TO_UTF8(*attr), PyLong_FromLong(n)) < 0) { UE_LOG(LogPython, Error, TEXT("Unable to set attribute %s"), *attr); } } void APyCharacter::SetPythonAttrVector(FString attr, FVector vec) { if (!py_character_instance) return; FScopePythonGIL gil; if (PyObject_SetAttrString(py_character_instance, TCHAR_TO_UTF8(*attr), py_ue_new_fvector(vec)) < 0) { UE_LOG(LogPython, Error, TEXT("Unable to set attribute %s"), *attr); } } void APyCharacter::SetPythonAttrRotator(FString attr, FRotator rot) { if (!py_character_instance) return; FScopePythonGIL gil; if (PyObject_SetAttrString(py_character_instance, TCHAR_TO_UTF8(*attr), py_ue_new_frotator(rot)) < 0) { UE_LOG(LogPython, Error, TEXT("Unable to set attribute %s"), *attr); } } void APyCharacter::SetPythonAttrBool(FString attr, bool b) { if (!py_character_instance) return; FScopePythonGIL gil; PyObject *py_bool = Py_False; if (b) { py_bool = Py_True; } if (PyObject_SetAttrString(py_character_instance, TCHAR_TO_UTF8(*attr), py_bool) < 0) { UE_LOG(LogPython, Error, TEXT("Unable to set attribute %s"), *attr); } } bool APyCharacter::CallPyCharacterMethodBool(FString method_name, FString args) { if (!py_character_instance) return false; FScopePythonGIL gil; PyObject *ret = nullptr; if (args.IsEmpty()) { ret = PyObject_CallMethod(py_character_instance, TCHAR_TO_UTF8(*method_name), NULL); } else { ret = PyObject_CallMethod(py_character_instance, TCHAR_TO_UTF8(*method_name), (char *)"s", TCHAR_TO_UTF8(*args)); } if (!ret) { unreal_engine_py_log_error(); return false; } if (PyObject_IsTrue(ret)) { Py_DECREF(ret); return true; } Py_DECREF(ret); return false; } float APyCharacter::CallPyCharacterMethodFloat(FString method_name, FString args) { if (!py_character_instance) return false; FScopePythonGIL gil; PyObject *ret = nullptr; if (args.IsEmpty()) { ret = PyObject_CallMethod(py_character_instance, TCHAR_TO_UTF8(*method_name), NULL); } else { ret = PyObject_CallMethod(py_character_instance, TCHAR_TO_UTF8(*method_name), (char *)"s", TCHAR_TO_UTF8(*args)); } if (!ret) { unreal_engine_py_log_error(); return false; } float value = 0; if (PyNumber_Check(ret)) { PyObject *py_value = PyNumber_Float(ret); value = PyFloat_AsDouble(py_value); Py_DECREF(py_value); } Py_DECREF(ret); return value; } FString APyCharacter::CallPyCharacterMethodString(FString method_name, FString args) { if (!py_character_instance) return FString(); FScopePythonGIL gil; PyObject *ret = nullptr; if (args.IsEmpty()) { ret = PyObject_CallMethod(py_character_instance, TCHAR_TO_UTF8(*method_name), NULL); } else { ret = PyObject_CallMethod(py_character_instance, TCHAR_TO_UTF8(*method_name), (char *)"s", TCHAR_TO_UTF8(*args)); } if (!ret) { unreal_engine_py_log_error(); return FString(); } PyObject *py_str = PyObject_Str(ret); if (!py_str) { Py_DECREF(ret); return FString(); } const char *str_ret = UEPyUnicode_AsUTF8(py_str); FString ret_fstring = FString(UTF8_TO_TCHAR(str_ret)); Py_DECREF(py_str); return ret_fstring; } // Called to bind functionality to input void APyCharacter::SetupPlayerInputComponent(class UInputComponent* input) { Super::SetupPlayerInputComponent(input); if (!py_character_instance) return; FScopePythonGIL gil; // no need to check for method availability, we did it in begin_play PyObject *ret = PyObject_CallMethod(py_character_instance, (char *)"setup_player_input_component", (char *)"O", ue_get_python_uobject(input)); if (!ret) { unreal_engine_py_log_error(); return; } Py_DECREF(ret); } void APyCharacter::EndPlay(const EEndPlayReason::Type EndPlayReason) { if (!py_character_instance) return; FScopePythonGIL gil; if (PyObject_HasAttrString(py_character_instance, (char *)"end_play")) { PyObject *ep_ret = PyObject_CallMethod(py_character_instance, (char *)"end_play", (char*)"i", (int)EndPlayReason); if (!ep_ret) { unreal_engine_py_log_error(); } Py_XDECREF(ep_ret); } Super::EndPlay(EndPlayReason); // ... } APyCharacter::~APyCharacter() { FScopePythonGIL gil; Py_XDECREF(py_character_instance); #if defined(UEPY_MEMORY_DEBUG) UE_LOG(LogPython, Warning, TEXT("Python ACharacter (mapped to %p) wrapper XDECREF'ed"), py_uobject ? py_uobject->py_proxy : nullptr); #endif // this could trigger the distruction of the python/uobject mapper Py_XDECREF(py_uobject); FUnrealEnginePythonHouseKeeper::Get()->UnregisterPyUObject(this); } ```
/content/code_sandbox/Source/UnrealEnginePython/Private/PyCharacter.cpp
c++
2016-08-07T05:00:51
2024-08-14T06:32:20
UnrealEnginePython
20tab/UnrealEnginePython
2,715
2,619
```objective-c #pragma once #include "UEPyModule.h" #include "Engine/EngineTypes.h" typedef struct { PyObject_HEAD /* Type-specific fields go here. */ FTimerHandle thandle; TWeakObjectPtr<UWorld> world; TSharedPtr<FPythonSmartDelegate> delegate_ptr; } ue_PyFTimerHandle; PyObject *py_ue_set_timer(ue_PyUObject *, PyObject *); void ue_python_init_ftimerhandle(PyObject *); ```
/content/code_sandbox/Source/UnrealEnginePython/Private/UEPyTimer.h
objective-c
2016-08-07T05:00:51
2024-08-14T06:32:20
UnrealEnginePython
20tab/UnrealEnginePython
2,715
98
```c++ #include "UEPyVisualLogger.h" #include "Runtime/Engine/Public/VisualLogger/VisualLogger.h" PyObject *py_ue_vlog(ue_PyUObject *self, PyObject * args) { ue_py_check(self); char *category; char *text; int verbosity = ELogVerbosity::Log; if (!PyArg_ParseTuple(args, "ss|i:vlog", &category, &text, &verbosity)) return nullptr; #if ENABLE_VISUAL_LOG if (FVisualLogger::IsRecording()) { FVisualLogger::CategorizedLogf(self->ue_object, FLogCategoryBase(UTF8_TO_TCHAR(category), (ELogVerbosity::Type)verbosity, (ELogVerbosity::Type)verbosity), (ELogVerbosity::Type)verbosity, TEXT("%s"), UTF8_TO_TCHAR(text)); } #endif Py_RETURN_NONE; } PyObject *py_ue_vlog_cylinder(ue_PyUObject *self, PyObject * args) { ue_py_check(self); char *category; PyObject *py_start; PyObject *py_end; float radius; PyObject *py_color = nullptr; char *text = (char*)""; int verbosity = ELogVerbosity::Log; if (!PyArg_ParseTuple(args, "sOOf|Osi:vlog_cylinder", &category, &py_start, &py_end, &radius, &py_color, &text, &verbosity)) return nullptr; ue_PyFVector *py_vec_start = py_ue_is_fvector(py_start); if (!py_vec_start) return PyErr_Format(PyExc_Exception, "argument is not a FVector"); ue_PyFVector *py_vec_end = py_ue_is_fvector(py_end); if (!py_vec_end) return PyErr_Format(PyExc_Exception, "argument is not a FVector"); FColor color = FColor::White; if (py_color) { ue_PyFColor *py_fcolor = py_ue_is_fcolor(py_color); if (!py_fcolor) return PyErr_Format(PyExc_Exception, "argument is not a FColor"); color = py_fcolor->color; } #if ENABLE_VISUAL_LOG if (FVisualLogger::IsRecording()) { FVisualLogger::GeometryShapeLogf(self->ue_object, FLogCategoryBase(UTF8_TO_TCHAR(category), (ELogVerbosity::Type)verbosity, (ELogVerbosity::Type)verbosity), (ELogVerbosity::Type)verbosity, py_vec_start->vec, py_vec_end->vec, radius, color, TEXT("%s"), UTF8_TO_TCHAR(text)); } #endif Py_RETURN_NONE; } ```
/content/code_sandbox/Source/UnrealEnginePython/Private/UEPyVisualLogger.cpp
c++
2016-08-07T05:00:51
2024-08-14T06:32:20
UnrealEnginePython
20tab/UnrealEnginePython
2,715
573
```c++ #include "PyHUD.h" #include "UEPyModule.h" #include "PythonDelegate.h" APyHUD::APyHUD() { PrimaryActorTick.bCanEverTick = true; PythonTickForceDisabled = false; PythonDisableAutoBinding = false; } // Called when the game starts void APyHUD::BeginPlay() { Super::BeginPlay(); // ... if (PythonModule.IsEmpty()) return; FScopePythonGIL gil; py_uobject = ue_get_python_uobject(this); if (!py_uobject) { unreal_engine_py_log_error(); return; } PyObject *py_hud_module = PyImport_ImportModule(TCHAR_TO_UTF8(*PythonModule)); if (!py_hud_module) { unreal_engine_py_log_error(); return; } #if WITH_EDITOR // todo implement autoreload with a dictionary of module timestamps py_hud_module = PyImport_ReloadModule(py_hud_module); if (!py_hud_module) { unreal_engine_py_log_error(); return; } #endif if (PythonClass.IsEmpty()) return; PyObject *py_hud_module_dict = PyModule_GetDict(py_hud_module); PyObject *py_hud_class = PyDict_GetItemString(py_hud_module_dict, TCHAR_TO_UTF8(*PythonClass)); if (!py_hud_class) { UE_LOG(LogPython, Error, TEXT("Unable to find class %s in module %s"), *PythonClass, *PythonModule); return; } py_hud_instance = PyObject_CallObject(py_hud_class, NULL); if (!py_hud_instance) { unreal_engine_py_log_error(); return; } py_uobject->py_proxy = py_hud_instance; PyObject_SetAttrString(py_hud_instance, (char*)"uobject", (PyObject *)py_uobject); if (!PyObject_HasAttrString(py_hud_instance, (char *)"tick") || PythonTickForceDisabled) { SetActorTickEnabled(false); } if (!PythonDisableAutoBinding) ue_autobind_events_for_pyclass(py_uobject, py_hud_instance); ue_bind_events_for_py_class_by_attribute(this, py_hud_instance); if (!PyObject_HasAttrString(py_hud_instance, (char *)"begin_play")) return; PyObject *bp_ret = PyObject_CallMethod(py_hud_instance, (char *)"begin_play", nullptr); if (!bp_ret) { unreal_engine_py_log_error(); return; } Py_DECREF(bp_ret); } // Called every frame void APyHUD::Tick(float DeltaTime) { Super::Tick(DeltaTime); if (!py_hud_instance) return; FScopePythonGIL gil; if (!PyObject_HasAttrString(py_hud_instance, (char *)"tick")) return; PyObject *ret = PyObject_CallMethod(py_hud_instance, (char *)"tick", (char *)"f", DeltaTime); if (!ret) { unreal_engine_py_log_error(); return; } Py_DECREF(ret); } void APyHUD::DrawHUD() { Super::DrawHUD(); if (!py_hud_instance) return; FScopePythonGIL gil; if (!PyObject_HasAttrString(py_hud_instance, (char *)"draw_hud")) return; PyObject *ret = PyObject_CallMethod(py_hud_instance, (char *)"draw_hud", nullptr); if (!ret) { unreal_engine_py_log_error(); return; } Py_DECREF(ret); } void APyHUD::CallPythonHUDMethod(FString method_name, FString args) { if (!py_hud_instance) return; FScopePythonGIL gil; PyObject *ret = nullptr; if (args.IsEmpty()) { ret = PyObject_CallMethod(py_hud_instance, TCHAR_TO_UTF8(*method_name), NULL); } else { ret = PyObject_CallMethod(py_hud_instance, TCHAR_TO_UTF8(*method_name), (char *)"s", TCHAR_TO_UTF8(*args)); } if (!ret) { unreal_engine_py_log_error(); return; } Py_DECREF(ret); } bool APyHUD::CallPythonHUDMethodBool(FString method_name, FString args) { if (!py_hud_instance) return false; FScopePythonGIL gil; PyObject *ret = nullptr; if (args.IsEmpty()) { ret = PyObject_CallMethod(py_hud_instance, TCHAR_TO_UTF8(*method_name), NULL); } else { ret = PyObject_CallMethod(py_hud_instance, TCHAR_TO_UTF8(*method_name), (char *)"s", TCHAR_TO_UTF8(*args)); } if (!ret) { unreal_engine_py_log_error(); return false; } if (PyObject_IsTrue(ret)) { Py_DECREF(ret); return true; } Py_DECREF(ret); return false; } FString APyHUD::CallPythonHUDMethodString(FString method_name, FString args) { if (!py_hud_instance) return FString(); FScopePythonGIL gil; PyObject *ret = nullptr; if (args.IsEmpty()) { ret = PyObject_CallMethod(py_hud_instance, TCHAR_TO_UTF8(*method_name), NULL); } else { ret = PyObject_CallMethod(py_hud_instance, TCHAR_TO_UTF8(*method_name), (char *)"s", TCHAR_TO_UTF8(*args)); } if (!ret) { unreal_engine_py_log_error(); return FString(); } PyObject *py_str = PyObject_Str(ret); if (!py_str) { Py_DECREF(ret); return FString(); } const char *str_ret = UEPyUnicode_AsUTF8(py_str); FString ret_fstring = FString(UTF8_TO_TCHAR(str_ret)); Py_DECREF(py_str); return ret_fstring; } APyHUD::~APyHUD() { FScopePythonGIL gil; Py_XDECREF(py_hud_instance); #if defined(UEPY_MEMORY_DEBUG) UE_LOG(LogPython, Warning, TEXT("Python AHUD %p (mapped to %p) wrapper XDECREF'ed"), this, py_uobject ? py_uobject->py_proxy : nullptr); #endif // this could trigger the distruction of the python/uobject mapper Py_XDECREF(py_uobject); FUnrealEnginePythonHouseKeeper::Get()->UnregisterPyUObject(this); } ```
/content/code_sandbox/Source/UnrealEnginePython/Private/PyHUD.cpp
c++
2016-08-07T05:00:51
2024-08-14T06:32:20
UnrealEnginePython
20tab/UnrealEnginePython
2,715
1,385
```objective-c #pragma once #include "UEPyModule.h" #if WITH_EDITOR PyObject *py_unreal_engine_get_editor_world(PyObject *, PyObject * args); PyObject *py_unreal_engine_editor_play_in_viewport(PyObject *, PyObject * args); PyObject *py_unreal_engine_editor_get_selected_actors(PyObject *, PyObject *); PyObject *py_unreal_engine_editor_deselect_actors(PyObject *, PyObject *); PyObject *py_unreal_engine_editor_select_actor(PyObject *, PyObject *); PyObject *py_unreal_engine_import_asset(PyObject *, PyObject *); PyObject *py_unreal_engine_get_asset(PyObject *, PyObject *); PyObject *py_unreal_engine_is_loading_assets(PyObject *, PyObject *); PyObject *py_unreal_engine_wait_for_assets(PyObject *, PyObject *); PyObject *py_unreal_engine_find_asset(PyObject *, PyObject *); PyObject *py_unreal_engine_create_asset(PyObject *, PyObject *); PyObject *py_unreal_engine_delete_object(PyObject *, PyObject *); PyObject *py_unreal_engine_get_assets(PyObject *, PyObject *); PyObject *py_unreal_engine_get_selected_assets(PyObject *, PyObject *); PyObject *py_unreal_engine_get_assets_by_class(PyObject *, PyObject *); PyObject *py_unreal_engine_get_assets_by_filter(PyObject *, PyObject *, PyObject *); PyObject *py_unreal_engine_set_fbx_import_option(PyObject *, PyObject *); PyObject *py_unreal_engine_redraw_all_viewports(PyObject *, PyObject *); PyObject *py_unreal_engine_update_ui(PyObject *, PyObject *); PyObject *py_unreal_engine_create_modal_save_asset_dialog(PyObject *, PyObject *); PyObject *py_unreal_engine_console_exec(PyObject *, PyObject * args); PyObject *py_unreal_engine_editor_tick(PyObject *, PyObject *); PyObject *py_unreal_engine_get_discovered_plugins(PyObject *, PyObject *); PyObject *py_unreal_engine_get_enabled_plugins(PyObject *, PyObject *); PyObject *py_unreal_engine_find_plugin(PyObject *, PyObject *); PyObject *py_unreal_engine_rename_asset(PyObject *, PyObject *); PyObject *py_unreal_engine_duplicate_asset(PyObject *, PyObject *); PyObject *py_unreal_engine_delete_asset(PyObject *, PyObject *); PyObject *py_unreal_engine_get_long_package_path(PyObject *, PyObject *); PyObject *py_unreal_engine_get_long_package_asset_name(PyObject *, PyObject *); PyObject *py_unreal_engine_create_blueprint(PyObject *, PyObject *); PyObject *py_unreal_engine_compile_blueprint(PyObject *, PyObject *); PyObject *py_unreal_engine_message_dialog_open(PyObject *, PyObject *); PyObject *py_unreal_engine_get_blueprint_hierarchy_from_class(PyObject *, PyObject *); PyObject *py_unreal_engine_reload_blueprint(PyObject *, PyObject *); PyObject *py_unreal_engine_replace_blueprint(PyObject *, PyObject *); PyObject *py_unreal_engine_create_blueprint_from_actor(PyObject *, PyObject *); PyObject *py_unreal_engine_add_component_to_blueprint(PyObject *, PyObject *); PyObject *py_unreal_engine_remove_component_from_blueprint(PyObject *, PyObject *); PyObject *py_unreal_engine_blueprint_add_member_variable(PyObject *, PyObject *); PyObject *py_unreal_engine_blueprint_add_new_timeline(PyObject *, PyObject *); PyObject *py_unreal_engine_blueprint_set_variable_visibility(PyObject *, PyObject *); PyObject *py_unreal_engine_get_blueprint_components(PyObject *, PyObject *); PyObject *py_unreal_engine_editor_play(PyObject *, PyObject *); PyObject *py_unreal_engine_editor_on_asset_post_import(PyObject *, PyObject *); PyObject *py_unreal_engine_on_main_frame_creation_finished(PyObject *, PyObject *); PyObject *py_unreal_engine_editor_command_build(PyObject *, PyObject *); PyObject *py_unreal_engine_editor_command_build_lighting(PyObject *, PyObject *); PyObject *py_unreal_engine_editor_command_save_current_level(PyObject *, PyObject *); PyObject *py_unreal_engine_editor_command_save_all_levels(PyObject *, PyObject *); PyObject *py_unreal_engine_editor_save_all(PyObject *, PyObject *); PyObject *py_unreal_engine_add_level_to_world(PyObject *, PyObject *); PyObject *py_unreal_engine_move_selected_actors_to_level(PyObject *, PyObject *); PyObject *py_unreal_engine_move_actor_to_level(PyObject *, PyObject *); PyObject *py_ue_factory_create_new(ue_PyUObject *, PyObject *); PyObject *py_ue_factory_import_object(ue_PyUObject *, PyObject *); PyObject *py_unreal_engine_blueprint_add_event_dispatcher(PyObject *, PyObject *); PyObject *py_unreal_engine_editor_take_high_res_screen_shots(PyObject *, PyObject *); PyObject *py_unreal_engine_blueprint_add_function(PyObject *, PyObject *); PyObject *py_unreal_engine_blueprint_add_ubergraph_page(PyObject *, PyObject *); PyObject *py_unreal_engine_blueprint_get_all_graphs(PyObject *, PyObject *); PyObject *py_unreal_engine_create_new_graph(PyObject *, PyObject *); PyObject *py_unreal_engine_blueprint_mark_as_structurally_modified(PyObject *, PyObject *); // efeng additional functions PyObject *py_unreal_engine_create_material_instance(PyObject *, PyObject *); PyObject *py_unreal_engine_allow_actor_script_execution_in_editor(PyObject *, PyObject *); PyObject *py_unreal_engine_get_asset_referencers(PyObject *, PyObject *); PyObject *py_unreal_engine_get_asset_identifier_referencers(PyObject *, PyObject *); PyObject *py_unreal_engine_get_asset_dependencies(PyObject *, PyObject *); PyObject *py_unreal_engine_open_editor_for_asset(PyObject *, PyObject *); PyObject *py_unreal_engine_find_editor_for_asset(PyObject *, PyObject *); PyObject *py_unreal_engine_get_all_edited_assets(PyObject *, PyObject *); PyObject *py_unreal_engine_close_editor_for_asset(PyObject *, PyObject *); PyObject *py_unreal_engine_close_all_asset_editors(PyObject *, PyObject *); // transactions PyObject *py_unreal_engine_begin_transaction(PyObject *, PyObject *); PyObject *py_unreal_engine_cancel_transaction(PyObject *, PyObject *); PyObject *py_unreal_engine_end_transaction(PyObject *, PyObject *); PyObject *py_unreal_engine_get_transaction_name(PyObject *, PyObject *); PyObject *py_unreal_engine_is_transaction_active(PyObject *, PyObject *); PyObject *py_unreal_engine_redo_transaction(PyObject *, PyObject *); PyObject *py_unreal_engine_reset_transaction(PyObject *, PyObject *); PyObject *py_unreal_engine_editor_undo(PyObject *, PyObject *); PyObject *py_unreal_engine_editor_redo(PyObject *, PyObject *); PyObject *py_unreal_engine_transactions(PyObject *, PyObject *); PyObject *py_unreal_engine_all_viewport_clients(PyObject *, PyObject *); PyObject *py_unreal_engine_editor_sync_browser_to_assets(PyObject *, PyObject *); PyObject *py_unreal_engine_heightmap_expand(PyObject *, PyObject *); PyObject *py_unreal_engine_heightmap_import(PyObject *, PyObject *); PyObject *py_unreal_engine_play_preview_sound(PyObject *, PyObject *); PyObject *py_unreal_engine_register_settings(PyObject *, PyObject *); PyObject *py_unreal_engine_show_viewer(PyObject *, PyObject *); PyObject *py_unreal_engine_unregister_settings(PyObject *, PyObject *); PyObject *py_unreal_engine_request_play_session(PyObject *, PyObject *); PyObject *py_unreal_engine_export_assets(PyObject *, PyObject *); #endif ```
/content/code_sandbox/Source/UnrealEnginePython/Private/UEPyEditor.h
objective-c
2016-08-07T05:00:51
2024-08-14T06:32:20
UnrealEnginePython
20tab/UnrealEnginePython
2,715
1,290
```objective-c #pragma once #include "UEPyModule.h" #if WITH_EDITOR #include "Runtime/Projects/Public/Interfaces/IPluginManager.h" typedef struct { PyObject_HEAD /* Type-specific fields go here. */ IPlugin *plugin; } ue_PyIPlugin; PyObject *py_ue_new_iplugin(IPlugin *); void ue_python_init_iplugin(PyObject *); #endif ```
/content/code_sandbox/Source/UnrealEnginePython/Private/UEPyIPlugin.h
objective-c
2016-08-07T05:00:51
2024-08-14T06:32:20
UnrealEnginePython
20tab/UnrealEnginePython
2,715
78
```c++ #include "UEPyModule.h" #include "UEPyEngine.h" #include "UEPyTimer.h" #include "UEPyTicker.h" #include "UEPyVisualLogger.h" #include "UObject/UEPyObject.h" #include "UObject/UEPyActor.h" #include "UObject/UEPyTransform.h" #include "UObject/UEPyPlayer.h" #include "UObject/UEPyInput.h" #include "UObject/UEPyWorld.h" #include "UObject/UEPyNavigation.h" #include "UObject/UEPySpline.h" #include "UObject/UEPyMovements.h" #include "UObject/UEPyAttaching.h" #include "UObject/UEPySkeletal.h" #include "UObject/UEPyStaticMesh.h" #include "UObject/UEPyTraceAndSweep.h" #include "UObject/UEPyPhysics.h" #include "UObject/UEPyAudio.h" #include "UObject/UEPySequencer.h" #include "UObject/UEPyViewport.h" #include "UObject/UEPyWidget.h" #include "UObject/UEPyWidgetComponent.h" #include "UObject/UEPyPackage.h" #include "UObject/UEPyTexture.h" #include "UObject/UEPyMaterial.h" #include "UObject/UEPyPawn.h" #include "UObject/UEPyController.h" #include "UObject/UEPyHUD.h" #include "UObject/UEPyAnimSequence.h" #include "UObject/UEPyCapture.h" #include "UObject/UEPyLandscape.h" #include "UObject/UEPyUserDefinedStruct.h" #include "UObject/UEPyDataTable.h" #include "UObject/UEPyExporter.h" #include "UObject/UEPyFoliage.h" #include "UEPyAssetUserData.h" #if WITH_EDITOR #include "UEPyEditor.h" #include "Blueprint/UEPyEdGraph.h" #include "Fbx/UEPyFbx.h" #include "Editor/BlueprintGraph/Classes/EdGraphSchema_K2.h" #include "Editor/BlueprintGraph/Public/BlueprintActionDatabase.h" #endif #include "Wrappers/UEPyESlateEnums.h" #include "Wrappers/UEPyFVector.h" #include "Wrappers/UEPyFVector2D.h" #include "Wrappers/UEPyFHitResult.h" #include "Wrappers/UEPyFRotator.h" #include "Wrappers/UEPyFTransform.h" #include "Wrappers/UEPyFColor.h" #include "Wrappers/UEPyFLinearColor.h" #include "Wrappers/UEPyFSocket.h" #include "Wrappers/UEPyFQuat.h" #include "Wrappers/UEPyFRawAnimSequenceTrack.h" #include "Wrappers/UEPyFRandomStream.h" #include "Wrappers/UEPyFPythonOutputDevice.h" #if WITH_EDITOR #include "Wrappers/UEPyFSoftSkinVertex.h" #endif #include "Wrappers/UEPyFMorphTargetDelta.h" #include "Wrappers/UEPyFObjectThumbnail.h" #include "Wrappers/UEPyFViewportClient.h" #if WITH_EDITOR #include "Wrappers/UEPyFEditorViewportClient.h" #include "Wrappers/UEPyIAssetEditorInstance.h" #endif #include "Wrappers/UEPyFFoliageInstance.h" #include "UEPyCallable.h" #include "UEPyUClassesImporter.h" #include "UEPyEnumsImporter.h" #include "UEPyUStructsImporter.h" #include "UEPyUScriptStruct.h" #if WITH_EDITOR #include "Wrappers/UEPyFSlowTask.h" #include "Wrappers/UEPyFAssetData.h" #include "Wrappers/UEPyFARFilter.h" #include "Wrappers/UEPyFRawMesh.h" #include "Wrappers/UEPyFStringAssetReference.h" #include "UObject/UEPyAnimSequence.h" #include "Blueprint/UEPyEdGraphPin.h" #include "UEPyIPlugin.h" #include "CollectionManager/UEPyICollectionManager.h" #include "MaterialEditorUtilities/UEPyFMaterialEditorUtilities.h" #endif #include "Wrappers/UEPyFFrameNumber.h" #include "Slate/UEPySlate.h" #include "Http/UEPyIHttp.h" #include "ConsoleManager/UEPyIConsoleManager.h" #include "SlateApplication/UEPyFSlateApplication.h" #include "Voice/UEPyIVoiceCapture.h" #include "PythonFunction.h" #include "PythonClass.h" #if ENGINE_MINOR_VERSION >= 15 #include "Engine/UserDefinedEnum.h" #endif #include "Runtime/Core/Public/UObject/PropertyPortFlags.h" #if ENGINE_MINOR_VERSION < 18 #define USoftObjectProperty UAssetObjectProperty #define USoftClassProperty UAssetClassProperty typedef FAssetPtr FSoftObjectPtr; #endif DEFINE_LOG_CATEGORY(LogPython); PyDoc_STRVAR(unreal_engine_py_doc, "Unreal Engine Python module."); #if PY_MAJOR_VERSION >= 3 static PyModuleDef unreal_engine_module = { PyModuleDef_HEAD_INIT, "unreal_engine", unreal_engine_py_doc, -1, NULL, }; static PyObject* init_unreal_engine(void); void init_unreal_engine_builtin() { PyImport_AppendInittab("unreal_engine", &init_unreal_engine); } #endif static PyObject* py_unreal_engine_py_gc(PyObject* self, PyObject* args) { int32 Garbaged = FUnrealEnginePythonHouseKeeper::Get()->RunGC(); return PyLong_FromLong(Garbaged); } static PyObject* py_unreal_engine_exec(PyObject* self, PyObject* args) { char* filename = nullptr; if (!PyArg_ParseTuple(args, "s:exec", &filename)) { return NULL; } FUnrealEnginePythonModule& PythonModule = FModuleManager::GetModuleChecked<FUnrealEnginePythonModule>("UnrealEnginePython"); Py_BEGIN_ALLOW_THREADS; PythonModule.RunFile(filename); Py_END_ALLOW_THREADS; Py_RETURN_NONE; } #if PLATFORM_MAC static PyObject* py_unreal_engine_exec_in_main_thread(PyObject* self, PyObject* args) { char* filename = nullptr; if (!PyArg_ParseTuple(args, "s:exec_in_main_thread", &filename)) { return NULL; } FUnrealEnginePythonModule& PythonModule = FModuleManager::GetModuleChecked<FUnrealEnginePythonModule>("UnrealEnginePython"); Py_BEGIN_ALLOW_THREADS; PythonModule.RunFileInMainThread(filename); Py_END_ALLOW_THREADS; Py_RETURN_NONE; } #endif static PyObject* py_ue_get_py_proxy(ue_PyUObject* self, PyObject* args) { ue_py_check(self); if (self->py_proxy) { Py_INCREF(self->py_proxy); return (PyObject*)self->py_proxy; } Py_RETURN_NONE; } static PyObject* py_unreal_engine_shutdown(PyObject* self, PyObject* args) { GIsRequestingExit = true; Py_RETURN_NONE; } static PyObject* py_unreal_engine_set_brutal_finalize(PyObject* self, PyObject* args) { PyObject* py_bool = nullptr; if (!PyArg_ParseTuple(args, "|O:set_brutal_finalize", &py_bool)) { return nullptr; } bool bBrutalFinalize = !py_bool || PyObject_IsTrue(py_bool); FUnrealEnginePythonModule& PythonModule = FModuleManager::GetModuleChecked<FUnrealEnginePythonModule>("UnrealEnginePython"); PythonModule.BrutalFinalize = bBrutalFinalize; Py_RETURN_NONE; } static PyMethodDef unreal_engine_methods[] = { { "log", py_unreal_engine_log, METH_VARARGS, "" }, { "log_warning", py_unreal_engine_log_warning, METH_VARARGS, "" }, { "log_error", py_unreal_engine_log_error, METH_VARARGS, "" }, { "shutdown", py_unreal_engine_shutdown, METH_VARARGS, "" }, { "set_brutal_finalize", py_unreal_engine_set_brutal_finalize, METH_VARARGS, "" }, { "add_on_screen_debug_message", py_unreal_engine_add_on_screen_debug_message, METH_VARARGS, "" }, { "print_string", py_unreal_engine_print_string, METH_VARARGS, "" }, { "set_random_seed", py_unreal_engine_set_random_seed, METH_VARARGS, "" }, { "find_class", py_unreal_engine_find_class, METH_VARARGS, "" }, { "find_struct", py_unreal_engine_find_struct, METH_VARARGS, "" }, { "find_enum", py_unreal_engine_find_enum, METH_VARARGS, "" }, { "load_class", py_unreal_engine_load_class, METH_VARARGS, "" }, { "load_struct", py_unreal_engine_load_struct, METH_VARARGS, "" }, { "load_enum", py_unreal_engine_load_enum, METH_VARARGS, "" }, { "find_object", py_unreal_engine_find_object, METH_VARARGS, "" }, { "load_object", py_unreal_engine_load_object, METH_VARARGS, "" }, { "load_package", py_unreal_engine_load_package, METH_VARARGS, "" }, #if WITH_EDITOR { "unload_package", py_unreal_engine_unload_package, METH_VARARGS, "" }, { "get_package_filename", py_unreal_engine_get_package_filename, METH_VARARGS, "" }, #endif { "get_forward_vector", py_unreal_engine_get_forward_vector, METH_VARARGS, "" }, { "get_up_vector", py_unreal_engine_get_up_vector, METH_VARARGS, "" }, { "get_right_vector", py_unreal_engine_get_right_vector, METH_VARARGS, "" }, { "get_content_dir", py_unreal_engine_get_content_dir, METH_VARARGS, "" }, { "get_game_saved_dir", py_unreal_engine_get_game_saved_dir, METH_VARARGS, "" }, { "get_game_user_developer_dir", py_unreal_engine_get_game_user_developer_dir, METH_VARARGS, "" }, { "convert_relative_path_to_full", py_unreal_engine_convert_relative_path_to_full, METH_VARARGS, "" }, { "get_path", py_unreal_engine_get_path, METH_VARARGS, "" }, { "get_base_filename", py_unreal_engine_get_base_filename, METH_VARARGS, "" }, { "object_path_to_package_name", py_unreal_engine_object_path_to_package_name, METH_VARARGS, "" }, { "compress_image_array", py_unreal_engine_compress_image_array, METH_VARARGS, "" }, { "create_checkerboard_texture", py_unreal_engine_create_checkerboard_texture, METH_VARARGS, "" }, { "create_transient_texture", py_unreal_engine_create_transient_texture, METH_VARARGS, "" }, { "create_transient_texture_render_target2d", py_unreal_engine_create_transient_texture_render_target2d, METH_VARARGS, "" }, #if WITH_EDITOR { "create_texture", py_unreal_engine_create_texture, METH_VARARGS, "" }, #endif { "create_world", py_unreal_engine_create_world, METH_VARARGS, "" }, // package { "create_package", (PyCFunction)py_unreal_engine_create_package, METH_VARARGS, "" }, { "get_or_create_package", (PyCFunction)py_unreal_engine_get_or_create_package, METH_VARARGS, "" }, { "get_transient_package", (PyCFunction)py_unreal_engine_get_transient_package, METH_VARARGS, "" }, { "open_file_dialog", py_unreal_engine_open_file_dialog, METH_VARARGS, "" }, { "save_file_dialog", py_unreal_engine_save_file_dialog, METH_VARARGS, "" }, { "open_directory_dialog", py_unreal_engine_open_directory_dialog, METH_VARARGS, "" }, { "open_font_dialog", py_unreal_engine_open_font_dialog, METH_VARARGS, "" }, // slate { "find_slate_style", py_unreal_engine_find_slate_style, METH_VARARGS, "" }, { "find_icon_for_class", py_unreal_engine_find_icon_for_class, METH_VARARGS, "" }, { "register_nomad_tab_spawner", py_unreal_engine_register_nomad_tab_spawner, METH_VARARGS, "" }, { "unregister_nomad_tab_spawner", py_unreal_engine_unregister_nomad_tab_spawner, METH_VARARGS, "" }, { "invoke_tab", py_unreal_engine_invoke_tab, METH_VARARGS, "" }, { "get_swidget_from_wrapper", py_unreal_engine_get_swidget_from_wrapper, METH_VARARGS, "" }, { "create_wrapper_from_pyswidget", py_unreal_engine_create_wrapper_from_pyswidget, METH_VARARGS, "" }, #if WITH_EDITOR { "get_editor_window", py_unreal_engine_get_editor_window, METH_VARARGS, "" }, { "add_menu_extension", py_unreal_engine_add_menu_extension, METH_VARARGS, "" }, { "add_menu_bar_extension", py_unreal_engine_add_menu_bar_extension, METH_VARARGS, "" }, { "add_tool_bar_extension", py_unreal_engine_add_tool_bar_extension, METH_VARARGS, "" }, { "add_asset_view_context_menu_extension", py_unreal_engine_add_asset_view_context_menu_extension, METH_VARARGS, "" }, { "redraw_all_viewports", py_unreal_engine_redraw_all_viewports, METH_VARARGS, "" }, { "update_ui", py_unreal_engine_update_ui, METH_VARARGS, "" }, #pragma warning(suppress: 4191) { "create_detail_view", (PyCFunction)py_unreal_engine_create_detail_view, METH_VARARGS | METH_KEYWORDS, "" }, #pragma warning(suppress: 4191) { "create_structure_detail_view", (PyCFunction)py_unreal_engine_create_structure_detail_view, METH_VARARGS | METH_KEYWORDS, "" }, #pragma warning(suppress: 4191) { "create_property_view", (PyCFunction)py_unreal_engine_create_property_view, METH_VARARGS | METH_KEYWORDS, "" }, { "open_editor_for_asset", py_unreal_engine_open_editor_for_asset, METH_VARARGS, "" }, { "find_editor_for_asset", py_unreal_engine_find_editor_for_asset, METH_VARARGS, "" }, { "get_all_edited_assets", py_unreal_engine_get_all_edited_assets, METH_VARARGS, "" }, { "close_editor_for_asset", py_unreal_engine_close_editor_for_asset, METH_VARARGS, "" }, { "close_all_asset_editors", py_unreal_engine_close_all_asset_editors, METH_VARARGS, "" }, { "allow_actor_script_execution_in_editor", py_unreal_engine_allow_actor_script_execution_in_editor , METH_VARARGS, "" }, { "get_editor_world", py_unreal_engine_get_editor_world, METH_VARARGS, "" }, { "console_exec", py_unreal_engine_console_exec, METH_VARARGS, "" }, { "editor_get_selected_actors", py_unreal_engine_editor_get_selected_actors, METH_VARARGS, "" }, { "editor_select_actor", py_unreal_engine_editor_select_actor, METH_VARARGS, "" }, { "editor_deselect_actors", py_unreal_engine_editor_deselect_actors, METH_VARARGS, "" }, { "import_asset", py_unreal_engine_import_asset, METH_VARARGS, "" }, { "export_assets", py_unreal_engine_export_assets, METH_VARARGS, "" }, { "get_asset", py_unreal_engine_get_asset, METH_VARARGS, "" }, { "find_asset", py_unreal_engine_find_asset, METH_VARARGS, "" }, { "create_asset", py_unreal_engine_create_asset, METH_VARARGS, "" }, { "delete_object", py_unreal_engine_delete_object, METH_VARARGS, "" }, { "get_assets", py_unreal_engine_get_assets, METH_VARARGS, "" }, { "get_selected_assets", py_unreal_engine_get_selected_assets, METH_VARARGS, "" }, { "get_assets_by_class", py_unreal_engine_get_assets_by_class, METH_VARARGS, "" }, { "is_loading_assets", py_unreal_engine_is_loading_assets, METH_VARARGS, "" }, { "wait_for_assets", py_unreal_engine_wait_for_assets, METH_VARARGS, "" }, { "sync_browser_to_assets", py_unreal_engine_editor_sync_browser_to_assets, METH_VARARGS, "" }, { "get_asset_referencers", py_unreal_engine_get_asset_referencers, METH_VARARGS, "" }, { "get_asset_identifier_referencers", py_unreal_engine_get_asset_identifier_referencers, METH_VARARGS, "" }, { "get_asset_dependencies", py_unreal_engine_get_asset_dependencies, METH_VARARGS, "" }, { "rename_asset", py_unreal_engine_rename_asset, METH_VARARGS, "" }, { "duplicate_asset", py_unreal_engine_duplicate_asset, METH_VARARGS, "" }, { "delete_asset", py_unreal_engine_delete_asset, METH_VARARGS, "" }, { "get_long_package_path", py_unreal_engine_get_long_package_path, METH_VARARGS, "" }, { "get_long_package_asset_name", py_unreal_engine_get_long_package_asset_name, METH_VARARGS, "" }, { "editor_command_build", py_unreal_engine_editor_command_build, METH_VARARGS, "" }, { "editor_command_build_lighting", py_unreal_engine_editor_command_build_lighting, METH_VARARGS, "" }, { "editor_command_save_current_level", py_unreal_engine_editor_command_save_current_level, METH_VARARGS, "" }, { "editor_command_save_all_levels", py_unreal_engine_editor_command_save_all_levels, METH_VARARGS, "" }, { "editor_save_all", py_unreal_engine_editor_save_all, METH_VARARGS, "" }, { "get_discovered_plugins", py_unreal_engine_get_discovered_plugins, METH_VARARGS, "" }, { "get_enabled_plugins", py_unreal_engine_get_enabled_plugins, METH_VARARGS, "" }, { "find_plugin", py_unreal_engine_find_plugin, METH_VARARGS, "" }, { "string_to_guid", py_unreal_engine_string_to_guid, METH_VARARGS, "" }, { "new_guid", py_unreal_engine_new_guid, METH_VARARGS, "" }, { "guid_to_string", py_unreal_engine_guid_to_string, METH_VARARGS, "" }, { "heightmap_expand", py_unreal_engine_heightmap_expand, METH_VARARGS, "" }, { "heightmap_import", py_unreal_engine_heightmap_import, METH_VARARGS, "" }, { "play_preview_sound", py_unreal_engine_play_preview_sound, METH_VARARGS, "" }, #pragma warning(suppress: 4191) { "get_assets_by_filter", (PyCFunction)py_unreal_engine_get_assets_by_filter, METH_VARARGS | METH_KEYWORDS, "" }, { "create_blueprint", py_unreal_engine_create_blueprint, METH_VARARGS, "" }, { "create_blueprint_from_actor", py_unreal_engine_create_blueprint_from_actor, METH_VARARGS, "" }, { "replace_blueprint", py_unreal_engine_replace_blueprint, METH_VARARGS, "" }, { "get_blueprint_hierarchy_from_class", py_unreal_engine_get_blueprint_hierarchy_from_class, METH_VARARGS, "" }, { "reload_blueprint", py_unreal_engine_reload_blueprint, METH_VARARGS, "" }, { "compile_blueprint", py_unreal_engine_compile_blueprint, METH_VARARGS, "" }, { "blueprint_add_member_variable", py_unreal_engine_blueprint_add_member_variable, METH_VARARGS, "" }, { "blueprint_add_event_dispatcher", py_unreal_engine_blueprint_add_event_dispatcher, METH_VARARGS, "" }, { "blueprint_add_new_timeline", py_unreal_engine_blueprint_add_new_timeline, METH_VARARGS, "" }, { "blueprint_set_variable_visibility", py_unreal_engine_blueprint_set_variable_visibility, METH_VARARGS, "" }, { "blueprint_add_function", py_unreal_engine_blueprint_add_function, METH_VARARGS, "" }, { "blueprint_add_ubergraph_page", py_unreal_engine_blueprint_add_ubergraph_page, METH_VARARGS, "" }, { "blueprint_get_all_graphs", py_unreal_engine_blueprint_get_all_graphs, METH_VARARGS, "" }, { "blueprint_mark_as_structurally_modified", py_unreal_engine_blueprint_mark_as_structurally_modified, METH_VARARGS, "" }, { "add_component_to_blueprint", py_unreal_engine_add_component_to_blueprint, METH_VARARGS, "" }, { "remove_component_from_blueprint", py_unreal_engine_remove_component_from_blueprint, METH_VARARGS, "" }, { "get_blueprint_components", py_unreal_engine_get_blueprint_components, METH_VARARGS, "" }, { "create_material_instance", py_unreal_engine_create_material_instance, METH_VARARGS, "" }, { "message_dialog_open", py_unreal_engine_message_dialog_open, METH_VARARGS, "" }, { "create_modal_save_asset_dialog", py_unreal_engine_create_modal_save_asset_dialog, METH_VARARGS, "" }, { "set_fbx_import_option", py_unreal_engine_set_fbx_import_option, METH_VARARGS, "" }, { "create_new_graph", py_unreal_engine_create_new_graph, METH_VARARGS, "" }, { "editor_play", py_unreal_engine_editor_play, METH_VARARGS, "" }, { "add_level_to_world", py_unreal_engine_add_level_to_world, METH_VARARGS, "" }, { "move_selected_actors_to_level", py_unreal_engine_move_selected_actors_to_level, METH_VARARGS, "" }, { "move_actor_to_level", py_unreal_engine_move_actor_to_level, METH_VARARGS, "" }, { "editor_on_asset_post_import", py_unreal_engine_editor_on_asset_post_import, METH_VARARGS, "" }, { "on_main_frame_creation_finished", py_unreal_engine_on_main_frame_creation_finished, METH_VARARGS, "" }, // transactions { "begin_transaction", py_unreal_engine_begin_transaction, METH_VARARGS, "" }, { "cancel_transaction", py_unreal_engine_cancel_transaction, METH_VARARGS, "" }, { "end_transaction", py_unreal_engine_end_transaction, METH_VARARGS, "" }, { "get_transaction_name", py_unreal_engine_get_transaction_name, METH_VARARGS, "" }, { "is_transaction_active", py_unreal_engine_is_transaction_active, METH_VARARGS, "" }, { "redo_transaction", py_unreal_engine_redo_transaction, METH_VARARGS, "" }, { "reset_transaction", py_unreal_engine_reset_transaction, METH_VARARGS, "" }, { "transactions", py_unreal_engine_transactions, METH_VARARGS, "" }, { "editor_undo", py_unreal_engine_editor_undo, METH_VARARGS, "" }, { "editor_redo", py_unreal_engine_editor_redo, METH_VARARGS, "" }, { "editor_tick", py_unreal_engine_editor_tick, METH_VARARGS, "" }, #endif { "engine_tick", py_unreal_engine_engine_tick, METH_VARARGS, "" }, #if WITH_EDITOR { "tick_rendering_tickables", py_unreal_engine_tick_rendering_tickables, METH_VARARGS, "" }, { "all_viewport_clients", py_unreal_engine_all_viewport_clients , METH_VARARGS, "" }, #endif { "slate_tick", py_unreal_engine_slate_tick, METH_VARARGS, "" }, { "get_delta_time", py_unreal_engine_get_delta_time, METH_VARARGS, "" }, { "new_object", py_unreal_engine_new_object, METH_VARARGS, "" }, { "get_mutable_default", py_unreal_engine_get_mutable_default, METH_VARARGS, "" }, { "all_classes", (PyCFunction)py_unreal_engine_all_classes, METH_VARARGS, "" }, { "all_worlds", (PyCFunction)py_unreal_engine_all_worlds, METH_VARARGS, "" }, { "tobject_iterator", (PyCFunction)py_unreal_engine_tobject_iterator, METH_VARARGS, "" }, { "new_class", py_unreal_engine_new_class, METH_VARARGS, "" }, { "create_and_dispatch_when_ready", py_unreal_engine_create_and_dispatch_when_ready, METH_VARARGS, "" }, #if PLATFORM_MAC { "main_thread_call", py_unreal_engine_main_thread_call, METH_VARARGS, "" }, #endif { "add_ticker", py_unreal_engine_add_ticker, METH_VARARGS, "" }, { "remove_ticker", py_unreal_engine_remove_ticker, METH_VARARGS, "" }, { "py_gc", py_unreal_engine_py_gc, METH_VARARGS, "" }, // exec is a reserved keyword in python2 #if PY_MAJOR_VERSION >= 3 { "exec", py_unreal_engine_exec, METH_VARARGS, "" }, #endif { "py_exec", py_unreal_engine_exec, METH_VARARGS, "" }, #if PLATFORM_MAC { "exec_in_main_thread", py_unreal_engine_exec_in_main_thread, METH_VARARGS, "" }, { "py_exec_in_main_thread", py_unreal_engine_exec_in_main_thread, METH_VARARGS, "" }, #endif { "get_engine_defined_action_mappings", py_unreal_engine_get_engine_defined_action_mappings, METH_VARARGS, "" }, { "get_viewport_screenshot", py_unreal_engine_get_viewport_screenshot, METH_VARARGS, "" }, { "get_viewport_size", py_unreal_engine_get_viewport_size, METH_VARARGS, "" }, { "get_resolution", py_unreal_engine_get_resolution, METH_VARARGS, "" }, { "get_game_viewport_size", py_unreal_engine_get_game_viewport_size, METH_VARARGS, "" }, { "get_game_viewport_client", py_unreal_engine_get_game_viewport_client, METH_VARARGS, "" }, #pragma warning(suppress: 4191) { "open_color_picker", (PyCFunction)py_unreal_engine_open_color_picker, METH_VARARGS | METH_KEYWORDS, "" }, { "destroy_color_picker", py_unreal_engine_destroy_color_picker, METH_VARARGS, "" }, { "play_sound", py_unreal_engine_play_sound, METH_VARARGS, "" }, #if WITH_EDITOR { "editor_play_in_viewport", py_unreal_engine_editor_play_in_viewport, METH_VARARGS, "" }, { "request_play_session", py_unreal_engine_request_play_session, METH_VARARGS, "" }, { "get_editor_pie_game_viewport_client", py_unreal_engine_get_editor_pie_game_viewport_client, METH_VARARGS, "" }, { "editor_get_active_viewport_screenshot", py_unreal_engine_editor_get_active_viewport_screenshot, METH_VARARGS, "" }, { "editor_get_pie_viewport_screenshot", py_unreal_engine_editor_get_pie_viewport_screenshot, METH_VARARGS, "" }, { "editor_set_view_mode", py_unreal_engine_editor_set_view_mode, METH_VARARGS, "" }, { "editor_set_camera_speed", py_unreal_engine_editor_set_camera_speed, METH_VARARGS, "" }, { "editor_set_view_location", py_unreal_engine_editor_set_view_location, METH_VARARGS, "" }, { "editor_set_view_rotation", py_unreal_engine_editor_set_view_rotation, METH_VARARGS, "" }, { "editor_get_active_viewport_size", py_unreal_engine_editor_get_active_viewport_size, METH_VARARGS, "" }, { "editor_get_pie_viewport_size", py_unreal_engine_editor_get_pie_viewport_size, METH_VARARGS, "" }, { "editor_take_high_res_screen_shots", py_unreal_engine_editor_take_high_res_screen_shots, METH_VARARGS, "" }, { "register_settings", py_unreal_engine_register_settings, METH_VARARGS, "" }, { "show_viewer", py_unreal_engine_show_viewer, METH_VARARGS, "" }, { "unregister_settings", py_unreal_engine_unregister_settings, METH_VARARGS, "" }, { "in_editor_capture", py_unreal_engine_in_editor_capture, METH_VARARGS, "" }, #endif { "clipboard_copy", py_unreal_engine_clipboard_copy, METH_VARARGS, "" }, { "clipboard_paste", py_unreal_engine_clipboard_paste, METH_VARARGS, "" }, #pragma warning(suppress: 4191) { "copy_properties_for_unrelated_objects", (PyCFunction)py_unreal_engine_copy_properties_for_unrelated_objects, METH_VARARGS | METH_KEYWORDS, "" }, { NULL, NULL }, }; static PyMethodDef ue_PyUObject_methods[] = { // Transform { "get_actor_location", (PyCFunction)py_ue_get_actor_location, METH_VARARGS, "" }, { "get_actor_rotation", (PyCFunction)py_ue_get_actor_rotation, METH_VARARGS, "" }, { "get_actor_scale", (PyCFunction)py_ue_get_actor_scale, METH_VARARGS, "" }, { "get_actor_transform", (PyCFunction)py_ue_get_actor_transform, METH_VARARGS, "" }, { "get_actor_forward", (PyCFunction)py_ue_get_actor_forward, METH_VARARGS, "" }, { "get_actor_right", (PyCFunction)py_ue_get_actor_right, METH_VARARGS, "" }, { "get_actor_up", (PyCFunction)py_ue_get_actor_up, METH_VARARGS, "" }, { "set_actor_location", (PyCFunction)py_ue_set_actor_location, METH_VARARGS, "" }, { "set_actor_rotation", (PyCFunction)py_ue_set_actor_rotation, METH_VARARGS, "" }, { "set_actor_scale", (PyCFunction)py_ue_set_actor_scale, METH_VARARGS, "" }, { "set_actor_transform", (PyCFunction)py_ue_set_actor_transform, METH_VARARGS, "" }, { "add_actor_world_offset", (PyCFunction)py_ue_add_actor_world_offset, METH_VARARGS, "" }, { "add_actor_local_offset", (PyCFunction)py_ue_add_actor_local_offset, METH_VARARGS, "" }, { "add_actor_world_rotation", (PyCFunction)py_ue_add_actor_world_rotation, METH_VARARGS, "" }, { "add_actor_local_rotation", (PyCFunction)py_ue_add_actor_local_rotation, METH_VARARGS, "" }, { "get_world_location", (PyCFunction)py_ue_get_world_location, METH_VARARGS, "" }, { "get_world_rotation", (PyCFunction)py_ue_get_world_rotation, METH_VARARGS, "" }, { "get_world_scale", (PyCFunction)py_ue_get_world_scale, METH_VARARGS, "" }, { "get_world_transform", (PyCFunction)py_ue_get_world_transform, METH_VARARGS, "" }, { "get_relative_location", (PyCFunction)py_ue_get_relative_location, METH_VARARGS, "" }, { "get_relative_rotation", (PyCFunction)py_ue_get_relative_rotation, METH_VARARGS, "" }, { "get_relative_scale", (PyCFunction)py_ue_get_relative_scale, METH_VARARGS, "" }, { "get_relative_transform", (PyCFunction)py_ue_get_relative_transform, METH_VARARGS, "" }, { "set_world_location", (PyCFunction)py_ue_set_world_location, METH_VARARGS, "" }, { "set_world_rotation", (PyCFunction)py_ue_set_world_rotation, METH_VARARGS, "" }, { "set_world_scale", (PyCFunction)py_ue_set_world_scale, METH_VARARGS, "" }, { "set_world_transform", (PyCFunction)py_ue_set_world_transform, METH_VARARGS, "" }, { "set_relative_location", (PyCFunction)py_ue_set_relative_location, METH_VARARGS, "" }, { "set_relative_rotation", (PyCFunction)py_ue_set_relative_rotation, METH_VARARGS, "" }, { "set_relative_scale", (PyCFunction)py_ue_set_relative_scale, METH_VARARGS, "" }, { "set_relative_transform", (PyCFunction)py_ue_set_relative_transform, METH_VARARGS, "" }, { "get_forward_vector", (PyCFunction)py_ue_get_forward_vector, METH_VARARGS, "" }, { "get_up_vector", (PyCFunction)py_ue_get_up_vector, METH_VARARGS, "" }, { "get_right_vector", (PyCFunction)py_ue_get_right_vector, METH_VARARGS, "" }, // UObject { "get_property", (PyCFunction)py_ue_get_property, METH_VARARGS, "" }, { "set_property", (PyCFunction)py_ue_set_property, METH_VARARGS, "" }, { "set_property_flags", (PyCFunction)py_ue_set_property_flags, METH_VARARGS, "" }, { "add_property_flags", (PyCFunction)py_ue_add_property_flags, METH_VARARGS, "" }, { "get_property_flags", (PyCFunction)py_ue_get_property_flags, METH_VARARGS, "" }, { "properties", (PyCFunction)py_ue_properties, METH_VARARGS, "" }, { "get_property_class", (PyCFunction)py_ue_get_property_class, METH_VARARGS, "" }, { "has_property", (PyCFunction)py_ue_has_property, METH_VARARGS, "" }, { "get_uproperty", (PyCFunction)py_ue_get_uproperty, METH_VARARGS, "" }, { "get_property_struct", (PyCFunction)py_ue_get_property_struct, METH_VARARGS, "" }, { "get_property_array_dim", (PyCFunction)py_ue_get_property_array_dim, METH_VARARGS, "" }, { "get_inner", (PyCFunction)py_ue_get_inner, METH_VARARGS, "" }, { "get_key_prop", (PyCFunction)py_ue_get_key_prop, METH_VARARGS, "" }, { "get_value_prop", (PyCFunction)py_ue_get_value_prop, METH_VARARGS, "" }, { "functions", (PyCFunction)py_ue_functions, METH_VARARGS, "" }, { "is_a", (PyCFunction)py_ue_is_a, METH_VARARGS, "" }, { "is_valid", (PyCFunction)py_ue_is_valid, METH_VARARGS, "" }, { "is_child_of", (PyCFunction)py_ue_is_child_of, METH_VARARGS, "" }, { "call", (PyCFunction)py_ue_call, METH_VARARGS, "" }, { "get_owner", (PyCFunction)py_ue_get_owner, METH_VARARGS, "" }, { "get_outer", (PyCFunction)py_ue_get_outer, METH_VARARGS, "" }, { "set_outer", (PyCFunction)py_ue_set_outer, METH_VARARGS, "" }, { "get_outermost", (PyCFunction)py_ue_get_outermost, METH_VARARGS, "" }, { "get_super_class", (PyCFunction)py_ue_get_super_class, METH_VARARGS, "" }, { "get_name", (PyCFunction)py_ue_get_name, METH_VARARGS, "" }, { "get_display_name", (PyCFunction)py_ue_get_display_name, METH_VARARGS, "" }, { "get_path_name", (PyCFunction)py_ue_get_path_name, METH_VARARGS, "" }, { "get_full_name", (PyCFunction)py_ue_get_full_name, METH_VARARGS, "" }, #if WITH_EDITOR { "import_custom_properties", (PyCFunction)py_ue_import_custom_properties, METH_VARARGS, "" }, #endif #if ENGINE_MINOR_VERSION >= 15 { "can_modify", (PyCFunction)py_ue_can_modify, METH_VARARGS, "" }, #endif { "set_name", (PyCFunction)py_ue_set_name, METH_VARARGS, "" }, { "bind_event", (PyCFunction)py_ue_bind_event, METH_VARARGS, "" }, { "unbind_event", (PyCFunction)py_ue_unbind_event, METH_VARARGS, "" }, { "delegate_bind_ufunction", (PyCFunction)py_ue_delegate_bind_ufunction, METH_VARARGS, "" }, { "get_py_proxy", (PyCFunction)py_ue_get_py_proxy, METH_VARARGS, "" }, { "post_edit_change", (PyCFunction)py_ue_post_edit_change, METH_VARARGS, "" }, { "post_edit_change_property", (PyCFunction)py_ue_post_edit_change_property, METH_VARARGS, "" }, { "pre_edit_change", (PyCFunction)py_ue_pre_edit_change, METH_VARARGS, "" }, { "modify", (PyCFunction)py_ue_modify, METH_VARARGS, "" }, #if WITH_EDITOR { "get_thumbnail", (PyCFunction)py_ue_get_thumbnail, METH_VARARGS, "" }, { "render_thumbnail", (PyCFunction)py_ue_render_thumbnail, METH_VARARGS, "" }, {"get_metadata_tag", (PyCFunction)py_ue_get_metadata_tag, METH_VARARGS, "" }, {"set_metadata_tag", (PyCFunction)py_ue_set_metadata_tag, METH_VARARGS, "" }, { "metadata_tags", (PyCFunction)py_ue_metadata_tags, METH_VARARGS, "" }, { "has_metadata_tag", (PyCFunction)py_ue_has_metadata_tag, METH_VARARGS, "" }, {"remove_metadata_tag", (PyCFunction)py_ue_remove_metadata_tag, METH_VARARGS, "" }, #endif #if WITH_EDITOR { "save_config", (PyCFunction)py_ue_save_config, METH_VARARGS, "" }, { "get_actor_label", (PyCFunction)py_ue_get_actor_label, METH_VARARGS, "" }, { "set_actor_label", (PyCFunction)py_ue_set_actor_label, METH_VARARGS, "" }, { "set_actor_hidden_in_game", (PyCFunction)py_ue_set_actor_hidden_in_game, METH_VARARGS, "" }, { "get_folder_path", (PyCFunction)py_ue_get_folder_path, METH_VARARGS, "" }, { "set_folder_path", (PyCFunction)py_ue_set_folder_path, METH_VARARGS, "" }, { "world_create_folder", (PyCFunction)py_ue_world_create_folder, METH_VARARGS, "" }, { "world_delete_folder", (PyCFunction)py_ue_world_delete_folder, METH_VARARGS, "" }, { "world_rename_folder", (PyCFunction)py_ue_world_rename_folder, METH_VARARGS, "" }, { "world_folders", (PyCFunction)py_ue_world_folders, METH_VARARGS, "" }, { "get_editor_world_counterpart_actor", (PyCFunction)py_ue_get_editor_world_counterpart_actor, METH_VARARGS, "" }, { "component_type_registry_invalidate_class", (PyCFunction)py_ue_component_type_registry_invalidate_class, METH_VARARGS, "" }, { "find_actor_by_label", (PyCFunction)py_ue_find_actor_by_label, METH_VARARGS, "" }, { "save_package", (PyCFunction)py_ue_save_package, METH_VARARGS, "" }, { "duplicate", (PyCFunction)py_ue_duplicate, METH_VARARGS, "" }, { "asset_can_reimport", (PyCFunction)py_ue_asset_can_reimport, METH_VARARGS, "" }, { "asset_reimport", (PyCFunction)py_ue_asset_reimport, METH_VARARGS, "" }, { "factory_create_new", (PyCFunction)py_ue_factory_create_new, METH_VARARGS, "" }, { "factory_import_object", (PyCFunction)py_ue_factory_import_object, METH_VARARGS, "" }, { "graph_add_node_call_function", (PyCFunction)py_ue_graph_add_node_call_function, METH_VARARGS, "" }, { "graph_add_node_custom_event", (PyCFunction)py_ue_graph_add_node_custom_event, METH_VARARGS, "" }, { "graph_add_node_variable_get", (PyCFunction)py_ue_graph_add_node_variable_get, METH_VARARGS, "" }, { "graph_add_node_variable_set", (PyCFunction)py_ue_graph_add_node_variable_set, METH_VARARGS, "" }, { "graph_add_node", (PyCFunction)py_ue_graph_add_node, METH_VARARGS, "" }, { "graph_add_node_dynamic_cast", (PyCFunction)py_ue_graph_add_node_dynamic_cast, METH_VARARGS, "" }, { "graph_add_node_event", (PyCFunction)py_ue_graph_add_node_event, METH_VARARGS, "" }, { "graph_get_good_place_for_new_node", (PyCFunction)py_ue_graph_get_good_place_for_new_node, METH_VARARGS, "" }, { "graph_reconstruct_node", (PyCFunction)py_ue_graph_reconstruct_node, METH_VARARGS, "" }, { "graph_remove_node", (PyCFunction)py_ue_graph_remove_node, METH_VARARGS, "" }, { "node_pins", (PyCFunction)py_ue_node_pins, METH_VARARGS, "" }, { "node_get_title", (PyCFunction)py_ue_node_get_title, METH_VARARGS, "" }, { "node_find_pin", (PyCFunction)py_ue_node_find_pin, METH_VARARGS, "" }, { "node_create_pin", (PyCFunction)py_ue_node_create_pin, METH_VARARGS, "" }, { "node_pin_type_changed", (PyCFunction)py_ue_node_pin_type_changed, METH_VARARGS, "" }, { "node_pin_default_value_changed", (PyCFunction)py_ue_node_pin_default_value_changed, METH_VARARGS, "" }, { "node_function_entry_set_pure", (PyCFunction)py_ue_node_function_entry_set_pure, METH_VARARGS, "" }, { "node_allocate_default_pins", (PyCFunction)py_ue_node_allocate_default_pins, METH_VARARGS, "" }, { "node_reconstruct", (PyCFunction)py_ue_node_reconstruct, METH_VARARGS, "" }, { "get_material_graph", (PyCFunction)py_ue_get_material_graph, METH_VARARGS, "" }, { "struct_add_variable", (PyCFunction)py_ue_struct_add_variable, METH_VARARGS, "" }, { "struct_get_variables", (PyCFunction)py_ue_struct_get_variables, METH_VARARGS, "" }, { "struct_remove_variable", (PyCFunction)py_ue_struct_remove_variable, METH_VARARGS, "" }, { "struct_move_variable_up", (PyCFunction)py_ue_struct_move_variable_up, METH_VARARGS, "" }, { "struct_move_variable_down", (PyCFunction)py_ue_struct_move_variable_down, METH_VARARGS, "" }, { "data_table_add_row", (PyCFunction)py_ue_data_table_add_row, METH_VARARGS, "" }, { "data_table_remove_row", (PyCFunction)py_ue_data_table_remove_row, METH_VARARGS, "" }, { "data_table_rename_row", (PyCFunction)py_ue_data_table_rename_row, METH_VARARGS, "" }, { "data_table_as_dict", (PyCFunction)py_ue_data_table_as_dict, METH_VARARGS, "" }, { "data_table_as_json", (PyCFunction)py_ue_data_table_as_json, METH_VARARGS, "" }, { "data_table_find_row", (PyCFunction)py_ue_data_table_find_row, METH_VARARGS, "" }, { "data_table_get_all_rows", (PyCFunction)py_ue_data_table_get_all_rows, METH_VARARGS, "" }, #endif { "export_to_file", (PyCFunction)py_ue_export_to_file, METH_VARARGS, "" }, { "is_rooted", (PyCFunction)py_ue_is_rooted, METH_VARARGS, "" }, { "add_to_root", (PyCFunction)py_ue_add_to_root, METH_VARARGS, "" }, { "auto_root", (PyCFunction)py_ue_auto_root, METH_VARARGS, "" }, { "remove_from_root", (PyCFunction)py_ue_remove_from_root, METH_VARARGS, "" }, { "own", (PyCFunction)py_ue_own, METH_VARARGS, "" }, { "disown", (PyCFunction)py_ue_disown, METH_VARARGS, "" }, { "is_owned", (PyCFunction)py_ue_is_owned, METH_VARARGS, "" }, { "find_function", (PyCFunction)py_ue_find_function, METH_VARARGS, "" }, #pragma warning(suppress: 4191) { "call_function", (PyCFunction)py_ue_call_function, METH_VARARGS | METH_KEYWORDS, "" }, { "all_objects", (PyCFunction)py_ue_all_objects, METH_VARARGS, "" }, { "all_actors", (PyCFunction)py_ue_all_actors, METH_VARARGS, "" }, // Package { "package_get_filename", (PyCFunction)py_ue_package_get_filename, METH_VARARGS, "" }, { "package_is_dirty", (PyCFunction)py_ue_package_is_dirty, METH_VARARGS, "" }, { "make_unique_object_name", (PyCFunction)py_ue_package_make_unique_object_name, METH_VARARGS, "" }, #if WITH_EDITOR // AssetUserData { "asset_import_data", (PyCFunction)py_ue_asset_import_data, METH_VARARGS, "" }, { "asset_import_data_set_sources", (PyCFunction)py_ue_asset_import_data_set_sources, METH_VARARGS, "" }, #endif // AnimSequence { "anim_get_skeleton", (PyCFunction)py_ue_anim_get_skeleton, METH_VARARGS, "" }, { "anim_set_skeleton", (PyCFunction)py_ue_anim_set_skeleton, METH_VARARGS, "" }, { "get_blend_parameter", (PyCFunction)py_ue_get_blend_parameter, METH_VARARGS, "" }, { "set_blend_parameter", (PyCFunction)py_ue_set_blend_parameter, METH_VARARGS, "" }, { "get_bone_transform", (PyCFunction)py_ue_anim_get_bone_transform, METH_VARARGS, "" }, { "extract_bone_transform", (PyCFunction)py_ue_anim_extract_bone_transform, METH_VARARGS, "" }, { "extract_root_motion", (PyCFunction)py_ue_anim_extract_root_motion, METH_VARARGS, "" }, #if WITH_EDITOR #if ENGINE_MINOR_VERSION > 13 { "get_raw_animation_data", (PyCFunction)py_ue_anim_sequence_get_raw_animation_data, METH_VARARGS, "" }, { "get_raw_animation_track", (PyCFunction)py_ue_anim_sequence_get_raw_animation_track, METH_VARARGS, "" }, { "add_new_raw_track", (PyCFunction)py_ue_anim_sequence_add_new_raw_track, METH_VARARGS, "" }, #if ENGINE_MINOR_VERSION <23 { "update_compressed_track_map_from_raw", (PyCFunction)py_ue_anim_sequence_update_compressed_track_map_from_raw, METH_VARARGS, "" }, #endif { "update_raw_track", (PyCFunction)py_ue_anim_sequence_update_raw_track, METH_VARARGS, "" }, { "apply_raw_anim_changes", (PyCFunction)py_ue_anim_sequence_apply_raw_anim_changes, METH_VARARGS, "" }, { "add_key_to_sequence", (PyCFunction)py_ue_anim_add_key_to_sequence, METH_VARARGS, "" }, #endif { "add_anim_composite_section", (PyCFunction)py_ue_add_anim_composite_section, METH_VARARGS, "" }, #endif // VisualLogger { "vlog", (PyCFunction)py_ue_vlog, METH_VARARGS, "" }, { "vlog_cylinder", (PyCFunction)py_ue_vlog_cylinder, METH_VARARGS, "" }, // StaticMesh { "get_static_mesh_bounds", (PyCFunction)py_ue_static_mesh_get_bounds, METH_VARARGS, "" }, #if WITH_EDITOR { "static_mesh_build", (PyCFunction)py_ue_static_mesh_build, METH_VARARGS, "" }, { "static_mesh_create_body_setup", (PyCFunction)py_ue_static_mesh_create_body_setup, METH_VARARGS, "" }, #endif // Input { "get_input_axis", (PyCFunction)py_ue_get_input_axis, METH_VARARGS, "" }, { "bind_input_axis", (PyCFunction)py_ue_bind_input_axis, METH_VARARGS, "" }, { "enable_input", (PyCFunction)py_ue_enable_input, METH_VARARGS, "" }, { "show_mouse_cursor", (PyCFunction)py_ue_show_mouse_cursor, METH_VARARGS, "" }, { "enable_click_events", (PyCFunction)py_ue_enable_click_events, METH_VARARGS, "" }, { "enable_mouse_over_events", (PyCFunction)py_ue_enable_mouse_over_events, METH_VARARGS, "" }, { "was_input_key_just_pressed", (PyCFunction)py_ue_was_input_key_just_pressed, METH_VARARGS, "" }, { "was_input_key_just_released", (PyCFunction)py_ue_was_input_key_just_released, METH_VARARGS, "" }, { "is_action_pressed", (PyCFunction)py_ue_is_action_pressed, METH_VARARGS, "" }, { "is_action_released", (PyCFunction)py_ue_is_action_released, METH_VARARGS, "" }, { "is_input_key_down", (PyCFunction)py_ue_is_input_key_down, METH_VARARGS, "" }, { "bind_action", (PyCFunction)py_ue_bind_action, METH_VARARGS, "" }, { "bind_axis", (PyCFunction)py_ue_bind_axis, METH_VARARGS, "" }, { "bind_key", (PyCFunction)py_ue_bind_key, METH_VARARGS, "" }, { "bind_pressed_key", (PyCFunction)py_ue_bind_pressed_key, METH_VARARGS, "" }, { "bind_released_key", (PyCFunction)py_ue_bind_released_key, METH_VARARGS, "" }, { "input_key", (PyCFunction)py_ue_input_key, METH_VARARGS, "" }, { "input_axis", (PyCFunction)py_ue_input_axis, METH_VARARGS, "" }, // HUD { "hud_draw_2d_line", (PyCFunction)py_ue_hud_draw_2d_line, METH_VARARGS, "" }, { "hud_draw_line", (PyCFunction)py_ue_hud_draw_line, METH_VARARGS, "" }, { "hud_draw_texture", (PyCFunction)py_ue_hud_draw_texture, METH_VARARGS, "" }, { "hud_draw_rect", (PyCFunction)py_ue_hud_draw_rect, METH_VARARGS, "" }, { "hud_draw_text", (PyCFunction)py_ue_hud_draw_text, METH_VARARGS, "" }, // Movements { "add_controller_pitch_input", (PyCFunction)py_ue_add_controller_pitch_input, METH_VARARGS, "" }, { "add_controller_yaw_input", (PyCFunction)py_ue_add_controller_yaw_input, METH_VARARGS, "" }, { "add_controller_roll_input", (PyCFunction)py_ue_add_controller_roll_input, METH_VARARGS, "" }, { "get_control_rotation", (PyCFunction)py_ue_get_control_rotation, METH_VARARGS, "" }, { "add_movement_input", (PyCFunction)py_ue_add_movement_input, METH_VARARGS, "" }, { "jump", (PyCFunction)py_ue_jump, METH_VARARGS, "" }, { "stop_jumping", (PyCFunction)py_ue_stop_jumping, METH_VARARGS, "" }, { "crouch", (PyCFunction)py_ue_crouch, METH_VARARGS, "" }, { "uncrouch", (PyCFunction)py_ue_uncrouch, METH_VARARGS, "" }, { "launch", (PyCFunction)py_ue_launch, METH_VARARGS, "" }, { "is_jumping", (PyCFunction)py_ue_is_jumping, METH_VARARGS, "" }, { "is_crouched", (PyCFunction)py_ue_is_crouched, METH_VARARGS, "" }, { "is_falling", (PyCFunction)py_ue_is_falling, METH_VARARGS, "" }, { "is_flying", (PyCFunction)py_ue_is_falling, METH_VARARGS, "" }, { "can_jump", (PyCFunction)py_ue_can_jump, METH_VARARGS, "" }, { "can_crouch", (PyCFunction)py_ue_can_crouch, METH_VARARGS, "" }, { "get_class", (PyCFunction)py_ue_get_class, METH_VARARGS, "" }, { "class_generated_by", (PyCFunction)py_ue_class_generated_by, METH_VARARGS, "" }, { "class_get_flags", (PyCFunction)py_ue_class_get_flags, METH_VARARGS, "" }, { "class_set_flags", (PyCFunction)py_ue_class_set_flags, METH_VARARGS, "" }, { "get_obj_flags", (PyCFunction)py_ue_get_obj_flags, METH_VARARGS, "" }, { "set_obj_flags", (PyCFunction)py_ue_set_obj_flags, METH_VARARGS, "" }, { "clear_obj_flags", (PyCFunction)py_ue_clear_obj_flags, METH_VARARGS, "" }, { "reset_obj_flags", (PyCFunction)py_ue_reset_obj_flags, METH_VARARGS, "" }, #if WITH_EDITOR { "class_get_config_name", (PyCFunction)py_ue_class_get_config_name, METH_VARARGS, "" }, { "class_set_config_name", (PyCFunction)py_ue_class_set_config_name, METH_VARARGS, "" }, #endif { "get_actor_components", (PyCFunction)py_ue_actor_components, METH_VARARGS, "" }, { "components", (PyCFunction)py_ue_actor_components, METH_VARARGS, "" }, { "get_components", (PyCFunction)py_ue_actor_components, METH_VARARGS, "" }, { "component_is_registered", (PyCFunction)py_ue_component_is_registered, METH_VARARGS, "" }, { "register_component", (PyCFunction)py_ue_register_component, METH_VARARGS, "" }, { "unregister_component", (PyCFunction)py_ue_unregister_component, METH_VARARGS, "" }, { "destroy_component", (PyCFunction)py_ue_destroy_component, METH_VARARGS, "" }, { "actor_destroy_component", (PyCFunction)py_ue_actor_destroy_component, METH_VARARGS, "" }, { "destroy_actor_component", (PyCFunction)py_ue_actor_destroy_component, METH_VARARGS, "" }, { "actor_create_default_subobject", (PyCFunction)py_ue_actor_create_default_subobject, METH_VARARGS, "" }, { "create_default_subobject", (PyCFunction)py_ue_actor_create_default_subobject, METH_VARARGS, "" }, { "actor_begin_play", (PyCFunction)py_ue_actor_begin_play, METH_VARARGS, "" }, { "broadcast", (PyCFunction)py_ue_broadcast, METH_VARARGS, "" }, #if WITH_EDITOR { "get_metadata", (PyCFunction)py_ue_get_metadata, METH_VARARGS, "" }, { "set_metadata", (PyCFunction)py_ue_set_metadata, METH_VARARGS, "" }, { "has_metadata", (PyCFunction)py_ue_has_metadata, METH_VARARGS, "" }, #endif { "quit_game", (PyCFunction)py_ue_quit_game, METH_VARARGS, "" }, { "play", (PyCFunction)py_ue_play, METH_VARARGS, "" }, { "get_world_type", (PyCFunction)py_ue_get_world_type, METH_VARARGS, "" }, { "world_exec", (PyCFunction)py_ue_world_exec, METH_VARARGS, "" }, { "simple_move_to_location", (PyCFunction)py_ue_simple_move_to_location, METH_VARARGS, "" }, { "actor_has_component_of_type", (PyCFunction)py_ue_actor_has_component_of_type, METH_VARARGS, "" }, { "actor_destroy", (PyCFunction)py_ue_actor_destroy, METH_VARARGS, "" }, #pragma warning(suppress: 4191) { "actor_spawn", (PyCFunction)py_ue_actor_spawn, METH_VARARGS | METH_KEYWORDS, "" }, { "actor_has_tag", (PyCFunction)py_ue_actor_has_tag, METH_VARARGS, "" }, { "component_has_tag", (PyCFunction)py_ue_component_has_tag, METH_VARARGS, "" }, { "get_actor_bounds", (PyCFunction)py_ue_get_actor_bounds, METH_VARARGS, "" }, { "line_trace_single_by_channel", (PyCFunction)py_ue_line_trace_single_by_channel, METH_VARARGS, "" }, { "line_trace_multi_by_channel", (PyCFunction)py_ue_line_trace_multi_by_channel, METH_VARARGS, "" }, { "get_hit_result_under_cursor", (PyCFunction)py_ue_get_hit_result_under_cursor, METH_VARARGS, "" }, { "draw_debug_line", (PyCFunction)py_ue_draw_debug_line, METH_VARARGS, "" }, { "destructible_apply_damage", (PyCFunction)py_ue_destructible_apply_damage, METH_VARARGS, "" }, { "set_view_target", (PyCFunction)py_ue_set_view_target, METH_VARARGS, "" }, { "get_world_delta_seconds", (PyCFunction)py_ue_get_world_delta_seconds, METH_VARARGS, "" }, { "get_levels", (PyCFunction)py_ue_get_levels, METH_VARARGS, "" }, { "get_current_level", (PyCFunction)py_ue_get_current_level, METH_VARARGS, "" }, { "set_current_level", (PyCFunction)py_ue_set_current_level, METH_VARARGS, "" }, #if WITH_EDITOR { "get_level_script_blueprint", (PyCFunction)py_ue_get_level_script_blueprint, METH_VARARGS, "" }, { "add_foliage_asset", (PyCFunction)py_ue_add_foliage_asset, METH_VARARGS, "" }, { "get_foliage_instances", (PyCFunction)py_ue_get_foliage_instances, METH_VARARGS, "" }, #endif { "get_instanced_foliage_actor_for_current_level", (PyCFunction)py_ue_get_instanced_foliage_actor_for_current_level, METH_VARARGS, "" }, { "get_instanced_foliage_actor_for_level", (PyCFunction)py_ue_get_instanced_foliage_actor_for_level, METH_VARARGS, "" }, { "get_foliage_types", (PyCFunction)py_ue_get_foliage_types, METH_VARARGS, "" }, { "add_actor_component", (PyCFunction)py_ue_add_actor_component, METH_VARARGS, "" }, { "add_instance_component", (PyCFunction)py_ue_add_instance_component, METH_VARARGS, "" }, { "get_actor_root_component", (PyCFunction)py_ue_get_actor_root_component, METH_VARARGS, "" }, { "add_actor_root_component", (PyCFunction)py_ue_add_actor_root_component, METH_VARARGS, "" }, { "get_actor_component_by_type", (PyCFunction)py_ue_get_actor_component_by_type, METH_VARARGS, "" }, { "get_actor_component_by_class", (PyCFunction)py_ue_get_actor_component_by_type, METH_VARARGS, "" }, { "get_component_by_type", (PyCFunction)py_ue_get_actor_component_by_type, METH_VARARGS, "" }, { "get_component_by_class", (PyCFunction)py_ue_get_actor_component_by_type, METH_VARARGS, "" }, { "get_component", (PyCFunction)py_ue_get_actor_component, METH_VARARGS, "" }, { "get_actor_component", (PyCFunction)py_ue_get_actor_component, METH_VARARGS, "" }, { "get_actor_components_by_type", (PyCFunction)py_ue_get_actor_components_by_type, METH_VARARGS, "" }, { "get_components_by_type", (PyCFunction)py_ue_get_actor_components_by_type, METH_VARARGS, "" }, { "get_actor_components_by_class", (PyCFunction)py_ue_get_actor_components_by_type, METH_VARARGS, "" }, { "get_components_by_class", (PyCFunction)py_ue_get_actor_components_by_type, METH_VARARGS, "" }, { "get_actor_components_by_tag", (PyCFunction)py_ue_get_actor_components_by_tag, METH_VARARGS, "" }, { "get_components_by_tag", (PyCFunction)py_ue_get_actor_components_by_tag, METH_VARARGS, "" }, { "add_python_component", (PyCFunction)py_ue_add_python_component, METH_VARARGS, "" }, { "set_simulate_physics", (PyCFunction)py_ue_set_simulate_physics, METH_VARARGS, "" }, { "add_impulse", (PyCFunction)py_ue_add_impulse, METH_VARARGS, "" }, { "add_angular_impulse", (PyCFunction)py_ue_add_angular_impulse, METH_VARARGS, "" }, { "add_force", (PyCFunction)py_ue_add_force, METH_VARARGS, "" }, { "add_torque", (PyCFunction)py_ue_add_torque, METH_VARARGS, "" }, { "set_physics_linear_velocity", (PyCFunction)py_ue_set_physics_linear_velocity, METH_VARARGS, "" }, { "get_physics_linear_velocity", (PyCFunction)py_ue_get_physics_linear_velocity, METH_VARARGS, "" }, { "set_physics_angular_velocity", (PyCFunction)py_ue_set_physics_angular_velocity, METH_VARARGS, "" }, { "get_physics_angular_velocity", (PyCFunction)py_ue_get_physics_angular_velocity, METH_VARARGS, "" }, { "find_object", (PyCFunction)py_ue_find_object, METH_VARARGS, "" }, { "get_world", (PyCFunction)py_ue_get_world, METH_VARARGS, "" }, { "has_world", (PyCFunction)py_ue_has_world, METH_VARARGS, "" }, { "get_game_viewport", (PyCFunction)py_ue_get_game_viewport, METH_VARARGS, "" }, { "game_viewport_client_set_rendering_flag", (PyCFunction)py_ue_game_viewport_client_set_rendering_flag, METH_VARARGS, "" }, { "get_world_location_at_distance_along_spline", (PyCFunction)py_ue_get_world_location_at_distance_along_spline, METH_VARARGS, "" }, { "get_spline_length", (PyCFunction)py_ue_get_spline_length, METH_VARARGS, "" }, { "game_viewport_client_get_window", (PyCFunction)py_ue_game_viewport_client_get_window, METH_VARARGS, "" }, // Widget { "take_widget", (PyCFunction)py_ue_take_widget, METH_VARARGS, "" }, { "create_widget", (PyCFunction)py_ue_create_widget, METH_VARARGS, "" }, // WidgetComponent { "set_slate_widget", (PyCFunction)py_ue_set_slate_widget, METH_VARARGS, "" }, { "get_actor_velocity", (PyCFunction)py_ue_get_actor_velocity, METH_VARARGS, "" }, { "play_sound_at_location", (PyCFunction)py_ue_play_sound_at_location, METH_VARARGS, "" }, { "queue_audio", (PyCFunction)py_ue_queue_audio, METH_VARARGS, "" }, { "reset_audio", (PyCFunction)py_ue_reset_audio, METH_VARARGS, "" }, { "get_available_audio_byte_count", (PyCFunction)py_ue_get_available_audio_byte_count, METH_VARARGS, "" }, { "sound_get_data", (PyCFunction)py_ue_sound_get_data, METH_VARARGS, "" }, { "sound_set_data", (PyCFunction)py_ue_sound_set_data, METH_VARARGS, "" }, { "world_tick", (PyCFunction)py_ue_world_tick, METH_VARARGS, "" }, { "conditional_begin_destroy", (PyCFunction)py_ue_conditional_begin_destroy, METH_VARARGS, "" }, // Landscape #if WITH_EDITOR { "create_landscape_info", (PyCFunction)py_ue_create_landscape_info, METH_VARARGS, "" }, { "get_landscape_info", (PyCFunction)py_ue_get_landscape_info, METH_VARARGS, "" }, { "landscape_import", (PyCFunction)py_ue_landscape_import, METH_VARARGS, "" }, { "landscape_export_to_raw_mesh", (PyCFunction)py_ue_landscape_export_to_raw_mesh, METH_VARARGS, "" }, #endif // Player { "create_player", (PyCFunction)py_ue_create_player, METH_VARARGS, "" }, { "get_num_players", (PyCFunction)py_ue_get_num_players, METH_VARARGS, "" }, { "get_num_spectators", (PyCFunction)py_ue_get_num_spectators, METH_VARARGS, "" }, { "get_player_controller", (PyCFunction)py_ue_get_player_controller, METH_VARARGS, "" }, { "get_player_hud", (PyCFunction)py_ue_get_player_hud, METH_VARARGS, "" }, { "set_player_hud", (PyCFunction)py_ue_set_player_hud, METH_VARARGS, "" }, { "get_player_camera_manager", (PyCFunction)py_ue_get_player_camera_manager, METH_VARARGS, "" }, { "get_player_pawn", (PyCFunction)py_ue_get_player_pawn, METH_VARARGS, "" }, { "restart_level", (PyCFunction)py_ue_restart_level, METH_VARARGS, "" }, { "get_overlapping_actors", (PyCFunction)py_ue_get_overlapping_actors, METH_VARARGS, "" }, { "actor_set_level_sequence", (PyCFunction)py_ue_actor_set_level_sequence, METH_VARARGS, "" }, // MovieSceneCapture { "capture_initialize", (PyCFunction)py_ue_capture_initialize, METH_VARARGS, "" }, { "capture_start", (PyCFunction)py_ue_capture_start, METH_VARARGS, "" }, { "capture_stop", (PyCFunction)py_ue_capture_stop, METH_VARARGS, "" }, { "capture_load_from_config", (PyCFunction)py_ue_capture_load_from_config, METH_VARARGS, "" }, #if WITH_EDITOR { "set_level_sequence_asset", (PyCFunction)py_ue_set_level_sequence_asset, METH_VARARGS, "" }, #endif // Pawn { "get_controller", (PyCFunction)py_ue_pawn_get_controller, METH_VARARGS, "" }, // Controller { "posses", (PyCFunction)py_ue_controller_posses, METH_VARARGS, "" }, { "unposses", (PyCFunction)py_ue_controller_unposses, METH_VARARGS, "" }, { "get_hud", (PyCFunction)py_ue_controller_get_hud, METH_VARARGS, "" }, { "get_controlled_pawn", (PyCFunction)py_ue_get_controlled_pawn, METH_VARARGS, "" }, { "get_pawn", (PyCFunction)py_ue_get_controlled_pawn, METH_VARARGS, "" }, { "project_world_location_to_screen", (PyCFunction)py_ue_controller_project_world_location_to_screen, METH_VARARGS, "" }, // Attaching { "get_socket_location", (PyCFunction)py_ue_get_socket_location, METH_VARARGS, "" }, { "get_socket_rotation", (PyCFunction)py_ue_get_socket_rotation, METH_VARARGS, "" }, { "get_socket_transform", (PyCFunction)py_ue_get_socket_transform, METH_VARARGS, "" }, { "get_socket_world_transform", (PyCFunction)py_ue_get_socket_world_transform, METH_VARARGS, "" }, { "get_socket_actor_transform", (PyCFunction)py_ue_get_socket_actor_transform, METH_VARARGS, "" }, { "get_attached_actors", (PyCFunction)py_ue_get_attached_actors, METH_VARARGS, "" }, { "get_all_child_actors", (PyCFunction)py_ue_get_all_child_actors, METH_VARARGS, "" }, { "attach_to_actor", (PyCFunction)py_ue_attach_to_actor, METH_VARARGS, "" }, { "attach_to_component", (PyCFunction)py_ue_attach_to_component, METH_VARARGS, "" }, // Skeletal { "get_anim_instance", (PyCFunction)py_ue_get_anim_instance, METH_VARARGS, "" }, { "set_skeletal_mesh", (PyCFunction)py_ue_set_skeletal_mesh, METH_VARARGS, "" }, { "skeleton_get_parent_index", (PyCFunction)py_ue_skeleton_get_parent_index, METH_VARARGS, "" }, { "skeleton_bones_get_num", (PyCFunction)py_ue_skeleton_bones_get_num, METH_VARARGS, "" }, { "skeleton_get_bone_name", (PyCFunction)py_ue_skeleton_get_bone_name, METH_VARARGS, "" }, { "skeleton_find_bone_index", (PyCFunction)py_ue_skeleton_find_bone_index, METH_VARARGS, "" }, { "skeleton_get_ref_bone_pose", (PyCFunction)py_ue_skeleton_get_ref_bone_pose, METH_VARARGS, "" }, #if ENGINE_MINOR_VERSION > 13 { "skeleton_add_bone", (PyCFunction)py_ue_skeleton_add_bone, METH_VARARGS, "" }, #endif #if WITH_EDITOR #if ENGINE_MINOR_VERSION > 12 { "skeletal_mesh_set_soft_vertices", (PyCFunction)py_ue_skeletal_mesh_set_soft_vertices, METH_VARARGS, "" }, { "skeletal_mesh_get_soft_vertices", (PyCFunction)py_ue_skeletal_mesh_get_soft_vertices, METH_VARARGS, "" }, #endif { "skeletal_mesh_get_lod", (PyCFunction)py_ue_skeletal_mesh_get_lod, METH_VARARGS, "" }, { "skeletal_mesh_get_raw_indices", (PyCFunction)py_ue_skeletal_mesh_get_raw_indices, METH_VARARGS, "" }, #endif { "skeletal_mesh_set_skeleton", (PyCFunction)py_ue_skeletal_mesh_set_skeleton, METH_VARARGS, "" }, #if WITH_EDITOR #if ENGINE_MINOR_VERSION > 12 { "skeletal_mesh_get_bone_map", (PyCFunction)py_ue_skeletal_mesh_get_bone_map, METH_VARARGS, "" }, { "skeletal_mesh_set_bone_map", (PyCFunction)py_ue_skeletal_mesh_set_bone_map, METH_VARARGS, "" }, #endif { "skeletal_mesh_set_active_bone_indices", (PyCFunction)py_ue_skeletal_mesh_set_active_bone_indices, METH_VARARGS, "" }, { "skeletal_mesh_set_required_bones", (PyCFunction)py_ue_skeletal_mesh_set_required_bones, METH_VARARGS, "" }, { "skeletal_mesh_get_active_bone_indices", (PyCFunction)py_ue_skeletal_mesh_get_active_bone_indices, METH_VARARGS, "" }, { "skeletal_mesh_get_required_bones", (PyCFunction)py_ue_skeletal_mesh_get_required_bones, METH_VARARGS, "" }, { "skeletal_mesh_lods_num", (PyCFunction)py_ue_skeletal_mesh_lods_num, METH_VARARGS, "" }, { "skeletal_mesh_sections_num", (PyCFunction)py_ue_skeletal_mesh_sections_num, METH_VARARGS, "" }, #pragma warning(suppress: 4191) { "skeletal_mesh_build_lod", (PyCFunction)py_ue_skeletal_mesh_build_lod, METH_VARARGS | METH_KEYWORDS, "" }, #endif #if WITH_EDITOR { "skeletal_mesh_register_morph_target", (PyCFunction)py_ue_skeletal_mesh_register_morph_target, METH_VARARGS, "" }, { "skeletal_mesh_to_import_vertex_map", (PyCFunction)py_ue_skeletal_mesh_to_import_vertex_map, METH_VARARGS, "" }, { "morph_target_populate_deltas", (PyCFunction)py_ue_morph_target_populate_deltas, METH_VARARGS, "" }, { "morph_target_get_deltas", (PyCFunction)py_ue_morph_target_get_deltas, METH_VARARGS, "" }, #endif // Timer { "set_timer", (PyCFunction)py_ue_set_timer, METH_VARARGS, "" }, // Texture { "texture_get_data", (PyCFunction)py_ue_texture_get_data, METH_VARARGS, "" }, { "texture_set_data", (PyCFunction)py_ue_texture_set_data, METH_VARARGS, "" }, { "texture_get_width", (PyCFunction)py_ue_texture_get_width, METH_VARARGS, "" }, { "texture_get_height", (PyCFunction)py_ue_texture_get_height, METH_VARARGS, "" }, { "texture_has_alpha_channel", (PyCFunction)py_ue_texture_has_alpha_channel, METH_VARARGS, "" }, { "render_target_get_data", (PyCFunction)py_ue_render_target_get_data, METH_VARARGS, "" }, { "render_target_get_data_to_buffer", (PyCFunction)py_ue_render_target_get_data_to_buffer, METH_VARARGS, "" }, { "texture_update_resource", (PyCFunction)py_ue_texture_update_resource, METH_VARARGS, "" }, #if WITH_EDITOR { "texture_get_source_data", (PyCFunction)py_ue_texture_get_source_data, METH_VARARGS, "" }, { "texture_set_source_data", (PyCFunction)py_ue_texture_set_source_data, METH_VARARGS, "" }, #endif // Sequencer { "sequencer_master_tracks", (PyCFunction)py_ue_sequencer_master_tracks, METH_VARARGS, "" }, { "sequencer_possessable_tracks", (PyCFunction)py_ue_sequencer_possessable_tracks, METH_VARARGS, "" }, { "sequencer_get_camera_cut_track", (PyCFunction)py_ue_sequencer_get_camera_cut_track, METH_VARARGS, "" }, #if WITH_EDITOR { "sequencer_set_playback_range", (PyCFunction)py_ue_sequencer_set_playback_range, METH_VARARGS, "" }, { "sequencer_set_view_range", (PyCFunction)py_ue_sequencer_set_view_range, METH_VARARGS, "" }, { "sequencer_set_working_range", (PyCFunction)py_ue_sequencer_set_working_range, METH_VARARGS, "" }, { "sequencer_set_section_range", (PyCFunction)py_ue_sequencer_set_section_range, METH_VARARGS, "" }, { "sequencer_get_playback_range", (PyCFunction)py_ue_sequencer_get_playback_range, METH_VARARGS, "" }, { "sequencer_get_selection_range", (PyCFunction)py_ue_sequencer_get_selection_range, METH_VARARGS, "" }, { "sequencer_folders", (PyCFunction)py_ue_sequencer_folders, METH_VARARGS, "" }, { "sequencer_create_folder", (PyCFunction)py_ue_sequencer_create_folder, METH_VARARGS, "" }, { "sequencer_set_display_name", (PyCFunction)py_ue_sequencer_set_display_name, METH_VARARGS, "" }, { "sequencer_get_display_name", (PyCFunction)py_ue_sequencer_get_display_name, METH_VARARGS, "" }, { "sequencer_changed", (PyCFunction)py_ue_sequencer_changed, METH_VARARGS, "" }, { "sequencer_add_camera_cut_track", (PyCFunction)py_ue_sequencer_add_camera_cut_track, METH_VARARGS, "" }, { "sequencer_add_actor", (PyCFunction)py_ue_sequencer_add_actor, METH_VARARGS, "" }, { "sequencer_add_actor_component", (PyCFunction)py_ue_sequencer_add_actor_component, METH_VARARGS, "" }, { "sequencer_make_new_spawnable", (PyCFunction)py_ue_sequencer_make_new_spawnable, METH_VARARGS, "" }, { "sequencer_add_possessable", (PyCFunction)py_ue_sequencer_add_possessable, METH_VARARGS, "" }, { "sequencer_track_add_section", (PyCFunction)py_ue_sequencer_track_add_section, METH_VARARGS, "" }, { "sequencer_section_add_key", (PyCFunction)py_ue_sequencer_section_add_key, METH_VARARGS, "" }, { "sequencer_remove_possessable", (PyCFunction)py_ue_sequencer_remove_possessable, METH_VARARGS, "" }, { "sequencer_remove_spawnable", (PyCFunction)py_ue_sequencer_remove_spawnable, METH_VARARGS, "" }, { "sequencer_remove_camera_cut_track", (PyCFunction)py_ue_sequencer_remove_camera_cut_track, METH_VARARGS, "" }, { "sequencer_remove_master_track", (PyCFunction)py_ue_sequencer_remove_master_track, METH_VARARGS, "" }, { "sequencer_remove_track", (PyCFunction)py_ue_sequencer_remove_track, METH_VARARGS, "" }, { "sequencer_import_fbx_transform", (PyCFunction)py_ue_sequencer_import_fbx_transform, METH_VARARGS, "" }, #endif { "sequencer_sections", (PyCFunction)py_ue_sequencer_sections, METH_VARARGS, "" }, { "sequencer_track_sections", (PyCFunction)py_ue_sequencer_track_sections, METH_VARARGS, "" }, { "sequencer_possessables", (PyCFunction)py_ue_sequencer_possessables, METH_VARARGS, "" }, { "sequencer_possessables_guid", (PyCFunction)py_ue_sequencer_possessables_guid, METH_VARARGS, "" }, { "sequencer_find_possessable", (PyCFunction)py_ue_sequencer_find_possessable, METH_VARARGS, "" }, { "sequencer_find_spawnable", (PyCFunction)py_ue_sequencer_find_spawnable, METH_VARARGS, "" }, { "sequencer_add_master_track", (PyCFunction)py_ue_sequencer_add_master_track, METH_VARARGS, "" }, { "sequencer_add_track", (PyCFunction)py_ue_sequencer_add_track, METH_VARARGS, "" }, // Material { "set_material", (PyCFunction)py_ue_set_material, METH_VARARGS, "" }, { "set_material_by_name", (PyCFunction)py_ue_set_material_by_name, METH_VARARGS, "" }, { "set_material_scalar_parameter", (PyCFunction)py_ue_set_material_scalar_parameter, METH_VARARGS, "" }, { "set_material_static_switch_parameter", (PyCFunction)py_ue_set_material_static_switch_parameter, METH_VARARGS, "" }, { "set_material_vector_parameter", (PyCFunction)py_ue_set_material_vector_parameter, METH_VARARGS, "" }, { "set_material_texture_parameter", (PyCFunction)py_ue_set_material_texture_parameter, METH_VARARGS, "" }, { "get_material_scalar_parameter", (PyCFunction)py_ue_get_material_scalar_parameter, METH_VARARGS, "" }, { "get_material_vector_parameter", (PyCFunction)py_ue_get_material_vector_parameter, METH_VARARGS, "" }, { "get_material_texture_parameter", (PyCFunction)py_ue_get_material_texture_parameter, METH_VARARGS, "" }, { "get_material_static_switch_parameter", (PyCFunction)py_ue_get_material_static_switch_parameter, METH_VARARGS, "" }, { "create_material_instance_dynamic", (PyCFunction)py_ue_create_material_instance_dynamic, METH_VARARGS, "" }, #if WITH_EDITOR { "set_material_parent", (PyCFunction)py_ue_set_material_parent, METH_VARARGS, "" }, { "static_mesh_set_collision_for_lod", (PyCFunction)py_ue_static_mesh_set_collision_for_lod, METH_VARARGS, "" }, { "static_mesh_set_shadow_for_lod", (PyCFunction)py_ue_static_mesh_set_shadow_for_lod, METH_VARARGS, "" }, { "get_raw_mesh", (PyCFunction)py_ue_static_mesh_get_raw_mesh, METH_VARARGS, "" }, { "static_mesh_generate_kdop10x", (PyCFunction)py_ue_static_mesh_generate_kdop10x, METH_VARARGS, "" }, { "static_mesh_generate_kdop10y", (PyCFunction)py_ue_static_mesh_generate_kdop10y, METH_VARARGS, "" }, { "static_mesh_generate_kdop10z", (PyCFunction)py_ue_static_mesh_generate_kdop10z, METH_VARARGS, "" }, { "static_mesh_generate_kdop18", (PyCFunction)py_ue_static_mesh_generate_kdop18, METH_VARARGS, "" }, { "static_mesh_generate_kdop26", (PyCFunction)py_ue_static_mesh_generate_kdop26, METH_VARARGS, "" }, { "static_mesh_import_lod", (PyCFunction)py_ue_static_mesh_import_lod, METH_VARARGS, "" }, #endif // Viewport { "add_viewport_widget_content", (PyCFunction)py_ue_add_viewport_widget_content, METH_VARARGS, "" }, { "remove_viewport_widget_content", (PyCFunction)py_ue_remove_viewport_widget_content, METH_VARARGS, "" }, { "remove_all_viewport_widgets", (PyCFunction)py_ue_remove_all_viewport_widgets, METH_VARARGS, "" }, #if PY_MAJOR_VERSION >= 3 { "add_function", (PyCFunction)py_ue_add_function, METH_VARARGS, "" }, #endif { "add_property", (PyCFunction)py_ue_add_property, METH_VARARGS, "" }, { "as_dict", (PyCFunction)py_ue_as_dict, METH_VARARGS, "" }, { "get_cdo", (PyCFunction)py_ue_get_cdo, METH_VARARGS, "" }, { "get_archetype", (PyCFunction)py_ue_get_archetype, METH_VARARGS, "" }, { "get_archetype_instances", (PyCFunction)py_ue_get_archetype_instances, METH_VARARGS, "" }, { "enum_values", (PyCFunction)py_ue_enum_values, METH_VARARGS, "" }, { "enum_names", (PyCFunction)py_ue_enum_names, METH_VARARGS, "" }, #if ENGINE_MINOR_VERSION >= 15 { "enum_user_defined_names", (PyCFunction)py_ue_enum_user_defined_names, METH_VARARGS, "" }, #endif // serialization { "to_bytes", (PyCFunction)py_ue_to_bytes, METH_VARARGS, "" }, { "to_bytearray", (PyCFunction)py_ue_to_bytearray, METH_VARARGS, "" }, { "from_bytes", (PyCFunction)py_ue_from_bytes, METH_VARARGS, "" }, { NULL } /* Sentinel */ }; // destructor static void ue_pyobject_dealloc(ue_PyUObject* self) { #if defined(UEPY_MEMORY_DEBUG) UE_LOG(LogPython, Warning, TEXT("Destroying ue_PyUObject %p mapped to UObject %p"), self, self->ue_object); #endif if (self->owned) { FUnrealEnginePythonHouseKeeper::Get()->UntrackUObject(self->ue_object); } if (self->auto_rooted && (self->ue_object && self->ue_object->IsValidLowLevel() && self->ue_object->IsRooted())) { self->ue_object->RemoveFromRoot(); } Py_XDECREF(self->py_dict); Py_TYPE(self)->tp_free((PyObject*)self); } static PyObject* ue_PyUObject_getattro(ue_PyUObject* self, PyObject* attr_name) { ue_py_check(self); PyObject* ret = PyObject_GenericGetAttr((PyObject*)self, attr_name); if (!ret) { if (PyUnicodeOrString_Check(attr_name)) { const char* attr = UEPyUnicode_AsUTF8(attr_name); // first check for property UStruct* u_struct = nullptr; if (self->ue_object->IsA<UStruct>()) { u_struct = (UStruct*)self->ue_object; } else { u_struct = (UStruct*)self->ue_object->GetClass(); } UProperty* u_property = u_struct->FindPropertyByName(FName(UTF8_TO_TCHAR(attr))); if (u_property) { // swallow previous exception PyErr_Clear(); return ue_py_convert_property(u_property, (uint8*)self->ue_object, 0); } UFunction* function = self->ue_object->FindFunction(FName(UTF8_TO_TCHAR(attr))); // retry wth K2_ prefix if (!function) { FString k2_name = FString("K2_") + UTF8_TO_TCHAR(attr); function = self->ue_object->FindFunction(FName(*k2_name)); } // is it a static class ? if (!function) { if (self->ue_object->IsA<UClass>()) { UClass* u_class = (UClass*)self->ue_object; UObject* cdo = u_class->GetDefaultObject(); if (cdo) { function = cdo->FindFunction(FName(UTF8_TO_TCHAR(attr))); // try _NEW ? if (!function) { FString name_new = UTF8_TO_TCHAR(attr) + FString("_NEW"); function = cdo->FindFunction(FName(*name_new)); } } } } // last hope, is it an enum ? if (!function) { #if ENGINE_MINOR_VERSION >= 15 if (self->ue_object->IsA<UUserDefinedEnum>()) { UUserDefinedEnum* u_enum = (UUserDefinedEnum*)self->ue_object; PyErr_Clear(); FString attr_as_string = FString(UTF8_TO_TCHAR(attr)); for (auto item : u_enum->DisplayNameMap) { if (item.Value.ToString() == attr_as_string) { #if ENGINE_MINOR_VERSION > 15 return PyLong_FromLong(u_enum->GetIndexByName(item.Key)); #else return PyLong_FromLong(u_enum->FindEnumIndex(item.Key)); #endif } } return PyErr_Format(PyExc_Exception, "unknown enum name \"%s\"", attr); } #endif if (self->ue_object->IsA<UEnum>()) { UEnum* u_enum = (UEnum*)self->ue_object; PyErr_Clear(); #if ENGINE_MINOR_VERSION > 15 int32 value = u_enum->GetIndexByName(FName(UTF8_TO_TCHAR(attr))); if (value == INDEX_NONE) return PyErr_Format(PyExc_Exception, "unknown enum name \"%s\"", attr); return PyLong_FromLong(value); #else int32 value = u_enum->FindEnumIndex(FName(UTF8_TO_TCHAR(attr))); if (value == INDEX_NONE) return PyErr_Format(PyExc_Exception, "unknown enum name \"%s\"", attr); return PyLong_FromLong(value); #endif } } if (function) { // swallow previous exception PyErr_Clear(); return py_ue_new_callable(function, self->ue_object); } } } return ret; } static int ue_PyUObject_setattro(ue_PyUObject* self, PyObject* attr_name, PyObject* value) { ue_py_check_int(self); // first of all check for UProperty if (PyUnicodeOrString_Check(attr_name)) { const char* attr = UEPyUnicode_AsUTF8(attr_name); // first check for property UStruct* u_struct = nullptr; if (self->ue_object->IsA<UStruct>()) { u_struct = (UStruct*)self->ue_object; } else { u_struct = (UStruct*)self->ue_object->GetClass(); } UProperty* u_property = u_struct->FindPropertyByName(FName(UTF8_TO_TCHAR(attr))); if (u_property) { #if WITH_EDITOR self->ue_object->PreEditChange(u_property); #endif if (ue_py_convert_pyobject(value, u_property, (uint8*)self->ue_object, 0)) { #if WITH_EDITOR FPropertyChangedEvent PropertyEvent(u_property, EPropertyChangeType::ValueSet); self->ue_object->PostEditChangeProperty(PropertyEvent); if (self->ue_object->HasAnyFlags(RF_ArchetypeObject | RF_ClassDefaultObject)) { TArray<UObject*> Instances; self->ue_object->GetArchetypeInstances(Instances); for (UObject* Instance : Instances) { Instance->PreEditChange(u_property); if (ue_py_convert_pyobject(value, u_property, (uint8*)Instance, 0)) { FPropertyChangedEvent InstancePropertyEvent(u_property, EPropertyChangeType::ValueSet); Instance->PostEditChangeProperty(InstancePropertyEvent); } else { PyErr_SetString(PyExc_ValueError, "invalid value for UProperty"); return -1; } } } #endif return 0; } PyErr_SetString(PyExc_ValueError, "invalid value for UProperty"); return -1; } // now check for function name if (self->ue_object->FindFunction(FName(UTF8_TO_TCHAR(attr)))) { PyErr_SetString(PyExc_ValueError, "you cannot overwrite a UFunction"); return -1; } } return PyObject_GenericSetAttr((PyObject*)self, attr_name, value); } static PyObject* ue_PyUObject_str(ue_PyUObject* self) { ue_py_check(self); #if PY_MAJOR_VERSION >= 3 return PyUnicode_FromFormat("<unreal_engine.UObject '%s' (%p) UClass '%s' (refcnt: %d)>", TCHAR_TO_UTF8(*self->ue_object->GetName()), self->ue_object, TCHAR_TO_UTF8(*self->ue_object->GetClass()->GetName()), self->ob_base.ob_refcnt); #else return PyUnicode_FromFormat("<unreal_engine.UObject '%s' (%p) UClass '%s'>", TCHAR_TO_UTF8(*self->ue_object->GetName()), self->ue_object, TCHAR_TO_UTF8(*self->ue_object->GetClass()->GetName())); #endif } static PyObject* ue_PyUObject_call(ue_PyUObject* self, PyObject* args, PyObject* kw) { ue_py_check(self); // if it is a class, create a new object if (self->ue_object->IsA<UClass>()) { UClass* u_class = (UClass*)self->ue_object; if (u_class->HasAnyClassFlags(CLASS_Abstract)) { return PyErr_Format(PyExc_Exception, "abstract classes cannot be instantiated"); } if (u_class->IsChildOf<AActor>()) { return PyErr_Format(PyExc_Exception, "you cannot use __call__ on actors, they have to be spawned"); } PyObject* py_name = nullptr; PyObject* py_outer = Py_None; if (!PyArg_ParseTuple(args, "|OO:new_object", &py_name, &py_outer)) { return NULL; } int num_args = py_name ? 3 : 1; PyObject* py_args = PyTuple_New(num_args); Py_INCREF((PyObject*)self); PyTuple_SetItem(py_args, 0, (PyObject*)self); if (py_name) { Py_INCREF(py_outer); PyTuple_SetItem(py_args, 1, py_outer); Py_INCREF(py_name); PyTuple_SetItem(py_args, 2, py_name); } ue_PyUObject* ret = (ue_PyUObject*)py_unreal_engine_new_object(nullptr, py_args); Py_DECREF(py_args); if (!ret) { return NULL; } // when new_object is called the reference counting is 2 and is registered in the GC // UObject crated explicitely from python, will be managed by python... FUnrealEnginePythonHouseKeeper::Get()->TrackUObject(ret->ue_object); return (PyObject*)ret; } // if it is a uscriptstruct, instantiate a new struct if (self->ue_object->IsA<UScriptStruct>()) { UScriptStruct* u_script_struct = (UScriptStruct*)self->ue_object; uint8* data = (uint8*)FMemory::Malloc(u_script_struct->GetStructureSize()); u_script_struct->InitializeStruct(data); #if WITH_EDITOR u_script_struct->InitializeDefaultValue(data); #endif if (kw) { PyObject* struct_keys = PyObject_GetIter(kw); for (;;) { PyObject* key = PyIter_Next(struct_keys); if (!key) { if (PyErr_Occurred()) { FMemory::Free(data); return PyErr_Format(PyExc_Exception, "unable to build struct from dictionary"); } break; } if (!PyUnicodeOrString_Check(key)) continue; const char* struct_key = UEPyUnicode_AsUTF8(key); PyObject* value = PyDict_GetItem(kw, key); if (!value) { if (PyErr_Occurred()) { FMemory::Free(data); return PyErr_Format(PyExc_Exception, "unable to build struct from dictionary"); } break; } UProperty* u_property = ue_struct_get_field_from_name(u_script_struct, (char*)struct_key); if (u_property) { if (!ue_py_convert_pyobject(value, u_property, data, 0)) { FMemory::Free(data); return PyErr_Format(PyExc_Exception, "invalid value for UProperty"); } } else { FMemory::Free(data); return PyErr_Format(PyExc_Exception, "UProperty %s not found", struct_key); } } } return py_ue_new_owned_uscriptstruct_zero_copy(u_script_struct, data); } return PyErr_Format(PyExc_Exception, "the specified uobject has no __call__ support"); } static PyTypeObject ue_PyUObjectType = { PyVarObject_HEAD_INIT(NULL, 0) "unreal_engine.UObject", /* tp_name */ sizeof(ue_PyUObject), /* tp_basicsize */ 0, /* tp_itemsize */ (destructor)ue_pyobject_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_reserved */ 0, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ (ternaryfunc)ue_PyUObject_call, /* tp_call */ (reprfunc)ue_PyUObject_str, /* tp_str */ (getattrofunc)ue_PyUObject_getattro, /* tp_getattro */ (setattrofunc)ue_PyUObject_setattro, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT, /* tp_flags */ "Unreal Engine UObject wrapper", /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ ue_PyUObject_methods, /* tp_methods */ }; UClass* unreal_engine_new_uclass(char* name, UClass* outer_parent) { bool is_overwriting = false; UObject* outer = GetTransientPackage(); UClass* parent = UObject::StaticClass(); if (outer_parent) { parent = outer_parent; outer = parent->GetOuter(); } UClass* new_object = FindObject<UClass>(ANY_PACKAGE, UTF8_TO_TCHAR(name)); if (!new_object) { new_object = NewObject<UPythonClass>(outer, UTF8_TO_TCHAR(name), RF_Public | RF_Transient | RF_MarkAsNative); if (!new_object) return nullptr; } else { UE_LOG(LogPython, Warning, TEXT("Preparing for overwriting class %s ..."), UTF8_TO_TCHAR(name)); is_overwriting = true; } if (is_overwriting && new_object->Children) { UField* u_field = new_object->Children; while (u_field) { if (u_field->IsA<UFunction>()) { UE_LOG(LogPython, Warning, TEXT("removing function %s"), *u_field->GetName()); new_object->RemoveFunctionFromFunctionMap((UFunction*)u_field); FLinkerLoad::InvalidateExport(u_field); } u_field = u_field->Next; } new_object->ClearFunctionMapsCaches(); new_object->PurgeClass(true); new_object->Children = nullptr; new_object->ClassAddReferencedObjects = parent->ClassAddReferencedObjects; } new_object->PropertiesSize = 0; new_object->ClassConstructor = parent->ClassConstructor; new_object->SetSuperStruct(parent); new_object->PropertyLink = parent->PropertyLink; new_object->ClassWithin = parent->ClassWithin; new_object->ClassConfigName = parent->ClassConfigName; new_object->ClassFlags |= (parent->ClassFlags & (CLASS_Inherit | CLASS_ScriptInherit)); new_object->ClassFlags |= CLASS_Native; #if WITH_EDITOR new_object->SetMetaData(FBlueprintMetadata::MD_AllowableBlueprintVariableType, TEXT("true")); if (new_object->IsChildOf<UActorComponent>()) { new_object->SetMetaData(FBlueprintMetadata::MD_BlueprintSpawnableComponent, TEXT("true")); } #endif new_object->ClassCastFlags = parent->ClassCastFlags; new_object->Bind(); new_object->StaticLink(true); // it could be a class update if (is_overwriting && new_object->ClassDefaultObject) { new_object->GetDefaultObject()->RemoveFromRoot(); new_object->GetDefaultObject()->ConditionalBeginDestroy(); new_object->ClassDefaultObject = nullptr; } #if WITH_EDITOR new_object->PostEditChange(); #endif new_object->GetDefaultObject()->PostInitProperties(); #if WITH_EDITOR new_object->PostLinkerChange(); #endif new_object->AssembleReferenceTokenStream(); #if WITH_EDITOR // this is required for avoiding startup crashes #405 if (GEditor) { FBlueprintActionDatabase::Get().RefreshClassActions(new_object); } #endif return new_object; } int unreal_engine_py_init(ue_PyUObject*, PyObject*, PyObject*); void unreal_engine_init_py_module() { #if PY_MAJOR_VERSION >= 3 PyObject * new_unreal_engine_module = PyImport_AddModule("unreal_engine"); #else PyObject* new_unreal_engine_module = Py_InitModule3("unreal_engine", NULL, unreal_engine_py_doc); #endif ue_PyUObjectType.tp_new = PyType_GenericNew; ue_PyUObjectType.tp_init = (initproc)unreal_engine_py_init; ue_PyUObjectType.tp_dictoffset = offsetof(ue_PyUObject, py_dict); if (PyType_Ready(&ue_PyUObjectType) < 0) return; Py_INCREF(&ue_PyUObjectType); PyModule_AddObject(new_unreal_engine_module, "UObject", (PyObject*)& ue_PyUObjectType); PyObject* unreal_engine_dict = PyModule_GetDict(new_unreal_engine_module); PyMethodDef* unreal_engine_function; for (unreal_engine_function = unreal_engine_methods; unreal_engine_function->ml_name != NULL; unreal_engine_function++) { PyObject* func = PyCFunction_New(unreal_engine_function, NULL); PyDict_SetItemString(unreal_engine_dict, unreal_engine_function->ml_name, func); Py_DECREF(func); } ue_python_init_fvector(new_unreal_engine_module); ue_python_init_fvector2d(new_unreal_engine_module); ue_python_init_frotator(new_unreal_engine_module); ue_python_init_ftransform(new_unreal_engine_module); ue_python_init_fhitresult(new_unreal_engine_module); ue_python_init_fcolor(new_unreal_engine_module); ue_python_init_flinearcolor(new_unreal_engine_module); ue_python_init_fquat(new_unreal_engine_module); #if ENGINE_MINOR_VERSION >= 20 ue_python_init_fframe_number(new_unreal_engine_module); #endif ue_python_init_frandomstream(new_unreal_engine_module); ue_python_init_fraw_anim_sequence_track(new_unreal_engine_module); #if WITH_EDITOR ue_python_init_fsoft_skin_vertex(new_unreal_engine_module); #endif ue_python_init_fmorph_target_delta(new_unreal_engine_module); ue_python_init_fobject_thumbnail(new_unreal_engine_module); ue_python_init_fviewport_client(new_unreal_engine_module); #if WITH_EDITOR ue_python_init_feditor_viewport_client(new_unreal_engine_module); ue_python_init_iasset_editor_instance(new_unreal_engine_module); #endif ue_python_init_fpython_output_device(new_unreal_engine_module); ue_python_init_ftimerhandle(new_unreal_engine_module); ue_python_init_fdelegatehandle(new_unreal_engine_module); ue_python_init_fsocket(new_unreal_engine_module); ue_python_init_callable(new_unreal_engine_module); ue_python_init_uscriptstruct(new_unreal_engine_module); ue_python_init_uclassesimporter(new_unreal_engine_module); ue_python_init_enumsimporter(new_unreal_engine_module); ue_python_init_ustructsimporter(new_unreal_engine_module); #if WITH_EDITOR ue_python_init_ffoliage_instance(new_unreal_engine_module); ue_python_init_fslowtask(new_unreal_engine_module); ue_python_init_swidget(new_unreal_engine_module); ue_python_init_farfilter(new_unreal_engine_module); ue_python_init_fassetdata(new_unreal_engine_module); ue_python_init_edgraphpin(new_unreal_engine_module); ue_python_init_fstring_asset_reference(new_unreal_engine_module); #if ENGINE_MINOR_VERSION > 12 ue_python_init_fbx(new_unreal_engine_module); #endif #if ENGINE_MINOR_VERSION > 13 ue_python_init_fraw_mesh(new_unreal_engine_module); #endif ue_python_init_iplugin(new_unreal_engine_module); #endif ue_python_init_slate(new_unreal_engine_module); ue_python_init_ihttp_base(new_unreal_engine_module); ue_python_init_ihttp_request(new_unreal_engine_module); ue_python_init_ihttp_response(new_unreal_engine_module); ue_python_init_iconsole_manager(new_unreal_engine_module); ue_python_init_fslate_application(new_unreal_engine_module); #if WITH_EDITOR ue_python_init_fmaterial_editor_utilities(new_unreal_engine_module); ue_python_init_icollection_manager(new_unreal_engine_module); #endif ue_python_init_ivoice_capture(new_unreal_engine_module); ue_py_register_magic_module((char*)"unreal_engine.classes", py_ue_new_uclassesimporter); ue_py_register_magic_module((char*)"unreal_engine.enums", py_ue_new_enumsimporter); ue_py_register_magic_module((char*)"unreal_engine.structs", py_ue_new_ustructsimporter); PyDict_SetItemString(unreal_engine_dict, "ENGINE_MAJOR_VERSION", PyLong_FromLong(ENGINE_MAJOR_VERSION)); PyDict_SetItemString(unreal_engine_dict, "ENGINE_MINOR_VERSION", PyLong_FromLong(ENGINE_MINOR_VERSION)); PyDict_SetItemString(unreal_engine_dict, "ENGINE_PATCH_VERSION", PyLong_FromLong(ENGINE_PATCH_VERSION)); // Collision channels PyDict_SetItemString(unreal_engine_dict, "COLLISION_CHANNEL_CAMERA", PyLong_FromLong(ECollisionChannel::ECC_Camera)); PyDict_SetItemString(unreal_engine_dict, "COLLISION_CHANNEL_DESTRUCTIBLE", PyLong_FromLong(ECollisionChannel::ECC_Destructible)); PyDict_SetItemString(unreal_engine_dict, "COLLISION_CHANNEL_PAWN", PyLong_FromLong(ECollisionChannel::ECC_Pawn)); PyDict_SetItemString(unreal_engine_dict, "COLLISION_CHANNEL_PHYSICS_BODY", PyLong_FromLong(ECollisionChannel::ECC_PhysicsBody)); PyDict_SetItemString(unreal_engine_dict, "COLLISION_CHANNEL_VEHICLE", PyLong_FromLong(ECollisionChannel::ECC_Vehicle)); PyDict_SetItemString(unreal_engine_dict, "COLLISION_CHANNEL_VISIBILITY", PyLong_FromLong(ECollisionChannel::ECC_Visibility)); PyDict_SetItemString(unreal_engine_dict, "COLLISION_CHANNEL_WORLD_DYNAMIC", PyLong_FromLong(ECollisionChannel::ECC_WorldDynamic)); PyDict_SetItemString(unreal_engine_dict, "COLLISION_CHANNEL_WORLD_STATIC", PyLong_FromLong(ECollisionChannel::ECC_WorldStatic)); // Attachments PyDict_SetItemString(unreal_engine_dict, "ATTACHMENT_RULE_KEEP_RELATIVE", PyLong_FromLong((int)EAttachmentRule::KeepRelative)); PyDict_SetItemString(unreal_engine_dict, "ATTACHMENT_RULE_KEEP_WORLD", PyLong_FromLong((int)EAttachmentRule::KeepWorld)); PyDict_SetItemString(unreal_engine_dict, "ATTACHMENT_RULE_SNAP_TO_TARGET", PyLong_FromLong((int)EAttachmentRule::SnapToTarget)); // Input PyDict_SetItemString(unreal_engine_dict, "IE_AXIS", PyLong_FromLong(EInputEvent::IE_Axis)); PyDict_SetItemString(unreal_engine_dict, "IE_DOUBLE_CLICK", PyLong_FromLong(EInputEvent::IE_DoubleClick)); PyDict_SetItemString(unreal_engine_dict, "IE_PRESSED", PyLong_FromLong(EInputEvent::IE_Pressed)); PyDict_SetItemString(unreal_engine_dict, "IE_RELEASED", PyLong_FromLong(EInputEvent::IE_Released)); PyDict_SetItemString(unreal_engine_dict, "IE_REPEAT", PyLong_FromLong(EInputEvent::IE_Repeat)); // Classes PyDict_SetItemString(unreal_engine_dict, "CLASS_CONFIG", PyLong_FromUnsignedLongLong((uint64)CLASS_Config)); PyDict_SetItemString(unreal_engine_dict, "CLASS_DEFAULT_CONFIG", PyLong_FromUnsignedLongLong((uint64)CLASS_DefaultConfig)); PyDict_SetItemString(unreal_engine_dict, "CLASS_ABSTRACT", PyLong_FromUnsignedLongLong((uint64)CLASS_Abstract)); PyDict_SetItemString(unreal_engine_dict, "CLASS_INTERFACE", PyLong_FromUnsignedLongLong((uint64)CLASS_Interface)); // Objects PyDict_SetItemString(unreal_engine_dict, "RF_NOFLAGS", PyLong_FromUnsignedLongLong((uint64)RF_NoFlags)); PyDict_SetItemString(unreal_engine_dict, "RF_PUBLIC", PyLong_FromUnsignedLongLong((uint64)RF_Public)); PyDict_SetItemString(unreal_engine_dict, "RF_STANDALONE", PyLong_FromUnsignedLongLong((uint64)RF_Standalone)); PyDict_SetItemString(unreal_engine_dict, "RF_MARKASNATIVE", PyLong_FromUnsignedLongLong((uint64)RF_MarkAsNative)); PyDict_SetItemString(unreal_engine_dict, "RF_TRANSACTIONAL", PyLong_FromUnsignedLongLong((uint64)RF_Transactional)); PyDict_SetItemString(unreal_engine_dict, "RF_CLASSDEFAULTOBJECT", PyLong_FromUnsignedLongLong((uint64)RF_ClassDefaultObject)); PyDict_SetItemString(unreal_engine_dict, "RF_CLASS_DEFAULT_OBJECT", PyLong_FromUnsignedLongLong((uint64)RF_ClassDefaultObject)); PyDict_SetItemString(unreal_engine_dict, "RF_ARCHETYPEOBJECT", PyLong_FromUnsignedLongLong((uint64)RF_ArchetypeObject)); PyDict_SetItemString(unreal_engine_dict, "RF_ARCHETYPE_OBJECT", PyLong_FromUnsignedLongLong((uint64)RF_ArchetypeObject)); PyDict_SetItemString(unreal_engine_dict, "RF_TRANSIENT", PyLong_FromUnsignedLongLong((uint64)RF_Transient)); PyDict_SetItemString(unreal_engine_dict, "RF_MARKASROOTSET", PyLong_FromUnsignedLongLong((uint64)RF_MarkAsRootSet)); PyDict_SetItemString(unreal_engine_dict, "RF_TAGGARBAGETEMP", PyLong_FromUnsignedLongLong((uint64)RF_TagGarbageTemp)); PyDict_SetItemString(unreal_engine_dict, "RF_NEEDINITIALIZATION", PyLong_FromUnsignedLongLong((uint64)RF_NeedInitialization)); PyDict_SetItemString(unreal_engine_dict, "RF_NEEDLOAD", PyLong_FromUnsignedLongLong((uint64)RF_NeedLoad)); PyDict_SetItemString(unreal_engine_dict, "RF_KEEPFORCOOKER", PyLong_FromUnsignedLongLong((uint64)RF_KeepForCooker)); PyDict_SetItemString(unreal_engine_dict, "RF_NEEDPOSTLOAD", PyLong_FromUnsignedLongLong((uint64)RF_NeedPostLoad)); PyDict_SetItemString(unreal_engine_dict, "RF_NEEDPOSTLOADSUBOBJECTS", PyLong_FromUnsignedLongLong((uint64)RF_NeedPostLoadSubobjects)); PyDict_SetItemString(unreal_engine_dict, "RF_NEWERVERSIONEXISTS", PyLong_FromUnsignedLongLong((uint64)RF_NewerVersionExists)); PyDict_SetItemString(unreal_engine_dict, "RF_BEGINDESTROYED", PyLong_FromUnsignedLongLong((uint64)RF_BeginDestroyed)); PyDict_SetItemString(unreal_engine_dict, "RF_FINISHDESTROYED", PyLong_FromUnsignedLongLong((uint64)RF_FinishDestroyed)); PyDict_SetItemString(unreal_engine_dict, "RF_BEINGREGENERATED", PyLong_FromUnsignedLongLong((uint64)RF_BeingRegenerated)); PyDict_SetItemString(unreal_engine_dict, "RF_DEFAULTSUBOBJECT", PyLong_FromUnsignedLongLong((uint64)RF_DefaultSubObject)); PyDict_SetItemString(unreal_engine_dict, "RF_WASLOADED", PyLong_FromUnsignedLongLong((uint64)RF_WasLoaded)); PyDict_SetItemString(unreal_engine_dict, "RF_TEXTEXPORTTRANSIENT", PyLong_FromUnsignedLongLong((uint64)RF_TextExportTransient)); PyDict_SetItemString(unreal_engine_dict, "RF_LOADCOMPLETED", PyLong_FromUnsignedLongLong((uint64)RF_LoadCompleted)); PyDict_SetItemString(unreal_engine_dict, "RF_INHERITABLECOMPONENTTEMPLATE", PyLong_FromUnsignedLongLong((uint64)RF_InheritableComponentTemplate)); PyDict_SetItemString(unreal_engine_dict, "RF_DUPLICATETRANSIENT", PyLong_FromUnsignedLongLong((uint64)RF_DuplicateTransient)); PyDict_SetItemString(unreal_engine_dict, "RF_STRONGREFONFRAME", PyLong_FromUnsignedLongLong((uint64)RF_StrongRefOnFrame)); PyDict_SetItemString(unreal_engine_dict, "RF_NONPIEDUPLICATETRANSIENT", PyLong_FromUnsignedLongLong((uint64)RF_NonPIEDuplicateTransient)); PyDict_SetItemString(unreal_engine_dict, "RF_DYNAMIC", PyLong_FromUnsignedLongLong((uint64)RF_Dynamic)); #if ENGINE_MINOR_VERSION > 15 PyDict_SetItemString(unreal_engine_dict, "RF_WILLBELOADED", PyLong_FromUnsignedLongLong((uint64)RF_WillBeLoaded)); #endif // Properties PyDict_SetItemString(unreal_engine_dict, "CPF_CONFIG", PyLong_FromUnsignedLongLong((uint64)CPF_Config)); PyDict_SetItemString(unreal_engine_dict, "CPF_GLOBAL_CONFIG", PyLong_FromUnsignedLongLong((uint64)CPF_GlobalConfig)); PyDict_SetItemString(unreal_engine_dict, "CPF_EXPOSE_ON_SPAWN", PyLong_FromUnsignedLongLong((uint64)CPF_ExposeOnSpawn)); PyDict_SetItemString(unreal_engine_dict, "CPF_NET", PyLong_FromUnsignedLongLong((uint64)CPF_Net)); PyDict_SetItemString(unreal_engine_dict, "CPF_REP_NOTIFY", PyLong_FromUnsignedLongLong((uint64)CPF_RepNotify)); #if WITH_EDITOR PyDict_SetItemString(unreal_engine_dict, "APP_MSG_TYPE_OK", PyLong_FromLong(EAppMsgType::Ok)); PyDict_SetItemString(unreal_engine_dict, "APP_MSG_TYPE_YES_NO", PyLong_FromLong(EAppMsgType::YesNo)); PyDict_SetItemString(unreal_engine_dict, "APP_MSG_TYPE_OK_CANCEL", PyLong_FromLong(EAppMsgType::OkCancel)); PyDict_SetItemString(unreal_engine_dict, "APP_MSG_TYPE_YES_NO_CANCEL", PyLong_FromLong(EAppMsgType::YesNoCancel)); PyDict_SetItemString(unreal_engine_dict, "APP_MSG_TYPE_CANCEL_RETRY_CONTINUE", PyLong_FromLong(EAppMsgType::CancelRetryContinue)); PyDict_SetItemString(unreal_engine_dict, "APP_MSG_TYPE_YES_NO_YES_ALL_NO_ALL", PyLong_FromLong(EAppMsgType::YesNoYesAllNoAll)); PyDict_SetItemString(unreal_engine_dict, "APP_MSG_TYPE_YES_NO_YES_ALL_NO_ALL_CANCEL", PyLong_FromLong(EAppMsgType::YesNoYesAllNoAllCancel)); PyDict_SetItemString(unreal_engine_dict, "APP_MSG_TYPE_YES_NO_YES_ALL", PyLong_FromLong(EAppMsgType::YesNoYesAll)); PyDict_SetItemString(unreal_engine_dict, "APP_RETURN_TYPE_OK", PyLong_FromLong(EAppReturnType::Ok)); PyDict_SetItemString(unreal_engine_dict, "APP_RETURN_TYPE_YES", PyLong_FromLong(EAppReturnType::Yes)); PyDict_SetItemString(unreal_engine_dict, "APP_RETURN_TYPE_YES_ALL", PyLong_FromLong(EAppReturnType::YesAll)); PyDict_SetItemString(unreal_engine_dict, "APP_RETURN_TYPE_NO_ALL", PyLong_FromLong(EAppReturnType::NoAll)); PyDict_SetItemString(unreal_engine_dict, "APP_RETURN_TYPE_NO", PyLong_FromLong(EAppReturnType::No)); PyDict_SetItemString(unreal_engine_dict, "APP_RETURN_TYPE_RETRY", PyLong_FromLong(EAppReturnType::Retry)); PyDict_SetItemString(unreal_engine_dict, "APP_RETURN_TYPE_CONTINUE", PyLong_FromLong(EAppReturnType::Continue)); PyDict_SetItemString(unreal_engine_dict, "APP_RETURN_TYPE_CANCEL", PyLong_FromLong(EAppReturnType::Cancel)); #endif } // utility functions ue_PyUObject* ue_get_python_uobject(UObject* ue_obj) { if (!ue_obj) return nullptr; ue_PyUObject* ret = FUnrealEnginePythonHouseKeeper::Get()->GetPyUObject(ue_obj); if (!ret) { if (!ue_obj->IsValidLowLevel() || ue_obj->IsPendingKillOrUnreachable()) return nullptr; ue_PyUObject* ue_py_object = (ue_PyUObject*)PyObject_New(ue_PyUObject, &ue_PyUObjectType); if (!ue_py_object) { return nullptr; } ue_py_object->ue_object = ue_obj; ue_py_object->py_proxy = nullptr; ue_py_object->auto_rooted = 0; ue_py_object->py_dict = PyDict_New(); ue_py_object->owned = 0; FUnrealEnginePythonHouseKeeper::Get()->RegisterPyUObject(ue_obj, ue_py_object); #if defined(UEPY_MEMORY_DEBUG) UE_LOG(LogPython, Warning, TEXT("CREATED UPyObject at %p for %p %s"), ue_py_object, ue_obj, *ue_obj->GetName()); #endif return ue_py_object; } return ret; } ue_PyUObject* ue_get_python_uobject_inc(UObject* ue_obj) { ue_PyUObject* ret = ue_get_python_uobject(ue_obj); if (ret) { Py_INCREF(ret); } return ret; } void unreal_engine_py_log_error() { PyObject* type = NULL; PyObject* value = NULL; PyObject* traceback = NULL; PyErr_Fetch(&type, &value, &traceback); PyErr_NormalizeException(&type, &value, &traceback); if (!value) { PyErr_Clear(); return; } char* msg = NULL; #if PY_MAJOR_VERSION >= 3 PyObject * zero = PyUnicode_AsUTF8String(PyObject_Str(value)); if (zero) { msg = PyBytes_AsString(zero); } #else msg = PyString_AsString(PyObject_Str(value)); #endif if (!msg) { PyErr_Clear(); return; } UE_LOG(LogPython, Error, TEXT("%s"), UTF8_TO_TCHAR(msg)); // taken from uWSGI ;) if (!traceback) { PyErr_Clear(); return; } PyObject* traceback_module = PyImport_ImportModule("traceback"); if (!traceback_module) { PyErr_Clear(); return; } PyObject* traceback_dict = PyModule_GetDict(traceback_module); PyObject* format_exception = PyDict_GetItemString(traceback_dict, "format_exception"); if (format_exception) { PyObject* ret = PyObject_CallFunctionObjArgs(format_exception, type, value, traceback, NULL); if (!ret) { PyErr_Clear(); return; } if (PyList_Check(ret)) { for (int i = 0; i < PyList_Size(ret); i++) { PyObject* item = PyList_GetItem(ret, i); if (item) { UE_LOG(LogPython, Error, TEXT("%s"), UTF8_TO_TCHAR(UEPyUnicode_AsUTF8(PyObject_Str(item)))); } } } else { UE_LOG(LogPython, Error, TEXT("%s"), UTF8_TO_TCHAR(UEPyUnicode_AsUTF8(PyObject_Str(ret)))); } } PyErr_Clear(); } // retrieve a UWorld from a generic UObject (if possible) UWorld* ue_get_uworld(ue_PyUObject* py_obj) { if (py_obj->ue_object->IsA<UWorld>()) { return (UWorld*)py_obj->ue_object; } if (py_obj->ue_object->IsA<AActor>()) { AActor* actor = (AActor*)py_obj->ue_object; return actor->GetWorld(); } if (py_obj->ue_object->IsA<UActorComponent>()) { UActorComponent* component = (UActorComponent*)py_obj->ue_object; return component->GetWorld(); } return nullptr; } // retrieve actor from component (if possible) AActor* ue_get_actor(ue_PyUObject* py_obj) { if (py_obj->ue_object->IsA<AActor>()) { return (AActor*)py_obj->ue_object; } if (py_obj->ue_object->IsA<UActorComponent>()) { UActorComponent* tmp_component = (UActorComponent*)py_obj->ue_object; return tmp_component->GetOwner(); } return nullptr; } // convert a property to a python object PyObject* ue_py_convert_property(UProperty* prop, uint8* buffer, int32 index) { if (auto casted_prop = Cast<UBoolProperty>(prop)) { bool value = casted_prop->GetPropertyValue_InContainer(buffer, index); if (value) { Py_RETURN_TRUE; } Py_RETURN_FALSE; } if (auto casted_prop = Cast<UIntProperty>(prop)) { int value = casted_prop->GetPropertyValue_InContainer(buffer, index); return PyLong_FromLong(value); } if (auto casted_prop = Cast<UUInt32Property>(prop)) { uint32 value = casted_prop->GetPropertyValue_InContainer(buffer, index); return PyLong_FromUnsignedLong(value); } if (auto casted_prop = Cast<UInt64Property>(prop)) { long long value = casted_prop->GetPropertyValue_InContainer(buffer, index); return PyLong_FromLongLong(value); } if (auto casted_prop = Cast<UUInt64Property>(prop)) { uint64 value = casted_prop->GetPropertyValue_InContainer(buffer, index); return PyLong_FromUnsignedLongLong(value); } if (auto casted_prop = Cast<UFloatProperty>(prop)) { float value = casted_prop->GetPropertyValue_InContainer(buffer, index); return PyFloat_FromDouble(value); } if (auto casted_prop = Cast<UByteProperty>(prop)) { uint8 value = casted_prop->GetPropertyValue_InContainer(buffer, index); return PyLong_FromUnsignedLong(value); } #if ENGINE_MINOR_VERSION >= 15 if (auto casted_prop = Cast<UEnumProperty>(prop)) { void* prop_addr = casted_prop->ContainerPtrToValuePtr<void>(buffer, index); uint64 enum_index = casted_prop->GetUnderlyingProperty()->GetUnsignedIntPropertyValue(prop_addr); return PyLong_FromUnsignedLong(enum_index); } #endif if (auto casted_prop = Cast<UStrProperty>(prop)) { FString value = casted_prop->GetPropertyValue_InContainer(buffer, index); return PyUnicode_FromString(TCHAR_TO_UTF8(*value)); } if (auto casted_prop = Cast<UTextProperty>(prop)) { FText value = casted_prop->GetPropertyValue_InContainer(buffer, index); return PyUnicode_FromString(TCHAR_TO_UTF8(*value.ToString())); } if (auto casted_prop = Cast<UNameProperty>(prop)) { FName value = casted_prop->GetPropertyValue_InContainer(buffer, index); return PyUnicode_FromString(TCHAR_TO_UTF8(*value.ToString())); } if (auto casted_prop = Cast<UObjectPropertyBase>(prop)) { auto value = casted_prop->GetObjectPropertyValue_InContainer(buffer, index); if (value) { Py_RETURN_UOBJECT(value); } Py_RETURN_NONE; } if (auto casted_prop = Cast<UClassProperty>(prop)) { auto value = casted_prop->GetPropertyValue_InContainer(buffer, index); if (value) { Py_RETURN_UOBJECT(value); } return PyErr_Format(PyExc_Exception, "invalid UClass type for %s", TCHAR_TO_UTF8(*casted_prop->GetName())); } // try to manage known struct first if (auto casted_prop = Cast<UStructProperty>(prop)) { if (auto casted_struct = Cast<UScriptStruct>(casted_prop->Struct)) { if (casted_struct == TBaseStructure<FVector>::Get()) { FVector vec = *casted_prop->ContainerPtrToValuePtr<FVector>(buffer, index); return py_ue_new_fvector(vec); } if (casted_struct == TBaseStructure<FVector2D>::Get()) { FVector2D vec = *casted_prop->ContainerPtrToValuePtr<FVector2D>(buffer, index); return py_ue_new_fvector2d(vec); } if (casted_struct == TBaseStructure<FRotator>::Get()) { FRotator rot = *casted_prop->ContainerPtrToValuePtr<FRotator>(buffer, index); return py_ue_new_frotator(rot); } if (casted_struct == TBaseStructure<FTransform>::Get()) { FTransform transform = *casted_prop->ContainerPtrToValuePtr<FTransform>(buffer, index); return py_ue_new_ftransform(transform); } if (casted_struct == FHitResult::StaticStruct()) { FHitResult hit = *casted_prop->ContainerPtrToValuePtr<FHitResult>(buffer, index); return py_ue_new_fhitresult(hit); } if (casted_struct == TBaseStructure<FColor>::Get()) { FColor color = *casted_prop->ContainerPtrToValuePtr<FColor>(buffer, index); return py_ue_new_fcolor(color); } if (casted_struct == TBaseStructure<FLinearColor>::Get()) { FLinearColor color = *casted_prop->ContainerPtrToValuePtr<FLinearColor>(buffer, index); return py_ue_new_flinearcolor(color); } return py_ue_new_uscriptstruct(casted_struct, casted_prop->ContainerPtrToValuePtr<uint8>(buffer, index)); } return PyErr_Format(PyExc_TypeError, "unsupported UStruct type"); } if (auto casted_prop = Cast<UWeakObjectProperty>(prop)) { auto value = casted_prop->GetPropertyValue_InContainer(buffer, index); UObject* strong_obj = value.Get(); if (strong_obj) { Py_RETURN_UOBJECT(strong_obj); } // nullptr Py_RETURN_NONE; } if (auto casted_prop = Cast<UMulticastDelegateProperty>(prop)) { Py_RETURN_UOBJECT(casted_prop); } if (auto casted_prop = Cast<UDelegateProperty>(prop)) { Py_RETURN_UOBJECT(casted_prop); } if (auto casted_prop = Cast<UArrayProperty>(prop)) { FScriptArrayHelper_InContainer array_helper(casted_prop, buffer, index); UProperty* array_prop = casted_prop->Inner; // check for TArray<uint8>, so we can use bytearray optimization if (auto uint8_tarray = Cast<UByteProperty>(array_prop)) { uint8* buf = array_helper.GetRawPtr(); return PyByteArray_FromStringAndSize((char*)buf, array_helper.Num()); } PyObject* py_list = PyList_New(0); for (int i = 0; i < array_helper.Num(); i++) { PyObject* item = ue_py_convert_property(array_prop, array_helper.GetRawPtr(i), 0); if (!item) { Py_DECREF(py_list); return NULL; } PyList_Append(py_list, item); Py_DECREF(item); } return py_list; } #if ENGINE_MINOR_VERSION >= 15 if (auto casted_prop = Cast<UMapProperty>(prop)) { FScriptMapHelper_InContainer map_helper(casted_prop, buffer, index); PyObject* py_dict = PyDict_New(); for (int32 i = 0; i < map_helper.Num(); i++) { if (map_helper.IsValidIndex(i)) { uint8* ptr = map_helper.GetPairPtr(i); PyObject* py_key = ue_py_convert_property(map_helper.KeyProp, ptr, 0); if (!py_key) { Py_DECREF(py_dict); return NULL; } PyObject* py_value = ue_py_convert_property(map_helper.ValueProp, ptr, 0); if (!py_value) { Py_DECREF(py_dict); return NULL; } PyDict_SetItem(py_dict, py_key, py_value); Py_DECREF(py_key); Py_DECREF(py_value); } } return py_dict; } #endif return PyErr_Format(PyExc_Exception, "unsupported value type %s for property %s", TCHAR_TO_UTF8(*prop->GetClass()->GetName()), TCHAR_TO_UTF8(*prop->GetName())); } // convert a python object to a property bool ue_py_convert_pyobject(PyObject* py_obj, UProperty* prop, uint8* buffer, int32 index) { if (PyBool_Check(py_obj)) { auto casted_prop = Cast<UBoolProperty>(prop); if (!casted_prop) return false; if (PyObject_IsTrue(py_obj)) { casted_prop->SetPropertyValue_InContainer(buffer, true, index); } else { casted_prop->SetPropertyValue_InContainer(buffer, false, index); } return true; } if (PyNumber_Check(py_obj)) { if (auto casted_prop = Cast<UIntProperty>(prop)) { PyObject* py_long = PyNumber_Long(py_obj); casted_prop->SetPropertyValue_InContainer(buffer, PyLong_AsLong(py_long), index); Py_DECREF(py_long); return true; } if (auto casted_prop = Cast<UUInt32Property>(prop)) { PyObject* py_long = PyNumber_Long(py_obj); casted_prop->SetPropertyValue_InContainer(buffer, PyLong_AsUnsignedLong(py_long), index); Py_DECREF(py_long); return true; } if (auto casted_prop = Cast<UInt64Property>(prop)) { PyObject* py_long = PyNumber_Long(py_obj); casted_prop->SetPropertyValue_InContainer(buffer, PyLong_AsLongLong(py_long), index); Py_DECREF(py_long); return true; } if (auto casted_prop = Cast<UUInt64Property>(prop)) { PyObject* py_long = PyNumber_Long(py_obj); casted_prop->SetPropertyValue_InContainer(buffer, PyLong_AsUnsignedLongLong(py_long), index); Py_DECREF(py_long); return true; } if (auto casted_prop = Cast<UFloatProperty>(prop)) { PyObject* py_float = PyNumber_Float(py_obj); casted_prop->SetPropertyValue_InContainer(buffer, PyFloat_AsDouble(py_float), index); Py_DECREF(py_float); return true; } if (auto casted_prop = Cast<UByteProperty>(prop)) { PyObject* py_long = PyNumber_Long(py_obj); casted_prop->SetPropertyValue_InContainer(buffer, PyLong_AsUnsignedLong(py_long), index); Py_DECREF(py_long); return true; } #if ENGINE_MINOR_VERSION >= 15 if (auto casted_prop = Cast<UEnumProperty>(prop)) { PyObject* py_long = PyNumber_Long(py_obj); void* prop_addr = casted_prop->ContainerPtrToValuePtr<void>(buffer, index); casted_prop->GetUnderlyingProperty()->SetIntPropertyValue(prop_addr, (uint64)PyLong_AsUnsignedLong(py_long)); Py_DECREF(py_long); return true; } #endif return false; } if (PyUnicodeOrString_Check(py_obj)) { if (auto casted_prop = Cast<UStrProperty>(prop)) { casted_prop->SetPropertyValue_InContainer(buffer, UTF8_TO_TCHAR(UEPyUnicode_AsUTF8(py_obj)), index); return true; } if (auto casted_prop = Cast<UNameProperty>(prop)) { casted_prop->SetPropertyValue_InContainer(buffer, UTF8_TO_TCHAR(UEPyUnicode_AsUTF8(py_obj)), index); return true; } if (auto casted_prop = Cast<UTextProperty>(prop)) { casted_prop->SetPropertyValue_InContainer(buffer, FText::FromString(UTF8_TO_TCHAR(UEPyUnicode_AsUTF8(py_obj))), index); return true; } return false; } if (PyBytes_Check(py_obj)) { if (auto casted_prop = Cast<UArrayProperty>(prop)) { FScriptArrayHelper_InContainer helper(casted_prop, buffer, index); if (auto item_casted_prop = Cast<UByteProperty>(casted_prop->Inner)) { Py_ssize_t pybytes_len = PyBytes_Size(py_obj); uint8* buf = (uint8*)PyBytes_AsString(py_obj); // fix array helper size if (helper.Num() < pybytes_len) { helper.AddValues(pybytes_len - helper.Num()); } else if (helper.Num() > pybytes_len) { helper.RemoveValues(pybytes_len, helper.Num() - pybytes_len); } FMemory::Memcpy(helper.GetRawPtr(), buf, pybytes_len); return true; } } return false; } if (PyByteArray_Check(py_obj)) { if (auto casted_prop = Cast<UArrayProperty>(prop)) { FScriptArrayHelper_InContainer helper(casted_prop, buffer, index); if (auto item_casted_prop = Cast<UByteProperty>(casted_prop->Inner)) { Py_ssize_t pybytes_len = PyByteArray_Size(py_obj); uint8* buf = (uint8*)PyByteArray_AsString(py_obj); // fix array helper size if (helper.Num() < pybytes_len) { helper.AddValues(pybytes_len - helper.Num()); } else if (helper.Num() > pybytes_len) { helper.RemoveValues(pybytes_len, helper.Num() - pybytes_len); } FMemory::Memcpy(helper.GetRawPtr(), buf, pybytes_len); return true; } } return false; } if (PyList_Check(py_obj)) { if (auto casted_prop = Cast<UArrayProperty>(prop)) { FScriptArrayHelper_InContainer helper(casted_prop, buffer, index); UProperty* array_prop = casted_prop->Inner; Py_ssize_t pylist_len = PyList_Size(py_obj); // fix array helper size if (helper.Num() < pylist_len) { helper.AddValues(pylist_len - helper.Num()); } else if (helper.Num() > pylist_len) { helper.RemoveValues(pylist_len, helper.Num() - pylist_len); } for (int i = 0; i < (int)pylist_len; i++) { PyObject* py_item = PyList_GetItem(py_obj, i); if (!ue_py_convert_pyobject(py_item, array_prop, helper.GetRawPtr(i), 0)) { return false; } } return true; } return false; } if (PyTuple_Check(py_obj)) { if (auto casted_prop = Cast<UArrayProperty>(prop)) { FScriptArrayHelper_InContainer helper(casted_prop, buffer, index); UProperty* array_prop = casted_prop->Inner; Py_ssize_t pytuple_len = PyTuple_Size(py_obj); // fix array helper size if (helper.Num() < pytuple_len) { helper.AddValues(pytuple_len - helper.Num()); } else if (helper.Num() > pytuple_len) { helper.RemoveValues(pytuple_len, helper.Num() - pytuple_len); } for (int i = 0; i < (int)pytuple_len; i++) { PyObject* py_item = PyTuple_GetItem(py_obj, i); if (!ue_py_convert_pyobject(py_item, array_prop, helper.GetRawPtr(i), 0)) { return false; } } return true; } return false; } #if ENGINE_MINOR_VERSION >= 15 if (PyDict_Check(py_obj)) { if (auto casted_prop = Cast<UMapProperty>(prop)) { FScriptMapHelper_InContainer map_helper(casted_prop, buffer, index); PyObject* py_key = nullptr; PyObject* py_value = nullptr; Py_ssize_t pos = 0; map_helper.EmptyValues(); while (PyDict_Next(py_obj, &pos, &py_key, &py_value)) { int32 hindex = map_helper.AddDefaultValue_Invalid_NeedsRehash(); uint8* ptr = map_helper.GetPairPtr(hindex); if (!ue_py_convert_pyobject(py_key, casted_prop->KeyProp, ptr, 0)) { return false; } if (!ue_py_convert_pyobject(py_value, casted_prop->ValueProp, ptr, 0)) { return false; } } map_helper.Rehash(); return true; } return false; } #endif // structs if (ue_PyFVector * py_vec = py_ue_is_fvector(py_obj)) { if (auto casted_prop = Cast<UStructProperty>(prop)) { if (casted_prop->Struct == TBaseStructure<FVector>::Get()) { *casted_prop->ContainerPtrToValuePtr<FVector>(buffer, index) = py_vec->vec; return true; } } return false; } if (ue_PyFVector2D * py_vec = py_ue_is_fvector2d(py_obj)) { if (auto casted_prop = Cast<UStructProperty>(prop)) { if (casted_prop->Struct == TBaseStructure<FVector2D>::Get()) { *casted_prop->ContainerPtrToValuePtr<FVector2D>(buffer, index) = py_vec->vec; return true; } } return false; } if (ue_PyFRotator * py_rot = py_ue_is_frotator(py_obj)) { if (auto casted_prop = Cast<UStructProperty>(prop)) { if (casted_prop->Struct == TBaseStructure<FRotator>::Get()) { *casted_prop->ContainerPtrToValuePtr<FRotator>(buffer, index) = py_rot->rot; return true; } } return false; } if (ue_PyFTransform * py_transform = py_ue_is_ftransform(py_obj)) { if (auto casted_prop = Cast<UStructProperty>(prop)) { if (casted_prop->Struct == TBaseStructure<FTransform>::Get()) { *casted_prop->ContainerPtrToValuePtr<FTransform>(buffer, index) = py_transform->transform; return true; } } return false; } if (ue_PyFColor * py_color = py_ue_is_fcolor(py_obj)) { if (auto casted_prop = Cast<UStructProperty>(prop)) { if (casted_prop->Struct == TBaseStructure<FColor>::Get()) { *casted_prop->ContainerPtrToValuePtr<FColor>(buffer, index) = py_color->color; return true; } } return false; } if (ue_PyFLinearColor * py_color = py_ue_is_flinearcolor(py_obj)) { if (auto casted_prop = Cast<UStructProperty>(prop)) { if (casted_prop->Struct == TBaseStructure<FLinearColor>::Get()) { *casted_prop->ContainerPtrToValuePtr<FLinearColor>(buffer, index) = py_color->color; return true; } } return false; } if (ue_PyFHitResult * py_hit = py_ue_is_fhitresult(py_obj)) { if (auto casted_prop = Cast<UStructProperty>(prop)) { if (casted_prop->Struct == FHitResult::StaticStruct()) { *casted_prop->ContainerPtrToValuePtr<FHitResult>(buffer, index) = py_hit->hit; return true; } } return false; } // generic structs if (py_ue_is_uscriptstruct(py_obj)) { ue_PyUScriptStruct* py_u_struct = (ue_PyUScriptStruct*)py_obj; if (auto casted_prop = Cast<UStructProperty>(prop)) { if (casted_prop->Struct == py_u_struct->u_struct) { uint8* dest = casted_prop->ContainerPtrToValuePtr<uint8>(buffer, index); py_u_struct->u_struct->InitializeStruct(dest); py_u_struct->u_struct->CopyScriptStruct(dest, py_u_struct->u_struct_ptr); return true; } } return false; } if (PyObject_IsInstance(py_obj, (PyObject*)& ue_PyUObjectType)) { ue_PyUObject* ue_obj = (ue_PyUObject*)py_obj; if (ue_obj->ue_object->IsA<UClass>()) { if (auto casted_prop = Cast<UClassProperty>(prop)) { casted_prop->SetPropertyValue_InContainer(buffer, ue_obj->ue_object, index); return true; } else if (auto casted_prop_soft_class = Cast<USoftClassProperty>(prop)) { casted_prop_soft_class->SetPropertyValue_InContainer(buffer, FSoftObjectPtr(ue_obj->ue_object), index); return true; } else if (auto casted_prop_soft_object = Cast<USoftObjectProperty>(prop)) { casted_prop_soft_object->SetPropertyValue_InContainer(buffer, FSoftObjectPtr(ue_obj->ue_object), index); return true; } else if (auto casted_prop_weak_object = Cast<UWeakObjectProperty>(prop)) { casted_prop_weak_object->SetPropertyValue_InContainer(buffer, FWeakObjectPtr(ue_obj->ue_object), index); return true; } else if (auto casted_prop_base = Cast<UObjectPropertyBase>(prop)) { // ensure the object type is correct, otherwise crash could happen (soon or later) if (!ue_obj->ue_object->IsA(casted_prop_base->PropertyClass)) return false; casted_prop_base->SetObjectPropertyValue_InContainer(buffer, ue_obj->ue_object, index); return true; } return false; } if (ue_obj->ue_object->IsA<UObject>()) { if (auto casted_prop = Cast<UObjectPropertyBase>(prop)) { // if the property specifies an interface, the object must be of a class that implements it if (casted_prop->PropertyClass->HasAnyClassFlags(CLASS_Interface)) { if (!ue_obj->ue_object->GetClass()->ImplementsInterface(casted_prop->PropertyClass)) return false; } else { // ensure the object type is correct, otherwise crash could happen (soon or later) if (!ue_obj->ue_object->IsA(casted_prop->PropertyClass)) return false; } casted_prop->SetObjectPropertyValue_InContainer(buffer, ue_obj->ue_object, index); return true; } else if (auto casted_prop_soft_object = Cast<USoftObjectProperty>(prop)) { if (!ue_obj->ue_object->IsA(casted_prop_soft_object->PropertyClass)) return false; casted_prop_soft_object->SetPropertyValue_InContainer(buffer, FSoftObjectPtr(ue_obj->ue_object), index); return true; } else if (auto casted_prop_interface = Cast<UInterfaceProperty>(prop)) { // ensure the object type is correct, otherwise crash could happen (soon or later) if (!ue_obj->ue_object->GetClass()->ImplementsInterface(casted_prop_interface->InterfaceClass)) return false; casted_prop_interface->SetPropertyValue_InContainer(buffer, FScriptInterface(ue_obj->ue_object), index); return true; } } return false; } if (py_obj == Py_None) { auto casted_prop_class = Cast<UClassProperty>(prop); if (casted_prop_class) { casted_prop_class->SetPropertyValue_InContainer(buffer, nullptr, index); return true; } auto casted_prop = Cast<UObjectPropertyBase>(prop); if (casted_prop) { casted_prop->SetObjectPropertyValue_InContainer(buffer, nullptr, index); return true; } return false; } return false; } // check if a python object is a wrapper to a UObject ue_PyUObject* ue_is_pyuobject(PyObject* obj) { if (!PyObject_IsInstance(obj, (PyObject*)& ue_PyUObjectType)) return nullptr; return (ue_PyUObject*)obj; } void ue_bind_events_for_py_class_by_attribute(UObject* u_obj, PyObject* py_class) { // attempt to register events PyObject* attrs = PyObject_Dir(py_class); if (!attrs) return; AActor* actor = Cast<AActor>(u_obj); if (!actor) { UActorComponent* component = Cast<UActorComponent>(u_obj); if (!component) return; actor = component->GetOwner(); } Py_ssize_t len = PyList_Size(attrs); for (Py_ssize_t i = 0; i < len; i++) { PyObject* py_attr_name = PyList_GetItem(attrs, i); if (!py_attr_name || !PyUnicodeOrString_Check(py_attr_name)) continue; PyObject* item = PyObject_GetAttrString(py_class, UEPyUnicode_AsUTF8(py_attr_name)); if (item && PyCallable_Check(item)) { // check for ue_event signature PyObject* event_signature = PyObject_GetAttrString(item, (char*)"ue_event"); if (event_signature) { if (PyUnicodeOrString_Check(event_signature)) { FString event_name = FString(UTF8_TO_TCHAR(UEPyUnicode_AsUTF8(event_signature))); TArray<FString> parts; int n = event_name.ParseIntoArray(parts, UTF8_TO_TCHAR(".")); if (n < 1 || n > 2) { PyErr_SetString(PyExc_Exception, "invalid ue_event syntax, must be the name of an event or ComponentName.Event"); unreal_engine_py_log_error(); } else { if (n == 1) { if (!ue_bind_pyevent(ue_get_python_uobject(actor), parts[0], item, true)) { unreal_engine_py_log_error(); } } else { bool found = false; for (UActorComponent* component : actor->GetComponents()) { if (component->GetFName() == FName(*parts[0])) { if (!ue_bind_pyevent(ue_get_python_uobject(component), parts[1], item, true)) { unreal_engine_py_log_error(); } found = true; break; } } if (!found) { PyErr_SetString(PyExc_Exception, "unable to find component by name"); unreal_engine_py_log_error(); } } } } else { PyErr_SetString(PyExc_Exception, "ue_event attribute must be a string"); unreal_engine_py_log_error(); } } Py_XDECREF(event_signature); } Py_XDECREF(item); } Py_DECREF(attrs); PyErr_Clear(); } // automatically bind events based on class methods names void ue_autobind_events_for_pyclass(ue_PyUObject* u_obj, PyObject* py_class) { PyObject* attrs = PyObject_Dir(py_class); if (!attrs) return; Py_ssize_t len = PyList_Size(attrs); for (Py_ssize_t i = 0; i < len; i++) { PyObject* py_attr_name = PyList_GetItem(attrs, i); if (!py_attr_name || !PyUnicodeOrString_Check(py_attr_name)) continue; FString attr_name = UTF8_TO_TCHAR(UEPyUnicode_AsUTF8(py_attr_name)); if (!attr_name.StartsWith("on_", ESearchCase::CaseSensitive)) continue; // check if the attr is a callable PyObject* item = PyObject_GetAttrString(py_class, TCHAR_TO_UTF8(*attr_name)); if (item && PyCallable_Check(item)) { TArray<FString> parts; if (attr_name.ParseIntoArray(parts, UTF8_TO_TCHAR("_")) > 1) { FString event_name; for (FString part : parts) { FString first_letter = part.Left(1).ToUpper(); part.RemoveAt(0); event_name = event_name.Append(first_letter); event_name = event_name.Append(part); } // do not fail on wrong properties ue_bind_pyevent(u_obj, event_name, item, false); } } Py_XDECREF(item); } Py_DECREF(attrs); } static void py_ue_destroy_params(UFunction* u_function, uint8* buffer) { // destroy params TFieldIterator<UProperty> DArgs(u_function); for (; DArgs && (DArgs->PropertyFlags & CPF_Parm); ++DArgs) { UProperty* prop = *DArgs; prop->DestroyValue_InContainer(buffer); } } PyObject* py_ue_ufunction_call(UFunction* u_function, UObject* u_obj, PyObject* args, int argn, PyObject* kwargs) { // check for __super call if (kwargs) { PyObject* is_super_call = PyDict_GetItemString(kwargs, (char*)"__super"); if (is_super_call) { if (!u_function->GetSuperFunction()) { return PyErr_Format(PyExc_Exception, "UFunction has no SuperFunction"); } u_function = u_function->GetSuperFunction(); } } //NOTE: u_function->PropertiesSize maps to local variable uproperties + ufunction paramaters uproperties uint8* buffer = (uint8*)FMemory_Alloca(u_function->ParmsSize); FMemory::Memzero(buffer, u_function->ParmsSize); // initialize args for (TFieldIterator<UProperty> IArgs(u_function); IArgs && IArgs->HasAnyPropertyFlags(CPF_Parm); ++IArgs) { UProperty* prop = *IArgs; if (!prop->HasAnyPropertyFlags(CPF_ZeroConstructor)) { prop->InitializeValue_InContainer(buffer); } //UObject::CallFunctionByNameWithArguments() only does this part on non return value params if ((IArgs->PropertyFlags & (CPF_Parm | CPF_ReturnParm)) == CPF_Parm) { if (!prop->IsInContainer(u_function->ParmsSize)) { return PyErr_Format(PyExc_Exception, "Attempting to import func param property that's out of bounds. %s", TCHAR_TO_UTF8(*u_function->GetName())); } #if WITH_EDITOR FString default_key = FString("CPP_Default_") + prop->GetName(); FString default_key_value = u_function->GetMetaData(FName(*default_key)); if (!default_key_value.IsEmpty()) { #if ENGINE_MINOR_VERSION >= 17 prop->ImportText(*default_key_value, prop->ContainerPtrToValuePtr<uint8>(buffer), PPF_None, NULL); #else prop->ImportText(*default_key_value, prop->ContainerPtrToValuePtr<uint8>(buffer), PPF_Localized, NULL); #endif } #endif } } Py_ssize_t tuple_len = PyTuple_Size(args); int has_out_params = 0; TFieldIterator<UProperty> PArgs(u_function); for (; PArgs && ((PArgs->PropertyFlags & (CPF_Parm | CPF_ReturnParm)) == CPF_Parm); ++PArgs) { UProperty* prop = *PArgs; if (argn < tuple_len) { PyObject* py_arg = PyTuple_GetItem(args, argn); if (!py_arg) { py_ue_destroy_params(u_function, buffer); return PyErr_Format(PyExc_TypeError, "unable to get pyobject for property %s", TCHAR_TO_UTF8(*prop->GetName())); } if (!ue_py_convert_pyobject(py_arg, prop, buffer, 0)) { py_ue_destroy_params(u_function, buffer); return PyErr_Format(PyExc_TypeError, "unable to convert pyobject to property %s (%s)", TCHAR_TO_UTF8(*prop->GetName()), TCHAR_TO_UTF8(*prop->GetClass()->GetName())); } } else if (kwargs) { char* prop_name = TCHAR_TO_UTF8(*prop->GetName()); PyObject* dict_value = PyDict_GetItemString(kwargs, prop_name); if (dict_value) { if (!ue_py_convert_pyobject(dict_value, prop, buffer, 0)) { py_ue_destroy_params(u_function, buffer); return PyErr_Format(PyExc_TypeError, "unable to convert pyobject to property %s (%s)", TCHAR_TO_UTF8(*prop->GetName()), TCHAR_TO_UTF8(*prop->GetClass()->GetName())); } } } if (prop->HasAnyPropertyFlags(CPF_OutParm) && (prop->IsA<UArrayProperty>() || prop->HasAnyPropertyFlags(CPF_ConstParm) == false)) { has_out_params++; } argn++; } FScopeCycleCounterUObject ObjectScope(u_obj); FScopeCycleCounterUObject FunctionScope(u_function); Py_BEGIN_ALLOW_THREADS; u_obj->ProcessEvent(u_function, buffer); Py_END_ALLOW_THREADS; PyObject* ret = nullptr; int has_ret_param = 0; TFieldIterator<UProperty> Props(u_function); for (; Props; ++Props) { UProperty* prop = *Props; if (prop->GetPropertyFlags() & CPF_ReturnParm) { ret = ue_py_convert_property(prop, buffer, 0); if (!ret) { // destroy params py_ue_destroy_params(u_function, buffer); return NULL; } has_ret_param = 1; break; } } if (has_out_params > 0) { PyObject* multi_ret = PyTuple_New(has_out_params + has_ret_param); if (ret) { PyTuple_SetItem(multi_ret, 0, ret); } TFieldIterator<UProperty> OProps(u_function); for (; OProps; ++OProps) { UProperty* prop = *OProps; if (prop->HasAnyPropertyFlags(CPF_OutParm) && (prop->IsA<UArrayProperty>() || prop->HasAnyPropertyFlags(CPF_ConstParm) == false)) { // skip return param as it must be always the first if (prop->GetPropertyFlags() & CPF_ReturnParm) continue; PyObject* py_out = ue_py_convert_property(prop, buffer, 0); if (!py_out) { Py_DECREF(multi_ret); // destroy params py_ue_destroy_params(u_function, buffer); return NULL; } PyTuple_SetItem(multi_ret, has_ret_param, py_out); has_ret_param++; } } // destroy params py_ue_destroy_params(u_function, buffer); return multi_ret; } // destroy params py_ue_destroy_params(u_function, buffer); if (ret) return ret; Py_RETURN_NONE; } PyObject* ue_unbind_pyevent(ue_PyUObject* u_obj, FString event_name, PyObject* py_callable, bool fail_on_wrong_property) { UProperty* u_property = u_obj->ue_object->GetClass()->FindPropertyByName(FName(*event_name)); if (!u_property) { if (fail_on_wrong_property) return PyErr_Format(PyExc_Exception, "unable to find event property %s", TCHAR_TO_UTF8(*event_name)); Py_RETURN_NONE; } if (auto casted_prop = Cast<UMulticastDelegateProperty>(u_property)) { UPythonDelegate* py_delegate = FUnrealEnginePythonHouseKeeper::Get()->FindDelegate(u_obj->ue_object, py_callable); if (py_delegate != nullptr) { #if ENGINE_MINOR_VERSION < 23 FMulticastScriptDelegate multiscript_delegate = casted_prop->GetPropertyValue_InContainer(u_obj->ue_object); #else FMulticastScriptDelegate multiscript_delegate = *casted_prop->GetMulticastDelegate(u_obj->ue_object); #endif multiscript_delegate.Remove(py_delegate, FName("PyFakeCallable")); // re-assign multicast delegate #if ENGINE_MINOR_VERSION < 23 casted_prop->SetPropertyValue_InContainer(u_obj->ue_object, multiscript_delegate); #else casted_prop->SetMulticastDelegate(u_obj->ue_object, multiscript_delegate); #endif } } else if (auto casted_prop_delegate = Cast<UDelegateProperty>(u_property)) { FScriptDelegate script_delegate = casted_prop_delegate->GetPropertyValue_InContainer(u_obj->ue_object); script_delegate.Unbind(); // re-assign multicast delegate casted_prop_delegate->SetPropertyValue_InContainer(u_obj->ue_object, script_delegate); } else { if (fail_on_wrong_property) return PyErr_Format(PyExc_Exception, "property %s is not an event", TCHAR_TO_UTF8(*event_name)); } Py_RETURN_NONE; } PyObject* ue_bind_pyevent(ue_PyUObject* u_obj, FString event_name, PyObject* py_callable, bool fail_on_wrong_property) { UProperty* u_property = u_obj->ue_object->GetClass()->FindPropertyByName(FName(*event_name)); if (!u_property) { if (fail_on_wrong_property) return PyErr_Format(PyExc_Exception, "unable to find event property %s", TCHAR_TO_UTF8(*event_name)); Py_RETURN_NONE; } if (auto casted_prop = Cast<UMulticastDelegateProperty>(u_property)) { #if ENGINE_MINOR_VERSION < 23 FMulticastScriptDelegate multiscript_delegate = casted_prop->GetPropertyValue_InContainer(u_obj->ue_object); #else FMulticastScriptDelegate multiscript_delegate = *casted_prop->GetMulticastDelegate(u_obj->ue_object); #endif FScriptDelegate script_delegate; UPythonDelegate* py_delegate = FUnrealEnginePythonHouseKeeper::Get()->NewDelegate(u_obj->ue_object, py_callable, casted_prop->SignatureFunction); // fake UFUNCTION for bypassing checks script_delegate.BindUFunction(py_delegate, FName("PyFakeCallable")); // add the new delegate multiscript_delegate.Add(script_delegate); // re-assign multicast delegate #if ENGINE_MINOR_VERSION < 23 casted_prop->SetPropertyValue_InContainer(u_obj->ue_object, multiscript_delegate); #else casted_prop->SetMulticastDelegate(u_obj->ue_object, multiscript_delegate); #endif } else if (auto casted_prop_delegate = Cast<UDelegateProperty>(u_property)) { FScriptDelegate script_delegate = casted_prop_delegate->GetPropertyValue_InContainer(u_obj->ue_object); UPythonDelegate* py_delegate = FUnrealEnginePythonHouseKeeper::Get()->NewDelegate(u_obj->ue_object, py_callable, casted_prop_delegate->SignatureFunction); // fake UFUNCTION for bypassing checks script_delegate.BindUFunction(py_delegate, FName("PyFakeCallable")); // re-assign multicast delegate casted_prop_delegate->SetPropertyValue_InContainer(u_obj->ue_object, script_delegate); } else { if (fail_on_wrong_property) return PyErr_Format(PyExc_Exception, "property %s is not an event", TCHAR_TO_UTF8(*event_name)); } Py_RETURN_NONE; } UFunction* unreal_engine_add_function(UClass* u_class, char* name, PyObject* py_callable, uint32 function_flags) { UFunction* parent_function = u_class->GetSuperClass()->FindFunctionByName(UTF8_TO_TCHAR(name)); // if the function is not available in the parent // check for name collision if (!parent_function) { if (u_class->FindFunctionByName(UTF8_TO_TCHAR(name))) { UE_LOG(LogPython, Error, TEXT("function %s is already registered"), UTF8_TO_TCHAR(name)); return nullptr; } } UPythonFunction* function = NewObject<UPythonFunction>(u_class, UTF8_TO_TCHAR(name), RF_Public | RF_Transient | RF_MarkAsNative); function->SetPyCallable(py_callable); #if ENGINE_MINOR_VERSION < 18 function->RepOffset = MAX_uint16; #endif function->ReturnValueOffset = MAX_uint16; function->FirstPropertyToInit = NULL; function->Script.Add(EX_EndFunctionParms); if (parent_function) { function->SetSuperStruct(parent_function); function_flags |= (parent_function->FunctionFlags & FUNC_FuncInherit); } // iterate all arguments using inspect.signature() // this is required to maintaining args order PyObject* inspect = PyImport_ImportModule("inspect"); if (!inspect) { return NULL; } PyObject* signature = PyObject_CallMethod(inspect, (char*)"signature", (char*)"O", py_callable); if (!signature) { return NULL; } PyObject* parameters = PyObject_GetAttrString(signature, "parameters"); if (!parameters) { return NULL; } PyObject* annotations = PyObject_GetAttrString(py_callable, "__annotations__"); UField** next_property = &function->Children; UProperty** next_property_link = &function->PropertyLink; PyObject* parameters_keys = PyObject_GetIter(parameters); // do not process args if no annotations are available while (annotations) { PyObject* key = PyIter_Next(parameters_keys); if (!key) { if (PyErr_Occurred()) return NULL; break; } if (!PyUnicodeOrString_Check(key)) continue; const char* p_name = UEPyUnicode_AsUTF8(key); PyObject* value = PyDict_GetItem(annotations, key); if (!value) continue; UProperty* prop = nullptr; if (PyType_Check(value)) { if ((PyTypeObject*)value == &PyFloat_Type) { prop = NewObject<UFloatProperty>(function, UTF8_TO_TCHAR(p_name), RF_Public); } else if ((PyTypeObject*)value == &PyUnicode_Type) { prop = NewObject<UStrProperty>(function, UTF8_TO_TCHAR(p_name), RF_Public); } else if ((PyTypeObject*)value == &PyBool_Type) { prop = NewObject<UBoolProperty>(function, UTF8_TO_TCHAR(p_name), RF_Public); } else if ((PyTypeObject*)value == &PyLong_Type) { prop = NewObject<UIntProperty>(function, UTF8_TO_TCHAR(p_name), RF_Public); } else if ((PyTypeObject*)value == &ue_PyFVectorType) { UStructProperty* prop_struct = NewObject<UStructProperty>(function, UTF8_TO_TCHAR(p_name), RF_Public); prop_struct->Struct = TBaseStructure<FVector>::Get(); prop = prop_struct; } else if ((PyTypeObject*)value == &ue_PyFVector2DType) { UStructProperty* prop_struct = NewObject<UStructProperty>(function, UTF8_TO_TCHAR(p_name), RF_Public); prop_struct->Struct = TBaseStructure<FVector2D>::Get(); prop = prop_struct; } else if ((PyTypeObject*)value == &ue_PyFRotatorType) { UStructProperty* prop_struct = NewObject<UStructProperty>(function, UTF8_TO_TCHAR(p_name), RF_Public); prop_struct->Struct = TBaseStructure<FRotator>::Get(); prop = prop_struct; } else if ((PyTypeObject*)value == &ue_PyFLinearColorType) { UStructProperty* prop_struct = NewObject<UStructProperty>(function, UTF8_TO_TCHAR(p_name), RF_Public); prop_struct->Struct = TBaseStructure<FLinearColor>::Get(); prop = prop_struct; } else if ((PyTypeObject*)value == &ue_PyFColorType) { UStructProperty* prop_struct = NewObject<UStructProperty>(function, UTF8_TO_TCHAR(p_name), RF_Public); prop_struct->Struct = TBaseStructure<FColor>::Get(); prop = prop_struct; } else if ((PyTypeObject*)value == &ue_PyFTransformType) { UStructProperty* prop_struct = NewObject<UStructProperty>(function, UTF8_TO_TCHAR(p_name), RF_Public); prop_struct->Struct = TBaseStructure<FTransform>::Get(); prop = prop_struct; } #if ENGINE_MINOR_VERSION > 18 else if ((PyTypeObject*)value == &ue_PyFQuatType) { UStructProperty* prop_struct = NewObject<UStructProperty>(function, UTF8_TO_TCHAR(p_name), RF_Public); prop_struct->Struct = TBaseStructure<FQuat>::Get(); prop = prop_struct; } #endif else if (PyObject_IsInstance(value, (PyObject*)& PyType_Type)) { // Method annotation like foo:typing.Type[Pawn] produces annotations like typing.Type[Pawn], with .__args__ = (Pawn,) PyObject* type_args = PyObject_GetAttrString(value, "__args__"); if (!type_args) { UE_LOG(LogPython, Error, TEXT("missing type info on %s"), UTF8_TO_TCHAR(name)); return nullptr; } if (PyTuple_Size(type_args) != 1) { Py_DECREF(type_args); UE_LOG(LogPython, Error, TEXT("exactly one class is allowed in type info for %s"), UTF8_TO_TCHAR(name)); return nullptr; } PyObject* py_class = PyTuple_GetItem(type_args, 0); ue_PyUObject* py_obj = ue_is_pyuobject(py_class); if (!py_obj) { Py_DECREF(type_args); UE_LOG(LogPython, Error, TEXT("type for %s must be a ue_PyUObject"), UTF8_TO_TCHAR(name)); return nullptr; } if (!py_obj->ue_object->IsA<UClass>()) { Py_DECREF(type_args); UE_LOG(LogPython, Error, TEXT("type for %s must be a UClass"), UTF8_TO_TCHAR(name)); return nullptr; } UClassProperty* prop_class = NewObject<UClassProperty>(function, UTF8_TO_TCHAR(p_name), RF_Public); prop_class->SetMetaClass((UClass*)py_obj->ue_object); prop_class->PropertyClass = UClass::StaticClass(); prop = prop_class; Py_DECREF(type_args); } } else if (ue_PyUObject * py_obj = ue_is_pyuobject(value)) { if (py_obj->ue_object->IsA<UClass>()) { UClass* p_u_class = (UClass*)py_obj->ue_object; UObjectProperty* prop_base = NewObject<UObjectProperty>(function, UTF8_TO_TCHAR(p_name), RF_Public); prop_base->SetPropertyClass(p_u_class); prop = prop_base; } #if ENGINE_MINOR_VERSION > 17 else if (py_obj->ue_object->IsA<UEnum>()) { UEnumProperty* prop_enum = NewObject<UEnumProperty>(function, UTF8_TO_TCHAR(p_name), RF_Public); UNumericProperty* prop_underlying = NewObject<UByteProperty>(prop_enum, TEXT("UnderlyingType"), RF_Public); prop_enum->SetEnum((UEnum*)py_obj->ue_object); prop_enum->AddCppProperty(prop_underlying); prop = prop_enum; } #endif else if (py_obj->ue_object->IsA<UStruct>()) { UStructProperty* prop_struct = NewObject<UStructProperty>(function, UTF8_TO_TCHAR(p_name), RF_Public); prop_struct->Struct = (UScriptStruct*)py_obj->ue_object; prop = prop_struct; } } if (prop) { prop->SetPropertyFlags(CPF_Parm); *next_property = prop; next_property = &prop->Next; *next_property_link = prop; next_property_link = &prop->PropertyLinkNext; UE_LOG(LogPython, Warning, TEXT("added prop %s"), UTF8_TO_TCHAR(p_name)); } else { UE_LOG(LogPython, Warning, TEXT("Unable to map argument %s to function %s"), UTF8_TO_TCHAR(p_name), UTF8_TO_TCHAR(name)); } } // check for return value if (annotations) { PyObject* py_return_value = PyDict_GetItemString(annotations, "return"); if (py_return_value) { UE_LOG(LogPython, Warning, TEXT("Return Value found")); UProperty* prop = nullptr; char* p_name = (char*) "ReturnValue"; if (PyType_Check(py_return_value)) { if ((PyTypeObject*)py_return_value == &PyFloat_Type) { prop = NewObject<UFloatProperty>(function, UTF8_TO_TCHAR(p_name), RF_Public); } else if ((PyTypeObject*)py_return_value == &PyUnicode_Type) { prop = NewObject<UStrProperty>(function, UTF8_TO_TCHAR(p_name), RF_Public); } else if ((PyTypeObject*)py_return_value == &PyBool_Type) { prop = NewObject<UBoolProperty>(function, UTF8_TO_TCHAR(p_name), RF_Public); } else if ((PyTypeObject*)py_return_value == &PyLong_Type) { prop = NewObject<UIntProperty>(function, UTF8_TO_TCHAR(p_name), RF_Public); } else if ((PyTypeObject*)py_return_value == &ue_PyFVectorType) { UStructProperty* prop_struct = NewObject<UStructProperty>(function, UTF8_TO_TCHAR(p_name), RF_Public); prop_struct->Struct = TBaseStructure<FVector>::Get(); prop = prop_struct; } else if ((PyTypeObject*)py_return_value == &ue_PyFVector2DType) { UStructProperty* prop_struct = NewObject<UStructProperty>(function, UTF8_TO_TCHAR(p_name), RF_Public); prop_struct->Struct = TBaseStructure<FVector2D>::Get(); prop = prop_struct; } else if ((PyTypeObject*)py_return_value == &ue_PyFRotatorType) { UStructProperty* prop_struct = NewObject<UStructProperty>(function, UTF8_TO_TCHAR(p_name), RF_Public); prop_struct->Struct = TBaseStructure<FRotator>::Get(); prop = prop_struct; } else if ((PyTypeObject*)py_return_value == &ue_PyFLinearColorType) { UStructProperty* prop_struct = NewObject<UStructProperty>(function, UTF8_TO_TCHAR(p_name), RF_Public); prop_struct->Struct = TBaseStructure<FLinearColor>::Get(); prop = prop_struct; } else if ((PyTypeObject*)py_return_value == &ue_PyFColorType) { UStructProperty* prop_struct = NewObject<UStructProperty>(function, UTF8_TO_TCHAR(p_name), RF_Public); prop_struct->Struct = TBaseStructure<FColor>::Get(); prop = prop_struct; } else if ((PyTypeObject*)py_return_value == &ue_PyFTransformType) { UStructProperty* prop_struct = NewObject<UStructProperty>(function, UTF8_TO_TCHAR(p_name), RF_Public); prop_struct->Struct = TBaseStructure<FTransform>::Get(); prop = prop_struct; } #if ENGINE_MINOR_VERSION > 18 else if ((PyTypeObject*)py_return_value == &ue_PyFQuatType) { UStructProperty* prop_struct = NewObject<UStructProperty>(function, UTF8_TO_TCHAR(p_name), RF_Public); prop_struct->Struct = TBaseStructure<FQuat>::Get(); prop = prop_struct; } #endif else if (PyObject_IsInstance(py_return_value, (PyObject*)& PyType_Type)) { // Method annotation like foo:typing.Type[Pawn] produces annotations like typing.Type[Pawn], with .__args__ = (Pawn,) PyObject* type_args = PyObject_GetAttrString(py_return_value, "__args__"); if (!type_args) { UE_LOG(LogPython, Error, TEXT("missing type info on %s"), UTF8_TO_TCHAR(name)); return nullptr; } if (PyTuple_Size(type_args) != 1) { Py_DECREF(type_args); UE_LOG(LogPython, Error, TEXT("exactly one class is allowed in type info for %s"), UTF8_TO_TCHAR(name)); return nullptr; } PyObject* py_class = PyTuple_GetItem(type_args, 0); ue_PyUObject* py_obj = ue_is_pyuobject(py_class); if (!py_obj) { Py_DECREF(type_args); UE_LOG(LogPython, Error, TEXT("type for %s must be a ue_PyUObject"), UTF8_TO_TCHAR(name)); return nullptr; } if (!py_obj->ue_object->IsA<UClass>()) { Py_DECREF(type_args); UE_LOG(LogPython, Error, TEXT("type for %s must be a UClass"), UTF8_TO_TCHAR(name)); return nullptr; } UClassProperty* prop_class = NewObject<UClassProperty>(function, UTF8_TO_TCHAR(p_name), RF_Public); prop_class->SetMetaClass((UClass*)py_obj->ue_object); prop_class->PropertyClass = UClass::StaticClass(); prop = prop_class; Py_DECREF(type_args); } } else if (ue_PyUObject * py_obj = ue_is_pyuobject(py_return_value)) { if (py_obj->ue_object->IsA<UClass>()) { UClass* p_u_class = (UClass*)py_obj->ue_object; UObjectProperty* prop_base = NewObject<UObjectProperty>(function, UTF8_TO_TCHAR(p_name), RF_Public); prop_base->SetPropertyClass(p_u_class); prop = prop_base; } #if ENGINE_MINOR_VERSION > 17 else if (py_obj->ue_object->IsA<UEnum>()) { UEnumProperty* prop_enum = NewObject<UEnumProperty>(function, UTF8_TO_TCHAR(p_name), RF_Public); UNumericProperty* prop_underlying = NewObject<UByteProperty>(prop_enum, TEXT("UnderlyingType"), RF_Public); prop_enum->SetEnum((UEnum*)py_obj->ue_object); prop_enum->AddCppProperty(prop_underlying); prop = prop_enum; } #endif else if (py_obj->ue_object->IsA<UStruct>()) { UStructProperty* prop_struct = NewObject<UStructProperty>(function, UTF8_TO_TCHAR(p_name), RF_Public); prop_struct->Struct = (UScriptStruct*)py_obj->ue_object; prop = prop_struct; } } if (prop) { prop->SetPropertyFlags(CPF_Parm | CPF_OutParm | CPF_ReturnParm); *next_property = prop; next_property = &prop->Next; *next_property_link = prop; next_property_link = &prop->PropertyLinkNext; } else { UE_LOG(LogPython, Warning, TEXT("Unable to map return value to function %s"), UTF8_TO_TCHAR(name)); } } } // link to fix props Offset_Internal function->Bind(); function->StaticLink(true); if (parent_function) { if (!function->IsSignatureCompatibleWith(parent_function)) { TFieldIterator<UProperty> It(parent_function); while (It) { UProperty* p = *It; if (p->PropertyFlags & CPF_Parm) { UE_LOG(LogPython, Warning, TEXT("Parent PROP: %s %d/%d %d %d %d %s %p"), *p->GetName(), (int)p->PropertyFlags, (int)UFunction::GetDefaultIgnoredSignatureCompatibilityFlags(), (int)(p->PropertyFlags & ~UFunction::GetDefaultIgnoredSignatureCompatibilityFlags()), p->GetSize(), p->GetOffset_ForGC(), *p->GetClass()->GetName(), p->GetClass()); UClassProperty* ucp = Cast<UClassProperty>(p); if (ucp) { UE_LOG(LogPython, Warning, TEXT("Parent UClassProperty = %p %s %p %s"), ucp->PropertyClass, *ucp->PropertyClass->GetName(), ucp->MetaClass, *ucp->MetaClass->GetName()); } } ++It; } TFieldIterator<UProperty> It2(function); while (It2) { UProperty* p = *It2; if (p->PropertyFlags & CPF_Parm) { UE_LOG(LogPython, Warning, TEXT("Function PROP: %s %d/%d %d %d %d %s %p"), *p->GetName(), (int)p->PropertyFlags, (int)UFunction::GetDefaultIgnoredSignatureCompatibilityFlags(), (int)(p->PropertyFlags & ~UFunction::GetDefaultIgnoredSignatureCompatibilityFlags()), p->GetSize(), p->GetOffset_ForGC(), *p->GetClass()->GetName(), p->GetClass()); UClassProperty* ucp = Cast<UClassProperty>(p); if (ucp) { UE_LOG(LogPython, Warning, TEXT("Function UClassProperty = %p %s %p %s"), ucp->PropertyClass, *ucp->PropertyClass->GetName(), ucp->MetaClass, *ucp->MetaClass->GetName()); } } ++It2; } PyErr_Format(PyExc_Exception, "function %s signature's is not compatible with the parent", name); return nullptr; } } function->ParmsSize = 0; function->NumParms = 0; // allocate properties storage (ignore super) TFieldIterator<UProperty> props(function, EFieldIteratorFlags::ExcludeSuper); for (; props; ++props) { UProperty* p = *props; if (p->HasAnyPropertyFlags(CPF_Parm)) { function->NumParms++; function->ParmsSize = p->GetOffset_ForUFunction() + p->GetSize(); if (p->HasAnyPropertyFlags(CPF_ReturnParm)) { function->ReturnValueOffset = p->GetOffset_ForUFunction(); } } } if (parent_function) { UE_LOG(LogPython, Warning, TEXT("OVERRIDDEN FUNCTION %s WITH %d PARAMS (size %d) %d"), *function->GetFName().ToString(), function->NumParms, function->ParmsSize, function->PropertiesSize); } else { UE_LOG(LogPython, Warning, TEXT("REGISTERED FUNCTION %s WITH %d PARAMS (size %d) %d"), *function->GetFName().ToString(), function->NumParms, function->ParmsSize, function->PropertiesSize); } #if ENGINE_MINOR_VERSION >= 17 function->FunctionFlags = (EFunctionFlags)function_flags; #else function->FunctionFlags = function_flags; #endif #if ENGINE_MINOR_VERSION > 18 function->SetNativeFunc((FNativeFuncPtr)& UPythonFunction::CallPythonCallable); #else function->SetNativeFunc((Native)& UPythonFunction::CallPythonCallable); #endif function->Next = u_class->Children; u_class->Children = function; #if ENGINE_MINOR_VERSION < 18 u_class->AddFunctionToFunctionMap(function); #else u_class->AddFunctionToFunctionMap(function, function->GetFName()); #endif u_class->Bind(); u_class->StaticLink(true); // regenerate CDO u_class->GetDefaultObject()->RemoveFromRoot(); u_class->GetDefaultObject()->ConditionalBeginDestroy(); u_class->ClassDefaultObject = nullptr; #if WITH_EDITOR u_class->PostEditChange(); #endif u_class->GetDefaultObject()->PostInitProperties(); #if WITH_EDITOR u_class->PostLinkerChange(); #endif #if WITH_EDITOR // this is required for avoiding startup crashes #405 if (GEditor) { FBlueprintActionDatabase::Get().RefreshClassActions(u_class); } #endif return function; } FGuid* ue_py_check_fguid(PyObject* py_obj) { ue_PyUScriptStruct* ue_py_struct = py_ue_is_uscriptstruct(py_obj); if (!ue_py_struct) { return nullptr; } if (ue_py_struct->u_struct == FindObject<UScriptStruct>(ANY_PACKAGE, UTF8_TO_TCHAR((char*)"Guid"))) { return (FGuid*)ue_py_struct->u_struct_ptr; } return nullptr; } uint8* do_ue_py_check_struct(PyObject* py_obj, UScriptStruct* chk_u_struct) { ue_PyUScriptStruct* ue_py_struct = py_ue_is_uscriptstruct(py_obj); if (!ue_py_struct) { return nullptr; } if (ue_py_struct->u_struct == chk_u_struct) { return ue_py_struct->u_struct_ptr; } return nullptr; } bool do_ue_py_check_childstruct(PyObject* py_obj, UScriptStruct* parent_u_struct) { ue_PyUScriptStruct* ue_py_struct = py_ue_is_uscriptstruct(py_obj); if (!ue_py_struct) { return false; } return ue_py_struct->u_struct->IsChildOf(parent_u_struct); } #if PY_MAJOR_VERSION >= 3 static PyObject * init_unreal_engine() { PyObject* new_unreal_engine_module = PyModule_Create(&unreal_engine_module); if (!new_unreal_engine_module) return nullptr; return new_unreal_engine_module; } #endif ```
/content/code_sandbox/Source/UnrealEnginePython/Private/UEPyModule.cpp
c++
2016-08-07T05:00:51
2024-08-14T06:32:20
UnrealEnginePython
20tab/UnrealEnginePython
2,715
39,870
```c++ #include "PythonHouseKeeper.h" void FUnrealEnginePythonHouseKeeper::AddReferencedObjects(FReferenceCollector& InCollector) { InCollector.AddReferencedObjects(PythonTrackedObjects); } FUnrealEnginePythonHouseKeeper *FUnrealEnginePythonHouseKeeper::Get() { static FUnrealEnginePythonHouseKeeper *Singleton; if (!Singleton) { Singleton = new FUnrealEnginePythonHouseKeeper(); // register a new delegate for the GC #if ENGINE_MINOR_VERSION >= 18 FCoreUObjectDelegates::GetPostGarbageCollect().AddRaw(Singleton, &FUnrealEnginePythonHouseKeeper::RunGCDelegate); #else FCoreUObjectDelegates::PostGarbageCollect.AddRaw(Singleton, &FUnrealEnginePythonHouseKeeper::RunGCDelegate); #endif } return Singleton; } void FUnrealEnginePythonHouseKeeper::RunGCDelegate() { FScopePythonGIL gil; RunGC(); } int32 FUnrealEnginePythonHouseKeeper::RunGC() { int32 Garbaged = PyUObjectsGC(); Garbaged += DelegatesGC(); return Garbaged; } bool FUnrealEnginePythonHouseKeeper::IsValidPyUObject(ue_PyUObject *PyUObject) { if (!PyUObject) return false; UObject *Object = PyUObject->ue_object; FPythonUOjectTracker *Tracker = UObjectPyMapping.Find(Object); if (!Tracker) { return false; } if (!Tracker->Owner.IsValid()) return false; return true; } void FUnrealEnginePythonHouseKeeper::TrackUObject(UObject *Object) { FPythonUOjectTracker *Tracker = UObjectPyMapping.Find(Object); if (!Tracker) { return; } if (Tracker->bPythonOwned) return; Tracker->bPythonOwned = true; // when a new ue_PyUObject spawns, it has a reference counting of two Py_DECREF(Tracker->PyUObject); Tracker->PyUObject->owned = 1; PythonTrackedObjects.Add(Object); } void FUnrealEnginePythonHouseKeeper::UntrackUObject(UObject *Object) { PythonTrackedObjects.Remove(Object); } void FUnrealEnginePythonHouseKeeper::RegisterPyUObject(UObject *Object, ue_PyUObject *InPyUObject) { UObjectPyMapping.Add(Object, FPythonUOjectTracker(Object, InPyUObject)); } void FUnrealEnginePythonHouseKeeper::UnregisterPyUObject(UObject *Object) { UObjectPyMapping.Remove(Object); } ue_PyUObject *FUnrealEnginePythonHouseKeeper::GetPyUObject(UObject *Object) { FPythonUOjectTracker *Tracker = UObjectPyMapping.Find(Object); if (!Tracker) { return nullptr; } if (!Tracker->Owner.IsValid(true)) { #if defined(UEPY_MEMORY_DEBUG) UE_LOG(LogPython, Warning, TEXT("DEFREF'ing UObject at %p (refcnt: %d)"), Object, Tracker->PyUObject->ob_base.ob_refcnt); #endif if (!Tracker->bPythonOwned) Py_DECREF((PyObject *)Tracker->PyUObject); UnregisterPyUObject(Object); return nullptr; } return Tracker->PyUObject; } uint32 FUnrealEnginePythonHouseKeeper::PyUObjectsGC() { uint32 Garbaged = 0; TArray<UObject *> BrokenList; for (auto &UObjectPyItem : UObjectPyMapping) { UObject *Object = UObjectPyItem.Key; FPythonUOjectTracker &Tracker = UObjectPyItem.Value; #if defined(UEPY_MEMORY_DEBUG) UE_LOG(LogPython, Warning, TEXT("Checking for UObject at %p"), Object); #endif if (!Tracker.Owner.IsValid(true)) { #if defined(UEPY_MEMORY_DEBUG) UE_LOG(LogPython, Warning, TEXT("Removing UObject at %p (refcnt: %d)"), Object, Tracker.PyUObject->ob_base.ob_refcnt); #endif BrokenList.Add(Object); Garbaged++; } else { #if defined(UEPY_MEMORY_DEBUG) UE_LOG(LogPython, Error, TEXT("UObject at %p %s is in use"), Object, *Object->GetName()); #endif } } for (UObject *Object : BrokenList) { FPythonUOjectTracker &Tracker = UObjectPyMapping[Object]; if (!Tracker.bPythonOwned) Py_DECREF((PyObject *)Tracker.PyUObject); UnregisterPyUObject(Object); } return Garbaged; } int32 FUnrealEnginePythonHouseKeeper::DelegatesGC() { int32 Garbaged = 0; #if defined(UEPY_MEMORY_DEBUG) UE_LOG(LogPython, Display, TEXT("Garbage collecting %d UObject delegates"), PyDelegatesTracker.Num()); #endif for (int32 i = PyDelegatesTracker.Num() - 1; i >= 0; --i) { FPythonDelegateTracker &Tracker = PyDelegatesTracker[i]; if (!Tracker.Owner.IsValid(true)) { Tracker.Delegate->RemoveFromRoot(); PyDelegatesTracker.RemoveAt(i); Garbaged++; } } #if defined(UEPY_MEMORY_DEBUG) UE_LOG(LogPython, Display, TEXT("Garbage collecting %d Slate delegates"), PySlateDelegatesTracker.Num()); #endif for (int32 i = PySlateDelegatesTracker.Num() - 1; i >= 0; --i) { FPythonSWidgetDelegateTracker &Tracker = PySlateDelegatesTracker[i]; if (!Tracker.Owner.IsValid()) { PySlateDelegatesTracker.RemoveAt(i); Garbaged++; } } return Garbaged; } UPythonDelegate *FUnrealEnginePythonHouseKeeper::FindDelegate(UObject *Owner, PyObject *PyCallable) { for (int32 i = PyDelegatesTracker.Num() - 1; i >= 0; --i) { FPythonDelegateTracker &Tracker = PyDelegatesTracker[i]; if (Tracker.Owner.Get() == Owner && Tracker.Delegate->UsesPyCallable(PyCallable)) return Tracker.Delegate; } return nullptr; } UPythonDelegate *FUnrealEnginePythonHouseKeeper::NewDelegate(UObject *Owner, PyObject *PyCallable, UFunction *Signature) { UPythonDelegate *Delegate = NewObject<UPythonDelegate>(); Delegate->AddToRoot(); Delegate->SetPyCallable(PyCallable); Delegate->SetSignature(Signature); FPythonDelegateTracker Tracker(Delegate, Owner); PyDelegatesTracker.Add(Tracker); return Delegate; } TSharedRef<FPythonSlateDelegate> FUnrealEnginePythonHouseKeeper::NewSlateDelegate(TSharedRef<SWidget> Owner, PyObject *PyCallable) { TSharedRef<FPythonSlateDelegate> Delegate = MakeShareable(new FPythonSlateDelegate()); Delegate->SetPyCallable(PyCallable); FPythonSWidgetDelegateTracker Tracker(Delegate, Owner); PySlateDelegatesTracker.Add(Tracker); return Delegate; } TSharedRef<FPythonSlateDelegate> FUnrealEnginePythonHouseKeeper::NewDeferredSlateDelegate(PyObject *PyCallable) { TSharedRef<FPythonSlateDelegate> Delegate = MakeShareable(new FPythonSlateDelegate()); Delegate->SetPyCallable(PyCallable); return Delegate; } TSharedRef<FPythonSmartDelegate> FUnrealEnginePythonHouseKeeper::NewPythonSmartDelegate(PyObject *PyCallable) { TSharedRef<FPythonSmartDelegate> Delegate = MakeShareable(new FPythonSmartDelegate()); Delegate->SetPyCallable(PyCallable); PyStaticSmartDelegatesTracker.Add(Delegate); return Delegate; } void FUnrealEnginePythonHouseKeeper::TrackDeferredSlateDelegate(TSharedRef<FPythonSlateDelegate> Delegate, TSharedRef<SWidget> Owner) { FPythonSWidgetDelegateTracker Tracker(Delegate, Owner); PySlateDelegatesTracker.Add(Tracker); } TSharedRef<FPythonSlateDelegate> FUnrealEnginePythonHouseKeeper::NewStaticSlateDelegate(PyObject *PyCallable) { TSharedRef<FPythonSlateDelegate> Delegate = MakeShareable(new FPythonSlateDelegate()); Delegate->SetPyCallable(PyCallable); PyStaticSlateDelegatesTracker.Add(Delegate); return Delegate; } ```
/content/code_sandbox/Source/UnrealEnginePython/Private/PythonHouseKeeper.cpp
c++
2016-08-07T05:00:51
2024-08-14T06:32:20
UnrealEnginePython
20tab/UnrealEnginePython
2,715
1,839
```c++ #include "PyNativeWidgetHost.h" UPyNativeWidgetHost::UPyNativeWidgetHost(const FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer) { bIsVariable = true; } #if WITH_EDITOR const FText UPyNativeWidgetHost::GetPaletteCategory() { return NSLOCTEXT("Python", "Python", "Python"); } #endif ```
/content/code_sandbox/Source/UnrealEnginePython/Private/PyNativeWidgetHost.cpp
c++
2016-08-07T05:00:51
2024-08-14T06:32:20
UnrealEnginePython
20tab/UnrealEnginePython
2,715
79
```c++ #include "PythonComponent.h" #include "UEPyModule.h" UPythonComponent::UPythonComponent() { // Set this component to be initialized when the game starts, and to be ticked every frame. You can turn these features // off to improve performance if you don't need them. #if ENGINE_MINOR_VERSION < 14 bWantsBeginPlay = true; #endif PrimaryComponentTick.bCanEverTick = true; PythonTickForceDisabled = false; PythonDisableAutoBinding = false; PythonTickEnableGenerator = false; bWantsInitializeComponent = true; py_generator = nullptr; } void UPythonComponent::InitializePythonComponent() { if (PythonModule.IsEmpty()) return; FScopePythonGIL gil; py_uobject = ue_get_python_uobject(this); if (!py_uobject) { unreal_engine_py_log_error(); return; } PyObject *py_component_module = PyImport_ImportModule(TCHAR_TO_UTF8(*PythonModule)); if (!py_component_module) { unreal_engine_py_log_error(); return; } #if WITH_EDITOR // todo implement autoreload with a dictionary of module timestamps py_component_module = PyImport_ReloadModule(py_component_module); if (!py_component_module) { unreal_engine_py_log_error(); return; } #endif if (PythonClass.IsEmpty()) return; PyObject *py_component_module_dict = PyModule_GetDict(py_component_module); PyObject *py_component_class = PyDict_GetItemString(py_component_module_dict, TCHAR_TO_UTF8(*PythonClass)); if (!py_component_class) { UE_LOG(LogPython, Error, TEXT("Unable to find class %s in module %s"), *PythonClass, *PythonModule); return; } py_component_instance = PyObject_CallObject(py_component_class, NULL); if (!py_component_instance) { unreal_engine_py_log_error(); return; } py_uobject->py_proxy = py_component_instance; PyObject_SetAttrString(py_component_instance, (char *)"uobject", (PyObject *)py_uobject); // disable ticking if no tick method is exposed if (!PyObject_HasAttrString(py_component_instance, (char *)"tick") || PythonTickForceDisabled) { PrimaryComponentTick.bCanEverTick = false; PrimaryComponentTick.SetTickFunctionEnable(false); } if (!PythonDisableAutoBinding) ue_autobind_events_for_pyclass(py_uobject, py_component_instance); ue_bind_events_for_py_class_by_attribute(this, py_component_instance); if (!PyObject_HasAttrString(py_component_instance, (char *)"initialize_component")) { return; } PyObject *ic_ret = PyObject_CallMethod(py_component_instance, (char *)"initialize_component", NULL); if (!ic_ret) { unreal_engine_py_log_error(); } Py_XDECREF(ic_ret); } void UPythonComponent::InitializeComponent() { Super::InitializeComponent(); InitializePythonComponent(); } // Called when the game starts void UPythonComponent::BeginPlay() { Super::BeginPlay(); if (!py_component_instance) return; FScopePythonGIL gil; if (!PyObject_HasAttrString(py_component_instance, (char *)"begin_play")) { return; } PyObject *bp_ret = PyObject_CallMethod(py_component_instance, (char *)"begin_play", NULL); if (!bp_ret) { unreal_engine_py_log_error(); } Py_XDECREF(bp_ret); } void UPythonComponent::EndPlay(const EEndPlayReason::Type EndPlayReason) { if (!py_component_instance) return; FScopePythonGIL gil; if (PyObject_HasAttrString(py_component_instance, (char *)"end_play")) { PyObject *ep_ret = PyObject_CallMethod(py_component_instance, (char *)"end_play", (char*)"i", (int)EndPlayReason); if (!ep_ret) { unreal_engine_py_log_error(); } Py_XDECREF(ep_ret); } Super::EndPlay(EndPlayReason); // ... } // Called every frame void UPythonComponent::TickComponent(float DeltaTime, ELevelTick TickType, FActorComponentTickFunction* ThisTickFunction) { Super::TickComponent(DeltaTime, TickType, ThisTickFunction); if (!py_component_instance) return; FScopePythonGIL gil; if (PythonTickEnableGenerator && py_generator) { PyObject *ret = PyIter_Next(py_generator); if (!ret) { if (PyErr_Occurred()) { unreal_engine_py_log_error(); } Py_DECREF(py_generator); py_generator = nullptr; return; } Py_DECREF(ret); return; } // no need to check for method availability, we did it in component initialization PyObject *ret = PyObject_CallMethod(py_component_instance, (char *)"tick", (char *)"f", DeltaTime); if (!ret) { unreal_engine_py_log_error(); return; } if (PythonTickEnableGenerator) { py_generator = PyObject_GetIter(ret); if (!py_generator) { UE_LOG(LogPython, Error, TEXT("tick is not a python generator")); } } Py_DECREF(ret); } void UPythonComponent::CallPythonComponentMethod(FString method_name, FString args) { if (!py_component_instance) return; FScopePythonGIL gil; PyObject *ret = nullptr; if (args.IsEmpty()) { ret = PyObject_CallMethod(py_component_instance, TCHAR_TO_UTF8(*method_name), NULL); } else { ret = PyObject_CallMethod(py_component_instance, TCHAR_TO_UTF8(*method_name), (char *)"s", TCHAR_TO_UTF8(*args)); } if (!ret) { unreal_engine_py_log_error(); return; } Py_DECREF(ret); } void UPythonComponent::SetPythonAttrObject(FString attr, UObject *object) { if (!py_component_instance) return; FScopePythonGIL gil; ue_PyUObject *py_obj = ue_get_python_uobject(object); if (!py_obj) { PyErr_Format(PyExc_Exception, "PyUObject is in invalid state"); unreal_engine_py_log_error(); return; } if (PyObject_SetAttrString(py_component_instance, TCHAR_TO_UTF8(*attr), (PyObject *)py_obj) < 0) { UE_LOG(LogPython, Error, TEXT("Unable to set attribute %s"), *attr); } } void UPythonComponent::SetPythonAttrString(FString attr, FString s) { if (!py_component_instance) return; FScopePythonGIL gil; if (PyObject_SetAttrString(py_component_instance, TCHAR_TO_UTF8(*attr), PyUnicode_FromString(TCHAR_TO_UTF8(*s))) < 0) { UE_LOG(LogPython, Error, TEXT("Unable to set attribute %s"), *attr); } } void UPythonComponent::SetPythonAttrFloat(FString attr, float f) { if (!py_component_instance) return; FScopePythonGIL gil; if (PyObject_SetAttrString(py_component_instance, TCHAR_TO_UTF8(*attr), PyFloat_FromDouble(f)) < 0) { UE_LOG(LogPython, Error, TEXT("Unable to set attribute %s"), *attr); } } void UPythonComponent::SetPythonAttrInt(FString attr, int n) { if (!py_component_instance) return; FScopePythonGIL gil; if (PyObject_SetAttrString(py_component_instance, TCHAR_TO_UTF8(*attr), PyLong_FromLong(n)) < 0) { UE_LOG(LogPython, Error, TEXT("Unable to set attribute %s"), *attr); } } void UPythonComponent::SetPythonAttrVector(FString attr, FVector vec) { if (!py_component_instance) return; FScopePythonGIL gil; if (PyObject_SetAttrString(py_component_instance, TCHAR_TO_UTF8(*attr), py_ue_new_fvector(vec)) < 0) { UE_LOG(LogPython, Error, TEXT("Unable to set attribute %s"), *attr); } } void UPythonComponent::SetPythonAttrRotator(FString attr, FRotator rot) { if (!py_component_instance) return; FScopePythonGIL gil; if (PyObject_SetAttrString(py_component_instance, TCHAR_TO_UTF8(*attr), py_ue_new_frotator(rot)) < 0) { UE_LOG(LogPython, Error, TEXT("Unable to set attribute %s"), *attr); } } void UPythonComponent::SetPythonAttrBool(FString attr, bool b) { if (!py_component_instance) return; FScopePythonGIL gil; PyObject *py_bool = Py_False; if (b) { py_bool = Py_True; } if (PyObject_SetAttrString(py_component_instance, TCHAR_TO_UTF8(*attr), py_bool) < 0) { UE_LOG(LogPython, Error, TEXT("Unable to set attribute %s"), *attr); } } bool UPythonComponent::CallPythonComponentMethodBool(FString method_name, FString args) { if (!py_component_instance) return false; FScopePythonGIL gil; PyObject *ret = nullptr; if (args.IsEmpty()) { ret = PyObject_CallMethod(py_component_instance, TCHAR_TO_UTF8(*method_name), NULL); } else { ret = PyObject_CallMethod(py_component_instance, TCHAR_TO_UTF8(*method_name), (char *)"s", TCHAR_TO_UTF8(*args)); } if (!ret) { unreal_engine_py_log_error(); return false; } if (PyObject_IsTrue(ret)) { Py_DECREF(ret); return true; } Py_DECREF(ret); return false; } float UPythonComponent::CallPythonComponentMethodFloat(FString method_name, FString args) { if (!py_component_instance) return 0; FScopePythonGIL gil; PyObject *ret = nullptr; if (args.IsEmpty()) { ret = PyObject_CallMethod(py_component_instance, TCHAR_TO_UTF8(*method_name), NULL); } else { ret = PyObject_CallMethod(py_component_instance, TCHAR_TO_UTF8(*method_name), (char *)"s", TCHAR_TO_UTF8(*args)); } if (!ret) { unreal_engine_py_log_error(); return 0; } float value = 0; if (PyNumber_Check(ret)) { PyObject *py_value = PyNumber_Float(ret); value = PyFloat_AsDouble(py_value); Py_DECREF(py_value); } Py_DECREF(ret); return value; } int UPythonComponent::CallPythonComponentMethodInt(FString method_name, FString args) { if (!py_component_instance) return 0; FScopePythonGIL gil; PyObject *ret = nullptr; if (args.IsEmpty()) { ret = PyObject_CallMethod(py_component_instance, TCHAR_TO_UTF8(*method_name), NULL); } else { ret = PyObject_CallMethod(py_component_instance, TCHAR_TO_UTF8(*method_name), (char *)"s", TCHAR_TO_UTF8(*args)); } if (!ret) { unreal_engine_py_log_error(); return 0; } int value = 0; if (PyNumber_Check(ret)) { PyObject *py_value = PyNumber_Long(ret); value = PyLong_AsLong(py_value); Py_DECREF(py_value); } Py_DECREF(ret); return value; } FString UPythonComponent::CallPythonComponentMethodString(FString method_name, FString args) { if (!py_component_instance) return FString(); FScopePythonGIL gil; PyObject *ret = nullptr; if (args.IsEmpty()) { ret = PyObject_CallMethod(py_component_instance, TCHAR_TO_UTF8(*method_name), NULL); } else { ret = PyObject_CallMethod(py_component_instance, TCHAR_TO_UTF8(*method_name), (char *)"s", TCHAR_TO_UTF8(*args)); } if (!ret) { unreal_engine_py_log_error(); return FString(); } PyObject *py_str = PyObject_Str(ret); if (!py_str) { Py_DECREF(ret); return FString(); } const char *str_ret = UEPyUnicode_AsUTF8(py_str); FString ret_fstring = FString(UTF8_TO_TCHAR(str_ret)); Py_DECREF(py_str); return ret_fstring; } UObject *UPythonComponent::CallPythonComponentMethodObject(FString method_name, UObject *arg) { if (!py_component_instance) return nullptr; FScopePythonGIL gil; PyObject *ret = nullptr; if (!arg) { ret = PyObject_CallMethod(py_component_instance, TCHAR_TO_UTF8(*method_name), NULL); } else { PyObject *py_arg_uobject = (PyObject *)ue_get_python_uobject(arg); if (!py_arg_uobject) { unreal_engine_py_log_error(); return nullptr; } ret = PyObject_CallMethod(py_component_instance, TCHAR_TO_UTF8(*method_name), (char *)"O", py_arg_uobject); } if (!ret) { unreal_engine_py_log_error(); return nullptr; } if (ue_is_pyuobject(ret)) { ue_PyUObject *py_obj = (ue_PyUObject *)ret; return py_obj->ue_object; } return nullptr; } #if ENGINE_MINOR_VERSION >= 15 TMap<FString, FString> UPythonComponent::CallPythonComponentMethodMap(FString method_name, FString args) { TMap<FString, FString> output_map; if (!py_component_instance) return output_map; FScopePythonGIL gil; PyObject *ret = nullptr; if (args.IsEmpty()) { ret = PyObject_CallMethod(py_component_instance, TCHAR_TO_UTF8(*method_name), NULL); } else { ret = PyObject_CallMethod(py_component_instance, TCHAR_TO_UTF8(*method_name), (char *)"s", TCHAR_TO_UTF8(*args)); } if (!ret) { unreal_engine_py_log_error(); return output_map; } if (!PyDict_Check(ret)) { UE_LOG(LogPython, Error, TEXT("return value is not a dict")); return output_map; } PyObject *py_keys = PyDict_Keys(ret); Py_ssize_t len = PyList_Size(py_keys); for (Py_ssize_t i = 0; i < len; i++) { PyObject *py_key = PyList_GetItem(py_keys, i); PyObject *py_str_key = PyObject_Str(py_key); PyObject *py_str_value = PyObject_Str(PyDict_GetItem(ret, py_key)); if (!py_str_key || !py_str_value) { Py_DECREF(ret); return output_map; } const char *str_key = UEPyUnicode_AsUTF8(py_str_key); const char *str_value = UEPyUnicode_AsUTF8(py_str_value); FString ret_fstring_key = FString(UTF8_TO_TCHAR(str_key)); FString ret_fstring_value = FString(UTF8_TO_TCHAR(str_value)); output_map.Add(ret_fstring_key, ret_fstring_value); Py_DECREF(py_str_key); Py_DECREF(py_str_value); } Py_DECREF(ret); return output_map; } #endif void UPythonComponent::CallPythonComponentMethodStringArray(FString method_name, FString args, TArray<FString> &output_strings) { if (!py_component_instance) return; output_strings.Empty(); FScopePythonGIL gil; PyObject *ret = nullptr; if (args.IsEmpty()) { ret = PyObject_CallMethod(py_component_instance, TCHAR_TO_UTF8(*method_name), NULL); } else { ret = PyObject_CallMethod(py_component_instance, TCHAR_TO_UTF8(*method_name), (char *)"s", TCHAR_TO_UTF8(*args)); } if (!ret) { unreal_engine_py_log_error(); return; } if (!PyList_Check(ret)) { UE_LOG(LogPython, Error, TEXT("return value is not a list")); return; } Py_ssize_t len = PyList_Size(ret); for (Py_ssize_t i = 0; i < len; i++) { PyObject *py_str = PyObject_Str(PyList_GetItem(ret, i)); if (!py_str) { Py_DECREF(ret); return; } const char *str_ret = UEPyUnicode_AsUTF8(py_str); FString ret_fstring = FString(UTF8_TO_TCHAR(str_ret)); output_strings.Add(ret_fstring); Py_DECREF(py_str); } Py_DECREF(ret); } UPythonComponent::~UPythonComponent() { FScopePythonGIL gil; # Py_XDECREF(py_component_instance); #if defined(UEPY_MEMORY_DEBUG) UE_LOG(LogPython, Warning, TEXT("Python UActorComponent %p (mapped to %p) wrapper XDECREF'ed"), this, py_uobject ? py_uobject->py_proxy : nullptr); #endif // this could trigger the distruction of the python/uobject mapper Py_XDECREF(py_uobject); FUnrealEnginePythonHouseKeeper::Get()->UnregisterPyUObject(this); } ```
/content/code_sandbox/Source/UnrealEnginePython/Private/PythonComponent.cpp
c++
2016-08-07T05:00:51
2024-08-14T06:32:20
UnrealEnginePython
20tab/UnrealEnginePython
2,715
3,770
```c++ #include "PyActor.h" #include "UEPyModule.h" APyActor::APyActor() { PrimaryActorTick.bCanEverTick = true; PythonTickForceDisabled = false; PythonDisableAutoBinding = false; } void APyActor::PreInitializeComponents() { Super::PreInitializeComponents(); if (PythonModule.IsEmpty()) return; FScopePythonGIL gil; py_uobject = ue_get_python_uobject(this); if (!py_uobject) { unreal_engine_py_log_error(); return; } PyObject *py_actor_module = PyImport_ImportModule(TCHAR_TO_UTF8(*PythonModule)); if (!py_actor_module) { unreal_engine_py_log_error(); return; } #if WITH_EDITOR // todo implement autoreload with a dictionary of module timestamps py_actor_module = PyImport_ReloadModule(py_actor_module); if (!py_actor_module) { unreal_engine_py_log_error(); return; } #endif if (PythonClass.IsEmpty()) return; PyObject *py_actor_module_dict = PyModule_GetDict(py_actor_module); PyObject *py_actor_class = PyDict_GetItemString(py_actor_module_dict, TCHAR_TO_UTF8(*PythonClass)); if (!py_actor_class) { UE_LOG(LogPython, Error, TEXT("Unable to find class %s in module %s"), *PythonClass, *PythonModule); return; } py_actor_instance = PyObject_CallObject(py_actor_class, NULL); if (!py_actor_instance) { unreal_engine_py_log_error(); return; } py_uobject->py_proxy = py_actor_instance; PyObject_SetAttrString(py_actor_instance, (char*)"uobject", (PyObject *)py_uobject); if (!PyObject_HasAttrString(py_actor_instance, (char *)"tick") || PythonTickForceDisabled) { SetActorTickEnabled(false); } if (!PythonDisableAutoBinding) ue_autobind_events_for_pyclass(py_uobject, py_actor_instance); ue_bind_events_for_py_class_by_attribute(this, py_actor_instance); if (!PyObject_HasAttrString(py_actor_instance, (char *)"pre_initialize_components")) return; PyObject *pic_ret = PyObject_CallMethod(py_actor_instance, (char *)"pre_initialize_components", NULL); if (!pic_ret) { unreal_engine_py_log_error(); return; } Py_DECREF(pic_ret); } void APyActor::PostInitializeComponents() { Super::PostInitializeComponents(); if (!py_actor_instance) return; FScopePythonGIL gil; if (!PyObject_HasAttrString(py_actor_instance, (char *)"post_initialize_components")) return; PyObject *pic_ret = PyObject_CallMethod(py_actor_instance, (char *)"post_initialize_components", NULL); if (!pic_ret) { unreal_engine_py_log_error(); return; } Py_DECREF(pic_ret); } // Called when the game starts void APyActor::BeginPlay() { Super::BeginPlay(); if (!py_actor_instance) return; FScopePythonGIL gil; if (!PyObject_HasAttrString(py_actor_instance, (char *)"begin_play")) return; PyObject *bp_ret = PyObject_CallMethod(py_actor_instance, (char *)"begin_play", NULL); if (!bp_ret) { unreal_engine_py_log_error(); return; } Py_DECREF(bp_ret); } // Called every frame void APyActor::Tick(float DeltaTime) { Super::Tick(DeltaTime); if (!py_actor_instance) return; FScopePythonGIL gil; if (!PyObject_HasAttrString(py_actor_instance, (char *)"tick")) return; PyObject *ret = PyObject_CallMethod(py_actor_instance, (char *)"tick", (char *)"f", DeltaTime); if (!ret) { unreal_engine_py_log_error(); return; } Py_DECREF(ret); } void APyActor::EndPlay(const EEndPlayReason::Type EndPlayReason) { if (!py_actor_instance) return; FScopePythonGIL gil; if (PyObject_HasAttrString(py_actor_instance, (char *)"end_play")) { PyObject *ep_ret = PyObject_CallMethod(py_actor_instance, (char *)"end_play", (char*)"i", (int)EndPlayReason); if (!ep_ret) { unreal_engine_py_log_error(); } Py_XDECREF(ep_ret); } Super::EndPlay(EndPlayReason); // ... } void APyActor::CallPythonActorMethod(FString method_name, FString args) { if (!py_actor_instance) return; FScopePythonGIL gil; PyObject *ret = nullptr; if (args.IsEmpty()) { ret = PyObject_CallMethod(py_actor_instance, TCHAR_TO_UTF8(*method_name), NULL); } else { ret = PyObject_CallMethod(py_actor_instance, TCHAR_TO_UTF8(*method_name), (char *)"s", TCHAR_TO_UTF8(*args)); } if (!ret) { unreal_engine_py_log_error(); return; } Py_DECREF(ret); } bool APyActor::CallPythonActorMethodBool(FString method_name, FString args) { if (!py_actor_instance) return false; FScopePythonGIL gil; PyObject *ret = nullptr; if (args.IsEmpty()) { ret = PyObject_CallMethod(py_actor_instance, TCHAR_TO_UTF8(*method_name), NULL); } else { ret = PyObject_CallMethod(py_actor_instance, TCHAR_TO_UTF8(*method_name), (char *)"s", TCHAR_TO_UTF8(*args)); } if (!ret) { unreal_engine_py_log_error(); return false; } if (PyObject_IsTrue(ret)) { Py_DECREF(ret); return true; } Py_DECREF(ret); return false; } FString APyActor::CallPythonActorMethodString(FString method_name, FString args) { if (!py_actor_instance) return FString(); FScopePythonGIL gil; PyObject *ret = nullptr; if (args.IsEmpty()) { ret = PyObject_CallMethod(py_actor_instance, TCHAR_TO_UTF8(*method_name), NULL); } else { ret = PyObject_CallMethod(py_actor_instance, TCHAR_TO_UTF8(*method_name), (char *)"s", TCHAR_TO_UTF8(*args)); } if (!ret) { unreal_engine_py_log_error(); return FString(); } PyObject *py_str = PyObject_Str(ret); if (!py_str) { Py_DECREF(ret); return FString(); } const char *str_ret = UEPyUnicode_AsUTF8(py_str); FString ret_fstring = FString(UTF8_TO_TCHAR(str_ret)); Py_DECREF(py_str); return ret_fstring; } APyActor::~APyActor() { FScopePythonGIL gil; Py_XDECREF(py_actor_instance); #if defined(UEPY_MEMORY_DEBUG) UE_LOG(LogPython, Warning, TEXT("Python AActor %p (mapped to %p) wrapper XDECREF'ed"), this, py_uobject ? py_uobject->py_proxy : nullptr); #endif Py_XDECREF(py_uobject); FUnrealEnginePythonHouseKeeper::Get()->UnregisterPyUObject(this); } ```
/content/code_sandbox/Source/UnrealEnginePython/Private/PyActor.cpp
c++
2016-08-07T05:00:51
2024-08-14T06:32:20
UnrealEnginePython
20tab/UnrealEnginePython
2,715
1,564
```objective-c #pragma once #include "UEPyModule.h" typedef struct { PyObject_HEAD /* Type-specific fields go here. */ } ue_PyUClassesImporter; PyObject *py_ue_new_uclassesimporter(); void ue_python_init_uclassesimporter(PyObject *); ```
/content/code_sandbox/Source/UnrealEnginePython/Private/UEPyUClassesImporter.h
objective-c
2016-08-07T05:00:51
2024-08-14T06:32:20
UnrealEnginePython
20tab/UnrealEnginePython
2,715
58
```c++ #include "UEPyEngine.h" #include "Kismet/KismetSystemLibrary.h" #include "Kismet/KismetMathLibrary.h" #include "Developer/DesktopPlatform/Public/IDesktopPlatform.h" #include "Developer/DesktopPlatform/Public/DesktopPlatformModule.h" #if WITH_EDITOR #include "PackageTools.h" #include "Editor.h" #endif #include "UnrealEngine.h" #include "Runtime/Engine/Classes/Engine/GameViewportClient.h" #if ENGINE_MINOR_VERSION >= 18 #include "HAL/PlatformApplicationMisc.h" #endif #include "Runtime/Launch/Public/LaunchEngineLoop.h" #if PLATFORM_MAC #include "Runtime/Core/Public/Mac/CocoaThread.h" #endif #include "Runtime/Slate/Public/Framework/Application/SlateApplication.h" #include "Runtime/CoreUObject/Public/UObject/UObjectIterator.h" PyObject *py_unreal_engine_log(PyObject * self, PyObject * args) { PyObject *py_message; if (!PyArg_ParseTuple(args, "O:log", &py_message)) { return NULL; } PyObject *stringified = PyObject_Str(py_message); if (!stringified) return PyErr_Format(PyExc_Exception, "argument cannot be casted to string"); const char *message = UEPyUnicode_AsUTF8(stringified); UE_LOG(LogPython, Log, TEXT("%s"), UTF8_TO_TCHAR(message)); Py_DECREF(stringified); Py_RETURN_NONE; } PyObject *py_unreal_engine_log_warning(PyObject * self, PyObject * args) { PyObject *py_message; if (!PyArg_ParseTuple(args, "O:log_warning", &py_message)) { return NULL; } PyObject *stringified = PyObject_Str(py_message); if (!stringified) return PyErr_Format(PyExc_Exception, "argument cannot be casted to string"); const char *message = UEPyUnicode_AsUTF8(stringified); UE_LOG(LogPython, Warning, TEXT("%s"), UTF8_TO_TCHAR(message)); Py_DECREF(stringified); Py_RETURN_NONE; } PyObject *py_unreal_engine_log_error(PyObject * self, PyObject * args) { PyObject *py_message; if (!PyArg_ParseTuple(args, "O:log_error", &py_message)) { return NULL; } PyObject *stringified = PyObject_Str(py_message); if (!stringified) return PyErr_Format(PyExc_Exception, "argument cannot be casted to string"); const char *message = UEPyUnicode_AsUTF8(stringified); UE_LOG(LogPython, Error, TEXT("%s"), UTF8_TO_TCHAR(message)); Py_DECREF(stringified); Py_RETURN_NONE; } PyObject *py_unreal_engine_add_on_screen_debug_message(PyObject * self, PyObject * args) { int key; float time_to_display; PyObject *py_message; if (!PyArg_ParseTuple(args, "ifO:add_on_screen_debug_message", &key, &time_to_display, &py_message)) { return NULL; } if (!GEngine) { Py_INCREF(Py_None); return Py_None; } PyObject *stringified = PyObject_Str(py_message); if (!stringified) return PyErr_Format(PyExc_Exception, "argument cannot be casted to string"); const char *message = UEPyUnicode_AsUTF8(stringified); GEngine->AddOnScreenDebugMessage(key, time_to_display, FColor::Green, FString::Printf(TEXT("%s"), UTF8_TO_TCHAR(message))); Py_DECREF(stringified); Py_RETURN_NONE; } PyObject *py_unreal_engine_print_string(PyObject * self, PyObject * args) { PyObject *py_message; float timeout = 2.0; PyObject *py_color = nullptr; if (!PyArg_ParseTuple(args, "O|fO:print_string", &py_message, &timeout, &py_color)) { return NULL; } if (!GEngine) { Py_RETURN_NONE; } FColor color = FColor::Cyan; if (py_color) { ue_PyFColor *f_color = py_ue_is_fcolor(py_color); if (!f_color) return PyErr_Format(PyExc_Exception, "argument is not a FColor"); color = f_color->color; } PyObject *stringified = PyObject_Str(py_message); if (!stringified) return PyErr_Format(PyExc_Exception, "argument cannot be casted to string"); const char *message = UEPyUnicode_AsUTF8(stringified); GEngine->AddOnScreenDebugMessage(-1, timeout, color, FString(UTF8_TO_TCHAR(message))); Py_DECREF(stringified); Py_RETURN_NONE; } PyObject *py_unreal_engine_get_forward_vector(PyObject * self, PyObject * args) { FRotator rot; if (!py_ue_rotator_arg(args, rot)) return NULL; FVector vec = UKismetMathLibrary::GetForwardVector(rot); return py_ue_new_fvector(vec); } PyObject *py_unreal_engine_get_right_vector(PyObject * self, PyObject * args) { FRotator rot; if (!py_ue_rotator_arg(args, rot)) return NULL; FVector vec = UKismetMathLibrary::GetRightVector(rot); return py_ue_new_fvector(vec); } PyObject *py_unreal_engine_get_up_vector(PyObject * self, PyObject * args) { FRotator rot; if (!py_ue_rotator_arg(args, rot)) return NULL; FVector vec = UKismetMathLibrary::GetUpVector(rot); return py_ue_new_fvector(vec); } PyObject *py_unreal_engine_get_content_dir(PyObject * self, PyObject * args) { #if ENGINE_MINOR_VERSION >= 18 return PyUnicode_FromString(TCHAR_TO_UTF8(*FPaths::ProjectContentDir())); #else return PyUnicode_FromString(TCHAR_TO_UTF8(*FPaths::GameContentDir())); #endif } PyObject *py_unreal_engine_get_game_saved_dir(PyObject * self, PyObject * args) { #if ENGINE_MINOR_VERSION >= 18 return PyUnicode_FromString(TCHAR_TO_UTF8(*FPaths::ProjectSavedDir())); #else return PyUnicode_FromString(TCHAR_TO_UTF8(*FPaths::GameSavedDir())); #endif } PyObject * py_unreal_engine_get_game_user_developer_dir(PyObject *, PyObject *) { return PyUnicode_FromString(TCHAR_TO_UTF8(*FPaths::GameUserDeveloperDir())); } PyObject *py_unreal_engine_convert_relative_path_to_full(PyObject * self, PyObject * args) { char *path; if (!PyArg_ParseTuple(args, "s:convert_relative_path_to_full", &path)) { return NULL; } return PyUnicode_FromString(TCHAR_TO_UTF8(*FPaths::ConvertRelativePathToFull(UTF8_TO_TCHAR(path)))); } PyObject *py_unreal_engine_object_path_to_package_name(PyObject * self, PyObject * args) { char *path; if (!PyArg_ParseTuple(args, "s:object_path_to_package_name", &path)) { return NULL; } return PyUnicode_FromString(TCHAR_TO_UTF8(*FPackageName::ObjectPathToPackageName(UTF8_TO_TCHAR(path)))); } PyObject *py_unreal_engine_get_path(PyObject * self, PyObject * args) { char *path; if (!PyArg_ParseTuple(args, "s:get_path", &path)) { return NULL; } return PyUnicode_FromString(TCHAR_TO_UTF8(*FPaths::GetPath(UTF8_TO_TCHAR(path)))); } PyObject *py_unreal_engine_get_base_filename(PyObject * self, PyObject * args) { char *path; if (!PyArg_ParseTuple(args, "s:get_base_filename", &path)) { return NULL; } return PyUnicode_FromString(TCHAR_TO_UTF8(*FPaths::GetBaseFilename(UTF8_TO_TCHAR(path)))); } PyObject *py_unreal_engine_create_world(PyObject * self, PyObject * args) { int world_type = 0; if (!PyArg_ParseTuple(args, "|i:create_world", &world_type)) { return NULL; } UWorld *world = UWorld::CreateWorld((EWorldType::Type)world_type, false); Py_RETURN_UOBJECT(world); } PyObject *py_unreal_engine_find_class(PyObject * self, PyObject * args) { char *name; if (!PyArg_ParseTuple(args, "s:find_class", &name)) { return NULL; } UClass *u_class = FindObject<UClass>(ANY_PACKAGE, UTF8_TO_TCHAR(name)); if (!u_class) return PyErr_Format(PyExc_Exception, "unable to find class %s", name); Py_RETURN_UOBJECT(u_class); } PyObject *py_unreal_engine_find_enum(PyObject * self, PyObject * args) { char *name; if (!PyArg_ParseTuple(args, "s:find_enum", &name)) { return NULL; } UEnum *u_enum = FindObject<UEnum>(ANY_PACKAGE, UTF8_TO_TCHAR(name)); if (!u_enum) return PyErr_Format(PyExc_Exception, "unable to find enum %s", name); Py_RETURN_UOBJECT(u_enum); } PyObject *py_unreal_engine_load_package(PyObject * self, PyObject * args) { char *name; if (!PyArg_ParseTuple(args, "s:load_package", &name)) { return nullptr; } UPackage *u_package = LoadPackage(nullptr, UTF8_TO_TCHAR(name), LOAD_None); if (!u_package) return PyErr_Format(PyExc_Exception, "unable to load package %s", name); Py_RETURN_UOBJECT(u_package); } #if WITH_EDITOR PyObject *py_unreal_engine_unload_package(PyObject * self, PyObject * args) { PyObject *obj; if (!PyArg_ParseTuple(args, "O:unload_package", &obj)) { return NULL; } UPackage* packageToUnload = ue_py_check_type<UPackage>(obj); if (!packageToUnload) { return PyErr_Format(PyExc_Exception, "argument is not a UPackage"); } FText outErrorMsg; if (!PackageTools::UnloadPackages({ packageToUnload }, outErrorMsg)) { return PyErr_Format(PyExc_Exception, "%s", TCHAR_TO_UTF8(*outErrorMsg.ToString())); } Py_RETURN_NONE; } PyObject *py_unreal_engine_get_package_filename(PyObject * self, PyObject * args) { char *name; if (!PyArg_ParseTuple(args, "s:get_package_filename", &name)) { return NULL; } FString Filename; if (!FPackageName::DoesPackageExist(FString(UTF8_TO_TCHAR(name)), nullptr, &Filename)) return PyErr_Format(PyExc_Exception, "package does not exist"); return PyUnicode_FromString(TCHAR_TO_UTF8(*Filename)); } #endif PyObject *py_unreal_engine_load_class(PyObject * self, PyObject * args) { char *name; char *filename = nullptr; if (!PyArg_ParseTuple(args, "s|s:load_class", &name, &filename)) { return NULL; } TCHAR *t_filename = (TCHAR *)0; if (filename) t_filename = UTF8_TO_TCHAR(filename); UObject *u_class = StaticLoadObject(UClass::StaticClass(), NULL, UTF8_TO_TCHAR(name), t_filename); if (!u_class) return PyErr_Format(PyExc_Exception, "unable to find class %s", name); Py_RETURN_UOBJECT(u_class); } PyObject *py_unreal_engine_load_enum(PyObject * self, PyObject * args) { char *name; char *filename = nullptr; if (!PyArg_ParseTuple(args, "s|s:load_enum", &name, &filename)) { return NULL; } TCHAR *t_filename = (TCHAR *)0; if (filename) t_filename = UTF8_TO_TCHAR(filename); UObject *u_enum = StaticLoadObject(UEnum::StaticClass(), NULL, UTF8_TO_TCHAR(name), t_filename); if (!u_enum) return PyErr_Format(PyExc_Exception, "unable to find enum %s", name); Py_RETURN_UOBJECT(u_enum); } PyObject *py_unreal_engine_find_struct(PyObject * self, PyObject * args) { char *name; if (!PyArg_ParseTuple(args, "s:find_struct", &name)) { return NULL; } UScriptStruct *u_struct = FindObject<UScriptStruct>(ANY_PACKAGE, UTF8_TO_TCHAR(name)); if (!u_struct) return PyErr_Format(PyExc_Exception, "unable to find struct %s", name); Py_RETURN_UOBJECT(u_struct); } PyObject *py_unreal_engine_load_struct(PyObject * self, PyObject * args) { char *name; char *filename = nullptr; if (!PyArg_ParseTuple(args, "s|s:load_struct", &name, &filename)) { return NULL; } TCHAR *t_filename = (TCHAR *)0; if (filename) t_filename = UTF8_TO_TCHAR(filename); UObject *u_struct = StaticLoadObject(UScriptStruct::StaticClass(), NULL, UTF8_TO_TCHAR(name), t_filename); if (!u_struct) return PyErr_Format(PyExc_Exception, "unable to find struct %s", name); Py_RETURN_UOBJECT(u_struct); } PyObject *py_unreal_engine_load_object(PyObject * self, PyObject * args) { PyObject *obj; char *name; char *filename = nullptr; if (!PyArg_ParseTuple(args, "Os|s:load_object", &obj, &name, &filename)) { return NULL; } if (!ue_is_pyuobject(obj)) { return PyErr_Format(PyExc_Exception, "argument is not a UObject"); } ue_PyUObject *py_obj = (ue_PyUObject *)obj; if (!py_obj->ue_object->IsA<UClass>()) { return PyErr_Format(PyExc_Exception, "argument is not a UClass"); } UClass *u_class = (UClass *)py_obj->ue_object; TCHAR *t_filename = (TCHAR *)0; if (filename) t_filename = UTF8_TO_TCHAR(filename); UObject *u_object = StaticLoadObject(u_class, NULL, UTF8_TO_TCHAR(name), t_filename); if (!u_object) return PyErr_Format(PyExc_Exception, "unable to load object %s", name); Py_RETURN_UOBJECT(u_object); } PyObject *py_unreal_engine_string_to_guid(PyObject * self, PyObject * args) { char *str; if (!PyArg_ParseTuple(args, "s:string_to_guid", &str)) { return nullptr; } FGuid guid; if (FGuid::Parse(FString(str), guid)) { return py_ue_new_owned_uscriptstruct(FindObject<UScriptStruct>(ANY_PACKAGE, UTF8_TO_TCHAR((char *)"Guid")), (uint8 *)&guid); } return PyErr_Format(PyExc_Exception, "unable to build FGuid"); } PyObject *py_unreal_engine_new_guid(PyObject * self, PyObject * args) { FGuid guid = FGuid::NewGuid(); return py_ue_new_owned_uscriptstruct(FindObject<UScriptStruct>(ANY_PACKAGE, UTF8_TO_TCHAR((char *)"Guid")), (uint8 *)&guid); } PyObject *py_unreal_engine_guid_to_string(PyObject * self, PyObject * args) { PyObject *py_guid; if (!PyArg_ParseTuple(args, "O:guid_to_string", &py_guid)) { return nullptr; } FGuid *guid = ue_py_check_fguid(py_guid); if (!guid) return PyErr_Format(PyExc_Exception, "object is not a FGuid"); return PyUnicode_FromString(TCHAR_TO_UTF8(*guid->ToString())); } PyObject *py_unreal_engine_slate_tick(PyObject * self, PyObject * args) { Py_BEGIN_ALLOW_THREADS; FSlateApplication::Get().PumpMessages(); FSlateApplication::Get().Tick(); Py_END_ALLOW_THREADS; Py_RETURN_NONE; } PyObject *py_unreal_engine_engine_tick(PyObject * self, PyObject * args) { float delta_seconds = FApp::GetDeltaTime(); PyObject *py_idle = nullptr; if (!PyArg_ParseTuple(args, "|fO:engine_tick", &delta_seconds, &py_idle)) { return nullptr; } bool bIdle = false; if (py_idle && PyObject_IsTrue(py_idle)) bIdle = true; Py_BEGIN_ALLOW_THREADS; GEngine->Tick(delta_seconds, bIdle); Py_END_ALLOW_THREADS; Py_RETURN_NONE; } #if WITH_EDITOR PyObject *py_unreal_engine_tick_rendering_tickables(PyObject * self, PyObject * args) { Py_BEGIN_ALLOW_THREADS; TickRenderingTickables(); Py_END_ALLOW_THREADS; Py_RETURN_NONE; } #endif PyObject *py_unreal_engine_get_delta_time(PyObject * self, PyObject * args) { return PyFloat_FromDouble(FApp::GetDeltaTime()); } PyObject *py_unreal_engine_find_object(PyObject * self, PyObject * args) { char *name; if (!PyArg_ParseTuple(args, "s:find_object", &name)) { return NULL; } UObject *u_object = FindObject<UObject>(ANY_PACKAGE, UTF8_TO_TCHAR(name)); if (!u_object) return PyErr_Format(PyExc_Exception, "unable to find object %s", name); Py_RETURN_UOBJECT(u_object); } PyObject *py_unreal_engine_new_object(PyObject * self, PyObject * args) { PyObject *obj; PyObject *py_outer = NULL; char *name = nullptr; uint64 flags = (uint64)(RF_Public); if (!PyArg_ParseTuple(args, "O|OsK:new_object", &obj, &py_outer, &name, &flags)) { return nullptr; } UClass *obj_class = ue_py_check_type<UClass>(obj); if (!obj_class) return PyErr_Format(PyExc_Exception, "uobject is not a UClass"); FName f_name = NAME_None; if (name && strlen(name) > 0) { f_name = FName(UTF8_TO_TCHAR(name)); } UObject *outer = GetTransientPackage(); if (py_outer && py_outer != Py_None) { outer = ue_py_check_type<UObject>(py_outer); if (!outer) return PyErr_Format(PyExc_Exception, "argument is not a UObject"); } UObject *new_object = nullptr; Py_BEGIN_ALLOW_THREADS; new_object = NewObject<UObject>(outer, obj_class, f_name, (EObjectFlags)flags); if (new_object) new_object->PostLoad(); Py_END_ALLOW_THREADS; if (!new_object) return PyErr_Format(PyExc_Exception, "unable to create object"); Py_RETURN_UOBJECT(new_object); } PyObject *py_unreal_engine_get_mutable_default(PyObject * self, PyObject * args) { PyObject *obj; if (!PyArg_ParseTuple(args, "O|Os:get_mutable_default", &obj)) { return NULL; } if (!ue_is_pyuobject(obj)) { return PyErr_Format(PyExc_Exception, "argument is not a UObject"); } ue_PyUObject *py_obj = (ue_PyUObject *)obj; if (!py_obj->ue_object->IsA<UClass>()) return PyErr_Format(PyExc_Exception, "uobject is not a UClass"); UClass *obj_class = (UClass *)py_obj->ue_object; UObject *mutable_object = GetMutableDefault<UObject>(obj_class); if (!mutable_object) return PyErr_Format(PyExc_Exception, "unable to create object"); Py_RETURN_UOBJECT(mutable_object); } PyObject *py_unreal_engine_new_class(PyObject * self, PyObject * args) { PyObject *py_parent; char *name; if (!PyArg_ParseTuple(args, "Os:new_class", &py_parent, &name)) { return NULL; } UClass *parent = nullptr; if (py_parent != Py_None) { if (!ue_is_pyuobject(py_parent)) { return PyErr_Format(PyExc_Exception, "argument is not a UObject"); } ue_PyUObject *py_obj = (ue_PyUObject *)py_parent; if (!py_obj->ue_object->IsA<UClass>()) return PyErr_Format(PyExc_Exception, "uobject is not a UClass"); parent = (UClass *)py_obj->ue_object; } UClass *new_object = unreal_engine_new_uclass(name, parent); if (!new_object) return PyErr_Format(PyExc_Exception, "unable to create UClass"); Py_RETURN_UOBJECT(new_object); } PyObject *py_unreal_engine_all_classes(PyObject * self, PyObject * args) { PyObject *ret = PyList_New(0); for (TObjectIterator<UClass> Itr; Itr; ++Itr) { ue_PyUObject *py_obj = ue_get_python_uobject(*Itr); if (!py_obj) continue; PyList_Append(ret, (PyObject *)py_obj); } return ret; } PyObject *py_unreal_engine_all_worlds(PyObject * self, PyObject * args) { PyObject *ret = PyList_New(0); for (TObjectIterator<UWorld> Itr; Itr; ++Itr) { ue_PyUObject *py_obj = ue_get_python_uobject(*Itr); if (!py_obj) continue; PyList_Append(ret, (PyObject *)py_obj); } return ret; } PyObject *py_unreal_engine_tobject_iterator(PyObject * self, PyObject * args) { PyObject *py_class; if (!PyArg_ParseTuple(args, "O:tobject_iterator", &py_class)) { return NULL; } UClass *u_class = ue_py_check_type<UClass>(py_class); if (!u_class) { return PyErr_Format(PyExc_TypeError, "argument is not a UClass"); } PyObject *ret = PyList_New(0); for (TObjectIterator<UObject> Itr; Itr; ++Itr) { if (!(*Itr)->IsA(u_class)) continue; ue_PyUObject *py_obj = ue_get_python_uobject(*Itr); if (!py_obj) continue; PyList_Append(ret, (PyObject *)py_obj); } return ret; } PyObject *py_unreal_engine_create_and_dispatch_when_ready(PyObject * self, PyObject * args) { PyObject *py_callable; int named_thread = (int)ENamedThreads::GameThread; if (!PyArg_ParseTuple(args, "O|i:create_and_dispatch_when_ready", &py_callable, &named_thread)) { return NULL; } if (!PyCallable_Check(py_callable)) return PyErr_Format(PyExc_TypeError, "argument is not callable"); Py_INCREF(py_callable); FGraphEventRef task = FFunctionGraphTask::CreateAndDispatchWhenReady([&]() { FScopePythonGIL gil; PyObject *ret = PyObject_CallObject(py_callable, nullptr); if (ret) { Py_DECREF(ret); } else { unreal_engine_py_log_error(); } Py_DECREF(py_callable); }, TStatId(), nullptr, (ENamedThreads::Type)named_thread); Py_BEGIN_ALLOW_THREADS; FTaskGraphInterface::Get().WaitUntilTaskCompletes(task); Py_END_ALLOW_THREADS; // TODO Implement signal triggering in addition to WaitUntilTaskCompletes // FTaskGraphInterface::Get().TriggerEventWhenTaskCompletes Py_RETURN_NONE; } #if PLATFORM_MAC PyObject *py_unreal_engine_main_thread_call(PyObject * self, PyObject * args) { PyObject *py_callable; if (!PyArg_ParseTuple(args, "O|:main_thread_call", &py_callable)) { return NULL; } if (!PyCallable_Check(py_callable)) return PyErr_Format(PyExc_TypeError, "argument is not callable"); Py_INCREF(py_callable); Py_BEGIN_ALLOW_THREADS; MainThreadCall(^{ FScopePythonGIL gil; PyObject *ret = PyObject_CallObject(py_callable, nullptr); if (ret) { Py_DECREF(ret); } else { unreal_engine_py_log_error(); } Py_DECREF(py_callable); }); Py_END_ALLOW_THREADS; Py_RETURN_NONE; } #endif PyObject *py_unreal_engine_get_game_viewport_size(PyObject *self, PyObject * args) { if (!GEngine->GameViewport) { return PyErr_Format(PyExc_Exception, "unable to get GameViewport"); } FVector2D size; GEngine->GameViewport->GetViewportSize(size); return Py_BuildValue("(ff)", size.X, size.Y); } PyObject *py_unreal_engine_get_resolution(PyObject *self, PyObject * args) { return Py_BuildValue("(ff)", GSystemResolution.ResX, GSystemResolution.ResY); } PyObject *py_unreal_engine_get_viewport_screenshot(PyObject *self, PyObject * args) { if (!GEngine->GameViewport) { Py_INCREF(Py_None); return Py_None; } PyObject *py_bool = nullptr; bool as_int_list = false; if (!PyArg_ParseTuple(args, "|O:get_viewport_screenshot", &py_bool)) { return NULL; } if (py_bool && PyObject_IsTrue(py_bool)) as_int_list = true; FViewport *viewport = GEngine->GameViewport->Viewport; TArray<FColor> bitmap; bool success = GetViewportScreenShot(viewport, bitmap); if (!success) { Py_INCREF(Py_None); return Py_None; } if (as_int_list) { PyObject *bitmap_tuple = PyTuple_New(bitmap.Num() * 4); for (int i = 0; i < bitmap.Num(); i++) { PyTuple_SetItem(bitmap_tuple, i * 4, PyLong_FromLong(bitmap[i].R)); PyTuple_SetItem(bitmap_tuple, i * 4 + 1, PyLong_FromLong(bitmap[i].G)); PyTuple_SetItem(bitmap_tuple, i * 4 + 2, PyLong_FromLong(bitmap[i].B)); PyTuple_SetItem(bitmap_tuple, i * 4 + 3, PyLong_FromLong(bitmap[i].A)); } return bitmap_tuple; } PyObject *bitmap_tuple = PyTuple_New(bitmap.Num()); for (int i = 0; i < bitmap.Num(); i++) { PyTuple_SetItem(bitmap_tuple, i, py_ue_new_fcolor(bitmap[i])); } return bitmap_tuple; } PyObject *py_unreal_engine_get_viewport_size(PyObject *self, PyObject * args) { if (!GEngine->GameViewport) { Py_INCREF(Py_None); return Py_None; } FViewport *viewport = GEngine->GameViewport->Viewport; PyObject *tuple_size = PyTuple_New(2); FIntPoint point = viewport->GetSizeXY(); PyTuple_SetItem(tuple_size, 0, PyLong_FromLong(point.X)); PyTuple_SetItem(tuple_size, 1, PyLong_FromLong(point.Y)); return tuple_size; } #if WITH_EDITOR PyObject *py_unreal_engine_editor_get_active_viewport_screenshot(PyObject *self, PyObject * args) { FViewport *viewport = GEditor->GetActiveViewport(); if (!viewport) { Py_INCREF(Py_None); return Py_None; } PyObject *py_bool = nullptr; bool as_int_list = false; if (!PyArg_ParseTuple(args, "|O:editor_get_active_viewport_screenshot", &py_bool)) { return NULL; } if (py_bool && PyObject_IsTrue(py_bool)) as_int_list = true; TArray<FColor> bitmap; bool success = GetViewportScreenShot(viewport, bitmap); if (!success) { Py_INCREF(Py_None); return Py_None; } if (as_int_list) { PyObject *bitmap_tuple = PyTuple_New(bitmap.Num() * 4); for (int i = 0; i < bitmap.Num(); i++) { PyTuple_SetItem(bitmap_tuple, i * 4, PyLong_FromLong(bitmap[i].R)); PyTuple_SetItem(bitmap_tuple, i * 4 + 1, PyLong_FromLong(bitmap[i].G)); PyTuple_SetItem(bitmap_tuple, i * 4 + 2, PyLong_FromLong(bitmap[i].B)); PyTuple_SetItem(bitmap_tuple, i * 4 + 3, PyLong_FromLong(bitmap[i].A)); } return bitmap_tuple; } PyObject *bitmap_tuple = PyTuple_New(bitmap.Num()); for (int i = 0; i < bitmap.Num(); i++) { PyTuple_SetItem(bitmap_tuple, i, py_ue_new_fcolor(bitmap[i])); } return bitmap_tuple; } PyObject *py_unreal_engine_editor_get_active_viewport_size(PyObject *self, PyObject * args) { FViewport *viewport = GEditor->GetActiveViewport(); if (!viewport) { Py_INCREF(Py_None); return Py_None; } PyObject *tuple_size = PyTuple_New(2); FIntPoint point = viewport->GetSizeXY(); PyTuple_SetItem(tuple_size, 0, PyLong_FromLong(point.X)); PyTuple_SetItem(tuple_size, 1, PyLong_FromLong(point.Y)); return tuple_size; } PyObject *py_unreal_engine_editor_get_pie_viewport_screenshot(PyObject *self, PyObject * args) { FViewport *viewport = GEditor->GetPIEViewport(); if (!viewport) { Py_INCREF(Py_None); return Py_None; } PyObject *py_bool = nullptr; bool as_int_list = false; if (!PyArg_ParseTuple(args, "|O:editor_get_pie_viewport_screenshot", &py_bool)) { return NULL; } if (py_bool && PyObject_IsTrue(py_bool)) as_int_list = true; TArray<FColor> bitmap; bool success = GetViewportScreenShot(viewport, bitmap); if (!success) { Py_INCREF(Py_None); return Py_None; } if (as_int_list) { PyObject *bitmap_tuple = PyTuple_New(bitmap.Num() * 4); for (int i = 0; i < bitmap.Num(); i++) { PyTuple_SetItem(bitmap_tuple, i * 4, PyLong_FromLong(bitmap[i].R)); PyTuple_SetItem(bitmap_tuple, i * 4 + 1, PyLong_FromLong(bitmap[i].G)); PyTuple_SetItem(bitmap_tuple, i * 4 + 2, PyLong_FromLong(bitmap[i].B)); PyTuple_SetItem(bitmap_tuple, i * 4 + 3, PyLong_FromLong(bitmap[i].A)); } return bitmap_tuple; } PyObject *bitmap_tuple = PyTuple_New(bitmap.Num()); for (int i = 0; i < bitmap.Num(); i++) { PyTuple_SetItem(bitmap_tuple, i, py_ue_new_fcolor(bitmap[i])); } return bitmap_tuple; } PyObject *py_unreal_engine_editor_get_pie_viewport_size(PyObject *self, PyObject * args) { FViewport *viewport = GEditor->GetPIEViewport(); if (!viewport) { Py_INCREF(Py_None); return Py_None; } PyObject *tuple_size = PyTuple_New(2); FIntPoint point = viewport->GetSizeXY(); PyTuple_SetItem(tuple_size, 0, PyLong_FromLong(point.X)); PyTuple_SetItem(tuple_size, 1, PyLong_FromLong(point.Y)); return tuple_size; } #endif PyObject *py_unreal_engine_create_package(PyObject *self, PyObject * args) { char *name; if (!PyArg_ParseTuple(args, "s:create_package", &name)) { return nullptr; } UPackage *u_package = (UPackage *)StaticFindObject(nullptr, ANY_PACKAGE, UTF8_TO_TCHAR(name), true); // create a new package if it does not exist if (u_package) { return PyErr_Format(PyExc_Exception, "package %s already exists", TCHAR_TO_UTF8(*u_package->GetPathName())); } u_package = CreatePackage(nullptr, UTF8_TO_TCHAR(name)); if (!u_package) return PyErr_Format(PyExc_Exception, "unable to create package"); u_package->FileName = *FPackageName::LongPackageNameToFilename(UTF8_TO_TCHAR(name), FPackageName::GetAssetPackageExtension()); u_package->FullyLoad(); u_package->MarkPackageDirty(); Py_RETURN_UOBJECT(u_package); } PyObject *py_unreal_engine_get_or_create_package(PyObject *self, PyObject * args) { char *name; if (!PyArg_ParseTuple(args, "s:get_or_create_package", &name)) { return nullptr; } UPackage *u_package = (UPackage *)StaticFindObject(nullptr, ANY_PACKAGE, UTF8_TO_TCHAR(name), true); // create a new package if it does not exist if (!u_package) { u_package = CreatePackage(nullptr, UTF8_TO_TCHAR(name)); if (!u_package) return PyErr_Format(PyExc_Exception, "unable to create package"); u_package->FileName = *FPackageName::LongPackageNameToFilename(UTF8_TO_TCHAR(name), FPackageName::GetAssetPackageExtension()); u_package->FullyLoad(); u_package->MarkPackageDirty(); } Py_RETURN_UOBJECT(u_package); } PyObject *py_unreal_engine_get_transient_package(PyObject *self, PyObject * args) { Py_RETURN_UOBJECT(GetTransientPackage()); } PyObject *py_unreal_engine_open_file_dialog(PyObject *self, PyObject * args) { char *title; char *default_path = (char *)""; char *default_file = (char *)""; char *file_types = (char *)""; PyObject *py_multiple = nullptr; if (!PyArg_ParseTuple(args, "s|sssO:open_file_dialog", &title, &default_path, &default_file, &file_types, &py_multiple)) return nullptr; IDesktopPlatform *DesktopPlatform = FDesktopPlatformModule::Get(); if (!DesktopPlatform) return PyErr_Format(PyExc_Exception, "unable to get reference to DesktopPlatform module"); TSharedPtr<SWindow> ParentWindow = FGlobalTabmanager::Get()->GetRootWindow(); if (!ParentWindow.IsValid()) return PyErr_Format(PyExc_Exception, "unable to get the Root Window"); if (!ParentWindow->GetNativeWindow().IsValid()) return PyErr_Format(PyExc_Exception, "unable to get Native Root Window"); TArray<FString> files; if (!DesktopPlatform->OpenFileDialog(ParentWindow->GetNativeWindow()->GetOSWindowHandle(), FString(UTF8_TO_TCHAR(title)), FString(UTF8_TO_TCHAR(default_path)), FString(UTF8_TO_TCHAR(default_file)), FString(UTF8_TO_TCHAR(file_types)), (py_multiple && PyObject_IsTrue(py_multiple)) ? EFileDialogFlags::Multiple : EFileDialogFlags::None, files)) { Py_RETURN_NONE; } PyObject *py_list = PyList_New(0); for (FString file : files) { PyList_Append(py_list, PyUnicode_FromString(TCHAR_TO_UTF8(*file))); } return py_list; } PyObject *py_unreal_engine_open_directory_dialog(PyObject *self, PyObject * args) { char *title; char *default_path = (char *)""; if (!PyArg_ParseTuple(args, "s|s:open_directory_dialog", &title, &default_path)) return nullptr; IDesktopPlatform *DesktopPlatform = FDesktopPlatformModule::Get(); if (!DesktopPlatform) return PyErr_Format(PyExc_Exception, "unable to get reference to DesktopPlatform module"); TSharedPtr<SWindow> ParentWindow = FGlobalTabmanager::Get()->GetRootWindow(); if (!ParentWindow.IsValid()) return PyErr_Format(PyExc_Exception, "unable to get the Root Window"); if (!ParentWindow->GetNativeWindow().IsValid()) return PyErr_Format(PyExc_Exception, "unable to get Native Root Window"); FString choosen_dir; if (!DesktopPlatform->OpenDirectoryDialog(ParentWindow->GetNativeWindow()->GetOSWindowHandle(), FString(UTF8_TO_TCHAR(title)), FString(UTF8_TO_TCHAR(default_path)), choosen_dir)) { Py_RETURN_NONE; } return PyUnicode_FromString(TCHAR_TO_UTF8(*choosen_dir)); } PyObject *py_unreal_engine_open_font_dialog(PyObject *self, PyObject * args) { IDesktopPlatform *DesktopPlatform = FDesktopPlatformModule::Get(); if (!DesktopPlatform) return PyErr_Format(PyExc_Exception, "unable to get reference to DesktopPlatform module"); TSharedPtr<SWindow> ParentWindow = FGlobalTabmanager::Get()->GetRootWindow(); if (!ParentWindow.IsValid()) return PyErr_Format(PyExc_Exception, "unable to get the Root Window"); if (!ParentWindow->GetNativeWindow().IsValid()) return PyErr_Format(PyExc_Exception, "unable to get Native Root Window"); FString font_name; float height; EFontImportFlags flags; if (!DesktopPlatform->OpenFontDialog(ParentWindow->GetNativeWindow()->GetOSWindowHandle(), font_name, height, flags)) { Py_RETURN_NONE; } return Py_BuildValue((char*)"(sfi)", TCHAR_TO_UTF8(*font_name), height, flags); } PyObject *py_unreal_engine_save_file_dialog(PyObject *self, PyObject * args) { char *title; char *default_path = (char *)""; char *default_file = (char *)""; char *file_types = (char *)""; PyObject *py_multiple = nullptr; if (!PyArg_ParseTuple(args, "s|sssO:save_file_dialog", &title, &default_path, &default_file, &file_types, &py_multiple)) return nullptr; IDesktopPlatform *DesktopPlatform = FDesktopPlatformModule::Get(); if (!DesktopPlatform) return PyErr_Format(PyExc_Exception, "unable to get reference to DesktopPlatform module"); TSharedPtr<SWindow> ParentWindow = FGlobalTabmanager::Get()->GetRootWindow(); if (!ParentWindow.IsValid()) return PyErr_Format(PyExc_Exception, "unable to get the Root Window"); if (!ParentWindow->GetNativeWindow().IsValid()) return PyErr_Format(PyExc_Exception, "unable to get Native Root Window"); TArray<FString> files; if (!DesktopPlatform->SaveFileDialog(ParentWindow->GetNativeWindow()->GetOSWindowHandle(), FString(UTF8_TO_TCHAR(title)), FString(UTF8_TO_TCHAR(default_path)), FString(UTF8_TO_TCHAR(default_file)), FString(UTF8_TO_TCHAR(file_types)), (py_multiple && PyObject_IsTrue(py_multiple)) ? EFileDialogFlags::Multiple : EFileDialogFlags::None, files)) { Py_RETURN_NONE; } PyObject *py_list = PyList_New(0); for (FString file : files) { PyList_Append(py_list, PyUnicode_FromString(TCHAR_TO_UTF8(*file))); } return py_list; } PyObject *py_unreal_engine_copy_properties_for_unrelated_objects(PyObject * self, PyObject * args, PyObject *kwargs) { PyObject *old_py_object; PyObject *new_py_object; PyObject *py_aggressive_default_subobject_replacement = nullptr; PyObject *py_copy_deprecated_properties = nullptr; PyObject *py_do_delta = nullptr; PyObject *py_notify_object_replacement = nullptr; PyObject *py_preserve_root_component = nullptr; PyObject *py_replace_object_class_references = nullptr; PyObject *py_skip_compiler_generated_defaults = nullptr; static char *kw_names[] = { (char *)"old_object", (char *)"new_object", (char *)"aggressive_default_subobject_replacement", (char *)"copy_deprecated_properties", (char *)"do_delta", (char *)"notify_object_replacement", (char *)"preserve_root_component", (char *)"replace_object_class_references", (char *)"skip_compiler_generated_defaults", nullptr }; if (!PyArg_ParseTupleAndKeywords(args, kwargs, "OO|OOOOOOO:copy_properties_for_unrelated_objects", kw_names, &old_py_object, &new_py_object, &py_aggressive_default_subobject_replacement, &py_copy_deprecated_properties, &py_do_delta, &py_notify_object_replacement, &py_preserve_root_component, &py_replace_object_class_references, &py_skip_compiler_generated_defaults)) { return nullptr; } UObject *old_object = ue_py_check_type<UObject>(old_py_object); if (!old_object) return PyErr_Format(PyExc_Exception, "argument is not a UObject"); UObject *new_object = ue_py_check_type<UObject>(new_py_object); if (!new_object) return PyErr_Format(PyExc_Exception, "argument is not a UObject"); UEngine::FCopyPropertiesForUnrelatedObjectsParams params; params.bAggressiveDefaultSubobjectReplacement = (py_aggressive_default_subobject_replacement && PyObject_IsTrue(py_aggressive_default_subobject_replacement)); params.bCopyDeprecatedProperties = (py_copy_deprecated_properties && PyObject_IsTrue(py_copy_deprecated_properties)); params.bDoDelta = (py_do_delta && PyObject_IsTrue(py_do_delta)); params.bNotifyObjectReplacement = (py_notify_object_replacement && PyObject_IsTrue(py_notify_object_replacement)); params.bPreserveRootComponent = (py_preserve_root_component && PyObject_IsTrue(py_preserve_root_component)); params.bReplaceObjectClassReferences = (py_replace_object_class_references && PyObject_IsTrue(py_replace_object_class_references)); params.bSkipCompilerGeneratedDefaults = (py_skip_compiler_generated_defaults && PyObject_IsTrue(py_skip_compiler_generated_defaults)); GEngine->CopyPropertiesForUnrelatedObjects( old_object, new_object, params); Py_RETURN_NONE; } PyObject *py_unreal_engine_set_random_seed(PyObject * self, PyObject * args) { int seed; if (!PyArg_ParseTuple(args, "i:set_random_seed", &seed)) { return nullptr; } // Thanks to Sven Mika (Ducandu GmbH) for spotting this FMath::RandInit(seed); FGenericPlatformMath::SRandInit(seed); FGenericPlatformMath::RandInit(seed); Py_RETURN_NONE; } PyObject *py_unreal_engine_clipboard_copy(PyObject * self, PyObject * args) { char *text; if (!PyArg_ParseTuple(args, "s:clipboard_copy", &text)) { return nullptr; } #if ENGINE_MINOR_VERSION >= 18 FPlatformApplicationMisc::ClipboardCopy(UTF8_TO_TCHAR(text)); #else FGenericPlatformMisc::ClipboardCopy(UTF8_TO_TCHAR(text)); #endif Py_RETURN_NONE; } PyObject *py_unreal_engine_clipboard_paste(PyObject * self, PyObject * args) { FString clipboard; #if ENGINE_MINOR_VERSION >= 18 FPlatformApplicationMisc::ClipboardPaste(clipboard); #else FGenericPlatformMisc::ClipboardPaste(clipboard); #endif return PyUnicode_FromString(TCHAR_TO_UTF8(*clipboard)); } ```
/content/code_sandbox/Source/UnrealEnginePython/Private/UEPyEngine.cpp
c++
2016-08-07T05:00:51
2024-08-14T06:32:20
UnrealEnginePython
20tab/UnrealEnginePython
2,715
9,107
```objective-c #pragma once #include "UEPyModule.h" typedef struct { PyObject_HEAD /* Type-specific fields go here. */ UFunction *u_function; UObject *u_target; } ue_PyCallable; PyObject *py_ue_new_callable(UFunction *, UObject *); ue_PyCallable *py_ue_is_callable(PyObject *); void ue_python_init_callable(PyObject *); ```
/content/code_sandbox/Source/UnrealEnginePython/Private/UEPyCallable.h
objective-c
2016-08-07T05:00:51
2024-08-14T06:32:20
UnrealEnginePython
20tab/UnrealEnginePython
2,715
77
```c++ #include "UEPyEnumsImporter.h" static PyObject *ue_PyEnumsImporter_getattro(ue_PyEnumsImporter *self, PyObject *attr_name) { PyObject *py_attr = PyObject_GenericGetAttr((PyObject *)self, attr_name); if (!py_attr) { if (PyUnicodeOrString_Check(attr_name)) { const char *attr = UEPyUnicode_AsUTF8(attr_name); if (attr[0] != '_') { UEnum *u_enum = FindObject<UEnum>(ANY_PACKAGE, UTF8_TO_TCHAR(attr)); if (u_enum) { // swallow old exception PyErr_Clear(); Py_RETURN_UOBJECT(u_enum); } } } } return py_attr; } static PyTypeObject ue_PyEnumsImporterType = { PyVarObject_HEAD_INIT(NULL, 0) "unreal_engine.EnumsImporter", /* tp_name */ sizeof(ue_PyEnumsImporter), /* tp_basicsize */ 0, /* tp_itemsize */ 0, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_reserved */ 0, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ (getattrofunc)ue_PyEnumsImporter_getattro, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT, /* tp_flags */ "Unreal Engine Enums Importer", /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ 0, /* tp_methods */ 0, 0, }; void ue_python_init_enumsimporter(PyObject *ue_module) { ue_PyEnumsImporterType.tp_new = PyType_GenericNew; if (PyType_Ready(&ue_PyEnumsImporterType) < 0) return; Py_INCREF(&ue_PyEnumsImporterType); PyModule_AddObject(ue_module, "EnumsImporter", (PyObject *)&ue_PyEnumsImporterType); } PyObject *py_ue_new_enumsimporter() { ue_PyEnumsImporter *ret = (ue_PyEnumsImporter *)PyObject_New(ue_PyEnumsImporter, &ue_PyEnumsImporterType); return (PyObject *)ret; } ```
/content/code_sandbox/Source/UnrealEnginePython/Private/UEPyEnumsImporter.cpp
c++
2016-08-07T05:00:51
2024-08-14T06:32:20
UnrealEnginePython
20tab/UnrealEnginePython
2,715
594
```objective-c #pragma once #include "UEPyModule.h" #if WITH_EDITOR #include "EditorFramework/AssetImportData.h" PyObject *py_ue_asset_import_data(ue_PyUObject *, PyObject *); PyObject *py_ue_asset_import_data_set_sources(ue_PyUObject *, PyObject *); #endif ```
/content/code_sandbox/Source/UnrealEnginePython/Private/UEPyAssetUserData.h
objective-c
2016-08-07T05:00:51
2024-08-14T06:32:20
UnrealEnginePython
20tab/UnrealEnginePython
2,715
61
```c++ #include "PythonDelegate.h" #include "UEPyModule.h" #include "UEPyCallable.h" UPythonDelegate::UPythonDelegate() { py_callable = nullptr; signature_set = false; } void UPythonDelegate::SetPyCallable(PyObject *callable) { // do not acquire the gil here as we set the callable in python call themselves py_callable = callable; Py_INCREF(py_callable); } void UPythonDelegate::SetSignature(UFunction *original_signature) { signature = original_signature; signature_set = true; } void UPythonDelegate::ProcessEvent(UFunction *function, void *Parms) { if (!py_callable) return; FScopePythonGIL gil; PyObject *py_args = nullptr; if (signature_set) { py_args = PyTuple_New(signature->NumParms); Py_ssize_t argn = 0; TFieldIterator<UProperty> PArgs(signature); for (; PArgs && argn < signature->NumParms && ((PArgs->PropertyFlags & (CPF_Parm | CPF_ReturnParm)) == CPF_Parm); ++PArgs) { UProperty *prop = *PArgs; PyObject *arg = ue_py_convert_property(prop, (uint8 *)Parms, 0); if (!arg) { unreal_engine_py_log_error(); Py_DECREF(py_args); return; } PyTuple_SetItem(py_args, argn, arg); argn++; } } PyObject *ret = PyObject_CallObject(py_callable, py_args); Py_XDECREF(py_args); if (!ret) { unreal_engine_py_log_error(); return; } // currently useless as events do not return a value /* if (signature_set) { UProperty *return_property = signature->GetReturnProperty(); if (return_property && signature->ReturnValueOffset != MAX_uint16) { if (!ue_py_convert_pyobject(ret, return_property, (uint8 *)Parms)) { UE_LOG(LogPython, Error, TEXT("Invalid return value type for delegate")); } } } */ Py_DECREF(ret); } void UPythonDelegate::PyFakeCallable() { } void UPythonDelegate::PyInputHandler() { FScopePythonGIL gil; PyObject *ret = PyObject_CallObject(py_callable, NULL); if (!ret) { unreal_engine_py_log_error(); return; } Py_DECREF(ret); } void UPythonDelegate::PyInputAxisHandler(float value) { FScopePythonGIL gil; PyObject *ret = PyObject_CallFunction(py_callable, (char *)"f", value); if (!ret) { unreal_engine_py_log_error(); return; } Py_DECREF(ret); } bool UPythonDelegate::UsesPyCallable(PyObject *other) { ue_PyCallable *other_callable = (ue_PyCallable*)other; ue_PyCallable *this_callable = (ue_PyCallable*)py_callable; return other_callable->u_function == this_callable->u_function && other_callable->u_target == this_callable->u_target; } UPythonDelegate::~UPythonDelegate() { FScopePythonGIL gil; Py_XDECREF(py_callable); #if defined(UEPY_MEMORY_DEBUG) UE_LOG(LogPython, Warning, TEXT("PythonDelegate %p callable XDECREF'ed"), this); #endif } ```
/content/code_sandbox/Source/UnrealEnginePython/Private/PythonDelegate.cpp
c++
2016-08-07T05:00:51
2024-08-14T06:32:20
UnrealEnginePython
20tab/UnrealEnginePython
2,715
722
```c++ #include "UEPySImage.h" #include "Engine/Texture2D.h" static PyObject *py_ue_simage_set_brush(ue_PySImage *self, PyObject * args) { ue_py_slate_cast(SImage); PyObject *py_brush; if (!PyArg_ParseTuple(args, "O:set_brush", &py_brush)) { return nullptr; } FSlateBrush *brush = ue_py_check_struct<FSlateBrush>(py_brush); if (!brush) return PyErr_Format(PyExc_Exception, "argument is not a FSlateBrush"); self->brush = *brush; py_SImage->SetImage(&self->brush); Py_RETURN_SLATE_SELF; } static PyObject *py_ue_simage_set_texture(ue_PySImage *self, PyObject * args) { ue_py_slate_cast(SImage); PyObject *py_texture; PyObject *py_linear_color = nullptr; if (!PyArg_ParseTuple(args, "O|O:set_texture", &py_texture, &py_linear_color)) { return nullptr; } UTexture2D *texture = ue_py_check_type<UTexture2D>(py_texture); if (!texture) return PyErr_Format(PyExc_Exception, "argument is not a Texture"); FLinearColor tint(1, 1, 1, 1); if (py_linear_color) { ue_PyFLinearColor *py_color = py_ue_is_flinearcolor(py_linear_color); if (!py_color) { return PyErr_Format(PyExc_Exception, "argument is not a FLinearColor"); } tint = py_color->color; } #if ENGINE_MINOR_VERSION > 15 self->brush = FSlateImageBrush(texture, FVector2D(texture->GetSurfaceWidth(), texture->GetSurfaceHeight()), tint); #else self->brush = FSlateBrush(); self->brush.ImageSize = FVector2D(texture->GetSurfaceWidth(), texture->GetSurfaceHeight()); self->brush.SetResourceObject(texture); self->brush.TintColor = tint; #endif py_SImage->SetImage(&self->brush); Py_RETURN_SLATE_SELF; } static PyMethodDef ue_PySImage_methods[] = { { "set_brush", (PyCFunction)py_ue_simage_set_brush, METH_VARARGS, "" }, { "set_image", (PyCFunction)py_ue_simage_set_brush, METH_VARARGS, "" }, { "set_texture", (PyCFunction)py_ue_simage_set_texture, METH_VARARGS, "" }, { NULL } /* Sentinel */ }; PyTypeObject ue_PySImageType = { PyVarObject_HEAD_INIT(NULL, 0) "unreal_engine.SImage", /* tp_name */ sizeof(ue_PySImage), /* tp_basicsize */ 0, /* tp_itemsize */ 0, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_reserved */ 0, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ 0, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ "Unreal Engine SImage", /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ ue_PySImage_methods, /* tp_methods */ }; static int ue_py_simage_init(ue_PySImage *self, PyObject *args, PyObject *kwargs) { ue_py_slate_setup_farguments(SImage); ue_py_slate_farguments_struct("color_and_opacity", ColorAndOpacity, FSlateColor); ue_py_slate_farguments_optional_struct_ptr("image", Image, FSlateBrush); ue_py_slate_farguments_event("on_mouse_button_down", OnMouseButtonDown, FPointerEventHandler, OnMouseEvent); ue_py_snew(SImage); return 0; } void ue_python_init_simage(PyObject *ue_module) { ue_PySImageType.tp_init = (initproc)ue_py_simage_init; ue_PySImageType.tp_base = &ue_PySLeafWidgetType; if (PyType_Ready(&ue_PySImageType) < 0) return; Py_INCREF(&ue_PySImageType); PyModule_AddObject(ue_module, "SImage", (PyObject *)&ue_PySImageType); } ```
/content/code_sandbox/Source/UnrealEnginePython/Private/Slate/UEPySImage.cpp
c++
2016-08-07T05:00:51
2024-08-14T06:32:20
UnrealEnginePython
20tab/UnrealEnginePython
2,715
1,058
```objective-c #pragma once #include "UEPySCompoundWidget.h" #include "Runtime/Slate/Public/Widgets/SViewport.h" extern PyTypeObject ue_PySViewportType; typedef struct { ue_PySCompoundWidget s_compound_widget; /* Type-specific fields go here. */ } ue_PySViewport; void ue_python_init_sviewport(PyObject *); ```
/content/code_sandbox/Source/UnrealEnginePython/Private/Slate/UEPySViewport.h
objective-c
2016-08-07T05:00:51
2024-08-14T06:32:20
UnrealEnginePython
20tab/UnrealEnginePython
2,715
76
```objective-c #pragma once #include "UEPyModule.h" #include "Runtime/SlateCore/Public/Layout/Geometry.h" typedef struct { PyObject_HEAD /* Type-specific fields go here. */ FGeometry geometry; } ue_PyFGeometry; void ue_python_init_fgeometry(PyObject *); ue_PyFGeometry *py_ue_is_fgeometry(PyObject *); PyObject *py_ue_new_fgeometry(FGeometry); ```
/content/code_sandbox/Source/UnrealEnginePython/Private/Slate/UEPyFGeometry.h
objective-c
2016-08-07T05:00:51
2024-08-14T06:32:20
UnrealEnginePython
20tab/UnrealEnginePython
2,715
84
```c++ #include "UEPySSlider.h" static PyObject *py_ue_sslider_set_value(ue_PySSlider *self, PyObject * args) { ue_py_slate_cast(SSlider); float value; if (!PyArg_ParseTuple(args, "f:set_value", &value)) { return nullptr; } py_SSlider->SetValue(value); Py_RETURN_SLATE_SELF; } static PyObject *py_ue_sslider_get_value(ue_PySSlider *self, PyObject * args) { ue_py_slate_cast(SSlider); return PyFloat_FromDouble(py_SSlider->GetValue()); } static PyMethodDef ue_PySSlider_methods[] = { { "set_value", (PyCFunction)py_ue_sslider_set_value, METH_VARARGS, "" }, { "get_value", (PyCFunction)py_ue_sslider_get_value, METH_VARARGS, "" }, { NULL } /* Sentinel */ }; PyTypeObject ue_PySSliderType = { PyVarObject_HEAD_INIT(NULL, 0) "unreal_engine.SSlider", /* tp_name */ sizeof(ue_PySSlider), /* tp_basicsize */ 0, /* tp_itemsize */ 0, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_reserved */ 0, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ 0, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ "Unreal Engine SSlider", /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ ue_PySSlider_methods, /* tp_methods */ }; static int ue_py_sslider_init(ue_PySSlider *self, PyObject *args, PyObject *kwargs) { ue_py_slate_setup_farguments(SSlider); ue_py_slate_farguments_bool("indent_handle", IndentHandle); ue_py_slate_farguments_optional_bool("is_focusable", IsFocusable); ue_py_slate_farguments_bool("locked", Locked); ue_py_slate_farguments_event("on_controller_capture_begin", OnControllerCaptureBegin, FSimpleDelegate, SimpleExecuteAction); ue_py_slate_farguments_event("on_controller_capture_end", OnControllerCaptureEnd, FSimpleDelegate, SimpleExecuteAction); ue_py_slate_farguments_event("on_mouse_capture_begin", OnMouseCaptureBegin, FSimpleDelegate, SimpleExecuteAction); ue_py_slate_farguments_event("on_mouse_capture_end", OnMouseCaptureEnd, FSimpleDelegate, SimpleExecuteAction); ue_py_slate_farguments_event("on_value_changed", OnValueChanged, FOnFloatValueChanged, OnFloatChanged); ue_py_slate_farguments_optional_enum("orientation", Orientation, EOrientation); ue_py_slate_farguments_struct("slider_bar_color", SliderBarColor, FSlateColor); ue_py_slate_farguments_struct("slider_handle_color", SliderHandleColor, FSlateColor); ue_py_slate_farguments_float("step_size", StepSize); ue_py_slate_farguments_optional_struct_ptr("style", Style, FSliderStyle); ue_py_slate_farguments_float("value", Value); ue_py_snew(SSlider); return 0; } void ue_python_init_sslider(PyObject *ue_module) { ue_PySSliderType.tp_init = (initproc)ue_py_sslider_init; ue_PySSliderType.tp_base = &ue_PySLeafWidgetType; if (PyType_Ready(&ue_PySSliderType) < 0) return; Py_INCREF(&ue_PySSliderType); PyModule_AddObject(ue_module, "SSlider", (PyObject *)&ue_PySSliderType); } ```
/content/code_sandbox/Source/UnrealEnginePython/Private/Slate/UEPySSlider.cpp
c++
2016-08-07T05:00:51
2024-08-14T06:32:20
UnrealEnginePython
20tab/UnrealEnginePython
2,715
922
```c++ #include "UEPyFCharacterEvent.h" #include "UEPyFModifierKeysState.h" static PyObject *py_ue_fcharacter_event_get_character(ue_PyFCharacterEvent *self, PyObject * args) { TCHAR c = self->character_event.GetCharacter(); FString s = FString(1, &c); return PyUnicode_FromString(TCHAR_TO_UTF8(*s)); } static PyMethodDef ue_PyFCharacterEvent_methods[] = { { "get_character", (PyCFunction)py_ue_fcharacter_event_get_character, METH_VARARGS, "" }, { NULL } /* Sentinel */ }; static PyObject *ue_PyFCharacterEvent_str(ue_PyFCharacterEvent *self) { TCHAR c = self->character_event.GetCharacter(); FString s = FString(1, &c); return PyUnicode_FromFormat("<unreal_engine.FCharacterEvent '%s'>", TCHAR_TO_UTF8(*s)); } static PyTypeObject ue_PyFCharacterEventType = { PyVarObject_HEAD_INIT(NULL, 0) "unreal_engine.FCharacterEvent", /* tp_name */ sizeof(ue_PyFCharacterEvent), /* tp_basicsize */ 0, /* tp_itemsize */ 0, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_reserved */ 0, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ (reprfunc)ue_PyFCharacterEvent_str, /* tp_str */ 0, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ "Unreal Engine FCharacterEvent", /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ ue_PyFCharacterEvent_methods, /* tp_methods */ }; static int ue_py_fcharacter_event_init(ue_PyFCharacterEvent *self, PyObject *args, PyObject *kwargs) { char *key; PyObject *py_repeat = nullptr; PyObject *py_modifier = nullptr; if (!PyArg_ParseTuple(args, "sO|O", &key, &py_repeat, &py_modifier)) { return -1; } FModifierKeysState modifier; if (py_modifier) { ue_PyFModifierKeysState *f_modifier = py_ue_is_fmodifier_keys_state(py_modifier); if (!f_modifier) { PyErr_SetString(PyExc_Exception, "argument is not a FModifierKeysState"); return -1; } modifier = f_modifier->modifier; } FCharacterEvent Event(*UTF8_TO_TCHAR(key), modifier, 0, (py_repeat && PyObject_IsTrue(py_repeat))); new(&self->character_event) FCharacterEvent(Event); new(&self->f_input.input) FInputEvent(Event); return 0; } void ue_python_init_fcharacter_event(PyObject *ue_module) { ue_PyFCharacterEventType.tp_base = &ue_PyFInputEventType; ue_PyFCharacterEventType.tp_init = (initproc)ue_py_fcharacter_event_init; if (PyType_Ready(&ue_PyFCharacterEventType) < 0) return; Py_INCREF(&ue_PyFCharacterEventType); PyModule_AddObject(ue_module, "FCharacterEvent", (PyObject *)&ue_PyFCharacterEventType); } PyObject *py_ue_new_fcharacter_event(FCharacterEvent key_event) { ue_PyFCharacterEvent *ret = (ue_PyFCharacterEvent *)PyObject_New(ue_PyFCharacterEvent, &ue_PyFCharacterEventType); new(&ret->character_event) FCharacterEvent(key_event); new(&ret->f_input.input) FInputEvent(key_event); return (PyObject *)ret; } ue_PyFCharacterEvent *py_ue_is_fcharacter_event(PyObject *obj) { if (!PyObject_IsInstance(obj, (PyObject *)&ue_PyFCharacterEventType)) return nullptr; return (ue_PyFCharacterEvent *)obj; } ```
/content/code_sandbox/Source/UnrealEnginePython/Private/Slate/UEPyFCharacterEvent.cpp
c++
2016-08-07T05:00:51
2024-08-14T06:32:20
UnrealEnginePython
20tab/UnrealEnginePython
2,715
962
```objective-c #pragma once #include "UEPySEditorViewport.h" #if WITH_EDITOR #include "Editor/LevelEditor/Public/SLevelViewport.h" #include "Editor/LevelEditor/Private/SLevelEditor.h" #include "Editor/UnrealEd/Public/EditorViewportClient.h" #include "Runtime/Engine/Public/PreviewScene.h" extern PyTypeObject ue_PySLevelViewportType; typedef struct { ue_PySEditorViewport s_editor_viewport; /* Type-specific fields go here. */ } ue_PySLevelViewport; void ue_python_init_slevel_viewport(PyObject *); #endif ```
/content/code_sandbox/Source/UnrealEnginePython/Private/Slate/UEPySLevelViewport.h
objective-c
2016-08-07T05:00:51
2024-08-14T06:32:20
UnrealEnginePython
20tab/UnrealEnginePython
2,715
122
```objective-c #pragma once #include "UnrealEnginePython.h" #include "UEPySCompoundWidget.h" #include "Runtime/Slate/Public/Widgets/Input/SRotatorInputBox.h" extern PyTypeObject ue_PySRotatorInputBoxType; typedef struct { ue_PySCompoundWidget s_compound_widget; /* Type-specific fields go here. */ } ue_PySRotatorInputBox; void ue_python_init_srotator_input_box(PyObject *); ```
/content/code_sandbox/Source/UnrealEnginePython/Private/Slate/UEPySRotatorInputBox.h
objective-c
2016-08-07T05:00:51
2024-08-14T06:32:20
UnrealEnginePython
20tab/UnrealEnginePython
2,715
96
```objective-c #pragma once #include "UEPySCompoundWidget.h" #include "Runtime/Slate/Public/Widgets/Input/SVectorInputBox.h" extern PyTypeObject ue_PySVectorInputBoxType; typedef struct { ue_PySCompoundWidget s_compound_widget; /* Type-specific fields go here. */ } ue_PySVectorInputBox; void ue_python_init_svector_input_box(PyObject *); ```
/content/code_sandbox/Source/UnrealEnginePython/Private/Slate/UEPySVectorInputBox.h
objective-c
2016-08-07T05:00:51
2024-08-14T06:32:20
UnrealEnginePython
20tab/UnrealEnginePython
2,715
85
```c++ #include "UEPyFTabManager.h" static PyMethodDef ue_PyFTabManager_methods[] = { { NULL } /* Sentinel */ }; static PyObject *ue_PyFTabManager_str(ue_PyFTabManager *self) { return PyUnicode_FromFormat("<unreal_engine.FTabManager %p srefs %d>", &self->tab_manager.Get(), self->tab_manager.GetSharedReferenceCount()); } static PyTypeObject ue_PyFTabManagerType = { PyVarObject_HEAD_INIT(NULL, 0) "unreal_engine.FTabManager", /* tp_name */ sizeof(ue_PyFTabManager), /* tp_basicsize */ 0, /* tp_itemsize */ 0, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_reserved */ 0, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ (reprfunc)ue_PyFTabManager_str, /* tp_str */ 0, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT, /* tp_flags */ "Unreal Engine FTabManager", /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ ue_PyFTabManager_methods, /* tp_methods */ }; void ue_python_init_ftab_manager(PyObject *ue_module) { ue_PyFTabManagerType.tp_new = PyType_GenericNew; if (PyType_Ready(&ue_PyFTabManagerType) < 0) return; Py_INCREF(&ue_PyFTabManagerType); PyModule_AddObject(ue_module, "FTabManager", (PyObject *)&ue_PyFTabManagerType); } PyObject *py_ue_new_ftab_manager(TSharedRef<FTabManager> tab_manager) { ue_PyFTabManager *ret = (ue_PyFTabManager *)PyObject_New(ue_PyFTabManager, &ue_PyFTabManagerType); new(&ret->tab_manager) TSharedRef<FTabManager>(tab_manager); return (PyObject *)ret; } ```
/content/code_sandbox/Source/UnrealEnginePython/Private/Slate/UEPyFTabManager.cpp
c++
2016-08-07T05:00:51
2024-08-14T06:32:20
UnrealEnginePython
20tab/UnrealEnginePython
2,715
556
```c++ #include "UEPyIDetailsView.h" #if WITH_EDITOR #include "Editor/PropertyEditor/Public/IDetailsView.h" static PyObject *py_ue_idetails_view_set_object(ue_PyIDetailsView *self, PyObject * args, PyObject *kwargs) { ue_py_slate_cast(IDetailsView); PyObject *py_in_obj = nullptr; PyObject *py_force_refresh = nullptr; char *kwlist[] = { (char *)"uobject", (char *)"force_refresh", nullptr }; if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O|O:set_object", kwlist, &py_in_obj, &py_force_refresh)) { return nullptr; } UObject *u_object = ue_py_check_type<UObject>(py_in_obj); if (!u_object) { return PyErr_Format(PyExc_Exception, "argument is not a UObject"); } const bool bForceRefresh = py_force_refresh && PyObject_IsTrue(py_force_refresh); py_IDetailsView->SetObject(u_object, bForceRefresh); Py_RETURN_NONE; } static PyMethodDef ue_PyIDetailsView_methods[] = { #pragma warning(suppress: 4191) { "set_object", (PyCFunction)py_ue_idetails_view_set_object, METH_VARARGS | METH_KEYWORDS, "" }, { NULL } /* Sentinel */ }; PyTypeObject ue_PyIDetailsViewType = { PyVarObject_HEAD_INIT(NULL, 0) "unreal_engine.IDetailsView", /* tp_name */ sizeof(ue_PyIDetailsView), /* tp_basicsize */ 0, /* tp_itemsize */ 0, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_reserved */ 0, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ 0, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ "Unreal Engine IDetailsView", /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ ue_PyIDetailsView_methods, /* tp_methods */ }; void ue_python_init_idetails_view(PyObject *ue_module) { ue_PyIDetailsViewType.tp_base = &ue_PySCompoundWidgetType; if (PyType_Ready(&ue_PyIDetailsViewType) < 0) return; Py_INCREF(&ue_PyIDetailsViewType); PyModule_AddObject(ue_module, "IDetailsView", (PyObject *)&ue_PyIDetailsViewType); } ue_PyIDetailsView *py_ue_is_idetails_view(PyObject *obj) { if (!PyObject_IsInstance(obj, (PyObject *)&ue_PyIDetailsViewType)) return nullptr; return (ue_PyIDetailsView *)obj; } #endif ```
/content/code_sandbox/Source/UnrealEnginePython/Private/Slate/UEPyIDetailsView.cpp
c++
2016-08-07T05:00:51
2024-08-14T06:32:20
UnrealEnginePython
20tab/UnrealEnginePython
2,715
725
```objective-c #pragma once #include "UnrealEnginePython.h" #include "UEPySPanel.h" #include "Runtime/SlateCore/Public/Widgets/SOverlay.h" extern PyTypeObject ue_PySOverlayType; typedef struct { ue_PySPanel s_panel; /* Type-specific fields go here. */ } ue_PySOverlay; void ue_python_init_soverlay(PyObject *); ```
/content/code_sandbox/Source/UnrealEnginePython/Private/Slate/UEPySOverlay.h
objective-c
2016-08-07T05:00:51
2024-08-14T06:32:20
UnrealEnginePython
20tab/UnrealEnginePython
2,715
80
```c++ #include "UEPySViewport.h" static PyObject *py_ue_sviewport_enable_stereo_rendering(ue_PySViewport *self, PyObject * args) { ue_py_slate_cast(SViewport); PyObject *py_bool; if (!PyArg_ParseTuple(args, "O:enable_stereo_rendering", &py_bool)) { return NULL; } py_SViewport->EnableStereoRendering(PyObject_IsTrue(py_bool) ? true : false); Py_RETURN_SLATE_SELF; } static PyMethodDef ue_PySViewport_methods[] = { { "enable_stereo_rendering", (PyCFunction)py_ue_sviewport_enable_stereo_rendering, METH_VARARGS, "" }, { NULL } /* Sentinel */ }; PyTypeObject ue_PySViewportType = { PyVarObject_HEAD_INIT(NULL, 0) "unreal_engine.SViewport", /* tp_name */ sizeof(ue_PySViewport), /* tp_basicsize */ 0, /* tp_itemsize */ 0, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_reserved */ 0, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ 0, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ "Unreal Engine SViewport", /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ ue_PySViewport_methods, /* tp_methods */ }; static int ue_py_sviewport_init(ue_PySViewport *self, PyObject *args, PyObject *kwargs) { ue_py_snew_simple(SViewport); return 0; } void ue_python_init_sviewport(PyObject *ue_module) { ue_PySViewportType.tp_init = (initproc)ue_py_sviewport_init; ue_PySViewportType.tp_base = &ue_PySCompoundWidgetType; if (PyType_Ready(&ue_PySViewportType) < 0) return; Py_INCREF(&ue_PySViewportType); PyModule_AddObject(ue_module, "SViewport", (PyObject *)&ue_PySViewportType); } ```
/content/code_sandbox/Source/UnrealEnginePython/Private/Slate/UEPySViewport.cpp
c++
2016-08-07T05:00:51
2024-08-14T06:32:20
UnrealEnginePython
20tab/UnrealEnginePython
2,715
587
```objective-c #pragma once #include "UnrealEnginePython.h" #include "UEPySLeafWidget.h" #include "Runtime/Slate/Public/Widgets/Notifications/SProgressBar.h" extern PyTypeObject ue_PySProgressBarType; typedef struct { ue_PySLeafWidget s_leaf_widget; /* Type-specific fields go here. */ } ue_PySProgressBar; void ue_python_init_sprogress_bar(PyObject *); ```
/content/code_sandbox/Source/UnrealEnginePython/Private/Slate/UEPySProgressBar.h
objective-c
2016-08-07T05:00:51
2024-08-14T06:32:20
UnrealEnginePython
20tab/UnrealEnginePython
2,715
85
```objective-c #pragma once #include "UnrealEnginePython.h" #include "UEPySPanel.h" #include "Runtime/Slate/Public/Widgets/Input/SComboBox.h" extern PyTypeObject ue_PySPythonComboBoxType; class SPythonComboBox : public SComboBox<TSharedPtr<FPythonItem>> { public: ~SPythonComboBox() { if (PythonOptionsSource) delete(PythonOptionsSource); } const TArray<TSharedPtr<FPythonItem>> *PythonOptionsSource; }; typedef struct { ue_PySPanel s_panel; /* Type-specific fields go here. */ } ue_PySPythonComboBox; void ue_python_init_spython_combo_box(PyObject *); ```
/content/code_sandbox/Source/UnrealEnginePython/Private/Slate/UEPySPythonComboBox.h
objective-c
2016-08-07T05:00:51
2024-08-14T06:32:20
UnrealEnginePython
20tab/UnrealEnginePython
2,715
140
```objective-c #pragma once #include "UnrealEnginePython.h" #include "UEPySPanel.h" #include "Runtime/Slate/Public/Widgets/Layout/SGridPanel.h" extern PyTypeObject ue_PySGridPanelType; typedef struct { ue_PySPanel s_panel; /* Type-specific fields go here. */ } ue_PySGridPanel; void ue_python_init_sgrid_panel(PyObject *); ```
/content/code_sandbox/Source/UnrealEnginePython/Private/Slate/UEPySGridPanel.h
objective-c
2016-08-07T05:00:51
2024-08-14T06:32:20
UnrealEnginePython
20tab/UnrealEnginePython
2,715
84
```c++ #include "UEPySPythonComboBox.h" static PyObject *py_ue_spython_combo_box_clear_selection(ue_PySPythonComboBox *self, PyObject * args) { ue_py_slate_cast(SPythonComboBox); py_SPythonComboBox->ClearSelection(); Py_RETURN_SLATE_SELF; } static PyObject *py_ue_spython_combo_box_get_selected_item(ue_PySPythonComboBox *self, PyObject * args) { ue_py_slate_cast(SPythonComboBox); TSharedPtr<FPythonItem> ptr_item = py_SPythonComboBox->GetSelectedItem(); if (!ptr_item.IsValid()) return PyErr_Format(PyExc_Exception, "invalid shared pointer to python item"); Py_INCREF(ptr_item->py_object); return ptr_item->py_object; } static PyObject *py_ue_spython_combo_box_set_selected_item(ue_PySPythonComboBox *self, PyObject * args) { ue_py_slate_cast(SPythonComboBox); PyObject *py_item; if (!PyArg_ParseTuple(args, "O", &py_item)) { return nullptr; } for (TSharedPtr<FPythonItem> item : *(py_SPythonComboBox->PythonOptionsSource)) { // just for being safe if (!item.IsValid()) continue; if (py_item == item->py_object) { py_SPythonComboBox->SetSelectedItem(item); break; } } Py_RETURN_SLATE_SELF; } static PyMethodDef ue_PySPythonComboBox_methods[] = { { "clear_selection", (PyCFunction)py_ue_spython_combo_box_clear_selection, METH_VARARGS, "" }, { "get_selected_item", (PyCFunction)py_ue_spython_combo_box_get_selected_item, METH_VARARGS, "" }, { "set_selected_item", (PyCFunction)py_ue_spython_combo_box_set_selected_item, METH_VARARGS, "" }, { NULL } /* Sentinel */ }; PyTypeObject ue_PySPythonComboBoxType = { PyVarObject_HEAD_INIT(NULL, 0) "unreal_engine.SPythonComboBox", /* tp_name */ sizeof(ue_PySPythonComboBox), /* tp_basicsize */ 0, /* tp_itemsize */ 0, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_reserved */ 0, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ 0, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ "Unreal Engine SPythonComboBox", /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ ue_PySPythonComboBox_methods, /* tp_methods */ }; static int ue_py_spython_combo_box_init(ue_PySPythonComboBox *self, PyObject *args, PyObject *kwargs) { ue_py_slate_setup_farguments(SPythonComboBox); // first of all check for values PyObject *values = ue_py_dict_get_item(kwargs, "options_source"); if (!values) { PyErr_SetString(PyExc_Exception, "you must specify the combo box items"); return -1; } values = PyObject_GetIter(values); if (!values) { PyErr_SetString(PyExc_Exception, "values field is not an iterable"); return -1; } TArray<TSharedPtr<FPythonItem>> *items = new TArray<TSharedPtr<FPythonItem>>(); while (PyObject *item = PyIter_Next(values)) { Py_INCREF(item); items->Add(TSharedPtr<FPythonItem>(new FPythonItem(item))); } Py_DECREF(values); arguments.OptionsSource(items); TSharedPtr<SWidget> child = nullptr; PyObject *content = ue_py_dict_get_item(kwargs, "content"); if (content) { child = py_ue_is_swidget<SWidget>(content); if (!child.IsValid()) { return -1; } arguments.Content()[child.ToSharedRef()]; } ue_py_slate_farguments_optional_struct_ptr("button_style", ButtonStyle, FButtonStyle); ue_py_slate_farguments_struct("content_padding", ContentPadding, FMargin); #if ENGINE_MINOR_VERSION > 13 ue_py_slate_farguments_optional_bool("enable_gamepad_navigation_mode", EnableGamepadNavigationMode); #endif ue_py_slate_farguments_struct("foreground_color", ForegroundColor, FSlateColor); ue_py_slate_farguments_optional_bool("has_down_arrow", HasDownArrow); #if ENGINE_MINOR_VERSION > 12 ue_py_slate_farguments_optional_struct_ptr("item_style", ItemStyle, FTableRowStyle); #endif ue_py_slate_farguments_optional_float("max_list_height", MaxListHeight); ue_py_slate_farguments_optional_enum("method", Method, EPopupMethod); ue_py_slate_farguments_optional_struct("pressed_sound_override", PressedSoundOverride, FSlateSound); ue_py_slate_farguments_optional_struct("selection_change_sound_override", SelectionChangeSoundOverride, FSlateSound); ue_py_slate_farguments_event("on_generate_widget", OnGenerateWidget, TSlateDelegates<TSharedPtr<FPythonItem>>::FOnGenerateWidget, OnGenerateWidget); ue_py_slate_farguments_event("on_selection_changed", OnSelectionChanged, TSlateDelegates<TSharedPtr<FPythonItem>>::FOnSelectionChanged, OnSelectionChanged); ue_py_snew(SPythonComboBox); ue_py_slate_cast(SPythonComboBox); // keep track of the list, so we can delete on destruction py_SPythonComboBox->PythonOptionsSource = items; return 0; } void ue_python_init_spython_combo_box(PyObject *ue_module) { ue_PySPythonComboBoxType.tp_base = &ue_PySPanelType; ue_PySPythonComboBoxType.tp_init = (initproc)ue_py_spython_combo_box_init; if (PyType_Ready(&ue_PySPythonComboBoxType) < 0) return; Py_INCREF(&ue_PySPythonComboBoxType); PyModule_AddObject(ue_module, "SPythonComboBox", (PyObject *)&ue_PySPythonComboBoxType); } ```
/content/code_sandbox/Source/UnrealEnginePython/Private/Slate/UEPySPythonComboBox.cpp
c++
2016-08-07T05:00:51
2024-08-14T06:32:20
UnrealEnginePython
20tab/UnrealEnginePython
2,715
1,430
```objective-c #pragma once #include "UEPyModule.h" #include "Runtime/SlateCore/Public/Input/Events.h" typedef struct { PyObject_HEAD /* Type-specific fields go here. */ FInputEvent input; } ue_PyFInputEvent; void ue_python_init_finput_event(PyObject *); PyObject *py_ue_new_finput_event(FInputEvent); ```
/content/code_sandbox/Source/UnrealEnginePython/Private/Slate/UEPyFInputEvent.h
objective-c
2016-08-07T05:00:51
2024-08-14T06:32:20
UnrealEnginePython
20tab/UnrealEnginePython
2,715
73
```objective-c #pragma once #include "UEPySCompoundWidget.h" #if WITH_EDITOR #include "Editor/EditorWidgets/Public/SDropTarget.h" extern PyTypeObject ue_PySDropTargetType; typedef struct { ue_PySCompoundWidget s_compound_widget; /* Type-specific fields go here. */ } ue_PySDropTarget; void ue_python_init_sdrop_target(PyObject *); #endif ```
/content/code_sandbox/Source/UnrealEnginePython/Private/Slate/UEPySDropTarget.h
objective-c
2016-08-07T05:00:51
2024-08-14T06:32:20
UnrealEnginePython
20tab/UnrealEnginePython
2,715
85
```c++ #include "UEPySEditableTextBox.h" static PyObject *py_ue_seditable_text_box_select_all_text(ue_PySEditableTextBox *self, PyObject * args) { ue_py_slate_cast(SEditableTextBox); py_SEditableTextBox->SelectAllText(); Py_RETURN_NONE; } static PyObject *py_ue_seditable_text_box_clear_selection(ue_PySEditableTextBox *self, PyObject * args) { ue_py_slate_cast(SEditableTextBox); py_SEditableTextBox->ClearSelection(); Py_RETURN_NONE; } static PyObject *py_ue_seditable_text_box_get_selected_text(ue_PySEditableTextBox *self, PyObject * args) { ue_py_slate_cast(SEditableTextBox); FText text = py_SEditableTextBox->GetSelectedText(); return PyUnicode_FromString(TCHAR_TO_UTF8(*text.ToString())); } static PyObject *py_ue_seditable_text_box_get_text(ue_PySEditableTextBox *self, PyObject * args) { ue_py_slate_cast(SEditableTextBox); FText text = py_SEditableTextBox->GetText(); return PyUnicode_FromString(TCHAR_TO_UTF8(*text.ToString())); } static PyObject *py_ue_seditable_text_box_set_text(ue_PySEditableTextBox *self, PyObject * args) { ue_py_slate_cast(SEditableTextBox); char *text; if (!PyArg_ParseTuple(args, "s:set_text", &text)) { return nullptr; } py_SEditableTextBox->SetText(FText::FromString(UTF8_TO_TCHAR(text))); Py_RETURN_SLATE_SELF; } static PyMethodDef ue_PySEditableTextBox_methods[] = { { "select_all_text", (PyCFunction)py_ue_seditable_text_box_select_all_text, METH_VARARGS, "" }, { "clear_selection", (PyCFunction)py_ue_seditable_text_box_clear_selection, METH_VARARGS, "" }, { "get_selected_text", (PyCFunction)py_ue_seditable_text_box_get_selected_text, METH_VARARGS, "" }, { "get_text", (PyCFunction)py_ue_seditable_text_box_get_text, METH_VARARGS, "" }, { "set_text", (PyCFunction)py_ue_seditable_text_box_set_text, METH_VARARGS, "" }, { NULL } /* Sentinel */ }; PyTypeObject ue_PySEditableTextBoxType = { PyVarObject_HEAD_INIT(NULL, 0) "unreal_engine.SEditableTextBox", /* tp_name */ sizeof(ue_PySEditableTextBox), /* tp_basicsize */ 0, /* tp_itemsize */ 0, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_reserved */ 0, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ 0, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ "Unreal Engine SEditableTextBox", /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ ue_PySEditableTextBox_methods, /* tp_methods */ }; static int ue_py_seditable_text_box_init(ue_PySEditableTextBox *self, PyObject *args, PyObject *kwargs) { ue_py_slate_setup_farguments(SEditableTextBox); ue_py_slate_farguments_bool("allow_context_menu", AllowContextMenu); ue_py_slate_farguments_struct("background_color", BackgroundColor, FSlateColor); ue_py_slate_farguments_bool("clear_keyboard_focus_on_commit", ClearKeyboardFocusOnCommit); ue_py_slate_farguments_struct("font", Font, FSlateFontInfo); ue_py_slate_farguments_struct("foreground_color", ForegroundColor, FSlateColor); ue_py_slate_farguments_text("hint_text", HintText); ue_py_slate_farguments_bool("is_caret_moved_when_gain_focus", IsCaretMovedWhenGainFocus); ue_py_slate_farguments_bool("is_password", IsPassword); ue_py_slate_farguments_bool("is_read_only", IsReadOnly); ue_py_slate_farguments_float("min_desired_width", MinDesiredWidth); ue_py_slate_farguments_event("on_context_menu_opening", OnContextMenuOpening, FOnContextMenuOpening, OnContextMenuOpening); ue_py_slate_farguments_event("on_key_down_handler", OnKeyDownHandler, FOnKeyDown, OnKeyDown); ue_py_slate_farguments_event("on_text_changed", OnTextChanged, FOnTextChanged, OnTextChanged); ue_py_slate_farguments_event("on_text_committed", OnTextCommitted, FOnTextCommitted, OnTextCommitted); ue_py_slate_farguments_struct("padding", Padding, FMargin); ue_py_slate_farguments_struct("read_only_foreground_color", ReadOnlyForegroundColor, FSlateColor); ue_py_slate_farguments_bool("revert_text_on_escape", RevertTextOnEscape); ue_py_slate_farguments_bool("select_all_text_on_commit", SelectAllTextOnCommit); ue_py_slate_farguments_bool("select_all_text_when_focused", SelectAllTextWhenFocused); ue_py_slate_farguments_optional_struct_ptr("style", Style, FEditableTextBoxStyle); ue_py_slate_farguments_text("text", Text); ue_py_slate_farguments_optional_enum("text_flow_direction", TextFlowDirection, ETextFlowDirection); ue_py_slate_farguments_optional_enum("text_shaping_method", TextShapingMethod, ETextShapingMethod); ue_py_slate_farguments_enum("virtual_keyboard_type", VirtualKeyboardType, EKeyboardType); ue_py_snew(SEditableTextBox); return 0; } void ue_python_init_seditable_text_box(PyObject *ue_module) { ue_PySEditableTextBoxType.tp_init = (initproc)ue_py_seditable_text_box_init; ue_PySEditableTextBoxType.tp_base = &ue_PySBorderType; if (PyType_Ready(&ue_PySEditableTextBoxType) < 0) return; Py_INCREF(&ue_PySEditableTextBoxType); PyModule_AddObject(ue_module, "SEditableTextBox", (PyObject *)&ue_PySEditableTextBoxType); } ```
/content/code_sandbox/Source/UnrealEnginePython/Private/Slate/UEPySEditableTextBox.cpp
c++
2016-08-07T05:00:51
2024-08-14T06:32:20
UnrealEnginePython
20tab/UnrealEnginePython
2,715
1,469
```c++ #include "UEPySVectorInputBox.h" static PyMethodDef ue_PySVectorInputBox_methods[] = { { NULL } /* Sentinel */ }; PyTypeObject ue_PySVectorInputBoxType = { PyVarObject_HEAD_INIT(NULL, 0) "unreal_engine.SVectorInputBox", /* tp_name */ sizeof(ue_PySVectorInputBox), /* tp_basicsize */ 0, /* tp_itemsize */ 0, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_reserved */ 0, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ 0, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ "Unreal Engine SVectorInputBox", /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ ue_PySVectorInputBox_methods, /* tp_methods */ }; static int ue_py_svector_input_box_init(ue_PySVectorInputBox *self, PyObject *args, PyObject *kwargs) { ue_py_slate_setup_farguments(SVectorInputBox); #if ENGINE_MINOR_VERSION > 15 ue_py_slate_farguments_optional_bool("allow_spin", AllowSpin); #endif ue_py_slate_farguments_optional_bool("allow_responsive_layout", AllowResponsiveLayout); ue_py_slate_farguments_optional_bool("color_axis_labels", bColorAxisLabels); ue_py_slate_farguments_struct("font", Font, FSlateFontInfo); ue_py_slate_farguments_event("on_x_changed", OnXChanged, FOnFloatValueChanged, OnFloatChanged); ue_py_slate_farguments_event("on_y_changed", OnYChanged, FOnFloatValueChanged, OnFloatChanged); ue_py_slate_farguments_event("on_z_changed", OnZChanged, FOnFloatValueChanged, OnFloatChanged); ue_py_slate_farguments_event("on_x_committed", OnXCommitted, FOnFloatValueCommitted, OnFloatCommitted); ue_py_slate_farguments_event("on_y_committed", OnYCommitted, FOnFloatValueCommitted, OnFloatCommitted); ue_py_slate_farguments_event("on_z_committed", OnZCommitted, FOnFloatValueCommitted, OnFloatCommitted); ue_py_slate_farguments_tfloat("x", X); ue_py_slate_farguments_tfloat("y", Y); ue_py_slate_farguments_tfloat("z", Z); ue_py_snew(SVectorInputBox); return 0; } void ue_python_init_svector_input_box(PyObject *ue_module) { ue_PySVectorInputBoxType.tp_init = (initproc)ue_py_svector_input_box_init; ue_PySVectorInputBoxType.tp_base = &ue_PySCompoundWidgetType; if (PyType_Ready(&ue_PySVectorInputBoxType) < 0) return; Py_INCREF(&ue_PySVectorInputBoxType); PyModule_AddObject(ue_module, "SVectorInputBox", (PyObject *)&ue_PySVectorInputBoxType); } ```
/content/code_sandbox/Source/UnrealEnginePython/Private/Slate/UEPySVectorInputBox.cpp
c++
2016-08-07T05:00:51
2024-08-14T06:32:20
UnrealEnginePython
20tab/UnrealEnginePython
2,715
803
```objective-c #pragma once #include "UnrealEnginePython.h" #include "UEPySBoxPanel.h" #include "Runtime/SlateCore/Public/Widgets/SBoxPanel.h" extern PyTypeObject ue_PySHorizontalBoxType; typedef struct { ue_PySBoxPanel s_box_panel; /* Type-specific fields go here. */ } ue_PySHorizontalBox; void ue_python_init_shorizontal_box(PyObject *); ```
/content/code_sandbox/Source/UnrealEnginePython/Private/Slate/UEPySHorizontalBox.h
objective-c
2016-08-07T05:00:51
2024-08-14T06:32:20
UnrealEnginePython
20tab/UnrealEnginePython
2,715
87
```c++ #include "UEPyFInputEvent.h" static PyObject *py_ue_finput_event_to_text(ue_PyFInputEvent *self, PyObject * args) { return PyUnicode_FromString(TCHAR_TO_UTF8(*self->input.ToText().ToString())); } static PyObject *py_ue_finput_event_get_user_index(ue_PyFInputEvent *self, PyObject * args) { return PyLong_FromUnsignedLong(self->input.GetUserIndex()); } static PyObject *py_ue_finput_event_is_alt_down(ue_PyFInputEvent *self, PyObject * args) { if (self->input.IsAltDown()) Py_RETURN_TRUE; Py_RETURN_FALSE; } static PyObject *py_ue_finput_event_is_command_down(ue_PyFInputEvent *self, PyObject * args) { if (self->input.IsCommandDown()) Py_RETURN_TRUE; Py_RETURN_FALSE; } static PyObject *py_ue_finput_event_is_control_down(ue_PyFInputEvent *self, PyObject * args) { if (self->input.IsControlDown()) Py_RETURN_TRUE; Py_RETURN_FALSE; } static PyMethodDef ue_PyFInputEvent_methods[] = { { "to_text", (PyCFunction)py_ue_finput_event_to_text, METH_VARARGS, "" }, { "get_user_index", (PyCFunction)py_ue_finput_event_get_user_index, METH_VARARGS, "" }, { "is_alt_down", (PyCFunction)py_ue_finput_event_is_alt_down, METH_VARARGS, "" }, { "is_command_down", (PyCFunction)py_ue_finput_event_is_command_down, METH_VARARGS, "" }, { "is_control_down", (PyCFunction)py_ue_finput_event_is_control_down, METH_VARARGS, "" }, { NULL } /* Sentinel */ }; static PyObject *ue_PyFInputEvent_str(ue_PyFInputEvent *self) { return PyUnicode_FromFormat("<unreal_engine.FInputEvent '%s'>", TCHAR_TO_UTF8(*self->input.ToText().ToString())); } PyTypeObject ue_PyFInputEventType = { PyVarObject_HEAD_INIT(NULL, 0) "unreal_engine.FInputEvent", /* tp_name */ sizeof(ue_PyFInputEvent), /* tp_basicsize */ 0, /* tp_itemsize */ 0, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_reserved */ 0, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ (reprfunc)ue_PyFInputEvent_str, /* tp_str */ 0, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ "Unreal Engine FInputEvent", /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ ue_PyFInputEvent_methods, /* tp_methods */ }; void ue_python_init_finput_event(PyObject *ue_module) { ue_PyFInputEventType.tp_new = PyType_GenericNew; if (PyType_Ready(&ue_PyFInputEventType) < 0) return; Py_INCREF(&ue_PyFInputEventType); PyModule_AddObject(ue_module, "FInputEvent", (PyObject *)&ue_PyFInputEventType); } PyObject *py_ue_new_finput_event(FInputEvent input) { ue_PyFInputEvent *ret = (ue_PyFInputEvent *)PyObject_New(ue_PyFInputEvent, &ue_PyFInputEventType); new(&ret->input) FInputEvent(input); return (PyObject *)ret; } ```
/content/code_sandbox/Source/UnrealEnginePython/Private/Slate/UEPyFInputEvent.cpp
c++
2016-08-07T05:00:51
2024-08-14T06:32:20
UnrealEnginePython
20tab/UnrealEnginePython
2,715
887
```c++ #include "UEPySPythonTreeView.h" #include "Runtime/Slate/Public/Widgets/Views/STreeView.h" static PyObject *py_ue_spython_tree_view_set_item_expansion(ue_PySPythonTreeView *self, PyObject * args) { ue_py_slate_cast(SPythonTreeView); PyObject *py_item; PyObject *py_bool; if (!PyArg_ParseTuple(args, "OO:set_item_expansion", &py_item, &py_bool)) { return nullptr; } py_SPythonTreeView->SetPythonItemExpansion(py_item, PyObject_IsTrue(py_bool) ? true : false); Py_RETURN_NONE; } void SPythonTreeView::SetPythonItemExpansion(PyObject *item, bool InShouldExpandItem) { for (TSharedPtr<struct FPythonItem> PythonItem : *ItemsSource) { if (PythonItem->py_object == item) { SetItemExpansion(PythonItem, InShouldExpandItem); } } } static PyMethodDef ue_PySPythonTreeView_methods[] = { { "set_item_expansion", (PyCFunction)py_ue_spython_tree_view_set_item_expansion, METH_VARARGS, "" }, { NULL } /* Sentinel */ }; PyTypeObject ue_PySPythonTreeViewType = { PyVarObject_HEAD_INIT(NULL, 0) "unreal_engine.SPythonTreeView", /* tp_name */ sizeof(ue_PySPythonTreeView), /* tp_basicsize */ 0, /* tp_itemsize */ 0, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_reserved */ 0, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ 0, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ "Unreal Engine SPythonTreeView", /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ ue_PySPythonTreeView_methods, /* tp_methods */ }; static int ue_py_spython_tree_view_init(ue_PySPythonTreeView *self, PyObject *args, PyObject *kwargs) { ue_py_slate_setup_farguments(SPythonTreeView); // first of all check for values PyObject *values = ue_py_dict_get_item(kwargs, "tree_items_source"); if (!values) { PyErr_SetString(PyExc_Exception, "you must specify tree items"); return -1; } values = PyObject_GetIter(values); if (!values) { PyErr_SetString(PyExc_Exception, "values field is not an iterable"); return -1; } TArray<TSharedPtr<FPythonItem>> *items = new TArray<TSharedPtr<FPythonItem>>(); while (PyObject *item = PyIter_Next(values)) { Py_INCREF(item); items->Add(TSharedPtr<FPythonItem>(new FPythonItem(item))); } Py_DECREF(values); arguments.TreeItemsSource(items); ue_py_slate_farguments_optional_enum("allow_overscroll", AllowOverscroll, EAllowOverscroll); ue_py_slate_farguments_optional_bool("clear_selection_on_click", ClearSelectionOnClick); ue_py_slate_farguments_optional_enum("consume_mouse_wheel", ConsumeMouseWheel, EConsumeMouseWheel); ue_py_slate_farguments_float("item_height", ItemHeight); ue_py_slate_farguments_event("on_generate_row", OnGenerateRow, TSlateDelegates<TSharedPtr<FPythonItem>>::FOnGenerateRow, GenerateRow); ue_py_slate_farguments_event("on_selection_changed", OnSelectionChanged, TSlateDelegates<TSharedPtr<FPythonItem>>::FOnSelectionChanged, OnSelectionChanged); ue_py_slate_farguments_enum("selection_mode", SelectionMode, ESelectionMode::Type); #if ENGINE_MINOR_VERSION > 12 ue_py_slate_farguments_optional_float("wheel_scroll_multiplier", WheelScrollMultiplier); #endif ue_py_slate_farguments_event("on_get_children", OnGetChildren, TSlateDelegates<TSharedPtr<FPythonItem>>::FOnGetChildren, GetChildren); ue_py_snew(SPythonTreeView); return 0; } void ue_python_init_spython_tree_view(PyObject *ue_module) { ue_PySPythonTreeViewType.tp_init = (initproc)ue_py_spython_tree_view_init; ue_PySPythonTreeViewType.tp_base = &ue_PySTreeViewType; if (PyType_Ready(&ue_PySPythonTreeViewType) < 0) return; Py_INCREF(&ue_PySPythonTreeViewType); PyModule_AddObject(ue_module, "SPythonTreeView", (PyObject *)&ue_PySPythonTreeViewType); } ```
/content/code_sandbox/Source/UnrealEnginePython/Private/Slate/UEPySPythonTreeView.cpp
c++
2016-08-07T05:00:51
2024-08-14T06:32:20
UnrealEnginePython
20tab/UnrealEnginePython
2,715
1,123
```objective-c #pragma once #include "UEPySCompoundWidget.h" #include "Runtime/SlateCore/Public/Widgets/SWindow.h" extern PyTypeObject ue_PySWindowType; typedef struct { ue_PySCompoundWidget s_compound_widget; /* Type-specific fields go here. */ } ue_PySWindow; void ue_python_init_swindow(PyObject *); ue_PySWindow *py_ue_is_swindow(PyObject *obj); ue_PySWindow *py_ue_new_swindow(TSharedRef<SWindow>); ```
/content/code_sandbox/Source/UnrealEnginePython/Private/Slate/UEPySWindow.h
objective-c
2016-08-07T05:00:51
2024-08-14T06:32:20
UnrealEnginePython
20tab/UnrealEnginePython
2,715
109
```objective-c #pragma once #include "UEPySBorder.h" #include "Runtime/Slate/Public/Widgets/Docking/SDockTab.h" extern PyTypeObject ue_PySDockTabType; typedef struct { ue_PySBorder s_border; /* Type-specific fields go here. */ } ue_PySDockTab; void ue_python_init_sdock_tab(PyObject *); ```
/content/code_sandbox/Source/UnrealEnginePython/Private/Slate/UEPySDockTab.h
objective-c
2016-08-07T05:00:51
2024-08-14T06:32:20
UnrealEnginePython
20tab/UnrealEnginePython
2,715
79
```objective-c #pragma once #include "UnrealEnginePython.h" #include "UEPySTreeView.h" extern PyTypeObject ue_PySPythonTreeViewType; class SPythonTreeView : public STreeView<TSharedPtr<struct FPythonItem>> { public: ~SPythonTreeView() { delete(ItemsSource); } void SetPythonItemExpansion(PyObject *item, bool InShouldExpandItem); }; typedef struct { ue_PySTreeView s_tree_view; /* Type-specific fields go here. */ } ue_PySPythonTreeView; void ue_python_init_spython_tree_view(PyObject *); ```
/content/code_sandbox/Source/UnrealEnginePython/Private/Slate/UEPySPythonTreeView.h
objective-c
2016-08-07T05:00:51
2024-08-14T06:32:20
UnrealEnginePython
20tab/UnrealEnginePython
2,715
127
```objective-c #pragma once #include "UEPySWidget.h" extern PyTypeObject ue_PySPanelType; typedef struct { ue_PySWidget s_widget; /* Type-specific fields go here. */ } ue_PySPanel; void ue_python_init_spanel(PyObject *); ```
/content/code_sandbox/Source/UnrealEnginePython/Private/Slate/UEPySPanel.h
objective-c
2016-08-07T05:00:51
2024-08-14T06:32:20
UnrealEnginePython
20tab/UnrealEnginePython
2,715
59
```c++ #include "UEPySDockTab.h" #include "UEPyFTabManager.h" static PyObject *py_ue_sdock_tab_set_label(ue_PySDockTab *self, PyObject * args) { ue_py_slate_cast(SDockTab); char *label; if (!PyArg_ParseTuple(args, "s:set_label", &label)) { return nullptr; } py_SDockTab->SetLabel(FText::FromString(UTF8_TO_TCHAR(label))); Py_RETURN_SLATE_SELF; } static PyObject *py_ue_sdock_tab_request_close_tab(ue_PySDockTab *self, PyObject * args) { ue_py_slate_cast(SDockTab); py_SDockTab->RequestCloseTab(); Py_RETURN_NONE; } static PyObject *py_ue_sdock_tab_new_tab_manager(ue_PySDockTab *self, PyObject * args) { ue_py_slate_cast(SDockTab); TSharedRef<FTabManager> tab_manager = FGlobalTabmanager::Get()->NewTabManager(py_SDockTab); return py_ue_new_ftab_manager(tab_manager); } static PyMethodDef ue_PySDockTab_methods[] = { { "set_label", (PyCFunction)py_ue_sdock_tab_set_label, METH_VARARGS, "" }, { "request_close_tab", (PyCFunction)py_ue_sdock_tab_request_close_tab, METH_VARARGS, "" }, { "new_tab_manager", (PyCFunction)py_ue_sdock_tab_new_tab_manager, METH_VARARGS, "" }, { NULL } /* Sentinel */ }; PyTypeObject ue_PySDockTabType = { PyVarObject_HEAD_INIT(NULL, 0) "unreal_engine.SDockTab", /* tp_name */ sizeof(ue_PySDockTab), /* tp_basicsize */ 0, /* tp_itemsize */ 0, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_reserved */ 0, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ 0, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ "Unreal Engine SDockTab", /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ ue_PySDockTab_methods, /* tp_methods */ }; static int ue_py_sdock_tab_init(ue_PySDockTab *self, PyObject *args, PyObject *kwargs) { ue_py_slate_setup_farguments(SDockTab); ue_py_slate_farguments_struct("content_padding", ContentPadding, FMargin); ue_py_slate_farguments_optional_struct_ptr("icon", Icon, FSlateBrush); ue_py_slate_farguments_text("label", Label); ue_py_slate_farguments_optional_bool("should_autosize", ShouldAutosize); ue_py_slate_farguments_optional_enum("tab_role", TabRole, ETabRole); ue_py_snew(SDockTab); return 0; } void ue_python_init_sdock_tab(PyObject *ue_module) { ue_PySDockTabType.tp_base = &ue_PySBorderType; ue_PySDockTabType.tp_init = (initproc)ue_py_sdock_tab_init; if (PyType_Ready(&ue_PySDockTabType) < 0) return; Py_INCREF(&ue_PySDockTabType); PyModule_AddObject(ue_module, "SDockTab", (PyObject *)&ue_PySDockTabType); } ```
/content/code_sandbox/Source/UnrealEnginePython/Private/Slate/UEPySDockTab.cpp
c++
2016-08-07T05:00:51
2024-08-14T06:32:20
UnrealEnginePython
20tab/UnrealEnginePython
2,715
880
```c++ #include "UEPySRotatorInputBox.h" static PyMethodDef ue_PySRotatorInputBox_methods[] = { { NULL } /* Sentinel */ }; PyTypeObject ue_PySRotatorInputBoxType = { PyVarObject_HEAD_INIT(NULL, 0) "unreal_engine.SRotatorInputBox", /* tp_name */ sizeof(ue_PySRotatorInputBox), /* tp_basicsize */ 0, /* tp_itemsize */ 0, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_reserved */ 0, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ 0, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ "Unreal Engine SRotatorInputBox", /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ ue_PySRotatorInputBox_methods, /* tp_methods */ }; static int ue_py_srotator_input_box_init(ue_PySRotatorInputBox *self, PyObject *args, PyObject *kwargs) { ue_py_slate_setup_farguments(SRotatorInputBox); ue_py_slate_farguments_optional_bool("allow_responsive_layout", AllowResponsiveLayout); ue_py_slate_farguments_optional_bool("color_axis_labels", bColorAxisLabels); ue_py_slate_farguments_optional_bool("allow_spin", AllowSpin); ue_py_slate_farguments_struct("font", Font, FSlateFontInfo); ue_py_slate_farguments_event("on_roll_changed", OnRollChanged, FOnFloatValueChanged, OnFloatChanged); ue_py_slate_farguments_event("on_pitch_changed", OnPitchChanged, FOnFloatValueChanged, OnFloatChanged); ue_py_slate_farguments_event("on_yaw_changed", OnYawChanged, FOnFloatValueChanged, OnFloatChanged); ue_py_slate_farguments_event("on_roll_committed", OnRollCommitted, FOnFloatValueCommitted, OnFloatCommitted); ue_py_slate_farguments_event("on_pitch_committed", OnPitchCommitted, FOnFloatValueCommitted, OnFloatCommitted); ue_py_slate_farguments_event("on_yaw_committed", OnYawCommitted, FOnFloatValueCommitted, OnFloatCommitted); ue_py_slate_farguments_tfloat("roll", Roll); ue_py_slate_farguments_tfloat("pitch", Pitch); ue_py_slate_farguments_tfloat("yaw", Yaw); ue_py_snew(SRotatorInputBox); return 0; } void ue_python_init_srotator_input_box(PyObject *ue_module) { ue_PySRotatorInputBoxType.tp_init = (initproc)ue_py_srotator_input_box_init; ue_PySRotatorInputBoxType.tp_base = &ue_PySCompoundWidgetType; if (PyType_Ready(&ue_PySRotatorInputBoxType) < 0) return; Py_INCREF(&ue_PySRotatorInputBoxType); PyModule_AddObject(ue_module, "SRotatorInputBox", (PyObject *)&ue_PySRotatorInputBoxType); } ```
/content/code_sandbox/Source/UnrealEnginePython/Private/Slate/UEPySRotatorInputBox.cpp
c++
2016-08-07T05:00:51
2024-08-14T06:32:20
UnrealEnginePython
20tab/UnrealEnginePython
2,715
813
```c++ #include "UEPySProgressBar.h" static PyObject *py_ue_sprogress_bar_set_percent(ue_PySProgressBar *self, PyObject *args) { ue_py_slate_cast(SProgressBar); float percent; if (!PyArg_ParseTuple(args, "f", &percent)) { return nullptr; } py_SProgressBar->SetPercent(percent); Py_RETURN_SLATE_SELF; } static PyMethodDef ue_PySProgressBar_methods[] = { { "set_percent", (PyCFunction)py_ue_sprogress_bar_set_percent, METH_VARARGS, "" }, { NULL } /* Sentinel */ }; PyTypeObject ue_PySProgressBarType = { PyVarObject_HEAD_INIT(NULL, 0) "unreal_engine.SProgressBar", /* tp_name */ sizeof(ue_PySProgressBar), /* tp_basicsize */ 0, /* tp_itemsize */ 0, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_reserved */ 0, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ 0, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ "Unreal Engine SProgressBar", /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ ue_PySProgressBar_methods, /* tp_methods */ }; static int ue_py_sprogress_bar_init(ue_PySProgressBar *self, PyObject *args, PyObject *kwargs) { ue_py_slate_setup_farguments(SProgressBar); ue_py_slate_farguments_optional_struct_ptr("background_image", BackgroundImage, FSlateBrush); ue_py_slate_farguments_optional_enum("bar_fill_type", BarFillType, EProgressBarFillType::Type); ue_py_slate_farguments_fvector2d("border_padding", BorderPadding); ue_py_slate_farguments_struct("fill_color_and_opacity", FillColorAndOpacity, FSlateColor); ue_py_slate_farguments_optional_struct_ptr("fill_image", FillImage, FSlateBrush); ue_py_slate_farguments_optional_struct_ptr("marquee_image", MarqueeImage, FSlateBrush); ue_py_slate_farguments_tfloat("percent", Percent); ue_py_slate_farguments_optional_float("refresh_rate", RefreshRate); ue_py_slate_farguments_optional_struct_ptr("style", Style, FProgressBarStyle); ue_py_snew(SProgressBar); return 0; } void ue_python_init_sprogress_bar(PyObject *ue_module) { ue_PySProgressBarType.tp_init = (initproc)ue_py_sprogress_bar_init; ue_PySProgressBarType.tp_base = &ue_PySLeafWidgetType; if (PyType_Ready(&ue_PySProgressBarType) < 0) return; Py_INCREF(&ue_PySProgressBarType); PyModule_AddObject(ue_module, "SProgressBar", (PyObject *)&ue_PySProgressBarType); } ```
/content/code_sandbox/Source/UnrealEnginePython/Private/Slate/UEPySProgressBar.cpp
c++
2016-08-07T05:00:51
2024-08-14T06:32:20
UnrealEnginePython
20tab/UnrealEnginePython
2,715
751