Halloween Costume ideas 2015
Articles by "blending"
@dorothiar #arttips #interview 101 2 Column Template 2012 mentee 2013 2013 mentee 2014 2014 mentee 2014 Portfolio Winner 2014 SCBWI Portfolio Mentorship Winner 2015 mentee 3 Column Template 360 3d 3d print 3d printing 3delight 8bit Abbey McCulloch abstract acryla gouache acrylic action addon adobe Adobe Flash CS3 Adobe Illustrator Advanced Tutorials advection Advertising advice Agata Wierzbicka agents airplane Al Wiseman ALA Alan E. Cober Alan Lee Alex Ross Alexandra Compain-Tissier Alexandra Lekias Alexandra Levasseur Alexandre Korobov Alexis Winter algorithm alien ALT Amelie Hegardt Amit Shimoni amusement an Ana Aranda analog Andrea Hrjnak Andrea Hrnjak andrea offermann andreaoffermann andreazuill Andy Musser Angela DiTerlizzi Angelika Peißker animal logic animals animation animation nodes anime anisculpt Anja Kroencke Anna Higgie Anna Jensen Anna McKay Annabel Briens AnneBerry Anneke Krull Annu Kilpeläinen anstudy anthology António Soares ar arduino area armature arrange array array modifier arrow art art director art directors Art is fun! art reps art tools Artaksiniya arthictecture arthur rackham artists artwork ase Ashlyn Anstee Asian aspiring asset atom attribute attribute transfer audio Audrey Kawasaki augmented reality aurasma Aurelius Battaglia author illustrator automatic automation Autumn Whitehurst avatar Avrom Yanovsky AW14/15 award awards Babeth Lafon Babies baboon Baby Love Background background color bacteria bake baking ball Bamboo banner Banner images banner making Barbara Dziadosz barcode basic bbox beads beats Bec Winnel beginner Bel Johnstone Ben Denison Bernie Fuchs Berto Martinez Beth Krush better photos bge Bijou Karman Bike biscuit bishop black and white black and white art Blair Breitenstein blam blender blender game engine blender3d blending Blinkie Blinky blob blocks Blog Tips blogger Blogging Friends blogs Blonde blur effect in pixlr and photoshop blur images and pictures bmesh bmesh viewer bolognaragazziaward bombing bone bone modeling bones book book launch books boomerang bottle bounding box bowl bpy brian eno brian ormiston Brian Sanders brian won brick bridge Bridget Davies bright Brooke Boynton Hughes build modifier building burns business Buttons bvh cage Caitlin Shearer caldecott calibration camera camera settings camera tips Candle capcom card career Carole Wilmet cartoony Cassandra Rhodin cast Catherine Campbell Cecilia Carlstedt cell center pivot centipede cg cg photography chair challenge Chanel changin color in pixlr changing color chaos character Character Bible character development charcoal charles Charlie Dot Charlie Hebdo Children children's book illustration chocolate Christina Drejenstam christina forshay Christina K christinaforshay Christmas Cindy Derby circle circle dance city cityengine clock clones cloning cloth Cloud based clover CMYK Coco Chanel Cody and the Fountain of Happiness coffee collect collection Collections collision color color balance color cast color correction color mode color study colorful Commercial Use complexity component compositing composition computational thinking computer concept art Condensed Posts conference connect connect the dot connection Connie Lim Conrad Roset constrain constrast contagion content Contest contracts control converter copy copyright Corinna Luyken count Courtney Brims crack Craft craftsmanship Craig & Karl creative creativity creature cricket Cristina Garcia Martin critic criticism critique Crop Crop Tool cross section crowd csv cubism curve curve modifier custom Custom Blog Design Custom Blog Design Tutorial Custom Blog Designers Custom Illustration custom properties Custom Signature custom xml cut cutting plane cycle cycles dae Damien Florébert Cuypers Dan Hillier dance Daniel Egnéus Daniel Segrove Danny Roberts Daren Newman Dasha Tolstikova data data path David Blossom david diaz David Shrigley David Stone Martin Dean Hardscrabble Debbie debbie ohi debbieohi deform deformer degrees deleting background in pixler demo demoscene desaturation of images design design by numbers design process Design Tips dictionaries dictionary Different Text Writing in Pixlr digital digital paint Digital Scrapbook Freebies Digital Scrapbooking disk distance distractions distribute diversion DIY DIY Contest Dolf Veenvliet Doll Doll Bones dolls domino domino effect doodle Doodles door doraemon Doris Jackson Dorothia Rohner dots dpi draw drawing drill driven driver drivers dual versions dummy duplicate duplicates duplication dupliframe dvd dynamic dynamic paint dynamic text E Simms Campbell Easy easy pixlr Easy Tutorials Ed Graham Ed Vebell editing editing photos editors education effect effects ego Eleanor Dalton electric Elia Fernández eliza wheeler Elizabeth Mayville elizawheeler Emily Forgot Emma Zanelli emoticon happy-face Emotional storytelling empathetic characters empty entoforms envy epicycloid EPS Illustration Epson scanner erasers Erin Armstrong Erin Petson erinoshea ernest shepard Esra Roise euler evaluate line Eveline Tarunadjaja evenly spacing vertex event everywhere door exhibition Expandable Posts experiments explode exploded view export expression extrude eye eye color in pixlr eye trick eyeball face rig facial expressions facial setup factory Faiyaz Jafri Families fashion illustration fashion week fcurve feature Featured Fee Harding Feedback fence Fernanda Guedes fibonacci Fifi Lapin file File Types Finalists Finding Nemo fire fix photos Flash Tutorials flicker flip flip flop floor flop flow flower Flowers fnmatch focal point follow up font Fontaine Anderson Fonts food footage For Sale force form formula fractal fracture frame Frames Francois Berthoud Frank Bellamy Frank Furlong Franklin McMahon freckles Fred Steffen FrederiqueBertrand Free for Commercial Use Free for Personal Use Free Stock Photography Free transform tool Freebies Frenchillustration Fritz Siebel frosted mylar fruit ninja Fumi Mini Nakamura Fun function futurism FW2017 fx Gabriel Moreno Gabriella Ibarra game game animation gameart gamma gangnam style Garance Doré Gary Fernandéz gel medium generate generative generator geometric geometry Gerald Lazare Géraldine Georges GIF Gildo Medina Girl Giuseppe Castellano Giveaway glorar goals golden ratio google google docs Google Tools Grant Young graph graphite graphite transfer grease pencil grid group group node growth Gucci Guest Guil Godier gustave dore hair handbook Harper's Bazaar harpercollins Harvey Schmidt Haute Couture head Headers heat map Helena Hauss hexagon hexagonal grid Hiroshi Mizuno Hiroshi Tanabe Holiday Holly Black homology honeycomb hook horror houdini how to how to blur a face or an object in pixlr How to change eye color how to delete an object how to desaturate an image how to edit a image in pixlr how to erase an object how to fix red eye problem how to fix red eyes in pixlt How to fix the parts in pixlr in photoshop How to make a banner in pixlr How to overlap the nevus how to remove a object How to remove an object in pixlr how to remove red eyes How to Remove the Background of an Image in Pixlr How to remove the parts that you don't want in pixlr and photoshop how to replace color How to write a Patterned Text in Pixlr how-to Hsiao-Ron Cheng hsv hue humor Hyshil I love illustration magazine idea ideas Igor+André illusion illustrating illustration illustration board Illustration Books Illustration Intensive Illustration Now! Fashion illustration process Illustrations Illustrative Berlin illustrator Illustrator Intensive Illustrator Tutorials iloveillustration magazine image ediditing lessons Image Ready image sequences image theft imaginative import import text import vertex color improving photos inbetween index visualizer Info Ingrid Bockting ink inktober input Inspiration inspirational quotes install instance instance switching intensive interaction Intermediate Tutorials internet interoperability interpolation intersect intersect edges intersecting intersection interview introduction invoke subprogram io ipad Irana Doucer Isabella Hemmersbach islam islamic iteration Izzie Klingels Jack Hearne Jack Tremblay James Dignan James Gurney japanese Jason Brooks Jean Kim Jeanne Detallante Jen and Chris Creed Photography jen betton Jen Rofé Jenny Mörtsell Jeremy Combot Jeslyn Kate Jesse Auersalo Jessica Jessica Lanan jessicalanan jewellery jewelry jiggle Jim Schaeffing Joe Bowler Joe Cleary Joe Isom Joe Krush Johanna Goodman john maeda John Vernon Lord joint Jordan Sondler JPEG JPG jpop juana martinez-neal juanamartinezneal Judge Judit Garcia Talavera Judith van den Hoek Judy Byron Schachner Jules Julien Julian Beever Julie Verhoeven Jump Break Tool JW Anderson K-Fai Steele Kaethe Butcher Kareem Iliya karel zeman Kate van Harreveld Kathrin Kuhn Kathryn Ault Noble Kathryn Noble Katie Kath kdtree Kei Meguro Kelly Beeman Kelly Light Kelly Smith kelly sonnack Kelly Thompson keyframe keyframing kidlit kidlitartists kimberlygee Kirkus Review Kisoo Chai Kodak Konstantin Kakanias Korean illustration Kotaro Chiba Kozue Himi Kremos Ksenia Finogeeva KT Smail kuler Kustaa Saksi Lanan Laptop larry gritz lasso tool latte lattice Laura Callaghan Laura Laine Lauren Rille layer layering Layla Holzer layout leaf learning learning blender LED Leendert meets Ingrid lego length Leonard Starr lessons levels LFW A/W 14 liangzhu liero lightbox lighting lightning Lina Bodén Lina Ekstrand Linda Dorn line line connect line drawing lines Links Linky Love Linn Olofsdotter Lionel Gilbert Lisa Anchin Lisa Billvik Lisa Krannichfeld lisaanchin lisbeth zwerger Liselotte Watkins list list comprehension List First Last listing locator lofting logo Logo Design Lola Dupré London Fashion Week loop looping loops looptools Lorraine Fox lossless lossy lost weekend lostweekend lotte reininger Louis Glanzman louis vuitton Luciana Rondolini luciograph LULU* lv Lynnie Zulu Mac macgyver macouno maeda Magda Antoniuk magic Magnus Voll Mathiassen mailing mailings maker Makiko Sugawa making banners Malika Favre MAMP mandala manga map map range maplelam mapping Marcel George Maren Esdar Margot Macé Margot van Huijkelom Maribeth Olson Marie El-Ahmar Marilyn Conover Marina Esmeraldo Marine Marbleindex mario Marlies Niemeijer Marsha Riti Martha Rago Martin Krusche Martine Johanna mask masking material materials math matrix matrix apply matryoshka Matt Baker matte medium Matthew Woodson maya maze mdd Meagan Morrison measure megaman Megan Hess Meizhen Xu Mel Crawford memory mentee mentees mentors mentorship program Mercer Mayer Meridth McKean Gimbel mesh mesh cutter meshlab Meta Tags metal gear rising Meyoko Mia Overgaard Micca mice Michael Sanderson Michela Picchi middle grade midi miku Milan milipede minidom Minima Mio Matsumoto mirror cut Misc Miss Blackbirdy miss maple's seeds Miss Take Mitchell Hooks mixamo mixing Mobile Apps mocap mod model modeling modifier modular modulation modulus mold molecule molly idle Molly Ruttan Molly Ruttan Illustration money monitors monkey mono-zero monster monster university morph morpher mosaic mosquito motion motion capture motion capture mouse motion trail moto360 mountain muji Muriel Wood Murray Tinkelman mushroom Music and Podcasts My dead pony Nadia Flower Naiad Einsel Naja Conrad-Hansen Natalie Brockett Natalie Foss nathan vegdahl nautilus Nav Bar navigation needle-felting negotiating Neil Boyle neon nescbwi14 nested New Blogger Questions New Blogger Template Tutorials new user pixlr new year new york New York Fashion week Newbery nicholas nicholas bishop Nicholas Hong Niki Pilkington Niso Ramponi nla No Software node node-based nodebox noise non linear animation Non-Web Font normal Noumeda Carbone npr number NURBS NYFW object object color change object info octopus offset Ola Volo Olaf Hayek old formats opaque projector open movie open shading language open source openshadinglanguage opensoundcontrol optical organization origami original art show Ornaments osc Oscar Schlienger osipa osl outline outliner output Pages paint paint weight painting painting on illustration board painting on wood painting with movie painting with numbers Pair pandas panorama Paper paper lantern parabola parametric parent parenting particle particle info node particles pat david Pat Zietlow Miller pattern Patterned Text Paul Faassen Paul X. Johnson Paula Sanz Caballero PC pdb pebbles pencil Pencil Sketch pencils Penguin perfume perlin Peter Helck Photo CD.8B photo editing software Photo Reference Photobucket photographing art Photographs photography photomerge photoshop Photoshop Brushes Photoshop CS3 Photoshop elements photoshop pixlr desaturaion Photoshop tips Photoshop Tutorials Picture Book Builders picture books Pierre Louis Mascia Piet Paris Pietari Posti pingpong pinnochio pipes pixar pixel pixel art pixel generator pixlr Pixlr advanced Pixlr blog pixlr desaturate keep a colorful part pixlr editting pixlr express Pixlr forum Pixlr free transform Pixlr Lesson Pixlr lessons Pixlr mobile Pixlr resizing images pixlr shortcuts Pixlr tools pixlr tutorial pixlr tutorial with pictures Pixlr Tutorials pixlr white black pixlr.com plant plot plotting ply PNG PNG Illustration podcast point point color pointilism polka dots polyCut polygon Pomme Chan pop-overs portfolio Portfolio award portfolio showcase portfolio-advice portrait position Post Dividers postcard poster Posting pot powdered graphite powerhousemuseum Prada presentation print printmaking Prize procedular procedural process processing programming projection Promotion property prototype PSD psy publishing pulse puppet puppetry pydriver pydrivers pyhandler pyhandlers pyramide python quad quick select set quick tips qumarion Rabbit Moon Rachel Ryle radians radius ramp random random motion randomization randomize range float raspi Ray Houlihan reading reading XML READY-TO-WEAR realflow Rebecca Clarke rebecca dautremer Rebecka Skog rebuild recursive recursivedrawing red eye remove reducing glare reference referencing release remesh modifier remix removal remove remove red eyes remove unwanted objects Removing backgroung render rendering renderman repeat repeater repeating replace replacement replacing color representation rerouter resample resampling research Resizing image resolutions retopology retro review revolve rgb rib Ricardo Fumanal Richard Scarry rig rigging rigify Rikke Jorgensen ring ripple roadkill Robert Heindel Robert J. Lee Robert McCloskey Robert Shore Roberta Zeta Robin Rosenthal robot robotic rocks Rodolfo Montalvo Roller Coaster rotation Rousseau rsl Rubin Pfeffer ruler tool Russ Mills russian rut S/S14 S/S15 S/S16 Sabine Pieper sadako Saftey Pins Sainte Maria Sale Sam Weber Sanda Suy Sandy Kossin santoso Sara Andreasson Sara Singh Sarah Jacoby saturation artist tools scan scanners scanning scatter scbwi SCBWI 2015 mentee SCBWI conference scbwi germany SCBWI mentorship scbwi-la scratch scratchboards screensaver screw screw modifier script scrub sculpting seamless Seamless Patterns Search Engines select by material select by name select by type SEO sequence series set keyframe set keyframes shader shading shadow Shannon Stirnweis shape grammars shape key shapekeys shapes shards shatter Sheilah Beckett shell ship shipping shipwright Shoes SHOWstudio shuffle Sid Barron Sidebar Titles Signature Silja Goetz silkworm Simon and Schuster Simon Varela simple simplicity simulation sine Site Engine Optimization Sjoukje Bierma sketch Sketches sketching skin skin modifier skinning slice slicing slides sloth slow parent smoke smoothstep SN snake Sneek Peek snippet Snow Snow White Snowflakes soccerball social media Social Media Buttons Social Networking society of illustrators Society6 soft body softbody Sonia Menti sound sound wave space spaceship sparta special spider spiderman spiderweb spin spiral Spiros Halaris Spiros Halaris x Urban Decay spline Spot Healing Tool spreadsheet SS16 stack stacking stair stamp Stan Galli star starfish stencyl step Steven G. Dobson still Stina Persson stone stones storytelling strand strand info strands street art string stripes structure studies studio style stylistic summary Summary Posts Summer sun supplies surface Susan Farrington suzanne Suzanne Kaufman sverchok swatch switch sydney system table table of contents take out background Tal Drori tangent tangled Taschen teaching teapot Template Templates tentacle Tess Jacobson Tex Avery text text editor Text Formats Text Styles in Pixlr texture texturing The Cartorialist The Grudge Keeper The Purple Book thinker1 Thomas B. Sawyer thread TIFF tile tilecam tiling time time code Tina Berning Tina Kugler tips tips for artists Toby Neilan Tom Baxter Tom Bjarnason tombow tomie depaola tool tools topology tower Tracy Turnbull Train transfer drawing transferring sketch transform transformation transit travel triangle wave Tricia Springstubb trigger tris tristan lock tube tubes Tutorials twitter type tool typeface typography unbake unity3d universal unquad utah uv valentine Valentino Valerie Servais vanilla variable variation variety vase vector vectorized Velwyn Yossy venus Veronica Ballart Lilja vertex vertex color vertex group vertex paint vertex weight VFX Victoria Boysen video Videos viewer Vintage virtual virtual studio visualization vivid vividfestival VOGUE volumetric voronoi Vote voxel voxelated voxelation walking teapot Walter Einsel wand tool water soluble graphite watercolor wav wave we need diverse books web webbing Week Themes weight welcome Wendy magazine Wendy Plovmand what casues red eyes What is Pixlr Wherever You Go Wide Awake Bear wiggle Will Davies Winner Winnie Fitch Winnie Truong Winter wire wired wireframe wolfram Woman wood woodwork wool wooly wordpress work workflow World writing writing XML www.pixlr.com XML YA yayoi kusama Yelena Bryksenkova yoda Yoko Furusho Yuliya zaha hadid zen zsphere

