void UPaperGroupedSpriteComponent::CreateAllInstanceBodies() { QUICK_SCOPE_CYCLE_COUNTER(STAT_UPaperGroupedSpriteComponent_CreateAllInstanceBodies); FPhysScene* PhysScene = GetWorld()->GetPhysicsScene(); const int32 NumBodies = PerInstanceSpriteData.Num(); check(InstanceBodies.Num() == 0); InstanceBodies.SetNumUninitialized(NumBodies); TArray<FTransform> Transforms; Transforms.Reserve(NumBodies); TArray<TWeakObjectPtr<UBodySetup>> BodySetups; BodySetups.Reserve(NumBodies); for (int32 InstanceIndex = 0; InstanceIndex < NumBodies; ++InstanceIndex) { const FSpriteInstanceData& InstanceData = PerInstanceSpriteData[InstanceIndex]; FBodyInstance* InstanceBody = InitInstanceBody(InstanceIndex, InstanceData, PhysScene); InstanceBodies[InstanceIndex] = InstanceBody; BodySetups.Add((InstanceBody != nullptr) ? InstanceBody->BodySetup : TWeakObjectPtr<UBodySetup>()); } if (SceneProxy != nullptr) { ENQUEUE_UNIQUE_RENDER_COMMAND_TWOPARAMETER( FSendPaperGroupBodySetups, FGroupedSpriteSceneProxy*, InSceneProxy, (FGroupedSpriteSceneProxy*)SceneProxy, TArray<TWeakObjectPtr<UBodySetup>>, InBodySetups, BodySetups, { InSceneProxy->SetAllBodySetups_RenderThread(InBodySetups); });
/** Populate OutSlateVerts and OutIndexes with data from this static mesh such that Slate can render it. */ static void SlateMeshToSlateRenderData(const USlateVectorArtData& DataSource, TArray<FSlateVertex>& OutSlateVerts, TArray<SlateIndex>& OutIndexes) { // Populate Index data { // Note that we do a slow copy because on some platforms the SlateIndex is // a 16-bit value, so we cannot do a memcopy. const TArray<uint32>& IndexDataSource = DataSource.GetIndexData(); const int32 NumIndexes = IndexDataSource.Num(); OutIndexes.Empty(); OutIndexes.Reserve(NumIndexes); for (int32 i = 0; i < NumIndexes; ++i) { OutIndexes.Add(IndexDataSource[i]); } } // Populate Vertex Data { const TArray<FSlateMeshVertex> VertexDataSource = DataSource.GetVertexData(); const uint32 NumVerts = VertexDataSource.Num(); OutSlateVerts.Empty(); OutSlateVerts.Reserve(NumVerts); for (uint32 i = 0; i < NumVerts; ++i) { const FSlateMeshVertex& SourceVertex = VertexDataSource[i]; FSlateVertex& NewVert = OutSlateVerts[OutSlateVerts.AddUninitialized()]; // Copy Position { NewVert.Position[0] = SourceVertex.Position.X; NewVert.Position[1] = SourceVertex.Position.Y; } // Copy Color { NewVert.Color = SourceVertex.Color; } // Copy all the UVs that we have, and as many as we can fit. { NewVert.TexCoords[0] = SourceVertex.UV0.X; NewVert.TexCoords[1] = SourceVertex.UV0.Y; NewVert.TexCoords[2] = SourceVertex.UV1.X; NewVert.TexCoords[3] = SourceVertex.UV1.Y; NewVert.MaterialTexCoords[0] = SourceVertex.UV2.X; NewVert.MaterialTexCoords[1] = SourceVertex.UV2.Y; NewVert.ClipRect.TopLeft = SourceVertex.UV3; NewVert.ClipRect.ExtentX = SourceVertex.UV4; NewVert.ClipRect.ExtentY = SourceVertex.UV5; } } } }
static void R_ExtendSpriteFrames(spritedef_t &spr, int frame) { unsigned int i, newstart; if (spr.numframes >= ++frame) { // The sprite already has enough frames, so do nothing. return; } if (spr.numframes == 0 || (spr.spriteframes + spr.numframes == SpriteFrames.Size())) { // Sprite's frames are at the end of the array, or it has no frames // at all, so we can tack the new frames directly on to the end // of the SpriteFrames array. newstart = SpriteFrames.Reserve(frame - spr.numframes); if (spr.numframes == 0) { spr.spriteframes = WORD(newstart); } } else { // We need to allocate space for all the sprite's frames and copy // the existing ones over to the new space. The old space will be // lost. newstart = SpriteFrames.Reserve(frame); for (i = 0; i < spr.numframes; ++i) { SpriteFrames[newstart + i] = SpriteFrames[spr.spriteframes + i]; } spr.spriteframes = WORD(newstart); newstart += i; } // Initialize all new frames to 0. memset(&SpriteFrames[newstart], 0, sizeof(spriteframe_t)*(frame - spr.numframes)); spr.numframes = frame; }
//!< FPrimitiveSceneProxy virtual void GetDynamicMeshElements(const TArray<const FSceneView*>& Views, const FSceneViewFamily& ViewFamily, uint32 VisibilityMap, class FMeshElementCollector& Collector) const override { FDynamicMeshBuilder MeshBuilder; const auto Num = 20; const auto DeltaUV = 1.0f / (Num - 1); TArray<FDynamicMeshVertex> Vertices; Vertices.Reserve(Num * Num); for (auto i = 0; i < Num; ++i) { for (auto j = 0; j < Num; ++j) { const auto UV = FVector2D(DeltaUV * j, DeltaUV * i); FDynamicMeshVertex Vertex; Vertex.Position = GetPosition(UV); Vertex.TextureCoordinate = GetUV(UV); const auto Edge01 = GetPosition(UV + FVector2D(0.01f, 0.0f)) - Vertex.Position; const auto Edge02 = GetPosition(UV - FVector2D(0.0f, 0.01f)) - Vertex.Position; Vertex.TangentX = Edge01.GetSafeNormal(); Vertex.TangentZ = (Edge02 ^ Edge01).GetSafeNormal(); Vertex.Color = FColor::Green; Vertices.Add(Vertex); } } MeshBuilder.AddVertices(Vertices); TArray<int32> Indices; Indices.Reserve((Num - 1) * (Num - 1) * 6); for (auto i = 0; i < Num - 1; ++i) { for (auto j = 0; j < Num - 1; ++j) { const auto Index = j + i * Num; Indices.Add(Index); Indices.Add(Index + Num); Indices.Add(Index + 1); Indices.Add(Index + 1); Indices.Add(Index + Num); Indices.Add(Index + Num + 1); } } MeshBuilder.AddTriangles(Indices); auto MaterialRenderProxy = UMaterial::GetDefaultMaterial(MD_Surface)->GetRenderProxy(IsSelected()); if (nullptr != MaterialInterface) { MaterialRenderProxy = MaterialInterface->GetRenderProxy(false); } if (Views[0]->Family->EngineShowFlags.Wireframe) { MaterialRenderProxy = GEngine->WireframeMaterial->GetRenderProxy(IsSelected()); } MeshBuilder.GetMesh(GetLocalToWorld(), MaterialRenderProxy, 0, false, false, 0, Collector); }
void ScanDirectory(TArray<FFileList> &list, const char *dirpath) { struct _finddata_t fileinfo; intptr_t handle; FString dirmatch; dirmatch << dirpath << "*"; if ((handle = _findfirst(dirmatch, &fileinfo)) == -1) { I_Error("Could not scan '%s': %s\n", dirpath, strerror(errno)); } else { do { if (fileinfo.attrib & _A_HIDDEN) { // Skip hidden files and directories. (Prevents SVN bookkeeping // info from being included.) continue; } if (fileinfo.attrib & _A_SUBDIR) { if (fileinfo.name[0] == '.' && (fileinfo.name[1] == '\0' || (fileinfo.name[1] == '.' && fileinfo.name[2] == '\0'))) { // Do not record . and .. directories. continue; } FFileList *fl = &list[list.Reserve(1)]; fl->Filename << dirpath << fileinfo.name; fl->isDirectory = true; FString newdir = fl->Filename; newdir << "/"; ScanDirectory(list, newdir); } else { FFileList *fl = &list[list.Reserve(1)]; fl->Filename << dirpath << fileinfo.name; fl->isDirectory = false; } } while (_findnext(handle, &fileinfo) == 0); _findclose(handle); } }
void ScanDirectory(TArray<FFileList> &list, const char *dirpath) { DIR *directory = opendir(dirpath); if(directory == NULL) return; struct dirent *file; while((file = readdir(directory)) != NULL) { if(file->d_name[0] == '.') //File is hidden or ./.. directory so ignore it. continue; FFileList *fl = &list[list.Reserve(1)]; fl->Filename << dirpath << file->d_name; struct stat fileStat; stat(fl->Filename, &fileStat); fl->isDirectory = S_ISDIR(fileStat.st_mode); if(fl->isDirectory) { FString newdir = fl->Filename; newdir += "/"; ScanDirectory(list, newdir); continue; } } closedir(directory); }
bool AddSeg(seg_t *seg) { FGLSectionLine &line = SectionLines[SectionLines.Reserve(1)]; bool firstline = loop->numlines == 0; if (ISDONE(seg-segs, processed_segs)) { // should never happen! DPrintf("Tried to add seg %d to Sections twice. Cannot create Sections.\n", seg-segs); return false; } SETDONE(seg-segs, processed_segs); section_for_segs[seg-segs] = Sections.Size()-1; line.start = seg->v1; line.end = seg->v2; line.sidedef = seg->sidedef; line.linedef = seg->linedef; line.refseg = seg; line.polysub = NULL; line.otherside = -1; if (loop->numlines == 0) { v1_l1 = seg->v1; v2_l1 = seg->v2; } loop->numlines++; return true; }
void NewLoop() { section->numloops++; loop = &SectionLoops[SectionLoops.Reserve(1)]; loop->startline = SectionLines.Size(); loop->numlines = 0 ; }
void UEnvQueryGenerator_SimpleGrid::GenerateItems(FEnvQueryInstance& QueryInstance) const { UObject* BindOwner = QueryInstance.Owner.Get(); GridSize.BindData(BindOwner, QueryInstance.QueryID); SpaceBetween.BindData(BindOwner, QueryInstance.QueryID); float RadiusValue = GridSize.GetValue(); float DensityValue = SpaceBetween.GetValue(); const int32 ItemCount = FPlatformMath::TruncToInt((RadiusValue * 2.0f / DensityValue) + 1); const int32 ItemCountHalf = ItemCount / 2; TArray<FVector> ContextLocations; QueryInstance.PrepareContext(GenerateAround, ContextLocations); TArray<FNavLocation> GridPoints; GridPoints.Reserve(ItemCount * ItemCount * ContextLocations.Num()); for (int32 ContextIndex = 0; ContextIndex < ContextLocations.Num(); ContextIndex++) { for (int32 IndexX = 0; IndexX <= ItemCount; ++IndexX) { for (int32 IndexY = 0; IndexY <= ItemCount; ++IndexY) { const FNavLocation TestPoint = FNavLocation(ContextLocations[ContextIndex] - FVector(DensityValue * (IndexX - ItemCountHalf), DensityValue * (IndexY - ItemCountHalf), 0)); GridPoints.Add(TestPoint); } } } ProjectAndFilterNavPoints(GridPoints, QueryInstance); StoreNavPoints(GridPoints, QueryInstance); }
TArray<FActiveGameplayEffectHandle> FGameplayAbilityTargetData::ApplyGameplayEffectSpec(FGameplayEffectSpec& InSpec, FPredictionKey PredictionKey) { TArray<FActiveGameplayEffectHandle> AppliedHandles; if (!ensure(InSpec.GetContext().IsValid() && InSpec.GetContext().GetInstigatorAbilitySystemComponent())) { return AppliedHandles; } TArray<TWeakObjectPtr<AActor> > Actors = GetActors(); AppliedHandles.Reserve(Actors.Num()); for (TWeakObjectPtr<AActor> TargetActor : Actors) { UAbilitySystemComponent* TargetComponent = UAbilitySystemBlueprintLibrary::GetAbilitySystemComponent(TargetActor.Get()); if (TargetComponent) { // We have to make a new effect spec and context here, because otherwise the targeting info gets accumulated and things take damage multiple times FGameplayEffectSpec SpecToApply(InSpec); FGameplayEffectContextHandle EffectContext = SpecToApply.GetContext().Duplicate(); SpecToApply.SetContext(EffectContext); AddTargetDataToContext(EffectContext, false); AppliedHandles.Add(EffectContext.GetInstigatorAbilitySystemComponent()->ApplyGameplayEffectSpecToTarget(SpecToApply, TargetComponent, PredictionKey)); } } return AppliedHandles; }
int32 UCrowdManager::GetNearbyAgentLocations(const ICrowdAgentInterface* Agent, TArray<FVector>& OutLocations) const { const int32 InitialSize = OutLocations.Num(); #if WITH_RECAST const FCrowdAgentData* AgentData = ActiveAgents.Find(Agent); if (AgentData && AgentData->bIsSimulated && AgentData->IsValid() && DetourCrowd) { const dtCrowdAgent* CrowdAgent = DetourCrowd->getAgent(AgentData->AgentIndex); if (CrowdAgent) { OutLocations.Reserve(InitialSize + CrowdAgent->nneis); for (int32 NeighbourIndex = 0; NeighbourIndex < CrowdAgent->nneis; NeighbourIndex++) { const dtCrowdAgent* NeighbourAgent = DetourCrowd->getAgent(CrowdAgent->neis[NeighbourIndex].idx); if (NeighbourAgent) { OutLocations.Add(Recast2UnrealPoint(NeighbourAgent->npos)); } } } } #endif return OutLocations.Num() - InitialSize; }
// add a poly index to the render list // note that the render list is a dynamic array of dynamic arrays // the first array is keyed with the OpenGL texture object // the sub-array is keyed with the polygon index // these are only ever resized up and only the count is reset each frame (they are completely reset on a map change, though) void RL_AddPoly(GLuint tex, int polyIndex) { RList *rl; int amt; unsigned int lastSize, i; //return; if ((tex + 1) >= renderList.Size()) { lastSize = renderList.Size(); amt = (tex + 1) - renderList.Size(); renderList.Reserve(amt); for (i = lastSize; i < lastSize + amt; i++) { rl = &renderList[i]; rl->numPolys = 0; rl->polys.Init(); } } rl = &renderList[tex]; if (rl->numPolys == rl->polys.Size()) { rl->polys.Reserve(1); } rl->polys[rl->numPolys] = polyIndex; rl->numPolys++; }
void FGroupedKeyCollection::InitializeRecursive(const TArray<FSequencerDisplayNode*>& InNodes, float DuplicateThreshold) { KeyAreas.Reset(); Groups.Reset(); TArray<TSharedRef<FSequencerSectionKeyAreaNode>> AllKeyAreaNodes; AllKeyAreaNodes.Reserve(36); for (FSequencerDisplayNode* Node : InNodes) { if (Node->GetType() == ESequencerNode::KeyArea) { AllKeyAreaNodes.Add(StaticCastSharedRef<FSequencerSectionKeyAreaNode>(Node->AsShared())); } Node->GetChildKeyAreaNodesRecursively(AllKeyAreaNodes); } for (const auto& Node : AllKeyAreaNodes) { const TArray<TSharedRef<IKeyArea>>& AllKeyAreas = Node->GetAllKeyAreas(); KeyAreas.Reserve(KeyAreas.Num() + AllKeyAreas.Num()); for (const TSharedRef<IKeyArea>& KeyArea : AllKeyAreas) { AddKeyArea(KeyArea); } } RemoveDuplicateKeys(DuplicateThreshold); }
void FGameplayCueTranslationManager::BuildTagTranslationTable_Forward() { #if WITH_EDITOR SCOPE_LOG_TIME_IN_SECONDS(*FString::Printf(TEXT("FGameplayCueTranslatorManager::BuildTagTranslationTable_Forward")), nullptr) #endif // Build the normal TranslationLUT first. This is only done to make sure that UsedTranslators are filled in, giving "real" tags higher priority. // Example: // 1) GC.Rampage.Enraged // 2) GC.Rampage.Elemental.Enraged // // 2 is am override for 1, but comes first alphabetically. In the _Forward method, 2 would be handled first and expanded again to GC.Rampage.Elemental.Elemental.Enraged. // rule recursion wouldn't have been hit yet because 2 actually exists and would be encountered before 1. // // Since BuildTagTranslationTable_Forward is only called by the editor and BuildTagTranslationTable is already fast, this is the simplest way to avoid the above example. // _Forward() could be made more complicated to test for this itself, but doesn't seem like a good trade off for how it would complicate the function. BuildTagTranslationTable(); TArray<FName> SplitNames; SplitNames.Reserve(10); FGameplayTagContainer AllGameplayCueTags = TagManager->RequestGameplayTagChildren(UGameplayCueSet::BaseGameplayCueTag()); // Each GameplayCueTag for (const FGameplayTag& Tag : AllGameplayCueTags) { SplitNames.Reset(); TagManager->SplitGameplayTagFName(Tag, SplitNames); BuildTagTranslationTable_Forward_r(Tag.GetTagName(), SplitNames); } }
bool FProceduralFoliageBroadphase::GetOverlaps(FProceduralFoliageInstance* Instance, TArray<FProceduralFoliageOverlap>& Overlaps) const { const float AShadeRadius = Instance->GetShadeRadius(); const float ACollisionRadius = Instance->GetCollisionRadius(); TArray<FProceduralFoliageInstance*> PossibleOverlaps; const FBox2D AABB = GetMaxAABB(Instance); QuadTree.GetElements(AABB, PossibleOverlaps); Overlaps.Reserve(Overlaps.Num() + PossibleOverlaps.Num()); for (FProceduralFoliageInstance* Overlap : PossibleOverlaps) { if (Overlap != Instance) { //We must determine if this is an overlap of shade or an overlap of collision. If both the collision overlap wins bool bCollisionOverlap = CircleOverlap(Instance->Location, ACollisionRadius, Overlap->Location, Overlap->GetCollisionRadius()); bool bShadeOverlap = CircleOverlap(Instance->Location, AShadeRadius, Overlap->Location, Overlap->GetShadeRadius()); if (bCollisionOverlap || bShadeOverlap) { new (Overlaps)FProceduralFoliageOverlap(Instance, Overlap, bCollisionOverlap ? ESimulationOverlap::CollisionOverlap : ESimulationOverlap::ShadeOverlap); } } } return Overlaps.Num() > 0; }
void SAnimationCompressionPanel::ApplyAlgorithm(class UAnimCompress* Algorithm) { if ( Algorithm ) { const bool bProceed = EAppReturnType::Yes == FMessageDialog::Open( EAppMsgType::YesNo, FText::Format( NSLOCTEXT("UnrealEd", "AboutToCompressAnimations_F", "About to compress {0} animations. Proceed?"), FText::AsNumber(AnimSequences.Num()) ) ); if ( bProceed ) { TArray<UAnimSequence*> AnimSequencePtrs; AnimSequencePtrs.Reserve(AnimSequences.Num()); for(int32 Index = 0; Index < AnimSequences.Num(); ++Index) { AnimSequencePtrs.Add(AnimSequences[Index].Get()); } GWarn->BeginSlowTask( LOCTEXT("AnimCompressing", "Compressing"), true); Algorithm->Reduce(AnimSequencePtrs, true); GWarn->EndSlowTask( ); } } }
EConvertQueryResult AddSweepResults(bool& OutHasValidBlockingHit, const UWorld* World, int32 NumHits, PxSweepHit* Hits, float CheckLength, const PxFilterData& QueryFilter, TArray<FHitResult>& OutHits, const FVector& StartLoc, const FVector& EndLoc, const PxGeometry& Geom, const PxTransform& QueryTM, float MaxDistance, bool bReturnFaceIndex, bool bReturnPhysMat) { OutHits.Reserve(OutHits.Num() + NumHits); EConvertQueryResult ConvertResult = EConvertQueryResult::Valid; bool bHadBlockingHit = false; const PxVec3 PDir = U2PVector((EndLoc - StartLoc).GetSafeNormal()); for(int32 i=0; i<NumHits; i++) { PxSweepHit& PHit = Hits[i]; checkSlow(PHit.flags & PxHitFlag::eDISTANCE); if(PHit.distance <= MaxDistance) { PHit.faceIndex = FindFaceIndex(PHit, PDir); FHitResult& NewResult = OutHits[OutHits.AddDefaulted()]; if (ConvertQueryImpactHit(World, PHit, NewResult, CheckLength, QueryFilter, StartLoc, EndLoc, &Geom, QueryTM, bReturnFaceIndex, bReturnPhysMat) == EConvertQueryResult::Valid) { bHadBlockingHit |= NewResult.bBlockingHit; } else { // Reject invalid result (this should be rare). Remove from the results. OutHits.Pop(/*bAllowShrinking=*/ false); ConvertResult = EConvertQueryResult::Invalid; } } } // Sort results from first to last hit OutHits.Sort( FCompareFHitResultTime() ); OutHasValidBlockingHit = bHadBlockingHit; return ConvertResult; }
void FGameplayCueTranslationManager::BuildTagTranslationTable() { #if WITH_EDITOR SCOPE_LOG_TIME_IN_SECONDS(*FString::Printf(TEXT("FGameplayCueTranslatorManager::BuildTagTranslationTables")), nullptr) #endif TagManager = &IGameplayTagsModule::Get().GetGameplayTagsManager(); check(TagManager); FGameplayTagContainer AllGameplayCueTags = TagManager->RequestGameplayTagChildren(UGameplayCueSet::BaseGameplayCueTag()); ResetTranslationLUT(); RefreshNameSwaps(); // ---------------------------------------------------------------------------------------------- // Find what tags may be derived from swap rules. Note how we work backwards. // If we worked forward, by expanding out all possible tags and then seeing if they exist, // this would take much much longer! TArray<FName> SplitNames; SplitNames.Reserve(10); // All gameplaycue tags for (const FGameplayTag& Tag : AllGameplayCueTags) { SplitNames.Reset(); TagManager->SplitGameplayTagFName(Tag, SplitNames); BuildTagTranslationTable_r(Tag.GetTagName(), SplitNames); } // ---------------------------------------------------------------------------------------------- }
static void ParseStatistics(const char *fn, TArray<FStatistics> &statlist) { statlist.Clear(); try { FScanner sc; sc.OpenFile(fn); while (sc.GetString()) { FStatistics &ep_entry = statlist[statlist.Reserve(1)]; ep_entry.epi_header = sc.String; sc.MustGetString(); ep_entry.epi_name = sc.String; sc.MustGetStringName("{"); while (!sc.CheckString("}")) { FSessionStatistics &session = ep_entry.stats[ep_entry.stats.Reserve(1)]; sc.MustGetString(); sc.MustGetString(); strncpy(session.name, sc.String, 12); sc.MustGetString(); strncpy(session.info, sc.String, 30); int h,m,s; sc.MustGetString(); sscanf(sc.String, "%d:%d:%d", &h, &m, &s); session.timeneeded= ((((h*60)+m)*60)+s)*TICRATE; sc.MustGetNumber(); session.skill=sc.Number; if (sc.CheckString("{")) { while (!sc.CheckString("}")) { FLevelStatistics &lstats = session.levelstats[session.levelstats.Reserve(1)]; sc.MustGetString(); strncpy(lstats.name, sc.String, 12); sc.MustGetString(); strncpy(lstats.info, sc.String, 30); int h,m,s; sc.MustGetString(); sscanf(sc.String, "%d:%d:%d", &h, &m, &s); lstats.timeneeded= ((((h*60)+m)*60)+s)*TICRATE; lstats.skill = 0; } } } } } catch(CRecoverableError &) { } }
void UAIPerceptionComponent::GetHostileActors(TArray<AActor*>& OutActors) const { bool bDeadDataFound = false; OutActors.Reserve(PerceptualData.Num()); for (TActorPerceptionContainer::TConstIterator DataIt = GetPerceptualDataConstIterator(); DataIt; ++DataIt) { if (DataIt->Value.bIsHostile) { if (DataIt->Value.Target.IsValid()) { OutActors.Add(DataIt->Value.Target.Get()); } else { bDeadDataFound = true; } } } if (bDeadDataFound) { FSimpleDelegateGraphTask::CreateAndDispatchWhenReady( FSimpleDelegateGraphTask::FDelegate::CreateUObject(this, &UAIPerceptionComponent::RemoveDeadData), GET_STATID(STAT_FSimpleDelegateGraphTask_RequestingRemovalOfDeadPerceptionData), NULL, ENamedThreads::GameThread); } }
void URadialForceComponent::TickComponent(float DeltaTime, enum ELevelTick TickType, FActorComponentTickFunction *ThisTickFunction) { Super::TickComponent(DeltaTime, TickType, ThisTickFunction); if(bIsActive) { const FVector Origin = GetComponentLocation(); // Find objects within the sphere static FName AddForceOverlapName = FName(TEXT("AddForceOverlap")); TArray<FOverlapResult> Overlaps; FCollisionQueryParams Params(AddForceOverlapName, false); Params.bTraceAsyncScene = true; // want to hurt stuff in async scene // Ignore owner actor if desired if (bIgnoreOwningActor) { Params.AddIgnoredActor(GetOwner()); } GetWorld()->OverlapMultiByObjectType(Overlaps, Origin, FQuat::Identity, CollisionObjectQueryParams, FCollisionShape::MakeSphere(Radius), Params); // A component can have multiple physics presences (e.g. destructible mesh components). // The component should handle the radial force for all of the physics objects it contains // so here we grab all of the unique components to avoid applying impulses more than once. TArray<UPrimitiveComponent*, TInlineAllocator<1>> AffectedComponents; AffectedComponents.Reserve(Overlaps.Num()); for(FOverlapResult& OverlapResult : Overlaps) { if(UPrimitiveComponent* PrimitiveComponent = OverlapResult.Component.Get()) { AffectedComponents.AddUnique(PrimitiveComponent); } } for(UPrimitiveComponent* PrimitiveComponent : AffectedComponents) { PrimitiveComponent->AddRadialForce(Origin, Radius, ForceStrength, Falloff); // see if this is a target for a movement component AActor* ComponentOwner = PrimitiveComponent->GetOwner(); if(ComponentOwner) { TInlineComponentArray<UMovementComponent*> MovementComponents; ComponentOwner->GetComponents<UMovementComponent>(MovementComponents); for(const auto& MovementComponent : MovementComponents) { if(MovementComponent->UpdatedComponent == PrimitiveComponent) { MovementComponent->AddRadialForce(Origin, Radius, ForceStrength, Falloff); break; } } } } } }
void URadialForceComponent::FireImpulse() { const FVector Origin = GetComponentLocation(); // Find objects within the sphere static FName FireImpulseOverlapName = FName(TEXT("FireImpulseOverlap")); TArray<FOverlapResult> Overlaps; FCollisionQueryParams Params(FireImpulseOverlapName, false); Params.bTraceAsyncScene = true; // want to hurt stuff in async scene // Ignore owner actor if desired if (bIgnoreOwningActor) { Params.AddIgnoredActor(GetOwner()); } GetWorld()->OverlapMultiByObjectType(Overlaps, Origin, FQuat::Identity, CollisionObjectQueryParams, FCollisionShape::MakeSphere(Radius), Params); // A component can have multiple physics presences (e.g. destructible mesh components). // The component should handle the radial force for all of the physics objects it contains // so here we grab all of the unique components to avoid applying impulses more than once. TArray<UPrimitiveComponent*, TInlineAllocator<1>> AffectedComponents; AffectedComponents.Reserve(Overlaps.Num()); for(FOverlapResult& OverlapResult : Overlaps) { if(UPrimitiveComponent* PrimitiveComponent = OverlapResult.Component.Get()) { AffectedComponents.AddUnique(PrimitiveComponent); } } for(UPrimitiveComponent* PrimitiveComponent : AffectedComponents) { if(DestructibleDamage > SMALL_NUMBER) { if(UDestructibleComponent* DestructibleComponent = Cast<UDestructibleComponent>(PrimitiveComponent)) { DestructibleComponent->ApplyRadiusDamage(DestructibleDamage, Origin, Radius, ImpulseStrength, Falloff == RIF_Constant); } } // Apply impulse PrimitiveComponent->AddRadialImpulse(Origin, Radius, ImpulseStrength, Falloff, bImpulseVelChange); // See if this is a target for a movement component, if so apply the impulse to it TInlineComponentArray<UMovementComponent*> MovementComponents; PrimitiveComponent->GetOwner()->GetComponents<UMovementComponent>(MovementComponents); for(const auto& MovementComponent : MovementComponents) { if(MovementComponent->UpdatedComponent == PrimitiveComponent) { MovementComponent->AddRadialImpulse(Origin, Radius, ImpulseStrength, Falloff, bImpulseVelChange); break; } } } }
void PopulateMarkerNameArray(TArray<FName>& Pattern, TArray<FAnimSyncMarker>& AuthoredSyncMarkers) { Pattern.Reserve(AuthoredSyncMarkers.Num()); for (FAnimSyncMarker& Marker : AuthoredSyncMarkers) { Pattern.Add(Marker.MarkerName); } }
static void AppendCollectionToArray(const TSet<FName>& InObjectSet, TArray<FName>& OutObjectArray) { OutObjectArray.Reserve(OutObjectArray.Num() + InObjectSet.Num()); for (const FName& ObjectName : InObjectSet) { OutObjectArray.Add(ObjectName); } }
void UAISense_Blueprint::GetAllListenerActors(TArray<AActor*>& OutListenerActors) const { OutListenerActors.Reserve(OutListenerActors.Num() + ListenerContainer.Num()); for (auto Listener : ListenerContainer) { AActor* ActorOwner = Listener->GetOwner(); OutListenerActors.Add(ActorOwner); } }
bool UBlendSpaceBase::GetSamplesFromBlendInput(const FVector &BlendInput, TArray<FBlendSampleData> & OutSampleDataList) const { static TArray<FGridBlendSample, TInlineAllocator<4> > RawGridSamples; check(IsInGameThread() && !RawGridSamples.Num()); // this must be called non-recursively from the gamethread GetRawSamplesFromBlendInput(BlendInput, RawGridSamples); OutSampleDataList.Reset(); OutSampleDataList.Reserve(RawGridSamples.Num() * FEditorElement::MAX_VERTICES); // consolidate all samples for (int32 SampleNum=0; SampleNum<RawGridSamples.Num(); ++SampleNum) { FGridBlendSample& GridSample = RawGridSamples[SampleNum]; float GridWeight = GridSample.BlendWeight; FEditorElement& GridElement = GridSample.GridElement; for(int Ind = 0; Ind < GridElement.MAX_VERTICES; ++Ind) { if(GridElement.Indices[Ind] != INDEX_NONE) { int32 Index = OutSampleDataList.AddUnique(GridElement.Indices[Ind]); OutSampleDataList[Index].AddWeight(GridElement.Weights[Ind]*GridWeight); } } } /** Used to sort by Weight. */ struct FCompareFBlendSampleData { FORCEINLINE bool operator()( const FBlendSampleData& A, const FBlendSampleData& B ) const { return B.TotalWeight < A.TotalWeight; } }; OutSampleDataList.Sort( FCompareFBlendSampleData() ); // remove noisy ones int32 TotalSample = OutSampleDataList.Num(); float TotalWeight = 0.f; for (int32 I=0; I<TotalSample; ++I) { if (OutSampleDataList[I].TotalWeight < ZERO_ANIMWEIGHT_THRESH) { // cut anything in front of this OutSampleDataList.RemoveAt(I, TotalSample-I, false); // we won't shrink here, that might screw up alloc optimization at a higher level, if not this is temp anyway break; } TotalWeight += OutSampleDataList[I].TotalWeight; } for (int32 I=0; I<OutSampleDataList.Num(); ++I) { // normalize to all weights OutSampleDataList[I].TotalWeight /= TotalWeight; } RawGridSamples.Reset(); return (OutSampleDataList.Num()!=0); }
//------------------------------------------------------------------------------ static bool BlueprintNativeCodeGenUtilsImpl::GenerateModuleBuildFile(const FBlueprintNativeCodeGenManifest& Manifest) { FModuleManager& ModuleManager = FModuleManager::Get(); TArray<FString> PublicDependencies; // for IModuleInterface PublicDependencies.Add(CoreModuleName); // for Engine.h PublicDependencies.Add(EngineModuleName); if (GameProjectUtils::ProjectHasCodeFiles()) { const FString GameModuleName = FApp::GetGameName(); if (ModuleManager.ModuleExists(*GameModuleName)) { PublicDependencies.Add(GameModuleName); } } TArray<FString> AdditionalPublicDependencyModuleNames; GConfig->GetArray(TEXT("BlueprintNativizationSettings"), TEXT("AdditionalPublicDependencyModuleNames"), AdditionalPublicDependencyModuleNames, GEditorIni); PublicDependencies.Append(AdditionalPublicDependencyModuleNames); TArray<FString> PrivateDependencies; const TArray<UPackage*>& ModulePackages = Manifest.GetModuleDependencies(); PrivateDependencies.Reserve(ModulePackages.Num()); for (UPackage* ModulePkg : ModulePackages) { const FString PkgModuleName = FPackageName::GetLongPackageAssetName(ModulePkg->GetName()); if (ModuleManager.ModuleExists(*PkgModuleName)) { if (!PublicDependencies.Contains(PkgModuleName)) { PrivateDependencies.Add(PkgModuleName); } } else { UE_LOG(LogBlueprintCodeGen, Warning, TEXT("Failed to find module for package: %s"), *PkgModuleName); } } FBlueprintNativeCodeGenPaths TargetPaths = Manifest.GetTargetPaths(); FText ErrorMessage; bool bSuccess = GameProjectUtils::GenerateGameModuleBuildFile(TargetPaths.RuntimeBuildFile(), TargetPaths.RuntimeModuleName(), PublicDependencies, PrivateDependencies, ErrorMessage); if (!bSuccess) { UE_LOG(LogBlueprintCodeGen, Error, TEXT("Failed to generate module build file: %s"), *ErrorMessage.ToString()); } return bSuccess; }
void NewSection(sector_t *sec) { section = &Sections[Sections.Reserve(1)]; section->sector = sec; section->subsectors.Clear(); section->numloops = 0; section->startloop = SectionLoops.Size(); section->validcount = -1; NewLoop(); }
//============================================================================= TArray<INode *> CGraph::GetNodes () { TArray<INode *> outNodes; outNodes.Reserve(m_nodes.Count()); for (CNode * node : m_nodes) outNodes.Add(node); return outNodes; }
void USsPlayerComponent::SendRenderDynamicData_Concurrent() { if(NULL == SceneProxy) { return; } switch(RenderMode) { case ESsPlayerComponentRenderMode::Default: { const TArray<FSsRenderPart> RenderParts = Player.GetRenderParts(); TArray<FSsRenderPartWithMaterial> NewRenderParts; NewRenderParts.Reserve(RenderParts.Num()); for(int32 i = 0; i < RenderParts.Num(); ++i) { FSsRenderPartWithMaterial Part; FMemory::Memcpy(&Part, &(RenderParts[i]), sizeof(FSsRenderPart)); uint32 MatIdx = PartsMatIndex(Part.AlphaBlendType, Part.ColorBlendType); UMaterialInstanceDynamic** ppMID = PartsMIDMap[MatIdx].Find(Part.Texture); if(ppMID && *ppMID) { Part.Material = *ppMID; } else { UMaterialInstanceDynamic* NewMID = UMaterialInstanceDynamic::Create(BasePartsMaterials[MatIdx], this); if(NewMID) { NewMID->AddToRoot(); NewMID->SetFlags(RF_Transient); NewMID->SetTextureParameterValue(FName(TEXT("SsCellTexture")), Part.Texture); Part.Material = NewMID; PartsMIDMap[MatIdx].Add(Part.Texture, NewMID); } } NewRenderParts.Add(Part); } if(0 < NewRenderParts.Num()) { ENQUEUE_UNIQUE_RENDER_COMMAND_FOURPARAMETER( FSendSsPartsData, FSsRenderPartsProxy*, SsPartsProxy, (FSsRenderPartsProxy*)SceneProxy, TArray<FSsRenderPartWithMaterial>, InRenderParts, NewRenderParts, FVector2D, Pivot, Player.GetAnimPivot(), FVector2D, CanvasSizeUU, (Player.GetAnimCanvasSize() * UUPerPixel), { SsPartsProxy->CanvasSizeUU = CanvasSizeUU; SsPartsProxy->SetPivot(Pivot); SsPartsProxy->SetDynamicData_RenderThread(InRenderParts); }); }