UE4物理引擎模塊分析

前段時間工作需要,將引擎World中的物理數(shù)據(jù)導(dǎo)出來乎芳,供服務(wù)器使用幽崩,并且將UE的物理那塊移植出來苦始。趁現(xiàn)在還有印象,將物理這塊記錄下來, 引擎封裝了Phyx3.4慌申。
物理模塊相關(guān)源碼:
Engine\Source\Runtime\Engine\Classes\PhysicsEngine

Paste_Image.png

引擎支持的碰撞體形狀有:

  • Sphere
  • Box
  • Capsule
  • Convex Mesh

UBodyStep包含了碰撞數(shù)據(jù)shape陌选,F(xiàn)BodyInstance對應(yīng)一個PhysX的一個actor. 一個UBodyStep實(shí)例可以被多個FBodyInstance實(shí)例使用。一個UPrimitiveComponent可以包含多個FBodyInstance(UStaticMeshComponent包含一個,USkeletonMeshComponent包含多個)咨油。

FBodyInstance映射到Physx Scene中

Engine\Source\Runtime\Engine\Private\PhysicsEngine\BodyInstance.cpptemplate <bool bCompileStatic> struct FInitBodiesHelper負(fù)責(zé)創(chuàng)建PhysX的actor.

創(chuàng)建PxRigidActor

    physx::PxRigidActor* CreateActor_PhysX_AssumesLocked(FBodyInstance* Instance, const PxTransform& PTransform) const
    {
        physx::PxRigidDynamic* PNewDynamic = nullptr;

        const ECollisionEnabled::Type CollisionType = Instance->GetCollisionEnabled();
        const bool bDisableSim = !CollisionEnabledHasPhysics(CollisionType) && CDisableQueryOnlyActors.GetValueOnGameThread();

        if (IsStatic())
        {
            Instance->RigidActorSync = GPhysXSDK->createRigidStatic(PTransform);

            if(bDisableSim)
            {
                ModifyActorFlag_Isolated<PxActorFlag::eDISABLE_SIMULATION>(Instance->RigidActorSync, true);
            }

            if (PAsyncScene)
            {
                Instance->RigidActorAsync = GPhysXSDK->createRigidStatic(PTransform);

                if (bDisableSim)
                {
                    ModifyActorFlag_Isolated<PxActorFlag::eDISABLE_SIMULATION>(Instance->RigidActorAsync, true);
                }
            }
        }
        else
        {
            PNewDynamic = GPhysXSDK->createRigidDynamic(PTransform);
            bool bWantsAsyncScene = false;
            if(SpawnParams.DynamicActorScene == EDynamicActorScene::Default)
            {
                bWantsAsyncScene = Instance->bUseAsyncScene;
            }
            else
            {
                bWantsAsyncScene = SpawnParams.DynamicActorScene == EDynamicActorScene::UseAsyncScene;
            }
            
            if(bWantsAsyncScene && PhysScene && PhysScene->HasAsyncScene())
            {
                Instance->RigidActorAsync = PNewDynamic;
            }
            else
            {
                Instance->RigidActorSync = PNewDynamic;
            }

            if(!Instance->ShouldInstanceSimulatingPhysics())
            {
                ModifyRigidBodyFlag_Isolated<PxRigidBodyFlag::eKINEMATIC>(PNewDynamic, true);
            }

            PxActorFlags ActorFlags = PNewDynamic->getActorFlags();
            if(Instance->bGenerateWakeEvents)
            {
                ModifyActorFlag<PxActorFlag::eSEND_SLEEP_NOTIFIES>(ActorFlags, true);
            }

            if(bDisableSim)
            {
                ModifyActorFlag<PxActorFlag::eDISABLE_SIMULATION>(ActorFlags, true);
            }

            PNewDynamic->setActorFlags(ActorFlags);
        }

        return PNewDynamic;
    }

