The blender python api: precision 3d modeling and add-on development 1st edition chris conlan - Own

Page 1


1st Edition Chris Conlan

Visit to download the full and correct content document: https://textbookfull.com/product/the-blender-python-api-precision-3d-modeling-and-ad d-on-development-1st-edition-chris-conlan/

More products digital (pdf, epub, mobi) instant download maybe you interests ...

Blender 3D Printing by Example Learn to use Blender s modeling tools for 3D printing by creating 4 projects 1st Edition Vicky Somma

https://textbookfull.com/product/blender-3d-printing-by-examplelearn-to-use-blender-s-modeling-tools-for-3d-printing-bycreating-4-projects-1st-edition-vicky-somma/

Building a Game with Unity and Blender Learn how to build a complete 3D game using the industry leading Unity game development engine and Blender the graphics software that gives life to your ideas 1st Edition Lee

Zhi Eng

https://textbookfull.com/product/building-a-game-with-unity-andblender-learn-how-to-build-a-complete-3d-game-using-the-industryleading-unity-game-development-engine-and-blender-the-graphicssoftware-that-gives-life-to-your-ideas-1s/

Geoprocessing with Python 1st Edition Chris Garrard

https://textbookfull.com/product/geoprocessing-with-python-1stedition-chris-garrard/

The Complete Guide to Blender Graphics: Computer Modeling and Animation 6th Edition John M. Blain

https://textbookfull.com/product/the-complete-guide-to-blendergraphics-computer-modeling-and-animation-6th-edition-john-mblain/

Core Blender Development: Understanding the Essential Source Code 1st Edition Brad E. Hollister

https://textbookfull.com/product/core-blender-developmentunderstanding-the-essential-source-code-1st-edition-brad-ehollister/

Modeling the 3D Conformation of Genomes 1st Edition Guido Tiana (Editor)

https://textbookfull.com/product/modeling-the-3d-conformation-ofgenomes-1st-edition-guido-tiana-editor/

The Complete Guide to Blender Graphics: Computer Modeling & Animation, Fifth Edition John M. Blain

https://textbookfull.com/product/the-complete-guide-to-blendergraphics-computer-modeling-animation-fifth-edition-john-m-blain/

The Complete Guide to Blender Graphics Computer Modeling Animation 6th Edition John M Blain

https://textbookfull.com/product/the-complete-guide-to-blendergraphics-computer-modeling-animation-6th-edition-john-m-blain/

Core Blender Development: Understanding the Essential Source Code Brad E. Hollister

https://textbookfull.com/product/core-blender-developmentunderstanding-the-essential-source-code-brad-e-hollister/

The Blender Python API

Precision 3D Modeling and Add-on Development

The Blender Python API

Precision 3D Modeling and Add-on Development

Chris Conlan

The Blender Python API: Precision 3D Modeling and Add-on Development

Bethesda,

USA

ISBN-13 (pbk): 978-1-4842-2801-2

DOI 10.1007/978-1-4842-2802-9

ISBN-13 (electronic): 978-1-4842-2802-9

Library of Congress Control Number: 2017944928

Copyright © 2017 by Chris Conlan

This work is subject to copyright. All rights are reserved by the Publisher, whether the whole or part of the material is concerned, specifically the rights of translation, reprinting, reuse of illustrations, recitation, broadcasting, reproduction on microfilms or in any other physical way, and transmission or information storage and retrieval, electronic adaptation, computer software, or by similar or dissimilar methodology now known or hereafter developed.

Trademarked names, logos, and images may appear in this book. Rather than use a trademark symbol with every occurrence of a trademarked name, logo, or image we use the names, logos, and images only in an editorial fashion and to the benefit of the trademark owner, with no intention of infringement of the trademark.

The use in this publication of trade names, trademarks, service marks, and similar terms, even if they are not identified as such, is not to be taken as an expression of opinion as to whether or not they are subject to proprietary rights.

While the advice and information in this book are believed to be true and accurate at the date of publication, neither the authors nor the editors nor the publisher can accept any legal responsibility for any errors or omissions that may be made. The publisher makes no warranty, express or implied, with respect to the material contained herein.

Cover image designed by Freepik

Managing Director: Welmoed Spahr

Editorial Director: Todd Green

Acquisitions Editor: Susan McDermott

Development Editor: Laura Berendson

Technical Reviewer: Justin Mancusi

Coordinating Editor: Rita Fernando

Copy Editor: Kezia Endsley

Compositor: SPi Global

Indexer: SPi Global

Distributed to the book trade worldwide by Springer Science+Business Media New York, 233 Spring Street, 6th Floor, New York, NY 10013. Phone 1-800-SPRINGER, fax (201) 348-4505, e-mail orders-ny@springer-sbm.com, or visit www.springeronline.com. Apress Media, LLC is a California LLC and the sole member (owner) is Springer Science + Business Media Finance Inc (SSBM Finance Inc). SSBM Finance Inc is a Delaware corporation.

For information on translations, please e-mail rights@apress.com, or visit http://www.apress.com/ rights-permissions.

Apress titles may be purchased in bulk for academic, corporate, or promotional use. eBook versions and licenses are also available for most titles. For more information, reference our Print and eBook Bulk Sales web page at http://www.apress.com/bulk-sales.

Any source code or other supplementary material referenced by the author in this book is available to readers on GitHub via the book’s product page, located at www.apress.com/9781484228012. For more detailed information, please visit http://www.apress.com/source-code

Printed on acid-free paper

For my teachers and colleagues at the University of Virginia Department of Statistics.

About the Author

Chris Conlan began his career as an independent data scientist specializing in trading algorithms. He obtained his degree in statistics from the University of Virginia where he established himself as an expert in automated trading. His passion for intuitive data visualization introduced him to various 3D modeling and virtual reality suites that he hopes to better integrate into the lives of data scientists. He is currently managing development of private technology companies in high-frequency Forex, machine vision, and precision 3D modeling.

About the Technical Reviewer

Justin Mancusi attended the University of Virginia, where he obtained degrees in computer science and mathematics. In the past, he has worked as an independent consultant at the intersection of computing and statistics. He is experienced in a breadth of computational topics including advanced optimization, computational statistics, and stochastic processes.

Introduction

This text details the development and use of 3D modeling tools in Blender’s Python API. We challenge the perception of Blender as purely an artist’s tool by building precise data-driven models. Simultaneously, we teach you how aid and enable artists by deploying custom tools in the familiar Blender environment.

The knowledge presented in this text is the result of a deep understanding of not only Blender’s documentation and source code, but also of the source code of add-ons written by Blender’s core developers. The author has discovered many useful functionalities that are, as of the time of writing, undocumented. Thankfully, we as users can stay on the cutting edge by listening to and learning from those developers. This text unifies well-documented introductory material and undocumented advanced material to create a powerful reference.

This book is packed with code examples and screenshots of powerful scripts and add-ons. We include scripts to automate precise tasks that would otherwise be very difficult to implement by hand. In addition, we build add-ons that augment Blender’s existing functionalities with new tools, objects, and customization options.

Definitions

3D modeling is the art of manipulating data to create 3D representations of objects and environments. 3D artists use the following tools and techniques to build 3D models.

• Manual modeling involves the artist interacting with a software interface. This can be:

• Using a 3D modeling suite (Blender, Maya, or 3ds Max) to create and edit objects by hand

• Playing video games with 3D building elements (Minecraft, Fallout 4, or Sims)

