# After Effects expressions ## Controls ### Cascading properties from a control layer to the current layer AE’s frustrating lack of global variables means that it’s sometimes necessary to cascade eg a slider control from a master control null layer to the current layer. The advantage of this is that you can then copy and paste expressions between layers that need to behave in the same way. For example, if you wanted the speed of two planets, Mercury and Venus, to be set by sliders in the control layer, you could put a slider called 'speed' inside the Mercury and Venus layers which simply copied the value from 'Mercury speed' and 'Venus speed' in the control layer. This is a general implementation of that. For a slider called 'speed', it will find a slider in the control layer called 'Foo speed' where 'Foo' is the first word of the current layer’s name. (This allows you to have multiple layers called things like 'Foo green' and 'Foo blue' which share properties, but will only use the first word when looking for the control.) ```javascript thisComp.layer("controls").effect(thisLayer.name.split(" ")[0] + " " + thisProperty.propertyGroup(1).name)("Slider"); ``` ### Dropdown menus Dropdown menu controls return a 1-indexed number representing the selected option. There doesn’t seem to be a way to get the name of that option, which is annoying. So don’t reorder your options after you’ve made expressions for them. And, don’t forget: _1_-indexed, not 0-indexed. ## Layers ### A simple grid of layers Paste this into the position property of many layers, and they will be arranged in a grid based on the x and y spacing and number of columns specified in a sliders in a control layer of your choice. Do not use this in the top layer, as its position is set manually to act as a parent to the rest of the grid. ```javascript // Layer containing slider controls controls_layer = thisComp.layer("controls") // Sliders controlling spacing x_spacing = controls_layer.effect("x spacing")("Slider"); y_spacing = controls_layer.effect("y spacing")("Slider"); // Number of columns is a quick and easy way to control the grid's extent // (Number of rows is implied by the total number of layers) n_col = controls_layer.effect("number of columns")("Slider"); // Topmost layer in the grid top_layer = thisComp.layer("parent layer"); // Get the top left position based on the top layer top_left = top_layer.transform.position; // How far through the grid are we? Count the number of layers before this one layer_index = thisLayer.index - top_layer.index; // Calculate position based on all of the above [ // Loop over x positions with layer index mod number of columns top_left[0] + x_spacing * (layer_index % n_col), // New row every n_col top_left[1] + y_spacing * Math.floor(layer_index/n_col) ]; ``` ### Objects within a shape layer Shape layers can contain multiple objects, like Rectangle 1, Circle 2 etc. Sometimes you might want to address these as though they’re layers, and apply effects based on the properties of adjacent ones, or the top object, or whatever. The syntax for this is somewhat ridiculous. This simple example gets the index of the current object, and then retrieves the opacity of the object below: ```javascript i = thisProperty.propertyGroup(2).propertyIndex; thisLayer("Contents")(i+1).transform.opacity; ``` You can also directly access objects within a shape layer by name, using `content('Name')`; in this case the position of a circle: ```javascript content("Circle 1").content("Path").position; ``` `content("Circle 1").content('Path')` refers to the circle path itself; `content("Circle 1").transform` allows you to access transform controls for that individual shape; and so on. Note that both the path and the transform controls have a `position` property, because shape layers have lots of ways to do the same thing. ## Keyframes ### Finding the previous or next keyframe of a property After Effects doesn’t have a built-in way to select the previous or next keyframe, only the nearest one. These two functions fix that. By default, the expression is applied to the property being manipulated, but you can pass the property you wish to look inside with the `prop` argument. ```javascript function previousKey(prop = thisProperty) { if(time < prop.nearestKey(time).time) { prevIndex = prop.nearestKey(time).index - 1 if(prevIndex <= 0) { return(false); } else { return prop.key(prevIndex); } } else { return prop.nearestKey(time); } } function nextKey(prop = thisProperty) { if(time >= prop.nearestKey(time).time) { nextIndex = prop.nearestKey(time).index + 1 if(nextIndex > prop.numKeys) { return(false); } else { return prop.key(nextIndex); } } else { return prop.nearestKey(time); } } nextKey().index ``` ### Fixing AE’s terrible keyframe interpolation Sometimes (often), After Effects will do very strange things between keyframes with similar values if the preceding or subsequent keyframes involve rapid change of those values. If you just can’t fix it, this function will do it for you in the case where you’d like the keyframe interpolation to be linear, using the previous and next keyframe functions defined above. You could probably extend this to rewrite all interpolation if the type of keyframe is accessible to JavaScript… ```javascript // Get the previous and next keyframes previous_keyframe = previousKey(); next_keyframe = nextKey(); // If they both exist... if(previous_keyframe !== false & next_keyframe !== false) { // Use a simple linear interpolation between them output = linear(time, previous_keyframe.time, next_keyframe.time, previous_keyframe.value, next_keyframe.value); } else { // But, if one is missing, just return the current value output = value; } output; ``` ### Taking a moving average to smooth over janky keyframes Sometimes you’ll generate one keyframe for every frame of the video (eg by 3D camera tracking and the like), but these keyframes can jump occasionally for no good reason. One way to cover this if precision isn’t important is to just smooth over the changes with a moving average: ```javascript // Number of frames (forward and backward) over which to average window_frames = 60; // Loop from -window_frames to +window_frames, summing the values mav = 0; for(i=-window_frames; i<=window_frames; i++) { t = time + i; x = valueAtTime(t); mav += x; } // Divide by the total number of frames averaged over to get an average mav /= window_frames*2; // Use the resulting value mav; ``` When using angles, the moving average approach might not work. eg with orientation, values close to ‘0’ may be 1° or 359°. There’s probably a slightly more general way to write this depending on the place your values are centred on, but here’s a quick kludge for the most common case: ```javascript window_frames = 60; // function to make values near 360 be small negative numbers function rebase(x) { for(j=0; j<3; j++) { if(x[j] > 180) { x[j] = 360-x[j]; } } return(x); } // function to return small negative numbers to be near 360 function unrebase(x) { for(j=0; j<3; j++) { if(x[j] < 0) { x[j] = 360+x[j]; } } return(x); } mav = 0; for(i=-window_frames; i<=window_frames; i++) { t = time + i; x = valueAtTime(t); // Add the value after 'rebasing' mav += rebase(x); } mav /= window_frames*2; // Use the corrected value unrebase(mav); ``` ## Text ### Make text appear character by character ```javascript text.sourceText.substring(0, effect("Slider Control")("Slider")); ``` Simply add a slider control in the text layer, and this allows the text to ‘type’ to appear (or do a bunch of other stuff, obviously). ### A simple clock ```javascript offsetHours = 0; offsetMinutes = 0; offsetSeconds = 0; timeOffset = offsetHours*3600 + offsetMinutes*60 + offsetSeconds; realTime = time + timeOffset ; hh = ("00"+Math.floor(realTime/3600)).substr(-2); mm = ("00"+Math.floor((realTime/60)%60)).substr(-2); ss = ("00"+Math.floor(realTime%60)).substr(-2); mm + ':' + ss; ``` This is a general-purpose script to write a clock that starts at `offsetHours` etc at the start of a composition, and outputs the time to a text layer. The adding zeros at the start and taking a substring thing is a kludgey way to ensure leading zeros. This simple version has no offset and displays minutes and seconds, so it’s just the video playback time. ### Deleting and typing text by keyframes Using the previous and next keyframe functions (defined elsewhere), this function will look ahead to the next keyframe in some text and delete the existing text ahead of it at a rate defined by a slider, and then type the new text after it at a rate defined by a different slider. I realised after writing this that it doesn’t actually need the `prevKey()` and `nextKey()` functions, you could just use `nearKey()` and do different things depending on whether `time - nearKey(time).time` was positive or negative. At least this is clearer! ```javascript function prevKey(prop = thisProperty) { if(time < prop.nearestKey(time).time) { prevIndex = prop.nearestKey(time).index - 1 if(prevIndex <= 0) { return(false); } else { return prop.key(prevIndex); } } else { return prop.nearestKey(time); } } function nextKey(prop = thisProperty) { if(time >= prop.nearestKey(time).time) { nextIndex = prop.nearestKey(time).index + 1 if(nextIndex > prop.numKeys) { return(false); } else { return prop.key(nextIndex); } } else { return prop.nearestKey(time); } } // Get the per-character deleting and typing times from the control layer deleteCharacter = thisComp.layer("controls").effect("delete time")("Slider"); typeCharacter = thisComp.layer("controls").effect("type time")("Slider"); // Get the previous and next text values prevText = prevKey().value; nextText = nextKey().value; // Find out how long it would take to delete and type them, respectively deleteTime = prevText.length * deleteCharacter; typeTime = prevText.length * typeCharacter; // Find out how far away the nearest or next keys are timeSincePrevKey = time - prevKey().time; timeToNextKey = nextKey().time - time; // if(timeToNextKey < deleteTime) { texty = prevText.substr(0,Math.round(timeToNextKey/deleteTime*prevText.length)); } else if (timeSincePrevKey < typeTime) { texty = prevText.substr(0,Math.round(timeSincePrevKey/typeTime*prevText.length)); } else { texty = prevText; } texty; ``` ## Data-driven animation ### Accessing data within a CSV The most general way to do this is using the `.dataValue()` function, which is called in a slightly weird way. You need to have your footage in the composition, but then you don’t call it from its layer, but using the `footage()` function, and then use zero-indexed row and column numbers to access the values, which are accessed backwards, as column, row, because of course they are: ```javascript footage("my-data.csv").dataValue([column,row]) ``` ## Shape layers ### Make a bar grow from the left By default, the anchor point on a rectangle in a shape layer is `[0,0]`, which means, if you increase its size, it will grow from the centre. For a graph, you might want it to instead grow from the left. Putting this expression in the shape’s *Transform > Anchor Point* property will fix this by dynamically moving the anchor as the rectangle expands: ```javascript [ -thisLayer("Contents")(thisProperty.propertyGroup(2).propertyIndex).content(1).size[0]/2, 0 ]; ```