Halloween Costume ideas 2015
Articles by "interoperability"
@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

Bunch of Cubes from Maya, imported into Blender (Color, Position) via XML and dynamically animated using Blender Bullet and rendered out.

PREREQUISITE

  • Python basics
  • Python data type, especially Dictionary
  • cElementTree module
  • File Read and Write
We will be looking at a bit of theory of XML and its practical usage.

PROGRAMMING AND DATA

The more one learns about programming in Python (in Blender or other 3D packages), the more one can see the pattern that the whole thing is really about "data management" and "data processing" and "data visualization":
  • How to retrieve data
  • How to process data
  • How to store data
  • How to export and import data
  • How to display or present the data
As "boring" as those may sound for artists at first, data is apparently can further be processed and presented elegantly in a creative ways. Lots of raw data just means more opportunity for us (artists) to visualize it in a beautiful kind of way.

3D artists (like you and me) are lucky from the very beginning to work visually with computer data from the very beginning (at least in the last 20+ years). All we have to deal is the Interface. Still there is a sweet and sad labor of hours in doing what you are doing :)

However, if we really want to dig deeper with Computer Graphics, it is nice to be able to read raw data and process them in a magical kind of way.

In this post, I will be attempting to do an introduction to XML, XML Writing and Reading. I am not from programming background and writing this post is quite strange to myself as well. Anyhow, I feel like writing and sharing with you all.

IT WAS CSV

I have written a bit about CSV (Comma Separated Value) data and Blender export-import using CSV a while ago. At the time I was still clueless about Python and programming. I felt that CSV is really simple and easy to understand so that was my reason to use CSV.


Sooner or later we will realize that CSV is probably limited in term of what we can "store" and "parse" from it. It does not have much of STRUCTURE apart from a long list of strings and numbers and line numbers. It can represent ROWS and COLUMN type of data, but not so much of HIERARCHY data.

See how CSV is parsed inside program like NodeBox or Houdini. It's still pretty cool:
CSV -> TABLE -> VISUALIZATION
http://blendersushi.blogspot.com.au/2012/12/python-importing-and-visualizing-data.html


\BLENDER CSV F-Curve Import 
http://blenderartists.org/forum/showthread.php?209181-A-Script-to-Import-a-CSV-File-and-Create-F-Curves-(for-Blender-2-5x-or-later)

So then, what is the alternative of CSV? Just a few days ago, I learned something new (yes, new for programming newbie like me!) called XML.

I think this XML is really worth looking.

Let see what can we do with XML using Python inside Blender.

What is XML?

XML stands for eXtensible Markup Language. Apart from this long name, I think the best description and what XML really is, can be read here:
http://www.w3schools.com/xml/xml_whatis.asp
http://www.w3schools.com/xml/xml_tree.asp#gsc.tab=0

The simple way I see XML is a kind of data format with tree-like hierarchy structure. XML is human readable, just like CSV, but when we look at the XML data, it is more  like a Tree with Branches and Leaves.

<root>
    <object1 attribute1 = "value" attribute2 = "value" attribute3 = "value">
    <object2 attribute1 = "value" attribute2 = "value" attribute3 = "value">
    <object3 attribute1 = "value" attribute2 = "value" attribute3 = "value">
</root>

WHAT XML CONSIST OF?
  • root node, child node, grand child node, and so on. it always has root.
  • tag
  • element(s)
  • attribute(s)
  • attribute value(s)
  • text
If I continue on digging on XML data structure without some examples probably we all can go to sleep. But I will try show you some interesting things soon.

Since XML itself is a little boring to look at and actually does nothing, why do we even need to look at this? One would rather spend time doodling inside Blender already!

Be patient, my friend.

Apparently the data stored in XML structure is easily accessible via Python, just like collection of Dictionary and List. It is a lot like Library actually.

This means with XML, we can easily WRITE OUT and READ IN data. And this is a cool way we can  TRANSFER DATA between any software packages or tools that supports Python. We can make them talk to one another as we can see soon.

The data inside could be anything and we can organize the data the way we like it, because with XML we can create our own custom "tags" and store the data the way we like within the XML structure.

PYTHON AND XML

Python provides many MODULE to work efficiently with XML data.
http://docs.python.org/2/library/xml.etree.elementtree.html

We will be using cElementTree module instead of DOM module.
http://effbot.org/zone/element.htm
http://www.bigfatalien.com/?p=223
http://eli.thegreenplace.net/2012/03/15/processing-xml-in-python-with-elementtree/

SIMPLE VS COMPLEX XML STRUCTURE

There are simple and there are complex XML structure.

A simple XML structure is when we only have 1 level of child under the root/parent.


<?xml version="1.0" ?>
<character>
  <pCube1 rotateX="0.0" rotateY="0.0" rotateZ="0.0" scaleX="1.0" scaleY="1.0" scaleZ="1.0" translateX="0.0" translateY="6.36026310449" translateZ="0.0" visibility="True" />
  <pCube2 rotateX="0.0" rotateY="0.0" rotateZ="0.0" scaleX="1.0" scaleY="1.0" scaleZ="1.0" translateX="0.0" translateY="12.8163721197" translateZ="0.0" visibility="True" />
  <pCube3 rotateX="0.0" rotateY="0.0" rotateZ="0.0" scaleX="1.0" scaleY="1.0" scaleZ="1.0" translateX="0.0" translateY="12.8163721197" translateZ="0.0" visibility="True" />
</character>


OR



<?xml version="1.0" ?>
<character>
  <MASTER rotateX="0.0" rotateY="0.0" rotateZ="0.0" scaleX="1.0" scaleY="1.0" scaleZ="1.0" translateX="0.0" translateY="0.0" translateZ="0.0" />
  <simplebot_lf_knee_pv_ctrl lfLegIkCtrl="0.0" snapKnee="0.0" translateX="0.0" translateY="0.0" translateZ="0.0" />
  <simplebot_rt_knee_pv_ctrl rtLegIkCtrl="0.0" snapKnee="0.0" translateX="0.0" translateY="0.0" translateZ="0.0" />
  <simplebot_rt_foot_ctrl ankleStretch="0.0" fkVis="False" ikFkBlend="1.0" ikVis="False" kneeStretch="0.0" legStretch="0.0" />
  <simplebot_lf_foot_ctrl ankleStretch="0.0" fkVis="False" ikFkBlend="1.0" ikVis="False" kneeStretch="0.0" legStretch="0.0" />
  <COG rotateX="0.0" rotateY="0.0" rotateZ="0.0" translateX="0.0" translateY="0.0" translateZ="0.0" />
  <L_FOOT rotateX="0.0" rotateY="0.0" rotateZ="0.0" translateX="0.0" translateY="0.0" translateZ="0.0" />
  <simplebot_lf_heel_ik_ctrl ballTwist="0.0" footBreak="40.0" footRoll="0.0" legTwist="0.0" maxStretch="3.0" pvControl="True" stretchyLeg="0.0" toeRoll="0.0" toeTwist="0.0" />
  <R_FOOT rotateX="0.0" rotateY="0.0" rotateZ="0.0" translateX="0.0" translateY="0.0" translateZ="0.0" />
  <simplebot_rt_heel_ik_ctrl ballTwist="0.0" footBreak="40.0" footRoll="0.0" legTwist="0.0" maxStretch="3.0" pvControl="True" stretchyLeg="0.0" toeRoll="0.0" toeTwist="0.0" />
  <REye_ctrl translateX="0.0" translateY="0.0" translateZ="0.0" />
  <LEye_ctrl translateX="0.0" translateY="0.0" translateZ="0.0" />
  <JG_Eye_GP eyeZ="0.0" translateX="0.0" translateY="0.0" translateZ="0.0" twist="0.0" />
