-
Notifications
You must be signed in to change notification settings - Fork 65
/
render.py
2194 lines (1919 loc) · 86.5 KB
/
render.py
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
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from typing import Any, Dict, Generator, List, Set, Tuple, Optional, Union
from PIL import Image
from .blend import affine_composite, perspective_composite
from .swf import (
SWF,
Frame,
Tag,
AP2ShapeTag,
AP2DefineSpriteTag,
AP2PlaceObjectTag,
AP2RemoveObjectTag,
AP2DoActionTag,
AP2DefineFontTag,
AP2DefineEditTextTag,
AP2DefineMorphShapeTag,
AP2PlaceCameraTag,
AP2ImageTag,
)
from .decompile import ByteCode
from .types import (
Color,
HSL,
Matrix,
Point,
Rectangle,
AAMode,
AP2Trigger,
AP2Action,
PushAction,
StoreRegisterAction,
StringConstant,
Register,
NULL,
UNDEFINED,
GLOBAL,
ROOT,
PARENT,
THIS,
CLIP,
)
from .geo import Shape, DrawParams
from .util import VerboseOutput
class RegisteredClip:
# A movie clip that we are rendering, frame by frame. These are manifest by the root
# SWF as well as AP2DefineSpriteTags which are essentially embedded movie clips. The
# tag_id is the AP2DefineSpriteTag that created us, or None if this is the clip for
# the root of the movie.
def __init__(
self,
tag_id: Optional[int],
frames: List[Frame],
tags: List[Tag],
labels: Dict[str, int],
) -> None:
self.tag_id = tag_id
self.frames = frames
self.tags = tags
self.labels = labels
def __repr__(self) -> str:
return f"RegisteredClip(tag_id={self.tag_id})"
@property
def reference(self) -> str:
return "anonymous sprite"
class RegisteredShape:
# A shape that we are rendering, as placed by some placed clip somewhere.
def __init__(
self,
tag_id: int,
reference: str,
vertex_points: List[Point],
tex_points: List[Point],
tex_colors: List[Color],
draw_params: List[DrawParams],
) -> None:
self.tag_id = tag_id
self.__reference = reference
self.vertex_points: List[Point] = vertex_points
self.tex_points: List[Point] = tex_points
self.tex_colors: List[Color] = tex_colors
self.draw_params: List[DrawParams] = draw_params
self.rectangle: Optional[Image.Image] = None
@property
def reference(self) -> str:
textures = {dp.region for dp in self.draw_params if dp.region is not None}
if textures:
vals = ", ".join(textures)
return f"{self.__reference}, {vals}"
else:
return f"{self.__reference}, untextured"
def __repr__(self) -> str:
return f"RegisteredShape(tag_id={self.tag_id}, reference={self.reference} vertex_points={self.vertex_points}, tex_points={self.tex_points}, tex_colors={self.tex_colors}, draw_params={self.draw_params})"
class RegisteredImage:
# An image that we should draw directly.
def __init__(self, tag_id: int, reference: str) -> None:
self.tag_id = tag_id
self.reference = reference
def __repr__(self) -> str:
return f"RegisteredImage(tag_id={self.tag_id}, reference={self.reference})"
class RegisteredDummy:
# An imported tag that we could not find.
def __init__(self, tag_id: int) -> None:
self.tag_id = tag_id
def __repr__(self) -> str:
return f"RegisteredDummy(tag_id={self.tag_id})"
@property
def reference(self) -> str:
return "anonymous dummy"
class Mask:
def __init__(self, bounds: Rectangle) -> None:
self.bounds = bounds
self.rectangle: Optional[Image.Image] = None
class PlacedObject:
# An object that occupies the screen at some depth.
def __init__(
self,
object_id: int,
depth: int,
rotation_origin: Point,
transform: Matrix,
projection: int,
mult_color: Color,
add_color: Color,
hsl_shift: HSL,
blend: int,
mask: Optional[Mask],
) -> None:
self.__object_id = object_id
self.__depth = depth
self.rotation_origin = rotation_origin
self.transform = transform
self.projection = projection
self.mult_color = mult_color
self.add_color = add_color
self.hsl_shift = hsl_shift
self.blend = blend
self.mask = mask
self.visible: bool = True
@property
def source(
self,
) -> Union[RegisteredClip, RegisteredShape, RegisteredImage, RegisteredDummy]:
raise NotImplementedError("Only implemented in subclass!")
@property
def depth(self) -> int:
return self.__depth
@property
def object_id(self) -> int:
return self.__object_id
def __repr__(self) -> str:
return f"PlacedObject(object_id={self.object_id}, depth={self.depth})"
class PlacedShape(PlacedObject):
# A shape that occupies its parent clip at some depth. Placed by an AP2PlaceObjectTag
# referencing an AP2ShapeTag.
def __init__(
self,
object_id: int,
depth: int,
rotation_origin: Point,
transform: Matrix,
projection: int,
mult_color: Color,
add_color: Color,
hsl_shift: HSL,
blend: int,
mask: Optional[Mask],
source: RegisteredShape,
) -> None:
super().__init__(
object_id,
depth,
rotation_origin,
transform,
projection,
mult_color,
add_color,
hsl_shift,
blend,
mask,
)
self.__source = source
@property
def source(self) -> RegisteredShape:
return self.__source
def __repr__(self) -> str:
return f"PlacedShape(object_id={self.object_id}, depth={self.depth}, source={self.source})"
class PlacedClip(PlacedObject):
# A movieclip that occupies its parent clip at some depth. Placed by an AP2PlaceObjectTag
# referencing an AP2DefineSpriteTag. Essentially an embedded movie clip.
def __init__(
self,
object_id: int,
depth: int,
rotation_origin: Point,
transform: Matrix,
projection: int,
mult_color: Color,
add_color: Color,
hsl_shift: HSL,
blend: int,
mask: Optional[Mask],
source: RegisteredClip,
) -> None:
super().__init__(
object_id,
depth,
rotation_origin,
transform,
projection,
mult_color,
add_color,
hsl_shift,
blend,
mask,
)
self.placed_objects: List[PlacedObject] = []
self.frame: int = 0
self.unplayed_tags: List[int] = [i for i in range(len(source.tags))]
self.__source = source
# Dynamic properties that are adjustable by SWF bytecode.
self.playing: bool = True
self.requested_frame: Optional[int] = None
self.visible_frame: int = -1
# Root clip resizing, which we don't really support.
self.__width = 0
self.__height = 0
@property
def source(self) -> RegisteredClip:
return self.__source
def __check_visible(self) -> None:
if self.visible_frame >= 0 and self.frame >= self.visible_frame:
self.visible = True
self.visible_frame = -1
def advance(self) -> None:
if self.frame < len(self.source.frames):
self.frame += 1
self.__check_visible()
def rewind(self) -> None:
self.frame = 0
self.unplayed_tags = [i for i in range(len(self.__source.tags))]
self.placed_objects = []
self.__check_visible()
@property
def finished(self) -> bool:
return self.frame == len(self.source.frames)
def __repr__(self) -> str:
return (
f"PlacedClip(object_id={self.object_id}, depth={self.depth}, source={self.source}, frame={self.frame}, "
+ f"requested_frame={self.requested_frame}, total_frames={len(self.source.frames)}, playing={self.playing}, "
+ f"finished={self.finished})"
)
def __resolve_frame(self, frame: Any) -> Optional[int]:
if isinstance(frame, int):
return frame
if isinstance(frame, str):
if frame in self.__source.labels:
return self.__source.labels[frame]
return None
# The following are attributes and functions necessary to support some simple bytecode.
def gotoAndStop(self, frame: Any) -> None:
actual_frame = self.__resolve_frame(frame)
if actual_frame is None:
print(f"WARNING: Unrecognized frame {frame} to gotoAndStop function!")
return
if actual_frame <= 0:
actual_frame = 1
if actual_frame > len(self.source.frames):
actual_frame = len(self.source.frames)
self.requested_frame = actual_frame
self.playing = False
def gotoAndPlay(self, frame: Any) -> None:
actual_frame = self.__resolve_frame(frame)
if actual_frame is None:
print(f"WARNING: Non-integer frame {frame} to gotoAndPlay function!")
return
if actual_frame <= 0:
actual_frame = 1
if actual_frame > len(self.source.frames):
actual_frame = len(self.source.frames)
self.requested_frame = actual_frame
self.playing = True
def stop(self) -> None:
self.playing = False
def play(self) -> None:
self.playing = True
def setInvisibleUntil(self, frame: Any) -> None:
actual_frame = self.__resolve_frame(frame)
if actual_frame is None:
print(f"WARNING: Non-integer frame {frame} to setInvisibleUntil function!")
return
actual_frame += self.frameOffset - 1
self.visible = False
if actual_frame <= 0:
actual_frame = 1
if actual_frame > len(self.source.frames):
actual_frame = len(self.source.frames)
self.visible_frame = actual_frame
self.__check_visible()
@property
def frameOffset(self) -> int:
return self.requested_frame or self.frame
@frameOffset.setter
def frameOffset(self, val: Any) -> None:
actual_frame = self.__resolve_frame(val)
if actual_frame is None:
print(f"WARNING: Non-integer frameOffset {val} to frameOffset attribute!")
return
if actual_frame < 0:
actual_frame = 0
if actual_frame >= len(self.source.frames):
actual_frame = len(self.source.frames) - 1
self.requested_frame = actual_frame + 1
@property
def _visible(self) -> int:
return 1 if self.visible else 0
@_visible.setter
def _visible(self, val: Any) -> None:
self.visible = val != 0
@property
def _width(self) -> int:
calculated_width = self.__width
for obj in self.placed_objects:
if isinstance(obj, PlacedClip):
calculated_width = max(calculated_width, obj._width)
return calculated_width
@_width.setter
def _width(self, val: Any) -> None:
self.__width = val
@property
def _height(self) -> int:
calculated_height = self.__height
for obj in self.placed_objects:
if isinstance(obj, PlacedClip):
calculated_height = max(calculated_height, obj._height)
return calculated_height
@_height.setter
def _height(self, val: Any) -> None:
self.__height = val
class PlacedImage(PlacedObject):
# An image that occupies its parent clip at some depth. Placed by an AP2PlaceObjectTag
# referencing an AP2ImageTag.
def __init__(
self,
object_id: int,
depth: int,
rotation_origin: Point,
transform: Matrix,
projection: int,
mult_color: Color,
add_color: Color,
hsl_shift: HSL,
blend: int,
mask: Optional[Mask],
source: RegisteredImage,
) -> None:
super().__init__(
object_id,
depth,
rotation_origin,
transform,
projection,
mult_color,
add_color,
hsl_shift,
blend,
mask,
)
self.__source = source
@property
def source(self) -> RegisteredImage:
return self.__source
def __repr__(self) -> str:
return f"PlacedImage(object_id={self.object_id}, depth={self.depth}, source={self.source})"
class PlacedDummy(PlacedObject):
# A reference to an object we can't find because we're missing the import.
def __init__(
self,
object_id: int,
depth: int,
rotation_origin: Point,
transform: Matrix,
projection: int,
mult_color: Color,
add_color: Color,
hsl_shift: HSL,
blend: int,
mask: Optional[Mask],
source: RegisteredDummy,
) -> None:
super().__init__(
object_id,
depth,
rotation_origin,
transform,
projection,
mult_color,
add_color,
hsl_shift,
blend,
mask,
)
self.__source = source
@property
def source(self) -> RegisteredDummy:
return self.__source
class PlacedCamera:
def __init__(self, center: Point, focal_length: float) -> None:
self.center = center
self.focal_length = focal_length
self.adjusted = False
class Global:
def __init__(self, root: PlacedClip, clip: PlacedClip) -> None:
self.root = root
self.clip = clip
def getInstanceAtDepth(self, depth: Any) -> Any:
if not isinstance(depth, int):
return UNDEFINED
# For some reason, it looks like internally the depth of all objects is
# stored added to -0x4000, so let's reverse that.
depth = depth + 0x4000
for obj in self.clip.placed_objects:
if obj.depth == depth:
return obj
print(f"WARNING: Could not find object at depth {depth}!")
return UNDEFINED
def deepGotoAndPlay(self, frame: Any) -> Any:
# This is identical to regular gotoAndPlay, however it also recursively
# goes through and sets all child clips playing as well.
try:
meth = getattr(self.clip, "gotoAndPlay")
# Call it, set the return on the stack.
retval = meth(frame)
# Recursively go through any children of "clip" and call play
# on them as well.
def play_children(obj: Any) -> None:
if isinstance(obj, PlacedClip):
obj.play()
for child in obj.placed_objects:
play_children(child)
play_children(self.clip)
return retval
except AttributeError:
# Function does not exist!
print(f"WARNING: Tried to call gotoAndPlay({frame}) on {self.clip} but that method doesn't exist!")
return UNDEFINED
def __find_parent(self, parent: PlacedClip, child: PlacedClip) -> Optional[PlacedClip]:
for obj in parent.placed_objects:
if obj is child:
# This is us, so the parent is our parent.
return parent
if isinstance(obj, PlacedClip):
maybe_parent = self.__find_parent(obj, child)
if maybe_parent is not None:
return maybe_parent
return None
def find_parent(self, child: PlacedClip) -> Optional[PlacedClip]:
return self.__find_parent(self.root, child)
class AEPLib:
def aep_set_rect_mask(self, thisptr: Any, left: Any, right: Any, top: Any, bottom: Any) -> None:
if (
not isinstance(left, (int, float))
or not isinstance(right, (int, float))
or not isinstance(top, (int, float))
or not isinstance(bottom, (int, float))
):
print(
f"WARNING: Ignoring aeplib.aep_set_rect_mask call with invalid parameters {left}, {right}, {top}, {bottom}!"
)
return
if isinstance(thisptr, PlacedObject):
thisptr.mask = Mask(
Rectangle(
left=float(left),
right=float(right),
top=float(top),
bottom=float(bottom),
),
)
else:
print(f"WARNING: Ignoring aeplib.aep_set_rect_mask call with unrecognized target {thisptr}!")
def aep_set_set_frame(self, thisptr: Any, frame: Any) -> None:
# This appears to be some sort of callback that the game or other animations can use to figure out
# what frame of animation is currently happening. Whenever I've seen it, it is with the 'frame' set
# to an integer value that matches the currently rendering frame in the render loop. I think its
# safe to ignore this, but if we ever create animations it might be necessary to add calls to this.
pass
def aep_set_frame_control(self, thisptr: Any, depth: Any, frame: Any) -> None:
if not isinstance(thisptr, PlacedClip):
print(f"WARNING: Ignoring aeplib.aep_set_frame_control with unrecognized current object {thisptr}!")
return
for obj in thisptr.placed_objects:
if obj.depth == depth:
if not isinstance(obj, PlacedClip):
print(f"WARNING: Ignoring aeplib.aep_set_frame_control called on object {obj} at depth {depth}!")
return
obj.setInvisibleUntil(frame)
return
print(f"WARNING: Ignoring aeplib.aep_set_frame_control called on nonexistent object at depth {depth}!")
def gotoAndPlay(self, thisptr: Any, frame: Any) -> Any:
# This appears to be a wrapper to allow calling gotoAndPlay on clips.
try:
meth = getattr(thisptr, "gotoAndPlay")
# Call it, set the return on the stack.
return meth(frame)
except AttributeError:
# Function does not exist!
print(f"WARNING: Tried to call gotoAndPlay({frame}) on {thisptr} but that method doesn't exist!")
return UNDEFINED
def gotoAndStop(self, thisptr: Any, frame: Any) -> Any:
# This appears to be a wrapper to allow calling gotoAndStop on clips.
try:
meth = getattr(thisptr, "gotoAndStop")
# Call it, set the return on the stack.
return meth(frame)
except AttributeError:
# Function does not exist!
print(f"WARNING: Tried to call gotoAndStop({frame}) on {thisptr} but that method doesn't exist!")
return UNDEFINED
def deepGotoAndPlay(self, thisptr: Any, frame: Any) -> Any:
# This is identical to regular gotoAndPlay, however it also recursively
# goes through and sets all child clips playing as well.
try:
meth = getattr(thisptr, "gotoAndPlay")
# Call it, set the return on the stack.
retval = meth(frame)
# Recursively go through any children of "thisptr" and call play
# on them as well.
def play_children(obj: Any) -> None:
if isinstance(obj, PlacedClip):
obj.play()
for child in obj.placed_objects:
play_children(child)
play_children(thisptr)
return retval
except AttributeError:
# Function does not exist!
print(f"WARNING: Tried to call gotoAndPlay({frame}) on {thisptr} but that method doesn't exist!")
return UNDEFINED
def deepGotoAndStop(self, thisptr: Any, frame: Any) -> Any:
# This is identical to regular gotoAndStop, however it also recursively
# goes through and sets all child clips stopped as well.
try:
meth = getattr(thisptr, "gotoAndStop")
# Call it, set the return on the stack.
retval = meth(frame)
# Recursively go through any children of "thisptr" and call stop
# on them as well.
def stop_children(obj: Any) -> None:
if isinstance(obj, PlacedClip):
obj.stop()
for child in obj.placed_objects:
stop_children(child)
stop_children(thisptr)
return retval
except AttributeError:
# Function does not exist!
print(f"WARNING: Tried to call gotoAndStop({frame}) on {thisptr} but that method doesn't exist!")
return UNDEFINED
def play(self, thisptr: Any) -> Any:
# This appears to be a wrapper to allow calling play on clips.
try:
meth = getattr(thisptr, "play")
# Call it, set the return on the stack.
return meth()
except AttributeError:
# Function does not exist!
print(f"WARNING: Tried to call play() on {thisptr} but that method doesn't exist!")
return UNDEFINED
def stop(self, thisptr: Any) -> Any:
# This appears to be a wrapper to allow calling stop on clips.
try:
meth = getattr(thisptr, "stop")
# Call it, set the return on the stack.
return meth()
except AttributeError:
# Function does not exist!
print(f"WARNING: Tried to call stop() on {thisptr} but that method doesn't exist!")
return UNDEFINED
class ASDLib:
def sound_play(self, sound: Any) -> None:
if not isinstance(sound, str):
print(f"WARNING: Ignoring asdlib.sound_play call with invalid parameters {sound}!")
print(f"WARNING: Requested sound {sound} be played but we don't support sound yet!")
MissingThis = object()
class AFPRenderer(VerboseOutput):
def __init__(
self,
shapes: Dict[str, Shape] = {},
textures: Dict[str, Image.Image] = {},
swfs: Dict[str, SWF] = {},
single_threaded: bool = False,
enable_aa: bool = False,
) -> None:
super().__init__()
# Options for rendering
self.__single_threaded = single_threaded
self.__enable_aa = enable_aa
# Library of shapes (draw instructions), textures (actual images) and swfs (us and other files for imports).
self.shapes: Dict[str, Shape] = shapes
self.textures: Dict[str, Image.Image] = textures
self.swfs: Dict[str, SWF] = swfs
# Internal render parameters.
self.__registered_objects: Dict[
int,
Union[RegisteredShape, RegisteredClip, RegisteredImage, RegisteredDummy],
] = {}
self.__root: Optional[PlacedClip] = None
self.__camera: Optional[PlacedCamera] = None
# List of imports that we provide stub implementations for.
self.__stubbed_swfs: Set[str] = {
"aeplib.aeplib",
"aeplib.__Packages.aeplib",
}
def add_shape(self, name: str, data: Shape) -> None:
# Register a named shape with the renderer.
if not data.parsed:
data.parse()
self.shapes[name] = data
def add_texture(self, name: str, data: Image.Image) -> None:
# Register a named texture (already loaded PIL image) with the renderer.
self.textures[name] = data.convert("RGBA")
def add_swf(self, name: str, data: SWF) -> None:
# Register a named SWF with the renderer.
if not data.parsed:
data.parse()
self.swfs[name] = data
def render_path(
self,
path: str,
background_color: Optional[Color] = None,
background_image: Optional[List[Image.Image]] = None,
only_depths: Optional[List[int]] = None,
only_frames: Optional[List[int]] = None,
movie_transform: Matrix = Matrix.identity(),
overridden_width: Optional[float] = None,
overridden_height: Optional[float] = None,
verbose: bool = False,
) -> Generator[Image.Image, None, None]:
# Given a path to a SWF root animation, attempt to render it to a list of frames.
for _name, swf in self.swfs.items():
if swf.exported_name == path:
# This is the SWF we care about.
with self.debugging(verbose):
swf.color = background_color or swf.color
yield from self.__render(
swf,
only_depths,
only_frames,
movie_transform,
background_image,
overridden_width,
overridden_height,
)
return
raise Exception(f"{path} not found in registered SWFs!")
def compute_path_location(
self,
path: str,
) -> Rectangle:
# Given a path to a SWF root animation, find its bounding rectangle.
for _name, swf in self.swfs.items():
if swf.exported_name == path:
# This is the SWF we care about.
return swf.location
raise Exception(f"{path} not found in registered SWFs!")
def compute_path_frames(
self,
path: str,
) -> int:
# Given a path to a SWF root animation, figure out how many frames are
# in that root path with no regard to bytecode 'stop()' commands.
for _name, swf in self.swfs.items():
if swf.exported_name == path:
# This is the SWF we care about.
return len(swf.frames)
raise Exception(f"{path} not found in registered SWFs!")
def compute_path_frame_duration(
self,
path: str,
) -> int:
# Given a path to a SWF root animation, figure out how many milliseconds are
# occupied by each frame.
for _name, swf in self.swfs.items():
if swf.exported_name == path:
# This is the SWF we care about.
spf = 1.0 / swf.fps
return int(spf * 1000.0)
raise Exception(f"{path} not found in registered SWFs!")
def compute_path_size(
self,
path: str,
) -> Rectangle:
# Given a path to a SWF root animation, figure out what the dimensions
# of the SWF are.
for _name, swf in self.swfs.items():
if swf.exported_name == path:
return swf.location
raise Exception(f"{path} not found in registered SWFs!")
def list_paths(self, verbose: bool = False) -> Generator[str, None, None]:
# Given the loaded animations, return a list of possible paths to render.
for _name, swf in self.swfs.items():
yield swf.exported_name
def __execute_bytecode(
self,
bytecode: ByteCode,
clip: PlacedClip,
thisptr: Optional[Any] = MissingThis,
prefix: str = "",
) -> None:
if self.__root is None:
raise Exception("Logic error, executing bytecode outside of a rendering movie clip!")
thisobj = clip if (thisptr is MissingThis) else thisptr
globalobj = Global(self.__root, clip)
location: int = 0
stack: List[Any] = []
variables: Dict[str, Any] = {
"aeplib": AEPLib(),
"asdlib": ASDLib(),
}
registers: List[Any] = [UNDEFINED] * 256
self.vprint(f"{prefix}Bytecode engine starting.", component="bytecode")
while location < len(bytecode.actions):
action = bytecode.actions[location]
if action.opcode == AP2Action.END:
# End the execution.
self.vprint(f"{prefix} Ending bytecode execution.", component="bytecode")
break
elif action.opcode == AP2Action.GET_VARIABLE:
varname = stack.pop()
# Look up the variable, put it on the stack.
if varname in variables:
stack.append(variables[varname])
else:
stack.append(UNDEFINED)
elif action.opcode == AP2Action.SET_MEMBER:
# Grab what we're about to do.
set_value = stack.pop()
attribute = stack.pop()
obj = stack.pop()
if not hasattr(obj, attribute):
print(
f"WARNING: Tried to set attribute {attribute} on {obj} to {set_value} but that attribute doesn't exist!"
)
else:
self.vprint(
f"{prefix} Setting attribute {attribute} on {obj} to {set_value}",
component="bytecode",
)
setattr(obj, attribute, set_value)
elif action.opcode == AP2Action.CALL_METHOD:
# Grab the method name.
methname = stack.pop()
# Grab the object to perform the call on.
obj = stack.pop()
# Grab the parameters to pass to the function.
num_params = stack.pop()
if not isinstance(num_params, int):
raise Exception("Logic error, cannot get number of parameters to method call!")
params = []
for _ in range(num_params):
params.append(stack.pop())
# Look up the python function we're calling.
try:
self.vprint(
f"{prefix} Calling method {methname}({', '.join(repr(s) for s in params)}) on {obj}",
component="bytecode",
)
meth = getattr(obj, methname)
# Call it, set the return on the stack.
stack.append(meth(*params))
except AttributeError:
# Function does not exist!
print(
f"WARNING: Tried to call {methname}({', '.join(repr(s) for s in params)}) on {obj} but that method doesn't exist!"
)
stack.append(UNDEFINED)
elif action.opcode == AP2Action.CALL_FUNCTION:
# Grab the method name.
funcname = stack.pop()
# Grab the parameters to pass to the function.
num_params = stack.pop()
if not isinstance(num_params, int):
raise Exception("Logic error, cannot get number of parameters to function call!")
params = []
for _ in range(num_params):
params.append(stack.pop())
# Look up the python function we're calling.
try:
self.vprint(
f"{prefix} Calling global function {funcname}({', '.join(repr(s) for s in params)})",
component="bytecode",
)
func = getattr(globalobj, funcname)
# Call it, set the return on the stack.
stack.append(func(*params))
except AttributeError:
# Function does not exist!
print(
f"WARNING: Tried to call {funcname}({', '.join(repr(s) for s in params)}) on {globalobj} but that function doesn't exist!"
)
stack.append(UNDEFINED)
elif isinstance(action, PushAction):
for obj in action.objects:
if isinstance(obj, Register):
stack.append(registers[obj.no])
elif isinstance(obj, StringConstant):
if obj.alias:
stack.append(obj.alias)
else:
stack.append(StringConstant.property_to_name(obj.const))
elif obj is NULL:
stack.append(None)
elif obj is THIS:
stack.append(thisobj)
elif obj is GLOBAL:
stack.append(globalobj)
elif obj is ROOT:
stack.append(self.__root)
elif obj is CLIP:
# I am not sure this is correct? Maybe it works out
# in circumstances where "THIS" is pointed at something
# else, such as defined function calls maybe?
stack.append(clip)
elif obj is PARENT:
# Find the parent of this clip.
stack.append(globalobj.find_parent(clip) or UNDEFINED)
else:
stack.append(obj)
elif isinstance(action, StoreRegisterAction):
set_value = stack.pop()
if action.preserve_stack:
stack.append(set_value)
for reg in action.registers:
registers[reg.no] = set_value
elif action.opcode == AP2Action.POP:
stack.pop()
else:
print(f"WARNING: Unhandled opcode {action} with stack {stack}")
# Next opcode!
location += 1
self.vprint(f"{prefix}Bytecode engine finished.", component="bytecode")
def __place(self, tag: Tag, operating_clip: PlacedClip, prefix: str = "") -> Tuple[Optional[PlacedClip], bool]:
# "Place" a tag on the screen. Most of the time, this means performing the action of the tag,
# such as defining a shape (registering it with our shape list) or adding/removing an object.
if isinstance(tag, AP2ShapeTag):
self.vprint(
f"{prefix} Loading {tag.reference} shape into object slot {tag.id}",
component="tags",
)
if tag.reference not in self.shapes:
raise Exception(f"Cannot find shape reference {tag.reference}!")
self.__registered_objects[tag.id] = RegisteredShape(
tag.id,
tag.reference,
self.shapes[tag.reference].vertex_points,
self.shapes[tag.reference].tex_points,
self.shapes[tag.reference].tex_colors,
self.shapes[tag.reference].draw_params,
)