本文整理汇总了C++中TArray::Num方法的典型用法代码示例。如果您正苦于以下问题:C++ TArray::Num方法的具体用法?C++ TArray::Num怎么用?C++ TArray::Num使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类TArray
的用法示例。
在下文中一共展示了TArray::Num方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: GetMessageTypes
int32 FMessageTracer::GetMessageTypes( TArray<FMessageTracerTypeInfoPtr>& OutTypes ) const
{
MessageTypes.GenerateValueArray(OutTypes);
return OutTypes.Num();
}
示例2: RunSmokeTests
bool FAutomationTestFramework::RunSmokeTests()
{
bool bAllSuccessful = true;
//so extra log spam isn't generated
bRunningSmokeTests = true;
// Skip running on cooked platforms like mobile
//@todo - better determination of whether to run than requires cooked data
// Ensure there isn't another slow task in progress when trying to run unit tests
const bool bRequiresCookedData = FPlatformProperties::RequiresCookedData();
if ((!bRequiresCookedData && !GIsSlowTask && !GIsPlayInEditorWorld) || bForceSmokeTests)
{
TArray<FAutomationTestInfo> TestInfo;
GetValidTestNames( TestInfo );
if ( TestInfo.Num() > 0 )
{
double SmokeTestStartTime = FPlatformTime::Seconds();
// Output the results of running the automation tests
TMap<FString, FAutomationTestExecutionInfo> OutExecutionInfoMap;
// Run each valid test
FScopedSlowTask SlowTask(TestInfo.Num());
for ( int TestIndex = 0; TestIndex < TestInfo.Num(); ++TestIndex )
{
SlowTask.EnterProgressFrame(1);
if (TestInfo[TestIndex].GetTestType() == EAutomationTestType::ATT_SmokeTest )
{
FString TestCommand = TestInfo[TestIndex].GetTestName();
FAutomationTestExecutionInfo& CurExecutionInfo = OutExecutionInfoMap.Add( TestCommand, FAutomationTestExecutionInfo() );
int32 RoleIndex = 0; //always default to "local" role index. Only used for multi-participant tests
StartTestByName( TestCommand, RoleIndex );
const bool CurTestSuccessful = StopTest(CurExecutionInfo);
bAllSuccessful = bAllSuccessful && CurTestSuccessful;
}
}
double EndTime = FPlatformTime::Seconds();
double TimeForTest = static_cast<float>(EndTime - SmokeTestStartTime);
if (TimeForTest > 1.0f)
{
//force a failure if a smoke test takes too long
UE_LOG(LogAutomationTest, Warning, TEXT("Smoke tests took > 1s to run: %.2fs"), (float)TimeForTest);
}
FAutomationTestFramework::DumpAutomationTestExecutionInfo( OutExecutionInfoMap );
}
}
else if( bRequiresCookedData )
{
UE_LOG( LogAutomationTest, Log, TEXT( "Skipping unit tests for the cooked build." ) );
}
else
{
UE_LOG(LogAutomationTest, Error, TEXT("Skipping unit tests.") );
bAllSuccessful = false;
}
//revert to allowing all logs
bRunningSmokeTests = false;
return bAllSuccessful;
}
示例3: BuildRenderingSection
void FSpriteDetailsCustomization::BuildRenderingSection(IDetailCategoryBuilder& RenderingCategory, IDetailLayoutBuilder& DetailLayout)
{
TAttribute<EVisibility> HideWhenInCollisionMode = TAttribute<EVisibility>::Create(TAttribute<EVisibility>::FGetter::CreateSP(this, &FSpriteDetailsCustomization::EditorModeIsNot, ESpriteEditorMode::EditCollisionMode));
TAttribute<EVisibility> ShowWhenInCollisionMode = TAttribute<EVisibility>::Create(TAttribute<EVisibility>::FGetter::CreateSP(this, &FSpriteDetailsCustomization::EditorModeMatches, ESpriteEditorMode::EditCollisionMode));
static const FText EditRenderingInRenderingMode = LOCTEXT("RenderingPropertiesHiddenInCollisionMode", "Switch to 'Edit RenderGeom' mode\nto edit Rendering settings");
RenderingCategory.AddCustomRow(EditRenderingInRenderingMode)
.Visibility(ShowWhenInCollisionMode)
.WholeRowContent()
.HAlign(HAlign_Center)
[
SNew(STextBlock)
.Font(DetailLayout.GetDetailFontItalic())
.Justification(ETextJustify::Center)
.Text(EditRenderingInRenderingMode)
];
TArray<TWeakObjectPtr<UObject>> ObjectsBeingCustomized;
DetailLayout.GetObjectsBeingCustomized(/*out*/ ObjectsBeingCustomized);
if (ObjectsBeingCustomized.Num() > 0)
{
if (UPaperSprite* SpriteBeingEdited = Cast<UPaperSprite>(ObjectsBeingCustomized[0].Get()))
{
static const FText TypesOfMaterialsTooltip = LOCTEXT("TypesOfMaterialsTooltip", "Translucent materials can have smooth alpha edges, blending with the background\nMasked materials have on or off alpha, useful for cutouts\nOpaque materials have no transparency but render faster");
RenderingCategory.HeaderContent
(
SNew(SBox)
.HAlign(HAlign_Right)
[
SNew(SHorizontalBox)
+SHorizontalBox::Slot()
.Padding(FMargin(5.0f, 0.0f))
.AutoWidth()
[
SNew(STextBlock)
.Font(FEditorStyle::GetFontStyle("TinyText"))
.Text(this, &FSpriteDetailsCustomization::GetRenderingHeaderContentText, TWeakObjectPtr<UPaperSprite>(SpriteBeingEdited))
.ToolTipText(TypesOfMaterialsTooltip)
]
]
);
}
}
// Add the rendering geometry mode into the parent container (renamed)
const FString RenderGeometryTypePropertyPath = FString::Printf(TEXT("%s.%s"), GET_MEMBER_NAME_STRING_CHECKED(UPaperSprite, RenderGeometry), GET_MEMBER_NAME_STRING_CHECKED(FSpriteGeometryCollection, GeometryType));
TSharedPtr<IPropertyHandle> RenderGeometryTypeProperty = DetailLayout.GetProperty(*RenderGeometryTypePropertyPath);
RenderingCategory.AddProperty(RenderGeometryTypeProperty)
.DisplayName(LOCTEXT("RenderGeometryType", "Render Geometry Type"))
.Visibility(HideWhenInCollisionMode);
// Show the alternate material, but only when the mode is Diced
TAttribute<EVisibility> ShowWhenModeIsDiced = TAttribute<EVisibility>::Create(TAttribute<EVisibility>::FGetter::CreateSP(this, &FSpriteDetailsCustomization::PolygonModeMatches, RenderGeometryTypeProperty, ESpritePolygonMode::Diced));
TSharedPtr<IPropertyHandle> AlternateMaterialProperty = DetailLayout.GetProperty(GET_MEMBER_NAME_CHECKED(UPaperSprite, AlternateMaterial));
RenderingCategory.AddProperty(AlternateMaterialProperty)
.Visibility(ShowWhenModeIsDiced);
// Show the rendering geometry settings
TSharedRef<IPropertyHandle> RenderGeometry = DetailLayout.GetProperty(GET_MEMBER_NAME_CHECKED(UPaperSprite, RenderGeometry));
IDetailPropertyRow& RenderGeometryProperty = RenderingCategory.AddProperty(RenderGeometry)
.Visibility(HideWhenInCollisionMode);
// Add the render polygons into advanced (renamed)
const FString RenderGeometryPolygonsPropertyPath = FString::Printf(TEXT("%s.%s"), GET_MEMBER_NAME_STRING_CHECKED(UPaperSprite, RenderGeometry), GET_MEMBER_NAME_STRING_CHECKED(FSpriteGeometryCollection, Shapes));
RenderingCategory.AddProperty(DetailLayout.GetProperty(*RenderGeometryPolygonsPropertyPath), EPropertyLocation::Advanced)
.DisplayName(LOCTEXT("RenderShapes", "Render Shapes"))
.Visibility(HideWhenInCollisionMode);
}
示例4: LoadReferencingPackages
void FAssetFixUpRedirectors::LoadReferencingPackages(TArray<FRedirectorRefs>& RedirectorsToFix, TArray<UPackage*>& OutReferencingPackagesToSave) const
{
FScopedSlowTask SlowTask( RedirectorsToFix.Num(), LOCTEXT( "LoadingReferencingPackages", "Loading Referencing Packages..." ) );
SlowTask.MakeDialog();
ISourceControlProvider& SourceControlProvider = ISourceControlModule::Get().GetProvider();
// Load all packages that reference each redirector, if possible
for ( auto RedirectorRefsIt = RedirectorsToFix.CreateIterator(); RedirectorRefsIt; ++RedirectorRefsIt )
{
SlowTask.EnterProgressFrame(1);
FRedirectorRefs& RedirectorRefs = *RedirectorRefsIt;
if ( ISourceControlModule::Get().IsEnabled() )
{
FSourceControlStatePtr SourceControlState = SourceControlProvider.GetState(RedirectorRefs.Redirector->GetOutermost(), EStateCacheUsage::Use);
const bool bValidSCCState = !SourceControlState.IsValid() || SourceControlState->IsAdded() || SourceControlState->IsCheckedOut() || SourceControlState->CanCheckout() || !SourceControlState->IsSourceControlled() || SourceControlState->IsIgnored();
if ( !bValidSCCState )
{
RedirectorRefs.bRedirectorValidForFixup = false;
RedirectorRefs.FailureReason = LOCTEXT("RedirectorFixupFailed_BadSCC", "Redirector could not be checked out or marked for delete");
}
}
// Load all referencers
for ( auto PackageNameIt = RedirectorRefs.ReferencingPackageNames.CreateConstIterator(); PackageNameIt; ++PackageNameIt )
{
const FString PackageName = (*PackageNameIt).ToString();
// Find the package in memory. If it is not in memory, try to load it
UPackage* Package = FindPackage(NULL, *PackageName);
if ( !Package )
{
// Check if the package is a map before loading it!
if ( FEditorFileUtils::IsMapPackageAsset(PackageName) )
{
// This reference was a map package, don't load it
RedirectorRefs.bRedirectorValidForFixup = false;
RedirectorRefs.FailureReason = FText::Format(LOCTEXT("RedirectorFixupFailed_MapReference", "Redirector is referenced by an unloaded map. Package: {0}"), FText::FromString(PackageName));
continue;
}
Package = LoadPackage(NULL, *PackageName, LOAD_None);
}
if ( Package )
{
if ( Package->PackageFlags & PKG_CompiledIn )
{
// This is a script reference
RedirectorRefs.bRedirectorValidForFixup = false;
RedirectorRefs.FailureReason = FText::Format(LOCTEXT("RedirectorFixupFailed_CodeReference", "Redirector is referenced by code. Package: {0}"), FText::FromString(PackageName));
}
else
{
// If we found a valid package, mark it for save
OutReferencingPackagesToSave.AddUnique(Package);
}
}
}
}
}
示例5: HighestCost
TSharedPtr<FEnvQueryInstance> UEnvQueryManager::CreateQueryInstance(const UEnvQuery* Template, EEnvQueryRunMode::Type RunMode)
{
if (Template == nullptr || Template->Options.Num() == 0)
{
UE_CLOG(Template != nullptr && Template->Options.Num() == 0, LogEQS, Warning, TEXT("Query [%s] doesn't have any valid options!"), *Template->GetName());
return nullptr;
}
// try to find entry in cache
FEnvQueryInstance* InstanceTemplate = NULL;
for (int32 InstanceIndex = 0; InstanceIndex < InstanceCache.Num(); InstanceIndex++)
{
if (InstanceCache[InstanceIndex].Template->GetFName() == Template->GetFName() &&
InstanceCache[InstanceIndex].Instance.Mode == RunMode)
{
InstanceTemplate = &InstanceCache[InstanceIndex].Instance;
break;
}
}
// and create one if can't be found
if (InstanceTemplate == NULL)
{
SCOPE_CYCLE_COUNTER(STAT_AI_EQS_LoadTime);
// duplicate template in manager's world for BP based nodes
UEnvQuery* LocalTemplate = (UEnvQuery*)StaticDuplicateObject(Template, this, *Template->GetName());
{
// memory stat tracking: temporary variable will exist only inside this section
FEnvQueryInstanceCache NewCacheEntry;
NewCacheEntry.Template = LocalTemplate;
NewCacheEntry.Instance.QueryName = LocalTemplate->GetName();
NewCacheEntry.Instance.Mode = RunMode;
const int32 Idx = InstanceCache.Add(NewCacheEntry);
InstanceTemplate = &InstanceCache[Idx].Instance;
}
// NOTE: We must iterate over this from 0->Num because we are copying the options from the template into the
// instance, and order matters! Since we also may need to remove invalid or null options, we must decrement
// the iteration pointer when doing so to avoid problems.
for (int32 OptionIndex = 0; OptionIndex < LocalTemplate->Options.Num(); ++OptionIndex)
{
UEnvQueryOption* MyOption = LocalTemplate->Options[OptionIndex];
if (MyOption == nullptr ||
MyOption->Generator == nullptr ||
MyOption->Generator->ItemType == nullptr)
{
UE_LOG(LogEQS, Error, TEXT("Trying to spawn a query with broken Template (generator:%s itemType:%s): %s, option %d"),
MyOption ? (MyOption->Generator ? TEXT("ok") : TEXT("MISSING")) : TEXT("N/A"),
(MyOption && MyOption->Generator) ? (MyOption->Generator->ItemType ? TEXT("ok") : TEXT("MISSING")) : TEXT("N/A"),
*GetNameSafe(LocalTemplate), OptionIndex);
LocalTemplate->Options.RemoveAt(OptionIndex, 1, false);
--OptionIndex; // See note at top of for loop. We cannot iterate backwards here.
continue;
}
UEnvQueryOption* LocalOption = (UEnvQueryOption*)StaticDuplicateObject(MyOption, this, TEXT("None"));
UEnvQueryGenerator* LocalGenerator = (UEnvQueryGenerator*)StaticDuplicateObject(MyOption->Generator, this, TEXT("None"));
LocalTemplate->Options[OptionIndex] = LocalOption;
LocalOption->Generator = LocalGenerator;
EEnvTestCost::Type HighestCost(EEnvTestCost::Low);
TArray<UEnvQueryTest*> SortedTests = MyOption->Tests;
TSubclassOf<UEnvQueryItemType> GeneratedType = MyOption->Generator->ItemType;
for (int32 TestIndex = SortedTests.Num() - 1; TestIndex >= 0; TestIndex--)
{
UEnvQueryTest* TestOb = SortedTests[TestIndex];
if (TestOb == NULL || !TestOb->IsSupportedItem(GeneratedType))
{
UE_LOG(LogEQS, Warning, TEXT("Query [%s] can't use test [%s] in option %d [%s], removing it"),
*GetNameSafe(LocalTemplate), *GetNameSafe(TestOb), OptionIndex, *MyOption->Generator->OptionName);
SortedTests.RemoveAt(TestIndex, 1, false);
}
else if (HighestCost < TestOb->Cost)
{
HighestCost = TestOb->Cost;
}
}
if (SortedTests.Num() == 0)
{
UE_LOG(LogEQS, Warning, TEXT("Query [%s] doesn't have any tests in option %d [%s]"),
*GetNameSafe(LocalTemplate), OptionIndex, *MyOption->Generator->OptionName);
LocalTemplate->Options.RemoveAt(OptionIndex, 1, false);
--OptionIndex; // See note at top of for loop. We cannot iterate backwards here.
continue;
}
LocalOption->Tests.Reset(SortedTests.Num());
for (int32 TestIdx = 0; TestIdx < SortedTests.Num(); TestIdx++)
{
UEnvQueryTest* LocalTest = (UEnvQueryTest*)StaticDuplicateObject(SortedTests[TestIdx], this, TEXT("None"));
LocalOption->Tests.Add(LocalTest);
}
//.........这里部分代码省略.........
示例6: Main
int32 UUpdateGameProjectCommandlet::Main( const FString& InParams )
{
// Parse command line.
TArray<FString> Tokens;
TArray<FString> Switches;
UCommandlet::ParseCommandLine(*InParams, Tokens, Switches);
FString Category;
FText ChangelistDescription = NSLOCTEXT("UpdateGameProjectCmdlet", "ChangelistDescription", "Updated game project");
bool bAutoCheckout = false;
bool bAutoSubmit = false;
bool bSignSampleProject = false;
const FString CategorySwitch = TEXT("Category=");
const FString ChangelistDescriptionSwitch = TEXT("ChangelistDescription=");
for ( int32 SwitchIdx = 0; SwitchIdx < Switches.Num(); ++SwitchIdx )
{
const FString& Switch = Switches[SwitchIdx];
if ( Switch == TEXT("AutoCheckout") )
{
bAutoCheckout = true;
}
else if ( Switch == TEXT("AutoSubmit") )
{
bAutoSubmit = true;
}
else if ( Switch == TEXT("SignSampleProject") )
{
bSignSampleProject = true;
}
else if ( Switch.StartsWith(CategorySwitch) )
{
Category = Switch.Mid( CategorySwitch.Len() );
}
else if ( Switch.StartsWith(ChangelistDescriptionSwitch) )
{
ChangelistDescription = FText::FromString( Switch.Mid( ChangelistDescriptionSwitch.Len() ) );
}
}
if ( !FPaths::IsProjectFilePathSet() )
{
UE_LOG(LogUpdateGameProjectCommandlet, Error, TEXT("You must launch with a project file to be able to update it"));
return 1;
}
const FString ProjectFilePath = FPaths::GetProjectFilePath();
ISourceControlProvider& SourceControlProvider = ISourceControlModule::Get().GetProvider();
if ( bAutoCheckout )
{
SourceControlProvider.Init();
}
FString EngineIdentifier = GEngineVersion.ToString(EVersionComponent::Minor);
UE_LOG(LogUpdateGameProjectCommandlet, Display, TEXT("Updating project file %s to %s..."), *ProjectFilePath, *EngineIdentifier);
FText FailReason;
if ( !FGameProjectGenerationModule::Get().UpdateGameProject(ProjectFilePath, EngineIdentifier, FailReason) )
{
UE_LOG(LogUpdateGameProjectCommandlet, Error, TEXT("Couldn't update game project: %s"), *FailReason.ToString());
return 1;
}
if ( bSignSampleProject )
{
UE_LOG(LogUpdateGameProjectCommandlet, Display, TEXT("Attempting to sign project file %s..."), *ProjectFilePath);
FText LocalFailReason;
if ( IProjectManager::Get().SignSampleProject(ProjectFilePath, Category, LocalFailReason) )
{
UE_LOG(LogUpdateGameProjectCommandlet, Display, TEXT("Signed project file %s saved."), *ProjectFilePath);
}
else
{
UE_LOG(LogUpdateGameProjectCommandlet, Warning, TEXT("%s"), *LocalFailReason.ToString());
}
}
if ( bAutoSubmit )
{
if ( !bAutoCheckout )
{
// We didn't init SCC above so do it now
SourceControlProvider.Init();
}
if ( ISourceControlModule::Get().IsEnabled() )
{
const FString AbsoluteFilename = FPaths::ConvertRelativePathToFull(FPaths::GetProjectFilePath());
FSourceControlStatePtr SourceControlState = SourceControlProvider.GetState(AbsoluteFilename, EStateCacheUsage::ForceUpdate);
if ( SourceControlState.IsValid() && SourceControlState->IsCheckedOut() )
{
TSharedRef<FCheckIn, ESPMode::ThreadSafe> CheckInOperation = ISourceControlOperation::Create<FCheckIn>();
CheckInOperation->SetDescription(ChangelistDescription);
SourceControlProvider.Execute(CheckInOperation, AbsoluteFilename);
}
}
}
//.........这里部分代码省略.........
示例7: TEXT
TSharedPtr<FPropertyNode> FDetailLayoutBuilderImpl::GetPropertyNodeInternal( const FName PropertyPath, const UClass* ClassOutermost, FName InstanceName ) const
{
FName PropertyName;
TArray<FString> PathList;
PropertyPath.ToString().ParseIntoArray( &PathList, TEXT("."), true );
if( PathList.Num() == 1 )
{
PropertyName = FName( *PathList[0] );
}
// The class to find properties in defaults to the class currently being customized
FName ClassName = CurrentCustomizationClass ? CurrentCustomizationClass->GetFName() : NAME_None;
if( ClassOutermost != NULL )
{
// The requested a different class
ClassName = ClassOutermost->GetFName();
}
// Find the outer variable name. This only matters if there are multiple instances of the same property
FName OuterVariableName = CurrentCustomizationVariableName;
if( InstanceName != NAME_None )
{
OuterVariableName = InstanceName;
}
// If this fails there are no properties associated with the class name provided
FClassInstanceToPropertyMap* ClassInstanceToPropertyMapPtr = PropertyMap.Find( ClassName );
if( ClassInstanceToPropertyMapPtr )
{
FClassInstanceToPropertyMap& ClassInstanceToPropertyMap = *ClassInstanceToPropertyMapPtr;
if( OuterVariableName == NAME_None && ClassInstanceToPropertyMap.Num() == 1 )
{
// If the outer variable name still wasnt specified and there is only one instance, just use that
auto FirstKey = ClassInstanceToPropertyMap.CreateIterator();
OuterVariableName = FirstKey.Key();
}
FPropertyNodeMap* PropertyNodeMapPtr = ClassInstanceToPropertyMap.Find( OuterVariableName );
if( PropertyNodeMapPtr )
{
FPropertyNodeMap& PropertyNodeMap = *PropertyNodeMapPtr;
// Check for property name fast path first
if( PropertyName != NAME_None )
{
// The property name was ambiguous or not found if this fails. If ambiguous, it means there are multiple data same typed data structures(components or structs) in the class which
// causes multiple properties by the same name to exist. These properties must be found via the path method.
return PropertyNodeMap.PropertyNameToNode.FindRef( PropertyName );
}
else
{
// We need to search through the tree for a property with the given path
TSharedPtr<FPropertyNode> PropertyNode;
// Path should be in the format A[optional_index].B.C
if( PathList.Num() )
{
// Get the base property and index
FString Property;
int32 Index;
GetPropertyAndIndex( PathList[0], Property, Index );
// Get the parent most property node which is the one in the map. Its children need to be searched
PropertyNode = PropertyNodeMap.PropertyNameToNode.FindRef( FName( *Property ) );
if( PropertyNode.IsValid() )
{
if( Index != INDEX_NONE )
{
// The parent is the actual array, its children are array elements
PropertyNode = PropertyNode->GetChildNode( Index );
}
// Search any additional paths for the child
for( int32 PathIndex = 1; PathIndex < PathList.Num(); ++PathIndex )
{
GetPropertyAndIndex( PathList[PathIndex], Property, Index );
PropertyNode = FindChildPropertyNode( *PropertyNode, Property, Index );
}
}
}
return PropertyNode;
}
}
}
return NULL;
}
示例8: ComponentOverlapTest
bool UWorld::ComponentOverlapTest(class UPrimitiveComponent* PrimComp, const FVector& Pos, const FRotator& Rot, const struct FComponentQueryParams& Params) const
{
if(GetPhysicsScene() == NULL)
{
return false;
}
if(PrimComp == NULL)
{
UE_LOG(LogCollision, Log, TEXT("ComponentOverlapMulti : No PrimComp"));
return false;
}
// if target is skeletalmeshcomponent and do not support singlebody physics, we don't support this yet
// talk to @JG, SP, LH
if ( !PrimComp->ShouldTrackOverlaps() )
{
UE_LOG(LogCollision, Log, TEXT("ComponentOverlapMulti : (%s) Does not support skeletalmesh with Physics Asset and destructibles."), *PrimComp->GetPathName());
return false;
}
#if WITH_PHYSX
ECollisionChannel TraceChannel = PrimComp->GetCollisionObjectType();
PxRigidActor* PRigidActor = PrimComp->BodyInstance.GetPxRigidActor();
if(PRigidActor == NULL)
{
UE_LOG(LogCollision, Log, TEXT("ComponentOverlapMulti : (%s) No physics data"), *PrimComp->GetPathName());
return false;
}
// calculate the test global pose of the actor
PxTransform PTestGlobalPose = U2PTransform(FTransform(Rot, Pos));
// Get all the shapes from the actor
TArray<PxShape*, TInlineAllocator<8>> PShapes;
PShapes.AddZeroed(PRigidActor->getNbShapes());
int32 NumShapes = PRigidActor->getShapes(PShapes.GetData(), PShapes.Num());
// Iterate over each shape
for(int32 ShapeIdx=0; ShapeIdx<PShapes.Num(); ShapeIdx++)
{
PxShape* PShape = PShapes[ShapeIdx];
check(PShape);
// Calc shape global pose
PxTransform PLocalPose = PShape->getLocalPose();
PxTransform PShapeGlobalPose = PTestGlobalPose.transform(PLocalPose);
GET_GEOMETRY_FROM_SHAPE(PGeom, PShape);
if(PGeom != NULL)
{
if( GeomOverlapTest(this, *PGeom, PShapeGlobalPose, TraceChannel, Params, FCollisionResponseParams(PrimComp->GetCollisionResponseToChannels())))
{
// in this test, it only matters true or false.
// if we found first true, we don't care next test anymore.
return true;
}
}
}
#endif //WITH_PHYSX
return false;
}
示例9: ComponentSweepSingle
bool UWorld::ComponentSweepSingle(struct FHitResult& OutHit,class UPrimitiveComponent* PrimComp, const FVector& Start, const FVector& End, const FRotator& Rot, const struct FComponentQueryParams& Params) const
{
OutHit.TraceStart = Start;
OutHit.TraceEnd = End;
if(GetPhysicsScene() == NULL)
{
return false;
}
if(PrimComp == NULL)
{
UE_LOG(LogCollision, Log, TEXT("ComponentSweepSingle : No PrimComp"));
return false;
}
// if target is skeletalmeshcomponent and do not support singlebody physics
if ( !PrimComp->ShouldTrackOverlaps() )
{
UE_LOG(LogCollision, Log, TEXT("ComponentSweepSingle : (%s) Does not support skeletalmesh with Physics Asset and destructibles."), *PrimComp->GetPathName());
return false;
}
ECollisionChannel TraceChannel = PrimComp->GetCollisionObjectType();
#if WITH_PHYSX
// if extent is 0, do line trace
if (PrimComp->IsZeroExtent())
{
return RaycastSingle(this, OutHit, Start, End, TraceChannel, Params, FCollisionResponseParams(PrimComp->GetCollisionResponseToChannels()));
}
PxRigidActor* PRigidActor = PrimComp->BodyInstance.GetPxRigidActor();
if(PRigidActor == NULL)
{
UE_LOG(LogCollision, Log, TEXT("ComponentSweepMulti : (%s) No physics data"), *PrimComp->GetPathName());
return false;
}
// Get all the shapes from the actor
TArray<PxShape*, TInlineAllocator<8>> PShapes;
PShapes.AddZeroed(PRigidActor->getNbShapes());
int32 NumShapes = PRigidActor->getShapes(PShapes.GetData(), PShapes.Num());
// calculate the test global pose of the actor
PxTransform PGlobalStartPose = U2PTransform(FTransform(Start));
PxTransform PGlobalEndPose = U2PTransform(FTransform(End));
bool bHaveBlockingHit = false;
PxQuat PGeomRot = U2PQuat(Rot.Quaternion());
// Iterate over each shape
for(int32 ShapeIdx=0; ShapeIdx<PShapes.Num(); ShapeIdx++)
{
PxShape* PShape = PShapes[ShapeIdx];
check(PShape);
// Calc shape global pose
PxTransform PLocalShape = PShape->getLocalPose();
PxTransform PShapeGlobalStartPose = PGlobalStartPose.transform(PLocalShape);
PxTransform PShapeGlobalEndPose = PGlobalEndPose.transform(PLocalShape);
// consider localshape rotation for shape rotation
PxQuat PShapeRot = PGeomRot * PLocalShape.q;
GET_GEOMETRY_FROM_SHAPE(PGeom, PShape);
if(PGeom != NULL)
{
// @todo UE4, this might not be the best behavior. If we're looking for the most closest, this have to change to save the result, and find the closest one or
// any other options, right now if anything hits first, it will return
if (GeomSweepSingle(this, *PGeom, PShapeRot, OutHit, P2UVector(PShapeGlobalStartPose.p), P2UVector(PShapeGlobalEndPose.p), TraceChannel, Params, FCollisionResponseParams(PrimComp->GetCollisionResponseToChannels())))
{
bHaveBlockingHit = true;
break;
}
}
}
return bHaveBlockingHit;
#endif //WITH_PHYSX
return false;
}
示例10: ApplyMaterialToActor
/**
* Attempts to apply the material to the specified actor.
*
* @param TargetActor the actor to apply the material to
* @param MaterialToApply the material to apply to the actor
* @param OptionalMaterialSlot the material slot to apply to.
*
* @return true if the material was successfully applied to the actor
*/
bool FActorFactoryAssetProxy::ApplyMaterialToActor( AActor* TargetActor, UMaterialInterface* MaterialToApply, int32 OptionalMaterialSlot )
{
bool bResult = false;
if ( TargetActor != NULL && MaterialToApply != NULL )
{
ALandscapeProxy* Landscape = Cast<ALandscapeProxy>(TargetActor);
if (Landscape != NULL)
{
UProperty* MaterialProperty = FindField<UProperty>(ALandscapeProxy::StaticClass(), "LandscapeMaterial");
Landscape->PreEditChange(MaterialProperty);
Landscape->LandscapeMaterial = MaterialToApply;
FPropertyChangedEvent PropertyChangedEvent(MaterialProperty);
Landscape->PostEditChangeProperty(PropertyChangedEvent);
bResult = true;
}
else
{
TArray<UActorComponent*> EditableComponents;
FActorEditorUtils::GetEditableComponents( TargetActor, EditableComponents );
// Some actors could potentially have multiple mesh components, so we need to store all of the potentially valid ones
// (or else perform special cases with IsA checks on the target actor)
TArray<USceneComponent*> FoundMeshComponents;
// Find which mesh the user clicked on first.
TInlineComponentArray<USceneComponent*> SceneComponents;
TargetActor->GetComponents(SceneComponents);
for ( int32 ComponentIdx=0; ComponentIdx < SceneComponents.Num(); ComponentIdx++ )
{
USceneComponent* SceneComp = SceneComponents[ComponentIdx];
// Only apply the material to editable components. Components which are not exposed are not intended to be changed.
if( EditableComponents.Contains( SceneComp ) )
{
UMeshComponent* MeshComponent = Cast<UMeshComponent>(SceneComp);
if((MeshComponent && MeshComponent->IsRegistered()) ||
SceneComp->IsA<UDecalComponent>())
{
// Intentionally do not break the loop here, as there could be potentially multiple mesh components
FoundMeshComponents.AddUnique( SceneComp );
}
}
}
if ( FoundMeshComponents.Num() > 0 )
{
// Check each component that was found
for ( TArray<USceneComponent*>::TConstIterator MeshCompIter( FoundMeshComponents ); MeshCompIter; ++MeshCompIter )
{
USceneComponent* SceneComp = *MeshCompIter;
bResult = FComponentEditorUtils::AttemptApplyMaterialToComponent(SceneComp, MaterialToApply, OptionalMaterialSlot);
}
}
}
}
return bResult;
}
示例11: setupVehiclesAndCamera
void ASimModeWorldMultiRotor::setupVehiclesAndCamera(std::vector<VehiclePtr>& vehicles)
{
//get player controller
APlayerController* player_controller = this->GetWorld()->GetFirstPlayerController();
FTransform actor_transform = player_controller->GetActorTransform();
//put camera little bit above vehicle
FTransform camera_transform(actor_transform.GetLocation() + FVector(-300, 0, 200));
//we will either find external camera if it already exist in evironment or create one
APIPCamera* external_camera;
//find all BP camera directors in the environment
{
TArray<AActor*> camera_dirs;
UAirBlueprintLib::FindAllActor<ACameraDirector>(this, camera_dirs);
if (camera_dirs.Num() == 0) {
//create director
FActorSpawnParameters camera_spawn_params;
camera_spawn_params.SpawnCollisionHandlingOverride = ESpawnActorCollisionHandlingMethod::AdjustIfPossibleButAlwaysSpawn;
CameraDirector = this->GetWorld()->SpawnActor<ACameraDirector>(camera_director_class_, camera_transform, camera_spawn_params);
spawned_actors_.Add(CameraDirector);
//create external camera required for the director
external_camera = this->GetWorld()->SpawnActor<APIPCamera>(external_camera_class_, camera_transform, camera_spawn_params);
spawned_actors_.Add(external_camera);
}
else {
CameraDirector = static_cast<ACameraDirector*>(camera_dirs[0]);
external_camera = CameraDirector->getExternalCamera();
}
}
//find all vehicle pawns
{
TArray<AActor*> pawns;
UAirBlueprintLib::FindAllActor<TMultiRotorPawn>(this, pawns);
//if no vehicle pawns exists in environment
if (pawns.Num() == 0) {
//create vehicle pawn
FActorSpawnParameters pawn_spawn_params;
pawn_spawn_params.SpawnCollisionHandlingOverride =
ESpawnActorCollisionHandlingMethod::AdjustIfPossibleButAlwaysSpawn;
TMultiRotorPawn* spawned_pawn = this->GetWorld()->SpawnActor<TMultiRotorPawn>(
vehicle_pawn_class_, actor_transform, pawn_spawn_params);
spawned_actors_.Add(spawned_pawn);
pawns.Add(spawned_pawn);
}
//set up vehicle pawns
for (AActor* pawn : pawns)
{
//initialize each vehicle pawn we found
TMultiRotorPawn* vehicle_pawn = static_cast<TMultiRotorPawn*>(pawn);
vehicle_pawn->initializeForBeginPlay();
//chose first pawn as FPV if none is designated as FPV
VehiclePawnWrapper* wrapper = vehicle_pawn->getVehiclePawnWrapper();
if (enable_collision_passthrough)
wrapper->config.enable_passthrough_on_collisions = true;
if (wrapper->config.is_fpv_vehicle || fpv_vehicle_pawn_wrapper_ == nullptr)
fpv_vehicle_pawn_wrapper_ = wrapper;
//now create the connector for each pawn
auto vehicle = createVehicle(wrapper);
if (vehicle != nullptr) {
vehicles.push_back(vehicle);
if (fpv_vehicle_pawn_wrapper_ == wrapper)
fpv_vehicle_connector_ = vehicle;
}
//else we don't have vehicle for this pawn
}
}
CameraDirector->initializeForBeginPlay(getInitialViewMode(), fpv_vehicle_pawn_wrapper_, external_camera);
}
示例12: BuildSelectedActorInfo
FSelectedActorInfo BuildSelectedActorInfo( const TArray<AActor*>& SelectedActors)
{
FSelectedActorInfo ActorInfo;
if( SelectedActors.Num() > 0 )
{
// Get the class type of the first actor.
AActor* FirstActor = SelectedActors[0];
if( FirstActor && !FirstActor->HasAnyFlags( RF_ClassDefaultObject ) )
{
UClass* FirstClass = FirstActor->GetClass();
UObject* FirstArchetype = FirstActor->GetArchetype();
ActorInfo.bAllSelectedAreBrushes = Cast< ABrush >( FirstActor ) != NULL;
ActorInfo.SelectionClass = FirstClass;
// Compare all actor types with the baseline.
for ( int32 ActorIndex = 0; ActorIndex < SelectedActors.Num(); ++ActorIndex )
{
AActor* CurrentActor = SelectedActors[ ActorIndex ];
if( CurrentActor->HasAnyFlags( RF_ClassDefaultObject ) )
{
continue;
}
ABrush* Brush = Cast< ABrush >( CurrentActor );
if( !Brush)
{
ActorInfo.bAllSelectedAreBrushes = false;
}
else
{
if( !ActorInfo.bHaveBuilderBrush )
{
ActorInfo.bHaveBuilderBrush = FActorEditorUtils::IsABuilderBrush(Brush);
}
ActorInfo.bHaveBrush |= true;
ActorInfo.bHaveBSPBrush |= (!Brush->IsVolumeBrush());
ActorInfo.bHaveVolume |= Brush->IsVolumeBrush();
}
UClass* CurrentClass = CurrentActor->GetClass();
if( FirstClass != CurrentClass )
{
ActorInfo.bAllSelectedActorsOfSameType = false;
ActorInfo.SelectionClass = NULL;
FirstClass = NULL;
}
else
{
ActorInfo.SelectionClass = CurrentActor->GetClass();
}
++ActorInfo.NumSelected;
if( ActorInfo.bAllSelectedActorsBelongToCurrentLevel )
{
if( !CurrentActor->GetOuter()->IsA(ULevel::StaticClass()) || !CurrentActor->GetLevel()->IsCurrentLevel() )
{
ActorInfo.bAllSelectedActorsBelongToCurrentLevel = false;
}
}
if( ActorInfo.bAllSelectedActorsBelongToSameWorld )
{
if ( !ActorInfo.SharedWorld )
{
ActorInfo.SharedWorld = CurrentActor->GetWorld();
check(ActorInfo.SharedWorld);
}
else
{
if( ActorInfo.SharedWorld != CurrentActor->GetWorld() )
{
ActorInfo.bAllSelectedActorsBelongToCurrentLevel = false;
ActorInfo.SharedWorld = NULL;
}
}
}
// To prevent move to other level for Landscape if its components are distributed in streaming levels
if (CurrentActor->IsA(ALandscape::StaticClass()))
{
ALandscape* Landscape = CastChecked<ALandscape>(CurrentActor);
if (!Landscape || !Landscape->HasAllComponent())
{
if( !ActorInfo.bAllSelectedActorsBelongToCurrentLevel )
{
ActorInfo.bAllSelectedActorsBelongToCurrentLevel = true;
}
}
}
if ( ActorInfo.bSelectedActorsBelongToSameLevel )
{
ULevel* ActorLevel = CurrentActor->GetOuter()->IsA(ULevel::StaticClass()) ? CurrentActor->GetLevel() : NULL;
if ( !ActorInfo.SharedLevel )
{
// This is the first selected actor we've encountered.
//.........这里部分代码省略.........
示例13: CompileShader_Metal
//.........这里部分代码省略.........
TEXT("%s shaders not supported for use in Metal."),
GLFrequencyStringTable[Input.Target.Frequency]
);
return;
}
// This requires removing the HLSLCC_NoPreprocess flag later on!
if (!RemoveUniformBuffersFromSource(PreprocessedShader))
{
return;
}
// Write out the preprocessed file and a batch file to compile it if requested (DumpDebugInfoPath is valid)
if (bDumpDebugInfo)
{
FArchive* FileWriter = IFileManager::Get().CreateFileWriter(*(Input.DumpDebugInfoPath / Input.SourceFilename + TEXT(".usf")));
if (FileWriter)
{
auto AnsiSourceFile = StringCast<ANSICHAR>(*PreprocessedShader);
FileWriter->Serialize((ANSICHAR*)AnsiSourceFile.Get(), AnsiSourceFile.Length());
FileWriter->Close();
delete FileWriter;
}
}
uint32 CCFlags = HLSLCC_NoPreprocess | HLSLCC_PackUniforms;
//CCFlags |= HLSLCC_FlattenUniformBuffers | HLSLCC_FlattenUniformBufferStructures;
if (bDumpDebugInfo)
{
const FString MetalFile = (Input.DumpDebugInfoPath / TEXT("Output.metal"));
const FString USFFile = (Input.DumpDebugInfoPath / Input.SourceFilename) + TEXT(".usf");
const FString CCBatchFileContents = CreateCommandLineHLSLCC(USFFile, MetalFile, *Input.EntryPointName, Frequency, CCFlags);
if (!CCBatchFileContents.IsEmpty())
{
FFileHelper::SaveStringToFile(CCBatchFileContents, *(Input.DumpDebugInfoPath / TEXT("CrossCompile.bat")));
}
}
// Required as we added the RemoveUniformBuffersFromSource() function (the cross-compiler won't be able to interpret comments w/o a preprocessor)
CCFlags &= ~HLSLCC_NoPreprocess;
FMetalCodeBackend MetalBackEnd(CCFlags);
FMetalLanguageSpec MetalLanguageSpec;
int32 Result = HlslCrossCompile(
TCHAR_TO_ANSI(*Input.SourceFilename),
TCHAR_TO_ANSI(*PreprocessedShader),
TCHAR_TO_ANSI(*Input.EntryPointName),
Frequency,
&MetalBackEnd,
&MetalLanguageSpec,
CCFlags,
HlslCompilerTarget,
&MetalShaderSource,
&ErrorLog
);
int32 SourceLen = MetalShaderSource ? FCStringAnsi::Strlen(MetalShaderSource) : 0;
if (bDumpDebugInfo)
{
if (SourceLen > 0)
{
FArchive* FileWriter = IFileManager::Get().CreateFileWriter(*(Input.DumpDebugInfoPath / Input.SourceFilename + TEXT(".metal")));
if (FileWriter)
{
FileWriter->Serialize(MetalShaderSource, SourceLen + 1);
FileWriter->Close();
delete FileWriter;
}
}
}
if (Result != 0)
{
Output.Target = Input.Target;
BuildMetalShaderOutput(Output, Input, MetalShaderSource, SourceLen, Output.Errors);
}
else
{
FString Tmp = ANSI_TO_TCHAR(ErrorLog);
TArray<FString> ErrorLines;
Tmp.ParseIntoArray(ErrorLines, TEXT("\n"), true);
for (int32 LineIndex = 0; LineIndex < ErrorLines.Num(); ++LineIndex)
{
const FString& Line = ErrorLines[LineIndex];
ParseHlslccError(Output.Errors, Line);
}
}
if (MetalShaderSource)
{
free(MetalShaderSource);
}
if (ErrorLog)
{
free(ErrorLog);
}
}
}
示例14: BuildMetalShaderOutput
/**
* Construct the final microcode from the compiled and verified shader source.
* @param ShaderOutput - Where to store the microcode and parameter map.
* @param InShaderSource - Metal source with input/output signature.
* @param SourceLen - The length of the Metal source code.
*/
static void BuildMetalShaderOutput(
FShaderCompilerOutput& ShaderOutput,
const FShaderCompilerInput& ShaderInput,
const ANSICHAR* InShaderSource,
int32 SourceLen,
TArray<FShaderCompilerError>& OutErrors
)
{
FMetalCodeHeader Header = {0};
const ANSICHAR* ShaderSource = InShaderSource;
FShaderParameterMap& ParameterMap = ShaderOutput.ParameterMap;
EShaderFrequency Frequency = (EShaderFrequency)ShaderOutput.Target.Frequency;
TBitArray<> UsedUniformBufferSlots;
UsedUniformBufferSlots.Init(false,32);
// Write out the magic markers.
Header.Frequency = Frequency;
#define DEF_PREFIX_STR(Str) \
const ANSICHAR* Str##Prefix = "// @" #Str ": "; \
const int32 Str##PrefixLen = FCStringAnsi::Strlen(Str##Prefix)
DEF_PREFIX_STR(Inputs);
DEF_PREFIX_STR(Outputs);
DEF_PREFIX_STR(UniformBlocks);
DEF_PREFIX_STR(Uniforms);
DEF_PREFIX_STR(PackedGlobals);
DEF_PREFIX_STR(PackedUB);
DEF_PREFIX_STR(PackedUBCopies);
DEF_PREFIX_STR(PackedUBGlobalCopies);
DEF_PREFIX_STR(Samplers);
DEF_PREFIX_STR(UAVs);
DEF_PREFIX_STR(SamplerStates);
DEF_PREFIX_STR(NumThreads);
#undef DEF_PREFIX_STR
// Skip any comments that come before the signature.
while ( FCStringAnsi::Strncmp(ShaderSource, "//", 2) == 0 &&
FCStringAnsi::Strncmp(ShaderSource, "// @", 4) != 0 )
{
while (*ShaderSource && *ShaderSource++ != '\n') {}
}
// HLSLCC first prints the list of inputs.
if (FCStringAnsi::Strncmp(ShaderSource, InputsPrefix, InputsPrefixLen) == 0)
{
ShaderSource += InputsPrefixLen;
// Only inputs for vertex shaders must be tracked.
if (Frequency == SF_Vertex)
{
const ANSICHAR* AttributePrefix = "in_ATTRIBUTE";
const int32 AttributePrefixLen = FCStringAnsi::Strlen(AttributePrefix);
while (*ShaderSource && *ShaderSource != '\n')
{
// Skip the type.
while (*ShaderSource && *ShaderSource++ != ':') {}
// Only process attributes.
if (FCStringAnsi::Strncmp(ShaderSource, AttributePrefix, AttributePrefixLen) == 0)
{
ShaderSource += AttributePrefixLen;
uint8 AttributeIndex = ParseNumber(ShaderSource);
Header.Bindings.InOutMask |= (1 << AttributeIndex);
}
// Skip to the next.
while (*ShaderSource && *ShaderSource != ',' && *ShaderSource != '\n')
{
ShaderSource++;
}
if (Match(ShaderSource, '\n'))
{
break;
}
verify(Match(ShaderSource, ','));
}
}
else
{
// Skip to the next line.
while (*ShaderSource && *ShaderSource++ != '\n') {}
}
}
// Then the list of outputs.
if (FCStringAnsi::Strncmp(ShaderSource, OutputsPrefix, OutputsPrefixLen) == 0)
{
ShaderSource += OutputsPrefixLen;
// Only outputs for pixel shaders must be tracked.
if (Frequency == SF_Pixel)
//.........这里部分代码省略.........
示例15: ParseSearchResult
/**
* Create a search result from a server response
*
* @param ServerDetails Steam server details
*/
void FOnlineAsyncTaskSteamFindServerBase::ParseSearchResult(class gameserveritem_t* ServerDetails)
{
TSharedRef<FInternetAddr> ServerAddr = ISocketSubsystem::Get(PLATFORM_SOCKETSUBSYSTEM)->CreateInternetAddr();
ServerAddr->SetIp(ServerDetails->m_NetAdr.GetIP());
ServerAddr->SetPort(ServerDetails->m_NetAdr.GetConnectionPort());
int32 ServerQueryPort = ServerDetails->m_NetAdr.GetQueryPort();
UE_LOG_ONLINE(Warning, TEXT("Server response IP:%s"), *ServerAddr->ToString(false));
if (ServerDetails->m_bHadSuccessfulResponse)
{
FString GameTags(UTF8_TO_TCHAR(ServerDetails->m_szGameTags));
// Check for build compatibility
int32 ServerBuildId = 0;
int32 BuildUniqueId = GetBuildUniqueId();
TArray<FString> TagArray;
GameTags.ParseIntoArray(TagArray, TEXT(","), true);
if (TagArray.Num() > 0 && TagArray[0].StartsWith(STEAMKEY_BUILDUNIQUEID))
{
ServerBuildId = FCString::Atoi(*TagArray[0].Mid(ARRAY_COUNT(STEAMKEY_BUILDUNIQUEID)));
}
if (ServerBuildId != 0 && ServerBuildId == BuildUniqueId)
{
// Create a new pending search result
FPendingSearchResultSteam* NewPendingSearch = new (PendingSearchResults) FPendingSearchResultSteam(this);
NewPendingSearch->ServerId = FUniqueNetIdSteam(ServerDetails->m_steamID);
NewPendingSearch->HostAddr = ServerAddr;
// Fill search result members
FOnlineSessionSearchResult* NewSearchResult = &NewPendingSearch->PendingSearchResult;
NewSearchResult->PingInMs = FMath::Clamp(ServerDetails->m_nPing, 0, MAX_QUERY_PING);
// Fill session members
FOnlineSession* NewSession = &NewSearchResult->Session;
//NewSession->OwningUserId = ;
NewSession->OwningUserName = UTF8_TO_TCHAR(ServerDetails->GetName());
NewSession->NumOpenPublicConnections = ServerDetails->m_nMaxPlayers - ServerDetails->m_nPlayers;
NewSession->NumOpenPrivateConnections = 0;
// Fill session settings members
NewSession->SessionSettings.NumPublicConnections = ServerDetails->m_nMaxPlayers;
NewSession->SessionSettings.NumPrivateConnections = 0;
NewSession->SessionSettings.bAntiCheatProtected = ServerDetails->m_bSecure ? true : false;
NewSession->SessionSettings.Set(SETTING_MAPNAME, FString(UTF8_TO_TCHAR(ServerDetails->m_szMap)), EOnlineDataAdvertisementType::ViaOnlineService);
// Start a rules request for this new result
NewPendingSearch->ServerQueryHandle = SteamMatchmakingServersPtr->ServerRules(ServerDetails->m_NetAdr.GetIP(), ServerQueryPort, NewPendingSearch);
if (NewPendingSearch->ServerQueryHandle == HSERVERQUERY_INVALID)
{
// Remove the failed element
PendingSearchResults.RemoveAtSwap(PendingSearchResults.Num() - 1);
}
}
else
{
UE_LOG_ONLINE(Warning, TEXT("Removed incompatible build: ServerBuildUniqueId = 0x%08x, GetBuildUniqueId() = 0x%08x"),
ServerBuildId, BuildUniqueId);
}
}
}