{"size": 1899, "ext": "js", "max_stars_repo_path": "brush/src/components/TileSet/TilesetGraphics.js", "max_stars_repo_name": "macabeus/klo-gba.js", "max_stars_repo_stars_event_min_datetime": "2019-03-12T04:01:48.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-29T07:16:12.000Z", "max_issues_repo_path": "brush/src/components/TileSet/TilesetGraphics.js", "max_issues_repo_name": "macabeus/klo-gba.js", "max_issues_repo_issues_event_min_datetime": "2019-03-17T00:22:53.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-19T00:25:03.000Z", "max_forks_repo_path": "brush/src/components/TileSet/TilesetGraphics.js", "max_forks_repo_name": "macabeus/klo-gba.js", "max_forks_repo_forks_event_min_datetime": "2019-03-12T11:55:27.000Z", "max_forks_repo_forks_event_max_datetime": "2021-04-03T12:56:31.000Z"}
{"max_stars_count": 134, "max_issues_count": 34, "max_forks_count": 9, "avg_line_length": 22.3411764706, "max_line_length": 73, "alphanum_fraction": 0.5987361769}
import React, { memo } from 'react'
import PropTypes from 'prop-types'
import * as PIXI from 'pixi.js'
import { Graphics } from '@inlet/react-pixi'
import { renderTilesTexture } from '../../pixiHelpers/renderTextures'

const TilesetGraphics = ({
  palette,
  pixiRenderer,
  setToolState,
  tileset,
}) => {
  const tileTextures = renderTilesTexture(pixiRenderer, tileset, palette)

  const tileIndexToCoordenates = (tileIndex) => {
    const x = tileIndex % 10
    const y = (Math.floor(tileIndex / 10))

    return [x * 8, y * 8]
  }

  const coordenatesToTileIndex = (x, y) => {
    const offsetX = Math.floor(x / 8)
    const offsetY = Math.floor(y / 8) * 10

    return offsetX + offsetY
  }

  return (
    <Graphics
      draw={(g) => {
        g.removeChildren()

        for (
          let tileIndex = 0;
          tileIndex < tileTextures.length;
          tileIndex += 1
        ) {
          const [x, y] = tileIndexToCoordenates(tileIndex)

          const texture = tileTextures[tileIndex]
          const sprite = new PIXI.Sprite(texture)

          sprite.x = x
          sprite.y = y

          g.addChild(sprite)
        }
      }}
      interactive
      pointerdown={e => {
        const tileId = coordenatesToTileIndex(
          e.data.global.x,
          e.data.global.y
        )

        if (tileId === 0) {
          setToolState('eraser')
          return
        }

        setToolState(
          'brush', tileId
        )
      }}
    />
  )
}

TilesetGraphics.propTypes = {
  palette: PropTypes.array.isRequired,
  pixiRenderer: PropTypes.object.isRequired,
  setToolState: PropTypes.func.isRequired,
  tileset: PropTypes.array.isRequired,
}

const memoReuseTilesetGraphics = (Component) => memo(
  Component,
  (previous, next) =>
    (previous.world === next.world)
    && (previous.index === next.index)
)

export default memoReuseTilesetGraphics(TilesetGraphics)
