Skip to main content

sb3_decoder/model/code/
blocks.rs

1use crate::{macros::string_id, model::sprite::RotationStyle, prelude::*};
2
3/// The representation of a Scratch script with maybe one hat block and many action blocks.
4#[derive(Debug, Clone)]
5#[non_exhaustive]
6pub struct Script {
7    pub hat: Option<Hat>,
8    pub actions: Vec<Action>,
9}
10
11/// The representation of a Scratch hat block.
12#[derive(Debug, Clone)]
13#[non_exhaustive]
14pub enum Hat {
15    // Events
16    WhenFlagClicked,
17    WhenKeyPressed { key: KeyField },
18    WhenThisSpriteClicked,
19    WhenStageClicked,
20    WhenBackdropSwitchesTo { backdrop: String },
21
22    WhenGreaterThan { loudness_timer: LoudnessTimerField, val: Reporter },
23
24    WhenIReceive { broadcast: code::BroadcastId },
25
26    // Control
27    WhenIStartAsAClone,
28
29    // Procedures
30    DefineProcedure { prototype: ProcPrototype },
31}
32
33/// The representation of a Scratch action block.
34#[derive(Debug, Clone)]
35#[non_exhaustive]
36pub enum Action {
37    // Motion
38    MoveSteps { steps: Reporter },
39    TurnRight { deg: Reporter },
40    TurnLeft { deg: Reporter },
41
42    GoTo { loc: Reporter },
43    GoToXY { x: Reporter, y: Reporter },
44    GlideSecsTo { secs: Reporter, loc: Reporter },
45    GlideSecsToXY { secs: Reporter, x: Reporter, y: Reporter },
46
47    PointInDirection { dir: Reporter },
48    PointTowards { loc: Reporter },
49
50    ChangeXBy { inc: Reporter },
51    SetXTo { x: Reporter },
52    ChangeYBy { inc: Reporter },
53    SetYTo { y: Reporter },
54
55    IfOnEdgeBounce,
56
57    SetRotationStyle { style: RotationStyle },
58
59    // Looks
60    SayForSeconds { content: Reporter, secs: Reporter },
61    Say { content: Reporter },
62    ThinkForSeconds { content: Reporter, secs: Reporter },
63    Think { content: Reporter },
64
65    SwitchCostumeTo { costume: Reporter },
66    NextCostume,
67    SwitchBackdropTo { backdrop: Reporter },
68    SwitchBackdropToAndWait { backdrop: Reporter },
69    NextBackdrop,
70
71    ChangeSizeBy { inc: Reporter },
72    SetSizeTo { size: Reporter },
73
74    ChangeGraphicEffectBy { effect: GraphicEffectField, inc: Reporter },
75    SetGraphicEffectTo { effect: GraphicEffectField, val: Reporter },
76    ClearGraphicEffects,
77
78    Show,
79    Hide,
80
81    GoToLayer { front_back: FrontBackField },
82    GoLayers { forward_backward: ForwardBackwardField, num: Reporter },
83
84    // Sound
85    PlaySoundUntilDone { sound: Reporter },
86    PlaySound { sound: Reporter },
87    StopAllSounds,
88
89    ChangeSoundEffectBy { effect: SoundEffectField, inc: Reporter },
90    SetSoundEffectTo { effect: SoundEffectField, val: Reporter },
91    ClearSoundEffects,
92
93    ChangeVolumeBy { inc: Reporter },
94    SetVolumeTo { volume: Reporter },
95
96    // Events
97    Broadcast { broadcast: Reporter },
98    BroadcastAndWait { broadcast: Reporter },
99
100    // Control
101    WaitSecs { secs: Reporter },
102
103    Repeat { times: Reporter, body: Vec<Action> },
104    Forever { body: Vec<Action> },
105
106    If { cond: Reporter, then: Vec<Action> },
107    IfElse { cond: Reporter, then: Vec<Action>, otherwise: Vec<Action> },
108    WaitUntil { cond: Reporter },
109    RepeatUntil { cond: Reporter, body: Vec<Action> },
110    While { cond: Reporter, body: Vec<Action> },
111
112    Stop { stop: StopField },
113
114    CreateCloneOf { menu: Reporter },
115    DeleteThisClone,
116
117    // Sensing
118    AskAndWait { content: Reporter },
119
120    SetDragMode { draggable: bool },
121
122    ResetTimer,
123
124    // Data
125    SetVariableTo { var: code::VarId, val: Reporter },
126    ChangeVariableBy { var: code::VarId, inc: Reporter },
127    ShowVariable { var: code::VarId },
128    HideVariable { var: code::VarId },
129
130    AddToList { list: code::ListId, val: Reporter },
131
132    DeleteOfList { list: code::ListId, index: Reporter },
133    DeleteAllOfList { list: code::ListId },
134    InsertAtOfList { list: code::ListId, val: Reporter, index: Reporter },
135    ReplaceItemOfListWith { list: code::ListId, index: Reporter, val: Reporter },
136
137    ShowList { list: code::ListId },
138    HideList { list: code::ListId },
139
140    // Procedures
141    CallProcedure { proccode: String, args: Vec<Reporter> },
142
143    // Unknown
144    Unknown(UnknownBlock),
145}
146
147/// The representation of a Scratch reporter block.
148#[derive(Debug, Clone)]
149#[non_exhaustive]
150pub enum Reporter {
151    // Primitives and Empty
152    Number { num: f64 },                        // 4
153    PosNumber { num: f64 },                     // 5
154    PosInteger { num: u64 },                    // 6
155    Integer { num: i64 },                       // 7
156    Angle { num: f64 },                         // 8
157    Color { r: u8, g: u8, b: u8 },              // 9
158    Text { text: String },                      // 10
159    Broadcast { broadcast: code::BroadcastId }, // 11
160    Variable { var: code::VarId },              // 12
161    List { list: code::ListId },                // 13
162    Empty,
163
164    // Motion
165    LocationMenu { menu: LocationMenu },
166
167    XPosition,
168    YPosition,
169    Direction,
170
171    // Looks
172    CostumeMenu { costume: String },
173    BackdropMenu { backdrop: String },
174
175    CurrentCostume { number_name: NumberNameField },
176    CurrentBackdrop { number_name: NumberNameField },
177    Size,
178
179    // Sound
180    SoundMenu { sound: String },
181
182    Volume,
183
184    // Control
185    CloneOfMenu { menu: CloneOfMenu },
186
187    // Sensing
188    KeyMenu { menu: KeyField },
189    TouchingObjectMenu { menu: TouchingObjectMenu },
190    DistanceToMenu { menu: DistanceToMenu },
191    OfObjectMenu { menu: OfObjectMenu },
192
193    TouchingObject { object: Box<Reporter> },
194    TouchingColor { color: Box<Reporter> },
195    ColorTouchingColor { a: Box<Reporter>, b: Box<Reporter> },
196    DistanceToObject { object: Box<Reporter> },
197
198    Answer,
199    KeyPressed { key: Box<Reporter> },
200    MouseDown,
201    MouseX,
202    MouseY,
203
204    Loudness,
205    Timer,
206
207    PropertyOfObject { property: PropertyField, object: Box<Reporter> },
208
209    Current { current: CurrentField },
210    DaysSince2000,
211
212    Online,
213    Username,
214
215    // Operators
216    Add { a: Box<Reporter>, b: Box<Reporter> },
217    Sub { a: Box<Reporter>, b: Box<Reporter> },
218    Mul { a: Box<Reporter>, b: Box<Reporter> },
219    Div { a: Box<Reporter>, b: Box<Reporter> },
220
221    PickRandom { min: Box<Reporter>, max: Box<Reporter> },
222
223    Gt { a: Box<Reporter>, b: Box<Reporter> },
224    Lt { a: Box<Reporter>, b: Box<Reporter> },
225    Eq { a: Box<Reporter>, b: Box<Reporter> },
226
227    And { a: Box<Reporter>, b: Box<Reporter> },
228    Or { a: Box<Reporter>, b: Box<Reporter> },
229    Not { x: Box<Reporter> },
230
231    Join { a: Box<Reporter>, b: Box<Reporter> },
232    LetterOf { index: Box<Reporter>, text: Box<Reporter> },
233    LengthOfText { text: Box<Reporter> },
234
235    TextContains { haystack: Box<Reporter>, needle: Box<Reporter> },
236
237    Mod { a: Box<Reporter>, b: Box<Reporter> },
238    Round { x: Box<Reporter> },
239
240    MathFunc { func: MathFuncField, x: Box<Reporter> },
241
242    // Data
243    ItemOfList { list: code::ListId, index: Box<Reporter> },
244    ItemNumOfItemInList { list: code::ListId, val: Box<Reporter> },
245    LengthOfList { list: code::ListId },
246    ListContains { haystack: code::ListId, needle: Box<Reporter> },
247
248    // Procedures
249    Argument { name: String },
250
251    // Unknown
252    Unknown(UnknownBlock),
253}
254
255#[derive(Debug, Clone)]
256#[non_exhaustive]
257pub struct ProcPrototype {
258    pub proccode: String,
259    pub params: Vec<Param>,
260    pub warp: bool,
261}
262
263#[derive(Debug, Clone)]
264#[non_exhaustive]
265pub struct Param {
266    pub id: ArgId,
267    pub name: String,
268    pub kind: ParamKind,
269    pub default: code::Value,
270}
271
272string_id! {
273    /// The ID of a procedure parameter.
274    ArgId
275}
276
277#[derive(Debug, Clone, Copy, PartialEq, Eq)]
278pub enum ParamKind {
279    StringNumber,
280    Boolean,
281}
282
283/// A block this crate doesn't understand, kept in a lowered but uninterpreted form. If you think
284/// this block should be added, create an issue on the repository. If you don't want to allow
285/// unknown blocks, use [`Decoder::allow_unknown_blocks`].
286#[derive(Debug, Clone)]
287#[non_exhaustive]
288pub struct UnknownBlock {
289    pub opcode: String,
290    pub inputs: Vec<(String, UnknownInput)>,
291    pub fields: Vec<(String, UnknownField)>,
292}
293
294#[derive(Debug, Clone)]
295#[non_exhaustive]
296pub enum UnknownInput {
297    /// A literal or reference, already lowered.
298    Reporter(Reporter),
299    /// A C-block substack.
300    Stack(Vec<Action>),
301}
302
303#[derive(Debug, Clone)]
304#[non_exhaustive]
305pub struct UnknownField {
306    pub value: String,
307    pub id: Option<String>,
308}
309
310/// The location menu used by some motion blocks.
311///
312/// Specifically:
313/// - `go to (menu)`
314/// - `glide (secs) secs to (menu)`
315/// - `point towards (menu)`
316#[derive(Debug, Clone, PartialEq, Eq, Hash)]
317#[non_exhaustive]
318pub enum LocationMenu {
319    Random,
320    MousePointer,
321    Sprite(String),
322}
323
324/// The effect field used by some looks blocks.
325///
326/// Specifically:
327/// - `change [graphic effect] effect by (inc)`
328/// - `set [graphic effect] effect to (value)`
329#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
330pub enum GraphicEffectField {
331    Color,
332    Fisheye,
333    Whirl,
334    Pixelate,
335    Mosaic,
336    Brightness,
337    Ghost,
338}
339
340/// The front-back field used by `go to [front-back] layer`.
341#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
342pub enum FrontBackField {
343    Front,
344    Back,
345}
346
347/// The forward-backward field used by `go [forward-backward] (num) layers`.
348#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
349pub enum ForwardBackwardField {
350    Forward,
351    Backward,
352}
353
354/// The number-name field used by some looks blocks.
355///
356/// Specifically:
357/// - `(costume [number-name])`
358/// - `(backdrop [number-name])`
359#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
360pub enum NumberNameField {
361    Number,
362    Name,
363}
364
365/// The effect field used by some sound blocks.
366///
367/// Specifically:
368/// - `change [sound effect] effect by (inc)`
369/// - `set [sound effect] effect to (value)`
370#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
371#[non_exhaustive]
372pub enum SoundEffectField {
373    Pitch,
374    PanLeftRight,
375}
376
377/// The key field used by `when [key] key pressed`. Additionally, [`Reporter::KeyMenu`] also uses
378/// this enum.
379#[derive(Debug, Clone, PartialEq, Eq, Hash)]
380#[non_exhaustive]
381pub enum KeyField {
382    Space,
383    UpArrow,
384    DownArrow,
385    LeftArrow,
386    RightArrow,
387    Any,
388    Letter(char),
389    Digit(u8),
390    Other(String),
391}
392
393/// The loudness-timer field used by `when [loudness-timer] > (val)`.
394#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
395#[non_exhaustive]
396pub enum LoudnessTimerField {
397    Loudness,
398    Timer,
399}
400
401/// The stop field used by `stop [stop]`.
402#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
403pub enum StopField {
404    All,
405    ThisScript,
406    OtherScriptsInSprite,
407}
408
409/// The object menu used by `<touching (menu)?>`.
410#[derive(Debug, Clone, PartialEq, Eq, Hash)]
411#[non_exhaustive]
412pub enum TouchingObjectMenu {
413    MousePointer,
414    Edge,
415    Sprite(String),
416}
417
418/// The object menu used by `(distance to (menu))`.
419#[derive(Debug, Clone, PartialEq, Eq, Hash)]
420#[non_exhaustive]
421pub enum DistanceToMenu {
422    MousePointer,
423    Sprite(String),
424}
425
426/// The object menu used by `([property] of (object))`.
427#[derive(Debug, Clone, PartialEq, Eq, Hash)]
428#[non_exhaustive]
429pub enum OfObjectMenu {
430    Stage,
431    Sprite(String),
432}
433
434/// The property field used by `([property] of (object))`.
435///
436/// Not every property is meaningful for every object (for example,
437/// `BackdropNumber` only applies to the stage); Scratch itself does not enforce this.
438#[derive(Debug, Clone, PartialEq, Eq, Hash)]
439#[non_exhaustive]
440pub enum PropertyField {
441    // Sprite properties
442    XPosition,
443    YPosition,
444    Direction,
445    CostumeNumber,
446    CostumeName,
447    Size,
448
449    // Stage properties
450    BackdropNumber,
451    BackdropName,
452
453    // Both
454    Volume,
455
456    /// Any other string is a variable name on the target.
457    Variable(String),
458}
459
460/// The current field used by `(current [current])`.
461#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
462pub enum CurrentField {
463    Year,
464    Month,
465    Date,
466    DayOfWeek,
467    Hour,
468    Minute,
469    Second,
470}
471
472/// The clone of menu used by `create clone of [menu]`.
473#[derive(Debug, Clone, PartialEq, Eq, Hash)]
474pub enum CloneOfMenu {
475    Myself,
476    Sprite(String),
477}
478
479/// The math function field used by `([math-func] of (x))`
480#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
481pub enum MathFuncField {
482    Abs,
483    Floor,
484    Ceiling,
485    Sqrt,
486    Sin,
487    Cos,
488    Tan,
489    Asin,
490    Acos,
491    Atan,
492    Ln,
493    Log,
494    EToPower,
495    TenToPower,
496}