In Voxel Play you can disable or enable events using the env.captureEvents property. Disabling events is useful to avoid recursion if you call an API inside an event handler. Always remember to reenable events by setting back captureEvents to true before the event handler ends execution.


The following methods are available:


Chunk methods


public VoxelTerrainChunk GetCurrentChunk ()
Returns the voxel chunk where the player is located


public Vector3 GetChunkPosition (Vector3 position)

Returns the chunk position that encloses a given world space position


public bool GetChunk (Vector3 position, out VoxelChunk chunk, bool forceCreation = false)
Returns the voxel chunk at a given position


public bool ChunkIsInFrustum (VoxelChunk chunk)
Returns true if the chunk is within camera's frustum.


public VoxelTerrainChunk GetChunkUnpopulated (Vector3 position)
Returns the chunk on a given position before it's been populated by the terrain engine. Can be used to fill the chunk with "holes" setting voxel.hasContent = 2. The default terrain generator won't place any voxel on holes.


public void GetChunks (List<VoxelChunk> chunks, bool onlyModified)
Returns all created chunks into the chunks list (must provide an already initialized list, contents will be cleared by the method). The onlyModified argument limit the result to chunks modified by the user.


public bool ChunkDestroy (Vector3 position)
Clears a chunk given a world space position.

public bool DestroyAllVoxels ()
Destroys everything and reloads the world. Similar to ReloadWorld method.


public bool GetChunkNavMeshIsReady(VoxelChunk chunk)

Returns true if the NavMesh is generated and ready to use on that chunk


public void ChunkRedraw (VoxelChunk chunk, bool includeNeighbours = false, bool refreshLightmap = true, bool refreshMesh = true)
Causes a chunk to be refreshed. Chunk lightmap will be computed again and Its mesh will be generated. Methods that modify chunks content automatically handle chunk refreshes so you should never need to call this method unless you're modifying directly the chunk.voxel array.

If includeNeighbours is set, the 26 surrounding chunks will also be refreshed.


public bool ChunkReset(VoxelChunk chunk)

Clears any user modification on a chunk and regenerates it by invoking the terrain generator again. Also clears the chunk.modified flag.


public void ChunkCheckArea (Vector3 position, Vector3 chunkExtents, bool renderChunks = false)

