# PSD document format

This document describes structure of the Psd object used in `readPsd` and `writePsd` functions, you can see instructions on how to use these functions in our [main README document](/README.md#functions)

You can see examples of different PSD documents and their corresponding JSON data in our [test folder](/test/read). Each subfolder contains `src.psd` document and corresponding `data.json` file with object generated by our library. Additionally there is `canvas.png` file representing composite image data, `thumb.png` file representing thumbnail image data and `layer-#.png` files with image data of each layer.

## Basic document structure

```ts
// example psd document structure
const psd: Psd = {
  "width": 300,
  "height": 200,
  "channels": 3,
  "bitsPerChannel": 8,
  "colorMode": 3,
  "canvas": <Canvas>,
  "children": [],
};
```

- The `width` and `height` properties specify PSD document size in pixels. These values are required when writing a document.

  ![](/files/width-height.png)

- `channels` property specifies number of color channels in the document, it's usually 3 channels (red, green, and blue, when document is in typical RGB color mode) Other color modes will have different channel count (grayscale - 1 channel, CMYK - 4 channels). This property can be omitted and is ignored when writing, this library only writes RGB color mode (3 channels, or 4 channels if composite image has transparency).

- `bitsPerChannel` property specifies number of bits per each color channel, this value will be 1 for one bit bitmap color mode and 8, 16 or 32 in other cases (see [Bitmaps and image data](#bitmaps-and-image-data)). Documents are written with the same bit depth, 16 and 32 bits are supported for "RGB" and "Grayscale" color modes and 16 bits for "CMYK" color mode. It can be omitted when writing a document and default value of 8 will be assumed (1 for "Bitmap" color mode).

- `colorMode` specifies color mode of the PSD document.

  ![](/files/color-mode.png)

  Value is one of the numbers that can be matched to this enumerable:

  ```ts
  enum ColorMode {
    Bitmap = 0,
    Grayscale = 1,
    Indexed = 2,
    RGB = 3,
    CMYK = 4,
    Multichannel = 7,
    Duotone = 8,
    Lab = 9,
  }
  ```
  The library supports reading "Bitmap", "Grayscale", "Indexed", "RGB" and "CMYK" color modes at the moment. Image data of "Bitmap", "Grayscale", "Indexed" and "CMYK" documents will be converted to RGB when reading PSD file (the `colorMode` field keeps the original value). CMYK image data is converted using approximation of U.S. Web Coated (SWOP) v2 profile (Photoshop's default CMYK profile), embedded color profile (`imageResources.iccProfile`) is not used, so colors of documents using other profiles can differ slightly from Photoshop. 32 bit CMYK documents are not supported. Documents are written in the same color mode ("Bitmap", "Grayscale", "Indexed", "RGB" and "CMYK" color modes are supported for writing, "RGB" is used if the value is omitted), image data is converted from RGB to the color mode of the document (CMYK colors are converted using inverse of the approximation used for reading, "Indexed" color mode uses the closest color from the `palette`). "Bitmap" and "Indexed" documents can't have layers (Photoshop doesn't support them in these color modes), only composite image is written.

- `palette` list of 256 RGB colors used by "Indexed" color mode, this property is only present when reading documents in "Indexed" color mode. It can be omitted when writing.

- `canvas` (or `imageData`) is a property containing bitmap with composite image data for the entire document. PSD file contains this extra bitmap additionally to bitmaps of each layer. `canvas` field will be an instance of `HTMLCanvasElement` (in browser environment) or `Canvas` object of `node-canvas` library (in nodejs environment).

  You can choose to instead use `imageData` field by choosing `useImageData: true` option when reading PSD file. In that case `imageData` will be a `PixelData` object, containing `width`, `height` and `data` properties (`data` is a byte array for 8 bit documents, see [Bitmaps and image data](#bitmaps-and-image-data) for 16 and 32 bit documents). `ImageData` object can also be used in place of `PixelData`. This is useful if you want to use bitmap data directly, and not use it for drawing using canvas. Additionally this will preserve accurate color information as canvas element will premultiply image alpha which will change color values slightly.
  
  If you don't need to use this field you can specify `skipCompositeImageData: true` option, while reading PSD file, to skip reading this field and save on processing time and memory usage.
  
  This image data is optional in PSD file so it may be missing in some PSD files that opted to skip it.
  
  When writing you can provide either `canvas` or `imageData` property and the library will use the one you provide. You can also skip the field entirely and not write this data at all as it's not needed by Photoshop to read the file. It might be used in some other application, for thumbnails or by some old versions of Adobe software, so you may want to still provide it to remain compatible with those programs.
  
  If you're generating your own PSD file and want to provide this composite image data you will have to generate one yourself by composing all layer image data and effects yourself, this library does not provide any utilities to generate this image data for you.

- `rawCompositeData` and `rawCompositeDataInfo` are used instead of `canvas` / `imageData` when `useRawData: true` option is passed to `readPsd` function. They contain undecoded composite image data that can be decoded later using `getCompositeImageData` or `getCompositeCanvas` functions (see [main README document](/README.md#functions)). Similarly layers will have `rawData` field (containing both layer and mask channels) instead of decoded image data, which can be decoded using `getLayerImageData`, `getLayerMaskImageData` and other helper functions. When writing, layer `rawData` is used instead of `canvas` / `imageData`. It's written back unchanged if it matches the format of the written file (the same color mode, bit depth and PSD/PSB format), otherwise it's decoded and re-encoded. `rawCompositeData` is ignored when writing.

- `children` list of layers and groups at the root of the document. [see Layers and Groups](#layers-and-groups)

- `imageResources` contains all document-wide parameters [see Image Resources](#image-resources)

- `linkedFiles` contains list of files linked in smart objects [see Smart Objects](#smart-objects)

- `artboards` contains global options for artboards. Artboards is a feature in new versions of Photoshop that lets you have multiple canvases in a single PSD document. The information about positioning, name and color of each artboard is stored inside each layer, in `artboard` property. This property will be absent if the document does not have any artboards specified. It can be omitted when writing.

  ```ts
  type Artboards = {
    count: number; // number of artboards in the document
    autoExpandOffset?: { horizontal: number; vertical: number; };
    origin?: { horizontal: number; vertical: number; };
    autoExpandEnabled?: boolean;
    autoNestEnabled?: boolean;
    autoPositionEnabled?: boolean;
    shrinkwrapOnSaveEnabled?: boolean;
    docDefaultNewArtboardBackgroundColor?: Color;
    docDefaultNewArtboardBackgroundType?: number;
  }
  ```

- `annotations` contains array of annotations, this field will be absent if the document does not have any annotations. It can be omitted when writing. Sound annotations are not decoded, their data is kept as raw `Uint8Array` buffer and written back unchanged.

  ![](/files/annotations.png)

  Each annotation object has a following structure:

  ```ts
  interface Annotation {
    type: 'text' | 'sound';
    open: boolean;
    iconLocation: { left: number; top: number; right: number; bottom: number };
    popupLocation: { left: number; top: number; right: number; bottom: number };
    color: Color;
    author: string;
    name: string;
    date: string;
    data: string | Uint8Array; // annotation text or sound buffer
  }
  ```

- `globalLayerMaskInfo` don't really know what this is, it can be omitted when writing.

- `patterns` Document-level pattern resources (`Patt`/`Pat2`/`Pat3` blocks). Each entry is a `PatternInfo` object:

  ```ts
  interface PatternInfo {
    name: string;
    id: string;
    x: number;
    y: number;
    bounds: { x: number; y: number; w: number, h: number; };
    data: Uint8Array; // RGBA pixel data
  }
  ```

  Reading supports raw and RLE compressed 8, 16 and 32 bit patterns in RGB, Grayscale, Indexed and CMYK color modes, all of them are converted to 8 bit RGBA pixel data. Zip-compressed patterns and patterns in other color modes are not supported (they are skipped). Patterns are always written in RGB color mode. Layer-effect pattern references (Pattern Overlay, stroke/vector fill) only carry a `name`/`id` and are not linked to these resources.

## Bitmaps and image data

Image data can be accessed from `psd.canvas` or `layer.canvas` fields by default. These fields store regular HTMLCanvasElement (or node-canvas object when running in node.js). For 16bit and 32 bit documents image data will be converted to regular 8bit canvas (this will result in a loss of data, use `useImageData` option if you want to preserve precision of color data).

If `useImageData` option is set to true in read options then the image data will be available in `psd.imageData` and `layer.imageData` fields instead. Using image data option gives you direct access to pixel data without having to go through the canvas object, which bypasses alpha premultiplication and conversion from 16/32bit image data to 8bit canvas data.

When writing, image data can be provided as canvas or `PixelData` with 8 bit (`Uint8Array` or `Uint8ClampedArray`), 16 bit (`Uint16Array`) or 32 bit (`Float32Array`) values regardless of the bit depth of the document, it's converted to the bit depth of the document. 16 and 32 bit layers are stored in `Lr16` / `Lr32` sections and compressed using zip compression with prediction (like Photoshop does).

For 16bit documents `imageData` fields will contain pixel data as `Uint16Array`, the values ranging from 0 to 65535.

For 32bit documents `imageData` fields will contain pixel data as `Float32Array`, the values ranging from 0 to 1. 32bit values are in linear color space (as opposed to gamma corrected sRGB color). In order to convert the values to regular sRGB color space the values need to be gamma-corrected by using following conversion code (except alpha channel):

```js
// convert 32bit linear to 8bit sRGB
destination[i] = Math.round(Math.pow(source[i], 1.0 / 2.2) * 255);

// convert 8bit sRGB to 32bit linear
destination[i] = Math.pow(source[i] / 255, 2.2);
```

## Layers and Groups

Psd document object has `children` property that contains all root level layers and groups in order from top to bottom as they appear in Photoshop (take note that if you want to draw the layer images to generate document image then you need to draw them in reverse order). The `children` property will contain both regular layers and groups. Each group will have `children` property, containing all the layers and groups that are inside that group. So the document will have a tree structure like this:

```js
var psd = {
  // ... other fields
  children: [
    {
      name: "layer 1",
      // ... other fields
    },
    {
      name: "group 1",
      // ... other fields
      children: [
        {
          name: "layer 2, inside group 1",
          // ... other fields
        },
        {
          name: "group 2, inside group 1",
          // ... other fields
          children: []
        }
      ]
    }
  ]
}
```

### Layer types

You can distinguish between different layer types by checking which properties they have set on them. If a layer has `children` property set it means that it's a group, if it has `text` property it's a text layer and so on. If you're only interested in the basic parsing of layers and want to just extract image data or layer parameter a simple parsing like this can be enough:

```js
// simple parsing
function parseLayer(layer) {
  if ('children' in layer) {
    // group
    layer.children.forEach(parseLayer);
  } else if (layer.canvas) {
    // regular layer with canvas
  } else {
    // empty or special layer
  }
}
```

If you need to know type of each layer, something like this could be a good approach:

```ts
// complex parsing
function parseLayer(layer) {
  if ('children' in layer) {
    // group
    layer.children.forEach(parseLayer);
  } else if ('text' in layer) {
    // text layer
  } else if ('adjustment' in layer) {
    // adjustment layer
  } else if ('placedLayer' in layer) {
    // smart object layer
  } else if ('vectorMask' in layer) {
    // vector layer
  } else {
    // bitmap layer
  }
}
```

But take into account that a lot of properties are shared for different types of layers. Any layer can have a `mask` property for example.

### Layer

Example layer structure:

```js
{
  "top": 0,
  "left": 0,
  "bottom": 200,
  "right": 300,
  "blendMode": "normal",
  "opacity": 1,
  "clipping": false,
  "timestamp": 1448235572.7235785,
  "transparencyProtected": true,
  "protected": {
    "transparency": true,
    "composite": false,
    "position": true
  },
  "hidden": false,
  "name": "Background",
  "nameSource": "bgnd",
  "id": 1,
  "layerColor": "none",
  "blendClippendElements": true,
  "blendInteriorElements": false,
  "knockout": false,
  "referencePoint": {
    "x": 0,
    "y": 0
  },
  "canvas": <Canvas>
},
```

- `top`, `left`, `bottom`, `right` properties specify location of layer image data within the document. `top` specifies offset in pixel of the top of layer image data from the top edge of the document, `bottom` specifies offset of the bottom of the layer image data from the top edge of the document and similar for `left` and `right`.

  This is necessary as layer image data can be smaller or large than the document size. This can cause in some cases the values of these fields to be negative. A value of `left: -100` means that the layer image data starts 100 pixels outside the left document edge. This can happen if you move the layer left beyond document edge in Photoshop.
  
  `top` and `left` values can be omitted when writing and will be assumed to be 0. `bottom` and `right` values can be omitted and will be ignored when writing and will instead be calculated from `canvas` (or `imageData`) width and height (they are only used when writing layers with `rawData` field).

- `blendMode` is a layer blending mode and will be one of the following values:

  ```ts
  type BlendMode = 'pass through' | 'normal' | 'dissolve' | 'darken' |
  'multiply' | 'color burn' | 'linear burn' | 'darker color' | 'lighten'|
  'screen' | 'color dodge' | 'linear dodge' | 'lighter color' | 'overlay' |
  'soft light' | 'hard light' | 'vivid light' | 'linear light' | 'pin light' |
  'hard mix' | 'difference' | 'exclusion' | 'subtract' | 'divide' | 'hue' |
  'saturation' | 'color' | 'luminosity' | 'linear height' | 'height' | 'subtraction'
  ```
  
  These values correspond to naming in layer blend mode dropdown. If omitted a value of `normal` will be assumed.

  ![](/files/blend-modes.png)

- `canvas` (or `imageData`) see `canvas` property description in [Basic document structure](#basic-document-structure)

  Vector, text and smart object layers still have image data with pregenerated bitmap. You also need to provide that image data when writing PSD files.
  
  Reading this property can be skipped if `skipLayerImageData: true` option is passed to `readPsd` function. This can be done to save on memory usage and processing time if layer image data is not needed.

- `opacity` specifies level of layer transparency (the value range is from 0 to 1). Can be omitted when writing, a default value of 1 will be assumed.

  ![](/files/opacity.png)

- `clipping` indicates if layer clipping is enabled (if enabled the layer is clipped to the layer below it). Can be omitted when writing, a default value of `false` will be assumed.

  ![](/files/clipping.png)
  
  ![](/files/clipping-2.png)

- `timestamp` timestamp of last time layer was modified (in unix time). Can be omitted when writing.

- `generatorSettings` Generator (Export As) settings of the layer, `exportOption` and `scaleSettings` are JSON strings. The same field on the document (`Psd` object) holds document generator settings, which can also have `assets` (Generator image assets settings) and `crema` (Export As document settings) JSON strings. Can be omitted when writing.

- `transparencyProtected` and `protected` properties specify status of various locks that you can set for each layer.

  ![](/files/locks.png)

  - `protected.position` indicates if moving layer is locked
  - `protected.composite` indicates if drawing on the layer is locked
  - `protected.transparency` indicates if drawing transparent pixels are locked
  - `protected.artboards` indicates if auto-nesting of layers in and out of artboards is prevented (only present when set)
  - `protected.all` indicates if "lock all" is enabled (only present when set)

  If the `transparencyProtected` is `true` but `protected.transparency` is `false` it means that the layer has "lock all" enabled. Both these fields can be omitted when writing, a value of `false` will be assumed for all of the omitted fields.

- `effectsOpen` indicates if effects/filters list of the layer is expanded in the layer list. Only present when set.

- `hidden` indicates if the layer is hidden. Can be omitted when writing, a value of `false` will be assumed.

  ![](/files/hidden.png)

- `name` name of the layer, can be any unicode string, can be empty. Can be omitted when writing, a value of `''` will be assumed.

- `nameSource` internal Photoshop information, can be ignored and omitted when writing.

- `id` unique ID number for layer, it may be missing in some PSD files. Can be omitted when writing, but if provided it has to be a unique number, if duplicate IDs are found they will be changed to a unique ones when writing the file.

- `layerColor` color of the layer in layer list, property will be missing or will be one of the following values:

  ```ts
  type LayerColor = 'none' | 'red' | 'orange' | 'yellow' | 'green' | 'blue' | 'violet' | 'gray' |
    'seafoam' | 'indigo' | 'magenta' | 'fuchsia'
  ```

  ![](/files/layer-color.png)

- `version` layer version, the Photoshop version of the layer format (`70` - Photoshop 7, `80` - CS, `110` - CS4, `120` - CS5, `130` - CS6 and newer versions). Internal Photoshop information, can be omitted when writing.

- `referencePoint` reference point of the layer (`x`, `y` in pixels). Photoshop updates it when the layer is moved, to keep content aligned to the layer position, like patterns of pattern overlay effect. It's `{ x: 0, y: 0 }` for layers that were never moved. Can be omitted when writing.

- `mask` Layer mask, property has the following structure.

  ```ts
  interface LayerMaskData {
    top?: number;
    left?: number;
    bottom?: number;
    right?: number;
    defaultColor?: number;
    disabled?: boolean;
    positionRelativeToLayer?: boolean;
    fromVectorData?: boolean; // set to true if the mask is generated from vector data, false if it's a bitmap provided by user
    userMaskDensity?: number;
    userMaskFeather?: number; // px
    vectorMaskDensity?: number;
    vectorMaskFeather?: number;
    canvas?: HTMLCanvasElement;
    imageData?: PixelData;
  }
  ```

  ![](/files/mask.png)

  Similar to layer image data this data has `top`, `left`, `bottom` and `right` offsets specified.

  `fromVectorData` Specifies if the mask image data was generated from `vectorMask`, if `fromVectorData` is set to false and both `vectorMask` and `mask` properties are present it means that the layer has 2 active masks, bitmap mask and a vector mask.

  `mask` property will be missing when layer has no mask, it can be omitted when writing.

- `realMask` "Real user mask", second layer mask with the same structure as `mask`, present in some files when layer has both a bitmap mask and a vector mask. It can be omitted when writing.

- `effects` Object describing layer "Blending Options"

  ![](/files/effects.png)
  
  ![](/files/effects-2.png)

  Effects property follows the following structure:

  ```ts
  interface LayerEffectsInfo {
    disabled?: boolean; // indicates if all effects are disabled
    scale?: number;
    dropShadow?: LayerEffectShadow[];
    innerShadow?: LayerEffectShadow[];
    outerGlow?: LayerEffectsOuterGlow;
    innerGlow?: LayerEffectInnerGlow;
    bevel?: LayerEffectBevel;
    solidFill?: LayerEffectSolidFill[];
    satin?: LayerEffectSatin;
    stroke?: LayerEffectStroke[];
    gradientOverlay?: LayerEffectGradientOverlay[];
    patternOverlay?: LayerEffectPatternOverlay; // pattern is referenced only by name/id
  }
  ```

  Some of the effects (specified here as arrays) can be specified multiple times. This is new feature, only supported in more recent versions of Photoshop.

  This property is not present if there are not blending options set for the layer. This property can be omitted when writing.

- `text` text properties of text layer (type tool info of Photoshop 5 text layers is also read into this field, these layers are written in current format)

  _TODO_

- `vectorFill` Fill color, gradient or pattern for the vector mask. Use `type` field to distinguish between different vector fill types, like this:

  ```ts
  switch (vectorFill.type) {
    case 'color':
      // solid color fill ({ color: Color } type)
      break;
    case 'solid':
      // solid gradient fill (EffectSolidGradient type)
      break;
    case 'noise':
      // noise gradient fill (EffectNoiseGradient type)
      break;
    case 'pattern':
      // pattern fill (EffectPattern type)
      break;
  }
  ```

- `vectorStroke` Vector stroke parameters for the vector mask. This field also contains parameters related to `vectorFill`. This property has following structure:

  ```ts
  type VectorStroke = {
		strokeEnabled?: boolean; // vector drawing has stroke
		fillEnabled?: boolean; // vector drawing has fill (specified by vectorFill property)
		lineWidth?: UnitsValue;
		lineDashOffset?: UnitsValue;
		miterLimit?: number;
		lineCapType?: LineCapType;
		lineJoinType?: LineJoinType;
		lineAlignment?: LineAlignment;
		scaleLock?: boolean;
		strokeAdjust?: boolean;
		lineDashSet?: UnitsValue[];
		blendMode?: BlendMode;
		opacity?: number;
		content?: VectorContent; // stroke color, gradient or pattern (see `vectorFill` field for more information)
		resolution?: number;
	}
  ```

- `vectorMask` Specifies vector mask used by `vectorFill` and `vectorStroke` to draw vector images. For layers without `vectorFill` it acts as a regular vector mask of the layer (clipping layer content to the path). This property has following structure:

  ```ts
  type LayerVectorMask = {
    invert?: boolean; // mask is inverted
    notLink?: boolean; // mask is not linked to the layer (doesn't move with layer content)
    disable?: boolean; // mask is disabled
    fillStartsWithAllPixels?: boolean; // initial fill rule, area outside of all paths is filled
    clipboard?: { top: number; left: number; bottom: number; right: number; resolution: number; }; // clipboard record, raw values
    paths: BezierPath[];
  };

  type BezierPath = {
    open: boolean; // path is open (not closed)
    operation?: 'combine' | 'subtract' | 'intersect' | 'exclude'; // how the path is combined with previous paths
    fillRule: 'even-odd' | 'non-zero';
    knots: BezierKnot[];
  };

  type BezierKnot = {
    linked: boolean; // control points are linked (smooth point)
    points: number[]; // [x0, y0, x1, y1, x2, y2] - preceding control point, anchor point and leaving control point in pixels
  };
  ```

- `usingAlignedRendering` "Align Edges" option of shape layers, snaps vector shape edges to pixel grid. Photoshop stores it on shape layers.

- `adjustment` indicates that the layer is an adjustment layer. Adjustment layer do not have image data. This property is not present on non-adjustment layers.

  ![](/files/adjustment.png)
  
  Use `type` field of the adjustment object to distinguish between different adjustment layer types.
  
  ```ts
  switch (adjustment.type) {
    case 'brightness/contrast':
      // handle BrightnessAdjustment layer
      break;
    case 'levels':
      // handle LevelsAdjustment layer
      break;
    // ... other cases ...
  }
  ```

  see all Adjustment layer types in [psd.ts file](/src/psd.ts)

- `placedLayer` indicates that this is smart object layer, see [Smart Objects section](#smart-objects) for more information. This property is only present on smart object layers.

- `vectorOrigination` Live shape properties of shape layers (shapes drawn with rectangle, ellipse, polygon, line, etc. tools that keep their original parameters editable in Properties panel). Contains one item in `keyDescriptorList` for each live shape in the layer's vector mask. Each item has the following structure:

  ```ts
  type KeyDescriptorItem = {
    keyOriginType?: number; // shape type: 1 - rectangle, 2 - rounded rectangle, 4 - line, 5 - ellipse, 8 - polygon
    keyOriginResolution?: number; // document resolution the shape was created with
    keyOriginRRectRadii?: { topRight: UnitsValue; topLeft: UnitsValue; bottomLeft: UnitsValue; bottomRight: UnitsValue; }; // corner radii of the rectangle
    keyOriginShapeBoundingBox?: { top: UnitsValue; left: UnitsValue; bottom: UnitsValue; right: UnitsValue; }; // bounds of the shape
    keyOriginBoxCorners?: { x: number; y: number; }[]; // 4 corners of the shape bounding box (top-left, top-right, bottom-right, bottom-left)
    // polygon (and star) settings
    keyOriginPolySides?: number;
    keyOriginPolyCornerRadius?: number;
    keyOriginPolyStarRatio?: number; // 0..1, inner radius of the star
    keyOriginPolyPreviousTightBoxCorners?: { x: number; y: number; }[];
    keyOriginPolyTrueRectCorners?: { x: number; y: number; }[];
    keyOriginPolyPixelHSF?: number;
    // line settings
    keyOriginLineStart?: { x: number; y: number; };
    keyOriginLineEnd?: { x: number; y: number; };
    keyOriginLineWeight?: number;
    keyOriginLineArrowStart?: boolean;
    keyOriginLineArrowEnd?: boolean;
    keyOriginLineArrowWidth?: number;
    keyOriginLineArrowLength?: number;
    keyOriginLineArrowConcavity?: number;
    transform?: number[]; // 2d transform matrix of the shape [xx, xy, yx, yy, tx, ty]
    keyShapeInvalidated?: boolean; // shape path was edited directly and is no longer a live shape
  };
  ```

- `compositorUsed` information about the compositing engine Photoshop used to render the image when saving the file. It's informational only and doesn't need to be provided when writing. Photoshop stores it on the document (`Psd` object), not on individual layers. Example value:

  ```js
  compositorUsed: {
    description: '',
    reason: '',
    engine: 'compCoreGPU', // 'compCore', 'compCoreGPU' or 'umerge' (older compositor, used when CompCore is disabled)
    version: { major: 1, minor: 3, fix: 0 }, // compositor version
    photoshopVersion: { major: 27, minor: 7, fix: 0 },
    enableCompCore: 'feature',
    enableCompCoreGPU: 'feature',
    enableCompCoreThreads: 'feature',
    compCoreSupport: 'supported', // 'supported' or 'featureDisabled'
    compCoreGPUSupport: 'supported', // 'supported' or 'featureDisabled'
  }
  ```

- `artboard` Artboard location and parameters, this property is only present when using artboards. Artboard object has the following structure:

  ```ts
  type Artboard = {
    rect: { top: number; left: number; bottom: number; right: number; };
    guideIndices?: any[];
    presetName?: string;
    color?: Color;
    backgroundType?: number;
  }
  ```

  ![](/files/artboards.png)

- **Advanced blending options**

  ![](/files/advanced-blending-options.png)

  - `fillOpacity` "Fill Opacity" level (value ranges from 0 to 1)
  
    ![](/files/fill-opacity.png)
  - `knockout` "Knockout" value
  - `blendClippendElements` "Blend Clipped Layers as Group" value (has to be set to `true` when using `color burn` blend mode)
  - `blendInteriorElements` "Blend Interior Effects as Group" value
  - `transparencyShapesLayer` "Transparency Shapes Layer" value
  - `layerMaskAsGlobalMask` "Layer Mask Hides Effects" value
  - `vectorMaskAsGlobalMask` "Vector Mask Hides Effects" value
  - `channelBlendingRestrictions` list of disabled color channels ("Channels" checkboxes), channel indices start from 0
  - `blendingRanges` "Blend If" ranges
  - `linkGroup` and `linkGroupEnabled` Layers with the same `linkGroup` value are linked together for moving/transforming. `0` value means no linking is active.
  
    ![](/files/linked-layers.png)

- `engineData` internal text information

- `animationFrames`, `animationFrameFlags` and `timeline` per-layer animation frame and video timeline data, see [psd.ts file](/src/psd.ts) for structure.

- `comps` per-layer settings for layer comps (see `layerComps` in [Image Resources](#image-resources)). Items of `comps.settings` and `animationFrames` can override layer properties for the comp/frame:

  ```ts
  {
    offset?: { x: number; y: number; }; // layer position offset
    vectorMaskOffset?: { x: number; y: number; };
    maskOffset?: { x: number; y: number; }; // animationFrames only
    effects?: LayerEffectsInfo;
    blendMode?: BlendMode;
    opacity?: number; // 0..1
    fillOpacity?: number; // 0..1
    blendClippedElements?: boolean;
    blendInteriorElements?: boolean;
    knockout?: 'none' | 'shallow' | 'deep';
    text?: { warp: Warp; warpRect: number[]; }; // warp of text layer
    placedLayerCompId?: number; // layer comp of smart object
  }
  ```

- `filterMask`, `userMask` and `filterEffectsMasks` additional mask information, `userMask.opacity` and `filterMask.opacity` values range from 0 to 1. Image data of `filterEffectsMasks` items is stored undecoded, it can be decoded using `getFilterEffectsMaskImageData` / `getFilterEffectsMaskCanvas` (color and transparency channels) and `getFilterEffectsMaskExtraImageData` / `getFilterEffectsMaskExtraCanvas` (`extra` mask) functions (see [main README document](/README.md#functions)). `colorMode` of `filterEffectsMasks` items is set to color mode of the document when reading (it's not written to the file), it's used for decoding the color channels.

- `pixelSource` video layer source information.

- `pixelSourceData` raw data of video layer frames (`Uint8Array` for each entry).

- `framedGroup` frame settings of frame layers (created with Frame tool), `rect` of the frame, frame `type` (1 - rectangle, 2 - ellipse), `lockPPI`, `preferredResolution` and `savedIteratedName`.

- `foreignEffectId`, `animationEffects` (raw descriptor data) and `patternData` (patterns used by the layer, Photoshop 6) additional layer information.

### Group

Example group structure:

```js
{
  "top": 0,
  "left": 0,
  "bottom": 0,
  "right": 0,
  "blendMode": "normal",
  "opacity": 1,
  "clipping": false,
  "timestamp": 1450198418.5245173,
  "transparencyProtected": false,
  "hidden": false,
  "name": "Group 1",
  "nameSource": "lset",
  "id": 5,
  "sectionDivider": {
    "type": 1,
    "key": "pass",
    "subType": 0
  },
  "protected": {
    "transparency": false,
    "composite": false,
    "position": false
  },
  "layerColor": "none",
  "referencePoint": {
    "x": 0,
    "y": 0
  },
  "opened": true,
  "children": [
    // layers here
  ]
}
```

Groups don't have `canvas` / `imageData` property, as you can't draw directly on a group. Groups don't have any other special layer property like `text`, `vectorFill`, `adjustment` or `placedLayer`.

**Group-only fields:**

- `children` contains list of all layers in this group. **Cannot** be omitted when writing, without this field a group will be assumed to be a regular layer. Use empty `children` array when writing empty group.

- `opened` indicates if the group is expanded or collapsed in the layer list. If omitted a default value of `true` will be assumed.

  ![](/files/group-open.png)

- `sectionDivider` internal Photoshop property, can be ignored and omitted when writing.

## Image Resources

Image resources are global document settings, stored in `psd.imageResources` field. Any of these settings can be omitted when writing. PSD file can have following global options:

- `versionInfo` Version information of Program that generated the PSD file, example value:

  ```js
  versionInfo = {
    "hasRealMergedData": true,
    "writerName": "Adobe Photoshop",
    "readerName": "Adobe Photoshop CS6",
    "fileVersion": 1
  }
  ```

- `layerSelectionIds` list of layer IDs of selected layers, these layers will be selected when you open PSD document in Photoshop.

- `pixelAspectRatio` Specifies aspect ratio of the PSD document pixels, almost always 1

  ```js
  pixelAspectRatio = {
    "aspect": 1
  }
  ```

- `gridAndGuidesInformation` Information about document grid and guides. Guide `location` is specified in pixels, `grid` values are specified in 1/32 pixel units (`576` is 18 pixels). Guides can also have `color` (RGB, Photoshop default is `{ r: 74, g: 255, b: 255 }`) and unique `id` (GUID string), guide ids are only written if all guides have them.

  ![](/files/guides.png)
  
  Example value:
  
  ```js
  gridAndGuidesInformation = {
    "grid": {
      "horizontal": 576,
      "vertical": 576
    },
    "guides": [
      {
        "location": 531.4375,
        "direction": "vertical", // "horizontal" or "vertical"
        "color": { "r": 74, "g": 255, "b": 255 },
        "id": "8544d157-6d38-7249-8b2c-56d4a2d49c08"
      },
      // ... more guides here ...
    ]
  };
  ```

- `resolutionInfo` Image resolution info, specifies physical size of the image pixels. Example value:

  ```js
  resolutionInfo: {
    "horizontalResolution": 72,
    "horizontalResolutionUnit": "PPI", // 'PPI' (pixels per inch) or 'PPCM' (pixels per centimeter)
    "widthUnit": "Inches",
    "verticalResolution": 72,
    "verticalResolutionUnit": "PPI",
    "heightUnit": "Inches" // 'Inches', 'Centimeters', 'Points', 'Picas' or 'Columns'
  },
  ```

- `thumbnail` Canvas element with thumbnail image for the document, this property can be missing in some PSD files. This property can be omitted when writing if there's no need to support thumbnails, this field can be automatically generated from composite image data if `generateThumbnail: true` option is passed to `writePsd` function.

- `thumbnailRaw` This property will be used instead if `useRawThumbnail` option is specified when reading PSD file. It contains `width`, `height` and `data` (JPEG encoded thumbnail) fields. Uncompressed (raw RGB) thumbnails are only read into `thumbnail` field.

- `xmpMetadata` XMP metadata. File info as XML description. See http://www.adobe.com/devnet/xmp/

- `iccUntaggedProfile` ICC Untagged Profile

- `iccProfile` raw ICC color profile data (`Uint8Array`).

- `exifData` raw EXIF data (`Uint8Array`, TIFF format).

- `iptcData` raw IPTC-NAA record (`Uint8Array`).

- `windowsDevMode` raw Windows DEVMODE structure with printer settings (`Uint8Array`).

- `outputSettings` Save for Web output settings, raw descriptor object (with `_name` and `_classID` fields), written back unchanged.

- `colorHalftoneScreens`, `grayscaleHalftoneScreens`, `colorTransferFunctions` and `grayscaleTransferFunctions` halftone screens and transfer functions used for printing.

- `printInformation`, `printScale`, `printFlags`, `printFlagsInfo` and `printStyle` Specifies options for printing the document.

- `indexedColorCount` and `transparencyIndex` number of used colors and index of transparent color of "Indexed" color mode palette, pixels with transparent color are read as transparent in composite image.

- `alphaChannelDisplayInfo` display options (color, opacity and kind) of alpha and spot channels, in the same order as `alphaChannelNames`. Colors in color spaces not supported by the library are stored in `rawColor` field (color space id and 4 raw values) instead of `color`. Obsolete display info resource (Photoshop 5) is also read into this field, it is always written in the newer format.

- `colorSamplers` positions (in pixels), color spaces and sample size (`depth`) of color samplers. Samplers are written in Photoshop CS3 format if any of them has `depth` set, otherwise Photoshop 5 format is used.

- `quickMaskInfo` channel id and "initially empty" flag of Quick Mask.

- `measurementScale` measurement scale settings (raw descriptor data, `Uint8Array`).

- `duotoneHalftoneScreens`, `duotoneTransferFunctions`, `duotoneImageInformation` (raw data) and `alternateDuotoneColors` (Lab equivalents of duotone inks) settings of "Duotone" documents.

- `effectsVisible` global flag to show or hide all layer effects (Photoshop only writes it when effects are hidden).

- `layerComps` list of layer comps defined in the document, per-layer settings are stored in `comps` field of each layer. `expanded` field of a comp indicates if it's expanded in Layer Comps panel.

- `animations`, `onionSkins`, `timelineInformation` and `sheetDisclosure` frame animation and video timeline settings. `animations.activeAnimation` is the active animation and `globalAngle` and `globalAltitude` fields of `animations.frames` items are global light settings of the frame.

- `slices` list of slices defined in the document.

- `countInformation` data of the Count tool.

- `copyrighted` and `url` copyright status and URL from File Info dialog.

- `layerState` index of the target (active) layer, `0` is the bottom layer.

- `alphaChannelNames` names of alpha channels (saved selections) and spot channels stored in the composite image, in channel order. Photoshop also lists merged transparency as the first channel named `"Transparency"` in some documents. Written to both the legacy (Pascal string) and the unicode image resource.

- `alphaIdentifiers` unique identifiers of alpha channels, in the same order as `alphaChannelNames`.

- `globalAngle` and `globalAltitude` global light angle (in degrees) and altitude (in degrees) used by layer effects with `useGlobalLight` option enabled.

- `urlsList` list of URLs assigned to slices, `id` is the id of the slice (`ref` is always `'slice'`).

- `captionDigest` MD5 digest of the IPTC data (`iptcData`), as 32 character hex string.

- `backgroundColor` background color of the color picker (tools panel) at the time the document was saved.

- `idsSeedNumber` base value that new layer IDs are generated from (Photoshop uses higher value if existing IDs already exceed it).

- `pathSelectionState` reference to selected path in the paths panel, for example `['Path.vectorMask', 'Rectangle 1']` for vector mask of the layer named "Rectangle 1", or `['Ordn.Trgt']` for the target path.

- `savedPaths` saved paths from the Paths panel. Path data uses the same structure as layer `vectorMask` (points are in document pixels):

  ```ts
  type SavedPath = {
    name: string;
    symmetryMode?: string; // raw enum value from paths with symmetry, e.g. 'pathSymmetryModeBasicPath'
    fillStartsWithAllPixels?: boolean;
    clipboard?: { top: number; left: number; bottom: number; right: number; resolution: number; };
    paths: BezierPath[];
    vectorOrigination?: { keyDescriptorList: KeyDescriptorItem[]; }; // live shape properties, same as layer `vectorOrigination`
  };
  ```

  Photoshop stores each path in a separate image resource (named using legacy encoding, non-ASCII characters are written as `?`) and unicode names in `pths` additional info, which is written whenever `savedPaths` is set (Photoshop writes empty `pths` for documents without paths, which reads as an empty array).

- `workPath` temporary "Work Path" from the Paths panel, same structure as saved path without `name`.

- `clippingPath` saved path used as clipping path (when placing image in other applications), `name` refers to name of one of `savedPaths`, `flatness` is in device pixels (`0` for printer default).

- `imageReadyVariables` and `imageReadyDataSets` XML of variables and data sets (Image > Variables), stored as raw strings.

## Smart Objects

Layers with `placedLayer` property are smart object layers. `placedLayer` property has the following structure:

```ts
interface PlacedLayer {
	id: string; // id of linked image file (psd.linkedFiles), must be in a GUID format (example: 20953ddb-9391-11ec-b4f1-c15674f50bc4)
	placed?: string; // unique id
	type: PlacedLayerType;
	external?: boolean; // linked smart object (linked file is stored outside of the document)
	pageNumber?: number;
	totalPages?: number;
	frameStep?: { numerator: number; denominator: number; };
	duration?: { numerator: number; denominator: number; };
	frameCount?: number;
	transform: number[]; // x, y of 4 corners of the transform
	nonAffineTransform?: number[]; // x, y of 4 corners of the transform
	width?: number; // width of the linked image
	height?: number; // height of the linked image
	resolution?: UnitsValue;
	warp?: Warp; // warp coordinates are relative to the linked image size
	crop?: number;
	comp?: number;
	compInfo?: { compID: number; originalCompID: number; };
	filter?: PlacedLayerFilter; // smart filters
	imported?: boolean; // `Impr` flag stored by Photoshop
}
```

Smart filters that are not supported by this library are skipped when reading (an error is thrown instead if `throwForMissingFeatures` option is set).

The Psd object has `linkedFiles` property, that specifies list of all files linked in smart objects. Each linked file has following structure:

```ts
interface LinkedFile {
	id: string; // must be in a GUID format (example: 20953ddb-9391-11ec-b4f1-c15674f50bc4)
	name: string;
	type?: string;
	creator?: string;
	data?: Uint8Array;
	time?: string; // for external files, date in ISO format
	descriptor?: {
		compInfo: { compID: number; originalCompID: number; };
	};
	childDocumentID?: string;
	assetModTime?: number;
	assetLockedState?: number;

	// external files
	linkedFile?: {
		fileSize: number;
		name: string;
		fullPath: string;
		originalPath: string;
		relativePath: string;
		alias?: string; // binary data of macOS alias record (one character per byte)
	};
}
```

`id` field in `PlacedLayer` refers to the `id` in `LinkedFile`. Example values:

```js
  layer.placedLayer = {
    "id": "20953ddb-9391-11ec-b4f1-c15674f50bc4", // id that matches linkedFiles ID
    "placed": "20953dda-9391-11ec-b4f1-c15674f50bc4", // unique id for this object
    "type": "raster", // one of the 'unknown', 'vector', 'raster' or 'image stack'
    "transform": [ // x, y of 4 corners of the transform box
      29,
      28,
      83,
      28,
      83,
      82,
      29,
      82
    ],
    "width": 32, // width and height of the target image
    "height": 32,
    "resolution": {
      "value": 299.99940490722656,
      "units": "Density"
    }
  };

  psd.linkedFiles = [
    {
      "id": "20953ddb-9391-11ec-b4f1-c15674f50bc4",
      "name": "cat.png",
      "data": fileContentsAsUint8Array,
    }
  ];
```

## Units value

Some fields in the PSD document specify a value with units, those fields use `UnitsValue` type:

```ts
interface UnitsValue {
	units: Units;
	value: number;
}
```

`value` fields can be any number value, `units` fields has to be one of the supported units: "Pixels", "Points", "Picas", "Millimeters", "Centimeters", "Inches", "None", "Density". Some fields only support some of the units, check with Photoshop for supported units.

Example values:

```ts
var distance = { value: 5, units: "Pixels" };
var lineWidth = { value: 3, units: "Points" };
```

## Colors

Many fields in PSD file support passing color in different color formats (RGBA, RGB, HSB, CMYK, LAB, Grayscale) Those fields will use `Color` type which is a union of all of these color formats. The color types have following structure:

```ts
type RGBA = { r: number; g: number; b: number; a: number; }; // values from 0 to 255
type RGB = { r: number; g: number; b: number; }; // values from 0 to 255
type FRGB = { fr: number; fg: number; fb: number; }; // values from 0 to 1 (can be above 1, can be negative)
type HSB = { h: number; s: number; b: number; }; // values from 0 to 1
type CMYK = { c: number; m: number; y: number; k: number; }; // values from 0 to 255
type LAB = { l: number; a: number; b: number; }; // values `l` from 0 to 1; `a` and `b` from -1 to 1
type Grayscale = { k: number }; // values from 0 to 255
type Color = (RGBA | RGB | FRGB | HSB | CMYK | LAB | Grayscale) & { book?: ColorBookInfo; };
```

Colors picked from color books (Pantone, etc.) also have `book` field with name of the book and the color (`{ book: string; name: string; bookID: number; bookKey: string; }`), color values hold the book color converted to document color space.

When you want to set field with a `Color` type, it's pretty straightforward, you can just choose any of the formats you like and set it on the field:

```ts
strokeEffect.color = { h: 0.79, s: 0.54, b: 0.93 };
```

Reading a color field is more complicated, you need to check what color format the field is in and then run correct code to handle it, here's how to do it for all color types:

```ts
if ('l' in color) {
  // color is LAB
} else if ('c' in color) {
  // color is CMYK
} else if ('h' in color) {
  // color is HSB
} else if ('k' in color) {
  // color is Grayscale
} else if ('a' in color) {
  // color is RGBA
} else if ('fr' in color) {
  // color is FRGB
} else {
  // color is RGB
}
```

If you expect the fields to be in one specific format you can just verify that it's correct and throw an error if it's a format that you didn't expect:

```ts
// handle only RGB colors
if ('r' in color && !('a' in color)) {
  // color is RGB
} else {
  throw new Error('Invalid color');
}
```
