prepare method

Future<void> prepare()

I am... INEVITABLE ~Thanos

Implementation

Future<void> prepare() async {
  //get image from child
  final fullImage = await _getImageFromWidget();

  //create an image for every bucket
  List<image.Image> images = List<image.Image>.generate(
    widget.numberOfBuckets,
    (i) => image.Image(width: fullImage.width, height: fullImage.height),
  );

  //for every line of pixels
  for (int y = 0; y < fullImage.height; y++) {
    //generate weight list of probabilities determining
    //to which bucket should given pixels go
    List<int> weights = List.generate(
      widget.numberOfBuckets,
      (bucket) => _gauss(
        y / fullImage.height,
        bucket / widget.numberOfBuckets,
      ),
    );
    int sumOfWeights = weights.fold(0, (sum, el) => sum + el);

    //for every pixel in a line
    for (int x = 0; x < fullImage.width; x++) {
      //get the pixel from fullImage
      image.Pixel pixel = fullImage.getPixel(x, y);
      //choose a bucket for a pixel
      int imageIndex = _pickABucket(weights, sumOfWeights);
      //set the pixel from chosen bucket
      images[imageIndex].setPixel(x, y, pixel);
    }
  }

  //* compute allows us to run _encodeImages in separate isolate
  //* as it's too slow to work on the main thread
  _layers = await compute<List<image.Image>, List<Uint8List>>(
      _encodeImages, images);

  //prepare random dislocations and set state
  setState(() {
    _randoms = List.generate(
      widget.numberOfBuckets,
      (i) => (math.Random().nextDouble() - 0.5) * 2,
    );
  });

  //give a short delay to draw images
  await Future.delayed(const Duration(milliseconds: 100));
  _isPrepared = true;
}