• Manually inputting data into a 3D object file (.obj, .stl, or .glTF)

• Automated Modeling involves algorithmically generating 3D models. This can be:

• Procedural generation of environments and characters in video games

• Generating detailed models of buildings from architectural specifications

• Producing 3D-printed art from fractal algorithms

• Primitives are the basic building blocks of 3D models. Though there are no strict rules on what constitutes a primitive, these can be:

• Simple closed shapes like planes, cubes, and pyramids

• Simple curved shapes like spheres, cylinders, and cones

• Complex shapes like tori (plural of torus), Bezier curves, Nurbs surfaces

3D models are data representations of objects and environments. 3D models have the following components.

• Data formats allow models to differentiate and specialize by application. Every type of 3D model has a format by which it is specified. These include:

• Suite-specific formats like .blend for Blender, .3ds for 3ds Max, and .ma for Maya

• Renderer-specific formats like .babylon for BabylonJS, .json geometry descriptor for 3JS, and .glsl for OpenGL shaders

• Minimalistic interchange formats like .obj and .stl

• Vertices and faces define the points and the surfaces connecting those points in 3D space.

• Vertices are triplets of real numbers 3D space, or traditional (x, y, z) coordinates of each point of the object.

• Faces are triplets of integers, where (i, j, k) represents the triangle in 3D space formed by the i-th, j-th, and k-th vertex.

Prerequisite Knowledge for This Book

This book covers Blender version 2.78c running Python 3.5.2. Most examples run on Blender 2.70 and greater, and the concepts apply to Blender generally. Nonetheless, it is recommended that readers use Blender 2.78c to best follow along. As we discuss the history and development of Blender and the Python language, we will point out programming practices that are not likely to work on past and future versions. We assume a basic working knowledge of Blender and Python 3. Familiarity with any version of Blender 2.60 or greater is sufficient. Similarly, pure Python 2 programmers will have no problem following along.

Material Overview

This text introduces knowledge and sequentially builds on it to create more and more complete and complex software solutions. We introduce and discuss the following major topics.

Chapter 1: The Blender Interface

There are many individual interfaces that make up Blender. The core interfaces are highly scriptable because almost every possible user interaction is tied directly to a Python function. We establish some familiarity with those parts of the interface especially important for Python programming. The Blender interface will act as both the deployment and development environment for your software. We discuss unique considerations for programming and testing Python while remaining in the Blender interface.

In an effort to minimize usage of screenshots throughout this text, we introduce important vocabulary for discussing the Blender interface. Using this vocabulary, we can focus on Python code while allowing users to work in their own preferred layout of the Blender interface.

Chapter 2: The bpy Module

The bpy module is the core of the Blender Python API. Learning to navigate this module will drastically improve your understanding both Blender and the API. Early in this book, we focus on classes within bpy that construct objects and manipulate their associated metadata. Later in the book, we access new classes in the bpy module that turn scripts into plugins.

The module itself is very verbose. Early scripts will appear both complicated and repetitive. After getting our feet wet with object creation and manipulation, we will begin adding useful function to a toolkit we will build throughout the book. We will store complex and commonly-used algorithms in the toolkit but encourage readers to commit core elements of the bpy module to memory. In this way, we create code that is both easy to write and easy to share.

Chapter 3: The bmesh Module

The bmesh module is a relatively new module that attempts to simplify complex vertex-level manipulation of object data. For those readers familiar with Blender, most of the operations in bmesh will only run in Edit Mode and not Object Mode. This serves to enforce that the functions in bmesh are for granular changes rather than global transformation of the mesh data.

This module, in the author’s opinion, is what distinguishes the Blender Python API from other automated 3D modeling software. The bmesh module gives us algorithmic access to Blender’s large suite of Edit Mode tools for vertex-level, edge-level, and face-level object manipulation. It allows us to write procedural generation algorithms for very complex objects in hundreds instead of thousands of lines of code.

Chapter 4: Topics in Modeling and Rendering

It is essential to anyone working in 3D modeling to have a basic understanding of the mechanisms we rely on to render and visualize our work product. We will discuss the basics of rendering pipelines and important rendering topics for Blender Python development. Many perceived bugs and strange behaviors in Blender and in visualizers to which we export are actually intended behaviors of renderers. We learn to detect and program around these behaviors to ensure we are creating highly portable models.

We discuss common and uncommon file formats, Z-fighting, normal vectors, the differences between software and hardware rendering, and much more. This will help us debug Python code based on behaviors we see in various rendering software.

Chapter 5: Introduction to Add-On Development

Bridging the gap between a script and a distributable add-on can be a difficult process that relies on very specific development practices, careful code organization, and occasional meta-programming. Many of these concepts mirror standard Python module development practices, while many others rely on unique behaviors of Blender’s scripting interface.

We discuss GUI development, custom Blender data objects, bpy.types, and bpy.utils in detail here. We discuss organization of add-on files and ways to increase portability across different versions of Blender. At this point in the text, readers will be able to create add-ons that extend Blender to the benefit of modelers that do have Python experience.

Chapter 6: The bgl and blf Modules

The bgl module is an OpenGL wrapper for Blender that is useful for marking up, measuring, and visualizing objects and data in the Blender interface. The blf module is for drawing text and fonts with the Blender interface and is rarely used without the bgl module. We touch on the bpy_extras and mathutils modules to aid us here.

These modules are incredibly useful for add-on development, because we can influence the data the user sees without affecting the models themselves. We introduce them at this point in the text because their effectiveness depends on the ability to run them as add-ons.

Chapter 7: Advanced Add-On Development

Up to this point, we will have used Blender’s Text Editor to create scripts and add-ons. The Text Editor introduces various limitations on the form of our add-ons that we overcome here. We also discuss best practices for data storage and module management by citing popular community add-ons. We conclude this chapter with a discussion of advanced GUI development.

Chapter 8: Textures and Rendering

Up to this point, we will have worked purely with meshes in Blender. In this chapter, we bring scenes to life with texturing and rendering. We discuss procedural uv-mapping, lighting placement, and camera positioning. With this discussion comes an overview of lighting types, camera perspective dynamics, and bounding box algorithms.

We conclude this chapter by procedurally rendering an arbitrary scene and providing a framework for automated rendering pipelines. We focus on still renderings in this chapter, but readers interested in automated animation will be able to extend the examples without difficulty.

History of Blender and Python

The relationship between the Blender interface and the Blender Python API is a rare one in the world of software development. It is typical for API-enabled platforms to treat users and developers as separate classes of citizens, complete with separate tools, separate environments, and separate goals. Blender, on the other hand, has erased the line between developers and users, making it easy for users to act as developers and vice versa.

The close relationship between developers and users is the product of wise early design decisions within Blender’s core development team. Before Blender was released as free open source software in August 2003 as version 2.26, the core development team released the Python API documentation for the then-premium version 2.25. Python 2.0 had just been released in October 2000, and Blender was already using it to manage calls from the interface to its C-level data structures.

Released in 2009, Blender 2.50 and forward would use pure Python to dispatch editing tasks to its lowerlevel algorithms and data structures. Every action on the user interface was linked to a Python function, and the user had the option of accessing and calling these functions from consoles and scripts.

