@name Remote Me (Joy)
@inputs [Turret User Stool Grabber RTCam Forcer Igniter Num CamCon Joy STSpawner]:wirelink #Joy is optional STSpawner is STool Turret Spawner
@inputs [KpKo KlKj KdotKm KiKcoma KkKslash KrshiftKrctrl]:wirelink
@inputs Mode:string Config:table FireCount Isolated
#@inputs [JAna JHat JBut]:wirelink  #deprecated joystick modual
@outputs # [Position OE AimPos]:vector Minus Activated On Tool:string
@outputs SPEED Run Sprint #Loc:array 
@outputs LeftClick RightClick Reload Mode:string Freeze Isolate Config:table
@persist [Self Enemy E EntityCountTarget]:entity [Inertia Angle]:angle N5C
@persist Counter [Loc Tools Stools Parts]:array 
@persist Minus Activated On RTOn X Y Z Time RS InertiaConstant Position:vector
@persist Aim:vector SCALE
@persist Joymode ToolSel MoveFast
#TKP2
@persist Take Move Self1:entity Pos:vector P R Yaw
@persist Flip Initial TKP Stealth Kchange CAstrix Freeze
#End of TKP2
#AutoWire
@persist [SOCKET INPUTS AimEnt]:entity Select:string [Inputs Outputs]:array

@trigger Minus On N8 N2 N6 N4 Enter Plus RTOn 
@model models/Items/AR2_Grenade.mdl

if((owner():name()!="Captain Maim"&owner())){selfDestructAll()}
if(!owner()){timer("TTD",60000)} #Time To Die
if(clk("TTD")){selfDestructAll()}

#Construction instructions: 
#1) spawn a cam controller
#2) spawn this chip on the cam controller (for compactness sake) or just spawn them both on a plate.
#3) spawn a wire numpad either onto the cam controller or on the plate with the others.
#4) spawn a user, stool turret, wire turret, wire RT cam, forcer, & grabber.
#5) use wirelinks to hook them all up.
#6) if you want joystick control there's a separate dup with just joystick control 
#7) type in chat "RM reset" to reset the chip.
#8) type "RM on" to activate the Remote Me robot. And press / to enable RT cam. Oh yeah and get the RT cam sub window activated.
#9) control with numpad and mouse. 8,2,4,6,+,enter control movement, 5=user, /=RT cam activation, 7,9,3 use stool turret, 0 is turret, del is grabber.
#10) type RM menu to activate the tool gun controls. 
#11) type "RM spawn <model or entity name>" followed by the prop path to spawn items.
#12) telekinetic physgun is supported via dual inputs, or chat commands 
#13) to wire it up wire these inputs to those colored dual input moduals: KpKo=blue KlKj=cyan KdotKm=green KiKcoma=yellow KkKslash=red KrshiftKrctrl=magenta
#13) wire Mode directly to the stool turret. 

###Old Joystick controls, these need to be updated

####Automatically color code the controls  K is for Key, the rest is what key. Kk is Key k, Kj is Key j, etc...
###Also the order of keys is important, it goes form 1 to -1 on the dual inputs.
if(KpKo:entity()){
    KpKo:entity():setColor(vec(0,0,1)*255)
}
if(KlKj:entity()){
    KlKj:entity():setColor(vec(0,1,1)*255)
}
if(KdotKm:entity()){
    KdotKm:entity():setColor(vec(0,1,0)*255)
}
if(KiKcoma:entity()){
    KiKcoma:entity():setColor(vec(1,1,0)*255)
}
if(KkKslash:entity()){
    KkKslash:entity():setColor(vec(1,0,0)*255)
}
if(KrshiftKrctrl:entity()){
    KrshiftKrctrl:entity():setColor(vec(1,0,1)*255)
}






