#!/usr/bin/env python
from gi.repository import v_sim

# Load the file to test.
data = v_sim.Data.new()
data.addFile("collisions.ascii",0,None)
v_sim.visuBasicLoad_dataFromFile(data,None,0)

# Parse the configuration files.
v_sim.visuBasicParse_configFiles()
# Or read only the given file.
#v_sim.visuConfigFileLoad(v_sim.CONFIGFILE_RESOURCE, "v_sim.res", data)


# Example of loop to create a dictionnary associating element name and radius.
rad = {}
dataIter = data.iterNew()
data.iterStart(dataIter)
while (dataIter.element != None):
  rad[dataIter.element.name] = v_sim.renderingAtomicGet_radius(dataIter.element)
  data.iterNextElement(dataIter)

# Example with integrated iterators (still an issue with the
# stop criterion)
try:
  for it in data.__iterElements__():
    rad[it.element.name] = v_sim.renderingAtomicGet_radius(it.element)
except RuntimeError:
  pass
print "Radii: ", rad


def hit(c1, r1, c2, r2):
  return ( (c1.x-c2.x)**2 + (c1.y-c2.y)**2 + (c1.z-c2.z)**2 < (r1 + r2) ** 2 )

# With Python iterators.
##collision = []
##try:
##  for it1 in data:
##    try:
##      for it2 in data:
##        if it1.node.number > it2.node.number and \
##	     hit(data.getNodeCoordinates(it1.node), rad[it1.element.name], \
##		 data.getNodeCoordinates(it2.node), rad[it2.element.name]):
##	  collision.append((int(it1.node.number), int(it2.node.number)))
##    except RuntimeError:
##      pass
##except RuntimeError:
##  pass
##print collision

# With V_Sim iterators
print "Collision detection..."
collision = []
it1 = data.iterNew()
it2 = data.iterNew()
data.iterStart(it1)
while (it1.node is not None):
  data.iterStart(it2)
  while (it2.node is not None):
    if it1.node.number > it2.node.number and \
	 hit(data.getNodeCoordinates(it1.node), rad[it1.element.name], \
	     data.getNodeCoordinates(it2.node), rad[it2.element.name]):
      collision.append((int(it1.node.number), int(it2.node.number)))
    data.iterNext(it2)
  data.iterNext(it1)
print collision
