Category Archives: Programming

Exploring Examples from the Forum| TouchDesigner


New TouchDesigner tool for those of you looking to meander through some examples.

Pull this whole repo and find example_explorer.toe in:{your_local_directory}\td_fb_forum_examples\example_explorer

All the examples I’ve collected appear as a list on the far left, read me docs display in the middle viewer, and the example network shows up on the right.

For right now, use the “h” key to home the network when you load a new tox. Tracking down the right way to have that happen automatically – coming soon.

As a bonus this has a functioning list comp that you’re welcome to pillage.

Only a single example is loaded at a time to try and keep things optimized.

If you’re teaching a course and could benefit from re-purposing this network design for assignments or examples please feel free.

Python in TouchDesigner | Extensions | TouchDesigner

Rounding out some of our work here with Python is to look extensions. If you’ve been following along with other posts you’ve probably already looked over some extensions in this post. If you’re brand new to this idea, check out that example first.

Rather than re-inventing the wheel and setting up a completely new example, let’s instead look at our previous example of making a logger and see how that would be different with extensions as compared to a module on demand.

A warning for those following along at home, we’re now knee deep in Python territory, so what’ we’ll find here is less specific to TouchDesigner and more of a look at using Classes in Python.

In our previous example looking at modules we wrote several functions that we left in a text DAT. We used the mod class in TouchDesigner to treat this text DAT as a python module. That’s a neat trick, and for some applications and situations this might be the right approach to take for a given problem. If we’re working on a stand alone component that we want to use and re-use with a minimal amount of additional effort, then extensions might be a great solution for us to consider.

Wait, what are extensions?! Extensions are way that we can extend a custom component that we make in TouchDesigner. This largely makes several scripting processes much simpler and allows us to treat a component more like an autonomous object rather than a complex set of dependent objects. If you find yourself re-reading that last statement let’s take a moment to see if we can find an analogy to help understand this abstract concept.

When we talked about for loops we used a simple analogy about washing dishes. In that example we didn’t bother to really think deeply about the process of washing dishes – we didn’t think about how much detergent, how much water, water temperature, washing method, et cetera. If we were to approach this problem more programatically we’d probably consider making a whole class to deal with the process of washing dishes:

Okay, so the above seems awfully silly… what’s going on here? In our silly example we can see that rather than one long function for Wash() or Dry(), we instead use several smaller helper functions in the process. Why do this? Well, for one thing it lets you debug your code much more easily. It also means that by separating out some of these elements into different processes we can fix a single part of our pipeline without having to do a complete refactor of the entire Wash() or Dry() methods. Why does that matter? Well, what if we decide that there’s a better way to determine how much soap to use. Rather than having to sort through a single long complex method for Wash() we can instead just look at Set_soap(). It makes unit testing easier, and allows us to replace or develop that method outside the context of the larger method. It also means that if we’re collaborating with other programmers we can divide up the process of writing methods.

What’s this self. business? self. allows us to call a method from inside another method in the same class. This is where extensions begin to really shine as opposed to using modules on demand. We an also use things like attributes andinheritance.

Okay, so how can we think about actually using this?

Let’s take a look at what this approach looks like in python:

So getting started we set up a couple of variables that we were going to reuse several times. Next we declared our class, and then nested our methods inside of that class. You’ll notice that different from methods, we need to include the argument self in our method definitions:

# syntax for just a function
def Clear_log():

# syntax for just a method in a class
def Clear_log( self ):

We can also see how we’ve got several helper functions here to get us up and running – ways to add to the log, save the log to an external file, a way to clear the log. We can imagine in the future we might want to add another method that both clears the log, and saves an empty file, like a reset. Since we’ve already broken those functions into their own methods we could simply add this method like this:

def Reset_log():

Now it’s time to experiment.

Over the course of this series we’ve looked at lots of fundamental pieces of working with Python in TouchDesigner. Now it’s your turn to start playing and experimenting.

Happy programming!

Python in TouchDesigner | Modules | TouchDesigner

There are a number of ways that we might use modules on demand in TouchDesigner. Before we get too far along, however, we might first ask “what is a module on demand?”

According to the TouchDesigner wiki:

The MOD class provides access to Module On Demand object, 
which allows DATs to be dynamically imported as modules. 
It can be accessed with the mod object, found in the automatically 
imported td module. 

Alternatively, one can use the regular python statement: import. 
Use of the import statement is limited to modules in the search path, 
where as the mod format allows complete statements in one line, 
which is more useful for entering expressions. Also note that DAT modules 
cannot be organized into packages as regular file system based 
python modules can be.