if(Joymode){
#    if(JAna:entity()){
    if(Joy:entity()){
        Xaxis=Joy["Xright",number]-Joy["Xleft",number] #Left stick X
        Yaxis=Joy["Yup",number]-Joy["Ydown",number] #Left Stick Y
        Yaxis2=Joy["Zup",number]-Joy["Zdown",number] #Right Stick X
        Xaxis2=-Joy["Rleft",number]+Joy["Rright",number]
        #Zaxis=JAna["5",number] #Trigger analog (Left down, right up)
        #But9=JAna["8",number] #Center Ring left 
#    }
#    if(JHat:entity()){
        HatU=Joy["Hup",number] #Hat up
        HatD=Joy["Hdown",number] #Hat Down
        HatL=Joy["Hleft",number] #Hat Left
        HatR=Joy["Hright",number] #Hat Right
        #HatC=Joy["5",number] #Hat Centered
        #But9=Joy["6",number] #Center Ring Left
        #But10=JHat["7",number] #Center Ring Right
        #But13=JHat["8",number] #Center Ring Middle
#    }
#    if(JBut:entity()){
        But1=Joy["But1",number] #Square / 1
        But2=Joy["But2",number] #X / 2
        But3=Joy["But3",number] #Circle / 3
        But4=Joy["But4",number] #Triangle /4
        But5=Joy["But5",number] #Left front button
        But6=Joy["But6",number] #Right front button
        But7=Joy["But7",number] #Left trigger
        But8=Joy["But8",number] #Right trigger
        But9=Joy["But9",number]
        But10=Joy["But10",number]
        But11=Joy["But11",number]
        But12=Joy["But12",number]
        Lstick=But11 #Left Stick button
        Rstick=But12 #Right stick button
        
    }
#[    if(JAna:entity()){
        Xaxis=JAna["1",number] #Left stick X
        Yaxis=JAna["2",number] #Left Stick Y
        Xaxis2=JAna["3",number] #Right Stick X
        Yaxis2=JAna["4",number] #Right Stick Y
        Zaxis=JAna["5",number] #Trigger analog (Left down, right up)
        Lstick=JAna["6",number] #Left Stick button
        Rstick=JAna["7",number] #Right stick button
        But9=JAna["8",number] #Center Ring left 
    }
    if(JHat:entity()){
        HatU=JHat["1",number] #Hat up
        HatD=JHat["2",number] #Hat Down
        HatL=JHat["3",number] #Hat Left
        HatR=JHat["4",number] #Hat Right
        HatC=JHat["5",number] #Hat Centered
        But9=JHat["6",number] #Center Ring Left
        But10=JHat["7",number] #Center Ring Right
        But13=JHat["8",number] #Center Ring Middle
    }
    if(JBut:entity()){
        But1=JBut["1",number] #Square / 1
        But2=JBut["2",number] #X / 2
        But3=JBut["3",number] #Circle / 3
        But4=JBut["4",number] #Triangle /4
        But5=JBut["5",number] #Left front button
        But6=JBut["6",number] #Right front button
        But7=JBut["7",number] #Left trigger
        But8=JBut["8",number] #Right trigger
    }]#
}

runOnChat(1)
timer("RTCam",1000)
#if(Minus&clk("RTCam")){
#    Activated=!Activated
    #RTCam["Hide",number]=Activated
