#!BPY

"""
Name: 'Blender World Forge'
Blender: 248
Group: 'Wizards'
Tooltip: 'World Forge Tool.'
"""
#############################################################
#                                                           #
# Blender World Forge Tool                                  #
#                                                           #
# (C) June 2003 Stefano <S68> Selleri                       #
# Originally Released under the Blender Artistic Licence (BAL)
# See www.blender.org                                       #
# http://www.selleri.org/Blender/scripts/text.html          #
#############################################################
# History                                                   #
# V: 0.0.0 - 08-06-03 - The script starts to take shape, an #
#                       history is now deserved :)          #
#    0.0.1 - 10-06-03 - I've found CGkit :)                 #
#    0.0.2 - 14-06-03 - Integration of the former 'Warp'    #
#                       script, introduction of PostProc    #
#    0.0.3 - 15-06-03 - Let's try CRATERS                   #
#    0.0.4 - 29-06-03 - Major Interface rearrangement       #
#    0.0.5 - 06-07-03 - Tan and Atan filters dropped in     #
#                       favour of HStep and VStep (more     #
#                       robust)                             #
#    0.0.6 - 09-07-03 - Craters works on sphere too, Added  #
#                       peaks, ready for a new release      #
#    0.0.7 - 20-10-03 - Added Load and Save functions       #
#                       Got Rid of some Filter              #
#                       inconsistencies                     #
#    0.0.8 - 25-10-03 - Sphere results are crap.            #
#                       Implementing other sphere mapping   #
#                       and Offsets                         #
#                       This actually required a complete   #
#                       rewrite of the Terraform Engine     #
#                       Bounding noise average to 0         #
#    0.0.9 - 27-10-03 - Brand New XML file save/load        #
#    0.0.10- 10-01-04 - Transition to Blender 2.32 with,    #
#                       hopefully a built-in noise module!  #
#                       In the meantime, some additional    #
#                       mesh stuff :)                       #
#    0.0.11- 17-01-04 - Layers are turned to a PostPro      #
#                       feature.                            #
#                       Better progressbar handling too     #
#    0.0.12- 07-02-04 - Other PostPro layers!               #
#-----------------------------------------------------------#
#    0.1.0 - 05-06-04 - New Python API has Noise, so let's  #
#            04-07-04   Get rid of CGkit                    #
#                       Added Dialogs                       #
#                       General rewriting                   #
#            10-08-04   Some time for file IN/OUT           #
#############################################################
# ***** BEGIN GPL LICENSE BLOCK *****
#
# 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 *****
#############################################################
#############################################################
#############################################################
#############################################################
#### DECLARATIONS ###########################################
#############################################################
#############################################################
#############################################################
#############################################################

import Blender
from Blender import *
from math import *
import os
import string

#############################################################
# GLOBALS                                                   #
#############################################################
VERSION         ='0.1.0'
ErrorMessage    = ''
PBtitle         = ''

#############################################################
# EVENTS                                                    #
#############################################################
EVENTHASH = {
    'NOEVENT': 1,
    'REDRAW': 2,
    'EXIT': 3,
    'DO': 4,
    'SAVE': 5,
    'LOAD': 6,
    'DLG_OK' : 7
    }

#############################################################
# INTERFACE GLOBALS                                         #
#############################################################
CONTEXTHASH = {   
    'Noise'     : Draw.Create(1), 'NoiseEV'     : 11,
    'Filters'   : Draw.Create(0), 'FiltersEV'   : 12,
    'Landmarks' : Draw.Create(0), 'LandmarksEV' : 13,
    'PostPro'   : Draw.Create(0), 'PostProEV'   : 14,
    }
	
NOISEHASH = {
    'Map'      : Draw.Create(0),
    'Usize'    : Draw.Create(32),
    'Vsize'    : Draw.Create(64),
    'Radius'   : Draw.Create(10.0),
    'Theta0'   : Draw.Create(-10.0),
    'Theta1'   : Draw.Create(10.0),
    'Phi0'     : Draw.Create(-20.0),
    'Phi1'     : Draw.Create(20.0),
    'Type'     : Draw.Create(0),
    'Function' : Draw.Create(0),
    'Metric'   : Draw.Create(0),
    'Uoffset'  : Draw.Create(0.0),
    'Voffset'  : Draw.Create(0.0),
    'Woffset'  : Draw.Create(0.0),
    'UVsize'   : Draw.Create(1.0),
    'Zsize'    : Draw.Create(1.0),
    'H'        : Draw.Create(1.0),
    'Lacu'     : Draw.Create(2.0),
    'Octs'     : Draw.Create(2.0),
    'Ofst'     : Draw.Create(1.0),
    'Gain'     : Draw.Create(1.0),
    'Hard'     : Draw.Create(0),
    'Ampl'     : Draw.Create(0.5),
    'Freq'     : Draw.Create(2.0),
    'Exp'      : Draw.Create(2.5)
    }

FILTERSHASH = {
    'Invert'    : Draw.Create(0),
    'Exp'       : Draw.Create(0),
    'ExpPa'     : Draw.Create(1.0), 'ExpPb'     : Draw.Create(1.0), 'ExpPc'   : Draw.Create(1.0),
    'Poly'      : Draw.Create(0),
    'PolyPa'    : Draw.Create(1.0), 'PolyPb'    : Draw.Create(1.0), 'PolyPc'  : Draw.Create(0.0), 'PolyPd': Draw.Create(0.0),
    'StepH'     : Draw.Create(0),
    'StepHPx0'  : Draw.Create(0.0), 'StepHPy0'  : Draw.Create(0.0), 'StepHPw' : Draw.Create(1.0),
    'StepHPmm1' : Draw.Create(1.0), 'StepHPmp1' : Draw.Create(1.0), 'StepHPs' : Draw.Create(0.0),
    'StepH0'    : (0.,0.,0.,0.),    'StepH1'    : (0.,0.,0.,0.),
    'StepV'     : Draw.Create(0),
    'StepVPx0'  : Draw.Create(0.0), 'StepVPy0'  : Draw.Create(0.0), 'StepVPw' : Draw.Create(1.0),
    'StepVPmm1' : Draw.Create(1.0), 'StepVPmp1' : Draw.Create(1.0), 'StepVPs' : Draw.Create(0.0),
    'StepV0'    : (0.,0.),          'StepV1'    : (0.,0.)
    }

LANDMARKSHASH = {
    'Crater'     : Draw.Create(0),
    'Cseed'      : Draw.Create(0),
    'Cradius'    : Draw.Create(1.0), 'CradiusV'    : Draw.Create(1.0),
    'Cheight'    : Draw.Create(1.0), 'CheightV'    : Draw.Create(1.0),
    'Cdepth'     : Draw.Create(1.0), 'CdepthV'     : Draw.Create(1.0),
    'Csteep'     : Draw.Create(1.0), 'CsteepV'     : Draw.Create(1.0),
    'Peaks'      : Draw.Create(0),
    'Pseed'      : Draw.Create(0),
    'Pradius'    : Draw.Create(1.0), 'PradiusV'    : Draw.Create(1.0),
    'Pheight'    : Draw.Create(1.0), 'PheightV'    : Draw.Create(1.0),
    'Ptopsteep'  : Draw.Create(0.0), 'PtopsteepV'  : Draw.Create(0.0),
    'Pfootsteep' : Draw.Create(0.0), 'PfootsteepV' : Draw.Create(0.0)
    }

CRATERHASH = {
    'Cu' : list(),
    'Cv' : list(),
    'Cw' : list(),
    'Cr' : list(),
    'Ch' : list(),
    'Cd' : list(),
    'Cs' : list()
    }

PEAKHASH = {
    'Pu' : list(),
    'Pv' : list(),
    'Pw' : list(),
    'Pa' : list(),
    'Pb' : list(),
    'Pc' : list(),
    'Pd' : list(),
    'Pr' : list()
    }

POSTPROHASH1 = {
    'Zmin'   : [Draw.Create(-1.0),  Draw.Create(-1.0),  Draw.Create(-1.0),  Draw.Create(-1.0),  Draw.Create(-1.0),  Draw.Create(-1.0)],
    'Zmax'   : [Draw.Create(1.0),   Draw.Create(1.0),   Draw.Create(1.0),   Draw.Create(1.0),   Draw.Create(1.0),   Draw.Create(1.0)],
    'Smin'   : [Draw.Create(0.0),   Draw.Create(0.0),   Draw.Create(0.0),   Draw.Create(0.0),   Draw.Create(0.0),   Draw.Create(0.0)],
    'Smax'   : [Draw.Create(100.0), Draw.Create(100.0), Draw.Create(100.0), Draw.Create(100.0), Draw.Create(100.0), Draw.Create(100.0)],
    'DOEV'   : 100,
    'ZEV'    : 110,
    'SEV'    : 120
    }

POSTPROHASH2 = {
    'Zmin'   : [Draw.Create(-1.0),  Draw.Create(-1.0),  Draw.Create(-1.0),  Draw.Create(-1.0),  Draw.Create(-1.0),  Draw.Create(-1.0)],
    'Zmax'   : [Draw.Create(1.0),   Draw.Create(1.0),   Draw.Create(1.0),   Draw.Create(1.0),   Draw.Create(1.0),   Draw.Create(1.0)],
    'Smin'   : [Draw.Create(0.0),   Draw.Create(0.0),   Draw.Create(0.0),   Draw.Create(0.0),   Draw.Create(0.0),   Draw.Create(0.0)],
    'Smax'   : [Draw.Create(100.0), Draw.Create(100.0), Draw.Create(100.0), Draw.Create(100.0), Draw.Create(100.0), Draw.Create(100.0)],
    'Verts'  : [Draw.Create(4.0),   Draw.Create(4.0),   Draw.Create(4.0),   Draw.Create(4.0),   Draw.Create(4.0),   Draw.Create(4.0)],
    'DOEV'   : 130,
    'ZEV'    : 140,
    'SEV'    : 150
    }

#############################################################
# Tetrahedron Octahedron and Icosahedron data               #
#############################################################
VertsT = [[-0.5,+0.5,0.,0.],
          [-0.28867513459481,-0.28867513459481,0.577350269189635,0.],
          [-0.20412414523193,-0.20412414523193,-0.20412414523193,0.6123724356957]]
FacesT = [[0,0,1,2],
          [2,1,2,0],
	  [1,3,3,3]]

VertsO = [[0.,-0.5,0.5,0.5,-0.5,0.],
          [0.,-0.5,-0.5,0.5,0.5,0.],
          [-0.70710678118655,0.,0.,0.,0.,0.70710678118655]]
FacesO = [[0,0,0,0,2,3,4,1],
          [2,3,4,1,5,5,5,5],
          [1,2,3,4,1,2,3,4]]

VertsI = [[0.,-0.5,0.5,0.80901699437495,0.,-0.80901699437495,
           0.,0.80901699437495,0.5,-0.5,-0.80901699437495,0.],
          [0.,-0.68819096023559,-0.68819096023559,0.26286555605957,0.85065080835204,0.26286555605957,
           -0.85065080835204,-0.26286555605957,0.68819096023559,0.68819096023559,-0.26286555605957,0.],
          [-0.95105651629515,-0.42532540417602,-0.42532540417602,-0.42532540417602,-0.42532540417602,-0.42532540417602,
           0.42532540417602,0.42532540417602,0.42532540417602,0.42532540417602,0.42532540417602,0.95105651629515]]
FacesI = [[0,0,0,0,0,1,2,3,4, 5,2,3,4, 5, 1, 6, 7, 8, 9,10],
          [2,3,4,5,1,2,3,4,5, 1,7,8,9,10, 6, 7, 8, 9,10, 6],
          [1,2,3,4,5,6,7,8,9,10,6,7,8, 9,10,11,11,11,11,11]]

#############################################################
#############################################################
#############################################################
#############################################################
#### FILE ACCESS ############################################
#############################################################
#############################################################
#############################################################
#############################################################

#############################################################
# XML Parser                                                #
#############################################################
from xml.sax.handler import ContentHandler
import xml.sax
import sys

def safe_eval(str):
    try:
        return int(str)
    except:
        try:
            return float(str)
        except:
            return repr(str)
        
