IESReader.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541
  1. using System.Collections.Generic;
  2. using System.Globalization;
  3. using System.IO;
  4. using System.Text.RegularExpressions;
  5. using UnityEngine;
  6. namespace UnityEditor.Rendering
  7. {
  8. /// <summary>
  9. /// Class to Parse IES File
  10. /// </summary>
  11. [System.Serializable]
  12. public class IESReader
  13. {
  14. string m_FileFormatVersion;
  15. /// <summary>
  16. /// Version of the IES File
  17. /// </summary>
  18. public string FileFormatVersion
  19. {
  20. get { return m_FileFormatVersion; }
  21. }
  22. float m_TotalLumens;
  23. /// <summary>
  24. /// Total light intensity (in Lumens) stored on the file, usage of it is optional (through the prefab subasset inside the IESObject)
  25. /// </summary>
  26. public float TotalLumens
  27. {
  28. get { return m_TotalLumens; }
  29. }
  30. float m_MaxCandelas;
  31. /// <summary>
  32. /// Maximum of Candela in the IES File
  33. /// </summary>
  34. public float MaxCandelas
  35. {
  36. get { return m_MaxCandelas; }
  37. }
  38. int m_PhotometricType;
  39. /// <summary>
  40. /// Type of Photometric light in the IES file, varying per IES-Type and version
  41. /// </summary>
  42. public int PhotometricType
  43. {
  44. get { return m_PhotometricType; }
  45. }
  46. Dictionary<string, string> m_KeywordDictionary = new Dictionary<string, string>();
  47. int m_VerticalAngleCount;
  48. int m_HorizontalAngleCount;
  49. float[] m_VerticalAngles;
  50. float[] m_HorizontalAngles;
  51. float[] m_CandelaValues;
  52. float m_MinDeltaVerticalAngle;
  53. float m_MinDeltaHorizontalAngle;
  54. float m_FirstHorizontalAngle;
  55. float m_LastHorizontalAngle;
  56. // File format references:
  57. // https://www.ies.org/product/standard-file-format-for-electronic-transfer-of-photometric-data/
  58. // http://lumen.iee.put.poznan.pl/kw/iesna.txt
  59. // https://seblagarde.wordpress.com/2014/11/05/ies-light-format-specification-and-reader/
  60. /// <summary>
  61. /// Main function to read the file
  62. /// </summary>
  63. /// <param name="iesFilePath">The path to the IES File on disk.</param>
  64. /// <returns>Return the error during the import otherwise null if no error</returns>
  65. public string ReadFile(string iesFilePath)
  66. {
  67. using (var iesReader = File.OpenText(iesFilePath))
  68. {
  69. string versionLine = iesReader.ReadLine();
  70. if (versionLine == null)
  71. {
  72. return "Premature end of file (empty file).";
  73. }
  74. switch (versionLine.Trim())
  75. {
  76. case "IESNA91":
  77. m_FileFormatVersion = "LM-63-1991";
  78. break;
  79. case "IESNA:LM-63-1995":
  80. m_FileFormatVersion = "LM-63-1995";
  81. break;
  82. case "IESNA:LM-63-2002":
  83. m_FileFormatVersion = "LM-63-2002";
  84. break;
  85. case "IES:LM-63-2019":
  86. m_FileFormatVersion = "LM-63-2019";
  87. break;
  88. default:
  89. m_FileFormatVersion = "LM-63-1986";
  90. break;
  91. }
  92. var keywordRegex = new Regex(@"\s*\[(?<keyword>\w+)\]\s*(?<data>.*)", RegexOptions.Compiled);
  93. var tiltRegex = new Regex(@"TILT=(?<data>.*)", RegexOptions.Compiled);
  94. string currentKeyword = string.Empty;
  95. for (string keywordLine = (m_FileFormatVersion == "LM-63-1986") ? versionLine : iesReader.ReadLine(); true; keywordLine = iesReader.ReadLine())
  96. {
  97. if (keywordLine == null)
  98. {
  99. return "Premature end of file (missing TILT=NONE).";
  100. }
  101. if (string.IsNullOrWhiteSpace(keywordLine))
  102. {
  103. continue;
  104. }
  105. Match keywordMatch = keywordRegex.Match(keywordLine);
  106. if (keywordMatch.Success)
  107. {
  108. string keyword = keywordMatch.Groups["keyword"].Value;
  109. string data = keywordMatch.Groups["data"].Value.Trim();
  110. if (keyword == currentKeyword || keyword == "MORE")
  111. {
  112. m_KeywordDictionary[currentKeyword] += $" {data}";
  113. }
  114. else
  115. {
  116. // Many separate occurrences of keyword OTHER will need to be handled properly once exposed in the inspector.
  117. currentKeyword = keyword;
  118. m_KeywordDictionary[currentKeyword] = data;
  119. }
  120. continue;
  121. }
  122. Match tiltMatch = tiltRegex.Match(keywordLine);
  123. if (tiltMatch.Success)
  124. {
  125. string data = tiltMatch.Groups["data"].Value.Trim();
  126. if (data == "NONE")
  127. {
  128. break;
  129. }
  130. return $"TILT format not supported: TILT={data}";
  131. }
  132. }
  133. string[] iesDataTokens = Regex.Split(iesReader.ReadToEnd().Trim(), @"[\s,]+");
  134. var iesDataTokenEnumerator = iesDataTokens.GetEnumerator();
  135. string iesDataToken;
  136. if (iesDataTokens.Length == 1 && string.IsNullOrWhiteSpace(iesDataTokens[0]))
  137. {
  138. return "Premature end of file (missing IES data).";
  139. }
  140. if (!iesDataTokenEnumerator.MoveNext())
  141. {
  142. return "Premature end of file (missing lamp count value).";
  143. }
  144. int lampCount;
  145. iesDataToken = iesDataTokenEnumerator.Current.ToString();
  146. if (!int.TryParse(iesDataToken, NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture, out lampCount))
  147. {
  148. return $"Invalid lamp count value: {iesDataToken}";
  149. }
  150. if (lampCount < 1) lampCount = 1;
  151. if (!iesDataTokenEnumerator.MoveNext())
  152. {
  153. return "Premature end of file (missing lumens per lamp value).";
  154. }
  155. float lumensPerLamp;
  156. iesDataToken = iesDataTokenEnumerator.Current.ToString();
  157. if (!float.TryParse(iesDataToken, NumberStyles.AllowLeadingSign | NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out lumensPerLamp))
  158. {
  159. return $"Invalid lumens per lamp value: {iesDataToken}";
  160. }
  161. m_TotalLumens = (lumensPerLamp < 0f) ? -1f : lampCount * lumensPerLamp;
  162. if (!iesDataTokenEnumerator.MoveNext())
  163. {
  164. return "Premature end of file (missing candela multiplier value).";
  165. }
  166. float candelaMultiplier;
  167. iesDataToken = iesDataTokenEnumerator.Current.ToString();
  168. if (!float.TryParse(iesDataToken, NumberStyles.AllowLeadingSign | NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out candelaMultiplier))
  169. {
  170. return $"Invalid candela multiplier value: {iesDataToken}";
  171. }
  172. if (candelaMultiplier < 0f) candelaMultiplier = 0f;
  173. if (!iesDataTokenEnumerator.MoveNext())
  174. {
  175. return "Premature end of file (missing vertical angle count value).";
  176. }
  177. iesDataToken = iesDataTokenEnumerator.Current.ToString();
  178. if (!int.TryParse(iesDataToken, NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture, out m_VerticalAngleCount))
  179. {
  180. return $"Invalid vertical angle count value: {iesDataToken}";
  181. }
  182. if (m_VerticalAngleCount < 1)
  183. {
  184. return $"Invalid number of vertical angles: {m_VerticalAngleCount}";
  185. }
  186. if (!iesDataTokenEnumerator.MoveNext())
  187. {
  188. return "Premature end of file (missing horizontal angle count value).";
  189. }
  190. iesDataToken = iesDataTokenEnumerator.Current.ToString();
  191. if (!int.TryParse(iesDataToken, NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture, out m_HorizontalAngleCount))
  192. {
  193. return $"Invalid horizontal angle count value: {iesDataToken}";
  194. }
  195. if (m_HorizontalAngleCount < 1)
  196. {
  197. return $"Invalid number of horizontal angles: {m_HorizontalAngleCount}";
  198. }
  199. if (!iesDataTokenEnumerator.MoveNext())
  200. {
  201. return "Premature end of file (missing photometric type value).";
  202. }
  203. iesDataToken = iesDataTokenEnumerator.Current.ToString();
  204. if (!int.TryParse(iesDataToken, NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture, out m_PhotometricType))
  205. {
  206. return $"Invalid photometric type value: {iesDataToken}";
  207. }
  208. if (m_PhotometricType < 1 || m_PhotometricType > 3)
  209. {
  210. return $"Invalid photometric type: {m_PhotometricType}";
  211. }
  212. // Skip luminous dimension unit type.
  213. if (!iesDataTokenEnumerator.MoveNext())
  214. {
  215. return "Premature end of file (missing luminous dimension unit type value).";
  216. }
  217. // Skip luminous dimension width.
  218. if (!iesDataTokenEnumerator.MoveNext())
  219. {
  220. return "Premature end of file (missing luminous dimension width value).";
  221. }
  222. // Skip luminous dimension length.
  223. if (!iesDataTokenEnumerator.MoveNext())
  224. {
  225. return "Premature end of file (missing luminous dimension length value).";
  226. }
  227. // Skip luminous dimension height.
  228. if (!iesDataTokenEnumerator.MoveNext())
  229. {
  230. return "Premature end of file (missing luminous dimension height value).";
  231. }
  232. if (!iesDataTokenEnumerator.MoveNext())
  233. {
  234. return "Premature end of file (missing ballast factor value).";
  235. }
  236. float ballastFactor;
  237. iesDataToken = iesDataTokenEnumerator.Current.ToString();
  238. if (!float.TryParse(iesDataToken, NumberStyles.AllowLeadingSign | NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out ballastFactor))
  239. {
  240. return $"Invalid ballast factor value: {iesDataToken}";
  241. }
  242. if (ballastFactor < 0f) ballastFactor = 0f;
  243. // Skip future use.
  244. if (!iesDataTokenEnumerator.MoveNext())
  245. {
  246. return "Premature end of file (missing future use value).";
  247. }
  248. // Skip input watts.
  249. if (!iesDataTokenEnumerator.MoveNext())
  250. {
  251. return "Premature end of file (missing input watts value).";
  252. }
  253. m_VerticalAngles = new float[m_VerticalAngleCount];
  254. float previousVerticalAngle = float.MinValue;
  255. m_MinDeltaVerticalAngle = 180f;
  256. for (int v = 0; v < m_VerticalAngleCount; ++v)
  257. {
  258. if (!iesDataTokenEnumerator.MoveNext())
  259. {
  260. return "Premature end of file (missing vertical angle values).";
  261. }
  262. float angle;
  263. iesDataToken = iesDataTokenEnumerator.Current.ToString();
  264. if (!float.TryParse(iesDataToken, NumberStyles.AllowLeadingSign | NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out angle))
  265. {
  266. return $"Invalid vertical angle value: {iesDataToken}";
  267. }
  268. if (angle <= previousVerticalAngle)
  269. {
  270. return $"Vertical angles are not in ascending order near: {angle}";
  271. }
  272. float deltaVerticalAngle = angle - previousVerticalAngle;
  273. if (deltaVerticalAngle < m_MinDeltaVerticalAngle)
  274. {
  275. m_MinDeltaVerticalAngle = deltaVerticalAngle;
  276. }
  277. m_VerticalAngles[v] = previousVerticalAngle = angle;
  278. }
  279. m_HorizontalAngles = new float[m_HorizontalAngleCount];
  280. float previousHorizontalAngle = float.MinValue;
  281. m_MinDeltaHorizontalAngle = 360f;
  282. for (int h = 0; h < m_HorizontalAngleCount; ++h)
  283. {
  284. if (!iesDataTokenEnumerator.MoveNext())
  285. {
  286. return "Premature end of file (missing horizontal angle values).";
  287. }
  288. float angle;
  289. iesDataToken = iesDataTokenEnumerator.Current.ToString();
  290. if (!float.TryParse(iesDataToken, NumberStyles.AllowLeadingSign | NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out angle))
  291. {
  292. return $"Invalid horizontal angle value: {iesDataToken}";
  293. }
  294. if (angle <= previousHorizontalAngle)
  295. {
  296. return $"Horizontal angles are not in ascending order near: {angle}";
  297. }
  298. float deltaHorizontalAngle = angle - previousHorizontalAngle;
  299. if (deltaHorizontalAngle < m_MinDeltaHorizontalAngle)
  300. {
  301. m_MinDeltaHorizontalAngle = deltaHorizontalAngle;
  302. }
  303. m_HorizontalAngles[h] = previousHorizontalAngle = angle;
  304. }
  305. m_FirstHorizontalAngle = m_HorizontalAngles[0];
  306. m_LastHorizontalAngle = m_HorizontalAngles[m_HorizontalAngleCount - 1];
  307. m_CandelaValues = new float[m_HorizontalAngleCount * m_VerticalAngleCount];
  308. m_MaxCandelas = 0f;
  309. for (int h = 0; h < m_HorizontalAngleCount; ++h)
  310. {
  311. for (int v = 0; v < m_VerticalAngleCount; ++v)
  312. {
  313. if (!iesDataTokenEnumerator.MoveNext())
  314. {
  315. return "Premature end of file (missing candela values).";
  316. }
  317. float value;
  318. iesDataToken = iesDataTokenEnumerator.Current.ToString();
  319. if (!float.TryParse(iesDataToken, NumberStyles.AllowLeadingSign | NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out value))
  320. {
  321. return $"Invalid candela value: {iesDataToken}";
  322. }
  323. value *= candelaMultiplier * ballastFactor;
  324. m_CandelaValues[h * m_VerticalAngleCount + v] = value;
  325. if (value > m_MaxCandelas)
  326. {
  327. m_MaxCandelas = value;
  328. }
  329. }
  330. }
  331. }
  332. return null;
  333. }
  334. internal string GetKeywordValue(string keyword)
  335. {
  336. return m_KeywordDictionary.ContainsKey(keyword) ? m_KeywordDictionary[keyword] : string.Empty;
  337. }
  338. internal int GetMinVerticalSampleCount()
  339. {
  340. if (m_PhotometricType == 2) // type B
  341. {
  342. // Factor in the 90 degree rotation that will be done when building the cylindrical texture.
  343. return 1 + (int)Mathf.Ceil(360 / m_MinDeltaHorizontalAngle); // 360 is 2 * 180 degrees
  344. }
  345. else // type A or C
  346. {
  347. return 1 + (int)Mathf.Ceil(360 / m_MinDeltaVerticalAngle); // 360 is 2 * 180 degrees
  348. }
  349. }
  350. internal int GetMinHorizontalSampleCount()
  351. {
  352. switch (m_PhotometricType)
  353. {
  354. case 3: // type A
  355. return 1 + (int)Mathf.Ceil(720 / m_MinDeltaHorizontalAngle); // 720 is 2 * 360 degrees
  356. case 2: // type B
  357. // Factor in the 90 degree rotation that will be done when building the cylindrical texture.
  358. return 1 + (int)Mathf.Ceil(720 / m_MinDeltaVerticalAngle); // 720 is 2 * 360 degrees
  359. default: // type C
  360. // Factor in the 90 degree rotation that will be done when building the cylindrical texture.
  361. return 1 + (int)Mathf.Ceil(720 / Mathf.Min(m_MinDeltaHorizontalAngle, m_MinDeltaVerticalAngle)); // 720 is 2 * 360 degrees
  362. }
  363. }
  364. internal float ComputeVerticalAnglePosition(float angle)
  365. {
  366. return ComputeAnglePosition(angle, m_VerticalAngles);
  367. }
  368. internal float ComputeTypeAorBHorizontalAnglePosition(float angle) // angle in range [-180..+180] degrees
  369. {
  370. return ComputeAnglePosition(((m_FirstHorizontalAngle == 0f) ? Mathf.Abs(angle) : angle), m_HorizontalAngles);
  371. }
  372. internal float ComputeTypeCHorizontalAnglePosition(float angle) // angle in range [0..360] degrees
  373. {
  374. switch (m_LastHorizontalAngle)
  375. {
  376. case 0f: // the luminaire is assumed to be laterally symmetric in all planes
  377. angle = 0f;
  378. break;
  379. case 90f: // the luminaire is assumed to be symmetric in each quadrant
  380. angle = 90f - Mathf.Abs(Mathf.Abs(angle - 180f) - 90f);
  381. break;
  382. case 180f: // the luminaire is assumed to be symmetric about the 0 to 180 degree plane
  383. angle = 180f - Mathf.Abs(angle - 180f);
  384. break;
  385. default: // the luminaire is assumed to exhibit no lateral symmetry
  386. break;
  387. }
  388. return ComputeAnglePosition(angle, m_HorizontalAngles);
  389. }
  390. internal float ComputeAnglePosition(float value, float[] angles)
  391. {
  392. int start = 0;
  393. int end = angles.Length - 1;
  394. if (value < angles[start])
  395. {
  396. return start;
  397. }
  398. if (value > angles[end])
  399. {
  400. return end;
  401. }
  402. while (start < end)
  403. {
  404. int index = (start + end + 1) / 2;
  405. float angle = angles[index];
  406. if (value >= angle)
  407. {
  408. start = index;
  409. }
  410. else
  411. {
  412. end = index - 1;
  413. }
  414. }
  415. float leftValue = angles[start];
  416. float fraction = 0f;
  417. if (start + 1 < angles.Length)
  418. {
  419. float rightValue = angles[start + 1];
  420. float deltaValue = rightValue - leftValue;
  421. if (deltaValue > 0.0001f)
  422. {
  423. fraction = (value - leftValue) / deltaValue;
  424. }
  425. }
  426. return start + fraction;
  427. }
  428. internal float InterpolateBilinear(float x, float y)
  429. {
  430. int ix = (int)Mathf.Floor(x);
  431. int iy = (int)Mathf.Floor(y);
  432. float fractionX = x - ix;
  433. float fractionY = y - iy;
  434. float p00 = InterpolatePoint(ix + 0, iy + 0);
  435. float p10 = InterpolatePoint(ix + 1, iy + 0);
  436. float p01 = InterpolatePoint(ix + 0, iy + 1);
  437. float p11 = InterpolatePoint(ix + 1, iy + 1);
  438. float p0 = Mathf.Lerp(p00, p01, fractionY);
  439. float p1 = Mathf.Lerp(p10, p11, fractionY);
  440. return Mathf.Lerp(p0, p1, fractionX);
  441. }
  442. internal float InterpolatePoint(int x, int y)
  443. {
  444. x %= m_HorizontalAngles.Length;
  445. y %= m_VerticalAngles.Length;
  446. return m_CandelaValues[y + x * m_VerticalAngles.Length];
  447. }
  448. }
  449. }