</character>



They may be slightly hard to read, but still human readable and our brain can see the pattern of what it is trying to do.

A complex XML structure is when we store every values inside child of child. Here is example I took from:
http://www.w3schools.com/dom/dom_nodes.asp

<bookstore>
  <book category="COOKING">
    <title lang="en">Everyday Italian</title>
    <author>Giada De Laurentiis</author>
    <year>2005</year>
    <price>30.00</price>
  </book>
  <book category="CHILDREN">
    <title lang="en">Harry Potter</title>
    <author>J K. Rowling</author>
    <year>2005</year>
    <price>29.99</price>
  </book>
  <book category="WEB">
    <title lang="en">Learning XML</title>
    <author>Erik T. Ray</author>
    <year>2003</year>
    <price>39.95</price>
  </book>
</bookstore>


I reckon that the complex XML is more "correct", but then the simple XML, the single liner that can be accessed as Dictionary is sufficient for us most of the time. It is really up to us how we like to store and organize the XML.

PS: Shaun Friedberg suggested the simple XML structure. Shaun is actually the one introducing me to this XML stuff (in Maya).

CREDIT NOTE:
Originally some of the contents I talked about in here is from the Python course taught by Shaun Friedberg
http://www.linkedin.com/in/pyrokinesis

WRITING XML (EXPORT XML DATA)

Whatever value we can print() in Python, we can easily pass that as XML lines.

We could type the XML lines by hand manually, but that is silly and we definitely will not do that unless we are a robot. We could of course edit the XML by hand too if we like, but that is also something we don't usually do.

We certainly use Python and LOOP to write XML.

Some module to help writing and parsing XML:

  • ElementTree
  • cElementTree
  • dom
It will be beneficial if you search and study some Python example to write and read XML using the above modules. In our case, we will be using cElementTree, because it seems to be the fastest.


BLENDER SUSHI SCRIPT: Writing Out XML Doodle Script


'''


Preparing XML construct and Writing out XML


Based on teaching by Shaun Friedberg


Edited by Jimmy Gunawan (Blender Sushi)


'''





from xml.etree import cElementTree as ElementTree

# PRETTY PRINT
# function to pretty print the XML code
def prettyPrint(element, level=0):
'''
Printing in elementTree requires a little massaging
Function taken from elementTree site:
http://effbot.org/zone/element-lib.htm#prettyprint

'''
indent = '\n' + level * ' '
if len(element):
if not element.text or not element.text.strip():
element.text = indent + ' '

if not element.tail or not element.tail.strip():
element.tail = indent

for element in element:
prettyPrint(element, level + 1)

if not element.tail or not element.tail.strip():
element.tail = indent

else:
if level and (not element.tail or not element.tail.strip()):
element.tail = indent

return element



# Create ROOT node
rootNode = ElementTree.Element('root')

### CREATE FIRST LINE OF ELEMENT

# Create node = CHILD element
elementNode = ElementTree.Element('node')

# Parent CHILD node to ROOT
rootNode.append(elementNode)

# Adding attribute
elementNode.attrib['exampleAttribute'] = 'example value'

# Adding more attributes
elementNode.attrib['color'] = 'Blue'
elementNode.attrib['smell'] = 'Ocean'
elementNode.attrib['eat'] = 'Sushi'

# Adding text
elementNode.text = 'this is an example text'

### CREATE SECOND LINE OF ELEMENT

# Create node = CHILD element
elementNode = ElementTree.Element('node2')

# Parent CHILD node to ROOT
rootNode.append(elementNode)

# Adding attribute
elementNode.attrib['exampleAttribute'] = 'example value'

# Adding more attributes
elementNode.attrib['color'] = 'Red'
elementNode.attrib['smell'] = 'Fire'
elementNode.attrib['eat'] = 'Spice'

# Adding text
elementNode.text = 'this is second example text'



### WRITING OUT IN A CLEAN WAY IS A BIT COMPLEX... WE USE THE PRETTY PRINT

# Pretty print the rootNode
prettyPrint(element=rootNode)

# We need to convert to STRING before we can see the whole thing
xmlText = ElementTree.tostring(rootNode)

# FINAL RESULT, we need to append the HEADER
print ( '<?xml version="1.0" ?>\n{xmlText}'.format(xmlText=xmlText) )

### NOW WE LIKE TO WRITE OUT THE XML TO FILE
outputPath = r'C:\pythonInBlender\test.xml'

fileObject = open(outputPath, 'w')
fileObject.write('<?xml version="1.0" ?>\n' + xmlText.decode('utf8'))
fileObject.close()

print('XML file has been written in here: {outputPath}'.format(outputPath=outputPath))







RESULT:



Additional Reference:

READING XML (IMPORT XML DATA)

Reading data is much simpler than writing. Well, at least it seems so. Writing data seems to be more complicated at first glance.

What we need to care is what we are going to do with the data after being exported. We also need to do some Data Conversion sometimes because all the data seems to come in as String, where sometimes we need data as Integer or Float for further processing.

The data comes in as Dictionary type of data. Hopefully you have some understanding of Dictionary in Python. I am also still new to all this and it is a matter of getting the KEY and VALUE from each ITEM per ELEMENT.


BLENDER SUSHI SCRIPT: Reading In XML Doodle Script



import bpy


from xml.etree import cElementTree as ElementTree





xmlPath = 'C:/pythonInBlender/mayaOut.xml'


xmlRoot = ElementTree.parse(xmlPath).getroot()