class BWFHandler(ContentHandler):
        
    def __init__(self):
        self.in_Map    = 0
        self.in_Invert = 0
        self.in_Exp    = 0
        self.in_Poly   = 0
        self.in_HStep  = 0
        self.in_VStep  = 0
        self.in_Craters= 0
        self.in_Peaks  = 0
        self.in_Layer  = 0
        self.SZmin      = [0, 0, 0, 0, 0, 0]
        self.SZmax      = [0, 0, 0, 0, 0, 0]
        self.SSmin      = [0, 0, 0, 0, 0, 0]
        self.SSmax      = [0, 0, 0, 0, 0, 0]
        self.ThisLayer = [0, 0, 0, 0, 0]
        self.VZmin      = [0, 0, 0, 0, 0, 0]
        self.VZmax      = [0, 0, 0, 0, 0, 0]
        self.VSmin      = [0, 0, 0, 0, 0, 0]
        self.VSmax      = [0, 0, 0, 0, 0, 0]
        self.Density    = [0, 0, 0, 0, 0, 0]

    def startDocument(self):
	print'--- Reading BWF XML file ---'

    def startElement(self, name, attrs):
        self.arg = ""
        if name=='BlenderWorld':
            for k in attrs.keys():
                if k=='version':
                    self.version  = str(attrs.getValue(k))
        if name=='Mapping':
            self.in_Map=1
        if name=='Dimensions':
            for k in attrs.keys():
                if k=='USize':
                    self.USize  = safe_eval(attrs.getValue(k))
                if k=='VSize':
                    self.VSize  = safe_eval(attrs.getValue(k))
                if k=='Radius':
                    self.Radius = safe_eval(attrs.getValue(k))
                if k=='ThMin':
                    self.ThMin  = safe_eval(attrs.getValue(k))
                if k=='ThMax':
                    self.ThMax  = safe_eval(attrs.getValue(k))
                if k=='PhMin':
                    self.PhMin  = safe_eval(attrs.getValue(k))
                if k=='PhMax':
                    self.PhMax  = safe_eval(attrs.getValue(k))
        if name=='Noise':
            for k in attrs.keys():
                if k=='Type':
                    self.Type     = safe_eval(attrs.getValue(k))
                if k=='XOffset':
                    self.XOffset  = safe_eval(attrs.getValue(k))
                if k=='YOffset':
                    self.YOffset  = safe_eval(attrs.getValue(k))
                if k=='ZOffset':
                    self.ZOffset  = safe_eval(attrs.getValue(k))
                if k=='NoiseInputScale':
                    self.NoiseInputScale  = safe_eval(attrs.getValue(k))
                if k=='AltitudeScale':
                    self.AltitudeScale    = safe_eval(attrs.getValue(k))
                if k=='Function':
                    self.Function  = safe_eval(attrs.getValue(k))
                if k=='Metric':
                    self.Metric    = safe_eval(attrs.getValue(k))
                if k=='H':
                    self.H         = safe_eval(attrs.getValue(k))
                if k=='Lacunarity':
                    self.Lacunarity= safe_eval(attrs.getValue(k))
                if k=='Octaves':
                    self.Octaves   = safe_eval(attrs.getValue(k))
                if k=='Offset':
                    self.Offset    = safe_eval(attrs.getValue(k))
                if k=='Gain':
                    self.Gain      = safe_eval(attrs.getValue(k))
                if k=='Type':
                    self.Type      = safe_eval(attrs.getValue(k))
                if k=='Hard':
                    self.Hard      = safe_eval(attrs.getValue(k))
                if k=='Amplitude':
                    self.Amplitude = safe_eval(attrs.getValue(k))
                if k=='Frequency':
                    self.Frequency = safe_eval(attrs.getValue(k))
                if k=='Exp':
                    self.NExp      = safe_eval(attrs.getValue(k))
        if name=='Invert':
            self.in_Invert=1
        if name=='Exp':
            self.in_Exp=1
            for k in attrs.keys():
                if k=='a':
                    self.Expa = safe_eval(attrs.getValue(k))
                if k=='b':
                    self.Expb = safe_eval(attrs.getValue(k))
                if k=='c':
                    self.Expc = safe_eval(attrs.getValue(k))
        if name=='Poly':
            self.in_Poly=1
            for k in attrs.keys():
                if k=='a':
                    self.Polya = safe_eval(attrs.getValue(k))
                if k=='b':
                    self.Polyb = safe_eval(attrs.getValue(k))
                if k=='c':
                    self.Polyc = safe_eval(attrs.getValue(k))
                if k=='d':
                    self.Polyd = safe_eval(attrs.getValue(k))
        if name=='HStep':
            self.in_HStep=1
            for k in attrs.keys():
                if k=='Px0':
                    self.HStepPx0 = safe_eval(attrs.getValue(k))
                if k=='Py0':
                    self.HStepPy0 = safe_eval(attrs.getValue(k))
                if k=='Pw':
                    self.HStepPw = safe_eval(attrs.getValue(k))
                if k=='Pmm1':
                    self.HStepPmm1 = safe_eval(attrs.getValue(k))
                if k=='Pmp1':
                    self.HStepPmp1 = safe_eval(attrs.getValue(k))
                if k=='Ps':
                    self.HStepPs = safe_eval(attrs.getValue(k))
        if name=='VStep':
            self.in_VStep=1
            for k in attrs.keys():
                if k=='Px0':
                    self.VStepPx0 = safe_eval(attrs.getValue(k))
                if k=='Py0':
                    self.VStepPy0 = safe_eval(attrs.getValue(k))
                if k=='Pw':
                    self.VStepPw = safe_eval(attrs.getValue(k))
                if k=='Pmm1':
                    self.VStepPmm1 = safe_eval(attrs.getValue(k))
                if k=='Pmp1':
                    self.VStepPmp1 = safe_eval(attrs.getValue(k))
                if k=='Ps':
                    self.VStepPs = safe_eval(attrs.getValue(k))
        if name=='Craters':
            self.in_Craters=1
            for k in attrs.keys():
                if k=='Seed':
                    self.CraterSeed = safe_eval(attrs.getValue(k))
                if k=='Radius':
                    self.CraterRadius = safe_eval(attrs.getValue(k))
                if k=='RadiusV':
                    self.CraterRadiusV = safe_eval(attrs.getValue(k))
                if k=='Height':
                    self.CraterHeight = safe_eval(attrs.getValue(k))
                if k=='HeightV':
                    self.CraterHeightV = safe_eval(attrs.getValue(k))
                if k=='Depth':
                    self.CraterDepth = safe_eval(attrs.getValue(k))
                if k=='DepthV':
                    self.CraterDepthV = safe_eval(attrs.getValue(k))
                if k=='Steep':
                    self.CraterSteep = safe_eval(attrs.getValue(k))
                if k=='SteepV':
                    self.CraterSteepV = safe_eval(attrs.getValue(k))
        if name=='Peaks':
            self.in_Peaks=1
            for k in attrs.keys():
                if k=='Seed':
                    self.PeakSeed = safe_eval(attrs.getValue(k))
                if k=='Radius':
                    self.PeakRadius = safe_eval(attrs.getValue(k))
                if k=='RadiusV':
                    self.PeakRadiusV = safe_eval(attrs.getValue(k))
                if k=='Height':
                    self.PeakHeight = safe_eval(attrs.getValue(k))
                if k=='HeightV':
                    self.PeakHeightV = safe_eval(attrs.getValue(k))
                if k=='TopSteep':
                    self.PeakTopSteep = safe_eval(attrs.getValue(k))
                if k=='TopSteepV':
                    self.PeakTopSteepV = safe_eval(attrs.getValue(k))
                if k=='FootSteep':
                    self.PeakFootSteep = safe_eval(attrs.getValue(k))
                if k=='FootSteepV':
                    self.PeakFootSteepV = safe_eval(attrs.getValue(k))
        if name=='SubLayer':
            self.in_SubLayer=1
            for k in attrs.keys():
                if k=='Zmin':
                    self.ThisLayer[0] = safe_eval(attrs.getValue(k))
                if k=='Zmax':
                    self.ThisLayer[1] = safe_eval(attrs.getValue(k))
                if k=='Smin':
                    self.ThisLayer[2] = safe_eval(attrs.getValue(k))
                if k=='Smax':
                    self.ThisLayer[3] = safe_eval(attrs.getValue(k))
        if name=='VertexCloud':
            self.in_VertexCloud=1
            for k in attrs.keys():
                if k=='Zmin':
                    self.ThisLayer[0] = safe_eval(attrs.getValue(k))
                if k=='Zmax':
                    self.ThisLayer[1] = safe_eval(attrs.getValue(k))
                if k=='Smin':
                    self.ThisLayer[2] = safe_eval(attrs.getValue(k))
                if k=='Smax':
                    self.ThisLayer[3] = safe_eval(attrs.getValue(k))
                if k=='Density':
                    self.ThisLayer[4] = safe_eval(attrs.getValue(k))
            
    def endElement(self, name):
        if name=='Mapping':
            self.Mapping = safe_eval(self.arg)
            self.in_Map=0
        if name=='Invert':    
            self.Invert = safe_eval(self.arg)
            self.in_Invert=0
        if name=='Exp':    
            self.Exp = safe_eval(self.arg)
            self.in_Exp=0
        if name=='Poly':    
            self.Poly = safe_eval(self.arg)
            self.in_Poly=0
        if name=='HStep':    
            self.HStep = safe_eval(self.arg)
            self.in_HStep=0
        if name=='VStep':    
            self.VStep = safe_eval(self.arg)
            self.in_VStep=0
        if name=='Craters':    
            self.Craters = safe_eval(self.arg)
            self.in_Craters=0
        if name=='Peaks':    
            self.Peaks = safe_eval(self.arg)
            self.in_Peaks=0
        if name=='SubLayer':
            i = safe_eval(self.arg)
            if (i>=0 and i<6):
                self.SZmin[i]   = self.ThisLayer[0]
                self.SZmax[i]   = self.ThisLayer[1]
                self.SSmin[i]   = self.ThisLayer[2]
                self.SSmax[i]   = self.ThisLayer[3]
            self.in_SubLayer=0
        if name=='VertexCloud':
            i = safe_eval(self.arg)
            if (i>=0 and i<6):
                self.VZmin[i]   = self.ThisLayer[0]
                self.VZmax[i]   = self.ThisLayer[1]
                self.VSmin[i]   = self.ThisLayer[2]
                self.VSmax[i]   = self.ThisLayer[3]
                self.Density[i] = self.ThisLayer[4]
            self.in_VertexCloud=0

    def characters(self, ch):
        self.arg = self.arg + ch

#############################################################
# WRITE A LINE                                              #
#############################################################
def writeln(f,x):
	try:
		if (type(x).__name__ == 'string'):
			nn = string.find(x, '\n')
			if (nn > 0):
				x = x[:nn] + x[nn + 1:]
		f.write(str(x))
		f.write('\n')
	except:
		pass

#############################################################
# WRITE A FILE                                              #
#############################################################
def BWFSave(filename):
    global CONTEXTHASH
    global NOISEHASH,FILTERSHASH,LANDMARKSHASH,CRATERHASH,PEAKHASH
    global POSTPROHASH1,POSTPROHASH2
    

    splitted = os.path.splitext(filename)
    if(splitted[1]==''):
	filename = string.join((filename,'bwf'),'.')

    print filename
    if os.path.exists(filename):
	print "We will overwrite without warning!";

    FD = open(filename,"w")

    writeln(FD,"<BlenderWorld version=\""+VERSION+"\">");
    writeln(FD,"<Mapping>"+str(NOISEHASH['Map'].val)+"</Mapping>");
    
    writeln(FD,"<Dimensions USize=\""+str(NOISEHASH['Usize'].val)+"\" VSize=\""+str(NOISEHASH['Vsize'].val)+"\" Radius=\""+str(NOISEHASH['Radius'].val)+"\"");
    writeln(FD,"            ThMin=\""+str(NOISEHASH['Theta0'].val)+"\" ThMax=\""+str(NOISEHASH['Theta1'].val)+"\" PhMin=\""+str(NOISEHASH['Phi0'].val)+"\" PhMax=\""+str(NOISEHASH['Phi1'].val)+"\">")
    writeln(FD,"</Dimensions>");

    writeln(FD,"<Noise Type=\""+str(NOISEHASH['Type'].val)+"\" XOffset=\""+str(NOISEHASH['Uoffset'].val)+"\" YOffset=\""+str(NOISEHASH['Voffset'].val)+"\" ZOffset=\""+str(NOISEHASH['Woffset'].val)+"\"");
    writeln(FD,"       NoiseInputScale=\""+str(NOISEHASH['UVsize'].val)+"\" AltitudeScale=\""+str(NOISEHASH['Zsize'].val)+"\"")
    writeln(FD,"       Function=\""+str(NOISEHASH['Function'].val)+"\" Metric=\""+str(NOISEHASH['Metric'].val)+"\" H=\""+str(NOISEHASH['H'].val)+"\"")
    writeln(FD,"       Lacunarity=\""+str(NOISEHASH['Lacu'].val)+"\" Octaves=\""+str(NOISEHASH['Octs'].val)+"\" Offset=\""+str(NOISEHASH['Ofst'].val)+"\"")
    writeln(FD,"       Gain=\""+str(NOISEHASH['Gain'].val)+"\" Hard=\""+str(NOISEHASH['Hard'].val)+"\" Amplitude=\""+str(NOISEHASH['Ampl'].val)+"\" Frequency=\""+str(NOISEHASH['Freq'].val)+"\" Exp=\""+str(NOISEHASH['Exp'].val)+"\">")
    writeln(FD,"</Noise>");

    writeln(FD,"<Invert>")
    writeln(FD,FILTERSHASH['Invert'].val)
    writeln(FD,"</Invert>")
	
    writeln(FD,"<Exp a=\""+str(FILTERSHASH['ExpPa'].val)+"\" b=\""+str(FILTERSHASH['ExpPb'].val)+"\" c=\""+str(FILTERSHASH['ExpPc'].val)+"\">")
    writeln(FD,FILTERSHASH['Exp'].val)
    writeln(FD,"</Exp>")

    writeln(FD,"<Poly a=\""+str(FILTERSHASH['PolyPa'].val)+"\" b=\""+str(FILTERSHASH['PolyPb'].val)+"\"")
    writeln(FD,"      c=\""+str(FILTERSHASH['PolyPc'].val)+"\" d=\""+str(FILTERSHASH['PolyPc'].val)+"\">")
    writeln(FD,FILTERSHASH['Poly'].val)
    writeln(FD,"</Poly>")

    writeln(FD,"<HStep Px0=\""+str(FILTERSHASH['StepHPx0'].val)+"\" Py0=\""+str(FILTERSHASH['StepHPy0'].val)+"\"")
    writeln(FD,"       Pw=\""+str(FILTERSHASH['StepHPw'].val)+"\" Ps=\""+str(FILTERSHASH['StepHPs'].val)+"\"")
    writeln(FD,"       Pmm1=\""+str(FILTERSHASH['StepHPmm1'].val)+"\" Pmp1=\""+str(FILTERSHASH['StepHPmp1'].val)+"\">")
    writeln(FD,FILTERSHASH['StepH'].val)
    writeln(FD,"</HStep>")

    writeln(FD,"<VStep Px0=\""+str(FILTERSHASH['StepVPx0'].val)+"\" Py0=\""+str(FILTERSHASH['StepVPy0'].val)+"\"")
    writeln(FD,"       Pw=\""+str(FILTERSHASH['StepVPw'].val)+"\" Ps=\""+str(FILTERSHASH['StepVPs'].val)+"\"")
    writeln(FD,"       Pmm1=\""+str(FILTERSHASH['StepVPmm1'].val)+"\" Pmp1=\""+str(FILTERSHASH['StepVPmp1'].val)+"\">")
    writeln(FD,FILTERSHASH['StepV'].val)
    writeln(FD,"</VStep>")


    writeln(FD,"<Craters Seed=\""+str(LANDMARKSHASH['Cseed'].val)+"\"")
    writeln(FD,"         Radius=\""+str(LANDMARKSHASH['Cradius'].val)+"\" RadiusV=\""+str(LANDMARKSHASH['CradiusV'].val)+"\"")
    writeln(FD,"         Height=\""+str(LANDMARKSHASH['Cheight'].val)+"\" HeightV=\""+str(LANDMARKSHASH['CheightV'].val)+"\"")
    writeln(FD,"         Depth=\""+str(LANDMARKSHASH['Cdepth'].val)+"\" DepthV=\""+str(LANDMARKSHASH['CdepthV'].val)+"\"")
    writeln(FD,"         Steep=\""+str(LANDMARKSHASH['Csteep'].val)+"\" SteepV=\""+str(LANDMARKSHASH['CsteepV'].val)+"\">")
    writeln(FD,LANDMARKSHASH['Crater'].val)
    writeln(FD,"</Craters>")
	
    writeln(FD,"<Peaks Seed=\""+str(LANDMARKSHASH['Pseed'].val)+"\"")
    writeln(FD,"       Radius=\""+str(LANDMARKSHASH['Pradius'].val)+"\" RadiusV=\""+str(LANDMARKSHASH['PradiusV'].val)+"\"")
    writeln(FD,"       Height=\""+str(LANDMARKSHASH['Pheight'].val)+"\" HeightV=\""+str(LANDMARKSHASH['PheightV'].val)+"\"")
    writeln(FD,"       TopSteep=\""+str(LANDMARKSHASH['Ptopsteep'].val)+"\" TopSteepV=\""+str(LANDMARKSHASH['PtopsteepV'].val)+"\"")
    writeln(FD,"       FootSteep=\""+str(LANDMARKSHASH['Pfootsteep'].val)+"\" FootSteepV=\""+str(LANDMARKSHASH['PfootsteepV'].val)+"\">")
    writeln(FD,LANDMARKSHASH['Peaks'].val)
    writeln(FD,"</Peaks>")

    for i in range(6):
        writeln(FD,"<SubLayer")
        writeln(FD,"       Zmin=\""+str(POSTPROHASH1['Zmin'][i].val)+"\" Zmax=\""+str(POSTPROHASH1['Zmax'][i].val)+"\"")
        writeln(FD,"       Smin=\""+str(POSTPROHASH1['Smin'][i].val)+"\" Smax=\""+str(POSTPROHASH1['Smax'][i].val)+"\">")
        writeln(FD,i)
        writeln(FD,"</SubLayer>")
            
    for i in range(6):
        writeln(FD,"<VertexCloud")
        writeln(FD,"       Zmin=\""+str(POSTPROHASH2['Zmin'][i].val)+"\" Zmax=\""+str(POSTPROHASH2['Zmax'][i].val)+"\"")
        writeln(FD,"       Smin=\""+str(POSTPROHASH2['Smin'][i].val)+"\" Smax=\""+str(POSTPROHASH2['Smax'][i].val)+"\"")
        writeln(FD,"       Density=\""+str(POSTPROHASH2['Verts'][i].val)+"\">")
        writeln(FD,i)
        writeln(FD,"</VertexCloud>")

    writeln(FD,"</BlenderWorld>");	

    FD.close()
	