設(shè)置PxRigidActor的shape屬性

    bool CreateShapes_PhysX_AssumesLocked(FBodyInstance* Instance, physx::PxRigidActor* PNewDynamic, bool bKinematicTargetForSQ) const
    {
        UPhysicalMaterial* SimplePhysMat = Instance->GetSimplePhysicalMaterial();
        TArray<UPhysicalMaterial*> ComplexPhysMats = Instance->GetComplexPhysicalMaterials();

        PxMaterial* PSimpleMat = SimplePhysMat ? SimplePhysMat->GetPhysXMaterial() : nullptr;

        FShapeData ShapeData;
        Instance->GetFilterData_AssumesLocked(ShapeData);
        Instance->GetShapeFlags_AssumesLocked(ShapeData, ShapeData.CollisionEnabled, BodySetup->GetCollisionTraceFlag() == CTF_UseComplexAsSimple);

        if (!IsStatic() && PNewDynamic)
        {
            if (!Instance->ShouldInstanceSimulatingPhysics())
            {
                ModifyRigidBodyFlag<PxRigidBodyFlag::eKINEMATIC>(ShapeData.SyncBodyFlags, true);
            }
            ModifyRigidBodyFlag<PxRigidBodyFlag::eUSE_KINEMATIC_TARGET_FOR_SCENE_QUERIES>(ShapeData.SyncBodyFlags, bKinematicTargetForSQ);
        }

        bool bInitFail = false;

        const bool bShapeSharing = Instance->HasSharedShapes(); //If we have a static actor we can reuse the shapes between sync and async scene
        TArray<PxShape*> PSharedShapes;
        if (Instance->RigidActorSync)
        {
            BodySetup->AddShapesToRigidActor_AssumesLocked(Instance, Instance->RigidActorSync, PST_Sync, Instance->Scale3D, PSimpleMat, ComplexPhysMats, ShapeData, FTransform::Identity, bShapeSharing ? &PSharedShapes : nullptr, bShapeSharing);
            bInitFail |= Instance->RigidActorSync->getNbShapes() == 0;
            Instance->RigidActorSync->userData = &Instance->PhysxUserData;
            Instance->RigidActorSync->setName(Instance->CharDebugName.IsValid() ? Instance->CharDebugName->GetData() : nullptr);

            check(FPhysxUserData::Get<FBodyInstance>(Instance->RigidActorSync->userData) == Instance);

        }

        if (Instance->RigidActorAsync)
        {
            check(PAsyncScene);
            if (bShapeSharing)
            {
                for (PxShape* PShape : PSharedShapes)
                {
                    Instance->RigidActorAsync->attachShape(*PShape);
                }
            }
            else
            {
                BodySetup->AddShapesToRigidActor_AssumesLocked(Instance, Instance->RigidActorAsync, PST_Async, Instance->Scale3D, PSimpleMat, ComplexPhysMats, ShapeData);
            }

            bInitFail |= Instance->RigidActorAsync->getNbShapes() == 0;
            Instance->RigidActorAsync->userData = &Instance->PhysxUserData;
            Instance->RigidActorAsync->setName(Instance->CharDebugName.IsValid() ? Instance->CharDebugName->GetData() : nullptr);

            check(FPhysxUserData::Get<FBodyInstance>(Instance->RigidActorAsync->userData) == Instance);
        }

        return bInitFail;
    }

UBodyStep創(chuàng)建shapes

void UBodySetup::CreatePhysicsMeshes()
{
    SCOPE_CYCLE_COUNTER(STAT_CreatePhysicsMeshes);

#if WITH_PHYSX
    // Create meshes from cooked data if not already done
    if(bCreatedPhysicsMeshes)
    {
        return;
    }

    // If we don't have any convex/trimesh data we can skip this whole function
    if (bNeverNeedsCookedCollisionData)
    {
        return;
    }
    
    bool bClearMeshes = true;

    // Find or create cooked physics data
    static FName PhysicsFormatName(FPlatformProperties::GetPhysicsFormat());
    FByteBulkData* FormatData = GetCookedData(PhysicsFormatName);
    if (FormatData)
    {
        if (FormatData->IsLocked())
        {
            // seems it's being already processed
            return;
        }

        FPhysXCookingDataReader CookedDataReader(*FormatData, &UVInfo);

        if (GetCollisionTraceFlag() != CTF_UseComplexAsSimple)
        {
            bool bNeedsCooking = bGenerateNonMirroredCollision && CookedDataReader.ConvexMeshes.Num() != AggGeom.ConvexElems.Num();
            bNeedsCooking = bNeedsCooking || (bGenerateMirroredCollision && CookedDataReader.ConvexMeshesNegX.Num() != AggGeom.ConvexElems.Num());
            if (bNeedsCooking)  //Because of bugs it's possible to save with out of sync cooked data. In editor we want to fixup this data
            {
                InvalidatePhysicsData();
                CreatePhysicsMeshes();
                return;
            }
        }

        FinishCreatingPhysicsMeshes(CookedDataReader.ConvexMeshes, CookedDataReader.ConvexMeshesNegX, CookedDataReader.TriMeshes);
        bClearMeshes = false;
    }
    else
    {
        if (IsRuntime(this))
        {
            FPhysXCookHelper CookHelper(GetPhysXCookingModule());
                    
            GetCookInfo(CookHelper.CookInfo, GetRuntimeOnlyCookOptimizationFlags());
            if(CookHelper.HasSomethingToCook(CookHelper.CookInfo))
            {
                if (!IsRuntimeCookingEnabled())
                {
                    UE_LOG(LogPhysics, Error, TEXT("Attempting to build physics data for %s at runtime, but runtime cooking is disabled (see the RuntimePhysXCooking plugin)."), *GetPathName());
                }
                else
                {
                    CookHelper.CreatePhysicsMeshes_Concurrent();
                    FinishCreatingPhysicsMeshes(CookHelper.OutNonMirroredConvexMeshes, CookHelper.OutMirroredConvexMeshes, CookHelper.OutTriangleMeshes);
                    bClearMeshes = false;
                }
            }
        }
    }

    if(bClearMeshes)
    {
        ClearPhysicsMeshes();
    }
    
    bCreatedPhysicsMeshes = true;
#endif //WITH_PHYSX
}