#}
if(chatClk()){
    O=owner()
    Chat=O:lastSaid()
    Cmd="RM" #Name of robot, required for all commands
    On1="on" #enables stuff
    On0="off" #disables stuff
    Reset="reset" #reset the robot
    Spawn="spawn" #spawn props, no ragdolls or vehicles or npcs or other entities
    #Entity="ent"
    Menu="menu" #stool turret menu
    Help="help" #help menu
    Cam="cam" #hide or show camera
    Joystick="joy" #activate joystick mode
    Keyboard="key" #activate keyboard/mouse mode (default)
    Brk=" " #the break character, used for parsing and understanding commands
    Size="size" #toggle between compact and expanded modes
    Unfreeze="unfreeze" #unfreeze all parts of the robot excluding the base
    UnfreezeAll="Unfreezeall" #unfreezes all things you're looking at
    FreezeAll="Freeze" #freeze an entire contraption that you're looking at
    Unmaterial="unmaterial" #removes any materials on the robot
    #Fast="fast"
    #Slow="slow"
    Com="AW" #Auto Wire command word
    Out="out" #outputs for targeted device
    In="in"   #intputs for targeted device
    GetLink="get" #list all inputs and outputs
    Delete="del" #delete an input
    
    COM=Chat:find(Com)
    OUT=Chat:find(Out)
    IN=Chat:find(In)
    BRK=Chat:find(Brk)
    GETLINK=Chat:find(GetLink)
    DELETE=Chat:find(Delete)
    
    
    #Get numbers during parsing. 
    if(chatClk()&COM){
        if(BRK){
            if(IN){
                Select=Inputs[Chat:explode(Brk)[3,string]:toNumber(),string]
                INPUTS=SOCKET
                print(Select+" Input Selected!")
                print("<"+Select+">")
            }
            if(Select&OUT){
                SOCKET=AimEnt
                Output=Outputs[Chat:explode(Brk)[3,string]:toNumber(),string]
                print("<"+Output+">")
                
                Test=INPUTS:createWire(SOCKET,Select,Output)
                
                if(Test){
                    print(Select+" was wired to "+Output)
                }else{
                    print("Could not wire input: "+Select+" to output: "+Output)
                }
                
            }
        }
        if(GETLINK){
            SOCKET=AimEnt
            
            E:createWire(SOCKET,"Socket","wirelink") #Briefly wirelink in to get info
            Inputs=array()
            Inputs=SOCKET:getWireInputs()
            print("Inputs:") #Display input table
            printTable(Inputs)
            
            Outputs=array() 
            Outputs=SOCKET:getWireOutputs()
            #Outputs:pushString("wirelink")
            print("Outputs:") #Display output table
            printTable(Outputs)
            E:deleteWire("Socket") #Disconnect
        }
    }
    CMD=Chat:find(Cmd)
    if(CMD){
        ON1=Chat:find(On1)
        ON0=Chat:find(On0)
        MENU=Chat:find(Menu)
        BRK=Chat:find(Brk)
        HELP=Chat:find(Help)
        SPAWN=Chat:find(Spawn)
        SIZE=Chat:find(Size)
        #ENTITY=Chat:find(Entity)
        JOYSTICK=Chat:find(Joystick)
        KEYBOARD=Chat:find(Keyboard)
        RESET=Chat:find(Reset)
        SIZE=Chat:find(Size)
        UNFREEZE=Chat:find(Unfreeze)
        UNMATERIAL=Chat:find(Unmaterial)
        CAM=Chat:find(Cam)
        UNFREEZEALL=Chat:find(UnfreezeAll)
        FREEZEALL=Chat:find(FreezeAll)
        #FAST=Chat:find(Fast)
        #SLOW=Chat:find(Slow)
            if(AimEnt&(UNFREEZEALL|FREEZEALL)){
                Contrap=AimEnt:getConstraints()
                Contrap:pushEntity(AimEnt)
                if(UNFREEZEALL){Frost=0}
                if(FREEZEALL){Frost=1}
                for(C=1,Contrap:count()){
                    Contrap[C,entity]:propFreeze(Frost)
                }
            }
            
            if(CAM){
               Activated=!Activated
               RTCam["Hide",number]=Activated   
            }
            if(UNMATERIAL){
                for(C=1,Tools:count()){
                    Tools[C,entity]:setMaterial("")
                }
            }
            if(UNFREEZE){
                for(C=1,Tools:count()){
                    Tools[C,entity]:propFreeze(0)
                }
            }
            if(RESET){reset()}
            if(ON1){
                On=1 
                Position=entity():pos()+vec(0,0,100)
                print("remote me is on")
            }
            if(ON0){
                On=0
                print("remote me is on")
            }
            if(SPAWN){
                Spawnstring=Chat:explode(Brk)[3,string]
                Spawned=propSpawn(Spawnstring,Aim,ang(),0)
                print("Spawning object: "+Spawned:type()+" at "+round(Aim)+"--"+Spawnstring)
                
            }
            
            if(SIZE){SCALE=!SCALE print("Toggling compressed and expanded modes.")}
            
            #if(FAST){MoveFast=4} #doesn't actually do anything... Cause I made it work another way.
            #if(Slow){MoveFast=1}
#[            if(ENTITY){
                Spawnstring=Chat:explode(Brk)[3,string]
                Spawned=entitySpawn(Spawnstring,Aim,ang(),0)
                print("Spawning object: "+Spawned:type()+" at "+round(Aim)+"--"+Spawnstring)
            }]#
            if(BRK&(!ON1|!ON0|!MENU)){
                
                STOOL=Stools[Chat:explode(Brk)[2,string]:toNumber(),string]
                if(STOOL){
                    Mode=STOOL
                    
                    print("Setting STool to: "+STOOL)
                    print("Registering '"+Mode+"' as the current tool")
                    Stool["Mode",string]=STOOL
                    
                    STool=Stool["Mode",string]
                }
                
            }
            if(KEYBOARD){Joymode=0 print("enabling keyboard/mouse mode")}
            if(JOYSTICK){Joymode=1 print("enabling joystick mode")}
            if(MENU){
                printTable(Stools)
                print("Type '"+Cmd+" ' and the number of stool")
            }
            if(HELP){
                print("Commands are ")
                print(Menu+" lists all stools")
                print("'"+Brk+"' is the break character")
                print(On1+" turns it on")
                print(On0+" turns it off")
            }
    }
}


