Statistics
10
Views
0
Downloads
0
Donations
Support
Share
Uploader

高宏飞

Shared on 2026-01-10

AuthorJim Parker

An Artist's Guide to Programming teaches computer programming with the aid of 100 example programs, each of which integrates graphical or sound output. The Processing-language-based examples range from drawing a circle and animating bouncing balls to 3D graphics, audio visualization, and interactive games. Readers learn core programming concepts like conditions, loops, arrays, strings and functions, as well as how to use Processing to draw lines, shapes, and 3D objects. They’ll learn key computer graphics concepts like manipulating images, animating text, mapping textures onto objects, and working with video. Advanced examples include sound effects and audio visualization, network communication, 3D geometry and animation, simulations of snow and smoke, predator-prey populations, and interactive games.

Tags
No tags
ISBN: 1098130227
Publisher: No Starch Press
Publish Year: 2022
Language: 英文
Pages: 463
File Format: PDF
File Size: 9.5 MB
Support Statistics
¥.00 · 0times
Text Preview (First 20 pages)
Registered users can read the full content for free

Register as a Gaohf Library member to read the complete e-book online for free and enjoy a better reading experience.

(This page has no text content)
CONTENTS IN DETAIL TITLE PAGE COPYRIGHT ABOUT THE AUTHOR AUTHOR’S NOTE INTRODUCTION The Basics of a Programming Language: Processing The Beginning The Middle The Rest Variables How to Write a Program PART 1: THE FUNDAMENTALS OF DRAWING Sketch 1: A Circle Example A Example B Example C Sketch 2: Colors Example A Example B Sketch 3: if Statements—Changing Colors Conditionally
Example A Example B Example C Sketch 4: Loops—Drawing 20 Circles Example A Example B Sketch 5: Lines Example A Example B Sketch 6: Arrays—Drawing Many Circles Sketch 7: Lines with Rubber Banding Sketch 8: Random Circles Sketch 9: A Rectangle Sketch 10: Triangles and Motion Sketch 11: Displaying Text Sketch 12: Manipulating Text Strings PART 2: WORKING WITH PREEXISTING IMAGES Sketch 13: Loading and Displaying an Image Example A Example B Sketch 14: Images—Theory and Practice Example A Example B Sketch 15: Manipulating Images I—Aspect Ratio Example A Example B Sketch 16: Manipulating Images II—Cropping
Sketch 17: Manipulating Images III—Magnifier Sketch 18: Rotation Example A Example B Sketch 19: Rotating About Any Point—Translation Example A Example B Sketch 20: Rotating an Image Sketch 21: Getting the Value of a Pixel Sketch 22: Setting and Changing the Values of Pixels Example A Example B Sketch 23: Changing the Values of Pixels—Thresholding Sketch 24: User-Defined Functions Sketch 25: Elements of Programming Style Sketch 26: Duplicating Images—More Functions PART 3: 2D GRAPHICS AND ANIMATION Sketch 27: Saving an Image and Adjusting Transparency Sketch 28: Bouncing an Object in a Window Sketch 29: Basic Sprite Graphics Sketch 30: Detecting Sprite-Sprite Collisions Sketch 31: Animation—Generating TV Static Sketch 32: Frame Animation Example A Example B Sketch 33: Flood Fill—Filling in Complex Shapes PART 4: WORKING WITH TEXT AND FILES
Sketch 34: Fonts, Sizes, Character Properties Sketch 35: Scrolling Text Sketch 36: Text Animation Sketch 37: Inputting a Filename Sketch 38: Inputting an Integer Sketch 39: Reading Parameters from a File Sketch 40: Writing Text to a File Sketch 41: Simulating Text on a Computer Screen PART 5: CREATING USER INTERFACES AND WIDGETS Sketch 42: A Button Sketch 43: The Class Object—Multiple Buttons Sketch 44: A Slider Sketch 45: A Gauge Display Sketch 46: A Likert Scale Sketch 47: A Thermometer PART 6: NETWORK COMMUNICATIONS Sketch 48: Opening a Web Page Example A Example B Sketch 49: Loading Images from a Web Page Sketch 50: Client/Server Communication PART 7: 3D GRAPHICS AND ANIMATION Sketch 51: Basic 3D Objects Example A Example B Sketch 52: 3D Geometry—Viewpoints, Projections Sketch 53: 3D Illumination
Sketch 54: Bouncing a Ball in 3D Sketch 55: Constructing 3D Objects Using Planes Sketch 56: Texture Mapping Sketch 57: Billboards—Simulating a Tree Sketch 58: Moving the Viewpoint in 3D Sketch 59: Spotlights Sketch 60: A Driving Simulation PART 8: ADVANCED GRAPHICS AND ANIMATION Sketch 61: Layering Sketch 62: Seeing the World Through a Window Sketch 63: The PShape Object—A Rotating Planet Sketch 64: Splines—Drawing Curves Sketch 65: A Driving Simulation with Waypoints Sketch 66: Many Small Objects—A Snowstorm Sketch 67: Particle Graphics—Smoke Sketch 68: Saving a State—A Spinning Propeller Sketch 69: L-Systems—Drawing Plants Sketch 70: Warping an Image PART 9: WORKING WITH SOUND Sketch 71: Playing a Sound File Sketch 72: Displaying a Sound’s Volume Sketch 73: Bouncing a Ball with Sound Effects Sketch 74: Mixing Two Sounds Sketch 75: Displaying Audio Waveforms Sketch 76: Controlling a Graphic with Sound Sketch 77: Positional Sound Sketch 78: Synthetic Sounds Sketch 79: Recording and Saving Sound
PART 10: WORKING WITH VIDEO Sketch 80: Playing a Video Sketch 81: Playing a Video with a Jog Wheel Sketch 82: Saving Still Frames from a Video Sketch 83: Processing Video in Real Time Sketch 84: Capturing Video from a Webcam Sketch 85: Mapping Live Video as a Texture PART 11: MEASURING AND SIMULATING TIME Sketch 86: Displaying a Clock Sketch 87: Time Differences—Measuring Reaction Time Sketch 88: M/M/1 Queue—Time in Simulations PART 12: CREATING SIMULATIONS AND GAMES Sketch 89: Predator-Prey Simulation Sketch 90: Flocking Behavior Sketch 91: Simulating the Aurora Sketch 92: A Dynamic Advertisement Sketch 93: Nim Sketch 94: Pathfinding Sketch 95: Metaballs—A Lava Lamp Sketch 96: A Robot Arm Sketch 97: Lightning Sketch 98: The Computer Game Breakout Sketch 99: Midpoint Displacement—Simulating Terrain PART 13: MAKING YOUR WORK PUBLIC Sketch 100: Processing on the Web
AN ARTIST’S GUIDE TO PROGRAMMING A Graphical Introduction Jim Parker
An Artist’s Guide to Programming. Copyright © 2022 by Jim Parker. All rights reserved. No part of this work may be reproduced or transmitted in any form or by any means, electronic or mechanical, including photocopying, recording, or by any information storage or retrieval system, without the prior written permission of the copyright owner and the publisher. First printing 25 24 23 22 1 2 3 4 5 6 7 8 9 ISBN-13: 978-1-7185-0164-5 (print) ISBN-13: 978-1-7185-0165-2 (ebook) Publisher: William Pollock Production Manager: Rachel Monaghan Production Editor: Paula Williamson Developmental Editors: Athabasca Witschi and Nathan Heidelberger Cover Illustration: Gina Redman Interior Design: Octopod Studios Technical Reviewer: Jeffrey Boyd Copyeditor: Andy Carroll Compositor: Jeff Lytle, Happenstance Type-O-Rama Proofreader: Emelie Battaglia The following images are reproduced with permission: Figure 96-1 by Brocken Inaglory, printed under the GNU Free Documentation License, Version 1.2. For information on distribution, bulk sales, corporate sales, or translations, please contact No Starch Press, Inc. directly at info@nostarch.com or: No Starch Press, Inc. 245 8th Street, San Francisco, CA 94103 phone: 1-415-863-9900 www.nostarch.com Library of Congress Cataloging-in-Publication Data Names: Parker, J. R. (Jim R.), 1955- author. Title: An artist’s guide to programming : a graphical introduction / Jim Parker. Description: San Francisco : No Starch Press, 2022. | Includes index. | Identifiers: LCCN 2021046087 (print) | LCCN 2021046088 (ebook) | ISBN 9781718501645 (print) | ISBN 9781718501652 (ebook) Subjects: LCSH: Multimedia systems. | Computer graphics. | Microcomputers--Programming. | Processing (Computer program language) | Java (Computer program language) Classification: LCC QA76.575 .P357 2022 (print) | LCC QA76.575 (ebook) | DDC 006.7--dc23 LC record available at https://lccn.loc.gov/2021046087 LC ebook record available at https://lccn.loc.gov/2021046088 No Starch Press and the No Starch Press logo are registered trademarks of No Starch Press, Inc. Other product and company names mentioned herein may be the trademarks of their respective owners. Rather than use a trademark symbol with every occurrence of a trademarked name, we are using the names only in an editorial fashion and to the benefit of the trademark owner, with no intention of infringement of the trademark. The information in this book is distributed on an “As Is” basis, without warranty. While every precaution has been taken in the preparation of this work, neither the author nor No Starch Press, Inc.
shall have any liability to any person or entity with respect to any loss or damage caused or alleged to be caused directly or indirectly by the information contained in it.
About the Author Jim Parker is a professor, author, and artist who has published a dozen books and over 170 technical papers, in addition to writing short stories. He has degrees in mathematics and computer science, and a PhD from the State University of Ghent, Belgium. His areas of expertise include computer simulation, image processing, artificial intelligence, game design, and generative art. He has exhibited generative art, and even sent art into space. He lives on a small ranch in the foothills of the Rocky Mountains, where he helps raise small animals and Tennessee walking horses. About the Technical Reviewer Jeffrey Boyd received his PhD in computer science from the University of British Columbia and is currently an associate professor at the University of Calgary. His research focuses on sensing and computer vision, with applications in analyzing human motion, interactive art and music, sonification, and computational musicology. Dr. Boyd and his students do diverse work that includes wearable systems that provide real-time, sonic feedback to train and rehabilitate speed skaters; numerous art and sound installations; and the musicological study of contemporary composers through the analysis of ambisonic recordings of their work.
AUTHOR’S NOTE Processing is a programming language designed by Casey Reas and Ben Fry to be used by artists creating generative art. It is based on Java, and it extends Java in many useful ways: it allows the programmer to easily read, display, and write image files; it has functions for drawing elementary shapes and curves; it makes manipulating colors simple; and so on. Most importantly, it opens a window into which the programmer/artist will draw. All Processing programs are intended to create an image, a visual output. This book presents the Processing language and its many applications in a set of graduated examples. The details of the syntax are not the focus, although they are explained briefly. The idea is to present a collection of programs that the reader can experiment with. When the book is open to any sketch, the left side of the page will have descriptive text, while the right will show the program and the result, as an image.
The code is available to you. Use it, change it, share it. You can download the code and all the necessary supporting files (images, sound files, and so on) at https://nostarch.com/artists-guide-programming/. Some concepts will be more complex than others, of course. There is plenty of documentation for Processing on the internet, beginning with the https://processing.org/ site. Processing can be used with Arduino computers too. It has modules for sound, video, and scientific calculations, and it can be used to present images in a browser. It is my hope that this book will allow you to start experimenting with programming and generative art. Why are there few comments in the code? To save space on the right page! The entire left page is a description of the program and method, so it is in effect a large comment. —Jim Parker
INTRODUCTION
The Basics of a Programming Language: Processing When someone programs a computer, they are really communicating with it. It is an imperative and precise communication. Imperative because the computer has no choice; it is being told what to do, and it will do exactly that. Precise because a computer does not apply any interpretation to what it is being told. Computers do not think and so can’t evaluate a command that would amount to “expose the patient to a fatal dose of radiation” with any skepticism. So we, as programmers, must be careful and precise in what we instruct the machine to do. When humans communicate with each other, we use a language. Similarly, humans use languages to communicate with computers, but these languages are artificial (humans invented them for this purpose), terse (there are few if any modifiers—no way to express emotions or gradations of any feeling), precise (each item in the language means one thing), and written (we do not yet speak to computers in a programming language). The process of programming begins with a problem to be solved, and the first step is to state the problem as clearly as possible. Then we analyze the problem and determine methods by which it may be solved. Computers can only directly manipulate numbers, so it is common for solutions discussed at this stage to be numerical or mathematical. A sketch of the solution, perhaps on paper in a human language and math, is created. This is then translated into computer language and typed into the computer using a keyboard. The resulting text file is called a script, source code, or more commonly the computer program. Next, another program called a compiler takes the program and converts it into a form that can be executed on the computer. Basically, all programs are converted into machine code, which consists of numbers, and which the computer can execute. You are going to learn a language called Processing. It was developed for use by artists, but it’s pretty good for lots of things, and it’s good for teaching because it makes a lot of things easy and it always has graphical visual output. It is much like a lot of other languages in use these days in terms of structure (syntax). It is, in fact, the language Java enclosed in some
special easy-to-use packaging. A Processing program is called a sketch in honor of its artistic origins. In order to use a programming language, you need to understand some basic concepts and structures, at least at a basic level. These concepts will be introduced in this introduction. The rest of the book will teach you to program by example: when you open the book to a random location, the left page will almost always outline a problem or Processing language concept, and the right page will almost always show code that illustrates that concept, along with a screen image of the output from that program. The idea is to introduce only one or two new things on any page. The code will execute on a computer running any major operating system, once the free Processing language download has been installed. Go to https://processing. org/download and download the latest stable version for your OS. To begin programming, you need to appreciate that a language has a syntax or structure, and for computer languages this structure cannot be varied. The computer will always be the arbiter of what is correct, and if any program has a syntax error or produces erroneous results, it is the program and not the computer that is at fault. Next you need to appreciate that the syntax is arbitrary. It was designed by a human with attitudes and biases and new ideas, and while the syntax might be ugly or hard to recall, it is what it is. You might not understand parts of it at first, but after a while and after reading and executing the first 50 or 60 sketches in this book, most of it will make sense. A program consists of symbols, and their order matters. Some symbols are special characters with a defined meaning. For example, + usually means add, and − usually means subtract. Some symbols are words, and words defined by the language, like if, while, and true, cannot be also defined by a programmer—they mean what the language says they mean, and they are called reserved words. Some names have a definition given by the system but can be reused by a programmer if needed. These are called predefined names or system variables. However, some words can be defined by the programmer and are names for things the programmer wants to use in the program: variables and functions are examples.
The Beginning All sketches have the same basic structure. There is something called setup() (a predefined name) that gets executed just once, when the program begins. This is where we will do initializations, such as defining the size of the output window. If we need to read a bunch of images or sounds from files, this is where we might do it. NOTE This discussion presents a template that can be used to start coding any program. Detailed explanation of the syntax will come later. The syntax of setup() is as follows: void setup () { your code goes here } This is something we call a function in Processing (see Sketch 24). It is a bunch of code that is enclosed in braces (the { and }) and is given a name. It gets executed (called, we say) when we use the name in code later on. In this case the function is named setup(), and it is invoked automatically by Processing just once, when the program starts executing. The word void (a reserved word) is not important just now, but it means the function does not return a value. After setup() has finished, a window will open on the screen where the program will draw. This is called the sketch window, and its size is one of the things initialized within setup(). The Middle The second part of a sketch is another function, one named draw(). This function is called many times each second (the default is 60 times, but this can be changed), and its purpose is to update the drawing being made by the
program. Processing assumes that the programmer is writing a program to draw a picture of some kind. Every 1/60 of a second, the Processing system will call the draw() function. Whatever code appears there will be executed each time, and the idea is that the programmer can update the picture being created there as a user watches. For example, if a set of images of a moving animal is displayed one at a time, the result will be an animated image of the animal. The programmer can draw shapes, display text and images, change colors, and move shapes about the screen as the user watches. The syntax of draw (a predefined name) is as follows: void draw () { your code goes here } The Rest The programmer writes code that is inside either of the functions setup() and draw() or that is executed by those functions. Any part of the program that cannot be reached from setup() or draw() will never be executed (except for some of the mouse and keyboard functions). The programmer can name and provide code for other functions, and these can be executed by (called from) draw() or setup(). These functions are usually placed after the draw() function in the program. For example, if the programmer wanted to define a function named doSomething(), it might look like this: void doSomething () { your code goes here } This would be executed when its name was used in a call: void draw () {
doSomething(); } The semicolon is used to end a statement so that Processing knows when the programmer thinks a statement ends. It is used to detect errors: if a programmer thinks the statement is complete and the Processing compiler does not, the compiler issues an error message. The compiler is, after all, always right. Variables The concept of a variable is one that most beginners find difficult. Essentially, a variable is a place to put a result, usually a number. In a programming language, a variable is represented by a name, and the connection between the name and the value is established by a statement in the language called an assignment statement: it assigns a value to a variable. Here’s an example: count = 0; This establishes that the value of a variable named count is 0. How do we know that the name count is a variable? It must appear in a declaration: we “declare” that count is a variable, and we specify a type. The type defines the set of values that can be assigned to the variable. For a numerical variable, common types are integer and float (a decimal fraction). If count is to be an integer, then this would be the declaration: int count; The predefined name int means integer, and this declaration states that the name count will hold an integer. If it were supposed to be a number with a fraction (a real or floating-point number) the declaration would be as follows: float count;
A variable can only be used after it has been declared. It is an error to attempt to use a variable that has not been in a declaration, partly because its type would not be known. Now that you can define variables, you can do complex computations. For arithmetic the usual operations are possible: + (add), − (subtract), * (multiply), and / (divide). Both variables and constants can be used in mathematical expressions, just as in algebra. The following would be a legal assignment statement (assuming that the name radius was declared): count = 2 * 3.1419926 * radius; It would calculate the circumference of a circle with the given radius. How to Write a Program When Processing is started, either by clicking processing.exe or by clicking a Processing source file, the integrated development environment (IDE) will open a window on the screen. It will look something like Figure 1, though it may look a little different depending on your operating system and the version of Processing you use.