"Manual" occlusion culling for dynamically generated scenes.

I am generating random scenes with many cube objects (50,000+) and need some kind of culling system to speed rendering. Occlusion culling in Unity Pro does not seem to be an option because the objects do not exist before the scene is loaded.

If anyone has any advice it would be appreciated.

Below is an example of my current line of thought in trying to do this manually (de-render cubes which are hidden from view).

private void initBlock()
	{
		renderer.enabled=true;
		_blockInit = true;

		Ray rayUp = new Ray(transform.position,transform.up);
		Ray rayDown = new Ray(transform.position,-transform.up);
		
		Ray rayLeft = new Ray(transform.position,-transform.right);
		Ray rayRight = new Ray(transform.position,transform.right);
		
		Ray rayForward = new Ray(transform.position,transform.forward);
		Ray rayBack = new Ray(transform.position,-transform.forward);

		
		if (Physics.Raycast(rayUp, 2f)) 
		{
			if (Physics.Raycast(rayDown, 2f)) 
			{
				if (Physics.Raycast(rayLeft, 2f)) 
				{								
					if (Physics.Raycast(rayRight, 2f)) 
					{											
						if (Physics.Raycast(rayForward, 2f)) 
						{														
							if (Physics.Raycast(rayBack, 2f)) 
							{
								renderer.enabled=false;
							}
						}
					}
				}
			}
		}

	}

Hmm. Or maybe you need another approach entirely. If these cubes are often touching, like a Minecraft (or Blockhaven) terrain, then you shouldn’t be using actual cube objects at all; you should be generating meshes dynamically based on your own data structures representing the terrain.

Wait, what? Unity doesn’t occlude dynamically created objects? I’d like to learn more about that — can you point me to a reference?

Thanks,

  • Joe

If you have any code or project examples/tutorial links for this method you could recommend please let me know. It sounds interesting. I guess i would need several arrays to store this data.

From what i read here: http://docs.unity3d.com/Documentation/Manual/OcclusionCulling.html it seems to need a baking process in preparation. If the objects are instantiated into the scene after run-time how does it bake? There seems to be no way to start a bake in c# from what i can tell.

Yes. I wish I could share my code, but it’s not as neatly separated from the rest of the game as it would need to be.

However, if you want to take a crack at doing it yourself, you would just need to look up procedural mesh generation. Here’s a good blog post and some docs on the subject.

The key bit for this application is, as you iterate through your arrays, you only generate a mesh face when you have a block next to empty air. If it’s a block next to another block, then you don’t bother generating that face, because nobody can see it anyway.

Well I’ll be. You’ve taught me something today — thank you very much!

Cheers,

  • Joe