Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 14 Next capture
2021 2022 2023
2 captures
13 Jun 22 - 14 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
1
Question by ThomasAqtl · May 12 at 09:07 AM · vertexgpuinstancing

How to use GPU instancing

Hi everyone,

In the doc, at the end of GPU Instancing page, it is mentionned that :

If you want to render a mesh with a low number of vertices many times, best practice is to create a single buffer that contains all the mesh information and use that to draw the meshes.

I do not understand what this means. I am currently in this situation with my team (we need to render multiple same meshed that has only few vertex). What is the best approach ? If anyone could detail what the above sentence specifically means, that would be awesome!

Regards

Comment
Add comment
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

1 Reply

· Add your reply
  • Sort: 
avatar image
0

Answer by andrew-lukasik · May 12 at 06:31 PM

  • Step 1:

Enable GPU Instancing in your material

link text


  • Step 2:

This component will let you render many MeshRenderers as a single draw call:

GPU Instancing example


GPU Instancing frustum culling example


 // web* scr: https://gist.github.com/andrew-raphael-lukasik/df4a36ff2ad89078258fd653c422a021
 using System.Collections.Generic;
 using UnityEngine;
 
 public class GpuInstancingForGameObjects : MonoBehaviour
 {
     [SerializeField] Camera _camera = null;
     [SerializeField] MeshRenderer[] _meshRenderers = new MeshRenderer[0];
     
     /// <summary>
     /// Prefer "true" as "false" require updates every frame.
     /// It is a good idea to keep lists of still and moving mesh renderers in a separate components.
     /// </summary>
     public bool meshesAreStill = true;
 
     Dictionary<(Mesh mesh,Material material),(List<Transform> transforms,Bounds aabb)> _sources = new Dictionary<(Mesh,Material),(List<Transform>,Bounds)>();
     Dictionary<(Mesh mesh,Material material),(Matrix4x4[] matrices,Bounds aabb)> _batches = new Dictionary<(Mesh,Material),(Matrix4x4[],Bounds)>();
     Dictionary<int,Stack<Matrix4x4[]>> _freeMatrices = new Dictionary<int,Stack<Matrix4x4[]>>();
     Plane[] _frustum = new Plane[6];
     
     void Start ()
     {
         Initialize();
         UpdateMatrices();
 
         if( _camera==null ) _camera = Camera.main;
         if( _camera==null )
         {
             Debug.LogError( "no camera, can't continue" , this );
             enabled = false;
         }
     }
 
     void Update ()
     {
         if( !meshesAreStill ) UpdateMatrices();
 
         GeometryUtility.CalculateFrustumPlanes( _camera , _frustum );
         foreach( var batch in _batches )
         {
             var meshMaterialPair = batch.Key;
             var matricesAabbPair = batch.Value;
             var aabb = matricesAabbPair.aabb;
             if( GeometryUtility.TestPlanesAABB(_frustum,aabb) )
             {
                 Graphics.DrawMeshInstanced(
                     mesh:            meshMaterialPair.mesh ,
                     submeshIndex:    0 ,
                     material:        meshMaterialPair.material ,
                     matrices:        matricesAabbPair.matrices
                 );
             }
         }
     }
 
     #if UNITY_EDITOR
     // void OnDrawGizmosSelected ()
     void OnDrawGizmos ()
     {
         Initialize();
 
         Gizmos.color = Color.yellow;
         foreach( var source in _sources )
         {
             var transformsAabbPair = source.Value;
             var aabb = transformsAabbPair.aabb;
             Gizmos.DrawWireCube( aabb.center , aabb.size );
             
             if( Application.isPlaying && !GeometryUtility.TestPlanesAABB(_frustum,aabb) )
                 UnityEditor.Handles.Label( aabb.center , "(out of camera view)" );
         }
     }
     #endif
 
     void Initialize ()
     {
         _sources.Clear();
         foreach( var meshRenderer in _meshRenderers )
         {
             if( meshRenderer==null ) continue;
             var meshFilter = meshRenderer.GetComponent<MeshFilter>();
             if( meshFilter==null ) continue;
             var mesh = meshFilter.sharedMesh;
             if( mesh==null ) continue;
             foreach( var material in meshRenderer.sharedMaterials )
             {
                 if( !material.enableInstancing && Application.isPlaying )
                 {
                     Debug.LogWarning($"\"{material.name}\" material won't be rendered as it's <b>GPU Instancing</b> is not enabled",meshRenderer);
                     continue;
                 }
                 if( material==null ) continue;
                 var aabb = meshRenderer.bounds;
                 var meshMaterialPair = ( mesh , material );
                 if( _sources.ContainsKey( meshMaterialPair ) )
                 {
                     var transforms = _sources[meshMaterialPair].transforms;
                     transforms.Add( meshRenderer.transform );
 
                     var newAabb = _sources[meshMaterialPair].aabb;
                     newAabb.Encapsulate( aabb );
 
                     _sources[meshMaterialPair] = ( transforms , newAabb );
                 }
                 else
                 {
                     _sources.Add( meshMaterialPair , ( new List<Transform>(){ meshRenderer.transform } , aabb ) );
                 }
             }
             if( Application.isPlaying )
                 meshRenderer.enabled = false;
         }
     }
 
     void UpdateMatrices ()
     {
         foreach( var batch in _batches )
         {
             var matricesAabbPair = batch.Value;
             var matrices = matricesAabbPair.matrices;
             if( _freeMatrices.ContainsKey( matrices.Length ) )
             {
                 _freeMatrices[matrices.Length].Push( matrices );
             }
             else
             {
                 var stack = new Stack<Matrix4x4[]>();
                 stack.Push( matrices );
                 _freeMatrices.Add( matrices.Length , stack );
             }
         }
         _batches.Clear();
 
         foreach( var source in _sources )
         {
             var meshMaterialPair = source.Key;
             var transformsAabbPair = source.Value;
             var transforms = transformsAabbPair.transforms;
             
             int numTransforms = transforms.Count;
             Matrix4x4[] matrices = null;
             if( _freeMatrices.ContainsKey(numTransforms) && _freeMatrices[numTransforms].Count!=0 )
             {
                 matrices = _freeMatrices[numTransforms].Pop();
             }
             else matrices = new Matrix4x4[ numTransforms ];
 
             for( int i=0 ; i<numTransforms ; i++ )
                 matrices[i] = transforms[i].localToWorldMatrix;
             _batches.Add( meshMaterialPair , ( matrices , transformsAabbPair.aabb ) );
         }
     }
 
 }


Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

137 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Multiple calls to Graphics.DrawMeshInstancedIndirect - only draws last call 1 Answer

Shader and material for GPU instancing particles? 2 Answers

How can I create GPU Instanced meshes using Texture2DArrays with different texture indices in the SRP? 0 Answers

CalculateInterpolatedLightAndOcclusionProbes retrieves occlusionProbes as (1,1,1,1) 0 Answers

How to use Point and Spot Lights With Mesh instancing? 0 Answers


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges