raytrace.js 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323
  1. // Copyright 2013 the V8 project authors. All rights reserved.
  2. // Redistribution and use in source and binary forms, with or without
  3. // modification, are permitted provided that the following conditions are
  4. // met:
  5. //
  6. // * Redistributions of source code must retain the above copyright
  7. // notice, this list of conditions and the following disclaimer.
  8. // * Redistributions in binary form must reproduce the above
  9. // copyright notice, this list of conditions and the following
  10. // disclaimer in the documentation and/or other materials provided
  11. // with the distribution.
  12. // * Neither the name of Google Inc. nor the names of its
  13. // contributors may be used to endorse or promote products derived
  14. // from this software without specific prior written permission.
  15. //
  16. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  17. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  18. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  19. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  20. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  21. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  22. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  23. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  24. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  25. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  26. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  27. // Performance.now is used in latency benchmarks, the fallback is Date.now.
  28. var performance = performance || {};
  29. performance.now = (function() {
  30. return performance.now ||
  31. performance.mozNow ||
  32. performance.msNow ||
  33. performance.oNow ||
  34. performance.webkitNow ||
  35. Date.now;
  36. })();
  37. // Simple framework for running the benchmark suites and
  38. // computing a score based on the timing measurements.
  39. // A benchmark has a name (string) and a function that will be run to
  40. // do the performance measurement. The optional setup and tearDown
  41. // arguments are functions that will be invoked before and after
  42. // running the benchmark, but the running time of these functions will
  43. // not be accounted for in the benchmark score.
  44. function Benchmark(name, doWarmup, doDeterministic, deterministicIterations,
  45. run, setup, tearDown, rmsResult, minIterations) {
  46. this.name = name;
  47. this.doWarmup = doWarmup;
  48. this.doDeterministic = doDeterministic;
  49. this.deterministicIterations = deterministicIterations;
  50. this.run = run;
  51. this.Setup = setup ? setup : function() { };
  52. this.TearDown = tearDown ? tearDown : function() { };
  53. this.rmsResult = rmsResult ? rmsResult : null;
  54. this.minIterations = minIterations ? minIterations : 32;
  55. }
  56. // Benchmark results hold the benchmark and the measured time used to
  57. // run the benchmark. The benchmark score is computed later once a
  58. // full benchmark suite has run to completion. If latency is set to 0
  59. // then there is no latency score for this benchmark.
  60. function BenchmarkResult(benchmark, time, latency) {
  61. this.benchmark = benchmark;
  62. this.time = time;
  63. this.latency = latency;
  64. }
  65. // Automatically convert results to numbers. Used by the geometric
  66. // mean computation.
  67. BenchmarkResult.prototype.valueOf = function() {
  68. return this.time;
  69. }
  70. // Suites of benchmarks consist of a name and the set of benchmarks in
  71. // addition to the reference timing that the final score will be based
  72. // on. This way, all scores are relative to a reference run and higher
  73. // scores implies better performance.
  74. function BenchmarkSuite(name, reference, benchmarks) {
  75. this.name = name;
  76. this.reference = reference;
  77. this.benchmarks = benchmarks;
  78. BenchmarkSuite.suites.push(this);
  79. }
  80. // Keep track of all declared benchmark suites.
  81. BenchmarkSuite.suites = [];
  82. // Scores are not comparable across versions. Bump the version if
  83. // you're making changes that will affect that scores, e.g. if you add
  84. // a new benchmark or change an existing one.
  85. BenchmarkSuite.version = '9';
  86. // Defines global benchsuite running mode that overrides benchmark suite
  87. // behavior. Intended to be set by the benchmark driver. Undefined
  88. // values here allow a benchmark to define behaviour itself.
  89. BenchmarkSuite.config = {
  90. doWarmup: undefined,
  91. doDeterministic: undefined
  92. };
  93. // Override the alert function to throw an exception instead.
  94. alert = function(s) {
  95. throw "Alert called with argument: " + s;
  96. };
  97. // To make the benchmark results predictable, we replace Math.random
  98. // with a 100% deterministic alternative.
  99. BenchmarkSuite.ResetRNG = function() {
  100. Math.random = (function() {
  101. var seed = 49734321;
  102. return function() {
  103. // Robert Jenkins' 32 bit integer hash function.
  104. seed = ((seed + 0x7ed55d16) + (seed << 12)) & 0xffffffff;
  105. seed = ((seed ^ 0xc761c23c) ^ (seed >>> 19)) & 0xffffffff;
  106. seed = ((seed + 0x165667b1) + (seed << 5)) & 0xffffffff;
  107. seed = ((seed + 0xd3a2646c) ^ (seed << 9)) & 0xffffffff;
  108. seed = ((seed + 0xfd7046c5) + (seed << 3)) & 0xffffffff;
  109. seed = ((seed ^ 0xb55a4f09) ^ (seed >>> 16)) & 0xffffffff;
  110. return (seed & 0xfffffff) / 0x10000000;
  111. };
  112. })();
  113. }
  114. // Runs all registered benchmark suites and optionally yields between
  115. // each individual benchmark to avoid running for too long in the
  116. // context of browsers. Once done, the final score is reported to the
  117. // runner.
  118. BenchmarkSuite.RunSuites = function(runner, skipBenchmarks) {
  119. skipBenchmarks = typeof skipBenchmarks === 'undefined' ? [] : skipBenchmarks;
  120. var continuation = null;
  121. var suites = BenchmarkSuite.suites;
  122. var length = suites.length;
  123. BenchmarkSuite.scores = [];
  124. var index = 0;
  125. function RunStep() {
  126. while (continuation || index < length) {
  127. if (continuation) {
  128. continuation = continuation();
  129. } else {
  130. var suite = suites[index++];
  131. if (runner.NotifyStart) runner.NotifyStart(suite.name);
  132. if (skipBenchmarks.indexOf(suite.name) > -1) {
  133. suite.NotifySkipped(runner);
  134. } else {
  135. continuation = suite.RunStep(runner);
  136. }
  137. }
  138. if (continuation && typeof window != 'undefined' && window.setTimeout) {
  139. window.setTimeout(RunStep, 25);
  140. return;
  141. }
  142. }
  143. // show final result
  144. if (runner.NotifyScore) {
  145. var score = BenchmarkSuite.GeometricMean(BenchmarkSuite.scores);
  146. var formatted = BenchmarkSuite.FormatScore(100 * score);
  147. runner.NotifyScore(formatted);
  148. }
  149. }
  150. RunStep();
  151. }
  152. // Counts the total number of registered benchmarks. Useful for
  153. // showing progress as a percentage.
  154. BenchmarkSuite.CountBenchmarks = function() {
  155. var result = 0;
  156. var suites = BenchmarkSuite.suites;
  157. for (var i = 0; i < suites.length; i++) {
  158. result += suites[i].benchmarks.length;
  159. }
  160. return result;
  161. }
  162. // Computes the geometric mean of a set of numbers.
  163. BenchmarkSuite.GeometricMean = function(numbers) {
  164. var log = 0;
  165. for (var i = 0; i < numbers.length; i++) {
  166. log += Math.log(numbers[i]);
  167. }
  168. return Math.pow(Math.E, log / numbers.length);
  169. }
  170. // Computes the geometric mean of a set of throughput time measurements.
  171. BenchmarkSuite.GeometricMeanTime = function(measurements) {
  172. var log = 0;
  173. for (var i = 0; i < measurements.length; i++) {
  174. log += Math.log(measurements[i].time);
  175. }
  176. return Math.pow(Math.E, log / measurements.length);
  177. }
  178. // Computes the geometric mean of a set of rms measurements.
  179. BenchmarkSuite.GeometricMeanLatency = function(measurements) {
  180. var log = 0;
  181. var hasLatencyResult = false;
  182. for (var i = 0; i < measurements.length; i++) {
  183. if (measurements[i].latency != 0) {
  184. log += Math.log(measurements[i].latency);
  185. hasLatencyResult = true;
  186. }
  187. }
  188. if (hasLatencyResult) {
  189. return Math.pow(Math.E, log / measurements.length);
  190. } else {
  191. return 0;
  192. }
  193. }
  194. // Converts a score value to a string with at least three significant
  195. // digits.
  196. BenchmarkSuite.FormatScore = function(value) {
  197. if (value > 100) {
  198. return value.toFixed(0);
  199. } else {
  200. return value.toPrecision(3);
  201. }
  202. }
  203. // Notifies the runner that we're done running a single benchmark in
  204. // the benchmark suite. This can be useful to report progress.
  205. BenchmarkSuite.prototype.NotifyStep = function(result) {
  206. this.results.push(result);
  207. if (this.runner.NotifyStep) this.runner.NotifyStep(result.benchmark.name);
  208. }
  209. // Notifies the runner that we're done with running a suite and that
  210. // we have a result which can be reported to the user if needed.
  211. BenchmarkSuite.prototype.NotifyResult = function() {
  212. var mean = BenchmarkSuite.GeometricMeanTime(this.results);
  213. var score = this.reference[0] / mean;
  214. BenchmarkSuite.scores.push(score);
  215. if (this.runner.NotifyResult) {
  216. var formatted = BenchmarkSuite.FormatScore(100 * score);
  217. this.runner.NotifyResult(this.name, formatted);
  218. }
  219. if (this.reference.length == 2) {
  220. var meanLatency = BenchmarkSuite.GeometricMeanLatency(this.results);
  221. if (meanLatency != 0) {
  222. var scoreLatency = this.reference[1] / meanLatency;
  223. BenchmarkSuite.scores.push(scoreLatency);
  224. if (this.runner.NotifyResult) {
  225. var formattedLatency = BenchmarkSuite.FormatScore(100 * scoreLatency)
  226. this.runner.NotifyResult(this.name + "Latency", formattedLatency);
  227. }
  228. }
  229. }
  230. }
  231. BenchmarkSuite.prototype.NotifySkipped = function(runner) {
  232. BenchmarkSuite.scores.push(1); // push default reference score.
  233. if (runner.NotifyResult) {
  234. runner.NotifyResult(this.name, "Skipped");
  235. }
  236. }
  237. // Notifies the runner that running a benchmark resulted in an error.
  238. BenchmarkSuite.prototype.NotifyError = function(error) {
  239. if (this.runner.NotifyError) {
  240. this.runner.NotifyError(this.name, error);
  241. }
  242. if (this.runner.NotifyStep) {
  243. this.runner.NotifyStep(this.name);
  244. }
  245. }
  246. // Runs a single benchmark for at least a second and computes the
  247. // average time it takes to run a single iteration.
  248. BenchmarkSuite.prototype.RunSingleBenchmark = function(benchmark, data) {
  249. var config = BenchmarkSuite.config;
  250. var doWarmup = config.doWarmup !== undefined
  251. ? config.doWarmup
  252. : benchmark.doWarmup;
  253. var doDeterministic = config.doDeterministic !== undefined
  254. ? config.doDeterministic
  255. : benchmark.doDeterministic;
  256. function Measure(data) {
  257. var elapsed = 0;
  258. var start = new Date();
  259. // Run either for 1 second or for the number of iterations specified
  260. // by minIterations, depending on the config flag doDeterministic.
  261. for (var i = 0; (doDeterministic ?
  262. i<benchmark.deterministicIterations : elapsed < 1000); i++) {
  263. benchmark.run();
  264. elapsed = new Date() - start;
  265. }
  266. if (data != null) {
  267. data.runs += i;
  268. data.elapsed += elapsed;
  269. }
  270. }
  271. // Sets up data in order to skip or not the warmup phase.
  272. if (!doWarmup && data == null) {
  273. data = { runs: 0, elapsed: 0 };
  274. }
  275. if (data == null) {
  276. Measure(null);
  277. return { runs: 0, elapsed: 0 };
  278. } else {
  279. Measure(data);
  280. // If we've run too few iterations, we continue for another second.
  281. if (data.runs < benchmark.minIterations) return data;
  282. var usec = (data.elapsed * 1000) / data.runs;
  283. var rms = (benchmark.rmsResult != null) ? benchmark.rmsResult() : 0;
  284. this.NotifyStep(new BenchmarkResult(benchmark, usec, rms));
  285. return null;
  286. }
  287. }
  288. // This function starts running a suite, but stops between each
  289. // individual benchmark in the suite and returns a continuation
  290. // function which can be invoked to run the next benchmark. Once the
  291. // last benchmark has been executed, null is returned.
  292. BenchmarkSuite.prototype.RunStep = function(runner) {
  293. BenchmarkSuite.ResetRNG();
  294. this.results = [];
  295. this.runner = runner;
  296. var length = this.benchmarks.length;
  297. var index = 0;
  298. var suite = this;
  299. var data;
  300. // Run the setup, the actual benchmark, and the tear down in three
  301. // separate steps to allow the framework to yield between any of the
  302. // steps.
  303. function RunNextSetup() {
  304. if (index < length) {
  305. try {
  306. suite.benchmarks[index].Setup();
  307. } catch (e) {
  308. suite.NotifyError(e);
  309. return null;
  310. }
  311. return RunNextBenchmark;
  312. }
  313. suite.NotifyResult();
  314. return null;
  315. }
  316. function RunNextBenchmark() {
  317. try {
  318. data = suite.RunSingleBenchmark(suite.benchmarks[index], data);
  319. } catch (e) {
  320. suite.NotifyError(e);
  321. return null;
  322. }
  323. // If data is null, we're done with this benchmark.
  324. return (data == null) ? RunNextTearDown : RunNextBenchmark();
  325. }
  326. function RunNextTearDown() {
  327. try {
  328. suite.benchmarks[index++].TearDown();
  329. } catch (e) {
  330. suite.NotifyError(e);
  331. return null;
  332. }
  333. return RunNextSetup;
  334. }
  335. // Start out running the setup.
  336. return RunNextSetup();
  337. }
  338. // The ray tracer code in this file is written by Adam Burmister. It
  339. // is available in its original form from:
  340. //
  341. // http://labs.flog.nz.co/raytracer/
  342. //
  343. // It has been modified slightly by Google to work as a standalone
  344. // benchmark, but the all the computational code remains
  345. // untouched. This file also contains a copy of parts of the Prototype
  346. // JavaScript framework which is used by the ray tracer.
  347. var RayTrace = new BenchmarkSuite('RayTrace', [739989], [
  348. new Benchmark('RayTrace', true, false, 600, renderScene)
  349. ]);
  350. // Variable used to hold a number that can be used to verify that
  351. // the scene was ray traced correctly.
  352. var checkNumber;
  353. // ------------------------------------------------------------------------
  354. // ------------------------------------------------------------------------
  355. // The following is a copy of parts of the Prototype JavaScript library:
  356. // Prototype JavaScript framework, version 1.5.0
  357. // (c) 2005-2007 Sam Stephenson
  358. //
  359. // Prototype is freely distributable under the terms of an MIT-style license.
  360. // For details, see the Prototype web site: http://prototype.conio.net/
  361. var Class = {
  362. create: function() {
  363. return function() {
  364. this.initialize.apply(this, arguments);
  365. }
  366. }
  367. };
  368. Object.extend = function(destination, source) {
  369. for (var property in source) {
  370. destination[property] = source[property];
  371. }
  372. return destination;
  373. };
  374. // ------------------------------------------------------------------------
  375. // ------------------------------------------------------------------------
  376. // The rest of this file is the actual ray tracer written by Adam
  377. // Burmister. It's a concatenation of the following files:
  378. //
  379. // flog/color.js
  380. // flog/light.js
  381. // flog/vector.js
  382. // flog/ray.js
  383. // flog/scene.js
  384. // flog/material/basematerial.js
  385. // flog/material/solid.js
  386. // flog/material/chessboard.js
  387. // flog/shape/baseshape.js
  388. // flog/shape/sphere.js
  389. // flog/shape/plane.js
  390. // flog/intersectioninfo.js
  391. // flog/camera.js
  392. // flog/background.js
  393. // flog/engine.js
  394. /* Fake a Flog.* namespace */
  395. if(typeof(Flog) == 'undefined') var Flog = {};
  396. if(typeof(Flog.RayTracer) == 'undefined') Flog.RayTracer = {};
  397. Flog.RayTracer.Color = Class.create();
  398. Flog.RayTracer.Color.prototype = {
  399. red : 0.0,
  400. green : 0.0,
  401. blue : 0.0,
  402. initialize : function(r, g, b) {
  403. if(!r) r = 0.0;
  404. if(!g) g = 0.0;
  405. if(!b) b = 0.0;
  406. this.red = r;
  407. this.green = g;
  408. this.blue = b;
  409. },
  410. add : function(c1, c2){
  411. var result = new Flog.RayTracer.Color(0,0,0);
  412. result.red = c1.red + c2.red;
  413. result.green = c1.green + c2.green;
  414. result.blue = c1.blue + c2.blue;
  415. return result;
  416. },
  417. addScalar: function(c1, s){
  418. var result = new Flog.RayTracer.Color(0,0,0);
  419. result.red = c1.red + s;
  420. result.green = c1.green + s;
  421. result.blue = c1.blue + s;
  422. result.limit();
  423. return result;
  424. },
  425. subtract: function(c1, c2){
  426. var result = new Flog.RayTracer.Color(0,0,0);
  427. result.red = c1.red - c2.red;
  428. result.green = c1.green - c2.green;
  429. result.blue = c1.blue - c2.blue;
  430. return result;
  431. },
  432. multiply : function(c1, c2) {
  433. var result = new Flog.RayTracer.Color(0,0,0);
  434. result.red = c1.red * c2.red;
  435. result.green = c1.green * c2.green;
  436. result.blue = c1.blue * c2.blue;
  437. return result;
  438. },
  439. multiplyScalar : function(c1, f) {
  440. var result = new Flog.RayTracer.Color(0,0,0);
  441. result.red = c1.red * f;
  442. result.green = c1.green * f;
  443. result.blue = c1.blue * f;
  444. return result;
  445. },
  446. divideFactor : function(c1, f) {
  447. var result = new Flog.RayTracer.Color(0,0,0);
  448. result.red = c1.red / f;
  449. result.green = c1.green / f;
  450. result.blue = c1.blue / f;
  451. return result;
  452. },
  453. limit: function(){
  454. this.red = (this.red > 0.0) ? ( (this.red > 1.0) ? 1.0 : this.red ) : 0.0;
  455. this.green = (this.green > 0.0) ? ( (this.green > 1.0) ? 1.0 : this.green ) : 0.0;
  456. this.blue = (this.blue > 0.0) ? ( (this.blue > 1.0) ? 1.0 : this.blue ) : 0.0;
  457. },
  458. distance : function(color) {
  459. var d = Math.abs(this.red - color.red) + Math.abs(this.green - color.green) + Math.abs(this.blue - color.blue);
  460. return d;
  461. },
  462. blend: function(c1, c2, w){
  463. var result = new Flog.RayTracer.Color(0,0,0);
  464. result = Flog.RayTracer.Color.prototype.add(
  465. Flog.RayTracer.Color.prototype.multiplyScalar(c1, 1 - w),
  466. Flog.RayTracer.Color.prototype.multiplyScalar(c2, w)
  467. );
  468. return result;
  469. },
  470. brightness : function() {
  471. var r = Math.floor(this.red*255);
  472. var g = Math.floor(this.green*255);
  473. var b = Math.floor(this.blue*255);
  474. return (r * 77 + g * 150 + b * 29) >> 8;
  475. },
  476. toString : function () {
  477. var r = Math.floor(this.red*255);
  478. var g = Math.floor(this.green*255);
  479. var b = Math.floor(this.blue*255);
  480. return "rgb("+ r +","+ g +","+ b +")";
  481. }
  482. }
  483. /* Fake a Flog.* namespace */
  484. if(typeof(Flog) == 'undefined') var Flog = {};
  485. if(typeof(Flog.RayTracer) == 'undefined') Flog.RayTracer = {};
  486. Flog.RayTracer.Light = Class.create();
  487. Flog.RayTracer.Light.prototype = {
  488. position: null,
  489. color: null,
  490. intensity: 10.0,
  491. initialize : function(pos, color, intensity) {
  492. this.position = pos;
  493. this.color = color;
  494. this.intensity = (intensity ? intensity : 10.0);
  495. },
  496. toString : function () {
  497. return 'Light [' + this.position.x + ',' + this.position.y + ',' + this.position.z + ']';
  498. }
  499. }
  500. /* Fake a Flog.* namespace */
  501. if(typeof(Flog) == 'undefined') var Flog = {};
  502. if(typeof(Flog.RayTracer) == 'undefined') Flog.RayTracer = {};
  503. Flog.RayTracer.Vector = Class.create();
  504. Flog.RayTracer.Vector.prototype = {
  505. x : 0.0,
  506. y : 0.0,
  507. z : 0.0,
  508. initialize : function(x, y, z) {
  509. this.x = (x ? x : 0);
  510. this.y = (y ? y : 0);
  511. this.z = (z ? z : 0);
  512. },
  513. copy: function(vector){
  514. this.x = vector.x;
  515. this.y = vector.y;
  516. this.z = vector.z;
  517. },
  518. normalize : function() {
  519. var m = this.magnitude();
  520. return new Flog.RayTracer.Vector(this.x / m, this.y / m, this.z / m);
  521. },
  522. magnitude : function() {
  523. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z));
  524. },
  525. cross : function(w) {
  526. return new Flog.RayTracer.Vector(
  527. -this.z * w.y + this.y * w.z,
  528. this.z * w.x - this.x * w.z,
  529. -this.y * w.x + this.x * w.y);
  530. },
  531. dot : function(w) {
  532. return this.x * w.x + this.y * w.y + this.z * w.z;
  533. },
  534. add : function(v, w) {
  535. return new Flog.RayTracer.Vector(w.x + v.x, w.y + v.y, w.z + v.z);
  536. },
  537. subtract : function(v, w) {
  538. if(!w || !v) throw 'Vectors must be defined [' + v + ',' + w + ']';
  539. return new Flog.RayTracer.Vector(v.x - w.x, v.y - w.y, v.z - w.z);
  540. },
  541. multiplyVector : function(v, w) {
  542. return new Flog.RayTracer.Vector(v.x * w.x, v.y * w.y, v.z * w.z);
  543. },
  544. multiplyScalar : function(v, w) {
  545. return new Flog.RayTracer.Vector(v.x * w, v.y * w, v.z * w);
  546. },
  547. toString : function () {
  548. return 'Vector [' + this.x + ',' + this.y + ',' + this.z + ']';
  549. }
  550. }
  551. /* Fake a Flog.* namespace */
  552. if(typeof(Flog) == 'undefined') var Flog = {};
  553. if(typeof(Flog.RayTracer) == 'undefined') Flog.RayTracer = {};
  554. Flog.RayTracer.Ray = Class.create();
  555. Flog.RayTracer.Ray.prototype = {
  556. position : null,
  557. direction : null,
  558. initialize : function(pos, dir) {
  559. this.position = pos;
  560. this.direction = dir;
  561. },
  562. toString : function () {
  563. return 'Ray [' + this.position + ',' + this.direction + ']';
  564. }
  565. }
  566. /* Fake a Flog.* namespace */
  567. if(typeof(Flog) == 'undefined') var Flog = {};
  568. if(typeof(Flog.RayTracer) == 'undefined') Flog.RayTracer = {};
  569. Flog.RayTracer.Scene = Class.create();
  570. Flog.RayTracer.Scene.prototype = {
  571. camera : null,
  572. shapes : [],
  573. lights : [],
  574. background : null,
  575. initialize : function() {
  576. this.camera = new Flog.RayTracer.Camera(
  577. new Flog.RayTracer.Vector(0,0,-5),
  578. new Flog.RayTracer.Vector(0,0,1),
  579. new Flog.RayTracer.Vector(0,1,0)
  580. );
  581. this.shapes = new Array();
  582. this.lights = new Array();
  583. this.background = new Flog.RayTracer.Background(new Flog.RayTracer.Color(0,0,0.5), 0.2);
  584. }
  585. }
  586. /* Fake a Flog.* namespace */
  587. if(typeof(Flog) == 'undefined') var Flog = {};
  588. if(typeof(Flog.RayTracer) == 'undefined') Flog.RayTracer = {};
  589. if(typeof(Flog.RayTracer.Material) == 'undefined') Flog.RayTracer.Material = {};
  590. Flog.RayTracer.Material.BaseMaterial = Class.create();
  591. Flog.RayTracer.Material.BaseMaterial.prototype = {
  592. gloss: 2.0, // [0...infinity] 0 = matt
  593. transparency: 0.0, // 0=opaque
  594. reflection: 0.0, // [0...infinity] 0 = no reflection
  595. refraction: 0.50,
  596. hasTexture: false,
  597. initialize : function() {
  598. },
  599. getColor: function(u, v){
  600. },
  601. wrapUp: function(t){
  602. t = t % 2.0;
  603. if(t < -1) t += 2.0;
  604. if(t >= 1) t -= 2.0;
  605. return t;
  606. },
  607. toString : function () {
  608. return 'Material [gloss=' + this.gloss + ', transparency=' + this.transparency + ', hasTexture=' + this.hasTexture +']';
  609. }
  610. }
  611. /* Fake a Flog.* namespace */
  612. if(typeof(Flog) == 'undefined') var Flog = {};
  613. if(typeof(Flog.RayTracer) == 'undefined') Flog.RayTracer = {};
  614. Flog.RayTracer.Material.Solid = Class.create();
  615. Flog.RayTracer.Material.Solid.prototype = Object.extend(
  616. new Flog.RayTracer.Material.BaseMaterial(), {
  617. initialize : function(color, reflection, refraction, transparency, gloss) {
  618. this.color = color;
  619. this.reflection = reflection;
  620. this.transparency = transparency;
  621. this.gloss = gloss;
  622. this.hasTexture = false;
  623. },
  624. getColor: function(u, v){
  625. return this.color;
  626. },
  627. toString : function () {
  628. return 'SolidMaterial [gloss=' + this.gloss + ', transparency=' + this.transparency + ', hasTexture=' + this.hasTexture +']';
  629. }
  630. }
  631. );
  632. /* Fake a Flog.* namespace */
  633. if(typeof(Flog) == 'undefined') var Flog = {};
  634. if(typeof(Flog.RayTracer) == 'undefined') Flog.RayTracer = {};
  635. Flog.RayTracer.Material.Chessboard = Class.create();
  636. Flog.RayTracer.Material.Chessboard.prototype = Object.extend(
  637. new Flog.RayTracer.Material.BaseMaterial(), {
  638. colorEven: null,
  639. colorOdd: null,
  640. density: 0.5,
  641. initialize : function(colorEven, colorOdd, reflection, transparency, gloss, density) {
  642. this.colorEven = colorEven;
  643. this.colorOdd = colorOdd;
  644. this.reflection = reflection;
  645. this.transparency = transparency;
  646. this.gloss = gloss;
  647. this.density = density;
  648. this.hasTexture = true;
  649. },
  650. getColor: function(u, v){
  651. var t = this.wrapUp(u * this.density) * this.wrapUp(v * this.density);
  652. if(t < 0.0)
  653. return this.colorEven;
  654. else
  655. return this.colorOdd;
  656. },
  657. toString : function () {
  658. return 'ChessMaterial [gloss=' + this.gloss + ', transparency=' + this.transparency + ', hasTexture=' + this.hasTexture +']';
  659. }
  660. }
  661. );
  662. /* Fake a Flog.* namespace */
  663. if(typeof(Flog) == 'undefined') var Flog = {};
  664. if(typeof(Flog.RayTracer) == 'undefined') Flog.RayTracer = {};
  665. if(typeof(Flog.RayTracer.Shape) == 'undefined') Flog.RayTracer.Shape = {};
  666. Flog.RayTracer.Shape.Sphere = Class.create();
  667. Flog.RayTracer.Shape.Sphere.prototype = {
  668. initialize : function(pos, radius, material) {
  669. this.radius = radius;
  670. this.position = pos;
  671. this.material = material;
  672. },
  673. intersect: function(ray){
  674. var info = new Flog.RayTracer.IntersectionInfo();
  675. info.shape = this;
  676. var dst = Flog.RayTracer.Vector.prototype.subtract(ray.position, this.position);
  677. var B = dst.dot(ray.direction);
  678. var C = dst.dot(dst) - (this.radius * this.radius);
  679. var D = (B * B) - C;
  680. if(D > 0){ // intersection!
  681. info.isHit = true;
  682. info.distance = (-B) - Math.sqrt(D);
  683. info.position = Flog.RayTracer.Vector.prototype.add(
  684. ray.position,
  685. Flog.RayTracer.Vector.prototype.multiplyScalar(
  686. ray.direction,
  687. info.distance
  688. )
  689. );
  690. info.normal = Flog.RayTracer.Vector.prototype.subtract(
  691. info.position,
  692. this.position
  693. ).normalize();
  694. info.color = this.material.getColor(0,0);
  695. } else {
  696. info.isHit = false;
  697. }
  698. return info;
  699. },
  700. toString : function () {
  701. return 'Sphere [position=' + this.position + ', radius=' + this.radius + ']';
  702. }
  703. }
  704. /* Fake a Flog.* namespace */
  705. if(typeof(Flog) == 'undefined') var Flog = {};
  706. if(typeof(Flog.RayTracer) == 'undefined') Flog.RayTracer = {};
  707. if(typeof(Flog.RayTracer.Shape) == 'undefined') Flog.RayTracer.Shape = {};
  708. Flog.RayTracer.Shape.Plane = Class.create();
  709. Flog.RayTracer.Shape.Plane.prototype = {
  710. d: 0.0,
  711. initialize : function(pos, d, material) {
  712. this.position = pos;
  713. this.d = d;
  714. this.material = material;
  715. },
  716. intersect: function(ray){
  717. var info = new Flog.RayTracer.IntersectionInfo();
  718. var Vd = this.position.dot(ray.direction);
  719. if(Vd == 0) return info; // no intersection
  720. var t = -(this.position.dot(ray.position) + this.d) / Vd;
  721. if(t <= 0) return info;
  722. info.shape = this;
  723. info.isHit = true;
  724. info.position = Flog.RayTracer.Vector.prototype.add(
  725. ray.position,
  726. Flog.RayTracer.Vector.prototype.multiplyScalar(
  727. ray.direction,
  728. t
  729. )
  730. );
  731. info.normal = this.position;
  732. info.distance = t;
  733. if(this.material.hasTexture){
  734. var vU = new Flog.RayTracer.Vector(this.position.y, this.position.z, -this.position.x);
  735. var vV = vU.cross(this.position);
  736. var u = info.position.dot(vU);
  737. var v = info.position.dot(vV);
  738. info.color = this.material.getColor(u,v);
  739. } else {
  740. info.color = this.material.getColor(0,0);
  741. }
  742. return info;
  743. },
  744. toString : function () {
  745. return 'Plane [' + this.position + ', d=' + this.d + ']';
  746. }
  747. }
  748. /* Fake a Flog.* namespace */
  749. if(typeof(Flog) == 'undefined') var Flog = {};
  750. if(typeof(Flog.RayTracer) == 'undefined') Flog.RayTracer = {};
  751. Flog.RayTracer.IntersectionInfo = Class.create();
  752. Flog.RayTracer.IntersectionInfo.prototype = {
  753. isHit: false,
  754. hitCount: 0,
  755. shape: null,
  756. position: null,
  757. normal: null,
  758. color: null,
  759. distance: null,
  760. initialize : function() {
  761. this.color = new Flog.RayTracer.Color(0,0,0);
  762. },
  763. toString : function () {
  764. return 'Intersection [' + this.position + ']';
  765. }
  766. }
  767. /* Fake a Flog.* namespace */
  768. if(typeof(Flog) == 'undefined') var Flog = {};
  769. if(typeof(Flog.RayTracer) == 'undefined') Flog.RayTracer = {};
  770. Flog.RayTracer.Camera = Class.create();
  771. Flog.RayTracer.Camera.prototype = {
  772. position: null,
  773. lookAt: null,
  774. equator: null,
  775. up: null,
  776. screen: null,
  777. initialize : function(pos, lookAt, up) {
  778. this.position = pos;
  779. this.lookAt = lookAt;
  780. this.up = up;
  781. this.equator = lookAt.normalize().cross(this.up);
  782. this.screen = Flog.RayTracer.Vector.prototype.add(this.position, this.lookAt);
  783. },
  784. getRay: function(vx, vy){
  785. var pos = Flog.RayTracer.Vector.prototype.subtract(
  786. this.screen,
  787. Flog.RayTracer.Vector.prototype.subtract(
  788. Flog.RayTracer.Vector.prototype.multiplyScalar(this.equator, vx),
  789. Flog.RayTracer.Vector.prototype.multiplyScalar(this.up, vy)
  790. )
  791. );
  792. pos.y = pos.y * -1;
  793. var dir = Flog.RayTracer.Vector.prototype.subtract(
  794. pos,
  795. this.position
  796. );
  797. var ray = new Flog.RayTracer.Ray(pos, dir.normalize());
  798. return ray;
  799. },
  800. toString : function () {
  801. return 'Ray []';
  802. }
  803. }
  804. /* Fake a Flog.* namespace */
  805. if(typeof(Flog) == 'undefined') var Flog = {};
  806. if(typeof(Flog.RayTracer) == 'undefined') Flog.RayTracer = {};
  807. Flog.RayTracer.Background = Class.create();
  808. Flog.RayTracer.Background.prototype = {
  809. color : null,
  810. ambience : 0.0,
  811. initialize : function(color, ambience) {
  812. this.color = color;
  813. this.ambience = ambience;
  814. }
  815. }
  816. /* Fake a Flog.* namespace */
  817. if(typeof(Flog) == 'undefined') var Flog = {};
  818. if(typeof(Flog.RayTracer) == 'undefined') Flog.RayTracer = {};
  819. Flog.RayTracer.Engine = Class.create();
  820. Flog.RayTracer.Engine.prototype = {
  821. canvas: null, /* 2d context we can render to */
  822. initialize: function(options){
  823. this.options = Object.extend({
  824. canvasHeight: 100,
  825. canvasWidth: 100,
  826. pixelWidth: 2,
  827. pixelHeight: 2,
  828. renderDiffuse: false,
  829. renderShadows: false,
  830. renderHighlights: false,
  831. renderReflections: false,
  832. rayDepth: 2
  833. }, options || {});
  834. this.options.canvasHeight /= this.options.pixelHeight;
  835. this.options.canvasWidth /= this.options.pixelWidth;
  836. /* TODO: dynamically include other scripts */
  837. },
  838. setPixel: function(x, y, color){
  839. var pxW, pxH;
  840. pxW = this.options.pixelWidth;
  841. pxH = this.options.pixelHeight;
  842. if (this.canvas) {
  843. this.canvas.fillStyle = color.toString();
  844. this.canvas.fillRect (x * pxW, y * pxH, pxW, pxH);
  845. } else {
  846. if (x === y) {
  847. checkNumber += color.brightness();
  848. }
  849. // print(x * pxW, y * pxH, pxW, pxH);
  850. }
  851. },
  852. renderScene: function(scene, canvas){
  853. checkNumber = 0;
  854. /* Get canvas */
  855. if (canvas) {
  856. this.canvas = canvas.getContext("2d");
  857. } else {
  858. this.canvas = null;
  859. }
  860. var canvasHeight = this.options.canvasHeight;
  861. var canvasWidth = this.options.canvasWidth;
  862. for(var y=0; y < canvasHeight; y++){
  863. for(var x=0; x < canvasWidth; x++){
  864. var yp = y * 1.0 / canvasHeight * 2 - 1;
  865. var xp = x * 1.0 / canvasWidth * 2 - 1;
  866. var ray = scene.camera.getRay(xp, yp);
  867. var color = this.getPixelColor(ray, scene);
  868. this.setPixel(x, y, color);
  869. }
  870. }
  871. if (checkNumber !== 2321) {
  872. throw new Error("Scene rendered incorrectly");
  873. }
  874. },
  875. getPixelColor: function(ray, scene){
  876. var info = this.testIntersection(ray, scene, null);
  877. if(info.isHit){
  878. var color = this.rayTrace(info, ray, scene, 0);
  879. return color;
  880. }
  881. return scene.background.color;
  882. },
  883. testIntersection: function(ray, scene, exclude){
  884. var hits = 0;
  885. var best = new Flog.RayTracer.IntersectionInfo();
  886. best.distance = 2000;
  887. for(var i=0; i<scene.shapes.length; i++){
  888. var shape = scene.shapes[i];
  889. if(shape != exclude){
  890. var info = shape.intersect(ray);
  891. if(info.isHit && info.distance >= 0 && info.distance < best.distance){
  892. best = info;
  893. hits++;
  894. }
  895. }
  896. }
  897. best.hitCount = hits;
  898. return best;
  899. },
  900. getReflectionRay: function(P,N,V){
  901. var c1 = -N.dot(V);
  902. var R1 = Flog.RayTracer.Vector.prototype.add(
  903. Flog.RayTracer.Vector.prototype.multiplyScalar(N, 2*c1),
  904. V
  905. );
  906. return new Flog.RayTracer.Ray(P, R1);
  907. },
  908. rayTrace: function(info, ray, scene, depth){
  909. // Calc ambient
  910. var color = Flog.RayTracer.Color.prototype.multiplyScalar(info.color, scene.background.ambience);
  911. var oldColor = color;
  912. var shininess = Math.pow(10, info.shape.material.gloss + 1);
  913. for(var i=0; i<scene.lights.length; i++){
  914. var light = scene.lights[i];
  915. // Calc diffuse lighting
  916. var v = Flog.RayTracer.Vector.prototype.subtract(
  917. light.position,
  918. info.position
  919. ).normalize();
  920. if(this.options.renderDiffuse){
  921. var L = v.dot(info.normal);
  922. if(L > 0.0){
  923. color = Flog.RayTracer.Color.prototype.add(
  924. color,
  925. Flog.RayTracer.Color.prototype.multiply(
  926. info.color,
  927. Flog.RayTracer.Color.prototype.multiplyScalar(
  928. light.color,
  929. L
  930. )
  931. )
  932. );
  933. }
  934. }
  935. // The greater the depth the more accurate the colours, but
  936. // this is exponentially (!) expensive
  937. if(depth <= this.options.rayDepth){
  938. // calculate reflection ray
  939. if(this.options.renderReflections && info.shape.material.reflection > 0)
  940. {
  941. var reflectionRay = this.getReflectionRay(info.position, info.normal, ray.direction);
  942. var refl = this.testIntersection(reflectionRay, scene, info.shape);
  943. if (refl.isHit && refl.distance > 0){
  944. refl.color = this.rayTrace(refl, reflectionRay, scene, depth + 1);
  945. } else {
  946. refl.color = scene.background.color;
  947. }
  948. color = Flog.RayTracer.Color.prototype.blend(
  949. color,
  950. refl.color,
  951. info.shape.material.reflection
  952. );
  953. }
  954. // Refraction
  955. /* TODO */
  956. }
  957. /* Render shadows and highlights */
  958. var shadowInfo = new Flog.RayTracer.IntersectionInfo();
  959. if(this.options.renderShadows){
  960. var shadowRay = new Flog.RayTracer.Ray(info.position, v);
  961. shadowInfo = this.testIntersection(shadowRay, scene, info.shape);
  962. if(shadowInfo.isHit && shadowInfo.shape != info.shape /*&& shadowInfo.shape.type != 'PLANE'*/){
  963. var vA = Flog.RayTracer.Color.prototype.multiplyScalar(color, 0.5);
  964. var dB = (0.5 * Math.pow(shadowInfo.shape.material.transparency, 0.5));
  965. color = Flog.RayTracer.Color.prototype.addScalar(vA,dB);
  966. }
  967. }
  968. // Phong specular highlights
  969. if(this.options.renderHighlights && !shadowInfo.isHit && info.shape.material.gloss > 0){
  970. var Lv = Flog.RayTracer.Vector.prototype.subtract(
  971. info.shape.position,
  972. light.position
  973. ).normalize();
  974. var E = Flog.RayTracer.Vector.prototype.subtract(
  975. scene.camera.position,
  976. info.shape.position
  977. ).normalize();
  978. var H = Flog.RayTracer.Vector.prototype.subtract(
  979. E,
  980. Lv
  981. ).normalize();
  982. var glossWeight = Math.pow(Math.max(info.normal.dot(H), 0), shininess);
  983. color = Flog.RayTracer.Color.prototype.add(
  984. Flog.RayTracer.Color.prototype.multiplyScalar(light.color, glossWeight),
  985. color
  986. );
  987. }
  988. }
  989. color.limit();
  990. return color;
  991. }
  992. };
  993. function renderScene(){
  994. var scene = new Flog.RayTracer.Scene();
  995. scene.camera = new Flog.RayTracer.Camera(
  996. new Flog.RayTracer.Vector(0, 0, -15),
  997. new Flog.RayTracer.Vector(-0.2, 0, 5),
  998. new Flog.RayTracer.Vector(0, 1, 0)
  999. );
  1000. scene.background = new Flog.RayTracer.Background(
  1001. new Flog.RayTracer.Color(0.5, 0.5, 0.5),
  1002. 0.4
  1003. );
  1004. var sphere = new Flog.RayTracer.Shape.Sphere(
  1005. new Flog.RayTracer.Vector(-1.5, 1.5, 2),
  1006. 1.5,
  1007. new Flog.RayTracer.Material.Solid(
  1008. new Flog.RayTracer.Color(0,0.5,0.5),
  1009. 0.3,
  1010. 0.0,
  1011. 0.0,
  1012. 2.0
  1013. )
  1014. );
  1015. var sphere1 = new Flog.RayTracer.Shape.Sphere(
  1016. new Flog.RayTracer.Vector(1, 0.25, 1),
  1017. 0.5,
  1018. new Flog.RayTracer.Material.Solid(
  1019. new Flog.RayTracer.Color(0.9,0.9,0.9),
  1020. 0.1,
  1021. 0.0,
  1022. 0.0,
  1023. 1.5
  1024. )
  1025. );
  1026. var plane = new Flog.RayTracer.Shape.Plane(
  1027. new Flog.RayTracer.Vector(0.1, 0.9, -0.5).normalize(),
  1028. 1.2,
  1029. new Flog.RayTracer.Material.Chessboard(
  1030. new Flog.RayTracer.Color(1,1,1),
  1031. new Flog.RayTracer.Color(0,0,0),
  1032. 0.2,
  1033. 0.0,
  1034. 1.0,
  1035. 0.7
  1036. )
  1037. );
  1038. scene.shapes.push(plane);
  1039. scene.shapes.push(sphere);
  1040. scene.shapes.push(sphere1);
  1041. var light = new Flog.RayTracer.Light(
  1042. new Flog.RayTracer.Vector(5, 10, -1),
  1043. new Flog.RayTracer.Color(0.8, 0.8, 0.8)
  1044. );
  1045. var light1 = new Flog.RayTracer.Light(
  1046. new Flog.RayTracer.Vector(-3, 5, -15),
  1047. new Flog.RayTracer.Color(0.8, 0.8, 0.8),
  1048. 100
  1049. );
  1050. scene.lights.push(light);
  1051. scene.lights.push(light1);
  1052. var imageWidth = 100; // $F('imageWidth');
  1053. var imageHeight = 100; // $F('imageHeight');
  1054. var pixelSize = "5,5".split(','); // $F('pixelSize').split(',');
  1055. var renderDiffuse = true; // $F('renderDiffuse');
  1056. var renderShadows = true; // $F('renderShadows');
  1057. var renderHighlights = true; // $F('renderHighlights');
  1058. var renderReflections = true; // $F('renderReflections');
  1059. var rayDepth = 2;//$F('rayDepth');
  1060. var raytracer = new Flog.RayTracer.Engine(
  1061. {
  1062. canvasWidth: imageWidth,
  1063. canvasHeight: imageHeight,
  1064. pixelWidth: pixelSize[0],
  1065. pixelHeight: pixelSize[1],
  1066. "renderDiffuse": renderDiffuse,
  1067. "renderHighlights": renderHighlights,
  1068. "renderShadows": renderShadows,
  1069. "renderReflections": renderReflections,
  1070. "rayDepth": rayDepth
  1071. }
  1072. );
  1073. raytracer.renderScene(scene, null, 0);
  1074. }
  1075. ////////////////////////////////////////////////////////////////////////////////
  1076. // Runner
  1077. ////////////////////////////////////////////////////////////////////////////////
  1078. var success = true;
  1079. function NotifyStart(name) {
  1080. }
  1081. function NotifyError(name, error) {
  1082. WScript.Echo(name + " : ERROR : " + error.stack);
  1083. success = false;
  1084. }
  1085. function NotifyResult(name, score) {
  1086. if (success) {
  1087. WScript.Echo("### SCORE:", score);
  1088. }
  1089. }
  1090. function NotifyScore(score) {
  1091. }
  1092. BenchmarkSuite.RunSuites({
  1093. NotifyStart: NotifyStart,
  1094. NotifyError: NotifyError,
  1095. NotifyResult: NotifyResult,
  1096. NotifyScore: NotifyScore
  1097. });