Simple Blend Dissolve using OSL


It has been a while since last post. I have a lot to think in my mind. Basically, on one side I like to start making a more finished/polished artworks, while on the other side, I always love the idea of exploring and experimenting with creative ideas in Computer Graphics in general and especially in Blender.

I think I can do both (Quality vs Creative Quantity). Just takes a bit more time in refining.

I also want to go back to doing Animation, although at the same time, I love doing technical works: Rigging, VFX, Particles, etc.

The thing I found with Shader Writing is that this is a never-ending study and exploration. Well almost like everything in CG is like that. The more we dig, the more we found a new complexity. I like the idea of understanding the simplicity of things. Complexity is not always needed.

Anyway, for this post on OSL, I think I will just dump one big large code that is basically containing some useful functions in relation to BLENDING MODE. We probably learn about Layer Blending from Photoshop, as we know we have few Blending Modes to mix 2 layers of pixels together:
  • Multiply
  • Darken
  • Lighten
  • Dodge
  • Burn
  • etc
Most of information and code about Blending is pretty much translated from book "The Renderman Shading Language Guide" by Rudy Cortes and Saty Raghavachary.
http://www.amazon.com/The-RenderMan-Shading-Language-Guide/dp/1598632868

DESIGN PHILOSOPHY OF SHADER WRITING
I like to quote a paragraph from the book above from page 362-363 in regards to Procedural Pattern Creation and Design:
"The most effective strategy to employ toward procedural pattern generation is to divide and conquer. When presented with a pattern to synthesize, the idea is to break the pattern into distinct layers, create each layer using an independent block of code, and then combine the layers to obtain the pattern sought."