As we moved through the early 2010s, Blender artists would become increasingly aware of the influence Python scripting had on the modeling experience. Certain add-ons would become “must-haves” for artists with interests in certain fields. Developers of other 3D modeling software were jumping on the opportunity to develop exporters to port Blender to their software. Today, Blender has its modularity to thank for its massive talent pool, well-paying career opportunities, and active development community.

The Blender Interface

This chapter discusses and defines components of Blender’s interface. It serves as a reference for vocabulary we use to discuss the interface throughout the text. We will focus on components of the interface most often used in Python development, as well as set up custom interfaces for efficient Python scripting. In an effort to avoid placing large screenshots throughout the book, we strictly define the names of various components in the Blender interface. Component names are introduced here in italics and appear with the first characters capitalized throughout the text.

The Default Blender Interface

When we first open up Blender, we get the familiar default user interface. We have a cube, a camera object, and a lamp object drawn into the scene shown in the 3D Viewport. Figure 1-1 is a simple screenshot of the default Blender interface. Figure 1-2 shows the same interface with various major components labeled. We discuss the function of each of these interfaces.

■ Note We have applied the white-orange theme to our Blender interface for ease of printing. The default Blender theme is dark gray.

1-1. The default Blender interface

Figure 1-2. The components of the Default Blender interface

Figure

3D Viewport

The 3D Viewport, or simply Viewport, gives us a preview of our work product. When we manipulate data in Blender, the 3D Viewport waits for all processes to finish writing data before updating itself. This is not noticeable in simple operations, like translations and rotations, that seem to happen instantaneously and in real time, but it is still important to acknowledge in add-on development.

The 3D Viewport has different viewing options and interaction options. Viewing options include solid, wireframe, and rendered, while interaction options include Object Mode, Edit Mode, and Sculpt Mode.

Header Menu

The Header menu is a fairly standard header for a graphical user interface. It allows us to switch between interface layouts like Default, Animation, and Scripting, as well as switch between rendering engines like Blender Render, Cycles Render, and Blender Game

Properties Window

The Properties window allows us to access properties of objects, scenes, textures, animations, and more. Most interfaces in the Properties window will give summaries and basic attributes rather than display all available details. It is very useful for keeping track of existing objects, object names, applied and unapplied transformations, and a few other important attributes. This window is generally always open in a Blender artist’s layout, so it is a popular location to place add-on functions.

Tool Shelf and Tool Properties

The Tool Shelf is where different classes of operators are grouped by type. If we expand the window, we can see the Tool Shelf has various tabs like Tools, Create, and Relations. Most Blender add-ons will create a new tab in the Tool Shelf to hold its operators and parameters.

The Tool Properties window is a dynamic window that Blender populates with different sets of parameters depending on what tool the user has active. For example, when using the Rotate tool, we can fine-tune the rotation in this window instead of navigating to the exact spot in the Properties window that specifies rotation. Tool Properties are advanced features typically intended to optimize ease-of-use rather than provide distinct functionalities to a tool. Many Blender add-ons ignore them altogether, and only a handful of native Blender tools use them.

Timeline

The Timeline is used in animation. We can ignore this as we will not be animating in this book.

The Scripting Interface

To enter the scripting interface, select the Scripting option in the drop-down menu to the right of the Help button within the Header menu. Throughout the text, we will present instructions like this with bold-faced directives, like: Header Menu ➤ Screen Layout ➤ Scripting. See Figure 1-3 for the location of the menu. The layout of Blender will change to appear like Figure 1-4

1-3. Selecting the Scripting interface

Figure 1-4. The Scripting interface

The Scripting layout, or some variant of it, will be where we do most of our work in Blender. We will discuss new components of the Blender interface introduced in Figure 1-5

Figure

Text Editor

We can edit Python scripts (and any other text files) in the Text Editor. We can click the New and Open buttons to create and open scripts, respectively. Once scripts are loaded, the menu bar at the bottom of the Text Editor will change to allow saving and switching between files. Blender’s Text Editor has some special properties pertaining to imports, system paths, and linked files in Python. We discuss this in detail later in this chapter and in future chapters when developing add-ons.

Command Log

The Command Log shows function calls made by the Blender interface during the session. This window is extremely useful when experimenting with scripts and learning about the API. If, for example, we translate the cube in the 3D Viewport using the red arrow, we get the output shown in Listing 1-1 in the Command Log.

Listing 1-1. Command Log Output from Translation Along x-Axis bpy.ops.transform.translate(value=(3.05332, 0, 0), constraint_axis=(True, False, False), constraint_orientation='GLOBAL', mirror=False, proportional='DISABLED', proportional_edit_falloff='SMOOTH', proportional_size=1, release_confirm=True)

The output in Listing 1-1 shows that we called the translate() function from the transform class of the bpy.ops submodule. The parameters are fairly verbose and often redundant in calls made from the interface, but they are straightforward enough that we can decipher what they mean and experiment with the function. We dig into code like this in the next chapter. While the act of deciphering is often the best and fastest way to learn about functions in Blender Python, we can also reference the official documentation for more detail. This is also discussed in the next chapter.

Figure 1-5. Components of the Scripting interface

Interactive Console

The Interactive Console is a Python 3 environment similar to vanilla Python console and IPython consoles that often appear at the bottom of IDEs (interactive development environments). The Interactive Console does not share local or module-level data with the Text Editor scripts, but both Interactive Console and Text Editor scripts have access to the same global Blender data stored in bpy and its submodules. So, the console will not be able to read or modify variables local to the the scripts, but modifications to bpy (and the Blender session in general) are shared.

To further complicate matters, the console and scripts share linked scripts and system path variables during the Blender session. The relationship between these components may seem needlessly complex, but we will come to see that their relationship is optimal for both development and experimentation.

Customizing the Interface

Components of the Blender interface are modular, detachable, expandable, and all-around customizable. Users can drag around the top-right corner of any window to modify and create new windows.

• Dragging the top-right corner to the left will create a new window of the same type

• Dragging the top-right corner to the right will allow you to overtake adjacent windows

• Holding Shift and dragging the top-right corner in any direction will copy the component in a new detached window

Creating a 3D Viewport in a detachable window and duplicating the Text Editor is great way to use a dual-screen setup. Having two Text Editors available is very helpful for debugging custom modules. See Figure 1-6 for a screenshot of a dual-screen setup.

Note that if your Tool Shelf or Tool Properties windows disappear when moving around the interface, press T on the keyboard while in the 3D Viewport to reveal them. Additionally, press N on the keyboard while in the 3D Viewport to reveal a new window, the Object Properties. This window is used very often in add-on development, specifically when we begin assigning custom Blender classes to our objects as parameters.

Figure 1-6. Example of a dual-screen development interface

Starting Blender from the Command Line (for Debugging)

When developing Python scripts in Blender, it is very important that we start Blender from the command line. When we run scripts in Blender, if we get an error, the Command Log will show this message:

Python script fail, look in the console for now...

This message can be very confusing, because the Interactive Console will show nothing. What Blender means is: Look in the terminal for now… Unfortunately, most people do not open Blender via the terminal, and the error messages and tracebacks will go unnoticed unless we have a terminal running Blender in the background. Opening Blender via the terminal is the unofficial “Debug Mode” for Python developers. Blender has an official Debug Mode used by the core developers, but this is not generally helpful to us as API users.

