#Include "Ninfa3d.bi"

dim Shared camera As nCAMERA
dim As nLIGHT light01,light02

'Enable vertical synch.
EnableVsync()

'Starts the Ninfa3D Engine
InitEngine(640,480,32,0)
	BackGroundColor(128,128,128)'Background Color
	AmbientLight(32,32,32)'Ambient color
	PhysicQuality(Q_LINEAR)

'Include the file "SampleFuntions.bi.
'It contains useful features, such as drawing the interface and create the test area.
#Include "SampleFunctions.bi"

'Create a camera
camera = CreateCamera()
	PositionEntity(camera,0,128,-256)'Position

'Creates the lights
light01 = CreateLight(LGT_POINT)
    lightradius(light01,175)
    lightcolor(light01,100,50,50)
	PositionEntity(light01,0,128,-128)' Position
	
	
light02 = CreateLight(LGT_POINT)
    lightradius(light02,175)
    lightcolor(light02,50,50,100)
	PositionEntity(light02,0,128,128)
	

CreateGround()'Creates the test area

'Create cubes in total approximately 490
Dim As nMESH msh(490)
Dim As nBODY bdy(490)

Dim As I x,y,z,i

For x = -9 To 9 Step 3
	For y = 1 To 19 Step 2
		For z = -9 To 9 Step 3
		
			i = i + 1
			
			msh(i) = CreateMeshCube()'Creates a mesh type cube
				ScaleMesh(msh(i),10,10,10)'Scale the mesh
				MaterialColor(msh(i),0,Rand(0,255),Rand(0,255),Rand(0,255))'Change the color
				
			bdy(i) = CreateBodyCube(10,10,10,2)'Create a cube body
				EntityParent(bdy(i),msh(i))'This makes the mesh assigned, follow both
													'Position as the rotation of the body.
				
				PositionEntity(bdy(i),x*7,y*8,z*7)'Position the body.

		Next
	Next
Next

'Load the sound.
Dim As nSOUND sound = LoadSound("media/hegrenade-2.wav")
	SoundType(sound,1)'Type of sound, sound 2D

'This is the countdown to the explosion.
Dim As I c = 200

While(EngineRun)'Returns 1 if the engine is running.

	'Begins scene
	BeginScene()
	
	'By pressing the "ESCAPE" closes the engine.
	If KeyHit(KEY_ESCAPE) Then CloseEngine()
	
	'Update the Engine.
	'Changing the value (only affects the physics) that will update the
	'Physical faster or slower.
	UpdateEngine(0.05)
    
    WorldMousePick(MouseX(),MouseY(),MouseDown(MOUSE_LEFT))
	'Countdown starts a very simple ;-)
	c = c - 1

	'Causes the ejection cube in all directions.
	If (c = 0) Then
	
		PlaySound(sound)

		For i = 1 To 490
			'Present position of the mesh
			Dim As S xx = EntityX(msh(i))
			Dim As S yy = EntityY(msh(i))
			Dim As S zz = EntityZ(msh(i))
			Dim As S dist2 = xx*xx+yy*yy+zz*zz
			' Force
			Dim As S power = 10000.0
			Dim As S fx = power*xx/dist2
			Dim As S fy = power*yy/dist2
			Dim As S fz = power*zz/dist2
			LinearVelocity(bdy(i),fx,fy,fz)
			' Turn
			Dim As S power2 = 100000.0
			Dim As S Torque = power2/dist2
			AngularVelocity(bdy(i),Rand(-Torque,Torque),Rand(-Torque,Torque),Rand(-Torque,Torque))
		Next
	EndIf

	'Displays the interface (FPS and triangles)
	'Interface()

	'Displays the time left before the explosion
	If c>0 Then Text(320,50,"Tiempo: "+Str$(c),1,1)

	'End the scene
	EndScene()
	
Wend

'Ends Ninfa3D Engine
EndEngine()