I have my own frustration when learning this Shader Writing. Sometimes it feels like re-inventing the wheels. Also, there are not many experts out there care to share their knowledge to help newbies. Lots of important documents are old and starting to break as we are moving to a more modern way. There is as if a huge gaps that artists to leap ahead in order for them to be able to take advantage of the tools.

I think we can take the analogy of Instant Ramen and real Ramen/Noodles made by hand. Or any kind of instant food (pizza, pasta, fried rice etc). Handmade takes longer but may taste a lot better and fresh and healthier too. Understanding of ingredients will make you a better chef. These days, people living in modern city got their fruits, vegetables and meats already pre-made and so easy to cook. Of course it is not always necessary to be able to cut the meat or to plant vegetables and wait for fruits, because that will not be efficient, however, a certain kind of understanding of the component will help us a lot when we are using "all purpose nodes" to create custom original texture that we needs.

More reading as recommendation:
http://www.renderman.org/RMR/Publications/

I really do learn a lot about Shader Writing from RSL (Renderman Shading Language). Slowly, hopefully, we all can gain enough knowledge to translate RSL knowledge to OSL. Somebody with good Shader Writing and OSL knowledge and experience ought to write a NEW book to help future shader writers in near future!

Now, that book above also mentioned a few times that the origin of the blending mode functions were taken from: http://www.pegtop.net/delphi/articles/blendmodes/

