1 /*
<lambda>null2 * Copyright (C) 2021 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 package com.example.testapp
18
19 import android.renderscript.toolkit.Range2d
20
21 /**
22 * Reference implementation of a ColorMatrix operation.
23 */
24 @ExperimentalUnsignedTypes
25 fun referenceColorMatrix(inputArray: ByteArray,
26 inputVectorSize: Int,
27 sizeX: Int,
28 sizeY: Int,
29 outputVectorSize: Int,
30 matrix: FloatArray, addVector: FloatArray,
31 restriction: Range2d?): ByteArray {
32 require (matrix.size == 16) { "RenderScriptToolkit colorMatrix. Matrix should have 16 values. ${matrix.size} provided." }
33
34 val input = Vector2dArray(inputArray.asUByteArray(), inputVectorSize, sizeX, sizeY)
35 val outputArray = ByteArray(sizeX * sizeY * paddedSize(outputVectorSize))
36 val output = Vector2dArray(outputArray.asUByteArray(), outputVectorSize, sizeX, sizeY)
37
38 output.forEach (restriction) { x, y ->
39 val inUByteValue = input[x, y]
40 val inFloatValue = FloatArray(4) { if (it >= inputVectorSize) 0f else byteToUnitFloat(inUByteValue[it]) }
41 val outFloatValue = multiplyAndAdd(matrix, inFloatValue, addVector)
42 val outUByteValue = UByteArray(paddedSize(output.vectorSize)) { unitFloatClampedToUByte(outFloatValue[it]) }
43 output[x, y] = outUByteValue
44 }
45 return outputArray
46 }
47
multiplyAndAddnull48 private fun multiplyAndAdd(matrix: FloatArray, inVector: FloatArray, addVector: FloatArray): FloatArray {
49 // In RenderScript, matrix were set in column major format
50 val result = addVector.clone()
51 for (i in 0..3) {
52 for (j in 0..3) {
53 result[i] += matrix[j * 4 + i] * inVector[j]
54 }
55 }
56 return result
57 }
58