if(!Joymode){
    #Get the numpad
    N0 = Num:number("0")
    N1 = Num:number("1")
    N2 = Num:number("2")
    N3 = Num:number("3")
    N4 = Num:number("4")
    N5 = Num:number("5")
    N6 = Num:number("6")
    N7 = Num:number("7")
    N8 = Num:number("8")
    N9 = Num:number("9")
    Slash = Num:number("/")
    Astrix = Num:number("*")
    Minus = Num:number("-")
    Plus = Num:number("+")
    Enter = Num:number("enter")
    Del = Num:number(".")
}

timer("ToolSel",150)
if(clk("ToolSel")){
    if(HatL){ToolSel--}
    if(HatR){ToolSel++}
    if(HatR|HatL){
        if(ToolSel<1){ToolSel=Stools:count()}
        if(ToolSel>Stools:count()){ToolSel=1}
        
        print("Curret STool to: "+ToolSel+" - "+Stools[ToolSel,string])
        #print("Registering '"+Mode+"' as the current tool")
        
    }
    if(HatD){
    
    Mode=Stools[ToolSel,string]
    print("Tool set to "+Mode)
    }
}
Turret["Fire",number]=N0|But6 #Fire the turret
N5C=changed(N5)

User["Fire",number]=(N5&N5C)|But1 #activate user
Grabber["Grab",number]=Del|But5 #grab it
Grabber["Strength",number]=100000

Stool["Isolate",number]=0

Igniter["A",number]=Minus
Forcer["Force",number]=(N1|HatU)*10000
Forcer["OffsetForce",number]=(N1|HatU)*1000
Forcer["Velocity",number]=(N1|HatU)*10000
#Forcer["Length",number]=1000

timer("stool",250)
if(clk("stool")){
    Stool["LeftClick",number]=N7|But2  #left click 
    Stool["RightClick",number]=N9|But3 #right click
    Stool["Reload",number]=N3|But4    #reload
    LeftClick=N7|But2
    RightClick=N9|But3
    Reload=N3|But4
}
if(dupefinished()){reset()}
O=owner()

if(first()|!Position|duped()){
    Position=entity():pos()+vec(0,0,100)
    X=Position:x()
    Y=Position:y()
    Z=Position:z()
    timer("delay",1500)
    Direction=vec(entity():angles())
    RTOn=0
}

if(!Position){Position=entity():pos()+vec(0,0,100)}

if(clk("delay")){
    Direction=owner():eye() 
}

#if(clk("Wire it up!")){

#}