The "pegtop" website is the work of Jens Gruschel. So I have to thank him also for the knowledge. These are priceless bits of knowledge of the legacy of shader writing.

NOTE: In this code example, I am also using OSL syntax that load Image File from directory.

I am using these 2 images as Texture to use inside OSL:
TEAPOT A: This is a generic Blender Cycles Render of a basic teapot I modeled in Blender a while ago.
TEAPOT B: This is a photograph of this awesome limited edition Renderman walking teapot (thanks Moxy!), 
Using the code below, we are loading the 2 image textures above and blend the two together.

It is very simple thing that we can easily do using Blender Mix Node, but with the idea of learning OSL Shader Writing, we are trying to recreate it with code.

The always handy MIX node.

THE "BLEND MODE" CODE

// HELPER FUNCTIONS THAT CHANGES THE BLENDING
// SOURCE:
//    The RenderMan Shading Language Guide Book
//    By Rudy Cortes and Saty Raghavachary
//    Also: Works of Jens Gruschel (http://pegtop.net)

// OVER MODE
color colorOver(color BaseMap, color Layer, float LayerOpac){
    return mix(BaseMap, Layer, LayerOpac);
}

// ADD MODE
color colorAdd(color BaseMap, color Layer, float LayerOpac){
    return BaseMap + (Layer * LayerOpac);
}

// SUBSTRACT MODE
color colorSubstract(color BaseMap, color Layer, float LayerOpac){
    return BaseMap + ((Layer-1) * LayerOpac);
}


