1 /*-------------------------------------------------------------------------
2 * drawElements Quality Program Random Shader Generator
3 * ----------------------------------------------------
5 * Copyright 2014 The Android Open Source Project
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
22 *//*--------------------------------------------------------------------*/
24 #include "rsgExpression.hpp"
25 #include "rsgVariableManager.hpp"
26 #include "rsgBinaryOps.hpp"
27 #include "rsgBuiltinFunctions.hpp"
28 #include "rsgUtils.hpp"
42 typedef ValueEntryIterator<IsReadableEntry> Iterator;
44 IsReadableEntry (deUint32 exprFlags)
45 : m_exprFlags(exprFlags)
49 bool operator() (const ValueEntry* entry) const
51 if ((m_exprFlags & CONST_EXPR) && (entry->getVariable()->getStorage() != Variable::STORAGE_CONST))
61 class IsReadableIntersectingEntry : public IsReadableEntry
64 typedef ValueEntryIterator<IsReadableIntersectingEntry> Iterator;
66 IsReadableIntersectingEntry (ConstValueRangeAccess valueRange, deUint32 exprFlags)
67 : IsReadableEntry (exprFlags)
68 , m_valueRange (valueRange)
72 bool operator() (const ValueEntry* entry) const
74 if (!IsReadableEntry::operator()(entry))
77 if (entry->getValueRange().getType() != m_valueRange.getType())
80 if (!entry->getValueRange().intersects(m_valueRange))
87 ConstValueRangeAccess m_valueRange;
90 class IsWritableIntersectingEntry : public IsWritableEntry
93 typedef ValueEntryIterator<IsWritableIntersectingEntry> Iterator;
95 IsWritableIntersectingEntry (ConstValueRangeAccess valueRange)
96 : m_valueRange(valueRange)
100 bool operator() (const ValueEntry* entry) const
102 return IsWritableEntry::operator()(entry) &&
103 entry->getVariable()->getType() == m_valueRange.getType() &&
104 entry->getValueRange().intersects(m_valueRange);
108 ConstValueRangeAccess m_valueRange;
111 class IsWritableSupersetEntry : public IsWritableEntry
114 typedef ValueEntryIterator<IsWritableSupersetEntry> Iterator;
116 IsWritableSupersetEntry (ConstValueRangeAccess valueRange)
117 : m_valueRange(valueRange)
121 bool operator() (const ValueEntry* entry) const
123 return IsWritableEntry()(entry) &&
124 entry->getVariable()->getType() == m_valueRange.getType() &&
125 entry->getValueRange().isSupersetOf(m_valueRange);
129 ConstValueRangeAccess m_valueRange;
135 typedef ValueEntryIterator<IsSamplerEntry> Iterator;
137 IsSamplerEntry (VariableType::Type type)
140 DE_ASSERT(m_type == VariableType::TYPE_SAMPLER_2D || m_type == VariableType::TYPE_SAMPLER_CUBE);
143 bool operator() (const ValueEntry* entry) const
145 if (entry->getVariable()->getType() == VariableType(m_type, 1))
147 DE_ASSERT(entry->getVariable()->getStorage() == Variable::STORAGE_UNIFORM);
155 VariableType::Type m_type;
158 inline bool getWeightedBool (de::Random& random, float trueWeight)
160 DE_ASSERT(de::inRange<float>(trueWeight, 0.0f, 1.0f));
161 return (random.getFloat() < trueWeight);
164 void computeRandomValueRangeForInfElements (GeneratorState& state, ValueRangeAccess valueRange)
166 const VariableType& type = valueRange.getType();
167 de::Random& rnd = state.getRandom();
169 switch (type.getBaseType())
171 case VariableType::TYPE_BOOL:
172 // No need to handle bool as it will be false, true
175 case VariableType::TYPE_INT:
176 for (int ndx = 0; ndx < type.getNumElements(); ndx++)
178 if (valueRange.getMin().component(ndx).asScalar() != Scalar::min<int>() ||
179 valueRange.getMax().component(ndx).asScalar() != Scalar::max<int>())
182 const int minIntVal = -16;
183 const int maxIntVal = 16;
184 const int maxRangeLen = maxIntVal - minIntVal;
186 int rangeLen = rnd.getInt(0, maxRangeLen);
187 int minVal = minIntVal + rnd.getInt(0, maxRangeLen-rangeLen);
188 int maxVal = minVal + rangeLen;
190 valueRange.getMin().component(ndx).asInt() = minVal;
191 valueRange.getMax().component(ndx).asInt() = maxVal;
195 case VariableType::TYPE_FLOAT:
196 for (int ndx = 0; ndx < type.getNumElements(); ndx++)
198 if (valueRange.getMin().component(ndx).asScalar() != Scalar::min<float>() ||
199 valueRange.getMax().component(ndx).asScalar() != Scalar::max<float>())
202 const float step = 0.1f;
203 const int maxSteps = 320;
204 const float minFloatVal = -16.0f;
206 int rangeLen = rnd.getInt(0, maxSteps);
207 int minStep = rnd.getInt(0, maxSteps-rangeLen);
209 float minVal = minFloatVal + step*(float)minStep;
210 float maxVal = minVal + step*(float)rangeLen;
212 valueRange.getMin().component(ndx).asFloat() = minVal;
213 valueRange.getMax().component(ndx).asFloat() = maxVal;
219 throw Exception("computeRandomValueRangeForInfElements(): unsupported type");
223 void setInfiniteRange (ValueRangeAccess valueRange)
225 const VariableType& type = valueRange.getType();
227 switch (type.getBaseType())
229 case VariableType::TYPE_BOOL:
230 for (int ndx = 0; ndx < type.getNumElements(); ndx++)
232 valueRange.getMin().component(ndx) = Scalar::min<bool>();
233 valueRange.getMax().component(ndx) = Scalar::max<bool>();
237 case VariableType::TYPE_INT:
238 for (int ndx = 0; ndx < type.getNumElements(); ndx++)
240 valueRange.getMin().component(ndx) = Scalar::min<int>();
241 valueRange.getMax().component(ndx) = Scalar::max<int>();
245 case VariableType::TYPE_FLOAT:
246 for (int ndx = 0; ndx < type.getNumElements(); ndx++)
248 valueRange.getMin().component(ndx) = Scalar::min<float>();
249 valueRange.getMax().component(ndx) = Scalar::max<float>();
255 throw Exception("setInfiniteRange(): unsupported type");
259 bool canAllocateVariable (const GeneratorState& state, const VariableType& type)
261 DE_ASSERT(!type.isVoid());
263 if (state.getExpressionFlags() & NO_VAR_ALLOCATION)
266 if (state.getVariableManager().getNumAllocatedScalars() + type.getScalarSize() > state.getShaderParameters().maxCombinedVariableScalars)
272 template <class T> float getWeight (const GeneratorState& state, ConstValueRangeAccess valueRange) { return T::getWeight(state, valueRange); }
273 template <class T> Expression* create (GeneratorState& state, ConstValueRangeAccess valueRange) { return new T(state, valueRange); }
275 struct ExpressionSpec
277 float (*getWeight) (const GeneratorState& state, ConstValueRangeAccess valueRange);
278 Expression* (*create) (GeneratorState& state, ConstValueRangeAccess valueRange);
281 static const ExpressionSpec s_expressionSpecs[] =
283 { getWeight<FloatLiteral>, create<FloatLiteral> },
284 { getWeight<IntLiteral>, create<IntLiteral> },
285 { getWeight<BoolLiteral>, create<BoolLiteral> },
286 { getWeight<ConstructorOp>, create<ConstructorOp> },
287 { getWeight<AssignOp>, create<AssignOp> },
288 { getWeight<VariableRead>, create<VariableRead> },
289 { getWeight<MulOp>, create<MulOp> },
290 { getWeight<AddOp>, create<AddOp> },
291 { getWeight<SubOp>, create<SubOp> },
292 { getWeight<LessThanOp>, create<LessThanOp> },
293 { getWeight<LessOrEqualOp>, create<LessOrEqualOp> },
294 { getWeight<GreaterThanOp>, create<GreaterThanOp> },
295 { getWeight<GreaterOrEqualOp>, create<GreaterOrEqualOp> },
296 { getWeight<EqualOp>, create<EqualOp> },
297 { getWeight<NotEqualOp>, create<NotEqualOp> },
298 { getWeight<SwizzleOp>, create<SwizzleOp> },
299 { getWeight<SinOp>, create<SinOp> },
300 { getWeight<CosOp>, create<CosOp> },
301 { getWeight<TanOp>, create<TanOp> },
302 { getWeight<AsinOp>, create<AsinOp> },
303 { getWeight<AcosOp>, create<AcosOp> },
304 { getWeight<AtanOp>, create<AtanOp> },
305 { getWeight<ExpOp>, create<ExpOp> },
306 { getWeight<LogOp>, create<LogOp> },
307 { getWeight<Exp2Op>, create<Exp2Op> },
308 { getWeight<Log2Op>, create<Log2Op> },
309 { getWeight<SqrtOp>, create<SqrtOp> },
310 { getWeight<InvSqrtOp>, create<InvSqrtOp> },
311 { getWeight<ParenOp>, create<ParenOp> },
312 { getWeight<TexLookup>, create<TexLookup> }
315 static const ExpressionSpec s_lvalueSpecs[] =
317 { getWeight<VariableWrite>, create<VariableWrite> }
321 # define DE_MAX(a, b) ((b) > (a) ? (b) : (a))
326 MAX_EXPRESSION_SPECS = (int)DE_MAX(DE_LENGTH_OF_ARRAY(s_expressionSpecs), DE_LENGTH_OF_ARRAY(s_lvalueSpecs))
329 const ExpressionSpec* chooseExpression (GeneratorState& state, const ExpressionSpec* specs, int numSpecs, ConstValueRangeAccess valueRange)
331 float weights[MAX_EXPRESSION_SPECS];
333 DE_ASSERT(numSpecs <= (int)DE_LENGTH_OF_ARRAY(weights));
336 for (int ndx = 0; ndx < numSpecs; ndx++)
337 weights[ndx] = specs[ndx].getWeight(state, valueRange);
340 return &state.getRandom().chooseWeighted<const ExpressionSpec&>(specs, specs+numSpecs, weights);
345 Expression::~Expression (void)
349 Expression* Expression::createRandom (GeneratorState& state, ConstValueRangeAccess valueRange)
351 return chooseExpression(state, s_expressionSpecs, (int)DE_LENGTH_OF_ARRAY(s_expressionSpecs), valueRange)->create(state, valueRange);
354 Expression* Expression::createRandomLValue (GeneratorState& state, ConstValueRangeAccess valueRange)
356 return chooseExpression(state, s_lvalueSpecs, (int)DE_LENGTH_OF_ARRAY(s_lvalueSpecs), valueRange)->create(state, valueRange);
359 FloatLiteral::FloatLiteral (GeneratorState& state, ConstValueRangeAccess valueRange)
360 : m_value(VariableType::getScalarType(VariableType::TYPE_FLOAT))
362 float minVal = -10.0f;
363 float maxVal = +10.0f;
366 if (valueRange.getType() == VariableType(VariableType::TYPE_FLOAT, 1))
368 minVal = valueRange.getMin().component(0).asFloat();
369 maxVal = valueRange.getMax().component(0).asFloat();
371 if (Scalar::min<float>() == minVal)
374 if (Scalar::max<float>() == maxVal)
378 int numSteps = (int)((maxVal-minVal)/step) + 1;
380 const float value = deFloatClamp(minVal + step*(float)state.getRandom().getInt(0, numSteps), minVal, maxVal);
381 ExecValueAccess access = m_value.getValue(VariableType::getScalarType(VariableType::TYPE_FLOAT));
383 for (int ndx = 0; ndx < EXEC_VEC_WIDTH; ndx++)
384 access.asFloat(ndx) = value;
387 float FloatLiteral::getWeight (const GeneratorState& state, ConstValueRangeAccess valueRange)
390 const VariableType& type = valueRange.getType();
391 if (type == VariableType(VariableType::TYPE_FLOAT, 1))
393 float minVal = valueRange.getMin().asFloat();
394 float maxVal = valueRange.getMax().asFloat();
396 if (Scalar::min<float>() == minVal && Scalar::max<float>() == maxVal)
399 // Weight based on value range length
400 float rangeLength = maxVal - minVal;
402 DE_ASSERT(rangeLength >= 0.0f);
403 return deFloatMax(0.1f, 1.0f - rangeLength);
405 else if (type.isVoid())
406 return unusedValueWeight;
411 void FloatLiteral::tokenize (GeneratorState& state, TokenStream& str) const
414 str << Token(m_value.getValue(VariableType::getScalarType(VariableType::TYPE_FLOAT)).asFloat(0));
417 IntLiteral::IntLiteral (GeneratorState& state, ConstValueRangeAccess valueRange)
418 : m_value(VariableType::getScalarType(VariableType::TYPE_INT))
423 if (valueRange.getType() == VariableType(VariableType::TYPE_INT, 1))
425 minVal = valueRange.getMin().component(0).asInt();
426 maxVal = valueRange.getMax().component(0).asInt();
428 if (Scalar::min<int>() == minVal)
431 if (Scalar::max<int>() == maxVal)
435 int value = state.getRandom().getInt(minVal, maxVal);
436 ExecValueAccess access = m_value.getValue(VariableType::getScalarType(VariableType::TYPE_INT));
438 for (int ndx = 0; ndx < EXEC_VEC_WIDTH; ndx++)
439 access.asInt(ndx) = value;
442 float IntLiteral::getWeight (const GeneratorState& state, ConstValueRangeAccess valueRange)
445 const VariableType& type = valueRange.getType();
446 if (type == VariableType(VariableType::TYPE_INT, 1))
448 int minVal = valueRange.getMin().asInt();
449 int maxVal = valueRange.getMax().asInt();
451 if (Scalar::min<int>() == minVal && Scalar::max<int>() == maxVal)
454 int rangeLength = maxVal - minVal;
456 DE_ASSERT(rangeLength >= 0);
457 return deFloatMax(0.1f, 1.0f - (float)rangeLength/4.0f);
459 else if (type.isVoid())
460 return unusedValueWeight;
465 void IntLiteral::tokenize (GeneratorState& state, TokenStream& str) const
468 str << Token(m_value.getValue(VariableType::getScalarType(VariableType::TYPE_INT)).asInt(0));
471 BoolLiteral::BoolLiteral (GeneratorState& state, ConstValueRangeAccess valueRange)
472 : m_value(VariableType::getScalarType(VariableType::TYPE_BOOL))
477 if (valueRange.getType() == VariableType(VariableType::TYPE_BOOL, 1))
479 minVal = valueRange.getMin().component(0).asBool() ? 1 : 0;
480 maxVal = valueRange.getMax().component(0).asBool() ? 1 : 0;
483 bool value = state.getRandom().getInt(minVal, maxVal) == 1;
484 ExecValueAccess access = m_value.getValue(VariableType::getScalarType(VariableType::TYPE_BOOL));
486 for (int ndx = 0; ndx < EXEC_VEC_WIDTH; ndx++)
487 access.asBool(ndx) = value;
490 float BoolLiteral::getWeight (const GeneratorState& state, ConstValueRangeAccess valueRange)
493 const VariableType& type = valueRange.getType();
494 if (type == VariableType(VariableType::TYPE_BOOL, 1))
496 else if (type.isVoid())
497 return unusedValueWeight;
502 void BoolLiteral::tokenize (GeneratorState& state, TokenStream& str) const
505 str << Token(m_value.getValue(VariableType::getScalarType(VariableType::TYPE_BOOL)).asBool(0));
511 // \note int-bool and float-bool conversions handled in a special way.
512 template <typename SrcType, typename DstType>
513 inline DstType convert (SrcType src)
515 if (Scalar::min<SrcType>() == src)
516 return Scalar::min<DstType>().template as<DstType>();
517 else if (Scalar::max<SrcType>() == src)
518 return Scalar::max<DstType>().template as<DstType>();
523 // According to GLSL ES spec.
524 template <> inline bool convert<float, bool> (float src) { return src != 0.0f; }
525 template <> inline bool convert<int, bool> (int src) { return src != 0; }
526 template <> inline bool convert<bool, bool> (bool src) { return src; }
527 template <> inline float convert<bool, float> (bool src) { return src ? 1.0f : 0.0f; }
528 template <> inline int convert<bool, int> (bool src) { return src ? 1 : 0; }
530 template <> inline int convert<float, int> (float src)
532 if (Scalar::min<float>() == src)
533 return Scalar::min<int>().as<int>();
534 else if (Scalar::max<float>() == src)
535 return Scalar::max<int>().as<int>();
537 return (int)deFloatFloor(src);
539 return (int)deFloatCeil(src);
542 template <typename SrcType, typename DstType>
543 inline void convertValueRange (SrcType srcMin, SrcType srcMax, DstType& dstMin, DstType& dstMax)
545 dstMin = convert<SrcType, DstType>(srcMin);
546 dstMax = convert<SrcType, DstType>(srcMax);
550 inline void convertValueRange<float, int> (float srcMin, float srcMax, int& dstMin, int& dstMax)
552 if (Scalar::min<float>() == srcMin)
553 dstMin = Scalar::min<int>().as<int>();
555 dstMin = (int)deFloatCeil(srcMin);
557 if (Scalar::max<float>() == srcMax)
558 dstMax = Scalar::max<int>().as<int>();
560 dstMax = (int)deFloatFloor(srcMax);
564 inline void convertValueRange<float, bool> (float srcMin, float srcMax, bool& dstMin, bool& dstMax)
566 dstMin = srcMin > 0.0f;
567 dstMax = srcMax > 0.0f;
570 // \todo [pyry] More special cases?
572 // Returns whether it is possible to convert some SrcType value range to given DstType valueRange
573 template <typename SrcType, typename DstType>
574 bool isConversionOk (DstType min, DstType max)
577 convertValueRange(min, max, sMin, sMax);
578 return sMin <= sMax &&
579 de::inRange(convert<SrcType, DstType>(sMin), min, max) &&
580 de::inRange(convert<SrcType, DstType>(sMax), min, max);
583 // Work-around for non-deterministic float behavior
584 template <> bool isConversionOk<float, float> (float, float) { return true; }
586 // \todo [2011-03-26 pyry] Provide this in ValueAccess?
587 template <typename T> T getValueAccessValue (ConstValueAccess access);
588 template<> inline float getValueAccessValue<float> (ConstValueAccess access) { return access.asFloat(); }
589 template<> inline int getValueAccessValue<int> (ConstValueAccess access) { return access.asInt(); }
590 template<> inline bool getValueAccessValue<bool> (ConstValueAccess access) { return access.asBool(); }
592 template <typename T> T& getValueAccessValue (ValueAccess access);
593 template<> inline float& getValueAccessValue<float> (ValueAccess access) { return access.asFloat(); }
594 template<> inline int& getValueAccessValue<int> (ValueAccess access) { return access.asInt(); }
595 template<> inline bool& getValueAccessValue<bool> (ValueAccess access) { return access.asBool(); }
597 template <typename SrcType, typename DstType>
598 bool isConversionOk (ConstValueRangeAccess valueRange)
600 return isConversionOk<SrcType>(getValueAccessValue<DstType>(valueRange.getMin()), getValueAccessValue<DstType>(valueRange.getMax()));
603 template <typename SrcType, typename DstType>
604 void convertValueRangeTempl (ConstValueRangeAccess src, ValueRangeAccess dst)
607 convertValueRange(getValueAccessValue<SrcType>(src.getMin()), getValueAccessValue<SrcType>(src.getMax()), dMin, dMax);
608 getValueAccessValue<DstType>(dst.getMin()) = dMin;
609 getValueAccessValue<DstType>(dst.getMax()) = dMax;
612 template <typename SrcType, typename DstType>
613 void convertExecValueTempl (ExecConstValueAccess src, ExecValueAccess dst)
615 for (int ndx = 0; ndx < EXEC_VEC_WIDTH; ndx++)
616 dst.as<DstType>(ndx) = convert<SrcType, DstType>(src.as<SrcType>(ndx));
619 typedef bool (*IsConversionOkFunc) (ConstValueRangeAccess);
620 typedef void (*ConvertValueRangeFunc) (ConstValueRangeAccess, ValueRangeAccess);
621 typedef void (*ConvertExecValueFunc) (ExecConstValueAccess, ExecValueAccess);
623 inline int getBaseTypeConvNdx (VariableType::Type type)
627 case VariableType::TYPE_FLOAT: return 0;
628 case VariableType::TYPE_INT: return 1;
629 case VariableType::TYPE_BOOL: return 2;
634 bool isConversionOk (VariableType::Type srcType, VariableType::Type dstType, ConstValueRangeAccess valueRange)
637 static const IsConversionOkFunc convTable[3][3] =
639 { isConversionOk<float, float>, isConversionOk<float, int>, isConversionOk<float, bool> },
640 { isConversionOk<int, float>, isConversionOk<int, int>, isConversionOk<int, bool> },
641 { isConversionOk<bool, float>, isConversionOk<bool, int>, isConversionOk<bool, bool> }
643 return convTable[getBaseTypeConvNdx(srcType)][getBaseTypeConvNdx(dstType)](valueRange);
646 void convertValueRange (ConstValueRangeAccess src, ValueRangeAccess dst)
649 static const ConvertValueRangeFunc convTable[3][3] =
651 { convertValueRangeTempl<float, float>, convertValueRangeTempl<float, int>, convertValueRangeTempl<float, bool> },
652 { convertValueRangeTempl<int, float>, convertValueRangeTempl<int, int>, convertValueRangeTempl<int, bool> },
653 { convertValueRangeTempl<bool, float>, convertValueRangeTempl<bool, int>, convertValueRangeTempl<bool, bool> }
656 convTable[getBaseTypeConvNdx(src.getType().getBaseType())][getBaseTypeConvNdx(dst.getType().getBaseType())](src, dst);
659 void convertExecValue (ExecConstValueAccess src, ExecValueAccess dst)
662 static const ConvertExecValueFunc convTable[3][3] =
664 { convertExecValueTempl<float, float>, convertExecValueTempl<float, int>, convertExecValueTempl<float, bool> },
665 { convertExecValueTempl<int, float>, convertExecValueTempl<int, int>, convertExecValueTempl<int, bool> },
666 { convertExecValueTempl<bool, float>, convertExecValueTempl<bool, int>, convertExecValueTempl<bool, bool> }
669 convTable[getBaseTypeConvNdx(src.getType().getBaseType())][getBaseTypeConvNdx(dst.getType().getBaseType())](src, dst);
674 ConstructorOp::ConstructorOp (GeneratorState& state, ConstValueRangeAccess valueRange)
675 : m_valueRange(valueRange)
677 if (valueRange.getType().isVoid())
680 const int maxScalars = 4; // We don't have to be able to assign this value to anywhere
681 m_valueRange = ValueRange(computeRandomType(state, maxScalars));
682 computeRandomValueRange(state, m_valueRange.asAccess());
685 // \todo [2011-03-26 pyry] Vector conversions
686 // int remainingDepth = state.getShaderParameters().maxExpressionDepth - state.getExpressionDepth();
688 const VariableType& type = m_valueRange.getType();
689 VariableType::Type baseType = type.getBaseType();
690 int numScalars = type.getNumElements();
691 int curScalarNdx = 0;
693 // \todo [2011-03-26 pyry] Separate op for struct constructors!
694 DE_ASSERT(type.isFloatOrVec() || type.isIntOrVec() || type.isBoolOrVec());
696 bool scalarConversions = state.getProgramParameters().useScalarConversions;
698 while (curScalarNdx < numScalars)
700 ConstValueRangeAccess comp = m_valueRange.asAccess().component(curScalarNdx);
702 if (scalarConversions)
705 VariableType::Type inTypes[3];
707 if (isConversionOk(VariableType::TYPE_FLOAT, baseType, comp)) inTypes[numInTypes++] = VariableType::TYPE_FLOAT;
708 if (isConversionOk(VariableType::TYPE_INT, baseType, comp)) inTypes[numInTypes++] = VariableType::TYPE_INT;
709 if (isConversionOk(VariableType::TYPE_BOOL, baseType, comp)) inTypes[numInTypes++] = VariableType::TYPE_BOOL;
711 DE_ASSERT(numInTypes > 0); // At least nop conversion should be ok
714 VariableType::Type inType = state.getRandom().choose<VariableType::Type>(&inTypes[0], &inTypes[0] + numInTypes);
716 // Compute converted value range
717 ValueRange inValueRange(VariableType(inType, 1));
718 convertValueRange(comp, inValueRange);
719 m_inputValueRanges.push_back(inValueRange);
725 m_inputValueRanges.push_back(ValueRange(comp));
731 ConstructorOp::~ConstructorOp (void)
733 for (vector<Expression*>::iterator i = m_inputExpressions.begin(); i != m_inputExpressions.end(); i++)
737 Expression* ConstructorOp::createNextChild (GeneratorState& state)
739 int numChildren = (int)m_inputExpressions.size();
740 Expression* child = DE_NULL;
742 // \note Created in reverse order!
743 if (numChildren < (int)m_inputValueRanges.size())
745 const ValueRange& inValueRange = m_inputValueRanges[m_inputValueRanges.size()-1-numChildren];
746 child = Expression::createRandom(state, inValueRange);
749 m_inputExpressions.push_back(child);
751 catch (const std::exception&)
761 float ConstructorOp::getWeight (const GeneratorState& state, ConstValueRangeAccess valueRange)
763 if (valueRange.getType().isVoid())
764 return unusedValueWeight;
766 if (!valueRange.getType().isFloatOrVec() && !valueRange.getType().isIntOrVec() && !valueRange.getType().isBoolOrVec())
769 if (state.getExpressionDepth() + getTypeConstructorDepth(valueRange.getType()) > state.getShaderParameters().maxExpressionDepth)
775 void ConstructorOp::tokenize (GeneratorState& state, TokenStream& str) const
777 const VariableType& type = m_valueRange.getType();
778 DE_ASSERT(type.getPrecision() == VariableType::PRECISION_NONE);
779 type.tokenizeShortType(str);
781 str << Token::LEFT_PAREN;
783 for (vector<Expression*>::const_reverse_iterator i = m_inputExpressions.rbegin(); i != m_inputExpressions.rend(); i++)
785 if (i != m_inputExpressions.rbegin())
787 (*i)->tokenize(state, str);
790 str << Token::RIGHT_PAREN;
793 void ConstructorOp::evaluate (ExecutionContext& evalCtx)
796 for (vector<Expression*>::reverse_iterator i = m_inputExpressions.rbegin(); i != m_inputExpressions.rend(); i++)
797 (*i)->evaluate(evalCtx);
800 const VariableType& type = m_valueRange.getType();
801 m_value.setStorage(type);
803 ExecValueAccess dst = m_value.getValue(type);
804 int curScalarNdx = 0;
806 for (vector<Expression*>::reverse_iterator i = m_inputExpressions.rbegin(); i != m_inputExpressions.rend(); i++)
808 ExecConstValueAccess src = (*i)->getValue();
810 for (int elemNdx = 0; elemNdx < src.getType().getNumElements(); elemNdx++)
811 convertExecValue(src.component(elemNdx), dst.component(curScalarNdx++));
815 AssignOp::AssignOp (GeneratorState& state, ConstValueRangeAccess valueRange)
816 : m_valueRange (valueRange)
817 , m_lvalueExpr (DE_NULL)
818 , m_rvalueExpr (DE_NULL)
820 if (m_valueRange.getType().isVoid())
822 // Compute random value range
823 int maxScalars = state.getShaderParameters().maxCombinedVariableScalars - state.getVariableManager().getNumAllocatedScalars();
824 bool useRandomRange = !state.getVariableManager().hasEntry<IsWritableEntry>() || ((maxScalars > 0) && getWeightedBool(state.getRandom(), 0.1f));
828 DE_ASSERT(maxScalars > 0);
829 m_valueRange = ValueRange(computeRandomType(state, maxScalars));
830 computeRandomValueRange(state, m_valueRange.asAccess());
834 // Use value range from random entry
835 // \todo [2011-02-28 pyry] Give lower weight to entries without range? Choose subtype range?
836 const ValueEntry* entry = state.getRandom().choose<const ValueEntry*>(state.getVariableManager().getBegin<IsWritableEntry>(), state.getVariableManager().getEnd<IsWritableEntry>());
837 m_valueRange = ValueRange(entry->getValueRange());
839 computeRandomValueRangeForInfElements(state, m_valueRange.asAccess());
841 DE_ASSERT(state.getVariableManager().hasEntry(IsWritableIntersectingEntry(m_valueRange.asAccess())));
845 IsWritableIntersectingEntry::Iterator first = state.getVariableManager().getBegin(IsWritableIntersectingEntry(m_valueRange.asAccess()));
846 IsWritableIntersectingEntry::Iterator end = state.getVariableManager().getEnd(IsWritableIntersectingEntry(m_valueRange.asAccess()));
848 bool possiblyCreateVar = canAllocateVariable(state, m_valueRange.getType()) &&
849 (first == end || getWeightedBool(state.getRandom(), 0.5f));
851 if (!possiblyCreateVar)
853 // Find all possible valueranges matching given type and intersecting with valuerange
854 // \todo [pyry] Actually collect all ValueRanges, currently operates only on whole variables
855 DE_ASSERT(first != end);
857 // Try to select one closest to given range but bigger (eg. superset)
858 bool supersetExists = false;
859 for (IsWritableIntersectingEntry::Iterator i = first; i != end; i++)
861 if ((*i)->getValueRange().isSupersetOf(m_valueRange.asAccess()))
863 supersetExists = true;
870 // Select some other range and compute intersection
871 // \todo [2011-02-03 pyry] Use some heuristics to select the range?
872 ConstValueRangeAccess selectedRange = state.getRandom().choose<const ValueEntry*>(first, end)->getValueRange();
874 ValueRange::computeIntersection(m_valueRange.asAccess(), m_valueRange.asAccess(), selectedRange);
879 AssignOp::~AssignOp (void)
885 float AssignOp::getWeight (const GeneratorState& state, ConstValueRangeAccess valueRange)
887 if (!valueRange.getType().isVoid() &&
888 !canAllocateVariable(state, valueRange.getType()) &&
889 !state.getVariableManager().hasEntry(IsWritableIntersectingEntry(valueRange)))
890 return 0.0f; // Would require creating a new variable
892 if (!valueRange.getType().isVoid() && state.getExpressionDepth() + getTypeConstructorDepth(valueRange.getType()) + 1 >= state.getShaderParameters().maxExpressionDepth)
895 if (valueRange.getType().isVoid() &&
896 !state.getVariableManager().hasEntry<IsWritableEntry>() &&
897 state.getVariableManager().getNumAllocatedScalars() >= state.getShaderParameters().maxCombinedVariableScalars)
898 return 0.0f; // Can not allocate a new entry
900 if (state.getExpressionDepth() == 0)
903 return 0.0f; // \todo [pyry] Fix assign ops
906 Expression* AssignOp::createNextChild (GeneratorState& state)
908 if (m_lvalueExpr == DE_NULL)
911 // \todo [2011-03-14 pyry] Proper l-value generation:
912 // - pure L-value part is generated first
913 // - variable valuerange is made unbound
914 // - R-value is generated
915 // - R-values in L-value are generated
916 m_lvalueExpr = Expression::createRandomLValue(state, m_valueRange.asAccess());
919 else if (m_rvalueExpr == DE_NULL)
921 // Construct value expr
922 m_rvalueExpr = Expression::createRandom(state, m_valueRange.asAccess());
929 void AssignOp::tokenize (GeneratorState& state, TokenStream& str) const
931 m_lvalueExpr->tokenize(state, str);
933 m_rvalueExpr->tokenize(state, str);
936 void AssignOp::evaluate (ExecutionContext& evalCtx)
939 m_lvalueExpr->evaluate(evalCtx);
942 m_rvalueExpr->evaluate(evalCtx);
943 m_value.setStorage(m_valueRange.getType());
944 m_value.getValue(m_valueRange.getType()) = m_rvalueExpr->getValue().value();
947 assignMasked(m_lvalueExpr->getLValue(), m_value.getValue(m_valueRange.getType()), evalCtx.getExecutionMask());
953 inline bool isShaderInOutSupportedType (const VariableType& type)
955 // \todo [2011-03-11 pyry] Float arrays, structs?
956 return type.getBaseType() == VariableType::TYPE_FLOAT;
959 Variable* allocateNewVariable (GeneratorState& state, ConstValueRangeAccess valueRange)
961 Variable* variable = state.getVariableManager().allocate(valueRange.getType());
963 // Update value range
964 state.getVariableManager().setValue(variable, valueRange);
966 // Random storage \todo [pyry] Check that scalar count in uniform/input classes is not exceeded
967 static const Variable::Storage storages[] =
969 Variable::STORAGE_CONST,
970 Variable::STORAGE_UNIFORM,
971 Variable::STORAGE_LOCAL,
972 Variable::STORAGE_SHADER_IN
974 float weights[DE_LENGTH_OF_ARRAY(storages)];
976 // Dynamic vs. constant weight.
977 float dynWeight = computeDynamicRangeWeight(valueRange);
978 int numScalars = valueRange.getType().getScalarSize();
979 bool uniformOk = state.getVariableManager().getNumAllocatedUniformScalars() + numScalars <= state.getShaderParameters().maxUniformScalars;
980 bool shaderInOk = isShaderInOutSupportedType(valueRange.getType()) &&
981 (state.getVariableManager().getNumAllocatedShaderInVariables() + NUM_RESERVED_SHADER_INPUTS < state.getShaderParameters().maxInputVariables);
983 weights[0] = de::max(1.0f-dynWeight, 0.1f);
984 weights[1] = uniformOk ? dynWeight*0.5f : 0.0f;
985 weights[2] = dynWeight;
986 weights[3] = shaderInOk ? dynWeight*2.0f : 0.0f;
988 state.getVariableManager().setStorage(variable, state.getRandom().chooseWeighted<Variable::Storage>(&storages[0], &storages[DE_LENGTH_OF_ARRAY(storages)], &weights[0]));
993 inline float combineWeight (float curCombinedWeight, float partialWeight)
995 return curCombinedWeight * partialWeight;
998 float computeEntryReadWeight (ConstValueRangeAccess entryValueRange, ConstValueRangeAccess readValueRange)
1000 const VariableType& type = entryValueRange.getType();
1001 DE_ASSERT(type == readValueRange.getType());
1003 float weight = 1.0f;
1005 switch (type.getBaseType())
1007 case VariableType::TYPE_FLOAT:
1009 for (int elemNdx = 0; elemNdx < type.getNumElements(); elemNdx++)
1011 float entryMin = entryValueRange.component(elemNdx).getMin().asFloat();
1012 float entryMax = entryValueRange.component(elemNdx).getMax().asFloat();
1013 float readMin = readValueRange.component(elemNdx).getMin().asFloat();
1014 float readMax = readValueRange.component(elemNdx).getMax().asFloat();
1016 // Check for -inf..inf ranges - they don't bring down the weight.
1017 if (Scalar::min<float>() == entryMin && Scalar::max<float>() == entryMax)
1020 // Intersection to entry value range length ratio.
1021 float intersectionMin = deFloatMax(entryMin, readMin);
1022 float intersectionMax = deFloatMin(entryMax, readMax);
1023 float entryRangeLen = entryMax - entryMin;
1024 float readRangeLen = readMax - readMin;
1025 float intersectionLen = intersectionMax - intersectionMin;
1026 float entryRatio = (entryRangeLen > 0.0f) ? (intersectionLen / entryRangeLen) : 1.0f;
1027 float readRatio = (readRangeLen > 0.0f) ? (intersectionLen / readRangeLen) : 1.0f;
1028 float elementWeight = 0.5f*readRatio + 0.5f*entryRatio;
1030 weight = combineWeight(weight, elementWeight);
1035 case VariableType::TYPE_INT:
1037 for (int elemNdx = 0; elemNdx < type.getNumElements(); elemNdx++)
1039 int entryMin = entryValueRange.component(elemNdx).getMin().asInt();
1040 int entryMax = entryValueRange.component(elemNdx).getMax().asInt();
1041 int readMin = readValueRange.component(elemNdx).getMin().asInt();
1042 int readMax = readValueRange.component(elemNdx).getMax().asInt();
1044 // Check for -inf..inf ranges - they don't bring down the weight.
1045 if (Scalar::min<int>() == entryMin && Scalar::max<int>() == entryMax)
1048 // Intersection to entry value range length ratio.
1049 int intersectionMin = deMax32(entryMin, readMin);
1050 int intersectionMax = deMin32(entryMax, readMax);
1051 deInt64 entryRangeLen = (deInt64)entryMax - (deInt64)entryMin;
1052 deInt64 readRangeLen = (deInt64)readMax - (deInt64)readMin;
1053 deInt64 intersectionLen = (deInt64)intersectionMax - (deInt64)intersectionMin;
1054 float entryRatio = (entryRangeLen > 0) ? ((float)intersectionLen / (float)entryRangeLen) : 1.0f;
1055 float readRatio = (readRangeLen > 0) ? ((float)intersectionLen / (float)readRangeLen) : 1.0f;
1056 float elementWeight = 0.5f*readRatio + 0.5f*entryRatio;
1058 weight = combineWeight(weight, elementWeight);
1063 case VariableType::TYPE_BOOL:
1070 case VariableType::TYPE_ARRAY:
1071 case VariableType::TYPE_STRUCT:
1074 TCU_FAIL("Unsupported type");
1077 return deFloatMax(weight, 0.01f);
1082 VariableRead::VariableRead (GeneratorState& state, ConstValueRangeAccess valueRange)
1084 if (valueRange.getType().isVoid())
1086 IsReadableEntry filter = IsReadableEntry(state.getExpressionFlags());
1087 int maxScalars = state.getShaderParameters().maxCombinedVariableScalars - state.getVariableManager().getNumAllocatedScalars();
1088 bool useRandomRange = !state.getVariableManager().hasEntry(filter) || ((maxScalars > 0) && getWeightedBool(state.getRandom(), 0.5f));
1092 // Allocate a new variable
1093 DE_ASSERT(maxScalars > 0);
1094 ValueRange newVarRange(computeRandomType(state, maxScalars));
1095 computeRandomValueRange(state, newVarRange.asAccess());
1097 m_variable = allocateNewVariable(state, newVarRange.asAccess());
1101 // Use random entry \todo [pyry] Handle -inf..inf ranges?
1102 m_variable = state.getRandom().choose<const ValueEntry*>(state.getVariableManager().getBegin(filter), state.getVariableManager().getEnd(filter))->getVariable();
1107 // Find variable that has value range that intersects with given range
1108 IsReadableIntersectingEntry::Iterator first = state.getVariableManager().getBegin(IsReadableIntersectingEntry(valueRange, state.getExpressionFlags()));
1109 IsReadableIntersectingEntry::Iterator end = state.getVariableManager().getEnd(IsReadableIntersectingEntry(valueRange, state.getExpressionFlags()));
1111 const float createOnReadWeight = 0.5f;
1112 bool createVar = canAllocateVariable(state, valueRange.getType()) && (first == end || getWeightedBool(state.getRandom(), createOnReadWeight));
1116 m_variable = allocateNewVariable(state, valueRange);
1120 // Copy value entries for computing weights.
1121 std::vector<const ValueEntry*> availableVars;
1122 std::vector<float> weights;
1124 std::copy(first, end, std::inserter(availableVars, availableVars.begin()));
1127 weights.resize(availableVars.size());
1128 for (int ndx = 0; ndx < (int)availableVars.size(); ndx++)
1129 weights[ndx] = computeEntryReadWeight(availableVars[ndx]->getValueRange(), valueRange);
1132 const ValueEntry* entry = state.getRandom().chooseWeighted<const ValueEntry*>(availableVars.begin(), availableVars.end(), weights.begin());
1133 m_variable = entry->getVariable();
1135 // Compute intersection
1136 ValueRange intersection(m_variable->getType());
1137 ValueRange::computeIntersection(intersection, entry->getValueRange(), valueRange);
1138 state.getVariableManager().setValue(m_variable, intersection.asAccess());
1143 VariableRead::VariableRead (const Variable* variable)
1145 m_variable = variable;
1148 float VariableRead::getWeight (const GeneratorState& state, ConstValueRangeAccess valueRange)
1150 if (valueRange.getType().isVoid())
1152 if (state.getVariableManager().hasEntry(IsReadableEntry(state.getExpressionFlags())) ||
1153 state.getVariableManager().getNumAllocatedScalars() < state.getShaderParameters().maxCombinedVariableScalars)
1154 return unusedValueWeight;
1159 if (!canAllocateVariable(state, valueRange.getType()) &&
1160 !state.getVariableManager().hasEntry(IsReadableIntersectingEntry(valueRange, state.getExpressionFlags())))
1166 VariableWrite::VariableWrite (GeneratorState& state, ConstValueRangeAccess valueRange)
1168 DE_ASSERT(!valueRange.getType().isVoid());
1170 // Find variable with range that is superset of given range
1171 IsWritableSupersetEntry::Iterator first = state.getVariableManager().getBegin(IsWritableSupersetEntry(valueRange));
1172 IsWritableSupersetEntry::Iterator end = state.getVariableManager().getEnd(IsWritableSupersetEntry(valueRange));
1174 const float createOnAssignWeight = 0.1f; // Will essentially create an unused variable
1175 bool createVar = canAllocateVariable(state, valueRange.getType()) && (first == end || getWeightedBool(state.getRandom(), createOnAssignWeight));
1179 m_variable = state.getVariableManager().allocate(valueRange.getType());
1180 // \note Storage will be LOCAL
1185 DE_ASSERT(first != end);
1186 const ValueEntry* entry = state.getRandom().choose<const ValueEntry*>(first, end);
1187 m_variable = entry->getVariable();
1190 DE_ASSERT(m_variable);
1192 // Reset value range.
1193 const ValueEntry* parentEntry = state.getVariableManager().getParentValue(m_variable);
1196 // Use parent value range.
1197 state.getVariableManager().setValue(m_variable, parentEntry->getValueRange());
1201 // Use infinite range.
1202 ValueRange infRange(m_variable->getType());
1203 setInfiniteRange(infRange);
1205 state.getVariableManager().setValue(m_variable, infRange.asAccess());
1209 float VariableWrite::getWeight (const GeneratorState& state, ConstValueRangeAccess valueRange)
1211 if (!canAllocateVariable(state, valueRange.getType()) &&
1212 !state.getVariableManager().hasEntry(IsWritableSupersetEntry(valueRange)))
1218 void VariableAccess::evaluate (ExecutionContext& evalCtx)
1220 m_valueAccess = evalCtx.getValue(m_variable);
1223 ParenOp::ParenOp (GeneratorState& state, ConstValueRangeAccess valueRange)
1224 : m_valueRange (valueRange)
1230 ParenOp::~ParenOp (void)
1235 Expression* ParenOp::createNextChild (GeneratorState& state)
1237 if (m_child == DE_NULL)
1239 m_child = Expression::createRandom(state, m_valueRange.asAccess());
1246 void ParenOp::tokenize (GeneratorState& state, TokenStream& str) const
1248 str << Token::LEFT_PAREN;
1249 m_child->tokenize(state, str);
1250 str << Token::RIGHT_PAREN;
1253 float ParenOp::getWeight (const GeneratorState& state, ConstValueRangeAccess valueRange)
1255 if (valueRange.getType().isVoid())
1256 return state.getExpressionDepth() + 2 <= state.getShaderParameters().maxExpressionDepth ? unusedValueWeight : 0.0f;
1259 int requiredDepth = 1 + getConservativeValueExprDepth(state, valueRange);
1260 return state.getExpressionDepth() + requiredDepth <= state.getShaderParameters().maxExpressionDepth ? 1.0f : 0.0f;
1264 const int swizzlePrecedence = 2;
1266 SwizzleOp::SwizzleOp (GeneratorState& state, ConstValueRangeAccess valueRange)
1267 : m_outValueRange (valueRange)
1268 , m_numInputElements (0)
1271 DE_ASSERT(!m_outValueRange.getType().isVoid()); // \todo [2011-06-13 pyry] Void support
1272 DE_ASSERT(m_outValueRange.getType().isFloatOrVec() ||
1273 m_outValueRange.getType().isIntOrVec() ||
1274 m_outValueRange.getType().isBoolOrVec());
1276 m_value.setStorage(m_outValueRange.getType());
1278 int numOutputElements = m_outValueRange.getType().getNumElements();
1280 // \note Swizzle works for vector types only.
1281 // \todo [2011-06-13 pyry] Use components multiple times.
1282 m_numInputElements = state.getRandom().getInt(deMax32(numOutputElements, 2), 4);
1284 std::set<int> availableElements;
1285 for (int ndx = 0; ndx < m_numInputElements; ndx++)
1286 availableElements.insert(ndx);
1288 // Randomize swizzle.
1289 for (int elemNdx = 0; elemNdx < (int)DE_LENGTH_OF_ARRAY(m_swizzle); elemNdx++)
1291 if (elemNdx < numOutputElements)
1293 int inElemNdx = state.getRandom().choose<int>(availableElements.begin(), availableElements.end());
1294 availableElements.erase(inElemNdx);
1295 m_swizzle[elemNdx] = (deUint8)inElemNdx;
1298 m_swizzle[elemNdx] = 0;
1302 SwizzleOp::~SwizzleOp (void)
1307 Expression* SwizzleOp::createNextChild (GeneratorState& state)
1312 // Compute input value range.
1313 VariableType inVarType = VariableType(m_outValueRange.getType().getBaseType(), m_numInputElements);
1314 ValueRange inValueRange = ValueRange(inVarType);
1316 // Initialize all inputs to -inf..inf
1317 setInfiniteRange(inValueRange);
1319 // Compute intersections.
1320 int numOutputElements = m_outValueRange.getType().getNumElements();
1321 for (int outElemNdx = 0; outElemNdx < numOutputElements; outElemNdx++)
1323 int inElemNdx = m_swizzle[outElemNdx];
1324 ValueRange::computeIntersection(inValueRange.asAccess().component(inElemNdx), inValueRange.asAccess().component(inElemNdx), m_outValueRange.asAccess().component(outElemNdx));
1328 state.pushPrecedence(swizzlePrecedence);
1329 m_child = Expression::createRandom(state, inValueRange.asAccess());
1330 state.popPrecedence();
1335 void SwizzleOp::tokenize (GeneratorState& state, TokenStream& str) const
1337 const char* rgbaSet[] = { "r", "g", "b", "a" };
1338 const char* xyzwSet[] = { "x", "y", "z", "w" };
1339 const char* stpqSet[] = { "s", "t", "p", "q" };
1340 const char** swizzleSet = DE_NULL;
1342 switch (state.getRandom().getInt(0, 2))
1344 case 0: swizzleSet = rgbaSet; break;
1345 case 1: swizzleSet = xyzwSet; break;
1346 case 2: swizzleSet = stpqSet; break;
1347 default: DE_ASSERT(DE_FALSE);
1350 std::string swizzleStr;
1351 for (int elemNdx = 0; elemNdx < m_outValueRange.getType().getNumElements(); elemNdx++)
1352 swizzleStr += swizzleSet[m_swizzle[elemNdx]];
1354 m_child->tokenize(state, str);
1355 str << Token::DOT << Token(swizzleStr.c_str());
1358 float SwizzleOp::getWeight (const GeneratorState& state, ConstValueRangeAccess valueRange)
1360 if (!state.getProgramParameters().useSwizzle)
1363 if (state.getPrecedence() < swizzlePrecedence)
1366 if (!valueRange.getType().isFloatOrVec() &&
1367 !valueRange.getType().isIntOrVec() &&
1368 !valueRange.getType().isBoolOrVec())
1371 int availableLevels = state.getShaderParameters().maxExpressionDepth - state.getExpressionDepth();
1373 // Swizzle + Constructor + Values
1374 if (availableLevels < 3)
1380 void SwizzleOp::evaluate (ExecutionContext& execCtx)
1382 m_child->evaluate(execCtx);
1384 ExecConstValueAccess inValue = m_child->getValue();
1385 ExecValueAccess outValue = m_value.getValue(m_outValueRange.getType());
1387 for (int outElemNdx = 0; outElemNdx < outValue.getType().getNumElements(); outElemNdx++)
1389 int inElemNdx = m_swizzle[outElemNdx];
1390 outValue.component(outElemNdx) = inValue.component(inElemNdx).value();
1394 static int countSamplers (const VariableManager& varManager, VariableType::Type samplerType)
1396 int numSamplers = 0;
1398 IsSamplerEntry::Iterator i = varManager.getBegin(IsSamplerEntry(samplerType));
1399 IsSamplerEntry::Iterator end = varManager.getEnd(IsSamplerEntry(samplerType));
1401 for (; i != end; i++)
1407 TexLookup::TexLookup (GeneratorState& state, ConstValueRangeAccess valueRange)
1408 : m_type (TYPE_LAST)
1409 , m_coordExpr (DE_NULL)
1410 , m_lodBiasExpr (DE_NULL)
1411 , m_valueType (VariableType::TYPE_FLOAT, 4)
1412 , m_value (m_valueType)
1414 DE_ASSERT(valueRange.getType() == VariableType(VariableType::TYPE_FLOAT, 4));
1415 DE_UNREF(valueRange); // Texture output value range is constant.
1418 vector<Type> typeCandidates;
1419 if (state.getShaderParameters().useTexture2D)
1421 typeCandidates.push_back(TYPE_TEXTURE2D);
1422 typeCandidates.push_back(TYPE_TEXTURE2D_LOD);
1423 typeCandidates.push_back(TYPE_TEXTURE2D_PROJ);
1424 typeCandidates.push_back(TYPE_TEXTURE2D_PROJ_LOD);
1427 if (state.getShaderParameters().useTextureCube)
1429 typeCandidates.push_back(TYPE_TEXTURECUBE);
1430 typeCandidates.push_back(TYPE_TEXTURECUBE_LOD);
1433 m_type = state.getRandom().choose<Type>(typeCandidates.begin(), typeCandidates.end());
1435 // Select or allocate sampler.
1436 VariableType::Type samplerType = VariableType::TYPE_LAST;
1439 case TYPE_TEXTURE2D:
1440 case TYPE_TEXTURE2D_LOD:
1441 case TYPE_TEXTURE2D_PROJ:
1442 case TYPE_TEXTURE2D_PROJ_LOD:
1443 samplerType = VariableType::TYPE_SAMPLER_2D;
1446 case TYPE_TEXTURECUBE:
1447 case TYPE_TEXTURECUBE_LOD:
1448 samplerType = VariableType::TYPE_SAMPLER_CUBE;
1452 DE_ASSERT(DE_FALSE);
1455 int sampler2DCount = countSamplers(state.getVariableManager(), VariableType::TYPE_SAMPLER_2D);
1456 int samplerCubeCount = countSamplers(state.getVariableManager(), VariableType::TYPE_SAMPLER_CUBE);
1457 bool canAllocSampler = sampler2DCount + samplerCubeCount < state.getShaderParameters().maxSamplers;
1458 bool hasSampler = samplerType == VariableType::TYPE_SAMPLER_2D ? (sampler2DCount > 0) : (samplerCubeCount > 0);
1459 bool allocSampler = !hasSampler || (canAllocSampler && state.getRandom().getBool());
1463 Variable* sampler = state.getVariableManager().allocate(VariableType(samplerType, 1));
1464 state.getVariableManager().setStorage(sampler, Variable::STORAGE_UNIFORM); // Samplers are always uniforms.
1465 m_sampler = sampler;
1468 m_sampler = state.getRandom().choose<const ValueEntry*>(state.getVariableManager().getBegin(IsSamplerEntry(samplerType)),
1469 state.getVariableManager().getEnd(IsSamplerEntry(samplerType)))->getVariable();
1472 TexLookup::~TexLookup (void)
1475 delete m_lodBiasExpr;
1478 Expression* TexLookup::createNextChild (GeneratorState& state)
1480 bool hasLodBias = m_type == TYPE_TEXTURE2D_LOD ||
1481 m_type == TYPE_TEXTURE2D_PROJ_LOD ||
1482 m_type == TYPE_TEXTURECUBE_LOD;
1484 if (hasLodBias && !m_lodBiasExpr)
1486 ValueRange lodRange(VariableType(VariableType::TYPE_FLOAT, 1));
1487 setInfiniteRange(lodRange); // Any value is valid.
1489 m_lodBiasExpr = Expression::createRandom(state, lodRange.asAccess());
1490 return m_lodBiasExpr;
1495 if (m_type == TYPE_TEXTURECUBE || m_type == TYPE_TEXTURECUBE_LOD)
1497 // Make sure major axis selection can be done.
1498 int majorAxisNdx = state.getRandom().getInt(0, 2);
1500 ValueRange coordRange(VariableType(VariableType::TYPE_FLOAT, 3));
1502 for (int ndx = 0; ndx < 3; ndx++)
1504 if (ndx == majorAxisNdx)
1506 bool neg = state.getRandom().getBool();
1507 coordRange.getMin().component(ndx) = neg ? -4.0f : 2.25f;
1508 coordRange.getMax().component(ndx) = neg ? -2.25f : 4.0f;
1512 coordRange.getMin().component(ndx) = -2.0f;
1513 coordRange.getMax().component(ndx) = 2.0f;
1517 m_coordExpr = Expression::createRandom(state, coordRange.asAccess());
1521 bool isProj = m_type == TYPE_TEXTURE2D_PROJ || m_type == TYPE_TEXTURE2D_PROJ_LOD;
1522 int coordScalarSize = isProj ? 3 : 2;
1524 ValueRange coordRange(VariableType(VariableType::TYPE_FLOAT, coordScalarSize));
1525 setInfiniteRange(coordRange); // Initialize base range with -inf..inf
1529 // w coordinate must be something sane, and not 0.
1530 bool neg = state.getRandom().getBool();
1531 coordRange.getMin().component(2) = neg ? -4.0f : 0.25f;
1532 coordRange.getMax().component(2) = neg ? -0.25f : 4.0f;
1535 m_coordExpr = Expression::createRandom(state, coordRange.asAccess());
1538 DE_ASSERT(m_coordExpr);
1542 return DE_NULL; // Done.
1545 void TexLookup::tokenize (GeneratorState& state, TokenStream& str) const
1547 bool isVertex = state.getShader().getType() == Shader::TYPE_VERTEX;
1549 if (state.getProgramParameters().version == VERSION_300)
1553 case TYPE_TEXTURE2D: str << "texture"; break;
1554 case TYPE_TEXTURE2D_LOD: str << (isVertex ? "textureLod" : "texture"); break;
1555 case TYPE_TEXTURE2D_PROJ: str << "textureProj"; break;
1556 case TYPE_TEXTURE2D_PROJ_LOD: str << (isVertex ? "textureProjLod" : "textureProj"); break;
1557 case TYPE_TEXTURECUBE: str << "texture"; break;
1558 case TYPE_TEXTURECUBE_LOD: str << (isVertex ? "textureLod" : "texture"); break;
1560 DE_ASSERT(DE_FALSE);
1567 case TYPE_TEXTURE2D: str << "texture2D"; break;
1568 case TYPE_TEXTURE2D_LOD: str << (isVertex ? "texture2DLod" : "texture2D"); break;
1569 case TYPE_TEXTURE2D_PROJ: str << "texture2DProj"; break;
1570 case TYPE_TEXTURE2D_PROJ_LOD: str << (isVertex ? "texture2DProjLod" : "texture2DProj"); break;
1571 case TYPE_TEXTURECUBE: str << "textureCube"; break;
1572 case TYPE_TEXTURECUBE_LOD: str << (isVertex ? "textureCubeLod" : "textureCube"); break;
1574 DE_ASSERT(DE_FALSE);
1578 str << Token::LEFT_PAREN;
1579 str << m_sampler->getName();
1580 str << Token::COMMA;
1581 m_coordExpr->tokenize(state, str);
1585 str << Token::COMMA;
1586 m_lodBiasExpr->tokenize(state, str);
1589 str << Token::RIGHT_PAREN;
1592 float TexLookup::getWeight (const GeneratorState& state, ConstValueRangeAccess valueRange)
1594 if (state.getShaderParameters().texLookupBaseWeight <= 0.0f)
1597 int availableLevels = state.getShaderParameters().maxExpressionDepth - state.getExpressionDepth();
1599 // Lookup + Constructor + Values
1600 if (availableLevels < 3)
1603 if (state.getExpressionFlags() & (CONST_EXPR|NO_VAR_ALLOCATION))
1606 if (valueRange.getType() != VariableType(VariableType::TYPE_FLOAT, 4))
1609 ValueRange texOutputRange(VariableType(VariableType::TYPE_FLOAT, 4));
1610 for (int ndx = 0; ndx < 4; ndx++)
1612 texOutputRange.getMin().component(ndx) = 0.0f;
1613 texOutputRange.getMax().component(ndx) = 1.0f;
1616 if (!valueRange.isSupersetOf(texOutputRange.asAccess()))
1619 return state.getShaderParameters().texLookupBaseWeight;
1622 void TexLookup::evaluate (ExecutionContext& execCtx)
1624 // Evaluate coord and bias.
1625 m_coordExpr->evaluate(execCtx);
1627 m_lodBiasExpr->evaluate(execCtx);
1629 ExecConstValueAccess coords = m_coordExpr->getValue();
1630 ExecValueAccess dst = m_value.getValue(m_valueType);
1634 case TYPE_TEXTURE2D:
1636 const Sampler2D& tex = execCtx.getSampler2D(m_sampler);
1637 for (int i = 0; i < EXEC_VEC_WIDTH; i++)
1639 float s = coords.component(0).asFloat(i);
1640 float t = coords.component(1).asFloat(i);
1641 tcu::Vec4 p = tex.sample(s, t, 0.0f);
1643 for (int comp = 0; comp < 4; comp++)
1644 dst.component(comp).asFloat(i) = p[comp];
1649 case TYPE_TEXTURE2D_LOD:
1651 ExecConstValueAccess lod = m_lodBiasExpr->getValue();
1652 const Sampler2D& tex = execCtx.getSampler2D(m_sampler);
1653 for (int i = 0; i < EXEC_VEC_WIDTH; i++)
1655 float s = coords.component(0).asFloat(i);
1656 float t = coords.component(1).asFloat(i);
1657 float l = lod.component(0).asFloat(i);
1658 tcu::Vec4 p = tex.sample(s, t, l);
1660 for (int comp = 0; comp < 4; comp++)
1661 dst.component(comp).asFloat(i) = p[comp];
1666 case TYPE_TEXTURE2D_PROJ:
1668 const Sampler2D& tex = execCtx.getSampler2D(m_sampler);
1669 for (int i = 0; i < EXEC_VEC_WIDTH; i++)
1671 float s = coords.component(0).asFloat(i);
1672 float t = coords.component(1).asFloat(i);
1673 float w = coords.component(2).asFloat(i);
1674 tcu::Vec4 p = tex.sample(s/w, t/w, 0.0f);
1676 for (int comp = 0; comp < 4; comp++)
1677 dst.component(comp).asFloat(i) = p[comp];
1682 case TYPE_TEXTURE2D_PROJ_LOD:
1684 ExecConstValueAccess lod = m_lodBiasExpr->getValue();
1685 const Sampler2D& tex = execCtx.getSampler2D(m_sampler);
1686 for (int i = 0; i < EXEC_VEC_WIDTH; i++)
1688 float s = coords.component(0).asFloat(i);
1689 float t = coords.component(1).asFloat(i);
1690 float w = coords.component(2).asFloat(i);
1691 float l = lod.component(0).asFloat(i);
1692 tcu::Vec4 p = tex.sample(s/w, t/w, l);
1694 for (int comp = 0; comp < 4; comp++)
1695 dst.component(comp).asFloat(i) = p[comp];
1700 case TYPE_TEXTURECUBE:
1702 const SamplerCube& tex = execCtx.getSamplerCube(m_sampler);
1703 for (int i = 0; i < EXEC_VEC_WIDTH; i++)
1705 float s = coords.component(0).asFloat(i);
1706 float t = coords.component(1).asFloat(i);
1707 float r = coords.component(2).asFloat(i);
1708 tcu::Vec4 p = tex.sample(s, t, r, 0.0f);
1710 for (int comp = 0; comp < 4; comp++)
1711 dst.component(comp).asFloat(i) = p[comp];
1716 case TYPE_TEXTURECUBE_LOD:
1718 ExecConstValueAccess lod = m_lodBiasExpr->getValue();
1719 const SamplerCube& tex = execCtx.getSamplerCube(m_sampler);
1720 for (int i = 0; i < EXEC_VEC_WIDTH; i++)
1722 float s = coords.component(0).asFloat(i);
1723 float t = coords.component(1).asFloat(i);
1724 float r = coords.component(2).asFloat(i);
1725 float l = lod.component(0).asFloat(i);
1726 tcu::Vec4 p = tex.sample(s, t, r, l);
1728 for (int comp = 0; comp < 4; comp++)
1729 dst.component(comp).asFloat(i) = p[comp];
1735 DE_ASSERT(DE_FALSE);