This page has been translated automatically.
Video Tutorials
Interface
Essentials
Advanced
How To
UnigineEditor
Interface Overview
Assets Workflow
Settings and Preferences
Working With Projects
Adjusting Node Parameters
Setting Up Materials
Setting Up Properties
Lighting
Landscape Tool
Sandworm
Using Editor Tools for Specific Tasks
Extending Editor Functionality
Built-in Node Types
Nodes
Objects
Effects
Decals
Light Sources
Geodetics
World Objects
Sound Objects
Pathfinding Objects
Players
Programming
Fundamentals
Setting Up Development Environment
UnigineScript
C++
C#
UUSL (Unified UNIGINE Shader Language)
File Formats
Rebuilding the Engine Tools
GUI
Double Precision Coordinates
API
Containers
Common Functionality
Controls-Related Classes
Engine-Related Classes
Filesystem Functionality
GUI-Related Classes
Math Functionality
Node-Related Classes
Objects-Related Classes
Networking Functionality
Pathfinding-Related Classes
Physics-Related Classes
Plugins-Related Classes
IG Plugin
CIGIConnector Plugin
Rendering-Related Classes
Content Creation
Content Optimization
Materials
Art Samples
Tutorials
Warning! This version of documentation is OUTDATED, as it describes an older SDK version! Please switch to the documentation for the latest SDK version.
Warning! This version of documentation describes an old SDK version which is no longer supported! Please upgrade to the latest SDK version.

Intersections

Unigine has different methods to detect intersections. Intersection is a shared point of the defined area (or line) and an object. This article describes different types of intersections and their usage.

There are three main types of intersections:

Shape and Object classes have their own getIntersection() functions. They are used for detecting intersections with the specific shape or the specific surface of the object.

World Intersection#

By using different overloaded World class getIntersection() functions you can find objects and nodes that intersect bounds of the specified bounding volume or find the first intersection of the object with the invisible tracing line.

World class functions for intersection search can be divided into 3 groups:

Intersection with Nodes#

To find the intersection of nodes with bounds of the specified volume, you should use functions that have a bounding volume and a vector of nodes in arguments:

Schematic visual representation of intersection with nodes in bounding volume.

These functions return the value indicating the result of the intersection search: 1 if the intersection was found; otherwise, 0. Intersected nodes can be found in the collection that passed as an argument to the function.

To clarify the nodes search, perform the following:

  • Specify the type of node to search.
Usage Example

In the example below, the engine checks intersections with a bounding box and shows the message in the console.

In the init() function the bounding box is defined.

The main logic is in the update() method: the engine checks the intersection and shows the message about intersection.