// MULTIPLY MODE
color colorMultiply(color BaseMap, color Layer, float LayerOpac){
    return BaseMap * ((Layer * LayerOpac) + (1-LayerOpac));
}

// COLOR DISSOLVE
color colorDissolve(color BaseMap, color Layer, float LayerOpac){
    //float Random = 5.0;
    //getattribute("object:random", Random);
    float myRandom = noise("snoise", P * 7);
    color out;
    if(myRandom < (LayerOpac))
        out = Layer;
    else
        out = BaseMap;
        
    return out;
}

// SCREEN MODE
color colorScreen(color BaseMap, color Layer, float LayerOpac){
    return 1 - ((1-BaseMap) * (1-Layer * LayerOpac));
}

// COLOR OVERLAY
color colorOverlay(color BaseMap, color Layer, float LayerOpac){
    //float layerval = colorToFloat(Layer);
    //float layerval = Layer[1];
    
    // color to grayscale (luminocity method)
    // READ: http://www.johndcook.com/blog/2009/08/24/algorithms-convert-color-grayscale/
    float layerval = 0.21 * Layer[0] + 0.71 * Layer[1] + 0.07 * Layer[2];

    return (layerval>0.5) ? (2*BaseMap*Layer*LayerOpac)+BaseMap*(1-LayerOpac):
    1 - ((1-BaseMap) * (1-Layer*LayerOpac))*(2-(1-LayerOpac));
}

// COLOR DARKEN
color colorDarken(color BaseMap, color Layer, float LayerOpac){
    float baseval = 0.21 * BaseMap[0] + 0.71 * BaseMap[1] + 0.07 * BaseMap[2];
    float layerval = 0.21 * Layer[0] + 0.71 * Layer[1] + 0.07 * Layer[2];
    return (baseval<layerval) ? BaseMap: Layer * LayerOpac + (BaseMap*(1-LayerOpac));
    
}

// COLOR LIGHTEN
color colorLighten(color BaseMap, color Layer, float LayerOpac){
    float baseval = 0.21 * BaseMap[0] + 0.71 * BaseMap[1] + 0.07 * BaseMap[2];
    float layerval = 0.21 * Layer[0] + 0.71 * Layer[1] + 0.07 * Layer[2];
    return (baseval>layerval) ? BaseMap: Layer * LayerOpac + (BaseMap*(1-LayerOpac));
    
}

// COLOR DIFFERENCE
color colorAbs(color col){
    return color(abs(col[0]), abs(col[1]), abs(col[2]));
}

color colorDifference(color BaseMap, color Layer, float LayerOpac){
    return colorAbs(BaseMap - (Layer * LayerOpac));
}

// COLOR HARDLIGHT
color colorHardlight(color BaseMap, color Layer, float LayerOpac){
    float layerval = 0.21 * Layer[0] + 0.71 * Layer[1] + 0.07 * Layer[2];
    return (layerval<0.5) ? (2*BaseMap*Layer*LayerOpac)+BaseMap*(1-LayerOpac):1-((1-BaseMap)*(1-Layer*LayerOpac))*(2-(1-LayerOpac));
    
}


// COLOR SOFTLIGHT
color colorSoftlight(color BaseMap, color Layer, float LayerOpac){
    color ctemp = BaseMap * Layer;
    return mix(BaseMap, ctemp+(BaseMap*(1-((1-BaseMap)*(1-Layer))-ctemp)), LayerOpac);
}

// COLOR DODGE
color colorDodge(color BaseMap, color Layer, float LayerOpac){
    color ctemp = mix(BaseMap, BaseMap/max(1-Layer, color(0.00001)), LayerOpac);
    return clamp(ctemp, color(0), color(1));
}

// COLOR BURN
color colorBurn(color BaseMap, color Layer, float LayerOpac){
    color ctemp = mix(BaseMap, 1-((1-BaseMap)/max(Layer, color(0.00001))), LayerOpac);
    return clamp(ctemp, color(0), color(1));
}



shader blending (
    color BaseMap = color(1,0,0),
    color Layer = color (0,1,0),
    float LayerOpac = 0.5,
    string filenameA = "/Users/jimmygunawan/Desktop/teapotA.png" ,
    string filenameB = "/Users/jimmygunawan/Desktop/teapotB.png" ,
    vector Pos = P,
    output color ColOut = color(0.2)
)
{

    color TextureA = texture(filenameA, Pos[0], 1.0 - Pos[1]);
    color TextureB = texture(filenameB, Pos[0], 1.0 - Pos[1]);
    
    // change the BLENDING MODE using the helper function of your choice above
    //ColOut = colorOver(TextureA, TextureB, LayerOpac);
    //ColOut = colorBurn(TextureA, TextureB, LayerOpac);
    //ColOut = colorHardlight(TextureA, TextureB, LayerOpac);
    ColOut = colorDissolve(TextureA, TextureB, LayerOpac);
}


Feel free to modify and mix the code above.



QUESTION ARISE...

If we compare the built-in Blender MIX Node that does blending with the function above, we can see that the result is a bit different sometimes. I am wondering why is that happening? Is it because things got "normalized" with the premade node and more correct?

I guess I need to compare the code from the book with what comes with Blender. Further investigation needed.

However, with the above code example, we start to think about LAYERING in OSL. OSL is certainly handy for:
- Procedural Pattern and Texture creation
- Texture Mapping
- Complex Blending
- Utility

I guess, the "best" of OSL is when shader writing is used together with the node network, so this is something we (more artists than coders) can always kept in mind.


REWRITING OSL CODE FOR LAYERING

Still reading this book, but I am most interested with Chapter 12 "Procedural Patterns".

Although some part is still quite complicated to understand, the book is quite consistent in term of explaining the concept of "LAYERING" and "PROCEDURAL PATTERN".

