forked from martinkirsche/wired-logic
/
wired-logic.go
421 lines (374 loc) · 10.4 KB
/
wired-logic.go
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
package main
import (
"bytes"
"crypto/sha1"
"encoding/binary"
"fmt"
"image"
"image/color"
"image/gif"
"log"
"os"
)
const maxCharge = 6
func main() {
inputFileName := os.Args[1]
outputFileName := os.Args[2]
in, err := os.Open(inputFileName)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
gifImage, err := gif.DecodeAll(in)
if err != nil {
log.Fatal(err)
}
img := gifImage.Image[0]
log.Println("converting...")
simulation := NewSimulation(img)
log.Println("simulating...")
var frameCount int
simulation, frameCount = simulation.FindLooping()
log.Println("rendering...")
img.Palette[0] = color.Transparent
gifImage.Delay = make([]int, frameCount)
gifImage.Disposal = make([]byte, frameCount)
for i := range gifImage.Delay {
gifImage.Delay[i] = 1
}
gifImage.Image = simulation.DrawAll(img, frameCount)
log.Println("writing...")
out, err := os.Create(outputFileName)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
err = gif.EncodeAll(out, gifImage)
if err != nil {
log.Fatal(err)
}
log.Println("done.")
}
type circuit struct {
wires []*wire
transistors []*transistor
}
type wireState struct {
charge uint8
wire *wire
}
type Simulation struct {
circuit *circuit
states []wireState
}
func NewSimulation(img *image.Paletted) *Simulation {
size := img.Bounds().Size()
groups := make(map[*group]struct{}, 0)
matrix := newBucketMatrix(size.X, size.Y)
for y := 0; y < size.Y; y++ {
for x := 0; x < size.X; x++ {
c := img.ColorIndexAt(x, y)
if c > 0 && c <= maxCharge+1 {
topLeftBucket := matrix.get(x-1, y-1)
topBucket := matrix.get(x, y-1)
leftBucket := matrix.get(x-1, y)
var currentBucket *bucket
switch {
case nil == topBucket && nil == leftBucket:
currentBucket = newBucket()
groups[currentBucket.group] = struct{}{}
case nil == topBucket && nil != leftBucket:
currentBucket = leftBucket
case (nil != topBucket && nil == leftBucket) ||
topBucket == leftBucket ||
topBucket.group == leftBucket.group:
currentBucket = topBucket
default:
currentBucket = topBucket
delete(groups, topBucket.group)
topBucket.group.moveBucketsTo(leftBucket.group)
}
if nil != topLeftBucket && nil != topBucket && nil != leftBucket {
currentBucket.group.wire.isPowerSource = true
}
matrix.set(x, y, currentBucket)
currentBucket.addPixel(image.Point{x, y})
}
}
}
for y := 0; y < size.Y; y++ {
for x := 0; x < size.X; x++ {
if nil != matrix.get(x, y) {
continue
}
topBucket := matrix.get(x, y-1)
topRightBucket := matrix.get(x+1, y-1)
rightBucket := matrix.get(x+1, y)
bottomRightBucket := matrix.get(x+1, y+1)
bottomBucket := matrix.get(x, y+1)
bottomLeftBucket := matrix.get(x-1, y+1)
leftBucket := matrix.get(x-1, y)
topLeftBucket := matrix.get(x-1, y-1)
if nil == topLeftBucket && nil == topRightBucket && nil == bottomLeftBucket && nil == bottomRightBucket &&
nil != topBucket && nil != rightBucket && nil != bottomBucket && nil != leftBucket {
delete(groups, topBucket.group)
topBucket.group.moveBucketsTo(bottomBucket.group)
delete(groups, leftBucket.group)
leftBucket.group.moveBucketsTo(rightBucket.group)
}
}
}
transistors := make([]*transistor, 0)
for y := 0; y < size.Y; y++ {
for x := 0; x < size.X; x++ {
if nil != matrix.get(x, y) {
continue
}
topBucket := matrix.get(x, y-1)
topRightBucket := matrix.get(x+1, y-1)
rightBucket := matrix.get(x+1, y)
bottomRightBucket := matrix.get(x+1, y+1)
bottomBucket := matrix.get(x, y+1)
bottomLeftBucket := matrix.get(x-1, y+1)
leftBucket := matrix.get(x-1, y)
topLeftBucket := matrix.get(x-1, y-1)
switch {
case nil == bottomLeftBucket && nil == bottomRightBucket &&
nil == topBucket && nil != rightBucket && nil != bottomBucket && nil != leftBucket:
transistors = append(transistors,
newTransistor(image.Point{x, y}, bottomBucket.group.wire, rightBucket.group.wire, leftBucket.group.wire))
case nil == bottomLeftBucket && nil == topLeftBucket &&
nil != topBucket && nil == rightBucket && nil != bottomBucket && nil != leftBucket:
transistors = append(transistors,
newTransistor(image.Point{x, y}, leftBucket.group.wire, topBucket.group.wire, bottomBucket.group.wire))
case nil == topLeftBucket && nil == topRightBucket &&
nil != topBucket && nil != rightBucket && nil == bottomBucket && nil != leftBucket:
transistors = append(transistors,
newTransistor(image.Point{x, y}, topBucket.group.wire, rightBucket.group.wire, leftBucket.group.wire))
case nil == bottomRightBucket && nil == topRightBucket &&
nil != topBucket && nil != rightBucket && nil != bottomBucket && nil == leftBucket:
transistors = append(transistors,
newTransistor(image.Point{x, y}, rightBucket.group.wire, topBucket.group.wire, bottomBucket.group.wire))
}
}
}
wires := make([]*wire, len(groups))
wireStates := make([]wireState, len(groups))
i := 0
for k := range groups {
k.wire.index = i
wires[i] = k.wire
var charge uint8
if k.wire.isPowerSource {
charge = maxCharge
} else {
charge = 0
}
wireStates[i] = wireState{charge, k.wire}
i++
}
return &Simulation{&circuit{wires: wires, transistors: transistors}, wireStates}
}
func (s *Simulation) Step() *Simulation {
newWireState := make([]wireState, len(s.states))
for i, state := range s.states {
charge := state.charge
if !state.wire.isPowerSource {
source := s.tracePowerSource(state)
if source.charge > state.charge+1 {
charge = state.charge + 1
} else if source.charge <= state.charge && state.charge > 0 {
charge = state.charge - 1
}
}
newWireState[i] = wireState{charge, state.wire}
}
return &Simulation{s.circuit, newWireState}
}
func (s *Simulation) tracePowerSource(origin wireState) wireState {
result := origin
for _, transistor := range origin.wire.transistors {
if nil != transistor.base && s.states[transistor.base.index].charge > 0 {
continue
}
if origin.wire == transistor.inputA {
inputBState := s.states[transistor.inputB.index]
if transistor.inputB.isPowerSource {
return inputBState
}
if inputBState.charge > result.charge {
result = inputBState
continue
}
} else if origin.wire == transistor.inputB {
inputAState := s.states[transistor.inputA.index]
if transistor.inputA.isPowerSource {
return inputAState
}
if inputAState.charge > result.charge {
result = inputAState
continue
}
}
}
return result
}
func (s *Simulation) DiffDraw(previousSimulation *Simulation, img *image.Paletted) {
for i, state := range s.states {
if previousSimulation.states[i].charge == state.charge {
continue
}
state.wire.draw(img, state.charge+1)
}
}
func (s *Simulation) Draw(img *image.Paletted) {
for _, state := range s.states {
state.wire.draw(img, state.charge+1)
}
for _, transistor := range s.circuit.transistors {
transistor.draw(img, maxCharge+2)
}
}
func (s *Simulation) DrawAll(initialImage *image.Paletted, frameCount int) []*image.Paletted {
bounds := initialImage.Bounds()
images := make([]*image.Paletted, frameCount)
s.Draw(initialImage)
images[0] = initialImage
for f := 1; f < frameCount; f++ {
newSimulation := s.Step()
img := image.NewPaletted(bounds, initialImage.Palette)
newSimulation.DiffDraw(s, img)
images[f] = img
s = newSimulation
}
return images
}
func (s *Simulation) FindLooping() (*Simulation, int) {
hashs := make(map[[sha1.Size]byte]int, 0)
frame := 0
for {
s = s.Step()
var hash [sha1.Size]byte
copy(hash[:], s.Hash())
if f, ok := hashs[hash]; ok {
return s, frame - f
}
hashs[hash] = frame
frame++
}
}
func (s *Simulation) Hash() []byte {
hash := sha1.New()
for index, state := range s.states {
buf := new(bytes.Buffer)
err := binary.Write(buf, binary.LittleEndian, uint32(index))
if err != nil {
log.Fatal(err)
}
err = binary.Write(buf, binary.LittleEndian, state.charge)
if err != nil {
log.Fatal(err)
}
_, err = hash.Write(buf.Bytes())
if err != nil {
log.Fatal(err)
}
}
return hash.Sum(nil)
}
type transistor struct {
position image.Point
base *wire
inputA *wire
inputB *wire
}
func newTransistor(position image.Point, base, inputA, inputB *wire) *transistor {
transistor := &transistor{
position: position,
base: base,
inputA: inputA,
inputB: inputB,
}
inputA.transistors = append(inputA.transistors, transistor)
inputB.transistors = append(inputB.transistors, transistor)
return transistor
}
func (t *transistor) draw(img *image.Paletted, colorIndex uint8) {
img.SetColorIndex(t.position.X, t.position.Y, colorIndex)
}
type wire struct {
index int
pixels []image.Point
bounds image.Rectangle
transistors []*transistor
isPowerSource bool
}
func newWire() *wire {
return &wire{
index: -1,
pixels: make([]image.Point, 0),
bounds: image.Rectangle{image.Pt(0, 0), image.Pt(0, 0)},
transistors: make([]*transistor, 0),
isPowerSource: false,
}
}
func (w *wire) draw(img *image.Paletted, colorIndex uint8) {
for _, pixel := range w.pixels {
img.SetColorIndex(pixel.X, pixel.Y, colorIndex)
}
}
type bucketMatrix struct {
buckets [][]*bucket
width int
height int
}
func newBucketMatrix(width int, height int) *bucketMatrix {
m := &bucketMatrix{make([][]*bucket, height), width, height}
for y := 0; y < height; y++ {
m.buckets[y] = make([]*bucket, width)
}
return m
}
func (m *bucketMatrix) get(x int, y int) *bucket {
if x < 0 || y < 0 || x >= m.width || y >= m.height {
return nil
}
return m.buckets[y][x]
}
func (m *bucketMatrix) set(x int, y int, bucket *bucket) {
m.buckets[y][x] = bucket
}
type bucket struct {
group *group
}
func newBucket() *bucket {
newBucket := &bucket{nil}
newGroup := &group{
buckets: []*bucket{newBucket},
wire: newWire(),
}
newBucket.group = newGroup
return newBucket
}
func (b *bucket) addPixel(pixel image.Point) {
b.group.wire.pixels = append(b.group.wire.pixels, pixel)
b.group.wire.bounds = b.group.wire.bounds.Union(
image.Rectangle{
pixel,
pixel.Add(image.Point{1, 1})})
}
type group struct {
buckets []*bucket
wire *wire
}
func (g *group) moveBucketsTo(other *group) {
for _, bucket := range g.buckets {
bucket.group = other
other.buckets = append(other.buckets, bucket)
}
if g.wire.isPowerSource {
other.wire.isPowerSource = true
}
other.wire.bounds = other.wire.bounds.Union(g.wire.bounds)
other.wire.pixels = append(other.wire.pixels, g.wire.pixels...)
}