To open Blender from the terminal, we must navigate to the Blender executable in a Blender distribution saved on our system. Make sure to have downloaded the Blender .zip or .bz2 file for the appropriate operating system from https://www.blender.org/download/. Save and unzip the folder in an easily accessible location. Windows users will open the command prompt, and UNIX users will open a terminal. Listings 1-2 and 1-3 show the commands required to open a Blender install sitting on the Desktop for Windows and UNIX users, respectively. Alternatively, Windows users can open Blender normally, then navigate to Header Menu ➤ Window ➤ Toggle System Console to view the terminal.

Listing 1-2. Opening Blender from the Command Line in Windows

# Assuming you are starting from C:\Users\%USERNAME%

cd Desktop\blender-2.78c-windows64 blender

# Navigating from anywhere on the Windows

# filesystem to Blender on the Desktop

cd C:\Users\%USERNAME%\Desktop\blender-2.78c-windows64 blender

# If an existing Blender install causes

# the wrong version to open, use blender.exe

cd C:\Users\%USERNAME%\Desktop\blender-2.78c-windows64 blender.exe

Listing 1-3. Opening Blender from the Command Line in UNIX

# Navigating to Blender on the Desktop from # anywhere in the filesystem for Linux

cd ~/Desktop/blender-2.78c-linux-glibc211-x86_64 ./blender

# Navigating to Blender in the home directory for OSX

cd ~/Desktop/blender-2.78c-OSX-10.6-x86_64 ./blender

Now Blender is running from the terminal, and it will dump warnings and errors to the terminal. If we exit the terminal, Blender will also close. Developers should always open Blender from the command line to get detailed debugging information. We will generally keep the terminal minimized until we get an error, then maximize it to study the recent output.

Running Our First Python Script

With the information presented in this chapter, we can open a fresh Blender session with the command line, arrange the interface to a nice development layout, and be prepared to debug our Python code. Our first objective will be to create a cube out of cubes. We will walk through the natural thought process of exploring Blender and the API to create a script that accomplishes our objective.

Finding the Function

First, we need to figure out which function adds a cube to the scene. Navigate to the 3D Viewport and go to 3D Viewport Header ➤ Add ➤ Meshes ➤ Cube. Now navigate to the Command Log to verify that the function was executed as shown in Listing 1-4.

Listing 1-4. Command Log Output for Adding a Cube to the Scene bpy.ops.mesh.primitive_cube_add(radius=1, view_align=False, enter_editmode=False, location=(0, 0, 0), layers=(True, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False))

Testing the Function

Upon examination, we see many arguments that we do not need to accomplish our objective. We do not want to enter Edit Mode, we do not need to align the 3D Viewport to the object, and we are working in the first layer for now. We will guess that we do not need the arguments view_align, enter_editmode, and layers, and that their default values are acceptable. Additionally, we will assume that radius specifies the size of the cube, and location specifies the location. To test this, run Listing 1-5 in the Interactive Console.

Listing 1-5. Testing Defaults of primitive_cube_add()

# Make a bigger cube sitting in the first quadrant bpy.ops.mesh.primitive_cube_add(radius=3, location=(5, 5, 5))

By running Listing 1-5 in the Interactive Console, we see no errors, and we see a large cube centered at (5, 5, 5) in the 3D Viewport. We can now confidently use the function in a script to accomplish our objective, making a cube of cubes.

Delete our big cube (and any other stray objects) from the scene in preparation to run our script. Use the A key in the 3D Viewport to toggle Select All and press the X key to be prompted to delete all selected objects.

Writing the Script

Make sure to go to Text Editor ➤ New to create a new script. To create a cube of cubes, we will nest three loops that iterate through our x, y, and z values. Copy Listing 1-6 into the Text Editor and go to Text Editor ➤ Run Script.

Listing 1-6. Creating a Cube of Cubes import bpy

for k in range(5): for j in range(5): for i in range(5): bpy.ops.mesh.primitive_cube_add(radius=0.25, location=(i, j, k))

This script creates a cube 0.25 * 2 = 0.5 units wide, centered at every combination of whole number vertices such that 0 ≤ x, y, z < 5. The result is pictured in Figure 1-7.

■ Note To find functions, classes, parameter lists, and minimal documentation, use the autocomplete feature of Blender’s Interactive Console. With the mouse cursor in the window of the Interactive Console, begin typing a bpy function. press Ctrl+Space, and Blender will show class and function information.

Conclusion

In the coming chapters, we expand on the process used to arrive at Listing 1-6, allowing us to create virtually anything in Blender. Using the vocabulary established in this chapter, we will be able to talk through advanced concepts in Blender Python scripting.

Figure 1-7. Cubes of cubes generated by Listing 1-6

CHAPTER 2

The bpy Module

This chapter introduces and details major components of the bpy module. In doing so, we explain many important behaviors of Blender. We cover selection and activation, creation and deletion, scene management, and code abstraction.

The official documentation for the Blender Python API can be found by selecting a version of Blender at http://www.blender.org/api/. We are using Blender 2.78c in this text, so our documentation can be found at http://www.blender.org/api/blender_python_api_2_78c_release/.

Module Overview

We begin by giving some background on each submodule of bpy.

bpy.ops

As implied, this submodule contains operators. These are primarily functions for manipulating objects, similarly to the way Blender artists manipulate objects in the default interface. The submodule can also manipulate the 3D Viewport, renderings, text, and much more.

For manipulating 3D objects, the two most important classes are bpy.ops.object and bpy.ops.mesh. The object class contains functions for manipulating multiple selected objects at the same time as well as many general utilities. The mesh class contains functions for manipulating vertices, edges, and faces of objects one at a time, typically in Edit Mode.

There are currently 71 classes in the bpy.ops submodule, all fairly well-named and well-organized.

■ Note Documentation for modules, submodules, and classes can be accessed directly by appending the Pythonic path to the object and .html to the home URL of your version’s Blender documentation. For example, documentation for the bpy.ops.mesh class can be found here: www.blender.org/api/blender_python_ api_2_78c_release/bpy.ops.mesh.html

bpy.context

The bpy.context submodule is used to access objects and areas of Blender by various status criteria. The primary function of this submodule is to give Python developers a means of accessing the current data that a user is working with. If we create a button that permutes all of the selected objects, we can allow the user to select the objects of his choice, then permute all objects in bpy.context.select_objects

© Chris Conlan 2017

C. Conlan, The Blender Python API, DOI 10.1007/978-1-4842-2802-9_2

11

We make frequent use of bpy.context.scene when building add-ons, as it is a required input to certain Blender objects. We can also use bpy.context to access the active objects, toggle between Object Mode and Edit Mode, and accept data from a grease pencil.

bpy.data

This submodule is used to access Blender’s internal data. It can be difficult to interpret documentation on this specific module (the */bpy.data.html page points directly to a separate class), but we will rely heavily on it throughout this text. The bpy.data.objects class contains all of the data determining an object’s shape and position. When we say the the previous submodule bpy.context is great for pointing us to groups of objects, we mean that bpy.context classes will generate references to datablocks of the bpy.data class.

bpy.app

This submodule is not entirely documented, but the information we are confident about thus far can be used to great effect in scripting and add-on development. The sub-submodule bpy.app.handlers is the only one we will concern ourselves with in this text. The handlers submodule contains special functions for triggering custom functions in response to events in Blender. Most commonly used is the frame change handle, which executes some function every time the 3D Viewport is updated (i.e., after a frame change).

bpy.types, bpy.utils, and bpy.props

These modules are discussed in detail in later chapters on add-on development. Readers may presently find the documentation in */bpy.types.html useful for describing classes of objects we are utilizing elsewhere.

