#!BPY
# -*- coding: latin-1 -*-
"""
Name: 'Holes'
Blender: 248
Group: 'Wizards'
Tooltip: 'edit holes.txt to change variation'
"""

# --------------------------------------------------------------------------
# ***** BEGIN GPL LICENSE BLOCK *****
#
# Copyright (c) Bartius Crouch, 2007
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software Foundation,
# Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
#
# ***** END GPL LICENCE BLOCK *****
# --------------------------------------------------------------------------
# Fill a rectangle with circles

# To execute, press ALT+P

import Blender
from Blender import *
from math import sin, cos, pi

def LoadFile(filename):
	#Get the resolution
	resolution = Draw.PupIntInput("Circle resolution",32,3,100)
	if resolution == None: resolution = 32
	
	#Make sure we're in object mode
	editmode = Window.EditMode()
	if editmode: Window.EditMode(0)
	
	#Load the file
	txt = Text.Load(filename)
	lines = txt.asLines()
	
	#Create / get the mesh
	try:
		me = Mesh.Get('Foam')
		me.verts = None
	except:
		me = Mesh.New('Foam')
	
	#Create the outer rectangle
	rect = lines[0].split()
	coords = [ [int(rect[0]),int(rect[1]),0],
	[int(rect[2]),int(rect[3]),0],
	[int(rect[4]),int(rect[5]),0],
	[int(rect[6]),int(rect[7]),0]]
	edges = [ [0,1], [1,2], [2,3], [3,0] ]
	me.verts.extend(coords)
	me.edges.extend(edges)
	lines.pop(0)
	
	#Create the circles
	coords = []
	edges = []
	n = -1
	for i in lines:
		n+=1
		a,b,c = i.split()
		x = float(a)
		y = float(b)
		r = float(c)/2
		for j in range(0,resolution):
			xj = cos((j/float(resolution))*2*pi)*r+x
			yj = sin((j/float(resolution))*2*pi)*r+y
			coords.append([xj,yj,0])
			if j==resolution-1:
				edges.append([n*resolution+4+j,n*resolution+4])
			else:
				edges.append([n*resolution+4+j,n*resolution+4+j+1])
	me.verts.extend(coords)
	me.edges.extend(edges)
	
	#Create / get the object
	scn = Scene.GetCurrent()
	try:
		ob = Object.Get('Foam')
		ob.link(me)
		try:
			scn.objects.link(ob)
		except:
			pass
	except:
		ob = scn.objects.new(me,'Foam')
	
	#Fill the mesh
	me.fill()
	
	#Clean up and redraw
	if editmode: Window.EditMode(1)
	Text.unlink(txt)
	Blender.Redraw()

#Select the file
file = Window.FileSelector(LoadFile, "Load file")