summaryrefslogtreecommitdiffstats
path: root/Scripts/DataDecoder.cs
blob: 810c46ae3701457b130d1a1eec25b2300fa686c7 (plain)
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
using UdonSharp;
using UnityEngine;
using VRC.SDK3.Rendering;
using VRC.Udon.Common.Interfaces;

public class DataDecoder : UdonSharpBehaviour
{
  public RenderTexture sourceTexture;
  public int tileSize = 8;
  public int tileToCheck = 0;

  private Color32[] pixelData;
  private bool hasData = false;
  private int readWidth;
  private int readHeight;

  void Start() {}

  void Update()
  {
    if (sourceTexture == null || tileSize <= 0) return;

    // TODO get more than one column
    int requestWidth = Mathf.Min(tileSize, sourceTexture.width);
    int requestHeight = sourceTexture.height;
    int pixelCount = requestWidth * requestHeight;

    if (pixelCount <= 0) return;

    if (pixelData == null || pixelCount != pixelData.Length)
    {
      pixelData = new Color32[pixelCount];
      hasData = false;
    }

    readWidth = requestWidth;
    readHeight = requestHeight;

    VRCAsyncGPUReadback.Request(sourceTexture,
        0,
        0, readWidth,
        0, readHeight,
        0, 1,
        (IUdonEventReceiver)this);

    if (hasData)
    {
      ProcessTiles();
      hasData = false;
    }
  }

  public override void OnAsyncGpuReadbackComplete(VRCAsyncGPUReadbackRequest request)
  {
    if (request.hasError) return;

    if (pixelData != null && request.TryGetData(pixelData))
    {
      hasData = true;
    }
  }

  private void ProcessTiles()
  {
    if (pixelData == null || readWidth <= 0 || readHeight <= 0) return;

    int tilesPerColumn = (int) Mathf.Floor(readHeight / tileSize);

    GetTileRGB(tileToCheck, out int r, out int g, out int b);
    Debug.Log($"Tile {tileToCheck}: R={r}, G={g}, B={b}");
  }

  private void GetTileRGB(int tileIndex, out int r, out int g, out int b)
  {
    r = 0;
    g = 0;
    b = 0;

    int tileY = tileIndex * tileSize;
    int centerY = tileY + tileSize / 2;

    if (centerY >= readHeight) return;

    int localX = readWidth / 2;
    int localY = readHeight - 1 - centerY;
    int index = localY * readWidth + localX;

    if (index < 0 || index >= pixelData.Length) return;

    Color32 c = pixelData[index];
    r = c.r;
    g = c.g;
    b = c.b;
  }
}