What does this mean? It’s hard to sum up in just a single sentence, but the big thing to take away is that we can essentially use any text DAT to hold whole functions for us that we can then call whenever we want.

Let’s take a closer look at this process. We’ll start with some simple ideas, then work our way up to something a little more complicated.

First we turn things way down, and just think about storing variables. To be clear, we probably wouldn’t use this in a project, but it can be helpful for us when we’re trying to understand what exactly is going on here.

Let’s create a new text DAT and call it “text_variables”, inside let’s put the following text:

width       = 1280
height      = 720

budget      = 'small'

Using the mod class we can access these variables in other operators! To do this we’ll use the following syntax:

mod( 'text_variables' ).width
mod( 'text_variables' ).height
mod( 'text_variables' ).budget

Try adding a constant CHOP, and a text TOP to your network and using the expressions above to retrieve these values.

Next try printing these values:

print( mod( 'text_variables' ).width )
print( mod( 'text_variables' ).height )
print( mod( 'text_variables' ).budget )

So, it looks like we can access the contents of a module as a means of storing variables. That’s hip. Let’s take a moment and circle back to one of the other use cases that we’ve already seen for a module. More than just a single value, we can also put a whole dictionary in a module and then call it on demand. We’ve already done this in some of our previous examples, but we can take a quick look at that process again to make sure we understand.

Let’s create a new text DAT called “text_dictionary_as_module”, inside of this text DAT let’s define the following dictionary:

fruit = {
    "apple" : 10,
    "orange"    : 5,
    "kiwi"  : 16

Let’s first print the whole dictionary object:

print( mod( 'text_dictionary_as_module' ).fruit )

Alternatively, we can also access individual keys in the dictionary:

mod( 'text_dictionary_as_module' ).fruit[ 'apple' ]
mod( 'text_dictionary_as_module' ).fruit[ 'orange' ]
mod( 'text_dictionary_as_module' ).fruit[ 'kiwi' ]

What can you do with this?! Well, you might store your config file in a text DAT that you can call from a module on demand. You might use this to store configuration variables for your UI – colors, fonts, etc. ; you might decide to use this to configure some portion of a network, or to hold on to data that you want to recall later; or really any number of things.

Before we get too excited about storing variables in modules on demand, let’s look at an even more powerful feature that will help us better understand where they really start to shine.

Up next we’re going to look at writing a simple function that we can use as a module on demand. In addition to writing some simple little functions, we’re also going to embrace docstrings – a feature of the python language that makes documenting your work easier. Docstings allow us to leave behind some notes for our future selves, or other programmers. One of the single most powerful changes you can make to how you work is to document your code. It’s a difficult practice to establish, and can be frustrating to maintain – but it is hands down one of the most important changes you can make in how you work.

Alright, I’ll get off my documentation soapbox for now. Let’s write a few methods and see how this works in TouchDesigner.

We can start by creating a new text DAT called “text_simple_reutrn”, inside of this DAT we’ll write out our new functions:

Great! But what can we do with these? We can start by using some eval DATs or print statements to see what we’ve got. I’m going to use eval DATs. Let’s add several to our network and try out some calls to our new module on demand. First let’s look at the generic syntax:

mod( name_of_text_dat ).name_of_method

In practice that will look like:

mod( 'text_simple_reutrn' ).multi_by_two( 5 )
mod( 'text_simple_reutrn' ).multi_by_two( 2.5524 )
mod( 'text_simple_reutrn' ).logic_test( 5 )
mod( 'text_simple_reutrn' ).logic_test( 6 )
mod( 'text_simple_reutrn' ).logic_test_two( "TouchDesigner" )

Now we can see that we wrote several small functions that we can then call from anywhere, as long as we know the path to the text DAT we’re using as a module on demand! Here’s where we start to really unlock the potential of modules on demand. As we begin to get a better handle on the kind of function we might write / need for a project we can begin to better understand how to take full advantage of this feature in TouchDesiger.

Doc Strings

Since we took the time to write out all of those doc strings, let’s look at how we might be able to print them out! Part of what’s great about doc strings is that there’s a standard way to retrieve them, and therefore to print them. This means that you can quickly get a some information about your function printed right in the text port. Let’s take a closer look by printing out the doc stings for all of our functions:

That worked pretty well! But looking back at this it seems like we repeated a lot of work. We just learned about for loops, so let’s look at how we could do the same thing with a loop instead:

A Practical Example

This is all fun and games, but what can we do with this? There are any number of functions you might write for a project, but part of what’s exciting here is the ability to write something re-usable in Python. What might that look like? Well, let’s look at an example of a logger. There are a number of events we might want to log in TouchDesigner when we have a complex project.

In our case we’ll write out a method that allows a verbose or compact message, a way to print it to the text port or not, and a way to append a file or not. Alright, here goes:

So now that we’ve written out the method, what would call for this look like?

operator = me

message ='''
Just a friendly message from your TouchDesigner Network.
Anything could go here, an error message an init message.

You dream it up, and it'll print

# print and append log file with a verbose log message
mod( 'text_module1' ).Log_message( operator, message, verbose = True )

# print and append log file with a compact log message
# mod( 'text_module1' ).Log_message( operator, message )

# append log file with verbose log message
# mod( 'text_module1' ).Log_message( operator, message, verbose = True, text_port_print = False )

# print a compact log message
# mod( 'text_module1' ).Log_message( operator, message, append_log = False )

Take a moment to look at the example network and then un-comment a line at a time in the text DAT with the script above. Take note of how things are printed in the text port, or how they’re appended to a file. This is our first generalized function that has some far reaching implications for our work in touch. Here we’ve started with a simple way to log system events, both to a file and to the text port. This is also a very re-usable piece of code. There’s nothing here that’s highly specific to this project, and with a little more thought we could turn this into a module that could be dropped into any project.

Local Modules

We’ve learned a lot so far about modules on demand, but the one glaring shortcoming here is that we need the path to the text DAT in question. That might not be so bad in some cases, but in complex networks writing a relative path might be complicated, and using an absolute path might be limiting. What can we do to solve this problem. We’re in luck, as there’s one feature of modules we haven’t looked at just yet. We can simplify the calling / locating of modules with a little extra organization.

First we need to add a base and rename it to “local”, inside of this base add another base and rename it to “modules”. Perfect. I’m going to reuse one of our existing code examples so we can see a small change in syntax here. I’ve also changed the name of the text DAT inside of local>modules to “simple_return”.

mod.simple_return.multi_by_two( 5 )
mod.simple_return.multi_by_two( 2.5524 )
mod.simple_return.logic_test( 5 )
mod.simple_return.logic_test( 6 )
mod.simple_return.logic_test_two( "TouchDesigner" )
mod.simple_return.logic_test_two( 10 )

Looking at the above, we can see that we were able to remove the parentheses after “mod”. But what else changed? Why is this any better? The benefit to placing this set of functions in local>modules is that as long as you’re inside of this component, you no longer need to use a path to locate the module you’re looking for.

Alright, now it’s time for you to take these ideas out for a test drive and see what you can learn.

Python in TouchDesigner | Intro to Functions | TouchDesigner

Core Concepts

  • Functions as a concept
  • Anatomy of a function
  • Writing functions
  • Calling functions
  • Returning values
  • Passing arguments

Before we can tackle CHOP executes we need to take a moment to learn about functions. There’s a lot to learn about with functions, so we’re not going to dive too deep just yet… yet. We are, however, going to peer into this idea so we can better understand part of what we’ll see next as we move into the exciting world of executes.

Let’s start by looking at what a function actually is:

“A function is a block of organized, reusable code that is used to perform a single, related action. Functions provide better modularity for your application and a high degree of code reusing.

As you already know, Python gives you many built-in functions like print(), etc. but you can also create your own functions.”
Tutorials Point

Great! But… how can we better understand that? For a moment let’s first appreciate that we have a wide variety of functions that we do on a regular basis… we just don’t think of them as functions. Most of us know how to calculate a tip, or gas mileage, or estimate travel time, or pack a suitcase, or make lunch, or or or, and and and. We don’t think of these as functions, but if we had to write out very specific instructions about how to complete one of these tasks we’d actually be close to starting to wrestle with the idea of what a function is – it’s okay if that doesn’t make sense yet. Hang on tight, because we’re gonna get there.

Let’s first look at a simple example that examines the anatomy of a function. Next we’ll write a few simple functions. Then we’ll look at why that’s important when it comes to thinking about CHOP executes.

Starting with Anatomy.

Here we go, we’re going to write a dead simple function:

def first_function():
    print( 'Hello World' )


There we go. We did it. Now, if we were to run this in TouchDesigner, nothing would happen… so at first glance it would seem like we didn’t really write a function after all. That might be a good guess, but the reason nothing happened is because we never actually called our function, we just defined it – we wrote out all of the instructions, but we never asked TouchDesigner to actually run the function. To see anything happen, we need to actually call the function – we need to tell TouchDesigner that we need to run it. Let’s modify our example to see what that would look like.

def first_function():
    print( 'Hello World' )



Okay… time to take this all apart and see what makes it tick.

  • We’re started out by indicating that we were going to define a function… that’s really what we meant when we wrote “def.”
  • Next we gave that function a name, in our case we called it “first_function.”
  • Next we specified that we weren’t going to pass in any arguments or parameters by writing “()” – don’t worry, we’re going to learn more about that in a second.
  • Then we indicated that we were going to outline what was in the function with our “:”
  • The next line is indented one tab space and here we print out “Hello World”
  • We ended the function with a return statement, which in this case didn’t return anything.
  • Finally, we summoned our function into action by saying its name… well, writing its name “first_function()”

At this point we’ve written a very simple function that just prints out “Hello World.” We started with this simple example so we could just talk about its anatomy. Before we can move on to something a little more interesting, we need to unpack a few things. Specifically, we need to talk more about what it means to *return* something, and what an argument or parameter is when it comes to functions.

Let’s start with *return*. Like it’s name suggests, to return something is to give it back, or deliver something. Seems straightforward enough, right? We might imagine that sometimes we don’t want to print out the result of a function, but we do want to get something out the other side to use in another process. In this case, we want something returned to us after the function has run. Let’s look at that in a concrete way.

We’re going to use our same example first function, but make a few changes.

def first_function():
    text = 'Hello World'

    return text


Okay, here we can see that we changed our function so we don’t actually print out “Hello World” anymore, instead we return it at the end. If we run our function, we encounter our same problem that we saw earlier… it would seem as if nothing happened. What gives. Let’s change our function in one small way and see what we end up with:

def first_function():
    text = 'Hello World'

    return text

print( first_function() )

The small change to print out first_function() means that we’re now printing out what’s returned from this function. It might feel like a small difference, but it means that we’re able to control what comes out of our function when we summon it into action. That’s actually a very important thing, and we’ll see why shortly.

If we can control what comes out of our functions, surely we can control what goes into them… right? In fact, you are right.

Now that we now how to get something out of our function, let’s pass it some information do to something with. We’re going to write another simple function, this time to do some simple math.

def percent( val1 ):
    calculation = val1 * 0.01

    return calculation

print( percent( 50 ) )

Alright, what do we have here? Let’s imagine we want to change an integer into it’s float equivalent as a percentage. 50% as becomes 0.5, 10% would be 0.1, and so on and so on. Here we’ve written a function to do just that. In this case we’ve specified that our function accepts one argument which is named val1. We later see in our function that “calculation” is val1 * 0.01. Finally, we return calculation. This means we can give percent any number, and get a float value in return. Not bad.

Okay, let’s look at two more examples. Next we’ll write a simple function to calculate a tip based on a total bill. At the end of this we want to see our tip and our total bill – using our new found lingo, we’re going to return these values.

Okay, let’s make some Python magic happen. If you’re playing along at home, trying writing this yourself before you look at how I did it.

def tip_calculator( total , tip_percentage ):

    tip = total * ( tip_percentage / 100 )
    total_bill = total + tip
    return tip , total_bill

print( tip_calculator( 50 , 15 ) )

Here we want two things back, our tip and our total_bill. We start by calculating the tip, and then by adding that to our total. Finally we return these two values.

Let’s try one more idea on for size. This next time around you’re challenge is to use the function we just wrote, and to write another function as a compliment. This second function is going to print out these values to our text port so we can see them. By writing this as two separate functions we decide when we want to print out our results, and when we want to just return our tip and total_bill. As an extra challenge, see if you can write your new function to accept only a single argument.

Okay, let’s look at how you might solve this problem:

def tip_calculator( total , tip_percentage ):
    tip = total * ( tip_percentage / 100 )
    total_bill = total + tip
    return tip , total_bill

def display_total( tip_and_total_bill ):
    dotted_line = '- ' * 10
    tip_text = "Your total tip is {}"
    total_bill_text = "Your total bill is {}"
    print( dotted_line )
    print( tip_text.format( tip_and_total_bill[ 0 ] ) )
    print( total_bill_text.format( tip_and_total_bill[ 1 ] ) )
    print( dotted_line )


total = 100
tip_percentage = 20

print( tip_calculator( total , tip_percentage ) )

display_total( tip_calculator( total , tip_percentage ) )

How did you do? We can see that our first function stayed the same. Our second function accepts a single argument – tip_and_total_bill. This tuple (a series of values) is then used by our second function when printing out to our textport. This probably isn’t the best way to solve this problem… but for the sake of a simple example our chances of getting into trouble are pretty slim.

Okay, so why do all of this?! Well, let’s take a sneak peak at what’s coming next. If we look at the contents of a CHOP execute we see:

# me - this DAT
# channel - the Channel object which has changed
# sampleIndex - the index of the changed sample
# val - the numeric value of the changed sample
# prev - the previous sample value
# Make sure the corresponding toggle is enabled in the CHOP Execute DAT.

def offToOn(channel, sampleIndex, val, prev):

def whileOn(channel, sampleIndex, val, prev):

def onToOff(channel, sampleIndex, val, prev):

def whileOff(channel, sampleIndex, val, prev):

def valueChange(channel, sampleIndex, val, prev):

We should now recognize the contents of these DATs as functions… and not only are they functions, they’re functions with four named incoming arguments. Now we can really start to have fun.

Learn more about functions in Python

Download the sample files from github

Python in TouchDesigner | Data Structures – Lists | TouchDesigner

Part 1 Core Concepts

  • Lists – a structure and a concept
  • Creating lists – syntax and structure
  • Retrieving items from a list – Syntax
  • Adding items to a list .append() and .extend()
  • Lists of Lists

Part 2 Core Concepts

  • Lists – a structure and a concept
  • Why Lists matter in TouchDesigner
  • The Channel Class – seeing CHOPs as lists
  • The Point Class – thinking of geometry as lists
  • The COMP Class and .findChildren() – pulling apart returned lists
  • More about how to read the TouchDesigner wiki

Lists are the bees knees, they’re the cat’s pajamas, they’re almost better than sliced bread. There are a few important things for us to think about before we dive into the Python of lists. Python lists are just like the lists you might make on a piece of paper. They’re a sequential ordering of items. A grocery list might be:

  • eggs
  • milk
  • bread
  • butter
  • coffee

We often make lists, and while the order of our grocery list might be arbitrary, there are plenty of lists that are not. Frequently a todo list has a specific order:

  1. Have preliminary discussion with collaborators
  2. Check schedule for availability
  3. Block off time for new project
  4. Coordinate schedules
  5. Build a preliminary budget
  6. Draft contracts
  7. Confirm costs
  8. Book space
  9. Purchase equipment

While this is a silly example, the important consideration is that here you wouldn’t purchase equipment before you started a preliminary discussion with your collaborators. Of course that seems obvious – but remember that you have a sense of linearity, a sense of time, a sense of order, and a idiomatic frame that you subconsciously constructed based on the content of the list items. Alright, semiotics aside, the more important idea here is that lists have order. Now while that may seem obvious, we’ll see later that dictionaries don’t necessarily work in the way – and in fact this is an important distinction we need to make early on.

Let’s go back to our grocery list. What might that look like in Python?

grocery_list = [ 'eggs' , 'milk' , 'bread' , 'butter', 'coffee' ]

You’ll notice that our items are enclosed in matching foot or inch marks: ” or “”. We can remember back to our first lesson on printing that this helps us see that these are strings. That’s wonderful. What if we want to print the whole list? Well we can do this:

print( grocery_list )

That prints our whole list. That’s pretty swanky, but what if we just want a single item from our list? How can we just print that? Well, we’ll remember that 0 is still a number for us here in Python. That means the indexing of our list items looks like: 0 1 2 3 4

We can print a single item in our list by indicating the index of the item we want:

print( grocery_list[ 0 ] )

Let’s look at that a little more closely and print out all of the items we have in our list:

print( grocery_list[ 0 ] )
print( grocery_list[ 1 ] )
print( grocery_list[ 2 ] )
print( grocery_list[ 3 ] )
print( grocery_list[ 4 ] )

Let’s go one step further and really make that as explicit as possible – just to make sure we understand.

print( "The item in the 0 position of our list is %r" % grocery_list[ 0 ] )
print( "The item in the 1 position of our list is %r" % grocery_list[ 1 ] )
print( "The item in the 2 position of our list is %r" % grocery_list[ 2 ] )
print( "The item in the 3 position of our list is %r" % grocery_list[ 3 ] )
print( "The item in the 4 position of our list is %r" % grocery_list[ 4 ] )

We can make lists out of just about anything. Let’s make a list out of all of the data types we’ve talked about so far:

my_int_list = [ 1 , 2 , 3 , 4 ]
my_float_list = [ 1.235 , 1.5679 , 9.454 , 4.23485 ]
my_string_list = [ 'apple' , 'kiwi' , 'orange' , 'pineapple' ]
my_bool_list = [ True , True , False , True, False ]
my_mixed_list = [ 1.234 , 5 , 'apple' , True , 3.45 ]

One question we might have is how long is our list? Well, there happens to be an easy way for us to figure that out with len() – as in length.

len( my_int_list )

Practice printing the length of all of your lists.

We can also build lists from scratch. First we need to create an empty list.

my_list = []

print( 'As we go, we will print our list at each' )
print( 'step along the way' )
print( 'My List' , my_list )

Next we can add items to our list with .append( theValueOrStringToBeAddedHere ).

my_list.append( 1 )

# this is here to make a line break
print( '\n' )

print( 'So we just added a single number out our list' )
print( 'what does that look like now?' )
print( 'My List' , my_list )

We can even add multiple items at once with .extend( aListofItemsHere ):

my_list.extend( [ 45 , 2 , 100 , 6 ] )

# this is here to make a line break
print( '\n' )

print( 'Can we add multiple items at once?' )
print( 'My List' , my_list )

print( 'We sure can, we just need to use .extend' )
print( 'instead of .append' )

That’s great… but what does this mean for me in TouchDesigner? Well, in Touch many things are returned as lists. Samples in CHOPs are often a list, as are points in a SOP. Once we have a fundamental understanding of lists as a data structure we can start to really have a lot of fun.

Let’s look at CHOPs first.
First, make sure you add a noise CHOP to your network called noise1.

# define some variables
noise1 = op( 'noise1' )

# understanding the channel operator make
# a big difference in the way we use TouchDesigner
# lets start by just printing our variable

print( 'If we just print our noise1 variable we see this' )
print( noise1 )

print( 'If we print chan1 in noise1 one we see this' )
print( noise1[ 'chan1' ] )

print( 'we can also access this by using .chan( channelIndexHere )' )
print( noise1.chan( 0 ) )

print( 'Finally, we can see the whole list of values if we use' )
print( '.vals as we... that looks like') 
print( 'noise1.( channelIndexHere ).vals' )
print( noise1.chan( 0 ).vals )

That’s pretty fun… but let’s take that a step further.

# okay, but why do we care?

# define some variables
noise1 = op( 'noise1' )

# we can use what we've learned working with the .chans().vals
# to help us understand a little bit more about our CHOP
# for example, if our channel is a list of values, we can
# access those values just like we might in a list

print( noise1[ 'chan1' ][ 0 ] )
print( noise1[ 'chan1' ][ 1 ] )
print( noise1[ 'chan1' ][ 2 ] )

# we can even do the same things we might do in python here
print( len( noise1[ 'chan1' ] ) )

# though if we look at the wiki, we'll find that there's already
# a method to do just this called .numSamples
# and a method called numChans - which tells us how many channels
# If we think of our CHOP as a list of lists... then we can both
# see how many lists, and the length of the lists.

print( noise1.numSamples )
print( noise1.numChans )

Next let’s add a rectangle SOP to our network.

# define some variables
rectangle1 = op( 'rectangle1' )

# That's great... but what about geometry?
# Let's take a closer look at SOPs

print( 'Like with a sop we can print the path to rectangle1 operator' )
print( rectangle1 )

print( 'We can also look at the member .points' )
print( rectangle1.points )

print( 'Seeing that it is an object by itself, means we can look closer' )
print( 'What happens if we just ask for the first item in this object?' )
print( rectangle1.points[ 0 ] )

print( 'What if we ask to make the whole object a list, and the print it out?' )
print( list( rectangle1.points ) )

While CHOPs and SOPs seem like obvious operators that might have lists, they’re certainly not the only ones. The method .findChildren returns a list of operators when dealing with COMPs. Let’s take a closer look at that while we’re at it. I started by making a container and adding three buttons inside. Make sure that you look at the example file to see what I’ve done to get started.

# define some variables
radio_buttons = op( 'container_radio_buttons' )

# Let's take a look at findChildren
# we can see all of the ops inside of our container with:
print( radio_buttons.findChildren() )

# What if we only wanted to see the buttons??
print( radio_buttons.findChildren( depth = 1 ) )

# That's fine as long as there aren't any other operators
# inside of our conatiner. If we wanted to make sure we only
# got a list of buttons, we could be even more specific with

print( radio_buttons.findChildren( type = buttonCOMP , depth = 1 ) )

# Okay... so?
# Well, what we get back is a list, so what if we did this?

print( radio_buttons.findChildren( type = buttonCOMP , depth = 1 )[ 0 ] )

# Maybe we don't want to see the whole path, we just want to see it's name
print( radio_buttons.findChildren( type = buttonCOMP , depth = 1 )[ 0 ].name )

# Or maybe just its digits
print( radio_buttons.findChildren( type = buttonCOMP , depth = 1 )[ 0 ].digits )

# We could even click on one of our buttons this way
radio_buttons.findChildren( type = buttonCOMP , depth = 1 )[ 0 ].click()

Lists are powerful and also flexible data structures. And this is only the start of what we can do with them. Practice making some lists, accessing their contents, and printing out pieces of them.

Learn more about data structures in Python

Download the sample files from github

Advanced Instancing | Pixel Mapping Geometry | TouchDesigner

Part 1

Core Concepts

  • Instancing geometry
  • Transferring data between operator types
  • Real time rendering

Part 2

Core Concepts

  • Instanced geometry from pixel data
  • Transferring data between operator types
  • Real time rendering

Part 3

Core Concepts

  • Spatial representations of time and images
  • Instanced geometry over time
  • Experiments in understanding depth
  • Real time rendering

Part 4

Core Concepts

  • Camera control
  • Spatial representations of time and images
  • Instanced geometry
  • Real time rendering

Download the Example Code from GitHub

TouchDesigner | FB HelpGroup | Presets

From the FaceBook TouchDesigner Help Group

In Looking at the design of a simple ue system..I can’t wrap my head around head following to start construction
Theoretically there would one dat table with the preset name description and values
One Table Per Preset or am I looking at setting and recalling the states wrong, and there is an easier way to save and set the state using storage ??
I will build it myself.. looking for the best approach to start working on this.

There are lots of ways you might tackle this. Using a table – you could use a table per preset switching between tables, or one table with all presets where you select the row or column you need.

If you’re using storage you might think about how you store your presets as dictionaries or lists – depending on the complexity of your presets.

IMHO – tables tend to be more straight forward, and for simpler systems are fast to build. Tables are also useful for distributed systems when you need / want to use Touch Out DATs to push information around a network.

Dictionaries are great for complex systems that have lots of moving parts. It takes some additional time to set-up and debug, but is very flexible and extensible once you have the scaffolding in place. For a simple system, however, this might be a little overkill – it’d be easy to loose a lot of time in the building of your data structure, rather than in building your system.

I might start by considering scale first… how many key / value pairs per preset, and how many machines are you running this one. In my experience, the more I’ve spent time thinking through how the larger scope of a project is going to function, the easier it is to make a decision about the appropriate data structure for a project.

I too want to build my own left-mouse->recall, right-mouse->save -table preset system. I started one but got stuck with it unsure.

There’s this on the forums: It’s great, but it was also a bit too much to reverse engineer. I’d like to have my own system. Not meaning to hijack this thread but just thinking out loud. If i have say 8 tables with the correct amount of rows, and i use “rmouseclick” to save the CHOP values of my sliders to those tables, and then “lmouseclick”(or whatever it was called) to recall the correct table and overide the slider CHOP value, i can haz presets. Sadly i cant write the python to read/write from table. Probably isn’t too hard

I think I have an example of something like this somewhere Marko – I’ll see if I can dig it out in the next couple of days.

Thanks Matthew… again.

I’ll probably put together an example that does this with tables or with storage – it’s handy to see the guts of how both of these things work in a simple kind of configuration

Thanks, it would be an interesting read into both to see which approach I am going to use

For M and J – first installment. Storing presets in a table data structure.


Move the sliders or type in values from 0 – 1.

Right click on the keys at the top to Record positions.
Left click on the keys to Recall positions.


More thanks than I can ever express to Keith Lostracco – it was one of the example files he posted last year that pushed me to better understand the table COMP, this example pulls a lot of inspiration from the TOX he originally posted.

Next I’ll put together an example of working with dictionaries as a different kind of data structure.
Follow up for M and J here you’ll find a python dictionary approach.

Same as the other TOX:


Right click records, left click recalls.

You’ll notice in dictMethod/table1/recall that a try and except is used for any keys that do not yet exist. Defaults from storage with a dictionary can be tricky, and this is one of many ways around this.


The benefit of a method like this would be scale – dictionaries can hold other dictionaries (just like lists can hold other lists). This means that you could use another set of buttons to specify which dictionary was recalled. You might want to save presets by venue, or media type, or any number of attributes. You could achieve the same result with tables, you would just need to spend some time thinking about how to appropriately structure that approach.

Hope this helps.

Download the examples from GitHub

  • presetsDictMethod
  • presetsTableMethod

TouchDesigner | Email | Cube Faces

Original Email – Thu, Jul 23, 2015 at 6:01 AM

Hi Matthew,

i love to work along your tutorials and learn more  about my best new friend since last year “Touchdesigner”. Theres is one idea i take with me. thought about a cube geometry with different pictures on each side. thats for the moment no problem, but how can i get the pictures changing automatically after a few seconds out of a folderDat. Any ideas?

Reply – Thu, Jul 9, 2015 at 12:10 AM

There are countless ways that you might try to solve this problem – some will scale better than others. The example included here, does well for 1-5 cubes, but probably wouldn’t scale well for more than 10. At 10 or more, you’d probably want to consider some  of the challenges of instancing in a slightly different way.


At any rate, here’s an example with several different considerations. The first is just placing different numbers of the different sides of a cube using a cube map.

The second is placing different images.

The third takes the contents of a folder DAT and changes all of the faces of the cube simultaneously. Every three seconds all of the images change.

The fourth example randomly changes the face of the cubes – both the order in which faces change is random, as is the selection of images. The images are shuffled so that you’re only likely to see as few repeated images as possible. I don’t know how strong your python is, but when you look at this example you’ll see that I wrote several functions in an embedded module that handle all of the logic of this operation.


You can download the example file from GitHub –


TouchDesigner | Email | Shrink Instance

Original Email – Mon, Jul 13, 2015 at 9:43 PM

Hey Matt!
So I’ve tried banging my brain around 10 different ways to where I’m sure it now resembles a sphereSOP – noiseSOP but I’m still coming up a little short. Naturally, I thought about your THP 494 Shape lesson but I was not able to figure out what I’m missing so I’m coming straight to teacher for some guidance.

I’m trying to recreate the attached image. I’m using a GridSOP, MetaballSOP – MagnetSOP which sort of works but I’m missing some very important part of the process. Can you have a look at this and give me a hint as to what I’m missing?

You certainly do not have to correct the work unless you want to but a point in the right direction (haha) would really help me sleep tonight!

Reply – Tue, Jul 14, 2015 at 12:23 AM,

That was a good brain teaser.

I’m including two different approaches to solve this problem. The first looks at using your magnet approach, and the second is more GPU focused.


Following your model with magnet, you had just about nailed it – all of the information you needed was in that SOP to CHOP, it was just a matter of reformatting it. In the magnet base, I grabbed the tz channel of the SOP to CHOP, scaled it, and renamed it scale, merged it in your instance CHOP, then applied it to the scale parameter of your instances. Pretty right on with your existing approach. The draw back here is that the magnet SOP is very expensive – nearly 7 milliseconds by itself – bottle-necking your performance at about 30 fps. This also keeps you pretty limited in terms of the number of points you can work with – CPU bottlenecks can be tricky to work around.


So, I started to think about how I would solve this problem on the GPU, and remembered that an array of pixels is just a different kind of grid. The second approach translates a circle TOP, and then converts that to CHOP information, merges this with a SOP to CHOP (using the xyz data from a gird), and then instances from there. I was looking at over 1400 instances without a problem. The challenge you’ll encounter, however, is when you try to replicate that many source textures. I did a quick test, and things slowed down when I had that many texture instances drawn using the newer texture instance approach. I was, however, able to get performance back up to 60 FPS if I loaded a 3D Texture Array TOP, and then turned off it’s active parameter. Markus uses this trick often.


Anyway, that’s as far as a I got in the little bit of time that I carved out. The next steps (in terms of mimicking your source image) would be to get the displacement right pushing instances up and down to make an opening in the center of the array.


Alright, well I put another hour into this because I got really interested in the idea of displacement. I think this still needs a little more work to really dial it in, but it’s a solid starting point for sure.


Hope this helps.



Look at the example file on GitHub – shrinkInstance_locked

TouchDesigner | Email | Realtime DNA


Original Email – Mon, Jun 22, 2015 at 11:53 PM

First of all.. Thank you for the knowledge , that you share – It is great . I watch all your tutorials in Youtube and they help me a lot . I would like to ask for a tutorial or advice how to make something in Touchdesigner . Its a Audio reactive DNA . I have seen tutorials for Qaurtz composer and i have done it there . I found one in the TD forums , but its not so good in a way that there is a limitation in the twisting of it .

this is mine in QC. if you find it interesting enough to be recreated in TD it would be great.
Thank you .

Reply – Thu, Jul 9, 2015 at 11:30 PM

Sorry for the late reply, I was out of the country when you initially wrote and have been playing catch up with email since I returned.

This is an interesting challenge, and was fun to re-create in TouchDesigner. I didn’t work on the audio reactive components at all – I’ll leave that to you to explore. You should be able to see how this is set up with some instancing and lighting to create a dynamically changing scene. I think there’s a bit more to play with in terms of rendering and layering, but this should be a solid starting point for you.

I hope this helps you get moving in the right direction.



Download the example from GitHub – DNArender.toe