Source code (C#)
// AppWorldLogic.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Unigine;

namespace UnigineApp
{
	class AppWorldLogic : WorldLogic
	{
		// define a bounding box
		WorldBoundBox boundBox;
		// create a counter to show the message once
		int counter = 1;

		public override bool Init()
		{
			// initialize the bounding box
			boundBox = new WorldBoundBox(new dvec3(0.0f), new dvec3(10.0f));
			return true;
		}

		public override bool Update()
		{
			// check the intersection with the bounding box

			List<Node> nodes = new List<Node>();
			bool result = World.GetIntersection(boundBox, nodes);
			if (result && counter !=0)
			{
				foreach(Node n in nodes)
				{
					// show the name of the intersected node in the console
					Log.Message("There was an intersection with: {0} \n", n.Name);
				}
				counter--;
			}
			return true;
		}

		/* ... */
	}
}

Intersection with Objects#

The following functions can be used to perform the intersection search with objects:

Schematic visual representation of intersection with objects in bounding volume.

These functions return the value indicating the result of the intersection search: 1 if the intersection was found; otherwise, 0. You can pass the start (vec3 p0) and the end (vec3 p1) point of the intersecting line or pass the (BoundBox, BoundFrustum, BoundSphere) to get the intersection of objects with a line or with a bounding volume, respectively. Intersected nodes can be found in the collection that passed as an argument to the function.

Usage Example 1

In the example below, the engine checks intersections with a bounding box and shows the message in the console.

In the init() function the bounding box is defined.

The main logic is in the update() method: the engine checks the intersection and shows the message about intersection.

Source code (C#)
// AppWorldLogic.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Unigine;

namespace UnigineApp
{
	class AppWorldLogic : WorldLogic
	{
		// define a bounding box
		WorldBoundBox boundBox;
		// create a counter to show the message once
		int counter = 1;

		public override bool Init()
		{
			// initialize the bounding box
			boundBox = new WorldBoundBox(new dvec3(0.0f), new dvec3(10.0f));
			return true;
		}

		public override bool Update()
		{
			// check the intersection with the bounding box
			List<Unigine.Object> objects = new List<Unigine.Object>();
			bool result = World.GetIntersection(boundBox, objects);
			if (result && counter != 0)
			{
				foreach (Unigine.Object o in objects)
				{
					Log.Message("There was an intersection with: {0} \n", o.Name);
				}
				counter--;
			}
			return true;
		}

		/* ... */
	}
}
Usage Example 2#

In the example below, the engine checks intersections of a world bound frustrum with objects which are invisible because they are out of their maximum visible distance. To do so, it is required to set the global distance scale parameter to infinite value. This will make invisible objects appear and be detected by the intersection. Then we need to restore the previous distance scale value right away to avoid surfaces popping out in the next frame.

Source code (C#)
// AppWorldLogic.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Object = Unigine.Object;
using Console = System.Console;

using Unigine;

namespace UnigineApp
{
	class AppWorldLogic : WorldLogic
	{
		bool inf_scale = false;

		public override bool Init()
		{
			// enable the visualizer
			Visualizer.Enabled = true;
		}

		public override bool Update()
		{
			// turn on and off the bound sphere visualization with a key press
			if (Input.IsKeyDown(Input.KEY.SPACE))
				inf_scale = !inf_scale;
			
			// get a reference to the camera
			Player player = Game.Player;
			Camera camera = player.Camera;

			// bound frustrum for the intersection and a list to store intersected objects
			var      bf = new BoundFrustum(camera.Projection, camera.Modelview);
			var objects = new List<Object>();

			// remember the old distance scale
			var old_ds = Render.DistanceScale;

			// set the global distance scale to infinity
			if (inf_scale)
				Render.DistanceScale = MathLib.INFINITY;
			
			// perform the intersection search with the bound frustrum
			World.GetIntersection(bf, objects);

			// draw the bound spheres of all objects' surfaces found by the search
			foreach(var obj in objects)
            {
				for (int i = 0; i < obj.NumSurfaces; ++i)
                {
					float d = obj.GetMaxVisibleDistance(i);
					if (d != MathLib.INFINITY)
                    {
						var bs = obj.GetBoundSphere(i);
						Visualizer.RenderBoundSphere(bs, obj.WorldTransform, new vec4(1,0,0,1));
						break;
					}
				}
			}

			// reset the distance scale to the old value
			Render.DistanceScale = old_ds;

			return true;
		}

		/* ... */
	}
}

By default, the intersection with a camera-based bounding frustrum uses the global distance scale. To make more objects get inside the camera frustrum, just increase the global distance scale.

First Intersected Object#

The following functions are used to find the nearest intersected object with the traced line. You should specify the start point and the end point of the line, and the function detects if there are any object on the way of this line.

Schematic visual representation of intersection with objects and traced line.

These functions return an intersection information and a pointer to the nearest object to the start point (p0). Information about the intersection can be presented in standard vectors or in the following format that you pass to functions as arguments:

  • WorldIntersection intersection - the WorldIntersection class instance. By using this class you can get the intersection point (coordinates), the index of the intersected triangle of the object and the index of the intersected surface.
  • WorldIntersectionNormal normal - the WorldIntersectionNormal class instance. By using this class you can get only the normal of the intersection point.
  • WorldIntersectionTexCoord texcoord - the WorldIntersectionTexCoord class instance. By using this class you can get only the texture coordinates of the intersection point.

These functions detect intersection with surfaces (polygons) of meshes. But there are some conditions to detect the intersection with the surface:

  1. The surface is enabled.
  2. The surface has a material assigned.
  3. Per-surface Intersection flag is enabled.
    Notice
    You can set this flag to the object's surface by using the Object.setIntersection() function.

To clarify the object search, perform the following:

  • Use an intersection mask. An intersection is found only if an object is matching the intersection mask.
  • Specify the list of objects (nodes) to exclude and pass to the function as an argument.
Usage Example

In the example below, the engine checks intersections with a bounding box and shows the message in the console.

In the init() function the bounding box is defined.

The main logic is in the update() method: the engine checks the intersection and shows the message about intersection.

Source code (C#)
// AppWorldLogic.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Unigine;

namespace UnigineApp
{
	class AppWorldLogic : WorldLogic
	{
		// define world intersection instance
		WorldIntersection wi;
		// create a counter to show the message once
		int counter = 1;

		public override bool Init()
		{
			// initialize the world intersection
			wi = new WorldIntersection();
			return true;
		}

		public override bool Update()
		{
			// check the intersection with the bounding box
			Unigine.Object o = World.GetIntersection(new dvec3(0.0f), new dvec3(1.0f), 1, wi);
			if (o != null && counter != 0)
			{
				Log.Message("The name of the obstacle is: {0} \n", o.Name);
				counter--;
			}
			return true;
		}

		/* ... */
	}
}

Physics Intersection#

Physics intersection function detects intersections with a physical shape or a fracture body. If the object has no body, this function detects intersection with surfaces (polygons) of the object having the physics intersection flag enabled. When you need to find the intersection with the shape of the object (not with polygons), the intersection function of Physics class is the best way to get it.

The picture above shows how the getIntersection() function detects the shape that intersects with the line.

There are 4 functions to find physics intersections:

These functions perform tracing from the start p0 point to the end p1 point to find a collision object (or a shape) located on that line. Functions use world space coordinates.

Thus, to exclude some obstacles you should use these methods:

  • Use a physics intersection mask. A physics intersection is detected only if the physics intersection mask of the surface/shape/body matches the intersection mask passed as a function argument, otherwise it is ignored.
  • Specify the list of objects to exclude and pass to the function as an argument.

Usage Example

The following example shows how you can get the intersection information by using the PhysicsIntersection class. In this example we specify a line from the point of the camera (vec3 p0) to the point of the mouse pointer (vec3 p1). The executing sequence is the following:

  1. Define and initialize two points (p0 and p1) by using the Player.getDirectionFromScreen() function.
  2. Create an instance of the PhysicsIntersection class to get the intersection information.
  3. Check, if there is an intersection with an object with a shape or a collision object. The getIntersection() function returns an intersected object when the object intersects with the traced line.
  4. In this example, when the object intersects with the traced line, all the surfaces of the intersected object change their material parameters. If the object has a shape, its information will be shown in console. The PhysicsIntersection class instance gets the coordinates of the intersection point and the Shape class object. You can get all these fields by using getShape(), getPoint() functions.
Source code (C#)
// AppWorldlogic.cs

using Unigine;

#if UNIGINE_DOUBLE
    using Vec3 = Unigine.dvec3;
    using Vec4 = Unigine.dvec4;
    using Mat4 = Unigine.dmat4;
#else
    using Vec3 = Unigine.vec3;
    using Vec4 = Unigine.vec4;
    using Mat4 = Unigine.mat4;
#endif

namespace UnigineApp
{
	class AppWorldLogic : WorldLogic
	{
		ObjectMeshDynamic dynamic_mesh;
		
		public override bool Init()
		{

            // create a mesh instance with a box surface
            Mesh mesh = new Mesh();
            mesh.AddBoxSurface("box", new vec3(2.2f));
            
            // create a new dynamic mesh from the Mesh instance and add it to editor
            dynamic_mesh = new ObjectMeshDynamic(mesh);

            // assign a material to the dynamic mesh
            dynamic_mesh.WorldTransform = MathLib.Translate(new Vec3(0.0f, 0.0f, 2.0f));
            dynamic_mesh.SetMaterial("mesh_base", "*");

            // assign a body and a shape to the dynamic mesh
            BodyRigid body = new BodyRigid(dynamic_mesh);
            ShapeBox shape = new ShapeBox(body, new vec3(2.2f));

			return true;
		}

		public override bool Update() {

			// initialize points of the mouse direction
			Vec3 p0, p1;

			// get the current player (camera)
			Player player = Game.Player;
			if (player == null)
				return false;
			// get width and height of the current application window
			int width = App.GetWidth();
			int height = App.GetHeight();
			// get the current X and Y coordinates of the mouse pointer
			int mouse_x = App.GetMouseX();
			int mouse_y = App.GetMouseY();
			// get the mouse direction from the player's position (p0) to the mouse cursor pointer (p1)
			player.GetDirectionFromScreen(out p0, out p1, mouse_x, mouse_y, width, height);

			// create the instance of the PhysicsIntersection object to save the information about the intersection
			PhysicsIntersection intersection = new PhysicsIntersection();
			// get an intersection
			Unigine.Object obj = Physics.GetIntersection(p0, p1, 1, intersection);

			// if the intersection has been occurred, change the parameter of the object's material    
			if (obj != null)
			{
				for (int i = 0; i < obj.NumSurfaces; i++)
				{
					obj.SetMaterialParameterFloat4("albedo_color", new vec4(1.0f, 1.0f, 0.0f, 1.0f), i);
				}

				// if the intersected object has a shape, show the information about the intersection   
				Shape shape = intersection.GetShape();
				if (shape != null)
				{
					Log.Message("physics intersection info: point: ({0} {1} {2}) shape: {3}\n", intersection.Point.x, intersection.Point.y, intersection.Point.z, shape.GetType());
				}
			}

			return true;
		}
	}
}

Game Intersection#

Game class getIntersection() functions are used to check the intersection with obstacles (pathfinding nodes):

The engine creates an invisible cylinder with specified radius between two points and checks if an obstacle is presented inside of it.

Schematic visual representation of intersection with objects and cylinder volume.

These functions return an intersection information and a pointer to the nearest obstacle to the start point (p0). Information about the intersection will be presented in the GameIntersection class instance which you pass to the function as an argument or in the vector.

Use mask and exclude arguments of the overloaded function to specify the obstacle search.

To clarify the obstacle search, perform the following:

  • Use an obstacle intersection mask. An intersection is found only if an object is matching the intersection mask, otherwise it is ignored.
  • Specify the list of obstacles to exclude and pass to the function as an argument.

Usage Example

In the example below, the engine checks intersections with a obstacle box and shows the message in the console.

In the init() function the obstacle box is initialized.

The main logic is in the update() method: the engine checks the intersection and shows the message about the intersection.

Helpers drawn using the Visualizer class to show the volume inside which to check for obstacles.

Source code (C#)
// AppWorldLogic.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Unigine;

namespace UnigineApp
{
	class AppWorldLogic : WorldLogic
	{
		// define an obstacle box and game intersection instance
		ObstacleBox obstacleBox;
		GameIntersection gi;
		// create a counter to show the message once
		int counter = 1;

		// parameters of the virtual cylinder defining the volume
		// inside which to check for intersections
		float radius = 5.0f;		// radius of the cylinder
		vec3 p1 = new vec3(0.0f);	// starting point of the ray
		vec3 p2 = new vec3(3.0f);	// ending point of the ray
		
		// define duration for rendering Visualizer helpers (in seconds)
		float duration = 10.0f;
		
		public override bool Init()
		{
			// initialize the obstacle box and specify the name
			obstacleBox = new ObstacleBox(new vec3(1.0f));
			obstacleBox.Name = "main_obstacle";
			
			// initialize the game intersection object
			gi = new GameIntersection();
			
			// enable visualizer to show helpers
			Visualizer.Enabled = true;

			// get transform matrix for the cylinder via the SetTo(p1, p2, Up) function,
			// it will translate our cylinder to p1 and orient it towards the p2 (Up vector here is the Z axis (0,0,1) )
			mat4 transform_matrix = MathLib.SetTo(p1, p2, new vec3(0.0f,0.0f,1.0f));

			// draw a red transparent cylinder
			Visualizer.RenderSolidCylinder(radius, height, transform_matrix, new vec4(1.0f, 0.0f, 0.0f, 0.2f), duration);

			// draw a black vector
			Visualizer.RenderVector(p1, p2, new vec4(0.0f, 0.0f, 0.0f, 1.0f), 0.25f, false, duration);

			// draw visualizer for the box obstacle
			Visualizer.RenderBox(obstacleBox.Size, obstacleBox.Transform, new vec4(1.0f), duration);
			
			return true;
		}

		public override bool Update()
		{

			
			// check for intersection with the obstacle box
			Obstacle obstacle = game.GetIntersection(p1, p2, radius, 1, gi);
			
			// draw helpers
			
			// calculate cylnder height (equals to the distance between the starting and ending points)
			float height = MathLib.Length(p2-p1);

			if (obstacle != null && counter != 0)
			{
				Log.Message("The name of the obstacle is: {0} \n", obstacle.Name);
				counter--;
			}
			return true;
		}

		/* ... */
	}
}
Last update: 2021-08-24
Build: ()