-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.cr
2680 lines (2123 loc) · 65.5 KB
/
app.cr
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
# FUN FACT: cells can move using messages
# FUN FACT: attacking one's own messages will make the cell follow entropy mountains,
# evading one's own messages will make the cell follow entropy valleys
# NOT SO FUN FACT: reading Tank#entropy() takes 30% of time in tick(). entropy is the
# biggest performance crappoint because it's read for every vesicle.
# when chemistries are there perhaps it'd be best to remove entropy()
# for vesicles (at least do jitter(0.0) by default for them)
# ANOTHER NOT SO FUN FACT: drawing vesicles is the second most expensive operation.
# perhaps drawing them as simple pixels will help, and also reduce
# the amount of vesicles drawn based on zoom level. another idea is
# to add a "toggle draw vesicles" function
require "lch"
require "lua"
require "uuid"
require "uuid/json"
require "json"
require "crsfml"
require "chipmunk"
require "chipmunk/chipmunk_crsfml"
require "colorize"
require "string_scanner"
require "open-simplex-noise"
require "./ext"
require "./line"
require "./buffer"
require "./view"
require "./controller"
require "./buffer_editor"
require "./expression_context"
require "./protocol"
require "./entity_collection"
FONT = SF::Font.from_memory({{read_file("./fonts/code/scientifica.otb")}}.to_slice)
FONT_BOLD = SF::Font.from_memory({{read_file("./fonts/code/scientificaBold.otb")}}.to_slice)
FONT_ITALIC = SF::Font.from_memory({{read_file("./fonts/code/scientificaItalic.otb")}}.to_slice)
FONT_UI = SF::Font.from_memory({{read_file("./fonts/ui/Roboto-Regular.ttf")}}.to_slice)
FONT_UI_MEDIUM = SF::Font.from_memory({{read_file("./fonts/ui/Roboto-Medium.ttf")}}.to_slice)
FONT_UI_BOLD = SF::Font.from_memory({{read_file("./fonts/ui/Roboto-Bold.ttf")}}.to_slice)
FONT.get_texture(11).smooth = false
FONT_BOLD.get_texture(11).smooth = false
FONT_ITALIC.get_texture(11).smooth = false
# https://www.desmos.com/calculator/bk3g3l6txg
def fmessage_amount(strength : Float)
if strength <= 80
1.8256 * Math.log(strength)
elsif strength <= 150
6/1225 * (strength - 80)**2 + 8
else
8 * Math.log(strength - 95.402)
end
end
def fmessage_amount_to_strength(amount : Float)
if amount < 8
Math::E**((625 * amount)/1141)
elsif amount < 32
(35 * Math.sqrt(amount - 8))/Math.sqrt(6) + 80
else
Math::E**(amount/8) + 47701/500
end
end
def fmessage_lifespan_ms(strength : Float)
if strength <= 155
2000 * Math::E**(-strength/60)
elsif strength <= 700
Math::E**(strength/100) + 146
else
190 * Math.log(strength)
end
end
def fmessage_lifespan_ms_to_strength(lifespan_ms : Float)
if lifespan_ms <= 151
60 * Math.log(2000/lifespan_ms)
elsif lifespan_ms <= 1242
100 * Math.log(lifespan_ms - 146)
else
Math::E**(lifespan_ms/190)
end
end
def fmagn_to_flow_scale(magn : Float)
if 3.684 <= magn
50/magn
elsif magn > 0
magn**2
else
0
end
end
def fmessage_strength_to_jitter(strength : Float)
if strength.in?(0.0..1000.0)
1 - (1/1000 * strength**2)/1000
else
0.0
end
end
module Inspectable
abstract def follow(in tank : Tank, view : SF::View) : SF::View
end
record Message, keyword : String, args : Array(Memorable), strength : Float64, decay = 0.0
abstract class Entity
include SF::Drawable
getter tt = TimeTable.new(App.time)
@decay_task_id : UUID
def initialize(@color : SF::Color, lifespan : Time::Span?)
@id = UUID.random
@tanks = [] of Tank
return unless lifespan
@decay_task_id = tt.after(lifespan) do
@tanks.each { |tank| suicide(in: tank) }
end
end
def self.z_index
0
end
def z_index
self.class.z_index
end
abstract def drawable
def summon(in tank : Tank)
@tanks << tank
tank.insert(self)
nil
end
def suicide(in tank : Tank)
@tanks.delete(tank)
tank.remove(self)
nil
end
def sync
end
def insert_into(collection : EntityCollection)
collection.insert(self.class, @id, entity: self)
end
def delete_from(collection : EntityCollection)
collection.delete(self.class, @id, entity: self)
end
def tick(delta : Float, in tank : Tank)
tt.tick
sync
end
def draw(target, states)
drawable.draw(target, states)
end
def draw(tank : Tank, target)
target.draw(self)
end
abstract def includes?(other : Vector2)
def_equals_and_hash @id
end
abstract class PhysicalEntity < Entity
@body : CP::Body
@shape : CP::Shape
private getter drawable : SF::Shape
def initialize(color : SF::Color, lifespan : Time::Span?)
super(color, lifespan)
@body = self.class.body
@shape = self.class.shape(@body)
@drawable = self.class.drawable(@color)
end
def width
@drawable.global_bounds.width + @drawable.local_bounds.left
end
def height
@drawable.global_bounds.height + @drawable.local_bounds.top
end
def self.mass
10.0
end
def self.friction
10.0
end
def self.elasticity
0.4
end
def mid
@body.position.x.at(@body.position.y)
end
def mid=(mid : Vector2)
@body.position = mid.cp
sync
mid
end
def stop
@body.velocity = 0.at(0).cp
end
def velocity
@body.velocity.x.at(@body.velocity.y)
end
def velocity=(velocity : Vector2)
@body.velocity = velocity.cp
velocity
end
def includes?(other : Vector2)
other.x.in?(mid.x - width//2..mid.x + width//2) &&
other.y.in?(mid.y - height//2..mid.y + height//2)
end
def summon(in tank : Tank)
super
tank.insert(self, @body)
tank.insert(self, @shape)
nil
end
def suicide(in tank : Tank)
super
tank.remove(self, @body)
tank.remove(self, @shape)
nil
end
def sync
@drawable.position = (mid - @shape.radius).sf
end
# Returns a sample [0; 1] from this cell's entropy device.
def entropy
return 0.0 if @tanks.empty?
mean = 0.0
@tanks.each do |tank|
mean += tank.entropy(mid)
end
mean / @tanks.size
end
def smack(other : Entity, in tank : Tank)
end
end
class RoundEntity < PhysicalEntity
def self.body
moment = CP::Circle.moment(mass, 0.0, radius)
CP::Body.new(mass, moment)
end
def self.shape(body : CP::Body)
shape = CP::Circle.new(body, radius)
shape.friction = friction
shape.elasticity = elasticity
shape
end
def self.drawable(color : SF::Color)
drawable = SF::CircleShape.new
drawable.radius = radius
drawable.fill_color = color
drawable
end
ANGLES = {0, 45, 90, 135, 180, 225, 270, 315}
# jitter: willingness to change elevation [0; 1]
property jitter = 0.0
# Amount of jitter ascent (0.0 = descent, 1.0 = ascent).
property jascent = 0.0
def tick(delta : Float, in tank : Tank)
super
return if @jitter.zero?
entropies = ANGLES.map { |angle| {angle, tank.entropy(mid + self.class.radius + angle.dir * self.class.radius)} }
min_hdg, _ = entropies.min_by { |angle, entropy| entropy }
max_hdg, _ = entropies.max_by { |angle, entropy| entropy }
#
# Compute weighed mean to get heading
#
ascent_w = @jascent
descent_w = 1 - @jascent
sines = 0
cosines = 0
sines += ascent_w * Math.sin(Math.radians(max_hdg))
cosines += ascent_w * Math.cos(Math.radians(max_hdg))
sines += descent_w * Math.sin(Math.radians(min_hdg))
cosines += descent_w * Math.cos(Math.radians(min_hdg))
heading = Math.degrees(Math.atan2(sines, cosines))
#
# Compute flow vector and flow scale.
#
flow_vec = heading.dir
flow_scale = fmagn_to_flow_scale(velocity.zero? ? 10 * @jitter : velocity.magn)
flow_scale_max = 13.572
flow_scale_norm = flow_scale / flow_scale_max
@body.velocity += (flow_vec * flow_scale).cp * @jitter
end
def self.radius
4
end
end
class Vesicle < RoundEntity
def initialize(
@message : Message,
impulse : Vector2,
lifespan : Time::Span,
color : SF::Color,
@birth : Time::Span
)
super(color, lifespan)
@body.apply_impulse_at_local_point(impulse.cp, CP.v(0, 0))
end
def self.z_index
1
end
def self.drawable(color : SF::Color)
drawable = super
drawable.point_count = 5
drawable
end
def decay
@tt.progress(@decay_task_id)
end
def message
@message.copy_with(decay: decay)
end
delegate :keyword, to: @message
def nargs
@message.args.size
end
def self.radius
0.5
end
def self.mass
0.5
end
def self.friction
0.7
end
def self.elasticity
1.0
end
def tick(delta : Float, in tank : Tank)
@jitter = fmessage_strength_to_jitter(@message.strength * (1 - decay))
super
end
def smack(other : Cell, in tank : Tank)
other.receive(self, tank)
end
end
# An excerpt with a beginning and an end. Keeps positional
# information in sync with the excerpt string.
#
# Note that in the excerpt range, the end point is excluded.
# That is, the excerpt range is [b; e)
record Excerpt, string : String, start : Int32 do
# Returns the end index of this excerpt in the source string.
def end : Int
start + string.size
end
# Maps *index* in this excerpt to the corresponding index in
# the source string.
def map(index : Int) : Int
start + index
end
# Removes whitespace from the left and right of this excerpt.
# Adjusts positional information accordingly.
def strip : Excerpt
orig = string
lstr = orig.lstrip
rstr = lstr.rstrip
Excerpt.new(
string: rstr,
start: start + (orig.size - lstr.size),
)
end
# Concatenates this and *other* excerpts.
#
# *other* excerpt must start immediately after this excerpt.
# That is, its beginning must be the same as this excerpt's
# end. Otherwise, this method will raise.
def +(other : Excerpt)
unless other.start == self.end
raise ArgumentError.new("'+': right bounded excerpt must follow the left bounded excerpt")
end
Excerpt.new(string + other.string, start)
end
end
# Represents the result of parsing a block. It's optionally
# a rule, plus zero or more markers.
record ParseResult, rule : Rule? = nil, markers = [] of Marker do
# A shorthand for an error result with no rule and a single
# hint marker.
def self.hint(offset : Int, message : String)
new(markers: [Marker.hint(offset, message)])
end
# A shorthand for a success result with `KeywordRule` rule
# and no markers.
def self.keyword(keyword : Excerpt, params : Array(Excerpt), lua : Excerpt)
new(rule: KeywordRule.new(keyword, params, lua))
end
# A shorthand for a success result with `HeartbeatRule` rule
# and no markers.
def self.heartbeat(keyword : Excerpt, lua : Excerpt, period : Time::Span? = nil)
new(rule: HeartbeatRule.new(keyword, lua, period))
end
end
# Blocks are intermediates between raw source and `Rule`s.
abstract struct Block
# Tries to convert this block into the corresponding `Rule`.
abstract def to_rule : ParseResult
end
# Birth blocks are implicit blocks that consist of code only,
# and are later converted into `BirthRule`s.
#
# ```synapse
# -- The following Lua code will be stored under the birth
# -- block/birth rule.
# x = 123
# y = 456
# z = "hello world"
#
# heartbeat |
# -- And this is going to be stored under a rule block /
# -- keyword rule (heartbeat)
# x = x + 1
# ```
record BirthBlock < Block, code : Excerpt do
def to_rule : ParseResult
ParseResult.new rule: BirthRule.new(code)
end
end
record RuleBlock < Block, header : Excerpt, code : Excerpt do
def to_rule : ParseResult
scanner = StringScanner.new(header.string)
#
# Parse message keyword.
#
# <messageKeyword> ::= <alpha> <alnum>*
#
start = header.map(scanner.offset)
unless keyword = scanner.scan(/(?:[A-Za-z]\w*|\*)/)
return ParseResult.hint(start, "I want keyword (aka message name) here!")
end
heartbeat = keyword == "heartbeat"
keyword = Excerpt.new(keyword, start)
if heartbeat
#
# Parse heartbeat. Heartbeat does not take parameters.
# It's either a period or the pipe.
#
# <heartbeat> ::= "heartbeat" WS (<period> | "|")
#
start = header.map(scanner.offset)
unless scanner.scan(/[ \t]+/)
return ParseResult.hint(start, "I want whitespace here!")
end
start = header.map(scanner.offset)
if number = scanner.scan(/[1-9][0-9]*/)
start = header.map(scanner.offset)
unless unit = scanner.scan(/m?s/)
return ParseResult.hint(start, "I want a time unit here, either 'ms' (for milliseconds) or 's' (for seconds)")
end
case unit
when "ms"
period = number.to_i.milliseconds
when "s"
period = number.to_i.seconds
end
end
result = ParseResult.heartbeat(keyword, code, period)
else
#
# Parse message parameters. Parameters follow the keyword,
# therefore, a leading whitespace is always expected.
#
# <params> ::= (WS <param>)*
# <param> ::= <alpha> <alnum>*
#
start = header.map(scanner.offset)
params = [] of Excerpt
while param = scanner.scan(/[ \t]+(?:[A-Za-z]\w*)/)
params << Excerpt.new(param, start).strip
start = header.map(scanner.offset)
end
result = ParseResult.keyword(keyword, params, code)
end
#
# Make sure that the pipe character itself is in the
# right place.
#
unless scanner.scan(/[ \t]*\|/)
return ParseResult.hint(header.map(scanner.offset), "I want space followed by pipe '|' here!")
end
result
end
end
record Marker, color : SF::Color, offset : Int32, tally : Hash(String, Int32) do
def initialize(color, offset, message : String)
hash = Hash(String, Int32).new(0)
initialize(color, offset, message.lines.tally_by(hash, &.itself))
end
def self.hint(offset, message)
hint_color = SF::Color.new(0xFF, 0xCA, 0x28)
new(hint_color, offset, message)
end
def message
String.build do |io|
tally.each do |line, count|
io << line
unless count == 1
io << "(x" << count << ")"
end
end
end
end
def stack(other : Marker)
tally.merge!(other.tally) do |_, l, r|
l + r
end
self
end
end
alias MarkerCollection = Hash(Int32, Marker)
class ProtocolEditorState
getter id : UUID # TODO: remove
property protocol : Protocol # TODO: remove
property? sync : Bool # TODO: remove
getter bstate # TODO: remove
getter markers # TODO: remove
def initialize(@protocol, @bstate = BufferEditorState.new, @markers = MarkerCollection.new, @sync = true)
@id = UUID.random
end
delegate :cursor, :cursor=, to: @bstate # TODO: remove
delegate :buffer, :buffer=, to: @bstate # TODO: remove
delegate :markers, :markers=, to: @bstate # TODO: remove
end
class ProtocolEditor
include SF::Drawable
getter state # TODO: remove
def initialize(@cell : Cell, @state : ProtocolEditorState)
@editor_view = BufferEditorView.new
@editor_view.active = true
@editor = BufferEditor.new(@state.bstate, @editor_view)
end
def initialize(cell : Cell, protocol : Protocol)
initialize(cell, ProtocolEditorState.new(protocol))
end
def initialize(cell : Cell, other : ProtocolEditor)
initialize(cell, other.state)
end
# TODO: remove
private delegate :protocol, :protocol=, to: @state
# TODO: remove
private delegate :markers, :markers=, to: @state
# TODO: remove
private delegate :sync?, :sync=, to: @state
# Editor needs to be refreshed when protocoleditor is focused
# because other cells that have the same protocol (copies) may
# have altered it.
def refresh
@editor.refresh
end
def update
before = @state.bstate.capture
yield
after = @state.bstate.capture
unless before == after
markers.clear
parse(after.string)
end
end
def unsync(err : ErrResult)
# Signal that what's currently running is out of sync from
# what's being shown.
self.sync = false
mark(SF::Color::Red, err.index, err.error.message || "lua error")
end
def mark(color : SF::Color, offset : Int32, message : String)
mark Marker.new(color, offset, message)
end
def mark(marker : Marker)
# FIXME: this is MarkerCollection business!
if prev = markers[marker.offset]?
marker = prev.stack(marker)
end
markers[marker.offset] = marker
end
def editor_handle(buf, event)
end
def handle(event)
update { @editor.handle(event) }
end
def rules_in(source : String)
stack = [BirthBlock.new(Excerpt.new("", 0))] of Block
offset = 0
results = [] of ParseResult
source.each_line(chomp: false) do |line|
excerpt = Excerpt.new(line, offset)
offset += line.size
content = excerpt.strip
if content.string.ends_with?('|')
results << stack.pop.to_rule
stack << RuleBlock.new(content, Excerpt.new("", excerpt.end))
next
end
top = stack.last
stack[-1] = top.copy_with(code: top.code + excerpt)
end
stack.each do |block|
results << block.to_rule
end
results
end
def parse(source : String)
results = rules_in(source)
signatures = Set(RuleSignature).new
if results.empty?
self.sync = true
protocol.rewrite(signatures)
return
end
error = false
results.each do |result|
if rule = result.rule
rule.signature(to: signatures)
protocol.update(for: @cell, newer: rule)
else
error = true
result.markers.each do |marker|
mark(marker)
end
end
end
self.sync = !error
unless error
protocol.rewrite(signatures)
end
end
# **Warning**: invalid before the first draw.
getter origin : Vector2 = 0.at(0)
# **Warning**: invalid before the first draw.
getter corner : Vector2 = 0.at(0)
def draw(target, states)
@origin = origin = @cell.mid + @cell.class.radius * 1.1
@editor_view.position = (origin + 15.at(15)).sfi
extent = @editor_view.size + SF.vector2f(30, 30)
@corner = origin + Vector2.new(extent)
sync_color = sync? ? SF::Color.new(0x81, 0xD4, 0xFA, 0x88) : SF::Color.new(0xEF, 0x9A, 0x9A, 0x88)
sync_color_opaque = SF::Color.new(sync_color.r, sync_color.g, sync_color.b)
#
# Draw line from origin of editor to center of cell.
#
va = SF::VertexArray.new(SF::Lines, 2)
va.append(SF::Vertex.new(@cell.mid.sfi, sync_color_opaque))
va.append(SF::Vertex.new(origin.sfi, sync_color_opaque))
va.draw(target, states)
#
# Draw little circles at start of line to really show
# which cell is selected.
#
start_circle = SF::CircleShape.new(radius: 2)
start_circle.fill_color = sync_color_opaque
start_circle.position = (@cell.mid - 2).sfi
start_circle.draw(target, states)
#
# Draw background rectangle.
#
bg_rect = SF::RectangleShape.new
bg_rect.fill_color = SF::Color.new(0x42, 0x42, 0x42, 0xbb)
bg_rect.position = (origin + 5.at(1)).sfi
bg_rect.outline_thickness = 1
bg_rect.outline_color = sync_color # SF::Color.new(0x42, 0x42, 0x42, 0xee)
bg_rect.size = extent - SF.vector2f(0, 2)
bg_rect.draw(target, states)
#
# Draw thick left bar which shows whether the code is
# synchronized with what's running.
#
bar = SF::RectangleShape.new
bar.fill_color = sync_color
bar.position = origin.sfi
bar.size = SF.vector2f(4, extent.y)
bar.draw(target, states)
#
# Underline every keyword rule. Keyword index and parameter
# indices are assumed to be on the same line.
#
# If out of sync (errors occured), the underlines are not
# drawn since the editor is probably in a bad state or they
# would be drawn incorrectly anyway.
#
rule_headers = [] of SF::RectangleShape
rule_header_bg = SF::Color.new(0x51, 0x51, 0x51)
protocol.each_keyword_rule do |kwrule|
next unless sync?
b = kwrule.header_start
b_pos = @editor_view.find_character_pos(b)
h_bg = SF::RectangleShape.new
h_bg.position = SF.vector2f(bg_rect.position.x, b_pos.y) + @editor_view.beam_margin
h_bg.size = SF.vector2f(bg_rect.size.x, @editor_view.font_size)
h_bg.fill_color = rule_header_bg
h_sep_top = SF::RectangleShape.new
h_sep_top.position = h_bg.position
h_sep_top.size = SF.vector2f(h_bg.size.x, 1)
h_sep_top.fill_color = SF::Color.new(0x61, 0x61, 0x61)
h_sep_bot = SF::RectangleShape.new
h_sep_bot.position = h_bg.position + SF.vector2f(0, h_bg.size.y)
h_sep_bot.size = SF.vector2f(h_bg.size.x, 1)
h_sep_bot.fill_color = SF::Color.new(0x61, 0x61, 0x61)
rule_headers << h_bg
rule_headers << h_sep_top
rule_headers << h_sep_bot
end
rule_headers.each &.draw(target, states)
@editor.draw(target, states)
#
# Draw markers
#
markers.each_value do |marker|
coords = @editor_view.find_character_pos(marker.offset)
# If cursor is below marker offset, we want this marker
# to be above.
m_line = state.bstate.index_to_line(marker.offset)
c_line = state.bstate.line
flip = c_line.ord > m_line.ord
offset = SF.vector2f(0, @editor_view.line_height)
coords += flip ? SF.vector2f(3, -3.5) : offset
# To enable variation while maintaining uniformity with
# the original color.
l, c, h = LCH.rgb2lch(marker.color.r, marker.color.g, marker.color.b)
bg_l = 70
fg_l = 40
mtext = SF::Text.new(marker.message, FONT, 11)
mbg_rect_position = coords + (flip ? SF.vector2f(-6, -@editor_view.line_height - 0.2) : SF.vector2f(-3, 4.5))
mbg_rect_size = SF.vector2f(
mtext.global_bounds.width + mtext.local_bounds.left + 10,
mtext.global_bounds.height + mtext.local_bounds.top + 4
)
#
# Draw shadow rect for the marker text.
#
mshadow_rect = SF::RectangleShape.new
mshadow_rect.position = mbg_rect_position + SF.vector2f(2, 2)
mshadow_rect.size = mbg_rect_size
mshadow_rect.fill_color = SF::Color.new(*LCH.lch2rgb(fg_l, c, h), 0x55)
mshadow_rect.draw(target, states)
@corner = @corner.max(Vector2.new(mshadow_rect.position + mshadow_rect.size))
#
# Draw the little triangle in the corner, pointing to the
# marker offset.
#
tri = SF::CircleShape.new(radius: 3, point_count: 3)
tri.fill_color = SF::Color.new(*LCH.lch2rgb(bg_l, c, h))
tri.position = coords
if flip
tri.position += SF.vector2f(0, 4)
tri.origin = SF.vector2f(3, 3)
tri.rotate(180.0)
end
tri.draw(target, states)
#
# Draw background rectangle for the marker text.
#
mbg_rect = SF::RectangleShape.new
mbg_rect.position = mbg_rect_position
mbg_rect.size = mbg_rect_size
mbg_rect.fill_color = SF::Color.new(*LCH.lch2rgb(bg_l, c, h))
mbg_rect.draw(target, states)
#
# Draw marker text.
#
mtext.fill_color = SF::Color.new(*LCH.lch2rgb(fg_l, c, h))
mtext.position = Vector2.new(mbg_rect.position + SF.vector2f(5, 2)).sfi
mtext.draw(target, states)
end
end
end
alias Memorable = Bool | Float64 | Lua::Table | String | Nil
class Cell < RoundEntity
include Inspectable
class InstanceMemory
include LuaCallable
def initialize(@cell : Cell)
@store = {} of String => Memorable
end
def _index(key : String)
@store[key]?
end
def _newindex(key : String, val : Memorable)
@store[key] = val
@cell.on_memory_changed
end
end
getter memory : InstanceMemory do
InstanceMemory.new(self)
end
@wires = Set(Wire).new
def initialize
super(self.class.color, lifespan: nil)
@protocol = Protocol.new
@relatives = [] of Cell
@editor = uninitialized ProtocolEditor
@editor = ProtocolEditor.new(self, @protocol)
@relatives << self
end
def initialize(color : SF::Color, @protocol : Protocol, editor : ProtocolEditor, @relatives : Array(Cell))
super(color, lifespan: nil)
@editor = uninitialized ProtocolEditor
@editor = ProtocolEditor.new(self, editor)
end
def copy
copy = Cell.new(@color, @protocol, @editor, @relatives)
@relatives << copy
copy
end
def self.radius
15
end
def self.mass