Ensures chunks within given bounds defined by chunkExtents are generated and optionally rendered (renderChunks = true). This is useful when you need to generate chunks on demand when they are out of view (ie. far chunks). When renderChunks is true, the chunks mesh, colliders and NavMesh will also be generated (if they're enabled in Voxel Play Environment options).


public byte[] GetChunkRawBuffer()

Returns a newly allocated byte array to store contents of a chunk. Use with GetChunkRawData() method:


public int GetChunkRawData(VoxelChunk chunk, byte[] contents)

Writes the contents of a chunk (voxels) into the array contents starting at index "baseIndex". The allocation of the byte array should be obtained using GetChunkRawData() method. Contents are packed using RLE compression to reduce memory usage. The method returns the actual data length contained in contents array.

    

public byte[] SetChunkRawData(VoxelChunk chunk, byte[] contents, int length, bool validate = true)

Replaces the contents of a chunk with "contents". Length param determines the length of valid data inside the contents array (because the array can be bigger than the actual data in it; . If validate is set to true, the voxel types will be checked to ensure they correspond to existing voxel definitions. The contents of the byte array should be obtained using GetChunkRawData() method.




Voxel Definitions methods


public List<VoxelDefinition> voxelDefinitions
The list with all available voxel definitions in current world.


public AddVoxelDefinition(VoxelDefinition vd)

Adds a custom voxel definition created at runtime.


public GetVoxelDefinition(string name)
Return a voxel definition by its name

public GetVoxelDefinition(int index)
Return a voxel definition by its index

voxelDefinitions.Count
Total number of voxel definitions



Voxel methods


Getting voxels:


public Voxel GetVoxel (Vector3 position)
Gets the voxel at a given position. Returns Voxel.Empty if no voxel found.


public Voxel GetVoxels (Vector3 boxMin, Vector3 boxMax, Voxel[,,] voxels)
Returns a copy of all voxels contained in the volume defined by boxMin/boxMax positions. Note that it retrieves a copy. Use SetVoxels to place a 3D array of voxels into the world. Use GetVoxelIndices if you need to examine contents of an area in a faster way.


public bool GetVoxelIndex (Vector3 position, out VoxelChunk chunk, out int voxelIndex, bool createChunkIfNotExists = true)
Gets the chunk and array index of the voxel at a given position

public int GetVoxelIndex (int px, int py, int pz)
Gets the index of a voxel by its local x,y,z positions inside a chunk.


public int GetVoxelIndices (Vector3 boxMin, Vector3 boxMax, List<VoxelIndex> indices, byte minOpaque, byte hasContents)

Returns all visible or empty voxels within a given 3D volume limited by boxMin/boxMax. You must provide a list as the third argument to which this method will write to. Method returns the count of all visible voxels found.


public int GetVoxelIndices (Vector3 center, int radius, List<VoxelIndex> indices, byte minOpaque, byte hasContents)

Returns all visible or empty voxels within a sphere defined by center and radius. You must provide a list as the third argument to which this method will write to. Method returns the count of all visible voxels found.


public int GetVoxelIndices (Vector3 boxMin, Vector3 boxMax, List<VoxelIndex> indices, SDF sdf)

Returns al voxel indices which satisfy the SDF. The sdf argument is a C# function that accepts a world space position and must return a negative value if that position is contained in a desired volume (sphere, torus, cylinder, custom, ...) or zero or greater if it's outside. The sdf function is evaluated for all positions in the area defined by boxMin - boxMax.

The SDF function must conform to the delegate: delegate float SDF(Vector3 worldPosition);


public Vector3 GetVoxelPosition (VoxelChunk chunk, int voxelIndex)
Gets the voxel position in world space coordinates.

public void GetVoxelChunkCoordinates (int voxelIndex, out int px, out int py, out int pz)
Given a voxel index, returns its x, y, z position inside the chunk


public Voxel GetVoxelUnder (Vector3 position, bool includeWater = false)

Returns the voxel under a given position optionally ignoring water.


public VoxelIndex GetVoxelUnderIndex (Vector3 position, bool includeWater = false)

Returns a VoxelIndex struct containing the chunk and voxelIndex in the chunk's voxel array for the voxel below position, optionally ignoring water.


public GameObject GetVoxelGameObject (Vector3 position)

Returns the gameobject of a custom voxel placed in the world. This only works with instantiated custom voxels. If the custom voxel has GPU instancing enabled, this method returns null, as Voxel Play directly renders GPU instanced voxels on the GPU without creating the gameobject (unless its creation is explicitly marked in the voxel definition).



Placing voxels:


public void VoxelPlace (Vector3 position, VoxelDefinition voxelType, [Color tintColor], [bool playSound])
Places a new voxel on a givel position in world space coordinates. Optionally assign a tint color and/or plays a sound.


public void VoxelPlace (Vector3 position, Color tintColor, bool playSound = true)
Places a new voxel on a givel position in world space coordinates. Uses default voxel (solid) with tint color. Optionally plays a sound.


public void VoxelPlace (List<Vector3> positions, VoxelDefinition voxelType, Color tintColor, List<VoxelChunk> modifiedChunks = null)
Mass place a voxel type on a list of world positions. Optionally assign a tintColor (use Color.white to preserve texture colors) and returns the list of modified chunks.


public void VoxelPlace (List<VoxelIndex> indices, VoxelDefinition voxelType, Color tintColor, List<VoxelChunk> modifiedChunks = null)
Mass place a voxel type on a list of voxel indices. Optionally assign a tintColor (use Color.white to preserve texture colors) and returns the list of modified chunks.


public void VoxelPlace (Vector3 boxMin, Vector3 boxMax, VoxelDefinition voxelType, Color tintColor, List<VoxelChunk> modifiedChunks = null)
Fills a volume with a given voxel definition and tint color. Optionally returns the list of modified chunks.


public void VoxelPlace (Vector3 boxMin, Vector3 boxMax, Voxel[,,] voxels, bool ignoreEmptyVoxels = false)
Fills a volume with the contents of the voxels array. To skip empty positions in the array, set ignoreEmptyVoxels to true.



Destroying voxels:


public bool VoxelDestroy (Vector3 position)
Clears a voxel at the given position.

public VoxelPlaceholder GetVoxelPlaceholder (VoxelChunk chunk, int voxelIndex, bool createIfNotExists = true)
Creates a placeholder for a given voxel. A placeholder is a real gameobject that's created at a given voxel position and acts as a placeholder for special effects (voxel cracks) or to hold specific scripts that are linked to that voxel. When that voxel is destroyed, the placeholder is disabled.


public bool VoxelDamage (Vector3 position, int damage)
Damages a voxel. This method won't add particles.


public bool VoxelDamage(Vector3 position, Vector3 hitDirection, int damage, bool addParticles = false, bool playSound = false)

This overload allows you to specify the impact direction and also emit particles and sound.


public bool VoxelDamage(Vector3 voxelCenter, Vector3 point, Vector3 normal, int damage, bool addParticles = false, bool playSound = false)

This overload damages a voxel by passing the center of the voxel, the hit position and the voxel surface normal..


public bool VoxelDamage(VoxelHitInfo hitInfo, int damage, bool addParticles = false, bool playSound = false)

This overload damages a voxel by passing the hitInfo struct data from env.RayCast method.


public bool VoxelDamage (Vector3 position, int damage, int radius, bool attenuateDamageWithDistance, bool addParticles, List<VoxelIndex> damagedVoxels)
Damages a group of voxels within given radius with optional damage attenuation based on distance. This method can also return the list of damaged voxels as well as add particle effects over the damaged voxels.



Hiding voxels:


public void VoxelSetHidden (VoxelChunk chunk, int voxelIndex, bool hidden, HideStyle hiddenStyle = HideStyle.DefinedByVoxelDefinition)

Changes the visibility status of a voxel.


public void VoxelSetHidden (List<VoxelIndex> indices, bool hidden, HideStyle hiddenStyle = HideStyle.DefinedByVoxelDefinition)

Changes the visibility status of a list of voxels defined by its indices.


public void VoxelSetHidden (VoxelIndex [] indices, int count, bool hidden, HideStyle hideStyle = HideStyle.DefinedByVoxelDefinition)

Changes the visibility status of a list of voxels defined by its indices (array variant).


public bool VoxelIsHidden (VoxelChunk chunk, int voxelIndex)

Returns the visibility status of a single voxel.



Storing/reading custom voxel data:


public void VoxelSetProperty(VoxelChunk chunk, int voxelIndex, string propertyName, float propertyValue)
Assigns a voxel property with name "propertyName" with the value of propertyValue (a float).


public void VoxelSetProperty(VoxelChunk chunk, int voxelIndex, string propertyName, string propertyValue)
Assigns a voxel property with name "propertyName" with the value of propertyValue (a string).


public float GetVoxelPropertyFloat(VoxelChunk chunk, int voxelIndex, string propertyName)

     Gets the value of the property "propertyName" previously assigned to the voxel. Returns null if there's no property with that name assigned to the voxel.


public float GetVoxelPropertyString(VoxelChunk chunk, int voxelIndex, string propertyName)

     Gets the value of the property "propertyName" previously assigned to the voxel. Returns null if there's no property with that name assigned to the voxel.


public float VoxelClearProperty(VoxelChunk chunk, int voxelIndex, string propertyName)

     Clears property "propertyName" for a given voxel.


public float VoxelClearProperties(VoxelChunk chunk, int voxelIndex)

     Clears all properties of a specific voxel.


Note: destroying a voxel also removes any assigned property. Properties are includes in the savegame file.



Other:


public bool CheckCollision (Vector3 position)
Returns true if there's a collider voxel on that voxel position.


public bool VoxelOverlaps (Vector3 position, VoxelDefinition type, Quaternion rotation, int layerMask = -1)
Returns true if there's a collision between a voxel type and existing geometry. Position is in world space coordinates, type is the voxel type to place/check and Rotation is an optional rotation (this method already takes into account any rotation specified in the voxel type). LayerMask can be used to limit the test to certain objects.


public bool VoxelThrow (Vector3 position, Vector3 direction, float velocity, VoxelDefinition voxelType, Color32 color)
Creates a recoverable voxel and throws it with specified velocity and direction.


public GameObject VoxelGetDynamic (VoxelChunk chunk, int voxelIndex, bool addRigidbody = false)
Converts a voxel into a normal gameobject preserving its appearance. Dynamic voxels can be rotated and moved, as well as damaged and destroyed as normal voxels. Note that a dynamic voxel keeps its entry in the chunk array but its voxel definition changes with renderType set to Custom.

public GameObject VoxelCancelDynamic (VoxelChunk chunk, int voxelIndex)
Converts a dynamic voxel back into a regular voxel. Note that the mesh change won't occur until the chunk is out of frustum or exceeds certain distance to the camera to avoid visual glitches. Since dynamic voxels can have arbitrary rotations and positions, some voxels may not be converted back to regular voxels (eg. two dynamic voxels converge into the same voxel location); as a result some voxels will be converted to regular voxels at the appropriate locations while others will simply be removed.


public GameObject VoxelGetGameObject (VoxelChunk chunk, int voxelIndex)
Returns the gameobject associated to a voxel in the scene. The voxel must be dynamic or custom type (in this case the voxel definition of the custom voxel type must have "Create GameObject" option enabled). Note that voxel gameobjects are only created when the chunk has refreshed which occurs a few frames after a VoxelPlace call is issued.


public bool VoxelIsDynamic (VoxelChunk chunk, int voxelIndex)
Returns true if the voxel has been converted to dynamic voxel.


public bool VoxelHighlight (Vector3 position, Color color, float edgeWidth = 0)
Adds an edge-glowing animation to a voxel at a given position. If there's no voxel at the position, this method simply returns false.


public void VoxelHighlight (bool visible)
Shows or hide the voxel highlight effect.


public void VoxelCollapse (Vector3 position, int amount)
Makes voxels above position fall. Only voxels of types marked with "Will Collapse" flag will be included up to "amount".


public void VoxelRotate (Vector3 position, float anglesX, float anglesY, float anglesZ)
Rotate voxel at a given position and angles.


public void VoxelSetRotation (VoxelChunk chunk, int voxelIndex, float anglesX, float anglesY, float anglesZ)
Sets the rotation of a voxel at a given position. Voxel will be converted do dynamic if required.


public Quaternion VoxelGetRotation (VoxelChunk chunk, int voxelIndex)
Returns the rotation applied to a custom or dynamic voxel. Regular voxels will return a quaternion equals to zero rotation.


public void VoxelSetTexturesRotation (VoxelChunk chunk, int voxelIndex, int rotation)
Set the rotation for a voxel. The voxel does not rotate but the textures are swapped around  Y-axis "rotation" times. Rotation can be 0, 1, 2 or 3. Only voxels of type 6-textures can be rotated using this method.


public int VoxelGetTexturesRotation (VoxelChunk chunk, int voxelIndex)
Returns the current textures rotation of a voxel.


public int VoxelRotateTextures (VoxelChunk chunk, int voxelIndex, int rotation)
Rotates the side textures of a voxel around Y-axis "rotation" times. The rotation argument can be either positive or negative and specified the number of turns. Each turn represents 90º degree, ie: VoxelRotateTexture(thisChunk, 15, 1).




Model Definition methods


public void ModelPlace (Vector3 position, ModelDefinition model | VoxelDefinition array | colors array, buildDuration...)

Takes all voxels included in a model or colors in the array and put them on the desired place. Each entry in the given model matches 1 voxel in world space.

When placing a model, ModelPlace can return the list of visible voxels included in that model - pass a List<VoxelIndex> as a third argument to get the indices.


public ModelDefinition ModelWorldCapture (Bounds bounds)

Captures the contents of the world inside the given bounds and returns a new Model Definition with those contents.




Voxel Objects


public GameObject VoxelCreateGameObject (Color32[] colors, int sizeX, int sizeY, int sizeZ, Vector3 offset, Vector3 scale)

Creates a voxel gameobject from a colors array with optimal vertex count. The colors array must follow a Y/Z/X distribution and its dimensions must match sizeX/sizeY/sizeZ parameters.

Offset and Scale are optional and defines the resulting mesh center offset and scale.

Note that ModelPlace method creates a voxel per color in the array, while VoxelCreateGameObject creates a single mesh and gameobject. This method is useful to create custom items with voxel appearance.




Terrain/Water methods


public int waterLevel
The water level generated by the terrain generator. Equals to (int)(seaLevel * maxHeight).


public float GetHeight (Vector3 position)
Gets the highest voxel position under a given location (includes terrain and any other voxel object, like trees)

public float GetTerrainHeight (Vector3 position, bool includeWater = true)
Gets the terrain height under a given position

public HeightMapInfo GetTerrainInfo (Vector3 position)
Gets the terrain data on a given position

public float GetVoxelAmbientLight (Vector3 position) 
Gets the computed light amount at a given position in 0..1 range


public void AddWaterFlood (Vector3 waterPos, VoxelDefinition waterVoxel, int lifeTime = 24);

Starts water flooding at a certain position. Lifetime value is used to avoid infinite flooding.


public bool IsWaterAtPosition (Vector3 position);

Returns true if there's a water voxel at a given position.


public float GetWaterDepth (Vector3 position);

Returns the amount of water at a given position (depth of water or vertical amount of water).


public bool IsWallAtPosition (Vector3 position);

Returns true if there's a solid (fully opaque) voxel at a given position.


public bool IsEmptyAtPosition (Vector3 position);

Returns true if there is no voxel at the position.


public bool enableWaterFlood;

Session only flag that allows you to toggle water flood on/off. Disabling water flood allows you to paint "cascades". Example.




    

Raycasting methods

  

These method returns additional information in the VoxelhitInfo struct like the voxel center position and voxel type (see below).


public bool RayHit (Ray ray, int damage, float maxDistance = 0, int damageRadius = 1) 
Casts a ray and applies given damage to any voxel impacted in the direction. If damage radius is greater than 1, nearby voxels will also be affected.


public bool RayHit (Vector3 origin, Vector3 direction, int damage, float maxDistance = 0, int damageRadius = 1)
Casts a ray and applies given damage to any voxel impacted in the direction.If damage radius is greater than 1, nearby voxels will also be affected.


public bool RayHit (Vector3 origin, Vector3 direction, int damage, out VoxelHitInfo hitInfo, float maxDistance = 0, int damageRadius = 1)

Casts a ray and applies given damage to any voxel impacted in the direction. If damage radius is greater than 1, nearby voxels will also be affected.

 

public bool RayCast (Ray ray, out VoxelHitInfo hitInfo, float maxDistance = 0, byte minOpaque = 0)

Raycasts in the direction of the ray. The minOpaque argument specifies the minimum opaque factor for the ray to stop (grass has opaque = 0, water = 2, cutout/tree leaves=3, opaque voxels=15).


public bool RayCast (Vector3 origin, Vector3 direction, out VoxelHitInfo hitInfo, float maxDistance = 0, byte minOpaque = 0)

Raycasts from a given origin and direction. The minOpaque argument specifies the minimum opaque factor for the ray to stop (grass has opaque = 0, water = 2, cutout/tree leaves=3, opaque voxels=15).


public VoxelHitInfo lastHitInfo;

Returns information on the last voxel hit.



VoxelHitInfo fields description:

- point: the world space position of the hit. Note that the hit position is always on the edge of a voxel and cannot be used to retrieve the voxel at that position. For example, when casting a ray downwards and hitting a voxel whose center is (x=0, y=26.5, z=0), the point position would be (x = 0, y=27.0, z=0) which corresponds with the top face of the cube. However if you use GetVoxelIndex() and use that position (x=0,y=27.0,z=0), it will return the voxel on top because the next voxel is at 27. Use voxelCenter instead which returns the center of the voxel hit.

- voxelCenter: the center of the voxel hit in world space. Use this position when calling GetVoxelIndex or other methods that require a position.

- distance: the distance to the hit surface.

- sqrDistance: distance * distance.

- voxelIndex: the index of the voxel.

- chunk: the chunk where the voxel is.

- normal: the normal of the voxel at the hit position.

- collider: the collider of the gameobject or voxel if it exists.

- placeholder: the voxel placeholder if the voxel is dynamic or custom type with "Create GameObject" enabled.




Inventory/items/object methods

   

public ItemDefinition[] allItems

Gets an array with all the available world voxel definitions


public ItemDefinition GetItemDefinition(category, voxelType)

Gets an item definition based on the category and voxel type options


public ItemDefinition GetItemDefinition(string name)

Gets an item definition by name


public GameObject TorchAttach(hitInfo)

Adds a torch on certain position. A hitinfo struct must be provided which includes the exact position and orientation of the torch. You can reuse the crosshairHitInfo public property of the Voxel

PlayFirstPersonController component (VoxelPlayFirstPersonController.instance.crosshairHitInfo). This method returns the gameobject of the torch itself.


public void TorchAttach(hitInfo)

Removes a torch. You need to pass the chunk where the torch is located and the gameobject of the torch itself.


public GameObject ItemThrow(position, direction, velocity, itemDefinition)

Throws a new item from position towards direction with velocity.


public GameObject ItemSpawn(itemDefinition, position, quantity)

Drops an amount of the same item definition on a given position.




Misc functions


      public void ParticleBurst(position, style, count, intensity, ...);

Adds voxel particles at a certain position simulating a explosion or other effects.


public float GetVoxelAmbientLight(position, out chunk, out voxelIndex);

Returns the GI intensity (0..1) at a given position. This method can also returns the chunk and voxel index at that position.


      public void SetSunRotation(Quaternion rotation);

Manually sets the current directional light (or Sun) rotation. This method is useful to ensure when syncing the daytime across clients in multiplayer environment.


public void ShowMessage (text, displayDuration, flashEffect);
Adds a message to the UI with optional duration and flash effect.

playerGameObject;
Returns a reference to the player gameobject (the gameobject that has the CharacterController script attached).


lastMessage;
Returns the last message added to the console.




Load/Save/Initialization functions


public void ReloadWorld()

Destroyes everything and reloads current assigned world 


public void Redraw()
Redraws all chunks. This method is called by the system when some visual property is changed (ie. GI or Ambient Occlusion)


public void ReloadTextures ()

Reloads all world textures 


public bool LoadGameBinary(bool firstLoad, bool preservePlayerPosition, VoxelDefinition fallbackVoxelDefinition)

Loads saved game specified by the saveFilename property of VoxelPlayEnvironment component. Use firstLoad = true if this saved game is used as the starting map, otherwise pass "false" if player is just loading a saved game. The "preservePlayerPosition" allows you to keep player position and orientation when the saved game is loaded (default = false).

The fallbackVoxelDefinition is optional and let you specify a substitute for any missing voxel definition.


public bool SaveGameBinary()

Saves the game into "saveFilename" (property of VoxelPlayEnvironment. Returns true if success.

Saved games are stored inside the Worlds/worldname/SavedGame folders when running inside Unity Editor. In a real build, saved games are stored in Application.persistentDataPath + "/VoxelPlay" folder.


public byte[] SaveGameToByteArray ()

Returns the world encoded in a byte array.


public string SaveGameToBase64 ()

Returns the world in a base-64 encoded string.


public bool LoadGameFromByteArray (byte[] saveGameData, bool preservePlayerPosition, bool clearScene, VoxelDefinition fallbackVoxelDefinition)
Loads game world from a byte array optionally preserving current player position. If you set clearScene to false, existing chunks will be preserved and only modified chunks will be considered (modified chunks in the scene not present in the saved file data will be reseted to default contents). The fallbackVoxelDefinition is optional and let you specify a substitute for any missing voxel definition.


public bool LoadGameFromBase64 (string saveGameData, bool preservePlayerPosition, bool clearScene, VoxelDefinition fallbackVoxelDefinition)
Loads game world from a base-64 encoded string optionally preserving current player position. If you set clearScene to false, existing chunks will be preserved and only modified chunks will be considered (modified chunks in the scene not present in the saved file data will be reseted to default contents). The fallbackVoxelDefinition is optional and let you specify a substitute for any missing voxel definition.


public void SetBuildMode (bool buildMode)  

Sets or cancel build mode