def createMonkeyFromData():


    for element in xmlRoot:





        objectName = element.tag


        if 'translateX' in element.keys():


            #print( 'Attribute called TranslateX: {name}'.format(name=element.get('translateX')) )


            locX = float(element.get('translateX'))


            locY = float(element.get('translateY'))


            locZ = float(element.get('translateZ'))


            bpy.ops.mesh.primitive_monkey_add( location=(locX, locY, locZ) )





createMonkeyFromData()








import bpy
from xml.etree import cElementTree as ElementTree

xmlPath = 'C:/pythonInBlender/mayaOut.xml'
xmlRoot = ElementTree.parse(xmlPath).getroot()

def createMonkeyFromData():
    for element in xmlRoot:

        objectName = element.tag
        if 'translateX' in element.keys():
            #print( 'Attribute called TranslateX: {name}'.format(name=element.get('translateX')) )
            locX = float(element.get('translateX'))
            locY = float(element.get('translateY'))
            locZ = float(element.get('translateZ'))
            bpy.ops.mesh.primitive_monkey_add( location=(locX, locY, locZ) )

createMonkeyFromData()



BLENDER XML BUILDER?
There is a script called xmlbuilder.py inside Blender, I am curious what this actually does. I will check this when I have time. Or you can check it. Maybe it is something to do with DAE (Collada) in Blender.

In the mean time, I will use the WRITING XML and READING XML construct like above.

CASE STUDY: Maya to Blender via XML


Comparison of Python in Maya and Blender
I have to admit that Maya provides a lot more (shortcut) commands that allow users to quickly get ATTRIBUTE or VALUE data from one object (or node in Maya).

A little bit information:
At the current state, Python in Maya is well-known as "Wrapper" of MEL (Maya Embedded Language) programming. MEL has been there in Maya for years, before later Python came in.

MEL scripts itself has hundreds of handy scripts to access all kind of data from nodes. But, even so, Python handles "Strings" and "List" like in a really awesome ways, and this makes writing script is surprisingly easy and data flow is becoming a breeze in Maya.

It will be a little weird for people learning Python in Maya because they have to always look at the MEL first. They need to kind of learn MEL too, at least to really understand the functions and reading the history.

There is PyMEL from Luma Pictures that allow for more Pythonic way to access data, kind of the more correct way Python should implemented in Maya. This is more like how Python in Blender works. It is all Object Oriented (OOP).

There are some Python API that allows to access some Maya's core that normally only accessible using C++ programming. But it is pretty complicated and low level and I am not familiar with those yet.

I am still new to Python in Blender and Blender BPY stuff and still getting familiar with the construct. I am definitely not 100% sure with a lot of things BPY. Meaning, I have a lot of questions regarding the API itself.

Like I said earlier, it seems to be much easier to access DATA inside Maya.

Examples of some handy "commands" in Maya:

  • List
  • Select
  • Get Attribute
  • Set Attribute
  • Connect Attribute
  • List Attribute
  • xform

Blender Python "does not" come with all those kind of commands. BPY feels more "raw" in my opinion.

Users may actually write their own COMMANDS that can mimic all those handy tools that are given from Maya commands.

In Blender, you are accessing the data and value more directly. In Maya, they give some commands to access the data and value in more handy kind of way.


Exporting data From Maya To Blender using XML
Let's take a look at example that I tested the other day.

I am inside Maya and I have 3000 cubes created using Python in Maya, which was based on 3000 Particle POSITION and COLOR. The Particle itself inherited its Colors from Procedural RAMP texture.



You can read a bit more at my Maya blog:

http://mayaspiral.blogspot.com.au/2013/04/python-getting-particle-rgbpp-and-apply.html


In Maya, it is super easy to query ANY Attributes and Values of Particles, including custom attributes per Particle that user created.

In Blender, we can also easily get Particle Attributes such Position, Size, etc. but still pretty limited at the current state. Blender unfortunately cannot access Particle Color by its index. Not at the moment, but I think pretty soon in the future. Fingers crossed.

EXAMPLE: Blender Particle, get position, create cube at position
For example, if I want to create some bunch of cubes at Particle Position, we could so something like this:


import bpy

obj = bpy.context.active_object
ps = obj.particle_systems.active
#ps.particles[0].location

def printPosition():

    for i in range(len(ps.particles)):
        location = ps.particles[i].location
        print(i, location)
        
        # Create Cube At Position
        bpy.ops.mesh.primitive_cube_add(location=(location[0], location[1], location[2]))
        selectedObject = bpy.context.selected_objects
        selectedObject[0].name = 'pixelcube.%s' % i
        selectedObject[0].scale = 0.45, 0.45, 0.45


Now, the reasons I am doing the XML data export from Maya to Blender are below:

  • Because I want to get more familiar with Python and XML data export import
  • Because Maya's Bullet is currently sucks. It is very limited and slow.
  • Because Blender's Bullet is awesome and fast.
  • Because I am thinking of Pipeline where Blender can be the Renderer, Compositor, etc. And I like the practical Blender Fire and Smoke and some more VFX things.


And so I wrote script that does the exporting of some specifc datas from some nodes (every objects in Maya is nodes).

Basically from the 3000 cubes, I exported the COLOR RGB information. That is what I need. I could export the POSITION data as well, but for that I actually just use DAE Collada. Same thing.

How example XML data from Maya looks like:
Simple Tree View in Chrome

The actual XML Data



Importing data Into Blender From Maya using XML
As the data is now "outside" of Maya as XML, we can do anything with it.

I bring the 3000 cubes from Maya as Collada DAE, Blender import them fine with the node names in tact and including Material that was set in Maya. Make sure the Unit Size is checked.

I wrote the script below to READ the XML data.

XML, Dictionary, Strings
XML, when imported will come as Dictionary type of data. And it is also STRING type of data. I imported the RGB like this "[0.124, 0.55, 0.123]" and they are strings. Where the data expected supposed to be 3 values of Float.

In my script below, I have noob attempt to convert 3 values string into 3 values float.



BLENDER SUSHI SCRIPT: Importing RGB via XML (but you need to setup the XML)


import bpy
# import xml.etree.ElementTree as ET
from xml.etree import cElementTree as ET

def applyColor(object='pCube999', rgb = [1.0,0.0,0.0]):
# Get specific object
object = bpy.data.objects[object]

# Create new vertex color
object.data.vertex_colors.new()

# Get Total Length of Vertex Colors for each selected meshes
totalVertCol = len(object.data.vertex_colors[0].data)

# Iterate over every mesh vertex color and give it a single colour
for i in range(totalVertCol):
object.data.vertex_colors[0].data[i].color = rgb

filepath = 'C://xml//test.xml'
tree = ET.parse(filepath)
root = tree.getroot()

print(root.tag)

# root = ET.fromstring(country_data_as_string)

for child in root:
# Get node name
nodeName = child.tag