#############################################################
# LOAD A FILE                                               #
#############################################################
def BWFLoad(filename):
    global CONTEXTHASH
    global NOISEHASH,FILTERSHASH,LANDMARKSHASH,CRATERHASH,PEAKHASH
    global POSTPROHASH1,POSTPROHASH2

    if not os.path.exists(filename):
	print "Well... where is the file?";
    else:
	parser = xml.sax.make_parser()
	handler = BWFHandler()
	parser.setContentHandler(handler)
	parser.parse(filename)

	### Version Check
	if (handler.version != VERSION):
	    print "*** WARNING *** This id BWF v."+VERSION+" while the "+filename+" file looks like being saved by BWF v."+handler.version
			
	### Mapping TAG
	try:
	    NOISEHASH['Map'].val=handler.Mapping
	except:
            NOISEHASH['Map'].val=0

	### Dimensions TAG	
	try:
            NOISEHASH['Usize'].val=handler.USize
	except:
            NOISEHASH['Usize'].val=64
	try:
            NOISEHASH['Vsize'].val=handler.VSize
	except:
            NOISEHASH['Vsize'].val=128
	try:
            NOISEHASH['Radius'].val=handler.Radius
	except:
            NOISEHASH['Radius'].val=10.0
	try:
            NOISEHASH['Theta0'].val=handler.ThMin
	except:
            NOISEHASH['Theta0'].val=-10.0
	try:
            NOISEHASH['Theta1'].val=handler.ThMax
	except:
            NOISEHASH['Theta1'].val=10.0
	try:
            NOISEHASH['Phi0'].val=handler.PhMin
	except:
            NOISEHASH['Phi0'].val=-20.0
	try:
            NOISEHASH['Phi1'].val=handler.PhMax
	except:
            NOISEHASH['Phi1'].val=20.0

	### Noise TAG	
	try:
	    NOISEHASH['Type'].val=handler.Type
	except:
	    NOISEHASH['Type'].val=3
	try:
	    NOISEHASH['Function'].val=handler.Function
	except:
	    NOISEHASH['Function'].val=0
	try:
	    NOISEHASH['Metric'].val=handler.Metric
	except:
	    NOISEHASH['Metric'].val=0
	try:
	    NOISEHASH['Uoffset'].val=handler.XOffset
	except:
	    NOISEHASH['Uoffset'].val=0.
	try:
	    NOISEHASH['Voffset'].val=handler.YOffset
	except:
	    NOISEHASH['Voffset'].val=0.
	try:
	    NOISEHASH['Woffset'].val=handler.ZOffset
	except:
	    NOISEHASH['Woffset'].val=0.
	try:
	    NOISEHASH['UVsize'].val=handler.NoiseInputScale
	except:
	    NOISEHASH['UVsize'].val=1.
	try:
	    NOISEHASH['Zsize'].val=handler.AltitudeScale
	except:
	    NOISEHASH['Zsize'].val=1.
	try:
	    NOISEHASH['H'].val=handler.H
	except:
	    NOISEHASH['H'].val=1.
	try:
	    NOISEHASH['Lacu'].val=handler.Lacunarity
	except:
	    NOISEHASH['Lacu'].val=2.
	try:
	    NOISEHASH['Octs'].val=handler.Octaves
	except:
	    NOISEHASH['Octs'].val=2.
	try:
	    NOISEHASH['Ofst'].val=handler.Offset
	except:
	    NOISEHASH['Ofst'].val=1.
	try:
	    NOISEHASH['Gain'].val=handler.Gain
	except:
	    NOISEHASH['Gain'].val=1.
	try:
	    NOISEHASH['Hard'].val=handler.Hard
	except:
	    NOISEHASH['Hard'].val=0
	try:
	    NOISEHASH['Ampl'].val=handler.Amplitude
	except:
	    NOISEHASH['Ampl'].val=0.5
	try:
	    NOISEHASH['Freq'].val=handler.Frequency
	except:
	    NOISEHASH['Freq'].val=2.
	try:
	    NOISEHASH['Exp'].val=handler.NExp
	except:
	    NOISEHASH['Exp'].val=2.5

	### Invert TAG
	try:
	    FILTERSHASH['Invert'].val=handler.Invert
	except:
	    FILTERSHASH['Invert'].val=0
			
	### Exp TAG
	try:
	    FILTERSHASH['Exp'].val=handler.Exp
	except:
	    FILTERSHASH['Exp'].val=0
	try:
	    FILTERSHASH['ExpPa'].val=handler.Expa
	except:
	    FILTERSHASH['ExpPa'].val=1.
        try:
	    FILTERSHASH['ExpPb'].val=handler.Expb
	except:
	    FILTERSHASH['ExpPb'].val=1.
	try:
	    FILTERSHASH['ExpPc'].val=handler.Expc
	except:
	    FILTERSHASH['ExpPc'].val=1.

	### Poly TAG
	try:
	    FILTERSHASH['Poly'].val=handler.Poly
	except:
            FILTERSHASH['Poly'].val=0
	try:
	    FILTERSHASH['PolyPa'].val=handler.Polya
	except:
	    FILTERSHASH['PolyPa'].val=1.
	try:
	    FILTERSHASH['PolyPb'].val=handler.Polyb
	except:
	    FILTERSHASH['PolyPb'].val=1.
	try:
	    FILTERSHASH['PolyPc'].val=handler.Polyc
	except:
	    FILTERSHASH['PolyPc'].val=0.
	try:
	    FILTERSHASH['PolyPd'].val=handler.Polyd
	except:
	    FILTERSHASH['PolyPd'].val=0.

	### HStep TAG
	try:
	    FILTERSHASH['StepH'].val=handler.HStep
	except:
	    FILTERSHASH['StepH'].val=0
	try:
	    FILTERSHASH['StepHPx0'].val=handler.HStepPx0
	except:
	    FILTERSHASH['StepHPx0'].val=0.
	try:
	    FILTERSHASH['StepHPy0'].val=handler.HStepPy0
	except:
	    FILTERSHASH['StepHPy0'].val=0.
	try:
	    FILTERSHASH['StepHPw'].val=handler.HStepPw
	except:
	    FILTERSHASH['StepHPw'].val=1.
	try:
	    FILTERSHASH['StepHPs'].val=handler.HStepPs
	except:
	    FILTERSHASH['StepHPs'].val=1.
	try:
	    FILTERSHASH['StepHPmm1'].val=handler.HStepPmm1
	except:
	    FILTERSHASH['StepHPmm1'].val=1.
	try:
	    FILTERSHASH['StepHPmp1'].val=handler.HStepPmp1
	except:
	    FILTERSHASH['StepHPmp1'].val=1.

	### VStep TAG
	try:
	    FILTERSHASH['StepV'].val=handler.VStep
	except:
	    FILTERSHASH['StepV'].val=0
	try:
	    FILTERSHASH['StepVPx0'].val=handler.VStepPx0
	except:
	    FILTERSHASH['StepVPx0'].val=0.
	try:
	    FILTERSHASH['StepVPy0'].val=handler.VStepPy0
	except:
	    FILTERSHASH['StepVPy0'].val=0.
	try:
	    FILTERSHASH['StepVPw'].val=handler.VStepPw
	except:
	    FILTERSHASH['StepVPw'].val=1.
	try:
	    FILTERSHASH['StepVPs'].val=handler.VStepPs
	except:
	    FILTERSHASH['StepVPs'].val=1.
	try:
	    FILTERSHASH['StepVPmm1'].val=handler.VStepPmm1
	except:
	    FILTERSHASH['StepVPmm1'].val=1.
	try:
	    FILTERSHASH['StepVPmp1'].val=handler.VStepPmp1
	except:
	    FILTERSHASH['StepVPmp1'].val=1.

	### Crater TAG
	try:
	    LANDMARKSHASH['Crater'].val=handler.Craters
	except:
	    LANDMARKSHASH['Crater'].val=0
	try:
	    LANDMARKSHASH['Cseed'].val=handler.CraterSeed
	except:
	    LANDMARKSHASH['Cseed'].val=0
	try:
	    LANDMARKSHASH['Cradius'].val=handler.CraterRadius
	except:
	    LANDMARKSHASH['Cradius'].val=1.
	try:
	    LANDMARKSHASH['CradiusV'].val=handler.CraterRadiusV
	except:
	    LANDMARKSHASH['CradiusV'].val=1.
	try:
	    LANDMARKSHASH['Cheight'].val=handler.CraterHeight
	except:
	    LANDMARKSHASH['Cheight'].val=1.
	try:
	    LANDMARKSHASH['CheightV'].val=handler.CraterHeightV
	except:
	    LANDMARKSHASH['CheightV'].val=1.
	try:
	    LANDMARKSHASH['Cdepth'].val=handler.CraterDepth
	except:
	    LANDMARKSHASH['Cdepth'].val=1.
	try:
	    LANDMARKSHASH['CdepthV'].val=handler.CraterDepthV
	except:
	    LANDMARKSHASH['CdepthV'].val=1.
	try:
	    LANDMARKSHASH['Csteep'].val=handler.CraterSteep
	except:
	    LANDMARKSHASH['Csteep'].val=1.
	try:
	    LANDMARKSHASH['CsteepV'].val=handler.CraterSteepV
	except:
	    LANDMARKSHASH['CsteepV'].val=1.


	### Peak TAG
        try:
	    LANDMARKSHASH['Peaks'].val=handler.Peaks
	except:
	    LANDMARKSHASH['Peaks'].val=0
	try:
	    LANDMARKSHASH['Pseed'].val=handler.PeakSeed
	except:
	    LANDMARKSHASH['Pseed'].val=0
	try:
	    LANDMARKSHASH['Pradius'].val=handler.PeakRadius
	except:
	    LANDMARKSHASH['Pradius'].val=1.
	try:
	    LANDMARKSHASH['PradiusV'].val=handler.PeakRadiusV
	except:
	    LANDMARKSHASH['PradiusV'].val=1.
	try:
	    LANDMARKSHASH['Pheight'].val=handler.PeakHeight
	except:
	    LANDMARKSHASH['Pheight'].val=1.
	try:
	    LANDMARKSHASH['PheightV'].val=handler.PeakHeightV
	except:
	    LANDMARKSHASH['PheightV'].val=1.
	try:
	    LANDMARKSHASH['Ptopsteep'].val=handler.PeakTopSteep
	except:
	    LANDMARKSHASH['Ptopsteep'].val=0.
	try:
	    LANDMARKSHASH['PtopsteepV'].val=handler.PeakTopSteepV
	except:
	    LANDMARKSHASH['PtopsteepV'].val=0.
	try:
	    LANDMARKSHASH['Pfootsteep'].val=handler.PeakFootSteep
	except:
	    LANDMARKSHASH['Pfootsteep'].val=0.
	try:
	    LANDMARKSHASH['PfootsteepV'].val=handler.PeakFootSteepV
	except:
	    LANDMARKSHASH['PfootsteepV'].val=0.

	### Layer TAGs
	for i in range(6):	
            try:
                POSTPROHASH1['Zmin'][i].val = handler.SZmin[i]
            except:
                POSTPROHASH1['Zmin'][i].val = -1.0
            try:
                POSTPROHASH1['Zmax'][i].val = handler.SZmax[i]
            except:
                POSTPROHASH1['Zmax'][i].val = 1.0
            try:
                POSTPROHASH1['Smin'][i].val = handler.SSmin[i]
            except:
                POSTPROHASH1['Smin'][i].val = 0.0
            try:
                POSTPROHASH1['Smax'][i].val = handler.SSmax[i]
            except:
                POSTPROHASH1['Smax'][i].val = 100.0

	### Layer 2 TAGs
	for i in range(6):	
            try:
                POSTPROHASH2['Zmin'][i].val = handler.VZmin[i]
            except:
                POSTPROHASH2['Zmin'][i].val = -1.0
            try:
                POSTPROHASH2['Zmax'][i].val = handler.VZmax[i]
            except:
                POSTPROHASH2['Zmax'][i].val = 1.0
            try:
                POSTPROHASH2['Smin'][i].val = handler.VSmin[i]
            except:
                POSTPROHASH2['Smin'][i].val = 0.0
            try:
                POSTPROHASH2['Smax'][i].val = handler.VSmax[i]
            except:
                POSTPROHASH2['Smax'][i].val = 100.0
            try:
                POSTPROHASH2['Verts'][i].val = handler.Density[i]
            except:
                POSTPROHASH2['Verts'][i].val = 4.0


	Draw.Redraw()
		

#############################################################
#############################################################
#############################################################
#############################################################
#### FILTERING ##############################################
#############################################################
#############################################################
#############################################################
#############################################################

#############################################################
# Pre-calculation of H and V step bevels                    #
#############################################################
def PreCalculateFilters():
    global FILTERSHASH
    print 'PCF'
    if (FILTERSHASH['StepHPs'].val>0):
	FILTERSHASH['StepH0'] = InterPoly(
                    FILTERSHASH['StepHPx0'].val-FILTERSHASH['StepHPw'].val-FILTERSHASH['StepHPs'].val,
		    FILTERSHASH['StepHPy0'].val-FILTERSHASH['StepHPmm1'].val*FILTERSHASH['StepHPs'].val,
		    FILTERSHASH['StepHPmm1'].val,
		    FILTERSHASH['StepHPx0'].val-FILTERSHASH['StepHPw'].val+FILTERSHASH['StepHPs'].val,
                    FILTERSHASH['StepHPy0'].val,
                    0.0)

	FILTERSHASH['StepH1'] = InterPoly(
                    FILTERSHASH['StepHPx0'].val+FILTERSHASH['StepHPw'].val-FILTERSHASH['StepHPs'].val,
		    FILTERSHASH['StepHPy0'].val,
		    0.0,
		    FILTERSHASH['StepHPx0'].val+FILTERSHASH['StepHPw'].val+FILTERSHASH['StepHPs'].val,
                    FILTERSHASH['StepHPy0'].val+FILTERSHASH['StepHPmp1'].val*FILTERSHASH['StepHPs'].val,
                    FILTERSHASH['StepHPmp1'].val)
    else:
	FILTERSHASH['StepH0'] = (FILTERSHASH['StepHPy0'].val,0.,0.,0.)
	FILTERSHASH['StepH1'] = (FILTERSHASH['StepHPy0'].val,0.,0.,0.)

    if (FILTERSHASH['StepVPs'].val>0):
	FILTERSHASH['StepV0'] = InterElly(FILTERSHASH['StepVPmm1'].val,FILTERSHASH['StepVPs'].val)
	FILTERSHASH['StepV1'] = InterElly(FILTERSHASH['StepVPmp1'].val,FILTERSHASH['StepVPs'].val)
    else:
	FILTERSHASH['StepV0'] = (0.,0.)
	FILTERSHASH['StepV1'] = (0.,0.)

#############################################################
# Polynomial interpolation                                  #
#############################################################
def InterPoly(x0,y0,m0,x1,y1,m1):

    dena = (x0**3-3*x1*x0*x0+3*x0*x1*x1-x1**3)

    if (dena==0):
	print "Major fault, this should NEVER have happened"
	print "bye bye";
	exit;

    a = (y1*x0**3-x1*x0**3*m1+x1**2*x0**2*m1-3*y1*x0**2*x1-x0**2*m0*x1**2+x0*m0*x1**3+3*y0*x0*x1**2-y0*x1**3)/dena;
    b = -(-m1*x0**3-m1*x1*x0**2-2*m0*x1*x0**2-6*x0*y1*x1+m0*x0*x1**2+2*m1*x0*x1**2+6*x0*y0*x1+m0*x1**3)/dena;
    c = (-x0**2*m0-2*x0**2*m1+3*y0*x0-3*y1*x0+x1*x0*m1-x0*m0*x1+2*x1**2*m0+3*y0*x1-3*y1*x1+x1**2*m1)/dena;
    d = -(-x0*m1-x0*m0-2*y1+x1*m1+2*y0+x1*m0)/dena;

    return(a,b,c,d)

