summaryrefslogtreecommitdiff
path: root/genshaders.go
blob: 494380693d666774a1887f49e14966476abbcc8d (plain)
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
// genshaders is a tool to generate fragment shaders that implement the
// X11 GC operations, and to generate fragment shaders that implement
// (some of) the RENDER extension blend operations.
//
// Note that some of the generated shaders are much more complex than
// they need to be; genshaders relies on the fxc optimizer to elimiate
// dead code. For example, the entire noop set contains generated code
// for the rest of the GC operations, but fxc optimizes it all to a
// single discard instruction.
//
// Also generated are a few useful vertex and geometry shaders.

package main

import (
	"bytes"
	"flag"
	"fmt"
	"os"
	"os/exec"
	"runtime"
	"sync"
	"text/template"
)

type compInfo struct {
	name   string
	suffix string
}

var compile = flag.Bool("compile", false, "Invoke the fxc compiler on each shader")

func compiler(wg *sync.WaitGroup, log chan string, in chan compInfo) {
	var errorBuf bytes.Buffer
	for {
		ci := <-in
		if *compile {
			model := ci.suffix + "_4_0"

			out, err := os.Create(ci.name + ".asm")
			if err != nil {
				panic(err)
			}
			cmd := exec.Command("fxc", "/T"+model, "/O3", ci.name+".hl"+ci.suffix)
			cmd.Stdout = out
			errorBuf.Reset()
			cmd.Stderr = &errorBuf
			err = cmd.Run()
			if err != nil {
				fmt.Fprintln(os.Stderr, "\nFatal Error while creating asm file", ci.name)
				fmt.Fprintln(os.Stderr, err.Error())
				errorBuf.WriteTo(os.Stderr)
				os.Exit(1)
			}
			out.Close()

			cmd = exec.Command("fxc", "/T"+model, "/O3", ci.name+".hl"+ci.suffix, "/Fo"+ci.name+"."+ci.suffix)
			cmd.Run()

			out, err = os.Create(ci.name + ".h")
			if err != nil {
				panic(err)
			}
			cmd = exec.Command("xxd", "-i", ci.name+"."+ci.suffix)
			cmd.Stdout = out
			errorBuf.Reset()
			cmd.Stderr = &errorBuf
			err = cmd.Run()
			if err != nil {
				fmt.Fprintln(os.Stderr, "\n Fatal Error while xxding", ci.name)
				fmt.Fprintln(os.Stderr, err.Error())
				errorBuf.WriteTo(os.Stderr)
				os.Exit(1)
			}
			out.Close()

			log <- ci.name + " Compiled."
		}
		wg.Done()
	}
}

type GlyphS struct {
	Cbuf     string
	TilePos  string
	GlyphPos string
	OutPos   string
}

func doVert(wg *sync.WaitGroup, log chan string, comp chan compInfo) {
	wg.Add(3)

	vt, err := template.ParseFiles("vertex.template")
	if err != nil {
		panic(err)
	}
	out, err := os.Create("size_calc.hlvs")
	if err != nil {
		panic(err)
	}
	err = vt.Execute(out, nil)
	if err != nil {
		panic(err)
	}
	out.Close()
	comp <- compInfo{"size_calc", "vs"}

	glypht, err := template.ParseFiles("glyphs.template")
	if err != nil {
		panic(err)
	}
	out, err = os.Create("render_glyphs.hlvs")
	if err != nil {
		panic(err)
	}
	render := GlyphS{"", "input.glyph_pos", "0", "0"}
	err = glypht.Execute(out, &render)
	if err != nil {
		panic(err)
	}
	out.Close()
	comp <- compInfo{"render_glyphs", "vs"}

	out, err = os.Create("core_glyphs.hlvs")
	if err != nil {
		panic(err)
	}
	core := GlyphS{`
cbuffer output_info :register(b1) {
    uint2  out_offset;
}
`,
		"input.pos - tile_offset",
		"input.glyph_pos / (float2)clip_size",
		"input.pos - out_offset"}
	err = glypht.Execute(out, &core)
	if err != nil {
		panic(err)
	}
	out.Close()
	comp <- compInfo{"core_glyphs", "vs"}

	log <- "Vertex shaders done."
	wg.Done()
}