This one example is also translated from the book to OSL. It seems complex at a glance, but this is actually simple and it explains a lot of things. I like how the code is nicely organized and every functions are separated from the main Shader code:

  • Helper Function to Rotate Texture in 2D: rotate2d() 
  • Few other helper functions: pulse(), repeat(), blend()
  • Concept of Layering and Opacity (Masking) using code.

CODE:

// converted from book Renderman Shading Language Guide
// page 370, for shader called "Optical Illussion"
// OSL code translation by Jimmy Gunawan

// the following HELPER FUNCTIONS was translated from 'rmannotes.sl'

float pulse (
    float a, 
    float b, 
    float fuzz, 
    float x
)
{
    return (smoothstep((a)-(fuzz), (a), (x)) - smoothstep((b)-(fuzz), (b), (x)));
}

float repeat(
    float x,
    float freq
)
{
    return (mod((x) * (freq), 1.0));
}

/*
rotate2d is taken from rmannotes.sl
2D rotation of point(x,y) about origin(ox,oy) by and angle rad.
the resulting point is (rx, ry).

*/

void rotate2d (
    float x,
    float y,
    float rad,
    float ox,
    float oy,
    float rx,
    float ry
)
{
    rx = ((x) - (ox)) * cos(rad) - ((y) - (oy)) * sin(rad) + (ox);
    ry = ((x) - (ox)) * sin(rad) + ((y) - (oy)) * cos(rad) + (oy);
}


color blend(
    color a,
    color b,
    color x
)

{
    return ((a) * (1-(x)) + (b) * (x));
}

    
shader optill(
    float fuzziness = 0.025,
    float freq = 10,
    float thickness1 = 0.75,
    float thickness2 = 0.75,
    float rot = 45,
    color baseColor = color(0,0,0),
    color c1 = color(1,0,0),
    color c2 = color(0,1,0),
    vector Pos = P,
    output color ColOut = color(1)
)
{
    color surface_color;
    color layer_color;
    
    color surface_opac;
    color layer_opac;

    float fuzz = fuzziness;
    float ss;
    float tt;
    
    surface_color = baseColor;
    surface_opac = color(0);
    
    // assign pixel position as s and t
    float s = Pos[0];
    float t = Pos[1];
    
    // rotate stuff in 2D
    rotate2d(s,t,radians(rot), 0.5, 0.5, ss, tt);    
    
    // repeat pattern
    ss = repeat(ss, freq);
    tt = repeat(tt, freq);
    
    float pwh = thickness1 * 1.0/freq;
    float pwv = thickness2 * 1.0/freq;
    
    // This is Layer 1 covering Layer 0 (Base Layer)
    layer_opac = pulse(0.5-pwh, 0.5+pwh, fuzz, ss);
    surface_color = blend(surface_color, c1, layer_opac);

    // This is Layer 2 covering Layer 1
    layer_opac = pulse(0.5-pwv, 0.5+pwv, fuzz, tt);
    surface_color = blend(surface_color, c2, layer_opac);

    ColOut = surface_color;
    
    // I omited some code in relation to "Opacity"
    // because I am not quite sure how it works.
    // However I will revise it in the future, hopefully!
    
}

The result of the above code can be seen as below.

We have 3 Layers (Color):
- Base
- c1
- c2




We can then try something like below:



We are using Image Textures and using the code above to layer them together:





Thing started to get more interesting, right? I thought so too.

Some parts may still be abstract, but when the code is arranged this way, we started to see something that looks like typical 2D Layerings in 2D image editing packages.

All contained within a single node, instead of complex noodles of node network.

The book is really teaching concept of:
- MULTI LAYER
- OPACITY or MASK
- BLEND as CODE

When thinking of Shader this way, whether we are using pre-made nodes, custom procedural textures, or image textures, or combinations of everything, thing is a lot more simple. We separate the problem in layers and then we will start LAYERING the COMPLEXITY, while still having enough CONTROL to achieve the look we like.

EXPLICIT vs IMPLICIT FUNCTIONS

At this moment, perhaps for me, the hardest part of the code is to think of Pattern Creation "IMPLICITELY", instead of "EXPLICITELY".

When doing coding to draw a shape in program like Processing, we can simply say things like:
ellipse(5,5,0,0); 
// draw an ellipse shape of size of 5x5 pixel at position (0,0).
// http://processing.org/reference/ellipse_.html

That's above is actually a simple function that is using EXPLICIT FUNCTIONS.

However, when doing SHADER WRITING (like OSL, OpenGL, RSL), even to create a simple shape of ellipse, we need to think kind of inside out. We are using IMPLICIT FUNCTIONS.
http://www.sciencehq.com/mathematics/implicit-and-explicit-functions.html


MORE OSL RELATED LINKS

http://spectralbattle.wordpress.com/2011/04/12/added-new-osl-function-texture/
http://blenderthings.blogspot.com.au/2013/01/gabor-noise-for-cycles-osl.html
http://blendbits.blogspot.com.au/2013/05/lens-flare-shader-for-blender-cycles.html
http://blenderartist.org/forum/showthread.php?293132-PYLA-PhYsically-correct-LAyers-with-OSL
http://peter.cassetta.info/material-library/submitting-help/
http://www.elysiun.com/forum/showthread.php?306353-Starscape-Texture-OSL
http://www.blenderartists.org/forum/showthread.php?277986-Random-Color-OSL
http://www.sfdm.scad.edu/faculty/mkesson/vsfx419/wip/spring11/eric_kurzmack/toon.html
http://blenderthings.blogspot.com.au/2013/02/simplex-noise-for-open-shading-language.html



In this article, I am sharing my research and notes on Blender NLA (Non Linear Animation) and write on how we could also use Python to orchestrate the animation of MANY objects in context of NLA.

