100% found this document useful (1 vote)
9 views

Processing for Android: Create Mobile, Sensor-aware, and XR Applications Using Processing 2nd Edition Colubri download

The document provides information about various ebooks available for download at ebookmass.com, including titles related to mobile application development, signal processing, and data processing. It highlights the book 'Processing for Android: Create Mobile, Sensor-aware, and XR Applications Using Processing, 2nd Edition' by Andrés Colubri, along with other recommended titles. Additionally, it includes details about the book's content, authorship, and copyright information.

Uploaded by

josolkolbet
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
9 views

Processing for Android: Create Mobile, Sensor-aware, and XR Applications Using Processing 2nd Edition Colubri download

The document provides information about various ebooks available for download at ebookmass.com, including titles related to mobile application development, signal processing, and data processing. It highlights the book 'Processing for Android: Create Mobile, Sensor-aware, and XR Applications Using Processing, 2nd Edition' by Andrés Colubri, along with other recommended titles. Additionally, it includes details about the book's content, authorship, and copyright information.

Uploaded by

josolkolbet
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 78

Download the full version and explore a variety of ebooks

or textbooks at https://ebookmass.com

Processing for Android: Create Mobile, Sensor-


aware, and XR Applications Using Processing 2nd
Edition Colubri

_____ Tap the link below to start your download _____

https://ebookmass.com/product/processing-for-android-create-
mobile-sensor-aware-and-xr-applications-using-
processing-2nd-edition-colubri/

Find ebooks or textbooks at ebookmass.com today!


Here are some recommended products for you. Click the link to
download, or explore more at ebookmass.com

Processing for Android: Create Mobile, Sensor-aware, and


XR Applications Using Processing, 2nd Edition Andrés
Colubri
https://ebookmass.com/product/processing-for-android-create-mobile-
sensor-aware-and-xr-applications-using-processing-2nd-edition-andres-
colubri/

Signal processing for neuroscientists 2nd ed Edition


Drongelen

https://ebookmass.com/product/signal-processing-for-
neuroscientists-2nd-ed-edition-drongelen/

Tensors for Data Processing. Theory, Methods, and


Applications Yipeng Liu

https://ebookmass.com/product/tensors-for-data-processing-theory-
methods-and-applications-yipeng-liu/

Oil Palm Biomass for Composite Panels: Fundamentals,


Processing, and Applications S.M. Sapuan

https://ebookmass.com/product/oil-palm-biomass-for-composite-panels-
fundamentals-processing-and-applications-s-m-sapuan/
Digital Image Processing Using MATLAB Rafael C. Gonzalez

https://ebookmass.com/product/digital-image-processing-using-matlab-
rafael-c-gonzalez/

Food Waste Recovery: Processing Technologies, Industrial


Techniques, and Applications 2nd Edition Charis M.
Galanakis
https://ebookmass.com/product/food-waste-recovery-processing-
technologies-industrial-techniques-and-applications-2nd-edition-
charis-m-galanakis/

Designing Applications for Google Cloud Platform: Create


and Deploy Applications Using Java Ashutosh Shashi

https://ebookmass.com/product/designing-applications-for-google-cloud-
platform-create-and-deploy-applications-using-java-ashutosh-shashi/

Essentials of Thermal Processing 2nd Edition Gary Tucker

https://ebookmass.com/product/essentials-of-thermal-processing-2nd-
edition-gary-tucker/

Android For Dummies 2nd Edition Dan Gookin

https://ebookmass.com/product/android-for-dummies-2nd-edition-dan-
gookin/
Processing
for Android
Create Mobile, Sensor-aware, and XR
Applications Using Processing

Second Edition

Andrés Colubri
Processing for Android
Create Mobile, Sensor-aware, and XR
Applications Using Processing

Second Edition

Andrés Colubri

More books: https://t.me/booksforits


Processing for Android: Create Mobile, Sensor-aware, and XR Applications Using
Processing, Second Edition
Andrés Colubri
University of Massachusetts, Worcester, MA, USA

ISBN-13 (pbk): 978-1-4842-9584-7 ISBN-13 (electronic): 978-1-4842-9585-4


https://doi.org/10.1007/978-1-4842-9585-4