#############################################################
# H Step Function                                           #
#############################################################
def hstep(x):

    global FILTERSHASH

    if(FILTERSHASH['StepHPs'].val>FILTERSHASH['StepHPw'].val):
	FILTERSHASH['StepHPs'].val=FILTERSHASH['StepHPw'].val

    if (x<=FILTERSHASH['StepHPx0'].val-FILTERSHASH['StepHPw'].val-FILTERSHASH['StepHPs'].val):
	y = FILTERSHASH['StepHPy0'].val + FILTERSHASH['StepHPmm1'].val*(x-FILTERSHASH['StepHPx0'].val+FILTERSHASH['StepHPw'].val)
    elif (x<=FILTERSHASH['StepHPx0'].val-FILTERSHASH['StepHPw'].val+FILTERSHASH['StepHPs'].val):
	y=FILTERSHASH['StepH0'][0] + FILTERSHASH['StepH0'][1]*x + FILTERSHASH['StepH0'][2]*x*x + FILTERSHASH['StepH0'][3]*x*x*x
    elif (x<=FILTERSHASH['StepHPx0'].val+FILTERSHASH['StepHPw'].val-FILTERSHASH['StepHPs'].val):
	y = FILTERSHASH['StepHPy0'].val
    elif (x<=FILTERSHASH['StepHPx0'].val+FILTERSHASH['StepHPw'].val+FILTERSHASH['StepHPs'].val):
	y=FILTERSHASH['StepH1'][0] + FILTERSHASH['StepH1'][1]*x + FILTERSHASH['StepH1'][2]*x*x + FILTERSHASH['StepH1'][3]*x*x*x
    else:
	y = FILTERSHASH['StepHPy0'].val + FILTERSHASH['StepHPmp1'].val*(x-FILTERSHASH['StepHPx0'].val-FILTERSHASH['StepHPw'].val)

    return(y)

#############################################################
# Elliptical Interpolation                                  #
#############################################################
def InterElly(m,s):

    if (abs(m-1)<0.001):
	m=1.001
	
    a = s / (1-m)
    b = abs(m * a**2 * sqrt(abs((s-a)**2/a**2-1))/(s-a));

    return (a,b)

#############################################################
# V Step Function                                           #
#############################################################
def vstep(x):

    global FILTERSHASH

    if(FILTERSHASH['StepVPs'].val>FILTERSHASH['StepVPw'].val):
	FILTERSHASH['StepVPs'].val=FILTERSHASH['StepVPw'].val

    if (FILTERSHASH['StepVPs'].val<.00001):
	if (x<=FILTERSHASH['StepVPx0'].val):
            y = FILTERSHASH['StepVPy0'].val + FILTERSHASH['StepVPmm1'].val*(x-FILTERSHASH['StepVPx0'].val)-FILTERSHASH['StepVPw'].val
	else:
            y = FILTERSHASH['StepVPy0'].val + FILTERSHASH['StepVPmp1'].val*(x-FILTERSHASH['StepVPx0'].val)+FILTERSHASH['StepVPw'].val
    else:
        if (x<=FILTERSHASH['StepVPx0'].val-FILTERSHASH['StepVPs'].val):
            y = FILTERSHASH['StepVPy0'].val + FILTERSHASH['StepVPmm1'].val*(x-FILTERSHASH['StepVPx0'].val)-FILTERSHASH['StepVPw'].val
	elif (x<=FILTERSHASH['StepVPx0'].val):
            ax = 2*FILTERSHASH['StepVPx0'].val-x
            ay = FILTERSHASH['StepVPy0'].val+FILTERSHASH['StepVPw'].val-FILTERSHASH['StepVPs'].val+FILTERSHASH['StepV0'][1]*sqrt(abs((ax-FILTERSHASH['StepVPx0'].val-FILTERSHASH['StepV0'][0])**2/FILTERSHASH['StepV0'][0]**2-1))
            y = 2*FILTERSHASH['StepVPy0'].val-ay
	elif (x<=FILTERSHASH['StepVPx0'].val+FILTERSHASH['StepVPs'].val):
	    y = FILTERSHASH['StepVPy0'].val+FILTERSHASH['StepVPw'].val-FILTERSHASH['StepVPs'].val+FILTERSHASH['StepV1'][1]*sqrt(abs((x-FILTERSHASH['StepVPx0'].val-FILTERSHASH['StepV0'][0])**2/FILTERSHASH['StepV0'][0]**2-1))
	else:
            y = FILTERSHASH['StepVPy0'].val + FILTERSHASH['StepVPmp1'].val*(x-FILTERSHASH['StepVPx0'].val)+FILTERSHASH['StepVPw'].val

    return(y)

#############################################################
# Filtering Main                                            #
#############################################################
def Filter(z):
    global FILTERSHASH

    if (FILTERSHASH['Invert'].val==1):
	z = - z
    if (FILTERSHASH['Exp'].val==1):
	z = FILTERSHASH['ExpPa'].val*exp(FILTERSHASH['ExpPb'].val*z+FILTERSHASH['ExpPc'].val)
    if (FILTERSHASH['Poly'].val==1):
	z = FILTERSHASH['PolyPa'].val+FILTERSHASH['PolyPb'].val*z+FILTERSHASH['PolyPc'].val*z*z+FILTERSHASH['PolyPd'].val*z*z*z
    if (FILTERSHASH['StepH'].val==1):
	z = hstep(z)
    if (FILTERSHASH['StepV'].val==1):
	z = vstep(z)

    return(z)


#############################################################
#############################################################
#############################################################
#############################################################
#### LANDMARKS ##############################################
#############################################################
#############################################################
#############################################################
#############################################################

#############################################################
# A Noise Which is almost white yet reproducible            #
#############################################################
def HigVarNoise(n,s):
    y = 157*Noise.noise((3.14159276*(n+s),0.498265482,0.),Noise.NoiseTypes.STDPERLIN)
    y = y -int(y)
    return y

#############################################################
# A Noise Which is 'Spherically' Squashed                   #
#############################################################
def LowVarNoise(n,s):
    y = HigVarNoise(n,s)
    z = abs(y)
    z = (1-sqrt(1-z*z))
    if (abs(y)>.00001):
        z = z*y/abs(y)

    return z

#############################################################
# Crater Preprocessing                                      #
#############################################################
def PreCrater():
    global NOISEHASH
    global LANDMARKSHASH
    global CRATERHASH

    CRATERHASH['Cu'] = list()
    CRATERHASH['Cv'] = list();
    CRATERHASH['Cw'] = list();
    CRATERHASH['Cr'] = list();
    CRATERHASH['Ch'] = list();
    CRATERHASH['Cd'] = list();
    CRATERHASH['Cs'] = list();

    for i in range(LANDMARKSHASH['Crater'].val):
	if (NOISEHASH['Map'].val==0):	
            u = NOISEHASH['Vsize'].val * (HigVarNoise(i,     LANDMARKSHASH['Cseed'].val) + 1.0) / 20.0
	    v = NOISEHASH['Usize'].val * (HigVarNoise(i+57.5,LANDMARKSHASH['Cseed'].val) + 1.0) / 20.0
	    #print u,v
	    w = 0.;

	elif (NOISEHASH['Map'].val==1):
            th = ((HigVarNoise(i,     LANDMARKSHASH['Cseed'].val) + 1.0) / 2.0)*(NOISEHASH['Theta1'].val - NOISEHASH['Theta0'].val) + NOISEHASH['Theta0'].val
	    ph = ((HigVarNoise(i+57.5,LANDMARKSHASH['Cseed'].val) + 1.0) / 2.0)*(NOISEHASH['Phi1'].val - NOISEHASH['Phi0'].val) + NOISEHASH['Phi0'].val
	    u = NOISEHASH['Radius'].val * cos(3.1415927*th/180.0)*cos(3.1415927*ph/180.0)
	    v = NOISEHASH['Radius'].val * cos(3.1415927*th/180.0)*sin(3.1415927*ph/180.0)
	    w = NOISEHASH['Radius'].val * sin(3.1415927*th/180.0)
	    #print th,ph,u,v,w
	else:	
            th = 3.1415927 * (LowVarNoise(i,     LANDMARKSHASH['Cseed'].val) / 2.0)
            ph = 2*3.1415927 * ((HigVarNoise(i+57.5,LANDMARKSHASH['Cseed'].val) + 1.0) / 2.0)
            u = NOISEHASH['Radius'].val * cos(th)*cos(ph)
            v = NOISEHASH['Radius'].val * cos(th)*sin(ph)
            w = NOISEHASH['Radius'].val * sin(th)

        CRATERHASH['Cu'].append(u)	
        CRATERHASH['Cv'].append(v)	
        CRATERHASH['Cw'].append(w)	
        CRATERHASH['Cr'].append(LANDMARKSHASH['Cradius'].val + LANDMARKSHASH['CradiusV'].val*HigVarNoise(i+137,LANDMARKSHASH['Cseed'].val))
        CRATERHASH['Ch'].append(LANDMARKSHASH['Cheight'].val + LANDMARKSHASH['CheightV'].val*HigVarNoise(i+299,LANDMARKSHASH['Cseed'].val))
        CRATERHASH['Cd'].append(LANDMARKSHASH['Cdepth'].val  + LANDMARKSHASH['CdepthV'].val *HigVarNoise(i+1021,LANDMARKSHASH['Cseed'].val))
        CRATERHASH['Cs'].append(LANDMARKSHASH['Csteep'].val  + LANDMARKSHASH['CsteepV'].val *HigVarNoise(i+4093,LANDMARKSHASH['Cseed'].val))	

        if (CRATERHASH['Cr'][i]<0.0001):
            CRATERHASH['Cr'][i]=0.0001
        if (CRATERHASH['Ch'][i]<0.0):
            CRATERHASH['Ch'][i]=0.0
        if (CRATERHASH['Cd'][i]<0.0):
            CRATERHASH['Cd'][i]=0.0
        if (CRATERHASH['Cs'][i]<0.0):
            CRATERHASH['Cs'][i]=0.0

#############################################################
# My Crater Function                                        #
#############################################################
def Crater(rho,r,h,d,s):
    if (rho<r):
	y = d*(rho/r)**(s+1)+h-d
    else:
	y = h*(r/rho)**s

    return (y)

#############################################################
# Peaks Preprocessing                                       #
#############################################################
def PrePeaks():
    global NOISEHASH
    global LANDMARKSHASH
    global PEAKHASH

    PEAKHASH['Pu'] = list()
    PEAKHASH['Pv'] = list();
    PEAKHASH['Pw'] = list();
    PEAKHASH['Pa'] = list();
    PEAKHASH['Pb'] = list();
    PEAKHASH['Pc'] = list();
    PEAKHASH['Pd'] = list();
    PEAKHASH['Pr'] = list();

    for i in range(LANDMARKSHASH['Peaks'].val):
	if (NOISEHASH['Map'].val==0):	
            u = NOISEHASH['Vsize'].val * (HigVarNoise(i,     LANDMARKSHASH['Pseed'].val) + 1.0) / 20.0
	    v = NOISEHASH['Usize'].val * (HigVarNoise(i+57.5,LANDMARKSHASH['Pseed'].val) + 1.0) / 20.0
	    #print u,v
	    w = 0.;
	elif (NOISEHASH['Map'].val==1):
            th = ((HigVarNoise(i,     LANDMARKSHASH['Pseed'].val) + 1.0) / 2.0)*(NOISEHASH['Theta1'].val - NOISEHASH['Theta0'].val) + NOISEHASH['Theta0'].val
	    ph = ((HigVarNoise(i+57.5,LANDMARKSHASH['Pseed'].val) + 1.0) / 2.0)*(NOISEHASH['Phi1'].val - NOISEHASH['Phi0'].val) + NOISEHASH['Phi0'].val
	    u = NOISEHASH['Radius'].val * cos(3.1415927*th/180.0)*cos(3.1415927*ph/180.0)
	    v = NOISEHASH['Radius'].val * cos(3.1415927*th/180.0)*sin(3.1415927*ph/180.0)
	    w = NOISEHASH['Radius'].val * sin(3.1415927*th/180.0)
	    #print th,ph,u,v,w
	else:	
            th = 3.1415927 * (LowVarNoise(i,     LANDMARKSHASH['Pseed'].val) / 2.0)
            ph = 2*3.1415927 * ((HigVarNoise(i+57.5,LANDMARKSHASH['Pseed'].val) + 1.0) / 2.0)
            u = NOISEHASH['Radius'].val * cos(th)*cos(ph)
            v = NOISEHASH['Radius'].val * cos(th)*sin(ph)
            w = NOISEHASH['Radius'].val * sin(th)
			
        PEAKHASH['Pu'].append(u)	
        PEAKHASH['Pv'].append(v)	
        PEAKHASH['Pw'].append(w)	
	Par  = LANDMARKSHASH['Pradius'].val + LANDMARKSHASH['PradiusV'].val*((HigVarNoise(i+299,LANDMARKSHASH['Pseed'].val) + 1.0) / 2.0)
	Pah  = LANDMARKSHASH['Pheight'].val + LANDMARKSHASH['PheightV'].val*((HigVarNoise(i+387,LANDMARKSHASH['Pseed'].val) + 1.0) / 2.0)
	Pamt = LANDMARKSHASH['Ptopsteep'].val + LANDMARKSHASH['PtopsteepV'].val*((HigVarNoise(i+459,LANDMARKSHASH['Pseed'].val) + 1.0) / 2.0)
	Pamb = LANDMARKSHASH['Pfootsteep'].val + LANDMARKSHASH['PfootsteepV'].val*((HigVarNoise(i+785,LANDMARKSHASH['Pseed'].val) + 1.0) / 2.0)

	aux = InterPoly(0,Pah,Pamt,Par,0,Pamb)

        PEAKHASH['Pa'].append(aux[0])	
        PEAKHASH['Pb'].append(aux[1])	
        PEAKHASH['Pc'].append(aux[2])	
        PEAKHASH['Pd'].append(aux[3])	
        PEAKHASH['Pr'].append(Par)	
	

#############################################################
# My Peak Function                                          #
#############################################################
def Peak(rho,r,a,b,c,d):
    if (rho<r):
	    y = a + b*rho + c*rho**2 + d*rho**3
    else:
	    y = 0

    return (y)

#############################################################
#############################################################
#############################################################
#############################################################
#### TERRAFORMING ###########################################
#############################################################
#############################################################
#############################################################
#############################################################

#############################################################
# Basic Quadrilateral Mesh                                  #
#############################################################
def QuadMesh(v1,v2,v3,v4,N,MeshQ):
    for i in range(N+1):
	for j in range(N+1):
	    x = ( (v3[0]-v4[0]) * i/N + v4[0] - (v2[0]-v1[0]) * i/N - v1[0] ) * j/N + (v2[0]-v1[0]) * i/N + v1[0];		
	    y = ( (v3[1]-v4[1]) * i/N + v4[1] - (v2[1]-v1[1]) * i/N - v1[1] ) * j/N + (v2[1]-v1[1]) * i/N + v1[1];			
	    z = ( (v3[2]-v4[2]) * i/N + v4[2] - (v2[2]-v1[2]) * i/N - v1[2] ) * j/N + (v2[2]-v1[2]) * i/N + v1[2];				
	    MeshQ.verts.append(NMesh.Vert(x,y,z))

    for i in range(N):
	for j in range(N):
	    nf = NMesh.Face()
	    nf.v.append(MeshQ.verts[i*(N+1)+j])
	    nf.v.append(MeshQ.verts[i*(N+1)+j+1])
	    nf.v.append(MeshQ.verts[(i+1)*(N+1)+j+1])
	    nf.v.append(MeshQ.verts[(i+1)*(N+1)+j])
	    MeshQ.faces.append(nf)
	    
