forked from cucy/unipdf1
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfunctions.go
855 lines (729 loc) · 22 KB
/
functions.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
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
/*
* This file is subject to the terms and conditions defined in
* file 'LICENSE.md', which is part of this source code package.
*/
package model
import (
"errors"
"math"
"github.com/unidoc/unipdf/v3/common"
"github.com/unidoc/unipdf/v3/core"
"github.com/unidoc/unipdf/v3/internal/sampling"
"github.com/unidoc/unipdf/v3/ps"
)
// PdfFunction interface represents the common methods of a function in PDF.
type PdfFunction interface {
Evaluate([]float64) ([]float64, error)
ToPdfObject() core.PdfObject
}
// In PDF: A function object may be a dictionary or a stream, depending on the type of function.
// - Stream: Type 0, Type 4
// - Dictionary: Type 2, Type 3.
// Loads a PDF Function from a PdfObject (can be either stream or dictionary).
func newPdfFunctionFromPdfObject(obj core.PdfObject) (PdfFunction, error) {
obj = core.ResolveReference(obj)
if stream, is := obj.(*core.PdfObjectStream); is {
dict := stream.PdfObjectDictionary
ftype, ok := dict.Get("FunctionType").(*core.PdfObjectInteger)
if !ok {
common.Log.Error("FunctionType number missing")
return nil, errors.New("invalid parameter or missing")
}
if *ftype == 0 {
return newPdfFunctionType0FromStream(stream)
} else if *ftype == 4 {
return newPdfFunctionType4FromStream(stream)
} else {
return nil, errors.New("invalid function type")
}
} else if indObj, is := obj.(*core.PdfIndirectObject); is {
// Indirect object containing a dictionary.
// The indirect object is the container (which is tracked).
dict, ok := indObj.PdfObject.(*core.PdfObjectDictionary)
if !ok {
common.Log.Error("Function Indirect object not containing dictionary")
return nil, errors.New("invalid parameter or missing")
}
ftype, ok := dict.Get("FunctionType").(*core.PdfObjectInteger)
if !ok {
common.Log.Error("FunctionType number missing")
return nil, errors.New("invalid parameter or missing")
}
if *ftype == 2 {
return newPdfFunctionType2FromPdfObject(indObj)
} else if *ftype == 3 {
return newPdfFunctionType3FromPdfObject(indObj)
} else {
return nil, errors.New("invalid function type")
}
} else if dict, is := obj.(*core.PdfObjectDictionary); is {
ftype, ok := dict.Get("FunctionType").(*core.PdfObjectInteger)
if !ok {
common.Log.Error("FunctionType number missing")
return nil, errors.New("invalid parameter or missing")
}
if *ftype == 2 {
return newPdfFunctionType2FromPdfObject(dict)
} else if *ftype == 3 {
return newPdfFunctionType3FromPdfObject(dict)
} else {
return nil, errors.New("invalid function type")
}
} else {
common.Log.Debug("Function Type error: %#v", obj)
return nil, errors.New("type error")
}
}
// Simple linear interpolation from the PDF manual.
func interpolate(x, xmin, xmax, ymin, ymax float64) float64 {
if math.Abs(xmax-xmin) < 0.000001 {
return ymin
}
y := ymin + (x-xmin)*(ymax-ymin)/(xmax-xmin)
return y
}
// PdfFunctionType0 uses a sequence of sample values (contained in a stream) to provide an approximation
// for functions whose domains and ranges are bounded. The samples are organized as an m-dimensional
// table in which each entry has n components
type PdfFunctionType0 struct {
Domain []float64 // required; 2*m length; where m is the number of input values
Range []float64 // required (type 0); 2*n length; where n is the number of output values
NumInputs int
NumOutputs int
Size []int
BitsPerSample int
Order int // Values 1 or 3 (linear or cubic spline interpolation)
Encode []float64
Decode []float64
rawData []byte
data []uint32
container *core.PdfObjectStream
}
// Construct the PDF function object from a stream object (typically loaded from a PDF file).
func newPdfFunctionType0FromStream(stream *core.PdfObjectStream) (*PdfFunctionType0, error) {
fun := &PdfFunctionType0{}
fun.container = stream
dict := stream.PdfObjectDictionary
// Domain
array, has := core.TraceToDirectObject(dict.Get("Domain")).(*core.PdfObjectArray)
if !has {
common.Log.Error("Domain not specified")
return nil, errors.New("required attribute missing or invalid")
}
if array.Len() < 0 || array.Len()%2 != 0 {
common.Log.Error("Domain invalid")
return nil, errors.New("invalid domain range")
}
fun.NumInputs = array.Len() / 2
domain, err := array.ToFloat64Array()
if err != nil {
return nil, err
}
fun.Domain = domain
// Range
array, has = core.TraceToDirectObject(dict.Get("Range")).(*core.PdfObjectArray)
if !has {
common.Log.Error("Range not specified")
return nil, errors.New("required attribute missing or invalid")
}
if array.Len() < 0 || array.Len()%2 != 0 {
return nil, errors.New("invalid range")
}
fun.NumOutputs = array.Len() / 2
rang, err := array.ToFloat64Array()
if err != nil {
return nil, err
}
fun.Range = rang
// Number of samples in each input dimension
array, has = core.TraceToDirectObject(dict.Get("Size")).(*core.PdfObjectArray)
if !has {
common.Log.Error("Size not specified")
return nil, errors.New("required attribute missing or invalid")
}
tablesize, err := array.ToIntegerArray()
if err != nil {
return nil, err
}
if len(tablesize) != fun.NumInputs {
common.Log.Error("Table size not matching number of inputs")
return nil, errors.New("range check")
}
fun.Size = tablesize
// BitsPerSample
bps, has := core.TraceToDirectObject(dict.Get("BitsPerSample")).(*core.PdfObjectInteger)
if !has {
common.Log.Error("BitsPerSample not specified")
return nil, errors.New("required attribute missing or invalid")
}
if *bps != 1 && *bps != 2 && *bps != 4 && *bps != 8 && *bps != 12 && *bps != 16 && *bps != 24 && *bps != 32 {
common.Log.Error("Bits per sample outside range (%d)", *bps)
return nil, errors.New("range check")
}
fun.BitsPerSample = int(*bps)
fun.Order = 1
order, has := core.TraceToDirectObject(dict.Get("Order")).(*core.PdfObjectInteger)
if has {
if *order != 1 && *order != 3 {
common.Log.Error("Invalid order (%d)", *order)
return nil, errors.New("range check")
}
fun.Order = int(*order)
}
// Encode: is a 2*m array specifying the linear mapping of input values into the domain of the function's
// sample table.
array, has = core.TraceToDirectObject(dict.Get("Encode")).(*core.PdfObjectArray)
if has {
encode, err := array.ToFloat64Array()
if err != nil {
return nil, err
}
fun.Encode = encode
}
// Decode
array, has = core.TraceToDirectObject(dict.Get("Decode")).(*core.PdfObjectArray)
if has {
decode, err := array.ToFloat64Array()
if err != nil {
return nil, err
}
fun.Decode = decode
}
data, err := core.DecodeStream(stream)
if err != nil {
return nil, err
}
fun.rawData = data
return fun, nil
}
// ToPdfObject returns the PDF representation of the function.
func (f *PdfFunctionType0) ToPdfObject() core.PdfObject {
if f.container == nil {
f.container = &core.PdfObjectStream{}
}
dict := core.MakeDict()
dict.Set("FunctionType", core.MakeInteger(0))
// Domain (required).
domainArray := &core.PdfObjectArray{}
for _, val := range f.Domain {
domainArray.Append(core.MakeFloat(val))
}
dict.Set("Domain", domainArray)
// Range (required).
rangeArray := &core.PdfObjectArray{}
for _, val := range f.Range {
rangeArray.Append(core.MakeFloat(val))
}
dict.Set("Range", rangeArray)
// Size (required).
sizeArray := &core.PdfObjectArray{}
for _, val := range f.Size {
sizeArray.Append(core.MakeInteger(int64(val)))
}
dict.Set("Size", sizeArray)
dict.Set("BitsPerSample", core.MakeInteger(int64(f.BitsPerSample)))
if f.Order != 1 {
dict.Set("Order", core.MakeInteger(int64(f.Order)))
}
// TODO: Encode.
// Either here, or automatically later on when writing out.
dict.Set("Length", core.MakeInteger(int64(len(f.rawData))))
f.container.Stream = f.rawData
f.container.PdfObjectDictionary = dict
return f.container
}
// Evaluate runs the function on the passed in slice and returns the results.
func (f *PdfFunctionType0) Evaluate(x []float64) ([]float64, error) {
if len(x) != f.NumInputs {
common.Log.Error("Number of inputs not matching what is needed")
return nil, errors.New("range check error")
}
if f.data == nil {
// Process the samples if not already done.
err := f.processSamples()
if err != nil {
return nil, err
}
}
// Fall back to default Encode/Decode params if not set.
encode := f.Encode
if encode == nil {
encode = []float64{}
for i := 0; i < len(f.Size); i++ {
encode = append(encode, 0)
encode = append(encode, float64(f.Size[i]-1))
}
}
decode := f.Decode
if decode == nil {
decode = f.Range
}
var indices []int
// Start with nearest neighbour interpolation.
for i := 0; i < len(x); i++ {
xi := x[i]
// See section 7.10.2 Type 0 (Sampled) Functions (pp. 93-94 PDF32000_2008).
xip := math.Min(math.Max(xi, f.Domain[2*i]), f.Domain[2*i+1])
ei := interpolate(xip, f.Domain[2*i], f.Domain[2*i+1], encode[2*i], encode[2*i+1])
eip := math.Min(math.Max(ei, 0), float64(f.Size[i]-1))
// eip represents coordinate into the data table.
// At this point it is real values.
// Interpolation shall be used to to determine output values
// from the nearest surrounding values in the sample table.
// Initial implementation is simply nearest neighbour.
// Then will add the linear and possibly bicubic/spline.
index := int(math.Floor(eip + 0.5))
if index < 0 {
index = 0
} else if index > f.Size[i] {
index = f.Size[i] - 1
}
indices = append(indices, index)
}
// Calculate the index
m := indices[0]
for i := 1; i < f.NumInputs; i++ {
add := indices[i]
for j := 0; j < i; j++ {
add *= f.Size[j]
}
m += add
}
m *= f.NumOutputs
// Output values.
var outputs []float64
for j := 0; j < f.NumOutputs; j++ {
rj := f.data[m+j]
rjp := interpolate(float64(rj), 0, math.Pow(2, float64(f.BitsPerSample)), decode[2*j], decode[2*j+1])
yj := math.Min(math.Max(rjp, f.Range[2*j]), f.Range[2*j+1])
outputs = append(outputs, yj)
}
return outputs, nil
}
// Convert raw data to data table. The maximum supported BitsPerSample is 32, so we store the resulting data
// in a uint32 array. This is somewhat wasteful in the case of a small BitsPerSample, but these tables are
// presumably not huge at any rate.
func (f *PdfFunctionType0) processSamples() error {
data := sampling.ResampleBytes(f.rawData, f.BitsPerSample)
f.data = data
return nil
}
// PdfFunctionType2 defines an exponential interpolation of one input value and n
// output values:
// f(x) = y_0, ..., y_(n-1)
// y_j = C0_j + x^N * (C1_j - C0_j); for 0 <= j < n
// When N=1 ; linear interpolation between C0 and C1.
type PdfFunctionType2 struct {
Domain []float64
Range []float64
C0 []float64
C1 []float64
N float64
container *core.PdfIndirectObject
}
// Can be either indirect object or dictionary. If indirect, then must be holding a dictionary,
// i.e. acting as a container. When converting back to pdf object, will use the container provided.
func newPdfFunctionType2FromPdfObject(obj core.PdfObject) (*PdfFunctionType2, error) {
fun := &PdfFunctionType2{}
var dict *core.PdfObjectDictionary
if indObj, is := obj.(*core.PdfIndirectObject); is {
d, ok := indObj.PdfObject.(*core.PdfObjectDictionary)
if !ok {
return nil, errors.New("type check error")
}
fun.container = indObj
dict = d
} else if d, is := obj.(*core.PdfObjectDictionary); is {
dict = d
} else {
return nil, errors.New("type check error")
}
common.Log.Trace("FUNC2: %s", dict.String())
// Domain
array, has := core.TraceToDirectObject(dict.Get("Domain")).(*core.PdfObjectArray)
if !has {
common.Log.Error("Domain not specified")
return nil, errors.New("required attribute missing or invalid")
}
if array.Len() < 0 || array.Len()%2 != 0 {
common.Log.Error("Domain range invalid")
return nil, errors.New("invalid domain range")
}
domain, err := array.ToFloat64Array()
if err != nil {
return nil, err
}
fun.Domain = domain
// Range
array, has = core.TraceToDirectObject(dict.Get("Range")).(*core.PdfObjectArray)
if has {
if array.Len() < 0 || array.Len()%2 != 0 {
return nil, errors.New("invalid range")
}
rang, err := array.ToFloat64Array()
if err != nil {
return nil, err
}
fun.Range = rang
}
// C0.
array, has = core.TraceToDirectObject(dict.Get("C0")).(*core.PdfObjectArray)
if has {
c0, err := array.ToFloat64Array()
if err != nil {
return nil, err
}
fun.C0 = c0
}
// C1.
array, has = core.TraceToDirectObject(dict.Get("C1")).(*core.PdfObjectArray)
if has {
c1, err := array.ToFloat64Array()
if err != nil {
return nil, err
}
fun.C1 = c1
}
if len(fun.C0) != len(fun.C1) {
common.Log.Error("C0 and C1 not matching")
return nil, core.ErrRangeError
}
// Exponent.
N, err := core.GetNumberAsFloat(core.TraceToDirectObject(dict.Get("N")))
if err != nil {
common.Log.Error("N missing or invalid, dict: %s", dict.String())
return nil, err
}
fun.N = N
return fun, nil
}
// ToPdfObject returns the PDF representation of the function.
func (f *PdfFunctionType2) ToPdfObject() core.PdfObject {
dict := core.MakeDict()
dict.Set("FunctionType", core.MakeInteger(2))
// Domain (required).
domainArray := &core.PdfObjectArray{}
for _, val := range f.Domain {
domainArray.Append(core.MakeFloat(val))
}
dict.Set("Domain", domainArray)
// Range (required).
if f.Range != nil {
rangeArray := &core.PdfObjectArray{}
for _, val := range f.Range {
rangeArray.Append(core.MakeFloat(val))
}
dict.Set("Range", rangeArray)
}
// C0.
if f.C0 != nil {
c0Array := &core.PdfObjectArray{}
for _, val := range f.C0 {
c0Array.Append(core.MakeFloat(val))
}
dict.Set("C0", c0Array)
}
// C1.
if f.C1 != nil {
c1Array := &core.PdfObjectArray{}
for _, val := range f.C1 {
c1Array.Append(core.MakeFloat(val))
}
dict.Set("C1", c1Array)
}
// exponent
dict.Set("N", core.MakeFloat(f.N))
// Wrap in a container if we have one already specified.
if f.container != nil {
f.container.PdfObject = dict
return f.container
}
return dict
}
// Evaluate runs the function on the passed in slice and returns the results.
func (f *PdfFunctionType2) Evaluate(x []float64) ([]float64, error) {
if len(x) != 1 {
common.Log.Error("Only one input allowed")
return nil, errors.New("range check")
}
// Prepare.
c0 := []float64{0.0}
if f.C0 != nil {
c0 = f.C0
}
c1 := []float64{1.0}
if f.C1 != nil {
c1 = f.C1
}
var y []float64
for i := 0; i < len(c0); i++ {
yi := c0[i] + math.Pow(x[0], f.N)*(c1[i]-c0[i])
y = append(y, yi)
}
return y, nil
}
// PdfFunctionType3 defines stitching of the subdomains of several 1-input functions to produce
// a single new 1-input function.
type PdfFunctionType3 struct {
Domain []float64
Range []float64
Functions []PdfFunction // k-1 input functions
Bounds []float64 // k-1 numbers; defines the intervals where each function applies
Encode []float64 // Array of 2k numbers..
container *core.PdfIndirectObject
}
// Evaluate runs the function on the passed in slice and returns the results.
func (f *PdfFunctionType3) Evaluate(x []float64) ([]float64, error) {
if len(x) != 1 {
common.Log.Error("Only one input allowed")
return nil, errors.New("range check")
}
// Determine which function to use
// Encode
return nil, errors.New("not implemented yet")
}
func newPdfFunctionType3FromPdfObject(obj core.PdfObject) (*PdfFunctionType3, error) {
fun := &PdfFunctionType3{}
var dict *core.PdfObjectDictionary
if indObj, is := obj.(*core.PdfIndirectObject); is {
d, ok := indObj.PdfObject.(*core.PdfObjectDictionary)
if !ok {
return nil, errors.New("type check error")
}
fun.container = indObj
dict = d
} else if d, is := obj.(*core.PdfObjectDictionary); is {
dict = d
} else {
return nil, errors.New("type check error")
}
// Domain
array, has := core.TraceToDirectObject(dict.Get("Domain")).(*core.PdfObjectArray)
if !has {
common.Log.Error("Domain not specified")
return nil, errors.New("required attribute missing or invalid")
}
if array.Len() != 2 {
common.Log.Error("Domain invalid")
return nil, errors.New("invalid domain range")
}
domain, err := array.ToFloat64Array()
if err != nil {
return nil, err
}
fun.Domain = domain
// Range
array, has = core.TraceToDirectObject(dict.Get("Range")).(*core.PdfObjectArray)
if has {
if array.Len() < 0 || array.Len()%2 != 0 {
return nil, errors.New("invalid range")
}
rang, err := array.ToFloat64Array()
if err != nil {
return nil, err
}
fun.Range = rang
}
// Functions.
array, has = core.TraceToDirectObject(dict.Get("Functions")).(*core.PdfObjectArray)
if !has {
common.Log.Error("Functions not specified")
return nil, errors.New("required attribute missing or invalid")
}
fun.Functions = []PdfFunction{}
for _, obj := range array.Elements() {
subf, err := newPdfFunctionFromPdfObject(obj)
if err != nil {
return nil, err
}
fun.Functions = append(fun.Functions, subf)
}
// Bounds
array, has = core.TraceToDirectObject(dict.Get("Bounds")).(*core.PdfObjectArray)
if !has {
common.Log.Error("Bounds not specified")
return nil, errors.New("required attribute missing or invalid")
}
bounds, err := array.ToFloat64Array()
if err != nil {
return nil, err
}
fun.Bounds = bounds
if len(fun.Bounds) != len(fun.Functions)-1 {
common.Log.Error("Bounds (%d) and num functions (%d) not matching", len(fun.Bounds), len(fun.Functions))
return nil, errors.New("range check")
}
// Encode.
array, has = core.TraceToDirectObject(dict.Get("Encode")).(*core.PdfObjectArray)
if !has {
common.Log.Error("Encode not specified")
return nil, errors.New("required attribute missing or invalid")
}
encode, err := array.ToFloat64Array()
if err != nil {
return nil, err
}
fun.Encode = encode
if len(fun.Encode) != 2*len(fun.Functions) {
common.Log.Error("Len encode (%d) and num functions (%d) not matching up", len(fun.Encode), len(fun.Functions))
return nil, errors.New("range check")
}
return fun, nil
}
// ToPdfObject returns the PDF representation of the function.
func (f *PdfFunctionType3) ToPdfObject() core.PdfObject {
dict := core.MakeDict()
dict.Set("FunctionType", core.MakeInteger(3))
// Domain (required).
domainArray := &core.PdfObjectArray{}
for _, val := range f.Domain {
domainArray.Append(core.MakeFloat(val))
}
dict.Set("Domain", domainArray)
// Range (required).
if f.Range != nil {
rangeArray := &core.PdfObjectArray{}
for _, val := range f.Range {
rangeArray.Append(core.MakeFloat(val))
}
dict.Set("Range", rangeArray)
}
// Functions
if f.Functions != nil {
fArray := &core.PdfObjectArray{}
for _, fun := range f.Functions {
fArray.Append(fun.ToPdfObject())
}
dict.Set("Functions", fArray)
}
// Bounds.
if f.Bounds != nil {
bArray := &core.PdfObjectArray{}
for _, val := range f.Bounds {
bArray.Append(core.MakeFloat(val))
}
dict.Set("Bounds", bArray)
}
// Encode.
if f.Encode != nil {
eArray := &core.PdfObjectArray{}
for _, val := range f.Encode {
eArray.Append(core.MakeFloat(val))
}
dict.Set("Encode", eArray)
}
// Wrap in a container if we have one already specified.
if f.container != nil {
f.container.PdfObject = dict
return f.container
}
return dict
}
// PdfFunctionType4 is a Postscript calculator functions.
type PdfFunctionType4 struct {
Domain []float64
Range []float64
Program *ps.PSProgram
executor *ps.PSExecutor
decodedData []byte
container *core.PdfObjectStream
}
// Evaluate runs the function. Input is [x1 x2 x3].
func (f *PdfFunctionType4) Evaluate(xVec []float64) ([]float64, error) {
if f.executor == nil {
f.executor = ps.NewPSExecutor(f.Program)
}
var inputs []ps.PSObject
for _, val := range xVec {
inputs = append(inputs, ps.MakeReal(val))
}
outputs, err := f.executor.Execute(inputs)
if err != nil {
return nil, err
}
// After execution the outputs are on the stack [y1 ... yM]
// Convert to floats.
yVec, err := ps.PSObjectArrayToFloat64Array(outputs)
if err != nil {
return nil, err
}
return yVec, nil
}
// Load a type 4 function from a PDF stream object.
func newPdfFunctionType4FromStream(stream *core.PdfObjectStream) (*PdfFunctionType4, error) {
fun := &PdfFunctionType4{}
fun.container = stream
dict := stream.PdfObjectDictionary
// Domain
array, has := core.TraceToDirectObject(dict.Get("Domain")).(*core.PdfObjectArray)
if !has {
common.Log.Error("Domain not specified")
return nil, errors.New("required attribute missing or invalid")
}
if array.Len()%2 != 0 {
common.Log.Error("Domain invalid")
return nil, errors.New("invalid domain range")
}
domain, err := array.ToFloat64Array()
if err != nil {
return nil, err
}
fun.Domain = domain
// Range
array, has = core.TraceToDirectObject(dict.Get("Range")).(*core.PdfObjectArray)
if has {
if array.Len() < 0 || array.Len()%2 != 0 {
return nil, errors.New("invalid range")
}
rang, err := array.ToFloat64Array()
if err != nil {
return nil, err
}
fun.Range = rang
}
// Program. Decode the program and parse the PS code.
decoded, err := core.DecodeStream(stream)
if err != nil {
return nil, err
}
fun.decodedData = decoded
psParser := ps.NewPSParser([]byte(decoded))
prog, err := psParser.Parse()
if err != nil {
return nil, err
}
fun.Program = prog
return fun, nil
}
// ToPdfObject returns the PDF representation of the function.
func (f *PdfFunctionType4) ToPdfObject() core.PdfObject {
container := f.container
if container == nil {
f.container = &core.PdfObjectStream{}
container = f.container
}
dict := core.MakeDict()
dict.Set("FunctionType", core.MakeInteger(4))
// Domain (required).
domainArray := &core.PdfObjectArray{}
for _, val := range f.Domain {
domainArray.Append(core.MakeFloat(val))
}
dict.Set("Domain", domainArray)
// Range (required).
rangeArray := &core.PdfObjectArray{}
for _, val := range f.Range {
rangeArray.Append(core.MakeFloat(val))
}
dict.Set("Range", rangeArray)
if f.decodedData == nil && f.Program != nil {
// Update data. This is used for created functions (not parsed ones).
f.decodedData = []byte(f.Program.String())
}
// TODO: Encode.
// Either here, or automatically later on when writing out.
dict.Set("Length", core.MakeInteger(int64(len(f.decodedData))))
container.Stream = f.decodedData
container.PdfObjectDictionary = dict
return container
}