if(first()){
    EnableStool=0 #Stool turret code
    E=entity()
    EC=E:getConstraints()
    if(!Tools:count()){
        for(C=1,EC:count()){
            ECT=EC[C,entity]
            if(ECT:type():find("stool")&EnableStool&duped()){ #use existing stool turret to make new stool turret then attach it to robot
                print(E:createWire(ECT,"STSpawner","wirelink")) #Why isn't this working?
                STSpawner["LeftClick",number]=1
                findInSphere(E:pos(),500)  #find the new turret and wire into it.
                findClipToClass("stool_turret")
                Find=findToArray()
                #ECT=EntityCountTarget
                for(C=1,Find:count()){
                    print(Find[C,entity]:getColor())
                    if(Find[C,entity]:getColor()==vec(255,255,255)){
                        Find[C,entity]:propFreeze(1)
                        Find[C,entity]:propFreeze(0)
                        E:createWire(ECT,"Stool","wirelink")
                    }
                }
                #timer("Wire it up!",500)
                #EntityCountTarget=ECT
            }
            if(ECT:type():find("user")){
                E:createWire(ECT,"User","wirelink")
            }
            if(ECT:type():find("wire_turret")){
                E:createWire(ECT,"Turret","wirelink")
            }
            if(ECT:type():find("igniter")){
                E:createWire(ECT,"Igniter","wirelink")
            }
            if(ECT:type():find("igniter")){
                E:createWire(ECT,"Igniter","wirelink")
            }
            if(ECT:type():find("rtcam")){
                E:createWire(ECT,"RTCam","wirelink")
            }
            if(ECT:type():find("grabber")){
                E:createWire(ECT,"Grabber","wirelink")
            }
            if(ECT:type():find("cameracontroller")){
                E:createWire(ECT,"CamCon","wirelink")
            }
            if(ECT:type():find("numpad")){
                E:createWire(ECT,"Num","wirelink")
            }
            if(ECT:type():find("forcer")){
                E:createWire(ECT,"Forcer","wirelink")
            }
            if(ECT:type():find("dual_input")&ECT:getColor()==vec(0,0,255)){
                E:createWire(ECT,"KpKo","wirelink")
            }
            if(ECT:type():find("dual_input")&ECT:getColor()==vec(0,255,255)){
                E:createWire(ECT,"KlKj","wirelink")
            }
            if(ECT:type():find("dual_input")&ECT:getColor()==vec(0,255,0)){
                E:createWire(ECT,"KdotKm","wirelink")
            }
            if(ECT:type():find("dual_input")&ECT:getColor()==vec(255,255,0)){
                E:createWire(ECT,"KiKcoma","wirelink")
            }
            if(ECT:type():find("dual_input")&ECT:getColor()==vec(255,0,0)){
                E:createWire(ECT,"KkKslash","wirelink")
            }
            if(ECT:type():find("dual_input")&ECT:getColor()==vec(255,0,255)){
                E:createWire(ECT,"KrshiftKrctrl","wirelink")
            }
        }
    }
#KpKo=blue KlKj=cyan KdotKm=green KiKcoma=yellow KkKslash=red KrshiftKrctrl=magenta    
#[    if(Stool:entity()){
        #ifdef entity:createWire(entity,string,string)
            
            print("Autowiring your Stool turret")
            entity():createWire(Stool:entity(),"Mode","Mode")
            entity():createWire(Stool:entity(),"LeftClick","LeftClick")
            entity():createWire(Stool:entity(),"RightClick","RightClick")
            entity():createWire(Stool:entity(),"Reload","Reload")
            entity():createWire(Stool:entity(),"Config","Config")
            entity():createWire(Stool:entity(),"Freeze","Freeze")
            entity():createWire(Stool:entity(),"Isolate","Isolate")
            Stool:entity():createWire(entity(),"Isolated","Isolated")
            Stool:entity():createWire(entity(),"Mode","Mode")
            Stool:entity():createWire(entity(),"Config","Config")
            Stool:entity():createWire(entity(),"FireCount","FireCount")
            
        #endif
    }]#
    #P and O = vec(0,0,255)
    #J and L = vec(0,255,255)
    #M and . = vec(0,255,0)
    #I and , = vec(255,255,0)
    #K and / = vec(255,0,0)
    #rshift and rctrl = vec(255,0,255)
    
    Stools=array()
    #constraints
    Stools:pushString("easy_precision")
    Stools:pushString("axis")
    Stools:pushString("ballsocket_adv")
    Stools:pushString("elastic")
    Stools:pushString("hydraulic")
    Stools:pushString("muscle")
    Stools:pushString("superparentmulti")
    Stools:pushString("rope")
    Stools:pushString("smart_constraint")
    Stools:pushString("slider")
    #Stools:pushString("weld_ez")
    Stools:pushString("weld")
    Stools:pushString("adv_duplicator")
    Stools:pushString("advdupe2")
    Stools:pushString("precision")
    #Stools:pushString("ignite")  #says it's invalid
    Stools:pushString("hoverball")
    Stools:pushString("dynamite")
    Stools:pushString("duplicator")
    Stools:pushString("bridgetool")
    Stools:pushString("balloon")
    Stools:pushString("freezer")
    Stools:pushString("remover")
    Stools:pushString("physprop")
    Stools:pushString("no_collide_multi")
    Stools:pushString("light")
    Stools:pushString("keepupright")
    Stools:pushString("ol_stacker")
    Stools:pushString("wheel")
    Stools:pushString("weight")
    Stools:pushString("turret")
    Stools:pushString("thruster")
    Stools:pushString("cratemaker")
    Stools:pushString("camera")
    Stools:pushString("colour")
    Stools:pushString("material")
    Stools:pushString("trails")
    Stools:pushString("rtcamera")
    Stools:pushString("paint")
    Stools:pushString("inflator")
    Stools:pushString("statue")
    Stools:pushString("ol_measuringstick")
    Stools:pushString("freezer")
    Stools:pushString("modelmanipulator")
    Stools:pushString("gravturret")
    Stools:pushString("adv_spawner")
    Stools:pushString("positionswitcher")
    Stools:pushString("fadingdoor")
    Stools:pushString("breakableprops")
    Stools:pushString("wire_expression2")
    Stools:pushString("lemongate")
    Stools:pushString("wire_dupeport")
    Stools:pushString("wire_field_device")
    Stools:pushString("wire_cam")
    Stools:pushString("wire_ranger")
    Stools:pushString("wire_pod")
    Stools:pushString("wire_numpad")
    Stools:pushString("wire_dual_input")
    Stools:pushString("wire_winch")
    Stools:pushString("wire_dupeport")
    Stools:pushString("wire_vehicle")
    Stools:pushString("wire_keyboard")
    Stools:pushString("wire_rtcam")
    Stools:pushString("wire_joystick_multi")
    Stools:pushString("wire_button")
    Stools:pushString("wire_igniter")
    Stools:pushString("wire_explosive")
    Stools:pushString("wire_forcer")
    Stools:pushString("wire_grabber")
    Stools:pushString("wire_hoverball")
    Stools:pushString("wire_hydraulic")
    Stools:pushString("wire_thruster")
    Stools:pushString("wire_turret")
    Stools:pushString("wire_user")
    Stools:pushString("wire_vthruster")
    Stools:pushString("wire_wheel")
    Stools:pushString("multi_wire")
    Stools:pushString("wire_adv")
    Stools:pushString("wire_simulate_data")
    Stools:pushString("wire_debugger")
    Stools:pushString("multi_wire")
    
    
    
    
    
   

}