bpy.path

This submodule is essentially the same as the os.path submodule that ships natively with Python. It is rarely useful to Blender Python developers outside of the core development team.

Selection, Activation, and Specification

The Blender interface was designed to be intuitive while also providing complex functionality. Certain operations logically apply to single objects where others can logically be used on one or many objects at the same time. To handle these scenarios, Blender developers created three ways to access an object and its data.

• Selection: One, many, or zero objects can be selected at once. Operations that use selected objects can perform that operation simultaneously on a single object or many objects.

• Activation: Only a single object can be active at any given time. Operations that work on the active object are typically more specific and drastic, thus cannot be intuitively performed on many things at once.

• Specification: (Python only) Python scripts can access objects by their names and write directly to their datablocks. While an operation that manipulates selected objects is typically a differential action like translate, rotate, or scale, writing data to specific objects is typically a declarative action like position, orientation, or size

Selecting an Object

Before continuing, readers are encouraged to create a handful of different objects in the 3D Viewport to use as examples. Go to 3D Viewport Header ➤ Add to see the object creation menu. When we click around in the 3D Viewport with a right-click, objects highlight and unhighlight. When we hold the Shift key and click around, we are able to highlight multiple objects at once. These highlights in the 3D Viewport represent the selected objects. To list the selected objects, type the code in Listing 2-1 into the Interactive Console.

Listing 2-1. Getting a List of Selected Objects

# Outputs bpy.data.objects datablocks bpy.context.selected_objects

As we alluded to earlier, the bpy.context submodule is great for fetching lists of objects based on their state within Blender. In this case, we fetched all the selected objects.

# Example output of Listing 2.1, list of bpy.data.objects datablocks [bpy.data.objects['Sphere'], bpy.data.objects['Circle'], bpy.data.objects['Cube']]

In this case, a sphere named Sphere, a circle named Circle, and a cube named Cube were all selected in the 3D Viewport. We were returned a Python list of bpy.data.objects datablocks. Given the knowledge that all datablocks of this type have a name value, we can loop through the results of Listing 2-1 to access the names of the selected objects. See Listing 2-2, where we grab both the names and positions of the selected objects.

Listing 2-2. Getting a List of Selected Objects

# Return the names of selected objects [k.name for k in bpy.context.selected_objects]

# Return the locations of selected objects

# (location of origin assuming no pending transformations) [k.location for k in bpy.context.selected_objects]

Now that we know how to manually select objects, we need to automatically select objects based on some criteria. The requisite functions are in bpy.ops. Listing 2-3 creates a function that takes an object name as an argument and selects it, clearing all other selections by default. If the user specifies additive = True, the function will not clear other selections beforehand.

Listing 2-3. Programmatically Selecting Objects import bpy

def mySelector(objName, additive=False):

# By default, clear other selections if not additive: bpy.ops.object.select_all(action='DESELECT')

# Set the 'select' property of the datablock to True bpy.data.objects[objName].select = True

Another random document with no related content on Scribd:

Power of mind over body.

Sublime is the dominion of the mind over the body, that, for a time, can make flesh and nerve impregnable, and string the sinews like steel, so that the weak become so mighty.

True heroism.

Have not many of us, in the weary way of life, felt, in some hours, how far easier it were to die than to live?

The martyr, when faced even by a death of bodily anguish and horror, finds in the very terror of his doom a strong stimulant and tonic. There is a vivid excitement, a thrill and fervor, which may carry through any crisis of suffering that is the birth-hour of eternal glory and rest.

But to live,—to wear on, day after day, of mean, bitter, low, harassing servitude, every nerve dampened and depressed, every power of feeling gradually smothered,—this long and wasting heart martyrdom, this slow, daily bleeding away of the inward life, drop by drop, hour after hour,—this is the true searching test of what there may be in man or woman.

Moral atmosphere.

An atmosphere of sympathetic influence encircles every human being; and the man or woman who feels strongly, healthily, and justly, on the great interests of humanity, is a constant benefactor to the human race.

Self-sacrifice.

There are in this world blessed souls, whose sorrows all spring up into joys for others; whose earthly hopes, laid in the grave with many tears, are the seed from which spring healing flowers and balm for the desolate and the distressed.

Strength of despair

When a heavy weight presses the soul to the lowest level at which endurance is possible, there is an instant and desperate effort of every physical and moral nerve

to throw off the weight; and hence the heaviest anguish often precedes a return tide of joy and courage.

Selfforgetfulness. Natural religious sensibility.

“Thee uses thyself only to learn how to love neighbor, Ruth,” said Simeon, looking with a beaming face on Ruth. He had one of those natures which could better and more clearly conceive of religious things from its own perceptions and instincts than many a matter-of-fact and practical Christian. The gift to appreciate and the sense to feel the finer shades and relations of moral things often seems an attribute of those whose whole life shows a careless disregard of them. Hence, Moore, Byron, Goethe, often speak words more wisely descriptive of the true religious sentiment, than another man whose whole life is governed by it. In such minds, disregard of religion is a more fearful treason,—a more deadly sin.

Superstition.

No one is so thoroughly superstitious as the godless man. The Christian is composed by the belief of a wise, all-ruling Father, whose presence fills the void unknown with light and order; but to the man who has dethroned God, the spirit-land is, indeed, in the words of the Hebrew poet, “a land of darkness and the shadow of death,” without any order, where the light is as darkness. Life and death to him are haunted grounds, filled with goblin forms of vague and shadowy dread.

The human soul.

After all, let a man take what pains he may to hush it down, a human soul is an awful ghostly, unquiet possession for a bad man to have. Who knows the metes and bounds of it? Who knows all its awful perhapses,—those shudderings and tremblings which it can no more live down than it can outlive its own eternity! What a fool is he who locks his door to

keep out spirits, who has in his own bosom a spirit he dares not meet alone,—whose voice, smothered far down, and piled over with mountains of earthliness, is yet like the forewarning trumpet of doom! DRED.

Practical and ideal.

The divine part of man is often shame-faced and selfdistrustful, ill at home in this world, and standing in awe of nothing so much as what is called common sense; and yet common sense very often, by its own keenness, is able to see that these unavailable currencies of another’s mind are of more worth, if the world only knew it, than the ready coin of its own; and so the practical and the ideal nature are drawn together.

Inexplicable preferences.

Sensitive people never like the fatigue of justifying their instincts. Nothing, in fact, is less capable of being justified by technical reasons than those fine insights into character whereupon affection is built. We have all had experience of preferences which would not follow the most exactly ascertained catalogue of virtues, and would be made captive where there was very little to be said in justification of the captivity.

Congeniality of opposites.

“Why, surely,” said Anne, “one wants one’s friends to be congenial, I should think.”

“So we do; and there is nothing in the world so congenial as differences. To be sure, the differences must be harmonious. In music, now, for instance, one doesn’t want a repetition of the same notes, but differing notes that chord. Nay, even discords are indispensable to complete harmony. Now, Nina has just that difference from me which chords with me; and all our little quarrels— for we have had a good many, and I dare say shall have more—are only a sort of chromatic passages,—discords of the seventh, leading into harmony. My life is inward, theorizing, self-absorbed. I am

hypochondriac, often morbid. The vivacity and acuteness of her outer life makes her just what I need. She wakens, she rouses, and keeps me in play; and her quick instincts are often more than a match for my reason.”