FPhysScene

FPhysScene對應(yīng)PhysX的physx::PxScene, 一個UWorld實(shí)例擁有一個FPhysScene實(shí)例您炉。UWorld提供的LineTrace, Sweep, Overlap查詢的功能均由物理引擎提供, 在Engine\Source\Runtime\Engine\Private\Collision\WorldCollision.cpp中實(shí)現(xiàn)。
一個示例
bool GeomSweepSingle(const UWorld* World, const struct FCollisionShape& CollisionShape, const FQuat& Rot, FHitResult& OutHit, FVector Start, FVector End, ECollisionChannel TraceChannel, const struct FCollisionQueryParams& Params, const struct FCollisionResponseParams& ResponseParams, const struct FCollisionObjectQueryParams& ObjectParams)的實(shí)現(xiàn):

Paste_Image.png

物理世界的事件監(jiān)聽

/** Event callback used to notify engine about various collision events */
class ENGINE_API FPhysXSimEventCallback : public PxSimulationEventCallback
{
public:
    FPhysXSimEventCallback(FPhysScene* InOwningScene, int32 InSceneType) : OwningScene(InOwningScene), SceneType(InSceneType){}

    virtual void onConstraintBreak(PxConstraintInfo* constraints, PxU32 count) override;
    virtual void onWake(PxActor** actors, PxU32 count) override;
    virtual void onSleep(PxActor** actors, PxU32 count) override;
    virtual void onTrigger(PxTriggerPair* pairs, PxU32 count) override {}
    virtual void onContact(const PxContactPairHeader& PairHeader, const PxContactPair* Pairs, PxU32 NumPairs) override;
    virtual void onAdvance(const PxRigidBody*const* bodyBuffer, const PxTransform* poseBuffer, const PxU32 count) override {}

private:    
    FPhysScene* OwningScene;
    int32 SceneType;
};

PxFilterFlags PhysXSimFilterShader( PxFilterObjectAttributes attributes0, PxFilterData filterData0, PxFilterObjectAttributes attributes1, PxFilterData filterData1, PxPairFlags& pairFlags, const void* constantBlock, PxU32 constantBlockSize )用于在simulate中提供碰撞過濾功能役电。

備注:關(guān)于引擎碰撞通道的配置和代碼中的實(shí)現(xiàn)主要是通過上述的過濾回調(diào)實(shí)現(xiàn)的邻吭,過濾標(biāo)記放在PxFilterData數(shù)據(jù)中。

PxFilterData CreateObjectQueryFilterData(const bool bTraceComplex, const int32 MultiTrace/*=1 if multi. 0 otherwise*/, const struct FCollisionObjectQueryParams & ObjectParam)
{
    /**
     * Format for QueryData : 
     *      word0 (meta data - ECollisionQuery. Extendable)
     *
     *      For object queries
     *
     *      word1 (object type queries)
     *      word2 (unused)
     *      word3 (Multi (1) or single (0) (top 8) + Flags (lower 24))
     */

    PxFilterData PNewData;

    PNewData.word0 = ECollisionQuery::ObjectQuery;

    if (bTraceComplex)
    {
        PNewData.word3 |= EPDF_ComplexCollision;
    }
    else
    {
        PNewData.word3 |= EPDF_SimpleCollision;
    }

    // get object param bits
    PNewData.word1 = ObjectParam.GetQueryBitfield();

    // if 'nothing', then set no bits
    PNewData.word3 |= CreateChannelAndFilter((ECollisionChannel)MultiTrace, ObjectParam.IgnoreMask);

    return PNewData;
}

