hkpShape* vHavokShapeFactory::CreateConvexShapeFromStaticMeshInstances(const VisStaticMeshInstCollection &meshInstances, hkvMat4 &refTransform, bool shrinkByCvxRadius)
{
  VVERIFY_OR_RET_VAL(meshInstances.GetLength()==1, NULL);

  // Get the collision mesh for the static mesh instance
  VisStaticMeshInstance_cl *pMeshInstance = meshInstances[0];
  VisStaticMesh_cl *pMesh = pMeshInstance->GetMesh();
  IVCollisionMesh *pColMesh = pMesh->GetCollisionMesh(true, true);
  VVERIFY_OR_RET_VAL(pColMesh!=NULL, NULL);

  // We transform each static mesh into the reference space.
  hkvMat4 mTransform = refTransform;
  mTransform = mTransform.multiply (pMeshInstance->GetTransform());

  hkGeometry geom;
  int iNumColMeshes = hkvMath::Max(pColMesh->GetSubmeshCount(), 1);
  for (int i=0;i<iNumColMeshes;i++)
    BuildGeomFromCollisionMesh(pColMesh, i, mTransform, false, geom);
 
  // Set the build configuration to set planes equations and connectivity automatically
  hkpConvexVerticesShape::BuildConfig config;
  config.m_createConnectivity = true;
  config.m_shrinkByConvexRadius = shrinkByCvxRadius;

  hkStridedVertices stridedVerts;
  stridedVerts.m_numVertices = geom.m_vertices.getSize();
  stridedVerts.m_striding    = sizeof(hkVector4);
  stridedVerts.m_vertices    = (const hkReal*)geom.m_vertices.begin();

  // Create convex shape
  hkvConvexVerticesShape *pConvexShape = new hkvConvexVerticesShape(pColMesh->GetFileTime(), stridedVerts, config);
  
  return pConvexShape;
}
Exemple #2
0
bool MeshLoader::Load(const VSceneListEntry& entry)
{
  Helper::SetupScene(entry);

  // load vmesh
  VisStaticMesh_cl* pRes = VisStaticMesh_cl::GetResourceManager().LoadStaticMeshFile(entry.sScenePath);
  if (pRes == NULL) 
    return false;
  
  // force loading of .colmesh file if it exists
  if (pRes->GetCollisionMesh(true)) 
    hkvLog::Info("Loaded collision mesh");
  else
    hkvLog::Info("No collision mesh loaded");

  // get a instance
  hkvMat4 mTransform;
  VisStaticMeshInstance_cl *pInst = pRes->CreateInstance(mTransform);

  // create the visibility zone
  const hkvAlignedBBox& bbox = pInst->GetBoundingBox();
  int iZones = Vision::GetSceneManager()->GetNumVisibilityZones();
  VisVisibilityZone_cl* pVisZone;
  if (iZones > 0)
  {
    pVisZone = Vision::GetSceneManager()->GetVisibilityZone(0);
  } 
  else
  {
    pVisZone = new VisVisibilityZone_cl(bbox);
    Vision::GetSceneManager()->AddVisibilityZone(pVisZone);
  }

  // add submeshes to vis zone
  for (int i = 0; i < pInst->GetSubmeshInstanceCount(); ++i)
  {
    pVisZone->AddStaticGeometryInstance(pInst->GetSubmeshInstance(i));
  }

  Helper::LookAtBox(bbox);
  return true;
}
bool VLightClippingVolumeRenderer::RenderLightClippingVolumeHelper(VisLightSource_cl *pLight,VStateGroupDepthStencil& sg)
{
  VLightClippingVolumeComponent* pComponent = pLight->Components().GetComponentOfBaseType<VLightClippingVolumeComponent>();
  if(pComponent != NULL && pComponent->GetVolume() != NULL && m_spLightClippingVolumeStencilFill)
  {
    INSERT_PERF_MARKER_SCOPE("VLightClippingVolumeRenderer::RenderLightClippingVolume");

    VisRenderStates_cl::SetDepthStencilState(sg);

    VCustomVolumeObject* pVolume = pComponent->GetVolume();

    VisStaticMesh_cl* pStaticMesh = pVolume->GetStaticMesh();
    if(!pStaticMesh)
      return false;

    VisMeshBuffer_cl* pMeshBuffer = pStaticMesh->GetMeshBuffer();
    if(!pMeshBuffer || pMeshBuffer->GetIndexCount() <= 0)
      return false;

    Vision::RenderLoopHelper.BeginMeshRendering();
    Vision::RenderLoopHelper.ResetMeshStreams();
    Vision::RenderLoopHelper.AddMeshStreams(pMeshBuffer, m_spLightClippingVolumeStencilFill->GetShader(0)->GetStreamMask() | VERTEX_STREAM_INDEXBUFFER);

    hkvMat4 transform;
    transform.setIdentity ();
    transform.setRotationalPart(pVolume->GetRotationMatrix());
    transform.setTranslation(pVolume->GetPosition());
    transform.setScalingFactors(pVolume->GetScale());

    Vision::RenderLoopHelper.SetMeshTransformationMatrix(transform);

    Vision::RenderLoopHelper.RenderMeshes(m_spLightClippingVolumeStencilFill->GetShader(0), pMeshBuffer->GetPrimitiveType(), 0, pMeshBuffer->GetIndexCount() / 3, pMeshBuffer->GetVertexCount());
    Vision::RenderLoopHelper.EndMeshRendering();

    return true;
  }
  return false;
}
void vHavokTriggerVolume::CommonInit()
{
  // Do not initialize the component in case our module is not active
  if (!m_pModule)
  {
    hkvLog::Warning("Failed to initialize vHavokTriggerVolume since a non Havok physics module is currently active");
    return;
  }

  // Get owner custom volume object
  VCustomVolumeObject *pCustomVolume = GetOwnerCustomVolume();
  VVERIFY_OR_RET(pCustomVolume != NULL); 

  // Get the static mesh from the custom volume object
  VisStaticMesh_cl *pMesh = pCustomVolume->GetStaticMesh();
  if (pMesh == NULL)
    return;
  pMesh->EnsureLoaded();

  if ((!pMesh->IsLoaded()) || (pMesh->GetNumOfTriangles() < 1))
    return;
 
  // Get scaling vector from custom volume object
  const hkvVec3 vScale = pCustomVolume->GetScale();

  // Check whether the static mesh has valid size
  const hkvAlignedBBox& bbox = pMesh->GetBoundingBox();
  hkVector4 bbox_min; vHavokConversionUtils::VisVecToPhysVec_noscale(bbox.m_vMin, bbox_min);
  hkVector4 bbox_max; vHavokConversionUtils::VisVecToPhysVec_noscale(bbox.m_vMax, bbox_max);
  hkVector4 bbox_scale; vHavokConversionUtils::VisVecToPhysVec_noscale(vScale, bbox_scale);

  bbox_scale.mul(vHavokConversionUtils::GetVision2HavokScaleSIMD());

  hkVector4 bbox_extent; bbox_extent.setSub(bbox_max,bbox_min); bbox_extent.mul(bbox_scale);

  hkVector4 meshTol; meshTol.setAll(hkReal((Havok_ShapeType==VHavokTriggerVolumeShapeType_CONVEX) ? HKVIS_CONVEX_SHAPE_TOLERANCE : HKVIS_MESH_SHAPE_TOLERANCE));
  hkVector4Comparison notLargeEnough = bbox_extent.less(meshTol);
  if (notLargeEnough.anyIsSet<hkVector4ComparisonMask::MASK_XYZ>())
  {
    const char *szMeshFilename = (pMesh->GetFilename()!=NULL) ? pMesh->GetFilename() : "Unnamed";
    hkvLog::Warning("Initializing vHavokTriggerVolume with a static mesh [%s] with undersized extents (%.4f, %4f, %.4f)", 
      szMeshFilename, bbox_extent(0), bbox_extent(1), bbox_extent(2));
    return;
  }

  // Create shape, thereby the shape is not cached to file. It would not be a good idea, to cache the shape every time, when the user has modified 
  // the custom volume or has switched the custom static mesh. Instead the final shape will be cached at serialization. Only try using a collision 
  // mesh for creation if custom static mesh is used, since otherwise the static mesh is not physically present on disk.
  int iCreationFlags = (!Vision::Editor.IsInEditor()) ? vHavokShapeFactory::VShapeCreationFlags_CACHE_SHAPE : 0;
  iCreationFlags |= pCustomVolume->GetCustomStaticMesh() ? vHavokShapeFactory::VShapeCreationFlags_USE_VCOLMESH : 0;
  
  // Create Havok trigger volume 
  bool bResult = CreateHkTriggerVolume(pMesh, vScale, iCreationFlags);
  VASSERT_MSG(bResult, "Failed to create Havok Trigger Volume");

  // Set debug visibility 
  SetDebugRendering(Debug_Render);

  // Note, that the trigger components are only created here inside vForge. Serialization reads these components from the archive.
  if (!m_spOnObjectEnter)
  {
    m_spOnObjectEnter = new VisTriggerSourceComponent_cl(VHAVOKTRIGGERVOLUME_ONOBJECTENTER, VIS_OBJECTCOMPONENTFLAG_NONE);
    AddComponent(m_spOnObjectEnter);
  }
  if (!m_spOnObjectLeave)
  {
    m_spOnObjectLeave = new VisTriggerSourceComponent_cl(VHAVOKTRIGGERVOLUME_ONOBJECTLEAVE, VIS_OBJECTCOMPONENTFLAG_NONE);
    AddComponent(m_spOnObjectLeave);
  }
  if (!m_spOnCharacterEnter)
  {
    m_spOnCharacterEnter = new VisTriggerSourceComponent_cl(VHAVOKTRIGGERVOLUME_ONCHARACTERENTER, VIS_OBJECTCOMPONENTFLAG_NONE);
    AddComponent(m_spOnCharacterEnter);
  }
  if (!m_spOnCharacterLeave)
  {
    m_spOnCharacterLeave = new VisTriggerSourceComponent_cl(VHAVOKTRIGGERVOLUME_ONCHARACTERLEAVE, VIS_OBJECTCOMPONENTFLAG_NONE);
    AddComponent(m_spOnCharacterLeave);
  }
}
hkpShape* vHavokShapeFactory::CreateMeshShapeFromStaticMeshInstances(const VisStaticMeshInstCollection &meshInstances, hkvMat4 &refTransform, 
                                                                     bool bAllowPerTriCollisionInfo, VisWeldingType_e eWeldingType)
{
  int iCount = meshInstances.GetLength();
  VVERIFY_OR_RET_VAL(iCount>0, NULL);

  hkGeometry geom;
  hkInt64 iFileTime = 0;

  // Iterate all the passed mesh instances
  hkvMeshMaterialCache materials;
  hkArray<hkUint8> collisionMask;
  int subPartIndex = 0;
  for (int i = 0; i < iCount; i++)
  { 
    // Get the collision mesh for the static mesh instance
    const VisStaticMeshInstance_cl *pMeshInstance = meshInstances[i];
    VisStaticMesh_cl *pMesh = pMeshInstance->GetMesh();
    IVCollisionMesh *pColMesh = pMesh->GetCollisionMesh(true, true);
    if (pColMesh == NULL)
    {
      VASSERT(false);
      continue;
    }

    // Simply retrieve file time from last static mesh instance
    iFileTime = pColMesh->GetFileTime();

    // Create the Havok triangle sub part
    {
      int startingNumTris = geom.m_triangles.getSize();

      // We transform each static mesh into the reference space.
      hkvMat4 mTransform = refTransform;
      mTransform = mTransform.multiply (pMeshInstance->GetTransform());

      int iNumColMeshes = hkvMath::Max(pColMesh->GetSubmeshCount(), 1);
      for (int i=0;i<iNumColMeshes;i++)
      {
        int startingNumVerts = geom.m_vertices.getSize();
        BuildGeomFromCollisionMesh(pColMesh, i, mTransform, false, geom);
        int endNumVerts = geom.m_vertices.getSize();
        int endNumTris = geom.m_triangles.getSize();
        VASSERT( (endNumVerts - startingNumVerts) > 0 );

        hkUint32 cdMask = 0;
        if (bAllowPerTriCollisionInfo && (pColMesh->GetSubmeshCount() > 0))
        {
          const VPhysicsSubmesh& submesh = pColMesh->GetSubmeshes()[i];
          cdMask = submesh.iGroupFilter & 0xff; // only lower 8 bits stored in compressed mesh.

          int numCD = endNumTris - collisionMask.getSize();
          hkUint8* cdi = collisionMask.expandBy( numCD );
          hkString::memSet(cdi, cdMask, numCD);
        }
      }
   
      // ColMesh can have Materials. Also need material to store the orig static mesh index (so if count > 1)
      if ( pColMesh->GetTriSrfIndices() )
      {
        VColMeshMaterial *pColMaterials = pColMesh->GetMaterials();
        VASSERT(pColMaterials);
        int iNumMats = pColMesh->GetMaterialCount();
        int matIndexOffset = materials.getSize();

        for(int ii=0;ii<iNumMats;ii++)
        {
          hkvMeshMaterial& mat = materials.expandOne();
          // in Havok there is no StaticFriction, DynamicFriction, anisotropic StaticFriction/ DynamicFriction
          // instead there is only Friction available
          // so DynamicFriction is used for Havok Friction -> is there a better workaround?
          mat.m_fFriction = pColMaterials[ii].fDynamicFriction; 

          mat.m_fRestitution = pColMaterials[ii].fRestitution;
          if (! pColMaterials[ii].szUserData.IsEmpty()) 
            mat.m_userData = pColMaterials[ii].szUserData.GetChar();   

          mat.m_iOrignalSubMeshIndex = subPartIndex;
        }

        // reindex geom mat id
        if (matIndexOffset> 0)
        {
          for (int ti=startingNumTris; ti < geom.m_triangles.getSize(); ++ti)
          {
            VASSERT(geom.m_triangles[ti].m_material < iNumMats);
            VASSERT(geom.m_triangles[ti].m_material >= 0);
            geom.m_triangles[ti].m_material += matIndexOffset;
          }
        }
      }

      // per instance part
      ++subPartIndex;     
    }
  }

  const bool bHaveTriCDData = collisionMask.getSize() > 0;
  vHavokCompressedInfoCinfo ci( &geom, bHaveTriCDData ? collisionMask.begin() : HK_NULL );
  ci.m_weldingType = vHavokConversionUtils::VisToHkWeldingType(eWeldingType);
  ci.m_collisionFilterInfoMode = bHaveTriCDData ? hkpBvCompressedMeshShape::PER_PRIMITIVE_DATA_8_BIT : hkpBvCompressedMeshShape::PER_PRIMITIVE_DATA_NONE;
  
  hkvBvCompressedMeshShape *pCompressedMeshShape = HK_NULL;
  if ( materials.getSize() > 0 && materials.getSize() < 255)
  {
    ci.m_userDataMode = hkpBvCompressedMeshShape::PER_PRIMITIVE_DATA_8_BIT; 
    pCompressedMeshShape = new hkvBvCompressedMeshShape(ci, materials, iFileTime);
  }
  else
  {
    ci.m_userDataMode = hkpBvCompressedMeshShape::PER_PRIMITIVE_DATA_NONE; 
    pCompressedMeshShape = new hkvBvCompressedMeshShape(ci, iFileTime);
  }
  VASSERT_MSG(pCompressedMeshShape->getNumChildShapes() > 0, "hkvBvCompressedMeshShape could not be created for static model!");

  pCompressedMeshShape->SetupMaterials();

  return pCompressedMeshShape;
}
hkRefNew<hkpShape> vHavokShapeFactory::CreateShapeFromStaticMeshInstances(const VisStaticMeshInstCollection &meshInstances, int iCreationFlags, const char **szShapeCacheId)
{
  int iCount = meshInstances.GetLength();
  VVERIFY_OR_RET_VAL(iCount>0 && szShapeCacheId!=NULL, NULL);
  
  // Actual mesh scale, which is only used for caching.
  hkvVec3 vScale(hkvNoInitialization);
  ExtractScaling(meshInstances[0]->GetTransform(), vScale);

  char szShapeId[512];
  const bool bAllowStaticMeshCaching = vHavokPhysicsModule_GetDefaultWorldRuntimeSettings().m_bEnableShapeCaching==TRUE;
  const vHavokPhysicsModule *pModule = vHavokPhysicsModule::GetInstance();
  VASSERT(pModule != NULL);
  const bool bForceHktShapeCaching = pModule->IsHktShapeCachingEnforced();

  // For single mesh instances the per instance welding type is used. For merged mesh instances the global merged welding type is used. 
  VisWeldingType_e eWeldingType = (iCount==1) ? meshInstances[0]->GetWeldingType() : (VisWeldingType_e)vHavokPhysicsModule_GetWorldSetupSettings().m_iMergedStaticWeldingType;

  const bool bAllowPerTriCollisionInfo = iCreationFlags & VShapeCreationFlags_ALLOW_PERTRICOLINFO;
  const bool bShrinkByCvxRadius = iCreationFlags & VShapeCreationFlags_SHRINK;

  // Check whether shape has been already cached for this mesh with the respective scaling.
  // We are just caching single static mesh instances and no static mesh collections.
  hkpShape *pCachedShape = HK_NULL; 
  if (iCount == 1)
  {
    // first, find the convex version
    GetIDStringForConvexShape(szShapeId, meshInstances[0]->GetMesh()->GetFilename(), vScale, bShrinkByCvxRadius);
    pCachedShape = FindShape(szShapeId, szShapeCacheId);
    if (!pCachedShape)
    {
      // then find the mesh version
      GetIDStringForMeshShape(szShapeId, meshInstances[0]->GetMesh()->GetFilename(), vScale, meshInstances[0]->GetCollisionBehavior(), eWeldingType);
      pCachedShape = FindShape(szShapeId, szShapeCacheId);
    }
    if (pCachedShape)
    {
      pCachedShape->addReference();
      return pCachedShape; 
    }

    if (bAllowStaticMeshCaching)
    {
      // first, find the convex version
      pCachedShape = vHavokCachedShape::LoadConvexShape(meshInstances[0]->GetMesh(), vScale, bShrinkByCvxRadius);
      if (pCachedShape)
      {
        *szShapeCacheId = AddShape(szShapeId, pCachedShape);
#ifdef HK_DEBUG_SLOW
        const hkClass* loadedClassType = hkVtableClassRegistry::getInstance().getClassFromVirtualInstance(pCachedShape);
        HK_ASSERT2(0x5432c902, loadedClassType && (hkString::strCmp( loadedClassType->getName(), "hkvConvexVerticesShape" ) == 0), "Serialized in a unexpected cached Havok shape type!");
#endif
        return pCachedShape; 
      }
      else
      {
        // then find the mesh version
        pCachedShape = vHavokCachedShape::LoadMeshShape(meshInstances[0]->GetMesh(), vScale, meshInstances[0]->GetCollisionBehavior(), eWeldingType);
      }
      if (pCachedShape )
      {
        *szShapeCacheId = AddShape(szShapeId, pCachedShape);
#ifdef HK_DEBUG_SLOW
        const hkClass* loadedClassType = hkVtableClassRegistry::getInstance().getClassFromVirtualInstance(pCachedShape);
        HK_ASSERT2(0x5432c902, loadedClassType && (hkString::strCmp( loadedClassType->getName(), "hkvBvCompressedMeshShape" ) == 0), "Serialized in a unexpected cached Havok shape type!");
#endif
        hkvBvCompressedMeshShape *pCompressedMeshShape = reinterpret_cast<hkvBvCompressedMeshShape*>(pCachedShape);
        pCompressedMeshShape->SetupMaterials();
        return pCachedShape; 
      }
      else if(!Vision::Editor.IsInEditor() && !bForceHktShapeCaching)
      {
        Vision::Error.Warning("Cached HKT file for %s is missing. Please generate HKT file (see documentation for details).", meshInstances[0]->GetMesh()->GetFilename());
      }
    }
  }

  // Get the reference transformation. We use the first static mesh as reference
  // transformation, and thus as the position of the corresponding rigid body.
  hkvMat4 referenceTransform = meshInstances[0]->GetTransform();

  // Remove any scaling from the reference matrix. This one has to be applied to
  // the Havok shapes, and thus needs to be part of the mesh transforms.
  referenceTransform.setScalingFactors(hkvVec3 (1));

  // We need the inverse referenceTransform to transform each instance into reference space
  referenceTransform.invert();
  referenceTransform.setRow (3, hkvVec4 (0, 0, 0, 1));

  // Determine collision type from first static mesh instance.
  const VisStaticMeshInstance_cl *pMeshInstance = meshInstances[0];
  VisStaticMesh_cl *pMesh = pMeshInstance->GetMesh();
  IVCollisionMesh *pColMesh = pMesh->GetCollisionMesh(true, true);
  const bool bIsConvex = pColMesh->GetType()==VIS_COLMESH_GEOTYPE_CONVEXHULL;

  // Only create a convex shape if a single mesh instance is used, since otherwise merging multiple mesh instances in one single convex hull
  // will provide in most cases not the desired behavior. Moreover we can only create either a convex hull or a concave mesh shape, therefore
  // mesh instances with different collision type can't be merged into one shape.
  hkpShape *pShape = (bIsConvex && iCount==1) ?
    CreateConvexShapeFromStaticMeshInstances(meshInstances, referenceTransform, bShrinkByCvxRadius) : 
    CreateMeshShapeFromStaticMeshInstances(meshInstances, referenceTransform, bAllowPerTriCollisionInfo, eWeldingType);

  // We are just caching single static mesh instances and no static mesh collections.
  if (iCount == 1)
  {
     *szShapeCacheId = AddShape(szShapeId, pShape);

    // Only cache shape to HKT file when inside vForge or when enforced.
    if ((Vision::Editor.IsInEditor() && bAllowStaticMeshCaching) || bForceHktShapeCaching)
    {
      if (bIsConvex)
        vHavokCachedShape::SaveConvexShape(meshInstances[0]->GetMesh(), vScale, bShrinkByCvxRadius, (hkvConvexVerticesShape*)pShape);
      else
        vHavokCachedShape::SaveMeshShape(meshInstances[0]->GetMesh(), vScale, meshInstances[0]->GetCollisionBehavior(), eWeldingType, (hkvBvCompressedMeshShape*)pShape);
    }
  }
  return pShape;
}