#!/usr/bin/env python3
"""Bisect edges between locations

Given pairs of co-ordinates, find all the edges going from one to the other 
and bisect, inserting new faces so that it doesn't change the static appearance.

The new vertices in the middle of the edges have the average of the 
values of their 'parents'.

You can do this in Blender, but sometimes the result cannot be re-exported 
to vb format.

The first argument is the mesh to modify. Subsequent arguments come in sixes, 
as the X, Y, Z and X2. Y2, Z2 of the points between which edges should be 
bisected. Accuracy depends on how many values follow the decimal point, 
for example, 4.5 matches 4.45-4.55, 4.50 matches 4.495-4.505.
"""

import sys

import vb

if __name__ == '__main__':
	mesh = vb.Mesh(sys.argv[1])
	additions = []
	for i in range(2, len(sys.argv), 6):
		s1 = [x[0] for x in mesh.find_by_position(sys.argv[i:i+3], maxnum=None)]
		s2 = [x[0] for x in mesh.find_by_position(sys.argv[i+3:i+6], maxnum=None)]
		for i in s1:
			other = [x for x in s2 if x in mesh.neighbours[i]]
			if len(other) != 1:
				raise Exception('Could not find precisely one selected neighbour')
			additions.append((i, other[0]))
	for i, j in additions:
		mesh.bisect_line(i, j)
	input('Bisected %d lines, ready to write...' % len(additions))
	mesh.write(sys.argv[1])

