[UE4C++] BitMask 使用介绍

BitMask是使用bit来表达True或false的概念,它可以使用一个int来表达多组的功能是否启用。

先让我们来看下图:

 

若我们想要依照PlayerLevel跟Speed来进行排序的话,一般不知道这个技巧的人可能会使用二个int来处理这件事。在使用了BitMask之后我们就可以藉由将第一跟第三个bit设为1来表达这件事。在一般的C++中我们常常在enum的设定中就直接将该bit位移,如下面的code:

enum  class  EHorizo​​nPlayerSortType 
{
  Invalidated = ( 1 << 0 ),
  Leve = ( 1 << 1 ),
  Power = ( 1 << 2 ),
  Speed = ( 1 << 3 ),
  PlaceHolder1 = ( 1 << 4 ),
  PlaceHolder2 = ( 1 << 5 ),
  PlaceHolder3 = ( 1 << 6 ),
  PlaceHolder4 = ( 1 << 7 ),
};

void  Usage (){
  int flag = EHorizo​​nPlayerSortType::Level | EHorizo​​nPlayerSortType::Speed;
}

但在UE4中的Bitmask没办法使用跟上面一样的做法,由于enum class被限制成只能使用uint8,因此在UE4中是直接将enum中的值当成位移数,如下面的code:

UENUM (BlueprintType, meta = (Bitflags))
enum class EHorizo​​nPlayerSortType : uint8
{
  Invalidated = 0 ,
  Level					 UMETA (DisplayName = " PlayerLevel " ),
  Power					 UMETA (DisplayName = " Power " ),
  Speed					 UMETA (DisplayName = " Speed " ),
  PlaceHolder1 			 UMETA (DisplayName = " PlaceHolder1 " ),
  PlaceHolder2			 UMETA (DisplayName = " PlaceHolder2 " ),
  PlaceHolder3			 UMETA (DisplayName = " PlaceHolder3 " ),
  PlaceHolder4			 UMETA (DisplayName = " PlaceHolder4 " ),
};

ENUM_CLASS_FLAGS (EHorizo​​nPlayerSortType)


USTRUCT(BlueprintType)
struct HORIZONTWEEN_API FHorizo​​nPlayerParameters
{
  GENERATED_BODY ()
    FHorizo​​nPlayerParameters ()
    : PlayerSortTypeFlags (( int )EHorizo​​nPlayerSortType::Level)
  {
  }
public:

  UPROPERTY (EditAnywhere, BlueprintReadWrite, meta = (Bitmask, BitmaskEnum = " EHorizo​​nPlayerSortType " ))
    int PlayerSortTypeFlags;
};



bool  HasFlag ( const INT32& Flags, EHorizo​​nPlayerSortType TestFlag)
 {
     INT32 bitFlag = static_cast <int32>( 1 << (INT32)TestFlag); // shift to the bit corresponding to the enum value
     return (Flags & bitFlag ) != 0 ;
 }
 
void  Usage ( const FHorizo​​nPlayerParameters& param){
 	INT32 bitFlag = static_cast <int32>(( 1 << (INT32)EHorizo​​nPlayerSortType::Level) |
             ( 1 << (INT32)EHorizo​​nPlayerSortType::Speed));   // 10
  bool b1 = HasFlag (param. PlayerSortTypeFlags , EHorizo​​nPlayerSortType::Level);   // true
  bool b2 = HasFlag (param. PlayerSortTypeFlags , EHorizo​​nPlayerSortType::Power); // false
  bool b3 = HasFlag (param. PlayerSortTypeFlags , EHorizo​​nPlayerSortType::Speed); // true
}

 

其中

INT32 bitFlag = static_cast<int32>((1 << (INT32)EHorizo​​nPlayerSortType::Level) |
(1 << (INT32)EHorizo​​nPlayerSortType::Speed));

就是模拟Blueprint中选择要启用哪个enum的C++实作。

 

Author: 90cg