Proof of heaven.

“How do you know there is any heaven, anyhow?”

“Know it?” said Milly, her eyes kindling, and striking her staff on the ground, “Know it? I know it by de hankering arter it I got in here;” giving her broad chest a blow which made it resound like a barrel. “De Lord knowed what he was ’bout when he made us. When he made babies rootin’ ’round, wid der poor little mouths open, he made milk, and de mammies for ’em too. Chile, we’s nothing but great babies, dat ain’t got our eyes open,—rootin’ ’round an’ ’round; but de Father ’ll feed us yet—He will so.”

Power of song.

As oil will find its way into crevices where water cannot penetrate, so song will find its way where speech can no longer enter.

Night resolutions.

What we have thought and said under the august presence of witnessing stars, or beneath the holy shadows of moonlight, seems with the dry, hot heat of next day’s sun to take wings, and rise to heaven with the night’s clear drops. If all the prayers and good resolutions which are laid down on sleeping pillows could be found there on awaking, the world would be better than it is.

Transition periods.

There are times in life when the soul, like a half-grown climbing vine, hangs hovering tremulously, stretching out its tendrils for something to ascend by. Such are generally the great transition periods of life, when we are passing from the ideas and conditions of one stage of existence to those of

another Such times are most favorable for the presentation of the higher truths of religion.

Connection with the spirit world.

This life may truly be called a haunted house, built as it is on the very confines of the land of darkness and the shadow of death. A thousand living fibres connect us with the unknown and unseen state; and the strongest hearts, which never stand still for any mortal terror, have sometimes hushed their very beating at a breath of a whisper from within the veil. Perhaps the most resolute unbeliever in spiritual things has hours of which he would be ashamed to tell, when he, too, yields to the powers of those awful affinities which bind us to that unknown realm.

Suffering in silence.

It is the last triumph of affection and magnanimity, when a loving heart can respect the suffering silence of its beloved, and allow that lonely liberty in which only some natures can find comfort.

Joy in endurance.

And, as he sang and prayed, that strange joy arose within him, which, like the sweetness of night flowers, is born of darkness and tribulation. The soul has in it somewhat of the divine, in that it can have joy in endurance beyond the joy of indulgence.

They mistake who suppose that the highest happiness lies in wishes accomplished—in prosperity, wealth, favor, and success. There has been a joy in dungeons and on racks passing the joy of harvest. A joy strange and solemn, mysterious even to its possessor. A white stone dropped from that signet ring, peace, which a dying Saviour took from his own bosom, and bequeathed to those who endure the cross, despising the shame.

Inward peace.

How natural it is to say of some place sheltered, simple, cool, and retired, here one might find peace, as if peace came from without, and not from within. In the shadiest and stillest places may be the most turbulent hearts, and there are hearts which, through the busiest scenes, carry with them unchanging peace.

Grace in affliction.

I have read of Alpine flowers leaning their cheeks on the snow. I wonder if any flowers grow near enough to that snow to touch it. I mean to go and see. So I went; there, sure enough, my little fringed purple bell, to which I had give the name of “suspirium,” was growing, not only close to the snow but in it.

Thus God’s grace, shining steadily on the waste places of the human heart, brings up heavenward sighings and aspirations, which pierce through the cold snows of affliction, and tell that there is yet life beneath.

God as an artist.

I was glad to walk on alone: for the scenery was so wonderful that human sympathy and communion seemed to be out of the question. The effect of such scenery to our generally sleeping and drowsy souls, bound with a double chain of earthliness and sin, is like the electric touch of the angel on Peter, bound and sleeping. They make us realize that we were not only made to commune with God, but also what a God He is with whom we may commune. We talk of poetry, we talk of painting, we go to the ends of the earth to see the artists and great men of this world; but what a poet, what an artist, is God! Truly said Michel Angelo, “The true painting is only a copy of the divine perfections—a shadow of his pencil.”

Soul-striving.

The human soul seems to me an imprisoned essence, striving after somewhat divine. There is strength in it, as of suffocated flame, finding vent now through poetry, now in

painting, now in music, sculpture, or architecture; various are the crevices and fissures, but the flame is one.

What a curious kind of thing shadow is,—that invisible veil, falling so evenly and so lightly over all things, bringing with it such thoughts of calmness and rest. I wonder the old Greeks did not build temples to Shadow, and call her the sister of Thought and Peace. The Hebrew writers speak of the “overshadowing of the Almighty;” they call his protection “the shadow of a great rock in a weary land.” Even as the shadow of Mont Blanc falls like a Sabbath across this valley, so falls the sense of his presence across our weary life-road.

Heimweh.

Why? why this veil of dim and indefinable anguish at sight of whatever is most fair, at hearing whatever is most lovely? Is it the exiled spirit, yearning for its own? Is it the captive, to whom the ray of heaven’s own glory comes through the crevice of his dungeon wall?

Seeing and feeling.

It is not enough to open one’s eyes on scenes; one must be able to be “en rapport” with them. Just so in the spiritual world, we sometimes see great truths,— see that God is beautiful and surpassingly lovely; but at other times we feel both nature and God, and O, how different seeing and feeling!

POGANUC PEOPLE.

Longing for love in the unlovely

There are hard, sinful, unlovely souls, who yet long to be loved, who sigh in their dark prison for that tenderness, that devotion, of which they are consciously unworthy. Love might redeem them; but who can love them? There is a fable of a prince, doomed by a cruel enchanter to

wear a loathsome, bestial form, till some fair woman should redeem him by the transforming kiss of love. The fable is a parable of the experience of many a lost human soul....

Who can read the awful mysteries of a single soul? We see human beings, hard, harsh, earthly, and apparently without an aspiration for anything high and holy; but let us never say that there is not far down in the depths of any soul a smothered aspiration, a dumb, repressed desire to be something higher and purer, to attain the perfectness to which God calls it.

LITTLE PUSSY WILLOW.

Seeing the bright side.

“She shall be called little Pussy Willow, and I shall give her the gift of always seeing the bright side of everything. That gift will be more to her than beauty or riches or honors. It is not so much matter what color one’s eyes are as what one sees with them. There is a bright side to everything, if people only knew it, and the best eyes are those which are always able to see this bright side.”

A DOG’S MISSION.

Reaction of harshness.

A conscientious person should beware of getting into a passion, for every sharp word one speaks comes back and lodges like a sliver in one’s own heart; and such slivers hurt us worse than they ever can any one else.

Man’s childish impatience.

Ah, the child is father of the man! when he gets older he will have the great toys of which these are emblems; he will believe in what he sees and touches,—in house, land, railroad stock,—he will believe in these earnestly and really, and in his eternal manhood nominally and partially. And when his father’s messengers meet him, and face him about, and take him off

his darling pursuits, and sweep his big ships into the fire, and crush his full-grown cars, then the grown man will complain and murmur, and wonder as the little man does now. The Father wants the future, the Child the present, all through life, till death makes the child a man.

MY WIFE AND I.

Discipline of patience.

Ennobling power of sorrow.

The moral discipline of bearing with evil patiently is a great deal better and more ennobling than the most vigorous assertion of one’s personal rights.

When we look at the apparent recklessness with which great sorrows seem to be distributed among the children of the earth, there is no way to keep our faith in a Fatherly love, except to recognize how invariably the sorrows that spring from love are a means of enlarging and dignifying a human being. Nothing great or good comes without birth-pangs, and in just the proportion that natures grow more noble their capacities of suffering increase.