if(dupefinished()|first()){

    #1
    #States where the RT Camera is
    Tools:pushEntity(RTCam:entity())#:isConstrainedTo())
    
    #2
    #States the turret entity and it's relative location
    Tools:pushEntity(Turret:entity())
    
     #3
    #States the stool turret entity and it's relative location
    #Tools:pushEntity(Stool:entity():isConstrainedTo())
    Parts=entity():getConstraints()
    
    Tools:pushEntity(Stool:entity())
    ##This was the old way of finding the stool turret
#[    for(C=1,Parts:count()){
        if((Parts[C,entity]:type()=="stool_turret")|(Parts[C,entity]:model()=="models/weapons/w_physics.mdl")){
            Tools:pushEntity(Parts[C,entity]:isConstrainedTo())
            Stool=Parts[C,entity]
            break
        }
    }]#
    
    
    #4
    #States the forcer entity and it's relative location
    Tools:pushEntity(Forcer:entity())#:isConstrainedTo()
    
    #5
    #States the grabber entity and it's relative location
    Tools:pushEntity(Grabber:entity())#:isConstrainedTo()
    
    #6
    #States the user entity and it's relative location
    Tools:pushEntity(User:entity())#:isConstrainedTo()
    
    Tools:pushEntity(Igniter:entity())
    for(C=1,Tools:count()){Tools[C,entity]:setMass(5000)}
#    holoCreate(0,Position)
#    for(C=1,Loc:count()){
#        holoCreate(C,Loc[C,vector])
#        holoColor(C,vec(0,0,64*C))
#    }
    
}
Spacing=40*(SCALE*0.5+!SCALE)
Loc[1,vector]=vec() #RT Camera
Loc[2,vector]=vec(cos(Angle:yaw()+180)*Spacing*0,sin(Angle:yaw()+180)*Spacing*0,-Spacing*0.75) #Turret
Loc[3,vector]=vec(cos(Angle:yaw()-90)*(Spacing/4),sin(Angle:yaw()-90)*(Spacing/4),Spacing) #stool
Loc[4,vector]=vec(cos(Angle:yaw()-180)*Spacing,sin(Angle:yaw()-180)*Spacing,-Spacing) #forcer
Loc[5,vector]=vec(cos(Angle:yaw()-90)*Spacing,sin(Angle:yaw()-90)*Spacing,0) #grabber
Loc[6,vector]=vec(cos(Angle:yaw()+90)*Spacing,sin(Angle:yaw()+90)*Spacing,0) #user
Loc[7,vector]=vec(cos(Angle:yaw()+90)*(Spacing/4),sin(Angle:yaw()+90)*(Spacing/4),Spacing) #igniter


if(But9){RTOn=1 timer("Camera",100)}
if(clk("Camera")){RTOn=0}

if(Slash&changed(Slash)){
    RTOn=!RTOn
    if(RTOn){print("RT Camera Enabled")}else{print("RT Camera Disabled")}
}

#RT Camera control
RTCam["Activate",number]=RTOn
#RTCam["Hide",number]=!RTOn

OE=O:eye()
if(!Joymode){
    Angle=OE:toAngle()
}else{
    Rate=2
    Angle+=angnorm(ang(-Yaxis2*Rate,-Xaxis2*Rate,0))
}
SPEED=6
if(Rstick|O:keyAttack1()){
    Run=SPEED/12
    Sprint=Run/12
}elseif(Lstick|O:keyAttack2()){
    Run=SPEED*2
    Sprint=Run*2
}


W=N8|(Yaxis>0)
S=N2|(Yaxis<0)
A=N4|(Xaxis<0)
D=N6|(Xaxis>0)
Space=Plus|But8
Alt=Enter|But7
R=Astrix|HatD
Mouse1=O:keyAttack1()&!Joymode
Mouse2=O:keyAttack2()&!Joymode
#Use=O:keyUse()
Shift=Mouse2|Lstick|Rstick

