xref: /aosp_15_r20/external/skia/src/sksl/ir/SkSLConstructorDiagonalMatrix.cpp (revision c8dee2aa9b3f27cf6c858bd81872bdeb2c07ed17)
1 /*
2  * Copyright 2021 Google LLC
3  *
4  * Use of this source code is governed by a BSD-style license that can be
5  * found in the LICENSE file.
6  */
7 
8 #include "src/sksl/ir/SkSLConstructorDiagonalMatrix.h"
9 
10 #include "include/core/SkTypes.h"
11 #include "src/sksl/SkSLConstantFolder.h"
12 #include "src/sksl/ir/SkSLType.h"
13 
14 namespace SkSL {
15 
Make(const Context & context,Position pos,const Type & type,std::unique_ptr<Expression> arg)16 std::unique_ptr<Expression> ConstructorDiagonalMatrix::Make(const Context& context,
17                                                             Position pos,
18                                                             const Type& type,
19                                                             std::unique_ptr<Expression> arg) {
20     SkASSERT(type.isMatrix());
21     SkASSERT(type.isAllowedInES2(context));
22     SkASSERT(arg->type().isScalar());
23     SkASSERT(arg->type().matches(type.componentType()));
24 
25     // Look up the value of constant variables. This allows constant-expressions like `mat4(five)`
26     // to be replaced with `mat4(5.0)`.
27     arg = ConstantFolder::MakeConstantValueForVariable(pos, std::move(arg));
28 
29     return std::make_unique<ConstructorDiagonalMatrix>(pos, type, std::move(arg));
30 }
31 
getConstantValue(int n) const32 std::optional<double> ConstructorDiagonalMatrix::getConstantValue(int n) const {
33     int rows = this->type().rows();
34     int row = n % rows;
35     int col = n / rows;
36 
37     SkASSERT(col >= 0);
38     SkASSERT(row >= 0);
39     SkASSERT(col < this->type().columns());
40     SkASSERT(row < this->type().rows());
41 
42     return (col == row) ? this->argument()->getConstantValue(0) : 0.0;
43 }
44 
45 }  // namespace SkSL
46