Copyright © 2023 by Andrés Colubri


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.
Managing Director, Apress Media LLC: Welmoed Spahr
Acquisitions Editor: Spandana Chatterjee
Development Editor: Spandana Chatterjee
Coordinating Editor: Mark Powers
Cover image designed by eStudioCalamar
Distributed to the book trade worldwide by Apress Media, LLC, 1 New York Plaza, New York, NY 10004,
U.S.A. 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 booktranslations@springernature.com; for reprint,
paperback, or audio rights, please e-mail bookpermissions@springernature.com.
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 (https://github.com/Apress). For more detailed information, please visit
https://www.apress.com/gp/services/source-code.
Paper in this product is recyclable

More books: https://t.me/booksforits


To L. J. for accompanying during the writing of this book.
To my family and friends for always supporting me.
And to the Processing community for putting these tools to great use.

More books: https://t.me/booksforits


Table of Contents

About the Author�����������������������������������������������������������������������������������������������������xv


About the Technical Reviewer�������������������������������������������������������������������������������xvii
Acknowledgments��������������������������������������������������������������������������������������������������xix
Introduction������������������������������������������������������������������������������������������������������������xxi


■Part I: First Steps with Processing for Android���������������������������������� 1

■Chapter 1: Getting Started with the Android Mode����������������������������������������������� 3
What Is the Processing Project?��������������������������������������������������������������������������������������� 3
The Processing Language���������������������������������������������������������������������������������������������������������������������� 3
The Processing Development Environment�������������������������������������������������������������������������������������������� 4

Extending Processing������������������������������������������������������������������������������������������������������� 6
The Contribution Manager���������������������������������������������������������������������������������������������������������������������� 7

Processing for Android����������������������������������������������������������������������������������������������������� 8


Installing the Android Mode�������������������������������������������������������������������������������������������������������������������� 9
Interface of the Android Mode�������������������������������������������������������������������������������������������������������������� 10
Running a Sketch on a Device�������������������������������������������������������������������������������������������������������������� 12
Running a Sketch in the Emulator�������������������������������������������������������������������������������������������������������� 14

Summary������������������������������������������������������������������������������������������������������������������������ 16

■Chapter 2: The Processing Language������������������������������������������������������������������ 17
A Programming Sketchbook for Artists and Designers�������������������������������������������������� 17
The Structure of a Processing Sketch���������������������������������������������������������������������������� 17

More books: https://t.me/booksforits


■ Table of Contents

Drawing with Code��������������������������������������������������������������������������������������������������������� 20


Coordinates������������������������������������������������������������������������������������������������������������������������������������������ 21
Form����������������������������������������������������������������������������������������������������������������������������������������������������� 23
Color����������������������������������������������������������������������������������������������������������������������������������������������������� 25
Applying Geometric Transformations���������������������������������������������������������������������������������������������������� 28

Responding to User Input����������������������������������������������������������������������������������������������� 32


Coding a “Vine Drawing” App����������������������������������������������������������������������������������������� 35
Summary������������������������������������������������������������������������������������������������������������������������ 38

■Chapter 3: From Sketch to Play Store����������������������������������������������������������������� 39
Sketching and Debugging���������������������������������������������������������������������������������������������� 39
Getting Information from the Console�������������������������������������������������������������������������������������������������� 39
Getting more information with logcat��������������������������������������������������������������������������������������������������� 41
Using the Integrated Debugger������������������������������������������������������������������������������������������������������������� 41
Reporting Processing Bugs������������������������������������������������������������������������������������������������������������������ 42

Preparing a Sketch for Release�������������������������������������������������������������������������������������� 42


Adjusting for Device’s DPI�������������������������������������������������������������������������������������������������������������������� 43
Using the Emulator������������������������������������������������������������������������������������������������������������������������������� 46
Setting Icons and Bundle Name����������������������������������������������������������������������������������������������������������� 48
Setting Package Name and Version������������������������������������������������������������������������������������������������������ 48
Exporting As Signed Bundle����������������������������������������������������������������������������������������������������������������� 49

Summary������������������������������������������������������������������������������������������������������������������������ 51


■Part II: Drawing and Interaction������������������������������������������������������� 53

■Chapter 4: Drawing Graphics and Text���������������������������������������������������������������� 55
Drawing Shapes������������������������������������������������������������������������������������������������������������� 55
More Types of Shapes��������������������������������������������������������������������������������������������������������������������������� 55
Curve Shapes��������������������������������������������������������������������������������������������������������������������������������������� 58
Using Bézier Curves����������������������������������������������������������������������������������������������������������������������������� 60
Shape Attributes����������������������������������������������������������������������������������������������������������������������������������� 66
Shape Styles����������������������������������������������������������������������������������������������������������������������������������������� 67

vi

More books: https://t.me/booksforits


■ Table of Contents

Drawing Images������������������������������������������������������������������������������������������������������������� 69
Drawing Text������������������������������������������������������������������������������������������������������������������� 70
Loading and Creating Fonts������������������������������������������������������������������������������������������������������������������ 70
Text Attributes��������������������������������������������������������������������������������������������������������������������������������������� 73
Scaling Text������������������������������������������������������������������������������������������������������������������������������������������ 73

Renderers in Processing������������������������������������������������������������������������������������������������ 75
The PShape Class����������������������������������������������������������������������������������������������������������� 76
Creating PShapes��������������������������������������������������������������������������������������������������������������������������������� 76
Loading Shapes from SVG�������������������������������������������������������������������������������������������������������������������� 79
Texturing Shapes���������������������������������������������������������������������������������������������������������������������������������� 81

Summary������������������������������������������������������������������������������������������������������������������������ 82

■Chapter 5: Touchscreen Interaction��������������������������������������������������������������������� 83
Touch Events in Android������������������������������������������������������������������������������������������������� 83
Basic Touch Events������������������������������������������������������������������������������������������������������������������������������� 83
Multi-touch Events������������������������������������������������������������������������������������������������������������������������������� 89

Touch-Based Interaction������������������������������������������������������������������������������������������������ 93
Item Selection��������������������������������������������������������������������������������������������������������������������������������������� 93
Scrolling����������������������������������������������������������������������������������������������������������������������������������������������� 95
Swipe and Pinch����������������������������������������������������������������������������������������������������������������������������������� 97

Using the Keyboard������������������������������������������������������������������������������������������������������ 100


Summary���������������������������������������������������������������������������������������������������������������������� 101

■Chapter 6: Live Wallpapers�������������������������������������������������������������������������������� 103
Live Wallpapers������������������������������������������������������������������������������������������������������������ 103
Writing and Installing Live Wallpapers����������������������������������������������������������������������������������������������� 103
Using Multiple Home Screens������������������������������������������������������������������������������������������������������������ 105
Handling Permissions������������������������������������������������������������������������������������������������������������������������� 107

Drawing with Particle Systems������������������������������������������������������������������������������������ 111


Simulating Natural Motion������������������������������������������������������������������������������������������������������������������ 116

vii

More books: https://t.me/booksforits


■ Table of Contents

An Image-Flow Wallpaper�������������������������������������������������������������������������������������������� 120


Loading, Resizing, and Cropping Images�������������������������������������������������������������������������������������������� 120
Putting Everything Together��������������������������������������������������������������������������������������������������������������� 121
Wrapping the Project Up��������������������������������������������������������������������������������������������������������������������� 124

Summary���������������������������������������������������������������������������������������������������������������������� 126


■Part III: Sensors������������������������������������������������������������������������������ 127

■Chapter 7: Reading Sensor Data������������������������������������������������������������������������ 129
Sensors in Android Devices������������������������������������������������������������������������������������������ 129
Accelerometer������������������������������������������������������������������������������������������������������������������������������������ 129
Gyroscope������������������������������������������������������������������������������������������������������������������������������������������� 130
Magnetometer������������������������������������������������������������������������������������������������������������������������������������ 130
Location���������������������������������������������������������������������������������������������������������������������������������������������� 130

Accessing Sensors from Processing���������������������������������������������������������������������������� 130


Creating a Sensor Manager���������������������������������������������������������������������������������������������������������������� 131
Adding a Sensor Listener������������������������������������������������������������������������������������������������������������������� 131
Reading Data from the Sensor����������������������������������������������������������������������������������������������������������� 132
Reading Data from Other Sensors������������������������������������������������������������������������������������������������������ 134

The Ketai Library���������������������������������������������������������������������������������������������������������� 135


Installing Ketai������������������������������������������������������������������������������������������������������������������������������������ 135
Using Ketai����������������������������������������������������������������������������������������������������������������������������������������� 136
Event Handlers in Ketai���������������������������������������������������������������������������������������������������������������������� 138
Summary���������������������������������������������������������������������������������������������������������������������� 140

■Chapter 8: Driving Graphics and Sound with Sensor Data�������������������������������� 141
Using Ketai to Read Sensor Data���������������������������������������������������������������������������������� 141
Measuring Acceleration������������������������������������������������������������������������������������������������ 141
Shake Detection��������������������������������������������������������������������������������������������������������������������������������� 142
Step Counter��������������������������������������������������������������������������������������������������������������������������������������� 143
Audio-visual Mapping of Step Data���������������������������������������������������������������������������������������������������� 144
Playing Audio�������������������������������������������������������������������������������������������������������������������������������������� 149

viii

More books: https://t.me/booksforits


■ Table of Contents

Using the Magnetic Sensor������������������������������������������������������������������������������������������ 152


Creating a Compass App�������������������������������������������������������������������������������������������������������������������� 152

The Gyroscope�������������������������������������������������������������������������������������������������������������� 156


Controlling Navigation with the Gyroscope���������������������������������������������������������������������������������������� 159

Summary���������������������������������������������������������������������������������������������������������������������� 162

■Chapter 9: Geolocation�������������������������������������������������������������������������������������� 163
Location Data in Android���������������������������������������������������������������������������������������������� 163
Using Location API in Processing��������������������������������������������������������������������������������� 164
Location Permissions������������������������������������������������������������������������������������������������������������������������� 165
Accessing Data from Multiple Threads����������������������������������������������������������������������������������������������� 167
Location with Ketai����������������������������������������������������������������������������������������������������������������������������� 171
Using Additional Location Data����������������������������������������������������������������������������������������������������������� 172

A Street View Collage��������������������������������������������������������������������������������������������������� 174


Using Google Street View Image API��������������������������������������������������������������������������������������������������� 175
Making a Simple Image Collage��������������������������������������������������������������������������������������������������������� 177
Putting Everything Together��������������������������������������������������������������������������������������������������������������� 179

Summary���������������������������������������������������������������������������������������������������������������������� 182


■Part IV: Wearables and Watch Faces���������������������������������������������� 183

■Chapter 10: Wearable Devices��������������������������������������������������������������������������� 185
From Activity Trackers to Smartwatches���������������������������������������������������������������������� 185
Smartwatches������������������������������������������������������������������������������������������������������������������������������������ 186

Running Watch Face Sketches������������������������������������������������������������������������������������� 186


Using a Watch������������������������������������������������������������������������������������������������������������������������������������� 186
Using the Emulator����������������������������������������������������������������������������������������������������������������������������� 189
Displaying Time���������������������������������������������������������������������������������������������������������������������������������� 191
Counting Steps����������������������������������������������������������������������������������������������������������������������������������� 192
Designing for Smartwatches���������������������������������������������������������������������������������������� 193
Adjusting for Screen Shape���������������������������������������������������������������������������������������������������������������� 194
Watch Face Preview Icons������������������������������������������������������������������������������������������������������������������ 194

Summary���������������������������������������������������������������������������������������������������������������������� 195
ix

More books: https://t.me/booksforits


■ Table of Contents


■Chapter 11: Visualizing Time����������������������������������������������������������������������������� 197
From Sundials to Smartwatches���������������������������������������������������������������������������������� 197
Using Time to Control Motion������������������������������������������������������������������������������������������������������������� 198
Square vs. Round Watch Faces���������������������������������������������������������������������������������������������������������� 200

Working with a Watch Face Concept���������������������������������������������������������������������������� 203


Elapsed/Remaining Time�������������������������������������������������������������������������������������������������������������������� 204
Adding Interaction������������������������������������������������������������������������������������������������������������������������������ 206
Loading and Displaying Images���������������������������������������������������������������������������������������������������������� 207

Summary���������������������������������������������������������������������������������������������������������������������� 209

■Chapter 12: Visualizing Physical Activity���������������������������������������������������������� 211
Body Sensors��������������������������������������������������������������������������������������������������������������� 211
Step Counter��������������������������������������������������������������������������������������������������������������������������������������� 211
Heart Rate������������������������������������������������������������������������������������������������������������������������������������������� 211

Visualizing Physical Activity in Real Time��������������������������������������������������������������������� 212


Simple Step Counter��������������������������������������������������������������������������������������������������������������������������� 212
Accessing the Heart Rate Sensor������������������������������������������������������������������������������������������������������� 214
Visualizing Step Count Data���������������������������������������������������������������������������������������������������������������� 215
A Beating Heart����������������������������������������������������������������������������������������������������������������������������������� 217
Sensor Debugging������������������������������������������������������������������������������������������������������������������������������ 219

Grow a Tree As You Exercise!��������������������������������������������������������������������������������������� 223


Generating a Tree with a Particle System������������������������������������������������������������������������������������������� 223
Incorporating Step Count Data����������������������������������������������������������������������������������������������������������� 226
Tweaking the Watch Face������������������������������������������������������������������������������������������������������������������� 228
Blooming the Tree������������������������������������������������������������������������������������������������������������������������������� 229

Summary���������������������������������������������������������������������������������������������������������������������� 235


■Part V: 3D and Shaders������������������������������������������������������������������� 237

■Chapter 13: 3D in Processing���������������������������������������������������������������������������� 239
The P3D Renderer�������������������������������������������������������������������������������������������������������� 239
Hello World in 3D�������������������������������������������������������������������������������������������������������������������������������� 239

More books: https://t.me/booksforits


■ Table of Contents

3D Transformations������������������������������������������������������������������������������������������������������ 240


Combining Transformations���������������������������������������������������������������������������������������������������������������� 241

3D Shapes�������������������������������������������������������������������������������������������������������������������� 243


Custom Shapes����������������������������������������������������������������������������������������������������������������������������������� 245
The Camera���������������������������������������������������������������������������������������������������������������������������������������� 246
Immediate vs. Retained Rendering����������������������������������������������������������������������������������������������������� 249
Custom PShape Objects��������������������������������������������������������������������������������������������������������������������� 250
Loading OBJ Shapes��������������������������������������������������������������������������������������������������������������������������� 253

Summary���������������������������������������������������������������������������������������������������������������������� 255

■Chapter 14: Lighting and Texturing������������������������������������������������������������������� 257
Making 3D Scenes more Realistic with Lights and Textures���������������������������������������� 257
Light Sources and Material Properties����������������������������������������������������������������������������������������������� 257
Texture Mapping��������������������������������������������������������������������������������������������������������������������������������� 261

Putting Everything Together����������������������������������������������������������������������������������������� 265


Summary���������������������������������������������������������������������������������������������������������������������� 267

■Chapter 15: GLSL Shaders��������������������������������������������������������������������������������� 269
What Is a Shader?�������������������������������������������������������������������������������������������������������� 269
The Graphics Pipeline: Vertex and Pixel Shaders�������������������������������������������������������������������������������� 269
The PShader Class������������������������������������������������������������������������������������������������������������������������������ 272
Anatomy of a Simple Shader�������������������������������������������������������������������������������������������������������������� 274
Defining Custom Uniforms������������������������������������������������������������������������������������������������������������������ 277
Types of Shaders in Processing����������������������������������������������������������������������������������� 279
Color Shaders������������������������������������������������������������������������������������������������������������������������������������� 279
Texture Shaders���������������������������������������������������������������������������������������������������������������������������������� 280
Light Shaders������������������������������������������������������������������������������������������������������������������������������������� 283
Texlight Shaders��������������������������������������������������������������������������������������������������������������������������������� 286
Image Postprocessing Filters������������������������������������������������������������������������������������������������������������� 288
Day-to-Night Earth Shader and Live Wallpaper������������������������������������������������������������ 292
Summary���������������������������������������������������������������������������������������������������������������������� 301

xi

More books: https://t.me/booksforits


■ Table of Contents


■Part VI: Extended Reality: VR and AR��������������������������������������������� 303

■Chapter 16: Basics of VR����������������������������������������������������������������������������������� 305
Brief History of VR�������������������������������������������������������������������������������������������������������� 305
Google Cardboard������������������������������������������������������������������������������������������������������������������������������� 305
Hardware Requirements��������������������������������������������������������������������������������������������������������������������� 306

VR in Processing���������������������������������������������������������������������������������������������������������� 306
Stereo Rendering�������������������������������������������������������������������������������������������������������������������������������� 307
Monoscopic Rendering����������������������������������������������������������������������������������������������������������������������� 309
VR Interaction��������������������������������������������������������������������������������������������������������������� 310
Eye and World Coordinates����������������������������������������������������������������������������������������������������������������� 311
The Line of Sight��������������������������������������������������������������������������������������������������������������������������������� 313
Selecting a Shape with Screen Coordinates��������������������������������������������������������������������������������������� 315
Bounding Box Selection���������������������������������������������������������������������������������������������������������������������� 318

Movement in VR����������������������������������������������������������������������������������������������������������� 322


Automatic Movement�������������������������������������������������������������������������������������������������������������������������� 323
Unconstrained Movement������������������������������������������������������������������������������������������������������������������� 325

Summary���������������������������������������������������������������������������������������������������������������������� 328

■Chapter 17: Basics of AR����������������������������������������������������������������������������������� 329
A Brief History of AR����������������������������������������������������������������������������������������������������� 329
AR on Android������������������������������������������������������������������������������������������������������������������������������������� 330
Requirements������������������������������������������������������������������������������������������������������������������������������������� 331
Getting Started����������������������������������������������������������������������������������������������������������������������������������� 331

Drawing Trackables������������������������������������������������������������������������������������������������������ 332


Using Anchors������������������������������������������������������������������������������������������������������������������������������������� 335
Hitting Trackables������������������������������������������������������������������������������������������������������������������������������� 337
Adding a User Interface���������������������������������������������������������������������������������������������������������������������� 340
Using Custom Shaders in AR�������������������������������������������������������������������������������������������������������������� 343
Drawing in AR������������������������������������������������������������������������������������������������������������������������������������� 346

Summary���������������������������������������������������������������������������������������������������������������������� 350

xii

More books: https://t.me/booksforits


■ Table of Contents


■Chapter 18: Creating XR Experiences���������������������������������������������������������������� 351
Challenges with XR Apps���������������������������������������������������������������������������������������������� 351
Drawing in VR������������������������������������������������������������������������������������������������������������������������������������� 352
Initial Sketches����������������������������������������������������������������������������������������������������������������������������������� 353

A Simple VR UI�������������������������������������������������������������������������������������������������������������� 354


Drawing in 3D��������������������������������������������������������������������������������������������������������������� 359
Flying Around��������������������������������������������������������������������������������������������������������������� 366
Final Tweaks and Packaging���������������������������������������������������������������������������������������� 371
Intro Text��������������������������������������������������������������������������������������������������������������������������������������������� 371
Icons and Package Export������������������������������������������������������������������������������������������������������������������ 372

Summary���������������������������������������������������������������������������������������������������������������������� 373


■Part VII: Appendixes����������������������������������������������������������������������� 375

■Chapter 19: Appendix A: Gradle and Android Studio Integration���������������������� 377
Google Tools for Android Development������������������������������������������������������������������������� 377
Exporting a Sketch As a Gradle Project������������������������������������������������������������������������ 379
Importing into Android Studio�������������������������������������������������������������������������������������� 380
Adding a Processing Sketch to a Layout���������������������������������������������������������������������� 384

■Chapter 20: Appendix B: Processing Libraries for Android������������������������������� 389
Extending Processing with Libraries���������������������������������������������������������������������������� 389
Installing Libraries with the Contribution Manager���������������������������������������������������������������������������� 389
Installing Libraries Manually�������������������������������������������������������������������������������������������������������������� 392

Writing New Libraries��������������������������������������������������������������������������������������������������� 393

Index��������������������������������������������������������������������������������������������������������������������� 397

xiii

More books: https://t.me/booksforits


About the Author

Andrés Colubri is a senior member of the Processing project and the


main developer of the OpenGL renderer, the video library, and Processing
for Android. He originally studied Physics and Mathematics in Argentina
and later did an MFA in the Design Media Arts Department at UCLA. He
uses Processing as a tool to bridge his interests in computer graphics,
data visualization, and biomedical research. He is currently an assistant
professor at the University of Massachusetts Chan Medical School
(https://co-labo.org).

xv

More books: https://t.me/booksforits


About the Technical Reviewer

Massimo Nardone has more than 25 years of experience in security, web


and mobile development, cloud, and IT architecture. His true IT passions
are security and Android. He has been programming and teaching others
how to program with Android, Perl, PHP, Java, VB, Python, C/C++, and
MySQL for more than 20 years. He holds a Master of Science degree in
computing science from the University of Salerno, Italy.
He has worked as a CISO, CSO, security executive, IoT executive,
project manager, software engineer, research engineer, chief security
architect, PCI/SCADA auditor, and senior lead IT security/cloud/SCADA
architect for many years. His technical skills include security, Android,
cloud, Java, MySQL, Drupal, COBOL, Perl, web and mobile development,
MongoDB, D3, Joomla, Couchbase, C/C++, WebGL, Python, Pro Rails,
Django CMS, Jekyll, Scratch, and more.
He was a visiting lecturer and supervisor for exercises at the Networking Laboratory of the Helsinki
University of Technology (Aalto University). He also holds four international patents (in the PKI, SIP, SAML,
and Proxy areas). He is currently working for Cognizant as head of cybersecurity and CISO to help clients
in areas of information and cybersecurity, including strategy, planning, processes, policies, procedures,
governance, awareness, and so forth. In June 2017, he became a permanent member of the ISACA
Finland Board.
Massimo has reviewed more than 45 IT books for different publishing companies and is the coauthor
of Pro Spring Security: Securing Spring Framework 5 and Boot 2-based Java Applications (Apress, 2019),
Beginning EJB in Java EE 8 (Apress, 2018), Pro JPA 2 in Java EE 8 (Apress, 2018), and Pro Android Games
(Apress, 2015).

xvii

More books: https://t.me/booksforits


Acknowledgments

First, I want to give recognition to Ben Fry and Casey Reas, who initiated the Processing project over two
decades ago and have worked steadfastly since then to promote software literacy within the visual arts and
visual literacy within technology. Also, very special thanks to Sam Pottinger for his hard work in Processing 4
and his help to make the Android mode compatible with it.
I would like to express my gratitude to all the Google Summer of Code students who contributed to the
project in very important ways in the years since the first edition: Syam Sundar Kirubakaran (GSoC 2018),
Deeraj Esvar (GSoC 2019), Aditya Rana (GSoC 2020), Rupesh Kumar (GSoC 2022), and Gaurav Puniya
(GSoC 2023).
I extend my appreciation to Chris Coleman and Kate Hollenbach for their invitation to do a residence at
the Clinic for Open Source Arts at the University of Denver in March 2023 to finalize the development of the
Android mode for Processing 4.
Finally, I thank the Apress editors, Spandana Chatterjee, Nirmal Selvaraj, and Mark Powers, for helping
steer this second edition through the finish line.

xix

More books: https://t.me/booksforits


Introduction

Welcome to the second edition of Processing for Android! In this book, we will explore the exciting world
of creative coding and mobile app development using the Processing programming language specifically
tailored for the Android platform. Whether you are an experienced programmer, an artist looking to expand
your creative horizons, or a beginner interested in exploring the intersection of technology and art, this book
is for you.
Processing, initiated by Ben Fry and Casey Reas in 2001, has revolutionized the way artists, designers,
and developers approach creative coding. Its intuitive syntax and powerful capabilities make it an ideal
tool for creating applications with interactive graphics, sound, animations, and more. With the rise of
smartphones and smartwatches, mobile apps became a widely available medium for exploring new ideas
with code, making Processing for Android a very useful tool to learn, prototype, and produce app projects.
Written by Andrés Colubri, an experienced software developer, computational scientist, and media
artist who has been an active contributor to the Processing project for more than ten years, this book is a
comprehensive guide that will take you on a journey from the fundamentals of Processing coding to building
complex Android applications. No matter if you are new to Processing or have previous experience with
the language, this book will equip you with the knowledge and skills necessary to develop engaging and
innovative apps.
The book is designed with a hands-on approach to learning. Through a series of step-by-step tutorials
and practical examples, you will learn how to set up your Processing development environment, navigate
the Processing for Android interface, and harness the power of the Android platform to craft app-based
experiences. From creating interactive animations to working with sensors, cameras, GLSL shaders, and
virtual and augmented reality, you will gain a deep understanding of the capabilities that are offered by
Processing for Android.
In addition to technical instruction, this book explores the artistic and creative possibilities that you can
unlock with Processing for Android. You will be inspired by the diverse range of examples and full projects
showcased throughout the book, demonstrating how Processing can be used to create visually sophisticated
and conceptually rich mobile apps. Whether you are interested in generative art, data visualization, or
immersive experiences in VR or AR, the combination of Processing and Android provides an exciting
playground for your creativity.
This second edition is a major update of the book, with all code examples and figures from the first
edition carefully revised to reflect the latest changes in the Processing software and the Android platform.
Furthermore, several of the full projects at the end of each section were significantly rewritten to make them
more concise and easier to follow while still highlighting the key techniques of their corresponding section.
An entire new section comprising three chapters devoted to VR and AR was added, as well as a chapter
where shader programming in Processing is described in depth and illustrated with many code examples
from basic to advanced.
As you progress through the chapters, you will not only acquire the technical skills to create Android
apps with Processing but also gain a deeper understanding of programming concepts and computational
thinking. This book encourages you to experiment, explore, and push the boundaries of what is possible
with Processing for Android.

xxi

More books: https://t.me/booksforits


■ Introduction

So if you are ready to embark on an exciting journey into the world of creative coding and mobile app
development, Processing for Android is your gateway. Let’s dive in and unlock the potential of this powerful
combination of art, technology, and Android!
Happy coding and creating!

xxii

More books: https://t.me/booksforits


PART I

First Steps with Processing for


Android

More books: https://t.me/booksforits


CHAPTER 1

Getting Started with the Android


Mode

In this chapter, we will introduce the Processing software and its Android mode, the community behind
these projects, and how we can start using Processing to create apps for Android devices.

What Is the Processing Project?


The Processing project is a community initiative with the goals of sharing knowledge, fostering education,
and promoting diversity in computer programming. The Processing software is a central part of this
initiative, guided by the Processing Foundation (https://processingfoundation.org/), whose main
mission is to “promote software literacy within the visual arts and visual literacy within technology-related
fields – and to make these fields accessible to diverse communities.” This community grew off the original
Processing software, a programming language and environment created in 2001 by Casey Reas and
Ben Fry at the MIT Media Lab as a teaching and production tool in computational arts and design. The
Processing software has been continuously developed since then and is available for download at https://
processing.org/, with its source code released under free software licenses. From now on, we will simply
refer to Processing when talking about the Processing software.
Processing consists of two complementary parts: the Processing programming language and the
Processing development environment. Together, they form a “software sketchbook” that allows users to
quickly implement, or “sketch,” their ideas with code while also providing them with enough room to
iteratively refine these ideas into fully developed projects. Processing has been used to create many beautiful
and inspiring works in generative art, data visualization, and interactive installations, just to mention a few
areas. There are several online resources listing some of these works, including CreativeApplications.Net
(www.creativeapplications.net/category/processing/), OpenProcessing (https://openprocessing.
org/), and “For Your Processing” on Tumblr (https://fyprocessing.tumblr.com/).

The Processing Language


The Processing language is a set of functions, classes, and constants we can use to program screen drawing,
data input/output, and user interaction, originally implemented in Java and now available in Python,
JavaScript, and other programming languages. The core team of people behind Processing (https://
processing.org/people/) has carefully constructed this language, technically called “Application
Programming Interface” or API, to simplify the development of graphical and interactive applications by
means of a simple and consistent naming convention, unambiguous behavior, and a well-defined scope.

© Andrés Colubri 2023 3


A. Colubri, Processing for Android, https://doi.org/10.1007/978-1-4842-9585-4_1

More books: https://t.me/booksforits


Chapter 1 ■ Getting Started with the Android Mode

The Java implementation of the Processing language has been part of Processing dating back to 2001
and encompasses around 200 functions. A defining feature of this language is that it offers us the possibility
of creating interactive graphics with very little code. It also includes several simplifications with respect
to the Java language, with the purpose of making it easier to teach to people who are not familiar with
computer code. The following program illustrates these features of the Processing language:

color bg = 150;

void setup() {
  size(200, 200);
}

void draw() {
  background(bg);
  ellipse(mouseX, mouseY, 100, 100);
}

The output of this program is a window of 200 by 200 pixels, with a white circle that follows the
movement of the mouse on a gray background. The functions setup() and draw() are present in most
Processing programs, and they drive its “drawing loop.” All the initialization of the program should take place
in setup(), which is called just once when the program starts up. The draw() function, containing all the
drawing instructions, is then called continuously several times per second (by default, 60 times) so that we
can animate the graphical output of our program. Another term specific to Processing is the word “sketch,”
which refers to a Processing program by highlighting the concept of code sketching we mentioned earlier.

The Processing Development Environment


The Processing Development Environment (PDE) is the software that provides users with a minimalistic
code editor to write, run, and refine Processing sketches (Figure 1-1). The PDE also incorporates an
uncluttered user interface to handle all the sketches created with it and to add libraries and other external
components that extend the core functionality of the PDE, such as p5.js, Python, or Android modes.
The ease of use and simplicity of the PDE and the Processing language are the key elements to realize
the concept of a “code sketchbook.” A stumbling block for many people wanting to start working with
code is the complexity of a modern development environment like Eclipse or IntelliJ, in terms of a lengthy
installation and an overwhelming user interface. In contrast, the PDE addresses these issues by providing
an easy install process and a clean interface, while the simple structure of a Processing sketch enables users
to obtain visual feedback rapidly. Processing’s aim is to enable an iterative development process analogous
to sketching with pen and paper, where we can start with a simple idea and then refine by continuous code
sketching.

■■Note The Processing language can be used outside of the PDE, for example, in advanced Integrated
Development Environments or IDEs, such as Eclipse or IntelliJ. All of Processing’s drawing, data, and interaction
API can be used when writing a program with these IDEs; but many of the simplifications that the Processing
language has with respect to Java will be lost.

Those of us who are familiar with Java have probably noticed that the code shown in Listing 1-1 is not
a valid Java program. For example, there is no explicit definition of a main class encapsulating all the code,
nor the additional instructions required in Java to initialize the graphical display and the user input. This

More books: https://t.me/booksforits


Chapter 1 ■ Getting Started with the Android Mode

sketch needs to be run inside the PDE, which applies a “pre-processing” step to the Processing code to
convert it into a complete Java program. However, this step occurs behind the scenes, and we do not need to
worry about it at all. Only when using an advanced IDE like those noted previously, we need to make sure to
incorporate the Processing API into a syntactically correct Java program.
We can download the latest version of Processing from the main website (https://processing.org/
download). As we pointed out in the previous paragraph, installation is very easy, only requiring unpacking
the zip (on Windows and macOS) or tgz (on Linux) package that contains the PDE and all other core files. We
should be able to then run the PDE without any additional steps, from whichever location inside the home
or applications folder.

Figure 1-1. The Processing Development Environment showing a running sketch in the Java mode

The PDE saves our sketches inside a “sketchbook” folder. Each sketch is stored in a subfolder inside
the sketchbook, which in turn contains one or more source code files with the pde extension. By default,
Processing creates the sketchbook inside the documents folder located in the user’s account (e.g., /Users/
andres/Documents/Processing on macOS), but we can change this location by selecting the desired
sketchbook folder in the Preferences window, available under the “Processing ➤ Settings” menu on macOS
and “File ➤ Settings” on Windows and Linux (Figure 1-2). Notice the sketchbook location at the top.

More books: https://t.me/booksforits


Chapter 1 ■ Getting Started with the Android Mode

Figure 1-2. The Preferences window on macOS

Extending Processing
As we mentioned at the beginning, the Processing project is not only the PDE and the language but also, and
very importantly, the community built around the use of the software and the “goal to empower people of all
interests and backgrounds to learn how to program and make creative work with code, especially those who
might not otherwise have access to these tools and resources,” as stated in the home page of the Processing
Foundation. Thanks to Processing’s open nature and modular architecture, many people have contributed
with improvements and extensions to the “core” software over the years. These contributions fall within one
of the following four categories:
• Libraries: Modules (comprising one or more Java code files built into a jar package
and additional documentation and example files) that make it possible to access
new functionality in the sketches, for example, OpenCV library for computer vision
applications on PC or Mac computers, or TensorFlow Lite for running machine
learning tasks on Android.

More books: https://t.me/booksforits


Chapter 1 ■ Getting Started with the Android Mode

• Programming modes: Alternative code editors and related PDE customizations that
allow using an entirely different language within the PDE, for example, the Android
mode itself! We will see in the next sections of this chapter how to install the Android
mode on top of the default PDE.
• Tools: Applications that can only run from Processing and provide specific
functionality to help while writing code, debugging, and testing the sketch, for
example, the color picker (discussed in Chapter 2).
• Examples: Packages of contributed code sketches that can be used as learning
material or reference, for example, the sketches from the Learning Processing book
by Daniel Shiffman (http://learningprocessing.com/).
The possibility of extending Processing through contributed libraries, modes, tools, and examples has
enabled the growth of Processing into application domains that were not part of the original software, such
as mobile apps, computer vision, and physical computing, while keeping the core functionality simple and
accessible for new programmers.

The Contribution Manager


By default, Processing includes one default mode, Java, where we can write and run sketches on Windows,
Mac, and Linux computers using the Java implementation of the Processing language. Processing also
bundles several “core” libraries, some of which are OpenGL (for drawing hardware-accelerated 2D and 3D
scenes), PDF (to export graphics as PDF files), and data (which allows handling data files in formats such as
CSV and JSON).
We can use the Contribution Manager (CM) to install additional contributions, which makes the entire
process very seamless. A screenshot of the CM is shown in Figure 1-3. The CM has five tabs, the first four
for each type of contribution – libraries, modes, tools, and examples – and the fifth tab for updates. All the
contributions that are registered by their authors in a central repository are accessible through the CM and
can also be updated through the CM when new versions become available.

■■Note Contributions that are not available through the CM can be installed manually. You need to download
the package containing the library, mode, tool, or examples, typically in zip format, and extract it into the
sketchbook folder. There are separate subfolders for libraries, modes, tools, and examples. See https://
processing.org/reference/libraries/ for more info.

More books: https://t.me/booksforits


Chapter 1 ■ Getting Started with the Android Mode

Figure 1-3. The Contribution Manager in Processing showing the Modes tab

Processing for Android


Processing for Android, just like the Processing software itself, is also several things. Primarily, it is a
community effort that started in 2009 with the purpose of supporting the development of Android apps
using Processing and translating some of the concepts of the project to the context of mobile apps: iterative
sketching, simplicity, and accessibility.
If we look more closely into the technical details, Processing for Android is made of two parts: the
processing-android library and the custom PDE programming mode itself. The library is the package
that contains all the functions of the Processing API but re-implemented for the Android platform. The
Android mode provides a customized version of the PDE that allows us to write Processing code and run
it on an Android device or in the emulator. The Android mode includes the processing-android library,
which we need for our Processing code to run without errors. However, we don’t need to worry about these
distinctions at this point, since Processing will let us install and use the Android mode and will make sure
that all the required libraries are placed in the right places. But knowing about the difference between the
android library and the mode would be important for those readers who may be planning to use Processing
for Android in more advanced applications.

■■Note The processing-android library can be imported from an IDE like Android Studio, allowing using all the
Processing functionality in a regular Android app. This advanced use is covered in Appendix A.

More books: https://t.me/booksforits


Chapter 1 ■ Getting Started with the Android Mode

Installing the Android Mode


Once we have installed Processing in our computer, we should be able to open the PDE by running the
Processing application and then to install the most recent release of the Android mode through the CM. The
mode also requires the Android Software Development Kit (SDK) to work. The Android SDK is the set
of libraries, tools, documentation, and other supporting files provided by Google to develop and debug
Android apps. So let’s follow these next steps to install the Android mode and, if needed, the SDK:
1. Open the CM by clicking the “Manage Modes…” option that appears in the drop-
down menu in the upper-right corner of the PDE (Figure 1-4).
2. Select the entry for the Android mode in the Modes tab and click the
“Install” button.
3. After installation is complete, close the CM and switch into the Android mode
using the same drop-down menu from Figure 1-4.
When switching into the Android mode for the first time, it will ask us to locate or download the
Android SDK (Figure 1-5). Because the SDK is very large (up to several GBs), it could be a good idea to use
the one that is already installed to save disk space. However, if that SDK is also used by another development
tool, such as Android Studio, it may get updated or changed outside Processing, which may lead to
incompatibilities with the Android mode. If that’s the case, then it may be better to allow Processing to
download and install its own copy of the Android SDK, which will not interfere with the SDK in use by other
development tools. If no valid Android SDK is detected, Processing will ask to manually locate an SDK, or
automatically download it (Figure 1-5).

Figure 1-4. Opening the Contribution Manager to add a new mode

■■Note Version 4.5+ of the Android mode requires Android version 13, corresponding to API level 33
(https://source.android.com/docs/setup/about/build-numbers). The mode’s automatic SDK
download will retrieve this version from the Google servers.

More books: https://t.me/booksforits


Chapter 1 ■ Getting Started with the Android Mode

Figure 1-5. Pop-up dialog in the Android mode allowing us to search for an existing SDK in our computer
manually or download a new copy of the SDK from Google’s servers

Finally, pre-releases of the Android mode, as well as older versions that are no longer are available
through the CM, are all deposited in the GitHub releases page (https://github.com/processing/
processing-android/releases). So, if we are interested in trying these versions out, we could install
them manually by downloading the corresponding zip file and extracting it into the modes folder in the
Processing’s sketchbook.

Interface of the Android Mode


The editor in the Android mode is very similar to that of the Java mode. The toolbar contains the play and
stop buttons to launch a sketch (on a connected device) and to stop its execution (on the device or in the
emulator). Code autocompletion and integrated debugger in the editor are available as well. The main
menu contains several Android-specific options as well (Figure 1-6). The “File” menu has options to export
the current sketch as a package ready to upload to the Google Play Store, or as a project that can be opened
with Android Studio. The “Sketch” menu contains separate options to run the sketch on a device or in the
emulator, as well as a separate “Android” menu containing several options, among them the type of output
to target with the sketch – regular app, wallpaper, watch face, VR, or AR app – and the list of Android devices
currently connected to the computer. We will cover all these options in the next chapters!

10

More books: https://t.me/booksforits


Chapter 1 ■ Getting Started with the Android Mode

Figure 1-6. Android-specific options in the interface of the Android mode

11

More books: https://t.me/booksforits


Chapter 1 ■ Getting Started with the Android Mode

Running a Sketch on a Device


Once we have written some sketch code with the PDE, we can then run it on an Android phone, tablet, or
watch. The first thing we need to do is to make sure that “USB Debugging” is turned on on our device. The
process to do this varies by device and which version of the Android OS we have installed on it. In most of
the cases, this setting is in the Developer Options, under system Setting. On Android 4.2 and higher, the
Developer Options are hidden by default, but we can enable them by following these instructions:
1. Open the Settings app.
2. Scroll to the bottom and select About phone.
3. Scroll to the bottom and tap Build number seven times.
4. Return to the previous screen to find Developer Options near the bottom.
After turning USB Debugging on (which we need to do only once), we need to connect the device to
the computer through the USB port. Processing will then try to recognize it and add it to the list of available
devices in the “Android” menu.

■■Note Version 4.5+ of the Android mode only supports devices that are running Android 4.2 (API level 17)
or newer.

Let’s use the code in Listing 1-1 as our first Processing for Android sketch. It is okay if we do not
understand every line of code in it, as we will go over the Processing API in detail in the next chapters. It
simply draws a black square in the half of the screen that receives a touch press.

Listing 1-1. Our first Processing for Android sketch

void setup() {
  fill(0);
}

void draw() {
  background(204);
  if (mousePressed) {
    if (mouseX < width/2) rect(0, 0, width/2, height);
    else rect(width/2, 0, width/2, height);
  }
}

It is possible to have several devices connected simultaneously to the computer, but only one can be
selected in the Devices menu as the “active” device, which will be where our sketch will be installed and run.
Figure 1-7 shows our first sketch already loaded in the PDE and the selected device to run it on.

12

More books: https://t.me/booksforits


Chapter 1 ■ Getting Started with the Android Mode

Figure 1-7. Selecting the device to run the sketch on

After we have picked the active device, we can hit the run button or select “Run on Device” under the
“Sketch” menu. Then, we should see some messages scrolling down in the PDE’s console, while Processing
compiles the sketch, packages it as an Android app, and installs it on the device. One important detail is
that the computer needs to be connected to the Internet the first time we run a sketch. The reason is that
Processing uses a tool called Gradle to build the app from the sketch’s source code, but Gradle is not part of
the initial Android mode installation. The Android mode will automatically download the Gradle tool the
first time it tries to run a sketch. It can be offline when running sketches after the first time. If everything goes
well, the sketch should launch and show up on the screen of the device, as shown in Figure 1-8.

Figure 1-8. Running a sketch on a connected phone

13

More books: https://t.me/booksforits


Chapter 1 ■ Getting Started with the Android Mode

■■Note If we are running Windows, we may need to install a special USB driver to connect to the device
(https://developer.android.com/studio/run/oem-usb.html). In the case of Linux, we may need
to install some additional packages depending on the distribution we are using (https://developer.
android.com/studio/run/device.html). Also, make sure that the USB connection is not configured as
“Charge Only.”

Running a Sketch in the Emulator


If we do not have a device to run our sketch on, we can still use the emulator. The emulator is a program that
creates a “software replica” of a physical device that runs on our computer. This replica is called an Android
Virtual Device (AVD), and even though it is generally slower than a real device, it can also be useful to test
our sketch on hardware we don’t currently have.
The first time we run a sketch in the emulator, Processing will download the “system image” containing
all the information needed to emulate the AVD in our computer (Figure 1-9). However, it will initially ask us
if we want to use the “ARM” or the “x86” images. The reason for this is that Android devices use ARM CPUs
(central processing units), while our desktop or laptop computers often have x86 CPUs (ARM and x86 denote
different “architectures” that CPUs can have to process the instructions from our code). When emulating an
AVD with an ARM image on an x86 CPU, the emulator will convert ARM instructions into x86 instructions
one by one, which could be slow. But if we use the x86 image on an x86 CPU, our computer will be able to
simulate the AVD’s CPU directly and therefore much faster. One drawback of using x86 images is that we
must install an additional software on Mac or Windows called HAXM. Processing already downloaded
HAXM together with the Android SDK, so it will install it for us in case we decide to use x86 images.
However, with the ARM-based Mac computers (M1, M2, etc.), we do not have this issue since their CPUs
have the same ARM architecture as the emulated devices.
We should also keep in mind that HAXM is only compatible with Intel processors, so the emulator won’t
work with x86 images if our computer has an AMD CPU. Linux has its own AVD acceleration system and
does not require HAXM, so we can use x86 images on a Linux computer with an AMD CPU. We would need
to perform some extra configuration steps though, which are described here: https://developer.android.
com/studio/run/emulator-acceleration.html#vm-linux.

14

More books: https://t.me/booksforits


Chapter 1 ■ Getting Started with the Android Mode

Figure 1-9. System image download dialog in the Android mode

After finishing the download, which can take several minutes depending on our Internet connection
(the system images for the emulator are over 1GB in size), Processing will boot up the emulator and then will
launch the sketch in it. Once our Listing 1-1 is running in the emulator, it should look like the one shown in
Figure 1-10.

15

More books: https://t.me/booksforits


Chapter 1 ■ Getting Started with the Android Mode

Figure 1-10. Running our sketch in the emulator

Summary
In this first chapter, we have learned what the Processing project and software are and how we can
use Processing to create apps, thanks to its Android mode. As we saw, some of the main features of the
Processing software are its minimal interface and the simple structure of a program, called a “sketch.”
These features allow us to start writing, testing, and refining our own sketches, either on a device or in the
emulator, very quickly.

16

More books: https://t.me/booksforits


CHAPTER 2

The Processing Language

If you are not familiar with the Processing language, read this chapter for an introduction to how to create 2D
shapes, use geometry transformations and color, and handle touchscreen input in Processing. The chapter
ends with a step-by-step example of a drawing sketch, which we will use in Chapter 3 to learn how to export
and upload an app created with Processing to the Play Store.

A Programming Sketchbook for Artists and Designers


As we learned in the first chapter, the Processing language, together with the Processing Development
Environment (PDE), makes it easier for users who are new to programming to start creating interactive
graphics. The language has been designed to be minimal and simple for learning and yet expressive enough
to create many kinds of code-based projects, including generative art, data visualization, sound art, film, and
performance. It includes around 200 functions across different categories: drawing, interaction, typography,
etc., as well as several classes that help with the handling of form, color, and data.
The creators of Processing were also inspired by the concept of sketching: when we have an idea and
use a paper sketchbook to draw it down, we often create many iterations or variations of the original idea as
we refine it or make changes. Processing supports a similar way of working with computer code by making it
easy for us to obtain visual feedback from the code so we can quickly iterate and refine a programming idea.
This is why you will see Processing described as a “coding sketchbook” in many places. The next section
describes the basic structure in Processing that allows us to sketch with code by getting animated graphics to
the computer screen.

The Structure of a Processing Sketch


Most of the time, we want our Processing sketches to run nonstop to animate graphics on the screen and
keep track of user input. This means that instead of running our code just one time, Processing will continue
running it repeatedly so that we can animate the visual output by programming how it changes from one
frame to the next and how it’s affected by any interaction of the user with the computer (desktop, laptop,
phone, etc.). Because of that, we call these “interactive sketches” in contrast with “static sketches” that run
just one time (we can create these with Processing too, but for now, we will focus on interactive sketches).

■■Note All the code examples in this chapter can be run in the Java or the Android mode, since they don’t
rely on any features of the Processing language specific to either mode. This chapter also assumes some basic
knowledge of programming, including conditions (if/else), loops (for/while), use of variables, and organizing our
code with functions, so we will not go over those concepts.

© Andrés Colubri 2023 17


A. Colubri, Processing for Android, https://doi.org/10.1007/978-1-4842-9585-4_2

More books: https://t.me/booksforits


Chapter 2 ■ The Processing Language

The structure of an interactive sketch in Processing is uncomplicated: it requires two functions, one
called setup() and the other, draw(). The setup() function will contain the code that we need to run only
one time at the beginning to set things up, and the draw() function will contain the code that generates the
visual output of our sketch and Processing will run every time it has to draw or “render” a new frame on the
screen of the computer, typically 60 times per second. Let’s use these functions to create our first animated
sketch in Processing!
A simple animation could be moving a vertical line from left to right across the screen. We do just
that in Listing 2-1, where we have both setup() and draw(). In the setup() function, we run a few initial
tasks: first, we set the size of the output window or “canvas” where Processing will draw to. In this case, we
are initializing the canvas with fullScreen(), which makes it as large as the entire screen of the computer
(or phone). Then we set the parameters of our line with strokeWeight(2), which sets the line weight
(or thickness) to 2 pixels, and stroke(255), which sets the line color to white (we will go over the use of
numbers to set color values later in this chapter). Finally, we set the value of the variable x, declared at the
top of the code, to zero. This variable holds the horizontal position of the line, and setting to zero means
placing it on the left side of the screen (also later in the chapter we will discuss about screen coordinates
in more detail). In the draw() function, we start by setting the color of the entire canvas to a tone of gray
with background(50) and then draw the line with line(x, 0, x, height). The line() function takes four
parameters: the first two (x, 0) correspond to the first point of the line, and the last two (x, height), to the
second point, so by calling this function, we get Processing to draw a line from (x, 0) to (x, height). The word
“height” is a “constant” in Processing that always represents the height of the canvas and therefore cannot
be used as a variable name by us (the Processing language includes several more constants like this; we
will learn about some of them later in this and following chapters). Because the two points have the same x
coordinate, we will get a vertical line running between the top (0) and the bottom (height) of the screen. The
last two lines of code in the draw() function control the animation: by doing x = x + 1, we are increasing
the value of the horizontal position of our vertical line by one unit; this means that the line will move to the
right one pixel per frame. If we keep adding 1 to x enough times, its value will eventually be larger than the
width of our canvas, and the line will no longer be visible. In that case, we put the line back at the left edge
of the canvas by checking if x is larger than the width and resetting to zero with if (width < x) x = 0. The
output of this sketch running on a phone is shown in Figure 2-1.

Listing 2-1. A sketch that draws a vertical line moving horizontally across the screen

int x;

void setup() {
  fullScreen();
  strokeWeight(2);
  stroke(255);
  x = 0;
}
void draw() {
  background(50);
  line(x, 0, x, height);
  x = x + 1;
  if (width < x) x = 0;
}

18

More books: https://t.me/booksforits


Chapter 2 ■ The Processing Language

Figure 2-1. Output of the animated line sketch, running on a Pixel 4a phone

This continuous sequence of calls to the draw() function that Processing does automatically in any
interactive sketch is called the “animation loop.” Processing calls the draw() function during the animation
loop at a default frame rate of 60 frames per second; however, we can change this default using the function
frameRate(). For instance, if we add frameRate(1) in setup(), then the animation loop will draw 1 frame
per second.
Sometimes, we may need to stop the animation loop at some point. We can use the noLoop()
function for doing this and then the loop() function to resume the animation afterward. Processing
also has a boolean (logical) constant named looping, which is true or false depending on whether the
sketch is running the animation loop. We can build on top of our previous sketch to pause/resume the
line movement if the user clicks the mouse (on a desktop/laptop) or taps the touchscreen (on a phone),
as shown in Listing 2-2. This code introduces another new function from the Processing language called
mousePressed(), where we can put code that should be run only when the user presses the mouse (or taps
the touchscreen). We will see a few more interaction-handling examples in this chapter and then will
deep-dive into touchscreen interaction more specific for mobile development in Chapter 5.

Listing 2-2. Pausing/resuming the animation loop

int x = 0;

void setup() {
  fullScreen();
  strokeWeight(2);
  stroke(255);
}

void draw() {
  background(50);
  line(x, 0, x, height);
  x = x + 1;
  if (width < x) x = 0;

19

More books: https://t.me/booksforits


Chapter 2 ■ The Processing Language

void mousePressed() {
  if (looping) {
    noLoop();
  } else {
    loop();
  }
}

We can also write static sketches without setup/draw, which are useful if we only want to create a
fixed composition that does not need to be animated. Processing runs the code in these sketches only
one time. Listing 2-3 contains a simple static sketch that draws the white circle in Figure 2-2. Here, we
use the function ellipse() to draw a circle centered at coordinates (400, 400) and width and height equal
to 300 pixels (by setting different width and height values, we would get an ellipse of any proportions
we like.) We use the fill() function to paint the interior of the circle with a purple color. We also use the
size() function, which allows us to set the width and height of the output canvas. We apply this function
instead of fullScreen() if we only want to use an area of the device’s screen for drawing and interaction.
Processing will paint the pixels outside of the drawing area with a light gray color, as seen in Figure 2-2,
and we will not be able to change this color. Tapping on this area will not result in any interaction events
with the sketch.

Listing 2-3. Static sketch without setup() and draw() functions

size(1000, 1000);
background(255);
fill(150, 100, 250);
ellipse(500, 500, 400, 400);

Figure 2-2. Output of the static sketch in Listing 2-3

D
 rawing with Code
We just saw in the examples from the previous section how the Processing language allows us to “draw with
code.” Even though these examples were very simple, they already point to some general concepts for code-
based drawing in Processing. First, we need to specify the coordinates of the elements we want to draw on
the screen. Second, there are functions, such as line() and ellipse(), that allow us to draw various shapes

20

More books: https://t.me/booksforits


Chapter 2 ■ The Processing Language

by setting numerical values that define their form, size, and position. Third, we can set the visual “style” of
these shapes (e.g., stroke and fill color) by using functions like fill(), stroke(), and strokeWeight(). In
the next sections, we will delve into these techniques in more depth to learn how to draw different kinds
of shapes.

Coordinates
One of the most important concepts in code-based drawing is knowing how to locate points on the
computer screen using numeric coordinates. Processing draws the graphical output of our code into a
rectangular grid of pixels, numbered from 0 to width-1 along the horizontal direction (the x axis) and 0 to
height-1 along the vertical direction (the y axis), illustrated in Figure 2-3. As we saw before, we can set the
precise width and height of this grid by using the size() function with our desired values as arguments. If we
use the fullScreen() function instead, then the width and height of the grid will be automatically set to the
width and height of the entire screen of our device.

x-axis
0 1 2 ... width-1
0
1
2
y-axis

...
height-1
pixel (1, 2)

Figure 2-3. Diagram of the screen’s pixels

The X coordinates run from left to right, while the Y coordinates run from top to bottom. So the pixel
(0, 0) represents the upper left corner of the screen, and the pixel (width-1, height-1) represents the lower
right corner. The arguments of most of the 2D drawing functions in Processing refer to the pixel coordinates
of the screen. Processing also offers two internal constants, conveniently called width and height, that hold
the values we set in the size() function or determined automatically when using fullScreen(). The following
“toy” sample code, where we set a very small output size so we can see each single pixel, would produce the
output in Figure 2-4 (although the actual output of running this code on a computer would be so small that
we would likely not be able to differentiate its parts):

size(12, 8);
stroke(200, 0, 0);
fill(100, 200, 100);
rect(2, 1, width - 1, height - 2);

21

More books: https://t.me/booksforits


Chapter 2 ■ The Processing Language

Figure 2-4. Pixels covered by a stroked rectangle in Processing

We should set the size of the shapes we draw with Processing according to the constraints of the screen
size. In general, it is recommended to use the width and height constants when referring to the size of the
screen instead of entering predetermined values, because the width and height of our output will likely
change between devices, especially if we use the fullScreen() function. Even when we set the width and
height in the size() function, if we later change the arguments of size(), we would then need to go through
the code updating any references to the original width and height values. This won’t be necessary if we use
the width and height constants. The code in Listing 2-4 provides a demonstration of this technique. With this
code, we generate a rectangular checkboard of 4×4 by drawing rectangles that have size equal to a quarter
of the width and height of the output canvas. The result is shown in Figure 2-5, as it would appear on a Pixel
4a phone. If we change the values in size(1000, 1000) to something else, the result would still be a grid of 4×4
rectangles, because those rectangles will be resized automatically according to the value of width and height.

Listing 2-4. Using screen coordinates

size(1000, 1000);
noStroke();
fill(255);
background(0);
rect(0, 0, width/4, height/4);
rect(width/2, 0, width/4, width/4);
rect(width/4, height/4, width/4, height/4);
rect(3*width/4, height/4, width/4, height/4);
rect(0, height/2, width/4, height/4);
rect(width/2, height/2, width/4, width/4);
rect(width/4, 3*height/4, width/4, height/4);
rect(3*width/4, 3*height/4, width/4, height/4);

22

More books: https://t.me/booksforits


Chapter 2 ■ The Processing Language

Figure 2-5. Using screen coordinates to draw a grid of rectangles

Form
All the shapes we draw in Processing have a form in two or three dimensions. One way to think of a shape
is as a perimeter or boundary that separates the inside of the shape from the outside. We already saw that
Processing includes functions to draw common shapes such as rectangles or ellipses by providing the
coordinates of their center and size. Processing will automatically construct the perimeter of these shapes
for us. But to construct the perimeter of an arbitrary shape in Processing, we need to explicitly provide
the coordinates of the vertices alongside the perimeter. We can do this by listing the vertices between the
beginShape() and endShape() functions as shown in Listing 2-5, whose output is presented in Figure 2-6.

Listing 2-5. Using beginShape() and endShape()

size(600, 300);

strokeWeight(2);

// Draw a rectangle in the bottom of the screen


beginShape();
vertex(5, 250);
vertex(590, 250);
vertex(590, 290);
vertex(5, 290);
endShape(CLOSE);

// Draw a star-like shape in right side


beginShape();
vertex(330, 25);
vertex(390, 90);
vertex(510, 10);
vertex(460, 120);
vertex(510, 270);
vertex(410, 180);
vertex(310, 270);
vertex(360, 150);
endShape(CLOSE);

23

More books: https://t.me/booksforits


Chapter 2 ■ The Processing Language

// Draw a small triangle right above the star shape


beginShape();
vertex(350, 30);
vertex(410, 30);
vertex(390, 75);
endShape();

ellipse(70, 80, 70, 70);

Figure 2-6. Composition created by drawing several shapes

We can learn a few important lessons from this example. First, shapes are drawn on top of each other
according to the order they appear in the code; this is why the rectangle in the bottom, which is the first
shape to be drawn, is partially obstructed by the star-like shape, which is drawn afterwards. Second, shapes
can be open or closed. When a shape is open, the stroke line that goes around its perimeter will not connect
the last and the first vertices, as we can see in the triangle shape. But if we add the argument CLOSE in the
endShape() function, which is the case for the two first shapes, the stroke line will wrap around and result in
an uninterrupted boundary delineating the shape. Third, we can combine common (also called “primitive”)
shapes drawn with functions like ellipse() or rect() with arbitrary shapes drawn with beginShape/endShape.
By applying some basic trigonometry, we can draw shapes that are regular polygons. The vertices
alongside the perimeter of a regular polygon have coordinates x = r * cos(a) and y = r * sin(a), where
r is the radius of the circumference, sin() and cos() are the sine and cosine functions, and a is an angle
between 0 and 360 degrees (for a great intro/refresher about trigonometry, check Chapter 3 from Daniel
Shiffman’s book The Nature of Code, available online at https://natureofcode.com/book/chapter-3-
oscillation/). For example, in Listing 2-6, we draw three regular polygons: a square, a hexagon, and an
octagon.

Listing 2-6. Drawing regular polygons

size(900, 300);

fill(200, 100, 100);


beginShape();
for (float angle = 0; angle <= TWO_PI; angle += TWO_PI/4) {
  float x = 150 + 100 * cos(angle);
  float y = 150 + 100 * sin(angle);
  vertex(x, y);
}
endShape(CLOSE);

24

More books: https://t.me/booksforits


Chapter 2 ■ The Processing Language

fill(100, 200, 100);


beginShape();
for (float angle = 0; angle <= TWO_PI; angle += TWO_PI/6) {
  float x = 450 + 100 * cos(angle);
  float y = 150 + 100 * sin(angle);
  vertex(x, y);
}
endShape(CLOSE);

fill(100, 100, 200);


beginShape();
for (float angle = 0; angle <= TWO_PI; angle += TWO_PI/8) {
  float x = 750 + 100 * cos(angle);
  float y = 150 + 100 * sin(angle);
  vertex(x, y);
}
endShape(CLOSE);

Here, we use a for loop to iterate over the angle that gives us the polygon vertices alongside its
perimeter. In Processing, because it’s built on top of the Java language, we can use all the control structures
from Java (if/else, for, etc.) that we need for code-based drawing. So in this loop, we increase the angle
variable by a fraction of 2π (which is 360 degrees expressed in radians and represented in Processing by the
TWO_PI constant) until we go around the entire perimeter of the polygon, calculating its vertices with the
cos/sin formula at each value of the angle. We can see the output of this code in Figure 2-7.

Figure 2-7. Output of the polygon code example

Color
Color is a fundamental element of visual design, and Processing provides many functions to let us set
the color of the interior of our shapes (the fill color) and their edges (the stroke color), in addition to the
background color of the entire output canvas.
By default, we can set colors using RGB (red, green, and blue) values between 0 and 255, as illustrated
in the code of Listing 2-7 and its output in Figure 2-8. As we saw at the beginning of this chapter, if we pass
a single value to the background(), fill(), or stroke() function, we will get a gray color (with the extremes of
black and white when the value is 0 and 255, respectively). This is equivalent to passing the same number
(e.g., (0, 0, 0)) as the three RGB values.

25

More books: https://t.me/booksforits


Chapter 2 ■ The Processing Language

Listing 2-7. Setting fill and stroke colors using RGB values

size(600, 300);
strokeWeight(5);
fill(214, 87, 58);
stroke(53, 124, 115);
rect(10, 10, 180, 280);
stroke(115, 48, 128);
fill(252, 215, 51);
rect(210, 10, 180, 280);
stroke(224, 155, 73);
fill(17, 76, 131);
rect(410, 10, 180, 280);

Figure 2-8. Output of setting stroke and fill RGB colors

We can also set an optional fourth parameter in the stroke() and fill() functions. This parameter
represents the transparency or “alpha value” of the color and allows us to draw semitransparent shapes, as
it is demonstrated in Listing 2-8, with its output in Figure 2-9. If we are using a single number to paint with a
gray hue, Processing will understand the second parameter in stroke() or fill() as the alpha value.

Listing 2-8. Using color transparency

size(600, 600);

background(255);

fill(0, 0, 255);
ellipse(525, 300, 150, 150);

fill(0, 255, 0, 120);


ellipse(450, 300, 270, 270);

fill(255, 0, 0, 50);
ellipse(300, 300, 500, 500);

fill(255, 0);
ellipse(300, 300, 600, 600);

26

More books: https://t.me/booksforits


Chapter 2 ■ The Processing Language

Figure 2-9. Output of setting alpha values in fill()

As we have seen so far, we can draw shapes of different kinds (points, lines, polygons) and set not
only their fill and stroke color but other style attributes or parameters as well. We used the stroke weight
before, but there are many more attributes we will learn about later. We can think of these attributes as
“style parameters” that once they are set, they affect everything drawn afterward. For example, each circle
in Listing 2-9 has a different fill color, but if we comment out the second fill() call, then the first and second
circles will be red, since the fill color set at the beginning affects the first two ellipse calls. Figure 2-10 shows
the outputs of this sketch in these two situations, with the left half beginning the output with the second fill()
enabled and the right half showing the output of the second fill() commented out.

Listing 2-9. Setting the fill color attribute

size(460, 200);
strokeWeight(5);
fill(200, 0, 0);
stroke(255);
ellipse(100, 100, 190, 190);
fill(255, 0, 200); // Comment this line out to make second circle red
stroke(0);
ellipse(250, 100, 100, 100);
fill(0, 200, 200);
ellipse(380, 100, 150, 150);

27

More books: https://t.me/booksforits


Chapter 2 ■ The Processing Language

Figure 2-10. Effect of the calling order of the fill() function

Even though we can create almost any imaginable color using the RGB values, it can be hard to find the
right combination of numbers for the color we need. Processing includes a handy Color Selector tool to help
us pick a color interactively, which we can then copy into our sketches as RGB values. The Color Selector is
available, alongside any other installed tool, under the “Tools” menu in the PDE (Figure 2-11).

Figure 2-11. Color Selector tool

■■Note We can also specify colors in hexadecimal (hex) format, often used in web development, that is,
fill(#FF0000) or stroke(#FFFFFF). The Code Selector tool provides the selected color in hex format as well.

Applying Geometric Transformations


So far, we have learned how to draw shapes and paint them with fill and stroke colors. In addition to all
of this, Processing allows us to move our shapes around and change their size by applying translations,
rotations, and scaling transformations (Figure 2-12).

28

More books: https://t.me/booksforits


Other documents randomly have
different content
"No; the major did not say. He will probably send here for letters,
and then I can mention that you called."
Harry assented, not being able to explain that this would not answer
his purpose.
When he reported his information at home, Adeline said, quickly:
"He left because he does not want us to communicate with Philip."
"Probably," said Rose. "This shows," she added, "that he is afraid
Philip would be inclined to do something for us. I am glad to have
my faith strengthened in the boy, at all events. If he were willing to
live in luxury while he knew we were struggling with poverty I could
not regard him as a cousin."
The next morning Mr. Codicil read in the morning papers, among the
passengers who had sailed for Europe the day before, the names of
Major Grafton and Philip.
"The fellow has lost no time," he said to himself. "The boy is bright
and attractive, but he stands a chance of being spoiled under such a
guardian. I wish I had questioned him, and tried to learn something
of him. I might have given him some idea of the injustice which has
been practiced toward his poor cousins. I do not care so much that
he profits by it as that that worthless uncle of his should live in
luxury at their expense. I am afraid they are having a hard time."
How hard a time the sisters were having—how stern and exacting
was the toil which her sister's helplessness imposed upon Rose—Mr.
Codicil really had little idea. If he had, he would certainly have done
something to assist them, for he was a kind-hearted man; but
whenever Rose called upon him she was neatly dressed, and did not
bear outward marks of the poverty with which she had to contend.
So far as Nicholas Walton was concerned, he was glad, upon the
whole, to learn that his nephew had gone to Europe. He could not
see Ben without his conscience reproaching him with the wrong he
had done him, and was still doing him and his mother, by retaining
possession of a sum of money which would have given them
opulence in exchange for the poverty which was not removed by the
small allowance he sent them.
"Perhaps Major Grafton will adopt the boy," he said to himself, "and
then he won't need his father's money."
As if this would gloss over or excuse the base fraud of which he had
been guilty. He had knowingly and intentionally been the occasion of
his brother-in-law's sudden death, and was as much his murderer as
if he had plunged a knife into his breast, though his crime was less
brutal and revolting.
While these thoughts were passing through his mind, Clarence
entered the office.
"Clarence, your cousin has been here to see you," said Mr. Walton.
"What did he have to say, pa?"
"He came to bid you good-by."
"To bid me good-by? What for? Where is he going?"
"He is to sail for Europe this afternoon."
"To sail for Europe!" repeated Clarence, in amazement. "He didn't
say anything about it last evening."
"Because he did not know it. He was only told this morning."
"He's a lucky beggar!" said Clarence, enviously. "I've been longing to
go to Europe this ever so long. Percy Van Dyke spent last summer in
Switzerland. It annoys me to hear him talk of the splendid times he
had. Here is my country cousin going, while I have to stay at home."
"Don't worry, Clarence," said his father, encouragingly. "You shall go
in time. If your friend Percy should be going again, and will accept
you as a companion, I will let you go."
This somewhat cheered up Clarence, though with the natural
impatience of youth he wanted to go at once.
"I think I never knew a boy as lucky as Ben," said he.
"He certainly has been strangely fortunate," said Mr. Walton.
"He would have been glad to take a place in a store at five dollars a
week, and now he's got something ever so much better. I believe he
has more money than I to spend, and I am sure he dresses better."
"He seems to have made an impression upon this Major Grafton. I
shouldn't be surprised if Grafton adopted him. He has no family of
his own, and is, I imagine, very rich."
We know that on this last point Mr. Walton was misinformed. The
suggestion, however, was enough to excite the envy and jealousy of
Clarence.
"Do you think he will be richer than I?" he asked.
"You will be well provided for, Clarence. You won't have occasion for
envying your cousin, even if he should be adopted by Major
Grafton."
We have now to change the scene to the little town of Sunderland,
from which our hero had come to New York to seek the good fortune
which he so strangely found.
We direct our steps to a plain cottage, containing but four rooms
and an attic, which stood a little out of the centre of the village.
Small and plain as it was, it had an air of refinement and good taste,
with its climbing honeysuckles, tiny bed of flowers, its trimly-kept
lawn and neat surroundings, which are vainly sought about many
more pretentious residences.
Here dwelt Mrs. Baker and Ben's little sister, Alice, but ten years old.
She bore a strong family resemblance to Ben, and was equally good-
looking.
"It seems an age since Ben left home," said Mrs. Baker, with a little
sigh.
"I miss him dreadfully, mother," said Alice. "Why need he go away?"
"I can't blame him, Alice, though I am very sorry to have him go,"
said Mrs. Baker. "He is ambitious——"
"What does that mean?" asked Alice, puzzled.
"It means that he is anxious to get on in the world—to make money.
It is a natural feeling for a boy."
"He used to earn money here at home," said Alice.
"Only a little. No doubt he can do better in New York, if he can get a
chance. If his uncle will only help him——"
"I should think he might, mother. Ben is a good boy."
"There is none better," assented his mother, fondly; "but strangers
may not know that."
Just then a neighbor, driving by, paused in the road and called out to
the widow, whom he saw at the open window:
"Widder Baker, there's a letter for you at the post-office. 'Spect it's
from Ben."
"Go right over and get it, Alice," said her mother, excitedly.
Alice wasn't long in performing her errand. She came back well
rewarded, bringing with her two letters, one of which had arrived
the day before. The first letter contained an account of his cold
reception by his uncle, and on the other hand his good luck in
encountering Major Grafton. As an earnest of his good fortune he
enclosed three five-dollar bills.
"God has been very good to us!" said the widow, with beaming face.
"I can hardly believe in Ben's good fortune."
"Open the other letter, mother," said Alice.
Mrs. Baker did so, and, glancing over it rapidly, uttered a quiet
exclamation of surprise and dismay.
"Alice," she said, "Ben has sailed for Europe!"
"Gone to Europe, and without bidding us good-by!"
"He did not have any chance," and Mrs. Baker read Ben's letter.
When she came to think it over, she felt that Ben was, on the whole,
fortunate to have so good an opportunity of seeing the world; and
as to dangers and risks, God would take care of him abroad as well
as at home. She would have liked to have known the man who had
her boy in charge. Doubtless he must have taken a fancy to Ben, or
he would not have given him such a chance.
CHAPTER XV.
Filippo Novarro.
Nicholas Walton was well pleased with the good fortune of his
nephew. Though a selfish man, he was not wholly without a
conscience and a heart. He had always regretted the manner in
which he had possessed himself of the large sum of money which,
by enabling him to take a store on Broadway, and largely extend his
business, had allowed him to take a place among the foremost
merchants of New York. He would have preferred to compass his
own fortune without bringing ill-fortune to his brother-in-law, but if
the thing had to be done again, under the same circumstances, he
would probably have yielded to the same temptation.
"Ben appears to be a smart, attractive boy," said Walton to himself.
"He is likely to make his own way in the world, especially in his
present position. I dare say it is better for him to have lived plainly,
and nourished self-reliance, than to have been reared in luxury.
Then, as to the fortune, Doctor Baker was a man of very little
business shrewdness. He would have wasted the money in bad
investments, and, ten to one, not a dollar of it would have remained
at the present time."
All this Nicholas Walton said to quiet his conscience, but without
success. Many a time, especially in the silent watches of the night,
memory revived for him that scene, which he would so gladly have
forgotten, when his ill-fated brother-in-law died in a fit of agitation
brought on by Walton intentionally. He could see himself once more
rifling the pockets of the dead man, and converting to his own use
the money which would have made the physician and his family
prosperous and happy.
These disquieting thoughts he tried to get rid of. He tried to
persuade himself that he was wholly disinterested in his good wishes
for his nephew. By way of keeping up the illusion he snatched five
minutes from his business, and wrote the following letter of
congratulation to his sister:

"My Dear Sister:—Benjamin has no doubt apprised you of his


success in obtaining a profitable engagement, and of his
departure for Europe. He has also, perhaps, told you that I was
opposed to his remaining in the city. I admit that I thought it
would have been better for him to remain in Sunderland and
obtain a practical acquaintance with farming, in which case I
would, at the proper time, have set him up on a farm of his
own, for I hold that the farmer is the only truly independent
man. A merchant may be rich to-day and a bankrupt to-morrow,
and that in spite of the utmost care and prudence. However, I
won't dwell on this subject. I am willing to admit that I did not
give my nephew credit for the energy and ability he has shown.
Though I refused to help him, further than to pay the expenses
of his trip to the city, on condition of his returning home at
once, he remained and succeeded in commending himself to the
favor of a rich man who has given him an excellent position,
and will probably—for he seems to be eccentric—finally
conclude to adopt the boy.
"It is needless to say that I could not have anticipated such
extraordinary luck for Benjamin, and that I am glad he followed
his own counsel and remained in the city. Doubtless a better
fortune awaits him than the life of a farmer, which, though
independent, is laborious. I only write now to congratulate you
upon his success, and to express my interest in him. Though
you will no doubt miss him, I think you will be able to see that
he has done the best thing for himself and for you in the
engagement which he has made with Major Grafton. He would
have dined at my house to-morrow, but for his sudden
departure.
"I inclose my next month's allowance a little in advance.

"Your affectionate brother,


"Nicholas Walton."

Mrs. Baker was surprised and gratified on receiving this unusually


long letter from her brother Nicholas. She had been wounded at the
cool reception which he had accorded to Ben, as detailed in the
letter of the latter, but this letter put a new face on the matter.
"After all, Nicholas feels an interest in Ben," she said to herself, "and
no doubt he acted for what he thought the best in the advice he
gave him to remain in Sunderland and become a farmer. He
acknowledges his mistake very handsomely."
So upon the spur of the moment she wrote her brother a letter,
acknowledging gratefully his kindness to her boy, and asking for a
continuance of it.
This letter was received by Mr. Walton with satisfaction. It made it
easier for him to feel that he had not, after all, wronged his sister
and her family as much as his conscience sometimes reproached him
with.
"Would that I could lose all the memories of that dreadful hour!" he
said to himself, with a shudder.
But he did not find that so very easy. It was destined to be recalled
to him in a startling manner within a week.
As he sat in his office the following Thursday, a clerk entered.
"Mr. Walton," he said, "there is a foreign gentleman in the store who
wishes to see you."
"Is it a stranger?"
"Yes, sir."
"He wishes to see me on business, doubtless. You may bring him
in."
The visitor entered—a man of medium size and swarthy complexion
—who would be taken at first sight for a Spaniard or a Portuguese.
Nicholas Walton regarded him with a look of inquiry.
"Do I speak to Mr. Walton?" asked the stranger, in good English, but
with a foreign accent.
"I am Mr. Walton," answered the merchant.
"You are brother-in-law to Mr.—I beg pardon, Doctor Baker?"
"Ye-es," answered the merchant, with a startled look.
"Can you tell me if the good doctor is well?"
"He is—dead!" replied Walton, slowly. "Did you know him?"
"I much regret to hear of his death. I did not know him, but I met
him once."
"This must be the man who gave him the bonds," thought Walton,
trying to conceal his perturbation. "The moment and the man I have
so long dreaded have arrived. Now, Nicholas Walton, you require all
your coolness and nerve."
"May I ask when that was?" he asked, with apparent unconcern.
"Five years ago. I was the agent for conveying to him a large sum in
securities bequeathed him by my uncle, to whom he had rendered a
great service."
"Indeed! I am most glad to see you, sir. I wish my brother-in-law
were alive to give you personal welcome."
"When—did he die?"
"But a short time after you met him. He died instantly—of heart
disease."
"He left a wife and child, did he not?"
"He left a wife and two children."
"And they live?"
"Yes."
"I wish I could see them."
Nicholas Walton was perplexed and alarmed. If the stranger should
see Mrs. Baker, his elaborate scheme would fall to the ground and
he would be called upon for an explanation.
"Do you remain long in the city?" he asked.
"I go to Havana in three days. Business of importance, not to
mention the sickness of my brother, calls me there."
"Ah!" said the merchant, relieved. "You will have to defer seeing Mrs.
Baker, then."
"I thought she might live near by," said Filippo Novarro, for such was
the name he gave.
"Two years ago she removed to Minnesota," said the merchant, with
fluent falsehood. "Her son, however, is travelling in Europe."
"That, at least, will look as if she retained her fortune," he said to
himself.
"Then I must not hope to meet her," said Novarro. "When you write,
will you give her my profound respects?"
"With pleasure, Señor Novarro," said Walton, briskly. "Can I be of
any service to you personally?"
"Thank you, sir, no. I shall be very busy till I leave the city."
"Then let me express my pleasure in meeting you," said Walton,
offering his hand.
"The pleasure is mutual, Mr. Walton, I assure you," said the stranger,
bowing low.
"Thank Heaven, I have got rid of you," said Walton to himself,
wiping the perspiration from his brow. "But shall I always be as
lucky?"
CHAPTER XVI.
On Board The Parthia.
"Am I really on the Atlantic, bound for Europe?" said Ben to himself,
as he paced the deck of the Parthia, then several hours out.
He found it hard to realize, for only a week before he had been in
his quiet country home, wholly unconscious of the great change that
fate had in store for him.
He was not unfavorably affected by the new sea-life. Instead of
making him sick, it only gave him a pleasant sense of exhilaration.
With Major Grafton it was different. He was a very poor sailor. He
was scarcely out of port before he began to feel dizzy, and was
obliged to retire to his state-room. He felt almost irritated when he
saw how much better Ben bore the voyage than he.
"One would think you were an old sailor, instead of me," he said. "I
have crossed the Atlantic a dozen times, and yet the first whiff of
sea air lays me on my back, while you seem to enjoy it."
"So I do at present," answered Ben; "but perhaps my time will come
to be sick. Can't I do something to make you comfortable?"
"You may tell the steward to bring some ginger ale," said the major.
Ben promptly complied with the major's request. He felt glad to do
something to earn the liberal salary which he was receiving. It was
not exactly acting as a private secretary; but, at any rate, he was
able to be of service, and this pleased him. He had no complaint to
make of Major Grafton. The latter saw that he wanted for nothing,
and had he been the major's son he would have fared no better. Yet
he did not form any attachment for his employer, as might have
been thought natural. He blamed himself for this, when he
considered the advantages of his position; but it was not so strange
or culpable as Ben supposed. The boy saw clearly that, whatever
might have been Major Grafton's motives in taking him into his
service, it was not any special interest or attachment. The reader
understands that Grafton had a purpose to serve, and that a selfish
one. For Ben he cared nothing, but his own interest required that he
should have a boy with him as a substitute for the one whose death
he wished to conceal, and our hero filled the bill as well as any he
could secure.
One day, while Major Grafton was in his state-room, enduring as well
as he could the pangs of sea-sickness, a gentleman on deck
accosted Ben:
"You seem to enjoy the voyage, young man," he said.
"Yes, sir; very much."
"You are not alone?"
"No; I am travelling with Major Grafton."
"Indeed!" said the gentleman, in surprise. "I didn't know the major
was on board. Where does he keep himself?"
"He seldom leaves his state-room. He has been sick ever since he
started."
"I remember meeting the major last summer in Switzerland. You
were sick at the time, but from your present appearance I judge that
you got bravely over it."
"I think you are mistaken, sir. I was not with Major Grafton at that
time."
"You were not! That is strange. Surely there was a boy with him; I
remember he called him Philip."
"He calls me so, but that is not my name."
"Do you mean to say that you were not with the major at that
time?"
"I did not know there was such a man at that time."
"Humph! I don't understand it," said James Bolton (this was the
traveller's name). "I do remember, however, hearing that the boy,
then called Philip, died at Florence."
"I think that settles it," said Ben. "Whoever the poor fellow may
have been that died, I am sure that it was not I."
"Are you Major Grafton's adopted son, or ward?"
"No, sir; I am his private secretary. That is, I was hired in that
capacity, though as yet I have not had much writing to do."
"You are lucky. Take care you don't die, like the other boy."
"I will try to live, I assure you, sir."
"By the way, just mention my name to the major—James Bolton, of
London. I dare say he will remember me. Just say that I occupied
the room opposite his in the Hotel des Bergues, in Geneva, and that
we went to Chamounix together. I should be glad to renew my
acquaintance with him, whenever he feels well enough to come on
deck."
"I will mention you to him, Mr. Bolton," said Ben, politely.
Our young hero took an early opportunity of keeping his promise.
On his next visit to the state-room he said:
"Major Grafton, I met a gentleman on deck this morning who wishes
to be remembered to you."
"Who is it?" asked the major, quickly, raising his head from the pillow
of his berth.
"He says his name is Bolton—James Bolton, of London."
"Don't know him!" said the major, shortly.
"He says that he was with you at the Hotel des Bergues, in Geneva,
Switzerland, last summer; also that he went with you to
Chamounix."
"What else did he say?" asked the major, who seemed unpleasantly
affected by the mention of Bolton's name.
"He thought I was with you at the time."
"Ha! What did you say?"
"I told him he was mistaken."
"Don't tell these fellows too much; they are simply impertinent," said
the major, with a frown. "What more did he say?"
"He said you had a boy with you whom you called Philip, and that
this boy, as he afterward heard, died at Florence."
Ben looked inquiringly at the major, as if to obtain confirmation or
denial of this story.
Major Grafton hesitated, as if not decided what to say.
"It is true," he said, after a pause. "Poor Philip died; but it is a
painful subject. I don't like to speak of it. You resemble him very
closely, and that was my chief object in taking you as a companion. I
don't really need a private secretary, as you have probably found
out."
"I wish you did, sir. I would like to do something to earn my wages."
"Don't trouble yourself on that score. It suits me to have a
companion; I hate being alone. As long as you conform to my
wishes, I will provide for you."
"Thank you, sir."
"But hark you, Philip! I don't care to have you talk too much to
strangers about me or my affairs. Now, as to this man Bolton, I
prefer that you should keep him at a distance. He is not a fit
companion for you."
"Is he a bad man?" asked Ben, in some surprise, for Bolton had
seemed to him a very respectable sort of man.
"He is a thoroughly unprincipled man," answered the major,
emphatically. "He is a confirmed gambler, and is cultivating your
society because he thinks you may have money. He is trying to lead
you into a snare."
"Then I was deceived in him," said Ben, indignantly, for it didn't
occur to him to doubt the positive statement of Major Grafton.
"Quite natural, Philip," said Grafton, pleased with having aroused the
boy's suspicions of a man who might impart dangerous information.
"Of course, I needn't suggest to you to keep the man at a distance. I
do not care to have you come under his influence."
"I shall bear in mind what you say, sir," said Ben.
"I think I have checkmated this meddling Bolton," said the major to
himself, in a tone of satisfaction.
When, a few hours later, Bolton approached Ben and asked: "Have
you spoken to Major Grafton about me?" Ben coldly answered, "Yes,
sir."
"Did he remember me?" questioned Bolton.
"Yes, sir."
"I thought he would. Are we likely to see him on deck soon?"
"No, sir, I think not."
Ben spoke so coldly that Bolton regarded him with a puzzled look.
He could not help seeing that the boy did not care to continue the
conversation, and, with a bow of farewell, joined another passenger
in a promenade.
"I should like to have asked him a little more about the boy I am
succeeding," thought Ben; but he respected the major's wishes, and
kept aloof from Bolton for the remainder of the voyage.
CHAPTER XVII.
The Beauforts in Trouble.
There was an anxious look on Rose Beaufort's pleasant face. She
and her young brother were the only bread-winners in the family,
and work as hard as they might it was very difficult to make both
ends meet. But for one item they could have managed with strict
economy, but that item—the rent—was a formidable one. They hired
their humble apartment of a Mrs. Flanagan, who leased the whole
floor, and agreed to pay two dollars a week. This woman was a
coarse, selfish person, whose heart was as hard and unfeeling as her
face and manners were unprepossessing.
One Monday morning, about two months after Ben's departure for
Europe, the landlady knocked at the door of the two sisters.
"It's Mrs. Flanagan," said Rose, with a troubled look, recognizing her
knock. "She has come for her rent, and I have but fifty cents toward
it."
"Perhaps she will wait," suggested Adeline; but her voice was not
hopeful.
"Come in!" said Rose.
"You were mighty long tellin' me to come in," grumbled the landlady,
as she entered the humble room, with a hostile look.
"I am sorry if I kept you waiting," said Rose, gently.
"I thought maybe you didn't want to see me," said Mrs. Flanagan. "I
won't stay long to trouble ye."
"Stay as long as you like," said Rose in a conciliatory manner.
"I didn't come for any palaver—I haven't the time. I suppose you
know what I came for. You haven't forgot it's Monday mornin'?" said
the landlady, in an aggressive tone.
"I didn't forget it, Mrs. Flanagan, but I am afraid I shall have to
disappoint you this morning."
"Do you mane to say you haven't got my rint ready?" demanded
Mrs. Flanagan, her red face becoming still more inflamed with anger.
"Indeed, Mrs. Flanagan, it isn't my fault," pleaded Rose. "I've got
fifty cents toward it, and if—"
"Fifty cints! What's fifty cints?" exclaimed the landlady, angrily. "Can
I pay my rint wid fifty cints? It's a shame—that it is—for you to chate
a poor hard-workin' woman, and a widder besides."
"My sister never cheats anybody," said Adeline, indignantly.
"Hoity-toity! So it's you that are spakin', is it?" said Mrs. Flanagan,
with her arms akimbo. "You can talk, anyway, if you can't work. All
you do is to sit here all day long, while your sister is wearin' out her
fingers wid the needle."
It was a cruel blow to the poor girl, who needed no reminder of
what she often thought about with bitter regret and mortification.
She did not retort angrily, but, turning sadly to her sister, said:
"I am afraid it's true, Rose; I am only a burden and an expense to
you. I do nothing to help you."
Now it was Rose's turn to be angry.
"Are you not ashamed, Mrs. Flanagan, to twit my poor sister with
what is her misfortune, not her fault?" she exclaimed, with flushed
face and sparkling eyes. "She would gladly work, if she could."
"It's ashamed I'm to be, am I?" retorted Mrs. Flanagan, viciously. "I
pay my bills, anyhow, and it's ashamed I'd be if I didn't. I don't want
no more talk from the like of you. It's money I want."
"Here are fifty cents, and I will try to get you the rest to-day," said
Rose, sadly.
"Them that wear gold rings can pay their rint, if they want to," was
Mrs. Flanagan's parting shot, as she slammed the door behind her.
Rose looked at the plain gold ring on her finger. It had been her
mother's ring, and for that she valued it above its intrinsic value.
"I can't part with this," she murmured, with moistened eyes. "Yet, is
it right to keep it when we owe money?"
"Don't part with mother's ring, whatever you do, Rose," said her
sister, hastily.
"But have we a right to keep it?" asked Rose, doubtfully.
"Yes, a thousand times, yes! That woman can wait for her money.
We cannot part with this legacy of our dying mother."
"But she may put us out into the street," said Rose, shuddering.
"Is there nothing else by which we can raise money?" said Adeline,
realizing their situation.
"Money is due me for two vests. As a general thing, Walton & Co.
don't pay me till I hand in half a dozen, but perhaps they would
make an exception in this case."
"That would be but seventy cents. It would not make up what we
owe Mrs. Flanagan."
"It might induce her to wait for the rest," said Rose. "If you don't
mind staying alone a little while, Addie, I will wrap them up and
carry them to the store."
"Go, if you like, Rose. I always miss you, but I cannot expect to keep
you here with me all the time."
Rose wrapped up the two completed vests, and putting on her hat,
kissed her sister and went down stairs.
It was not far to the great store, which we have already entered
with Ben.
Entering, Rose walked to the back part of the store and took the
elevator to the second floor, where she found the superintendent of
the work-room.
She made known her request.
"Quite out of the question, miss," said the superintendent, sharply.
He was a hard-featured man, who was a good man of business, but
was not open to sentimental consideration.
"Didn't you know our rules?" he asked.
"Yes, sir; but this was a case of necessity."
"I beg your pardon, miss, it is a matter of business. When you have
finished the batch we will pay you, and not till then."
"But, sir, I need the money very much."
"That is your affair, not ours. Probably you have friends and can
borrow money, if you need it sooner than we are ready to pay it to
you."
"I don't know where to find them," thought Rose, but she did not
say this.
The superintendent had already turned away, as if to intimate that
he had no more time to give her. Rose walked to the elevator slowly
and sadly, and descended to the main store.
"What shall I do?" she thought. "Mrs. Flanagan will turn us out, and
then poor Addie will suffer."
As she stepped out into the street the thought of the ring came back
to her. It was dear to her as a cherished legacy from a mother early
lost and deeply mourned, yet it had a money value which would
relieve their pressing necessities for a week at least.
"I don't think mother would wish me to keep it under the
circumstances," she thought. "Addie will scold me, but it appears to
be the only thing that remains for me to do. Heaven knows that I
don't wish to part with it."
The proper place to go would have been to a pawnbroker's shop,
but Rose did not know of one. She had never had dealings with any.
As she passed a jewelry store it occurred to her that perhaps they
would buy it inside, and she entered.
"In what way can I serve you, miss?" asked a young man behind the
counter.
"I—I wish to dispose of a ring," said Rose, hurriedly. "Can you tell
me the value of it?" and she slipped the ring from her finger and
offered it to the salesman.
"We don't buy second-hand jewelry," said the clerk, rudely. "We sell
rings here; don't buy them."
"Then would you be kind enough to lend me two dollars on it till—till
next week?" entreated Rose. "It must be worth much more than
that."
"It doesn't matter how much it is worth," said the clerk. "We ain't in
that line of business. You don't suppose we keep a pawnbroker's
shop, do you?" and he laughed contemptuously, glancing at a tall
lady who stood beside Rose and had listened attentively to the
conversation, as if inviting her to enjoy the joke with him.
"Then perhaps you will direct me to a pawnbroker's," said Rose, ill at
ease.
"Oh, you can go find one on the Bowery," said the clerk, carelessly.
"Now, madam," turning to the tall lady, "what can I show you?"
His tone was much more respectful than the one he employed in
speaking to Rose, for the lady, though far from beautiful, and no
longer young, was handsomely-dressed, and had the appearance of
being wealthy.
"You can't show me anything to-day, young man," said Miss Jane
Wilmot, for it was she. "I wish to speak to this young lady. My dear,
come out of the store with me. I wish to ask you a few questions."
The clerk arched his brows in surprise and disappointment as his
hoped-for customer walked away without purchasing anything,
followed by Rose.
Welcome to our website – the perfect destination for book lovers and
knowledge seekers. We believe that every book holds a new world,
offering opportunities for learning, discovery, and personal growth.
That’s why we are dedicated to bringing you a diverse collection of
books, ranging from classic literature and specialized publications to
self-development guides and children's books.

More than just a book-buying platform, we strive to be a bridge


connecting you with timeless cultural and intellectual values. With an
elegant, user-friendly interface and a smart search system, you can
quickly find the books that best suit your interests. Additionally,
our special promotions and home delivery services help you save time
and fully enjoy the joy of reading.

Join us on a journey of knowledge exploration, passion nurturing, and


personal growth every day!

ebookmasss.com

You might also like