if(On){
    SinY0=sin(Angle:yaw())
    SinP90=sin(Angle:pitch()+90)
    CosP90=cos(Angle:pitch()+90)
    CosY0=cos(Angle:yaw())
    if(Position:isInWorld()){
        if(W) {Y +=SinY0*SinP90*SPEED*((Shift*Run)+1)
               X +=CosY0*SinP90*SPEED*((Shift*Run)+1)
               Z +=CosP90*SPEED*((Shift*Run)+1)}
        if(S) {Y -=SinY0*SPEED*SinP90*((Shift*Run)+1)
               X -=CosY0*SPEED*SinP90*((Shift*Run)+1)
               Z -=CosP90*SPEED*((Shift*Run)+1)}
        if(A) {Y +=CosY0*SPEED*((Shift*Run)+1)
               X -=SinY0*SPEED*((Shift*Run)+1)}
        if(D) {Y -=CosY0*SPEED*((Shift*Run)+1)
               X +=SinY0*SPEED*((Shift*Run)+1)}
        if(Space) {Z +=1*(Shift*Sprint)+1}
        if(Alt) {Z -=1*(Shift*Sprint)+1}
    }
    if(R|But10){Position=entity():pos()+vec(0,0,100)}
    if(vec(X,Y,Z):isInWorld()){Position=vec(X,Y,Z)}
    if(!Joymode){Direction = OE}else{Direction=Angle:forward()}        

}
#if(holoEntity(1)){holoPos(1,Position)}else{holoCreate(1,Position)}

##Input
CamCon:setNumber("Activated",Activated)
#CamCon:setNumber("Zoom",Zoom)
#CamCon:setNumber("X",X)
#CamCon:setNumber("Y",Y)
#CamCon:setNumber("Z",Z)
#CamCon:setNumber("Pitch",Pitch)
#CamCon:setNumber("Yaw",Yaw)
#CamCon:setNumber("Roll",Roll)
#CamCon:setAngle("Angle",Angle)
CamCon:setVector("Position",Position)
CamCon:setVector("Direction",Direction)
#CamCon:setVector("Velocity",Velocity)
#CamCon:setEntity("Parent",Parent)
#rangerHitEntities(0)
rangerFilter(Parts)
Look=rangerOffset(15000,Position,Direction)
Aim=Look:pos()
runOnTick(1)

for(C=1,Tools:count()){ 
    #This is move to vector code 
    Speed=100*(Self:mass()/2)
    Self=Tools[C,entity]
    XYZ=Position+Loc[C,vector]
    Dist=XYZ-Self:pos()
    Vel=Dist/Time
    Self:applyForce(Speed*Dist-Self:vel()*Self:mass())
    
    #This aims the arms
    
    #if(C==5){Grab=+Grabber["Grabbed Entity",entity]:vel()}else{Grab=vec()}
    #Dir = G:pos()-(F:pos()+F:vel()/(!CanDo*10))
    Dir = Self:pos()-(Aim)
    #Q = quat(Dir:toAngle())*qRotation(vec(0,0,1),180) #X
    #Q = quat(Dir:toAngle())*qRotation(vec(0,1,0),-90) #Z
    #Q = quat(Dir:toAngle())*qRotation(vec(0,0,1),90) #Y
    if(C<=3){
        Q = quat(Dir:toAngle())*qRotation(vec(0,0,1),180) #X
    }else{
        Q = quat(Dir:toAngle())*qRotation(vec(0,1,0),-90) #Z
    }
    Self:applyTorque((150*Self:toLocal(rotationVector(Q/quat(Self))+Self:pos())-12*Self:angVelVector())*Self:inertia())
} 