#############################################################
# Quadrilateral Portion of Flat Mesh                        #
#############################################################
def MeshFormQ(v1,v2,v3,v4,U,V,MeshQ):

    for i in range(V+1):
	for j in range(U+1):
            x = ( (v3[0]-v4[0]) * i/V + v4[0] - (v2[0]-v1[0]) * i/V - v1[0] ) * j/U + (v2[0]-v1[0]) * i/V + v1[0];		
	    y = ( (v3[1]-v4[1]) * i/V + v4[1] - (v2[1]-v1[1]) * i/V - v1[1] ) * j/U + (v2[1]-v1[1]) * i/V + v1[1];			
	    z = ( (v3[2]-v4[2]) * i/V + v4[2] - (v2[2]-v1[2]) * i/V - v1[2] ) * j/U + (v2[2]-v1[2]) * i/V + v1[2];				
	    MeshQ.verts.append(NMesh.Vert(x,y,z))

    for i in range(V):
	for j in range(U):
	    nf = NMesh.Face()
	    nf.v.append(MeshQ.verts[i*(U+1)+j])
	    nf.v.append(MeshQ.verts[i*(U+1)+j+1])
	    nf.v.append(MeshQ.verts[(i+1)*(U+1)+j+1])
	    nf.v.append(MeshQ.verts[(i+1)*(U+1)+j])
	    MeshQ.faces.append(nf)

#############################################################
# Quadrilateral Portion of Sphere Mesh                      #
#############################################################
def MeshFormSQ(ThetaMin,ThetaMax,PhiMin,PhiMax,U,V,MeshQ):

    global NOISEHASH

    for i in range(U+1):
	for j in range(V+1):
	    Theta = (ThetaMax-ThetaMin)*i/U + ThetaMin;
	    Phi   = (PhiMax-PhiMin)*j/V + PhiMin;
	    x = NOISEHASH['Radius'].val * cos(Theta)*cos(Phi)
	    y = NOISEHASH['Radius'].val * cos(Theta)*sin(Phi)
            z = NOISEHASH['Radius'].val * sin(Theta)
	    MeshQ.verts.append(NMesh.Vert(x,y,z))

    for i in range(U):
	for j in range(V):
            nf = NMesh.Face()
	    nf.v.append(MeshQ.verts[i*(V+1)+j])
	    nf.v.append(MeshQ.verts[i*(V+1)+j+1])
	    nf.v.append(MeshQ.verts[(i+1)*(V+1)+j+1])
	    nf.v.append(MeshQ.verts[(i+1)*(V+1)+j])
	    MeshQ.faces.append(nf)

#############################################################
# Triangular Portion of Sphere Mesh                         #
#############################################################
def MeshFormT(v1,v2,v3,MeshT):

    global noisehash

    va1 = list();
    va2 = list();
    va3 = list();
    va4 = list();

    va1.append((v2[0]+v1[0])/2.)		
    va1.append((v2[1]+v1[1])/2.)		
    va1.append((v2[2]+v1[2])/2.)		

    va2.append((v3[0]+v2[0])/2.)		
    va2.append((v3[1]+v2[1])/2.)		
    va2.append((v3[2]+v2[2])/2.)		

    va3.append((v1[0]+v3[0])/2.)		
    va3.append((v1[1]+v3[1])/2.)		
    va3.append((v1[2]+v3[2])/2.)		

    va4.append((v1[0]+v2[0]+v3[0])/3.)		
    va4.append((v1[1]+v2[1]+v3[1])/3.)		
    va4.append((v1[2]+v2[2]+v3[2])/3.)		

    MeshQ1 = NMesh.GetRaw()
    MeshQ2 = NMesh.GetRaw()
    MeshQ3 = NMesh.GetRaw()
    QuadMesh(v1,va1,va4,va3,NOISEHASH['Usize'].val,MeshQ1)
    QuadMesh(v2,va2,va4,va1,NOISEHASH['Usize'].val,MeshQ2)
    QuadMesh(v3,va3,va4,va2,NOISEHASH['Usize'].val,MeshQ3)

    MeshT.verts.extend(MeshQ1.verts)
    MeshT.faces.extend(MeshQ1.faces)
    MeshT.verts.extend(MeshQ2.verts)
    MeshT.faces.extend(MeshQ2.faces)
    MeshT.verts.extend(MeshQ3.verts)
    MeshT.faces.extend(MeshQ3.faces)
            
    del MeshQ1
    del MeshQ2
    del MeshQ3
            
    if (NOISEHASH['Radius'].val > 0):
	for v in MeshT.verts:
	    x = v.co[0];
	    y = v.co[1];
	    z = v.co[2];

	    d = sqrt(x*x+y*y+z*z);

	    v.co[0] = NOISEHASH['Radius'].val*x/d;
	    v.co[1] = NOISEHASH['Radius'].val*y/d;
	    v.co[2] = NOISEHASH['Radius'].val*z/d;

#############################################################
# The actual TERRAFORMING                                   #
#############################################################
def TerraFormF (Mesh):
    global NOISEHASH
    global LANDMARKSHASH,CRATERHASH,PEAKHASH
    
    global PBtitle
        
    N = 1.0*len(Mesh.verts)
    i = 0

    if (NOISEHASH['Type'].val == 0):
        NT = Noise.NoiseTypes.BLENDER
    elif (NOISEHASH['Type'].val == 1):
        NT = Noise.NoiseTypes.STDPERLIN
    elif (NOISEHASH['Type'].val == 2):
        NT = Noise.NoiseTypes.NEWPERLIN
    elif (NOISEHASH['Type'].val == 3):
        NT = Noise.NoiseTypes.VORONOI_F1
    elif (NOISEHASH['Type'].val == 4):
        NT = Noise.NoiseTypes.VORONOI_F2
    elif (NOISEHASH['Type'].val == 5):
        NT = Noise.NoiseTypes.VORONOI_F3
    elif (NOISEHASH['Type'].val == 6):
        NT = Noise.NoiseTypes.VORONOI_F4
    elif (NOISEHASH['Type'].val == 7):
        NT = Noise.NoiseTypes.VORONOI_F2F1
    elif (NOISEHASH['Type'].val == 8):
        NT = Noise.NoiseTypes.VORONOI_CRACKLE
    else:
        NT = Noise.NoiseTypes.CELLNOISE

    if (NOISEHASH['Metric'].val == 0):
        MT = Noise.DistanceMetrics.DISTANCE
    elif (NOISEHASH['Metric'].val == 1):
        MT = Noise.DistanceMetrics.DISTANCE_SQUARED
    elif (NOISEHASH['Metric'].val == 2):
        MT = Noise.DistanceMetrics.MANHATTAN
    elif (NOISEHASH['Metric'].val == 3):
        MT = Noise.DistanceMetrics.CHEBYCHEV
    elif (NOISEHASH['Metric'].val == 4):
        MT = Noise.DistanceMetrics.MINKOVSKY_HALF
    elif (NOISEHASH['Metric'].val == 5):
        MT = Noise.DistanceMetrics.MINKOVSKY_HALF
    else:
        MT = Noise.DistanceMetrics.MINKOVSKY
        
    for ve in Mesh.verts:
	v = ve.co[0] * NOISEHASH['UVsize'].val + NOISEHASH['Voffset'].val
	u = ve.co[1] * NOISEHASH['UVsize'].val + NOISEHASH['Uoffset'].val

        if (NOISEHASH['Function'].val == 0):
            vn = Noise.noise((u,v,0.0),NT)
        elif (NOISEHASH['Function'].val == 1):
            vn = Noise.fBm((u,v,0.0),NOISEHASH['H'].val,NOISEHASH['Lacu'].val,NOISEHASH['Octs'].val,NT)
        elif (NOISEHASH['Function'].val == 2):
            vn = Noise.multiFractal((u,v,0.0),NOISEHASH['H'].val,NOISEHASH['Lacu'].val,NOISEHASH['Octs'].val,NT)
        elif (NOISEHASH['Function'].val == 3):
            vn = Noise.hybridMFractal((u,v,0.0),NOISEHASH['H'].val,NOISEHASH['Lacu'].val,NOISEHASH['Octs'].val,NOISEHASH['Ofst'].val,NOISEHASH['Gain'].val,NT)
        elif (NOISEHASH['Function'].val == 4):
            vn = Noise.ridgedMFractal((u,v,0.0),NOISEHASH['H'].val,NOISEHASH['Lacu'].val,NOISEHASH['Octs'].val,NOISEHASH['Ofst'].val,NOISEHASH['Gain'].val,NT)
        elif (NOISEHASH['Function'].val == 5):
            vn = Noise.turbulence((u,v,0.0),NOISEHASH['Octs'].val,NOISEHASH['Hard'].val,NT,NOISEHASH['Ampl'].val,NOISEHASH['Freq'].val)
        else:
            vn = Noise.voronoi((u,v,0.0),MT,NOISEHASH['Exp'].val)[0][0]
    		
	zv = (vn - 0.5) * NOISEHASH['Zsize'].val
	#POSTPRO#
	zv = Filter(zv)
	#CRATERS#
	for k in range(LANDMARKSHASH['Crater'].val):
	    rho = sqrt((ve.co[1]-CRATERHASH['Cv'][k])*(ve.co[1]-CRATERHASH['Cv'][k])+
                       (ve.co[0]-CRATERHASH['Cu'][k])*(ve.co[0]-CRATERHASH['Cu'][k]))
	    zv = zv + Crater(rho,CRATERHASH['Cr'][k],CRATERHASH['Ch'][k],CRATERHASH['Cd'][k],CRATERHASH['Cs'][k])
	#PEAKS#
	for k in range(LANDMARKSHASH['Peaks'].val):
	    rho = sqrt((v-PEAKHASH['Pv'][k])*(v-PEAKHASH['Pv'][k])+(u-PEAKHASH['Pu'][k])*(u-PEAKHASH['Pu'][k]))
	    zv = zv + Peak(rho,PEAKHASH['Pr'][k],PEAKHASH['Pa'][k],PEAKHASH['Pb'][k],PEAKHASH['Pc'][k],PEAKHASH['Pd'][k])				
	ve.co[2] = zv;
		
        i = i+1
        if (i/500 == i/500.0):
            Blender.Window.DrawProgressBar(i/N,PBtitle+"Terraforming")
                
def TerraFormS (Mesh):

    global NOISEHASH
    global LANDMARKSHASH,CRATERHASH

    global PBtitle
        
    N = 1.0*len(Mesh.verts)
    i = 0

    if (NOISEHASH['Type'].val == 0):
        NT = Noise.NoiseTypes.BLENDER
    elif (NOISEHASH['Type'].val == 1):
        NT = Noise.NoiseTypes.STDPERLIN
    elif (NOISEHASH['Type'].val == 2):
        NT = Noise.NoiseTypes.NEWPERLIN
    elif (NOISEHASH['Type'].val == 3):
        NT = Noise.NoiseTypes.VORONOI_F1
    elif (NOISEHASH['Type'].val == 4):
        NT = Noise.NoiseTypes.VORONOI_F2
    elif (NOISEHASH['Type'].val == 5):
        NT = Noise.NoiseTypes.VORONOI_F3
    elif (NOISEHASH['Type'].val == 6):
        NT = Noise.NoiseTypes.VORONOI_F4
    elif (NOISEHASH['Type'].val == 7):
        NT = Noise.NoiseTypes.VORONOI_F2F1
    elif (NOISEHASH['Type'].val == 8):
        NT = Noise.NoiseTypes.VORONOI_CRACKLE
    else:
        NT = Noise.NoiseTypes.CELLNOISE

    if (NOISEHASH['Metric'].val == 0):
        MT = Noise.DistanceMetrics.DISTANCE
    elif (NOISEHASH['Metric'].val == 1):
        MT = Noise.DistanceMetrics.DISTANCE_SQUARED
    elif (NOISEHASH['Metric'].val == 2):
        MT = Noise.DistanceMetrics.MANHATTAN
    elif (NOISEHASH['Metric'].val == 3):
        MT = Noise.DistanceMetrics.CHEBYCHEV
    elif (NOISEHASH['Metric'].val == 4):
        MT = Noise.DistanceMetrics.MINKOVSKY_HALF
    elif (NOISEHASH['Metric'].val == 5):
        MT = Noise.DistanceMetrics.MINKOVSKY_HALF
    else:
        MT = Noise.DistanceMetrics.MINKOVSKY
        
    for ve in Mesh.verts:
	u = ve.co[0] * NOISEHASH['UVsize'].val + NOISEHASH['Uoffset'].val
	v = ve.co[1] * NOISEHASH['UVsize'].val + NOISEHASH['Voffset'].val
	w = ve.co[2] * NOISEHASH['UVsize'].val + NOISEHASH['Woffset'].val

        if (NOISEHASH['Function'].val == 0):
            vn = Noise.noise((u,v,w),NT)
        elif (NOISEHASH['Function'].val == 1):
            vn = Noise.fBm((u,v,w),NOISEHASH['H'].val,NOISEHASH['Lacu'].val,NOISEHASH['Octs'].val,NT)
        elif (NOISEHASH['Function'].val == 2):
            vn = Noise.multiFractal((u,v,w),NOISEHASH['H'].val,NOISEHASH['Lacu'].val,NOISEHASH['Octs'].val,NT)
        elif (NOISEHASH['Function'].val == 3):
            vn = Noise.hybridMFractal((u,v,w),NOISEHASH['H'].val,NOISEHASH['Lacu'].val,NOISEHASH['Octs'].val,NOISEHASH['Ofst'].val,NOISEHASH['Gain'].val,NT)
        elif (NOISEHASH['Function'].val == 4):
            vn = Noise.ridgedMFractal((u,v,w),NOISEHASH['H'].val,NOISEHASH['Lacu'].val,NOISEHASH['Octs'].val,NOISEHASH['Ofst'].val,NOISEHASH['Gain'].val,NT)
        elif (NOISEHASH['Function'].val == 5):
            vn = Noise.turbulence((u,v,w),NOISEHASH['Octs'].val,NOISEHASH['Hard'].val,NT,NOISEHASH['Ampl'].val,NOISEHASH['Freq'].val)
        else:
            vn = Noise.voronoi((u,v,w),MT,NOISEHASH['Exp'].val)[0][0]

	vn = (vn - 0.5) * NOISEHASH['Zsize'].val
		
	#POSTPRO#
	vn = Filter(vn)
	#CRATERS#
	for k in range(LANDMARKSHASH['Crater'].val):
	    rho = sqrt((ve.co[0]-CRATERHASH['Cu'][k])*(ve.co[0]-CRATERHASH['Cu'][k])+
                       (ve.co[1]-CRATERHASH['Cv'][k])*(ve.co[1]-CRATERHASH['Cv'][k])+
                       (ve.co[2]-CRATERHASH['Cw'][k])*(ve.co[2]-CRATERHASH['Cw'][k]))
	    vn = vn + Crater(rho,CRATERHASH['Cr'][k],CRATERHASH['Ch'][k],CRATERHASH['Cd'][k],CRATERHASH['Cs'][k])

	#PEAKS#
	for k in range(LANDMARKSHASH['Peaks'].val):
            rho = sqrt((v-PEAKHASH['Pu'][k])*(v-PEAKHASH['Pu'][k])+
                       (u-PEAKHASH['Pv'][k])*(u-PEAKHASH['Pv'][k])+
                       (w-PEAKHASH['Pw'][k])*(w-PEAKHASH['Pw'][k]))
	    vn = vn + Peak(rho,PEAKHASH['Pr'][k],PEAKHASH['Pa'][k],PEAKHASH['Pb'][k],PEAKHASH['Pc'][k],PEAKHASH['Pd'][k])
		
	d = sqrt(ve.co[0]*ve.co[0]+ve.co[1]*ve.co[1]+ve.co[2]*ve.co[2])
	ve.co[0] = ve.co[0] + vn * ve.co[0]/d
	ve.co[1] = ve.co[1] + vn * ve.co[1]/d
	ve.co[2] = ve.co[2] + vn * ve.co[2]/d

        i = i+1
        if (i/100 == i/100.0):
            Blender.Window.DrawProgressBar(i/N,PBtitle+"Terraforming")