PxFilterData CreateTraceQueryFilterData(const uint8 MyChannel, const bool bTraceComplex, const FCollisionResponseContainer& InCollisionResponseContainer, const FCollisionQueryParams& Params)
{
    /**
     * Format for QueryData : 
     *      word0 (meta data - ECollisionQuery. Extendable)
     *
     *      For trace queries
     *
     *      word1 (blocking channels)
     *      word2 (touching channels)
     *      word3 (MyChannel (top 8) as ECollisionChannel + Flags (lower 24))
     */

    PxFilterData PNewData;

    PNewData.word0 = ECollisionQuery::TraceQuery;

    if (bTraceComplex)
    {
        PNewData.word3 |= EPDF_ComplexCollision;
    }
    else
    {
        PNewData.word3 |= EPDF_SimpleCollision;
    }

    // word1 encodes 'what i block', word2 encodes 'what i touch'
    for(int32 i=0; i<ARRAY_COUNT(InCollisionResponseContainer.EnumArray); i++)
    {
        if(InCollisionResponseContainer.EnumArray[i] == ECR_Block)
        {
            // if i block, set that in word1
            PNewData.word1 |= CRC_TO_BITFIELD(i);
        }
        else if(InCollisionResponseContainer.EnumArray[i] == ECR_Overlap)
        {
            // if i touch, set that in word2
            PNewData.word2 |= CRC_TO_BITFIELD(i);
        }
    }
    
    // if 'nothing', then set no bits
    PNewData.word3 |= CreateChannelAndFilter((ECollisionChannel)MyChannel, Params.IgnoreMask);

    return PNewData;
}

物理世界的初始化堆棧

Paste_Image.png

結(jié)尾

本文比較膚淺地闡述了物理模塊的集成宴霸,主要是了解一下其集成的方式囱晴。后面分析Movement代碼需要了解這塊知識。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末瓢谢,一起剝皮案震驚了整個濱河市畸写,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌氓扛,老刑警劉巖枯芬,帶你破解...
    沈念sama閱讀 206,311評論 6 481
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異采郎,居然都是意外死亡千所,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 88,339評論 2 382
  • 文/潘曉璐 我一進(jìn)店門蒜埋,熙熙樓的掌柜王于貴愁眉苦臉地迎上來淫痰,“玉大人,你說我怎么就攤上這事整份〈恚” “怎么了?”我有些...
    開封第一講書人閱讀 152,671評論 0 342
  • 文/不壞的土叔 我叫張陵烈评,是天一觀的道長火俄。 經(jīng)常有香客問我,道長讲冠,這世上最難降的妖魔是什么瓜客? 我笑而不...
    開封第一講書人閱讀 55,252評論 1 279
  • 正文 為了忘掉前任,我火速辦了婚禮竿开,結(jié)果婚禮上谱仪,老公的妹妹穿的比我還像新娘。我一直安慰自己德迹,他們只是感情好芽卿,可當(dāng)我...
    茶點(diǎn)故事閱讀 64,253評論 5 371
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著胳搞,像睡著了一般卸例。 火紅的嫁衣襯著肌膚如雪称杨。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 49,031評論 1 285
  • 那天筷转,我揣著相機(jī)與錄音姑原,去河邊找鬼。 笑死呜舒,一個胖子當(dāng)著我的面吹牛锭汛,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播袭蝗,決...
    沈念sama閱讀 38,340評論 3 399
  • 文/蒼蘭香墨 我猛地睜開眼唤殴,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了到腥?” 一聲冷哼從身側(cè)響起朵逝,我...
    開封第一講書人閱讀 36,973評論 0 259
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎乡范,沒想到半個月后配名,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 43,466評論 1 300
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡晋辆,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 35,937評論 2 323
  • 正文 我和宋清朗相戀三年渠脉,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片瓶佳。...
    茶點(diǎn)故事閱讀 38,039評論 1 333
  • 序言:一個原本活蹦亂跳的男人離奇死亡芋膘,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出涩哟,到底是詐尸還是另有隱情索赏,我是刑警寧澤,帶...
    沈念sama閱讀 33,701評論 4 323
  • 正文 年R本政府宣布贴彼,位于F島的核電站,受9級特大地震影響埃儿,放射性物質(zhì)發(fā)生泄漏器仗。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 39,254評論 3 307
  • 文/蒙蒙 一童番、第九天 我趴在偏房一處隱蔽的房頂上張望精钮。 院中可真熱鬧,春花似錦剃斧、人聲如沸轨香。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,259評論 0 19
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽臂容。三九已至科雳,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間脓杉,已是汗流浹背糟秘。 一陣腳步聲響...
    開封第一講書人閱讀 31,485評論 1 262
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留球散,地道東北人尿赚。 一個月前我還...
    沈念sama閱讀 45,497評論 2 354
  • 正文 我出身青樓,卻偏偏與公主長得像蕉堰,于是被迫代替她去往敵國和親凌净。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 42,786評論 2 345

推薦閱讀更多精彩內(nèi)容