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
/*
 * Copyright (c) 2018-2021 Thomas Kramer.
 *
 * This file is part of LibrEDA 
 * (see https://codeberg.org/libreda/libreda-oasis).
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */
//! Write `Layout` data structures into the OASIS file format.

use crate::Modal;
use libreda_db::layout::prelude::*;

use crate::base_types::*;

use std::io::Write;
use std::ptr;

/// Type of integrity checksum used while writing the OASIS stream.
#[derive(Copy, Clone, Debug)]
pub enum OASISValidationScheme {
    None,
    // CHECKSUM32, // Not supported yet.
    // CRC32 // Not supported yet.
}

impl Default for OASISValidationScheme {
    fn default() -> Self {
        OASISValidationScheme::None
    }
}

/// Configuration for the output stream format.
#[derive(Clone, Debug, Default)]
pub struct OASISWriterConfig {
    /// Put offset table at start or at end?
    /// TODO: Table offset at start is not supported yet.
    table_offsets_at_start: bool,

    /// Tells if IDs are given implicitly by a counter or are explicitly written in the file.
    explicit_ids: bool,

    /// Type of integrity checksum used while writing the OASIS stream. Default is `None` (0).
    validation_scheme: OASISValidationScheme,
}

#[derive(Copy, Clone, Debug, Default)]
struct Offset {
    flag: UInt,
    offset: UInt,
}

#[derive(Clone, Debug, Default)]
struct OffsetTable {
    cellname: Offset,
    textstring: Offset,
    propname: Offset,
    propstring: Offset,
    layername: Offset,
    xname: Offset,
}

/// TODO
fn write_offset_table<W: Write>(writer: &mut W, t: &OffsetTable) -> Result<(), OASISWriteError> {
    for o in &[t.cellname, t.textstring, t.propname, t.propstring, t.layername, t.xname] {
        write_unsigned_integer(writer, o.flag)?;
        write_unsigned_integer(writer, o.offset)?;
    }

    Ok(())
}

/// Return a integer with the bit at position `index` set depending on the `value`.
fn bit(index: UInt, value: bool) -> UInt {
    (value as UInt) << index
}

