// Atari ST per-surface planar storage, shared between the HAL
// (src/atarist/hal.c) and the cross-platform sprite dispatchers
// (src/codegen/spriteCompile.c) so buffer-base access inlines instead
// of paying a cross-TU function call (NATIVE-PERF Phase 2). The base
// pointer is lifetime-immutable: portData is written only at surface
// create/destroy, so reading it needs no cache and no invalidation.
#ifndef JOEY_ST_PLANAR_H
#define JOEY_ST_PLANAR_H

#include <stdint.h>
#include <stdbool.h>

#include "surfaceInternal.h"

// Interleaved-layout strides, shared with the stTile.h inlines:
// 160 bytes per scanline as 20 groups of 4 plane words (8 bytes).
#define ST_BYTES_PER_ROW    160
#define ST_BYTES_PER_GROUP  8         // 4 plane words back-to-back

// jlSurfaceT.portData points to this on the ST. ST has word-interleaved
// planar: ONE 32000-byte buffer per surface holds all 4 planes packed
// 8 bytes per 16-pixel group. Per-scanline layout (160 bytes) is 20
// groups of 8 bytes, where each group holds p0_word, p1_word, p2_word,
// p3_word back-to-back. Compare with Amiga's 4 separate plane buffers
// -- same total bytes, very different access pattern.
//
// The stage gets its own SHADOW planar buffer (NOT aliased to a
// displayed page) so drawing primitives don't appear until
// jlStagePresent copies the union(prev,current) dirty rows from the
// shadow into the off-screen page and flips the shifter to it. Same
// rationale as Amiga's per-stage shadow planes feeding its 2-buffer
// page flip.
typedef struct {
    uint8_t *base;          // 32000-byte interleaved planar buffer
    uint8_t *raw;           // unaligned malloc result for free()
    bool     ownsBuffer;    // true = we malloc'd, false = aliased
} StPlanarT;


// NULL means "surface has no planar storage" -- callers use that as
// their route-to-generic / no-op gate, exactly the contract the old
// jlpSurfacePlanePtr cross-TU function provided.
static inline StPlanarT *stSurfacePlanar(const jlSurfaceT *s) {
    return (StPlanarT *)s->portData;
}

#endif
