from visual import *
from random import random

import time,sys,thread


spinUnitCellW = display(title='Spin Unit Cell', width=410, height=310, x=20, y=630, center=(0,0,0), background=(.05,.1,.1), visible=1)
spinUnitCellW.fov = pi/90.0
spinUnitCellW.lights = [vector(.5,.5,.5), vector(-.5,-.5,-.5)]

spinUnitCellW.up = (0,0,1)
spinUnitCellW.forward = (0.0,0.5,-1.0)
spinUnitCellW.range = 2.0
spinUnitCellW.autoscale = 0

spinUnitCellW.select()




class Spin:
    vector = arrow(visible=0)
    
    def __init__(self):
        self.vector = arrow(visible=0)


 
class VisualUnitCell:
    visualArray = []

    toggleVectorsVar = 1
       
    def __init__(self, nSpinsX, nSpinsY):
        self.nSpinsX = nSpinsX
        self.nSpinsY = nSpinsY

        visualArray = [ None ] * nSpinsX                               # a vector of null elements, nSpinsX long
        for x in range(nSpinsX):
            visualArray[x] = [0] * nSpinsY                             # a vector of zeros nSpinsY long
            for y in range(nSpinsY):
                visualArray[x][y] = Spin()
               
        self.visualArray = visualArray



    def addVectors(self,numericArray):
        for x in range(self.nSpinsX):
            for y in range(self.nSpinsY):
                self.visualArray[x][y].vector = arrow(pos=(x-self.nSpinsX/2.0+1/2.0-numericArray[x][y].spin[0]/2.0,y-self.nSpinsY/2.0+1/2.0-numericArray[x][y].spin[1]/2.0,0.0), axis=numericArray[x][y].spin, color=(1-((x+y)%2),.3*(x+y+2.0)/((x+1.0)*(y+1.0)),((x+y)%2)), shaftwidth=0.15, visible=self.toggleVectorsVar)

    def updateVectors(self,numericArray):
        for x in range(self.nSpinsX):
            for y in range(self.nSpinsY):
                self.visualArray[x][y].vector.pos = vector(x-self.nSpinsX/2.0+1/2.0,y-self.nSpinsY/2.0+1/2.0,0.0) - numericArray[x][y].spin/2.0
                self.visualArray[x][y].vector.axis = numericArray[x][y].spin

    def toggleVectors(self):
        self.toggleVectorsVar = (self.toggleVectorsVar+1)%2
        
        for x in range(self.nSpinsX):
            for y in range(self.nSpinsY):
                self.visualArray[x][y].vector.visible = self.toggleVectorsVar
           
    def getArray(self):                         # handy, since we dont want to have to know the name of the object's actual variable!
        return self.visualArray
















