forked from renpy/renpy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
atl.py
2366 lines (1664 loc) · 67.7 KB
/
atl.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
# Copyright 2004-2024 Tom Rothamel <pytom@bishoujo.us>
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, copy, modify, merge,
# publish, distribute, sublicense, and/or sell copies of the Software,
# and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
from __future__ import division, absolute_import, with_statement, print_function, unicode_literals
from renpy.compat import PY2, basestring, bchr, bord, chr, open, pystr, range, round, str, tobytes, unicode # *
import random
import renpy
from renpy.pyanalysis import Analysis, NOT_CONST, GLOBAL_CONST
def compiling(loc):
file, number = loc # @ReservedAssignment
renpy.game.exception_info = "Compiling ATL code at %s:%d" % (file, number)
def executing(loc):
file, number = loc # @ReservedAssignment
renpy.game.exception_info = "Executing ATL code at %s:%d" % (file, number)
# A map from the name of a time warp function to the function itself.
warpers = { }
def atl_warper(f):
name = f.__name__
warpers[name] = f
return f
# The pause warper is used internally when no other warper is
# specified.
@atl_warper
def pause(t):
if t < 1.0:
return 0.0
else:
return 1.0
@atl_warper
def instant(t):
return 1.0
class position(object):
"""
A combination of relative and absolute coordinates.
"""
__slots__ = ('absolute', 'relative')
def __new__(cls, absolute=0, relative=None):
"""
If passed two parameters, takes them as an absolute and a relative.
If passed only one parameter, converts it.
Using __new__ so that passing a position returns it unchanged.
"""
if relative is None:
self = cls.from_any(absolute)
else:
self = object.__new__(cls)
self.absolute = absolute
self.relative = relative
return self
@classmethod
def from_any(cls, other):
if isinstance(other, cls):
return other
elif type(other) is float:
return cls(0, other)
else:
return cls(other, 0)
def simplify(self):
"""
Tries to represent this position as an int, float, or absolute, if
possible.
"""
if self.relative == 0.0:
if self.absolute == int(self.absolute):
return int(self.absolute)
else:
return renpy.display.core.absolute(self.absolute)
elif self.absolute == 0:
return float(self.relative)
else:
return self
def __add__(self, other):
if isinstance(other, position):
return position(self.absolute + other.absolute, self.relative + other.relative)
# elif isinstance(other, (int, float)):
# return self + position.from_any(other)
return NotImplemented
__radd__ = __add__
def __sub__(self, other):
return self + -other
def __rsub__(self, other):
return other + -self
def __mul__(self, other):
if isinstance(other, (int, float)):
return position(self.absolute * other, self.relative * other)
return NotImplemented
__rmul__ = __mul__
def __truediv__(self, other):
if isinstance(other, (int, float)):
return self * (1/other)
return NotImplemented
__div__ = __truediv__ # PY2
def __pos__(self):
return position(renpy.display.core.absolute(self.absolute), float(self.relative))
def __neg__(self):
return -1 * self
def __repr__(self):
return "position(absolute={}, relative={})".format(self.absolute, self.relative)
class DualAngle(object):
def __init__(self, absolute, relative): # for tests, convert to PY2 after
self.absolute = absolute
self.relative = relative
@classmethod
def from_any(cls, other):
if isinstance(other, cls):
return other
elif type(other) is float:
return cls(other, other)
raise TypeError("Cannot convert {} to DualAngle".format(type(other)))
def __add__(self, other):
if isinstance(other, DualAngle):
return DualAngle(self.absolute + other.absolute, self.relative + other.relative)
return NotImplemented
def __sub__(self, other):
return self + -other
def __mul__(self, other):
if isinstance(other, (int, float)):
return DualAngle(self.absolute * other, self.relative * other)
return NotImplemented
__rmul__ = __mul__
def __neg__(self):
return -1 * self
def position_or_none(x):
if x is None:
return None
return position.from_any(x)
def any_object(x):
return x
def bool_or_none(x):
if x is None:
return x
return bool(x)
def float_or_none(x):
if x is None:
return x
return float(x)
def matrix(x):
if x is None:
return None
elif callable(x):
return x
else:
return renpy.display.matrix.Matrix(x)
def mesh(x):
if isinstance(x, (renpy.gl2.gl2mesh2.Mesh2, renpy.gl2.gl2mesh3.Mesh3, tuple)):
return x
return bool(x)
# A dictionary giving property names and the corresponding type or
# function. This is massively added to by renpy.display.transform.
PROPERTIES = { }
def interpolate(t, a, b, typ):
"""
Linearly interpolate the arguments.
"""
# Deal with booleans, nones, etc.
if b is None or isinstance(b, (bool, basestring, renpy.display.matrix.Matrix, renpy.display.transform.Camera)):
if t >= 1.0:
return b
else:
return a
# Recurse into tuples.
elif isinstance(b, tuple):
if a is None:
a = [ None ] * len(b)
if not isinstance(typ, tuple):
typ = (typ,) * len(b)
return tuple(interpolate(t, i, j, ty) for i, j, ty in zip(a, b, typ))
# If something is callable, call it and return the result.
elif callable(b):
a_origin = getattr(a, "origin", None)
rv = b(a_origin, t)
rv.origin = b
return rv
# Interpolate everything else.
else:
if a is None:
a = 0
if typ in (position_or_none, position):
if renpy.config.mixed_position:
a = position.from_any(a)
b = position.from_any(b)
return (1-t)*a + t*b # same result, faster execution
else:
typ = type(b)
return typ(a + t * (b - a))
# Interpolate the value of a spline. This code is based on Aenakume's code,
# from 00splines.rpy.
def interpolate_spline(t, spline, typ):
if isinstance(spline[-1], tuple):
return tuple(interpolate_spline(t, i, ty) for i, ty in zip(zip(*spline), typ))
if spline[0] is None:
return spline[-1]
if renpy.config.mixed_position and typ in (position_or_none, position):
spline = [position_or_none(i) for i in spline]
lenspline = len(spline)
if lenspline == 2:
t_p = 1.0 - t
rv = t_p * spline[0] + t * spline[-1]
elif lenspline == 3:
t_pp = (1.0 - t) ** 2
t_p = 2 * t * (1.0 - t)
t2 = t ** 2
rv = t_pp * spline[0] + t_p * spline[1] + t2 * spline[2]
elif lenspline == 4:
t_ppp = (1.0 - t) ** 3
t_pp = 3 * t * (1.0 - t) ** 2
t_p = 3 * t ** 2 * (1.0 - t)
t3 = t ** 3
rv = t_ppp * spline[0] + t_pp * spline[1] + t_p * spline[2] + t3 * spline[3]
elif t <= 0.0:
rv = spline[0]
elif t >= 1.0:
rv = spline[-1]
else:
# Catmull-Rom (re-adjust the control points)
spline = [
spline[1],
spline[0]
] + list(spline[2:-2]) + [
spline[-1],
spline[-2]
]
inner_spline_count = float(lenspline - 3)
# determine which spline values are relevant
sector = int(t // (1.0 / inner_spline_count) + 1)
# determine t for this sector
t = (t % (1.0 / inner_spline_count)) * inner_spline_count
rv = get_catmull_rom_value(t, *spline[sector - 1:sector + 3])
if rv is None:
return None
else:
return type(spline[-1])(rv)
def get_catmull_rom_value(t, p_1, p0, p1, p2):
"""
Very basic Catmull-Rom calculation with no alpha or handling
of multi-dimensional points
"""
t = float(max(0.0, min(1.0, t)))
return type(p0)(
(t * ((2 - t) * t - 1) * p_1
+(t * t * (3 * t - 5) + 2) * p0
+t * ((4 - 3 * t) * t + 1) * p1
+(t - 1) * t * t * p2) / 2)
# A list of atl transforms that may need to be compiled.
compile_queue = [ ]
def compile_all():
"""
Called after the init phase is finished and transforms are compiled,
to compile all constant transforms.
"""
global compile_queue
for i in compile_queue:
if i.atl.constant == GLOBAL_CONST:
i.compile()
compile_queue = [ ]
# Used to indicate that a variable is not in the context.
NotInContext = renpy.object.Sentinel("NotInContext")
# This is the context used when compiling an ATL statement. It stores the
# scopes that are used to evaluate the various expressions in the statement,
# and has a method to do the evaluation and return a result.
class Context(object):
def __init__(self, context):
self.context = context
def eval(self, expr): # @ReservedAssignment
return renpy.python.py_eval(expr, locals=self.context)
def __eq__(self, other):
if not isinstance(other, Context):
return False
return self.context == other.context
def __ne__(self, other):
return not (self == other)
class ATLTransformBase(renpy.object.Object):
"""
This is intended to be subclassed by ATLTransform. It takes care of
managing ATL execution, which allows ATLTransform itself to not care
much about the contents of this file.
"""
# Compatibility with older saves.
parameters = renpy.ast.EMPTY_PARAMETERS
parent_transform = None
atl_st_offset = 0
# The block, as first compiled for prediction.
predict_block = None
nosave = [ 'parent_transform' ]
def __init__(self, atl, context, parameters):
# The constructor will be called by atltransform.
if parameters is None:
parameters = ATLTransformBase.parameters
else:
# Apply the default parameters.
context = context.copy()
for k, p in parameters.parameters.items():
v = p.default
if v is not None:
context[k] = renpy.python.py_eval(v, locals=context)
# The parameters that we take.
self.parameters = parameters
# The raw code that makes up this ATL statement.
self.atl = atl
# The context in which execution occurs.
self.context = Context(context)
# The code after it has been compiled into a block.
self.block = None
# The same thing, but only if the code was compiled into a block
# for prediction purposes only.
self.predict_block = None
# The properties of the block, if it contains only an
# Interpolation.
self.properties = None
# The state of the statement we are executing. As this can be
# shared between more than one object (in the case of a hide),
# the data must not be altered.
self.atl_state = None
# Are we done?
self.done = False
# The transform event we are going to process.
self.transform_event = None
# The transform event we last processed.
self.last_transform_event = None
# The child transform event we last processed.
self.last_child_transform_event = None
# The child, without any transformations.
self.raw_child = None
# The parent transform that was called to create this transform.
self.parent_transform = None
# The offset between st and when this ATL block first executed.
if renpy.config.atl_start_on_show:
self.atl_st_offset = None
else:
self.atl_st_offset = 0
if renpy.game.context().init_phase:
compile_queue.append(self)
@property
def transition(self):
"""
Returns true if this is likely to be an ATL transition.
"""
return "new_widget" in self.context.context
def _handles_event(self, event):
if (event == "replaced") and (self.atl_state is None):
return True
if (self.block is not None) and (self.block._handles_event(event)):
return True
if self.child is None:
return False
return self.child._handles_event(event)
def get_block(self):
"""
Returns the compiled block to use.
"""
if self.block:
return self.block
elif self.predict_block and renpy.display.predict.predicting:
return self.predict_block
else:
return None
def take_execution_state(self, t):
"""
Updates self to begin executing from the same point as t. This
requires that t.atl is self.atl.
"""
super(ATLTransformBase, self).take_execution_state(t) # type: ignore
self.atl_st_offset = None
self.atl_state = None
if self is t:
return
elif not isinstance(t, ATLTransformBase):
return
elif t.atl is not self.atl:
return
# Only take the execution state if the contexts haven't changed in
# a way that would affect the execution of the ATL.
if t.atl.constant != GLOBAL_CONST:
block = self.get_block()
if block is None:
block = self.compile()
if not deep_compare(self.block, t.block):
return
self.done = t.done
self.block = t.block
self.atl_state = t.atl_state
self.transform_event = t.transform_event
self.last_transform_event = t.last_transform_event
self.last_child_transform_event = t.last_child_transform_event
self.st = t.st
self.at = t.at
self.st_offset = t.st_offset
self.at_offset = t.at_offset
self.atl_st_offset = t.atl_st_offset
if self.child is renpy.display.motion.null:
if t.child and t.child._duplicatable:
self.child = t.child._duplicate(None)
else:
self.child = t.child
self.raw_child = t.raw_child
def __call__(self, *args, **kwargs):
_args = kwargs.pop("_args", None)
context = self.context.context.copy()
positional = list(self.parameters.positional)
args = list(args)
child = None
if not positional and args:
child = args.pop(0)
# Handle positional arguments.
while positional and args:
name = positional.pop(0)
value = args.pop(0)
if name in kwargs:
raise Exception('Parameter %r is used as both a positional and keyword argument to a transition.' % name)
if (name == "child") or (name == "old_widget"):
child = value
context[name] = value
if args:
raise Exception("Too many arguments passed to ATL transform.")
# Handle keyword arguments.
for k, v in kwargs.items():
if k == "old_widget":
child = v
if k in positional:
positional.remove(k)
context[k] = v
elif k in context:
context[k] = v
elif k == 'child':
child = v
else:
raise Exception('Parameter %r is not known by ATL Transform.' % k)
if child is None:
child = self.child
if getattr(child, '_duplicatable', False):
child = child._duplicate(_args)
# Create a new ATL Transform.
parameters = renpy.ast.ParameterInfo.legacy([ ], positional, None, None)
rv = renpy.display.motion.ATLTransform(
atl=self.atl,
child=child,
style=self.style_arg, # type: ignore
context=context,
parameters=parameters,
_args=_args,
)
rv.parent_transform = self # type: ignore
rv.take_state(self)
return rv
def compile(self): # @ReservedAssignment
"""
Compiles the ATL code into a block. As necessary, updates the
properties.
"""
constant = (self.atl.constant == GLOBAL_CONST)
if not constant:
for p in self.parameters.positional:
if p not in self.context.context:
raise Exception("Cannot compile ATL Transform at %s:%d, as it's missing positional parameter %s." % (
self.atl.loc[0],
self.atl.loc[1],
p,
))
if constant and self.parent_transform:
if self.parent_transform.block:
self.block = self.parent_transform.block
self.properties = self.parent_transform.properties
self.parent_transform = None
return self.block
old_exception_info = renpy.game.exception_info
if constant and self.atl.compiled_block is not None:
block = self.atl.compiled_block
else:
block = self.atl.compile(self.context)
if all(
isinstance(statement, Interpolation) and statement.duration == 0
for statement in block.statements
):
self.properties = []
for interp in block.statements:
self.properties.extend(interp.properties)
if not constant and renpy.display.predict.predicting:
self.predict_block = block
else:
self.block = block
self.predict_block = None
renpy.game.exception_info = old_exception_info
if constant and self.parent_transform:
self.parent_transform.block = self.block
self.parent_transform.properties = self.properties
self.parent_transform = None
return block
def execute(self, trans, st, at):
if self.done:
return None
block = self.get_block()
if block is None:
block = self.compile()
events = [ ]
# Hide request.
if trans.hide_request:
self.transform_event = "hide"
if trans.replaced_request:
self.transform_event = "replaced"
# Notice transform events.
if renpy.config.atl_multiple_events:
if self.transform_event != self.last_transform_event:
events.append(self.transform_event)
self.last_transform_event = self.transform_event
# Propagate transform_events from children.
if (self.child is not None) and self.child.transform_event != self.last_child_transform_event:
self.last_child_transform_event = self.child.transform_event
if self.child.transform_event is not None:
self.transform_event = self.child.transform_event
# Notice transform events, again.
if self.transform_event != self.last_transform_event:
events.append(self.transform_event)
self.last_transform_event = self.transform_event
if self.transform_event in renpy.config.repeat_transform_events:
self.transform_event = None
self.last_transform_event = None
old_exception_info = renpy.game.exception_info
if (self.atl_st_offset is None) or (st - self.atl_st_offset) < 0:
self.atl_st_offset = st
if self.atl.animation or self.transition:
timebase = at
else:
timebase = st - self.atl_st_offset
action, arg, pause = block.execute(trans, timebase, self.atl_state, events)
renpy.game.exception_info = old_exception_info
if action == "continue" and not renpy.display.predict.predicting:
self.atl_state = arg
else:
self.done = True
return pause
def predict_one(self):
self.atl.predict(self.context)
def visit(self):
block = self.get_block()
if block is None:
block = self.compile()
return self.children + block.visit() # type: ignore
# The base class for raw ATL statements.
class RawStatement(object):
constant = None
def __init__(self, loc):
super(RawStatement, self).__init__()
self.loc = loc
# Compiles this RawStatement into a Statement, by using ctx to
# evaluate expressions as necessary.
def compile(self, ctx): # @ReservedAssignment
raise Exception("Compile not implemented.")
# Predicts the images used by this statement.
def predict(self, ctx):
return
# RawBlock also has an analysis method which creates an Analysis
# object, applies passed parameters and calls mark_constant
def mark_constant(self, analysis):
"""
Sets self.constant to GLOBAL_CONST if all expressions used in
this statement and its children are constant.
`analysis`
A pyanalysis.Analysis object containing the analysis of this ATL.
"""
self.constant = NOT_CONST
# The base class for compiled ATL Statements.
class Statement(renpy.object.Object):
def __init__(self, loc):
super(Statement, self).__init__()
self.loc = loc
# trans is the transform we're working on.
# st is the time since this statement started executing.
# state is the state stored by this statement, or None if
# we've just started executing this statement.
# event is an event we're triggering.
#
# "continue", state, pause - Causes this statement to execute
# again, with the given state passed in the second time around.
#
#
# "next", timeleft, pause - Causes the next statement to execute,
# with timeleft being the amount of time left after this statement
# finished.
#
# "event", (name, timeleft), pause - Causes an event to be reported,
# and control to head up to the event handler.
#
# "repeat", (count, timeleft), pause - Causes the repeat behavior
# to occur.
#
# As the Repeat statement can only appear in a block, only Block
# needs to deal with the repeat behavior.
#
# Pause is the amount of time until execute should be called again,
# or None if there's no need to call execute ever again.
def execute(self, trans, st, state, events):
raise Exception("Not implemented.")
# Return a list of displayable children.
def visit(self):
return [ ]
# Does this respond to an event?
def _handles_event(self, event):
return False
# This represents a Raw ATL block.
class RawBlock(RawStatement):
# Should we use the animation timebase or the showing timebase?
animation = False
# If this block uses only constant values we can once compile it
# and use this value for all ATLTransform that use us as an atl.
compiled_block = None
def __init__(self, loc, statements, animation):
super(RawBlock, self).__init__(loc)
# A list of RawStatements in this block.
self.statements = statements
self.animation = animation
def compile(self, ctx): # @ReservedAssignment
compiling(self.loc)
statements = [ i.compile(ctx) for i in self.statements ]
return Block(self.loc, statements)
def predict(self, ctx):
for i in self.statements:
i.predict(ctx)
def analyze(self, parameters=None):
analysis = Analysis(None)
# Apply the passed parameters to take into account
# the names that are not constant in this context
if parameters is not None:
analysis.parameters(parameters)
self.mark_constant(analysis)
# We can only be a constant if we do not use values
# from parameters or do not have them at all.
# So we can pass an empty context for compilation.
if self.constant == GLOBAL_CONST:
self.compile_block()
def compile_block(self):
# This may failed if we use another transfrom
# which use non constant value.
# In this case we also non constant.
old_exception_info = renpy.game.exception_info
try:
block = self.compile(Context({}))
except RuntimeError: # PY3: RecursionError
raise Exception("This transform refers to itself in a cycle.")
except Exception:
self.constant = NOT_CONST
else:
self.compiled_block = block
renpy.game.exception_info = old_exception_info
def mark_constant(self, analysis):
constant = GLOBAL_CONST
for i in self.statements:
i.mark_constant(analysis)
constant = min(constant, i.constant)
self.constant = constant
# A compiled ATL block.
class Block(Statement):
def __init__(self, loc, statements):
super(Block, self).__init__(loc)
# A list of statements in the block.
self.statements = statements
# The start times of various statements.
self.times = [ ]
for i, s in enumerate(statements):
if isinstance(s, Time):
self.times.append((s.time, i + 1))
self.times.sort()
def _handles_event(self, event):
for i in self.statements:
if i._handles_event(event):
return True
return False
def execute(self, trans, st, state, events):
executing(self.loc)
# Unpack the state.
if state is not None:
index, start, loop_start, repeats, times, child_state = state
else:
index, start, loop_start, repeats, times, child_state = 0, 0, 0, 0, self.times[:], None
# What we might be returning.
action = "continue"
arg = None
pause = None
while action == "continue":
# Target is the time we're willing to execute to.
# Max_pause is how long we'll wait before executing again.
# If we have times queued up, then use them to inform target
# and time.
if times:
time, tindex = times[0]
target = min(time, st)
max_pause = time - target
# Otherwise, take the defaults.
else:
target = st
max_pause = 15
while True:
# If we've hit the last statement, it's the end of
# this block.
if index >= len(self.statements):
return "next", target - start, None
# Find the statement and try to run it.
stmt = self.statements[index]
action, arg, pause = stmt.execute(trans, target - start, child_state, events)
# On continue, persist our state.
if action == "continue":
if pause is None:
pause = max_pause
action, arg, pause = "continue", (index, start, loop_start, repeats, times, arg), min(max_pause, pause)
break
elif action == "event":
return action, arg, pause
# On next, advance to the next statement in the block.
elif action == "next":
index += 1