Line between right and wrong.

The line between right and wrong seems always so indefinite, like the line between any two colors of the prism; it is hard to say just where one ends and another begins.

Doubt.

“Doubt is very well as a sort of constitutional crisis in the beginning of one’s life; but if it runs on and gets to be chronic it breaks a fellow up, and makes him morally spindling and sickly. Men that do anything in the world must be men of strong convictions; it won’t do to go through life like a hen, craw-crawing and lifting up one foot, not knowing where to set it down next.”

“I don’t think,” said she, “you should say ‘ make’ friends,—friends are discovered, rather than made. There are people who are in their own nature friends, only they don’t know each other; but certain things, like poetry, music, and painting, are like the free-masons’ signs,—they reveal the initiated to each other.”

Friends. Forgiveness of friends.

WE AND OUR NEIGHBORS.

“Yes,” said Harry, “forgiveness of enemies used to be the ultima thule of virtue; but I rather think it will have to be forgiveness of friends. I call the man a perfect Christian that can always forgive his friends.”

Do not our failures and mistakes often come from discouragement? Does not every human being need a believing second self, whose support and approbation shall reinforce one’s failing courage? The saddest hours of life are when we doubt ourselves. To sensitive, excitable people, who expend nervous energy freely, must come many such low tides. “Am I really a miserable failure,—a poor, good-for-nothing, abortive attempt?” In such crises we need another self to restore our equilibrium.

Altruism. Reproach.

The agony of his self-reproach and despair had been doubled by the reproaches and expostulations of many of his own family friends, who poured upon bare nerves the nitric acid of reproach.

Help from work.

Something definite to do is, in some crises, a far better medicine for a sick soul than any amount of meditation and prayer. One step fairly taken in a right direction goes farther than any amount of agonized back-looking.

Praise and blame.

God working through man.

Praise is sunshine; it warms, it inspires, it promotes growth: blame and rebuke are rain and hail; they beat down and bedraggle, even though they may at times be necessary. The invisible Christ must be made known through human eyes; He must speak though a voice of earthly love, and a human hand inspired by his spirit must be reached forth to save.

Inner life.

The external life is positive, visible, definable; easily made the subject of conversation. The inner life is shy, retiring, most difficult to be expressed in words, often inexplicable, even to the subject of it, yet no less a positive reality than the outward.

RELIGIOUS POEMS.

Peace through suffering.

The spirit within.

For not alone in those old Eastern regions Are Christ’s beloved ones tried by cross and chain; In many a house are his elect ones hidden, His martyrs suffering in their patient pain. The rack, the cross, life’s weary wrench of woe, The world sees not, as slow, from day to day, In calm, unspoken patience, sadly still, The loving spirit bleeds itself away; But there are hours, when from the heavens unfolding Come down the angels with the glad release, And we look upward, to behold in glory Our suffering loved ones borne away to peace.

As some rare perfume in a vase of clay Pervades it with a fragrance not its own,

So, when Thou dwellest in a mortal soul, All heaven’s own sweetness seems around it thrown.

The calm of God’s love.

When winds are raging o’er the upper ocean, And billows wild contend with angry roar, ’Tis said, far down beneath the wild commotion, That peaceful stillness reigneth evermore. Far, far beneath, the noise of tempest dieth, And silver waves chime ever peacefully; And no rude storm, how fierce soe’er he flieth, Disturbs the Sabbath of that deeper sea.

So to the soul that knows thy love, O Purest, There is a temple peaceful evermore! And all the babble of life’s angry voices Die in hushed stillness at its sacred door.

God’s comfort.

Think not, when the wailing winds of autumn Drive the shivering leaflets from the trees,—

Think not all is over: spring returneth; Buds and leaves and blossoms thou shalt see. Think not, when thy heart is waste and dreary, When thy cherished hopes lie chill and sere,— Think not all is over: God still loveth; He will wipe away thy every tear.

Ignorant selfishness.

CHAPTER II.

HUMAN NATURE.

THE MINISTER’S WOOING.

He was one of that class of people who, of a freezing day, will plant themselves directly between you and the fire, and then stand and argue to prove that selfishness is the root of all moral evil. Simeon said he always had thought so; and his neighbors sometimes supposed that nobody could enjoy better experimental advantages for understanding the subject. He was one of those men who suppose themselves submissive to the divine will, to the uttermost extent demanded by the extreme theology of that day, simply because they have no nerves to feel, no imagination to conceive, what endless happiness or suffering is, and who deal therefore with the great question of the salvation or damnation of myriads as a problem of theological algebra, to be worked out by their inevitable x, y, z.

Sensitiveness to blame.

Depression after

A generous, upright nature is always more sensitive to blame than another,—sensitive in proportion to the amount of its reverence for good.

It is a hard condition of our existence that every exaltation must have its depression. God will not let us

exaltation.

have heaven here below, but only such glimpses and faint showings as parents sometimes give to children, when they show them beforehand the jewelry and pictures and stores of rare and curious treasures which they hold for the possession of their riper years. So it very often happens that the man who has gone to bed an angel, feeling as if all sin were forever vanquished, and he himself immutably grounded in love, may wake the next morning with a sick-headache, and, if he be not careful, may scold about his breakfast like a miserable sinner.

French nature.

True Frenchwoman as she was, always in one rainbow shimmer of fancy and feeling, like one of those cloudspotted April days, which give you flowers and rain, sun and shadow, and snatches of bird-singing, all at once.

Simple honesty vs. worldliness.

He is one of those great, honest fellows, without the smallest notion of the world we live in, who think, in dealing with men, that you must go to work and prove the right or the wrong of a matter; just as if anybody cared for that! Supposing he is right,—which appears very probable to me,—what is he going to do about it? No moral argument, since the world began, ever prevailed over twenty-five per cent. profit.

Duty vs. expediency.

“Madam,” said the doctor, “I’d sooner my system should be sunk in the sea than that it should be a millstone round my neck to keep me from my duty. Let God take care of my theology; I must do my duty.”

Joy of living.

There are some people so evidently broadly and heartily of this world that their coming into a room always materializes the conversation. We wish to be understood that we mean no disparaging reflection on such persons; they are as necessary to make up a world as cabbages to make up a garden;

the great, healthy principles of cheerfulness and animal life seem to exist in them in the gross; they are wedges and ingots of solid, contented vitality.

A boy’s growth.

“Oh, you go ’long, Massa Marvin; ye’ll live to count dat ar’ boy for de staff o’ yer old age yit, now I tell ye; got de makin’ o’ ten or’nary men in him; kittles dat’s full allers will bile over; good yeast will blow at de cork,—lucky ef it don’t bust de bottle. Tell ye, der’s angels hes der hooks in sich, an’ when de Lord wants him, dey’ll haul him in safe an’ sound.”

Will-power

The world’s injustice.

“Law me! what’s de use? I’se set out to b’liebe de Catechize, an’ I’se gwine to b’liebe it, so!”

“But, Marie, how unjust is the world! how unjust both in praise and blame.”

OLDTOWN FOLKS.

Selfish love.

These dear, good souls who wear their life out for you, have they not a right to scold you, and dictate to you, and tie up your liberty, and make your life a burden to you? If they have not, who has? If you complain, you break their worthy old hearts. They insist on the privilege of seeking your happiness by thwarting you in everything you want to do, and putting their will instead of yours in every step of your life.