NOTE: It comes to my own surprise that I only found out about the POWER of Blender NLA just recently.

NLA INTRO

I would start by reading these:
http://wiki.blender.org/index.php/Doc:2.6/Manual/Animation/Editors/NLA
http://aligorith.blogspot.com.au/2010/10/clarifying-animation-workflow-in.html

In short, I am seeing NLA as a way to non-linearly edit normal Animation(s) keyframes into a Strip of Action(s) just like any non-linear editor. A single Action animation can be offset, sliced, blended in time.

NLA workflow is great for Game Animation where one may reuse animations (Idle, Walk, Run) or to specifically trigger an Action Animation based on Event.

On top of that, I believe NLA is also useful for LOOPING kind of animation, usually for musical score that has beats and loops. Not only that, NLA has tremendous potential to create a lot of interesting "wave motion" animation effects.

Keep in mind that NLA is NOT complex NOR super technical, in fact I think Blender NLA is pretty intuitive and very simple to use.

I have not looked at NLA thoroughly, but I believe there are few different NLA types:
  • NLA for normal object transformation
  • NLA for Armature
  • NLA for Materials
  • etc
I am not yet 100% understand how NLA data block works in relation to each other, but I will touch on the basic first. For example, I am wondering whether it is possible to "drive" Material animation using Actions of Transform, apparently cannot. I am guessing we need Blender Drivers for that.


NLA BASIC

Let's do a little experiment.

1. MANUAL ANIMATION
Create a simple animation of a block going from position A to position B. Maybe just an animation of a Cube going from original position and go up few units in Z axis.
  • Single keyframe Position of Cube in Z axis at frame 1.
  • Move the frame in timeline, lift up the Cube in Z axis, and keyframe at frame 20.
2. SWITCH TO NLA EDITOR
Next, we like to switch panel to NLA Editor. I usually do this inside Blender Animation layout. But feel free to modify your current layout so you can get to NLA Editor panel.


3. NLA EDITOR
Now, we are ready to turn the animation into Strip. You simple click on tiny Snowflake button to freeze the animation and work in NLA kind of way.


By doing the freeze, we now get Strip named "CubeAction". NLA Track is also automatically created.


4. EDIT THE ACTION STRIP
To Edit the action like normal, we can apparently do that quickly by hitting TAB while selecting the Action Strip:

We hit TAB again to go out from the Action Edit Mode.

5. APPLY ACTION STRIP TO OTHER OBJECT aka INCLUDE SELECTED OBJECTS
Next, let say we want to apply the same animation to other object. Firstly, I created a few other objects. 

What we need to do next is to create NLA track for the objects. But as you may notice we don't have any listing of new objects. We need to Include Selected Objects inside NLA first, before we are able to add NLA Tracks and Action Strips.


Handy Shorcuts:
  • Shift+A while hovering on the NLA left panel to add NLA Track 
  • Shift+A while hovering on the NLA right panel to add Action.
  • X to quickly delete NLA Track
  • Ctrl+LMB click on the name of object to quickly rename the object name inside NLA
5. EDITING ACTIONS STRIPS IN NLA CONTEXT
Next thing you probably want to explore yourself is how you can edit and modify the strip inside NLA Editor. There are a lot of interesting NLE features that I did not even think that they are existed before, such as: Trimming, Muting, Splitting, Holding, Retiming, Combo-ing and Layering animations. 


What I am even more interested is how we can use Python to actually do some automation inside NLE that we may want to know especially when we are doing Motion Graphics type of work.

STUDY: FLIP ANIMATION WITH NLA AND PYTHON

This found video at Eibriel blog is a good inspiration for what we are trying to do:
http://www.eibriel.com/2012/01/30/working-with-blender-python-nla/

Some times ago, I created a complex setup using Dynamic Paint to trigger flipping animation:
http://blendersushi.blogspot.com.au/2012/02/vfx-multilayers-triggering-of-effects.html

Last time on my blog post, I did the same thing using Python to set it up.

Now we are revisiting the idea once more, using NLA. Setting up repeating tasks is a breeze with Python scripting. Although it does require some hours of R&D.

Let's try to achieve the flipping animation of many objects using Python and NLA.

We basically need to "propagate" a single animation into many objects, with certain OFFSET value. Because a single repeating animation that starts and ends at the same time is kind of boring. While many same animation with offset is usually slightly more interesting.

Our animation in this case is just a flipping object, very simple. And we like to do that for many objects. The process will be like this:

1. Create a flipping animation, freeze and turn it into NLA Action Strip. This animation can be applied using any object. We just care about the Action.
2. Create some bunch objects that we like to flip.
3. Use Python to "copy" those Actions.

NOTE:
Before running the script below, you want to make sure that you have "Include Selected Objects" inside NLA Editor. Read "INCLUDE SELECTED OBJECT" topic above.

BLENDER SUSHI SCRIPT: Apply Action To Many Objects With Frame Offset


import bpy

# Initial setup
ACTION = "CubeAction" # Specify name of action to be copied here
START = 1 # Action Strip will be propagated starting with this frame number
OFFSET = 10 # How much frame offset
NEWTRACK = "MyTrack01" # Name of new NLA track for every object

# http://blenderartists.org/forum/showthread.php?233608-activate-NLA-track

sce = bpy.context.scene # get the scene
rig = bpy.context.active_object

objs = bpy.context.selected_objects

# get name to make active
names = []
for obj in objs:
names.append(obj.name)

# reverse order of selected objects
names.reverse()

# For every ACTIVE OBJECT

for i, name in enumerate(names):
bpy.context.scene.objects.active = bpy.data.objects[name]
rig = bpy.context.active_object

#get or create a new track called MyTrack

