nature-of-code / noc-book-2 Goto Github PK
View Code? Open in Web Editor NEWThe 2024 edition of The Nature of Code with p5.js. Includes Notion workflow and build system.
Home Page: https://natureofcode.com
The 2024 edition of The Nature of Code with p5.js. Includes Notion workflow and build system.
Home Page: https://natureofcode.com
@jasongao97 I think I probably once said to skip bringing chapter 5 to notion b/c I need to rewrite it, but maybe it's best to import as a starting point.
As of now, my plan is to replace box2d with matter.js, and keep toxiclibs (using toxiclibs.js?) But I may consider removing toxiclibs if it's not actively maintained.
Thoughts or comments appreciated!
(Also I plan to swap the order between 5 and 6.)
I sometimes say "p5" and sometimes "p5.js" when referring to the aforementioned library. I should probably be consistent. I lean towards using "p5.js" everywhere?
There are many artists that have worked with attractors over the years to create patterns. What are some examples I can include that represent a diversity of work and artists?
<p>
In the example above, there is a system (i.e. array) of
<code>Mover</code> objects and one <code>Attractor</code> object. Build
an example that has systems of both movers and attractors. What if you
make the attractors invisible? Can you create a pattern/design from the
trails of objects moving around attractors? See the <a
href="http://processing.org/exhibition/works/metropop/">Metropop
Denim project by Clayton Cubitt and Tom
Carden</a> for an example.
</p>
I had some time on a flight today to start playing around with the table of contents. At some point I might make individual issues to track smaller items, but here's a list of some general stuff.
includes/toc.html
to parse the toc object? Or use CSS to hide elements? For example, I don't want want third level headers to appear. (Or do I?).(FYI I'm using dev-shiffman.json
as my test TOC generator.)
@alterebro if you want to start playing around with the CSS to do cleanup and match styles, go right ahead.
I'm thinking about utilizing p5-web-editor
's API (e.g. https://editor.p5js.org/editor/codingtrain/projects/JmEToUfk) to fetch and download example codes during website build time (or import time, depending on whether we want it to be tracked by git). So they can be served at the same place as the website with customizations. it could be in subfolders like content/examples/Nature_of_Code_1:_Vectors_1
.
In this way, only a p5 editor link bookmark need to be added to the Notion callout block
.
In revising for p5.js, I have the option of using var
, let
, or const
. var
is out as I'd like the book to use ES6+, however, the question remains as to whether for readability and alignment with p5.js to skip const
. I'll leave this open for now as it can be a global change later on. If I use const
I'll want to include a brief explanation, probably in the intro.
Example that could use const:
function step() {
//{!2} Yields -1, 0, or 1
let xstep = floor(random(3)) - 1;
let ystep = floor(random(3)) - 1;
x += xstep;
y += ystep;
}
The first edition of the book came with some exercise solutions (not all). Picking up on the conversation from #54, I'm filing an issue (for later) to develop a way to either include exercise solutions in the book text itself or separate repo.
A lot has changed.
I am switching some examples in chapter 6 to use p5.Vector.fromAngle()
. I should check and see if this is mentioned in chapter 3 and if not, add in a mention!
Making a note that I am adding a reference to QuadTrees in chapter 6. Edits happening in #98.
I already posted this in the Discord but I feel like this is a better place to put this so I'm reposting it here
So in the section with the random walk, you say any given pixel has 8 neighbors. This is sort of correct, but it really depends on what you define as a neighbor. You could define a neighbor as an orthogonally adjacent square and that would be just as correct
This particular code snippet is wrong:
// 1 and 3 are stored in the array twice, making them more likely to be picked than 2.
let stuff = {1, 1, 2, 3, 3};
// Picking a random element from an array
let value = random(stuff);
print(value);
You have to use square brackets, also I would use console.log
but if you want you can use print
it doesn't really matter
In I.4 you just refer to a simulation of monkeys that doesn't even exist. Like...you never even introduced it
Then there's this paragraph:
The y=x
graph is actually wrong. The probability of any given value being picked is actually zero. What this graph actually is is what's called a "probability density function" (PDF). It doesn't show what the probability is of any one value being picked, it just shows the proportions of those probabilities. That's still not an entirely accurate description but you get what I mean
The beginning of chapter 1 still has the old division scheme for the book: the first 5 chapters are about physics, the next 3 about complexity, and the final 2 about intelligence. I'm not saying this is wrong, but especially with swapping chapters 5 and 6, I feel like you're moving to a different system: the first 6 chapters about physics, and the final 4 about...other things
Chris Sears posted a thing:
Puts on math teacher hat
From the introduction: "Technically speaking, the random number picked can never be 4.0, but rather the highest possibility is 3.999999999 (with as many 9s as there are decimal places)..." Since 3.9999..... = 4.0, you may want to sidestep this part. One possible edit could be: "Technically speaking, the random number picked can never be exactly 4, but numbers like 3.9, 3.99, or 3.999999999 are possible."
Is there a GitHub repository for the book? Sorry I missed the live stream where you talked about the book. I feel like a student who missed class.
Takes off teacher hat and puts on dunce cap
This is the famous 0.99999... = 1 theorem. In case you haven't seen it before, here is an algebraic proof:
Let's call 0.99999... X
X = 0.99999...
Multiply by 10
10X = 9.99999...
Subtract
9X = 9
Divide by 9
X = 1
And here's an intuitive proof:
True thing about the real numbers: take two numbers. Unless they're the same, there must be a number greater than one and less than the other (e.g. take the average)
Can you name a number which is in between 0.99999... and 1? You can't, it's impossible. From the above, it thus logically follows that 0.99999... and 1 are the same
Finally, not a mistake but an idea (not saying you should do this but I just feel like it makes sense): what if you call the intro chapter chapter 0? Everything in code starts at 0 anyway, so I feel like this would be a good idea
Chapter 4 covers for of
loops and also mentions higher order functions like filter()
. I may want to mention the existence of forEach()
and for in
as well which often cause confusion.
My explanation about the multiplying the angular acceleration by -1 has some flaws according to this discussion on Khan Academy: https://www.khanacademy.org/computing/computer-programming/programming-natural-simulations/programming-oscillations/a/trig-and-forces-the-pendulum?qa_expand_key=ag5zfmtoYW4tYWNhZGVteXIlCxIIVXNlckRhdGEYqMN5DAsSCEZlZWRiYWNrGICAgJiazIUKDA
<a data-primary="oscillation" data-secondary="on two axes" data-type="indexterm"></a>
<div data-type="exercise" id="chapter03_exercise1">
<div data-type="example">
<figure class="screenshot" data-p5-sketch="https://editor.p5js.org/embed/rJkWNeWOx">
<img alt="ch03 ex07" src="chapter03/ch03_ex07.png" />
<figcaption> </figcaption>
</figure>
See: #79 (comment)
When p5 version is completed:
ask them to add rel canonical tags to their pages. That will tell google that even though the content is on khan, it’s originally from your site
https://www.khanacademy.org/computing/computer-programming/programming-natural-simulations
<link rel="canonical" href="________"/>
TBD
Can we have two sources file for the PDF and the website build?
So they can be optimized for each build and don't need to worry about compatibility
It's also easier to have markdown frontmatter storing other database attributes for route generating, etc.
<!-- chapter_2_forces.html -->
<h1>Chapter 2. Forces</h1>
<blockquote data-type="epigraph">
<p>“Don’t underestimate the Force.”</p>
<p>— Darth Vader</p>
</blockquote>
<div data-type="example">
<h5>Example 1.1: Bouncing ball with no vectors</h5>
<figure>
<img src="https://cdn.jsdelivr.net/gh/nature-of-code/noc-book-2/context/noc_html/imgs/chapter01/ch01_ex01.png" alt="If you are reading this book as a PDF or in print, then you will only see screenshots of the canvas. Motion, of course, is a key element of the discussion, so to the extent possible, the static screenshots will include trails to give a sense of the behavior. For more about how to draw trails, see the code examples linked from the website.">
<figcaption>If you are reading this book as a PDF or in print, then you will only see screenshots of the canvas. Motion, of course, is a key element of the discussion, so to the extent possible, the static screenshots will include trails to give a sense of the behavior. For more about how to draw trails, see the code examples linked from the website.</figcaption>
</figure>
</div>
<!-- chapter_2_forces.md -->
---
title: Chapter 2. Forces
slug: "02_forces"
---
> “Don’t underestimate the Force.”
> — Darth Vader
<example example-path="chp01_vectors/NOC_1_01_bouncingball_novectors/" p5-editor-url="https://editor.p5js.org/codingtrain/sketches/_HHLfcGx" />
When I run magicbook build
I get the following error:
Required file: stylesheets cannot be found
Cannot register permalinks . stylesheets:insert not found
Cannot register katex:setup . stylesheets:move not found
Error: Cannot find module '/Users/shiffman/Repos/noc/noc-notion/node_modules/stylesheets'
It appears to be looking for the stylesheets in node_modules
rather than in the root directory of the repo (where they are!)?
@jasongao97 @43-stuti do you also get this error or is this something perhaps related to my own local set-up?
This will certainly need to become multiple, smaller issues, but filing one now just to remember the following:
I would really love to add a flipbook animation to the margins of the print book!
Note to self to add additional example and explanation after I.5 with a "pool selection" algorithm (https://youtu.be/816ayuhDo0E). I will also swap in this algorithm in the Genetic Algorithm chapter 9 examples to improve the selection process.
Hi Dan! I'm thinking about two ways of arranging the project. We can either separate the three parts(node script for fetching data from notion to create local HTML files / magicbook pdf build / gatsby website build) into three node.js packages/modules or create one big project with all the scripts and logic. Which one do you prefer?
├── content/
│ ├── html/
│ ├── images/
│ ├── package.json
│ └── scripts/
├── pdf/
│ ├── magicbook.json
│ └── package.json
└── website/
├── gatsby-browser.js
├── gatsby-config.js
├── gatsby-node.js
├── package.json
└── src/
├── content/
├── magicbook/
│ ├── layouts
│ └── stylessheets/
├── scripts/
├── src/
│ ├── components/
│ ├── pages/
│ └── styles/
├── gatsby-browser.js
├── gatsby-config.js
├── gatsby-node.js
├── magicbook.json
└── package.json
From: @hardmaru "maybe applying genetic algos to evolve neural nets can be a way to wrap up the last 2 chapters of #natureofcode?"
http://blog.otoro.net/2015/05/07/creatures-avoiding-planks/
https://twitter.com/hardmaru/status/596446184673185793
There is a small issue in section 2.8 Air and Fluid Resistance: the computed instantaneous drag force can be so large that it causes objects to bounce. This can be disconcerting to readers who try out the code and experiment with different settings and wonder what they did wrong! So it would be helpful to describe the issue: the simulation goes in steps and the large computed drag force is instantaneous and doesn't last the entire step. There is an easy solution: the drag force will cause an object to stop, but never to change direction, so just add a line to limit the drag force to mover.velocity.mag() * mover.mass if the applyForce function divides by the mover's mass, or to mover.velocity.mag() * mover.mass if it doesn't.
The random walker example is biased towards the top left (or at least the original Processing example was.) This gets asked a lot so I should check the new p5 examples and address this as necessary. See: nature-of-code/noc-book#134
The old Processing wiki with more info no longer exists, I should build out the example and include it as part of the book itself.
the book says the 3d examples are online so i either need to make them or take this out.
Noting that in my examples I just use a multiplier to tie radius to mass.
this.radius = mass * 8;
Another, perhaps more accurate, way to approach this would be to consider surface area as corresponding to mass which would involve taking the square root (area = πr²
).
this.radius = sqrt(mass) * 8;
This would need to be addressed in the text and examples.
Just filing an issue to track implementing an index which I believe is the only remaining item for the PDF build?
Maybe a more environmentally friendly scenario would be nice? Or weave something in about sustainability and public transportation, etc.
Feedback: Complex systems often include a
feedback loop where the output of the system is fed back into the
system to influence its behavior in a positive or negative direction.
Let’s say you drive to work each day because the price of gas is low.
In fact, everyone drives to work. The price of gas goes up as demand
begins to exceed supply. You, and everyone else, decide to take the
train to work because driving is too expensive. And the price of gas
declines as the demand declines. The price of gas is both the input of
the system (determining whether you choose to drive or ride the train)
and the output (the demand that results from your choice). I should
note that economic models (like supply/demand, the stock market) are
one example of a human complex system. Others include fads and trends,
elections, crowds, and traffic flow.
Picking up on comments from @alignedleft in this thread: nature-of-code/The-Nature-of-Code-archive#350 I now have the following in edition 2:
Any feedback @alignedleft?
This is a reminder of the missing handler for the example callout.
An aerodynamic Lamborghini, for example, will experience less air resistance than a boxy Volvo. Nevertheless, for a basic simulation, I will consider the object to be spherical and ignore this element.
Dated reference or charming? Maybe something less sports-car-y would be nice here.
nature-of-code/The-Nature-of-Code-archive#301
In some Nature of Code examples regarding group steering behaviors (Chapter 6) I noticed that, for averaging the velocity of all the vehicles/boids at play, you do some vector math in sequence:
sum.div(count);
sum.normalize();
sum.mult(maxspeed);
but, since all the functions act on the vector as a scalar, the last function of the three will ultimately set the magnitude of the vector to a determined value, the result of the previous two will be useless.
Maybe we could map the magnitude of sum.div(count) to something btw a minimum value and "maxspeed", or just limit it to "maxspeed"?
I get a lot of inquiries regarding translation, should write up a quick FAQ to point people towards.
Almost all of the objects in the book are drawn with ellipse()
. As I am going through I am removing the 4th argument since p5 supports 3 arguments (x, y, diameter)
for ellipse()
. I could also consider using the new-ish circle()
method.
This issue is both a question as well as a reminder to do a global pass over the book for consistency with whatever decision is reached.
Add paragraph with additional info about Perlin noise (fractal vs. value vs. gradient vs. simplex), improved perlin noise, simplex noise, and OpenSimplexNoise. (explanation: https://youtu.be/Lv9gyZZJPE0)
It looks like the build is pulling some images from the NOC Book 2 repo. When we first started this repo it was a speculative exploration of working with Notion. Now that are moving forward in that direction I think it maybe makes sense to bring everything here and archive the noc-book-2
repo. Or do we need two separate repos still?
The options are:
noc-book-2
and bring everything into noc-notion
noc-notion
and integrate all of these build scripts into noc-book-2
I think my preference is to go with (1) but I'll want to go through all of the issues there and resolve them or bring them over. What do you think @jasongao97?
As discussed in our meeting, a next step is to redo the GitHub action to automate an import/pull request now that we are brining the book from notion to this repo as HTML files!
I have imported all the contents in the noc-book-2 repository and successfully turn it back to HTML on my local side.
However, I failed to run the script with GitHub action. Is it something with my permission/settings?
Latex / Katex math formula rendering is broken in HTML and PDF builds.
(Not sure if this is true just an example issue).
Just a note here that the book will require a pass over to check for consistencies of curly vs. plain quotes. The rules should be as follows:
I can‘t imagine them saying ”I didn‘t read the book!”
// This line of code is "crazy"
let s = "Crazy, I say! Crazy!";
In line 224 of the Introduction, void
should be removed from the front of the method declaration.
Additionally, the if/else block starting on line 239 is missing this.
for each of the changes to x
and y
.
The full method should read
step() {
let choice = floor(random(4));
if (choice == 0) {
this.x++;
} else if (choice == 1) {
this.x--;
} else if (choice == 2) {
this.y++;
} else {
this.y--;
}
}
Finally, as a reader, I personally find it confusing to have the explanation on lines 228-235 inserted in the middle of the two halves of this method declaration.
#75 is now merged but one thing I want to go back and look at is how the origin
is stored and intialized with a particle system. Overall I find this passing in x,y
and then creating a vector more clear than passing in a vector and calling copy()
. In addition, some of the example there isn't a good reason to store an origin
and it would make more sense to call addParticle(x,y)
.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.