# Get Dictionary (including key and value)
dict = child.attrib

# Extract value from Dictionary
rgb = dict.get('rgbVal')
rgbClean = rgb.strip( '[]' )
rgbList = rgbClean.split(',')
rgbColor = float(rgbList[0]), float(rgbList[1]), float(rgbList[2])
print (rgbColor)

applyColor(object='{nodeName}'.format(nodeName=nodeName), rgb = rgbColor)













Thanks again to Taisuke Tanimura and his magic of list comprehension, there is a better way of doing that 3 values String RGB into correct 3 values FLOAT:

rgbList = [float(token) for token in rgbVal[1:-1].split(',')]

Big thanks to:


 COMING SOON (HOPEFULLY)

  • XML to save poses and presets of objects
  • XML for assembly and layout between 3D packages
  • XML for saving animation and simulation data

 OTHER LINKS

It has been quite a while since I posted that old post on Blender Python Scripting topic:
http://blendersushi.blogspot.com.au/2012/03/programming-one-can-script.html

I am keeping my eyes on that post and will continue to update it overtime as I gain more understanding of concept of programming, and how one can use programming inside 3D software like Blender, and how Python is utilized. I probably will re-write some of my approach in explaining Blender Python to you. It is only recently that I actually started to understand Python and programming a little bit better (than last time).

I will babble a little bit, but if you think you are a pro and want to skip, just go to subheading "PROGRAM START HERE". Do not miss "IF BUCKY CAN, YOU CAN" though if you are beginner in Python.

##########################################################
NOTE 2012.12.07:
I am looking for simplest "Syntax Highlighter" for Code Snippet. At the moment the Python Code written here looks pretty ugly and messy because the lines and tabs are not presented nicely as it supposed to). Anyhow, if you first copy-paste the code inside the box into a good text editor (Sublime, NotePad++), it should work. In Python, space and Tab often matters when writing code.
##########################################################

FROM FIRST STEP TO NEXT STEP
Ok, so that post should be "the first step" if you also want to get into programming. This post I am writing will be still touching BASIC of Python but also jumping  into INTERMEDIATE level.

Here, I am not writing Python theory per se, but this post will be kind of like written documentation to share some notes that I collected while I am studying Python and trying to find SOLUTION for PROBLEM.

WAY OF TEACHING AND CODING
I want to emphasize something that I learned recently:
Modern education is no longer about TEACHER and STUDENT, but more likely it is a COLLABORATION between people to think CREATIVELY in finding SOLUTION for PROBLEM. This is seriously applicable when you are learning 3D using Blender on your own, with helps of Online Community.

Learn to Google for information and read and filter forum postings. Do ask forum if you are completely stuck and cannot find solution anywhere else. Even nicer is to have some kind of meetup to talk and get active about your passion (Blender in this case). You are your own teacher.

I will try to be like a MENTOR. I do not know everything, but I will try showing you the way. Maybe you already have solution yourself though.

IF BUCKY CAN, YOU CAN
First thing first, I must share this with you, I stumbled into this awesome YouTube Channel full of interesting materials, owned by a guy named Bucky. Bucky teaches all kind of stuffs in his own way. Although most of the stuffs there are "basic" but this guy really teaches the basic really well. I actually would like to adapt his way of teaching for my future video tutorials.

Bucky also teaches Python Basics, here is a link to Playlist for snippet of videos explaining the foundation of Python:
http://www.youtube.com/course?list=ECEA1FEF17E1E5C0DA&feature=plcp

It is not related directly to Blender, but it will give you excellent introduction on Python.

Bucky is a great teacher, I salute people like this.

WHAT IS THE TASK YOU WANT TO DO USING PYTHON?
This is an important question once you get a hang of Python and programming a little bit better. What interest you the most?
  • Tools and UI creation
  • Data I/O (Input Output)
  • 3D Data Manipulation
  • Rigging and Animation
  • Visual Effects
  • Game (physics, behaviour, interaction)
(Although I sound like I know things, but I am also still figuring a lot of things. So please keep that in mind and bear with me,)

Whenever thinking about Blender Python, beginner programmers tends to what to accomplish big tasks. Even me, was kind of naively thinking to achieve complex stuffs.

Have you watched the movie "Jiro Dream of Sushi (2011)"?
http://www.imdb.com/title/tt1772925/

Well, that movie is basically a documentary about Master of Sushi called Jiro in Japan. Any beginner apprentice would like to work with the Master takes years (to learn how to prepare Squid perfectly) before allowed to touch Fish and create Sushi.

It will be frustrating. You will make thousands of mistakes.

Anyways, if you are stuck, always go few back steps, maybe you need certain "basic" skills in order to successfully complete that task.

In this post, I will attempt to show you this simple task that I manage to accomplish using Blender and Python. You will learn a lot just by accomplishing small task.

000. PROGRAM START HERE
Enough babbling around let's get started.

I bet Python can do a lot of stuffs, but for beginner like me, I have big interest in how Python can be used to bring DATA in and out from one place to another. In our context, let see how Blender can take data from outside and then process into something that you can render.

I seriously do not know how to do this, this morning. But now 7+ hours later, I finally understand and decided to spend some time writing this notes to share with you.

001. THE TASK IS...
To import data and create 3D visualization in Blender using Python.

002. WHAT IS THE DATA? 
Or in programming context, what type of data are we dealing here?

I cannot write all the theory regarding DATA TYPE, but however you can Google and read some articles or video tutorials on data type in programming in general.

Watch and look up for these terminologies:
  • String -> string of text
  • Float -> floating value of number eg. 14.233, 1.245
  • Integer -> round number eg. 5, 9, 1456
  • Boolean -> True or False
  • List --> you will deal with list a lot in Python, it is the strength of Python
  • Array
  • Tuple
  • Dictionary
003. PREPARE THE RAW DATA
For this example, I just use a simple Tabular Data in a Spreadsheet that I created inside Google Doc Spreadsheet. It looks like this:

Very simple row x column tabular data. The COLUMN x ROW data basically contains:
  • Name (text data)
  • Number (number data)
  • Color (text data)
Total 11 row of data.

How do we bring that data into Blender using Python?

There are probably many ways to do that, but one thing that I certain is using CSV (Comma Separated Value) file format.

From Google Docs, you simply to to File - Download As - CSV. You will then get a file in CSV format. It is basically a text format, but the data comes as rows of text, with comma separated value, like below:

helloworld,14,red
one,23,green
two,67,blue
three,43,blue
four,77,red
five,99,green
six,45,red
seven,32,blue
eight,78,green
nine,22,red
ten,73,blue

CSV file format is something that Python can process quite nicely using Python CSV Module. Anyhow, let's slowly see how this can be accomplish. Let's bring in this data into Blender using Python.