#############################################################
# Main Body                                                 #
#############################################################
def DoTheTerraform():
    global NOISEHASH
    global VertT,VertsO,VertsI
    global PBtitle
    
    print "BLENDER WORLD FORGE  - (C) 2003,2004 Stefano <S68> Selleri"
    print "Vers. "+VERSION
    print "Released under Blender Artistic License (www.blender.org)"

    BaseMeshes = list()
    LayerMeshes = [[],[],[],[],[],[]]
	
    #############################################################
    # Creates a set of UNDEFORMED Meshes                        #
    #############################################################
    if (NOISEHASH['Map'].val==0 or NOISEHASH['Map'].val==1):
	N = int(NOISEHASH['Vsize'].val / 250.0)+1
	M = int(NOISEHASH['Usize'].val / 250.0)+1
	
	idx = 0
	for i in range(0,N):
            for j in range(0,M):
                Mname = "Land_"+str(i)+"_"+str(j)
		Vmin = i*250
		Vmax = (i+1)*250
		if (Vmax>NOISEHASH['Vsize'].val):
                    Vmax = NOISEHASH['Vsize'].val

                Umin = j*250
		Umax = (j+1)*250
		if (Umax>NOISEHASH['Usize'].val):
		    Umax = NOISEHASH['Usize'].val

		Mesh = NMesh.GetRaw()
		Mesh.name = Mname
                PBtitle = "P["+str(i)+','+str(j)+']:'
                                
	        if (NOISEHASH['Map'].val==0):
		    v1 = [Vmin/10.,Umin/10.,0.]
		    v2 = [Vmax/10.,Umin/10.,0.]
		    v3 = [Vmax/10.,Umax/10.,0.]
		    v4 = [Vmin/10.,Umax/10.,0.]
		    Blender.Window.DrawProgressBar(0.0,PBtitle+"Gridding");
		    MeshFormQ(v1,v2,v3,v4,Umax-Umin,Vmax-Vmin,Mesh)
		    TerraFormF(Mesh)
		    Mesh.mode = 260
		else:
		    ThetaMin = (3.1415927/180) * ((1.0*Umin /(NOISEHASH['Usize'].val))*(NOISEHASH['Theta1'].val - NOISEHASH['Theta0'].val) + NOISEHASH['Theta0'].val)
		    ThetaMax = (3.1415927/180) * ((1.0*Umax /(NOISEHASH['Usize'].val))*(NOISEHASH['Theta1'].val - NOISEHASH['Theta0'].val) + NOISEHASH['Theta0'].val)
		    PhiMin   = (3.1415927/180) * ((1.0*Vmin /(NOISEHASH['Vsize'].val))*(NOISEHASH['Phi1'].val - NOISEHASH['Phi0'].val) + NOISEHASH['Phi0'].val)
		    PhiMax   = (3.1415927/180) * ((1.0*Vmax /(NOISEHASH['Vsize'].val))*(NOISEHASH['Phi1'].val - NOISEHASH['Phi0'].val) + NOISEHASH['Phi0'].val)
        	    Blender.Window.DrawProgressBar(0.0,PBtitle+"Gridding");
		    MeshFormSQ(ThetaMin,ThetaMax,PhiMin,PhiMax,Umax-Umin,Vmax-Vmin,Mesh)
		    TerraFormS(Mesh)
		    Mesh.mode = 260
					
		BaseMeshes.append( NMesh.PutRaw(Mesh) )
                BaseMeshes[len(BaseMeshes)-1].name = Mname
                                        
		print "Terraformed plot (",i,j,") number ",idx," of ",N*M
		idx = idx+1

    elif (NOISEHASH['Map'].val==2):
        for i in range(4):
            PBtitle = "P["+str(i)+']:'
            Mname = "Land_"+str(i)
	    Mesh = NMesh.GetRaw()
	    Mesh.name = Mname
	    Blender.Window.DrawProgressBar(0.0,PBtitle+"Gridding");
	    MeshFormT([VertsT[0][FacesT[0][i]],VertsT[1][FacesT[0][i]],VertsT[2][FacesT[0][i]]],
		      [VertsT[0][FacesT[1][i]],VertsT[1][FacesT[1][i]],VertsT[2][FacesT[1][i]]],
		      [VertsT[0][FacesT[2][i]],VertsT[1][FacesT[2][i]],VertsT[2][FacesT[2][i]]],
		      Mesh)
	    TerraFormS(Mesh)
	    Mesh.mode = 260
	    BaseMeshes.append( NMesh.PutRaw(Mesh) )
            BaseMeshes[len(BaseMeshes)-1].name = Mname
	    print "Terraformed plot (",i,") of 4"
			
    elif (NOISEHASH['Map'].val==3):
	for i in range(8):
            PBtitle = "P["+str(i)+']:'
            Mname = "Land_"+str(i)
            Mesh = NMesh.GetRaw()
	    Mesh.name = Mname
	    Blender.Window.DrawProgressBar(0.0,PBtitle+"Gridding");
	    MeshFormT([VertsO[0][FacesO[0][i]],VertsO[1][FacesO[0][i]],VertsO[2][FacesO[0][i]]],
		      [VertsO[0][FacesO[1][i]],VertsO[1][FacesO[1][i]],VertsO[2][FacesO[1][i]]],
		      [VertsO[0][FacesO[2][i]],VertsO[1][FacesO[2][i]],VertsO[2][FacesO[2][i]]],
		      Mesh)
	    TerraFormS(Mesh)
	    Mesh.mode = 260
	    BaseMeshes.append( NMesh.PutRaw(Mesh) )
            BaseMeshes[len(BaseMeshes)-1].name = Mname
	    print "Terraformed plot (",i,") of 8"

    elif (NOISEHASH['Map'].val==4):
	for i in range(20):
            PBtitle = "P["+str(i)+']:'
            Mname = "Land_"+str(i)
	    Mesh = NMesh.GetRaw()
	    Mesh.name = Mname
	    Blender.Window.DrawProgressBar(0.0,PBtitle+"Gridding");
	    MeshFormT([VertsI[0][FacesI[0][i]],VertsI[1][FacesI[0][i]],VertsI[2][FacesI[0][i]]],
		      [VertsI[0][FacesI[1][i]],VertsI[1][FacesI[1][i]],VertsI[2][FacesI[1][i]]],
		      [VertsI[0][FacesI[2][i]],VertsI[1][FacesI[2][i]],VertsI[2][FacesI[2][i]]],
		      Mesh)
            TerraFormS(Mesh)
            Mesh.mode = 260
            BaseMeshes.append( NMesh.PutRaw(Mesh) )
            BaseMeshes[len(BaseMeshes)-1].name = Mname
            print "Terraformed plot (",i,") of 20"

    Blender.Window.DrawProgressBar(1.0,"")

#############################################################
#############################################################
#############################################################
#############################################################
#### POSTPRO ################################################
#############################################################
#############################################################
#############################################################
#############################################################

def DoThePostPro1(layer):

    global POSTPROHASH1
    global PBtitle
    
    Zmin = POSTPROHASH1['Zmin'][layer].val
    Zmax = POSTPROHASH1['Zmax'][layer].val
    Smin = POSTPROHASH1['Smin'][layer].val
    Smax = POSTPROHASH1['Smax'][layer].val

    print "PP Working on ",len(Object.GetSelected())," objects"
    Blender.Window.DrawProgressBar(0.0,"Preparing")
    
    for obj in Object.GetSelected():
        OName = obj.name
        PBtitle = "PP["+OName+"]"
        RawMesh = NMesh.GetRawFromObject(OName)
        print OName, RawMesh
        RawMesh.name = OName+"Layer"+str(layer)
        LandToLayer(RawMesh,Zmin,Zmax,Smin,Smax)
        RawMesh.mode=260
        NewLayer = NMesh.PutRaw(RawMesh)
        NewLayer.name = "OName"+"L"+str(layer)
    
    Blender.Window.DrawProgressBar(1.0,"")

#############################################################
# Creates the additional LAYERS                             #
#############################################################
def LandToLayer (Mesh,Zmin,Zmax,Smin,Smax):

    global PBtitle

    print Zmin,Zmax,Smin,Smax
    # Enforces [Zmin,Zmax] Constraint
    vtokill = []
    
    for i in range(len(Mesh.verts)):
        if (Mesh.verts[i].co[2]<Zmin or Mesh.verts[i].co[2]>Zmax):
            vtokill.append(Mesh.verts[i])

    i = 0
    N = 1.0*len(Mesh.faces)
    while (i<len(Mesh.faces)):
        f = Mesh.faces[i]
        flag=0
        for v in f.v:
            try:
                vtokill.index(v)
                flag=1
            except:
                pass
                
        if (flag==1):
            Mesh.faces.remove(f)
        else:
            i = i+1

        if (i/100 == i/100.0):
            Blender.Window.DrawProgressBar(i/N,PBtitle+"L(Z)")

    for v in vtokill:
        Mesh.verts.remove(v)

    # Enforces [Smin,Smax] Constraint
    ftokill = []
    vcount = [0] * len (Mesh.verts)

    i = 0
    N = 1.0*len(Mesh.faces)
    for f in Mesh.faces:
        zmi=f.v[0].co[2]
        zma=zmi
        for v in f.v:
            vi = Mesh.verts.index(v)
            vcount[vi] = vcount[vi] + 1
            if (v.co[2]<zmi):
                zmi = v.co[2]
            if (v.co[2]>zma):
                zma = v.co[2]

        s = 10*abs(zma-zmi)

        if (s<Smin or s>Smax):
            ftokill.append(f)

        i = i + 1
        if (i/100 == i/100.0):
            Blender.Window.DrawProgressBar(i/N,PBtitle+"L(S(a))")

    i = 0
    N = 1.0*len(Mesh.faces)
    for f in ftokill:
        for v in f.v:
            vi = Mesh.verts.index(v)
            vcount[vi] = vcount[vi] - 1
        Mesh.faces.remove(f)
        i = i + 1
        if (i/100 == i/100.0):
            Blender.Window.DrawProgressBar(i/N,PBtitle+"L(S(b))")

    vtokill = []
    for vi in range(len(Mesh.verts)):
        if (vcount[vi]<=0):
            vtokill.append(Mesh.verts[vi])

    for v in vtokill:
        Mesh.verts.remove(v)
   
def DoThePostPro2(layer):

    global POSTPROHASH2
    global PBtitle
    
    Zmin  = POSTPROHASH2['Zmin'][layer].val
    Zmax  = POSTPROHASH2['Zmax'][layer].val
    Smin  = POSTPROHASH2['Smin'][layer].val
    Smax  = POSTPROHASH2['Smax'][layer].val
    Verts = POSTPROHASH2['Verts'][layer].val

    print "PP Working on ",len(Object.GetSelected())," objects"
    Blender.Window.DrawProgressBar(0.0,"Preparing")
    
    for obj in Object.GetSelected():
        OName = obj.name
        PBtitle = "PP["+OName+"]"
        RawMesh = NMesh.GetRawFromObject(OName)
        print OName, RawMesh
        RawMesh.name = OName+"Layer"+str(layer)
        CloudMesh = LandToCloud(RawMesh,Zmin,Zmax,Smin,Smax,Verts)
        CloudMesh.mode=260
        NewLayer = NMesh.PutRaw(CloudMesh)
        NewLayer.name = "OName"+"L"+str(layer)
    
    Blender.Window.DrawProgressBar(1.0,"")

#############################################################
# Creates the additional CLOUDS                             #
#############################################################
def LandToCloud (Mesh,Zmin,Zmax,Smin,Smax,VertsD):

    global PBtitle

    print Zmin,Zmax,Smin,Smax,VertsD

    idx = 1
    Cmesh = NMesh.GetRaw()

    for f in Mesh.faces:
        zmi=f.v[0].co[2]
        zma=zmi
        for v in f.v:
            if (v.co[2]<zmi):
                zmi = v.co[2]
            if (v.co[2]>zma):
                zma = v.co[2]
        VF = 1
        if (zmi<Zmin or zma>Zmax):
            VF = 0

        s = 10*abs(zma-zmi)

        if (s<Smin or s>Smax):
            VF = 0

        #print 'This is face ',zmi,zma,s,VF
        if (VF==1):
            accumulated = (HigVarNoise(idx+897, 0) + 1.0) / 2.0
            idx = idx+1
            while (accumulated<VertsD):
                #print accumulated
                
                u = (HigVarNoise(idx+97+VertsD*12379, 0) + 1.0) / 2.0
                idx = idx+1
                v = (HigVarNoise(idx+1873+VertsD*15379, 0) + 1.0) / 2.0
                idx = idx+1

                xa = u*(f.v[1].co[0]-f.v[0].co[0]) + f.v[0].co[0]
                ya = u*(f.v[1].co[1]-f.v[0].co[1]) + f.v[0].co[1]
                za = u*(f.v[1].co[2]-f.v[0].co[2]) + f.v[0].co[2]

                xb = u*(f.v[2].co[0]-f.v[3].co[0]) + f.v[3].co[0]
                yb = u*(f.v[2].co[1]-f.v[3].co[1]) + f.v[3].co[1]
                zb = u*(f.v[2].co[2]-f.v[3].co[2]) + f.v[3].co[2]

                x = v*(xb-xa) + xa
                y = v*(yb-ya) + ya
                z = v*(zb-za) + za

                Cmesh.verts.append(NMesh.Vert(x,y,z))
                accumulated = accumulated + (HigVarNoise(idx+897, 0) + 1.0) / 2.0
                idx = idx+1
                    
                
    return (Cmesh)        
    
   
#############################################################
#############################################################
#############################################################
#############################################################
#### GUI ####################################################
#############################################################
#############################################################
#############################################################
#############################################################
    
#############################################################
# Graphics                                                  #
#############################################################
def draw():
    global ErrorMessage
    if (ErrorMessage==''):
        MainWindow()
    else:
        ErrorDialog()
        
#############################################################
# Main Window                                               #
#############################################################
def MainWindow():
    global EVENTHASH
    global CONTEXTHASH
    
    BGL.glClearColor(0.5, 0.5, 0.5, 0.0)
    BGL.glClear(BGL.GL_COLOR_BUFFER_BIT)
    BGL.glColor3f(0, 0, 0) 			# Black
    BGL.glRectf(2, 2, 482, 520)
    BGL.glColor3f(0.48, 0.4, 0.57) 		# Light Purple
    BGL.glRectf(4, 479, 480, 510)
    BGL.glRectf(4, 34, 480, 450)
    BGL.glColor3f(0.3, 0.27, 0.35) 		# Dark purple
    BGL.glRectf(4, 451,480, 478)
    BGL.glRectf(4, 4, 480, 33)

    #############################################################
    # Common Header                                             #
    #############################################################

    BGL.glColor3f(0.9, 0.8, 1)
    BGL.glRasterPos2d(10, 500)
    Draw.Text("Blender World Forge v. "+VERSION)
    BGL.glRasterPos2d(10, 484)
    Draw.Text("(C) 2003 - 2004 Stefano Selleri <a.k.a. S68>")
    Draw.Button("Save", EVENTHASH['SAVE'], 307, 494, 60, 12,
		"Save currents settings to a file")
    Draw.Button("Load", EVENTHASH['LOAD'], 307, 482, 60, 12,
		"Loads Previously saved Settings form a file")
    Draw.Button("Exit", EVENTHASH['EXIT'], 367, 482, 110, 24)
 
    CONTEXTHASH['Noise'] = Draw.Toggle(
        "Noise",CONTEXTHASH['NoiseEV'],7,454,110,20,CONTEXTHASH['Noise'].val,
        "General settings (land size, noise)")
    CONTEXTHASH['Filters'] = Draw.Toggle(
        "Filters",CONTEXTHASH['FiltersEV'],127,454,110,20,CONTEXTHASH['Filters'].val,
        "Noise Filtering")
    CONTEXTHASH['Landmarks'] = Draw.Toggle(
        "Landmarks",CONTEXTHASH['LandmarksEV'],247,454,110,20,CONTEXTHASH['Landmarks'].val,
        "Peculiar Landmarks (Peaks, Craters)")
    CONTEXTHASH['PostPro'] = Draw.Toggle(
        "PostPro",CONTEXTHASH['PostProEV'],367,454,110,20,CONTEXTHASH['PostPro'].val,
        "PostPro Mesh Layers for dupliverting items")

    #############################################################
    # Common Footer                                             #
    #############################################################

    if (CONTEXTHASH['PostPro'].val==0):
        Draw.Button("TERRAFORM", EVENTHASH['DO'], 7, 7, 470, 24)
        BGL.glColor3f(0.9, 0.9, 0.9)

    if (CONTEXTHASH['Noise'].val==1):
	#############################################################
	# Context 1 NOISE                                           #
	#############################################################
        Context1GUI()
        
    elif(CONTEXTHASH['Filters'].val==1):
	#############################################################
	# Context 2 FILTERS                                         #
	#############################################################
        Context2GUI()
        
    elif(CONTEXTHASH['Landmarks'].val==1):
	#############################################################
	# Context 3 LANDMARKS                                       #
	#############################################################
        Context3GUI()
        
    else:
	#############################################################
	# Context 4 POSTPRO                                         #
	#############################################################
        Context4GUI()