Expressive silence.

Aunt Lois, as I have often said before, was a good Christian, and held it her duty to govern her tongue. True, she said many sharp and bitter things; but nobody but herself and her God knew how many more she would have said had she not reined herself up in conscientious silence. But

never was there a woman whose silence could express more contempt and displeasure than hers. You could feel it in the air about you, though she never said a word. You could feel it in the rustle of her dress, in the tap of her heels over the floor, in the occasional flash of her sharp black eye. She was like a thunder-cloud, whose quiet is portentous, and from which you every moment expect a flash or an explosion.

Power of a tone. Making the best of it.

That kind of tone which sounds so much like a blow that one dodges one’s head involuntarily.

“There’s no use in such talk, Lois: what’s done’s done; and if the Lord let it be done, we may. We can’t always make people do as we would. There’s no use in being dragged through the world like a dog under a cart, hanging back and yelping. What we must do, we may as well do willingly,—as well walk as be dragged.”

Influence of heredity and association.

It is strange that no human being grows up who does not so intertwist in his growth the whole idea and spirit of his day, that rightly to dissect out his history would require one to cut to pieces and analyze society, law, religion, the metaphysics, and the morals of his time; and, as all things run back to those of past days, the problem is still further complicated. The humblest human being is the sum total of a column of figures which go back through centuries before he was born.

Personal magnetism.

Supposing a man is made like an organ, with two or three banks of keys, and ever so many stops, so that he can play all sorts of tunes on himself; is it being a hypocrite with each person to play precisely the tune, and draw out exactly the stop, which he knows will make himself agreeable and further his purpose?

Physical good humor

That charming gift of physical good humor, which is often praised as a virtue in children and in grown people, but which is a mere condition of the animal nature.

SAM LAWSON’S STORIES.

Effect of sinning.

Scepticism.

“Ye know sinnin’ will always make a man leave prayin’.”

“You look at the folks that’s allers tellin’ you what they don’t believe,—they don’t believe this, an’ they don’t believe that,—an’ what sort o’ folks is they? Why, like yer Aunt Lois, sort o’ stringy an’ dry. There ain’t no ’sorption got out o’ not believin’ nothin’.”

Life.

“That ’are’s jest the way folks go all their lives, boys. It’s all fuss, fuss, and stew, stew, till ye get somewhere; an’ then it’s fuss, fuss, an’ stew, stew, to get back again; jump here an’ scratch your eyes out, an’ jump there an’ scratch ’em in again,—that ’are’s life.”

PEARL OF ORR’S ISLAND.

Life as a play

There are those people who possess a peculiar faculty of mingling in the affairs of this life as spectators as well as actors. It does not, of course, suppose any coldness of nature or want of human interest or sympathy,—nay, it often exists more completely with people of the tenderest human feeling. It rather seems to be a kind of distinct faculty working harmoniously with all the others; but he who possesses it needs never to be at a loss for interest or amusement; he is always a spectator at a tragedy or a

comedy, and sees in real life a humor and a pathos beyond anything he can find shadowed in books.

A childlike nature.

Mrs. Pennel had one of those natures, gentle, trustful, and hopeful, because not very deep; she was one of the little children of the world, whose faith rests on childlike ignorance, and who know not the deeper needs of deeper natures; such see only the sunshine, and forget the storm.

Unintended hurts.

All that there was developed of him, at present, was a fund of energy, self-esteem, hope, courage, and daring, the love of action, life, and adventure; his life was in the outward and present, not in the inward and reflective; he was a true ten-year-old boy, in its healthiest and most animal perfection. What she was, the small pearl with the golden hair, with her frail and highstrung organization, her sensitive nerves, her half-spiritual fibres, her ponderings, and marvels, and dreams, her power of love and yearning for self-devotion, our reader may, perhaps, have seen. But if ever two children, or two grown people, thus organized, are thrown into intimate relations, it follows, from the very laws of their being, that one must hurt the other, simply by being itself; one must always hunger for what the other has not to give.

Real love.

“I always thought that my wife must be one of the sort of women who pray.”

“And why?” said Mara, in surprise.

“Because I need to be loved a great deal, and it is only that kind who pray who know how to love really.”

LITTLE FOXES.

Difficulty of selfknowledge.

It is astonishing how much we think about ourselves, yet to how little purpose; how very clever people will talk and wonder about themselves and each other, not knowing how to use either themselves or each other,—not having as much practical philosophy in the matter of their own character and that of their friends as they have in respect to the screws of their gas-fixtures or the management of their water-pipes.

Reserve not understood.

There are in every family circle individuals whom a certain sensitiveness of nature inclines to quietness and reserve; and there are very well-meaning families where no such quietness and reserve is possible. Nobody can be let alone, nobody may have a secret, nobody can move in any direction, without a host of inquiries and comments: “Who is your letter from? Let’s see.”—“My letter is from So-and-so.”—“He writing to you! I didn’t know that. What’s he writing about?”—“Where did you go yesterday? What did you buy? What did you give for it? What are you going to do with it?”—“Seems to me that’s an odd way to do. I shouldn’t do so.”—“Look here, Mary; Sarah’s going to have a dress of silk tissue this spring. Now I think they’re too dear, don’t you?”

I recollect seeing in some author a description of a true gentleman, in which, among other things, he was characterized as the man that asks the fewest questions. This trait of refined society might be adopted into home-life in a far greater degree than it is, and make it far more agreeable.

If there is perfect unreserve and mutual confidence, let it show itself in free communications coming unsolicited. It may fairly be presumed that, if there is anything our intimate friends wish us to know, they will tell us of it, and that when we are in close and confidential terms with persons, and there are topics on which they do not speak to us, it is because for some reason they prefer to keep silence concerning them; and the delicacy that respects a friend’s silence is one of the charms of life.

Shyness of love.

It comes far easier to scold our friend in an angry moment than to say how much we love, honor, and esteem him in a kindly mood. Wrath and bitterness speak themselves and go with their own force; love is shame-faced, looks shyly out of the window, lingers long at the door-latch.

Throwing away happiness.

For the contentions that loosen the very foundations of love, that crumble away all its fine traceries and carved work, about what miserable, worthless things do they commonly begin! A dinner underdone, too much oil consumed, a newspaper torn, a waste of coal or soap, a dish broken!—and for this miserable sort of trash, very good, very generous, very religious people will sometimes waste and throw away by double-handfuls the very thing for which houses are built and all the paraphernalia of a home established,— their happiness. Better cold coffee, smoky tea, burnt meat, better any inconvenience, any loss, than a loss of love; and nothing so surely turns away love as constant fault-finding.

Morbid feelings.

There is fretfulness, a mizzling, drizzling rain of discomforting remark; there is grumbling, a northeast snowstorm that never clears; there is scolding, the thunder-storm with lightning and hail. All these are worse than useless; they are positive sins, by whomsoever indulged,—sins as great and real as many that are shuddered at in polite society. All these are for the most part but the venting on our fellow-beings of morbid feelings resulting from dyspepsia, over-taxed nerves, or general ill-health.

HOUSE AND HOME PAPERS.

Love of a bargain.

Milton says that the love of fame is the last infirmity of noble minds. I think he had not rightly considered the subject. I believe that last infirmity is the love of getting things cheap! Understand me, now. I don’t mean the love of getting

Turn static files into dynamic content formats.

Create a flipbook
Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.