diff --git a/native/cocos/scene/Light.cpp b/native/cocos/scene/Light.cpp index 3e3e2f0a9f..b7a054cdc7 100644 --- a/native/cocos/scene/Light.cpp +++ b/native/cocos/scene/Light.cpp @@ -45,5 +45,33 @@ float Light::nt2lm(float size) { return 4 * math::PI * math::PI * size * size; } +Vec3 Light::colorTemperatureToRGB(float kelvin) { + if (kelvin < 1000.0) { + kelvin = 1000.0; + } else if (kelvin > 15000.0) { + kelvin = 15000.0; + } + + // Approximate Planckian locus in CIE 1960 UCS + const float kSqr = kelvin * kelvin; + const float u = (0.860117757 + 1.54118254e-4 * kelvin + 1.28641212e-7 * kSqr) / (1.0 + 8.42420235e-4 * kelvin + 7.08145163e-7 * kSqr); + const float v = (0.317398726 + 4.22806245e-5 * kelvin + 4.20481691e-8 * kSqr) / (1.0 - 2.89741816e-5 * kelvin + 1.61456053e-7 * kSqr); + + const float d = (2.0 * u - 8.0 * v + 4.0); + const float x = (3.0 * u) / d; + const float y = (2.0 * v) / d; + const float z = (1.0 - x) - y; + + const float X = (1.0 / y) * x; + const float Z = (1.0 / y) * z; + + // XYZ to RGB with BT.709 primaries + Vec3 colorWithTemperature; + colorWithTemperature.x = 3.2404542 * X + -1.5371385 + -0.4985314 * Z; + colorWithTemperature.y = -0.9692660 * X + 1.8760108 + 0.0415560 * Z; + colorWithTemperature.z = 0.0556434 * X + -0.2040259 + 1.0572252 * Z; + return colorWithTemperature; +} + } // namespace scene } // namespace cc diff --git a/native/cocos/scene/Light.h b/native/cocos/scene/Light.h index d94fe53d9d..e8347a9f74 100644 --- a/native/cocos/scene/Light.h +++ b/native/cocos/scene/Light.h @@ -70,7 +70,10 @@ public: inline void setUseColorTemperature(bool value) { _useColorTemperature = value; } inline float getColorTemperature() const { return _colorTemp; } - inline void setColorTemperature(float val) { _colorTemp = val; } + inline void setColorTemperature(float val) { + _colorTemp = val; + setColorTemperatureRGB(colorTemperatureToRGB(val)); + } inline Node *getNode() const { return _node.get(); } void setNode(Node *node); @@ -87,6 +90,7 @@ public: inline void setColorTemperatureRGB(const Vec3 &value) { _colorTemperatureRGB = value; } static float nt2lm(float size); + static Vec3 colorTemperatureToRGB(float kelvin); protected: bool _useColorTemperature{false};