func doGeom(wg *sync.WaitGroup, log chan string, comp chan compInfo) {
	gt, err := template.ParseFiles("geometry.template")
	if err != nil {
		panic(err)
	}
	out, err := os.Create("line2rect.hlgs")
	if err != nil {
		panic(err)
	}
	err = gt.Execute(out, nil)
	if err != nil {
		panic(err)
	}
	out.Close()

	wg.Add(1)
	comp <- compInfo{"line2rect", "gs"}

	log <- "Geometry shader done."
	wg.Done()
}

type pixelInfo struct {
	Rop            string
	Style          string
	PlaneMask      string
	ClipMask       string
	Tex            string
	ClipMaskBlock  string
	Load           string
	RopBlock       string
	PlaneMaskBlock string
}

var rop = [...]string{"clear", "and", "andreverse", "copy", "andinverted", "noop", "xor", "or", "nor", "equiv", "invert", "orreverse", "copyinverted", "orinverted", "nand", "set"}
var style = [...]string{"solid", "tile", "stipple", "opaquestip"}
var planemask = [...]string{"fullmask", "planemask"}
var clipmask = [...]string{"unclipped", "clipmask"}

func forEachCore(cb func(r, s, p, c string)) {
	for _, c := range clipmask {
		for _, p := range planemask {
			for _, s := range style {
				for _, r := range rop {
					cb(r, s, p, c)
				}
			}
		}
	}
}

func forEachCopyPlane(cb func(r, s, p, c string)) {
	for _, c := range clipmask {
		for _, p := range planemask {
			for _, r := range rop {
				cb(r, "copyplane", p, c)
			}
		}
	}
}

