After Effects CS6 Tutorial: Targeting Properties in the new Ray-Traced 3D Engine
Chris and Trish Meyer | 04/25
Although the new extrusion and beveling capabilities initially seem limited, you can actually edit the individual material options for each group of surfaces.
The latest version has several significant new features.
3D Camera Tracker
Clip CAN119 courtesy Artbeats.com
The big new visual effects feature in After Effects CS6 - which will also be highly useful for motion graphics artists - is a new 3D Camera Tracker. Rather than tracking an object in already-shot footage, the 3D Camera Tracker tracks a number of objects, and then tries to reverse-engineer where the camera originally was. It can then create a corresponding Camera layer, and can place new 3D layers at coordinates that line up with objects and surfaces it found in the original scene. This means you can add new layers in After Effects that seem to have camera movement and perspective changes that match already-shot footage.
As is the case with the Warp Stabilizer introduced in CS5.5, the 3D Camera Tracker is highly automated, automatically determining which points to track. Another similarity is that you can use a precomp to mask out areas you know should not be tracked (such as a stationary bug in a scene with a moving camera, or a person moving in the scene separate from the camera’s motion), yielding better results. However, unlike the Warp Stabilizer, the 3D Camera Tracker exposes the track points it chose, making it possible to verify that it used good points, and enabling you to delete points where the track goes astray. You can also enter additional information such as the original camera’s angle of view, whether it had a fixed lens length or was zooming, and broad settings of how the scene was shot.
To create new objects in this world, you can choose an individual point, have After Effect triangulate between a trio of points (shown in the figure above), or manually select a group of points to average together for reference. The latter is the preferred approach, as you can explicitly select good track points on a surface (the further apart the better), or select multiple points and let After Effects average them together (it can also automatically reject bad points you might have accidentally selected). You can create text, a null object, or a solid (which you can then swap out for a footage layer) that can be used directly or as a parent for another footage layer. Another new feature in After Effects CS6 is the ability to hold Shift while parenting a layer to another; this zeros out its positional offset, placing it exactly where the null or other parent layer is located.
A really nice trick is the ability to create a “shadow catcher” layer: a white solid that is set to only receive shadows (a new parameter option in CS6). This makes it easier to have your new layers appear to cast shadows on objects on items in the original 2D scene, which is normally not possible without a bit of manual trickery.
This is a case where you need to be very conscious of which 3D rendering engine you choose. As noted on the previous page, the new Ray-traced 3D renderer does not support effects, masks, mattes, or modes - and can take longer to render as well. Quite often you will want to use effects or blending modes to match your new footage into your scene (as shown below), and use masks or mattes to cut out portions that are not supposed to be visible to simulate them being obscured by objects in the original scene (for example, appearing to pass behind a foreground building).
Inevitably, the question will be asked if this is a replacement for The Foundry’s CameraTracker. For many applications, it is. However, The Foundry’s plug-in allows much more control over refining your track, including the ability to remove lens distortion - so it will remain the choice for some industrial-strength tasks.
By the way, a small side effect of the addition of the 3D Camera Tracker is that the Tracker panel in After Effects has received a slight (and welcome) overhaul, making it clearer if you’re applying the traditional point tracker or stabilizer, the new Warp Stabilizer, or the 3D Camera Tracker.
Track in mocha
Clip courtesy Kevin Dole
While on the subject of tracking, we should mention that Imagineer Systems’ mocha AE is still bundled with After Effects, and is better integrated as well. Instead of launching a separate application, you now select the footage to be tracked inside an After Effects composition, and choose the new menu command Animation > Track in mocha AE. mocha AE will honor the layer’s In and Out trim points, as well as the frame rate, field order, and pixel aspect ratio from After Effects, making the process more fluid and less error-prone. Note, however, that you still need to manually copy and paste the tracked data from mocha back into After Effects.
The one downside of this new scheme is that mocha AE can’t be launched on its own any more - including by Mathias Möhl’s excellent MochaImport+ add-on for After Effects. Hopefully the complications this presents will be resolved in the not too distant future.
Rolling Shutter Repair
The image on the left is a slow pan shot with a Canon 5D mkII, which has a CMOS sensor: Note how the building and its posts are leaning to the right, even with this slow movement. The image on the right is after Rolling Shutter Repair.
An outgrowth of the Dynamic Media Advanced Product Development Group’s work on Warp Stabilizer and 3D Camera Tracker is a new Rolling Shutter Repair effect in After Effects CS6. This simple effect strives to remove some of the “jello cam” effect we’ve come to know and love hate in footage shot with CMOS sensor cameras such as DSLRs. We’ve found it to be very effective on some shots, such as camera pans and wobbly hand-held shots where there is not a lot of conflicting motion (one object moving one way, and another object moving a different direction). It is somewhat less successful on shots with conflicting motion, such as car drivebys where the road and background is stationary, and the car is moving: It has trouble determining which pixels to unwarp and which to leave alone, even when set to Pixel Motion mode with maximum Pixel Motion Detail. Sometimes, reality is just hard. But it’s a welcome addition, helping to straighten out many shots before you attempt to composite in new non-jelloed layers.
Variable Mask Feathering
Clip LM111 courtesy Artbeats.com
A long-requested feature in After Effects has been the ability to change the size of the feather around a mask shape. That wish has finally been granted in After Effects CS6 with a new Mask Feather tool. You can add as many feather points as you like around a mask outline - they don’t have to be aligned with normal mask verticies - and drag them either in or out (but not both at the same point). Similar to the way Auto Bezier mask points work, you don’t have explicit Bezier handles for the feather outline; instead, you Option (Alt) drag a mask feather point to alter the “tension” of the feather outline around that point. As shown above, you can also right-click a mask feather point to bring up additional options including the Radius (similar in operation to a brush size) and Corner Angle for each feather point.
A Layer > Mask option also allows you to set the Feather Falloff. A Linear falloff in opacity creates the optical illusion of a hard edge where the feathered falloff begins; the default setting of Smooth has an S-shaped falloff curve, which has fewer artifacts. This can be set per Mask Path, so make sure you select the desired mask before trying to get the menu command to work.
The figure on the left uses a Linear falloff for the mask feather, which makes transitions more obvious; the default of Smooth on the right often yields more visually pleasing results, although it may require tweaking the mask shape and feather outlines to get the result you envisioned.
There have been other minor tweaks to the Pen tool as well. Pressing G now toggles between just the Pen and Mask Feather tools, rather than scrolling through the entire list of options. If you like the old behavior, you can revert to this by unchecking Preferences > General > Pen Tool Shortcut Toggles Between Pen and Mask Feather Tools. In either mode, hovering the cursor over a mask point no longer auto-switches to the Delete Vertex tool; the Selection tool remains active unless you also press Command on Mac (Ctrl on Windows).
next page: Global Performance Cache, plus other improvements and issues
A quick review of what’s changed in recent versions
After Effects CS5
Here is a quick video introduction to the big new features in After Effects CS5:
Overview of New Features in After Effects CS5
Some of those features included the major new Roto Brush effect, an upgrade to the bundled tracker mocha plus the addition of mocha shape, the bundling of the Digieffects FreeForm 3D warping effect (as well as a nice update to the bundled color correction effect Color Finesse), the ability to import extruded Adobe Repoussé layers from Photoshop CS5, vastly improved support for RED footage as well as the ability to apply some color LUTs (look-up tables) to any footage or comp, improvements to color management, more blending modes, new and updated effects borrowed from Photoshop, and more.
Perhaps most important is that After Effects became a native 64-bit application, requiring a 64-bit operating system and for all of your third-party plug-ins to be updated. This has held back many users from upgrading, but the vastly improved memory management and performance (including longer RAM previews) has proved to be more than worth it. For those who purchased the suite but are still running an older OS, an installer for After Effects CS4 was included in the relevant CS5 suites.
For more comprehensive coverage of these features, check out:
As we did not yet have enough experience using mocha when After Effects CS4 was released, we avoided providing advice on how to use it, afraid of inadvertently teaching you a wrong approach. Fortunately, we had more experience by the time CS5 rolled around, and also worked with the helpful folks at Imagineer Systems to determine a set of preferred working practices. We cover those in this introductory mocha video:
mocha Basic Tutorial
CS5 saw another major update in the 3D capabilities of not After Effects, but Photoshop - this time with the addition of their extrusion technology Repoussé. Although you cannot create Repoussé objects directly inside After Effects, you can import layered Photoshop 3D files and perform camera moves around the result inside After Effects.
Frankly, if you have the budget for third-party effects, you are better off with solutions such as Zaxwerks Invigorator Pro or ProAnimator, the 3D Objects effects inside Boris Continuum Complete, or the upcoming Mettle Shapeshifter AE. However, we know many of you work inside corporate environments where you get an Adobe suite and that’s it. For those, the following two movies show how to use Repoussé inside Photoshop, and then manipulate the results inside After Effects:
Repoussé inside Photoshop
Repoussé inside After Effects
However, the really big feature in After Effects CS5 was Roto Brush: a new technology that helps automate the separation of a foreground object (such as an actor) from its background. Fellow After Effects user, PVC Founder, book author, and lynda.com trainer Mark Christiansen created his own After Effects CS5 New Features course for lynda.com; he recorded the following two movies to provide you a quick start for using Roto Brush:
Making a Quick Selection with Roto Brush
Refining a Matte with Roto Brush
Mark also gave a quick demonstration of the new Photoshop-derived color effects and blending modes added to After Effects CS5:
Making Use of Updated Color Effects and Blending Modes
(We included Roto Brush, the new color effects and blending modes, and many other subjects Mark covered in our own New Creative Techniques course as well; it’s good to see different perspectives as Mark comes from a visual effects orientation while we come from a motion graphics orientation.)
A series of videos demonstrating how to put the new features to work.
Warp Stabilizer
This is the headline new feature in After Effects CS5.5: Just apply it to a clip, wait for it to process, and now the bumps in the camera movement have been smoothed out without any user intervention required. A single parameter allows you to adjust the amount of smoothness; a simple pop-up allows you to completely lock down the shot. Of course, there is a lot more power under the hood…
Warp Stabilizer Instant Gratification
See how to quickly apply the new Warp Stabilizer to footage for instant gratification, including setting the Smoothness amount as well as choosing between Smooth Motion and No Motion:
Warp Stabilizer Basic Parameters
Learn more about the new Warp Stabilizer’s Result and Smoothness settings, Stabilization Method, choices for how to treat the borders of an image, and automatic scaling options.
Warp Stabilizer Advanced Parameters
Explore the new Warp Stabilizer’s advanced settings, including its innovative Synthesize Edges option. In the process, you will learn how to make custom adjustments to compensate for problem footage.
Outsmarting the Warp Stabilizer
The Warp Stabilizer’s ability to automatically distinguish between foreground and background requires user intervention on some shots, such as a greenscreen stage with tracking dots in the background. Learn how to work around these issues.
There have been two early criticisms of the Warp Stabilizer: You currently can’t reverse the process (so you can’t stabilize a scene, add or touch up an element, then re-introduce the original camera motion), and that it has taken over the traditional Stabilizer’s button. If you still need to get access to the original AE Stabilizer (i.e. for the case spelled out in the first complaint), it can found still lurking in the Tracker panel: click Track Motion (not Stabilize Motion), and then switch the Track Type to Stabilize.
Deeper Modes of Expression, Part 12: Expressive Text
Chris Meyer | 11/28
In this final installment in our series, we’ll demonstrate several ways to manipulate numbers and text using expressions.
Strings of Text
In addition to numbers, you can have Source Text display text. To do this, put the characters you want inside quotes – like “Creating Motion Graphics”. This is referred to as a text string, or string for short. You can add together text strings to make a longer strings: For example, “Creating ” + “Motion ” + “Graphics” would give the same result (note the spaces after the first and second words; + does not automatically add spaces). You can also define the text inside expressions using ASCII character codes. For example, String.fromCharCode(50) produces the letter “C”.
If you want to insert carriage returns between pieces of text, place the characters \r wherever you want a return. An example of this is at left and below: “Creating\rMotion\rGraphics” places each word on its own line. Select the layer and edit the Leading parameter in the Character panel to change the spacing between lines; use the Paragraph panel to change the justification (left, right, or centered).
If you want to display a single character in a string, you can “index” into it just as you would an array of numbers. If your expression for Source Text was my_text = “Creating”; my_text[0], just the letter “C” would be displayed. If the second line was my_text[5], the letter “i” would be displayed. (Remember that JavaScript thinks the first number in an array is 0, not 1!) Also, when you’re indexing into a character string, you must give After Effects a whole integer number – otherwise, it will display “undefined” in your comp.
In the example below, the second and third layers display individual characters, based on what frame it is in the comp. The second layer has an expression designed to go through the entire string once, then stop on the last character:
The first line creates the text string we’re using. The second line converts the current time in the comp into a frame number (an expression we discussed earlier). The third line uses the clamp method we discussed way back in the first installment on math operations: It says take the frame number and restrict it to the range between 0 (the first character) and our_text.length – 1 (our last character). You can add .length onto the end of any variable that holds a string to see how many characters are in the string; unlike most expression methods, .length starts counting at 1, instead of 0 – that’s why we had to subtract one from it to create the index we will need.
The last line says display the character that equals the frame number, clamped in the previous line to not go beyond the last character (which we entered to be a space). A variation on this theme would be to replace the clamp method with the modulus operator % (discussed earlier) so that we would keep repeating the same characters over and over again. These two respective expressions would look like:
You can also enter a number of words or characters as a string, then pick which one of them you want to display. To do this, use the .split()[] function. Pick a unique character to show where the breaks between individual words or phrases are. Then add .split()[] onto the end of any variable that holds your text string.
An expression for Source Text that said my_text = “Creating,Motion,Graphics”; my_text.split(“,”)[1] would tell After Effects to look for a comma to decide where to split your string, then index in to display the second word (remembering that [1] means the second, not the first, value in an array – again, most counting starts at 0!).
The first line uses the posterizeTime method which says to run the expression only three times a second.
The second line is our string, using commas to divide our words.
The third line creates a random number between 0 and 2 (there are three words in our string, and counting starts at 0), while the method Math.round says round this random number to the nearest whole number – After Effects will display “undefined” if it gets an index other than a nice, clean integer.
The final line splits our string at the commas, then displays the random word chosen in the line above.
There is much more you can do, obviously, but this gives you the fundamentals of how to deal with strings, words, and characters. The rest, as they say, is limited only by your imagination (and JavaScript programming skills).
A clever use of expressions to manipulate text is the Buzz Words animation Preset (look in the Effects & Presets panel under Animation Presets > Text > Expressions > Buzz Words). Apply it to a text layer, and then type EE to reveal the associated expression:
Enter words you wish to step through in the first line, between the vertical bars (note that the | character is used to split the text string), adding or removing words as desired. This expression uses the expression method split_buzz_words_array.length to automatically determine how many words you entered. The preset also automatically adds an Effect > Expression Controls > Slider named “Buzz Frame Rate” to set the speed at which you cycle through the words.
Of course, you can use expressions to control virtually any other parameter of After Effects text – such as point size or tracking – that you’ve added to your text layer using the Animate or Add > Property popup menus.
This underutilized, recently-added feature provides numerous ways to enhance your footage.
The original clip we’re enhancing (Artbeats GU127H1).
Modes are grouped by similar function. Not all modes are equally useful; I will focus on what I feel are the best ones out of each group. Rather than going through the groups in order, I’m going to jump straight to my favorite eye candy group: What I call the “lighting” modes including Overlay, Soft Light, Hard Light, Vivid Light, and Pin Light.
Overlay
Overlay is often the first mode I reach for when I want to combine two clips in sexy, interesting ways, as it tends to increase the contrast and apparent saturation of the original clip. Technically, the lighter areas of the enhancement clip on top will lighten the corresponding areas of the original clip underneath, the darker areas in the enhancement clip will darken the corresponding areas in the original clip, and areas that are 50% gray in the enhancement clip have no effect on the original clip. Given that, note in the first example above that the predominantly dark enhancement clip has the overall effect of darkening the original, while the predominantly light second clip lightens the result.
Overlay is also an excellent choice when compositing a clip back on top of itself (the fourth example above). If no effects are applied to the copy on top, the result is increased contrast and saturation, which is great for improving washed out or flat footage or 3D renders; applying a bit of blur to the copy on top adds subtle blooming to both the highlights and shadows.
Soft Light
Soft Light is a subdued version of Overlay - there is less saturation added, and the result usually will not clip in the highlights and shadows. Overall, the contribution of the enhancement clip will be more subdued. (Of course, you can control the depth of any of these effects by altering the Opacity of the moded clip on top.)
Hard Light
Hard Light is an amped-up version of Overlay, with increased contrast and usually more saturation. Note that in the final mix, the enhancement clip tends to appear more prominently than the original clip underneath.
Linear Light
Technically, Linear Light is supposed to be an amped-up version of Soft Light (increasing or decreasing the brightness of the original clip based on the pixel values of the enhancement clip), but the result looks more like a slightly amped-up version of Hard Light. Use it when Hard Light gets you close, but you want it to go to 11.
Vivid Light
Vivid Light continues the progression, offering an even more amped-up version of Linear Light. For those with a Photoshop background, it dodges and burns the underlying original clip based on the pixel values of the enhancement clip, resulting in more of a color shift in addition to the extreme contrast. As with Hard Light and Linear Light, the composite favors the image on top; you can try reversing the stacking order of the clips in the timeline for an alternate look (don’t forget to set the Blend Mode for the new top clip!). And again: You can always reduce the Opacity of the enhancement clip to dial back the effect.
next page: Linear Dodge, Screen, Color Dodge, Multiply, Color Burn, and Linear Burn modes
Deeper Modes of Expression, Part 11: Dreaming in Color
Chris Meyer | 11/07
Using expressions to choose, modify, or create master colors.
Sampling Colors
After Effects CS3 added an expression method that allows you to sample the color of a pixel or group of pixels in an image. You can use this power to do something as simple as matching the color of a lower third bar to a changing color in a background, or as complex as writing your own color correction or flicker reduction effects.
Like many expression methods, sampleImage can be quite simple, or quite complex. Its basic form is sampleImage(point) where point is a position derived from an effect point or another layer. In this form, sampleImage will sample just the one pixel located at that point (the default radius is 0.5 pixels), after any effects have been applied to the layer, and at the current time.
The full-blown version of this method is sampleImage(point, radius, postEffect, time) where radius is a two-dimension array (the X and Y range of how many pixels are being sampled), postEffect is a Boolean (replace it with either true or false), and time is a numeric value. You can leave out time, or postEffect and time, or radius, postEffect, and time.
The example at left and below contains a simple application of sampleImage. Note where the cursor is pointing in the image at left: this is the Effect Point being used to sample the underlying footage, The yellow rectangle in the lower left is the area being colored based on this Effect Point.
Image DG101 courtesy of Artbeats.
To accomplish this, we added an Expression Controls > Point Control to this layer, and renamed it “sample point.” Next, we created a small mask path (with its mode set to None) on the movie layer and used Generate > Fill to color this masked area. Finally, we applied the sampleImage expression to Fill’s Color swatch, and used the pick whip to wire it to follow the point controller. The resulting expression is:
sampleImage(effect(“sample point”)(“Point”))
Below is a more complex example that points out some real world considerations for using sampleImage. The image whose color we wish to sample – DV_MusicMix.jpg – is larger than the comp. We also want to use another layer – CM_sensor_crl.tif (where the cursor is pointing in the image below) – to determine which pixel we are sampling. We’d like to have easy control over how many pixels we’re averaging together to determine our selected color. Finally, we want to apply the resulting color to yet another image: the shape layer Hex Button (as well as bevel highlight color of the Layer Style applied to it).
Image courtesy Digital Vision/Music Mix.
To pull this off, we applied two Expression Controls to DV_MusicMix.jpg: a Slider Control we renamed “set_sample radius,” and a Color Control we renamed “out_sample color.” We then pick whipped the color for Hex Button’s Fill attribute to out_sample color.
Next, we started working on the expression for DV_MusicMix’s out_sample color effect. First, we need to translate from the CM_sensor_crl’s position in comp space to DV_MusicMix’s own layer space. To do this, we created a variable for DV_MusicMix.jpg called samplePoint, and used the fromComp() expression discussed earlier in this series to do the translation. When pick whipped to the sensor layer to fill the parenthesis for fromComp().
We then created a variable called sampleRadius, and pick whipped to the “set_sample radius” slider to get its value. As it turns out, sampleImage returns an error if you set its radius to a value equal to or less than 0, so we added a quick if/then statement to make sure it was no smaller than 0.5 pixels.
The final line of the expression – sampleImage(samplePoint,[sampleRadius,sampleRadius]) – uses these variables we’ve created. We had to repeat sampleRadius twice inside brackets to convert the one-dimensional slider value into the two dimensions that the radius value requires. (You could also have used a Point Control in place of the Slider Control for set_sample radius in order to give yourself independent control over the X and Y radius of the area being sampled.)
The final expression for DV_MusicMix’s Color Control is:
As we drag the sensor layer around in the example above, we get color changes in the hex button based on the pixel underneath the crosshairs of the sensor. If we were to increase the value of the set_sample radius slider and drag our sensor around, the color changes would be more gradual, as adjacent pixels would be averaged together. Of course, you can animate the sensor’s position as well.
(Note: You may might notice the user interface “flashes” occasionally while working with the sampleImage expression. This is just a side effect of the serious voodoo After Effects is performing underneath the hood to make sampleImage work.)
Next Installment: Expressive Text
In our last installment, we will show how to use the mysterious Expression Selector to control individual characters in a text layer. Until then…
We’re in the process of serializing the Deeper Modes of Expression bonus chapter from our book Creating Motion Graphics with After Effects into a set of 12 posts here on PVC.
The latest edition of Creating Motion Graphics - covering the updates introduced in After Effects CS4 and CS5 - is shipping now.
The content contained in Creating Motion Graphics with After Effects - as well as the CMG Blogs and CMG Keyframes posts on ProVideoCoalition - are copyright Crish Design, except where otherwise attributed.
Deeper Modes of Expression, Part 7: Making Decisions
Chris Meyer | 07/04
Learning how to craft if/then/else statements plus do/while loops will open the door to a wide range of advanced techniques.
If/Then Continued…
Now let’s put if/then tests to a more practical application. You might remember in our previous installment that we had a layer scale up as it approached a layer marker, then scale down as it moved away from a layer marker. What if we wanted the layer to stay at Scale = 0% until it reached a marker, then jump to 50% and scale down from there? The answer is in the question: Use an if/then statement. In the example below, we’ve modified our prior example to use an if/then statement to give us this modified behavior:
As a quick review, this expression sets up our preliminary Scale value and figures how close we are to the nearest marker. If the resulting time is 0 or greater, that means we just passed the nearest marker, and we can get about the business of replacing our temporary Scale value with a number based on how far away from that marker we are. The linear interpolation function does the ugly math for us of converting 0 to 0.5 second to 100% to 0% Scale; as before, we have it calculating a two-dimensional array for Scale – that’s why we included [50,50] and [0,0] as the upper and lower ranges. The last line plugs in our final answer. (Sometimes you can leave out the final recapitulation of the answer, but we prefer to state it for clarity.)
Study the position of the time indicator relative to the marker and the resulting red Scale value in the series of figures below: You will see Scale is 0% just before the marker (when the “if” test fails), 50% right on the marker (the result of the “if” interpolation being executed, with time_to_marker = 0), and slowly returns to 0% as the current time moves past the marker:
Not all is perfect in our world: After Effects tells us only where the nearest keyframe or marker is – not where the next one is. In this example, we are trying to fade out the layer over 0.5 seconds. If two markers are less than one second apart, we won’t get a chance to get 0.5 seconds away from the marker we just passed; we will already be closer to the next (the “nearest”) marker. This will cause the layer to suddenly jump to 0% scale on the frame before a too-close marker, then resume its programmed behavior from that new marker onward.
You can either start writing even more complicated if/then checks that look at the index numbers of markers and alternate expressions that do something else if markers are too close…or just copy and paste keyframes. We’ve said it before, and we’ll say it again: Don’t write expressions for the sake of writing expressions; write them because you think they’ll save you time and free you up to be more creative. (Or at least, allow you to get more sleep.)
Testing Other Types of Parameters
Some attributes don’t have numeric values; they have yes/no or true/false answers – such as whether the layer has an audio track. These tests need slightly different symbols. If you wanted to test for the presence of audio at the start of an if/then statement, you would type:
if (has_audio == 1)
The == symbol (also known as the “is-equal-to” operator) looks for a logical match, rather than a numeric one. The value 1 means true (or turned on, or enabled); 0 means false (or turned off, or disabled). The symbol != means “is not equal to.”
Note that the double equals signs has a very different meaning than a single equals: Writing has_audio = 1 would try to sethas_audio to a value of 1, rather than compare it with a value of 1.
There are even more complex operators and tests, such as AND (&&) and OR (||). Rather than go down all these side streets here, at this point we’re going to turn you over to a JavaScript book (we like JavaScript: A Beginner’s Guide by John Pollock).
Error Checking
What if there was no marker to look for in the examples above? Then After Effects would return an error, and turn off the expression.
This is another case in which if/then statements can come in handy: to check to see if a property you are asking for even exists. You shouldn’t run into problems like these if you are writing an expression for just one layer – you would just remember to add a marker, for example. However, if you have complex expressions that you plan to reuse later, or that you intend to hand off to someone else to use, if/then error checks allow you to “bulletproof” your expressions against special circumstances or user error.
Below is an updated version of our previous example, with some error checking added. After we set up our temporary value for opacity, we use an “if” test to see if any markers are present. If so, we then go into a second if/then statement embedded inside this overall error test. This embedded code is the same that we demonstrated previously, turning a layer’s Opacity on only if we have passed the first marker in the layer.
If you get lost reading that expression, search out the curly brackets: They indicate the “then” part of the expression. In the first test – if (marker.num_keys > 0) – if the answer was false (in other words, marker.num_keys = 0), then After Effects will ignore everything inside the pair of curly brackets that follow.
The opening curly bracket is obvious – the hard part is finding its corresponding close bracket. If you find another open curly bracket while you’re looking for the close bracket, this new open bracket belongs to another if/then statement that is buried inside the one you were working your way through. You then need to look for two close brackets: the first one is for the nested if/then statement, and the second one is for the original if/then statement you were trying to finish off.
Nested if/then statements are hard to read; that’s why some use an approach of indenting lines that are inside if/then statements, and even using extra lines and spaces to make sure the curly brackets for each separate if/then statement line up with each other:
In short, if you’re having trouble getting the logic of an expression or interpolation method to behave, consider using if/then statements to break it down into separate conditions (for example, a value is above or below an important threshold), and then solve your problem a piece at a time.
next page: creating while/do loops to accumulate numbers over time
Deeper Modes of Expression, Part 6: Managing Time, Layer Numbers, Speed, and Velocity
Chris Meyer | 06/06
Ways of manipulating time with expressions, including having one layer echo the movements of another with delay.
Indexes and Time
The valueAtTime method is an excellent way to create a number of layers that all follow another. However, it quickly becomes cumbersome to edit the expression for each layer – for example, giving each layer its own time delay setting. This is where the concept of layer indexing comes in handy.
You can refer to layers two different ways inside an expression: either by its name (surrounded by quotes), or by its number in the Timeline panel stack (no quotes necessary). A layer’s own number is referred to as its index; you can offset this index to look at other layers that are above or below the layer that has the expression applied.
Here is an alternate version of the text example shown on the previous page, which uses this indexing method.
In this example, word 2’s Opacity has this expression applied:
What this expression says is rather than look for a layer with a specific name, use my own index (layer number), subtract 1, and use that layer’s value. As word 1 is above word 2 in the Timeline panel, this expression for word 2 points to word 1.
What is really cool is that we can use the same expression for each layer in the comp. This means each word would delay itself by the same amount of time compared with the word above it in the chain, rather than just word 1. This makes it easy to copy and paste the same expression to multiple layers, apply it with an Animation Preset, etc.
You must keep track of the layer order in the Timeline panel: Swap the order of the layers around, and the layers will respond differently, following whoever is above. If you drag word 2 to the top of the layer stack, you will get an error message, because it’s impossible for it to look at a layer with an index = 0 (1–1). (We’ll discuss error checking and recovery in a later installment.) On the upside, since the expressions are looking at a layer’s number rather than its name, you can save Animation Presets that aren’t reliant on a specific layer name in order to work.
Absolute versus Relative Indexing
The trick of looking at a layer that’s a certain number above or below your own layer number is referred to as relative indexing. It works great, but it starts to break down if you have too long of a chain of layers looking at each other. It takes After Effects a lot of time to say “For my value, I have to look at the layer above me…who has to look at the layer above it…who has to look at the layer above it…who has to…” The result can have a slight effect on performance and rendering times.
Once you get past about four or so of these references, you should give serious thought to using absolute indexing, which sets values based strictly on the layer’s own number. Using absolute indexing requires discipline in stacking layers properly in the Timeline panel, but pays you back in improved responsiveness. Let’s put it to work.
Let’s put this concept to work with our staggered word fade example. We still want our other words to follow word 1’s lead, but to delay them based strictly on their layer number. Our expression then becomes:
This expression works only if the master – word 1 – is placed at the top of the stack as layer 1, and all of the other words are stacked immediately below it. The first line takes the layer number (index) of a staggered layer, subtracts 1 to compensate for the master layer being on top (in other words, the first delayed layer is the second layer, which should only be delayed once, not twice), and multiplies the result by 0.5 seconds. Each higher-numbered layer gets an additional 0.5 seconds of delay. The second line then says to look at the Opacity of layer 1 (word 1 in this case), and then offset the time you look at it based on the stagger_time we calculated in the first line. This is shown below:
These layers use expressions based on their layer index (number), not their names. This means you can rename them without breaking the expression, but reordering them in the Timeline stack will change how they behave.
Yes, using absolute indexing is a little more confusing, but the results will render a little bit faster. And by just thinking a little, you can rearrange the relative timing of layers just by dragging them up and down the layer stack in the Timeline panel.
Of course, the danger here – and with expressions in general – is that you may spend more time and energy being clever than you would have spent merely copying, pasting, and sliding keyframes around. Clever is nice, but clarity and meeting deadlines are even better…
next page: deriving a parameter’s speed and velocity
Deeper Modes of Expression, Part 5: Comp, Footage, and Layer Attributes
Chris Meyer | 05/01
Grabbing numbers from places such as the comp settings.
Frames and Seconds
Expressions, as well as most effects, think of time in terms of seconds. However, most animators think of time in term of number of frames. You can use comp and footage attributes to automatically translate between the two for you.
After Effects features a pair of expression methods – timeToFrames() and framesToTime() – which make it easy to convert these two ways of representing time. You can enter one, two, or three parameters in the () of these methods. If you enter just one number, it is used as the time or frame number you want to convert from. For example, if you want to know the current frame number of a composition, you would write timeToFrame(time) (as time is always the current time in a composition, in seconds).
If you enter two numbers inside the () for these methods (separated by commas), the first number is still the time or frame number, and the second number is the fps (frames per second) value. This number defaults to the comp’s current frame rate; if you instead wanted to know how the current time in seconds would translate to a frame number if the frame rate was 12 fps, you would write timeToFrames(time, 12).
The third, optional value inside () is known as isDuration; it defaults to false. If instead of an absolute frame or time number, you were calculating the difference between two different values, the result may be negative. (This is where the potential rounding errors we discussed back in the first installment with Math.floor and Math.ceil might creep in.) If you set this value to true, the result will always be rounded away from 0, which is generally what you want. Say you had an expression where you calculated a value – time_difference – that you now wanted to convert to the nearest whole frame, at a rate of 24 fps: You would use timeToFrames(time_difference, 24, true).
A simple example of using one of these methods is shown here. The Echo effect requires you to set its Echo Time as a number of seconds. To compute this as a number of frames, we added a Slider Control where we could set the number of frames. Then for the Echo Time parameter, we wrote framesToTime(, dragged the pick whip to our slider, typed ), and press Enter. The resulting expression is:
In addition to these handy time and frame methods, After Effects also provides a pair of attributes to help us find the duration of a frame, either at the comp’s frame rate, or the source layer’s frame rate:
thisComp.frameDuration: the length (in seconds) of one frame, using the comp’s current frame rate
source.frameDuration: the length (in seconds) of one frame of the source or precomp, using its own frame rate instead of the comp’s
To convert either of these to a frame rate value, rather than a frame duration, place 1 / before them. For example, 1 / thisComp.frameDuration gives you the comp’s frame rate.
(A complete list of attributes is available as part of the Expression Language Reference section of the After Effects Online Help.)
Next Installment: Managing Time
Continuing the theme of calculating time, the next installment will discuss tricks such as setting up delayed animations using valueAtTime, using indexing to change a layer’s values based on its index in the Timeline, finding the rate at which a value changes, and triggering animations based on markers. Until then…
We’re in the process of serializing the Deeper Modes of Expression bonus chapter from our book Creating Motion Graphics with After Effects into a set of 12 posts here on PVC.
The next edition of Creating Motion Graphics - for After Effects CS5 - is due out by the end of June 2010.
The content contained in Creating Motion Graphics with After Effects - as well as the CMG Blogs and CMG Keyframes posts on ProVideoCoalition - are copyright Crish Design, except where otherwise attributed.
All rights reserved. HD EXPO, High Def EXPO, Createasphere, E-Tech, Entertainment Technology Exposition, 3D Production Workshop, VariCamp, P2 Camp, ColorCamp 101, and Lighting, Filters & Gels for HD are all trademarks of HD Expo, LLC.