004. READING CSV
I learn how to read CSV by reading this blog post:

I like that blog a lot, and I think you will also find it useful. Lots of great snippet (short Python code) that you can study and use.

Basically, you need to import the CSV file.
file = csv.reader(open('\\Users\Jimmy\Desktop\data.csv', newline=''), delimiter=',')

Make sure that you write the correct directory path. I use Windows 7, so the data path is as below:
'\\Users\Jimmy\Desktop\data.csv'

Then you parse the data using CSV module.

The STARTER PYTHON SCRIPT inside Blender then goes like this:
import bpy # THIS IS A MUST TO IMPORT ALL BLENDER PYTHON MODULE
import csv # IMPORT CSV MODULE

# READ INPUT FILE

file = csv.reader(open('\\Users\Jimmy\Desktop\data.csv', newline=''), delimiter=',')

for idx, row in enumerate(file):
if idx<11: # this is hard coded at the moment
print(idx,row)

I modify the script slightly below, just to get the TOTAL OF ROW, I seriously think there is a better way, but for now, it is a hack.

Maybe the file also needs to be closed to prevent memory leaks. But I leave that for later.

Remember that you need to be inside Blender Scripting layout and place the script inside the Text Editor Panel. You then run the script using hotkey Alt+P.




When run, that Python code will import (open) the data.csv and go through the loop and print every row of data of the CSV file and print out the: ROW INDEX + the value for each row as LIST of STRING.

If your script is executed correctly, you will see something like below on the Blender console window:


This means that you successfully import the CSV data (Strings) into Blender.

Next step will be to process the data further. The data itself is really simple and ready to use, it is a type of LIST of STRING that you can simply use in Blender.

In order to have much simpler LIST data that I can process in loop for every line, I modify the script again like below:

import bpy # THIS IS A MUST TO IMPORT ALL BLENDER PYTHON MODULE
import csv # IMPORT CSV MODULE

# READ INPUT FILE

file = csv.reader(open('\\Users\Jimmy\Desktop\data.csv', newline=''), delimiter=',')

curRow = [] #empty placeholder for current row

for idx, row in enumerate(file):
if idx<11: # this is hard coded at the moment

curRow = row



The "curRow" variable there is a new LIST data variable that further break the CSV data into easier data to pass on.

005. STRING INTO 3D TEXT OBJECT
First data is String type and we can simply pass it to Blender to create 3D Text Object.

Via Google Search, I stumbled into this video tutorial: 

That video should explain clearly how you can use Python inside Blender to create Text Object with string data that you are supplying. 

So based from that information, our code becomes like below:

import bpy # THIS IS A MUST TO IMPORT ALL BLENDER PYTHON MODULE
import csv # IMPORT CSV MODULE

# READ INPUT FILE

file = csv.reader(open('\\Users\Jimmy\Desktop\data.csv', newline=''), delimiter=',')

curRow = [] #empty placeholder for current row

for idx, row in enumerate(file):
if idx<11: # this is hard coded but you can use

curRow = row

# display first data index as string
bpy.ops.object.text_add(location=(0,idx,0), rotation=(0,0,0))
bpy.ops.object.editmode_toggle()
bpy.ops.font.delete()
bpy.ops.font.text_insert(text=curRow[0])
bpy.ops.object.editmode_toggle()




You see how the first column of data which were originally in tabular format is now spit out as 3D Text Object and visualized in 3D!

We are good and on the right track!

The process continues for the other data on Column 2 and 3 (from the original Tabular Data)

006. NUMBER
Our number data is simple.

It is totally up to you how you like to visualize it. To be really simple, we just pass on the NUMBER into SCALE. I use 3D Polygon Cube and Scale them in one axis to create BAR kind of type of visualization, based on the number provided. And I simply place them on location.

The script is now like this:

import bpy # THIS IS A MUST TO IMPORT ALL BLENDER PYTHON MODULE
import csv # IMPORT CSV MODULE

# READ INPUT FILE

file = csv.reader(open('\\Users\Jimmy\Desktop\data.csv', newline=''), delimiter=',')

curRow = [] #empty placeholder for current row

for idx, row in enumerate(file):
if idx<11: # this is hard coded but you can use

curRow = row

# PROCESS COLUMN ONE
# display first data index as string
bpy.ops.object.text_add(location=(0,idx,0), rotation=(0,0,0))
bpy.ops.object.editmode_toggle()
bpy.ops.font.delete()
bpy.ops.font.text_insert(text=curRow[0])
bpy.ops.object.editmode_toggle()

# PROCESS COLUMN TWO
# create cube and transform resize
bpy.ops.mesh.primitive_cube_add(view_align=False, enter_editmode=False, location=(0, 0, 0), rotation=(0, 0, 0))


# store the location of current 3d cursor
saved_location = bpy.context.scene.cursor_location.copy() # returns a copy of the vector

# give 3dcursor new coordinates
bpy.context.scene.cursor_location = (0.0,0.0,-1.0)

# set the origin on the current object to the 3dcursor location
bpy.ops.object.origin_set(type='ORIGIN_CURSOR')

# set 3dcursor location back to the stored location
bpy.context.scene.cursor_location = saved_location


myScale = int(curRow[1])


#bpy.ops.transform.resize(value=(0.5, 0.5, 0.5))
bpy.ops.transform.resize(value=(0.5, 0.5, myScale), constraint_axis=(False, False, False), constraint_orientation='GLOBAL', mirror=False, proportional='DISABLED', proportional_edit_falloff='SMOOTH', proportional_size=1, snap=False, snap_target='CLOSEST', snap_point=(0, 0, 0), snap_align=False, snap_normal=(0, 0, 0), texture_space=False, release_confirm=False)

bpy.ops.transform.translate(value=(5, idx, 0), constraint_axis=(False, False, False))


I basically take the data from Column Two, as now passed in by curRow[1] placeholder. It does that for every line. It is as if you are create Cube, move it into place, and scale it accordingly based on the data provided.


It actually works, but not optimized. You see how the BARS are really too long in Blender Unit. Perhaps later I can optimize the data range so that they can be "normalized" and scaled into manageable size.

I also did something with the 3D Cube Origin there using Python. Looks tricky, but really simple once understood. Read below blog post:

Dealing with Origin using Python

This is unrelated but interesting:

007. COLOR DATA
Ok, now we get to data in Column 3, which is COLOR type. Well, it is actually STRING data (text), where I specified: RED, GREEN, or BLUE.

To accomplish this, I actually brainstormed a bit. Rather than using "all Python solutions", I am thinking that maybe it is easier if you prepare some Materials named "red", "green", "blue" that can then be linked into the Object.