if NEWTRACK in rig.animation_data.nla_tracks:
NLATrack = rig.animation_data.nla_tracks[NEWTRACK]
else:
NLATrack= rig.animation_data.nla_tracks.new()
NLATrack.name = NEWTRACK

action = bpy.data.actions[ACTION] # your action

#sce.frame_set(frame=1)

startframe = START + OFFSET * i
actionstartframe = 1

MyNLAStrip = NLATrack.strips.new("MyStripName",start=startframe,action=action)






VIDEO DEMO

Here is an example how you can use the script above:





That simple script should show you a simple implementation of Python inside NLA. This one works only for Transform (Translate, Rotate, Scale). If you like to do the same thing on other context like Materials, Shapekeys, etc, keep reading.

NLA ACTION SCRIPT IN OTHER OBJECT TYPE CONTEXT

Further on in my curiosity toward the data flow in NLA and how we can access the data using Python, I also did a quick look and study on Shape Keys and Materials in context of NLA.

I dig and test inside Python Console and started to see some kind of interesting data pattern.

MATERIAL ---> NLA 
bpy.data.materials[MATERIALNAME].animation_data.nla_tracks.new()
bpy.data.materials['Material.001'].animation_data.nla_tracks['NlaTrack'].select = True
bpy.data.materials['Material.001'].animation_data.nla_tracks['NlaTrack'].select = False

SHAPE KEYS  ---> NLA 
# Create new NLA Track
bpy.data.shape_keys[KEY].animation_data.nla_tracks.new()

# Change the Frame Start and End Example
bpy.data.shape_keys[KEY].animation_data.nla_tracks[NLATRACK].strips[KEYACTION].frame_start = 1
bpy.data.shape_keys[KEY].animation_data.nla_tracks[NLATRACK].strips[KEYACTION].frame_end = 40

So if it is for Armature or for other Object Type, we can access and modify the Action Data just like above.

This is actually a new revelation for me in term of my understanding of Python Object Oriented Programming (OOP) in Blender and how the data is really stored inside Blender.

With this knowledge, we could actually further improve the script above to work on existing Strip Animation Data. So, instead of just assigning Strip, we can simply Query the current Script and maybe:

  • Randomize
  • Offset
  • Add, Combine, and Mix Strip with other actions.
A slight modifiaction from above script if this was for Object Material:

BLENDER SUSHI SCRIPT: Propagate Speificed Action To Selected Object Materials


import bpy

# Initial setup
ACTION = "MaterialAction" # Specify name of action to be copied here
START = 1 # Action Strip will be propagated starting with this frame number
OFFSET = 10 # How much frame offset
NEWTRACK = "MyTrack01" # Name of new NLA track for every object

# Get Active Material for every selected objects

objs = bpy.context.selected_objects

# Get Materials name, sort them in a list, and activate Animation Data for each one of them
mat = []
mat_names = []

for obj in objs:
# Query Material of every object
mat.append(obj.data.materials)
mat_names.append(obj.data.materials[0].name)

# Sort Animation Name
mat_names.sort()
mat_names.reverse()

# Create Animation Data
obj.data.materials[0].animation_data_create()

# Get Object to make active
names = []
for obj in objs:
names.append(obj.name)

# reverse order of selected objects
names.reverse()

# For every ACTIVE OBJECT

for i, name in enumerate(names):
bpy.context.scene.objects.active = bpy.data.objects[name]
rig = bpy.context.active_object.data.materials[0]

#get or create a new track called MyTrack

if NEWTRACK in rig.animation_data.nla_tracks:
NLATrack = rig.animation_data.nla_tracks[NEWTRACK]
else:
NLATrack= rig.animation_data.nla_tracks.new()
NLATrack.name = NEWTRACK

action = bpy.data.actions[ACTION] # your action

#sce.frame_set(frame=1)

startframe = START + OFFSET * i
actionstartframe = 1

MyNLAStrip = NLATrack.strips.new("MyStripName",start=startframe,action=action)







NOTE:
Notice that in this second script, we improve the code slightly so that we don't have to do "Include Selected Objects" thingy. We just simply run the script and it is accessing the Material, add Animation Action from the back door.

What you need to take care is the name of specified Material Action that you would like to propagate to every Object's Material. So you need to make sure you know the name of Action. In the script, I hardcoded "MaterialAction" as the action to be "copied" to every Material.

RENAMING ACTION EXAMPLE
bpy.data.actions['Material.004Action'].name = "MaterialAction"


MORE THAN JUST DOMINO EFFECT

At this moment, all we get with the script above is this DOMINO EFFECT where one action leads to another action and all the actions are the same. What would be nice is is we could create a condition where the action only happens when triggered by a certain condition, or another action.

I really like the idea of "triggering" of actions based on distance approximation, for example. Something that Dynamic Paint does it well for Vertex Weighting.

Maybe I can do something like this:
1. Query some kind of STATE or CONDITION that Blender can write out or save in memory.
2. Based from that query, we then apply second code that will BORN NLA animation at that certain point.

I am sure that this can be done easily in BGE (Blender Game Engine) environment. At some point, I have to find out the relations between BGE and the normal Blender animation environment and hook them together.


OTHER REFERENCES

http://blenderartists.org/forum/showthread.php?248442-NLA-Editor-Make-a-strip-active
http://blenderartists.org/forum/showthread.php?233608-activate-NLA-track
http://blenderartists.org/forum/showthread.php?225783-How-do-I-emulate-the-quot-Snowflake-button-quot-in-the-NLA-in-python-code
https://sites.google.com/site/makehumandocs/blender-export-and-mhx/mocap-tool/combining-actions-in-nla-editor

MKRdezign

Contact Form

Name

Email *

Message *

Powered by Blogger.
Javascript DisablePlease Enable Javascript To See All Widget