navier-stokes.js 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834
  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. /**
  339. * Copyright 2013 the V8 project authors. All rights reserved.
  340. * Copyright 2009 Oliver Hunt <http://nerget.com>
  341. *
  342. * Permission is hereby granted, free of charge, to any person
  343. * obtaining a copy of this software and associated documentation
  344. * files (the "Software"), to deal in the Software without
  345. * restriction, including without limitation the rights to use,
  346. * copy, modify, merge, publish, distribute, sublicense, and/or sell
  347. * copies of the Software, and to permit persons to whom the
  348. * Software is furnished to do so, subject to the following
  349. * conditions:
  350. *
  351. * The above copyright notice and this permission notice shall be
  352. * included in all copies or substantial portions of the Software.
  353. *
  354. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  355. * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
  356. * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  357. * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
  358. * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
  359. * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  360. * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
  361. * OTHER DEALINGS IN THE SOFTWARE.
  362. *
  363. * Update 10/21/2013: fixed loop variables at line 119
  364. */
  365. var NavierStokes = new BenchmarkSuite('NavierStokes', [1484000, 2000],
  366. [new Benchmark('NavierStokes',
  367. true,
  368. true,
  369. 180,
  370. runNavierStokes,
  371. setupNavierStokes,
  372. tearDownNavierStokes,
  373. null,
  374. 16)]);
  375. var solver = null;
  376. var nsFrameCounter = 0;
  377. function runNavierStokes()
  378. {
  379. solver.update();
  380. nsFrameCounter++;
  381. if(nsFrameCounter==15)
  382. checkResult(solver.getDens());
  383. }
  384. function checkResult(dens) {
  385. this.result = 0;
  386. for (var i=7000;i<7100;i++) {
  387. this.result+=~~((dens[i]*10));
  388. }
  389. if (this.result!=77) {
  390. throw(new Error("checksum failed"));
  391. }
  392. }
  393. function setupNavierStokes()
  394. {
  395. solver = new FluidField(null);
  396. solver.setResolution(128, 128);
  397. solver.setIterations(20);
  398. solver.setDisplayFunction(function(){});
  399. solver.setUICallback(prepareFrame);
  400. solver.reset();
  401. }
  402. function tearDownNavierStokes()
  403. {
  404. solver = null;
  405. }
  406. function addPoints(field) {
  407. var n = 64;
  408. for (var i = 1; i <= n; i++) {
  409. field.setVelocity(i, i, n, n);
  410. field.setDensity(i, i, 5);
  411. field.setVelocity(i, n - i, -n, -n);
  412. field.setDensity(i, n - i, 20);
  413. field.setVelocity(128 - i, n + i, -n, -n);
  414. field.setDensity(128 - i, n + i, 30);
  415. }
  416. }
  417. var framesTillAddingPoints = 0;
  418. var framesBetweenAddingPoints = 5;
  419. function prepareFrame(field)
  420. {
  421. if (framesTillAddingPoints == 0) {
  422. addPoints(field);
  423. framesTillAddingPoints = framesBetweenAddingPoints;
  424. framesBetweenAddingPoints++;
  425. } else {
  426. framesTillAddingPoints--;
  427. }
  428. }
  429. // Code from Oliver Hunt (http://nerget.com/fluidSim/pressure.js) starts here.
  430. function FluidField(canvas) {
  431. function addFields(x, s, dt)
  432. {
  433. for (var i=0; i<size ; i++ ) x[i] += dt*s[i];
  434. }
  435. function set_bnd(b, x)
  436. {
  437. if (b===1) {
  438. for (var i = 1; i <= width; i++) {
  439. x[i] = x[i + rowSize];
  440. x[i + (height+1) *rowSize] = x[i + height * rowSize];
  441. }
  442. for (var j = 1; j <= height; j++) {
  443. x[j * rowSize] = -x[1 + j * rowSize];
  444. x[(width + 1) + j * rowSize] = -x[width + j * rowSize];
  445. }
  446. } else if (b === 2) {
  447. for (var i = 1; i <= width; i++) {
  448. x[i] = -x[i + rowSize];
  449. x[i + (height + 1) * rowSize] = -x[i + height * rowSize];
  450. }
  451. for (var j = 1; j <= height; j++) { // site 1
  452. x[j * rowSize] = x[1 + j * rowSize];
  453. x[(width + 1) + j * rowSize] = x[width + j * rowSize];
  454. }
  455. } else {
  456. for (var i = 1; i <= width; i++) {
  457. x[i] = x[i + rowSize];
  458. x[i + (height + 1) * rowSize] = x[i + height * rowSize];
  459. }
  460. for (var j = 1; j <= height; j++) { // site 2
  461. x[j * rowSize] = x[1 + j * rowSize];
  462. x[(width + 1) + j * rowSize] = x[width + j * rowSize];
  463. }
  464. }
  465. var maxEdge = (height + 1) * rowSize;
  466. x[0] = 0.5 * (x[1] + x[rowSize]);
  467. x[maxEdge] = 0.5 * (x[1 + maxEdge] + x[height * rowSize]);
  468. x[(width+1)] = 0.5 * (x[width] + x[(width + 1) + rowSize]);
  469. x[(width+1)+maxEdge] = 0.5 * (x[width + maxEdge] + x[(width + 1) + height * rowSize]);
  470. }
  471. function lin_solve(b, x, x0, a, c)
  472. {
  473. if (a === 0 && c === 1) {
  474. for (var j=1 ; j<=height; j++) {
  475. var currentRow = j * rowSize;
  476. ++currentRow;
  477. for (var i = 0; i < width; i++) {
  478. x[currentRow] = x0[currentRow];
  479. ++currentRow;
  480. }
  481. }
  482. set_bnd(b, x);
  483. } else {
  484. var invC = 1 / c;
  485. for (var k=0 ; k<iterations; k++) {
  486. for (var j=1 ; j<=height; j++) {
  487. var lastRow = (j - 1) * rowSize;
  488. var currentRow = j * rowSize;
  489. var nextRow = (j + 1) * rowSize;
  490. var lastX = x[currentRow];
  491. ++currentRow;
  492. for (var i=1; i<=width; i++)
  493. lastX = x[currentRow] = (x0[currentRow] + a*(lastX+x[++currentRow]+x[++lastRow]+x[++nextRow])) * invC;
  494. }
  495. set_bnd(b, x);
  496. }
  497. }
  498. }
  499. function diffuse(b, x, x0, dt)
  500. {
  501. var a = 0;
  502. lin_solve(b, x, x0, a, 1 + 4*a);
  503. }
  504. function lin_solve2(x, x0, y, y0, a, c)
  505. {
  506. if (a === 0 && c === 1) {
  507. for (var j=1 ; j <= height; j++) {
  508. var currentRow = j * rowSize;
  509. ++currentRow;
  510. for (var i = 0; i < width; i++) {
  511. x[currentRow] = x0[currentRow];
  512. y[currentRow] = y0[currentRow];
  513. ++currentRow;
  514. }
  515. }
  516. set_bnd(1, x);
  517. set_bnd(2, y);
  518. } else {
  519. var invC = 1/c;
  520. for (var k=0 ; k<iterations; k++) {
  521. for (var j=1 ; j <= height; j++) {
  522. var lastRow = (j - 1) * rowSize;
  523. var currentRow = j * rowSize;
  524. var nextRow = (j + 1) * rowSize;
  525. var lastX = x[currentRow];
  526. var lastY = y[currentRow];
  527. ++currentRow;
  528. for (var i = 1; i <= width; i++) {
  529. lastX = x[currentRow] = (x0[currentRow] + a * (lastX + x[currentRow] + x[lastRow] + x[nextRow])) * invC;
  530. lastY = y[currentRow] = (y0[currentRow] + a * (lastY + y[++currentRow] + y[++lastRow] + y[++nextRow])) * invC;
  531. }
  532. }
  533. set_bnd(1, x);
  534. set_bnd(2, y);
  535. }
  536. }
  537. }
  538. function diffuse2(x, x0, y, y0, dt)
  539. {
  540. var a = 0;
  541. lin_solve2(x, x0, y, y0, a, 1 + 4 * a);
  542. }
  543. function advect(b, d, d0, u, v, dt)
  544. {
  545. var Wdt0 = dt * width;
  546. var Hdt0 = dt * height;
  547. var Wp5 = width + 0.5;
  548. var Hp5 = height + 0.5;
  549. for (var j = 1; j<= height; j++) {
  550. var pos = j * rowSize;
  551. for (var i = 1; i <= width; i++) {
  552. var x = i - Wdt0 * u[++pos];
  553. var y = j - Hdt0 * v[pos];
  554. if (x < 0.5)
  555. x = 0.5;
  556. else if (x > Wp5)
  557. x = Wp5;
  558. var i0 = x | 0;
  559. var i1 = i0 + 1;
  560. if (y < 0.5)
  561. y = 0.5;
  562. else if (y > Hp5)
  563. y = Hp5;
  564. var j0 = y | 0;
  565. var j1 = j0 + 1;
  566. var s1 = x - i0;
  567. var s0 = 1 - s1;
  568. var t1 = y - j0;
  569. var t0 = 1 - t1;
  570. var row1 = j0 * rowSize;
  571. var row2 = j1 * rowSize;
  572. d[pos] = s0 * (t0 * d0[i0 + row1] + t1 * d0[i0 + row2]) + s1 * (t0 * d0[i1 + row1] + t1 * d0[i1 + row2]);
  573. }
  574. }
  575. set_bnd(b, d);
  576. }
  577. function project(u, v, p, div)
  578. {
  579. var h = -0.5 / Math.sqrt(width * height);
  580. for (var j = 1 ; j <= height; j++ ) {
  581. var row = j * rowSize;
  582. var previousRow = (j - 1) * rowSize;
  583. var prevValue = row - 1;
  584. var currentRow = row;
  585. var nextValue = row + 1;
  586. var nextRow = (j + 1) * rowSize;
  587. for (var i = 1; i <= width; i++ ) {
  588. div[++currentRow] = h * (u[++nextValue] - u[++prevValue] + v[++nextRow] - v[++previousRow]);
  589. p[currentRow] = 0;
  590. }
  591. }
  592. set_bnd(0, div);
  593. set_bnd(0, p);
  594. lin_solve(0, p, div, 1, 4 );
  595. var wScale = 0.5 * width;
  596. var hScale = 0.5 * height;
  597. for (var j = 1; j<= height; j++ ) {
  598. var prevPos = j * rowSize - 1;
  599. var currentPos = j * rowSize;
  600. var nextPos = j * rowSize + 1;
  601. var prevRow = (j - 1) * rowSize;
  602. var currentRow = j * rowSize;
  603. var nextRow = (j + 1) * rowSize;
  604. for (var i = 1; i<= width; i++) {
  605. u[++currentPos] -= wScale * (p[++nextPos] - p[++prevPos]);
  606. v[currentPos] -= hScale * (p[++nextRow] - p[++prevRow]);
  607. }
  608. }
  609. set_bnd(1, u);
  610. set_bnd(2, v);
  611. }
  612. function dens_step(x, x0, u, v, dt)
  613. {
  614. addFields(x, x0, dt);
  615. diffuse(0, x0, x, dt );
  616. advect(0, x, x0, u, v, dt );
  617. }
  618. function vel_step(u, v, u0, v0, dt)
  619. {
  620. addFields(u, u0, dt );
  621. addFields(v, v0, dt );
  622. var temp = u0; u0 = u; u = temp;
  623. var temp = v0; v0 = v; v = temp;
  624. diffuse2(u,u0,v,v0, dt);
  625. project(u, v, u0, v0);
  626. var temp = u0; u0 = u; u = temp;
  627. var temp = v0; v0 = v; v = temp;
  628. advect(1, u, u0, u0, v0, dt);
  629. advect(2, v, v0, u0, v0, dt);
  630. project(u, v, u0, v0 );
  631. }
  632. var uiCallback = function(d,u,v) {};
  633. function Field(dens, u, v) {
  634. // Just exposing the fields here rather than using accessors is a measurable win during display (maybe 5%)
  635. // but makes the code ugly.
  636. this.setDensity = function(x, y, d) {
  637. dens[(x + 1) + (y + 1) * rowSize] = d;
  638. }
  639. this.getDensity = function(x, y) {
  640. return dens[(x + 1) + (y + 1) * rowSize];
  641. }
  642. this.setVelocity = function(x, y, xv, yv) {
  643. u[(x + 1) + (y + 1) * rowSize] = xv;
  644. v[(x + 1) + (y + 1) * rowSize] = yv;
  645. }
  646. this.getXVelocity = function(x, y) {
  647. return u[(x + 1) + (y + 1) * rowSize];
  648. }
  649. this.getYVelocity = function(x, y) {
  650. return v[(x + 1) + (y + 1) * rowSize];
  651. }
  652. this.width = function() { return width; }
  653. this.height = function() { return height; }
  654. }
  655. function queryUI(d, u, v)
  656. {
  657. for (var i = 0; i < size; i++)
  658. u[i] = v[i] = d[i] = 0.0;
  659. uiCallback(new Field(d, u, v));
  660. }
  661. this.update = function () {
  662. queryUI(dens_prev, u_prev, v_prev);
  663. vel_step(u, v, u_prev, v_prev, dt);
  664. dens_step(dens, dens_prev, u, v, dt);
  665. displayFunc(new Field(dens, u, v));
  666. }
  667. this.setDisplayFunction = function(func) {
  668. displayFunc = func;
  669. }
  670. this.iterations = function() { return iterations; }
  671. this.setIterations = function(iters) {
  672. if (iters > 0 && iters <= 100)
  673. iterations = iters;
  674. }
  675. this.setUICallback = function(callback) {
  676. uiCallback = callback;
  677. }
  678. var iterations = 10;
  679. var visc = 0.5;
  680. var dt = 0.1;
  681. var dens;
  682. var dens_prev;
  683. var u;
  684. var u_prev;
  685. var v;
  686. var v_prev;
  687. var width;
  688. var height;
  689. var rowSize;
  690. var size;
  691. var displayFunc;
  692. function reset()
  693. {
  694. rowSize = width + 2;
  695. size = (width+2)*(height+2);
  696. dens = new Array(size);
  697. dens_prev = new Array(size);
  698. u = new Array(size);
  699. u_prev = new Array(size);
  700. v = new Array(size);
  701. v_prev = new Array(size);
  702. for (var i = 0; i < size; i++)
  703. dens_prev[i] = u_prev[i] = v_prev[i] = dens[i] = u[i] = v[i] = 0;
  704. }
  705. this.reset = reset;
  706. this.getDens = function()
  707. {
  708. return dens;
  709. }
  710. this.setResolution = function (hRes, wRes)
  711. {
  712. var res = wRes * hRes;
  713. if (res > 0 && res < 1000000 && (wRes != width || hRes != height)) {
  714. width = wRes;
  715. height = hRes;
  716. reset();
  717. return true;
  718. }
  719. return false;
  720. }
  721. this.setResolution(64, 64);
  722. }
  723. ////////////////////////////////////////////////////////////////////////////////
  724. // Runner
  725. ////////////////////////////////////////////////////////////////////////////////
  726. var success = true;
  727. function NotifyStart(name) {
  728. }
  729. function NotifyError(name, error) {
  730. WScript.Echo(name + " : ERROR : " + error.stack);
  731. success = false;
  732. }
  733. function NotifyResult(name, score) {
  734. if (success) {
  735. WScript.Echo("### SCORE:", score);
  736. }
  737. }
  738. function NotifyScore(score) {
  739. }
  740. BenchmarkSuite.RunSuites({
  741. NotifyStart: NotifyStart,
  742. NotifyError: NotifyError,
  743. NotifyResult: NotifyResult,
  744. NotifyScore: NotifyScore
  745. });