It would be interesting too, to actually try to create new material and change the Color Diffuse value using Python. I might add addendum that does that.

Typically Color data is in format of Vector, RGB (123, 122, 123). I have not looked into it yet.

Anyhow, the idea is really to prepare 3 Materials named "red", "green", "blue", and then using Python to apply it to the BARS.

Assigning Materials using Python
Assigning certain Materials (with specific name) to certain object in Blender is slightly tricky because you need some understanding of Blender Data Flow and Linking.

This forum post helps me a lot:

But this one also helps:

What would be interesting is to do also try this, importing Materials from other BLEND. Very cool, but you may want to do this later.

I borrow the code from ATOM (on Material creation), and plonked it in into our script. I think I need to digest this information a little further and try to explain what happening later. But for now, the idea is like this:

1. In Blender, you need to create Material Data for each Object. You cannot assign material if you don't first assign Material.
2. Once you have Material Data, as we know, Blender can have "Multiple Slots" per Material.
3. For our task here, we just need a single Material Data and change the value of Material Slot into the Material name that we specified.
4. Make sure that you have prepared the "red", "green", and "blue" Materials before running the script.

The code becoming like this:


import bpy


import csv





# READ CSV DATA FILE





file = csv.reader(open('\\Users\Jimmy\Desktop\data.csv', newline=''), delimiter=',')





curRow = [] #empty placeholder for current row





# ATOM


def returnMaterialByName(passedName):


    result = None


    for m in bpy.data.materials:


        if m.name == passedName:


            result = m


            break


    return result





def createNewMaterial (passedName):


    tempMat = bpy.data.materials.new(passedName)


    if tempMat != None:


        tempMat.diffuse_color = (0.5,0.6,0.7)


        tempMat.diffuse_shader = 'LAMBERT'


        tempMat.diffuse_intensity = 1.0


        tempMat.specular_color = (0.9,0.9,0.9)


        tempMat.specular_shader = 'COOKTORR'


        tempMat.specular_intensity = 0.5


        tempMat.alpha = 1.0


        tempMat.ambient = 0.3


        tempMat.emit = 0.2


    return tempMat





def aquireOrCreateMaterial(passedName):


    tempMat = returnMaterialByName(passedName)


    if tempMat == None:


        tempMat = createNewMaterial(passedName)


    return tempMat








for idx, row in enumerate(file):


    if idx < 10: #still hard coded, how to check the total line size or length


        print(idx,row)


        curRow = row


        


        # display first data index as string


        bpy.ops.object.text_add(location=(0,idx,0), rotation=(0,0,0))


        bpy.ops.object.editmode_toggle()


        bpy.ops.font.delete()


        bpy.ops.font.text_insert(text=curRow[0])


        bpy.ops.object.editmode_toggle()


               


        # create cube and transform resize


        bpy.ops.mesh.primitive_cube_add(view_align=False, enter_editmode=False, location=(0, 0, 0), rotation=(0, 0, 0))


             





        # store the location of current 3d cursor


        saved_location = bpy.context.scene.cursor_location.copy()  # returns a copy of the vector


        


        # give 3dcursor new coordinates


        bpy.context.scene.cursor_location = (0.0,0.0,-1.0)


        


        # set the origin on the current object to the 3dcursor location


        bpy.ops.object.origin_set(type='ORIGIN_CURSOR')


        


        # set 3dcursor location back to the stored location


        bpy.context.scene.cursor_location = saved_location


        myScale = int(curRow[1])




        #bpy.ops.transform.resize(value=(0.5, 0.5, 0.5))


        bpy.ops.transform.resize(value=(0.5, 0.5, myScale), constraint_axis=(False, False, False), constraint_orientation='GLOBAL', mirror=False, proportional='DISABLED', proportional_edit_falloff='SMOOTH', proportional_size=1, snap=False, snap_target='CLOSEST', snap_point=(0, 0, 0), snap_align=False, snap_normal=(0, 0, 0), texture_space=False, release_confirm=False)





       


        bpy.ops.transform.translate(value=(5, idx, 0), constraint_axis=(False, False, False))







# create material


#bpy.ops.material.new()





# to script and create specific material with certain name will be difficult, another way is to create manually or import from outside BLEND and apply it using script


# if we manually already create certain material with certain name it will be easier, we simply need to apply it per selected object




        myObj = bpy.context.active_object


        print(myObj)


        


        


        # Program begins here.


        #bpy.ops.mesh.primitive_cylinder_add()


        #ob = bpy.context.active_object


        #ob.name = "myCylinder"


        me = myObj.data


        mat = aquireOrCreateMaterial ("myNewMaterial")


        me.materials.append(mat)





                


        # before applying below, you need to create material data slot first!


        myObj.material_slots[0].material = bpy.data.materials[curRow[2]]



When the script is run, hopefully you get the result like below:


So, there you have it, a whole documentation on how I accomplish this task of importing CSV data, passing it into Blender 3D Objects to visualize the data, using Python.

WHAT NEXT?
Actually even if the code is working, you can then take it further:
  • Further optimize the code and function
  • See what variations you can create with it
  • Create User Interface (UI) if required
This is a very basic example of how you can bring code from CSV, but I think you can do a lot from here.

Actually, this example is probably too hard for beginner programmers. It is probably useful to look into Python LIST as well, and how to work with list.

There are some parts where I jump and use the code without 100% understanding it. It does the job, but I need to take steps back and try to understand that part and simplify it.

The Material creation and assignment using Python should not be that complicated, just need a way to think and understand it.

At least if you and me manage to go through this exercise, you understand the workflow on how:
1. To bring data from CSV using Python in Blender.
2. Parse the data line by line using Python in Blender..
3. Further process the data and pass on the value to create 3D objects in Blender.

My WISHLIST to do using Python in near future:
  • Import and Export of Particle Data
  • Understand Python better, especially within Blender context, we want to be able to write out Blender data and read it back in on other 3D sofware like Maya, Houdini, Softimage.
  • Create Simulations
  • Create Random Looking Creature
  • Asset Management Pipeline
There is no doubt that Blender Python can be utilized to the level like below:
http://www.molecularmovies.com/toolkit/

UPDATE 2012.12.12: Blender PDB Atomic Molecular data importer
Well, in Blender 2.65 update, we have Protein Data Bank (PDB) Molecule Importer built in inside Blender!!! How awesome is that? You can actually study the Python of addons.
http://wiki.blender.org/index.php/Extensions:2.6/Py/Scripts/Import-Export/PDB

SEE ALSO: Bio Blender by Mike Pan
http://bioblender.eu/

This is Alcohol Atom formation.
Above is Alcohol PDB taken from here:
http://wbiomed.curtin.edu.au/biochem/tutorials/pdb/index.html