func doPixel(wg *sync.WaitGroup, log chan string, comp chan compInfo) {
	pt, err := template.ParseFiles("pixel.template")
	if err != nil {
		panic(err)
	}

	cmask := map[string]string{
		"unclipped": "",
		"clipmask": `    // Test clip mask
    float4 cm = clipmask.Sample(point_sample, input.clip_pos);
    if (cm.r < 0.5) {
        discard;
        return 0;
    }

`}
	pmask := map[string]string{
		"fullmask": "",
		"planemask": `
    // planemask
    color = (color & planemask) | (out_color & ~planemask);
`}
	style := map[string]string{
		"solid": "    color = foreground;",
		"tile": `    int3 tp;
    tp.xy = input.tile_pos.xy % tile_wh.xy;
    tp.z = 0;
    color = tile.Load(tp);`,
		"stipple": `    float4 pt = stipple.Sample(point_sample, input.tile_pos);
    if (pt.r < 0.5) {
        discard;
        return 0;
    }
    color = foreground;`,
		"opaquestip": `    float4 pt = stipple.Sample(point_sample, input.tile_pos);
    color = foreground;
    if (pt.r < 0.5)
        color = background;`,
		"copyplane": `    int3 tp;
    tp.xy = input.tile_pos.xy % tile_wh.xy;
    tp.z = 0;
    color = tile.Load(tp);
    if (any(color & plane))
        color = foreground;
    else
        color = background;`,
	}
	rop := map[string]string{
		"clear":        "color = 0",
		"and":          "color = color & out_color",
		"andreverse":   "color = color & ~out_color",
		"copy":         "color = color",
		"andinverted":  "color = ~color & out_color",
		"noop":         "discard",
		"xor":          "color = color ^ out_color",
		"or":           "color = color | out_color",
		"nor":          "color = ~color & ~out_color",
		"equiv":        "color = ~color ^ out_color",
		"invert":       "color = ~out_color",
		"orreverse":    "color = color | ~out_color",
		"copyinverted": "color = ~color",
		"orinverted":   "color = ~color | out_color",
		"nand":         "color = ~color | ~out_color",
		"set":          "color = 255",
	}

	var pi pixelInfo
	for pi.ClipMask, pi.ClipMaskBlock = range cmask {
		for pi.PlaneMask, pi.PlaneMaskBlock = range pmask {
			for pi.Style, pi.Load = range style {
				for pi.Rop, pi.RopBlock = range rop {
					name := pi.Rop + "_" + pi.Style + "_" + pi.PlaneMask + "_" + pi.ClipMask
					pi.Tex = ""
					switch pi.Style {
					case "stipple", "opaquestip":
						pi.Tex = "\nTexture2D stipple : register(t0);"
					case "tile", "copyplane":
						pi.Tex = "\nTexture2D<uint4> tile : register(t0);"
					}
					if pi.ClipMask == "clipmask" {
						pi.Tex += "\nTexture2D clipmask : register(t1);"
					}

					out, err := os.Create(name + ".hlps")
					if err != nil {
						panic(err)
					}
					err = pt.Execute(out, &pi)
					if err != nil {
						panic(err)
					}
					out.Close()
					wg.Add(1)
					comp <- compInfo{name, "ps"}
				}
			}
		}
	}

	pix_h, err := os.Create("pixel_shaders.h")
	if err != nil {
		panic(err)
	}
	fmt.Fprintln(pix_h, "/* Automatically generated file; do not edit */")
	fmt.Fprintln(pix_h)
	include := func(rop, style, planemask, clipmask string) {
		name := rop + "_" + style + "_" + planemask + "_" + clipmask
		fmt.Fprintln(pix_h, `#include "`+name+`.h"`)
	}
	ps := func(rop, style, planemask, clipmask string) {
		name := "    " + rop + "_" + style + "_" + planemask + "_" + clipmask + "_ps,"
		fmt.Fprintln(pix_h, name)
	}
	ps_len := func(rop, style, planemask, clipmask string) {
		name := "    " + rop + "_" + style + "_" + planemask + "_" + clipmask + "_ps_len,"
		fmt.Fprintln(pix_h, name)
	}
	forEachCore(include)
	forEachCopyPlane(include)

	fmt.Fprintln(pix_h)
	fmt.Fprintln(pix_h, "static const unsigned char *core_ps[] = {")
	forEachCore(ps)
	fmt.Fprintln(pix_h, "};")
	fmt.Fprintln(pix_h)

	fmt.Fprintln(pix_h, "static const unsigned int core_ps_len[] = {")
	forEachCore(ps_len)
	fmt.Fprintln(pix_h, "};")
	fmt.Fprintln(pix_h)

	fmt.Fprintln(pix_h, "static const unsigned char *copyplane_ps[] = {")
	forEachCopyPlane(ps)
	fmt.Fprintln(pix_h, "};")
	fmt.Fprintln(pix_h)

	fmt.Fprintln(pix_h, "static const unsigned int copyplane_ps_len[] = {")
	forEachCopyPlane(ps_len)
	fmt.Fprintln(pix_h, "};")

	pix_h.Close()
	log <- "Pixel shaders done."
	wg.Done()
}

func foreachRenderSimple(cb func(name string, hasmask, srcswiz, dstswiz, maskswiz, compalpha, skip bool)) {
	falsetrue := [...]bool{false, true}
	for _, srcswizzle := range falsetrue {
		for _, dstswizzle := range falsetrue {
			for _, hasmask := range falsetrue {
				for _, maskswizzle := range falsetrue {
					for _, componentalpha := range falsetrue {
						skip := maskswizzle && !hasmask
						skip = skip || (componentalpha && !hasmask)

						name := "render_simple" + map[bool]string{true: "_sswiz"}[srcswizzle] +
							map[bool]string{true: "_dswiz"}[dstswizzle] +
							map[bool]string{true: "_mask"}[hasmask] +
							map[bool]string{true: "_swiz"}[maskswizzle] +
							map[bool]string{true: "_ca"}[componentalpha]

						cb(name, hasmask, srcswizzle, dstswizzle, maskswizzle, componentalpha, skip)
					}
				}
			}
		}
	}
}