#############################################################
# CONTEXT 1 GUI                                             #
#############################################################
def Context1GUI():
    global EVENTHASH
    global NOISEHASH
    
    BGL.glRasterPos2d(8, 425)
    Draw.Text("Mapping:")

    NOISEHASH['Map'] = Draw.Menu(
        "Mapping Type%t|Flat%x0|Spherical: LatLong%x1|Spherical: Tetra%x2|Spherical: Octa%x3|Spherical: Ico%x4",
        EVENTHASH['REDRAW'], 107, 420, 360, 18,NOISEHASH['Map'].val) 

    BGL.glRasterPos2d(8, 405)
    Draw.Text("Terrain size:")

    if (NOISEHASH['Map'].val==0):
	####################################################
	# Sub Screen 1.A                                   #
	####################################################
	NOISEHASH['Usize'] = Draw.Slider(
            "Terrain Size U : ", EVENTHASH['NOEVENT'], 107, 380, 360, 18, NOISEHASH['Usize'].val, 0, 2048 , 0,
	    "Number of vertices in the U direction")
	NOISEHASH['Vsize'] = Draw.Slider(
            "Terrain Size V : ", EVENTHASH['NOEVENT'], 107, 360, 360, 18, NOISEHASH['Vsize'].val, 0, 4096 , 0,
            "Number of vertices in the V direction")
	 
    elif(NOISEHASH['Map'].val==1):
	####################################################
	# Sub Screen 1.B                                   #
	####################################################
	NOISEHASH['Usize'] = Draw.Slider(
            "Terrain Size U : ", EVENTHASH['NOEVENT'], 107, 380, 360, 18, NOISEHASH['Usize'].val, 0, 2048 , 0,
	    "Number of vertices in the Pole to Pole (Theta) direction")
	NOISEHASH['Vsize'] = Draw.Slider(
            "Terrain Size V : ", EVENTHASH['NOEVENT'], 107, 360, 360, 18, NOISEHASH['Vsize'].val, 0, 4096 , 0,
            "Number of vertices in the Aequatorial (Phi) direction")
       	NOISEHASH['Radius'] = Draw.Slider(
            "Radius: ", EVENTHASH['NOEVENT'], 107, 340, 360, 18, NOISEHASH['Radius'].val, 0.1, 500.0, 0,
            "Planet radius")

	NOISEHASH['Theta1'] = Draw.Number(
            "Th max: ", EVENTHASH['NOEVENT'], 230, 320, 120, 18, NOISEHASH['Theta1'].val, 0.1, 90.0, 
            "Maximum Theta (North of Aequator)")
	NOISEHASH['Theta0'] = Draw.Number(
            "Th min: ", EVENTHASH['NOEVENT'], 230, 280, 120, 18, NOISEHASH['Theta0'].val, -90.0, -0.1, 
	    "Minimum Theta (South of Aequator)")
	NOISEHASH['Phi0'] = Draw.Number(
            "Ph max: ", EVENTHASH['NOEVENT'], 107, 300, 120, 18, NOISEHASH['Phi0'].val, -180.0, -0.1, 
            "Minimum Phi (West of 'Greenwich')")
	NOISEHASH['Phi1'] = Draw.Number(
            "Ph min: ", EVENTHASH['NOEVENT'], 353, 300, 120, 18, NOISEHASH['Phi1'].val, 0.1, 180.0, 
	    "Maximum Phi (Est of 'Greenwich')")
	BGL.glRasterPos2d(230, 305)
	Draw.Text("<- LatLong Limits ->")

    else:
	####################################################
	# Sub Screen 1.C,D,E                               #
	####################################################
	NOISEHASH['Usize'] = Draw.Slider(
            "Terrain Size U : ", EVENTHASH['NOEVENT'], 107, 380, 360, 18, NOISEHASH['Usize'].val, 0, 2048 , 0,
	    "Number of vertices along the triangle half side")
       	NOISEHASH['Radius'] = Draw.Slider(
            "Radius: ", EVENTHASH['NOEVENT'], 107, 340, 360, 18, NOISEHASH['Radius'].val, 0.1, 500.0, 0,
            "Planet radius")

    BGL.glRasterPos2d(8, 255)
    Draw.Text("Noise:")

    if (NOISEHASH['Function'].val!=6):
        NOISEHASH['Type'] = Draw.Menu(
            "Noise Type%t|Blender%x0|Perlin%x1|Mod. Perlin%x2|Voronoi F1%x3|Voronoi F2%x4|Voronoi F3%x5|Voronoi F4%x6|Voronoi F2-F1%x7|Voronoi Crackle%x8|Cell%x9",
            EVENTHASH['REDRAW'], 107, 230, 160, 18,NOISEHASH['Type'].val)	
    NOISEHASH['Function'] = Draw.Menu(
        "Noise Function%t|Plain Noise%x0|Fractional Brownian%x1|MultiFractal%x2|Hybrid Multfractal%x3|Ridged Multifractal%x4|Turbulence%x5|Voronoi%x6",
	EVENTHASH['REDRAW'], 270, 230, 160, 18,NOISEHASH['Function'].val)	

    NOISEHASH['Uoffset'] = Draw.Slider(
        "X Origin  : ", EVENTHASH['NOEVENT'], 107, 210, 360, 18, NOISEHASH['Uoffset'].val, -10000., 10000.0 , 0,
        "X Origin of the noise")
    NOISEHASH['Voffset'] = Draw.Slider(
        "Y Origin  : ", EVENTHASH['NOEVENT'], 107, 190, 360, 18, NOISEHASH['Voffset'].val, -10000., 10000.0 , 0,
        "Y Origin of the noise")
    if (NOISEHASH['Map'].val!=0):
        NOISEHASH['Woffset'] = Draw.Slider(
            "Z Origin  : ", EVENTHASH['NOEVENT'], 107, 170, 360, 18, NOISEHASH['Woffset'].val, -10000., 10000.0 , 0,
            "Z Origin of the noise")

    NOISEHASH['UVsize'] = Draw.Slider(
        "Input Sc : ", EVENTHASH['NOEVENT'], 107, 150, 160, 18, NOISEHASH['UVsize'].val, -10., 10.0 , 0,
        "Scale of the coordinates for the noise input")
    NOISEHASH['Zsize'] = Draw.Slider(
        "Alt Sc : ", EVENTHASH['NOEVENT'], 270, 150, 160, 18, NOISEHASH['Zsize'].val, 0.0, 10.0 , 0,
        "Scaling for the noise output")

	
    if (NOISEHASH['Function'].val>=1 and NOISEHASH['Function'].val<=4):
        NOISEHASH['H'] = Draw.Slider(
            "H : ", EVENTHASH['NOEVENT'], 107, 130, 160, 18, NOISEHASH['H'].val, 0.0, 2.0 , 0,
            "Fractal Increment")
        NOISEHASH['Lacu'] = Draw.Slider(
            "Lacu : ", EVENTHASH['NOEVENT'], 270, 130, 160, 18, NOISEHASH['Lacu'].val, 0.0, 6.0 , 0,
            "Lacunarity")

    if (NOISEHASH['Function'].val>=1 and NOISEHASH['Function'].val<=5):
        NOISEHASH['Octs'] = Draw.Slider(
            "Octs : ", EVENTHASH['NOEVENT'], 107, 110, 160, 18, NOISEHASH['Octs'].val, 0.0, 16.0 , 0,
            "Octaves")

    if (NOISEHASH['Function'].val>=3 and NOISEHASH['Function'].val<=4):
        NOISEHASH['Ofst'] = Draw.Slider(
            "Ofst : ", EVENTHASH['NOEVENT'], 270, 110, 160, 18, NOISEHASH['Ofst'].val, 0.0, 6.0 , 0,
            "Offset")
        NOISEHASH['Gain'] = Draw.Slider(
            "Gain : ", EVENTHASH['NOEVENT'], 107, 90, 160, 18, NOISEHASH['Gain'].val, 0.0, 6.0 , 0,
            "Gain")

    if (NOISEHASH['Function'].val==5):
        NOISEHASH['Hard'] = Draw.Toggle(
            "Hard : ", EVENTHASH['NOEVENT'], 270, 90, 160, 18, NOISEHASH['Hard'].val, 
            "Soft or Hard noise?")
        NOISEHASH['Ampl'] = Draw.Slider(
            "Ampl : ", EVENTHASH['NOEVENT'], 107, 70, 160, 18, NOISEHASH['Ampl'].val, 0.0, 6.0 , 0,
            "Amplitude Scale")
        NOISEHASH['Freq'] = Draw.Slider(
            "Freq : ", EVENTHASH['NOEVENT'], 270, 70, 160, 18, NOISEHASH['Freq'].val, 0.0, 6.0 , 0,
            "Frequency Scale")

    if (NOISEHASH['Function'].val==6):
        NOISEHASH['Metric'] = Draw.Menu(
            "Voronoi Metric%t|Distance%x0|Distance Sq.%x1|Manhattan%x2|Chebychev%x3|Minkowsky half%x4|Minkowsky four%x5|Minkowsky%x6",
            EVENTHASH['REDRAW'], 107, 50, 160, 18,NOISEHASH['Metric'].val)	
        NOISEHASH['Exp'] = Draw.Slider(
            "Exp : ", EVENTHASH['NOEVENT'], 270, 50, 160, 18, NOISEHASH['Freq'].val, 0.0, 6.0 , 0,
            "Exponent")

#############################################################
# CONTEXT 2 GUI                                             #
#############################################################
def Context2GUI():
    global EVENTHASH
    global FILTERSHASH

    BGL.glRasterPos2d(8, 425)
    Draw.Text("Noise Filters:")
	
    FILTERSHASH['Invert'] = Draw.Toggle(
        "Invert",EVENTHASH['NOEVENT'],10,400,80,18,FILTERSHASH['Invert'].val,
        "Inverts the height z = -z")

    BGL.glRasterPos2d(45, 384)
    Draw.Text("V")
	
    FILTERSHASH['Exp'] = Draw.Toggle(
        "Exp",EVENTHASH['NOEVENT'],10,360,80,18,FILTERSHASH['Exp'].val,
        "Exponential filter z = a * exp(b*z + c)")
    FILTERSHASH['ExpPa'] = Draw.Number(
        "a: ", EVENTHASH['NOEVENT'], 90, 360, 90, 18, FILTERSHASH['ExpPa'].val, -10.0, 10.0, 
        "Filter amplitude")
    FILTERSHASH['ExpPb'] = Draw.Number(
        "b: ", EVENTHASH['NOEVENT'], 180, 360, 90, 18, FILTERSHASH['ExpPb'].val, -10.0, 10.0, 
	"Filter exponent")
    FILTERSHASH['ExpPc'] = Draw.Number(
        "c: ", EVENTHASH['NOEVENT'], 270, 360, 90, 18, FILTERSHASH['ExpPc'].val, -10.0, 10.0, 
	"Filter offset")

    BGL.glRasterPos2d(45, 344)
    Draw.Text("V")
	
    FILTERSHASH['Poly'] = Draw.Toggle(
        "Poly",EVENTHASH['NOEVENT'],10,320,80,18,FILTERSHASH['Poly'].val,
        "Exponential filter z = a + b*z + c*z^2 +d*z^3")
    FILTERSHASH['PolyPa'] = Draw.Number(
        "a: ", EVENTHASH['NOEVENT'], 90, 320, 90, 18, FILTERSHASH['PolyPa'].val, -100.0, 100.0, 
        "0th order polynomial coefficients")
    FILTERSHASH['PolyPb'] = Draw.Number(
        "b: ", EVENTHASH['NOEVENT'], 180, 320, 90, 18, FILTERSHASH['PolyPb'].val, -100.0, 100.0, 
        "1st order polynomial coefficient")
    FILTERSHASH['PolyPc'] = Draw.Number(
        "c: ", EVENTHASH['NOEVENT'], 270, 320, 90, 18, FILTERSHASH['PolyPc'].val, -100.0, 100.0, 
        "2nd order polynomial coefficient")
    FILTERSHASH['PolyPd'] = Draw.Number(
        "d: ", EVENTHASH['NOEVENT'], 360, 320, 90, 18, FILTERSHASH['PolyPd'].val, -100.0, 100.0, 
        "3rd order polynomial coefficient")

    BGL.glRasterPos2d(45, 304)
    Draw.Text("V")

    FILTERSHASH['StepH'] = Draw.Toggle(
        "H Step",EVENTHASH['NOEVENT'],10,280,80,18,FILTERSHASH['StepH'].val,
        "Step function, see doc")
    FILTERSHASH['StepHPx0']  = Draw.Number(
        "x0: ", EVENTHASH['NOEVENT'], 90, 280, 90, 18, FILTERSHASH['StepHPx0'].val, -100.0, 100.0, 
        "Filter center position")
    FILTERSHASH['StepHPy0'] = Draw.Number(
        "y0: ", EVENTHASH['NOEVENT'], 180, 280, 90, 18, FILTERSHASH['StepHPy0'].val, -100.0, 100.0, 
        "Filter center quote")
    FILTERSHASH['StepHPw'] = Draw.Number(
        "w: ", EVENTHASH['NOEVENT'], 270, 280, 90, 18, FILTERSHASH['StepHPw'].val, 0.0, 100.0, 
        "Filter flat area width")

    FILTERSHASH['StepHPmm1'] = Draw.Number(
        "m-: ", EVENTHASH['NOEVENT'], 90, 260, 90, 18, FILTERSHASH['StepHPmm1'].val, 0.0, 100.0,
        "Filter steepness (on the left)")
    FILTERSHASH['StepHPmp1'] = Draw.Number(
        "m+: ", EVENTHASH['NOEVENT'], 180, 260, 90, 18, FILTERSHASH['StepHPmp1'].val, 0.0, 100.0, 
        "Filter steepness (on the right)")
    FILTERSHASH['StepHPs'] = Draw.Number(
        "Smooth: ", EVENTHASH['NOEVENT'], 270, 260, 90, 18, FILTERSHASH['StepHPs'].val, 0.0, 100.0, 
        "Filter smoothness")


    BGL.glRasterPos2d(45, 244)
    Draw.Text("V")

    FILTERSHASH['StepV'] = Draw.Toggle(
        "V Step",EVENTHASH['NOEVENT'],10,220,80,18,FILTERSHASH['StepV'].val,
        "Step function, see doc")
    FILTERSHASH['StepVPx0'] = Draw.Number(
        "x0: ", EVENTHASH['NOEVENT'], 90, 220, 90, 18, FILTERSHASH['StepVPx0'].val, -100.0, 100.0, 
        "Filter center position")
    FILTERSHASH['StepVPy0'] = Draw.Number(
        "y0: ", EVENTHASH['NOEVENT'], 180, 220, 90, 18, FILTERSHASH['StepVPy0'].val, -100.0, 100.0, 
        "Filter center quote")
    FILTERSHASH['StepVPw'] = Draw.Number(
        "w: ", EVENTHASH['NOEVENT'], 270, 220, 90, 18, FILTERSHASH['StepVPw'].val, 0.0, 100.0, 
        "Filter vertical area height")

    FILTERSHASH['StepVPmm1'] = Draw.Number(
        "m-: ", EVENTHASH['NOEVENT'], 90, 200, 90, 18, FILTERSHASH['StepVPmm1'].val, 0.0, 100.0, 
        "Filter steepness (on the left)")
    FILTERSHASH['StepVPmp1'] = Draw.Number(
        "m+: ", EVENTHASH['NOEVENT'], 180, 200, 90, 18, FILTERSHASH['StepVPmp1'].val, 0.0, 100.0, 
        "Filter steepness (on the right)")
    FILTERSHASH['StepVPs'] = Draw.Number(
        "Smooth: ", EVENTHASH['NOEVENT'], 270, 200, 90, 18, FILTERSHASH['StepVPs'].val, 0.0, 100.0, 
        "Filter smoothness")
   