CHALLENGE:
For you, Blender Python genius that is mentally challenged:
  • Get live Twitter data and pass it into Blender
  • Get Facebook Data and visualize your friend's birthday across 12 months
  • Get live Yahoo! Weather data and visualize temperature of certain area in globe.


Thousands of Mario rendered 3Delight from inside Blender. The scene is using RIB Archive from Maya (contains animation and Maya shaders) that is instanced with Blender Particles, and rendered with very little memory usage and under 1 minute.
WARNING: This is one of those "wordy" blog post!

AS ONE MAN'S BAND
Working with multiple 3D tools is like playing multiple ensemble of instruments. It is quite a privilege to be able to do so from your own computer. Nowadays anyone with access to decent computer and Internet, can start playing and working with these powerful ensembles right away.

I am maybe one of those "One Man's Band" people, most of the time. Perhaps some of you, readers of this blog, are too. Surely it is nice to work in a big or small team, where each plays part of  musical piece and can play together an epic musical. But sometimes in a low tide situation, one needs to be able to survive alone. Not just that, I am sure each artist has self-desire to make own personal project.

Remember, the thing is: You are not really alone because there are many artists out there sharing their knowledge and brain online. You just need to find it and create your own party.

If for musicians the aim is to play a beautiful music to inspire many. For us CG artists, hopefully we are always aiming to create beautiful visuals and creative imagery to inspire many.

For that reason, we use all kind of tools to do so. From choosing your modeling tool, animation tool, all the ways ... to finally to choosing your rendering and compositing tool.

If you came to this blog, you are more likely to have chosen Blender to be your 3D tool. Blender actually provides almost all of those functionality you ever need to create 3D animation and with a high standard. This comes to my surprise, as someone who was originally using other commercial 3D packages (Maya), Blender still amazes me. There must have been a lot of efforts put into Blender by programmers, developers and artists out there to improve this 3D package to the current stage.

Saying that, I think Blender is just "too ideal" for the actual 3D industry at this moment, and it is actually a good idea to also learn 3D Commercial package. Almost all of them actually give you the "Student Learning Edition", you can install 3DSMax, Maya, Softimage, and Houdini for your study. Not for commercial though, for that you need license. Unlike Blender.

It's good to think both  "Inside The Box" and also "Outside The Box".

EXTERNAL CG RENDERERS
Let's focus on actual topic I want to talk about: 3D rendering and its renderer.

Based on my little knowledge, we can probably categorizing CG renderer like this:
1. Real Time Renderer (like for games): Blender Game Engine
2. Non Real Time Renderer
   - Non physically based renderer and physically based renderer
   - Raster and Raytrace
   - Non photorealistic renderer: Blender Freestyle

Famous 3D renderers (commercial) out there that I knew of or I heard a lot lately:
  • VRay -> has nice Global Illumination
  • Mental Ray (like in Maya and Max)
  • Maxwell Render
  • Octane Render -> similar concept to Blender Cycles, it is really fast GPU renderer. Octane takes OBJ as input.
  • Pixar Renderman PRMan ->  Renderman Complient Renderer
  • 3Delight -> Renderman Complient Renderer
BLENDER RENDERER
Recent version of Blender comes with its built-in Blender Internal and Cycles as we already know. Those are really powerful renderer if one really knows how to use it well.

Although Blender Internal seems to be quiet in development, it is still powerful as currently is and have plenty to explore.

Cycles renderer is actively and continuously being developed. As a real time GPU renderer (utilizing OpenGL), Cycles has a real edge in itself. It is actually a huge leaps in term of 3D rendering that CG artist today can take for granted. 

Custom node-based building of Cycles Materials is an open ended area to explore and I would love to have time to look into this more in near future.

Blender itself being an open source 3D package with great organizing capability (able to reference and link objects from outside), has a capability to act as unlimited renderer engine for other 3D packages, can render on any computer with Blender installed.

But the thing is Blender needs a better FBX support (I believe they are working on it) in order to work together with other 3D packages. Until then, it could be a little tricky to put things together works from outside the box.

3DELIGHT FOR BLENDER
http://mattebb.com/3delightblender/


I was recently looking at this 3Delight add-on by Matt Ebb. I don't know how many Blender users out there is actually using this amazing Add-On. One of the best 3Delight Renderer Interface for Blender, it is probably the only one.

I looked at Matt's add-on few times and recently got upgraded for Blender version 2.63. I believe Matt worked on the add-on on his own spare time, which is certainly impressive.

Matt Ebb's example render using Blender and 3Delight:
https://vimeo.com/29014574

This 3Delight Blender Add-On allows you to translate Blender scene into Renderman language, into beautiful pictures rendered with Renderman compliant renderer, such as 3Delight and PRMan (Pixar Photorealistic Renderman), high end renderer used in so many major movies.

3Delight first license is actually free with CPU limitation (2 CPU Processor max) . PRMan is not free (it has cost), but PRMan has the most complete feature and other advantages.

I will not be writing much about in depth history of PRMan or 3Delight, I just feel to write and express my actual curiosity of this 3Delight Add-On and also Renderman in general. Hopefully can also motivate you to look into Renderman and how you can use Blender to help you learning Renderman.

What you need to get started:
1. Blender version 2.63
2. Matt Ebb's 3Delight/Blender Add-On
3. 3Delight installed on your computer.
http://www.3delight.com/

The Add-On itself is like "Work In Progress (WIP)", meaning it is not totally complete and it does not serve a complete feature of Renderman. However, this is still a good looking add-on and usable when you wanted to learn Renderman and the art of 3D rendering, Renderman way.

NOTE: 
I have little knowledge about Renderman, 3Delight, and PRMan, so probably not all what I wrote is correct, please be kind and correct me in the comments.

INTERFACE FOR RENDERER
You see, the INTERFACE is everything nowadays.

All good 3D packages these days can already do pretty much what all 3D packages supposed to do and it all comes back to the INTERFACE (aka User Interface)

First, you have the interface of your 3D tool of choice, to work on your 3D project. Then you might have all kinds of other modeling tools with each own interface: ZBrush, MudBox, Sculptris or Blender Sculpt brush for sculpting. The 3D data being passed on from one package to another package. If it is just your model, OBJ is usually fine.

If I take another analogy, it is like you can take photograph and do photography using DSLR camera or using good compact camera or mobile phone camera. For mobile camera, the interface is even taken to another level of complexity (or simplicity) where you could literally have hundreds of apps to take photo and process it in an instant.