type simpleRender struct {
	Description                        string
	SrcSwiz, Mask, MaskSwiz, CompAlpha string
	Return                             string
}

func doRender(wg *sync.WaitGroup, log chan string, comp chan compInfo) {
	rt, err := template.ParseFiles("simple.template")
	if err != nil {
		panic(err)
	}

	simple_h, err := os.Create("render_simple_shaders.h")
	if err != nil {
		panic(err)
	}
	fmt.Fprintln(simple_h, "/* Automatically generated file; do not edit */")
	fmt.Fprintln(simple_h)

	foreachRenderSimple(func(name string, hasmask, srcswiz, dstswiz, maskswiz, compalpha, skip bool) {
		if skip {
			return
		}

		fmt.Fprintln(simple_h, `#include "`+name+`.h"`)

		var sr simpleRender
		if srcswiz {
			sr.Description += " for source swizzled"
		}
		if hasmask {
			sr.Description += " with mask"
		}
		if maskswiz {
			sr.Description += " swizzled"
		}
		if compalpha {
			sr.Description += ", component alpha"
		}
		if srcswiz {
			sr.SrcSwiz = `
    s.a = s.r;
    s.rgb = 0;`
		}

		if hasmask {
			sr.Mask = "\n    float4 m = mask.Sample(mask_sample, input.mask_pos);"
			if maskswiz {
				sr.MaskSwiz = "\n    m.a = m.r;"
			}
			sr.CompAlpha = "\n    s *= m.a;"
			if compalpha {
				sr.CompAlpha = "\n    s *= m;"
			}
		}
		sr.Return = "s"
		if dstswiz {
			sr.Return = "s.a"
		}

		out, err := os.Create(name + ".hlps")
		if err != nil {
			panic(err)
		}
		err = rt.Execute(out, &sr)
		if err != nil {
			panic(err)
		}
		out.Close()
		wg.Add(1)
		comp <- compInfo{name, "ps"}
	})

	fmt.Fprintln(simple_h)
	fmt.Fprintln(simple_h, "static const unsigned char *render_simple[] = {")
	foreachRenderSimple(func(name string, hasmask, srcswiz, dstswiz, maskswiz, compalpha, skip bool) {
		if skip {
			fmt.Fprintln(simple_h, "    NULL,")
		} else {
			fmt.Fprintln(simple_h, "    "+name+"_ps,")
		}
	})
	fmt.Fprintln(simple_h, "};")
	fmt.Fprintln(simple_h)
	fmt.Fprintln(simple_h, "static const unsigned int render_simple_len[] = {")
	foreachRenderSimple(func(name string, hasmask, srcswiz, dstswiz, maskswiz, compalpha, skip bool) {
		if skip {
			fmt.Fprintln(simple_h, "    0,")
		} else {
			fmt.Fprintln(simple_h, "    "+name+"_ps_len,")
		}
	})
	fmt.Fprintln(simple_h, "};")
	simple_h.Close()

	log <- "Render shaders done."
	wg.Done()
}

func logger(wg *sync.WaitGroup, in chan string) {
	for {
		msg := <-in
		if msg == "" {
			wg.Done()
			return
		}
		fmt.Println(msg)
	}
}

func main() {
	flag.Parse()

	var wg sync.WaitGroup
	log := make(chan string)
	go logger(&wg, log)

	// Limit number of concurrent compiles
	compile := make(chan compInfo)
	for i := 0; i < runtime.NumCPU(); i++ {
		go compiler(&wg, log, compile)
	}

	wg.Add(4)
	go doVert(&wg, log, compile)
	go doGeom(&wg, log, compile)
	go doPixel(&wg, log, compile)
	go doRender(&wg, log, compile)
	wg.Wait()

	wg.Add(1)
	log <- "Done."
	log <- ""
	wg.Wait()
}