-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.tex
More file actions
607 lines (522 loc) · 19.2 KB
/
main.tex
File metadata and controls
607 lines (522 loc) · 19.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
\documentclass[aspectratio=169]{beamer}
\usepackage{ITMOtheme}
\usepackage{my}
\title[CG with Rust]{Computer Graphics with Rust}
\author{Borworntat Dendumrongkul\\and\\Teejuta Sriwaranon}
\institute[CPCU]{Computer Engineering, Chulalongkorn University}
\date{\today}
\subject{Computer Graphics}
\keywords{Chulalongkorn University, Beamer, Rust, wgpu, Rayon, Mandelbrot Set}
\begin{document}
\begin{frame}[plain, noframenumbering]
\itmobackgroundsnakes{
\vfill
\usebeamerfont{title}{\Huge \inserttitle\par}
\vfill
\insertauthor\par
\vfill
\insertinstitute\\
\insertdate
}
\end{frame}
\AtBeginSection[]
{
\begin{frame}[plain, noframenumbering]
\frametitle{Outline}
\Large
\tableofcontents[currentsection]
\end{frame}
}
\section{Rust}
\begin{frame}
\frametitle{C++/OpenGL Pain}
C++ and OpenGL contains lots of pains.
\begin{itemize}
\item Segmentation fault (core dumped)
\item Iterator invalidation
\item Data race conditions
\item OpenGL's ``GLOBAL STATE MACHINE"
\item \texttt{glBindBuffer(...)}???
\item \texttt{glEnable(...)}???
\end{itemize}
\hspace{4pt}
C++ is powerful but \textbf{unsafe}. OpenGL is fimiliar but \textbf{outdated} and \textbf{stateful}.
\end{frame}
\begin{frame}
\frametitle{Philosophy of Rust}
\textbf{Safety First}: Rust aims to eliminate entire classes of errors common in other languages, like memory leaks, dangling pointers, and data races.
\medskip
\textbf{Zero-Cost Abstraction}: Rust strives to provide powerful abstractions without sacrificing performance.
\medskip
\textbf{Performance}: Rust offering speeds comparable to languages like \textbf{C and C++}
\medskip
\textbf{Concurrency}: Rust's compiler prevent data races by itself.
\medskip
\textbf{Modern Tooling}: A single command is used to build, run, test and manage dependencies.
\end{frame}
\begin{frame}
\frametitle{Meet Cargo!}
Cargo is Rust's build system and package manager. It simplifies the process of managing Rust projects.
\begin{itemize}
\item \texttt{cargo new <project-name>}: Create a new Rust project.
\item \texttt{cargo build}: Compile the current project.
\item \texttt{cargo run}: Build and run the current project.
\item \texttt{cargo test}: Run tests for the current project.
\item \texttt{cargo doc --open}: Generate and open documentation for the current project.
\end{itemize}
\end{frame}
\begin{frame}
\frametitle{Rust IDE/Compiler}
We highly recommend using \textbf{Rust Rover} by JetBrains or \textbf{Visual Studio Code} with the Rust extension for a better development experience.
\begin{center}
\includegraphics[width=0.1\textwidth]{./assets/rustrover.png}
\hspace{1cm}
\includegraphics[width=0.1\textwidth]{./assets/vscode.png}
\end{center}
\end{frame}
\begin{frame}[fragile]
\frametitle{Your First Rust Program}
\begin{minted}{rust}
fn main() {
println!("Hello, World!");
}
\end{minted}
You can run this program by saving it in a file named \texttt{main.rs} and executing \texttt{cargo run} in the terminal.
\end{frame}
\begin{frame}
\frametitle{Concept of Ownership}
Rust's ownership system is a set of rules that govern how memory is managed in Rust. The three main concepts of ownership are:
\begin{itemize}
\item Each value in Rust has a variable that is called its \textbf{owner}.
\item There can only be one owner at a time.
\item When the owner goes out of scope, the value will be dropped.
\end{itemize}
\end{frame}
\begin{frame}
\frametitle{Borrowing and Mutability}
In Rust, you can borrow a value using references. There are two types of references: immutable and mutable.
\medskip
\begin{itemize}
\item Immutable references allow you to read the value without modifying it. You can have multiple immutable references to the same value at the same time.
\item Mutable references allow you to modify the value. However, you can only have one mutable reference to a value at a time, and you cannot have any immutable references while a mutable reference exists.
\end{itemize}
\end{frame}
\begin{frame}
\frametitle{Data Types in Rust}
Rust has several built-in data types, including:
\begin{center}
\begin{tabular}{|l|l|}
\hline
\textbf{Data Type} & \textbf{Description} \\
\hline
\texttt{i32} & 32-bit signed integer \\
\texttt{u32} & 32-bit unsigned integer \\
\texttt{f32} & 32-bit floating-point number \\
\texttt{bool} & Boolean value (true or false) \\
\texttt{char} & Unicode character \\
\texttt{String} & Growable string type \\
\hline
\end{tabular}
\end{center}
\end{frame}
\begin{frame}[fragile]
\frametitle{Variables in Rust}
\begin{minted}{rust}
// Variable declaration
let x: i32 = 5; // Immutable variable
let mut y: i32 = 10; // Mutable variable
\end{minted}
By default, variables in Rust are immutable. To make a variable mutable, you need to use the \texttt{mut} keyword.
\medskip
\begin{center}
\begin{tabular}{|l|l|}
\hline
\textbf{Keyword} & \textbf{Description} \\
\hline
\texttt{let} & Declare a variable \\
\texttt{mut} & Make a variable mutable \\
\texttt{const} & Declare a constant value \\
\texttt{static} & Declare a static variable \\
\hline
\end{tabular}
\end{center}
\end{frame}
\begin{frame}[fragile]
\frametitle{Control Flow in Rust}
\begin{minted}{rust}
// If-else statement
if x < y {
println!("x is less than y");
} else {
println!("x is greater than or equal to y");
}
// Switch statement
match x {
1 => println!("One"),
2 => println!("Two"),
_ => println!("Other"),
}
\end{minted}
\end{frame}
\begin{frame}[fragile]
\frametitle{Loops in Rust}
\begin{minted}{rust}
// While loop
let mut count = 0;
while count < 5 {
println!("Count: {}", count);
count += 1;
}
// For loop
for i in 0..5 {
println!("i: {}", i);
}
\end{minted}
\end{frame}
\begin{frame}[fragile]
\frametitle{Functions in Rust}
Function in Rust are defined using the \texttt{fn} keyword. There are two ways to return a value from a function: implicit return and explicit return.
\medskip
\begin{minted}{rust}
// Implicit return
fn add(a: i32, b: i32) -> i32 {
a + b
}
// Explicit return
fn add_return(a: i32, b: i32) -> i32 {
return a + b;
}
\end{minted}
\end{frame}
\begin{frame}[fragile]
\frametitle{Structs in Rust}
Structs are custom data types that allow you to group related data together. You can define a struct using the \texttt{struct} keyword.
\medskip
\begin{minted}{rust}
struct Point {
x: f32,
y: f32,
}
\end{minted}
You can create an instance of a struct and access its fields using dot notation.
\medskip
\begin{minted}{rust}
let p = Point { x: 1.0, y: 2.0 };
println!("Point: ({}, {})", p.x, p.y);
\end{minted}
\end{frame}
\begin{frame}[fragile]
\frametitle{Struct Methods in Rust}
You can define methods for a struct using the \texttt{impl} keyword. Methods are functions that are associated with a specific struct.
\medskip
\begin{minted}{rust}
impl Point {
fn distance_from_origin(&self) -> f32 {
(self.x.powi(2) + self.y.powi(2)).sqrt()
}
}
\end{minted}
You can call a method on an instance of a struct using dot notation.
\medskip
\begin{minted}{rust}
let p = Point { x: 3.0, y: 4.0 };
println!("Distance from origin: {}", p.distance_from_origin());
\end{minted}
\end{frame}
\begin{frame}
\frametitle{Debug vs Release Builds in Rust}
In Rust, there are two main build profiles: \textbf{debug} and \textbf{release}. The default \texttt{cargo run} uses the debug build, while \texttt{cargo run --release} uses the release build.
\medskip
\textbf{Debug Build:}
\begin{itemize}
\item Includes debug symbols for easier debugging.
\item No optimizations applied, so code runs slower.
\item Includes runtime checks (e.g., bounds checking) for safety.
\item Faster compilation time.
\end{itemize}
\medskip
\textbf{Release Build:}
\begin{itemize}
\item Optimizations enabled (e.g., inlining, loop unrolling) for maximum performance.
\item Debug symbols and checks are removed to improve speed.
\item Slower compilation but much faster execution.
\end{itemize}
\medskip
For performance-critical applications like rendering, always use \texttt{--release} for the best speed!
\end{frame}
\section{Lab 8.1: Mandelbrot Set Rendering (Single Thread)}
\begin{frame}
\frametitle{Lab 8.1: Mandelbrot Set Rendering using Rust}
From the skeleton code provided, implement a program that renders the Mandelbrot set in single threaded.\\
\medskip
\begin{center}
\includegraphics[width=0.6\textwidth]{./assets/mandelbrot.png}
\end{center}
\end{frame}
\begin{frame}
\frametitle{Mandelbrot Set Definition}
The Mandelbrot set is defined by iterating the function:
\[
Z_{n + 1} = Z_{n}^2 + C
\]
where $Z_{0} = 0$ and $C$ is a complex number corresponding to a point in the complex plane. A point $C$ is part of the Mandelbrot set if the sequence does not diverge to infinity.
\end{frame}
\begin{frame}
\frametitle{Mandelbrot Set Visualization}
To visualize the Mandelbrot set, we map each pixel in the image to a point in the complex plane. We then iterate the function for each point and determine how quickly the sequence diverges. The number of iterations before divergence is used to assign a color to the pixel.
\medskip
The resulting image is just a monochrome representation of the Mandelbrot set.
\begin{center}
\includegraphics[width=0.6\textwidth]{./assets/mandelbrot-nocolor.png}
\end{center}
\end{frame}
\begin{frame}
\frametitle{Mandelbrot Set Coloring}
To enhance the visualization, we can apply coloring based on the number of iterations before divergence. A common approach is to use a color gradient or palette to map iteration counts to colors. This can create visually appealing images that highlight the intricate details of the Mandelbrot set.
\medskip
\begin{center}
\includegraphics[width=0.6\textwidth]{./assets/mandelbrot.png}
\end{center}
\end{frame}
\begin{frame}[fragile]
\frametitle{Using External Crates}
To work with images and complex numbers in Rust, we can use external crates. In this lab, we will use the \texttt{image} crate for image manipulation and the \texttt{num-complex} crate for complex number operations.
\medskip
To add these dependencies, include the following in your \texttt{Cargo.toml} file
\begin{minted}{toml}
[dependencies]
image = "0.24.9"
num-complex = "0.4.2"
\end{minted}
Or just use \href{template}{https://github.com/2110479-Computer-Graphics/Lab08-Rust-Parallel} provided!
\end{frame}
\section{Parallelism in Rust}
\begin{frame}
\frametitle{Parallelism in Rust}
We can achieve parallelism in Rust using several libraries and techniques. One of the most popular libraries for parallelism in Rust is \texttt{rayon}, which provides a simple and efficient way to perform data parallelism.
\texttt{rayon}: A data parallelism library that allows you to easily parallelize computations over collections.
In our lab, we will be using the \texttt{rayon} crate to parallelize the Mandelbrot set rendering process.
\end{frame}
\begin{frame}[fragile]
\frametitle{Using Rayon for Parallelism}
To use \texttt{rayon}, you first need to add it as a dependency in
your \texttt{Cargo.toml} file:
\begin{minted}{toml}
[dependencies]
rayon = "1.10.0"
\end{minted}
\begin{center}
\includegraphics[width=0.35\textwidth]{./assets/multi-thread-meme.png}\\
from: Reddit r/ProgrammerHumor
\end{center}
\end{frame}
\begin{frame}[fragile]
\frametitle{Parallel Iteration with Rayon}
With \texttt{rayon}, you can easily parallelize iterations over collections using the \
\texttt{par\_iter()} method. This method allows you to perform operations on each element of a collection in parallel, utilizing multiple threads to improve performance.
\begin{minted}{rust}
use rayon::prelude::*;
let numbers = vec![1, 2, 3, 4, 5];
let sum: i32 = numbers.par_iter().map(|&x| x * 2).sum();
\end{minted}
\end{frame}
\begin{frame}
\frametitle{Why we need Parallelism?}
Sometimes single-threaded performance is not enough, especially for computationally intensive tasks like rendering the raytracing or fractals. By leveraging multiple CPU cores, we can significantly reduce the time it takes to complete these tasks.
\medskip
\begin{center}
\includegraphics[width=0.35\textwidth]{./assets/raytrace.png}\\
from: Reddit r/pcmasterrace
\end{center}
\end{frame}
\section{Lab 8.2: Mandelbrot Set Rendering (Multi-thread)}
\begin{frame}
\frametitle{Lab 8.2: Mandelbrot Set Rendering using Rust in Multi-threading}
From 8.1, extend your program to support multi-threading using \texttt{rayon} crate. Also, compare the performance between single-threaded and multi-threaded implementations. (Question set in MCV)
\end{frame}
\section{Graphics API}
\begin{frame}
\frametitle{Graphics API Overview}
A Graphics API (Application Programming Interface) is a set of functions and protocols that allow developers to create and manipulate graphics in applications. Graphics APIs provide a way to interact with the underlying hardware, such as GPUs (Graphics Processing Units), to render images, animations, and visual effects.
\medskip
Some popular graphics APIs include:
\begin{itemize}
\item OpenGL (Khronos Group)
\item Vulkan (Khronos Group)
\item DirectX (Microsoft)
\item Metal (Apple)
\item WebGPU (W3C)
\end{itemize}
\end{frame}
\begin{frame}
\frametitle{Choosing a Graphics API}
When choosing a graphics API for your project, consider the following factors:
\begin{itemize}
\item \textbf{Platform support}: Ensure the API supports the target platforms (Windows, macOS,
Linux, Web, etc.).
\item \textbf{Performance}: Evaluate the performance characteristics of the API for your specific use case.
\item \textbf{Ease of use}: Consider the learning curve and available documentation and resources.
\item \textbf{Community and ecosystem}: Look for an active community and a rich ecosystem of libraries and
tools.
\end{itemize}
\end{frame}
\section{GPU Programming with wgpu}
\begin{frame}
\frametitle{Introduction to wgpu}
\texttt{wgpu} is a modern, safe, and efficient graphics API for Rust that provides a high-level abstraction over low-level graphics APIs like Vulkan, Metal, and DirectX 12. It is designed to be easy to use while still providing powerful features for GPU programming.
\medskip
Some key features of \texttt{wgpu} include:
\begin{itemize}
\item Cross-platform support
\item Safety and performance
\item Modern graphics features
\item Integration with Rust's ecosystem
\end{itemize}
\end{frame}
\begin{frame}
\frametitle{Why wgpu?}
\begin{center}
\includegraphics[width=0.6\textwidth]{./assets/wgpu-support.png}\\
from: \url{https://github.com/gfx-rs/wgpu}
\end{center}
\end{frame}
\begin{frame}[fragile]
\frametitle{Adding wgpu to Your Project}
To use \texttt{wgpu} in your Rust project, you need to add it
as a dependency in your \texttt{Cargo.toml} file:
\begin{minted}{toml}
[dependencies]
wgpu = "0.17"
\end{minted}
\begin{center}
\includegraphics[width=0.2\textwidth]{./assets/wgpu.png}
\end{center}
\end{frame}
\begin{frame}
\frametitle{Basic Structure of a wgpu Application}
A basic \texttt{wgpu} application typically consists of the following initialization steps:
\begin{enumerate}
\item \textbf{Instance}: Create a \texttt{wgpu::Instance} to represent the WebGPU API instance.
\item \textbf{Adapter}: Request a \texttt{wgpu::Adapter} from the instance, which represents a physical GPU or graphics device.
\item \textbf{Device and Queue}: Request a \texttt{wgpu::Device} and \texttt{wgpu::Queue} from the adapter. The device manages GPU resources, and the queue handles command submission.
\item \textbf{Swap Chain}: Create a swap chain for presenting rendered images to the window.
\item Create shaders, buffers, and other resources.
\item Implement the rendering loop to draw frames.
\end{enumerate}
\end{frame}
\begin{frame}
\frametitle{Example: Hello Triangle with wgpu}
Here is a simple example of rendering a triangle using \texttt{wgpu}:
\begin{itemize}
\item Initialize \texttt{wgpu} and create a window.
\item Set up the GPU device and swap chain.
\item Create vertex and index buffers for the triangle.
\item Write shaders to render the triangle.
\item Implement the rendering loop to draw the triangle.
\end{itemize}
\end{frame}
\begin{frame}
\frametitle{Shader Programming in wgpu}
In \texttt{wgpu}, shaders are typically written in WGSL (WebGPU Shading Language). WGSL is a modern shading language designed specifically for use with WebGPU and \texttt{wgpu}.
Compared to GLSL or HLSL, WGSL has a simpler syntax and is designed to be more secure and easier to use.
\end{frame}
\begin{frame}[fragile]
\frametitle{WGSL vs GLSL (Vertex Shader)}
\textbf{WGSL Vertex Shader:}
\begin{minted}{rust}
// WGSL
@vertex
fn main(@location(0) position: vec4<f32>) -> @builtin(position) vec4<f32> {
return position;
}
\end{minted}
\textbf{GLSL Vertex Shader:}
\begin{minted}{glsl}
// GLSL
#version 450
layout(location = 0) in vec4 position;
void main() {
gl_Position = position;
}
\end{minted}
\end{frame}
\begin{frame}[fragile]
\frametitle{WGSL vs GLSL (Fragment Shader)}
\textbf{WGSL Fragment Shader:}
\begin{minted}{rust}
// WGSL
@fragment
fn main() -> @location(0) vec4<f32> {
return vec4<f32>(1.0, 0.0, 0.0, 1.0); // Red color
}
\end{minted}
\textbf{GLSL Fragment Shader:}
\begin{minted}{glsl}
// GLSL
#version 450
layout(location = 0) out vec4 color;
void main() {
color = vec4(1.0, 0.0, 0.0, 1.0);
}
\end{minted}
\end{frame}
\begin{frame}
\frametitle{WGSL Playground}
To experiment with WGSL shaders, you can use the WGSL Playground, an online tool that allows you to write and test WGSL shaders in real-time.
\medskip
\begin{center}
\includegraphics[width=0.4\textwidth]{./assets/wgsl-pg.png}\\
from: \url{https://github.com/paulgb/wgsl-playground}
\end{center}
\end{frame}
\begin{frame}
\frametitle{wgpu Pipelines: Graphics vs Compute}
\texttt{wgpu} supports two main types of pipelines:
\begin{itemize}
\item \textbf{Graphics/Render Pipeline}: Used for traditional rendering tasks like drawing triangles, applying shaders, and outputting to the screen. This is what you'll use in Lab 8.3 for rendering shapes.
\item \textbf{Compute Pipeline}: Used for general-purpose GPU computing tasks like mathematical calculations, simulations, or image processing. This is what you'll use in Lab 8.4 for computing the Mandelbrot set.
\end{itemize}
\medskip
The graphics pipeline processes vertices through stages (vertex shader → fragment shader), while the compute pipeline runs parallel compute shaders on GPU threads.
\end{frame}
\section{Lab 8.3: Hello N-Gon using wgpu}
\begin{frame}
\frametitle{Lab 8.3: Hello N-Gon using wgpu}
Try to render your Lab 1 (N-gon rendering) using \texttt{wgpu} crate.
\begin{center}
\includegraphics[width=0.6\textwidth]{./assets/triangle.png}
\end{center}
\end{frame}
\section{Lab 8.4: Mandelbrot Set using wgpu}
\begin{frame}
\frametitle{Lab 8.4: Mandelbrot Set using wgpu}
We will try to render Mandelbrot again!, using \texttt{wgpu} crate.
\begin{center}
\includegraphics[width=0.8\textwidth]{./assets/mandelbrot-v2.png}
\end{center}
\end{frame}
\begin{frame}
\frametitle{Lab 8.4: Mandelbrot Set using wgpu}
Requirements:
\begin{itemize}
\item Render Mandelbrot set using GPU (wgpu crate)
\item (Optional) Implement zoom-in functionality using left mouse click
\end{itemize}
\begin{center}
\includegraphics[width=0.4\textwidth]{./assets/zoom.jpg}\\
from: Imgflip
\end{center}
\end{frame}
\begin{frame}[plain]
\itmobackgroundsnakes{
\vfill
\Huge{cargo run --release}
\vfill
}
\end{frame}
\begin{frame}[allowframebreaks, noframenumbering]
\frametitle{Bibliography}
\printbibliography
\nocite{*}
\end{frame}
\end{document}