Now, back to actual topic of 3D Renderer, why do we need to care about it? Isn't it enough just to use whatever renderer available in your 3D package and hit the render button? Yes, that is true for most cases. You typically would render out your 3D scene, inside your 3D package as something like EXR, which is like RAW format in photography, which contains extra information to be used and processed further during compositing. Why do we then need for external renderer with yet ANOTHER INTERFACE (if using Renderman workflow)?

Well, I guess the full list of answers are like below (the reason on why we need additional interface before actual rendering):
  • Quality: able to create high quality result renders
  • Usability: ease of use and smoother pipeline for more complex setup
  • Customability: able to create custom shaders and be really specific on how it should look
  • Speed, Memory and Stability: able to render complex scene without crashing
  • Expandability and ability to handle Complexity: able to work in a large massive scene in a large scale way (cloud and server render)
  • Flexibility, Modularity and Interoperability: can be passed on from one renderer to another within the same rendering languages. If I am not wrong, RIB is also can be passed to compositing software like Nuke. It involves Renderman AOV, etc, whic I don't really quite understand yet.
TO WATCH FOR: Pixel Samples, Shading Rate, Pixel Filter, Depth Of Field, Motion Blur, and Renderman Output.
Separating 3D package from its 3D render, and having a human readable text is really powerful.

RENDERMAN = THE HIGH END RENDERER
With Renderman workflow, we sort of have ways to separate 3D Packages and actual 3D scene object geometry to render (with all the shaders, lighting, etc). You can render without actual 3D software Interface, yet still manageable and controllable.

It is kind of having a RAW file for your render, but still in 3D format that you can tweak.
[any 3D Scene] --> RIB (Renderman Interface ByteStream) --> [any Renderman Renderer]

RIB
In short, this is your 3D scene description. This is the bare minimum input you can pass on to Renderman to give you image output. You specify a series of commands or calls to render.

Everything that is shown on your 3D view, can be translated into RIB packages, to be passed on any Renderman renderer. Matt Ebb's Add-On 3Delight provide you easy way to set the RIB automatically, translating Blender scene as RIB.

Imagine "HTML" for "web pages", this RIB is just like "HTML" but for CG and you specify to the renderer what to do, where the Shader is, how the object should be transformed, etc. Well, if you think about it, it is kind of like "CSS" too. RIB works in hierarchy and you can add anything into stack to change certain attribute and be very specific.

RIB is easily editable and can be modified with text program.


Maya Paint Effects (PFX) and SOuP instancing Blender Monkey Primitive, exported out as RIB. RIB modified slightly to override the original RIB Shader.
Quick render inside Blender as RIB Archive.

C Binding, Programming and Compiling
When learning Renderman language, you will eventually get to this terminology. The way I look at it, C programming is like a way to procedurally script your 3D scene geometry. Don't even want to go there.

The point of having 3D softwares is the reason artists can avoid all those complexity. Leave the codes to the developers and geniuses. Unless you are genius.

NOTE: You could learn RIB binding using Python though. Python RIB Binding is kind of more for human!

At a quick glance, my understanding is that you could write script outside RIB that you can call to procedurally generate some values, instead of typing each lines manually.

RSL/Renderman Shading Language
Not the best example of renders, but this is just few basic Surface and Displacement Shaders that usually come by default with Renderman renderer. Watch out for Displacement Bound when you use Displacement.
RSL or Renderman Shading Language is probably something you want to get into. Generally, RSL is more accessible to artist's brain, you can basically write your own Shaders for Surface, Displacement, Light, etc. instead of relying of the common set of Materials made available inside 3D package.

You write RSL as *.SL using any notepad text (I use NotePad++) and then you compile it into a Renderman Shading Language that you can attach into 3D geometry.

With 3Delight, all you need to do to compile is to go to Command and then run the command like below:
shaderdl mySurface.sl
shaderdl myDisplacement.sl

It will then produce a compiled version:
  • For 3Delight: (shaderdl.exe)SL > SDL
  • For Pixar PRMan: (shader.exe)SL > SLO
Some default Renderman Shaders and more. Plenty more. Renderman is about shaders that give you that perfect look.
Each Shader comes with defined parameters. And you can make your own.

USING RIB ARCHIVE
This is Renderman feature that I like a lot:
Being able to export and import RIB archive (including animation sequences) from outside, just like if you are referencing 3D objects from outside the scene into the current scene.

Using RIB Archive can save memory for rendering, supposedly really efficient, especially with DelayedLoadArchive feature which allow Renderman to render only what is seen via camera. The workflow is quite specific, I suggest you to read the documentation.

All you need to do to render the RIB archive is to attach RIB Archive Path into some kind of placeholder in 3D scene (can be Empty, or any geometry). Ideally the placeholder is about the same size bounding box of the RIB Archive so we could have a better reference.

RIB Archive output may have geometry, light, shaders, all in a single package, which ideally can be overridden via Renderman specific Attribute inside your current 3D package. Not sure if this is implemented with the Add-On. You could always edit the RIB Archive by text editor.


RIB Archive From Maya > to Blender to 3Delight





RIB Archive From Houdini > to Blender to 3Delight



I supposed with RIB we can easily bring all kinds of scene elements together and can be rendered inside or outside any 3D package. Well... providing we completely understand Renderman workflow.

So far, the most smooth workflow is via Maya (because 3Delight provides a full on Maya plugins). Scene and animation from Blender is exported out as RIB archive, and then brought into Maya for further adjustment and final render.

Ideally, I want to do the Final Layout and Render in Blender + 3Delight and then Compositing.

THE FUTURE OF FUTURE OF RENDERING
Who would know what "3D rendering" is going to be in few years to come. Game engine has become so powerful that Real Time Rendering and Game Cinematic will also be a more common everyday accessible tool to create an actual cinematic experience.

Still thought.... Renderman legacy in Computer Graphics is something that is dear to CG Artists. I dare to say: One does not know Computer Graphics fully, until he/she learns Renderman. Who knows where Renderman is heading in the future?

I heard also about OSL (Open Shading Language) for Blender Cycles, which I don't know exactly what this is, but it is probably something like RSL of Renderman.

BOOKS TO READ
WEB RESOURCES
UPDATE 20120909
Blender Open Shading Language (OSL) for Cycles: (brilliant implementation, similar to Renderman Code Node)
http://www.youtube.com/watch?v=F9zxJr9_5Vk

Now officially available with Blender 2.65!

UPDATE 20121129
See also this great video tutorial from Thomas Dinges:
http://www.youtube.com/watch?v=4LQXjIDWtz0&feature=plcp


Shader writing is always kind of interesting for me. I don't know much about it though, still reading here and there. Anyways, there are geniuses out there sharing OSL knowledge and shaders, so I will list any links related to OSL below, so we can all learn together:

OSL RELATED LINKS

MKRdezign

Contact Form

Name

Email *

Message *

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