#############################################################
# CONTEXT 3 GUI                                             #
#############################################################
def Context3GUI():
    global EVENTHASH
    global LANDMARKSHASH

    BGL.glRasterPos2d(8, 425)
    Draw.Text("Cospicuous Landmarks:")

    LANDMARKSHASH['Crater'] = Draw.Number(
        "Craters No.",EVENTHASH['NOEVENT'],10,400,120,18,LANDMARKSHASH['Crater'].val, 0, 10000,
        "Add a given number of craters around")
    LANDMARKSHASH['Cseed'] = Draw.Number(
        "Seed",EVENTHASH['NOEVENT'],130,400,120,18,LANDMARKSHASH['Cseed'].val, 0, 10000,
        "Seed for the random distribution")
		
    LANDMARKSHASH['Cradius'] = Draw.Number(
        "r: ", EVENTHASH['NOEVENT'], 130, 380, 120, 18, LANDMARKSHASH['Cradius'].val, 0.0, 100.0, 
        "Mean crater radius")
    LANDMARKSHASH['Cheight'] = Draw.Number(
        "h: ", EVENTHASH['NOEVENT'], 130, 360, 120, 18, LANDMARKSHASH['Cheight'].val, 0.0, 100.0, 
        "Mean height of crater rim over surrounding planes")
    LANDMARKSHASH['Cdepth']  = Draw.Number(
        "d: ", EVENTHASH['NOEVENT'], 130, 340, 120, 18, LANDMARKSHASH['Cdepth'].val, 0.0, 100.0, 
        "Mean depth of bottom of crater beneath its rim")
    LANDMARKSHASH['Csteep']  = Draw.Number(
        "s: ", EVENTHASH['NOEVENT'], 130, 320, 120, 18, LANDMARKSHASH['Csteep'].val, 0.0, 10.0, 
        "Mean steepness of crater border (higher->steeper)")

    LANDMARKSHASH['CradiusV']= Draw.Number(
        "rV: ", EVENTHASH['NOEVENT'], 250, 380, 120, 18, LANDMARKSHASH['CradiusV'].val, 0.0, 100.0, 
        "Radius variance")
    LANDMARKSHASH['CheightV']= Draw.Number(
        "hV: ", EVENTHASH['NOEVENT'], 250, 360, 120, 18, LANDMARKSHASH['CheightV'].val, 0.0, 100.0, 
        "Height variance")
    LANDMARKSHASH['CdepthV'] = Draw.Number(
        "dV: ", EVENTHASH['NOEVENT'], 250, 340, 120, 18, LANDMARKSHASH['CdepthV'].val, 0.0, 100.0, 
        "Depth variance")
    LANDMARKSHASH['CsteepV'] = Draw.Number(
        "sV: ", EVENTHASH['NOEVENT'], 250, 320, 120, 18, LANDMARKSHASH['CsteepV'].val, 0.0, 100.0, 
        "Steepness variance")


    LANDMARKSHASH['Peaks']  = Draw.Number(
        "Peaks No.",EVENTHASH['NOEVENT'],10,280,120,18,LANDMARKSHASH['Peaks'].val, 0, 10000,
        "Add a given number of peaks around")
    LANDMARKSHASH['Pseed']   = Draw.Number(
        "Seed",EVENTHASH['NOEVENT'],130,280,120,18,LANDMARKSHASH['Pseed'].val, 0, 10000,
        "Seed for the random distribution")
		
    LANDMARKSHASH['Pradius']    = Draw.Number(
        "r: ", EVENTHASH['NOEVENT'], 130, 260, 120, 18, LANDMARKSHASH['Pradius'].val, 0.0, 100.0, 
        "Mean peak radius")
    LANDMARKSHASH['Pheight']    = Draw.Number(
        "h: ", EVENTHASH['NOEVENT'], 130, 240, 120, 18, LANDMARKSHASH['Pheight'].val, 0.0, 100.0, 
        "Mean height of peak over surrounding planes")
    LANDMARKSHASH['Ptopsteep']  = Draw.Number(
        "mt: ", EVENTHASH['NOEVENT'], 130, 220, 120, 18, LANDMARKSHASH['Ptopsteep'].val, -100.0, 100.0, 
        "Mean steepness at top of peak")
    LANDMARKSHASH['Pfootsteep'] = Draw.Number(
        "mb: ", EVENTHASH['NOEVENT'], 130, 200, 120, 18, LANDMARKSHASH['Pfootsteep'].val, -100.0, 10.0, 
        "Mean steepness at the bottom of the peak")

    LANDMARKSHASH['PradiusV']   = Draw.Number(
        "rV: ", EVENTHASH['NOEVENT'], 250, 260, 120, 18, LANDMARKSHASH['PradiusV'].val, 0.0, 100.0, 
        "Radius variance")
    LANDMARKSHASH['PheightV']   = Draw.Number(
        "hV: ", EVENTHASH['NOEVENT'], 250, 240, 120, 18, LANDMARKSHASH['PheightV'].val, 0.0, 100.0, 
        "Height variance")
    LANDMARKSHASH['PtopsteepV'] = Draw.Number(
        "mtV: ", EVENTHASH['NOEVENT'], 250, 220, 120, 18, LANDMARKSHASH['PtopsteepV'].val, 0.0, 100.0, 
        "Top steepness variance")
    LANDMARKSHASH['PfootsteepV']= Draw.Number(
        "mbV: ", EVENTHASH['NOEVENT'], 250, 200, 120, 18, LANDMARKSHASH['PfootsteepV'].val, 0.0, 100.0, 
        "Bottom steepness variance")

#############################################################
# CONTEXT 4 GUI                                             #
#############################################################
def Context4GUI():
    global EVENTHASH
    global POSTPROHASH1,POSTPROHASH2

    BGL.glRasterPos2d(8, 425)
    Draw.Text("Full Mesh Limited Layers:")

    for i in range(6):
        Draw.Button("GO", POSTPROHASH1['DOEV']+i, 8, 400-i*20,60,18, "Apply this PostPro to the selected item(s)")
 	POSTPROHASH1['Zmin'][i] = Draw.Number(
            "z-: ", POSTPROHASH1['ZEV']+i, 68, 400-i*20, 80, 18, POSTPROHASH1['Zmin'][i].val, -100.0, 100.0, 
            "Minimum Z at which layer starts")
 	POSTPROHASH1['Zmax'][i] = Draw.Number(
            "z+: ", POSTPROHASH1['ZEV']+i, 148, 400-i*20, 80, 18, POSTPROHASH1['Zmax'][i].val, -100.0, 100.0, 
            "Maximum Z at which layer starts")
	POSTPROHASH1['Smin'][i] = Draw.Number(
            "s-: ", POSTPROHASH1['SEV']+i, 228, 400-i*20, 80, 18, POSTPROHASH1['Smin'][i].val, 0.0, 1000.0, 
            "Minimum slope at which layer exists")
	POSTPROHASH1['Smax'][i] = Draw.Number(
            "s+: ", POSTPROHASH1['SEV']+i, 308, 400-i*20, 80, 18, POSTPROHASH1['Smax'][i].val, 0.0, 1000.0, 
            "Maximum slope at which layer exists")

    BGL.glRasterPos2d(8, 225)
    Draw.Text("Vertex Only Limited Layers:")

    for i in range(6):
        Draw.Button("GO", POSTPROHASH2['DOEV']+i, 8, 200-i*20,60,18, "Apply this PostPro to the selected item(s)")
        POSTPROHASH2['Zmin'][i] = Draw.Number(
            "z-: ", POSTPROHASH2['ZEV']+i, 68, 200-i*20, 80, 18, POSTPROHASH2['Zmin'][i].val, -100.0, 100.0, 
            "Minimum Z at which layer starts")
	POSTPROHASH2['Zmax'][i] = Draw.Number(
            "z+: ", POSTPROHASH2['ZEV']+i, 148, 200-i*20, 80, 18, POSTPROHASH2['Zmax'][i].val, -100.0, 100.0, 
            "Maximum Z at which layer starts")
	POSTPROHASH2['Smin'][i] = Draw.Number(
            "s-: ", POSTPROHASH2['SEV']+i, 228, 200-i*20, 80, 18, POSTPROHASH2['Smin'][i].val, 0.0, 1000.0, 
            "Minimum slope at which layer exists")
	POSTPROHASH2['Smax'][i] = Draw.Number(
            "s+: ", POSTPROHASH2['SEV']+i, 308, 200-i*20, 80, 18, POSTPROHASH2['Smax'][i].val, 0.0, 1000.0, 
            "Maximum slope at which layer exists")
	POSTPROHASH2['Verts'][i] = Draw.Number(
            "V: ", EVENTHASH['NOEVENT'], 388, 200-i*20, 80, 18, POSTPROHASH2['Verts'][i].val, 0.0, 100.0, 
            "Maximum slope at which layer exists")


#############################################################
# ERRORDIALOG                                               #
#############################################################
def ErrorDialog():
    global ErrorMessage

    global EVENTHASH
    
    BGL.glClearColor(0.5, 0.5, 0.5, 0.0)
    BGL.glClear(BGL.GL_COLOR_BUFFER_BIT)
    BGL.glColor3f(0, 0, 0) 			# Black
    BGL.glRectf(2, 100, 482, 320)
    BGL.glColor3f(0.6, 0.1, 0.1) 		# Dark Red
    BGL.glRectf(4, 282, 480, 318)
    BGL.glRectf(4, 102, 480, 262)

    #############################################################
    # Common Header                                             #
    #############################################################

    BGL.glColor3f(1., 1., 0.6)
    BGL.glRasterPos2d(10, 305)
    Draw.Text("Blender World Forge v. "+VERSION)
    BGL.glRasterPos2d(10, 289)
    Draw.Text("(C) June 2003 2004 Stefano Selleri <a.k.a. S68>")
    BGL.glColor3f(1.0, 1.0, 0.4)
    w = Draw.GetStringWidth('ERROR','normal')
    BGL.glRasterPos2d(240-w/2, 269)
    Draw.Text("ERROR")
    Draw.Button("OK", EVENTHASH['DLG_OK'], 407, 287, 70, 24)

    EM = ErrorMessage
    i = 0
    BGL.glColor3f(1., 1., 0.6)
    while (EM != ''):
        s = EM[0:64]
        EM = EM[64:]
        try:
            cr = re.search(r'\n',s).start()
        except:
            cr = -1

        if( cr >- 1 ):
            EM = s[cr+1:]+EM
            s = s[0:cr]
        
        BGL.glRasterPos2d(10, 249-i*15)
        Draw.Text(s)
        i = i + 1
        
    
#############################################################
# EVENT HANDLER                                             #
#############################################################
def event(evt, val): 
	if (evt== Draw.QKEY and not val):
		Draw.Exit()

def bevent(evt):
    global EVENTHASH
    global ErrorMessage
    global CONTEXTHASH
    global POSTPROHASH1,POSTPROHASH2

    if   (evt == EVENTHASH['REDRAW']):
	Draw.Redraw()
    elif (evt == EVENTHASH['EXIT']):
	Draw.Exit()
    elif (evt == EVENTHASH['DO']):
        print 'Starting Computation'
	PreCalculateFilters()
	PreCrater()
	PrePeaks()
	DoTheTerraform()
	Draw.Redraw()
    elif (evt == EVENTHASH['SAVE']):
        Window.FileSelector (BWFSave, 'SAVE FILE:')
    elif (evt == EVENTHASH['LOAD']):
        Window.FileSelector (BWFLoad, 'LOAD FILE:')
    elif (evt == EVENTHASH['DLG_OK']):
        ErrorMessage=''
        Draw.Redraw()

    #############################################################
    # Interface CONTEXT Swapping                                #
    #############################################################
    elif (evt == CONTEXTHASH['NoiseEV']):
	CONTEXTHASH['Noise'].val     = 1
	CONTEXTHASH['Filters'].val   = 0
	CONTEXTHASH['Landmarks'].val = 0
	CONTEXTHASH['PostPro'].val   = 0
	Draw.Redraw()
    elif (evt == CONTEXTHASH['FiltersEV']):
	CONTEXTHASH['Noise'].val     = 0
	CONTEXTHASH['Filters'].val   = 1
	CONTEXTHASH['Landmarks'].val = 0
	CONTEXTHASH['PostPro'].val   = 0
	Draw.Redraw()
    elif (evt == CONTEXTHASH['LandmarksEV']):
	CONTEXTHASH['Noise'].val     = 0
	CONTEXTHASH['Filters'].val   = 0
	CONTEXTHASH['Landmarks'].val = 1
	CONTEXTHASH['PostPro'].val   = 0
	Draw.Redraw()
    elif (evt == CONTEXTHASH['PostProEV']):
	CONTEXTHASH['Noise'].val     = 0
	CONTEXTHASH['Filters'].val   = 0
	CONTEXTHASH['Landmarks'].val = 0
	CONTEXTHASH['PostPro'].val   = 1
	Draw.Redraw()

    #############################################################
    # Layer limit check                                         #
    #############################################################

    elif (evt >= POSTPROHASH1['DOEV'] and evt <POSTPROHASH1['ZEV']):
        DoThePostPro1(evt-POSTPROHASH1['DOEV'])    
    elif (evt >= POSTPROHASH1['ZEV'] and evt <POSTPROHASH1['SEV']):
        i = evt - POSTPROHASH1['ZEV']
        if (POSTPROHASH1['Zmin'][i].val>POSTPROHASH1['Zmax'][i].val):
            POSTPROHASH1['Zmin'][i].val=POSTPROHASH1['Zmax'][i].val
        Draw.Redraw()
    elif (evt >= POSTPROHASH1['SEV'] and evt <POSTPROHASH2['DOEV']):
        i = evt - POSTPROHASH1['SEV']
        if (POSTPROHASH1['Smin'][i].val>POSTPROHASH1['Smax'][i].val):
            POSTPROHASH1['Smin'][i].val=POSTPROHASH1['Smax'][i].val
        Draw.Redraw()
            
    elif (evt >= POSTPROHASH2['DOEV'] and evt <POSTPROHASH2['ZEV']):
        DoThePostPro2(evt-POSTPROHASH2['DOEV'])    
    elif (evt >= POSTPROHASH2['ZEV'] and evt <POSTPROHASH2['SEV']):
        i = evt - POSTPROHASH2['ZEV']
        if (POSTPROHASH2['Zmin'][i].val>POSTPROHASH2['Zmax'][i].val):
            POSTPROHASH2['Zmin'][i].val=POSTPROHASH2['Zmax'][i].val
        Draw.Redraw()
    elif (evt >= POSTPROHASH2['SEV'] and evt <POSTPROHASH2['SEV']+10):
        i = evt - POSTPROHASH2['SEV']
        if (POSTPROHASH2['Smin'][i].val>POSTPROHASH2['Smax'][i].val):
            POSTPROHASH2['Smin'][i].val=POSTPROHASH2['Smax'][i].val
        Draw.Redraw()
    else:
        print 'Unmatched Event',evt

  	    
#############################################################
# Registering all functions                                 #
#############################################################

Draw.Register(draw, event, bevent)