/// Serialize the `layout` to the `writer` in the OASIS format.
/// The `conf` structure is used for controlling the output format.
pub fn write_layout<W: Write>(writer: &mut W, layout: &Layout, conf: &OASISWriterConfig) -> Result<(), OASISWriteError> {

    // Modal variables.
    let mut modal = Modal::default();

    write_magic(writer)?;
    // Write START record.
    write_unsigned_integer(writer, 1)?;
    // Write version string.
    write_ascii_string(writer, "1.0".as_bytes())?;

    // Write resolution.
    if layout.dbu == 0 {
        return Err(OASISWriteError::DbuIsZero);
    }
    let resolution = Real::PositiveWholeNumber(layout.dbu);
    write_real(writer, resolution)?;

    // Put offset table at start or at end?
    let offset_flag = if conf.table_offsets_at_start { 0 } else { 1 };
    write_unsigned_integer(writer, offset_flag)?;
    if conf.table_offsets_at_start {
        // table-offsets is stored in START record.
        write_offset_table(writer, &OffsetTable::default())?; // TODO: Construct proper offset table.
    }

    // Define counters for implicit IDs.
    // TODO: Writing implicit IDs is not supported yet.
    let mut _cellname_id_counter = (0..).into_iter();
    let mut _textstrings_id_counter = (0..).into_iter();
    let mut _propname_id_counter = (0..).into_iter();
    let mut _propstrings_id_counter = (0..).into_iter();

    // Loop through all cells.
    for cell in layout.each_cell() {
        debug!("write cell '{:?}'", cell.name());

        // Write CELL record (identified by name).
        // TODO: Support CELL record 13 by ID.
        write_unsigned_integer(writer, 14)?;
        write_name_string(writer, cell.name()
            .expect("Cell has no name!")
            .as_bytes())?;

        modal.reset();

        // Write all shapes inside this cell.
        for l in cell.each_used_layer() {
            debug!("write shapes on layer '{:?}'", l);
            let layer_info = layout.get_layer_info(l).unwrap();
            let layer_index = layer_info.index;
            let layer_datatype = layer_info.datatype;
            for shape in cell.each_shape(l) {
                match &shape.geometry {
                    Geometry::Rect(r) => {
                        write_unsigned_integer(writer, 20)?;

                        // write_rectangle(r, layer_info.index, layer_info.datatype)?;
                        let width = r.width() as UInt;
                        let height = r.height() as UInt;
                        let (x, y) = r.lower_left.into();

                        let is_square = width == height;
                        let write_layer_number = modal.layer != Some(layer_index);
                        let write_datatype = modal.datatype != Some(layer_datatype);
                        let write_width = modal.geometry_w != Some(width);
                        let write_height = !is_square && modal.geometry_h != Some(height);
                        let write_x = modal.geometry_x != x;
                        let write_y = modal.geometry_y != y;
                        let write_repetition = false; // TODO: Detect repetitions. This would lead to more compressed outputs!
                        let rectangle_info_byte =
                            bit(7, is_square)
                                | bit(6, write_width)
                                | bit(5, write_height)
                                | bit(4, write_x)
                                | bit(3, write_y)
                                | bit(2, write_repetition)
                                | bit(1, write_datatype)
                                | bit(0, write_layer_number);
                        write_byte(writer, rectangle_info_byte as u8)?;

                        if write_layer_number { write_unsigned_integer(writer, layer_index)? };
                        if write_datatype { write_unsigned_integer(writer, layer_datatype)? };
                        if write_width { write_unsigned_integer(writer, width)? };
                        if write_height { write_unsigned_integer(writer, height)? };
                        if write_x { write_signed_integer(writer, x)? };
                        if write_y { write_signed_integer(writer, y)? };
                        if write_repetition { unimplemented!(); };

                        modal.geometry_w = Some(width);
                        modal.geometry_h = Some(height);
                        modal.geometry_x = x;
                        modal.geometry_y = y;

                        modal.datatype = Some(layer_datatype);
                        modal.layer = Some(layer_index);
                    }
                    Geometry::SimplePolygon(p) => {
                        write_unsigned_integer(writer, 21)?;

                        if p.len() > 1 {
                            let offset = p.points.first().unwrap(); // There must be a point, because this is checked in the condition above.
                            let point_list = PointList::from_points_explicit(&p.points);

                            let (x, y) = offset.into();

                            // TODO: This part is the same as for 'rectangle': Merge it?
                            let write_layer_number = modal.layer != Some(layer_index);
                            let write_datatype = modal.layer != Some(layer_datatype);
                            let write_x = modal.geometry_x != x;
                            let write_y = modal.geometry_y != y;
                            let write_repetition = false; // TODO: Detect repetitions. This would lead to more compressed outputs!

                            let is_pointlist_present = Some(&point_list) != modal.polygon_point_list.as_ref();

                            let polygon_info_byte =
                                bit(5, is_pointlist_present)
                                    | bit(4, write_x)
                                    | bit(3, write_y)
                                    | bit(2, write_repetition)
                                    | bit(1, write_datatype)
                                    | bit(0, write_layer_number);
                            write_byte(writer, polygon_info_byte as u8)?;
                            if write_layer_number { write_unsigned_integer(writer, layer_index)? };
                            if write_datatype { write_unsigned_integer(writer, layer_datatype)? };
                            if is_pointlist_present { write_pointlist(writer, &point_list)? };
                            if write_x { write_signed_integer(writer, x)? };
                            if write_y { write_signed_integer(writer, y)? };
                            if write_repetition {
                                modal.repetition = None;
                                unimplemented!();
                            };

                            // Remember last written point list.
                            modal.polygon_point_list = Some(point_list);

                            modal.geometry_x = x;
                            modal.geometry_y = y;

                            modal.datatype = Some(layer_datatype);
                            modal.layer = Some(layer_index);
                        } else {
                            // Empty polygon: Skip it.
                        }
                    }
                    Geometry::Path(p) => {
                        write_unsigned_integer(writer, 22)?; // PATH record.

                        if p.len() > 0 {
                            let offset = p.points.points.first().unwrap(); // There must be a point, because this is checked in the condition above.
                            let point_list = PointList::from_points_explicit(&p.points.points);

                            let (x, y) = offset.into();
                            let half_width = (p.width as UInt) / 2; // FXIME: Width is rounded down to next even number.

                            let (start_ext, end_ext) = match p.path_type {
                                PathEndType::Flat => (0, 0),
                                PathEndType::Extended(s, e) => (s, e),
                                PathEndType::Round => unimplemented!("Round path endings are not supported yet.") // TODO: Convert paths with round ends into polygons.
                            };

                            // TODO: This part is the same as for 'rectangle': Merge it?
                            let write_layer_number = modal.layer != Some(layer_index);
                            let write_datatype = modal.layer != Some(layer_datatype);
                            let write_x = modal.geometry_x != x;
                            let write_y = modal.geometry_y != y;
                            let write_repetition = false; // TODO: Detect repetitions. This would lead to more compressed outputs!

                            let write_point_list = Some(&point_list) != modal.path_point_list.as_ref();
                            let write_half_width_present = modal.path_halfwidth != Some(half_width);
                            let write_extension_scheme_present = modal.path_start_extension != Some(start_ext)
                                || modal.path_end_extension != Some(end_ext);

                            let path_info_byte =
                                bit(7, write_extension_scheme_present)
                                    | bit(6, write_half_width_present)
                                    | bit(5, write_point_list)
                                    | bit(4, write_x)
                                    | bit(3, write_y)
                                    | bit(2, write_repetition)
                                    | bit(1, write_datatype)
                                    | bit(0, write_layer_number);
                            write_byte(writer, path_info_byte as u8)?;

                            if write_layer_number { write_unsigned_integer(writer, layer_index)? };
                            if write_datatype { write_unsigned_integer(writer, layer_datatype)? };
                            if write_half_width_present { write_unsigned_integer(writer, half_width)? };
                            if write_extension_scheme_present {
                                let ss = match start_ext {
                                    0 => 0b01, // Zero-length extension.
                                    x if x == half_width as SInt => 0b10, // Half-width extension.
                                    x if Some(x) == modal.path_start_extension => 0b00, // Use modal variable.
                                    _ => 0b11 // Explicit encoding.
                                };
                                let ee = match end_ext {
                                    0 => 0b01, // Zero-length extension.
                                    x if x == half_width as SInt => 0b10, // Half-width extension.
                                    x if Some(x) == modal.path_end_extension => 0b00, // Use modal variable.
                                    _ => 0b11 // Explicit encoding.
                                };

                                let extension_scheme = (ss << 2) | ee;

                                // Write extension-scheme.
                                write_byte(writer, extension_scheme)?;

                                if ss == 0b11 {
                                    // Explicit start extension.
                                    write_signed_integer(writer, start_ext)?;
                                }

                                if ee == 0b11 {
                                    // Explicit end extension.
                                    write_signed_integer(writer, end_ext)?;
                                }
                            };
                            if write_point_list { write_pointlist(writer, &point_list)? };
                            if write_x { write_signed_integer(writer, x)? };
                            if write_y { write_signed_integer(writer, y)? };
                            if write_repetition {
                                modal.repetition = None;
                                unimplemented!();
                            };

                            // Remember last written point list.
                            modal.path_point_list = Some(point_list);
                            modal.path_halfwidth = Some(half_width);
                            modal.path_start_extension = Some(start_ext);
                            modal.path_end_extension = Some(end_ext);

                            modal.geometry_x = x;
                            modal.geometry_y = y;

                            modal.datatype = Some(layer_datatype);
                            modal.layer = Some(layer_index);
                        } else {
                            // Empty path, don't write anything.
                        }
                    }
                    Geometry::Text(text) => {
                        debug!("TEXT record");
                        write_unsigned_integer(writer, 19)?; // Text record.

                        let text_string = text.text();
                        let x = text.x();
                        let y = text.y();

                        // Construct text-info byte.
                        // No need to write the text if the modal variable currently contains it.
                        let write_text_reference = modal.text_string.as_ref() != Some(text_string);
                        // Write a reference number instead of a text string?
                        // TODO: Create a lookup-table for strings on-the-fly.
                        let write_reference_number = false;

                        let write_textlayer = modal.textlayer != Some(layer_index);
                        let write_texttype = modal.texttype != Some(layer_datatype);
                        let write_x = modal.text_x != x;
                        let write_y = modal.text_y != y;

                        let write_repetition = false; // TODO: Detect repetitions. This would lead to more compressed outputs!

                        let text_info_byte =
                            bit(6, write_text_reference)
                                | bit(5, write_reference_number)
                                | bit(4, write_x)
                                | bit(3, write_y)
                                | bit(2, write_repetition)
                                | bit(1, write_texttype)
                                | bit(0, write_textlayer);
                        write_byte(writer, text_info_byte as u8)?;

                        if write_text_reference {
                            if write_reference_number {
                                // Text must be present in a TEXT STRING record.
                                unimplemented!()
                            } else {
                                // Write text explicitly.
                                write_ascii_string(writer, text_string.as_bytes())?
                            }
                        }

                        if write_textlayer { write_unsigned_integer(writer, layer_index)? };
                        if write_texttype { write_unsigned_integer(writer, layer_datatype)? };
                        if write_x { write_signed_integer(writer, x)? };
                        if write_y { write_signed_integer(writer, y)? };
                        if write_repetition {
                            modal.repetition = None;
                            unimplemented!();
                        };

                        // Update modal variables.
                        modal.text_x = x;
                        modal.text_y = y;
                        modal.texttype = Some(layer_datatype);
                        modal.textlayer = Some(layer_index);
                        if write_text_reference {
                            modal.text_string = Some(text_string.clone());
                        }
                    }
                    _ => unimplemented!()
                }
            }
        }

        // Loop through all instances.
        for inst in cell.each_inst() {
            // Write PLACEMENT records.
            let placement_cell = inst.cell().upgrade().unwrap();

            let tf = inst.get_transform();

            if tf.magnification == 1 {
                write_unsigned_integer(writer, 17)?; // PLACEMENT record (with simple representation of rotation and magnification).

                let (x, y) = tf.displacement.into();

                // Prepare encoding of the angle in the AA bits of the placement info byte.
                let aa = match tf.rotation {
                    Angle::R0 => 0,
                    Angle::R90 => 1,
                    Angle::R180 => 2,
                    Angle::R270 => 3,
                };

                let is_explicit_reference =  // C
                    // Use an implicit reference if the current placement cell is the same as the last.
                    modal.placement_cell.as_ref()
                        .map(|c| !ptr::eq(c.as_ref(), placement_cell.as_ref()))
                        .unwrap_or(true);
                // For now, always use references by cell name.
                let is_cell_ref_present = false; // N

                let is_flip = tf.mirror; // F

                let write_x = modal.placement_x != x; // X
                let write_y = modal.placement_y != y; // Y
                let write_repetition = false; // R

                let placement_info_byte = bit(0, is_flip)
                    | (aa << 1)
                    | bit(3, write_repetition)
                    | bit(4, write_y)
                    | bit(5, write_x)
                    | bit(6, is_cell_ref_present)
                    | bit(7, is_explicit_reference);

                write_byte(writer, placement_info_byte as u8)?;

                if is_explicit_reference {
                    if is_cell_ref_present {
                        // Write placement cell reference number.
                        unimplemented!();
                    } else {
                        // Write placement cell name.
                        // TODO: Return error instead of expect or generate cell name!
                        write_name_string(writer, placement_cell.name()
                            .expect("Cell has no name!").as_bytes())?;
                    }
                }

                if write_x { write_signed_integer(writer, x)? };
                if write_y { write_signed_integer(writer, y)? };
                if write_repetition {
                    modal.repetition = None;
                    unimplemented!();
                };

                modal.placement_cell = Some(placement_cell);
                modal.placement_x = x;
                modal.placement_y = y;
            } else {
                unimplemented!("Magnifications other than 1 are not supported yet.");
            }
        }
    }

    // Write END record.
    let mut end_record_buf = Vec::new();
    write_unsigned_integer(&mut end_record_buf, 2)?; // END record.

    if !conf.table_offsets_at_start {
        // TODO: Write meaningful offset table instead of dummy.
        write_offset_table(&mut end_record_buf, &OffsetTable::default())?;
    }


    // Write padding string: Sized such that the total byte length of the END record is exactly 256 bytes.
    // (Including record ID)
    // Validation scheme: -1
    // Validation signature: -1/-4
    // Length field of padding string: 2
    let padding_length = 256 - end_record_buf.len() - 1 - 1 - 2;
    writer.write(end_record_buf.as_slice())?;
    write_byte_string(writer, vec![0u8; padding_length].as_slice())?;

    // Write validation scheme.
    // TODO: Support CRC32, CHECKSUM32.
    let validation_scheme = match conf.validation_scheme {
        OASISValidationScheme::None => 0,
    };
    write_unsigned_integer(writer, validation_scheme)?;

    // Write validation signature.
    match conf.validation_scheme {
        OASISValidationScheme::None => {
            write_unsigned_integer(writer, 0)?;
        }
    };

    // Finalize output.
    writer.flush()?;

    Ok(())
}