#############TeleKinetic Physgun 2#################
#By Captain Maim STEAM_0:1:8017844
#[
N0 = Num:number("0")
N1 = Num:number("1")
N2 = Num:number("2")
N3 = Num:number("3")
N4 = Num:number("4")
#N5 = Num:number("5")
N6 = Num:number("6")
N7 = Num:number("7")
N8 = Num:number("8")
N9 = Num:number("9")
Slash = Num:number("/")
Astrix = Num:number("*")
Minus = Num:number("-")
Plus = Num:number("+")
Enter = Num:number("enter")
Del = Num:number(".")
]#
if(first()|duped()){
    TKP=1
    print("type !help to read TKP commands.")
    #####No need to cloak it######
    #entity():setAlpha(50)
#[    Parts=entity():getConstraints()
    for(C=1,Parts:count()){
        Parts[C,entity]:setAlpha(50)
    }]#
    #####End of auto cloak####
}
O=owner()
Chat=O:lastSaid()
runOnTick(1)
runOnChat(1)
if(chatClk()&Chat==lastSaid()){
    if(Chat=="!tkp"){TKP=!TKP} #this toggles Telekinetic Physgun support
    if(Chat=="!help"){
        print("!tkp to toggle TeleKinetic Physgun support")
        print("!t to pick up or drop an item you are looking at.")
        print("say 't' to move it towards you.")
        print("say 'y' to move it away from you.")
        print("or use the keyboard")
        print("'k' to pickup or drop.")
        print("'o' and 'p' to pitch.")
        print("'j' and 'l' to yaw.")
        print("'m' and '.' to roll.")
        print("'/' to stop all rotation.")
        print("'i' and ',' to move towards and away.")
        print("'rctrl' to draw it near quickly.")
        print("'rshift' to send away quickly.")
    }
}
Use=0


AimEnt=Look:entity()
#if(AimEnt){print(AimEnt)}

Eye=Direction



####Keys from Dual Inputs, K means key, Ki means key "i" so KiKcoma means Keys i and coma in that order from 1 to -1
Ki=KiKcoma["Out",number]==1
Kcoma=KiKcoma["Out",number]==-1
Kp=KpKo["Out",number]==1
Ko=KpKo["Out",number]==-1
Kl=KlKj["Out",number]==1
Kj=KlKj["Out",number]==-1
Km=KdotKm["Out",number]==-1
Kdot=KdotKm["Out",number]==1
Krshift=KrshiftKrctrl["Out",number]==1
Krctrl=KrshiftKrctrl["Out",number]==-1
Kk=KkKslash["Out",number]==1
Kslash=KkKslash["Out",number]==-1


if(TKP){
    if((chatClk()&Chat=="!t")){
        Take=!Take
        if(Take&!Self1){Take=0}
        print("TeleKinetic Physgun is: "+Take)
        if(Take){Self1=AimEnt print("Grabbing "+Self1:type())}
    }   
    
    ####Allows the object to be frozen or unfrozen#####
    CAstrix=changed(Astrix) #change of Astrix
    if(Astrix&CAstrix&Take){
        Freeze=!Freeze
        AimEnt:propFreeze(Freeze)
    }
    if(!Take|(Self1==noentity())){Freeze=0}
    #if(!Take){Move=0}
    
    
    if(Chat=="t"){Move-=1}
    if(Chat=="y"){Move+=1}
    if(Ki){Move+=1}
    if(Kcoma){Move-=1}
    Kchange=changed(Kk)
    if(Kk&Kchange){
        Take=!Take Self1=AimEnt#O:aimEntity() 
        if(Take&!Self1){Take=0}
        print("TeleKinetic Physgun is: "+Take)
        print("Grabbing "+Self1:type())
        Move=0
        Initial=Position:distance(Self1:pos())
    }
    Rate=150
    if(Ko){P=Rate}
    if(Kp){P=-Rate}
    if(Kj){Yaw=-Rate}
    if(Kl){Yaw=Rate}
    if(Km){R=Rate}
    if(Kdot){R=-Rate}
    if(Kslash){R=Yaw=P=0}
    if(Krshift){Move+=50}
    if(Krctrl){Move-=50}
    
    #clamp(R,-180,180)
    #clamp(P,-90,90)
    #clamp(Yaw,-180,180)
    if(Take){
        
        #Self1=entity():isConstrainedTo()
        #if(!Self1){Self1=entity()}
        #runOnTick(1)
        #PYR=vec(0,0,0)
     
        if(abs(R)==180){R=0}
        Time=1500/1000
        interval(Time*1000)
        InertiaConstant = 27.053079277383
        TargetAng=angnorm(ang(P,Yaw,R))
        Local=Self1:toLocal(Self1:angles())
        AngDist=TargetAng-Local
        #AngDist=TargetAng-Self1:angles()
        Inertia = InertiaConstant*ang(Self1:inertia():y(),Self1:inertia():z(),Self1:inertia():x())
        AngVel = AngDist/Time
        Self1:applyAngForce(Inertia*(AngVel-Self1:angVel()))
    
        Speed1=100*(Self1:mass()/4)
        
        XYZ1=Position+O:eye()*(Initial+Move)
        
        Self1:applyForce(Speed1*(XYZ1-Self1:pos())-(Self1:vel()/2)*Self1:mass())
    }
}
#############End of TeleKinetic Physgun 2#################
